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