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