btrfs: kill tree_mod_log_set_root_pointer 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 /*
887  * check if the tree block can be shared by multiple trees
888  */
889 int btrfs_block_can_be_shared(struct btrfs_root *root,
890                               struct extent_buffer *buf)
891 {
892         /*
893          * Tree blocks not in reference counted trees and tree roots
894          * are never shared. If a block was allocated after the last
895          * snapshot and the block was not allocated by tree relocation,
896          * we know the block is not shared.
897          */
898         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
899             buf != root->node && buf != root->commit_root &&
900             (btrfs_header_generation(buf) <=
901              btrfs_root_last_snapshot(&root->root_item) ||
902              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
903                 return 1;
904 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
905         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
906             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
907                 return 1;
908 #endif
909         return 0;
910 }
911
912 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
913                                        struct btrfs_root *root,
914                                        struct extent_buffer *buf,
915                                        struct extent_buffer *cow,
916                                        int *last_ref)
917 {
918         struct btrfs_fs_info *fs_info = root->fs_info;
919         u64 refs;
920         u64 owner;
921         u64 flags;
922         u64 new_flags = 0;
923         int ret;
924
925         /*
926          * Backrefs update rules:
927          *
928          * Always use full backrefs for extent pointers in tree block
929          * allocated by tree relocation.
930          *
931          * If a shared tree block is no longer referenced by its owner
932          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
933          * use full backrefs for extent pointers in tree block.
934          *
935          * If a tree block is been relocating
936          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
937          * use full backrefs for extent pointers in tree block.
938          * The reason for this is some operations (such as drop tree)
939          * are only allowed for blocks use full backrefs.
940          */
941
942         if (btrfs_block_can_be_shared(root, buf)) {
943                 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
944                                                btrfs_header_level(buf), 1,
945                                                &refs, &flags);
946                 if (ret)
947                         return ret;
948                 if (refs == 0) {
949                         ret = -EROFS;
950                         btrfs_handle_fs_error(fs_info, ret, NULL);
951                         return ret;
952                 }
953         } else {
954                 refs = 1;
955                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
956                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
957                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
958                 else
959                         flags = 0;
960         }
961
962         owner = btrfs_header_owner(buf);
963         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
964                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
965
966         if (refs > 1) {
967                 if ((owner == root->root_key.objectid ||
968                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
969                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
970                         ret = btrfs_inc_ref(trans, root, buf, 1);
971                         if (ret)
972                                 return ret;
973
974                         if (root->root_key.objectid ==
975                             BTRFS_TREE_RELOC_OBJECTID) {
976                                 ret = btrfs_dec_ref(trans, root, buf, 0);
977                                 if (ret)
978                                         return ret;
979                                 ret = btrfs_inc_ref(trans, root, cow, 1);
980                                 if (ret)
981                                         return ret;
982                         }
983                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
984                 } else {
985
986                         if (root->root_key.objectid ==
987                             BTRFS_TREE_RELOC_OBJECTID)
988                                 ret = btrfs_inc_ref(trans, root, cow, 1);
989                         else
990                                 ret = btrfs_inc_ref(trans, root, cow, 0);
991                         if (ret)
992                                 return ret;
993                 }
994                 if (new_flags != 0) {
995                         int level = btrfs_header_level(buf);
996
997                         ret = btrfs_set_disk_extent_flags(trans, fs_info,
998                                                           buf->start,
999                                                           buf->len,
1000                                                           new_flags, level, 0);
1001                         if (ret)
1002                                 return ret;
1003                 }
1004         } else {
1005                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
1006                         if (root->root_key.objectid ==
1007                             BTRFS_TREE_RELOC_OBJECTID)
1008                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1009                         else
1010                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1011                         if (ret)
1012                                 return ret;
1013                         ret = btrfs_dec_ref(trans, root, buf, 1);
1014                         if (ret)
1015                                 return ret;
1016                 }
1017                 clean_tree_block(fs_info, buf);
1018                 *last_ref = 1;
1019         }
1020         return 0;
1021 }
1022
1023 /*
1024  * does the dirty work in cow of a single block.  The parent block (if
1025  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1026  * dirty and returned locked.  If you modify the block it needs to be marked
1027  * dirty again.
1028  *
1029  * search_start -- an allocation hint for the new block
1030  *
1031  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1032  * bytes the allocator should try to find free next to the block it returns.
1033  * This is just a hint and may be ignored by the allocator.
1034  */
1035 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1036                              struct btrfs_root *root,
1037                              struct extent_buffer *buf,
1038                              struct extent_buffer *parent, int parent_slot,
1039                              struct extent_buffer **cow_ret,
1040                              u64 search_start, u64 empty_size)
1041 {
1042         struct btrfs_fs_info *fs_info = root->fs_info;
1043         struct btrfs_disk_key disk_key;
1044         struct extent_buffer *cow;
1045         int level, ret;
1046         int last_ref = 0;
1047         int unlock_orig = 0;
1048         u64 parent_start = 0;
1049
1050         if (*cow_ret == buf)
1051                 unlock_orig = 1;
1052
1053         btrfs_assert_tree_locked(buf);
1054
1055         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1056                 trans->transid != fs_info->running_transaction->transid);
1057         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1058                 trans->transid != root->last_trans);
1059
1060         level = btrfs_header_level(buf);
1061
1062         if (level == 0)
1063                 btrfs_item_key(buf, &disk_key, 0);
1064         else
1065                 btrfs_node_key(buf, &disk_key, 0);
1066
1067         if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1068                 parent_start = parent->start;
1069
1070         cow = btrfs_alloc_tree_block(trans, root, parent_start,
1071                         root->root_key.objectid, &disk_key, level,
1072                         search_start, empty_size);
1073         if (IS_ERR(cow))
1074                 return PTR_ERR(cow);
1075
1076         /* cow is set to blocking by btrfs_init_new_buffer */
1077
1078         copy_extent_buffer_full(cow, buf);
1079         btrfs_set_header_bytenr(cow, cow->start);
1080         btrfs_set_header_generation(cow, trans->transid);
1081         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1082         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1083                                      BTRFS_HEADER_FLAG_RELOC);
1084         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1085                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1086         else
1087                 btrfs_set_header_owner(cow, root->root_key.objectid);
1088
1089         write_extent_buffer_fsid(cow, fs_info->fsid);
1090
1091         ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1092         if (ret) {
1093                 btrfs_abort_transaction(trans, ret);
1094                 return ret;
1095         }
1096
1097         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1098                 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1099                 if (ret) {
1100                         btrfs_abort_transaction(trans, ret);
1101                         return ret;
1102                 }
1103         }
1104
1105         if (buf == root->node) {
1106                 WARN_ON(parent && parent != buf);
1107                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1108                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1109                         parent_start = buf->start;
1110
1111                 extent_buffer_get(cow);
1112                 ret = tree_mod_log_insert_root(root->node, cow, 1);
1113                 BUG_ON(ret < 0);
1114                 rcu_assign_pointer(root->node, cow);
1115
1116                 btrfs_free_tree_block(trans, root, buf, parent_start,
1117                                       last_ref);
1118                 free_extent_buffer(buf);
1119                 add_root_to_dirty_list(root);
1120         } else {
1121                 WARN_ON(trans->transid != btrfs_header_generation(parent));
1122                 tree_mod_log_insert_key(parent, parent_slot,
1123                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1124                 btrfs_set_node_blockptr(parent, parent_slot,
1125                                         cow->start);
1126                 btrfs_set_node_ptr_generation(parent, parent_slot,
1127                                               trans->transid);
1128                 btrfs_mark_buffer_dirty(parent);
1129                 if (last_ref) {
1130                         ret = tree_mod_log_free_eb(buf);
1131                         if (ret) {
1132                                 btrfs_abort_transaction(trans, ret);
1133                                 return ret;
1134                         }
1135                 }
1136                 btrfs_free_tree_block(trans, root, buf, parent_start,
1137                                       last_ref);
1138         }
1139         if (unlock_orig)
1140                 btrfs_tree_unlock(buf);
1141         free_extent_buffer_stale(buf);
1142         btrfs_mark_buffer_dirty(cow);
1143         *cow_ret = cow;
1144         return 0;
1145 }
1146
1147 /*
1148  * returns the logical address of the oldest predecessor of the given root.
1149  * entries older than time_seq are ignored.
1150  */
1151 static struct tree_mod_elem *__tree_mod_log_oldest_root(
1152                 struct extent_buffer *eb_root, u64 time_seq)
1153 {
1154         struct tree_mod_elem *tm;
1155         struct tree_mod_elem *found = NULL;
1156         u64 root_logical = eb_root->start;
1157         int looped = 0;
1158
1159         if (!time_seq)
1160                 return NULL;
1161
1162         /*
1163          * the very last operation that's logged for a root is the
1164          * replacement operation (if it is replaced at all). this has
1165          * the logical address of the *new* root, making it the very
1166          * first operation that's logged for this root.
1167          */
1168         while (1) {
1169                 tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
1170                                                 time_seq);
1171                 if (!looped && !tm)
1172                         return NULL;
1173                 /*
1174                  * if there are no tree operation for the oldest root, we simply
1175                  * return it. this should only happen if that (old) root is at
1176                  * level 0.
1177                  */
1178                 if (!tm)
1179                         break;
1180
1181                 /*
1182                  * if there's an operation that's not a root replacement, we
1183                  * found the oldest version of our root. normally, we'll find a
1184                  * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1185                  */
1186                 if (tm->op != MOD_LOG_ROOT_REPLACE)
1187                         break;
1188
1189                 found = tm;
1190                 root_logical = tm->old_root.logical;
1191                 looped = 1;
1192         }
1193
1194         /* if there's no old root to return, return what we found instead */
1195         if (!found)
1196                 found = tm;
1197
1198         return found;
1199 }
1200
1201 /*
1202  * tm is a pointer to the first operation to rewind within eb. then, all
1203  * previous operations will be rewound (until we reach something older than
1204  * time_seq).
1205  */
1206 static void
1207 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1208                       u64 time_seq, struct tree_mod_elem *first_tm)
1209 {
1210         u32 n;
1211         struct rb_node *next;
1212         struct tree_mod_elem *tm = first_tm;
1213         unsigned long o_dst;
1214         unsigned long o_src;
1215         unsigned long p_size = sizeof(struct btrfs_key_ptr);
1216
1217         n = btrfs_header_nritems(eb);
1218         read_lock(&fs_info->tree_mod_log_lock);
1219         while (tm && tm->seq >= time_seq) {
1220                 /*
1221                  * all the operations are recorded with the operator used for
1222                  * the modification. as we're going backwards, we do the
1223                  * opposite of each operation here.
1224                  */
1225                 switch (tm->op) {
1226                 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1227                         BUG_ON(tm->slot < n);
1228                         /* Fallthrough */
1229                 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1230                 case MOD_LOG_KEY_REMOVE:
1231                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1232                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1233                         btrfs_set_node_ptr_generation(eb, tm->slot,
1234                                                       tm->generation);
1235                         n++;
1236                         break;
1237                 case MOD_LOG_KEY_REPLACE:
1238                         BUG_ON(tm->slot >= n);
1239                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1240                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1241                         btrfs_set_node_ptr_generation(eb, tm->slot,
1242                                                       tm->generation);
1243                         break;
1244                 case MOD_LOG_KEY_ADD:
1245                         /* if a move operation is needed it's in the log */
1246                         n--;
1247                         break;
1248                 case MOD_LOG_MOVE_KEYS:
1249                         o_dst = btrfs_node_key_ptr_offset(tm->slot);
1250                         o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1251                         memmove_extent_buffer(eb, o_dst, o_src,
1252                                               tm->move.nr_items * p_size);
1253                         break;
1254                 case MOD_LOG_ROOT_REPLACE:
1255                         /*
1256                          * this operation is special. for roots, this must be
1257                          * handled explicitly before rewinding.
1258                          * for non-roots, this operation may exist if the node
1259                          * was a root: root A -> child B; then A gets empty and
1260                          * B is promoted to the new root. in the mod log, we'll
1261                          * have a root-replace operation for B, a tree block
1262                          * that is no root. we simply ignore that operation.
1263                          */
1264                         break;
1265                 }
1266                 next = rb_next(&tm->node);
1267                 if (!next)
1268                         break;
1269                 tm = rb_entry(next, struct tree_mod_elem, node);
1270                 if (tm->logical != first_tm->logical)
1271                         break;
1272         }
1273         read_unlock(&fs_info->tree_mod_log_lock);
1274         btrfs_set_header_nritems(eb, n);
1275 }
1276
1277 /*
1278  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1279  * is returned. If rewind operations happen, a fresh buffer is returned. The
1280  * returned buffer is always read-locked. If the returned buffer is not the
1281  * input buffer, the lock on the input buffer is released and the input buffer
1282  * is freed (its refcount is decremented).
1283  */
1284 static struct extent_buffer *
1285 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1286                     struct extent_buffer *eb, u64 time_seq)
1287 {
1288         struct extent_buffer *eb_rewin;
1289         struct tree_mod_elem *tm;
1290
1291         if (!time_seq)
1292                 return eb;
1293
1294         if (btrfs_header_level(eb) == 0)
1295                 return eb;
1296
1297         tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1298         if (!tm)
1299                 return eb;
1300
1301         btrfs_set_path_blocking(path);
1302         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1303
1304         if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1305                 BUG_ON(tm->slot != 0);
1306                 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1307                 if (!eb_rewin) {
1308                         btrfs_tree_read_unlock_blocking(eb);
1309                         free_extent_buffer(eb);
1310                         return NULL;
1311                 }
1312                 btrfs_set_header_bytenr(eb_rewin, eb->start);
1313                 btrfs_set_header_backref_rev(eb_rewin,
1314                                              btrfs_header_backref_rev(eb));
1315                 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1316                 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1317         } else {
1318                 eb_rewin = btrfs_clone_extent_buffer(eb);
1319                 if (!eb_rewin) {
1320                         btrfs_tree_read_unlock_blocking(eb);
1321                         free_extent_buffer(eb);
1322                         return NULL;
1323                 }
1324         }
1325
1326         btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1327         btrfs_tree_read_unlock_blocking(eb);
1328         free_extent_buffer(eb);
1329
1330         extent_buffer_get(eb_rewin);
1331         btrfs_tree_read_lock(eb_rewin);
1332         __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1333         WARN_ON(btrfs_header_nritems(eb_rewin) >
1334                 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1335
1336         return eb_rewin;
1337 }
1338
1339 /*
1340  * get_old_root() rewinds the state of @root's root node to the given @time_seq
1341  * value. If there are no changes, the current root->root_node is returned. If
1342  * anything changed in between, there's a fresh buffer allocated on which the
1343  * rewind operations are done. In any case, the returned buffer is read locked.
1344  * Returns NULL on error (with no locks held).
1345  */
1346 static inline struct extent_buffer *
1347 get_old_root(struct btrfs_root *root, u64 time_seq)
1348 {
1349         struct btrfs_fs_info *fs_info = root->fs_info;
1350         struct tree_mod_elem *tm;
1351         struct extent_buffer *eb = NULL;
1352         struct extent_buffer *eb_root;
1353         struct extent_buffer *old;
1354         struct tree_mod_root *old_root = NULL;
1355         u64 old_generation = 0;
1356         u64 logical;
1357
1358         eb_root = btrfs_read_lock_root_node(root);
1359         tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1360         if (!tm)
1361                 return eb_root;
1362
1363         if (tm->op == MOD_LOG_ROOT_REPLACE) {
1364                 old_root = &tm->old_root;
1365                 old_generation = tm->generation;
1366                 logical = old_root->logical;
1367         } else {
1368                 logical = eb_root->start;
1369         }
1370
1371         tm = tree_mod_log_search(fs_info, logical, time_seq);
1372         if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1373                 btrfs_tree_read_unlock(eb_root);
1374                 free_extent_buffer(eb_root);
1375                 old = read_tree_block(fs_info, logical, 0);
1376                 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1377                         if (!IS_ERR(old))
1378                                 free_extent_buffer(old);
1379                         btrfs_warn(fs_info,
1380                                    "failed to read tree block %llu from get_old_root",
1381                                    logical);
1382                 } else {
1383                         eb = btrfs_clone_extent_buffer(old);
1384                         free_extent_buffer(old);
1385                 }
1386         } else if (old_root) {
1387                 btrfs_tree_read_unlock(eb_root);
1388                 free_extent_buffer(eb_root);
1389                 eb = alloc_dummy_extent_buffer(fs_info, logical);
1390         } else {
1391                 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1392                 eb = btrfs_clone_extent_buffer(eb_root);
1393                 btrfs_tree_read_unlock_blocking(eb_root);
1394                 free_extent_buffer(eb_root);
1395         }
1396
1397         if (!eb)
1398                 return NULL;
1399         extent_buffer_get(eb);
1400         btrfs_tree_read_lock(eb);
1401         if (old_root) {
1402                 btrfs_set_header_bytenr(eb, eb->start);
1403                 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1404                 btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
1405                 btrfs_set_header_level(eb, old_root->level);
1406                 btrfs_set_header_generation(eb, old_generation);
1407         }
1408         if (tm)
1409                 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1410         else
1411                 WARN_ON(btrfs_header_level(eb) != 0);
1412         WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1413
1414         return eb;
1415 }
1416
1417 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1418 {
1419         struct tree_mod_elem *tm;
1420         int level;
1421         struct extent_buffer *eb_root = btrfs_root_node(root);
1422
1423         tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1424         if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1425                 level = tm->old_root.level;
1426         } else {
1427                 level = btrfs_header_level(eb_root);
1428         }
1429         free_extent_buffer(eb_root);
1430
1431         return level;
1432 }
1433
1434 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1435                                    struct btrfs_root *root,
1436                                    struct extent_buffer *buf)
1437 {
1438         if (btrfs_is_testing(root->fs_info))
1439                 return 0;
1440
1441         /* ensure we can see the force_cow */
1442         smp_rmb();
1443
1444         /*
1445          * We do not need to cow a block if
1446          * 1) this block is not created or changed in this transaction;
1447          * 2) this block does not belong to TREE_RELOC tree;
1448          * 3) the root is not forced COW.
1449          *
1450          * What is forced COW:
1451          *    when we create snapshot during committing the transaction,
1452          *    after we've finished coping src root, we must COW the shared
1453          *    block to ensure the metadata consistency.
1454          */
1455         if (btrfs_header_generation(buf) == trans->transid &&
1456             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1457             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1458               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1459             !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1460                 return 0;
1461         return 1;
1462 }
1463
1464 /*
1465  * cows a single block, see __btrfs_cow_block for the real work.
1466  * This version of it has extra checks so that a block isn't COWed more than
1467  * once per transaction, as long as it hasn't been written yet
1468  */
1469 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1470                     struct btrfs_root *root, struct extent_buffer *buf,
1471                     struct extent_buffer *parent, int parent_slot,
1472                     struct extent_buffer **cow_ret)
1473 {
1474         struct btrfs_fs_info *fs_info = root->fs_info;
1475         u64 search_start;
1476         int ret;
1477
1478         if (trans->transaction != fs_info->running_transaction)
1479                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1480                        trans->transid,
1481                        fs_info->running_transaction->transid);
1482
1483         if (trans->transid != fs_info->generation)
1484                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1485                        trans->transid, fs_info->generation);
1486
1487         if (!should_cow_block(trans, root, buf)) {
1488                 trans->dirty = true;
1489                 *cow_ret = buf;
1490                 return 0;
1491         }
1492
1493         search_start = buf->start & ~((u64)SZ_1G - 1);
1494
1495         if (parent)
1496                 btrfs_set_lock_blocking(parent);
1497         btrfs_set_lock_blocking(buf);
1498
1499         ret = __btrfs_cow_block(trans, root, buf, parent,
1500                                  parent_slot, cow_ret, search_start, 0);
1501
1502         trace_btrfs_cow_block(root, buf, *cow_ret);
1503
1504         return ret;
1505 }
1506
1507 /*
1508  * helper function for defrag to decide if two blocks pointed to by a
1509  * node are actually close by
1510  */
1511 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1512 {
1513         if (blocknr < other && other - (blocknr + blocksize) < 32768)
1514                 return 1;
1515         if (blocknr > other && blocknr - (other + blocksize) < 32768)
1516                 return 1;
1517         return 0;
1518 }
1519
1520 /*
1521  * compare two keys in a memcmp fashion
1522  */
1523 static int comp_keys(const struct btrfs_disk_key *disk,
1524                      const struct btrfs_key *k2)
1525 {
1526         struct btrfs_key k1;
1527
1528         btrfs_disk_key_to_cpu(&k1, disk);
1529
1530         return btrfs_comp_cpu_keys(&k1, k2);
1531 }
1532
1533 /*
1534  * same as comp_keys only with two btrfs_key's
1535  */
1536 int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1537 {
1538         if (k1->objectid > k2->objectid)
1539                 return 1;
1540         if (k1->objectid < k2->objectid)
1541                 return -1;
1542         if (k1->type > k2->type)
1543                 return 1;
1544         if (k1->type < k2->type)
1545                 return -1;
1546         if (k1->offset > k2->offset)
1547                 return 1;
1548         if (k1->offset < k2->offset)
1549                 return -1;
1550         return 0;
1551 }
1552
1553 /*
1554  * this is used by the defrag code to go through all the
1555  * leaves pointed to by a node and reallocate them so that
1556  * disk order is close to key order
1557  */
1558 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1559                        struct btrfs_root *root, struct extent_buffer *parent,
1560                        int start_slot, u64 *last_ret,
1561                        struct btrfs_key *progress)
1562 {
1563         struct btrfs_fs_info *fs_info = root->fs_info;
1564         struct extent_buffer *cur;
1565         u64 blocknr;
1566         u64 gen;
1567         u64 search_start = *last_ret;
1568         u64 last_block = 0;
1569         u64 other;
1570         u32 parent_nritems;
1571         int end_slot;
1572         int i;
1573         int err = 0;
1574         int parent_level;
1575         int uptodate;
1576         u32 blocksize;
1577         int progress_passed = 0;
1578         struct btrfs_disk_key disk_key;
1579
1580         parent_level = btrfs_header_level(parent);
1581
1582         WARN_ON(trans->transaction != fs_info->running_transaction);
1583         WARN_ON(trans->transid != fs_info->generation);
1584
1585         parent_nritems = btrfs_header_nritems(parent);
1586         blocksize = fs_info->nodesize;
1587         end_slot = parent_nritems - 1;
1588
1589         if (parent_nritems <= 1)
1590                 return 0;
1591
1592         btrfs_set_lock_blocking(parent);
1593
1594         for (i = start_slot; i <= end_slot; i++) {
1595                 int close = 1;
1596
1597                 btrfs_node_key(parent, &disk_key, i);
1598                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1599                         continue;
1600
1601                 progress_passed = 1;
1602                 blocknr = btrfs_node_blockptr(parent, i);
1603                 gen = btrfs_node_ptr_generation(parent, i);
1604                 if (last_block == 0)
1605                         last_block = blocknr;
1606
1607                 if (i > 0) {
1608                         other = btrfs_node_blockptr(parent, i - 1);
1609                         close = close_blocks(blocknr, other, blocksize);
1610                 }
1611                 if (!close && i < end_slot) {
1612                         other = btrfs_node_blockptr(parent, i + 1);
1613                         close = close_blocks(blocknr, other, blocksize);
1614                 }
1615                 if (close) {
1616                         last_block = blocknr;
1617                         continue;
1618                 }
1619
1620                 cur = find_extent_buffer(fs_info, blocknr);
1621                 if (cur)
1622                         uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1623                 else
1624                         uptodate = 0;
1625                 if (!cur || !uptodate) {
1626                         if (!cur) {
1627                                 cur = read_tree_block(fs_info, blocknr, gen);
1628                                 if (IS_ERR(cur)) {
1629                                         return PTR_ERR(cur);
1630                                 } else if (!extent_buffer_uptodate(cur)) {
1631                                         free_extent_buffer(cur);
1632                                         return -EIO;
1633                                 }
1634                         } else if (!uptodate) {
1635                                 err = btrfs_read_buffer(cur, gen);
1636                                 if (err) {
1637                                         free_extent_buffer(cur);
1638                                         return err;
1639                                 }
1640                         }
1641                 }
1642                 if (search_start == 0)
1643                         search_start = last_block;
1644
1645                 btrfs_tree_lock(cur);
1646                 btrfs_set_lock_blocking(cur);
1647                 err = __btrfs_cow_block(trans, root, cur, parent, i,
1648                                         &cur, search_start,
1649                                         min(16 * blocksize,
1650                                             (end_slot - i) * blocksize));
1651                 if (err) {
1652                         btrfs_tree_unlock(cur);
1653                         free_extent_buffer(cur);
1654                         break;
1655                 }
1656                 search_start = cur->start;
1657                 last_block = cur->start;
1658                 *last_ret = search_start;
1659                 btrfs_tree_unlock(cur);
1660                 free_extent_buffer(cur);
1661         }
1662         return err;
1663 }
1664
1665 /*
1666  * search for key in the extent_buffer.  The items start at offset p,
1667  * and they are item_size apart.  There are 'max' items in p.
1668  *
1669  * the slot in the array is returned via slot, and it points to
1670  * the place where you would insert key if it is not found in
1671  * the array.
1672  *
1673  * slot may point to max if the key is bigger than all of the keys
1674  */
1675 static noinline int generic_bin_search(struct extent_buffer *eb,
1676                                        unsigned long p, int item_size,
1677                                        const struct btrfs_key *key,
1678                                        int max, int *slot)
1679 {
1680         int low = 0;
1681         int high = max;
1682         int mid;
1683         int ret;
1684         struct btrfs_disk_key *tmp = NULL;
1685         struct btrfs_disk_key unaligned;
1686         unsigned long offset;
1687         char *kaddr = NULL;
1688         unsigned long map_start = 0;
1689         unsigned long map_len = 0;
1690         int err;
1691
1692         if (low > high) {
1693                 btrfs_err(eb->fs_info,
1694                  "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1695                           __func__, low, high, eb->start,
1696                           btrfs_header_owner(eb), btrfs_header_level(eb));
1697                 return -EINVAL;
1698         }
1699
1700         while (low < high) {
1701                 mid = (low + high) / 2;
1702                 offset = p + mid * item_size;
1703
1704                 if (!kaddr || offset < map_start ||
1705                     (offset + sizeof(struct btrfs_disk_key)) >
1706                     map_start + map_len) {
1707
1708                         err = map_private_extent_buffer(eb, offset,
1709                                                 sizeof(struct btrfs_disk_key),
1710                                                 &kaddr, &map_start, &map_len);
1711
1712                         if (!err) {
1713                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1714                                                         map_start);
1715                         } else if (err == 1) {
1716                                 read_extent_buffer(eb, &unaligned,
1717                                                    offset, sizeof(unaligned));
1718                                 tmp = &unaligned;
1719                         } else {
1720                                 return err;
1721                         }
1722
1723                 } else {
1724                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
1725                                                         map_start);
1726                 }
1727                 ret = comp_keys(tmp, key);
1728
1729                 if (ret < 0)
1730                         low = mid + 1;
1731                 else if (ret > 0)
1732                         high = mid;
1733                 else {
1734                         *slot = mid;
1735                         return 0;
1736                 }
1737         }
1738         *slot = low;
1739         return 1;
1740 }
1741
1742 /*
1743  * simple bin_search frontend that does the right thing for
1744  * leaves vs nodes
1745  */
1746 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1747                      int level, int *slot)
1748 {
1749         if (level == 0)
1750                 return generic_bin_search(eb,
1751                                           offsetof(struct btrfs_leaf, items),
1752                                           sizeof(struct btrfs_item),
1753                                           key, btrfs_header_nritems(eb),
1754                                           slot);
1755         else
1756                 return generic_bin_search(eb,
1757                                           offsetof(struct btrfs_node, ptrs),
1758                                           sizeof(struct btrfs_key_ptr),
1759                                           key, btrfs_header_nritems(eb),
1760                                           slot);
1761 }
1762
1763 static void root_add_used(struct btrfs_root *root, u32 size)
1764 {
1765         spin_lock(&root->accounting_lock);
1766         btrfs_set_root_used(&root->root_item,
1767                             btrfs_root_used(&root->root_item) + size);
1768         spin_unlock(&root->accounting_lock);
1769 }
1770
1771 static void root_sub_used(struct btrfs_root *root, u32 size)
1772 {
1773         spin_lock(&root->accounting_lock);
1774         btrfs_set_root_used(&root->root_item,
1775                             btrfs_root_used(&root->root_item) - size);
1776         spin_unlock(&root->accounting_lock);
1777 }
1778
1779 /* given a node and slot number, this reads the blocks it points to.  The
1780  * extent buffer is returned with a reference taken (but unlocked).
1781  */
1782 static noinline struct extent_buffer *
1783 read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
1784                int slot)
1785 {
1786         int level = btrfs_header_level(parent);
1787         struct extent_buffer *eb;
1788
1789         if (slot < 0 || slot >= btrfs_header_nritems(parent))
1790                 return ERR_PTR(-ENOENT);
1791
1792         BUG_ON(level == 0);
1793
1794         eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1795                              btrfs_node_ptr_generation(parent, slot));
1796         if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1797                 free_extent_buffer(eb);
1798                 eb = ERR_PTR(-EIO);
1799         }
1800
1801         return eb;
1802 }
1803
1804 /*
1805  * node level balancing, used to make sure nodes are in proper order for
1806  * item deletion.  We balance from the top down, so we have to make sure
1807  * that a deletion won't leave an node completely empty later on.
1808  */
1809 static noinline int balance_level(struct btrfs_trans_handle *trans,
1810                          struct btrfs_root *root,
1811                          struct btrfs_path *path, int level)
1812 {
1813         struct btrfs_fs_info *fs_info = root->fs_info;
1814         struct extent_buffer *right = NULL;
1815         struct extent_buffer *mid;
1816         struct extent_buffer *left = NULL;
1817         struct extent_buffer *parent = NULL;
1818         int ret = 0;
1819         int wret;
1820         int pslot;
1821         int orig_slot = path->slots[level];
1822         u64 orig_ptr;
1823
1824         if (level == 0)
1825                 return 0;
1826
1827         mid = path->nodes[level];
1828
1829         WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1830                 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1831         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1832
1833         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1834
1835         if (level < BTRFS_MAX_LEVEL - 1) {
1836                 parent = path->nodes[level + 1];
1837                 pslot = path->slots[level + 1];
1838         }
1839
1840         /*
1841          * deal with the case where there is only one pointer in the root
1842          * by promoting the node below to a root
1843          */
1844         if (!parent) {
1845                 struct extent_buffer *child;
1846
1847                 if (btrfs_header_nritems(mid) != 1)
1848                         return 0;
1849
1850                 /* promote the child to a root */
1851                 child = read_node_slot(fs_info, mid, 0);
1852                 if (IS_ERR(child)) {
1853                         ret = PTR_ERR(child);
1854                         btrfs_handle_fs_error(fs_info, ret, NULL);
1855                         goto enospc;
1856                 }
1857
1858                 btrfs_tree_lock(child);
1859                 btrfs_set_lock_blocking(child);
1860                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1861                 if (ret) {
1862                         btrfs_tree_unlock(child);
1863                         free_extent_buffer(child);
1864                         goto enospc;
1865                 }
1866
1867                 ret = tree_mod_log_insert_root(root->node, child, 1);
1868                 BUG_ON(ret < 0);
1869                 rcu_assign_pointer(root->node, child);
1870
1871                 add_root_to_dirty_list(root);
1872                 btrfs_tree_unlock(child);
1873
1874                 path->locks[level] = 0;
1875                 path->nodes[level] = NULL;
1876                 clean_tree_block(fs_info, mid);
1877                 btrfs_tree_unlock(mid);
1878                 /* once for the path */
1879                 free_extent_buffer(mid);
1880
1881                 root_sub_used(root, mid->len);
1882                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1883                 /* once for the root ptr */
1884                 free_extent_buffer_stale(mid);
1885                 return 0;
1886         }
1887         if (btrfs_header_nritems(mid) >
1888             BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1889                 return 0;
1890
1891         left = read_node_slot(fs_info, parent, pslot - 1);
1892         if (IS_ERR(left))
1893                 left = NULL;
1894
1895         if (left) {
1896                 btrfs_tree_lock(left);
1897                 btrfs_set_lock_blocking(left);
1898                 wret = btrfs_cow_block(trans, root, left,
1899                                        parent, pslot - 1, &left);
1900                 if (wret) {
1901                         ret = wret;
1902                         goto enospc;
1903                 }
1904         }
1905
1906         right = read_node_slot(fs_info, parent, pslot + 1);
1907         if (IS_ERR(right))
1908                 right = NULL;
1909
1910         if (right) {
1911                 btrfs_tree_lock(right);
1912                 btrfs_set_lock_blocking(right);
1913                 wret = btrfs_cow_block(trans, root, right,
1914                                        parent, pslot + 1, &right);
1915                 if (wret) {
1916                         ret = wret;
1917                         goto enospc;
1918                 }
1919         }
1920
1921         /* first, try to make some room in the middle buffer */
1922         if (left) {
1923                 orig_slot += btrfs_header_nritems(left);
1924                 wret = push_node_left(trans, fs_info, left, mid, 1);
1925                 if (wret < 0)
1926                         ret = wret;
1927         }
1928
1929         /*
1930          * then try to empty the right most buffer into the middle
1931          */
1932         if (right) {
1933                 wret = push_node_left(trans, fs_info, mid, right, 1);
1934                 if (wret < 0 && wret != -ENOSPC)
1935                         ret = wret;
1936                 if (btrfs_header_nritems(right) == 0) {
1937                         clean_tree_block(fs_info, right);
1938                         btrfs_tree_unlock(right);
1939                         del_ptr(root, path, level + 1, pslot + 1);
1940                         root_sub_used(root, right->len);
1941                         btrfs_free_tree_block(trans, root, right, 0, 1);
1942                         free_extent_buffer_stale(right);
1943                         right = NULL;
1944                 } else {
1945                         struct btrfs_disk_key right_key;
1946                         btrfs_node_key(right, &right_key, 0);
1947                         ret = tree_mod_log_insert_key(parent, pslot + 1,
1948                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1949                         BUG_ON(ret < 0);
1950                         btrfs_set_node_key(parent, &right_key, pslot + 1);
1951                         btrfs_mark_buffer_dirty(parent);
1952                 }
1953         }
1954         if (btrfs_header_nritems(mid) == 1) {
1955                 /*
1956                  * we're not allowed to leave a node with one item in the
1957                  * tree during a delete.  A deletion from lower in the tree
1958                  * could try to delete the only pointer in this node.
1959                  * So, pull some keys from the left.
1960                  * There has to be a left pointer at this point because
1961                  * otherwise we would have pulled some pointers from the
1962                  * right
1963                  */
1964                 if (!left) {
1965                         ret = -EROFS;
1966                         btrfs_handle_fs_error(fs_info, ret, NULL);
1967                         goto enospc;
1968                 }
1969                 wret = balance_node_right(trans, fs_info, mid, left);
1970                 if (wret < 0) {
1971                         ret = wret;
1972                         goto enospc;
1973                 }
1974                 if (wret == 1) {
1975                         wret = push_node_left(trans, fs_info, left, mid, 1);
1976                         if (wret < 0)
1977                                 ret = wret;
1978                 }
1979                 BUG_ON(wret == 1);
1980         }
1981         if (btrfs_header_nritems(mid) == 0) {
1982                 clean_tree_block(fs_info, mid);
1983                 btrfs_tree_unlock(mid);
1984                 del_ptr(root, path, level + 1, pslot);
1985                 root_sub_used(root, mid->len);
1986                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1987                 free_extent_buffer_stale(mid);
1988                 mid = NULL;
1989         } else {
1990                 /* update the parent key to reflect our changes */
1991                 struct btrfs_disk_key mid_key;
1992                 btrfs_node_key(mid, &mid_key, 0);
1993                 ret = tree_mod_log_insert_key(parent, pslot,
1994                                 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1995                 BUG_ON(ret < 0);
1996                 btrfs_set_node_key(parent, &mid_key, pslot);
1997                 btrfs_mark_buffer_dirty(parent);
1998         }
1999
2000         /* update the path */
2001         if (left) {
2002                 if (btrfs_header_nritems(left) > orig_slot) {
2003                         extent_buffer_get(left);
2004                         /* left was locked after cow */
2005                         path->nodes[level] = left;
2006                         path->slots[level + 1] -= 1;
2007                         path->slots[level] = orig_slot;
2008                         if (mid) {
2009                                 btrfs_tree_unlock(mid);
2010                                 free_extent_buffer(mid);
2011                         }
2012                 } else {
2013                         orig_slot -= btrfs_header_nritems(left);
2014                         path->slots[level] = orig_slot;
2015                 }
2016         }
2017         /* double check we haven't messed things up */
2018         if (orig_ptr !=
2019             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2020                 BUG();
2021 enospc:
2022         if (right) {
2023                 btrfs_tree_unlock(right);
2024                 free_extent_buffer(right);
2025         }
2026         if (left) {
2027                 if (path->nodes[level] != left)
2028                         btrfs_tree_unlock(left);
2029                 free_extent_buffer(left);
2030         }
2031         return ret;
2032 }
2033
2034 /* Node balancing for insertion.  Here we only split or push nodes around
2035  * when they are completely full.  This is also done top down, so we
2036  * have to be pessimistic.
2037  */
2038 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2039                                           struct btrfs_root *root,
2040                                           struct btrfs_path *path, int level)
2041 {
2042         struct btrfs_fs_info *fs_info = root->fs_info;
2043         struct extent_buffer *right = NULL;
2044         struct extent_buffer *mid;
2045         struct extent_buffer *left = NULL;
2046         struct extent_buffer *parent = NULL;
2047         int ret = 0;
2048         int wret;
2049         int pslot;
2050         int orig_slot = path->slots[level];
2051
2052         if (level == 0)
2053                 return 1;
2054
2055         mid = path->nodes[level];
2056         WARN_ON(btrfs_header_generation(mid) != trans->transid);
2057
2058         if (level < BTRFS_MAX_LEVEL - 1) {
2059                 parent = path->nodes[level + 1];
2060                 pslot = path->slots[level + 1];
2061         }
2062
2063         if (!parent)
2064                 return 1;
2065
2066         left = read_node_slot(fs_info, parent, pslot - 1);
2067         if (IS_ERR(left))
2068                 left = NULL;
2069
2070         /* first, try to make some room in the middle buffer */
2071         if (left) {
2072                 u32 left_nr;
2073
2074                 btrfs_tree_lock(left);
2075                 btrfs_set_lock_blocking(left);
2076
2077                 left_nr = btrfs_header_nritems(left);
2078                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2079                         wret = 1;
2080                 } else {
2081                         ret = btrfs_cow_block(trans, root, left, parent,
2082                                               pslot - 1, &left);
2083                         if (ret)
2084                                 wret = 1;
2085                         else {
2086                                 wret = push_node_left(trans, fs_info,
2087                                                       left, mid, 0);
2088                         }
2089                 }
2090                 if (wret < 0)
2091                         ret = wret;
2092                 if (wret == 0) {
2093                         struct btrfs_disk_key disk_key;
2094                         orig_slot += left_nr;
2095                         btrfs_node_key(mid, &disk_key, 0);
2096                         ret = tree_mod_log_insert_key(parent, pslot,
2097                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
2098                         BUG_ON(ret < 0);
2099                         btrfs_set_node_key(parent, &disk_key, pslot);
2100                         btrfs_mark_buffer_dirty(parent);
2101                         if (btrfs_header_nritems(left) > orig_slot) {
2102                                 path->nodes[level] = left;
2103                                 path->slots[level + 1] -= 1;
2104                                 path->slots[level] = orig_slot;
2105                                 btrfs_tree_unlock(mid);
2106                                 free_extent_buffer(mid);
2107                         } else {
2108                                 orig_slot -=
2109                                         btrfs_header_nritems(left);
2110                                 path->slots[level] = orig_slot;
2111                                 btrfs_tree_unlock(left);
2112                                 free_extent_buffer(left);
2113                         }
2114                         return 0;
2115                 }
2116                 btrfs_tree_unlock(left);
2117                 free_extent_buffer(left);
2118         }
2119         right = read_node_slot(fs_info, parent, pslot + 1);
2120         if (IS_ERR(right))
2121                 right = NULL;
2122
2123         /*
2124          * then try to empty the right most buffer into the middle
2125          */
2126         if (right) {
2127                 u32 right_nr;
2128
2129                 btrfs_tree_lock(right);
2130                 btrfs_set_lock_blocking(right);
2131
2132                 right_nr = btrfs_header_nritems(right);
2133                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2134                         wret = 1;
2135                 } else {
2136                         ret = btrfs_cow_block(trans, root, right,
2137                                               parent, pslot + 1,
2138                                               &right);
2139                         if (ret)
2140                                 wret = 1;
2141                         else {
2142                                 wret = balance_node_right(trans, fs_info,
2143                                                           right, mid);
2144                         }
2145                 }
2146                 if (wret < 0)
2147                         ret = wret;
2148                 if (wret == 0) {
2149                         struct btrfs_disk_key disk_key;
2150
2151                         btrfs_node_key(right, &disk_key, 0);
2152                         ret = tree_mod_log_insert_key(parent, pslot + 1,
2153                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
2154                         BUG_ON(ret < 0);
2155                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
2156                         btrfs_mark_buffer_dirty(parent);
2157
2158                         if (btrfs_header_nritems(mid) <= orig_slot) {
2159                                 path->nodes[level] = right;
2160                                 path->slots[level + 1] += 1;
2161                                 path->slots[level] = orig_slot -
2162                                         btrfs_header_nritems(mid);
2163                                 btrfs_tree_unlock(mid);
2164                                 free_extent_buffer(mid);
2165                         } else {
2166                                 btrfs_tree_unlock(right);
2167                                 free_extent_buffer(right);
2168                         }
2169                         return 0;
2170                 }
2171                 btrfs_tree_unlock(right);
2172                 free_extent_buffer(right);
2173         }
2174         return 1;
2175 }
2176
2177 /*
2178  * readahead one full node of leaves, finding things that are close
2179  * to the block in 'slot', and triggering ra on them.
2180  */
2181 static void reada_for_search(struct btrfs_fs_info *fs_info,
2182                              struct btrfs_path *path,
2183                              int level, int slot, u64 objectid)
2184 {
2185         struct extent_buffer *node;
2186         struct btrfs_disk_key disk_key;
2187         u32 nritems;
2188         u64 search;
2189         u64 target;
2190         u64 nread = 0;
2191         struct extent_buffer *eb;
2192         u32 nr;
2193         u32 blocksize;
2194         u32 nscan = 0;
2195
2196         if (level != 1)
2197                 return;
2198
2199         if (!path->nodes[level])
2200                 return;
2201
2202         node = path->nodes[level];
2203
2204         search = btrfs_node_blockptr(node, slot);
2205         blocksize = fs_info->nodesize;
2206         eb = find_extent_buffer(fs_info, search);
2207         if (eb) {
2208                 free_extent_buffer(eb);
2209                 return;
2210         }
2211
2212         target = search;
2213
2214         nritems = btrfs_header_nritems(node);
2215         nr = slot;
2216
2217         while (1) {
2218                 if (path->reada == READA_BACK) {
2219                         if (nr == 0)
2220                                 break;
2221                         nr--;
2222                 } else if (path->reada == READA_FORWARD) {
2223                         nr++;
2224                         if (nr >= nritems)
2225                                 break;
2226                 }
2227                 if (path->reada == READA_BACK && objectid) {
2228                         btrfs_node_key(node, &disk_key, nr);
2229                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
2230                                 break;
2231                 }
2232                 search = btrfs_node_blockptr(node, nr);
2233                 if ((search <= target && target - search <= 65536) ||
2234                     (search > target && search - target <= 65536)) {
2235                         readahead_tree_block(fs_info, search);
2236                         nread += blocksize;
2237                 }
2238                 nscan++;
2239                 if ((nread > 65536 || nscan > 32))
2240                         break;
2241         }
2242 }
2243
2244 static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2245                                        struct btrfs_path *path, int level)
2246 {
2247         int slot;
2248         int nritems;
2249         struct extent_buffer *parent;
2250         struct extent_buffer *eb;
2251         u64 gen;
2252         u64 block1 = 0;
2253         u64 block2 = 0;
2254
2255         parent = path->nodes[level + 1];
2256         if (!parent)
2257                 return;
2258
2259         nritems = btrfs_header_nritems(parent);
2260         slot = path->slots[level + 1];
2261
2262         if (slot > 0) {
2263                 block1 = btrfs_node_blockptr(parent, slot - 1);
2264                 gen = btrfs_node_ptr_generation(parent, slot - 1);
2265                 eb = find_extent_buffer(fs_info, block1);
2266                 /*
2267                  * if we get -eagain from btrfs_buffer_uptodate, we
2268                  * don't want to return eagain here.  That will loop
2269                  * forever
2270                  */
2271                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2272                         block1 = 0;
2273                 free_extent_buffer(eb);
2274         }
2275         if (slot + 1 < nritems) {
2276                 block2 = btrfs_node_blockptr(parent, slot + 1);
2277                 gen = btrfs_node_ptr_generation(parent, slot + 1);
2278                 eb = find_extent_buffer(fs_info, block2);
2279                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2280                         block2 = 0;
2281                 free_extent_buffer(eb);
2282         }
2283
2284         if (block1)
2285                 readahead_tree_block(fs_info, block1);
2286         if (block2)
2287                 readahead_tree_block(fs_info, block2);
2288 }
2289
2290
2291 /*
2292  * when we walk down the tree, it is usually safe to unlock the higher layers
2293  * in the tree.  The exceptions are when our path goes through slot 0, because
2294  * operations on the tree might require changing key pointers higher up in the
2295  * tree.
2296  *
2297  * callers might also have set path->keep_locks, which tells this code to keep
2298  * the lock if the path points to the last slot in the block.  This is part of
2299  * walking through the tree, and selecting the next slot in the higher block.
2300  *
2301  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2302  * if lowest_unlock is 1, level 0 won't be unlocked
2303  */
2304 static noinline void unlock_up(struct btrfs_path *path, int level,
2305                                int lowest_unlock, int min_write_lock_level,
2306                                int *write_lock_level)
2307 {
2308         int i;
2309         int skip_level = level;
2310         int no_skips = 0;
2311         struct extent_buffer *t;
2312
2313         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2314                 if (!path->nodes[i])
2315                         break;
2316                 if (!path->locks[i])
2317                         break;
2318                 if (!no_skips && path->slots[i] == 0) {
2319                         skip_level = i + 1;
2320                         continue;
2321                 }
2322                 if (!no_skips && path->keep_locks) {
2323                         u32 nritems;
2324                         t = path->nodes[i];
2325                         nritems = btrfs_header_nritems(t);
2326                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
2327                                 skip_level = i + 1;
2328                                 continue;
2329                         }
2330                 }
2331                 if (skip_level < i && i >= lowest_unlock)
2332                         no_skips = 1;
2333
2334                 t = path->nodes[i];
2335                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2336                         btrfs_tree_unlock_rw(t, path->locks[i]);
2337                         path->locks[i] = 0;
2338                         if (write_lock_level &&
2339                             i > min_write_lock_level &&
2340                             i <= *write_lock_level) {
2341                                 *write_lock_level = i - 1;
2342                         }
2343                 }
2344         }
2345 }
2346
2347 /*
2348  * This releases any locks held in the path starting at level and
2349  * going all the way up to the root.
2350  *
2351  * btrfs_search_slot will keep the lock held on higher nodes in a few
2352  * corner cases, such as COW of the block at slot zero in the node.  This
2353  * ignores those rules, and it should only be called when there are no
2354  * more updates to be done higher up in the tree.
2355  */
2356 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2357 {
2358         int i;
2359
2360         if (path->keep_locks)
2361                 return;
2362
2363         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2364                 if (!path->nodes[i])
2365                         continue;
2366                 if (!path->locks[i])
2367                         continue;
2368                 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2369                 path->locks[i] = 0;
2370         }
2371 }
2372
2373 /*
2374  * helper function for btrfs_search_slot.  The goal is to find a block
2375  * in cache without setting the path to blocking.  If we find the block
2376  * we return zero and the path is unchanged.
2377  *
2378  * If we can't find the block, we set the path blocking and do some
2379  * reada.  -EAGAIN is returned and the search must be repeated.
2380  */
2381 static int
2382 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2383                       struct extent_buffer **eb_ret, int level, int slot,
2384                       const struct btrfs_key *key)
2385 {
2386         struct btrfs_fs_info *fs_info = root->fs_info;
2387         u64 blocknr;
2388         u64 gen;
2389         struct extent_buffer *b = *eb_ret;
2390         struct extent_buffer *tmp;
2391         int ret;
2392
2393         blocknr = btrfs_node_blockptr(b, slot);
2394         gen = btrfs_node_ptr_generation(b, slot);
2395
2396         tmp = find_extent_buffer(fs_info, blocknr);
2397         if (tmp) {
2398                 /* first we do an atomic uptodate check */
2399                 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2400                         *eb_ret = tmp;
2401                         return 0;
2402                 }
2403
2404                 /* the pages were up to date, but we failed
2405                  * the generation number check.  Do a full
2406                  * read for the generation number that is correct.
2407                  * We must do this without dropping locks so
2408                  * we can trust our generation number
2409                  */
2410                 btrfs_set_path_blocking(p);
2411
2412                 /* now we're allowed to do a blocking uptodate check */
2413                 ret = btrfs_read_buffer(tmp, gen);
2414                 if (!ret) {
2415                         *eb_ret = tmp;
2416                         return 0;
2417                 }
2418                 free_extent_buffer(tmp);
2419                 btrfs_release_path(p);
2420                 return -EIO;
2421         }
2422
2423         /*
2424          * reduce lock contention at high levels
2425          * of the btree by dropping locks before
2426          * we read.  Don't release the lock on the current
2427          * level because we need to walk this node to figure
2428          * out which blocks to read.
2429          */
2430         btrfs_unlock_up_safe(p, level + 1);
2431         btrfs_set_path_blocking(p);
2432
2433         free_extent_buffer(tmp);
2434         if (p->reada != READA_NONE)
2435                 reada_for_search(fs_info, p, level, slot, key->objectid);
2436
2437         btrfs_release_path(p);
2438
2439         ret = -EAGAIN;
2440         tmp = read_tree_block(fs_info, blocknr, 0);
2441         if (!IS_ERR(tmp)) {
2442                 /*
2443                  * If the read above didn't mark this buffer up to date,
2444                  * it will never end up being up to date.  Set ret to EIO now
2445                  * and give up so that our caller doesn't loop forever
2446                  * on our EAGAINs.
2447                  */
2448                 if (!btrfs_buffer_uptodate(tmp, 0, 0))
2449                         ret = -EIO;
2450                 free_extent_buffer(tmp);
2451         } else {
2452                 ret = PTR_ERR(tmp);
2453         }
2454         return ret;
2455 }
2456
2457 /*
2458  * helper function for btrfs_search_slot.  This does all of the checks
2459  * for node-level blocks and does any balancing required based on
2460  * the ins_len.
2461  *
2462  * If no extra work was required, zero is returned.  If we had to
2463  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2464  * start over
2465  */
2466 static int
2467 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2468                        struct btrfs_root *root, struct btrfs_path *p,
2469                        struct extent_buffer *b, int level, int ins_len,
2470                        int *write_lock_level)
2471 {
2472         struct btrfs_fs_info *fs_info = root->fs_info;
2473         int ret;
2474
2475         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2476             BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2477                 int sret;
2478
2479                 if (*write_lock_level < level + 1) {
2480                         *write_lock_level = level + 1;
2481                         btrfs_release_path(p);
2482                         goto again;
2483                 }
2484
2485                 btrfs_set_path_blocking(p);
2486                 reada_for_balance(fs_info, p, level);
2487                 sret = split_node(trans, root, p, level);
2488                 btrfs_clear_path_blocking(p, NULL, 0);
2489
2490                 BUG_ON(sret > 0);
2491                 if (sret) {
2492                         ret = sret;
2493                         goto done;
2494                 }
2495                 b = p->nodes[level];
2496         } else if (ins_len < 0 && btrfs_header_nritems(b) <
2497                    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2498                 int sret;
2499
2500                 if (*write_lock_level < level + 1) {
2501                         *write_lock_level = level + 1;
2502                         btrfs_release_path(p);
2503                         goto again;
2504                 }
2505
2506                 btrfs_set_path_blocking(p);
2507                 reada_for_balance(fs_info, p, level);
2508                 sret = balance_level(trans, root, p, level);
2509                 btrfs_clear_path_blocking(p, NULL, 0);
2510
2511                 if (sret) {
2512                         ret = sret;
2513                         goto done;
2514                 }
2515                 b = p->nodes[level];
2516                 if (!b) {
2517                         btrfs_release_path(p);
2518                         goto again;
2519                 }
2520                 BUG_ON(btrfs_header_nritems(b) == 1);
2521         }
2522         return 0;
2523
2524 again:
2525         ret = -EAGAIN;
2526 done:
2527         return ret;
2528 }
2529
2530 static void key_search_validate(struct extent_buffer *b,
2531                                 const struct btrfs_key *key,
2532                                 int level)
2533 {
2534 #ifdef CONFIG_BTRFS_ASSERT
2535         struct btrfs_disk_key disk_key;
2536
2537         btrfs_cpu_key_to_disk(&disk_key, key);
2538
2539         if (level == 0)
2540                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2541                     offsetof(struct btrfs_leaf, items[0].key),
2542                     sizeof(disk_key)));
2543         else
2544                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2545                     offsetof(struct btrfs_node, ptrs[0].key),
2546                     sizeof(disk_key)));
2547 #endif
2548 }
2549
2550 static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2551                       int level, int *prev_cmp, int *slot)
2552 {
2553         if (*prev_cmp != 0) {
2554                 *prev_cmp = btrfs_bin_search(b, key, level, slot);
2555                 return *prev_cmp;
2556         }
2557
2558         key_search_validate(b, key, level);
2559         *slot = 0;
2560
2561         return 0;
2562 }
2563
2564 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2565                 u64 iobjectid, u64 ioff, u8 key_type,
2566                 struct btrfs_key *found_key)
2567 {
2568         int ret;
2569         struct btrfs_key key;
2570         struct extent_buffer *eb;
2571
2572         ASSERT(path);
2573         ASSERT(found_key);
2574
2575         key.type = key_type;
2576         key.objectid = iobjectid;
2577         key.offset = ioff;
2578
2579         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2580         if (ret < 0)
2581                 return ret;
2582
2583         eb = path->nodes[0];
2584         if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2585                 ret = btrfs_next_leaf(fs_root, path);
2586                 if (ret)
2587                         return ret;
2588                 eb = path->nodes[0];
2589         }
2590
2591         btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2592         if (found_key->type != key.type ||
2593                         found_key->objectid != key.objectid)
2594                 return 1;
2595
2596         return 0;
2597 }
2598
2599 /*
2600  * btrfs_search_slot - look for a key in a tree and perform necessary
2601  * modifications to preserve tree invariants.
2602  *
2603  * @trans:      Handle of transaction, used when modifying the tree
2604  * @p:          Holds all btree nodes along the search path
2605  * @root:       The root node of the tree
2606  * @key:        The key we are looking for
2607  * @ins_len:    Indicates purpose of search, for inserts it is 1, for
2608  *              deletions it's -1. 0 for plain searches
2609  * @cow:        boolean should CoW operations be performed. Must always be 1
2610  *              when modifying the tree.
2611  *
2612  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2613  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2614  *
2615  * If @key is found, 0 is returned and you can find the item in the leaf level
2616  * of the path (level 0)
2617  *
2618  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2619  * points to the slot where it should be inserted
2620  *
2621  * If an error is encountered while searching the tree a negative error number
2622  * is returned
2623  */
2624 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2625                       const struct btrfs_key *key, struct btrfs_path *p,
2626                       int ins_len, int cow)
2627 {
2628         struct btrfs_fs_info *fs_info = root->fs_info;
2629         struct extent_buffer *b;
2630         int slot;
2631         int ret;
2632         int err;
2633         int level;
2634         int lowest_unlock = 1;
2635         int root_lock;
2636         /* everything at write_lock_level or lower must be write locked */
2637         int write_lock_level = 0;
2638         u8 lowest_level = 0;
2639         int min_write_lock_level;
2640         int prev_cmp;
2641
2642         lowest_level = p->lowest_level;
2643         WARN_ON(lowest_level && ins_len > 0);
2644         WARN_ON(p->nodes[0] != NULL);
2645         BUG_ON(!cow && ins_len);
2646
2647         if (ins_len < 0) {
2648                 lowest_unlock = 2;
2649
2650                 /* when we are removing items, we might have to go up to level
2651                  * two as we update tree pointers  Make sure we keep write
2652                  * for those levels as well
2653                  */
2654                 write_lock_level = 2;
2655         } else if (ins_len > 0) {
2656                 /*
2657                  * for inserting items, make sure we have a write lock on
2658                  * level 1 so we can update keys
2659                  */
2660                 write_lock_level = 1;
2661         }
2662
2663         if (!cow)
2664                 write_lock_level = -1;
2665
2666         if (cow && (p->keep_locks || p->lowest_level))
2667                 write_lock_level = BTRFS_MAX_LEVEL;
2668
2669         min_write_lock_level = write_lock_level;
2670
2671 again:
2672         prev_cmp = -1;
2673         /*
2674          * we try very hard to do read locks on the root
2675          */
2676         root_lock = BTRFS_READ_LOCK;
2677         level = 0;
2678         if (p->search_commit_root) {
2679                 /*
2680                  * the commit roots are read only
2681                  * so we always do read locks
2682                  */
2683                 if (p->need_commit_sem)
2684                         down_read(&fs_info->commit_root_sem);
2685                 b = root->commit_root;
2686                 extent_buffer_get(b);
2687                 level = btrfs_header_level(b);
2688                 if (p->need_commit_sem)
2689                         up_read(&fs_info->commit_root_sem);
2690                 if (!p->skip_locking)
2691                         btrfs_tree_read_lock(b);
2692         } else {
2693                 if (p->skip_locking) {
2694                         b = btrfs_root_node(root);
2695                         level = btrfs_header_level(b);
2696                 } else {
2697                         /* we don't know the level of the root node
2698                          * until we actually have it read locked
2699                          */
2700                         b = btrfs_read_lock_root_node(root);
2701                         level = btrfs_header_level(b);
2702                         if (level <= write_lock_level) {
2703                                 /* whoops, must trade for write lock */
2704                                 btrfs_tree_read_unlock(b);
2705                                 free_extent_buffer(b);
2706                                 b = btrfs_lock_root_node(root);
2707                                 root_lock = BTRFS_WRITE_LOCK;
2708
2709                                 /* the level might have changed, check again */
2710                                 level = btrfs_header_level(b);
2711                         }
2712                 }
2713         }
2714         p->nodes[level] = b;
2715         if (!p->skip_locking)
2716                 p->locks[level] = root_lock;
2717
2718         while (b) {
2719                 level = btrfs_header_level(b);
2720
2721                 /*
2722                  * setup the path here so we can release it under lock
2723                  * contention with the cow code
2724                  */
2725                 if (cow) {
2726                         bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2727
2728                         /*
2729                          * if we don't really need to cow this block
2730                          * then we don't want to set the path blocking,
2731                          * so we test it here
2732                          */
2733                         if (!should_cow_block(trans, root, b)) {
2734                                 trans->dirty = true;
2735                                 goto cow_done;
2736                         }
2737
2738                         /*
2739                          * must have write locks on this node and the
2740                          * parent
2741                          */
2742                         if (level > write_lock_level ||
2743                             (level + 1 > write_lock_level &&
2744                             level + 1 < BTRFS_MAX_LEVEL &&
2745                             p->nodes[level + 1])) {
2746                                 write_lock_level = level + 1;
2747                                 btrfs_release_path(p);
2748                                 goto again;
2749                         }
2750
2751                         btrfs_set_path_blocking(p);
2752                         if (last_level)
2753                                 err = btrfs_cow_block(trans, root, b, NULL, 0,
2754                                                       &b);
2755                         else
2756                                 err = btrfs_cow_block(trans, root, b,
2757                                                       p->nodes[level + 1],
2758                                                       p->slots[level + 1], &b);
2759                         if (err) {
2760                                 ret = err;
2761                                 goto done;
2762                         }
2763                 }
2764 cow_done:
2765                 p->nodes[level] = b;
2766                 btrfs_clear_path_blocking(p, NULL, 0);
2767
2768                 /*
2769                  * we have a lock on b and as long as we aren't changing
2770                  * the tree, there is no way to for the items in b to change.
2771                  * It is safe to drop the lock on our parent before we
2772                  * go through the expensive btree search on b.
2773                  *
2774                  * If we're inserting or deleting (ins_len != 0), then we might
2775                  * be changing slot zero, which may require changing the parent.
2776                  * So, we can't drop the lock until after we know which slot
2777                  * we're operating on.
2778                  */
2779                 if (!ins_len && !p->keep_locks) {
2780                         int u = level + 1;
2781
2782                         if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2783                                 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2784                                 p->locks[u] = 0;
2785                         }
2786                 }
2787
2788                 ret = key_search(b, key, level, &prev_cmp, &slot);
2789                 if (ret < 0)
2790                         goto done;
2791
2792                 if (level != 0) {
2793                         int dec = 0;
2794                         if (ret && slot > 0) {
2795                                 dec = 1;
2796                                 slot -= 1;
2797                         }
2798                         p->slots[level] = slot;
2799                         err = setup_nodes_for_search(trans, root, p, b, level,
2800                                              ins_len, &write_lock_level);
2801                         if (err == -EAGAIN)
2802                                 goto again;
2803                         if (err) {
2804                                 ret = err;
2805                                 goto done;
2806                         }
2807                         b = p->nodes[level];
2808                         slot = p->slots[level];
2809
2810                         /*
2811                          * slot 0 is special, if we change the key
2812                          * we have to update the parent pointer
2813                          * which means we must have a write lock
2814                          * on the parent
2815                          */
2816                         if (slot == 0 && ins_len &&
2817                             write_lock_level < level + 1) {
2818                                 write_lock_level = level + 1;
2819                                 btrfs_release_path(p);
2820                                 goto again;
2821                         }
2822
2823                         unlock_up(p, level, lowest_unlock,
2824                                   min_write_lock_level, &write_lock_level);
2825
2826                         if (level == lowest_level) {
2827                                 if (dec)
2828                                         p->slots[level]++;
2829                                 goto done;
2830                         }
2831
2832                         err = read_block_for_search(root, p, &b, level,
2833                                                     slot, key);
2834                         if (err == -EAGAIN)
2835                                 goto again;
2836                         if (err) {
2837                                 ret = err;
2838                                 goto done;
2839                         }
2840
2841                         if (!p->skip_locking) {
2842                                 level = btrfs_header_level(b);
2843                                 if (level <= write_lock_level) {
2844                                         err = btrfs_try_tree_write_lock(b);
2845                                         if (!err) {
2846                                                 btrfs_set_path_blocking(p);
2847                                                 btrfs_tree_lock(b);
2848                                                 btrfs_clear_path_blocking(p, b,
2849                                                                   BTRFS_WRITE_LOCK);
2850                                         }
2851                                         p->locks[level] = BTRFS_WRITE_LOCK;
2852                                 } else {
2853                                         err = btrfs_tree_read_lock_atomic(b);
2854                                         if (!err) {
2855                                                 btrfs_set_path_blocking(p);
2856                                                 btrfs_tree_read_lock(b);
2857                                                 btrfs_clear_path_blocking(p, b,
2858                                                                   BTRFS_READ_LOCK);
2859                                         }
2860                                         p->locks[level] = BTRFS_READ_LOCK;
2861                                 }
2862                                 p->nodes[level] = b;
2863                         }
2864                 } else {
2865                         p->slots[level] = slot;
2866                         if (ins_len > 0 &&
2867                             btrfs_leaf_free_space(fs_info, b) < ins_len) {
2868                                 if (write_lock_level < 1) {
2869                                         write_lock_level = 1;
2870                                         btrfs_release_path(p);
2871                                         goto again;
2872                                 }
2873
2874                                 btrfs_set_path_blocking(p);
2875                                 err = split_leaf(trans, root, key,
2876                                                  p, ins_len, ret == 0);
2877                                 btrfs_clear_path_blocking(p, NULL, 0);
2878
2879                                 BUG_ON(err > 0);
2880                                 if (err) {
2881                                         ret = err;
2882                                         goto done;
2883                                 }
2884                         }
2885                         if (!p->search_for_split)
2886                                 unlock_up(p, level, lowest_unlock,
2887                                           min_write_lock_level, &write_lock_level);
2888                         goto done;
2889                 }
2890         }
2891         ret = 1;
2892 done:
2893         /*
2894          * we don't really know what they plan on doing with the path
2895          * from here on, so for now just mark it as blocking
2896          */
2897         if (!p->leave_spinning)
2898                 btrfs_set_path_blocking(p);
2899         if (ret < 0 && !p->skip_release_on_error)
2900                 btrfs_release_path(p);
2901         return ret;
2902 }
2903
2904 /*
2905  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2906  * current state of the tree together with the operations recorded in the tree
2907  * modification log to search for the key in a previous version of this tree, as
2908  * denoted by the time_seq parameter.
2909  *
2910  * Naturally, there is no support for insert, delete or cow operations.
2911  *
2912  * The resulting path and return value will be set up as if we called
2913  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2914  */
2915 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2916                           struct btrfs_path *p, u64 time_seq)
2917 {
2918         struct btrfs_fs_info *fs_info = root->fs_info;
2919         struct extent_buffer *b;
2920         int slot;
2921         int ret;
2922         int err;
2923         int level;
2924         int lowest_unlock = 1;
2925         u8 lowest_level = 0;
2926         int prev_cmp = -1;
2927
2928         lowest_level = p->lowest_level;
2929         WARN_ON(p->nodes[0] != NULL);
2930
2931         if (p->search_commit_root) {
2932                 BUG_ON(time_seq);
2933                 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2934         }
2935
2936 again:
2937         b = get_old_root(root, time_seq);
2938         level = btrfs_header_level(b);
2939         p->locks[level] = BTRFS_READ_LOCK;
2940
2941         while (b) {
2942                 level = btrfs_header_level(b);
2943                 p->nodes[level] = b;
2944                 btrfs_clear_path_blocking(p, NULL, 0);
2945
2946                 /*
2947                  * we have a lock on b and as long as we aren't changing
2948                  * the tree, there is no way to for the items in b to change.
2949                  * It is safe to drop the lock on our parent before we
2950                  * go through the expensive btree search on b.
2951                  */
2952                 btrfs_unlock_up_safe(p, level + 1);
2953
2954                 /*
2955                  * Since we can unwind ebs we want to do a real search every
2956                  * time.
2957                  */
2958                 prev_cmp = -1;
2959                 ret = key_search(b, key, level, &prev_cmp, &slot);
2960
2961                 if (level != 0) {
2962                         int dec = 0;
2963                         if (ret && slot > 0) {
2964                                 dec = 1;
2965                                 slot -= 1;
2966                         }
2967                         p->slots[level] = slot;
2968                         unlock_up(p, level, lowest_unlock, 0, NULL);
2969
2970                         if (level == lowest_level) {
2971                                 if (dec)
2972                                         p->slots[level]++;
2973                                 goto done;
2974                         }
2975
2976                         err = read_block_for_search(root, p, &b, level,
2977                                                     slot, key);
2978                         if (err == -EAGAIN)
2979                                 goto again;
2980                         if (err) {
2981                                 ret = err;
2982                                 goto done;
2983                         }
2984
2985                         level = btrfs_header_level(b);
2986                         err = btrfs_tree_read_lock_atomic(b);
2987                         if (!err) {
2988                                 btrfs_set_path_blocking(p);
2989                                 btrfs_tree_read_lock(b);
2990                                 btrfs_clear_path_blocking(p, b,
2991                                                           BTRFS_READ_LOCK);
2992                         }
2993                         b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2994                         if (!b) {
2995                                 ret = -ENOMEM;
2996                                 goto done;
2997                         }
2998                         p->locks[level] = BTRFS_READ_LOCK;
2999                         p->nodes[level] = b;
3000                 } else {
3001                         p->slots[level] = slot;
3002                         unlock_up(p, level, lowest_unlock, 0, NULL);
3003                         goto done;
3004                 }
3005         }
3006         ret = 1;
3007 done:
3008         if (!p->leave_spinning)
3009                 btrfs_set_path_blocking(p);
3010         if (ret < 0)
3011                 btrfs_release_path(p);
3012
3013         return ret;
3014 }
3015
3016 /*
3017  * helper to use instead of search slot if no exact match is needed but
3018  * instead the next or previous item should be returned.
3019  * When find_higher is true, the next higher item is returned, the next lower
3020  * otherwise.
3021  * When return_any and find_higher are both true, and no higher item is found,
3022  * return the next lower instead.
3023  * When return_any is true and find_higher is false, and no lower item is found,
3024  * return the next higher instead.
3025  * It returns 0 if any item is found, 1 if none is found (tree empty), and
3026  * < 0 on error
3027  */
3028 int btrfs_search_slot_for_read(struct btrfs_root *root,
3029                                const struct btrfs_key *key,
3030                                struct btrfs_path *p, int find_higher,
3031                                int return_any)
3032 {
3033         int ret;
3034         struct extent_buffer *leaf;
3035
3036 again:
3037         ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3038         if (ret <= 0)
3039                 return ret;
3040         /*
3041          * a return value of 1 means the path is at the position where the
3042          * item should be inserted. Normally this is the next bigger item,
3043          * but in case the previous item is the last in a leaf, path points
3044          * to the first free slot in the previous leaf, i.e. at an invalid
3045          * item.
3046          */
3047         leaf = p->nodes[0];
3048
3049         if (find_higher) {
3050                 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3051                         ret = btrfs_next_leaf(root, p);
3052                         if (ret <= 0)
3053                                 return ret;
3054                         if (!return_any)
3055                                 return 1;
3056                         /*
3057                          * no higher item found, return the next
3058                          * lower instead
3059                          */
3060                         return_any = 0;
3061                         find_higher = 0;
3062                         btrfs_release_path(p);
3063                         goto again;
3064                 }
3065         } else {
3066                 if (p->slots[0] == 0) {
3067                         ret = btrfs_prev_leaf(root, p);
3068                         if (ret < 0)
3069                                 return ret;
3070                         if (!ret) {
3071                                 leaf = p->nodes[0];
3072                                 if (p->slots[0] == btrfs_header_nritems(leaf))
3073                                         p->slots[0]--;
3074                                 return 0;
3075                         }
3076                         if (!return_any)
3077                                 return 1;
3078                         /*
3079                          * no lower item found, return the next
3080                          * higher instead
3081                          */
3082                         return_any = 0;
3083                         find_higher = 1;
3084                         btrfs_release_path(p);
3085                         goto again;
3086                 } else {
3087                         --p->slots[0];
3088                 }
3089         }
3090         return 0;
3091 }
3092
3093 /*
3094  * adjust the pointers going up the tree, starting at level
3095  * making sure the right key of each node is points to 'key'.
3096  * This is used after shifting pointers to the left, so it stops
3097  * fixing up pointers when a given leaf/node is not in slot 0 of the
3098  * higher levels
3099  *
3100  */
3101 static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3102                            struct btrfs_path *path,
3103                            struct btrfs_disk_key *key, int level)
3104 {
3105         int i;
3106         struct extent_buffer *t;
3107         int ret;
3108
3109         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3110                 int tslot = path->slots[i];
3111
3112                 if (!path->nodes[i])
3113                         break;
3114                 t = path->nodes[i];
3115                 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3116                                 GFP_ATOMIC);
3117                 BUG_ON(ret < 0);
3118                 btrfs_set_node_key(t, key, tslot);
3119                 btrfs_mark_buffer_dirty(path->nodes[i]);
3120                 if (tslot != 0)
3121                         break;
3122         }
3123 }
3124
3125 /*
3126  * update item key.
3127  *
3128  * This function isn't completely safe. It's the caller's responsibility
3129  * that the new key won't break the order
3130  */
3131 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3132                 &n