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