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