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