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