GNU Linux-libre 4.9.308-gnu1
[releases.git] / fs / btrfs / ctree.c
1 /*
2  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/rbtree.h>
22 #include <linux/vmalloc.h>
23 #include "ctree.h"
24 #include "disk-io.h"
25 #include "transaction.h"
26 #include "print-tree.h"
27 #include "locking.h"
28
29 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30                       *root, struct btrfs_path *path, int level);
31 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
32                       *root, struct btrfs_key *ins_key,
33                       struct btrfs_path *path, int data_size, int extend);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35                           struct btrfs_root *root, struct extent_buffer *dst,
36                           struct extent_buffer *src, int empty);
37 static int balance_node_right(struct btrfs_trans_handle *trans,
38                               struct btrfs_root *root,
39                               struct extent_buffer *dst_buf,
40                               struct extent_buffer *src_buf);
41 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
42                     int level, int slot);
43 static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
44                                  struct extent_buffer *eb);
45
46 struct btrfs_path *btrfs_alloc_path(void)
47 {
48         return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
49 }
50
51 /*
52  * set all locked nodes in the path to blocking locks.  This should
53  * be done before scheduling
54  */
55 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
56 {
57         int i;
58         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
59                 if (!p->nodes[i] || !p->locks[i])
60                         continue;
61                 btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
62                 if (p->locks[i] == BTRFS_READ_LOCK)
63                         p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
64                 else if (p->locks[i] == BTRFS_WRITE_LOCK)
65                         p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
66         }
67 }
68
69 /*
70  * reset all the locked nodes in the patch to spinning locks.
71  *
72  * held is used to keep lockdep happy, when lockdep is enabled
73  * we set held to a blocking lock before we go around and
74  * retake all the spinlocks in the path.  You can safely use NULL
75  * for held
76  */
77 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
78                                         struct extent_buffer *held, int held_rw)
79 {
80         int i;
81
82         if (held) {
83                 btrfs_set_lock_blocking_rw(held, held_rw);
84                 if (held_rw == BTRFS_WRITE_LOCK)
85                         held_rw = BTRFS_WRITE_LOCK_BLOCKING;
86                 else if (held_rw == BTRFS_READ_LOCK)
87                         held_rw = BTRFS_READ_LOCK_BLOCKING;
88         }
89         btrfs_set_path_blocking(p);
90
91         for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
92                 if (p->nodes[i] && p->locks[i]) {
93                         btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
94                         if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
95                                 p->locks[i] = BTRFS_WRITE_LOCK;
96                         else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
97                                 p->locks[i] = BTRFS_READ_LOCK;
98                 }
99         }
100
101         if (held)
102                 btrfs_clear_lock_blocking_rw(held, held_rw);
103 }
104
105 /* this also releases the path */
106 void btrfs_free_path(struct btrfs_path *p)
107 {
108         if (!p)
109                 return;
110         btrfs_release_path(p);
111         kmem_cache_free(btrfs_path_cachep, p);
112 }
113
114 /*
115  * path release drops references on the extent buffers in the path
116  * and it drops any locks held by this path
117  *
118  * It is safe to call this on paths that no locks or extent buffers held.
119  */
120 noinline void btrfs_release_path(struct btrfs_path *p)
121 {
122         int i;
123
124         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
125                 p->slots[i] = 0;
126                 if (!p->nodes[i])
127                         continue;
128                 if (p->locks[i]) {
129                         btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
130                         p->locks[i] = 0;
131                 }
132                 free_extent_buffer(p->nodes[i]);
133                 p->nodes[i] = NULL;
134         }
135 }
136
137 /*
138  * safely gets a reference on the root node of a tree.  A lock
139  * is not taken, so a concurrent writer may put a different node
140  * at the root of the tree.  See btrfs_lock_root_node for the
141  * looping required.
142  *
143  * The extent buffer returned by this has a reference taken, so
144  * it won't disappear.  It may stop being the root of the tree
145  * at any time because there are no locks held.
146  */
147 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
148 {
149         struct extent_buffer *eb;
150
151         while (1) {
152                 rcu_read_lock();
153                 eb = rcu_dereference(root->node);
154
155                 /*
156                  * RCU really hurts here, we could free up the root node because
157                  * it was COWed but we may not get the new root node yet so do
158                  * the inc_not_zero dance and if it doesn't work then
159                  * synchronize_rcu and try again.
160                  */
161                 if (atomic_inc_not_zero(&eb->refs)) {
162                         rcu_read_unlock();
163                         break;
164                 }
165                 rcu_read_unlock();
166                 synchronize_rcu();
167         }
168         return eb;
169 }
170
171 /* loop around taking references on and locking the root node of the
172  * tree until you end up with a lock on the root.  A locked buffer
173  * is returned, with a reference held.
174  */
175 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
176 {
177         struct extent_buffer *eb;
178
179         while (1) {
180                 eb = btrfs_root_node(root);
181                 btrfs_tree_lock(eb);
182                 if (eb == root->node)
183                         break;
184                 btrfs_tree_unlock(eb);
185                 free_extent_buffer(eb);
186         }
187         return eb;
188 }
189
190 /* loop around taking references on and locking the root node of the
191  * tree until you end up with a lock on the root.  A locked buffer
192  * is returned, with a reference held.
193  */
194 static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
195 {
196         struct extent_buffer *eb;
197
198         while (1) {
199                 eb = btrfs_root_node(root);
200                 btrfs_tree_read_lock(eb);
201                 if (eb == root->node)
202                         break;
203                 btrfs_tree_read_unlock(eb);
204                 free_extent_buffer(eb);
205         }
206         return eb;
207 }
208
209 /* cowonly root (everything not a reference counted cow subvolume), just get
210  * put onto a simple dirty list.  transaction.c walks this to make sure they
211  * get properly updated on disk.
212  */
213 static void add_root_to_dirty_list(struct btrfs_root *root)
214 {
215         if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
216             !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
217                 return;
218
219         spin_lock(&root->fs_info->trans_lock);
220         if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
221                 /* Want the extent tree to be the last on the list */
222                 if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
223                         list_move_tail(&root->dirty_list,
224                                        &root->fs_info->dirty_cowonly_roots);
225                 else
226                         list_move(&root->dirty_list,
227                                   &root->fs_info->dirty_cowonly_roots);
228         }
229         spin_unlock(&root->fs_info->trans_lock);
230 }
231
232 /*
233  * used by snapshot creation to make a copy of a root for a tree with
234  * a given objectid.  The buffer with the new root node is returned in
235  * cow_ret, and this func returns zero on success or a negative error code.
236  */
237 int btrfs_copy_root(struct btrfs_trans_handle *trans,
238                       struct btrfs_root *root,
239                       struct extent_buffer *buf,
240                       struct extent_buffer **cow_ret, u64 new_root_objectid)
241 {
242         struct extent_buffer *cow;
243         int ret = 0;
244         int level;
245         struct btrfs_disk_key disk_key;
246
247         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
248                 trans->transid != root->fs_info->running_transaction->transid);
249         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
250                 trans->transid != root->last_trans);
251
252         level = btrfs_header_level(buf);
253         if (level == 0)
254                 btrfs_item_key(buf, &disk_key, 0);
255         else
256                 btrfs_node_key(buf, &disk_key, 0);
257
258         cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
259                         &disk_key, level, buf->start, 0);
260         if (IS_ERR(cow))
261                 return PTR_ERR(cow);
262
263         copy_extent_buffer(cow, buf, 0, 0, cow->len);
264         btrfs_set_header_bytenr(cow, cow->start);
265         btrfs_set_header_generation(cow, trans->transid);
266         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
267         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
268                                      BTRFS_HEADER_FLAG_RELOC);
269         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
270                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
271         else
272                 btrfs_set_header_owner(cow, new_root_objectid);
273
274         write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
275                             BTRFS_FSID_SIZE);
276
277         WARN_ON(btrfs_header_generation(buf) > trans->transid);
278         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
279                 ret = btrfs_inc_ref(trans, root, cow, 1);
280         else
281                 ret = btrfs_inc_ref(trans, root, cow, 0);
282         if (ret) {
283                 btrfs_tree_unlock(cow);
284                 free_extent_buffer(cow);
285                 btrfs_abort_transaction(trans, ret);
286                 return ret;
287         }
288
289         btrfs_mark_buffer_dirty(cow);
290         *cow_ret = cow;
291         return 0;
292 }
293
294 enum mod_log_op {
295         MOD_LOG_KEY_REPLACE,
296         MOD_LOG_KEY_ADD,
297         MOD_LOG_KEY_REMOVE,
298         MOD_LOG_KEY_REMOVE_WHILE_FREEING,
299         MOD_LOG_KEY_REMOVE_WHILE_MOVING,
300         MOD_LOG_MOVE_KEYS,
301         MOD_LOG_ROOT_REPLACE,
302 };
303
304 struct tree_mod_move {
305         int dst_slot;
306         int nr_items;
307 };
308
309 struct tree_mod_root {
310         u64 logical;
311         u8 level;
312 };
313
314 struct tree_mod_elem {
315         struct rb_node node;
316         u64 logical;
317         u64 seq;
318         enum mod_log_op op;
319
320         /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
321         int slot;
322
323         /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
324         u64 generation;
325
326         /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
327         struct btrfs_disk_key key;
328         u64 blockptr;
329
330         /* this is used for op == MOD_LOG_MOVE_KEYS */
331         struct tree_mod_move move;
332
333         /* this is used for op == MOD_LOG_ROOT_REPLACE */
334         struct tree_mod_root old_root;
335 };
336
337 /*
338  * Pull a new tree mod seq number for our operation.
339  */
340 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
341 {
342         return atomic64_inc_return(&fs_info->tree_mod_seq);
343 }
344
345 /*
346  * This adds a new blocker to the tree mod log's blocker list if the @elem
347  * passed does not already have a sequence number set. So when a caller expects
348  * to record tree modifications, it should ensure to set elem->seq to zero
349  * before calling btrfs_get_tree_mod_seq.
350  * Returns a fresh, unused tree log modification sequence number, even if no new
351  * blocker was added.
352  */
353 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
354                            struct seq_list *elem)
355 {
356         write_lock(&fs_info->tree_mod_log_lock);
357         if (!elem->seq) {
358                 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
359                 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
360         }
361         write_unlock(&fs_info->tree_mod_log_lock);
362
363         return elem->seq;
364 }
365
366 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
367                             struct seq_list *elem)
368 {
369         struct rb_root *tm_root;
370         struct rb_node *node;
371         struct rb_node *next;
372         struct seq_list *cur_elem;
373         struct tree_mod_elem *tm;
374         u64 min_seq = (u64)-1;
375         u64 seq_putting = elem->seq;
376
377         if (!seq_putting)
378                 return;
379
380         write_lock(&fs_info->tree_mod_log_lock);
381         list_del(&elem->list);
382         elem->seq = 0;
383
384         list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
385                 if (cur_elem->seq < min_seq) {
386                         if (seq_putting > cur_elem->seq) {
387                                 /*
388                                  * blocker with lower sequence number exists, we
389                                  * cannot remove anything from the log
390                                  */
391                                 write_unlock(&fs_info->tree_mod_log_lock);
392                                 return;
393                         }
394                         min_seq = cur_elem->seq;
395                 }
396         }
397
398         /*
399          * anything that's lower than the lowest existing (read: blocked)
400          * sequence number can be removed from the tree.
401          */
402         tm_root = &fs_info->tree_mod_log;
403         for (node = rb_first(tm_root); node; node = next) {
404                 next = rb_next(node);
405                 tm = container_of(node, struct tree_mod_elem, node);
406                 if (tm->seq >= min_seq)
407                         continue;
408                 rb_erase(node, tm_root);
409                 kfree(tm);
410         }
411         write_unlock(&fs_info->tree_mod_log_lock);
412 }
413
414 /*
415  * key order of the log:
416  *       node/leaf start address -> sequence
417  *
418  * The 'start address' is the logical address of the *new* root node
419  * for root replace operations, or the logical address of the affected
420  * block for all other operations.
421  *
422  * Note: must be called with write lock for fs_info::tree_mod_log_lock.
423  */
424 static noinline int
425 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
426 {
427         struct rb_root *tm_root;
428         struct rb_node **new;
429         struct rb_node *parent = NULL;
430         struct tree_mod_elem *cur;
431
432         BUG_ON(!tm);
433
434         tm->seq = btrfs_inc_tree_mod_seq(fs_info);
435
436         tm_root = &fs_info->tree_mod_log;
437         new = &tm_root->rb_node;
438         while (*new) {
439                 cur = container_of(*new, struct tree_mod_elem, node);
440                 parent = *new;
441                 if (cur->logical < tm->logical)
442                         new = &((*new)->rb_left);
443                 else if (cur->logical > tm->logical)
444                         new = &((*new)->rb_right);
445                 else if (cur->seq < tm->seq)
446                         new = &((*new)->rb_left);
447                 else if (cur->seq > tm->seq)
448                         new = &((*new)->rb_right);
449                 else
450                         return -EEXIST;
451         }
452
453         rb_link_node(&tm->node, parent, new);
454         rb_insert_color(&tm->node, tm_root);
455         return 0;
456 }
457
458 /*
459  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
460  * returns zero with the tree_mod_log_lock acquired. The caller must hold
461  * this until all tree mod log insertions are recorded in the rb tree and then
462  * write unlock fs_info::tree_mod_log_lock.
463  */
464 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
465                                     struct extent_buffer *eb) {
466         smp_mb();
467         if (list_empty(&(fs_info)->tree_mod_seq_list))
468                 return 1;
469         if (eb && btrfs_header_level(eb) == 0)
470                 return 1;
471
472         write_lock(&fs_info->tree_mod_log_lock);
473         if (list_empty(&(fs_info)->tree_mod_seq_list)) {
474                 write_unlock(&fs_info->tree_mod_log_lock);
475                 return 1;
476         }
477
478         return 0;
479 }
480
481 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
482 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
483                                     struct extent_buffer *eb)
484 {
485         smp_mb();
486         if (list_empty(&(fs_info)->tree_mod_seq_list))
487                 return 0;
488         if (eb && btrfs_header_level(eb) == 0)
489                 return 0;
490
491         return 1;
492 }
493
494 static struct tree_mod_elem *
495 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
496                     enum mod_log_op op, gfp_t flags)
497 {
498         struct tree_mod_elem *tm;
499
500         tm = kzalloc(sizeof(*tm), flags);
501         if (!tm)
502                 return NULL;
503
504         tm->logical = eb->start;
505         if (op != MOD_LOG_KEY_ADD) {
506                 btrfs_node_key(eb, &tm->key, slot);
507                 tm->blockptr = btrfs_node_blockptr(eb, slot);
508         }
509         tm->op = op;
510         tm->slot = slot;
511         tm->generation = btrfs_node_ptr_generation(eb, slot);
512         RB_CLEAR_NODE(&tm->node);
513
514         return tm;
515 }
516
517 static noinline int
518 tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
519                         struct extent_buffer *eb, int slot,
520                         enum mod_log_op op, gfp_t flags)
521 {
522         struct tree_mod_elem *tm;
523         int ret;
524
525         if (!tree_mod_need_log(fs_info, eb))
526                 return 0;
527
528         tm = alloc_tree_mod_elem(eb, slot, op, flags);
529         if (!tm)
530                 return -ENOMEM;
531
532         if (tree_mod_dont_log(fs_info, eb)) {
533                 kfree(tm);
534                 return 0;
535         }
536
537         ret = __tree_mod_log_insert(fs_info, tm);
538         write_unlock(&eb->fs_info->tree_mod_log_lock);
539         if (ret)
540                 kfree(tm);
541
542         return ret;
543 }
544
545 static noinline int
546 tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
547                          struct extent_buffer *eb, int dst_slot, int src_slot,
548                          int nr_items, gfp_t flags)
549 {
550         struct tree_mod_elem *tm = NULL;
551         struct tree_mod_elem **tm_list = NULL;
552         int ret = 0;
553         int i;
554         int locked = 0;
555
556         if (!tree_mod_need_log(fs_info, eb))
557                 return 0;
558
559         tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), flags);
560         if (!tm_list)
561                 return -ENOMEM;
562
563         tm = kzalloc(sizeof(*tm), flags);
564         if (!tm) {
565                 ret = -ENOMEM;
566                 goto free_tms;
567         }
568
569         tm->logical = eb->start;
570         tm->slot = src_slot;
571         tm->move.dst_slot = dst_slot;
572         tm->move.nr_items = nr_items;
573         tm->op = MOD_LOG_MOVE_KEYS;
574
575         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
576                 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
577                     MOD_LOG_KEY_REMOVE_WHILE_MOVING, flags);
578                 if (!tm_list[i]) {
579                         ret = -ENOMEM;
580                         goto free_tms;
581                 }
582         }
583
584         if (tree_mod_dont_log(fs_info, eb))
585                 goto free_tms;
586         locked = 1;
587
588         /*
589          * When we override something during the move, we log these removals.
590          * This can only happen when we move towards the beginning of the
591          * buffer, i.e. dst_slot < src_slot.
592          */
593         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
594                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
595                 if (ret)
596                         goto free_tms;
597         }
598
599         ret = __tree_mod_log_insert(fs_info, tm);
600         if (ret)
601                 goto free_tms;
602         write_unlock(&eb->fs_info->tree_mod_log_lock);
603         kfree(tm_list);
604
605         return 0;
606 free_tms:
607         for (i = 0; i < nr_items; i++) {
608                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
609                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
610                 kfree(tm_list[i]);
611         }
612         if (locked)
613                 write_unlock(&eb->fs_info->tree_mod_log_lock);
614         kfree(tm_list);
615         kfree(tm);
616
617         return ret;
618 }
619
620 static inline int
621 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
622                        struct tree_mod_elem **tm_list,
623                        int nritems)
624 {
625         int i, j;
626         int ret;
627
628         for (i = nritems - 1; i >= 0; i--) {
629                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
630                 if (ret) {
631                         for (j = nritems - 1; j > i; j--)
632                                 rb_erase(&tm_list[j]->node,
633                                          &fs_info->tree_mod_log);
634                         return ret;
635                 }
636         }
637
638         return 0;
639 }
640
641 static noinline int
642 tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
643                          struct extent_buffer *old_root,
644                          struct extent_buffer *new_root, gfp_t flags,
645                          int log_removal)
646 {
647         struct tree_mod_elem *tm = NULL;
648         struct tree_mod_elem **tm_list = NULL;
649         int nritems = 0;
650         int ret = 0;
651         int i;
652
653         if (!tree_mod_need_log(fs_info, NULL))
654                 return 0;
655
656         if (log_removal && btrfs_header_level(old_root) > 0) {
657                 nritems = btrfs_header_nritems(old_root);
658                 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
659                                   flags);
660                 if (!tm_list) {
661                         ret = -ENOMEM;
662                         goto free_tms;
663                 }
664                 for (i = 0; i < nritems; i++) {
665                         tm_list[i] = alloc_tree_mod_elem(old_root, i,
666                             MOD_LOG_KEY_REMOVE_WHILE_FREEING, flags);
667                         if (!tm_list[i]) {
668                                 ret = -ENOMEM;
669                                 goto free_tms;
670                         }
671                 }
672         }
673
674         tm = kzalloc(sizeof(*tm), flags);
675         if (!tm) {
676                 ret = -ENOMEM;
677                 goto free_tms;
678         }
679
680         tm->logical = new_root->start;
681         tm->old_root.logical = old_root->start;
682         tm->old_root.level = btrfs_header_level(old_root);
683         tm->generation = btrfs_header_generation(old_root);
684         tm->op = MOD_LOG_ROOT_REPLACE;
685
686         if (tree_mod_dont_log(fs_info, NULL))
687                 goto free_tms;
688
689         if (tm_list)
690                 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
691         if (!ret)
692                 ret = __tree_mod_log_insert(fs_info, tm);
693
694         write_unlock(&fs_info->tree_mod_log_lock);
695         if (ret)
696                 goto free_tms;
697         kfree(tm_list);
698
699         return ret;
700
701 free_tms:
702         if (tm_list) {
703                 for (i = 0; i < nritems; i++)
704                         kfree(tm_list[i]);
705                 kfree(tm_list);
706         }
707         kfree(tm);
708
709         return ret;
710 }
711
712 static struct tree_mod_elem *
713 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
714                       int smallest)
715 {
716         struct rb_root *tm_root;
717         struct rb_node *node;
718         struct tree_mod_elem *cur = NULL;
719         struct tree_mod_elem *found = NULL;
720
721         read_lock(&fs_info->tree_mod_log_lock);
722         tm_root = &fs_info->tree_mod_log;
723         node = tm_root->rb_node;
724         while (node) {
725                 cur = container_of(node, struct tree_mod_elem, node);
726                 if (cur->logical < start) {
727                         node = node->rb_left;
728                 } else if (cur->logical > start) {
729                         node = node->rb_right;
730                 } else if (cur->seq < min_seq) {
731                         node = node->rb_left;
732                 } else if (!smallest) {
733                         /* we want the node with the highest seq */
734                         if (found)
735                                 BUG_ON(found->seq > cur->seq);
736                         found = cur;
737                         node = node->rb_left;
738                 } else if (cur->seq > min_seq) {
739                         /* we want the node with the smallest seq */
740                         if (found)
741                                 BUG_ON(found->seq < cur->seq);
742                         found = cur;
743                         node = node->rb_right;
744                 } else {
745                         found = cur;
746                         break;
747                 }
748         }
749         read_unlock(&fs_info->tree_mod_log_lock);
750
751         return found;
752 }
753
754 /*
755  * this returns the element from the log with the smallest time sequence
756  * value that's in the log (the oldest log item). any element with a time
757  * sequence lower than min_seq will be ignored.
758  */
759 static struct tree_mod_elem *
760 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
761                            u64 min_seq)
762 {
763         return __tree_mod_log_search(fs_info, start, min_seq, 1);
764 }
765
766 /*
767  * this returns the element from the log with the largest time sequence
768  * value that's in the log (the most recent log item). any element with
769  * a time sequence lower than min_seq will be ignored.
770  */
771 static struct tree_mod_elem *
772 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
773 {
774         return __tree_mod_log_search(fs_info, start, min_seq, 0);
775 }
776
777 static noinline int
778 tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
779                      struct extent_buffer *src, unsigned long dst_offset,
780                      unsigned long src_offset, int nr_items)
781 {
782         int ret = 0;
783         struct tree_mod_elem **tm_list = NULL;
784         struct tree_mod_elem **tm_list_add, **tm_list_rem;
785         int i;
786         int locked = 0;
787
788         if (!tree_mod_need_log(fs_info, NULL))
789                 return 0;
790
791         if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
792                 return 0;
793
794         tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
795                           GFP_NOFS);
796         if (!tm_list)
797                 return -ENOMEM;
798
799         tm_list_add = tm_list;
800         tm_list_rem = tm_list + nr_items;
801         for (i = 0; i < nr_items; i++) {
802                 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
803                     MOD_LOG_KEY_REMOVE, GFP_NOFS);
804                 if (!tm_list_rem[i]) {
805                         ret = -ENOMEM;
806                         goto free_tms;
807                 }
808
809                 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
810                     MOD_LOG_KEY_ADD, GFP_NOFS);
811                 if (!tm_list_add[i]) {
812                         ret = -ENOMEM;
813                         goto free_tms;
814                 }
815         }
816
817         if (tree_mod_dont_log(fs_info, NULL))
818                 goto free_tms;
819         locked = 1;
820
821         for (i = 0; i < nr_items; i++) {
822                 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
823                 if (ret)
824                         goto free_tms;
825                 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
826                 if (ret)
827                         goto free_tms;
828         }
829
830         write_unlock(&fs_info->tree_mod_log_lock);
831         kfree(tm_list);
832
833         return 0;
834
835 free_tms:
836         for (i = 0; i < nr_items * 2; i++) {
837                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
838                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
839                 kfree(tm_list[i]);
840         }
841         if (locked)
842                 write_unlock(&fs_info->tree_mod_log_lock);
843         kfree(tm_list);
844
845         return ret;
846 }
847
848 static inline void
849 tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
850                      int dst_offset, int src_offset, int nr_items)
851 {
852         int ret;
853         ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
854                                        nr_items, GFP_NOFS);
855         BUG_ON(ret < 0);
856 }
857
858 static noinline void
859 tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
860                           struct extent_buffer *eb, int slot, int atomic)
861 {
862         int ret;
863
864         ret = tree_mod_log_insert_key(fs_info, eb, slot,
865                                         MOD_LOG_KEY_REPLACE,
866                                         atomic ? GFP_ATOMIC : GFP_NOFS);
867         BUG_ON(ret < 0);
868 }
869
870 static noinline int
871 tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
872 {
873         struct tree_mod_elem **tm_list = NULL;
874         int nritems = 0;
875         int i;
876         int ret = 0;
877
878         if (btrfs_header_level(eb) == 0)
879                 return 0;
880
881         if (!tree_mod_need_log(fs_info, NULL))
882                 return 0;
883
884         nritems = btrfs_header_nritems(eb);
885         tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
886         if (!tm_list)
887                 return -ENOMEM;
888
889         for (i = 0; i < nritems; i++) {
890                 tm_list[i] = alloc_tree_mod_elem(eb, i,
891                     MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
892                 if (!tm_list[i]) {
893                         ret = -ENOMEM;
894                         goto free_tms;
895                 }
896         }
897
898         if (tree_mod_dont_log(fs_info, eb))
899                 goto free_tms;
900
901         ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
902         write_unlock(&eb->fs_info->tree_mod_log_lock);
903         if (ret)
904                 goto free_tms;
905         kfree(tm_list);
906
907         return 0;
908
909 free_tms:
910         for (i = 0; i < nritems; i++)
911                 kfree(tm_list[i]);
912         kfree(tm_list);
913
914         return ret;
915 }
916
917 static noinline void
918 tree_mod_log_set_root_pointer(struct btrfs_root *root,
919                               struct extent_buffer *new_root_node,
920                               int log_removal)
921 {
922         int ret;
923         ret = tree_mod_log_insert_root(root->fs_info, root->node,
924                                        new_root_node, GFP_NOFS, log_removal);
925         BUG_ON(ret < 0);
926 }
927
928 /*
929  * check if the tree block can be shared by multiple trees
930  */
931 int btrfs_block_can_be_shared(struct btrfs_root *root,
932                               struct extent_buffer *buf)
933 {
934         /*
935          * Tree blocks not in reference counted trees and tree roots
936          * are never shared. If a block was allocated after the last
937          * snapshot and the block was not allocated by tree relocation,
938          * we know the block is not shared.
939          */
940         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
941             buf != root->node && buf != root->commit_root &&
942             (btrfs_header_generation(buf) <=
943              btrfs_root_last_snapshot(&root->root_item) ||
944              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
945                 return 1;
946 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
947         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
948             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
949                 return 1;
950 #endif
951         return 0;
952 }
953
954 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
955                                        struct btrfs_root *root,
956                                        struct extent_buffer *buf,
957                                        struct extent_buffer *cow,
958                                        int *last_ref)
959 {
960         u64 refs;
961         u64 owner;
962         u64 flags;
963         u64 new_flags = 0;
964         int ret;
965
966         /*
967          * Backrefs update rules:
968          *
969          * Always use full backrefs for extent pointers in tree block
970          * allocated by tree relocation.
971          *
972          * If a shared tree block is no longer referenced by its owner
973          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
974          * use full backrefs for extent pointers in tree block.
975          *
976          * If a tree block is been relocating
977          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
978          * use full backrefs for extent pointers in tree block.
979          * The reason for this is some operations (such as drop tree)
980          * are only allowed for blocks use full backrefs.
981          */
982
983         if (btrfs_block_can_be_shared(root, buf)) {
984                 ret = btrfs_lookup_extent_info(trans, root, buf->start,
985                                                btrfs_header_level(buf), 1,
986                                                &refs, &flags);
987                 if (ret)
988                         return ret;
989                 if (refs == 0) {
990                         ret = -EROFS;
991                         btrfs_handle_fs_error(root->fs_info, ret, NULL);
992                         return ret;
993                 }
994         } else {
995                 refs = 1;
996                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
997                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
998                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
999                 else
1000                         flags = 0;
1001         }
1002
1003         owner = btrfs_header_owner(buf);
1004         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
1005                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
1006
1007         if (refs > 1) {
1008                 if ((owner == root->root_key.objectid ||
1009                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
1010                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1011                         ret = btrfs_inc_ref(trans, root, buf, 1);
1012                         BUG_ON(ret); /* -ENOMEM */
1013
1014                         if (root->root_key.objectid ==
1015                             BTRFS_TREE_RELOC_OBJECTID) {
1016                                 ret = btrfs_dec_ref(trans, root, buf, 0);
1017                                 BUG_ON(ret); /* -ENOMEM */
1018                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1019                                 BUG_ON(ret); /* -ENOMEM */
1020                         }
1021                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
1022                 } else {
1023
1024                         if (root->root_key.objectid ==
1025                             BTRFS_TREE_RELOC_OBJECTID)
1026                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1027                         else
1028                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1029                         BUG_ON(ret); /* -ENOMEM */
1030                 }
1031                 if (new_flags != 0) {
1032                         int level = btrfs_header_level(buf);
1033
1034                         ret = btrfs_set_disk_extent_flags(trans, root,
1035                                                           buf->start,
1036                                                           buf->len,
1037                                                           new_flags, level, 0);
1038                         if (ret)
1039                                 return ret;
1040                 }
1041         } else {
1042                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
1043                         if (root->root_key.objectid ==
1044                             BTRFS_TREE_RELOC_OBJECTID)
1045                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1046                         else
1047                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1048                         BUG_ON(ret); /* -ENOMEM */
1049                         ret = btrfs_dec_ref(trans, root, buf, 1);
1050                         BUG_ON(ret); /* -ENOMEM */
1051                 }
1052                 clean_tree_block(trans, root->fs_info, buf);
1053                 *last_ref = 1;
1054         }
1055         return 0;
1056 }
1057
1058 /*
1059  * does the dirty work in cow of a single block.  The parent block (if
1060  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1061  * dirty and returned locked.  If you modify the block it needs to be marked
1062  * dirty again.
1063  *
1064  * search_start -- an allocation hint for the new block
1065  *
1066  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1067  * bytes the allocator should try to find free next to the block it returns.
1068  * This is just a hint and may be ignored by the allocator.
1069  */
1070 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1071                              struct btrfs_root *root,
1072                              struct extent_buffer *buf,
1073                              struct extent_buffer *parent, int parent_slot,
1074                              struct extent_buffer **cow_ret,
1075                              u64 search_start, u64 empty_size)
1076 {
1077         struct btrfs_disk_key disk_key;
1078         struct extent_buffer *cow;
1079         int level, ret;
1080         int last_ref = 0;
1081         int unlock_orig = 0;
1082         u64 parent_start = 0;
1083
1084         if (*cow_ret == buf)
1085                 unlock_orig = 1;
1086
1087         btrfs_assert_tree_locked(buf);
1088
1089         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1090                 trans->transid != root->fs_info->running_transaction->transid);
1091         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1092                 trans->transid != root->last_trans);
1093
1094         level = btrfs_header_level(buf);
1095
1096         if (level == 0)
1097                 btrfs_item_key(buf, &disk_key, 0);
1098         else
1099                 btrfs_node_key(buf, &disk_key, 0);
1100
1101         if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1102                 parent_start = parent->start;
1103
1104         cow = btrfs_alloc_tree_block(trans, root, parent_start,
1105                         root->root_key.objectid, &disk_key, level,
1106                         search_start, empty_size);
1107         if (IS_ERR(cow))
1108                 return PTR_ERR(cow);
1109
1110         /* cow is set to blocking by btrfs_init_new_buffer */
1111
1112         copy_extent_buffer(cow, buf, 0, 0, cow->len);
1113         btrfs_set_header_bytenr(cow, cow->start);
1114         btrfs_set_header_generation(cow, trans->transid);
1115         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1116         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1117                                      BTRFS_HEADER_FLAG_RELOC);
1118         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1119                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1120         else
1121                 btrfs_set_header_owner(cow, root->root_key.objectid);
1122
1123         write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
1124                             BTRFS_FSID_SIZE);
1125
1126         ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1127         if (ret) {
1128                 btrfs_tree_unlock(cow);
1129                 free_extent_buffer(cow);
1130                 btrfs_abort_transaction(trans, ret);
1131                 return ret;
1132         }
1133
1134         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1135                 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1136                 if (ret) {
1137                         btrfs_tree_unlock(cow);
1138                         free_extent_buffer(cow);
1139                         btrfs_abort_transaction(trans, ret);
1140                         return ret;
1141                 }
1142         }
1143
1144         if (buf == root->node) {
1145                 WARN_ON(parent && parent != buf);
1146                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1147                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1148                         parent_start = buf->start;
1149
1150                 extent_buffer_get(cow);
1151                 tree_mod_log_set_root_pointer(root, cow, 1);
1152                 rcu_assign_pointer(root->node, cow);
1153
1154                 btrfs_free_tree_block(trans, root, buf, parent_start,
1155                                       last_ref);
1156                 free_extent_buffer(buf);
1157                 add_root_to_dirty_list(root);
1158         } else {
1159                 WARN_ON(trans->transid != btrfs_header_generation(parent));
1160                 tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1161                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1162                 btrfs_set_node_blockptr(parent, parent_slot,
1163                                         cow->start);
1164                 btrfs_set_node_ptr_generation(parent, parent_slot,
1165                                               trans->transid);
1166                 btrfs_mark_buffer_dirty(parent);
1167                 if (last_ref) {
1168                         ret = tree_mod_log_free_eb(root->fs_info, buf);
1169                         if (ret) {
1170                                 btrfs_tree_unlock(cow);
1171                                 free_extent_buffer(cow);
1172                                 btrfs_abort_transaction(trans, ret);
1173                                 return ret;
1174                         }
1175                 }
1176                 btrfs_free_tree_block(trans, root, buf, parent_start,
1177                                       last_ref);
1178         }
1179         if (unlock_orig)
1180                 btrfs_tree_unlock(buf);
1181         free_extent_buffer_stale(buf);
1182         btrfs_mark_buffer_dirty(cow);
1183         *cow_ret = cow;
1184         return 0;
1185 }
1186
1187 /*
1188  * returns the logical address of the oldest predecessor of the given root.
1189  * entries older than time_seq are ignored.
1190  */
1191 static struct tree_mod_elem *
1192 __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
1193                            struct extent_buffer *eb_root, u64 time_seq)
1194 {
1195         struct tree_mod_elem *tm;
1196         struct tree_mod_elem *found = NULL;
1197         u64 root_logical = eb_root->start;
1198         int looped = 0;
1199
1200         if (!time_seq)
1201                 return NULL;
1202
1203         /*
1204          * the very last operation that's logged for a root is the
1205          * replacement operation (if it is replaced at all). this has
1206          * the logical address of the *new* root, making it the very
1207          * first operation that's logged for this root.
1208          */
1209         while (1) {
1210                 tm = tree_mod_log_search_oldest(fs_info, root_logical,
1211                                                 time_seq);
1212                 if (!looped && !tm)
1213                         return NULL;
1214                 /*
1215                  * if there are no tree operation for the oldest root, we simply
1216                  * return it. this should only happen if that (old) root is at
1217                  * level 0.
1218                  */
1219                 if (!tm)
1220                         break;
1221
1222                 /*
1223                  * if there's an operation that's not a root replacement, we
1224                  * found the oldest version of our root. normally, we'll find a
1225                  * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1226                  */
1227                 if (tm->op != MOD_LOG_ROOT_REPLACE)
1228                         break;
1229
1230                 found = tm;
1231                 root_logical = tm->old_root.logical;
1232                 looped = 1;
1233         }
1234
1235         /* if there's no old root to return, return what we found instead */
1236         if (!found)
1237                 found = tm;
1238
1239         return found;
1240 }
1241
1242 /*
1243  * tm is a pointer to the first operation to rewind within eb. then, all
1244  * previous operations will be rewound (until we reach something older than
1245  * time_seq).
1246  */
1247 static void
1248 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1249                       u64 time_seq, struct tree_mod_elem *first_tm)
1250 {
1251         u32 n;
1252         struct rb_node *next;
1253         struct tree_mod_elem *tm = first_tm;
1254         unsigned long o_dst;
1255         unsigned long o_src;
1256         unsigned long p_size = sizeof(struct btrfs_key_ptr);
1257
1258         n = btrfs_header_nritems(eb);
1259         read_lock(&fs_info->tree_mod_log_lock);
1260         while (tm && tm->seq >= time_seq) {
1261                 /*
1262                  * all the operations are recorded with the operator used for
1263                  * the modification. as we're going backwards, we do the
1264                  * opposite of each operation here.
1265                  */
1266                 switch (tm->op) {
1267                 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1268                         BUG_ON(tm->slot < n);
1269                         /* Fallthrough */
1270                 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1271                 case MOD_LOG_KEY_REMOVE:
1272                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1273                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1274                         btrfs_set_node_ptr_generation(eb, tm->slot,
1275                                                       tm->generation);
1276                         n++;
1277                         break;
1278                 case MOD_LOG_KEY_REPLACE:
1279                         BUG_ON(tm->slot >= n);
1280                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1281                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1282                         btrfs_set_node_ptr_generation(eb, tm->slot,
1283                                                       tm->generation);
1284                         break;
1285                 case MOD_LOG_KEY_ADD:
1286                         /* if a move operation is needed it's in the log */
1287                         n--;
1288                         break;
1289                 case MOD_LOG_MOVE_KEYS:
1290                         o_dst = btrfs_node_key_ptr_offset(tm->slot);
1291                         o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1292                         memmove_extent_buffer(eb, o_dst, o_src,
1293                                               tm->move.nr_items * p_size);
1294                         break;
1295                 case MOD_LOG_ROOT_REPLACE:
1296                         /*
1297                          * this operation is special. for roots, this must be
1298                          * handled explicitly before rewinding.
1299                          * for non-roots, this operation may exist if the node
1300                          * was a root: root A -> child B; then A gets empty and
1301                          * B is promoted to the new root. in the mod log, we'll
1302                          * have a root-replace operation for B, a tree block
1303                          * that is no root. we simply ignore that operation.
1304                          */
1305                         break;
1306                 }
1307                 next = rb_next(&tm->node);
1308                 if (!next)
1309                         break;
1310                 tm = container_of(next, struct tree_mod_elem, node);
1311                 if (tm->logical != first_tm->logical)
1312                         break;
1313         }
1314         read_unlock(&fs_info->tree_mod_log_lock);
1315         btrfs_set_header_nritems(eb, n);
1316 }
1317
1318 /*
1319  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1320  * is returned. If rewind operations happen, a fresh buffer is returned. The
1321  * returned buffer is always read-locked. If the returned buffer is not the
1322  * input buffer, the lock on the input buffer is released and the input buffer
1323  * is freed (its refcount is decremented).
1324  */
1325 static struct extent_buffer *
1326 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1327                     struct extent_buffer *eb, u64 time_seq)
1328 {
1329         struct extent_buffer *eb_rewin;
1330         struct tree_mod_elem *tm;
1331
1332         if (!time_seq)
1333                 return eb;
1334
1335         if (btrfs_header_level(eb) == 0)
1336                 return eb;
1337
1338         tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1339         if (!tm)
1340                 return eb;
1341
1342         btrfs_set_path_blocking(path);
1343         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1344
1345         if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1346                 BUG_ON(tm->slot != 0);
1347                 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start,
1348                                                 eb->len);
1349                 if (!eb_rewin) {
1350                         btrfs_tree_read_unlock_blocking(eb);
1351                         free_extent_buffer(eb);
1352                         return NULL;
1353                 }
1354                 btrfs_set_header_bytenr(eb_rewin, eb->start);
1355                 btrfs_set_header_backref_rev(eb_rewin,
1356                                              btrfs_header_backref_rev(eb));
1357                 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1358                 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1359         } else {
1360                 eb_rewin = btrfs_clone_extent_buffer(eb);
1361                 if (!eb_rewin) {
1362                         btrfs_tree_read_unlock_blocking(eb);
1363                         free_extent_buffer(eb);
1364                         return NULL;
1365                 }
1366         }
1367
1368         btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1369         btrfs_tree_read_unlock_blocking(eb);
1370         free_extent_buffer(eb);
1371
1372         btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1373                                        eb_rewin, btrfs_header_level(eb_rewin));
1374         btrfs_tree_read_lock(eb_rewin);
1375         __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1376         WARN_ON(btrfs_header_nritems(eb_rewin) >
1377                 BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
1378
1379         return eb_rewin;
1380 }
1381
1382 /*
1383  * get_old_root() rewinds the state of @root's root node to the given @time_seq
1384  * value. If there are no changes, the current root->root_node is returned. If
1385  * anything changed in between, there's a fresh buffer allocated on which the
1386  * rewind operations are done. In any case, the returned buffer is read locked.
1387  * Returns NULL on error (with no locks held).
1388  */
1389 static inline struct extent_buffer *
1390 get_old_root(struct btrfs_root *root, u64 time_seq)
1391 {
1392         struct tree_mod_elem *tm;
1393         struct extent_buffer *eb = NULL;
1394         struct extent_buffer *eb_root;
1395         u64 eb_root_owner = 0;
1396         struct extent_buffer *old;
1397         struct tree_mod_root *old_root = NULL;
1398         u64 old_generation = 0;
1399         u64 logical;
1400
1401         eb_root = btrfs_read_lock_root_node(root);
1402         tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
1403         if (!tm)
1404                 return eb_root;
1405
1406         if (tm->op == MOD_LOG_ROOT_REPLACE) {
1407                 old_root = &tm->old_root;
1408                 old_generation = tm->generation;
1409                 logical = old_root->logical;
1410         } else {
1411                 logical = eb_root->start;
1412         }
1413
1414         tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1415         if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1416                 btrfs_tree_read_unlock(eb_root);
1417                 free_extent_buffer(eb_root);
1418                 old = read_tree_block(root, logical, 0);
1419                 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1420                         if (!IS_ERR(old))
1421                                 free_extent_buffer(old);
1422                         btrfs_warn(root->fs_info,
1423                                 "failed to read tree block %llu from get_old_root", logical);
1424                 } else {
1425                         btrfs_tree_read_lock(old);
1426                         eb = btrfs_clone_extent_buffer(old);
1427                         btrfs_tree_read_unlock(old);
1428                         free_extent_buffer(old);
1429                 }
1430         } else if (old_root) {
1431                 eb_root_owner = btrfs_header_owner(eb_root);
1432                 btrfs_tree_read_unlock(eb_root);
1433                 free_extent_buffer(eb_root);
1434                 eb = alloc_dummy_extent_buffer(root->fs_info, logical,
1435                                         root->nodesize);
1436         } else {
1437                 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1438                 eb = btrfs_clone_extent_buffer(eb_root);
1439                 btrfs_tree_read_unlock_blocking(eb_root);
1440                 free_extent_buffer(eb_root);
1441         }
1442
1443         if (!eb)
1444                 return NULL;
1445         if (old_root) {
1446                 btrfs_set_header_bytenr(eb, eb->start);
1447                 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1448                 btrfs_set_header_owner(eb, eb_root_owner);
1449                 btrfs_set_header_level(eb, old_root->level);
1450                 btrfs_set_header_generation(eb, old_generation);
1451         }
1452         btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1453                                        btrfs_header_level(eb));
1454         btrfs_tree_read_lock(eb);
1455         if (tm)
1456                 __tree_mod_log_rewind(root->fs_info, eb, time_seq, tm);
1457         else
1458                 WARN_ON(btrfs_header_level(eb) != 0);
1459         WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
1460
1461         return eb;
1462 }
1463
1464 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1465 {
1466         struct tree_mod_elem *tm;
1467         int level;
1468         struct extent_buffer *eb_root = btrfs_root_node(root);
1469
1470         tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
1471         if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1472                 level = tm->old_root.level;
1473         } else {
1474                 level = btrfs_header_level(eb_root);
1475         }
1476         free_extent_buffer(eb_root);
1477
1478         return level;
1479 }
1480
1481 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1482                                    struct btrfs_root *root,
1483                                    struct extent_buffer *buf)
1484 {
1485         if (btrfs_is_testing(root->fs_info))
1486                 return 0;
1487
1488         /* ensure we can see the force_cow */
1489         smp_rmb();
1490
1491         /*
1492          * We do not need to cow a block if
1493          * 1) this block is not created or changed in this transaction;
1494          * 2) this block does not belong to TREE_RELOC tree;
1495          * 3) the root is not forced COW.
1496          *
1497          * What is forced COW:
1498          *    when we create snapshot during committing the transaction,
1499          *    after we've finished coping src root, we must COW the shared
1500          *    block to ensure the metadata consistency.
1501          */
1502         if (btrfs_header_generation(buf) == trans->transid &&
1503             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1504             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1505               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1506             !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1507                 return 0;
1508         return 1;
1509 }
1510
1511 /*
1512  * cows a single block, see __btrfs_cow_block for the real work.
1513  * This version of it has extra checks so that a block isn't COWed more than
1514  * once per transaction, as long as it hasn't been written yet
1515  */
1516 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1517                     struct btrfs_root *root, struct extent_buffer *buf,
1518                     struct extent_buffer *parent, int parent_slot,
1519                     struct extent_buffer **cow_ret)
1520 {
1521         u64 search_start;
1522         int ret;
1523
1524         if (trans->transaction != root->fs_info->running_transaction)
1525                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1526                        trans->transid,
1527                        root->fs_info->running_transaction->transid);
1528
1529         if (trans->transid != root->fs_info->generation)
1530                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1531                        trans->transid, root->fs_info->generation);
1532
1533         if (!should_cow_block(trans, root, buf)) {
1534                 trans->dirty = true;
1535                 *cow_ret = buf;
1536                 return 0;
1537         }
1538
1539         search_start = buf->start & ~((u64)SZ_1G - 1);
1540
1541         if (parent)
1542                 btrfs_set_lock_blocking(parent);
1543         btrfs_set_lock_blocking(buf);
1544
1545         ret = __btrfs_cow_block(trans, root, buf, parent,
1546                                  parent_slot, cow_ret, search_start, 0);
1547
1548         trace_btrfs_cow_block(root, buf, *cow_ret);
1549
1550         return ret;
1551 }
1552
1553 /*
1554  * helper function for defrag to decide if two blocks pointed to by a
1555  * node are actually close by
1556  */
1557 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1558 {
1559         if (blocknr < other && other - (blocknr + blocksize) < 32768)
1560                 return 1;
1561         if (blocknr > other && blocknr - (other + blocksize) < 32768)
1562                 return 1;
1563         return 0;
1564 }
1565
1566 /*
1567  * compare two keys in a memcmp fashion
1568  */
1569 static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1570 {
1571         struct btrfs_key k1;
1572
1573         btrfs_disk_key_to_cpu(&k1, disk);
1574
1575         return btrfs_comp_cpu_keys(&k1, k2);
1576 }
1577
1578 /*
1579  * same as comp_keys only with two btrfs_key's
1580  */
1581 int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1582 {
1583         if (k1->objectid > k2->objectid)
1584                 return 1;
1585         if (k1->objectid < k2->objectid)
1586                 return -1;
1587         if (k1->type > k2->type)
1588                 return 1;
1589         if (k1->type < k2->type)
1590                 return -1;
1591         if (k1->offset > k2->offset)
1592                 return 1;
1593         if (k1->offset < k2->offset)
1594                 return -1;
1595         return 0;
1596 }
1597
1598 /*
1599  * this is used by the defrag code to go through all the
1600  * leaves pointed to by a node and reallocate them so that
1601  * disk order is close to key order
1602  */
1603 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1604                        struct btrfs_root *root, struct extent_buffer *parent,
1605                        int start_slot, u64 *last_ret,
1606                        struct btrfs_key *progress)
1607 {
1608         struct extent_buffer *cur;
1609         u64 blocknr;
1610         u64 gen;
1611         u64 search_start = *last_ret;
1612         u64 last_block = 0;
1613         u64 other;
1614         u32 parent_nritems;
1615         int end_slot;
1616         int i;
1617         int err = 0;
1618         int parent_level;
1619         int uptodate;
1620         u32 blocksize;
1621         int progress_passed = 0;
1622         struct btrfs_disk_key disk_key;
1623
1624         parent_level = btrfs_header_level(parent);
1625
1626         WARN_ON(trans->transaction != root->fs_info->running_transaction);
1627         WARN_ON(trans->transid != root->fs_info->generation);
1628
1629         parent_nritems = btrfs_header_nritems(parent);
1630         blocksize = root->nodesize;
1631         end_slot = parent_nritems - 1;
1632
1633         if (parent_nritems <= 1)
1634                 return 0;
1635
1636         btrfs_set_lock_blocking(parent);
1637
1638         for (i = start_slot; i <= end_slot; i++) {
1639                 int close = 1;
1640
1641                 btrfs_node_key(parent, &disk_key, i);
1642                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1643                         continue;
1644
1645                 progress_passed = 1;
1646                 blocknr = btrfs_node_blockptr(parent, i);
1647                 gen = btrfs_node_ptr_generation(parent, i);
1648                 if (last_block == 0)
1649                         last_block = blocknr;
1650
1651                 if (i > 0) {
1652                         other = btrfs_node_blockptr(parent, i - 1);
1653                         close = close_blocks(blocknr, other, blocksize);
1654                 }
1655                 if (!close && i < end_slot) {
1656                         other = btrfs_node_blockptr(parent, i + 1);
1657                         close = close_blocks(blocknr, other, blocksize);
1658                 }
1659                 if (close) {
1660                         last_block = blocknr;
1661                         continue;
1662                 }
1663
1664                 cur = btrfs_find_tree_block(root->fs_info, blocknr);
1665                 if (cur)
1666                         uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1667                 else
1668                         uptodate = 0;
1669                 if (!cur || !uptodate) {
1670                         if (!cur) {
1671                                 cur = read_tree_block(root, blocknr, gen);
1672                                 if (IS_ERR(cur)) {
1673                                         return PTR_ERR(cur);
1674                                 } else if (!extent_buffer_uptodate(cur)) {
1675                                         free_extent_buffer(cur);
1676                                         return -EIO;
1677                                 }
1678                         } else if (!uptodate) {
1679                                 err = btrfs_read_buffer(cur, gen);
1680                                 if (err) {
1681                                         free_extent_buffer(cur);
1682                                         return err;
1683                                 }
1684                         }
1685                 }
1686                 if (search_start == 0)
1687                         search_start = last_block;
1688
1689                 btrfs_tree_lock(cur);
1690                 btrfs_set_lock_blocking(cur);
1691                 err = __btrfs_cow_block(trans, root, cur, parent, i,
1692                                         &cur, search_start,
1693                                         min(16 * blocksize,
1694                                             (end_slot - i) * blocksize));
1695                 if (err) {
1696                         btrfs_tree_unlock(cur);
1697                         free_extent_buffer(cur);
1698                         break;
1699                 }
1700                 search_start = cur->start;
1701                 last_block = cur->start;
1702                 *last_ret = search_start;
1703                 btrfs_tree_unlock(cur);
1704                 free_extent_buffer(cur);
1705         }
1706         return err;
1707 }
1708
1709
1710 /*
1711  * search for key in the extent_buffer.  The items start at offset p,
1712  * and they are item_size apart.  There are 'max' items in p.
1713  *
1714  * the slot in the array is returned via slot, and it points to
1715  * the place where you would insert key if it is not found in
1716  * the array.
1717  *
1718  * slot may point to max if the key is bigger than all of the keys
1719  */
1720 static noinline int generic_bin_search(struct extent_buffer *eb,
1721                                        unsigned long p,
1722                                        int item_size, struct btrfs_key *key,
1723                                        int max, int *slot)
1724 {
1725         int low = 0;
1726         int high = max;
1727         int mid;
1728         int ret;
1729         struct btrfs_disk_key *tmp = NULL;
1730         struct btrfs_disk_key unaligned;
1731         unsigned long offset;
1732         char *kaddr = NULL;
1733         unsigned long map_start = 0;
1734         unsigned long map_len = 0;
1735         int err;
1736
1737         if (low > high) {
1738                 btrfs_err(eb->fs_info,
1739                  "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1740                           __func__, low, high, eb->start,
1741                           btrfs_header_owner(eb), btrfs_header_level(eb));
1742                 return -EINVAL;
1743         }
1744
1745         while (low < high) {
1746                 mid = (low + high) / 2;
1747                 offset = p + mid * item_size;
1748
1749                 if (!kaddr || offset < map_start ||
1750                     (offset + sizeof(struct btrfs_disk_key)) >
1751                     map_start + map_len) {
1752
1753                         err = map_private_extent_buffer(eb, offset,
1754                                                 sizeof(struct btrfs_disk_key),
1755                                                 &kaddr, &map_start, &map_len);
1756
1757                         if (!err) {
1758                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1759                                                         map_start);
1760                         } else if (err == 1) {
1761                                 read_extent_buffer(eb, &unaligned,
1762                                                    offset, sizeof(unaligned));
1763                                 tmp = &unaligned;
1764                         } else {
1765                                 return err;
1766                         }
1767
1768                 } else {
1769                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
1770                                                         map_start);
1771                 }
1772                 ret = comp_keys(tmp, key);
1773
1774                 if (ret < 0)
1775                         low = mid + 1;
1776                 else if (ret > 0)
1777                         high = mid;
1778                 else {
1779                         *slot = mid;
1780                         return 0;
1781                 }
1782         }
1783         *slot = low;
1784         return 1;
1785 }
1786
1787 /*
1788  * simple bin_search frontend that does the right thing for
1789  * leaves vs nodes
1790  */
1791 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1792                       int level, int *slot)
1793 {
1794         if (level == 0)
1795                 return generic_bin_search(eb,
1796                                           offsetof(struct btrfs_leaf, items),
1797                                           sizeof(struct btrfs_item),
1798                                           key, btrfs_header_nritems(eb),
1799                                           slot);
1800         else
1801                 return generic_bin_search(eb,
1802                                           offsetof(struct btrfs_node, ptrs),
1803                                           sizeof(struct btrfs_key_ptr),
1804                                           key, btrfs_header_nritems(eb),
1805                                           slot);
1806 }
1807
1808 int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1809                      int level, int *slot)
1810 {
1811         return bin_search(eb, key, level, slot);
1812 }
1813
1814 static void root_add_used(struct btrfs_root *root, u32 size)
1815 {
1816         spin_lock(&root->accounting_lock);
1817         btrfs_set_root_used(&root->root_item,
1818                             btrfs_root_used(&root->root_item) + size);
1819         spin_unlock(&root->accounting_lock);
1820 }
1821
1822 static void root_sub_used(struct btrfs_root *root, u32 size)
1823 {
1824         spin_lock(&root->accounting_lock);
1825         btrfs_set_root_used(&root->root_item,
1826                             btrfs_root_used(&root->root_item) - size);
1827         spin_unlock(&root->accounting_lock);
1828 }
1829
1830 /* given a node and slot number, this reads the blocks it points to.  The
1831  * extent buffer is returned with a reference taken (but unlocked).
1832  */
1833 static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
1834                                    struct extent_buffer *parent, int slot)
1835 {
1836         int level = btrfs_header_level(parent);
1837         struct extent_buffer *eb;
1838
1839         if (slot < 0 || slot >= btrfs_header_nritems(parent))
1840                 return ERR_PTR(-ENOENT);
1841
1842         BUG_ON(level == 0);
1843
1844         eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1845                              btrfs_node_ptr_generation(parent, slot));
1846         if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1847                 free_extent_buffer(eb);
1848                 eb = ERR_PTR(-EIO);
1849         }
1850
1851         return eb;
1852 }
1853
1854 /*
1855  * node level balancing, used to make sure nodes are in proper order for
1856  * item deletion.  We balance from the top down, so we have to make sure
1857  * that a deletion won't leave an node completely empty later on.
1858  */
1859 static noinline int balance_level(struct btrfs_trans_handle *trans,
1860                          struct btrfs_root *root,
1861                          struct btrfs_path *path, int level)
1862 {
1863         struct extent_buffer *right = NULL;
1864         struct extent_buffer *mid;
1865         struct extent_buffer *left = NULL;
1866         struct extent_buffer *parent = NULL;
1867         int ret = 0;
1868         int wret;
1869         int pslot;
1870         int orig_slot = path->slots[level];
1871         u64 orig_ptr;
1872
1873         if (level == 0)
1874                 return 0;
1875
1876         mid = path->nodes[level];
1877
1878         WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1879                 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1880         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1881
1882         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1883
1884         if (level < BTRFS_MAX_LEVEL - 1) {
1885                 parent = path->nodes[level + 1];
1886                 pslot = path->slots[level + 1];
1887         }
1888
1889         /*
1890          * deal with the case where there is only one pointer in the root
1891          * by promoting the node below to a root
1892          */
1893         if (!parent) {
1894                 struct extent_buffer *child;
1895
1896                 if (btrfs_header_nritems(mid) != 1)
1897                         return 0;
1898
1899                 /* promote the child to a root */
1900                 child = read_node_slot(root, mid, 0);
1901                 if (IS_ERR(child)) {
1902                         ret = PTR_ERR(child);
1903                         btrfs_handle_fs_error(root->fs_info, ret, NULL);
1904                         goto enospc;
1905                 }
1906
1907                 btrfs_tree_lock(child);
1908                 btrfs_set_lock_blocking(child);
1909                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1910                 if (ret) {
1911                         btrfs_tree_unlock(child);
1912                         free_extent_buffer(child);
1913                         goto enospc;
1914                 }
1915
1916                 tree_mod_log_set_root_pointer(root, child, 1);
1917                 rcu_assign_pointer(root->node, child);
1918
1919                 add_root_to_dirty_list(root);
1920                 btrfs_tree_unlock(child);
1921
1922                 path->locks[level] = 0;
1923                 path->nodes[level] = NULL;
1924                 clean_tree_block(trans, root->fs_info, mid);
1925                 btrfs_tree_unlock(mid);
1926                 /* once for the path */
1927                 free_extent_buffer(mid);
1928
1929                 root_sub_used(root, mid->len);
1930                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1931                 /* once for the root ptr */
1932                 free_extent_buffer_stale(mid);
1933                 return 0;
1934         }
1935         if (btrfs_header_nritems(mid) >
1936             BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1937                 return 0;
1938
1939         left = read_node_slot(root, parent, pslot - 1);
1940         if (IS_ERR(left))
1941                 left = NULL;
1942
1943         if (left) {
1944                 btrfs_tree_lock(left);
1945                 btrfs_set_lock_blocking(left);
1946                 wret = btrfs_cow_block(trans, root, left,
1947                                        parent, pslot - 1, &left);
1948                 if (wret) {
1949                         ret = wret;
1950                         goto enospc;
1951                 }
1952         }
1953
1954         right = read_node_slot(root, parent, pslot + 1);
1955         if (IS_ERR(right))
1956                 right = NULL;
1957
1958         if (right) {
1959                 btrfs_tree_lock(right);
1960                 btrfs_set_lock_blocking(right);
1961                 wret = btrfs_cow_block(trans, root, right,
1962                                        parent, pslot + 1, &right);
1963                 if (wret) {
1964                         ret = wret;
1965                         goto enospc;
1966                 }
1967         }
1968
1969         /* first, try to make some room in the middle buffer */
1970         if (left) {
1971                 orig_slot += btrfs_header_nritems(left);
1972                 wret = push_node_left(trans, root, left, mid, 1);
1973                 if (wret < 0)
1974                         ret = wret;
1975         }
1976
1977         /*
1978          * then try to empty the right most buffer into the middle
1979          */
1980         if (right) {
1981                 wret = push_node_left(trans, root, mid, right, 1);
1982                 if (wret < 0 && wret != -ENOSPC)
1983                         ret = wret;
1984                 if (btrfs_header_nritems(right) == 0) {
1985                         clean_tree_block(trans, root->fs_info, right);
1986                         btrfs_tree_unlock(right);
1987                         del_ptr(root, path, level + 1, pslot + 1);
1988                         root_sub_used(root, right->len);
1989                         btrfs_free_tree_block(trans, root, right, 0, 1);
1990                         free_extent_buffer_stale(right);
1991                         right = NULL;
1992                 } else {
1993                         struct btrfs_disk_key right_key;
1994                         btrfs_node_key(right, &right_key, 0);
1995                         tree_mod_log_set_node_key(root->fs_info, parent,
1996                                                   pslot + 1, 0);
1997                         btrfs_set_node_key(parent, &right_key, pslot + 1);
1998                         btrfs_mark_buffer_dirty(parent);
1999                 }
2000         }
2001         if (btrfs_header_nritems(mid) == 1) {
2002                 /*
2003                  * we're not allowed to leave a node with one item in the
2004                  * tree during a delete.  A deletion from lower in the tree
2005                  * could try to delete the only pointer in this node.
2006                  * So, pull some keys from the left.
2007                  * There has to be a left pointer at this point because
2008                  * otherwise we would have pulled some pointers from the
2009                  * right
2010                  */
2011                 if (!left) {
2012                         ret = -EROFS;
2013                         btrfs_handle_fs_error(root->fs_info, ret, NULL);
2014                         goto enospc;
2015                 }
2016                 wret = balance_node_right(trans, root, mid, left);
2017                 if (wret < 0) {
2018                         ret = wret;
2019                         goto enospc;
2020                 }
2021                 if (wret == 1) {
2022                         wret = push_node_left(trans, root, left, mid, 1);
2023                         if (wret < 0)
2024                                 ret = wret;
2025                 }
2026                 BUG_ON(wret == 1);
2027         }
2028         if (btrfs_header_nritems(mid) == 0) {
2029                 clean_tree_block(trans, root->fs_info, mid);
2030                 btrfs_tree_unlock(mid);
2031                 del_ptr(root, path, level + 1, pslot);
2032                 root_sub_used(root, mid->len);
2033                 btrfs_free_tree_block(trans, root, mid, 0, 1);
2034                 free_extent_buffer_stale(mid);
2035                 mid = NULL;
2036         } else {
2037                 /* update the parent key to reflect our changes */
2038                 struct btrfs_disk_key mid_key;
2039                 btrfs_node_key(mid, &mid_key, 0);
2040                 tree_mod_log_set_node_key(root->fs_info, parent,
2041                                           pslot, 0);
2042                 btrfs_set_node_key(parent, &mid_key, pslot);
2043                 btrfs_mark_buffer_dirty(parent);
2044         }
2045
2046         /* update the path */
2047         if (left) {
2048                 if (btrfs_header_nritems(left) > orig_slot) {
2049                         extent_buffer_get(left);
2050                         /* left was locked after cow */
2051                         path->nodes[level] = left;
2052                         path->slots[level + 1] -= 1;
2053                         path->slots[level] = orig_slot;
2054                         if (mid) {
2055                                 btrfs_tree_unlock(mid);
2056                                 free_extent_buffer(mid);
2057                         }
2058                 } else {
2059                         orig_slot -= btrfs_header_nritems(left);
2060                         path->slots[level] = orig_slot;
2061                 }
2062         }
2063         /* double check we haven't messed things up */
2064         if (orig_ptr !=
2065             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2066                 BUG();
2067 enospc:
2068         if (right) {
2069                 btrfs_tree_unlock(right);
2070                 free_extent_buffer(right);
2071         }
2072         if (left) {
2073                 if (path->nodes[level] != left)
2074                         btrfs_tree_unlock(left);
2075                 free_extent_buffer(left);
2076         }
2077         return ret;
2078 }
2079
2080 /* Node balancing for insertion.  Here we only split or push nodes around
2081  * when they are completely full.  This is also done top down, so we
2082  * have to be pessimistic.
2083  */
2084 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2085                                           struct btrfs_root *root,
2086                                           struct btrfs_path *path, int level)
2087 {
2088         struct extent_buffer *right = NULL;
2089         struct extent_buffer *mid;
2090         struct extent_buffer *left = NULL;
2091         struct extent_buffer *parent = NULL;
2092         int ret = 0;
2093         int wret;
2094         int pslot;
2095         int orig_slot = path->slots[level];
2096
2097         if (level == 0)
2098                 return 1;
2099
2100         mid = path->nodes[level];
2101         WARN_ON(btrfs_header_generation(mid) != trans->transid);
2102
2103         if (level < BTRFS_MAX_LEVEL - 1) {
2104                 parent = path->nodes[level + 1];
2105                 pslot = path->slots[level + 1];
2106         }
2107
2108         if (!parent)
2109                 return 1;
2110
2111         left = read_node_slot(root, parent, pslot - 1);
2112         if (IS_ERR(left))
2113                 left = NULL;
2114
2115         /* first, try to make some room in the middle buffer */
2116         if (left) {
2117                 u32 left_nr;
2118
2119                 btrfs_tree_lock(left);
2120                 btrfs_set_lock_blocking(left);
2121
2122                 left_nr = btrfs_header_nritems(left);
2123                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
2124                         wret = 1;
2125                 } else {
2126                         ret = btrfs_cow_block(trans, root, left, parent,
2127                                               pslot - 1, &left);
2128                         if (ret)
2129                                 wret = 1;
2130                         else {
2131                                 wret = push_node_left(trans, root,
2132                                                       left, mid, 0);
2133                         }
2134                 }
2135                 if (wret < 0)
2136                         ret = wret;
2137                 if (wret == 0) {
2138                         struct btrfs_disk_key disk_key;
2139                         orig_slot += left_nr;
2140                         btrfs_node_key(mid, &disk_key, 0);
2141                         tree_mod_log_set_node_key(root->fs_info, parent,
2142                                                   pslot, 0);
2143                         btrfs_set_node_key(parent, &disk_key, pslot);
2144                         btrfs_mark_buffer_dirty(parent);
2145                         if (btrfs_header_nritems(left) > orig_slot) {
2146                                 path->nodes[level] = left;
2147                                 path->slots[level + 1] -= 1;
2148                                 path->slots[level] = orig_slot;
2149                                 btrfs_tree_unlock(mid);
2150                                 free_extent_buffer(mid);
2151                         } else {
2152                                 orig_slot -=
2153                                         btrfs_header_nritems(left);
2154                                 path->slots[level] = orig_slot;
2155                                 btrfs_tree_unlock(left);
2156                                 free_extent_buffer(left);
2157                         }
2158                         return 0;
2159                 }
2160                 btrfs_tree_unlock(left);
2161                 free_extent_buffer(left);
2162         }
2163         right = read_node_slot(root, parent, pslot + 1);
2164         if (IS_ERR(right))
2165                 right = NULL;
2166
2167         /*
2168          * then try to empty the right most buffer into the middle
2169          */
2170         if (right) {
2171                 u32 right_nr;
2172
2173                 btrfs_tree_lock(right);
2174                 btrfs_set_lock_blocking(right);
2175
2176                 right_nr = btrfs_header_nritems(right);
2177                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
2178                         wret = 1;
2179                 } else {
2180                         ret = btrfs_cow_block(trans, root, right,
2181                                               parent, pslot + 1,
2182                                               &right);
2183                         if (ret)
2184                                 wret = 1;
2185                         else {
2186                                 wret = balance_node_right(trans, root,
2187                                                           right, mid);
2188                         }
2189                 }
2190                 if (wret < 0)
2191                         ret = wret;
2192                 if (wret == 0) {
2193                         struct btrfs_disk_key disk_key;
2194
2195                         btrfs_node_key(right, &disk_key, 0);
2196                         tree_mod_log_set_node_key(root->fs_info, parent,
2197                                                   pslot + 1, 0);
2198                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
2199                         btrfs_mark_buffer_dirty(parent);
2200
2201                         if (btrfs_header_nritems(mid) <= orig_slot) {
2202                                 path->nodes[level] = right;
2203                                 path->slots[level + 1] += 1;
2204                                 path->slots[level] = orig_slot -
2205                                         btrfs_header_nritems(mid);
2206                                 btrfs_tree_unlock(mid);
2207                                 free_extent_buffer(mid);
2208                         } else {
2209                                 btrfs_tree_unlock(right);
2210                                 free_extent_buffer(right);
2211                         }
2212                         return 0;
2213                 }
2214                 btrfs_tree_unlock(right);
2215                 free_extent_buffer(right);
2216         }
2217         return 1;
2218 }
2219
2220 /*
2221  * readahead one full node of leaves, finding things that are close
2222  * to the block in 'slot', and triggering ra on them.
2223  */
2224 static void reada_for_search(struct btrfs_root *root,
2225                              struct btrfs_path *path,
2226                              int level, int slot, u64 objectid)
2227 {
2228         struct extent_buffer *node;
2229         struct btrfs_disk_key disk_key;
2230         u32 nritems;
2231         u64 search;
2232         u64 target;
2233         u64 nread = 0;
2234         struct extent_buffer *eb;
2235         u32 nr;
2236         u32 blocksize;
2237         u32 nscan = 0;
2238
2239         if (level != 1)
2240                 return;
2241
2242         if (!path->nodes[level])
2243                 return;
2244
2245         node = path->nodes[level];
2246
2247         search = btrfs_node_blockptr(node, slot);
2248         blocksize = root->nodesize;
2249         eb = btrfs_find_tree_block(root->fs_info, search);
2250         if (eb) {
2251                 free_extent_buffer(eb);
2252                 return;
2253         }
2254
2255         target = search;
2256
2257         nritems = btrfs_header_nritems(node);
2258         nr = slot;
2259
2260         while (1) {
2261                 if (path->reada == READA_BACK) {
2262                         if (nr == 0)
2263                                 break;
2264                         nr--;
2265                 } else if (path->reada == READA_FORWARD) {
2266                         nr++;
2267                         if (nr >= nritems)
2268                                 break;
2269                 }
2270                 if (path->reada == READA_BACK && objectid) {
2271                         btrfs_node_key(node, &disk_key, nr);
2272                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
2273                                 break;
2274                 }
2275                 search = btrfs_node_blockptr(node, nr);
2276                 if ((search <= target && target - search <= 65536) ||
2277                     (search > target && search - target <= 65536)) {
2278                         readahead_tree_block(root, search);
2279                         nread += blocksize;
2280                 }
2281                 nscan++;
2282                 if ((nread > 65536 || nscan > 32))
2283                         break;
2284         }
2285 }
2286
2287 static noinline void reada_for_balance(struct btrfs_root *root,
2288                                        struct btrfs_path *path, int level)
2289 {
2290         int slot;
2291         int nritems;
2292         struct extent_buffer *parent;
2293         struct extent_buffer *eb;
2294         u64 gen;
2295         u64 block1 = 0;
2296         u64 block2 = 0;
2297
2298         parent = path->nodes[level + 1];
2299         if (!parent)
2300                 return;
2301
2302         nritems = btrfs_header_nritems(parent);
2303         slot = path->slots[level + 1];
2304
2305         if (slot > 0) {
2306                 block1 = btrfs_node_blockptr(parent, slot - 1);
2307                 gen = btrfs_node_ptr_generation(parent, slot - 1);
2308                 eb = btrfs_find_tree_block(root->fs_info, block1);
2309                 /*
2310                  * if we get -eagain from btrfs_buffer_uptodate, we
2311                  * don't want to return eagain here.  That will loop
2312                  * forever
2313                  */
2314                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2315                         block1 = 0;
2316                 free_extent_buffer(eb);
2317         }
2318         if (slot + 1 < nritems) {
2319                 block2 = btrfs_node_blockptr(parent, slot + 1);
2320                 gen = btrfs_node_ptr_generation(parent, slot + 1);
2321                 eb = btrfs_find_tree_block(root->fs_info, block2);
2322                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2323                         block2 = 0;
2324                 free_extent_buffer(eb);
2325         }
2326
2327         if (block1)
2328                 readahead_tree_block(root, block1);
2329         if (block2)
2330                 readahead_tree_block(root, block2);
2331 }
2332
2333
2334 /*
2335  * when we walk down the tree, it is usually safe to unlock the higher layers
2336  * in the tree.  The exceptions are when our path goes through slot 0, because
2337  * operations on the tree might require changing key pointers higher up in the
2338  * tree.
2339  *
2340  * callers might also have set path->keep_locks, which tells this code to keep
2341  * the lock if the path points to the last slot in the block.  This is part of
2342  * walking through the tree, and selecting the next slot in the higher block.
2343  *
2344  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2345  * if lowest_unlock is 1, level 0 won't be unlocked
2346  */
2347 static noinline void unlock_up(struct btrfs_path *path, int level,
2348                                int lowest_unlock, int min_write_lock_level,
2349                                int *write_lock_level)
2350 {
2351         int i;
2352         int skip_level = level;
2353         int no_skips = 0;
2354         struct extent_buffer *t;
2355
2356         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2357                 if (!path->nodes[i])
2358                         break;
2359                 if (!path->locks[i])
2360                         break;
2361                 if (!no_skips && path->slots[i] == 0) {
2362                         skip_level = i + 1;
2363                         continue;
2364                 }
2365                 if (!no_skips && path->keep_locks) {
2366                         u32 nritems;
2367                         t = path->nodes[i];
2368                         nritems = btrfs_header_nritems(t);
2369                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
2370                                 skip_level = i + 1;
2371                                 continue;
2372                         }
2373                 }
2374                 if (skip_level < i && i >= lowest_unlock)
2375                         no_skips = 1;
2376
2377                 t = path->nodes[i];
2378                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2379                         btrfs_tree_unlock_rw(t, path->locks[i]);
2380                         path->locks[i] = 0;
2381                         if (write_lock_level &&
2382                             i > min_write_lock_level &&
2383                             i <= *write_lock_level) {
2384                                 *write_lock_level = i - 1;
2385                         }
2386                 }
2387         }
2388 }
2389
2390 /*
2391  * This releases any locks held in the path starting at level and
2392  * going all the way up to the root.
2393  *
2394  * btrfs_search_slot will keep the lock held on higher nodes in a few
2395  * corner cases, such as COW of the block at slot zero in the node.  This
2396  * ignores those rules, and it should only be called when there are no
2397  * more updates to be done higher up in the tree.
2398  */
2399 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2400 {
2401         int i;
2402
2403         if (path->keep_locks)
2404                 return;
2405
2406         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2407                 if (!path->nodes[i])
2408                         continue;
2409                 if (!path->locks[i])
2410                         continue;
2411                 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2412                 path->locks[i] = 0;
2413         }
2414 }
2415
2416 /*
2417  * helper function for btrfs_search_slot.  The goal is to find a block
2418  * in cache without setting the path to blocking.  If we find the block
2419  * we return zero and the path is unchanged.
2420  *
2421  * If we can't find the block, we set the path blocking and do some
2422  * reada.  -EAGAIN is returned and the search must be repeated.
2423  */
2424 static int
2425 read_block_for_search(struct btrfs_trans_handle *trans,
2426                        struct btrfs_root *root, struct btrfs_path *p,
2427                        struct extent_buffer **eb_ret, int level, int slot,
2428                        struct btrfs_key *key, u64 time_seq)
2429 {
2430         u64 blocknr;
2431         u64 gen;
2432         struct extent_buffer *b = *eb_ret;
2433         struct extent_buffer *tmp;
2434         int ret;
2435
2436         blocknr = btrfs_node_blockptr(b, slot);
2437         gen = btrfs_node_ptr_generation(b, slot);
2438
2439         tmp = btrfs_find_tree_block(root->fs_info, blocknr);
2440         if (tmp) {
2441                 /* first we do an atomic uptodate check */
2442                 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2443                         *eb_ret = tmp;
2444                         return 0;
2445                 }
2446
2447                 /* the pages were up to date, but we failed
2448                  * the generation number check.  Do a full
2449                  * read for the generation number that is correct.
2450                  * We must do this without dropping locks so
2451                  * we can trust our generation number
2452                  */
2453                 btrfs_set_path_blocking(p);
2454
2455                 /* now we're allowed to do a blocking uptodate check */
2456                 ret = btrfs_read_buffer(tmp, gen);
2457                 if (!ret) {
2458                         *eb_ret = tmp;
2459                         return 0;
2460                 }
2461                 free_extent_buffer(tmp);
2462                 btrfs_release_path(p);
2463                 return -EIO;
2464         }
2465
2466         /*
2467          * reduce lock contention at high levels
2468          * of the btree by dropping locks before
2469          * we read.  Don't release the lock on the current
2470          * level because we need to walk this node to figure
2471          * out which blocks to read.
2472          */
2473         btrfs_unlock_up_safe(p, level + 1);
2474         btrfs_set_path_blocking(p);
2475
2476         free_extent_buffer(tmp);
2477         if (p->reada != READA_NONE)
2478                 reada_for_search(root, p, level, slot, key->objectid);
2479
2480         ret = -EAGAIN;
2481         tmp = read_tree_block(root, blocknr, gen);
2482         if (!IS_ERR(tmp)) {
2483                 /*
2484                  * If the read above didn't mark this buffer up to date,
2485                  * it will never end up being up to date.  Set ret to EIO now
2486                  * and give up so that our caller doesn't loop forever
2487                  * on our EAGAINs.
2488                  */
2489                 if (!btrfs_buffer_uptodate(tmp, 0, 0))
2490                         ret = -EIO;
2491                 free_extent_buffer(tmp);
2492         } else {
2493                 ret = PTR_ERR(tmp);
2494         }
2495
2496         btrfs_release_path(p);
2497         return ret;
2498 }
2499
2500 /*
2501  * helper function for btrfs_search_slot.  This does all of the checks
2502  * for node-level blocks and does any balancing required based on
2503  * the ins_len.
2504  *
2505  * If no extra work was required, zero is returned.  If we had to
2506  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2507  * start over
2508  */
2509 static int
2510 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2511                        struct btrfs_root *root, struct btrfs_path *p,
2512                        struct extent_buffer *b, int level, int ins_len,
2513                        int *write_lock_level)
2514 {
2515         int ret;
2516         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2517             BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2518                 int sret;
2519
2520                 if (*write_lock_level < level + 1) {
2521                         *write_lock_level = level + 1;
2522                         btrfs_release_path(p);
2523                         goto again;
2524                 }
2525
2526                 btrfs_set_path_blocking(p);
2527                 reada_for_balance(root, p, level);
2528                 sret = split_node(trans, root, p, level);
2529                 btrfs_clear_path_blocking(p, NULL, 0);
2530
2531                 BUG_ON(sret > 0);
2532                 if (sret) {
2533                         ret = sret;
2534                         goto done;
2535                 }
2536                 b = p->nodes[level];
2537         } else if (ins_len < 0 && btrfs_header_nritems(b) <
2538                    BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2539                 int sret;
2540
2541                 if (*write_lock_level < level + 1) {
2542                         *write_lock_level = level + 1;
2543                         btrfs_release_path(p);
2544                         goto again;
2545                 }
2546
2547                 btrfs_set_path_blocking(p);
2548                 reada_for_balance(root, p, level);
2549                 sret = balance_level(trans, root, p, level);
2550                 btrfs_clear_path_blocking(p, NULL, 0);
2551
2552                 if (sret) {
2553                         ret = sret;
2554                         goto done;
2555                 }
2556                 b = p->nodes[level];
2557                 if (!b) {
2558                         btrfs_release_path(p);
2559                         goto again;
2560                 }
2561                 BUG_ON(btrfs_header_nritems(b) == 1);
2562         }
2563         return 0;
2564
2565 again:
2566         ret = -EAGAIN;
2567 done:
2568         return ret;
2569 }
2570
2571 static void key_search_validate(struct extent_buffer *b,
2572                                 struct btrfs_key *key,
2573                                 int level)
2574 {
2575 #ifdef CONFIG_BTRFS_ASSERT
2576         struct btrfs_disk_key disk_key;
2577
2578         btrfs_cpu_key_to_disk(&disk_key, key);
2579
2580         if (level == 0)
2581                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2582                     offsetof(struct btrfs_leaf, items[0].key),
2583                     sizeof(disk_key)));
2584         else
2585                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2586                     offsetof(struct btrfs_node, ptrs[0].key),
2587                     sizeof(disk_key)));
2588 #endif
2589 }
2590
2591 static int key_search(struct extent_buffer *b, struct btrfs_key *key,
2592                       int level, int *prev_cmp, int *slot)
2593 {
2594         if (*prev_cmp != 0) {
2595                 *prev_cmp = bin_search(b, key, level, slot);
2596                 return *prev_cmp;
2597         }
2598
2599         key_search_validate(b, key, level);
2600         *slot = 0;
2601
2602         return 0;
2603 }
2604
2605 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2606                 u64 iobjectid, u64 ioff, u8 key_type,
2607                 struct btrfs_key *found_key)
2608 {
2609         int ret;
2610         struct btrfs_key key;
2611         struct extent_buffer *eb;
2612
2613         ASSERT(path);
2614         ASSERT(found_key);
2615
2616         key.type = key_type;
2617         key.objectid = iobjectid;
2618         key.offset = ioff;
2619
2620         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2621         if (ret < 0)
2622                 return ret;
2623
2624         eb = path->nodes[0];
2625         if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2626                 ret = btrfs_next_leaf(fs_root, path);
2627                 if (ret)
2628                         return ret;
2629                 eb = path->nodes[0];
2630         }
2631
2632         btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2633         if (found_key->type != key.type ||
2634                         found_key->objectid != key.objectid)
2635                 return 1;
2636
2637         return 0;
2638 }
2639
2640 /*
2641  * look for key in the tree.  path is filled in with nodes along the way
2642  * if key is found, we return zero and you can find the item in the leaf
2643  * level of the path (level 0)
2644  *
2645  * If the key isn't found, the path points to the slot where it should
2646  * be inserted, and 1 is returned.  If there are other errors during the
2647  * search a negative error number is returned.
2648  *
2649  * if ins_len > 0, nodes and leaves will be split as we walk down the
2650  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
2651  * possible)
2652  */
2653 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2654                       *root, struct btrfs_key *key, struct btrfs_path *p, int
2655                       ins_len, int cow)
2656 {
2657         struct extent_buffer *b;
2658         int slot;
2659         int ret;
2660         int err;
2661         int level;
2662         int lowest_unlock = 1;
2663         int root_lock;
2664         /* everything at write_lock_level or lower must be write locked */
2665         int write_lock_level = 0;
2666         u8 lowest_level = 0;
2667         int min_write_lock_level;
2668         int prev_cmp;
2669
2670         lowest_level = p->lowest_level;
2671         WARN_ON(lowest_level && ins_len > 0);
2672         WARN_ON(p->nodes[0] != NULL);
2673         BUG_ON(!cow && ins_len);
2674
2675         if (ins_len < 0) {
2676                 lowest_unlock = 2;
2677
2678                 /* when we are removing items, we might have to go up to level
2679                  * two as we update tree pointers  Make sure we keep write
2680                  * for those levels as well
2681                  */
2682                 write_lock_level = 2;
2683         } else if (ins_len > 0) {
2684                 /*
2685                  * for inserting items, make sure we have a write lock on
2686                  * level 1 so we can update keys
2687                  */
2688                 write_lock_level = 1;
2689         }
2690
2691         if (!cow)
2692                 write_lock_level = -1;
2693
2694         if (cow && (p->keep_locks || p->lowest_level))
2695                 write_lock_level = BTRFS_MAX_LEVEL;
2696
2697         min_write_lock_level = write_lock_level;
2698
2699 again:
2700         prev_cmp = -1;
2701         /*
2702          * we try very hard to do read locks on the root
2703          */
2704         root_lock = BTRFS_READ_LOCK;
2705         level = 0;
2706         if (p->search_commit_root) {
2707                 /*
2708                  * the commit roots are read only
2709                  * so we always do read locks
2710                  */
2711                 if (p->need_commit_sem)
2712                         down_read(&root->fs_info->commit_root_sem);
2713                 b = root->commit_root;
2714                 extent_buffer_get(b);
2715                 level = btrfs_header_level(b);
2716                 if (p->need_commit_sem)
2717                         up_read(&root->fs_info->commit_root_sem);
2718                 if (!p->skip_locking)
2719                         btrfs_tree_read_lock(b);
2720         } else {
2721                 if (p->skip_locking) {
2722                         b = btrfs_root_node(root);
2723                         level = btrfs_header_level(b);
2724                 } else {
2725                         /* we don't know the level of the root node
2726                          * until we actually have it read locked
2727                          */
2728                         b = btrfs_read_lock_root_node(root);
2729                         level = btrfs_header_level(b);
2730                         if (level <= write_lock_level) {
2731                                 /* whoops, must trade for write lock */
2732                                 btrfs_tree_read_unlock(b);
2733                                 free_extent_buffer(b);
2734                                 b = btrfs_lock_root_node(root);
2735                                 root_lock = BTRFS_WRITE_LOCK;
2736
2737                                 /* the level might have changed, check again */
2738                                 level = btrfs_header_level(b);
2739                         }
2740                 }
2741         }
2742         p->nodes[level] = b;
2743         if (!p->skip_locking)
2744                 p->locks[level] = root_lock;
2745
2746         while (b) {
2747                 level = btrfs_header_level(b);
2748
2749                 /*
2750                  * setup the path here so we can release it under lock
2751                  * contention with the cow code
2752                  */
2753                 if (cow) {
2754                         bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2755
2756                         /*
2757                          * if we don't really need to cow this block
2758                          * then we don't want to set the path blocking,
2759                          * so we test it here
2760                          */
2761                         if (!should_cow_block(trans, root, b)) {
2762                                 trans->dirty = true;
2763                                 goto cow_done;
2764                         }
2765
2766                         /*
2767                          * must have write locks on this node and the
2768                          * parent
2769                          */
2770                         if (level > write_lock_level ||
2771                             (level + 1 > write_lock_level &&
2772                             level + 1 < BTRFS_MAX_LEVEL &&
2773                             p->nodes[level + 1])) {
2774                                 write_lock_level = level + 1;
2775                                 btrfs_release_path(p);
2776                                 goto again;
2777                         }
2778
2779                         btrfs_set_path_blocking(p);
2780                         if (last_level)
2781                                 err = btrfs_cow_block(trans, root, b, NULL, 0,
2782                                                       &b);
2783                         else
2784                                 err = btrfs_cow_block(trans, root, b,
2785                                                       p->nodes[level + 1],
2786                                                       p->slots[level + 1], &b);
2787                         if (err) {
2788                                 ret = err;
2789                                 goto done;
2790                         }
2791                 }
2792 cow_done:
2793                 p->nodes[level] = b;
2794                 btrfs_clear_path_blocking(p, NULL, 0);
2795
2796                 /*
2797                  * we have a lock on b and as long as we aren't changing
2798                  * the tree, there is no way to for the items in b to change.
2799                  * It is safe to drop the lock on our parent before we
2800                  * go through the expensive btree search on b.
2801                  *
2802                  * If we're inserting or deleting (ins_len != 0), then we might
2803                  * be changing slot zero, which may require changing the parent.
2804                  * So, we can't drop the lock until after we know which slot
2805                  * we're operating on.
2806                  */
2807                 if (!ins_len && !p->keep_locks) {
2808                         int u = level + 1;
2809
2810                         if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2811                                 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2812                                 p->locks[u] = 0;
2813                         }
2814                 }
2815
2816                 ret = key_search(b, key, level, &prev_cmp, &slot);
2817                 if (ret < 0)
2818                         goto done;
2819
2820                 if (level != 0) {
2821                         int dec = 0;
2822                         if (ret && slot > 0) {
2823                                 dec = 1;
2824                                 slot -= 1;
2825                         }
2826                         p->slots[level] = slot;
2827                         err = setup_nodes_for_search(trans, root, p, b, level,
2828                                              ins_len, &write_lock_level);
2829                         if (err == -EAGAIN)
2830                                 goto again;
2831                         if (err) {
2832                                 ret = err;
2833                                 goto done;
2834                         }
2835                         b = p->nodes[level];
2836                         slot = p->slots[level];
2837
2838                         /*
2839                          * slot 0 is special, if we change the key
2840                          * we have to update the parent pointer
2841                          * which means we must have a write lock
2842                          * on the parent
2843                          */
2844                         if (slot == 0 && ins_len &&
2845                             write_lock_level < level + 1) {
2846                                 write_lock_level = level + 1;
2847                                 btrfs_release_path(p);
2848                                 goto again;
2849                         }
2850
2851                         unlock_up(p, level, lowest_unlock,
2852                                   min_write_lock_level, &write_lock_level);
2853
2854                         if (level == lowest_level) {
2855                                 if (dec)
2856                                         p->slots[level]++;
2857                                 goto done;
2858                         }
2859
2860                         err = read_block_for_search(trans, root, p,
2861                                                     &b, level, slot, key, 0);
2862                         if (err == -EAGAIN)
2863                                 goto again;
2864                         if (err) {
2865                                 ret = err;
2866                                 goto done;
2867                         }
2868
2869                         if (!p->skip_locking) {
2870                                 level = btrfs_header_level(b);
2871                                 if (level <= write_lock_level) {
2872                                         err = btrfs_try_tree_write_lock(b);
2873                                         if (!err) {
2874                                                 btrfs_set_path_blocking(p);
2875                                                 btrfs_tree_lock(b);
2876                                                 btrfs_clear_path_blocking(p, b,
2877                                                                   BTRFS_WRITE_LOCK);
2878                                         }
2879                                         p->locks[level] = BTRFS_WRITE_LOCK;
2880                                 } else {
2881                                         err = btrfs_tree_read_lock_atomic(b);
2882                                         if (!err) {
2883                                                 btrfs_set_path_blocking(p);
2884                                                 btrfs_tree_read_lock(b);
2885                                                 btrfs_clear_path_blocking(p, b,
2886                                                                   BTRFS_READ_LOCK);
2887                                         }
2888                                         p->locks[level] = BTRFS_READ_LOCK;
2889                                 }
2890                                 p->nodes[level] = b;
2891                         }
2892                 } else {
2893                         p->slots[level] = slot;
2894                         if (ins_len > 0 &&
2895                             btrfs_leaf_free_space(root, b) < ins_len) {
2896                                 if (write_lock_level < 1) {
2897                                         write_lock_level = 1;
2898                                         btrfs_release_path(p);
2899                                         goto again;
2900                                 }
2901
2902                                 btrfs_set_path_blocking(p);
2903                                 err = split_leaf(trans, root, key,
2904                                                  p, ins_len, ret == 0);
2905                                 btrfs_clear_path_blocking(p, NULL, 0);
2906
2907                                 BUG_ON(err > 0);
2908                                 if (err) {
2909                                         ret = err;
2910                                         goto done;
2911                                 }
2912                         }
2913                         if (!p->search_for_split)
2914                                 unlock_up(p, level, lowest_unlock,
2915                                           min_write_lock_level, &write_lock_level);
2916                         goto done;
2917                 }
2918         }
2919         ret = 1;
2920 done:
2921         /*
2922          * we don't really know what they plan on doing with the path
2923          * from here on, so for now just mark it as blocking
2924          */
2925         if (!p->leave_spinning)
2926                 btrfs_set_path_blocking(p);
2927         if (ret < 0 && !p->skip_release_on_error)
2928                 btrfs_release_path(p);
2929         return ret;
2930 }
2931
2932 /*
2933  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2934  * current state of the tree together with the operations recorded in the tree
2935  * modification log to search for the key in a previous version of this tree, as
2936  * denoted by the time_seq parameter.
2937  *
2938  * Naturally, there is no support for insert, delete or cow operations.
2939  *
2940  * The resulting path and return value will be set up as if we called
2941  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2942  */
2943 int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
2944                           struct btrfs_path *p, u64 time_seq)
2945 {
2946         struct extent_buffer *b;
2947         int slot;
2948         int ret;
2949         int err;
2950         int level;
2951         int lowest_unlock = 1;
2952         u8 lowest_level = 0;
2953         int prev_cmp = -1;
2954
2955         lowest_level = p->lowest_level;
2956         WARN_ON(p->nodes[0] != NULL);
2957
2958         if (p->search_commit_root) {
2959                 BUG_ON(time_seq);
2960                 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2961         }
2962
2963 again:
2964         b = get_old_root(root, time_seq);
2965         if (!b) {
2966                 ret = -EIO;
2967                 goto done;
2968         }
2969         level = btrfs_header_level(b);
2970         p->locks[level] = BTRFS_READ_LOCK;
2971
2972         while (b) {
2973                 level = btrfs_header_level(b);
2974                 p->nodes[level] = b;
2975                 btrfs_clear_path_blocking(p, NULL, 0);
2976
2977                 /*
2978                  * we have a lock on b and as long as we aren't changing
2979                  * the tree, there is no way to for the items in b to change.
2980                  * It is safe to drop the lock on our parent before we
2981                  * go through the expensive btree search on b.
2982                  */
2983                 btrfs_unlock_up_safe(p, level + 1);
2984
2985                 /*
2986                  * Since we can unwind ebs we want to do a real search every
2987                  * time.
2988                  */
2989                 prev_cmp = -1;
2990                 ret = key_search(b, key, level, &prev_cmp, &slot);
2991
2992                 if (level != 0) {
2993                         int dec = 0;
2994                         if (ret && slot > 0) {
2995                                 dec = 1;
2996                                 slot -= 1;
2997                         }
2998                         p->slots[level] = slot;
2999                         unlock_up(p, level, lowest_unlock, 0, NULL);
3000
3001                         if (level == lowest_level) {
3002                                 if (dec)
3003                                         p->slots[level]++;
3004                                 goto done;
3005                         }
3006
3007                         err = read_block_for_search(NULL, root, p, &b, level,
3008                                                     slot, key, time_seq);
3009                         if (err == -EAGAIN)
3010                                 goto again;
3011                         if (err) {
3012                                 ret = err;
3013                                 goto done;
3014                         }
3015
3016                         level = btrfs_header_level(b);
3017                         err = btrfs_tree_read_lock_atomic(b);
3018                         if (!err) {
3019                                 btrfs_set_path_blocking(p);
3020                                 btrfs_tree_read_lock(b);
3021                                 btrfs_clear_path_blocking(p, b,
3022                                                           BTRFS_READ_LOCK);
3023                         }
3024                         b = tree_mod_log_rewind(root->fs_info, p, b, time_seq);
3025                         if (!b) {
3026                                 ret = -ENOMEM;
3027                                 goto done;
3028                         }
3029                         p->locks[level] = BTRFS_READ_LOCK;
3030                         p->nodes[level] = b;
3031                 } else {
3032                         p->slots[level] = slot;
3033                         unlock_up(p, level, lowest_unlock, 0, NULL);
3034                         goto done;
3035                 }
3036         }
3037         ret = 1;
3038 done:
3039         if (!p->leave_spinning)
3040                 btrfs_set_path_blocking(p);
3041         if (ret < 0)
3042                 btrfs_release_path(p);
3043
3044         return ret;
3045 }
3046
3047 /*
3048  * helper to use instead of search slot if no exact match is needed but
3049  * instead the next or previous item should be returned.
3050  * When find_higher is true, the next higher item is returned, the next lower
3051  * otherwise.
3052  * When return_any and find_higher are both true, and no higher item is found,
3053  * return the next lower instead.
3054  * When return_any is true and find_higher is false, and no lower item is found,
3055  * return the next higher instead.
3056  * It returns 0 if any item is found, 1 if none is found (tree empty), and
3057  * < 0 on error
3058  */
3059 int btrfs_search_slot_for_read(struct btrfs_root *root,
3060                                struct btrfs_key *key, struct btrfs_path *p,
3061                                int find_higher, int return_any)
3062 {
3063         int ret;
3064         struct extent_buffer *leaf;
3065
3066 again:
3067         ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3068         if (ret <= 0)
3069                 return ret;
3070         /*
3071          * a return value of 1 means the path is at the position where the
3072          * item should be inserted. Normally this is the next bigger item,
3073          * but in case the previous item is the last in a leaf, path points
3074          * to the first free slot in the previous leaf, i.e. at an invalid
3075          * item.
3076          */
3077         leaf = p->nodes[0];
3078
3079         if (find_higher) {
3080                 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3081                         ret = btrfs_next_leaf(root, p);
3082                         if (ret <= 0)
3083                                 return ret;
3084                         if (!return_any)
3085                                 return 1;
3086                         /*
3087                          * no higher item found, return the next
3088                          * lower instead
3089                          */
3090                         return_any = 0;
3091                         find_higher = 0;
3092                         btrfs_release_path(p);
3093                         goto again;
3094                 }
3095         } else {
3096                 if (p->slots[0] == 0) {
3097                         ret = btrfs_prev_leaf(root, p);
3098                         if (ret < 0)
3099                                 return ret;
3100                         if (!ret) {
3101                                 leaf = p->nodes[0];
3102                                 if (p->slots[0] == btrfs_header_nritems(leaf))
3103                                         p->slots[0]--;
3104                                 return 0;
3105                         }
3106                         if (!return_any)
3107                                 return 1;
3108                         /*
3109                          * no lower item found, return the next
3110                          * higher instead
3111                          */
3112                         return_any = 0;
3113                         find_higher = 1;
3114                         btrfs_release_path(p);
3115                         goto again;
3116                 } else {
3117                         --p->slots[0];
3118                 }
3119         }
3120         return 0;
3121 }
3122
3123 /*
3124  * adjust the pointers going up the tree, starting at level
3125  * making sure the right key of each node is points to 'key'.
3126  * This is used after shifting pointers to the left, so it stops
3127  * fixing up pointers when a given leaf/node is not in slot 0 of the
3128  * higher levels
3129  *
3130  */
3131 static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3132                            struct btrfs_path *path,
3133                            struct btrfs_disk_key *key, int level)
3134 {
3135         int i;
3136         struct extent_buffer *t;
3137
3138         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3139                 int tslot = path->slots[i];
3140                 if (!path->nodes[i])
3141                         break;
3142                 t = path->nodes[i];
3143                 tree_mod_log_set_node_key(fs_info, t, tslot, 1);
3144                 btrfs_set_node_key(t, key, tslot);
3145                 btrfs_mark_buffer_dirty(path->nodes[i]);
3146                 if (tslot != 0)
3147                         break;
3148         }
3149 }
3150
3151 /*
3152  * update item key.
3153  *
3154  * This function isn't completely safe. It's the caller's responsibility
3155  * that the new key won't break the order
3156  */
3157 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3158                              struct btrfs_path *path,
3159                              struct btrfs_key *new_key)
3160 {
3161         struct btrfs_disk_key disk_key;
3162         struct extent_buffer *eb;
3163         int slot;
3164
3165         eb = path->nodes[0];
3166         slot = path->slots[0];
3167         if (slot > 0) {
3168                 btrfs_item_key(eb, &disk_key, slot - 1);
3169                 BUG_ON(comp_keys(&disk_key, new_key) >= 0);
3170         }
3171         if (slot < btrfs_header_nritems(eb) - 1) {
3172                 btrfs_item_key(eb, &disk_key, slot + 1);
3173                 BUG_ON(comp_keys(&disk_key, new_key) <= 0);
3174         }
3175
3176         btrfs_cpu_key_to_disk(&disk_key, new_key);
3177         btrfs_set_item_key(eb, &disk_key, slot);
3178         btrfs_mark_buffer_dirty(eb);
3179         if (slot == 0)
3180                 fixup_low_keys(fs_info, path, &disk_key, 1);
3181 }
3182
3183 /*
3184  * try to push data from one node into the next node left in the
3185  * tree.
3186  *
3187  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3188  * error, and > 0 if there was no room in the left hand block.
3189  */
3190 static int push_node_left(struct btrfs_trans_handle *trans,
3191                           struct btrfs_root *root, struct extent_buffer *dst,
3192                           struct extent_buffer *src, int empty)
3193 {
3194         int push_items = 0;
3195         int src_nritems;
3196         int dst_nritems;
3197         int ret = 0;
3198
3199         src_nritems = btrfs_header_nritems(src);
3200         dst_nritems = btrfs_header_nritems(dst);
3201         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3202         WARN_ON(btrfs_header_generation(src) != trans->transid);
3203         WARN_ON(btrfs_header_generation(dst) != trans->transid);
3204
3205         if (!empty && src_nritems <= 8)
3206                 return 1;
3207
3208         if (push_items <= 0)
3209                 return 1;
3210
3211         if (empty) {
3212                 push_items = min(src_nritems, push_items);
3213                 if (push_items < src_nritems) {
3214                         /* leave at least 8 pointers in the node if
3215                          * we aren't going to empty it
3216                          */
3217                         if (src_nritems - push_items < 8) {
3218                                 if (push_items <= 8)
3219                                         return 1;
3220                                 push_items -= 8;
3221                         }
3222                 }
3223         } else
3224                 push_items = min(src_nritems - 8, push_items);
3225
3226         ret = tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
3227                                    push_items);
3228         if (ret) {
3229                 btrfs_abort_transaction(trans, ret);
3230                 return ret;
3231         }
3232         copy_extent_buffer(dst, src,
3233                            btrfs_node_key_ptr_offset(dst_nritems),
3234                            btrfs_node_key_ptr_offset(0),
3235                            push_items * sizeof(struct btrfs_key_ptr));
3236
3237         if (push_items < src_nritems) {
3238                 /*
3239                  * don't call tree_mod_log_eb_move here, key removal was already
3240                  * fully logged by tree_mod_log_eb_copy above.
3241                  */
3242                 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3243                                       btrfs_node_key_ptr_offset(push_items),
3244                                       (src_nritems - push_items) *
3245                                       sizeof(struct btrfs_key_ptr));
3246         }
3247         btrfs_set_header_nritems(src, src_nritems - push_items);
3248         btrfs_set_header_nritems(dst, dst_nritems + push_items);
3249         btrfs_mark_buffer_dirty(src);
3250         btrfs_mark_buffer_dirty(dst);
3251
3252         return ret;
3253 }
3254
3255 /*
3256  * try to push data from one node into the next node right in the
3257  * tree.
3258  *
3259  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3260  * error, and > 0 if there was no room in the right hand block.
3261  *
3262  * this will  only push up to 1/2 the contents of the left node over
3263  */
3264 static int balance_node_right(struct btrfs_trans_handle *trans,
3265                               struct btrfs_root *root,
3266                               struct extent_buffer *dst,
3267                               struct extent_buffer *src)
3268 {
3269         int push_items = 0;
3270         int max_push;
3271         int src_nritems;
3272         int dst_nritems;
3273         int ret = 0;
3274
3275         WARN_ON(btrfs_header_generation(src) != trans->transid);
3276         WARN_ON(btrfs_header_generation(dst) != trans->transid);
3277
3278         src_nritems = btrfs_header_nritems(src);
3279         dst_nritems = btrfs_header_nritems(dst);
3280         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3281         if (push_items <= 0)
3282                 return 1;
3283
3284         if (src_nritems < 4)
3285                 return 1;
3286
3287         max_push = src_nritems / 2 + 1;
3288         /* don't try to empty the node */
3289         if (max_push >= src_nritems)
3290                 return 1;
3291
3292         if (max_push < push_items)
3293                 push_items = max_push;
3294
3295         tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
3296         memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3297                                       btrfs_node_key_ptr_offset(0),
3298                                       (dst_nritems) *
3299                                       sizeof(struct btrfs_key_ptr));
3300
3301         ret = tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
3302                                    src_nritems - push_items, push_items);
3303         if (ret) {
3304                 btrfs_abort_transaction(trans, ret);
3305                 return ret;
3306         }
3307         copy_extent_buffer(dst, src,
3308                            btrfs_node_key_ptr_offset(0),
3309                            btrfs_node_key_ptr_offset(src_nritems - push_items),
3310                            push_items * sizeof(struct btrfs_key_ptr));
3311
3312         btrfs_set_header_nritems(src, src_nritems - push_items);
3313         btrfs_set_header_nritems(dst, dst_nritems + push_items);
3314
3315         btrfs_mark_buffer_dirty(src);
3316         btrfs_mark_buffer_dirty(dst);
3317
3318         return ret;
3319 }
3320
3321 /*
3322  * helper function to insert a new root level in the tree.
3323  * A new node is allocated, and a single item is inserted to
3324  * point to the existing root
3325  *
3326  * returns zero on success or < 0 on failure.
3327  */
3328 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
3329                            struct btrfs_root *root,
3330                            struct btrfs_path *path, int level)
3331 {
3332         u64 lower_gen;
3333         struct extent_buffer *lower;
3334         struct extent_buffer *c;
3335         struct extent_buffer *old;
3336         struct btrfs_disk_key lower_key;
3337
3338         BUG_ON(path->nodes[level]);
3339         BUG_ON(path->nodes[level-1] != root->node);
3340
3341         lower = path->nodes[level-1];
3342         if (level == 1)
3343                 btrfs_item_key(lower, &lower_key, 0);
3344         else
3345                 btrfs_node_key(lower, &lower_key, 0);
3346
3347         c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3348                                    &lower_key, level, root->node->start, 0);
3349         if (IS_ERR(c))
3350                 return PTR_ERR(c);
3351
3352         root_add_used(root, root->nodesize);
3353
3354         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
3355         btrfs_set_header_nritems(c, 1);
3356         btrfs_set_header_level(c, level);
3357         btrfs_set_header_bytenr(c, c->start);
3358         btrfs_set_header_generation(c, trans->transid);
3359         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
3360         btrfs_set_header_owner(c, root->root_key.objectid);
3361
3362         write_extent_buffer(c, root->fs_info->fsid, btrfs_header_fsid(),
3363                             BTRFS_FSID_SIZE);
3364
3365         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3366                             btrfs_header_chunk_tree_uuid(c), BTRFS_UUID_SIZE);
3367
3368         btrfs_set_node_key(c, &lower_key, 0);
3369         btrfs_set_node_blockptr(c, 0, lower->start);
3370         lower_gen = btrfs_header_generation(lower);
3371         WARN_ON(lower_gen != trans->transid);
3372
3373         btrfs_set_node_ptr_generation(c, 0, lower_gen);
3374
3375         btrfs_mark_buffer_dirty(c);
3376
3377         old = root->node;
3378         tree_mod_log_set_root_pointer(root, c, 0);
3379         rcu_assign_pointer(root->node, c);
3380
3381         /* the super has an extra ref to root->node */
3382         free_extent_buffer(old);
3383
3384         add_root_to_dirty_list(root);
3385         extent_buffer_get(c);
3386         path->nodes[level] = c;
3387         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
3388         path->slots[level] = 0;
3389         return 0;
3390 }
3391
3392 /*
3393  * worker function to insert a single pointer in a node.
3394  * the node should have enough room for the pointer already
3395  *
3396  * slot and level indicate where you want the key to go, and
3397  * blocknr is the block the key points to.
3398  */
3399 static void insert_ptr(struct btrfs_trans_handle *trans,
3400                        struct btrfs_root *root, struct btrfs_path *path,
3401                        struct btrfs_disk_key *key, u64 bytenr,
3402                        int slot, int level)
3403 {
3404         struct extent_buffer *lower;
3405         int nritems;
3406         int ret;
3407
3408         BUG_ON(!path->nodes[level]);
3409         btrfs_assert_tree_locked(path->nodes[level]);
3410         lower = path->nodes[level];
3411         nritems = btrfs_header_nritems(lower);
3412         BUG_ON(slot > nritems);
3413         BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
3414         if (slot != nritems) {
3415                 if (level)
3416                         tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3417                                              slot, nritems - slot);
3418                 memmove_extent_buffer(lower,
3419                               btrfs_node_key_ptr_offset(slot + 1),
3420                               btrfs_node_key_ptr_offset(slot),
3421                               (nritems - slot) * sizeof(struct btrfs_key_ptr));
3422         }
3423         if (level) {
3424                 ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3425                                               MOD_LOG_KEY_ADD, GFP_NOFS);
3426                 BUG_ON(ret < 0);
3427         }
3428         btrfs_set_node_key(lower, key, slot);
3429         btrfs_set_node_blockptr(lower, slot, bytenr);
3430         WARN_ON(trans->transid == 0);
3431         btrfs_set_node_ptr_generation(lower, slot, trans->transid);
3432         btrfs_set_header_nritems(lower, nritems + 1);
3433         btrfs_mark_buffer_dirty(lower);
3434 }
3435
3436 /*
3437  * split the node at the specified level in path in two.
3438  * The path is corrected to point to the appropriate node after the split
3439  *
3440  * Before splitting this tries to make some room in the node by pushing
3441  * left and right, if either one works, it returns right away.
3442  *
3443  * returns 0 on success and < 0 on failure
3444  */
3445 static noinline int split_node(struct btrfs_trans_handle *trans,
3446                                struct btrfs_root *root,
3447                                struct btrfs_path *path, int level)
3448 {
3449         struct extent_buffer *c;
3450         struct extent_buffer *split;
3451         struct btrfs_disk_key disk_key;
3452         int mid;
3453         int ret;
3454         u32 c_nritems;
3455
3456         c = path->nodes[level];
3457         WARN_ON(btrfs_header_generation(c) != trans->transid);
3458         if (c == root->node) {
3459                 /*
3460                  * trying to split the root, lets make a new one
3461                  *
3462                  * tree mod log: We don't log_removal old root in
3463                  * insert_new_root, because that root buffer will be kept as a
3464                  * normal node. We are going to log removal of half of the
3465                  * elements below with tree_mod_log_eb_copy. We're holding a
3466                  * tree lock on the buffer, which is why we cannot race with
3467                  * other tree_mod_log users.
3468                  */
3469                 ret = insert_new_root(trans, root, path, level + 1);
3470                 if (ret)
3471                         return ret;
3472         } else {
3473                 ret = push_nodes_for_insert(trans, root, path, level);
3474                 c = path->nodes[level];
3475                 if (!ret && btrfs_header_nritems(c) <
3476                     BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3477                         return 0;
3478                 if (ret < 0)
3479                         return ret;
3480         }
3481
3482         c_nritems = btrfs_header_nritems(c);
3483         mid = (c_nritems + 1) / 2;
3484         btrfs_node_key(c, &disk_key, mid);
3485
3486         split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3487                         &disk_key, level, c->start, 0);
3488         if (IS_ERR(split))
3489                 return PTR_ERR(split);
3490
3491         root_add_used(root, root->nodesize);
3492
3493         memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
3494         btrfs_set_header_level(split, btrfs_header_level(c));
3495         btrfs_set_header_bytenr(split, split->start);
3496         btrfs_set_header_generation(split, trans->transid);
3497         btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
3498         btrfs_set_header_owner(split, root->root_key.objectid);
3499         write_extent_buffer(split, root->fs_info->fsid,
3500                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
3501         write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3502                             btrfs_header_chunk_tree_uuid(split),
3503                             BTRFS_UUID_SIZE);
3504
3505         ret = tree_mod_log_eb_copy(root->fs_info, split, c, 0,
3506                                    mid, c_nritems - mid);
3507         if (ret) {
3508                 btrfs_abort_transaction(trans, ret);
3509                 return ret;
3510         }
3511         copy_extent_buffer(split, c,
3512                            btrfs_node_key_ptr_offset(0),
3513                            btrfs_node_key_ptr_offset(mid),
3514                            (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3515         btrfs_set_header_nritems(split, c_nritems - mid);
3516         btrfs_set_header_nritems(c, mid);
3517         ret = 0;
3518
3519         btrfs_mark_buffer_dirty(c);
3520         btrfs_mark_buffer_dirty(split);
3521
3522         insert_ptr(trans, root, path, &disk_key, split->start,
3523                    path->slots[level + 1] + 1, level + 1);
3524
3525         if (path->slots[level] >= mid) {
3526                 path->slots[level] -= mid;
3527                 btrfs_tree_unlock(c);
3528                 free_extent_buffer(c);
3529                 path->nodes[level] = split;
3530                 path->slots[level + 1] += 1;
3531         } else {
3532                 btrfs_tree_unlock(split);
3533                 free_extent_buffer(split);
3534         }
3535         return ret;
3536 }
3537
3538 /*
3539  * how many bytes are required to store the items in a leaf.  start
3540  * and nr indicate which items in the leaf to check.  This totals up the
3541  * space used both by the item structs and the item data
3542  */
3543 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3544 {
3545         struct btrfs_item *start_item;
3546         struct btrfs_item *end_item;
3547         struct btrfs_map_token token;
3548         int data_len;
3549         int nritems = btrfs_header_nritems(l);
3550         int end = min(nritems, start + nr) - 1;
3551
3552         if (!nr)
3553                 return 0;
3554         btrfs_init_map_token(&token);
3555         start_item = btrfs_item_nr(start);
3556         end_item = btrfs_item_nr(end);
3557         data_len = btrfs_token_item_offset(l, start_item, &token) +
3558                 btrfs_token_item_size(l, start_item, &token);
3559         data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
3560         data_len += sizeof(struct btrfs_item) * nr;
3561         WARN_ON(data_len < 0);
3562         return data_len;
3563 }
3564
3565 /*
3566  * The space between the end of the leaf items and
3567  * the start of the leaf data.  IOW, how much room
3568  * the leaf has left for both items and data
3569  */
3570 noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3571                                    struct extent_buffer *leaf)
3572 {
3573         int nritems = btrfs_header_nritems(leaf);
3574         int ret;
3575         ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
3576         if (ret < 0) {
3577                 btrfs_crit(root->fs_info,
3578                         "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3579                        ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
3580                        leaf_space_used(leaf, 0, nritems), nritems);
3581         }
3582         return ret;
3583 }
3584
3585 /*
3586  * min slot controls the lowest index we're willing to push to the
3587  * right.  We'll push up to and including min_slot, but no lower
3588  */
3589 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3590                                       struct btrfs_root *root,
3591                                       struct btrfs_path *path,
3592                                       int data_size, int empty,
3593                                       struct extent_buffer *right,
3594                                       int free_space, u32 left_nritems,
3595                                       u32 min_slot)
3596 {
3597         struct extent_buffer *left = path->nodes[0];
3598         struct extent_buffer *upper = path->nodes[1];
3599         struct btrfs_map_token token;
3600         struct btrfs_disk_key disk_key;
3601         int slot;
3602         u32 i;
3603         int push_space = 0;
3604         int push_items = 0;
3605         struct btrfs_item *item;
3606         u32 nr;
3607         u32 right_nritems;
3608         u32 data_end;
3609         u32 this_item_size;
3610
3611         btrfs_init_map_token(&token);
3612
3613         if (empty)
3614                 nr = 0;
3615         else
3616                 nr = max_t(u32, 1, min_slot);
3617
3618         if (path->slots[0] >= left_nritems)
3619                 push_space += data_size;
3620
3621         slot = path->slots[1];
3622         i = left_nritems - 1;
3623         while (i >= nr) {
3624                 item = btrfs_item_nr(i);
3625
3626                 if (!empty && push_items > 0) {
3627                         if (path->slots[0] > i)
3628                                 break;
3629                         if (path->slots[0] == i) {
3630                                 int space = btrfs_leaf_free_space(root, left);
3631                                 if (space + push_space * 2 > free_space)
3632                                         break;
3633                         }
3634                 }
3635
3636                 if (path->slots[0] == i)
3637                         push_space += data_size;
3638
3639                 this_item_size = btrfs_item_size(left, item);
3640                 if (this_item_size + sizeof(*item) + push_space > free_space)
3641                         break;
3642
3643                 push_items++;
3644                 push_space += this_item_size + sizeof(*item);
3645                 if (i == 0)
3646                         break;
3647                 i--;
3648         }
3649
3650         if (push_items == 0)
3651                 goto out_unlock;
3652
3653         WARN_ON(!empty && push_items == left_nritems);
3654
3655         /* push left to right */
3656         right_nritems = btrfs_header_nritems(right);
3657
3658         push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3659         push_space -= leaf_data_end(root, left);
3660
3661         /* make room in the right data area */
3662         data_end = leaf_data_end(root, right);
3663         memmove_extent_buffer(right,
3664                               btrfs_leaf_data(right) + data_end - push_space,
3665                               btrfs_leaf_data(right) + data_end,
3666                               BTRFS_LEAF_DATA_SIZE(root) - data_end);
3667
3668         /* copy from the left data area */
3669         copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3670                      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3671                      btrfs_leaf_data(left) + leaf_data_end(root, left),
3672                      push_space);
3673
3674         memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3675                               btrfs_item_nr_offset(0),
3676                               right_nritems * sizeof(struct btrfs_item));
3677
3678         /* copy the items from left to right */
3679         copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3680                    btrfs_item_nr_offset(left_nritems - push_items),
3681                    push_items * sizeof(struct btrfs_item));
3682
3683         /* update the item pointers */
3684         right_nritems += push_items;
3685         btrfs_set_header_nritems(right, right_nritems);
3686         push_space = BTRFS_LEAF_DATA_SIZE(root);
3687         for (i = 0; i < right_nritems; i++) {
3688                 item = btrfs_item_nr(i);
3689                 push_space -= btrfs_token_item_size(right, item, &token);
3690                 btrfs_set_token_item_offset(right, item, push_space, &token);
3691         }
3692
3693         left_nritems -= push_items;
3694         btrfs_set_header_nritems(left, left_nritems);
3695
3696         if (left_nritems)
3697                 btrfs_mark_buffer_dirty(left);
3698         else
3699                 clean_tree_block(trans, root->fs_info, left);
3700
3701         btrfs_mark_buffer_dirty(right);
3702
3703         btrfs_item_key(right, &disk_key, 0);
3704         btrfs_set_node_key(upper, &disk_key, slot + 1);
3705         btrfs_mark_buffer_dirty(upper);
3706
3707         /* then fixup the leaf pointer in the path */
3708         if (path->slots[0] >= left_nritems) {
3709                 path->slots[0] -= left_nritems;
3710                 if (btrfs_header_nritems(path->nodes[0]) == 0)
3711                         clean_tree_block(trans, root->fs_info, path->nodes[0]);
3712                 btrfs_tree_unlock(path->nodes[0]);
3713                 free_extent_buffer(path->nodes[0]);
3714                 path->nodes[0] = right;
3715                 path->slots[1] += 1;
3716         } else {
3717                 btrfs_tree_unlock(right);
3718                 free_extent_buffer(right);
3719         }
3720         return 0;
3721
3722 out_unlock:
3723         btrfs_tree_unlock(right);
3724         free_extent_buffer(right);
3725         return 1;
3726 }
3727
3728 /*
3729  * push some data in the path leaf to the right, trying to free up at
3730  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3731  *
3732  * returns 1 if the push failed because the other node didn't have enough
3733  * room, 0 if everything worked out and < 0 if there were major errors.
3734  *
3735  * this will push starting from min_slot to the end of the leaf.  It won't
3736  * push any slot lower than min_slot
3737  */
3738 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3739                            *root, struct btrfs_path *path,
3740                            int min_data_size, int data_size,
3741                            int empty, u32 min_slot)
3742 {
3743         struct extent_buffer *left = path->nodes[0];
3744         struct extent_buffer *right;
3745         struct extent_buffer *upper;
3746         int slot;
3747         int free_space;
3748         u32 left_nritems;
3749         int ret;
3750
3751         if (!path->nodes[1])
3752                 return 1;
3753
3754         slot = path->slots[1];
3755         upper = path->nodes[1];
3756         if (slot >= btrfs_header_nritems(upper) - 1)
3757                 return 1;
3758
3759         btrfs_assert_tree_locked(path->nodes[1]);
3760
3761         right = read_node_slot(root, upper, slot + 1);
3762         /*
3763          * slot + 1 is not valid or we fail to read the right node,
3764          * no big deal, just return.
3765          */
3766         if (IS_ERR(right))
3767                 return 1;
3768
3769         btrfs_tree_lock(right);
3770         btrfs_set_lock_blocking(right);
3771
3772         free_space = btrfs_leaf_free_space(root, right);
3773         if (free_space < data_size)
3774                 goto out_unlock;
3775
3776         /* cow and double check */
3777         ret = btrfs_cow_block(trans, root, right, upper,
3778                               slot + 1, &right);
3779         if (ret)
3780                 goto out_unlock;
3781
3782         free_space = btrfs_leaf_free_space(root, right);
3783         if (free_space < data_size)
3784                 goto out_unlock;
3785
3786         left_nritems = btrfs_header_nritems(left);
3787         if (left_nritems == 0)
3788                 goto out_unlock;
3789
3790         if (path->slots[0] == left_nritems && !empty) {
3791                 /* Key greater than all keys in the leaf, right neighbor has
3792                  * enough room for it and we're not emptying our leaf to delete
3793                  * it, therefore use right neighbor to insert the new item and
3794                  * no need to touch/dirty our left leaft. */
3795                 btrfs_tree_unlock(left);
3796                 free_extent_buffer(left);
3797                 path->nodes[0] = right;
3798                 path->slots[0] = 0;
3799                 path->slots[1]++;
3800                 return 0;
3801         }
3802
3803         return __push_leaf_right(trans, root, path, min_data_size, empty,
3804                                 right, free_space, left_nritems, min_slot);
3805 out_unlock:
3806         btrfs_tree_unlock(right);
3807         free_extent_buffer(right);
3808         return 1;
3809 }
3810
3811 /*
3812  * push some data in the path leaf to the left, trying to free up at
3813  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3814  *
3815  * max_slot can put a limit on how far into the leaf we'll push items.  The
3816  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
3817  * items
3818  */
3819 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3820                                      struct btrfs_root *root,
3821                                      struct btrfs_path *path, int data_size,
3822                                      int empty, struct extent_buffer *left,
3823                                      int free_space, u32 right_nritems,
3824                                      u32 max_slot)
3825 {
3826         struct btrfs_disk_key disk_key;
3827         struct extent_buffer *right = path->nodes[0];
3828         int i;
3829         int push_space = 0;
3830         int push_items = 0;
3831         struct btrfs_item *item;
3832         u32 old_left_nritems;
3833         u32 nr;
3834         int ret = 0;
3835         u32 this_item_size;
3836         u32 old_left_item_size;
3837         struct btrfs_map_token token;
3838
3839         btrfs_init_map_token(&token);
3840
3841         if (empty)
3842                 nr = min(right_nritems, max_slot);
3843         else
3844                 nr = min(right_nritems - 1, max_slot);
3845
3846         for (i = 0; i < nr; i++) {
3847                 item = btrfs_item_nr(i);
3848
3849                 if (!empty && push_items > 0) {
3850                         if (path->slots[0] < i)
3851                                 break;
3852                         if (path->slots[0] == i) {
3853                                 int space = btrfs_leaf_free_space(root, right);
3854                                 if (space + push_space * 2 > free_space)
3855                                         break;
3856                         }
3857                 }
3858
3859                 if (path->slots[0] == i)
3860                         push_space += data_size;
3861
3862                 this_item_size = btrfs_item_size(right, item);
3863                 if (this_item_size + sizeof(*item) + push_space > free_space)
3864                         break;
3865
3866                 push_items++;
3867                 push_space += this_item_size + sizeof(*item);
3868         }
3869
3870         if (push_items == 0) {
3871                 ret = 1;
3872                 goto out;
3873         }
3874         WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3875
3876         /* push data from right to left */
3877         copy_extent_buffer(left, right,
3878                            btrfs_item_nr_offset(btrfs_header_nritems(left)),
3879                            btrfs_item_nr_offset(0),
3880                            push_items * sizeof(struct btrfs_item));
3881
3882         push_space = BTRFS_LEAF_DATA_SIZE(root) -
3883                      btrfs_item_offset_nr(right, push_items - 1);
3884
3885         copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3886                      leaf_data_end(root, left) - push_space,
3887                      btrfs_leaf_data(right) +
3888                      btrfs_item_offset_nr(right, push_items - 1),
3889                      push_space);
3890         old_left_nritems = btrfs_header_nritems(left);
3891         BUG_ON(old_left_nritems <= 0);
3892
3893         old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3894         for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3895                 u32 ioff;
3896
3897                 item = btrfs_item_nr(i);
3898
3899                 ioff = btrfs_token_item_offset(left, item, &token);
3900                 btrfs_set_token_item_offset(left, item,
3901                       ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3902                       &token);
3903         }
3904         btrfs_set_header_nritems(left, old_left_nritems + push_items);
3905
3906         /* fixup right node */
3907         if (push_items > right_nritems)
3908                 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3909                        right_nritems);
3910
3911         if (push_items < right_nritems) {
3912                 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3913                                                   leaf_data_end(root, right);
3914                 memmove_extent_buffer(right, btrfs_leaf_data(right) +
3915                                       BTRFS_LEAF_DATA_SIZE(root) - push_space,
3916                                       btrfs_leaf_data(right) +
3917                                       leaf_data_end(root, right), push_space);
3918
3919                 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3920                               btrfs_item_nr_offset(push_items),
3921                              (btrfs_header_nritems(right) - push_items) *
3922                              sizeof(struct btrfs_item));
3923         }
3924         right_nritems -= push_items;
3925         btrfs_set_header_nritems(right, right_nritems);
3926         push_space = BTRFS_LEAF_DATA_SIZE(root);
3927         for (i = 0; i < right_nritems; i++) {
3928                 item = btrfs_item_nr(i);
3929
3930                 push_space = push_space - btrfs_token_item_size(right,
3931                                                                 item, &token);
3932                 btrfs_set_token_item_offset(right, item, push_space, &token);
3933         }
3934
3935         btrfs_mark_buffer_dirty(left);
3936         if (right_nritems)
3937                 btrfs_mark_buffer_dirty(right);
3938         else
3939                 clean_tree_block(trans, root->fs_info, right);
3940
3941         btrfs_item_key(right, &disk_key, 0);
3942         fixup_low_keys(root->fs_info, path, &disk_key, 1);
3943
3944         /* then fixup the leaf pointer in the path */
3945         if (path->slots[0] < push_items) {
3946                 path->slots[0] += old_left_nritems;
3947                 btrfs_tree_unlock(path->nodes[0]);
3948                 free_extent_buffer(path->nodes[0]);
3949                 path->nodes[0] = left;
3950                 path->slots[1] -= 1;
3951         } else {
3952                 btrfs_tree_unlock(left);
3953                 free_extent_buffer(left);
3954                 path->slots[0] -= push_items;
3955         }
3956         BUG_ON(path->slots[0] < 0);
3957         return ret;
3958 out:
3959         btrfs_tree_unlock(left);
3960         free_extent_buffer(left);
3961         return ret;
3962 }
3963
3964 /*
3965  * push some data in the path leaf to the left, trying to free up at
3966  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3967  *
3968  * max_slot can put a limit on how far into the leaf we'll push items.  The
3969  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
3970  * items
3971  */
3972 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3973                           *root, struct btrfs_path *path, int min_data_size,
3974                           int data_size, int empty, u32 max_slot)
3975 {
3976         struct extent_buffer *right = path->nodes[0];
3977         struct extent_buffer *left;
3978         int slot;
3979         int free_space;
3980         u32 right_nritems;
3981         int ret = 0;
3982
3983         slot = path->slots[1];
3984         if (slot == 0)
3985                 return 1;
3986         if (!path->nodes[1])
3987                 return 1;
3988
3989         right_nritems = btrfs_header_nritems(right);
3990         if (right_nritems == 0)
3991                 return 1;
3992
3993         btrfs_assert_tree_locked(path->nodes[1]);
3994
3995         left = read_node_slot(root, path->nodes[1], slot - 1);
3996         /*
3997          * slot - 1 is not valid or we fail to read the left node,
3998          * no big deal, just return.
3999          */
4000         if (IS_ERR(left))
4001                 return 1;
4002
4003         btrfs_tree_lock(left);
4004         btrfs_set_lock_blocking(left);
4005
4006         free_space = btrfs_leaf_free_space(root, left);
4007         if (free_space < data_size) {
4008                 ret = 1;
4009                 goto out;
4010         }
4011
4012         /* cow and double check */
4013         ret = btrfs_cow_block(trans, root, left,
4014                               path->nodes[1], slot - 1, &left);
4015         if (ret) {
4016                 /* we hit -ENOSPC, but it isn't fatal here */
4017                 if (ret == -ENOSPC)
4018                         ret = 1;
4019                 goto out;
4020         }
4021
4022         free_space = btrfs_leaf_free_space(root, left);
4023         if (free_space < data_size) {
4024                 ret = 1;
4025                 goto out;
4026         }
4027
4028         return __push_leaf_left(trans, root, path, min_data_size,
4029                                empty, left, free_space, right_nritems,
4030                                max_slot);
4031 out:
4032         btrfs_tree_unlock(left);
4033         free_extent_buffer(left);
4034         return ret;
4035 }
4036
4037 /*
4038  * split the path's leaf in two, making sure there is at least data_size
4039  * available for the resulting leaf level of the path.
4040  */
4041 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4042                                     struct btrfs_root *root,
4043                                     struct btrfs_path *path,
4044                                     struct extent_buffer *l,
4045                                     struct extent_buffer *right,
4046                                     int slot, int mid, int nritems)
4047 {
4048         int data_copy_size;
4049         int rt_data_off;
4050         int i;
4051         struct btrfs_disk_key disk_key;
4052         struct btrfs_map_token token;
4053
4054         btrfs_init_map_token(&token);
4055
4056         nritems = nritems - mid;
4057         btrfs_set_header_nritems(right, nritems);
4058         data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
4059
4060         copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4061                            btrfs_item_nr_offset(mid),
4062                            nritems * sizeof(struct btrfs_item));
4063
4064         copy_extent_buffer(right, l,
4065                      btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
4066                      data_copy_size, btrfs_leaf_data(l) +
4067                      leaf_data_end(root, l), data_copy_size);
4068
4069         rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
4070                       btrfs_item_end_nr(l, mid);
4071
4072         for (i = 0; i < nritems; i++) {
4073                 struct btrfs_item *item = btrfs_item_nr(i);
4074                 u32 ioff;
4075
4076                 ioff = btrfs_token_item_offset(right, item, &token);
4077                 btrfs_set_token_item_offset(right, item,
4078                                             ioff + rt_data_off, &token);
4079         }
4080
4081         btrfs_set_header_nritems(l, mid);
4082         btrfs_item_key(right, &disk_key, 0);
4083         insert_ptr(trans, root, path, &disk_key, right->start,
4084                    path->slots[1] + 1, 1);
4085
4086         btrfs_mark_buffer_dirty(right);
4087         btrfs_mark_buffer_dirty(l);
4088         BUG_ON(path->slots[0] != slot);
4089
4090         if (mid <= slot) {
4091                 btrfs_tree_unlock(path->nodes[0]);
4092                 free_extent_buffer(path->nodes[0]);
4093                 path->nodes[0] = right;
4094                 path->slots[0] -= mid;
4095                 path->slots[1] += 1;
4096         } else {
4097                 btrfs_tree_unlock(right);
4098                 free_extent_buffer(right);
4099         }
4100
4101         BUG_ON(path->slots[0] < 0);
4102 }
4103
4104 /*
4105  * double splits happen when we need to insert a big item in the middle
4106  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
4107  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4108  *          A                 B                 C
4109  *
4110  * We avoid this by trying to push the items on either side of our target
4111  * into the adjacent leaves.  If all goes well we can avoid the double split
4112  * completely.
4113  */
4114 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4115                                           struct btrfs_root *root,
4116                                           struct btrfs_path *path,
4117                                           int data_size)
4118 {
4119         int ret;
4120         int progress = 0;
4121         int slot;
4122         u32 nritems;
4123         int space_needed = data_size;
4124
4125         slot = path->slots[0];
4126         if (slot < btrfs_header_nritems(path->nodes[0]))
4127                 space_needed -= btrfs_leaf_free_space(root, path->nodes[0]);
4128
4129         /*
4130          * try to push all the items after our slot into the
4131          * right leaf
4132          */
4133         ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
4134         if (ret < 0)
4135                 return ret;
4136
4137         if (ret == 0)
4138                 progress++;
4139
4140         nritems = btrfs_header_nritems(path->nodes[0]);
4141         /*
4142          * our goal is to get our slot at the start or end of a leaf.  If
4143          * we've done so we're done
4144          */
4145         if (path->slots[0] == 0 || path->slots[0] == nritems)
4146                 return 0;
4147
4148         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
4149                 return 0;
4150
4151         /* try to push all the items before our slot into the next leaf */
4152         slot = path->slots[0];
4153         ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
4154         if (ret < 0)
4155                 return ret;
4156
4157         if (ret == 0)
4158                 progress++;
4159
4160         if (progress)
4161                 return 0;
4162         return 1;
4163 }
4164
4165 /*
4166  * split the path's leaf in two, making sure there is at least data_size
4167  * available for the resulting leaf level of the path.
4168  *
4169  * returns 0 if all went well and < 0 on failure.
4170  */
4171 static noinline int split_leaf(struct btrfs_trans_handle *trans,
4172                                struct btrfs_root *root,
4173                                struct btrfs_key *ins_key,
4174                                struct btrfs_path *path, int data_size,
4175                                int extend)
4176 {
4177         struct btrfs_disk_key disk_key;
4178         struct extent_buffer *l;
4179         u32 nritems;
4180         int mid;
4181         int slot;
4182         struct extent_buffer *right;
4183         struct btrfs_fs_info *fs_info = root->fs_info;
4184         int ret = 0;
4185         int wret;
4186         int split;
4187         int num_doubles = 0;
4188         int tried_avoid_double = 0;
4189
4190         l = path->nodes[0];
4191         slot = path->slots[0];
4192         if (extend && data_size + btrfs_item_size_nr(l, slot) +
4193             sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
4194                 return -EOVERFLOW;
4195
4196         /* first try to make some room by pushing left and right */
4197         if (data_size && path->nodes[1]) {
4198                 int space_needed = data_size;
4199
4200                 if (slot < btrfs_header_nritems(l))
4201                         space_needed -= btrfs_leaf_free_space(root, l);
4202
4203                 wret = push_leaf_right(trans, root, path, space_needed,
4204                                        space_needed, 0, 0);
4205                 if (wret < 0)
4206                         return wret;
4207                 if (wret) {
4208                         wret = push_leaf_left(trans, root, path, space_needed,
4209                                               space_needed, 0, (u32)-1);
4210                         if (wret < 0)
4211                                 return wret;
4212                 }
4213                 l = path->nodes[0];
4214
4215                 /* did the pushes work? */
4216                 if (btrfs_leaf_free_space(root, l) >= data_size)
4217                         return 0;
4218         }
4219
4220         if (!path->nodes[1]) {
4221                 ret = insert_new_root(trans, root, path, 1);
4222                 if (ret)
4223                         return ret;
4224         }
4225 again:
4226         split = 1;
4227         l = path->nodes[0];
4228         slot = path->slots[0];
4229         nritems = btrfs_header_nritems(l);
4230         mid = (nritems + 1) / 2;
4231
4232         if (mid <= slot) {
4233                 if (nritems == 1 ||
4234                     leaf_space_used(l, mid, nritems - mid) + data_size >
4235                         BTRFS_LEAF_DATA_SIZE(root)) {
4236                         if (slot >= nritems) {
4237                                 split = 0;
4238                         } else {
4239                                 mid = slot;
4240                                 if (mid != nritems &&
4241                                     leaf_space_used(l, mid, nritems - mid) +
4242                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
4243                                         if (data_size && !tried_avoid_double)
4244                                                 goto push_for_double;
4245                                         split = 2;
4246                                 }
4247                         }
4248                 }
4249         } else {
4250                 if (leaf_space_used(l, 0, mid) + data_size >
4251                         BTRFS_LEAF_DATA_SIZE(root)) {
4252                         if (!extend && data_size && slot == 0) {
4253                                 split = 0;
4254                         } else if ((extend || !data_size) && slot == 0) {
4255                                 mid = 1;
4256                         } else {
4257                                 mid = slot;
4258                                 if (mid != nritems &&
4259                                     leaf_space_used(l, mid, nritems - mid) +
4260                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
4261                                         if (data_size && !tried_avoid_double)
4262                                                 goto push_for_double;
4263                                         split = 2;
4264                                 }
4265                         }
4266                 }
4267         }
4268
4269         if (split == 0)
4270                 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4271         else
4272                 btrfs_item_key(l, &disk_key, mid);
4273
4274         right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
4275                         &disk_key, 0, l->start, 0);
4276         if (IS_ERR(right))
4277                 return PTR_ERR(right);
4278
4279         root_add_used(root, root->nodesize);
4280
4281         memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
4282         btrfs_set_header_bytenr(right, right->start);
4283         btrfs_set_header_generation(right, trans->transid);
4284         btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
4285         btrfs_set_header_owner(right, root->root_key.objectid);
4286         btrfs_set_header_level(right, 0);
4287         write_extent_buffer(right, fs_info->fsid,
4288                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
4289
4290         write_extent_buffer(right, fs_info->chunk_tree_uuid,
4291                             btrfs_header_chunk_tree_uuid(right),
4292                             BTRFS_UUID_SIZE);
4293
4294         if (split == 0) {
4295                 if (mid <= slot) {
4296                         btrfs_set_header_nritems(right, 0);
4297                         insert_ptr(trans, root, path, &disk_key, right->start,
4298                                    path->slots[1] + 1, 1);
4299                         btrfs_tree_unlock(path->nodes[0]);
4300                         free_extent_buffer(path->nodes[0]);
4301                         path->nodes[0] = right;
4302                         path->slots[0] = 0;
4303                         path->slots[1] += 1;
4304                 } else {
4305                         btrfs_set_header_nritems(right, 0);
4306                         insert_ptr(trans, root, path, &disk_key, right->start,
4307                                           path->slots[1], 1);
4308                         btrfs_tree_unlock(path->nodes[0]);
4309                         free_extent_buffer(path->nodes[0]);
4310                         path->nodes[0] = right;
4311                         path->slots[0] = 0;
4312                         if (path->slots[1] == 0)
4313                                 fixup_low_keys(fs_info, path, &disk_key, 1);
4314                 }
4315                 /*
4316                  * We create a new leaf 'right' for the required ins_len and
4317                  * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4318                  * the content of ins_len to 'right'.
4319                  */
4320                 return ret;
4321         }
4322
4323         copy_for_split(trans, root, path, l, right, slot, mid, nritems);
4324
4325         if (split == 2) {
4326                 BUG_ON(num_doubles != 0);
4327                 num_doubles++;
4328                 goto again;
4329         }
4330
4331         return 0;
4332
4333 push_for_double:
4334         push_for_double_split(trans, root, path, data_size);
4335         tried_avoid_double = 1;
4336         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
4337                 return 0;
4338         goto again;
4339 }
4340
4341 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4342                                          struct btrfs_root *root,
4343                                          struct btrfs_path *path, int ins_len)
4344 {
4345         struct btrfs_key key;
4346         struct extent_buffer *leaf;
4347         struct btrfs_file_extent_item *fi;
4348         u64 extent_len = 0;
4349         u32 item_size;
4350         int ret;
4351
4352         leaf = path->nodes[0];
4353         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4354
4355         BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4356                key.type != BTRFS_EXTENT_CSUM_KEY);
4357
4358         if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4359                 return 0;
4360
4361         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4362         if (key.type == BTRFS_EXTENT_DATA_KEY) {
4363                 fi = btrfs_item_ptr(leaf, path->slots[0],
4364                                     struct btrfs_file_extent_item);
4365                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4366         }
4367         btrfs_release_path(path);
4368
4369         path->keep_locks = 1;
4370         path->search_for_split = 1;
4371         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4372         path->search_for_split = 0;
4373         if (ret > 0)
4374                 ret = -EAGAIN;
4375         if (ret < 0)
4376                 goto err;
4377
4378         ret = -EAGAIN;
4379         leaf = path->nodes[0];
4380         /* if our item isn't there, return now */
4381         if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4382                 goto err;
4383
4384         /* the leaf has  changed, it now has room.  return now */
4385         if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4386                 goto err;
4387
4388         if (key.type == BTRFS_EXTENT_DATA_KEY) {
4389                 fi = btrfs_item_ptr(leaf, path->slots[0],
4390                                     struct btrfs_file_extent_item);
4391                 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4392                         goto err;
4393         }
4394
4395         btrfs_set_path_blocking(path);
4396         ret = split_leaf(trans, root, &key, path, ins_len, 1);
4397         if (ret)
4398                 goto err;
4399
4400         path->keep_locks = 0;
4401         btrfs_unlock_up_safe(path, 1);
4402         return 0;
4403 err:
4404         path->keep_locks = 0;
4405         return ret;
4406 }
4407
4408 static noinline int split_item(struct btrfs_trans_handle *trans,
4409                                struct btrfs_root *root,
4410                                struct btrfs_path *path,
4411                                struct btrfs_key *new_key,
4412                                unsigned long split_offset)
4413 {
4414         struct extent_buffer *leaf;
4415         struct btrfs_item *item;
4416         struct btrfs_item *new_item;
4417         int slot;
4418         char *buf;
4419         u32 nritems;
4420         u32 item_size;
4421         u32 orig_offset;
4422         struct btrfs_disk_key disk_key;
4423
4424         leaf = path->nodes[0];
4425         BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4426
4427         btrfs_set_path_blocking(path);
4428
4429         item = btrfs_item_nr(path->slots[0]);
4430         orig_offset = btrfs_item_offset(leaf, item);
4431         item_size = btrfs_item_size(leaf, item);
4432
4433         buf = kmalloc(item_size, GFP_NOFS);
4434         if (!buf)
4435                 return -ENOMEM;
4436
4437         read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4438                             path->slots[0]), item_size);
4439
4440         slot = path->slots[0] + 1;
4441         nritems = btrfs_header_nritems(leaf);
4442         if (slot != nritems) {
4443                 /* shift the items */
4444                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4445                                 btrfs_item_nr_offset(slot),
4446                                 (nritems - slot) * sizeof(struct btrfs_item));
4447         }
4448
4449         btrfs_cpu_key_to_disk(&disk_key, new_key);
4450         btrfs_set_item_key(leaf, &disk_key, slot);
4451
4452         new_item = btrfs_item_nr(slot);
4453
4454         btrfs_set_item_offset(leaf, new_item, orig_offset);
4455         btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4456
4457         btrfs_set_item_offset(leaf, item,
4458                               orig_offset + item_size - split_offset);
4459         btrfs_set_item_size(leaf, item, split_offset);
4460
4461         btrfs_set_header_nritems(leaf, nritems + 1);
4462
4463         /* write the data for the start of the original item */
4464         write_extent_buffer(leaf, buf,
4465                             btrfs_item_ptr_offset(leaf, path->slots[0]),
4466                             split_offset);
4467
4468         /* write the data for the new item */
4469         write_extent_buffer(leaf, buf + split_offset,
4470                             btrfs_item_ptr_offset(leaf, slot),
4471                             item_size - split_offset);
4472         btrfs_mark_buffer_dirty(leaf);
4473
4474         BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4475         kfree(buf);
4476         return 0;
4477 }
4478
4479 /*
4480  * This function splits a single item into two items,
4481  * giving 'new_key' to the new item and splitting the
4482  * old one at split_offset (from the start of the item).
4483  *
4484  * The path may be released by this operation.  After
4485  * the split, the path is pointing to the old item.  The
4486  * new item is going to be in the same node as the old one.
4487  *
4488  * Note, the item being split must be smaller enough to live alone on
4489  * a tree block with room for one extra struct btrfs_item
4490  *
4491  * This allows us to split the item in place, keeping a lock on the
4492  * leaf the entire time.
4493  */
4494 int btrfs_split_item(struct btrfs_trans_handle *trans,
4495                      struct btrfs_root *root,
4496                      struct btrfs_path *path,
4497                      struct btrfs_key *new_key,
4498                      unsigned long split_offset)
4499 {
4500         int ret;
4501         ret = setup_leaf_for_split(trans, root, path,
4502                                    sizeof(struct btrfs_item));
4503         if (ret)
4504                 return ret;
4505
4506         ret = split_item(trans, root, path, new_key, split_offset);
4507         return ret;
4508 }
4509
4510 /*
4511  * This function duplicate a item, giving 'new_key' to the new item.
4512  * It guarantees both items live in the same tree leaf and the new item
4513  * is contiguous with the original item.
4514  *
4515  * This allows us to split file extent in place, keeping a lock on the
4516  * leaf the entire time.
4517  */
4518 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4519                          struct btrfs_root *root,
4520                          struct btrfs_path *path,
4521                          struct btrfs_key *new_key)
4522 {
4523         struct extent_buffer *leaf;
4524         int ret;
4525         u32 item_size;
4526
4527         leaf = path->nodes[0];
4528         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4529         ret = setup_leaf_for_split(trans, root, path,
4530                                    item_size + sizeof(struct btrfs_item));
4531         if (ret)
4532                 return ret;
4533
4534         path->slots[0]++;
4535         setup_items_for_insert(root, path, new_key, &item_size,
4536                                item_size, item_size +
4537                                sizeof(struct btrfs_item), 1);
4538         leaf = path->nodes[0];
4539         memcpy_extent_buffer(leaf,
4540                              btrfs_item_ptr_offset(leaf, path->slots[0]),
4541                              btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4542                              item_size);
4543         return 0;
4544 }
4545
4546 /*
4547  * make the item pointed to by the path smaller.  new_size indicates
4548  * how small to make it, and from_end tells us if we just chop bytes
4549  * off the end of the item or if we shift the item to chop bytes off
4550  * the front.
4551  */
4552 void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4553                          u32 new_size, int from_end)
4554 {
4555         int slot;
4556         struct extent_buffer *leaf;
4557         struct btrfs_item *item;
4558         u32 nritems;
4559         unsigned int data_end;
4560         unsigned int old_data_start;
4561         unsigned int old_size;
4562         unsigned int size_diff;
4563         int i;
4564         struct btrfs_map_token token;
4565
4566         btrfs_init_map_token(&token);
4567
4568         leaf = path->nodes[0];
4569         slot = path->slots[0];
4570
4571         old_size = btrfs_item_size_nr(leaf, slot);
4572         if (old_size == new_size)
4573                 return;
4574
4575         nritems = btrfs_header_nritems(leaf);
4576         data_end = leaf_data_end(root, leaf);
4577
4578         old_data_start = btrfs_item_offset_nr(leaf, slot);
4579
4580         size_diff = old_size - new_size;
4581
4582         BUG_ON(slot < 0);
4583         BUG_ON(slot >= nritems);
4584
4585         /*
4586          * item0..itemN ... dataN.offset..dataN.size .. data0.size
4587          */
4588         /* first correct the data pointers */
4589         for (i = slot; i < nritems; i++) {
4590                 u32 ioff;
4591                 item = btrfs_item_nr(i);
4592
4593                 ioff = btrfs_token_item_offset(leaf, item, &token);
4594                 btrfs_set_token_item_offset(leaf, item,
4595                                             ioff + size_diff, &token);
4596         }
4597
4598         /* shift the data */
4599         if (from_end) {
4600                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4601                               data_end + size_diff, btrfs_leaf_data(leaf) +
4602                               data_end, old_data_start + new_size - data_end);
4603         } else {
4604                 struct btrfs_disk_key disk_key;
4605                 u64 offset;
4606
4607                 btrfs_item_key(leaf, &disk_key, slot);
4608
4609                 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4610                         unsigned long ptr;
4611                         struct btrfs_file_extent_item *fi;
4612
4613                         fi = btrfs_item_ptr(leaf, slot,
4614                                             struct btrfs_file_extent_item);
4615                         fi = (struct btrfs_file_extent_item *)(
4616                              (unsigned long)fi - size_diff);
4617
4618                         if (btrfs_file_extent_type(leaf, fi) ==
4619                             BTRFS_FILE_EXTENT_INLINE) {
4620                                 ptr = btrfs_item_ptr_offset(leaf, slot);
4621                                 memmove_extent_buffer(leaf, ptr,
4622                                       (unsigned long)fi,
4623                                       BTRFS_FILE_EXTENT_INLINE_DATA_START);
4624                         }
4625                 }
4626
4627                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4628                               data_end + size_diff, btrfs_leaf_data(leaf) +
4629                               data_end, old_data_start - data_end);
4630
4631                 offset = btrfs_disk_key_offset(&disk_key);
4632                 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4633                 btrfs_set_item_key(leaf, &disk_key, slot);
4634                 if (slot == 0)
4635                         fixup_low_keys(root->fs_info, path, &disk_key, 1);
4636         }
4637
4638         item = btrfs_item_nr(slot);
4639         btrfs_set_item_size(leaf, item, new_size);
4640         btrfs_mark_buffer_dirty(leaf);
4641
4642         if (btrfs_leaf_free_space(root, leaf) < 0) {
4643                 btrfs_print_leaf(root, leaf);
4644                 BUG();
4645         }
4646 }
4647
4648 /*
4649  * make the item pointed to by the path bigger, data_size is the added size.
4650  */
4651 void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
4652                        u32 data_size)
4653 {
4654         int slot;
4655         struct extent_buffer *leaf;
4656         struct btrfs_item *item;
4657         u32 nritems;
4658         unsigned int data_end;
4659         unsigned int old_data;
4660         unsigned int old_size;
4661         int i;
4662         struct btrfs_map_token token;
4663
4664         btrfs_init_map_token(&token);
4665
4666         leaf = path->nodes[0];
4667
4668         nritems = btrfs_header_nritems(leaf);
4669         data_end = leaf_data_end(root, leaf);
4670
4671         if (btrfs_leaf_free_space(root, leaf) < data_size) {
4672                 btrfs_print_leaf(root, leaf);
4673                 BUG();
4674         }
4675         slot = path->slots[0];
4676         old_data = btrfs_item_end_nr(leaf, slot);
4677
4678         BUG_ON(slot < 0);
4679         if (slot >= nritems) {
4680                 btrfs_print_leaf(root, leaf);
4681                 btrfs_crit(root->fs_info, "slot %d too large, nritems %d",
4682                        slot, nritems);
4683                 BUG_ON(1);
4684         }
4685
4686         /*
4687          * item0..itemN ... dataN.offset..dataN.size .. data0.size
4688          */
4689         /* first correct the data pointers */
4690         for (i = slot; i < nritems; i++) {
4691                 u32 ioff;
4692                 item = btrfs_item_nr(i);
4693
4694                 ioff = btrfs_token_item_offset(leaf, item, &token);
4695                 btrfs_set_token_item_offset(leaf, item,
4696                                             ioff - data_size, &token);
4697         }
4698
4699         /* shift the data */
4700         memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4701                       data_end - data_size, btrfs_leaf_data(leaf) +
4702                       data_end, old_data - data_end);
4703
4704         data_end = old_data;
4705         old_size = btrfs_item_size_nr(leaf, slot);
4706         item = btrfs_item_nr(slot);
4707         btrfs_set_item_size(leaf, item, old_size + data_size);
4708         btrfs_mark_buffer_dirty(leaf);
4709
4710         if (btrfs_leaf_free_space(root, leaf) < 0) {
4711                 btrfs_print_leaf(root, leaf);
4712                 BUG();
4713         }
4714 }
4715
4716 /*
4717  * this is a helper for btrfs_insert_empty_items, the main goal here is
4718  * to save stack depth by doing the bulk of the work in a function
4719  * that doesn't call btrfs_search_slot
4720  */
4721 void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4722                             struct btrfs_key *cpu_key, u32 *data_size,
4723                             u32 total_data, u32 total_size, int nr)
4724 {
4725         struct btrfs_item *item;
4726         int i;
4727         u32 nritems;
4728         unsigned int data_end;
4729         struct btrfs_disk_key disk_key;
4730         struct extent_buffer *leaf;
4731         int slot;
4732         struct btrfs_map_token token;
4733
4734         if (path->slots[0] == 0) {
4735                 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4736                 fixup_low_keys(root->fs_info, path, &disk_key, 1);
4737         }
4738         btrfs_unlock_up_safe(path, 1);
4739
4740         btrfs_init_map_token(&token);
4741
4742         leaf = path->nodes[0];
4743         slot = path->slots[0];
4744
4745         nritems = btrfs_header_nritems(leaf);
4746         data_end = leaf_data_end(root, leaf);
4747
4748         if (btrfs_leaf_free_space(root, leaf) < total_size) {
4749                 btrfs_print_leaf(root, leaf);
4750                 btrfs_crit(root->fs_info,
4751                            "not enough freespace need %u have %d",
4752                            total_size, btrfs_leaf_free_space(root, leaf));
4753                 BUG();
4754         }
4755
4756         if (slot != nritems) {
4757                 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4758
4759                 if (old_data < data_end) {
4760                         btrfs_print_leaf(root, leaf);
4761                         btrfs_crit(root->fs_info,
4762                                    "slot %d old_data %d data_end %d",
4763                                    slot, old_data, data_end);
4764                         BUG_ON(1);
4765                 }
4766                 /*
4767                  * item0..itemN ... dataN.offset..dataN.size .. data0.size
4768                  */
4769                 /* first correct the data pointers */
4770                 for (i = slot; i < nritems; i++) {
4771                         u32 ioff;
4772
4773                         item = btrfs_item_nr(i);
4774                         ioff = btrfs_token_item_offset(leaf, item, &token);
4775                         btrfs_set_token_item_offset(leaf, item,
4776                                                     ioff - total_data, &token);
4777                 }
4778                 /* shift the items */
4779                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4780                               btrfs_item_nr_offset(slot),
4781                               (nritems - slot) * sizeof(struct btrfs_item));
4782
4783                 /* shift the data */
4784                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4785                               data_end - total_data, btrfs_leaf_data(leaf) +
4786                               data_end, old_data - data_end);
4787                 data_end = old_data;
4788         }
4789
4790         /* setup the item for the new data */
4791         for (i = 0; i < nr; i++) {
4792                 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4793                 btrfs_set_item_key(leaf, &disk_key, slot + i);
4794                 item = btrfs_item_nr(slot + i);
4795                 btrfs_set_token_item_offset(leaf, item,
4796                                             data_end - data_size[i], &token);
4797                 data_end -= data_size[i];
4798                 btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4799         }
4800
4801         btrfs_set_header_nritems(leaf, nritems + nr);
4802         btrfs_mark_buffer_dirty(leaf);
4803
4804         if (btrfs_leaf_free_space(root, leaf) < 0) {
4805                 btrfs_print_leaf(root, leaf);
4806                 BUG();
4807         }
4808 }
4809
4810 /*
4811  * Given a key and some data, insert items into the tree.
4812  * This does all the path init required, making room in the tree if needed.
4813  */
4814 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4815                             struct btrfs_root *root,
4816                             struct btrfs_path *path,
4817                             struct btrfs_key *cpu_key, u32 *data_size,
4818                             int nr)
4819 {
4820         int ret = 0;
4821         int slot;
4822         int i;
4823         u32 total_size = 0;
4824         u32 total_data = 0;
4825
4826         for (i = 0; i < nr; i++)
4827                 total_data += data_size[i];
4828
4829         total_size = total_data + (nr * sizeof(struct btrfs_item));
4830         ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4831         if (ret == 0)
4832                 return -EEXIST;
4833         if (ret < 0)
4834                 return ret;
4835
4836         slot = path->slots[0];
4837         BUG_ON(slot < 0);
4838
4839         setup_items_for_insert(root, path, cpu_key, data_size,
4840                                total_data, total_size, nr);
4841         return 0;
4842 }
4843
4844 /*
4845  * Given a key and some data, insert an item into the tree.
4846  * This does all the path init required, making room in the tree if needed.
4847  */
4848 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4849                       *root, struct btrfs_key *cpu_key, void *data, u32
4850                       data_size)
4851 {
4852         int ret = 0;
4853         struct btrfs_path *path;
4854         struct extent_buffer *leaf;
4855         unsigned long ptr;
4856
4857         path = btrfs_alloc_path();
4858         if (!path)
4859                 return -ENOMEM;
4860         ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4861         if (!ret) {
4862                 leaf = path->nodes[0];
4863                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4864                 write_extent_buffer(leaf, data, ptr, data_size);
4865                 btrfs_mark_buffer_dirty(leaf);
4866         }
4867         btrfs_free_path(path);
4868         return ret;
4869 }
4870
4871 /*
4872  * delete the pointer from a given node.
4873  *
4874  * the tree should have been previously balanced so the deletion does not
4875  * empty a node.
4876  */
4877 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4878                     int level, int slot)
4879 {
4880         struct extent_buffer *parent = path->nodes[level];
4881         u32 nritems;
4882         int ret;
4883
4884         nritems = btrfs_header_nritems(parent);
4885         if (slot != nritems - 1) {
4886                 if (level)
4887                         tree_mod_log_eb_move(root->fs_info, parent, slot,
4888                                              slot + 1, nritems - slot - 1);
4889                 memmove_extent_buffer(parent,
4890                               btrfs_node_key_ptr_offset(slot),
4891                               btrfs_node_key_ptr_offset(slot + 1),
4892                               sizeof(struct btrfs_key_ptr) *
4893                               (nritems - slot - 1));
4894         } else if (level) {
4895                 ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4896                                               MOD_LOG_KEY_REMOVE, GFP_NOFS);
4897                 BUG_ON(ret < 0);
4898         }
4899
4900         nritems--;
4901         btrfs_set_header_nritems(parent, nritems);
4902         if (nritems == 0 && parent == root->node) {
4903                 BUG_ON(btrfs_header_level(root->node) != 1);
4904                 /* just turn the root into a leaf and break */
4905                 btrfs_set_header_level(root->node, 0);
4906         } else if (slot == 0) {
4907                 struct btrfs_disk_key disk_key;
4908
4909                 btrfs_node_key(parent, &disk_key, 0);
4910                 fixup_low_keys(root->fs_info, path, &disk_key, level + 1);
4911         }
4912         btrfs_mark_buffer_dirty(parent);
4913 }
4914
4915 /*
4916  * a helper function to delete the leaf pointed to by path->slots[1] and
4917  * path->nodes[1].
4918  *
4919  * This deletes the pointer in path->nodes[1] and frees the leaf
4920  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4921  *
4922  * The path must have already been setup for deleting the leaf, including
4923  * all the proper balancing.  path->nodes[1] must be locked.
4924  */
4925 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4926                                     struct btrfs_root *root,
4927                                     struct btrfs_path *path,
4928                                     struct extent_buffer *leaf)
4929 {
4930         WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4931         del_ptr(root, path, 1, path->slots[1]);
4932
4933         /*
4934          * btrfs_free_extent is expensive, we want to make sure we
4935          * aren't holding any locks when we call it
4936          */
4937         btrfs_unlock_up_safe(path, 0);
4938
4939         root_sub_used(root, leaf->len);
4940
4941         extent_buffer_get(leaf);
4942         btrfs_free_tree_block(trans, root, leaf, 0, 1);
4943         free_extent_buffer_stale(leaf);
4944 }
4945 /*
4946  * delete the item at the leaf level in path.  If that empties
4947  * the leaf, remove it from the tree
4948  */
4949 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4950                     struct btrfs_path *path, int slot, int nr)
4951 {
4952         struct extent_buffer *leaf;
4953         struct btrfs_item *item;
4954         u32 last_off;
4955         u32 dsize = 0;
4956         int ret = 0;
4957         int wret;
4958         int i;
4959         u32 nritems;
4960         struct btrfs_map_token token;
4961
4962         btrfs_init_map_token(&token);
4963
4964         leaf = path->nodes[0];
4965         last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4966
4967         for (i = 0; i < nr; i++)
4968                 dsize += btrfs_item_size_nr(leaf, slot + i);
4969
4970         nritems = btrfs_header_nritems(leaf);
4971
4972         if (slot + nr != nritems) {
4973                 int data_end = leaf_data_end(root, leaf);
4974
4975                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4976                               data_end + dsize,
4977                               btrfs_leaf_data(leaf) + data_end,
4978                               last_off - data_end);
4979
4980                 for (i = slot + nr; i < nritems; i++) {
4981                         u32 ioff;
4982
4983                         item = btrfs_item_nr(i);
4984                         ioff = btrfs_token_item_offset(leaf, item, &token);
4985                         btrfs_set_token_item_offset(leaf, item,
4986                                                     ioff + dsize, &token);
4987                 }
4988
4989                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
4990                               btrfs_item_nr_offset(slot + nr),
4991                               sizeof(struct btrfs_item) *
4992                               (nritems - slot - nr));
4993         }
4994         btrfs_set_header_nritems(leaf, nritems - nr);
4995         nritems -= nr;
4996
4997         /* delete the leaf if we've emptied it */
4998         if (nritems == 0) {
4999                 if (leaf == root->node) {
5000                         btrfs_set_header_level(leaf, 0);
5001                 } else {
5002                         btrfs_set_path_blocking(path);
5003                         clean_tree_block(trans, root->fs_info, leaf);
5004                         btrfs_del_leaf(trans, root, path, leaf);
5005                 }
5006         } else {
5007                 int used = leaf_space_used(leaf, 0, nritems);
5008                 if (slot == 0) {
5009                         struct btrfs_disk_key disk_key;
5010
5011                         btrfs_item_key(leaf, &disk_key, 0);
5012                         fixup_low_keys(root->fs_info, path, &disk_key, 1);
5013                 }
5014
5015                 /* delete the leaf if it is mostly empty */
5016                 if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
5017                         /* push_leaf_left fixes the path.
5018                          * make sure the path still points to our leaf
5019                          * for possible call to del_ptr below
5020                          */
5021                         slot = path->slots[1];
5022                         extent_buffer_get(leaf);
5023
5024                         btrfs_set_path_blocking(path);
5025                         wret = push_leaf_left(trans, root, path, 1, 1,
5026                                               1, (u32)-1);
5027                         if (wret < 0 && wret != -ENOSPC)
5028                                 ret = wret;
5029
5030                         if (path->nodes[0] == leaf &&
5031                             btrfs_header_nritems(leaf)) {
5032                                 wret = push_leaf_right(trans, root, path, 1,
5033                                                        1, 1, 0);
5034                                 if (wret < 0 && wret != -ENOSPC)
5035                                         ret = wret;
5036                         }
5037
5038                         if (btrfs_header_nritems(leaf) == 0) {
5039                                 path->slots[1] = slot;
5040                                 btrfs_del_leaf(trans, root, path, leaf);
5041                                 free_extent_buffer(leaf);
5042                                 ret = 0;
5043                         } else {
5044                                 /* if we're still in the path, make sure
5045                                  * we're dirty.  Otherwise, one of the
5046                                  * push_leaf functions must have already
5047                                  * dirtied this buffer
5048                                  */
5049                                 if (path->nodes[0] == leaf)
5050                                         btrfs_mark_buffer_dirty(leaf);
5051                                 free_extent_buffer(leaf);
5052                         }
5053                 } else {
5054                         btrfs_mark_buffer_dirty(leaf);
5055                 }
5056         }
5057         return ret;
5058 }
5059
5060 /*
5061  * search the tree again to find a leaf with lesser keys
5062  * returns 0 if it found something or 1 if there are no lesser leaves.
5063  * returns < 0 on io errors.
5064  *
5065  * This may release the path, and so you may lose any locks held at the
5066  * time you call it.
5067  */
5068 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
5069 {
5070         struct btrfs_key key;
5071         struct btrfs_disk_key found_key;
5072         int ret;
5073
5074         btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5075
5076         if (key.offset > 0) {
5077                 key.offset--;
5078         } else if (key.type > 0) {
5079                 key.type--;
5080                 key.offset = (u64)-1;
5081         } else if (key.objectid > 0) {
5082                 key.objectid--;
5083                 key.type = (u8)-1;
5084                 key.offset = (u64)-1;
5085         } else {
5086                 return 1;
5087         }
5088
5089         btrfs_release_path(path);
5090         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5091         if (ret < 0)
5092                 return ret;
5093         btrfs_item_key(path->nodes[0], &found_key, 0);
5094         ret = comp_keys(&found_key, &key);
5095         /*
5096          * We might have had an item with the previous key in the tree right
5097          * before we released our path. And after we released our path, that
5098          * item might have been pushed to the first slot (0) of the leaf we
5099          * were holding due to a tree balance. Alternatively, an item with the
5100          * previous key can exist as the only element of a leaf (big fat item).
5101          * Therefore account for these 2 cases, so that our callers (like
5102          * btrfs_previous_item) don't miss an existing item with a key matching
5103          * the previous key we computed above.
5104          */
5105         if (ret <= 0)
5106                 return 0;
5107         return 1;
5108 }
5109
5110 /*
5111  * A helper function to walk down the tree starting at min_key, and looking
5112  * for nodes or leaves that are have a minimum transaction id.
5113  * This is used by the btree defrag code, and tree logging
5114  *
5115  * This does not cow, but it does stuff the starting key it finds back
5116  * into min_key, so you can call btrfs_search_slot with cow=1 on the
5117  * key and get a writable path.
5118  *
5119  * This does lock as it descends, and path->keep_locks should be set
5120  * to 1 by the caller.
5121  *
5122  * This honors path->lowest_level to prevent descent past a given level
5123  * of the tree.
5124  *
5125  * min_trans indicates the oldest transaction that you are interested
5126  * in walking through.  Any nodes or leaves older than min_trans are
5127  * skipped over (without reading them).
5128  *
5129  * returns zero if something useful was found, < 0 on error and 1 if there
5130  * was nothing in the tree that matched the search criteria.
5131  */
5132 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5133                          struct btrfs_path *path,
5134                          u64 min_trans)
5135 {
5136         struct extent_buffer *cur;
5137         struct btrfs_key found_key;
5138         int slot;
5139         int sret;
5140         u32 nritems;
5141         int level;
5142         int ret = 1;
5143         int keep_locks = path->keep_locks;
5144
5145         path->keep_locks = 1;
5146 again:
5147         cur = btrfs_read_lock_root_node(root);
5148         level = btrfs_header_level(cur);
5149         WARN_ON(path->nodes[level]);
5150         path->nodes[level] = cur;
5151         path->locks[level] = BTRFS_READ_LOCK;
5152
5153         if (btrfs_header_generation(cur) < min_trans) {
5154                 ret = 1;
5155                 goto out;
5156         }
5157         while (1) {
5158                 nritems = btrfs_header_nritems(cur);
5159                 level = btrfs_header_level(cur);
5160                 sret = bin_search(cur, min_key, level, &slot);
5161
5162                 /* at the lowest level, we're done, setup the path and exit */
5163                 if (level == path->lowest_level) {
5164                         if (slot >= nritems)
5165                                 goto find_next_key;
5166                         ret = 0;
5167                         path->slots[level] = slot;
5168                         btrfs_item_key_to_cpu(cur, &found_key, slot);
5169                         goto out;
5170                 }
5171                 if (sret && slot > 0)
5172                         slot--;
5173                 /*
5174                  * check this node pointer against the min_trans parameters.
5175                  * If it is too old, old, skip to the next one.
5176                  */
5177                 while (slot < nritems) {
5178                         u64 gen;
5179
5180                         gen = btrfs_node_ptr_generation(cur, slot);
5181                         if (gen < min_trans) {
5182                                 slot++;
5183                                 continue;
5184                         }
5185                         break;
5186                 }
5187 find_next_key:
5188                 /*
5189                  * we didn't find a candidate key in this node, walk forward
5190                  * and find another one
5191                  */
5192                 if (slot >= nritems) {
5193                         path->slots[level] = slot;
5194                         btrfs_set_path_blocking(path);
5195                         sret = btrfs_find_next_key(root, path, min_key, level,
5196                                                   min_trans);
5197                         if (sret == 0) {
5198                                 btrfs_release_path(path);
5199                                 goto again;
5200                         } else {
5201                                 goto out;
5202                         }
5203                 }
5204                 /* save our key for returning back */
5205                 btrfs_node_key_to_cpu(cur, &found_key, slot);
5206                 path->slots[level] = slot;
5207                 if (level == path->lowest_level) {
5208                         ret = 0;
5209                         goto out;
5210                 }
5211                 btrfs_set_path_blocking(path);
5212                 cur = read_node_slot(root, cur, slot);
5213                 if (IS_ERR(cur)) {
5214                         ret = PTR_ERR(cur);
5215                         goto out;
5216                 }
5217
5218                 btrfs_tree_read_lock(cur);
5219
5220                 path->locks[level - 1] = BTRFS_READ_LOCK;
5221                 path->nodes[level - 1] = cur;
5222                 unlock_up(path, level, 1, 0, NULL);
5223                 btrfs_clear_path_blocking(path, NULL, 0);
5224         }
5225 out:
5226         path->keep_locks = keep_locks;
5227         if (ret == 0) {
5228                 btrfs_unlock_up_safe(path, path->lowest_level + 1);
5229                 btrfs_set_path_blocking(path);
5230                 memcpy(min_key, &found_key, sizeof(found_key));
5231         }
5232         return ret;
5233 }
5234
5235 static int tree_move_down(struct btrfs_root *root,
5236                            struct btrfs_path *path,
5237                            int *level, int root_level)
5238 {
5239         struct extent_buffer *eb;
5240
5241         BUG_ON(*level == 0);
5242         eb = read_node_slot(root, path->nodes[*level], path->slots[*level]);
5243         if (IS_ERR(eb))
5244                 return PTR_ERR(eb);
5245
5246         path->nodes[*level - 1] = eb;
5247         path->slots[*level - 1] = 0;
5248         (*level)--;
5249         return 0;
5250 }
5251
5252 static int tree_move_next_or_upnext(struct btrfs_root *root,
5253                                     struct btrfs_path *path,
5254                                     int *level, int root_level)
5255 {
5256         int ret = 0;
5257         int nritems;
5258         nritems = btrfs_header_nritems(path->nodes[*level]);
5259
5260         path->slots[*level]++;
5261
5262         while (path->slots[*level] >= nritems) {
5263                 if (*level == root_level)
5264                         return -1;
5265
5266                 /* move upnext */
5267                 path->slots[*level] = 0;
5268                 free_extent_buffer(path->nodes[*level]);
5269                 path->nodes[*level] = NULL;
5270                 (*level)++;
5271                 path->slots[*level]++;
5272
5273                 nritems = btrfs_header_nritems(path->nodes[*level]);
5274                 ret = 1;
5275         }
5276         return ret;
5277 }
5278
5279 /*
5280  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
5281  * or down.
5282  */
5283 static int tree_advance(struct btrfs_root *root,
5284                         struct btrfs_path *path,
5285                         int *level, int root_level,
5286                         int allow_down,
5287                         struct btrfs_key *key)
5288 {
5289         int ret;
5290
5291         if (*level == 0 || !allow_down) {
5292                 ret = tree_move_next_or_upnext(root, path, level, root_level);
5293         } else {
5294                 ret = tree_move_down(root, path, level, root_level);
5295         }
5296         if (ret >= 0) {
5297                 if (*level == 0)
5298                         btrfs_item_key_to_cpu(path->nodes[*level], key,
5299                                         path->slots[*level]);
5300                 else
5301                         btrfs_node_key_to_cpu(path->nodes[*level], key,
5302                                         path->slots[*level]);
5303         }
5304         return ret;
5305 }
5306
5307 static int tree_compare_item(struct btrfs_root *left_root,
5308                              struct btrfs_path *left_path,
5309                              struct btrfs_path *right_path,
5310                              char *tmp_buf)
5311 {
5312         int cmp;
5313         int len1, len2;
5314         unsigned long off1, off2;
5315
5316         len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
5317         len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
5318         if (len1 != len2)
5319                 return 1;
5320
5321         off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
5322         off2 = btrfs_item_ptr_offset(right_path->nodes[0],
5323                                 right_path->slots[0]);
5324
5325         read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
5326
5327         cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
5328         if (cmp)
5329                 return 1;
5330         return 0;
5331 }
5332
5333 #define ADVANCE 1
5334 #define ADVANCE_ONLY_NEXT -1
5335
5336 /*
5337  * This function compares two trees and calls the provided callback for
5338  * every changed/new/deleted item it finds.
5339  * If shared tree blocks are encountered, whole subtrees are skipped, making
5340  * the compare pretty fast on snapshotted subvolumes.
5341  *
5342  * This currently works on commit roots only. As commit roots are read only,
5343  * we don't do any locking. The commit roots are protected with transactions.
5344  * Transactions are ended and rejoined when a commit is tried in between.
5345  *
5346  * This function checks for modifications done to the trees while comparing.
5347  * If it detects a change, it aborts immediately.
5348  */
5349 int btrfs_compare_trees(struct btrfs_root *left_root,
5350                         struct btrfs_root *right_root,
5351                         btrfs_changed_cb_t changed_cb, void *ctx)
5352 {
5353         int ret;
5354         int cmp;
5355         struct btrfs_path *left_path = NULL;
5356         struct btrfs_path *right_path = NULL;
5357         struct btrfs_key left_key;
5358         struct btrfs_key right_key;
5359         char *tmp_buf = NULL;
5360         int left_root_level;
5361         int right_root_level;
5362         int left_level;
5363         int right_level;
5364         int left_end_reached;
5365         int right_end_reached;
5366         int advance_left;
5367         int advance_right;
5368         u64 left_blockptr;
5369         u64 right_blockptr;
5370         u64 left_gen;
5371         u64 right_gen;
5372
5373         left_path = btrfs_alloc_path();
5374         if (!left_path) {
5375                 ret = -ENOMEM;
5376                 goto out;
5377         }
5378         right_path = btrfs_alloc_path();
5379         if (!right_path) {
5380                 ret = -ENOMEM;
5381                 goto out;
5382         }
5383
5384         tmp_buf = kmalloc(left_root->nodesize, GFP_KERNEL | __GFP_NOWARN);
5385         if (!tmp_buf) {
5386                 tmp_buf = vmalloc(left_root->nodesize);
5387                 if (!tmp_buf) {
5388                         ret = -ENOMEM;
5389                         goto out;
5390                 }
5391         }
5392
5393         left_path->search_commit_root = 1;
5394         left_path->skip_locking = 1;
5395         right_path->search_commit_root = 1;
5396         right_path->skip_locking = 1;
5397
5398         /*
5399          * Strategy: Go to the first items of both trees. Then do
5400          *
5401          * If both trees are at level 0
5402          *   Compare keys of current items
5403          *     If left < right treat left item as new, advance left tree
5404          *       and repeat
5405          *     If left > right treat right item as deleted, advance right tree
5406          *       and repeat
5407          *     If left == right do deep compare of items, treat as changed if
5408          *       needed, advance both trees and repeat
5409          * If both trees are at the same level but not at level 0
5410          *   Compare keys of current nodes/leafs
5411          *     If left < right advance left tree and repeat
5412          *     If left > right advance right tree and repeat
5413          *     If left == right compare blockptrs of the next nodes/leafs
5414          *       If they match advance both trees but stay at the same level
5415          *         and repeat
5416          *       If they don't match advance both trees while allowing to go
5417          *         deeper and repeat
5418          * If tree levels are different
5419          *   Advance the tree that needs it and repeat
5420          *
5421          * Advancing a tree means:
5422          *   If we are at level 0, try to go to the next slot. If that's not
5423          *   possible, go one level up and repeat. Stop when we found a level
5424          *   where we could go to the next slot. We may at this point be on a
5425          *   node or a leaf.
5426          *
5427          *   If we are not at level 0 and not on shared tree blocks, go one
5428          *   level deeper.
5429          *
5430          *   If we are not at level 0 and on shared tree blocks, go one slot to
5431          *   the right if possible or go up and right.
5432          */
5433
5434         down_read(&left_root->fs_info->commit_root_sem);
5435         left_level = btrfs_header_level(left_root->commit_root);
5436         left_root_level = left_level;
5437         left_path->nodes[left_level] = left_root->commit_root;
5438         extent_buffer_get(left_path->nodes[left_level]);
5439
5440         right_level = btrfs_header_level(right_root->commit_root);
5441         right_root_level = right_level;
5442         right_path->nodes[right_level] = right_root->commit_root;
5443         extent_buffer_get(right_path->nodes[right_level]);
5444         up_read(&left_root->fs_info->commit_root_sem);
5445
5446         if (left_level == 0)
5447                 btrfs_item_key_to_cpu(left_path->nodes[left_level],
5448                                 &left_key, left_path->slots[left_level]);
5449         else
5450                 btrfs_node_key_to_cpu(left_path->nodes[left_level],
5451                                 &left_key, left_path->slots[left_level]);
5452         if (right_level == 0)
5453                 btrfs_item_key_to_cpu(right_path->nodes[right_level],
5454                                 &right_key, right_path->slots[right_level]);
5455         else
5456                 btrfs_node_key_to_cpu(right_path->nodes[right_level],
5457                                 &right_key, right_path->slots[right_level]);
5458
5459         left_end_reached = right_end_reached = 0;
5460         advance_left = advance_right = 0;
5461
5462         while (1) {
5463                 cond_resched();
5464                 if (advance_left && !left_end_reached) {
5465                         ret = tree_advance(left_root, left_path, &left_level,
5466                                         left_root_level,
5467                                         advance_left != ADVANCE_ONLY_NEXT,
5468                                         &left_key);
5469                         if (ret == -1)
5470                                 left_end_reached = ADVANCE;
5471                         else if (ret < 0)
5472                                 goto out;
5473                         advance_left = 0;
5474                 }
5475                 if (advance_right && !right_end_reached) {
5476                         ret = tree_advance(right_root, right_path, &right_level,
5477                                         right_root_level,
5478                                         advance_right != ADVANCE_ONLY_NEXT,
5479                                         &right_key);
5480                         if (ret == -1)
5481                                 right_end_reached = ADVANCE;
5482                         else if (ret < 0)
5483                                 goto out;
5484                         advance_right = 0;
5485                 }
5486
5487                 if (left_end_reached && right_end_reached) {
5488                         ret = 0;
5489                         goto out;
5490                 } else if (left_end_reached) {
5491                         if (right_level == 0) {
5492                                 ret = changed_cb(left_root, right_root,
5493                                                 left_path, right_path,
5494                                                 &right_key,
5495                                                 BTRFS_COMPARE_TREE_DELETED,
5496                                                 ctx);
5497                                 if (ret < 0)
5498                                         goto out;
5499                         }
5500                         advance_right = ADVANCE;
5501                         continue;
5502                 } else if (right_end_reached) {
5503                         if (left_level == 0) {
5504                                 ret = changed_cb(left_root, right_root,
5505                                                 left_path, right_path,
5506                                                 &left_key,
5507                                                 BTRFS_COMPARE_TREE_NEW,
5508                                                 ctx);
5509                                 if (ret < 0)
5510                                         goto out;
5511                         }
5512                         advance_left = ADVANCE;
5513                         continue;
5514                 }
5515
5516                 if (left_level == 0 && right_level == 0) {
5517                         cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5518                         if (cmp < 0) {
5519                                 ret = changed_cb(left_root, right_root,
5520                                                 left_path, right_path,
5521                                                 &left_key,
5522                                                 BTRFS_COMPARE_TREE_NEW,
5523                                                 ctx);
5524                                 if (ret < 0)
5525                                         goto out;
5526                                 advance_left = ADVANCE;
5527                         } else if (cmp > 0) {
5528                                 ret = changed_cb(left_root, right_root,
5529                                                 left_path, right_path,
5530                                                 &right_key,
5531                                                 BTRFS_COMPARE_TREE_DELETED,
5532                                                 ctx);
5533                                 if (ret < 0)
5534                                         goto out;
5535                                 advance_right = ADVANCE;
5536                         } else {
5537                                 enum btrfs_compare_tree_result result;
5538
5539                                 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
5540                                 ret = tree_compare_item(left_root, left_path,
5541                                                 right_path, tmp_buf);
5542                                 if (ret)
5543                                         result = BTRFS_COMPARE_TREE_CHANGED;
5544                                 else
5545                                         result = BTRFS_COMPARE_TREE_SAME;
5546                                 ret = changed_cb(left_root, right_root,
5547                                                  left_path, right_path,
5548                                                  &left_key, result, ctx);
5549                                 if (ret < 0)
5550                                         goto out;
5551                                 advance_left = ADVANCE;
5552                                 advance_right = ADVANCE;
5553                         }
5554                 } else if (left_level == right_level) {
5555                         cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5556                         if (cmp < 0) {
5557                                 advance_left = ADVANCE;
5558                         } else if (cmp > 0) {
5559                                 advance_right = ADVANCE;
5560                         } else {
5561                                 left_blockptr = btrfs_node_blockptr(
5562                                                 left_path->nodes[left_level],
5563                                                 left_path->slots[left_level]);
5564                                 right_blockptr = btrfs_node_blockptr(
5565                                                 right_path->nodes[right_level],
5566                                                 right_path->slots[right_level]);
5567                                 left_gen = btrfs_node_ptr_generation(
5568                                                 left_path->nodes[left_level],
5569                                                 left_path->slots[left_level]);
5570                                 right_gen = btrfs_node_ptr_generation(
5571                                                 right_path->nodes[right_level],
5572                                                 right_path->slots[right_level]);
5573                                 if (left_blockptr == right_blockptr &&
5574                                     left_gen == right_gen) {
5575                                         /*
5576                                          * As we're on a shared block, don't
5577                                          * allow to go deeper.
5578                                          */
5579                                         advance_left = ADVANCE_ONLY_NEXT;
5580                                         advance_right = ADVANCE_ONLY_NEXT;
5581                                 } else {
5582                                         advance_left = ADVANCE;
5583                                         advance_right = ADVANCE;
5584                                 }
5585                         }
5586                 } else if (left_level < right_level) {
5587                         advance_right = ADVANCE;
5588                 } else {
5589                         advance_left = ADVANCE;
5590                 }
5591         }
5592
5593 out:
5594         btrfs_free_path(left_path);
5595         btrfs_free_path(right_path);
5596         kvfree(tmp_buf);
5597         return ret;
5598 }
5599
5600 /*
5601  * this is similar to btrfs_next_leaf, but does not try to preserve
5602  * and fixup the path.  It looks for and returns the next key in the
5603  * tree based on the current path and the min_trans parameters.
5604  *
5605  * 0 is returned if another key is found, < 0 if there are any errors
5606  * and 1 is returned if there are no higher keys in the tree
5607  *
5608  * path->keep_locks should be set to 1 on the search made before
5609  * calling this function.
5610  */
5611 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5612                         struct btrfs_key *key, int level, u64 min_trans)
5613 {
5614         int slot;
5615         struct extent_buffer *c;
5616
5617         WARN_ON(!path->keep_locks);
5618         while (level < BTRFS_MAX_LEVEL) {
5619                 if (!path->nodes[level])
5620                         return 1;
5621
5622                 slot = path->slots[level] + 1;
5623                 c = path->nodes[level];
5624 next:
5625                 if (slot >= btrfs_header_nritems(c)) {
5626                         int ret;
5627                         int orig_lowest;
5628                         struct btrfs_key cur_key;
5629                         if (level + 1 >= BTRFS_MAX_LEVEL ||
5630                             !path->nodes[level + 1])
5631                                 return 1;
5632
5633                         if (path->locks[level + 1]) {
5634                                 level++;
5635                                 continue;
5636                         }
5637
5638                         slot = btrfs_header_nritems(c) - 1;
5639                         if (level == 0)
5640                                 btrfs_item_key_to_cpu(c, &cur_key, slot);
5641                         else
5642                                 btrfs_node_key_to_cpu(c, &cur_key, slot);
5643
5644                         orig_lowest = path->lowest_level;
5645                         btrfs_release_path(path);
5646                         path->lowest_level = level;
5647                         ret = btrfs_search_slot(NULL, root, &cur_key, path,
5648                                                 0, 0);
5649                         path->lowest_level = orig_lowest;
5650                         if (ret < 0)
5651                                 return ret;
5652
5653                         c = path->nodes[level];
5654                         slot = path->slots[level];
5655                         if (ret == 0)
5656                                 slot++;
5657                         goto next;
5658                 }
5659
5660                 if (level == 0)
5661                         btrfs_item_key_to_cpu(c, key, slot);
5662                 else {
5663                         u64 gen = btrfs_node_ptr_generation(c, slot);
5664
5665                         if (gen < min_trans) {
5666                                 slot++;
5667                                 goto next;
5668                         }
5669                         btrfs_node_key_to_cpu(c, key, slot);
5670                 }
5671                 return 0;
5672         }
5673         return 1;
5674 }
5675
5676 /*
5677  * search the tree again to find a leaf with greater keys
5678  * returns 0 if it found something or 1 if there are no greater leaves.
5679  * returns < 0 on io errors.
5680  */
5681 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5682 {
5683         return btrfs_next_old_leaf(root, path, 0);
5684 }
5685
5686 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5687                         u64 time_seq)
5688 {
5689         int slot;
5690         int level;
5691         struct extent_buffer *c;
5692         struct extent_buffer *next;
5693         struct btrfs_key key;
5694         u32 nritems;
5695         int ret;
5696         int old_spinning = path->leave_spinning;
5697         int next_rw_lock = 0;
5698
5699         nritems = btrfs_header_nritems(path->nodes[0]);
5700         if (nritems == 0)
5701                 return 1;
5702
5703         btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5704 again:
5705         level = 1;
5706         next = NULL;
5707         next_rw_lock = 0;
5708         btrfs_release_path(path);
5709
5710         path->keep_locks = 1;
5711         path->leave_spinning = 1;
5712
5713         if (time_seq)
5714                 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5715         else
5716                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5717         path->keep_locks = 0;
5718
5719         if (ret < 0)
5720                 return ret;
5721
5722         nritems = btrfs_header_nritems(path->nodes[0]);
5723         /*
5724          * by releasing the path above we dropped all our locks.  A balance
5725          * could have added more items next to the key that used to be
5726          * at the very end of the block.  So, check again here and
5727          * advance the path if there are now more items available.
5728          */
5729         if (nritems > 0 && path->slots[0] < nritems - 1) {
5730                 if (ret == 0)
5731                         path->slots[0]++;
5732                 ret = 0;
5733                 goto done;
5734         }
5735         /*
5736          * So the above check misses one case:
5737          * - after releasing the path above, someone has removed the item that
5738          *   used to be at the very end of the block, and balance between leafs
5739          *   gets another one with bigger key.offset to replace it.
5740          *
5741          * This one should be returned as well, or we can get leaf corruption
5742          * later(esp. in __btrfs_drop_extents()).
5743          *
5744          * And a bit more explanation about this check,
5745          * with ret > 0, the key isn't found, the path points to the slot
5746          * where it should be inserted, so the path->slots[0] item must be the
5747          * bigger one.
5748          */
5749         if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5750                 ret = 0;
5751                 goto done;
5752         }
5753
5754         while (level < BTRFS_MAX_LEVEL) {
5755                 if (!path->nodes[level]) {
5756                         ret = 1;
5757                         goto done;
5758                 }
5759
5760                 slot = path->slots[level] + 1;
5761                 c = path->nodes[level];
5762                 if (slot >= btrfs_header_nritems(c)) {
5763                         level++;
5764                         if (level == BTRFS_MAX_LEVEL) {
5765                                 ret = 1;
5766                                 goto done;
5767                         }
5768                         continue;
5769                 }
5770
5771                 if (next) {
5772                         btrfs_tree_unlock_rw(next, next_rw_lock);
5773                         free_extent_buffer(next);
5774                 }
5775
5776                 next = c;
5777                 next_rw_lock = path->locks[level];
5778                 ret = read_block_for_search(NULL, root, path, &next, level,
5779                                             slot, &key, 0);
5780                 if (ret == -EAGAIN)
5781                         goto again;
5782
5783                 if (ret < 0) {
5784                         btrfs_release_path(path);
5785                         goto done;
5786                 }
5787
5788                 if (!path->skip_locking) {
5789                         ret = btrfs_try_tree_read_lock(next);
5790                         if (!ret && time_seq) {
5791                                 /*
5792                                  * If we don't get the lock, we may be racing
5793                                  * with push_leaf_left, holding that lock while
5794                                  * itself waiting for the leaf we've currently
5795                                  * locked. To solve this situation, we give up
5796                                  * on our lock and cycle.
5797                                  */
5798                                 free_extent_buffer(next);
5799                                 btrfs_release_path(path);
5800                                 cond_resched();
5801                                 goto again;
5802                         }
5803                         if (!ret) {
5804                                 btrfs_set_path_blocking(path);
5805                                 btrfs_tree_read_lock(next);
5806                                 btrfs_clear_path_blocking(path, next,
5807                                                           BTRFS_READ_LOCK);
5808                         }
5809                         next_rw_lock = BTRFS_READ_LOCK;
5810                 }
5811                 break;
5812         }
5813         path->slots[level] = slot;
5814         while (1) {
5815                 level--;
5816                 c = path->nodes[level];
5817                 if (path->locks[level])
5818                         btrfs_tree_unlock_rw(c, path->locks[level]);
5819
5820                 free_extent_buffer(c);
5821                 path->nodes[level] = next;
5822                 path->slots[level] = 0;
5823                 if (!path->skip_locking)
5824                         path->locks[level] = next_rw_lock;
5825                 if (!level)
5826                         break;
5827
5828                 ret = read_block_for_search(NULL, root, path, &next, level,
5829                                             0, &key, 0);
5830                 if (ret == -EAGAIN)
5831                         goto again;
5832
5833                 if (ret < 0) {
5834                         btrfs_release_path(path);
5835                         goto done;
5836                 }
5837
5838                 if (!path->skip_locking) {
5839                         ret = btrfs_try_tree_read_lock(next);
5840                         if (!ret) {
5841                                 btrfs_set_path_blocking(path);
5842                                 btrfs_tree_read_lock(next);
5843                                 btrfs_clear_path_blocking(path, next,
5844                                                           BTRFS_READ_LOCK);
5845                         }
5846                         next_rw_lock = BTRFS_READ_LOCK;
5847                 }
5848         }
5849         ret = 0;
5850 done:
5851         unlock_up(path, 0, 1, 0, NULL);
5852         path->leave_spinning = old_spinning;
5853         if (!old_spinning)
5854                 btrfs_set_path_blocking(path);
5855
5856         return ret;
5857 }
5858
5859 /*
5860  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5861  * searching until it gets past min_objectid or finds an item of 'type'
5862  *
5863  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5864  */
5865 int btrfs_previous_item(struct btrfs_root *root,
5866                         struct btrfs_path *path, u64 min_objectid,
5867                         int type)
5868 {
5869         struct btrfs_key found_key;
5870         struct extent_buffer *leaf;
5871         u32 nritems;
5872         int ret;
5873
5874         while (1) {
5875                 if (path->slots[0] == 0) {
5876                         btrfs_set_path_blocking(path);
5877                         ret = btrfs_prev_leaf(root, path);
5878                         if (ret != 0)
5879                                 return ret;
5880                 } else {
5881                         path->slots[0]--;
5882                 }
5883                 leaf = path->nodes[0];
5884                 nritems = btrfs_header_nritems(leaf);
5885                 if (nritems == 0)
5886                         return 1;
5887                 if (path->slots[0] == nritems)
5888                         path->slots[0]--;
5889
5890                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5891                 if (found_key.objectid < min_objectid)
5892                         break;
5893                 if (found_key.type == type)
5894                         return 0;
5895                 if (found_key.objectid == min_objectid &&
5896                     found_key.type < type)
5897                         break;
5898         }
5899         return 1;
5900 }
5901
5902 /*
5903  * search in extent tree to find a previous Metadata/Data extent item with
5904  * min objecitd.
5905  *
5906  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5907  */
5908 int btrfs_previous_extent_item(struct btrfs_root *root,
5909                         struct btrfs_path *path, u64 min_objectid)
5910 {
5911         struct btrfs_key found_key;
5912         struct extent_buffer *leaf;
5913         u32 nritems;
5914         int ret;
5915
5916         while (1) {
5917                 if (path->slots[0] == 0) {
5918                         btrfs_set_path_blocking(path);
5919                         ret = btrfs_prev_leaf(root, path);
5920                         if (ret != 0)
5921                                 return ret;
5922                 } else {
5923                         path->slots[0]--;
5924                 }
5925                 leaf = path->nodes[0];
5926                 nritems = btrfs_header_nritems(leaf);
5927                 if (nritems == 0)
5928                         return 1;
5929                 if (path->slots[0] == nritems)
5930                         path->slots[0]--;
5931
5932                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5933                 if (found_key.objectid < min_objectid)
5934                         break;
5935                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5936                     found_key.type == BTRFS_METADATA_ITEM_KEY)
5937                         return 0;
5938                 if (found_key.objectid == min_objectid &&
5939                     found_key.type < BTRFS_EXTENT_ITEM_KEY)
5940                         break;
5941         }
5942         return 1;
5943 }