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