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