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