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