btrfs: kill tree_mod_log_set_node_key helper
[sfrench/cifs-2.6.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/mm.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 *root,
32                       const struct btrfs_key *ins_key, struct btrfs_path *path,
33                       int data_size, int extend);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35                           struct btrfs_fs_info *fs_info,
36                           struct extent_buffer *dst,
37                           struct extent_buffer *src, int empty);
38 static int balance_node_right(struct btrfs_trans_handle *trans,
39                               struct btrfs_fs_info *fs_info,
40                               struct extent_buffer *dst_buf,
41                               struct extent_buffer *src_buf);
42 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
43                     int level, int slot);
44
45 struct btrfs_path *btrfs_alloc_path(void)
46 {
47         return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
48 }
49
50 /*
51  * set all locked nodes in the path to blocking locks.  This should
52  * be done before scheduling
53  */
54 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
55 {
56         int i;
57         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
58                 if (!p->nodes[i] || !p->locks[i])
59                         continue;
60                 btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
61                 if (p->locks[i] == BTRFS_READ_LOCK)
62                         p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
63                 else if (p->locks[i] == BTRFS_WRITE_LOCK)
64                         p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
65         }
66 }
67
68 /*
69  * reset all the locked nodes in the patch to spinning locks.
70  *
71  * held is used to keep lockdep happy, when lockdep is enabled
72  * we set held to a blocking lock before we go around and
73  * retake all the spinlocks in the path.  You can safely use NULL
74  * for held
75  */
76 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
77                                         struct extent_buffer *held, int held_rw)
78 {
79         int i;
80
81         if (held) {
82                 btrfs_set_lock_blocking_rw(held, held_rw);
83                 if (held_rw == BTRFS_WRITE_LOCK)
84                         held_rw = BTRFS_WRITE_LOCK_BLOCKING;
85                 else if (held_rw == BTRFS_READ_LOCK)
86                         held_rw = BTRFS_READ_LOCK_BLOCKING;
87         }
88         btrfs_set_path_blocking(p);
89
90         for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
91                 if (p->nodes[i] && p->locks[i]) {
92                         btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
93                         if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
94                                 p->locks[i] = BTRFS_WRITE_LOCK;
95                         else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
96                                 p->locks[i] = BTRFS_READ_LOCK;
97                 }
98         }
99
100         if (held)
101                 btrfs_clear_lock_blocking_rw(held, held_rw);
102 }
103
104 /* this also releases the path */
105 void btrfs_free_path(struct btrfs_path *p)
106 {
107         if (!p)
108                 return;
109         btrfs_release_path(p);
110         kmem_cache_free(btrfs_path_cachep, p);
111 }
112
113 /*
114  * path release drops references on the extent buffers in the path
115  * and it drops any locks held by this path
116  *
117  * It is safe to call this on paths that no locks or extent buffers held.
118  */
119 noinline void btrfs_release_path(struct btrfs_path *p)
120 {
121         int i;
122
123         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
124                 p->slots[i] = 0;
125                 if (!p->nodes[i])
126                         continue;
127                 if (p->locks[i]) {
128                         btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
129                         p->locks[i] = 0;
130                 }
131                 free_extent_buffer(p->nodes[i]);
132                 p->nodes[i] = NULL;
133         }
134 }
135
136 /*
137  * safely gets a reference on the root node of a tree.  A lock
138  * is not taken, so a concurrent writer may put a different node
139  * at the root of the tree.  See btrfs_lock_root_node for the
140  * looping required.
141  *
142  * The extent buffer returned by this has a reference taken, so
143  * it won't disappear.  It may stop being the root of the tree
144  * at any time because there are no locks held.
145  */
146 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
147 {
148         struct extent_buffer *eb;
149
150         while (1) {
151                 rcu_read_lock();
152                 eb = rcu_dereference(root->node);
153
154                 /*
155                  * RCU really hurts here, we could free up the root node because
156                  * it was COWed but we may not get the new root node yet so do
157                  * the inc_not_zero dance and if it doesn't work then
158                  * synchronize_rcu and try again.
159                  */
160                 if (atomic_inc_not_zero(&eb->refs)) {
161                         rcu_read_unlock();
162                         break;
163                 }
164                 rcu_read_unlock();
165                 synchronize_rcu();
166         }
167         return eb;
168 }
169
170 /* loop around taking references on and locking the root node of the
171  * tree until you end up with a lock on the root.  A locked buffer
172  * is returned, with a reference held.
173  */
174 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
175 {
176         struct extent_buffer *eb;
177
178         while (1) {
179                 eb = btrfs_root_node(root);
180                 btrfs_tree_lock(eb);
181                 if (eb == root->node)
182                         break;
183                 btrfs_tree_unlock(eb);
184                 free_extent_buffer(eb);
185         }
186         return eb;
187 }
188
189 /* loop around taking references on and locking the root node of the
190  * tree until you end up with a lock on the root.  A locked buffer
191  * is returned, with a reference held.
192  */
193 struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
194 {
195         struct extent_buffer *eb;
196
197         while (1) {
198                 eb = btrfs_root_node(root);
199                 btrfs_tree_read_lock(eb);
200                 if (eb == root->node)
201                         break;
202                 btrfs_tree_read_unlock(eb);
203                 free_extent_buffer(eb);
204         }
205         return eb;
206 }
207
208 /* cowonly root (everything not a reference counted cow subvolume), just get
209  * put onto a simple dirty list.  transaction.c walks this to make sure they
210  * get properly updated on disk.
211  */
212 static void add_root_to_dirty_list(struct btrfs_root *root)
213 {
214         struct btrfs_fs_info *fs_info = root->fs_info;
215
216         if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
217             !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
218                 return;
219
220         spin_lock(&fs_info->trans_lock);
221         if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
222                 /* Want the extent tree to be the last on the list */
223                 if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
224                         list_move_tail(&root->dirty_list,
225                                        &fs_info->dirty_cowonly_roots);
226                 else
227                         list_move(&root->dirty_list,
228                                   &fs_info->dirty_cowonly_roots);
229         }
230         spin_unlock(&fs_info->trans_lock);
231 }
232
233 /*
234  * used by snapshot creation to make a copy of a root for a tree with
235  * a given objectid.  The buffer with the new root node is returned in
236  * cow_ret, and this func returns zero on success or a negative error code.
237  */
238 int btrfs_copy_root(struct btrfs_trans_handle *trans,
239                       struct btrfs_root *root,
240                       struct extent_buffer *buf,
241                       struct extent_buffer **cow_ret, u64 new_root_objectid)
242 {
243         struct btrfs_fs_info *fs_info = root->fs_info;
244         struct extent_buffer *cow;
245         int ret = 0;
246         int level;
247         struct btrfs_disk_key disk_key;
248
249         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
250                 trans->transid != fs_info->running_transaction->transid);
251         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
252                 trans->transid != root->last_trans);
253
254         level = btrfs_header_level(buf);
255         if (level == 0)
256                 btrfs_item_key(buf, &disk_key, 0);
257         else
258                 btrfs_node_key(buf, &disk_key, 0);
259
260         cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
261                         &disk_key, level, buf->start, 0);
262         if (IS_ERR(cow))
263                 return PTR_ERR(cow);
264
265         copy_extent_buffer_full(cow, buf);
266         btrfs_set_header_bytenr(cow, cow->start);
267         btrfs_set_header_generation(cow, trans->transid);
268         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
269         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
270                                      BTRFS_HEADER_FLAG_RELOC);
271         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
272                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
273         else
274                 btrfs_set_header_owner(cow, new_root_objectid);
275
276         write_extent_buffer_fsid(cow, fs_info->fsid);
277
278         WARN_ON(btrfs_header_generation(buf) > trans->transid);
279         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
280                 ret = btrfs_inc_ref(trans, root, cow, 1);
281         else
282                 ret = btrfs_inc_ref(trans, root, cow, 0);
283
284         if (ret)
285                 return ret;
286
287         btrfs_mark_buffer_dirty(cow);
288         *cow_ret = cow;
289         return 0;
290 }
291
292 enum mod_log_op {
293         MOD_LOG_KEY_REPLACE,
294         MOD_LOG_KEY_ADD,
295         MOD_LOG_KEY_REMOVE,
296         MOD_LOG_KEY_REMOVE_WHILE_FREEING,
297         MOD_LOG_KEY_REMOVE_WHILE_MOVING,
298         MOD_LOG_MOVE_KEYS,
299         MOD_LOG_ROOT_REPLACE,
300 };
301
302 struct tree_mod_root {
303         u64 logical;
304         u8 level;
305 };
306
307 struct tree_mod_elem {
308         struct rb_node node;
309         u64 logical;
310         u64 seq;
311         enum mod_log_op op;
312
313         /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
314         int slot;
315
316         /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
317         u64 generation;
318
319         /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
320         struct btrfs_disk_key key;
321         u64 blockptr;
322
323         /* this is used for op == MOD_LOG_MOVE_KEYS */
324         struct {
325                 int dst_slot;
326                 int nr_items;
327         } move;
328
329         /* this is used for op == MOD_LOG_ROOT_REPLACE */
330         struct tree_mod_root old_root;
331 };
332
333 /*
334  * Pull a new tree mod seq number for our operation.
335  */
336 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
337 {
338         return atomic64_inc_return(&fs_info->tree_mod_seq);
339 }
340
341 /*
342  * This adds a new blocker to the tree mod log's blocker list if the @elem
343  * passed does not already have a sequence number set. So when a caller expects
344  * to record tree modifications, it should ensure to set elem->seq to zero
345  * before calling btrfs_get_tree_mod_seq.
346  * Returns a fresh, unused tree log modification sequence number, even if no new
347  * blocker was added.
348  */
349 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
350                            struct seq_list *elem)
351 {
352         write_lock(&fs_info->tree_mod_log_lock);
353         spin_lock(&fs_info->tree_mod_seq_lock);
354         if (!elem->seq) {
355                 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
356                 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
357         }
358         spin_unlock(&fs_info->tree_mod_seq_lock);
359         write_unlock(&fs_info->tree_mod_log_lock);
360
361         return elem->seq;
362 }
363
364 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
365                             struct seq_list *elem)
366 {
367         struct rb_root *tm_root;
368         struct rb_node *node;
369         struct rb_node *next;
370         struct seq_list *cur_elem;
371         struct tree_mod_elem *tm;
372         u64 min_seq = (u64)-1;
373         u64 seq_putting = elem->seq;
374
375         if (!seq_putting)
376                 return;
377
378         spin_lock(&fs_info->tree_mod_seq_lock);
379         list_del(&elem->list);
380         elem->seq = 0;
381
382         list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
383                 if (cur_elem->seq < min_seq) {
384                         if (seq_putting > cur_elem->seq) {
385                                 /*
386                                  * blocker with lower sequence number exists, we
387                                  * cannot remove anything from the log
388                                  */
389                                 spin_unlock(&fs_info->tree_mod_seq_lock);
390                                 return;
391                         }
392                         min_seq = cur_elem->seq;
393                 }
394         }
395         spin_unlock(&fs_info->tree_mod_seq_lock);
396
397         /*
398          * anything that's lower than the lowest existing (read: blocked)
399          * sequence number can be removed from the tree.
400          */
401         write_lock(&fs_info->tree_mod_log_lock);
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 = rb_entry(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         tm->seq = btrfs_inc_tree_mod_seq(fs_info);
433
434         tm_root = &fs_info->tree_mod_log;
435         new = &tm_root->rb_node;
436         while (*new) {
437                 cur = rb_entry(*new, struct tree_mod_elem, node);
438                 parent = *new;
439                 if (cur->logical < tm->logical)
440                         new = &((*new)->rb_left);
441                 else if (cur->logical > tm->logical)
442                         new = &((*new)->rb_right);
443                 else if (cur->seq < tm->seq)
444                         new = &((*new)->rb_left);
445                 else if (cur->seq > tm->seq)
446                         new = &((*new)->rb_right);
447                 else
448                         return -EEXIST;
449         }
450
451         rb_link_node(&tm->node, parent, new);
452         rb_insert_color(&tm->node, tm_root);
453         return 0;
454 }
455
456 /*
457  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
458  * returns zero with the tree_mod_log_lock acquired. The caller must hold
459  * this until all tree mod log insertions are recorded in the rb tree and then
460  * write unlock fs_info::tree_mod_log_lock.
461  */
462 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
463                                     struct extent_buffer *eb) {
464         smp_mb();
465         if (list_empty(&(fs_info)->tree_mod_seq_list))
466                 return 1;
467         if (eb && btrfs_header_level(eb) == 0)
468                 return 1;
469
470         write_lock(&fs_info->tree_mod_log_lock);
471         if (list_empty(&(fs_info)->tree_mod_seq_list)) {
472                 write_unlock(&fs_info->tree_mod_log_lock);
473                 return 1;
474         }
475
476         return 0;
477 }
478
479 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
480 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
481                                     struct extent_buffer *eb)
482 {
483         smp_mb();
484         if (list_empty(&(fs_info)->tree_mod_seq_list))
485                 return 0;
486         if (eb && btrfs_header_level(eb) == 0)
487                 return 0;
488
489         return 1;
490 }
491
492 static struct tree_mod_elem *
493 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
494                     enum mod_log_op op, gfp_t flags)
495 {
496         struct tree_mod_elem *tm;
497
498         tm = kzalloc(sizeof(*tm), flags);
499         if (!tm)
500                 return NULL;
501
502         tm->logical = eb->start;
503         if (op != MOD_LOG_KEY_ADD) {
504                 btrfs_node_key(eb, &tm->key, slot);
505                 tm->blockptr = btrfs_node_blockptr(eb, slot);
506         }
507         tm->op = op;
508         tm->slot = slot;
509         tm->generation = btrfs_node_ptr_generation(eb, slot);
510         RB_CLEAR_NODE(&tm->node);
511
512         return tm;
513 }
514
515 static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
516                 enum mod_log_op op, gfp_t flags)
517 {
518         struct tree_mod_elem *tm;
519         int ret;
520
521         if (!tree_mod_need_log(eb->fs_info, eb))
522                 return 0;
523
524         tm = alloc_tree_mod_elem(eb, slot, op, flags);
525         if (!tm)
526                 return -ENOMEM;
527
528         if (tree_mod_dont_log(eb->fs_info, eb)) {
529                 kfree(tm);
530                 return 0;
531         }
532
533         ret = __tree_mod_log_insert(eb->fs_info, tm);
534         write_unlock(&eb->fs_info->tree_mod_log_lock);
535         if (ret)
536                 kfree(tm);
537
538         return ret;
539 }
540
541 static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
542                 int dst_slot, int src_slot, int nr_items)
543 {
544         struct tree_mod_elem *tm = NULL;
545         struct tree_mod_elem **tm_list = NULL;
546         int ret = 0;
547         int i;
548         int locked = 0;
549
550         if (!tree_mod_need_log(eb->fs_info, eb))
551                 return 0;
552
553         tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
554         if (!tm_list)
555                 return -ENOMEM;
556
557         tm = kzalloc(sizeof(*tm), GFP_NOFS);
558         if (!tm) {
559                 ret = -ENOMEM;
560                 goto free_tms;
561         }
562
563         tm->logical = eb->start;
564         tm->slot = src_slot;
565         tm->move.dst_slot = dst_slot;
566         tm->move.nr_items = nr_items;
567         tm->op = MOD_LOG_MOVE_KEYS;
568
569         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
570                 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
571                     MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
572                 if (!tm_list[i]) {
573                         ret = -ENOMEM;
574                         goto free_tms;
575                 }
576         }
577
578         if (tree_mod_dont_log(eb->fs_info, eb))
579                 goto free_tms;
580         locked = 1;
581
582         /*
583          * When we override something during the move, we log these removals.
584          * This can only happen when we move towards the beginning of the
585          * buffer, i.e. dst_slot < src_slot.
586          */
587         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
588                 ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
589                 if (ret)
590                         goto free_tms;
591         }
592
593         ret = __tree_mod_log_insert(eb->fs_info, tm);
594         if (ret)
595                 goto free_tms;
596         write_unlock(&eb->fs_info->tree_mod_log_lock);
597         kfree(tm_list);
598
599         return 0;
600 free_tms:
601         for (i = 0; i < nr_items; i++) {
602                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
603                         rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
604                 kfree(tm_list[i]);
605         }
606         if (locked)
607                 write_unlock(&eb->fs_info->tree_mod_log_lock);
608         kfree(tm_list);
609         kfree(tm);
610
611         return ret;
612 }
613
614 static inline int
615 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
616                        struct tree_mod_elem **tm_list,
617                        int nritems)
618 {
619         int i, j;
620         int ret;
621
622         for (i = nritems - 1; i >= 0; i--) {
623                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
624                 if (ret) {
625                         for (j = nritems - 1; j > i; j--)
626                                 rb_erase(&tm_list[j]->node,
627                                          &fs_info->tree_mod_log);
628                         return ret;
629                 }
630         }
631
632         return 0;
633 }
634
635 static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
636                          struct extent_buffer *new_root, int log_removal)
637 {
638         struct btrfs_fs_info *fs_info = old_root->fs_info;
639         struct tree_mod_elem *tm = NULL;
640         struct tree_mod_elem **tm_list = NULL;
641         int nritems = 0;
642         int ret = 0;
643         int i;
644
645         if (!tree_mod_need_log(fs_info, NULL))
646                 return 0;
647
648         if (log_removal && btrfs_header_level(old_root) > 0) {
649                 nritems = btrfs_header_nritems(old_root);
650                 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
651                                   GFP_NOFS);
652                 if (!tm_list) {
653                         ret = -ENOMEM;
654                         goto free_tms;
655                 }
656                 for (i = 0; i < nritems; i++) {
657                         tm_list[i] = alloc_tree_mod_elem(old_root, i,
658                             MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
659                         if (!tm_list[i]) {
660                                 ret = -ENOMEM;
661                                 goto free_tms;
662                         }
663                 }
664         }
665
666         tm = kzalloc(sizeof(*tm), GFP_NOFS);
667         if (!tm) {
668                 ret = -ENOMEM;
669                 goto free_tms;
670         }
671
672         tm->logical = new_root->start;
673         tm->old_root.logical = old_root->start;
674         tm->old_root.level = btrfs_header_level(old_root);
675         tm->generation = btrfs_header_generation(old_root);
676         tm->op = MOD_LOG_ROOT_REPLACE;
677
678         if (tree_mod_dont_log(fs_info, NULL))
679                 goto free_tms;
680
681         if (tm_list)
682                 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
683         if (!ret)
684                 ret = __tree_mod_log_insert(fs_info, tm);
685
686         write_unlock(&fs_info->tree_mod_log_lock);
687         if (ret)
688                 goto free_tms;
689         kfree(tm_list);
690
691         return ret;
692
693 free_tms:
694         if (tm_list) {
695                 for (i = 0; i < nritems; i++)
696                         kfree(tm_list[i]);
697                 kfree(tm_list);
698         }
699         kfree(tm);
700
701         return ret;
702 }
703
704 static struct tree_mod_elem *
705 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
706                       int smallest)
707 {
708         struct rb_root *tm_root;
709         struct rb_node *node;
710         struct tree_mod_elem *cur = NULL;
711         struct tree_mod_elem *found = NULL;
712
713         read_lock(&fs_info->tree_mod_log_lock);
714         tm_root = &fs_info->tree_mod_log;
715         node = tm_root->rb_node;
716         while (node) {
717                 cur = rb_entry(node, struct tree_mod_elem, node);
718                 if (cur->logical < start) {
719                         node = node->rb_left;
720                 } else if (cur->logical > start) {
721                         node = node->rb_right;
722                 } else if (cur->seq < min_seq) {
723                         node = node->rb_left;
724                 } else if (!smallest) {
725                         /* we want the node with the highest seq */
726                         if (found)
727                                 BUG_ON(found->seq > cur->seq);
728                         found = cur;
729                         node = node->rb_left;
730                 } else if (cur->seq > min_seq) {
731                         /* we want the node with the smallest seq */
732                         if (found)
733                                 BUG_ON(found->seq < cur->seq);
734                         found = cur;
735                         node = node->rb_right;
736                 } else {
737                         found = cur;
738                         break;
739                 }
740         }
741         read_unlock(&fs_info->tree_mod_log_lock);
742
743         return found;
744 }
745
746 /*
747  * this returns the element from the log with the smallest time sequence
748  * value that's in the log (the oldest log item). any element with a time
749  * sequence lower than min_seq will be ignored.
750  */
751 static struct tree_mod_elem *
752 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
753                            u64 min_seq)
754 {
755         return __tree_mod_log_search(fs_info, start, min_seq, 1);
756 }
757
758 /*
759  * this returns the element from the log with the largest time sequence
760  * value that's in the log (the most recent log item). any element with
761  * a time sequence lower than min_seq will be ignored.
762  */
763 static struct tree_mod_elem *
764 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
765 {
766         return __tree_mod_log_search(fs_info, start, min_seq, 0);
767 }
768
769 static noinline int
770 tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
771                      struct extent_buffer *src, unsigned long dst_offset,
772                      unsigned long src_offset, int nr_items)
773 {
774         int ret = 0;
775         struct tree_mod_elem **tm_list = NULL;
776         struct tree_mod_elem **tm_list_add, **tm_list_rem;
777         int i;
778         int locked = 0;
779
780         if (!tree_mod_need_log(fs_info, NULL))
781                 return 0;
782
783         if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
784                 return 0;
785
786         tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
787                           GFP_NOFS);
788         if (!tm_list)
789                 return -ENOMEM;
790
791         tm_list_add = tm_list;
792         tm_list_rem = tm_list + nr_items;
793         for (i = 0; i < nr_items; i++) {
794                 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
795                     MOD_LOG_KEY_REMOVE, GFP_NOFS);
796                 if (!tm_list_rem[i]) {
797                         ret = -ENOMEM;
798                         goto free_tms;
799                 }
800
801                 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
802                     MOD_LOG_KEY_ADD, GFP_NOFS);
803                 if (!tm_list_add[i]) {
804                         ret = -ENOMEM;
805                         goto free_tms;
806                 }
807         }
808
809         if (tree_mod_dont_log(fs_info, NULL))
810                 goto free_tms;
811         locked = 1;
812
813         for (i = 0; i < nr_items; i++) {
814                 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
815                 if (ret)
816                         goto free_tms;
817                 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
818                 if (ret)
819                         goto free_tms;
820         }
821
822         write_unlock(&fs_info->tree_mod_log_lock);
823         kfree(tm_list);
824
825         return 0;
826
827 free_tms:
828         for (i = 0; i < nr_items * 2; i++) {
829                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
830                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
831                 kfree(tm_list[i]);
832         }
833         if (locked)
834                 write_unlock(&fs_info->tree_mod_log_lock);
835         kfree(tm_list);
836
837         return ret;
838 }
839
840 static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
841 {
842         struct tree_mod_elem **tm_list = NULL;
843         int nritems = 0;
844         int i;
845         int ret = 0;
846
847         if (btrfs_header_level(eb) == 0)
848                 return 0;
849
850         if (!tree_mod_need_log(eb->fs_info, NULL))
851                 return 0;
852
853         nritems = btrfs_header_nritems(eb);
854         tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
855         if (!tm_list)
856                 return -ENOMEM;
857
858         for (i = 0; i < nritems; i++) {
859                 tm_list[i] = alloc_tree_mod_elem(eb, i,
860                     MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
861                 if (!tm_list[i]) {
862                         ret = -ENOMEM;
863                         goto free_tms;
864                 }
865         }
866
867         if (tree_mod_dont_log(eb->fs_info, eb))
868                 goto free_tms;
869
870         ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
871         write_unlock(&eb->fs_info->tree_mod_log_lock);
872         if (ret)
873                 goto free_tms;
874         kfree(tm_list);
875
876         return 0;
877
878 free_tms:
879         for (i = 0; i < nritems; i++)
880                 kfree(tm_list[i]);
881         kfree(tm_list);
882
883         return ret;
884 }
885
886 static noinline void
887 tree_mod_log_set_root_pointer(struct btrfs_root *root,
888                               struct extent_buffer *new_root_node,
889                               int log_removal)
890 {
891         int ret;
892         ret = tree_mod_log_insert_root(root->node, new_root_node, log_removal);
893         BUG_ON(ret < 0);
894 }
895
896 /*
897  * check if the tree block can be shared by multiple trees
898  */
899 int btrfs_block_can_be_shared(struct btrfs_root *root,
900                               struct extent_buffer *buf)
901 {
902         /*
903          * Tree blocks not in reference counted trees and tree roots
904          * are never shared. If a block was allocated after the last
905          * snapshot and the block was not allocated by tree relocation,
906          * we know the block is not shared.
907          */
908         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
909             buf != root->node && buf != root->commit_root &&
910             (btrfs_header_generation(buf) <=
911              btrfs_root_last_snapshot(&root->root_item) ||
912              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
913                 return 1;
914 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
915         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
916             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
917                 return 1;
918 #endif
919         return 0;
920 }
921
922 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
923                                        struct btrfs_root *root,
924                                        struct extent_buffer *buf,
925                                        struct extent_buffer *cow,
926                                        int *last_ref)
927 {
928         struct btrfs_fs_info *fs_info = root->fs_info;
929         u64 refs;
930         u64 owner;
931         u64 flags;
932         u64 new_flags = 0;
933         int ret;
934
935         /*
936          * Backrefs update rules:
937          *
938          * Always use full backrefs for extent pointers in tree block
939          * allocated by tree relocation.
940          *
941          * If a shared tree block is no longer referenced by its owner
942          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
943          * use full backrefs for extent pointers in tree block.
944          *
945          * If a tree block is been relocating
946          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
947          * use full backrefs for extent pointers in tree block.
948          * The reason for this is some operations (such as drop tree)
949          * are only allowed for blocks use full backrefs.
950          */
951
952         if (btrfs_block_can_be_shared(root, buf)) {
953                 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
954                                                btrfs_header_level(buf), 1,
955                                                &refs, &flags);
956                 if (ret)
957                         return ret;
958                 if (refs == 0) {
959                         ret = -EROFS;
960                         btrfs_handle_fs_error(fs_info, ret, NULL);
961                         return ret;
962                 }
963         } else {
964                 refs = 1;
965                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
966                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
967                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
968                 else
969                         flags = 0;
970         }
971
972         owner = btrfs_header_owner(buf);
973         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
974                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
975
976         if (refs > 1) {
977                 if ((owner == root->root_key.objectid ||
978                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
979                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
980                         ret = btrfs_inc_ref(trans, root, buf, 1);
981                         if (ret)
982                                 return ret;
983
984                         if (root->root_key.objectid ==
985                             BTRFS_TREE_RELOC_OBJECTID) {
986                                 ret = btrfs_dec_ref(trans, root, buf, 0);
987                                 if (ret)
988                                         return ret;
989                                 ret = btrfs_inc_ref(trans, root, cow, 1);
990                                 if (ret)
991                                         return ret;
992                         }
993                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
994                 } else {
995
996                         if (root->root_key.objectid ==
997                             BTRFS_TREE_RELOC_OBJECTID)
998                                 ret = btrfs_inc_ref(trans, root, cow, 1);
999                         else
1000                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1001                         if (ret)
1002                                 return ret;
1003                 }
1004                 if (new_flags != 0) {
1005                         int level = btrfs_header_level(buf);
1006
1007                         ret = btrfs_set_disk_extent_flags(trans, fs_info,
1008                                                           buf->start,
1009                                                           buf->len,
1010                                                           new_flags, level, 0);
1011                         if (ret)
1012                                 return ret;
1013                 }
1014         } else {
1015                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
1016                         if (root->root_key.objectid ==
1017                             BTRFS_TREE_RELOC_OBJECTID)
1018                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1019                         else
1020                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1021                         if (ret)
1022                                 return ret;
1023                         ret = btrfs_dec_ref(trans, root, buf, 1);
1024                         if (ret)
1025                                 return ret;
1026                 }
1027                 clean_tree_block(fs_info, buf);
1028                 *last_ref = 1;
1029         }
1030         return 0;
1031 }
1032
1033 /*
1034  * does the dirty work in cow of a single block.  The parent block (if
1035  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1036  * dirty and returned locked.  If you modify the block it needs to be marked
1037  * dirty again.
1038  *
1039  * search_start -- an allocation hint for the new block
1040  *
1041  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1042  * bytes the allocator should try to find free next to the block it returns.
1043  * This is just a hint and may be ignored by the allocator.
1044  */
1045 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1046                              struct btrfs_root *root,
1047                              struct extent_buffer *buf,
1048                              struct extent_buffer *parent, int parent_slot,
1049                              struct extent_buffer **cow_ret,
1050                              u64 search_start, u64 empty_size)
1051 {
1052         struct btrfs_fs_info *fs_info = root->fs_info;
1053         struct btrfs_disk_key disk_key;
1054         struct extent_buffer *cow;
1055         int level, ret;
1056         int last_ref = 0;
1057         int unlock_orig = 0;
1058         u64 parent_start = 0;
1059
1060         if (*cow_ret == buf)
1061                 unlock_orig = 1;
1062
1063         btrfs_assert_tree_locked(buf);
1064
1065         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1066                 trans->transid != fs_info->running_transaction->transid);
1067         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1068                 trans->transid != root->last_trans);
1069
1070         level = btrfs_header_level(buf);
1071
1072         if (level == 0)
1073                 btrfs_item_key(buf, &disk_key, 0);
1074         else
1075                 btrfs_node_key(buf, &disk_key, 0);
1076
1077         if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1078                 parent_start = parent->start;
1079
1080         cow = btrfs_alloc_tree_block(trans, root, parent_start,
1081                         root->root_key.objectid, &disk_key, level,
1082                         search_start, empty_size);
1083         if (IS_ERR(cow))
1084                 return PTR_ERR(cow);
1085
1086         /* cow is set to blocking by btrfs_init_new_buffer */
1087
1088         copy_extent_buffer_full(cow, buf);
1089         btrfs_set_header_bytenr(cow, cow->start);
1090         btrfs_set_header_generation(cow, trans->transid);
1091         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1092         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1093                                      BTRFS_HEADER_FLAG_RELOC);
1094         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1095                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1096         else
1097                 btrfs_set_header_owner(cow, root->root_key.objectid);
1098
1099         write_extent_buffer_fsid(cow, fs_info->fsid);
1100
1101         ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1102         if (ret) {
1103                 btrfs_abort_transaction(trans, ret);
1104                 return ret;
1105         }
1106
1107         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1108                 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1109                 if (ret) {
1110                         btrfs_abort_transaction(trans, ret);
1111                         return ret;
1112                 }
1113         }
1114
1115         if (buf == root->node) {
1116                 WARN_ON(parent && parent != buf);
1117                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1118                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1119                         parent_start = buf->start;
1120
1121                 extent_buffer_get(cow);
1122                 tree_mod_log_set_root_pointer(root, cow, 1);
1123                 rcu_assign_pointer(root->node, cow);
1124
1125                 btrfs_free_tree_block(trans, root, buf, parent_start,
1126                                       last_ref);
1127                 free_extent_buffer(buf);
1128                 add_root_to_dirty_list(root);
1129         } else {
1130                 WARN_ON(trans->transid != btrfs_header_generation(parent));
1131                 tree_mod_log_insert_key(parent, parent_slot,
1132                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1133                 btrfs_set_node_blockptr(parent, parent_slot,
1134                                         cow->start);
1135                 btrfs_set_node_ptr_generation(parent, parent_slot,
1136                                               trans->transid);
1137                 btrfs_mark_buffer_dirty(parent);
1138                 if (last_ref) {
1139                         ret = tree_mod_log_free_eb(buf);
1140                         if (ret) {
1141                                 btrfs_abort_transaction(trans, ret);
1142                                 return ret;
1143                         }
1144                 }
1145                 btrfs_free_tree_block(trans, root, buf, parent_start,
1146                                       last_ref);
1147         }
1148         if (unlock_orig)
1149                 btrfs_tree_unlock(buf);
1150         free_extent_buffer_stale(buf);
1151         btrfs_mark_buffer_dirty(cow);
1152         *cow_ret = cow;
1153         return 0;
1154 }
1155
1156 /*
1157  * returns the logical address of the oldest predecessor of the given root.
1158  * entries older than time_seq are ignored.
1159  */
1160 static struct tree_mod_elem *__tree_mod_log_oldest_root(
1161                 struct extent_buffer *eb_root, u64 time_seq)
1162 {
1163         struct tree_mod_elem *tm;
1164         struct tree_mod_elem *found = NULL;
1165         u64 root_logical = eb_root->start;
1166         int looped = 0;
1167
1168         if (!time_seq)
1169                 return NULL;
1170
1171         /*
1172          * the very last operation that's logged for a root is the
1173          * replacement operation (if it is replaced at all). this has
1174          * the logical address of the *new* root, making it the very
1175          * first operation that's logged for this root.
1176          */
1177         while (1) {
1178                 tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
1179                                                 time_seq);
1180                 if (!looped && !tm)
1181                         return NULL;
1182                 /*
1183                  * if there are no tree operation for the oldest root, we simply
1184                  * return it. this should only happen if that (old) root is at
1185                  * level 0.
1186                  */
1187                 if (!tm)
1188                         break;
1189
1190                 /*
1191                  * if there's an operation that's not a root replacement, we
1192                  * found the oldest version of our root. normally, we'll find a
1193                  * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1194                  */
1195                 if (tm->op != MOD_LOG_ROOT_REPLACE)
1196                         break;
1197
1198                 found = tm;
1199                 root_logical = tm->old_root.logical;
1200                 looped = 1;
1201         }
1202
1203         /* if there's no old root to return, return what we found instead */
1204         if (!found)
1205                 found = tm;
1206
1207         return found;
1208 }
1209
1210 /*
1211  * tm is a pointer to the first operation to rewind within eb. then, all
1212  * previous operations will be rewound (until we reach something older than
1213  * time_seq).
1214  */
1215 static void
1216 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1217                       u64 time_seq, struct tree_mod_elem *first_tm)
1218 {
1219         u32 n;
1220         struct rb_node *next;
1221         struct tree_mod_elem *tm = first_tm;
1222         unsigned long o_dst;
1223         unsigned long o_src;
1224         unsigned long p_size = sizeof(struct btrfs_key_ptr);
1225
1226         n = btrfs_header_nritems(eb);
1227         read_lock(&fs_info->tree_mod_log_lock);
1228         while (tm && tm->seq >= time_seq) {
1229                 /*
1230                  * all the operations are recorded with the operator used for
1231                  * the modification. as we're going backwards, we do the
1232                  * opposite of each operation here.
1233                  */
1234                 switch (tm->op) {
1235                 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1236                         BUG_ON(tm->slot < n);
1237                         /* Fallthrough */
1238                 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1239                 case MOD_LOG_KEY_REMOVE:
1240                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1241                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1242                         btrfs_set_node_ptr_generation(eb, tm->slot,
1243                                                       tm->generation);
1244                         n++;
1245                         break;
1246                 case MOD_LOG_KEY_REPLACE:
1247                         BUG_ON(tm->slot >= n);
1248                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1249                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1250                         btrfs_set_node_ptr_generation(eb, tm->slot,
1251                                                       tm->generation);
1252                         break;
1253                 case MOD_LOG_KEY_ADD:
1254                         /* if a move operation is needed it's in the log */
1255                         n--;
1256                         break;
1257                 case MOD_LOG_MOVE_KEYS:
1258                         o_dst = btrfs_node_key_ptr_offset(tm->slot);
1259                         o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1260                         memmove_extent_buffer(eb, o_dst, o_src,
1261                                               tm->move.nr_items * p_size);
1262                         break;
1263                 case MOD_LOG_ROOT_REPLACE:
1264                         /*
1265                          * this operation is special. for roots, this must be
1266                          * handled explicitly before rewinding.
1267                          * for non-roots, this operation may exist if the node
1268                          * was a root: root A -> child B; then A gets empty and
1269                          * B is promoted to the new root. in the mod log, we'll
1270                          * have a root-replace operation for B, a tree block
1271                          * that is no root. we simply ignore that operation.
1272                          */
1273                         break;
1274                 }
1275                 next = rb_next(&tm->node);
1276                 if (!next)
1277                         break;
1278                 tm = rb_entry(next, struct tree_mod_elem, node);
1279                 if (tm->logical != first_tm->logical)
1280                         break;
1281         }
1282         read_unlock(&fs_info->tree_mod_log_lock);
1283         btrfs_set_header_nritems(eb, n);
1284 }
1285
1286 /*
1287  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1288  * is returned. If rewind operations happen, a fresh buffer is returned. The
1289  * returned buffer is always read-locked. If the returned buffer is not the
1290  * input buffer, the lock on the input buffer is released and the input buffer
1291  * is freed (its refcount is decremented).
1292  */
1293 static struct extent_buffer *
1294 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1295                     struct extent_buffer *eb, u64 time_seq)
1296 {
1297         struct extent_buffer *eb_rewin;
1298         struct tree_mod_elem *tm;
1299
1300         if (!time_seq)
1301                 return eb;
1302
1303         if (btrfs_header_level(eb) == 0)
1304                 return eb;
1305
1306         tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1307         if (!tm)
1308                 return eb;
1309
1310         btrfs_set_path_blocking(path);
1311         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1312
1313         if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1314                 BUG_ON(tm->slot != 0);
1315                 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1316                 if (!eb_rewin) {
1317                         btrfs_tree_read_unlock_blocking(eb);
1318                         free_extent_buffer(eb);
1319                         return NULL;
1320                 }
1321                 btrfs_set_header_bytenr(eb_rewin, eb->start);
1322                 btrfs_set_header_backref_rev(eb_rewin,
1323                                              btrfs_header_backref_rev(eb));
1324                 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1325                 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1326         } else {
1327                 eb_rewin = btrfs_clone_extent_buffer(eb);
1328                 if (!eb_rewin) {
1329                         btrfs_tree_read_unlock_blocking(eb);
1330                         free_extent_buffer(eb);
1331                         return NULL;
1332                 }
1333         }
1334
1335         btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1336         btrfs_tree_read_unlock_blocking(eb);
1337         free_extent_buffer(eb);
1338
1339         extent_buffer_get(eb_rewin);
1340         btrfs_tree_read_lock(eb_rewin);
1341         __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1342         WARN_ON(btrfs_header_nritems(eb_rewin) >
1343                 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1344
1345         return eb_rewin;
1346 }
1347
1348 /*
1349  * get_old_root() rewinds the state of @root's root node to the given @time_seq
1350  * value. If there are no changes, the current root->root_node is returned. If
1351  * anything changed in between, there's a fresh buffer allocated on which the
1352  * rewind operations are done. In any case, the returned buffer is read locked.
1353  * Returns NULL on error (with no locks held).
1354  */
1355 static inline struct extent_buffer *
1356 get_old_root(struct btrfs_root *root, u64 time_seq)
1357 {
1358         struct btrfs_fs_info *fs_info = root->fs_info;
1359         struct tree_mod_elem *tm;
1360         struct extent_buffer *eb = NULL;
1361         struct extent_buffer *eb_root;
1362         struct extent_buffer *old;
1363         struct tree_mod_root *old_root = NULL;
1364         u64 old_generation = 0;
1365         u64 logical;
1366
1367         eb_root = btrfs_read_lock_root_node(root);
1368         tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1369         if (!tm)
1370                 return eb_root;
1371
1372         if (tm->op == MOD_LOG_ROOT_REPLACE) {
1373                 old_root = &tm->old_root;
1374                 old_generation = tm->generation;
1375                 logical = old_root->logical;
1376         } else {
1377                 logical = eb_root->start;
1378         }
1379
1380         tm = tree_mod_log_search(fs_info, logical, time_seq);
1381         if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1382                 btrfs_tree_read_unlock(eb_root);
1383                 free_extent_buffer(eb_root);
1384                 old = read_tree_block(fs_info, logical, 0);
1385                 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1386                         if (!IS_ERR(old))
1387                                 free_extent_buffer(old);
1388                         btrfs_warn(fs_info,
1389                                    "failed to read tree block %llu from get_old_root",
1390                                    logical);
1391                 } else {
1392                         eb = btrfs_clone_extent_buffer(old);
1393                         free_extent_buffer(old);
1394                 }
1395         } else if (old_root) {
1396                 btrfs_tree_read_unlock(eb_root);
1397                 free_extent_buffer(eb_root);
1398                 eb = alloc_dummy_extent_buffer(fs_info, logical);
1399         } else {
1400                 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1401                 eb = btrfs_clone_extent_buffer(eb_root);
1402                 btrfs_tree_read_unlock_blocking(eb_root);
1403                 free_extent_buffer(eb_root);
1404         }
1405
1406         if (!eb)
1407                 return NULL;
1408         extent_buffer_get(eb);
1409         btrfs_tree_read_lock(eb);
1410         if (old_root) {
1411                 btrfs_set_header_bytenr(eb, eb->start);
1412                 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1413                 btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
1414                 btrfs_set_header_level(eb, old_root->level);
1415                 btrfs_set_header_generation(eb, old_generation);
1416         }
1417         if (tm)
1418                 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1419         else
1420                 WARN_ON(btrfs_header_level(eb) != 0);
1421         WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1422
1423         return eb;
1424 }
1425
1426 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1427 {
1428         struct tree_mod_elem *tm;
1429         int level;
1430         struct extent_buffer *eb_root = btrfs_root_node(root);
1431
1432         tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1433         if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1434                 level = tm->old_root.level;
1435         } else {
1436                 level = btrfs_header_level(eb_root);
1437         }
1438         free_extent_buffer(eb_root);
1439
1440         return level;
1441 }
1442
1443 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1444                                    struct btrfs_root *root,
1445                                    struct extent_buffer *buf)
1446 {
1447         if (btrfs_is_testing(root->fs_info))
1448                 return 0;
1449
1450         /* ensure we can see the force_cow */
1451         smp_rmb();
1452
1453         /*
1454          * We do not need to cow a block if
1455          * 1) this block is not created or changed in this transaction;
1456          * 2) this block does not belong to TREE_RELOC tree;
1457          * 3) the root is not forced COW.
1458          *
1459          * What is forced COW:
1460          *    when we create snapshot during committing the transaction,
1461          *    after we've finished coping src root, we must COW the shared
1462          *    block to ensure the metadata consistency.
1463          */
1464         if (btrfs_header_generation(buf) == trans->transid &&
1465             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1466             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1467               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1468             !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1469                 return 0;
1470         return 1;
1471 }
1472
1473 /*
1474  * cows a single block, see __btrfs_cow_block for the real work.
1475  * This version of it has extra checks so that a block isn't COWed more than
1476  * once per transaction, as long as it hasn't been written yet
1477  */
1478 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1479                     struct btrfs_root *root, struct extent_buffer *buf,
1480                     struct extent_buffer *parent, int parent_slot,
1481                     struct extent_buffer **cow_ret)
1482 {
1483         struct btrfs_fs_info *fs_info = root->fs_info;
1484         u64 search_start;
1485         int ret;
1486
1487         if (trans->transaction != fs_info->running_transaction)
1488                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1489                        trans->transid,
1490                        fs_info->running_transaction->transid);
1491
1492         if (trans->transid != fs_info->generation)
1493                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1494                        trans->transid, fs_info->generation);
1495
1496         if (!should_cow_block(trans, root, buf)) {
1497                 trans->dirty = true;
1498                 *cow_ret = buf;
1499                 return 0;
1500         }
1501
1502         search_start = buf->start & ~((u64)SZ_1G - 1);
1503
1504         if (parent)
1505                 btrfs_set_lock_blocking(parent);
1506         btrfs_set_lock_blocking(buf);
1507
1508         ret = __btrfs_cow_block(trans, root, buf, parent,
1509                                  parent_slot, cow_ret, search_start, 0);
1510
1511         trace_btrfs_cow_block(root, buf, *cow_ret);
1512
1513         return ret;
1514 }
1515
1516 /*
1517  * helper function for defrag to decide if two blocks pointed to by a
1518  * node are actually close by
1519  */
1520 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1521 {
1522         if (blocknr < other && other - (blocknr + blocksize) < 32768)
1523                 return 1;
1524         if (blocknr > other && blocknr - (other + blocksize) < 32768)
1525                 return 1;
1526         return 0;
1527 }
1528
1529 /*
1530  * compare two keys in a memcmp fashion
1531  */
1532 static int comp_keys(const struct btrfs_disk_key *disk,
1533                      const struct btrfs_key *k2)
1534 {
1535         struct btrfs_key k1;
1536
1537         btrfs_disk_key_to_cpu(&k1, disk);
1538
1539         return btrfs_comp_cpu_keys(&k1, k2);
1540 }
1541
1542 /*
1543  * same as comp_keys only with two btrfs_key's
1544  */
1545 int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1546 {
1547         if (k1->objectid > k2->objectid)
1548                 return 1;
1549         if (k1->objectid < k2->objectid)
1550                 return -1;
1551         if (k1->type > k2->type)
1552                 return 1;
1553         if (k1->type < k2->type)
1554                 return -1;
1555         if (k1->offset > k2->offset)
1556                 return 1;
1557         if (k1->offset < k2->offset)
1558                 return -1;
1559         return 0;
1560 }
1561
1562 /*
1563  * this is used by the defrag code to go through all the
1564  * leaves pointed to by a node and reallocate them so that
1565  * disk order is close to key order
1566  */
1567 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1568                        struct btrfs_root *root, struct extent_buffer *parent,
1569                        int start_slot, u64 *last_ret,
1570                        struct btrfs_key *progress)
1571 {
1572         struct btrfs_fs_info *fs_info = root->fs_info;
1573         struct extent_buffer *cur;
1574         u64 blocknr;
1575         u64 gen;
1576         u64 search_start = *last_ret;
1577         u64 last_block = 0;
1578         u64 other;
1579         u32 parent_nritems;
1580         int end_slot;
1581         int i;
1582         int err = 0;
1583         int parent_level;
1584         int uptodate;
1585         u32 blocksize;
1586         int progress_passed = 0;
1587         struct btrfs_disk_key disk_key;
1588
1589         parent_level = btrfs_header_level(parent);
1590
1591         WARN_ON(trans->transaction != fs_info->running_transaction);
1592         WARN_ON(trans->transid != fs_info->generation);
1593
1594         parent_nritems = btrfs_header_nritems(parent);
1595         blocksize = fs_info->nodesize;
1596         end_slot = parent_nritems - 1;
1597
1598         if (parent_nritems <= 1)
1599                 return 0;
1600
1601         btrfs_set_lock_blocking(parent);
1602
1603         for (i = start_slot; i <= end_slot; i++) {
1604                 int close = 1;
1605
1606                 btrfs_node_key(parent, &disk_key, i);
1607                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1608                         continue;
1609
1610                 progress_passed = 1;
1611                 blocknr = btrfs_node_blockptr(parent, i);
1612                 gen = btrfs_node_ptr_generation(parent, i);
1613                 if (last_block == 0)
1614                         last_block = blocknr;
1615
1616                 if (i > 0) {
1617                         other = btrfs_node_blockptr(parent, i - 1);
1618                         close = close_blocks(blocknr, other, blocksize);
1619                 }
1620                 if (!close && i < end_slot) {
1621                         other = btrfs_node_blockptr(parent, i + 1);
1622                         close = close_blocks(blocknr, other, blocksize);
1623                 }
1624                 if (close) {
1625                         last_block = blocknr;
1626                         continue;
1627                 }
1628
1629                 cur = find_extent_buffer(fs_info, blocknr);
1630                 if (cur)
1631                         uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1632                 else
1633                         uptodate = 0;
1634                 if (!cur || !uptodate) {
1635                         if (!cur) {
1636                                 cur = read_tree_block(fs_info, blocknr, gen);
1637                                 if (IS_ERR(cur)) {
1638                                         return PTR_ERR(cur);
1639                                 } else if (!extent_buffer_uptodate(cur)) {
1640                                         free_extent_buffer(cur);
1641                                         return -EIO;
1642                                 }
1643                         } else if (!uptodate) {
1644                                 err = btrfs_read_buffer(cur, gen);
1645                                 if (err) {
1646                                         free_extent_buffer(cur);
1647                                         return err;
1648                                 }
1649                         }
1650                 }
1651                 if (search_start == 0)
1652                         search_start = last_block;
1653
1654                 btrfs_tree_lock(cur);
1655                 btrfs_set_lock_blocking(cur);
1656                 err = __btrfs_cow_block(trans, root, cur, parent, i,
1657                                         &cur, search_start,
1658                                         min(16 * blocksize,
1659                                             (end_slot - i) * blocksize));
1660                 if (err) {
1661                         btrfs_tree_unlock(cur);
1662                         free_extent_buffer(cur);
1663                         break;
1664                 }
1665                 search_start = cur->start;
1666                 last_block = cur->start;
1667                 *last_ret = search_start;
1668                 btrfs_tree_unlock(cur);
1669                 free_extent_buffer(cur);
1670         }
1671         return err;
1672 }
1673
1674 /*
1675  * search for key in the extent_buffer.  The items start at offset p,
1676  * and they are item_size apart.  There are 'max' items in p.
1677  *
1678  * the slot in the array is returned via slot, and it points to
1679  * the place where you would insert key if it is not found in
1680  * the array.
1681  *
1682  * slot may point to max if the key is bigger than all of the keys
1683  */
1684 static noinline int generic_bin_search(struct extent_buffer *eb,
1685                                        unsigned long p, int item_size,
1686                                        const struct btrfs_key *key,
1687                                        int max, int *slot)
1688 {
1689         int low = 0;
1690         int high = max;
1691         int mid;
1692         int ret;
1693         struct btrfs_disk_key *tmp = NULL;
1694         struct btrfs_disk_key unaligned;
1695         unsigned long offset;
1696         char *kaddr = NULL;
1697         unsigned long map_start = 0;
1698         unsigned long map_len = 0;
1699         int err;
1700
1701         if (low > high) {
1702                 btrfs_err(eb->fs_info,
1703                  "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1704                           __func__, low, high, eb->start,
1705                           btrfs_header_owner(eb), btrfs_header_level(eb));
1706                 return -EINVAL;
1707         }
1708
1709         while (low < high) {
1710                 mid = (low + high) / 2;
1711                 offset = p + mid * item_size;
1712
1713                 if (!kaddr || offset < map_start ||
1714                     (offset + sizeof(struct btrfs_disk_key)) >
1715                     map_start + map_len) {
1716
1717                         err = map_private_extent_buffer(eb, offset,
1718                                                 sizeof(struct btrfs_disk_key),
1719                                                 &kaddr, &map_start, &map_len);
1720
1721                         if (!err) {
1722                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1723                                                         map_start);
1724                         } else if (err == 1) {
1725                                 read_extent_buffer(eb, &unaligned,
1726                                                    offset, sizeof(unaligned));
1727                                 tmp = &unaligned;
1728                         } else {
1729                                 return err;
1730                         }
1731
1732                 } else {
1733                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
1734                                                         map_start);
1735                 }
1736                 ret = comp_keys(tmp, key);
1737
1738                 if (ret < 0)
1739                         low = mid + 1;
1740                 else if (ret > 0)
1741                         high = mid;
1742                 else {
1743                         *slot = mid;
1744                         return 0;
1745                 }
1746         }
1747         *slot = low;
1748         return 1;
1749 }
1750
1751 /*
1752  * simple bin_search frontend that does the right thing for
1753  * leaves vs nodes
1754  */
1755 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1756                      int level, int *slot)
1757 {
1758         if (level == 0)
1759                 return generic_bin_search(eb,
1760                                           offsetof(struct btrfs_leaf, items),
1761                                           sizeof(struct btrfs_item),
1762                                           key, btrfs_header_nritems(eb),
1763                                           slot);
1764         else
1765                 return generic_bin_search(eb,
1766                                           offsetof(struct btrfs_node, ptrs),
1767                                           sizeof(struct btrfs_key_ptr),
1768                                           key, btrfs_header_nritems(eb),
1769                                           slot);
1770 }
1771
1772 static void root_add_used(struct btrfs_root *root, u32 size)
1773 {
1774         spin_lock(&root->accounting_lock);
1775         btrfs_set_root_used(&root->root_item,
1776                             btrfs_root_used(&root->root_item) + size);
1777         spin_unlock(&root->accounting_lock);
1778 }
1779
1780 static void root_sub_used(struct btrfs_root *root, u32 size)
1781 {
1782         spin_lock(&root->accounting_lock);
1783         btrfs_set_root_used(&root->root_item,
1784                             btrfs_root_used(&root->root_item) - size);
1785         spin_unlock(&root->accounting_lock);
1786 }
1787
1788 /* given a node and slot number, this reads the blocks it points to.  The
1789  * extent buffer is returned with a reference taken (but unlocked).
1790  */
1791 static noinline struct extent_buffer *
1792 read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
1793                int slot)
1794 {
1795         int level = btrfs_header_level(parent);
1796         struct extent_buffer *eb;
1797
1798         if (slot < 0 || slot >= btrfs_header_nritems(parent))
1799                 return ERR_PTR(-ENOENT);
1800
1801         BUG_ON(level == 0);
1802
1803         eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1804                              btrfs_node_ptr_generation(parent, slot));
1805         if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1806                 free_extent_buffer(eb);
1807                 eb = ERR_PTR(-EIO);
1808         }
1809
1810         return eb;
1811 }
1812
1813 /*
1814  * node level balancing, used to make sure nodes are in proper order for
1815  * item deletion.  We balance from the top down, so we have to make sure
1816  * that a deletion won't leave an node completely empty later on.
1817  */
1818 static noinline int balance_level(struct btrfs_trans_handle *trans,
1819                          struct btrfs_root *root,
1820                          struct btrfs_path *path, int level)
1821 {
1822         struct btrfs_fs_info *fs_info = root->fs_info;
1823         struct extent_buffer *right = NULL;
1824         struct extent_buffer *mid;
1825         struct extent_buffer *left = NULL;
1826         struct extent_buffer *parent = NULL;
1827         int ret = 0;
1828         int wret;
1829         int pslot;
1830         int orig_slot = path->slots[level];
1831         u64 orig_ptr;
1832
1833         if (level == 0)
1834                 return 0;
1835
1836         mid = path->nodes[level];
1837
1838         WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1839                 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1840         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1841
1842         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1843
1844         if (level < BTRFS_MAX_LEVEL - 1) {
1845                 parent = path->nodes[level + 1];
1846                 pslot = path->slots[level + 1];
1847         }
1848
1849         /*
1850          * deal with the case where there is only one pointer in the root
1851          * by promoting the node below to a root
1852          */
1853         if (!parent) {
1854                 struct extent_buffer *child;
1855
1856                 if (btrfs_header_nritems(mid) != 1)
1857                         return 0;
1858
1859                 /* promote the child to a root */
1860                 child = read_node_slot(fs_info, mid, 0);
1861                 if (IS_ERR(child)) {
1862                         ret = PTR_ERR(child);
1863                         btrfs_handle_fs_error(fs_info, ret, NULL);
1864                         goto enospc;
1865                 }
1866
1867                 btrfs_tree_lock(child);
1868                 btrfs_set_lock_blocking(child);
1869                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1870                 if (ret) {
1871                         btrfs_tree_unlock(child);
1872                         free_extent_buffer(child);
1873                         goto enospc;
1874                 }
1875
1876                 tree_mod_log_set_root_pointer(root, child, 1);
1877                 rcu_assign_pointer(root->node, child);
1878
1879                 add_root_to_dirty_list(root);
1880                 btrfs_tree_unlock(child);
1881
1882                 path->locks[level] = 0;
1883                 path->nodes[level] = NULL;
1884                 clean_tree_block(fs_info, mid);
1885                 btrfs_tree_unlock(mid);
1886                 /* once for the path */
1887                 free_extent_buffer(mid);
1888
1889                 root_sub_used(root, mid->len);
1890                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1891                 /* once for the root ptr */
1892                 free_extent_buffer_stale(mid);
1893                 return 0;
1894         }
1895         if (btrfs_header_nritems(mid) >
1896             BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1897                 return 0;
1898
1899         left = read_node_slot(fs_info, parent, pslot - 1);
1900         if (IS_ERR(left))
1901                 left = NULL;
1902
1903         if (left) {
1904                 btrfs_tree_lock(left);
1905                 btrfs_set_lock_blocking(left);
1906                 wret = btrfs_cow_block(trans, root, left,
1907                                        parent, pslot - 1, &left);
1908                 if (wret) {
1909                         ret = wret;
1910                         goto enospc;
1911                 }
1912         }
1913
1914         right = read_node_slot(fs_info, parent, pslot + 1);
1915         if (IS_ERR(right))
1916                 right = NULL;
1917
1918         if (right) {
1919                 btrfs_tree_lock(right);
1920                 btrfs_set_lock_blocking(right);
1921                 wret = btrfs_cow_block(trans, root, right,
1922                                        parent, pslot + 1, &right);
1923                 if (wret) {
1924                         ret = wret;
1925                         goto enospc;
1926                 }
1927         }
1928
1929         /* first, try to make some room in the middle buffer */
1930         if (left) {
1931                 orig_slot += btrfs_header_nritems(left);
1932                 wret = push_node_left(trans, fs_info, left, mid, 1);
1933                 if (wret < 0)
1934                         ret = wret;
1935         }
1936
1937         /*
1938          * then try to empty the right most buffer into the middle
1939          */
1940         if (right) {
1941                 wret = push_node_left(trans, fs_info, mid, right, 1);
1942                 if (wret < 0 && wret != -ENOSPC)
1943                         ret = wret;
1944                 if (btrfs_header_nritems(right) == 0) {
1945                         clean_tree_block(fs_info, right);
1946                         btrfs_tree_unlock(right);
1947                         del_ptr(root, path, level + 1, pslot + 1);
1948                         root_sub_used(root, right->len);
1949                         btrfs_free_tree_block(trans, root, right, 0, 1);
1950                         free_extent_buffer_stale(right);
1951                         right = NULL;
1952                 } else {
1953                         struct btrfs_disk_key right_key;
1954                         btrfs_node_key(right, &right_key, 0);
1955                         ret = tree_mod_log_insert_key(parent, pslot + 1,
1956                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1957                         BUG_ON(ret < 0);
1958                         btrfs_set_node_key(parent, &right_key, pslot + 1);
1959                         btrfs_mark_buffer_dirty(parent);
1960                 }
1961         }
1962         if (btrfs_header_nritems(mid) == 1) {
1963                 /*
1964                  * we're not allowed to leave a node with one item in the
1965                  * tree during a delete.  A deletion from lower in the tree
1966                  * could try to delete the only pointer in this node.
1967                  * So, pull some keys from the left.
1968                  * There has to be a left pointer at this point because
1969                  * otherwise we would have pulled some pointers from the
1970                  * right
1971                  */
1972                 if (!left) {
1973                         ret = -EROFS;
1974                         btrfs_handle_fs_error(fs_info, ret, NULL);
1975                         goto enospc;
1976                 }
1977                 wret = balance_node_right(trans, fs_info, mid, left);
1978                 if (wret < 0) {
1979                         ret = wret;
1980                         goto enospc;
1981                 }
1982                 if (wret == 1) {
1983                         wret = push_node_left(trans, fs_info, left, mid, 1);
1984                         if (wret < 0)
1985                                 ret = wret;
1986                 }
1987                 BUG_ON(wret == 1);
1988         }
1989         if (btrfs_header_nritems(mid) == 0) {
1990                 clean_tree_block(fs_info, mid);
1991                 btrfs_tree_unlock(mid);
1992                 del_ptr(root, path, level + 1, pslot);
1993                 root_sub_used(root, mid->len);
1994                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1995                 free_extent_buffer_stale(mid);
1996                 mid = NULL;
1997         } else {
1998                 /* update the parent key to reflect our changes */
1999                 struct btrfs_disk_key mid_key;
2000                 btrfs_node_key(mid, &mid_key, 0);
2001                 ret = tree_mod_log_insert_key(parent, pslot,
2002                                 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2003                 BUG_ON(ret < 0);
2004                 btrfs_set_node_key(parent, &mid_key, pslot);
2005                 btrfs_mark_buffer_dirty(parent);
2006         }
2007
2008         /* update the path */
2009         if (left) {
2010                 if (btrfs_header_nritems(left) > orig_slot) {
2011                         extent_buffer_get(left);
2012                         /* left was locked after cow */
2013                         path->nodes[level] = left;
2014                         path->slots[level + 1] -= 1;
2015                         path->slots[level] = orig_slot;
2016                         if (mid) {
2017                                 btrfs_tree_unlock(mid);
2018                                 free_extent_buffer(mid);
2019                         }
2020                 } else {
2021                         orig_slot -= btrfs_header_nritems(left);
2022                         path->slots[level] = orig_slot;
2023                 }
2024         }
2025         /* double check we haven't messed things up */
2026         if (orig_ptr !=
2027             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2028                 BUG();
2029 enospc:
2030         if (right) {
2031                 btrfs_tree_unlock(right);
2032                 free_extent_buffer(right);
2033         }
2034         if (left) {
2035                 if (path->nodes[level] != left)
2036                         btrfs_tree_unlock(left);
2037                 free_extent_buffer(left);
2038         }
2039         return ret;
2040 }
2041
2042 /* Node balancing for insertion.  Here we only split or push nodes around
2043  * when they are completely full.  This is also done top down, so we
2044  * have to be pessimistic.
2045  */
2046 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2047                                           struct btrfs_root *root,
2048                                           struct btrfs_path *path, int level)
2049 {
2050         struct btrfs_fs_info *fs_info = root->fs_info;
2051         struct extent_buffer *right = NULL;
2052         struct extent_buffer *mid;
2053         struct extent_buffer *left = NULL;
2054         struct extent_buffer *parent = NULL;
2055         int ret = 0;
2056         int wret;
2057         int pslot;
2058         int orig_slot = path->slots[level];
2059
2060         if (level == 0)
2061                 return 1;
2062
2063         mid = path->nodes[level];
2064         WARN_ON(btrfs_header_generation(mid) != trans->transid);
2065
2066         if (level < BTRFS_MAX_LEVEL - 1) {
2067                 parent = path->nodes[level + 1];
2068                 pslot = path->slots[level + 1];
2069         }
2070
2071         if (!parent)
2072                 return 1;
2073
2074         left = read_node_slot(fs_info, parent, pslot - 1);
2075         if (IS_ERR(left))
2076                 left = NULL;
2077
2078         /* first, try to make some room in the middle buffer */
2079         if (left) {
2080                 u32 left_nr;
2081
2082                 btrfs_tree_lock(left);
2083                 btrfs_set_lock_blocking(left);
2084
2085                 left_nr = btrfs_header_nritems(left);
2086                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2087                         wret = 1;
2088                 } else {
2089                         ret = btrfs_cow_block(trans, root, left, parent,
2090                                               pslot - 1, &left);
2091                         if (ret)
2092                                 wret = 1;
2093                         else {
2094                                 wret = push_node_left(trans, fs_info,
2095                                                       left, mid, 0);
2096                         }
2097                 }
2098                 if (wret < 0)
2099                         ret = wret;
2100                 if (wret == 0) {
2101                         struct btrfs_disk_key disk_key;
2102                         orig_slot += left_nr;
2103                         btrfs_node_key(mid, &disk_key, 0);
2104                         ret = tree_mod_log_insert_key(parent, pslot,
2105                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
2106                         BUG_ON(ret < 0);
2107                         btrfs_set_node_key(parent, &disk_key, pslot);
2108                         btrfs_mark_buffer_dirty(parent);
2109                         if (btrfs_header_nritems(left) > orig_slot) {
2110                                 path->nodes[level] = left;
2111                                 path->slots[level + 1] -= 1;
2112                                 path->slots[level] = orig_slot;
2113                                 btrfs_tree_unlock(mid);
2114                                 free_extent_buffer(mid);
2115                         } else {
2116                                 orig_slot -=
2117                                         btrfs_header_nritems(left);
2118                                 path->slots[level] = orig_slot;
2119                                 btrfs_tree_unlock(left);
2120                                 free_extent_buffer(left);
2121                         }
2122                         return 0;
2123                 }
2124                 btrfs_tree_unlock(left);
2125                 free_extent_buffer(left);
2126         }
2127         right = read_node_slot(fs_info, parent, pslot + 1);
2128         if (IS_ERR(right))
2129                 right = NULL;
2130
2131         /*
2132          * then try to empty the right most buffer into the middle
2133          */
2134         if (right) {
2135                 u32 right_nr;
2136
2137                 btrfs_tree_lock(right);
2138                 btrfs_set_lock_blocking(right);
2139
2140                 right_nr = btrfs_header_nritems(right);
2141                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2142                         wret = 1;
2143                 } else {
2144                         ret = btrfs_cow_block(trans, root, right,
2145                                               parent, pslot + 1,
2146                                               &right);
2147                         if (ret)
2148                                 wret = 1;
2149                         else {
2150                                 wret = balance_node_right(trans, fs_info,
2151                                                           right, mid);
2152                         }
2153                 }
2154                 if (wret < 0)
2155                         ret = wret;
2156                 if (wret == 0) {
2157                         struct btrfs_disk_key disk_key;
2158
2159                         btrfs_node_key(right, &disk_key, 0);
2160                         ret = tree_mod_log_insert_key(parent, pslot + 1,
2161                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
2162                         BUG_ON(ret < 0);
2163                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
2164                         btrfs_mark_buffer_dirty(parent);
2165
2166                         if (btrfs_header_nritems(mid) <= orig_slot) {
2167                                 path->nodes[level] = right;
2168                                 path->slots[level + 1] += 1;
2169                                 path->slots[level] = orig_slot -
2170                                         btrfs_header_nritems(mid);
2171                                 btrfs_tree_unlock(mid);
2172                                 free_extent_buffer(mid);
2173                         } else {
2174                                 btrfs_tree_unlock(right);
2175                                 free_extent_buffer(right);
2176                         }
2177                         return 0;
2178                 }
2179                 btrfs_tree_unlock(right);
2180                 free_extent_buffer(right);
2181         }
2182         return 1;
2183 }
2184
2185 /*
2186  * readahead one full node of leaves, finding things that are close
2187  * to the block in 'slot', and triggering ra on them.
2188  */
2189 static void reada_for_search(struct btrfs_fs_info *fs_info,
2190                              struct btrfs_path *path,
2191                              int level, int slot, u64 objectid)
2192 {
2193         struct extent_buffer *node;
2194         struct btrfs_disk_key disk_key;
2195         u32 nritems;
2196         u64 search;
2197         u64 target;
2198         u64 nread = 0;
2199         struct extent_buffer *eb;
2200         u32 nr;
2201         u32 blocksize;
2202         u32 nscan = 0;
2203
2204         if (level != 1)
2205                 return;
2206
2207         if (!path->nodes[level])
2208                 return;
2209
2210         node = path->nodes[level];
2211
2212         search = btrfs_node_blockptr(node, slot);
2213         blocksize = fs_info->nodesize;
2214         eb = find_extent_buffer(fs_info, search);
2215         if (eb) {
2216                 free_extent_buffer(eb);
2217                 return;
2218         }
2219
2220         target = search;
2221
2222         nritems = btrfs_header_nritems(node);
2223         nr = slot;
2224
2225         while (1) {
2226                 if (path->reada == READA_BACK) {
2227                         if (nr == 0)
2228                                 break;
2229                         nr--;
2230                 } else if (path->reada == READA_FORWARD) {
2231                         nr++;
2232                         if (nr >= nritems)
2233                                 break;
2234                 }
2235                 if (path->reada == READA_BACK && objectid) {
2236                         btrfs_node_key(node, &disk_key, nr);
2237                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
2238                                 break;
2239                 }
2240                 search = btrfs_node_blockptr(node, nr);
2241                 if ((search <= target && target - search <= 65536) ||
2242                     (search > target && search - target <= 65536)) {
2243                         readahead_tree_block(fs_info, search);
2244                         nread += blocksize;
2245                 }
2246                 nscan++;
2247                 if ((nread > 65536 || nscan > 32))
2248                         break;
2249         }
2250 }
2251
2252 static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2253                                        struct btrfs_path *path, int level)
2254 {
2255         int slot;
2256         int nritems;
2257         struct extent_buffer *parent;
2258         struct extent_buffer *eb;
2259         u64 gen;
2260         u64 block1 = 0;
2261         u64 block2 = 0;
2262
2263         parent = path->nodes[level + 1];
2264         if (!parent)
2265                 return;
2266
2267         nritems = btrfs_header_nritems(parent);
2268         slot = path->slots[level + 1];
2269
2270         if (slot > 0) {
2271                 block1 = btrfs_node_blockptr(parent, slot - 1);
2272                 gen = btrfs_node_ptr_generation(parent, slot - 1);
2273                 eb = find_extent_buffer(fs_info, block1);
2274                 /*
2275                  * if we get -eagain from btrfs_buffer_uptodate, we
2276                  * don't want to return eagain here.  That will loop
2277                  * forever
2278                  */
2279                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2280                         block1 = 0;
2281                 free_extent_buffer(eb);
2282         }
2283         if (slot + 1 < nritems) {
2284                 block2 = btrfs_node_blockptr(parent, slot + 1);
2285                 gen = btrfs_node_ptr_generation(parent, slot + 1);
2286                 eb = find_extent_buffer(fs_info, block2);
2287                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2288                         block2 = 0;
2289                 free_extent_buffer(eb);
2290         }
2291
2292         if (block1)
2293                 readahead_tree_block(fs_info, block1);
2294         if (block2)
2295                 readahead_tree_block(fs_info, block2);
2296 }
2297
2298
2299 /*
2300  * when we walk down the tree, it is usually safe to unlock the higher layers
2301  * in the tree.  The exceptions are when our path goes through slot 0, because
2302  * operations on the tree might require changing key pointers higher up in the
2303  * tree.
2304  *
2305  * callers might also have set path->keep_locks, which tells this code to keep
2306  * the lock if the path points to the last slot in the block.  This is part of
2307  * walking through the tree, and selecting the next slot in the higher block.
2308  *
2309  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2310  * if lowest_unlock is 1, level 0 won't be unlocked
2311  */
2312 static noinline void unlock_up(struct btrfs_path *path, int level,
2313                                int lowest_unlock, int min_write_lock_level,
2314                                int *write_lock_level)
2315 {
2316         int i;
2317         int skip_level = level;
2318         int no_skips = 0;
2319         struct extent_buffer *t;
2320
2321         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2322                 if (!path->nodes[i])
2323                         break;
2324                 if (!path->locks[i])
2325                         break;
2326                 if (!no_skips && path->slots[i] == 0) {
2327                         skip_level = i + 1;
2328                         continue;
2329                 }
2330                 if (!no_skips && path->keep_locks) {
2331                         u32 nritems;
2332                         t = path->nodes[i];
2333                         nritems = btrfs_header_nritems(t);
2334                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
2335                                 skip_level = i + 1;
2336                                 continue;
2337                         }
2338                 }
2339                 if (skip_level < i && i >= lowest_unlock)
2340                         no_skips = 1;
2341
2342                 t = path->nodes[i];
2343                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2344                         btrfs_tree_unlock_rw(t, path->locks[i]);
2345                         path->locks[i] = 0;
2346                         if (write_lock_level &&
2347                             i > min_write_lock_level &&
2348                             i <= *write_lock_level) {
2349                                 *write_lock_level = i - 1;
2350                         }
2351                 }
2352         }
2353 }
2354
2355 /*
2356  * This releases any locks held in the path starting at level and
2357  * going all the way up to the root.
2358  *
2359  * btrfs_search_slot will keep the lock held on higher nodes in a few
2360  * corner cases, such as COW of the block at slot zero in the node.  This
2361  * ignores those rules, and it should only be called when there are no
2362  * more updates to be done higher up in the tree.
2363  */
2364 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2365 {
2366         int i;
2367
2368         if (path->keep_locks)
2369                 return;
2370
2371         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2372                 if (!path->nodes[i])
2373                         continue;
2374                 if (!path->locks[i])
2375                         continue;
2376                 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2377                 path->locks[i] = 0;
2378         }
2379 }
2380
2381 /*
2382  * helper function for btrfs_search_slot.  The goal is to find a block
2383  * in cache without setting the path to blocking.  If we find the block
2384  * we return zero and the path is unchanged.
2385  *
2386  * If we can't find the block, we set the path blocking and do some
2387  * reada.  -EAGAIN is returned and the search must be repeated.
2388  */
2389 static int
2390 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2391                       struct extent_buffer **eb_ret, int level, int slot,
2392                       const struct btrfs_key *key)
2393 {
2394         struct btrfs_fs_info *fs_info = root->fs_info;
2395         u64 blocknr;
2396         u64 gen;
2397         struct extent_buffer *b = *eb_ret;
2398         struct extent_buffer *tmp;
2399         int ret;
2400
2401         blocknr = btrfs_node_blockptr(b, slot);
2402         gen = btrfs_node_ptr_generation(b, slot);
2403
2404         tmp = find_extent_buffer(fs_info, blocknr);
2405         if (tmp) {
2406                 /* first we do an atomic uptodate check */
2407                 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2408                         *eb_ret = tmp;
2409                         return 0;
2410                 }
2411
2412                 /* the pages were up to date, but we failed
2413                  * the generation number check.  Do a full
2414                  * read for the generation number that is correct.
2415                  * We must do this without dropping locks so
2416                  * we can trust our generation number
2417                  */
2418                 btrfs_set_path_blocking(p);
2419
2420                 /* now we're allowed to do a blocking uptodate check */
2421                 ret = btrfs_read_buffer(tmp, gen);
2422                 if (!ret) {
2423                         *eb_ret = tmp;
2424                         return 0;
2425                 }
2426                 free_extent_buffer(tmp);
2427                 btrfs_release_path(p);
2428                 return -EIO;
2429         }
2430
2431         /*
2432          * reduce lock contention at high levels
2433          * of the btree by dropping locks before
2434          * we read.  Don't release the lock on the current
2435          * level because we need to walk this node to figure
2436          * out which blocks to read.
2437          */
2438         btrfs_unlock_up_safe(p, level + 1);
2439         btrfs_set_path_blocking(p);
2440
2441         free_extent_buffer(tmp);
2442         if (p->reada != READA_NONE)
2443                 reada_for_search(fs_info, p, level, slot, key->objectid);
2444
2445         btrfs_release_path(p);
2446
2447         ret = -EAGAIN;
2448         tmp = read_tree_block(fs_info, blocknr, 0);
2449         if (!IS_ERR(tmp)) {
2450                 /*
2451                  * If the read above didn't mark this buffer up to date,
2452                  * it will never end up being up to date.  Set ret to EIO now
2453                  * and give up so that our caller doesn't loop forever
2454                  * on our EAGAINs.
2455                  */
2456                 if (!btrfs_buffer_uptodate(tmp, 0, 0))
2457                         ret = -EIO;
2458                 free_extent_buffer(tmp);
2459         } else {
2460                 ret = PTR_ERR(tmp);
2461         }
2462         return ret;
2463 }
2464
2465 /*
2466  * helper function for btrfs_search_slot.  This does all of the checks
2467  * for node-level blocks and does any balancing required based on
2468  * the ins_len.
2469  *
2470  * If no extra work was required, zero is returned.  If we had to
2471  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2472  * start over
2473  */
2474 static int
2475 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2476                        struct btrfs_root *root, struct btrfs_path *p,
2477                        struct extent_buffer *b, int level, int ins_len,
2478                        int *write_lock_level)
2479 {
2480         struct btrfs_fs_info *fs_info = root->fs_info;
2481         int ret;
2482
2483         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2484             BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2485                 int sret;
2486
2487                 if (*write_lock_level < level + 1) {
2488                         *write_lock_level = level + 1;
2489                         btrfs_release_path(p);
2490                         goto again;
2491                 }
2492
2493                 btrfs_set_path_blocking(p);
2494                 reada_for_balance(fs_info, p, level);
2495                 sret = split_node(trans, root, p, level);
2496                 btrfs_clear_path_blocking(p, NULL, 0);
2497
2498                 BUG_ON(sret > 0);
2499                 if (sret) {
2500                         ret = sret;
2501                         goto done;
2502                 }
2503                 b = p->nodes[level];
2504         } else if (ins_len < 0 && btrfs_header_nritems(b) <
2505                    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2506                 int sret;
2507
2508                 if (*write_lock_level < level + 1) {
2509                         *write_lock_level = level + 1;
2510                         btrfs_release_path(p);
2511                         goto again;
2512                 }
2513
2514                 btrfs_set_path_blocking(p);
2515                 reada_for_balance(fs_info, p, level);
2516                 sret = balance_level(trans, root, p, level);
2517                 btrfs_clear_path_blocking(p, NULL, 0);
2518
2519                 if (sret) {
2520                         ret = sret;
2521                         goto done;
2522                 }
2523                 b = p->nodes[level];
2524                 if (!b) {
2525                         btrfs_release_path(p);
2526                         goto again;
2527                 }
2528                 BUG_ON(btrfs_header_nritems(b) == 1);
2529         }
2530         return 0;
2531
2532 again:
2533         ret = -EAGAIN;
2534 done:
2535         return ret;
2536 }
2537
2538 static void key_search_validate(struct extent_buffer *b,
2539                                 const struct btrfs_key *key,
2540                                 int level)
2541 {
2542 #ifdef CONFIG_BTRFS_ASSERT
2543         struct btrfs_disk_key disk_key;
2544
2545         btrfs_cpu_key_to_disk(&disk_key, key);
2546
2547         if (level == 0)
2548                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2549                     offsetof(struct btrfs_leaf, items[0].key),
2550                     sizeof(disk_key)));
2551         else
2552                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2553                     offsetof(struct btrfs_node, ptrs[0].key),
2554                     sizeof(disk_key)));
2555 #endif
2556 }
2557
2558 static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2559                       int level, int *prev_cmp, int *slot)
2560 {
2561         if (*prev_cmp != 0) {
2562                 *prev_cmp = btrfs_bin_search(b, key, level, slot);
2563                 return *prev_cmp;
2564         }
2565
2566         key_search_validate(b, key, level);
2567         *slot = 0;
2568
2569         return 0;
2570 }
2571
2572 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2573                 u64 iobjectid, u64 ioff, u8 key_type,
2574                 struct btrfs_key *found_key)
2575 {
2576         int ret;
2577         struct btrfs_key key;
2578         struct extent_buffer *eb;
2579
2580         ASSERT(path);
2581         ASSERT(found_key);
2582
2583         key.type = key_type;
2584         key.objectid = iobjectid;
2585         key.offset = ioff;
2586
2587         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2588         if (ret < 0)
2589                 return ret;
2590
2591         eb = path->nodes[0];
2592         if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2593                 ret = btrfs_next_leaf(fs_root, path);
2594                 if (ret)
2595                         return ret;
2596                 eb = path->nodes[0];
2597         }
2598
2599         btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2600         if (found_key->type != key.type ||
2601                         found_key->objectid != key.objectid)
2602                 return 1;
2603
2604         return 0;
2605 }
2606
2607 /*
2608  * btrfs_search_slot - look for a key in a tree and perform necessary
2609  * modifications to preserve tree invariants.
2610  *
2611  * @trans:      Handle of transaction, used when modifying the tree
2612  * @p:          Holds all btree nodes along the search path
2613  * @root:       The root node of the tree
2614  * @key:        The key we are looking for
2615  * @ins_len:    Indicates purpose of search, for inserts it is 1, for
2616  *              deletions it's -1. 0 for plain searches
2617  * @cow:        boolean should CoW operations be performed. Must always be 1
2618  *              when modifying the tree.
2619  *
2620  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2621  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2622  *
2623  * If @key is found, 0 is returned and you can find the item in the leaf level
2624  * of the path (level 0)
2625  *
2626  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2627  * points to the slot where it should be inserted
2628  *
2629  * If an error is encountered while searching the tree a negative error number
2630  * is returned
2631  */
2632 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2633                       const struct btrfs_key *key, struct btrfs_path *p,
2634                       int ins_len, int cow)
2635 {
2636         struct btrfs_fs_info *fs_info = root->fs_info;
2637         struct extent_buffer *b;
2638         int slot;
2639         int ret;
2640         int err;
2641         int level;
2642         int lowest_unlock = 1;
2643         int root_lock;
2644         /* everything at write_lock_level or lower must be write locked */
2645         int write_lock_level = 0;
2646         u8 lowest_level = 0;
2647         int min_write_lock_level;
2648         int prev_cmp;
2649
2650         lowest_level = p->lowest_level;
2651         WARN_ON(lowest_level && ins_len > 0);
2652         WARN_ON(p->nodes[0] != NULL);
2653         BUG_ON(!cow && ins_len);
2654
2655         if (ins_len < 0) {
2656                 lowest_unlock = 2;
2657
2658                 /* when we are removing items, we might have to go up to level
2659                  * two as we update tree pointers  Make sure we keep write
2660                  * for those levels as well
2661                  */
2662                 write_lock_level = 2;
2663         } else if (ins_len > 0) {
2664                 /*
2665                  * for inserting items, make sure we have a write lock on
2666                  * level 1 so we can update keys
2667                  */
2668                 write_lock_level = 1;
2669         }
2670
2671         if (!cow)
2672                 write_lock_level = -1;
2673
2674         if (cow && (p->keep_locks || p->lowest_level))
2675                 write_lock_level = BTRFS_MAX_LEVEL;
2676
2677         min_write_lock_level = write_lock_level;
2678
2679 again:
2680         prev_cmp = -1;
2681         /*
2682          * we try very hard to do read locks on the root
2683          */
2684         root_lock = BTRFS_READ_LOCK;
2685         level = 0;
2686         if (p->search_commit_root) {
2687                 /*
2688                  * the commit roots are read only
2689                  * so we always do read locks
2690                  */
2691                 if (p->need_commit_sem)
2692                         down_read(&fs_info->commit_root_sem);
2693                 b = root->commit_root;
2694                 extent_buffer_get(b);
2695                 level = btrfs_header_level(b);
2696                 if (p->need_commit_sem)
2697                         up_read(&fs_info->commit_root_sem);
2698                 if (!p->skip_locking)
2699                         btrfs_tree_read_lock(b);
2700         } else {
2701                 if (p->skip_locking) {
2702                         b = btrfs_root_node(root);
2703                         level = btrfs_header_level(b);
2704                 } else {
2705                         /* we don't know the level of the root node
2706                          * until we actually have it read locked
2707                          */
2708                         b = btrfs_read_lock_root_node(root);
2709                         level = btrfs_header_level(b);
2710                         if (level <= write_lock_level) {
2711                                 /* whoops, must trade for write lock */
2712                                 btrfs_tree_read_unlock(b);
2713                                 free_extent_buffer(b);
2714                                 b = btrfs_lock_root_node(root);
2715                                 root_lock = BTRFS_WRITE_LOCK;
2716
2717                                 /* the level might have changed, check again */
2718                                 level = btrfs_header_level(b);
2719                         }
2720                 }
2721         }
2722         p->nodes[level] = b;
2723         if (!p->skip_locking)
2724                 p->locks[level] = root_lock;
2725
2726         while (b) {
2727                 level = btrfs_header_level(b);
2728
2729                 /*
2730                  * setup the path here so we can release it under lock
2731                  * contention with the cow code
2732                  */
2733                 if (cow) {
2734                         bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2735
2736                         /*
2737                          * if we don't really need to cow this block
2738                          * then we don't want to set the path blocking,
2739                          * so we test it here
2740                          */
2741                         if (!should_cow_block(trans, root, b)) {
2742                                 trans->dirty = true;
2743                                 goto cow_done;
2744                         }
2745
2746                         /*
2747                          * must have write locks on this node and the
2748                          * parent
2749                          */
2750                         if (level > write_lock_level ||
2751                             (level + 1 > write_lock_level &&
2752                             level + 1 < BTRFS_MAX_LEVEL &&
2753                             p->nodes[level + 1])) {
2754                                 write_lock_level = level + 1;
2755                                 btrfs_release_path(p);
2756                                 goto again;
2757                         }
2758
2759                         btrfs_set_path_blocking(p);
2760                         if (last_level)
2761                                 err = btrfs_cow_block(trans, root, b, NULL, 0,
2762                                                       &b);
2763                         else
2764                                 err = btrfs_cow_block(trans, root, b,
2765                                                       p->nodes[level + 1],
2766                                                       p->slots[level + 1], &b);
2767                         if (err) {
2768                                 ret = err;
2769                                 goto done;
2770                         }
2771                 }
2772 cow_done:
2773                 p->nodes[level] = b;
2774                 btrfs_clear_path_blocking(p, NULL, 0);
2775
2776                 /*
2777                  * we have a lock on b and as long as we aren't changing
2778                  * the tree, there is no way to for the items in b to change.
2779                  * It is safe to drop the lock on our parent before we
2780                  * go through the expensive btree search on b.
2781                  *
2782                  * If we're inserting or deleting (ins_len != 0), then we might
2783                  * be changing slot zero, which may require changing the parent.
2784                  * So, we can't drop the lock until after we know which slot
2785                  * we're operating on.
2786                  */
2787                 if (!ins_len && !p->keep_locks) {
2788                         int u = level + 1;
2789
2790                         if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2791                                 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2792                                 p->locks[u] = 0;
2793                         }
2794                 }
2795
2796                 ret = key_search(b, key, level, &prev_cmp, &slot);
2797                 if (ret < 0)
2798                         goto done;
2799
2800                 if (level != 0) {
2801                         int dec = 0;
2802                         if (ret && slot > 0) {
2803                                 dec = 1;
2804                                 slot -= 1;
2805                         }
2806                         p->slots[level] = slot;
2807                         err = setup_nodes_for_search(trans, root, p, b, level,
2808                                              ins_len, &write_lock_level);
2809                         if (err == -EAGAIN)
2810                                 goto again;
2811                         if (err) {
2812                                 ret = err;
2813                                 goto done;
2814                         }
2815                         b = p->nodes[level];
2816                         slot = p->slots[level];
2817
2818                         /*
2819                          * slot 0 is special, if we change the key
2820                          * we have to update the parent pointer
2821                          * which means we must have a write lock
2822                          * on the parent
2823                          */
2824                         if (slot == 0 && ins_len &&
2825                             write_lock_level < level + 1) {
2826                                 write_lock_level = level + 1;
2827                                 btrfs_release_path(p);
2828                                 goto again;
2829                         }
2830
2831                         unlock_up(p, level, lowest_unlock,
2832                                   min_write_lock_level, &write_lock_level);
2833
2834                         if (level == lowest_level) {
2835                                 if (dec)
2836                                         p->slots[level]++;
2837                                 goto done;
2838                         }
2839
2840                         err = read_block_for_search(root, p, &b, level,
2841                                                     slot, key);
2842                         if (err == -EAGAIN)
2843                                 goto again;
2844                         if (err) {
2845                                 ret = err;
2846                                 goto done;
2847                         }
2848
2849                         if (!p->skip_locking) {
2850                                 level = btrfs_header_level(b);
2851                                 if (level <= write_lock_level) {
2852                                         err = btrfs_try_tree_write_lock(b);
2853                                         if (!err) {
2854                                                 btrfs_set_path_blocking(p);
2855                                                 btrfs_tree_lock(b);
2856                                                 btrfs_clear_path_blocking(p, b,
2857                                                                   BTRFS_WRITE_LOCK);
2858                                         }
2859                                         p->locks[level] = BTRFS_WRITE_LOCK;
2860                                 } else {
2861                                         err = btrfs_tree_read_lock_atomic(b);
2862                                         if (!err) {
2863                                                 btrfs_set_path_blocking(p);
2864                                                 btrfs_tree_read_lock(b);
2865                                                 btrfs_clear_path_blocking(p, b,
2866                                                                   BTRFS_READ_LOCK);
2867                                         }
2868                                         p->locks[level] = BTRFS_READ_LOCK;
2869                                 }
2870                                 p->nodes[level] = b;
2871                         }
2872                 } else {
2873                         p->slots[level] = slot;
2874                         if (ins_len > 0 &&
2875                             btrfs_leaf_free_space(fs_info, b) < ins_len) {
2876                                 if (write_lock_level < 1) {
2877                                         write_lock_level = 1;
2878                                         btrfs_release_path(p);
2879                                         goto again;
2880                                 }
2881
2882                                 btrfs_set_path_blocking(p);
2883                                 err = split_leaf(trans, root, key,
2884                                                  p, ins_len, ret == 0);
2885                                 btrfs_clear_path_blocking(p, NULL, 0);
2886
2887                                 BUG_ON(err > 0);
2888                                 if (err) {
2889                                         ret = err;
2890                                         goto done;
2891                                 }
2892                         }
2893                         if (!p->search_for_split)
2894                                 unlock_up(p, level, lowest_unlock,
2895                                           min_write_lock_level, &write_lock_level);
2896                         goto done;
2897                 }
2898         }
2899         ret = 1;
2900 done:
2901         /*
2902          * we don't really know what they plan on doing with the path
2903          * from here on, so for now just mark it as blocking
2904          */
2905         if (!p->leave_spinning)
2906                 btrfs_set_path_blocking(p);
2907         if (ret < 0 && !p->skip_release_on_error)
2908                 btrfs_release_path(p);
2909         return ret;
2910 }
2911
2912 /*
2913  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2914  * current state of the tree together with the operations recorded in the tree
2915  * modification log to search for the key in a previous version of this tree, as
2916  * denoted by the time_seq parameter.
2917  *
2918  * Naturally, there is no support for insert, delete or cow operations.
2919  *
2920  * The resulting path and return value will be set up as if we called
2921  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2922  */
2923 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2924                           struct btrfs_path *p, u64 time_seq)
2925 {
2926         struct btrfs_fs_info *fs_info = root->fs_info;
2927         struct extent_buffer *b;
2928         int slot;
2929         int ret;
2930         int err;
2931         int level;
2932         int lowest_unlock = 1;
2933         u8 lowest_level = 0;
2934         int prev_cmp = -1;
2935
2936         lowest_level = p->lowest_level;
2937         WARN_ON(p->nodes[0] != NULL);
2938
2939         if (p->search_commit_root) {
2940                 BUG_ON(time_seq);
2941                 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2942         }
2943
2944 again:
2945         b = get_old_root(root, time_seq);
2946         level = btrfs_header_level(b);
2947         p->locks[level] = BTRFS_READ_LOCK;
2948
2949         while (b) {
2950                 level = btrfs_header_level(b);
2951                 p->nodes[level] = b;
2952                 btrfs_clear_path_blocking(p, NULL, 0);
2953
2954                 /*
2955                  * we have a lock on b and as long as we aren't changing
2956                  * the tree, there is no way to for the items in b to change.
2957                  * It is safe to drop the lock on our parent before we
2958                  * go through the expensive btree search on b.
2959                  */
2960                 btrfs_unlock_up_safe(p, level + 1);
2961
2962                 /*
2963                  * Since we can unwind ebs we want to do a real search every
2964                  * time.
2965                  */
2966                 prev_cmp = -1;
2967                 ret = key_search(b, key, level, &prev_cmp, &slot);
2968
2969                 if (level != 0) {
2970                         int dec = 0;
2971                         if (ret && slot > 0) {
2972                                 dec = 1;
2973                                 slot -= 1;
2974                         }
2975                         p->slots[level] = slot;
2976                         unlock_up(p, level, lowest_unlock, 0, NULL);
2977
2978                         if (level == lowest_level) {
2979                                 if (dec)
2980                                         p->slots[level]++;
2981                                 goto done;
2982                         }
2983
2984                         err = read_block_for_search(root, p, &b, level,
2985                                                     slot, key);
2986                         if (err == -EAGAIN)
2987                                 goto again;
2988                         if (err) {
2989                                 ret = err;
2990                                 goto done;
2991                         }
2992
2993                         level = btrfs_header_level(b);
2994                         err = btrfs_tree_read_lock_atomic(b);
2995                         if (!err) {
2996                                 btrfs_set_path_blocking(p);
2997                                 btrfs_tree_read_lock(b);
2998                                 btrfs_clear_path_blocking(p, b,
2999                                                           BTRFS_READ_LOCK);
3000                         }
3001                         b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3002                         if (!b) {
3003                                 ret = -ENOMEM;
3004                                 goto done;
3005                         }
3006                         p->locks[level] = BTRFS_READ_LOCK;
3007                         p->nodes[level] = b;
3008                 } else {
3009                         p->slots[level] = slot;
3010                         unlock_up(p, level, lowest_unlock, 0, NULL);
3011                         goto done;
3012                 }
3013         }
3014         ret = 1;
3015 done:
3016         if (!p->leave_spinning)
3017                 btrfs_set_path_blocking(p);
3018         if (ret < 0)
3019                 btrfs_release_path(p);
3020
3021         return ret;
3022 }
3023
3024 /*
3025  * helper to use instead of search slot if no exact match is needed but
3026  * instead the next or previous item should be returned.
3027  * When find_higher is true, the next higher item is returned, the next lower
3028  * otherwise.
3029  * When return_any and find_higher are both true, and no higher item is found,
3030  * return the next lower instead.
3031  * When return_any is true and find_higher is false, and no lower item is found,
3032  * return the next higher instead.
3033  * It returns 0 if any item is found, 1 if none is found (tree empty), and
3034  * < 0 on error
3035  */
3036 int btrfs_search_slot_for_read(struct btrfs_root *root,
3037                                const struct btrfs_key *key,
3038                                struct btrfs_path *p, int find_higher,
3039                                int return_any)
3040 {
3041         int ret;
3042         struct extent_buffer *leaf;
3043
3044 again:
3045         ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3046         if (ret <= 0)
3047                 return ret;
3048         /*
3049          * a return value of 1 means the path is at the position where the
3050          * item should be inserted. Normally this is the next bigger item,
3051          * but in case the previous item is the last in a leaf, path points
3052          * to the first free slot in the previous leaf, i.e. at an invalid
3053          * item.
3054          */
3055         leaf = p->nodes[0];
3056
3057         if (find_higher) {
3058                 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3059                         ret = btrfs_next_leaf(root, p);
3060                         if (ret <= 0)
3061                                 return ret;
3062                         if (!return_any)
3063                                 return 1;
3064                         /*
3065                          * no higher item found, return the next
3066                          * lower instead
3067                          */
3068                         return_any = 0;
3069                         find_higher = 0;
3070                         btrfs_release_path(p);
3071                         goto again;
3072                 }
3073         } else {
3074                 if (p->slots[0] == 0) {
3075                         ret = btrfs_prev_leaf(root, p);
3076                         if (ret < 0)
3077                                 return ret;
3078                         if (!ret) {
3079                                 leaf = p->nodes[0];
3080                                 if (p->slots[0] == btrfs_header_nritems(leaf))
3081                                         p->slots[0]--;
3082                                 return 0;
3083                         }
3084                         if (!return_any)
3085                                 return 1;
3086                         /*
3087                          * no lower item found, return the next
3088                          * higher instead
3089                          */
3090                         return_any = 0;
3091                         find_higher = 1;
3092                         btrfs_release_path(p);
3093                         goto again;
3094                 } else {
3095                         --p->slots[0];
3096                 }
3097         }
3098         return 0;
3099 }
3100
3101 /*
3102  * adjust the pointers going up the tree, starting at level
3103  * making sure the right key of each node is points to 'key'.
3104  * This is used after shifting pointers to the left, so it stops
3105  * fixing up pointers when a given leaf/node is not in slot 0 of the
3106  * higher levels
3107  *
3108  */
3109 static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3110                            struct btrfs_path *path,
3111                            struct btrfs_disk_key *key, int level)
3112 {
3113         int i;
3114         struct extent_buffer *t;
3115         int ret;
3116
3117         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3118                 int tslot = path->slots[i];
3119
3120                 if (!path->nodes[i])
3121                         break;
3122                 t = path->nodes[i];
3123                 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3124                                 GFP_ATOMIC);
3125                 BUG_ON(ret < 0);
3126                 btrfs_set_node_key(t, key, tslot);
3127                 btrfs_mark_buffer_dirty(path->nodes[i]);
3128                 if (tslot != 0)
3129                         break;
3130         }
3131 }