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