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