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