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