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