OSDN Git Service

Btrfs: fix use-after-free when using the tree modification log
[sagit-ice-cold/kernel_xiaomi_msm8998.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 "ctree.h"
23 #include "disk-io.h"
24 #include "transaction.h"
25 #include "print-tree.h"
26 #include "locking.h"
27
28 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
29                       *root, struct btrfs_path *path, int level);
30 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
31                       *root, struct btrfs_key *ins_key,
32                       struct btrfs_path *path, int data_size, int extend);
33 static int push_node_left(struct btrfs_trans_handle *trans,
34                           struct btrfs_root *root, struct extent_buffer *dst,
35                           struct extent_buffer *src, int empty);
36 static int balance_node_right(struct btrfs_trans_handle *trans,
37                               struct btrfs_root *root,
38                               struct extent_buffer *dst_buf,
39                               struct extent_buffer *src_buf);
40 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41                     int level, int slot);
42 static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
43                                  struct extent_buffer *eb);
44
45 struct btrfs_path *btrfs_alloc_path(void)
46 {
47         struct btrfs_path *path;
48         path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
49         return path;
50 }
51
52 /*
53  * set all locked nodes in the path to blocking locks.  This should
54  * be done before scheduling
55  */
56 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
57 {
58         int i;
59         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
60                 if (!p->nodes[i] || !p->locks[i])
61                         continue;
62                 btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
63                 if (p->locks[i] == BTRFS_READ_LOCK)
64                         p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
65                 else if (p->locks[i] == BTRFS_WRITE_LOCK)
66                         p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
67         }
68 }
69
70 /*
71  * reset all the locked nodes in the patch to spinning locks.
72  *
73  * held is used to keep lockdep happy, when lockdep is enabled
74  * we set held to a blocking lock before we go around and
75  * retake all the spinlocks in the path.  You can safely use NULL
76  * for held
77  */
78 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
79                                         struct extent_buffer *held, int held_rw)
80 {
81         int i;
82
83         if (held) {
84                 btrfs_set_lock_blocking_rw(held, held_rw);
85                 if (held_rw == BTRFS_WRITE_LOCK)
86                         held_rw = BTRFS_WRITE_LOCK_BLOCKING;
87                 else if (held_rw == BTRFS_READ_LOCK)
88                         held_rw = BTRFS_READ_LOCK_BLOCKING;
89         }
90         btrfs_set_path_blocking(p);
91
92         for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
93                 if (p->nodes[i] && p->locks[i]) {
94                         btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
95                         if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
96                                 p->locks[i] = BTRFS_WRITE_LOCK;
97                         else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
98                                 p->locks[i] = BTRFS_READ_LOCK;
99                 }
100         }
101
102         if (held)
103                 btrfs_clear_lock_blocking_rw(held, held_rw);
104 }
105
106 /* this also releases the path */
107 void btrfs_free_path(struct btrfs_path *p)
108 {
109         if (!p)
110                 return;
111         btrfs_release_path(p);
112         kmem_cache_free(btrfs_path_cachep, p);
113 }
114
115 /*
116  * path release drops references on the extent buffers in the path
117  * and it drops any locks held by this path
118  *
119  * It is safe to call this on paths that no locks or extent buffers held.
120  */
121 noinline void btrfs_release_path(struct btrfs_path *p)
122 {
123         int i;
124
125         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
126                 p->slots[i] = 0;
127                 if (!p->nodes[i])
128                         continue;
129                 if (p->locks[i]) {
130                         btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
131                         p->locks[i] = 0;
132                 }
133                 free_extent_buffer(p->nodes[i]);
134                 p->nodes[i] = NULL;
135         }
136 }
137
138 /*
139  * safely gets a reference on the root node of a tree.  A lock
140  * is not taken, so a concurrent writer may put a different node
141  * at the root of the tree.  See btrfs_lock_root_node for the
142  * looping required.
143  *
144  * The extent buffer returned by this has a reference taken, so
145  * it won't disappear.  It may stop being the root of the tree
146  * at any time because there are no locks held.
147  */
148 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
149 {
150         struct extent_buffer *eb;
151
152         while (1) {
153                 rcu_read_lock();
154                 eb = rcu_dereference(root->node);
155
156                 /*
157                  * RCU really hurts here, we could free up the root node because
158                  * it was cow'ed but we may not get the new root node yet so do
159                  * the inc_not_zero dance and if it doesn't work then
160                  * synchronize_rcu and try again.
161                  */
162                 if (atomic_inc_not_zero(&eb->refs)) {
163                         rcu_read_unlock();
164                         break;
165                 }
166                 rcu_read_unlock();
167                 synchronize_rcu();
168         }
169         return eb;
170 }
171
172 /* loop around taking references on and locking the root node of the
173  * tree until you end up with a lock on the root.  A locked buffer
174  * is returned, with a reference held.
175  */
176 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
177 {
178         struct extent_buffer *eb;
179
180         while (1) {
181                 eb = btrfs_root_node(root);
182                 btrfs_tree_lock(eb);
183                 if (eb == root->node)
184                         break;
185                 btrfs_tree_unlock(eb);
186                 free_extent_buffer(eb);
187         }
188         return eb;
189 }
190
191 /* loop around taking references on and locking the root node of the
192  * tree until you end up with a lock on the root.  A locked buffer
193  * is returned, with a reference held.
194  */
195 static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
196 {
197         struct extent_buffer *eb;
198
199         while (1) {
200                 eb = btrfs_root_node(root);
201                 btrfs_tree_read_lock(eb);
202                 if (eb == root->node)
203                         break;
204                 btrfs_tree_read_unlock(eb);
205                 free_extent_buffer(eb);
206         }
207         return eb;
208 }
209
210 /* cowonly root (everything not a reference counted cow subvolume), just get
211  * put onto a simple dirty list.  transaction.c walks this to make sure they
212  * get properly updated on disk.
213  */
214 static void add_root_to_dirty_list(struct btrfs_root *root)
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(&root->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                                        &root->fs_info->dirty_cowonly_roots);
226                 else
227                         list_move(&root->dirty_list,
228                                   &root->fs_info->dirty_cowonly_roots);
229         }
230         spin_unlock(&root->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 extent_buffer *cow;
244         int ret = 0;
245         int level;
246         struct btrfs_disk_key disk_key;
247
248         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
249                 trans->transid != root->fs_info->running_transaction->transid);
250         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
251                 trans->transid != root->last_trans);
252
253         level = btrfs_header_level(buf);
254         if (level == 0)
255                 btrfs_item_key(buf, &disk_key, 0);
256         else
257                 btrfs_node_key(buf, &disk_key, 0);
258
259         cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
260                         &disk_key, level, buf->start, 0);
261         if (IS_ERR(cow))
262                 return PTR_ERR(cow);
263
264         copy_extent_buffer(cow, buf, 0, 0, cow->len);
265         btrfs_set_header_bytenr(cow, cow->start);
266         btrfs_set_header_generation(cow, trans->transid);
267         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
268         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
269                                      BTRFS_HEADER_FLAG_RELOC);
270         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
271                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
272         else
273                 btrfs_set_header_owner(cow, new_root_objectid);
274
275         write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
276                             BTRFS_FSID_SIZE);
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_move {
303         int dst_slot;
304         int nr_items;
305 };
306
307 struct tree_mod_root {
308         u64 logical;
309         u8 level;
310 };
311
312 struct tree_mod_elem {
313         struct rb_node node;
314         u64 index;              /* shifted logical */
315         u64 seq;
316         enum mod_log_op op;
317
318         /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
319         int slot;
320
321         /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
322         u64 generation;
323
324         /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
325         struct btrfs_disk_key key;
326         u64 blockptr;
327
328         /* this is used for op == MOD_LOG_MOVE_KEYS */
329         struct tree_mod_move move;
330
331         /* this is used for op == MOD_LOG_ROOT_REPLACE */
332         struct tree_mod_root old_root;
333 };
334
335 static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
336 {
337         read_lock(&fs_info->tree_mod_log_lock);
338 }
339
340 static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
341 {
342         read_unlock(&fs_info->tree_mod_log_lock);
343 }
344
345 static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
346 {
347         write_lock(&fs_info->tree_mod_log_lock);
348 }
349
350 static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
351 {
352         write_unlock(&fs_info->tree_mod_log_lock);
353 }
354
355 /*
356  * Pull a new tree mod seq number for our operation.
357  */
358 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
359 {
360         return atomic64_inc_return(&fs_info->tree_mod_seq);
361 }
362
363 /*
364  * This adds a new blocker to the tree mod log's blocker list if the @elem
365  * passed does not already have a sequence number set. So when a caller expects
366  * to record tree modifications, it should ensure to set elem->seq to zero
367  * before calling btrfs_get_tree_mod_seq.
368  * Returns a fresh, unused tree log modification sequence number, even if no new
369  * blocker was added.
370  */
371 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
372                            struct seq_list *elem)
373 {
374         tree_mod_log_write_lock(fs_info);
375         spin_lock(&fs_info->tree_mod_seq_lock);
376         if (!elem->seq) {
377                 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
378                 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
379         }
380         spin_unlock(&fs_info->tree_mod_seq_lock);
381         tree_mod_log_write_unlock(fs_info);
382
383         return elem->seq;
384 }
385
386 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
387                             struct seq_list *elem)
388 {
389         struct rb_root *tm_root;
390         struct rb_node *node;
391         struct rb_node *next;
392         struct seq_list *cur_elem;
393         struct tree_mod_elem *tm;
394         u64 min_seq = (u64)-1;
395         u64 seq_putting = elem->seq;
396
397         if (!seq_putting)
398                 return;
399
400         spin_lock(&fs_info->tree_mod_seq_lock);
401         list_del(&elem->list);
402         elem->seq = 0;
403
404         list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
405                 if (cur_elem->seq < min_seq) {
406                         if (seq_putting > cur_elem->seq) {
407                                 /*
408                                  * blocker with lower sequence number exists, we
409                                  * cannot remove anything from the log
410                                  */
411                                 spin_unlock(&fs_info->tree_mod_seq_lock);
412                                 return;
413                         }
414                         min_seq = cur_elem->seq;
415                 }
416         }
417         spin_unlock(&fs_info->tree_mod_seq_lock);
418
419         /*
420          * anything that's lower than the lowest existing (read: blocked)
421          * sequence number can be removed from the tree.
422          */
423         tree_mod_log_write_lock(fs_info);
424         tm_root = &fs_info->tree_mod_log;
425         for (node = rb_first(tm_root); node; node = next) {
426                 next = rb_next(node);
427                 tm = container_of(node, struct tree_mod_elem, node);
428                 if (tm->seq > min_seq)
429                         continue;
430                 rb_erase(node, tm_root);
431                 kfree(tm);
432         }
433         tree_mod_log_write_unlock(fs_info);
434 }
435
436 /*
437  * key order of the log:
438  *       index -> sequence
439  *
440  * the index is the shifted logical of the *new* root node for root replace
441  * operations, or the shifted logical of the affected block for all other
442  * operations.
443  *
444  * Note: must be called with write lock (tree_mod_log_write_lock).
445  */
446 static noinline int
447 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
448 {
449         struct rb_root *tm_root;
450         struct rb_node **new;
451         struct rb_node *parent = NULL;
452         struct tree_mod_elem *cur;
453
454         BUG_ON(!tm);
455
456         tm->seq = btrfs_inc_tree_mod_seq(fs_info);
457
458         tm_root = &fs_info->tree_mod_log;
459         new = &tm_root->rb_node;
460         while (*new) {
461                 cur = container_of(*new, struct tree_mod_elem, node);
462                 parent = *new;
463                 if (cur->index < tm->index)
464                         new = &((*new)->rb_left);
465                 else if (cur->index > tm->index)
466                         new = &((*new)->rb_right);
467                 else if (cur->seq < tm->seq)
468                         new = &((*new)->rb_left);
469                 else if (cur->seq > tm->seq)
470                         new = &((*new)->rb_right);
471                 else
472                         return -EEXIST;
473         }
474
475         rb_link_node(&tm->node, parent, new);
476         rb_insert_color(&tm->node, tm_root);
477         return 0;
478 }
479
480 /*
481  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
482  * returns zero with the tree_mod_log_lock acquired. The caller must hold
483  * this until all tree mod log insertions are recorded in the rb tree and then
484  * call tree_mod_log_write_unlock() to release.
485  */
486 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
487                                     struct extent_buffer *eb) {
488         smp_mb();
489         if (list_empty(&(fs_info)->tree_mod_seq_list))
490                 return 1;
491         if (eb && btrfs_header_level(eb) == 0)
492                 return 1;
493
494         tree_mod_log_write_lock(fs_info);
495         if (list_empty(&(fs_info)->tree_mod_seq_list)) {
496                 tree_mod_log_write_unlock(fs_info);
497                 return 1;
498         }
499
500         return 0;
501 }
502
503 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
504 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
505                                     struct extent_buffer *eb)
506 {
507         smp_mb();
508         if (list_empty(&(fs_info)->tree_mod_seq_list))
509                 return 0;
510         if (eb && btrfs_header_level(eb) == 0)
511                 return 0;
512
513         return 1;
514 }
515
516 static struct tree_mod_elem *
517 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
518                     enum mod_log_op op, gfp_t flags)
519 {
520         struct tree_mod_elem *tm;
521
522         tm = kzalloc(sizeof(*tm), flags);
523         if (!tm)
524                 return NULL;
525
526         tm->index = eb->start >> PAGE_CACHE_SHIFT;
527         if (op != MOD_LOG_KEY_ADD) {
528                 btrfs_node_key(eb, &tm->key, slot);
529                 tm->blockptr = btrfs_node_blockptr(eb, slot);
530         }
531         tm->op = op;
532         tm->slot = slot;
533         tm->generation = btrfs_node_ptr_generation(eb, slot);
534         RB_CLEAR_NODE(&tm->node);
535
536         return tm;
537 }
538
539 static noinline int
540 tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
541                         struct extent_buffer *eb, int slot,
542                         enum mod_log_op op, gfp_t flags)
543 {
544         struct tree_mod_elem *tm;
545         int ret;
546
547         if (!tree_mod_need_log(fs_info, eb))
548                 return 0;
549
550         tm = alloc_tree_mod_elem(eb, slot, op, flags);
551         if (!tm)
552                 return -ENOMEM;
553
554         if (tree_mod_dont_log(fs_info, eb)) {
555                 kfree(tm);
556                 return 0;
557         }
558
559         ret = __tree_mod_log_insert(fs_info, tm);
560         tree_mod_log_write_unlock(fs_info);
561         if (ret)
562                 kfree(tm);
563
564         return ret;
565 }
566
567 static noinline int
568 tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
569                          struct extent_buffer *eb, int dst_slot, int src_slot,
570                          int nr_items, gfp_t flags)
571 {
572         struct tree_mod_elem *tm = NULL;
573         struct tree_mod_elem **tm_list = NULL;
574         int ret = 0;
575         int i;
576         int locked = 0;
577
578         if (!tree_mod_need_log(fs_info, eb))
579                 return 0;
580
581         tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), flags);
582         if (!tm_list)
583                 return -ENOMEM;
584
585         tm = kzalloc(sizeof(*tm), flags);
586         if (!tm) {
587                 ret = -ENOMEM;
588                 goto free_tms;
589         }
590
591         tm->index = eb->start >> PAGE_CACHE_SHIFT;
592         tm->slot = src_slot;
593         tm->move.dst_slot = dst_slot;
594         tm->move.nr_items = nr_items;
595         tm->op = MOD_LOG_MOVE_KEYS;
596
597         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
598                 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
599                     MOD_LOG_KEY_REMOVE_WHILE_MOVING, flags);
600                 if (!tm_list[i]) {
601                         ret = -ENOMEM;
602                         goto free_tms;
603                 }
604         }
605
606         if (tree_mod_dont_log(fs_info, eb))
607                 goto free_tms;
608         locked = 1;
609
610         /*
611          * When we override something during the move, we log these removals.
612          * This can only happen when we move towards the beginning of the
613          * buffer, i.e. dst_slot < src_slot.
614          */
615         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
616                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
617                 if (ret)
618                         goto free_tms;
619         }
620
621         ret = __tree_mod_log_insert(fs_info, tm);
622         if (ret)
623                 goto free_tms;
624         tree_mod_log_write_unlock(fs_info);
625         kfree(tm_list);
626
627         return 0;
628 free_tms:
629         for (i = 0; i < nr_items; i++) {
630                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
631                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
632                 kfree(tm_list[i]);
633         }
634         if (locked)
635                 tree_mod_log_write_unlock(fs_info);
636         kfree(tm_list);
637         kfree(tm);
638
639         return ret;
640 }
641
642 static inline int
643 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
644                        struct tree_mod_elem **tm_list,
645                        int nritems)
646 {
647         int i, j;
648         int ret;
649
650         for (i = nritems - 1; i >= 0; i--) {
651                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
652                 if (ret) {
653                         for (j = nritems - 1; j > i; j--)
654                                 rb_erase(&tm_list[j]->node,
655                                          &fs_info->tree_mod_log);
656                         return ret;
657                 }
658         }
659
660         return 0;
661 }
662
663 static noinline int
664 tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
665                          struct extent_buffer *old_root,
666                          struct extent_buffer *new_root, gfp_t flags,
667                          int log_removal)
668 {
669         struct tree_mod_elem *tm = NULL;
670         struct tree_mod_elem **tm_list = NULL;
671         int nritems = 0;
672         int ret = 0;
673         int i;
674
675         if (!tree_mod_need_log(fs_info, NULL))
676                 return 0;
677
678         if (log_removal && btrfs_header_level(old_root) > 0) {
679                 nritems = btrfs_header_nritems(old_root);
680                 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
681                                   flags);
682                 if (!tm_list) {
683                         ret = -ENOMEM;
684                         goto free_tms;
685                 }
686                 for (i = 0; i < nritems; i++) {
687                         tm_list[i] = alloc_tree_mod_elem(old_root, i,
688                             MOD_LOG_KEY_REMOVE_WHILE_FREEING, flags);
689                         if (!tm_list[i]) {
690                                 ret = -ENOMEM;
691                                 goto free_tms;
692                         }
693                 }
694         }
695
696         tm = kzalloc(sizeof(*tm), flags);
697         if (!tm) {
698                 ret = -ENOMEM;
699                 goto free_tms;
700         }
701
702         tm->index = new_root->start >> PAGE_CACHE_SHIFT;
703         tm->old_root.logical = old_root->start;
704         tm->old_root.level = btrfs_header_level(old_root);
705         tm->generation = btrfs_header_generation(old_root);
706         tm->op = MOD_LOG_ROOT_REPLACE;
707
708         if (tree_mod_dont_log(fs_info, NULL))
709                 goto free_tms;
710
711         if (tm_list)
712                 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
713         if (!ret)
714                 ret = __tree_mod_log_insert(fs_info, tm);
715
716         tree_mod_log_write_unlock(fs_info);
717         if (ret)
718                 goto free_tms;
719         kfree(tm_list);
720
721         return ret;
722
723 free_tms:
724         if (tm_list) {
725                 for (i = 0; i < nritems; i++)
726                         kfree(tm_list[i]);
727                 kfree(tm_list);
728         }
729         kfree(tm);
730
731         return ret;
732 }
733
734 static struct tree_mod_elem *
735 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
736                       int smallest)
737 {
738         struct rb_root *tm_root;
739         struct rb_node *node;
740         struct tree_mod_elem *cur = NULL;
741         struct tree_mod_elem *found = NULL;
742         u64 index = start >> PAGE_CACHE_SHIFT;
743
744         tree_mod_log_read_lock(fs_info);
745         tm_root = &fs_info->tree_mod_log;
746         node = tm_root->rb_node;
747         while (node) {
748                 cur = container_of(node, struct tree_mod_elem, node);
749                 if (cur->index < index) {
750                         node = node->rb_left;
751                 } else if (cur->index > index) {
752                         node = node->rb_right;
753                 } else if (cur->seq < min_seq) {
754                         node = node->rb_left;
755                 } else if (!smallest) {
756                         /* we want the node with the highest seq */
757                         if (found)
758                                 BUG_ON(found->seq > cur->seq);
759                         found = cur;
760                         node = node->rb_left;
761                 } else if (cur->seq > min_seq) {
762                         /* we want the node with the smallest seq */
763                         if (found)
764                                 BUG_ON(found->seq < cur->seq);
765                         found = cur;
766                         node = node->rb_right;
767                 } else {
768                         found = cur;
769                         break;
770                 }
771         }
772         tree_mod_log_read_unlock(fs_info);
773
774         return found;
775 }
776
777 /*
778  * this returns the element from the log with the smallest time sequence
779  * value that's in the log (the oldest log item). any element with a time
780  * sequence lower than min_seq will be ignored.
781  */
782 static struct tree_mod_elem *
783 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
784                            u64 min_seq)
785 {
786         return __tree_mod_log_search(fs_info, start, min_seq, 1);
787 }
788
789 /*
790  * this returns the element from the log with the largest time sequence
791  * value that's in the log (the most recent log item). any element with
792  * a time sequence lower than min_seq will be ignored.
793  */
794 static struct tree_mod_elem *
795 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
796 {
797         return __tree_mod_log_search(fs_info, start, min_seq, 0);
798 }
799
800 static noinline int
801 tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
802                      struct extent_buffer *src, unsigned long dst_offset,
803                      unsigned long src_offset, int nr_items)
804 {
805         int ret = 0;
806         struct tree_mod_elem **tm_list = NULL;
807         struct tree_mod_elem **tm_list_add, **tm_list_rem;
808         int i;
809         int locked = 0;
810
811         if (!tree_mod_need_log(fs_info, NULL))
812                 return 0;
813
814         if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
815                 return 0;
816
817         tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
818                           GFP_NOFS);
819         if (!tm_list)
820                 return -ENOMEM;
821
822         tm_list_add = tm_list;
823         tm_list_rem = tm_list + nr_items;
824         for (i = 0; i < nr_items; i++) {
825                 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
826                     MOD_LOG_KEY_REMOVE, GFP_NOFS);
827                 if (!tm_list_rem[i]) {
828                         ret = -ENOMEM;
829                         goto free_tms;
830                 }
831
832                 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
833                     MOD_LOG_KEY_ADD, GFP_NOFS);
834                 if (!tm_list_add[i]) {
835                         ret = -ENOMEM;
836                         goto free_tms;
837                 }
838         }
839
840         if (tree_mod_dont_log(fs_info, NULL))
841                 goto free_tms;
842         locked = 1;
843
844         for (i = 0; i < nr_items; i++) {
845                 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
846                 if (ret)
847                         goto free_tms;
848                 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
849                 if (ret)
850                         goto free_tms;
851         }
852
853         tree_mod_log_write_unlock(fs_info);
854         kfree(tm_list);
855
856         return 0;
857
858 free_tms:
859         for (i = 0; i < nr_items * 2; i++) {
860                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
861                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
862                 kfree(tm_list[i]);
863         }
864         if (locked)
865                 tree_mod_log_write_unlock(fs_info);
866         kfree(tm_list);
867
868         return ret;
869 }
870
871 static inline void
872 tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
873                      int dst_offset, int src_offset, int nr_items)
874 {
875         int ret;
876         ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
877                                        nr_items, GFP_NOFS);
878         BUG_ON(ret < 0);
879 }
880
881 static noinline void
882 tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
883                           struct extent_buffer *eb, int slot, int atomic)
884 {
885         int ret;
886
887         ret = tree_mod_log_insert_key(fs_info, eb, slot,
888                                         MOD_LOG_KEY_REPLACE,
889                                         atomic ? GFP_ATOMIC : GFP_NOFS);
890         BUG_ON(ret < 0);
891 }
892
893 static noinline int
894 tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
895 {
896         struct tree_mod_elem **tm_list = NULL;
897         int nritems = 0;
898         int i;
899         int ret = 0;
900
901         if (btrfs_header_level(eb) == 0)
902                 return 0;
903
904         if (!tree_mod_need_log(fs_info, NULL))
905                 return 0;
906
907         nritems = btrfs_header_nritems(eb);
908         tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
909         if (!tm_list)
910                 return -ENOMEM;
911
912         for (i = 0; i < nritems; i++) {
913                 tm_list[i] = alloc_tree_mod_elem(eb, i,
914                     MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
915                 if (!tm_list[i]) {
916                         ret = -ENOMEM;
917                         goto free_tms;
918                 }
919         }
920
921         if (tree_mod_dont_log(fs_info, eb))
922                 goto free_tms;
923
924         ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
925         tree_mod_log_write_unlock(fs_info);
926         if (ret)
927                 goto free_tms;
928         kfree(tm_list);
929
930         return 0;
931
932 free_tms:
933         for (i = 0; i < nritems; i++)
934                 kfree(tm_list[i]);
935         kfree(tm_list);
936
937         return ret;
938 }
939
940 static noinline void
941 tree_mod_log_set_root_pointer(struct btrfs_root *root,
942                               struct extent_buffer *new_root_node,
943                               int log_removal)
944 {
945         int ret;
946         ret = tree_mod_log_insert_root(root->fs_info, root->node,
947                                        new_root_node, GFP_NOFS, log_removal);
948         BUG_ON(ret < 0);
949 }
950
951 /*
952  * check if the tree block can be shared by multiple trees
953  */
954 int btrfs_block_can_be_shared(struct btrfs_root *root,
955                               struct extent_buffer *buf)
956 {
957         /*
958          * Tree blocks not in refernece counted trees and tree roots
959          * are never shared. If a block was allocated after the last
960          * snapshot and the block was not allocated by tree relocation,
961          * we know the block is not shared.
962          */
963         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
964             buf != root->node && buf != root->commit_root &&
965             (btrfs_header_generation(buf) <=
966              btrfs_root_last_snapshot(&root->root_item) ||
967              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
968                 return 1;
969 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
970         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
971             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
972                 return 1;
973 #endif
974         return 0;
975 }
976
977 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
978                                        struct btrfs_root *root,
979                                        struct extent_buffer *buf,
980                                        struct extent_buffer *cow,
981                                        int *last_ref)
982 {
983         u64 refs;
984         u64 owner;
985         u64 flags;
986         u64 new_flags = 0;
987         int ret;
988
989         /*
990          * Backrefs update rules:
991          *
992          * Always use full backrefs for extent pointers in tree block
993          * allocated by tree relocation.
994          *
995          * If a shared tree block is no longer referenced by its owner
996          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
997          * use full backrefs for extent pointers in tree block.
998          *
999          * If a tree block is been relocating
1000          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
1001          * use full backrefs for extent pointers in tree block.
1002          * The reason for this is some operations (such as drop tree)
1003          * are only allowed for blocks use full backrefs.
1004          */
1005
1006         if (btrfs_block_can_be_shared(root, buf)) {
1007                 ret = btrfs_lookup_extent_info(trans, root, buf->start,
1008                                                btrfs_header_level(buf), 1,
1009                                                &refs, &flags);
1010                 if (ret)
1011                         return ret;
1012                 if (refs == 0) {
1013                         ret = -EROFS;
1014                         btrfs_std_error(root->fs_info, ret, NULL);
1015                         return ret;
1016                 }
1017         } else {
1018                 refs = 1;
1019                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1020                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1021                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
1022                 else
1023                         flags = 0;
1024         }
1025
1026         owner = btrfs_header_owner(buf);
1027         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
1028                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
1029
1030         if (refs > 1) {
1031                 if ((owner == root->root_key.objectid ||
1032                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
1033                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1034                         ret = btrfs_inc_ref(trans, root, buf, 1);
1035                         BUG_ON(ret); /* -ENOMEM */
1036
1037                         if (root->root_key.objectid ==
1038                             BTRFS_TREE_RELOC_OBJECTID) {
1039                                 ret = btrfs_dec_ref(trans, root, buf, 0);
1040                                 BUG_ON(ret); /* -ENOMEM */
1041                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1042                                 BUG_ON(ret); /* -ENOMEM */
1043                         }
1044                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
1045                 } else {
1046
1047                         if (root->root_key.objectid ==
1048                             BTRFS_TREE_RELOC_OBJECTID)
1049                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1050                         else
1051                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1052                         BUG_ON(ret); /* -ENOMEM */
1053                 }
1054                 if (new_flags != 0) {
1055                         int level = btrfs_header_level(buf);
1056
1057                         ret = btrfs_set_disk_extent_flags(trans, root,
1058                                                           buf->start,
1059                                                           buf->len,
1060                                                           new_flags, level, 0);
1061                         if (ret)
1062                                 return ret;
1063                 }
1064         } else {
1065                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
1066                         if (root->root_key.objectid ==
1067                             BTRFS_TREE_RELOC_OBJECTID)
1068                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1069                         else
1070                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1071                         BUG_ON(ret); /* -ENOMEM */
1072                         ret = btrfs_dec_ref(trans, root, buf, 1);
1073                         BUG_ON(ret); /* -ENOMEM */
1074                 }
1075                 clean_tree_block(trans, root->fs_info, buf);
1076                 *last_ref = 1;
1077         }
1078         return 0;
1079 }
1080
1081 /*
1082  * does the dirty work in cow of a single block.  The parent block (if
1083  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1084  * dirty and returned locked.  If you modify the block it needs to be marked
1085  * dirty again.
1086  *
1087  * search_start -- an allocation hint for the new block
1088  *
1089  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1090  * bytes the allocator should try to find free next to the block it returns.
1091  * This is just a hint and may be ignored by the allocator.
1092  */
1093 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1094                              struct btrfs_root *root,
1095                              struct extent_buffer *buf,
1096                              struct extent_buffer *parent, int parent_slot,
1097                              struct extent_buffer **cow_ret,
1098                              u64 search_start, u64 empty_size)
1099 {
1100         struct btrfs_disk_key disk_key;
1101         struct extent_buffer *cow;
1102         int level, ret;
1103         int last_ref = 0;
1104         int unlock_orig = 0;
1105         u64 parent_start;
1106
1107         if (*cow_ret == buf)
1108                 unlock_orig = 1;
1109
1110         btrfs_assert_tree_locked(buf);
1111
1112         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1113                 trans->transid != root->fs_info->running_transaction->transid);
1114         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1115                 trans->transid != root->last_trans);
1116
1117         level = btrfs_header_level(buf);
1118
1119         if (level == 0)
1120                 btrfs_item_key(buf, &disk_key, 0);
1121         else
1122                 btrfs_node_key(buf, &disk_key, 0);
1123
1124         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
1125                 if (parent)
1126                         parent_start = parent->start;
1127                 else
1128                         parent_start = 0;
1129         } else
1130                 parent_start = 0;
1131
1132         cow = btrfs_alloc_tree_block(trans, root, parent_start,
1133                         root->root_key.objectid, &disk_key, level,
1134                         search_start, empty_size);
1135         if (IS_ERR(cow))
1136                 return PTR_ERR(cow);
1137
1138         /* cow is set to blocking by btrfs_init_new_buffer */
1139
1140         copy_extent_buffer(cow, buf, 0, 0, cow->len);
1141         btrfs_set_header_bytenr(cow, cow->start);
1142         btrfs_set_header_generation(cow, trans->transid);
1143         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1144         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1145                                      BTRFS_HEADER_FLAG_RELOC);
1146         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1147                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1148         else
1149                 btrfs_set_header_owner(cow, root->root_key.objectid);
1150
1151         write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
1152                             BTRFS_FSID_SIZE);
1153
1154         ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1155         if (ret) {
1156                 btrfs_abort_transaction(trans, root, ret);
1157                 return ret;
1158         }
1159
1160         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1161                 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1162                 if (ret) {
1163                         btrfs_abort_transaction(trans, root, ret);
1164                         return ret;
1165                 }
1166         }
1167
1168         if (buf == root->node) {
1169                 WARN_ON(parent && parent != buf);
1170                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1171                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1172                         parent_start = buf->start;
1173                 else
1174                         parent_start = 0;
1175
1176                 extent_buffer_get(cow);
1177                 tree_mod_log_set_root_pointer(root, cow, 1);
1178                 rcu_assign_pointer(root->node, cow);
1179
1180                 btrfs_free_tree_block(trans, root, buf, parent_start,
1181                                       last_ref);
1182                 free_extent_buffer(buf);
1183                 add_root_to_dirty_list(root);
1184         } else {
1185                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1186                         parent_start = parent->start;
1187                 else
1188                         parent_start = 0;
1189
1190                 WARN_ON(trans->transid != btrfs_header_generation(parent));
1191                 tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1192                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1193                 btrfs_set_node_blockptr(parent, parent_slot,
1194                                         cow->start);
1195                 btrfs_set_node_ptr_generation(parent, parent_slot,
1196                                               trans->transid);
1197                 btrfs_mark_buffer_dirty(parent);
1198                 if (last_ref) {
1199                         ret = tree_mod_log_free_eb(root->fs_info, buf);
1200                         if (ret) {
1201                                 btrfs_abort_transaction(trans, root, ret);
1202                                 return ret;
1203                         }
1204                 }
1205                 btrfs_free_tree_block(trans, root, buf, parent_start,
1206                                       last_ref);
1207         }
1208         if (unlock_orig)
1209                 btrfs_tree_unlock(buf);
1210         free_extent_buffer_stale(buf);
1211         btrfs_mark_buffer_dirty(cow);
1212         *cow_ret = cow;
1213         return 0;
1214 }
1215
1216 /*
1217  * returns the logical address of the oldest predecessor of the given root.
1218  * entries older than time_seq are ignored.
1219  */
1220 static struct tree_mod_elem *
1221 __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
1222                            struct extent_buffer *eb_root, u64 time_seq)
1223 {
1224         struct tree_mod_elem *tm;
1225         struct tree_mod_elem *found = NULL;
1226         u64 root_logical = eb_root->start;
1227         int looped = 0;
1228
1229         if (!time_seq)
1230                 return NULL;
1231
1232         /*
1233          * the very last operation that's logged for a root is the replacement
1234          * operation (if it is replaced at all). this has the index of the *new*
1235          * root, making it the very first operation that's logged for this root.
1236          */
1237         while (1) {
1238                 tm = tree_mod_log_search_oldest(fs_info, root_logical,
1239                                                 time_seq);
1240                 if (!looped && !tm)
1241                         return NULL;
1242                 /*
1243                  * if there are no tree operation for the oldest root, we simply
1244                  * return it. this should only happen if that (old) root is at
1245                  * level 0.
1246                  */
1247                 if (!tm)
1248                         break;
1249
1250                 /*
1251                  * if there's an operation that's not a root replacement, we
1252                  * found the oldest version of our root. normally, we'll find a
1253                  * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1254                  */
1255                 if (tm->op != MOD_LOG_ROOT_REPLACE)
1256                         break;
1257
1258                 found = tm;
1259                 root_logical = tm->old_root.logical;
1260                 looped = 1;
1261         }
1262
1263         /* if there's no old root to return, return what we found instead */
1264         if (!found)
1265                 found = tm;
1266
1267         return found;
1268 }
1269
1270 /*
1271  * tm is a pointer to the first operation to rewind within eb. then, all
1272  * previous operations will be rewinded (until we reach something older than
1273  * time_seq).
1274  */
1275 static void
1276 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1277                       u64 time_seq, struct tree_mod_elem *first_tm)
1278 {
1279         u32 n;
1280         struct rb_node *next;
1281         struct tree_mod_elem *tm = first_tm;
1282         unsigned long o_dst;
1283         unsigned long o_src;
1284         unsigned long p_size = sizeof(struct btrfs_key_ptr);
1285
1286         n = btrfs_header_nritems(eb);
1287         tree_mod_log_read_lock(fs_info);
1288         while (tm && tm->seq >= time_seq) {
1289                 /*
1290                  * all the operations are recorded with the operator used for
1291                  * the modification. as we're going backwards, we do the
1292                  * opposite of each operation here.
1293                  */
1294                 switch (tm->op) {
1295                 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1296                         BUG_ON(tm->slot < n);
1297                         /* Fallthrough */
1298                 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1299                 case MOD_LOG_KEY_REMOVE:
1300                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1301                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1302                         btrfs_set_node_ptr_generation(eb, tm->slot,
1303                                                       tm->generation);
1304                         n++;
1305                         break;
1306                 case MOD_LOG_KEY_REPLACE:
1307                         BUG_ON(tm->slot >= n);
1308                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1309                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1310                         btrfs_set_node_ptr_generation(eb, tm->slot,
1311                                                       tm->generation);
1312                         break;
1313                 case MOD_LOG_KEY_ADD:
1314                         /* if a move operation is needed it's in the log */
1315                         n--;
1316                         break;
1317                 case MOD_LOG_MOVE_KEYS:
1318                         o_dst = btrfs_node_key_ptr_offset(tm->slot);
1319                         o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1320                         memmove_extent_buffer(eb, o_dst, o_src,
1321                                               tm->move.nr_items * p_size);
1322                         break;
1323                 case MOD_LOG_ROOT_REPLACE:
1324                         /*
1325                          * this operation is special. for roots, this must be
1326                          * handled explicitly before rewinding.
1327                          * for non-roots, this operation may exist if the node
1328                          * was a root: root A -> child B; then A gets empty and
1329                          * B is promoted to the new root. in the mod log, we'll
1330                          * have a root-replace operation for B, a tree block
1331                          * that is no root. we simply ignore that operation.
1332                          */
1333                         break;
1334                 }
1335                 next = rb_next(&tm->node);
1336                 if (!next)
1337                         break;
1338                 tm = container_of(next, struct tree_mod_elem, node);
1339                 if (tm->index != first_tm->index)
1340                         break;
1341         }
1342         tree_mod_log_read_unlock(fs_info);
1343         btrfs_set_header_nritems(eb, n);
1344 }
1345
1346 /*
1347  * Called with eb read locked. If the buffer cannot be rewinded, the same buffer
1348  * is returned. If rewind operations happen, a fresh buffer is returned. The
1349  * returned buffer is always read-locked. If the returned buffer is not the
1350  * input buffer, the lock on the input buffer is released and the input buffer
1351  * is freed (its refcount is decremented).
1352  */
1353 static struct extent_buffer *
1354 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1355                     struct extent_buffer *eb, u64 time_seq)
1356 {
1357         struct extent_buffer *eb_rewin;
1358         struct tree_mod_elem *tm;
1359
1360         if (!time_seq)
1361                 return eb;
1362
1363         if (btrfs_header_level(eb) == 0)
1364                 return eb;
1365
1366         tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1367         if (!tm)
1368                 return eb;
1369
1370         btrfs_set_path_blocking(path);
1371         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1372
1373         if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1374                 BUG_ON(tm->slot != 0);
1375                 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1376                 if (!eb_rewin) {
1377                         btrfs_tree_read_unlock_blocking(eb);
1378                         free_extent_buffer(eb);
1379                         return NULL;
1380                 }
1381                 btrfs_set_header_bytenr(eb_rewin, eb->start);
1382                 btrfs_set_header_backref_rev(eb_rewin,
1383                                              btrfs_header_backref_rev(eb));
1384                 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1385                 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1386         } else {
1387                 eb_rewin = btrfs_clone_extent_buffer(eb);
1388                 if (!eb_rewin) {
1389                         btrfs_tree_read_unlock_blocking(eb);
1390                         free_extent_buffer(eb);
1391                         return NULL;
1392                 }
1393         }
1394
1395         btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1396         btrfs_tree_read_unlock_blocking(eb);
1397         free_extent_buffer(eb);
1398
1399         extent_buffer_get(eb_rewin);
1400         btrfs_tree_read_lock(eb_rewin);
1401         __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1402         WARN_ON(btrfs_header_nritems(eb_rewin) >
1403                 BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
1404
1405         return eb_rewin;
1406 }
1407
1408 /*
1409  * get_old_root() rewinds the state of @root's root node to the given @time_seq
1410  * value. If there are no changes, the current root->root_node is returned. If
1411  * anything changed in between, there's a fresh buffer allocated on which the
1412  * rewind operations are done. In any case, the returned buffer is read locked.
1413  * Returns NULL on error (with no locks held).
1414  */
1415 static inline struct extent_buffer *
1416 get_old_root(struct btrfs_root *root, u64 time_seq)
1417 {
1418         struct tree_mod_elem *tm;
1419         struct extent_buffer *eb = NULL;
1420         struct extent_buffer *eb_root;
1421         u64 eb_root_owner = 0;
1422         struct extent_buffer *old;
1423         struct tree_mod_root *old_root = NULL;
1424         u64 old_generation = 0;
1425         u64 logical;
1426
1427         eb_root = btrfs_read_lock_root_node(root);
1428         tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
1429         if (!tm)
1430                 return eb_root;
1431
1432         if (tm->op == MOD_LOG_ROOT_REPLACE) {
1433                 old_root = &tm->old_root;
1434                 old_generation = tm->generation;
1435                 logical = old_root->logical;
1436         } else {
1437                 logical = eb_root->start;
1438         }
1439
1440         tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1441         if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1442                 btrfs_tree_read_unlock(eb_root);
1443                 free_extent_buffer(eb_root);
1444                 old = read_tree_block(root, logical, 0);
1445                 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1446                         if (!IS_ERR(old))
1447                                 free_extent_buffer(old);
1448                         btrfs_warn(root->fs_info,
1449                                 "failed to read tree block %llu from get_old_root", logical);
1450                 } else {
1451                         eb = btrfs_clone_extent_buffer(old);
1452                         free_extent_buffer(old);
1453                 }
1454         } else if (old_root) {
1455                 eb_root_owner = btrfs_header_owner(eb_root);
1456                 btrfs_tree_read_unlock(eb_root);
1457                 free_extent_buffer(eb_root);
1458                 eb = alloc_dummy_extent_buffer(root->fs_info, logical);
1459         } else {
1460                 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1461                 eb = btrfs_clone_extent_buffer(eb_root);
1462                 btrfs_tree_read_unlock_blocking(eb_root);
1463                 free_extent_buffer(eb_root);
1464         }
1465
1466         if (!eb)
1467                 return NULL;
1468         extent_buffer_get(eb);
1469         btrfs_tree_read_lock(eb);
1470         if (old_root) {
1471                 btrfs_set_header_bytenr(eb, eb->start);
1472                 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1473                 btrfs_set_header_owner(eb, eb_root_owner);
1474                 btrfs_set_header_level(eb, old_root->level);
1475                 btrfs_set_header_generation(eb, old_generation);
1476         }
1477         if (tm)
1478                 __tree_mod_log_rewind(root->fs_info, eb, time_seq, tm);
1479         else
1480                 WARN_ON(btrfs_header_level(eb) != 0);
1481         WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
1482
1483         return eb;
1484 }
1485
1486 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1487 {
1488         struct tree_mod_elem *tm;
1489         int level;
1490         struct extent_buffer *eb_root = btrfs_root_node(root);
1491
1492         tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
1493         if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1494                 level = tm->old_root.level;
1495         } else {
1496                 level = btrfs_header_level(eb_root);
1497         }
1498         free_extent_buffer(eb_root);
1499
1500         return level;
1501 }
1502
1503 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1504                                    struct btrfs_root *root,
1505                                    struct extent_buffer *buf)
1506 {
1507         if (btrfs_test_is_dummy_root(root))
1508                 return 0;
1509
1510         /* ensure we can see the force_cow */
1511         smp_rmb();
1512
1513         /*
1514          * We do not need to cow a block if
1515          * 1) this block is not created or changed in this transaction;
1516          * 2) this block does not belong to TREE_RELOC tree;
1517          * 3) the root is not forced COW.
1518          *
1519          * What is forced COW:
1520          *    when we create snapshot during commiting the transaction,
1521          *    after we've finished coping src root, we must COW the shared
1522          *    block to ensure the metadata consistency.
1523          */
1524         if (btrfs_header_generation(buf) == trans->transid &&
1525             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1526             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1527               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1528             !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1529                 return 0;
1530         return 1;
1531 }
1532
1533 /*
1534  * cows a single block, see __btrfs_cow_block for the real work.
1535  * This version of it has extra checks so that a block isn't cow'd more than
1536  * once per transaction, as long as it hasn't been written yet
1537  */
1538 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1539                     struct btrfs_root *root, struct extent_buffer *buf,
1540                     struct extent_buffer *parent, int parent_slot,
1541                     struct extent_buffer **cow_ret)
1542 {
1543         u64 search_start;
1544         int ret;
1545
1546         if (trans->transaction != root->fs_info->running_transaction)
1547                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1548                        trans->transid,
1549                        root->fs_info->running_transaction->transid);
1550
1551         if (trans->transid != root->fs_info->generation)
1552                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1553                        trans->transid, root->fs_info->generation);
1554
1555         if (!should_cow_block(trans, root, buf)) {
1556                 trans->dirty = true;
1557                 *cow_ret = buf;
1558                 return 0;
1559         }
1560
1561         search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1562
1563         if (parent)
1564                 btrfs_set_lock_blocking(parent);
1565         btrfs_set_lock_blocking(buf);
1566
1567         ret = __btrfs_cow_block(trans, root, buf, parent,
1568                                  parent_slot, cow_ret, search_start, 0);
1569
1570         trace_btrfs_cow_block(root, buf, *cow_ret);
1571
1572         return ret;
1573 }
1574
1575 /*
1576  * helper function for defrag to decide if two blocks pointed to by a
1577  * node are actually close by
1578  */
1579 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1580 {
1581         if (blocknr < other && other - (blocknr + blocksize) < 32768)
1582                 return 1;
1583         if (blocknr > other && blocknr - (other + blocksize) < 32768)
1584                 return 1;
1585         return 0;
1586 }
1587
1588 /*
1589  * compare two keys in a memcmp fashion
1590  */
1591 static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1592 {
1593         struct btrfs_key k1;
1594
1595         btrfs_disk_key_to_cpu(&k1, disk);
1596
1597         return btrfs_comp_cpu_keys(&k1, k2);
1598 }
1599
1600 /*
1601  * same as comp_keys only with two btrfs_key's
1602  */
1603 int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1604 {
1605         if (k1->objectid > k2->objectid)
1606                 return 1;
1607         if (k1->objectid < k2->objectid)
1608                 return -1;
1609         if (k1->type > k2->type)
1610                 return 1;
1611         if (k1->type < k2->type)
1612                 return -1;
1613         if (k1->offset > k2->offset)
1614                 return 1;
1615         if (k1->offset < k2->offset)
1616                 return -1;
1617         return 0;
1618 }
1619
1620 /*
1621  * this is used by the defrag code to go through all the
1622  * leaves pointed to by a node and reallocate them so that
1623  * disk order is close to key order
1624  */
1625 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1626                        struct btrfs_root *root, struct extent_buffer *parent,
1627                        int start_slot, u64 *last_ret,
1628                        struct btrfs_key *progress)
1629 {
1630         struct extent_buffer *cur;
1631         u64 blocknr;
1632         u64 gen;
1633         u64 search_start = *last_ret;
1634         u64 last_block = 0;
1635         u64 other;
1636         u32 parent_nritems;
1637         int end_slot;
1638         int i;
1639         int err = 0;
1640         int parent_level;
1641         int uptodate;
1642         u32 blocksize;
1643         int progress_passed = 0;
1644         struct btrfs_disk_key disk_key;
1645
1646         parent_level = btrfs_header_level(parent);
1647
1648         WARN_ON(trans->transaction != root->fs_info->running_transaction);
1649         WARN_ON(trans->transid != root->fs_info->generation);
1650
1651         parent_nritems = btrfs_header_nritems(parent);
1652         blocksize = root->nodesize;
1653         end_slot = parent_nritems - 1;
1654
1655         if (parent_nritems <= 1)
1656                 return 0;
1657
1658         btrfs_set_lock_blocking(parent);
1659
1660         for (i = start_slot; i <= end_slot; i++) {
1661                 int close = 1;
1662
1663                 btrfs_node_key(parent, &disk_key, i);
1664                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1665                         continue;
1666
1667                 progress_passed = 1;
1668                 blocknr = btrfs_node_blockptr(parent, i);
1669                 gen = btrfs_node_ptr_generation(parent, i);
1670                 if (last_block == 0)
1671                         last_block = blocknr;
1672
1673                 if (i > 0) {
1674                         other = btrfs_node_blockptr(parent, i - 1);
1675                         close = close_blocks(blocknr, other, blocksize);
1676                 }
1677                 if (!close && i < end_slot) {
1678                         other = btrfs_node_blockptr(parent, i + 1);
1679                         close = close_blocks(blocknr, other, blocksize);
1680                 }
1681                 if (close) {
1682                         last_block = blocknr;
1683                         continue;
1684                 }
1685
1686                 cur = btrfs_find_tree_block(root->fs_info, blocknr);
1687                 if (cur)
1688                         uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1689                 else
1690                         uptodate = 0;
1691                 if (!cur || !uptodate) {
1692                         if (!cur) {
1693                                 cur = read_tree_block(root, blocknr, gen);
1694                                 if (IS_ERR(cur)) {
1695                                         return PTR_ERR(cur);
1696                                 } else if (!extent_buffer_uptodate(cur)) {
1697                                         free_extent_buffer(cur);
1698                                         return -EIO;
1699                                 }
1700                         } else if (!uptodate) {
1701                                 err = btrfs_read_buffer(cur, gen);
1702                                 if (err) {
1703                                         free_extent_buffer(cur);
1704                                         return err;
1705                                 }
1706                         }
1707                 }
1708                 if (search_start == 0)
1709                         search_start = last_block;
1710
1711                 btrfs_tree_lock(cur);
1712                 btrfs_set_lock_blocking(cur);
1713                 err = __btrfs_cow_block(trans, root, cur, parent, i,
1714                                         &cur, search_start,
1715                                         min(16 * blocksize,
1716                                             (end_slot - i) * blocksize));
1717                 if (err) {
1718                         btrfs_tree_unlock(cur);
1719                         free_extent_buffer(cur);
1720                         break;
1721                 }
1722                 search_start = cur->start;
1723                 last_block = cur->start;
1724                 *last_ret = search_start;
1725                 btrfs_tree_unlock(cur);
1726                 free_extent_buffer(cur);
1727         }
1728         return err;
1729 }
1730
1731
1732 /*
1733  * search for key in the extent_buffer.  The items start at offset p,
1734  * and they are item_size apart.  There are 'max' items in p.
1735  *
1736  * the slot in the array is returned via slot, and it points to
1737  * the place where you would insert key if it is not found in
1738  * the array.
1739  *
1740  * slot may point to max if the key is bigger than all of the keys
1741  */
1742 static noinline int generic_bin_search(struct extent_buffer *eb,
1743                                        unsigned long p,
1744                                        int item_size, struct btrfs_key *key,
1745                                        int max, int *slot)
1746 {
1747         int low = 0;
1748         int high = max;
1749         int mid;
1750         int ret;
1751         struct btrfs_disk_key *tmp = NULL;
1752         struct btrfs_disk_key unaligned;
1753         unsigned long offset;
1754         char *kaddr = NULL;
1755         unsigned long map_start = 0;
1756         unsigned long map_len = 0;
1757         int err;
1758
1759         while (low < high) {
1760                 mid = (low + high) / 2;
1761                 offset = p + mid * item_size;
1762
1763                 if (!kaddr || offset < map_start ||
1764                     (offset + sizeof(struct btrfs_disk_key)) >
1765                     map_start + map_len) {
1766
1767                         err = map_private_extent_buffer(eb, offset,
1768                                                 sizeof(struct btrfs_disk_key),
1769                                                 &kaddr, &map_start, &map_len);
1770
1771                         if (!err) {
1772                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1773                                                         map_start);
1774                         } else {
1775                                 read_extent_buffer(eb, &unaligned,
1776                                                    offset, sizeof(unaligned));
1777                                 tmp = &unaligned;
1778                         }
1779
1780                 } else {
1781                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
1782                                                         map_start);
1783                 }
1784                 ret = comp_keys(tmp, key);
1785
1786                 if (ret < 0)
1787                         low = mid + 1;
1788                 else if (ret > 0)
1789                         high = mid;
1790                 else {
1791                         *slot = mid;
1792                         return 0;
1793                 }
1794         }
1795         *slot = low;
1796         return 1;
1797 }
1798
1799 /*
1800  * simple bin_search frontend that does the right thing for
1801  * leaves vs nodes
1802  */
1803 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1804                       int level, int *slot)
1805 {
1806         if (level == 0)
1807                 return generic_bin_search(eb,
1808                                           offsetof(struct btrfs_leaf, items),
1809                                           sizeof(struct btrfs_item),
1810                                           key, btrfs_header_nritems(eb),
1811                                           slot);
1812         else
1813                 return generic_bin_search(eb,
1814                                           offsetof(struct btrfs_node, ptrs),
1815                                           sizeof(struct btrfs_key_ptr),
1816                                           key, btrfs_header_nritems(eb),
1817                                           slot);
1818 }
1819
1820 int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1821                      int level, int *slot)
1822 {
1823         return bin_search(eb, key, level, slot);
1824 }
1825
1826 static void root_add_used(struct btrfs_root *root, u32 size)
1827 {
1828         spin_lock(&root->accounting_lock);
1829         btrfs_set_root_used(&root->root_item,
1830                             btrfs_root_used(&root->root_item) + size);
1831         spin_unlock(&root->accounting_lock);
1832 }
1833
1834 static void root_sub_used(struct btrfs_root *root, u32 size)
1835 {
1836         spin_lock(&root->accounting_lock);
1837         btrfs_set_root_used(&root->root_item,
1838                             btrfs_root_used(&root->root_item) - size);
1839         spin_unlock(&root->accounting_lock);
1840 }
1841
1842 /* given a node and slot number, this reads the blocks it points to.  The
1843  * extent buffer is returned with a reference taken (but unlocked).
1844  * NULL is returned on error.
1845  */
1846 static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
1847                                    struct extent_buffer *parent, int slot)
1848 {
1849         int level = btrfs_header_level(parent);
1850         struct extent_buffer *eb;
1851
1852         if (slot < 0)
1853                 return NULL;
1854         if (slot >= btrfs_header_nritems(parent))
1855                 return NULL;
1856
1857         BUG_ON(level == 0);
1858
1859         eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1860                              btrfs_node_ptr_generation(parent, slot));
1861         if (IS_ERR(eb) || !extent_buffer_uptodate(eb)) {
1862                 if (!IS_ERR(eb))
1863                         free_extent_buffer(eb);
1864                 eb = NULL;
1865         }
1866
1867         return eb;
1868 }
1869
1870 /*
1871  * node level balancing, used to make sure nodes are in proper order for
1872  * item deletion.  We balance from the top down, so we have to make sure
1873  * that a deletion won't leave an node completely empty later on.
1874  */
1875 static noinline int balance_level(struct btrfs_trans_handle *trans,
1876                          struct btrfs_root *root,
1877                          struct btrfs_path *path, int level)
1878 {
1879         struct extent_buffer *right = NULL;
1880         struct extent_buffer *mid;
1881         struct extent_buffer *left = NULL;
1882         struct extent_buffer *parent = NULL;
1883         int ret = 0;
1884         int wret;
1885         int pslot;
1886         int orig_slot = path->slots[level];
1887         u64 orig_ptr;
1888
1889         if (level == 0)
1890                 return 0;
1891
1892         mid = path->nodes[level];
1893
1894         WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1895                 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1896         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1897
1898         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1899
1900         if (level < BTRFS_MAX_LEVEL - 1) {
1901                 parent = path->nodes[level + 1];
1902                 pslot = path->slots[level + 1];
1903         }
1904
1905         /*
1906          * deal with the case where there is only one pointer in the root
1907          * by promoting the node below to a root
1908          */
1909         if (!parent) {
1910                 struct extent_buffer *child;
1911
1912                 if (btrfs_header_nritems(mid) != 1)
1913                         return 0;
1914
1915                 /* promote the child to a root */
1916                 child = read_node_slot(root, mid, 0);
1917                 if (!child) {
1918                         ret = -EROFS;
1919                         btrfs_std_error(root->fs_info, ret, NULL);
1920                         goto enospc;
1921                 }
1922
1923                 btrfs_tree_lock(child);
1924                 btrfs_set_lock_blocking(child);
1925                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1926                 if (ret) {
1927                         btrfs_tree_unlock(child);
1928                         free_extent_buffer(child);
1929                         goto enospc;
1930                 }
1931
1932                 tree_mod_log_set_root_pointer(root, child, 1);
1933                 rcu_assign_pointer(root->node, child);
1934
1935                 add_root_to_dirty_list(root);
1936                 btrfs_tree_unlock(child);
1937
1938                 path->locks[level] = 0;
1939                 path->nodes[level] = NULL;
1940                 clean_tree_block(trans, root->fs_info, mid);
1941                 btrfs_tree_unlock(mid);
1942                 /* once for the path */
1943                 free_extent_buffer(mid);
1944
1945                 root_sub_used(root, mid->len);
1946                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1947                 /* once for the root ptr */
1948                 free_extent_buffer_stale(mid);
1949                 return 0;
1950         }
1951         if (btrfs_header_nritems(mid) >
1952             BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1953                 return 0;
1954
1955         left = read_node_slot(root, parent, pslot - 1);
1956         if (left) {
1957                 btrfs_tree_lock(left);
1958                 btrfs_set_lock_blocking(left);
1959                 wret = btrfs_cow_block(trans, root, left,
1960                                        parent, pslot - 1, &left);
1961                 if (wret) {
1962                         ret = wret;
1963                         goto enospc;
1964                 }
1965         }
1966         right = read_node_slot(root, parent, pslot + 1);
1967         if (right) {
1968                 btrfs_tree_lock(right);
1969                 btrfs_set_lock_blocking(right);
1970                 wret = btrfs_cow_block(trans, root, right,
1971                                        parent, pslot + 1, &right);
1972                 if (wret) {
1973                         ret = wret;
1974                         goto enospc;
1975                 }
1976         }
1977
1978         /* first, try to make some room in the middle buffer */
1979         if (left) {
1980                 orig_slot += btrfs_header_nritems(left);
1981                 wret = push_node_left(trans, root, left, mid, 1);
1982                 if (wret < 0)
1983                         ret = wret;
1984         }
1985
1986         /*
1987          * then try to empty the right most buffer into the middle
1988          */
1989         if (right) {
1990                 wret = push_node_left(trans, root, mid, right, 1);
1991                 if (wret < 0 && wret != -ENOSPC)
1992                         ret = wret;
1993                 if (btrfs_header_nritems(right) == 0) {
1994                         clean_tree_block(trans, root->fs_info, right);
1995                         btrfs_tree_unlock(right);
1996                         del_ptr(root, path, level + 1, pslot + 1);
1997                         root_sub_used(root, right->len);
1998                         btrfs_free_tree_block(trans, root, right, 0, 1);
1999                         free_extent_buffer_stale(right);
2000                         right = NULL;
2001                 } else {
2002                         struct btrfs_disk_key right_key;
2003                         btrfs_node_key(right, &right_key, 0);
2004                         tree_mod_log_set_node_key(root->fs_info, parent,
2005                                                   pslot + 1, 0);
2006                         btrfs_set_node_key(parent, &right_key, pslot + 1);
2007                         btrfs_mark_buffer_dirty(parent);
2008                 }
2009         }
2010         if (btrfs_header_nritems(mid) == 1) {
2011                 /*
2012                  * we're not allowed to leave a node with one item in the
2013                  * tree during a delete.  A deletion from lower in the tree
2014                  * could try to delete the only pointer in this node.
2015                  * So, pull some keys from the left.
2016                  * There has to be a left pointer at this point because
2017                  * otherwise we would have pulled some pointers from the
2018                  * right
2019                  */
2020                 if (!left) {
2021                         ret = -EROFS;
2022                         btrfs_std_error(root->fs_info, ret, NULL);
2023                         goto enospc;
2024                 }
2025                 wret = balance_node_right(trans, root, mid, left);
2026                 if (wret < 0) {
2027                         ret = wret;
2028                         goto enospc;
2029                 }
2030                 if (wret == 1) {
2031                         wret = push_node_left(trans, root, left, mid, 1);
2032                         if (wret < 0)
2033                                 ret = wret;
2034                 }
2035                 BUG_ON(wret == 1);
2036         }
2037         if (btrfs_header_nritems(mid) == 0) {
2038                 clean_tree_block(trans, root->fs_info, mid);
2039                 btrfs_tree_unlock(mid);
2040                 del_ptr(root, path, level + 1, pslot);
2041                 root_sub_used(root, mid->len);
2042                 btrfs_free_tree_block(trans, root, mid, 0, 1);
2043                 free_extent_buffer_stale(mid);
2044                 mid = NULL;
2045         } else {
2046                 /* update the parent key to reflect our changes */
2047                 struct btrfs_disk_key mid_key;
2048                 btrfs_node_key(mid, &mid_key, 0);
2049                 tree_mod_log_set_node_key(root->fs_info, parent,
2050                                           pslot, 0);
2051                 btrfs_set_node_key(parent, &mid_key, pslot);
2052                 btrfs_mark_buffer_dirty(parent);
2053         }
2054
2055         /* update the path */
2056         if (left) {
2057                 if (btrfs_header_nritems(left) > orig_slot) {
2058                         extent_buffer_get(left);
2059                         /* left was locked after cow */
2060                         path->nodes[level] = left;
2061                         path->slots[level + 1] -= 1;
2062                         path->slots[level] = orig_slot;
2063                         if (mid) {
2064                                 btrfs_tree_unlock(mid);
2065                                 free_extent_buffer(mid);
2066                         }
2067                 } else {
2068                         orig_slot -= btrfs_header_nritems(left);
2069                         path->slots[level] = orig_slot;
2070                 }
2071         }
2072         /* double check we haven't messed things up */
2073         if (orig_ptr !=
2074             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2075                 BUG();
2076 enospc:
2077         if (right) {
2078                 btrfs_tree_unlock(right);
2079                 free_extent_buffer(right);
2080         }
2081         if (left) {
2082                 if (path->nodes[level] != left)
2083                         btrfs_tree_unlock(left);
2084                 free_extent_buffer(left);
2085         }
2086         return ret;
2087 }
2088
2089 /* Node balancing for insertion.  Here we only split or push nodes around
2090  * when they are completely full.  This is also done top down, so we
2091  * have to be pessimistic.
2092  */
2093 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2094                                           struct btrfs_root *root,
2095                                           struct btrfs_path *path, int level)
2096 {
2097         struct extent_buffer *right = NULL;
2098         struct extent_buffer *mid;
2099         struct extent_buffer *left = NULL;
2100         struct extent_buffer *parent = NULL;
2101         int ret = 0;
2102         int wret;
2103         int pslot;
2104         int orig_slot = path->slots[level];
2105
2106         if (level == 0)
2107                 return 1;
2108
2109         mid = path->nodes[level];
2110         WARN_ON(btrfs_header_generation(mid) != trans->transid);
2111
2112         if (level < BTRFS_MAX_LEVEL - 1) {
2113                 parent = path->nodes[level + 1];
2114                 pslot = path->slots[level + 1];
2115         }
2116
2117         if (!parent)
2118                 return 1;
2119
2120         left = read_node_slot(root, parent, pslot - 1);
2121
2122         /* first, try to make some room in the middle buffer */
2123         if (left) {
2124                 u32 left_nr;
2125
2126                 btrfs_tree_lock(left);
2127                 btrfs_set_lock_blocking(left);
2128
2129                 left_nr = btrfs_header_nritems(left);
2130                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
2131                         wret = 1;
2132                 } else {
2133                         ret = btrfs_cow_block(trans, root, left, parent,
2134                                               pslot - 1, &left);
2135                         if (ret)
2136                                 wret = 1;
2137                         else {
2138                                 wret = push_node_left(trans, root,
2139                                                       left, mid, 0);
2140                         }
2141                 }
2142                 if (wret < 0)
2143                         ret = wret;
2144                 if (wret == 0) {
2145                         struct btrfs_disk_key disk_key;
2146                         orig_slot += left_nr;
2147                         btrfs_node_key(mid, &disk_key, 0);
2148                         tree_mod_log_set_node_key(root->fs_info, parent,
2149                                                   pslot, 0);
2150                         btrfs_set_node_key(parent, &disk_key, pslot);
2151                         btrfs_mark_buffer_dirty(parent);
2152                         if (btrfs_header_nritems(left) > orig_slot) {
2153                                 path->nodes[level] = left;
2154                                 path->slots[level + 1] -= 1;
2155                                 path->slots[level] = orig_slot;
2156                                 btrfs_tree_unlock(mid);
2157                                 free_extent_buffer(mid);
2158                         } else {
2159                                 orig_slot -=
2160                                         btrfs_header_nritems(left);
2161                                 path->slots[level] = orig_slot;
2162                                 btrfs_tree_unlock(left);
2163                                 free_extent_buffer(left);
2164                         }
2165                         return 0;
2166                 }
2167                 btrfs_tree_unlock(left);
2168                 free_extent_buffer(left);
2169         }
2170         right = read_node_slot(root, parent, pslot + 1);
2171
2172         /*
2173          * then try to empty the right most buffer into the middle
2174          */
2175         if (right) {
2176                 u32 right_nr;
2177
2178                 btrfs_tree_lock(right);
2179                 btrfs_set_lock_blocking(right);
2180
2181                 right_nr = btrfs_header_nritems(right);
2182                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
2183                         wret = 1;
2184                 } else {
2185                         ret = btrfs_cow_block(trans, root, right,
2186                                               parent, pslot + 1,
2187                                               &right);
2188                         if (ret)
2189                                 wret = 1;
2190                         else {
2191                                 wret = balance_node_right(trans, root,
2192                                                           right, mid);
2193                         }
2194                 }
2195                 if (wret < 0)
2196                         ret = wret;
2197                 if (wret == 0) {
2198                         struct btrfs_disk_key disk_key;
2199
2200                         btrfs_node_key(right, &disk_key, 0);
2201                         tree_mod_log_set_node_key(root->fs_info, parent,
2202                                                   pslot + 1, 0);
2203                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
2204                         btrfs_mark_buffer_dirty(parent);
2205
2206                         if (btrfs_header_nritems(mid) <= orig_slot) {
2207                                 path->nodes[level] = right;
2208                                 path->slots[level + 1] += 1;
2209                                 path->slots[level] = orig_slot -
2210                                         btrfs_header_nritems(mid);
2211                                 btrfs_tree_unlock(mid);
2212                                 free_extent_buffer(mid);
2213                         } else {
2214                                 btrfs_tree_unlock(right);
2215                                 free_extent_buffer(right);
2216                         }
2217                         return 0;
2218                 }
2219                 btrfs_tree_unlock(right);
2220                 free_extent_buffer(right);
2221         }
2222         return 1;
2223 }
2224
2225 /*
2226  * readahead one full node of leaves, finding things that are close
2227  * to the block in 'slot', and triggering ra on them.
2228  */
2229 static void reada_for_search(struct btrfs_root *root,
2230                              struct btrfs_path *path,
2231                              int level, int slot, u64 objectid)
2232 {
2233         struct extent_buffer *node;
2234         struct btrfs_disk_key disk_key;
2235         u32 nritems;
2236         u64 search;
2237         u64 target;
2238         u64 nread = 0;
2239         u64 gen;
2240         int direction = path->reada;
2241         struct extent_buffer *eb;
2242         u32 nr;
2243         u32 blocksize;
2244         u32 nscan = 0;
2245
2246         if (level != 1)
2247                 return;
2248
2249         if (!path->nodes[level])
2250                 return;
2251
2252         node = path->nodes[level];
2253
2254         search = btrfs_node_blockptr(node, slot);
2255         blocksize = root->nodesize;
2256         eb = btrfs_find_tree_block(root->fs_info, search);
2257         if (eb) {
2258                 free_extent_buffer(eb);
2259                 return;
2260         }
2261
2262         target = search;
2263
2264         nritems = btrfs_header_nritems(node);
2265         nr = slot;
2266
2267         while (1) {
2268                 if (direction < 0) {
2269                         if (nr == 0)
2270                                 break;
2271                         nr--;
2272                 } else if (direction > 0) {
2273                         nr++;
2274                         if (nr >= nritems)
2275                                 break;
2276                 }
2277                 if (path->reada < 0 && objectid) {
2278                         btrfs_node_key(node, &disk_key, nr);
2279                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
2280                                 break;
2281                 }
2282                 search = btrfs_node_blockptr(node, nr);
2283                 if ((search <= target && target - search <= 65536) ||
2284                     (search > target && search - target <= 65536)) {
2285                         gen = btrfs_node_ptr_generation(node, nr);
2286                         readahead_tree_block(root, search);
2287                         nread += blocksize;
2288                 }
2289                 nscan++;
2290                 if ((nread > 65536 || nscan > 32))
2291                         break;
2292         }
2293 }
2294
2295 static noinline void reada_for_balance(struct btrfs_root *root,
2296                                        struct btrfs_path *path, int level)
2297 {
2298         int slot;
2299         int nritems;
2300         struct extent_buffer *parent;
2301         struct extent_buffer *eb;
2302         u64 gen;
2303         u64 block1 = 0;
2304         u64 block2 = 0;
2305
2306         parent = path->nodes[level + 1];
2307         if (!parent)
2308                 return;
2309
2310         nritems = btrfs_header_nritems(parent);
2311         slot = path->slots[level + 1];
2312
2313         if (slot > 0) {
2314                 block1 = btrfs_node_blockptr(parent, slot - 1);
2315                 gen = btrfs_node_ptr_generation(parent, slot - 1);
2316                 eb = btrfs_find_tree_block(root->fs_info, block1);
2317                 /*
2318                  * if we get -eagain from btrfs_buffer_uptodate, we
2319                  * don't want to return eagain here.  That will loop
2320                  * forever
2321                  */
2322                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2323                         block1 = 0;
2324                 free_extent_buffer(eb);
2325         }
2326         if (slot + 1 < nritems) {
2327                 block2 = btrfs_node_blockptr(parent, slot + 1);
2328                 gen = btrfs_node_ptr_generation(parent, slot + 1);
2329                 eb = btrfs_find_tree_block(root->fs_info, block2);
2330                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2331                         block2 = 0;
2332                 free_extent_buffer(eb);
2333         }
2334
2335         if (block1)
2336                 readahead_tree_block(root, block1);
2337         if (block2)
2338                 readahead_tree_block(root, block2);
2339 }
2340
2341
2342 /*
2343  * when we walk down the tree, it is usually safe to unlock the higher layers
2344  * in the tree.  The exceptions are when our path goes through slot 0, because
2345  * operations on the tree might require changing key pointers higher up in the
2346  * tree.
2347  *
2348  * callers might also have set path->keep_locks, which tells this code to keep
2349  * the lock if the path points to the last slot in the block.  This is part of
2350  * walking through the tree, and selecting the next slot in the higher block.
2351  *
2352  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2353  * if lowest_unlock is 1, level 0 won't be unlocked
2354  */
2355 static noinline void unlock_up(struct btrfs_path *path, int level,
2356                                int lowest_unlock, int min_write_lock_level,
2357                                int *write_lock_level)
2358 {
2359         int i;
2360         int skip_level = level;
2361         int no_skips = 0;
2362         struct extent_buffer *t;
2363
2364         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2365                 if (!path->nodes[i])
2366                         break;
2367                 if (!path->locks[i])
2368                         break;
2369                 if (!no_skips && path->slots[i] == 0) {
2370                         skip_level = i + 1;
2371                         continue;
2372                 }
2373                 if (!no_skips && path->keep_locks) {
2374                         u32 nritems;
2375                         t = path->nodes[i];
2376                         nritems = btrfs_header_nritems(t);
2377                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
2378                                 skip_level = i + 1;
2379                                 continue;
2380                         }
2381                 }
2382                 if (skip_level < i && i >= lowest_unlock)
2383                         no_skips = 1;
2384
2385                 t = path->nodes[i];
2386                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2387                         btrfs_tree_unlock_rw(t, path->locks[i]);
2388                         path->locks[i] = 0;
2389                         if (write_lock_level &&
2390                             i > min_write_lock_level &&
2391                             i <= *write_lock_level) {
2392                                 *write_lock_level = i - 1;
2393                         }
2394                 }
2395         }
2396 }
2397
2398 /*
2399  * This releases any locks held in the path starting at level and
2400  * going all the way up to the root.
2401  *
2402  * btrfs_search_slot will keep the lock held on higher nodes in a few
2403  * corner cases, such as COW of the block at slot zero in the node.  This
2404  * ignores those rules, and it should only be called when there are no
2405  * more updates to be done higher up in the tree.
2406  */
2407 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2408 {
2409         int i;
2410
2411         if (path->keep_locks)
2412                 return;
2413
2414         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2415                 if (!path->nodes[i])
2416                         continue;
2417                 if (!path->locks[i])
2418                         continue;
2419                 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2420                 path->locks[i] = 0;
2421         }
2422 }
2423
2424 /*
2425  * helper function for btrfs_search_slot.  The goal is to find a block
2426  * in cache without setting the path to blocking.  If we find the block
2427  * we return zero and the path is unchanged.
2428  *
2429  * If we can't find the block, we set the path blocking and do some
2430  * reada.  -EAGAIN is returned and the search must be repeated.
2431  */
2432 static int
2433 read_block_for_search(struct btrfs_trans_handle *trans,
2434                        struct btrfs_root *root, struct btrfs_path *p,
2435                        struct extent_buffer **eb_ret, int level, int slot,
2436                        struct btrfs_key *key, u64 time_seq)
2437 {
2438         u64 blocknr;
2439         u64 gen;
2440         struct extent_buffer *b = *eb_ret;
2441         struct extent_buffer *tmp;
2442         int ret;
2443
2444         blocknr = btrfs_node_blockptr(b, slot);
2445         gen = btrfs_node_ptr_generation(b, slot);
2446
2447         tmp = btrfs_find_tree_block(root->fs_info, blocknr);
2448         if (tmp) {
2449                 /* first we do an atomic uptodate check */
2450                 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2451                         *eb_ret = tmp;
2452                         return 0;
2453                 }
2454
2455                 /* the pages were up to date, but we failed
2456                  * the generation number check.  Do a full
2457                  * read for the generation number that is correct.
2458                  * We must do this without dropping locks so
2459                  * we can trust our generation number
2460                  */
2461                 btrfs_set_path_blocking(p);
2462
2463                 /* now we're allowed to do a blocking uptodate check */
2464                 ret = btrfs_read_buffer(tmp, gen);
2465                 if (!ret) {
2466                         *eb_ret = tmp;
2467                         return 0;
2468                 }
2469                 free_extent_buffer(tmp);
2470                 btrfs_release_path(p);
2471                 return -EIO;
2472         }
2473
2474         /*
2475          * reduce lock contention at high levels
2476          * of the btree by dropping locks before
2477          * we read.  Don't release the lock on the current
2478          * level because we need to walk this node to figure
2479          * out which blocks to read.
2480          */
2481         btrfs_unlock_up_safe(p, level + 1);
2482         btrfs_set_path_blocking(p);
2483
2484         free_extent_buffer(tmp);
2485         if (p->reada)
2486                 reada_for_search(root, p, level, slot, key->objectid);
2487
2488         ret = -EAGAIN;
2489         tmp = read_tree_block(root, blocknr, gen);
2490         if (!IS_ERR(tmp)) {
2491                 /*
2492                  * If the read above didn't mark this buffer up to date,
2493                  * it will never end up being up to date.  Set ret to EIO now
2494                  * and give up so that our caller doesn't loop forever
2495                  * on our EAGAINs.
2496                  */
2497                 if (!btrfs_buffer_uptodate(tmp, 0, 0))
2498                         ret = -EIO;
2499                 free_extent_buffer(tmp);
2500         }
2501
2502         btrfs_release_path(p);
2503         return ret;
2504 }
2505
2506 /*
2507  * helper function for btrfs_search_slot.  This does all of the checks
2508  * for node-level blocks and does any balancing required based on
2509  * the ins_len.
2510  *
2511  * If no extra work was required, zero is returned.  If we had to
2512  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2513  * start over
2514  */
2515 static int
2516 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2517                        struct btrfs_root *root, struct btrfs_path *p,
2518                        struct extent_buffer *b, int level, int ins_len,
2519                        int *write_lock_level)
2520 {
2521         int ret;
2522         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2523             BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2524                 int sret;
2525
2526                 if (*write_lock_level < level + 1) {
2527                         *write_lock_level = level + 1;
2528                         btrfs_release_path(p);
2529                         goto again;
2530                 }
2531
2532                 btrfs_set_path_blocking(p);
2533                 reada_for_balance(root, p, level);
2534                 sret = split_node(trans, root, p, level);
2535                 btrfs_clear_path_blocking(p, NULL, 0);
2536
2537                 BUG_ON(sret > 0);
2538                 if (sret) {
2539                         ret = sret;
2540                         goto done;
2541                 }
2542                 b = p->nodes[level];
2543         } else if (ins_len < 0 && btrfs_header_nritems(b) <
2544                    BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2545                 int sret;
2546
2547                 if (*write_lock_level < level + 1) {
2548                         *write_lock_level = level + 1;
2549                         btrfs_release_path(p);
2550                         goto again;
2551                 }
2552
2553                 btrfs_set_path_blocking(p);
2554                 reada_for_balance(root, p, level);
2555                 sret = balance_level(trans, root, p, level);
2556                 btrfs_clear_path_blocking(p, NULL, 0);
2557
2558                 if (sret) {
2559                         ret = sret;
2560                         goto done;
2561                 }
2562                 b = p->nodes[level];
2563                 if (!b) {
2564                         btrfs_release_path(p);
2565                         goto again;
2566                 }
2567                 BUG_ON(btrfs_header_nritems(b) == 1);
2568         }
2569         return 0;
2570
2571 again:
2572         ret = -EAGAIN;
2573 done:
2574         return ret;
2575 }
2576
2577 static void key_search_validate(struct extent_buffer *b,
2578                                 struct btrfs_key *key,
2579                                 int level)
2580 {
2581 #ifdef CONFIG_BTRFS_ASSERT
2582         struct btrfs_disk_key disk_key;
2583
2584         btrfs_cpu_key_to_disk(&disk_key, key);
2585
2586         if (level == 0)
2587                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2588                     offsetof(struct btrfs_leaf, items[0].key),
2589                     sizeof(disk_key)));
2590         else
2591                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2592                     offsetof(struct btrfs_node, ptrs[0].key),
2593                     sizeof(disk_key)));
2594 #endif
2595 }
2596
2597 static int key_search(struct extent_buffer *b, struct btrfs_key *key,
2598                       int level, int *prev_cmp, int *slot)
2599 {
2600         if (*prev_cmp != 0) {
2601                 *prev_cmp = bin_search(b, key, level, slot);
2602                 return *prev_cmp;
2603         }
2604
2605         key_search_validate(b, key, level);
2606         *slot = 0;
2607
2608         return 0;
2609 }
2610
2611 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2612                 u64 iobjectid, u64 ioff, u8 key_type,
2613                 struct btrfs_key *found_key)
2614 {
2615         int ret;
2616         struct btrfs_key key;
2617         struct extent_buffer *eb;
2618
2619         ASSERT(path);
2620         ASSERT(found_key);
2621
2622         key.type = key_type;
2623         key.objectid = iobjectid;
2624         key.offset = ioff;
2625
2626         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2627         if (ret < 0)
2628                 return ret;
2629
2630         eb = path->nodes[0];
2631         if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2632                 ret = btrfs_next_leaf(fs_root, path);
2633                 if (ret)
2634                         return ret;
2635                 eb = path->nodes[0];
2636         }
2637
2638         btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2639         if (found_key->type != key.type ||
2640                         found_key->objectid != key.objectid)
2641                 return 1;
2642
2643         return 0;
2644 }
2645
2646 /*
2647  * look for key in the tree.  path is filled in with nodes along the way
2648  * if key is found, we return zero and you can find the item in the leaf
2649  * level of the path (level 0)
2650  *
2651  * If the key isn't found, the path points to the slot where it should
2652  * be inserted, and 1 is returned.  If there are other errors during the
2653  * search a negative error number is returned.
2654  *
2655  * if ins_len > 0, nodes and leaves will be split as we walk down the
2656  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
2657  * possible)
2658  */
2659 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2660                       *root, struct btrfs_key *key, struct btrfs_path *p, int
2661                       ins_len, int cow)
2662 {
2663         struct extent_buffer *b;
2664         int slot;
2665         int ret;
2666         int err;
2667         int level;
2668         int lowest_unlock = 1;
2669         int root_lock;
2670         /* everything at write_lock_level or lower must be write locked */
2671         int write_lock_level = 0;
2672         u8 lowest_level = 0;
2673         int min_write_lock_level;
2674         int prev_cmp;
2675
2676         lowest_level = p->lowest_level;
2677         WARN_ON(lowest_level && ins_len > 0);
2678         WARN_ON(p->nodes[0] != NULL);
2679         BUG_ON(!cow && ins_len);
2680
2681         if (ins_len < 0) {
2682                 lowest_unlock = 2;
2683
2684                 /* when we are removing items, we might have to go up to level
2685                  * two as we update tree pointers  Make sure we keep write
2686                  * for those levels as well
2687                  */
2688                 write_lock_level = 2;
2689         } else if (ins_len > 0) {
2690                 /*
2691                  * for inserting items, make sure we have a write lock on
2692                  * level 1 so we can update keys
2693                  */
2694                 write_lock_level = 1;
2695         }
2696
2697         if (!cow)
2698                 write_lock_level = -1;
2699
2700         if (cow && (p->keep_locks || p->lowest_level))
2701                 write_lock_level = BTRFS_MAX_LEVEL;
2702
2703         min_write_lock_level = write_lock_level;
2704
2705 again:
2706         prev_cmp = -1;
2707         /*
2708          * we try very hard to do read locks on the root
2709          */
2710         root_lock = BTRFS_READ_LOCK;
2711         level = 0;
2712         if (p->search_commit_root) {
2713                 /*
2714                  * the commit roots are read only
2715                  * so we always do read locks
2716                  */
2717                 if (p->need_commit_sem)
2718                         down_read(&root->fs_info->commit_root_sem);
2719                 b = root->commit_root;
2720                 extent_buffer_get(b);
2721                 level = btrfs_header_level(b);
2722                 if (p->need_commit_sem)
2723                         up_read(&root->fs_info->commit_root_sem);
2724                 if (!p->skip_locking)
2725                         btrfs_tree_read_lock(b);
2726         } else {
2727                 if (p->skip_locking) {
2728                         b = btrfs_root_node(root);
2729                         level = btrfs_header_level(b);
2730                 } else {
2731                         /* we don't know the level of the root node
2732                          * until we actually have it read locked
2733                          */
2734                         b = btrfs_read_lock_root_node(root);
2735                         level = btrfs_header_level(b);
2736                         if (level <= write_lock_level) {
2737                                 /* whoops, must trade for write lock */
2738                                 btrfs_tree_read_unlock(b);
2739                                 free_extent_buffer(b);
2740                                 b = btrfs_lock_root_node(root);
2741                                 root_lock = BTRFS_WRITE_LOCK;
2742
2743                                 /* the level might have changed, check again */
2744                                 level = btrfs_header_level(b);
2745                         }
2746                 }
2747         }
2748         p->nodes[level] = b;
2749         if (!p->skip_locking)
2750                 p->locks[level] = root_lock;
2751
2752         while (b) {
2753                 level = btrfs_header_level(b);
2754
2755                 /*
2756                  * setup the path here so we can release it under lock
2757                  * contention with the cow code
2758                  */
2759                 if (cow) {
2760                         bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2761
2762                         /*
2763                          * if we don't really need to cow this block
2764                          * then we don't want to set the path blocking,
2765                          * so we test it here
2766                          */
2767                         if (!should_cow_block(trans, root, b)) {
2768                                 trans->dirty = true;
2769                                 goto cow_done;
2770                         }
2771
2772                         /*
2773                          * must have write locks on this node and the
2774                          * parent
2775                          */
2776                         if (level > write_lock_level ||
2777                             (level + 1 > write_lock_level &&
2778                             level + 1 < BTRFS_MAX_LEVEL &&
2779                             p->nodes[level + 1])) {
2780                                 write_lock_level = level + 1;
2781                                 btrfs_release_path(p);
2782                                 goto again;
2783                         }
2784
2785                         btrfs_set_path_blocking(p);
2786                         if (last_level)
2787                                 err = btrfs_cow_block(trans, root, b, NULL, 0,
2788                                                       &b);
2789                         else
2790                                 err = btrfs_cow_block(trans, root, b,
2791                                                       p->nodes[level + 1],
2792                                                       p->slots[level + 1], &b);
2793                         if (err) {
2794                                 ret = err;
2795                                 goto done;
2796                         }
2797                 }
2798 cow_done:
2799                 p->nodes[level] = b;
2800                 btrfs_clear_path_blocking(p, NULL, 0);
2801
2802                 /*
2803                  * we have a lock on b and as long as we aren't changing
2804                  * the tree, there is no way to for the items in b to change.
2805                  * It is safe to drop the lock on our parent before we
2806                  * go through the expensive btree search on b.
2807                  *
2808                  * If we're inserting or deleting (ins_len != 0), then we might
2809                  * be changing slot zero, which may require changing the parent.
2810                  * So, we can't drop the lock until after we know which slot
2811                  * we're operating on.
2812                  */
2813                 if (!ins_len && !p->keep_locks) {
2814                         int u = level + 1;
2815
2816                         if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2817                                 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2818                                 p->locks[u] = 0;
2819                         }
2820                 }
2821
2822                 ret = key_search(b, key, level, &prev_cmp, &slot);
2823
2824                 if (level != 0) {
2825                         int dec = 0;
2826                         if (ret && slot > 0) {
2827                                 dec = 1;
2828                                 slot -= 1;
2829                         }
2830                         p->slots[level] = slot;
2831                         err = setup_nodes_for_search(trans, root, p, b, level,
2832                                              ins_len, &write_lock_level);
2833                         if (err == -EAGAIN)
2834                                 goto again;
2835                         if (err) {
2836                                 ret = err;
2837                                 goto done;
2838                         }
2839                         b = p->nodes[level];
2840                         slot = p->slots[level];
2841
2842                         /*
2843                          * slot 0 is special, if we change the key
2844                          * we have to update the parent pointer
2845                          * which means we must have a write lock
2846                          * on the parent
2847                          */
2848                         if (slot == 0 && ins_len &&
2849                             write_lock_level < level + 1) {
2850                                 write_lock_level = level + 1;
2851                                 btrfs_release_path(p);
2852                                 goto again;
2853                         }
2854
2855                         unlock_up(p, level, lowest_unlock,
2856                                   min_write_lock_level, &write_lock_level);
2857
2858                         if (level == lowest_level) {
2859                                 if (dec)
2860                                         p->slots[level]++;
2861                                 goto done;
2862                         }
2863
2864                         err = read_block_for_search(trans, root, p,
2865                                                     &b, level, slot, key, 0);
2866                         if (err == -EAGAIN)
2867                                 goto again;
2868                         if (err) {
2869                                 ret = err;
2870                                 goto done;
2871                         }
2872
2873                         if (!p->skip_locking) {
2874                                 level = btrfs_header_level(b);
2875                                 if (level <= write_lock_level) {
2876                                         err = btrfs_try_tree_write_lock(b);
2877                                         if (!err) {
2878                                                 btrfs_set_path_blocking(p);
2879                                                 btrfs_tree_lock(b);
2880                                                 btrfs_clear_path_blocking(p, b,
2881                                                                   BTRFS_WRITE_LOCK);
2882                                         }
2883                                         p->locks[level] = BTRFS_WRITE_LOCK;
2884                                 } else {
2885                                         err = btrfs_tree_read_lock_atomic(b);
2886                                         if (!err) {
2887                                                 btrfs_set_path_blocking(p);
2888                                                 btrfs_tree_read_lock(b);
2889                                                 btrfs_clear_path_blocking(p, b,
2890                                                                   BTRFS_READ_LOCK);
2891                                         }
2892                                         p->locks[level] = BTRFS_READ_LOCK;
2893                                 }
2894                                 p->nodes[level] = b;
2895                         }
2896                 } else {
2897                         p->slots[level] = slot;
2898                         if (ins_len > 0 &&
2899                             btrfs_leaf_free_space(root, b) < ins_len) {
2900                                 if (write_lock_level < 1) {
2901                                         write_lock_level = 1;
2902                                         btrfs_release_path(p);
2903                                         goto again;
2904                                 }
2905
2906                                 btrfs_set_path_blocking(p);
2907                                 err = split_leaf(trans, root, key,
2908                                                  p, ins_len, ret == 0);
2909                                 btrfs_clear_path_blocking(p, NULL, 0);
2910
2911                                 BUG_ON(err > 0);
2912                                 if (err) {
2913                                         ret = err;
2914                                         goto done;
2915                                 }
2916                         }
2917                         if (!p->search_for_split)
2918                                 unlock_up(p, level, lowest_unlock,
2919                                           min_write_lock_level, &write_lock_level);
2920                         goto done;
2921                 }
2922         }
2923         ret = 1;
2924 done:
2925         /*
2926          * we don't really know what they plan on doing with the path
2927          * from here on, so for now just mark it as blocking
2928          */
2929         if (!p->leave_spinning)
2930                 btrfs_set_path_blocking(p);
2931         if (ret < 0 && !p->skip_release_on_error)
2932                 btrfs_release_path(p);
2933         return ret;
2934 }
2935
2936 /*
2937  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2938  * current state of the tree together with the operations recorded in the tree
2939  * modification log to search for the key in a previous version of this tree, as
2940  * denoted by the time_seq parameter.
2941  *
2942  * Naturally, there is no support for insert, delete or cow operations.
2943  *
2944  * The resulting path and return value will be set up as if we called
2945  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2946  */
2947 int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
2948                           struct btrfs_path *p, u64 time_seq)
2949 {
2950         struct extent_buffer *b;
2951         int slot;
2952         int ret;
2953         int err;
2954         int level;
2955         int lowest_unlock = 1;
2956         u8 lowest_level = 0;
2957         int prev_cmp = -1;
2958
2959         lowest_level = p->lowest_level;
2960         WARN_ON(p->nodes[0] != NULL);
2961
2962         if (p->search_commit_root) {
2963                 BUG_ON(time_seq);
2964                 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2965         }
2966
2967 again:
2968         b = get_old_root(root, time_seq);
2969         level = btrfs_header_level(b);
2970         p->locks[level] = BTRFS_READ_LOCK;
2971
2972         while (b) {
2973                 level = btrfs_header_level(b);
2974                 p->nodes[level] = b;
2975                 btrfs_clear_path_blocking(p, NULL, 0);
2976
2977                 /*
2978                  * we have a lock on b and as long as we aren't changing
2979                  * the tree, there is no way to for the items in b to change.
2980                  * It is safe to drop the lock on our parent before we
2981                  * go through the expensive btree search on b.
2982                  */
2983                 btrfs_unlock_up_safe(p, level + 1);
2984
2985                 /*
2986                  * Since we can unwind eb's we want to do a real search every
2987                  * time.
2988                  */
2989                 prev_cmp = -1;
2990                 ret = key_search(b, key, level, &prev_cmp, &slot);
2991
2992                 if (level != 0) {
2993                         int dec = 0;
2994                         if (ret && slot > 0) {
2995                                 dec = 1;
2996                                 slot -= 1;
2997                         }
2998                         p->slots[level] = slot;
2999                         unlock_up(p, level, lowest_unlock, 0, NULL);
3000
3001                         if (level == lowest_level) {
3002                                 if (dec)
3003                                         p->slots[level]++;
3004                                 goto done;
3005                         }
3006
3007                         err = read_block_for_search(NULL, root, p, &b, level,
3008                                                     slot, key, time_seq);
3009                         if (err == -EAGAIN)
3010                                 goto again;
3011                         if (err) {
3012                                 ret = err;
3013                                 goto done;
3014                         }
3015
3016                         level = btrfs_header_level(b);
3017                         err = btrfs_tree_read_lock_atomic(b);
3018                         if (!err) {
3019                                 btrfs_set_path_blocking(p);
3020                                 btrfs_tree_read_lock(b);
3021                                 btrfs_clear_path_blocking(p, b,
3022                                                           BTRFS_READ_LOCK);
3023                         }
3024                         b = tree_mod_log_rewind(root->fs_info, p, b, time_seq);
3025                         if (!b) {
3026                                 ret = -ENOMEM;
3027                                 goto done;
3028                         }
3029                         p->locks[level] = BTRFS_READ_LOCK;
3030                         p->nodes[level] = b;
3031                 } else {
3032                         p->slots[level] = slot;
3033                         unlock_up(p, level, lowest_unlock, 0, NULL);
3034                         goto done;
3035                 }
3036         }
3037         ret = 1;
3038 done:
3039         if (!p->leave_spinning)
3040                 btrfs_set_path_blocking(p);
3041         if (ret < 0)
3042                 btrfs_release_path(p);
3043
3044         return ret;
3045 }
3046
3047 /*
3048  * helper to use instead of search slot if no exact match is needed but
3049  * instead the next or previous item should be returned.
3050  * When find_higher is true, the next higher item is returned, the next lower
3051  * otherwise.
3052  * When return_any and find_higher are both true, and no higher item is found,
3053  * return the next lower instead.
3054  * When return_any is true and find_higher is false, and no lower item is found,
3055  * return the next higher instead.
3056  * It returns 0 if any item is found, 1 if none is found (tree empty), and
3057  * < 0 on error
3058  */
3059 int btrfs_search_slot_for_read(struct btrfs_root *root,
3060                                struct btrfs_key *key, struct btrfs_path *p,
3061                                int find_higher, int return_any)
3062 {
3063         int ret;
3064         struct extent_buffer *leaf;
3065
3066 again:
3067         ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3068         if (ret <= 0)
3069                 return ret;
3070         /*
3071          * a return value of 1 means the path is at the position where the
3072          * item should be inserted. Normally this is the next bigger item,
3073          * but in case the previous item is the last in a leaf, path points
3074          * to the first free slot in the previous leaf, i.e. at an invalid
3075          * item.
3076          */
3077         leaf = p->nodes[0];
3078
3079         if (find_higher) {
3080                 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3081                         ret = btrfs_next_leaf(root, p);
3082                         if (ret <= 0)
3083                                 return ret;
3084                         if (!return_any)
3085                                 return 1;
3086                         /*
3087                          * no higher item found, return the next
3088                          * lower instead
3089                          */
3090                         return_any = 0;
3091                         find_higher = 0;
3092                         btrfs_release_path(p);
3093                         goto again;
3094                 }
3095         } else {
3096                 if (p->slots[0] == 0) {
3097                         ret = btrfs_prev_leaf(root, p);
3098                         if (ret < 0)
3099                                 return ret;
3100                         if (!ret) {
3101                                 leaf = p->nodes[0];
3102                                 if (p->slots[0] == btrfs_header_nritems(leaf))
3103                                         p->slots[0]--;
3104                                 return 0;
3105                         }
3106                         if (!return_any)
3107                                 return 1;
3108                         /*
3109                          * no lower item found, return the next
3110                          * higher instead
3111                          */
3112                         return_any = 0;
3113                         find_higher = 1;
3114                         btrfs_release_path(p);
3115                         goto again;
3116                 } else {
3117                         --p->slots[0];
3118                 }
3119         }
3120         return 0;
3121 }
3122
3123 /*
3124  * adjust the pointers going up the tree, starting at level
3125  * making sure the right key of each node is points to 'key'.
3126  * This is used after shifting pointers to the left, so it stops
3127  * fixing up pointers when a given leaf/node is not in slot 0 of the
3128  * higher levels
3129  *
3130  */
3131 static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3132                            struct btrfs_path *path,
3133                            struct btrfs_disk_key *key, int level)
3134 {
3135         int i;
3136         struct extent_buffer *t;
3137
3138         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3139                 int tslot = path->slots[i];
3140                 if (!path->nodes[i])
3141                         break;
3142                 t = path->nodes[i];
3143                 tree_mod_log_set_node_key(fs_info, t, tslot, 1);
3144                 btrfs_set_node_key(t, key, tslot);
3145                 btrfs_mark_buffer_dirty(path->nodes[i]);
3146                 if (tslot != 0)
3147                         break;
3148         }
3149 }
3150
3151 /*
3152  * update item key.
3153  *
3154  * This function isn't completely safe. It's the caller's responsibility
3155  * that the new key won't break the order
3156  */
3157 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3158                              struct btrfs_path *path,
3159                              struct btrfs_key *new_key)
3160 {
3161         struct btrfs_disk_key disk_key;
3162         struct extent_buffer *eb;
3163         int slot;
3164
3165         eb = path->nodes[0];
3166         slot = path->slots[0];
3167         if (slot > 0) {
3168                 btrfs_item_key(eb, &disk_key, slot - 1);
3169                 BUG_ON(comp_keys(&disk_key, new_key) >= 0);
3170         }
3171         if (slot < btrfs_header_nritems(eb) - 1) {
3172                 btrfs_item_key(eb, &disk_key, slot + 1);
3173                 BUG_ON(comp_keys(&disk_key, new_key) <= 0);
3174         }
3175
3176         btrfs_cpu_key_to_disk(&disk_key, new_key);
3177         btrfs_set_item_key(eb, &disk_key, slot);
3178         btrfs_mark_buffer_dirty(eb);
3179         if (slot == 0)
3180                 fixup_low_keys(fs_info, path, &disk_key, 1);
3181 }
3182
3183 /*
3184  * try to push data from one node into the next node left in the
3185  * tree.
3186  *
3187  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3188  * error, and > 0 if there was no room in the left hand block.
3189  */
3190 static int push_node_left(struct btrfs_trans_handle *trans,
3191                           struct btrfs_root *root, struct extent_buffer *dst,
3192                           struct extent_buffer *src, int empty)
3193 {
3194         int push_items = 0;
3195         int src_nritems;
3196         int dst_nritems;
3197         int ret = 0;
3198
3199         src_nritems = btrfs_header_nritems(src);
3200         dst_nritems = btrfs_header_nritems(dst);
3201         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3202         WARN_ON(btrfs_header_generation(src) != trans->transid);
3203         WARN_ON(btrfs_header_generation(dst) != trans->transid);
3204
3205         if (!empty && src_nritems <= 8)
3206                 return 1;
3207
3208         if (push_items <= 0)
3209                 return 1;
3210
3211         if (empty) {
3212                 push_items = min(src_nritems, push_items);
3213                 if (push_items < src_nritems) {
3214                         /* leave at least 8 pointers in the node if
3215                          * we aren't going to empty it
3216                          */
3217                         if (src_nritems - push_items < 8) {
3218                                 if (push_items <= 8)
3219                                         return 1;
3220                                 push_items -= 8;
3221                         }
3222                 }
3223         } else
3224                 push_items = min(src_nritems - 8, push_items);
3225
3226         ret = tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
3227                                    push_items);
3228         if (ret) {
3229                 btrfs_abort_transaction(trans, root, ret);
3230                 return ret;
3231         }
3232         copy_extent_buffer(dst, src,
3233                            btrfs_node_key_ptr_offset(dst_nritems),
3234                            btrfs_node_key_ptr_offset(0),
3235                            push_items * sizeof(struct btrfs_key_ptr));
3236
3237         if (push_items < src_nritems) {
3238                 /*
3239                  * don't call tree_mod_log_eb_move here, key removal was already
3240                  * fully logged by tree_mod_log_eb_copy above.
3241                  */
3242                 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3243                                       btrfs_node_key_ptr_offset(push_items),
3244                                       (src_nritems - push_items) *
3245                                       sizeof(struct btrfs_key_ptr));
3246         }
3247         btrfs_set_header_nritems(src, src_nritems - push_items);
3248         btrfs_set_header_nritems(dst, dst_nritems + push_items);
3249         btrfs_mark_buffer_dirty(src);
3250         btrfs_mark_buffer_dirty(dst);
3251
3252         return ret;
3253 }
3254
3255 /*
3256  * try to push data from one node into the next node right in the
3257  * tree.
3258  *
3259  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3260  * error, and > 0 if there was no room in the right hand block.
3261  *
3262  * this will  only push up to 1/2 the contents of the left node over
3263  */
3264 static int balance_node_right(struct btrfs_trans_handle *trans,
3265                               struct btrfs_root *root,
3266                               struct extent_buffer *dst,
3267                               struct extent_buffer *src)
3268 {
3269         int push_items = 0;
3270         int max_push;
3271         int src_nritems;
3272         int dst_nritems;
3273         int ret = 0;
3274
3275         WARN_ON(btrfs_header_generation(src) != trans->transid);
3276         WARN_ON(btrfs_header_generation(dst) != trans->transid);
3277
3278         src_nritems = btrfs_header_nritems(src);
3279         dst_nritems = btrfs_header_nritems(dst);
3280         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3281         if (push_items <= 0)
3282                 return 1;
3283
3284         if (src_nritems < 4)
3285                 return 1;
3286
3287         max_push = src_nritems / 2 + 1;
3288         /* don't try to empty the node */
3289         if (max_push >= src_nritems)
3290                 return 1;
3291
3292         if (max_push < push_items)
3293                 push_items = max_push;
3294
3295         tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
3296         memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3297                                       btrfs_node_key_ptr_offset(0),
3298                                       (dst_nritems) *
3299                                       sizeof(struct btrfs_key_ptr));
3300
3301         ret = tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
3302                                    src_nritems - push_items, push_items);
3303         if (ret) {
3304                 btrfs_abort_transaction(trans, root, ret);
3305                 return ret;
3306         }
3307         copy_extent_buffer(dst, src,
3308                            btrfs_node_key_ptr_offset(0),
3309                            btrfs_node_key_ptr_offset(src_nritems - push_items),
3310                            push_items * sizeof(struct btrfs_key_ptr));
3311
3312         btrfs_set_header_nritems(src, src_nritems - push_items);
3313         btrfs_set_header_nritems(dst, dst_nritems + push_items);
3314
3315         btrfs_mark_buffer_dirty(src);
3316         btrfs_mark_buffer_dirty(dst);
3317
3318         return ret;
3319 }
3320
3321 /*
3322  * helper function to insert a new root level in the tree.
3323  * A new node is allocated, and a single item is inserted to
3324  * point to the existing root
3325  *
3326  * returns zero on success or < 0 on failure.
3327  */
3328 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
3329                            struct btrfs_root *root,
3330                            struct btrfs_path *path, int level)
3331 {
3332         u64 lower_gen;
3333         struct extent_buffer *lower;
3334         struct extent_buffer *c;
3335         struct extent_buffer *old;
3336         struct btrfs_disk_key lower_key;
3337
3338         BUG_ON(path->nodes[level]);
3339         BUG_ON(path->nodes[level-1] != root->node);
3340
3341         lower = path->nodes[level-1];
3342         if (level == 1)
3343                 btrfs_item_key(lower, &lower_key, 0);
3344         else
3345                 btrfs_node_key(lower, &lower_key, 0);
3346
3347         c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3348                                    &lower_key, level, root->node->start, 0);
3349         if (IS_ERR(c))
3350                 return PTR_ERR(c);
3351
3352         root_add_used(root, root->nodesize);
3353
3354         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
3355         btrfs_set_header_nritems(c, 1);
3356         btrfs_set_header_level(c, level);
3357         btrfs_set_header_bytenr(c, c->start);
3358         btrfs_set_header_generation(c, trans->transid);
3359         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
3360         btrfs_set_header_owner(c, root->root_key.objectid);
3361
3362         write_extent_buffer(c, root->fs_info->fsid, btrfs_header_fsid(),
3363                             BTRFS_FSID_SIZE);
3364
3365         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3366                             btrfs_header_chunk_tree_uuid(c), BTRFS_UUID_SIZE);
3367
3368         btrfs_set_node_key(c, &lower_key, 0);
3369         btrfs_set_node_blockptr(c, 0, lower->start);
3370         lower_gen = btrfs_header_generation(lower);
3371         WARN_ON(lower_gen != trans->transid);
3372
3373         btrfs_set_node_ptr_generation(c, 0, lower_gen);
3374
3375         btrfs_mark_buffer_dirty(c);
3376
3377         old = root->node;
3378         tree_mod_log_set_root_pointer(root, c, 0);
3379         rcu_assign_pointer(root->node, c);
3380
3381         /* the super has an extra ref to root->node */
3382         free_extent_buffer(old);
3383
3384         add_root_to_dirty_list(root);
3385         extent_buffer_get(c);
3386         path->nodes[level] = c;
3387         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
3388         path->slots[level] = 0;
3389         return 0;
3390 }
3391
3392 /*
3393  * worker function to insert a single pointer in a node.
3394  * the node should have enough room for the pointer already
3395  *
3396  * slot and level indicate where you want the key to go, and
3397  * blocknr is the block the key points to.
3398  */
3399 static void insert_ptr(struct btrfs_trans_handle *trans,
3400                        struct btrfs_root *root, struct btrfs_path *path,
3401                        struct btrfs_disk_key *key, u64 bytenr,
3402                        int slot, int level)
3403 {
3404         struct extent_buffer *lower;
3405         int nritems;
3406         int ret;
3407
3408         BUG_ON(!path->nodes[level]);
3409         btrfs_assert_tree_locked(path->nodes[level]);
3410         lower = path->nodes[level];
3411         nritems = btrfs_header_nritems(lower);
3412         BUG_ON(slot > nritems);
3413         BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
3414         if (slot != nritems) {
3415                 if (level)
3416                         tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3417                                              slot, nritems - slot);
3418                 memmove_extent_buffer(lower,
3419                               btrfs_node_key_ptr_offset(slot + 1),
3420                               btrfs_node_key_ptr_offset(slot),
3421                               (nritems - slot) * sizeof(struct btrfs_key_ptr));
3422         }
3423         if (level) {
3424                 ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3425                                               MOD_LOG_KEY_ADD, GFP_NOFS);
3426                 BUG_ON(ret < 0);
3427         }
3428         btrfs_set_node_key(lower, key, slot);
3429         btrfs_set_node_blockptr(lower, slot, bytenr);
3430         WARN_ON(trans->transid == 0);
3431         btrfs_set_node_ptr_generation(lower, slot, trans->transid);
3432         btrfs_set_header_nritems(lower, nritems + 1);
3433         btrfs_mark_buffer_dirty(lower);
3434 }
3435
3436 /*
3437  * split the node at the specified level in path in two.
3438  * The path is corrected to point to the appropriate node after the split
3439  *
3440  * Before splitting this tries to make some room in the node by pushing
3441  * left and right, if either one works, it returns right away.
3442  *
3443  * returns 0 on success and < 0 on failure
3444  */
3445 static noinline int split_node(struct btrfs_trans_handle *trans,
3446                                struct btrfs_root *root,
3447                                struct btrfs_path *path, int level)
3448 {
3449         struct extent_buffer *c;
3450         struct extent_buffer *split;
3451         struct btrfs_disk_key disk_key;
3452         int mid;
3453         int ret;
3454         u32 c_nritems;
3455
3456         c = path->nodes[level];
3457         WARN_ON(btrfs_header_generation(c) != trans->transid);
3458         if (c == root->node) {
3459                 /*
3460                  * trying to split the root, lets make a new one
3461                  *
3462                  * tree mod log: We don't log_removal old root in
3463                  * insert_new_root, because that root buffer will be kept as a
3464                  * normal node. We are going to log removal of half of the
3465                  * elements below with tree_mod_log_eb_copy. We're holding a
3466                  * tree lock on the buffer, which is why we cannot race with
3467                  * other tree_mod_log users.
3468                  */
3469                 ret = insert_new_root(trans, root, path, level + 1);
3470                 if (ret)
3471                         return ret;
3472         } else {
3473                 ret = push_nodes_for_insert(trans, root, path, level);
3474                 c = path->nodes[level];
3475                 if (!ret && btrfs_header_nritems(c) <
3476                     BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3477                         return 0;
3478                 if (ret < 0)
3479                         return ret;
3480         }
3481
3482         c_nritems = btrfs_header_nritems(c);
3483         mid = (c_nritems + 1) / 2;
3484         btrfs_node_key(c, &disk_key, mid);
3485
3486         split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3487                         &disk_key, level, c->start, 0);
3488         if (IS_ERR(split))
3489                 return PTR_ERR(split);
3490
3491         root_add_used(root, root->nodesize);
3492
3493         memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
3494         btrfs_set_header_level(split, btrfs_header_level(c));
3495         btrfs_set_header_bytenr(split, split->start);
3496         btrfs_set_header_generation(split, trans->transid);
3497         btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
3498         btrfs_set_header_owner(split, root->root_key.objectid);
3499         write_extent_buffer(split, root->fs_info->fsid,
3500                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
3501         write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3502                             btrfs_header_chunk_tree_uuid(split),
3503                             BTRFS_UUID_SIZE);
3504
3505         ret = tree_mod_log_eb_copy(root->fs_info, split, c, 0,
3506                                    mid, c_nritems - mid);
3507         if (ret) {
3508                 btrfs_abort_transaction(trans, root, ret);
3509                 return ret;
3510         }
3511         copy_extent_buffer(split, c,
3512                            btrfs_node_key_ptr_offset(0),
3513                            btrfs_node_key_ptr_offset(mid),
3514                            (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3515         btrfs_set_header_nritems(split, c_nritems - mid);
3516         btrfs_set_header_nritems(c, mid);
3517         ret = 0;
3518
3519         btrfs_mark_buffer_dirty(c);
3520         btrfs_mark_buffer_dirty(split);
3521
3522         insert_ptr(trans, root, path, &disk_key, split->start,
3523                    path->slots[level + 1] + 1, level + 1);
3524
3525         if (path->slots[level] >= mid) {
3526                 path->slots[level] -= mid;
3527                 btrfs_tree_unlock(c);
3528                 free_extent_buffer(c);
3529                 path->nodes[level] = split;
3530                 path->slots[level + 1] += 1;
3531         } else {
3532                 btrfs_tree_unlock(split);
3533                 free_extent_buffer(split);
3534         }
3535         return ret;
3536 }
3537
3538 /*
3539  * how many bytes are required to store the items in a leaf.  start
3540  * and nr indicate which items in the leaf to check.  This totals up the
3541  * space used both by the item structs and the item data
3542  */
3543 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3544 {
3545         struct btrfs_item *start_item;
3546         struct btrfs_item *end_item;
3547         struct btrfs_map_token token;
3548         int data_len;
3549         int nritems = btrfs_header_nritems(l);
3550         int end = min(nritems, start + nr) - 1;
3551
3552         if (!nr)
3553                 return 0;
3554         btrfs_init_map_token(&token);
3555         start_item = btrfs_item_nr(start);
3556         end_item = btrfs_item_nr(end);
3557         data_len = btrfs_token_item_offset(l, start_item, &token) +
3558                 btrfs_token_item_size(l, start_item, &token);
3559         data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
3560         data_len += sizeof(struct btrfs_item) * nr;
3561         WARN_ON(data_len < 0);
3562         return data_len;
3563 }
3564
3565 /*
3566  * The space between the end of the leaf items and
3567  * the start of the leaf data.  IOW, how much room
3568  * the leaf has left for both items and data
3569  */
3570 noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3571                                    struct extent_buffer *leaf)
3572 {
3573         int nritems = btrfs_header_nritems(leaf);
3574         int ret;
3575         ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
3576         if (ret < 0) {
3577                 btrfs_crit(root->fs_info,
3578                         "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3579                        ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
3580                        leaf_space_used(leaf, 0, nritems), nritems);
3581         }
3582         return ret;
3583 }
3584
3585 /*
3586  * min slot controls the lowest index we're willing to push to the
3587  * right.  We'll push up to and including min_slot, but no lower
3588  */
3589 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3590                                       struct btrfs_root *root,
3591                                       struct btrfs_path *path,
3592                                       int data_size, int empty,
3593                                       struct extent_buffer *right,
3594                                       int free_space, u32 left_nritems,
3595                                       u32 min_slot)
3596 {
3597         struct extent_buffer *left = path->nodes[0];
3598         struct extent_buffer *upper = path->nodes[1];
3599         struct btrfs_map_token token;
3600         struct btrfs_disk_key disk_key;
3601         int slot;
3602         u32 i;
3603         int push_space = 0;
3604         int push_items = 0;
3605         struct btrfs_item *item;
3606         u32 nr;
3607         u32 right_nritems;
3608         u32 data_end;
3609         u32 this_item_size;
3610
3611         btrfs_init_map_token(&token);
3612
3613         if (empty)
3614                 nr = 0;
3615         else
3616                 nr = max_t(u32, 1, min_slot);
3617
3618         if (path->slots[0] >= left_nritems)
3619                 push_space += data_size;
3620
3621         slot = path->slots[1];
3622         i = left_nritems - 1;
3623         while (i >= nr) {
3624                 item = btrfs_item_nr(i);
3625
3626                 if (!empty && push_items > 0) {
3627                         if (path->slots[0] > i)
3628                                 break;
3629                         if (path->slots[0] == i) {
3630                                 int space = btrfs_leaf_free_space(root, left);
3631                                 if (space + push_space * 2 > free_space)
3632                                         break;
3633                         }
3634                 }
3635
3636                 if (path->slots[0] == i)
3637                         push_space += data_size;
3638
3639                 this_item_size = btrfs_item_size(left, item);
3640                 if (this_item_size + sizeof(*item) + push_space > free_space)
3641                         break;
3642
3643                 push_items++;
3644                 push_space += this_item_size + sizeof(*item);
3645                 if (i == 0)
3646                         break;
3647                 i--;
3648         }
3649
3650         if (push_items == 0)
3651                 goto out_unlock;
3652
3653         WARN_ON(!empty && push_items == left_nritems);
3654
3655         /* push left to right */
3656         right_nritems = btrfs_header_nritems(right);
3657
3658         push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3659         push_space -= leaf_data_end(root, left);
3660
3661         /* make room in the right data area */
3662         data_end = leaf_data_end(root, right);
3663         memmove_extent_buffer(right,
3664                               btrfs_leaf_data(right) + data_end - push_space,
3665                               btrfs_leaf_data(right) + data_end,
3666                               BTRFS_LEAF_DATA_SIZE(root) - data_end);
3667
3668         /* copy from the left data area */
3669         copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3670                      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3671                      btrfs_leaf_data(left) + leaf_data_end(root, left),
3672                      push_space);
3673
3674         memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3675                               btrfs_item_nr_offset(0),
3676                               right_nritems * sizeof(struct btrfs_item));
3677
3678         /* copy the items from left to right */
3679         copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3680                    btrfs_item_nr_offset(left_nritems - push_items),
3681                    push_items * sizeof(struct btrfs_item));
3682
3683         /* update the item pointers */
3684         right_nritems += push_items;
3685         btrfs_set_header_nritems(right, right_nritems);
3686         push_space = BTRFS_LEAF_DATA_SIZE(root);
3687         for (i = 0; i < right_nritems; i++) {
3688                 item = btrfs_item_nr(i);
3689                 push_space -= btrfs_token_item_size(right, item, &token);
3690                 btrfs_set_token_item_offset(right, item, push_space, &token);
3691         }
3692
3693         left_nritems -= push_items;
3694         btrfs_set_header_nritems(left, left_nritems);
3695
3696         if (left_nritems)
3697                 btrfs_mark_buffer_dirty(left);
3698         else
3699                 clean_tree_block(trans, root->fs_info, left);
3700
3701         btrfs_mark_buffer_dirty(right);
3702
3703         btrfs_item_key(right, &disk_key, 0);
3704         btrfs_set_node_key(upper, &disk_key, slot + 1);
3705         btrfs_mark_buffer_dirty(upper);
3706
3707         /* then fixup the leaf pointer in the path */
3708         if (path->slots[0] >= left_nritems) {
3709                 path->slots[0] -= left_nritems;
3710                 if (btrfs_header_nritems(path->nodes[0]) == 0)
3711                         clean_tree_block(trans, root->fs_info, path->nodes[0]);
3712                 btrfs_tree_unlock(path->nodes[0]);
3713                 free_extent_buffer(path->nodes[0]);
3714                 path->nodes[0] = right;
3715                 path->slots[1] += 1;
3716         } else {
3717                 btrfs_tree_unlock(right);
3718                 free_extent_buffer(right);
3719         }
3720         return 0;
3721
3722 out_unlock:
3723         btrfs_tree_unlock(right);
3724         free_extent_buffer(right);
3725         return 1;
3726 }
3727
3728 /*
3729  * push some data in the path leaf to the right, trying to free up at
3730  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3731  *
3732  * returns 1 if the push failed because the other node didn't have enough
3733  * room, 0 if everything worked out and < 0 if there were major errors.
3734  *
3735  * this will push starting from min_slot to the end of the leaf.  It won't
3736  * push any slot lower than min_slot
3737  */
3738 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3739                            *root, struct btrfs_path *path,
3740                            int min_data_size, int data_size,
3741                            int empty, u32 min_slot)
3742 {
3743         struct extent_buffer *left = path->nodes[0];
3744         struct extent_buffer *right;
3745         struct extent_buffer *upper;
3746         int slot;
3747         int free_space;
3748         u32 left_nritems;
3749         int ret;
3750
3751         if (!path->nodes[1])
3752                 return 1;
3753
3754         slot = path->slots[1];
3755         upper = path->nodes[1];
3756         if (slot >= btrfs_header_nritems(upper) - 1)
3757                 return 1;
3758
3759         btrfs_assert_tree_locked(path->nodes[1]);
3760
3761         right = read_node_slot(root, upper, slot + 1);
3762         if (right == NULL)
3763                 return 1;
3764
3765         btrfs_tree_lock(right);
3766         btrfs_set_lock_blocking(right);
3767
3768         free_space = btrfs_leaf_free_space(root, right);
3769         if (free_space < data_size)
3770                 goto out_unlock;
3771
3772         /* cow and double check */
3773         ret = btrfs_cow_block(trans, root, right, upper,
3774                               slot + 1, &right);
3775         if (ret)
3776                 goto out_unlock;
3777
3778         free_space = btrfs_leaf_free_space(root, right);
3779         if (free_space < data_size)
3780                 goto out_unlock;
3781
3782         left_nritems = btrfs_header_nritems(left);
3783         if (left_nritems == 0)
3784                 goto out_unlock;
3785
3786         if (path->slots[0] == left_nritems && !empty) {
3787                 /* Key greater than all keys in the leaf, right neighbor has
3788                  * enough room for it and we're not emptying our leaf to delete
3789                  * it, therefore use right neighbor to insert the new item and
3790                  * no need to touch/dirty our left leaft. */
3791                 btrfs_tree_unlock(left);
3792                 free_extent_buffer(left);
3793                 path->nodes[0] = right;
3794                 path->slots[0] = 0;
3795                 path->slots[1]++;
3796                 return 0;
3797         }
3798
3799         return __push_leaf_right(trans, root, path, min_data_size, empty,
3800                                 right, free_space, left_nritems, min_slot);
3801 out_unlock:
3802         btrfs_tree_unlock(right);
3803         free_extent_buffer(right);
3804         return 1;
3805 }
3806
3807 /*
3808  * push some data in the path leaf to the left, trying to free up at
3809  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3810  *
3811  * max_slot can put a limit on how far into the leaf we'll push items.  The
3812  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
3813  * items
3814  */
3815 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3816                                      struct btrfs_root *root,
3817                                      struct btrfs_path *path, int data_size,
3818                                      int empty, struct extent_buffer *left,
3819                                      int free_space, u32 right_nritems,
3820                                      u32 max_slot)
3821 {
3822         struct btrfs_disk_key disk_key;
3823         struct extent_buffer *right = path->nodes[0];
3824         int i;
3825         int push_space = 0;
3826         int push_items = 0;
3827         struct btrfs_item *item;
3828         u32 old_left_nritems;
3829         u32 nr;
3830         int ret = 0;
3831         u32 this_item_size;
3832         u32 old_left_item_size;
3833         struct btrfs_map_token token;
3834
3835         btrfs_init_map_token(&token);
3836
3837         if (empty)
3838                 nr = min(right_nritems, max_slot);
3839         else
3840                 nr = min(right_nritems - 1, max_slot);
3841
3842         for (i = 0; i < nr; i++) {
3843                 item = btrfs_item_nr(i);
3844
3845                 if (!empty && push_items > 0) {
3846                         if (path->slots[0] < i)
3847                                 break;
3848                         if (path->slots[0] == i) {
3849                                 int space = btrfs_leaf_free_space(root, right);
3850                                 if (space + push_space * 2 > free_space)
3851                                         break;
3852                         }
3853                 }
3854
3855                 if (path->slots[0] == i)
3856                         push_space += data_size;
3857
3858                 this_item_size = btrfs_item_size(right, item);
3859                 if (this_item_size + sizeof(*item) + push_space > free_space)
3860                         break;
3861
3862                 push_items++;
3863                 push_space += this_item_size + sizeof(*item);
3864         }
3865
3866         if (push_items == 0) {
3867                 ret = 1;
3868                 goto out;
3869         }
3870         WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3871
3872         /* push data from right to left */
3873         copy_extent_buffer(left, right,
3874                            btrfs_item_nr_offset(btrfs_header_nritems(left)),
3875                            btrfs_item_nr_offset(0),
3876                            push_items * sizeof(struct btrfs_item));
3877
3878         push_space = BTRFS_LEAF_DATA_SIZE(root) -
3879                      btrfs_item_offset_nr(right, push_items - 1);
3880
3881         copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3882                      leaf_data_end(root, left) - push_space,
3883                      btrfs_leaf_data(right) +
3884                      btrfs_item_offset_nr(right, push_items - 1),
3885                      push_space);
3886         old_left_nritems = btrfs_header_nritems(left);
3887         BUG_ON(old_left_nritems <= 0);
3888
3889         old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3890         for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3891                 u32 ioff;
3892
3893                 item = btrfs_item_nr(i);
3894
3895                 ioff = btrfs_token_item_offset(left, item, &token);
3896                 btrfs_set_token_item_offset(left, item,
3897                       ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3898                       &token);
3899         }
3900         btrfs_set_header_nritems(left, old_left_nritems + push_items);
3901
3902         /* fixup right node */
3903         if (push_items > right_nritems)
3904                 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3905                        right_nritems);
3906
3907         if (push_items < right_nritems) {
3908                 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3909                                                   leaf_data_end(root, right);
3910                 memmove_extent_buffer(right, btrfs_leaf_data(right) +
3911                                       BTRFS_LEAF_DATA_SIZE(root) - push_space,
3912                                       btrfs_leaf_data(right) +
3913                                       leaf_data_end(root, right), push_space);
3914
3915                 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3916                               btrfs_item_nr_offset(push_items),
3917                              (btrfs_header_nritems(right) - push_items) *
3918                              sizeof(struct btrfs_item));
3919         }
3920         right_nritems -= push_items;
3921         btrfs_set_header_nritems(right, right_nritems);
3922         push_space = BTRFS_LEAF_DATA_SIZE(root);
3923         for (i = 0; i < right_nritems; i++) {
3924                 item = btrfs_item_nr(i);
3925
3926                 push_space = push_space - btrfs_token_item_size(right,
3927                                                                 item, &token);
3928                 btrfs_set_token_item_offset(right, item, push_space, &token);
3929         }
3930
3931         btrfs_mark_buffer_dirty(left);
3932         if (right_nritems)
3933                 btrfs_mark_buffer_dirty(right);
3934         else
3935                 clean_tree_block(trans, root->fs_info, right);
3936
3937         btrfs_item_key(right, &disk_key, 0);
3938         fixup_low_keys(root->fs_info, path, &disk_key, 1);
3939
3940         /* then fixup the leaf pointer in the path */
3941         if (path->slots[0] < push_items) {
3942                 path->slots[0] += old_left_nritems;
3943                 btrfs_tree_unlock(path->nodes[0]);
3944                 free_extent_buffer(path->nodes[0]);
3945                 path->nodes[0] = left;
3946                 path->slots[1] -= 1;
3947         } else {
3948                 btrfs_tree_unlock(left);
3949                 free_extent_buffer(left);
3950                 path->slots[0] -= push_items;
3951         }
3952         BUG_ON(path->slots[0] < 0);
3953         return ret;
3954 out:
3955         btrfs_tree_unlock(left);
3956         free_extent_buffer(left);
3957         return ret;
3958 }
3959
3960 /*
3961  * push some data in the path leaf to the left, trying to free up at
3962  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3963  *
3964  * max_slot can put a limit on how far into the leaf we'll push items.  The
3965  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
3966  * items
3967  */
3968 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3969                           *root, struct btrfs_path *path, int min_data_size,
3970                           int data_size, int empty, u32 max_slot)
3971 {
3972         struct extent_buffer *right = path->nodes[0];
3973         struct extent_buffer *left;
3974         int slot;
3975         int free_space;
3976         u32 right_nritems;
3977         int ret = 0;
3978
3979         slot = path->slots[1];
3980         if (slot == 0)
3981                 return 1;
3982         if (!path->nodes[1])
3983                 return 1;
3984
3985         right_nritems = btrfs_header_nritems(right);
3986         if (right_nritems == 0)
3987                 return 1;
3988
3989         btrfs_assert_tree_locked(path->nodes[1]);
3990
3991         left = read_node_slot(root, path->nodes[1], slot - 1);
3992         if (left == NULL)
3993                 return 1;
3994
3995         btrfs_tree_lock(left);
3996         btrfs_set_lock_blocking(left);
3997
3998         free_space = btrfs_leaf_free_space(root, left);
3999         if (free_space < data_size) {
4000                 ret = 1;
4001                 goto out;
4002         }
4003
4004         /* cow and double check */
4005         ret = btrfs_cow_block(trans, root, left,
4006                               path->nodes[1], slot - 1, &left);
4007         if (ret) {
4008                 /* we hit -ENOSPC, but it isn't fatal here */
4009                 if (ret == -ENOSPC)
4010                         ret = 1;
4011                 goto out;
4012         }
4013
4014         free_space = btrfs_leaf_free_space(root, left);
4015         if (free_space < data_size) {
4016                 ret = 1;
4017                 goto out;
4018         }
4019
4020         return __push_leaf_left(trans, root, path, min_data_size,
4021                                empty, left, free_space, right_nritems,
4022                                max_slot);
4023 out:
4024         btrfs_tree_unlock(left);
4025         free_extent_buffer(left);
4026         return ret;
4027 }
4028
4029 /*
4030  * split the path's leaf in two, making sure there is at least data_size
4031  * available for the resulting leaf level of the path.
4032  */
4033 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4034                                     struct btrfs_root *root,
4035                                     struct btrfs_path *path,
4036                                     struct extent_buffer *l,
4037                                     struct extent_buffer *right,
4038                                     int slot, int mid, int nritems)
4039 {
4040         int data_copy_size;
4041         int rt_data_off;
4042         int i;
4043         struct btrfs_disk_key disk_key;
4044         struct btrfs_map_token token;
4045
4046         btrfs_init_map_token(&token);
4047
4048         nritems = nritems - mid;
4049         btrfs_set_header_nritems(right, nritems);
4050         data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
4051
4052         copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4053                            btrfs_item_nr_offset(mid),
4054                            nritems * sizeof(struct btrfs_item));
4055
4056         copy_extent_buffer(right, l,
4057                      btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
4058                      data_copy_size, btrfs_leaf_data(l) +
4059                      leaf_data_end(root, l), data_copy_size);
4060
4061         rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
4062                       btrfs_item_end_nr(l, mid);
4063
4064         for (i = 0; i < nritems; i++) {
4065                 struct btrfs_item *item = btrfs_item_nr(i);
4066                 u32 ioff;
4067
4068                 ioff = btrfs_token_item_offset(right, item, &token);
4069                 btrfs_set_token_item_offset(right, item,
4070                                             ioff + rt_data_off, &token);
4071         }
4072
4073         btrfs_set_header_nritems(l, mid);
4074         btrfs_item_key(right, &disk_key, 0);
4075         insert_ptr(trans, root, path, &disk_key, right->start,
4076                    path->slots[1] + 1, 1);
4077
4078         btrfs_mark_buffer_dirty(right);
4079         btrfs_mark_buffer_dirty(l);
4080         BUG_ON(path->slots[0] != slot);
4081
4082         if (mid <= slot) {
4083                 btrfs_tree_unlock(path->nodes[0]);
4084                 free_extent_buffer(path->nodes[0]);
4085                 path->nodes[0] = right;
4086                 path->slots[0] -= mid;
4087                 path->slots[1] += 1;
4088         } else {
4089                 btrfs_tree_unlock(right);
4090                 free_extent_buffer(right);
4091         }
4092
4093         BUG_ON(path->slots[0] < 0);
4094 }
4095
4096 /*
4097  * double splits happen when we need to insert a big item in the middle
4098  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
4099  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4100  *          A                 B                 C
4101  *
4102  * We avoid this by trying to push the items on either side of our target
4103  * into the adjacent leaves.  If all goes well we can avoid the double split
4104  * completely.
4105  */
4106 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4107                                           struct btrfs_root *root,
4108                                           struct btrfs_path *path,
4109                                           int data_size)
4110 {
4111         int ret;
4112         int progress = 0;
4113         int slot;
4114         u32 nritems;
4115         int space_needed = data_size;
4116
4117         slot = path->slots[0];
4118         if (slot < btrfs_header_nritems(path->nodes[0]))
4119                 space_needed -= btrfs_leaf_free_space(root, path->nodes[0]);
4120
4121         /*
4122          * try to push all the items after our slot into the
4123          * right leaf
4124          */
4125         ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
4126         if (ret < 0)
4127                 return ret;
4128
4129         if (ret == 0)
4130                 progress++;
4131
4132         nritems = btrfs_header_nritems(path->nodes[0]);
4133         /*
4134          * our goal is to get our slot at the start or end of a leaf.  If
4135          * we've done so we're done
4136          */
4137         if (path->slots[0] == 0 || path->slots[0] == nritems)
4138                 return 0;
4139
4140         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
4141                 return 0;
4142
4143         /* try to push all the items before our slot into the next leaf */
4144         slot = path->slots[0];
4145         ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
4146         if (ret < 0)
4147                 return ret;
4148
4149         if (ret == 0)
4150                 progress++;
4151
4152         if (progress)
4153                 return 0;
4154         return 1;
4155 }
4156
4157 /*
4158  * split the path's leaf in two, making sure there is at least data_size
4159  * available for the resulting leaf level of the path.
4160  *
4161  * returns 0 if all went well and < 0 on failure.
4162  */
4163 static noinline int split_leaf(struct btrfs_trans_handle *trans,
4164                                struct btrfs_root *root,
4165                                struct btrfs_key *ins_key,
4166                                struct btrfs_path *path, int data_size,
4167                                int extend)
4168 {
4169         struct btrfs_disk_key disk_key;
4170         struct extent_buffer *l;
4171         u32 nritems;
4172         int mid;
4173         int slot;
4174         struct extent_buffer *right;
4175         struct btrfs_fs_info *fs_info = root->fs_info;
4176         int ret = 0;
4177         int wret;
4178         int split;
4179         int num_doubles = 0;
4180         int tried_avoid_double = 0;
4181
4182         l = path->nodes[0];
4183         slot = path->slots[0];
4184         if (extend && data_size + btrfs_item_size_nr(l, slot) +
4185             sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
4186                 return -EOVERFLOW;
4187
4188         /* first try to make some room by pushing left and right */
4189         if (data_size && path->nodes[1]) {
4190                 int space_needed = data_size;
4191
4192                 if (slot < btrfs_header_nritems(l))
4193                         space_needed -= btrfs_leaf_free_space(root, l);
4194
4195                 wret = push_leaf_right(trans, root, path, space_needed,
4196                                        space_needed, 0, 0);
4197                 if (wret < 0)
4198                         return wret;
4199                 if (wret) {
4200                         wret = push_leaf_left(trans, root, path, space_needed,
4201                                               space_needed, 0, (u32)-1);
4202                         if (wret < 0)
4203                                 return wret;
4204                 }
4205                 l = path->nodes[0];
4206
4207                 /* did the pushes work? */
4208                 if (btrfs_leaf_free_space(root, l) >= data_size)
4209                         return 0;
4210         }
4211
4212         if (!path->nodes[1]) {
4213                 ret = insert_new_root(trans, root, path, 1);
4214                 if (ret)
4215                         return ret;
4216         }
4217 again:
4218         split = 1;
4219         l = path->nodes[0];
4220         slot = path->slots[0];
4221         nritems = btrfs_header_nritems(l);
4222         mid = (nritems + 1) / 2;
4223
4224         if (mid <= slot) {
4225                 if (nritems == 1 ||
4226                     leaf_space_used(l, mid, nritems - mid) + data_size >
4227                         BTRFS_LEAF_DATA_SIZE(root)) {
4228                         if (slot >= nritems) {
4229                                 split = 0;
4230                         } else {
4231                                 mid = slot;
4232                                 if (mid != nritems &&
4233                                     leaf_space_used(l, mid, nritems - mid) +
4234                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
4235                                         if (data_size && !tried_avoid_double)
4236                                                 goto push_for_double;
4237                                         split = 2;
4238                                 }
4239                         }
4240                 }
4241         } else {
4242                 if (leaf_space_used(l, 0, mid) + data_size >
4243                         BTRFS_LEAF_DATA_SIZE(root)) {
4244                         if (!extend && data_size && slot == 0) {
4245                                 split = 0;
4246                         } else if ((extend || !data_size) && slot == 0) {
4247                                 mid = 1;
4248                         } else {
4249                                 mid = slot;
4250                                 if (mid != nritems &&
4251                                     leaf_space_used(l, mid, nritems - mid) +
4252                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
4253                                         if (data_size && !tried_avoid_double)
4254                                                 goto push_for_double;
4255                                         split = 2;
4256                                 }
4257                         }
4258                 }
4259         }
4260
4261         if (split == 0)
4262                 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4263         else
4264                 btrfs_item_key(l, &disk_key, mid);
4265
4266         right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
4267                         &disk_key, 0, l->start, 0);
4268         if (IS_ERR(right))
4269                 return PTR_ERR(right);
4270
4271         root_add_used(root, root->nodesize);
4272
4273         memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
4274         btrfs_set_header_bytenr(right, right->start);
4275         btrfs_set_header_generation(right, trans->transid);
4276         btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
4277         btrfs_set_header_owner(right, root->root_key.objectid);
4278         btrfs_set_header_level(right, 0);
4279         write_extent_buffer(right, fs_info->fsid,
4280                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
4281
4282         write_extent_buffer(right, fs_info->chunk_tree_uuid,
4283                             btrfs_header_chunk_tree_uuid(right),
4284                             BTRFS_UUID_SIZE);
4285
4286         if (split == 0) {
4287                 if (mid <= slot) {
4288                         btrfs_set_header_nritems(right, 0);
4289                         insert_ptr(trans, root, path, &disk_key, right->start,
4290                                    path->slots[1] + 1, 1);
4291                         btrfs_tree_unlock(path->nodes[0]);
4292                         free_extent_buffer(path->nodes[0]);
4293                         path->nodes[0] = right;
4294                         path->slots[0] = 0;
4295                         path->slots[1] += 1;
4296                 } else {
4297                         btrfs_set_header_nritems(right, 0);
4298                         insert_ptr(trans, root, path, &disk_key, right->start,
4299                                           path->slots[1], 1);
4300                         btrfs_tree_unlock(path->nodes[0]);
4301                         free_extent_buffer(path->nodes[0]);
4302                         path->nodes[0] = right;
4303                         path->slots[0] = 0;
4304                         if (path->slots[1] == 0)
4305                                 fixup_low_keys(fs_info, path, &disk_key, 1);
4306                 }
4307                 btrfs_mark_buffer_dirty(right);
4308                 return ret;
4309         }
4310
4311         copy_for_split(trans, root, path, l, right, slot, mid, nritems);
4312
4313         if (split == 2) {
4314                 BUG_ON(num_doubles != 0);
4315                 num_doubles++;
4316                 goto again;
4317         }
4318
4319         return 0;
4320
4321 push_for_double:
4322         push_for_double_split(trans, root, path, data_size);
4323         tried_avoid_double = 1;
4324         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
4325                 return 0;
4326         goto again;
4327 }
4328
4329 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4330                                          struct btrfs_root *root,
4331                                          struct btrfs_path *path, int ins_len)
4332 {
4333         struct btrfs_key key;
4334         struct extent_buffer *leaf;
4335         struct btrfs_file_extent_item *fi;
4336         u64 extent_len = 0;
4337         u32 item_size;
4338         int ret;
4339
4340         leaf = path->nodes[0];
4341         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4342
4343         BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4344                key.type != BTRFS_EXTENT_CSUM_KEY);
4345
4346         if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4347                 return 0;
4348
4349         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4350         if (key.type == BTRFS_EXTENT_DATA_KEY) {
4351                 fi = btrfs_item_ptr(leaf, path->slots[0],
4352                                     struct btrfs_file_extent_item);
4353                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4354         }
4355         btrfs_release_path(path);
4356
4357         path->keep_locks = 1;
4358         path->search_for_split = 1;
4359         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4360         path->search_for_split = 0;
4361         if (ret > 0)
4362                 ret = -EAGAIN;
4363         if (ret < 0)
4364                 goto err;
4365
4366         ret = -EAGAIN;
4367         leaf = path->nodes[0];
4368         /* if our item isn't there, return now */
4369         if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4370                 goto err;
4371
4372         /* the leaf has  changed, it now has room.  return now */
4373         if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4374                 goto err;
4375
4376         if (key.type == BTRFS_EXTENT_DATA_KEY) {
4377                 fi = btrfs_item_ptr(leaf, path->slots[0],
4378                                     struct btrfs_file_extent_item);
4379                 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4380                         goto err;
4381         }
4382
4383         btrfs_set_path_blocking(path);
4384         ret = split_leaf(trans, root, &key, path, ins_len, 1);
4385         if (ret)
4386                 goto err;
4387
4388         path->keep_locks = 0;
4389         btrfs_unlock_up_safe(path, 1);
4390         return 0;
4391 err:
4392         path->keep_locks = 0;
4393         return ret;
4394 }
4395
4396 static noinline int split_item(struct btrfs_trans_handle *trans,
4397                                struct btrfs_root *root,
4398                                struct btrfs_path *path,
4399                                struct btrfs_key *new_key,
4400                                unsigned long split_offset)
4401 {
4402         struct extent_buffer *leaf;
4403         struct btrfs_item *item;
4404         struct btrfs_item *new_item;
4405         int slot;
4406         char *buf;
4407         u32 nritems;
4408         u32 item_size;
4409         u32 orig_offset;
4410         struct btrfs_disk_key disk_key;
4411
4412         leaf = path->nodes[0];
4413         BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4414
4415         btrfs_set_path_blocking(path);
4416
4417         item = btrfs_item_nr(path->slots[0]);
4418         orig_offset = btrfs_item_offset(leaf, item);
4419         item_size = btrfs_item_size(leaf, item);
4420
4421         buf = kmalloc(item_size, GFP_NOFS);
4422         if (!buf)
4423                 return -ENOMEM;
4424
4425         read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4426                             path->slots[0]), item_size);
4427
4428         slot = path->slots[0] + 1;
4429         nritems = btrfs_header_nritems(leaf);
4430         if (slot != nritems) {
4431                 /* shift the items */
4432                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4433                                 btrfs_item_nr_offset(slot),
4434                                 (nritems - slot) * sizeof(struct btrfs_item));
4435         }
4436
4437         btrfs_cpu_key_to_disk(&disk_key, new_key);
4438         btrfs_set_item_key(leaf, &disk_key, slot);
4439
4440         new_item = btrfs_item_nr(slot);
4441
4442         btrfs_set_item_offset(leaf, new_item, orig_offset);
4443         btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4444
4445         btrfs_set_item_offset(leaf, item,
4446                               orig_offset + item_size - split_offset);
4447         btrfs_set_item_size(leaf, item, split_offset);
4448
4449         btrfs_set_header_nritems(leaf, nritems + 1);
4450
4451         /* write the data for the start of the original item */
4452         write_extent_buffer(leaf, buf,
4453                             btrfs_item_ptr_offset(leaf, path->slots[0]),
4454                             split_offset);
4455
4456         /* write the data for the new item */
4457         write_extent_buffer(leaf, buf + split_offset,
4458                             btrfs_item_ptr_offset(leaf, slot),
4459                             item_size - split_offset);
4460         btrfs_mark_buffer_dirty(leaf);
4461
4462         BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4463         kfree(buf);
4464         return 0;
4465 }
4466
4467 /*
4468  * This function splits a single item into two items,
4469  * giving 'new_key' to the new item and splitting the
4470  * old one at split_offset (from the start of the item).
4471  *
4472  * The path may be released by this operation.  After
4473  * the split, the path is pointing to the old item.  The
4474  * new item is going to be in the same node as the old one.
4475  *
4476  * Note, the item being split must be smaller enough to live alone on
4477  * a tree block with room for one extra struct btrfs_item
4478  *
4479  * This allows us to split the item in place, keeping a lock on the
4480  * leaf the entire time.
4481  */
4482 int btrfs_split_item(struct btrfs_trans_handle *trans,
4483                      struct btrfs_root *root,
4484                      struct btrfs_path *path,
4485                      struct btrfs_key *new_key,
4486                      unsigned long split_offset)
4487 {
4488         int ret;
4489         ret = setup_leaf_for_split(trans, root, path,
4490                                    sizeof(struct btrfs_item));
4491         if (ret)
4492                 return ret;
4493
4494         ret = split_item(trans, root, path, new_key, split_offset);
4495         return ret;
4496 }
4497
4498 /*
4499  * This function duplicate a item, giving 'new_key' to the new item.
4500  * It guarantees both items live in the same tree leaf and the new item
4501  * is contiguous with the original item.
4502  *
4503  * This allows us to split file extent in place, keeping a lock on the
4504  * leaf the entire time.
4505  */
4506 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4507                          struct btrfs_root *root,
4508                          struct btrfs_path *path,
4509                          struct btrfs_key *new_key)
4510 {
4511         struct extent_buffer *leaf;
4512         int ret;
4513         u32 item_size;
4514
4515         leaf = path->nodes[0];
4516         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4517         ret = setup_leaf_for_split(trans, root, path,
4518                                    item_size + sizeof(struct btrfs_item));
4519         if (ret)
4520                 return ret;
4521
4522         path->slots[0]++;
4523         setup_items_for_insert(root, path, new_key, &item_size,
4524                                item_size, item_size +
4525                                sizeof(struct btrfs_item), 1);
4526         leaf = path->nodes[0];
4527         memcpy_extent_buffer(leaf,
4528                              btrfs_item_ptr_offset(leaf, path->slots[0]),
4529                              btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4530                              item_size);
4531         return 0;
4532 }
4533
4534 /*
4535  * make the item pointed to by the path smaller.  new_size indicates
4536  * how small to make it, and from_end tells us if we just chop bytes
4537  * off the end of the item or if we shift the item to chop bytes off
4538  * the front.
4539  */
4540 void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4541                          u32 new_size, int from_end)
4542 {
4543         int slot;
4544         struct extent_buffer *leaf;
4545         struct btrfs_item *item;
4546         u32 nritems;
4547         unsigned int data_end;
4548         unsigned int old_data_start;
4549         unsigned int old_size;
4550         unsigned int size_diff;
4551         int i;
4552         struct btrfs_map_token token;
4553
4554         btrfs_init_map_token(&token);
4555
4556         leaf = path->nodes[0];
4557         slot = path->slots[0];
4558
4559         old_size = btrfs_item_size_nr(leaf, slot);
4560         if (old_size == new_size)
4561                 return;
4562
4563         nritems = btrfs_header_nritems(leaf);
4564         data_end = leaf_data_end(root, leaf);
4565
4566         old_data_start = btrfs_item_offset_nr(leaf, slot);
4567
4568         size_diff = old_size - new_size;
4569
4570         BUG_ON(slot < 0);
4571         BUG_ON(slot >= nritems);
4572
4573         /*
4574          * item0..itemN ... dataN.offset..dataN.size .. data0.size
4575          */
4576         /* first correct the data pointers */
4577         for (i = slot; i < nritems; i++) {
4578                 u32 ioff;
4579                 item = btrfs_item_nr(i);
4580
4581                 ioff = btrfs_token_item_offset(leaf, item, &token);
4582                 btrfs_set_token_item_offset(leaf, item,
4583                                             ioff + size_diff, &token);
4584         }
4585
4586         /* shift the data */
4587         if (from_end) {
4588                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4589                               data_end + size_diff, btrfs_leaf_data(leaf) +
4590                               data_end, old_data_start + new_size - data_end);
4591         } else {
4592                 struct btrfs_disk_key disk_key;
4593                 u64 offset;
4594
4595                 btrfs_item_key(leaf, &disk_key, slot);
4596
4597                 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4598                         unsigned long ptr;
4599                         struct btrfs_file_extent_item *fi;
4600
4601                         fi = btrfs_item_ptr(leaf, slot,
4602                                             struct btrfs_file_extent_item);
4603                         fi = (struct btrfs_file_extent_item *)(
4604                              (unsigned long)fi - size_diff);
4605
4606                         if (btrfs_file_extent_type(leaf, fi) ==
4607                             BTRFS_FILE_EXTENT_INLINE) {
4608                                 ptr = btrfs_item_ptr_offset(leaf, slot);
4609                                 memmove_extent_buffer(leaf, ptr,
4610                                       (unsigned long)fi,
4611                                       BTRFS_FILE_EXTENT_INLINE_DATA_START);
4612                         }
4613                 }
4614
4615                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4616                               data_end + size_diff, btrfs_leaf_data(leaf) +
4617                               data_end, old_data_start - data_end);
4618
4619                 offset = btrfs_disk_key_offset(&disk_key);
4620                 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4621                 btrfs_set_item_key(leaf, &disk_key, slot);
4622                 if (slot == 0)
4623                         fixup_low_keys(root->fs_info, path, &disk_key, 1);
4624         }
4625
4626         item = btrfs_item_nr(slot);
4627         btrfs_set_item_size(leaf, item, new_size);
4628         btrfs_mark_buffer_dirty(leaf);
4629
4630         if (btrfs_leaf_free_space(root, leaf) < 0) {
4631                 btrfs_print_leaf(root, leaf);
4632                 BUG();
4633         }
4634 }
4635
4636 /*
4637  * make the item pointed to by the path bigger, data_size is the added size.
4638  */
4639 void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
4640                        u32 data_size)
4641 {
4642         int slot;
4643         struct extent_buffer *leaf;
4644         struct btrfs_item *item;
4645         u32 nritems;
4646         unsigned int data_end;
4647         unsigned int old_data;
4648         unsigned int old_size;
4649         int i;
4650         struct btrfs_map_token token;
4651
4652         btrfs_init_map_token(&token);
4653
4654         leaf = path->nodes[0];
4655
4656         nritems = btrfs_header_nritems(leaf);
4657         data_end = leaf_data_end(root, leaf);
4658
4659         if (btrfs_leaf_free_space(root, leaf) < data_size) {
4660                 btrfs_print_leaf(root, leaf);
4661                 BUG();
4662         }
4663         slot = path->slots[0];
4664         old_data = btrfs_item_end_nr(leaf, slot);
4665
4666         BUG_ON(slot < 0);
4667         if (slot >= nritems) {
4668                 btrfs_print_leaf(root, leaf);
4669                 btrfs_crit(root->fs_info, "slot %d too large, nritems %d",
4670                        slot, nritems);
4671                 BUG_ON(1);
4672         }
4673
4674         /*
4675          * item0..itemN ... dataN.offset..dataN.size .. data0.size
4676          */
4677         /* first correct the data pointers */
4678         for (i = slot; i < nritems; i++) {
4679                 u32 ioff;
4680                 item = btrfs_item_nr(i);
4681
4682                 ioff = btrfs_token_item_offset(leaf, item, &token);
4683                 btrfs_set_token_item_offset(leaf, item,
4684                                             ioff - data_size, &token);
4685         }
4686
4687         /* shift the data */
4688         memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4689                       data_end - data_size, btrfs_leaf_data(leaf) +
4690                       data_end, old_data - data_end);
4691
4692         data_end = old_data;
4693         old_size = btrfs_item_size_nr(leaf, slot);
4694         item = btrfs_item_nr(slot);
4695         btrfs_set_item_size(leaf, item, old_size + data_size);
4696         btrfs_mark_buffer_dirty(leaf);
4697
4698         if (btrfs_leaf_free_space(root, leaf) < 0) {
4699                 btrfs_print_leaf(root, leaf);
4700                 BUG();
4701         }
4702 }
4703
4704 /*
4705  * this is a helper for btrfs_insert_empty_items, the main goal here is
4706  * to save stack depth by doing the bulk of the work in a function
4707  * that doesn't call btrfs_search_slot
4708  */
4709 void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4710                             struct btrfs_key *cpu_key, u32 *data_size,
4711                             u32 total_data, u32 total_size, int nr)
4712 {
4713         struct btrfs_item *item;
4714         int i;
4715         u32 nritems;
4716         unsigned int data_end;
4717         struct btrfs_disk_key disk_key;
4718         struct extent_buffer *leaf;
4719         int slot;
4720         struct btrfs_map_token token;
4721
4722         if (path->slots[0] == 0) {
4723                 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4724                 fixup_low_keys(root->fs_info, path, &disk_key, 1);
4725         }
4726         btrfs_unlock_up_safe(path, 1);
4727
4728         btrfs_init_map_token(&token);
4729
4730         leaf = path->nodes[0];
4731         slot = path->slots[0];
4732
4733         nritems = btrfs_header_nritems(leaf);
4734         data_end = leaf_data_end(root, leaf);
4735
4736         if (btrfs_leaf_free_space(root, leaf) < total_size) {
4737                 btrfs_print_leaf(root, leaf);
4738                 btrfs_crit(root->fs_info, "not enough freespace need %u have %d",
4739                        total_size, btrfs_leaf_free_space(root, leaf));
4740                 BUG();
4741         }
4742
4743         if (slot != nritems) {
4744                 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4745
4746                 if (old_data < data_end) {
4747                         btrfs_print_leaf(root, leaf);
4748                         btrfs_crit(root->fs_info, "slot %d old_data %d data_end %d",
4749                                slot, old_data, data_end);
4750                         BUG_ON(1);
4751                 }
4752                 /*
4753                  * item0..itemN ... dataN.offset..dataN.size .. data0.size
4754                  */
4755                 /* first correct the data pointers */
4756                 for (i = slot; i < nritems; i++) {
4757                         u32 ioff;
4758
4759                         item = btrfs_item_nr( i);
4760                         ioff = btrfs_token_item_offset(leaf, item, &token);
4761                         btrfs_set_token_item_offset(leaf, item,
4762                                                     ioff - total_data, &token);
4763                 }
4764                 /* shift the items */
4765                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4766                               btrfs_item_nr_offset(slot),
4767                               (nritems - slot) * sizeof(struct btrfs_item));
4768
4769                 /* shift the data */
4770                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4771                               data_end - total_data, btrfs_leaf_data(leaf) +
4772                               data_end, old_data - data_end);
4773                 data_end = old_data;
4774         }
4775
4776         /* setup the item for the new data */
4777         for (i = 0; i < nr; i++) {
4778                 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4779                 btrfs_set_item_key(leaf, &disk_key, slot + i);
4780                 item = btrfs_item_nr(slot + i);
4781                 btrfs_set_token_item_offset(leaf, item,
4782                                             data_end - data_size[i], &token);
4783                 data_end -= data_size[i];
4784                 btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4785         }
4786
4787         btrfs_set_header_nritems(leaf, nritems + nr);
4788         btrfs_mark_buffer_dirty(leaf);
4789
4790         if (btrfs_leaf_free_space(root, leaf) < 0) {
4791                 btrfs_print_leaf(root, leaf);
4792                 BUG();
4793         }
4794 }
4795
4796 /*
4797  * Given a key and some data, insert items into the tree.
4798  * This does all the path init required, making room in the tree if needed.
4799  */
4800 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4801                             struct btrfs_root *root,
4802                             struct btrfs_path *path,
4803                             struct btrfs_key *cpu_key, u32 *data_size,
4804                             int nr)
4805 {
4806         int ret = 0;
4807         int slot;
4808         int i;
4809         u32 total_size = 0;
4810         u32 total_data = 0;
4811
4812         for (i = 0; i < nr; i++)
4813                 total_data += data_size[i];
4814
4815         total_size = total_data + (nr * sizeof(struct btrfs_item));
4816         ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4817         if (ret == 0)
4818                 return -EEXIST;
4819         if (ret < 0)
4820                 return ret;
4821
4822         slot = path->slots[0];
4823         BUG_ON(slot < 0);
4824
4825         setup_items_for_insert(root, path, cpu_key, data_size,
4826                                total_data, total_size, nr);
4827         return 0;
4828 }
4829
4830 /*
4831  * Given a key and some data, insert an item into the tree.
4832  * This does all the path init required, making room in the tree if needed.
4833  */
4834 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4835                       *root, struct btrfs_key *cpu_key, void *data, u32
4836                       data_size)
4837 {
4838         int ret = 0;
4839         struct btrfs_path *path;
4840         struct extent_buffer *leaf;
4841         unsigned long ptr;
4842
4843         path = btrfs_alloc_path();
4844         if (!path)
4845                 return -ENOMEM;
4846         ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4847         if (!ret) {
4848                 leaf = path->nodes[0];
4849                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4850                 write_extent_buffer(leaf, data, ptr, data_size);
4851                 btrfs_mark_buffer_dirty(leaf);
4852         }
4853         btrfs_free_path(path);
4854         return ret;
4855 }
4856
4857 /*
4858  * delete the pointer from a given node.
4859  *
4860  * the tree should have been previously balanced so the deletion does not
4861  * empty a node.
4862  */
4863 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4864                     int level, int slot)
4865 {
4866         struct extent_buffer *parent = path->nodes[level];
4867         u32 nritems;
4868         int ret;
4869
4870         nritems = btrfs_header_nritems(parent);
4871         if (slot != nritems - 1) {
4872                 if (level)
4873                         tree_mod_log_eb_move(root->fs_info, parent, slot,
4874                                              slot + 1, nritems - slot - 1);
4875                 memmove_extent_buffer(parent,
4876                               btrfs_node_key_ptr_offset(slot),
4877                               btrfs_node_key_ptr_offset(slot + 1),
4878                               sizeof(struct btrfs_key_ptr) *
4879                               (nritems - slot - 1));
4880         } else if (level) {
4881                 ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4882                                               MOD_LOG_KEY_REMOVE, GFP_NOFS);
4883                 BUG_ON(ret < 0);
4884         }
4885
4886         nritems--;
4887         btrfs_set_header_nritems(parent, nritems);
4888         if (nritems == 0 && parent == root->node) {
4889                 BUG_ON(btrfs_header_level(root->node) != 1);
4890                 /* just turn the root into a leaf and break */
4891                 btrfs_set_header_level(root->node, 0);
4892         } else if (slot == 0) {
4893                 struct btrfs_disk_key disk_key;
4894
4895                 btrfs_node_key(parent, &disk_key, 0);
4896                 fixup_low_keys(root->fs_info, path, &disk_key, level + 1);
4897         }
4898         btrfs_mark_buffer_dirty(parent);
4899 }
4900
4901 /*
4902  * a helper function to delete the leaf pointed to by path->slots[1] and
4903  * path->nodes[1].
4904  *
4905  * This deletes the pointer in path->nodes[1] and frees the leaf
4906  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4907  *
4908  * The path must have already been setup for deleting the leaf, including
4909  * all the proper balancing.  path->nodes[1] must be locked.
4910  */
4911 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4912                                     struct btrfs_root *root,
4913                                     struct btrfs_path *path,
4914                                     struct extent_buffer *leaf)
4915 {
4916         WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4917         del_ptr(root, path, 1, path->slots[1]);
4918
4919         /*
4920          * btrfs_free_extent is expensive, we want to make sure we
4921          * aren't holding any locks when we call it
4922          */
4923         btrfs_unlock_up_safe(path, 0);
4924
4925         root_sub_used(root, leaf->len);
4926
4927         extent_buffer_get(leaf);
4928         btrfs_free_tree_block(trans, root, leaf, 0, 1);
4929         free_extent_buffer_stale(leaf);
4930 }
4931 /*
4932  * delete the item at the leaf level in path.  If that empties
4933  * the leaf, remove it from the tree
4934  */
4935 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4936                     struct btrfs_path *path, int slot, int nr)
4937 {
4938         struct extent_buffer *leaf;
4939         struct btrfs_item *item;
4940         u32 last_off;
4941         u32 dsize = 0;
4942         int ret = 0;
4943         int wret;
4944         int i;
4945         u32 nritems;
4946         struct btrfs_map_token token;
4947
4948         btrfs_init_map_token(&token);
4949
4950         leaf = path->nodes[0];
4951         last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4952
4953         for (i = 0; i < nr; i++)
4954                 dsize += btrfs_item_size_nr(leaf, slot + i);
4955
4956         nritems = btrfs_header_nritems(leaf);
4957
4958         if (slot + nr != nritems) {
4959                 int data_end = leaf_data_end(root, leaf);
4960
4961                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4962                               data_end + dsize,
4963                               btrfs_leaf_data(leaf) + data_end,
4964                               last_off - data_end);
4965
4966                 for (i = slot + nr; i < nritems; i++) {
4967                         u32 ioff;
4968
4969                         item = btrfs_item_nr(i);
4970                         ioff = btrfs_token_item_offset(leaf, item, &token);
4971                         btrfs_set_token_item_offset(leaf, item,
4972                                                     ioff + dsize, &token);
4973                 }
4974
4975                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
4976                               btrfs_item_nr_offset(slot + nr),
4977                               sizeof(struct btrfs_item) *
4978                               (nritems - slot - nr));
4979         }
4980         btrfs_set_header_nritems(leaf, nritems - nr);
4981         nritems -= nr;
4982
4983         /* delete the leaf if we've emptied it */
4984         if (nritems == 0) {
4985                 if (leaf == root->node) {
4986                         btrfs_set_header_level(leaf, 0);
4987                 } else {
4988                         btrfs_set_path_blocking(path);
4989                         clean_tree_block(trans, root->fs_info, leaf);
4990                         btrfs_del_leaf(trans, root, path, leaf);
4991                 }
4992         } else {
4993                 int used = leaf_space_used(leaf, 0, nritems);
4994                 if (slot == 0) {
4995                         struct btrfs_disk_key disk_key;
4996
4997                         btrfs_item_key(leaf, &disk_key, 0);
4998                         fixup_low_keys(root->fs_info, path, &disk_key, 1);
4999                 }
5000
5001                 /* delete the leaf if it is mostly empty */
5002                 if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
5003                         /* push_leaf_left fixes the path.
5004                          * make sure the path still points to our leaf
5005                          * for possible call to del_ptr below
5006                          */
5007                         slot = path->slots[1];
5008                         extent_buffer_get(leaf);
5009
5010                         btrfs_set_path_blocking(path);
5011                         wret = push_leaf_left(trans, root, path, 1, 1,
5012                                               1, (u32)-1);
5013                         if (wret < 0 && wret != -ENOSPC)
5014                                 ret = wret;
5015
5016                         if (path->nodes[0] == leaf &&
5017                             btrfs_header_nritems(leaf)) {
5018                                 wret = push_leaf_right(trans, root, path, 1,
5019                                                        1, 1, 0);
5020                                 if (wret < 0 && wret != -ENOSPC)
5021                                         ret = wret;
5022                         }
5023
5024                         if (btrfs_header_nritems(leaf) == 0) {
5025                                 path->slots[1] = slot;
5026                                 btrfs_del_leaf(trans, root, path, leaf);
5027                                 free_extent_buffer(leaf);
5028                                 ret = 0;
5029                         } else {
5030                                 /* if we're still in the path, make sure
5031                                  * we're dirty.  Otherwise, one of the
5032                                  * push_leaf functions must have already
5033                                  * dirtied this buffer
5034                                  */
5035                                 if (path->nodes[0] == leaf)
5036                                         btrfs_mark_buffer_dirty(leaf);
5037                                 free_extent_buffer(leaf);
5038                         }
5039                 } else {
5040                         btrfs_mark_buffer_dirty(leaf);
5041                 }
5042         }
5043         return ret;
5044 }
5045
5046 /*
5047  * search the tree again to find a leaf with lesser keys
5048  * returns 0 if it found something or 1 if there are no lesser leaves.
5049  * returns < 0 on io errors.
5050  *
5051  * This may release the path, and so you may lose any locks held at the
5052  * time you call it.
5053  */
5054 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
5055 {
5056         struct btrfs_key key;
5057         struct btrfs_disk_key found_key;
5058         int ret;
5059
5060         btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5061
5062         if (key.offset > 0) {
5063                 key.offset--;
5064         } else if (key.type > 0) {
5065                 key.type--;
5066                 key.offset = (u64)-1;
5067         } else if (key.objectid > 0) {
5068                 key.objectid--;
5069                 key.type = (u8)-1;
5070                 key.offset = (u64)-1;
5071         } else {
5072                 return 1;
5073         }
5074
5075         btrfs_release_path(path);
5076         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5077         if (ret < 0)
5078                 return ret;
5079         btrfs_item_key(path->nodes[0], &found_key, 0);
5080         ret = comp_keys(&found_key, &key);
5081         /*
5082          * We might have had an item with the previous key in the tree right
5083          * before we released our path. And after we released our path, that
5084          * item might have been pushed to the first slot (0) of the leaf we
5085          * were holding due to a tree balance. Alternatively, an item with the
5086          * previous key can exist as the only element of a leaf (big fat item).
5087          * Therefore account for these 2 cases, so that our callers (like
5088          * btrfs_previous_item) don't miss an existing item with a key matching
5089          * the previous key we computed above.
5090          */
5091         if (ret <= 0)
5092                 return 0;
5093         return 1;
5094 }
5095
5096 /*
5097  * A helper function to walk down the tree starting at min_key, and looking
5098  * for nodes or leaves that are have a minimum transaction id.
5099  * This is used by the btree defrag code, and tree logging
5100  *
5101  * This does not cow, but it does stuff the starting key it finds back
5102  * into min_key, so you can call btrfs_search_slot with cow=1 on the
5103  * key and get a writable path.
5104  *
5105  * This does lock as it descends, and path->keep_locks should be set
5106  * to 1 by the caller.
5107  *
5108  * This honors path->lowest_level to prevent descent past a given level
5109  * of the tree.
5110  *
5111  * min_trans indicates the oldest transaction that you are interested
5112  * in walking through.  Any nodes or leaves older than min_trans are
5113  * skipped over (without reading them).
5114  *
5115  * returns zero if something useful was found, < 0 on error and 1 if there
5116  * was nothing in the tree that matched the search criteria.
5117  */
5118 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5119                          struct btrfs_path *path,
5120                          u64 min_trans)
5121 {
5122         struct extent_buffer *cur;
5123         struct btrfs_key found_key;
5124         int slot;
5125         int sret;
5126         u32 nritems;
5127         int level;
5128         int ret = 1;
5129         int keep_locks = path->keep_locks;
5130
5131         path->keep_locks = 1;
5132 again:
5133         cur = btrfs_read_lock_root_node(root);
5134         level = btrfs_header_level(cur);
5135         WARN_ON(path->nodes[level]);
5136         path->nodes[level] = cur;
5137         path->locks[level] = BTRFS_READ_LOCK;
5138
5139         if (btrfs_header_generation(cur) < min_trans) {
5140                 ret = 1;
5141                 goto out;
5142         }
5143         while (1) {
5144                 nritems = btrfs_header_nritems(cur);
5145                 level = btrfs_header_level(cur);
5146                 sret = bin_search(cur, min_key, level, &slot);
5147
5148                 /* at the lowest level, we're done, setup the path and exit */
5149                 if (level == path->lowest_level) {
5150                         if (slot >= nritems)
5151                                 goto find_next_key;
5152                         ret = 0;
5153                         path->slots[level] = slot;
5154                         btrfs_item_key_to_cpu(cur, &found_key, slot);
5155                         goto out;
5156                 }
5157                 if (sret && slot > 0)
5158                         slot--;
5159                 /*
5160                  * check this node pointer against the min_trans parameters.
5161                  * If it is too old, old, skip to the next one.
5162                  */
5163                 while (slot < nritems) {
5164                         u64 gen;
5165
5166                         gen = btrfs_node_ptr_generation(cur, slot);
5167                         if (gen < min_trans) {
5168                                 slot++;
5169                                 continue;
5170                         }
5171                         break;
5172                 }
5173 find_next_key:
5174                 /*
5175                  * we didn't find a candidate key in this node, walk forward
5176                  * and find another one
5177                  */
5178                 if (slot >= nritems) {
5179                         path->slots[level] = slot;
5180                         btrfs_set_path_blocking(path);
5181                         sret = btrfs_find_next_key(root, path, min_key, level,
5182                                                   min_trans);
5183                         if (sret == 0) {
5184                                 btrfs_release_path(path);
5185                                 goto again;
5186                         } else {
5187                                 goto out;
5188                         }
5189                 }
5190                 /* save our key for returning back */
5191                 btrfs_node_key_to_cpu(cur, &found_key, slot);
5192                 path->slots[level] = slot;
5193                 if (level == path->lowest_level) {
5194                         ret = 0;
5195                         goto out;
5196                 }
5197                 btrfs_set_path_blocking(path);
5198                 cur = read_node_slot(root, cur, slot);
5199                 BUG_ON(!cur); /* -ENOMEM */
5200
5201                 btrfs_tree_read_lock(cur);
5202
5203                 path->locks[level - 1] = BTRFS_READ_LOCK;
5204                 path->nodes[level - 1] = cur;
5205                 unlock_up(path, level, 1, 0, NULL);
5206                 btrfs_clear_path_blocking(path, NULL, 0);
5207         }
5208 out:
5209         path->keep_locks = keep_locks;
5210         if (ret == 0) {
5211                 btrfs_unlock_up_safe(path, path->lowest_level + 1);
5212                 btrfs_set_path_blocking(path);
5213                 memcpy(min_key, &found_key, sizeof(found_key));
5214         }
5215         return ret;
5216 }
5217
5218 static void tree_move_down(struct btrfs_root *root,
5219                            struct btrfs_path *path,
5220                            int *level, int root_level)
5221 {
5222         BUG_ON(*level == 0);
5223         path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
5224                                         path->slots[*level]);
5225         path->slots[*level - 1] = 0;
5226         (*level)--;
5227 }
5228
5229 static int tree_move_next_or_upnext(struct btrfs_root *root,
5230                                     struct btrfs_path *path,
5231                                     int *level, int root_level)
5232 {
5233         int ret = 0;
5234         int nritems;
5235         nritems = btrfs_header_nritems(path->nodes[*level]);
5236
5237         path->slots[*level]++;
5238
5239         while (path->slots[*level] >= nritems) {
5240                 if (*level == root_level)
5241                         return -1;
5242
5243                 /* move upnext */
5244                 path->slots[*level] = 0;
5245                 free_extent_buffer(path->nodes[*level]);
5246                 path->nodes[*level] = NULL;
5247                 (*level)++;
5248                 path->slots[*level]++;
5249
5250                 nritems = btrfs_header_nritems(path->nodes[*level]);
5251                 ret = 1;
5252         }
5253         return ret;
5254 }
5255
5256 /*
5257  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
5258  * or down.
5259  */
5260 static int tree_advance(struct btrfs_root *root,
5261                         struct btrfs_path *path,
5262                         int *level, int root_level,
5263                         int allow_down,
5264                         struct btrfs_key *key)
5265 {
5266         int ret;
5267
5268         if (*level == 0 || !allow_down) {
5269                 ret = tree_move_next_or_upnext(root, path, level, root_level);
5270         } else {
5271                 tree_move_down(root, path, level, root_level);
5272                 ret = 0;
5273         }
5274         if (ret >= 0) {
5275                 if (*level == 0)
5276                         btrfs_item_key_to_cpu(path->nodes[*level], key,
5277                                         path->slots[*level]);
5278                 else
5279                         btrfs_node_key_to_cpu(path->nodes[*level], key,
5280                                         path->slots[*level]);
5281         }
5282         return ret;
5283 }
5284
5285 static int tree_compare_item(struct btrfs_root *left_root,
5286                              struct btrfs_path *left_path,
5287                              struct btrfs_path *right_path,
5288                              char *tmp_buf)
5289 {
5290         int cmp;
5291         int len1, len2;
5292         unsigned long off1, off2;
5293
5294         len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
5295         len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
5296         if (len1 != len2)
5297                 return 1;
5298
5299         off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
5300         off2 = btrfs_item_ptr_offset(right_path->nodes[0],
5301                                 right_path->slots[0]);
5302
5303         read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
5304
5305         cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
5306         if (cmp)
5307                 return 1;
5308         return 0;
5309 }
5310
5311 #define ADVANCE 1
5312 #define ADVANCE_ONLY_NEXT -1
5313
5314 /*
5315  * This function compares two trees and calls the provided callback for
5316  * every changed/new/deleted item it finds.
5317  * If shared tree blocks are encountered, whole subtrees are skipped, making
5318  * the compare pretty fast on snapshotted subvolumes.
5319  *
5320  * This currently works on commit roots only. As commit roots are read only,
5321  * we don't do any locking. The commit roots are protected with transactions.
5322  * Transactions are ended and rejoined when a commit is tried in between.
5323  *
5324  * This function checks for modifications done to the trees while comparing.
5325  * If it detects a change, it aborts immediately.
5326  */
5327 int btrfs_compare_trees(struct btrfs_root *left_root,
5328                         struct btrfs_root *right_root,
5329                         btrfs_changed_cb_t changed_cb, void *ctx)
5330 {
5331         int ret;
5332         int cmp;
5333         struct btrfs_path *left_path = NULL;
5334         struct btrfs_path *right_path = NULL;
5335         struct btrfs_key left_key;
5336         struct btrfs_key right_key;
5337         char *tmp_buf = NULL;
5338         int left_root_level;
5339         int right_root_level;
5340         int left_level;
5341         int right_level;
5342         int left_end_reached;
5343         int right_end_reached;
5344         int advance_left;
5345         int advance_right;
5346         u64 left_blockptr;
5347         u64 right_blockptr;
5348         u64 left_gen;
5349         u64 right_gen;
5350
5351         left_path = btrfs_alloc_path();
5352         if (!left_path) {
5353                 ret = -ENOMEM;
5354                 goto out;
5355         }
5356         right_path = btrfs_alloc_path();
5357         if (!right_path) {
5358                 ret = -ENOMEM;
5359                 goto out;
5360         }
5361
5362         tmp_buf = kmalloc(left_root->nodesize, GFP_NOFS);
5363         if (!tmp_buf) {
5364                 ret = -ENOMEM;
5365                 goto out;
5366         }
5367
5368         left_path->search_commit_root = 1;
5369         left_path->skip_locking = 1;
5370         right_path->search_commit_root = 1;
5371         right_path->skip_locking = 1;
5372
5373         /*
5374          * Strategy: Go to the first items of both trees. Then do
5375          *
5376          * If both trees are at level 0
5377          *   Compare keys of current items
5378          *     If left < right treat left item as new, advance left tree
5379          *       and repeat
5380          *     If left > right treat right item as deleted, advance right tree
5381          *       and repeat
5382          *     If left == right do deep compare of items, treat as changed if
5383          *       needed, advance both trees and repeat
5384          * If both trees are at the same level but not at level 0
5385          *   Compare keys of current nodes/leafs
5386          *     If left < right advance left tree and repeat
5387          *     If left > right advance right tree and repeat
5388          *     If left == right compare blockptrs of the next nodes/leafs
5389          *       If they match advance both trees but stay at the same level
5390          *         and repeat
5391          *       If they don't match advance both trees while allowing to go
5392          *         deeper and repeat
5393          * If tree levels are different
5394          *   Advance the tree that needs it and repeat
5395          *
5396          * Advancing a tree means:
5397          *   If we are at level 0, try to go to the next slot. If that's not
5398          *   possible, go one level up and repeat. Stop when we found a level
5399          *   where we could go to the next slot. We may at this point be on a
5400          *   node or a leaf.
5401          *
5402          *   If we are not at level 0 and not on shared tree blocks, go one
5403          *   level deeper.
5404          *
5405          *   If we are not at level 0 and on shared tree blocks, go one slot to
5406          *   the right if possible or go up and right.
5407          */
5408
5409         down_read(&left_root->fs_info->commit_root_sem);
5410         left_level = btrfs_header_level(left_root->commit_root);
5411         left_root_level = left_level;
5412         left_path->nodes[left_level] = left_root->commit_root;
5413         extent_buffer_get(left_path->nodes[left_level]);
5414
5415         right_level = btrfs_header_level(right_root->commit_root);
5416         right_root_level = right_level;
5417         right_path->nodes[right_level] = right_root->commit_root;
5418         extent_buffer_get(right_path->nodes[right_level]);
5419         up_read(&left_root->fs_info->commit_root_sem);
5420
5421         if (left_level == 0)
5422                 btrfs_item_key_to_cpu(left_path->nodes[left_level],
5423                                 &left_key, left_path->slots[left_level]);
5424         else
5425                 btrfs_node_key_to_cpu(left_path->nodes[left_level],
5426                                 &left_key, left_path->slots[left_level]);
5427         if (right_level == 0)
5428                 btrfs_item_key_to_cpu(right_path->nodes[right_level],
5429                                 &right_key, right_path->slots[right_level]);
5430         else
5431                 btrfs_node_key_to_cpu(right_path->nodes[right_level],
5432                                 &right_key, right_path->slots[right_level]);
5433
5434         left_end_reached = right_end_reached = 0;
5435         advance_left = advance_right = 0;
5436
5437         while (1) {
5438                 if (advance_left && !left_end_reached) {
5439                         ret = tree_advance(left_root, left_path, &left_level,
5440                                         left_root_level,
5441                                         advance_left != ADVANCE_ONLY_NEXT,
5442                                         &left_key);
5443                         if (ret < 0)
5444                                 left_end_reached = ADVANCE;
5445                         advance_left = 0;
5446                 }
5447                 if (advance_right && !right_end_reached) {
5448                         ret = tree_advance(right_root, right_path, &right_level,
5449                                         right_root_level,
5450                                         advance_right != ADVANCE_ONLY_NEXT,
5451                                         &right_key);
5452                         if (ret < 0)
5453                                 right_end_reached = ADVANCE;
5454                         advance_right = 0;
5455                 }
5456
5457                 if (left_end_reached && right_end_reached) {
5458                         ret = 0;
5459                         goto out;
5460                 } else if (left_end_reached) {
5461                         if (right_level == 0) {
5462                                 ret = changed_cb(left_root, right_root,
5463                                                 left_path, right_path,
5464                                                 &right_key,
5465                                                 BTRFS_COMPARE_TREE_DELETED,
5466                                                 ctx);
5467                                 if (ret < 0)
5468                                         goto out;
5469                         }
5470                         advance_right = ADVANCE;
5471                         continue;
5472                 } else if (right_end_reached) {
5473                         if (left_level == 0) {
5474                                 ret = changed_cb(left_root, right_root,
5475                                                 left_path, right_path,
5476                                                 &left_key,
5477                                                 BTRFS_COMPARE_TREE_NEW,
5478                                                 ctx);
5479                                 if (ret < 0)
5480                                         goto out;
5481                         }
5482                         advance_left = ADVANCE;
5483                         continue;
5484                 }
5485
5486                 if (left_level == 0 && right_level == 0) {
5487                         cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5488                         if (cmp < 0) {
5489                                 ret = changed_cb(left_root, right_root,
5490                                                 left_path, right_path,
5491                                                 &left_key,
5492                                                 BTRFS_COMPARE_TREE_NEW,
5493                                                 ctx);
5494                                 if (ret < 0)
5495                                         goto out;
5496                                 advance_left = ADVANCE;
5497                         } else if (cmp > 0) {
5498                                 ret = changed_cb(left_root, right_root,
5499                                                 left_path, right_path,
5500                                                 &right_key,
5501                                                 BTRFS_COMPARE_TREE_DELETED,
5502                                                 ctx);
5503                                 if (ret < 0)
5504                                         goto out;
5505                                 advance_right = ADVANCE;
5506                         } else {
5507                                 enum btrfs_compare_tree_result result;
5508
5509                                 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
5510                                 ret = tree_compare_item(left_root, left_path,
5511                                                 right_path, tmp_buf);
5512                                 if (ret)
5513                                         result = BTRFS_COMPARE_TREE_CHANGED;
5514                                 else
5515                                         result = BTRFS_COMPARE_TREE_SAME;
5516                                 ret = changed_cb(left_root, right_root,
5517                                                  left_path, right_path,
5518                                                  &left_key, result, ctx);
5519                                 if (ret < 0)
5520                                         goto out;
5521                                 advance_left = ADVANCE;
5522                                 advance_right = ADVANCE;
5523                         }
5524                 } else if (left_level == right_level) {
5525                         cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5526                         if (cmp < 0) {
5527                                 advance_left = ADVANCE;
5528                         } else if (cmp > 0) {
5529                                 advance_right = ADVANCE;
5530                         } else {
5531                                 left_blockptr = btrfs_node_blockptr(
5532                                                 left_path->nodes[left_level],
5533                                                 left_path->slots[left_level]);
5534                                 right_blockptr = btrfs_node_blockptr(
5535                                                 right_path->nodes[right_level],
5536                                                 right_path->slots[right_level]);
5537                                 left_gen = btrfs_node_ptr_generation(
5538                                                 left_path->nodes[left_level],
5539                                                 left_path->slots[left_level]);
5540                                 right_gen = btrfs_node_ptr_generation(
5541                                                 right_path->nodes[right_level],
5542                                                 right_path->slots[right_level]);
5543                                 if (left_blockptr == right_blockptr &&
5544                                     left_gen == right_gen) {
5545                                         /*
5546                                          * As we're on a shared block, don't
5547                                          * allow to go deeper.
5548                                          */
5549                                         advance_left = ADVANCE_ONLY_NEXT;
5550                                         advance_right = ADVANCE_ONLY_NEXT;
5551                                 } else {
5552                                         advance_left = ADVANCE;
5553                                         advance_right = ADVANCE;
5554                                 }
5555                         }
5556                 } else if (left_level < right_level) {
5557                         advance_right = ADVANCE;
5558                 } else {
5559                         advance_left = ADVANCE;
5560                 }
5561         }
5562
5563 out:
5564         btrfs_free_path(left_path);
5565         btrfs_free_path(right_path);
5566         kfree(tmp_buf);
5567         return ret;
5568 }
5569
5570 /*
5571  * this is similar to btrfs_next_leaf, but does not try to preserve
5572  * and fixup the path.  It looks for and returns the next key in the
5573  * tree based on the current path and the min_trans parameters.
5574  *
5575  * 0 is returned if another key is found, < 0 if there are any errors
5576  * and 1 is returned if there are no higher keys in the tree
5577  *
5578  * path->keep_locks should be set to 1 on the search made before
5579  * calling this function.
5580  */
5581 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5582                         struct btrfs_key *key, int level, u64 min_trans)
5583 {
5584         int slot;
5585         struct extent_buffer *c;
5586
5587         WARN_ON(!path->keep_locks);
5588         while (level < BTRFS_MAX_LEVEL) {
5589                 if (!path->nodes[level])
5590                         return 1;
5591
5592                 slot = path->slots[level] + 1;
5593                 c = path->nodes[level];
5594 next:
5595                 if (slot >= btrfs_header_nritems(c)) {
5596                         int ret;
5597                         int orig_lowest;
5598                         struct btrfs_key cur_key;
5599                         if (level + 1 >= BTRFS_MAX_LEVEL ||
5600                             !path->nodes[level + 1])
5601                                 return 1;
5602
5603                         if (path->locks[level + 1]) {
5604                                 level++;
5605                                 continue;
5606                         }
5607
5608                         slot = btrfs_header_nritems(c) - 1;
5609                         if (level == 0)
5610                                 btrfs_item_key_to_cpu(c, &cur_key, slot);
5611                         else
5612                                 btrfs_node_key_to_cpu(c, &cur_key, slot);
5613
5614                         orig_lowest = path->lowest_level;
5615                         btrfs_release_path(path);
5616                         path->lowest_level = level;
5617                         ret = btrfs_search_slot(NULL, root, &cur_key, path,
5618                                                 0, 0);
5619                         path->lowest_level = orig_lowest;
5620                         if (ret < 0)
5621                                 return ret;
5622
5623                         c = path->nodes[level];
5624                         slot = path->slots[level];
5625                         if (ret == 0)
5626                                 slot++;
5627                         goto next;
5628                 }
5629
5630                 if (level == 0)
5631                         btrfs_item_key_to_cpu(c, key, slot);
5632                 else {
5633                         u64 gen = btrfs_node_ptr_generation(c, slot);
5634
5635                         if (gen < min_trans) {
5636                                 slot++;
5637                                 goto next;
5638                         }
5639                         btrfs_node_key_to_cpu(c, key, slot);
5640                 }
5641                 return 0;
5642         }
5643         return 1;
5644 }
5645
5646 /*
5647  * search the tree again to find a leaf with greater keys
5648  * returns 0 if it found something or 1 if there are no greater leaves.
5649  * returns < 0 on io errors.
5650  */
5651 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5652 {
5653         return btrfs_next_old_leaf(root, path, 0);
5654 }
5655
5656 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5657                         u64 time_seq)
5658 {
5659         int slot;
5660         int level;
5661         struct extent_buffer *c;
5662         struct extent_buffer *next;
5663         struct btrfs_key key;
5664         u32 nritems;
5665         int ret;
5666         int old_spinning = path->leave_spinning;
5667         int next_rw_lock = 0;
5668
5669         nritems = btrfs_header_nritems(path->nodes[0]);
5670         if (nritems == 0)
5671                 return 1;
5672
5673         btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5674 again:
5675         level = 1;
5676         next = NULL;
5677         next_rw_lock = 0;
5678         btrfs_release_path(path);
5679
5680         path->keep_locks = 1;
5681         path->leave_spinning = 1;
5682
5683         if (time_seq)
5684                 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5685         else
5686                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5687         path->keep_locks = 0;
5688
5689         if (ret < 0)
5690                 return ret;
5691
5692         nritems = btrfs_header_nritems(path->nodes[0]);
5693         /*
5694          * by releasing the path above we dropped all our locks.  A balance
5695          * could have added more items next to the key that used to be
5696          * at the very end of the block.  So, check again here and
5697          * advance the path if there are now more items available.
5698          */
5699         if (nritems > 0 && path->slots[0] < nritems - 1) {
5700                 if (ret == 0)
5701                         path->slots[0]++;
5702                 ret = 0;
5703                 goto done;
5704         }
5705         /*
5706          * So the above check misses one case:
5707          * - after releasing the path above, someone has removed the item that
5708          *   used to be at the very end of the block, and balance between leafs
5709          *   gets another one with bigger key.offset to replace it.
5710          *
5711          * This one should be returned as well, or we can get leaf corruption
5712          * later(esp. in __btrfs_drop_extents()).
5713          *
5714          * And a bit more explanation about this check,
5715          * with ret > 0, the key isn't found, the path points to the slot
5716          * where it should be inserted, so the path->slots[0] item must be the
5717          * bigger one.
5718          */
5719         if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5720                 ret = 0;
5721                 goto done;
5722         }
5723
5724         while (level < BTRFS_MAX_LEVEL) {
5725                 if (!path->nodes[level]) {
5726                         ret = 1;
5727                         goto done;
5728                 }
5729
5730                 slot = path->slots[level] + 1;
5731                 c = path->nodes[level];
5732                 if (slot >= btrfs_header_nritems(c)) {
5733                         level++;
5734                         if (level == BTRFS_MAX_LEVEL) {
5735                                 ret = 1;
5736                                 goto done;
5737                         }
5738                         continue;
5739                 }
5740
5741                 if (next) {
5742                         btrfs_tree_unlock_rw(next, next_rw_lock);
5743                         free_extent_buffer(next);
5744                 }
5745
5746                 next = c;
5747                 next_rw_lock = path->locks[level];
5748                 ret = read_block_for_search(NULL, root, path, &next, level,
5749                                             slot, &key, 0);
5750                 if (ret == -EAGAIN)
5751                         goto again;
5752
5753                 if (ret < 0) {
5754                         btrfs_release_path(path);
5755                         goto done;
5756                 }
5757
5758                 if (!path->skip_locking) {
5759                         ret = btrfs_try_tree_read_lock(next);
5760                         if (!ret && time_seq) {
5761                                 /*
5762                                  * If we don't get the lock, we may be racing
5763                                  * with push_leaf_left, holding that lock while
5764                                  * itself waiting for the leaf we've currently
5765                                  * locked. To solve this situation, we give up
5766                                  * on our lock and cycle.
5767                                  */
5768                                 free_extent_buffer(next);
5769                                 btrfs_release_path(path);
5770                                 cond_resched();
5771                                 goto again;
5772                         }
5773                         if (!ret) {
5774                                 btrfs_set_path_blocking(path);
5775                                 btrfs_tree_read_lock(next);
5776                                 btrfs_clear_path_blocking(path, next,
5777                                                           BTRFS_READ_LOCK);
5778                         }
5779                         next_rw_lock = BTRFS_READ_LOCK;
5780                 }
5781                 break;
5782         }
5783         path->slots[level] = slot;
5784         while (1) {
5785                 level--;
5786                 c = path->nodes[level];
5787                 if (path->locks[level])
5788                         btrfs_tree_unlock_rw(c, path->locks[level]);
5789
5790                 free_extent_buffer(c);
5791                 path->nodes[level] = next;
5792                 path->slots[level] = 0;
5793                 if (!path->skip_locking)
5794                         path->locks[level] = next_rw_lock;
5795                 if (!level)
5796                         break;
5797
5798                 ret = read_block_for_search(NULL, root, path, &next, level,
5799                                             0, &key, 0);
5800                 if (ret == -EAGAIN)
5801                         goto again;
5802
5803                 if (ret < 0) {
5804                         btrfs_release_path(path);
5805                         goto done;
5806                 }
5807
5808                 if (!path->skip_locking) {
5809                         ret = btrfs_try_tree_read_lock(next);
5810                         if (!ret) {
5811                                 btrfs_set_path_blocking(path);
5812                                 btrfs_tree_read_lock(next);
5813                                 btrfs_clear_path_blocking(path, next,
5814                                                           BTRFS_READ_LOCK);
5815                         }
5816                         next_rw_lock = BTRFS_READ_LOCK;
5817                 }
5818         }
5819         ret = 0;
5820 done:
5821         unlock_up(path, 0, 1, 0, NULL);
5822         path->leave_spinning = old_spinning;
5823         if (!old_spinning)
5824                 btrfs_set_path_blocking(path);
5825
5826         return ret;
5827 }
5828
5829 /*
5830  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5831  * searching until it gets past min_objectid or finds an item of 'type'
5832  *
5833  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5834  */
5835 int btrfs_previous_item(struct btrfs_root *root,
5836                         struct btrfs_path *path, u64 min_objectid,
5837                         int type)
5838 {
5839         struct btrfs_key found_key;
5840         struct extent_buffer *leaf;
5841         u32 nritems;
5842         int ret;
5843
5844         while (1) {
5845                 if (path->slots[0] == 0) {
5846                         btrfs_set_path_blocking(path);
5847                         ret = btrfs_prev_leaf(root, path);
5848                         if (ret != 0)
5849                                 return ret;
5850                 } else {
5851                         path->slots[0]--;
5852                 }
5853                 leaf = path->nodes[0];
5854                 nritems = btrfs_header_nritems(leaf);
5855                 if (nritems == 0)
5856                         return 1;
5857                 if (path->slots[0] == nritems)
5858                         path->slots[0]--;
5859
5860                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5861                 if (found_key.objectid < min_objectid)
5862                         break;
5863                 if (found_key.type == type)
5864                         return 0;
5865                 if (found_key.objectid == min_objectid &&
5866                     found_key.type < type)
5867                         break;
5868         }
5869         return 1;
5870 }
5871
5872 /*
5873  * search in extent tree to find a previous Metadata/Data extent item with
5874  * min objecitd.
5875  *
5876  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5877  */
5878 int btrfs_previous_extent_item(struct btrfs_root *root,
5879                         struct btrfs_path *path, u64 min_objectid)
5880 {
5881         struct btrfs_key found_key;
5882         struct extent_buffer *leaf;
5883         u32 nritems;
5884         int ret;
5885
5886         while (1) {
5887                 if (path->slots[0] == 0) {
5888                         btrfs_set_path_blocking(path);
5889                         ret = btrfs_prev_leaf(root, path);
5890                         if (ret != 0)
5891                                 return ret;
5892                 } else {
5893                         path->slots[0]--;
5894                 }
5895                 leaf = path->nodes[0];
5896                 nritems = btrfs_header_nritems(leaf);
5897                 if (nritems == 0)
5898                         return 1;
5899                 if (path->slots[0] == nritems)
5900                         path->slots[0]--;
5901
5902                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5903                 if (found_key.objectid < min_objectid)
5904                         break;
5905                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5906                     found_key.type == BTRFS_METADATA_ITEM_KEY)
5907                         return 0;
5908                 if (found_key.objectid == min_objectid &&
5909                     found_key.type < BTRFS_EXTENT_ITEM_KEY)
5910                         break;
5911         }
5912         return 1;
5913 }