]> git.ipfire.org Git - thirdparty/linux.git/blob - fs/btrfs/ctree.c
btrfs: move btrfs_realloc_node() from ctree.c into defrag.c
[thirdparty/linux.git] / fs / btrfs / ctree.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2007,2008 Oracle. All rights reserved.
4 */
5
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/rbtree.h>
9 #include <linux/mm.h>
10 #include <linux/error-injection.h>
11 #include "messages.h"
12 #include "ctree.h"
13 #include "disk-io.h"
14 #include "transaction.h"
15 #include "print-tree.h"
16 #include "locking.h"
17 #include "volumes.h"
18 #include "qgroup.h"
19 #include "tree-mod-log.h"
20 #include "tree-checker.h"
21 #include "fs.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
24 #include "relocation.h"
25 #include "file-item.h"
26
27 static struct kmem_cache *btrfs_path_cachep;
28
29 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30 *root, struct btrfs_path *path, int level);
31 static 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);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35 struct extent_buffer *dst,
36 struct extent_buffer *src, int empty);
37 static int balance_node_right(struct btrfs_trans_handle *trans,
38 struct extent_buffer *dst_buf,
39 struct extent_buffer *src_buf);
40
41 static const struct btrfs_csums {
42 u16 size;
43 const char name[10];
44 const char driver[12];
45 } btrfs_csums[] = {
46 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
47 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
48 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50 .driver = "blake2b-256" },
51 };
52
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 */
57 static 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
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 */
79 static 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 {
84 memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
85 btrfs_item_nr_offset(leaf, 0) + src_offset, len);
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 */
102 static 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 {
107 copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
108 btrfs_item_nr_offset(src, 0) + src_offset, len);
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 */
122 static 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 */
142 static 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
151 /* This exists for btrfs-progs usages. */
152 u16 btrfs_csum_type_size(u16 type)
153 {
154 return btrfs_csums[type].size;
155 }
156
157 int 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 */
163 return btrfs_csum_type_size(t);
164 }
165
166 const 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
172 /*
173 * Return driver name if defined, otherwise the name that's also a valid driver
174 * name
175 */
176 const char *btrfs_super_csum_driver(u16 csum_type)
177 {
178 /* csum type is validated at mount time */
179 return btrfs_csums[csum_type].driver[0] ?
180 btrfs_csums[csum_type].driver :
181 btrfs_csums[csum_type].name;
182 }
183
184 size_t __attribute_const__ btrfs_get_num_csums(void)
185 {
186 return ARRAY_SIZE(btrfs_csums);
187 }
188
189 struct btrfs_path *btrfs_alloc_path(void)
190 {
191 might_sleep();
192
193 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
194 }
195
196 /* this also releases the path */
197 void btrfs_free_path(struct btrfs_path *p)
198 {
199 if (!p)
200 return;
201 btrfs_release_path(p);
202 kmem_cache_free(btrfs_path_cachep, p);
203 }
204
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 */
211 noinline void btrfs_release_path(struct btrfs_path *p)
212 {
213 int i;
214
215 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
216 p->slots[i] = 0;
217 if (!p->nodes[i])
218 continue;
219 if (p->locks[i]) {
220 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
221 p->locks[i] = 0;
222 }
223 free_extent_buffer(p->nodes[i]);
224 p->nodes[i] = NULL;
225 }
226 }
227
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 */
233 bool __cold abort_should_print_stack(int error)
234 {
235 switch (error) {
236 case -EIO:
237 case -EROFS:
238 case -ENOMEM:
239 return false;
240 }
241 return true;
242 }
243
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 */
254 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
255 {
256 struct extent_buffer *eb;
257
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
264 * it was COWed but we may not get the new root node yet so do
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 }
275 return eb;
276 }
277
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.
282 */
283 static void add_root_to_dirty_list(struct btrfs_root *root)
284 {
285 struct btrfs_fs_info *fs_info = root->fs_info;
286
287 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
288 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
289 return;
290
291 spin_lock(&fs_info->trans_lock);
292 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
293 /* Want the extent tree to be the last on the list */
294 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
295 list_move_tail(&root->dirty_list,
296 &fs_info->dirty_cowonly_roots);
297 else
298 list_move(&root->dirty_list,
299 &fs_info->dirty_cowonly_roots);
300 }
301 spin_unlock(&fs_info->trans_lock);
302 }
303
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 */
309 int 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 {
314 struct btrfs_fs_info *fs_info = root->fs_info;
315 struct extent_buffer *cow;
316 int ret = 0;
317 int level;
318 struct btrfs_disk_key disk_key;
319 u64 reloc_src_root = 0;
320
321 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
322 trans->transid != fs_info->running_transaction->transid);
323 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
324 trans->transid != root->last_trans);
325
326 level = btrfs_header_level(buf);
327 if (level == 0)
328 btrfs_item_key(buf, &disk_key, 0);
329 else
330 btrfs_node_key(buf, &disk_key, 0);
331
332 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
333 reloc_src_root = btrfs_header_owner(buf);
334 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
335 &disk_key, level, buf->start, 0,
336 reloc_src_root, BTRFS_NESTING_NEW_ROOT);
337 if (IS_ERR(cow))
338 return PTR_ERR(cow);
339
340 copy_extent_buffer_full(cow, buf);
341 btrfs_set_header_bytenr(cow, cow->start);
342 btrfs_set_header_generation(cow, trans->transid);
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);
350
351 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
352
353 WARN_ON(btrfs_header_generation(buf) > trans->transid);
354 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
355 ret = btrfs_inc_ref(trans, root, cow, 1);
356 else
357 ret = btrfs_inc_ref(trans, root, cow, 0);
358 if (ret) {
359 btrfs_tree_unlock(cow);
360 free_extent_buffer(cow);
361 btrfs_abort_transaction(trans, ret);
362 return ret;
363 }
364
365 btrfs_mark_buffer_dirty(trans, cow);
366 *cow_ret = cow;
367 return 0;
368 }
369
370 /*
371 * check if the tree block can be shared by multiple trees
372 */
373 int btrfs_block_can_be_shared(struct btrfs_root *root,
374 struct extent_buffer *buf)
375 {
376 /*
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.
380 */
381 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
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;
387
388 return 0;
389 }
390
391 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
392 struct btrfs_root *root,
393 struct extent_buffer *buf,
394 struct extent_buffer *cow,
395 int *last_ref)
396 {
397 struct btrfs_fs_info *fs_info = root->fs_info;
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)) {
422 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
423 btrfs_header_level(buf), 1,
424 &refs, &flags);
425 if (ret)
426 return ret;
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);
434 return ret;
435 }
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)) {
453 ret = btrfs_inc_ref(trans, root, buf, 1);
454 if (ret)
455 return ret;
456
457 if (root->root_key.objectid ==
458 BTRFS_TREE_RELOC_OBJECTID) {
459 ret = btrfs_dec_ref(trans, root, buf, 0);
460 if (ret)
461 return ret;
462 ret = btrfs_inc_ref(trans, root, cow, 1);
463 if (ret)
464 return ret;
465 }
466 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
467 } else {
468
469 if (root->root_key.objectid ==
470 BTRFS_TREE_RELOC_OBJECTID)
471 ret = btrfs_inc_ref(trans, root, cow, 1);
472 else
473 ret = btrfs_inc_ref(trans, root, cow, 0);
474 if (ret)
475 return ret;
476 }
477 if (new_flags != 0) {
478 ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
479 if (ret)
480 return ret;
481 }
482 } else {
483 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
484 if (root->root_key.objectid ==
485 BTRFS_TREE_RELOC_OBJECTID)
486 ret = btrfs_inc_ref(trans, root, cow, 1);
487 else
488 ret = btrfs_inc_ref(trans, root, cow, 0);
489 if (ret)
490 return ret;
491 ret = btrfs_dec_ref(trans, root, buf, 1);
492 if (ret)
493 return ret;
494 }
495 btrfs_clear_buffer_dirty(trans, buf);
496 *last_ref = 1;
497 }
498 return 0;
499 }
500
501 /*
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.
506 *
507 * search_start -- an allocation hint for the new block
508 *
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.
512 */
513 int 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)
520 {
521 struct btrfs_fs_info *fs_info = root->fs_info;
522 struct btrfs_disk_key disk_key;
523 struct extent_buffer *cow;
524 int level, ret;
525 int last_ref = 0;
526 int unlock_orig = 0;
527 u64 parent_start = 0;
528 u64 reloc_src_root = 0;
529
530 if (*cow_ret == buf)
531 unlock_orig = 1;
532
533 btrfs_assert_tree_write_locked(buf);
534
535 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
536 trans->transid != fs_info->running_transaction->transid);
537 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
538 trans->transid != root->last_trans);
539
540 level = btrfs_header_level(buf);
541
542 if (level == 0)
543 btrfs_item_key(buf, &disk_key, 0);
544 else
545 btrfs_node_key(buf, &disk_key, 0);
546
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 }
552 cow = btrfs_alloc_tree_block(trans, root, parent_start,
553 root->root_key.objectid, &disk_key, level,
554 search_start, empty_size, reloc_src_root, nest);
555 if (IS_ERR(cow))
556 return PTR_ERR(cow);
557
558 /* cow is set to blocking by btrfs_init_new_buffer */
559
560 copy_extent_buffer_full(cow, buf);
561 btrfs_set_header_bytenr(cow, cow->start);
562 btrfs_set_header_generation(cow, trans->transid);
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);
570
571 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
572
573 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
574 if (ret) {
575 btrfs_tree_unlock(cow);
576 free_extent_buffer(cow);
577 btrfs_abort_transaction(trans, ret);
578 return ret;
579 }
580
581 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
582 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
583 if (ret) {
584 btrfs_tree_unlock(cow);
585 free_extent_buffer(cow);
586 btrfs_abort_transaction(trans, ret);
587 return ret;
588 }
589 }
590
591 if (buf == root->node) {
592 WARN_ON(parent && parent != buf);
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;
596
597 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
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);
605 rcu_assign_pointer(root->node, cow);
606
607 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
608 parent_start, last_ref);
609 free_extent_buffer(buf);
610 add_root_to_dirty_list(root);
611 } else {
612 WARN_ON(trans->transid != btrfs_header_generation(parent));
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 }
621 btrfs_set_node_blockptr(parent, parent_slot,
622 cow->start);
623 btrfs_set_node_ptr_generation(parent, parent_slot,
624 trans->transid);
625 btrfs_mark_buffer_dirty(trans, parent);
626 if (last_ref) {
627 ret = btrfs_tree_mod_log_free_eb(buf);
628 if (ret) {
629 btrfs_tree_unlock(cow);
630 free_extent_buffer(cow);
631 btrfs_abort_transaction(trans, ret);
632 return ret;
633 }
634 }
635 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
636 parent_start, last_ref);
637 }
638 if (unlock_orig)
639 btrfs_tree_unlock(buf);
640 free_extent_buffer_stale(buf);
641 btrfs_mark_buffer_dirty(trans, cow);
642 *cow_ret = cow;
643 return 0;
644 }
645
646 static inline int should_cow_block(struct btrfs_trans_handle *trans,
647 struct btrfs_root *root,
648 struct extent_buffer *buf)
649 {
650 if (btrfs_is_testing(root->fs_info))
651 return 0;
652
653 /* Ensure we can see the FORCE_COW bit */
654 smp_mb__before_atomic();
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:
663 * when we create snapshot during committing the transaction,
664 * after we've finished copying src root, we must COW the shared
665 * block to ensure the metadata consistency.
666 */
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 &&
670 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
671 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
672 return 0;
673 return 1;
674 }
675
676 /*
677 * COWs a single block, see btrfs_force_cow_block() for the real work.
678 * This version of it has extra checks so that a block isn't COWed more than
679 * once per transaction, as long as it hasn't been written yet
680 */
681 int btrfs_cow_block(struct btrfs_trans_handle *trans,
682 struct btrfs_root *root, struct extent_buffer *buf,
683 struct extent_buffer *parent, int parent_slot,
684 struct extent_buffer **cow_ret,
685 enum btrfs_lock_nesting nest)
686 {
687 struct btrfs_fs_info *fs_info = root->fs_info;
688 u64 search_start;
689 int ret;
690
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 }
698
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 }
715
716 if (!should_cow_block(trans, root, buf)) {
717 *cow_ret = buf;
718 return 0;
719 }
720
721 search_start = round_down(buf->start, SZ_1G);
722
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);
730 ret = btrfs_force_cow_block(trans, root, buf, parent, parent_slot,
731 cow_ret, search_start, 0, nest);
732
733 trace_btrfs_cow_block(root, buf, *cow_ret);
734
735 return ret;
736 }
737 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
738
739 /*
740 * same as comp_keys only with two btrfs_key's
741 */
742 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
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 }
758
759 /*
760 * Search for a key in the given extent_buffer.
761 *
762 * The lower boundary for the search is specified by the slot number @first_slot.
763 * Use a value of 0 to search over the whole extent buffer. Works for both
764 * leaves and nodes.
765 *
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.
772 */
773 int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
774 const struct btrfs_key *key, int *slot)
775 {
776 unsigned long p;
777 int item_size;
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);
784 int ret;
785 const int key_size = sizeof(struct btrfs_disk_key);
786
787 if (unlikely(low > high)) {
788 btrfs_err(eb->fs_info,
789 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
790 __func__, low, high, eb->start,
791 btrfs_header_owner(eb), btrfs_header_level(eb));
792 return -EINVAL;
793 }
794
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
803 while (low < high) {
804 unsigned long oip;
805 unsigned long offset;
806 struct btrfs_disk_key *tmp;
807 struct btrfs_disk_key unaligned;
808 int mid;
809
810 mid = (low + high) / 2;
811 offset = p + mid * item_size;
812 oip = offset_in_page(offset);
813
814 if (oip + key_size <= PAGE_SIZE) {
815 const unsigned long idx = get_eb_page_index(offset);
816 char *kaddr = page_address(eb->pages[idx]);
817
818 oip = get_eb_offset_in_page(eb, offset);
819 tmp = (struct btrfs_disk_key *)(kaddr + oip);
820 } else {
821 read_extent_buffer(eb, &unaligned, offset, key_size);
822 tmp = &unaligned;
823 }
824
825 ret = btrfs_comp_keys(tmp, key);
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
840 static void root_add_used_bytes(struct btrfs_root *root)
841 {
842 spin_lock(&root->accounting_lock);
843 btrfs_set_root_used(&root->root_item,
844 btrfs_root_used(&root->root_item) + root->fs_info->nodesize);
845 spin_unlock(&root->accounting_lock);
846 }
847
848 static void root_sub_used_bytes(struct btrfs_root *root)
849 {
850 spin_lock(&root->accounting_lock);
851 btrfs_set_root_used(&root->root_item,
852 btrfs_root_used(&root->root_item) - root->fs_info->nodesize);
853 spin_unlock(&root->accounting_lock);
854 }
855
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).
858 */
859 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
860 int slot)
861 {
862 int level = btrfs_header_level(parent);
863 struct btrfs_tree_parent_check check = { 0 };
864 struct extent_buffer *eb;
865
866 if (slot < 0 || slot >= btrfs_header_nritems(parent))
867 return ERR_PTR(-ENOENT);
868
869 ASSERT(level);
870
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
877 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
878 &check);
879 if (IS_ERR(eb))
880 return eb;
881 if (!extent_buffer_uptodate(eb)) {
882 free_extent_buffer(eb);
883 return ERR_PTR(-EIO);
884 }
885
886 return eb;
887 }
888
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 */
894 static noinline int balance_level(struct btrfs_trans_handle *trans,
895 struct btrfs_root *root,
896 struct btrfs_path *path, int level)
897 {
898 struct btrfs_fs_info *fs_info = root->fs_info;
899 struct extent_buffer *right = NULL;
900 struct extent_buffer *mid;
901 struct extent_buffer *left = NULL;
902 struct extent_buffer *parent = NULL;
903 int ret = 0;
904 int wret;
905 int pslot;
906 int orig_slot = path->slots[level];
907 u64 orig_ptr;
908
909 ASSERT(level > 0);
910
911 mid = path->nodes[level];
912
913 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
914 WARN_ON(btrfs_header_generation(mid) != trans->transid);
915
916 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
917
918 if (level < BTRFS_MAX_LEVEL - 1) {
919 parent = path->nodes[level + 1];
920 pslot = path->slots[level + 1];
921 }
922
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 */
927 if (!parent) {
928 struct extent_buffer *child;
929
930 if (btrfs_header_nritems(mid) != 1)
931 return 0;
932
933 /* promote the child to a root */
934 child = btrfs_read_node_slot(mid, 0);
935 if (IS_ERR(child)) {
936 ret = PTR_ERR(child);
937 goto out;
938 }
939
940 btrfs_tree_lock(child);
941 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
942 BTRFS_NESTING_COW);
943 if (ret) {
944 btrfs_tree_unlock(child);
945 free_extent_buffer(child);
946 goto out;
947 }
948
949 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
950 if (ret < 0) {
951 btrfs_tree_unlock(child);
952 free_extent_buffer(child);
953 btrfs_abort_transaction(trans, ret);
954 goto out;
955 }
956 rcu_assign_pointer(root->node, child);
957
958 add_root_to_dirty_list(root);
959 btrfs_tree_unlock(child);
960
961 path->locks[level] = 0;
962 path->nodes[level] = NULL;
963 btrfs_clear_buffer_dirty(trans, mid);
964 btrfs_tree_unlock(mid);
965 /* once for the path */
966 free_extent_buffer(mid);
967
968 root_sub_used_bytes(root);
969 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
970 /* once for the root ptr */
971 free_extent_buffer_stale(mid);
972 return 0;
973 }
974 if (btrfs_header_nritems(mid) >
975 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
976 return 0;
977
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;
983 goto out;
984 }
985
986 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
987 wret = btrfs_cow_block(trans, root, left,
988 parent, pslot - 1, &left,
989 BTRFS_NESTING_LEFT_COW);
990 if (wret) {
991 ret = wret;
992 goto out;
993 }
994 }
995
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;
1001 goto out;
1002 }
1003
1004 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1005 wret = btrfs_cow_block(trans, root, right,
1006 parent, pslot + 1, &right,
1007 BTRFS_NESTING_RIGHT_COW);
1008 if (wret) {
1009 ret = wret;
1010 goto out;
1011 }
1012 }
1013
1014 /* first, try to make some room in the middle buffer */
1015 if (left) {
1016 orig_slot += btrfs_header_nritems(left);
1017 wret = push_node_left(trans, left, mid, 1);
1018 if (wret < 0)
1019 ret = wret;
1020 }
1021
1022 /*
1023 * then try to empty the right most buffer into the middle
1024 */
1025 if (right) {
1026 wret = push_node_left(trans, mid, right, 1);
1027 if (wret < 0 && wret != -ENOSPC)
1028 ret = wret;
1029 if (btrfs_header_nritems(right) == 0) {
1030 btrfs_clear_buffer_dirty(trans, right);
1031 btrfs_tree_unlock(right);
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 }
1038 root_sub_used_bytes(root);
1039 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1040 0, 1);
1041 free_extent_buffer_stale(right);
1042 right = NULL;
1043 } else {
1044 struct btrfs_disk_key right_key;
1045 btrfs_node_key(right, &right_key, 0);
1046 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1047 BTRFS_MOD_LOG_KEY_REPLACE);
1048 if (ret < 0) {
1049 btrfs_abort_transaction(trans, ret);
1050 goto out;
1051 }
1052 btrfs_set_node_key(parent, &right_key, pslot + 1);
1053 btrfs_mark_buffer_dirty(trans, parent);
1054 }
1055 }
1056 if (btrfs_header_nritems(mid) == 1) {
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 */
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);
1073 goto out;
1074 }
1075 wret = balance_node_right(trans, mid, left);
1076 if (wret < 0) {
1077 ret = wret;
1078 goto out;
1079 }
1080 if (wret == 1) {
1081 wret = push_node_left(trans, left, mid, 1);
1082 if (wret < 0)
1083 ret = wret;
1084 }
1085 BUG_ON(wret == 1);
1086 }
1087 if (btrfs_header_nritems(mid) == 0) {
1088 btrfs_clear_buffer_dirty(trans, mid);
1089 btrfs_tree_unlock(mid);
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 }
1096 root_sub_used_bytes(root);
1097 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1098 free_extent_buffer_stale(mid);
1099 mid = NULL;
1100 } else {
1101 /* update the parent key to reflect our changes */
1102 struct btrfs_disk_key mid_key;
1103 btrfs_node_key(mid, &mid_key, 0);
1104 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1105 BTRFS_MOD_LOG_KEY_REPLACE);
1106 if (ret < 0) {
1107 btrfs_abort_transaction(trans, ret);
1108 goto out;
1109 }
1110 btrfs_set_node_key(parent, &mid_key, pslot);
1111 btrfs_mark_buffer_dirty(trans, parent);
1112 }
1113
1114 /* update the path */
1115 if (left) {
1116 if (btrfs_header_nritems(left) > orig_slot) {
1117 atomic_inc(&left->refs);
1118 /* left was locked after cow */
1119 path->nodes[level] = left;
1120 path->slots[level + 1] -= 1;
1121 path->slots[level] = orig_slot;
1122 if (mid) {
1123 btrfs_tree_unlock(mid);
1124 free_extent_buffer(mid);
1125 }
1126 } else {
1127 orig_slot -= btrfs_header_nritems(left);
1128 path->slots[level] = orig_slot;
1129 }
1130 }
1131 /* double check we haven't messed things up */
1132 if (orig_ptr !=
1133 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1134 BUG();
1135 out:
1136 if (right) {
1137 btrfs_tree_unlock(right);
1138 free_extent_buffer(right);
1139 }
1140 if (left) {
1141 if (path->nodes[level] != left)
1142 btrfs_tree_unlock(left);
1143 free_extent_buffer(left);
1144 }
1145 return ret;
1146 }
1147
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 */
1152 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1153 struct btrfs_root *root,
1154 struct btrfs_path *path, int level)
1155 {
1156 struct btrfs_fs_info *fs_info = root->fs_info;
1157 struct extent_buffer *right = NULL;
1158 struct extent_buffer *mid;
1159 struct extent_buffer *left = NULL;
1160 struct extent_buffer *parent = NULL;
1161 int ret = 0;
1162 int wret;
1163 int pslot;
1164 int orig_slot = path->slots[level];
1165
1166 if (level == 0)
1167 return 1;
1168
1169 mid = path->nodes[level];
1170 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1171
1172 if (level < BTRFS_MAX_LEVEL - 1) {
1173 parent = path->nodes[level + 1];
1174 pslot = path->slots[level + 1];
1175 }
1176
1177 if (!parent)
1178 return 1;
1179
1180 /* first, try to make some room in the middle buffer */
1181 if (pslot) {
1182 u32 left_nr;
1183
1184 left = btrfs_read_node_slot(parent, pslot - 1);
1185 if (IS_ERR(left))
1186 return PTR_ERR(left);
1187
1188 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1189
1190 left_nr = btrfs_header_nritems(left);
1191 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1192 wret = 1;
1193 } else {
1194 ret = btrfs_cow_block(trans, root, left, parent,
1195 pslot - 1, &left,
1196 BTRFS_NESTING_LEFT_COW);
1197 if (ret)
1198 wret = 1;
1199 else {
1200 wret = push_node_left(trans, left, mid, 0);
1201 }
1202 }
1203 if (wret < 0)
1204 ret = wret;
1205 if (wret == 0) {
1206 struct btrfs_disk_key disk_key;
1207 orig_slot += left_nr;
1208 btrfs_node_key(mid, &disk_key, 0);
1209 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1210 BTRFS_MOD_LOG_KEY_REPLACE);
1211 if (ret < 0) {
1212 btrfs_tree_unlock(left);
1213 free_extent_buffer(left);
1214 btrfs_abort_transaction(trans, ret);
1215 return ret;
1216 }
1217 btrfs_set_node_key(parent, &disk_key, pslot);
1218 btrfs_mark_buffer_dirty(trans, parent);
1219 if (btrfs_header_nritems(left) > orig_slot) {
1220 path->nodes[level] = left;
1221 path->slots[level + 1] -= 1;
1222 path->slots[level] = orig_slot;
1223 btrfs_tree_unlock(mid);
1224 free_extent_buffer(mid);
1225 } else {
1226 orig_slot -=
1227 btrfs_header_nritems(left);
1228 path->slots[level] = orig_slot;
1229 btrfs_tree_unlock(left);
1230 free_extent_buffer(left);
1231 }
1232 return 0;
1233 }
1234 btrfs_tree_unlock(left);
1235 free_extent_buffer(left);
1236 }
1237
1238 /*
1239 * then try to empty the right most buffer into the middle
1240 */
1241 if (pslot + 1 < btrfs_header_nritems(parent)) {
1242 u32 right_nr;
1243
1244 right = btrfs_read_node_slot(parent, pslot + 1);
1245 if (IS_ERR(right))
1246 return PTR_ERR(right);
1247
1248 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1249
1250 right_nr = btrfs_header_nritems(right);
1251 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1252 wret = 1;
1253 } else {
1254 ret = btrfs_cow_block(trans, root, right,
1255 parent, pslot + 1,
1256 &right, BTRFS_NESTING_RIGHT_COW);
1257 if (ret)
1258 wret = 1;
1259 else {
1260 wret = balance_node_right(trans, right, mid);
1261 }
1262 }
1263 if (wret < 0)
1264 ret = wret;
1265 if (wret == 0) {
1266 struct btrfs_disk_key disk_key;
1267
1268 btrfs_node_key(right, &disk_key, 0);
1269 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1270 BTRFS_MOD_LOG_KEY_REPLACE);
1271 if (ret < 0) {
1272 btrfs_tree_unlock(right);
1273 free_extent_buffer(right);
1274 btrfs_abort_transaction(trans, ret);
1275 return ret;
1276 }
1277 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1278 btrfs_mark_buffer_dirty(trans, parent);
1279
1280 if (btrfs_header_nritems(mid) <= orig_slot) {
1281 path->nodes[level] = right;
1282 path->slots[level + 1] += 1;
1283 path->slots[level] = orig_slot -
1284 btrfs_header_nritems(mid);
1285 btrfs_tree_unlock(mid);
1286 free_extent_buffer(mid);
1287 } else {
1288 btrfs_tree_unlock(right);
1289 free_extent_buffer(right);
1290 }
1291 return 0;
1292 }
1293 btrfs_tree_unlock(right);
1294 free_extent_buffer(right);
1295 }
1296 return 1;
1297 }
1298
1299 /*
1300 * readahead one full node of leaves, finding things that are close
1301 * to the block in 'slot', and triggering ra on them.
1302 */
1303 static void reada_for_search(struct btrfs_fs_info *fs_info,
1304 struct btrfs_path *path,
1305 int level, int slot, u64 objectid)
1306 {
1307 struct extent_buffer *node;
1308 struct btrfs_disk_key disk_key;
1309 u32 nritems;
1310 u64 search;
1311 u64 target;
1312 u64 nread = 0;
1313 u64 nread_max;
1314 u32 nr;
1315 u32 blocksize;
1316 u32 nscan = 0;
1317
1318 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1319 return;
1320
1321 if (!path->nodes[level])
1322 return;
1323
1324 node = path->nodes[level];
1325
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
1340 search = btrfs_node_blockptr(node, slot);
1341 blocksize = fs_info->nodesize;
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 }
1350 }
1351
1352 target = search;
1353
1354 nritems = btrfs_header_nritems(node);
1355 nr = slot;
1356
1357 while (1) {
1358 if (path->reada == READA_BACK) {
1359 if (nr == 0)
1360 break;
1361 nr--;
1362 } else if (path->reada == READA_FORWARD ||
1363 path->reada == READA_FORWARD_ALWAYS) {
1364 nr++;
1365 if (nr >= nritems)
1366 break;
1367 }
1368 if (path->reada == READA_BACK && objectid) {
1369 btrfs_node_key(node, &disk_key, nr);
1370 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1371 break;
1372 }
1373 search = btrfs_node_blockptr(node, nr);
1374 if (path->reada == READA_FORWARD_ALWAYS ||
1375 (search <= target && target - search <= 65536) ||
1376 (search > target && search - target <= 65536)) {
1377 btrfs_readahead_node_child(node, nr);
1378 nread += blocksize;
1379 }
1380 nscan++;
1381 if (nread > nread_max || nscan > 32)
1382 break;
1383 }
1384 }
1385
1386 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1387 {
1388 struct extent_buffer *parent;
1389 int slot;
1390 int nritems;
1391
1392 parent = path->nodes[level + 1];
1393 if (!parent)
1394 return;
1395
1396 nritems = btrfs_header_nritems(parent);
1397 slot = path->slots[level + 1];
1398
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);
1403 }
1404
1405
1406 /*
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.
1411 *
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.
1415 *
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
1418 */
1419 static noinline void unlock_up(struct btrfs_path *path, int level,
1420 int lowest_unlock, int min_write_lock_level,
1421 int *write_lock_level)
1422 {
1423 int i;
1424 int skip_level = level;
1425 bool check_skip = true;
1426
1427 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1428 if (!path->nodes[i])
1429 break;
1430 if (!path->locks[i])
1431 break;
1432
1433 if (check_skip) {
1434 if (path->slots[i] == 0) {
1435 skip_level = i + 1;
1436 continue;
1437 }
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 }
1448 }
1449
1450 if (i >= lowest_unlock && i > skip_level) {
1451 check_skip = false;
1452 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1453 path->locks[i] = 0;
1454 if (write_lock_level &&
1455 i > min_write_lock_level &&
1456 i <= *write_lock_level) {
1457 *write_lock_level = i - 1;
1458 }
1459 }
1460 }
1461 }
1462
1463 /*
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.
1468 *
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.
1471 */
1472 static int
1473 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1474 struct extent_buffer **eb_ret, int level, int slot,
1475 const struct btrfs_key *key)
1476 {
1477 struct btrfs_fs_info *fs_info = root->fs_info;
1478 struct btrfs_tree_parent_check check = { 0 };
1479 u64 blocknr;
1480 u64 gen;
1481 struct extent_buffer *tmp;
1482 int ret;
1483 int parent_level;
1484 bool unlock_up;
1485
1486 unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
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);
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;
1495
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 */
1503 tmp = find_extent_buffer(fs_info, blocknr);
1504 if (tmp) {
1505 if (p->reada == READA_FORWARD_ALWAYS)
1506 reada_for_search(fs_info, p, level, slot, key->objectid);
1507
1508 /* first we do an atomic uptodate check */
1509 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
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 */
1515 if (btrfs_verify_level_key(tmp,
1516 parent_level - 1, &check.first_key, gen)) {
1517 free_extent_buffer(tmp);
1518 return -EUCLEAN;
1519 }
1520 *eb_ret = tmp;
1521 return 0;
1522 }
1523
1524 if (p->nowait) {
1525 free_extent_buffer(tmp);
1526 return -EAGAIN;
1527 }
1528
1529 if (unlock_up)
1530 btrfs_unlock_up_safe(p, level + 1);
1531
1532 /* now we're allowed to do a blocking uptodate check */
1533 ret = btrfs_read_extent_buffer(tmp, &check);
1534 if (ret) {
1535 free_extent_buffer(tmp);
1536 btrfs_release_path(p);
1537 return -EIO;
1538 }
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 }
1544
1545 if (unlock_up)
1546 ret = -EAGAIN;
1547
1548 goto out;
1549 } else if (p->nowait) {
1550 return -EAGAIN;
1551 }
1552
1553 if (unlock_up) {
1554 btrfs_unlock_up_safe(p, level + 1);
1555 ret = -EAGAIN;
1556 } else {
1557 ret = 0;
1558 }
1559
1560 if (p->reada != READA_NONE)
1561 reada_for_search(fs_info, p, level, slot, key->objectid);
1562
1563 tmp = read_tree_block(fs_info, blocknr, &check);
1564 if (IS_ERR(tmp)) {
1565 btrfs_release_path(p);
1566 return PTR_ERR(tmp);
1567 }
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;
1576
1577 out:
1578 if (ret == 0) {
1579 *eb_ret = tmp;
1580 } else {
1581 free_extent_buffer(tmp);
1582 btrfs_release_path(p);
1583 }
1584
1585 return ret;
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 */
1597 static int
1598 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1599 struct btrfs_root *root, struct btrfs_path *p,
1600 struct extent_buffer *b, int level, int ins_len,
1601 int *write_lock_level)
1602 {
1603 struct btrfs_fs_info *fs_info = root->fs_info;
1604 int ret = 0;
1605
1606 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1607 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1608
1609 if (*write_lock_level < level + 1) {
1610 *write_lock_level = level + 1;
1611 btrfs_release_path(p);
1612 return -EAGAIN;
1613 }
1614
1615 reada_for_balance(p, level);
1616 ret = split_node(trans, root, p, level);
1617
1618 b = p->nodes[level];
1619 } else if (ins_len < 0 && btrfs_header_nritems(b) <
1620 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1621
1622 if (*write_lock_level < level + 1) {
1623 *write_lock_level = level + 1;
1624 btrfs_release_path(p);
1625 return -EAGAIN;
1626 }
1627
1628 reada_for_balance(p, level);
1629 ret = balance_level(trans, root, p, level);
1630 if (ret)
1631 return ret;
1632
1633 b = p->nodes[level];
1634 if (!b) {
1635 btrfs_release_path(p);
1636 return -EAGAIN;
1637 }
1638 BUG_ON(btrfs_header_nritems(b) == 1);
1639 }
1640 return ret;
1641 }
1642
1643 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
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;
1650
1651 ASSERT(path);
1652 ASSERT(found_key);
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);
1659 if (ret < 0)
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
1678 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1679 struct btrfs_path *p,
1680 int write_lock_level)
1681 {
1682 struct extent_buffer *b;
1683 int root_lock = 0;
1684 int level = 0;
1685
1686 if (p->search_commit_root) {
1687 b = root->commit_root;
1688 atomic_inc(&b->refs);
1689 level = btrfs_header_level(b);
1690 /*
1691 * Ensure that all callers have set skip_locking when
1692 * p->search_commit_root = 1.
1693 */
1694 ASSERT(p->skip_locking == 1);
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
1705 /* We try very hard to do read locks on the root */
1706 root_lock = BTRFS_READ_LOCK;
1707
1708 /*
1709 * If the level is set to maximum, we can skip trying to get the read
1710 * lock.
1711 */
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 */
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 }
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 }
1732
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
1739 out:
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
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
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 */
1772 static 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 }
1796
1797 static 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
1815 return btrfs_bin_search(eb, search_low_slot, key, slot);
1816 }
1817
1818 static 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 */
1862 ret = btrfs_comp_keys(&first_key, key);
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));
1935 ASSERT(err <= 0);
1936 if (WARN_ON(err > 0))
1937 err = -EUCLEAN;
1938 if (err)
1939 ret = err;
1940 }
1941 }
1942
1943 return ret;
1944 }
1945
1946 /*
1947 * Look for a key in a tree and perform necessary modifications to preserve
1948 * tree invariants.
1949 *
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
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.
1962 * @cow: boolean should CoW operations be performed. Must always be 1
1963 * when modifying the tree.
1964 *
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
1976 */
1977 int 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)
1980 {
1981 struct btrfs_fs_info *fs_info = root->fs_info;
1982 struct extent_buffer *b;
1983 int slot;
1984 int ret;
1985 int err;
1986 int level;
1987 int lowest_unlock = 1;
1988 /* everything at write_lock_level or lower must be write locked */
1989 int write_lock_level = 0;
1990 u8 lowest_level = 0;
1991 int min_write_lock_level;
1992 int prev_cmp;
1993
1994 might_sleep();
1995
1996 lowest_level = p->lowest_level;
1997 WARN_ON(lowest_level && ins_len > 0);
1998 WARN_ON(p->nodes[0] != NULL);
1999 BUG_ON(!cow && ins_len);
2000
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
2008 if (ins_len < 0) {
2009 lowest_unlock = 2;
2010
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
2027 if (cow && (p->keep_locks || p->lowest_level))
2028 write_lock_level = BTRFS_MAX_LEVEL;
2029
2030 min_write_lock_level = write_lock_level;
2031
2032 if (p->need_commit_sem) {
2033 ASSERT(p->search_commit_root);
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 }
2040 }
2041
2042 again:
2043 prev_cmp = -1;
2044 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2045 if (IS_ERR(b)) {
2046 ret = PTR_ERR(b);
2047 goto done;
2048 }
2049
2050 while (b) {
2051 int dec = 0;
2052
2053 level = btrfs_header_level(b);
2054
2055 if (cow) {
2056 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2057
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 */
2063 if (!should_cow_block(trans, root, b))
2064 goto cow_done;
2065
2066 /*
2067 * must have write locks on this node and the
2068 * parent
2069 */
2070 if (level > write_lock_level ||
2071 (level + 1 > write_lock_level &&
2072 level + 1 < BTRFS_MAX_LEVEL &&
2073 p->nodes[level + 1])) {
2074 write_lock_level = level + 1;
2075 btrfs_release_path(p);
2076 goto again;
2077 }
2078
2079 if (last_level)
2080 err = btrfs_cow_block(trans, root, b, NULL, 0,
2081 &b,
2082 BTRFS_NESTING_COW);
2083 else
2084 err = btrfs_cow_block(trans, root, b,
2085 p->nodes[level + 1],
2086 p->slots[level + 1], &b,
2087 BTRFS_NESTING_COW);
2088 if (err) {
2089 ret = err;
2090 goto done;
2091 }
2092 }
2093 cow_done:
2094 p->nodes[level] = b;
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 *
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.
2106 */
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 }
2115
2116 if (level == 0) {
2117 if (ins_len > 0)
2118 ASSERT(write_lock_level >= 1);
2119
2120 ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2121 if (!p->search_for_split)
2122 unlock_up(p, level, lowest_unlock,
2123 min_write_lock_level, NULL);
2124 goto done;
2125 }
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
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);
2178
2179 btrfs_maybe_reset_lockdep_class(root, b);
2180
2181 if (level <= write_lock_level) {
2182 btrfs_tree_lock(b);
2183 p->locks[level] = BTRFS_WRITE_LOCK;
2184 } else {
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 }
2194 p->locks[level] = BTRFS_READ_LOCK;
2195 }
2196 p->nodes[level] = b;
2197 }
2198 }
2199 ret = 1;
2200 done:
2201 if (ret < 0 && !p->skip_release_on_error)
2202 btrfs_release_path(p);
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
2213 return ret;
2214 }
2215 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2216
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 */
2228 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2229 struct btrfs_path *p, u64 time_seq)
2230 {
2231 struct btrfs_fs_info *fs_info = root->fs_info;
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);
2242 ASSERT(!p->nowait);
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
2249 again:
2250 b = btrfs_get_old_root(root, time_seq);
2251 if (!b) {
2252 ret = -EIO;
2253 goto done;
2254 }
2255 level = btrfs_header_level(b);
2256 p->locks[level] = BTRFS_READ_LOCK;
2257
2258 while (b) {
2259 int dec = 0;
2260
2261 level = btrfs_header_level(b);
2262 p->nodes[level] = b;
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
2272 ret = btrfs_bin_search(b, 0, key, &slot);
2273 if (ret < 0)
2274 goto done;
2275
2276 if (level == 0) {
2277 p->slots[level] = slot;
2278 unlock_up(p, level, lowest_unlock, 0, NULL);
2279 goto done;
2280 }
2281
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);
2288
2289 if (level == lowest_level) {
2290 if (dec)
2291 p->slots[level]++;
2292 goto done;
2293 }
2294
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;
2300 goto done;
2301 }
2302
2303 level = btrfs_header_level(b);
2304 btrfs_tree_read_lock(b);
2305 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2306 if (!b) {
2307 ret = -ENOMEM;
2308 goto done;
2309 }
2310 p->locks[level] = BTRFS_READ_LOCK;
2311 p->nodes[level] = b;
2312 }
2313 ret = 1;
2314 done:
2315 if (ret < 0)
2316 btrfs_release_path(p);
2317
2318 return ret;
2319 }
2320
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 */
2330 static 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]);
2371 ret = btrfs_comp_keys(&found_key, &orig_key);
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);
2386 ret = btrfs_comp_keys(&found_key, &key);
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
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 */
2414 int btrfs_search_slot_for_read(struct btrfs_root *root,
2415 const struct btrfs_key *key,
2416 struct btrfs_path *p, int find_higher,
2417 int return_any)
2418 {
2419 int ret;
2420 struct extent_buffer *leaf;
2421
2422 again:
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 {
2452 if (p->slots[0] == 0) {
2453 ret = btrfs_prev_leaf(root, p);
2454 if (ret < 0)
2455 return ret;
2456 if (!ret) {
2457 leaf = p->nodes[0];
2458 if (p->slots[0] == btrfs_header_nritems(leaf))
2459 p->slots[0]--;
2460 return 0;
2461 }
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 {
2473 --p->slots[0];
2474 }
2475 }
2476 return 0;
2477 }
2478
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 */
2485 int 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
2500 /*
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 */
2511 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2512 struct btrfs_path *path)
2513 {
2514 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2515 int ret;
2516
2517 ret = btrfs_next_leaf(root, path);
2518 if (ret)
2519 return ret;
2520 }
2521
2522 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2523 return 0;
2524 }
2525
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
2532 *
2533 */
2534 static void fixup_low_keys(struct btrfs_trans_handle *trans,
2535 struct btrfs_path *path,
2536 struct btrfs_disk_key *key, int level)
2537 {
2538 int i;
2539 struct extent_buffer *t;
2540 int ret;
2541
2542 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2543 int tslot = path->slots[i];
2544
2545 if (!path->nodes[i])
2546 break;
2547 t = path->nodes[i];
2548 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2549 BTRFS_MOD_LOG_KEY_REPLACE);
2550 BUG_ON(ret < 0);
2551 btrfs_set_node_key(t, key, tslot);
2552 btrfs_mark_buffer_dirty(trans, path->nodes[i]);
2553 if (tslot != 0)
2554 break;
2555 }
2556 }
2557
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 */
2564 void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
2565 struct btrfs_path *path,
2566 const struct btrfs_key *new_key)
2567 {
2568 struct btrfs_fs_info *fs_info = trans->fs_info;
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);
2577 if (unlikely(btrfs_comp_keys(&disk_key, new_key) >= 0)) {
2578 btrfs_print_leaf(eb);
2579 btrfs_crit(fs_info,
2580 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2581 slot, btrfs_disk_key_objectid(&disk_key),
2582 btrfs_disk_key_type(&disk_key),
2583 btrfs_disk_key_offset(&disk_key),
2584 new_key->objectid, new_key->type,
2585 new_key->offset);
2586 BUG();
2587 }
2588 }
2589 if (slot < btrfs_header_nritems(eb) - 1) {
2590 btrfs_item_key(eb, &disk_key, slot + 1);
2591 if (unlikely(btrfs_comp_keys(&disk_key, new_key) <= 0)) {
2592 btrfs_print_leaf(eb);
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);
2600 BUG();
2601 }
2602 }
2603
2604 btrfs_cpu_key_to_disk(&disk_key, new_key);
2605 btrfs_set_item_key(eb, &disk_key, slot);
2606 btrfs_mark_buffer_dirty(trans, eb);
2607 if (slot == 0)
2608 fixup_low_keys(trans, path, &disk_key, 1);
2609 }
2610
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 */
2631 static 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
2652 if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
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);
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
2667 /*
2668 * try to push data from one node into the next node left in the
2669 * tree.
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.
2673 */
2674 static int push_node_left(struct btrfs_trans_handle *trans,
2675 struct extent_buffer *dst,
2676 struct extent_buffer *src, int empty)
2677 {
2678 struct btrfs_fs_info *fs_info = trans->fs_info;
2679 int push_items = 0;
2680 int src_nritems;
2681 int dst_nritems;
2682 int ret = 0;
2683
2684 src_nritems = btrfs_header_nritems(src);
2685 dst_nritems = btrfs_header_nritems(dst);
2686 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2687 WARN_ON(btrfs_header_generation(src) != trans->transid);
2688 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2689
2690 if (!empty && src_nritems <= 8)
2691 return 1;
2692
2693 if (push_items <= 0)
2694 return 1;
2695
2696 if (empty) {
2697 push_items = min(src_nritems, push_items);
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);
2710
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 }
2717 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2718 if (ret) {
2719 btrfs_abort_transaction(trans, ret);
2720 return ret;
2721 }
2722 copy_extent_buffer(dst, src,
2723 btrfs_node_key_ptr_offset(dst, dst_nritems),
2724 btrfs_node_key_ptr_offset(src, 0),
2725 push_items * sizeof(struct btrfs_key_ptr));
2726
2727 if (push_items < src_nritems) {
2728 /*
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.
2731 */
2732 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2733 btrfs_node_key_ptr_offset(src, push_items),
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);
2739 btrfs_mark_buffer_dirty(trans, src);
2740 btrfs_mark_buffer_dirty(trans, dst);
2741
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 */
2754 static int balance_node_right(struct btrfs_trans_handle *trans,
2755 struct extent_buffer *dst,
2756 struct extent_buffer *src)
2757 {
2758 struct btrfs_fs_info *fs_info = trans->fs_info;
2759 int push_items = 0;
2760 int max_push;
2761 int src_nritems;
2762 int dst_nritems;
2763 int ret = 0;
2764
2765 WARN_ON(btrfs_header_generation(src) != trans->transid);
2766 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2767
2768 src_nritems = btrfs_header_nritems(src);
2769 dst_nritems = btrfs_header_nritems(dst);
2770 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2771 if (push_items <= 0)
2772 return 1;
2773
2774 if (src_nritems < 4)
2775 return 1;
2776
2777 max_push = src_nritems / 2 + 1;
2778 /* don't try to empty the node */
2779 if (max_push >= src_nritems)
2780 return 1;
2781
2782 if (max_push < push_items)
2783 push_items = max_push;
2784
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 }
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 */
2796 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2797 btrfs_node_key_ptr_offset(dst, 0),
2798 (dst_nritems) *
2799 sizeof(struct btrfs_key_ptr));
2800
2801 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2802 push_items);
2803 if (ret) {
2804 btrfs_abort_transaction(trans, ret);
2805 return ret;
2806 }
2807 copy_extent_buffer(dst, src,
2808 btrfs_node_key_ptr_offset(dst, 0),
2809 btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2810 push_items * sizeof(struct btrfs_key_ptr));
2811
2812 btrfs_set_header_nritems(src, src_nritems - push_items);
2813 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2814
2815 btrfs_mark_buffer_dirty(trans, src);
2816 btrfs_mark_buffer_dirty(trans, dst);
2817
2818 return ret;
2819 }
2820
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
2825 *
2826 * returns zero on success or < 0 on failure.
2827 */
2828 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2829 struct btrfs_root *root,
2830 struct btrfs_path *path, int level)
2831 {
2832 u64 lower_gen;
2833 struct extent_buffer *lower;
2834 struct extent_buffer *c;
2835 struct extent_buffer *old;
2836 struct btrfs_disk_key lower_key;
2837 int ret;
2838
2839 BUG_ON(path->nodes[level]);
2840 BUG_ON(path->nodes[level-1] != root->node);
2841
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
2848 c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2849 &lower_key, level, root->node->start, 0,
2850 0, BTRFS_NESTING_NEW_ROOT);
2851 if (IS_ERR(c))
2852 return PTR_ERR(c);
2853
2854 root_add_used_bytes(root);
2855
2856 btrfs_set_header_nritems(c, 1);
2857 btrfs_set_node_key(c, &lower_key, 0);
2858 btrfs_set_node_blockptr(c, 0, lower->start);
2859 lower_gen = btrfs_header_generation(lower);
2860 WARN_ON(lower_gen != trans->transid);
2861
2862 btrfs_set_node_ptr_generation(c, 0, lower_gen);
2863
2864 btrfs_mark_buffer_dirty(trans, c);
2865
2866 old = root->node;
2867 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
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 }
2874 rcu_assign_pointer(root->node, c);
2875
2876 /* the super has an extra ref to root->node */
2877 free_extent_buffer(old);
2878
2879 add_root_to_dirty_list(root);
2880 atomic_inc(&c->refs);
2881 path->nodes[level] = c;
2882 path->locks[level] = BTRFS_WRITE_LOCK;
2883 path->slots[level] = 0;
2884 return 0;
2885 }
2886
2887 /*
2888 * worker function to insert a single pointer in a node.
2889 * the node should have enough room for the pointer already
2890 *
2891 * slot and level indicate where you want the key to go, and
2892 * blocknr is the block the key points to.
2893 */
2894 static 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)
2898 {
2899 struct extent_buffer *lower;
2900 int nritems;
2901 int ret;
2902
2903 BUG_ON(!path->nodes[level]);
2904 btrfs_assert_tree_write_locked(path->nodes[level]);
2905 lower = path->nodes[level];
2906 nritems = btrfs_header_nritems(lower);
2907 BUG_ON(slot > nritems);
2908 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2909 if (slot != nritems) {
2910 if (level) {
2911 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2912 slot, nritems - slot);
2913 if (ret < 0) {
2914 btrfs_abort_transaction(trans, ret);
2915 return ret;
2916 }
2917 }
2918 memmove_extent_buffer(lower,
2919 btrfs_node_key_ptr_offset(lower, slot + 1),
2920 btrfs_node_key_ptr_offset(lower, slot),
2921 (nritems - slot) * sizeof(struct btrfs_key_ptr));
2922 }
2923 if (level) {
2924 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2925 BTRFS_MOD_LOG_KEY_ADD);
2926 if (ret < 0) {
2927 btrfs_abort_transaction(trans, ret);
2928 return ret;
2929 }
2930 }
2931 btrfs_set_node_key(lower, key, slot);
2932 btrfs_set_node_blockptr(lower, slot, bytenr);
2933 WARN_ON(trans->transid == 0);
2934 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2935 btrfs_set_header_nritems(lower, nritems + 1);
2936 btrfs_mark_buffer_dirty(trans, lower);
2937
2938 return 0;
2939 }
2940
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.
2947 *
2948 * returns 0 on success and < 0 on failure
2949 */
2950 static noinline int split_node(struct btrfs_trans_handle *trans,
2951 struct btrfs_root *root,
2952 struct btrfs_path *path, int level)
2953 {
2954 struct btrfs_fs_info *fs_info = root->fs_info;
2955 struct extent_buffer *c;
2956 struct extent_buffer *split;
2957 struct btrfs_disk_key disk_key;
2958 int mid;
2959 int ret;
2960 u32 c_nritems;
2961
2962 c = path->nodes[level];
2963 WARN_ON(btrfs_header_generation(c) != trans->transid);
2964 if (c == root->node) {
2965 /*
2966 * trying to split the root, lets make a new one
2967 *
2968 * tree mod log: We don't log_removal old root in
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
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.
2974 */
2975 ret = insert_new_root(trans, root, path, level + 1);
2976 if (ret)
2977 return ret;
2978 } else {
2979 ret = push_nodes_for_insert(trans, root, path, level);
2980 c = path->nodes[level];
2981 if (!ret && btrfs_header_nritems(c) <
2982 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2983 return 0;
2984 if (ret < 0)
2985 return ret;
2986 }
2987
2988 c_nritems = btrfs_header_nritems(c);
2989 mid = (c_nritems + 1) / 2;
2990 btrfs_node_key(c, &disk_key, mid);
2991
2992 split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2993 &disk_key, level, c->start, 0,
2994 0, BTRFS_NESTING_SPLIT);
2995 if (IS_ERR(split))
2996 return PTR_ERR(split);
2997
2998 root_add_used_bytes(root);
2999 ASSERT(btrfs_header_level(c) == level);
3000
3001 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
3002 if (ret) {
3003 btrfs_tree_unlock(split);
3004 free_extent_buffer(split);
3005 btrfs_abort_transaction(trans, ret);
3006 return ret;
3007 }
3008 copy_extent_buffer(split, c,
3009 btrfs_node_key_ptr_offset(split, 0),
3010 btrfs_node_key_ptr_offset(c, mid),
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);
3014
3015 btrfs_mark_buffer_dirty(trans, c);
3016 btrfs_mark_buffer_dirty(trans, split);
3017
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 }
3025
3026 if (path->slots[level] >= mid) {
3027 path->slots[level] -= mid;
3028 btrfs_tree_unlock(c);
3029 free_extent_buffer(c);
3030 path->nodes[level] = split;
3031 path->slots[level + 1] += 1;
3032 } else {
3033 btrfs_tree_unlock(split);
3034 free_extent_buffer(split);
3035 }
3036 return 0;
3037 }
3038
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 */
3044 static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3045 {
3046 int data_len;
3047 int nritems = btrfs_header_nritems(l);
3048 int end = min(nritems, start + nr) - 1;
3049
3050 if (!nr)
3051 return 0;
3052 data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
3053 data_len = data_len - btrfs_item_offset(l, end);
3054 data_len += sizeof(struct btrfs_item) * nr;
3055 WARN_ON(data_len < 0);
3056 return data_len;
3057 }
3058
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 */
3064 int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3065 {
3066 struct btrfs_fs_info *fs_info = leaf->fs_info;
3067 int nritems = btrfs_header_nritems(leaf);
3068 int ret;
3069
3070 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3071 if (ret < 0) {
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);
3077 }
3078 return ret;
3079 }
3080
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 */
3085 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3086 struct btrfs_path *path,
3087 int data_size, int empty,
3088 struct extent_buffer *right,
3089 int free_space, u32 left_nritems,
3090 u32 min_slot)
3091 {
3092 struct btrfs_fs_info *fs_info = right->fs_info;
3093 struct extent_buffer *left = path->nodes[0];
3094 struct extent_buffer *upper = path->nodes[1];
3095 struct btrfs_map_token token;
3096 struct btrfs_disk_key disk_key;
3097 int slot;
3098 u32 i;
3099 int push_space = 0;
3100 int push_items = 0;
3101 u32 nr;
3102 u32 right_nritems;
3103 u32 data_end;
3104 u32 this_item_size;
3105
3106 if (empty)
3107 nr = 0;
3108 else
3109 nr = max_t(u32, 1, min_slot);
3110
3111 if (path->slots[0] >= left_nritems)
3112 push_space += data_size;
3113
3114 slot = path->slots[1];
3115 i = left_nritems - 1;
3116 while (i >= nr) {
3117 if (!empty && push_items > 0) {
3118 if (path->slots[0] > i)
3119 break;
3120 if (path->slots[0] == i) {
3121 int space = btrfs_leaf_free_space(left);
3122
3123 if (space + push_space * 2 > free_space)
3124 break;
3125 }
3126 }
3127
3128 if (path->slots[0] == i)
3129 push_space += data_size;
3130
3131 this_item_size = btrfs_item_size(left, i);
3132 if (this_item_size + sizeof(struct btrfs_item) +
3133 push_space > free_space)
3134 break;
3135
3136 push_items++;
3137 push_space += this_item_size + sizeof(struct btrfs_item);
3138 if (i == 0)
3139 break;
3140 i--;
3141 }
3142
3143 if (push_items == 0)
3144 goto out_unlock;
3145
3146 WARN_ON(!empty && push_items == left_nritems);
3147
3148 /* push left to right */
3149 right_nritems = btrfs_header_nritems(right);
3150
3151 push_space = btrfs_item_data_end(left, left_nritems - push_items);
3152 push_space -= leaf_data_end(left);
3153
3154 /* make room in the right data area */
3155 data_end = leaf_data_end(right);
3156 memmove_leaf_data(right, data_end - push_space, data_end,
3157 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3158
3159 /* copy from the left data area */
3160 copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3161 leaf_data_end(left), push_space);
3162
3163 memmove_leaf_items(right, push_items, 0, right_nritems);
3164
3165 /* copy the items from left to right */
3166 copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
3167
3168 /* update the item pointers */
3169 btrfs_init_map_token(&token, right);
3170 right_nritems += push_items;
3171 btrfs_set_header_nritems(right, right_nritems);
3172 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3173 for (i = 0; i < right_nritems; i++) {
3174 push_space -= btrfs_token_item_size(&token, i);
3175 btrfs_set_token_item_offset(&token, i, push_space);
3176 }
3177
3178 left_nritems -= push_items;
3179 btrfs_set_header_nritems(left, left_nritems);
3180
3181 if (left_nritems)
3182 btrfs_mark_buffer_dirty(trans, left);
3183 else
3184 btrfs_clear_buffer_dirty(trans, left);
3185
3186 btrfs_mark_buffer_dirty(trans, right);
3187
3188 btrfs_item_key(right, &disk_key, 0);
3189 btrfs_set_node_key(upper, &disk_key, slot + 1);
3190 btrfs_mark_buffer_dirty(trans, upper);
3191
3192 /* then fixup the leaf pointer in the path */
3193 if (path->slots[0] >= left_nritems) {
3194 path->slots[0] -= left_nritems;
3195 if (btrfs_header_nritems(path->nodes[0]) == 0)
3196 btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3197 btrfs_tree_unlock(path->nodes[0]);
3198 free_extent_buffer(path->nodes[0]);
3199 path->nodes[0] = right;
3200 path->slots[1] += 1;
3201 } else {
3202 btrfs_tree_unlock(right);
3203 free_extent_buffer(right);
3204 }
3205 return 0;
3206
3207 out_unlock:
3208 btrfs_tree_unlock(right);
3209 free_extent_buffer(right);
3210 return 1;
3211 }
3212
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.
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
3222 */
3223 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3224 *root, struct btrfs_path *path,
3225 int min_data_size, int data_size,
3226 int empty, u32 min_slot)
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
3244 btrfs_assert_tree_write_locked(path->nodes[1]);
3245
3246 right = btrfs_read_node_slot(upper, slot + 1);
3247 if (IS_ERR(right))
3248 return PTR_ERR(right);
3249
3250 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3251
3252 free_space = btrfs_leaf_free_space(right);
3253 if (free_space < data_size)
3254 goto out_unlock;
3255
3256 ret = btrfs_cow_block(trans, root, right, upper,
3257 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3258 if (ret)
3259 goto out_unlock;
3260
3261 left_nritems = btrfs_header_nritems(left);
3262 if (left_nritems == 0)
3263 goto out_unlock;
3264
3265 if (check_sibling_keys(left, right)) {
3266 ret = -EUCLEAN;
3267 btrfs_abort_transaction(trans, ret);
3268 btrfs_tree_unlock(right);
3269 free_extent_buffer(right);
3270 return ret;
3271 }
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
3276 * no need to touch/dirty our left leaf. */
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
3285 return __push_leaf_right(trans, path, min_data_size, empty, right,
3286 free_space, left_nritems, min_slot);
3287 out_unlock:
3288 btrfs_tree_unlock(right);
3289 free_extent_buffer(right);
3290 return 1;
3291 }
3292
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
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
3300 */
3301 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3302 struct btrfs_path *path, int data_size,
3303 int empty, struct extent_buffer *left,
3304 int free_space, u32 right_nritems,
3305 u32 max_slot)
3306 {
3307 struct btrfs_fs_info *fs_info = left->fs_info;
3308 struct btrfs_disk_key disk_key;
3309 struct extent_buffer *right = path->nodes[0];
3310 int i;
3311 int push_space = 0;
3312 int push_items = 0;
3313 u32 old_left_nritems;
3314 u32 nr;
3315 int ret = 0;
3316 u32 this_item_size;
3317 u32 old_left_item_size;
3318 struct btrfs_map_token token;
3319
3320 if (empty)
3321 nr = min(right_nritems, max_slot);
3322 else
3323 nr = min(right_nritems - 1, max_slot);
3324
3325 for (i = 0; i < nr; i++) {
3326 if (!empty && push_items > 0) {
3327 if (path->slots[0] < i)
3328 break;
3329 if (path->slots[0] == i) {
3330 int space = btrfs_leaf_free_space(right);
3331
3332 if (space + push_space * 2 > free_space)
3333 break;
3334 }
3335 }
3336
3337 if (path->slots[0] == i)
3338 push_space += data_size;
3339
3340 this_item_size = btrfs_item_size(right, i);
3341 if (this_item_size + sizeof(struct btrfs_item) + push_space >
3342 free_space)
3343 break;
3344
3345 push_items++;
3346 push_space += this_item_size + sizeof(struct btrfs_item);
3347 }
3348
3349 if (push_items == 0) {
3350 ret = 1;
3351 goto out;
3352 }
3353 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3354
3355 /* push data from right to left */
3356 copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
3357
3358 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3359 btrfs_item_offset(right, push_items - 1);
3360
3361 copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3362 btrfs_item_offset(right, push_items - 1), push_space);
3363 old_left_nritems = btrfs_header_nritems(left);
3364 BUG_ON(old_left_nritems <= 0);
3365
3366 btrfs_init_map_token(&token, left);
3367 old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3368 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3369 u32 ioff;
3370
3371 ioff = btrfs_token_item_offset(&token, i);
3372 btrfs_set_token_item_offset(&token, i,
3373 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3374 }
3375 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3376
3377 /* fixup right node */
3378 if (push_items > right_nritems)
3379 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3380 right_nritems);
3381
3382 if (push_items < right_nritems) {
3383 push_space = btrfs_item_offset(right, push_items - 1) -
3384 leaf_data_end(right);
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);
3391 }
3392
3393 btrfs_init_map_token(&token, right);
3394 right_nritems -= push_items;
3395 btrfs_set_header_nritems(right, right_nritems);
3396 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3397 for (i = 0; i < right_nritems; i++) {
3398 push_space = push_space - btrfs_token_item_size(&token, i);
3399 btrfs_set_token_item_offset(&token, i, push_space);
3400 }
3401
3402 btrfs_mark_buffer_dirty(trans, left);
3403 if (right_nritems)
3404 btrfs_mark_buffer_dirty(trans, right);
3405 else
3406 btrfs_clear_buffer_dirty(trans, right);
3407
3408 btrfs_item_key(right, &disk_key, 0);
3409 fixup_low_keys(trans, path, &disk_key, 1);
3410
3411 /* then fixup the leaf pointer in the path */
3412 if (path->slots[0] < push_items) {
3413 path->slots[0] += old_left_nritems;
3414 btrfs_tree_unlock(path->nodes[0]);
3415 free_extent_buffer(path->nodes[0]);
3416 path->nodes[0] = left;
3417 path->slots[1] -= 1;
3418 } else {
3419 btrfs_tree_unlock(left);
3420 free_extent_buffer(left);
3421 path->slots[0] -= push_items;
3422 }
3423 BUG_ON(path->slots[0] < 0);
3424 return ret;
3425 out:
3426 btrfs_tree_unlock(left);
3427 free_extent_buffer(left);
3428 return ret;
3429 }
3430
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
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
3438 */
3439 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3440 *root, struct btrfs_path *path, int min_data_size,
3441 int data_size, int empty, u32 max_slot)
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
3460 btrfs_assert_tree_write_locked(path->nodes[1]);
3461
3462 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3463 if (IS_ERR(left))
3464 return PTR_ERR(left);
3465
3466 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3467
3468 free_space = btrfs_leaf_free_space(left);
3469 if (free_space < data_size) {
3470 ret = 1;
3471 goto out;
3472 }
3473
3474 ret = btrfs_cow_block(trans, root, left,
3475 path->nodes[1], slot - 1, &left,
3476 BTRFS_NESTING_LEFT_COW);
3477 if (ret) {
3478 /* we hit -ENOSPC, but it isn't fatal here */
3479 if (ret == -ENOSPC)
3480 ret = 1;
3481 goto out;
3482 }
3483
3484 if (check_sibling_keys(left, right)) {
3485 ret = -EUCLEAN;
3486 btrfs_abort_transaction(trans, ret);
3487 goto out;
3488 }
3489 return __push_leaf_left(trans, path, min_data_size, empty, left,
3490 free_space, right_nritems, max_slot);
3491 out:
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.
3500 */
3501 static 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)
3506 {
3507 struct btrfs_fs_info *fs_info = trans->fs_info;
3508 int data_copy_size;
3509 int rt_data_off;
3510 int i;
3511 int ret;
3512 struct btrfs_disk_key disk_key;
3513 struct btrfs_map_token token;
3514
3515 nritems = nritems - mid;
3516 btrfs_set_header_nritems(right, nritems);
3517 data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3518
3519 copy_leaf_items(right, l, 0, mid, nritems);
3520
3521 copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
3522 leaf_data_end(l), data_copy_size);
3523
3524 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3525
3526 btrfs_init_map_token(&token, right);
3527 for (i = 0; i < nritems; i++) {
3528 u32 ioff;
3529
3530 ioff = btrfs_token_item_offset(&token, i);
3531 btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3532 }
3533
3534 btrfs_set_header_nritems(l, mid);
3535 btrfs_item_key(right, &disk_key, 0);
3536 ret = insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3537 if (ret < 0)
3538 return ret;
3539
3540 btrfs_mark_buffer_dirty(trans, right);
3541 btrfs_mark_buffer_dirty(trans, l);
3542 BUG_ON(path->slots[0] != slot);
3543
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);
3556
3557 return 0;
3558 }
3559
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 */
3570 static 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;
3579 int space_needed = data_size;
3580
3581 slot = path->slots[0];
3582 if (slot < btrfs_header_nritems(path->nodes[0]))
3583 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3584
3585 /*
3586 * try to push all the items after our slot into the
3587 * right leaf
3588 */
3589 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
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
3604 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3605 return 0;
3606
3607 /* try to push all the items before our slot into the next leaf */
3608 slot = path->slots[0];
3609 space_needed = data_size;
3610 if (slot > 0)
3611 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3612 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
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
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.
3627 *
3628 * returns 0 if all went well and < 0 on failure.
3629 */
3630 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3631 struct btrfs_root *root,
3632 const struct btrfs_key *ins_key,
3633 struct btrfs_path *path, int data_size,
3634 int extend)
3635 {
3636 struct btrfs_disk_key disk_key;
3637 struct extent_buffer *l;
3638 u32 nritems;
3639 int mid;
3640 int slot;
3641 struct extent_buffer *right;
3642 struct btrfs_fs_info *fs_info = root->fs_info;
3643 int ret = 0;
3644 int wret;
3645 int split;
3646 int num_doubles = 0;
3647 int tried_avoid_double = 0;
3648
3649 l = path->nodes[0];
3650 slot = path->slots[0];
3651 if (extend && data_size + btrfs_item_size(l, slot) +
3652 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3653 return -EOVERFLOW;
3654
3655 /* first try to make some room by pushing left and right */
3656 if (data_size && path->nodes[1]) {
3657 int space_needed = data_size;
3658
3659 if (slot < btrfs_header_nritems(l))
3660 space_needed -= btrfs_leaf_free_space(l);
3661
3662 wret = push_leaf_right(trans, root, path, space_needed,
3663 space_needed, 0, 0);
3664 if (wret < 0)
3665 return wret;
3666 if (wret) {
3667 space_needed = data_size;
3668 if (slot > 0)
3669 space_needed -= btrfs_leaf_free_space(l);
3670 wret = push_leaf_left(trans, root, path, space_needed,
3671 space_needed, 0, (u32)-1);
3672 if (wret < 0)
3673 return wret;
3674 }
3675 l = path->nodes[0];
3676
3677 /* did the pushes work? */
3678 if (btrfs_leaf_free_space(l) >= data_size)
3679 return 0;
3680 }
3681
3682 if (!path->nodes[1]) {
3683 ret = insert_new_root(trans, root, path, 1);
3684 if (ret)
3685 return ret;
3686 }
3687 again:
3688 split = 1;
3689 l = path->nodes[0];
3690 slot = path->slots[0];
3691 nritems = btrfs_header_nritems(l);
3692 mid = (nritems + 1) / 2;
3693
3694 if (mid <= slot) {
3695 if (nritems == 1 ||
3696 leaf_space_used(l, mid, nritems - mid) + data_size >
3697 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3698 if (slot >= nritems) {
3699 split = 0;
3700 } else {
3701 mid = slot;
3702 if (mid != nritems &&
3703 leaf_space_used(l, mid, nritems - mid) +
3704 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3705 if (data_size && !tried_avoid_double)
3706 goto push_for_double;
3707 split = 2;
3708 }
3709 }
3710 }
3711 } else {
3712 if (leaf_space_used(l, 0, mid) + data_size >
3713 BTRFS_LEAF_DATA_SIZE(fs_info)) {
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) +
3722 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3723 if (data_size && !tried_avoid_double)
3724 goto push_for_double;
3725 split = 2;
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
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 */
3744 right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3745 &disk_key, 0, l->start, 0, 0,
3746 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3747 BTRFS_NESTING_SPLIT);
3748 if (IS_ERR(right))
3749 return PTR_ERR(right);
3750
3751 root_add_used_bytes(root);
3752
3753 if (split == 0) {
3754 if (mid <= slot) {
3755 btrfs_set_header_nritems(right, 0);
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 }
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);
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 }
3777 btrfs_tree_unlock(path->nodes[0]);
3778 free_extent_buffer(path->nodes[0]);
3779 path->nodes[0] = right;
3780 path->slots[0] = 0;
3781 if (path->slots[1] == 0)
3782 fixup_low_keys(trans, path, &disk_key, 1);
3783 }
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 */
3789 return ret;
3790 }
3791
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 }
3798
3799 if (split == 2) {
3800 BUG_ON(num_doubles != 0);
3801 num_doubles++;
3802 goto again;
3803 }
3804
3805 return 0;
3806
3807 push_for_double:
3808 push_for_double_split(trans, root, path, data_size);
3809 tried_avoid_double = 1;
3810 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3811 return 0;
3812 goto again;
3813 }
3814
3815 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3816 struct btrfs_root *root,
3817 struct btrfs_path *path, int ins_len)
3818 {
3819 struct btrfs_key key;
3820 struct extent_buffer *leaf;
3821 struct btrfs_file_extent_item *fi;
3822 u64 extent_len = 0;
3823 u32 item_size;
3824 int ret;
3825
3826 leaf = path->nodes[0];
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
3832 if (btrfs_leaf_free_space(leaf) >= ins_len)
3833 return 0;
3834
3835 item_size = btrfs_item_size(leaf, path->slots[0]);
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 }
3841 btrfs_release_path(path);
3842
3843 path->keep_locks = 1;
3844 path->search_for_split = 1;
3845 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3846 path->search_for_split = 0;
3847 if (ret > 0)
3848 ret = -EAGAIN;
3849 if (ret < 0)
3850 goto err;
3851
3852 ret = -EAGAIN;
3853 leaf = path->nodes[0];
3854 /* if our item isn't there, return now */
3855 if (item_size != btrfs_item_size(leaf, path->slots[0]))
3856 goto err;
3857
3858 /* the leaf has changed, it now has room. return now */
3859 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3860 goto err;
3861
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;
3867 }
3868
3869 ret = split_leaf(trans, root, &key, path, ins_len, 1);
3870 if (ret)
3871 goto err;
3872
3873 path->keep_locks = 0;
3874 btrfs_unlock_up_safe(path, 1);
3875 return 0;
3876 err:
3877 path->keep_locks = 0;
3878 return ret;
3879 }
3880
3881 static noinline int split_item(struct btrfs_trans_handle *trans,
3882 struct btrfs_path *path,
3883 const struct btrfs_key *new_key,
3884 unsigned long split_offset)
3885 {
3886 struct extent_buffer *leaf;
3887 int orig_slot, slot;
3888 char *buf;
3889 u32 nritems;
3890 u32 item_size;
3891 u32 orig_offset;
3892 struct btrfs_disk_key disk_key;
3893
3894 leaf = path->nodes[0];
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;
3901
3902 orig_slot = path->slots[0];
3903 orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3904 item_size = btrfs_item_size(leaf, path->slots[0]);
3905
3906 buf = kmalloc(item_size, GFP_NOFS);
3907 if (!buf)
3908 return -ENOMEM;
3909
3910 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3911 path->slots[0]), item_size);
3912
3913 slot = path->slots[0] + 1;
3914 nritems = btrfs_header_nritems(leaf);
3915 if (slot != nritems) {
3916 /* shift the items */
3917 memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3918 }
3919
3920 btrfs_cpu_key_to_disk(&disk_key, new_key);
3921 btrfs_set_item_key(leaf, &disk_key, slot);
3922
3923 btrfs_set_item_offset(leaf, slot, orig_offset);
3924 btrfs_set_item_size(leaf, slot, item_size - split_offset);
3925
3926 btrfs_set_item_offset(leaf, orig_slot,
3927 orig_offset + item_size - split_offset);
3928 btrfs_set_item_size(leaf, orig_slot, split_offset);
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);
3941 btrfs_mark_buffer_dirty(trans, leaf);
3942
3943 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3944 kfree(buf);
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 */
3963 int btrfs_split_item(struct btrfs_trans_handle *trans,
3964 struct btrfs_root *root,
3965 struct btrfs_path *path,
3966 const struct btrfs_key *new_key,
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
3975 ret = split_item(trans, path, new_key, split_offset);
3976 return ret;
3977 }
3978
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 */
3985 void btrfs_truncate_item(struct btrfs_trans_handle *trans,
3986 struct btrfs_path *path, u32 new_size, int from_end)
3987 {
3988 int slot;
3989 struct extent_buffer *leaf;
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;
3996 struct btrfs_map_token token;
3997
3998 leaf = path->nodes[0];
3999 slot = path->slots[0];
4000
4001 old_size = btrfs_item_size(leaf, slot);
4002 if (old_size == new_size)
4003 return;
4004
4005 nritems = btrfs_header_nritems(leaf);
4006 data_end = leaf_data_end(leaf);
4007
4008 old_data_start = btrfs_item_offset(leaf, slot);
4009
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 */
4019 btrfs_init_map_token(&token, leaf);
4020 for (i = slot; i < nritems; i++) {
4021 u32 ioff;
4022
4023 ioff = btrfs_token_item_offset(&token, i);
4024 btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4025 }
4026
4027 /* shift the data */
4028 if (from_end) {
4029 memmove_leaf_data(leaf, data_end + size_diff, data_end,
4030 old_data_start + new_size - data_end);
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,
4050 (unsigned long)fi,
4051 BTRFS_FILE_EXTENT_INLINE_DATA_START);
4052 }
4053 }
4054
4055 memmove_leaf_data(leaf, data_end + size_diff, data_end,
4056 old_data_start - data_end);
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)
4062 fixup_low_keys(trans, path, &disk_key, 1);
4063 }
4064
4065 btrfs_set_item_size(leaf, slot, new_size);
4066 btrfs_mark_buffer_dirty(trans, leaf);
4067
4068 if (btrfs_leaf_free_space(leaf) < 0) {
4069 btrfs_print_leaf(leaf);
4070 BUG();
4071 }
4072 }
4073
4074 /*
4075 * make the item pointed to by the path bigger, data_size is the added size.
4076 */
4077 void btrfs_extend_item(struct btrfs_trans_handle *trans,
4078 struct btrfs_path *path, u32 data_size)
4079 {
4080 int slot;
4081 struct extent_buffer *leaf;
4082 u32 nritems;
4083 unsigned int data_end;
4084 unsigned int old_data;
4085 unsigned int old_size;
4086 int i;
4087 struct btrfs_map_token token;
4088
4089 leaf = path->nodes[0];
4090
4091 nritems = btrfs_header_nritems(leaf);
4092 data_end = leaf_data_end(leaf);
4093
4094 if (btrfs_leaf_free_space(leaf) < data_size) {
4095 btrfs_print_leaf(leaf);
4096 BUG();
4097 }
4098 slot = path->slots[0];
4099 old_data = btrfs_item_data_end(leaf, slot);
4100
4101 BUG_ON(slot < 0);
4102 if (slot >= nritems) {
4103 btrfs_print_leaf(leaf);
4104 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4105 slot, nritems);
4106 BUG();
4107 }
4108
4109 /*
4110 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4111 */
4112 /* first correct the data pointers */
4113 btrfs_init_map_token(&token, leaf);
4114 for (i = slot; i < nritems; i++) {
4115 u32 ioff;
4116
4117 ioff = btrfs_token_item_offset(&token, i);
4118 btrfs_set_token_item_offset(&token, i, ioff - data_size);
4119 }
4120
4121 /* shift the data */
4122 memmove_leaf_data(leaf, data_end - data_size, data_end,
4123 old_data - data_end);
4124
4125 data_end = old_data;
4126 old_size = btrfs_item_size(leaf, slot);
4127 btrfs_set_item_size(leaf, slot, old_size + data_size);
4128 btrfs_mark_buffer_dirty(trans, leaf);
4129
4130 if (btrfs_leaf_free_space(leaf) < 0) {
4131 btrfs_print_leaf(leaf);
4132 BUG();
4133 }
4134 }
4135
4136 /*
4137 * Make space in the node before inserting one or more items.
4138 *
4139 * @trans: transaction handle
4140 * @root: root we are inserting items to
4141 * @path: points to the leaf/slot where we are going to insert new items
4142 * @batch: information about the batch of items to insert
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
4146 */
4147 static void setup_items_for_insert(struct btrfs_trans_handle *trans,
4148 struct btrfs_root *root, struct btrfs_path *path,
4149 const struct btrfs_item_batch *batch)
4150 {
4151 struct btrfs_fs_info *fs_info = root->fs_info;
4152 int i;
4153 u32 nritems;
4154 unsigned int data_end;
4155 struct btrfs_disk_key disk_key;
4156 struct extent_buffer *leaf;
4157 int slot;
4158 struct btrfs_map_token token;
4159 u32 total_size;
4160
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 */
4166 if (path->slots[0] == 0) {
4167 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4168 fixup_low_keys(trans, path, &disk_key, 1);
4169 }
4170 btrfs_unlock_up_safe(path, 1);
4171
4172 leaf = path->nodes[0];
4173 slot = path->slots[0];
4174
4175 nritems = btrfs_header_nritems(leaf);
4176 data_end = leaf_data_end(leaf);
4177 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4178
4179 if (btrfs_leaf_free_space(leaf) < total_size) {
4180 btrfs_print_leaf(leaf);
4181 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4182 total_size, btrfs_leaf_free_space(leaf));
4183 BUG();
4184 }
4185
4186 btrfs_init_map_token(&token, leaf);
4187 if (slot != nritems) {
4188 unsigned int old_data = btrfs_item_data_end(leaf, slot);
4189
4190 if (old_data < data_end) {
4191 btrfs_print_leaf(leaf);
4192 btrfs_crit(fs_info,
4193 "item at slot %d with data offset %u beyond data end of leaf %u",
4194 slot, old_data, data_end);
4195 BUG();
4196 }
4197 /*
4198 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4199 */
4200 /* first correct the data pointers */
4201 for (i = slot; i < nritems; i++) {
4202 u32 ioff;
4203
4204 ioff = btrfs_token_item_offset(&token, i);
4205 btrfs_set_token_item_offset(&token, i,
4206 ioff - batch->total_data_size);
4207 }
4208 /* shift the items */
4209 memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4210
4211 /* shift the data */
4212 memmove_leaf_data(leaf, data_end - batch->total_data_size,
4213 data_end, old_data - data_end);
4214 data_end = old_data;
4215 }
4216
4217 /* setup the item for the new data */
4218 for (i = 0; i < batch->nr; i++) {
4219 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4220 btrfs_set_item_key(leaf, &disk_key, slot + i);
4221 data_end -= batch->data_sizes[i];
4222 btrfs_set_token_item_offset(&token, slot + i, data_end);
4223 btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4224 }
4225
4226 btrfs_set_header_nritems(leaf, nritems + batch->nr);
4227 btrfs_mark_buffer_dirty(trans, leaf);
4228
4229 if (btrfs_leaf_free_space(leaf) < 0) {
4230 btrfs_print_leaf(leaf);
4231 BUG();
4232 }
4233 }
4234
4235 /*
4236 * Insert a new item into a leaf.
4237 *
4238 * @trans: Transaction handle.
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 */
4244 void btrfs_setup_item_for_insert(struct btrfs_trans_handle *trans,
4245 struct btrfs_root *root,
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
4257 setup_items_for_insert(trans, root, path, &batch);
4258 }
4259
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 */
4264 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4265 struct btrfs_root *root,
4266 struct btrfs_path *path,
4267 const struct btrfs_item_batch *batch)
4268 {
4269 int ret = 0;
4270 int slot;
4271 u32 total_size;
4272
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);
4275 if (ret == 0)
4276 return -EEXIST;
4277 if (ret < 0)
4278 return ret;
4279
4280 slot = path->slots[0];
4281 BUG_ON(slot < 0);
4282
4283 setup_items_for_insert(trans, root, path, batch);
4284 return 0;
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 */
4291 int 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)
4294 {
4295 int ret = 0;
4296 struct btrfs_path *path;
4297 struct extent_buffer *leaf;
4298 unsigned long ptr;
4299
4300 path = btrfs_alloc_path();
4301 if (!path)
4302 return -ENOMEM;
4303 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4304 if (!ret) {
4305 leaf = path->nodes[0];
4306 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4307 write_extent_buffer(leaf, data, ptr, data_size);
4308 btrfs_mark_buffer_dirty(trans, leaf);
4309 }
4310 btrfs_free_path(path);
4311 return ret;
4312 }
4313
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 */
4322 int 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];
4332 item_size = btrfs_item_size(leaf, path->slots[0]);
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]++;
4339 btrfs_setup_item_for_insert(trans, root, path, new_key, item_size);
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
4348 /*
4349 * delete the pointer from a given node.
4350 *
4351 * the tree should have been previously balanced so the deletion does not
4352 * empty a node.
4353 *
4354 * This is exported for use inside btrfs-progs, don't un-export it.
4355 */
4356 int btrfs_del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4357 struct btrfs_path *path, int level, int slot)
4358 {
4359 struct extent_buffer *parent = path->nodes[level];
4360 u32 nritems;
4361 int ret;
4362
4363 nritems = btrfs_header_nritems(parent);
4364 if (slot != nritems - 1) {
4365 if (level) {
4366 ret = btrfs_tree_mod_log_insert_move(parent, slot,
4367 slot + 1, nritems - slot - 1);
4368 if (ret < 0) {
4369 btrfs_abort_transaction(trans, ret);
4370 return ret;
4371 }
4372 }
4373 memmove_extent_buffer(parent,
4374 btrfs_node_key_ptr_offset(parent, slot),
4375 btrfs_node_key_ptr_offset(parent, slot + 1),
4376 sizeof(struct btrfs_key_ptr) *
4377 (nritems - slot - 1));
4378 } else if (level) {
4379 ret = btrfs_tree_mod_log_insert_key(parent, slot,
4380 BTRFS_MOD_LOG_KEY_REMOVE);
4381 if (ret < 0) {
4382 btrfs_abort_transaction(trans, ret);
4383 return ret;
4384 }
4385 }
4386
4387 nritems--;
4388 btrfs_set_header_nritems(parent, nritems);
4389 if (nritems == 0 && parent == root->node) {
4390 BUG_ON(btrfs_header_level(root->node) != 1);
4391 /* just turn the root into a leaf and break */
4392 btrfs_set_header_level(root->node, 0);
4393 } else if (slot == 0) {
4394 struct btrfs_disk_key disk_key;
4395
4396 btrfs_node_key(parent, &disk_key, 0);
4397 fixup_low_keys(trans, path, &disk_key, level + 1);
4398 }
4399 btrfs_mark_buffer_dirty(trans, parent);
4400 return 0;
4401 }
4402
4403 /*
4404 * a helper function to delete the leaf pointed to by path->slots[1] and
4405 * path->nodes[1].
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 */
4413 static 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)
4417 {
4418 int ret;
4419
4420 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4421 ret = btrfs_del_ptr(trans, root, path, 1, path->slots[1]);
4422 if (ret < 0)
4423 return ret;
4424
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
4431 root_sub_used_bytes(root);
4432
4433 atomic_inc(&leaf->refs);
4434 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4435 free_extent_buffer_stale(leaf);
4436 return 0;
4437 }
4438 /*
4439 * delete the item at the leaf level in path. If that empties
4440 * the leaf, remove it from the tree
4441 */
4442 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4443 struct btrfs_path *path, int slot, int nr)
4444 {
4445 struct btrfs_fs_info *fs_info = root->fs_info;
4446 struct extent_buffer *leaf;
4447 int ret = 0;
4448 int wret;
4449 u32 nritems;
4450
4451 leaf = path->nodes[0];
4452 nritems = btrfs_header_nritems(leaf);
4453
4454 if (slot + nr != nritems) {
4455 const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4456 const int data_end = leaf_data_end(leaf);
4457 struct btrfs_map_token token;
4458 u32 dsize = 0;
4459 int i;
4460
4461 for (i = 0; i < nr; i++)
4462 dsize += btrfs_item_size(leaf, slot + i);
4463
4464 memmove_leaf_data(leaf, data_end + dsize, data_end,
4465 last_off - data_end);
4466
4467 btrfs_init_map_token(&token, leaf);
4468 for (i = slot + nr; i < nritems; i++) {
4469 u32 ioff;
4470
4471 ioff = btrfs_token_item_offset(&token, i);
4472 btrfs_set_token_item_offset(&token, i, ioff + dsize);
4473 }
4474
4475 memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4476 }
4477 btrfs_set_header_nritems(leaf, nritems - nr);
4478 nritems -= nr;
4479
4480 /* delete the leaf if we've emptied it */
4481 if (nritems == 0) {
4482 if (leaf == root->node) {
4483 btrfs_set_header_level(leaf, 0);
4484 } else {
4485 btrfs_clear_buffer_dirty(trans, leaf);
4486 ret = btrfs_del_leaf(trans, root, path, leaf);
4487 if (ret < 0)
4488 return ret;
4489 }
4490 } else {
4491 int used = leaf_space_used(leaf, 0, nritems);
4492 if (slot == 0) {
4493 struct btrfs_disk_key disk_key;
4494
4495 btrfs_item_key(leaf, &disk_key, 0);
4496 fixup_low_keys(trans, path, &disk_key, 1);
4497 }
4498
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 */
4507 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4508 u32 min_push_space;
4509
4510 /* push_leaf_left fixes the path.
4511 * make sure the path still points to our leaf
4512 * for possible call to btrfs_del_ptr below
4513 */
4514 slot = path->slots[1];
4515 atomic_inc(&leaf->refs);
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);
4524 if (wret < 0 && wret != -ENOSPC)
4525 ret = wret;
4526
4527 if (path->nodes[0] == leaf &&
4528 btrfs_header_nritems(leaf)) {
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);
4543 if (wret < 0 && wret != -ENOSPC)
4544 ret = wret;
4545 }
4546
4547 if (btrfs_header_nritems(leaf) == 0) {
4548 path->slots[1] = slot;
4549 ret = btrfs_del_leaf(trans, root, path, leaf);
4550 if (ret < 0)
4551 return ret;
4552 free_extent_buffer(leaf);
4553 ret = 0;
4554 } else {
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)
4561 btrfs_mark_buffer_dirty(trans, leaf);
4562 free_extent_buffer(leaf);
4563 }
4564 } else {
4565 btrfs_mark_buffer_dirty(trans, leaf);
4566 }
4567 }
4568 return ret;
4569 }
4570
4571 /*
4572 * A helper function to walk down the tree starting at min_key, and looking
4573 * for nodes or leaves that are have a minimum transaction id.
4574 * This is used by the btree defrag code, and tree logging
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 *
4580 * This honors path->lowest_level to prevent descent past a given level
4581 * of the tree.
4582 *
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 *
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 */
4590 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4591 struct btrfs_path *path,
4592 u64 min_trans)
4593 {
4594 struct extent_buffer *cur;
4595 struct btrfs_key found_key;
4596 int slot;
4597 int sret;
4598 u32 nritems;
4599 int level;
4600 int ret = 1;
4601 int keep_locks = path->keep_locks;
4602
4603 ASSERT(!path->nowait);
4604 path->keep_locks = 1;
4605 again:
4606 cur = btrfs_read_lock_root_node(root);
4607 level = btrfs_header_level(cur);
4608 WARN_ON(path->nodes[level]);
4609 path->nodes[level] = cur;
4610 path->locks[level] = BTRFS_READ_LOCK;
4611
4612 if (btrfs_header_generation(cur) < min_trans) {
4613 ret = 1;
4614 goto out;
4615 }
4616 while (1) {
4617 nritems = btrfs_header_nritems(cur);
4618 level = btrfs_header_level(cur);
4619 sret = btrfs_bin_search(cur, 0, min_key, &slot);
4620 if (sret < 0) {
4621 ret = sret;
4622 goto out;
4623 }
4624
4625 /* at the lowest level, we're done, setup the path and exit */
4626 if (level == path->lowest_level) {
4627 if (slot >= nritems)
4628 goto find_next_key;
4629 ret = 0;
4630 path->slots[level] = slot;
4631 btrfs_item_key_to_cpu(cur, &found_key, slot);
4632 goto out;
4633 }
4634 if (sret && slot > 0)
4635 slot--;
4636 /*
4637 * check this node pointer against the min_trans parameters.
4638 * If it is too old, skip to the next one.
4639 */
4640 while (slot < nritems) {
4641 u64 gen;
4642
4643 gen = btrfs_node_ptr_generation(cur, slot);
4644 if (gen < min_trans) {
4645 slot++;
4646 continue;
4647 }
4648 break;
4649 }
4650 find_next_key:
4651 /*
4652 * we didn't find a candidate key in this node, walk forward
4653 * and find another one
4654 */
4655 if (slot >= nritems) {
4656 path->slots[level] = slot;
4657 sret = btrfs_find_next_key(root, path, min_key, level,
4658 min_trans);
4659 if (sret == 0) {
4660 btrfs_release_path(path);
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;
4671 goto out;
4672 }
4673 cur = btrfs_read_node_slot(cur, slot);
4674 if (IS_ERR(cur)) {
4675 ret = PTR_ERR(cur);
4676 goto out;
4677 }
4678
4679 btrfs_tree_read_lock(cur);
4680
4681 path->locks[level - 1] = BTRFS_READ_LOCK;
4682 path->nodes[level - 1] = cur;
4683 unlock_up(path, level, 1, 0, NULL);
4684 }
4685 out:
4686 path->keep_locks = keep_locks;
4687 if (ret == 0) {
4688 btrfs_unlock_up_safe(path, path->lowest_level + 1);
4689 memcpy(min_key, &found_key, sizeof(found_key));
4690 }
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
4697 * tree based on the current path and the min_trans parameters.
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 */
4705 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4706 struct btrfs_key *key, int level, u64 min_trans)
4707 {
4708 int slot;
4709 struct extent_buffer *c;
4710
4711 WARN_ON(!path->keep_locks && !path->skip_locking);
4712 while (level < BTRFS_MAX_LEVEL) {
4713 if (!path->nodes[level])
4714 return 1;
4715
4716 slot = path->slots[level] + 1;
4717 c = path->nodes[level];
4718 next:
4719 if (slot >= btrfs_header_nritems(c)) {
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])
4725 return 1;
4726
4727 if (path->locks[level + 1] || path->skip_locking) {
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;
4739 btrfs_release_path(path);
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;
4752 }
4753
4754 if (level == 0)
4755 btrfs_item_key_to_cpu(c, key, slot);
4756 else {
4757 u64 gen = btrfs_node_ptr_generation(c, slot);
4758
4759 if (gen < min_trans) {
4760 slot++;
4761 goto next;
4762 }
4763 btrfs_node_key_to_cpu(c, key, slot);
4764 }
4765 return 0;
4766 }
4767 return 1;
4768 }
4769
4770 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4771 u64 time_seq)
4772 {
4773 int slot;
4774 int level;
4775 struct extent_buffer *c;
4776 struct extent_buffer *next;
4777 struct btrfs_fs_info *fs_info = root->fs_info;
4778 struct btrfs_key key;
4779 bool need_commit_sem = false;
4780 u32 nritems;
4781 int ret;
4782 int i;
4783
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);
4790
4791 nritems = btrfs_header_nritems(path->nodes[0]);
4792 if (nritems == 0)
4793 return 1;
4794
4795 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4796 again:
4797 level = 1;
4798 next = NULL;
4799 btrfs_release_path(path);
4800
4801 path->keep_locks = 1;
4802
4803 if (time_seq) {
4804 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4805 } else {
4806 if (path->need_commit_sem) {
4807 path->need_commit_sem = 0;
4808 need_commit_sem = true;
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 }
4817 }
4818 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4819 }
4820 path->keep_locks = 0;
4821
4822 if (ret < 0)
4823 goto done;
4824
4825 nritems = btrfs_header_nritems(path->nodes[0]);
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 */
4832 if (nritems > 0 && path->slots[0] < nritems - 1) {
4833 if (ret == 0)
4834 path->slots[0]++;
4835 ret = 0;
4836 goto done;
4837 }
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 }
4856
4857 while (level < BTRFS_MAX_LEVEL) {
4858 if (!path->nodes[level]) {
4859 ret = 1;
4860 goto done;
4861 }
4862
4863 slot = path->slots[level] + 1;
4864 c = path->nodes[level];
4865 if (slot >= btrfs_header_nritems(c)) {
4866 level++;
4867 if (level == BTRFS_MAX_LEVEL) {
4868 ret = 1;
4869 goto done;
4870 }
4871 continue;
4872 }
4873
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;
4887 }
4888
4889 next = c;
4890 ret = read_block_for_search(root, path, &next, level,
4891 slot, &key);
4892 if (ret == -EAGAIN && !path->nowait)
4893 goto again;
4894
4895 if (ret < 0) {
4896 btrfs_release_path(path);
4897 goto done;
4898 }
4899
4900 if (!path->skip_locking) {
4901 ret = btrfs_try_tree_read_lock(next);
4902 if (!ret && path->nowait) {
4903 ret = -EAGAIN;
4904 goto done;
4905 }
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 */
4914 free_extent_buffer(next);
4915 btrfs_release_path(path);
4916 cond_resched();
4917 goto again;
4918 }
4919 if (!ret)
4920 btrfs_tree_read_lock(next);
4921 }
4922 break;
4923 }
4924 path->slots[level] = slot;
4925 while (1) {
4926 level--;
4927 path->nodes[level] = next;
4928 path->slots[level] = 0;
4929 if (!path->skip_locking)
4930 path->locks[level] = BTRFS_READ_LOCK;
4931 if (!level)
4932 break;
4933
4934 ret = read_block_for_search(root, path, &next, level,
4935 0, &key);
4936 if (ret == -EAGAIN && !path->nowait)
4937 goto again;
4938
4939 if (ret < 0) {
4940 btrfs_release_path(path);
4941 goto done;
4942 }
4943
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 }
4954 }
4955 ret = 0;
4956 done:
4957 unlock_up(path, 0, 1, 0, NULL);
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 }
4967
4968 return ret;
4969 }
4970
4971 int 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
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 */
4985 int 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;
4991 u32 nritems;
4992 int ret;
4993
4994 while (1) {
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];
5003 nritems = btrfs_header_nritems(leaf);
5004 if (nritems == 0)
5005 return 1;
5006 if (path->slots[0] == nritems)
5007 path->slots[0]--;
5008
5009 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5010 if (found_key.objectid < min_objectid)
5011 break;
5012 if (found_key.type == type)
5013 return 0;
5014 if (found_key.objectid == min_objectid &&
5015 found_key.type < type)
5016 break;
5017 }
5018 return 1;
5019 }
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 */
5027 int 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) {
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 }
5062
5063 int __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
5073 void __cold btrfs_ctree_exit(void)
5074 {
5075 kmem_cache_destroy(btrfs_path_cachep);
5076 }