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