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