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