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