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