Btrfs: Add lowest key information to back refs for extent tree blocks as well.
[pandora-kernel.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, 0, 0);
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                         ret = btrfs_inc_extent_ref(trans, root, bytenr,
750                                            btrfs_level_size(root, level - 1),
751                                            root->root_key.objectid,
752                                            trans->transid, 0, 0);
753                         if (ret) {
754                                 faili = i;
755                                 goto fail;
756                         }
757                 }
758         }
759         return 0;
760 fail:
761         WARN_ON(1);
762 #if 0
763         for (i =0; i < faili; i++) {
764                 if (level == 0) {
765                         u64 disk_bytenr;
766                         btrfs_item_key_to_cpu(buf, &key, i);
767                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
768                                 continue;
769                         fi = btrfs_item_ptr(buf, i,
770                                             struct btrfs_file_extent_item);
771                         if (btrfs_file_extent_type(buf, fi) ==
772                             BTRFS_FILE_EXTENT_INLINE)
773                                 continue;
774                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
775                         if (disk_bytenr == 0)
776                                 continue;
777                         err = btrfs_free_extent(trans, root, disk_bytenr,
778                                     btrfs_file_extent_disk_num_bytes(buf,
779                                                                       fi), 0);
780                         BUG_ON(err);
781                 } else {
782                         bytenr = btrfs_node_blockptr(buf, i);
783                         err = btrfs_free_extent(trans, root, bytenr,
784                                         btrfs_level_size(root, level - 1), 0);
785                         BUG_ON(err);
786                 }
787         }
788 #endif
789         return ret;
790 }
791
792 static int write_one_cache_group(struct btrfs_trans_handle *trans,
793                                  struct btrfs_root *root,
794                                  struct btrfs_path *path,
795                                  struct btrfs_block_group_cache *cache)
796 {
797         int ret;
798         int pending_ret;
799         struct btrfs_root *extent_root = root->fs_info->extent_root;
800         unsigned long bi;
801         struct extent_buffer *leaf;
802
803         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
804         if (ret < 0)
805                 goto fail;
806         BUG_ON(ret);
807
808         leaf = path->nodes[0];
809         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
810         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
811         btrfs_mark_buffer_dirty(leaf);
812         btrfs_release_path(extent_root, path);
813 fail:
814         finish_current_insert(trans, extent_root);
815         pending_ret = del_pending_extents(trans, extent_root);
816         if (ret)
817                 return ret;
818         if (pending_ret)
819                 return pending_ret;
820         return 0;
821
822 }
823
824 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
825                                    struct btrfs_root *root)
826 {
827         struct extent_map_tree *block_group_cache;
828         struct btrfs_block_group_cache *cache;
829         int ret;
830         int err = 0;
831         int werr = 0;
832         struct btrfs_path *path;
833         u64 last = 0;
834         u64 start;
835         u64 end;
836         u64 ptr;
837
838         block_group_cache = &root->fs_info->block_group_cache;
839         path = btrfs_alloc_path();
840         if (!path)
841                 return -ENOMEM;
842
843         while(1) {
844                 ret = find_first_extent_bit(block_group_cache, last,
845                                             &start, &end, BLOCK_GROUP_DIRTY);
846                 if (ret)
847                         break;
848
849                 last = end + 1;
850                 ret = get_state_private(block_group_cache, start, &ptr);
851                 if (ret)
852                         break;
853
854                 cache = (struct btrfs_block_group_cache *)(unsigned long)ptr;
855                 err = write_one_cache_group(trans, root,
856                                             path, cache);
857                 /*
858                  * if we fail to write the cache group, we want
859                  * to keep it marked dirty in hopes that a later
860                  * write will work
861                  */
862                 if (err) {
863                         werr = err;
864                         continue;
865                 }
866                 clear_extent_bits(block_group_cache, start, end,
867                                   BLOCK_GROUP_DIRTY, GFP_NOFS);
868         }
869         btrfs_free_path(path);
870         return werr;
871 }
872
873 static int update_block_group(struct btrfs_trans_handle *trans,
874                               struct btrfs_root *root,
875                               u64 bytenr, u64 num_bytes, int alloc,
876                               int mark_free, int data)
877 {
878         struct btrfs_block_group_cache *cache;
879         struct btrfs_fs_info *info = root->fs_info;
880         u64 total = num_bytes;
881         u64 old_val;
882         u64 byte_in_group;
883         u64 start;
884         u64 end;
885
886         while(total) {
887                 cache = btrfs_lookup_block_group(info, bytenr);
888                 if (!cache) {
889                         return -1;
890                 }
891                 byte_in_group = bytenr - cache->key.objectid;
892                 WARN_ON(byte_in_group > cache->key.offset);
893                 start = cache->key.objectid;
894                 end = start + cache->key.offset - 1;
895                 set_extent_bits(&info->block_group_cache, start, end,
896                                 BLOCK_GROUP_DIRTY, GFP_NOFS);
897
898                 old_val = btrfs_block_group_used(&cache->item);
899                 num_bytes = min(total, cache->key.offset - byte_in_group);
900                 if (alloc) {
901                         if (cache->data != data &&
902                             old_val < (cache->key.offset >> 1)) {
903                                 int bit_to_clear;
904                                 int bit_to_set;
905                                 cache->data = data;
906                                 if (data) {
907                                         bit_to_clear = BLOCK_GROUP_METADATA;
908                                         bit_to_set = BLOCK_GROUP_DATA;
909                                         cache->item.flags &=
910                                                 ~BTRFS_BLOCK_GROUP_MIXED;
911                                         cache->item.flags |=
912                                                 BTRFS_BLOCK_GROUP_DATA;
913                                 } else {
914                                         bit_to_clear = BLOCK_GROUP_DATA;
915                                         bit_to_set = BLOCK_GROUP_METADATA;
916                                         cache->item.flags &=
917                                                 ~BTRFS_BLOCK_GROUP_MIXED;
918                                         cache->item.flags &=
919                                                 ~BTRFS_BLOCK_GROUP_DATA;
920                                 }
921                                 clear_extent_bits(&info->block_group_cache,
922                                                   start, end, bit_to_clear,
923                                                   GFP_NOFS);
924                                 set_extent_bits(&info->block_group_cache,
925                                                 start, end, bit_to_set,
926                                                 GFP_NOFS);
927                         } else if (cache->data != data &&
928                                    cache->data != BTRFS_BLOCK_GROUP_MIXED) {
929                                 cache->data = BTRFS_BLOCK_GROUP_MIXED;
930                                 set_extent_bits(&info->block_group_cache,
931                                                 start, end,
932                                                 BLOCK_GROUP_DATA |
933                                                 BLOCK_GROUP_METADATA,
934                                                 GFP_NOFS);
935                         }
936                         old_val += num_bytes;
937                 } else {
938                         old_val -= num_bytes;
939                         if (mark_free) {
940                                 set_extent_dirty(&info->free_space_cache,
941                                                  bytenr, bytenr + num_bytes - 1,
942                                                  GFP_NOFS);
943                         }
944                 }
945                 btrfs_set_block_group_used(&cache->item, old_val);
946                 total -= num_bytes;
947                 bytenr += num_bytes;
948         }
949         return 0;
950 }
951 static int update_pinned_extents(struct btrfs_root *root,
952                                 u64 bytenr, u64 num, int pin)
953 {
954         u64 len;
955         struct btrfs_block_group_cache *cache;
956         struct btrfs_fs_info *fs_info = root->fs_info;
957
958         if (pin) {
959                 set_extent_dirty(&fs_info->pinned_extents,
960                                 bytenr, bytenr + num - 1, GFP_NOFS);
961         } else {
962                 clear_extent_dirty(&fs_info->pinned_extents,
963                                 bytenr, bytenr + num - 1, GFP_NOFS);
964         }
965         while (num > 0) {
966                 cache = btrfs_lookup_block_group(fs_info, bytenr);
967                 WARN_ON(!cache);
968                 len = min(num, cache->key.offset -
969                           (bytenr - cache->key.objectid));
970                 if (pin) {
971                         cache->pinned += len;
972                         fs_info->total_pinned += len;
973                 } else {
974                         cache->pinned -= len;
975                         fs_info->total_pinned -= len;
976                 }
977                 bytenr += len;
978                 num -= len;
979         }
980         return 0;
981 }
982
983 int btrfs_copy_pinned(struct btrfs_root *root, struct extent_map_tree *copy)
984 {
985         u64 last = 0;
986         u64 start;
987         u64 end;
988         struct extent_map_tree *pinned_extents = &root->fs_info->pinned_extents;
989         int ret;
990
991         while(1) {
992                 ret = find_first_extent_bit(pinned_extents, last,
993                                             &start, &end, EXTENT_DIRTY);
994                 if (ret)
995                         break;
996                 set_extent_dirty(copy, start, end, GFP_NOFS);
997                 last = end + 1;
998         }
999         return 0;
1000 }
1001
1002 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
1003                                struct btrfs_root *root,
1004                                struct extent_map_tree *unpin)
1005 {
1006         u64 start;
1007         u64 end;
1008         int ret;
1009         struct extent_map_tree *free_space_cache;
1010         free_space_cache = &root->fs_info->free_space_cache;
1011
1012         while(1) {
1013                 ret = find_first_extent_bit(unpin, 0, &start, &end,
1014                                             EXTENT_DIRTY);
1015                 if (ret)
1016                         break;
1017                 update_pinned_extents(root, start, end + 1 - start, 0);
1018                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
1019                 set_extent_dirty(free_space_cache, start, end, GFP_NOFS);
1020         }
1021         return 0;
1022 }
1023
1024 static int finish_current_insert(struct btrfs_trans_handle *trans, struct
1025                                  btrfs_root *extent_root)
1026 {
1027         u64 start;
1028         u64 end;
1029         struct btrfs_fs_info *info = extent_root->fs_info;
1030         struct extent_buffer *eb;
1031         struct btrfs_path *path;
1032         struct btrfs_key ins;
1033         struct btrfs_disk_key first;
1034         struct btrfs_extent_item extent_item;
1035         int ret;
1036         int level;
1037         int err = 0;
1038
1039         btrfs_set_stack_extent_refs(&extent_item, 1);
1040         btrfs_set_key_type(&ins, BTRFS_EXTENT_ITEM_KEY);
1041         path = btrfs_alloc_path();
1042
1043         while(1) {
1044                 ret = find_first_extent_bit(&info->extent_ins, 0, &start,
1045                                             &end, EXTENT_LOCKED);
1046                 if (ret)
1047                         break;
1048
1049                 ins.objectid = start;
1050                 ins.offset = end + 1 - start;
1051                 err = btrfs_insert_item(trans, extent_root, &ins,
1052                                         &extent_item, sizeof(extent_item));
1053                 clear_extent_bits(&info->extent_ins, start, end, EXTENT_LOCKED,
1054                                   GFP_NOFS);
1055                 eb = read_tree_block(extent_root, ins.objectid, ins.offset);
1056                 level = btrfs_header_level(eb);
1057                 if (level == 0) {
1058                         btrfs_item_key(eb, &first, 0);
1059                 } else {
1060                         btrfs_node_key(eb, &first, 0);
1061                 }
1062                 err = btrfs_insert_extent_backref(trans, extent_root, path,
1063                                           start, extent_root->root_key.objectid,
1064                                           0, btrfs_disk_key_objectid(&first),
1065                                           level);
1066                 BUG_ON(err);
1067                 free_extent_buffer(eb);
1068         }
1069         btrfs_free_path(path);
1070         return 0;
1071 }
1072
1073 static int pin_down_bytes(struct btrfs_root *root, u64 bytenr, u32 num_bytes,
1074                           int pending)
1075 {
1076         int err = 0;
1077         struct extent_buffer *buf;
1078
1079         if (!pending) {
1080                 buf = btrfs_find_tree_block(root, bytenr, num_bytes);
1081                 if (buf) {
1082                         if (btrfs_buffer_uptodate(buf)) {
1083                                 u64 transid =
1084                                     root->fs_info->running_transaction->transid;
1085                                 if (btrfs_header_generation(buf) == transid) {
1086                                         free_extent_buffer(buf);
1087                                         return 1;
1088                                 }
1089                         }
1090                         free_extent_buffer(buf);
1091                 }
1092                 update_pinned_extents(root, bytenr, num_bytes, 1);
1093         } else {
1094                 set_extent_bits(&root->fs_info->pending_del,
1095                                 bytenr, bytenr + num_bytes - 1,
1096                                 EXTENT_LOCKED, GFP_NOFS);
1097         }
1098         BUG_ON(err < 0);
1099         return 0;
1100 }
1101
1102 /*
1103  * remove an extent from the root, returns 0 on success
1104  */
1105 static int __free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1106                          *root, u64 bytenr, u64 num_bytes,
1107                          u64 root_objectid, u64 ref_generation,
1108                          u64 owner_objectid, u64 owner_offset, int pin,
1109                          int mark_free)
1110 {
1111         struct btrfs_path *path;
1112         struct btrfs_key key;
1113         struct btrfs_fs_info *info = root->fs_info;
1114         struct btrfs_root *extent_root = info->extent_root;
1115         struct extent_buffer *leaf;
1116         int ret;
1117         struct btrfs_extent_item *ei;
1118         u32 refs;
1119
1120         key.objectid = bytenr;
1121         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1122         key.offset = num_bytes;
1123
1124         path = btrfs_alloc_path();
1125         if (!path)
1126                 return -ENOMEM;
1127
1128         if (ref_generation && owner_objectid == 0 && root_objectid == 3) {
1129 //printk("drop backref root %Lu gen %Lu byte %Lu\n", root_objectid, ref_generation, bytenr );
1130         }
1131         ret = lookup_extent_backref(trans, extent_root, path,
1132                                     bytenr, root_objectid,
1133                                     ref_generation,
1134                                     owner_objectid, owner_offset, 1);
1135         if (ret == 0) {
1136                 ret = btrfs_del_item(trans, extent_root, path);
1137         } else {
1138                 btrfs_print_leaf(extent_root, path->nodes[0]);
1139                 WARN_ON(1);
1140                 printk("Unable to find ref byte nr %Lu root %Lu "
1141                        " gen %Lu owner %Lu offset %Lu\n", bytenr,
1142                        root_objectid, ref_generation, owner_objectid,
1143                        owner_offset);
1144         }
1145         btrfs_release_path(extent_root, path);
1146         ret = btrfs_search_slot(trans, extent_root, &key, path, -1, 1);
1147         if (ret < 0)
1148                 return ret;
1149         BUG_ON(ret);
1150
1151         leaf = path->nodes[0];
1152         ei = btrfs_item_ptr(leaf, path->slots[0],
1153                             struct btrfs_extent_item);
1154         refs = btrfs_extent_refs(leaf, ei);
1155         BUG_ON(refs == 0);
1156         refs -= 1;
1157         btrfs_set_extent_refs(leaf, ei, refs);
1158         btrfs_mark_buffer_dirty(leaf);
1159
1160         if (refs == 0) {
1161                 u64 super_used;
1162                 u64 root_used;
1163
1164                 if (pin) {
1165                         ret = pin_down_bytes(root, bytenr, num_bytes, 0);
1166                         if (ret > 0)
1167                                 mark_free = 1;
1168                         BUG_ON(ret < 0);
1169                 }
1170
1171                 /* block accounting for super block */
1172                 super_used = btrfs_super_bytes_used(&info->super_copy);
1173                 btrfs_set_super_bytes_used(&info->super_copy,
1174                                            super_used - num_bytes);
1175
1176                 /* block accounting for root item */
1177                 root_used = btrfs_root_used(&root->root_item);
1178                 btrfs_set_root_used(&root->root_item,
1179                                            root_used - num_bytes);
1180
1181                 ret = btrfs_del_item(trans, extent_root, path);
1182                 if (ret) {
1183                         return ret;
1184                 }
1185                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
1186                                          mark_free, 0);
1187                 BUG_ON(ret);
1188         }
1189         btrfs_free_path(path);
1190         finish_current_insert(trans, extent_root);
1191         return ret;
1192 }
1193
1194 /*
1195  * find all the blocks marked as pending in the radix tree and remove
1196  * them from the extent map
1197  */
1198 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
1199                                btrfs_root *extent_root)
1200 {
1201         int ret;
1202         int err = 0;
1203         u64 start;
1204         u64 end;
1205         struct extent_map_tree *pending_del;
1206         struct extent_map_tree *pinned_extents;
1207
1208         pending_del = &extent_root->fs_info->pending_del;
1209         pinned_extents = &extent_root->fs_info->pinned_extents;
1210
1211         while(1) {
1212                 ret = find_first_extent_bit(pending_del, 0, &start, &end,
1213                                             EXTENT_LOCKED);
1214                 if (ret)
1215                         break;
1216                 update_pinned_extents(extent_root, start, end + 1 - start, 1);
1217                 clear_extent_bits(pending_del, start, end, EXTENT_LOCKED,
1218                                   GFP_NOFS);
1219                 ret = __free_extent(trans, extent_root,
1220                                      start, end + 1 - start,
1221                                      extent_root->root_key.objectid,
1222                                      0, 0, 0, 0, 0);
1223                 if (ret)
1224                         err = ret;
1225         }
1226         return err;
1227 }
1228
1229 /*
1230  * remove an extent from the root, returns 0 on success
1231  */
1232 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1233                       *root, u64 bytenr, u64 num_bytes,
1234                       u64 root_objectid, u64 ref_generation,
1235                       u64 owner_objectid, u64 owner_offset, int pin)
1236 {
1237         struct btrfs_root *extent_root = root->fs_info->extent_root;
1238         int pending_ret;
1239         int ret;
1240
1241         WARN_ON(num_bytes < root->sectorsize);
1242         if (!root->ref_cows)
1243                 ref_generation = 0;
1244
1245         if (root == extent_root) {
1246                 pin_down_bytes(root, bytenr, num_bytes, 1);
1247                 return 0;
1248         }
1249         ret = __free_extent(trans, root, bytenr, num_bytes, root_objectid,
1250                             ref_generation, owner_objectid, owner_offset,
1251                             pin, pin == 0);
1252         pending_ret = del_pending_extents(trans, root->fs_info->extent_root);
1253         return ret ? ret : pending_ret;
1254 }
1255
1256 static u64 stripe_align(struct btrfs_root *root, u64 val)
1257 {
1258         u64 mask = ((u64)root->stripesize - 1);
1259         u64 ret = (val + mask) & ~mask;
1260         return ret;
1261 }
1262
1263 /*
1264  * walks the btree of allocated extents and find a hole of a given size.
1265  * The key ins is changed to record the hole:
1266  * ins->objectid == block start
1267  * ins->flags = BTRFS_EXTENT_ITEM_KEY
1268  * ins->offset == number of blocks
1269  * Any available blocks before search_start are skipped.
1270  */
1271 static int find_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1272                             *orig_root, u64 num_bytes, u64 empty_size,
1273                             u64 search_start, u64 search_end, u64 hint_byte,
1274                             struct btrfs_key *ins, u64 exclude_start,
1275                             u64 exclude_nr, int data)
1276 {
1277         struct btrfs_path *path;
1278         struct btrfs_key key;
1279         u64 hole_size = 0;
1280         u64 aligned;
1281         int ret;
1282         int slot = 0;
1283         u64 last_byte = 0;
1284         u64 orig_search_start = search_start;
1285         int start_found;
1286         struct extent_buffer *l;
1287         struct btrfs_root * root = orig_root->fs_info->extent_root;
1288         struct btrfs_fs_info *info = root->fs_info;
1289         u64 total_needed = num_bytes;
1290         int level;
1291         struct btrfs_block_group_cache *block_group;
1292         int full_scan = 0;
1293         int wrapped = 0;
1294         u64 cached_start;
1295
1296         WARN_ON(num_bytes < root->sectorsize);
1297         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
1298
1299         level = btrfs_header_level(root->node);
1300
1301         if (num_bytes >= 32 * 1024 * 1024 && hint_byte) {
1302                 data = BTRFS_BLOCK_GROUP_MIXED;
1303         }
1304
1305         if (search_end == (u64)-1)
1306                 search_end = btrfs_super_total_bytes(&info->super_copy);
1307         if (hint_byte) {
1308                 block_group = btrfs_lookup_block_group(info, hint_byte);
1309                 if (!block_group)
1310                         hint_byte = search_start;
1311                 block_group = btrfs_find_block_group(root, block_group,
1312                                                      hint_byte, data, 1);
1313         } else {
1314                 block_group = btrfs_find_block_group(root,
1315                                                      trans->block_group,
1316                                                      search_start, data, 1);
1317         }
1318
1319         total_needed += empty_size;
1320         path = btrfs_alloc_path();
1321 check_failed:
1322         search_start = find_search_start(root, &block_group, search_start,
1323                                          total_needed, data, full_scan);
1324         search_start = stripe_align(root, search_start);
1325         cached_start = search_start;
1326         btrfs_init_path(path);
1327         ins->objectid = search_start;
1328         ins->offset = 0;
1329         start_found = 0;
1330         path->reada = 2;
1331
1332         ret = btrfs_search_slot(trans, root, ins, path, 0, 0);
1333         if (ret < 0)
1334                 goto error;
1335
1336         if (path->slots[0] > 0) {
1337                 path->slots[0]--;
1338         }
1339
1340         l = path->nodes[0];
1341         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1342
1343         /*
1344          * walk backwards to find the first extent item key
1345          */
1346         while(btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY) {
1347                 if (path->slots[0] == 0) {
1348                         ret = btrfs_prev_leaf(root, path);
1349                         if (ret != 0) {
1350                                 ret = btrfs_search_slot(trans, root, ins,
1351                                                         path, 0, 0);
1352                                 if (ret < 0)
1353                                         goto error;
1354                                 if (path->slots[0] > 0)
1355                                         path->slots[0]--;
1356                                 break;
1357                         }
1358                 } else {
1359                         path->slots[0]--;
1360                 }
1361                 l = path->nodes[0];
1362                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1363         }
1364         while (1) {
1365                 l = path->nodes[0];
1366                 slot = path->slots[0];
1367                 if (slot >= btrfs_header_nritems(l)) {
1368                         ret = btrfs_next_leaf(root, path);
1369                         if (ret == 0)
1370                                 continue;
1371                         if (ret < 0)
1372                                 goto error;
1373
1374                         search_start = max(search_start,
1375                                            block_group->key.objectid);
1376                         if (!start_found) {
1377                                 aligned = stripe_align(root, search_start);
1378                                 ins->objectid = aligned;
1379                                 if (aligned >= search_end) {
1380                                         ret = -ENOSPC;
1381                                         goto error;
1382                                 }
1383                                 ins->offset = search_end - aligned;
1384                                 start_found = 1;
1385                                 goto check_pending;
1386                         }
1387                         ins->objectid = stripe_align(root,
1388                                                      last_byte > search_start ?
1389                                                      last_byte : search_start);
1390                         if (search_end <= ins->objectid) {
1391                                 ret = -ENOSPC;
1392                                 goto error;
1393                         }
1394                         ins->offset = search_end - ins->objectid;
1395                         BUG_ON(ins->objectid >= search_end);
1396                         goto check_pending;
1397                 }
1398                 btrfs_item_key_to_cpu(l, &key, slot);
1399
1400                 if (key.objectid >= search_start && key.objectid > last_byte &&
1401                     start_found) {
1402                         if (last_byte < search_start)
1403                                 last_byte = search_start;
1404                         aligned = stripe_align(root, last_byte);
1405                         hole_size = key.objectid - aligned;
1406                         if (key.objectid > aligned && hole_size >= num_bytes) {
1407                                 ins->objectid = aligned;
1408                                 ins->offset = hole_size;
1409                                 goto check_pending;
1410                         }
1411                 }
1412                 if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY) {
1413                         if (!start_found && btrfs_key_type(&key) ==
1414                             BTRFS_BLOCK_GROUP_ITEM_KEY) {
1415                                 last_byte = key.objectid;
1416                                 start_found = 1;
1417                         }
1418                         goto next;
1419                 }
1420
1421
1422                 start_found = 1;
1423                 last_byte = key.objectid + key.offset;
1424
1425                 if (!full_scan && data != BTRFS_BLOCK_GROUP_MIXED &&
1426                     last_byte >= block_group->key.objectid +
1427                     block_group->key.offset) {
1428                         btrfs_release_path(root, path);
1429                         search_start = block_group->key.objectid +
1430                                 block_group->key.offset;
1431                         goto new_group;
1432                 }
1433 next:
1434                 path->slots[0]++;
1435                 cond_resched();
1436         }
1437 check_pending:
1438         /* we have to make sure we didn't find an extent that has already
1439          * been allocated by the map tree or the original allocation
1440          */
1441         btrfs_release_path(root, path);
1442         BUG_ON(ins->objectid < search_start);
1443
1444         if (ins->objectid + num_bytes >= search_end)
1445                 goto enospc;
1446         if (!full_scan && data != BTRFS_BLOCK_GROUP_MIXED &&
1447             ins->objectid + num_bytes > block_group->
1448             key.objectid + block_group->key.offset) {
1449                 search_start = block_group->key.objectid +
1450                         block_group->key.offset;
1451                 goto new_group;
1452         }
1453         if (test_range_bit(&info->extent_ins, ins->objectid,
1454                            ins->objectid + num_bytes -1, EXTENT_LOCKED, 0)) {
1455                 search_start = ins->objectid + num_bytes;
1456                 goto new_group;
1457         }
1458         if (test_range_bit(&info->pinned_extents, ins->objectid,
1459                            ins->objectid + num_bytes -1, EXTENT_DIRTY, 0)) {
1460                 search_start = ins->objectid + num_bytes;
1461                 goto new_group;
1462         }
1463         if (exclude_nr > 0 && (ins->objectid + num_bytes > exclude_start &&
1464             ins->objectid < exclude_start + exclude_nr)) {
1465                 search_start = exclude_start + exclude_nr;
1466                 goto new_group;
1467         }
1468         if (!data) {
1469                 block_group = btrfs_lookup_block_group(info, ins->objectid);
1470                 if (block_group)
1471                         trans->block_group = block_group;
1472         }
1473         ins->offset = num_bytes;
1474         btrfs_free_path(path);
1475         return 0;
1476
1477 new_group:
1478         if (search_start + num_bytes >= search_end) {
1479 enospc:
1480                 search_start = orig_search_start;
1481                 if (full_scan) {
1482                         ret = -ENOSPC;
1483                         goto error;
1484                 }
1485                 if (wrapped) {
1486                         if (!full_scan)
1487                                 total_needed -= empty_size;
1488                         full_scan = 1;
1489                         data = BTRFS_BLOCK_GROUP_MIXED;
1490                 } else
1491                         wrapped = 1;
1492         }
1493         block_group = btrfs_lookup_block_group(info, search_start);
1494         cond_resched();
1495         block_group = btrfs_find_block_group(root, block_group,
1496                                              search_start, data, 0);
1497         goto check_failed;
1498
1499 error:
1500         btrfs_release_path(root, path);
1501         btrfs_free_path(path);
1502         return ret;
1503 }
1504 /*
1505  * finds a free extent and does all the dirty work required for allocation
1506  * returns the key for the extent through ins, and a tree buffer for
1507  * the first block of the extent through buf.
1508  *
1509  * returns 0 if everything worked, non-zero otherwise.
1510  */
1511 int btrfs_alloc_extent(struct btrfs_trans_handle *trans,
1512                        struct btrfs_root *root,
1513                        u64 num_bytes, u64 root_objectid, u64 ref_generation,
1514                        u64 owner, u64 owner_offset,
1515                        u64 empty_size, u64 hint_byte,
1516                        u64 search_end, struct btrfs_key *ins, int data)
1517 {
1518         int ret;
1519         int pending_ret;
1520         u64 super_used, root_used;
1521         u64 search_start = 0;
1522         struct btrfs_fs_info *info = root->fs_info;
1523         struct btrfs_root *extent_root = info->extent_root;
1524         struct btrfs_extent_item extent_item;
1525         struct btrfs_path *path;
1526
1527         btrfs_set_stack_extent_refs(&extent_item, 1);
1528
1529         WARN_ON(num_bytes < root->sectorsize);
1530         ret = find_free_extent(trans, root, num_bytes, empty_size,
1531                                search_start, search_end, hint_byte, ins,
1532                                trans->alloc_exclude_start,
1533                                trans->alloc_exclude_nr, data);
1534         BUG_ON(ret);
1535         if (ret)
1536                 return ret;
1537
1538         /* block accounting for super block */
1539         super_used = btrfs_super_bytes_used(&info->super_copy);
1540         btrfs_set_super_bytes_used(&info->super_copy, super_used + num_bytes);
1541
1542         /* block accounting for root item */
1543         root_used = btrfs_root_used(&root->root_item);
1544         btrfs_set_root_used(&root->root_item, root_used + num_bytes);
1545
1546         clear_extent_dirty(&root->fs_info->free_space_cache,
1547                            ins->objectid, ins->objectid + ins->offset - 1,
1548                            GFP_NOFS);
1549
1550         if (root == extent_root) {
1551                 set_extent_bits(&root->fs_info->extent_ins, ins->objectid,
1552                                 ins->objectid + ins->offset - 1,
1553                                 EXTENT_LOCKED, GFP_NOFS);
1554                 WARN_ON(data == 1);
1555                 goto update_block;
1556         }
1557
1558         WARN_ON(trans->alloc_exclude_nr);
1559         trans->alloc_exclude_start = ins->objectid;
1560         trans->alloc_exclude_nr = ins->offset;
1561         ret = btrfs_insert_item(trans, extent_root, ins, &extent_item,
1562                                 sizeof(extent_item));
1563
1564         trans->alloc_exclude_start = 0;
1565         trans->alloc_exclude_nr = 0;
1566         BUG_ON(ret);
1567
1568         path = btrfs_alloc_path();
1569         BUG_ON(!path);
1570         ret = btrfs_insert_extent_backref(trans, extent_root, path,
1571                                           ins->objectid, root_objectid,
1572                                           ref_generation, owner, owner_offset);
1573
1574         BUG_ON(ret);
1575         btrfs_free_path(path);
1576         finish_current_insert(trans, extent_root);
1577         pending_ret = del_pending_extents(trans, extent_root);
1578
1579         if (ret) {
1580                 return ret;
1581         }
1582         if (pending_ret) {
1583                 return pending_ret;
1584         }
1585
1586 update_block:
1587         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1, 0,
1588                                  data);
1589         BUG_ON(ret);
1590         return 0;
1591 }
1592
1593 /*
1594  * helper function to allocate a block for a given tree
1595  * returns the tree buffer or NULL.
1596  */
1597 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1598                                              struct btrfs_root *root,
1599                                              u32 blocksize,
1600                                              u64 root_objectid, u64 hint,
1601                                              u64 empty_size)
1602 {
1603         u64 ref_generation;
1604
1605         if (root->ref_cows)
1606                 ref_generation = trans->transid;
1607         else
1608                 ref_generation = 0;
1609
1610
1611         return __btrfs_alloc_free_block(trans, root, blocksize, root_objectid,
1612                                         ref_generation, 0, 0, hint, empty_size);
1613 }
1614
1615 /*
1616  * helper function to allocate a block for a given tree
1617  * returns the tree buffer or NULL.
1618  */
1619 struct extent_buffer *__btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1620                                              struct btrfs_root *root,
1621                                              u32 blocksize,
1622                                              u64 root_objectid,
1623                                              u64 ref_generation,
1624                                              u64 first_objectid,
1625                                              int level,
1626                                              u64 hint,
1627                                              u64 empty_size)
1628 {
1629         struct btrfs_key ins;
1630         int ret;
1631         struct extent_buffer *buf;
1632
1633         ret = btrfs_alloc_extent(trans, root, blocksize,
1634                                  root_objectid, ref_generation,
1635                                  first_objectid, level, empty_size, hint,
1636                                  (u64)-1, &ins, 0);
1637         if (ret) {
1638                 BUG_ON(ret > 0);
1639                 return ERR_PTR(ret);
1640         }
1641         buf = btrfs_find_create_tree_block(root, ins.objectid, blocksize);
1642         if (!buf) {
1643                 btrfs_free_extent(trans, root, ins.objectid, blocksize,
1644                                   root->root_key.objectid, ref_generation,
1645                                   0, 0, 0);
1646                 return ERR_PTR(-ENOMEM);
1647         }
1648         btrfs_set_buffer_uptodate(buf);
1649         set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
1650                          buf->start + buf->len - 1, GFP_NOFS);
1651         set_extent_bits(&BTRFS_I(root->fs_info->btree_inode)->extent_tree,
1652                         buf->start, buf->start + buf->len - 1,
1653                         EXTENT_CSUM, GFP_NOFS);
1654         buf->flags |= EXTENT_CSUM;
1655         btrfs_set_buffer_defrag(buf);
1656         trans->blocks_used++;
1657         return buf;
1658 }
1659
1660 static int drop_leaf_ref(struct btrfs_trans_handle *trans,
1661                          struct btrfs_root *root, struct extent_buffer *leaf)
1662 {
1663         u64 leaf_owner;
1664         u64 leaf_generation;
1665         struct btrfs_key key;
1666         struct btrfs_file_extent_item *fi;
1667         int i;
1668         int nritems;
1669         int ret;
1670
1671         BUG_ON(!btrfs_is_leaf(leaf));
1672         nritems = btrfs_header_nritems(leaf);
1673         leaf_owner = btrfs_header_owner(leaf);
1674         leaf_generation = btrfs_header_generation(leaf);
1675
1676         for (i = 0; i < nritems; i++) {
1677                 u64 disk_bytenr;
1678
1679                 btrfs_item_key_to_cpu(leaf, &key, i);
1680                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1681                         continue;
1682                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
1683                 if (btrfs_file_extent_type(leaf, fi) ==
1684                     BTRFS_FILE_EXTENT_INLINE)
1685                         continue;
1686                 /*
1687                  * FIXME make sure to insert a trans record that
1688                  * repeats the snapshot del on crash
1689                  */
1690                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1691                 if (disk_bytenr == 0)
1692                         continue;
1693                 ret = btrfs_free_extent(trans, root, disk_bytenr,
1694                                 btrfs_file_extent_disk_num_bytes(leaf, fi),
1695                                 leaf_owner, leaf_generation,
1696                                 key.objectid, key.offset, 0);
1697                 BUG_ON(ret);
1698         }
1699         return 0;
1700 }
1701
1702 static void reada_walk_down(struct btrfs_root *root,
1703                             struct extent_buffer *node)
1704 {
1705         int i;
1706         u32 nritems;
1707         u64 bytenr;
1708         int ret;
1709         u32 refs;
1710         int level;
1711         u32 blocksize;
1712
1713         nritems = btrfs_header_nritems(node);
1714         level = btrfs_header_level(node);
1715         for (i = 0; i < nritems; i++) {
1716                 bytenr = btrfs_node_blockptr(node, i);
1717                 blocksize = btrfs_level_size(root, level - 1);
1718                 ret = lookup_extent_ref(NULL, root, bytenr, blocksize, &refs);
1719                 BUG_ON(ret);
1720                 if (refs != 1)
1721                         continue;
1722                 mutex_unlock(&root->fs_info->fs_mutex);
1723                 ret = readahead_tree_block(root, bytenr, blocksize);
1724                 cond_resched();
1725                 mutex_lock(&root->fs_info->fs_mutex);
1726                 if (ret)
1727                         break;
1728         }
1729 }
1730
1731 /*
1732  * helper function for drop_snapshot, this walks down the tree dropping ref
1733  * counts as it goes.
1734  */
1735 static int walk_down_tree(struct btrfs_trans_handle *trans, struct btrfs_root
1736                           *root, struct btrfs_path *path, int *level)
1737 {
1738         u64 root_owner;
1739         u64 root_gen;
1740         u64 bytenr;
1741         struct extent_buffer *next;
1742         struct extent_buffer *cur;
1743         struct extent_buffer *parent;
1744         u32 blocksize;
1745         int ret;
1746         u32 refs;
1747
1748         WARN_ON(*level < 0);
1749         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1750         ret = lookup_extent_ref(trans, root,
1751                                 path->nodes[*level]->start,
1752                                 path->nodes[*level]->len, &refs);
1753         BUG_ON(ret);
1754         if (refs > 1)
1755                 goto out;
1756
1757         /*
1758          * walk down to the last node level and free all the leaves
1759          */
1760         while(*level >= 0) {
1761                 WARN_ON(*level < 0);
1762                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1763                 cur = path->nodes[*level];
1764
1765                 if (*level > 0 && path->slots[*level] == 0)
1766                         reada_walk_down(root, cur);
1767
1768                 if (btrfs_header_level(cur) != *level)
1769                         WARN_ON(1);
1770
1771                 if (path->slots[*level] >=
1772                     btrfs_header_nritems(cur))
1773                         break;
1774                 if (*level == 0) {
1775                         ret = drop_leaf_ref(trans, root, cur);
1776                         BUG_ON(ret);
1777                         break;
1778                 }
1779                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1780                 blocksize = btrfs_level_size(root, *level - 1);
1781                 ret = lookup_extent_ref(trans, root, bytenr, blocksize, &refs);
1782                 BUG_ON(ret);
1783                 if (refs != 1) {
1784                         parent = path->nodes[*level];
1785                         root_owner = btrfs_header_owner(parent);
1786                         root_gen = btrfs_header_generation(parent);
1787                         path->slots[*level]++;
1788                         ret = btrfs_free_extent(trans, root, bytenr,
1789                                                 blocksize, root_owner,
1790                                                 root_gen, 0, 0, 1);
1791                         BUG_ON(ret);
1792                         continue;
1793                 }
1794                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1795                 if (!next || !btrfs_buffer_uptodate(next)) {
1796                         free_extent_buffer(next);
1797                         mutex_unlock(&root->fs_info->fs_mutex);
1798                         next = read_tree_block(root, bytenr, blocksize);
1799                         mutex_lock(&root->fs_info->fs_mutex);
1800
1801                         /* we dropped the lock, check one more time */
1802                         ret = lookup_extent_ref(trans, root, bytenr,
1803                                                 blocksize, &refs);
1804                         BUG_ON(ret);
1805                         if (refs != 1) {
1806                                 parent = path->nodes[*level];
1807                                 root_owner = btrfs_header_owner(parent);
1808                                 root_gen = btrfs_header_generation(parent);
1809
1810                                 path->slots[*level]++;
1811                                 free_extent_buffer(next);
1812                                 ret = btrfs_free_extent(trans, root, bytenr,
1813                                                         blocksize,
1814                                                         root_owner,
1815                                                         root_gen, 0, 0, 1);
1816                                 BUG_ON(ret);
1817                                 continue;
1818                         }
1819                 }
1820                 WARN_ON(*level <= 0);
1821                 if (path->nodes[*level-1])
1822                         free_extent_buffer(path->nodes[*level-1]);
1823                 path->nodes[*level-1] = next;
1824                 *level = btrfs_header_level(next);
1825                 path->slots[*level] = 0;
1826         }
1827 out:
1828         WARN_ON(*level < 0);
1829         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1830
1831         if (path->nodes[*level] == root->node) {
1832                 root_owner = root->root_key.objectid;
1833                 parent = path->nodes[*level];
1834         } else {
1835                 parent = path->nodes[*level + 1];
1836                 root_owner = btrfs_header_owner(parent);
1837         }
1838
1839         root_gen = btrfs_header_generation(parent);
1840         ret = btrfs_free_extent(trans, root, path->nodes[*level]->start,
1841                                 path->nodes[*level]->len,
1842                                 root_owner, root_gen, 0, 0, 1);
1843         free_extent_buffer(path->nodes[*level]);
1844         path->nodes[*level] = NULL;
1845         *level += 1;
1846         BUG_ON(ret);
1847         return 0;
1848 }
1849
1850 /*
1851  * helper for dropping snapshots.  This walks back up the tree in the path
1852  * to find the first node higher up where we haven't yet gone through
1853  * all the slots
1854  */
1855 static int walk_up_tree(struct btrfs_trans_handle *trans, struct btrfs_root
1856                         *root, struct btrfs_path *path, int *level)
1857 {
1858         u64 root_owner;
1859         u64 root_gen;
1860         struct btrfs_root_item *root_item = &root->root_item;
1861         int i;
1862         int slot;
1863         int ret;
1864
1865         for(i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1866                 slot = path->slots[i];
1867                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
1868                         struct extent_buffer *node;
1869                         struct btrfs_disk_key disk_key;
1870                         node = path->nodes[i];
1871                         path->slots[i]++;
1872                         *level = i;
1873                         WARN_ON(*level == 0);
1874                         btrfs_node_key(node, &disk_key, path->slots[i]);
1875                         memcpy(&root_item->drop_progress,
1876                                &disk_key, sizeof(disk_key));
1877                         root_item->drop_level = i;
1878                         return 0;
1879                 } else {
1880                         if (path->nodes[*level] == root->node) {
1881                                 root_owner = root->root_key.objectid;
1882                                 root_gen =
1883                                    btrfs_header_generation(path->nodes[*level]);
1884                         } else {
1885                                 struct extent_buffer *node;
1886                                 node = path->nodes[*level + 1];
1887                                 root_owner = btrfs_header_owner(node);
1888                                 root_gen = btrfs_header_generation(node);
1889                         }
1890                         ret = btrfs_free_extent(trans, root,
1891                                                 path->nodes[*level]->start,
1892                                                 path->nodes[*level]->len,
1893                                                 root_owner, root_gen, 0, 0, 1);
1894                         BUG_ON(ret);
1895                         free_extent_buffer(path->nodes[*level]);
1896                         path->nodes[*level] = NULL;
1897                         *level = i + 1;
1898                 }
1899         }
1900         return 1;
1901 }
1902
1903 /*
1904  * drop the reference count on the tree rooted at 'snap'.  This traverses
1905  * the tree freeing any blocks that have a ref count of zero after being
1906  * decremented.
1907  */
1908 int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
1909                         *root)
1910 {
1911         int ret = 0;
1912         int wret;
1913         int level;
1914         struct btrfs_path *path;
1915         int i;
1916         int orig_level;
1917         struct btrfs_root_item *root_item = &root->root_item;
1918
1919         path = btrfs_alloc_path();
1920         BUG_ON(!path);
1921
1922         level = btrfs_header_level(root->node);
1923         orig_level = level;
1924         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1925                 path->nodes[level] = root->node;
1926                 extent_buffer_get(root->node);
1927                 path->slots[level] = 0;
1928         } else {
1929                 struct btrfs_key key;
1930                 struct btrfs_disk_key found_key;
1931                 struct extent_buffer *node;
1932
1933                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1934                 level = root_item->drop_level;
1935                 path->lowest_level = level;
1936                 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1937                 if (wret < 0) {
1938                         ret = wret;
1939                         goto out;
1940                 }
1941                 node = path->nodes[level];
1942                 btrfs_node_key(node, &found_key, path->slots[level]);
1943                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1944                                sizeof(found_key)));
1945         }
1946         while(1) {
1947                 wret = walk_down_tree(trans, root, path, &level);
1948                 if (wret > 0)
1949                         break;
1950                 if (wret < 0)
1951                         ret = wret;
1952
1953                 wret = walk_up_tree(trans, root, path, &level);
1954                 if (wret > 0)
1955                         break;
1956                 if (wret < 0)
1957                         ret = wret;
1958                 ret = -EAGAIN;
1959                 break;
1960         }
1961         for (i = 0; i <= orig_level; i++) {
1962                 if (path->nodes[i]) {
1963                         free_extent_buffer(path->nodes[i]);
1964                         path->nodes[i] = NULL;
1965                 }
1966         }
1967 out:
1968         btrfs_free_path(path);
1969         return ret;
1970 }
1971
1972 int btrfs_free_block_groups(struct btrfs_fs_info *info)
1973 {
1974         u64 start;
1975         u64 end;
1976         u64 ptr;
1977         int ret;
1978         while(1) {
1979                 ret = find_first_extent_bit(&info->block_group_cache, 0,
1980                                             &start, &end, (unsigned int)-1);
1981                 if (ret)
1982                         break;
1983                 ret = get_state_private(&info->block_group_cache, start, &ptr);
1984                 if (!ret)
1985                         kfree((void *)(unsigned long)ptr);
1986                 clear_extent_bits(&info->block_group_cache, start,
1987                                   end, (unsigned int)-1, GFP_NOFS);
1988         }
1989         while(1) {
1990                 ret = find_first_extent_bit(&info->free_space_cache, 0,
1991                                             &start, &end, EXTENT_DIRTY);
1992                 if (ret)
1993                         break;
1994                 clear_extent_dirty(&info->free_space_cache, start,
1995                                    end, GFP_NOFS);
1996         }
1997         return 0;
1998 }
1999
2000 int btrfs_read_block_groups(struct btrfs_root *root)
2001 {
2002         struct btrfs_path *path;
2003         int ret;
2004         int err = 0;
2005         int bit;
2006         struct btrfs_block_group_cache *cache;
2007         struct btrfs_fs_info *info = root->fs_info;
2008         struct extent_map_tree *block_group_cache;
2009         struct btrfs_key key;
2010         struct btrfs_key found_key;
2011         struct extent_buffer *leaf;
2012
2013         block_group_cache = &info->block_group_cache;
2014
2015         root = info->extent_root;
2016         key.objectid = 0;
2017         key.offset = BTRFS_BLOCK_GROUP_SIZE;
2018         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
2019
2020         path = btrfs_alloc_path();
2021         if (!path)
2022                 return -ENOMEM;
2023
2024         while(1) {
2025                 ret = btrfs_search_slot(NULL, info->extent_root,
2026                                         &key, path, 0, 0);
2027                 if (ret != 0) {
2028                         err = ret;
2029                         break;
2030                 }
2031                 leaf = path->nodes[0];
2032                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2033                 cache = kmalloc(sizeof(*cache), GFP_NOFS);
2034                 if (!cache) {
2035                         err = -1;
2036                         break;
2037                 }
2038
2039                 read_extent_buffer(leaf, &cache->item,
2040                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
2041                                    sizeof(cache->item));
2042                 memcpy(&cache->key, &found_key, sizeof(found_key));
2043                 cache->cached = 0;
2044                 cache->pinned = 0;
2045                 key.objectid = found_key.objectid + found_key.offset;
2046                 btrfs_release_path(root, path);
2047
2048                 if (cache->item.flags & BTRFS_BLOCK_GROUP_MIXED) {
2049                         bit = BLOCK_GROUP_DATA | BLOCK_GROUP_METADATA;
2050                         cache->data = BTRFS_BLOCK_GROUP_MIXED;
2051                 } else if (cache->item.flags & BTRFS_BLOCK_GROUP_DATA) {
2052                         bit = BLOCK_GROUP_DATA;
2053                         cache->data = BTRFS_BLOCK_GROUP_DATA;
2054                 } else {
2055                         bit = BLOCK_GROUP_METADATA;
2056                         cache->data = 0;
2057                 }
2058
2059                 /* use EXTENT_LOCKED to prevent merging */
2060                 set_extent_bits(block_group_cache, found_key.objectid,
2061                                 found_key.objectid + found_key.offset - 1,
2062                                 bit | EXTENT_LOCKED, GFP_NOFS);
2063                 set_state_private(block_group_cache, found_key.objectid,
2064                                   (unsigned long)cache);
2065
2066                 if (key.objectid >=
2067                     btrfs_super_total_bytes(&info->super_copy))
2068                         break;
2069         }
2070
2071         btrfs_free_path(path);
2072         return 0;
2073 }