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