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