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