Recow all roots at the end of mkfs
[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) == transid) {
1266                                         free_extent_buffer(buf);
1267                                         return 1;
1268                                 }
1269                         }
1270                         free_extent_buffer(buf);
1271                 }
1272                 update_pinned_extents(root, bytenr, num_bytes, 1);
1273         } else {
1274                 set_extent_bits(&root->fs_info->pending_del,
1275                                 bytenr, bytenr + num_bytes - 1,
1276                                 EXTENT_LOCKED, GFP_NOFS);
1277         }
1278         BUG_ON(err < 0);
1279         return 0;
1280 }
1281
1282 /*
1283  * remove an extent from the root, returns 0 on success
1284  */
1285 static int __free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1286                          *root, u64 bytenr, u64 num_bytes,
1287                          u64 root_objectid, u64 ref_generation,
1288                          u64 owner_objectid, u64 owner_offset, int pin,
1289                          int mark_free)
1290 {
1291         struct btrfs_path *path;
1292         struct btrfs_key key;
1293         struct btrfs_fs_info *info = root->fs_info;
1294         struct btrfs_extent_ops *ops = info->extent_ops;
1295         struct btrfs_root *extent_root = info->extent_root;
1296         struct extent_buffer *leaf;
1297         int ret;
1298         int extent_slot = 0;
1299         int found_extent = 0;
1300         int num_to_del = 1;
1301         struct btrfs_extent_item *ei;
1302         u32 refs;
1303
1304         key.objectid = bytenr;
1305         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1306         key.offset = num_bytes;
1307
1308         path = btrfs_alloc_path();
1309         if (!path)
1310                 return -ENOMEM;
1311
1312         ret = lookup_extent_backref(trans, extent_root, path,
1313                                     bytenr, root_objectid,
1314                                     ref_generation,
1315                                     owner_objectid, owner_offset, 1);
1316         if (ret == 0) {
1317                 struct btrfs_key found_key;
1318                 extent_slot = path->slots[0];
1319                 while(extent_slot > 0) {
1320                         extent_slot--;
1321                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1322                                               extent_slot);
1323                         if (found_key.objectid != bytenr)
1324                                 break;
1325                         if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1326                             found_key.offset == num_bytes) {
1327                                 found_extent = 1;
1328                                 break;
1329                         }
1330                         if (path->slots[0] - extent_slot > 5)
1331                                 break;
1332                 }
1333                 if (!found_extent)
1334                         ret = btrfs_del_item(trans, extent_root, path);
1335         } else {
1336                 btrfs_print_leaf(extent_root, path->nodes[0]);
1337                 WARN_ON(1);
1338                 printk("Unable to find ref byte nr %llu root %llu "
1339                        " gen %llu owner %llu offset %llu\n",
1340                        (unsigned long long)bytenr,
1341                        (unsigned long long)root_objectid,
1342                        (unsigned long long)ref_generation,
1343                        (unsigned long long)owner_objectid,
1344                        (unsigned long long)owner_offset);
1345         }
1346         if (!found_extent) {
1347                 btrfs_release_path(extent_root, path);
1348                 ret = btrfs_search_slot(trans, extent_root, &key, path, -1, 1);
1349                 if (ret < 0)
1350                         return ret;
1351                 BUG_ON(ret);
1352                 extent_slot = path->slots[0];
1353         }
1354
1355         leaf = path->nodes[0];
1356         ei = btrfs_item_ptr(leaf, extent_slot,
1357                             struct btrfs_extent_item);
1358         refs = btrfs_extent_refs(leaf, ei);
1359         BUG_ON(refs == 0);
1360         refs -= 1;
1361         btrfs_set_extent_refs(leaf, ei, refs);
1362
1363         btrfs_mark_buffer_dirty(leaf);
1364
1365         if (refs == 0 && found_extent && path->slots[0] == extent_slot + 1) {
1366                 /* if the back ref and the extent are next to each other
1367                  * they get deleted below in one shot
1368                  */
1369                 path->slots[0] = extent_slot;
1370                 num_to_del = 2;
1371         } else if (found_extent) {
1372                 /* otherwise delete the extent back ref */
1373                 ret = btrfs_del_item(trans, extent_root, path);
1374                 BUG_ON(ret);
1375                 /* if refs are 0, we need to setup the path for deletion */
1376                 if (refs == 0) {
1377                         btrfs_release_path(extent_root, path);
1378                         ret = btrfs_search_slot(trans, extent_root, &key, path,
1379                                                 -1, 1);
1380                         if (ret < 0)
1381                                 return ret;
1382                         BUG_ON(ret);
1383                 }
1384         }
1385
1386         if (refs == 0) {
1387                 u64 super_used;
1388                 u64 root_used;
1389
1390                 if (pin) {
1391                         ret = pin_down_bytes(root, bytenr, num_bytes, 0);
1392                         if (ret > 0)
1393                                 mark_free = 1;
1394                         BUG_ON(ret < 0);
1395                 }
1396
1397                 /* block accounting for super block */
1398                 super_used = btrfs_super_bytes_used(&info->super_copy);
1399                 btrfs_set_super_bytes_used(&info->super_copy,
1400                                            super_used - num_bytes);
1401
1402                 /* block accounting for root item */
1403                 root_used = btrfs_root_used(&root->root_item);
1404                 btrfs_set_root_used(&root->root_item,
1405                                            root_used - num_bytes);
1406                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
1407                                       num_to_del);
1408                 if (ret)
1409                         return ret;
1410
1411                 if (ops && ops->free_extent)
1412                         ops->free_extent(root, bytenr, num_bytes);
1413
1414                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
1415                                          mark_free);
1416                 BUG_ON(ret);
1417         }
1418         btrfs_free_path(path);
1419         finish_current_insert(trans, extent_root);
1420         return ret;
1421 }
1422
1423 /*
1424  * find all the blocks marked as pending in the radix tree and remove
1425  * them from the extent map
1426  */
1427 static int del_pending_extents(struct btrfs_trans_handle *trans, struct
1428                                btrfs_root *extent_root)
1429 {
1430         int ret;
1431         int err = 0;
1432         u64 start;
1433         u64 end;
1434         struct extent_io_tree *pending_del;
1435         struct extent_io_tree *pinned_extents;
1436
1437         pending_del = &extent_root->fs_info->pending_del;
1438         pinned_extents = &extent_root->fs_info->pinned_extents;
1439
1440         while(1) {
1441                 ret = find_first_extent_bit(pending_del, 0, &start, &end,
1442                                             EXTENT_LOCKED);
1443                 if (ret)
1444                         break;
1445                 update_pinned_extents(extent_root, start, end + 1 - start, 1);
1446                 clear_extent_bits(pending_del, start, end, EXTENT_LOCKED,
1447                                   GFP_NOFS);
1448                 ret = __free_extent(trans, extent_root,
1449                                      start, end + 1 - start,
1450                                      extent_root->root_key.objectid,
1451                                      0, 0, 0, 0, 0);
1452                 if (ret)
1453                         err = ret;
1454         }
1455         return err;
1456 }
1457
1458 /*
1459  * remove an extent from the root, returns 0 on success
1460  */
1461 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root
1462                       *root, u64 bytenr, u64 num_bytes,
1463                       u64 root_objectid, u64 ref_generation,
1464                       u64 owner_objectid, u64 owner_offset, int pin)
1465 {
1466         struct btrfs_root *extent_root = root->fs_info->extent_root;
1467         int pending_ret;
1468         int ret;
1469
1470         WARN_ON(num_bytes < root->sectorsize);
1471         if (!root->ref_cows)
1472                 ref_generation = 0;
1473
1474         if (root == extent_root) {
1475                 pin_down_bytes(root, bytenr, num_bytes, 1);
1476                 return 0;
1477         }
1478         ret = __free_extent(trans, root, bytenr, num_bytes, root_objectid,
1479                             ref_generation, owner_objectid, owner_offset,
1480                             pin, pin == 0);
1481         pending_ret = del_pending_extents(trans, root->fs_info->extent_root);
1482         return ret ? ret : pending_ret;
1483 }
1484
1485 static u64 stripe_align(struct btrfs_root *root, u64 val)
1486 {
1487         u64 mask = ((u64)root->stripesize - 1);
1488         u64 ret = (val + mask) & ~mask;
1489         return ret;
1490 }
1491
1492 /*
1493  * walks the btree of allocated extents and find a hole of a given size.
1494  * The key ins is changed to record the hole:
1495  * ins->objectid == block start
1496  * ins->flags = BTRFS_EXTENT_ITEM_KEY
1497  * ins->offset == number of blocks
1498  * Any available blocks before search_start are skipped.
1499  */
1500 static int noinline find_free_extent(struct btrfs_trans_handle *trans,
1501                                      struct btrfs_root *orig_root,
1502                                      u64 num_bytes, u64 empty_size,
1503                                      u64 search_start, u64 search_end,
1504                                      u64 hint_byte, struct btrfs_key *ins,
1505                                      u64 exclude_start, u64 exclude_nr,
1506                                      int data)
1507 {
1508         int ret;
1509         u64 orig_search_start = search_start;
1510         struct btrfs_root * root = orig_root->fs_info->extent_root;
1511         struct btrfs_fs_info *info = root->fs_info;
1512         u64 total_needed = num_bytes;
1513         struct btrfs_block_group_cache *block_group;
1514         int full_scan = 0;
1515         int wrapped = 0;
1516
1517         WARN_ON(num_bytes < root->sectorsize);
1518         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
1519
1520         if (search_end == (u64)-1)
1521                 search_end = btrfs_super_total_bytes(&info->super_copy);
1522
1523         if (hint_byte) {
1524                 block_group = btrfs_lookup_block_group(info, hint_byte);
1525                 if (!block_group)
1526                         hint_byte = search_start;
1527                 block_group = btrfs_find_block_group(root, block_group,
1528                                                      hint_byte, data, 1);
1529         } else {
1530                 block_group = btrfs_find_block_group(root,
1531                                                      trans->block_group,
1532                                                      search_start, data, 1);
1533         }
1534
1535         total_needed += empty_size;
1536
1537 check_failed:
1538         if (!block_group) {
1539                 block_group = btrfs_lookup_block_group(info, search_start);
1540                 if (!block_group)
1541                         block_group = btrfs_lookup_block_group(info,
1542                                                        orig_search_start);
1543         }
1544         ret = find_search_start(root, &block_group, &search_start,
1545                                 total_needed, data);
1546         if (ret)
1547                 goto error;
1548
1549         search_start = stripe_align(root, search_start);
1550         ins->objectid = search_start;
1551         ins->offset = num_bytes;
1552
1553         if (ins->objectid + num_bytes >= search_end)
1554                 goto enospc;
1555
1556         if (ins->objectid + num_bytes >
1557             block_group->key.objectid + block_group->key.offset) {
1558                 search_start = block_group->key.objectid +
1559                         block_group->key.offset;
1560                 goto new_group;
1561         }
1562
1563         if (test_range_bit(&info->extent_ins, ins->objectid,
1564                            ins->objectid + num_bytes -1, EXTENT_LOCKED, 0)) {
1565                 search_start = ins->objectid + num_bytes;
1566                 goto new_group;
1567         }
1568
1569         if (test_range_bit(&info->pinned_extents, ins->objectid,
1570                            ins->objectid + num_bytes -1, EXTENT_DIRTY, 0)) {
1571                 search_start = ins->objectid + num_bytes;
1572                 goto new_group;
1573         }
1574
1575         if (exclude_nr > 0 && (ins->objectid + num_bytes > exclude_start &&
1576             ins->objectid < exclude_start + exclude_nr)) {
1577                 search_start = exclude_start + exclude_nr;
1578                 goto new_group;
1579         }
1580
1581         if (!(data & BTRFS_BLOCK_GROUP_DATA)) {
1582                 block_group = btrfs_lookup_block_group(info, ins->objectid);
1583                 if (block_group)
1584                         trans->block_group = block_group;
1585         }
1586         ins->offset = num_bytes;
1587         return 0;
1588
1589 new_group:
1590         if (search_start + num_bytes >= search_end) {
1591 enospc:
1592                 search_start = orig_search_start;
1593                 if (full_scan) {
1594                         ret = -ENOSPC;
1595                         goto error;
1596                 }
1597                 if (wrapped) {
1598                         if (!full_scan)
1599                                 total_needed -= empty_size;
1600                         full_scan = 1;
1601                 } else
1602                         wrapped = 1;
1603         }
1604         block_group = btrfs_lookup_block_group(info, search_start);
1605         cond_resched();
1606         block_group = btrfs_find_block_group(root, block_group,
1607                                              search_start, data, 0);
1608         goto check_failed;
1609
1610 error:
1611         return ret;
1612 }
1613 /*
1614  * finds a free extent and does all the dirty work required for allocation
1615  * returns the key for the extent through ins, and a tree buffer for
1616  * the first block of the extent through buf.
1617  *
1618  * returns 0 if everything worked, non-zero otherwise.
1619  */
1620 int btrfs_alloc_extent(struct btrfs_trans_handle *trans,
1621                        struct btrfs_root *root,
1622                        u64 num_bytes, u64 root_objectid, u64 ref_generation,
1623                        u64 owner, u64 owner_offset,
1624                        u64 empty_size, u64 hint_byte,
1625                        u64 search_end, struct btrfs_key *ins, int data)
1626 {
1627         int ret;
1628         int pending_ret;
1629         u64 super_used, root_used;
1630         u64 search_start = 0;
1631         u64 alloc_profile;
1632         struct btrfs_fs_info *info = root->fs_info;
1633         struct btrfs_extent_ops *ops = info->extent_ops;
1634         u32 sizes[2];
1635         struct btrfs_root *extent_root = info->extent_root;
1636         struct btrfs_path *path;
1637         struct btrfs_extent_item *extent_item;
1638         struct btrfs_extent_ref *ref;
1639         struct btrfs_key keys[2];
1640
1641         if (data) {
1642                 alloc_profile = info->avail_data_alloc_bits &
1643                                 info->data_alloc_profile;
1644                 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
1645         } else if (root == info->chunk_root || info->force_system_allocs) {
1646                 alloc_profile = info->avail_system_alloc_bits &
1647                                 info->system_alloc_profile;
1648                 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
1649         } else {
1650                 alloc_profile = info->avail_metadata_alloc_bits &
1651                                 info->metadata_alloc_profile;
1652                 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
1653         }
1654
1655         if (root->ref_cows) {
1656                 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
1657                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1658                                              num_bytes,
1659                                              BTRFS_BLOCK_GROUP_METADATA);
1660                         BUG_ON(ret);
1661                 }
1662                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1663                                      num_bytes + 2 * 1024 * 1024, data);
1664                 BUG_ON(ret);
1665         }
1666
1667         WARN_ON(num_bytes < root->sectorsize);
1668         if (ops && ops->alloc_extent) {
1669                 ret = ops->alloc_extent(root, num_bytes, hint_byte, ins);
1670         } else {
1671                 ret = find_free_extent(trans, root, num_bytes, empty_size,
1672                                         search_start, search_end, hint_byte,
1673                                         ins, trans->alloc_exclude_start,
1674                                         trans->alloc_exclude_nr, data);
1675         }
1676         BUG_ON(ret);
1677         if (ret)
1678                 return ret;
1679
1680         /* block accounting for super block */
1681         super_used = btrfs_super_bytes_used(&info->super_copy);
1682         btrfs_set_super_bytes_used(&info->super_copy, super_used + num_bytes);
1683
1684         /* block accounting for root item */
1685         root_used = btrfs_root_used(&root->root_item);
1686         btrfs_set_root_used(&root->root_item, root_used + num_bytes);
1687
1688         clear_extent_dirty(&root->fs_info->free_space_cache,
1689                            ins->objectid, ins->objectid + ins->offset - 1,
1690                            GFP_NOFS);
1691
1692         if (root == extent_root) {
1693                 set_extent_bits(&root->fs_info->extent_ins, ins->objectid,
1694                                 ins->objectid + ins->offset - 1,
1695                                 EXTENT_LOCKED, GFP_NOFS);
1696                 goto update_block;
1697         }
1698
1699         WARN_ON(trans->alloc_exclude_nr);
1700         trans->alloc_exclude_start = ins->objectid;
1701         trans->alloc_exclude_nr = ins->offset;
1702
1703         memcpy(&keys[0], ins, sizeof(*ins));
1704         keys[1].offset = hash_extent_ref(root_objectid, ref_generation,
1705                                          owner, owner_offset);
1706         keys[1].objectid = ins->objectid;
1707         keys[1].type = BTRFS_EXTENT_REF_KEY;
1708         sizes[0] = sizeof(*extent_item);
1709         sizes[1] = sizeof(*ref);
1710
1711         path = btrfs_alloc_path();
1712         BUG_ON(!path);
1713
1714         ret = btrfs_insert_empty_items(trans, extent_root, path, keys,
1715                                        sizes, 2);
1716
1717         BUG_ON(ret);
1718         extent_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1719                                      struct btrfs_extent_item);
1720         btrfs_set_extent_refs(path->nodes[0], extent_item, 1);
1721         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
1722                              struct btrfs_extent_ref);
1723
1724         btrfs_set_ref_root(path->nodes[0], ref, root_objectid);
1725         btrfs_set_ref_generation(path->nodes[0], ref, ref_generation);
1726         btrfs_set_ref_objectid(path->nodes[0], ref, owner);
1727         btrfs_set_ref_offset(path->nodes[0], ref, owner_offset);
1728
1729         btrfs_mark_buffer_dirty(path->nodes[0]);
1730
1731         trans->alloc_exclude_start = 0;
1732         trans->alloc_exclude_nr = 0;
1733         btrfs_free_path(path);
1734         finish_current_insert(trans, extent_root);
1735         pending_ret = del_pending_extents(trans, extent_root);
1736
1737         if (ret) {
1738                 return ret;
1739         }
1740         if (pending_ret) {
1741                 return pending_ret;
1742         }
1743
1744 update_block:
1745         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1, 0);
1746         if (ret) {
1747                 printk("update block group failed for %llu %llu\n",
1748                        (unsigned long long)ins->objectid,
1749                        (unsigned long long)ins->offset);
1750                 BUG();
1751         }
1752         return 0;
1753 }
1754
1755 /*
1756  * helper function to allocate a block for a given tree
1757  * returns the tree buffer or NULL.
1758  */
1759 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1760                                              struct btrfs_root *root,
1761                                              u32 blocksize,
1762                                              u64 root_objectid, u64 hint,
1763                                              u64 empty_size)
1764 {
1765         u64 ref_generation;
1766
1767         if (root->ref_cows)
1768                 ref_generation = trans->transid;
1769         else
1770                 ref_generation = 0;
1771
1772
1773         return __btrfs_alloc_free_block(trans, root, blocksize, root_objectid,
1774                                         ref_generation, 0, 0, hint, empty_size);
1775 }
1776
1777 /*
1778  * helper function to allocate a block for a given tree
1779  * returns the tree buffer or NULL.
1780  */
1781 struct extent_buffer *__btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
1782                                              struct btrfs_root *root,
1783                                              u32 blocksize,
1784                                              u64 root_objectid,
1785                                              u64 ref_generation,
1786                                              u64 first_objectid,
1787                                              int level,
1788                                              u64 hint,
1789                                              u64 empty_size)
1790 {
1791         struct btrfs_key ins;
1792         int ret;
1793         struct extent_buffer *buf;
1794
1795         ret = btrfs_alloc_extent(trans, root, blocksize,
1796                                  root_objectid, ref_generation,
1797                                  level, first_objectid, empty_size, hint,
1798                                  (u64)-1, &ins, 0);
1799         if (ret) {
1800                 BUG_ON(ret > 0);
1801                 return ERR_PTR(ret);
1802         }
1803         buf = btrfs_find_create_tree_block(root, ins.objectid, blocksize);
1804         if (!buf) {
1805                 btrfs_free_extent(trans, root, ins.objectid, blocksize,
1806                                   root->root_key.objectid, ref_generation,
1807                                   0, 0, 0);
1808                 BUG_ON(1);
1809                 return ERR_PTR(-ENOMEM);
1810         }
1811         btrfs_set_buffer_uptodate(buf);
1812         trans->blocks_used++;
1813         return buf;
1814 }
1815
1816 static int noinline drop_leaf_ref(struct btrfs_trans_handle *trans,
1817                                   struct btrfs_root *root,
1818                                   struct extent_buffer *leaf)
1819 {
1820         u64 leaf_owner;
1821         u64 leaf_generation;
1822         struct btrfs_key key;
1823         struct btrfs_file_extent_item *fi;
1824         int i;
1825         int nritems;
1826         int ret;
1827
1828         BUG_ON(!btrfs_is_leaf(leaf));
1829         nritems = btrfs_header_nritems(leaf);
1830         leaf_owner = btrfs_header_owner(leaf);
1831         leaf_generation = btrfs_header_generation(leaf);
1832
1833         for (i = 0; i < nritems; i++) {
1834                 u64 disk_bytenr;
1835
1836                 btrfs_item_key_to_cpu(leaf, &key, i);
1837                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1838                         continue;
1839                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
1840                 if (btrfs_file_extent_type(leaf, fi) ==
1841                     BTRFS_FILE_EXTENT_INLINE)
1842                         continue;
1843                 /*
1844                  * FIXME make sure to insert a trans record that
1845                  * repeats the snapshot del on crash
1846                  */
1847                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1848                 if (disk_bytenr == 0)
1849                         continue;
1850                 ret = btrfs_free_extent(trans, root, disk_bytenr,
1851                                 btrfs_file_extent_disk_num_bytes(leaf, fi),
1852                                 leaf_owner, leaf_generation,
1853                                 key.objectid, key.offset, 0);
1854                 BUG_ON(ret);
1855         }
1856         return 0;
1857 }
1858
1859 static void noinline reada_walk_down(struct btrfs_root *root,
1860                                      struct extent_buffer *node,
1861                                      int slot)
1862 {
1863         u64 bytenr;
1864         u64 last = 0;
1865         u32 nritems;
1866         u32 refs;
1867         u32 blocksize;
1868         int ret;
1869         int i;
1870         int level;
1871         int skipped = 0;
1872
1873         nritems = btrfs_header_nritems(node);
1874         level = btrfs_header_level(node);
1875         if (level)
1876                 return;
1877
1878         for (i = slot; i < nritems && skipped < 32; i++) {
1879                 bytenr = btrfs_node_blockptr(node, i);
1880                 if (last && ((bytenr > last && bytenr - last > 32 * 1024) ||
1881                              (last > bytenr && last - bytenr > 32 * 1024))) {
1882                         skipped++;
1883                         continue;
1884                 }
1885                 blocksize = btrfs_level_size(root, level - 1);
1886                 if (i != slot) {
1887                         ret = lookup_extent_ref(NULL, root, bytenr,
1888                                                 blocksize, &refs);
1889                         BUG_ON(ret);
1890                         if (refs != 1) {
1891                                 skipped++;
1892                                 continue;
1893                         }
1894                 }
1895                 mutex_unlock(&root->fs_info->fs_mutex);
1896                 ret = readahead_tree_block(root, bytenr, blocksize);
1897                 last = bytenr + blocksize;
1898                 cond_resched();
1899                 mutex_lock(&root->fs_info->fs_mutex);
1900                 if (ret)
1901                         break;
1902         }
1903 }
1904
1905 /*
1906  * helper function for drop_snapshot, this walks down the tree dropping ref
1907  * counts as it goes.
1908  */
1909 static int noinline walk_down_tree(struct btrfs_trans_handle *trans,
1910                                    struct btrfs_root *root,
1911                                    struct btrfs_path *path, int *level)
1912 {
1913         u64 root_owner;
1914         u64 root_gen;
1915         u64 bytenr;
1916         struct extent_buffer *next;
1917         struct extent_buffer *cur;
1918         struct extent_buffer *parent;
1919         u32 blocksize;
1920         int ret;
1921         u32 refs;
1922
1923         WARN_ON(*level < 0);
1924         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1925         ret = lookup_extent_ref(trans, root,
1926                                 path->nodes[*level]->start,
1927                                 path->nodes[*level]->len, &refs);
1928         BUG_ON(ret);
1929         if (refs > 1)
1930                 goto out;
1931
1932         /*
1933          * walk down to the last node level and free all the leaves
1934          */
1935         while(*level >= 0) {
1936                 WARN_ON(*level < 0);
1937                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1938                 cur = path->nodes[*level];
1939
1940                 if (btrfs_header_level(cur) != *level)
1941                         WARN_ON(1);
1942
1943                 if (path->slots[*level] >=
1944                     btrfs_header_nritems(cur))
1945                         break;
1946                 if (*level == 0) {
1947                         ret = drop_leaf_ref(trans, root, cur);
1948                         BUG_ON(ret);
1949                         break;
1950                 }
1951                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1952                 blocksize = btrfs_level_size(root, *level - 1);
1953                 ret = lookup_extent_ref(trans, root, bytenr, blocksize, &refs);
1954                 BUG_ON(ret);
1955                 if (refs != 1) {
1956                         parent = path->nodes[*level];
1957                         root_owner = btrfs_header_owner(parent);
1958                         root_gen = btrfs_header_generation(parent);
1959                         path->slots[*level]++;
1960                         ret = btrfs_free_extent(trans, root, bytenr,
1961                                                 blocksize, root_owner,
1962                                                 root_gen, 0, 0, 1);
1963                         BUG_ON(ret);
1964                         continue;
1965                 }
1966                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1967                 if (!next || !btrfs_buffer_uptodate(next)) {
1968                         free_extent_buffer(next);
1969                         reada_walk_down(root, cur, path->slots[*level]);
1970                         mutex_unlock(&root->fs_info->fs_mutex);
1971                         next = read_tree_block(root, bytenr, blocksize);
1972                         mutex_lock(&root->fs_info->fs_mutex);
1973
1974                         /* we dropped the lock, check one more time */
1975                         ret = lookup_extent_ref(trans, root, bytenr,
1976                                                 blocksize, &refs);
1977                         BUG_ON(ret);
1978                         if (refs != 1) {
1979                                 parent = path->nodes[*level];
1980                                 root_owner = btrfs_header_owner(parent);
1981                                 root_gen = btrfs_header_generation(parent);
1982
1983                                 path->slots[*level]++;
1984                                 free_extent_buffer(next);
1985                                 ret = btrfs_free_extent(trans, root, bytenr,
1986                                                         blocksize,
1987                                                         root_owner,
1988                                                         root_gen, 0, 0, 1);
1989                                 BUG_ON(ret);
1990                                 continue;
1991                         }
1992                 }
1993                 WARN_ON(*level <= 0);
1994                 if (path->nodes[*level-1])
1995                         free_extent_buffer(path->nodes[*level-1]);
1996                 path->nodes[*level-1] = next;
1997                 *level = btrfs_header_level(next);
1998                 path->slots[*level] = 0;
1999         }
2000 out:
2001         WARN_ON(*level < 0);
2002         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2003
2004         if (path->nodes[*level] == root->node) {
2005                 root_owner = root->root_key.objectid;
2006                 parent = path->nodes[*level];
2007         } else {
2008                 parent = path->nodes[*level + 1];
2009                 root_owner = btrfs_header_owner(parent);
2010         }
2011
2012         root_gen = btrfs_header_generation(parent);
2013         ret = btrfs_free_extent(trans, root, path->nodes[*level]->start,
2014                                 path->nodes[*level]->len,
2015                                 root_owner, root_gen, 0, 0, 1);
2016         free_extent_buffer(path->nodes[*level]);
2017         path->nodes[*level] = NULL;
2018         *level += 1;
2019         BUG_ON(ret);
2020         return 0;
2021 }
2022
2023 /*
2024  * helper for dropping snapshots.  This walks back up the tree in the path
2025  * to find the first node higher up where we haven't yet gone through
2026  * all the slots
2027  */
2028 static int noinline walk_up_tree(struct btrfs_trans_handle *trans,
2029                                  struct btrfs_root *root,
2030                                  struct btrfs_path *path, int *level)
2031 {
2032         u64 root_owner;
2033         u64 root_gen;
2034         struct btrfs_root_item *root_item = &root->root_item;
2035         int i;
2036         int slot;
2037         int ret;
2038
2039         for(i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2040                 slot = path->slots[i];
2041                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
2042                         struct extent_buffer *node;
2043                         struct btrfs_disk_key disk_key;
2044                         node = path->nodes[i];
2045                         path->slots[i]++;
2046                         *level = i;
2047                         WARN_ON(*level == 0);
2048                         btrfs_node_key(node, &disk_key, path->slots[i]);
2049                         memcpy(&root_item->drop_progress,
2050                                &disk_key, sizeof(disk_key));
2051                         root_item->drop_level = i;
2052                         return 0;
2053                 } else {
2054                         if (path->nodes[*level] == root->node) {
2055                                 root_owner = root->root_key.objectid;
2056                                 root_gen =
2057                                    btrfs_header_generation(path->nodes[*level]);
2058                         } else {
2059                                 struct extent_buffer *node;
2060                                 node = path->nodes[*level + 1];
2061                                 root_owner = btrfs_header_owner(node);
2062                                 root_gen = btrfs_header_generation(node);
2063                         }
2064                         ret = btrfs_free_extent(trans, root,
2065                                                 path->nodes[*level]->start,
2066                                                 path->nodes[*level]->len,
2067                                                 root_owner, root_gen, 0, 0, 1);
2068                         BUG_ON(ret);
2069                         free_extent_buffer(path->nodes[*level]);
2070                         path->nodes[*level] = NULL;
2071                         *level = i + 1;
2072                 }
2073         }
2074         return 1;
2075 }
2076
2077 /*
2078  * drop the reference count on the tree rooted at 'snap'.  This traverses
2079  * the tree freeing any blocks that have a ref count of zero after being
2080  * decremented.
2081  */
2082 int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
2083                         *root)
2084 {
2085         int ret = 0;
2086         int wret;
2087         int level;
2088         struct btrfs_path *path;
2089         int i;
2090         int orig_level;
2091         struct btrfs_root_item *root_item = &root->root_item;
2092
2093         path = btrfs_alloc_path();
2094         BUG_ON(!path);
2095
2096         level = btrfs_header_level(root->node);
2097         orig_level = level;
2098         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2099                 path->nodes[level] = root->node;
2100                 extent_buffer_get(root->node);
2101                 path->slots[level] = 0;
2102         } else {
2103                 struct btrfs_key key;
2104                 struct btrfs_disk_key found_key;
2105                 struct extent_buffer *node;
2106
2107                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2108                 level = root_item->drop_level;
2109                 path->lowest_level = level;
2110                 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2111                 if (wret < 0) {
2112                         ret = wret;
2113                         goto out;
2114                 }
2115                 node = path->nodes[level];
2116                 btrfs_node_key(node, &found_key, path->slots[level]);
2117                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
2118                                sizeof(found_key)));
2119         }
2120         while(1) {
2121                 wret = walk_down_tree(trans, root, path, &level);
2122                 if (wret < 0)
2123                         ret = wret;
2124                 if (wret != 0)
2125                         break;
2126
2127                 wret = walk_up_tree(trans, root, path, &level);
2128                 if (wret < 0)
2129                         ret = wret;
2130                 if (wret != 0)
2131                         break;
2132                 /*
2133                 ret = -EAGAIN;
2134                 break;
2135                 */
2136         }
2137         for (i = 0; i <= orig_level; i++) {
2138                 if (path->nodes[i]) {
2139                         free_extent_buffer(path->nodes[i]);
2140                         path->nodes[i] = NULL;
2141                 }
2142         }
2143 out:
2144         btrfs_free_path(path);
2145         return ret;
2146 }
2147
2148 int btrfs_free_block_groups(struct btrfs_fs_info *info)
2149 {
2150         u64 start;
2151         u64 end;
2152         u64 ptr;
2153         int ret;
2154         while(1) {
2155                 ret = find_first_extent_bit(&info->block_group_cache, 0,
2156                                             &start, &end, (unsigned int)-1);
2157                 if (ret)
2158                         break;
2159                 ret = get_state_private(&info->block_group_cache, start, &ptr);
2160                 if (!ret)
2161                         kfree((void *)(unsigned long)ptr);
2162                 clear_extent_bits(&info->block_group_cache, start,
2163                                   end, (unsigned int)-1, GFP_NOFS);
2164         }
2165         while(1) {
2166                 ret = find_first_extent_bit(&info->free_space_cache, 0,
2167                                             &start, &end, EXTENT_DIRTY);
2168                 if (ret)
2169                         break;
2170                 clear_extent_dirty(&info->free_space_cache, start,
2171                                    end, GFP_NOFS);
2172         }
2173         return 0;
2174 }
2175
2176 int find_first_block_group(struct btrfs_root *root, struct btrfs_path *path,
2177                            struct btrfs_key *key)
2178 {
2179         int ret;
2180         struct btrfs_key found_key;
2181         struct extent_buffer *leaf;
2182         int slot;
2183
2184         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2185         if (ret < 0)
2186                 return ret;
2187         while(1) {
2188                 slot = path->slots[0];
2189                 leaf = path->nodes[0];
2190                 if (slot >= btrfs_header_nritems(leaf)) {
2191                         ret = btrfs_next_leaf(root, path);
2192                         if (ret == 0)
2193                                 continue;
2194                         if (ret < 0)
2195                                 goto error;
2196                         break;
2197                 }
2198                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2199
2200                 if (found_key.objectid >= key->objectid &&
2201                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY)
2202                         return 0;
2203                 path->slots[0]++;
2204         }
2205         ret = -ENOENT;
2206 error:
2207         return ret;
2208 }
2209
2210 int btrfs_read_block_groups(struct btrfs_root *root)
2211 {
2212         struct btrfs_path *path;
2213         int ret;
2214         int bit;
2215         struct btrfs_block_group_cache *cache;
2216         struct btrfs_fs_info *info = root->fs_info;
2217         struct btrfs_space_info *space_info;
2218         struct extent_io_tree *block_group_cache;
2219         struct btrfs_key key;
2220         struct btrfs_key found_key;
2221         struct extent_buffer *leaf;
2222
2223         block_group_cache = &info->block_group_cache;
2224
2225         root = info->extent_root;
2226         key.objectid = 0;
2227         key.offset = 0;
2228         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
2229         path = btrfs_alloc_path();
2230         if (!path)
2231                 return -ENOMEM;
2232
2233         while(1) {
2234                 ret = find_first_block_group(root, path, &key);
2235                 if (ret > 0) {
2236                         ret = 0;
2237                         goto error;
2238                 }
2239                 if (ret != 0) {
2240                         goto error;
2241                 }
2242                 leaf = path->nodes[0];
2243                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2244                 cache = kmalloc(sizeof(*cache), GFP_NOFS);
2245                 if (!cache) {
2246                         ret = -ENOMEM;
2247                         break;
2248                 }
2249
2250                 read_extent_buffer(leaf, &cache->item,
2251                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
2252                                    sizeof(cache->item));
2253                 memcpy(&cache->key, &found_key, sizeof(found_key));
2254                 cache->cached = 0;
2255                 cache->pinned = 0;
2256                 key.objectid = found_key.objectid + found_key.offset;
2257                 btrfs_release_path(root, path);
2258                 cache->flags = btrfs_block_group_flags(&cache->item);
2259                 bit = 0;
2260                 if (cache->flags & BTRFS_BLOCK_GROUP_DATA) {
2261                         bit = BLOCK_GROUP_DATA;
2262                 } else if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2263                         bit = BLOCK_GROUP_SYSTEM;
2264                 } else if (cache->flags & BTRFS_BLOCK_GROUP_METADATA) {
2265                         bit = BLOCK_GROUP_METADATA;
2266                 }
2267                 set_avail_alloc_bits(info, cache->flags);
2268
2269                 ret = update_space_info(info, cache->flags, found_key.offset,
2270                                         btrfs_block_group_used(&cache->item),
2271                                         &space_info);
2272                 BUG_ON(ret);
2273                 cache->space_info = space_info;
2274
2275                 /* use EXTENT_LOCKED to prevent merging */
2276                 set_extent_bits(block_group_cache, found_key.objectid,
2277                                 found_key.objectid + found_key.offset - 1,
2278                                 bit | EXTENT_LOCKED, GFP_NOFS);
2279                 set_state_private(block_group_cache, found_key.objectid,
2280                                   (unsigned long)cache);
2281
2282                 if (key.objectid >=
2283                     btrfs_super_total_bytes(&info->super_copy))
2284                         break;
2285         }
2286         ret = 0;
2287 error:
2288         btrfs_free_path(path);
2289         return ret;
2290 }
2291
2292 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
2293                            struct btrfs_root *root, u64 bytes_used,
2294                            u64 type, u64 chunk_tree, u64 chunk_objectid,
2295                            u64 size)
2296 {
2297         int ret;
2298         int bit = 0;
2299         struct btrfs_root *extent_root;
2300         struct btrfs_block_group_cache *cache;
2301         struct extent_io_tree *block_group_cache;
2302
2303         extent_root = root->fs_info->extent_root;
2304         block_group_cache = &root->fs_info->block_group_cache;
2305
2306         cache = kzalloc(sizeof(*cache), GFP_NOFS);
2307         BUG_ON(!cache);
2308         cache->key.objectid = chunk_objectid;
2309         cache->key.offset = size;
2310         btrfs_set_key_type(&cache->key, BTRFS_BLOCK_GROUP_ITEM_KEY);
2311         btrfs_set_block_group_used(&cache->item, bytes_used);
2312         btrfs_set_block_group_chunk_tree(&cache->item, chunk_tree);
2313         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
2314         cache->flags = type;
2315         btrfs_set_block_group_flags(&cache->item, type);
2316
2317         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
2318                                 &cache->space_info);
2319         BUG_ON(ret);
2320
2321         bit = block_group_state_bits(type);
2322         set_extent_bits(block_group_cache, chunk_objectid,
2323                         chunk_objectid + size - 1,
2324                         bit | EXTENT_LOCKED, GFP_NOFS);
2325         set_state_private(block_group_cache, chunk_objectid,
2326                           (unsigned long)cache);
2327
2328         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
2329                                 sizeof(cache->item));
2330         BUG_ON(ret);
2331
2332         finish_current_insert(trans, extent_root);
2333         ret = del_pending_extents(trans, extent_root);
2334         BUG_ON(ret);
2335         set_avail_alloc_bits(extent_root->fs_info, type);
2336         return 0;
2337 }
2338
2339 u64 btrfs_hash_extent_ref(u64 root_objectid, u64 ref_generation,
2340                           u64 owner, u64 owner_offset)
2341 {
2342         return hash_extent_ref(root_objectid, ref_generation,
2343                                owner, owner_offset);
2344 }
2345
2346 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2347                              struct btrfs_root *root,
2348                              u64 bytenr, u64 num_bytes, int alloc,
2349                              int mark_free)
2350 {
2351         return update_block_group(trans, root, bytenr, num_bytes,
2352                                   alloc, mark_free);
2353 }