Btrfs-progs: remove the unnecessary 'return -1;' at the end of bin_search
[platform/upstream/btrfs-progs.git] / ctree.c
1 /*
2  * Copyright (C) 2007 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 #include "ctree.h"
19 #include "disk-io.h"
20 #include "transaction.h"
21 #include "print-tree.h"
22 #include "repair.h"
23
24 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
25                       *root, struct btrfs_path *path, int level);
26 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
27                       *root, struct btrfs_key *ins_key,
28                       struct btrfs_path *path, int data_size, int extend);
29 static int push_node_left(struct btrfs_trans_handle *trans,
30                           struct btrfs_root *root, struct extent_buffer *dst,
31                           struct extent_buffer *src, int empty);
32 static int balance_node_right(struct btrfs_trans_handle *trans,
33                               struct btrfs_root *root,
34                               struct extent_buffer *dst_buf,
35                               struct extent_buffer *src_buf);
36
37 inline void btrfs_init_path(struct btrfs_path *p)
38 {
39         memset(p, 0, sizeof(*p));
40 }
41
42 struct btrfs_path *btrfs_alloc_path(void)
43 {
44         struct btrfs_path *path;
45         path = kmalloc(sizeof(struct btrfs_path), GFP_NOFS);
46         if (path) {
47                 btrfs_init_path(path);
48                 path->reada = 0;
49         }
50         return path;
51 }
52
53 void btrfs_free_path(struct btrfs_path *p)
54 {
55         btrfs_release_path(NULL, p);
56         kfree(p);
57 }
58
59 void btrfs_release_path(struct btrfs_root *root, struct btrfs_path *p)
60 {
61         int i;
62         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
63                 if (!p->nodes[i])
64                         continue;
65                 free_extent_buffer(p->nodes[i]);
66         }
67         memset(p, 0, sizeof(*p));
68 }
69
70 void add_root_to_dirty_list(struct btrfs_root *root)
71 {
72         if (root->track_dirty && list_empty(&root->dirty_list)) {
73                 list_add(&root->dirty_list,
74                          &root->fs_info->dirty_cowonly_roots);
75         }
76 }
77
78 int btrfs_copy_root(struct btrfs_trans_handle *trans,
79                       struct btrfs_root *root,
80                       struct extent_buffer *buf,
81                       struct extent_buffer **cow_ret, u64 new_root_objectid)
82 {
83         struct extent_buffer *cow;
84         int ret = 0;
85         int level;
86         struct btrfs_root *new_root;
87         struct btrfs_disk_key disk_key;
88
89         new_root = kmalloc(sizeof(*new_root), GFP_NOFS);
90         if (!new_root)
91                 return -ENOMEM;
92
93         memcpy(new_root, root, sizeof(*new_root));
94         new_root->root_key.objectid = new_root_objectid;
95
96         WARN_ON(root->ref_cows && trans->transid !=
97                 root->fs_info->running_transaction->transid);
98         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
99
100         level = btrfs_header_level(buf);
101         if (level == 0)
102                 btrfs_item_key(buf, &disk_key, 0);
103         else
104                 btrfs_node_key(buf, &disk_key, 0);
105         cow = btrfs_alloc_free_block(trans, new_root, buf->len,
106                                      new_root_objectid, &disk_key,
107                                      level, buf->start, 0);
108         if (IS_ERR(cow)) {
109                 kfree(new_root);
110                 return PTR_ERR(cow);
111         }
112
113         copy_extent_buffer(cow, buf, 0, 0, cow->len);
114         btrfs_set_header_bytenr(cow, cow->start);
115         btrfs_set_header_generation(cow, trans->transid);
116         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
117         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
118                                      BTRFS_HEADER_FLAG_RELOC);
119         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
120                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
121         else
122                 btrfs_set_header_owner(cow, new_root_objectid);
123
124         write_extent_buffer(cow, root->fs_info->fsid,
125                             (unsigned long)btrfs_header_fsid(cow),
126                             BTRFS_FSID_SIZE);
127
128         WARN_ON(btrfs_header_generation(buf) > trans->transid);
129         ret = btrfs_inc_ref(trans, new_root, cow, 0);
130         kfree(new_root);
131
132         if (ret)
133                 return ret;
134
135         btrfs_mark_buffer_dirty(cow);
136         *cow_ret = cow;
137         return 0;
138 }
139
140 /*
141  * check if the tree block can be shared by multiple trees
142  */
143 int btrfs_block_can_be_shared(struct btrfs_root *root,
144                               struct extent_buffer *buf)
145 {
146         /*
147          * Tree blocks not in refernece counted trees and tree roots
148          * are never shared. If a block was allocated after the last
149          * snapshot and the block was not allocated by tree relocation,
150          * we know the block is not shared.
151          */
152         if (root->ref_cows &&
153             buf != root->node && buf != root->commit_root &&
154             (btrfs_header_generation(buf) <=
155              btrfs_root_last_snapshot(&root->root_item) ||
156              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
157                 return 1;
158 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
159         if (root->ref_cows &&
160             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
161                 return 1;
162 #endif
163         return 0;
164 }
165
166 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
167                                        struct btrfs_root *root,
168                                        struct extent_buffer *buf,
169                                        struct extent_buffer *cow)
170 {
171         u64 refs;
172         u64 owner;
173         u64 flags;
174         u64 new_flags = 0;
175         int ret;
176
177         /*
178          * Backrefs update rules:
179          *
180          * Always use full backrefs for extent pointers in tree block
181          * allocated by tree relocation.
182          *
183          * If a shared tree block is no longer referenced by its owner
184          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
185          * use full backrefs for extent pointers in tree block.
186          *
187          * If a tree block is been relocating
188          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
189          * use full backrefs for extent pointers in tree block.
190          * The reason for this is some operations (such as drop tree)
191          * are only allowed for blocks use full backrefs.
192          */
193
194         if (btrfs_block_can_be_shared(root, buf)) {
195                 ret = btrfs_lookup_extent_info(trans, root, buf->start,
196                                                btrfs_header_level(buf), 1,
197                                                &refs, &flags);
198                 BUG_ON(ret);
199                 BUG_ON(refs == 0);
200         } else {
201                 refs = 1;
202                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
203                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
204                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
205                 else
206                         flags = 0;
207         }
208
209         owner = btrfs_header_owner(buf);
210         BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
211                owner == BTRFS_TREE_RELOC_OBJECTID);
212
213         if (refs > 1) {
214                 if ((owner == root->root_key.objectid ||
215                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
216                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
217                         ret = btrfs_inc_ref(trans, root, buf, 1);
218                         BUG_ON(ret);
219
220                         if (root->root_key.objectid ==
221                             BTRFS_TREE_RELOC_OBJECTID) {
222                                 ret = btrfs_dec_ref(trans, root, buf, 0);
223                                 BUG_ON(ret);
224                                 ret = btrfs_inc_ref(trans, root, cow, 1);
225                                 BUG_ON(ret);
226                         }
227                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
228                 } else {
229
230                         if (root->root_key.objectid ==
231                             BTRFS_TREE_RELOC_OBJECTID)
232                                 ret = btrfs_inc_ref(trans, root, cow, 1);
233                         else
234                                 ret = btrfs_inc_ref(trans, root, cow, 0);
235                         BUG_ON(ret);
236                 }
237                 if (new_flags != 0) {
238                         ret = btrfs_set_block_flags(trans, root, buf->start,
239                                                     btrfs_header_level(buf),
240                                                     new_flags);
241                         BUG_ON(ret);
242                 }
243         } else {
244                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
245                         if (root->root_key.objectid ==
246                             BTRFS_TREE_RELOC_OBJECTID)
247                                 ret = btrfs_inc_ref(trans, root, cow, 1);
248                         else
249                                 ret = btrfs_inc_ref(trans, root, cow, 0);
250                         BUG_ON(ret);
251                         ret = btrfs_dec_ref(trans, root, buf, 1);
252                         BUG_ON(ret);
253                 }
254                 clean_tree_block(trans, root, buf);
255         }
256         return 0;
257 }
258
259 int __btrfs_cow_block(struct btrfs_trans_handle *trans,
260                              struct btrfs_root *root,
261                              struct extent_buffer *buf,
262                              struct extent_buffer *parent, int parent_slot,
263                              struct extent_buffer **cow_ret,
264                              u64 search_start, u64 empty_size)
265 {
266         struct extent_buffer *cow;
267         struct btrfs_disk_key disk_key;
268         int level;
269
270         WARN_ON(root->ref_cows && trans->transid !=
271                 root->fs_info->running_transaction->transid);
272         WARN_ON(root->ref_cows && trans->transid != root->last_trans);
273
274         level = btrfs_header_level(buf);
275
276         if (level == 0)
277                 btrfs_item_key(buf, &disk_key, 0);
278         else
279                 btrfs_node_key(buf, &disk_key, 0);
280
281         cow = btrfs_alloc_free_block(trans, root, buf->len,
282                                      root->root_key.objectid, &disk_key,
283                                      level, search_start, empty_size);
284         if (IS_ERR(cow))
285                 return PTR_ERR(cow);
286
287         copy_extent_buffer(cow, buf, 0, 0, cow->len);
288         btrfs_set_header_bytenr(cow, cow->start);
289         btrfs_set_header_generation(cow, trans->transid);
290         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
291         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
292                                      BTRFS_HEADER_FLAG_RELOC);
293         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
294                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
295         else
296                 btrfs_set_header_owner(cow, root->root_key.objectid);
297
298         write_extent_buffer(cow, root->fs_info->fsid,
299                             (unsigned long)btrfs_header_fsid(cow),
300                             BTRFS_FSID_SIZE);
301
302         WARN_ON(btrfs_header_generation(buf) > trans->transid);
303
304         update_ref_for_cow(trans, root, buf, cow);
305
306         if (buf == root->node) {
307                 root->node = cow;
308                 extent_buffer_get(cow);
309
310                 btrfs_free_extent(trans, root, buf->start, buf->len,
311                                   0, root->root_key.objectid, level, 0);
312                 free_extent_buffer(buf);
313                 add_root_to_dirty_list(root);
314         } else {
315                 btrfs_set_node_blockptr(parent, parent_slot,
316                                         cow->start);
317                 WARN_ON(trans->transid == 0);
318                 btrfs_set_node_ptr_generation(parent, parent_slot,
319                                               trans->transid);
320                 btrfs_mark_buffer_dirty(parent);
321                 WARN_ON(btrfs_header_generation(parent) != trans->transid);
322
323                 btrfs_free_extent(trans, root, buf->start, buf->len,
324                                   0, root->root_key.objectid, level, 1);
325         }
326         free_extent_buffer(buf);
327         btrfs_mark_buffer_dirty(cow);
328         *cow_ret = cow;
329         return 0;
330 }
331
332 static inline int should_cow_block(struct btrfs_trans_handle *trans,
333                                    struct btrfs_root *root,
334                                    struct extent_buffer *buf)
335 {
336         if (btrfs_header_generation(buf) == trans->transid &&
337             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
338             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
339               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
340                 return 0;
341         return 1;
342 }
343
344 int btrfs_cow_block(struct btrfs_trans_handle *trans,
345                     struct btrfs_root *root, struct extent_buffer *buf,
346                     struct extent_buffer *parent, int parent_slot,
347                     struct extent_buffer **cow_ret)
348 {
349         u64 search_start;
350         int ret;
351         /*
352         if (trans->transaction != root->fs_info->running_transaction) {
353                 printk(KERN_CRIT "trans %Lu running %Lu\n", trans->transid,
354                        root->fs_info->running_transaction->transid);
355                 WARN_ON(1);
356         }
357         */
358         if (trans->transid != root->fs_info->generation) {
359                 printk(KERN_CRIT "trans %llu running %llu\n",
360                         (unsigned long long)trans->transid,
361                         (unsigned long long)root->fs_info->generation);
362                 WARN_ON(1);
363         }
364         if (!should_cow_block(trans, root, buf)) {
365                 *cow_ret = buf;
366                 return 0;
367         }
368
369         search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
370         ret = __btrfs_cow_block(trans, root, buf, parent,
371                                  parent_slot, cow_ret, search_start, 0);
372         return ret;
373 }
374
375 /*
376  * compare two keys in a memcmp fashion
377  */
378 int btrfs_comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
379 {
380         struct btrfs_key k1;
381
382         btrfs_disk_key_to_cpu(&k1, disk);
383
384         if (k1.objectid > k2->objectid)
385                 return 1;
386         if (k1.objectid < k2->objectid)
387                 return -1;
388         if (k1.type > k2->type)
389                 return 1;
390         if (k1.type < k2->type)
391                 return -1;
392         if (k1.offset > k2->offset)
393                 return 1;
394         if (k1.offset < k2->offset)
395                 return -1;
396         return 0;
397 }
398
399 /*
400  * The leaf data grows from end-to-front in the node.
401  * this returns the address of the start of the last item,
402  * which is the stop of the leaf data stack
403  */
404 static inline unsigned int leaf_data_end(struct btrfs_root *root,
405                                          struct extent_buffer *leaf)
406 {
407         u32 nr = btrfs_header_nritems(leaf);
408         if (nr == 0)
409                 return BTRFS_LEAF_DATA_SIZE(root);
410         return btrfs_item_offset_nr(leaf, nr - 1);
411 }
412
413 int btrfs_check_node(struct btrfs_root *root,
414                       struct btrfs_disk_key *parent_key,
415                       struct extent_buffer *buf)
416 {
417         int i;
418         struct btrfs_key cpukey;
419         struct btrfs_disk_key key;
420         u32 nritems = btrfs_header_nritems(buf);
421
422         if (nritems == 0 || nritems > BTRFS_NODEPTRS_PER_BLOCK(root))
423                 goto fail;
424
425         if (parent_key && parent_key->type) {
426                 btrfs_node_key(buf, &key, 0);
427                 if (memcmp(parent_key, &key, sizeof(key)))
428                         goto fail;
429         }
430         for (i = 0; nritems > 1 && i < nritems - 2; i++) {
431                 btrfs_node_key(buf, &key, i);
432                 btrfs_node_key_to_cpu(buf, &cpukey, i + 1);
433                 if (btrfs_comp_keys(&key, &cpukey) >= 0)
434                         goto fail;
435         }
436         return 0;
437 fail:
438         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID) {
439                 if (parent_key)
440                         btrfs_disk_key_to_cpu(&cpukey, parent_key);
441                 else
442                         btrfs_node_key_to_cpu(buf, &cpukey, 0);
443                 btrfs_add_corrupt_extent_record(root->fs_info, &cpukey,
444                                                 buf->start, buf->len,
445                                                 btrfs_header_level(buf));
446         }
447         return -EIO;
448 }
449
450 int btrfs_check_leaf(struct btrfs_root *root,
451                       struct btrfs_disk_key *parent_key,
452                       struct extent_buffer *buf)
453 {
454         int i;
455         struct btrfs_key cpukey;
456         struct btrfs_disk_key key;
457         u32 nritems = btrfs_header_nritems(buf);
458
459         if (nritems * sizeof(struct btrfs_item) > buf->len)  {
460                 fprintf(stderr, "invalid number of items %llu\n",
461                         (unsigned long long)buf->start);
462                 goto fail;
463         }
464
465         if (btrfs_header_level(buf) != 0) {
466                 fprintf(stderr, "leaf is not a leaf %llu\n",
467                        (unsigned long long)btrfs_header_bytenr(buf));
468                 goto fail;
469         }
470         if (btrfs_leaf_free_space(root, buf) < 0) {
471                 fprintf(stderr, "leaf free space incorrect %llu %d\n",
472                         (unsigned long long)btrfs_header_bytenr(buf),
473                         btrfs_leaf_free_space(root, buf));
474                 goto fail;
475         }
476
477         if (nritems == 0)
478                 return 0;
479
480         btrfs_item_key(buf, &key, 0);
481         if (parent_key && parent_key->type &&
482             memcmp(parent_key, &key, sizeof(key))) {
483                 fprintf(stderr, "leaf parent key incorrect %llu\n",
484                        (unsigned long long)btrfs_header_bytenr(buf));
485                 goto fail;
486         }
487         for (i = 0; nritems > 1 && i < nritems - 2; i++) {
488                 btrfs_item_key(buf, &key, i);
489                 btrfs_item_key_to_cpu(buf, &cpukey, i + 1);
490                 if (btrfs_comp_keys(&key, &cpukey) >= 0) {
491                         fprintf(stderr, "bad key ordering %d %d\n", i, i+1);
492                         goto fail;
493                 }
494                 if (btrfs_item_offset_nr(buf, i) !=
495                         btrfs_item_end_nr(buf, i + 1)) {
496                         fprintf(stderr, "incorrect offsets %u %u\n",
497                                 btrfs_item_offset_nr(buf, i),
498                                 btrfs_item_end_nr(buf, i + 1));
499                         goto fail;
500                 }
501                 if (i == 0 && btrfs_item_end_nr(buf, i) !=
502                     BTRFS_LEAF_DATA_SIZE(root)) {
503                         fprintf(stderr, "bad item end %u wanted %u\n",
504                                 btrfs_item_end_nr(buf, i),
505                                 (unsigned)BTRFS_LEAF_DATA_SIZE(root));
506                         goto fail;
507                 }
508         }
509         return 0;
510 fail:
511         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID) {
512                 if (parent_key)
513                         btrfs_disk_key_to_cpu(&cpukey, parent_key);
514                 else
515                         btrfs_item_key_to_cpu(buf, &cpukey, 0);
516
517                 btrfs_add_corrupt_extent_record(root->fs_info, &cpukey,
518                                                 buf->start, buf->len, 0);
519         }
520         return -EIO;
521 }
522
523 static int noinline check_block(struct btrfs_root *root,
524                                 struct btrfs_path *path, int level)
525 {
526         struct btrfs_disk_key key;
527         struct btrfs_disk_key *key_ptr = NULL;
528         struct extent_buffer *parent;
529
530         if (path->nodes[level + 1]) {
531                 parent = path->nodes[level + 1];
532                 btrfs_node_key(parent, &key, path->slots[level + 1]);
533                 key_ptr = &key;
534         }
535         if (level == 0)
536                 return btrfs_check_leaf(root, key_ptr, path->nodes[0]);
537         return btrfs_check_node(root, key_ptr, path->nodes[level]);
538 }
539
540 /*
541  * search for key in the extent_buffer.  The items start at offset p,
542  * and they are item_size apart.  There are 'max' items in p.
543  *
544  * the slot in the array is returned via slot, and it points to
545  * the place where you would insert key if it is not found in
546  * the array.
547  *
548  * slot may point to max if the key is bigger than all of the keys
549  */
550 static int generic_bin_search(struct extent_buffer *eb, unsigned long p,
551                               int item_size, struct btrfs_key *key,
552                               int max, int *slot)
553 {
554         int low = 0;
555         int high = max;
556         int mid;
557         int ret;
558         unsigned long offset;
559         struct btrfs_disk_key *tmp;
560
561         while(low < high) {
562                 mid = (low + high) / 2;
563                 offset = p + mid * item_size;
564
565                 tmp = (struct btrfs_disk_key *)(eb->data + offset);
566                 ret = btrfs_comp_keys(tmp, key);
567
568                 if (ret < 0)
569                         low = mid + 1;
570                 else if (ret > 0)
571                         high = mid;
572                 else {
573                         *slot = mid;
574                         return 0;
575                 }
576         }
577         *slot = low;
578         return 1;
579 }
580
581 /*
582  * simple bin_search frontend that does the right thing for
583  * leaves vs nodes
584  */
585 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
586                       int level, int *slot)
587 {
588         if (level == 0)
589                 return generic_bin_search(eb,
590                                           offsetof(struct btrfs_leaf, items),
591                                           sizeof(struct btrfs_item),
592                                           key, btrfs_header_nritems(eb),
593                                           slot);
594         else
595                 return generic_bin_search(eb,
596                                           offsetof(struct btrfs_node, ptrs),
597                                           sizeof(struct btrfs_key_ptr),
598                                           key, btrfs_header_nritems(eb),
599                                           slot);
600 }
601
602 struct extent_buffer *read_node_slot(struct btrfs_root *root,
603                                    struct extent_buffer *parent, int slot)
604 {
605         int level = btrfs_header_level(parent);
606         if (slot < 0)
607                 return NULL;
608         if (slot >= btrfs_header_nritems(parent))
609                 return NULL;
610
611         if (level == 0)
612                 return NULL;
613
614         return read_tree_block(root, btrfs_node_blockptr(parent, slot),
615                        btrfs_level_size(root, level - 1),
616                        btrfs_node_ptr_generation(parent, slot));
617 }
618
619 static int balance_level(struct btrfs_trans_handle *trans,
620                          struct btrfs_root *root,
621                          struct btrfs_path *path, int level)
622 {
623         struct extent_buffer *right = NULL;
624         struct extent_buffer *mid;
625         struct extent_buffer *left = NULL;
626         struct extent_buffer *parent = NULL;
627         int ret = 0;
628         int wret;
629         int pslot;
630         int orig_slot = path->slots[level];
631         u64 orig_ptr;
632
633         if (level == 0)
634                 return 0;
635
636         mid = path->nodes[level];
637         WARN_ON(btrfs_header_generation(mid) != trans->transid);
638
639         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
640
641         if (level < BTRFS_MAX_LEVEL - 1) {
642                 parent = path->nodes[level + 1];
643                 pslot = path->slots[level + 1];
644         }
645
646         /*
647          * deal with the case where there is only one pointer in the root
648          * by promoting the node below to a root
649          */
650         if (!parent) {
651                 struct extent_buffer *child;
652
653                 if (btrfs_header_nritems(mid) != 1)
654                         return 0;
655
656                 /* promote the child to a root */
657                 child = read_node_slot(root, mid, 0);
658                 BUG_ON(!child);
659                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
660                 BUG_ON(ret);
661
662                 root->node = child;
663                 add_root_to_dirty_list(root);
664                 path->nodes[level] = NULL;
665                 clean_tree_block(trans, root, mid);
666                 wait_on_tree_block_writeback(root, mid);
667                 /* once for the path */
668                 free_extent_buffer(mid);
669
670                 ret = btrfs_free_extent(trans, root, mid->start, mid->len,
671                                         0, root->root_key.objectid,
672                                         level, 1);
673                 /* once for the root ptr */
674                 free_extent_buffer(mid);
675                 return ret;
676         }
677         if (btrfs_header_nritems(mid) >
678             BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
679                 return 0;
680
681         left = read_node_slot(root, parent, pslot - 1);
682         if (left) {
683                 wret = btrfs_cow_block(trans, root, left,
684                                        parent, pslot - 1, &left);
685                 if (wret) {
686                         ret = wret;
687                         goto enospc;
688                 }
689         }
690         right = read_node_slot(root, parent, pslot + 1);
691         if (right) {
692                 wret = btrfs_cow_block(trans, root, right,
693                                        parent, pslot + 1, &right);
694                 if (wret) {
695                         ret = wret;
696                         goto enospc;
697                 }
698         }
699
700         /* first, try to make some room in the middle buffer */
701         if (left) {
702                 orig_slot += btrfs_header_nritems(left);
703                 wret = push_node_left(trans, root, left, mid, 1);
704                 if (wret < 0)
705                         ret = wret;
706         }
707
708         /*
709          * then try to empty the right most buffer into the middle
710          */
711         if (right) {
712                 wret = push_node_left(trans, root, mid, right, 1);
713                 if (wret < 0 && wret != -ENOSPC)
714                         ret = wret;
715                 if (btrfs_header_nritems(right) == 0) {
716                         u64 bytenr = right->start;
717                         u32 blocksize = right->len;
718
719                         clean_tree_block(trans, root, right);
720                         wait_on_tree_block_writeback(root, right);
721                         free_extent_buffer(right);
722                         right = NULL;
723                         wret = btrfs_del_ptr(trans, root, path,
724                                              level + 1, pslot + 1);
725                         if (wret)
726                                 ret = wret;
727                         wret = btrfs_free_extent(trans, root, bytenr,
728                                                  blocksize, 0,
729                                                  root->root_key.objectid,
730                                                  level, 0);
731                         if (wret)
732                                 ret = wret;
733                 } else {
734                         struct btrfs_disk_key right_key;
735                         btrfs_node_key(right, &right_key, 0);
736                         btrfs_set_node_key(parent, &right_key, pslot + 1);
737                         btrfs_mark_buffer_dirty(parent);
738                 }
739         }
740         if (btrfs_header_nritems(mid) == 1) {
741                 /*
742                  * we're not allowed to leave a node with one item in the
743                  * tree during a delete.  A deletion from lower in the tree
744                  * could try to delete the only pointer in this node.
745                  * So, pull some keys from the left.
746                  * There has to be a left pointer at this point because
747                  * otherwise we would have pulled some pointers from the
748                  * right
749                  */
750                 BUG_ON(!left);
751                 wret = balance_node_right(trans, root, mid, left);
752                 if (wret < 0) {
753                         ret = wret;
754                         goto enospc;
755                 }
756                 if (wret == 1) {
757                         wret = push_node_left(trans, root, left, mid, 1);
758                         if (wret < 0)
759                                 ret = wret;
760                 }
761                 BUG_ON(wret == 1);
762         }
763         if (btrfs_header_nritems(mid) == 0) {
764                 /* we've managed to empty the middle node, drop it */
765                 u64 bytenr = mid->start;
766                 u32 blocksize = mid->len;
767                 clean_tree_block(trans, root, mid);
768                 wait_on_tree_block_writeback(root, mid);
769                 free_extent_buffer(mid);
770                 mid = NULL;
771                 wret = btrfs_del_ptr(trans, root, path, level + 1, pslot);
772                 if (wret)
773                         ret = wret;
774                 wret = btrfs_free_extent(trans, root, bytenr, blocksize,
775                                          0, root->root_key.objectid,
776                                          level, 0);
777                 if (wret)
778                         ret = wret;
779         } else {
780                 /* update the parent key to reflect our changes */
781                 struct btrfs_disk_key mid_key;
782                 btrfs_node_key(mid, &mid_key, 0);
783                 btrfs_set_node_key(parent, &mid_key, pslot);
784                 btrfs_mark_buffer_dirty(parent);
785         }
786
787         /* update the path */
788         if (left) {
789                 if (btrfs_header_nritems(left) > orig_slot) {
790                         extent_buffer_get(left);
791                         path->nodes[level] = left;
792                         path->slots[level + 1] -= 1;
793                         path->slots[level] = orig_slot;
794                         if (mid)
795                                 free_extent_buffer(mid);
796                 } else {
797                         orig_slot -= btrfs_header_nritems(left);
798                         path->slots[level] = orig_slot;
799                 }
800         }
801         /* double check we haven't messed things up */
802         check_block(root, path, level);
803         if (orig_ptr !=
804             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
805                 BUG();
806 enospc:
807         if (right)
808                 free_extent_buffer(right);
809         if (left)
810                 free_extent_buffer(left);
811         return ret;
812 }
813
814 /* returns zero if the push worked, non-zero otherwise */
815 static int noinline push_nodes_for_insert(struct btrfs_trans_handle *trans,
816                                           struct btrfs_root *root,
817                                           struct btrfs_path *path, int level)
818 {
819         struct extent_buffer *right = NULL;
820         struct extent_buffer *mid;
821         struct extent_buffer *left = NULL;
822         struct extent_buffer *parent = NULL;
823         int ret = 0;
824         int wret;
825         int pslot;
826         int orig_slot = path->slots[level];
827
828         if (level == 0)
829                 return 1;
830
831         mid = path->nodes[level];
832         WARN_ON(btrfs_header_generation(mid) != trans->transid);
833
834         if (level < BTRFS_MAX_LEVEL - 1) {
835                 parent = path->nodes[level + 1];
836                 pslot = path->slots[level + 1];
837         }
838
839         if (!parent)
840                 return 1;
841
842         left = read_node_slot(root, parent, pslot - 1);
843
844         /* first, try to make some room in the middle buffer */
845         if (left) {
846                 u32 left_nr;
847                 left_nr = btrfs_header_nritems(left);
848                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
849                         wret = 1;
850                 } else {
851                         ret = btrfs_cow_block(trans, root, left, parent,
852                                               pslot - 1, &left);
853                         if (ret)
854                                 wret = 1;
855                         else {
856                                 wret = push_node_left(trans, root,
857                                                       left, mid, 0);
858                         }
859                 }
860                 if (wret < 0)
861                         ret = wret;
862                 if (wret == 0) {
863                         struct btrfs_disk_key disk_key;
864                         orig_slot += left_nr;
865                         btrfs_node_key(mid, &disk_key, 0);
866                         btrfs_set_node_key(parent, &disk_key, pslot);
867                         btrfs_mark_buffer_dirty(parent);
868                         if (btrfs_header_nritems(left) > orig_slot) {
869                                 path->nodes[level] = left;
870                                 path->slots[level + 1] -= 1;
871                                 path->slots[level] = orig_slot;
872                                 free_extent_buffer(mid);
873                         } else {
874                                 orig_slot -=
875                                         btrfs_header_nritems(left);
876                                 path->slots[level] = orig_slot;
877                                 free_extent_buffer(left);
878                         }
879                         return 0;
880                 }
881                 free_extent_buffer(left);
882         }
883         right= read_node_slot(root, parent, pslot + 1);
884
885         /*
886          * then try to empty the right most buffer into the middle
887          */
888         if (right) {
889                 u32 right_nr;
890                 right_nr = btrfs_header_nritems(right);
891                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
892                         wret = 1;
893                 } else {
894                         ret = btrfs_cow_block(trans, root, right,
895                                               parent, pslot + 1,
896                                               &right);
897                         if (ret)
898                                 wret = 1;
899                         else {
900                                 wret = balance_node_right(trans, root,
901                                                           right, mid);
902                         }
903                 }
904                 if (wret < 0)
905                         ret = wret;
906                 if (wret == 0) {
907                         struct btrfs_disk_key disk_key;
908
909                         btrfs_node_key(right, &disk_key, 0);
910                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
911                         btrfs_mark_buffer_dirty(parent);
912
913                         if (btrfs_header_nritems(mid) <= orig_slot) {
914                                 path->nodes[level] = right;
915                                 path->slots[level + 1] += 1;
916                                 path->slots[level] = orig_slot -
917                                         btrfs_header_nritems(mid);
918                                 free_extent_buffer(mid);
919                         } else {
920                                 free_extent_buffer(right);
921                         }
922                         return 0;
923                 }
924                 free_extent_buffer(right);
925         }
926         return 1;
927 }
928
929 /*
930  * readahead one full node of leaves
931  */
932 void reada_for_search(struct btrfs_root *root, struct btrfs_path *path,
933                              int level, int slot, u64 objectid)
934 {
935         struct extent_buffer *node;
936         struct btrfs_disk_key disk_key;
937         u32 nritems;
938         u64 search;
939         u64 lowest_read;
940         u64 highest_read;
941         u64 nread = 0;
942         int direction = path->reada;
943         struct extent_buffer *eb;
944         u32 nr;
945         u32 blocksize;
946         u32 nscan = 0;
947
948         if (level != 1)
949                 return;
950
951         if (!path->nodes[level])
952                 return;
953
954         node = path->nodes[level];
955         search = btrfs_node_blockptr(node, slot);
956         blocksize = btrfs_level_size(root, level - 1);
957         eb = btrfs_find_tree_block(root, search, blocksize);
958         if (eb) {
959                 free_extent_buffer(eb);
960                 return;
961         }
962
963         highest_read = search;
964         lowest_read = search;
965
966         nritems = btrfs_header_nritems(node);
967         nr = slot;
968         while(1) {
969                 if (direction < 0) {
970                         if (nr == 0)
971                                 break;
972                         nr--;
973                 } else if (direction > 0) {
974                         nr++;
975                         if (nr >= nritems)
976                                 break;
977                 }
978                 if (path->reada < 0 && objectid) {
979                         btrfs_node_key(node, &disk_key, nr);
980                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
981                                 break;
982                 }
983                 search = btrfs_node_blockptr(node, nr);
984                 if ((search >= lowest_read && search <= highest_read) ||
985                     (search < lowest_read && lowest_read - search <= 32768) ||
986                     (search > highest_read && search - highest_read <= 32768)) {
987                         readahead_tree_block(root, search, blocksize,
988                                      btrfs_node_ptr_generation(node, nr));
989                         nread += blocksize;
990                 }
991                 nscan++;
992                 if (path->reada < 2 && (nread > (256 * 1024) || nscan > 32))
993                         break;
994                 if(nread > (1024 * 1024) || nscan > 128)
995                         break;
996
997                 if (search < lowest_read)
998                         lowest_read = search;
999                 if (search > highest_read)
1000                         highest_read = search;
1001         }
1002 }
1003
1004 /*
1005  * look for key in the tree.  path is filled in with nodes along the way
1006  * if key is found, we return zero and you can find the item in the leaf
1007  * level of the path (level 0)
1008  *
1009  * If the key isn't found, the path points to the slot where it should
1010  * be inserted, and 1 is returned.  If there are other errors during the
1011  * search a negative error number is returned.
1012  *
1013  * if ins_len > 0, nodes and leaves will be split as we walk down the
1014  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
1015  * possible)
1016  */
1017 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
1018                       *root, struct btrfs_key *key, struct btrfs_path *p, int
1019                       ins_len, int cow)
1020 {
1021         struct extent_buffer *b;
1022         int slot;
1023         int ret;
1024         int level;
1025         int should_reada = p->reada;
1026         u8 lowest_level = 0;
1027
1028         lowest_level = p->lowest_level;
1029         WARN_ON(lowest_level && ins_len > 0);
1030         WARN_ON(p->nodes[0] != NULL);
1031         /*
1032         WARN_ON(!mutex_is_locked(&root->fs_info->fs_mutex));
1033         */
1034 again:
1035         b = root->node;
1036         extent_buffer_get(b);
1037         while (b) {
1038                 level = btrfs_header_level(b);
1039                 if (cow) {
1040                         int wret;
1041                         wret = btrfs_cow_block(trans, root, b,
1042                                                p->nodes[level + 1],
1043                                                p->slots[level + 1],
1044                                                &b);
1045                         if (wret) {
1046                                 free_extent_buffer(b);
1047                                 return wret;
1048                         }
1049                 }
1050                 BUG_ON(!cow && ins_len);
1051                 if (level != btrfs_header_level(b))
1052                         WARN_ON(1);
1053                 level = btrfs_header_level(b);
1054                 p->nodes[level] = b;
1055                 ret = check_block(root, p, level);
1056                 if (ret)
1057                         return -1;
1058                 ret = bin_search(b, key, level, &slot);
1059                 if (level != 0) {
1060                         if (ret && slot > 0)
1061                                 slot -= 1;
1062                         p->slots[level] = slot;
1063                         if ((p->search_for_split || ins_len > 0) &&
1064                             btrfs_header_nritems(b) >=
1065                             BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
1066                                 int sret = split_node(trans, root, p, level);
1067                                 BUG_ON(sret > 0);
1068                                 if (sret)
1069                                         return sret;
1070                                 b = p->nodes[level];
1071                                 slot = p->slots[level];
1072                         } else if (ins_len < 0) {
1073                                 int sret = balance_level(trans, root, p,
1074                                                          level);
1075                                 if (sret)
1076                                         return sret;
1077                                 b = p->nodes[level];
1078                                 if (!b) {
1079                                         btrfs_release_path(NULL, p);
1080                                         goto again;
1081                                 }
1082                                 slot = p->slots[level];
1083                                 BUG_ON(btrfs_header_nritems(b) == 1);
1084                         }
1085                         /* this is only true while dropping a snapshot */
1086                         if (level == lowest_level)
1087                                 break;
1088
1089                         if (should_reada)
1090                                 reada_for_search(root, p, level, slot,
1091                                                  key->objectid);
1092
1093                         b = read_node_slot(root, b, slot);
1094                         if (!extent_buffer_uptodate(b))
1095                                 return -EIO;
1096                 } else {
1097                         p->slots[level] = slot;
1098                         if (ins_len > 0 &&
1099                             ins_len > btrfs_leaf_free_space(root, b)) {
1100                                 int sret = split_leaf(trans, root, key,
1101                                                       p, ins_len, ret == 0);
1102                                 BUG_ON(sret > 0);
1103                                 if (sret)
1104                                         return sret;
1105                         }
1106                         return ret;
1107                 }
1108         }
1109         return 1;
1110 }
1111
1112 /*
1113  * adjust the pointers going up the tree, starting at level
1114  * making sure the right key of each node is points to 'key'.
1115  * This is used after shifting pointers to the left, so it stops
1116  * fixing up pointers when a given leaf/node is not in slot 0 of the
1117  * higher levels
1118  *
1119  * If this fails to write a tree block, it returns -1, but continues
1120  * fixing up the blocks in ram so the tree is consistent.
1121  */
1122 static int fixup_low_keys(struct btrfs_trans_handle *trans,
1123                           struct btrfs_root *root, struct btrfs_path *path,
1124                           struct btrfs_disk_key *key, int level)
1125 {
1126         int i;
1127         int ret = 0;
1128         struct extent_buffer *t;
1129
1130         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1131                 int tslot = path->slots[i];
1132                 if (!path->nodes[i])
1133                         break;
1134                 t = path->nodes[i];
1135                 btrfs_set_node_key(t, key, tslot);
1136                 btrfs_mark_buffer_dirty(path->nodes[i]);
1137                 if (tslot != 0)
1138                         break;
1139         }
1140         return ret;
1141 }
1142
1143 /*
1144  * update item key.
1145  *
1146  * This function isn't completely safe. It's the caller's responsibility
1147  * that the new key won't break the order
1148  */
1149 int btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
1150                             struct btrfs_root *root, struct btrfs_path *path,
1151                             struct btrfs_key *new_key)
1152 {
1153         struct btrfs_disk_key disk_key;
1154         struct extent_buffer *eb;
1155         int slot;
1156
1157         eb = path->nodes[0];
1158         slot = path->slots[0];
1159         if (slot > 0) {
1160                 btrfs_item_key(eb, &disk_key, slot - 1);
1161                 if (btrfs_comp_keys(&disk_key, new_key) >= 0)
1162                         return -1;
1163         }
1164         if (slot < btrfs_header_nritems(eb) - 1) {
1165                 btrfs_item_key(eb, &disk_key, slot + 1);
1166                 if (btrfs_comp_keys(&disk_key, new_key) <= 0)
1167                         return -1;
1168         }
1169
1170         btrfs_cpu_key_to_disk(&disk_key, new_key);
1171         btrfs_set_item_key(eb, &disk_key, slot);
1172         btrfs_mark_buffer_dirty(eb);
1173         if (slot == 0)
1174                 fixup_low_keys(trans, root, path, &disk_key, 1);
1175         return 0;
1176 }
1177
1178 /*
1179  * try to push data from one node into the next node left in the
1180  * tree.
1181  *
1182  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
1183  * error, and > 0 if there was no room in the left hand block.
1184  */
1185 static int push_node_left(struct btrfs_trans_handle *trans,
1186                           struct btrfs_root *root, struct extent_buffer *dst,
1187                           struct extent_buffer *src, int empty)
1188 {
1189         int push_items = 0;
1190         int src_nritems;
1191         int dst_nritems;
1192         int ret = 0;
1193
1194         src_nritems = btrfs_header_nritems(src);
1195         dst_nritems = btrfs_header_nritems(dst);
1196         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
1197         WARN_ON(btrfs_header_generation(src) != trans->transid);
1198         WARN_ON(btrfs_header_generation(dst) != trans->transid);
1199
1200         if (!empty && src_nritems <= 8)
1201                 return 1;
1202
1203         if (push_items <= 0) {
1204                 return 1;
1205         }
1206
1207         if (empty) {
1208                 push_items = min(src_nritems, push_items);
1209                 if (push_items < src_nritems) {
1210                         /* leave at least 8 pointers in the node if
1211                          * we aren't going to empty it
1212                          */
1213                         if (src_nritems - push_items < 8) {
1214                                 if (push_items <= 8)
1215                                         return 1;
1216                                 push_items -= 8;
1217                         }
1218                 }
1219         } else
1220                 push_items = min(src_nritems - 8, push_items);
1221
1222         copy_extent_buffer(dst, src,
1223                            btrfs_node_key_ptr_offset(dst_nritems),
1224                            btrfs_node_key_ptr_offset(0),
1225                            push_items * sizeof(struct btrfs_key_ptr));
1226
1227         if (push_items < src_nritems) {
1228                 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
1229                                       btrfs_node_key_ptr_offset(push_items),
1230                                       (src_nritems - push_items) *
1231                                       sizeof(struct btrfs_key_ptr));
1232         }
1233         btrfs_set_header_nritems(src, src_nritems - push_items);
1234         btrfs_set_header_nritems(dst, dst_nritems + push_items);
1235         btrfs_mark_buffer_dirty(src);
1236         btrfs_mark_buffer_dirty(dst);
1237
1238         return ret;
1239 }
1240
1241 /*
1242  * try to push data from one node into the next node right in the
1243  * tree.
1244  *
1245  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
1246  * error, and > 0 if there was no room in the right hand block.
1247  *
1248  * this will  only push up to 1/2 the contents of the left node over
1249  */
1250 static int balance_node_right(struct btrfs_trans_handle *trans,
1251                               struct btrfs_root *root,
1252                               struct extent_buffer *dst,
1253                               struct extent_buffer *src)
1254 {
1255         int push_items = 0;
1256         int max_push;
1257         int src_nritems;
1258         int dst_nritems;
1259         int ret = 0;
1260
1261         WARN_ON(btrfs_header_generation(src) != trans->transid);
1262         WARN_ON(btrfs_header_generation(dst) != trans->transid);
1263
1264         src_nritems = btrfs_header_nritems(src);
1265         dst_nritems = btrfs_header_nritems(dst);
1266         push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
1267         if (push_items <= 0) {
1268                 return 1;
1269         }
1270
1271         if (src_nritems < 4) {
1272                 return 1;
1273         }
1274
1275         max_push = src_nritems / 2 + 1;
1276         /* don't try to empty the node */
1277         if (max_push >= src_nritems) {
1278                 return 1;
1279         }
1280
1281         if (max_push < push_items)
1282                 push_items = max_push;
1283
1284         memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
1285                                       btrfs_node_key_ptr_offset(0),
1286                                       (dst_nritems) *
1287                                       sizeof(struct btrfs_key_ptr));
1288
1289         copy_extent_buffer(dst, src,
1290                            btrfs_node_key_ptr_offset(0),
1291                            btrfs_node_key_ptr_offset(src_nritems - push_items),
1292                            push_items * sizeof(struct btrfs_key_ptr));
1293
1294         btrfs_set_header_nritems(src, src_nritems - push_items);
1295         btrfs_set_header_nritems(dst, dst_nritems + push_items);
1296
1297         btrfs_mark_buffer_dirty(src);
1298         btrfs_mark_buffer_dirty(dst);
1299
1300         return ret;
1301 }
1302
1303 /*
1304  * helper function to insert a new root level in the tree.
1305  * A new node is allocated, and a single item is inserted to
1306  * point to the existing root
1307  *
1308  * returns zero on success or < 0 on failure.
1309  */
1310 static int noinline insert_new_root(struct btrfs_trans_handle *trans,
1311                            struct btrfs_root *root,
1312                            struct btrfs_path *path, int level)
1313 {
1314         u64 lower_gen;
1315         struct extent_buffer *lower;
1316         struct extent_buffer *c;
1317         struct extent_buffer *old;
1318         struct btrfs_disk_key lower_key;
1319
1320         BUG_ON(path->nodes[level]);
1321         BUG_ON(path->nodes[level-1] != root->node);
1322
1323         lower = path->nodes[level-1];
1324         if (level == 1)
1325                 btrfs_item_key(lower, &lower_key, 0);
1326         else
1327                 btrfs_node_key(lower, &lower_key, 0);
1328
1329         c = btrfs_alloc_free_block(trans, root, root->nodesize,
1330                                    root->root_key.objectid, &lower_key, 
1331                                    level, root->node->start, 0);
1332
1333         if (IS_ERR(c))
1334                 return PTR_ERR(c);
1335
1336         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
1337         btrfs_set_header_nritems(c, 1);
1338         btrfs_set_header_level(c, level);
1339         btrfs_set_header_bytenr(c, c->start);
1340         btrfs_set_header_generation(c, trans->transid);
1341         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
1342         btrfs_set_header_owner(c, root->root_key.objectid);
1343
1344         write_extent_buffer(c, root->fs_info->fsid,
1345                             (unsigned long)btrfs_header_fsid(c),
1346                             BTRFS_FSID_SIZE);
1347
1348         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
1349                             (unsigned long)btrfs_header_chunk_tree_uuid(c),
1350                             BTRFS_UUID_SIZE);
1351
1352         btrfs_set_node_key(c, &lower_key, 0);
1353         btrfs_set_node_blockptr(c, 0, lower->start);
1354         lower_gen = btrfs_header_generation(lower);
1355         WARN_ON(lower_gen != trans->transid);
1356
1357         btrfs_set_node_ptr_generation(c, 0, lower_gen);
1358
1359         btrfs_mark_buffer_dirty(c);
1360
1361         old = root->node;
1362         root->node = c;
1363
1364         /* the super has an extra ref to root->node */
1365         free_extent_buffer(old);
1366
1367         add_root_to_dirty_list(root);
1368         extent_buffer_get(c);
1369         path->nodes[level] = c;
1370         path->slots[level] = 0;
1371         return 0;
1372 }
1373
1374 /*
1375  * worker function to insert a single pointer in a node.
1376  * the node should have enough room for the pointer already
1377  *
1378  * slot and level indicate where you want the key to go, and
1379  * blocknr is the block the key points to.
1380  *
1381  * returns zero on success and < 0 on any error
1382  */
1383 static int insert_ptr(struct btrfs_trans_handle *trans, struct btrfs_root
1384                       *root, struct btrfs_path *path, struct btrfs_disk_key
1385                       *key, u64 bytenr, int slot, int level)
1386 {
1387         struct extent_buffer *lower;
1388         int nritems;
1389
1390         BUG_ON(!path->nodes[level]);
1391         lower = path->nodes[level];
1392         nritems = btrfs_header_nritems(lower);
1393         if (slot > nritems)
1394                 BUG();
1395         if (nritems == BTRFS_NODEPTRS_PER_BLOCK(root))
1396                 BUG();
1397         if (slot != nritems) {
1398                 memmove_extent_buffer(lower,
1399                               btrfs_node_key_ptr_offset(slot + 1),
1400                               btrfs_node_key_ptr_offset(slot),
1401                               (nritems - slot) * sizeof(struct btrfs_key_ptr));
1402         }
1403         btrfs_set_node_key(lower, key, slot);
1404         btrfs_set_node_blockptr(lower, slot, bytenr);
1405         WARN_ON(trans->transid == 0);
1406         btrfs_set_node_ptr_generation(lower, slot, trans->transid);
1407         btrfs_set_header_nritems(lower, nritems + 1);
1408         btrfs_mark_buffer_dirty(lower);
1409         return 0;
1410 }
1411
1412 /*
1413  * split the node at the specified level in path in two.
1414  * The path is corrected to point to the appropriate node after the split
1415  *
1416  * Before splitting this tries to make some room in the node by pushing
1417  * left and right, if either one works, it returns right away.
1418  *
1419  * returns 0 on success and < 0 on failure
1420  */
1421 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
1422                       *root, struct btrfs_path *path, int level)
1423 {
1424         struct extent_buffer *c;
1425         struct extent_buffer *split;
1426         struct btrfs_disk_key disk_key;
1427         int mid;
1428         int ret;
1429         int wret;
1430         u32 c_nritems;
1431
1432         c = path->nodes[level];
1433         WARN_ON(btrfs_header_generation(c) != trans->transid);
1434         if (c == root->node) {
1435                 /* trying to split the root, lets make a new one */
1436                 ret = insert_new_root(trans, root, path, level + 1);
1437                 if (ret)
1438                         return ret;
1439         } else {
1440                 ret = push_nodes_for_insert(trans, root, path, level);
1441                 c = path->nodes[level];
1442                 if (!ret && btrfs_header_nritems(c) <
1443                     BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
1444                         return 0;
1445                 if (ret < 0)
1446                         return ret;
1447         }
1448
1449         c_nritems = btrfs_header_nritems(c);
1450         mid = (c_nritems + 1) / 2;
1451         btrfs_node_key(c, &disk_key, mid);
1452
1453         split = btrfs_alloc_free_block(trans, root, root->nodesize,
1454                                         root->root_key.objectid,
1455                                         &disk_key, level, c->start, 0);
1456         if (IS_ERR(split))
1457                 return PTR_ERR(split);
1458
1459         memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
1460         btrfs_set_header_level(split, btrfs_header_level(c));
1461         btrfs_set_header_bytenr(split, split->start);
1462         btrfs_set_header_generation(split, trans->transid);
1463         btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
1464         btrfs_set_header_owner(split, root->root_key.objectid);
1465         write_extent_buffer(split, root->fs_info->fsid,
1466                             (unsigned long)btrfs_header_fsid(split),
1467                             BTRFS_FSID_SIZE);
1468         write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
1469                             (unsigned long)btrfs_header_chunk_tree_uuid(split),
1470                             BTRFS_UUID_SIZE);
1471
1472
1473         copy_extent_buffer(split, c,
1474                            btrfs_node_key_ptr_offset(0),
1475                            btrfs_node_key_ptr_offset(mid),
1476                            (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
1477         btrfs_set_header_nritems(split, c_nritems - mid);
1478         btrfs_set_header_nritems(c, mid);
1479         ret = 0;
1480
1481         btrfs_mark_buffer_dirty(c);
1482         btrfs_mark_buffer_dirty(split);
1483
1484         wret = insert_ptr(trans, root, path, &disk_key, split->start,
1485                           path->slots[level + 1] + 1,
1486                           level + 1);
1487         if (wret)
1488                 ret = wret;
1489
1490         if (path->slots[level] >= mid) {
1491                 path->slots[level] -= mid;
1492                 free_extent_buffer(c);
1493                 path->nodes[level] = split;
1494                 path->slots[level + 1] += 1;
1495         } else {
1496                 free_extent_buffer(split);
1497         }
1498         return ret;
1499 }
1500
1501 /*
1502  * how many bytes are required to store the items in a leaf.  start
1503  * and nr indicate which items in the leaf to check.  This totals up the
1504  * space used both by the item structs and the item data
1505  */
1506 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
1507 {
1508         int data_len;
1509         int nritems = btrfs_header_nritems(l);
1510         int end = min(nritems, start + nr) - 1;
1511
1512         if (!nr)
1513                 return 0;
1514         data_len = btrfs_item_end_nr(l, start);
1515         data_len = data_len - btrfs_item_offset_nr(l, end);
1516         data_len += sizeof(struct btrfs_item) * nr;
1517         WARN_ON(data_len < 0);
1518         return data_len;
1519 }
1520
1521 /*
1522  * The space between the end of the leaf items and
1523  * the start of the leaf data.  IOW, how much room
1524  * the leaf has left for both items and data
1525  */
1526 int btrfs_leaf_free_space(struct btrfs_root *root, struct extent_buffer *leaf)
1527 {
1528         int nritems = btrfs_header_nritems(leaf);
1529         int ret;
1530         ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
1531         if (ret < 0) {
1532                 printk("leaf free space ret %d, leaf data size %lu, used %d nritems %d\n",
1533                        ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
1534                        leaf_space_used(leaf, 0, nritems), nritems);
1535         }
1536         return ret;
1537 }
1538
1539 /*
1540  * push some data in the path leaf to the right, trying to free up at
1541  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
1542  *
1543  * returns 1 if the push failed because the other node didn't have enough
1544  * room, 0 if everything worked out and < 0 if there were major errors.
1545  */
1546 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
1547                            *root, struct btrfs_path *path, int data_size,
1548                            int empty)
1549 {
1550         struct extent_buffer *left = path->nodes[0];
1551         struct extent_buffer *right;
1552         struct extent_buffer *upper;
1553         struct btrfs_disk_key disk_key;
1554         int slot;
1555         u32 i;
1556         int free_space;
1557         int push_space = 0;
1558         int push_items = 0;
1559         struct btrfs_item *item;
1560         u32 left_nritems;
1561         u32 nr;
1562         u32 right_nritems;
1563         u32 data_end;
1564         u32 this_item_size;
1565         int ret;
1566
1567         slot = path->slots[1];
1568         if (!path->nodes[1]) {
1569                 return 1;
1570         }
1571         upper = path->nodes[1];
1572         if (slot >= btrfs_header_nritems(upper) - 1)
1573                 return 1;
1574
1575         right = read_node_slot(root, upper, slot + 1);
1576         free_space = btrfs_leaf_free_space(root, right);
1577         if (free_space < data_size) {
1578                 free_extent_buffer(right);
1579                 return 1;
1580         }
1581
1582         /* cow and double check */
1583         ret = btrfs_cow_block(trans, root, right, upper,
1584                               slot + 1, &right);
1585         if (ret) {
1586                 free_extent_buffer(right);
1587                 return 1;
1588         }
1589         free_space = btrfs_leaf_free_space(root, right);
1590         if (free_space < data_size) {
1591                 free_extent_buffer(right);
1592                 return 1;
1593         }
1594
1595         left_nritems = btrfs_header_nritems(left);
1596         if (left_nritems == 0) {
1597                 free_extent_buffer(right);
1598                 return 1;
1599         }
1600
1601         if (empty)
1602                 nr = 0;
1603         else
1604                 nr = 1;
1605
1606         i = left_nritems - 1;
1607         while (i >= nr) {
1608                 item = btrfs_item_nr(left, i);
1609
1610                 if (path->slots[0] == i)
1611                         push_space += data_size + sizeof(*item);
1612
1613                 this_item_size = btrfs_item_size(left, item);
1614                 if (this_item_size + sizeof(*item) + push_space > free_space)
1615                         break;
1616                 push_items++;
1617                 push_space += this_item_size + sizeof(*item);
1618                 if (i == 0)
1619                         break;
1620                 i--;
1621         }
1622
1623         if (push_items == 0) {
1624                 free_extent_buffer(right);
1625                 return 1;
1626         }
1627
1628         if (!empty && push_items == left_nritems)
1629                 WARN_ON(1);
1630
1631         /* push left to right */
1632         right_nritems = btrfs_header_nritems(right);
1633
1634         push_space = btrfs_item_end_nr(left, left_nritems - push_items);
1635         push_space -= leaf_data_end(root, left);
1636
1637         /* make room in the right data area */
1638         data_end = leaf_data_end(root, right);
1639         memmove_extent_buffer(right,
1640                               btrfs_leaf_data(right) + data_end - push_space,
1641                               btrfs_leaf_data(right) + data_end,
1642                               BTRFS_LEAF_DATA_SIZE(root) - data_end);
1643
1644         /* copy from the left data area */
1645         copy_extent_buffer(right, left, btrfs_leaf_data(right) +
1646                      BTRFS_LEAF_DATA_SIZE(root) - push_space,
1647                      btrfs_leaf_data(left) + leaf_data_end(root, left),
1648                      push_space);
1649
1650         memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
1651                               btrfs_item_nr_offset(0),
1652                               right_nritems * sizeof(struct btrfs_item));
1653
1654         /* copy the items from left to right */
1655         copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
1656                    btrfs_item_nr_offset(left_nritems - push_items),
1657                    push_items * sizeof(struct btrfs_item));
1658
1659         /* update the item pointers */
1660         right_nritems += push_items;
1661         btrfs_set_header_nritems(right, right_nritems);
1662         push_space = BTRFS_LEAF_DATA_SIZE(root);
1663         for (i = 0; i < right_nritems; i++) {
1664                 item = btrfs_item_nr(right, i);
1665                 push_space -= btrfs_item_size(right, item);
1666                 btrfs_set_item_offset(right, item, push_space);
1667         }
1668
1669         left_nritems -= push_items;
1670         btrfs_set_header_nritems(left, left_nritems);
1671
1672         if (left_nritems)
1673                 btrfs_mark_buffer_dirty(left);
1674         btrfs_mark_buffer_dirty(right);
1675
1676         btrfs_item_key(right, &disk_key, 0);
1677         btrfs_set_node_key(upper, &disk_key, slot + 1);
1678         btrfs_mark_buffer_dirty(upper);
1679
1680         /* then fixup the leaf pointer in the path */
1681         if (path->slots[0] >= left_nritems) {
1682                 path->slots[0] -= left_nritems;
1683                 free_extent_buffer(path->nodes[0]);
1684                 path->nodes[0] = right;
1685                 path->slots[1] += 1;
1686         } else {
1687                 free_extent_buffer(right);
1688         }
1689         return 0;
1690 }
1691 /*
1692  * push some data in the path leaf to the left, trying to free up at
1693  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
1694  */
1695 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
1696                           *root, struct btrfs_path *path, int data_size,
1697                           int empty)
1698 {
1699         struct btrfs_disk_key disk_key;
1700         struct extent_buffer *right = path->nodes[0];
1701         struct extent_buffer *left;
1702         int slot;
1703         int i;
1704         int free_space;
1705         int push_space = 0;
1706         int push_items = 0;
1707         struct btrfs_item *item;
1708         u32 old_left_nritems;
1709         u32 right_nritems;
1710         u32 nr;
1711         int ret = 0;
1712         int wret;
1713         u32 this_item_size;
1714         u32 old_left_item_size;
1715
1716         slot = path->slots[1];
1717         if (slot == 0)
1718                 return 1;
1719         if (!path->nodes[1])
1720                 return 1;
1721
1722         right_nritems = btrfs_header_nritems(right);
1723         if (right_nritems == 0) {
1724                 return 1;
1725         }
1726
1727         left = read_node_slot(root, path->nodes[1], slot - 1);
1728         free_space = btrfs_leaf_free_space(root, left);
1729         if (free_space < data_size) {
1730                 free_extent_buffer(left);
1731                 return 1;
1732         }
1733
1734         /* cow and double check */
1735         ret = btrfs_cow_block(trans, root, left,
1736                               path->nodes[1], slot - 1, &left);
1737         if (ret) {
1738                 /* we hit -ENOSPC, but it isn't fatal here */
1739                 free_extent_buffer(left);
1740                 return 1;
1741         }
1742
1743         free_space = btrfs_leaf_free_space(root, left);
1744         if (free_space < data_size) {
1745                 free_extent_buffer(left);
1746                 return 1;
1747         }
1748
1749         if (empty)
1750                 nr = right_nritems;
1751         else
1752                 nr = right_nritems - 1;
1753
1754         for (i = 0; i < nr; i++) {
1755                 item = btrfs_item_nr(right, i);
1756
1757                 if (path->slots[0] == i)
1758                         push_space += data_size + sizeof(*item);
1759
1760                 this_item_size = btrfs_item_size(right, item);
1761                 if (this_item_size + sizeof(*item) + push_space > free_space)
1762                         break;
1763
1764                 push_items++;
1765                 push_space += this_item_size + sizeof(*item);
1766         }
1767
1768         if (push_items == 0) {
1769                 free_extent_buffer(left);
1770                 return 1;
1771         }
1772         if (!empty && push_items == btrfs_header_nritems(right))
1773                 WARN_ON(1);
1774
1775         /* push data from right to left */
1776         copy_extent_buffer(left, right,
1777                            btrfs_item_nr_offset(btrfs_header_nritems(left)),
1778                            btrfs_item_nr_offset(0),
1779                            push_items * sizeof(struct btrfs_item));
1780
1781         push_space = BTRFS_LEAF_DATA_SIZE(root) -
1782                      btrfs_item_offset_nr(right, push_items -1);
1783
1784         copy_extent_buffer(left, right, btrfs_leaf_data(left) +
1785                      leaf_data_end(root, left) - push_space,
1786                      btrfs_leaf_data(right) +
1787                      btrfs_item_offset_nr(right, push_items - 1),
1788                      push_space);
1789         old_left_nritems = btrfs_header_nritems(left);
1790         BUG_ON(old_left_nritems == 0);
1791
1792         old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
1793         for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
1794                 u32 ioff;
1795
1796                 item = btrfs_item_nr(left, i);
1797                 ioff = btrfs_item_offset(left, item);
1798                 btrfs_set_item_offset(left, item,
1799                       ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size));
1800         }
1801         btrfs_set_header_nritems(left, old_left_nritems + push_items);
1802
1803         /* fixup right node */
1804         if (push_items > right_nritems) {
1805                 printk("push items %d nr %u\n", push_items, right_nritems);
1806                 WARN_ON(1);
1807         }
1808
1809         if (push_items < right_nritems) {
1810                 push_space = btrfs_item_offset_nr(right, push_items - 1) -
1811                                                   leaf_data_end(root, right);
1812                 memmove_extent_buffer(right, btrfs_leaf_data(right) +
1813                                       BTRFS_LEAF_DATA_SIZE(root) - push_space,
1814                                       btrfs_leaf_data(right) +
1815                                       leaf_data_end(root, right), push_space);
1816
1817                 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
1818                               btrfs_item_nr_offset(push_items),
1819                              (btrfs_header_nritems(right) - push_items) *
1820                              sizeof(struct btrfs_item));
1821         }
1822         right_nritems -= push_items;
1823         btrfs_set_header_nritems(right, right_nritems);
1824         push_space = BTRFS_LEAF_DATA_SIZE(root);
1825         for (i = 0; i < right_nritems; i++) {
1826                 item = btrfs_item_nr(right, i);
1827                 push_space = push_space - btrfs_item_size(right, item);
1828                 btrfs_set_item_offset(right, item, push_space);
1829         }
1830
1831         btrfs_mark_buffer_dirty(left);
1832         if (right_nritems)
1833                 btrfs_mark_buffer_dirty(right);
1834
1835         btrfs_item_key(right, &disk_key, 0);
1836         wret = fixup_low_keys(trans, root, path, &disk_key, 1);
1837         if (wret)
1838                 ret = wret;
1839
1840         /* then fixup the leaf pointer in the path */
1841         if (path->slots[0] < push_items) {
1842                 path->slots[0] += old_left_nritems;
1843                 free_extent_buffer(path->nodes[0]);
1844                 path->nodes[0] = left;
1845                 path->slots[1] -= 1;
1846         } else {
1847                 free_extent_buffer(left);
1848                 path->slots[0] -= push_items;
1849         }
1850         BUG_ON(path->slots[0] < 0);
1851         return ret;
1852 }
1853
1854 /*
1855  * split the path's leaf in two, making sure there is at least data_size
1856  * available for the resulting leaf level of the path.
1857  *
1858  * returns 0 if all went well and < 0 on failure.
1859  */
1860 static noinline int copy_for_split(struct btrfs_trans_handle *trans,
1861                                struct btrfs_root *root,
1862                                struct btrfs_path *path,
1863                                struct extent_buffer *l,
1864                                struct extent_buffer *right,
1865                                int slot, int mid, int nritems)
1866 {
1867         int data_copy_size;
1868         int rt_data_off;
1869         int i;
1870         int ret = 0;
1871         int wret;
1872         struct btrfs_disk_key disk_key;
1873
1874         nritems = nritems - mid;
1875         btrfs_set_header_nritems(right, nritems);
1876         data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
1877
1878         copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
1879                            btrfs_item_nr_offset(mid),
1880                            nritems * sizeof(struct btrfs_item));
1881
1882         copy_extent_buffer(right, l,
1883                      btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
1884                      data_copy_size, btrfs_leaf_data(l) +
1885                      leaf_data_end(root, l), data_copy_size);
1886
1887         rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
1888                       btrfs_item_end_nr(l, mid);
1889
1890         for (i = 0; i < nritems; i++) {
1891                 struct btrfs_item *item = btrfs_item_nr(right, i);
1892                 u32 ioff = btrfs_item_offset(right, item);
1893                 btrfs_set_item_offset(right, item, ioff + rt_data_off);
1894         }
1895
1896         btrfs_set_header_nritems(l, mid);
1897         ret = 0;
1898         btrfs_item_key(right, &disk_key, 0);
1899         wret = insert_ptr(trans, root, path, &disk_key, right->start,
1900                           path->slots[1] + 1, 1);
1901         if (wret)
1902                 ret = wret;
1903
1904         btrfs_mark_buffer_dirty(right);
1905         btrfs_mark_buffer_dirty(l);
1906         BUG_ON(path->slots[0] != slot);
1907
1908         if (mid <= slot) {
1909                 free_extent_buffer(path->nodes[0]);
1910                 path->nodes[0] = right;
1911                 path->slots[0] -= mid;
1912                 path->slots[1] += 1;
1913         } else {
1914                 free_extent_buffer(right);
1915         }
1916
1917         BUG_ON(path->slots[0] < 0);
1918
1919         return ret;
1920 }
1921
1922 /*
1923  * split the path's leaf in two, making sure there is at least data_size
1924  * available for the resulting leaf level of the path.
1925  *
1926  * returns 0 if all went well and < 0 on failure.
1927  */
1928 static noinline int split_leaf(struct btrfs_trans_handle *trans,
1929                                struct btrfs_root *root,
1930                                struct btrfs_key *ins_key,
1931                                struct btrfs_path *path, int data_size,
1932                                int extend)
1933 {
1934         struct btrfs_disk_key disk_key;
1935         struct extent_buffer *l;
1936         u32 nritems;
1937         int mid;
1938         int slot;
1939         struct extent_buffer *right;
1940         int ret = 0;
1941         int wret;
1942         int split;
1943         int num_doubles = 0;
1944
1945         /* first try to make some room by pushing left and right */
1946         if (data_size && ins_key->type != BTRFS_DIR_ITEM_KEY) {
1947                 wret = push_leaf_right(trans, root, path, data_size, 0);
1948                 if (wret < 0)
1949                         return wret;
1950                 if (wret) {
1951                         wret = push_leaf_left(trans, root, path, data_size, 0);
1952                         if (wret < 0)
1953                                 return wret;
1954                 }
1955                 l = path->nodes[0];
1956
1957                 /* did the pushes work? */
1958                 if (btrfs_leaf_free_space(root, l) >= data_size)
1959                         return 0;
1960         }
1961
1962         if (!path->nodes[1]) {
1963                 ret = insert_new_root(trans, root, path, 1);
1964                 if (ret)
1965                         return ret;
1966         }
1967 again:
1968         split = 1;
1969         l = path->nodes[0];
1970         slot = path->slots[0];
1971         nritems = btrfs_header_nritems(l);
1972         mid = (nritems + 1) / 2;
1973
1974         if (mid <= slot) {
1975                 if (nritems == 1 ||
1976                     leaf_space_used(l, mid, nritems - mid) + data_size >
1977                         BTRFS_LEAF_DATA_SIZE(root)) {
1978                         if (slot >= nritems) {
1979                                 split = 0;
1980                         } else {
1981                                 mid = slot;
1982                                 if (mid != nritems &&
1983                                     leaf_space_used(l, mid, nritems - mid) +
1984                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
1985                                         split = 2;
1986                                 }
1987                         }
1988                 }
1989         } else {
1990                 if (leaf_space_used(l, 0, mid) + data_size >
1991                         BTRFS_LEAF_DATA_SIZE(root)) {
1992                         if (!extend && data_size && slot == 0) {
1993                                 split = 0;
1994                         } else if ((extend || !data_size) && slot == 0) {
1995                                 mid = 1;
1996                         } else {
1997                                 mid = slot;
1998                                 if (mid != nritems &&
1999                                     leaf_space_used(l, mid, nritems - mid) +
2000                                     data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2001                                         split = 2 ;
2002                                 }
2003                         }
2004                 }
2005         }
2006         
2007         if (split == 0)
2008                 btrfs_cpu_key_to_disk(&disk_key, ins_key);
2009         else
2010                 btrfs_item_key(l, &disk_key, mid);
2011
2012         right = btrfs_alloc_free_block(trans, root, root->leafsize,
2013                                         root->root_key.objectid,
2014                                         &disk_key, 0, l->start, 0);
2015         if (IS_ERR(right)) {
2016                 BUG_ON(1);
2017                 return PTR_ERR(right);
2018         }
2019
2020         memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
2021         btrfs_set_header_bytenr(right, right->start);
2022         btrfs_set_header_generation(right, trans->transid);
2023         btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
2024         btrfs_set_header_owner(right, root->root_key.objectid);
2025         btrfs_set_header_level(right, 0);
2026         write_extent_buffer(right, root->fs_info->fsid,
2027                             (unsigned long)btrfs_header_fsid(right),
2028                             BTRFS_FSID_SIZE);
2029
2030         write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
2031                             (unsigned long)btrfs_header_chunk_tree_uuid(right),
2032                             BTRFS_UUID_SIZE);
2033
2034         if (split == 0) {
2035                 if (mid <= slot) {
2036                         btrfs_set_header_nritems(right, 0);
2037                         wret = insert_ptr(trans, root, path,
2038                                           &disk_key, right->start,
2039                                           path->slots[1] + 1, 1);
2040                         if (wret)
2041                                 ret = wret;
2042
2043                         free_extent_buffer(path->nodes[0]);
2044                         path->nodes[0] = right;
2045                         path->slots[0] = 0;
2046                         path->slots[1] += 1;
2047                 } else {
2048                         btrfs_set_header_nritems(right, 0);
2049                         wret = insert_ptr(trans, root, path,
2050                                           &disk_key,
2051                                           right->start,
2052                                           path->slots[1], 1);
2053                         if (wret)
2054                                 ret = wret;
2055                         free_extent_buffer(path->nodes[0]);
2056                         path->nodes[0] = right;
2057                         path->slots[0] = 0;
2058                         if (path->slots[1] == 0) {
2059                                 wret = fixup_low_keys(trans, root,
2060                                                 path, &disk_key, 1);
2061                                 if (wret)
2062                                         ret = wret;
2063                         }
2064                 }
2065                 btrfs_mark_buffer_dirty(right);
2066                 return ret;
2067         }
2068
2069         ret = copy_for_split(trans, root, path, l, right, slot, mid, nritems);
2070         BUG_ON(ret);
2071
2072         if (split == 2) {
2073                 BUG_ON(num_doubles != 0);
2074                 num_doubles++;
2075                 goto again;
2076         }
2077
2078         return ret;
2079 }
2080
2081 /*
2082  * This function splits a single item into two items,
2083  * giving 'new_key' to the new item and splitting the
2084  * old one at split_offset (from the start of the item).
2085  *
2086  * The path may be released by this operation.  After
2087  * the split, the path is pointing to the old item.  The
2088  * new item is going to be in the same node as the old one.
2089  *
2090  * Note, the item being split must be smaller enough to live alone on
2091  * a tree block with room for one extra struct btrfs_item
2092  *
2093  * This allows us to split the item in place, keeping a lock on the
2094  * leaf the entire time.
2095  */
2096 int btrfs_split_item(struct btrfs_trans_handle *trans,
2097                      struct btrfs_root *root,
2098                      struct btrfs_path *path,
2099                      struct btrfs_key *new_key,
2100                      unsigned long split_offset)
2101 {
2102         u32 item_size;
2103         struct extent_buffer *leaf;
2104         struct btrfs_key orig_key;
2105         struct btrfs_item *item;
2106         struct btrfs_item *new_item;
2107         int ret = 0;
2108         int slot;
2109         u32 nritems;
2110         u32 orig_offset;
2111         struct btrfs_disk_key disk_key;
2112         char *buf;
2113
2114         leaf = path->nodes[0];
2115         btrfs_item_key_to_cpu(leaf, &orig_key, path->slots[0]);
2116         if (btrfs_leaf_free_space(root, leaf) >= sizeof(struct btrfs_item))
2117                 goto split;
2118
2119         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2120         btrfs_release_path(root, path);
2121
2122         path->search_for_split = 1;
2123
2124         ret = btrfs_search_slot(trans, root, &orig_key, path, 0, 1);
2125         path->search_for_split = 0;
2126
2127         /* if our item isn't there or got smaller, return now */
2128         if (ret != 0 || item_size != btrfs_item_size_nr(path->nodes[0],
2129                                                         path->slots[0])) {
2130                 return -EAGAIN;
2131         }
2132
2133         ret = split_leaf(trans, root, &orig_key, path, 0, 0);
2134         BUG_ON(ret);
2135
2136         BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
2137         leaf = path->nodes[0];
2138
2139 split:
2140         item = btrfs_item_nr(leaf, path->slots[0]);
2141         orig_offset = btrfs_item_offset(leaf, item);
2142         item_size = btrfs_item_size(leaf, item);
2143
2144
2145         buf = kmalloc(item_size, GFP_NOFS);
2146         read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
2147                             path->slots[0]), item_size);
2148         slot = path->slots[0] + 1;
2149         leaf = path->nodes[0];
2150
2151         nritems = btrfs_header_nritems(leaf);
2152
2153         if (slot != nritems) {
2154                 /* shift the items */
2155                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
2156                               btrfs_item_nr_offset(slot),
2157                               (nritems - slot) * sizeof(struct btrfs_item));
2158
2159         }
2160
2161         btrfs_cpu_key_to_disk(&disk_key, new_key);
2162         btrfs_set_item_key(leaf, &disk_key, slot);
2163
2164         new_item = btrfs_item_nr(leaf, slot);
2165
2166         btrfs_set_item_offset(leaf, new_item, orig_offset);
2167         btrfs_set_item_size(leaf, new_item, item_size - split_offset);
2168
2169         btrfs_set_item_offset(leaf, item,
2170                               orig_offset + item_size - split_offset);
2171         btrfs_set_item_size(leaf, item, split_offset);
2172
2173         btrfs_set_header_nritems(leaf, nritems + 1);
2174
2175         /* write the data for the start of the original item */
2176         write_extent_buffer(leaf, buf,
2177                             btrfs_item_ptr_offset(leaf, path->slots[0]),
2178                             split_offset);
2179
2180         /* write the data for the new item */
2181         write_extent_buffer(leaf, buf + split_offset,
2182                             btrfs_item_ptr_offset(leaf, slot),
2183                             item_size - split_offset);
2184         btrfs_mark_buffer_dirty(leaf);
2185
2186         ret = 0;
2187         if (btrfs_leaf_free_space(root, leaf) < 0) {
2188                 btrfs_print_leaf(root, leaf);
2189                 BUG();
2190         }
2191         kfree(buf);
2192         return ret;
2193 }
2194
2195 int btrfs_truncate_item(struct btrfs_trans_handle *trans,
2196                         struct btrfs_root *root,
2197                         struct btrfs_path *path,
2198                         u32 new_size, int from_end)
2199 {
2200         int ret = 0;
2201         int slot;
2202         struct extent_buffer *leaf;
2203         struct btrfs_item *item;
2204         u32 nritems;
2205         unsigned int data_end;
2206         unsigned int old_data_start;
2207         unsigned int old_size;
2208         unsigned int size_diff;
2209         int i;
2210
2211         leaf = path->nodes[0];
2212         slot = path->slots[0];
2213
2214         old_size = btrfs_item_size_nr(leaf, slot);
2215         if (old_size == new_size)
2216                 return 0;
2217
2218         nritems = btrfs_header_nritems(leaf);
2219         data_end = leaf_data_end(root, leaf);
2220
2221         old_data_start = btrfs_item_offset_nr(leaf, slot);
2222
2223         size_diff = old_size - new_size;
2224
2225         BUG_ON(slot < 0);
2226         BUG_ON(slot >= nritems);
2227
2228         /*
2229          * item0..itemN ... dataN.offset..dataN.size .. data0.size
2230          */
2231         /* first correct the data pointers */
2232         for (i = slot; i < nritems; i++) {
2233                 u32 ioff;
2234                 item = btrfs_item_nr(leaf, i);
2235                 ioff = btrfs_item_offset(leaf, item);
2236                 btrfs_set_item_offset(leaf, item, ioff + size_diff);
2237         }
2238
2239         /* shift the data */
2240         if (from_end) {
2241                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
2242                               data_end + size_diff, btrfs_leaf_data(leaf) +
2243                               data_end, old_data_start + new_size - data_end);
2244         } else {
2245                 struct btrfs_disk_key disk_key;
2246                 u64 offset;
2247
2248                 btrfs_item_key(leaf, &disk_key, slot);
2249
2250                 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
2251                         unsigned long ptr;
2252                         struct btrfs_file_extent_item *fi;
2253
2254                         fi = btrfs_item_ptr(leaf, slot,
2255                                             struct btrfs_file_extent_item);
2256                         fi = (struct btrfs_file_extent_item *)(
2257                              (unsigned long)fi - size_diff);
2258
2259                         if (btrfs_file_extent_type(leaf, fi) ==
2260                             BTRFS_FILE_EXTENT_INLINE) {
2261                                 ptr = btrfs_item_ptr_offset(leaf, slot);
2262                                 memmove_extent_buffer(leaf, ptr,
2263                                         (unsigned long)fi,
2264                                         offsetof(struct btrfs_file_extent_item,
2265                                                  disk_bytenr));
2266                         }
2267                 }
2268
2269                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
2270                               data_end + size_diff, btrfs_leaf_data(leaf) +
2271                               data_end, old_data_start - data_end);
2272
2273                 offset = btrfs_disk_key_offset(&disk_key);
2274                 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
2275                 btrfs_set_item_key(leaf, &disk_key, slot);
2276                 if (slot == 0)
2277                         fixup_low_keys(trans, root, path, &disk_key, 1);
2278         }
2279
2280         item = btrfs_item_nr(leaf, slot);
2281         btrfs_set_item_size(leaf, item, new_size);
2282         btrfs_mark_buffer_dirty(leaf);
2283
2284         ret = 0;
2285         if (btrfs_leaf_free_space(root, leaf) < 0) {
2286                 btrfs_print_leaf(root, leaf);
2287                 BUG();
2288         }
2289         return ret;
2290 }
2291
2292 int btrfs_extend_item(struct btrfs_trans_handle *trans,
2293                       struct btrfs_root *root, struct btrfs_path *path,
2294                       u32 data_size)
2295 {
2296         int ret = 0;
2297         int slot;
2298         struct extent_buffer *leaf;
2299         struct btrfs_item *item;
2300         u32 nritems;
2301         unsigned int data_end;
2302         unsigned int old_data;
2303         unsigned int old_size;
2304         int i;
2305
2306         leaf = path->nodes[0];
2307
2308         nritems = btrfs_header_nritems(leaf);
2309         data_end = leaf_data_end(root, leaf);
2310
2311         if (btrfs_leaf_free_space(root, leaf) < data_size) {
2312                 btrfs_print_leaf(root, leaf);
2313                 BUG();
2314         }
2315         slot = path->slots[0];
2316         old_data = btrfs_item_end_nr(leaf, slot);
2317
2318         BUG_ON(slot < 0);
2319         if (slot >= nritems) {
2320                 btrfs_print_leaf(root, leaf);
2321                 printk("slot %d too large, nritems %d\n", slot, nritems);
2322                 BUG_ON(1);
2323         }
2324
2325         /*
2326          * item0..itemN ... dataN.offset..dataN.size .. data0.size
2327          */
2328         /* first correct the data pointers */
2329         for (i = slot; i < nritems; i++) {
2330                 u32 ioff;
2331                 item = btrfs_item_nr(leaf, i);
2332                 ioff = btrfs_item_offset(leaf, item);
2333                 btrfs_set_item_offset(leaf, item, ioff - data_size);
2334         }
2335
2336         /* shift the data */
2337         memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
2338                       data_end - data_size, btrfs_leaf_data(leaf) +
2339                       data_end, old_data - data_end);
2340
2341         data_end = old_data;
2342         old_size = btrfs_item_size_nr(leaf, slot);
2343         item = btrfs_item_nr(leaf, slot);
2344         btrfs_set_item_size(leaf, item, old_size + data_size);
2345         btrfs_mark_buffer_dirty(leaf);
2346
2347         ret = 0;
2348         if (btrfs_leaf_free_space(root, leaf) < 0) {
2349                 btrfs_print_leaf(root, leaf);
2350                 BUG();
2351         }
2352         return ret;
2353 }
2354
2355 /*
2356  * Given a key and some data, insert an item into the tree.
2357  * This does all the path init required, making room in the tree if needed.
2358  */
2359 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
2360                             struct btrfs_root *root,
2361                             struct btrfs_path *path,
2362                             struct btrfs_key *cpu_key, u32 *data_size,
2363                             int nr)
2364 {
2365         struct extent_buffer *leaf;
2366         struct btrfs_item *item;
2367         int ret = 0;
2368         int slot;
2369         int i;
2370         u32 nritems;
2371         u32 total_size = 0;
2372         u32 total_data = 0;
2373         unsigned int data_end;
2374         struct btrfs_disk_key disk_key;
2375
2376         for (i = 0; i < nr; i++) {
2377                 total_data += data_size[i];
2378         }
2379
2380         /* create a root if there isn't one */
2381         if (!root->node)
2382                 BUG();
2383
2384         total_size = total_data + nr * sizeof(struct btrfs_item);
2385         ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
2386         if (ret == 0) {
2387                 return -EEXIST;
2388         }
2389         if (ret < 0)
2390                 goto out;
2391
2392         leaf = path->nodes[0];
2393
2394         nritems = btrfs_header_nritems(leaf);
2395         data_end = leaf_data_end(root, leaf);
2396
2397         if (btrfs_leaf_free_space(root, leaf) < total_size) {
2398                 btrfs_print_leaf(root, leaf);
2399                 printk("not enough freespace need %u have %d\n",
2400                        total_size, btrfs_leaf_free_space(root, leaf));
2401                 BUG();
2402         }
2403
2404         slot = path->slots[0];
2405         BUG_ON(slot < 0);
2406
2407         if (slot != nritems) {
2408                 int i;
2409                 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
2410
2411                 if (old_data < data_end) {
2412                         btrfs_print_leaf(root, leaf);
2413                         printk("slot %d old_data %d data_end %d\n",
2414                                slot, old_data, data_end);
2415                         BUG_ON(1);
2416                 }
2417                 /*
2418                  * item0..itemN ... dataN.offset..dataN.size .. data0.size
2419                  */
2420                 /* first correct the data pointers */
2421                 for (i = slot; i < nritems; i++) {
2422                         u32 ioff;
2423
2424                         item = btrfs_item_nr(leaf, i);
2425                         ioff = btrfs_item_offset(leaf, item);
2426                         btrfs_set_item_offset(leaf, item, ioff - total_data);
2427                 }
2428
2429                 /* shift the items */
2430                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
2431                               btrfs_item_nr_offset(slot),
2432                               (nritems - slot) * sizeof(struct btrfs_item));
2433
2434                 /* shift the data */
2435                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
2436                               data_end - total_data, btrfs_leaf_data(leaf) +
2437                               data_end, old_data - data_end);
2438                 data_end = old_data;
2439         }
2440
2441         /* setup the item for the new data */
2442         for (i = 0; i < nr; i++) {
2443                 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
2444                 btrfs_set_item_key(leaf, &disk_key, slot + i);
2445                 item = btrfs_item_nr(leaf, slot + i);
2446                 btrfs_set_item_offset(leaf, item, data_end - data_size[i]);
2447                 data_end -= data_size[i];
2448                 btrfs_set_item_size(leaf, item, data_size[i]);
2449         }
2450         btrfs_set_header_nritems(leaf, nritems + nr);
2451         btrfs_mark_buffer_dirty(leaf);
2452
2453         ret = 0;
2454         if (slot == 0) {
2455                 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
2456                 ret = fixup_low_keys(trans, root, path, &disk_key, 1);
2457         }
2458
2459         if (btrfs_leaf_free_space(root, leaf) < 0) {
2460                 btrfs_print_leaf(root, leaf);
2461                 BUG();
2462         }
2463
2464 out:
2465         return ret;
2466 }
2467
2468 /*
2469  * Given a key and some data, insert an item into the tree.
2470  * This does all the path init required, making room in the tree if needed.
2471  */
2472 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
2473                       *root, struct btrfs_key *cpu_key, void *data, u32
2474                       data_size)
2475 {
2476         int ret = 0;
2477         struct btrfs_path *path;
2478         struct extent_buffer *leaf;
2479         unsigned long ptr;
2480
2481         path = btrfs_alloc_path();
2482         BUG_ON(!path);
2483         ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
2484         if (!ret) {
2485                 leaf = path->nodes[0];
2486                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2487                 write_extent_buffer(leaf, data, ptr, data_size);
2488                 btrfs_mark_buffer_dirty(leaf);
2489         }
2490         btrfs_free_path(path);
2491         return ret;
2492 }
2493
2494 /*
2495  * delete the pointer from a given node.
2496  *
2497  * If the delete empties a node, the node is removed from the tree,
2498  * continuing all the way the root if required.  The root is converted into
2499  * a leaf if all the nodes are emptied.
2500  */
2501 int btrfs_del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2502                    struct btrfs_path *path, int level, int slot)
2503 {
2504         struct extent_buffer *parent = path->nodes[level];
2505         u32 nritems;
2506         int ret = 0;
2507         int wret;
2508
2509         nritems = btrfs_header_nritems(parent);
2510         if (slot != nritems -1) {
2511                 memmove_extent_buffer(parent,
2512                               btrfs_node_key_ptr_offset(slot),
2513                               btrfs_node_key_ptr_offset(slot + 1),
2514                               sizeof(struct btrfs_key_ptr) *
2515                               (nritems - slot - 1));
2516         }
2517         nritems--;
2518         btrfs_set_header_nritems(parent, nritems);
2519         if (nritems == 0 && parent == root->node) {
2520                 BUG_ON(btrfs_header_level(root->node) != 1);
2521                 /* just turn the root into a leaf and break */
2522                 btrfs_set_header_level(root->node, 0);
2523         } else if (slot == 0) {
2524                 struct btrfs_disk_key disk_key;
2525
2526                 btrfs_node_key(parent, &disk_key, 0);
2527                 wret = fixup_low_keys(trans, root, path, &disk_key, level + 1);
2528                 if (wret)
2529                         ret = wret;
2530         }
2531         btrfs_mark_buffer_dirty(parent);
2532         return ret;
2533 }
2534
2535 /*
2536  * a helper function to delete the leaf pointed to by path->slots[1] and
2537  * path->nodes[1].
2538  *
2539  * This deletes the pointer in path->nodes[1] and frees the leaf
2540  * block extent.  zero is returned if it all worked out, < 0 otherwise.
2541  *
2542  * The path must have already been setup for deleting the leaf, including
2543  * all the proper balancing.  path->nodes[1] must be locked.
2544  */
2545 static noinline int btrfs_del_leaf(struct btrfs_trans_handle *trans,
2546                                    struct btrfs_root *root,
2547                                    struct btrfs_path *path,
2548                                    struct extent_buffer *leaf)
2549 {
2550         int ret;
2551
2552         WARN_ON(btrfs_header_generation(leaf) != trans->transid);
2553         ret = btrfs_del_ptr(trans, root, path, 1, path->slots[1]);
2554         if (ret)
2555                 return ret;
2556
2557         ret = btrfs_free_extent(trans, root, leaf->start, leaf->len,
2558                                 0, root->root_key.objectid, 0, 0);
2559         return ret;
2560 }
2561
2562 /*
2563  * delete the item at the leaf level in path.  If that empties
2564  * the leaf, remove it from the tree
2565  */
2566 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2567                     struct btrfs_path *path, int slot, int nr)
2568 {
2569         struct extent_buffer *leaf;
2570         struct btrfs_item *item;
2571         int last_off;
2572         int dsize = 0;
2573         int ret = 0;
2574         int wret;
2575         int i;
2576         u32 nritems;
2577
2578         leaf = path->nodes[0];
2579         last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
2580
2581         for (i = 0; i < nr; i++)
2582                 dsize += btrfs_item_size_nr(leaf, slot + i);
2583
2584         nritems = btrfs_header_nritems(leaf);
2585
2586         if (slot + nr != nritems) {
2587                 int i;
2588                 int data_end = leaf_data_end(root, leaf);
2589
2590                 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
2591                               data_end + dsize,
2592                               btrfs_leaf_data(leaf) + data_end,
2593                               last_off - data_end);
2594
2595                 for (i = slot + nr; i < nritems; i++) {
2596                         u32 ioff;
2597
2598                         item = btrfs_item_nr(leaf, i);
2599                         ioff = btrfs_item_offset(leaf, item);
2600                         btrfs_set_item_offset(leaf, item, ioff + dsize);
2601                 }
2602
2603                 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
2604                               btrfs_item_nr_offset(slot + nr),
2605                               sizeof(struct btrfs_item) *
2606                               (nritems - slot - nr));
2607         }
2608         btrfs_set_header_nritems(leaf, nritems - nr);
2609         nritems -= nr;
2610
2611         /* delete the leaf if we've emptied it */
2612         if (nritems == 0) {
2613                 if (leaf == root->node) {
2614                         btrfs_set_header_level(leaf, 0);
2615                 } else {
2616                         clean_tree_block(trans, root, leaf);
2617                         wait_on_tree_block_writeback(root, leaf);
2618
2619                         wret = btrfs_del_leaf(trans, root, path, leaf);
2620                         BUG_ON(ret);
2621                         if (wret)
2622                                 ret = wret;
2623                 }
2624         } else {
2625                 int used = leaf_space_used(leaf, 0, nritems);
2626                 if (slot == 0) {
2627                         struct btrfs_disk_key disk_key;
2628
2629                         btrfs_item_key(leaf, &disk_key, 0);
2630                         wret = fixup_low_keys(trans, root, path,
2631                                               &disk_key, 1);
2632                         if (wret)
2633                                 ret = wret;
2634                 }
2635
2636                 /* delete the leaf if it is mostly empty */
2637                 if (used < BTRFS_LEAF_DATA_SIZE(root) / 4) {
2638                         /* push_leaf_left fixes the path.
2639                          * make sure the path still points to our leaf
2640                          * for possible call to del_ptr below
2641                          */
2642                         slot = path->slots[1];
2643                         extent_buffer_get(leaf);
2644
2645                         wret = push_leaf_left(trans, root, path, 1, 1);
2646                         if (wret < 0 && wret != -ENOSPC)
2647                                 ret = wret;
2648
2649                         if (path->nodes[0] == leaf &&
2650                             btrfs_header_nritems(leaf)) {
2651                                 wret = push_leaf_right(trans, root, path, 1, 1);
2652                                 if (wret < 0 && wret != -ENOSPC)
2653                                         ret = wret;
2654                         }
2655
2656                         if (btrfs_header_nritems(leaf) == 0) {
2657                                 clean_tree_block(trans, root, leaf);
2658                                 wait_on_tree_block_writeback(root, leaf);
2659
2660                                 path->slots[1] = slot;
2661                                 ret = btrfs_del_leaf(trans, root, path, leaf);
2662                                 BUG_ON(ret);
2663                                 free_extent_buffer(leaf);
2664
2665                         } else {
2666                                 btrfs_mark_buffer_dirty(leaf);
2667                                 free_extent_buffer(leaf);
2668                         }
2669                 } else {
2670                         btrfs_mark_buffer_dirty(leaf);
2671                 }
2672         }
2673         return ret;
2674 }
2675
2676 /*
2677  * walk up the tree as far as required to find the previous leaf.
2678  * returns 0 if it found something or 1 if there are no lesser leaves.
2679  * returns < 0 on io errors.
2680  */
2681 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2682 {
2683         int slot;
2684         int level = 1;
2685         struct extent_buffer *c;
2686         struct extent_buffer *next = NULL;
2687
2688         while(level < BTRFS_MAX_LEVEL) {
2689                 if (!path->nodes[level])
2690                         return 1;
2691
2692                 slot = path->slots[level];
2693                 c = path->nodes[level];
2694                 if (slot == 0) {
2695                         level++;
2696                         if (level == BTRFS_MAX_LEVEL)
2697                                 return 1;
2698                         continue;
2699                 }
2700                 slot--;
2701
2702                 next = read_node_slot(root, c, slot);
2703                 break;
2704         }
2705         path->slots[level] = slot;
2706         while(1) {
2707                 level--;
2708                 c = path->nodes[level];
2709                 free_extent_buffer(c);
2710                 slot = btrfs_header_nritems(next);
2711                 if (slot != 0)
2712                         slot--;
2713                 path->nodes[level] = next;
2714                 path->slots[level] = slot;
2715                 if (!level)
2716                         break;
2717                 next = read_node_slot(root, next, slot);
2718         }
2719         return 0;
2720 }
2721
2722 /*
2723  * walk up the tree as far as required to find the next leaf.
2724  * returns 0 if it found something or 1 if there are no greater leaves.
2725  * returns < 0 on io errors.
2726  */
2727 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
2728 {
2729         int slot;
2730         int level = 1;
2731         struct extent_buffer *c;
2732         struct extent_buffer *next = NULL;
2733
2734         while(level < BTRFS_MAX_LEVEL) {
2735                 if (!path->nodes[level])
2736                         return 1;
2737
2738                 slot = path->slots[level] + 1;
2739                 c = path->nodes[level];
2740                 if (slot >= btrfs_header_nritems(c)) {
2741                         level++;
2742                         if (level == BTRFS_MAX_LEVEL)
2743                                 return 1;
2744                         continue;
2745                 }
2746
2747                 if (path->reada)
2748                         reada_for_search(root, path, level, slot, 0);
2749
2750                 next = read_node_slot(root, c, slot);
2751                 if (!next)
2752                         return -EIO;
2753                 break;
2754         }
2755         path->slots[level] = slot;
2756         while(1) {
2757                 level--;
2758                 c = path->nodes[level];
2759                 free_extent_buffer(c);
2760                 path->nodes[level] = next;
2761                 path->slots[level] = 0;
2762                 if (!level)
2763                         break;
2764                 if (path->reada)
2765                         reada_for_search(root, path, level, 0, 0);
2766                 next = read_node_slot(root, next, 0);
2767                 if (!next)
2768                         return -EIO;
2769         }
2770         return 0;
2771 }
2772
2773 int btrfs_previous_item(struct btrfs_root *root,
2774                         struct btrfs_path *path, u64 min_objectid,
2775                         int type)
2776 {
2777         struct btrfs_key found_key;
2778         struct extent_buffer *leaf;
2779         int ret;
2780
2781         while(1) {
2782                 if (path->slots[0] == 0) {
2783                         ret = btrfs_prev_leaf(root, path);
2784                         if (ret != 0)
2785                                 return ret;
2786                 } else {
2787                         path->slots[0]--;
2788                 }
2789                 leaf = path->nodes[0];
2790                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2791                 if (found_key.type == type)
2792                         return 0;
2793         }
2794         return 1;
2795 }
2796