btrfs: use btrfs_item_size_nr/btrfs_item_offset_nr everywhere
[linux-block.git] / fs / btrfs / ctree.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
6cbd5570 2/*
d352ac68 3 * Copyright (C) 2007,2008 Oracle. All rights reserved.
6cbd5570
CM
4 */
5
a6b6e75e 6#include <linux/sched.h>
5a0e3ad6 7#include <linux/slab.h>
bd989ba3 8#include <linux/rbtree.h>
adf02123 9#include <linux/mm.h>
e41d12f5 10#include <linux/error-injection.h>
eb60ceac
CM
11#include "ctree.h"
12#include "disk-io.h"
7f5c1516 13#include "transaction.h"
5f39d397 14#include "print-tree.h"
925baedd 15#include "locking.h"
de37aa51 16#include "volumes.h"
f616f5cd 17#include "qgroup.h"
f3a84ccd 18#include "tree-mod-log.h"
9a8dd150 19
e089f05c
CM
20static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
21 *root, struct btrfs_path *path, int level);
310712b2
OS
22static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
23 const struct btrfs_key *ins_key, struct btrfs_path *path,
24 int data_size, int extend);
5f39d397 25static int push_node_left(struct btrfs_trans_handle *trans,
2ff7e61e 26 struct extent_buffer *dst,
971a1f66 27 struct extent_buffer *src, int empty);
5f39d397 28static int balance_node_right(struct btrfs_trans_handle *trans,
5f39d397
CM
29 struct extent_buffer *dst_buf,
30 struct extent_buffer *src_buf);
afe5fea7
TI
31static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
32 int level, int slot);
d97e63b6 33
af024ed2
JT
34static const struct btrfs_csums {
35 u16 size;
59a0fcdb
DS
36 const char name[10];
37 const char driver[12];
af024ed2
JT
38} btrfs_csums[] = {
39 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
3951e7f0 40 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
3831bf00 41 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
352ae07b
DS
42 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
43 .driver = "blake2b-256" },
af024ed2
JT
44};
45
46int btrfs_super_csum_size(const struct btrfs_super_block *s)
47{
48 u16 t = btrfs_super_csum_type(s);
49 /*
50 * csum type is validated at mount time
51 */
52 return btrfs_csums[t].size;
53}
54
55const char *btrfs_super_csum_name(u16 csum_type)
56{
57 /* csum type is validated at mount time */
58 return btrfs_csums[csum_type].name;
59}
60
b4e967be
DS
61/*
62 * Return driver name if defined, otherwise the name that's also a valid driver
63 * name
64 */
65const char *btrfs_super_csum_driver(u16 csum_type)
66{
67 /* csum type is validated at mount time */
59a0fcdb
DS
68 return btrfs_csums[csum_type].driver[0] ?
69 btrfs_csums[csum_type].driver :
b4e967be
DS
70 btrfs_csums[csum_type].name;
71}
72
604997b4 73size_t __attribute_const__ btrfs_get_num_csums(void)
f7cea56c
DS
74{
75 return ARRAY_SIZE(btrfs_csums);
76}
77
df24a2b9 78struct btrfs_path *btrfs_alloc_path(void)
2c90e5d6 79{
e2c89907 80 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
2c90e5d6
CM
81}
82
d352ac68 83/* this also releases the path */
df24a2b9 84void btrfs_free_path(struct btrfs_path *p)
be0e5c09 85{
ff175d57
JJ
86 if (!p)
87 return;
b3b4aa74 88 btrfs_release_path(p);
df24a2b9 89 kmem_cache_free(btrfs_path_cachep, p);
be0e5c09
CM
90}
91
d352ac68
CM
92/*
93 * path release drops references on the extent buffers in the path
94 * and it drops any locks held by this path
95 *
96 * It is safe to call this on paths that no locks or extent buffers held.
97 */
b3b4aa74 98noinline void btrfs_release_path(struct btrfs_path *p)
eb60ceac
CM
99{
100 int i;
a2135011 101
234b63a0 102 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
3f157a2f 103 p->slots[i] = 0;
eb60ceac 104 if (!p->nodes[i])
925baedd
CM
105 continue;
106 if (p->locks[i]) {
bd681513 107 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
925baedd
CM
108 p->locks[i] = 0;
109 }
5f39d397 110 free_extent_buffer(p->nodes[i]);
3f157a2f 111 p->nodes[i] = NULL;
eb60ceac
CM
112 }
113}
114
d352ac68
CM
115/*
116 * safely gets a reference on the root node of a tree. A lock
117 * is not taken, so a concurrent writer may put a different node
118 * at the root of the tree. See btrfs_lock_root_node for the
119 * looping required.
120 *
121 * The extent buffer returned by this has a reference taken, so
122 * it won't disappear. It may stop being the root of the tree
123 * at any time because there are no locks held.
124 */
925baedd
CM
125struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
126{
127 struct extent_buffer *eb;
240f62c8 128
3083ee2e
JB
129 while (1) {
130 rcu_read_lock();
131 eb = rcu_dereference(root->node);
132
133 /*
134 * RCU really hurts here, we could free up the root node because
01327610 135 * it was COWed but we may not get the new root node yet so do
3083ee2e
JB
136 * the inc_not_zero dance and if it doesn't work then
137 * synchronize_rcu and try again.
138 */
139 if (atomic_inc_not_zero(&eb->refs)) {
140 rcu_read_unlock();
141 break;
142 }
143 rcu_read_unlock();
144 synchronize_rcu();
145 }
925baedd
CM
146 return eb;
147}
148
92a7cc42
QW
149/*
150 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
151 * just get put onto a simple dirty list. Transaction walks this list to make
152 * sure they get properly updated on disk.
d352ac68 153 */
0b86a832
CM
154static void add_root_to_dirty_list(struct btrfs_root *root)
155{
0b246afa
JM
156 struct btrfs_fs_info *fs_info = root->fs_info;
157
e7070be1
JB
158 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
159 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
160 return;
161
0b246afa 162 spin_lock(&fs_info->trans_lock);
e7070be1
JB
163 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
164 /* Want the extent tree to be the last on the list */
4fd786e6 165 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
e7070be1 166 list_move_tail(&root->dirty_list,
0b246afa 167 &fs_info->dirty_cowonly_roots);
e7070be1
JB
168 else
169 list_move(&root->dirty_list,
0b246afa 170 &fs_info->dirty_cowonly_roots);
0b86a832 171 }
0b246afa 172 spin_unlock(&fs_info->trans_lock);
0b86a832
CM
173}
174
d352ac68
CM
175/*
176 * used by snapshot creation to make a copy of a root for a tree with
177 * a given objectid. The buffer with the new root node is returned in
178 * cow_ret, and this func returns zero on success or a negative error code.
179 */
be20aa9d
CM
180int btrfs_copy_root(struct btrfs_trans_handle *trans,
181 struct btrfs_root *root,
182 struct extent_buffer *buf,
183 struct extent_buffer **cow_ret, u64 new_root_objectid)
184{
0b246afa 185 struct btrfs_fs_info *fs_info = root->fs_info;
be20aa9d 186 struct extent_buffer *cow;
be20aa9d
CM
187 int ret = 0;
188 int level;
5d4f98a2 189 struct btrfs_disk_key disk_key;
be20aa9d 190
92a7cc42 191 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
0b246afa 192 trans->transid != fs_info->running_transaction->transid);
92a7cc42 193 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
27cdeb70 194 trans->transid != root->last_trans);
be20aa9d
CM
195
196 level = btrfs_header_level(buf);
5d4f98a2
YZ
197 if (level == 0)
198 btrfs_item_key(buf, &disk_key, 0);
199 else
200 btrfs_node_key(buf, &disk_key, 0);
31840ae1 201
4d75f8a9 202 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
cf6f34aa
JB
203 &disk_key, level, buf->start, 0,
204 BTRFS_NESTING_NEW_ROOT);
5d4f98a2 205 if (IS_ERR(cow))
be20aa9d
CM
206 return PTR_ERR(cow);
207
58e8012c 208 copy_extent_buffer_full(cow, buf);
be20aa9d
CM
209 btrfs_set_header_bytenr(cow, cow->start);
210 btrfs_set_header_generation(cow, trans->transid);
5d4f98a2
YZ
211 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
212 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
213 BTRFS_HEADER_FLAG_RELOC);
214 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
215 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
216 else
217 btrfs_set_header_owner(cow, new_root_objectid);
be20aa9d 218
de37aa51 219 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2b82032c 220
be20aa9d 221 WARN_ON(btrfs_header_generation(buf) > trans->transid);
5d4f98a2 222 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
e339a6b0 223 ret = btrfs_inc_ref(trans, root, cow, 1);
5d4f98a2 224 else
e339a6b0 225 ret = btrfs_inc_ref(trans, root, cow, 0);
867ed321 226 if (ret) {
72c9925f
FM
227 btrfs_tree_unlock(cow);
228 free_extent_buffer(cow);
867ed321 229 btrfs_abort_transaction(trans, ret);
be20aa9d 230 return ret;
867ed321 231 }
be20aa9d
CM
232
233 btrfs_mark_buffer_dirty(cow);
234 *cow_ret = cow;
235 return 0;
236}
237
5d4f98a2
YZ
238/*
239 * check if the tree block can be shared by multiple trees
240 */
241int btrfs_block_can_be_shared(struct btrfs_root *root,
242 struct extent_buffer *buf)
243{
244 /*
92a7cc42
QW
245 * Tree blocks not in shareable trees and tree roots are never shared.
246 * If a block was allocated after the last snapshot and the block was
247 * not allocated by tree relocation, we know the block is not shared.
5d4f98a2 248 */
92a7cc42 249 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5d4f98a2
YZ
250 buf != root->node && buf != root->commit_root &&
251 (btrfs_header_generation(buf) <=
252 btrfs_root_last_snapshot(&root->root_item) ||
253 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
254 return 1;
a79865c6 255
5d4f98a2
YZ
256 return 0;
257}
258
259static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
260 struct btrfs_root *root,
261 struct extent_buffer *buf,
f0486c68
YZ
262 struct extent_buffer *cow,
263 int *last_ref)
5d4f98a2 264{
0b246afa 265 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
266 u64 refs;
267 u64 owner;
268 u64 flags;
269 u64 new_flags = 0;
270 int ret;
271
272 /*
273 * Backrefs update rules:
274 *
275 * Always use full backrefs for extent pointers in tree block
276 * allocated by tree relocation.
277 *
278 * If a shared tree block is no longer referenced by its owner
279 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
280 * use full backrefs for extent pointers in tree block.
281 *
282 * If a tree block is been relocating
283 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
284 * use full backrefs for extent pointers in tree block.
285 * The reason for this is some operations (such as drop tree)
286 * are only allowed for blocks use full backrefs.
287 */
288
289 if (btrfs_block_can_be_shared(root, buf)) {
2ff7e61e 290 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3173a18f
JB
291 btrfs_header_level(buf), 1,
292 &refs, &flags);
be1a5564
MF
293 if (ret)
294 return ret;
e5df9573
MF
295 if (refs == 0) {
296 ret = -EROFS;
0b246afa 297 btrfs_handle_fs_error(fs_info, ret, NULL);
e5df9573
MF
298 return ret;
299 }
5d4f98a2
YZ
300 } else {
301 refs = 1;
302 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
303 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
304 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
305 else
306 flags = 0;
307 }
308
309 owner = btrfs_header_owner(buf);
310 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
311 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
312
313 if (refs > 1) {
314 if ((owner == root->root_key.objectid ||
315 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
316 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
e339a6b0 317 ret = btrfs_inc_ref(trans, root, buf, 1);
692826b2
JM
318 if (ret)
319 return ret;
5d4f98a2
YZ
320
321 if (root->root_key.objectid ==
322 BTRFS_TREE_RELOC_OBJECTID) {
e339a6b0 323 ret = btrfs_dec_ref(trans, root, buf, 0);
692826b2
JM
324 if (ret)
325 return ret;
e339a6b0 326 ret = btrfs_inc_ref(trans, root, cow, 1);
692826b2
JM
327 if (ret)
328 return ret;
5d4f98a2
YZ
329 }
330 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
331 } else {
332
333 if (root->root_key.objectid ==
334 BTRFS_TREE_RELOC_OBJECTID)
e339a6b0 335 ret = btrfs_inc_ref(trans, root, cow, 1);
5d4f98a2 336 else
e339a6b0 337 ret = btrfs_inc_ref(trans, root, cow, 0);
692826b2
JM
338 if (ret)
339 return ret;
5d4f98a2
YZ
340 }
341 if (new_flags != 0) {
b1c79e09
JB
342 int level = btrfs_header_level(buf);
343
42c9d0b5 344 ret = btrfs_set_disk_extent_flags(trans, buf,
b1c79e09 345 new_flags, level, 0);
be1a5564
MF
346 if (ret)
347 return ret;
5d4f98a2
YZ
348 }
349 } else {
350 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
351 if (root->root_key.objectid ==
352 BTRFS_TREE_RELOC_OBJECTID)
e339a6b0 353 ret = btrfs_inc_ref(trans, root, cow, 1);
5d4f98a2 354 else
e339a6b0 355 ret = btrfs_inc_ref(trans, root, cow, 0);
692826b2
JM
356 if (ret)
357 return ret;
e339a6b0 358 ret = btrfs_dec_ref(trans, root, buf, 1);
692826b2
JM
359 if (ret)
360 return ret;
5d4f98a2 361 }
6a884d7d 362 btrfs_clean_tree_block(buf);
f0486c68 363 *last_ref = 1;
5d4f98a2
YZ
364 }
365 return 0;
366}
367
d352ac68 368/*
d397712b
CM
369 * does the dirty work in cow of a single block. The parent block (if
370 * supplied) is updated to point to the new cow copy. The new buffer is marked
371 * dirty and returned locked. If you modify the block it needs to be marked
372 * dirty again.
d352ac68
CM
373 *
374 * search_start -- an allocation hint for the new block
375 *
d397712b
CM
376 * empty_size -- a hint that you plan on doing more cow. This is the size in
377 * bytes the allocator should try to find free next to the block it returns.
378 * This is just a hint and may be ignored by the allocator.
d352ac68 379 */
d397712b 380static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5f39d397
CM
381 struct btrfs_root *root,
382 struct extent_buffer *buf,
383 struct extent_buffer *parent, int parent_slot,
384 struct extent_buffer **cow_ret,
9631e4cc
JB
385 u64 search_start, u64 empty_size,
386 enum btrfs_lock_nesting nest)
02217ed2 387{
0b246afa 388 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2 389 struct btrfs_disk_key disk_key;
5f39d397 390 struct extent_buffer *cow;
be1a5564 391 int level, ret;
f0486c68 392 int last_ref = 0;
925baedd 393 int unlock_orig = 0;
0f5053eb 394 u64 parent_start = 0;
7bb86316 395
925baedd
CM
396 if (*cow_ret == buf)
397 unlock_orig = 1;
398
49d0c642 399 btrfs_assert_tree_write_locked(buf);
925baedd 400
92a7cc42 401 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
0b246afa 402 trans->transid != fs_info->running_transaction->transid);
92a7cc42 403 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
27cdeb70 404 trans->transid != root->last_trans);
5f39d397 405
7bb86316 406 level = btrfs_header_level(buf);
31840ae1 407
5d4f98a2
YZ
408 if (level == 0)
409 btrfs_item_key(buf, &disk_key, 0);
410 else
411 btrfs_node_key(buf, &disk_key, 0);
412
0f5053eb
GR
413 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
414 parent_start = parent->start;
5d4f98a2 415
79bd3712
FM
416 cow = btrfs_alloc_tree_block(trans, root, parent_start,
417 root->root_key.objectid, &disk_key, level,
418 search_start, empty_size, nest);
54aa1f4d
CM
419 if (IS_ERR(cow))
420 return PTR_ERR(cow);
6702ed49 421
b4ce94de
CM
422 /* cow is set to blocking by btrfs_init_new_buffer */
423
58e8012c 424 copy_extent_buffer_full(cow, buf);
db94535d 425 btrfs_set_header_bytenr(cow, cow->start);
5f39d397 426 btrfs_set_header_generation(cow, trans->transid);
5d4f98a2
YZ
427 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
428 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
429 BTRFS_HEADER_FLAG_RELOC);
430 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
431 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
432 else
433 btrfs_set_header_owner(cow, root->root_key.objectid);
6702ed49 434
de37aa51 435 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2b82032c 436
be1a5564 437 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
b68dc2a9 438 if (ret) {
572c83ac
JB
439 btrfs_tree_unlock(cow);
440 free_extent_buffer(cow);
66642832 441 btrfs_abort_transaction(trans, ret);
b68dc2a9
MF
442 return ret;
443 }
1a40e23b 444
92a7cc42 445 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
83d4cfd4 446 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
93314e3b 447 if (ret) {
572c83ac
JB
448 btrfs_tree_unlock(cow);
449 free_extent_buffer(cow);
66642832 450 btrfs_abort_transaction(trans, ret);
83d4cfd4 451 return ret;
93314e3b 452 }
83d4cfd4 453 }
3fd0a558 454
02217ed2 455 if (buf == root->node) {
925baedd 456 WARN_ON(parent && parent != buf);
5d4f98a2
YZ
457 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
458 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
459 parent_start = buf->start;
925baedd 460
67439dad 461 atomic_inc(&cow->refs);
406808ab 462 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
d9d19a01 463 BUG_ON(ret < 0);
240f62c8 464 rcu_assign_pointer(root->node, cow);
925baedd 465
7a163608
FM
466 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
467 parent_start, last_ref);
5f39d397 468 free_extent_buffer(buf);
0b86a832 469 add_root_to_dirty_list(root);
02217ed2 470 } else {
5d4f98a2 471 WARN_ON(trans->transid != btrfs_header_generation(parent));
f3a84ccd
FM
472 btrfs_tree_mod_log_insert_key(parent, parent_slot,
473 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
5f39d397 474 btrfs_set_node_blockptr(parent, parent_slot,
db94535d 475 cow->start);
74493f7a
CM
476 btrfs_set_node_ptr_generation(parent, parent_slot,
477 trans->transid);
d6025579 478 btrfs_mark_buffer_dirty(parent);
5de865ee 479 if (last_ref) {
f3a84ccd 480 ret = btrfs_tree_mod_log_free_eb(buf);
5de865ee 481 if (ret) {
572c83ac
JB
482 btrfs_tree_unlock(cow);
483 free_extent_buffer(cow);
66642832 484 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
485 return ret;
486 }
487 }
7a163608
FM
488 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
489 parent_start, last_ref);
02217ed2 490 }
925baedd
CM
491 if (unlock_orig)
492 btrfs_tree_unlock(buf);
3083ee2e 493 free_extent_buffer_stale(buf);
ccd467d6 494 btrfs_mark_buffer_dirty(cow);
2c90e5d6 495 *cow_ret = cow;
02217ed2
CM
496 return 0;
497}
498
5d4f98a2
YZ
499static inline int should_cow_block(struct btrfs_trans_handle *trans,
500 struct btrfs_root *root,
501 struct extent_buffer *buf)
502{
f5ee5c9a 503 if (btrfs_is_testing(root->fs_info))
faa2dbf0 504 return 0;
fccb84c9 505
d1980131
DS
506 /* Ensure we can see the FORCE_COW bit */
507 smp_mb__before_atomic();
f1ebcc74
LB
508
509 /*
510 * We do not need to cow a block if
511 * 1) this block is not created or changed in this transaction;
512 * 2) this block does not belong to TREE_RELOC tree;
513 * 3) the root is not forced COW.
514 *
515 * What is forced COW:
01327610 516 * when we create snapshot during committing the transaction,
52042d8e 517 * after we've finished copying src root, we must COW the shared
f1ebcc74
LB
518 * block to ensure the metadata consistency.
519 */
5d4f98a2
YZ
520 if (btrfs_header_generation(buf) == trans->transid &&
521 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
522 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
f1ebcc74 523 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
27cdeb70 524 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5d4f98a2
YZ
525 return 0;
526 return 1;
527}
528
d352ac68
CM
529/*
530 * cows a single block, see __btrfs_cow_block for the real work.
01327610 531 * This version of it has extra checks so that a block isn't COWed more than
d352ac68
CM
532 * once per transaction, as long as it hasn't been written yet
533 */
d397712b 534noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5f39d397
CM
535 struct btrfs_root *root, struct extent_buffer *buf,
536 struct extent_buffer *parent, int parent_slot,
9631e4cc
JB
537 struct extent_buffer **cow_ret,
538 enum btrfs_lock_nesting nest)
6702ed49 539{
0b246afa 540 struct btrfs_fs_info *fs_info = root->fs_info;
6702ed49 541 u64 search_start;
f510cfec 542 int ret;
dc17ff8f 543
83354f07
JB
544 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
545 btrfs_err(fs_info,
546 "COW'ing blocks on a fs root that's being dropped");
547
0b246afa 548 if (trans->transaction != fs_info->running_transaction)
31b1a2bd 549 WARN(1, KERN_CRIT "trans %llu running %llu\n",
c1c9ff7c 550 trans->transid,
0b246afa 551 fs_info->running_transaction->transid);
31b1a2bd 552
0b246afa 553 if (trans->transid != fs_info->generation)
31b1a2bd 554 WARN(1, KERN_CRIT "trans %llu running %llu\n",
0b246afa 555 trans->transid, fs_info->generation);
dc17ff8f 556
5d4f98a2 557 if (!should_cow_block(trans, root, buf)) {
6702ed49
CM
558 *cow_ret = buf;
559 return 0;
560 }
c487685d 561
ee22184b 562 search_start = buf->start & ~((u64)SZ_1G - 1);
b4ce94de 563
f616f5cd
QW
564 /*
565 * Before CoWing this block for later modification, check if it's
566 * the subtree root and do the delayed subtree trace if needed.
567 *
568 * Also We don't care about the error, as it's handled internally.
569 */
570 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
f510cfec 571 ret = __btrfs_cow_block(trans, root, buf, parent,
9631e4cc 572 parent_slot, cow_ret, search_start, 0, nest);
1abe9b8a 573
574 trace_btrfs_cow_block(root, buf, *cow_ret);
575
f510cfec 576 return ret;
6702ed49 577}
f75e2b79 578ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
6702ed49 579
d352ac68
CM
580/*
581 * helper function for defrag to decide if two blocks pointed to by a
582 * node are actually close by
583 */
6b80053d 584static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6702ed49 585{
6b80053d 586 if (blocknr < other && other - (blocknr + blocksize) < 32768)
6702ed49 587 return 1;
6b80053d 588 if (blocknr > other && blocknr - (other + blocksize) < 32768)
6702ed49
CM
589 return 1;
590 return 0;
591}
592
ce6ef5ab
DS
593#ifdef __LITTLE_ENDIAN
594
595/*
596 * Compare two keys, on little-endian the disk order is same as CPU order and
597 * we can avoid the conversion.
598 */
599static int comp_keys(const struct btrfs_disk_key *disk_key,
600 const struct btrfs_key *k2)
601{
602 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
603
604 return btrfs_comp_cpu_keys(k1, k2);
605}
606
607#else
608
081e9573
CM
609/*
610 * compare two keys in a memcmp fashion
611 */
310712b2
OS
612static int comp_keys(const struct btrfs_disk_key *disk,
613 const struct btrfs_key *k2)
081e9573
CM
614{
615 struct btrfs_key k1;
616
617 btrfs_disk_key_to_cpu(&k1, disk);
618
20736aba 619 return btrfs_comp_cpu_keys(&k1, k2);
081e9573 620}
ce6ef5ab 621#endif
081e9573 622
f3465ca4
JB
623/*
624 * same as comp_keys only with two btrfs_key's
625 */
e1f60a65 626int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
f3465ca4
JB
627{
628 if (k1->objectid > k2->objectid)
629 return 1;
630 if (k1->objectid < k2->objectid)
631 return -1;
632 if (k1->type > k2->type)
633 return 1;
634 if (k1->type < k2->type)
635 return -1;
636 if (k1->offset > k2->offset)
637 return 1;
638 if (k1->offset < k2->offset)
639 return -1;
640 return 0;
641}
081e9573 642
d352ac68
CM
643/*
644 * this is used by the defrag code to go through all the
645 * leaves pointed to by a node and reallocate them so that
646 * disk order is close to key order
647 */
6702ed49 648int btrfs_realloc_node(struct btrfs_trans_handle *trans,
5f39d397 649 struct btrfs_root *root, struct extent_buffer *parent,
de78b51a 650 int start_slot, u64 *last_ret,
a6b6e75e 651 struct btrfs_key *progress)
6702ed49 652{
0b246afa 653 struct btrfs_fs_info *fs_info = root->fs_info;
6b80053d 654 struct extent_buffer *cur;
6702ed49 655 u64 blocknr;
e9d0b13b
CM
656 u64 search_start = *last_ret;
657 u64 last_block = 0;
6702ed49
CM
658 u64 other;
659 u32 parent_nritems;
6702ed49
CM
660 int end_slot;
661 int i;
662 int err = 0;
6b80053d 663 u32 blocksize;
081e9573
CM
664 int progress_passed = 0;
665 struct btrfs_disk_key disk_key;
6702ed49 666
0b246afa
JM
667 WARN_ON(trans->transaction != fs_info->running_transaction);
668 WARN_ON(trans->transid != fs_info->generation);
86479a04 669
6b80053d 670 parent_nritems = btrfs_header_nritems(parent);
0b246afa 671 blocksize = fs_info->nodesize;
5dfe2be7 672 end_slot = parent_nritems - 1;
6702ed49 673
5dfe2be7 674 if (parent_nritems <= 1)
6702ed49
CM
675 return 0;
676
5dfe2be7 677 for (i = start_slot; i <= end_slot; i++) {
6702ed49 678 int close = 1;
a6b6e75e 679
081e9573
CM
680 btrfs_node_key(parent, &disk_key, i);
681 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
682 continue;
683
684 progress_passed = 1;
6b80053d 685 blocknr = btrfs_node_blockptr(parent, i);
e9d0b13b
CM
686 if (last_block == 0)
687 last_block = blocknr;
5708b959 688
6702ed49 689 if (i > 0) {
6b80053d
CM
690 other = btrfs_node_blockptr(parent, i - 1);
691 close = close_blocks(blocknr, other, blocksize);
6702ed49 692 }
5dfe2be7 693 if (!close && i < end_slot) {
6b80053d
CM
694 other = btrfs_node_blockptr(parent, i + 1);
695 close = close_blocks(blocknr, other, blocksize);
6702ed49 696 }
e9d0b13b
CM
697 if (close) {
698 last_block = blocknr;
6702ed49 699 continue;
e9d0b13b 700 }
6702ed49 701
206983b7
JB
702 cur = btrfs_read_node_slot(parent, i);
703 if (IS_ERR(cur))
704 return PTR_ERR(cur);
e9d0b13b 705 if (search_start == 0)
6b80053d 706 search_start = last_block;
e9d0b13b 707
e7a84565 708 btrfs_tree_lock(cur);
6b80053d 709 err = __btrfs_cow_block(trans, root, cur, parent, i,
e7a84565 710 &cur, search_start,
6b80053d 711 min(16 * blocksize,
9631e4cc
JB
712 (end_slot - i) * blocksize),
713 BTRFS_NESTING_COW);
252c38f0 714 if (err) {
e7a84565 715 btrfs_tree_unlock(cur);
6b80053d 716 free_extent_buffer(cur);
6702ed49 717 break;
252c38f0 718 }
e7a84565
CM
719 search_start = cur->start;
720 last_block = cur->start;
f2183bde 721 *last_ret = search_start;
e7a84565
CM
722 btrfs_tree_unlock(cur);
723 free_extent_buffer(cur);
6702ed49
CM
724 }
725 return err;
726}
727
74123bd7 728/*
5f39d397 729 * search for key in the extent_buffer. The items start at offset p,
67d5e289 730 * and they are item_size apart.
5f39d397 731 *
74123bd7
CM
732 * the slot in the array is returned via slot, and it points to
733 * the place where you would insert key if it is not found in
734 * the array.
735 *
67d5e289
MPS
736 * Slot may point to total number of items if the key is bigger than
737 * all of the keys
74123bd7 738 */
e02119d5 739static noinline int generic_bin_search(struct extent_buffer *eb,
310712b2 740 unsigned long p, int item_size,
67d5e289 741 const struct btrfs_key *key, int *slot)
be0e5c09
CM
742{
743 int low = 0;
67d5e289 744 int high = btrfs_header_nritems(eb);
be0e5c09 745 int ret;
5cd17f34 746 const int key_size = sizeof(struct btrfs_disk_key);
be0e5c09 747
5e24e9af
LB
748 if (low > high) {
749 btrfs_err(eb->fs_info,
750 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
751 __func__, low, high, eb->start,
752 btrfs_header_owner(eb), btrfs_header_level(eb));
753 return -EINVAL;
754 }
755
d397712b 756 while (low < high) {
5cd17f34
DS
757 unsigned long oip;
758 unsigned long offset;
759 struct btrfs_disk_key *tmp;
760 struct btrfs_disk_key unaligned;
761 int mid;
762
be0e5c09 763 mid = (low + high) / 2;
5f39d397 764 offset = p + mid * item_size;
5cd17f34 765 oip = offset_in_page(offset);
5f39d397 766
5cd17f34 767 if (oip + key_size <= PAGE_SIZE) {
884b07d0 768 const unsigned long idx = get_eb_page_index(offset);
5cd17f34 769 char *kaddr = page_address(eb->pages[idx]);
5f39d397 770
884b07d0 771 oip = get_eb_offset_in_page(eb, offset);
5cd17f34 772 tmp = (struct btrfs_disk_key *)(kaddr + oip);
5f39d397 773 } else {
5cd17f34
DS
774 read_extent_buffer(eb, &unaligned, offset, key_size);
775 tmp = &unaligned;
5f39d397 776 }
5cd17f34 777
be0e5c09
CM
778 ret = comp_keys(tmp, key);
779
780 if (ret < 0)
781 low = mid + 1;
782 else if (ret > 0)
783 high = mid;
784 else {
785 *slot = mid;
786 return 0;
787 }
788 }
789 *slot = low;
790 return 1;
791}
792
97571fd0
CM
793/*
794 * simple bin_search frontend that does the right thing for
795 * leaves vs nodes
796 */
a74b35ec 797int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
e3b83361 798 int *slot)
be0e5c09 799{
e3b83361 800 if (btrfs_header_level(eb) == 0)
5f39d397
CM
801 return generic_bin_search(eb,
802 offsetof(struct btrfs_leaf, items),
67d5e289 803 sizeof(struct btrfs_item), key, slot);
f775738f 804 else
5f39d397
CM
805 return generic_bin_search(eb,
806 offsetof(struct btrfs_node, ptrs),
67d5e289 807 sizeof(struct btrfs_key_ptr), key, slot);
be0e5c09
CM
808}
809
f0486c68
YZ
810static void root_add_used(struct btrfs_root *root, u32 size)
811{
812 spin_lock(&root->accounting_lock);
813 btrfs_set_root_used(&root->root_item,
814 btrfs_root_used(&root->root_item) + size);
815 spin_unlock(&root->accounting_lock);
816}
817
818static void root_sub_used(struct btrfs_root *root, u32 size)
819{
820 spin_lock(&root->accounting_lock);
821 btrfs_set_root_used(&root->root_item,
822 btrfs_root_used(&root->root_item) - size);
823 spin_unlock(&root->accounting_lock);
824}
825
d352ac68
CM
826/* given a node and slot number, this reads the blocks it points to. The
827 * extent buffer is returned with a reference taken (but unlocked).
d352ac68 828 */
4b231ae4
DS
829struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
830 int slot)
bb803951 831{
ca7a79ad 832 int level = btrfs_header_level(parent);
416bc658 833 struct extent_buffer *eb;
581c1760 834 struct btrfs_key first_key;
416bc658 835
fb770ae4
LB
836 if (slot < 0 || slot >= btrfs_header_nritems(parent))
837 return ERR_PTR(-ENOENT);
ca7a79ad
CM
838
839 BUG_ON(level == 0);
840
581c1760 841 btrfs_node_key_to_cpu(parent, &first_key, slot);
d0d20b0f 842 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1b7ec85e 843 btrfs_header_owner(parent),
581c1760
QW
844 btrfs_node_ptr_generation(parent, slot),
845 level - 1, &first_key);
fb770ae4
LB
846 if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
847 free_extent_buffer(eb);
848 eb = ERR_PTR(-EIO);
416bc658
JB
849 }
850
851 return eb;
bb803951
CM
852}
853
d352ac68
CM
854/*
855 * node level balancing, used to make sure nodes are in proper order for
856 * item deletion. We balance from the top down, so we have to make sure
857 * that a deletion won't leave an node completely empty later on.
858 */
e02119d5 859static noinline int balance_level(struct btrfs_trans_handle *trans,
98ed5174
CM
860 struct btrfs_root *root,
861 struct btrfs_path *path, int level)
bb803951 862{
0b246afa 863 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
864 struct extent_buffer *right = NULL;
865 struct extent_buffer *mid;
866 struct extent_buffer *left = NULL;
867 struct extent_buffer *parent = NULL;
bb803951
CM
868 int ret = 0;
869 int wret;
870 int pslot;
bb803951 871 int orig_slot = path->slots[level];
79f95c82 872 u64 orig_ptr;
bb803951 873
98e6b1eb 874 ASSERT(level > 0);
bb803951 875
5f39d397 876 mid = path->nodes[level];
b4ce94de 877
ac5887c8 878 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
7bb86316
CM
879 WARN_ON(btrfs_header_generation(mid) != trans->transid);
880
1d4f8a0c 881 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
79f95c82 882
a05a9bb1 883 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 884 parent = path->nodes[level + 1];
a05a9bb1
LZ
885 pslot = path->slots[level + 1];
886 }
bb803951 887
40689478
CM
888 /*
889 * deal with the case where there is only one pointer in the root
890 * by promoting the node below to a root
891 */
5f39d397
CM
892 if (!parent) {
893 struct extent_buffer *child;
bb803951 894
5f39d397 895 if (btrfs_header_nritems(mid) != 1)
bb803951
CM
896 return 0;
897
898 /* promote the child to a root */
4b231ae4 899 child = btrfs_read_node_slot(mid, 0);
fb770ae4
LB
900 if (IS_ERR(child)) {
901 ret = PTR_ERR(child);
0b246afa 902 btrfs_handle_fs_error(fs_info, ret, NULL);
305a26af
MF
903 goto enospc;
904 }
905
925baedd 906 btrfs_tree_lock(child);
9631e4cc
JB
907 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
908 BTRFS_NESTING_COW);
f0486c68
YZ
909 if (ret) {
910 btrfs_tree_unlock(child);
911 free_extent_buffer(child);
912 goto enospc;
913 }
2f375ab9 914
406808ab 915 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
d9d19a01 916 BUG_ON(ret < 0);
240f62c8 917 rcu_assign_pointer(root->node, child);
925baedd 918
0b86a832 919 add_root_to_dirty_list(root);
925baedd 920 btrfs_tree_unlock(child);
b4ce94de 921
925baedd 922 path->locks[level] = 0;
bb803951 923 path->nodes[level] = NULL;
6a884d7d 924 btrfs_clean_tree_block(mid);
925baedd 925 btrfs_tree_unlock(mid);
bb803951 926 /* once for the path */
5f39d397 927 free_extent_buffer(mid);
f0486c68
YZ
928
929 root_sub_used(root, mid->len);
7a163608 930 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
bb803951 931 /* once for the root ptr */
3083ee2e 932 free_extent_buffer_stale(mid);
f0486c68 933 return 0;
bb803951 934 }
5f39d397 935 if (btrfs_header_nritems(mid) >
0b246afa 936 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
bb803951
CM
937 return 0;
938
4b231ae4 939 left = btrfs_read_node_slot(parent, pslot - 1);
fb770ae4
LB
940 if (IS_ERR(left))
941 left = NULL;
942
5f39d397 943 if (left) {
bf77467a 944 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
5f39d397 945 wret = btrfs_cow_block(trans, root, left,
9631e4cc 946 parent, pslot - 1, &left,
bf59a5a2 947 BTRFS_NESTING_LEFT_COW);
54aa1f4d
CM
948 if (wret) {
949 ret = wret;
950 goto enospc;
951 }
2cc58cf2 952 }
fb770ae4 953
4b231ae4 954 right = btrfs_read_node_slot(parent, pslot + 1);
fb770ae4
LB
955 if (IS_ERR(right))
956 right = NULL;
957
5f39d397 958 if (right) {
bf77467a 959 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
5f39d397 960 wret = btrfs_cow_block(trans, root, right,
9631e4cc 961 parent, pslot + 1, &right,
bf59a5a2 962 BTRFS_NESTING_RIGHT_COW);
2cc58cf2
CM
963 if (wret) {
964 ret = wret;
965 goto enospc;
966 }
967 }
968
969 /* first, try to make some room in the middle buffer */
5f39d397
CM
970 if (left) {
971 orig_slot += btrfs_header_nritems(left);
d30a668f 972 wret = push_node_left(trans, left, mid, 1);
79f95c82
CM
973 if (wret < 0)
974 ret = wret;
bb803951 975 }
79f95c82
CM
976
977 /*
978 * then try to empty the right most buffer into the middle
979 */
5f39d397 980 if (right) {
d30a668f 981 wret = push_node_left(trans, mid, right, 1);
54aa1f4d 982 if (wret < 0 && wret != -ENOSPC)
79f95c82 983 ret = wret;
5f39d397 984 if (btrfs_header_nritems(right) == 0) {
6a884d7d 985 btrfs_clean_tree_block(right);
925baedd 986 btrfs_tree_unlock(right);
afe5fea7 987 del_ptr(root, path, level + 1, pslot + 1);
f0486c68 988 root_sub_used(root, right->len);
7a163608
FM
989 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
990 0, 1);
3083ee2e 991 free_extent_buffer_stale(right);
f0486c68 992 right = NULL;
bb803951 993 } else {
5f39d397
CM
994 struct btrfs_disk_key right_key;
995 btrfs_node_key(right, &right_key, 0);
f3a84ccd
FM
996 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
997 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
0e82bcfe 998 BUG_ON(ret < 0);
5f39d397
CM
999 btrfs_set_node_key(parent, &right_key, pslot + 1);
1000 btrfs_mark_buffer_dirty(parent);
bb803951
CM
1001 }
1002 }
5f39d397 1003 if (btrfs_header_nritems(mid) == 1) {
79f95c82
CM
1004 /*
1005 * we're not allowed to leave a node with one item in the
1006 * tree during a delete. A deletion from lower in the tree
1007 * could try to delete the only pointer in this node.
1008 * So, pull some keys from the left.
1009 * There has to be a left pointer at this point because
1010 * otherwise we would have pulled some pointers from the
1011 * right
1012 */
305a26af
MF
1013 if (!left) {
1014 ret = -EROFS;
0b246afa 1015 btrfs_handle_fs_error(fs_info, ret, NULL);
305a26af
MF
1016 goto enospc;
1017 }
55d32ed8 1018 wret = balance_node_right(trans, mid, left);
54aa1f4d 1019 if (wret < 0) {
79f95c82 1020 ret = wret;
54aa1f4d
CM
1021 goto enospc;
1022 }
bce4eae9 1023 if (wret == 1) {
d30a668f 1024 wret = push_node_left(trans, left, mid, 1);
bce4eae9
CM
1025 if (wret < 0)
1026 ret = wret;
1027 }
79f95c82
CM
1028 BUG_ON(wret == 1);
1029 }
5f39d397 1030 if (btrfs_header_nritems(mid) == 0) {
6a884d7d 1031 btrfs_clean_tree_block(mid);
925baedd 1032 btrfs_tree_unlock(mid);
afe5fea7 1033 del_ptr(root, path, level + 1, pslot);
f0486c68 1034 root_sub_used(root, mid->len);
7a163608 1035 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
3083ee2e 1036 free_extent_buffer_stale(mid);
f0486c68 1037 mid = NULL;
79f95c82
CM
1038 } else {
1039 /* update the parent key to reflect our changes */
5f39d397
CM
1040 struct btrfs_disk_key mid_key;
1041 btrfs_node_key(mid, &mid_key, 0);
f3a84ccd
FM
1042 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1043 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
0e82bcfe 1044 BUG_ON(ret < 0);
5f39d397
CM
1045 btrfs_set_node_key(parent, &mid_key, pslot);
1046 btrfs_mark_buffer_dirty(parent);
79f95c82 1047 }
bb803951 1048
79f95c82 1049 /* update the path */
5f39d397
CM
1050 if (left) {
1051 if (btrfs_header_nritems(left) > orig_slot) {
67439dad 1052 atomic_inc(&left->refs);
925baedd 1053 /* left was locked after cow */
5f39d397 1054 path->nodes[level] = left;
bb803951
CM
1055 path->slots[level + 1] -= 1;
1056 path->slots[level] = orig_slot;
925baedd
CM
1057 if (mid) {
1058 btrfs_tree_unlock(mid);
5f39d397 1059 free_extent_buffer(mid);
925baedd 1060 }
bb803951 1061 } else {
5f39d397 1062 orig_slot -= btrfs_header_nritems(left);
bb803951
CM
1063 path->slots[level] = orig_slot;
1064 }
1065 }
79f95c82 1066 /* double check we haven't messed things up */
e20d96d6 1067 if (orig_ptr !=
5f39d397 1068 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
79f95c82 1069 BUG();
54aa1f4d 1070enospc:
925baedd
CM
1071 if (right) {
1072 btrfs_tree_unlock(right);
5f39d397 1073 free_extent_buffer(right);
925baedd
CM
1074 }
1075 if (left) {
1076 if (path->nodes[level] != left)
1077 btrfs_tree_unlock(left);
5f39d397 1078 free_extent_buffer(left);
925baedd 1079 }
bb803951
CM
1080 return ret;
1081}
1082
d352ac68
CM
1083/* Node balancing for insertion. Here we only split or push nodes around
1084 * when they are completely full. This is also done top down, so we
1085 * have to be pessimistic.
1086 */
d397712b 1087static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
98ed5174
CM
1088 struct btrfs_root *root,
1089 struct btrfs_path *path, int level)
e66f709b 1090{
0b246afa 1091 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
1092 struct extent_buffer *right = NULL;
1093 struct extent_buffer *mid;
1094 struct extent_buffer *left = NULL;
1095 struct extent_buffer *parent = NULL;
e66f709b
CM
1096 int ret = 0;
1097 int wret;
1098 int pslot;
1099 int orig_slot = path->slots[level];
e66f709b
CM
1100
1101 if (level == 0)
1102 return 1;
1103
5f39d397 1104 mid = path->nodes[level];
7bb86316 1105 WARN_ON(btrfs_header_generation(mid) != trans->transid);
e66f709b 1106
a05a9bb1 1107 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 1108 parent = path->nodes[level + 1];
a05a9bb1
LZ
1109 pslot = path->slots[level + 1];
1110 }
e66f709b 1111
5f39d397 1112 if (!parent)
e66f709b 1113 return 1;
e66f709b 1114
4b231ae4 1115 left = btrfs_read_node_slot(parent, pslot - 1);
fb770ae4
LB
1116 if (IS_ERR(left))
1117 left = NULL;
e66f709b
CM
1118
1119 /* first, try to make some room in the middle buffer */
5f39d397 1120 if (left) {
e66f709b 1121 u32 left_nr;
925baedd 1122
bf77467a 1123 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
b4ce94de 1124
5f39d397 1125 left_nr = btrfs_header_nritems(left);
0b246afa 1126 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
33ade1f8
CM
1127 wret = 1;
1128 } else {
5f39d397 1129 ret = btrfs_cow_block(trans, root, left, parent,
9631e4cc 1130 pslot - 1, &left,
bf59a5a2 1131 BTRFS_NESTING_LEFT_COW);
54aa1f4d
CM
1132 if (ret)
1133 wret = 1;
1134 else {
d30a668f 1135 wret = push_node_left(trans, left, mid, 0);
54aa1f4d 1136 }
33ade1f8 1137 }
e66f709b
CM
1138 if (wret < 0)
1139 ret = wret;
1140 if (wret == 0) {
5f39d397 1141 struct btrfs_disk_key disk_key;
e66f709b 1142 orig_slot += left_nr;
5f39d397 1143 btrfs_node_key(mid, &disk_key, 0);
f3a84ccd
FM
1144 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1145 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
0e82bcfe 1146 BUG_ON(ret < 0);
5f39d397
CM
1147 btrfs_set_node_key(parent, &disk_key, pslot);
1148 btrfs_mark_buffer_dirty(parent);
1149 if (btrfs_header_nritems(left) > orig_slot) {
1150 path->nodes[level] = left;
e66f709b
CM
1151 path->slots[level + 1] -= 1;
1152 path->slots[level] = orig_slot;
925baedd 1153 btrfs_tree_unlock(mid);
5f39d397 1154 free_extent_buffer(mid);
e66f709b
CM
1155 } else {
1156 orig_slot -=
5f39d397 1157 btrfs_header_nritems(left);
e66f709b 1158 path->slots[level] = orig_slot;
925baedd 1159 btrfs_tree_unlock(left);
5f39d397 1160 free_extent_buffer(left);
e66f709b 1161 }
e66f709b
CM
1162 return 0;
1163 }
925baedd 1164 btrfs_tree_unlock(left);
5f39d397 1165 free_extent_buffer(left);
e66f709b 1166 }
4b231ae4 1167 right = btrfs_read_node_slot(parent, pslot + 1);
fb770ae4
LB
1168 if (IS_ERR(right))
1169 right = NULL;
e66f709b
CM
1170
1171 /*
1172 * then try to empty the right most buffer into the middle
1173 */
5f39d397 1174 if (right) {
33ade1f8 1175 u32 right_nr;
b4ce94de 1176
bf77467a 1177 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
b4ce94de 1178
5f39d397 1179 right_nr = btrfs_header_nritems(right);
0b246afa 1180 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
33ade1f8
CM
1181 wret = 1;
1182 } else {
5f39d397
CM
1183 ret = btrfs_cow_block(trans, root, right,
1184 parent, pslot + 1,
bf59a5a2 1185 &right, BTRFS_NESTING_RIGHT_COW);
54aa1f4d
CM
1186 if (ret)
1187 wret = 1;
1188 else {
55d32ed8 1189 wret = balance_node_right(trans, right, mid);
54aa1f4d 1190 }
33ade1f8 1191 }
e66f709b
CM
1192 if (wret < 0)
1193 ret = wret;
1194 if (wret == 0) {
5f39d397
CM
1195 struct btrfs_disk_key disk_key;
1196
1197 btrfs_node_key(right, &disk_key, 0);
f3a84ccd
FM
1198 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1199 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
0e82bcfe 1200 BUG_ON(ret < 0);
5f39d397
CM
1201 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1202 btrfs_mark_buffer_dirty(parent);
1203
1204 if (btrfs_header_nritems(mid) <= orig_slot) {
1205 path->nodes[level] = right;
e66f709b
CM
1206 path->slots[level + 1] += 1;
1207 path->slots[level] = orig_slot -
5f39d397 1208 btrfs_header_nritems(mid);
925baedd 1209 btrfs_tree_unlock(mid);
5f39d397 1210 free_extent_buffer(mid);
e66f709b 1211 } else {
925baedd 1212 btrfs_tree_unlock(right);
5f39d397 1213 free_extent_buffer(right);
e66f709b 1214 }
e66f709b
CM
1215 return 0;
1216 }
925baedd 1217 btrfs_tree_unlock(right);
5f39d397 1218 free_extent_buffer(right);
e66f709b 1219 }
e66f709b
CM
1220 return 1;
1221}
1222
3c69faec 1223/*
d352ac68
CM
1224 * readahead one full node of leaves, finding things that are close
1225 * to the block in 'slot', and triggering ra on them.
3c69faec 1226 */
2ff7e61e 1227static void reada_for_search(struct btrfs_fs_info *fs_info,
c8c42864
CM
1228 struct btrfs_path *path,
1229 int level, int slot, u64 objectid)
3c69faec 1230{
5f39d397 1231 struct extent_buffer *node;
01f46658 1232 struct btrfs_disk_key disk_key;
3c69faec 1233 u32 nritems;
3c69faec 1234 u64 search;
a7175319 1235 u64 target;
6b80053d 1236 u64 nread = 0;
ace75066 1237 u64 nread_max;
6b80053d
CM
1238 u32 nr;
1239 u32 blocksize;
1240 u32 nscan = 0;
db94535d 1241
ace75066 1242 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
6702ed49
CM
1243 return;
1244
1245 if (!path->nodes[level])
3c69faec
CM
1246 return;
1247
5f39d397 1248 node = path->nodes[level];
925baedd 1249
ace75066
FM
1250 /*
1251 * Since the time between visiting leaves is much shorter than the time
1252 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1253 * much IO at once (possibly random).
1254 */
1255 if (path->reada == READA_FORWARD_ALWAYS) {
1256 if (level > 1)
1257 nread_max = node->fs_info->nodesize;
1258 else
1259 nread_max = SZ_128K;
1260 } else {
1261 nread_max = SZ_64K;
1262 }
1263
3c69faec 1264 search = btrfs_node_blockptr(node, slot);
0b246afa 1265 blocksize = fs_info->nodesize;
069a2e37
FM
1266 if (path->reada != READA_FORWARD_ALWAYS) {
1267 struct extent_buffer *eb;
1268
1269 eb = find_extent_buffer(fs_info, search);
1270 if (eb) {
1271 free_extent_buffer(eb);
1272 return;
1273 }
3c69faec
CM
1274 }
1275
a7175319 1276 target = search;
6b80053d 1277
5f39d397 1278 nritems = btrfs_header_nritems(node);
6b80053d 1279 nr = slot;
25b8b936 1280
d397712b 1281 while (1) {
e4058b54 1282 if (path->reada == READA_BACK) {
6b80053d
CM
1283 if (nr == 0)
1284 break;
1285 nr--;
ace75066
FM
1286 } else if (path->reada == READA_FORWARD ||
1287 path->reada == READA_FORWARD_ALWAYS) {
6b80053d
CM
1288 nr++;
1289 if (nr >= nritems)
1290 break;
3c69faec 1291 }
e4058b54 1292 if (path->reada == READA_BACK && objectid) {
01f46658
CM
1293 btrfs_node_key(node, &disk_key, nr);
1294 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1295 break;
1296 }
6b80053d 1297 search = btrfs_node_blockptr(node, nr);
ace75066
FM
1298 if (path->reada == READA_FORWARD_ALWAYS ||
1299 (search <= target && target - search <= 65536) ||
a7175319 1300 (search > target && search - target <= 65536)) {
bfb484d9 1301 btrfs_readahead_node_child(node, nr);
6b80053d
CM
1302 nread += blocksize;
1303 }
1304 nscan++;
ace75066 1305 if (nread > nread_max || nscan > 32)
6b80053d 1306 break;
3c69faec
CM
1307 }
1308}
925baedd 1309
bfb484d9 1310static noinline void reada_for_balance(struct btrfs_path *path, int level)
b4ce94de 1311{
bfb484d9 1312 struct extent_buffer *parent;
b4ce94de
CM
1313 int slot;
1314 int nritems;
b4ce94de 1315
8c594ea8 1316 parent = path->nodes[level + 1];
b4ce94de 1317 if (!parent)
0b08851f 1318 return;
b4ce94de
CM
1319
1320 nritems = btrfs_header_nritems(parent);
8c594ea8 1321 slot = path->slots[level + 1];
b4ce94de 1322
bfb484d9
JB
1323 if (slot > 0)
1324 btrfs_readahead_node_child(parent, slot - 1);
1325 if (slot + 1 < nritems)
1326 btrfs_readahead_node_child(parent, slot + 1);
b4ce94de
CM
1327}
1328
1329
d352ac68 1330/*
d397712b
CM
1331 * when we walk down the tree, it is usually safe to unlock the higher layers
1332 * in the tree. The exceptions are when our path goes through slot 0, because
1333 * operations on the tree might require changing key pointers higher up in the
1334 * tree.
d352ac68 1335 *
d397712b
CM
1336 * callers might also have set path->keep_locks, which tells this code to keep
1337 * the lock if the path points to the last slot in the block. This is part of
1338 * walking through the tree, and selecting the next slot in the higher block.
d352ac68 1339 *
d397712b
CM
1340 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
1341 * if lowest_unlock is 1, level 0 won't be unlocked
d352ac68 1342 */
e02119d5 1343static noinline void unlock_up(struct btrfs_path *path, int level,
f7c79f30
CM
1344 int lowest_unlock, int min_write_lock_level,
1345 int *write_lock_level)
925baedd
CM
1346{
1347 int i;
1348 int skip_level = level;
051e1b9f 1349 int no_skips = 0;
925baedd
CM
1350 struct extent_buffer *t;
1351
1352 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1353 if (!path->nodes[i])
1354 break;
1355 if (!path->locks[i])
1356 break;
051e1b9f 1357 if (!no_skips && path->slots[i] == 0) {
925baedd
CM
1358 skip_level = i + 1;
1359 continue;
1360 }
051e1b9f 1361 if (!no_skips && path->keep_locks) {
925baedd
CM
1362 u32 nritems;
1363 t = path->nodes[i];
1364 nritems = btrfs_header_nritems(t);
051e1b9f 1365 if (nritems < 1 || path->slots[i] >= nritems - 1) {
925baedd
CM
1366 skip_level = i + 1;
1367 continue;
1368 }
1369 }
051e1b9f
CM
1370 if (skip_level < i && i >= lowest_unlock)
1371 no_skips = 1;
1372
925baedd 1373 t = path->nodes[i];
d80bb3f9 1374 if (i >= lowest_unlock && i > skip_level) {
bd681513 1375 btrfs_tree_unlock_rw(t, path->locks[i]);
925baedd 1376 path->locks[i] = 0;
f7c79f30
CM
1377 if (write_lock_level &&
1378 i > min_write_lock_level &&
1379 i <= *write_lock_level) {
1380 *write_lock_level = i - 1;
1381 }
925baedd
CM
1382 }
1383 }
1384}
1385
c8c42864
CM
1386/*
1387 * helper function for btrfs_search_slot. The goal is to find a block
1388 * in cache without setting the path to blocking. If we find the block
1389 * we return zero and the path is unchanged.
1390 *
1391 * If we can't find the block, we set the path blocking and do some
1392 * reada. -EAGAIN is returned and the search must be repeated.
1393 */
1394static int
d07b8528
LB
1395read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1396 struct extent_buffer **eb_ret, int level, int slot,
cda79c54 1397 const struct btrfs_key *key)
c8c42864 1398{
0b246afa 1399 struct btrfs_fs_info *fs_info = root->fs_info;
c8c42864
CM
1400 u64 blocknr;
1401 u64 gen;
c8c42864 1402 struct extent_buffer *tmp;
581c1760 1403 struct btrfs_key first_key;
76a05b35 1404 int ret;
581c1760 1405 int parent_level;
c8c42864 1406
213ff4b7
NB
1407 blocknr = btrfs_node_blockptr(*eb_ret, slot);
1408 gen = btrfs_node_ptr_generation(*eb_ret, slot);
1409 parent_level = btrfs_header_level(*eb_ret);
1410 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
c8c42864 1411
0b246afa 1412 tmp = find_extent_buffer(fs_info, blocknr);
cb44921a 1413 if (tmp) {
ace75066
FM
1414 if (p->reada == READA_FORWARD_ALWAYS)
1415 reada_for_search(fs_info, p, level, slot, key->objectid);
1416
b9fab919 1417 /* first we do an atomic uptodate check */
bdf7c00e 1418 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
448de471
QW
1419 /*
1420 * Do extra check for first_key, eb can be stale due to
1421 * being cached, read from scrub, or have multiple
1422 * parents (shared tree blocks).
1423 */
e064d5e9 1424 if (btrfs_verify_level_key(tmp,
448de471
QW
1425 parent_level - 1, &first_key, gen)) {
1426 free_extent_buffer(tmp);
1427 return -EUCLEAN;
1428 }
bdf7c00e
JB
1429 *eb_ret = tmp;
1430 return 0;
1431 }
1432
bdf7c00e 1433 /* now we're allowed to do a blocking uptodate check */
581c1760 1434 ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
bdf7c00e
JB
1435 if (!ret) {
1436 *eb_ret = tmp;
1437 return 0;
cb44921a 1438 }
bdf7c00e
JB
1439 free_extent_buffer(tmp);
1440 btrfs_release_path(p);
1441 return -EIO;
c8c42864
CM
1442 }
1443
1444 /*
1445 * reduce lock contention at high levels
1446 * of the btree by dropping locks before
76a05b35
CM
1447 * we read. Don't release the lock on the current
1448 * level because we need to walk this node to figure
1449 * out which blocks to read.
c8c42864 1450 */
8c594ea8 1451 btrfs_unlock_up_safe(p, level + 1);
8c594ea8 1452
e4058b54 1453 if (p->reada != READA_NONE)
2ff7e61e 1454 reada_for_search(fs_info, p, level, slot, key->objectid);
c8c42864 1455
76a05b35 1456 ret = -EAGAIN;
1b7ec85e
JB
1457 tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
1458 gen, parent_level - 1, &first_key);
64c043de 1459 if (!IS_ERR(tmp)) {
76a05b35
CM
1460 /*
1461 * If the read above didn't mark this buffer up to date,
1462 * it will never end up being up to date. Set ret to EIO now
1463 * and give up so that our caller doesn't loop forever
1464 * on our EAGAINs.
1465 */
e6a1d6fd 1466 if (!extent_buffer_uptodate(tmp))
76a05b35 1467 ret = -EIO;
c8c42864 1468 free_extent_buffer(tmp);
c871b0f2
LB
1469 } else {
1470 ret = PTR_ERR(tmp);
76a05b35 1471 }
02a3307a
LB
1472
1473 btrfs_release_path(p);
76a05b35 1474 return ret;
c8c42864
CM
1475}
1476
1477/*
1478 * helper function for btrfs_search_slot. This does all of the checks
1479 * for node-level blocks and does any balancing required based on
1480 * the ins_len.
1481 *
1482 * If no extra work was required, zero is returned. If we had to
1483 * drop the path, -EAGAIN is returned and btrfs_search_slot must
1484 * start over
1485 */
1486static int
1487setup_nodes_for_search(struct btrfs_trans_handle *trans,
1488 struct btrfs_root *root, struct btrfs_path *p,
bd681513
CM
1489 struct extent_buffer *b, int level, int ins_len,
1490 int *write_lock_level)
c8c42864 1491{
0b246afa 1492 struct btrfs_fs_info *fs_info = root->fs_info;
95b982de 1493 int ret = 0;
0b246afa 1494
c8c42864 1495 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
0b246afa 1496 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
c8c42864 1497
bd681513
CM
1498 if (*write_lock_level < level + 1) {
1499 *write_lock_level = level + 1;
1500 btrfs_release_path(p);
95b982de 1501 return -EAGAIN;
bd681513
CM
1502 }
1503
bfb484d9 1504 reada_for_balance(p, level);
95b982de 1505 ret = split_node(trans, root, p, level);
c8c42864 1506
c8c42864
CM
1507 b = p->nodes[level];
1508 } else if (ins_len < 0 && btrfs_header_nritems(b) <
0b246afa 1509 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
c8c42864 1510
bd681513
CM
1511 if (*write_lock_level < level + 1) {
1512 *write_lock_level = level + 1;
1513 btrfs_release_path(p);
95b982de 1514 return -EAGAIN;
bd681513
CM
1515 }
1516
bfb484d9 1517 reada_for_balance(p, level);
95b982de
NB
1518 ret = balance_level(trans, root, p, level);
1519 if (ret)
1520 return ret;
c8c42864 1521
c8c42864
CM
1522 b = p->nodes[level];
1523 if (!b) {
b3b4aa74 1524 btrfs_release_path(p);
95b982de 1525 return -EAGAIN;
c8c42864
CM
1526 }
1527 BUG_ON(btrfs_header_nritems(b) == 1);
1528 }
c8c42864
CM
1529 return ret;
1530}
1531
381cf658 1532int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
e33d5c3d
KN
1533 u64 iobjectid, u64 ioff, u8 key_type,
1534 struct btrfs_key *found_key)
1535{
1536 int ret;
1537 struct btrfs_key key;
1538 struct extent_buffer *eb;
381cf658
DS
1539
1540 ASSERT(path);
1d4c08e0 1541 ASSERT(found_key);
e33d5c3d
KN
1542
1543 key.type = key_type;
1544 key.objectid = iobjectid;
1545 key.offset = ioff;
1546
1547 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1d4c08e0 1548 if (ret < 0)
e33d5c3d
KN
1549 return ret;
1550
1551 eb = path->nodes[0];
1552 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1553 ret = btrfs_next_leaf(fs_root, path);
1554 if (ret)
1555 return ret;
1556 eb = path->nodes[0];
1557 }
1558
1559 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1560 if (found_key->type != key.type ||
1561 found_key->objectid != key.objectid)
1562 return 1;
1563
1564 return 0;
1565}
1566
1fc28d8e
LB
1567static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1568 struct btrfs_path *p,
1569 int write_lock_level)
1570{
1571 struct btrfs_fs_info *fs_info = root->fs_info;
1572 struct extent_buffer *b;
1573 int root_lock;
1574 int level = 0;
1575
1576 /* We try very hard to do read locks on the root */
1577 root_lock = BTRFS_READ_LOCK;
1578
1579 if (p->search_commit_root) {
be6821f8
FM
1580 /*
1581 * The commit roots are read only so we always do read locks,
1582 * and we always must hold the commit_root_sem when doing
1583 * searches on them, the only exception is send where we don't
1584 * want to block transaction commits for a long time, so
1585 * we need to clone the commit root in order to avoid races
1586 * with transaction commits that create a snapshot of one of
1587 * the roots used by a send operation.
1588 */
1589 if (p->need_commit_sem) {
1fc28d8e 1590 down_read(&fs_info->commit_root_sem);
be6821f8 1591 b = btrfs_clone_extent_buffer(root->commit_root);
1fc28d8e 1592 up_read(&fs_info->commit_root_sem);
be6821f8
FM
1593 if (!b)
1594 return ERR_PTR(-ENOMEM);
1595
1596 } else {
1597 b = root->commit_root;
67439dad 1598 atomic_inc(&b->refs);
be6821f8
FM
1599 }
1600 level = btrfs_header_level(b);
f9ddfd05
LB
1601 /*
1602 * Ensure that all callers have set skip_locking when
1603 * p->search_commit_root = 1.
1604 */
1605 ASSERT(p->skip_locking == 1);
1fc28d8e
LB
1606
1607 goto out;
1608 }
1609
1610 if (p->skip_locking) {
1611 b = btrfs_root_node(root);
1612 level = btrfs_header_level(b);
1613 goto out;
1614 }
1615
1616 /*
662c653b
LB
1617 * If the level is set to maximum, we can skip trying to get the read
1618 * lock.
1fc28d8e 1619 */
662c653b
LB
1620 if (write_lock_level < BTRFS_MAX_LEVEL) {
1621 /*
1622 * We don't know the level of the root node until we actually
1623 * have it read locked
1624 */
1bb96598 1625 b = btrfs_read_lock_root_node(root);
662c653b
LB
1626 level = btrfs_header_level(b);
1627 if (level > write_lock_level)
1628 goto out;
1629
1630 /* Whoops, must trade for write lock */
1631 btrfs_tree_read_unlock(b);
1632 free_extent_buffer(b);
1633 }
1fc28d8e 1634
1fc28d8e
LB
1635 b = btrfs_lock_root_node(root);
1636 root_lock = BTRFS_WRITE_LOCK;
1637
1638 /* The level might have changed, check again */
1639 level = btrfs_header_level(b);
1640
1641out:
1642 p->nodes[level] = b;
1643 if (!p->skip_locking)
1644 p->locks[level] = root_lock;
1645 /*
1646 * Callers are responsible for dropping b's references.
1647 */
1648 return b;
1649}
1650
1651
74123bd7 1652/*
4271ecea
NB
1653 * btrfs_search_slot - look for a key in a tree and perform necessary
1654 * modifications to preserve tree invariants.
74123bd7 1655 *
4271ecea
NB
1656 * @trans: Handle of transaction, used when modifying the tree
1657 * @p: Holds all btree nodes along the search path
1658 * @root: The root node of the tree
1659 * @key: The key we are looking for
9a664971 1660 * @ins_len: Indicates purpose of search:
1661 * >0 for inserts it's size of item inserted (*)
1662 * <0 for deletions
1663 * 0 for plain searches, not modifying the tree
1664 *
1665 * (*) If size of item inserted doesn't include
1666 * sizeof(struct btrfs_item), then p->search_for_extension must
1667 * be set.
4271ecea
NB
1668 * @cow: boolean should CoW operations be performed. Must always be 1
1669 * when modifying the tree.
97571fd0 1670 *
4271ecea
NB
1671 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
1672 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
1673 *
1674 * If @key is found, 0 is returned and you can find the item in the leaf level
1675 * of the path (level 0)
1676 *
1677 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
1678 * points to the slot where it should be inserted
1679 *
1680 * If an error is encountered while searching the tree a negative error number
1681 * is returned
74123bd7 1682 */
310712b2
OS
1683int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1684 const struct btrfs_key *key, struct btrfs_path *p,
1685 int ins_len, int cow)
be0e5c09 1686{
5f39d397 1687 struct extent_buffer *b;
be0e5c09
CM
1688 int slot;
1689 int ret;
33c66f43 1690 int err;
be0e5c09 1691 int level;
925baedd 1692 int lowest_unlock = 1;
bd681513
CM
1693 /* everything at write_lock_level or lower must be write locked */
1694 int write_lock_level = 0;
9f3a7427 1695 u8 lowest_level = 0;
f7c79f30 1696 int min_write_lock_level;
d7396f07 1697 int prev_cmp;
9f3a7427 1698
6702ed49 1699 lowest_level = p->lowest_level;
323ac95b 1700 WARN_ON(lowest_level && ins_len > 0);
22b0ebda 1701 WARN_ON(p->nodes[0] != NULL);
eb653de1 1702 BUG_ON(!cow && ins_len);
25179201 1703
bd681513 1704 if (ins_len < 0) {
925baedd 1705 lowest_unlock = 2;
65b51a00 1706
bd681513
CM
1707 /* when we are removing items, we might have to go up to level
1708 * two as we update tree pointers Make sure we keep write
1709 * for those levels as well
1710 */
1711 write_lock_level = 2;
1712 } else if (ins_len > 0) {
1713 /*
1714 * for inserting items, make sure we have a write lock on
1715 * level 1 so we can update keys
1716 */
1717 write_lock_level = 1;
1718 }
1719
1720 if (!cow)
1721 write_lock_level = -1;
1722
09a2a8f9 1723 if (cow && (p->keep_locks || p->lowest_level))
bd681513
CM
1724 write_lock_level = BTRFS_MAX_LEVEL;
1725
f7c79f30
CM
1726 min_write_lock_level = write_lock_level;
1727
bb803951 1728again:
d7396f07 1729 prev_cmp = -1;
1fc28d8e 1730 b = btrfs_search_slot_get_root(root, p, write_lock_level);
be6821f8
FM
1731 if (IS_ERR(b)) {
1732 ret = PTR_ERR(b);
1733 goto done;
1734 }
925baedd 1735
eb60ceac 1736 while (b) {
f624d976
QW
1737 int dec = 0;
1738
5f39d397 1739 level = btrfs_header_level(b);
65b51a00 1740
02217ed2 1741 if (cow) {
9ea2c7c9
NB
1742 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
1743
c8c42864
CM
1744 /*
1745 * if we don't really need to cow this block
1746 * then we don't want to set the path blocking,
1747 * so we test it here
1748 */
5963ffca 1749 if (!should_cow_block(trans, root, b))
65b51a00 1750 goto cow_done;
5d4f98a2 1751
bd681513
CM
1752 /*
1753 * must have write locks on this node and the
1754 * parent
1755 */
5124e00e
JB
1756 if (level > write_lock_level ||
1757 (level + 1 > write_lock_level &&
1758 level + 1 < BTRFS_MAX_LEVEL &&
1759 p->nodes[level + 1])) {
bd681513
CM
1760 write_lock_level = level + 1;
1761 btrfs_release_path(p);
1762 goto again;
1763 }
1764
9ea2c7c9
NB
1765 if (last_level)
1766 err = btrfs_cow_block(trans, root, b, NULL, 0,
9631e4cc
JB
1767 &b,
1768 BTRFS_NESTING_COW);
9ea2c7c9
NB
1769 else
1770 err = btrfs_cow_block(trans, root, b,
1771 p->nodes[level + 1],
9631e4cc
JB
1772 p->slots[level + 1], &b,
1773 BTRFS_NESTING_COW);
33c66f43 1774 if (err) {
33c66f43 1775 ret = err;
65b51a00 1776 goto done;
54aa1f4d 1777 }
02217ed2 1778 }
65b51a00 1779cow_done:
eb60ceac 1780 p->nodes[level] = b;
52398340
LB
1781 /*
1782 * Leave path with blocking locks to avoid massive
1783 * lock context switch, this is made on purpose.
1784 */
b4ce94de
CM
1785
1786 /*
1787 * we have a lock on b and as long as we aren't changing
1788 * the tree, there is no way to for the items in b to change.
1789 * It is safe to drop the lock on our parent before we
1790 * go through the expensive btree search on b.
1791 *
eb653de1
FDBM
1792 * If we're inserting or deleting (ins_len != 0), then we might
1793 * be changing slot zero, which may require changing the parent.
1794 * So, we can't drop the lock until after we know which slot
1795 * we're operating on.
b4ce94de 1796 */
eb653de1
FDBM
1797 if (!ins_len && !p->keep_locks) {
1798 int u = level + 1;
1799
1800 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
1801 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
1802 p->locks[u] = 0;
1803 }
1804 }
b4ce94de 1805
995e9a16
NB
1806 /*
1807 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
1808 * we can safely assume the target key will always be in slot 0
1809 * on lower levels due to the invariants BTRFS' btree provides,
1810 * namely that a btrfs_key_ptr entry always points to the
1811 * lowest key in the child node, thus we can skip searching
1812 * lower levels
1813 */
1814 if (prev_cmp == 0) {
1815 slot = 0;
1816 ret = 0;
1817 } else {
1818 ret = btrfs_bin_search(b, key, &slot);
1819 prev_cmp = ret;
1820 if (ret < 0)
1821 goto done;
1822 }
b4ce94de 1823
f624d976 1824 if (level == 0) {
be0e5c09 1825 p->slots[level] = slot;
9a664971 1826 /*
1827 * Item key already exists. In this case, if we are
1828 * allowed to insert the item (for example, in dir_item
1829 * case, item key collision is allowed), it will be
1830 * merged with the original item. Only the item size
1831 * grows, no new btrfs item will be added. If
1832 * search_for_extension is not set, ins_len already
1833 * accounts the size btrfs_item, deduct it here so leaf
1834 * space check will be correct.
1835 */
1836 if (ret == 0 && ins_len > 0 && !p->search_for_extension) {
1837 ASSERT(ins_len >= sizeof(struct btrfs_item));
1838 ins_len -= sizeof(struct btrfs_item);
1839 }
87b29b20 1840 if (ins_len > 0 &&
e902baac 1841 btrfs_leaf_free_space(b) < ins_len) {
bd681513
CM
1842 if (write_lock_level < 1) {
1843 write_lock_level = 1;
1844 btrfs_release_path(p);
1845 goto again;
1846 }
1847
33c66f43
YZ
1848 err = split_leaf(trans, root, key,
1849 p, ins_len, ret == 0);
b4ce94de 1850
33c66f43
YZ
1851 BUG_ON(err > 0);
1852 if (err) {
1853 ret = err;
65b51a00
CM
1854 goto done;
1855 }
5c680ed6 1856 }
459931ec 1857 if (!p->search_for_split)
f7c79f30 1858 unlock_up(p, level, lowest_unlock,
4b6f8e96 1859 min_write_lock_level, NULL);
65b51a00 1860 goto done;
be0e5c09 1861 }
f624d976
QW
1862 if (ret && slot > 0) {
1863 dec = 1;
1864 slot--;
1865 }
1866 p->slots[level] = slot;
1867 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
1868 &write_lock_level);
1869 if (err == -EAGAIN)
1870 goto again;
1871 if (err) {
1872 ret = err;
1873 goto done;
1874 }
1875 b = p->nodes[level];
1876 slot = p->slots[level];
1877
1878 /*
1879 * Slot 0 is special, if we change the key we have to update
1880 * the parent pointer which means we must have a write lock on
1881 * the parent
1882 */
1883 if (slot == 0 && ins_len && write_lock_level < level + 1) {
1884 write_lock_level = level + 1;
1885 btrfs_release_path(p);
1886 goto again;
1887 }
1888
1889 unlock_up(p, level, lowest_unlock, min_write_lock_level,
1890 &write_lock_level);
1891
1892 if (level == lowest_level) {
1893 if (dec)
1894 p->slots[level]++;
1895 goto done;
1896 }
1897
1898 err = read_block_for_search(root, p, &b, level, slot, key);
1899 if (err == -EAGAIN)
1900 goto again;
1901 if (err) {
1902 ret = err;
1903 goto done;
1904 }
1905
1906 if (!p->skip_locking) {
1907 level = btrfs_header_level(b);
1908 if (level <= write_lock_level) {
ac5887c8 1909 btrfs_tree_lock(b);
f624d976
QW
1910 p->locks[level] = BTRFS_WRITE_LOCK;
1911 } else {
fe596ca3 1912 btrfs_tree_read_lock(b);
f624d976
QW
1913 p->locks[level] = BTRFS_READ_LOCK;
1914 }
1915 p->nodes[level] = b;
1916 }
be0e5c09 1917 }
65b51a00
CM
1918 ret = 1;
1919done:
5f5bc6b1 1920 if (ret < 0 && !p->skip_release_on_error)
b3b4aa74 1921 btrfs_release_path(p);
65b51a00 1922 return ret;
be0e5c09 1923}
f75e2b79 1924ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
be0e5c09 1925
5d9e75c4
JS
1926/*
1927 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
1928 * current state of the tree together with the operations recorded in the tree
1929 * modification log to search for the key in a previous version of this tree, as
1930 * denoted by the time_seq parameter.
1931 *
1932 * Naturally, there is no support for insert, delete or cow operations.
1933 *
1934 * The resulting path and return value will be set up as if we called
1935 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
1936 */
310712b2 1937int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
5d9e75c4
JS
1938 struct btrfs_path *p, u64 time_seq)
1939{
0b246afa 1940 struct btrfs_fs_info *fs_info = root->fs_info;
5d9e75c4
JS
1941 struct extent_buffer *b;
1942 int slot;
1943 int ret;
1944 int err;
1945 int level;
1946 int lowest_unlock = 1;
1947 u8 lowest_level = 0;
1948
1949 lowest_level = p->lowest_level;
1950 WARN_ON(p->nodes[0] != NULL);
1951
1952 if (p->search_commit_root) {
1953 BUG_ON(time_seq);
1954 return btrfs_search_slot(NULL, root, key, p, 0, 0);
1955 }
1956
1957again:
f3a84ccd 1958 b = btrfs_get_old_root(root, time_seq);
315bed43
NB
1959 if (!b) {
1960 ret = -EIO;
1961 goto done;
1962 }
5d9e75c4 1963 level = btrfs_header_level(b);
5d9e75c4
JS
1964 p->locks[level] = BTRFS_READ_LOCK;
1965
1966 while (b) {
abe9339d
QW
1967 int dec = 0;
1968
5d9e75c4
JS
1969 level = btrfs_header_level(b);
1970 p->nodes[level] = b;
5d9e75c4
JS
1971
1972 /*
1973 * we have a lock on b and as long as we aren't changing
1974 * the tree, there is no way to for the items in b to change.
1975 * It is safe to drop the lock on our parent before we
1976 * go through the expensive btree search on b.
1977 */
1978 btrfs_unlock_up_safe(p, level + 1);
1979
995e9a16 1980 ret = btrfs_bin_search(b, key, &slot);
cbca7d59
FM
1981 if (ret < 0)
1982 goto done;
5d9e75c4 1983
abe9339d 1984 if (level == 0) {
5d9e75c4
JS
1985 p->slots[level] = slot;
1986 unlock_up(p, level, lowest_unlock, 0, NULL);
abe9339d
QW
1987 goto done;
1988 }
5d9e75c4 1989
abe9339d
QW
1990 if (ret && slot > 0) {
1991 dec = 1;
1992 slot--;
1993 }
1994 p->slots[level] = slot;
1995 unlock_up(p, level, lowest_unlock, 0, NULL);
5d9e75c4 1996
abe9339d
QW
1997 if (level == lowest_level) {
1998 if (dec)
1999 p->slots[level]++;
2000 goto done;
2001 }
5d9e75c4 2002
abe9339d
QW
2003 err = read_block_for_search(root, p, &b, level, slot, key);
2004 if (err == -EAGAIN)
2005 goto again;
2006 if (err) {
2007 ret = err;
5d9e75c4
JS
2008 goto done;
2009 }
abe9339d
QW
2010
2011 level = btrfs_header_level(b);
ac5887c8 2012 btrfs_tree_read_lock(b);
f3a84ccd 2013 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
abe9339d
QW
2014 if (!b) {
2015 ret = -ENOMEM;
2016 goto done;
2017 }
2018 p->locks[level] = BTRFS_READ_LOCK;
2019 p->nodes[level] = b;
5d9e75c4
JS
2020 }
2021 ret = 1;
2022done:
5d9e75c4
JS
2023 if (ret < 0)
2024 btrfs_release_path(p);
2025
2026 return ret;
2027}
2028
2f38b3e1
AJ
2029/*
2030 * helper to use instead of search slot if no exact match is needed but
2031 * instead the next or previous item should be returned.
2032 * When find_higher is true, the next higher item is returned, the next lower
2033 * otherwise.
2034 * When return_any and find_higher are both true, and no higher item is found,
2035 * return the next lower instead.
2036 * When return_any is true and find_higher is false, and no lower item is found,
2037 * return the next higher instead.
2038 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2039 * < 0 on error
2040 */
2041int btrfs_search_slot_for_read(struct btrfs_root *root,
310712b2
OS
2042 const struct btrfs_key *key,
2043 struct btrfs_path *p, int find_higher,
2044 int return_any)
2f38b3e1
AJ
2045{
2046 int ret;
2047 struct extent_buffer *leaf;
2048
2049again:
2050 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2051 if (ret <= 0)
2052 return ret;
2053 /*
2054 * a return value of 1 means the path is at the position where the
2055 * item should be inserted. Normally this is the next bigger item,
2056 * but in case the previous item is the last in a leaf, path points
2057 * to the first free slot in the previous leaf, i.e. at an invalid
2058 * item.
2059 */
2060 leaf = p->nodes[0];
2061
2062 if (find_higher) {
2063 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2064 ret = btrfs_next_leaf(root, p);
2065 if (ret <= 0)
2066 return ret;
2067 if (!return_any)
2068 return 1;
2069 /*
2070 * no higher item found, return the next
2071 * lower instead
2072 */
2073 return_any = 0;
2074 find_higher = 0;
2075 btrfs_release_path(p);
2076 goto again;
2077 }
2078 } else {
e6793769
AJ
2079 if (p->slots[0] == 0) {
2080 ret = btrfs_prev_leaf(root, p);
2081 if (ret < 0)
2082 return ret;
2083 if (!ret) {
23c6bf6a
FDBM
2084 leaf = p->nodes[0];
2085 if (p->slots[0] == btrfs_header_nritems(leaf))
2086 p->slots[0]--;
e6793769 2087 return 0;
2f38b3e1 2088 }
e6793769
AJ
2089 if (!return_any)
2090 return 1;
2091 /*
2092 * no lower item found, return the next
2093 * higher instead
2094 */
2095 return_any = 0;
2096 find_higher = 1;
2097 btrfs_release_path(p);
2098 goto again;
2099 } else {
2f38b3e1
AJ
2100 --p->slots[0];
2101 }
2102 }
2103 return 0;
2104}
2105
0ff40a91
MPS
2106/*
2107 * Execute search and call btrfs_previous_item to traverse backwards if the item
2108 * was not found.
2109 *
2110 * Return 0 if found, 1 if not found and < 0 if error.
2111 */
2112int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2113 struct btrfs_path *path)
2114{
2115 int ret;
2116
2117 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2118 if (ret > 0)
2119 ret = btrfs_previous_item(root, path, key->objectid, key->type);
2120
2121 if (ret == 0)
2122 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2123
2124 return ret;
2125}
2126
74123bd7
CM
2127/*
2128 * adjust the pointers going up the tree, starting at level
2129 * making sure the right key of each node is points to 'key'.
2130 * This is used after shifting pointers to the left, so it stops
2131 * fixing up pointers when a given leaf/node is not in slot 0 of the
2132 * higher levels
aa5d6bed 2133 *
74123bd7 2134 */
b167fa91 2135static void fixup_low_keys(struct btrfs_path *path,
143bede5 2136 struct btrfs_disk_key *key, int level)
be0e5c09
CM
2137{
2138 int i;
5f39d397 2139 struct extent_buffer *t;
0e82bcfe 2140 int ret;
5f39d397 2141
234b63a0 2142 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
be0e5c09 2143 int tslot = path->slots[i];
0e82bcfe 2144
eb60ceac 2145 if (!path->nodes[i])
be0e5c09 2146 break;
5f39d397 2147 t = path->nodes[i];
f3a84ccd
FM
2148 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2149 BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
0e82bcfe 2150 BUG_ON(ret < 0);
5f39d397 2151 btrfs_set_node_key(t, key, tslot);
d6025579 2152 btrfs_mark_buffer_dirty(path->nodes[i]);
be0e5c09
CM
2153 if (tslot != 0)
2154 break;
2155 }
2156}
2157
31840ae1
ZY
2158/*
2159 * update item key.
2160 *
2161 * This function isn't completely safe. It's the caller's responsibility
2162 * that the new key won't break the order
2163 */
b7a0365e
DD
2164void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2165 struct btrfs_path *path,
310712b2 2166 const struct btrfs_key *new_key)
31840ae1
ZY
2167{
2168 struct btrfs_disk_key disk_key;
2169 struct extent_buffer *eb;
2170 int slot;
2171
2172 eb = path->nodes[0];
2173 slot = path->slots[0];
2174 if (slot > 0) {
2175 btrfs_item_key(eb, &disk_key, slot - 1);
7c15d410
QW
2176 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2177 btrfs_crit(fs_info,
2178 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2179 slot, btrfs_disk_key_objectid(&disk_key),
2180 btrfs_disk_key_type(&disk_key),
2181 btrfs_disk_key_offset(&disk_key),
2182 new_key->objectid, new_key->type,
2183 new_key->offset);
2184 btrfs_print_leaf(eb);
2185 BUG();
2186 }
31840ae1
ZY
2187 }
2188 if (slot < btrfs_header_nritems(eb) - 1) {
2189 btrfs_item_key(eb, &disk_key, slot + 1);
7c15d410
QW
2190 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2191 btrfs_crit(fs_info,
2192 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2193 slot, btrfs_disk_key_objectid(&disk_key),
2194 btrfs_disk_key_type(&disk_key),
2195 btrfs_disk_key_offset(&disk_key),
2196 new_key->objectid, new_key->type,
2197 new_key->offset);
2198 btrfs_print_leaf(eb);
2199 BUG();
2200 }
31840ae1
ZY
2201 }
2202
2203 btrfs_cpu_key_to_disk(&disk_key, new_key);
2204 btrfs_set_item_key(eb, &disk_key, slot);
2205 btrfs_mark_buffer_dirty(eb);
2206 if (slot == 0)
b167fa91 2207 fixup_low_keys(path, &disk_key, 1);
31840ae1
ZY
2208}
2209
d16c702f
QW
2210/*
2211 * Check key order of two sibling extent buffers.
2212 *
2213 * Return true if something is wrong.
2214 * Return false if everything is fine.
2215 *
2216 * Tree-checker only works inside one tree block, thus the following
2217 * corruption can not be detected by tree-checker:
2218 *
2219 * Leaf @left | Leaf @right
2220 * --------------------------------------------------------------
2221 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
2222 *
2223 * Key f6 in leaf @left itself is valid, but not valid when the next
2224 * key in leaf @right is 7.
2225 * This can only be checked at tree block merge time.
2226 * And since tree checker has ensured all key order in each tree block
2227 * is correct, we only need to bother the last key of @left and the first
2228 * key of @right.
2229 */
2230static bool check_sibling_keys(struct extent_buffer *left,
2231 struct extent_buffer *right)
2232{
2233 struct btrfs_key left_last;
2234 struct btrfs_key right_first;
2235 int level = btrfs_header_level(left);
2236 int nr_left = btrfs_header_nritems(left);
2237 int nr_right = btrfs_header_nritems(right);
2238
2239 /* No key to check in one of the tree blocks */
2240 if (!nr_left || !nr_right)
2241 return false;
2242
2243 if (level) {
2244 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2245 btrfs_node_key_to_cpu(right, &right_first, 0);
2246 } else {
2247 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2248 btrfs_item_key_to_cpu(right, &right_first, 0);
2249 }
2250
2251 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2252 btrfs_crit(left->fs_info,
2253"bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2254 left_last.objectid, left_last.type,
2255 left_last.offset, right_first.objectid,
2256 right_first.type, right_first.offset);
2257 return true;
2258 }
2259 return false;
2260}
2261
74123bd7
CM
2262/*
2263 * try to push data from one node into the next node left in the
79f95c82 2264 * tree.
aa5d6bed
CM
2265 *
2266 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2267 * error, and > 0 if there was no room in the left hand block.
74123bd7 2268 */
98ed5174 2269static int push_node_left(struct btrfs_trans_handle *trans,
2ff7e61e 2270 struct extent_buffer *dst,
971a1f66 2271 struct extent_buffer *src, int empty)
be0e5c09 2272{
d30a668f 2273 struct btrfs_fs_info *fs_info = trans->fs_info;
be0e5c09 2274 int push_items = 0;
bb803951
CM
2275 int src_nritems;
2276 int dst_nritems;
aa5d6bed 2277 int ret = 0;
be0e5c09 2278
5f39d397
CM
2279 src_nritems = btrfs_header_nritems(src);
2280 dst_nritems = btrfs_header_nritems(dst);
0b246afa 2281 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
7bb86316
CM
2282 WARN_ON(btrfs_header_generation(src) != trans->transid);
2283 WARN_ON(btrfs_header_generation(dst) != trans->transid);
54aa1f4d 2284
bce4eae9 2285 if (!empty && src_nritems <= 8)
971a1f66
CM
2286 return 1;
2287
d397712b 2288 if (push_items <= 0)
be0e5c09
CM
2289 return 1;
2290
bce4eae9 2291 if (empty) {
971a1f66 2292 push_items = min(src_nritems, push_items);
bce4eae9
CM
2293 if (push_items < src_nritems) {
2294 /* leave at least 8 pointers in the node if
2295 * we aren't going to empty it
2296 */
2297 if (src_nritems - push_items < 8) {
2298 if (push_items <= 8)
2299 return 1;
2300 push_items -= 8;
2301 }
2302 }
2303 } else
2304 push_items = min(src_nritems - 8, push_items);
79f95c82 2305
d16c702f
QW
2306 /* dst is the left eb, src is the middle eb */
2307 if (check_sibling_keys(dst, src)) {
2308 ret = -EUCLEAN;
2309 btrfs_abort_transaction(trans, ret);
2310 return ret;
2311 }
f3a84ccd 2312 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
5de865ee 2313 if (ret) {
66642832 2314 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
2315 return ret;
2316 }
5f39d397
CM
2317 copy_extent_buffer(dst, src,
2318 btrfs_node_key_ptr_offset(dst_nritems),
2319 btrfs_node_key_ptr_offset(0),
d397712b 2320 push_items * sizeof(struct btrfs_key_ptr));
5f39d397 2321
bb803951 2322 if (push_items < src_nritems) {
57911b8b 2323 /*
f3a84ccd
FM
2324 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2325 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
57911b8b 2326 */
5f39d397
CM
2327 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
2328 btrfs_node_key_ptr_offset(push_items),
2329 (src_nritems - push_items) *
2330 sizeof(struct btrfs_key_ptr));
2331 }
2332 btrfs_set_header_nritems(src, src_nritems - push_items);
2333 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2334 btrfs_mark_buffer_dirty(src);
2335 btrfs_mark_buffer_dirty(dst);
31840ae1 2336
79f95c82
CM
2337 return ret;
2338}
2339
2340/*
2341 * try to push data from one node into the next node right in the
2342 * tree.
2343 *
2344 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2345 * error, and > 0 if there was no room in the right hand block.
2346 *
2347 * this will only push up to 1/2 the contents of the left node over
2348 */
5f39d397 2349static int balance_node_right(struct btrfs_trans_handle *trans,
5f39d397
CM
2350 struct extent_buffer *dst,
2351 struct extent_buffer *src)
79f95c82 2352{
55d32ed8 2353 struct btrfs_fs_info *fs_info = trans->fs_info;
79f95c82
CM
2354 int push_items = 0;
2355 int max_push;
2356 int src_nritems;
2357 int dst_nritems;
2358 int ret = 0;
79f95c82 2359
7bb86316
CM
2360 WARN_ON(btrfs_header_generation(src) != trans->transid);
2361 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2362
5f39d397
CM
2363 src_nritems = btrfs_header_nritems(src);
2364 dst_nritems = btrfs_header_nritems(dst);
0b246afa 2365 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
d397712b 2366 if (push_items <= 0)
79f95c82 2367 return 1;
bce4eae9 2368
d397712b 2369 if (src_nritems < 4)
bce4eae9 2370 return 1;
79f95c82
CM
2371
2372 max_push = src_nritems / 2 + 1;
2373 /* don't try to empty the node */
d397712b 2374 if (max_push >= src_nritems)
79f95c82 2375 return 1;
252c38f0 2376
79f95c82
CM
2377 if (max_push < push_items)
2378 push_items = max_push;
2379
d16c702f
QW
2380 /* dst is the right eb, src is the middle eb */
2381 if (check_sibling_keys(src, dst)) {
2382 ret = -EUCLEAN;
2383 btrfs_abort_transaction(trans, ret);
2384 return ret;
2385 }
f3a84ccd 2386 ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
bf1d3425 2387 BUG_ON(ret < 0);
5f39d397
CM
2388 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
2389 btrfs_node_key_ptr_offset(0),
2390 (dst_nritems) *
2391 sizeof(struct btrfs_key_ptr));
d6025579 2392
f3a84ccd
FM
2393 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2394 push_items);
5de865ee 2395 if (ret) {
66642832 2396 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
2397 return ret;
2398 }
5f39d397
CM
2399 copy_extent_buffer(dst, src,
2400 btrfs_node_key_ptr_offset(0),
2401 btrfs_node_key_ptr_offset(src_nritems - push_items),
d397712b 2402 push_items * sizeof(struct btrfs_key_ptr));
79f95c82 2403
5f39d397
CM
2404 btrfs_set_header_nritems(src, src_nritems - push_items);
2405 btrfs_set_header_nritems(dst, dst_nritems + push_items);
79f95c82 2406
5f39d397
CM
2407 btrfs_mark_buffer_dirty(src);
2408 btrfs_mark_buffer_dirty(dst);
31840ae1 2409
aa5d6bed 2410 return ret;
be0e5c09
CM
2411}
2412
97571fd0
CM
2413/*
2414 * helper function to insert a new root level in the tree.
2415 * A new node is allocated, and a single item is inserted to
2416 * point to the existing root
aa5d6bed
CM
2417 *
2418 * returns zero on success or < 0 on failure.
97571fd0 2419 */
d397712b 2420static noinline int insert_new_root(struct btrfs_trans_handle *trans,
5f39d397 2421 struct btrfs_root *root,
fdd99c72 2422 struct btrfs_path *path, int level)
5c680ed6 2423{
0b246afa 2424 struct btrfs_fs_info *fs_info = root->fs_info;
7bb86316 2425 u64 lower_gen;
5f39d397
CM
2426 struct extent_buffer *lower;
2427 struct extent_buffer *c;
925baedd 2428 struct extent_buffer *old;
5f39d397 2429 struct btrfs_disk_key lower_key;
d9d19a01 2430 int ret;
5c680ed6
CM
2431
2432 BUG_ON(path->nodes[level]);
2433 BUG_ON(path->nodes[level-1] != root->node);
2434
7bb86316
CM
2435 lower = path->nodes[level-1];
2436 if (level == 1)
2437 btrfs_item_key(lower, &lower_key, 0);
2438 else
2439 btrfs_node_key(lower, &lower_key, 0);
2440
79bd3712
FM
2441 c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2442 &lower_key, level, root->node->start, 0,
2443 BTRFS_NESTING_NEW_ROOT);
5f39d397
CM
2444 if (IS_ERR(c))
2445 return PTR_ERR(c);
925baedd 2446
0b246afa 2447 root_add_used(root, fs_info->nodesize);
f0486c68 2448
5f39d397 2449 btrfs_set_header_nritems(c, 1);
5f39d397 2450 btrfs_set_node_key(c, &lower_key, 0);
db94535d 2451 btrfs_set_node_blockptr(c, 0, lower->start);
7bb86316 2452 lower_gen = btrfs_header_generation(lower);
31840ae1 2453 WARN_ON(lower_gen != trans->transid);
7bb86316
CM
2454
2455 btrfs_set_node_ptr_generation(c, 0, lower_gen);
d5719762 2456
5f39d397 2457 btrfs_mark_buffer_dirty(c);
d5719762 2458
925baedd 2459 old = root->node;
406808ab 2460 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
d9d19a01 2461 BUG_ON(ret < 0);
240f62c8 2462 rcu_assign_pointer(root->node, c);
925baedd
CM
2463
2464 /* the super has an extra ref to root->node */
2465 free_extent_buffer(old);
2466
0b86a832 2467 add_root_to_dirty_list(root);
67439dad 2468 atomic_inc(&c->refs);
5f39d397 2469 path->nodes[level] = c;
ac5887c8 2470 path->locks[level] = BTRFS_WRITE_LOCK;
5c680ed6
CM
2471 path->slots[level] = 0;
2472 return 0;
2473}
2474
74123bd7
CM
2475/*
2476 * worker function to insert a single pointer in a node.
2477 * the node should have enough room for the pointer already
97571fd0 2478 *
74123bd7
CM
2479 * slot and level indicate where you want the key to go, and
2480 * blocknr is the block the key points to.
2481 */
143bede5 2482static void insert_ptr(struct btrfs_trans_handle *trans,
6ad3cf6d 2483 struct btrfs_path *path,
143bede5 2484 struct btrfs_disk_key *key, u64 bytenr,
c3e06965 2485 int slot, int level)
74123bd7 2486{
5f39d397 2487 struct extent_buffer *lower;
74123bd7 2488 int nritems;
f3ea38da 2489 int ret;
5c680ed6
CM
2490
2491 BUG_ON(!path->nodes[level]);
49d0c642 2492 btrfs_assert_tree_write_locked(path->nodes[level]);
5f39d397
CM
2493 lower = path->nodes[level];
2494 nritems = btrfs_header_nritems(lower);
c293498b 2495 BUG_ON(slot > nritems);
6ad3cf6d 2496 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
74123bd7 2497 if (slot != nritems) {
bf1d3425 2498 if (level) {
f3a84ccd
FM
2499 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2500 slot, nritems - slot);
bf1d3425
DS
2501 BUG_ON(ret < 0);
2502 }
5f39d397
CM
2503 memmove_extent_buffer(lower,
2504 btrfs_node_key_ptr_offset(slot + 1),
2505 btrfs_node_key_ptr_offset(slot),
d6025579 2506 (nritems - slot) * sizeof(struct btrfs_key_ptr));
74123bd7 2507 }
c3e06965 2508 if (level) {
f3a84ccd
FM
2509 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2510 BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
f3ea38da
JS
2511 BUG_ON(ret < 0);
2512 }
5f39d397 2513 btrfs_set_node_key(lower, key, slot);
db94535d 2514 btrfs_set_node_blockptr(lower, slot, bytenr);
74493f7a
CM
2515 WARN_ON(trans->transid == 0);
2516 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
5f39d397
CM
2517 btrfs_set_header_nritems(lower, nritems + 1);
2518 btrfs_mark_buffer_dirty(lower);
74123bd7
CM
2519}
2520
97571fd0
CM
2521/*
2522 * split the node at the specified level in path in two.
2523 * The path is corrected to point to the appropriate node after the split
2524 *
2525 * Before splitting this tries to make some room in the node by pushing
2526 * left and right, if either one works, it returns right away.
aa5d6bed
CM
2527 *
2528 * returns 0 on success and < 0 on failure
97571fd0 2529 */
e02119d5
CM
2530static noinline int split_node(struct btrfs_trans_handle *trans,
2531 struct btrfs_root *root,
2532 struct btrfs_path *path, int level)
be0e5c09 2533{
0b246afa 2534 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
2535 struct extent_buffer *c;
2536 struct extent_buffer *split;
2537 struct btrfs_disk_key disk_key;
be0e5c09 2538 int mid;
5c680ed6 2539 int ret;
7518a238 2540 u32 c_nritems;
eb60ceac 2541
5f39d397 2542 c = path->nodes[level];
7bb86316 2543 WARN_ON(btrfs_header_generation(c) != trans->transid);
5f39d397 2544 if (c == root->node) {
d9abbf1c 2545 /*
90f8d62e
JS
2546 * trying to split the root, lets make a new one
2547 *
fdd99c72 2548 * tree mod log: We don't log_removal old root in
90f8d62e
JS
2549 * insert_new_root, because that root buffer will be kept as a
2550 * normal node. We are going to log removal of half of the
f3a84ccd
FM
2551 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2552 * holding a tree lock on the buffer, which is why we cannot
2553 * race with other tree_mod_log users.
d9abbf1c 2554 */
fdd99c72 2555 ret = insert_new_root(trans, root, path, level + 1);
5c680ed6
CM
2556 if (ret)
2557 return ret;
b3612421 2558 } else {
e66f709b 2559 ret = push_nodes_for_insert(trans, root, path, level);
5f39d397
CM
2560 c = path->nodes[level];
2561 if (!ret && btrfs_header_nritems(c) <
0b246afa 2562 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
e66f709b 2563 return 0;
54aa1f4d
CM
2564 if (ret < 0)
2565 return ret;
be0e5c09 2566 }
e66f709b 2567
5f39d397 2568 c_nritems = btrfs_header_nritems(c);
5d4f98a2
YZ
2569 mid = (c_nritems + 1) / 2;
2570 btrfs_node_key(c, &disk_key, mid);
7bb86316 2571
79bd3712
FM
2572 split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2573 &disk_key, level, c->start, 0,
2574 BTRFS_NESTING_SPLIT);
5f39d397
CM
2575 if (IS_ERR(split))
2576 return PTR_ERR(split);
2577
0b246afa 2578 root_add_used(root, fs_info->nodesize);
bc877d28 2579 ASSERT(btrfs_header_level(c) == level);
54aa1f4d 2580
f3a84ccd 2581 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
5de865ee 2582 if (ret) {
66642832 2583 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
2584 return ret;
2585 }
5f39d397
CM
2586 copy_extent_buffer(split, c,
2587 btrfs_node_key_ptr_offset(0),
2588 btrfs_node_key_ptr_offset(mid),
2589 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2590 btrfs_set_header_nritems(split, c_nritems - mid);
2591 btrfs_set_header_nritems(c, mid);
aa5d6bed 2592
5f39d397
CM
2593 btrfs_mark_buffer_dirty(c);
2594 btrfs_mark_buffer_dirty(split);
2595
6ad3cf6d 2596 insert_ptr(trans, path, &disk_key, split->start,
c3e06965 2597 path->slots[level + 1] + 1, level + 1);
aa5d6bed 2598
5de08d7d 2599 if (path->slots[level] >= mid) {
5c680ed6 2600 path->slots[level] -= mid;
925baedd 2601 btrfs_tree_unlock(c);
5f39d397
CM
2602 free_extent_buffer(c);
2603 path->nodes[level] = split;
5c680ed6
CM
2604 path->slots[level + 1] += 1;
2605 } else {
925baedd 2606 btrfs_tree_unlock(split);
5f39d397 2607 free_extent_buffer(split);
be0e5c09 2608 }
d5286a92 2609 return 0;
be0e5c09
CM
2610}
2611
74123bd7
CM
2612/*
2613 * how many bytes are required to store the items in a leaf. start
2614 * and nr indicate which items in the leaf to check. This totals up the
2615 * space used both by the item structs and the item data
2616 */
5f39d397 2617static int leaf_space_used(struct extent_buffer *l, int start, int nr)
be0e5c09
CM
2618{
2619 int data_len;
5f39d397 2620 int nritems = btrfs_header_nritems(l);
d4dbff95 2621 int end = min(nritems, start + nr) - 1;
be0e5c09
CM
2622
2623 if (!nr)
2624 return 0;
227f3cd0
JB
2625 data_len = btrfs_item_offset_nr(l, start) + btrfs_item_size_nr(l, start);
2626 data_len = data_len - btrfs_item_offset_nr(l, end);
0783fcfc 2627 data_len += sizeof(struct btrfs_item) * nr;
d4dbff95 2628 WARN_ON(data_len < 0);
be0e5c09
CM
2629 return data_len;
2630}
2631
d4dbff95
CM
2632/*
2633 * The space between the end of the leaf items and
2634 * the start of the leaf data. IOW, how much room
2635 * the leaf has left for both items and data
2636 */
e902baac 2637noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
d4dbff95 2638{
e902baac 2639 struct btrfs_fs_info *fs_info = leaf->fs_info;
5f39d397
CM
2640 int nritems = btrfs_header_nritems(leaf);
2641 int ret;
0b246afa
JM
2642
2643 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
5f39d397 2644 if (ret < 0) {
0b246afa
JM
2645 btrfs_crit(fs_info,
2646 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2647 ret,
2648 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
2649 leaf_space_used(leaf, 0, nritems), nritems);
5f39d397
CM
2650 }
2651 return ret;
d4dbff95
CM
2652}
2653
99d8f83c
CM
2654/*
2655 * min slot controls the lowest index we're willing to push to the
2656 * right. We'll push up to and including min_slot, but no lower
2657 */
f72f0010 2658static noinline int __push_leaf_right(struct btrfs_path *path,
44871b1b
CM
2659 int data_size, int empty,
2660 struct extent_buffer *right,
99d8f83c
CM
2661 int free_space, u32 left_nritems,
2662 u32 min_slot)
00ec4c51 2663{
f72f0010 2664 struct btrfs_fs_info *fs_info = right->fs_info;
5f39d397 2665 struct extent_buffer *left = path->nodes[0];
44871b1b 2666 struct extent_buffer *upper = path->nodes[1];
cfed81a0 2667 struct btrfs_map_token token;
5f39d397 2668 struct btrfs_disk_key disk_key;
00ec4c51 2669 int slot;
34a38218 2670 u32 i;
00ec4c51
CM
2671 int push_space = 0;
2672 int push_items = 0;
0783fcfc 2673 struct btrfs_item *item;
34a38218 2674 u32 nr;
7518a238 2675 u32 right_nritems;
5f39d397 2676 u32 data_end;
db94535d 2677 u32 this_item_size;
00ec4c51 2678
34a38218
CM
2679 if (empty)
2680 nr = 0;
2681 else
99d8f83c 2682 nr = max_t(u32, 1, min_slot);
34a38218 2683
31840ae1 2684 if (path->slots[0] >= left_nritems)
87b29b20 2685 push_space += data_size;
31840ae1 2686
44871b1b 2687 slot = path->slots[1];
34a38218
CM
2688 i = left_nritems - 1;
2689 while (i >= nr) {
31840ae1
ZY
2690 if (!empty && push_items > 0) {
2691 if (path->slots[0] > i)
2692 break;
2693 if (path->slots[0] == i) {
e902baac
DS
2694 int space = btrfs_leaf_free_space(left);
2695
31840ae1
ZY
2696 if (space + push_space * 2 > free_space)
2697 break;
2698 }
2699 }
2700
00ec4c51 2701 if (path->slots[0] == i)
87b29b20 2702 push_space += data_size;
db94535d 2703
227f3cd0 2704 this_item_size = btrfs_item_size_nr(left, i);
db94535d 2705 if (this_item_size + sizeof(*item) + push_space > free_space)
00ec4c51 2706 break;
31840ae1 2707
00ec4c51 2708 push_items++;
db94535d 2709 push_space += this_item_size + sizeof(*item);
34a38218
CM
2710 if (i == 0)
2711 break;
2712 i--;
db94535d 2713 }
5f39d397 2714
925baedd
CM
2715 if (push_items == 0)
2716 goto out_unlock;
5f39d397 2717
6c1500f2 2718 WARN_ON(!empty && push_items == left_nritems);
5f39d397 2719
00ec4c51 2720 /* push left to right */
5f39d397 2721 right_nritems = btrfs_header_nritems(right);
34a38218 2722
5f39d397 2723 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
8f881e8c 2724 push_space -= leaf_data_end(left);
5f39d397 2725
00ec4c51 2726 /* make room in the right data area */
8f881e8c 2727 data_end = leaf_data_end(right);
5f39d397 2728 memmove_extent_buffer(right,
3d9ec8c4
NB
2729 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
2730 BTRFS_LEAF_DATA_OFFSET + data_end,
0b246afa 2731 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
5f39d397 2732
00ec4c51 2733 /* copy from the left data area */
3d9ec8c4 2734 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
0b246afa 2735 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
8f881e8c 2736 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
d6025579 2737 push_space);
5f39d397
CM
2738
2739 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
2740 btrfs_item_nr_offset(0),
2741 right_nritems * sizeof(struct btrfs_item));
2742
00ec4c51 2743 /* copy the items from left to right */
5f39d397
CM
2744 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
2745 btrfs_item_nr_offset(left_nritems - push_items),
2746 push_items * sizeof(struct btrfs_item));
00ec4c51
CM
2747
2748 /* update the item pointers */
c82f823c 2749 btrfs_init_map_token(&token, right);
7518a238 2750 right_nritems += push_items;
5f39d397 2751 btrfs_set_header_nritems(right, right_nritems);
0b246afa 2752 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
7518a238 2753 for (i = 0; i < right_nritems; i++) {
dd3cc16b 2754 item = btrfs_item_nr(i);
cc4c13d5
DS
2755 push_space -= btrfs_token_item_size(&token, item);
2756 btrfs_set_token_item_offset(&token, item, push_space);
db94535d
CM
2757 }
2758
7518a238 2759 left_nritems -= push_items;
5f39d397 2760 btrfs_set_header_nritems(left, left_nritems);
00ec4c51 2761
34a38218
CM
2762 if (left_nritems)
2763 btrfs_mark_buffer_dirty(left);
f0486c68 2764 else
6a884d7d 2765 btrfs_clean_tree_block(left);
f0486c68 2766
5f39d397 2767 btrfs_mark_buffer_dirty(right);
a429e513 2768
5f39d397
CM
2769 btrfs_item_key(right, &disk_key, 0);
2770 btrfs_set_node_key(upper, &disk_key, slot + 1);
d6025579 2771 btrfs_mark_buffer_dirty(upper);
02217ed2 2772
00ec4c51 2773 /* then fixup the leaf pointer in the path */
7518a238
CM
2774 if (path->slots[0] >= left_nritems) {
2775 path->slots[0] -= left_nritems;
925baedd 2776 if (btrfs_header_nritems(path->nodes[0]) == 0)
6a884d7d 2777 btrfs_clean_tree_block(path->nodes[0]);
925baedd 2778 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
2779 free_extent_buffer(path->nodes[0]);
2780 path->nodes[0] = right;
00ec4c51
CM
2781 path->slots[1] += 1;
2782 } else {
925baedd 2783 btrfs_tree_unlock(right);
5f39d397 2784 free_extent_buffer(right);
00ec4c51
CM
2785 }
2786 return 0;
925baedd
CM
2787
2788out_unlock:
2789 btrfs_tree_unlock(right);
2790 free_extent_buffer(right);
2791 return 1;
00ec4c51 2792}
925baedd 2793
44871b1b
CM
2794/*
2795 * push some data in the path leaf to the right, trying to free up at
2796 * least data_size bytes. returns zero if the push worked, nonzero otherwise
2797 *
2798 * returns 1 if the push failed because the other node didn't have enough
2799 * room, 0 if everything worked out and < 0 if there were major errors.
99d8f83c
CM
2800 *
2801 * this will push starting from min_slot to the end of the leaf. It won't
2802 * push any slot lower than min_slot
44871b1b
CM
2803 */
2804static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
2805 *root, struct btrfs_path *path,
2806 int min_data_size, int data_size,
2807 int empty, u32 min_slot)
44871b1b
CM
2808{
2809 struct extent_buffer *left = path->nodes[0];
2810 struct extent_buffer *right;
2811 struct extent_buffer *upper;
2812 int slot;
2813 int free_space;
2814 u32 left_nritems;
2815 int ret;
2816
2817 if (!path->nodes[1])
2818 return 1;
2819
2820 slot = path->slots[1];
2821 upper = path->nodes[1];
2822 if (slot >= btrfs_header_nritems(upper) - 1)
2823 return 1;
2824
49d0c642 2825 btrfs_assert_tree_write_locked(path->nodes[1]);
44871b1b 2826
4b231ae4 2827 right = btrfs_read_node_slot(upper, slot + 1);
fb770ae4
LB
2828 /*
2829 * slot + 1 is not valid or we fail to read the right node,
2830 * no big deal, just return.
2831 */
2832 if (IS_ERR(right))
91ca338d
TI
2833 return 1;
2834
bf77467a 2835 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
44871b1b 2836
e902baac 2837 free_space = btrfs_leaf_free_space(right);
44871b1b
CM
2838 if (free_space < data_size)
2839 goto out_unlock;
2840
2841 /* cow and double check */
2842 ret = btrfs_cow_block(trans, root, right, upper,
bf59a5a2 2843 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
44871b1b
CM
2844 if (ret)
2845 goto out_unlock;
2846
e902baac 2847 free_space = btrfs_leaf_free_space(right);
44871b1b
CM
2848 if (free_space < data_size)
2849 goto out_unlock;
2850
2851 left_nritems = btrfs_header_nritems(left);
2852 if (left_nritems == 0)
2853 goto out_unlock;
2854
d16c702f
QW
2855 if (check_sibling_keys(left, right)) {
2856 ret = -EUCLEAN;
2857 btrfs_tree_unlock(right);
2858 free_extent_buffer(right);
2859 return ret;
2860 }
2ef1fed2
FDBM
2861 if (path->slots[0] == left_nritems && !empty) {
2862 /* Key greater than all keys in the leaf, right neighbor has
2863 * enough room for it and we're not emptying our leaf to delete
2864 * it, therefore use right neighbor to insert the new item and
52042d8e 2865 * no need to touch/dirty our left leaf. */
2ef1fed2
FDBM
2866 btrfs_tree_unlock(left);
2867 free_extent_buffer(left);
2868 path->nodes[0] = right;
2869 path->slots[0] = 0;
2870 path->slots[1]++;
2871 return 0;
2872 }
2873
f72f0010 2874 return __push_leaf_right(path, min_data_size, empty,
99d8f83c 2875 right, free_space, left_nritems, min_slot);
44871b1b
CM
2876out_unlock:
2877 btrfs_tree_unlock(right);
2878 free_extent_buffer(right);
2879 return 1;
2880}
2881
74123bd7
CM
2882/*
2883 * push some data in the path leaf to the left, trying to free up at
2884 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
2885 *
2886 * max_slot can put a limit on how far into the leaf we'll push items. The
2887 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
2888 * items
74123bd7 2889 */
8087c193 2890static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
44871b1b 2891 int empty, struct extent_buffer *left,
99d8f83c
CM
2892 int free_space, u32 right_nritems,
2893 u32 max_slot)
be0e5c09 2894{
8087c193 2895 struct btrfs_fs_info *fs_info = left->fs_info;
5f39d397
CM
2896 struct btrfs_disk_key disk_key;
2897 struct extent_buffer *right = path->nodes[0];
be0e5c09 2898 int i;
be0e5c09
CM
2899 int push_space = 0;
2900 int push_items = 0;
0783fcfc 2901 struct btrfs_item *item;
7518a238 2902 u32 old_left_nritems;
34a38218 2903 u32 nr;
aa5d6bed 2904 int ret = 0;
db94535d
CM
2905 u32 this_item_size;
2906 u32 old_left_item_size;
cfed81a0
CM
2907 struct btrfs_map_token token;
2908
34a38218 2909 if (empty)
99d8f83c 2910 nr = min(right_nritems, max_slot);
34a38218 2911 else
99d8f83c 2912 nr = min(right_nritems - 1, max_slot);
34a38218
CM
2913
2914 for (i = 0; i < nr; i++) {
31840ae1
ZY
2915 if (!empty && push_items > 0) {
2916 if (path->slots[0] < i)
2917 break;
2918 if (path->slots[0] == i) {
e902baac
DS
2919 int space = btrfs_leaf_free_space(right);
2920
31840ae1
ZY
2921 if (space + push_space * 2 > free_space)
2922 break;
2923 }
2924 }
2925
be0e5c09 2926 if (path->slots[0] == i)
87b29b20 2927 push_space += data_size;
db94535d 2928
227f3cd0 2929 this_item_size = btrfs_item_size_nr(right, i);
db94535d 2930 if (this_item_size + sizeof(*item) + push_space > free_space)
be0e5c09 2931 break;
db94535d 2932
be0e5c09 2933 push_items++;
db94535d
CM
2934 push_space += this_item_size + sizeof(*item);
2935 }
2936
be0e5c09 2937 if (push_items == 0) {
925baedd
CM
2938 ret = 1;
2939 goto out;
be0e5c09 2940 }
fae7f21c 2941 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
5f39d397 2942
be0e5c09 2943 /* push data from right to left */
5f39d397
CM
2944 copy_extent_buffer(left, right,
2945 btrfs_item_nr_offset(btrfs_header_nritems(left)),
2946 btrfs_item_nr_offset(0),
2947 push_items * sizeof(struct btrfs_item));
2948
0b246afa 2949 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
d397712b 2950 btrfs_item_offset_nr(right, push_items - 1);
5f39d397 2951
3d9ec8c4 2952 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
8f881e8c 2953 leaf_data_end(left) - push_space,
3d9ec8c4 2954 BTRFS_LEAF_DATA_OFFSET +
5f39d397 2955 btrfs_item_offset_nr(right, push_items - 1),
d6025579 2956 push_space);
5f39d397 2957 old_left_nritems = btrfs_header_nritems(left);
87b29b20 2958 BUG_ON(old_left_nritems <= 0);
eb60ceac 2959
c82f823c 2960 btrfs_init_map_token(&token, left);
db94535d 2961 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
0783fcfc 2962 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
5f39d397 2963 u32 ioff;
db94535d 2964
dd3cc16b 2965 item = btrfs_item_nr(i);
db94535d 2966
cc4c13d5
DS
2967 ioff = btrfs_token_item_offset(&token, item);
2968 btrfs_set_token_item_offset(&token, item,
2969 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
be0e5c09 2970 }
5f39d397 2971 btrfs_set_header_nritems(left, old_left_nritems + push_items);
be0e5c09
CM
2972
2973 /* fixup right node */
31b1a2bd
JL
2974 if (push_items > right_nritems)
2975 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
d397712b 2976 right_nritems);
34a38218
CM
2977
2978 if (push_items < right_nritems) {
2979 push_space = btrfs_item_offset_nr(right, push_items - 1) -
8f881e8c 2980 leaf_data_end(right);
3d9ec8c4 2981 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
0b246afa 2982 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3d9ec8c4 2983 BTRFS_LEAF_DATA_OFFSET +
8f881e8c 2984 leaf_data_end(right), push_space);
34a38218
CM
2985
2986 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
5f39d397
CM
2987 btrfs_item_nr_offset(push_items),
2988 (btrfs_header_nritems(right) - push_items) *
2989 sizeof(struct btrfs_item));
34a38218 2990 }
c82f823c
DS
2991
2992 btrfs_init_map_token(&token, right);
eef1c494
Y
2993 right_nritems -= push_items;
2994 btrfs_set_header_nritems(right, right_nritems);
0b246afa 2995 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
5f39d397 2996 for (i = 0; i < right_nritems; i++) {
dd3cc16b 2997 item = btrfs_item_nr(i);
db94535d 2998
cc4c13d5
DS
2999 push_space = push_space - btrfs_token_item_size(&token, item);
3000 btrfs_set_token_item_offset(&token, item, push_space);
db94535d 3001 }
eb60ceac 3002
5f39d397 3003 btrfs_mark_buffer_dirty(left);
34a38218
CM
3004 if (right_nritems)
3005 btrfs_mark_buffer_dirty(right);
f0486c68 3006 else
6a884d7d 3007 btrfs_clean_tree_block(right);
098f59c2 3008
5f39d397 3009 btrfs_item_key(right, &disk_key, 0);
b167fa91 3010 fixup_low_keys(path, &disk_key, 1);
be0e5c09
CM
3011
3012 /* then fixup the leaf pointer in the path */
3013 if (path->slots[0] < push_items) {
3014 path->slots[0] += old_left_nritems;
925baedd 3015 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
3016 free_extent_buffer(path->nodes[0]);
3017 path->nodes[0] = left;
be0e5c09
CM
3018 path->slots[1] -= 1;
3019 } else {
925baedd 3020 btrfs_tree_unlock(left);
5f39d397 3021 free_extent_buffer(left);
be0e5c09
CM
3022 path->slots[0] -= push_items;
3023 }
eb60ceac 3024 BUG_ON(path->slots[0] < 0);
aa5d6bed 3025 return ret;
925baedd
CM
3026out:
3027 btrfs_tree_unlock(left);
3028 free_extent_buffer(left);
3029 return ret;
be0e5c09
CM
3030}
3031
44871b1b
CM
3032/*
3033 * push some data in the path leaf to the left, trying to free up at
3034 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
3035 *
3036 * max_slot can put a limit on how far into the leaf we'll push items. The
3037 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3038 * items
44871b1b
CM
3039 */
3040static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
3041 *root, struct btrfs_path *path, int min_data_size,
3042 int data_size, int empty, u32 max_slot)
44871b1b
CM
3043{
3044 struct extent_buffer *right = path->nodes[0];
3045 struct extent_buffer *left;
3046 int slot;
3047 int free_space;
3048 u32 right_nritems;
3049 int ret = 0;
3050
3051 slot = path->slots[1];
3052 if (slot == 0)
3053 return 1;
3054 if (!path->nodes[1])
3055 return 1;
3056
3057 right_nritems = btrfs_header_nritems(right);
3058 if (right_nritems == 0)
3059 return 1;
3060
49d0c642 3061 btrfs_assert_tree_write_locked(path->nodes[1]);
44871b1b 3062
4b231ae4 3063 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
fb770ae4
LB
3064 /*
3065 * slot - 1 is not valid or we fail to read the left node,
3066 * no big deal, just return.
3067 */
3068 if (IS_ERR(left))
91ca338d
TI
3069 return 1;
3070
bf77467a 3071 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
44871b1b 3072
e902baac 3073 free_space = btrfs_leaf_free_space(left);
44871b1b
CM
3074 if (free_space < data_size) {
3075 ret = 1;
3076 goto out;
3077 }
3078
3079 /* cow and double check */
3080 ret = btrfs_cow_block(trans, root, left,
9631e4cc 3081 path->nodes[1], slot - 1, &left,
bf59a5a2 3082 BTRFS_NESTING_LEFT_COW);
44871b1b
CM
3083 if (ret) {
3084 /* we hit -ENOSPC, but it isn't fatal here */
79787eaa
JM
3085 if (ret == -ENOSPC)
3086 ret = 1;
44871b1b
CM
3087 goto out;
3088 }
3089
e902baac 3090 free_space = btrfs_leaf_free_space(left);
44871b1b
CM
3091 if (free_space < data_size) {
3092 ret = 1;
3093 goto out;
3094 }
3095
d16c702f
QW
3096 if (check_sibling_keys(left, right)) {
3097 ret = -EUCLEAN;
3098 goto out;
3099 }
8087c193 3100 return __push_leaf_left(path, min_data_size,
99d8f83c
CM
3101 empty, left, free_space, right_nritems,
3102 max_slot);
44871b1b
CM
3103out:
3104 btrfs_tree_unlock(left);
3105 free_extent_buffer(left);
3106 return ret;
3107}
3108
3109/*
3110 * split the path's leaf in two, making sure there is at least data_size
3111 * available for the resulting leaf level of the path.
44871b1b 3112 */
143bede5 3113static noinline void copy_for_split(struct btrfs_trans_handle *trans,
143bede5
JM
3114 struct btrfs_path *path,
3115 struct extent_buffer *l,
3116 struct extent_buffer *right,
3117 int slot, int mid, int nritems)
44871b1b 3118{
94f94ad9 3119 struct btrfs_fs_info *fs_info = trans->fs_info;
44871b1b
CM
3120 int data_copy_size;
3121 int rt_data_off;
3122 int i;
44871b1b 3123 struct btrfs_disk_key disk_key;
cfed81a0
CM
3124 struct btrfs_map_token token;
3125
44871b1b
CM
3126 nritems = nritems - mid;
3127 btrfs_set_header_nritems(right, nritems);
8f881e8c 3128 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
44871b1b
CM
3129
3130 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
3131 btrfs_item_nr_offset(mid),
3132 nritems * sizeof(struct btrfs_item));
3133
3134 copy_extent_buffer(right, l,
3d9ec8c4
NB
3135 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
3136 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
8f881e8c 3137 leaf_data_end(l), data_copy_size);
44871b1b 3138
0b246afa 3139 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
44871b1b 3140
c82f823c 3141 btrfs_init_map_token(&token, right);
44871b1b 3142 for (i = 0; i < nritems; i++) {
dd3cc16b 3143 struct btrfs_item *item = btrfs_item_nr(i);
44871b1b
CM
3144 u32 ioff;
3145
cc4c13d5
DS
3146 ioff = btrfs_token_item_offset(&token, item);
3147 btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
44871b1b
CM
3148 }
3149
44871b1b 3150 btrfs_set_header_nritems(l, mid);
44871b1b 3151 btrfs_item_key(right, &disk_key, 0);
6ad3cf6d 3152 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
44871b1b
CM
3153
3154 btrfs_mark_buffer_dirty(right);
3155 btrfs_mark_buffer_dirty(l);
3156 BUG_ON(path->slots[0] != slot);
3157
44871b1b
CM
3158 if (mid <= slot) {
3159 btrfs_tree_unlock(path->nodes[0]);
3160 free_extent_buffer(path->nodes[0]);
3161 path->nodes[0] = right;
3162 path->slots[0] -= mid;
3163 path->slots[1] += 1;
3164 } else {
3165 btrfs_tree_unlock(right);
3166 free_extent_buffer(right);
3167 }
3168
3169 BUG_ON(path->slots[0] < 0);
44871b1b
CM
3170}
3171
99d8f83c
CM
3172/*
3173 * double splits happen when we need to insert a big item in the middle
3174 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3175 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3176 * A B C
3177 *
3178 * We avoid this by trying to push the items on either side of our target
3179 * into the adjacent leaves. If all goes well we can avoid the double split
3180 * completely.
3181 */
3182static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3183 struct btrfs_root *root,
3184 struct btrfs_path *path,
3185 int data_size)
3186{
3187 int ret;
3188 int progress = 0;
3189 int slot;
3190 u32 nritems;
5a4267ca 3191 int space_needed = data_size;
99d8f83c
CM
3192
3193 slot = path->slots[0];
5a4267ca 3194 if (slot < btrfs_header_nritems(path->nodes[0]))
e902baac 3195 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
99d8f83c
CM
3196
3197 /*
3198 * try to push all the items after our slot into the
3199 * right leaf
3200 */
5a4267ca 3201 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
99d8f83c
CM
3202 if (ret < 0)
3203 return ret;
3204
3205 if (ret == 0)
3206 progress++;
3207
3208 nritems = btrfs_header_nritems(path->nodes[0]);
3209 /*
3210 * our goal is to get our slot at the start or end of a leaf. If
3211 * we've done so we're done
3212 */
3213 if (path->slots[0] == 0 || path->slots[0] == nritems)
3214 return 0;
3215
e902baac 3216 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
99d8f83c
CM
3217 return 0;
3218
3219 /* try to push all the items before our slot into the next leaf */
3220 slot = path->slots[0];
263d3995
FM
3221 space_needed = data_size;
3222 if (slot > 0)
e902baac 3223 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
5a4267ca 3224 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
99d8f83c
CM
3225 if (ret < 0)
3226 return ret;
3227
3228 if (ret == 0)
3229 progress++;
3230
3231 if (progress)
3232 return 0;
3233 return 1;
3234}
3235
74123bd7
CM
3236/*
3237 * split the path's leaf in two, making sure there is at least data_size
3238 * available for the resulting leaf level of the path.
aa5d6bed
CM
3239 *
3240 * returns 0 if all went well and < 0 on failure.
74123bd7 3241 */
e02119d5
CM
3242static noinline int split_leaf(struct btrfs_trans_handle *trans,
3243 struct btrfs_root *root,
310712b2 3244 const struct btrfs_key *ins_key,
e02119d5
CM
3245 struct btrfs_path *path, int data_size,
3246 int extend)
be0e5c09 3247{
5d4f98a2 3248 struct btrfs_disk_key disk_key;
5f39d397 3249 struct extent_buffer *l;
7518a238 3250 u32 nritems;
eb60ceac
CM
3251 int mid;
3252 int slot;
5f39d397 3253 struct extent_buffer *right;
b7a0365e 3254 struct btrfs_fs_info *fs_info = root->fs_info;
d4dbff95 3255 int ret = 0;
aa5d6bed 3256 int wret;
5d4f98a2 3257 int split;
cc0c5538 3258 int num_doubles = 0;
99d8f83c 3259 int tried_avoid_double = 0;
aa5d6bed 3260
a5719521
YZ
3261 l = path->nodes[0];
3262 slot = path->slots[0];
3263 if (extend && data_size + btrfs_item_size_nr(l, slot) +
0b246afa 3264 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
a5719521
YZ
3265 return -EOVERFLOW;
3266
40689478 3267 /* first try to make some room by pushing left and right */
33157e05 3268 if (data_size && path->nodes[1]) {
5a4267ca
FDBM
3269 int space_needed = data_size;
3270
3271 if (slot < btrfs_header_nritems(l))
e902baac 3272 space_needed -= btrfs_leaf_free_space(l);
5a4267ca
FDBM
3273
3274 wret = push_leaf_right(trans, root, path, space_needed,
3275 space_needed, 0, 0);
d397712b 3276 if (wret < 0)
eaee50e8 3277 return wret;
3685f791 3278 if (wret) {
263d3995
FM
3279 space_needed = data_size;
3280 if (slot > 0)
e902baac 3281 space_needed -= btrfs_leaf_free_space(l);
5a4267ca
FDBM
3282 wret = push_leaf_left(trans, root, path, space_needed,
3283 space_needed, 0, (u32)-1);
3685f791
CM
3284 if (wret < 0)
3285 return wret;
3286 }
3287 l = path->nodes[0];
aa5d6bed 3288
3685f791 3289 /* did the pushes work? */
e902baac 3290 if (btrfs_leaf_free_space(l) >= data_size)
3685f791 3291 return 0;
3326d1b0 3292 }
aa5d6bed 3293
5c680ed6 3294 if (!path->nodes[1]) {
fdd99c72 3295 ret = insert_new_root(trans, root, path, 1);
5c680ed6
CM
3296 if (ret)
3297 return ret;
3298 }
cc0c5538 3299again:
5d4f98a2 3300 split = 1;
cc0c5538 3301 l = path->nodes[0];
eb60ceac 3302 slot = path->slots[0];
5f39d397 3303 nritems = btrfs_header_nritems(l);
d397712b 3304 mid = (nritems + 1) / 2;
54aa1f4d 3305
5d4f98a2
YZ
3306 if (mid <= slot) {
3307 if (nritems == 1 ||
3308 leaf_space_used(l, mid, nritems - mid) + data_size >
0b246afa 3309 BTRFS_LEAF_DATA_SIZE(fs_info)) {
5d4f98a2
YZ
3310 if (slot >= nritems) {
3311 split = 0;
3312 } else {
3313 mid = slot;
3314 if (mid != nritems &&
3315 leaf_space_used(l, mid, nritems - mid) +
0b246afa 3316 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
99d8f83c
CM
3317 if (data_size && !tried_avoid_double)
3318 goto push_for_double;
5d4f98a2
YZ
3319 split = 2;
3320 }
3321 }
3322 }
3323 } else {
3324 if (leaf_space_used(l, 0, mid) + data_size >
0b246afa 3325 BTRFS_LEAF_DATA_SIZE(fs_info)) {
5d4f98a2
YZ
3326 if (!extend && data_size && slot == 0) {
3327 split = 0;
3328 } else if ((extend || !data_size) && slot == 0) {
3329 mid = 1;
3330 } else {
3331 mid = slot;
3332 if (mid != nritems &&
3333 leaf_space_used(l, mid, nritems - mid) +
0b246afa 3334 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
99d8f83c
CM
3335 if (data_size && !tried_avoid_double)
3336 goto push_for_double;
67871254 3337 split = 2;
5d4f98a2
YZ
3338 }
3339 }
3340 }
3341 }
3342
3343 if (split == 0)
3344 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3345 else
3346 btrfs_item_key(l, &disk_key, mid);
3347
ca9d473a
JB
3348 /*
3349 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3350 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3351 * subclasses, which is 8 at the time of this patch, and we've maxed it
3352 * out. In the future we could add a
3353 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3354 * use BTRFS_NESTING_NEW_ROOT.
3355 */
79bd3712
FM
3356 right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3357 &disk_key, 0, l->start, 0,
3358 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3359 BTRFS_NESTING_SPLIT);
f0486c68 3360 if (IS_ERR(right))
5f39d397 3361 return PTR_ERR(right);
f0486c68 3362
0b246afa 3363 root_add_used(root, fs_info->nodesize);
5f39d397 3364
5d4f98a2
YZ
3365 if (split == 0) {
3366 if (mid <= slot) {
3367 btrfs_set_header_nritems(right, 0);
6ad3cf6d 3368 insert_ptr(trans, path, &disk_key,
2ff7e61e 3369 right->start, path->slots[1] + 1, 1);
5d4f98a2
YZ
3370 btrfs_tree_unlock(path->nodes[0]);
3371 free_extent_buffer(path->nodes[0]);
3372 path->nodes[0] = right;
3373 path->slots[0] = 0;
3374 path->slots[1] += 1;
3375 } else {
3376 btrfs_set_header_nritems(right, 0);
6ad3cf6d 3377 insert_ptr(trans, path, &disk_key,
2ff7e61e 3378 right->start, path->slots[1], 1);
5d4f98a2
YZ
3379 btrfs_tree_unlock(path->nodes[0]);
3380 free_extent_buffer(path->nodes[0]);
3381 path->nodes[0] = right;
3382 path->slots[0] = 0;
143bede5 3383 if (path->slots[1] == 0)
b167fa91 3384 fixup_low_keys(path, &disk_key, 1);
d4dbff95 3385 }
196e0249
LB
3386 /*
3387 * We create a new leaf 'right' for the required ins_len and
3388 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3389 * the content of ins_len to 'right'.
3390 */
5d4f98a2 3391 return ret;
d4dbff95 3392 }
74123bd7 3393
94f94ad9 3394 copy_for_split(trans, path, l, right, slot, mid, nritems);
31840ae1 3395
5d4f98a2 3396 if (split == 2) {
cc0c5538
CM
3397 BUG_ON(num_doubles != 0);
3398 num_doubles++;
3399 goto again;
a429e513 3400 }
44871b1b 3401
143bede5 3402 return 0;
99d8f83c
CM
3403
3404push_for_double:
3405 push_for_double_split(trans, root, path, data_size);
3406 tried_avoid_double = 1;
e902baac 3407 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
99d8f83c
CM
3408 return 0;
3409 goto again;
be0e5c09
CM
3410}
3411
ad48fd75
YZ
3412static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3413 struct btrfs_root *root,
3414 struct btrfs_path *path, int ins_len)
459931ec 3415{
ad48fd75 3416 struct btrfs_key key;
459931ec 3417 struct extent_buffer *leaf;
ad48fd75
YZ
3418 struct btrfs_file_extent_item *fi;
3419 u64 extent_len = 0;
3420 u32 item_size;
3421 int ret;
459931ec
CM
3422
3423 leaf = path->nodes[0];
ad48fd75
YZ
3424 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3425
3426 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3427 key.type != BTRFS_EXTENT_CSUM_KEY);
3428
e902baac 3429 if (btrfs_leaf_free_space(leaf) >= ins_len)
ad48fd75 3430 return 0;
459931ec
CM
3431
3432 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
ad48fd75
YZ
3433 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3434 fi = btrfs_item_ptr(leaf, path->slots[0],
3435 struct btrfs_file_extent_item);
3436 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3437 }
b3b4aa74 3438 btrfs_release_path(path);
459931ec 3439
459931ec 3440 path->keep_locks = 1;
ad48fd75
YZ
3441 path->search_for_split = 1;
3442 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
459931ec 3443 path->search_for_split = 0;
a8df6fe6
FM
3444 if (ret > 0)
3445 ret = -EAGAIN;
ad48fd75
YZ
3446 if (ret < 0)
3447 goto err;
459931ec 3448
ad48fd75
YZ
3449 ret = -EAGAIN;
3450 leaf = path->nodes[0];
a8df6fe6
FM
3451 /* if our item isn't there, return now */
3452 if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
ad48fd75
YZ
3453 goto err;
3454
109f6aef 3455 /* the leaf has changed, it now has room. return now */
e902baac 3456 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
109f6aef
CM
3457 goto err;
3458
ad48fd75
YZ
3459 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3460 fi = btrfs_item_ptr(leaf, path->slots[0],
3461 struct btrfs_file_extent_item);
3462 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3463 goto err;
459931ec
CM
3464 }
3465
ad48fd75 3466 ret = split_leaf(trans, root, &key, path, ins_len, 1);
f0486c68
YZ
3467 if (ret)
3468 goto err;
459931ec 3469
ad48fd75 3470 path->keep_locks = 0;
b9473439 3471 btrfs_unlock_up_safe(path, 1);
ad48fd75
YZ
3472 return 0;
3473err:
3474 path->keep_locks = 0;
3475 return ret;
3476}
3477
25263cd7 3478static noinline int split_item(struct btrfs_path *path,
310712b2 3479 const struct btrfs_key *new_key,
ad48fd75
YZ
3480 unsigned long split_offset)
3481{
3482 struct extent_buffer *leaf;
3483 struct btrfs_item *item;
3484 struct btrfs_item *new_item;
3485 int slot;
3486 char *buf;
3487 u32 nritems;
3488 u32 item_size;
3489 u32 orig_offset;
3490 struct btrfs_disk_key disk_key;
3491
b9473439 3492 leaf = path->nodes[0];
e902baac 3493 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
b9473439 3494
dd3cc16b 3495 item = btrfs_item_nr(path->slots[0]);
227f3cd0
JB
3496 orig_offset = btrfs_item_offset_nr(leaf, path->slots[0]);
3497 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
459931ec 3498
459931ec 3499 buf = kmalloc(item_size, GFP_NOFS);
ad48fd75
YZ
3500 if (!buf)
3501 return -ENOMEM;
3502
459931ec
CM
3503 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3504 path->slots[0]), item_size);
459931ec 3505
ad48fd75 3506 slot = path->slots[0] + 1;
459931ec 3507 nritems = btrfs_header_nritems(leaf);
459931ec
CM
3508 if (slot != nritems) {
3509 /* shift the items */
3510 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
ad48fd75
YZ
3511 btrfs_item_nr_offset(slot),
3512 (nritems - slot) * sizeof(struct btrfs_item));
459931ec
CM
3513 }
3514
3515 btrfs_cpu_key_to_disk(&disk_key, new_key);
3516 btrfs_set_item_key(leaf, &disk_key, slot);
3517
dd3cc16b 3518 new_item = btrfs_item_nr(slot);
459931ec
CM
3519
3520 btrfs_set_item_offset(leaf, new_item, orig_offset);
3521 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3522
3523 btrfs_set_item_offset(leaf, item,
3524 orig_offset + item_size - split_offset);
3525 btrfs_set_item_size(leaf, item, split_offset);
3526
3527 btrfs_set_header_nritems(leaf, nritems + 1);
3528
3529 /* write the data for the start of the original item */
3530 write_extent_buffer(leaf, buf,
3531 btrfs_item_ptr_offset(leaf, path->slots[0]),
3532 split_offset);
3533
3534 /* write the data for the new item */
3535 write_extent_buffer(leaf, buf + split_offset,
3536 btrfs_item_ptr_offset(leaf, slot),
3537 item_size - split_offset);
3538 btrfs_mark_buffer_dirty(leaf);
3539
e902baac 3540 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
459931ec 3541 kfree(buf);
ad48fd75
YZ
3542 return 0;
3543}
3544
3545/*
3546 * This function splits a single item into two items,
3547 * giving 'new_key' to the new item and splitting the
3548 * old one at split_offset (from the start of the item).
3549 *
3550 * The path may be released by this operation. After
3551 * the split, the path is pointing to the old item. The
3552 * new item is going to be in the same node as the old one.
3553 *
3554 * Note, the item being split must be smaller enough to live alone on
3555 * a tree block with room for one extra struct btrfs_item
3556 *
3557 * This allows us to split the item in place, keeping a lock on the
3558 * leaf the entire time.
3559 */
3560int btrfs_split_item(struct btrfs_trans_handle *trans,
3561 struct btrfs_root *root,
3562 struct btrfs_path *path,
310712b2 3563 const struct btrfs_key *new_key,
ad48fd75
YZ
3564 unsigned long split_offset)
3565{
3566 int ret;
3567 ret = setup_leaf_for_split(trans, root, path,
3568 sizeof(struct btrfs_item));
3569 if (ret)
3570 return ret;
3571
25263cd7 3572 ret = split_item(path, new_key, split_offset);
459931ec
CM
3573 return ret;
3574}
3575
d352ac68
CM
3576/*
3577 * make the item pointed to by the path smaller. new_size indicates
3578 * how small to make it, and from_end tells us if we just chop bytes
3579 * off the end of the item or if we shift the item to chop bytes off
3580 * the front.
3581 */
78ac4f9e 3582void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
b18c6685 3583{
b18c6685 3584 int slot;
5f39d397
CM
3585 struct extent_buffer *leaf;
3586 struct btrfs_item *item;
b18c6685
CM
3587 u32 nritems;
3588 unsigned int data_end;
3589 unsigned int old_data_start;
3590 unsigned int old_size;
3591 unsigned int size_diff;
3592 int i;
cfed81a0
CM
3593 struct btrfs_map_token token;
3594
5f39d397 3595 leaf = path->nodes[0];
179e29e4
CM
3596 slot = path->slots[0];
3597
3598 old_size = btrfs_item_size_nr(leaf, slot);
3599 if (old_size == new_size)
143bede5 3600 return;
b18c6685 3601
5f39d397 3602 nritems = btrfs_header_nritems(leaf);
8f881e8c 3603 data_end = leaf_data_end(leaf);
b18c6685 3604
5f39d397 3605 old_data_start = btrfs_item_offset_nr(leaf, slot);
179e29e4 3606
b18c6685
CM
3607 size_diff = old_size - new_size;
3608
3609 BUG_ON(slot < 0);
3610 BUG_ON(slot >= nritems);
3611
3612 /*
3613 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3614 */
3615 /* first correct the data pointers */
c82f823c 3616 btrfs_init_map_token(&token, leaf);
b18c6685 3617 for (i = slot; i < nritems; i++) {
5f39d397 3618 u32 ioff;
dd3cc16b 3619 item = btrfs_item_nr(i);
db94535d 3620
cc4c13d5
DS
3621 ioff = btrfs_token_item_offset(&token, item);
3622 btrfs_set_token_item_offset(&token, item, ioff + size_diff);
b18c6685 3623 }
db94535d 3624
b18c6685 3625 /* shift the data */
179e29e4 3626 if (from_end) {
3d9ec8c4
NB
3627 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3628 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
179e29e4
CM
3629 data_end, old_data_start + new_size - data_end);
3630 } else {
3631 struct btrfs_disk_key disk_key;
3632 u64 offset;
3633
3634 btrfs_item_key(leaf, &disk_key, slot);
3635
3636 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3637 unsigned long ptr;
3638 struct btrfs_file_extent_item *fi;
3639
3640 fi = btrfs_item_ptr(leaf, slot,
3641 struct btrfs_file_extent_item);
3642 fi = (struct btrfs_file_extent_item *)(
3643 (unsigned long)fi - size_diff);
3644
3645 if (btrfs_file_extent_type(leaf, fi) ==
3646 BTRFS_FILE_EXTENT_INLINE) {
3647 ptr = btrfs_item_ptr_offset(leaf, slot);
3648 memmove_extent_buffer(leaf, ptr,
d397712b 3649 (unsigned long)fi,
7ec20afb 3650 BTRFS_FILE_EXTENT_INLINE_DATA_START);
179e29e4
CM
3651 }
3652 }
3653
3d9ec8c4
NB
3654 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3655 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
179e29e4
CM
3656 data_end, old_data_start - data_end);
3657
3658 offset = btrfs_disk_key_offset(&disk_key);
3659 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3660 btrfs_set_item_key(leaf, &disk_key, slot);
3661 if (slot == 0)
b167fa91 3662 fixup_low_keys(path, &disk_key, 1);
179e29e4 3663 }
5f39d397 3664
dd3cc16b 3665 item = btrfs_item_nr(slot);
5f39d397
CM
3666 btrfs_set_item_size(leaf, item, new_size);
3667 btrfs_mark_buffer_dirty(leaf);
b18c6685 3668
e902baac 3669 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 3670 btrfs_print_leaf(leaf);
b18c6685 3671 BUG();
5f39d397 3672 }
b18c6685
CM
3673}
3674
d352ac68 3675/*
8f69dbd2 3676 * make the item pointed to by the path bigger, data_size is the added size.
d352ac68 3677 */
c71dd880 3678void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
6567e837 3679{
6567e837 3680 int slot;
5f39d397
CM
3681 struct extent_buffer *leaf;
3682 struct btrfs_item *item;
6567e837
CM
3683 u32 nritems;
3684 unsigned int data_end;
3685 unsigned int old_data;
3686 unsigned int old_size;
3687 int i;
cfed81a0
CM
3688 struct btrfs_map_token token;
3689
5f39d397 3690 leaf = path->nodes[0];
6567e837 3691
5f39d397 3692 nritems = btrfs_header_nritems(leaf);
8f881e8c 3693 data_end = leaf_data_end(leaf);
6567e837 3694
e902baac 3695 if (btrfs_leaf_free_space(leaf) < data_size) {
a4f78750 3696 btrfs_print_leaf(leaf);
6567e837 3697 BUG();
5f39d397 3698 }
6567e837 3699 slot = path->slots[0];
5f39d397 3700 old_data = btrfs_item_end_nr(leaf, slot);
6567e837
CM
3701
3702 BUG_ON(slot < 0);
3326d1b0 3703 if (slot >= nritems) {
a4f78750 3704 btrfs_print_leaf(leaf);
c71dd880 3705 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
0b246afa 3706 slot, nritems);
290342f6 3707 BUG();
3326d1b0 3708 }
6567e837
CM
3709
3710 /*
3711 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3712 */
3713 /* first correct the data pointers */
c82f823c 3714 btrfs_init_map_token(&token, leaf);
6567e837 3715 for (i = slot; i < nritems; i++) {
5f39d397 3716 u32 ioff;
dd3cc16b 3717 item = btrfs_item_nr(i);
db94535d 3718
cc4c13d5
DS
3719 ioff = btrfs_token_item_offset(&token, item);
3720 btrfs_set_token_item_offset(&token, item, ioff - data_size);
6567e837 3721 }
5f39d397 3722
6567e837 3723 /* shift the data */
3d9ec8c4
NB
3724 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3725 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
6567e837 3726 data_end, old_data - data_end);
5f39d397 3727
6567e837 3728 data_end = old_data;
5f39d397 3729 old_size = btrfs_item_size_nr(leaf, slot);
dd3cc16b 3730 item = btrfs_item_nr(slot);
5f39d397
CM
3731 btrfs_set_item_size(leaf, item, old_size + data_size);
3732 btrfs_mark_buffer_dirty(leaf);
6567e837 3733
e902baac 3734 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 3735 btrfs_print_leaf(leaf);
6567e837 3736 BUG();
5f39d397 3737 }
6567e837
CM
3738}
3739
da9ffb24
NB
3740/**
3741 * setup_items_for_insert - Helper called before inserting one or more items
3742 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3743 * in a function that doesn't call btrfs_search_slot
3744 *
3745 * @root: root we are inserting items to
3746 * @path: points to the leaf/slot where we are going to insert new items
b7ef5f3a 3747 * @batch: information about the batch of items to insert
74123bd7 3748 */
f0641656
FM
3749static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3750 const struct btrfs_item_batch *batch)
be0e5c09 3751{
0b246afa 3752 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397 3753 struct btrfs_item *item;
9c58309d 3754 int i;
7518a238 3755 u32 nritems;
be0e5c09 3756 unsigned int data_end;
e2fa7227 3757 struct btrfs_disk_key disk_key;
44871b1b
CM
3758 struct extent_buffer *leaf;
3759 int slot;
cfed81a0 3760 struct btrfs_map_token token;
fc0d82e1 3761 u32 total_size;
cfed81a0 3762
b7ef5f3a
FM
3763 /*
3764 * Before anything else, update keys in the parent and other ancestors
3765 * if needed, then release the write locks on them, so that other tasks
3766 * can use them while we modify the leaf.
3767 */
24cdc847 3768 if (path->slots[0] == 0) {
b7ef5f3a 3769 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
b167fa91 3770 fixup_low_keys(path, &disk_key, 1);
24cdc847
FM
3771 }
3772 btrfs_unlock_up_safe(path, 1);
3773
5f39d397 3774 leaf = path->nodes[0];
44871b1b 3775 slot = path->slots[0];
74123bd7 3776
5f39d397 3777 nritems = btrfs_header_nritems(leaf);
8f881e8c 3778 data_end = leaf_data_end(leaf);
b7ef5f3a 3779 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
eb60ceac 3780
e902baac 3781 if (btrfs_leaf_free_space(leaf) < total_size) {
a4f78750 3782 btrfs_print_leaf(leaf);
0b246afa 3783 btrfs_crit(fs_info, "not enough freespace need %u have %d",
e902baac 3784 total_size, btrfs_leaf_free_space(leaf));
be0e5c09 3785 BUG();
d4dbff95 3786 }
5f39d397 3787
c82f823c 3788 btrfs_init_map_token(&token, leaf);
be0e5c09 3789 if (slot != nritems) {
5f39d397 3790 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
be0e5c09 3791
5f39d397 3792 if (old_data < data_end) {
a4f78750 3793 btrfs_print_leaf(leaf);
7269ddd2
NB
3794 btrfs_crit(fs_info,
3795 "item at slot %d with data offset %u beyond data end of leaf %u",
5d163e0e 3796 slot, old_data, data_end);
290342f6 3797 BUG();
5f39d397 3798 }
be0e5c09
CM
3799 /*
3800 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3801 */
3802 /* first correct the data pointers */
0783fcfc 3803 for (i = slot; i < nritems; i++) {
5f39d397 3804 u32 ioff;
db94535d 3805
62e85577 3806 item = btrfs_item_nr(i);
cc4c13d5
DS
3807 ioff = btrfs_token_item_offset(&token, item);
3808 btrfs_set_token_item_offset(&token, item,
b7ef5f3a 3809 ioff - batch->total_data_size);
0783fcfc 3810 }
be0e5c09 3811 /* shift the items */
b7ef5f3a 3812 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
5f39d397 3813 btrfs_item_nr_offset(slot),
d6025579 3814 (nritems - slot) * sizeof(struct btrfs_item));
be0e5c09
CM
3815
3816 /* shift the data */
3d9ec8c4 3817 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
b7ef5f3a
FM
3818 data_end - batch->total_data_size,
3819 BTRFS_LEAF_DATA_OFFSET + data_end,
3820 old_data - data_end);
be0e5c09
CM
3821 data_end = old_data;
3822 }
5f39d397 3823
62e2749e 3824 /* setup the item for the new data */
b7ef5f3a
FM
3825 for (i = 0; i < batch->nr; i++) {
3826 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
9c58309d 3827 btrfs_set_item_key(leaf, &disk_key, slot + i);
dd3cc16b 3828 item = btrfs_item_nr(slot + i);
b7ef5f3a 3829 data_end -= batch->data_sizes[i];
fc0716c2 3830 btrfs_set_token_item_offset(&token, item, data_end);
b7ef5f3a 3831 btrfs_set_token_item_size(&token, item, batch->data_sizes[i]);
9c58309d 3832 }
44871b1b 3833
b7ef5f3a 3834 btrfs_set_header_nritems(leaf, nritems + batch->nr);
b9473439 3835 btrfs_mark_buffer_dirty(leaf);
aa5d6bed 3836
e902baac 3837 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 3838 btrfs_print_leaf(leaf);
be0e5c09 3839 BUG();
5f39d397 3840 }
44871b1b
CM
3841}
3842
f0641656
FM
3843/*
3844 * Insert a new item into a leaf.
3845 *
3846 * @root: The root of the btree.
3847 * @path: A path pointing to the target leaf and slot.
3848 * @key: The key of the new item.
3849 * @data_size: The size of the data associated with the new key.
3850 */
3851void btrfs_setup_item_for_insert(struct btrfs_root *root,
3852 struct btrfs_path *path,
3853 const struct btrfs_key *key,
3854 u32 data_size)
3855{
3856 struct btrfs_item_batch batch;
3857
3858 batch.keys = key;
3859 batch.data_sizes = &data_size;
3860 batch.total_data_size = data_size;
3861 batch.nr = 1;
3862
3863 setup_items_for_insert(root, path, &batch);
3864}
3865
44871b1b
CM
3866/*
3867 * Given a key and some data, insert items into the tree.
3868 * This does all the path init required, making room in the tree if needed.
3869 */
3870int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
3871 struct btrfs_root *root,
3872 struct btrfs_path *path,
b7ef5f3a 3873 const struct btrfs_item_batch *batch)
44871b1b 3874{
44871b1b
CM
3875 int ret = 0;
3876 int slot;
b7ef5f3a 3877 u32 total_size;
44871b1b 3878
b7ef5f3a
FM
3879 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
3880 ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
44871b1b
CM
3881 if (ret == 0)
3882 return -EEXIST;
3883 if (ret < 0)
143bede5 3884 return ret;
44871b1b 3885
44871b1b
CM
3886 slot = path->slots[0];
3887 BUG_ON(slot < 0);
3888
b7ef5f3a 3889 setup_items_for_insert(root, path, batch);
143bede5 3890 return 0;
62e2749e
CM
3891}
3892
3893/*
3894 * Given a key and some data, insert an item into the tree.
3895 * This does all the path init required, making room in the tree if needed.
3896 */
310712b2
OS
3897int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3898 const struct btrfs_key *cpu_key, void *data,
3899 u32 data_size)
62e2749e
CM
3900{
3901 int ret = 0;
2c90e5d6 3902 struct btrfs_path *path;
5f39d397
CM
3903 struct extent_buffer *leaf;
3904 unsigned long ptr;
62e2749e 3905
2c90e5d6 3906 path = btrfs_alloc_path();
db5b493a
TI
3907 if (!path)
3908 return -ENOMEM;
2c90e5d6 3909 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
62e2749e 3910 if (!ret) {
5f39d397
CM
3911 leaf = path->nodes[0];
3912 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3913 write_extent_buffer(leaf, data, ptr, data_size);
3914 btrfs_mark_buffer_dirty(leaf);
62e2749e 3915 }
2c90e5d6 3916 btrfs_free_path(path);
aa5d6bed 3917 return ret;
be0e5c09
CM
3918}
3919
f0641656
FM
3920/*
3921 * This function duplicates an item, giving 'new_key' to the new item.
3922 * It guarantees both items live in the same tree leaf and the new item is
3923 * contiguous with the original item.
3924 *
3925 * This allows us to split a file extent in place, keeping a lock on the leaf
3926 * the entire time.
3927 */
3928int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
3929 struct btrfs_root *root,
3930 struct btrfs_path *path,
3931 const struct btrfs_key *new_key)
3932{
3933 struct extent_buffer *leaf;
3934 int ret;
3935 u32 item_size;
3936
3937 leaf = path->nodes[0];
3938 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3939 ret = setup_leaf_for_split(trans, root, path,
3940 item_size + sizeof(struct btrfs_item));
3941 if (ret)
3942 return ret;
3943
3944 path->slots[0]++;
3945 btrfs_setup_item_for_insert(root, path, new_key, item_size);
3946 leaf = path->nodes[0];
3947 memcpy_extent_buffer(leaf,
3948 btrfs_item_ptr_offset(leaf, path->slots[0]),
3949 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
3950 item_size);
3951 return 0;
3952}
3953
74123bd7 3954/*
5de08d7d 3955 * delete the pointer from a given node.
74123bd7 3956 *
d352ac68
CM
3957 * the tree should have been previously balanced so the deletion does not
3958 * empty a node.
74123bd7 3959 */
afe5fea7
TI
3960static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
3961 int level, int slot)
be0e5c09 3962{
5f39d397 3963 struct extent_buffer *parent = path->nodes[level];
7518a238 3964 u32 nritems;
f3ea38da 3965 int ret;
be0e5c09 3966
5f39d397 3967 nritems = btrfs_header_nritems(parent);
d397712b 3968 if (slot != nritems - 1) {
bf1d3425 3969 if (level) {
f3a84ccd
FM
3970 ret = btrfs_tree_mod_log_insert_move(parent, slot,
3971 slot + 1, nritems - slot - 1);
bf1d3425
DS
3972 BUG_ON(ret < 0);
3973 }
5f39d397
CM
3974 memmove_extent_buffer(parent,
3975 btrfs_node_key_ptr_offset(slot),
3976 btrfs_node_key_ptr_offset(slot + 1),
d6025579
CM
3977 sizeof(struct btrfs_key_ptr) *
3978 (nritems - slot - 1));
57ba86c0 3979 } else if (level) {
f3a84ccd
FM
3980 ret = btrfs_tree_mod_log_insert_key(parent, slot,
3981 BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
57ba86c0 3982 BUG_ON(ret < 0);
bb803951 3983 }
f3ea38da 3984
7518a238 3985 nritems--;
5f39d397 3986 btrfs_set_header_nritems(parent, nritems);
7518a238 3987 if (nritems == 0 && parent == root->node) {
5f39d397 3988 BUG_ON(btrfs_header_level(root->node) != 1);
bb803951 3989 /* just turn the root into a leaf and break */
5f39d397 3990 btrfs_set_header_level(root->node, 0);
bb803951 3991 } else if (slot == 0) {
5f39d397
CM
3992 struct btrfs_disk_key disk_key;
3993
3994 btrfs_node_key(parent, &disk_key, 0);
b167fa91 3995 fixup_low_keys(path, &disk_key, level + 1);
be0e5c09 3996 }
d6025579 3997 btrfs_mark_buffer_dirty(parent);
be0e5c09
CM
3998}
3999
323ac95b
CM
4000/*
4001 * a helper function to delete the leaf pointed to by path->slots[1] and
5d4f98a2 4002 * path->nodes[1].
323ac95b
CM
4003 *
4004 * This deletes the pointer in path->nodes[1] and frees the leaf
4005 * block extent. zero is returned if it all worked out, < 0 otherwise.
4006 *
4007 * The path must have already been setup for deleting the leaf, including
4008 * all the proper balancing. path->nodes[1] must be locked.
4009 */
143bede5
JM
4010static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4011 struct btrfs_root *root,
4012 struct btrfs_path *path,
4013 struct extent_buffer *leaf)
323ac95b 4014{
5d4f98a2 4015 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
afe5fea7 4016 del_ptr(root, path, 1, path->slots[1]);
323ac95b 4017
4d081c41
CM
4018 /*
4019 * btrfs_free_extent is expensive, we want to make sure we
4020 * aren't holding any locks when we call it
4021 */
4022 btrfs_unlock_up_safe(path, 0);
4023
f0486c68
YZ
4024 root_sub_used(root, leaf->len);
4025
67439dad 4026 atomic_inc(&leaf->refs);
7a163608 4027 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
3083ee2e 4028 free_extent_buffer_stale(leaf);
323ac95b 4029}
74123bd7
CM
4030/*
4031 * delete the item at the leaf level in path. If that empties
4032 * the leaf, remove it from the tree
4033 */
85e21bac
CM
4034int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4035 struct btrfs_path *path, int slot, int nr)
be0e5c09 4036{
0b246afa 4037 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
4038 struct extent_buffer *leaf;
4039 struct btrfs_item *item;
ce0eac2a
AM
4040 u32 last_off;
4041 u32 dsize = 0;
aa5d6bed
CM
4042 int ret = 0;
4043 int wret;
85e21bac 4044 int i;
7518a238 4045 u32 nritems;
be0e5c09 4046
5f39d397 4047 leaf = path->nodes[0];
85e21bac
CM
4048 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4049
4050 for (i = 0; i < nr; i++)
4051 dsize += btrfs_item_size_nr(leaf, slot + i);
4052
5f39d397 4053 nritems = btrfs_header_nritems(leaf);
be0e5c09 4054
85e21bac 4055 if (slot + nr != nritems) {
8f881e8c 4056 int data_end = leaf_data_end(leaf);
c82f823c 4057 struct btrfs_map_token token;
5f39d397 4058
3d9ec8c4 4059 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
d6025579 4060 data_end + dsize,
3d9ec8c4 4061 BTRFS_LEAF_DATA_OFFSET + data_end,
85e21bac 4062 last_off - data_end);
5f39d397 4063
c82f823c 4064 btrfs_init_map_token(&token, leaf);
85e21bac 4065 for (i = slot + nr; i < nritems; i++) {
5f39d397 4066 u32 ioff;
db94535d 4067
dd3cc16b 4068 item = btrfs_item_nr(i);
cc4c13d5
DS
4069 ioff = btrfs_token_item_offset(&token, item);
4070 btrfs_set_token_item_offset(&token, item, ioff + dsize);
0783fcfc 4071 }
db94535d 4072
5f39d397 4073 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
85e21bac 4074 btrfs_item_nr_offset(slot + nr),
d6025579 4075 sizeof(struct btrfs_item) *
85e21bac 4076 (nritems - slot - nr));
be0e5c09 4077 }
85e21bac
CM
4078 btrfs_set_header_nritems(leaf, nritems - nr);
4079 nritems -= nr;
5f39d397 4080
74123bd7 4081 /* delete the leaf if we've emptied it */
7518a238 4082 if (nritems == 0) {
5f39d397
CM
4083 if (leaf == root->node) {
4084 btrfs_set_header_level(leaf, 0);
9a8dd150 4085 } else {
6a884d7d 4086 btrfs_clean_tree_block(leaf);
143bede5 4087 btrfs_del_leaf(trans, root, path, leaf);
9a8dd150 4088 }
be0e5c09 4089 } else {
7518a238 4090 int used = leaf_space_used(leaf, 0, nritems);
aa5d6bed 4091 if (slot == 0) {
5f39d397
CM
4092 struct btrfs_disk_key disk_key;
4093
4094 btrfs_item_key(leaf, &disk_key, 0);
b167fa91 4095 fixup_low_keys(path, &disk_key, 1);
aa5d6bed 4096 }
aa5d6bed 4097
74123bd7 4098 /* delete the leaf if it is mostly empty */
0b246afa 4099 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
be0e5c09
CM
4100 /* push_leaf_left fixes the path.
4101 * make sure the path still points to our leaf
4102 * for possible call to del_ptr below
4103 */
4920c9ac 4104 slot = path->slots[1];
67439dad 4105 atomic_inc(&leaf->refs);
5f39d397 4106
99d8f83c
CM
4107 wret = push_leaf_left(trans, root, path, 1, 1,
4108 1, (u32)-1);
54aa1f4d 4109 if (wret < 0 && wret != -ENOSPC)
aa5d6bed 4110 ret = wret;
5f39d397
CM
4111
4112 if (path->nodes[0] == leaf &&
4113 btrfs_header_nritems(leaf)) {
99d8f83c
CM
4114 wret = push_leaf_right(trans, root, path, 1,
4115 1, 1, 0);
54aa1f4d 4116 if (wret < 0 && wret != -ENOSPC)
aa5d6bed
CM
4117 ret = wret;
4118 }
5f39d397
CM
4119
4120 if (btrfs_header_nritems(leaf) == 0) {
323ac95b 4121 path->slots[1] = slot;
143bede5 4122 btrfs_del_leaf(trans, root, path, leaf);
5f39d397 4123 free_extent_buffer(leaf);
143bede5 4124 ret = 0;
5de08d7d 4125 } else {
925baedd
CM
4126 /* if we're still in the path, make sure
4127 * we're dirty. Otherwise, one of the
4128 * push_leaf functions must have already
4129 * dirtied this buffer
4130 */
4131 if (path->nodes[0] == leaf)
4132 btrfs_mark_buffer_dirty(leaf);
5f39d397 4133 free_extent_buffer(leaf);
be0e5c09 4134 }
d5719762 4135 } else {
5f39d397 4136 btrfs_mark_buffer_dirty(leaf);
be0e5c09
CM
4137 }
4138 }
aa5d6bed 4139 return ret;
be0e5c09
CM
4140}
4141
7bb86316 4142/*
925baedd 4143 * search the tree again to find a leaf with lesser keys
7bb86316
CM
4144 * returns 0 if it found something or 1 if there are no lesser leaves.
4145 * returns < 0 on io errors.
d352ac68
CM
4146 *
4147 * This may release the path, and so you may lose any locks held at the
4148 * time you call it.
7bb86316 4149 */
16e7549f 4150int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
7bb86316 4151{
925baedd
CM
4152 struct btrfs_key key;
4153 struct btrfs_disk_key found_key;
4154 int ret;
7bb86316 4155
925baedd 4156 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
7bb86316 4157
e8b0d724 4158 if (key.offset > 0) {
925baedd 4159 key.offset--;
e8b0d724 4160 } else if (key.type > 0) {
925baedd 4161 key.type--;
e8b0d724
FDBM
4162 key.offset = (u64)-1;
4163 } else if (key.objectid > 0) {
925baedd 4164 key.objectid--;
e8b0d724
FDBM
4165 key.type = (u8)-1;
4166 key.offset = (u64)-1;
4167 } else {
925baedd 4168 return 1;
e8b0d724 4169 }
7bb86316 4170
b3b4aa74 4171 btrfs_release_path(path);
925baedd
CM
4172 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4173 if (ret < 0)
4174 return ret;
4175 btrfs_item_key(path->nodes[0], &found_key, 0);
4176 ret = comp_keys(&found_key, &key);
337c6f68
FM
4177 /*
4178 * We might have had an item with the previous key in the tree right
4179 * before we released our path. And after we released our path, that
4180 * item might have been pushed to the first slot (0) of the leaf we
4181 * were holding due to a tree balance. Alternatively, an item with the
4182 * previous key can exist as the only element of a leaf (big fat item).
4183 * Therefore account for these 2 cases, so that our callers (like
4184 * btrfs_previous_item) don't miss an existing item with a key matching
4185 * the previous key we computed above.
4186 */
4187 if (ret <= 0)
925baedd
CM
4188 return 0;
4189 return 1;
7bb86316
CM
4190}
4191
3f157a2f
CM
4192/*
4193 * A helper function to walk down the tree starting at min_key, and looking
de78b51a
ES
4194 * for nodes or leaves that are have a minimum transaction id.
4195 * This is used by the btree defrag code, and tree logging
3f157a2f
CM
4196 *
4197 * This does not cow, but it does stuff the starting key it finds back
4198 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4199 * key and get a writable path.
4200 *
3f157a2f
CM
4201 * This honors path->lowest_level to prevent descent past a given level
4202 * of the tree.
4203 *
d352ac68
CM
4204 * min_trans indicates the oldest transaction that you are interested
4205 * in walking through. Any nodes or leaves older than min_trans are
4206 * skipped over (without reading them).
4207 *
3f157a2f
CM
4208 * returns zero if something useful was found, < 0 on error and 1 if there
4209 * was nothing in the tree that matched the search criteria.
4210 */
4211int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
de78b51a 4212 struct btrfs_path *path,
3f157a2f
CM
4213 u64 min_trans)
4214{
4215 struct extent_buffer *cur;
4216 struct btrfs_key found_key;
4217 int slot;
9652480b 4218 int sret;
3f157a2f
CM
4219 u32 nritems;
4220 int level;
4221 int ret = 1;
f98de9b9 4222 int keep_locks = path->keep_locks;
3f157a2f 4223
f98de9b9 4224 path->keep_locks = 1;
3f157a2f 4225again:
bd681513 4226 cur = btrfs_read_lock_root_node(root);
3f157a2f 4227 level = btrfs_header_level(cur);
e02119d5 4228 WARN_ON(path->nodes[level]);
3f157a2f 4229 path->nodes[level] = cur;
bd681513 4230 path->locks[level] = BTRFS_READ_LOCK;
3f157a2f
CM
4231
4232 if (btrfs_header_generation(cur) < min_trans) {
4233 ret = 1;
4234 goto out;
4235 }
d397712b 4236 while (1) {
3f157a2f
CM
4237 nritems = btrfs_header_nritems(cur);
4238 level = btrfs_header_level(cur);
e3b83361 4239 sret = btrfs_bin_search(cur, min_key, &slot);
cbca7d59
FM
4240 if (sret < 0) {
4241 ret = sret;
4242 goto out;
4243 }
3f157a2f 4244
323ac95b
CM
4245 /* at the lowest level, we're done, setup the path and exit */
4246 if (level == path->lowest_level) {
e02119d5
CM
4247 if (slot >= nritems)
4248 goto find_next_key;
3f157a2f
CM
4249 ret = 0;
4250 path->slots[level] = slot;
4251 btrfs_item_key_to_cpu(cur, &found_key, slot);
4252 goto out;
4253 }
9652480b
Y
4254 if (sret && slot > 0)
4255 slot--;
3f157a2f 4256 /*
de78b51a 4257 * check this node pointer against the min_trans parameters.
260db43c 4258 * If it is too old, skip to the next one.
3f157a2f 4259 */
d397712b 4260 while (slot < nritems) {
3f157a2f 4261 u64 gen;
e02119d5 4262
3f157a2f
CM
4263 gen = btrfs_node_ptr_generation(cur, slot);
4264 if (gen < min_trans) {
4265 slot++;
4266 continue;
4267 }
de78b51a 4268 break;
3f157a2f 4269 }
e02119d5 4270find_next_key:
3f157a2f
CM
4271 /*
4272 * we didn't find a candidate key in this node, walk forward
4273 * and find another one
4274 */
4275 if (slot >= nritems) {
e02119d5
CM
4276 path->slots[level] = slot;
4277 sret = btrfs_find_next_key(root, path, min_key, level,
de78b51a 4278 min_trans);
e02119d5 4279 if (sret == 0) {
b3b4aa74 4280 btrfs_release_path(path);
3f157a2f
CM
4281 goto again;
4282 } else {
4283 goto out;
4284 }
4285 }
4286 /* save our key for returning back */
4287 btrfs_node_key_to_cpu(cur, &found_key, slot);
4288 path->slots[level] = slot;
4289 if (level == path->lowest_level) {
4290 ret = 0;
3f157a2f
CM
4291 goto out;
4292 }
4b231ae4 4293 cur = btrfs_read_node_slot(cur, slot);
fb770ae4
LB
4294 if (IS_ERR(cur)) {
4295 ret = PTR_ERR(cur);
4296 goto out;
4297 }
3f157a2f 4298
bd681513 4299 btrfs_tree_read_lock(cur);
b4ce94de 4300
bd681513 4301 path->locks[level - 1] = BTRFS_READ_LOCK;
3f157a2f 4302 path->nodes[level - 1] = cur;
f7c79f30 4303 unlock_up(path, level, 1, 0, NULL);
3f157a2f
CM
4304 }
4305out:
f98de9b9
FM
4306 path->keep_locks = keep_locks;
4307 if (ret == 0) {
4308 btrfs_unlock_up_safe(path, path->lowest_level + 1);
3f157a2f 4309 memcpy(min_key, &found_key, sizeof(found_key));
f98de9b9 4310 }
3f157a2f
CM
4311 return ret;
4312}
4313
4314/*
4315 * this is similar to btrfs_next_leaf, but does not try to preserve
4316 * and fixup the path. It looks for and returns the next key in the
de78b51a 4317 * tree based on the current path and the min_trans parameters.
3f157a2f
CM
4318 *
4319 * 0 is returned if another key is found, < 0 if there are any errors
4320 * and 1 is returned if there are no higher keys in the tree
4321 *
4322 * path->keep_locks should be set to 1 on the search made before
4323 * calling this function.
4324 */
e7a84565 4325int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
de78b51a 4326 struct btrfs_key *key, int level, u64 min_trans)
e7a84565 4327{
e7a84565
CM
4328 int slot;
4329 struct extent_buffer *c;
4330
6a9fb468 4331 WARN_ON(!path->keep_locks && !path->skip_locking);
d397712b 4332 while (level < BTRFS_MAX_LEVEL) {
e7a84565
CM
4333 if (!path->nodes[level])
4334 return 1;
4335
4336 slot = path->slots[level] + 1;
4337 c = path->nodes[level];
3f157a2f 4338next:
e7a84565 4339 if (slot >= btrfs_header_nritems(c)) {
33c66f43
YZ
4340 int ret;
4341 int orig_lowest;
4342 struct btrfs_key cur_key;
4343 if (level + 1 >= BTRFS_MAX_LEVEL ||
4344 !path->nodes[level + 1])
e7a84565 4345 return 1;
33c66f43 4346
6a9fb468 4347 if (path->locks[level + 1] || path->skip_locking) {
33c66f43
YZ
4348 level++;
4349 continue;
4350 }
4351
4352 slot = btrfs_header_nritems(c) - 1;
4353 if (level == 0)
4354 btrfs_item_key_to_cpu(c, &cur_key, slot);
4355 else
4356 btrfs_node_key_to_cpu(c, &cur_key, slot);
4357
4358 orig_lowest = path->lowest_level;
b3b4aa74 4359 btrfs_release_path(path);
33c66f43
YZ
4360 path->lowest_level = level;
4361 ret = btrfs_search_slot(NULL, root, &cur_key, path,
4362 0, 0);
4363 path->lowest_level = orig_lowest;
4364 if (ret < 0)
4365 return ret;
4366
4367 c = path->nodes[level];
4368 slot = path->slots[level];
4369 if (ret == 0)
4370 slot++;
4371 goto next;
e7a84565 4372 }
33c66f43 4373
e7a84565
CM
4374 if (level == 0)
4375 btrfs_item_key_to_cpu(c, key, slot);
3f157a2f 4376 else {
3f157a2f
CM
4377 u64 gen = btrfs_node_ptr_generation(c, slot);
4378
3f157a2f
CM
4379 if (gen < min_trans) {
4380 slot++;
4381 goto next;
4382 }
e7a84565 4383 btrfs_node_key_to_cpu(c, key, slot);
3f157a2f 4384 }
e7a84565
CM
4385 return 0;
4386 }
4387 return 1;
4388}
4389
3d7806ec
JS
4390int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4391 u64 time_seq)
d97e63b6
CM
4392{
4393 int slot;
8e73f275 4394 int level;
5f39d397 4395 struct extent_buffer *c;
8e73f275 4396 struct extent_buffer *next;
925baedd
CM
4397 struct btrfs_key key;
4398 u32 nritems;
4399 int ret;
0e46318d 4400 int i;
925baedd
CM
4401
4402 nritems = btrfs_header_nritems(path->nodes[0]);
d397712b 4403 if (nritems == 0)
925baedd 4404 return 1;
925baedd 4405
8e73f275
CM
4406 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4407again:
4408 level = 1;
4409 next = NULL;
b3b4aa74 4410 btrfs_release_path(path);
8e73f275 4411
a2135011 4412 path->keep_locks = 1;
8e73f275 4413
3d7806ec
JS
4414 if (time_seq)
4415 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4416 else
4417 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
925baedd
CM
4418 path->keep_locks = 0;
4419
4420 if (ret < 0)
4421 return ret;
4422
a2135011 4423 nritems = btrfs_header_nritems(path->nodes[0]);
168fd7d2
CM
4424 /*
4425 * by releasing the path above we dropped all our locks. A balance
4426 * could have added more items next to the key that used to be
4427 * at the very end of the block. So, check again here and
4428 * advance the path if there are now more items available.
4429 */
a2135011 4430 if (nritems > 0 && path->slots[0] < nritems - 1) {
e457afec
YZ
4431 if (ret == 0)
4432 path->slots[0]++;
8e73f275 4433 ret = 0;
925baedd
CM
4434 goto done;
4435 }
0b43e04f
LB
4436 /*
4437 * So the above check misses one case:
4438 * - after releasing the path above, someone has removed the item that
4439 * used to be at the very end of the block, and balance between leafs
4440 * gets another one with bigger key.offset to replace it.
4441 *
4442 * This one should be returned as well, or we can get leaf corruption
4443 * later(esp. in __btrfs_drop_extents()).
4444 *
4445 * And a bit more explanation about this check,
4446 * with ret > 0, the key isn't found, the path points to the slot
4447 * where it should be inserted, so the path->slots[0] item must be the
4448 * bigger one.
4449 */
4450 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4451 ret = 0;
4452 goto done;
4453 }
d97e63b6 4454
d397712b 4455 while (level < BTRFS_MAX_LEVEL) {
8e73f275
CM
4456 if (!path->nodes[level]) {
4457 ret = 1;
4458 goto done;
4459 }
5f39d397 4460
d97e63b6
CM
4461 slot = path->slots[level] + 1;
4462 c = path->nodes[level];
5f39d397 4463 if (slot >= btrfs_header_nritems(c)) {
d97e63b6 4464 level++;
8e73f275
CM
4465 if (level == BTRFS_MAX_LEVEL) {
4466 ret = 1;
4467 goto done;
4468 }
d97e63b6
CM
4469 continue;
4470 }
5f39d397 4471
0e46318d
JB
4472
4473 /*
4474 * Our current level is where we're going to start from, and to
4475 * make sure lockdep doesn't complain we need to drop our locks
4476 * and nodes from 0 to our current level.
4477 */
4478 for (i = 0; i < level; i++) {
4479 if (path->locks[level]) {
4480 btrfs_tree_read_unlock(path->nodes[i]);
4481 path->locks[i] = 0;
4482 }
4483 free_extent_buffer(path->nodes[i]);
4484 path->nodes[i] = NULL;
925baedd 4485 }
5f39d397 4486
8e73f275 4487 next = c;
d07b8528 4488 ret = read_block_for_search(root, path, &next, level,
cda79c54 4489 slot, &key);
8e73f275
CM
4490 if (ret == -EAGAIN)
4491 goto again;
5f39d397 4492
76a05b35 4493 if (ret < 0) {
b3b4aa74 4494 btrfs_release_path(path);
76a05b35
CM
4495 goto done;
4496 }
4497
5cd57b2c 4498 if (!path->skip_locking) {
bd681513 4499 ret = btrfs_try_tree_read_lock(next);
d42244a0
JS
4500 if (!ret && time_seq) {
4501 /*
4502 * If we don't get the lock, we may be racing
4503 * with push_leaf_left, holding that lock while
4504 * itself waiting for the leaf we've currently
4505 * locked. To solve this situation, we give up
4506 * on our lock and cycle.
4507 */
cf538830 4508 free_extent_buffer(next);
d42244a0
JS
4509 btrfs_release_path(path);
4510 cond_resched();
4511 goto again;
4512 }
0e46318d
JB
4513 if (!ret)
4514 btrfs_tree_read_lock(next);
5cd57b2c 4515 }
d97e63b6
CM
4516 break;
4517 }
4518 path->slots[level] = slot;
d397712b 4519 while (1) {
d97e63b6 4520 level--;
d97e63b6
CM
4521 path->nodes[level] = next;
4522 path->slots[level] = 0;
a74a4b97 4523 if (!path->skip_locking)
ffeb03cf 4524 path->locks[level] = BTRFS_READ_LOCK;
d97e63b6
CM
4525 if (!level)
4526 break;
b4ce94de 4527
d07b8528 4528 ret = read_block_for_search(root, path, &next, level,
cda79c54 4529 0, &key);
8e73f275
CM
4530 if (ret == -EAGAIN)
4531 goto again;
4532
76a05b35 4533 if (ret < 0) {
b3b4aa74 4534 btrfs_release_path(path);
76a05b35
CM
4535 goto done;
4536 }
4537
ffeb03cf 4538 if (!path->skip_locking)
0e46318d 4539 btrfs_tree_read_lock(next);
d97e63b6 4540 }
8e73f275 4541 ret = 0;
925baedd 4542done:
f7c79f30 4543 unlock_up(path, 0, 1, 0, NULL);
8e73f275
CM
4544
4545 return ret;
d97e63b6 4546}
0b86a832 4547
3f157a2f
CM
4548/*
4549 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4550 * searching until it gets past min_objectid or finds an item of 'type'
4551 *
4552 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4553 */
0b86a832
CM
4554int btrfs_previous_item(struct btrfs_root *root,
4555 struct btrfs_path *path, u64 min_objectid,
4556 int type)
4557{
4558 struct btrfs_key found_key;
4559 struct extent_buffer *leaf;
e02119d5 4560 u32 nritems;
0b86a832
CM
4561 int ret;
4562
d397712b 4563 while (1) {
0b86a832
CM
4564 if (path->slots[0] == 0) {
4565 ret = btrfs_prev_leaf(root, path);
4566 if (ret != 0)
4567 return ret;
4568 } else {
4569 path->slots[0]--;
4570 }
4571 leaf = path->nodes[0];
e02119d5
CM
4572 nritems = btrfs_header_nritems(leaf);
4573 if (nritems == 0)
4574 return 1;
4575 if (path->slots[0] == nritems)
4576 path->slots[0]--;
4577
0b86a832 4578 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
e02119d5
CM
4579 if (found_key.objectid < min_objectid)
4580 break;
0a4eefbb
YZ
4581 if (found_key.type == type)
4582 return 0;
e02119d5
CM
4583 if (found_key.objectid == min_objectid &&
4584 found_key.type < type)
4585 break;
0b86a832
CM
4586 }
4587 return 1;
4588}
ade2e0b3
WS
4589
4590/*
4591 * search in extent tree to find a previous Metadata/Data extent item with
4592 * min objecitd.
4593 *
4594 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4595 */
4596int btrfs_previous_extent_item(struct btrfs_root *root,
4597 struct btrfs_path *path, u64 min_objectid)
4598{
4599 struct btrfs_key found_key;
4600 struct extent_buffer *leaf;
4601 u32 nritems;
4602 int ret;
4603
4604 while (1) {
4605 if (path->slots[0] == 0) {
ade2e0b3
WS
4606 ret = btrfs_prev_leaf(root, path);
4607 if (ret != 0)
4608 return ret;
4609 } else {
4610 path->slots[0]--;
4611 }
4612 leaf = path->nodes[0];
4613 nritems = btrfs_header_nritems(leaf);
4614 if (nritems == 0)
4615 return 1;
4616 if (path->slots[0] == nritems)
4617 path->slots[0]--;
4618
4619 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4620 if (found_key.objectid < min_objectid)
4621 break;
4622 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4623 found_key.type == BTRFS_METADATA_ITEM_KEY)
4624 return 0;
4625 if (found_key.objectid == min_objectid &&
4626 found_key.type < BTRFS_EXTENT_ITEM_KEY)
4627 break;
4628 }
4629 return 1;
4630}