Fix btrfs_inc_ref to add backref hints
[linux-2.6-block.git] / fs / btrfs / 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 <linux/sched.h>
20 #include <linux/crc32c.h>
21 #include "hash.h"
22 #include "ctree.h"
23 #include "disk-io.h"
24 #include "print-tree.h"
25 #include "transaction.h"
26
27 #define BLOCK_GROUP_DATA EXTENT_WRITEBACK
28 #define BLOCK_GROUP_METADATA EXTENT_UPTODATE
29 #define BLOCK_GROUP_DIRTY EXTENT_DIRTY
30
31 static int finish_current_insert(struct btrfs_trans_handle *trans, struct
32                                  btrfs_root *extent_root);
33 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
34                                btrfs_root *extent_root);
35
36 static int cache_block_group(struct btrfs_root *root,
37                              struct btrfs_block_group_cache *block_group)
38 {
39         struct btrfs_path *path;
40         int ret;
41         struct btrfs_key key;
42         struct extent_buffer *leaf;
43         struct extent_map_tree *free_space_cache;
44         int slot;
45         u64 last = 0;
46         u64 hole_size;
47         u64 first_free;
48         int found = 0;
49
50         if (!block_group)
51                 return 0;
52
53         root = root->fs_info->extent_root;
54         free_space_cache = &root->fs_info->free_space_cache;
55
56         if (block_group->cached)
57                 return 0;
58
59         path = btrfs_alloc_path();
60         if (!path)
61                 return -ENOMEM;
62
63         path->reada = 2;
64         first_free = block_group->key.objectid;
65         key.objectid = block_group->key.objectid;
66         key.offset = 0;
67
68         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
69         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
70
71         if (ret < 0)
72                 return ret;
73
74         if (ret && path->slots[0] > 0)
75                 path->slots[0]--;
76
77         while(1) {
78                 leaf = path->nodes[0];
79                 slot = path->slots[0];
80                 if (slot >= btrfs_header_nritems(leaf)) {
81                         ret = btrfs_next_leaf(root, path);
82                         if (ret < 0)
83                                 goto err;
84                         if (ret == 0) {
85                                 continue;
86                         } else {
87                                 break;
88                         }
89                 }
90
91                 btrfs_item_key_to_cpu(leaf, &key, slot);
92                 if (key.objectid < block_group->key.objectid) {
93                         if (btrfs_key_type(&key) != BTRFS_EXTENT_REF_KEY &&
94                             key.objectid + key.offset > first_free)
95                                 first_free = key.objectid + key.offset;
96                         goto next;
97                 }
98
99                 if (key.objectid >= block_group->key.objectid +
100                     block_group->key.offset) {
101                         break;
102                 }
103
104                 if (btrfs_key_type(&key) == BTRFS_EXTENT_ITEM_KEY) {
105                         if (!found) {
106                                 last = first_free;
107                                 found = 1;
108                         }
109                         if (key.objectid > last) {
110                                 hole_size = key.objectid - last;
111                                 set_extent_dirty(free_space_cache, last,
112                                                  last + hole_size - 1,
113                                                  GFP_NOFS);
114                         }
115                         last = key.objectid + key.offset;
116                 }
117 next:
118                 path->slots[0]++;
119         }
120
121         if (!found)
122                 last = first_free;
123         if (block_group->key.objectid +
124             block_group->key.offset > last) {
125                 hole_size = block_group->key.objectid +
126                         block_group->key.offset - last;
127                 set_extent_dirty(free_space_cache, last,
128                                  last + hole_size - 1, GFP_NOFS);
129         }
130         block_group->cached = 1;
131 err:
132         btrfs_free_path(path);
133         return 0;
134 }
135
136 struct btrfs_block_group_cache *btrfs_lookup_block_group(struct
137                                                          btrfs_fs_info *info,
138                                                          u64 bytenr)
139 {
140         struct extent_map_tree *block_group_cache;
141         struct btrfs_block_group_cache *block_group = NULL;
142         u64 ptr;
143         u64 start;
144         u64 end;
145         int ret;
146
147         block_group_cache = &info->block_group_cache;
148         ret = find_first_extent_bit(block_group_cache,
149                                     bytenr, &start, &end,
150                                     BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA);
151         if (ret) {
152                 return NULL;
153         }
154         ret = get_state_private(block_group_cache, start, &ptr);
155         if (ret)
156                 return NULL;
157
158         block_group = (struct btrfs_block_group_cache *)(unsigned long)ptr;
159         if (block_group->key.objectid <= bytenr && bytenr <
160             block_group->key.objectid + block_group->key.offset)
161                 return block_group;
162         return NULL;
163 }
164 static u64 find_search_start(struct btrfs_root *root,
165                              struct btrfs_block_group_cache **cache_ret,
166                              u64 search_start, int num,
167                              int data, int full_scan)
168 {
169         int ret;
170         struct btrfs_block_group_cache *cache = *cache_ret;
171         u64 last;
172         u64 start = 0;
173         u64 end = 0;
174         u64 cache_miss = 0;
175         int wrapped = 0;
176
177         if (!cache) {
178                 goto out;
179         }
180 again:
181         ret = cache_block_group(root, cache);
182         if (ret)
183                 goto out;
184
185         last = max(search_start, cache->key.objectid);
186
187         while(1) {
188                 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
189                                             last, &start, &end, EXTENT_DIRTY);
190                 if (ret) {
191                         if (!cache_miss)
192                                 cache_miss = last;
193                         goto new_group;
194                 }
195
196                 start = max(last, start);
197                 last = end + 1;
198                 if (last - start < num) {
199                         if (last == cache->key.objectid + cache->key.offset)
200                                 cache_miss = start;
201                         continue;
202                 }
203                 if (data != BTRFS_BLOCK_GROUP_MIXED &&
204                     start + num > cache->key.objectid + cache->key.offset)
205                         goto new_group;
206                 return start;
207         }
208 out:
209         cache = btrfs_lookup_block_group(root->fs_info, search_start);
210         if (!cache) {
211                 printk("Unable to find block group for %Lu\n",
212                        search_start);
213                 WARN_ON(1);
214                 return search_start;
215         }
216         return search_start;
217
218 new_group:
219         last = cache->key.objectid + cache->key.offset;
220 wrapped:
221         cache = btrfs_lookup_block_group(root->fs_info, last);
222         if (!cache) {
223 no_cache:
224                 if (!wrapped) {
225                         wrapped = 1;
226                         last = search_start;
227                         data = BTRFS_BLOCK_GROUP_MIXED;
228                         goto wrapped;
229                 }
230                 goto out;
231         }
232         if (cache_miss && !cache->cached) {
233                 cache_block_group(root, cache);
234                 last = cache_miss;
235                 cache = btrfs_lookup_block_group(root->fs_info, last);
236         }
237         cache = btrfs_find_block_group(root, cache, last, data, 0);
238         if (!cache)
239                 goto no_cache;
240         *cache_ret = cache;
241         cache_miss = 0;
242         goto again;
243 }
244
245 static u64 div_factor(u64 num, int factor)
246 {
247         if (factor == 10)
248                 return num;
249         num *= factor;
250         do_div(num, 10);
251         return num;
252 }
253
254 struct btrfs_block_group_cache *btrfs_find_block_group(struct btrfs_root *root,
255                                                  struct btrfs_block_group_cache
256                                                  *hint, u64 search_start,
257                                                  int data, int owner)
258 {
259         struct btrfs_block_group_cache *cache;
260         struct extent_map_tree *block_group_cache;
261         struct btrfs_block_group_cache *found_group = NULL;
262         struct btrfs_fs_info *info = root->fs_info;
263         u64 used;
264         u64 last = 0;
265         u64 hint_last;
266         u64 start;
267         u64 end;
268         u64 free_check;
269         u64 ptr;
270         int bit;
271         int ret;
272         int full_search = 0;
273         int factor = 8;
274         int data_swap = 0;
275
276         block_group_cache = &info->block_group_cache;
277
278         if (!owner)
279                 factor = 8;
280
281         if (data == BTRFS_BLOCK_GROUP_MIXED) {
282                 bit = BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA;
283                 factor = 10;
284         } else if (data)
285                 bit = BLOCK_GROUP_DATA;
286         else
287                 bit = BLOCK_GROUP_METADATA;
288
289         if (search_start) {
290                 struct btrfs_block_group_cache *shint;
291                 shint = btrfs_lookup_block_group(info, search_start);
292                 if (shint && (shint->data == data ||
293                               shint->data == BTRFS_BLOCK_GROUP_MIXED)) {
294                         used = btrfs_block_group_used(&shint->item);
295                         if (used + shint->pinned <
296                             div_factor(shint->key.offset, factor)) {
297                                 return shint;
298                         }
299                 }
300         }
301         if (hint && (hint->data == data ||
302                      hint->data == BTRFS_BLOCK_GROUP_MIXED)) {
303                 used = btrfs_block_group_used(&hint->item);
304                 if (used + hint->pinned <
305                     div_factor(hint->key.offset, factor)) {
306                         return hint;
307                 }
308                 last = hint->key.objectid + hint->key.offset;
309                 hint_last = last;
310         } else {
311                 if (hint)
312                         hint_last = max(hint->key.objectid, search_start);
313                 else
314                         hint_last = search_start;
315
316                 last = hint_last;
317         }
318 again:
319         while(1) {
320                 ret = find_first_extent_bit(block_group_cache, last,
321                                             &start, &end, bit);
322                 if (ret)
323                         break;
324
325                 ret = get_state_private(block_group_cache, start, &ptr);
326                 if (ret)
327                         break;
328
329                 cache = (struct btrfs_block_group_cache *)(unsigned long)ptr;
330                 last = cache->key.objectid + cache->key.offset;
331                 used = btrfs_block_group_used(&cache->item);
332
333                 if (full_search)
334                         free_check = cache->key.offset;
335                 else
336                         free_check = div_factor(cache->key.offset, factor);
337                 if (used + cache->pinned < free_check) {
338                         found_group = cache;
339                         goto found;
340                 }
341                 cond_resched();
342         }
343         if (!full_search) {
344                 last = search_start;
345                 full_search = 1;
346                 goto again;
347         }
348         if (!data_swap) {
349                 data_swap = 1;
350                 bit = BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA;
351                 last = search_start;
352                 goto again;
353         }
354 found:
355         return found_group;
356 }
357
358 static u64 hash_extent_ref(u64 root_objectid, u64 ref_generation,
359                            u64 owner, u64 owner_offset)
360 {
361         u32 high_crc = ~(u32)0;
362         u32 low_crc = ~(u32)0;
363         __le64 lenum;
364
365         lenum = cpu_to_le64(root_objectid);
366         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
367         lenum = cpu_to_le64(ref_generation);
368         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
369
370 #if 0
371         lenum = cpu_to_le64(owner);
372         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
373         lenum = cpu_to_le64(owner_offset);
374         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
375 #endif
376         return ((u64)high_crc << 32) | (u64)low_crc;
377 }
378
379 static int match_extent_ref(struct extent_buffer *leaf,
380                             struct btrfs_extent_ref *disk_ref,
381                             struct btrfs_extent_ref *cpu_ref)
382 {
383         int ret;
384         int len;
385
386         if (cpu_ref->objectid)
387                 len = sizeof(*cpu_ref);
388         else
389                 len = 2 * sizeof(u64);
390         ret = memcmp_extent_buffer(leaf, cpu_ref, (unsigned long)disk_ref,
391                                    len);
392         return ret == 0;
393 }
394
395 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
396                                  struct btrfs_root *root,
397                                  struct btrfs_path *path, u64 bytenr,
398                                  u64 root_objectid, u64 ref_generation,
399                                  u64 owner, u64 owner_offset, int del)
400 {
401         u64 hash;
402         struct btrfs_key key;
403         struct btrfs_key found_key;
404         struct btrfs_extent_ref ref;
405         struct extent_buffer *leaf;
406         struct btrfs_extent_ref *disk_ref;
407         int ret;
408         int ret2;
409
410         btrfs_set_stack_ref_root(&ref, root_objectid);
411         btrfs_set_stack_ref_generation(&ref, ref_generation);
412         btrfs_set_stack_ref_objectid(&ref, owner);
413         btrfs_set_stack_ref_offset(&ref, owner_offset);
414
415         hash = hash_extent_ref(root_objectid, ref_generation, owner,
416                                owner_offset);
417         key.offset = hash;
418         key.objectid = bytenr;
419         key.type = BTRFS_EXTENT_REF_KEY;
420
421         while (1) {
422                 ret = btrfs_search_slot(trans, root, &key, path,
423                                         del ? -1 : 0, del);
424                 if (ret < 0)
425                         goto out;
426                 leaf = path->nodes[0];
427                 if (ret != 0) {
428                         u32 nritems = btrfs_header_nritems(leaf);
429                         if (path->slots[0] >= nritems) {
430                                 ret2 = btrfs_next_leaf(root, path);
431                                 if (ret2)
432                                         goto out;
433                                 leaf = path->nodes[0];
434                         }
435                         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
436                         if (found_key.objectid != bytenr ||
437                             found_key.type != BTRFS_EXTENT_REF_KEY)
438                                 goto out;
439                         key.offset = found_key.offset;
440                         if (del) {
441                                 btrfs_release_path(root, path);
442                                 continue;
443                         }
444                 }
445                 disk_ref = btrfs_item_ptr(path->nodes[0],
446                                           path->slots[0],
447                                           struct btrfs_extent_ref);
448                 if (match_extent_ref(path->nodes[0], disk_ref, &ref)) {
449                         ret = 0;
450                         goto out;
451                 }
452                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
453                 key.offset = found_key.offset + 1;
454                 btrfs_release_path(root, path);
455         }
456 out:
457         return ret;
458 }
459
460 /*
461  * Back reference rules.  Back refs have three main goals:
462  *
463  * 1) differentiate between all holders of references to an extent so that
464  *    when a reference is dropped we can make sure it was a valid reference
465  *    before freeing the extent.
466  *
467  * 2) Provide enough information to quickly find the holders of an extent
468  *    if we notice a given block is corrupted or bad.
469  *
470  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
471  *    maintenance.  This is actually the same as #2, but with a slightly
472  *    different use case.
473  *
474  * File extents can be referenced by:
475  *
476  * - multiple snapshots, subvolumes, or different generations in one subvol
477  * - different files inside a single subvolume (in theory, not implemented yet)
478  * - different offsets inside a file (bookend extents in file.c)
479  *
480  * The extent ref structure has fields for:
481  *
482  * - Objectid of the subvolume root
483  * - Generation number of the tree holding the reference
484  * - objectid of the file holding the reference
485  * - offset in the file corresponding to the key holding the reference
486  *
487  * When a file extent is allocated the fields are filled in:
488  *     (root_key.objectid, trans->transid, inode objectid, offset in file)
489  *
490  * When a leaf is cow'd new references are added for every file extent found
491  * in the leaf.  It looks the same as the create case, but trans->transid
492  * will be different when the block is cow'd.
493  *
494  *     (root_key.objectid, trans->transid, inode objectid, offset in file)
495  *
496  * When a file extent is removed either during snapshot deletion or file
497  * truncation, the corresponding back reference is found
498  * by searching for:
499  *
500  *     (btrfs_header_owner(leaf), btrfs_header_generation(leaf),
501  *      inode objectid, offset in file)
502  *
503  * Btree extents can be referenced by:
504  *
505  * - Different subvolumes
506  * - Different generations of the same subvolume
507  *
508  * Storing sufficient information for a full reverse mapping of a btree
509  * block would require storing the lowest key of the block in the backref,
510  * and it would require updating that lowest key either before write out or
511  * every time it changed.  Instead, the objectid of the lowest key is stored
512  * along with the level of the tree block.  This provides a hint
513  * about where in the btree the block can be found.  Searches through the
514  * btree only need to look for a pointer to that block, so they stop one
515  * level higher than the level recorded in the backref.
516  *
517  * Some btrees do not do reference counting on their extents.  These
518  * include the extent tree and the tree of tree roots.  Backrefs for these
519  * trees always have a generation of zero.
520  *
521  * When a tree block is created, back references are inserted:
522  *
523  * (root->root_key.objectid, trans->transid or zero, lowest_key_objectid, level)
524  *
525  * When a tree block is cow'd in a reference counted root,
526  * new back references are added for all the blocks it points to.
527  * These are of the form (trans->transid will have increased since creation):
528  *
529  * (root->root_key.objectid, trans->transid, lowest_key_objectid, level)
530  *
531  * Because the lowest_key_objectid and the level are just hints
532  * they are not used when backrefs are deleted.  When a backref is deleted:
533  *
534  * if backref was for a tree root:
535  *     root_objectid = root->root_key.objectid
536  * else
537  *     root_objectid = btrfs_header_owner(parent)
538  *
539  * (root_objectid, btrfs_header_generation(parent) or zero, 0, 0)
540  *
541  * Back Reference Key hashing:
542  *
543  * Back references have four fields, each 64 bits long.  Unfortunately,
544  * This is hashed into a single 64 bit number and placed into the key offset.
545  * The key objectid corresponds to the first byte in the extent, and the
546  * key type is set to BTRFS_EXTENT_REF_KEY
547  */
548 int btrfs_insert_extent_backref(struct btrfs_trans_handle *trans,
549                                  struct btrfs_root *root,
550                                  struct btrfs_path *path, u64 bytenr,
551                                  u64 root_objectid, u64 ref_generation,
552                                  u64 owner, u64 owner_offset)
553 {
554         u64 hash;
555         struct btrfs_key key;
556         struct btrfs_extent_ref ref;
557         struct btrfs_extent_ref *disk_ref;
558         int ret;
559
560         btrfs_set_stack_ref_root(&ref, root_objectid);
561         btrfs_set_stack_ref_generation(&ref, ref_generation);
562         btrfs_set_stack_ref_objectid(&ref, owner);
563         btrfs_set_stack_ref_offset(&ref, owner_offset);
564
565         hash = hash_extent_ref(root_objectid, ref_generation, owner,
566                                owner_offset);
567         key.offset = hash;
568         key.objectid = bytenr;
569         key.type = BTRFS_EXTENT_REF_KEY;
570
571         ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(ref));
572         while (ret == -EEXIST) {
573                 disk_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
574                                           struct btrfs_extent_ref);
575                 if (match_extent_ref(path->nodes[0], disk_ref, &ref))
576                         goto out;
577                 key.offset++;
578                 btrfs_release_path(root, path);
579                 ret = btrfs_insert_empty_item(trans, root, path, &key,
580                                               sizeof(ref));
581         }
582         if (ret)
583                 goto out;
584         disk_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
585                                   struct btrfs_extent_ref);
586         write_extent_buffer(path->nodes[0], &ref, (unsigned long)disk_ref,
587                             sizeof(ref));
588         btrfs_mark_buffer_dirty(path->nodes[0]);
589 out:
590         btrfs_release_path(root, path);
591         return ret;
592 }
593
594 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
595                                 struct btrfs_root *root,
596                                 u64 bytenr, u64 num_bytes,
597                                 u64 root_objectid, u64 ref_generation,
598                                 u64 owner, u64 owner_offset)
599 {
600         struct btrfs_path *path;
601         int ret;
602         struct btrfs_key key;
603         struct extent_buffer *l;
604         struct btrfs_extent_item *item;
605         u32 refs;
606
607         WARN_ON(num_bytes < root->sectorsize);
608         path = btrfs_alloc_path();
609         if (!path)
610                 return -ENOMEM;
611
612         key.objectid = bytenr;
613         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
614         key.offset = num_bytes;
615         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
616                                 0, 1);
617         if (ret < 0)
618                 return ret;
619         if (ret != 0) {
620                 BUG();
621         }
622         BUG_ON(ret != 0);
623         l = path->nodes[0];
624         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
625         refs = btrfs_extent_refs(l, item);
626         btrfs_set_extent_refs(l, item, refs + 1);
627         btrfs_mark_buffer_dirty(path->nodes[0]);
628
629         btrfs_release_path(root->fs_info->extent_root, path);
630
631         ret = btrfs_insert_extent_backref(trans, root->fs_info->extent_root,
632                                           path, bytenr, root_objectid,
633                                           ref_generation, owner, owner_offset);
634         BUG_ON(ret);
635         finish_current_insert(trans, root->fs_info->extent_root);
636         del_pending_extents(trans, root->fs_info->extent_root);
637
638         btrfs_free_path(path);
639         return 0;
640 }
641
642 int btrfs_extent_post_op(struct btrfs_trans_handle *trans,
643                          struct btrfs_root *root)
644 {
645         finish_current_insert(trans, root->fs_info->extent_root);
646         del_pending_extents(trans, root->fs_info->extent_root);
647         return 0;
648 }
649
650 static int lookup_extent_ref(struct btrfs_trans_handle *trans,
651                              struct btrfs_root *root, u64 bytenr,
652                              u64 num_bytes, u32 *refs)
653 {
654         struct btrfs_path *path;
655         int ret;
656         struct btrfs_key key;
657         struct extent_buffer *l;
658         struct btrfs_extent_item *item;
659
660         WARN_ON(num_bytes < root->sectorsize);
661         path = btrfs_alloc_path();
662         key.objectid = bytenr;
663         key.offset = num_bytes;
664         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
665         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
666                                 0, 0);
667         if (ret < 0)
668                 goto out;
669         if (ret != 0) {
670                 btrfs_print_leaf(root, path->nodes[0]);
671                 printk("failed to find block number %Lu\n", bytenr);
672                 BUG();
673         }
674         l = path->nodes[0];
675         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
676         *refs = btrfs_extent_refs(l, item);
677 out:
678         btrfs_free_path(path);
679         return 0;
680 }
681
682 int btrfs_inc_root_ref(struct btrfs_trans_handle *trans,
683                        struct btrfs_root *root, u64 owner_objectid)
684 {
685         u64 generation;
686         u64 key_objectid;
687         u64 level;
688         u32 nritems;
689         struct btrfs_disk_key disk_key;
690
691         level = btrfs_header_level(root->node);
692         generation = trans->transid;
693         nritems = btrfs_header_nritems(root->node);
694         if (nritems > 0) {
695                 if (level == 0)
696                         btrfs_item_key(root->node, &disk_key, 0);
697                 else
698                         btrfs_node_key(root->node, &disk_key, 0);
699                 key_objectid = btrfs_disk_key_objectid(&disk_key);
700         } else {
701                 key_objectid = 0;
702         }
703         return btrfs_inc_extent_ref(trans, root, root->node->start,
704                                     root->node->len, owner_objectid,
705                                     generation, key_objectid, level);
706 }
707
708 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
709                   struct extent_buffer *buf)
710 {
711         u64 bytenr;
712         u32 nritems;
713         struct btrfs_key key;
714         struct btrfs_file_extent_item *fi;
715         int i;
716         int level;
717         int ret;
718         int faili;
719
720         if (!root->ref_cows)
721                 return 0;
722
723         level = btrfs_header_level(buf);
724         nritems = btrfs_header_nritems(buf);
725         for (i = 0; i < nritems; i++) {
726                 if (level == 0) {
727                         u64 disk_bytenr;
728                         btrfs_item_key_to_cpu(buf, &key, i);
729                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
730                                 continue;
731                         fi = btrfs_item_ptr(buf, i,
732                                             struct btrfs_file_extent_item);
733                         if (btrfs_file_extent_type(buf, fi) ==
734                             BTRFS_FILE_EXTENT_INLINE)
735                                 continue;
736                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
737                         if (disk_bytenr == 0)
738                                 continue;
739                         ret = btrfs_inc_extent_ref(trans, root, disk_bytenr,
740                                     btrfs_file_extent_disk_num_bytes(buf, fi),
741                                     root->root_key.objectid, trans->transid,
742                                     key.objectid, key.offset);
743                         if (ret) {
744                                 faili = i;
745                                 goto fail;
746                         }
747                 } else {
748                         bytenr = btrfs_node_blockptr(buf, i);
749                         btrfs_node_key_to_cpu(buf, &key, i);
750                         ret = btrfs_inc_extent_ref(trans, root, bytenr,
751                                            btrfs_level_size(root, level - 1),
752                                            root->root_key.objectid,
753                                            trans->transid, key.objectid,
754                                            level - 1);
755                         if (ret) {
756                                 faili = i;
757                                 goto fail;
758                         }
759                 }
760         }
761         return 0;
762 fail:
763         WARN_ON(1);
764 #if 0
765         for (i =0; i < faili; i++) {
766                 if (level == 0) {
767                         u64 disk_bytenr;
768                         btrfs_item_key_to_cpu(buf, &key, i);
769                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
770                                 continue;
771                         fi = btrfs_item_ptr(buf, i,
772                                             struct btrfs_file_extent_item);
773                         if (btrfs_file_extent_type(buf, fi) ==
774                             BTRFS_FILE_EXTENT_INLINE)
775                                 continue;
776                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
777                         if (disk_bytenr == 0)
778                                 continue;
779                         err = btrfs_free_extent(trans, root, disk_bytenr,
780                                     btrfs_file_extent_disk_num_bytes(buf,
781                                                                       fi), 0);
782                         BUG_ON(err);
783                 } else {
784                         bytenr = btrfs_node_blockptr(buf, i);
785                         err = btrfs_free_extent(trans, root, bytenr,
786                                         btrfs_level_size(root, level - 1), 0);
787                         BUG_ON(err);
788                 }
789         }
790 #endif
791         return ret;
792 }
793
794 static int write_one_cache_group(struct btrfs_trans_handle *trans,
795                                  struct btrfs_root *root,
796                                  struct btrfs_path *path,
797                                  struct btrfs_block_group_cache *cache)
798 {
799         int ret;
800         int pending_ret;
801         struct btrfs_root *extent_root = root->fs_info->extent_root;
802         unsigned long bi;
803         struct extent_buffer *leaf;
804
805         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
806         if (ret < 0)
807                 goto fail;
808         BUG_ON(ret);
809
810         leaf = path->nodes[0];
811         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
812         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
813         btrfs_mark_buffer_dirty(leaf);
814         btrfs_release_path(extent_root, path);
815 fail:
816         finish_current_insert(trans, extent_root);
817         pending_ret = del_pending_extents(trans, extent_root);
818         if (ret)
819                 return ret;
820         if (pending_ret)
821                 return pending_ret;
822         return 0;
823
824 }
825
826 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
827                                    struct btrfs_root *root)
828 {
829         struct extent_map_tree *block_group_cache;
830         struct btrfs_block_group_cache *cache;
831         int ret;
832         int err = 0;
833         int werr = 0;
834         struct btrfs_path *path;
835         u64 last = 0;
836         u64 start;
837         u64 end;
838         u64 ptr;
839
840         block_group_cache = &root->fs_info->block_group_cache;
841         path = btrfs_alloc_path();
842         if (!path)
843                 return -ENOMEM;
844
845         while(1) {
846                 ret = find_first_extent_bit(block_group_cache, last,
847                                             &start, &end, BLOCK_GROUP_DIRTY);
848                 if (ret)
849                         break;
850
851                 last = end + 1;
852                 ret = get_state_private(block_group_cache, start, &ptr);
853                 if (ret)
854                         break;
855
856                 cache = (struct btrfs_block_group_cache *)(unsigned long)ptr;
857                 err = write_one_cache_group(trans, root,
858                                             path, cache);
859                 /*
860                  * if we fail to write the cache group, we want
861                  * to keep it marked dirty in hopes that a later
862                  * write will work
863                  */
864                 if (err) {
865                         werr = err;
866                         continue;
867                 }
868                 clear_extent_bits(block_group_cache, start, end,
869                                   BLOCK_GROUP_DIRTY, GFP_NOFS);
870         }
871         btrfs_free_path(path);
872         return werr;
873 }
874
875 static int update_block_group(struct btrfs_trans_handle *trans,
876                               struct btrfs_root *root,
877                               u64 bytenr, u64 num_bytes, int alloc,
878                               int mark_free, int data)
879 {
880         struct btrfs_block_group_cache *cache;
881         struct btrfs_fs_info *info = root->fs_info;
882         u64 total = num_bytes;
883         u64 old_val;
884         u64 byte_in_group;
885         u64 start;
886         u64 end;
887
888         while(total) {
889                 cache = btrfs_lookup_block_group(info, bytenr);
890                 if (!cache) {
891                         return -1;
892                 }
893                 byte_in_group = bytenr - cache->key.objectid;
894                 WARN_ON(byte_in_group > cache->key.offset);
895                 start = cache->key.objectid;
896                 end = start + cache->key.offset - 1;
897                 set_extent_bits(&info->block_group_cache, start, end,
898                                 BLOCK_GROUP_DIRTY, GFP_NOFS);
899
900                 old_val = btrfs_block_group_used(&cache->item);
901                 num_bytes = min(total, cache->key.offset - byte_in_group);
902                 if (alloc) {
903                         if (cache->data != data &&
904                             old_val < (cache->key.offset >> 1)) {
905                                 int bit_to_clear;
906                                 int bit_to_set;
907                                 cache->data = data;
908                                 if (data) {
909                                         bit_to_clear = BLOCK_GROUP_METADATA;
910                                         bit_to_set = BLOCK_GROUP_DATA;
911                                         cache->item.flags &=
912                                                 ~BTRFS_BLOCK_GROUP_MIXED;
913                                         cache->item.flags |=
914                                                 BTRFS_BLOCK_GROUP_DATA;
915                                 } else {
916                                         bit_to_clear = BLOCK_GROUP_DATA;
917                                         bit_to_set = BLOCK_GROUP_METADATA;
918                                         cache->item.flags &=
919                                                 ~BTRFS_BLOCK_GROUP_MIXED;
920                                         cache->item.flags &=
921                                                 ~BTRFS_BLOCK_GROUP_DATA;
922                                 }
923                                 clear_extent_bits(&info->block_group_cache,
924                                                   start, end, bit_to_clear,
925                                                   GFP_NOFS);
926                                 set_extent_bits(&info->block_group_cache,
927                                                 start, end, bit_to_set,
928                                                 GFP_NOFS);
929                         } else if (cache->data != data &&
930                                    cache->data != BTRFS_BLOCK_GROUP_MIXED) {
931                                 cache->data = BTRFS_BLOCK_GROUP_MIXED;
932                                 set_extent_bits(&info->block_group_cache,
933                                                 start, end,
934                                                 BLOCK_GROUP_DATA |
935                                                 BLOCK_GROUP_METADATA,
936                                                 GFP_NOFS);
937                         }
938                         old_val += num_bytes;
939                 } else {
940                         old_val -= num_bytes;
941                         if (mark_free) {
942                                 set_extent_dirty(&info->free_space_cache,
943                                                  bytenr, bytenr + num_bytes - 1,
944                                                  GFP_NOFS);
945                         }
946                 }
947                 btrfs_set_block_group_used(&cache->item, old_val);
948                 total -= num_bytes;
949                 bytenr += num_bytes;
950         }
951         return 0;
952 }
953 static int update_pinned_extents(struct btrfs_root *root,
954                                 u64 bytenr, u64 num, int pin)
955 {
956         u64 len;
957         struct btrfs_block_group_cache *cache;
958         struct btrfs_fs_info *fs_info = root->fs_info;
959
960         if (pin) {
961                 set_extent_dirty(&fs_info->pinned_extents,
962                                 bytenr, bytenr + num - 1, GFP_NOFS);
963         } else {
964                 clear_extent_dirty(&fs_info->pinned_extents,
965                                 bytenr, bytenr + num - 1, GFP_NOFS);
966         }
967         while (num > 0) {
968                 cache = btrfs_lookup_block_group(fs_info, bytenr);
969                 WARN_ON(!cache);
970                 len = min(num, cache->key.offset -
971                           (bytenr - cache->key.objectid));
972                 if (pin) {
973                         cache->pinned += len;
974                         fs_info->total_pinned += len;
975                 } else {
976                         cache->pinned -= len;
977                         fs_info->total_pinned -= len;
978                 }
979                 bytenr += len;
980                 num -= len;
981         }
982         return 0;
983 }
984
985 int btrfs_copy_pinned(struct btrfs_root *root, struct extent_map_tree *copy)
986 {
987         u64 last = 0;
988         u64 start;
989         u64 end;
990         struct extent_map_tree *pinned_extents = &root->fs_info->pinned_extents;
991         int ret;
992
993         while(1) {
994                 ret = find_first_extent_bit(pinned_extents, last,
995                                             &start, &end, EXTENT_DIRTY);
996                 if (ret)
997                         break;
998                 set_extent_dirty(copy, start, end, GFP_NOFS);
999                 last = end + 1;
1000         }
1001         return 0;
1002 }
1003
1004 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
1005                                struct btrfs_root *root,
1006                                struct extent_map_tree *unpin)
1007 {
1008         u64 start;
1009         u64 end;
1010         int ret;
1011         struct extent_map_tree *free_space_cache;
1012         free_space_cache = &root->fs_info->free_space_cache;
1013
1014         while(1) {
1015                 ret = find_first_extent_bit(unpin, 0, &start, &end,
1016                                             EXTENT_DIRTY);
1017                 if (ret)
1018                         break;
1019                 update_pinned_extents(root, start, end + 1 - start, 0);
1020                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
1021                 set_extent_dirty(free_space_cache, start, end, GFP_NOFS);
1022         }
1023         return 0;
1024 }
1025
1026 static int finish_current_insert(struct btrfs_trans_handle *trans, struct
1027                                  btrfs_root *extent_root)
1028 {
1029         u64 start;
1030         u64 end;
1031         struct btrfs_fs_info *info = extent_root->fs_info;
1032         struct extent_buffer *eb;
1033         struct btrfs_path *path;
1034         struct btrfs_key ins;
1035         struct btrfs_disk_key first;
1036         struct btrfs_extent_item extent_item;
1037         int ret;
1038         int level;
1039         int err = 0;
1040
1041         btrfs_set_stack_extent_refs(&extent_item, 1);
1042         btrfs_set_key_type(&ins, BTRFS_EXTENT_ITEM_KEY);
1043         path = btrfs_alloc_path();
1044
1045         while(1) {
1046                 ret = find_first_extent_bit(&info->extent_ins, 0, &start,
1047                                             &end, EXTENT_LOCKED);
1048                 if (ret)
1049                         break;
1050
1051                 ins.objectid = start;
1052                 ins.offset = end + 1 - start;
1053                 err = btrfs_insert_item(trans, extent_root, &ins,
1054                                         &extent_item, sizeof(extent_item));
1055                 clear_extent_bits(&info->extent_ins, start, end, EXTENT_LOCKED,
1056                                   GFP_NOFS);
1057                 eb = read_tree_block(extent_root, ins.objectid, ins.offset);
1058                 level = btrfs_header_level(eb);
1059                 if (level == 0) {
1060                         btrfs_item_key(eb, &first, 0);
1061                 } else {
1062                         btrfs_node_key(eb, &first, 0);
1063                 }
1064                 err = btrfs_insert_extent_backref(trans, extent_root, path,
1065                                           start, extent_root->root_key.objectid,
1066                                           0, btrfs_disk_key_objectid(&first),
1067                                           level);
1068                 BUG_ON(err);
1069                 free_extent_buffer(eb);
1070         }
1071         btrfs_free_path(path);
1072         return 0;
1073 }
1074
1075 static int pin_down_bytes(struct btrfs_root *root, u64 bytenr, u32 num_bytes,
1076                           int pending)
1077 {
1078         int err = 0;
1079         struct extent_buffer *buf;
1080
1081         if (!pending) {
1082                 buf = btrfs_find_tree_block(root, bytenr, num_bytes);
1083                 if (buf) {
1084                         if (btrfs_buffer_uptodate(buf)) {
1085                                 u64 transid =
1086                                     root->fs_info->running_transaction->transid;
1087                                 if (btrfs_header_generation(buf) == transid) {
1088                                         free_extent_buffer(buf);
1089                                         return 1;
1090                                 }
1091                         }
1092                         free_extent_buffer(buf);
1093                 }
1094                 update_pinned_extents(root, bytenr, num_bytes, 1);
1095         } else {
1096                 set_extent_bits(&root->fs_info->pending_del,
1097                                 bytenr, bytenr + num_bytes - 1,
1098                                 EXTENT_LOCKED, GFP_NOFS);
1099         }
1100         BUG_ON(err < 0);
1101         return 0;
1102 }
1103
1104 /*
1105  * remove an extent from the root, returns 0 on success
1106  */
1107 static int __free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1108                          *root, u64 bytenr, u64 num_bytes,
1109                          u64 root_objectid, u64 ref_generation,
1110                          u64 owner_objectid, u64 owner_offset, int pin,
1111                          int mark_free)
1112 {
1113         struct btrfs_path *path;
1114         struct btrfs_key key;
1115         struct btrfs_fs_info *info = root->fs_info;
1116         struct btrfs_root *extent_root = info->extent_root;
1117         struct extent_buffer *leaf;
1118         int ret;
1119         struct btrfs_extent_item *ei;
1120         u32 refs;
1121
1122         key.objectid = bytenr;
1123         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1124         key.offset = num_bytes;
1125
1126         path = btrfs_alloc_path();
1127         if (!path)
1128                 return -ENOMEM;
1129
1130         if (ref_generation && owner_objectid == 0 && root_objectid == 3) {
1131 //printk("drop backref root %Lu gen %Lu byte %Lu\n", root_objectid, ref_generation, bytenr );
1132         }
1133         ret = lookup_extent_backref(trans, extent_root, path,
1134                                     bytenr, root_objectid,
1135                                     ref_generation,
1136                                     owner_objectid, owner_offset, 1);
1137         if (ret == 0) {
1138                 ret = btrfs_del_item(trans, extent_root, path);
1139         } else {
1140                 btrfs_print_leaf(extent_root, path->nodes[0]);
1141                 WARN_ON(1);
1142                 printk("Unable to find ref byte nr %Lu root %Lu "
1143                        " gen %Lu owner %Lu offset %Lu\n", bytenr,
1144                        root_objectid, ref_generation, owner_objectid,
1145                        owner_offset);
1146         }
1147         btrfs_release_path(extent_root, path);
1148         ret = btrfs_search_slot(trans, extent_root, &key, path, -1, 1);
1149         if (ret < 0)
1150                 return ret;
1151         BUG_ON(ret);
1152
1153         leaf = path->nodes[0];
1154         ei = btrfs_item_ptr(leaf, path->slots[0],
1155                             struct btrfs_extent_item);
1156         refs = btrfs_extent_refs(leaf, ei);
1157         BUG_ON(refs == 0);
1158         refs -= 1;
1159         btrfs_set_extent_refs(leaf, ei, refs);
1160         btrfs_mark_buffer_dirty(leaf);
1161
1162         if (refs == 0) {
1163                 u64 super_used;
1164                 u64 root_used;
1165
1166                 if (pin) {
1167                         ret = pin_down_bytes(root, bytenr, num_bytes, 0);
1168                         if (ret > 0)
1169                                 mark_free = 1;
1170                         BUG_ON(ret < 0);
1171                 }
1172
1173                 /* block accounting for super block */
1174                 super_used = btrfs_super_bytes_used(&info->super_copy);
1175                 btrfs_set_super_bytes_used(&info->super_copy,
1176                                            super_used - num_bytes);
1177
1178                 /* block accounting for root item */
1179                 root_used = btrfs_root_used(&root->root_item);
1180                 btrfs_set_root_used(&root->root_item,
1181                                            root_used - num_bytes);
1182
1183                 ret = btrfs_del_item(trans, extent_root, path);
1184                 if (ret) {
1185                         return ret;
1186                 }
1187                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
1188                                          mark_free, 0);
1189                 BUG_ON(ret);
1190         }
1191         btrfs_free_path(path);
1192         finish_current_insert(trans, extent_root);
1193         return ret;
1194 }
1195
1196 /*
1197  * find all the blocks marked as pending in the radix tree and remove
1198  * them from the extent map
1199  */
1200 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
1201                                btrfs_root *extent_root)
1202 {
1203         int ret;
1204         int err = 0;
1205         u64 start;
1206         u64 end;
1207         struct extent_map_tree *pending_del;
1208         struct extent_map_tree *pinned_extents;
1209
1210         pending_del = &extent_root->fs_info->pending_del;
1211         pinned_extents = &extent_root->fs_info->pinned_extents;
1212
1213         while(1) {
1214                 ret = find_first_extent_bit(pending_del, 0, &start, &end,
1215                                             EXTENT_LOCKED);
1216                 if (ret)
1217                         break;
1218                 update_pinned_extents(extent_root, start, end + 1 - start, 1);
1219                 clear_extent_bits(pending_del, start, end, EXTENT_LOCKED,
1220                                   GFP_NOFS);
1221                 ret = __free_extent(trans, extent_root,
1222                                      start, end + 1 - start,
1223                                      extent_root->root_key.objectid,
1224                                      0, 0, 0, 0, 0);
1225                 if (ret)
1226                         err = ret;
1227         }
1228         return err;
1229 }
1230
1231 /*
1232  * remove an extent from the root, returns 0 on success
1233  */
1234 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1235                       *root, u64 bytenr, u64 num_bytes,
1236                       u64 root_objectid, u64 ref_generation,
1237                       u64 owner_objectid, u64 owner_offset, int pin)
1238 {
1239         struct btrfs_root *extent_root = root->fs_info->extent_root;
1240         int pending_ret;
1241         int ret;
1242
1243         WARN_ON(num_bytes < root->sectorsize);
1244         if (!root->ref_cows)
1245                 ref_generation = 0;
1246
1247         if (root == extent_root) {
1248                 pin_down_bytes(root, bytenr, num_bytes, 1);
1249                 return 0;
1250         }
1251         ret = __free_extent(trans, root, bytenr, num_bytes, root_objectid,
1252                             ref_generation, owner_objectid, owner_offset,
1253                             pin, pin == 0);
1254         pending_ret = del_pending_extents(trans, root->fs_info->extent_root);
1255         return ret ? ret : pending_ret;
1256 }
1257
1258 static u64 stripe_align(struct btrfs_root *root, u64 val)
1259 {
1260         u64 mask = ((u64)root->stripesize - 1);
1261         u64 ret = (val + mask) & ~mask;
1262         return ret;
1263 }
1264
1265 /*
1266  * walks the btree of allocated extents and find a hole of a given size.
1267  * The key ins is changed to record the hole:
1268  * ins->objectid == block start
1269  * ins->flags = BTRFS_EXTENT_ITEM_KEY
1270  * ins->offset == number of blocks
1271  * Any available blocks before search_start are skipped.
1272  */
1273 static int find_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1274                             *orig_root, u64 num_bytes, u64 empty_size,
1275                             u64 search_start, u64 search_end, u64 hint_byte,
1276                             struct btrfs_key *ins, u64 exclude_start,
1277                             u64 exclude_nr, int data)
1278 {
1279         struct btrfs_path *path;
1280         struct btrfs_key key;
1281         u64 hole_size = 0;
1282         u64 aligned;
1283         int ret;
1284         int slot = 0;
1285         u64 last_byte = 0;
1286         u64 orig_search_start = search_start;
1287         int start_found;
1288         struct extent_buffer *l;
1289         struct btrfs_root * root = orig_root->fs_info->extent_root;
1290         struct btrfs_fs_info *info = root->fs_info;
1291         u64 total_needed = num_bytes;
1292         int level;
1293         struct btrfs_block_group_cache *block_group;
1294         int full_scan = 0;
1295         int wrapped = 0;
1296         u64 cached_start;
1297
1298         WARN_ON(num_bytes < root->sectorsize);
1299         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
1300
1301         level = btrfs_header_level(root->node);
1302
1303         if (num_bytes >= 32 * 1024 * 1024 && hint_byte) {
1304                 data = BTRFS_BLOCK_GROUP_MIXED;
1305         }
1306
1307         if (search_end == (u64)-1)
1308                 search_end = btrfs_super_total_bytes(&info->super_copy);
1309         if (hint_byte) {
1310                 block_group = btrfs_lookup_block_group(info, hint_byte);
1311                 if (!block_group)
1312                         hint_byte = search_start;
1313                 block_group = btrfs_find_block_group(root, block_group,
1314                                                      hint_byte, data, 1);
1315         } else {
1316                 block_group = btrfs_find_block_group(root,
1317                                                      trans->block_group,
1318                                                      search_start, data, 1);
1319         }
1320
1321         total_needed += empty_size;
1322         path = btrfs_alloc_path();
1323 check_failed:
1324         if (!block_group) {
1325                 block_group = btrfs_lookup_block_group(info, search_start);
1326                 if (!block_group)
1327                         block_group = btrfs_lookup_block_group(info,
1328                                                        orig_search_start);
1329         }
1330         search_start = find_search_start(root, &block_group, search_start,
1331                                          total_needed, data, full_scan);
1332         search_start = stripe_align(root, search_start);
1333         cached_start = search_start;
1334         btrfs_init_path(path);
1335         ins->objectid = search_start;
1336         ins->offset = 0;
1337         start_found = 0;
1338         path->reada = 2;
1339
1340         ret = btrfs_search_slot(trans, root, ins, path, 0, 0);
1341         if (ret < 0)
1342                 goto error;
1343
1344         if (path->slots[0] > 0) {
1345                 path->slots[0]--;
1346         }
1347
1348         l = path->nodes[0];
1349         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1350
1351         /*
1352          * walk backwards to find the first extent item key
1353          */
1354         while(btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY) {
1355                 if (path->slots[0] == 0) {
1356                         ret = btrfs_prev_leaf(root, path);
1357                         if (ret != 0) {
1358                                 ret = btrfs_search_slot(trans, root, ins,
1359                                                         path, 0, 0);
1360                                 if (ret < 0)
1361                                         goto error;
1362                                 if (path->slots[0] > 0)
1363                                         path->slots[0]--;
1364                                 break;
1365                         }
1366                 } else {
1367                         path->slots[0]--;
1368                 }
1369                 l = path->nodes[0];
1370                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1371         }
1372         while (1) {
1373                 l = path->nodes[0];
1374                 slot = path->slots[0];
1375                 if (slot >= btrfs_header_nritems(l)) {
1376                         ret = btrfs_next_leaf(root, path);
1377                         if (ret == 0)
1378                                 continue;
1379                         if (ret < 0)
1380                                 goto error;
1381
1382                         search_start = max(search_start,
1383                                            block_group->key.objectid);
1384                         if (!start_found) {
1385                                 aligned = stripe_align(root, search_start);
1386                                 ins->objectid = aligned;
1387                                 if (aligned >= search_end) {
1388                                         ret = -ENOSPC;
1389                                         goto error;
1390                                 }
1391                                 ins->offset = search_end - aligned;
1392                                 start_found = 1;
1393                                 goto check_pending;
1394                         }
1395                         ins->objectid = stripe_align(root,
1396                                                      last_byte > search_start ?
1397                                                      last_byte : search_start);
1398                         if (search_end <= ins->objectid) {
1399                                 ret = -ENOSPC;
1400                                 goto error;
1401                         }
1402                         ins->offset = search_end - ins->objectid;
1403                         BUG_ON(ins->objectid >= search_end);
1404                         goto check_pending;
1405                 }
1406                 btrfs_item_key_to_cpu(l, &key, slot);
1407
1408                 if (key.objectid >= search_start && key.objectid > last_byte &&
1409                     start_found) {
1410                         if (last_byte < search_start)
1411                                 last_byte = search_start;
1412                         aligned = stripe_align(root, last_byte);
1413                         hole_size = key.objectid - aligned;
1414                         if (key.objectid > aligned && hole_size >= num_bytes) {
1415                                 ins->objectid = aligned;
1416                                 ins->offset = hole_size;
1417                                 goto check_pending;
1418                         }
1419                 }
1420                 if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY) {
1421                         if (!start_found && btrfs_key_type(&key) ==
1422                             BTRFS_BLOCK_GROUP_ITEM_KEY) {
1423                                 last_byte = key.objectid;
1424                                 start_found = 1;
1425                         }
1426                         goto next;
1427                 }
1428
1429
1430                 start_found = 1;
1431                 last_byte = key.objectid + key.offset;
1432
1433                 if (!full_scan && data != BTRFS_BLOCK_GROUP_MIXED &&
1434                     last_byte >= block_group->key.objectid +
1435                     block_group->key.offset) {
1436                         btrfs_release_path(root, path);
1437                         search_start = block_group->key.objectid +
1438                                 block_group->key.offset;
1439                         goto new_group;
1440                 }
1441 next:
1442                 path->slots[0]++;
1443                 cond_resched();
1444         }
1445 check_pending:
1446         /* we have to make sure we didn't find an extent that has already
1447          * been allocated by the map tree or the original allocation
1448          */
1449         btrfs_release_path(root, path);
1450         BUG_ON(ins->objectid < search_start);
1451
1452         if (ins->objectid + num_bytes >= search_end)
1453                 goto enospc;
1454         if (!full_scan && data != BTRFS_BLOCK_GROUP_MIXED &&
1455             ins->objectid + num_bytes > block_group->
1456             key.objectid + block_group->key.offset) {
1457                 search_start = block_group->key.objectid +
1458                         block_group->key.offset;
1459                 goto new_group;
1460         }
1461         if (test_range_bit(&info->extent_ins, ins->objectid,
1462                            ins->objectid + num_bytes -1, EXTENT_LOCKED, 0)) {
1463                 search_start = ins->objectid + num_bytes;
1464                 goto new_group;
1465         }
1466         if (test_range_bit(&info->pinned_extents, ins->objectid,
1467                            ins->objectid + num_bytes -1, EXTENT_DIRTY, 0)) {
1468                 search_start = ins->objectid + num_bytes;
1469                 goto new_group;
1470         }
1471         if (exclude_nr > 0 && (ins->objectid + num_bytes > exclude_start &&
1472             ins->objectid < exclude_start + exclude_nr)) {
1473                 search_start = exclude_start + exclude_nr;
1474                 goto new_group;
1475         }
1476         if (!data) {
1477                 block_group = btrfs_lookup_block_group(info, ins->objectid);
1478                 if (block_group)
1479                         trans->block_group = block_group;
1480         }
1481         ins->offset = num_bytes;
1482         btrfs_free_path(path);
1483         return 0;
1484
1485 new_group:
1486         if (search_start + num_bytes >= search_end) {
1487 enospc:
1488                 search_start = orig_search_start;
1489                 if (full_scan) {
1490                         ret = -ENOSPC;
1491                         goto error;
1492                 }
1493                 if (wrapped) {
1494                         if (!full_scan)
1495                                 total_needed -= empty_size;
1496                         full_scan = 1;
1497                         data = BTRFS_BLOCK_GROUP_MIXED;
1498                 } else
1499                         wrapped = 1;
1500         }
1501         block_group = btrfs_lookup_block_group(info, search_start);
1502         cond_resched();
1503         block_group = btrfs_find_block_group(root, block_group,
1504                                              search_start, data, 0);
1505         goto check_failed;
1506
1507 error:
1508         btrfs_release_path(root, path);
1509         btrfs_free_path(path);
1510         return ret;
1511 }
1512 /*
1513  * finds a free extent and does all the dirty work required for allocation
1514  * returns the key for the extent through ins, and a tree buffer for
1515  * the first block of the extent through buf.
1516  *
1517  * returns 0 if everything worked, non-zero otherwise.
1518  */
1519 int btrfs_alloc_extent(struct btrfs_trans_handle *trans,
1520                        struct btrfs_root *root,
1521                        u64 num_bytes, u64 root_objectid, u64 ref_generation,
1522                        u64 owner, u64 owner_offset,
1523                        u64 empty_size, u64 hint_byte,
1524                        u64 search_end, struct btrfs_key *ins, int data)
1525 {
1526         int ret;
1527         int pending_ret;
1528         u64 super_used, root_used;
1529         u64 search_start = 0;
1530         struct btrfs_fs_info *info = root->fs_info;
1531         struct btrfs_root *extent_root = info->extent_root;
1532         struct btrfs_extent_item extent_item;
1533         struct btrfs_path *path;
1534
1535         btrfs_set_stack_extent_refs(&extent_item, 1);
1536
1537         WARN_ON(num_bytes < root->sectorsize);
1538         ret = find_free_extent(trans, root, num_bytes, empty_size,
1539                                search_start, search_end, hint_byte, ins,
1540                                trans->alloc_exclude_start,
1541                                trans->alloc_exclude_nr, data);
1542         BUG_ON(ret);
1543         if (ret)
1544                 return ret;
1545
1546         /* block accounting for super block */
1547         super_used = btrfs_super_bytes_used(&info->super_copy);
1548         btrfs_set_super_bytes_used(&info->super_copy, super_used + num_bytes);
1549
1550         /* block accounting for root item */
1551         root_used = btrfs_root_used(&root->root_item);
1552         btrfs_set_root_used(&root->root_item, root_used + num_bytes);
1553
1554         clear_extent_dirty(&root->fs_info->free_space_cache,
1555                            ins->objectid, ins->objectid + ins->offset - 1,
1556                            GFP_NOFS);
1557
1558         if (root == extent_root) {
1559                 set_extent_bits(&root->fs_info->extent_ins, ins->objectid,
1560                                 ins->objectid + ins->offset - 1,
1561                                 EXTENT_LOCKED, GFP_NOFS);
1562                 WARN_ON(data == 1);
1563                 goto update_block;
1564         }
1565
1566         WARN_ON(trans->alloc_exclude_nr);
1567         trans->alloc_exclude_start = ins->objectid;
1568         trans->alloc_exclude_nr = ins->offset;
1569         ret = btrfs_insert_item(trans, extent_root, ins, &extent_item,
1570                                 sizeof(extent_item));
1571
1572         trans->alloc_exclude_start = 0;
1573         trans->alloc_exclude_nr = 0;
1574         BUG_ON(ret);
1575
1576         path = btrfs_alloc_path();
1577         BUG_ON(!path);
1578         ret = btrfs_insert_extent_backref(trans, extent_root, path,
1579                                           ins->objectid, root_objectid,
1580                                           ref_generation, owner, owner_offset);
1581
1582         BUG_ON(ret);
1583         btrfs_free_path(path);
1584         finish_current_insert(trans, extent_root);
1585         pending_ret = del_pending_extents(trans, extent_root);
1586
1587         if (ret) {
1588                 return ret;
1589         }
1590         if (pending_ret) {
1591                 return pending_ret;
1592         }
1593
1594 update_block:
1595         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1, 0,
1596                                  data);
1597         BUG_ON(ret);
1598         return 0;
1599 }
1600
1601 /*
1602  * helper function to allocate a block for a given tree
1603  * returns the tree buffer or NULL.
1604  */
1605 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1606                                              struct btrfs_root *root,
1607                                              u32 blocksize,
1608                                              u64 root_objectid, u64 hint,
1609                                              u64 empty_size)
1610 {
1611         u64 ref_generation;
1612
1613         if (root->ref_cows)
1614                 ref_generation = trans->transid;
1615         else
1616                 ref_generation = 0;
1617
1618
1619         return __btrfs_alloc_free_block(trans, root, blocksize, root_objectid,
1620                                         ref_generation, 0, 0, hint, empty_size);
1621 }
1622
1623 /*
1624  * helper function to allocate a block for a given tree
1625  * returns the tree buffer or NULL.
1626  */
1627 struct extent_buffer *__btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1628                                              struct btrfs_root *root,
1629                                              u32 blocksize,
1630                                              u64 root_objectid,
1631                                              u64 ref_generation,
1632                                              u64 first_objectid,
1633                                              int level,
1634                                              u64 hint,
1635                                              u64 empty_size)
1636 {
1637         struct btrfs_key ins;
1638         int ret;
1639         struct extent_buffer *buf;
1640
1641         ret = btrfs_alloc_extent(trans, root, blocksize,
1642                                  root_objectid, ref_generation,
1643                                  first_objectid, level, empty_size, hint,
1644                                  (u64)-1, &ins, 0);
1645         if (ret) {
1646                 BUG_ON(ret > 0);
1647                 return ERR_PTR(ret);
1648         }
1649         buf = btrfs_find_create_tree_block(root, ins.objectid, blocksize);
1650         if (!buf) {
1651                 btrfs_free_extent(trans, root, ins.objectid, blocksize,
1652                                   root->root_key.objectid, ref_generation,
1653                                   0, 0, 0);
1654                 return ERR_PTR(-ENOMEM);
1655         }
1656         btrfs_set_buffer_uptodate(buf);
1657         set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
1658                          buf->start + buf->len - 1, GFP_NOFS);
1659         set_extent_bits(&BTRFS_I(root->fs_info->btree_inode)->extent_tree,
1660                         buf->start, buf->start + buf->len - 1,
1661                         EXTENT_CSUM, GFP_NOFS);
1662         buf->flags |= EXTENT_CSUM;
1663         btrfs_set_buffer_defrag(buf);
1664         trans->blocks_used++;
1665         return buf;
1666 }
1667
1668 static int drop_leaf_ref(struct btrfs_trans_handle *trans,
1669                          struct btrfs_root *root, struct extent_buffer *leaf)
1670 {
1671         u64 leaf_owner;
1672         u64 leaf_generation;
1673         struct btrfs_key key;
1674         struct btrfs_file_extent_item *fi;
1675         int i;
1676         int nritems;
1677         int ret;
1678
1679         BUG_ON(!btrfs_is_leaf(leaf));
1680         nritems = btrfs_header_nritems(leaf);
1681         leaf_owner = btrfs_header_owner(leaf);
1682         leaf_generation = btrfs_header_generation(leaf);
1683
1684         for (i = 0; i < nritems; i++) {
1685                 u64 disk_bytenr;
1686
1687                 btrfs_item_key_to_cpu(leaf, &key, i);
1688                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1689                         continue;
1690                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
1691                 if (btrfs_file_extent_type(leaf, fi) ==
1692                     BTRFS_FILE_EXTENT_INLINE)
1693                         continue;
1694                 /*
1695                  * FIXME make sure to insert a trans record that
1696                  * repeats the snapshot del on crash
1697                  */
1698                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1699                 if (disk_bytenr == 0)
1700                         continue;
1701                 ret = btrfs_free_extent(trans, root, disk_bytenr,
1702                                 btrfs_file_extent_disk_num_bytes(leaf, fi),
1703                                 leaf_owner, leaf_generation,
1704                                 key.objectid, key.offset, 0);
1705                 BUG_ON(ret);
1706         }
1707         return 0;
1708 }
1709
1710 static void reada_walk_down(struct btrfs_root *root,
1711                             struct extent_buffer *node)
1712 {
1713         int i;
1714         u32 nritems;
1715         u64 bytenr;
1716         int ret;
1717         u32 refs;
1718         int level;
1719         u32 blocksize;
1720
1721         nritems = btrfs_header_nritems(node);
1722         level = btrfs_header_level(node);
1723         for (i = 0; i < nritems; i++) {
1724                 bytenr = btrfs_node_blockptr(node, i);
1725                 blocksize = btrfs_level_size(root, level - 1);
1726                 ret = lookup_extent_ref(NULL, root, bytenr, blocksize, &refs);
1727                 BUG_ON(ret);
1728                 if (refs != 1)
1729                         continue;
1730                 mutex_unlock(&root->fs_info->fs_mutex);
1731                 ret = readahead_tree_block(root, bytenr, blocksize);
1732                 cond_resched();
1733                 mutex_lock(&root->fs_info->fs_mutex);
1734                 if (ret)
1735                         break;
1736         }
1737 }
1738
1739 /*
1740  * helper function for drop_snapshot, this walks down the tree dropping ref
1741  * counts as it goes.
1742  */
1743 static int walk_down_tree(struct btrfs_trans_handle *trans, struct btrfs_root
1744                           *root, struct btrfs_path *path, int *level)
1745 {
1746         u64 root_owner;
1747         u64 root_gen;
1748         u64 bytenr;
1749         struct extent_buffer *next;
1750         struct extent_buffer *cur;
1751         struct extent_buffer *parent;
1752         u32 blocksize;
1753         int ret;
1754         u32 refs;
1755
1756         WARN_ON(*level < 0);
1757         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1758         ret = lookup_extent_ref(trans, root,
1759                                 path->nodes[*level]->start,
1760                                 path->nodes[*level]->len, &refs);
1761         BUG_ON(ret);
1762         if (refs > 1)
1763                 goto out;
1764
1765         /*
1766          * walk down to the last node level and free all the leaves
1767          */
1768         while(*level >= 0) {
1769                 WARN_ON(*level < 0);
1770                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1771                 cur = path->nodes[*level];
1772
1773                 if (*level > 0 && path->slots[*level] == 0)
1774                         reada_walk_down(root, cur);
1775
1776                 if (btrfs_header_level(cur) != *level)
1777                         WARN_ON(1);
1778
1779                 if (path->slots[*level] >=
1780                     btrfs_header_nritems(cur))
1781                         break;
1782                 if (*level == 0) {
1783                         ret = drop_leaf_ref(trans, root, cur);
1784                         BUG_ON(ret);
1785                         break;
1786                 }
1787                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1788                 blocksize = btrfs_level_size(root, *level - 1);
1789                 ret = lookup_extent_ref(trans, root, bytenr, blocksize, &refs);
1790                 BUG_ON(ret);
1791                 if (refs != 1) {
1792                         parent = path->nodes[*level];
1793                         root_owner = btrfs_header_owner(parent);
1794                         root_gen = btrfs_header_generation(parent);
1795                         path->slots[*level]++;
1796                         ret = btrfs_free_extent(trans, root, bytenr,
1797                                                 blocksize, root_owner,
1798                                                 root_gen, 0, 0, 1);
1799                         BUG_ON(ret);
1800                         continue;
1801                 }
1802                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1803                 if (!next || !btrfs_buffer_uptodate(next)) {
1804                         free_extent_buffer(next);
1805                         mutex_unlock(&root->fs_info->fs_mutex);
1806                         next = read_tree_block(root, bytenr, blocksize);
1807                         mutex_lock(&root->fs_info->fs_mutex);
1808
1809                         /* we dropped the lock, check one more time */
1810                         ret = lookup_extent_ref(trans, root, bytenr,
1811                                                 blocksize, &refs);
1812                         BUG_ON(ret);
1813                         if (refs != 1) {
1814                                 parent = path->nodes[*level];
1815                                 root_owner = btrfs_header_owner(parent);
1816                                 root_gen = btrfs_header_generation(parent);
1817
1818                                 path->slots[*level]++;
1819                                 free_extent_buffer(next);
1820                                 ret = btrfs_free_extent(trans, root, bytenr,
1821                                                         blocksize,
1822                                                         root_owner,
1823                                                         root_gen, 0, 0, 1);
1824                                 BUG_ON(ret);
1825                                 continue;
1826                         }
1827                 }
1828                 WARN_ON(*level <= 0);
1829                 if (path->nodes[*level-1])
1830                         free_extent_buffer(path->nodes[*level-1]);
1831                 path->nodes[*level-1] = next;
1832                 *level = btrfs_header_level(next);
1833                 path->slots[*level] = 0;
1834         }
1835 out:
1836         WARN_ON(*level < 0);
1837         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1838
1839         if (path->nodes[*level] == root->node) {
1840                 root_owner = root->root_key.objectid;
1841                 parent = path->nodes[*level];
1842         } else {
1843                 parent = path->nodes[*level + 1];
1844                 root_owner = btrfs_header_owner(parent);
1845         }
1846
1847         root_gen = btrfs_header_generation(parent);
1848         ret = btrfs_free_extent(trans, root, path->nodes[*level]->start,
1849                                 path->nodes[*level]->len,
1850                                 root_owner, root_gen, 0, 0, 1);
1851         free_extent_buffer(path->nodes[*level]);
1852         path->nodes[*level] = NULL;
1853         *level += 1;
1854         BUG_ON(ret);
1855         return 0;
1856 }
1857
1858 /*
1859  * helper for dropping snapshots.  This walks back up the tree in the path
1860  * to find the first node higher up where we haven't yet gone through
1861  * all the slots
1862  */
1863 static int walk_up_tree(struct btrfs_trans_handle *trans, struct btrfs_root
1864                         *root, struct btrfs_path *path, int *level)
1865 {
1866         u64 root_owner;
1867         u64 root_gen;
1868         struct btrfs_root_item *root_item = &root->root_item;
1869         int i;
1870         int slot;
1871         int ret;
1872
1873         for(i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1874                 slot = path->slots[i];
1875                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
1876                         struct extent_buffer *node;
1877                         struct btrfs_disk_key disk_key;
1878                         node = path->nodes[i];
1879                         path->slots[i]++;
1880                         *level = i;
1881                         WARN_ON(*level == 0);
1882                         btrfs_node_key(node, &disk_key, path->slots[i]);
1883                         memcpy(&root_item->drop_progress,
1884                                &disk_key, sizeof(disk_key));
1885                         root_item->drop_level = i;
1886                         return 0;
1887                 } else {
1888                         if (path->nodes[*level] == root->node) {
1889                                 root_owner = root->root_key.objectid;
1890                                 root_gen =
1891                                    btrfs_header_generation(path->nodes[*level]);
1892                         } else {
1893                                 struct extent_buffer *node;
1894                                 node = path->nodes[*level + 1];
1895                                 root_owner = btrfs_header_owner(node);
1896                                 root_gen = btrfs_header_generation(node);
1897                         }
1898                         ret = btrfs_free_extent(trans, root,
1899                                                 path->nodes[*level]->start,
1900                                                 path->nodes[*level]->len,
1901                                                 root_owner, root_gen, 0, 0, 1);
1902                         BUG_ON(ret);
1903                         free_extent_buffer(path->nodes[*level]);
1904                         path->nodes[*level] = NULL;
1905                         *level = i + 1;
1906                 }
1907         }
1908         return 1;
1909 }
1910
1911 /*
1912  * drop the reference count on the tree rooted at 'snap'.  This traverses
1913  * the tree freeing any blocks that have a ref count of zero after being
1914  * decremented.
1915  */
1916 int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
1917                         *root)
1918 {
1919         int ret = 0;
1920         int wret;
1921         int level;
1922         struct btrfs_path *path;
1923         int i;
1924         int orig_level;
1925         struct btrfs_root_item *root_item = &root->root_item;
1926
1927         path = btrfs_alloc_path();
1928         BUG_ON(!path);
1929
1930         level = btrfs_header_level(root->node);
1931         orig_level = level;
1932         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1933                 path->nodes[level] = root->node;
1934                 extent_buffer_get(root->node);
1935                 path->slots[level] = 0;
1936         } else {
1937                 struct btrfs_key key;
1938                 struct btrfs_disk_key found_key;
1939                 struct extent_buffer *node;
1940
1941                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1942                 level = root_item->drop_level;
1943                 path->lowest_level = level;
1944                 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1945                 if (wret < 0) {
1946                         ret = wret;
1947                         goto out;
1948                 }
1949                 node = path->nodes[level];
1950                 btrfs_node_key(node, &found_key, path->slots[level]);
1951                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1952                                sizeof(found_key)));
1953         }
1954         while(1) {
1955                 wret = walk_down_tree(trans, root, path, &level);
1956                 if (wret > 0)
1957                         break;
1958                 if (wret < 0)
1959                         ret = wret;
1960
1961                 wret = walk_up_tree(trans, root, path, &level);
1962                 if (wret > 0)
1963                         break;
1964                 if (wret < 0)
1965                         ret = wret;
1966                 ret = -EAGAIN;
1967                 break;
1968         }
1969         for (i = 0; i <= orig_level; i++) {
1970                 if (path->nodes[i]) {
1971                         free_extent_buffer(path->nodes[i]);
1972                         path->nodes[i] = NULL;
1973                 }
1974         }
1975 out:
1976         btrfs_free_path(path);
1977         return ret;
1978 }
1979
1980 int btrfs_free_block_groups(struct btrfs_fs_info *info)
1981 {
1982         u64 start;
1983         u64 end;
1984         u64 ptr;
1985         int ret;
1986         while(1) {
1987                 ret = find_first_extent_bit(&info->block_group_cache, 0,
1988                                             &start, &end, (unsigned int)-1);
1989                 if (ret)
1990                         break;
1991                 ret = get_state_private(&info->block_group_cache, start, &ptr);
1992                 if (!ret)
1993                         kfree((void *)(unsigned long)ptr);
1994                 clear_extent_bits(&info->block_group_cache, start,
1995                                   end, (unsigned int)-1, GFP_NOFS);
1996         }
1997         while(1) {
1998                 ret = find_first_extent_bit(&info->free_space_cache, 0,
1999                                             &start, &end, EXTENT_DIRTY);
2000                 if (ret)
2001                         break;
2002                 clear_extent_dirty(&info->free_space_cache, start,
2003                                    end, GFP_NOFS);
2004         }
2005         return 0;
2006 }
2007
2008 int btrfs_read_block_groups(struct btrfs_root *root)
2009 {
2010         struct btrfs_path *path;
2011         int ret;
2012         int err = 0;
2013         int bit;
2014         struct btrfs_block_group_cache *cache;
2015         struct btrfs_fs_info *info = root->fs_info;
2016         struct extent_map_tree *block_group_cache;
2017         struct btrfs_key key;
2018         struct btrfs_key found_key;
2019         struct extent_buffer *leaf;
2020
2021         block_group_cache = &info->block_group_cache;
2022
2023         root = info->extent_root;
2024         key.objectid = 0;
2025         key.offset = BTRFS_BLOCK_GROUP_SIZE;
2026         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
2027
2028         path = btrfs_alloc_path();
2029         if (!path)
2030                 return -ENOMEM;
2031
2032         while(1) {
2033                 ret = btrfs_search_slot(NULL, info->extent_root,
2034                                         &key, path, 0, 0);
2035                 if (ret != 0) {
2036                         err = ret;
2037                         break;
2038                 }
2039                 leaf = path->nodes[0];
2040                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2041                 cache = kmalloc(sizeof(*cache), GFP_NOFS);
2042                 if (!cache) {
2043                         err = -1;
2044                         break;
2045                 }
2046
2047                 read_extent_buffer(leaf, &cache->item,
2048                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
2049                                    sizeof(cache->item));
2050                 memcpy(&cache->key, &found_key, sizeof(found_key));
2051                 cache->cached = 0;
2052                 cache->pinned = 0;
2053                 key.objectid = found_key.objectid + found_key.offset;
2054                 btrfs_release_path(root, path);
2055
2056                 if (cache->item.flags & BTRFS_BLOCK_GROUP_MIXED) {
2057                         bit = BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA;
2058                         cache->data = BTRFS_BLOCK_GROUP_MIXED;
2059                 } else if (cache->item.flags & BTRFS_BLOCK_GROUP_DATA) {
2060                         bit = BLOCK_GROUP_DATA;
2061                         cache->data = BTRFS_BLOCK_GROUP_DATA;
2062                 } else {
2063                         bit = BLOCK_GROUP_METADATA;
2064                         cache->data = 0;
2065                 }
2066
2067                 /* use EXTENT_LOCKED to prevent merging */
2068                 set_extent_bits(block_group_cache, found_key.objectid,
2069                                 found_key.objectid + found_key.offset - 1,
2070                                 bit | EXTENT_LOCKED, GFP_NOFS);
2071                 set_state_private(block_group_cache, found_key.objectid,
2072                                   (unsigned long)cache);
2073
2074                 if (key.objectid >=
2075                     btrfs_super_total_bytes(&info->super_copy))
2076                         break;
2077         }
2078
2079         btrfs_free_path(path);
2080         return 0;
2081 }