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