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