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