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