Merge branch 'x86-fixes-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
[sfrench/cifs-2.6.git] / fs / btrfs / ctree.c
1 /*
2  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include "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         btrfs_release_path(NULL, p);
109         kmem_cache_free(btrfs_path_cachep, p);
110 }
111
112 /*
113  * path release drops references on the extent buffers in the path
114  * and it drops any locks held by this path
115  *
116  * It is safe to call this on paths that no locks or extent buffers held.
117  */
118 noinline void btrfs_release_path(struct btrfs_root *root, struct btrfs_path *p)
119 {
120         int i;
121
122         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
123                 p->slots[i] = 0;
124                 if (!p->nodes[i])
125                         continue;
126                 if (p->locks[i]) {
127                         btrfs_tree_unlock(p->nodes[i]);
128                         p->locks[i] = 0;
129                 }
130                 free_extent_buffer(p->nodes[i]);
131                 p->nodes[i] = NULL;
132         }
133 }
134
135 /*
136  * safely gets a reference on the root node of a tree.  A lock
137  * is not taken, so a concurrent writer may put a different node
138  * at the root of the tree.  See btrfs_lock_root_node for the
139  * looping required.
140  *
141  * The extent buffer returned by this has a reference taken, so
142  * it won't disappear.  It may stop being the root of the tree
143  * at any time because there are no locks held.
144  */
145 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
146 {
147         struct extent_buffer *eb;
148         spin_lock(&root->node_lock);
149         eb = root->node;
150         extent_buffer_get(eb);
151         spin_unlock(&root->node_lock);
152         return eb;
153 }
154
155 /* loop around taking references on and locking the root node of the
156  * tree until you end up with a lock on the root.  A locked buffer
157  * is returned, with a reference held.
158  */
159 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
160 {
161         struct extent_buffer *eb;
162
163         while (1) {
164                 eb = btrfs_root_node(root);
165                 btrfs_tree_lock(eb);
166
167                 spin_lock(&root->node_lock);
168                 if (eb == root->node) {
169                         spin_unlock(&root->node_lock);
170                         break;
171                 }
172                 spin_unlock(&root->node_lock);
173
174                 btrfs_tree_unlock(eb);
175                 free_extent_buffer(eb);
176         }
177         return eb;
178 }
179
180 /* cowonly root (everything not a reference counted cow subvolume), just get
181  * put onto a simple dirty list.  transaction.c walks this to make sure they
182  * get properly updated on disk.
183  */
184 static void add_root_to_dirty_list(struct btrfs_root *root)
185 {
186         if (root->track_dirty && list_empty(&root->dirty_list)) {
187                 list_add(&root->dirty_list,
188                          &root->fs_info->dirty_cowonly_roots);
189         }
190 }
191
192 /*
193  * used by snapshot creation to make a copy of a root for a tree with
194  * a given objectid.  The buffer with the new root node is returned in
195  * cow_ret, and this func returns zero on success or a negative error code.
196  */
197 int btrfs_copy_root(struct btrfs_trans_handle *trans,
198                       struct btrfs_root *root,
199                       struct extent_buffer *buf,
200                       struct extent_buffer **cow_ret, u64 new_root_objectid)
201 {
202         struct extent_buffer *cow;
203         u32 nritems;
204         int ret = 0;
205         int level;
206         struct btrfs_disk_key disk_key;
207
208         WARN_ON(root->ref_cows && trans->transid !=
209                 root->fs_info->running_transaction->transid);
210         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
211
212         level = btrfs_header_level(buf);
213         nritems = btrfs_header_nritems(buf);
214         if (level == 0)
215                 btrfs_item_key(buf, &disk_key, 0);
216         else
217                 btrfs_node_key(buf, &disk_key, 0);
218
219         cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
220                                      new_root_objectid, &disk_key, level,
221                                      buf->start, 0);
222         if (IS_ERR(cow))
223                 return PTR_ERR(cow);
224
225         copy_extent_buffer(cow, buf, 0, 0, cow->len);
226         btrfs_set_header_bytenr(cow, cow->start);
227         btrfs_set_header_generation(cow, trans->transid);
228         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
229         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
230                                      BTRFS_HEADER_FLAG_RELOC);
231         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
232                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
233         else
234                 btrfs_set_header_owner(cow, new_root_objectid);
235
236         write_extent_buffer(cow, root->fs_info->fsid,
237                             (unsigned long)btrfs_header_fsid(cow),
238                             BTRFS_FSID_SIZE);
239
240         WARN_ON(btrfs_header_generation(buf) > trans->transid);
241         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
242                 ret = btrfs_inc_ref(trans, root, cow, 1);
243         else
244                 ret = btrfs_inc_ref(trans, root, cow, 0);
245
246         if (ret)
247                 return ret;
248
249         btrfs_mark_buffer_dirty(cow);
250         *cow_ret = cow;
251         return 0;
252 }
253
254 /*
255  * check if the tree block can be shared by multiple trees
256  */
257 int btrfs_block_can_be_shared(struct btrfs_root *root,
258                               struct extent_buffer *buf)
259 {
260         /*
261          * Tree blocks not in refernece counted trees and tree roots
262          * are never shared. If a block was allocated after the last
263          * snapshot and the block was not allocated by tree relocation,
264          * we know the block is not shared.
265          */
266         if (root->ref_cows &&
267             buf != root->node && buf != root->commit_root &&
268             (btrfs_header_generation(buf) <=
269              btrfs_root_last_snapshot(&root->root_item) ||
270              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
271                 return 1;
272 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
273         if (root->ref_cows &&
274             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
275                 return 1;
276 #endif
277         return 0;
278 }
279
280 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
281                                        struct btrfs_root *root,
282                                        struct extent_buffer *buf,
283                                        struct extent_buffer *cow,
284                                        int *last_ref)
285 {
286         u64 refs;
287         u64 owner;
288         u64 flags;
289         u64 new_flags = 0;
290         int ret;
291
292         /*
293          * Backrefs update rules:
294          *
295          * Always use full backrefs for extent pointers in tree block
296          * allocated by tree relocation.
297          *
298          * If a shared tree block is no longer referenced by its owner
299          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
300          * use full backrefs for extent pointers in tree block.
301          *
302          * If a tree block is been relocating
303          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
304          * use full backrefs for extent pointers in tree block.
305          * The reason for this is some operations (such as drop tree)
306          * are only allowed for blocks use full backrefs.
307          */
308
309         if (btrfs_block_can_be_shared(root, buf)) {
310                 ret = btrfs_lookup_extent_info(trans, root, buf->start,
311                                                buf->len, &refs, &flags);
312                 BUG_ON(ret);
313                 BUG_ON(refs == 0);
314         } else {
315                 refs = 1;
316                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
317                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
318                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
319                 else
320                         flags = 0;
321         }
322
323         owner = btrfs_header_owner(buf);
324         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
325                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
326
327         if (refs > 1) {
328                 if ((owner == root->root_key.objectid ||
329                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
330                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
331                         ret = btrfs_inc_ref(trans, root, buf, 1);
332                         BUG_ON(ret);
333
334                         if (root->root_key.objectid ==
335                             BTRFS_TREE_RELOC_OBJECTID) {
336                                 ret = btrfs_dec_ref(trans, root, buf, 0);
337                                 BUG_ON(ret);
338                                 ret = btrfs_inc_ref(trans, root, cow, 1);
339                                 BUG_ON(ret);
340                         }
341                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
342                 } else {
343
344                         if (root->root_key.objectid ==
345                             BTRFS_TREE_RELOC_OBJECTID)
346                                 ret = btrfs_inc_ref(trans, root, cow, 1);
347                         else
348                                 ret = btrfs_inc_ref(trans, root, cow, 0);
349                         BUG_ON(ret);
350                 }
351                 if (new_flags != 0) {
352                         ret = btrfs_set_disk_extent_flags(trans, root,
353                                                           buf->start,
354                                                           buf->len,
355                                                           new_flags, 0);
356                         BUG_ON(ret);
357                 }
358         } else {
359                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
360                         if (root->root_key.objectid ==
361                             BTRFS_TREE_RELOC_OBJECTID)
362                                 ret = btrfs_inc_ref(trans, root, cow, 1);
363                         else
364                                 ret = btrfs_inc_ref(trans, root, cow, 0);
365                         BUG_ON(ret);
366                         ret = btrfs_dec_ref(trans, root, buf, 1);
367                         BUG_ON(ret);
368                 }
369                 clean_tree_block(trans, root, buf);
370                 *last_ref = 1;
371         }
372         return 0;
373 }
374
375 /*
376  * does the dirty work in cow of a single block.  The parent block (if
377  * supplied) is updated to point to the new cow copy.  The new buffer is marked
378  * dirty and returned locked.  If you modify the block it needs to be marked
379  * dirty again.
380  *
381  * search_start -- an allocation hint for the new block
382  *
383  * empty_size -- a hint that you plan on doing more cow.  This is the size in
384  * bytes the allocator should try to find free next to the block it returns.
385  * This is just a hint and may be ignored by the allocator.
386  */
387 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
388                              struct btrfs_root *root,
389                              struct extent_buffer *buf,
390                              struct extent_buffer *parent, int parent_slot,
391                              struct extent_buffer **cow_ret,
392                              u64 search_start, u64 empty_size)
393 {
394         struct btrfs_disk_key disk_key;
395         struct extent_buffer *cow;
396         int level;
397         int last_ref = 0;
398         int unlock_orig = 0;
399         u64 parent_start;
400
401         if (*cow_ret == buf)
402                 unlock_orig = 1;
403
404         btrfs_assert_tree_locked(buf);
405
406         WARN_ON(root->ref_cows && trans->transid !=
407                 root->fs_info->running_transaction->transid);
408         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
409
410         level = btrfs_header_level(buf);
411
412         if (level == 0)
413                 btrfs_item_key(buf, &disk_key, 0);
414         else
415                 btrfs_node_key(buf, &disk_key, 0);
416
417         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
418                 if (parent)
419                         parent_start = parent->start;
420                 else
421                         parent_start = 0;
422         } else
423                 parent_start = 0;
424
425         cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
426                                      root->root_key.objectid, &disk_key,
427                                      level, search_start, empty_size);
428         if (IS_ERR(cow))
429                 return PTR_ERR(cow);
430
431         /* cow is set to blocking by btrfs_init_new_buffer */
432
433         copy_extent_buffer(cow, buf, 0, 0, cow->len);
434         btrfs_set_header_bytenr(cow, cow->start);
435         btrfs_set_header_generation(cow, trans->transid);
436         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
437         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
438                                      BTRFS_HEADER_FLAG_RELOC);
439         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
440                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
441         else
442                 btrfs_set_header_owner(cow, root->root_key.objectid);
443
444         write_extent_buffer(cow, root->fs_info->fsid,
445                             (unsigned long)btrfs_header_fsid(cow),
446                             BTRFS_FSID_SIZE);
447
448         update_ref_for_cow(trans, root, buf, cow, &last_ref);
449
450         if (root->ref_cows)
451                 btrfs_reloc_cow_block(trans, root, buf, cow);
452
453         if (buf == root->node) {
454                 WARN_ON(parent && parent != buf);
455                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
456                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
457                         parent_start = buf->start;
458                 else
459                         parent_start = 0;
460
461                 spin_lock(&root->node_lock);
462                 root->node = cow;
463                 extent_buffer_get(cow);
464                 spin_unlock(&root->node_lock);
465
466                 btrfs_free_tree_block(trans, root, buf, parent_start,
467                                       last_ref);
468                 free_extent_buffer(buf);
469                 add_root_to_dirty_list(root);
470         } else {
471                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
472                         parent_start = parent->start;
473                 else
474                         parent_start = 0;
475
476                 WARN_ON(trans->transid != btrfs_header_generation(parent));
477                 btrfs_set_node_blockptr(parent, parent_slot,
478                                         cow->start);
479                 btrfs_set_node_ptr_generation(parent, parent_slot,
480                                               trans->transid);
481                 btrfs_mark_buffer_dirty(parent);
482                 btrfs_free_tree_block(trans, root, buf, parent_start,
483                                       last_ref);
484         }
485         if (unlock_orig)
486                 btrfs_tree_unlock(buf);
487         free_extent_buffer(buf);
488         btrfs_mark_buffer_dirty(cow);
489         *cow_ret = cow;
490         return 0;
491 }
492
493 static inline int should_cow_block(struct btrfs_trans_handle *trans,
494                                    struct btrfs_root *root,
495                                    struct extent_buffer *buf)
496 {
497         if (btrfs_header_generation(buf) == trans->transid &&
498             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
499             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
500               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
501                 return 0;
502         return 1;
503 }
504
505 /*
506  * cows a single block, see __btrfs_cow_block for the real work.
507  * This version of it has extra checks so that a block isn't cow'd more than
508  * once per transaction, as long as it hasn't been written yet
509  */
510 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
511                     struct btrfs_root *root, struct extent_buffer *buf,
512                     struct extent_buffer *parent, int parent_slot,
513                     struct extent_buffer **cow_ret)
514 {
515         u64 search_start;
516         int ret;
517
518         if (trans->transaction != root->fs_info->running_transaction) {
519                 printk(KERN_CRIT "trans %llu running %llu\n",
520                        (unsigned long long)trans->transid,
521                        (unsigned long long)
522                        root->fs_info->running_transaction->transid);
523                 WARN_ON(1);
524         }
525         if (trans->transid != root->fs_info->generation) {
526                 printk(KERN_CRIT "trans %llu running %llu\n",
527                        (unsigned long long)trans->transid,
528                        (unsigned long long)root->fs_info->generation);
529                 WARN_ON(1);
530         }
531
532         if (!should_cow_block(trans, root, buf)) {
533                 *cow_ret = buf;
534                 return 0;
535         }
536
537         search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
538
539         if (parent)
540                 btrfs_set_lock_blocking(parent);
541         btrfs_set_lock_blocking(buf);
542
543         ret = __btrfs_cow_block(trans, root, buf, parent,
544                                  parent_slot, cow_ret, search_start, 0);
545         return ret;
546 }
547
548 /*
549  * helper function for defrag to decide if two blocks pointed to by a
550  * node are actually close by
551  */
552 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
553 {
554         if (blocknr < other && other - (blocknr + blocksize) < 32768)
555                 return 1;
556         if (blocknr > other && blocknr - (other + blocksize) < 32768)
557                 return 1;
558         return 0;
559 }
560
561 /*
562  * compare two keys in a memcmp fashion
563  */
564 static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
565 {
566         struct btrfs_key k1;
567
568         btrfs_disk_key_to_cpu(&k1, disk);
569
570         return btrfs_comp_cpu_keys(&k1, k2);
571 }
572
573 /*
574  * same as comp_keys only with two btrfs_key's
575  */
576 int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
577 {
578         if (k1->objectid > k2->objectid)
579                 return 1;
580         if (k1->objectid < k2->objectid)
581                 return -1;
582         if (k1->type > k2->type)
583                 return 1;
584         if (k1->type < k2->type)
585                 return -1;
586         if (k1->offset > k2->offset)
587                 return 1;
588         if (k1->offset < k2->offset)
589                 return -1;
590         return 0;
591 }
592
593 /*
594  * this is used by the defrag code to go through all the
595  * leaves pointed to by a node and reallocate them so that
596  * disk order is close to key order
597  */
598 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
599                        struct btrfs_root *root, struct extent_buffer *parent,
600                        int start_slot, int cache_only, u64 *last_ret,
601                        struct btrfs_key *progress)
602 {
603         struct extent_buffer *cur;
604         u64 blocknr;
605         u64 gen;
606         u64 search_start = *last_ret;
607         u64 last_block = 0;
608         u64 other;
609         u32 parent_nritems;
610         int end_slot;
611         int i;
612         int err = 0;
613         int parent_level;
614         int uptodate;
615         u32 blocksize;
616         int progress_passed = 0;
617         struct btrfs_disk_key disk_key;
618
619         parent_level = btrfs_header_level(parent);
620         if (cache_only && parent_level != 1)
621                 return 0;
622
623         if (trans->transaction != root->fs_info->running_transaction)
624                 WARN_ON(1);
625         if (trans->transid != root->fs_info->generation)
626                 WARN_ON(1);
627
628         parent_nritems = btrfs_header_nritems(parent);
629         blocksize = btrfs_level_size(root, parent_level - 1);
630         end_slot = parent_nritems;
631
632         if (parent_nritems == 1)
633                 return 0;
634
635         btrfs_set_lock_blocking(parent);
636
637         for (i = start_slot; i < end_slot; i++) {
638                 int close = 1;
639
640                 if (!parent->map_token) {
641                         map_extent_buffer(parent,
642                                         btrfs_node_key_ptr_offset(i),
643                                         sizeof(struct btrfs_key_ptr),
644                                         &parent->map_token, &parent->kaddr,
645                                         &parent->map_start, &parent->map_len,
646                                         KM_USER1);
647                 }
648                 btrfs_node_key(parent, &disk_key, i);
649                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
650                         continue;
651
652                 progress_passed = 1;
653                 blocknr = btrfs_node_blockptr(parent, i);
654                 gen = btrfs_node_ptr_generation(parent, i);
655                 if (last_block == 0)
656                         last_block = blocknr;
657
658                 if (i > 0) {
659                         other = btrfs_node_blockptr(parent, i - 1);
660                         close = close_blocks(blocknr, other, blocksize);
661                 }
662                 if (!close && i < end_slot - 2) {
663                         other = btrfs_node_blockptr(parent, i + 1);
664                         close = close_blocks(blocknr, other, blocksize);
665                 }
666                 if (close) {
667                         last_block = blocknr;
668                         continue;
669                 }
670                 if (parent->map_token) {
671                         unmap_extent_buffer(parent, parent->map_token,
672                                             KM_USER1);
673                         parent->map_token = NULL;
674                 }
675
676                 cur = btrfs_find_tree_block(root, blocknr, blocksize);
677                 if (cur)
678                         uptodate = btrfs_buffer_uptodate(cur, gen);
679                 else
680                         uptodate = 0;
681                 if (!cur || !uptodate) {
682                         if (cache_only) {
683                                 free_extent_buffer(cur);
684                                 continue;
685                         }
686                         if (!cur) {
687                                 cur = read_tree_block(root, blocknr,
688                                                          blocksize, gen);
689                         } else if (!uptodate) {
690                                 btrfs_read_buffer(cur, gen);
691                         }
692                 }
693                 if (search_start == 0)
694                         search_start = last_block;
695
696                 btrfs_tree_lock(cur);
697                 btrfs_set_lock_blocking(cur);
698                 err = __btrfs_cow_block(trans, root, cur, parent, i,
699                                         &cur, search_start,
700                                         min(16 * blocksize,
701                                             (end_slot - i) * blocksize));
702                 if (err) {
703                         btrfs_tree_unlock(cur);
704                         free_extent_buffer(cur);
705                         break;
706                 }
707                 search_start = cur->start;
708                 last_block = cur->start;
709                 *last_ret = search_start;
710                 btrfs_tree_unlock(cur);
711                 free_extent_buffer(cur);
712         }
713         if (parent->map_token) {
714                 unmap_extent_buffer(parent, parent->map_token,
715                                     KM_USER1);
716                 parent->map_token = NULL;
717         }
718         return err;
719 }
720
721 /*
722  * The leaf data grows from end-to-front in the node.
723  * this returns the address of the start of the last item,
724  * which is the stop of the leaf data stack
725  */
726 static inline unsigned int leaf_data_end(struct btrfs_root *root,
727                                          struct extent_buffer *leaf)
728 {
729         u32 nr = btrfs_header_nritems(leaf);
730         if (nr == 0)
731                 return BTRFS_LEAF_DATA_SIZE(root);
732         return btrfs_item_offset_nr(leaf, nr - 1);
733 }
734
735 /*
736  * extra debugging checks to make sure all the items in a key are
737  * well formed and in the proper order
738  */
739 static int check_node(struct btrfs_root *root, struct btrfs_path *path,
740                       int level)
741 {
742         struct extent_buffer *parent = NULL;
743         struct extent_buffer *node = path->nodes[level];
744         struct btrfs_disk_key parent_key;
745         struct btrfs_disk_key node_key;
746         int parent_slot;
747         int slot;
748         struct btrfs_key cpukey;
749         u32 nritems = btrfs_header_nritems(node);
750
751         if (path->nodes[level + 1])
752                 parent = path->nodes[level + 1];
753
754         slot = path->slots[level];
755         BUG_ON(nritems == 0);
756         if (parent) {
757                 parent_slot = path->slots[level + 1];
758                 btrfs_node_key(parent, &parent_key, parent_slot);
759                 btrfs_node_key(node, &node_key, 0);
760                 BUG_ON(memcmp(&parent_key, &node_key,
761                               sizeof(struct btrfs_disk_key)));
762                 BUG_ON(btrfs_node_blockptr(parent, parent_slot) !=
763                        btrfs_header_bytenr(node));
764         }
765         BUG_ON(nritems > BTRFS_NODEPTRS_PER_BLOCK(root));
766         if (slot != 0) {
767                 btrfs_node_key_to_cpu(node, &cpukey, slot - 1);
768                 btrfs_node_key(node, &node_key, slot);
769                 BUG_ON(comp_keys(&node_key, &cpukey) <= 0);
770         }
771         if (slot < nritems - 1) {
772                 btrfs_node_key_to_cpu(node, &cpukey, slot + 1);
773                 btrfs_node_key(node, &node_key, slot);
774                 BUG_ON(comp_keys(&node_key, &cpukey) >= 0);
775         }
776         return 0;
777 }
778
779 /*
780  * extra checking to make sure all the items in a leaf are
781  * well formed and in the proper order
782  */
783 static int check_leaf(struct btrfs_root *root, struct btrfs_path *path,
784                       int level)
785 {
786         struct extent_buffer *leaf = path->nodes[level];
787         struct extent_buffer *parent = NULL;
788         int parent_slot;
789         struct btrfs_key cpukey;
790         struct btrfs_disk_key parent_key;
791         struct btrfs_disk_key leaf_key;
792         int slot = path->slots[0];
793
794         u32 nritems = btrfs_header_nritems(leaf);
795
796         if (path->nodes[level + 1])
797                 parent = path->nodes[level + 1];
798
799         if (nritems == 0)
800                 return 0;
801
802         if (parent) {
803                 parent_slot = path->slots[level + 1];
804                 btrfs_node_key(parent, &parent_key, parent_slot);
805                 btrfs_item_key(leaf, &leaf_key, 0);
806
807                 BUG_ON(memcmp(&parent_key, &leaf_key,
808                        sizeof(struct btrfs_disk_key)));
809                 BUG_ON(btrfs_node_blockptr(parent, parent_slot) !=
810                        btrfs_header_bytenr(leaf));
811         }
812         if (slot != 0 && slot < nritems - 1) {
813                 btrfs_item_key(leaf, &leaf_key, slot);
814                 btrfs_item_key_to_cpu(leaf, &cpukey, slot - 1);
815                 if (comp_keys(&leaf_key, &cpukey) <= 0) {
816                         btrfs_print_leaf(root, leaf);
817                         printk(KERN_CRIT "slot %d offset bad key\n", slot);
818                         BUG_ON(1);
819                 }
820                 if (btrfs_item_offset_nr(leaf, slot - 1) !=
821                        btrfs_item_end_nr(leaf, slot)) {
822                         btrfs_print_leaf(root, leaf);
823                         printk(KERN_CRIT "slot %d offset bad\n", slot);
824                         BUG_ON(1);
825                 }
826         }
827         if (slot < nritems - 1) {
828                 btrfs_item_key(leaf, &leaf_key, slot);
829                 btrfs_item_key_to_cpu(leaf, &cpukey, slot + 1);
830                 BUG_ON(comp_keys(&leaf_key, &cpukey) >= 0);
831                 if (btrfs_item_offset_nr(leaf, slot) !=
832                         btrfs_item_end_nr(leaf, slot + 1)) {
833                         btrfs_print_leaf(root, leaf);
834                         printk(KERN_CRIT "slot %d offset bad\n", slot);
835                         BUG_ON(1);
836                 }
837         }
838         BUG_ON(btrfs_item_offset_nr(leaf, 0) +
839                btrfs_item_size_nr(leaf, 0) != BTRFS_LEAF_DATA_SIZE(root));
840         return 0;
841 }
842
843 static noinline int check_block(struct btrfs_root *root,
844                                 struct btrfs_path *path, int level)
845 {
846         return 0;
847         if (level == 0)
848                 return check_leaf(root, path, level);
849         return check_node(root, path, level);
850 }
851
852 /*
853  * search for key in the extent_buffer.  The items start at offset p,
854  * and they are item_size apart.  There are 'max' items in p.
855  *
856  * the slot in the array is returned via slot, and it points to
857  * the place where you would insert key if it is not found in
858  * the array.
859  *
860  * slot may point to max if the key is bigger than all of the keys
861  */
862 static noinline int generic_bin_search(struct extent_buffer *eb,
863                                        unsigned long p,
864                                        int item_size, struct btrfs_key *key,
865                                        int max, int *slot)
866 {
867         int low = 0;
868         int high = max;
869         int mid;
870         int ret;
871         struct btrfs_disk_key *tmp = NULL;
872         struct btrfs_disk_key unaligned;
873         unsigned long offset;
874         char *map_token = NULL;
875         char *kaddr = NULL;
876         unsigned long map_start = 0;
877         unsigned long map_len = 0;
878         int err;
879
880         while (low < high) {
881                 mid = (low + high) / 2;
882                 offset = p + mid * item_size;
883
884                 if (!map_token || offset < map_start ||
885                     (offset + sizeof(struct btrfs_disk_key)) >
886                     map_start + map_len) {
887                         if (map_token) {
888                                 unmap_extent_buffer(eb, map_token, KM_USER0);
889                                 map_token = NULL;
890                         }
891
892                         err = map_private_extent_buffer(eb, offset,
893                                                 sizeof(struct btrfs_disk_key),
894                                                 &map_token, &kaddr,
895                                                 &map_start, &map_len, KM_USER0);
896
897                         if (!err) {
898                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
899                                                         map_start);
900                         } else {
901                                 read_extent_buffer(eb, &unaligned,
902                                                    offset, sizeof(unaligned));
903                                 tmp = &unaligned;
904                         }
905
906                 } else {
907                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
908                                                         map_start);
909                 }
910                 ret = comp_keys(tmp, key);
911
912                 if (ret < 0)
913                         low = mid + 1;
914                 else if (ret > 0)
915                         high = mid;
916                 else {
917                         *slot = mid;
918                         if (map_token)
919                                 unmap_extent_buffer(eb, map_token, KM_USER0);
920                         return 0;
921                 }
922         }
923         *slot = low;
924         if (map_token)
925                 unmap_extent_buffer(eb, map_token, KM_USER0);
926         return 1;
927 }
928
929 /*
930  * simple bin_search frontend that does the right thing for
931  * leaves vs nodes
932  */
933 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
934                       int level, int *slot)
935 {
936         if (level == 0) {
937                 return generic_bin_search(eb,
938                                           offsetof(struct btrfs_leaf, items),
939                                           sizeof(struct btrfs_item),
940                                           key, btrfs_header_nritems(eb),
941                                           slot);
942         } else {
943                 return generic_bin_search(eb,
944                                           offsetof(struct btrfs_node, ptrs),
945                                           sizeof(struct btrfs_key_ptr),
946                                           key, btrfs_header_nritems(eb),
947                                           slot);
948         }
949         return -1;
950 }
951
952 int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
953                      int level, int *slot)
954 {
955         return bin_search(eb, key, level, slot);
956 }
957
958 static void root_add_used(struct btrfs_root *root, u32 size)
959 {
960         spin_lock(&root->accounting_lock);
961         btrfs_set_root_used(&root->root_item,
962                             btrfs_root_used(&root->root_item) + size);
963         spin_unlock(&root->accounting_lock);
964 }
965
966 static void root_sub_used(struct btrfs_root *root, u32 size)
967 {
968         spin_lock(&root->accounting_lock);
969         btrfs_set_root_used(&root->root_item,
970                             btrfs_root_used(&root->root_item) - size);
971         spin_unlock(&root->accounting_lock);
972 }
973
974 /* given a node and slot number, this reads the blocks it points to.  The
975  * extent buffer is returned with a reference taken (but unlocked).
976  * NULL is returned on error.
977  */
978 static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
979                                    struct extent_buffer *parent, int slot)
980 {
981         int level = btrfs_header_level(parent);
982         if (slot < 0)
983                 return NULL;
984         if (slot >= btrfs_header_nritems(parent))
985                 return NULL;
986
987         BUG_ON(level == 0);
988
989         return read_tree_block(root, btrfs_node_blockptr(parent, slot),
990                        btrfs_level_size(root, level - 1),
991                        btrfs_node_ptr_generation(parent, slot));
992 }
993
994 /*
995  * node level balancing, used to make sure nodes are in proper order for
996  * item deletion.  We balance from the top down, so we have to make sure
997  * that a deletion won't leave an node completely empty later on.
998  */
999 static noinline int balance_level(struct btrfs_trans_handle *trans,
1000                          struct btrfs_root *root,
1001                          struct btrfs_path *path, int level)
1002 {
1003         struct extent_buffer *right = NULL;
1004         struct extent_buffer *mid;
1005         struct extent_buffer *left = NULL;
1006         struct extent_buffer *parent = NULL;
1007         int ret = 0;
1008         int wret;
1009         int pslot;
1010         int orig_slot = path->slots[level];
1011         int err_on_enospc = 0;
1012         u64 orig_ptr;
1013
1014         if (level == 0)
1015                 return 0;
1016
1017         mid = path->nodes[level];
1018
1019         WARN_ON(!path->locks[level]);
1020         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1021
1022         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1023
1024         if (level < BTRFS_MAX_LEVEL - 1)
1025                 parent = path->nodes[level + 1];
1026         pslot = path->slots[level + 1];
1027
1028         /*
1029          * deal with the case where there is only one pointer in the root
1030          * by promoting the node below to a root
1031          */
1032         if (!parent) {
1033                 struct extent_buffer *child;
1034
1035                 if (btrfs_header_nritems(mid) != 1)
1036                         return 0;
1037
1038                 /* promote the child to a root */
1039                 child = read_node_slot(root, mid, 0);
1040                 BUG_ON(!child);
1041                 btrfs_tree_lock(child);
1042                 btrfs_set_lock_blocking(child);
1043                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1044                 if (ret) {
1045                         btrfs_tree_unlock(child);
1046                         free_extent_buffer(child);
1047                         goto enospc;
1048                 }
1049
1050                 spin_lock(&root->node_lock);
1051                 root->node = child;
1052                 spin_unlock(&root->node_lock);
1053
1054                 add_root_to_dirty_list(root);
1055                 btrfs_tree_unlock(child);
1056
1057                 path->locks[level] = 0;
1058                 path->nodes[level] = NULL;
1059                 clean_tree_block(trans, root, mid);
1060                 btrfs_tree_unlock(mid);
1061                 /* once for the path */
1062                 free_extent_buffer(mid);
1063
1064                 root_sub_used(root, mid->len);
1065                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1066                 /* once for the root ptr */
1067                 free_extent_buffer(mid);
1068                 return 0;
1069         }
1070         if (btrfs_header_nritems(mid) >
1071             BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1072                 return 0;
1073
1074         if (btrfs_header_nritems(mid) < 2)
1075                 err_on_enospc = 1;
1076
1077         left = read_node_slot(root, parent, pslot - 1);
1078         if (left) {
1079                 btrfs_tree_lock(left);
1080                 btrfs_set_lock_blocking(left);
1081                 wret = btrfs_cow_block(trans, root, left,
1082                                        parent, pslot - 1, &left);
1083                 if (wret) {
1084                         ret = wret;
1085                         goto enospc;
1086                 }
1087         }
1088         right = read_node_slot(root, parent, pslot + 1);
1089         if (right) {
1090                 btrfs_tree_lock(right);
1091                 btrfs_set_lock_blocking(right);
1092                 wret = btrfs_cow_block(trans, root, right,
1093                                        parent, pslot + 1, &right);
1094                 if (wret) {
1095                         ret = wret;
1096                         goto enospc;
1097                 }
1098         }
1099
1100         /* first, try to make some room in the middle buffer */
1101         if (left) {
1102                 orig_slot += btrfs_header_nritems(left);
1103                 wret = push_node_left(trans, root, left, mid, 1);
1104                 if (wret < 0)
1105                         ret = wret;
1106                 if (btrfs_header_nritems(mid) < 2)
1107                         err_on_enospc = 1;
1108         }
1109
1110         /*
1111          * then try to empty the right most buffer into the middle
1112          */
1113         if (right) {
1114                 wret = push_node_left(trans, root, mid, right, 1);
1115                 if (wret < 0 && wret != -ENOSPC)
1116                         ret = wret;
1117                 if (btrfs_header_nritems(right) == 0) {
1118                         clean_tree_block(trans, root, right);
1119                         btrfs_tree_unlock(right);
1120                         wret = del_ptr(trans, root, path, level + 1, pslot +
1121                                        1);
1122                         if (wret)
1123                                 ret = wret;
1124                         root_sub_used(root, right->len);
1125                         btrfs_free_tree_block(trans, root, right, 0, 1);
1126                         free_extent_buffer(right);
1127                         right = NULL;
1128                 } else {
1129                         struct btrfs_disk_key right_key;
1130                         btrfs_node_key(right, &right_key, 0);
1131                         btrfs_set_node_key(parent, &right_key, pslot + 1);
1132                         btrfs_mark_buffer_dirty(parent);
1133                 }
1134         }
1135         if (btrfs_header_nritems(mid) == 1) {
1136                 /*
1137                  * we're not allowed to leave a node with one item in the
1138                  * tree during a delete.  A deletion from lower in the tree
1139                  * could try to delete the only pointer in this node.
1140                  * So, pull some keys from the left.
1141                  * There has to be a left pointer at this point because
1142                  * otherwise we would have pulled some pointers from the
1143                  * right
1144                  */
1145                 BUG_ON(!left);
1146                 wret = balance_node_right(trans, root, mid, left);
1147                 if (wret < 0) {
1148                         ret = wret;
1149                         goto enospc;
1150                 }
1151                 if (wret == 1) {
1152                         wret = push_node_left(trans, root, left, mid, 1);
1153                         if (wret < 0)
1154                                 ret = wret;
1155                 }
1156                 BUG_ON(wret == 1);
1157         }
1158         if (btrfs_header_nritems(mid) == 0) {
1159                 clean_tree_block(trans, root, mid);
1160                 btrfs_tree_unlock(mid);
1161                 wret = del_ptr(trans, root, path, level + 1, pslot);
1162                 if (wret)
1163                         ret = wret;
1164                 root_sub_used(root, mid->len);
1165                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1166                 free_extent_buffer(mid);
1167                 mid = NULL;
1168         } else {
1169                 /* update the parent key to reflect our changes */
1170                 struct btrfs_disk_key mid_key;
1171                 btrfs_node_key(mid, &mid_key, 0);
1172                 btrfs_set_node_key(parent, &mid_key, pslot);
1173                 btrfs_mark_buffer_dirty(parent);
1174         }
1175
1176         /* update the path */
1177         if (left) {
1178                 if (btrfs_header_nritems(left) > orig_slot) {
1179                         extent_buffer_get(left);
1180                         /* left was locked after cow */
1181                         path->nodes[level] = left;
1182                         path->slots[level + 1] -= 1;
1183                         path->slots[level] = orig_slot;
1184                         if (mid) {
1185                                 btrfs_tree_unlock(mid);
1186                                 free_extent_buffer(mid);
1187                         }
1188                 } else {
1189                         orig_slot -= btrfs_header_nritems(left);
1190                         path->slots[level] = orig_slot;
1191                 }
1192         }
1193         /* double check we haven't messed things up */
1194         check_block(root, path, level);
1195         if (orig_ptr !=
1196             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1197                 BUG();
1198 enospc:
1199         if (right) {
1200                 btrfs_tree_unlock(right);
1201                 free_extent_buffer(right);
1202         }
1203         if (left) {
1204                 if (path->nodes[level] != left)
1205                         btrfs_tree_unlock(left);
1206                 free_extent_buffer(left);
1207         }
1208         return ret;
1209 }
1210
1211 /* Node balancing for insertion.  Here we only split or push nodes around
1212  * when they are completely full.  This is also done top down, so we
1213  * have to be pessimistic.
1214  */
1215 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1216                                           struct btrfs_root *root,
1217                                           struct btrfs_path *path, int level)
1218 {
1219         struct extent_buffer *right = NULL;
1220         struct extent_buffer *mid;
1221         struct extent_buffer *left = NULL;
1222         struct extent_buffer *parent = NULL;
1223         int ret = 0;
1224         int wret;
1225         int pslot;
1226         int orig_slot = path->slots[level];
1227         u64 orig_ptr;
1228
1229         if (level == 0)
1230                 return 1;
1231
1232         mid = path->nodes[level];
1233         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1234         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1235
1236         if (level < BTRFS_MAX_LEVEL - 1)
1237                 parent = path->nodes[level + 1];
1238         pslot = path->slots[level + 1];
1239
1240         if (!parent)
1241                 return 1;
1242
1243         left = read_node_slot(root, parent, pslot - 1);
1244
1245         /* first, try to make some room in the middle buffer */
1246         if (left) {
1247                 u32 left_nr;
1248
1249                 btrfs_tree_lock(left);
1250                 btrfs_set_lock_blocking(left);
1251
1252                 left_nr = btrfs_header_nritems(left);
1253                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1254                         wret = 1;
1255                 } else {
1256                         ret = btrfs_cow_block(trans, root, left, parent,
1257                                               pslot - 1, &left);
1258                         if (ret)
1259                                 wret = 1;
1260                         else {
1261                                 wret = push_node_left(trans, root,
1262                                                       left, mid, 0);
1263                         }
1264                 }
1265                 if (wret < 0)
1266                         ret = wret;
1267                 if (wret == 0) {
1268                         struct btrfs_disk_key disk_key;
1269                         orig_slot += left_nr;
1270                         btrfs_node_key(mid, &disk_key, 0);
1271                         btrfs_set_node_key(parent, &disk_key, pslot);
1272                         btrfs_mark_buffer_dirty(parent);
1273                         if (btrfs_header_nritems(left) > orig_slot) {
1274                                 path->nodes[level] = left;
1275                                 path->slots[level + 1] -= 1;
1276                                 path->slots[level] = orig_slot;
1277                                 btrfs_tree_unlock(mid);
1278                                 free_extent_buffer(mid);
1279                         } else {
1280                                 orig_slot -=
1281                                         btrfs_header_nritems(left);
1282                                 path->slots[level] = orig_slot;
1283                                 btrfs_tree_unlock(left);
1284                                 free_extent_buffer(left);
1285                         }
1286                         return 0;
1287                 }
1288                 btrfs_tree_unlock(left);
1289                 free_extent_buffer(left);
1290         }
1291         right = read_node_slot(root, parent, pslot + 1);
1292
1293         /*
1294          * then try to empty the right most buffer into the middle
1295          */
1296         if (right) {
1297                 u32 right_nr;
1298
1299                 btrfs_tree_lock(right);
1300                 btrfs_set_lock_blocking(right);
1301
1302                 right_nr = btrfs_header_nritems(right);
1303                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1304                         wret = 1;
1305                 } else {
1306                         ret = btrfs_cow_block(trans, root, right,
1307                                               parent, pslot + 1,
1308                                               &right);
1309                         if (ret)
1310                                 wret = 1;
1311                         else {
1312                                 wret = balance_node_right(trans, root,
1313                                                           right, mid);
1314                         }
1315                 }
1316                 if (wret < 0)
1317                         ret = wret;
1318                 if (wret == 0) {
1319                         struct btrfs_disk_key disk_key;
1320
1321                         btrfs_node_key(right, &disk_key, 0);
1322                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
1323                         btrfs_mark_buffer_dirty(parent);
1324
1325                         if (btrfs_header_nritems(mid) <= orig_slot) {
1326                                 path->nodes[level] = right;
1327                                 path->slots[level + 1] += 1;
1328                                 path->slots[level] = orig_slot -
1329                                         btrfs_header_nritems(mid);
1330                                 btrfs_tree_unlock(mid);
1331                                 free_extent_buffer(mid);
1332                         } else {
1333                                 btrfs_tree_unlock(right);
1334                                 free_extent_buffer(right);
1335                         }
1336                         return 0;
1337                 }
1338                 btrfs_tree_unlock(right);
1339                 free_extent_buffer(right);
1340         }
1341         return 1;
1342 }
1343
1344 /*
1345  * readahead one full node of leaves, finding things that are close
1346  * to the block in 'slot', and triggering ra on them.
1347  */
1348 static void reada_for_search(struct btrfs_root *root,
1349                              struct btrfs_path *path,
1350                              int level, int slot, u64 objectid)
1351 {
1352         struct extent_buffer *node;
1353         struct btrfs_disk_key disk_key;
1354         u32 nritems;
1355         u64 search;
1356         u64 target;
1357         u64 nread = 0;
1358         int direction = path->reada;
1359         struct extent_buffer *eb;
1360         u32 nr;
1361         u32 blocksize;
1362         u32 nscan = 0;
1363
1364         if (level != 1)
1365                 return;
1366
1367         if (!path->nodes[level])
1368                 return;
1369
1370         node = path->nodes[level];
1371
1372         search = btrfs_node_blockptr(node, slot);
1373         blocksize = btrfs_level_size(root, level - 1);
1374         eb = btrfs_find_tree_block(root, search, blocksize);
1375         if (eb) {
1376                 free_extent_buffer(eb);
1377                 return;
1378         }
1379
1380         target = search;
1381
1382         nritems = btrfs_header_nritems(node);
1383         nr = slot;
1384         while (1) {
1385                 if (direction < 0) {
1386                         if (nr == 0)
1387                                 break;
1388                         nr--;
1389                 } else if (direction > 0) {
1390                         nr++;
1391                         if (nr >= nritems)
1392                                 break;
1393                 }
1394                 if (path->reada < 0 && objectid) {
1395                         btrfs_node_key(node, &disk_key, nr);
1396                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
1397                                 break;
1398                 }
1399                 search = btrfs_node_blockptr(node, nr);
1400                 if ((search <= target && target - search <= 65536) ||
1401                     (search > target && search - target <= 65536)) {
1402                         readahead_tree_block(root, search, blocksize,
1403                                      btrfs_node_ptr_generation(node, nr));
1404                         nread += blocksize;
1405                 }
1406                 nscan++;
1407                 if ((nread > 65536 || nscan > 32))
1408                         break;
1409         }
1410 }
1411
1412 /*
1413  * returns -EAGAIN if it had to drop the path, or zero if everything was in
1414  * cache
1415  */
1416 static noinline int reada_for_balance(struct btrfs_root *root,
1417                                       struct btrfs_path *path, int level)
1418 {
1419         int slot;
1420         int nritems;
1421         struct extent_buffer *parent;
1422         struct extent_buffer *eb;
1423         u64 gen;
1424         u64 block1 = 0;
1425         u64 block2 = 0;
1426         int ret = 0;
1427         int blocksize;
1428
1429         parent = path->nodes[level + 1];
1430         if (!parent)
1431                 return 0;
1432
1433         nritems = btrfs_header_nritems(parent);
1434         slot = path->slots[level + 1];
1435         blocksize = btrfs_level_size(root, level);
1436
1437         if (slot > 0) {
1438                 block1 = btrfs_node_blockptr(parent, slot - 1);
1439                 gen = btrfs_node_ptr_generation(parent, slot - 1);
1440                 eb = btrfs_find_tree_block(root, block1, blocksize);
1441                 if (eb && btrfs_buffer_uptodate(eb, gen))
1442                         block1 = 0;
1443                 free_extent_buffer(eb);
1444         }
1445         if (slot + 1 < nritems) {
1446                 block2 = btrfs_node_blockptr(parent, slot + 1);
1447                 gen = btrfs_node_ptr_generation(parent, slot + 1);
1448                 eb = btrfs_find_tree_block(root, block2, blocksize);
1449                 if (eb && btrfs_buffer_uptodate(eb, gen))
1450                         block2 = 0;
1451                 free_extent_buffer(eb);
1452         }
1453         if (block1 || block2) {
1454                 ret = -EAGAIN;
1455
1456                 /* release the whole path */
1457                 btrfs_release_path(root, path);
1458
1459                 /* read the blocks */
1460                 if (block1)
1461                         readahead_tree_block(root, block1, blocksize, 0);
1462                 if (block2)
1463                         readahead_tree_block(root, block2, blocksize, 0);
1464
1465                 if (block1) {
1466                         eb = read_tree_block(root, block1, blocksize, 0);
1467                         free_extent_buffer(eb);
1468                 }
1469                 if (block2) {
1470                         eb = read_tree_block(root, block2, blocksize, 0);
1471                         free_extent_buffer(eb);
1472                 }
1473         }
1474         return ret;
1475 }
1476
1477
1478 /*
1479  * when we walk down the tree, it is usually safe to unlock the higher layers
1480  * in the tree.  The exceptions are when our path goes through slot 0, because
1481  * operations on the tree might require changing key pointers higher up in the
1482  * tree.
1483  *
1484  * callers might also have set path->keep_locks, which tells this code to keep
1485  * the lock if the path points to the last slot in the block.  This is part of
1486  * walking through the tree, and selecting the next slot in the higher block.
1487  *
1488  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1489  * if lowest_unlock is 1, level 0 won't be unlocked
1490  */
1491 static noinline void unlock_up(struct btrfs_path *path, int level,
1492                                int lowest_unlock)
1493 {
1494         int i;
1495         int skip_level = level;
1496         int no_skips = 0;
1497         struct extent_buffer *t;
1498
1499         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1500                 if (!path->nodes[i])
1501                         break;
1502                 if (!path->locks[i])
1503                         break;
1504                 if (!no_skips && path->slots[i] == 0) {
1505                         skip_level = i + 1;
1506                         continue;
1507                 }
1508                 if (!no_skips && path->keep_locks) {
1509                         u32 nritems;
1510                         t = path->nodes[i];
1511                         nritems = btrfs_header_nritems(t);
1512                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
1513                                 skip_level = i + 1;
1514                                 continue;
1515                         }
1516                 }
1517                 if (skip_level < i && i >= lowest_unlock)
1518                         no_skips = 1;
1519
1520                 t = path->nodes[i];
1521                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
1522                         btrfs_tree_unlock(t);
1523                         path->locks[i] = 0;
1524                 }
1525         }
1526 }
1527
1528 /*
1529  * This releases any locks held in the path starting at level and
1530  * going all the way up to the root.
1531  *
1532  * btrfs_search_slot will keep the lock held on higher nodes in a few
1533  * corner cases, such as COW of the block at slot zero in the node.  This
1534  * ignores those rules, and it should only be called when there are no
1535  * more updates to be done higher up in the tree.
1536  */
1537 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
1538 {
1539         int i;
1540
1541         if (path->keep_locks)
1542                 return;
1543
1544         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1545                 if (!path->nodes[i])
1546                         continue;
1547                 if (!path->locks[i])
1548                         continue;
1549                 btrfs_tree_unlock(path->nodes[i]);
1550                 path->locks[i] = 0;
1551         }
1552 }
1553
1554 /*
1555  * helper function for btrfs_search_slot.  The goal is to find a block
1556  * in cache without setting the path to blocking.  If we find the block
1557  * we return zero and the path is unchanged.
1558  *
1559  * If we can't find the block, we set the path blocking and do some
1560  * reada.  -EAGAIN is returned and the search must be repeated.
1561  */
1562 static int
1563 read_block_for_search(struct btrfs_trans_handle *trans,
1564                        struct btrfs_root *root, struct btrfs_path *p,
1565                        struct extent_buffer **eb_ret, int level, int slot,
1566                        struct btrfs_key *key)
1567 {
1568         u64 blocknr;
1569         u64 gen;
1570         u32 blocksize;
1571         struct extent_buffer *b = *eb_ret;
1572         struct extent_buffer *tmp;
1573         int ret;
1574
1575         blocknr = btrfs_node_blockptr(b, slot);
1576         gen = btrfs_node_ptr_generation(b, slot);
1577         blocksize = btrfs_level_size(root, level - 1);
1578
1579         tmp = btrfs_find_tree_block(root, blocknr, blocksize);
1580         if (tmp && btrfs_buffer_uptodate(tmp, gen)) {
1581                 /*
1582                  * we found an up to date block without sleeping, return
1583                  * right away
1584                  */
1585                 *eb_ret = tmp;
1586                 return 0;
1587         }
1588
1589         /*
1590          * reduce lock contention at high levels
1591          * of the btree by dropping locks before
1592          * we read.  Don't release the lock on the current
1593          * level because we need to walk this node to figure
1594          * out which blocks to read.
1595          */
1596         btrfs_unlock_up_safe(p, level + 1);
1597         btrfs_set_path_blocking(p);
1598
1599         if (tmp)
1600                 free_extent_buffer(tmp);
1601         if (p->reada)
1602                 reada_for_search(root, p, level, slot, key->objectid);
1603
1604         btrfs_release_path(NULL, p);
1605
1606         ret = -EAGAIN;
1607         tmp = read_tree_block(root, blocknr, blocksize, 0);
1608         if (tmp) {
1609                 /*
1610                  * If the read above didn't mark this buffer up to date,
1611                  * it will never end up being up to date.  Set ret to EIO now
1612                  * and give up so that our caller doesn't loop forever
1613                  * on our EAGAINs.
1614                  */
1615                 if (!btrfs_buffer_uptodate(tmp, 0))
1616                         ret = -EIO;
1617                 free_extent_buffer(tmp);
1618         }
1619         return ret;
1620 }
1621
1622 /*
1623  * helper function for btrfs_search_slot.  This does all of the checks
1624  * for node-level blocks and does any balancing required based on
1625  * the ins_len.
1626  *
1627  * If no extra work was required, zero is returned.  If we had to
1628  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1629  * start over
1630  */
1631 static int
1632 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1633                        struct btrfs_root *root, struct btrfs_path *p,
1634                        struct extent_buffer *b, int level, int ins_len)
1635 {
1636         int ret;
1637         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1638             BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
1639                 int sret;
1640
1641                 sret = reada_for_balance(root, p, level);
1642                 if (sret)
1643                         goto again;
1644
1645                 btrfs_set_path_blocking(p);
1646                 sret = split_node(trans, root, p, level);
1647                 btrfs_clear_path_blocking(p, NULL);
1648
1649                 BUG_ON(sret > 0);
1650                 if (sret) {
1651                         ret = sret;
1652                         goto done;
1653                 }
1654                 b = p->nodes[level];
1655         } else if (ins_len < 0 && btrfs_header_nritems(b) <
1656                    BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
1657                 int sret;
1658
1659                 sret = reada_for_balance(root, p, level);
1660                 if (sret)
1661                         goto again;
1662
1663                 btrfs_set_path_blocking(p);
1664                 sret = balance_level(trans, root, p, level);
1665                 btrfs_clear_path_blocking(p, NULL);
1666
1667                 if (sret) {
1668                         ret = sret;
1669                         goto done;
1670                 }
1671                 b = p->nodes[level];
1672                 if (!b) {
1673                         btrfs_release_path(NULL, p);
1674                         goto again;
1675                 }
1676                 BUG_ON(btrfs_header_nritems(b) == 1);
1677         }
1678         return 0;
1679
1680 again:
1681         ret = -EAGAIN;
1682 done:
1683         return ret;
1684 }
1685
1686 /*
1687  * look for key in the tree.  path is filled in with nodes along the way
1688  * if key is found, we return zero and you can find the item in the leaf
1689  * level of the path (level 0)
1690  *
1691  * If the key isn't found, the path points to the slot where it should
1692  * be inserted, and 1 is returned.  If there are other errors during the
1693  * search a negative error number is returned.
1694  *
1695  * if ins_len > 0, nodes and leaves will be split as we walk down the
1696  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
1697  * possible)
1698  */
1699 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
1700                       *root, struct btrfs_key *key, struct btrfs_path *p, int
1701                       ins_len, int cow)
1702 {
1703         struct extent_buffer *b;
1704         int slot;
1705         int ret;
1706         int err;
1707         int level;
1708         int lowest_unlock = 1;
1709         u8 lowest_level = 0;
1710
1711         lowest_level = p->lowest_level;
1712         WARN_ON(lowest_level && ins_len > 0);
1713         WARN_ON(p->nodes[0] != NULL);
1714
1715         if (ins_len < 0)
1716                 lowest_unlock = 2;
1717
1718 again:
1719         if (p->search_commit_root) {
1720                 b = root->commit_root;
1721                 extent_buffer_get(b);
1722                 if (!p->skip_locking)
1723                         btrfs_tree_lock(b);
1724         } else {
1725                 if (p->skip_locking)
1726                         b = btrfs_root_node(root);
1727                 else
1728                         b = btrfs_lock_root_node(root);
1729         }
1730
1731         while (b) {
1732                 level = btrfs_header_level(b);
1733
1734                 /*
1735                  * setup the path here so we can release it under lock
1736                  * contention with the cow code
1737                  */
1738                 p->nodes[level] = b;
1739                 if (!p->skip_locking)
1740                         p->locks[level] = 1;
1741
1742                 if (cow) {
1743                         /*
1744                          * if we don't really need to cow this block
1745                          * then we don't want to set the path blocking,
1746                          * so we test it here
1747                          */
1748                         if (!should_cow_block(trans, root, b))
1749                                 goto cow_done;
1750
1751                         btrfs_set_path_blocking(p);
1752
1753                         err = btrfs_cow_block(trans, root, b,
1754                                               p->nodes[level + 1],
1755                                               p->slots[level + 1], &b);
1756                         if (err) {
1757                                 ret = err;
1758                                 goto done;
1759                         }
1760                 }
1761 cow_done:
1762                 BUG_ON(!cow && ins_len);
1763                 if (level != btrfs_header_level(b))
1764                         WARN_ON(1);
1765                 level = btrfs_header_level(b);
1766
1767                 p->nodes[level] = b;
1768                 if (!p->skip_locking)
1769                         p->locks[level] = 1;
1770
1771                 btrfs_clear_path_blocking(p, NULL);
1772
1773                 /*
1774                  * we have a lock on b and as long as we aren't changing
1775                  * the tree, there is no way to for the items in b to change.
1776                  * It is safe to drop the lock on our parent before we
1777                  * go through the expensive btree search on b.
1778                  *
1779                  * If cow is true, then we might be changing slot zero,
1780                  * which may require changing the parent.  So, we can't
1781                  * drop the lock until after we know which slot we're
1782                  * operating on.
1783                  */
1784                 if (!cow)
1785                         btrfs_unlock_up_safe(p, level + 1);
1786
1787                 ret = check_block(root, p, level);
1788                 if (ret) {
1789                         ret = -1;
1790                         goto done;
1791                 }
1792
1793                 ret = bin_search(b, key, level, &slot);
1794
1795                 if (level != 0) {
1796                         int dec = 0;
1797                         if (ret && slot > 0) {
1798                                 dec = 1;
1799                                 slot -= 1;
1800                         }
1801                         p->slots[level] = slot;
1802                         err = setup_nodes_for_search(trans, root, p, b, level,
1803                                                      ins_len);
1804                         if (err == -EAGAIN)
1805                                 goto again;
1806                         if (err) {
1807                                 ret = err;
1808                                 goto done;
1809                         }
1810                         b = p->nodes[level];
1811                         slot = p->slots[level];
1812
1813                         unlock_up(p, level, lowest_unlock);
1814
1815                         if (level == lowest_level) {
1816                                 if (dec)
1817                                         p->slots[level]++;
1818                                 goto done;
1819                         }
1820
1821                         err = read_block_for_search(trans, root, p,
1822                                                     &b, level, slot, key);
1823                         if (err == -EAGAIN)
1824                                 goto again;
1825                         if (err) {
1826                                 ret = err;
1827                                 goto done;
1828                         }
1829
1830                         if (!p->skip_locking) {
1831                                 btrfs_clear_path_blocking(p, NULL);
1832                                 err = btrfs_try_spin_lock(b);
1833
1834                                 if (!err) {
1835                                         btrfs_set_path_blocking(p);
1836                                         btrfs_tree_lock(b);
1837                                         btrfs_clear_path_blocking(p, b);
1838                                 }
1839                         }
1840                 } else {
1841                         p->slots[level] = slot;
1842                         if (ins_len > 0 &&
1843                             btrfs_leaf_free_space(root, b) < ins_len) {
1844                                 btrfs_set_path_blocking(p);
1845                                 err = split_leaf(trans, root, key,
1846                                                  p, ins_len, ret == 0);
1847                                 btrfs_clear_path_blocking(p, NULL);
1848
1849                                 BUG_ON(err > 0);
1850                                 if (err) {
1851                                         ret = err;
1852                                         goto done;
1853                                 }
1854                         }
1855                         if (!p->search_for_split)
1856                                 unlock_up(p, level, lowest_unlock);
1857                         goto done;
1858                 }
1859         }
1860         ret = 1;
1861 done:
1862         /*
1863          * we don't really know what they plan on doing with the path
1864          * from here on, so for now just mark it as blocking
1865          */
1866         if (!p->leave_spinning)
1867                 btrfs_set_path_blocking(p);
1868         if (ret < 0)
1869                 btrfs_release_path(root, p);
1870         return ret;
1871 }
1872
1873 /*
1874  * adjust the pointers going up the tree, starting at level
1875  * making sure the right key of each node is points to 'key'.
1876  * This is used after shifting pointers to the left, so it stops
1877  * fixing up pointers when a given leaf/node is not in slot 0 of the
1878  * higher levels
1879  *
1880  * If this fails to write a tree block, it returns -1, but continues
1881  * fixing up the blocks in ram so the tree is consistent.
1882  */
1883 static int fixup_low_keys(struct btrfs_trans_handle *trans,
1884                           struct btrfs_root *root, struct btrfs_path *path,
1885                           struct btrfs_disk_key *key, int level)
1886 {
1887         int i;
1888         int ret = 0;
1889         struct extent_buffer *t;
1890
1891         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1892                 int tslot = path->slots[i];
1893                 if (!path->nodes[i])
1894                         break;
1895                 t = path->nodes[i];
1896                 btrfs_set_node_key(t, key, tslot);
1897                 btrfs_mark_buffer_dirty(path->nodes[i]);
1898                 if (tslot != 0)
1899                         break;
1900         }
1901         return ret;
1902 }
1903
1904 /*
1905  * update item key.
1906  *
1907  * This function isn't completely safe. It's the caller's responsibility
1908  * that the new key won't break the order
1909  */
1910 int btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
1911                             struct btrfs_root *root, struct btrfs_path *path,
1912                             struct btrfs_key *new_key)
1913 {
1914         struct btrfs_disk_key disk_key;
1915         struct extent_buffer *eb;
1916         int slot;
1917
1918         eb = path->nodes[0];
1919         slot = path->slots[0];
1920         if (slot > 0) {
1921                 btrfs_item_key(eb, &disk_key, slot - 1);
1922                 if (comp_keys(&disk_key, new_key) >= 0)
1923                         return -1;
1924         }
1925         if (slot < btrfs_header_nritems(eb) - 1) {
1926                 btrfs_item_key(eb, &disk_key, slot + 1);
1927                 if (comp_keys(&disk_key, new_key) <= 0)
1928                         return -1;
1929         }
1930
1931         btrfs_cpu_key_to_disk(&disk_key, new_key);
1932         btrfs_set_item_key(eb, &disk_key, slot);
1933         btrfs_mark_buffer_dirty(eb);
1934         if (slot == 0)
1935                 fixup_low_keys(trans, root, path, &disk_key, 1);
1936         return 0;
1937 }
1938
1939 /*
1940  * try to push data from one node into the next node left in the
1941  * tree.
1942  *
1943  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
1944  * error, and > 0 if there was no room in the left hand block.
1945  */
1946 static int push_node_left(struct btrfs_trans_handle *trans,
1947                           struct btrfs_root *root, struct extent_buffer *dst,
1948                           struct extent_buffer *src, int empty)
1949 {
1950         int push_items = 0;
1951         int src_nritems;
1952         int dst_nritems;
1953         int ret = 0;
1954
1955         src_nritems = btrfs_header_nritems(src);
1956         dst_nritems = btrfs_header_nritems(dst);
1957         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
1958         WARN_ON(btrfs_header_generation(src) != trans->transid);
1959         WARN_ON(btrfs_header_generation(dst) != trans->transid);
1960
1961         if (!empty && src_nritems <= 8)
1962                 return 1;
1963
1964         if (push_items <= 0)
1965                 return 1;
1966
1967         if (empty) {
1968                 push_items = min(src_nritems, push_items);
1969                 if (push_items < src_nritems) {
1970                         /* leave at least 8 pointers in the node if
1971                          * we aren't going to empty it
1972                          */
1973                         if (src_nritems - push_items < 8) {
1974                                 if (push_items <= 8)
1975                                         return 1;
1976                                 push_items -= 8;
1977                         }
1978                 }
1979         } else
1980                 push_items = min(src_nritems - 8, push_items);
1981
1982         copy_extent_buffer(dst, src,
1983                            btrfs_node_key_ptr_offset(dst_nritems),
1984                            btrfs_node_key_ptr_offset(0),
1985                            push_items * sizeof(struct btrfs_key_ptr));
1986
1987         if (push_items < src_nritems) {
1988                 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
1989                                       btrfs_node_key_ptr_offset(push_items),
1990                                       (src_nritems - push_items) *
1991                                       sizeof(struct btrfs_key_ptr));
1992         }
1993         btrfs_set_header_nritems(src, src_nritems - push_items);
1994         btrfs_set_header_nritems(dst, dst_nritems + push_items);
1995         btrfs_mark_buffer_dirty(src);
1996         btrfs_mark_buffer_dirty(dst);
1997
1998         return ret;
1999 }
2000
2001 /*
2002  * try to push data from one node into the next node right in the
2003  * tree.
2004  *
2005  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2006  * error, and > 0 if there was no room in the right hand block.
2007  *
2008  * this will  only push up to 1/2 the contents of the left node over
2009  */
2010 static int balance_node_right(struct btrfs_trans_handle *trans,
2011                               struct btrfs_root *root,
2012                               struct extent_buffer *dst,
2013                               struct extent_buffer *src)
2014 {
2015         int push_items = 0;
2016         int max_push;
2017         int src_nritems;
2018         int dst_nritems;
2019         int ret = 0;
2020
2021         WARN_ON(btrfs_header_generation(src) != trans->transid);
2022         WARN_ON(btrfs_header_generation(dst) != trans->transid);
2023
2024         src_nritems = btrfs_header_nritems(src);
2025         dst_nritems = btrfs_header_nritems(dst);
2026         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2027         if (push_items <= 0)
2028                 return 1;
2029
2030         if (src_nritems < 4)
2031                 return 1;
2032
2033         max_push = src_nritems / 2 + 1;
2034         /* don't try to empty the node */
2035         if (max_push >= src_nritems)
2036                 return 1;
2037
2038         if (max_push < push_items)
2039                 push_items = max_push;
2040
2041         memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
2042                                       btrfs_node_key_ptr_offset(0),
2043                                       (dst_nritems) *
2044                                       sizeof(struct btrfs_key_ptr));
2045
2046         copy_extent_buffer(dst, src,
2047                            btrfs_node_key_ptr_offset(0),
2048                            btrfs_node_key_ptr_offset(src_nritems - push_items),
2049                            push_items * sizeof(struct btrfs_key_ptr));
2050
2051         btrfs_set_header_nritems(src, src_nritems - push_items);
2052         btrfs_set_header_nritems(dst, dst_nritems + push_items);
2053
2054         btrfs_mark_buffer_dirty(src);
2055         btrfs_mark_buffer_dirty(dst);
2056
2057         return ret;
2058 }
2059
2060 /*
2061  * helper function to insert a new root level in the tree.
2062  * A new node is allocated, and a single item is inserted to
2063  * point to the existing root
2064  *
2065  * returns zero on success or < 0 on failure.
2066  */
2067 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2068                            struct btrfs_root *root,
2069                            struct btrfs_path *path, int level)
2070 {
2071         u64 lower_gen;
2072         struct extent_buffer *lower;
2073         struct extent_buffer *c;
2074         struct extent_buffer *old;
2075         struct btrfs_disk_key lower_key;
2076
2077         BUG_ON(path->nodes[level]);
2078         BUG_ON(path->nodes[level-1] != root->node);
2079
2080         lower = path->nodes[level-1];
2081         if (level == 1)
2082                 btrfs_item_key(lower, &lower_key, 0);
2083         else
2084                 btrfs_node_key(lower, &lower_key, 0);
2085
2086         c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
2087                                    root->root_key.objectid, &lower_key,
2088                                    level, root->node->start, 0);
2089         if (IS_ERR(c))
2090                 return PTR_ERR(c);
2091
2092         root_add_used(root, root->nodesize);
2093
2094         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
2095         btrfs_set_header_nritems(c, 1);
2096         btrfs_set_header_level(c, level);
2097         btrfs_set_header_bytenr(c, c->start);
2098         btrfs_set_header_generation(c, trans->transid);
2099         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
2100         btrfs_set_header_owner(c, root->root_key.objectid);
2101
2102         write_extent_buffer(c, root->fs_info->fsid,
2103                             (unsigned long)btrfs_header_fsid(c),
2104                             BTRFS_FSID_SIZE);
2105
2106         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2107                             (unsigned long)btrfs_header_chunk_tree_uuid(c),
2108                             BTRFS_UUID_SIZE);
2109
2110         btrfs_set_node_key(c, &lower_key, 0);
2111         btrfs_set_node_blockptr(c, 0, lower->start);
2112         lower_gen = btrfs_header_generation(lower);
2113         WARN_ON(lower_gen != trans->transid);
2114
2115         btrfs_set_node_ptr_generation(c, 0, lower_gen);
2116
2117         btrfs_mark_buffer_dirty(c);
2118
2119         spin_lock(&root->node_lock);
2120         old = root->node;
2121         root->node = c;
2122         spin_unlock(&root->node_lock);
2123
2124         /* the super has an extra ref to root->node */
2125         free_extent_buffer(old);
2126
2127         add_root_to_dirty_list(root);
2128         extent_buffer_get(c);
2129         path->nodes[level] = c;
2130         path->locks[level] = 1;
2131         path->slots[level] = 0;
2132         return 0;
2133 }
2134
2135 /*
2136  * worker function to insert a single pointer in a node.
2137  * the node should have enough room for the pointer already
2138  *
2139  * slot and level indicate where you want the key to go, and
2140  * blocknr is the block the key points to.
2141  *
2142  * returns zero on success and < 0 on any error
2143  */
2144 static int insert_ptr(struct btrfs_trans_handle *trans, struct btrfs_root
2145                       *root, struct btrfs_path *path, struct btrfs_disk_key
2146                       *key, u64 bytenr, int slot, int level)
2147 {
2148         struct extent_buffer *lower;
2149         int nritems;
2150
2151         BUG_ON(!path->nodes[level]);
2152         btrfs_assert_tree_locked(path->nodes[level]);
2153         lower = path->nodes[level];
2154         nritems = btrfs_header_nritems(lower);
2155         BUG_ON(slot > nritems);
2156         if (nritems == BTRFS_NODEPTRS_PER_BLOCK(root))
2157                 BUG();
2158         if (slot != nritems) {
2159                 memmove_extent_buffer(lower,
2160                               btrfs_node_key_ptr_offset(slot + 1),
2161                               btrfs_node_key_ptr_offset(slot),
2162                               (nritems - slot) * sizeof(struct btrfs_key_ptr));
2163         }
2164         btrfs_set_node_key(lower, key, slot);
2165         btrfs_set_node_blockptr(lower, slot, bytenr);
2166         WARN_ON(trans->transid == 0);
2167         btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2168         btrfs_set_header_nritems(lower, nritems + 1);
2169         btrfs_mark_buffer_dirty(lower);
2170         return 0;
2171 }
2172
2173 /*
2174  * split the node at the specified level in path in two.
2175  * The path is corrected to point to the appropriate node after the split
2176  *
2177  * Before splitting this tries to make some room in the node by pushing
2178  * left and right, if either one works, it returns right away.
2179  *
2180  * returns 0 on success and < 0 on failure
2181  */
2182 static noinline int split_node(struct btrfs_trans_handle *trans,
2183                                struct btrfs_root *root,
2184                                struct btrfs_path *path, int level)
2185 {
2186         struct extent_buffer *c;
2187         struct extent_buffer *split;
2188         struct btrfs_disk_key disk_key;
2189         int mid;
2190         int ret;
2191         int wret;
2192         u32 c_nritems;
2193
2194         c = path->nodes[level];
2195         WARN_ON(btrfs_header_generation(c) != trans->transid);
2196         if (c == root->node) {
2197                 /* trying to split the root, lets make a new one */
2198                 ret = insert_new_root(trans, root, path, level + 1);
2199                 if (ret)
2200                         return ret;
2201         } else {
2202                 ret = push_nodes_for_insert(trans, root, path, level);
2203                 c = path->nodes[level];
2204                 if (!ret && btrfs_header_nritems(c) <
2205                     BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
2206                         return 0;
2207                 if (ret < 0)
2208                         return ret;
2209         }
2210
2211         c_nritems = btrfs_header_nritems(c);
2212         mid = (c_nritems + 1) / 2;
2213         btrfs_node_key(c, &disk_key, mid);
2214
2215         split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
2216                                         root->root_key.objectid,
2217                                         &disk_key, level, c->start, 0);
2218         if (IS_ERR(split))
2219                 return PTR_ERR(split);
2220
2221         root_add_used(root, root->nodesize);
2222
2223         memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
2224         btrfs_set_header_level(split, btrfs_header_level(c));
2225         btrfs_set_header_bytenr(split, split->start);
2226         btrfs_set_header_generation(split, trans->transid);
2227         btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
2228         btrfs_set_header_owner(split, root->root_key.objectid);
2229         write_extent_buffer(split, root->fs_info->fsid,
2230                             (unsigned long)btrfs_header_fsid(split),
2231                             BTRFS_FSID_SIZE);
2232         write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
2233                             (unsigned long)btrfs_header_chunk_tree_uuid(split),
2234                             BTRFS_UUID_SIZE);
2235
2236
2237         copy_extent_buffer(split, c,
2238                            btrfs_node_key_ptr_offset(0),
2239                            btrfs_node_key_ptr_offset(mid),
2240                            (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2241         btrfs_set_header_nritems(split, c_nritems - mid);
2242         btrfs_set_header_nritems(c, mid);
2243         ret = 0;
2244
2245         btrfs_mark_buffer_dirty(c);
2246         btrfs_mark_buffer_dirty(split);
2247
2248         wret = insert_ptr(trans, root, path, &disk_key, split->start,
2249                           path->slots[level + 1] + 1,
2250                           level + 1);
2251         if (wret)
2252                 ret = wret;
2253
2254         if (path->slots[level] >= mid) {
2255                 path->slots[level] -= mid;
2256                 btrfs_tree_unlock(c);
2257                 free_extent_buffer(c);
2258                 path->nodes[level] = split;
2259                 path->slots[level + 1] += 1;
2260         } else {
2261                 btrfs_tree_unlock(split);
2262                 free_extent_buffer(split);
2263         }
2264         return ret;
2265 }
2266
2267 /*
2268  * how many bytes are required to store the items in a leaf.  start
2269  * and nr indicate which items in the leaf to check.  This totals up the
2270  * space used both by the item structs and the item data
2271  */
2272 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2273 {
2274         int data_len;
2275         int nritems = btrfs_header_nritems(l);
2276         int end = min(nritems, start + nr) - 1;
2277
2278         if (!nr)
2279                 return 0;
2280         data_len = btrfs_item_end_nr(l, start);
2281         data_len = data_len - btrfs_item_offset_nr(l, end);
2282         data_len += sizeof(struct btrfs_item) * nr;
2283         WARN_ON(data_len < 0);
2284         return data_len;
2285 }
2286
2287 /*
2288  * The space between the end of the leaf items and
2289  * the start of the leaf data.  IOW, how much room
2290  * the leaf has left for both items and data
2291  */
2292 noinline int btrfs_leaf_free_space(struct btrfs_root *root,
2293                                    struct extent_buffer *leaf)
2294 {
2295         int nritems = btrfs_header_nritems(leaf);
2296         int ret;
2297         ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
2298         if (ret < 0) {
2299                 printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
2300                        "used %d nritems %d\n",
2301                        ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
2302                        leaf_space_used(leaf, 0, nritems), nritems);
2303         }
2304         return ret;
2305 }
2306
2307 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
2308                                       struct btrfs_root *root,
2309                                       struct btrfs_path *path,
2310                                       int data_size, int empty,
2311                                       struct extent_buffer *right,
2312                                       int free_space, u32 left_nritems)
2313 {
2314         struct extent_buffer *left = path->nodes[0];
2315         struct extent_buffer *upper = path->nodes[1];
2316         struct btrfs_disk_key disk_key;
2317         int slot;
2318         u32 i;
2319         int push_space = 0;
2320         int push_items = 0;
2321         struct btrfs_item *item;
2322         u32 nr;
2323         u32 right_nritems;
2324         u32 data_end;
2325         u32 this_item_size;
2326
2327         if (empty)
2328                 nr = 0;
2329         else
2330                 nr = 1;
2331
2332         if (path->slots[0] >= left_nritems)
2333                 push_space += data_size;
2334
2335         slot = path->slots[1];
2336         i = left_nritems - 1;
2337         while (i >= nr) {
2338                 item = btrfs_item_nr(left, i);
2339
2340                 if (!empty && push_items > 0) {
2341                         if (path->slots[0] > i)
2342                                 break;
2343                         if (path->slots[0] == i) {
2344                                 int space = btrfs_leaf_free_space(root, left);
2345                                 if (space + push_space * 2 > free_space)
2346                                         break;
2347                         }
2348                 }
2349
2350                 if (path->slots[0] == i)
2351                         push_space += data_size;
2352
2353                 if (!left->map_token) {
2354                         map_extent_buffer(left, (unsigned long)item,
2355                                         sizeof(struct btrfs_item),
2356                                         &left->map_token, &left->kaddr,
2357                                         &left->map_start, &left->map_len,
2358                                         KM_USER1);
2359                 }
2360
2361                 this_item_size = btrfs_item_size(left, item);
2362                 if (this_item_size + sizeof(*item) + push_space > free_space)
2363                         break;
2364
2365                 push_items++;
2366                 push_space += this_item_size + sizeof(*item);
2367                 if (i == 0)
2368                         break;
2369                 i--;
2370         }
2371         if (left->map_token) {
2372                 unmap_extent_buffer(left, left->map_token, KM_USER1);
2373                 left->map_token = NULL;
2374         }
2375
2376         if (push_items == 0)
2377                 goto out_unlock;
2378
2379         if (!empty && push_items == left_nritems)
2380                 WARN_ON(1);
2381
2382         /* push left to right */
2383         right_nritems = btrfs_header_nritems(right);
2384
2385         push_space = btrfs_item_end_nr(left, left_nritems - push_items);
2386         push_space -= leaf_data_end(root, left);
2387
2388         /* make room in the right data area */
2389         data_end = leaf_data_end(root, right);
2390         memmove_extent_buffer(right,
2391                               btrfs_leaf_data(right) + data_end - push_space,
2392                               btrfs_leaf_data(right) + data_end,
2393                               BTRFS_LEAF_DATA_SIZE(root) - data_end);
2394
2395         /* copy from the left data area */
2396         copy_extent_buffer(right, left, btrfs_leaf_data(right) +
2397                      BTRFS_LEAF_DATA_SIZE(root) - push_space,
2398                      btrfs_leaf_data(left) + leaf_data_end(root, left),
2399                      push_space);
2400
2401         memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
2402                               btrfs_item_nr_offset(0),
2403                               right_nritems * sizeof(struct btrfs_item));
2404
2405         /* copy the items from left to right */
2406         copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
2407                    btrfs_item_nr_offset(left_nritems - push_items),
2408                    push_items * sizeof(struct btrfs_item));
2409
2410         /* update the item pointers */
2411         right_nritems += push_items;
2412         btrfs_set_header_nritems(right, right_nritems);
2413         push_space = BTRFS_LEAF_DATA_SIZE(root);
2414         for (i = 0; i < right_nritems; i++) {
2415                 item = btrfs_item_nr(right, i);
2416                 if (!right->map_token) {
2417                         map_extent_buffer(right, (unsigned long)item,
2418                                         sizeof(struct btrfs_item),
2419                                         &right->map_token, &right->kaddr,
2420                                         &right->map_start, &right->map_len,
2421                                         KM_USER1);
2422                 }
2423                 push_space -= btrfs_item_size(right, item);
2424                 btrfs_set_item_offset(right, item, push_space);
2425         }
2426
2427         if (right->map_token) {
2428                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2429                 right->map_token = NULL;
2430         }
2431         left_nritems -= push_items;
2432         btrfs_set_header_nritems(left, left_nritems);
2433
2434         if (left_nritems)
2435                 btrfs_mark_buffer_dirty(left);
2436         else
2437                 clean_tree_block(trans, root, left);
2438
2439         btrfs_mark_buffer_dirty(right);
2440
2441         btrfs_item_key(right, &disk_key, 0);
2442         btrfs_set_node_key(upper, &disk_key, slot + 1);
2443         btrfs_mark_buffer_dirty(upper);
2444
2445         /* then fixup the leaf pointer in the path */
2446         if (path->slots[0] >= left_nritems) {
2447                 path->slots[0] -= left_nritems;
2448                 if (btrfs_header_nritems(path->nodes[0]) == 0)
2449                         clean_tree_block(trans, root, path->nodes[0]);
2450                 btrfs_tree_unlock(path->nodes[0]);
2451                 free_extent_buffer(path->nodes[0]);
2452                 path->nodes[0] = right;
2453                 path->slots[1] += 1;
2454         } else {
2455                 btrfs_tree_unlock(right);
2456                 free_extent_buffer(right);
2457         }
2458         return 0;
2459
2460 out_unlock:
2461         btrfs_tree_unlock(right);
2462         free_extent_buffer(right);
2463         return 1;
2464 }
2465
2466 /*
2467  * push some data in the path leaf to the right, trying to free up at
2468  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2469  *
2470  * returns 1 if the push failed because the other node didn't have enough
2471  * room, 0 if everything worked out and < 0 if there were major errors.
2472  */
2473 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
2474                            *root, struct btrfs_path *path, int data_size,
2475                            int empty)
2476 {
2477         struct extent_buffer *left = path->nodes[0];
2478         struct extent_buffer *right;
2479         struct extent_buffer *upper;
2480         int slot;
2481         int free_space;
2482         u32 left_nritems;
2483         int ret;
2484
2485         if (!path->nodes[1])
2486                 return 1;
2487
2488         slot = path->slots[1];
2489         upper = path->nodes[1];
2490         if (slot >= btrfs_header_nritems(upper) - 1)
2491                 return 1;
2492
2493         btrfs_assert_tree_locked(path->nodes[1]);
2494
2495         right = read_node_slot(root, upper, slot + 1);
2496         btrfs_tree_lock(right);
2497         btrfs_set_lock_blocking(right);
2498
2499         free_space = btrfs_leaf_free_space(root, right);
2500         if (free_space < data_size)
2501                 goto out_unlock;
2502
2503         /* cow and double check */
2504         ret = btrfs_cow_block(trans, root, right, upper,
2505                               slot + 1, &right);
2506         if (ret)
2507                 goto out_unlock;
2508
2509         free_space = btrfs_leaf_free_space(root, right);
2510         if (free_space < data_size)
2511                 goto out_unlock;
2512
2513         left_nritems = btrfs_header_nritems(left);
2514         if (left_nritems == 0)
2515                 goto out_unlock;
2516
2517         return __push_leaf_right(trans, root, path, data_size, empty,
2518                                 right, free_space, left_nritems);
2519 out_unlock:
2520         btrfs_tree_unlock(right);
2521         free_extent_buffer(right);
2522         return 1;
2523 }
2524
2525 /*
2526  * push some data in the path leaf to the left, trying to free up at
2527  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2528  */
2529 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
2530                                      struct btrfs_root *root,
2531                                      struct btrfs_path *path, int data_size,
2532                                      int empty, struct extent_buffer *left,
2533                                      int free_space, int right_nritems)
2534 {
2535         struct btrfs_disk_key disk_key;
2536         struct extent_buffer *right = path->nodes[0];
2537         int slot;
2538         int i;
2539         int push_space = 0;
2540         int push_items = 0;
2541         struct btrfs_item *item;
2542         u32 old_left_nritems;
2543         u32 nr;
2544         int ret = 0;
2545         int wret;
2546         u32 this_item_size;
2547         u32 old_left_item_size;
2548
2549         slot = path->slots[1];
2550
2551         if (empty)
2552                 nr = right_nritems;
2553         else
2554                 nr = right_nritems - 1;
2555
2556         for (i = 0; i < nr; i++) {
2557                 item = btrfs_item_nr(right, i);
2558                 if (!right->map_token) {
2559                         map_extent_buffer(right, (unsigned long)item,
2560                                         sizeof(struct btrfs_item),
2561                                         &right->map_token, &right->kaddr,
2562                                         &right->map_start, &right->map_len,
2563                                         KM_USER1);
2564                 }
2565
2566                 if (!empty && push_items > 0) {
2567                         if (path->slots[0] < i)
2568                                 break;
2569                         if (path->slots[0] == i) {
2570                                 int space = btrfs_leaf_free_space(root, right);
2571                                 if (space + push_space * 2 > free_space)
2572                                         break;
2573                         }
2574                 }
2575
2576                 if (path->slots[0] == i)
2577                         push_space += data_size;
2578
2579                 this_item_size = btrfs_item_size(right, item);
2580                 if (this_item_size + sizeof(*item) + push_space > free_space)
2581                         break;
2582
2583                 push_items++;
2584                 push_space += this_item_size + sizeof(*item);
2585         }
2586
2587         if (right->map_token) {
2588                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2589                 right->map_token = NULL;
2590         }
2591
2592         if (push_items == 0) {
2593                 ret = 1;
2594                 goto out;
2595         }
2596         if (!empty && push_items == btrfs_header_nritems(right))
2597                 WARN_ON(1);
2598
2599         /* push data from right to left */
2600         copy_extent_buffer(left, right,
2601                            btrfs_item_nr_offset(btrfs_header_nritems(left)),
2602                            btrfs_item_nr_offset(0),
2603                            push_items * sizeof(struct btrfs_item));
2604
2605         push_space = BTRFS_LEAF_DATA_SIZE(root) -
2606                      btrfs_item_offset_nr(right, push_items - 1);
2607
2608         copy_extent_buffer(left, right, btrfs_leaf_data(left) +
2609                      leaf_data_end(root, left) - push_space,
2610                      btrfs_leaf_data(right) +
2611                      btrfs_item_offset_nr(right, push_items - 1),
2612                      push_space);
2613         old_left_nritems = btrfs_header_nritems(left);
2614         BUG_ON(old_left_nritems <= 0);
2615
2616         old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
2617         for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
2618                 u32 ioff;
2619
2620                 item = btrfs_item_nr(left, i);
2621                 if (!left->map_token) {
2622                         map_extent_buffer(left, (unsigned long)item,
2623                                         sizeof(struct btrfs_item),
2624                                         &left->map_token, &left->kaddr,
2625                                         &left->map_start, &left->map_len,
2626                                         KM_USER1);
2627                 }
2628
2629                 ioff = btrfs_item_offset(left, item);
2630                 btrfs_set_item_offset(left, item,
2631                       ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size));
2632         }
2633         btrfs_set_header_nritems(left, old_left_nritems + push_items);
2634         if (left->map_token) {
2635                 unmap_extent_buffer(left, left->map_token, KM_USER1);
2636                 left->map_token = NULL;
2637         }
2638
2639         /* fixup right node */
2640         if (push_items > right_nritems) {
2641                 printk(KERN_CRIT "push items %d nr %u\n", push_items,
2642                        right_nritems);
2643                 WARN_ON(1);
2644         }
2645
2646         if (push_items < right_nritems) {
2647                 push_space = btrfs_item_offset_nr(right, push_items - 1) -
2648                                                   leaf_data_end(root, right);
2649                 memmove_extent_buffer(right, btrfs_leaf_data(right) +
2650                                       BTRFS_LEAF_DATA_SIZE(root) - push_space,
2651                                       btrfs_leaf_data(right) +
2652                                       leaf_data_end(root, right), push_space);
2653
2654                 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
2655                               btrfs_item_nr_offset(push_items),
2656                              (btrfs_header_nritems(right) - push_items) *
2657                              sizeof(struct btrfs_item));
2658         }
2659         right_nritems -= push_items;
2660         btrfs_set_header_nritems(right, right_nritems);
2661         push_space = BTRFS_LEAF_DATA_SIZE(root);
2662         for (i = 0; i < right_nritems; i++) {
2663                 item = btrfs_item_nr(right, i);
2664
2665                 if (!right->map_token) {
2666                         map_extent_buffer(right, (unsigned long)item,
2667                                         sizeof(struct btrfs_item),
2668                                         &right->map_token, &right->kaddr,
2669                                         &right->map_start, &right->map_len,
2670                                         KM_USER1);
2671                 }
2672
2673                 push_space = push_space - btrfs_item_size(right, item);
2674                 btrfs_set_item_offset(right, item, push_space);
2675         }
2676         if (right->map_token) {
2677                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2678                 right->map_token = NULL;
2679         }
2680
2681         btrfs_mark_buffer_dirty(left);
2682         if (right_nritems)
2683                 btrfs_mark_buffer_dirty(right);
2684         else
2685                 clean_tree_block(trans, root, right);
2686
2687         btrfs_item_key(right, &disk_key, 0);
2688         wret = fixup_low_keys(trans, root, path, &disk_key, 1);
2689         if (wret)
2690                 ret = wret;
2691
2692         /* then fixup the leaf pointer in the path */
2693         if (path->slots[0] < push_items) {
2694                 path->slots[0] += old_left_nritems;
2695                 btrfs_tree_unlock(path->nodes[0]);
2696                 free_extent_buffer(path->nodes[0]);
2697                 path->nodes[0] = left;
2698                 path->slots[1] -= 1;
2699         } else {
2700                 btrfs_tree_unlock(left);
2701                 free_extent_buffer(left);
2702                 path->slots[0] -= push_items;
2703         }
2704         BUG_ON(path->slots[0] < 0);
2705         return ret;
2706 out:
2707         btrfs_tree_unlock(left);
2708         free_extent_buffer(left);
2709         return ret;
2710 }
2711
2712 /*
2713  * push some data in the path leaf to the left, trying to free up at
2714  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2715  */
2716 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
2717                           *root, struct btrfs_path *path, int data_size,
2718                           int empty)
2719 {
2720         struct extent_buffer *right = path->nodes[0];
2721         struct extent_buffer *left;
2722         int slot;
2723         int free_space;
2724         u32 right_nritems;
2725         int ret = 0;
2726
2727         slot = path->slots[1];
2728         if (slot == 0)
2729                 return 1;
2730         if (!path->nodes[1])
2731                 return 1;
2732
2733         right_nritems = btrfs_header_nritems(right);
2734         if (right_nritems == 0)
2735                 return 1;
2736
2737         btrfs_assert_tree_locked(path->nodes[1]);
2738
2739         left = read_node_slot(root, path->nodes[1], slot - 1);
2740         btrfs_tree_lock(left);
2741         btrfs_set_lock_blocking(left);
2742
2743         free_space = btrfs_leaf_free_space(root, left);
2744         if (free_space < data_size) {
2745                 ret = 1;
2746                 goto out;
2747         }
2748
2749         /* cow and double check */
2750         ret = btrfs_cow_block(trans, root, left,
2751                               path->nodes[1], slot - 1, &left);
2752         if (ret) {
2753                 /* we hit -ENOSPC, but it isn't fatal here */
2754                 ret = 1;
2755                 goto out;
2756         }
2757
2758         free_space = btrfs_leaf_free_space(root, left);
2759         if (free_space < data_size) {
2760                 ret = 1;
2761                 goto out;
2762         }
2763
2764         return __push_leaf_left(trans, root, path, data_size,
2765                                empty, left, free_space, right_nritems);
2766 out:
2767         btrfs_tree_unlock(left);
2768         free_extent_buffer(left);
2769         return ret;
2770 }
2771
2772 /*
2773  * split the path's leaf in two, making sure there is at least data_size
2774  * available for the resulting leaf level of the path.
2775  *
2776  * returns 0 if all went well and < 0 on failure.
2777  */
2778 static noinline int copy_for_split(struct btrfs_trans_handle *trans,
2779                                struct btrfs_root *root,
2780                                struct btrfs_path *path,
2781                                struct extent_buffer *l,
2782                                struct extent_buffer *right,
2783                                int slot, int mid, int nritems)
2784 {
2785         int data_copy_size;
2786         int rt_data_off;
2787         int i;
2788         int ret = 0;
2789         int wret;
2790         struct btrfs_disk_key disk_key;
2791
2792         nritems = nritems - mid;
2793         btrfs_set_header_nritems(right, nritems);
2794         data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
2795
2796         copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
2797                            btrfs_item_nr_offset(mid),
2798                            nritems * sizeof(struct btrfs_item));
2799
2800         copy_extent_buffer(right, l,
2801                      btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
2802                      data_copy_size, btrfs_leaf_data(l) +
2803                      leaf_data_end(root, l), data_copy_size);
2804
2805         rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
2806                       btrfs_item_end_nr(l, mid);
2807
2808         for (i = 0; i < nritems; i++) {
2809                 struct btrfs_item *item = btrfs_item_nr(right, i);
2810                 u32 ioff;
2811
2812                 if (!right->map_token) {
2813                         map_extent_buffer(right, (unsigned long)item,
2814                                         sizeof(struct btrfs_item),
2815                                         &right->map_token, &right->kaddr,
2816                                         &right->map_start, &right->map_len,
2817                                         KM_USER1);
2818                 }
2819
2820                 ioff = btrfs_item_offset(right, item);
2821                 btrfs_set_item_offset(right, item, ioff + rt_data_off);
2822         }
2823
2824         if (right->map_token) {
2825                 unmap_extent_buffer(right, right->map_token, KM_USER1);
2826                 right->map_token = NULL;
2827         }
2828
2829         btrfs_set_header_nritems(l, mid);
2830         ret = 0;
2831         btrfs_item_key(right, &disk_key, 0);
2832         wret = insert_ptr(trans, root, path, &disk_key, right->start,
2833                           path->slots[1] + 1, 1);
2834         if (wret)
2835                 ret = wret;
2836
2837         btrfs_mark_buffer_dirty(right);
2838         btrfs_mark_buffer_dirty(l);
2839         BUG_ON(path->slots[0] != slot);
2840
2841         if (mid <= slot) {
2842                 btrfs_tree_unlock(path->nodes[0]);
2843                 free_extent_buffer(path->nodes[0]);
2844                 path->nodes[0] = right;
2845                 path->slots[0] -= mid;
2846                 path->slots[1] += 1;
2847         } else {
2848                 btrfs_tree_unlock(right);
2849                 free_extent_buffer(right);
2850         }
2851
2852         BUG_ON(path->slots[0] < 0);
2853
2854         return ret;
2855 }
2856
2857 /*
2858  * split the path's leaf in two, making sure there is at least data_size
2859  * available for the resulting leaf level of the path.
2860  *
2861  * returns 0 if all went well and < 0 on failure.
2862  */
2863 static noinline int split_leaf(struct btrfs_trans_handle *trans,
2864                                struct btrfs_root *root,
2865                                struct btrfs_key *ins_key,
2866                                struct btrfs_path *path, int data_size,
2867                                int extend)
2868 {
2869         struct btrfs_disk_key disk_key;
2870         struct extent_buffer *l;
2871         u32 nritems;
2872         int mid;
2873         int slot;
2874         struct extent_buffer *right;
2875         int ret = 0;
2876         int wret;
2877         int split;
2878         int num_doubles = 0;
2879
2880         l = path->nodes[0];
2881         slot = path->slots[0];
2882         if (extend && data_size + btrfs_item_size_nr(l, slot) +
2883             sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
2884                 return -EOVERFLOW;
2885
2886         /* first try to make some room by pushing left and right */
2887         if (data_size && ins_key->type != BTRFS_DIR_ITEM_KEY) {
2888                 wret = push_leaf_right(trans, root, path, data_size, 0);
2889                 if (wret < 0)
2890                         return wret;
2891                 if (wret) {
2892                         wret = push_leaf_left(trans, root, path, data_size, 0);
2893                         if (wret < 0)
2894                                 return wret;
2895                 }
2896                 l = path->nodes[0];
2897
2898                 /* did the pushes work? */
2899                 if (btrfs_leaf_free_space(root, l) >= data_size)
2900                         return 0;
2901         }
2902
2903         if (!path->nodes[1]) {
2904                 ret = insert_new_root(trans, root, path, 1);
2905                 if (ret)
2906                         return ret;
2907         }
2908 again:
2909         split = 1;
2910         l = path->nodes[0];
2911         slot = path->slots[0];
2912         nritems = btrfs_header_nritems(l);
2913         mid = (nritems + 1) / 2;
2914
2915         if (mid <= slot) {
2916                 if (nritems == 1 ||
2917                     leaf_space_used(l, mid, nritems - mid) + data_size >
2918                         BTRFS_LEAF_DATA_SIZE(root)) {
2919                         if (slot >= nritems) {
2920                                 split = 0;
2921                         } else {
2922                                 mid = slot;
2923                                 if (mid != nritems &&
2924                                     leaf_space_used(l, mid, nritems - mid) +
2925                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2926                                         split = 2;
2927                                 }
2928                         }
2929                 }
2930         } else {
2931                 if (leaf_space_used(l, 0, mid) + data_size >
2932                         BTRFS_LEAF_DATA_SIZE(root)) {
2933                         if (!extend && data_size && slot == 0) {
2934                                 split = 0;
2935                         } else if ((extend || !data_size) && slot == 0) {
2936                                 mid = 1;
2937                         } else {
2938                                 mid = slot;
2939                                 if (mid != nritems &&
2940                                     leaf_space_used(l, mid, nritems - mid) +
2941                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2942                                         split = 2 ;
2943                                 }
2944                         }
2945                 }
2946         }
2947
2948         if (split == 0)
2949                 btrfs_cpu_key_to_disk(&disk_key, ins_key);
2950         else
2951                 btrfs_item_key(l, &disk_key, mid);
2952
2953         right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
2954                                         root->root_key.objectid,
2955                                         &disk_key, 0, l->start, 0);
2956         if (IS_ERR(right))
2957                 return PTR_ERR(right);
2958
2959         root_add_used(root, root->leafsize);
2960
2961         memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
2962         btrfs_set_header_bytenr(right, right->start);
2963         btrfs_set_header_generation(right, trans->transid);
2964         btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
2965         btrfs_set_header_owner(right, root->root_key.objectid);
2966         btrfs_set_header_level(right, 0);
2967         write_extent_buffer(right, root->fs_info->fsid,
2968                             (unsigned long)btrfs_header_fsid(right),
2969                             BTRFS_FSID_SIZE);
2970
2971         write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
2972                             (unsigned long)btrfs_header_chunk_tree_uuid(right),
2973                             BTRFS_UUID_SIZE);
2974
2975         if (split == 0) {
2976                 if (mid <= slot) {
2977                         btrfs_set_header_nritems(right, 0);
2978                         wret = insert_ptr(trans, root, path,
2979                                           &disk_key, right->start,
2980                                           path->slots[1] + 1, 1);
2981                         if (wret)
2982                                 ret = wret;
2983
2984                         btrfs_tree_unlock(path->nodes[0]);
2985                         free_extent_buffer(path->nodes[0]);
2986                         path->nodes[0] = right;
2987                         path->slots[0] = 0;
2988                         path->slots[1] += 1;
2989                 } else {
2990                         btrfs_set_header_nritems(right, 0);
2991                         wret = insert_ptr(trans, root, path,
2992                                           &disk_key,
2993                                           right->start,
2994                                           path->slots[1], 1);
2995                         if (wret)
2996                                 ret = wret;
2997                         btrfs_tree_unlock(path->nodes[0]);
2998                         free_extent_buffer(path->nodes[0]);
2999                         path->nodes[0] = right;
3000                         path->slots[0] = 0;
3001                         if (path->slots[1] == 0) {
3002                                 wret = fixup_low_keys(trans, root,
3003                                                 path, &disk_key, 1);
3004                                 if (wret)
3005                                         ret = wret;
3006                         }
3007                 }
3008                 btrfs_mark_buffer_dirty(right);
3009                 return ret;
3010         }
3011
3012         ret = copy_for_split(trans, root, path, l, right, slot, mid, nritems);
3013         BUG_ON(ret);
3014
3015         if (split == 2) {
3016                 BUG_ON(num_doubles != 0);
3017                 num_doubles++;
3018                 goto again;
3019         }
3020
3021         return ret;
3022 }
3023
3024 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3025                                          struct btrfs_root *root,
3026                                          struct btrfs_path *path, int ins_len)
3027 {
3028         struct btrfs_key key;
3029         struct extent_buffer *leaf;
3030         struct btrfs_file_extent_item *fi;
3031         u64 extent_len = 0;
3032         u32 item_size;
3033         int ret;
3034
3035         leaf = path->nodes[0];
3036         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3037
3038         BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3039                key.type != BTRFS_EXTENT_CSUM_KEY);
3040
3041         if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3042                 return 0;
3043
3044         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3045         if (key.type == BTRFS_EXTENT_DATA_KEY) {
3046                 fi = btrfs_item_ptr(leaf, path->slots[0],
3047                                     struct btrfs_file_extent_item);
3048                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3049         }
3050         btrfs_release_path(root, path);
3051
3052         path->keep_locks = 1;
3053         path->search_for_split = 1;
3054         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3055         path->search_for_split = 0;
3056         if (ret < 0)
3057                 goto err;
3058
3059         ret = -EAGAIN;
3060         leaf = path->nodes[0];
3061         /* if our item isn't there or got smaller, return now */
3062         if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3063                 goto err;
3064
3065         /* the leaf has  changed, it now has room.  return now */
3066         if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3067                 goto err;
3068
3069         if (key.type == BTRFS_EXTENT_DATA_KEY) {
3070                 fi = btrfs_item_ptr(leaf, path->slots[0],
3071                                     struct btrfs_file_extent_item);
3072                 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3073                         goto err;
3074         }
3075
3076         btrfs_set_path_blocking(path);
3077         ret = split_leaf(trans, root, &key, path, ins_len, 1);
3078         if (ret)
3079                 goto err;
3080
3081         path->keep_locks = 0;
3082         btrfs_unlock_up_safe(path, 1);
3083         return 0;
3084 err:
3085         path->keep_locks = 0;
3086         return ret;
3087 }
3088
3089 static noinline int split_item(struct btrfs_trans_handle *trans,
3090                                struct btrfs_root *root,
3091                                struct btrfs_path *path,
3092                                struct btrfs_key *new_key,
3093                                unsigned long split_offset)
3094 {
3095         struct extent_buffer *leaf;
3096         struct btrfs_item *item;
3097         struct btrfs_item *new_item;
3098         int slot;
3099         char *buf;
3100         u32 nritems;
3101         u32 item_size;
3102         u32 orig_offset;
3103         struct btrfs_disk_key disk_key;
3104
3105         leaf = path->nodes[0];
3106         BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3107
3108         btrfs_set_path_blocking(path);
3109
3110         item = btrfs_item_nr(leaf, path->slots[0]);
3111         orig_offset = btrfs_item_offset(leaf, item);
3112         item_size = btrfs_item_size(leaf, item);
3113
3114         buf = kmalloc(item_size, GFP_NOFS);
3115         if (!buf)
3116                 return -ENOMEM;
3117
3118         read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3119                             path->slots[0]), item_size);
3120
3121         slot = path->slots[0] + 1;
3122         nritems = btrfs_header_nritems(leaf);
3123         if (slot != nritems) {
3124                 /* shift the items */
3125                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3126                                 btrfs_item_nr_offset(slot),
3127                                 (nritems - slot) * sizeof(struct btrfs_item));
3128         }
3129
3130         btrfs_cpu_key_to_disk(&disk_key, new_key);
3131         btrfs_set_item_key(leaf, &disk_key, slot);
3132
3133         new_item = btrfs_item_nr(leaf, slot);
3134
3135         btrfs_set_item_offset(leaf, new_item, orig_offset);
3136         btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3137
3138         btrfs_set_item_offset(leaf, item,
3139                               orig_offset + item_size - split_offset);
3140         btrfs_set_item_size(leaf, item, split_offset);
3141
3142         btrfs_set_header_nritems(leaf, nritems + 1);
3143
3144         /* write the data for the start of the original item */
3145         write_extent_buffer(leaf, buf,
3146                             btrfs_item_ptr_offset(leaf, path->slots[0]),