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