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