Add basic RAID[56] support
[platform/upstream/btrfs-progs.git] / extent-tree.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 <stdio.h>
20 #include <stdlib.h>
21 #include "kerncompat.h"
22 #include "radix-tree.h"
23 #include "ctree.h"
24 #include "disk-io.h"
25 #include "print-tree.h"
26 #include "transaction.h"
27 #include "crc32c.h"
28 #include "volumes.h"
29
30 #define BLOCK_GROUP_DATA     EXTENT_WRITEBACK
31 #define BLOCK_GROUP_METADATA EXTENT_UPTODATE
32 #define BLOCK_GROUP_SYSTEM   EXTENT_NEW
33
34 #define BLOCK_GROUP_DIRTY EXTENT_DIRTY
35
36 #define PENDING_EXTENT_INSERT 0
37 #define PENDING_EXTENT_DELETE 1
38 #define PENDING_BACKREF_UPDATE 2
39
40 struct pending_extent_op {
41         int type;
42         u64 bytenr;
43         u64 num_bytes;
44         u64 flags;
45         struct btrfs_disk_key key;
46         int level;
47 };
48
49 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
50                                      struct btrfs_root *root,
51                                      u64 root_objectid, u64 generation,
52                                      u64 flags, struct btrfs_disk_key *key,
53                                      int level, struct btrfs_key *ins);
54 static int __free_extent(struct btrfs_trans_handle *trans,
55                          struct btrfs_root *root,
56                          u64 bytenr, u64 num_bytes, u64 parent,
57                          u64 root_objectid, u64 owner_objectid,
58                          u64 owner_offset, int refs_to_drop);
59 static int finish_current_insert(struct btrfs_trans_handle *trans, struct
60                                  btrfs_root *extent_root);
61 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
62                                btrfs_root *extent_root);
63
64 static int remove_sb_from_cache(struct btrfs_root *root,
65                                 struct btrfs_block_group_cache *cache)
66 {
67         u64 bytenr;
68         u64 *logical;
69         int stripe_len;
70         int i, nr, ret;
71         struct extent_io_tree *free_space_cache;
72
73         free_space_cache = &root->fs_info->free_space_cache;
74         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
75                 bytenr = btrfs_sb_offset(i);
76                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
77                                        cache->key.objectid, bytenr, 0,
78                                        &logical, &nr, &stripe_len);
79                 BUG_ON(ret);
80                 while (nr--) {
81                         clear_extent_dirty(free_space_cache, logical[nr],
82                                 logical[nr] + stripe_len - 1, GFP_NOFS);
83                 }
84                 kfree(logical);
85         }
86         return 0;
87 }
88
89 static int cache_block_group(struct btrfs_root *root,
90                              struct btrfs_block_group_cache *block_group)
91 {
92         struct btrfs_path *path;
93         int ret;
94         struct btrfs_key key;
95         struct extent_buffer *leaf;
96         struct extent_io_tree *free_space_cache;
97         int slot;
98         u64 last;
99         u64 hole_size;
100
101         if (!block_group)
102                 return 0;
103
104         root = root->fs_info->extent_root;
105         free_space_cache = &root->fs_info->free_space_cache;
106
107         if (block_group->cached)
108                 return 0;
109
110         path = btrfs_alloc_path();
111         if (!path)
112                 return -ENOMEM;
113
114         path->reada = 2;
115         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
116         key.objectid = last;
117         key.offset = 0;
118         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
119         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
120         if (ret < 0)
121                 goto err;
122
123         while(1) {
124                 leaf = path->nodes[0];
125                 slot = path->slots[0];
126                 if (slot >= btrfs_header_nritems(leaf)) {
127                         ret = btrfs_next_leaf(root, path);
128                         if (ret < 0)
129                                 goto err;
130                         if (ret == 0) {
131                                 continue;
132                         } else {
133                                 break;
134                         }
135                 }
136                 btrfs_item_key_to_cpu(leaf, &key, slot);
137                 if (key.objectid < block_group->key.objectid) {
138                         goto next;
139                 }
140                 if (key.objectid >= block_group->key.objectid +
141                     block_group->key.offset) {
142                         break;
143                 }
144
145                 if (btrfs_key_type(&key) == BTRFS_EXTENT_ITEM_KEY) {
146                         if (key.objectid > last) {
147                                 hole_size = key.objectid - last;
148                                 set_extent_dirty(free_space_cache, last,
149                                                  last + hole_size - 1,
150                                                  GFP_NOFS);
151                         }
152                         last = key.objectid + key.offset;
153                 }
154 next:
155                 path->slots[0]++;
156         }
157
158         if (block_group->key.objectid +
159             block_group->key.offset > last) {
160                 hole_size = block_group->key.objectid +
161                         block_group->key.offset - last;
162                 set_extent_dirty(free_space_cache, last,
163                                  last + hole_size - 1, GFP_NOFS);
164         }
165         remove_sb_from_cache(root, block_group);
166         block_group->cached = 1;
167 err:
168         btrfs_free_path(path);
169         return 0;
170 }
171
172 struct btrfs_block_group_cache *btrfs_lookup_first_block_group(struct
173                                                        btrfs_fs_info *info,
174                                                        u64 bytenr)
175 {
176         struct extent_io_tree *block_group_cache;
177         struct btrfs_block_group_cache *block_group = NULL;
178         u64 ptr;
179         u64 start;
180         u64 end;
181         int ret;
182
183         bytenr = max_t(u64, bytenr,
184                        BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE);
185         block_group_cache = &info->block_group_cache;
186         ret = find_first_extent_bit(block_group_cache,
187                                     bytenr, &start, &end,
188                                     BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA |
189                                     BLOCK_GROUP_SYSTEM);
190         if (ret) {
191                 return NULL;
192         }
193         ret = get_state_private(block_group_cache, start, &ptr);
194         if (ret)
195                 return NULL;
196
197         block_group = (struct btrfs_block_group_cache *)(unsigned long)ptr;
198         return block_group;
199 }
200
201 struct btrfs_block_group_cache *btrfs_lookup_block_group(struct
202                                                          btrfs_fs_info *info,
203                                                          u64 bytenr)
204 {
205         struct extent_io_tree *block_group_cache;
206         struct btrfs_block_group_cache *block_group = NULL;
207         u64 ptr;
208         u64 start;
209         u64 end;
210         int ret;
211
212         block_group_cache = &info->block_group_cache;
213         ret = find_first_extent_bit(block_group_cache,
214                                     bytenr, &start, &end,
215                                     BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA |
216                                     BLOCK_GROUP_SYSTEM);
217         if (ret) {
218                 return NULL;
219         }
220         ret = get_state_private(block_group_cache, start, &ptr);
221         if (ret)
222                 return NULL;
223
224         block_group = (struct btrfs_block_group_cache *)(unsigned long)ptr;
225         if (block_group->key.objectid <= bytenr && bytenr <
226             block_group->key.objectid + block_group->key.offset)
227                 return block_group;
228         return NULL;
229 }
230
231 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
232 {
233         return (cache->flags & bits) == bits;
234 }
235
236 static int noinline find_search_start(struct btrfs_root *root,
237                               struct btrfs_block_group_cache **cache_ret,
238                               u64 *start_ret, int num, int data)
239 {
240         int ret;
241         struct btrfs_block_group_cache *cache = *cache_ret;
242         u64 last;
243         u64 start = 0;
244         u64 end = 0;
245         u64 search_start = *start_ret;
246         int wrapped = 0;
247
248         if (!cache) {
249                 goto out;
250         }
251 again:
252         ret = cache_block_group(root, cache);
253         if (ret)
254                 goto out;
255
256         last = max(search_start, cache->key.objectid);
257         if (cache->ro || !block_group_bits(cache, data)) {
258                 goto new_group;
259         }
260
261         while(1) {
262                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
263                                             last, &start, &end, EXTENT_DIRTY);
264                 if (ret) {
265                         goto new_group;
266                 }
267
268                 start = max(last, start);
269                 last = end + 1;
270                 if (last - start < num) {
271                         continue;
272                 }
273                 if (start + num > cache->key.objectid + cache->key.offset) {
274                         goto new_group;
275                 }
276                 *start_ret = start;
277                 return 0;
278         }
279 out:
280         cache = btrfs_lookup_block_group(root->fs_info, search_start);
281         if (!cache) {
282                 printk("Unable to find block group for %llu\n",
283                         (unsigned long long)search_start);
284                 WARN_ON(1);
285         }
286         return -ENOSPC;
287
288 new_group:
289         last = cache->key.objectid + cache->key.offset;
290 wrapped:
291         cache = btrfs_lookup_first_block_group(root->fs_info, last);
292         if (!cache) {
293 no_cache:
294                 if (!wrapped) {
295                         wrapped = 1;
296                         last = search_start;
297                         goto wrapped;
298                 }
299                 goto out;
300         }
301         cache = btrfs_find_block_group(root, cache, last, data, 0);
302         cache = btrfs_find_block_group(root, cache, last, data, 0);
303         if (!cache)
304                 goto no_cache;
305
306         *cache_ret = cache;
307         goto again;
308 }
309
310 static u64 div_factor(u64 num, int factor)
311 {
312         if (factor == 10)
313                 return num;
314         num *= factor;
315         num /= 10;
316         return num;
317 }
318
319 static int block_group_state_bits(u64 flags)
320 {
321         int bits = 0;
322         if (flags & BTRFS_BLOCK_GROUP_DATA)
323                 bits |= BLOCK_GROUP_DATA;
324         if (flags & BTRFS_BLOCK_GROUP_METADATA)
325                 bits |= BLOCK_GROUP_METADATA;
326         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
327                 bits |= BLOCK_GROUP_SYSTEM;
328         return bits;
329 }
330
331 struct btrfs_block_group_cache *btrfs_find_block_group(struct btrfs_root *root,
332                                                  struct btrfs_block_group_cache
333                                                  *hint, u64 search_start,
334                                                  int data, int owner)
335 {
336         struct btrfs_block_group_cache *cache;
337         struct extent_io_tree *block_group_cache;
338         struct btrfs_block_group_cache *found_group = NULL;
339         struct btrfs_fs_info *info = root->fs_info;
340         u64 used;
341         u64 last = 0;
342         u64 hint_last;
343         u64 start;
344         u64 end;
345         u64 free_check;
346         u64 ptr;
347         int bit;
348         int ret;
349         int full_search = 0;
350         int factor = 10;
351
352         block_group_cache = &info->block_group_cache;
353
354         if (!owner)
355                 factor = 10;
356
357         bit = block_group_state_bits(data);
358
359         if (search_start) {
360                 struct btrfs_block_group_cache *shint;
361                 shint = btrfs_lookup_block_group(info, search_start);
362                 if (shint && !shint->ro && block_group_bits(shint, data)) {
363                         used = btrfs_block_group_used(&shint->item);
364                         if (used + shint->pinned <
365                             div_factor(shint->key.offset, factor)) {
366                                 return shint;
367                         }
368                 }
369         }
370         if (hint && !hint->ro && block_group_bits(hint, data)) {
371                 used = btrfs_block_group_used(&hint->item);
372                 if (used + hint->pinned <
373                     div_factor(hint->key.offset, factor)) {
374                         return hint;
375                 }
376                 last = hint->key.objectid + hint->key.offset;
377                 hint_last = last;
378         } else {
379                 if (hint)
380                         hint_last = max(hint->key.objectid, search_start);
381                 else
382                         hint_last = search_start;
383
384                 last = hint_last;
385         }
386 again:
387         while(1) {
388                 ret = find_first_extent_bit(block_group_cache, last,
389                                             &start, &end, bit);
390                 if (ret)
391                         break;
392
393                 ret = get_state_private(block_group_cache, start, &ptr);
394                 if (ret)
395                         break;
396
397                 cache = (struct btrfs_block_group_cache *)(unsigned long)ptr;
398                 last = cache->key.objectid + cache->key.offset;
399                 used = btrfs_block_group_used(&cache->item);
400
401                 if (!cache->ro && block_group_bits(cache, data)) {
402                         if (full_search)
403                                 free_check = cache->key.offset;
404                         else
405                                 free_check = div_factor(cache->key.offset,
406                                                         factor);
407
408                         if (used + cache->pinned < free_check) {
409                                 found_group = cache;
410                                 goto found;
411                         }
412                 }
413                 cond_resched();
414         }
415         if (!full_search) {
416                 last = search_start;
417                 full_search = 1;
418                 goto again;
419         }
420 found:
421         return found_group;
422 }
423
424 /*
425  * Back reference rules.  Back refs have three main goals:
426  *
427  * 1) differentiate between all holders of references to an extent so that
428  *    when a reference is dropped we can make sure it was a valid reference
429  *    before freeing the extent.
430  *
431  * 2) Provide enough information to quickly find the holders of an extent
432  *    if we notice a given block is corrupted or bad.
433  *
434  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
435  *    maintenance.  This is actually the same as #2, but with a slightly
436  *    different use case.
437  *
438  * There are two kinds of back refs. The implicit back refs is optimized
439  * for pointers in non-shared tree blocks. For a given pointer in a block,
440  * back refs of this kind provide information about the block's owner tree
441  * and the pointer's key. These information allow us to find the block by
442  * b-tree searching. The full back refs is for pointers in tree blocks not
443  * referenced by their owner trees. The location of tree block is recorded
444  * in the back refs. Actually the full back refs is generic, and can be
445  * used in all cases the implicit back refs is used. The major shortcoming
446  * of the full back refs is its overhead. Every time a tree block gets
447  * COWed, we have to update back refs entry for all pointers in it.
448  *
449  * For a newly allocated tree block, we use implicit back refs for
450  * pointers in it. This means most tree related operations only involve
451  * implicit back refs. For a tree block created in old transaction, the
452  * only way to drop a reference to it is COW it. So we can detect the
453  * event that tree block loses its owner tree's reference and do the
454  * back refs conversion.
455  *
456  * When a tree block is COW'd through a tree, there are four cases:
457  *
458  * The reference count of the block is one and the tree is the block's
459  * owner tree. Nothing to do in this case.
460  *
461  * The reference count of the block is one and the tree is not the
462  * block's owner tree. In this case, full back refs is used for pointers
463  * in the block. Remove these full back refs, add implicit back refs for
464  * every pointers in the new block.
465  *
466  * The reference count of the block is greater than one and the tree is
467  * the block's owner tree. In this case, implicit back refs is used for
468  * pointers in the block. Add full back refs for every pointers in the
469  * block, increase lower level extents' reference counts. The original
470  * implicit back refs are entailed to the new block.
471  *
472  * The reference count of the block is greater than one and the tree is
473  * not the block's owner tree. Add implicit back refs for every pointer in
474  * the new block, increase lower level extents' reference count.
475  *
476  * Back Reference Key composing:
477  *
478  * The key objectid corresponds to the first byte in the extent,
479  * The key type is used to differentiate between types of back refs.
480  * There are different meanings of the key offset for different types
481  * of back refs.
482  *
483  * File extents can be referenced by:
484  *
485  * - multiple snapshots, subvolumes, or different generations in one subvol
486  * - different files inside a single subvolume
487  * - different offsets inside a file (bookend extents in file.c)
488  *
489  * The extent ref structure for the implicit back refs has fields for:
490  *
491  * - Objectid of the subvolume root
492  * - objectid of the file holding the reference
493  * - original offset in the file
494  * - how many bookend extents
495  *
496  * The key offset for the implicit back refs is hash of the first
497  * three fields.
498  *
499  * The extent ref structure for the full back refs has field for:
500  *
501  * - number of pointers in the tree leaf
502  *
503  * The key offset for the implicit back refs is the first byte of
504  * the tree leaf
505  *
506  * When a file extent is allocated, The implicit back refs is used.
507  * the fields are filled in:
508  *
509  *     (root_key.objectid, inode objectid, offset in file, 1)
510  *
511  * When a file extent is removed file truncation, we find the
512  * corresponding implicit back refs and check the following fields:
513  *
514  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
515  *
516  * Btree extents can be referenced by:
517  *
518  * - Different subvolumes
519  *
520  * Both the implicit back refs and the full back refs for tree blocks
521  * only consist of key. The key offset for the implicit back refs is
522  * objectid of block's owner tree. The key offset for the full back refs
523  * is the first byte of parent block.
524  *
525  * When implicit back refs is used, information about the lowest key and
526  * level of the tree block are required. These information are stored in
527  * tree block info structure.
528  */
529
530 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
531 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
532                                   struct btrfs_root *root,
533                                   struct btrfs_path *path,
534                                   u64 owner, u32 extra_size)
535 {
536         struct btrfs_extent_item *item;
537         struct btrfs_extent_item_v0 *ei0;
538         struct btrfs_extent_ref_v0 *ref0;
539         struct btrfs_tree_block_info *bi;
540         struct extent_buffer *leaf;
541         struct btrfs_key key;
542         struct btrfs_key found_key;
543         u32 new_size = sizeof(*item);
544         u64 refs;
545         int ret;
546
547         leaf = path->nodes[0];
548         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
549
550         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
551         ei0 = btrfs_item_ptr(leaf, path->slots[0],
552                              struct btrfs_extent_item_v0);
553         refs = btrfs_extent_refs_v0(leaf, ei0);
554
555         if (owner == (u64)-1) {
556                 while (1) {
557                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
558                                 ret = btrfs_next_leaf(root, path);
559                                 if (ret < 0)
560                                         return ret;
561                                 BUG_ON(ret > 0);
562                                 leaf = path->nodes[0];
563                         }
564                         btrfs_item_key_to_cpu(leaf, &found_key,
565                                               path->slots[0]);
566                         BUG_ON(key.objectid != found_key.objectid);
567                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
568                                 path->slots[0]++;
569                                 continue;
570                         }
571                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
572                                               struct btrfs_extent_ref_v0);
573                         owner = btrfs_ref_objectid_v0(leaf, ref0);
574                         break;
575                 }
576         }
577         btrfs_release_path(root, path);
578
579         if (owner < BTRFS_FIRST_FREE_OBJECTID)
580                 new_size += sizeof(*bi);
581
582         new_size -= sizeof(*ei0);
583         ret = btrfs_search_slot(trans, root, &key, path, new_size, 1);
584         if (ret < 0)
585                 return ret;
586         BUG_ON(ret);
587
588         ret = btrfs_extend_item(trans, root, path, new_size);
589         BUG_ON(ret);
590
591         leaf = path->nodes[0];
592         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
593         btrfs_set_extent_refs(leaf, item, refs);
594         /* FIXME: get real generation */
595         btrfs_set_extent_generation(leaf, item, 0);
596         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
597                 btrfs_set_extent_flags(leaf, item,
598                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
599                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
600                 bi = (struct btrfs_tree_block_info *)(item + 1);
601                 /* FIXME: get first key of the block */
602                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
603                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
604         } else {
605                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
606         }
607         btrfs_mark_buffer_dirty(leaf);
608         return 0;
609 }
610 #endif
611
612 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
613 {
614         u32 high_crc = ~(u32)0;
615         u32 low_crc = ~(u32)0;
616         __le64 lenum;
617
618         lenum = cpu_to_le64(root_objectid);
619         high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
620         lenum = cpu_to_le64(owner);
621         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
622         lenum = cpu_to_le64(offset);
623         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
624
625         return ((u64)high_crc << 31) ^ (u64)low_crc;
626 }
627
628 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
629                                      struct btrfs_extent_data_ref *ref)
630 {
631         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
632                                     btrfs_extent_data_ref_objectid(leaf, ref),
633                                     btrfs_extent_data_ref_offset(leaf, ref));
634 }
635
636 static int match_extent_data_ref(struct extent_buffer *leaf,
637                                  struct btrfs_extent_data_ref *ref,
638                                  u64 root_objectid, u64 owner, u64 offset)
639 {
640         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
641             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
642             btrfs_extent_data_ref_offset(leaf, ref) != offset)
643                 return 0;
644         return 1;
645 }
646
647 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
648                                            struct btrfs_root *root,
649                                            struct btrfs_path *path,
650                                            u64 bytenr, u64 parent,
651                                            u64 root_objectid,
652                                            u64 owner, u64 offset)
653 {
654         struct btrfs_key key;
655         struct btrfs_extent_data_ref *ref;
656         struct extent_buffer *leaf;
657         u32 nritems;
658         int ret;
659         int recow;
660         int err = -ENOENT;
661
662         key.objectid = bytenr;
663         if (parent) {
664                 key.type = BTRFS_SHARED_DATA_REF_KEY;
665                 key.offset = parent;
666         } else {
667                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
668                 key.offset = hash_extent_data_ref(root_objectid,
669                                                   owner, offset);
670         }
671 again:
672         recow = 0;
673         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
674         if (ret < 0) {
675                 err = ret;
676                 goto fail;
677         }
678
679         if (parent) {
680                 if (!ret)
681                         return 0;
682 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
683                 key.type = BTRFS_EXTENT_REF_V0_KEY;
684                 btrfs_release_path(root, path);
685                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
686                 if (ret < 0) {
687                         err = ret;
688                         goto fail;
689                 }
690                 if (!ret)
691                         return 0;
692 #endif
693                 goto fail;
694         }
695
696         leaf = path->nodes[0];
697         nritems = btrfs_header_nritems(leaf);
698         while (1) {
699                 if (path->slots[0] >= nritems) {
700                         ret = btrfs_next_leaf(root, path);
701                         if (ret < 0)
702                                 err = ret;
703                         if (ret)
704                                 goto fail;
705
706                         leaf = path->nodes[0];
707                         nritems = btrfs_header_nritems(leaf);
708                         recow = 1;
709                 }
710
711                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
712                 if (key.objectid != bytenr ||
713                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
714                         goto fail;
715                 
716                 ref = btrfs_item_ptr(leaf, path->slots[0],
717                                      struct btrfs_extent_data_ref);
718
719                 if (match_extent_data_ref(leaf, ref, root_objectid,
720                                           owner, offset)) {
721                         if (recow) {
722                                 btrfs_release_path(root, path);
723                                 goto again;
724                         }
725                         err = 0;
726                         break;
727                 }
728                 path->slots[0]++;
729         }
730 fail:
731         return err;
732 }
733
734 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
735                                            struct btrfs_root *root,
736                                            struct btrfs_path *path,
737                                            u64 bytenr, u64 parent,
738                                            u64 root_objectid, u64 owner,
739                                            u64 offset, int refs_to_add)
740 {
741         struct btrfs_key key;
742         struct extent_buffer *leaf;
743         u32 size;
744         u32 num_refs;
745         int ret;
746
747         key.objectid = bytenr;
748         if (parent) {
749                 key.type = BTRFS_SHARED_DATA_REF_KEY;
750                 key.offset = parent;
751                 size = sizeof(struct btrfs_shared_data_ref);
752         } else {
753                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
754                 key.offset = hash_extent_data_ref(root_objectid,
755                                                   owner, offset);
756                 size = sizeof(struct btrfs_extent_data_ref);
757         }
758
759         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
760         if (ret && ret != -EEXIST)
761                 goto fail;
762
763         leaf = path->nodes[0];
764         if (parent) {
765                 struct btrfs_shared_data_ref *ref;
766                 ref = btrfs_item_ptr(leaf, path->slots[0],
767                                      struct btrfs_shared_data_ref);
768                 if (ret == 0) {
769                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
770                 } else {
771                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
772                         num_refs += refs_to_add;
773                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
774                 }
775         } else {
776                 struct btrfs_extent_data_ref *ref;
777                 while (ret == -EEXIST) {
778                         ref = btrfs_item_ptr(leaf, path->slots[0],
779                                              struct btrfs_extent_data_ref);
780                         if (match_extent_data_ref(leaf, ref, root_objectid,
781                                                   owner, offset))
782                                 break;
783                         btrfs_release_path(root, path);
784
785                         key.offset++;
786                         ret = btrfs_insert_empty_item(trans, root, path, &key,
787                                                       size);
788                         if (ret && ret != -EEXIST)
789                                 goto fail;
790
791                         leaf = path->nodes[0];
792                 }
793                 ref = btrfs_item_ptr(leaf, path->slots[0],
794                                      struct btrfs_extent_data_ref);
795                 if (ret == 0) {
796                         btrfs_set_extent_data_ref_root(leaf, ref,
797                                                        root_objectid);
798                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
799                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
800                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
801                 } else {
802                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
803                         num_refs += refs_to_add;
804                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
805                 }
806         }
807         btrfs_mark_buffer_dirty(leaf);
808         ret = 0;
809 fail:
810         btrfs_release_path(root, path);
811         return ret;
812 }
813
814 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
815                                            struct btrfs_root *root,
816                                            struct btrfs_path *path,
817                                            int refs_to_drop)
818 {
819         struct btrfs_key key;
820         struct btrfs_extent_data_ref *ref1 = NULL;
821         struct btrfs_shared_data_ref *ref2 = NULL;
822         struct extent_buffer *leaf;
823         u32 num_refs = 0;
824         int ret = 0;
825
826         leaf = path->nodes[0];
827         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
828
829         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
830                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
831                                       struct btrfs_extent_data_ref);
832                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
833         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
834                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
835                                       struct btrfs_shared_data_ref);
836                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
837 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
838         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
839                 struct btrfs_extent_ref_v0 *ref0;
840                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
841                                       struct btrfs_extent_ref_v0);
842                 num_refs = btrfs_ref_count_v0(leaf, ref0);
843 #endif
844         } else {
845                 BUG();
846         }
847
848         BUG_ON(num_refs < refs_to_drop);
849         num_refs -= refs_to_drop;
850
851         if (num_refs == 0) {
852                 ret = btrfs_del_item(trans, root, path);
853         } else {
854                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
855                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
856                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
857                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
858 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
859                 else {
860                         struct btrfs_extent_ref_v0 *ref0;
861                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
862                                         struct btrfs_extent_ref_v0);
863                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
864                 }
865 #endif
866                 btrfs_mark_buffer_dirty(leaf);
867         }
868         return ret;
869 }
870
871 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
872                                           struct btrfs_path *path,
873                                           struct btrfs_extent_inline_ref *iref)
874 {
875         struct btrfs_key key;
876         struct extent_buffer *leaf;
877         struct btrfs_extent_data_ref *ref1;
878         struct btrfs_shared_data_ref *ref2;
879         u32 num_refs = 0;
880
881         leaf = path->nodes[0];
882         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
883         if (iref) {
884                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
885                     BTRFS_EXTENT_DATA_REF_KEY) {
886                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
887                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
888                 } else {
889                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
890                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
891                 }
892         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
893                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
894                                       struct btrfs_extent_data_ref);
895                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
896         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
897                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
898                                       struct btrfs_shared_data_ref);
899                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
900 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
901         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
902                 struct btrfs_extent_ref_v0 *ref0;
903                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
904                                       struct btrfs_extent_ref_v0);
905                 num_refs = btrfs_ref_count_v0(leaf, ref0);
906 #endif
907         } else {
908                 BUG();
909         }
910         return num_refs;
911 }
912
913 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
914                                           struct btrfs_root *root,
915                                           struct btrfs_path *path,
916                                           u64 bytenr, u64 parent,
917                                           u64 root_objectid)
918 {
919         struct btrfs_key key;
920         int ret;
921
922         key.objectid = bytenr;
923         if (parent) {
924                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
925                 key.offset = parent;
926         } else {
927                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
928                 key.offset = root_objectid;
929         }
930
931         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
932         if (ret > 0)
933                 ret = -ENOENT;
934 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
935         if (ret == -ENOENT && parent) {
936                 btrfs_release_path(root, path);
937                 key.type = BTRFS_EXTENT_REF_V0_KEY;
938                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
939                 if (ret > 0)
940                         ret = -ENOENT;
941         }
942 #endif
943         return ret;
944 }
945
946 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
947                                           struct btrfs_root *root,
948                                           struct btrfs_path *path,
949                                           u64 bytenr, u64 parent,
950                                           u64 root_objectid)
951 {
952         struct btrfs_key key;
953         int ret;
954
955         key.objectid = bytenr;
956         if (parent) {
957                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
958                 key.offset = parent;
959         } else {
960                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
961                 key.offset = root_objectid;
962         }
963
964         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
965
966         btrfs_release_path(root, path);
967         return ret;
968 }
969
970 static inline int extent_ref_type(u64 parent, u64 owner)
971 {
972         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
973                 if (parent > 0)
974                         return BTRFS_SHARED_BLOCK_REF_KEY;
975                 else
976                         return BTRFS_TREE_BLOCK_REF_KEY;
977         } else {
978                 if (parent > 0)
979                         return BTRFS_SHARED_DATA_REF_KEY;
980                 else
981                         return BTRFS_EXTENT_DATA_REF_KEY;
982         }
983 }
984
985 static int find_next_key(struct btrfs_path *path, struct btrfs_key *key)
986
987 {
988         int level;
989         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
990                 if (!path->nodes[level])
991                         break;
992                 if (path->slots[level] + 1 >=
993                     btrfs_header_nritems(path->nodes[level]))
994                         continue;
995                 if (level == 0)
996                         btrfs_item_key_to_cpu(path->nodes[level], key,
997                                               path->slots[level] + 1);
998                 else
999                         btrfs_node_key_to_cpu(path->nodes[level], key,
1000                                               path->slots[level] + 1);
1001                 return 0;
1002         }
1003         return 1;
1004 }
1005
1006 static int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1007                                  struct btrfs_root *root,
1008                                  struct btrfs_path *path,
1009                                  struct btrfs_extent_inline_ref **ref_ret,
1010                                  u64 bytenr, u64 num_bytes,
1011                                  u64 parent, u64 root_objectid,
1012                                  u64 owner, u64 offset, int insert)
1013 {
1014         struct btrfs_key key;
1015         struct extent_buffer *leaf;
1016         struct btrfs_extent_item *ei;
1017         struct btrfs_extent_inline_ref *iref;
1018         u64 flags;
1019         u32 item_size;
1020         unsigned long ptr;
1021         unsigned long end;
1022         int extra_size;
1023         int type;
1024         int want;
1025         int ret;
1026         int err = 0;
1027
1028         key.objectid = bytenr;
1029         key.type = BTRFS_EXTENT_ITEM_KEY;
1030         key.offset = num_bytes;
1031
1032         want = extent_ref_type(parent, owner);
1033         if (insert)
1034                 extra_size = btrfs_extent_inline_ref_size(want);
1035         else
1036                 extra_size = -1;
1037         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1038         if (ret < 0) {
1039                 err = ret;
1040                 goto out;
1041         }
1042         if (ret) {
1043                 printf("Failed to find [%llu, %u, %llu]\n", key.objectid, key.type, key.offset);
1044                 return -ENOENT;
1045         }
1046
1047         BUG_ON(ret);
1048
1049         leaf = path->nodes[0];
1050         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1051 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1052         if (item_size < sizeof(*ei)) {
1053                 if (!insert) {
1054                         err = -ENOENT;
1055                         goto out;
1056                 }
1057                 ret = convert_extent_item_v0(trans, root, path, owner,
1058                                              extra_size);
1059                 if (ret < 0) {
1060                         err = ret;
1061                         goto out;
1062                 }
1063                 leaf = path->nodes[0];
1064                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1065         }
1066 #endif
1067         if (item_size < sizeof(*ei)) {
1068                 printf("Size is %u, needs to be %u, slot %d\n",
1069                        (unsigned)item_size,
1070                        (unsigned)sizeof(*ei), path->slots[0]);
1071                 btrfs_print_leaf(root, leaf);
1072                 return -EINVAL;
1073         }
1074         BUG_ON(item_size < sizeof(*ei));
1075
1076         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1077         flags = btrfs_extent_flags(leaf, ei);
1078
1079         ptr = (unsigned long)(ei + 1);
1080         end = (unsigned long)ei + item_size;
1081
1082         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1083                 ptr += sizeof(struct btrfs_tree_block_info);
1084                 BUG_ON(ptr > end);
1085         } else {
1086                 if (!(flags & BTRFS_EXTENT_FLAG_DATA)) {
1087                         return -EIO;
1088                 }
1089         }
1090
1091         err = -ENOENT;
1092         while (1) {
1093                 if (ptr >= end) {
1094                         WARN_ON(ptr > end);
1095                         break;
1096                 }
1097                 iref = (struct btrfs_extent_inline_ref *)ptr;
1098                 type = btrfs_extent_inline_ref_type(leaf, iref);
1099                 if (want < type)
1100                         break;
1101                 if (want > type) {
1102                         ptr += btrfs_extent_inline_ref_size(type);
1103                         continue;
1104                 }
1105
1106                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1107                         struct btrfs_extent_data_ref *dref;
1108                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1109                         if (match_extent_data_ref(leaf, dref, root_objectid,
1110                                                   owner, offset)) {
1111                                 err = 0;
1112                                 break;
1113                         }
1114                         if (hash_extent_data_ref_item(leaf, dref) <
1115                             hash_extent_data_ref(root_objectid, owner, offset))
1116                                 break;
1117                 } else {
1118                         u64 ref_offset;
1119                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1120                         if (parent > 0) {
1121                                 if (parent == ref_offset) {
1122                                         err = 0;
1123                                         break;
1124                                 }
1125                                 if (ref_offset < parent)
1126                                         break;
1127                         } else {
1128                                 if (root_objectid == ref_offset) {
1129                                         err = 0;
1130                                         break;
1131                                 }
1132                                 if (ref_offset < root_objectid)
1133                                         break;
1134                         }
1135                 }
1136                 ptr += btrfs_extent_inline_ref_size(type);
1137         }
1138         if (err == -ENOENT && insert) {
1139                 if (item_size + extra_size >=
1140                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1141                         err = -EAGAIN;
1142                         goto out;
1143                 }
1144                 /*
1145                  * To add new inline back ref, we have to make sure
1146                  * there is no corresponding back ref item.
1147                  * For simplicity, we just do not add new inline back
1148                  * ref if there is any back ref item.
1149                  */
1150                 if (find_next_key(path, &key) == 0 && key.objectid == bytenr &&
1151                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1152                         err = -EAGAIN;
1153                         goto out;
1154                 }
1155         }
1156         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1157 out:
1158         return err;
1159 }
1160
1161 static int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1162                                 struct btrfs_root *root,
1163                                 struct btrfs_path *path,
1164                                 struct btrfs_extent_inline_ref *iref,
1165                                 u64 parent, u64 root_objectid,
1166                                 u64 owner, u64 offset, int refs_to_add)
1167 {
1168         struct extent_buffer *leaf;
1169         struct btrfs_extent_item *ei;
1170         unsigned long ptr;
1171         unsigned long end;
1172         unsigned long item_offset;
1173         u64 refs;
1174         int size;
1175         int type;
1176         int ret;
1177
1178         leaf = path->nodes[0];
1179         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1180         item_offset = (unsigned long)iref - (unsigned long)ei;
1181
1182         type = extent_ref_type(parent, owner);
1183         size = btrfs_extent_inline_ref_size(type);
1184
1185         ret = btrfs_extend_item(trans, root, path, size);
1186         BUG_ON(ret);
1187
1188         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1189         refs = btrfs_extent_refs(leaf, ei);
1190         refs += refs_to_add;
1191         btrfs_set_extent_refs(leaf, ei, refs);
1192
1193         ptr = (unsigned long)ei + item_offset;
1194         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1195         if (ptr < end - size)
1196                 memmove_extent_buffer(leaf, ptr + size, ptr,
1197                                       end - size - ptr);
1198
1199         iref = (struct btrfs_extent_inline_ref *)ptr;
1200         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1201         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1202                 struct btrfs_extent_data_ref *dref;
1203                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1204                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1205                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1206                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1207                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1208         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1209                 struct btrfs_shared_data_ref *sref;
1210                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1211                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1212                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1213         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1214                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1215         } else {
1216                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1217         }
1218         btrfs_mark_buffer_dirty(leaf);
1219         return 0;
1220 }
1221
1222 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1223                                  struct btrfs_root *root,
1224                                  struct btrfs_path *path,
1225                                  struct btrfs_extent_inline_ref **ref_ret,
1226                                  u64 bytenr, u64 num_bytes, u64 parent,
1227                                  u64 root_objectid, u64 owner, u64 offset)
1228 {
1229         int ret;
1230
1231         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1232                                            bytenr, num_bytes, parent,
1233                                            root_objectid, owner, offset, 0);
1234         if (ret != -ENOENT)
1235                 return ret;
1236
1237         btrfs_release_path(root, path);
1238         *ref_ret = NULL;
1239
1240         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1241                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1242                                             root_objectid);
1243         } else {
1244                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1245                                              root_objectid, owner, offset);
1246         }
1247         return ret;
1248 }
1249
1250 static int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1251                                  struct btrfs_root *root,
1252                                  struct btrfs_path *path,
1253                                  struct btrfs_extent_inline_ref *iref,
1254                                  int refs_to_mod)
1255 {
1256         struct extent_buffer *leaf;
1257         struct btrfs_extent_item *ei;
1258         struct btrfs_extent_data_ref *dref = NULL;
1259         struct btrfs_shared_data_ref *sref = NULL;
1260         unsigned long ptr;
1261         unsigned long end;
1262         u32 item_size;
1263         int size;
1264         int type;
1265         int ret;
1266         u64 refs;
1267
1268         leaf = path->nodes[0];
1269         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1270         refs = btrfs_extent_refs(leaf, ei);
1271         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1272         refs += refs_to_mod;
1273         btrfs_set_extent_refs(leaf, ei, refs);
1274
1275         type = btrfs_extent_inline_ref_type(leaf, iref);
1276
1277         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1278                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1279                 refs = btrfs_extent_data_ref_count(leaf, dref);
1280         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1281                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1282                 refs = btrfs_shared_data_ref_count(leaf, sref);
1283         } else {
1284                 refs = 1;
1285                 BUG_ON(refs_to_mod != -1);
1286         }
1287
1288         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1289         refs += refs_to_mod;
1290
1291         if (refs > 0) {
1292                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1293                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1294                 else
1295                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1296         } else {
1297                 size =  btrfs_extent_inline_ref_size(type);
1298                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1299                 ptr = (unsigned long)iref;
1300                 end = (unsigned long)ei + item_size;
1301                 if (ptr + size < end)
1302                         memmove_extent_buffer(leaf, ptr, ptr + size,
1303                                               end - ptr - size);
1304                 item_size -= size;
1305                 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1306                 BUG_ON(ret);
1307         }
1308         btrfs_mark_buffer_dirty(leaf);
1309         return 0;
1310 }
1311
1312 static int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1313                                  struct btrfs_root *root,
1314                                  struct btrfs_path *path,
1315                                  u64 bytenr, u64 num_bytes, u64 parent,
1316                                  u64 root_objectid, u64 owner,
1317                                  u64 offset, int refs_to_add)
1318 {
1319         struct btrfs_extent_inline_ref *iref;
1320         int ret;
1321
1322         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1323                                            bytenr, num_bytes, parent,
1324                                            root_objectid, owner, offset, 1);
1325         if (ret == 0) {
1326                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1327                 ret = update_inline_extent_backref(trans, root, path, iref,
1328                                                    refs_to_add);
1329         } else if (ret == -ENOENT) {
1330                 ret = setup_inline_extent_backref(trans, root, path, iref,
1331                                                   parent, root_objectid,
1332                                                   owner, offset, refs_to_add);
1333         }
1334         return ret;
1335 }
1336
1337 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1338                                  struct btrfs_root *root,
1339                                  struct btrfs_path *path,
1340                                  u64 bytenr, u64 parent, u64 root_objectid,
1341                                  u64 owner, u64 offset, int refs_to_add)
1342 {
1343         int ret;
1344
1345         if (owner >= BTRFS_FIRST_FREE_OBJECTID) {
1346                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1347                                              parent, root_objectid,
1348                                              owner, offset, refs_to_add);
1349         } else {
1350                 BUG_ON(refs_to_add != 1);
1351                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1352                                             parent, root_objectid);
1353         }
1354         return ret;
1355 }
1356
1357 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1358                                  struct btrfs_root *root,
1359                                  struct btrfs_path *path,
1360                                  struct btrfs_extent_inline_ref *iref,
1361                                  int refs_to_drop, int is_data)
1362 {
1363         int ret;
1364
1365         BUG_ON(!is_data && refs_to_drop != 1);
1366         if (iref) {
1367                 ret = update_inline_extent_backref(trans, root, path, iref,
1368                                                    -refs_to_drop);
1369         } else if (is_data) {
1370                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1371         } else {
1372                 ret = btrfs_del_item(trans, root, path);
1373         }
1374         return ret;
1375 }
1376
1377 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1378                          struct btrfs_root *root,
1379                          u64 bytenr, u64 num_bytes, u64 parent,
1380                          u64 root_objectid, u64 owner, u64 offset)
1381 {
1382         struct btrfs_path *path;
1383         struct extent_buffer *leaf;
1384         struct btrfs_extent_item *item;
1385         u64 refs;
1386         int ret;
1387         int err = 0;
1388
1389         path = btrfs_alloc_path();
1390         if (!path)
1391                 return -ENOMEM;
1392
1393         path->reada = 1;
1394         path->leave_spinning = 1;
1395
1396         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1397                                            path, bytenr, num_bytes, parent,
1398                                            root_objectid, owner, offset, 1);
1399         if (ret == 0)
1400                 goto out;
1401
1402         if (ret != -EAGAIN) {
1403                 err = ret;
1404                 goto out;
1405         }
1406         
1407         leaf = path->nodes[0];
1408         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1409         refs = btrfs_extent_refs(leaf, item);
1410         btrfs_set_extent_refs(leaf, item, refs + 1);
1411
1412         btrfs_mark_buffer_dirty(leaf);
1413         btrfs_release_path(root->fs_info->extent_root, path);
1414
1415         path->reada = 1;
1416         path->leave_spinning = 1;
1417
1418         /* now insert the actual backref */
1419         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1420                                     path, bytenr, parent, root_objectid,
1421                                     owner, offset, 1);
1422         if (ret)
1423                 err = ret;
1424 out:
1425         btrfs_free_path(path);
1426         finish_current_insert(trans, root->fs_info->extent_root);
1427         del_pending_extents(trans, root->fs_info->extent_root);
1428         BUG_ON(err);
1429         return err;
1430 }
1431
1432 int btrfs_extent_post_op(struct btrfs_trans_handle *trans,
1433                          struct btrfs_root *root)
1434 {
1435         finish_current_insert(trans, root->fs_info->extent_root);
1436         del_pending_extents(trans, root->fs_info->extent_root);
1437         return 0;
1438 }
1439
1440 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
1441                              struct btrfs_root *root, u64 bytenr,
1442                              u64 num_bytes, u64 *refs, u64 *flags)
1443 {
1444         struct btrfs_path *path;
1445         int ret;
1446         struct btrfs_key key;
1447         struct extent_buffer *l;
1448         struct btrfs_extent_item *item;
1449         u32 item_size;
1450         u64 num_refs;
1451         u64 extent_flags;
1452
1453         WARN_ON(num_bytes < root->sectorsize);
1454         path = btrfs_alloc_path();
1455         path->reada = 1;
1456         key.objectid = bytenr;
1457         key.offset = num_bytes;
1458         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1459         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
1460                                 0, 0);
1461         if (ret < 0)
1462                 goto out;
1463         if (ret != 0) {
1464                 ret = -EIO;
1465                 goto out;
1466         }
1467
1468         l = path->nodes[0];
1469         item_size = btrfs_item_size_nr(l, path->slots[0]);
1470         if (item_size >= sizeof(*item)) {
1471                 item = btrfs_item_ptr(l, path->slots[0],
1472                                       struct btrfs_extent_item);
1473                 num_refs = btrfs_extent_refs(l, item);
1474                 extent_flags = btrfs_extent_flags(l, item);
1475         } else {
1476 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1477                         struct btrfs_extent_item_v0 *ei0;
1478                         BUG_ON(item_size != sizeof(*ei0));
1479                         ei0 = btrfs_item_ptr(l, path->slots[0],
1480                                              struct btrfs_extent_item_v0);
1481                         num_refs = btrfs_extent_refs_v0(l, ei0);
1482                         /* FIXME: this isn't correct for data */
1483                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
1484 #else
1485                         BUG();
1486 #endif
1487         }
1488         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
1489         if (refs)
1490                 *refs = num_refs;
1491         if (flags)
1492                 *flags = extent_flags;
1493 out:
1494         btrfs_free_path(path);
1495         return 0;
1496 }
1497
1498 int btrfs_set_block_flags(struct btrfs_trans_handle *trans,
1499                           struct btrfs_root *root,
1500                           u64 bytenr, u64 num_bytes, u64 flags)
1501 {
1502         struct btrfs_path *path;
1503         int ret;
1504         struct btrfs_key key;
1505         struct extent_buffer *l;
1506         struct btrfs_extent_item *item;
1507         u32 item_size;
1508
1509         WARN_ON(num_bytes < root->sectorsize);
1510         path = btrfs_alloc_path();
1511         path->reada = 1;
1512         key.objectid = bytenr;
1513         key.offset = num_bytes;
1514         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1515         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
1516                                 0, 0);
1517         if (ret < 0)
1518                 goto out;
1519         if (ret != 0) {
1520                 btrfs_print_leaf(root, path->nodes[0]);
1521                 printk("failed to find block number %Lu\n",
1522                         (unsigned long long)bytenr);
1523                 BUG();
1524         }
1525         l = path->nodes[0];
1526         item_size = btrfs_item_size_nr(l, path->slots[0]);
1527 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1528         if (item_size < sizeof(*item)) {
1529                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1530                                              path, (u64)-1, 0);
1531                 if (ret < 0)
1532                         goto out;
1533
1534                 l = path->nodes[0];
1535                 item_size = btrfs_item_size_nr(l, path->slots[0]);
1536         }
1537 #endif
1538         BUG_ON(item_size < sizeof(*item));
1539         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
1540         flags |= btrfs_extent_flags(l, item);
1541         btrfs_set_extent_flags(l, item, flags);
1542 out:
1543         btrfs_free_path(path);
1544         finish_current_insert(trans, root->fs_info->extent_root);
1545         del_pending_extents(trans, root->fs_info->extent_root);
1546         return ret;
1547 }
1548
1549 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
1550                            struct btrfs_root *root,
1551                            struct extent_buffer *buf,
1552                            int record_parent, int inc)
1553 {
1554         u64 bytenr;
1555         u64 num_bytes;
1556         u64 parent;
1557         u64 ref_root;
1558         u32 nritems;
1559         struct btrfs_key key;
1560         struct btrfs_file_extent_item *fi;
1561         int i;
1562         int level;
1563         int ret = 0;
1564         int (*process_func)(struct btrfs_trans_handle *trans,
1565                             struct btrfs_root *root,
1566                             u64, u64, u64, u64, u64, u64);
1567
1568         ref_root = btrfs_header_owner(buf);
1569         nritems = btrfs_header_nritems(buf);
1570         level = btrfs_header_level(buf);
1571
1572         if (!root->ref_cows && level == 0)
1573                 return 0;
1574
1575         if (inc)
1576                 process_func = btrfs_inc_extent_ref;
1577         else
1578                 process_func = btrfs_free_extent;
1579
1580         if (record_parent)
1581                 parent = buf->start;
1582         else
1583                 parent = 0;
1584
1585         for (i = 0; i < nritems; i++) {
1586                 cond_resched();
1587                 if (level == 0) {
1588                         btrfs_item_key_to_cpu(buf, &key, i);
1589                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1590                                 continue;
1591                         fi = btrfs_item_ptr(buf, i,
1592                                             struct btrfs_file_extent_item);
1593                         if (btrfs_file_extent_type(buf, fi) ==
1594                             BTRFS_FILE_EXTENT_INLINE)
1595                                 continue;
1596                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1597                         if (bytenr == 0)
1598                                 continue;
1599                         
1600                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
1601                         key.offset -= btrfs_file_extent_offset(buf, fi);
1602                         ret = process_func(trans, root, bytenr, num_bytes,
1603                                            parent, ref_root, key.objectid,
1604                                            key.offset);
1605                         if (ret) {
1606                                 WARN_ON(1);
1607                                 goto fail;
1608                         }
1609                 } else {
1610                         bytenr = btrfs_node_blockptr(buf, i);
1611                         num_bytes = btrfs_level_size(root, level - 1);
1612                         ret = process_func(trans, root, bytenr, num_bytes,
1613                                            parent, ref_root, level - 1, 0);
1614                         if (ret) {
1615                                 WARN_ON(1);
1616                                 goto fail;
1617                         }
1618                 }
1619         }
1620         return 0;
1621 fail:
1622         WARN_ON(1);
1623         return ret;
1624 }
1625
1626 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1627                   struct extent_buffer *buf, int record_parent)
1628 {
1629         return __btrfs_mod_ref(trans, root, buf, record_parent, 1);
1630 }
1631
1632 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1633                   struct extent_buffer *buf, int record_parent)
1634 {
1635         return __btrfs_mod_ref(trans, root, buf, record_parent, 0);
1636 }
1637
1638 static int write_one_cache_group(struct btrfs_trans_handle *trans,
1639                                  struct btrfs_root *root,
1640                                  struct btrfs_path *path,
1641                                  struct btrfs_block_group_cache *cache)
1642 {
1643         int ret;
1644         int pending_ret;
1645         struct btrfs_root *extent_root = root->fs_info->extent_root;
1646         unsigned long bi;
1647         struct extent_buffer *leaf;
1648
1649         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
1650         if (ret < 0)
1651                 goto fail;
1652         BUG_ON(ret);
1653
1654         leaf = path->nodes[0];
1655         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
1656         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
1657         btrfs_mark_buffer_dirty(leaf);
1658         btrfs_release_path(extent_root, path);
1659 fail:
1660         finish_current_insert(trans, extent_root);
1661         pending_ret = del_pending_extents(trans, extent_root);
1662         if (ret)
1663                 return ret;
1664         if (pending_ret)
1665                 return pending_ret;
1666         return 0;
1667
1668 }
1669
1670 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
1671                                    struct btrfs_root *root)
1672 {
1673         struct extent_io_tree *block_group_cache;
1674         struct btrfs_block_group_cache *cache;
1675         int ret;
1676         struct btrfs_path *path;
1677         u64 last = 0;
1678         u64 start;
1679         u64 end;
1680         u64 ptr;
1681
1682         block_group_cache = &root->fs_info->block_group_cache;
1683         path = btrfs_alloc_path();
1684         if (!path)
1685                 return -ENOMEM;
1686
1687         while(1) {
1688                 ret = find_first_extent_bit(block_group_cache, last,
1689                                             &start, &end, BLOCK_GROUP_DIRTY);
1690                 if (ret) {
1691                         if (last == 0)
1692                                 break;
1693                         last = 0;
1694                         continue;
1695                 }
1696
1697                 last = end + 1;
1698                 ret = get_state_private(block_group_cache, start, &ptr);
1699                 BUG_ON(ret);
1700
1701                 clear_extent_bits(block_group_cache, start, end,
1702                                   BLOCK_GROUP_DIRTY, GFP_NOFS);
1703
1704                 cache = (struct btrfs_block_group_cache *)(unsigned long)ptr;
1705                 ret = write_one_cache_group(trans, root, path, cache);
1706         }
1707         btrfs_free_path(path);
1708         return 0;
1709 }
1710
1711 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
1712                                                   u64 flags)
1713 {
1714         struct list_head *head = &info->space_info;
1715         struct list_head *cur;
1716         struct btrfs_space_info *found;
1717         list_for_each(cur, head) {
1718                 found = list_entry(cur, struct btrfs_space_info, list);
1719                 if (found->flags & flags)
1720                         return found;
1721         }
1722         return NULL;
1723
1724 }
1725
1726 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
1727                              u64 total_bytes, u64 bytes_used,
1728                              struct btrfs_space_info **space_info)
1729 {
1730         struct btrfs_space_info *found;
1731
1732         found = __find_space_info(info, flags);
1733         if (found) {
1734                 found->total_bytes += total_bytes;
1735                 found->bytes_used += bytes_used;
1736                 if (found->total_bytes < found->bytes_used) {
1737                         fprintf(stderr, "warning, bad space info total_bytes "
1738                                 "%llu used %llu\n",
1739                                (unsigned long long)found->total_bytes,
1740                                (unsigned long long)found->bytes_used);
1741                 }
1742                 *space_info = found;
1743                 return 0;
1744         }
1745         found = kmalloc(sizeof(*found), GFP_NOFS);
1746         if (!found)
1747                 return -ENOMEM;
1748
1749         list_add(&found->list, &info->space_info);
1750         found->flags = flags;
1751         found->total_bytes = total_bytes;
1752         found->bytes_used = bytes_used;
1753         found->bytes_pinned = 0;
1754         found->full = 0;
1755         *space_info = found;
1756         return 0;
1757 }
1758
1759
1760 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1761 {
1762         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
1763                                    BTRFS_BLOCK_GROUP_RAID1 |
1764                                    BTRFS_BLOCK_GROUP_RAID10 |
1765                                    BTRFS_BLOCK_GROUP_RAID5 |
1766                                    BTRFS_BLOCK_GROUP_RAID6 |
1767                                    BTRFS_BLOCK_GROUP_DUP);
1768         if (extra_flags) {
1769                 if (flags & BTRFS_BLOCK_GROUP_DATA)
1770                         fs_info->avail_data_alloc_bits |= extra_flags;
1771                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1772                         fs_info->avail_metadata_alloc_bits |= extra_flags;
1773                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1774                         fs_info->avail_system_alloc_bits |= extra_flags;
1775         }
1776 }
1777
1778 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
1779                           struct btrfs_root *extent_root, u64 alloc_bytes,
1780                           u64 flags)
1781 {
1782         struct btrfs_space_info *space_info;
1783         u64 thresh;
1784         u64 start;
1785         u64 num_bytes;
1786         int ret;
1787
1788         space_info = __find_space_info(extent_root->fs_info, flags);
1789         if (!space_info) {
1790                 ret = update_space_info(extent_root->fs_info, flags,
1791                                         0, 0, &space_info);
1792                 BUG_ON(ret);
1793         }
1794         BUG_ON(!space_info);
1795
1796         if (space_info->full)
1797                 return 0;
1798
1799         thresh = div_factor(space_info->total_bytes, 7);
1800         if ((space_info->bytes_used + space_info->bytes_pinned + alloc_bytes) <
1801             thresh)
1802                 return 0;
1803
1804         ret = btrfs_alloc_chunk(trans, extent_root, &start, &num_bytes,
1805                                 space_info->flags);
1806         if (ret == -ENOSPC) {
1807                 space_info->full = 1;
1808                 return 0;
1809         }
1810
1811         BUG_ON(ret);
1812
1813         ret = btrfs_make_block_group(trans, extent_root, 0, space_info->flags,
1814                      BTRFS_FIRST_CHUNK_TREE_OBJECTID, start, num_bytes);
1815         BUG_ON(ret);
1816         return 0;
1817 }
1818
1819 static int update_block_group(struct btrfs_trans_handle *trans,
1820                               struct btrfs_root *root,
1821                               u64 bytenr, u64 num_bytes, int alloc,
1822                               int mark_free)
1823 {
1824         struct btrfs_block_group_cache *cache;
1825         struct btrfs_fs_info *info = root->fs_info;
1826         u64 total = num_bytes;
1827         u64 old_val;
1828         u64 byte_in_group;
1829         u64 start;
1830         u64 end;
1831
1832         /* block accounting for super block */
1833         old_val = btrfs_super_bytes_used(&info->super_copy);
1834         if (alloc)
1835                 old_val += num_bytes;
1836         else
1837                 old_val -= num_bytes;
1838         btrfs_set_super_bytes_used(&info->super_copy, old_val);
1839
1840         /* block accounting for root item */
1841         old_val = btrfs_root_used(&root->root_item);
1842         if (alloc)
1843                 old_val += num_bytes;
1844         else
1845                 old_val -= num_bytes;
1846         btrfs_set_root_used(&root->root_item, old_val);
1847
1848         while(total) {
1849                 cache = btrfs_lookup_block_group(info, bytenr);
1850                 if (!cache) {
1851                         return -1;
1852                 }
1853                 byte_in_group = bytenr - cache->key.objectid;
1854                 WARN_ON(byte_in_group > cache->key.offset);
1855                 start = cache->key.objectid;
1856                 end = start + cache->key.offset - 1;
1857                 set_extent_bits(&info->block_group_cache, start, end,
1858                                 BLOCK_GROUP_DIRTY, GFP_NOFS);
1859
1860                 old_val = btrfs_block_group_used(&cache->item);
1861                 num_bytes = min(total, cache->key.offset - byte_in_group);
1862
1863                 if (alloc) {
1864                         old_val += num_bytes;
1865                         cache->space_info->bytes_used += num_bytes;
1866                 } else {
1867                         old_val -= num_bytes;
1868                         cache->space_info->bytes_used -= num_bytes;
1869                         if (mark_free) {
1870                                 set_extent_dirty(&info->free_space_cache,
1871                                                  bytenr, bytenr + num_bytes - 1,
1872                                                  GFP_NOFS);
1873                         }
1874                 }
1875                 btrfs_set_block_group_used(&cache->item, old_val);
1876                 total -= num_bytes;
1877                 bytenr += num_bytes;
1878         }
1879         return 0;
1880 }
1881
1882 static int update_pinned_extents(struct btrfs_root *root,
1883                                 u64 bytenr, u64 num, int pin)
1884 {
1885         u64 len;
1886         struct btrfs_block_group_cache *cache;
1887         struct btrfs_fs_info *fs_info = root->fs_info;
1888
1889         if (pin) {
1890                 set_extent_dirty(&fs_info->pinned_extents,
1891                                 bytenr, bytenr + num - 1, GFP_NOFS);
1892         } else {
1893                 clear_extent_dirty(&fs_info->pinned_extents,
1894                                 bytenr, bytenr + num - 1, GFP_NOFS);
1895         }
1896         while (num > 0) {
1897                 cache = btrfs_lookup_block_group(fs_info, bytenr);
1898                 if (!cache) {
1899                         len = min((u64)root->sectorsize, num);
1900                         goto next;
1901                 }
1902                 WARN_ON(!cache);
1903                 len = min(num, cache->key.offset -
1904                           (bytenr - cache->key.objectid));
1905                 if (pin) {
1906                         cache->pinned += len;
1907                         cache->space_info->bytes_pinned += len;
1908                         fs_info->total_pinned += len;
1909                 } else {
1910                         cache->pinned -= len;
1911                         cache->space_info->bytes_pinned -= len;
1912                         fs_info->total_pinned -= len;
1913                 }
1914 next:
1915                 bytenr += len;
1916                 num -= len;
1917         }
1918         return 0;
1919 }
1920
1921 int btrfs_copy_pinned(struct btrfs_root *root, struct extent_io_tree *copy)
1922 {
1923         u64 last = 0;
1924         u64 start;
1925         u64 end;
1926         struct extent_io_tree *pinned_extents = &root->fs_info->pinned_extents;
1927         int ret;
1928
1929         while(1) {
1930                 ret = find_first_extent_bit(pinned_extents, last,
1931                                             &start, &end, EXTENT_DIRTY);
1932                 if (ret)
1933                         break;
1934                 set_extent_dirty(copy, start, end, GFP_NOFS);
1935                 last = end + 1;
1936         }
1937         return 0;
1938 }
1939
1940 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
1941                                struct btrfs_root *root,
1942                                struct extent_io_tree *unpin)
1943 {
1944         u64 start;
1945         u64 end;
1946         int ret;
1947         struct extent_io_tree *free_space_cache;
1948         free_space_cache = &root->fs_info->free_space_cache;
1949
1950         while(1) {
1951                 ret = find_first_extent_bit(unpin, 0, &start, &end,
1952                                             EXTENT_DIRTY);
1953                 if (ret)
1954                         break;
1955                 update_pinned_extents(root, start, end + 1 - start, 0);
1956                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
1957                 set_extent_dirty(free_space_cache, start, end, GFP_NOFS);
1958         }
1959         return 0;
1960 }
1961
1962 static int extent_root_pending_ops(struct btrfs_fs_info *info)
1963 {
1964         u64 start;
1965         u64 end;
1966         int ret;
1967
1968         ret = find_first_extent_bit(&info->extent_ins, 0, &start,
1969                                     &end, EXTENT_LOCKED);
1970         if (!ret) {
1971                 ret = find_first_extent_bit(&info->pending_del, 0, &start, &end,
1972                                             EXTENT_LOCKED);
1973         }
1974         return ret == 0;
1975
1976 }
1977 static int finish_current_insert(struct btrfs_trans_handle *trans,
1978                                  struct btrfs_root *extent_root)
1979 {
1980         u64 start;
1981         u64 end;
1982         u64 priv;
1983         struct btrfs_fs_info *info = extent_root->fs_info;
1984         struct btrfs_path *path;
1985         struct pending_extent_op *extent_op;
1986         struct btrfs_key key;
1987         int ret;
1988
1989         path = btrfs_alloc_path();
1990
1991         while(1) {
1992                 ret = find_first_extent_bit(&info->extent_ins, 0, &start,
1993                                             &end, EXTENT_LOCKED);
1994                 if (ret)
1995                         break;
1996
1997                 ret = get_state_private(&info->extent_ins, start, &priv);
1998                 BUG_ON(ret);
1999                 extent_op = (struct pending_extent_op *)(unsigned long)priv;
2000
2001                 if (extent_op->type == PENDING_EXTENT_INSERT) {
2002                         key.objectid = start;
2003                         key.offset = end + 1 - start;
2004                         key.type = BTRFS_EXTENT_ITEM_KEY;
2005                         ret = alloc_reserved_tree_block(trans, extent_root,
2006                                                 extent_root->root_key.objectid,
2007                                                 trans->transid,
2008                                                 extent_op->flags,
2009                                                 &extent_op->key,
2010                                                 extent_op->level, &key);
2011                 } else {
2012                         BUG_ON(1);
2013                 }
2014
2015                 clear_extent_bits(&info->extent_ins, start, end, EXTENT_LOCKED,
2016                                   GFP_NOFS);
2017                 kfree(extent_op);
2018         }
2019         btrfs_free_path(path);
2020         return 0;
2021 }
2022
2023 static int pin_down_bytes(struct btrfs_trans_handle *trans,
2024                           struct btrfs_root *root,
2025                           u64 bytenr, u64 num_bytes, int is_data)
2026 {
2027         int err = 0;
2028         struct extent_buffer *buf;
2029
2030         if (is_data)
2031                 goto pinit;
2032
2033         buf = btrfs_find_tree_block(root, bytenr, num_bytes);
2034         if (!buf)
2035                 goto pinit;
2036
2037         /* we can reuse a block if it hasn't been written
2038          * and it is from this transaction.  We can't
2039          * reuse anything from the tree log root because
2040          * it has tiny sub-transactions.
2041          */
2042         if (btrfs_buffer_uptodate(buf, 0)) {
2043                 u64 header_owner = btrfs_header_owner(buf);
2044                 u64 header_transid = btrfs_header_generation(buf);
2045                 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
2046                     header_transid == trans->transid &&
2047                     !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
2048                         clean_tree_block(NULL, root, buf);
2049                         free_extent_buffer(buf);
2050                         return 1;
2051                 }
2052         }
2053         free_extent_buffer(buf);
2054 pinit:
2055         update_pinned_extents(root, bytenr, num_bytes, 1);
2056
2057         BUG_ON(err < 0);
2058         return 0;
2059 }
2060
2061 void btrfs_pin_extent(struct btrfs_fs_info *fs_info,
2062                        u64 bytenr, u64 num_bytes)
2063 {
2064         update_pinned_extents(fs_info->extent_root, bytenr, num_bytes, 1);
2065 }
2066
2067 /*
2068  * remove an extent from the root, returns 0 on success
2069  */
2070 static int __free_extent(struct btrfs_trans_handle *trans,
2071                          struct btrfs_root *root,
2072                          u64 bytenr, u64 num_bytes, u64 parent,
2073                          u64 root_objectid, u64 owner_objectid,
2074                          u64 owner_offset, int refs_to_drop)
2075 {
2076
2077         struct btrfs_key key;
2078         struct btrfs_path *path;
2079         struct btrfs_extent_ops *ops = root->fs_info->extent_ops;
2080         struct btrfs_root *extent_root = root->fs_info->extent_root;
2081         struct extent_buffer *leaf;
2082         struct btrfs_extent_item *ei;
2083         struct btrfs_extent_inline_ref *iref;
2084         int ret;
2085         int is_data;
2086         int extent_slot = 0;
2087         int found_extent = 0;
2088         int num_to_del = 1;
2089         u32 item_size;
2090         u64 refs;
2091
2092         if (root->fs_info->free_extent_hook) {
2093                 root->fs_info->free_extent_hook(trans, root, bytenr, num_bytes,
2094                                                 parent, root_objectid, owner_objectid,
2095                                                 owner_offset, refs_to_drop);
2096
2097         }
2098         path = btrfs_alloc_path();
2099         if (!path)
2100                 return -ENOMEM;
2101
2102         path->reada = 1;
2103         path->leave_spinning = 1;
2104
2105         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2106         BUG_ON(!is_data && refs_to_drop != 1);
2107
2108         ret = lookup_extent_backref(trans, extent_root, path, &iref,
2109                                     bytenr, num_bytes, parent,
2110                                     root_objectid, owner_objectid,
2111                                     owner_offset);
2112         if (ret == 0) {
2113                 extent_slot = path->slots[0];
2114                 while (extent_slot >= 0) {
2115                         btrfs_item_key_to_cpu(path->nodes[0], &key,
2116                                               extent_slot);
2117                         if (key.objectid != bytenr)
2118                                 break;
2119                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
2120                             key.offset == num_bytes) {
2121                                 found_extent = 1;
2122                                 break;
2123                         }
2124                         if (path->slots[0] - extent_slot > 5)
2125                                 break;
2126                         extent_slot--;
2127                 }
2128 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2129                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
2130                 if (found_extent && item_size < sizeof(*ei))
2131                         found_extent = 0;
2132 #endif
2133                 if (!found_extent) {
2134                         BUG_ON(iref);
2135                         ret = remove_extent_backref(trans, extent_root, path,
2136                                                     NULL, refs_to_drop,
2137                                                     is_data);
2138                         BUG_ON(ret);
2139                         btrfs_release_path(extent_root, path);
2140                         path->leave_spinning = 1;
2141
2142                         key.objectid = bytenr;
2143                         key.type = BTRFS_EXTENT_ITEM_KEY;
2144                         key.offset = num_bytes;
2145
2146                         ret = btrfs_search_slot(trans, extent_root,
2147                                                 &key, path, -1, 1);
2148                         if (ret) {
2149                                 printk(KERN_ERR "umm, got %d back from search"
2150                                        ", was looking for %llu\n", ret,
2151                                        (unsigned long long)bytenr);
2152                                 btrfs_print_leaf(extent_root, path->nodes[0]);
2153                         }
2154                         BUG_ON(ret);
2155                         extent_slot = path->slots[0];
2156                 }
2157         } else {
2158                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
2159                        "parent %llu root %llu  owner %llu offset %llu\n",
2160                        (unsigned long long)bytenr,
2161                        (unsigned long long)parent,
2162                        (unsigned long long)root_objectid,
2163                        (unsigned long long)owner_objectid,
2164                        (unsigned long long)owner_offset);
2165                 ret = -EIO;
2166                 goto fail;
2167         }
2168
2169         leaf = path->nodes[0];
2170         item_size = btrfs_item_size_nr(leaf, extent_slot);
2171 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2172         if (item_size < sizeof(*ei)) {
2173                 BUG_ON(found_extent || extent_slot != path->slots[0]);
2174                 ret = convert_extent_item_v0(trans, extent_root, path,
2175                                              owner_objectid, 0);
2176                 BUG_ON(ret < 0);
2177
2178                 btrfs_release_path(extent_root, path);
2179                 path->leave_spinning = 1;
2180
2181                 key.objectid = bytenr;
2182                 key.type = BTRFS_EXTENT_ITEM_KEY;
2183                 key.offset = num_bytes;
2184
2185                 ret = btrfs_search_slot(trans, extent_root, &key, path,
2186                                         -1, 1);
2187                 if (ret) {
2188                         printk(KERN_ERR "umm, got %d back from search"
2189                                ", was looking for %llu\n", ret,
2190                                (unsigned long long)bytenr);
2191                         btrfs_print_leaf(extent_root, path->nodes[0]);
2192                 }
2193                 BUG_ON(ret);
2194                 extent_slot = path->slots[0];
2195                 leaf = path->nodes[0];
2196                 item_size = btrfs_item_size_nr(leaf, extent_slot);
2197         }
2198 #endif
2199         BUG_ON(item_size < sizeof(*ei));
2200         ei = btrfs_item_ptr(leaf, extent_slot,
2201                             struct btrfs_extent_item);
2202         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
2203                 struct btrfs_tree_block_info *bi;
2204                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
2205                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2206                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
2207         }
2208
2209         refs = btrfs_extent_refs(leaf, ei);
2210         BUG_ON(refs < refs_to_drop);
2211         refs -= refs_to_drop;
2212
2213         if (refs > 0) {
2214                 /*
2215                  * In the case of inline back ref, reference count will
2216                  * be updated by remove_extent_backref
2217                  */
2218                 if (iref) {
2219                         BUG_ON(!found_extent);
2220                 } else {
2221                         btrfs_set_extent_refs(leaf, ei, refs);
2222                         btrfs_mark_buffer_dirty(leaf);
2223                 }
2224                 if (found_extent) {
2225                         ret = remove_extent_backref(trans, extent_root, path,
2226                                                     iref, refs_to_drop,
2227                                                     is_data);
2228                         BUG_ON(ret);
2229                 }
2230         } else {
2231                 int mark_free = 0;
2232                 int pin = 1;
2233
2234                 if (found_extent) {
2235                         BUG_ON(is_data && refs_to_drop !=
2236                                extent_data_ref_count(root, path, iref));
2237                         if (iref) {
2238                                 BUG_ON(path->slots[0] != extent_slot);
2239                         } else {
2240                                 BUG_ON(path->slots[0] != extent_slot + 1);
2241                                 path->slots[0] = extent_slot;
2242                                 num_to_del = 2;
2243                         }
2244                 }
2245
2246                 if (ops && ops->free_extent) {
2247                         ret = ops->free_extent(root, bytenr, num_bytes);
2248                         if (ret > 0) {
2249                                 pin = 0;
2250                                 mark_free = 0;
2251                         }
2252                 }
2253
2254                 if (pin) {
2255                         ret = pin_down_bytes(trans, root, bytenr, num_bytes,
2256                                              is_data);
2257                         if (ret > 0)
2258                                 mark_free = 1;
2259                         BUG_ON(ret < 0);
2260                 }
2261
2262                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
2263                                       num_to_del);
2264                 BUG_ON(ret);
2265                 btrfs_release_path(extent_root, path);
2266
2267                 if (is_data) {
2268                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
2269                         BUG_ON(ret);
2270                 }
2271
2272                 update_block_group(trans, root, bytenr, num_bytes, 0, mark_free);
2273         }
2274 fail:
2275         btrfs_free_path(path);
2276         finish_current_insert(trans, extent_root);
2277         return ret;
2278 }
2279
2280 /*
2281  * find all the blocks marked as pending in the radix tree and remove
2282  * them from the extent map
2283  */
2284 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
2285                                btrfs_root *extent_root)
2286 {
2287         int ret;
2288         int err = 0;
2289         u64 start;
2290         u64 end;
2291         u64 priv;
2292         struct extent_io_tree *pending_del;
2293         struct extent_io_tree *extent_ins;
2294         struct pending_extent_op *extent_op;
2295
2296         extent_ins = &extent_root->fs_info->extent_ins;
2297         pending_del = &extent_root->fs_info->pending_del;
2298
2299         while(1) {
2300                 ret = find_first_extent_bit(pending_del, 0, &start, &end,
2301                                             EXTENT_LOCKED);
2302                 if (ret)
2303                         break;
2304
2305                 ret = get_state_private(pending_del, start, &priv);
2306                 BUG_ON(ret);
2307                 extent_op = (struct pending_extent_op *)(unsigned long)priv;
2308
2309                 clear_extent_bits(pending_del, start, end, EXTENT_LOCKED,
2310                                   GFP_NOFS);
2311
2312                 if (!test_range_bit(extent_ins, start, end,
2313                                     EXTENT_LOCKED, 0)) {
2314                         ret = __free_extent(trans, extent_root,
2315                                             start, end + 1 - start, 0,
2316                                             extent_root->root_key.objectid,
2317                                             extent_op->level, 0, 1);
2318                         kfree(extent_op);
2319                 } else {
2320                         kfree(extent_op);
2321                         ret = get_state_private(extent_ins, start, &priv);
2322                         BUG_ON(ret);
2323                         extent_op = (struct pending_extent_op *)
2324                                                         (unsigned long)priv;
2325
2326                         clear_extent_bits(extent_ins, start, end,
2327                                           EXTENT_LOCKED, GFP_NOFS);
2328
2329                         if (extent_op->type == PENDING_BACKREF_UPDATE)
2330                                 BUG_ON(1);
2331
2332                         kfree(extent_op);
2333                 }
2334                 if (ret)
2335                         err = ret;
2336         }
2337         return err;
2338 }
2339
2340 /*
2341  * remove an extent from the root, returns 0 on success
2342  */
2343
2344 int btrfs_free_extent(struct btrfs_trans_handle *trans,
2345                       struct btrfs_root *root,
2346                       u64 bytenr, u64 num_bytes, u64 parent,
2347                       u64 root_objectid, u64 owner, u64 offset)
2348 {
2349         struct btrfs_root *extent_root = root->fs_info->extent_root;
2350         int pending_ret;
2351         int ret;
2352
2353         WARN_ON(num_bytes < root->sectorsize);
2354         if (root == extent_root) {
2355                 struct pending_extent_op *extent_op;
2356
2357                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2358                 BUG_ON(!extent_op);
2359
2360                 extent_op->type = PENDING_EXTENT_DELETE;
2361                 extent_op->bytenr = bytenr;
2362                 extent_op->num_bytes = num_bytes;
2363                 extent_op->level = (int)owner;
2364
2365                 set_extent_bits(&root->fs_info->pending_del,
2366                                 bytenr, bytenr + num_bytes - 1,
2367                                 EXTENT_LOCKED, GFP_NOFS);
2368                 set_state_private(&root->fs_info->pending_del,
2369                                   bytenr, (unsigned long)extent_op);
2370                 return 0;
2371         }
2372         ret = __free_extent(trans, root, bytenr, num_bytes, parent,
2373                             root_objectid, owner, offset, 1);
2374         pending_ret = del_pending_extents(trans, root->fs_info->extent_root);
2375         return ret ? ret : pending_ret;
2376 }
2377
2378 static u64 stripe_align(struct btrfs_root *root, u64 val)
2379 {
2380         u64 mask = ((u64)root->stripesize - 1);
2381         u64 ret = (val + mask) & ~mask;
2382         return ret;
2383 }
2384
2385 /*
2386  * walks the btree of allocated extents and find a hole of a given size.
2387  * The key ins is changed to record the hole:
2388  * ins->objectid == block start
2389  * ins->flags = BTRFS_EXTENT_ITEM_KEY
2390  * ins->offset == number of blocks
2391  * Any available blocks before search_start are skipped.
2392  */
2393 static int noinline find_free_extent(struct btrfs_trans_handle *trans,
2394                                      struct btrfs_root *orig_root,
2395                                      u64 num_bytes, u64 empty_size,
2396                                      u64 search_start, u64 search_end,
2397                                      u64 hint_byte, struct btrfs_key *ins,
2398                                      u64 exclude_start, u64 exclude_nr,
2399                                      int data)
2400 {
2401         int ret;
2402         u64 orig_search_start = search_start;
2403         struct btrfs_root * root = orig_root->fs_info->extent_root;
2404         struct btrfs_fs_info *info = root->fs_info;
2405         u64 total_needed = num_bytes;
2406         struct btrfs_block_group_cache *block_group;
2407         int full_scan = 0;
2408         int wrapped = 0;
2409
2410         WARN_ON(num_bytes < root->sectorsize);
2411         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
2412
2413         search_start = stripe_align(root, search_start);
2414
2415         if (hint_byte) {
2416                 block_group = btrfs_lookup_first_block_group(info, hint_byte);
2417                 if (!block_group)
2418                         hint_byte = search_start;
2419                 block_group = btrfs_find_block_group(root, block_group,
2420                                                      hint_byte, data, 1);
2421         } else {
2422                 block_group = btrfs_find_block_group(root,
2423                                                      trans->block_group,
2424                                                      search_start, data, 1);
2425         }
2426
2427         total_needed += empty_size;
2428
2429 check_failed:
2430         search_start = stripe_align(root, search_start);
2431         if (!block_group) {
2432                 block_group = btrfs_lookup_first_block_group(info,
2433                                                              search_start);
2434                 if (!block_group)
2435                         block_group = btrfs_lookup_first_block_group(info,
2436                                                        orig_search_start);
2437         }
2438         ret = find_search_start(root, &block_group, &search_start,
2439                                 total_needed, data);
2440         if (ret)
2441                 goto error;
2442
2443         ins->objectid = search_start;
2444         ins->offset = num_bytes;
2445
2446         if (ins->objectid + num_bytes >
2447             block_group->key.objectid + block_group->key.offset) {
2448                 search_start = block_group->key.objectid +
2449                         block_group->key.offset;
2450                 goto new_group;
2451         }
2452
2453         if (test_range_bit(&info->extent_ins, ins->objectid,
2454                            ins->objectid + num_bytes -1, EXTENT_LOCKED, 0)) {
2455                 search_start = ins->objectid + num_bytes;
2456                 goto new_group;
2457         }
2458
2459         if (test_range_bit(&info->pinned_extents, ins->objectid,
2460                            ins->objectid + num_bytes -1, EXTENT_DIRTY, 0)) {
2461                 search_start = ins->objectid + num_bytes;
2462                 goto new_group;
2463         }
2464
2465         if (exclude_nr > 0 && (ins->objectid + num_bytes > exclude_start &&
2466             ins->objectid < exclude_start + exclude_nr)) {
2467                 search_start = exclude_start + exclude_nr;
2468                 goto new_group;
2469         }
2470
2471         if (!(data & BTRFS_BLOCK_GROUP_DATA)) {
2472                 block_group = btrfs_lookup_block_group(info, ins->objectid);
2473                 if (block_group)
2474                         trans->block_group = block_group;
2475         }
2476         ins->offset = num_bytes;
2477         return 0;
2478
2479 new_group:
2480         block_group = btrfs_lookup_first_block_group(info, search_start);
2481         if (!block_group) {
2482                 search_start = orig_search_start;
2483                 if (full_scan) {
2484                         ret = -ENOSPC;
2485                         goto error;
2486                 }
2487                 if (wrapped) {
2488                         if (!full_scan)
2489                                 total_needed -= empty_size;
2490                         full_scan = 1;
2491                 } else
2492                         wrapped = 1;
2493         }
2494         cond_resched();
2495         block_group = btrfs_find_block_group(root, block_group,
2496                                              search_start, data, 0);
2497         goto check_failed;
2498
2499 error:
2500         return ret;
2501 }
2502
2503 static int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
2504                                 struct btrfs_root *root,
2505                                 u64 num_bytes, u64 empty_size,
2506                                 u64 hint_byte, u64 search_end,
2507                                 struct btrfs_key *ins, int data)
2508 {
2509         int ret;
2510         u64 search_start = 0;
2511         u64 alloc_profile;
2512         struct btrfs_fs_info *info = root->fs_info;
2513
2514         if (info->extent_ops) {
2515                 struct btrfs_extent_ops *ops = info->extent_ops;
2516                 ret = ops->alloc_extent(root, num_bytes, hint_byte, ins);
2517                 BUG_ON(ret);
2518                 goto found;
2519         }
2520
2521         if (data) {
2522                 alloc_profile = info->avail_data_alloc_bits &
2523                                 info->data_alloc_profile;
2524                 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
2525         } else if ((info->system_allocs > 0 || root == info->chunk_root) &&
2526                    info->system_allocs >= 0) {
2527                 alloc_profile = info->avail_system_alloc_bits &
2528                                 info->system_alloc_profile;
2529                 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
2530         } else {
2531                 alloc_profile = info->avail_metadata_alloc_bits &
2532                                 info->metadata_alloc_profile;
2533                 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
2534         }
2535
2536         if (root->ref_cows) {
2537                 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
2538                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2539                                              num_bytes,
2540                                              BTRFS_BLOCK_GROUP_METADATA);
2541                         BUG_ON(ret);
2542                 }
2543                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2544                                      num_bytes + 2 * 1024 * 1024, data);
2545                 BUG_ON(ret);
2546         }
2547
2548         WARN_ON(num_bytes < root->sectorsize);
2549         ret = find_free_extent(trans, root, num_bytes, empty_size,
2550                                search_start, search_end, hint_byte, ins,
2551                                trans->alloc_exclude_start,
2552                                trans->alloc_exclude_nr, data);
2553         BUG_ON(ret);
2554 found:
2555         clear_extent_dirty(&root->fs_info->free_space_cache,
2556                            ins->objectid, ins->objectid + ins->offset - 1,
2557                            GFP_NOFS);
2558         return ret;
2559 }
2560
2561 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
2562                                      struct btrfs_root *root,
2563                                      u64 root_objectid, u64 generation,
2564                                      u64 flags, struct btrfs_disk_key *key,
2565                                      int level, struct btrfs_key *ins)
2566 {
2567         int ret;
2568         struct btrfs_fs_info *fs_info = root->fs_info;
2569         struct btrfs_extent_item *extent_item;
2570         struct btrfs_tree_block_info *block_info;
2571         struct btrfs_extent_inline_ref *iref;
2572         struct btrfs_path *path;
2573         struct extent_buffer *leaf;
2574         u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
2575
2576         path = btrfs_alloc_path();
2577         BUG_ON(!path);
2578
2579         path->leave_spinning = 1;
2580         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
2581                                       ins, size);
2582         BUG_ON(ret);
2583
2584         leaf = path->nodes[0];
2585         extent_item = btrfs_item_ptr(leaf, path->slots[0],
2586                                      struct btrfs_extent_item);
2587         btrfs_set_extent_refs(leaf, extent_item, 1);
2588         btrfs_set_extent_generation(leaf, extent_item, generation);
2589         btrfs_set_extent_flags(leaf, extent_item,
2590                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
2591         block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
2592
2593         btrfs_set_tree_block_key(leaf, block_info, key);
2594         btrfs_set_tree_block_level(leaf, block_info, level);
2595
2596         iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
2597         btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_TREE_BLOCK_REF_KEY);
2598         btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
2599
2600         btrfs_mark_buffer_dirty(leaf);
2601         btrfs_free_path(path);
2602
2603         ret = update_block_group(trans, root, ins->objectid, ins->offset,
2604                                  1, 0);
2605         return 0;
2606 }
2607
2608 static int alloc_tree_block(struct btrfs_trans_handle *trans,
2609                             struct btrfs_root *root, u64 num_bytes,
2610                             u64 root_objectid, u64 generation,
2611                             u64 flags, struct btrfs_disk_key *key,
2612                             int level, u64 empty_size, u64 hint_byte,
2613                             u64 search_end, struct btrfs_key *ins)
2614 {
2615         int ret;
2616         ret = btrfs_reserve_extent(trans, root, num_bytes, empty_size,
2617                                    hint_byte, search_end, ins, 0);
2618         BUG_ON(ret);
2619
2620         if (root_objectid == BTRFS_EXTENT_TREE_OBJECTID) {
2621                 struct pending_extent_op *extent_op;
2622
2623                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2624                 BUG_ON(!extent_op);
2625
2626                 extent_op->type = PENDING_EXTENT_INSERT;
2627                 extent_op->bytenr = ins->objectid;
2628                 extent_op->num_bytes = ins->offset;
2629                 extent_op->level = level;
2630                 extent_op->flags = flags;
2631                 memcpy(&extent_op->key, key, sizeof(*key));
2632
2633                 set_extent_bits(&root->fs_info->extent_ins, ins->objectid,
2634                                 ins->objectid + ins->offset - 1,
2635                                 EXTENT_LOCKED, GFP_NOFS);
2636                 set_state_private(&root->fs_info->extent_ins,
2637                                   ins->objectid, (unsigned long)extent_op);
2638         } else {
2639                 ret = alloc_reserved_tree_block(trans, root, root_objectid,
2640                                                 generation, flags,
2641                                                 key, level, ins);
2642                 finish_current_insert(trans, root->fs_info->extent_root);
2643                 del_pending_extents(trans, root->fs_info->extent_root);
2644         }
2645         return ret;
2646 }
2647
2648 /*
2649  * helper function to allocate a block for a given tree
2650  * returns the tree buffer or NULL.
2651  */
2652 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
2653                                         struct btrfs_root *root,
2654                                         u32 blocksize, u64 root_objectid,
2655                                         struct btrfs_disk_key *key, int level,
2656                                         u64 hint, u64 empty_size)
2657 {
2658         struct btrfs_key ins;
2659         int ret;
2660         struct extent_buffer *buf;
2661
2662         ret = alloc_tree_block(trans, root, blocksize, root_objectid,
2663                                trans->transid, 0, key, level,
2664                                empty_size, hint, (u64)-1, &ins);
2665         if (ret) {
2666                 BUG_ON(ret > 0);
2667                 return ERR_PTR(ret);
2668         }
2669
2670         buf = btrfs_find_create_tree_block(root, ins.objectid, blocksize);
2671         if (!buf) {
2672                 btrfs_free_extent(trans, root, ins.objectid, ins.offset,
2673                                   0, root->root_key.objectid, level, 0);
2674                 BUG_ON(1);
2675                 return ERR_PTR(-ENOMEM);
2676         }
2677         btrfs_set_buffer_uptodate(buf);
2678         trans->blocks_used++;
2679
2680         return buf;
2681 }
2682
2683 #if 0
2684
2685 static int noinline drop_leaf_ref(struct btrfs_trans_handle *trans,
2686                                   struct btrfs_root *root,
2687                                   struct extent_buffer *leaf)
2688 {
2689         u64 leaf_owner;
2690         u64 leaf_generation;
2691         struct btrfs_key key;
2692         struct btrfs_file_extent_item *fi;
2693         int i;
2694         int nritems;
2695         int ret;
2696
2697         BUG_ON(!btrfs_is_leaf(leaf));
2698         nritems = btrfs_header_nritems(leaf);
2699         leaf_owner = btrfs_header_owner(leaf);
2700         leaf_generation = btrfs_header_generation(leaf);
2701
2702         for (i = 0; i < nritems; i++) {
2703                 u64 disk_bytenr;
2704
2705                 btrfs_item_key_to_cpu(leaf, &key, i);
2706                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2707                         continue;
2708                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
2709                 if (btrfs_file_extent_type(leaf, fi) ==
2710                     BTRFS_FILE_EXTENT_INLINE)
2711                         continue;
2712                 /*
2713                  * FIXME make sure to insert a trans record that
2714                  * repeats the snapshot del on crash
2715                  */
2716                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2717                 if (disk_bytenr == 0)
2718                         continue;
2719                 ret = btrfs_free_extent(trans, root, disk_bytenr,
2720                                 btrfs_file_extent_disk_num_bytes(leaf, fi),
2721                                 leaf->start, leaf_owner, leaf_generation,
2722                                 key.objectid, 0);
2723                 BUG_ON(ret);
2724         }
2725         return 0;
2726 }
2727
2728 static void noinline reada_walk_down(struct btrfs_root *root,
2729                                      struct extent_buffer *node,
2730                                      int slot)
2731 {
2732         u64 bytenr;
2733         u64 last = 0;
2734         u32 nritems;
2735         u32 refs;
2736         u32 blocksize;
2737         int ret;
2738         int i;
2739         int level;
2740         int skipped = 0;
2741
2742         nritems = btrfs_header_nritems(node);
2743         level = btrfs_header_level(node);
2744         if (level)
2745                 return;
2746
2747         for (i = slot; i < nritems && skipped < 32; i++) {
2748                 bytenr = btrfs_node_blockptr(node, i);
2749                 if (last && ((bytenr > last && bytenr - last > 32 * 1024) ||
2750                              (last > bytenr && last - bytenr > 32 * 1024))) {
2751                         skipped++;
2752                         continue;
2753                 }
2754                 blocksize = btrfs_level_size(root, level - 1);
2755                 if (i != slot) {
2756                         ret = btrfs_lookup_extent_ref(NULL, root, bytenr,
2757                                                       blocksize, &refs);
2758                         BUG_ON(ret);
2759                         if (refs != 1) {
2760                                 skipped++;
2761                                 continue;
2762                         }
2763                 }
2764                 mutex_unlock(&root->fs_info->fs_mutex);
2765                 ret = readahead_tree_block(root, bytenr, blocksize,
2766                                            btrfs_node_ptr_generation(node, i));
2767                 last = bytenr + blocksize;
2768                 cond_resched();
2769                 mutex_lock(&root->fs_info->fs_mutex);
2770                 if (ret)
2771                         break;
2772         }
2773 }
2774
2775 /*
2776  * helper function for drop_snapshot, this walks down the tree dropping ref
2777  * counts as it goes.
2778  */
2779 static int noinline walk_down_tree(struct btrfs_trans_handle *trans,
2780                                    struct btrfs_root *root,
2781                                    struct btrfs_path *path, int *level)
2782 {
2783         u64 root_owner;
2784         u64 root_gen;
2785         u64 bytenr;
2786         u64 ptr_gen;
2787         struct extent_buffer *next;
2788         struct extent_buffer *cur;
2789         struct extent_buffer *parent;
2790         u32 blocksize;
2791         int ret;
2792         u32 refs;
2793
2794         WARN_ON(*level < 0);
2795         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2796         ret = btrfs_lookup_extent_ref(trans, root,
2797                                       path->nodes[*level]->start,
2798                                       path->nodes[*level]->len, &refs);
2799         BUG_ON(ret);
2800         if (refs > 1)
2801                 goto out;
2802
2803         /*
2804          * walk down to the last node level and free all the leaves
2805          */
2806         while(*level >= 0) {
2807                 WARN_ON(*level < 0);
2808                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2809                 cur = path->nodes[*level];
2810
2811                 if (btrfs_header_level(cur) != *level)
2812                         WARN_ON(1);
2813
2814                 if (path->slots[*level] >=
2815                     btrfs_header_nritems(cur))
2816                         break;
2817                 if (*level == 0) {
2818                         ret = drop_leaf_ref(trans, root, cur);
2819                         BUG_ON(ret);
2820                         break;
2821                 }
2822                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2823                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2824                 blocksize = btrfs_level_size(root, *level - 1);
2825                 ret = btrfs_lookup_extent_ref(trans, root, bytenr, blocksize,
2826                                               &refs);
2827                 BUG_ON(ret);
2828                 if (refs != 1) {
2829                         parent = path->nodes[*level];
2830                         root_owner = btrfs_header_owner(parent);
2831                         root_gen = btrfs_header_generation(parent);
2832                         path->slots[*level]++;
2833                         ret = btrfs_free_extent(trans, root, bytenr, blocksize,
2834                                                 parent->start, root_owner,
2835                                                 root_gen, *level - 1, 1);
2836                         BUG_ON(ret);
2837                         continue;
2838                 }
2839                 next = btrfs_find_tree_block(root, bytenr, blocksize);
2840                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
2841                         free_extent_buffer(next);
2842                         reada_walk_down(root, cur, path->slots[*level]);
2843                         mutex_unlock(&root->fs_info->fs_mutex);
2844                         next = read_tree_block(root, bytenr, blocksize,
2845                                                ptr_gen);
2846                         mutex_lock(&root->fs_info->fs_mutex);
2847                 }
2848                 WARN_ON(*level <= 0);
2849                 if (path->nodes[*level-1])
2850                         free_extent_buffer(path->nodes[*level-1]);
2851                 path->nodes[*level-1] = next;
2852                 *level = btrfs_header_level(next);
2853                 path->slots[*level] = 0;
2854         }
2855 out:
2856         WARN_ON(*level < 0);
2857         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2858
2859         if (path->nodes[*level] == root->node) {
2860                 root_owner = root->root_key.objectid;
2861                 parent = path->nodes[*level];
2862         } else {
2863                 parent = path->nodes[*level + 1];
2864                 root_owner = btrfs_header_owner(parent);
2865         }
2866
2867         root_gen = btrfs_header_generation(parent);
2868         ret = btrfs_free_extent(trans, root, path->nodes[*level]->start,
2869                                 path->nodes[*level]->len, parent->start,
2870                                 root_owner, root_gen, *level, 1);
2871         free_extent_buffer(path->nodes[*level]);
2872         path->nodes[*level] = NULL;
2873         *level += 1;
2874         BUG_ON(ret);
2875         return 0;
2876 }
2877
2878 /*
2879  * helper for dropping snapshots.  This walks back up the tree in the path
2880  * to find the first node higher up where we haven't yet gone through
2881  * all the slots
2882  */
2883 static int noinline walk_up_tree(struct btrfs_trans_handle *trans,
2884                                  struct btrfs_root *root,
2885                                  struct btrfs_path *path, int *level)
2886 {
2887         u64 root_owner;
2888         u64 root_gen;
2889         struct btrfs_root_item *root_item = &root->root_item;
2890         int i;
2891         int slot;
2892         int ret;
2893
2894         for(i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2895                 slot = path->slots[i];
2896                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
2897                         struct extent_buffer *node;
2898                         struct btrfs_disk_key disk_key;
2899                         node = path->nodes[i];
2900                         path->slots[i]++;
2901                         *level = i;
2902                         WARN_ON(*level == 0);
2903                         btrfs_node_key(node, &disk_key, path->slots[i]);
2904                         memcpy(&root_item->drop_progress,
2905                                &disk_key, sizeof(disk_key));
2906                         root_item->drop_level = i;
2907                         return 0;
2908                 } else {
2909                         struct extent_buffer *parent;
2910                         if (path->nodes[*level] == root->node)
2911                                 parent = path->nodes[*level];
2912                         else
2913                                 parent = path->nodes[*level + 1];
2914
2915                         root_owner = btrfs_header_owner(parent);
2916                         root_gen = btrfs_header_generation(parent);
2917                         ret = btrfs_free_extent(trans, root,
2918                                                 path->nodes[*level]->start,
2919                                                 path->nodes[*level]->len,
2920                                                 parent->start, root_owner,
2921                                                 root_gen, *level, 1);
2922                         BUG_ON(ret);
2923                         free_extent_buffer(path->nodes[*level]);
2924                         path->nodes[*level] = NULL;
2925                         *level = i + 1;
2926                 }
2927         }
2928         return 1;
2929 }
2930
2931 /*
2932  * drop the reference count on the tree rooted at 'snap'.  This traverses
2933  * the tree freeing any blocks that have a ref count of zero after being
2934  * decremented.
2935  */
2936 int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
2937                         *root)
2938 {
2939         int ret = 0;
2940         int wret;
2941         int level;
2942         struct btrfs_path *path;
2943         int i;
2944         int orig_level;
2945         struct btrfs_root_item *root_item = &root->root_item;
2946
2947         path = btrfs_alloc_path();
2948         BUG_ON(!path);
2949
2950         level = btrfs_header_level(root->node);
2951         orig_level = level;
2952         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2953                 path->nodes[level] = root->node;
2954                 extent_buffer_get(root->node);
2955                 path->slots[level] = 0;
2956         } else {
2957                 struct btrfs_key key;
2958                 struct btrfs_disk_key found_key;
2959                 struct extent_buffer *node;
2960
2961                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2962                 level = root_item->drop_level;
2963                 path->lowest_level = level;
2964                 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2965                 if (wret < 0) {
2966                         ret = wret;
2967                         goto out;
2968                 }
2969                 node = path->nodes[level];
2970                 btrfs_node_key(node, &found_key, path->slots[level]);
2971                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
2972                                sizeof(found_key)));
2973         }
2974         while(1) {
2975                 wret = walk_down_tree(trans, root, path, &level);
2976                 if (wret < 0)
2977                         ret = wret;
2978                 if (wret != 0)
2979                         break;
2980
2981                 wret = walk_up_tree(trans, root, path, &level);
2982                 if (wret < 0)
2983                         ret = wret;
2984                 if (wret != 0)
2985                         break;
2986                 /*
2987                 ret = -EAGAIN;
2988                 break;
2989                 */
2990         }
2991         for (i = 0; i <= orig_level; i++) {
2992                 if (path->nodes[i]) {
2993                         free_extent_buffer(path->nodes[i]);
2994                         path->nodes[i] = NULL;
2995                 }
2996         }
2997 out:
2998         btrfs_free_path(path);
2999         return ret;
3000 }
3001
3002 #endif
3003
3004 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3005 {
3006         u64 start;
3007         u64 end;
3008         u64 ptr;
3009         int ret;
3010         while(1) {
3011                 ret = find_first_extent_bit(&info->block_group_cache, 0,
3012                                             &start, &end, (unsigned int)-1);
3013                 if (ret)
3014                         break;
3015                 ret = get_state_private(&info->block_group_cache, start, &ptr);
3016                 if (!ret)
3017                         kfree((void *)(unsigned long)ptr);
3018                 clear_extent_bits(&info->block_group_cache, start,
3019                                   end, (unsigned int)-1, GFP_NOFS);
3020         }
3021         while(1) {
3022                 ret = find_first_extent_bit(&info->free_space_cache, 0,
3023                                             &start, &end, EXTENT_DIRTY);
3024                 if (ret)
3025                         break;
3026                 clear_extent_dirty(&info->free_space_cache, start,
3027                                    end, GFP_NOFS);
3028         }
3029         return 0;
3030 }
3031
3032 int find_first_block_group(struct btrfs_root *root, struct btrfs_path *path,
3033                            struct btrfs_key *key)
3034 {
3035         int ret;
3036         struct btrfs_key found_key;
3037         struct extent_buffer *leaf;
3038         int slot;
3039
3040         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
3041         if (ret < 0)
3042                 return ret;
3043         while(1) {
3044                 slot = path->slots[0];
3045                 leaf = path->nodes[0];
3046                 if (slot >= btrfs_header_nritems(leaf)) {
3047                         ret = btrfs_next_leaf(root, path);
3048                         if (ret == 0)
3049                                 continue;
3050                         if (ret < 0)
3051                                 goto error;
3052                         break;
3053                 }
3054                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3055
3056                 if (found_key.objectid >= key->objectid &&
3057                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY)
3058                         return 0;
3059                 path->slots[0]++;
3060         }
3061         ret = -ENOENT;
3062 error:
3063         return ret;
3064 }
3065
3066 int btrfs_read_block_groups(struct btrfs_root *root)
3067 {
3068         struct btrfs_path *path;
3069         int ret;
3070         int bit;
3071         struct btrfs_block_group_cache *cache;
3072         struct btrfs_fs_info *info = root->fs_info;
3073         struct btrfs_space_info *space_info;
3074         struct extent_io_tree *block_group_cache;
3075         struct btrfs_key key;
3076         struct btrfs_key found_key;
3077         struct extent_buffer *leaf;
3078
3079         block_group_cache = &info->block_group_cache;
3080
3081         root = info->extent_root;
3082         key.objectid = 0;
3083         key.offset = 0;
3084         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
3085         path = btrfs_alloc_path();
3086         if (!path)
3087                 return -ENOMEM;
3088
3089         while(1) {
3090                 ret = find_first_block_group(root, path, &key);
3091                 if (ret > 0) {
3092                         ret = 0;
3093                         goto error;
3094                 }
3095                 if (ret != 0) {
3096                         goto error;
3097                 }
3098                 leaf = path->nodes[0];
3099                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3100                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
3101                 if (!cache) {
3102                         ret = -ENOMEM;
3103                         break;
3104                 }
3105
3106                 read_extent_buffer(leaf, &cache->item,
3107                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
3108                                    sizeof(cache->item));
3109                 memcpy(&cache->key, &found_key, sizeof(found_key));
3110                 cache->cached = 0;
3111                 cache->pinned = 0;
3112                 key.objectid = found_key.objectid + found_key.offset;
3113                 btrfs_release_path(root, path);
3114                 cache->flags = btrfs_block_group_flags(&cache->item);
3115                 bit = 0;
3116                 if (cache->flags & BTRFS_BLOCK_GROUP_DATA) {
3117                         bit = BLOCK_GROUP_DATA;
3118                 } else if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
3119                         bit = BLOCK_GROUP_SYSTEM;
3120                 } else if (cache->flags & BTRFS_BLOCK_GROUP_METADATA) {
3121                         bit = BLOCK_GROUP_METADATA;
3122                 }
3123                 set_avail_alloc_bits(info, cache->flags);
3124                 if (btrfs_chunk_readonly(root, cache->key.objectid))
3125                         cache->ro = 1;
3126
3127                 ret = update_space_info(info, cache->flags, found_key.offset,
3128                                         btrfs_block_group_used(&cache->item),
3129                                         &space_info);
3130                 BUG_ON(ret);
3131                 cache->space_info = space_info;
3132
3133                 /* use EXTENT_LOCKED to prevent merging */
3134                 set_extent_bits(block_group_cache, found_key.objectid,
3135                                 found_key.objectid + found_key.offset - 1,
3136                                 bit | EXTENT_LOCKED, GFP_NOFS);
3137                 set_state_private(block_group_cache, found_key.objectid,
3138                                   (unsigned long)cache);
3139         }
3140         ret = 0;
3141 error:
3142         btrfs_free_path(path);
3143         return ret;
3144 }
3145
3146 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
3147                            struct btrfs_root *root, u64 bytes_used,
3148                            u64 type, u64 chunk_objectid, u64 chunk_offset,
3149                            u64 size)
3150 {
3151         int ret;
3152         int bit = 0;
3153         struct btrfs_root *extent_root;
3154         struct btrfs_block_group_cache *cache;
3155         struct extent_io_tree *block_group_cache;
3156
3157         extent_root = root->fs_info->extent_root;
3158         block_group_cache = &root->fs_info->block_group_cache;
3159
3160         cache = kzalloc(sizeof(*cache), GFP_NOFS);
3161         BUG_ON(!cache);
3162         cache->key.objectid = chunk_offset;
3163         cache->key.offset = size;
3164
3165         btrfs_set_key_type(&cache->key, BTRFS_BLOCK_GROUP_ITEM_KEY);
3166         btrfs_set_block_group_used(&cache->item, bytes_used);
3167         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
3168         cache->flags = type;
3169         btrfs_set_block_group_flags(&cache->item, type);
3170
3171         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
3172                                 &cache->space_info);
3173         BUG_ON(ret);
3174
3175         bit = block_group_state_bits(type);
3176         set_extent_bits(block_group_cache, chunk_offset,
3177                         chunk_offset + size - 1,
3178                         bit | EXTENT_LOCKED, GFP_NOFS);
3179
3180         set_state_private(block_group_cache, chunk_offset,
3181                           (unsigned long)cache);
3182         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
3183                                 sizeof(cache->item));
3184         BUG_ON(ret);
3185
3186         finish_current_insert(trans, extent_root);
3187         ret = del_pending_extents(trans, extent_root);
3188         set_avail_alloc_bits(extent_root->fs_info, type);
3189         return 0;
3190 }
3191
3192 /*
3193  * This is for converter use only.
3194  *
3195  * In that case, we don't know where are free blocks located.
3196  * Therefore all block group cache entries must be setup properly
3197  * before doing any block allocation.
3198  */
3199 int btrfs_make_block_groups(struct btrfs_trans_handle *trans,
3200                             struct btrfs_root *root)
3201 {
3202         u64 total_bytes;
3203         u64 cur_start;
3204         u64 group_type;
3205         u64 group_size;
3206         u64 group_align;
3207         u64 total_data = 0;
3208         u64 total_metadata = 0;
3209         u64 chunk_objectid;
3210         int ret;
3211         int bit;
3212         struct btrfs_root *extent_root;
3213         struct btrfs_block_group_cache *cache;
3214         struct extent_io_tree *block_group_cache;
3215
3216         extent_root = root->fs_info->extent_root;
3217         block_group_cache = &root->fs_info->block_group_cache;
3218         chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3219         total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
3220         group_align = 64 * root->sectorsize;
3221
3222         cur_start = 0;
3223         while (cur_start < total_bytes) {
3224                 group_size = total_bytes / 12;
3225                 group_size = min_t(u64, group_size, total_bytes - cur_start);
3226                 if (cur_start == 0) {
3227                         bit = BLOCK_GROUP_SYSTEM;
3228                         group_type = BTRFS_BLOCK_GROUP_SYSTEM;
3229                         group_size /= 4;
3230                         group_size &= ~(group_align - 1);
3231                         group_size = max_t(u64, group_size, 8 * 1024 * 1024);
3232                         group_size = min_t(u64, group_size, 32 * 1024 * 1024);
3233                 } else {
3234                         group_size &= ~(group_align - 1);
3235                         if (total_data >= total_metadata * 2) {
3236                                 group_type = BTRFS_BLOCK_GROUP_METADATA;
3237                                 group_size = min_t(u64, group_size,
3238                                                    1ULL * 1024 * 1024 * 1024);
3239                                 total_metadata += group_size;
3240                         } else {
3241                                 group_type = BTRFS_BLOCK_GROUP_DATA;
3242                                 group_size = min_t(u64, group_size,
3243                                                    5ULL * 1024 * 1024 * 1024);
3244                                 total_data += group_size;
3245                         }
3246                         if ((total_bytes - cur_start) * 4 < group_size * 5)
3247                                 group_size = total_bytes - cur_start;
3248                 }
3249
3250                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
3251                 BUG_ON(!cache);
3252
3253                 cache->key.objectid = cur_start;
3254                 cache->key.offset = group_size;
3255                 btrfs_set_key_type(&cache->key, BTRFS_BLOCK_GROUP_ITEM_KEY);
3256
3257                 btrfs_set_block_group_used(&cache->item, 0);
3258                 btrfs_set_block_group_chunk_objectid(&cache->item,
3259                                                      chunk_objectid);
3260                 btrfs_set_block_group_flags(&cache->item, group_type);
3261
3262                 cache->flags = group_type;
3263
3264                 ret = update_space_info(root->fs_info, group_type, group_size,
3265                                         0, &cache->space_info);
3266                 BUG_ON(ret);
3267                 set_avail_alloc_bits(extent_root->fs_info, group_type);
3268
3269                 set_extent_bits(block_group_cache, cur_start,
3270                                 cur_start + group_size - 1,
3271                                 bit | EXTENT_LOCKED, GFP_NOFS);
3272                 set_state_private(block_group_cache, cur_start,
3273                                   (unsigned long)cache);
3274                 cur_start += group_size;
3275         }
3276         /* then insert all the items */
3277         cur_start = 0;
3278         while(cur_start < total_bytes) {
3279                 cache = btrfs_lookup_block_group(root->fs_info, cur_start);
3280                 BUG_ON(!cache);
3281
3282                 ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
3283                                         sizeof(cache->item));
3284                 BUG_ON(ret);
3285
3286                 finish_current_insert(trans, extent_root);
3287                 ret = del_pending_extents(trans, extent_root);
3288                 BUG_ON(ret);
3289
3290                 cur_start = cache->key.objectid + cache->key.offset;
3291         }
3292         return 0;
3293 }
3294
3295 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3296                              struct btrfs_root *root,
3297                              u64 bytenr, u64 num_bytes, int alloc,
3298                              int mark_free)
3299 {
3300         return update_block_group(trans, root, bytenr, num_bytes,
3301                                   alloc, mark_free);
3302 }
3303
3304 static int btrfs_count_extents_in_block_group(struct btrfs_root *root,
3305                                               struct btrfs_path *path, u64 start,
3306                                               u64 len,
3307                                               u64 *total)
3308 {
3309         struct btrfs_key key;
3310         struct extent_buffer *leaf;
3311         u64 bytes_used = 0;
3312         int ret;
3313         int slot;
3314
3315         key.offset = 0;
3316         key.objectid = start;
3317         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
3318         ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
3319                                 &key, path, 0, 0);
3320         if (ret < 0)
3321                 return ret;
3322         while(1) {
3323                 leaf = path->nodes[0];
3324                 slot = path->slots[0];
3325                 if (slot >= btrfs_header_nritems(leaf)) {
3326                         ret = btrfs_next_leaf(root, path);
3327                         if (ret < 0)
3328                                 return ret;
3329                         if (ret > 0)
3330                                 break;
3331                         leaf = path->nodes[0];
3332                         slot = path->slots[0];
3333                 }
3334                 btrfs_item_key_to_cpu(leaf, &key, slot);
3335                 if (key.objectid > start + len)
3336                         break;
3337                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3338                         bytes_used += key.offset;
3339                 path->slots[0]++;
3340         }
3341         *total = bytes_used;
3342         btrfs_release_path(root, path);
3343         return 0;
3344 }
3345
3346 int btrfs_check_block_accounting(struct btrfs_root *root)
3347 {
3348         int ret;
3349         u64 start = 0;
3350         u64 bytes_used = 0;
3351         struct btrfs_path path;
3352         struct btrfs_block_group_cache *cache;
3353         struct btrfs_fs_info *fs_info = root->fs_info;
3354
3355         btrfs_init_path(&path);
3356
3357         while(1) {
3358                 cache = btrfs_lookup_block_group(fs_info, start);
3359                 if (!cache)
3360                         break;
3361
3362                 ret = btrfs_count_extents_in_block_group(root, &path,
3363                                                          cache->key.objectid,
3364                                                          cache->key.offset,
3365                                                          &bytes_used);
3366
3367                 if (ret == 0) {
3368                         u64 on_disk = btrfs_block_group_used(&cache->item);
3369                         if (on_disk != bytes_used) {
3370                                 fprintf(stderr, "bad block group accounting found %llu "
3371                                         "expected %llu block group %llu\n",
3372                                         (unsigned long long)bytes_used,
3373                                         (unsigned long long)on_disk,
3374                                         (unsigned long long)cache->key.objectid);
3375                         }
3376                 }
3377                 start = cache->key.objectid + cache->key.offset;
3378
3379                 cache->space_info->bytes_used = 0;
3380         }
3381         return 0;
3382 }
3383
3384 /*
3385  * Fixup block accounting. The initial block accounting created by
3386  * make_block_groups isn't accuracy in this case.
3387  */
3388 int btrfs_fix_block_accounting(struct btrfs_trans_handle *trans,
3389                                struct btrfs_root *root)
3390 {
3391         int ret;
3392         int slot;
3393         u64 start = 0;
3394         u64 bytes_used = 0;
3395         struct btrfs_path path;
3396         struct btrfs_key key;
3397         struct extent_buffer *leaf;
3398         struct btrfs_block_group_cache *cache;
3399         struct btrfs_fs_info *fs_info = root->fs_info;
3400
3401         root = root->fs_info->extent_root;
3402
3403         while(extent_root_pending_ops(fs_info)) {
3404                 ret = finish_current_insert(trans, root);
3405                 if (ret)
3406                         return ret;
3407                 ret = del_pending_extents(trans, root);
3408                 if (ret)
3409                         return ret;
3410         }
3411
3412         while(1) {
3413                 cache = btrfs_lookup_block_group(fs_info, start);
3414                 if (!cache)
3415                         break;
3416                 start = cache->key.objectid + cache->key.offset;
3417                 btrfs_set_block_group_used(&cache->item, 0);
3418                 cache->space_info->bytes_used = 0;
3419                 set_extent_bits(&root->fs_info->block_group_cache,
3420                                 cache->key.objectid,
3421                                 cache->key.objectid + cache->key.offset -1,
3422                                 BLOCK_GROUP_DIRTY, GFP_NOFS);
3423         }
3424
3425         btrfs_init_path(&path);
3426         key.offset = 0;
3427         key.objectid = 0;
3428         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
3429         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
3430                                 &key, &path, 0, 0);
3431         if (ret < 0)
3432                 return ret;
3433         while(1) {
3434                 leaf = path.nodes[0];
3435                 slot = path.slots[0];
3436                 if (slot >= btrfs_header_nritems(leaf)) {
3437                         ret = btrfs_next_leaf(root, &path);
3438                         if (ret < 0)
3439                                 return ret;
3440                         if (ret > 0)
3441                                 break;
3442                         leaf = path.nodes[0];
3443                         slot = path.slots[0];
3444                 }
3445                 btrfs_item_key_to_cpu(leaf, &key, slot);
3446                 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
3447                         bytes_used += key.offset;
3448                         ret = btrfs_update_block_group(trans, root,
3449                                   key.objectid, key.offset, 1, 0);
3450                         BUG_ON(ret);
3451                 }
3452                 path.slots[0]++;
3453         }
3454         btrfs_set_super_bytes_used(&root->fs_info->super_copy, bytes_used);
3455         btrfs_release_path(root, &path);
3456         return 0;
3457 }