4edcbe91573631fb7ba226b541f336a793264650
[linux-3.10.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 "ctree.h"
22 #include "disk-io.h"
23 #include "transaction.h"
24 #include "print-tree.h"
25 #include "locking.h"
26
27 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
28                       *root, struct btrfs_path *path, int level);
29 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
30                       *root, struct btrfs_key *ins_key,
31                       struct btrfs_path *path, int data_size, int extend);
32 static int push_node_left(struct btrfs_trans_handle *trans,
33                           struct btrfs_root *root, struct extent_buffer *dst,
34                           struct extent_buffer *src, int empty);
35 static int balance_node_right(struct btrfs_trans_handle *trans,
36                               struct btrfs_root *root,
37                               struct extent_buffer *dst_buf,
38                               struct extent_buffer *src_buf);
39 static int del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
40                    struct btrfs_path *path, int level, int slot);
41 static int setup_items_for_insert(struct btrfs_trans_handle *trans,
42                         struct btrfs_root *root, struct btrfs_path *path,
43                         struct btrfs_key *cpu_key, u32 *data_size,
44                         u32 total_data, u32 total_size, int nr);
45
46
47 struct btrfs_path *btrfs_alloc_path(void)
48 {
49         struct btrfs_path *path;
50         path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
51         if (path)
52                 path->reada = 1;
53         return path;
54 }
55
56 /*
57  * set all locked nodes in the path to blocking locks.  This should
58  * be done before scheduling
59  */
60 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
61 {
62         int i;
63         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
64                 if (p->nodes[i] && p->locks[i])
65                         btrfs_set_lock_blocking(p->nodes[i]);
66         }
67 }
68
69 /*
70  * reset all the locked nodes in the patch to spinning locks.
71  *
72  * held is used to keep lockdep happy, when lockdep is enabled
73  * we set held to a blocking lock before we go around and
74  * retake all the spinlocks in the path.  You can safely use NULL
75  * for held
76  */
77 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
78                                         struct extent_buffer *held)
79 {
80         int i;
81
82 #ifdef CONFIG_DEBUG_LOCK_ALLOC
83         /* lockdep really cares that we take all of these spinlocks
84          * in the right order.  If any of the locks in the path are not
85          * currently blocking, it is going to complain.  So, make really
86          * really sure by forcing the path to blocking before we clear
87          * the path blocking.
88          */
89         if (held)
90                 btrfs_set_lock_blocking(held);
91         btrfs_set_path_blocking(p);
92 #endif
93
94         for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
95                 if (p->nodes[i] && p->locks[i])
96                         btrfs_clear_lock_blocking(p->nodes[i]);
97         }
98
99 #ifdef CONFIG_DEBUG_LOCK_ALLOC
100         if (held)
101                 btrfs_clear_lock_blocking(held);
102 #endif
103 }
104
105 /* this also releases the path */
106 void btrfs_free_path(struct btrfs_path *p)
107 {
108         if (!p)
109                 return;
110         btrfs_release_path(NULL, p);
111         kmem_cache_free(btrfs_path_cachep, p);
112 }
113
114 /*
115  * path release drops references on the extent buffers in the path
116  * and it drops any locks held by this path
117  *
118  * It is safe to call this on paths that no locks or extent buffers held.
119  */
120 noinline void btrfs_release_path(struct btrfs_root *root, struct btrfs_path *p)
121 {
122         int i;
123
124         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
125                 p->slots[i] = 0;
126                 if (!p->nodes[i])
127                         continue;
128                 if (p->locks[i]) {
129                         btrfs_tree_unlock(p->nodes[i]);
130                         p->locks[i] = 0;
131                 }
132                 free_extent_buffer(p->nodes[i]);
133                 p->nodes[i] = NULL;
134         }
135 }
136
137 /*
138  * safely gets a reference on the root node of a tree.  A lock
139  * is not taken, so a concurrent writer may put a different node
140  * at the root of the tree.  See btrfs_lock_root_node for the
141  * looping required.
142  *
143  * The extent buffer returned by this has a reference taken, so
144  * it won't disappear.  It may stop being the root of the tree
145  * at any time because there are no locks held.
146  */
147 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
148 {
149         struct extent_buffer *eb;
150
151         rcu_read_lock();
152         eb = rcu_dereference(root->node);
153         extent_buffer_get(eb);
154         rcu_read_unlock();
155         return eb;
156 }
157
158 /* loop around taking references on and locking the root node of the
159  * tree until you end up with a lock on the root.  A locked buffer
160  * is returned, with a reference held.
161  */
162 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
163 {
164         struct extent_buffer *eb;
165
166         while (1) {
167                 eb = btrfs_root_node(root);
168                 btrfs_tree_lock(eb);
169                 if (eb == root->node)
170                         break;
171                 btrfs_tree_unlock(eb);
172                 free_extent_buffer(eb);
173         }
174         return eb;
175 }
176
177 /* cowonly root (everything not a reference counted cow subvolume), just get
178  * put onto a simple dirty list.  transaction.c walks this to make sure they
179  * get properly updated on disk.
180  */
181 static void add_root_to_dirty_list(struct btrfs_root *root)
182 {
183         if (root->track_dirty && list_empty(&root->dirty_list)) {
184                 list_add(&root->dirty_list,
185                          &root->fs_info->dirty_cowonly_roots);
186         }
187 }
188
189 /*
190  * used by snapshot creation to make a copy of a root for a tree with
191  * a given objectid.  The buffer with the new root node is returned in
192  * cow_ret, and this func returns zero on success or a negative error code.
193  */
194 int btrfs_copy_root(struct btrfs_trans_handle *trans,
195                       struct btrfs_root *root,
196                       struct extent_buffer *buf,
197                       struct extent_buffer **cow_ret, u64 new_root_objectid)
198 {
199         struct extent_buffer *cow;
200         int ret = 0;
201         int level;
202         struct btrfs_disk_key disk_key;
203
204         WARN_ON(root->ref_cows && trans->transid !=
205                 root->fs_info->running_transaction->transid);
206         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
207
208         level = btrfs_header_level(buf);
209         if (level == 0)
210                 btrfs_item_key(buf, &disk_key, 0);
211         else
212                 btrfs_node_key(buf, &disk_key, 0);
213
214         cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
215                                      new_root_objectid, &disk_key, level,
216                                      buf->start, 0);
217         if (IS_ERR(cow))
218                 return PTR_ERR(cow);
219
220         copy_extent_buffer(cow, buf, 0, 0, cow->len);
221         btrfs_set_header_bytenr(cow, cow->start);
222         btrfs_set_header_generation(cow, trans->transid);
223         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
224         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
225                                      BTRFS_HEADER_FLAG_RELOC);
226         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
227                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
228         else
229                 btrfs_set_header_owner(cow, new_root_objectid);
230
231         write_extent_buffer(cow, root->fs_info->fsid,
232                             (unsigned long)btrfs_header_fsid(cow),
233                             BTRFS_FSID_SIZE);
234
235         WARN_ON(btrfs_header_generation(buf) > trans->transid);
236         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
237                 ret = btrfs_inc_ref(trans, root, cow, 1);
238         else
239                 ret = btrfs_inc_ref(trans, root, cow, 0);
240
241         if (ret)
242                 return ret;
243
244         btrfs_mark_buffer_dirty(cow);
245         *cow_ret = cow;
246         return 0;
247 }
248
249 /*
250  * check if the tree block can be shared by multiple trees
251  */
252 int btrfs_block_can_be_shared(struct btrfs_root *root,
253                               struct extent_buffer *buf)
254 {
255         /*
256          * Tree blocks not in refernece counted trees and tree roots
257          * are never shared. If a block was allocated after the last
258          * snapshot and the block was not allocated by tree relocation,
259          * we know the block is not shared.
260          */
261         if (root->ref_cows &&
262             buf != root->node && buf != root->commit_root &&
263             (btrfs_header_generation(buf) <=
264              btrfs_root_last_snapshot(&root->root_item) ||
265              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
266                 return 1;
267 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
268         if (root->ref_cows &&
269             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
270                 return 1;
271 #endif
272         return 0;
273 }
274
275 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
276                                        struct btrfs_root *root,
277                                        struct extent_buffer *buf,
278                                        struct extent_buffer *cow,
279                                        int *last_ref)
280 {
281         u64 refs;
282         u64 owner;
283         u64 flags;
284         u64 new_flags = 0;
285         int ret;
286
287         /*
288          * Backrefs update rules:
289          *
290          * Always use full backrefs for extent pointers in tree block
291          * allocated by tree relocation.
292          *
293          * If a shared tree block is no longer referenced by its owner
294          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
295          * use full backrefs for extent pointers in tree block.
296          *
297          * If a tree block is been relocating
298          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
299          * use full backrefs for extent pointers in tree block.
300          * The reason for this is some operations (such as drop tree)
301          * are only allowed for blocks use full backrefs.
302          */
303
304         if (btrfs_block_can_be_shared(root, buf)) {
305                 ret = btrfs_lookup_extent_info(trans, root, buf->start,
306                                                buf->len, &refs, &flags);
307                 BUG_ON(ret);
308                 BUG_ON(refs == 0);
309         } else {
310                 refs = 1;
311                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
312                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
313                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
314                 else
315                         flags = 0;
316         }
317
318         owner = btrfs_header_owner(buf);
319         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
320                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
321
322         if (refs > 1) {
323                 if ((owner == root->root_key.objectid ||
324                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
325                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
326                         ret = btrfs_inc_ref(trans, root, buf, 1);
327                         BUG_ON(ret);
328
329                         if (root->root_key.objectid ==
330                             BTRFS_TREE_RELOC_OBJECTID) {
331                                 ret = btrfs_dec_ref(trans, root, buf, 0);
332                                 BUG_ON(ret);
333                                 ret = btrfs_inc_ref(trans, root, cow, 1);
334                                 BUG_ON(ret);
335                         }
336                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
337                 } else {
338
339                         if (root->root_key.objectid ==
340                             BTRFS_TREE_RELOC_OBJECTID)
341                                 ret = btrfs_inc_ref(trans, root, cow, 1);
342                         else
343                                 ret = btrfs_inc_ref(trans, root, cow, 0);
344                         BUG_ON(ret);
345                 }
346                 if (new_flags != 0) {
347                         ret = btrfs_set_disk_extent_flags(trans, root,
348                                                           buf->start,
349                                                           buf->len,
350                                                           new_flags, 0);
351                         BUG_ON(ret);
352                 }
353         } else {
354                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
355                         if (root->root_key.objectid ==
356                             BTRFS_TREE_RELOC_OBJECTID)
357                                 ret = btrfs_inc_ref(trans, root, cow, 1);
358                         else
359                                 ret = btrfs_inc_ref(trans, root, cow, 0);
360                         BUG_ON(ret);
361                         ret = btrfs_dec_ref(trans, root, buf, 1);
362                         BUG_ON(ret);
363                 }
364                 clean_tree_block(trans, root, buf);
365                 *last_ref = 1;
366         }
367         return 0;
368 }
369
370 /*
371  * does the dirty work in cow of a single block.  The parent block (if
372  * supplied) is updated to point to the new cow copy.  The new buffer is marked
373  * dirty and returned locked.  If you modify the block it needs to be marked
374  * dirty again.
375  *
376  * search_start -- an allocation hint for the new block
377  *
378  * empty_size -- a hint that you plan on doing more cow.  This is the size in
379  * bytes the allocator should try to find free next to the block it returns.
380  * This is just a hint and may be ignored by the allocator.
381  */
382 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
383                              struct btrfs_root *root,
384                              struct extent_buffer *buf,
385                              struct extent_buffer *parent, int parent_slot,
386                              struct extent_buffer **cow_ret,
387                              u64 search_start, u64 empty_size)
388 {
389         struct btrfs_disk_key disk_key;
390         struct extent_buffer *cow;
391         int level;
392         int last_ref = 0;
393         int unlock_orig = 0;
394         u64 parent_start;
395
396         if (*cow_ret == buf)
397                 unlock_orig = 1;
398
399         btrfs_assert_tree_locked(buf);
400
401         WARN_ON(root->ref_cows && trans->transid !=
402                 root->fs_info->running_transaction->transid);
403         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
404
405         level = btrfs_header_level(buf);
406
407         if (level == 0)
408                 btrfs_item_key(buf, &disk_key, 0);
409         else
410                 btrfs_node_key(buf, &disk_key, 0);
411
412         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
413                 if (parent)
414                         parent_start = parent->start;
415                 else
416                         parent_start = 0;
417         } else
418                 parent_start = 0;
419
420         cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
421                                      root->root_key.objectid, &disk_key,
422                                      level, search_start, empty_size);
423         if (IS_ERR(cow))
424                 return PTR_ERR(cow);
425
426         /* cow is set to blocking by btrfs_init_new_buffer */
427
428         copy_extent_buffer(cow, buf, 0, 0, cow->len);
429         btrfs_set_header_bytenr(cow, cow->start);
430         btrfs_set_header_generation(cow, trans->transid);
431         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
432         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
433                                      BTRFS_HEADER_FLAG_RELOC);
434         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
435                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
436         else
437                 btrfs_set_header_owner(cow, root->root_key.objectid);
438
439         write_extent_buffer(cow, root->fs_info->fsid,
440                             (unsigned long)btrfs_header_fsid(cow),
441                             BTRFS_FSID_SIZE);
442
443         update_ref_for_cow(trans, root, buf, cow, &last_ref);
444
445         if (root->ref_cows)
446                 btrfs_reloc_cow_block(trans, root, buf, cow);
447
448         if (buf == root->node) {
449                 WARN_ON(parent && parent != buf);
450                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
451                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
452                         parent_start = buf->start;
453                 else
454                         parent_start = 0;
455
456                 extent_buffer_get(cow);
457                 rcu_assign_pointer(root->node, cow);
458
459                 btrfs_free_tree_block(trans, root, buf, parent_start,
460                                       last_ref);
461                 free_extent_buffer(buf);
462                 add_root_to_dirty_list(root);
463         } else {
464                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
465                         parent_start = parent->start;
466                 else
467                         parent_start = 0;
468
469                 WARN_ON(trans->transid != btrfs_header_generation(parent));
470                 btrfs_set_node_blockptr(parent, parent_slot,
471                                         cow->start);
472                 btrfs_set_node_ptr_generation(parent, parent_slot,
473                                               trans->transid);
474                 btrfs_mark_buffer_dirty(parent);
475                 btrfs_free_tree_block(trans, root, buf, parent_start,
476                                       last_ref);
477         }
478         if (unlock_orig)
479                 btrfs_tree_unlock(buf);
480         free_extent_buffer(buf);
481         btrfs_mark_buffer_dirty(cow);
482         *cow_ret = cow;
483         return 0;
484 }
485
486 static inline int should_cow_block(struct btrfs_trans_handle *trans,
487                                    struct btrfs_root *root,
488                                    struct extent_buffer *buf)
489 {
490         if (btrfs_header_generation(buf) == trans->transid &&
491             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
492             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
493               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
494                 return 0;
495         return 1;
496 }
497
498 /*
499  * cows a single block, see __btrfs_cow_block for the real work.
500  * This version of it has extra checks so that a block isn't cow'd more than
501  * once per transaction, as long as it hasn't been written yet
502  */
503 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
504                     struct btrfs_root *root, struct extent_buffer *buf,
505                     struct extent_buffer *parent, int parent_slot,
506                     struct extent_buffer **cow_ret)
507 {
508         u64 search_start;
509         int ret;
510
511         if (trans->transaction != root->fs_info->running_transaction) {
512                 printk(KERN_CRIT "trans %llu running %llu\n",
513                        (unsigned long long)trans->transid,
514                        (unsigned long long)
515                        root->fs_info->running_transaction->transid);
516                 WARN_ON(1);
517         }
518         if (trans->transid != root->fs_info->generation) {
519                 printk(KERN_CRIT "trans %llu running %llu\n",
520                        (unsigned long long)trans->transid,
521                        (unsigned long long)root->fs_info->generation);
522                 WARN_ON(1);
523         }
524
525         if (!should_cow_block(trans, root, buf)) {
526                 *cow_ret = buf;
527                 return 0;
528         }
529
530         search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
531
532         if (parent)
533                 btrfs_set_lock_blocking(parent);
534         btrfs_set_lock_blocking(buf);
535
536         ret = __btrfs_cow_block(trans, root, buf, parent,
537                                  parent_slot, cow_ret, search_start, 0);
538
539         trace_btrfs_cow_block(root, buf, *cow_ret);
540
541         return ret;
542 }
543
544 /*
545  * helper function for defrag to decide if two blocks pointed to by a
546  * node are actually close by
547  */
548 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
549 {
550         if (blocknr < other && other - (blocknr + blocksize) < 32768)
551                 return 1;
552         if (blocknr > other && blocknr - (other + blocksize) < 32768)
553                 return 1;
554         return 0;
555 }
556
557 /*
558  * compare two keys in a memcmp fashion
559  */
560 static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
561 {
562         struct btrfs_key k1;
563
564         btrfs_disk_key_to_cpu(&k1, disk);
565
566         return btrfs_comp_cpu_keys(&k1, k2);
567 }
568
569 /*
570  * same as comp_keys only with two btrfs_key's
571  */
572 int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
573 {
574         if (k1->objectid > k2->objectid)
575                 return 1;
576         if (k1->objectid < k2->objectid)
577                 return -1;
578         if (k1->type > k2->type)
579                 return 1;
580         if (k1->type < k2->type)
581                 return -1;
582         if (k1->offset > k2->offset)
583                 return 1;
584         if (k1->offset < k2->offset)
585                 return -1;
586         return 0;
587 }
588
589 /*
590  * this is used by the defrag code to go through all the
591  * leaves pointed to by a node and reallocate them so that
592  * disk order is close to key order
593  */
594 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
595                        struct btrfs_root *root, struct extent_buffer *parent,
596                        int start_slot, int cache_only, u64 *last_ret,
597                        struct btrfs_key *progress)
598 {
599         struct extent_buffer *cur;
600         u64 blocknr;
601         u64 gen;
602         u64 search_start = *last_ret;
603         u64 last_block = 0;
604         u64 other;
605         u32 parent_nritems;
606         int end_slot;
607         int i;
608         int err = 0;
609         int parent_level;
610         int uptodate;
611         u32 blocksize;
612         int progress_passed = 0;
613         struct btrfs_disk_key disk_key;
614
615         parent_level = btrfs_header_level(parent);
616         if (cache_only && parent_level != 1)
617                 return 0;
618
619         if (trans->transaction != root->fs_info->running_transaction)
620                 WARN_ON(1);
621         if (trans->transid != root->fs_info->generation)
622                 WARN_ON(1);
623
624         parent_nritems = btrfs_header_nritems(parent);
625         blocksize = btrfs_level_size(root, parent_level - 1);
626         end_slot = parent_nritems;
627
628         if (parent_nritems == 1)
629                 return 0;
630
631         btrfs_set_lock_blocking(parent);
632
633         for (i = start_slot; i < end_slot; i++) {
634                 int close = 1;
635
636                 if (!parent->map_token) {
637                         map_extent_buffer(parent,
638                                         btrfs_node_key_ptr_offset(i),
639                                         sizeof(struct btrfs_key_ptr),
640                                         &parent->map_token, &parent->kaddr,
641                                         &parent->map_start, &parent->map_len,
642                                         KM_USER1);
643                 }
644                 btrfs_node_key(parent, &disk_key, i);
645                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
646                         continue;
647
648                 progress_passed = 1;
649                 blocknr = btrfs_node_blockptr(parent, i);
650                 gen = btrfs_node_ptr_generation(parent, i);
651                 if (last_block == 0)
652                         last_block = blocknr;
653
654                 if (i > 0) {
655                         other = btrfs_node_blockptr(parent, i - 1);
656                         close = close_blocks(blocknr, other, blocksize);
657                 }
658                 if (!close && i < end_slot - 2) {
659                         other = btrfs_node_blockptr(parent, i + 1);
660                         close = close_blocks(blocknr, other, blocksize);
661                 }
662                 if (close) {
663                         last_block = blocknr;
664                         continue;
665                 }
666                 if (parent->map_token) {
667                         unmap_extent_buffer(parent, parent->map_token,
668                                             KM_USER1);
669                         parent->map_token = NULL;
670                 }
671
672                 cur = btrfs_find_tree_block(root, blocknr, blocksize);
673                 if (cur)
674                         uptodate = btrfs_buffer_uptodate(cur, gen);
675                 else
676                         uptodate = 0;
677                 if (!cur || !uptodate) {
678                         if (cache_only) {
679                                 free_extent_buffer(cur);
680                                 continue;
681                         }
682                         if (!cur) {
683                                 cur = read_tree_block(root, blocknr,
684                                                          blocksize, gen);
685                         } else if (!uptodate) {
686                                 btrfs_read_buffer(cur, gen);
687                         }
688                 }
689                 if (search_start == 0)
690                         search_start = last_block;
691
692                 btrfs_tree_lock(cur);
693                 btrfs_set_lock_blocking(cur);
694                 err = __btrfs_cow_block(trans, root, cur, parent, i,
695                                         &cur, search_start,
696                                         min(16 * blocksize,
697                                             (end_slot - i) * blocksize));
698                 if (err) {
699                         btrfs_tree_unlock(cur);
700                         free_extent_buffer(cur);
701                         break;
702                 }
703                 search_start = cur->start;
704                 last_block = cur->start;
705                 *last_ret = search_start;
706                 btrfs_tree_unlock(cur);
707                 free_extent_buffer(cur);
708         }
709         if (parent->map_token) {
710                 unmap_extent_buffer(parent, parent->map_token,
711                                     KM_USER1);
712                 parent->map_token = NULL;
713         }
714         return err;
715 }
716
717 /*
718  * The leaf data grows from end-to-front in the node.
719  * this returns the address of the start of the last item,
720  * which is the stop of the leaf data stack
721  */
722 static inline unsigned int leaf_data_end(struct btrfs_root *root,
723                                          struct extent_buffer *leaf)
724 {
725         u32 nr = btrfs_header_nritems(leaf);
726         if (nr == 0)
727                 return BTRFS_LEAF_DATA_SIZE(root);
728         return btrfs_item_offset_nr(leaf, nr - 1);
729 }
730
731
732 /*
733  * search for key in the extent_buffer.  The items start at offset p,
734  * and they are item_size apart.  There are 'max' items in p.
735  *
736  * the slot in the array is returned via slot, and it points to
737  * the place where you would insert key if it is not found in
738  * the array.
739  *
740  * slot may point to max if the key is bigger than all of the keys
741  */
742 static noinline int generic_bin_search(struct extent_buffer *eb,
743                                        unsigned long p,
744                                        int item_size, struct btrfs_key *key,
745                                        int max, int *slot)
746 {
747         int low = 0;
748         int high = max;
749         int mid;
750         int ret;
751         struct btrfs_disk_key *tmp = NULL;
752         struct btrfs_disk_key unaligned;
753         unsigned long offset;
754         char *map_token = NULL;
755         char *kaddr = NULL;
756         unsigned long map_start = 0;
757         unsigned long map_len = 0;
758         int err;
759
760         while (low < high) {
761                 mid = (low + high) / 2;
762                 offset = p + mid * item_size;
763
764                 if (!map_token || offset < map_start ||
765                     (offset + sizeof(struct btrfs_disk_key)) >
766                     map_start + map_len) {
767                         if (map_token) {
768                                 unmap_extent_buffer(eb, map_token, KM_USER0);
769                                 map_token = NULL;
770                         }
771
772                         err = map_private_extent_buffer(eb, offset,
773                                                 sizeof(struct btrfs_disk_key),
774                                                 &map_token, &kaddr,
775                                                 &map_start, &map_len, KM_USER0);
776
777                         if (!err) {
778                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
779                                                         map_start);
780                         } else {
781                                 read_extent_buffer(eb, &unaligned,
782                                                    offset, sizeof(unaligned));
783                                 tmp = &unaligned;
784                         }
785
786                 } else {
787                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
788                                                         map_start);
789                 }
790                 ret = comp_keys(tmp, key);
791
792                 if (ret < 0)
793                         low = mid + 1;
794                 else if (ret > 0)
795                         high = mid;
796                 else {
797                         *slot = mid;
798                         if (map_token)
799                                 unmap_extent_buffer(eb, map_token, KM_USER0);
800                         return 0;
801                 }
802         }
803         *slot = low;
804         if (map_token)
805                 unmap_extent_buffer(eb, map_token, KM_USER0);
806         return 1;
807 }
808
809 /*
810  * simple bin_search frontend that does the right thing for
811  * leaves vs nodes
812  */
813 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
814                       int level, int *slot)
815 {
816         if (level == 0) {
817                 return generic_bin_search(eb,
818                                           offsetof(struct btrfs_leaf, items),
819                                           sizeof(struct btrfs_item),
820                                           key, btrfs_header_nritems(eb),
821                                           slot);
822         } else {
823                 return generic_bin_search(eb,
824                                           offsetof(struct btrfs_node, ptrs),
825                                           sizeof(struct btrfs_key_ptr),
826                                           key, btrfs_header_nritems(eb),
827                                           slot);
828         }
829         return -1;
830 }
831
832 int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
833                      int level, int *slot)
834 {
835         return bin_search(eb, key, level, slot);
836 }
837
838 static void root_add_used(struct btrfs_root *root, u32 size)
839 {
840         spin_lock(&root->accounting_lock);
841         btrfs_set_root_used(&root->root_item,
842                             btrfs_root_used(&root->root_item) + size);
843         spin_unlock(&root->accounting_lock);
844 }
845
846 static void root_sub_used(struct btrfs_root *root, u32 size)
847 {
848         spin_lock(&root->accounting_lock);
849         btrfs_set_root_used(&root->root_item,
850                             btrfs_root_used(&root->root_item) - size);
851         spin_unlock(&root->accounting_lock);
852 }
853
854 /* given a node and slot number, this reads the blocks it points to.  The
855  * extent buffer is returned with a reference taken (but unlocked).
856  * NULL is returned on error.
857  */
858 static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
859                                    struct extent_buffer *parent, int slot)
860 {
861         int level = btrfs_header_level(parent);
862         if (slot < 0)
863                 return NULL;
864         if (slot >= btrfs_header_nritems(parent))
865                 return NULL;
866
867         BUG_ON(level == 0);
868
869         return read_tree_block(root, btrfs_node_blockptr(parent, slot),
870                        btrfs_level_size(root, level - 1),
871                        btrfs_node_ptr_generation(parent, slot));
872 }
873
874 /*
875  * node level balancing, used to make sure nodes are in proper order for
876  * item deletion.  We balance from the top down, so we have to make sure
877  * that a deletion won't leave an node completely empty later on.
878  */
879 static noinline int balance_level(struct btrfs_trans_handle *trans,
880                          struct btrfs_root *root,
881                          struct btrfs_path *path, int level)
882 {
883         struct extent_buffer *right = NULL;
884         struct extent_buffer *mid;
885         struct extent_buffer *left = NULL;
886         struct extent_buffer *parent = NULL;
887         int ret = 0;
888         int wret;
889         int pslot;
890         int orig_slot = path->slots[level];
891         u64 orig_ptr;
892
893         if (level == 0)
894                 return 0;
895
896         mid = path->nodes[level];
897
898         WARN_ON(!path->locks[level]);
899         WARN_ON(btrfs_header_generation(mid) != trans->transid);
900
901         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
902
903         if (level < BTRFS_MAX_LEVEL - 1)
904                 parent = path->nodes[level + 1];
905         pslot = path->slots[level + 1];
906
907         /*
908          * deal with the case where there is only one pointer in the root
909          * by promoting the node below to a root
910          */
911         if (!parent) {
912                 struct extent_buffer *child;
913
914                 if (btrfs_header_nritems(mid) != 1)
915                         return 0;
916
917                 /* promote the child to a root */
918                 child = read_node_slot(root, mid, 0);
919                 BUG_ON(!child);
920                 btrfs_tree_lock(child);
921                 btrfs_set_lock_blocking(child);
922                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
923                 if (ret) {
924                         btrfs_tree_unlock(child);
925                         free_extent_buffer(child);
926                         goto enospc;
927                 }
928
929                 rcu_assign_pointer(root->node, child);
930
931                 add_root_to_dirty_list(root);
932                 btrfs_tree_unlock(child);
933
934                 path->locks[level] = 0;
935                 path->nodes[level] = NULL;
936                 clean_tree_block(trans, root, mid);
937                 btrfs_tree_unlock(mid);
938                 /* once for the path */
939                 free_extent_buffer(mid);
940
941                 root_sub_used(root, mid->len);
942                 btrfs_free_tree_block(trans, root, mid, 0, 1);
943                 /* once for the root ptr */
944                 free_extent_buffer(mid);
945                 return 0;
946         }
947         if (btrfs_header_nritems(mid) >
948             BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
949                 return 0;
950
951         btrfs_header_nritems(mid);
952
953         left = read_node_slot(root, parent, pslot - 1);
954         if (left) {
955                 btrfs_tree_lock(left);
956                 btrfs_set_lock_blocking(left);
957                 wret = btrfs_cow_block(trans, root, left,
958                                        parent, pslot - 1, &left);
959                 if (wret) {
960                         ret = wret;
961                         goto enospc;
962                 }
963         }
964         right = read_node_slot(root, parent, pslot + 1);
965         if (right) {
966                 btrfs_tree_lock(right);
967                 btrfs_set_lock_blocking(right);
968                 wret = btrfs_cow_block(trans, root, right,
969                                        parent, pslot + 1, &right);
970                 if (wret) {
971                         ret = wret;
972                         goto enospc;
973                 }
974         }
975
976         /* first, try to make some room in the middle buffer */
977         if (left) {
978                 orig_slot += btrfs_header_nritems(left);
979                 wret = push_node_left(trans, root, left, mid, 1);
980                 if (wret < 0)
981                         ret = wret;
982                 btrfs_header_nritems(mid);
983         }
984
985         /*
986          * then try to empty the right most buffer into the middle
987          */
988         if (right) {
989                 wret = push_node_left(trans, root, mid, right, 1);
990                 if (wret < 0 && wret != -ENOSPC)
991                         ret = wret;
992                 if (btrfs_header_nritems(right) == 0) {
993                         clean_tree_block(trans, root, right);
994                         btrfs_tree_unlock(right);
995                         wret = del_ptr(trans, root, path, level + 1, pslot +
996                                        1);
997                         if (wret)
998                                 ret = wret;
999                         root_sub_used(root, right->len);
1000                         btrfs_free_tree_block(trans, root, right, 0, 1);
1001                         free_extent_buffer(right);
1002                         right = NULL;
1003                 } else {
1004                         struct btrfs_disk_key right_key;
1005                         btrfs_node_key(right, &right_key, 0);
1006                         btrfs_set_node_key(parent, &right_key, pslot + 1);
1007                         btrfs_mark_buffer_dirty(parent);
1008                 }
1009         }
1010         if (btrfs_header_nritems(mid) == 1) {
1011                 /*
1012                  * we're not allowed to leave a node with one item in the
1013                  * tree during a delete.  A deletion from lower in the tree
1014                  * could try to delete the only pointer in this node.
1015                  * So, pull some keys from the left.
1016                  * There has to be a left pointer at this point because
1017                  * otherwise we would have pulled some pointers from the
1018                  * right
1019                  */
1020                 BUG_ON(!left);
1021                 wret = balance_node_right(trans, root, mid, left);
1022                 if (wret < 0) {
1023                         ret = wret;
1024                         goto enospc;
1025                 }
1026                 if (wret == 1) {
1027                         wret = push_node_left(trans, root, left, mid, 1);
1028                         if (wret < 0)
1029                                 ret = wret;
1030                 }
1031                 BUG_ON(wret == 1);
1032         }
1033         if (btrfs_header_nritems(mid) == 0) {
1034                 clean_tree_block(trans, root, mid);
1035                 btrfs_tree_unlock(mid);
1036                 wret = del_ptr(trans, root, path, level + 1, pslot);
1037                 if (wret)
1038                         ret = wret;
1039                 root_sub_used(root, mid->len);
1040                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1041                 free_extent_buffer(mid);
1042                 mid = NULL;
1043         } else {
1044                 /* update the parent key to reflect our changes */
1045                 struct btrfs_disk_key mid_key;
1046                 btrfs_node_key(mid, &mid_key, 0);
1047                 btrfs_set_node_key(parent, &mid_key, pslot);
1048                 btrfs_mark_buffer_dirty(parent);
1049         }
1050
1051         /* update the path */
1052         if (left) {
1053                 if (btrfs_header_nritems(left) > orig_slot) {
1054                         extent_buffer_get(left);
1055                         /* left was locked after cow */
1056                         path->nodes[level] = left;
1057                         path->slots[level + 1] -= 1;
1058                         path->slots[level] = orig_slot;
1059                         if (mid) {
1060                                 btrfs_tree_unlock(mid);
1061                                 free_extent_buffer(mid);
1062                         }
1063                 } else {
1064                         orig_slot -= btrfs_header_nritems(left);
1065                         path->slots[level] = orig_slot;
1066                 }
1067         }
1068         /* double check we haven't messed things up */
1069         if (orig_ptr !=
1070             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1071                 BUG();
1072 enospc:
1073         if (right) {
1074                 btrfs_tree_unlock(right);
1075                 free_extent_buffer(right);
1076         }
1077         if (left) {
1078                 if (path->nodes[level] != left)
1079                         btrfs_tree_unlock(left);
1080                 free_extent_buffer(left);
1081         }
1082         return ret;
1083 }
1084
1085 /* Node balancing for insertion.  Here we only split or push nodes around
1086  * when they are completely full.  This is also done top down, so we
1087  * have to be pessimistic.
1088  */
1089 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1090                                           struct btrfs_root *root,
1091                                           struct btrfs_path *path, int level)
1092 {
1093         struct extent_buffer *right = NULL;
1094         struct extent_buffer *mid;
1095         struct extent_buffer *left = NULL;
1096         struct extent_buffer *parent = NULL;
1097         int ret = 0;
1098         int wret;
1099         int pslot;
1100         int orig_slot = path->slots[level];
1101
1102         if (level == 0)
1103                 return 1;
1104
1105         mid = path->nodes[level];
1106         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1107
1108         if (level < BTRFS_MAX_LEVEL - 1)
1109                 parent = path->nodes[level + 1];
1110         pslot = path->slots[level + 1];
1111
1112         if (!parent)
1113                 return 1;
1114
1115         left = read_node_slot(root, parent, pslot - 1);
1116
1117         /* first, try to make some room in the middle buffer */
1118         if (left) {
1119                 u32 left_nr;
1120
1121                 btrfs_tree_lock(left);
1122                 btrfs_set_lock_blocking(left);
1123
1124                 left_nr = btrfs_header_nritems(left);
1125                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1126                         wret = 1;
1127                 } else {
1128                         ret = btrfs_cow_block(trans, root, left, parent,
1129                                               pslot - 1, &left);
1130                         if (ret)
1131                                 wret = 1;
1132                         else {
1133                                 wret = push_node_left(trans, root,
1134                                                       left, mid, 0);
1135                         }
1136                 }
1137                 if (wret < 0)
1138                         ret = wret;
1139                 if (wret == 0) {
1140                         struct btrfs_disk_key disk_key;
1141                         orig_slot += left_nr;
1142                         btrfs_node_key(mid, &disk_key, 0);
1143                         btrfs_set_node_key(parent, &disk_key, pslot);
1144                         btrfs_mark_buffer_dirty(parent);
1145                         if (btrfs_header_nritems(left) > orig_slot) {
1146                                 path->nodes[level] = left;
1147                                 path->slots[level + 1] -= 1;
1148                                 path->slots[level] = orig_slot;
1149                                 btrfs_tree_unlock(mid);
1150                                 free_extent_buffer(mid);
1151                         } else {
1152                                 orig_slot -=
1153                                         btrfs_header_nritems(left);
1154                                 path->slots[level] = orig_slot;
1155                                 btrfs_tree_unlock(left);
1156                                 free_extent_buffer(left);
1157                         }
1158                         return 0;
1159                 }
1160                 btrfs_tree_unlock(left);
1161                 free_extent_buffer(left);
1162         }
1163         right = read_node_slot(root, parent, pslot + 1);
1164
1165         /*
1166          * then try to empty the right most buffer into the middle
1167          */
1168         if (right) {
1169                 u32 right_nr;
1170
1171                 btrfs_tree_lock(right);
1172                 btrfs_set_lock_blocking(right);
1173
1174                 right_nr = btrfs_header_nritems(right);
1175                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1176                         wret = 1;
1177                 } else {
1178                         ret = btrfs_cow_block(trans, root, right,
1179                                               parent, pslot + 1,
1180                                               &right);
1181                         if (ret)
1182                                 wret = 1;
1183                         else {
1184                                 wret = balance_node_right(trans, root,
1185                                                           right, mid);
1186                         }
1187                 }
1188                 if (wret < 0)
1189                         ret = wret;
1190                 if (wret == 0) {
1191                         struct btrfs_disk_key disk_key;
1192
1193                         btrfs_node_key(right, &disk_key, 0);
1194                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
1195                         btrfs_mark_buffer_dirty(parent);
1196
1197                         if (btrfs_header_nritems(mid) <= orig_slot) {
1198                                 path->nodes[level] = right;
1199                                 path->slots[level + 1] += 1;
1200                                 path->slots[level] = orig_slot -
1201                                         btrfs_header_nritems(mid);
1202                                 btrfs_tree_unlock(mid);
1203                                 free_extent_buffer(mid);
1204                         } else {
1205                                 btrfs_tree_unlock(right);
1206                                 free_extent_buffer(right);
1207                         }
1208                         return 0;
1209                 }
1210                 btrfs_tree_unlock(right);
1211                 free_extent_buffer(right);
1212         }
1213         return 1;
1214 }
1215
1216 /*
1217  * readahead one full node of leaves, finding things that are close
1218  * to the block in 'slot', and triggering ra on them.
1219  */
1220 static void reada_for_search(struct btrfs_root *root,
1221                              struct btrfs_path *path,
1222                              int level, int slot, u64 objectid)
1223 {
1224         struct extent_buffer *node;
1225         struct btrfs_disk_key disk_key;
1226         u32 nritems;
1227         u64 search;
1228         u64 target;
1229         u64 nread = 0;
1230         int direction = path->reada;
1231         struct extent_buffer *eb;
1232         u32 nr;
1233         u32 blocksize;
1234         u32 nscan = 0;
1235
1236         if (level != 1)
1237                 return;
1238
1239         if (!path->nodes[level])
1240                 return;
1241
1242         node = path->nodes[level];
1243
1244         search = btrfs_node_blockptr(node, slot);
1245         blocksize = btrfs_level_size(root, level - 1);
1246         eb = btrfs_find_tree_block(root, search, blocksize);
1247         if (eb) {
1248                 free_extent_buffer(eb);
1249                 return;
1250         }
1251
1252         target = search;
1253
1254         nritems = btrfs_header_nritems(node);
1255         nr = slot;
1256         while (1) {
1257                 if (direction < 0) {
1258                         if (nr == 0)
1259                                 break;
1260                         nr--;
1261                 } else if (direction > 0) {
1262                         nr++;
1263                         if (nr >= nritems)
1264                                 break;
1265                 }
1266                 if (path->reada < 0 && objectid) {
1267                         btrfs_node_key(node, &disk_key, nr);
1268                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
1269                                 break;
1270                 }
1271                 search = btrfs_node_blockptr(node, nr);
1272                 if ((search <= target && target - search <= 65536) ||
1273                     (search > target && search - target <= 65536)) {
1274                         readahead_tree_block(root, search, blocksize,
1275                                      btrfs_node_ptr_generation(node, nr));
1276                         nread += blocksize;
1277                 }
1278                 nscan++;
1279                 if ((nread > 65536 || nscan > 32))
1280                         break;
1281         }
1282 }
1283
1284 /*
1285  * returns -EAGAIN if it had to drop the path, or zero if everything was in
1286  * cache
1287  */
1288 static noinline int reada_for_balance(struct btrfs_root *root,
1289                                       struct btrfs_path *path, int level)
1290 {
1291         int slot;
1292         int nritems;
1293         struct extent_buffer *parent;
1294         struct extent_buffer *eb;
1295         u64 gen;
1296         u64 block1 = 0;
1297         u64 block2 = 0;
1298         int ret = 0;
1299         int blocksize;
1300
1301         parent = path->nodes[level + 1];
1302         if (!parent)
1303                 return 0;
1304
1305         nritems = btrfs_header_nritems(parent);
1306         slot = path->slots[level + 1];
1307         blocksize = btrfs_level_size(root, level);
1308
1309         if (slot > 0) {
1310                 block1 = btrfs_node_blockptr(parent, slot - 1);
1311                 gen = btrfs_node_ptr_generation(parent, slot - 1);
1312                 eb = btrfs_find_tree_block(root, block1, blocksize);
1313                 if (eb && btrfs_buffer_uptodate(eb, gen))
1314                         block1 = 0;
1315                 free_extent_buffer(eb);
1316         }
1317         if (slot + 1 < nritems) {
1318                 block2 = btrfs_node_blockptr(parent, slot + 1);
1319                 gen = btrfs_node_ptr_generation(parent, slot + 1);
1320                 eb = btrfs_find_tree_block(root, block2, blocksize);
1321                 if (eb && btrfs_buffer_uptodate(eb, gen))
1322                         block2 = 0;
1323                 free_extent_buffer(eb);
1324         }
1325         if (block1 || block2) {
1326                 ret = -EAGAIN;
1327
1328                 /* release the whole path */
1329                 btrfs_release_path(root, path);
1330
1331                 /* read the blocks */
1332                 if (block1)
1333                         readahead_tree_block(root, block1, blocksize, 0);
1334                 if (block2)
1335                         readahead_tree_block(root, block2, blocksize, 0);
1336
1337                 if (block1) {
1338                         eb = read_tree_block(root, block1, blocksize, 0);
1339                         free_extent_buffer(eb);
1340                 }
1341                 if (block2) {
1342                         eb = read_tree_block(root, block2, blocksize, 0);
1343                         free_extent_buffer(eb);
1344                 }
1345         }
1346         return ret;
1347 }
1348
1349
1350 /*
1351  * when we walk down the tree, it is usually safe to unlock the higher layers
1352  * in the tree.  The exceptions are when our path goes through slot 0, because
1353  * operations on the tree might require changing key pointers higher up in the
1354  * tree.
1355  *
1356  * callers might also have set path->keep_locks, which tells this code to keep
1357  * the lock if the path points to the last slot in the block.  This is part of
1358  * walking through the tree, and selecting the next slot in the higher block.
1359  *
1360  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1361  * if lowest_unlock is 1, level 0 won't be unlocked
1362  */
1363 static noinline void unlock_up(struct btrfs_path *path, int level,
1364                                int lowest_unlock)
1365 {
1366         int i;
1367         int skip_level = level;
1368         int no_skips = 0;
1369         struct extent_buffer *t;
1370
1371         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1372                 if (!path->nodes[i])
1373                         break;
1374                 if (!path->locks[i])
1375                         break;
1376                 if (!no_skips && path->slots[i] == 0) {
1377                         skip_level = i + 1;
1378                         continue;
1379                 }
1380                 if (!no_skips && path->keep_locks) {
1381                         u32 nritems;
1382                         t = path->nodes[i];
1383                         nritems = btrfs_header_nritems(t);
1384                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
1385                                 skip_level = i + 1;
1386                                 continue;
1387                         }
1388                 }
1389                 if (skip_level < i && i >= lowest_unlock)
1390                         no_skips = 1;
1391
1392                 t = path->nodes[i];
1393                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
1394                         btrfs_tree_unlock(t);
1395                         path->locks[i] = 0;
1396                 }
1397         }
1398 }
1399
1400 /*
1401  * This releases any locks held in the path starting at level and
1402  * going all the way up to the root.
1403  *
1404  * btrfs_search_slot will keep the lock held on higher nodes in a few
1405  * corner cases, such as COW of the block at slot zero in the node.  This
1406  * ignores those rules, and it should only be called when there are no
1407  * more updates to be done higher up in the tree.
1408  */
1409 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
1410 {
1411         int i;
1412
1413         if (path->keep_locks)
1414                 return;
1415
1416         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1417                 if (!path->nodes[i])
1418                         continue;
1419                 if (!path->locks[i])
1420                         continue;
1421                 btrfs_tree_unlock(path->nodes[i]);
1422                 path->locks[i] = 0;
1423         }
1424 }
1425
1426 /*
1427  * helper function for btrfs_search_slot.  The goal is to find a block
1428  * in cache without setting the path to blocking.  If we find the block
1429  * we return zero and the path is unchanged.
1430  *
1431  * If we can't find the block, we set the path blocking and do some
1432  * reada.  -EAGAIN is returned and the search must be repeated.
1433  */
1434 static int
1435 read_block_for_search(struct btrfs_trans_handle *trans,
1436                        struct btrfs_root *root, struct btrfs_path *p,
1437                        struct extent_buffer **eb_ret, int level, int slot,
1438                        struct btrfs_key *key)
1439 {
1440         u64 blocknr;
1441         u64 gen;
1442         u32 blocksize;
1443         struct extent_buffer *b = *eb_ret;
1444         struct extent_buffer *tmp;
1445         int ret;
1446
1447         blocknr = btrfs_node_blockptr(b, slot);
1448         gen = btrfs_node_ptr_generation(b, slot);
1449         blocksize = btrfs_level_size(root, level - 1);
1450
1451         tmp = btrfs_find_tree_block(root, blocknr, blocksize);
1452         if (tmp) {
1453                 if (btrfs_buffer_uptodate(tmp, 0)) {
1454                         if (btrfs_buffer_uptodate(tmp, gen)) {
1455                                 /*
1456                                  * we found an up to date block without
1457                                  * sleeping, return
1458                                  * right away
1459                                  */
1460                                 *eb_ret = tmp;
1461                                 return 0;
1462                         }
1463                         /* the pages were up to date, but we failed
1464                          * the generation number check.  Do a full
1465                          * read for the generation number that is correct.
1466                          * We must do this without dropping locks so
1467                          * we can trust our generation number
1468                          */
1469                         free_extent_buffer(tmp);
1470                         tmp = read_tree_block(root, blocknr, blocksize, gen);
1471                         if (tmp && btrfs_buffer_uptodate(tmp, gen)) {
1472                                 *eb_ret = tmp;
1473                                 return 0;
1474                         }
1475                         free_extent_buffer(tmp);
1476                         btrfs_release_path(NULL, p);
1477                         return -EIO;
1478                 }
1479         }
1480
1481         /*
1482          * reduce lock contention at high levels
1483          * of the btree by dropping locks before
1484          * we read.  Don't release the lock on the current
1485          * level because we need to walk this node to figure
1486          * out which blocks to read.
1487          */
1488         btrfs_unlock_up_safe(p, level + 1);
1489         btrfs_set_path_blocking(p);
1490
1491         free_extent_buffer(tmp);
1492         if (p->reada)
1493                 reada_for_search(root, p, level, slot, key->objectid);
1494
1495         btrfs_release_path(NULL, p);
1496
1497         ret = -EAGAIN;
1498         tmp = read_tree_block(root, blocknr, blocksize, 0);
1499         if (tmp) {
1500                 /*
1501                  * If the read above didn't mark this buffer up to date,
1502                  * it will never end up being up to date.  Set ret to EIO now
1503                  * and give up so that our caller doesn't loop forever
1504                  * on our EAGAINs.
1505                  */
1506                 if (!btrfs_buffer_uptodate(tmp, 0))
1507                         ret = -EIO;
1508                 free_extent_buffer(tmp);
1509         }
1510         return ret;
1511 }
1512
1513 /*
1514  * helper function for btrfs_search_slot.  This does all of the checks
1515  * for node-level blocks and does any balancing required based on
1516  * the ins_len.
1517  *
1518  * If no extra work was required, zero is returned.  If we had to
1519  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1520  * start over
1521  */
1522 static int
1523 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1524                        struct btrfs_root *root, struct btrfs_path *p,
1525                        struct extent_buffer *b, int level, int ins_len)
1526 {
1527         int ret;
1528         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1529             BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
1530                 int sret;
1531
1532                 sret = reada_for_balance(root, p, level);
1533                 if (sret)
1534                         goto again;
1535
1536                 btrfs_set_path_blocking(p);
1537                 sret = split_node(trans, root, p, level);
1538                 btrfs_clear_path_blocking(p, NULL);
1539
1540                 BUG_ON(sret > 0);
1541                 if (sret) {
1542                         ret = sret;
1543                         goto done;
1544                 }
1545                 b = p->nodes[level];
1546         } else if (ins_len < 0 && btrfs_header_nritems(b) <
1547                    BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
1548                 int sret;
1549
1550                 sret = reada_for_balance(root, p, level);
1551                 if (sret)
1552                         goto again;
1553
1554                 btrfs_set_path_blocking(p);
1555                 sret = balance_level(trans, root, p, level);
1556                 btrfs_clear_path_blocking(p, NULL);
1557
1558                 if (sret) {
1559                         ret = sret;
1560                         goto done;
1561                 }
1562                 b = p->nodes[level];
1563                 if (!b) {
1564                         btrfs_release_path(NULL, p);
1565                         goto again;
1566                 }
1567                 BUG_ON(btrfs_header_nritems(b) == 1);
1568         }
1569         return 0;
1570
1571 again:
1572         ret = -EAGAIN;
1573 done:
1574         return ret;
1575 }
1576
1577 /*
1578  * look for key in the tree.  path is filled in with nodes along the way
1579  * if key is found, we return zero and you can find the item in the leaf
1580  * level of the path (level 0)
1581  *
1582  * If the key isn't found, the path points to the slot where it should
1583  * be inserted, and 1 is returned.  If there are other errors during the
1584  * search a negative error number is returned.
1585  *
1586  * if ins_len > 0, nodes and leaves will be split as we walk down the
1587  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
1588  * possible)
1589  */
1590 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
1591                       *root, struct btrfs_key *key, struct btrfs_path *p, int
1592                       ins_len, int cow)
1593 {
1594         struct extent_buffer *b;
1595         int slot;
1596         int ret;
1597         int err;
1598         int level;
1599         int lowest_unlock = 1;
1600         u8 lowest_level = 0;
1601
1602         lowest_level = p->lowest_level;
1603         WARN_ON(lowest_level && ins_len > 0);
1604         WARN_ON(p->nodes[0] != NULL);
1605
1606         if (ins_len < 0)
1607                 lowest_unlock = 2;
1608
1609 again:
1610         if (p->search_commit_root) {
1611                 b = root->commit_root;
1612                 extent_buffer_get(b);
1613                 if (!p->skip_locking)
1614                         btrfs_tree_lock(b);
1615         } else {
1616                 if (p->skip_locking)
1617                         b = btrfs_root_node(root);
1618                 else
1619                         b = btrfs_lock_root_node(root);
1620         }
1621
1622         while (b) {
1623                 level = btrfs_header_level(b);
1624
1625                 /*
1626                  * setup the path here so we can release it under lock
1627                  * contention with the cow code
1628                  */
1629                 p->nodes[level] = b;
1630                 if (!p->skip_locking)
1631                         p->locks[level] = 1;
1632
1633                 if (cow) {
1634                         /*
1635                          * if we don't really need to cow this block
1636                          * then we don't want to set the path blocking,
1637                          * so we test it here
1638                          */
1639                         if (!should_cow_block(trans, root, b))
1640                                 goto cow_done;
1641
1642                         btrfs_set_path_blocking(p);
1643
1644                         err = btrfs_cow_block(trans, root, b,
1645                                               p->nodes[level + 1],
1646                                               p->slots[level + 1], &b);
1647                         if (err) {
1648                                 ret = err;
1649                                 goto done;
1650                         }
1651                 }
1652 cow_done:
1653                 BUG_ON(!cow && ins_len);
1654                 if (level != btrfs_header_level(b))
1655                         WARN_ON(1);
1656                 level = btrfs_header_level(b);
1657
1658                 p->nodes[level] = b;
1659                 if (!p->skip_locking)
1660                         p->locks[level] = 1;
1661
1662                 btrfs_clear_path_blocking(p, NULL);
1663
1664                 /*
1665                  * we have a lock on b and as long as we aren't changing
1666                  * the tree, there is no way to for the items in b to change.
1667                  * It is safe to drop the lock on our parent before we
1668                  * go through the expensive btree search on b.
1669                  *
1670                  * If cow is true, then we might be changing slot zero,
1671                  * which may require changing the parent.  So, we can't
1672                  * drop the lock until after we know which slot we're
1673                  * operating on.
1674                  */
1675                 if (!cow)
1676                         btrfs_unlock_up_safe(p, level + 1);
1677
1678                 ret = bin_search(b, key, level, &slot);
1679
1680                 if (level != 0) {
1681                         int dec = 0;
1682                         if (ret && slot > 0) {
1683                                 dec = 1;
1684                                 slot -= 1;
1685                         }
1686                         p->slots[level] = slot;
1687                         err = setup_nodes_for_search(trans, root, p, b, level,
1688                                                      ins_len);
1689                         if (err == -EAGAIN)
1690                                 goto again;
1691                         if (err) {
1692                                 ret = err;
1693                                 goto done;
1694                         }
1695                         b = p->nodes[level];
1696                         slot = p->slots[level];
1697
1698                         unlock_up(p, level, lowest_unlock);
1699
1700                         if (level == lowest_level) {
1701                                 if (dec)
1702                                         p->slots[level]++;
1703                                 goto done;
1704                         }
1705
1706                         err = read_block_for_search(trans, root, p,
1707                                                     &b, level, slot, key);
1708                         if (err == -EAGAIN)
1709                                 goto again;
1710                         if (err) {
1711                                 ret = err;
1712                                 goto done;
1713                         }
1714
1715                         if (!p->skip_locking) {
1716                                 btrfs_clear_path_blocking(p, NULL);
1717                                 err = btrfs_try_spin_lock(b);
1718
1719                                 if (!err) {
1720                                         btrfs_set_path_blocking(p);
1721                                         btrfs_tree_lock(b);
1722                                         btrfs_clear_path_blocking(p, b);
1723                                 }
1724                         }
1725                 } else {
1726                         p->slots[level] = slot;
1727                         if (ins_len > 0 &&
1728                             btrfs_leaf_free_space(root, b) < ins_len) {
1729                                 btrfs_set_path_blocking(p);
1730                                 err = split_leaf(trans, root, key,
1731                                                  p, ins_len, ret == 0);
1732                                 btrfs_clear_path_blocking(p, NULL);
1733
1734                                 BUG_ON(err > 0);
1735                                 if (err) {
1736                                         ret = err;
1737                                         goto done;
1738                                 }
1739                         }
1740                         if (!p->search_for_split)
1741                                 unlock_up(p, level, lowest_unlock);
1742                         goto done;
1743                 }
1744         }
1745         ret = 1;
1746 done:
1747         /*
1748          * we don't really know what they plan on doing with the path
1749          * from here on, so for now just mark it as blocking
1750          */
1751         if (!p->leave_spinning)
1752                 btrfs_set_path_blocking(p);
1753         if (ret < 0)
1754                 btrfs_release_path(root, p);
1755         return ret;
1756 }
1757
1758 /*
1759  * adjust the pointers going up the tree, starting at level
1760  * making sure the right key of each node is points to 'key'.
1761  * This is used after shifting pointers to the left, so it stops
1762  * fixing up pointers when a given leaf/node is not in slot 0 of the
1763  * higher levels
1764  *
1765  * If this fails to write a tree block, it returns -1, but continues
1766  * fixing up the blocks in ram so the tree is consistent.
1767  */
1768 static int fixup_low_keys(struct btrfs_trans_handle *trans,
1769                           struct btrfs_root *root, struct btrfs_path *path,
1770                           struct btrfs_disk_key *key, int level)
1771 {
1772         int i;
1773         int ret = 0;
1774         struct extent_buffer *t;
1775
1776         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1777                 int tslot = path->slots[i];
1778                 if (!path->nodes[i])
1779                         break;
1780                 t = path->nodes[i];
1781                 btrfs_set_node_key(t, key, tslot);
1782                 btrfs_mark_buffer_dirty(path->nodes[i]);
1783                 if (tslot != 0)
1784                         break;
1785         }
1786         return ret;
1787 }
1788
1789 /*
1790  * update item key.
1791  *
1792  * This function isn't completely safe. It's the caller's responsibility
1793  * that the new key won't break the order
1794  */
1795 int btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
1796                             struct btrfs_root *root, struct btrfs_path *path,
1797                             struct btrfs_key *new_key)
1798 {
1799         struct btrfs_disk_key disk_key;
1800         struct extent_buffer *eb;
1801         int slot;
1802
1803         eb = path->nodes[0];
1804         slot = path->slots[0];
1805         if (slot > 0) {
1806                 btrfs_item_key(eb, &disk_key, slot - 1);
1807                 if (comp_keys(&disk_key, new_key) >= 0)
1808                         return -1;
1809         }
1810         if (slot < btrfs_header_nritems(eb) - 1) {
1811                 btrfs_item_key(eb, &disk_key, slot + 1);
1812                 if (comp_keys(&disk_key, new_key) <= 0)
1813                         return -1;
1814         }
1815
1816         btrfs_cpu_key_to_disk(&disk_key, new_key);
1817         btrfs_set_item_key(eb, &disk_key, slot);
1818         btrfs_mark_buffer_dirty(eb);
1819         if (slot == 0)
1820                 fixup_low_keys(trans, root, path, &disk_key, 1);
1821         return 0;
1822 }
1823
1824 /*
1825  * try to push data from one node into the next node left in the
1826  * tree.
1827  *
1828  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
1829  * error, and > 0 if there was no room in the left hand block.
1830  */
1831 static int push_node_left(struct btrfs_trans_handle *trans,
1832                           struct btrfs_root *root, struct extent_buffer *dst,
1833                           struct extent_buffer *src, int empty)
1834 {
1835         int push_items = 0;
1836         int src_nritems;
1837         int dst_nritems;
1838         int ret = 0;
1839
1840         src_nritems = btrfs_header_nritems(src);
1841         dst_nritems = btrfs_header_nritems(dst);
1842         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
1843         WARN_ON(btrfs_header_generation(src) != trans->transid);
1844         WARN_ON(btrfs_header_generation(dst) != trans->transid);
1845
1846         if (!empty && src_nritems <= 8)
1847                 return 1;
1848
1849         if (push_items <= 0)
1850                 return 1;
1851
1852         if (empty) {
1853                 push_items = min(src_nritems, push_items);
1854                 if (push_items < src_nritems) {
1855                         /* leave at least 8 pointers in the node if
1856                          * we aren't going to empty it
1857                          */
1858                         if (src_nritems - push_items < 8) {
1859                                 if (push_items <= 8)
1860                                         return 1;
1861                                 push_items -= 8;
1862                         }
1863                 }
1864         } else
1865                 push_items = min(src_nritems - 8, push_items);
1866
1867         copy_extent_buffer(dst, src,
1868                            btrfs_node_key_ptr_offset(dst_nritems),
1869                            btrfs_node_key_ptr_offset(0),
1870                            push_items * sizeof(struct btrfs_key_ptr));
1871
1872         if (push_items < src_nritems) {
1873                 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
1874                                       btrfs_node_key_ptr_offset(push_items),
1875                                       (src_nritems - push_items) *
1876                                       sizeof(struct btrfs_key_ptr));
1877         }
1878         btrfs_set_header_nritems(src, src_nritems - push_items);
1879         btrfs_set_header_nritems(dst, dst_nritems + push_items);
1880         btrfs_mark_buffer_dirty(src);
1881         btrfs_mark_buffer_dirty(dst);
1882
1883         return ret;
1884 }
1885
1886 /*
1887  * try to push data from one node into the next node right in the
1888  * tree.
1889  *
1890  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
1891  * error, and > 0 if there was no room in the right hand block.
1892  *
1893  * this will  only push up to 1/2 the contents of the left node over
1894  */
1895 static int balance_node_right(struct btrfs_trans_handle *trans,
1896                               struct btrfs_root *root,
1897                               struct extent_buffer *dst,
1898                               struct extent_buffer *src)
1899 {
1900         int push_items = 0;
1901         int max_push;
1902         int src_nritems;
1903         int dst_nritems;
1904         int ret = 0;
1905
1906         WARN_ON(btrfs_header_generation(src) != trans->transid);
1907         WARN_ON(btrfs_header_generation(dst) != trans->transid);
1908
1909         src_nritems = btrfs_header_nritems(src);
1910         dst_nritems = btrfs_header_nritems(dst);
1911         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
1912         if (push_items <= 0)
1913                 return 1;
1914
1915         if (src_nritems < 4)
1916                 return 1;
1917
1918         max_push = src_nritems / 2 + 1;
1919         /* don't try to empty the node */
1920         if (max_push >= src_nritems)
1921                 return 1;
1922
1923         if (max_push < push_items)
1924                 push_items = max_push;
1925
1926         memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
1927                                       btrfs_node_key_ptr_offset(0),
1928                                       (dst_nritems) *
1929                                       sizeof(struct btrfs_key_ptr));
1930
1931         copy_extent_buffer(dst, src,
1932                            btrfs_node_key_ptr_offset(0),
1933                            btrfs_node_key_ptr_offset(src_nritems - push_items),
1934                            push_items * sizeof(struct btrfs_key_ptr));
1935
1936         btrfs_set_header_nritems(src, src_nritems - push_items);
1937         btrfs_set_header_nritems(dst, dst_nritems + push_items);
1938
1939         btrfs_mark_buffer_dirty(src);
1940         btrfs_mark_buffer_dirty(dst);
1941
1942         return ret;
1943 }
1944
1945 /*
1946  * helper function to insert a new root level in the tree.
1947  * A new node is allocated, and a single item is inserted to
1948  * point to the existing root
1949  *
1950  * returns zero on success or < 0 on failure.
1951  */
1952 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
1953                            struct btrfs_root *root,
1954                            struct btrfs_path *path, int level)
1955 {
1956         u64 lower_gen;
1957         struct extent_buffer *lower;
1958         struct extent_buffer *c;
1959         struct extent_buffer *old;
1960         struct btrfs_disk_key lower_key;
1961
1962         BUG_ON(path->nodes[level]);
1963         BUG_ON(path->nodes[level-1] != root->node);
1964
1965         lower = path->nodes[level-1];
1966         if (level == 1)
1967                 btrfs_item_key(lower, &lower_key, 0);
1968         else
1969                 btrfs_node_key(lower, &lower_key, 0);
1970
1971         c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
1972                                    root->root_key.objectid, &lower_key,
1973                                    level, root->node->start, 0);
1974         if (IS_ERR(c))
1975                 return PTR_ERR(c);
1976
1977         root_add_used(root, root->nodesize);
1978
1979         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
1980         btrfs_set_header_nritems(c, 1);
1981         btrfs_set_header_level(c, level);
1982         btrfs_set_header_bytenr(c, c->start);
1983         btrfs_set_header_generation(c, trans->transid);
1984         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
1985         btrfs_set_header_owner(c, root->root_key.objectid);
1986
1987         write_extent_buffer(c, root->fs_info->fsid,
1988                             (unsigned long)btrfs_header_fsid(c),
1989                             BTRFS_FSID_SIZE);
1990
1991         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
1992                             (unsigned long)btrfs_header_chunk_tree_uuid(c),
1993                             BTRFS_UUID_SIZE);
1994
1995         btrfs_set_node_key(c, &lower_key, 0);
1996         btrfs_set_node_blockptr(c, 0, lower->start);
1997         lower_gen = btrfs_header_generation(lower);
1998         WARN_ON(lower_gen != trans->transid);
1999
2000         btrfs_set_node_ptr_generation(c, 0, lower_gen);
2001
2002         btrfs_mark_buffer_dirty(c);
2003
2004         old = root->node;
2005         rcu_assign_pointer(root->node, c);
2006
2007         /* the super has an extra ref to root->node */
2008         free_extent_buffer(old);
2009
2010         add_root_to_dirty_list(root);
2011         extent_buffer_get(c);
2012         path->nodes[level] = c;
2013         path->locks[level] = 1;
2014         path->slots[level] = 0;
2015         return 0;
2016 }
2017
2018 /*
2019  * worker function to insert a single pointer in a node.
2020  * the node should have enough room for the pointer already
2021  *
2022  * slot and level indicate where you want the key to go, and
2023  * blocknr is the block the key points to.
2024  *
2025  * returns zero on success and < 0 on any error
2026  */
2027 static int insert_ptr(struct btrfs_trans_handle *trans, struct btrfs_root
2028                       *root, struct btrfs_path *path, struct btrfs_disk_key
2029                       *key, u64 bytenr, int slot, int level)
2030 {
2031         struct extent_buffer *lower;
2032         int nritems;
2033
2034         BUG_ON(!path->nodes[level]);
2035         btrfs_assert_tree_locked(path->nodes[level]);
2036         lower = path->nodes[level];
2037         nritems = btrfs_header_nritems(lower);
2038         BUG_ON(slot > nritems);
2039         if (nritems == BTRFS_NODEPTRS_PER_BLOCK(root))
2040                 BUG();
2041         if (slot != nritems) {
2042                 memmove_extent_buffer(lower,
2043                               btrfs_node_key_ptr_offset(slot + 1),
2044                               btrfs_node_key_ptr_offset(slot),
2045                               (nritems - slot) * sizeof(struct btrfs_key_ptr));
2046         }
2047         btrfs_set_node_key(lower, key, slot);
2048         btrfs_set_node_blockptr(lower, slot, bytenr);
2049         WARN_ON(trans->transid == 0);
2050         btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2051         btrfs_set_header_nritems(lower, nritems + 1);
2052         btrfs_mark_buffer_dirty(lower);
2053         return 0;
2054 }
2055
2056 /*
2057  * split the node at the specified level in path in two.
2058  * The path is corrected to point to the appropriate node after the split
2059  *
2060  * Before splitting this tries to make some room in the node by pushing
2061  * left and right, if either one works, it returns right away.
2062  *
2063  * returns 0 on success and < 0 on failure
2064  */
2065 static noinline int split_node(struct btrfs_trans_handle *trans,
2066                                struct btrfs_root *root,
2067                                struct btrfs_path *path, int level)
2068 {
2069         struct extent_buffer *c;
2070         struct extent_buffer *split;
2071         struct btrfs_disk_key disk_key;
2072         int mid;
2073         int ret;
2074         int wret;
2075         u32 c_nritems;
2076
2077         c = path->nodes[level];
2078         WARN_ON(btrfs_header_generation(c) != trans->transid);
2079         if (c == root->node) {
2080                 /* trying to split the root, lets make a new one */
2081                 ret = insert_new_root(trans, root, path, level + 1);
2082                 if (ret)
2083                         return ret;
2084         } else {
2085                 ret = push_nodes_for_insert(trans, root, path, level);
2086                 c = path->nodes[level];
2087                 if (!ret && btrfs_header_nritems(c) <
2088                     BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
2089                         return 0;
2090                 if (ret < 0)
2091                         return ret;
2092         }
2093
2094         c_nritems = btrfs_header_nritems(c);
2095         mid = (c_nritems + 1) / 2;
2096         btrfs_node_key(c, &disk_key, mid);
2097
2098         split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
2099                                         root->root_key.objectid,
2100                                         &disk_key, level, c->start, 0);
2101         if (IS_ERR(split))
2102                 return PTR_ERR(split);
2103
2104         root_add_used(root, root->nodesize);
2105
2106         memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
2107         btrfs_set_header_level(split, btrfs_header_level(c));
2108         btrfs_set_header_bytenr(split, split->start);
2109         btrfs_set_header_generation(split, trans->transid);
2110         btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
2111         btrfs_set_header_owner(split, root->root_key.objectid);
2112         write_extent_buffer(split, root->fs_info->fsid,
2113                             (unsigned long)btrfs_header_fsid(split),
2114                             BTRFS_FSID_SIZE);
2115         write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
2116                             (unsigned long)btrfs_header_chunk_tree_uuid(split),
2117                             BTRFS_UUID_SIZE);
2118
2119
2120         copy_extent_buffer(split, c,
2121                            btrfs_node_key_ptr_offset(0),
2122                            btrfs_node_key_ptr_offset(mid),
2123                            (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2124         btrfs_set_header_nritems(split, c_nritems - mid);
2125         btrfs_set_header_nritems(c, mid);
2126         ret = 0;
2127
2128         btrfs_mark_buffer_dirty(c);
2129         btrfs_mark_buffer_dirty(split);
2130
2131         wret = insert_ptr(trans, root, path, &disk_key, split->start,
2132                           path->slots[level + 1] + 1,
2133                           level + 1);
2134         if (wret)
2135                 ret = wret;
2136
2137         if (path->slots[level] >= mid) {
2138                 path->slots[level] -= mid;
2139                 btrfs_tree_unlock(c);
2140                 free_extent_buffer(c);
2141                 path->nodes[level] = split;
2142                 path->slots[level + 1] += 1;
2143         } else {
2144                 btrfs_tree_unlock(split);
2145                 free_extent_buffer(split);
2146         }
2147         return ret;
2148 }
2149
2150 /*
2151  * how many bytes are required to store the items in a leaf.  start
2152  * and nr indicate which items in the leaf to check.  This totals up the
2153  * space used both by the item structs and the item data
2154  */
2155 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2156 {
2157         int data_len;
2158         int nritems = btrfs_header_nritems(l);
2159         int end = min(nritems, start + nr) - 1;
2160
2161         if (!nr)
2162                 return 0;
2163         data_len = btrfs_item_end_nr(l, start);
2164         data_len = data_len - btrfs_item_offset_nr(l, end);
2165         data_len += sizeof(struct btrfs_item) * nr;
2166         WARN_ON(data_len < 0);
2167         return data_len;
2168 }
2169
2170 /*
2171  * The space between the end of the leaf items and
2172  * the start of the leaf data.  IOW, how much room
2173  * the leaf has left for both items and data
2174  */
2175 noinline int btrfs_leaf_free_space(struct btrfs_root *root,
2176                                    struct extent_buffer *leaf)
2177 {
2178         int nritems = btrfs_header_nritems(leaf);
2179         int ret;
2180         ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
2181         if (ret < 0) {
2182                 printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
2183                        "used %d nritems %d\n",
2184                        ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
2185                        leaf_space_used(leaf, 0, nritems), nritems);
2186         }
2187         return ret;
2188 }
2189
2190 /*
2191  * min slot controls the lowest index we're willing to push to the
2192  * right.  We'll push up to and including min_slot, but no lower
2193  */
2194 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
2195                                       struct btrfs_root *root,
2196                                       struct btrfs_path *path,
2197                                       int data_size, int empty,
2198                                       struct extent_buffer *right,
2199                                       int free_space, u32 left_nritems,
2200                                       u32 min_slot)
2201 {
2202         struct extent_buffer *left = path->nodes[0];
2203         struct extent_buffer *upper = path->nodes[1];
2204         struct btrfs_disk_key disk_key;
2205         int slot;
2206         u32 i;
2207         int push_space = 0;
2208         int push_items = 0;
2209         struct btrfs_item *item;
2210         u32 nr;
2211         u32 right_nritems;
2212         u32 data_end;
2213         u32 this_item_size;
2214
2215         if (empty)
2216                 nr = 0;
2217         else
2218                 nr = max_t(u32, 1, min_slot);
2219
2220         if (path->slots[0] >= left_nritems)
2221                 push_space += data_size;
2222
2223         slot = path->slots[1];
2224         i = left_nritems - 1;
2225         while (i >= nr) {
2226                 item = btrfs_item_nr(left, i);
2227
2228                 if (!empty && push_items > 0) {
2229                         if (path->slots[0] > i)
2230                                 break;
2231                         if (path->slots[0] == i) {
2232                                 int space = btrfs_leaf_free_space(root, left);
2233                                 if (space + push_space * 2 > free_space)
2234                                         break;
2235                         }
2236                 }
2237
2238                 if (path->slots[0] == i)
2239                         push_space += data_size;
2240
2241                 if (!left->map_token) {
2242                         map_extent_buffer(left, (unsigned long)item,
2243                                         sizeof(struct btrfs_item),
2244                                         &left->map_token, &left->kaddr,
2245                                         &left->map_start, &left->map_len,
2246                                         KM_USER1);
2247                 }
2248
2249                 this_item_size = btrfs_item_size(left, item);
2250                 if (this_item_size + sizeof(*item) + push_space > free_space)
2251                         break;
2252
2253                 push_items++;
2254                 push_space += this_item_size + sizeof(*item);
2255                 if (i == 0)
2256                         break;
2257                 i--;
2258         }
2259         if (left->map_token) {
2260                 unmap_extent_buffer(left, left->map_token, KM_USER1);
2261                 left->map_token = NULL;
2262         }
2263
2264         if (push_items == 0)
2265                 goto out_unlock;
2266
2267         if (!empty && push_items == left_nritems)
2268                 WARN_ON(1);
2269
2270         /* push left to right */
2271         right_nritems = btrfs_header_nritems(right);
2272
2273         push_space = btrfs_item_end_nr(left, left_nritems - push_items);
2274         push_space -= leaf_data_end(root, left);
2275
2276         /* make room in the right data area */
2277         data_end = leaf_data_end(root, right);
2278         memmove_extent_buffer(right,
2279                               btrfs_leaf_data(right) + data_end - push_space,
2280                               btrfs_leaf_data(right) + data_end,
2281                               BTRFS_LEAF_DATA_SIZE(root) - data_end);
2282
2283         /* copy from the left data area */
2284         copy_extent_buffer(right, left, btrfs_leaf_data(right) +
2285                      BTRFS_LEAF_DATA_SIZE(root) - push_space,
2286                      btrfs_leaf_data(left) + leaf_data_end(root, left),
2287                      push_space);
2288
2289         memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
2290                               btrfs_item_nr_offset(0),
2291                               right_nritems * sizeof(struct btrfs_item));
2292
2293         /* copy the items from left to right */
2294         copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
2295                    btrfs_item_nr_offset(left_nritems - push_items),
2296                    push_items * sizeof(struct btrfs_item));
2297
2298         /* update the item pointers */
2299         right_nritems += push_items;
2300         btrfs_set_header_nritems(right, right_nritems);
2301         push_space = BTRFS_LEAF_DATA_SIZE(root);
2302         for (i = 0; i < right_nritems; i++) {
2303                 item = btrfs_item_nr(right, i);
2304                 if (!right->map_token) {
2305                         map_extent_buffer(right, (unsigned long)item,
2306                                         sizeof(struct btrfs_item),
2307                                         &right->map_token, &right->kaddr,
2308                                         &right->map_start, &right->map_len,
2309                                         KM_USER1);
2310                 }
2311                 push_space -= btrfs_item_size(right, item);
2312                 btrfs_set_item_offset(right, item, push_space);
2313         }
2314
2315         if (right->map_token) {
2316                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2317                 right->map_token = NULL;
2318         }
2319         left_nritems -= push_items;
2320         btrfs_set_header_nritems(left, left_nritems);
2321
2322         if (left_nritems)
2323                 btrfs_mark_buffer_dirty(left);
2324         else
2325                 clean_tree_block(trans, root, left);
2326
2327         btrfs_mark_buffer_dirty(right);
2328
2329         btrfs_item_key(right, &disk_key, 0);
2330         btrfs_set_node_key(upper, &disk_key, slot + 1);
2331         btrfs_mark_buffer_dirty(upper);
2332
2333         /* then fixup the leaf pointer in the path */
2334         if (path->slots[0] >= left_nritems) {
2335                 path->slots[0] -= left_nritems;
2336                 if (btrfs_header_nritems(path->nodes[0]) == 0)
2337                         clean_tree_block(trans, root, path->nodes[0]);
2338                 btrfs_tree_unlock(path->nodes[0]);
2339                 free_extent_buffer(path->nodes[0]);
2340                 path->nodes[0] = right;
2341                 path->slots[1] += 1;
2342         } else {
2343                 btrfs_tree_unlock(right);
2344                 free_extent_buffer(right);
2345         }
2346         return 0;
2347
2348 out_unlock:
2349         btrfs_tree_unlock(right);
2350         free_extent_buffer(right);
2351         return 1;
2352 }
2353
2354 /*
2355  * push some data in the path leaf to the right, trying to free up at
2356  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2357  *
2358  * returns 1 if the push failed because the other node didn't have enough
2359  * room, 0 if everything worked out and < 0 if there were major errors.
2360  *
2361  * this will push starting from min_slot to the end of the leaf.  It won't
2362  * push any slot lower than min_slot
2363  */
2364 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
2365                            *root, struct btrfs_path *path,
2366                            int min_data_size, int data_size,
2367                            int empty, u32 min_slot)
2368 {
2369         struct extent_buffer *left = path->nodes[0];
2370         struct extent_buffer *right;
2371         struct extent_buffer *upper;
2372         int slot;
2373         int free_space;
2374         u32 left_nritems;
2375         int ret;
2376
2377         if (!path->nodes[1])
2378                 return 1;
2379
2380         slot = path->slots[1];
2381         upper = path->nodes[1];
2382         if (slot >= btrfs_header_nritems(upper) - 1)
2383                 return 1;
2384
2385         btrfs_assert_tree_locked(path->nodes[1]);
2386
2387         right = read_node_slot(root, upper, slot + 1);
2388         if (right == NULL)
2389                 return 1;
2390
2391         btrfs_tree_lock(right);
2392         btrfs_set_lock_blocking(right);
2393
2394         free_space = btrfs_leaf_free_space(root, right);
2395         if (free_space < data_size)
2396                 goto out_unlock;
2397
2398         /* cow and double check */
2399         ret = btrfs_cow_block(trans, root, right, upper,
2400                               slot + 1, &right);
2401         if (ret)
2402                 goto out_unlock;
2403
2404         free_space = btrfs_leaf_free_space(root, right);
2405         if (free_space < data_size)
2406                 goto out_unlock;
2407
2408         left_nritems = btrfs_header_nritems(left);
2409         if (left_nritems == 0)
2410                 goto out_unlock;
2411
2412         return __push_leaf_right(trans, root, path, min_data_size, empty,
2413                                 right, free_space, left_nritems, min_slot);
2414 out_unlock:
2415         btrfs_tree_unlock(right);
2416         free_extent_buffer(right);
2417         return 1;
2418 }
2419
2420 /*
2421  * push some data in the path leaf to the left, trying to free up at
2422  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2423  *
2424  * max_slot can put a limit on how far into the leaf we'll push items.  The
2425  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
2426  * items
2427  */
2428 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
2429                                      struct btrfs_root *root,
2430                                      struct btrfs_path *path, int data_size,
2431                                      int empty, struct extent_buffer *left,
2432                                      int free_space, u32 right_nritems,
2433                                      u32 max_slot)
2434 {
2435         struct btrfs_disk_key disk_key;
2436         struct extent_buffer *right = path->nodes[0];
2437         int i;
2438         int push_space = 0;
2439         int push_items = 0;
2440         struct btrfs_item *item;
2441         u32 old_left_nritems;
2442         u32 nr;
2443         int ret = 0;
2444         int wret;
2445         u32 this_item_size;
2446         u32 old_left_item_size;
2447
2448         if (empty)
2449                 nr = min(right_nritems, max_slot);
2450         else
2451                 nr = min(right_nritems - 1, max_slot);
2452
2453         for (i = 0; i < nr; i++) {
2454                 item = btrfs_item_nr(right, i);
2455                 if (!right->map_token) {
2456                         map_extent_buffer(right, (unsigned long)item,
2457                                         sizeof(struct btrfs_item),
2458                                         &right->map_token, &right->kaddr,
2459                                         &right->map_start, &right->map_len,
2460                                         KM_USER1);
2461                 }
2462
2463                 if (!empty && push_items > 0) {
2464                         if (path->slots[0] < i)
2465                                 break;
2466                         if (path->slots[0] == i) {
2467                                 int space = btrfs_leaf_free_space(root, right);
2468                                 if (space + push_space * 2 > free_space)
2469                                         break;
2470                         }
2471                 }
2472
2473                 if (path->slots[0] == i)
2474                         push_space += data_size;
2475
2476                 this_item_size = btrfs_item_size(right, item);
2477                 if (this_item_size + sizeof(*item) + push_space > free_space)
2478                         break;
2479
2480                 push_items++;
2481                 push_space += this_item_size + sizeof(*item);
2482         }
2483
2484         if (right->map_token) {
2485                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2486                 right->map_token = NULL;
2487         }
2488
2489         if (push_items == 0) {
2490                 ret = 1;
2491                 goto out;
2492         }
2493         if (!empty && push_items == btrfs_header_nritems(right))
2494                 WARN_ON(1);
2495
2496         /* push data from right to left */
2497         copy_extent_buffer(left, right,
2498                            btrfs_item_nr_offset(btrfs_header_nritems(left)),
2499                            btrfs_item_nr_offset(0),
2500                            push_items * sizeof(struct btrfs_item));
2501
2502         push_space = BTRFS_LEAF_DATA_SIZE(root) -
2503                      btrfs_item_offset_nr(right, push_items - 1);
2504
2505         copy_extent_buffer(left, right, btrfs_leaf_data(left) +
2506                      leaf_data_end(root, left) - push_space,
2507                      btrfs_leaf_data(right) +
2508                      btrfs_item_offset_nr(right, push_items - 1),
2509                      push_space);
2510         old_left_nritems = btrfs_header_nritems(left);
2511         BUG_ON(old_left_nritems <= 0);
2512
2513         old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
2514         for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
2515                 u32 ioff;
2516
2517                 item = btrfs_item_nr(left, i);
2518                 if (!left->map_token) {
2519                         map_extent_buffer(left, (unsigned long)item,
2520                                         sizeof(struct btrfs_item),
2521                                         &left->map_token, &left->kaddr,
2522                                         &left->map_start, &left->map_len,
2523                                         KM_USER1);
2524                 }
2525
2526                 ioff = btrfs_item_offset(left, item);
2527                 btrfs_set_item_offset(left, item,
2528                       ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size));
2529         }
2530         btrfs_set_header_nritems(left, old_left_nritems + push_items);
2531         if (left->map_token) {
2532                 unmap_extent_buffer(left, left->map_token, KM_USER1);
2533                 left->map_token = NULL;
2534         }
2535
2536         /* fixup right node */
2537         if (push_items > right_nritems) {
2538                 printk(KERN_CRIT "push items %d nr %u\n", push_items,
2539                        right_nritems);
2540                 WARN_ON(1);
2541         }
2542
2543         if (push_items < right_nritems) {
2544                 push_space = btrfs_item_offset_nr(right, push_items - 1) -
2545                                                   leaf_data_end(root, right);
2546                 memmove_extent_buffer(right, btrfs_leaf_data(right) +
2547                                       BTRFS_LEAF_DATA_SIZE(root) - push_space,
2548                                       btrfs_leaf_data(right) +
2549                                       leaf_data_end(root, right), push_space);
2550
2551                 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
2552                               btrfs_item_nr_offset(push_items),
2553                              (btrfs_header_nritems(right) - push_items) *
2554                              sizeof(struct btrfs_item));
2555         }
2556         right_nritems -= push_items;
2557         btrfs_set_header_nritems(right, right_nritems);
2558         push_space = BTRFS_LEAF_DATA_SIZE(root);
2559         for (i = 0; i < right_nritems; i++) {
2560                 item = btrfs_item_nr(right, i);
2561
2562                 if (!right->map_token) {
2563                         map_extent_buffer(right, (unsigned long)item,
2564                                         sizeof(struct btrfs_item),
2565                                         &right->map_token, &right->kaddr,
2566                                         &right->map_start, &right->map_len,
2567                                         KM_USER1);
2568                 }
2569
2570                 push_space = push_space - btrfs_item_size(right, item);
2571                 btrfs_set_item_offset(right, item, push_space);
2572         }
2573         if (right->map_token) {
2574                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2575                 right->map_token = NULL;
2576         }
2577
2578         btrfs_mark_buffer_dirty(left);
2579         if (right_nritems)
2580                 btrfs_mark_buffer_dirty(right);
2581         else
2582                 clean_tree_block(trans, root, right);
2583
2584         btrfs_item_key(right, &disk_key, 0);
2585         wret = fixup_low_keys(trans, root, path, &disk_key, 1);
2586         if (wret)
2587                 ret = wret;
2588
2589         /* then fixup the leaf pointer in the path */
2590         if (path->slots[0] < push_items) {
2591                 path->slots[0] += old_left_nritems;
2592                 btrfs_tree_unlock(path->nodes[0]);
2593                 free_extent_buffer(path->nodes[0]);
2594                 path->nodes[0] = left;
2595                 path->slots[1] -= 1;
2596         } else {
2597                 btrfs_tree_unlock(left);
2598                 free_extent_buffer(left);
2599                 path->slots[0] -= push_items;
2600         }
2601         BUG_ON(path->slots[0] < 0);
2602         return ret;
2603 out:
2604         btrfs_tree_unlock(left);
2605         free_extent_buffer(left);
2606         return ret;
2607 }
2608
2609 /*
2610  * push some data in the path leaf to the left, trying to free up at
2611  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2612  *
2613  * max_slot can put a limit on how far into the leaf we'll push items.  The
2614  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
2615  * items
2616  */
2617 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
2618                           *root, struct btrfs_path *path, int min_data_size,
2619                           int data_size, int empty, u32 max_slot)
2620 {
2621         struct extent_buffer *right = path->nodes[0];
2622         struct extent_buffer *left;
2623         int slot;
2624         int free_space;
2625         u32 right_nritems;
2626         int ret = 0;
2627
2628         slot = path->slots[1];
2629         if (slot == 0)
2630                 return 1;
2631         if (!path->nodes[1])
2632                 return 1;
2633
2634         right_nritems = btrfs_header_nritems(right);
2635         if (right_nritems == 0)
2636                 return 1;
2637
2638         btrfs_assert_tree_locked(path->nodes[1]);
2639
2640         left = read_node_slot(root, path->nodes[1], slot - 1);
2641         if (left == NULL)
2642                 return 1;
2643
2644         btrfs_tree_lock(left);
2645         btrfs_set_lock_blocking(left);
2646
2647         free_space = btrfs_leaf_free_space(root, left);
2648         if (free_space < data_size) {
2649                 ret = 1;
2650                 goto out;
2651         }
2652
2653         /* cow and double check */
2654         ret = btrfs_cow_block(trans, root, left,
2655                               path->nodes[1], slot - 1, &left);
2656         if (ret) {
2657                 /* we hit -ENOSPC, but it isn't fatal here */
2658                 ret = 1;
2659                 goto out;
2660         }
2661
2662         free_space = btrfs_leaf_free_space(root, left);
2663         if (free_space < data_size) {
2664                 ret = 1;
2665                 goto out;
2666         }
2667
2668         return __push_leaf_left(trans, root, path, min_data_size,
2669                                empty, left, free_space, right_nritems,
2670                                max_slot);
2671 out:
2672         btrfs_tree_unlock(left);
2673         free_extent_buffer(left);
2674         return ret;
2675 }
2676
2677 /*
2678  * split the path's leaf in two, making sure there is at least data_size
2679  * available for the resulting leaf level of the path.
2680  *
2681  * returns 0 if all went well and < 0 on failure.
2682  */
2683 static noinline int copy_for_split(struct btrfs_trans_handle *trans,
2684                                struct btrfs_root *root,
2685                                struct btrfs_path *path,
2686                                struct extent_buffer *l,
2687                                struct extent_buffer *right,
2688                                int slot, int mid, int nritems)
2689 {
2690         int data_copy_size;
2691         int rt_data_off;
2692         int i;
2693         int ret = 0;
2694         int wret;
2695         struct btrfs_disk_key disk_key;
2696
2697         nritems = nritems - mid;
2698         btrfs_set_header_nritems(right, nritems);
2699         data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
2700
2701         copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
2702                            btrfs_item_nr_offset(mid),
2703                            nritems * sizeof(struct btrfs_item));
2704
2705         copy_extent_buffer(right, l,
2706                      btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
2707                      data_copy_size, btrfs_leaf_data(l) +
2708                      leaf_data_end(root, l), data_copy_size);
2709
2710         rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
2711                       btrfs_item_end_nr(l, mid);
2712
2713         for (i = 0; i < nritems; i++) {
2714                 struct btrfs_item *item = btrfs_item_nr(right, i);
2715                 u32 ioff;
2716
2717                 if (!right->map_token) {
2718                         map_extent_buffer(right, (unsigned long)item,
2719                                         sizeof(struct btrfs_item),
2720                                         &right->map_token, &right->kaddr,
2721                                         &right->map_start, &right->map_len,
2722                                         KM_USER1);
2723                 }
2724
2725                 ioff = btrfs_item_offset(right, item);
2726                 btrfs_set_item_offset(right, item, ioff + rt_data_off);
2727         }
2728
2729         if (right->map_token) {
2730                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2731                 right->map_token = NULL;
2732         }
2733
2734         btrfs_set_header_nritems(l, mid);
2735         ret = 0;
2736         btrfs_item_key(right, &disk_key, 0);
2737         wret = insert_ptr(trans, root, path, &disk_key, right->start,
2738                           path->slots[1] + 1, 1);
2739         if (wret)
2740                 ret = wret;
2741
2742         btrfs_mark_buffer_dirty(right);
2743         btrfs_mark_buffer_dirty(l);
2744         BUG_ON(path->slots[0] != slot);
2745
2746         if (mid <= slot) {
2747                 btrfs_tree_unlock(path->nodes[0]);
2748                 free_extent_buffer(path->nodes[0]);
2749                 path->nodes[0] = right;
2750                 path->slots[0] -= mid;
2751                 path->slots[1] += 1;
2752         } else {
2753                 btrfs_tree_unlock(right);
2754                 free_extent_buffer(right);
2755         }
2756
2757         BUG_ON(path->slots[0] < 0);
2758
2759         return ret;
2760 }
2761
2762 /*
2763  * double splits happen when we need to insert a big item in the middle
2764  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
2765  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
2766  *          A                 B                 C
2767  *
2768  * We avoid this by trying to push the items on either side of our target
2769  * into the adjacent leaves.  If all goes well we can avoid the double split
2770  * completely.
2771  */
2772 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
2773                                           struct btrfs_root *root,
2774                                           struct btrfs_path *path,
2775                                           int data_size)
2776 {
2777         int ret;
2778         int progress = 0;
2779         int slot;
2780         u32 nritems;
2781
2782         slot = path->slots[0];
2783
2784         /*
2785          * try to push all the items after our slot into the
2786          * right leaf
2787          */
2788         ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
2789         if (ret < 0)
2790                 return ret;
2791
2792         if (ret == 0)
2793                 progress++;
2794
2795         nritems = btrfs_header_nritems(path->nodes[0]);
2796         /*
2797          * our goal is to get our slot at the start or end of a leaf.  If
2798          * we've done so we're done
2799          */
2800         if (path->slots[0] == 0 || path->slots[0] == nritems)
2801                 return 0;
2802
2803         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
2804                 return 0;
2805
2806         /* try to push all the items before our slot into the next leaf */
2807         slot = path->slots[0];
2808         ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
2809         if (ret < 0)
2810                 return ret;
2811
2812         if (ret == 0)
2813                 progress++;
2814
2815         if (progress)
2816                 return 0;
2817         return 1;
2818 }
2819
2820 /*
2821  * split the path's leaf in two, making sure there is at least data_size
2822  * available for the resulting leaf level of the path.
2823  *
2824  * returns 0 if all went well and < 0 on failure.
2825  */
2826 static noinline int split_leaf(struct btrfs_trans_handle *trans,
2827                                struct btrfs_root *root,
2828                                struct btrfs_key *ins_key,
2829                                struct btrfs_path *path, int data_size,
2830                                int extend)
2831 {
2832         struct btrfs_disk_key disk_key;
2833         struct extent_buffer *l;
2834         u32 nritems;
2835         int mid;
2836         int slot;
2837         struct extent_buffer *right;
2838         int ret = 0;
2839         int wret;
2840         int split;
2841         int num_doubles = 0;
2842         int tried_avoid_double = 0;
2843
2844         l = path->nodes[0];
2845         slot = path->slots[0];
2846         if (extend && data_size + btrfs_item_size_nr(l, slot) +
2847             sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
2848                 return -EOVERFLOW;
2849
2850         /* first try to make some room by pushing left and right */
2851         if (data_size) {
2852                 wret = push_leaf_right(trans, root, path, data_size,
2853                                        data_size, 0, 0);
2854                 if (wret < 0)
2855                         return wret;
2856                 if (wret) {
2857                         wret = push_leaf_left(trans, root, path, data_size,
2858                                               data_size, 0, (u32)-1);
2859                         if (wret < 0)
2860                                 return wret;
2861                 }
2862                 l = path->nodes[0];
2863
2864                 /* did the pushes work? */
2865                 if (btrfs_leaf_free_space(root, l) >= data_size)
2866                         return 0;
2867         }
2868
2869         if (!path->nodes[1]) {
2870                 ret = insert_new_root(trans, root, path, 1);
2871                 if (ret)
2872                         return ret;
2873         }
2874 again:
2875         split = 1;
2876         l = path->nodes[0];
2877         slot = path->slots[0];
2878         nritems = btrfs_header_nritems(l);
2879         mid = (nritems + 1) / 2;
2880
2881         if (mid <= slot) {
2882                 if (nritems == 1 ||
2883                     leaf_space_used(l, mid, nritems - mid) + data_size >
2884                         BTRFS_LEAF_DATA_SIZE(root)) {
2885                         if (slot >= nritems) {
2886                                 split = 0;
2887                         } else {
2888                                 mid = slot;
2889                                 if (mid != nritems &&
2890                                     leaf_space_used(l, mid, nritems - mid) +
2891                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2892                                         if (data_size && !tried_avoid_double)
2893                                                 goto push_for_double;
2894                                         split = 2;
2895                                 }
2896                         }
2897                 }
2898         } else {
2899                 if (leaf_space_used(l, 0, mid) + data_size >
2900                         BTRFS_LEAF_DATA_SIZE(root)) {
2901                         if (!extend && data_size && slot == 0) {
2902                                 split = 0;
2903                         } else if ((extend || !data_size) && slot == 0) {
2904                                 mid = 1;
2905                         } else {
2906                                 mid = slot;
2907                                 if (mid != nritems &&
2908                                     leaf_space_used(l, mid, nritems - mid) +
2909                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2910                                         if (data_size && !tried_avoid_double)
2911                                                 goto push_for_double;
2912                                         split = 2 ;
2913                                 }
2914                         }
2915                 }
2916         }
2917
2918         if (split == 0)
2919                 btrfs_cpu_key_to_disk(&disk_key, ins_key);
2920         else
2921                 btrfs_item_key(l, &disk_key, mid);
2922
2923         right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
2924                                         root->root_key.objectid,
2925                                         &disk_key, 0, l->start, 0);
2926         if (IS_ERR(right))
2927                 return PTR_ERR(right);
2928
2929         root_add_used(root, root->leafsize);
2930
2931         memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
2932         btrfs_set_header_bytenr(right, right->start);
2933         btrfs_set_header_generation(right, trans->transid);
2934         btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
2935         btrfs_set_header_owner(right, root->root_key.objectid);
2936         btrfs_set_header_level(right, 0);
2937         write_extent_buffer(right, root->fs_info->fsid,
2938                             (unsigned long)btrfs_header_fsid(right),
2939                             BTRFS_FSID_SIZE);
2940
2941         write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
2942                             (unsigned long)btrfs_header_chunk_tree_uuid(right),
2943                             BTRFS_UUID_SIZE);
2944
2945         if (split == 0) {
2946                 if (mid <= slot) {
2947                         btrfs_set_header_nritems(right, 0);
2948                         wret = insert_ptr(trans, root, path,
2949                                           &disk_key, right->start,
2950                                           path->slots[1] + 1, 1);
2951                         if (wret)
2952                                 ret = wret;
2953
2954                         btrfs_tree_unlock(path->nodes[0]);
2955                         free_extent_buffer(path->nodes[0]);
2956                         path->nodes[0] = right;
2957                         path->slots[0] = 0;
2958                         path->slots[1] += 1;
2959                 } else {
2960                         btrfs_set_header_nritems(right, 0);
2961                         wret = insert_ptr(trans, root, path,
2962                                           &disk_key,
2963                                           right->start,
2964                                           path->slots[1], 1);
2965                         if (wret)
2966                                 ret = wret;
2967                         btrfs_tree_unlock(path->nodes[0]);
2968                         free_extent_buffer(path->nodes[0]);
2969                         path->nodes[0] = right;
2970                         path->slots[0] = 0;
2971                         if (path->slots[1] == 0) {
2972                                 wret = fixup_low_keys(trans, root,
2973                                                 path, &disk_key, 1);
2974                                 if (wret)
2975                                         ret = wret;
2976                         }
2977                 }
2978                 btrfs_mark_buffer_dirty(right);
2979                 return ret;
2980         }
2981
2982         ret = copy_for_split(trans, root, path, l, right, slot, mid, nritems);
2983         BUG_ON(ret);
2984
2985         if (split == 2) {
2986                 BUG_ON(num_doubles != 0);
2987                 num_doubles++;
2988                 goto again;
2989         }
2990
2991         return ret;
2992
2993 push_for_double:
2994         push_for_double_split(trans, root, path, data_size);
2995         tried_avoid_double = 1;
2996         if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
2997                 return 0;
2998         goto again;
2999 }
3000
3001 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3002                                          struct btrfs_root *root,
3003                                          struct btrfs_path *path, int ins_len)
3004 {
3005         struct btrfs_key key;
3006         struct extent_buffer *leaf;
3007         struct btrfs_file_extent_item *fi;
3008         u64 extent_len = 0;
3009         u32 item_size;
3010         int ret;
3011
3012         leaf = path->nodes[0];
3013         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3014
3015         BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3016                key.type != BTRFS_EXTENT_CSUM_KEY);
3017
3018         if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3019                 return 0;
3020
3021         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3022         if (key.type == BTRFS_EXTENT_DATA_KEY) {
3023                 fi = btrfs_item_ptr(leaf, path->slots[0],
3024                                     struct btrfs_file_extent_item);
3025                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3026         }
3027         btrfs_release_path(root, path);
3028
3029         path->keep_locks = 1;
3030         path->search_for_split = 1;
3031         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3032         path->search_for_split = 0;
3033         if (ret < 0)
3034                 goto err;
3035
3036         ret = -EAGAIN;
3037         leaf = path->nodes[0];
3038         /* if our item isn't there or got smaller, return now */
3039         if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3040                 goto err;
3041
3042         /* the leaf has  changed, it now has room.  return now */
3043         if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3044                 goto err;
3045
3046         if (key.type == BTRFS_EXTENT_DATA_KEY) {
3047                 fi = btrfs_item_ptr(leaf, path->slots[0],
3048                                     struct btrfs_file_extent_item);
3049                 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3050                         goto err;
3051         }
3052
3053         btrfs_set_path_blocking(path);
3054         ret = split_leaf(trans, root, &key, path, ins_len, 1);
3055         if (ret)
3056                 goto err;
3057
3058         path->keep_locks = 0;
3059         btrfs_unlock_up_safe(path, 1);
3060         return 0;
3061 err:
3062         path->keep_locks = 0;
3063         return ret;
3064 }
3065
3066 static noinline int split_item(struct btrfs_trans_handle *trans,
3067                                struct btrfs_root *root,
3068                                struct btrfs_path *path,
3069                                struct btrfs_key *new_key,
3070                                unsigned long split_offset)
3071 {
3072         struct extent_buffer *leaf;
3073         struct btrfs_item *item;
3074         struct btrfs_item *new_item;
3075         int slot;
3076         char *buf;
3077         u32 nritems;
3078         u32 item_size;
3079         u32 orig_offset;
3080         struct btrfs_disk_key disk_key;
3081
3082         leaf = path->nodes[0];
3083         BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3084
3085         btrfs_set_path_blocking(path);
3086
3087         item = btrfs_item_nr(leaf, path->slots[0]);
3088         orig_offset = btrfs_item_offset(leaf, item);
3089         item_size = btrfs_item_size(leaf, item);
3090
3091         buf = kmalloc(item_size, GFP_NOFS);
3092         if (!buf)
3093                 return -ENOMEM;
3094
3095         read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3096                             path->slots[0]), item_size);
3097
3098         slot = path->slots[0] + 1;
3099         nritems = btrfs_header_nritems(leaf);
3100         if (slot != nritems) {
3101                 /* shift the items */
3102                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3103                                 btrfs_item_nr_offset(slot),
3104                                 (nritems - slot) * sizeof(struct btrfs_item));
3105         }
3106
3107         btrfs_cpu_key_to_disk(&disk_key, new_key);
3108         btrfs_set_item_key(leaf, &disk_key, slot);
3109
3110         new_item = btrfs_item_nr(leaf, slot);
3111
3112         btrfs_set_item_offset(leaf, new_item, orig_offset);
3113         btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3114
3115         btrfs_set_item_offset(leaf, item,
3116                               orig_offset + item_size - split_offset);
3117         btrfs_set_item_size(leaf, item, split_offset);
3118
3119         btrfs_set_header_nritems(leaf, nritems + 1);
3120
3121         /* write the data for the start of the original item */
3122         write_extent_buffer(leaf, buf,
3123                             btrfs_item_ptr_offset(leaf, path->slots[0]),
3124                             split_offset);
3125
3126         /* write the data for the new item */
3127         write_extent_buffer(leaf, buf + split_offset,
3128                             btrfs_item_ptr_offset(leaf, slot),
3129                             item_size - split_offset);
3130         btrfs_mark_buffer_dirty(leaf);
3131
3132         BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
3133         kfree(buf);
3134         return 0;
3135 }
3136
3137 /*
3138  * This function splits a single item into two items,
3139  * giving 'new_key' to the new item and splitting the
3140  * old one at split_offset (from the start of the item).
3141  *
3142  * The path may be released by this operation.  After
3143  * the split, the path is pointing to the old item.  The
3144  * new item is going to be in the same node as the old one.
3145  *
3146  * Note, the item being split must be smaller enough to live alone on
3147  * a tree block with room for one extra struct btrfs_item
3148  *
3149  * This allows us to split the item in place, keeping a lock on the
3150  * leaf the entire time.
3151  */
3152 int btrfs_split_item(struct btrfs_trans_handle *trans,
3153                      struct btrfs_root *root,
3154                      struct btrfs_path *path,
3155                      struct btrfs_key *new_key,
3156                      unsigned long split_offset)
3157 {
3158         int ret;
3159         ret = setup_leaf_for_split(trans, root, path,
3160                                    sizeof(struct btrfs_item));
3161         if (ret)
3162                 return ret;
3163
3164         ret = split_item(trans, root, path, new_key, split_offset);
3165         return ret;
3166 }
3167
3168 /*
3169  * This function duplicate a item, giving 'new_key' to the new item.
3170  * It guarantees both items live in the same tree leaf and the new item
3171  * is contiguous with the original item.
3172  *
3173  * This allows us to split file extent in place, keeping a lock on the
3174  * leaf the entire time.
3175  */
3176 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
3177                          struct btrfs_root *root,
3178                          struct btrfs_path *path,
3179                          struct btrfs_key *new_key)
3180 {
3181         struct extent_buffer *leaf;
3182         int ret;
3183         u32 item_size;
3184
3185         leaf = path->nodes[0];
3186         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3187         ret = setup_leaf_for_split(trans, root, path,
3188                                    item_size + sizeof(struct btrfs_item));
3189         if (ret)
3190                 return ret;
3191
3192         path->slots[0]++;
3193         ret = setup_items_for_insert(trans, root, path, new_key, &item_size,
3194                                      item_size, item_size +
3195                                      sizeof(struct btrfs_item), 1);
3196         BUG_ON(ret);
3197
3198         leaf = path->nodes[0];
3199         memcpy_extent_buffer(leaf,
3200                              btrfs_item_ptr_offset(leaf, path->slots[0]),
3201                              btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
3202                              item_size);
3203         return 0;
3204 }
3205
3206 /*
3207  * make the item pointed to by the path smaller.  new_size indicates
3208  * how small to make it, and from_end tells us if we just chop bytes
3209  * off the end of the item or if we shift the item to chop bytes off
3210  * the front.
3211  */
3212 int btrfs_truncate_item(struct btrfs_trans_handle *trans,
3213                         struct btrfs_root *root,
3214                         struct btrfs_path *path,
3215                         u32 new_size, int from_end)
3216 {
3217         int ret = 0;
3218         int slot;
3219         struct extent_buffer *leaf;
3220         struct btrfs_item *item;
3221         u32 nritems;
3222         unsigned int data_end;
3223         unsigned int old_data_start;
3224         unsigned int old_size;
3225         unsigned int size_diff;
3226         int i;
3227
3228         leaf = path->nodes[0];
3229         slot = path->slots[0];
3230
3231         old_size = btrfs_item_size_nr(leaf, slot);
3232         if (old_size == new_size)
3233                 return 0;
3234
3235         nritems = btrfs_header_nritems(leaf);
3236         data_end = leaf_data_end(root, leaf);
3237
3238         old_data_start = btrfs_item_offset_nr(leaf, slot);
3239
3240         size_diff = old_size - new_size;
3241
3242         BUG_ON(slot < 0);
3243         BUG_ON(slot >= nritems);
3244
3245         /*
3246          * item0..itemN ... dataN.offset..dataN.size .. data0.size
3247          */
3248         /* first correct the data pointers */
3249         for (i = slot; i < nritems; i++) {
3250                 u32 ioff;
3251                 item = btrfs_item_nr(leaf, i);
3252
3253                 if (!leaf->map_token) {
3254                         map_extent_buffer(leaf, (unsigned long)item,
3255                                         sizeof(struct btrfs_item),
3256                                         &leaf->map_token, &leaf->kaddr,
3257                                         &leaf->map_start, &leaf->map_len,
3258                                         KM_USER1);
3259                 }
3260
3261                 ioff = btrfs_item_offset(leaf, item);
3262                 btrfs_set_item_offset(leaf, item, ioff + size_diff);
3263         }
3264
3265         if (leaf->map_token) {
3266                 unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
3267                 leaf->map_token = NULL;
3268         }
3269
3270         /* shift the data */
3271         if (from_end) {
3272                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3273                               data_end + size_diff, btrfs_leaf_data(leaf) +
3274                               data_end, old_data_start + new_size - data_end);
3275         } else {
3276                 struct btrfs_disk_key disk_key;
3277                 u64 offset;
3278
3279                 btrfs_item_key(leaf, &disk_key, slot);
3280
3281                 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3282                         unsigned long ptr;
3283                         struct btrfs_file_extent_item *fi;
3284
3285                         fi = btrfs_item_ptr(leaf, slot,
3286                                             struct btrfs_file_extent_item);
3287                         fi = (struct btrfs_file_extent_item *)(
3288                              (unsigned long)fi - size_diff);
3289
3290                         if (btrfs_file_extent_type(leaf, fi) ==
3291                             BTRFS_FILE_EXTENT_INLINE) {
3292                                 ptr = btrfs_item_ptr_offset(leaf, slot);
3293                                 memmove_extent_buffer(leaf, ptr,
3294                                       (unsigned long)fi,
3295                                       offsetof(struct btrfs_file_extent_item,
3296                                                  disk_bytenr));
3297                         }
3298                 }
3299
3300                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3301                               data_end + size_diff, btrfs_leaf_data(leaf) +
3302                               data_end, old_data_start - data_end);
3303
3304                 offset = btrfs_disk_key_offset(&disk_key);
3305                 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3306                 btrfs_set_item_key(leaf, &disk_key, slot);
3307                 if (slot == 0)
3308                         fixup_low_keys(trans, root, path, &disk_key, 1);
3309         }
3310
3311         item = btrfs_item_nr(leaf, slot);
3312         btrfs_set_item_size(leaf, item, new_size);
3313         btrfs_mark_buffer_dirty(leaf);
3314
3315         ret = 0;
3316         if (btrfs_leaf_free_space(root, leaf) < 0) {
3317                 btrfs_print_leaf(root, leaf);
3318                 BUG();
3319         }
3320         return ret;
3321 }
3322
3323 /*
3324  * make the item pointed to by the path bigger, data_size is the new size.
3325  */
3326 int btrfs_extend_item(struct btrfs_trans_handle *trans,
3327                       struct btrfs_root *root, struct btrfs_path *path,
3328                       u32 data_size)
3329 {
3330         int ret = 0;
3331         int slot;
3332         struct extent_buffer *leaf;
3333         struct btrfs_item *item;
3334         u32 nritems;
3335         unsigned int data_end;
3336         unsigned int old_data;
3337         unsigned int old_size;
3338         int i;
3339
3340         leaf = path->nodes[0];
3341
3342         nritems = btrfs_header_nritems(leaf);
3343         data_end = leaf_data_end(root, leaf);
3344
3345         if (btrfs_leaf_free_space(root, leaf) < data_size) {
3346                 btrfs_print_leaf(root, leaf);
3347                 BUG();
3348         }
3349         slot = path->slots[0];
3350         old_data = btrfs_item_end_nr(leaf, slot);
3351
3352         BUG_ON(slot < 0);
3353         if (slot >= nritems) {
3354                 btrfs_print_leaf(root, leaf);
3355                 printk(KERN_CRIT "slot %d too large, nritems %d\n",
3356                        slot, nritems);
3357                 BUG_ON(1);
3358         }
3359
3360         /*
3361          * item0..itemN ... dataN.offset..dataN.size .. data0.size
3362          */
3363         /* first correct the data pointers */
3364         for (i = slot; i < nritems; i++) {
3365                 u32 ioff;
3366                 item = btrfs_item_nr(leaf, i);
3367
3368                 if (!leaf->map_token) {
3369                         map_extent_buffer(leaf, (unsigned long)item,
3370                                         sizeof(struct btrfs_item),
3371                                         &leaf->map_token, &leaf->kaddr,
3372                                         &leaf->map_start, &leaf->map_len,
3373                                         KM_USER1);
3374                 }
3375                 ioff = btrfs_item_offset(leaf, item);
3376                 btrfs_set_item_offset(leaf, item, ioff - data_size);
3377         }
3378
3379         if (leaf->map_token) {
3380                 unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
3381                 leaf->map_token = NULL;
3382         }
3383
3384         /* shift the data */
3385         memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3386                       data_end - data_size, btrfs_leaf_data(leaf) +
3387                       data_end, old_data - data_end);
3388
3389         data_end = old_data;
3390         old_size = btrfs_item_size_nr(leaf, slot);
3391         item = btrfs_item_nr(leaf, slot);
3392         btrfs_set_item_size(leaf, item, old_size + data_size);
3393         btrfs_mark_buffer_dirty(leaf);
3394
3395         ret = 0;
3396         if (btrfs_leaf_free_space(root, leaf) < 0) {
3397                 btrfs_print_leaf(root, leaf);
3398                 BUG();
3399         }
3400         return ret;
3401 }
3402
3403 /*
3404  * Given a key and some data, insert items into the tree.
3405  * This does all the path init required, making room in the tree if needed.
3406  * Returns the number of keys that were inserted.
3407  */
3408 int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
3409                             struct btrfs_root *root,
3410                             struct btrfs_path *path,
3411                             struct btrfs_key *cpu_key, u32 *data_size,
3412                             int nr)
3413 {
3414         struct extent_buffer *leaf;
3415         struct btrfs_item *item;
3416         int ret = 0;
3417         int slot;
3418         int i;
3419         u32 nritems;
3420         u32 total_data = 0;
3421         u32 total_size = 0;
3422         unsigned int data_end;
3423         struct btrfs_disk_key disk_key;
3424         struct btrfs_key found_key;
3425
3426         for (i = 0; i < nr; i++) {
3427                 if (total_size + data_size[i] + sizeof(struct btrfs_item) >
3428                     BTRFS_LEAF_DATA_SIZE(root)) {
3429                         break;
3430                         nr = i;
3431                 }
3432                 total_data += data_size[i];
3433                 total_size += data_size[i] + sizeof(struct btrfs_item);
3434         }
3435         BUG_ON(nr == 0);
3436
3437         ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
3438         if (ret == 0)
3439                 return -EEXIST;
3440         if (ret < 0)
3441                 goto out;
3442
3443         leaf = path->nodes[0];
3444
3445         nritems = btrfs_header_nritems(leaf);
3446         data_end = leaf_data_end(root, leaf);
3447
3448         if (btrfs_leaf_free_space(root, leaf) < total_size) {
3449                 for (i = nr; i >= 0; i--) {
3450                         total_data -= data_size[i];
3451                         total_size -= data_size[i] + sizeof(struct btrfs_item);
3452                         if (total_size < btrfs_leaf_free_space(root, leaf))
3453                                 break;
3454                 }
3455                 nr = i;
3456         }
3457
3458         slot = path->slots[0];
3459         BUG_ON(slot < 0);
3460
3461         if (slot != nritems) {
3462                 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3463
3464                 item = btrfs_item_nr(leaf, slot);
3465                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3466
3467                 /* figure out how many keys we can insert in here */
3468                 total_data = data_size[0];
3469                 for (i = 1; i < nr; i++) {
3470                         if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
3471                                 break;
3472                         total_data += data_size[i];
3473                 }
3474                 nr = i;
3475
3476                 if (old_data < data_end) {
3477                         btrfs_print_leaf(root, leaf);
3478                         printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
3479                                slot, old_data, data_end);
3480                         BUG_ON(1);
3481                 }
3482                 /*
3483                  * item0..itemN ... dataN.offset..dataN.size .. data0.size
3484                  */
3485                 /* first correct the data pointers */
3486                 WARN_ON(leaf->map_token);
3487                 for (i = slot; i < nritems; i++) {
3488                         u32 ioff;
3489
3490                         item = btrfs_item_nr(leaf, i);
3491                         if (!leaf->map_token) {
3492                                 map_extent_buffer(leaf, (unsigned long)item,
3493                                         sizeof(struct btrfs_item),
3494                                         &leaf->map_token, &leaf->kaddr,
3495                                         &leaf->map_start, &leaf->map_len,
3496                                         KM_USER1);
3497                         }
3498
3499                         ioff = btrfs_item_offset(leaf, item);
3500                         btrfs_set_item_offset(leaf, item, ioff - total_data);
3501                 }
3502                 if (leaf->map_token) {
3503                         unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
3504                         leaf->map_token = NULL;
3505                 }
3506
3507                 /* shift the items */
3508                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
3509                               btrfs_item_nr_offset(slot),
3510                               (nritems - slot) * sizeof(struct btrfs_item));
3511
3512                 /* shift the data */
3513                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3514                               data_end - total_data, btrfs_leaf_data(leaf) +
3515                               data_end, old_data - data_end);
3516                 data_end = old_data;
3517         } else {
3518                 /*
3519                  * this sucks but it has to be done, if we are inserting at
3520                  * the end of the leaf only insert 1 of the items, since we
3521                  * have no way of knowing whats on the next leaf and we'd have
3522                  * to drop our current locks to figure it out
3523                  */
3524                 nr = 1;
3525         }
3526
3527         /* setup the item for the new data */
3528         for (i = 0; i < nr; i++) {
3529                 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
3530                 btrfs_set_item_key(leaf, &disk_key, slot + i);
3531                 item = btrfs_item_nr(leaf, slot + i);
3532                 btrfs_set_item_offset(leaf, item, data_end - data_size[i]);
3533                 data_end -= data_size[i];
3534                 btrfs_set_item_size(leaf, item, data_size[i]);
3535         }
3536         btrfs_set_header_nritems(leaf, nritems + nr);
3537         btrfs_mark_buffer_dirty(leaf);
3538
3539         ret = 0;
3540         if (slot == 0) {
3541                 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3542                 ret = fixup_low_keys(trans, root, path, &disk_key, 1);
3543         }
3544
3545         if (btrfs_leaf_free_space(root, leaf) < 0) {
3546                 btrfs_print_leaf(root, leaf);
3547                 BUG();
3548         }
3549 out:
3550         if (!ret)
3551                 ret = nr;
3552         return ret;
3553 }
3554
3555 /*
3556  * this is a helper for btrfs_insert_empty_items, the main goal here is
3557  * to save stack depth by doing the bulk of the work in a function
3558  * that doesn't call btrfs_search_slot
3559  */
3560 static noinline_for_stack int
3561 setup_items_for_insert(struct btrfs_trans_handle *trans,
3562                       struct btrfs_root *root, struct btrfs_path *path,
3563                       struct btrfs_key *cpu_key, u32 *data_size,
3564                       u32 total_data, u32 total_size, int nr)
3565 {
3566         struct btrfs_item *item;
3567         int i;
3568         u32 nritems;
3569         unsigned int data_end;
3570         struct btrfs_disk_key disk_key;
3571         int ret;
3572         struct extent_buffer *leaf;
3573         int slot;
3574
3575         leaf = path->nodes[0];
3576         slot = path->slots[0];
3577
3578         nritems = btrfs_header_nritems(leaf);
3579         data_end = leaf_data_end(root, leaf);
3580
3581         if (btrfs_leaf_free_space(root, leaf) < total_size) {
3582                 btrfs_print_leaf(root, leaf);
3583                 printk(KERN_CRIT "not enough freespace need %u have %d\n",
3584                        total_size, btrfs_leaf_free_space(root, leaf));
3585                 BUG();
3586         }
3587
3588         if (slot != nritems) {
3589                 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3590
3591                 if (old_data < data_end) {
3592                         btrfs_print_leaf(root, leaf);
3593                         printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
3594                                slot, old_data, data_end);
3595                         BUG_ON(1);
3596                 }
3597                 /*
3598                  * item0..itemN ... dataN.offset..dataN.size .. data0.size
3599                  */
3600                 /* first correct the data pointers */
3601                 WARN_ON(leaf->map_token);
3602                 for (i = slot; i < nritems; i++) {
3603                         u32 ioff;
3604
3605                         item = btrfs_item_nr(leaf, i);
3606                         if (!leaf->map_token) {
3607                                 map_extent_buffer(leaf, (unsigned long)item,
3608                                         sizeof(struct btrfs_item),
3609                                         &leaf->map_token, &leaf->kaddr,
3610                                         &leaf->map_start, &leaf->map_len,
3611                                         KM_USER1);
3612                         }
3613
3614                         ioff = btrfs_item_offset(leaf, item);
3615                         btrfs_set_item_offset(leaf, item, ioff - total_data);
3616                 }
3617                 if (leaf->map_token) {
3618                         unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
3619                         leaf->map_token = NULL;
3620                 }
3621
3622                 /* shift the items */
3623                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
3624                               btrfs_item_nr_offset(slot),
3625                               (nritems - slot) * sizeof(struct btrfs_item));
3626
3627                 /* shift the data */
3628                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3629                               data_end - total_data, btrfs_leaf_data(leaf) +
3630                               data_end, old_data - data_end);
3631                 data_end = old_data;
3632         }
3633
3634         /* setup the item for the new data */
3635         for (i = 0; i < nr; i++) {
3636                 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
3637                 btrfs_set_item_key(leaf, &disk_key, slot + i);
3638                 item = btrfs_item_nr(leaf, slot + i);
3639                 btrfs_set_item_offset(leaf, item, data_end - data_size[i]);
3640                 data_end -= data_size[i];
3641                 btrfs_set_item_size(leaf, item, data_size[i]);
3642         }
3643
3644         btrfs_set_header_nritems(leaf, nritems + nr);
3645
3646         ret = 0;
3647         if (slot == 0) {
3648                 struct btrfs_disk_key disk_key;
3649                 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3650                 ret = fixup_low_keys(trans, root, path, &disk_key, 1);
3651         }
3652         btrfs_unlock_up_safe(path, 1);
3653         btrfs_mark_buffer_dirty(leaf);
3654
3655         if (btrfs_leaf_free_space(root, leaf) < 0) {
3656                 btrfs_print_leaf(root, leaf);
3657                 BUG();
3658         }
3659         return ret;
3660 }
3661
3662 /*
3663  * Given a key and some data, insert items into the tree.
3664  * This does all the path init required, making room in the tree if needed.
3665  */
3666 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
3667                             struct btrfs_root *root,
3668                             struct btrfs_path *path,
3669                             struct btrfs_key *cpu_key, u32 *data_size,
3670                             int nr)
3671 {
3672         int ret = 0;
3673         int slot;
3674         int i;
3675         u32 total_size = 0;
3676         u32 total_data = 0;
3677
3678         for (i = 0; i < nr; i++)
3679                 total_data += data_size[i];
3680
3681         total_size = total_data + (nr * sizeof(struct btrfs_item));
3682         ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
3683         if (ret == 0)
3684                 return -EEXIST;
3685         if (ret < 0)
3686                 goto out;
3687
3688         slot = path->slots[0];
3689         BUG_ON(slot < 0);
3690
3691         ret = setup_items_for_insert(trans, root, path, cpu_key, data_size,
3692                                total_data, total_size, nr);
3693
3694 out:
3695         return ret;
3696 }
3697
3698 /*
3699  * Given a key and some data, insert an item into the tree.
3700  * This does all the path init required, making room in the tree if needed.
3701  */
3702 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
3703                       *root, struct btrfs_key *cpu_key, void *data, u32
3704                       data_size)
3705 {
3706         int ret = 0;
3707         struct btrfs_path *path;
3708         struct extent_buffer *leaf;
3709         unsigned long ptr;
3710
3711         path = btrfs_alloc_path();
3712         if (!path)
3713                 return -ENOMEM;
3714         ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
3715         if (!ret) {
3716                 leaf = path->nodes[0];
3717                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3718                 write_extent_buffer(leaf, data, ptr, data_size);
3719                 btrfs_mark_buffer_dirty(leaf);
3720         }
3721         btrfs_free_path(path);
3722         return ret;
3723 }
3724
3725 /*
3726  * delete the pointer from a given node.
3727  *
3728  * the tree should have been previously balanced so the deletion does not
3729  * empty a node.
3730  */
3731 static int del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3732                    struct btrfs_path *path, int level, int slot)
3733 {
3734         struct extent_buffer *parent = path->nodes[level];
3735         u32 nritems;
3736         int ret = 0;
3737         int wret;
3738
3739         nritems = btrfs_header_nritems(parent);
3740         if (slot != nritems - 1) {
3741                 memmove_extent_buffer(parent,
3742                               btrfs_node_key_ptr_offset(slot),
3743                               btrfs_node_key_ptr_offset(slot + 1),
3744                               sizeof(struct btrfs_key_ptr) *
3745                               (nritems - slot - 1));
3746         }
3747         nritems--;
3748         btrfs_set_header_nritems(parent, nritems);
3749         if (nritems == 0 && parent == root->node) {
3750                 BUG_ON(btrfs_header_level(root->node) != 1);
3751                 /* just turn the root into a leaf and break */
3752                 btrfs_set_header_level(root->node, 0);
3753         } else if (slot == 0) {
3754                 struct btrfs_disk_key disk_key;
3755
3756                 btrfs_node_key(parent, &disk_key, 0);
3757                 wret = fixup_low_keys(trans, root, path, &disk_key, level + 1);
3758                 if (wret)
3759                         ret = wret;
3760         }
3761         btrfs_mark_buffer_dirty(parent);
3762         return ret;
3763 }
3764
3765 /*
3766  * a helper function to delete the leaf pointed to by path->slots[1] and
3767  * path->nodes[1].
3768  *
3769  * This deletes the pointer in path->nodes[1] and frees the leaf
3770  * block extent.  zero is returned if it all worked out, < 0 otherwise.
3771  *
3772  * The path must have already been setup for deleting the leaf, including
3773  * all the proper balancing.  path->nodes[1] must be locked.
3774  */
3775 static noinline int btrfs_del_leaf(struct btrfs_trans_handle *trans,
3776                                    struct btrfs_root *root,
3777                                    struct btrfs_path *path,
3778                                    struct extent_buffer *leaf)
3779 {
3780         int ret;
3781
3782         WARN_ON(btrfs_header_generation(leaf) != trans->transid);
3783         ret = del_ptr(trans, root, path, 1, path->slots[1]);
3784         if (ret)
3785                 return ret;
3786
3787         /*
3788          * btrfs_free_extent is expensive, we want to make sure we
3789          * aren't holding any locks when we call it
3790          */
3791         btrfs_unlock_up_safe(path, 0);
3792
3793         root_sub_used(root, leaf->len);
3794
3795         btrfs_free_tree_block(trans, root, leaf, 0, 1);
3796         return 0;
3797 }
3798 /*
3799  * delete the item at the leaf level in path.  If that empties
3800  * the leaf, remove it from the tree
3801  */
3802 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3803                     struct btrfs_path *path, int slot, int nr)
3804 {
3805         struct extent_buffer *leaf;
3806         struct btrfs_item *item;
3807         int last_off;
3808         int dsize = 0;
3809         int ret = 0;
3810         int wret;
3811         int i;
3812         u32 nritems;
3813
3814         leaf = path->nodes[0];
3815         last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
3816
3817         for (i = 0; i < nr; i++)
3818                 dsize += btrfs_item_size_nr(leaf, slot + i);
3819
3820         nritems = btrfs_header_nritems(leaf);
3821
3822         if (slot + nr != nritems) {
3823                 int data_end = leaf_data_end(root, leaf);
3824
3825                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3826                               data_end + dsize,
3827                               btrfs_leaf_data(leaf) + data_end,
3828                               last_off - data_end);
3829
3830                 for (i = slot + nr; i < nritems; i++) {
3831                         u32 ioff;
3832
3833                         item = btrfs_item_nr(leaf, i);
3834                         if (!leaf->map_token) {
3835                                 map_extent_buffer(leaf, (unsigned long)item,
3836                                         sizeof(struct btrfs_item),
3837                                         &leaf->map_token, &leaf->kaddr,
3838                                         &leaf->map_start, &leaf->map_len,
3839                                         KM_USER1);
3840                         }
3841                         ioff = btrfs_item_offset(leaf, item);
3842                         btrfs_set_item_offset(leaf, item, ioff + dsize);
3843                 }
3844
3845                 if (leaf->map_token) {
3846                         unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
3847                         leaf->map_token = NULL;
3848                 }
3849
3850                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
3851                               btrfs_item_nr_offset(slot + nr),
3852                               sizeof(struct btrfs_item) *
3853                               (nritems - slot - nr));
3854         }
3855         btrfs_set_header_nritems(leaf, nritems - nr);
3856         nritems -= nr;
3857
3858         /* delete the leaf if we've emptied it */
3859         if (nritems == 0) {
3860                 if (leaf == root->node) {
3861                         btrfs_set_header_level(leaf, 0);
3862                 } else {
3863                         btrfs_set_path_blocking(path);
3864                         clean_tree_block(trans, root, leaf);
3865                         ret = btrfs_del_leaf(trans, root, path, leaf);
3866                         BUG_ON(ret);
3867                 }
3868         } else {
3869                 int used = leaf_space_used(leaf, 0, nritems);
3870                 if (slot == 0) {
3871                         struct btrfs_disk_key disk_key;
3872
3873                         btrfs_item_key(leaf, &disk_key, 0);
3874                         wret = fixup_low_keys(trans, root, path,
3875                                               &disk_key, 1);
3876                         if (wret)
3877                                 ret = wret;
3878                 }
3879
3880                 /* delete the leaf if it is mostly empty */
3881                 if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
3882                         /* push_leaf_left fixes the path.
3883                          * make sure the path still points to our leaf
3884                          * for possible call to del_ptr below
3885                          */
3886                         slot = path->slots[1];
3887                         extent_buffer_get(leaf);
3888
3889                         btrfs_set_path_blocking(path);
3890                         wret = push_leaf_left(trans, root, path, 1, 1,
3891                                               1, (u32)-1);
3892                         if (wret < 0 && wret != -ENOSPC)
3893                                 ret = wret;
3894
3895                         if (path->nodes[0] == leaf &&
3896                             btrfs_header_nritems(leaf)) {
3897                                 wret = push_leaf_right(trans, root, path, 1,
3898                                                        1, 1, 0);
3899                                 if (wret < 0 && wret != -ENOSPC)
3900                                         ret = wret;
3901                         }
3902
3903                         if (btrfs_header_nritems(leaf) == 0) {
3904                                 path->slots[1] = slot;
3905                                 ret = btrfs_del_leaf(trans, root, path, leaf);
3906                                 BUG_ON(ret);
3907                                 free_extent_buffer(leaf);
3908                         } else {
3909                                 /* if we're still in the path, make sure
3910                                  * we're dirty.  Otherwise, one of the
3911                                  * push_leaf functions must have already
3912                                  * dirtied this buffer
3913                                  */
3914                                 if (path->nodes[0] == leaf)
3915                                         btrfs_mark_buffer_dirty(leaf);
3916                                 free_extent_buffer(leaf);
3917                         }
3918                 } else {
3919                         btrfs_mark_buffer_dirty(leaf);
3920                 }
3921         }
3922         return ret;
3923 }
3924
3925 /*
3926  * search the tree again to find a leaf with lesser keys
3927  * returns 0 if it found something or 1 if there are no lesser leaves.
3928  * returns < 0 on io errors.
3929  *
3930  * This may release the path, and so you may lose any locks held at the
3931  * time you call it.
3932  */
3933 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
3934 {
3935         struct btrfs_key key;
3936         struct btrfs_disk_key found_key;
3937         int ret;
3938
3939         btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
3940
3941         if (key.offset > 0)
3942                 key.offset--;
3943         else if (key.type > 0)
3944                 key.type--;
3945         else if (key.objectid > 0)
3946                 key.objectid--;
3947         else
3948                 return 1;
3949
3950         btrfs_release_path(root, path);
3951         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3952         if (ret < 0)
3953                 return ret;
3954         btrfs_item_key(path->nodes[0], &found_key, 0);
3955         ret = comp_keys(&found_key, &key);
3956         if (ret < 0)
3957                 return 0;
3958         return 1;
3959 }
3960
3961 /*
3962  * A helper function to walk down the tree starting at min_key, and looking
3963  * for nodes or leaves that are either in cache or have a minimum
3964  * transaction id.  This is used by the btree defrag code, and tree logging
3965  *
3966  * This does not cow, but it does stuff the starting key it finds back
3967  * into min_key, so you can call btrfs_search_slot with cow=1 on the
3968  * key and get a writable path.
3969  *
3970  * This does lock as it descends, and path->keep_locks should be set
3971  * to 1 by the caller.
3972  *
3973  * This honors path->lowest_level to prevent descent past a given level
3974  * of the tree.
3975  *
3976  * min_trans indicates the oldest transaction that you are interested
3977  * in walking through.  Any nodes or leaves older than min_trans are
3978  * skipped over (without reading them).
3979  *
3980  * returns zero if something useful was found, < 0 on error and 1 if there
3981  * was nothing in the tree that matched the search criteria.
3982  */
3983 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
3984                          struct btrfs_key *max_key,
3985                          struct btrfs_path *path, int cache_only,
3986                          u64 min_trans)
3987 {
3988         struct extent_buffer *cur;
3989         struct btrfs_key found_key;
3990         int slot;
3991         int sret;
3992         u32 nritems;
3993         int level;
3994         int ret = 1;
3995
3996         WARN_ON(!path->keep_locks);
3997 again:
3998         cur = btrfs_lock_root_node(root);
3999         level = btrfs_header_level(cur);
4000         WARN_ON(path->nodes[level]);
4001         path->nodes[level] = cur;
4002         path->locks[level] = 1;
4003
4004         if (btrfs_header_generation(cur) < min_trans) {
4005                 ret = 1;
4006                 goto out;
4007         }
4008         while (1) {
4009                 nritems = btrfs_header_nritems(cur);
4010                 level = btrfs_header_level(cur);
4011                 sret = bin_search(cur, min_key, level, &slot);
4012
4013                 /* at the lowest level, we're done, setup the path and exit */
4014                 if (level == path->lowest_level) {
4015                         if (slot >= nritems)
4016                                 goto find_next_key;
4017                         ret = 0;
4018                         path->slots[level] = slot;
4019                         btrfs_item_key_to_cpu(cur, &found_key, slot);
4020                         goto out;
4021                 }
4022                 if (sret && slot > 0)
4023                         slot--;
4024                 /*
4025                  * check this node pointer against the cache_only and
4026                  * min_trans parameters.  If it isn't in cache or is too
4027                  * old, skip to the next one.
4028                  */
4029                 while (slot < nritems) {
4030                         u64 blockptr;
4031                         u64 gen;
4032                         struct extent_buffer *tmp;
4033                         struct btrfs_disk_key disk_key;
4034
4035                         blockptr = btrfs_node_blockptr(cur, slot);
4036                         gen = btrfs_node_ptr_generation(cur, slot);
4037                         if (gen < min_trans) {
4038                                 slot++;
4039                                 continue;
4040                         }
4041                         if (!cache_only)
4042                                 break;
4043
4044                         if (max_key) {
4045                                 btrfs_node_key(cur, &disk_key, slot);
4046                                 if (comp_keys(&disk_key, max_key) >= 0) {
4047                                         ret = 1;
4048                                         goto out;
4049                                 }
4050                         }
4051
4052                         tmp = btrfs_find_tree_block(root, blockptr,
4053                                             btrfs_level_size(root, level - 1));
4054
4055                         if (tmp && btrfs_buffer_uptodate(tmp, gen)) {
4056                                 free_extent_buffer(tmp);
4057                                 break;
4058                         }
4059                         if (tmp)
4060                                 free_extent_buffer(tmp);
4061                         slot++;
4062                 }
4063 find_next_key:
4064                 /*
4065                  * we didn't find a candidate key in this node, walk forward
4066                  * and find another one
4067                  */
4068                 if (slot >= nritems) {
4069                         path->slots[level] = slot;
4070                         btrfs_set_path_blocking(path);
4071                         sret = btrfs_find_next_key(root, path, min_key, level,
4072                                                   cache_only, min_trans);
4073                         if (sret == 0) {
4074                                 btrfs_release_path(root, path);
4075                                 goto again;
4076                         } else {
4077                                 goto out;
4078                         }
4079                 }
4080                 /* save our key for returning back */
4081                 btrfs_node_key_to_cpu(cur, &found_key, slot);
4082                 path->slots[level] = slot;
4083                 if (level == path->lowest_level) {
4084                         ret = 0;
4085                         unlock_up(path, level, 1);
4086                         goto out;
4087                 }
4088                 btrfs_set_path_blocking(path);
4089                 cur = read_node_slot(root, cur, slot);
4090
4091                 btrfs_tree_lock(cur);
4092
4093                 path->locks[level - 1] = 1;
4094                 path->nodes[level - 1] = cur;
4095                 unlock_up(path, level, 1);
4096                 btrfs_clear_path_blocking(path, NULL);
4097         }
4098 out:
4099         if (ret == 0)
4100                 memcpy(min_key, &found_key, sizeof(found_key));
4101         btrfs_set_path_blocking(path);
4102         return ret;
4103 }
4104
4105 /*
4106  * this is similar to btrfs_next_leaf, but does not try to preserve
4107  * and fixup the path.  It looks for and returns the next key in the
4108  * tree based on the current path and the cache_only and min_trans
4109  * parameters.
4110  *
4111  * 0 is returned if another key is found, < 0 if there are any errors
4112  * and 1 is returned if there are no higher keys in the tree
4113  *
4114  * path->keep_locks should be set to 1 on the search made before
4115  * calling this function.
4116  */
4117 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4118                         struct btrfs_key *key, int level,
4119                         int cache_only, u64 min_trans)
4120 {
4121         int slot;
4122         struct extent_buffer *c;
4123
4124         WARN_ON(!path->keep_locks);
4125         while (level < BTRFS_MAX_LEVEL) {
4126                 if (!path->nodes[level])
4127                         return 1;
4128
4129                 slot = path->slots[level] + 1;
4130                 c = path->nodes[level];
4131 next:
4132                 if (slot >= btrfs_header_nritems(c)) {
4133                         int ret;
4134                         int orig_lowest;
4135                         struct btrfs_key cur_key;
4136                         if (level + 1 >= BTRFS_MAX_LEVEL ||
4137                             !path->nodes[level + 1])
4138                                 return 1;
4139
4140                         if (path->locks[level + 1]) {
4141                                 level++;
4142                                 continue;
4143                         }
4144
4145                         slot = btrfs_header_nritems(c) - 1;
4146                         if (level == 0)
4147                                 btrfs_item_key_to_cpu(c, &cur_key, slot);
4148                         else
4149                                 btrfs_node_key_to_cpu(c, &cur_key, slot);
4150
4151                         orig_lowest = path->lowest_level;
4152                         btrfs_release_path(root, path);
4153                         path->lowest_level = level;
4154                         ret = btrfs_search_slot(NULL, root, &cur_key, path,
4155                                                 0, 0);
4156                         path->lowest_level = orig_lowest;
4157                         if (ret < 0)
4158                                 return ret;
4159
4160                         c = path->nodes[level];
4161                         slot = path->slots[level];
4162                         if (ret == 0)
4163                                 slot++;
4164                         goto next;
4165                 }
4166
4167                 if (level == 0)
4168                         btrfs_item_key_to_cpu(c, key, slot);
4169                 else {
4170                         u64 blockptr = btrfs_node_blockptr(c, slot);
4171                         u64 gen = btrfs_node_ptr_generation(c, slot);
4172
4173                         if (cache_only) {
4174                                 struct extent_buffer *cur;
4175                                 cur = btrfs_find_tree_block(root, blockptr,
4176                                             btrfs_level_size(root, level - 1));
4177                                 if (!cur || !btrfs_buffer_uptodate(cur, gen)) {
4178                                         slot++;
4179                                         if (cur)
4180                                                 free_extent_buffer(cur);
4181                                         goto next;
4182                                 }
4183                                 free_extent_buffer(cur);
4184                         }
4185                         if (gen < min_trans) {
4186                                 slot++;
4187                                 goto next;
4188                         }
4189                         btrfs_node_key_to_cpu(c, key, slot);
4190                 }
4191                 return 0;
4192         }
4193         return 1;
4194 }
4195
4196 /*
4197  * search the tree again to find a leaf with greater keys
4198  * returns 0 if it found something or 1 if there are no greater leaves.
4199  * returns < 0 on io errors.
4200  */
4201 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
4202 {
4203         int slot;
4204         int level;
4205         struct extent_buffer *c;
4206         struct extent_buffer *next;
4207         struct btrfs_key key;
4208         u32 nritems;
4209         int ret;
4210         int old_spinning = path->leave_spinning;
4211         int force_blocking = 0;
4212
4213         nritems = btrfs_header_nritems(path->nodes[0]);
4214         if (nritems == 0)
4215                 return 1;
4216
4217         /*
4218          * we take the blocks in an order that upsets lockdep.  Using
4219          * blocking mode is the only way around it.
4220          */
4221 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4222         force_blocking = 1;
4223 #endif
4224
4225         btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4226 again:
4227         level = 1;
4228         next = NULL;
4229         btrfs_release_path(root, path);
4230
4231         path->keep_locks = 1;
4232
4233         if (!force_blocking)
4234                 path->leave_spinning = 1;
4235
4236         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4237         path->keep_locks = 0;
4238
4239         if (ret < 0)
4240                 return ret;
4241
4242         nritems = btrfs_header_nritems(path->nodes[0]);
4243         /*
4244          * by releasing the path above we dropped all our locks.  A balance
4245          * could have added more items next to the key that used to be
4246          * at the very end of the block.  So, check again here and
4247          * advance the path if there are now more items available.
4248          */
4249         if (nritems > 0 && path->slots[0] < nritems - 1) {
4250                 if (ret == 0)
4251                         path->slots[0]++;
4252                 ret = 0;
4253                 goto done;
4254         }
4255
4256         while (level < BTRFS_MAX_LEVEL) {
4257                 if (!path->nodes[level]) {
4258                         ret = 1;
4259                         goto done;
4260                 }
4261
4262                 slot = path->slots[level] + 1;
4263                 c = path->nodes[level];
4264                 if (slot >= btrfs_header_nritems(c)) {
4265                         level++;
4266                         if (level == BTRFS_MAX_LEVEL) {
4267                                 ret = 1;
4268                                 goto done;
4269                         }
4270                         continue;
4271                 }
4272
4273                 if (next) {
4274                         btrfs_tree_unlock(next);
4275                         free_extent_buffer(next);
4276                 }
4277
4278                 next = c;
4279                 ret = read_block_for_search(NULL, root, path, &next, level,
4280                                             slot, &key);
4281                 if (ret == -EAGAIN)
4282                         goto again;
4283
4284                 if (ret < 0) {
4285                         btrfs_release_path(root, path);
4286                         goto done;
4287                 }
4288
4289                 if (!path->skip_locking) {
4290                         ret = btrfs_try_spin_lock(next);
4291                         if (!ret) {
4292                                 btrfs_set_path_blocking(path);
4293                                 btrfs_tree_lock(next);
4294                                 if (!force_blocking)
4295                                         btrfs_clear_path_blocking(path, next);
4296                         }
4297                         if (force_blocking)
4298                                 btrfs_set_lock_blocking(next);
4299                 }
4300                 break;
4301         }
4302         path->slots[level] = slot;
4303         while (1) {
4304                 level--;
4305                 c = path->nodes[level];
4306                 if (path->locks[level])
4307                         btrfs_tree_unlock(c);
4308
4309                 free_extent_buffer(c);
4310                 path->nodes[level] = next;
4311                 path->slots[level] = 0;
4312                 if (!path->skip_locking)
4313                         path->locks[level] = 1;
4314
4315                 if (!level)
4316                         break;
4317
4318                 ret = read_block_for_search(NULL, root, path, &next, level,
4319                                             0, &key);
4320                 if (ret == -EAGAIN)
4321                         goto again;
4322
4323                 if (ret < 0) {
4324                         btrfs_release_path(root, path);
4325                         goto done;
4326                 }
4327
4328                 if (!path->skip_locking) {
4329                         btrfs_assert_tree_locked(path->nodes[level]);
4330                         ret = btrfs_try_spin_lock(next);
4331                         if (!ret) {
4332                                 btrfs_set_path_blocking(path);
4333                                 btrfs_tree_lock(next);
4334                                 if (!force_blocking)
4335                                         btrfs_clear_path_blocking(path, next);
4336                         }
4337                         if (force_blocking)
4338                                 btrfs_set_lock_blocking(next);
4339                 }
4340         }
4341         ret = 0;
4342 done:
4343         unlock_up(path, 0, 1);
4344         path->leave_spinning = old_spinning;
4345         if (!old_spinning)
4346                 btrfs_set_path_blocking(path);
4347
4348         return ret;
4349 }
4350
4351 /*
4352  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4353  * searching until it gets past min_objectid or finds an item of 'type'
4354  *
4355  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4356  */
4357 int btrfs_previous_item(struct btrfs_root *root,
4358                         struct btrfs_path *path, u64 min_objectid,
4359                         int type)
4360 {
4361         struct btrfs_key found_key;
4362         struct extent_buffer *leaf;
4363         u32 nritems;
4364         int ret;
4365
4366         while (1) {
4367                 if (path->slots[0] == 0) {
4368                         btrfs_set_path_blocking(path);
4369                         ret = btrfs_prev_leaf(root, path);
4370                         if (ret != 0)
4371                                 return ret;
4372                 } else {
4373                         path->slots[0]--;
4374                 }
4375                 leaf = path->nodes[0];
4376                 nritems = btrfs_header_nritems(leaf);
4377                 if (nritems == 0)
4378                         return 1;
4379                 if (path->slots[0] == nritems)
4380                         path->slots[0]--;
4381
4382                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4383                 if (found_key.objectid < min_objectid)
4384                         break;
4385                 if (found_key.type == type)
4386                         return 0;
4387                 if (found_key.objectid == min_objectid &&
4388                     found_key.type < type)
4389                         break;
4390         }
4391         return 1;
4392 }