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