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