]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - fs/btrfs/extent-tree.c
Btrfs: try to cleanup delayed refs while freeing extents
[linux-2.6-omap-h63xx.git] / fs / btrfs / 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 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include <linux/rcupdate.h>
24 #include "compat.h"
25 #include "hash.h"
26 #include "crc32c.h"
27 #include "ctree.h"
28 #include "disk-io.h"
29 #include "print-tree.h"
30 #include "transaction.h"
31 #include "volumes.h"
32 #include "locking.h"
33 #include "ref-cache.h"
34
35 #define PENDING_EXTENT_INSERT 0
36 #define PENDING_EXTENT_DELETE 1
37 #define PENDING_BACKREF_UPDATE 2
38
39 struct pending_extent_op {
40         int type;
41         u64 bytenr;
42         u64 num_bytes;
43         u64 parent;
44         u64 orig_parent;
45         u64 generation;
46         u64 orig_generation;
47         int level;
48         struct list_head list;
49         int del;
50 };
51
52 static int __btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
53                                          struct btrfs_root *root, u64 parent,
54                                          u64 root_objectid, u64 ref_generation,
55                                          u64 owner, struct btrfs_key *ins,
56                                          int ref_mod);
57 static int update_reserved_extents(struct btrfs_root *root,
58                                    u64 bytenr, u64 num, int reserve);
59 static int pin_down_bytes(struct btrfs_trans_handle *trans,
60                           struct btrfs_root *root,
61                           u64 bytenr, u64 num_bytes, int is_data);
62 static int update_block_group(struct btrfs_trans_handle *trans,
63                               struct btrfs_root *root,
64                               u64 bytenr, u64 num_bytes, int alloc,
65                               int mark_free);
66 static noinline int __btrfs_free_extent(struct btrfs_trans_handle *trans,
67                                         struct btrfs_root *root,
68                                         u64 bytenr, u64 num_bytes, u64 parent,
69                                         u64 root_objectid, u64 ref_generation,
70                                         u64 owner_objectid, int pin,
71                                         int ref_to_drop);
72
73 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
74                           struct btrfs_root *extent_root, u64 alloc_bytes,
75                           u64 flags, int force);
76
77 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
78 {
79         return (cache->flags & bits) == bits;
80 }
81
82 /*
83  * this adds the block group to the fs_info rb tree for the block group
84  * cache
85  */
86 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
87                                 struct btrfs_block_group_cache *block_group)
88 {
89         struct rb_node **p;
90         struct rb_node *parent = NULL;
91         struct btrfs_block_group_cache *cache;
92
93         spin_lock(&info->block_group_cache_lock);
94         p = &info->block_group_cache_tree.rb_node;
95
96         while (*p) {
97                 parent = *p;
98                 cache = rb_entry(parent, struct btrfs_block_group_cache,
99                                  cache_node);
100                 if (block_group->key.objectid < cache->key.objectid) {
101                         p = &(*p)->rb_left;
102                 } else if (block_group->key.objectid > cache->key.objectid) {
103                         p = &(*p)->rb_right;
104                 } else {
105                         spin_unlock(&info->block_group_cache_lock);
106                         return -EEXIST;
107                 }
108         }
109
110         rb_link_node(&block_group->cache_node, parent, p);
111         rb_insert_color(&block_group->cache_node,
112                         &info->block_group_cache_tree);
113         spin_unlock(&info->block_group_cache_lock);
114
115         return 0;
116 }
117
118 /*
119  * This will return the block group at or after bytenr if contains is 0, else
120  * it will return the block group that contains the bytenr
121  */
122 static struct btrfs_block_group_cache *
123 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
124                               int contains)
125 {
126         struct btrfs_block_group_cache *cache, *ret = NULL;
127         struct rb_node *n;
128         u64 end, start;
129
130         spin_lock(&info->block_group_cache_lock);
131         n = info->block_group_cache_tree.rb_node;
132
133         while (n) {
134                 cache = rb_entry(n, struct btrfs_block_group_cache,
135                                  cache_node);
136                 end = cache->key.objectid + cache->key.offset - 1;
137                 start = cache->key.objectid;
138
139                 if (bytenr < start) {
140                         if (!contains && (!ret || start < ret->key.objectid))
141                                 ret = cache;
142                         n = n->rb_left;
143                 } else if (bytenr > start) {
144                         if (contains && bytenr <= end) {
145                                 ret = cache;
146                                 break;
147                         }
148                         n = n->rb_right;
149                 } else {
150                         ret = cache;
151                         break;
152                 }
153         }
154         if (ret)
155                 atomic_inc(&ret->count);
156         spin_unlock(&info->block_group_cache_lock);
157
158         return ret;
159 }
160
161 /*
162  * this is only called by cache_block_group, since we could have freed extents
163  * we need to check the pinned_extents for any extents that can't be used yet
164  * since their free space will be released as soon as the transaction commits.
165  */
166 static int add_new_free_space(struct btrfs_block_group_cache *block_group,
167                               struct btrfs_fs_info *info, u64 start, u64 end)
168 {
169         u64 extent_start, extent_end, size;
170         int ret;
171
172         mutex_lock(&info->pinned_mutex);
173         while (start < end) {
174                 ret = find_first_extent_bit(&info->pinned_extents, start,
175                                             &extent_start, &extent_end,
176                                             EXTENT_DIRTY);
177                 if (ret)
178                         break;
179
180                 if (extent_start == start) {
181                         start = extent_end + 1;
182                 } else if (extent_start > start && extent_start < end) {
183                         size = extent_start - start;
184                         ret = btrfs_add_free_space(block_group, start,
185                                                    size);
186                         BUG_ON(ret);
187                         start = extent_end + 1;
188                 } else {
189                         break;
190                 }
191         }
192
193         if (start < end) {
194                 size = end - start;
195                 ret = btrfs_add_free_space(block_group, start, size);
196                 BUG_ON(ret);
197         }
198         mutex_unlock(&info->pinned_mutex);
199
200         return 0;
201 }
202
203 static int remove_sb_from_cache(struct btrfs_root *root,
204                                 struct btrfs_block_group_cache *cache)
205 {
206         u64 bytenr;
207         u64 *logical;
208         int stripe_len;
209         int i, nr, ret;
210
211         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
212                 bytenr = btrfs_sb_offset(i);
213                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
214                                        cache->key.objectid, bytenr, 0,
215                                        &logical, &nr, &stripe_len);
216                 BUG_ON(ret);
217                 while (nr--) {
218                         btrfs_remove_free_space(cache, logical[nr],
219                                                 stripe_len);
220                 }
221                 kfree(logical);
222         }
223         return 0;
224 }
225
226 static int cache_block_group(struct btrfs_root *root,
227                              struct btrfs_block_group_cache *block_group)
228 {
229         struct btrfs_path *path;
230         int ret = 0;
231         struct btrfs_key key;
232         struct extent_buffer *leaf;
233         int slot;
234         u64 last;
235
236         if (!block_group)
237                 return 0;
238
239         root = root->fs_info->extent_root;
240
241         if (block_group->cached)
242                 return 0;
243
244         path = btrfs_alloc_path();
245         if (!path)
246                 return -ENOMEM;
247
248         path->reada = 2;
249         /*
250          * we get into deadlocks with paths held by callers of this function.
251          * since the alloc_mutex is protecting things right now, just
252          * skip the locking here
253          */
254         path->skip_locking = 1;
255         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
256         key.objectid = last;
257         key.offset = 0;
258         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
259         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
260         if (ret < 0)
261                 goto err;
262
263         while (1) {
264                 leaf = path->nodes[0];
265                 slot = path->slots[0];
266                 if (slot >= btrfs_header_nritems(leaf)) {
267                         ret = btrfs_next_leaf(root, path);
268                         if (ret < 0)
269                                 goto err;
270                         if (ret == 0)
271                                 continue;
272                         else
273                                 break;
274                 }
275                 btrfs_item_key_to_cpu(leaf, &key, slot);
276                 if (key.objectid < block_group->key.objectid)
277                         goto next;
278
279                 if (key.objectid >= block_group->key.objectid +
280                     block_group->key.offset)
281                         break;
282
283                 if (btrfs_key_type(&key) == BTRFS_EXTENT_ITEM_KEY) {
284                         add_new_free_space(block_group, root->fs_info, last,
285                                            key.objectid);
286
287                         last = key.objectid + key.offset;
288                 }
289 next:
290                 path->slots[0]++;
291         }
292
293         add_new_free_space(block_group, root->fs_info, last,
294                            block_group->key.objectid +
295                            block_group->key.offset);
296
297         remove_sb_from_cache(root, block_group);
298         block_group->cached = 1;
299         ret = 0;
300 err:
301         btrfs_free_path(path);
302         return ret;
303 }
304
305 /*
306  * return the block group that starts at or after bytenr
307  */
308 static struct btrfs_block_group_cache *
309 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
310 {
311         struct btrfs_block_group_cache *cache;
312
313         cache = block_group_cache_tree_search(info, bytenr, 0);
314
315         return cache;
316 }
317
318 /*
319  * return the block group that contains teh given bytenr
320  */
321 struct btrfs_block_group_cache *btrfs_lookup_block_group(
322                                                  struct btrfs_fs_info *info,
323                                                  u64 bytenr)
324 {
325         struct btrfs_block_group_cache *cache;
326
327         cache = block_group_cache_tree_search(info, bytenr, 1);
328
329         return cache;
330 }
331
332 static inline void put_block_group(struct btrfs_block_group_cache *cache)
333 {
334         if (atomic_dec_and_test(&cache->count))
335                 kfree(cache);
336 }
337
338 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
339                                                   u64 flags)
340 {
341         struct list_head *head = &info->space_info;
342         struct btrfs_space_info *found;
343
344         rcu_read_lock();
345         list_for_each_entry_rcu(found, head, list) {
346                 if (found->flags == flags) {
347                         rcu_read_unlock();
348                         return found;
349                 }
350         }
351         rcu_read_unlock();
352         return NULL;
353 }
354
355 /*
356  * after adding space to the filesystem, we need to clear the full flags
357  * on all the space infos.
358  */
359 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
360 {
361         struct list_head *head = &info->space_info;
362         struct btrfs_space_info *found;
363
364         rcu_read_lock();
365         list_for_each_entry_rcu(found, head, list)
366                 found->full = 0;
367         rcu_read_unlock();
368 }
369
370 static u64 div_factor(u64 num, int factor)
371 {
372         if (factor == 10)
373                 return num;
374         num *= factor;
375         do_div(num, 10);
376         return num;
377 }
378
379 u64 btrfs_find_block_group(struct btrfs_root *root,
380                            u64 search_start, u64 search_hint, int owner)
381 {
382         struct btrfs_block_group_cache *cache;
383         u64 used;
384         u64 last = max(search_hint, search_start);
385         u64 group_start = 0;
386         int full_search = 0;
387         int factor = 9;
388         int wrapped = 0;
389 again:
390         while (1) {
391                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
392                 if (!cache)
393                         break;
394
395                 spin_lock(&cache->lock);
396                 last = cache->key.objectid + cache->key.offset;
397                 used = btrfs_block_group_used(&cache->item);
398
399                 if ((full_search || !cache->ro) &&
400                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
401                         if (used + cache->pinned + cache->reserved <
402                             div_factor(cache->key.offset, factor)) {
403                                 group_start = cache->key.objectid;
404                                 spin_unlock(&cache->lock);
405                                 put_block_group(cache);
406                                 goto found;
407                         }
408                 }
409                 spin_unlock(&cache->lock);
410                 put_block_group(cache);
411                 cond_resched();
412         }
413         if (!wrapped) {
414                 last = search_start;
415                 wrapped = 1;
416                 goto again;
417         }
418         if (!full_search && factor < 10) {
419                 last = search_start;
420                 full_search = 1;
421                 factor = 10;
422                 goto again;
423         }
424 found:
425         return group_start;
426 }
427
428 /* simple helper to search for an existing extent at a given offset */
429 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
430 {
431         int ret;
432         struct btrfs_key key;
433         struct btrfs_path *path;
434
435         path = btrfs_alloc_path();
436         BUG_ON(!path);
437         key.objectid = start;
438         key.offset = len;
439         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
440         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
441                                 0, 0);
442         btrfs_free_path(path);
443         return ret;
444 }
445
446 /*
447  * Back reference rules.  Back refs have three main goals:
448  *
449  * 1) differentiate between all holders of references to an extent so that
450  *    when a reference is dropped we can make sure it was a valid reference
451  *    before freeing the extent.
452  *
453  * 2) Provide enough information to quickly find the holders of an extent
454  *    if we notice a given block is corrupted or bad.
455  *
456  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
457  *    maintenance.  This is actually the same as #2, but with a slightly
458  *    different use case.
459  *
460  * File extents can be referenced by:
461  *
462  * - multiple snapshots, subvolumes, or different generations in one subvol
463  * - different files inside a single subvolume
464  * - different offsets inside a file (bookend extents in file.c)
465  *
466  * The extent ref structure has fields for:
467  *
468  * - Objectid of the subvolume root
469  * - Generation number of the tree holding the reference
470  * - objectid of the file holding the reference
471  * - number of references holding by parent node (alway 1 for tree blocks)
472  *
473  * Btree leaf may hold multiple references to a file extent. In most cases,
474  * these references are from same file and the corresponding offsets inside
475  * the file are close together.
476  *
477  * When a file extent is allocated the fields are filled in:
478  *     (root_key.objectid, trans->transid, inode objectid, 1)
479  *
480  * When a leaf is cow'd new references are added for every file extent found
481  * in the leaf.  It looks similar to the create case, but trans->transid will
482  * be different when the block is cow'd.
483  *
484  *     (root_key.objectid, trans->transid, inode objectid,
485  *      number of references in the leaf)
486  *
487  * When a file extent is removed either during snapshot deletion or
488  * file truncation, we find the corresponding back reference and check
489  * the following fields:
490  *
491  *     (btrfs_header_owner(leaf), btrfs_header_generation(leaf),
492  *      inode objectid)
493  *
494  * Btree extents can be referenced by:
495  *
496  * - Different subvolumes
497  * - Different generations of the same subvolume
498  *
499  * When a tree block is created, back references are inserted:
500  *
501  * (root->root_key.objectid, trans->transid, level, 1)
502  *
503  * When a tree block is cow'd, new back references are added for all the
504  * blocks it points to. If the tree block isn't in reference counted root,
505  * the old back references are removed. These new back references are of
506  * the form (trans->transid will have increased since creation):
507  *
508  * (root->root_key.objectid, trans->transid, level, 1)
509  *
510  * When a backref is in deleting, the following fields are checked:
511  *
512  * if backref was for a tree root:
513  *     (btrfs_header_owner(itself), btrfs_header_generation(itself), level)
514  * else
515  *     (btrfs_header_owner(parent), btrfs_header_generation(parent), level)
516  *
517  * Back Reference Key composing:
518  *
519  * The key objectid corresponds to the first byte in the extent, the key
520  * type is set to BTRFS_EXTENT_REF_KEY, and the key offset is the first
521  * byte of parent extent. If a extent is tree root, the key offset is set
522  * to the key objectid.
523  */
524
525 static noinline int lookup_extent_backref(struct btrfs_trans_handle *trans,
526                                           struct btrfs_root *root,
527                                           struct btrfs_path *path,
528                                           u64 bytenr, u64 parent,
529                                           u64 ref_root, u64 ref_generation,
530                                           u64 owner_objectid, int del)
531 {
532         struct btrfs_key key;
533         struct btrfs_extent_ref *ref;
534         struct extent_buffer *leaf;
535         u64 ref_objectid;
536         int ret;
537
538         key.objectid = bytenr;
539         key.type = BTRFS_EXTENT_REF_KEY;
540         key.offset = parent;
541
542         ret = btrfs_search_slot(trans, root, &key, path, del ? -1 : 0, 1);
543         if (ret < 0)
544                 goto out;
545         if (ret > 0) {
546                 ret = -ENOENT;
547                 goto out;
548         }
549
550         leaf = path->nodes[0];
551         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
552         ref_objectid = btrfs_ref_objectid(leaf, ref);
553         if (btrfs_ref_root(leaf, ref) != ref_root ||
554             btrfs_ref_generation(leaf, ref) != ref_generation ||
555             (ref_objectid != owner_objectid &&
556              ref_objectid != BTRFS_MULTIPLE_OBJECTIDS)) {
557                 ret = -EIO;
558                 WARN_ON(1);
559                 goto out;
560         }
561         ret = 0;
562 out:
563         return ret;
564 }
565
566 static noinline int insert_extent_backref(struct btrfs_trans_handle *trans,
567                                           struct btrfs_root *root,
568                                           struct btrfs_path *path,
569                                           u64 bytenr, u64 parent,
570                                           u64 ref_root, u64 ref_generation,
571                                           u64 owner_objectid,
572                                           int refs_to_add)
573 {
574         struct btrfs_key key;
575         struct extent_buffer *leaf;
576         struct btrfs_extent_ref *ref;
577         u32 num_refs;
578         int ret;
579
580         key.objectid = bytenr;
581         key.type = BTRFS_EXTENT_REF_KEY;
582         key.offset = parent;
583
584         ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*ref));
585         if (ret == 0) {
586                 leaf = path->nodes[0];
587                 ref = btrfs_item_ptr(leaf, path->slots[0],
588                                      struct btrfs_extent_ref);
589                 btrfs_set_ref_root(leaf, ref, ref_root);
590                 btrfs_set_ref_generation(leaf, ref, ref_generation);
591                 btrfs_set_ref_objectid(leaf, ref, owner_objectid);
592                 btrfs_set_ref_num_refs(leaf, ref, refs_to_add);
593         } else if (ret == -EEXIST) {
594                 u64 existing_owner;
595
596                 BUG_ON(owner_objectid < BTRFS_FIRST_FREE_OBJECTID);
597                 leaf = path->nodes[0];
598                 ref = btrfs_item_ptr(leaf, path->slots[0],
599                                      struct btrfs_extent_ref);
600                 if (btrfs_ref_root(leaf, ref) != ref_root ||
601                     btrfs_ref_generation(leaf, ref) != ref_generation) {
602                         ret = -EIO;
603                         WARN_ON(1);
604                         goto out;
605                 }
606
607                 num_refs = btrfs_ref_num_refs(leaf, ref);
608                 BUG_ON(num_refs == 0);
609                 btrfs_set_ref_num_refs(leaf, ref, num_refs + refs_to_add);
610
611                 existing_owner = btrfs_ref_objectid(leaf, ref);
612                 if (existing_owner != owner_objectid &&
613                     existing_owner != BTRFS_MULTIPLE_OBJECTIDS) {
614                         btrfs_set_ref_objectid(leaf, ref,
615                                         BTRFS_MULTIPLE_OBJECTIDS);
616                 }
617                 ret = 0;
618         } else {
619                 goto out;
620         }
621         btrfs_mark_buffer_dirty(path->nodes[0]);
622 out:
623         btrfs_release_path(root, path);
624         return ret;
625 }
626
627 static noinline int remove_extent_backref(struct btrfs_trans_handle *trans,
628                                           struct btrfs_root *root,
629                                           struct btrfs_path *path,
630                                           int refs_to_drop)
631 {
632         struct extent_buffer *leaf;
633         struct btrfs_extent_ref *ref;
634         u32 num_refs;
635         int ret = 0;
636
637         leaf = path->nodes[0];
638         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
639         num_refs = btrfs_ref_num_refs(leaf, ref);
640         BUG_ON(num_refs < refs_to_drop);
641         num_refs -= refs_to_drop;
642         if (num_refs == 0) {
643                 ret = btrfs_del_item(trans, root, path);
644         } else {
645                 btrfs_set_ref_num_refs(leaf, ref, num_refs);
646                 btrfs_mark_buffer_dirty(leaf);
647         }
648         btrfs_release_path(root, path);
649         return ret;
650 }
651
652 #ifdef BIO_RW_DISCARD
653 static void btrfs_issue_discard(struct block_device *bdev,
654                                 u64 start, u64 len)
655 {
656         blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL);
657 }
658 #endif
659
660 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
661                                 u64 num_bytes)
662 {
663 #ifdef BIO_RW_DISCARD
664         int ret;
665         u64 map_length = num_bytes;
666         struct btrfs_multi_bio *multi = NULL;
667
668         /* Tell the block device(s) that the sectors can be discarded */
669         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
670                               bytenr, &map_length, &multi, 0);
671         if (!ret) {
672                 struct btrfs_bio_stripe *stripe = multi->stripes;
673                 int i;
674
675                 if (map_length > num_bytes)
676                         map_length = num_bytes;
677
678                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
679                         btrfs_issue_discard(stripe->dev->bdev,
680                                             stripe->physical,
681                                             map_length);
682                 }
683                 kfree(multi);
684         }
685
686         return ret;
687 #else
688         return 0;
689 #endif
690 }
691
692 static int __btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
693                                      struct btrfs_root *root, u64 bytenr,
694                                      u64 num_bytes,
695                                      u64 orig_parent, u64 parent,
696                                      u64 orig_root, u64 ref_root,
697                                      u64 orig_generation, u64 ref_generation,
698                                      u64 owner_objectid)
699 {
700         int ret;
701         int pin = owner_objectid < BTRFS_FIRST_FREE_OBJECTID;
702
703         ret = btrfs_update_delayed_ref(trans, bytenr, num_bytes,
704                                        orig_parent, parent, orig_root,
705                                        ref_root, orig_generation,
706                                        ref_generation, owner_objectid, pin);
707         BUG_ON(ret);
708         return ret;
709 }
710
711 int btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
712                             struct btrfs_root *root, u64 bytenr,
713                             u64 num_bytes, u64 orig_parent, u64 parent,
714                             u64 ref_root, u64 ref_generation,
715                             u64 owner_objectid)
716 {
717         int ret;
718         if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
719             owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
720                 return 0;
721
722         ret = __btrfs_update_extent_ref(trans, root, bytenr, num_bytes,
723                                         orig_parent, parent, ref_root,
724                                         ref_root, ref_generation,
725                                         ref_generation, owner_objectid);
726         return ret;
727 }
728 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
729                                   struct btrfs_root *root, u64 bytenr,
730                                   u64 num_bytes,
731                                   u64 orig_parent, u64 parent,
732                                   u64 orig_root, u64 ref_root,
733                                   u64 orig_generation, u64 ref_generation,
734                                   u64 owner_objectid)
735 {
736         int ret;
737
738         ret = btrfs_add_delayed_ref(trans, bytenr, num_bytes, parent, ref_root,
739                                     ref_generation, owner_objectid,
740                                     BTRFS_ADD_DELAYED_REF, 0);
741         BUG_ON(ret);
742         return ret;
743 }
744
745 static noinline_for_stack int add_extent_ref(struct btrfs_trans_handle *trans,
746                           struct btrfs_root *root, u64 bytenr,
747                           u64 num_bytes, u64 parent, u64 ref_root,
748                           u64 ref_generation, u64 owner_objectid,
749                           int refs_to_add)
750 {
751         struct btrfs_path *path;
752         int ret;
753         struct btrfs_key key;
754         struct extent_buffer *l;
755         struct btrfs_extent_item *item;
756         u32 refs;
757
758         path = btrfs_alloc_path();
759         if (!path)
760                 return -ENOMEM;
761
762         path->reada = 1;
763         key.objectid = bytenr;
764         key.type = BTRFS_EXTENT_ITEM_KEY;
765         key.offset = num_bytes;
766
767         /* first find the extent item and update its reference count */
768         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
769                                 path, 0, 1);
770         if (ret < 0)
771                 return ret;
772
773         if (ret > 0) {
774                 WARN_ON(1);
775                 btrfs_free_path(path);
776                 return -EIO;
777         }
778         l = path->nodes[0];
779
780         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
781         if (key.objectid != bytenr) {
782                 btrfs_print_leaf(root->fs_info->extent_root, path->nodes[0]);
783                 printk(KERN_ERR "btrfs wanted %llu found %llu\n",
784                        (unsigned long long)bytenr,
785                        (unsigned long long)key.objectid);
786                 BUG();
787         }
788         BUG_ON(key.type != BTRFS_EXTENT_ITEM_KEY);
789
790         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
791
792         refs = btrfs_extent_refs(l, item);
793         btrfs_set_extent_refs(l, item, refs + refs_to_add);
794         btrfs_mark_buffer_dirty(path->nodes[0]);
795
796         btrfs_release_path(root->fs_info->extent_root, path);
797
798         path->reada = 1;
799         /* now insert the actual backref */
800         ret = insert_extent_backref(trans, root->fs_info->extent_root,
801                                     path, bytenr, parent,
802                                     ref_root, ref_generation,
803                                     owner_objectid, refs_to_add);
804         BUG_ON(ret);
805         btrfs_free_path(path);
806         return 0;
807 }
808
809 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
810                          struct btrfs_root *root,
811                          u64 bytenr, u64 num_bytes, u64 parent,
812                          u64 ref_root, u64 ref_generation,
813                          u64 owner_objectid)
814 {
815         int ret;
816         if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
817             owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
818                 return 0;
819
820         ret = __btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0, parent,
821                                      0, ref_root, 0, ref_generation,
822                                      owner_objectid);
823         return ret;
824 }
825
826 static int drop_delayed_ref(struct btrfs_trans_handle *trans,
827                                         struct btrfs_root *root,
828                                         struct btrfs_delayed_ref_node *node)
829 {
830         int ret = 0;
831         struct btrfs_delayed_ref *ref = btrfs_delayed_node_to_ref(node);
832
833         BUG_ON(node->ref_mod == 0);
834         ret = __btrfs_free_extent(trans, root, node->bytenr, node->num_bytes,
835                                   node->parent, ref->root, ref->generation,
836                                   ref->owner_objectid, ref->pin, node->ref_mod);
837
838         return ret;
839 }
840
841 /* helper function to actually process a single delayed ref entry */
842 static noinline int run_one_delayed_ref(struct btrfs_trans_handle *trans,
843                                         struct btrfs_root *root,
844                                         struct btrfs_delayed_ref_node *node,
845                                         int insert_reserved)
846 {
847         int ret;
848         struct btrfs_delayed_ref *ref;
849
850         if (node->parent == (u64)-1) {
851                 struct btrfs_delayed_ref_head *head;
852                 /*
853                  * we've hit the end of the chain and we were supposed
854                  * to insert this extent into the tree.  But, it got
855                  * deleted before we ever needed to insert it, so all
856                  * we have to do is clean up the accounting
857                  */
858                 if (insert_reserved) {
859                         update_reserved_extents(root, node->bytenr,
860                                                 node->num_bytes, 0);
861                 }
862                 head = btrfs_delayed_node_to_head(node);
863                 mutex_unlock(&head->mutex);
864                 return 0;
865         }
866
867         ref = btrfs_delayed_node_to_ref(node);
868         if (ref->action == BTRFS_ADD_DELAYED_REF) {
869                 if (insert_reserved) {
870                         struct btrfs_key ins;
871
872                         ins.objectid = node->bytenr;
873                         ins.offset = node->num_bytes;
874                         ins.type = BTRFS_EXTENT_ITEM_KEY;
875
876                         /* record the full extent allocation */
877                         ret = __btrfs_alloc_reserved_extent(trans, root,
878                                         node->parent, ref->root,
879                                         ref->generation, ref->owner_objectid,
880                                         &ins, node->ref_mod);
881                         update_reserved_extents(root, node->bytenr,
882                                                 node->num_bytes, 0);
883                 } else {
884                         /* just add one backref */
885                         ret = add_extent_ref(trans, root, node->bytenr,
886                                      node->num_bytes,
887                                      node->parent, ref->root, ref->generation,
888                                      ref->owner_objectid, node->ref_mod);
889                 }
890                 BUG_ON(ret);
891         } else if (ref->action == BTRFS_DROP_DELAYED_REF) {
892                 WARN_ON(insert_reserved);
893                 ret = drop_delayed_ref(trans, root, node);
894         }
895         return 0;
896 }
897
898 static noinline struct btrfs_delayed_ref_node *
899 select_delayed_ref(struct btrfs_delayed_ref_head *head)
900 {
901         struct rb_node *node;
902         struct btrfs_delayed_ref_node *ref;
903         int action = BTRFS_ADD_DELAYED_REF;
904 again:
905         /*
906          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
907          * this prevents ref count from going down to zero when
908          * there still are pending delayed ref.
909          */
910         node = rb_prev(&head->node.rb_node);
911         while (1) {
912                 if (!node)
913                         break;
914                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
915                                 rb_node);
916                 if (ref->bytenr != head->node.bytenr)
917                         break;
918                 if (btrfs_delayed_node_to_ref(ref)->action == action)
919                         return ref;
920                 node = rb_prev(node);
921         }
922         if (action == BTRFS_ADD_DELAYED_REF) {
923                 action = BTRFS_DROP_DELAYED_REF;
924                 goto again;
925         }
926         return NULL;
927 }
928
929 /*
930  * this starts processing the delayed reference count updates and
931  * extent insertions we have queued up so far.  count can be
932  * 0, which means to process everything in the tree at the start
933  * of the run (but not newly added entries), or it can be some target
934  * number you'd like to process.
935  */
936 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
937                            struct btrfs_root *root, unsigned long count)
938 {
939         struct rb_node *node;
940         struct btrfs_delayed_ref_root *delayed_refs;
941         struct btrfs_delayed_ref_node *ref;
942         struct btrfs_delayed_ref_head *locked_ref = NULL;
943         int ret;
944         int must_insert_reserved = 0;
945         int run_all = count == (unsigned long)-1;
946
947         if (root == root->fs_info->extent_root)
948                 root = root->fs_info->tree_root;
949
950         delayed_refs = &trans->transaction->delayed_refs;
951 again:
952         spin_lock(&delayed_refs->lock);
953         if (count == 0)
954                 count = delayed_refs->num_entries;
955         while (1) {
956                 if (!locked_ref) {
957                         /*
958                          * no locked ref, go find something we can
959                          * process in the rbtree.  We start at
960                          * the beginning of the tree, there may be less
961                          * lock contention if we do something smarter here.
962                          */
963                         node = rb_first(&delayed_refs->root);
964                         if (!node) {
965                                 spin_unlock(&delayed_refs->lock);
966                                 break;
967                         }
968
969                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
970                                        rb_node);
971                         ret = btrfs_lock_delayed_ref(trans, ref, &locked_ref);
972                         if (ret) {
973                                 spin_unlock(&delayed_refs->lock);
974                                 break;
975                         }
976                 }
977
978                 /*
979                  * record the must insert reserved flag before we
980                  * drop the spin lock.
981                  */
982                 must_insert_reserved = locked_ref->must_insert_reserved;
983                 locked_ref->must_insert_reserved = 0;
984
985                 /*
986                  * locked_ref is the head node, so we have to go one
987                  * node back for any delayed ref updates
988                  */
989
990                 ref = select_delayed_ref(locked_ref);
991                 if (!ref) {
992                         /* All delayed refs have been processed, Go ahead
993                          * and send the head node to run_one_delayed_ref,
994                          * so that any accounting fixes can happen
995                          */
996                         ref = &locked_ref->node;
997                         locked_ref = NULL;
998                 }
999
1000                 ref->in_tree = 0;
1001                 rb_erase(&ref->rb_node, &delayed_refs->root);
1002                 delayed_refs->num_entries--;
1003                 spin_unlock(&delayed_refs->lock);
1004
1005                 ret = run_one_delayed_ref(trans, root, ref,
1006                                           must_insert_reserved);
1007                 BUG_ON(ret);
1008                 btrfs_put_delayed_ref(ref);
1009
1010                 /* once we lock the head ref, we have to process all the
1011                  * entries for it.  So, we might end up doing more entries
1012                  * that count was asking us to do.
1013                  */
1014                 if (count > 0)
1015                         count--;
1016
1017                 /*
1018                  * we set locked_ref to null above if we're all done
1019                  * with this bytenr
1020                  */
1021                 if (!locked_ref && count == 0)
1022                         break;
1023
1024                 cond_resched();
1025                 spin_lock(&delayed_refs->lock);
1026         }
1027         if (run_all) {
1028                 spin_lock(&delayed_refs->lock);
1029                 node = rb_first(&delayed_refs->root);
1030                 if (!node) {
1031                         spin_unlock(&delayed_refs->lock);
1032                         goto out;
1033                 }
1034
1035                 while (node) {
1036                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
1037                                        rb_node);
1038                         if (btrfs_delayed_ref_is_head(ref)) {
1039                                 struct btrfs_delayed_ref_head *head;
1040
1041                                 head = btrfs_delayed_node_to_head(ref);
1042                                 atomic_inc(&ref->refs);
1043
1044                                 spin_unlock(&delayed_refs->lock);
1045                                 mutex_lock(&head->mutex);
1046                                 mutex_unlock(&head->mutex);
1047
1048                                 btrfs_put_delayed_ref(ref);
1049                                 cond_resched();
1050                                 goto again;
1051                         }
1052                         node = rb_next(node);
1053                 }
1054                 spin_unlock(&delayed_refs->lock);
1055                 count = (unsigned long)-1;
1056                 schedule_timeout(1);
1057                 goto again;
1058         }
1059 out:
1060         return 0;
1061 }
1062
1063 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
1064                           struct btrfs_root *root, u64 objectid, u64 bytenr)
1065 {
1066         struct btrfs_root *extent_root = root->fs_info->extent_root;
1067         struct btrfs_path *path;
1068         struct extent_buffer *leaf;
1069         struct btrfs_extent_ref *ref_item;
1070         struct btrfs_key key;
1071         struct btrfs_key found_key;
1072         u64 ref_root;
1073         u64 last_snapshot;
1074         u32 nritems;
1075         int ret;
1076
1077         key.objectid = bytenr;
1078         key.offset = (u64)-1;
1079         key.type = BTRFS_EXTENT_ITEM_KEY;
1080
1081         path = btrfs_alloc_path();
1082         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1083         if (ret < 0)
1084                 goto out;
1085         BUG_ON(ret == 0);
1086
1087         ret = -ENOENT;
1088         if (path->slots[0] == 0)
1089                 goto out;
1090
1091         path->slots[0]--;
1092         leaf = path->nodes[0];
1093         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1094
1095         if (found_key.objectid != bytenr ||
1096             found_key.type != BTRFS_EXTENT_ITEM_KEY)
1097                 goto out;
1098
1099         last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1100         while (1) {
1101                 leaf = path->nodes[0];
1102                 nritems = btrfs_header_nritems(leaf);
1103                 if (path->slots[0] >= nritems) {
1104                         ret = btrfs_next_leaf(extent_root, path);
1105                         if (ret < 0)
1106                                 goto out;
1107                         if (ret == 0)
1108                                 continue;
1109                         break;
1110                 }
1111                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1112                 if (found_key.objectid != bytenr)
1113                         break;
1114
1115                 if (found_key.type != BTRFS_EXTENT_REF_KEY) {
1116                         path->slots[0]++;
1117                         continue;
1118                 }
1119
1120                 ref_item = btrfs_item_ptr(leaf, path->slots[0],
1121                                           struct btrfs_extent_ref);
1122                 ref_root = btrfs_ref_root(leaf, ref_item);
1123                 if ((ref_root != root->root_key.objectid &&
1124                      ref_root != BTRFS_TREE_LOG_OBJECTID) ||
1125                      objectid != btrfs_ref_objectid(leaf, ref_item)) {
1126                         ret = 1;
1127                         goto out;
1128                 }
1129                 if (btrfs_ref_generation(leaf, ref_item) <= last_snapshot) {
1130                         ret = 1;
1131                         goto out;
1132                 }
1133
1134                 path->slots[0]++;
1135         }
1136         ret = 0;
1137 out:
1138         btrfs_free_path(path);
1139         return ret;
1140 }
1141
1142 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1143                     struct extent_buffer *buf, u32 nr_extents)
1144 {
1145         struct btrfs_key key;
1146         struct btrfs_file_extent_item *fi;
1147         u64 root_gen;
1148         u32 nritems;
1149         int i;
1150         int level;
1151         int ret = 0;
1152         int shared = 0;
1153
1154         if (!root->ref_cows)
1155                 return 0;
1156
1157         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1158                 shared = 0;
1159                 root_gen = root->root_key.offset;
1160         } else {
1161                 shared = 1;
1162                 root_gen = trans->transid - 1;
1163         }
1164
1165         level = btrfs_header_level(buf);
1166         nritems = btrfs_header_nritems(buf);
1167
1168         if (level == 0) {
1169                 struct btrfs_leaf_ref *ref;
1170                 struct btrfs_extent_info *info;
1171
1172                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
1173                 if (!ref) {
1174                         ret = -ENOMEM;
1175                         goto out;
1176                 }
1177
1178                 ref->root_gen = root_gen;
1179                 ref->bytenr = buf->start;
1180                 ref->owner = btrfs_header_owner(buf);
1181                 ref->generation = btrfs_header_generation(buf);
1182                 ref->nritems = nr_extents;
1183                 info = ref->extents;
1184
1185                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
1186                         u64 disk_bytenr;
1187                         btrfs_item_key_to_cpu(buf, &key, i);
1188                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1189                                 continue;
1190                         fi = btrfs_item_ptr(buf, i,
1191                                             struct btrfs_file_extent_item);
1192                         if (btrfs_file_extent_type(buf, fi) ==
1193                             BTRFS_FILE_EXTENT_INLINE)
1194                                 continue;
1195                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1196                         if (disk_bytenr == 0)
1197                                 continue;
1198
1199                         info->bytenr = disk_bytenr;
1200                         info->num_bytes =
1201                                 btrfs_file_extent_disk_num_bytes(buf, fi);
1202                         info->objectid = key.objectid;
1203                         info->offset = key.offset;
1204                         info++;
1205                 }
1206
1207                 ret = btrfs_add_leaf_ref(root, ref, shared);
1208                 if (ret == -EEXIST && shared) {
1209                         struct btrfs_leaf_ref *old;
1210                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
1211                         BUG_ON(!old);
1212                         btrfs_remove_leaf_ref(root, old);
1213                         btrfs_free_leaf_ref(root, old);
1214                         ret = btrfs_add_leaf_ref(root, ref, shared);
1215                 }
1216                 WARN_ON(ret);
1217                 btrfs_free_leaf_ref(root, ref);
1218         }
1219 out:
1220         return ret;
1221 }
1222
1223 /* when a block goes through cow, we update the reference counts of
1224  * everything that block points to.  The internal pointers of the block
1225  * can be in just about any order, and it is likely to have clusters of
1226  * things that are close together and clusters of things that are not.
1227  *
1228  * To help reduce the seeks that come with updating all of these reference
1229  * counts, sort them by byte number before actual updates are done.
1230  *
1231  * struct refsort is used to match byte number to slot in the btree block.
1232  * we sort based on the byte number and then use the slot to actually
1233  * find the item.
1234  *
1235  * struct refsort is smaller than strcut btrfs_item and smaller than
1236  * struct btrfs_key_ptr.  Since we're currently limited to the page size
1237  * for a btree block, there's no way for a kmalloc of refsorts for a
1238  * single node to be bigger than a page.
1239  */
1240 struct refsort {
1241         u64 bytenr;
1242         u32 slot;
1243 };
1244
1245 /*
1246  * for passing into sort()
1247  */
1248 static int refsort_cmp(const void *a_void, const void *b_void)
1249 {
1250         const struct refsort *a = a_void;
1251         const struct refsort *b = b_void;
1252
1253         if (a->bytenr < b->bytenr)
1254                 return -1;
1255         if (a->bytenr > b->bytenr)
1256                 return 1;
1257         return 0;
1258 }
1259
1260
1261 noinline int btrfs_inc_ref(struct btrfs_trans_handle *trans,
1262                            struct btrfs_root *root,
1263                            struct extent_buffer *orig_buf,
1264                            struct extent_buffer *buf, u32 *nr_extents)
1265 {
1266         u64 bytenr;
1267         u64 ref_root;
1268         u64 orig_root;
1269         u64 ref_generation;
1270         u64 orig_generation;
1271         struct refsort *sorted;
1272         u32 nritems;
1273         u32 nr_file_extents = 0;
1274         struct btrfs_key key;
1275         struct btrfs_file_extent_item *fi;
1276         int i;
1277         int level;
1278         int ret = 0;
1279         int faili = 0;
1280         int refi = 0;
1281         int slot;
1282         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
1283                             u64, u64, u64, u64, u64, u64, u64, u64, u64);
1284
1285         ref_root = btrfs_header_owner(buf);
1286         ref_generation = btrfs_header_generation(buf);
1287         orig_root = btrfs_header_owner(orig_buf);
1288         orig_generation = btrfs_header_generation(orig_buf);
1289
1290         nritems = btrfs_header_nritems(buf);
1291         level = btrfs_header_level(buf);
1292
1293         sorted = kmalloc(sizeof(struct refsort) * nritems, GFP_NOFS);
1294         BUG_ON(!sorted);
1295
1296         if (root->ref_cows) {
1297                 process_func = __btrfs_inc_extent_ref;
1298         } else {
1299                 if (level == 0 &&
1300                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1301                         goto out;
1302                 if (level != 0 &&
1303                     root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1304                         goto out;
1305                 process_func = __btrfs_update_extent_ref;
1306         }
1307
1308         /*
1309          * we make two passes through the items.  In the first pass we
1310          * only record the byte number and slot.  Then we sort based on
1311          * byte number and do the actual work based on the sorted results
1312          */
1313         for (i = 0; i < nritems; i++) {
1314                 cond_resched();
1315                 if (level == 0) {
1316                         btrfs_item_key_to_cpu(buf, &key, i);
1317                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1318                                 continue;
1319                         fi = btrfs_item_ptr(buf, i,
1320                                             struct btrfs_file_extent_item);
1321                         if (btrfs_file_extent_type(buf, fi) ==
1322                             BTRFS_FILE_EXTENT_INLINE)
1323                                 continue;
1324                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1325                         if (bytenr == 0)
1326                                 continue;
1327
1328                         nr_file_extents++;
1329                         sorted[refi].bytenr = bytenr;
1330                         sorted[refi].slot = i;
1331                         refi++;
1332                 } else {
1333                         bytenr = btrfs_node_blockptr(buf, i);
1334                         sorted[refi].bytenr = bytenr;
1335                         sorted[refi].slot = i;
1336                         refi++;
1337                 }
1338         }
1339         /*
1340          * if refi == 0, we didn't actually put anything into the sorted
1341          * array and we're done
1342          */
1343         if (refi == 0)
1344                 goto out;
1345
1346         sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
1347
1348         for (i = 0; i < refi; i++) {
1349                 cond_resched();
1350                 slot = sorted[i].slot;
1351                 bytenr = sorted[i].bytenr;
1352
1353                 if (level == 0) {
1354                         btrfs_item_key_to_cpu(buf, &key, slot);
1355                         fi = btrfs_item_ptr(buf, slot,
1356                                             struct btrfs_file_extent_item);
1357
1358                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1359                         if (bytenr == 0)
1360                                 continue;
1361
1362                         ret = process_func(trans, root, bytenr,
1363                                    btrfs_file_extent_disk_num_bytes(buf, fi),
1364                                    orig_buf->start, buf->start,
1365                                    orig_root, ref_root,
1366                                    orig_generation, ref_generation,
1367                                    key.objectid);
1368
1369                         if (ret) {
1370                                 faili = slot;
1371                                 WARN_ON(1);
1372                                 goto fail;
1373                         }
1374                 } else {
1375                         ret = process_func(trans, root, bytenr, buf->len,
1376                                            orig_buf->start, buf->start,
1377                                            orig_root, ref_root,
1378                                            orig_generation, ref_generation,
1379                                            level - 1);
1380                         if (ret) {
1381                                 faili = slot;
1382                                 WARN_ON(1);
1383                                 goto fail;
1384                         }
1385                 }
1386         }
1387 out:
1388         kfree(sorted);
1389         if (nr_extents) {
1390                 if (level == 0)
1391                         *nr_extents = nr_file_extents;
1392                 else
1393                         *nr_extents = nritems;
1394         }
1395         return 0;
1396 fail:
1397         kfree(sorted);
1398         WARN_ON(1);
1399         return ret;
1400 }
1401
1402 int btrfs_update_ref(struct btrfs_trans_handle *trans,
1403                      struct btrfs_root *root, struct extent_buffer *orig_buf,
1404                      struct extent_buffer *buf, int start_slot, int nr)
1405
1406 {
1407         u64 bytenr;
1408         u64 ref_root;
1409         u64 orig_root;
1410         u64 ref_generation;
1411         u64 orig_generation;
1412         struct btrfs_key key;
1413         struct btrfs_file_extent_item *fi;
1414         int i;
1415         int ret;
1416         int slot;
1417         int level;
1418
1419         BUG_ON(start_slot < 0);
1420         BUG_ON(start_slot + nr > btrfs_header_nritems(buf));
1421
1422         ref_root = btrfs_header_owner(buf);
1423         ref_generation = btrfs_header_generation(buf);
1424         orig_root = btrfs_header_owner(orig_buf);
1425         orig_generation = btrfs_header_generation(orig_buf);
1426         level = btrfs_header_level(buf);
1427
1428         if (!root->ref_cows) {
1429                 if (level == 0 &&
1430                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1431                         return 0;
1432                 if (level != 0 &&
1433                     root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1434                         return 0;
1435         }
1436
1437         for (i = 0, slot = start_slot; i < nr; i++, slot++) {
1438                 cond_resched();
1439                 if (level == 0) {
1440                         btrfs_item_key_to_cpu(buf, &key, slot);
1441                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1442                                 continue;
1443                         fi = btrfs_item_ptr(buf, slot,
1444                                             struct btrfs_file_extent_item);
1445                         if (btrfs_file_extent_type(buf, fi) ==
1446                             BTRFS_FILE_EXTENT_INLINE)
1447                                 continue;
1448                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1449                         if (bytenr == 0)
1450                                 continue;
1451                         ret = __btrfs_update_extent_ref(trans, root, bytenr,
1452                                     btrfs_file_extent_disk_num_bytes(buf, fi),
1453                                     orig_buf->start, buf->start,
1454                                     orig_root, ref_root, orig_generation,
1455                                     ref_generation, key.objectid);
1456                         if (ret)
1457                                 goto fail;
1458                 } else {
1459                         bytenr = btrfs_node_blockptr(buf, slot);
1460                         ret = __btrfs_update_extent_ref(trans, root, bytenr,
1461                                             buf->len, orig_buf->start,
1462                                             buf->start, orig_root, ref_root,
1463                                             orig_generation, ref_generation,
1464                                             level - 1);
1465                         if (ret)
1466                                 goto fail;
1467                 }
1468         }
1469         return 0;
1470 fail:
1471         WARN_ON(1);
1472         return -1;
1473 }
1474
1475 static int write_one_cache_group(struct btrfs_trans_handle *trans,
1476                                  struct btrfs_root *root,
1477                                  struct btrfs_path *path,
1478                                  struct btrfs_block_group_cache *cache)
1479 {
1480         int ret;
1481         struct btrfs_root *extent_root = root->fs_info->extent_root;
1482         unsigned long bi;
1483         struct extent_buffer *leaf;
1484
1485         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
1486         if (ret < 0)
1487                 goto fail;
1488         BUG_ON(ret);
1489
1490         leaf = path->nodes[0];
1491         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
1492         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
1493         btrfs_mark_buffer_dirty(leaf);
1494         btrfs_release_path(extent_root, path);
1495 fail:
1496         if (ret)
1497                 return ret;
1498         return 0;
1499
1500 }
1501
1502 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
1503                                    struct btrfs_root *root)
1504 {
1505         struct btrfs_block_group_cache *cache, *entry;
1506         struct rb_node *n;
1507         int err = 0;
1508         int werr = 0;
1509         struct btrfs_path *path;
1510         u64 last = 0;
1511
1512         path = btrfs_alloc_path();
1513         if (!path)
1514                 return -ENOMEM;
1515
1516         while (1) {
1517                 cache = NULL;
1518                 spin_lock(&root->fs_info->block_group_cache_lock);
1519                 for (n = rb_first(&root->fs_info->block_group_cache_tree);
1520                      n; n = rb_next(n)) {
1521                         entry = rb_entry(n, struct btrfs_block_group_cache,
1522                                          cache_node);
1523                         if (entry->dirty) {
1524                                 cache = entry;
1525                                 break;
1526                         }
1527                 }
1528                 spin_unlock(&root->fs_info->block_group_cache_lock);
1529
1530                 if (!cache)
1531                         break;
1532
1533                 cache->dirty = 0;
1534                 last += cache->key.offset;
1535
1536                 err = write_one_cache_group(trans, root,
1537                                             path, cache);
1538                 /*
1539                  * if we fail to write the cache group, we want
1540                  * to keep it marked dirty in hopes that a later
1541                  * write will work
1542                  */
1543                 if (err) {
1544                         werr = err;
1545                         continue;
1546                 }
1547         }
1548         btrfs_free_path(path);
1549         return werr;
1550 }
1551
1552 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
1553 {
1554         struct btrfs_block_group_cache *block_group;
1555         int readonly = 0;
1556
1557         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1558         if (!block_group || block_group->ro)
1559                 readonly = 1;
1560         if (block_group)
1561                 put_block_group(block_group);
1562         return readonly;
1563 }
1564
1565 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
1566                              u64 total_bytes, u64 bytes_used,
1567                              struct btrfs_space_info **space_info)
1568 {
1569         struct btrfs_space_info *found;
1570
1571         found = __find_space_info(info, flags);
1572         if (found) {
1573                 spin_lock(&found->lock);
1574                 found->total_bytes += total_bytes;
1575                 found->bytes_used += bytes_used;
1576                 found->full = 0;
1577                 spin_unlock(&found->lock);
1578                 *space_info = found;
1579                 return 0;
1580         }
1581         found = kzalloc(sizeof(*found), GFP_NOFS);
1582         if (!found)
1583                 return -ENOMEM;
1584
1585         INIT_LIST_HEAD(&found->block_groups);
1586         init_rwsem(&found->groups_sem);
1587         spin_lock_init(&found->lock);
1588         found->flags = flags;
1589         found->total_bytes = total_bytes;
1590         found->bytes_used = bytes_used;
1591         found->bytes_pinned = 0;
1592         found->bytes_reserved = 0;
1593         found->bytes_readonly = 0;
1594         found->bytes_delalloc = 0;
1595         found->full = 0;
1596         found->force_alloc = 0;
1597         *space_info = found;
1598         list_add_rcu(&found->list, &info->space_info);
1599         return 0;
1600 }
1601
1602 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1603 {
1604         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
1605                                    BTRFS_BLOCK_GROUP_RAID1 |
1606                                    BTRFS_BLOCK_GROUP_RAID10 |
1607                                    BTRFS_BLOCK_GROUP_DUP);
1608         if (extra_flags) {
1609                 if (flags & BTRFS_BLOCK_GROUP_DATA)
1610                         fs_info->avail_data_alloc_bits |= extra_flags;
1611                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1612                         fs_info->avail_metadata_alloc_bits |= extra_flags;
1613                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1614                         fs_info->avail_system_alloc_bits |= extra_flags;
1615         }
1616 }
1617
1618 static void set_block_group_readonly(struct btrfs_block_group_cache *cache)
1619 {
1620         spin_lock(&cache->space_info->lock);
1621         spin_lock(&cache->lock);
1622         if (!cache->ro) {
1623                 cache->space_info->bytes_readonly += cache->key.offset -
1624                                         btrfs_block_group_used(&cache->item);
1625                 cache->ro = 1;
1626         }
1627         spin_unlock(&cache->lock);
1628         spin_unlock(&cache->space_info->lock);
1629 }
1630
1631 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
1632 {
1633         u64 num_devices = root->fs_info->fs_devices->rw_devices;
1634
1635         if (num_devices == 1)
1636                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
1637         if (num_devices < 4)
1638                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
1639
1640         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
1641             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
1642                       BTRFS_BLOCK_GROUP_RAID10))) {
1643                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
1644         }
1645
1646         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
1647             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
1648                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
1649         }
1650
1651         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
1652             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
1653              (flags & BTRFS_BLOCK_GROUP_RAID10) |
1654              (flags & BTRFS_BLOCK_GROUP_DUP)))
1655                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
1656         return flags;
1657 }
1658
1659 static u64 btrfs_get_alloc_profile(struct btrfs_root *root, u64 data)
1660 {
1661         struct btrfs_fs_info *info = root->fs_info;
1662         u64 alloc_profile;
1663
1664         if (data) {
1665                 alloc_profile = info->avail_data_alloc_bits &
1666                         info->data_alloc_profile;
1667                 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
1668         } else if (root == root->fs_info->chunk_root) {
1669                 alloc_profile = info->avail_system_alloc_bits &
1670                         info->system_alloc_profile;
1671                 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
1672         } else {
1673                 alloc_profile = info->avail_metadata_alloc_bits &
1674                         info->metadata_alloc_profile;
1675                 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
1676         }
1677
1678         return btrfs_reduce_alloc_profile(root, data);
1679 }
1680
1681 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
1682 {
1683         u64 alloc_target;
1684
1685         alloc_target = btrfs_get_alloc_profile(root, 1);
1686         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
1687                                                        alloc_target);
1688 }
1689
1690 /*
1691  * for now this just makes sure we have at least 5% of our metadata space free
1692  * for use.
1693  */
1694 int btrfs_check_metadata_free_space(struct btrfs_root *root)
1695 {
1696         struct btrfs_fs_info *info = root->fs_info;
1697         struct btrfs_space_info *meta_sinfo;
1698         u64 alloc_target, thresh;
1699         int committed = 0, ret;
1700
1701         /* get the space info for where the metadata will live */
1702         alloc_target = btrfs_get_alloc_profile(root, 0);
1703         meta_sinfo = __find_space_info(info, alloc_target);
1704
1705 again:
1706         spin_lock(&meta_sinfo->lock);
1707         if (!meta_sinfo->full)
1708                 thresh = meta_sinfo->total_bytes * 80;
1709         else
1710                 thresh = meta_sinfo->total_bytes * 95;
1711
1712         do_div(thresh, 100);
1713
1714         if (meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
1715             meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly > thresh) {
1716                 struct btrfs_trans_handle *trans;
1717                 if (!meta_sinfo->full) {
1718                         meta_sinfo->force_alloc = 1;
1719                         spin_unlock(&meta_sinfo->lock);
1720
1721                         trans = btrfs_start_transaction(root, 1);
1722                         if (!trans)
1723                                 return -ENOMEM;
1724
1725                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1726                                              2 * 1024 * 1024, alloc_target, 0);
1727                         btrfs_end_transaction(trans, root);
1728                         goto again;
1729                 }
1730                 spin_unlock(&meta_sinfo->lock);
1731
1732                 if (!committed) {
1733                         committed = 1;
1734                         trans = btrfs_join_transaction(root, 1);
1735                         if (!trans)
1736                                 return -ENOMEM;
1737                         ret = btrfs_commit_transaction(trans, root);
1738                         if (ret)
1739                                 return ret;
1740                         goto again;
1741                 }
1742                 return -ENOSPC;
1743         }
1744         spin_unlock(&meta_sinfo->lock);
1745
1746         return 0;
1747 }
1748
1749 /*
1750  * This will check the space that the inode allocates from to make sure we have
1751  * enough space for bytes.
1752  */
1753 int btrfs_check_data_free_space(struct btrfs_root *root, struct inode *inode,
1754                                 u64 bytes)
1755 {
1756         struct btrfs_space_info *data_sinfo;
1757         int ret = 0, committed = 0;
1758
1759         /* make sure bytes are sectorsize aligned */
1760         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
1761
1762         data_sinfo = BTRFS_I(inode)->space_info;
1763 again:
1764         /* make sure we have enough space to handle the data first */
1765         spin_lock(&data_sinfo->lock);
1766         if (data_sinfo->total_bytes - data_sinfo->bytes_used -
1767             data_sinfo->bytes_delalloc - data_sinfo->bytes_reserved -
1768             data_sinfo->bytes_pinned - data_sinfo->bytes_readonly -
1769             data_sinfo->bytes_may_use < bytes) {
1770                 struct btrfs_trans_handle *trans;
1771
1772                 /*
1773                  * if we don't have enough free bytes in this space then we need
1774                  * to alloc a new chunk.
1775                  */
1776                 if (!data_sinfo->full) {
1777                         u64 alloc_target;
1778
1779                         data_sinfo->force_alloc = 1;
1780                         spin_unlock(&data_sinfo->lock);
1781
1782                         alloc_target = btrfs_get_alloc_profile(root, 1);
1783                         trans = btrfs_start_transaction(root, 1);
1784                         if (!trans)
1785                                 return -ENOMEM;
1786
1787                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1788                                              bytes + 2 * 1024 * 1024,
1789                                              alloc_target, 0);
1790                         btrfs_end_transaction(trans, root);
1791                         if (ret)
1792                                 return ret;
1793                         goto again;
1794                 }
1795                 spin_unlock(&data_sinfo->lock);
1796
1797                 /* commit the current transaction and try again */
1798                 if (!committed) {
1799                         committed = 1;
1800                         trans = btrfs_join_transaction(root, 1);
1801                         if (!trans)
1802                                 return -ENOMEM;
1803                         ret = btrfs_commit_transaction(trans, root);
1804                         if (ret)
1805                                 return ret;
1806                         goto again;
1807                 }
1808
1809                 printk(KERN_ERR "no space left, need %llu, %llu delalloc bytes"
1810                        ", %llu bytes_used, %llu bytes_reserved, "
1811                        "%llu bytes_pinned, %llu bytes_readonly, %llu may use"
1812                        "%llu total\n", bytes, data_sinfo->bytes_delalloc,
1813                        data_sinfo->bytes_used, data_sinfo->bytes_reserved,
1814                        data_sinfo->bytes_pinned, data_sinfo->bytes_readonly,
1815                        data_sinfo->bytes_may_use, data_sinfo->total_bytes);
1816                 return -ENOSPC;
1817         }
1818         data_sinfo->bytes_may_use += bytes;
1819         BTRFS_I(inode)->reserved_bytes += bytes;
1820         spin_unlock(&data_sinfo->lock);
1821
1822         return btrfs_check_metadata_free_space(root);
1823 }
1824
1825 /*
1826  * if there was an error for whatever reason after calling
1827  * btrfs_check_data_free_space, call this so we can cleanup the counters.
1828  */
1829 void btrfs_free_reserved_data_space(struct btrfs_root *root,
1830                                     struct inode *inode, u64 bytes)
1831 {
1832         struct btrfs_space_info *data_sinfo;
1833
1834         /* make sure bytes are sectorsize aligned */
1835         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
1836
1837         data_sinfo = BTRFS_I(inode)->space_info;
1838         spin_lock(&data_sinfo->lock);
1839         data_sinfo->bytes_may_use -= bytes;
1840         BTRFS_I(inode)->reserved_bytes -= bytes;
1841         spin_unlock(&data_sinfo->lock);
1842 }
1843
1844 /* called when we are adding a delalloc extent to the inode's io_tree */
1845 void btrfs_delalloc_reserve_space(struct btrfs_root *root, struct inode *inode,
1846                                   u64 bytes)
1847 {
1848         struct btrfs_space_info *data_sinfo;
1849
1850         /* get the space info for where this inode will be storing its data */
1851         data_sinfo = BTRFS_I(inode)->space_info;
1852
1853         /* make sure we have enough space to handle the data first */
1854         spin_lock(&data_sinfo->lock);
1855         data_sinfo->bytes_delalloc += bytes;
1856
1857         /*
1858          * we are adding a delalloc extent without calling
1859          * btrfs_check_data_free_space first.  This happens on a weird
1860          * writepage condition, but shouldn't hurt our accounting
1861          */
1862         if (unlikely(bytes > BTRFS_I(inode)->reserved_bytes)) {
1863                 data_sinfo->bytes_may_use -= BTRFS_I(inode)->reserved_bytes;
1864                 BTRFS_I(inode)->reserved_bytes = 0;
1865         } else {
1866                 data_sinfo->bytes_may_use -= bytes;
1867                 BTRFS_I(inode)->reserved_bytes -= bytes;
1868         }
1869
1870         spin_unlock(&data_sinfo->lock);
1871 }
1872
1873 /* called when we are clearing an delalloc extent from the inode's io_tree */
1874 void btrfs_delalloc_free_space(struct btrfs_root *root, struct inode *inode,
1875                               u64 bytes)
1876 {
1877         struct btrfs_space_info *info;
1878
1879         info = BTRFS_I(inode)->space_info;
1880
1881         spin_lock(&info->lock);
1882         info->bytes_delalloc -= bytes;
1883         spin_unlock(&info->lock);
1884 }
1885
1886 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
1887                           struct btrfs_root *extent_root, u64 alloc_bytes,
1888                           u64 flags, int force)
1889 {
1890         struct btrfs_space_info *space_info;
1891         u64 thresh;
1892         int ret = 0;
1893
1894         mutex_lock(&extent_root->fs_info->chunk_mutex);
1895
1896         flags = btrfs_reduce_alloc_profile(extent_root, flags);
1897
1898         space_info = __find_space_info(extent_root->fs_info, flags);
1899         if (!space_info) {
1900                 ret = update_space_info(extent_root->fs_info, flags,
1901                                         0, 0, &space_info);
1902                 BUG_ON(ret);
1903         }
1904         BUG_ON(!space_info);
1905
1906         spin_lock(&space_info->lock);
1907         if (space_info->force_alloc) {
1908                 force = 1;
1909                 space_info->force_alloc = 0;
1910         }
1911         if (space_info->full) {
1912                 spin_unlock(&space_info->lock);
1913                 goto out;
1914         }
1915
1916         thresh = space_info->total_bytes - space_info->bytes_readonly;
1917         thresh = div_factor(thresh, 6);
1918         if (!force &&
1919            (space_info->bytes_used + space_info->bytes_pinned +
1920             space_info->bytes_reserved + alloc_bytes) < thresh) {
1921                 spin_unlock(&space_info->lock);
1922                 goto out;
1923         }
1924         spin_unlock(&space_info->lock);
1925
1926         ret = btrfs_alloc_chunk(trans, extent_root, flags);
1927         if (ret)
1928                 space_info->full = 1;
1929 out:
1930         mutex_unlock(&extent_root->fs_info->chunk_mutex);
1931         return ret;
1932 }
1933
1934 static int update_block_group(struct btrfs_trans_handle *trans,
1935                               struct btrfs_root *root,
1936                               u64 bytenr, u64 num_bytes, int alloc,
1937                               int mark_free)
1938 {
1939         struct btrfs_block_group_cache *cache;
1940         struct btrfs_fs_info *info = root->fs_info;
1941         u64 total = num_bytes;
1942         u64 old_val;
1943         u64 byte_in_group;
1944
1945         while (total) {
1946                 cache = btrfs_lookup_block_group(info, bytenr);
1947                 if (!cache)
1948                         return -1;
1949                 byte_in_group = bytenr - cache->key.objectid;
1950                 WARN_ON(byte_in_group > cache->key.offset);
1951
1952                 spin_lock(&cache->space_info->lock);
1953                 spin_lock(&cache->lock);
1954                 cache->dirty = 1;
1955                 old_val = btrfs_block_group_used(&cache->item);
1956                 num_bytes = min(total, cache->key.offset - byte_in_group);
1957                 if (alloc) {
1958                         old_val += num_bytes;
1959                         cache->space_info->bytes_used += num_bytes;
1960                         if (cache->ro)
1961                                 cache->space_info->bytes_readonly -= num_bytes;
1962                         btrfs_set_block_group_used(&cache->item, old_val);
1963                         spin_unlock(&cache->lock);
1964                         spin_unlock(&cache->space_info->lock);
1965                 } else {
1966                         old_val -= num_bytes;
1967                         cache->space_info->bytes_used -= num_bytes;
1968                         if (cache->ro)
1969                                 cache->space_info->bytes_readonly += num_bytes;
1970                         btrfs_set_block_group_used(&cache->item, old_val);
1971                         spin_unlock(&cache->lock);
1972                         spin_unlock(&cache->space_info->lock);
1973                         if (mark_free) {
1974                                 int ret;
1975
1976                                 ret = btrfs_discard_extent(root, bytenr,
1977                                                            num_bytes);
1978                                 WARN_ON(ret);
1979
1980                                 ret = btrfs_add_free_space(cache, bytenr,
1981                                                            num_bytes);
1982                                 WARN_ON(ret);
1983                         }
1984                 }
1985                 put_block_group(cache);
1986                 total -= num_bytes;
1987                 bytenr += num_bytes;
1988         }
1989         return 0;
1990 }
1991
1992 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
1993 {
1994         struct btrfs_block_group_cache *cache;
1995         u64 bytenr;
1996
1997         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
1998         if (!cache)
1999                 return 0;
2000
2001         bytenr = cache->key.objectid;
2002         put_block_group(cache);
2003
2004         return bytenr;
2005 }
2006
2007 int btrfs_update_pinned_extents(struct btrfs_root *root,
2008                                 u64 bytenr, u64 num, int pin)
2009 {
2010         u64 len;
2011         struct btrfs_block_group_cache *cache;
2012         struct btrfs_fs_info *fs_info = root->fs_info;
2013
2014         WARN_ON(!mutex_is_locked(&root->fs_info->pinned_mutex));
2015         if (pin) {
2016                 set_extent_dirty(&fs_info->pinned_extents,
2017                                 bytenr, bytenr + num - 1, GFP_NOFS);
2018         } else {
2019                 clear_extent_dirty(&fs_info->pinned_extents,
2020                                 bytenr, bytenr + num - 1, GFP_NOFS);
2021         }
2022         while (num > 0) {
2023                 cache = btrfs_lookup_block_group(fs_info, bytenr);
2024                 BUG_ON(!cache);
2025                 len = min(num, cache->key.offset -
2026                           (bytenr - cache->key.objectid));
2027                 if (pin) {
2028                         spin_lock(&cache->space_info->lock);
2029                         spin_lock(&cache->lock);
2030                         cache->pinned += len;
2031                         cache->space_info->bytes_pinned += len;
2032                         spin_unlock(&cache->lock);
2033                         spin_unlock(&cache->space_info->lock);
2034                         fs_info->total_pinned += len;
2035                 } else {
2036                         spin_lock(&cache->space_info->lock);
2037                         spin_lock(&cache->lock);
2038                         cache->pinned -= len;
2039                         cache->space_info->bytes_pinned -= len;
2040                         spin_unlock(&cache->lock);
2041                         spin_unlock(&cache->space_info->lock);
2042                         fs_info->total_pinned -= len;
2043                         if (cache->cached)
2044                                 btrfs_add_free_space(cache, bytenr, len);
2045                 }
2046                 put_block_group(cache);
2047                 bytenr += len;
2048                 num -= len;
2049         }
2050         return 0;
2051 }
2052
2053 static int update_reserved_extents(struct btrfs_root *root,
2054                                    u64 bytenr, u64 num, int reserve)
2055 {
2056         u64 len;
2057         struct btrfs_block_group_cache *cache;
2058         struct btrfs_fs_info *fs_info = root->fs_info;
2059
2060         while (num > 0) {
2061                 cache = btrfs_lookup_block_group(fs_info, bytenr);
2062                 BUG_ON(!cache);
2063                 len = min(num, cache->key.offset -
2064                           (bytenr - cache->key.objectid));
2065
2066                 spin_lock(&cache->space_info->lock);
2067                 spin_lock(&cache->lock);
2068                 if (reserve) {
2069                         cache->reserved += len;
2070                         cache->space_info->bytes_reserved += len;
2071                 } else {
2072                         cache->reserved -= len;
2073                         cache->space_info->bytes_reserved -= len;
2074                 }
2075                 spin_unlock(&cache->lock);
2076                 spin_unlock(&cache->space_info->lock);
2077                 put_block_group(cache);
2078                 bytenr += len;
2079                 num -= len;
2080         }
2081         return 0;
2082 }
2083
2084 int btrfs_copy_pinned(struct btrfs_root *root, struct extent_io_tree *copy)
2085 {
2086         u64 last = 0;
2087         u64 start;
2088         u64 end;
2089         struct extent_io_tree *pinned_extents = &root->fs_info->pinned_extents;
2090         int ret;
2091
2092         mutex_lock(&root->fs_info->pinned_mutex);
2093         while (1) {
2094                 ret = find_first_extent_bit(pinned_extents, last,
2095                                             &start, &end, EXTENT_DIRTY);
2096                 if (ret)
2097                         break;
2098                 set_extent_dirty(copy, start, end, GFP_NOFS);
2099                 last = end + 1;
2100         }
2101         mutex_unlock(&root->fs_info->pinned_mutex);
2102         return 0;
2103 }
2104
2105 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
2106                                struct btrfs_root *root,
2107                                struct extent_io_tree *unpin)
2108 {
2109         u64 start;
2110         u64 end;
2111         int ret;
2112
2113         mutex_lock(&root->fs_info->pinned_mutex);
2114         while (1) {
2115                 ret = find_first_extent_bit(unpin, 0, &start, &end,
2116                                             EXTENT_DIRTY);
2117                 if (ret)
2118                         break;
2119
2120                 ret = btrfs_discard_extent(root, start, end + 1 - start);
2121
2122                 btrfs_update_pinned_extents(root, start, end + 1 - start, 0);
2123                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
2124
2125                 if (need_resched()) {
2126                         mutex_unlock(&root->fs_info->pinned_mutex);
2127                         cond_resched();
2128                         mutex_lock(&root->fs_info->pinned_mutex);
2129                 }
2130         }
2131         mutex_unlock(&root->fs_info->pinned_mutex);
2132         return ret;
2133 }
2134
2135 static int pin_down_bytes(struct btrfs_trans_handle *trans,
2136                           struct btrfs_root *root,
2137                           u64 bytenr, u64 num_bytes, int is_data)
2138 {
2139         int err = 0;
2140         struct extent_buffer *buf;
2141
2142         if (is_data)
2143                 goto pinit;
2144
2145         buf = btrfs_find_tree_block(root, bytenr, num_bytes);
2146         if (!buf)
2147                 goto pinit;
2148
2149         /* we can reuse a block if it hasn't been written
2150          * and it is from this transaction.  We can't
2151          * reuse anything from the tree log root because
2152          * it has tiny sub-transactions.
2153          */
2154         if (btrfs_buffer_uptodate(buf, 0) &&
2155             btrfs_try_tree_lock(buf)) {
2156                 u64 header_owner = btrfs_header_owner(buf);
2157                 u64 header_transid = btrfs_header_generation(buf);
2158                 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
2159                     header_owner != BTRFS_TREE_RELOC_OBJECTID &&
2160                     header_owner != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2161                     header_transid == trans->transid &&
2162                     !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
2163                         clean_tree_block(NULL, root, buf);
2164                         btrfs_tree_unlock(buf);
2165                         free_extent_buffer(buf);
2166                         return 1;
2167                 }
2168                 btrfs_tree_unlock(buf);
2169         }
2170         free_extent_buffer(buf);
2171 pinit:
2172         btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
2173
2174         BUG_ON(err < 0);
2175         return 0;
2176 }
2177
2178 /*
2179  * remove an extent from the root, returns 0 on success
2180  */
2181 static int __free_extent(struct btrfs_trans_handle *trans,
2182                          struct btrfs_root *root,
2183                          u64 bytenr, u64 num_bytes, u64 parent,
2184                          u64 root_objectid, u64 ref_generation,
2185                          u64 owner_objectid, int pin, int mark_free,
2186                          int refs_to_drop)
2187 {
2188         struct btrfs_path *path;
2189         struct btrfs_key key;
2190         struct btrfs_fs_info *info = root->fs_info;
2191         struct btrfs_root *extent_root = info->extent_root;
2192         struct extent_buffer *leaf;
2193         int ret;
2194         int extent_slot = 0;
2195         int found_extent = 0;
2196         int num_to_del = 1;
2197         struct btrfs_extent_item *ei;
2198         u32 refs;
2199
2200         key.objectid = bytenr;
2201         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
2202         key.offset = num_bytes;
2203         path = btrfs_alloc_path();
2204         if (!path)
2205                 return -ENOMEM;
2206
2207         path->reada = 1;
2208         ret = lookup_extent_backref(trans, extent_root, path,
2209                                     bytenr, parent, root_objectid,
2210                                     ref_generation, owner_objectid, 1);
2211         if (ret == 0) {
2212                 struct btrfs_key found_key;
2213                 extent_slot = path->slots[0];
2214                 while (extent_slot > 0) {
2215                         extent_slot--;
2216                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2217                                               extent_slot);
2218                         if (found_key.objectid != bytenr)
2219                                 break;
2220                         if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
2221                             found_key.offset == num_bytes) {
2222                                 found_extent = 1;
2223                                 break;
2224                         }
2225                         if (path->slots[0] - extent_slot > 5)
2226                                 break;
2227                 }
2228                 if (!found_extent) {
2229                         ret = remove_extent_backref(trans, extent_root, path,
2230                                                     refs_to_drop);
2231                         BUG_ON(ret);
2232                         btrfs_release_path(extent_root, path);
2233                         ret = btrfs_search_slot(trans, extent_root,
2234                                                 &key, path, -1, 1);
2235                         if (ret) {
2236                                 printk(KERN_ERR "umm, got %d back from search"
2237                                        ", was looking for %llu\n", ret,
2238                                        (unsigned long long)bytenr);
2239                                 btrfs_print_leaf(extent_root, path->nodes[0]);
2240                         }
2241                         BUG_ON(ret);
2242                         extent_slot = path->slots[0];
2243                 }
2244         } else {
2245                 btrfs_print_leaf(extent_root, path->nodes[0]);
2246                 WARN_ON(1);
2247                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
2248                        "parent %llu root %llu gen %llu owner %llu\n",
2249                        (unsigned long long)bytenr,
2250                        (unsigned long long)parent,
2251                        (unsigned long long)root_objectid,
2252                        (unsigned long long)ref_generation,
2253                        (unsigned long long)owner_objectid);
2254         }
2255
2256         leaf = path->nodes[0];
2257         ei = btrfs_item_ptr(leaf, extent_slot,
2258                             struct btrfs_extent_item);
2259         refs = btrfs_extent_refs(leaf, ei);
2260
2261         /*
2262          * we're not allowed to delete the extent item if there
2263          * are other delayed ref updates pending
2264          */
2265
2266         BUG_ON(refs < refs_to_drop);
2267         refs -= refs_to_drop;
2268         btrfs_set_extent_refs(leaf, ei, refs);
2269         btrfs_mark_buffer_dirty(leaf);
2270
2271         if (refs == 0 && found_extent &&
2272             path->slots[0] == extent_slot + 1) {
2273                 struct btrfs_extent_ref *ref;
2274                 ref = btrfs_item_ptr(leaf, path->slots[0],
2275                                      struct btrfs_extent_ref);
2276                 BUG_ON(btrfs_ref_num_refs(leaf, ref) != refs_to_drop);
2277                 /* if the back ref and the extent are next to each other
2278                  * they get deleted below in one shot
2279                  */
2280                 path->slots[0] = extent_slot;
2281                 num_to_del = 2;
2282         } else if (found_extent) {
2283                 /* otherwise delete the extent back ref */
2284                 ret = remove_extent_backref(trans, extent_root, path,
2285                                             refs_to_drop);
2286                 BUG_ON(ret);
2287                 /* if refs are 0, we need to setup the path for deletion */
2288                 if (refs == 0) {
2289                         btrfs_release_path(extent_root, path);
2290                         ret = btrfs_search_slot(trans, extent_root, &key, path,
2291                                                 -1, 1);
2292                         BUG_ON(ret);
2293                 }
2294         }
2295
2296         if (refs == 0) {
2297                 u64 super_used;
2298                 u64 root_used;
2299
2300                 if (pin) {
2301                         mutex_lock(&root->fs_info->pinned_mutex);
2302                         ret = pin_down_bytes(trans, root, bytenr, num_bytes,
2303                                 owner_objectid >= BTRFS_FIRST_FREE_OBJECTID);
2304                         mutex_unlock(&root->fs_info->pinned_mutex);
2305                         if (ret > 0)
2306                                 mark_free = 1;
2307                         BUG_ON(ret < 0);
2308                 }
2309                 /* block accounting for super block */
2310                 spin_lock(&info->delalloc_lock);
2311                 super_used = btrfs_super_bytes_used(&info->super_copy);
2312                 btrfs_set_super_bytes_used(&info->super_copy,
2313                                            super_used - num_bytes);
2314
2315                 /* block accounting for root item */
2316                 root_used = btrfs_root_used(&root->root_item);
2317                 btrfs_set_root_used(&root->root_item,
2318                                            root_used - num_bytes);
2319                 spin_unlock(&info->delalloc_lock);
2320                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
2321                                       num_to_del);
2322                 BUG_ON(ret);
2323                 btrfs_release_path(extent_root, path);
2324
2325                 if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
2326                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
2327                         BUG_ON(ret);
2328                 }
2329
2330                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
2331                                          mark_free);
2332                 BUG_ON(ret);
2333         }
2334         btrfs_free_path(path);
2335         return ret;
2336 }
2337
2338 /*
2339  * remove an extent from the root, returns 0 on success
2340  */
2341 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2342                                         struct btrfs_root *root,
2343                                         u64 bytenr, u64 num_bytes, u64 parent,
2344                                         u64 root_objectid, u64 ref_generation,
2345                                         u64 owner_objectid, int pin,
2346                                         int refs_to_drop)
2347 {
2348         WARN_ON(num_bytes < root->sectorsize);
2349
2350         /*
2351          * if metadata always pin
2352          * if data pin when any transaction has committed this
2353          */
2354         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID ||
2355             ref_generation != trans->transid)
2356                 pin = 1;
2357
2358         if (ref_generation != trans->transid)
2359                 pin = 1;
2360
2361         return __free_extent(trans, root, bytenr, num_bytes, parent,
2362                             root_objectid, ref_generation,
2363                             owner_objectid, pin, pin == 0, refs_to_drop);
2364 }
2365
2366 /*
2367  * when we free an extent, it is possible (and likely) that we free the last
2368  * delayed ref for that extent as well.  This searches the delayed ref tree for
2369  * a given extent, and if there are no other delayed refs to be processed, it
2370  * removes it from the tree.
2371  */
2372 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
2373                                       struct btrfs_root *root, u64 bytenr)
2374 {
2375         struct btrfs_delayed_ref_head *head;
2376         struct btrfs_delayed_ref_root *delayed_refs;
2377         struct btrfs_delayed_ref_node *ref;
2378         struct rb_node *node;
2379         int ret;
2380
2381         delayed_refs = &trans->transaction->delayed_refs;
2382         spin_lock(&delayed_refs->lock);
2383         head = btrfs_find_delayed_ref_head(trans, bytenr);
2384         if (!head)
2385                 goto out;
2386
2387         node = rb_prev(&head->node.rb_node);
2388         if (!node)
2389                 goto out;
2390
2391         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2392
2393         /* there are still entries for this ref, we can't drop it */
2394         if (ref->bytenr == bytenr)
2395                 goto out;
2396
2397         /*
2398          * waiting for the lock here would deadlock.  If someone else has it
2399          * locked they are already in the process of dropping it anyway
2400          */
2401         if (!mutex_trylock(&head->mutex))
2402                 goto out;
2403
2404         /*
2405          * at this point we have a head with no other entries.  Go
2406          * ahead and process it.
2407          */
2408         head->node.in_tree = 0;
2409         rb_erase(&head->node.rb_node, &delayed_refs->root);
2410         delayed_refs->num_entries--;
2411
2412         /*
2413          * we don't take a ref on the node because we're removing it from the
2414          * tree, so we just steal the ref the tree was holding.
2415          */
2416         spin_unlock(&delayed_refs->lock);
2417
2418         ret = run_one_delayed_ref(trans, root->fs_info->tree_root,
2419                                   &head->node, head->must_insert_reserved);
2420         BUG_ON(ret);
2421         btrfs_put_delayed_ref(&head->node);
2422         return 0;
2423 out:
2424         spin_unlock(&delayed_refs->lock);
2425         return 0;
2426 }
2427
2428 int btrfs_free_extent(struct btrfs_trans_handle *trans,
2429                       struct btrfs_root *root,
2430                       u64 bytenr, u64 num_bytes, u64 parent,
2431                       u64 root_objectid, u64 ref_generation,
2432                       u64 owner_objectid, int pin)
2433 {
2434         int ret;
2435
2436         /*
2437          * tree log blocks never actually go into the extent allocation
2438          * tree, just update pinning info and exit early.
2439          *
2440          * data extents referenced by the tree log do need to have
2441          * their reference counts bumped.
2442          */
2443         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID &&
2444             owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
2445                 mutex_lock(&root->fs_info->pinned_mutex);
2446                 btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
2447                 mutex_unlock(&root->fs_info->pinned_mutex);
2448                 update_reserved_extents(root, bytenr, num_bytes, 0);
2449                 ret = 0;
2450         } else {
2451                 ret = btrfs_add_delayed_ref(trans, bytenr, num_bytes, parent,
2452                                        root_objectid, ref_generation,
2453                                        owner_objectid,
2454                                        BTRFS_DROP_DELAYED_REF, 1);
2455                 BUG_ON(ret);
2456                 ret = check_ref_cleanup(trans, root, bytenr);
2457                 BUG_ON(ret);
2458         }
2459         return ret;
2460 }
2461
2462 static u64 stripe_align(struct btrfs_root *root, u64 val)
2463 {
2464         u64 mask = ((u64)root->stripesize - 1);
2465         u64 ret = (val + mask) & ~mask;
2466         return ret;
2467 }
2468
2469 /*
2470  * walks the btree of allocated extents and find a hole of a given size.
2471  * The key ins is changed to record the hole:
2472  * ins->objectid == block start
2473  * ins->flags = BTRFS_EXTENT_ITEM_KEY
2474  * ins->offset == number of blocks
2475  * Any available blocks before search_start are skipped.
2476  */
2477 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
2478                                      struct btrfs_root *orig_root,
2479                                      u64 num_bytes, u64 empty_size,
2480                                      u64 search_start, u64 search_end,
2481                                      u64 hint_byte, struct btrfs_key *ins,
2482                                      u64 exclude_start, u64 exclude_nr,
2483                                      int data)
2484 {
2485         int ret = 0;
2486         struct btrfs_root *root = orig_root->fs_info->extent_root;
2487         u64 total_needed = num_bytes;
2488         u64 *last_ptr = NULL;
2489         u64 last_wanted = 0;
2490         struct btrfs_block_group_cache *block_group = NULL;
2491         int chunk_alloc_done = 0;
2492         int empty_cluster = 2 * 1024 * 1024;
2493         int allowed_chunk_alloc = 0;
2494         struct list_head *head = NULL, *cur = NULL;
2495         int loop = 0;
2496         int extra_loop = 0;
2497         struct btrfs_space_info *space_info;
2498
2499         WARN_ON(num_bytes < root->sectorsize);
2500         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
2501         ins->objectid = 0;
2502         ins->offset = 0;
2503
2504         if (orig_root->ref_cows || empty_size)
2505                 allowed_chunk_alloc = 1;
2506
2507         if (data & BTRFS_BLOCK_GROUP_METADATA) {
2508                 last_ptr = &root->fs_info->last_alloc;
2509                 if (!btrfs_test_opt(root, SSD))
2510                         empty_cluster = 64 * 1024;
2511         }
2512
2513         if ((data & BTRFS_BLOCK_GROUP_DATA) && btrfs_test_opt(root, SSD))
2514                 last_ptr = &root->fs_info->last_data_alloc;
2515
2516         if (last_ptr) {
2517                 if (*last_ptr) {
2518                         hint_byte = *last_ptr;
2519                         last_wanted = *last_ptr;
2520                 } else
2521                         empty_size += empty_cluster;
2522         } else {
2523                 empty_cluster = 0;
2524         }
2525         search_start = max(search_start, first_logical_byte(root, 0));
2526         search_start = max(search_start, hint_byte);
2527
2528         if (last_wanted && search_start != last_wanted) {
2529                 last_wanted = 0;
2530                 empty_size += empty_cluster;
2531         }
2532
2533         total_needed += empty_size;
2534         block_group = btrfs_lookup_block_group(root->fs_info, search_start);
2535         if (!block_group)
2536                 block_group = btrfs_lookup_first_block_group(root->fs_info,
2537                                                              search_start);
2538         space_info = __find_space_info(root->fs_info, data);
2539
2540         down_read(&space_info->groups_sem);
2541         while (1) {
2542                 struct btrfs_free_space *free_space;
2543                 /*
2544                  * the only way this happens if our hint points to a block
2545                  * group thats not of the proper type, while looping this
2546                  * should never happen
2547                  */
2548                 if (empty_size)
2549                         extra_loop = 1;
2550
2551                 if (!block_group)
2552                         goto new_group_no_lock;
2553
2554                 if (unlikely(!block_group->cached)) {
2555                         mutex_lock(&block_group->cache_mutex);
2556                         ret = cache_block_group(root, block_group);
2557                         mutex_unlock(&block_group->cache_mutex);
2558                         if (ret)
2559                                 break;
2560                 }
2561
2562                 mutex_lock(&block_group->alloc_mutex);
2563                 if (unlikely(!block_group_bits(block_group, data)))
2564                         goto new_group;
2565
2566                 if (unlikely(block_group->ro))
2567                         goto new_group;
2568
2569                 free_space = btrfs_find_free_space(block_group, search_start,
2570                                                    total_needed);
2571                 if (free_space) {
2572                         u64 start = block_group->key.objectid;
2573                         u64 end = block_group->key.objectid +
2574                                 block_group->key.offset;
2575
2576                         search_start = stripe_align(root, free_space->offset);
2577
2578                         /* move on to the next group */
2579                         if (search_start + num_bytes >= search_end)
2580                                 goto new_group;
2581
2582                         /* move on to the next group */
2583                         if (search_start + num_bytes > end)
2584                                 goto new_group;
2585
2586                         if (last_wanted && search_start != last_wanted) {
2587                                 total_needed += empty_cluster;
2588                                 empty_size += empty_cluster;
2589                                 last_wanted = 0;
2590                                 /*
2591                                  * if search_start is still in this block group
2592                                  * then we just re-search this block group
2593                                  */
2594                                 if (search_start >= start &&
2595                                     search_start < end) {
2596                                         mutex_unlock(&block_group->alloc_mutex);
2597                                         continue;
2598                                 }
2599
2600                                 /* else we go to the next block group */
2601                                 goto new_group;
2602                         }
2603
2604                         if (exclude_nr > 0 &&
2605                             (search_start + num_bytes > exclude_start &&
2606                              search_start < exclude_start + exclude_nr)) {
2607                                 search_start = exclude_start + exclude_nr;
2608                                 /*
2609                                  * if search_start is still in this block group
2610                                  * then we just re-search this block group
2611                                  */
2612                                 if (search_start >= start &&
2613                                     search_start < end) {
2614                                         mutex_unlock(&block_group->alloc_mutex);
2615                                         last_wanted = 0;
2616                                         continue;
2617                                 }
2618
2619                                 /* else we go to the next block group */
2620                                 goto new_group;
2621                         }
2622
2623                         ins->objectid = search_start;
2624                         ins->offset = num_bytes;
2625
2626                         btrfs_remove_free_space_lock(block_group, search_start,
2627                                                      num_bytes);
2628                         /* we are all good, lets return */
2629                         mutex_unlock(&block_group->alloc_mutex);
2630                         break;
2631                 }
2632 new_group:
2633                 mutex_unlock(&block_group->alloc_mutex);
2634                 put_block_group(block_group);
2635                 block_group = NULL;
2636 new_group_no_lock:
2637                 /* don't try to compare new allocations against the
2638                  * last allocation any more
2639                  */
2640                 last_wanted = 0;
2641
2642                 /*
2643                  * Here's how this works.
2644                  * loop == 0: we were searching a block group via a hint
2645                  *              and didn't find anything, so we start at
2646                  *              the head of the block groups and keep searching
2647                  * loop == 1: we're searching through all of the block groups
2648                  *              if we hit the head again we have searched
2649                  *              all of the block groups for this space and we
2650                  *              need to try and allocate, if we cant error out.
2651                  * loop == 2: we allocated more space and are looping through
2652                  *              all of the block groups again.
2653                  */
2654                 if (loop == 0) {
2655                         head = &space_info->block_groups;
2656                         cur = head->next;
2657                         loop++;
2658                 } else if (loop == 1 && cur == head) {
2659                         int keep_going;
2660
2661                         /* at this point we give up on the empty_size
2662                          * allocations and just try to allocate the min
2663                          * space.
2664                          *
2665                          * The extra_loop field was set if an empty_size
2666                          * allocation was attempted above, and if this
2667                          * is try we need to try the loop again without
2668                          * the additional empty_size.
2669                          */
2670                         total_needed -= empty_size;
2671                         empty_size = 0;
2672                         keep_going = extra_loop;
2673                         loop++;
2674
2675                         if (allowed_chunk_alloc && !chunk_alloc_done) {
2676                                 up_read(&space_info->groups_sem);
2677                                 ret = do_chunk_alloc(trans, root, num_bytes +
2678                                                      2 * 1024 * 1024, data, 1);
2679                                 down_read(&space_info->groups_sem);
2680                                 if (ret < 0)
2681                                         goto loop_check;
2682                                 head = &space_info->block_groups;
2683                                 /*
2684                                  * we've allocated a new chunk, keep
2685                                  * trying
2686                                  */
2687                                 keep_going = 1;
2688                                 chunk_alloc_done = 1;
2689                         } else if (!allowed_chunk_alloc) {
2690                                 space_info->force_alloc = 1;
2691                         }
2692 loop_check:
2693                         if (keep_going) {
2694                                 cur = head->next;
2695                                 extra_loop = 0;
2696                         } else {
2697                                 break;
2698                         }
2699                 } else if (cur == head) {
2700                         break;
2701                 }
2702
2703                 block_group = list_entry(cur, struct btrfs_block_group_cache,
2704                                          list);
2705                 atomic_inc(&block_group->count);
2706
2707                 search_start = block_group->key.objectid;
2708                 cur = cur->next;
2709         }
2710
2711         /* we found what we needed */
2712         if (ins->objectid) {
2713                 if (!(data & BTRFS_BLOCK_GROUP_DATA))
2714                         trans->block_group = block_group->key.objectid;
2715
2716                 if (last_ptr)
2717                         *last_ptr = ins->objectid + ins->offset;
2718                 ret = 0;
2719         } else if (!ret) {
2720                 printk(KERN_ERR "btrfs searching for %llu bytes, "
2721                        "num_bytes %llu, loop %d, allowed_alloc %d\n",
2722                        (unsigned long long)total_needed,
2723                        (unsigned long long)num_bytes,
2724                        loop, allowed_chunk_alloc);
2725                 ret = -ENOSPC;
2726         }
2727         if (block_group)
2728                 put_block_group(block_group);
2729
2730         up_read(&space_info->groups_sem);
2731         return ret;
2732 }
2733
2734 static void dump_space_info(struct btrfs_space_info *info, u64 bytes)
2735 {
2736         struct btrfs_block_group_cache *cache;
2737
2738         printk(KERN_INFO "space_info has %llu free, is %sfull\n",
2739                (unsigned long long)(info->total_bytes - info->bytes_used -
2740                                     info->bytes_pinned - info->bytes_reserved),
2741                (info->full) ? "" : "not ");
2742         printk(KERN_INFO "space_info total=%llu, pinned=%llu, delalloc=%llu,"
2743                " may_use=%llu, used=%llu\n", info->total_bytes,
2744                info->bytes_pinned, info->bytes_delalloc, info->bytes_may_use,
2745                info->bytes_used);
2746
2747         down_read(&info->groups_sem);
2748         list_for_each_entry(cache, &info->block_groups, list) {
2749                 spin_lock(&cache->lock);
2750                 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
2751                        "%llu pinned %llu reserved\n",
2752                        (unsigned long long)cache->key.objectid,
2753                        (unsigned long long)cache->key.offset,
2754                        (unsigned long long)btrfs_block_group_used(&cache->item),
2755                        (unsigned long long)cache->pinned,
2756                        (unsigned long long)cache->reserved);
2757                 btrfs_dump_free_space(cache, bytes);
2758                 spin_unlock(&cache->lock);
2759         }
2760         up_read(&info->groups_sem);
2761 }
2762
2763 static int __btrfs_reserve_extent(struct btrfs_trans_handle *trans,
2764                                   struct btrfs_root *root,
2765                                   u64 num_bytes, u64 min_alloc_size,
2766                                   u64 empty_size, u64 hint_byte,
2767                                   u64 search_end, struct btrfs_key *ins,
2768                                   u64 data)
2769 {
2770         int ret;
2771         u64 search_start = 0;
2772         struct btrfs_fs_info *info = root->fs_info;
2773
2774         data = btrfs_get_alloc_profile(root, data);
2775 again:
2776         /*
2777          * the only place that sets empty_size is btrfs_realloc_node, which
2778          * is not called recursively on allocations
2779          */
2780         if (empty_size || root->ref_cows) {
2781                 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
2782                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2783                                      2 * 1024 * 1024,
2784                                      BTRFS_BLOCK_GROUP_METADATA |
2785                                      (info->metadata_alloc_profile &
2786                                       info->avail_metadata_alloc_bits), 0);
2787                 }
2788                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2789                                      num_bytes + 2 * 1024 * 1024, data, 0);
2790         }
2791
2792         WARN_ON(num_bytes < root->sectorsize);
2793         ret = find_free_extent(trans, root, num_bytes, empty_size,
2794                                search_start, search_end, hint_byte, ins,
2795                                trans->alloc_exclude_start,
2796                                trans->alloc_exclude_nr, data);
2797
2798         if (ret == -ENOSPC && num_bytes > min_alloc_size) {
2799                 num_bytes = num_bytes >> 1;
2800                 num_bytes = num_bytes & ~(root->sectorsize - 1);
2801                 num_bytes = max(num_bytes, min_alloc_size);
2802                 do_chunk_alloc(trans, root->fs_info->extent_root,
2803                                num_bytes, data, 1);
2804                 goto again;
2805         }
2806         if (ret) {
2807                 struct btrfs_space_info *sinfo;
2808
2809                 sinfo = __find_space_info(root->fs_info, data);
2810                 printk(KERN_ERR "btrfs allocation failed flags %llu, "
2811                        "wanted %llu\n", (unsigned long long)data,
2812                        (unsigned long long)num_bytes);
2813                 dump_space_info(sinfo, num_bytes);
2814                 BUG();
2815         }
2816
2817         return ret;
2818 }
2819
2820 int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
2821 {
2822         struct btrfs_block_group_cache *cache;
2823         int ret = 0;
2824
2825         cache = btrfs_lookup_block_group(root->fs_info, start);
2826         if (!cache) {
2827                 printk(KERN_ERR "Unable to find block group for %llu\n",
2828                        (unsigned long long)start);
2829                 return -ENOSPC;
2830         }
2831
2832         ret = btrfs_discard_extent(root, start, len);
2833
2834         btrfs_add_free_space(cache, start, len);
2835         put_block_group(cache);
2836         update_reserved_extents(root, start, len, 0);
2837
2838         return ret;
2839 }
2840
2841 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
2842                                   struct btrfs_root *root,
2843                                   u64 num_bytes, u64 min_alloc_size,
2844                                   u64 empty_size, u64 hint_byte,
2845                                   u64 search_end, struct btrfs_key *ins,
2846                                   u64 data)
2847 {
2848         int ret;
2849         ret = __btrfs_reserve_extent(trans, root, num_bytes, min_alloc_size,
2850                                      empty_size, hint_byte, search_end, ins,
2851                                      data);
2852         update_reserved_extents(root, ins->objectid, ins->offset, 1);
2853         return ret;
2854 }
2855
2856 static int __btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
2857                                          struct btrfs_root *root, u64 parent,
2858                                          u64 root_objectid, u64 ref_generation,
2859                                          u64 owner, struct btrfs_key *ins,
2860                                          int ref_mod)
2861 {
2862         int ret;
2863         u64 super_used;
2864         u64 root_used;
2865         u64 num_bytes = ins->offset;
2866         u32 sizes[2];
2867         struct btrfs_fs_info *info = root->fs_info;
2868         struct btrfs_root *extent_root = info->extent_root;
2869         struct btrfs_extent_item *extent_item;
2870         struct btrfs_extent_ref *ref;
2871         struct btrfs_path *path;
2872         struct btrfs_key keys[2];
2873
2874         if (parent == 0)
2875                 parent = ins->objectid;
2876
2877         /* block accounting for super block */
2878         spin_lock(&info->delalloc_lock);
2879         super_used = btrfs_super_bytes_used(&info->super_copy);
2880         btrfs_set_super_bytes_used(&info->super_copy, super_used + num_bytes);
2881
2882         /* block accounting for root item */
2883         root_used = btrfs_root_used(&root->root_item);
2884         btrfs_set_root_used(&root->root_item, root_used + num_bytes);
2885         spin_unlock(&info->delalloc_lock);
2886
2887         memcpy(&keys[0], ins, sizeof(*ins));
2888         keys[1].objectid = ins->objectid;
2889         keys[1].type = BTRFS_EXTENT_REF_KEY;
2890         keys[1].offset = parent;
2891         sizes[0] = sizeof(*extent_item);
2892         sizes[1] = sizeof(*ref);
2893
2894         path = btrfs_alloc_path();
2895         BUG_ON(!path);
2896
2897         ret = btrfs_insert_empty_items(trans, extent_root, path, keys,
2898                                        sizes, 2);
2899         BUG_ON(ret);
2900
2901         extent_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2902                                      struct btrfs_extent_item);
2903         btrfs_set_extent_refs(path->nodes[0], extent_item, ref_mod);
2904         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
2905                              struct btrfs_extent_ref);
2906
2907         btrfs_set_ref_root(path->nodes[0], ref, root_objectid);
2908         btrfs_set_ref_generation(path->nodes[0], ref, ref_generation);
2909         btrfs_set_ref_objectid(path->nodes[0], ref, owner);
2910         btrfs_set_ref_num_refs(path->nodes[0], ref, ref_mod);
2911
2912         btrfs_mark_buffer_dirty(path->nodes[0]);
2913
2914         trans->alloc_exclude_start = 0;
2915         trans->alloc_exclude_nr = 0;
2916         btrfs_free_path(path);
2917
2918         if (ret)
2919                 goto out;
2920
2921         ret = update_block_group(trans, root, ins->objectid,
2922                                  ins->offset, 1, 0);
2923         if (ret) {
2924                 printk(KERN_ERR "btrfs update block group failed for %llu "
2925                        "%llu\n", (unsigned long long)ins->objectid,
2926                        (unsigned long long)ins->offset);
2927                 BUG();
2928         }
2929 out:
2930         return ret;
2931 }
2932
2933 int btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
2934                                 struct btrfs_root *root, u64 parent,
2935                                 u64 root_objectid, u64 ref_generation,
2936                                 u64 owner, struct btrfs_key *ins)
2937 {
2938         int ret;
2939
2940         if (root_objectid == BTRFS_TREE_LOG_OBJECTID)
2941                 return 0;
2942
2943         ret = btrfs_add_delayed_ref(trans, ins->objectid,
2944                                     ins->offset, parent, root_objectid,
2945                                     ref_generation, owner,
2946                                     BTRFS_ADD_DELAYED_EXTENT, 0);
2947         BUG_ON(ret);
2948         return ret;
2949 }
2950
2951 /*
2952  * this is used by the tree logging recovery code.  It records that
2953  * an extent has been allocated and makes sure to clear the free
2954  * space cache bits as well
2955  */
2956 int btrfs_alloc_logged_extent(struct btrfs_trans_handle *trans,
2957                                 struct btrfs_root *root, u64 parent,
2958                                 u64 root_objectid, u64 ref_generation,
2959                                 u64 owner, struct btrfs_key *ins)
2960 {
2961         int ret;
2962         struct btrfs_block_group_cache *block_group;
2963
2964         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
2965         mutex_lock(&block_group->cache_mutex);
2966         cache_block_group(root, block_group);
2967         mutex_unlock(&block_group->cache_mutex);
2968
2969         ret = btrfs_remove_free_space(block_group, ins->objectid,
2970                                       ins->offset);
2971         BUG_ON(ret);
2972         put_block_group(block_group);
2973         ret = __btrfs_alloc_reserved_extent(trans, root, parent, root_objectid,
2974                                             ref_generation, owner, ins, 1);
2975         return ret;
2976 }
2977
2978 /*
2979  * finds a free extent and does all the dirty work required for allocation
2980  * returns the key for the extent through ins, and a tree buffer for
2981  * the first block of the extent through buf.
2982  *
2983  * returns 0 if everything worked, non-zero otherwise.
2984  */
2985 int btrfs_alloc_extent(struct btrfs_trans_handle *trans,
2986                        struct btrfs_root *root,
2987                        u64 num_bytes, u64 parent, u64 min_alloc_size,
2988                        u64 root_objectid, u64 ref_generation,
2989                        u64 owner_objectid, u64 empty_size, u64 hint_byte,
2990                        u64 search_end, struct btrfs_key *ins, u64 data)
2991 {
2992         int ret;
2993         ret = __btrfs_reserve_extent(trans, root, num_bytes,
2994                                      min_alloc_size, empty_size, hint_byte,
2995                                      search_end, ins, data);
2996         BUG_ON(ret);
2997         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
2998                 ret = btrfs_add_delayed_ref(trans, ins->objectid,
2999                                             ins->offset, parent, root_objectid,
3000                                             ref_generation, owner_objectid,
3001                                             BTRFS_ADD_DELAYED_EXTENT, 0);
3002                 BUG_ON(ret);
3003         }
3004         update_reserved_extents(root, ins->objectid, ins->offset, 1);
3005         return ret;
3006 }
3007
3008 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
3009                                             struct btrfs_root *root,
3010                                             u64 bytenr, u32 blocksize,
3011                                             int level)
3012 {
3013         struct extent_buffer *buf;
3014
3015         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
3016         if (!buf)
3017                 return ERR_PTR(-ENOMEM);
3018         btrfs_set_header_generation(buf, trans->transid);
3019         btrfs_set_buffer_lockdep_class(buf, level);
3020         btrfs_tree_lock(buf);
3021         clean_tree_block(trans, root, buf);
3022
3023         btrfs_set_lock_blocking(buf);
3024         btrfs_set_buffer_uptodate(buf);
3025
3026         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
3027                 set_extent_dirty(&root->dirty_log_pages, buf->start,
3028                          buf->start + buf->len - 1, GFP_NOFS);
3029         } else {
3030                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
3031                          buf->start + buf->len - 1, GFP_NOFS);
3032         }
3033         trans->blocks_used++;
3034         /* this returns a buffer locked for blocking */
3035         return buf;
3036 }
3037
3038 /*
3039  * helper function to allocate a block for a given tree
3040  * returns the tree buffer or NULL.
3041  */
3042 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
3043                                              struct btrfs_root *root,
3044                                              u32 blocksize, u64 parent,
3045                                              u64 root_objectid,
3046                                              u64 ref_generation,
3047                                              int level,
3048                                              u64 hint,
3049                                              u64 empty_size)
3050 {
3051         struct btrfs_key ins;
3052         int ret;
3053         struct extent_buffer *buf;
3054
3055         ret = btrfs_alloc_extent(trans, root, blocksize, parent, blocksize,
3056                                  root_objectid, ref_generation, level,
3057                                  empty_size, hint, (u64)-1, &ins, 0);
3058         if (ret) {
3059                 BUG_ON(ret > 0);
3060                 return ERR_PTR(ret);
3061         }
3062
3063         buf = btrfs_init_new_buffer(trans, root, ins.objectid,
3064                                     blocksize, level);
3065         return buf;
3066 }
3067
3068 int btrfs_drop_leaf_ref(struct btrfs_trans_handle *trans,
3069                         struct btrfs_root *root, struct extent_buffer *leaf)
3070 {
3071         u64 leaf_owner;
3072         u64 leaf_generation;
3073         struct refsort *sorted;
3074         struct btrfs_key key;
3075         struct btrfs_file_extent_item *fi;
3076         int i;
3077         int nritems;
3078         int ret;
3079         int refi = 0;
3080         int slot;
3081
3082         BUG_ON(!btrfs_is_leaf(leaf));
3083         nritems = btrfs_header_nritems(leaf);
3084         leaf_owner = btrfs_header_owner(leaf);
3085         leaf_generation = btrfs_header_generation(leaf);
3086
3087         sorted = kmalloc(sizeof(*sorted) * nritems, GFP_NOFS);
3088         /* we do this loop twice.  The first time we build a list
3089          * of the extents we have a reference on, then we sort the list
3090          * by bytenr.  The second time around we actually do the
3091          * extent freeing.
3092          */
3093         for (i = 0; i < nritems; i++) {
3094                 u64 disk_bytenr;
3095                 cond_resched();
3096
3097                 btrfs_item_key_to_cpu(leaf, &key, i);
3098
3099                 /* only extents have references, skip everything else */
3100                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3101                         continue;
3102
3103                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
3104
3105                 /* inline extents live in the btree, they don't have refs */
3106                 if (btrfs_file_extent_type(leaf, fi) ==
3107                     BTRFS_FILE_EXTENT_INLINE)
3108                         continue;
3109
3110                 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
3111
3112                 /* holes don't have refs */
3113                 if (disk_bytenr == 0)
3114                         continue;
3115
3116                 sorted[refi].bytenr = disk_bytenr;
3117                 sorted[refi].slot = i;
3118                 refi++;
3119         }
3120
3121         if (refi == 0)
3122                 goto out;
3123
3124         sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
3125
3126         for (i = 0; i < refi; i++) {
3127                 u64 disk_bytenr;
3128
3129                 disk_bytenr = sorted[i].bytenr;
3130                 slot = sorted[i].slot;
3131
3132                 cond_resched();
3133
3134                 btrfs_item_key_to_cpu(leaf, &key, slot);
3135                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3136                         continue;
3137
3138                 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
3139
3140                 ret = btrfs_free_extent(trans, root, disk_bytenr,
3141                                 btrfs_file_extent_disk_num_bytes(leaf, fi),
3142                                 leaf->start, leaf_owner, leaf_generation,
3143                                 key.objectid, 0);
3144                 BUG_ON(ret);
3145
3146                 atomic_inc(&root->fs_info->throttle_gen);
3147                 wake_up(&root->fs_info->transaction_throttle);
3148                 cond_resched();
3149         }
3150 out:
3151         kfree(sorted);
3152         return 0;
3153 }
3154
3155 static noinline int cache_drop_leaf_ref(struct btrfs_trans_handle *trans,
3156                                         struct btrfs_root *root,
3157                                         struct btrfs_leaf_ref *ref)
3158 {
3159         int i;
3160         int ret;
3161         struct btrfs_extent_info *info;
3162         struct refsort *sorted;
3163
3164         if (ref->nritems == 0)
3165                 return 0;
3166
3167         sorted = kmalloc(sizeof(*sorted) * ref->nritems, GFP_NOFS);
3168         for (i = 0; i < ref->nritems; i++) {
3169                 sorted[i].bytenr = ref->extents[i].bytenr;
3170                 sorted[i].slot = i;
3171         }
3172         sort(sorted, ref->nritems, sizeof(struct refsort), refsort_cmp, NULL);
3173
3174         /*
3175          * the items in the ref were sorted when the ref was inserted
3176          * into the ref cache, so this is already in order
3177          */
3178         for (i = 0; i < ref->nritems; i++) {
3179                 info = ref->extents + sorted[i].slot;
3180                 ret = btrfs_free_extent(trans, root, info->bytenr,
3181                                           info->num_bytes, ref->bytenr,
3182                                           ref->owner, ref->generation,
3183                                           info->objectid, 0);
3184
3185                 atomic_inc(&root->fs_info->throttle_gen);
3186                 wake_up(&root->fs_info->transaction_throttle);
3187                 cond_resched();
3188
3189                 BUG_ON(ret);
3190                 info++;
3191         }
3192
3193         kfree(sorted);
3194         return 0;
3195 }
3196
3197 static int drop_snap_lookup_refcount(struct btrfs_trans_handle *trans,
3198                                      struct btrfs_root *root, u64 start,
3199                                      u64 len, u32 *refs)
3200 {
3201         int ret;
3202
3203         ret = btrfs_lookup_extent_ref(trans, root, start, len, refs);
3204         BUG_ON(ret);
3205
3206 #if 0 /* some debugging code in case we see problems here */
3207         /* if the refs count is one, it won't get increased again.  But
3208          * if the ref count is > 1, someone may be decreasing it at
3209          * the same time we are.
3210          */
3211         if (*refs != 1) {
3212                 struct extent_buffer *eb = NULL;
3213                 eb = btrfs_find_create_tree_block(root, start, len);
3214                 if (eb)
3215                         btrfs_tree_lock(eb);
3216
3217                 mutex_lock(&root->fs_info->alloc_mutex);
3218                 ret = lookup_extent_ref(NULL, root, start, len, refs);
3219                 BUG_ON(ret);
3220                 mutex_unlock(&root->fs_info->alloc_mutex);
3221
3222                 if (eb) {
3223                         btrfs_tree_unlock(eb);
3224                         free_extent_buffer(eb);
3225                 }
3226                 if (*refs == 1) {
3227                         printk(KERN_ERR "btrfs block %llu went down to one "
3228                                "during drop_snap\n", (unsigned long long)start);
3229                 }
3230
3231         }
3232 #endif
3233
3234         cond_resched();
3235         return ret;
3236 }
3237
3238 /*
3239  * this is used while deleting old snapshots, and it drops the refs
3240  * on a whole subtree starting from a level 1 node.
3241  *
3242  * The idea is to sort all the leaf pointers, and then drop the
3243  * ref on all the leaves in order.  Most of the time the leaves
3244  * will have ref cache entries, so no leaf IOs will be required to
3245  * find the extents they have references on.
3246  *
3247  * For each leaf, any references it has are also dropped in order
3248  *
3249  * This ends up dropping the references in something close to optimal
3250  * order for reading and modifying the extent allocation tree.
3251  */
3252 static noinline int drop_level_one_refs(struct btrfs_trans_handle *trans,
3253                                         struct btrfs_root *root,
3254                                         struct btrfs_path *path)
3255 {
3256         u64 bytenr;
3257         u64 root_owner;
3258         u64 root_gen;
3259         struct extent_buffer *eb = path->nodes[1];
3260         struct extent_buffer *leaf;
3261         struct btrfs_leaf_ref *ref;
3262         struct refsort *sorted = NULL;
3263         int nritems = btrfs_header_nritems(eb);
3264         int ret;
3265         int i;
3266         int refi = 0;
3267         int slot = path->slots[1];
3268         u32 blocksize = btrfs_level_size(root, 0);
3269         u32 refs;
3270
3271         if (nritems == 0)
3272                 goto out;
3273
3274         root_owner = btrfs_header_owner(eb);
3275         root_gen = btrfs_header_generation(eb);
3276         sorted = kmalloc(sizeof(*sorted) * nritems, GFP_NOFS);
3277
3278         /*
3279          * step one, sort all the leaf pointers so we don't scribble
3280          * randomly into the extent allocation tree
3281          */
3282         for (i = slot; i < nritems; i++) {
3283                 sorted[refi].bytenr = btrfs_node_blockptr(eb, i);
3284                 sorted[refi].slot = i;
3285                 refi++;
3286         }
3287
3288         /*
3289          * nritems won't be zero, but if we're picking up drop_snapshot
3290          * after a crash, slot might be > 0, so double check things
3291          * just in case.
3292          */
3293         if (refi == 0)
3294                 goto out;
3295
3296         sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
3297
3298         /*
3299          * the first loop frees everything the leaves point to
3300          */
3301         for (i = 0; i < refi; i++) {
3302                 u64 ptr_gen;
3303
3304                 bytenr = sorted[i].bytenr;
3305
3306                 /*
3307                  * check the reference count on this leaf.  If it is > 1
3308                  * we just decrement it below and don't update any
3309                  * of the refs the leaf points to.
3310                  */
3311                 ret = drop_snap_lookup_refcount(trans, root, bytenr,
3312                                                 blocksize, &refs);
3313                 BUG_ON(ret);
3314                 if (refs != 1)
3315                         continue;
3316
3317                 ptr_gen = btrfs_node_ptr_generation(eb, sorted[i].slot);
3318
3319                 /*
3320                  * the leaf only had one reference, which means the
3321                  * only thing pointing to this leaf is the snapshot
3322                  * we're deleting.  It isn't possible for the reference
3323                  * count to increase again later
3324                  *
3325                  * The reference cache is checked for the leaf,
3326                  * and if found we'll be able to drop any refs held by
3327                  * the leaf without needing to read it in.
3328                  */
3329                 ref = btrfs_lookup_leaf_ref(root, bytenr);
3330                 if (ref && ref->generation != ptr_gen) {
3331                         btrfs_free_leaf_ref(root, ref);
3332                         ref = NULL;
3333                 }
3334                 if (ref) {
3335                         ret = cache_drop_leaf_ref(trans, root, ref);
3336                         BUG_ON(ret);
3337                         btrfs_remove_leaf_ref(root, ref);
3338                         btrfs_free_leaf_ref(root, ref);
3339                 } else {
3340                         /*
3341                          * the leaf wasn't in the reference cache, so
3342                          * we have to read it.
3343                          */
3344                         leaf = read_tree_block(root, bytenr, blocksize,
3345                                                ptr_gen);
3346                         ret = btrfs_drop_leaf_ref(trans, root, leaf);
3347                         BUG_ON(ret);
3348                         free_extent_buffer(leaf);
3349                 }
3350                 atomic_inc(&root->fs_info->throttle_gen);
3351                 wake_up(&root->fs_info->transaction_throttle);
3352                 cond_resched();
3353         }
3354
3355         /*
3356          * run through the loop again to free the refs on the leaves.
3357          * This is faster than doing it in the loop above because
3358          * the leaves are likely to be clustered together.  We end up
3359          * working in nice chunks on the extent allocation tree.
3360          */
3361         for (i = 0; i < refi; i++) {
3362                 bytenr = sorted[i].bytenr;
3363                 ret = btrfs_free_extent(trans, root, bytenr,
3364                                         blocksize, eb->start,
3365                                         root_owner, root_gen, 0, 1);
3366                 BUG_ON(ret);
3367
3368                 atomic_inc(&root->fs_info->throttle_gen);
3369                 wake_up(&root->fs_info->transaction_throttle);
3370                 cond_resched();
3371         }
3372 out:
3373         kfree(sorted);
3374
3375         /*
3376          * update the path to show we've processed the entire level 1
3377          * node.  This will get saved into the root's drop_snapshot_progress
3378          * field so these drops are not repeated again if this transaction
3379          * commits.
3380          */
3381         path->slots[1] = nritems;
3382         return 0;
3383 }
3384
3385 /*
3386  * helper function for drop_snapshot, this walks down the tree dropping ref
3387  * counts as it goes.
3388  */
3389 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
3390                                    struct btrfs_root *root,
3391                                    struct btrfs_path *path, int *level)
3392 {
3393         u64 root_owner;
3394         u64 root_gen;
3395         u64 bytenr;
3396         u64 ptr_gen;
3397         struct extent_buffer *next;
3398         struct extent_buffer *cur;
3399         struct extent_buffer *parent;
3400         u32 blocksize;
3401         int ret;
3402         u32 refs;
3403
3404         WARN_ON(*level < 0);
3405         WARN_ON(*level >= BTRFS_MAX_LEVEL);
3406         ret = drop_snap_lookup_refcount(trans, root, path->nodes[*level]->start,
3407                                 path->nodes[*level]->len, &refs);
3408         BUG_ON(ret);
3409         if (refs > 1)
3410                 goto out;
3411
3412         /*
3413          * walk down to the last node level and free all the leaves
3414          */
3415         while (*level >= 0) {
3416                 WARN_ON(*level < 0);
3417                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
3418                 cur = path->nodes[*level];
3419
3420                 if (btrfs_header_level(cur) != *level)
3421                         WARN_ON(1);
3422
3423                 if (path->slots[*level] >=
3424                     btrfs_header_nritems(cur))
3425                         break;
3426
3427                 /* the new code goes down to level 1 and does all the
3428                  * leaves pointed to that node in bulk.  So, this check
3429                  * for level 0 will always be false.
3430                  *
3431                  * But, the disk format allows the drop_snapshot_progress
3432                  * field in the root to leave things in a state where
3433                  * a leaf will need cleaning up here.  If someone crashes
3434                  * with the old code and then boots with the new code,
3435                  * we might find a leaf here.
3436                  */
3437                 if (*level == 0) {
3438                         ret = btrfs_drop_leaf_ref(trans, root, cur);
3439                         BUG_ON(ret);
3440                         break;
3441                 }
3442
3443                 /*
3444                  * once we get to level one, process the whole node
3445                  * at once, including everything below it.
3446                  */
3447                 if (*level == 1) {
3448                         ret = drop_level_one_refs(trans, root, path);
3449                         BUG_ON(ret);
3450                         break;
3451                 }
3452
3453                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
3454                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
3455                 blocksize = btrfs_level_size(root, *level - 1);
3456
3457                 ret = drop_snap_lookup_refcount(trans, root, bytenr,
3458                                                 blocksize, &refs);
3459                 BUG_ON(ret);
3460
3461                 /*
3462                  * if there is more than one reference, we don't need
3463                  * to read that node to drop any references it has.  We
3464                  * just drop the ref we hold on that node and move on to the
3465                  * next slot in this level.
3466                  */
3467                 if (refs != 1) {
3468                         parent = path->nodes[*level];
3469                         root_owner = btrfs_header_owner(parent);
3470                         root_gen = btrfs_header_generation(parent);
3471                         path->slots[*level]++;
3472
3473                         ret = btrfs_free_extent(trans, root, bytenr,
3474                                                 blocksize, parent->start,
3475                                                 root_owner, root_gen,
3476                                                 *level - 1, 1);
3477                         BUG_ON(ret);
3478
3479                         atomic_inc(&root->fs_info->throttle_gen);
3480                         wake_up(&root->fs_info->transaction_throttle);
3481                         cond_resched();
3482
3483                         continue;
3484                 }
3485
3486                 /*
3487                  * we need to keep freeing things in the next level down.
3488                  * read the block and loop around to process it
3489                  */
3490                 next = read_tree_block(root, bytenr, blocksize, ptr_gen);
3491                 WARN_ON(*level <= 0);
3492                 if (path->nodes[*level-1])
3493                         free_extent_buffer(path->nodes[*level-1]);
3494                 path->nodes[*level-1] = next;
3495                 *level = btrfs_header_level(next);
3496                 path->slots[*level] = 0;
3497                 cond_resched();
3498         }
3499 out:
3500         WARN_ON(*level < 0);
3501         WARN_ON(*level >= BTRFS_MAX_LEVEL);
3502
3503         if (path->nodes[*level] == root->node) {
3504                 parent = path->nodes[*level];
3505                 bytenr = path->nodes[*level]->start;
3506         } else {
3507                 parent = path->nodes[*level + 1];
3508                 bytenr = btrfs_node_blockptr(parent, path->slots[*level + 1]);
3509         }
3510
3511         blocksize = btrfs_level_size(root, *level);
3512         root_owner = btrfs_header_owner(parent);
3513         root_gen = btrfs_header_generation(parent);
3514
3515         /*
3516          * cleanup and free the reference on the last node
3517          * we processed
3518          */
3519         ret = btrfs_free_extent(trans, root, bytenr, blocksize,
3520                                   parent->start, root_owner, root_gen,
3521                                   *level, 1);
3522         free_extent_buffer(path->nodes[*level]);
3523         path->nodes[*level] = NULL;
3524
3525         *level += 1;
3526         BUG_ON(ret);
3527
3528         cond_resched();
3529         return 0;
3530 }
3531
3532 /*
3533  * helper function for drop_subtree, this function is similar to
3534  * walk_down_tree. The main difference is that it checks reference
3535  * counts while tree blocks are locked.
3536  */
3537 static noinline int walk_down_subtree(struct btrfs_trans_handle *trans,
3538                                       struct btrfs_root *root,
3539                                       struct btrfs_path *path, int *level)
3540 {
3541         struct extent_buffer *next;
3542         struct extent_buffer *cur;
3543         struct extent_buffer *parent;
3544         u64 bytenr;
3545         u64 ptr_gen;
3546         u32 blocksize;
3547         u32 refs;
3548         int ret;
3549
3550         cur = path->nodes[*level];
3551         ret = btrfs_lookup_extent_ref(trans, root, cur->start, cur->len,
3552                                       &refs);
3553         BUG_ON(ret);
3554         if (refs > 1)
3555                 goto out;
3556
3557         while (*level >= 0) {
3558                 cur = path->nodes[*level];
3559                 if (*level == 0) {
3560                         ret = btrfs_drop_leaf_ref(trans, root, cur);
3561                         BUG_ON(ret);
3562                         clean_tree_block(trans, root, cur);
3563                         break;
3564                 }
3565                 if (path->slots[*level] >= btrfs_header_nritems(cur)) {
3566                         clean_tree_block(trans, root, cur);
3567                         break;
3568                 }
3569
3570                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
3571                 blocksize = btrfs_level_size(root, *level - 1);
3572                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
3573
3574                 next = read_tree_block(root, bytenr, blocksize, ptr_gen);
3575                 btrfs_tree_lock(next);
3576                 btrfs_set_lock_blocking(next);
3577
3578                 ret = btrfs_lookup_extent_ref(trans, root, bytenr, blocksize,
3579                                               &refs);
3580                 BUG_ON(ret);
3581                 if (refs > 1) {
3582                         parent = path->nodes[*level];
3583                         ret = btrfs_free_extent(trans, root, bytenr,
3584                                         blocksize, parent->start,
3585                                         btrfs_header_owner(parent),
3586                                         btrfs_header_generation(parent),
3587                                         *level - 1, 1);
3588                         BUG_ON(ret);
3589                         path->slots[*level]++;
3590                         btrfs_tree_unlock(next);
3591                         free_extent_buffer(next);
3592                         continue;
3593                 }
3594
3595                 *level = btrfs_header_level(next);
3596                 path->nodes[*level] = next;
3597                 path->slots[*level] = 0;
3598                 path->locks[*level] = 1;
3599                 cond_resched();
3600         }
3601 out:
3602         parent = path->nodes[*level + 1];
3603         bytenr = path->nodes[*level]->start;
3604         blocksize = path->nodes[*level]->len;
3605
3606         ret = btrfs_free_extent(trans, root, bytenr, blocksize,
3607                         parent->start, btrfs_header_owner(parent),
3608                         btrfs_header_generation(parent), *level, 1);
3609         BUG_ON(ret);
3610
3611         if (path->locks[*level]) {
3612                 btrfs_tree_unlock(path->nodes[*level]);
3613                 path->locks[*level] = 0;
3614         }
3615         free_extent_buffer(path->nodes[*level]);
3616         path->nodes[*level] = NULL;
3617         *level += 1;
3618         cond_resched();
3619         return 0;
3620 }
3621
3622 /*
3623  * helper for dropping snapshots.  This walks back up the tree in the path
3624  * to find the first node higher up where we haven't yet gone through
3625  * all the slots
3626  */
3627 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
3628                                  struct btrfs_root *root,
3629                                  struct btrfs_path *path,
3630                                  int *level, int max_level)
3631 {
3632         u64 root_owner;
3633         u64 root_gen;
3634         struct btrfs_root_item *root_item = &root->root_item;
3635         int i;
3636         int slot;
3637         int ret;
3638
3639         for (i = *level; i < max_level && path->nodes[i]; i++) {
3640                 slot = path->slots[i];
3641                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
3642                         struct extent_buffer *node;
3643                         struct btrfs_disk_key disk_key;
3644
3645                         /*
3646                          * there is more work to do in this level.
3647                          * Update the drop_progress marker to reflect
3648                          * the work we've done so far, and then bump
3649                          * the slot number
3650                          */
3651                         node = path->nodes[i];
3652                         path->slots[i]++;
3653                         *level = i;
3654                         WARN_ON(*level == 0);
3655                         btrfs_node_key(node, &disk_key, path->slots[i]);
3656                         memcpy(&root_item->drop_progress,
3657                                &disk_key, sizeof(disk_key));
3658                         root_item->drop_level = i;
3659                         return 0;
3660                 } else {
3661                         struct extent_buffer *parent;
3662
3663                         /*
3664                          * this whole node is done, free our reference
3665                          * on it and go up one level
3666                          */
3667                         if (path->nodes[*level] == root->node)
3668                                 parent = path->nodes[*level];
3669                         else
3670                                 parent = path->nodes[*level + 1];
3671
3672                         root_owner = btrfs_header_owner(parent);
3673                         root_gen = btrfs_header_generation(parent);
3674
3675                         clean_tree_block(trans, root, path->nodes[*level]);
3676                         ret = btrfs_free_extent(trans, root,
3677                                                 path->nodes[*level]->start,
3678                                                 path->nodes[*level]->len,
3679                                                 parent->start, root_owner,
3680                                                 root_gen, *level, 1);
3681                         BUG_ON(ret);
3682                         if (path->locks[*level]) {
3683                                 btrfs_tree_unlock(path->nodes[*level]);
3684                                 path->locks[*level] = 0;
3685                         }
3686                         free_extent_buffer(path->nodes[*level]);
3687                         path->nodes[*level] = NULL;
3688                         *level = i + 1;
3689                 }
3690         }
3691         return 1;
3692 }
3693
3694 /*
3695  * drop the reference count on the tree rooted at 'snap'.  This traverses
3696  * the tree freeing any blocks that have a ref count of zero after being
3697  * decremented.
3698  */
3699 int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
3700                         *root)
3701 {
3702         int ret = 0;
3703         int wret;
3704         int level;
3705         struct btrfs_path *path;
3706         int i;
3707         int orig_level;
3708         struct btrfs_root_item *root_item = &root->root_item;
3709
3710         WARN_ON(!mutex_is_locked(&root->fs_info->drop_mutex));
3711         path = btrfs_alloc_path();
3712         BUG_ON(!path);
3713
3714         level = btrfs_header_level(root->node);
3715         orig_level = level;
3716         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3717                 path->nodes[level] = root->node;
3718                 extent_buffer_get(root->node);
3719                 path->slots[level] = 0;
3720         } else {
3721                 struct btrfs_key key;
3722                 struct btrfs_disk_key found_key;
3723                 struct extent_buffer *node;
3724
3725                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3726                 level = root_item->drop_level;
3727                 path->lowest_level = level;
3728                 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3729                 if (wret < 0) {
3730                         ret = wret;
3731                         goto out;
3732                 }
3733                 node = path->nodes[level];
3734                 btrfs_node_key(node, &found_key, path->slots[level]);
3735                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3736                                sizeof(found_key)));
3737                 /*
3738                  * unlock our path, this is safe because only this
3739                  * function is allowed to delete this snapshot
3740                  */
3741                 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
3742                         if (path->nodes[i] && path->locks[i]) {
3743                                 path->locks[i] = 0;
3744                                 btrfs_tree_unlock(path->nodes[i]);
3745                         }
3746                 }
3747         }
3748         while (1) {
3749                 wret = walk_down_tree(trans, root, path, &level);
3750                 if (wret > 0)
3751                         break;
3752                 if (wret < 0)
3753                         ret = wret;
3754
3755                 wret = walk_up_tree(trans, root, path, &level,
3756                                     BTRFS_MAX_LEVEL);
3757                 if (wret > 0)
3758                         break;
3759                 if (wret < 0)
3760                         ret = wret;
3761                 if (trans->transaction->in_commit) {
3762                         ret = -EAGAIN;
3763                         break;
3764                 }
3765                 atomic_inc(&root->fs_info->throttle_gen);
3766                 wake_up(&root->fs_info->transaction_throttle);
3767         }
3768         for (i = 0; i <= orig_level; i++) {
3769                 if (path->nodes[i]) {
3770                         free_extent_buffer(path->nodes[i]);
3771                         path->nodes[i] = NULL;
3772                 }
3773         }
3774 out:
3775         btrfs_free_path(path);
3776         return ret;
3777 }
3778
3779 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
3780                         struct btrfs_root *root,
3781                         struct extent_buffer *node,
3782                         struct extent_buffer *parent)
3783 {
3784         struct btrfs_path *path;
3785         int level;
3786         int parent_level;
3787         int ret = 0;
3788         int wret;
3789
3790         path = btrfs_alloc_path();
3791         BUG_ON(!path);
3792
3793         btrfs_assert_tree_locked(parent);
3794         parent_level = btrfs_header_level(parent);
3795         extent_buffer_get(parent);
3796         path->nodes[parent_level] = parent;
3797         path->slots[parent_level] = btrfs_header_nritems(parent);
3798
3799         btrfs_assert_tree_locked(node);
3800         level = btrfs_header_level(node);
3801         extent_buffer_get(node);
3802         path->nodes[level] = node;
3803         path->slots[level] = 0;
3804
3805         while (1) {
3806                 wret = walk_down_subtree(trans, root, path, &level);
3807                 if (wret < 0)
3808                         ret = wret;
3809                 if (wret != 0)
3810                         break;
3811
3812                 wret = walk_up_tree(trans, root, path, &level, parent_level);
3813                 if (wret < 0)
3814                         ret = wret;
3815                 if (wret != 0)
3816                         break;
3817         }
3818
3819         btrfs_free_path(path);
3820         return ret;
3821 }
3822
3823 static unsigned long calc_ra(unsigned long start, unsigned long last,
3824                              unsigned long nr)
3825 {
3826         return min(last, start + nr - 1);
3827 }
3828
3829 static noinline int relocate_inode_pages(struct inode *inode, u64 start,
3830                                          u64 len)
3831 {
3832         u64 page_start;
3833         u64 page_end;
3834         unsigned long first_index;
3835         unsigned long last_index;
3836         unsigned long i;
3837         struct page *page;
3838         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3839         struct file_ra_state *ra;
3840         struct btrfs_ordered_extent *ordered;
3841         unsigned int total_read = 0;
3842         unsigned int total_dirty = 0;
3843         int ret = 0;
3844
3845         ra = kzalloc(sizeof(*ra), GFP_NOFS);
3846
3847         mutex_lock(&inode->i_mutex);
3848         first_index = start >> PAGE_CACHE_SHIFT;
3849         last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
3850
3851         /* make sure the dirty trick played by the caller work */
3852         ret = invalidate_inode_pages2_range(inode->i_mapping,
3853                                             first_index, last_index);
3854         if (ret)
3855                 goto out_unlock;
3856
3857         file_ra_state_init(ra, inode->i_mapping);
3858
3859         for (i = first_index ; i <= last_index; i++) {
3860                 if (total_read % ra->ra_pages == 0) {
3861                         btrfs_force_ra(inode->i_mapping, ra, NULL, i,
3862                                        calc_ra(i, last_index, ra->ra_pages));
3863                 }
3864                 total_read++;
3865 again:
3866                 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
3867                         BUG_ON(1);
3868                 page = grab_cache_page(inode->i_mapping, i);
3869                 if (!page) {
3870                         ret = -ENOMEM;
3871                         goto out_unlock;
3872                 }
3873                 if (!PageUptodate(page)) {
3874                         btrfs_readpage(NULL, page);
3875                         lock_page(page);
3876                         if (!PageUptodate(page)) {
3877                                 unlock_page(page);
3878                                 page_cache_release(page);
3879                                 ret = -EIO;
3880                                 goto out_unlock;
3881                         }
3882                 }
3883                 wait_on_page_writeback(page);
3884
3885                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
3886                 page_end = page_start + PAGE_CACHE_SIZE - 1;
3887                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
3888
3889                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3890                 if (ordered) {
3891                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3892                         unlock_page(page);
3893                         page_cache_release(page);
3894                         btrfs_start_ordered_extent(inode, ordered, 1);
3895                         btrfs_put_ordered_extent(ordered);
3896                         goto again;
3897                 }
3898                 set_page_extent_mapped(page);
3899
3900                 if (i == first_index)
3901                         set_extent_bits(io_tree, page_start, page_end,
3902                                         EXTENT_BOUNDARY, GFP_NOFS);
3903                 btrfs_set_extent_delalloc(inode, page_start, page_end);
3904
3905                 set_page_dirty(page);
3906                 total_dirty++;
3907
3908                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3909                 unlock_page(page);
3910                 page_cache_release(page);
3911         }
3912
3913 out_unlock:
3914         kfree(ra);
3915         mutex_unlock(&inode->i_mutex);
3916         balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
3917         return ret;
3918 }
3919
3920 static noinline int relocate_data_extent(struct inode *reloc_inode,
3921                                          struct btrfs_key *extent_key,
3922                                          u64 offset)
3923 {
3924         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
3925         struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
3926         struct extent_map *em;
3927         u64 start = extent_key->objectid - offset;
3928         u64 end = start + extent_key->offset - 1;
3929
3930         em = alloc_extent_map(GFP_NOFS);
3931         BUG_ON(!em || IS_ERR(em));
3932
3933         em->start = start;
3934         em->len = extent_key->offset;
3935         em->block_len = extent_key->offset;
3936         em->block_start = extent_key->objectid;
3937         em->bdev = root->fs_info->fs_devices->latest_bdev;
3938         set_bit(EXTENT_FLAG_PINNED, &em->flags);
3939
3940         /* setup extent map to cheat btrfs_readpage */
3941         lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
3942         while (1) {
3943                 int ret;
3944                 spin_lock(&em_tree->lock);
3945                 ret = add_extent_mapping(em_tree, em);
3946                 spin_unlock(&em_tree->lock);
3947                 if (ret != -EEXIST) {
3948                         free_extent_map(em);
3949                         break;
3950                 }
3951                 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
3952         }
3953         unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
3954
3955         return relocate_inode_pages(reloc_inode, start, extent_key->offset);
3956 }
3957
3958 struct btrfs_ref_path {
3959         u64 extent_start;
3960         u64 nodes[BTRFS_MAX_LEVEL];
3961         u64 root_objectid;
3962         u64 root_generation;
3963         u64 owner_objectid;
3964         u32 num_refs;
3965         int lowest_level;
3966         int current_level;
3967         int shared_level;
3968
3969         struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
3970         u64 new_nodes[BTRFS_MAX_LEVEL];
3971 };
3972
3973 struct disk_extent {
3974         u64 ram_bytes;
3975         u64 disk_bytenr;
3976         u64 disk_num_bytes;
3977         u64 offset;
3978         u64 num_bytes;
3979         u8 compression;
3980         u8 encryption;
3981         u16 other_encoding;
3982 };
3983
3984 static int is_cowonly_root(u64 root_objectid)
3985 {
3986         if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
3987             root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
3988             root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
3989             root_objectid == BTRFS_DEV_TREE_OBJECTID ||
3990             root_objectid == BTRFS_TREE_LOG_OBJECTID ||
3991             root_objectid == BTRFS_CSUM_TREE_OBJECTID)
3992                 return 1;
3993         return 0;
3994 }
3995
3996 static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
3997                                     struct btrfs_root *extent_root,
3998                                     struct btrfs_ref_path *ref_path,
3999                                     int first_time)
4000 {
4001         struct extent_buffer *leaf;
4002         struct btrfs_path *path;
4003         struct btrfs_extent_ref *ref;
4004         struct btrfs_key key;
4005         struct btrfs_key found_key;
4006         u64 bytenr;
4007         u32 nritems;
4008         int level;
4009         int ret = 1;
4010
4011         path = btrfs_alloc_path();
4012         if (!path)
4013                 return -ENOMEM;
4014
4015         if (first_time) {
4016                 ref_path->lowest_level = -1;
4017                 ref_path->current_level = -1;
4018                 ref_path->shared_level = -1;
4019                 goto walk_up;
4020         }
4021 walk_down:
4022         level = ref_path->current_level - 1;
4023         while (level >= -1) {
4024                 u64 parent;
4025                 if (level < ref_path->lowest_level)
4026                         break;
4027
4028                 if (level >= 0)
4029                         bytenr = ref_path->nodes[level];
4030                 else
4031                         bytenr = ref_path->extent_start;
4032                 BUG_ON(bytenr == 0);
4033
4034                 parent = ref_path->nodes[level + 1];
4035                 ref_path->nodes[level + 1] = 0;
4036                 ref_path->current_level = level;
4037                 BUG_ON(parent == 0);
4038
4039                 key.objectid = bytenr;
4040                 key.offset = parent + 1;
4041                 key.type = BTRFS_EXTENT_REF_KEY;
4042
4043                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
4044                 if (ret < 0)
4045                         goto out;
4046                 BUG_ON(ret == 0);
4047
4048                 leaf = path->nodes[0];
4049                 nritems = btrfs_header_nritems(leaf);
4050                 if (path->slots[0] >= nritems) {
4051                         ret = btrfs_next_leaf(extent_root, path);
4052                         if (ret < 0)
4053                                 goto out;
4054                         if (ret > 0)
4055                                 goto next;
4056                         leaf = path->nodes[0];
4057                 }
4058
4059                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4060                 if (found_key.objectid == bytenr &&
4061                     found_key.type == BTRFS_EXTENT_REF_KEY) {
4062                         if (level < ref_path->shared_level)
4063                                 ref_path->shared_level = level;
4064                         goto found;
4065                 }
4066 next:
4067                 level--;
4068                 btrfs_release_path(extent_root, path);
4069                 cond_resched();
4070         }
4071         /* reached lowest level */
4072         ret = 1;
4073         goto out;
4074 walk_up:
4075         level = ref_path->current_level;
4076         while (level < BTRFS_MAX_LEVEL - 1) {
4077                 u64 ref_objectid;
4078
4079                 if (level >= 0)
4080                         bytenr = ref_path->nodes[level];
4081                 else
4082                         bytenr = ref_path->extent_start;
4083
4084                 BUG_ON(bytenr == 0);
4085
4086                 key.objectid = bytenr;
4087                 key.offset = 0;
4088                 key.type = BTRFS_EXTENT_REF_KEY;
4089
4090                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
4091                 if (ret < 0)
4092                         goto out;
4093
4094                 leaf = path->nodes[0];
4095                 nritems = btrfs_header_nritems(leaf);
4096                 if (path->slots[0] >= nritems) {
4097                         ret = btrfs_next_leaf(extent_root, path);
4098                         if (ret < 0)
4099                                 goto out;
4100                         if (ret > 0) {
4101                                 /* the extent was freed by someone */
4102                                 if (ref_path->lowest_level == level)
4103                                         goto out;
4104                                 btrfs_release_path(extent_root, path);
4105                                 goto walk_down;
4106                         }
4107                         leaf = path->nodes[0];
4108                 }
4109
4110                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4111                 if (found_key.objectid != bytenr ||
4112                                 found_key.type != BTRFS_EXTENT_REF_KEY) {
4113                         /* the extent was freed by someone */
4114                         if (ref_path->lowest_level == level) {
4115                                 ret = 1;
4116                                 goto out;
4117                         }
4118                         btrfs_release_path(extent_root, path);
4119                         goto walk_down;
4120                 }
4121 found:
4122                 ref = btrfs_item_ptr(leaf, path->slots[0],
4123                                 struct btrfs_extent_ref);
4124                 ref_objectid = btrfs_ref_objectid(leaf, ref);
4125                 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
4126                         if (first_time) {
4127                                 level = (int)ref_objectid;
4128                                 BUG_ON(level >= BTRFS_MAX_LEVEL);
4129                                 ref_path->lowest_level = level;
4130                                 ref_path->current_level = level;
4131                                 ref_path->nodes[level] = bytenr;
4132                         } else {
4133                                 WARN_ON(ref_objectid != level);
4134                         }
4135                 } else {
4136                         WARN_ON(level != -1);
4137                 }
4138                 first_time = 0;
4139
4140                 if (ref_path->lowest_level == level) {
4141                         ref_path->owner_objectid = ref_objectid;
4142                         ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
4143                 }
4144
4145                 /*
4146                  * the block is tree root or the block isn't in reference
4147                  * counted tree.
4148                  */
4149                 if (found_key.objectid == found_key.offset ||
4150                     is_cowonly_root(btrfs_ref_root(leaf, ref))) {
4151                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
4152                         ref_path->root_generation =
4153                                 btrfs_ref_generation(leaf, ref);
4154                         if (level < 0) {
4155                                 /* special reference from the tree log */
4156                                 ref_path->nodes[0] = found_key.offset;
4157                                 ref_path->current_level = 0;
4158                         }
4159                         ret = 0;
4160                         goto out;
4161                 }
4162
4163                 level++;
4164                 BUG_ON(ref_path->nodes[level] != 0);
4165                 ref_path->nodes[level] = found_key.offset;
4166                 ref_path->current_level = level;
4167
4168                 /*
4169                  * the reference was created in the running transaction,
4170                  * no need to continue walking up.
4171                  */
4172                 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
4173                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
4174                         ref_path->root_generation =
4175                                 btrfs_ref_generation(leaf, ref);
4176                         ret = 0;
4177                         goto out;
4178                 }
4179
4180                 btrfs_release_path(extent_root, path);
4181                 cond_resched();
4182         }
4183         /* reached max tree level, but no tree root found. */
4184         BUG();
4185 out:
4186         btrfs_free_path(path);
4187         return ret;
4188 }
4189
4190 static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
4191                                 struct btrfs_root *extent_root,
4192                                 struct btrfs_ref_path *ref_path,
4193                                 u64 extent_start)
4194 {
4195         memset(ref_path, 0, sizeof(*ref_path));
4196         ref_path->extent_start = extent_start;
4197
4198         return __next_ref_path(trans, extent_root, ref_path, 1);
4199 }
4200
4201 static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
4202                                struct btrfs_root *extent_root,
4203                                struct btrfs_ref_path *ref_path)
4204 {
4205         return __next_ref_path(trans, extent_root, ref_path, 0);
4206 }
4207
4208 static noinline int get_new_locations(struct inode *reloc_inode,
4209                                       struct btrfs_key *extent_key,
4210                                       u64 offset, int no_fragment,
4211                                       struct disk_extent **extents,
4212                                       int *nr_extents)
4213 {
4214         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
4215         struct btrfs_path *path;
4216         struct btrfs_file_extent_item *fi;
4217         struct extent_buffer *leaf;
4218         struct disk_extent *exts = *extents;
4219         struct btrfs_key found_key;
4220         u64 cur_pos;
4221         u64 last_byte;
4222         u32 nritems;
4223         int nr = 0;
4224         int max = *nr_extents;
4225         int ret;
4226
4227         WARN_ON(!no_fragment && *extents);
4228         if (!exts) {
4229                 max = 1;
4230                 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
4231                 if (!exts)
4232                         return -ENOMEM;
4233         }
4234
4235         path = btrfs_alloc_path();
4236         BUG_ON(!path);
4237
4238         cur_pos = extent_key->objectid - offset;
4239         last_byte = extent_key->objectid + extent_key->offset;
4240         ret = btrfs_lookup_file_extent(NULL, root, path, reloc_inode->i_ino,
4241                                        cur_pos, 0);
4242         if (ret < 0)
4243                 goto out;
4244         if (ret > 0) {
4245                 ret = -ENOENT;
4246                 goto out;
4247         }
4248
4249         while (1) {
4250                 leaf = path->nodes[0];
4251                 nritems = btrfs_header_nritems(leaf);
4252                 if (path->slots[0] >= nritems) {
4253                         ret = btrfs_next_leaf(root, path);
4254                         if (ret < 0)
4255                                 goto out;
4256                         if (ret > 0)
4257                                 break;
4258                         leaf = path->nodes[0];
4259                 }
4260
4261                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4262                 if (found_key.offset != cur_pos ||
4263                     found_key.type != BTRFS_EXTENT_DATA_KEY ||
4264                     found_key.objectid != reloc_inode->i_ino)
4265                         break;
4266
4267                 fi = btrfs_item_ptr(leaf, path->slots[0],
4268                                     struct btrfs_file_extent_item);
4269                 if (btrfs_file_extent_type(leaf, fi) !=
4270                     BTRFS_FILE_EXTENT_REG ||
4271                     btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
4272                         break;
4273
4274                 if (nr == max) {
4275                         struct disk_extent *old = exts;
4276                         max *= 2;
4277                         exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
4278                         memcpy(exts, old, sizeof(*exts) * nr);
4279                         if (old != *extents)
4280                                 kfree(old);
4281                 }
4282
4283                 exts[nr].disk_bytenr =
4284                         btrfs_file_extent_disk_bytenr(leaf, fi);
4285                 exts[nr].disk_num_bytes =
4286                         btrfs_file_extent_disk_num_bytes(leaf, fi);
4287                 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
4288                 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
4289                 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
4290                 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
4291                 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
4292                 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
4293                                                                            fi);
4294                 BUG_ON(exts[nr].offset > 0);
4295                 BUG_ON(exts[nr].compression || exts[nr].encryption);
4296                 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
4297
4298                 cur_pos += exts[nr].num_bytes;
4299                 nr++;
4300
4301                 if (cur_pos + offset >= last_byte)
4302                         break;
4303
4304                 if (no_fragment) {
4305                         ret = 1;
4306                         goto out;
4307                 }
4308                 path->slots[0]++;
4309         }
4310
4311         BUG_ON(cur_pos + offset > last_byte);
4312         if (cur_pos + offset < last_byte) {
4313                 ret = -ENOENT;
4314                 goto out;
4315         }
4316         ret = 0;
4317 out:
4318         btrfs_free_path(path);
4319         if (ret) {
4320                 if (exts != *extents)
4321                         kfree(exts);
4322         } else {
4323                 *extents = exts;
4324                 *nr_extents = nr;
4325         }
4326         return ret;
4327 }
4328
4329 static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
4330                                         struct btrfs_root *root,
4331                                         struct btrfs_path *path,
4332                                         struct btrfs_key *extent_key,
4333                                         struct btrfs_key *leaf_key,
4334                                         struct btrfs_ref_path *ref_path,
4335                                         struct disk_extent *new_extents,
4336                                         int nr_extents)
4337 {
4338         struct extent_buffer *leaf;
4339         struct btrfs_file_extent_item *fi;
4340         struct inode *inode = NULL;
4341         struct btrfs_key key;
4342         u64 lock_start = 0;
4343         u64 lock_end = 0;
4344         u64 num_bytes;
4345         u64 ext_offset;
4346         u64 search_end = (u64)-1;
4347         u32 nritems;
4348         int nr_scaned = 0;
4349         int extent_locked = 0;
4350         int extent_type;
4351         int ret;
4352
4353         memcpy(&key, leaf_key, sizeof(key));
4354         if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
4355                 if (key.objectid < ref_path->owner_objectid ||
4356                     (key.objectid == ref_path->owner_objectid &&
4357                      key.type < BTRFS_EXTENT_DATA_KEY)) {
4358                         key.objectid = ref_path->owner_objectid;
4359                         key.type = BTRFS_EXTENT_DATA_KEY;
4360                         key.offset = 0;
4361                 }
4362         }
4363
4364         while (1) {
4365                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4366                 if (ret < 0)
4367                         goto out;
4368
4369                 leaf = path->nodes[0];
4370                 nritems = btrfs_header_nritems(leaf);
4371 next:
4372                 if (extent_locked && ret > 0) {
4373                         /*
4374                          * the file extent item was modified by someone
4375                          * before the extent got locked.
4376                          */
4377                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4378                                       lock_end, GFP_NOFS);
4379                         extent_locked = 0;
4380                 }
4381
4382                 if (path->slots[0] >= nritems) {
4383                         if (++nr_scaned > 2)
4384                                 break;
4385
4386                         BUG_ON(extent_locked);
4387                         ret = btrfs_next_leaf(root, path);
4388                         if (ret < 0)
4389                                 goto out;
4390                         if (ret > 0)
4391                                 break;
4392                         leaf = path->nodes[0];
4393                         nritems = btrfs_header_nritems(leaf);
4394                 }
4395
4396                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4397
4398                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
4399                         if ((key.objectid > ref_path->owner_objectid) ||
4400                             (key.objectid == ref_path->owner_objectid &&
4401                              key.type > BTRFS_EXTENT_DATA_KEY) ||
4402                             key.offset >= search_end)
4403                                 break;
4404                 }
4405
4406                 if (inode && key.objectid != inode->i_ino) {
4407                         BUG_ON(extent_locked);
4408                         btrfs_release_path(root, path);
4409                         mutex_unlock(&inode->i_mutex);
4410                         iput(inode);
4411                         inode = NULL;
4412                         continue;
4413                 }
4414
4415                 if (key.type != BTRFS_EXTENT_DATA_KEY) {
4416                         path->slots[0]++;
4417                         ret = 1;
4418                         goto next;
4419                 }
4420                 fi = btrfs_item_ptr(leaf, path->slots[0],
4421                                     struct btrfs_file_extent_item);
4422                 extent_type = btrfs_file_extent_type(leaf, fi);
4423                 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
4424                      extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
4425                     (btrfs_file_extent_disk_bytenr(leaf, fi) !=
4426                      extent_key->objectid)) {
4427                         path->slots[0]++;
4428                         ret = 1;
4429                         goto next;
4430                 }
4431
4432                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
4433                 ext_offset = btrfs_file_extent_offset(leaf, fi);
4434
4435                 if (search_end == (u64)-1) {
4436                         search_end = key.offset - ext_offset +
4437                                 btrfs_file_extent_ram_bytes(leaf, fi);
4438                 }
4439
4440                 if (!extent_locked) {
4441                         lock_start = key.offset;
4442                         lock_end = lock_start + num_bytes - 1;
4443                 } else {
4444                         if (lock_start > key.offset ||
4445                             lock_end + 1 < key.offset + num_bytes) {
4446                                 unlock_extent(&BTRFS_I(inode)->io_tree,
4447                                               lock_start, lock_end, GFP_NOFS);
4448                                 extent_locked = 0;
4449                         }
4450                 }
4451
4452                 if (!inode) {
4453                         btrfs_release_path(root, path);
4454
4455                         inode = btrfs_iget_locked(root->fs_info->sb,
4456                                                   key.objectid, root);
4457                         if (inode->i_state & I_NEW) {
4458                                 BTRFS_I(inode)->root = root;
4459                                 BTRFS_I(inode)->location.objectid =
4460                                         key.objectid;
4461                                 BTRFS_I(inode)->location.type =
4462                                         BTRFS_INODE_ITEM_KEY;
4463                                 BTRFS_I(inode)->location.offset = 0;
4464                                 btrfs_read_locked_inode(inode);
4465                                 unlock_new_inode(inode);
4466                         }
4467                         /*
4468                          * some code call btrfs_commit_transaction while
4469                          * holding the i_mutex, so we can't use mutex_lock
4470                          * here.
4471                          */
4472                         if (is_bad_inode(inode) ||
4473                             !mutex_trylock(&inode->i_mutex)) {
4474                                 iput(inode);
4475                                 inode = NULL;
4476                                 key.offset = (u64)-1;
4477                                 goto skip;
4478                         }
4479                 }
4480
4481                 if (!extent_locked) {
4482                         struct btrfs_ordered_extent *ordered;
4483
4484                         btrfs_release_path(root, path);
4485
4486                         lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4487                                     lock_end, GFP_NOFS);
4488                         ordered = btrfs_lookup_first_ordered_extent(inode,
4489                                                                     lock_end);
4490                         if (ordered &&
4491                             ordered->file_offset <= lock_end &&
4492                             ordered->file_offset + ordered->len > lock_start) {
4493                                 unlock_extent(&BTRFS_I(inode)->io_tree,
4494                                               lock_start, lock_end, GFP_NOFS);
4495                                 btrfs_start_ordered_extent(inode, ordered, 1);
4496                                 btrfs_put_ordered_extent(ordered);
4497                                 key.offset += num_bytes;
4498                                 goto skip;
4499                         }
4500                         if (ordered)
4501                                 btrfs_put_ordered_extent(ordered);
4502
4503                         extent_locked = 1;
4504                         continue;
4505                 }
4506
4507                 if (nr_extents == 1) {
4508                         /* update extent pointer in place */
4509                         btrfs_set_file_extent_disk_bytenr(leaf, fi,
4510                                                 new_extents[0].disk_bytenr);
4511                         btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4512                                                 new_extents[0].disk_num_bytes);
4513                         btrfs_mark_buffer_dirty(leaf);
4514
4515                         btrfs_drop_extent_cache(inode, key.offset,
4516                                                 key.offset + num_bytes - 1, 0);
4517
4518                         ret = btrfs_inc_extent_ref(trans, root,
4519                                                 new_extents[0].disk_bytenr,
4520                                                 new_extents[0].disk_num_bytes,
4521                                                 leaf->start,
4522                                                 root->root_key.objectid,
4523                                                 trans->transid,
4524                                                 key.objectid);
4525                         BUG_ON(ret);
4526
4527                         ret = btrfs_free_extent(trans, root,
4528                                                 extent_key->objectid,
4529                                                 extent_key->offset,
4530                                                 leaf->start,
4531                                                 btrfs_header_owner(leaf),
4532                                                 btrfs_header_generation(leaf),
4533                                                 key.objectid, 0);
4534                         BUG_ON(ret);
4535
4536                         btrfs_release_path(root, path);
4537                         key.offset += num_bytes;
4538                 } else {
4539                         BUG_ON(1);
4540 #if 0
4541                         u64 alloc_hint;
4542                         u64 extent_len;
4543                         int i;
4544                         /*
4545                          * drop old extent pointer at first, then insert the
4546                          * new pointers one bye one
4547                          */
4548                         btrfs_release_path(root, path);
4549                         ret = btrfs_drop_extents(trans, root, inode, key.offset,
4550                                                  key.offset + num_bytes,
4551                                                  key.offset, &alloc_hint);
4552                         BUG_ON(ret);
4553
4554                         for (i = 0; i < nr_extents; i++) {
4555                                 if (ext_offset >= new_extents[i].num_bytes) {
4556                                         ext_offset -= new_extents[i].num_bytes;
4557                                         continue;
4558                                 }
4559                                 extent_len = min(new_extents[i].num_bytes -
4560                                                  ext_offset, num_bytes);
4561
4562                                 ret = btrfs_insert_empty_item(trans, root,
4563                                                               path, &key,
4564                                                               sizeof(*fi));
4565                                 BUG_ON(ret);
4566
4567                                 leaf = path->nodes[0];
4568                                 fi = btrfs_item_ptr(leaf, path->slots[0],
4569                                                 struct btrfs_file_extent_item);
4570                                 btrfs_set_file_extent_generation(leaf, fi,
4571                                                         trans->transid);
4572                                 btrfs_set_file_extent_type(leaf, fi,
4573                                                         BTRFS_FILE_EXTENT_REG);
4574                                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
4575                                                 new_extents[i].disk_bytenr);
4576                                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4577                                                 new_extents[i].disk_num_bytes);
4578                                 btrfs_set_file_extent_ram_bytes(leaf, fi,
4579                                                 new_extents[i].ram_bytes);
4580
4581                                 btrfs_set_file_extent_compression(leaf, fi,
4582                                                 new_extents[i].compression);
4583                                 btrfs_set_file_extent_encryption(leaf, fi,
4584                                                 new_extents[i].encryption);
4585                                 btrfs_set_file_extent_other_encoding(leaf, fi,
4586                                                 new_extents[i].other_encoding);
4587
4588                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4589                                                         extent_len);
4590                                 ext_offset += new_extents[i].offset;
4591                                 btrfs_set_file_extent_offset(leaf, fi,
4592                                                         ext_offset);
4593                                 btrfs_mark_buffer_dirty(leaf);
4594
4595                                 btrfs_drop_extent_cache(inode, key.offset,
4596                                                 key.offset + extent_len - 1, 0);
4597
4598                                 ret = btrfs_inc_extent_ref(trans, root,
4599                                                 new_extents[i].disk_bytenr,
4600                                                 new_extents[i].disk_num_bytes,
4601                                                 leaf->start,
4602                                                 root->root_key.objectid,
4603                                                 trans->transid, key.objectid);
4604                                 BUG_ON(ret);
4605                                 btrfs_release_path(root, path);
4606
4607                                 inode_add_bytes(inode, extent_len);
4608
4609                                 ext_offset = 0;
4610                                 num_bytes -= extent_len;
4611                                 key.offset += extent_len;
4612
4613                                 if (num_bytes == 0)
4614                                         break;
4615                         }
4616                         BUG_ON(i >= nr_extents);
4617 #endif
4618                 }
4619
4620                 if (extent_locked) {
4621                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4622                                       lock_end, GFP_NOFS);
4623                         extent_locked = 0;
4624                 }
4625 skip:
4626                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
4627                     key.offset >= search_end)
4628                         break;
4629
4630                 cond_resched();
4631         }
4632         ret = 0;
4633 out:
4634         btrfs_release_path(root, path);
4635         if (inode) {
4636                 mutex_unlock(&inode->i_mutex);
4637                 if (extent_locked) {
4638                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4639                                       lock_end, GFP_NOFS);
4640                 }
4641                 iput(inode);
4642         }
4643         return ret;
4644 }
4645
4646 int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
4647                                struct btrfs_root *root,
4648                                struct extent_buffer *buf, u64 orig_start)
4649 {
4650         int level;
4651         int ret;
4652
4653         BUG_ON(btrfs_header_generation(buf) != trans->transid);
4654         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
4655
4656         level = btrfs_header_level(buf);
4657         if (level == 0) {
4658                 struct btrfs_leaf_ref *ref;
4659                 struct btrfs_leaf_ref *orig_ref;
4660
4661                 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
4662                 if (!orig_ref)
4663                         return -ENOENT;
4664
4665                 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
4666                 if (!ref) {
4667                         btrfs_free_leaf_ref(root, orig_ref);
4668                         return -ENOMEM;
4669                 }
4670
4671                 ref->nritems = orig_ref->nritems;
4672                 memcpy(ref->extents, orig_ref->extents,
4673                         sizeof(ref->extents[0]) * ref->nritems);
4674
4675                 btrfs_free_leaf_ref(root, orig_ref);
4676
4677                 ref->root_gen = trans->transid;
4678                 ref->bytenr = buf->start;
4679                 ref->owner = btrfs_header_owner(buf);
4680                 ref->generation = btrfs_header_generation(buf);
4681
4682                 ret = btrfs_add_leaf_ref(root, ref, 0);
4683                 WARN_ON(ret);
4684                 btrfs_free_leaf_ref(root, ref);
4685         }
4686         return 0;
4687 }
4688
4689 static noinline int invalidate_extent_cache(struct btrfs_root *root,
4690                                         struct extent_buffer *leaf,
4691                                         struct btrfs_block_group_cache *group,
4692                                         struct btrfs_root *target_root)
4693 {
4694         struct btrfs_key key;
4695         struct inode *inode = NULL;
4696         struct btrfs_file_extent_item *fi;
4697         u64 num_bytes;
4698         u64 skip_objectid = 0;
4699         u32 nritems;
4700         u32 i;
4701
4702         nritems = btrfs_header_nritems(leaf);
4703         for (i = 0; i < nritems; i++) {
4704                 btrfs_item_key_to_cpu(leaf, &key, i);
4705                 if (key.objectid == skip_objectid ||
4706                     key.type != BTRFS_EXTENT_DATA_KEY)
4707                         continue;
4708                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
4709                 if (btrfs_file_extent_type(leaf, fi) ==
4710                     BTRFS_FILE_EXTENT_INLINE)
4711                         continue;
4712                 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
4713                         continue;
4714                 if (!inode || inode->i_ino != key.objectid) {
4715                         iput(inode);
4716                         inode = btrfs_ilookup(target_root->fs_info->sb,
4717                                               key.objectid, target_root, 1);
4718                 }
4719                 if (!inode) {
4720                         skip_objectid = key.objectid;
4721                         continue;
4722                 }
4723                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
4724
4725                 lock_extent(&BTRFS_I(inode)->io_tree, key.offset,
4726                             key.offset + num_bytes - 1, GFP_NOFS);
4727                 btrfs_drop_extent_cache(inode, key.offset,
4728                                         key.offset + num_bytes - 1, 1);
4729                 unlock_extent(&BTRFS_I(inode)->io_tree, key.offset,
4730                               key.offset + num_bytes - 1, GFP_NOFS);
4731                 cond_resched();
4732         }
4733         iput(inode);
4734         return 0;
4735 }
4736
4737 static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
4738                                         struct btrfs_root *root,
4739                                         struct extent_buffer *leaf,
4740                                         struct btrfs_block_group_cache *group,
4741                                         struct inode *reloc_inode)
4742 {
4743         struct btrfs_key key;
4744         struct btrfs_key extent_key;
4745         struct btrfs_file_extent_item *fi;
4746         struct btrfs_leaf_ref *ref;
4747         struct disk_extent *new_extent;
4748         u64 bytenr;
4749         u64 num_bytes;
4750         u32 nritems;
4751         u32 i;
4752         int ext_index;
4753         int nr_extent;
4754         int ret;
4755
4756         new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
4757         BUG_ON(!new_extent);
4758
4759         ref = btrfs_lookup_leaf_ref(root, leaf->start);
4760         BUG_ON(!ref);
4761
4762         ext_index = -1;
4763         nritems = btrfs_header_nritems(leaf);
4764         for (i = 0; i < nritems; i++) {
4765                 btrfs_item_key_to_cpu(leaf, &key, i);
4766                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
4767                         continue;
4768                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
4769                 if (btrfs_file_extent_type(leaf, fi) ==
4770                     BTRFS_FILE_EXTENT_INLINE)
4771                         continue;
4772                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4773                 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4774                 if (bytenr == 0)
4775                         continue;
4776
4777                 ext_index++;
4778                 if (bytenr >= group->key.objectid + group->key.offset ||
4779                     bytenr + num_bytes <= group->key.objectid)
4780                         continue;
4781
4782                 extent_key.objectid = bytenr;
4783                 extent_key.offset = num_bytes;
4784                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4785                 nr_extent = 1;
4786                 ret = get_new_locations(reloc_inode, &extent_key,
4787                                         group->key.objectid, 1,
4788                                         &new_extent, &nr_extent);
4789                 if (ret > 0)
4790                         continue;
4791                 BUG_ON(ret < 0);
4792
4793                 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
4794                 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
4795                 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
4796                 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
4797
4798                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
4799                                                 new_extent->disk_bytenr);
4800                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4801                                                 new_extent->disk_num_bytes);
4802                 btrfs_mark_buffer_dirty(leaf);
4803
4804                 ret = btrfs_inc_extent_ref(trans, root,
4805                                         new_extent->disk_bytenr,
4806                                         new_extent->disk_num_bytes,
4807                                         leaf->start,
4808                                         root->root_key.objectid,
4809                                         trans->transid, key.objectid);
4810                 BUG_ON(ret);
4811
4812                 ret = btrfs_free_extent(trans, root,
4813                                         bytenr, num_bytes, leaf->start,
4814                                         btrfs_header_owner(leaf),
4815                                         btrfs_header_generation(leaf),
4816                                         key.objectid, 0);
4817                 BUG_ON(ret);
4818                 cond_resched();
4819         }
4820         kfree(new_extent);
4821         BUG_ON(ext_index + 1 != ref->nritems);
4822         btrfs_free_leaf_ref(root, ref);
4823         return 0;
4824 }
4825
4826 int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
4827                           struct btrfs_root *root)
4828 {
4829         struct btrfs_root *reloc_root;
4830         int ret;
4831
4832         if (root->reloc_root) {
4833                 reloc_root = root->reloc_root;
4834                 root->reloc_root = NULL;
4835                 list_add(&reloc_root->dead_list,
4836                          &root->fs_info->dead_reloc_roots);
4837
4838                 btrfs_set_root_bytenr(&reloc_root->root_item,
4839                                       reloc_root->node->start);
4840                 btrfs_set_root_level(&root->root_item,
4841                                      btrfs_header_level(reloc_root->node));
4842                 memset(&reloc_root->root_item.drop_progress, 0,
4843                         sizeof(struct btrfs_disk_key));
4844                 reloc_root->root_item.drop_level = 0;
4845
4846                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
4847                                         &reloc_root->root_key,
4848                                         &reloc_root->root_item);
4849                 BUG_ON(ret);
4850         }
4851         return 0;
4852 }
4853
4854 int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
4855 {
4856         struct btrfs_trans_handle *trans;
4857         struct btrfs_root *reloc_root;
4858         struct btrfs_root *prev_root = NULL;
4859         struct list_head dead_roots;
4860         int ret;
4861         unsigned long nr;
4862
4863         INIT_LIST_HEAD(&dead_roots);
4864         list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
4865
4866         while (!list_empty(&dead_roots)) {
4867                 reloc_root = list_entry(dead_roots.prev,
4868                                         struct btrfs_root, dead_list);
4869                 list_del_init(&reloc_root->dead_list);
4870
4871                 BUG_ON(reloc_root->commit_root != NULL);
4872                 while (1) {
4873                         trans = btrfs_join_transaction(root, 1);
4874                         BUG_ON(!trans);
4875
4876                         mutex_lock(&root->fs_info->drop_mutex);
4877                         ret = btrfs_drop_snapshot(trans, reloc_root);
4878                         if (ret != -EAGAIN)
4879                                 break;
4880                         mutex_unlock(&root->fs_info->drop_mutex);
4881
4882                         nr = trans->blocks_used;
4883                         ret = btrfs_end_transaction(trans, root);
4884                         BUG_ON(ret);
4885                         btrfs_btree_balance_dirty(root, nr);
4886                 }
4887
4888                 free_extent_buffer(reloc_root->node);
4889
4890                 ret = btrfs_del_root(trans, root->fs_info->tree_root,
4891                                      &reloc_root->root_key);
4892                 BUG_ON(ret);
4893                 mutex_unlock(&root->fs_info->drop_mutex);
4894
4895                 nr = trans->blocks_used;
4896                 ret = btrfs_end_transaction(trans, root);
4897                 BUG_ON(ret);
4898                 btrfs_btree_balance_dirty(root, nr);
4899
4900                 kfree(prev_root);
4901                 prev_root = reloc_root;
4902         }
4903         if (prev_root) {
4904                 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
4905                 kfree(prev_root);
4906         }
4907         return 0;
4908 }
4909
4910 int btrfs_add_dead_reloc_root(struct btrfs_root *root)
4911 {
4912         list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
4913         return 0;
4914 }
4915
4916 int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
4917 {
4918         struct btrfs_root *reloc_root;
4919         struct btrfs_trans_handle *trans;
4920         struct btrfs_key location;
4921         int found;
4922         int ret;
4923
4924         mutex_lock(&root->fs_info->tree_reloc_mutex);
4925         ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
4926         BUG_ON(ret);
4927         found = !list_empty(&root->fs_info->dead_reloc_roots);
4928         mutex_unlock(&root->fs_info->tree_reloc_mutex);
4929
4930         if (found) {
4931                 trans = btrfs_start_transaction(root, 1);
4932                 BUG_ON(!trans);
4933                 ret = btrfs_commit_transaction(trans, root);
4934                 BUG_ON(ret);
4935         }
4936
4937         location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
4938         location.offset = (u64)-1;
4939         location.type = BTRFS_ROOT_ITEM_KEY;
4940
4941         reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
4942         BUG_ON(!reloc_root);
4943         btrfs_orphan_cleanup(reloc_root);
4944         return 0;
4945 }
4946
4947 static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
4948                                     struct btrfs_root *root)
4949 {
4950         struct btrfs_root *reloc_root;
4951         struct extent_buffer *eb;
4952         struct btrfs_root_item *root_item;
4953         struct btrfs_key root_key;
4954         int ret;
4955
4956         BUG_ON(!root->ref_cows);
4957         if (root->reloc_root)
4958                 return 0;
4959
4960         root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
4961         BUG_ON(!root_item);
4962
4963         ret = btrfs_copy_root(trans, root, root->commit_root,
4964                               &eb, BTRFS_TREE_RELOC_OBJECTID);
4965         BUG_ON(ret);
4966
4967         root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
4968         root_key.offset = root->root_key.objectid;
4969         root_key.type = BTRFS_ROOT_ITEM_KEY;
4970
4971         memcpy(root_item, &root->root_item, sizeof(root_item));
4972         btrfs_set_root_refs(root_item, 0);
4973         btrfs_set_root_bytenr(root_item, eb->start);
4974         btrfs_set_root_level(root_item, btrfs_header_level(eb));
4975         btrfs_set_root_generation(root_item, trans->transid);
4976
4977         btrfs_tree_unlock(eb);
4978         free_extent_buffer(eb);
4979
4980         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
4981                                 &root_key, root_item);
4982         BUG_ON(ret);
4983         kfree(root_item);
4984
4985         reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
4986                                                  &root_key);
4987         BUG_ON(!reloc_root);
4988         reloc_root->last_trans = trans->transid;
4989         reloc_root->commit_root = NULL;
4990         reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
4991
4992         root->reloc_root = reloc_root;
4993         return 0;
4994 }
4995
4996 /*
4997  * Core function of space balance.
4998  *
4999  * The idea is using reloc trees to relocate tree blocks in reference
5000  * counted roots. There is one reloc tree for each subvol, and all
5001  * reloc trees share same root key objectid. Reloc trees are snapshots
5002  * of the latest committed roots of subvols (root->commit_root).
5003  *
5004  * To relocate a tree block referenced by a subvol, there are two steps.
5005  * COW the block through subvol's reloc tree, then update block pointer
5006  * in the subvol to point to the new block. Since all reloc trees share
5007  * same root key objectid, doing special handing for tree blocks owned
5008  * by them is easy. Once a tree block has been COWed in one reloc tree,
5009  * we can use the resulting new block directly when the same block is
5010  * required to COW again through other reloc trees. By this way, relocated
5011  * tree blocks are shared between reloc trees, so they are also shared
5012  * between subvols.
5013  */
5014 static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
5015                                       struct btrfs_root *root,
5016                                       struct btrfs_path *path,
5017                                       struct btrfs_key *first_key,
5018                                       struct btrfs_ref_path *ref_path,
5019                                       struct btrfs_block_group_cache *group,
5020                                       struct inode *reloc_inode)
5021 {
5022         struct btrfs_root *reloc_root;
5023         struct extent_buffer *eb = NULL;
5024         struct btrfs_key *keys;
5025         u64 *nodes;
5026         int level;
5027         int shared_level;
5028         int lowest_level = 0;
5029         int ret;
5030
5031         if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
5032                 lowest_level = ref_path->owner_objectid;
5033
5034         if (!root->ref_cows) {
5035                 path->lowest_level = lowest_level;
5036                 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
5037                 BUG_ON(ret < 0);
5038                 path->lowest_level = 0;
5039                 btrfs_release_path(root, path);
5040                 return 0;
5041         }
5042
5043         mutex_lock(&root->fs_info->tree_reloc_mutex);
5044         ret = init_reloc_tree(trans, root);
5045         BUG_ON(ret);
5046         reloc_root = root->reloc_root;
5047
5048         shared_level = ref_path->shared_level;
5049         ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
5050
5051         keys = ref_path->node_keys;
5052         nodes = ref_path->new_nodes;
5053         memset(&keys[shared_level + 1], 0,
5054                sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
5055         memset(&nodes[shared_level + 1], 0,
5056                sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
5057
5058         if (nodes[lowest_level] == 0) {
5059                 path->lowest_level = lowest_level;
5060                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
5061                                         0, 1);
5062                 BUG_ON(ret);
5063                 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
5064                         eb = path->nodes[level];
5065                         if (!eb || eb == reloc_root->node)
5066                                 break;
5067                         nodes[level] = eb->start;
5068                         if (level == 0)
5069                                 btrfs_item_key_to_cpu(eb, &keys[level], 0);
5070                         else
5071                                 btrfs_node_key_to_cpu(eb, &keys[level], 0);
5072                 }
5073                 if (nodes[0] &&
5074                     ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5075                         eb = path->nodes[0];
5076                         ret = replace_extents_in_leaf(trans, reloc_root, eb,
5077                                                       group, reloc_inode);
5078                         BUG_ON(ret);
5079                 }
5080                 btrfs_release_path(reloc_root, path);
5081         } else {
5082                 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
5083                                        lowest_level);
5084                 BUG_ON(ret);
5085         }
5086
5087         /*
5088          * replace tree blocks in the fs tree with tree blocks in
5089          * the reloc tree.
5090          */
5091         ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
5092         BUG_ON(ret < 0);
5093
5094         if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5095                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
5096                                         0, 0);
5097                 BUG_ON(ret);
5098                 extent_buffer_get(path->nodes[0]);
5099                 eb = path->nodes[0];
5100                 btrfs_release_path(reloc_root, path);
5101                 ret = invalidate_extent_cache(reloc_root, eb, group, root);
5102                 BUG_ON(ret);
5103                 free_extent_buffer(eb);
5104         }
5105
5106         mutex_unlock(&root->fs_info->tree_reloc_mutex);
5107         path->lowest_level = 0;
5108         return 0;
5109 }
5110
5111 static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
5112                                         struct btrfs_root *root,
5113                                         struct btrfs_path *path,
5114                                         struct btrfs_key *first_key,
5115                                         struct btrfs_ref_path *ref_path)
5116 {
5117         int ret;
5118
5119         ret = relocate_one_path(trans, root, path, first_key,
5120                                 ref_path, NULL, NULL);
5121         BUG_ON(ret);
5122
5123         return 0;
5124 }
5125
5126 static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
5127                                     struct btrfs_root *extent_root,
5128                                     struct btrfs_path *path,
5129                                     struct btrfs_key *extent_key)
5130 {
5131         int ret;
5132
5133         ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
5134         if (ret)
5135                 goto out;
5136         ret = btrfs_del_item(trans, extent_root, path);
5137 out:
5138         btrfs_release_path(extent_root, path);
5139         return ret;
5140 }
5141
5142 static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
5143                                                 struct btrfs_ref_path *ref_path)
5144 {
5145         struct btrfs_key root_key;
5146
5147         root_key.objectid = ref_path->root_objectid;
5148         root_key.type = BTRFS_ROOT_ITEM_KEY;
5149         if (is_cowonly_root(ref_path->root_objectid))
5150                 root_key.offset = 0;
5151         else
5152                 root_key.offset = (u64)-1;
5153
5154         return btrfs_read_fs_root_no_name(fs_info, &root_key);
5155 }
5156
5157 static noinline int relocate_one_extent(struct btrfs_root *extent_root,
5158                                         struct btrfs_path *path,
5159                                         struct btrfs_key *extent_key,
5160                                         struct btrfs_block_group_cache *group,
5161                                         struct inode *reloc_inode, int pass)
5162 {
5163         struct btrfs_trans_handle *trans;
5164         struct btrfs_root *found_root;
5165         struct btrfs_ref_path *ref_path = NULL;
5166         struct disk_extent *new_extents = NULL;
5167         int nr_extents = 0;
5168         int loops;
5169         int ret;
5170         int level;
5171         struct btrfs_key first_key;
5172         u64 prev_block = 0;
5173
5174
5175         trans = btrfs_start_transaction(extent_root, 1);
5176         BUG_ON(!trans);
5177
5178         if (extent_key->objectid == 0) {
5179                 ret = del_extent_zero(trans, extent_root, path, extent_key);
5180                 goto out;
5181         }
5182
5183         ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
5184         if (!ref_path) {
5185                 ret = -ENOMEM;
5186                 goto out;
5187         }
5188
5189         for (loops = 0; ; loops++) {
5190                 if (loops == 0) {
5191                         ret = btrfs_first_ref_path(trans, extent_root, ref_path,
5192                                                    extent_key->objectid);
5193                 } else {
5194                         ret = btrfs_next_ref_path(trans, extent_root, ref_path);
5195                 }
5196                 if (ret < 0)
5197                         goto out;
5198                 if (ret > 0)
5199                         break;
5200
5201                 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
5202                     ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
5203                         continue;
5204
5205                 found_root = read_ref_root(extent_root->fs_info, ref_path);
5206                 BUG_ON(!found_root);
5207                 /*
5208                  * for reference counted tree, only process reference paths
5209                  * rooted at the latest committed root.
5210                  */
5211                 if (found_root->ref_cows &&
5212                     ref_path->root_generation != found_root->root_key.offset)
5213                         continue;
5214
5215                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5216                         if (pass == 0) {
5217                                 /*
5218                                  * copy data extents to new locations
5219                                  */
5220                                 u64 group_start = group->key.objectid;
5221                                 ret = relocate_data_extent(reloc_inode,
5222                                                            extent_key,
5223                                                            group_start);
5224                                 if (ret < 0)
5225                                         goto out;
5226                                 break;
5227                         }
5228                         level = 0;
5229                 } else {
5230                         level = ref_path->owner_objectid;
5231                 }
5232
5233                 if (prev_block != ref_path->nodes[level]) {
5234                         struct extent_buffer *eb;
5235                         u64 block_start = ref_path->nodes[level];
5236                         u64 block_size = btrfs_level_size(found_root, level);
5237
5238                         eb = read_tree_block(found_root, block_start,
5239                                              block_size, 0);
5240                         btrfs_tree_lock(eb);
5241                         BUG_ON(level != btrfs_header_level(eb));
5242
5243                         if (level == 0)
5244                                 btrfs_item_key_to_cpu(eb, &first_key, 0);
5245                         else
5246                                 btrfs_node_key_to_cpu(eb, &first_key, 0);
5247
5248                         btrfs_tree_unlock(eb);
5249                         free_extent_buffer(eb);
5250                         prev_block = block_start;
5251                 }
5252
5253                 mutex_lock(&extent_root->fs_info->trans_mutex);
5254                 btrfs_record_root_in_trans(found_root);
5255                 mutex_unlock(&extent_root->fs_info->trans_mutex);
5256                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5257                         /*
5258                          * try to update data extent references while
5259                          * keeping metadata shared between snapshots.
5260                          */
5261                         if (pass == 1) {
5262                                 ret = relocate_one_path(trans, found_root,
5263                                                 path, &first_key, ref_path,
5264                                                 group, reloc_inode);
5265                                 if (ret < 0)
5266                                         goto out;
5267                                 continue;
5268                         }
5269                         /*
5270                          * use fallback method to process the remaining
5271                          * references.
5272                          */
5273                         if (!new_extents) {
5274                                 u64 group_start = group->key.objectid;
5275                                 new_extents = kmalloc(sizeof(*new_extents),
5276                                                       GFP_NOFS);
5277                                 nr_extents = 1;
5278                                 ret = get_new_locations(reloc_inode,
5279                                                         extent_key,
5280                                                         group_start, 1,
5281                                                         &new_extents,
5282                                                         &nr_extents);
5283                                 if (ret)
5284                                         goto out;
5285                         }
5286                         ret = replace_one_extent(trans, found_root,
5287                                                 path, extent_key,
5288                                                 &first_key, ref_path,
5289                                                 new_extents, nr_extents);
5290                 } else {
5291                         ret = relocate_tree_block(trans, found_root, path,
5292                                                   &first_key, ref_path);
5293                 }
5294                 if (ret < 0)
5295                         goto out;
5296         }
5297         ret = 0;
5298 out:
5299         btrfs_end_transaction(trans, extent_root);
5300         kfree(new_extents);
5301         kfree(ref_path);
5302         return ret;
5303 }
5304
5305 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
5306 {
5307         u64 num_devices;
5308         u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
5309                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
5310
5311         num_devices = root->fs_info->fs_devices->rw_devices;
5312         if (num_devices == 1) {
5313                 stripped |= BTRFS_BLOCK_GROUP_DUP;
5314                 stripped = flags & ~stripped;
5315
5316                 /* turn raid0 into single device chunks */
5317                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
5318                         return stripped;
5319
5320                 /* turn mirroring into duplication */
5321                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
5322                              BTRFS_BLOCK_GROUP_RAID10))
5323                         return stripped | BTRFS_BLOCK_GROUP_DUP;
5324                 return flags;
5325         } else {
5326                 /* they already had raid on here, just return */
5327                 if (flags & stripped)
5328                         return flags;
5329
5330                 stripped |= BTRFS_BLOCK_GROUP_DUP;
5331                 stripped = flags & ~stripped;
5332
5333                 /* switch duplicated blocks with raid1 */
5334                 if (flags & BTRFS_BLOCK_GROUP_DUP)
5335                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
5336
5337                 /* turn single device chunks into raid0 */
5338                 return stripped | BTRFS_BLOCK_GROUP_RAID0;
5339         }
5340         return flags;
5341 }
5342
5343 static int __alloc_chunk_for_shrink(struct btrfs_root *root,
5344                      struct btrfs_block_group_cache *shrink_block_group,
5345                      int force)
5346 {
5347         struct btrfs_trans_handle *trans;
5348         u64 new_alloc_flags;
5349         u64 calc;
5350
5351         spin_lock(&shrink_block_group->lock);
5352         if (btrfs_block_group_used(&shrink_block_group->item) > 0) {
5353                 spin_unlock(&shrink_block_group->lock);
5354
5355                 trans = btrfs_start_transaction(root, 1);
5356                 spin_lock(&shrink_block_group->lock);
5357
5358                 new_alloc_flags = update_block_group_flags(root,
5359                                                    shrink_block_group->flags);
5360                 if (new_alloc_flags != shrink_block_group->flags) {
5361                         calc =
5362                              btrfs_block_group_used(&shrink_block_group->item);
5363                 } else {
5364                         calc = shrink_block_group->key.offset;
5365                 }
5366                 spin_unlock(&shrink_block_group->lock);
5367
5368                 do_chunk_alloc(trans, root->fs_info->extent_root,
5369                                calc + 2 * 1024 * 1024, new_alloc_flags, force);
5370
5371                 btrfs_end_transaction(trans, root);
5372         } else
5373                 spin_unlock(&shrink_block_group->lock);
5374         return 0;
5375 }
5376
5377 static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
5378                                  struct btrfs_root *root,
5379                                  u64 objectid, u64 size)
5380 {
5381         struct btrfs_path *path;
5382         struct btrfs_inode_item *item;
5383         struct extent_buffer *leaf;
5384         int ret;
5385
5386         path = btrfs_alloc_path();
5387         if (!path)
5388                 return -ENOMEM;
5389
5390         ret = btrfs_insert_empty_inode(trans, root, path, objectid);
5391         if (ret)
5392                 goto out;
5393
5394         leaf = path->nodes[0];
5395         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
5396         memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
5397         btrfs_set_inode_generation(leaf, item, 1);
5398         btrfs_set_inode_size(leaf, item, size);
5399         btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
5400         btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS);
5401         btrfs_mark_buffer_dirty(leaf);
5402         btrfs_release_path(root, path);
5403 out:
5404         btrfs_free_path(path);
5405         return ret;
5406 }
5407
5408 static noinline struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
5409                                         struct btrfs_block_group_cache *group)
5410 {
5411         struct inode *inode = NULL;
5412         struct btrfs_trans_handle *trans;
5413         struct btrfs_root *root;
5414         struct btrfs_key root_key;
5415         u64 objectid = BTRFS_FIRST_FREE_OBJECTID;
5416         int err = 0;
5417
5418         root_key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
5419         root_key.type = BTRFS_ROOT_ITEM_KEY;
5420         root_key.offset = (u64)-1;
5421         root = btrfs_read_fs_root_no_name(fs_info, &root_key);
5422         if (IS_ERR(root))
5423                 return ERR_CAST(root);
5424
5425         trans = btrfs_start_transaction(root, 1);
5426         BUG_ON(!trans);
5427
5428         err = btrfs_find_free_objectid(trans, root, objectid, &objectid);
5429         if (err)
5430                 goto out;
5431
5432         err = __insert_orphan_inode(trans, root, objectid, group->key.offset);
5433         BUG_ON(err);
5434
5435         err = btrfs_insert_file_extent(trans, root, objectid, 0, 0, 0,
5436                                        group->key.offset, 0, group->key.offset,
5437                                        0, 0, 0);
5438         BUG_ON(err);
5439
5440         inode = btrfs_iget_locked(root->fs_info->sb, objectid, root);
5441         if (inode->i_state & I_NEW) {
5442                 BTRFS_I(inode)->root = root;
5443                 BTRFS_I(inode)->location.objectid = objectid;
5444                 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5445                 BTRFS_I(inode)->location.offset = 0;
5446                 btrfs_read_locked_inode(inode);
5447                 unlock_new_inode(inode);
5448                 BUG_ON(is_bad_inode(inode));
5449         } else {
5450                 BUG_ON(1);
5451         }
5452         BTRFS_I(inode)->index_cnt = group->key.objectid;
5453
5454         err = btrfs_orphan_add(trans, inode);
5455 out:
5456         btrfs_end_transaction(trans, root);
5457         if (err) {
5458                 if (inode)
5459                         iput(inode);
5460                 inode = ERR_PTR(err);
5461         }
5462         return inode;
5463 }
5464
5465 int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
5466 {
5467
5468         struct btrfs_ordered_sum *sums;
5469         struct btrfs_sector_sum *sector_sum;
5470         struct btrfs_ordered_extent *ordered;
5471         struct btrfs_root *root = BTRFS_I(inode)->root;
5472         struct list_head list;
5473         size_t offset;
5474         int ret;
5475         u64 disk_bytenr;
5476
5477         INIT_LIST_HEAD(&list);
5478
5479         ordered = btrfs_lookup_ordered_extent(inode, file_pos);
5480         BUG_ON(ordered->file_offset != file_pos || ordered->len != len);
5481
5482         disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
5483         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, disk_bytenr,
5484                                        disk_bytenr + len - 1, &list);
5485
5486         while (!list_empty(&list)) {
5487                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
5488                 list_del_init(&sums->list);
5489
5490                 sector_sum = sums->sums;
5491                 sums->bytenr = ordered->start;
5492
5493                 offset = 0;
5494                 while (offset < sums->len) {
5495                         sector_sum->bytenr += ordered->start - disk_bytenr;
5496                         sector_sum++;
5497                         offset += root->sectorsize;
5498                 }
5499
5500                 btrfs_add_ordered_sum(inode, ordered, sums);
5501         }
5502         btrfs_put_ordered_extent(ordered);
5503         return 0;
5504 }
5505
5506 int btrfs_relocate_block_group(struct btrfs_root *root, u64 group_start)
5507 {
5508         struct btrfs_trans_handle *trans;
5509         struct btrfs_path *path;
5510         struct btrfs_fs_info *info = root->fs_info;
5511         struct extent_buffer *leaf;
5512         struct inode *reloc_inode;
5513         struct btrfs_block_group_cache *block_group;
5514         struct btrfs_key key;
5515         u64 skipped;
5516         u64 cur_byte;
5517         u64 total_found;
5518         u32 nritems;
5519         int ret;
5520         int progress;
5521         int pass = 0;
5522
5523         root = root->fs_info->extent_root;
5524
5525         block_group = btrfs_lookup_block_group(info, group_start);
5526         BUG_ON(!block_group);
5527
5528         printk(KERN_INFO "btrfs relocating block group %llu flags %llu\n",
5529                (unsigned long long)block_group->key.objectid,
5530                (unsigned long long)block_group->flags);
5531
5532         path = btrfs_alloc_path();
5533         BUG_ON(!path);
5534
5535         reloc_inode = create_reloc_inode(info, block_group);
5536         BUG_ON(IS_ERR(reloc_inode));
5537
5538         __alloc_chunk_for_shrink(root, block_group, 1);
5539         set_block_group_readonly(block_group);
5540
5541         btrfs_start_delalloc_inodes(info->tree_root);
5542         btrfs_wait_ordered_extents(info->tree_root, 0);
5543 again:
5544         skipped = 0;
5545         total_found = 0;
5546         progress = 0;
5547         key.objectid = block_group->key.objectid;
5548         key.offset = 0;
5549         key.type = 0;
5550         cur_byte = key.objectid;
5551
5552         trans = btrfs_start_transaction(info->tree_root, 1);
5553         btrfs_commit_transaction(trans, info->tree_root);
5554
5555         mutex_lock(&root->fs_info->cleaner_mutex);
5556         btrfs_clean_old_snapshots(info->tree_root);
5557         btrfs_remove_leaf_refs(info->tree_root, (u64)-1, 1);
5558         mutex_unlock(&root->fs_info->cleaner_mutex);
5559
5560         trans = btrfs_start_transaction(info->tree_root, 1);
5561         btrfs_commit_transaction(trans, info->tree_root);
5562
5563         while (1) {
5564                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5565                 if (ret < 0)
5566                         goto out;
5567 next:
5568                 leaf = path->nodes[0];
5569                 nritems = btrfs_header_nritems(leaf);
5570                 if (path->slots[0] >= nritems) {
5571                         ret = btrfs_next_leaf(root, path);
5572                         if (ret < 0)
5573                                 goto out;
5574                         if (ret == 1) {
5575                                 ret = 0;
5576                                 break;
5577                         }
5578                         leaf = path->nodes[0];
5579                         nritems = btrfs_header_nritems(leaf);
5580                 }
5581
5582                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5583
5584                 if (key.objectid >= block_group->key.objectid +
5585                     block_group->key.offset)
5586                         break;
5587
5588                 if (progress && need_resched()) {
5589                         btrfs_release_path(root, path);
5590                         cond_resched();
5591                         progress = 0;
5592                         continue;
5593                 }
5594                 progress = 1;
5595
5596                 if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY ||
5597                     key.objectid + key.offset <= cur_byte) {
5598                         path->slots[0]++;
5599                         goto next;
5600                 }
5601
5602                 total_found++;
5603                 cur_byte = key.objectid + key.offset;
5604                 btrfs_release_path(root, path);
5605
5606                 __alloc_chunk_for_shrink(root, block_group, 0);
5607                 ret = relocate_one_extent(root, path, &key, block_group,
5608                                           reloc_inode, pass);
5609                 BUG_ON(ret < 0);
5610                 if (ret > 0)
5611                         skipped++;
5612
5613                 key.objectid = cur_byte;
5614                 key.type = 0;
5615                 key.offset = 0;
5616         }
5617
5618         btrfs_release_path(root, path);
5619
5620         if (pass == 0) {
5621                 btrfs_wait_ordered_range(reloc_inode, 0, (u64)-1);
5622                 invalidate_mapping_pages(reloc_inode->i_mapping, 0, -1);
5623         }
5624
5625         if (total_found > 0) {
5626                 printk(KERN_INFO "btrfs found %llu extents in pass %d\n",
5627                        (unsigned long long)total_found, pass);
5628                 pass++;
5629                 if (total_found == skipped && pass > 2) {
5630                         iput(reloc_inode);
5631                         reloc_inode = create_reloc_inode(info, block_group);
5632                         pass = 0;
5633                 }
5634                 goto again;
5635         }
5636
5637         /* delete reloc_inode */
5638         iput(reloc_inode);
5639
5640         /* unpin extents in this range */
5641         trans = btrfs_start_transaction(info->tree_root, 1);
5642         btrfs_commit_transaction(trans, info->tree_root);
5643
5644         spin_lock(&block_group->lock);
5645         WARN_ON(block_group->pinned > 0);
5646         WARN_ON(block_group->reserved > 0);
5647         WARN_ON(btrfs_block_group_used(&block_group->item) > 0);
5648         spin_unlock(&block_group->lock);
5649         put_block_group(block_group);
5650         ret = 0;
5651 out:
5652         btrfs_free_path(path);
5653         return ret;
5654 }
5655
5656 static int find_first_block_group(struct btrfs_root *root,
5657                 struct btrfs_path *path, struct btrfs_key *key)
5658 {
5659         int ret = 0;
5660         struct btrfs_key found_key;
5661         struct extent_buffer *leaf;
5662         int slot;
5663
5664         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
5665         if (ret < 0)
5666                 goto out;
5667
5668         while (1) {
5669                 slot = path->slots[0];
5670                 leaf = path->nodes[0];
5671                 if (slot >= btrfs_header_nritems(leaf)) {
5672                         ret = btrfs_next_leaf(root, path);
5673                         if (ret == 0)
5674                                 continue;
5675                         if (ret < 0)
5676                                 goto out;
5677                         break;
5678                 }
5679                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5680
5681                 if (found_key.objectid >= key->objectid &&
5682                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5683                         ret = 0;
5684                         goto out;
5685                 }
5686                 path->slots[0]++;
5687         }
5688         ret = -ENOENT;
5689 out:
5690         return ret;
5691 }
5692
5693 int btrfs_free_block_groups(struct btrfs_fs_info *info)
5694 {
5695         struct btrfs_block_group_cache *block_group;
5696         struct btrfs_space_info *space_info;
5697         struct rb_node *n;
5698
5699         spin_lock(&info->block_group_cache_lock);
5700         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
5701                 block_group = rb_entry(n, struct btrfs_block_group_cache,
5702                                        cache_node);
5703                 rb_erase(&block_group->cache_node,
5704                          &info->block_group_cache_tree);
5705                 spin_unlock(&info->block_group_cache_lock);
5706
5707                 btrfs_remove_free_space_cache(block_group);
5708                 down_write(&block_group->space_info->groups_sem);
5709                 list_del(&block_group->list);
5710                 up_write(&block_group->space_info->groups_sem);
5711
5712                 WARN_ON(atomic_read(&block_group->count) != 1);
5713                 kfree(block_group);
5714
5715                 spin_lock(&info->block_group_cache_lock);
5716         }
5717         spin_unlock(&info->block_group_cache_lock);
5718
5719         /* now that all the block groups are freed, go through and
5720          * free all the space_info structs.  This is only called during
5721          * the final stages of unmount, and so we know nobody is
5722          * using them.  We call synchronize_rcu() once before we start,
5723          * just to be on the safe side.
5724          */
5725         synchronize_rcu();
5726
5727         while(!list_empty(&info->space_info)) {
5728                 space_info = list_entry(info->space_info.next,
5729                                         struct btrfs_space_info,
5730                                         list);
5731
5732                 list_del(&space_info->list);
5733                 kfree(space_info);
5734         }
5735         return 0;
5736 }
5737
5738 int btrfs_read_block_groups(struct btrfs_root *root)
5739 {
5740         struct btrfs_path *path;
5741         int ret;
5742         struct btrfs_block_group_cache *cache;
5743         struct btrfs_fs_info *info = root->fs_info;
5744         struct btrfs_space_info *space_info;
5745         struct btrfs_key key;
5746         struct btrfs_key found_key;
5747         struct extent_buffer *leaf;
5748
5749         root = info->extent_root;
5750         key.objectid = 0;
5751         key.offset = 0;
5752         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
5753         path = btrfs_alloc_path();
5754         if (!path)
5755                 return -ENOMEM;
5756
5757         while (1) {
5758                 ret = find_first_block_group(root, path, &key);
5759                 if (ret > 0) {
5760                         ret = 0;
5761                         goto error;
5762                 }
5763                 if (ret != 0)
5764                         goto error;
5765
5766                 leaf = path->nodes[0];
5767                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5768                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
5769                 if (!cache) {
5770                         ret = -ENOMEM;
5771                         break;
5772                 }
5773
5774                 atomic_set(&cache->count, 1);
5775                 spin_lock_init(&cache->lock);
5776                 mutex_init(&cache->alloc_mutex);
5777                 mutex_init(&cache->cache_mutex);
5778                 INIT_LIST_HEAD(&cache->list);
5779                 read_extent_buffer(leaf, &cache->item,
5780                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
5781                                    sizeof(cache->item));
5782                 memcpy(&cache->key, &found_key, sizeof(found_key));
5783
5784                 key.objectid = found_key.objectid + found_key.offset;
5785                 btrfs_release_path(root, path);
5786                 cache->flags = btrfs_block_group_flags(&cache->item);
5787
5788                 ret = update_space_info(info, cache->flags, found_key.offset,
5789                                         btrfs_block_group_used(&cache->item),
5790                                         &space_info);
5791                 BUG_ON(ret);
5792                 cache->space_info = space_info;
5793                 down_write(&space_info->groups_sem);
5794                 list_add_tail(&cache->list, &space_info->block_groups);
5795                 up_write(&space_info->groups_sem);
5796
5797                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
5798                 BUG_ON(ret);
5799
5800                 set_avail_alloc_bits(root->fs_info, cache->flags);
5801                 if (btrfs_chunk_readonly(root, cache->key.objectid))
5802                         set_block_group_readonly(cache);
5803         }
5804         ret = 0;
5805 error:
5806         btrfs_free_path(path);
5807         return ret;
5808 }
5809
5810 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
5811                            struct btrfs_root *root, u64 bytes_used,
5812                            u64 type, u64 chunk_objectid, u64 chunk_offset,
5813                            u64 size)
5814 {
5815         int ret;
5816         struct btrfs_root *extent_root;
5817         struct btrfs_block_group_cache *cache;
5818
5819         extent_root = root->fs_info->extent_root;
5820
5821         root->fs_info->last_trans_new_blockgroup = trans->transid;
5822
5823         cache = kzalloc(sizeof(*cache), GFP_NOFS);
5824         if (!cache)
5825                 return -ENOMEM;
5826
5827         cache->key.objectid = chunk_offset;
5828         cache->key.offset = size;
5829         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
5830         atomic_set(&cache->count, 1);
5831         spin_lock_init(&cache->lock);
5832         mutex_init(&cache->alloc_mutex);
5833         mutex_init(&cache->cache_mutex);
5834         INIT_LIST_HEAD(&cache->list);
5835
5836         btrfs_set_block_group_used(&cache->item, bytes_used);
5837         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
5838         cache->flags = type;
5839         btrfs_set_block_group_flags(&cache->item, type);
5840
5841         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
5842                                 &cache->space_info);
5843         BUG_ON(ret);
5844         down_write(&cache->space_info->groups_sem);
5845         list_add_tail(&cache->list, &cache->space_info->block_groups);
5846         up_write(&cache->space_info->groups_sem);
5847
5848         ret = btrfs_add_block_group_cache(root->fs_info, cache);
5849         BUG_ON(ret);
5850
5851         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
5852                                 sizeof(cache->item));
5853         BUG_ON(ret);
5854
5855         set_avail_alloc_bits(extent_root->fs_info, type);
5856
5857         return 0;
5858 }
5859
5860 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
5861                              struct btrfs_root *root, u64 group_start)
5862 {
5863         struct btrfs_path *path;
5864         struct btrfs_block_group_cache *block_group;
5865         struct btrfs_key key;
5866         int ret;
5867
5868         root = root->fs_info->extent_root;
5869
5870         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
5871         BUG_ON(!block_group);
5872         BUG_ON(!block_group->ro);
5873
5874         memcpy(&key, &block_group->key, sizeof(key));
5875
5876         path = btrfs_alloc_path();
5877         BUG_ON(!path);
5878
5879         spin_lock(&root->fs_info->block_group_cache_lock);
5880         rb_erase(&block_group->cache_node,
5881                  &root->fs_info->block_group_cache_tree);
5882         spin_unlock(&root->fs_info->block_group_cache_lock);
5883         btrfs_remove_free_space_cache(block_group);
5884         down_write(&block_group->space_info->groups_sem);
5885         list_del(&block_group->list);
5886         up_write(&block_group->space_info->groups_sem);
5887
5888         spin_lock(&block_group->space_info->lock);
5889         block_group->space_info->total_bytes -= block_group->key.offset;
5890         block_group->space_info->bytes_readonly -= block_group->key.offset;
5891         spin_unlock(&block_group->space_info->lock);
5892         block_group->space_info->full = 0;
5893
5894         put_block_group(block_group);
5895         put_block_group(block_group);
5896
5897         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5898         if (ret > 0)
5899                 ret = -EIO;
5900         if (ret < 0)
5901                 goto out;
5902
5903         ret = btrfs_del_item(trans, root, path);
5904 out:
5905         btrfs_free_path(path);
5906         return ret;
5907 }