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