Btrfs: remove unnecessary dget_parent/dput when creating the pending snapshot
[deliverable/linux.git] / fs / btrfs / extent-tree.c
CommitLineData
6cbd5570
CM
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 */
ec6b910f 18#include <linux/sched.h>
edbd8d4e 19#include <linux/pagemap.h>
ec44a35c 20#include <linux/writeback.h>
21af804c 21#include <linux/blkdev.h>
b7a9f29f 22#include <linux/sort.h>
4184ea7f 23#include <linux/rcupdate.h>
817d52f8 24#include <linux/kthread.h>
5a0e3ad6 25#include <linux/slab.h>
dff51cd1 26#include <linux/ratelimit.h>
4b4e25f2 27#include "compat.h"
74493f7a 28#include "hash.h"
fec577fb
CM
29#include "ctree.h"
30#include "disk-io.h"
31#include "print-tree.h"
e089f05c 32#include "transaction.h"
0b86a832 33#include "volumes.h"
53b381b3 34#include "raid56.h"
925baedd 35#include "locking.h"
fa9c0d79 36#include "free-space-cache.h"
3fed40cc 37#include "math.h"
fec577fb 38
709c0486
AJ
39#undef SCRAMBLE_DELAYED_REFS
40
9e622d6b
MX
41/*
42 * control flags for do_chunk_alloc's force field
0e4f8f88
CM
43 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
44 * if we really need one.
45 *
0e4f8f88
CM
46 * CHUNK_ALLOC_LIMITED means to only try and allocate one
47 * if we have very few chunks already allocated. This is
48 * used as part of the clustering code to help make sure
49 * we have a good pool of storage to cluster in, without
50 * filling the FS with empty chunks
51 *
9e622d6b
MX
52 * CHUNK_ALLOC_FORCE means it must try to allocate one
53 *
0e4f8f88
CM
54 */
55enum {
56 CHUNK_ALLOC_NO_FORCE = 0,
9e622d6b
MX
57 CHUNK_ALLOC_LIMITED = 1,
58 CHUNK_ALLOC_FORCE = 2,
0e4f8f88
CM
59};
60
fb25e914
JB
61/*
62 * Control how reservations are dealt with.
63 *
64 * RESERVE_FREE - freeing a reservation.
65 * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
66 * ENOSPC accounting
67 * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
68 * bytes_may_use as the ENOSPC accounting is done elsewhere
69 */
70enum {
71 RESERVE_FREE = 0,
72 RESERVE_ALLOC = 1,
73 RESERVE_ALLOC_NO_ACCOUNT = 2,
74};
75
c53d613e 76static int update_block_group(struct btrfs_root *root,
f0486c68 77 u64 bytenr, u64 num_bytes, int alloc);
5d4f98a2
YZ
78static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
79 struct btrfs_root *root,
80 u64 bytenr, u64 num_bytes, u64 parent,
81 u64 root_objectid, u64 owner_objectid,
82 u64 owner_offset, int refs_to_drop,
83 struct btrfs_delayed_extent_op *extra_op);
84static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
85 struct extent_buffer *leaf,
86 struct btrfs_extent_item *ei);
87static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
88 struct btrfs_root *root,
89 u64 parent, u64 root_objectid,
90 u64 flags, u64 owner, u64 offset,
91 struct btrfs_key *ins, int ref_mod);
92static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
93 struct btrfs_root *root,
94 u64 parent, u64 root_objectid,
95 u64 flags, struct btrfs_disk_key *key,
96 int level, struct btrfs_key *ins);
6a63209f 97static int do_chunk_alloc(struct btrfs_trans_handle *trans,
698d0082
JB
98 struct btrfs_root *extent_root, u64 flags,
99 int force);
11833d66
YZ
100static int find_next_key(struct btrfs_path *path, int level,
101 struct btrfs_key *key);
9ed74f2d
JB
102static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
103 int dump_block_groups);
fb25e914
JB
104static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
105 u64 num_bytes, int reserve);
5d80366e
JB
106static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
107 u64 num_bytes);
6a63209f 108
817d52f8
JB
109static noinline int
110block_group_cache_done(struct btrfs_block_group_cache *cache)
111{
112 smp_mb();
113 return cache->cached == BTRFS_CACHE_FINISHED;
114}
115
0f9dd46c
JB
116static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
117{
118 return (cache->flags & bits) == bits;
119}
120
62a45b60 121static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
11dfe35a
JB
122{
123 atomic_inc(&cache->count);
124}
125
126void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
127{
f0486c68
YZ
128 if (atomic_dec_and_test(&cache->count)) {
129 WARN_ON(cache->pinned > 0);
130 WARN_ON(cache->reserved > 0);
34d52cb6 131 kfree(cache->free_space_ctl);
11dfe35a 132 kfree(cache);
f0486c68 133 }
11dfe35a
JB
134}
135
0f9dd46c
JB
136/*
137 * this adds the block group to the fs_info rb tree for the block group
138 * cache
139 */
b2950863 140static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
0f9dd46c
JB
141 struct btrfs_block_group_cache *block_group)
142{
143 struct rb_node **p;
144 struct rb_node *parent = NULL;
145 struct btrfs_block_group_cache *cache;
146
147 spin_lock(&info->block_group_cache_lock);
148 p = &info->block_group_cache_tree.rb_node;
149
150 while (*p) {
151 parent = *p;
152 cache = rb_entry(parent, struct btrfs_block_group_cache,
153 cache_node);
154 if (block_group->key.objectid < cache->key.objectid) {
155 p = &(*p)->rb_left;
156 } else if (block_group->key.objectid > cache->key.objectid) {
157 p = &(*p)->rb_right;
158 } else {
159 spin_unlock(&info->block_group_cache_lock);
160 return -EEXIST;
161 }
162 }
163
164 rb_link_node(&block_group->cache_node, parent, p);
165 rb_insert_color(&block_group->cache_node,
166 &info->block_group_cache_tree);
a1897fdd
LB
167
168 if (info->first_logical_byte > block_group->key.objectid)
169 info->first_logical_byte = block_group->key.objectid;
170
0f9dd46c
JB
171 spin_unlock(&info->block_group_cache_lock);
172
173 return 0;
174}
175
176/*
177 * This will return the block group at or after bytenr if contains is 0, else
178 * it will return the block group that contains the bytenr
179 */
180static struct btrfs_block_group_cache *
181block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
182 int contains)
183{
184 struct btrfs_block_group_cache *cache, *ret = NULL;
185 struct rb_node *n;
186 u64 end, start;
187
188 spin_lock(&info->block_group_cache_lock);
189 n = info->block_group_cache_tree.rb_node;
190
191 while (n) {
192 cache = rb_entry(n, struct btrfs_block_group_cache,
193 cache_node);
194 end = cache->key.objectid + cache->key.offset - 1;
195 start = cache->key.objectid;
196
197 if (bytenr < start) {
198 if (!contains && (!ret || start < ret->key.objectid))
199 ret = cache;
200 n = n->rb_left;
201 } else if (bytenr > start) {
202 if (contains && bytenr <= end) {
203 ret = cache;
204 break;
205 }
206 n = n->rb_right;
207 } else {
208 ret = cache;
209 break;
210 }
211 }
a1897fdd 212 if (ret) {
11dfe35a 213 btrfs_get_block_group(ret);
a1897fdd
LB
214 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
215 info->first_logical_byte = ret->key.objectid;
216 }
0f9dd46c
JB
217 spin_unlock(&info->block_group_cache_lock);
218
219 return ret;
220}
221
11833d66
YZ
222static int add_excluded_extent(struct btrfs_root *root,
223 u64 start, u64 num_bytes)
817d52f8 224{
11833d66
YZ
225 u64 end = start + num_bytes - 1;
226 set_extent_bits(&root->fs_info->freed_extents[0],
227 start, end, EXTENT_UPTODATE, GFP_NOFS);
228 set_extent_bits(&root->fs_info->freed_extents[1],
229 start, end, EXTENT_UPTODATE, GFP_NOFS);
230 return 0;
231}
817d52f8 232
11833d66
YZ
233static void free_excluded_extents(struct btrfs_root *root,
234 struct btrfs_block_group_cache *cache)
235{
236 u64 start, end;
817d52f8 237
11833d66
YZ
238 start = cache->key.objectid;
239 end = start + cache->key.offset - 1;
240
241 clear_extent_bits(&root->fs_info->freed_extents[0],
242 start, end, EXTENT_UPTODATE, GFP_NOFS);
243 clear_extent_bits(&root->fs_info->freed_extents[1],
244 start, end, EXTENT_UPTODATE, GFP_NOFS);
817d52f8
JB
245}
246
11833d66
YZ
247static int exclude_super_stripes(struct btrfs_root *root,
248 struct btrfs_block_group_cache *cache)
817d52f8 249{
817d52f8
JB
250 u64 bytenr;
251 u64 *logical;
252 int stripe_len;
253 int i, nr, ret;
254
06b2331f
YZ
255 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
256 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
257 cache->bytes_super += stripe_len;
258 ret = add_excluded_extent(root, cache->key.objectid,
259 stripe_len);
79787eaa 260 BUG_ON(ret); /* -ENOMEM */
06b2331f
YZ
261 }
262
817d52f8
JB
263 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
264 bytenr = btrfs_sb_offset(i);
265 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
266 cache->key.objectid, bytenr,
267 0, &logical, &nr, &stripe_len);
79787eaa 268 BUG_ON(ret); /* -ENOMEM */
11833d66 269
817d52f8 270 while (nr--) {
1b2da372 271 cache->bytes_super += stripe_len;
11833d66
YZ
272 ret = add_excluded_extent(root, logical[nr],
273 stripe_len);
79787eaa 274 BUG_ON(ret); /* -ENOMEM */
817d52f8 275 }
11833d66 276
817d52f8
JB
277 kfree(logical);
278 }
817d52f8
JB
279 return 0;
280}
281
11833d66
YZ
282static struct btrfs_caching_control *
283get_caching_control(struct btrfs_block_group_cache *cache)
284{
285 struct btrfs_caching_control *ctl;
286
287 spin_lock(&cache->lock);
288 if (cache->cached != BTRFS_CACHE_STARTED) {
289 spin_unlock(&cache->lock);
290 return NULL;
291 }
292
dde5abee
JB
293 /* We're loading it the fast way, so we don't have a caching_ctl. */
294 if (!cache->caching_ctl) {
295 spin_unlock(&cache->lock);
11833d66
YZ
296 return NULL;
297 }
298
299 ctl = cache->caching_ctl;
300 atomic_inc(&ctl->count);
301 spin_unlock(&cache->lock);
302 return ctl;
303}
304
305static void put_caching_control(struct btrfs_caching_control *ctl)
306{
307 if (atomic_dec_and_test(&ctl->count))
308 kfree(ctl);
309}
310
0f9dd46c
JB
311/*
312 * this is only called by cache_block_group, since we could have freed extents
313 * we need to check the pinned_extents for any extents that can't be used yet
314 * since their free space will be released as soon as the transaction commits.
315 */
817d52f8 316static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
0f9dd46c
JB
317 struct btrfs_fs_info *info, u64 start, u64 end)
318{
817d52f8 319 u64 extent_start, extent_end, size, total_added = 0;
0f9dd46c
JB
320 int ret;
321
322 while (start < end) {
11833d66 323 ret = find_first_extent_bit(info->pinned_extents, start,
0f9dd46c 324 &extent_start, &extent_end,
e6138876
JB
325 EXTENT_DIRTY | EXTENT_UPTODATE,
326 NULL);
0f9dd46c
JB
327 if (ret)
328 break;
329
06b2331f 330 if (extent_start <= start) {
0f9dd46c
JB
331 start = extent_end + 1;
332 } else if (extent_start > start && extent_start < end) {
333 size = extent_start - start;
817d52f8 334 total_added += size;
ea6a478e
JB
335 ret = btrfs_add_free_space(block_group, start,
336 size);
79787eaa 337 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
338 start = extent_end + 1;
339 } else {
340 break;
341 }
342 }
343
344 if (start < end) {
345 size = end - start;
817d52f8 346 total_added += size;
ea6a478e 347 ret = btrfs_add_free_space(block_group, start, size);
79787eaa 348 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
349 }
350
817d52f8 351 return total_added;
0f9dd46c
JB
352}
353
bab39bf9 354static noinline void caching_thread(struct btrfs_work *work)
e37c9e69 355{
bab39bf9
JB
356 struct btrfs_block_group_cache *block_group;
357 struct btrfs_fs_info *fs_info;
358 struct btrfs_caching_control *caching_ctl;
359 struct btrfs_root *extent_root;
e37c9e69 360 struct btrfs_path *path;
5f39d397 361 struct extent_buffer *leaf;
11833d66 362 struct btrfs_key key;
817d52f8 363 u64 total_found = 0;
11833d66
YZ
364 u64 last = 0;
365 u32 nritems;
366 int ret = 0;
f510cfec 367
bab39bf9
JB
368 caching_ctl = container_of(work, struct btrfs_caching_control, work);
369 block_group = caching_ctl->block_group;
370 fs_info = block_group->fs_info;
371 extent_root = fs_info->extent_root;
372
e37c9e69
CM
373 path = btrfs_alloc_path();
374 if (!path)
bab39bf9 375 goto out;
7d7d6068 376
817d52f8 377 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
11833d66 378
5cd57b2c 379 /*
817d52f8
JB
380 * We don't want to deadlock with somebody trying to allocate a new
381 * extent for the extent root while also trying to search the extent
382 * root to add free space. So we skip locking and search the commit
383 * root, since its read-only
5cd57b2c
CM
384 */
385 path->skip_locking = 1;
817d52f8 386 path->search_commit_root = 1;
026fd317 387 path->reada = 1;
817d52f8 388
e4404d6e 389 key.objectid = last;
e37c9e69 390 key.offset = 0;
11833d66 391 key.type = BTRFS_EXTENT_ITEM_KEY;
013f1b12 392again:
11833d66 393 mutex_lock(&caching_ctl->mutex);
013f1b12
CM
394 /* need to make sure the commit_root doesn't disappear */
395 down_read(&fs_info->extent_commit_sem);
396
11833d66 397 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
e37c9e69 398 if (ret < 0)
ef8bbdfe 399 goto err;
a512bbf8 400
11833d66
YZ
401 leaf = path->nodes[0];
402 nritems = btrfs_header_nritems(leaf);
403
d397712b 404 while (1) {
7841cb28 405 if (btrfs_fs_closing(fs_info) > 1) {
f25784b3 406 last = (u64)-1;
817d52f8 407 break;
f25784b3 408 }
817d52f8 409
11833d66
YZ
410 if (path->slots[0] < nritems) {
411 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
412 } else {
413 ret = find_next_key(path, 0, &key);
414 if (ret)
e37c9e69 415 break;
817d52f8 416
589d8ade
JB
417 if (need_resched() ||
418 btrfs_next_leaf(extent_root, path)) {
419 caching_ctl->progress = last;
ff5714cc 420 btrfs_release_path(path);
589d8ade
JB
421 up_read(&fs_info->extent_commit_sem);
422 mutex_unlock(&caching_ctl->mutex);
11833d66 423 cond_resched();
589d8ade
JB
424 goto again;
425 }
426 leaf = path->nodes[0];
427 nritems = btrfs_header_nritems(leaf);
428 continue;
11833d66 429 }
817d52f8 430
11833d66
YZ
431 if (key.objectid < block_group->key.objectid) {
432 path->slots[0]++;
817d52f8 433 continue;
e37c9e69 434 }
0f9dd46c 435
e37c9e69 436 if (key.objectid >= block_group->key.objectid +
0f9dd46c 437 block_group->key.offset)
e37c9e69 438 break;
7d7d6068 439
11833d66 440 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
817d52f8
JB
441 total_found += add_new_free_space(block_group,
442 fs_info, last,
443 key.objectid);
7d7d6068 444 last = key.objectid + key.offset;
817d52f8 445
11833d66
YZ
446 if (total_found > (1024 * 1024 * 2)) {
447 total_found = 0;
448 wake_up(&caching_ctl->wait);
449 }
817d52f8 450 }
e37c9e69
CM
451 path->slots[0]++;
452 }
817d52f8 453 ret = 0;
e37c9e69 454
817d52f8
JB
455 total_found += add_new_free_space(block_group, fs_info, last,
456 block_group->key.objectid +
457 block_group->key.offset);
11833d66 458 caching_ctl->progress = (u64)-1;
817d52f8
JB
459
460 spin_lock(&block_group->lock);
11833d66 461 block_group->caching_ctl = NULL;
817d52f8
JB
462 block_group->cached = BTRFS_CACHE_FINISHED;
463 spin_unlock(&block_group->lock);
0f9dd46c 464
54aa1f4d 465err:
e37c9e69 466 btrfs_free_path(path);
276e680d 467 up_read(&fs_info->extent_commit_sem);
817d52f8 468
11833d66
YZ
469 free_excluded_extents(extent_root, block_group);
470
471 mutex_unlock(&caching_ctl->mutex);
bab39bf9 472out:
11833d66
YZ
473 wake_up(&caching_ctl->wait);
474
475 put_caching_control(caching_ctl);
11dfe35a 476 btrfs_put_block_group(block_group);
817d52f8
JB
477}
478
9d66e233 479static int cache_block_group(struct btrfs_block_group_cache *cache,
9d66e233 480 int load_cache_only)
817d52f8 481{
291c7d2f 482 DEFINE_WAIT(wait);
11833d66
YZ
483 struct btrfs_fs_info *fs_info = cache->fs_info;
484 struct btrfs_caching_control *caching_ctl;
817d52f8
JB
485 int ret = 0;
486
291c7d2f 487 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
79787eaa
JM
488 if (!caching_ctl)
489 return -ENOMEM;
291c7d2f
JB
490
491 INIT_LIST_HEAD(&caching_ctl->list);
492 mutex_init(&caching_ctl->mutex);
493 init_waitqueue_head(&caching_ctl->wait);
494 caching_ctl->block_group = cache;
495 caching_ctl->progress = cache->key.objectid;
496 atomic_set(&caching_ctl->count, 1);
497 caching_ctl->work.func = caching_thread;
498
499 spin_lock(&cache->lock);
500 /*
501 * This should be a rare occasion, but this could happen I think in the
502 * case where one thread starts to load the space cache info, and then
503 * some other thread starts a transaction commit which tries to do an
504 * allocation while the other thread is still loading the space cache
505 * info. The previous loop should have kept us from choosing this block
506 * group, but if we've moved to the state where we will wait on caching
507 * block groups we need to first check if we're doing a fast load here,
508 * so we can wait for it to finish, otherwise we could end up allocating
509 * from a block group who's cache gets evicted for one reason or
510 * another.
511 */
512 while (cache->cached == BTRFS_CACHE_FAST) {
513 struct btrfs_caching_control *ctl;
514
515 ctl = cache->caching_ctl;
516 atomic_inc(&ctl->count);
517 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
518 spin_unlock(&cache->lock);
519
520 schedule();
521
522 finish_wait(&ctl->wait, &wait);
523 put_caching_control(ctl);
524 spin_lock(&cache->lock);
525 }
526
527 if (cache->cached != BTRFS_CACHE_NO) {
528 spin_unlock(&cache->lock);
529 kfree(caching_ctl);
11833d66 530 return 0;
291c7d2f
JB
531 }
532 WARN_ON(cache->caching_ctl);
533 cache->caching_ctl = caching_ctl;
534 cache->cached = BTRFS_CACHE_FAST;
535 spin_unlock(&cache->lock);
11833d66 536
d53ba474 537 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
9d66e233
JB
538 ret = load_free_space_cache(fs_info, cache);
539
540 spin_lock(&cache->lock);
541 if (ret == 1) {
291c7d2f 542 cache->caching_ctl = NULL;
9d66e233
JB
543 cache->cached = BTRFS_CACHE_FINISHED;
544 cache->last_byte_to_unpin = (u64)-1;
545 } else {
291c7d2f
JB
546 if (load_cache_only) {
547 cache->caching_ctl = NULL;
548 cache->cached = BTRFS_CACHE_NO;
549 } else {
550 cache->cached = BTRFS_CACHE_STARTED;
551 }
9d66e233
JB
552 }
553 spin_unlock(&cache->lock);
291c7d2f 554 wake_up(&caching_ctl->wait);
3c14874a 555 if (ret == 1) {
291c7d2f 556 put_caching_control(caching_ctl);
3c14874a 557 free_excluded_extents(fs_info->extent_root, cache);
9d66e233 558 return 0;
3c14874a 559 }
291c7d2f
JB
560 } else {
561 /*
562 * We are not going to do the fast caching, set cached to the
563 * appropriate value and wakeup any waiters.
564 */
565 spin_lock(&cache->lock);
566 if (load_cache_only) {
567 cache->caching_ctl = NULL;
568 cache->cached = BTRFS_CACHE_NO;
569 } else {
570 cache->cached = BTRFS_CACHE_STARTED;
571 }
572 spin_unlock(&cache->lock);
573 wake_up(&caching_ctl->wait);
9d66e233
JB
574 }
575
291c7d2f
JB
576 if (load_cache_only) {
577 put_caching_control(caching_ctl);
11833d66 578 return 0;
817d52f8 579 }
817d52f8 580
11833d66 581 down_write(&fs_info->extent_commit_sem);
291c7d2f 582 atomic_inc(&caching_ctl->count);
11833d66
YZ
583 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
584 up_write(&fs_info->extent_commit_sem);
585
11dfe35a 586 btrfs_get_block_group(cache);
11833d66 587
bab39bf9 588 btrfs_queue_worker(&fs_info->caching_workers, &caching_ctl->work);
817d52f8 589
ef8bbdfe 590 return ret;
e37c9e69
CM
591}
592
0f9dd46c
JB
593/*
594 * return the block group that starts at or after bytenr
595 */
d397712b
CM
596static struct btrfs_block_group_cache *
597btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
0ef3e66b 598{
0f9dd46c 599 struct btrfs_block_group_cache *cache;
0ef3e66b 600
0f9dd46c 601 cache = block_group_cache_tree_search(info, bytenr, 0);
0ef3e66b 602
0f9dd46c 603 return cache;
0ef3e66b
CM
604}
605
0f9dd46c 606/*
9f55684c 607 * return the block group that contains the given bytenr
0f9dd46c 608 */
d397712b
CM
609struct btrfs_block_group_cache *btrfs_lookup_block_group(
610 struct btrfs_fs_info *info,
611 u64 bytenr)
be744175 612{
0f9dd46c 613 struct btrfs_block_group_cache *cache;
be744175 614
0f9dd46c 615 cache = block_group_cache_tree_search(info, bytenr, 1);
96b5179d 616
0f9dd46c 617 return cache;
be744175 618}
0b86a832 619
0f9dd46c
JB
620static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
621 u64 flags)
6324fbf3 622{
0f9dd46c 623 struct list_head *head = &info->space_info;
0f9dd46c 624 struct btrfs_space_info *found;
4184ea7f 625
52ba6929 626 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
b742bb82 627
4184ea7f
CM
628 rcu_read_lock();
629 list_for_each_entry_rcu(found, head, list) {
67377734 630 if (found->flags & flags) {
4184ea7f 631 rcu_read_unlock();
0f9dd46c 632 return found;
4184ea7f 633 }
0f9dd46c 634 }
4184ea7f 635 rcu_read_unlock();
0f9dd46c 636 return NULL;
6324fbf3
CM
637}
638
4184ea7f
CM
639/*
640 * after adding space to the filesystem, we need to clear the full flags
641 * on all the space infos.
642 */
643void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
644{
645 struct list_head *head = &info->space_info;
646 struct btrfs_space_info *found;
647
648 rcu_read_lock();
649 list_for_each_entry_rcu(found, head, list)
650 found->full = 0;
651 rcu_read_unlock();
652}
653
d2fb3437
YZ
654u64 btrfs_find_block_group(struct btrfs_root *root,
655 u64 search_start, u64 search_hint, int owner)
cd1bc465 656{
96b5179d 657 struct btrfs_block_group_cache *cache;
cd1bc465 658 u64 used;
d2fb3437
YZ
659 u64 last = max(search_hint, search_start);
660 u64 group_start = 0;
31f3c99b 661 int full_search = 0;
d2fb3437 662 int factor = 9;
0ef3e66b 663 int wrapped = 0;
31f3c99b 664again:
e8569813
ZY
665 while (1) {
666 cache = btrfs_lookup_first_block_group(root->fs_info, last);
0f9dd46c
JB
667 if (!cache)
668 break;
96b5179d 669
c286ac48 670 spin_lock(&cache->lock);
96b5179d
CM
671 last = cache->key.objectid + cache->key.offset;
672 used = btrfs_block_group_used(&cache->item);
673
d2fb3437
YZ
674 if ((full_search || !cache->ro) &&
675 block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
e8569813 676 if (used + cache->pinned + cache->reserved <
d2fb3437
YZ
677 div_factor(cache->key.offset, factor)) {
678 group_start = cache->key.objectid;
c286ac48 679 spin_unlock(&cache->lock);
fa9c0d79 680 btrfs_put_block_group(cache);
8790d502
CM
681 goto found;
682 }
6324fbf3 683 }
c286ac48 684 spin_unlock(&cache->lock);
fa9c0d79 685 btrfs_put_block_group(cache);
de428b63 686 cond_resched();
cd1bc465 687 }
0ef3e66b
CM
688 if (!wrapped) {
689 last = search_start;
690 wrapped = 1;
691 goto again;
692 }
693 if (!full_search && factor < 10) {
be744175 694 last = search_start;
31f3c99b 695 full_search = 1;
0ef3e66b 696 factor = 10;
31f3c99b
CM
697 goto again;
698 }
be744175 699found:
d2fb3437 700 return group_start;
925baedd 701}
0f9dd46c 702
e02119d5 703/* simple helper to search for an existing extent at a given offset */
31840ae1 704int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
e02119d5
CM
705{
706 int ret;
707 struct btrfs_key key;
31840ae1 708 struct btrfs_path *path;
e02119d5 709
31840ae1 710 path = btrfs_alloc_path();
d8926bb3
MF
711 if (!path)
712 return -ENOMEM;
713
e02119d5
CM
714 key.objectid = start;
715 key.offset = len;
716 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
717 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
718 0, 0);
31840ae1 719 btrfs_free_path(path);
7bb86316
CM
720 return ret;
721}
722
a22285a6
YZ
723/*
724 * helper function to lookup reference count and flags of extent.
725 *
726 * the head node for delayed ref is used to store the sum of all the
727 * reference count modifications queued up in the rbtree. the head
728 * node may also store the extent flags to set. This way you can check
729 * to see what the reference count and extent flags would be if all of
730 * the delayed refs are not processed.
731 */
732int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
733 struct btrfs_root *root, u64 bytenr,
734 u64 num_bytes, u64 *refs, u64 *flags)
735{
736 struct btrfs_delayed_ref_head *head;
737 struct btrfs_delayed_ref_root *delayed_refs;
738 struct btrfs_path *path;
739 struct btrfs_extent_item *ei;
740 struct extent_buffer *leaf;
741 struct btrfs_key key;
742 u32 item_size;
743 u64 num_refs;
744 u64 extent_flags;
745 int ret;
746
747 path = btrfs_alloc_path();
748 if (!path)
749 return -ENOMEM;
750
751 key.objectid = bytenr;
752 key.type = BTRFS_EXTENT_ITEM_KEY;
753 key.offset = num_bytes;
754 if (!trans) {
755 path->skip_locking = 1;
756 path->search_commit_root = 1;
757 }
758again:
759 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
760 &key, path, 0, 0);
761 if (ret < 0)
762 goto out_free;
763
764 if (ret == 0) {
765 leaf = path->nodes[0];
766 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
767 if (item_size >= sizeof(*ei)) {
768 ei = btrfs_item_ptr(leaf, path->slots[0],
769 struct btrfs_extent_item);
770 num_refs = btrfs_extent_refs(leaf, ei);
771 extent_flags = btrfs_extent_flags(leaf, ei);
772 } else {
773#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
774 struct btrfs_extent_item_v0 *ei0;
775 BUG_ON(item_size != sizeof(*ei0));
776 ei0 = btrfs_item_ptr(leaf, path->slots[0],
777 struct btrfs_extent_item_v0);
778 num_refs = btrfs_extent_refs_v0(leaf, ei0);
779 /* FIXME: this isn't correct for data */
780 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
781#else
782 BUG();
783#endif
784 }
785 BUG_ON(num_refs == 0);
786 } else {
787 num_refs = 0;
788 extent_flags = 0;
789 ret = 0;
790 }
791
792 if (!trans)
793 goto out;
794
795 delayed_refs = &trans->transaction->delayed_refs;
796 spin_lock(&delayed_refs->lock);
797 head = btrfs_find_delayed_ref_head(trans, bytenr);
798 if (head) {
799 if (!mutex_trylock(&head->mutex)) {
800 atomic_inc(&head->node.refs);
801 spin_unlock(&delayed_refs->lock);
802
b3b4aa74 803 btrfs_release_path(path);
a22285a6 804
8cc33e5c
DS
805 /*
806 * Mutex was contended, block until it's released and try
807 * again
808 */
a22285a6
YZ
809 mutex_lock(&head->mutex);
810 mutex_unlock(&head->mutex);
811 btrfs_put_delayed_ref(&head->node);
812 goto again;
813 }
814 if (head->extent_op && head->extent_op->update_flags)
815 extent_flags |= head->extent_op->flags_to_set;
816 else
817 BUG_ON(num_refs == 0);
818
819 num_refs += head->node.ref_mod;
820 mutex_unlock(&head->mutex);
821 }
822 spin_unlock(&delayed_refs->lock);
823out:
824 WARN_ON(num_refs == 0);
825 if (refs)
826 *refs = num_refs;
827 if (flags)
828 *flags = extent_flags;
829out_free:
830 btrfs_free_path(path);
831 return ret;
832}
833
d8d5f3e1
CM
834/*
835 * Back reference rules. Back refs have three main goals:
836 *
837 * 1) differentiate between all holders of references to an extent so that
838 * when a reference is dropped we can make sure it was a valid reference
839 * before freeing the extent.
840 *
841 * 2) Provide enough information to quickly find the holders of an extent
842 * if we notice a given block is corrupted or bad.
843 *
844 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
845 * maintenance. This is actually the same as #2, but with a slightly
846 * different use case.
847 *
5d4f98a2
YZ
848 * There are two kinds of back refs. The implicit back refs is optimized
849 * for pointers in non-shared tree blocks. For a given pointer in a block,
850 * back refs of this kind provide information about the block's owner tree
851 * and the pointer's key. These information allow us to find the block by
852 * b-tree searching. The full back refs is for pointers in tree blocks not
853 * referenced by their owner trees. The location of tree block is recorded
854 * in the back refs. Actually the full back refs is generic, and can be
855 * used in all cases the implicit back refs is used. The major shortcoming
856 * of the full back refs is its overhead. Every time a tree block gets
857 * COWed, we have to update back refs entry for all pointers in it.
858 *
859 * For a newly allocated tree block, we use implicit back refs for
860 * pointers in it. This means most tree related operations only involve
861 * implicit back refs. For a tree block created in old transaction, the
862 * only way to drop a reference to it is COW it. So we can detect the
863 * event that tree block loses its owner tree's reference and do the
864 * back refs conversion.
865 *
866 * When a tree block is COW'd through a tree, there are four cases:
867 *
868 * The reference count of the block is one and the tree is the block's
869 * owner tree. Nothing to do in this case.
870 *
871 * The reference count of the block is one and the tree is not the
872 * block's owner tree. In this case, full back refs is used for pointers
873 * in the block. Remove these full back refs, add implicit back refs for
874 * every pointers in the new block.
875 *
876 * The reference count of the block is greater than one and the tree is
877 * the block's owner tree. In this case, implicit back refs is used for
878 * pointers in the block. Add full back refs for every pointers in the
879 * block, increase lower level extents' reference counts. The original
880 * implicit back refs are entailed to the new block.
881 *
882 * The reference count of the block is greater than one and the tree is
883 * not the block's owner tree. Add implicit back refs for every pointer in
884 * the new block, increase lower level extents' reference count.
885 *
886 * Back Reference Key composing:
887 *
888 * The key objectid corresponds to the first byte in the extent,
889 * The key type is used to differentiate between types of back refs.
890 * There are different meanings of the key offset for different types
891 * of back refs.
892 *
d8d5f3e1
CM
893 * File extents can be referenced by:
894 *
895 * - multiple snapshots, subvolumes, or different generations in one subvol
31840ae1 896 * - different files inside a single subvolume
d8d5f3e1
CM
897 * - different offsets inside a file (bookend extents in file.c)
898 *
5d4f98a2 899 * The extent ref structure for the implicit back refs has fields for:
d8d5f3e1
CM
900 *
901 * - Objectid of the subvolume root
d8d5f3e1 902 * - objectid of the file holding the reference
5d4f98a2
YZ
903 * - original offset in the file
904 * - how many bookend extents
d8d5f3e1 905 *
5d4f98a2
YZ
906 * The key offset for the implicit back refs is hash of the first
907 * three fields.
d8d5f3e1 908 *
5d4f98a2 909 * The extent ref structure for the full back refs has field for:
d8d5f3e1 910 *
5d4f98a2 911 * - number of pointers in the tree leaf
d8d5f3e1 912 *
5d4f98a2
YZ
913 * The key offset for the implicit back refs is the first byte of
914 * the tree leaf
d8d5f3e1 915 *
5d4f98a2
YZ
916 * When a file extent is allocated, The implicit back refs is used.
917 * the fields are filled in:
d8d5f3e1 918 *
5d4f98a2 919 * (root_key.objectid, inode objectid, offset in file, 1)
d8d5f3e1 920 *
5d4f98a2
YZ
921 * When a file extent is removed file truncation, we find the
922 * corresponding implicit back refs and check the following fields:
d8d5f3e1 923 *
5d4f98a2 924 * (btrfs_header_owner(leaf), inode objectid, offset in file)
d8d5f3e1 925 *
5d4f98a2 926 * Btree extents can be referenced by:
d8d5f3e1 927 *
5d4f98a2 928 * - Different subvolumes
d8d5f3e1 929 *
5d4f98a2
YZ
930 * Both the implicit back refs and the full back refs for tree blocks
931 * only consist of key. The key offset for the implicit back refs is
932 * objectid of block's owner tree. The key offset for the full back refs
933 * is the first byte of parent block.
d8d5f3e1 934 *
5d4f98a2
YZ
935 * When implicit back refs is used, information about the lowest key and
936 * level of the tree block are required. These information are stored in
937 * tree block info structure.
d8d5f3e1 938 */
31840ae1 939
5d4f98a2
YZ
940#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
941static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
942 struct btrfs_root *root,
943 struct btrfs_path *path,
944 u64 owner, u32 extra_size)
7bb86316 945{
5d4f98a2
YZ
946 struct btrfs_extent_item *item;
947 struct btrfs_extent_item_v0 *ei0;
948 struct btrfs_extent_ref_v0 *ref0;
949 struct btrfs_tree_block_info *bi;
950 struct extent_buffer *leaf;
7bb86316 951 struct btrfs_key key;
5d4f98a2
YZ
952 struct btrfs_key found_key;
953 u32 new_size = sizeof(*item);
954 u64 refs;
955 int ret;
956
957 leaf = path->nodes[0];
958 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
959
960 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
961 ei0 = btrfs_item_ptr(leaf, path->slots[0],
962 struct btrfs_extent_item_v0);
963 refs = btrfs_extent_refs_v0(leaf, ei0);
964
965 if (owner == (u64)-1) {
966 while (1) {
967 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
968 ret = btrfs_next_leaf(root, path);
969 if (ret < 0)
970 return ret;
79787eaa 971 BUG_ON(ret > 0); /* Corruption */
5d4f98a2
YZ
972 leaf = path->nodes[0];
973 }
974 btrfs_item_key_to_cpu(leaf, &found_key,
975 path->slots[0]);
976 BUG_ON(key.objectid != found_key.objectid);
977 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
978 path->slots[0]++;
979 continue;
980 }
981 ref0 = btrfs_item_ptr(leaf, path->slots[0],
982 struct btrfs_extent_ref_v0);
983 owner = btrfs_ref_objectid_v0(leaf, ref0);
984 break;
985 }
986 }
b3b4aa74 987 btrfs_release_path(path);
5d4f98a2
YZ
988
989 if (owner < BTRFS_FIRST_FREE_OBJECTID)
990 new_size += sizeof(*bi);
991
992 new_size -= sizeof(*ei0);
993 ret = btrfs_search_slot(trans, root, &key, path,
994 new_size + extra_size, 1);
995 if (ret < 0)
996 return ret;
79787eaa 997 BUG_ON(ret); /* Corruption */
5d4f98a2 998
143bede5 999 btrfs_extend_item(trans, root, path, new_size);
5d4f98a2
YZ
1000
1001 leaf = path->nodes[0];
1002 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1003 btrfs_set_extent_refs(leaf, item, refs);
1004 /* FIXME: get real generation */
1005 btrfs_set_extent_generation(leaf, item, 0);
1006 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1007 btrfs_set_extent_flags(leaf, item,
1008 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1009 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1010 bi = (struct btrfs_tree_block_info *)(item + 1);
1011 /* FIXME: get first key of the block */
1012 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1013 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1014 } else {
1015 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1016 }
1017 btrfs_mark_buffer_dirty(leaf);
1018 return 0;
1019}
1020#endif
1021
1022static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1023{
1024 u32 high_crc = ~(u32)0;
1025 u32 low_crc = ~(u32)0;
1026 __le64 lenum;
1027
1028 lenum = cpu_to_le64(root_objectid);
163e783e 1029 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
5d4f98a2 1030 lenum = cpu_to_le64(owner);
163e783e 1031 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2 1032 lenum = cpu_to_le64(offset);
163e783e 1033 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2
YZ
1034
1035 return ((u64)high_crc << 31) ^ (u64)low_crc;
1036}
1037
1038static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1039 struct btrfs_extent_data_ref *ref)
1040{
1041 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1042 btrfs_extent_data_ref_objectid(leaf, ref),
1043 btrfs_extent_data_ref_offset(leaf, ref));
1044}
1045
1046static int match_extent_data_ref(struct extent_buffer *leaf,
1047 struct btrfs_extent_data_ref *ref,
1048 u64 root_objectid, u64 owner, u64 offset)
1049{
1050 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1051 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1052 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1053 return 0;
1054 return 1;
1055}
1056
1057static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1058 struct btrfs_root *root,
1059 struct btrfs_path *path,
1060 u64 bytenr, u64 parent,
1061 u64 root_objectid,
1062 u64 owner, u64 offset)
1063{
1064 struct btrfs_key key;
1065 struct btrfs_extent_data_ref *ref;
31840ae1 1066 struct extent_buffer *leaf;
5d4f98a2 1067 u32 nritems;
74493f7a 1068 int ret;
5d4f98a2
YZ
1069 int recow;
1070 int err = -ENOENT;
74493f7a 1071
31840ae1 1072 key.objectid = bytenr;
5d4f98a2
YZ
1073 if (parent) {
1074 key.type = BTRFS_SHARED_DATA_REF_KEY;
1075 key.offset = parent;
1076 } else {
1077 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1078 key.offset = hash_extent_data_ref(root_objectid,
1079 owner, offset);
1080 }
1081again:
1082 recow = 0;
1083 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1084 if (ret < 0) {
1085 err = ret;
1086 goto fail;
1087 }
31840ae1 1088
5d4f98a2
YZ
1089 if (parent) {
1090 if (!ret)
1091 return 0;
1092#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1093 key.type = BTRFS_EXTENT_REF_V0_KEY;
b3b4aa74 1094 btrfs_release_path(path);
5d4f98a2
YZ
1095 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1096 if (ret < 0) {
1097 err = ret;
1098 goto fail;
1099 }
1100 if (!ret)
1101 return 0;
1102#endif
1103 goto fail;
31840ae1
ZY
1104 }
1105
1106 leaf = path->nodes[0];
5d4f98a2
YZ
1107 nritems = btrfs_header_nritems(leaf);
1108 while (1) {
1109 if (path->slots[0] >= nritems) {
1110 ret = btrfs_next_leaf(root, path);
1111 if (ret < 0)
1112 err = ret;
1113 if (ret)
1114 goto fail;
1115
1116 leaf = path->nodes[0];
1117 nritems = btrfs_header_nritems(leaf);
1118 recow = 1;
1119 }
1120
1121 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1122 if (key.objectid != bytenr ||
1123 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1124 goto fail;
1125
1126 ref = btrfs_item_ptr(leaf, path->slots[0],
1127 struct btrfs_extent_data_ref);
1128
1129 if (match_extent_data_ref(leaf, ref, root_objectid,
1130 owner, offset)) {
1131 if (recow) {
b3b4aa74 1132 btrfs_release_path(path);
5d4f98a2
YZ
1133 goto again;
1134 }
1135 err = 0;
1136 break;
1137 }
1138 path->slots[0]++;
31840ae1 1139 }
5d4f98a2
YZ
1140fail:
1141 return err;
31840ae1
ZY
1142}
1143
5d4f98a2
YZ
1144static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1145 struct btrfs_root *root,
1146 struct btrfs_path *path,
1147 u64 bytenr, u64 parent,
1148 u64 root_objectid, u64 owner,
1149 u64 offset, int refs_to_add)
31840ae1
ZY
1150{
1151 struct btrfs_key key;
1152 struct extent_buffer *leaf;
5d4f98a2 1153 u32 size;
31840ae1
ZY
1154 u32 num_refs;
1155 int ret;
74493f7a 1156
74493f7a 1157 key.objectid = bytenr;
5d4f98a2
YZ
1158 if (parent) {
1159 key.type = BTRFS_SHARED_DATA_REF_KEY;
1160 key.offset = parent;
1161 size = sizeof(struct btrfs_shared_data_ref);
1162 } else {
1163 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1164 key.offset = hash_extent_data_ref(root_objectid,
1165 owner, offset);
1166 size = sizeof(struct btrfs_extent_data_ref);
1167 }
74493f7a 1168
5d4f98a2
YZ
1169 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1170 if (ret && ret != -EEXIST)
1171 goto fail;
1172
1173 leaf = path->nodes[0];
1174 if (parent) {
1175 struct btrfs_shared_data_ref *ref;
31840ae1 1176 ref = btrfs_item_ptr(leaf, path->slots[0],
5d4f98a2
YZ
1177 struct btrfs_shared_data_ref);
1178 if (ret == 0) {
1179 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1180 } else {
1181 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1182 num_refs += refs_to_add;
1183 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
31840ae1 1184 }
5d4f98a2
YZ
1185 } else {
1186 struct btrfs_extent_data_ref *ref;
1187 while (ret == -EEXIST) {
1188 ref = btrfs_item_ptr(leaf, path->slots[0],
1189 struct btrfs_extent_data_ref);
1190 if (match_extent_data_ref(leaf, ref, root_objectid,
1191 owner, offset))
1192 break;
b3b4aa74 1193 btrfs_release_path(path);
5d4f98a2
YZ
1194 key.offset++;
1195 ret = btrfs_insert_empty_item(trans, root, path, &key,
1196 size);
1197 if (ret && ret != -EEXIST)
1198 goto fail;
31840ae1 1199
5d4f98a2
YZ
1200 leaf = path->nodes[0];
1201 }
1202 ref = btrfs_item_ptr(leaf, path->slots[0],
1203 struct btrfs_extent_data_ref);
1204 if (ret == 0) {
1205 btrfs_set_extent_data_ref_root(leaf, ref,
1206 root_objectid);
1207 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1208 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1209 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1210 } else {
1211 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1212 num_refs += refs_to_add;
1213 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
31840ae1 1214 }
31840ae1 1215 }
5d4f98a2
YZ
1216 btrfs_mark_buffer_dirty(leaf);
1217 ret = 0;
1218fail:
b3b4aa74 1219 btrfs_release_path(path);
7bb86316 1220 return ret;
74493f7a
CM
1221}
1222
5d4f98a2
YZ
1223static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1224 struct btrfs_root *root,
1225 struct btrfs_path *path,
1226 int refs_to_drop)
31840ae1 1227{
5d4f98a2
YZ
1228 struct btrfs_key key;
1229 struct btrfs_extent_data_ref *ref1 = NULL;
1230 struct btrfs_shared_data_ref *ref2 = NULL;
31840ae1 1231 struct extent_buffer *leaf;
5d4f98a2 1232 u32 num_refs = 0;
31840ae1
ZY
1233 int ret = 0;
1234
1235 leaf = path->nodes[0];
5d4f98a2
YZ
1236 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1237
1238 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1239 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1240 struct btrfs_extent_data_ref);
1241 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1242 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1243 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1244 struct btrfs_shared_data_ref);
1245 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1246#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1247 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1248 struct btrfs_extent_ref_v0 *ref0;
1249 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1250 struct btrfs_extent_ref_v0);
1251 num_refs = btrfs_ref_count_v0(leaf, ref0);
1252#endif
1253 } else {
1254 BUG();
1255 }
1256
56bec294
CM
1257 BUG_ON(num_refs < refs_to_drop);
1258 num_refs -= refs_to_drop;
5d4f98a2 1259
31840ae1
ZY
1260 if (num_refs == 0) {
1261 ret = btrfs_del_item(trans, root, path);
1262 } else {
5d4f98a2
YZ
1263 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1264 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1265 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1266 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1267#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1268 else {
1269 struct btrfs_extent_ref_v0 *ref0;
1270 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1271 struct btrfs_extent_ref_v0);
1272 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1273 }
1274#endif
31840ae1
ZY
1275 btrfs_mark_buffer_dirty(leaf);
1276 }
31840ae1
ZY
1277 return ret;
1278}
1279
5d4f98a2
YZ
1280static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1281 struct btrfs_path *path,
1282 struct btrfs_extent_inline_ref *iref)
15916de8 1283{
5d4f98a2
YZ
1284 struct btrfs_key key;
1285 struct extent_buffer *leaf;
1286 struct btrfs_extent_data_ref *ref1;
1287 struct btrfs_shared_data_ref *ref2;
1288 u32 num_refs = 0;
1289
1290 leaf = path->nodes[0];
1291 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1292 if (iref) {
1293 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1294 BTRFS_EXTENT_DATA_REF_KEY) {
1295 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1296 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1297 } else {
1298 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1299 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1300 }
1301 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1302 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1303 struct btrfs_extent_data_ref);
1304 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1305 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1306 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1307 struct btrfs_shared_data_ref);
1308 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1309#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1310 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1311 struct btrfs_extent_ref_v0 *ref0;
1312 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1313 struct btrfs_extent_ref_v0);
1314 num_refs = btrfs_ref_count_v0(leaf, ref0);
4b4e25f2 1315#endif
5d4f98a2
YZ
1316 } else {
1317 WARN_ON(1);
1318 }
1319 return num_refs;
1320}
15916de8 1321
5d4f98a2
YZ
1322static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1323 struct btrfs_root *root,
1324 struct btrfs_path *path,
1325 u64 bytenr, u64 parent,
1326 u64 root_objectid)
1f3c79a2 1327{
5d4f98a2 1328 struct btrfs_key key;
1f3c79a2 1329 int ret;
1f3c79a2 1330
5d4f98a2
YZ
1331 key.objectid = bytenr;
1332 if (parent) {
1333 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1334 key.offset = parent;
1335 } else {
1336 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1337 key.offset = root_objectid;
1f3c79a2
LH
1338 }
1339
5d4f98a2
YZ
1340 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1341 if (ret > 0)
1342 ret = -ENOENT;
1343#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1344 if (ret == -ENOENT && parent) {
b3b4aa74 1345 btrfs_release_path(path);
5d4f98a2
YZ
1346 key.type = BTRFS_EXTENT_REF_V0_KEY;
1347 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1348 if (ret > 0)
1349 ret = -ENOENT;
1350 }
1f3c79a2 1351#endif
5d4f98a2 1352 return ret;
1f3c79a2
LH
1353}
1354
5d4f98a2
YZ
1355static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1356 struct btrfs_root *root,
1357 struct btrfs_path *path,
1358 u64 bytenr, u64 parent,
1359 u64 root_objectid)
31840ae1 1360{
5d4f98a2 1361 struct btrfs_key key;
31840ae1 1362 int ret;
31840ae1 1363
5d4f98a2
YZ
1364 key.objectid = bytenr;
1365 if (parent) {
1366 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1367 key.offset = parent;
1368 } else {
1369 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1370 key.offset = root_objectid;
1371 }
1372
1373 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
b3b4aa74 1374 btrfs_release_path(path);
31840ae1
ZY
1375 return ret;
1376}
1377
5d4f98a2 1378static inline int extent_ref_type(u64 parent, u64 owner)
31840ae1 1379{
5d4f98a2
YZ
1380 int type;
1381 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1382 if (parent > 0)
1383 type = BTRFS_SHARED_BLOCK_REF_KEY;
1384 else
1385 type = BTRFS_TREE_BLOCK_REF_KEY;
1386 } else {
1387 if (parent > 0)
1388 type = BTRFS_SHARED_DATA_REF_KEY;
1389 else
1390 type = BTRFS_EXTENT_DATA_REF_KEY;
1391 }
1392 return type;
31840ae1 1393}
56bec294 1394
2c47e605
YZ
1395static int find_next_key(struct btrfs_path *path, int level,
1396 struct btrfs_key *key)
56bec294 1397
02217ed2 1398{
2c47e605 1399 for (; level < BTRFS_MAX_LEVEL; level++) {
5d4f98a2
YZ
1400 if (!path->nodes[level])
1401 break;
5d4f98a2
YZ
1402 if (path->slots[level] + 1 >=
1403 btrfs_header_nritems(path->nodes[level]))
1404 continue;
1405 if (level == 0)
1406 btrfs_item_key_to_cpu(path->nodes[level], key,
1407 path->slots[level] + 1);
1408 else
1409 btrfs_node_key_to_cpu(path->nodes[level], key,
1410 path->slots[level] + 1);
1411 return 0;
1412 }
1413 return 1;
1414}
037e6390 1415
5d4f98a2
YZ
1416/*
1417 * look for inline back ref. if back ref is found, *ref_ret is set
1418 * to the address of inline back ref, and 0 is returned.
1419 *
1420 * if back ref isn't found, *ref_ret is set to the address where it
1421 * should be inserted, and -ENOENT is returned.
1422 *
1423 * if insert is true and there are too many inline back refs, the path
1424 * points to the extent item, and -EAGAIN is returned.
1425 *
1426 * NOTE: inline back refs are ordered in the same way that back ref
1427 * items in the tree are ordered.
1428 */
1429static noinline_for_stack
1430int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1431 struct btrfs_root *root,
1432 struct btrfs_path *path,
1433 struct btrfs_extent_inline_ref **ref_ret,
1434 u64 bytenr, u64 num_bytes,
1435 u64 parent, u64 root_objectid,
1436 u64 owner, u64 offset, int insert)
1437{
1438 struct btrfs_key key;
1439 struct extent_buffer *leaf;
1440 struct btrfs_extent_item *ei;
1441 struct btrfs_extent_inline_ref *iref;
1442 u64 flags;
1443 u64 item_size;
1444 unsigned long ptr;
1445 unsigned long end;
1446 int extra_size;
1447 int type;
1448 int want;
1449 int ret;
1450 int err = 0;
26b8003f 1451
db94535d 1452 key.objectid = bytenr;
31840ae1 1453 key.type = BTRFS_EXTENT_ITEM_KEY;
56bec294 1454 key.offset = num_bytes;
31840ae1 1455
5d4f98a2
YZ
1456 want = extent_ref_type(parent, owner);
1457 if (insert) {
1458 extra_size = btrfs_extent_inline_ref_size(want);
85d4198e 1459 path->keep_locks = 1;
5d4f98a2
YZ
1460 } else
1461 extra_size = -1;
1462 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
b9473439 1463 if (ret < 0) {
5d4f98a2
YZ
1464 err = ret;
1465 goto out;
1466 }
79787eaa
JM
1467 if (ret && !insert) {
1468 err = -ENOENT;
1469 goto out;
1470 }
1471 BUG_ON(ret); /* Corruption */
5d4f98a2
YZ
1472
1473 leaf = path->nodes[0];
1474 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1475#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1476 if (item_size < sizeof(*ei)) {
1477 if (!insert) {
1478 err = -ENOENT;
1479 goto out;
1480 }
1481 ret = convert_extent_item_v0(trans, root, path, owner,
1482 extra_size);
1483 if (ret < 0) {
1484 err = ret;
1485 goto out;
1486 }
1487 leaf = path->nodes[0];
1488 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1489 }
1490#endif
1491 BUG_ON(item_size < sizeof(*ei));
1492
5d4f98a2
YZ
1493 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1494 flags = btrfs_extent_flags(leaf, ei);
1495
1496 ptr = (unsigned long)(ei + 1);
1497 end = (unsigned long)ei + item_size;
1498
1499 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1500 ptr += sizeof(struct btrfs_tree_block_info);
1501 BUG_ON(ptr > end);
1502 } else {
1503 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1504 }
1505
1506 err = -ENOENT;
1507 while (1) {
1508 if (ptr >= end) {
1509 WARN_ON(ptr > end);
1510 break;
1511 }
1512 iref = (struct btrfs_extent_inline_ref *)ptr;
1513 type = btrfs_extent_inline_ref_type(leaf, iref);
1514 if (want < type)
1515 break;
1516 if (want > type) {
1517 ptr += btrfs_extent_inline_ref_size(type);
1518 continue;
1519 }
1520
1521 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1522 struct btrfs_extent_data_ref *dref;
1523 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1524 if (match_extent_data_ref(leaf, dref, root_objectid,
1525 owner, offset)) {
1526 err = 0;
1527 break;
1528 }
1529 if (hash_extent_data_ref_item(leaf, dref) <
1530 hash_extent_data_ref(root_objectid, owner, offset))
1531 break;
1532 } else {
1533 u64 ref_offset;
1534 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1535 if (parent > 0) {
1536 if (parent == ref_offset) {
1537 err = 0;
1538 break;
1539 }
1540 if (ref_offset < parent)
1541 break;
1542 } else {
1543 if (root_objectid == ref_offset) {
1544 err = 0;
1545 break;
1546 }
1547 if (ref_offset < root_objectid)
1548 break;
1549 }
1550 }
1551 ptr += btrfs_extent_inline_ref_size(type);
1552 }
1553 if (err == -ENOENT && insert) {
1554 if (item_size + extra_size >=
1555 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1556 err = -EAGAIN;
1557 goto out;
1558 }
1559 /*
1560 * To add new inline back ref, we have to make sure
1561 * there is no corresponding back ref item.
1562 * For simplicity, we just do not add new inline back
1563 * ref if there is any kind of item for this block
1564 */
2c47e605
YZ
1565 if (find_next_key(path, 0, &key) == 0 &&
1566 key.objectid == bytenr &&
85d4198e 1567 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
5d4f98a2
YZ
1568 err = -EAGAIN;
1569 goto out;
1570 }
1571 }
1572 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1573out:
85d4198e 1574 if (insert) {
5d4f98a2
YZ
1575 path->keep_locks = 0;
1576 btrfs_unlock_up_safe(path, 1);
1577 }
1578 return err;
1579}
1580
1581/*
1582 * helper to add new inline back ref
1583 */
1584static noinline_for_stack
143bede5
JM
1585void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1586 struct btrfs_root *root,
1587 struct btrfs_path *path,
1588 struct btrfs_extent_inline_ref *iref,
1589 u64 parent, u64 root_objectid,
1590 u64 owner, u64 offset, int refs_to_add,
1591 struct btrfs_delayed_extent_op *extent_op)
5d4f98a2
YZ
1592{
1593 struct extent_buffer *leaf;
1594 struct btrfs_extent_item *ei;
1595 unsigned long ptr;
1596 unsigned long end;
1597 unsigned long item_offset;
1598 u64 refs;
1599 int size;
1600 int type;
5d4f98a2
YZ
1601
1602 leaf = path->nodes[0];
1603 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1604 item_offset = (unsigned long)iref - (unsigned long)ei;
1605
1606 type = extent_ref_type(parent, owner);
1607 size = btrfs_extent_inline_ref_size(type);
1608
143bede5 1609 btrfs_extend_item(trans, root, path, size);
5d4f98a2
YZ
1610
1611 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1612 refs = btrfs_extent_refs(leaf, ei);
1613 refs += refs_to_add;
1614 btrfs_set_extent_refs(leaf, ei, refs);
1615 if (extent_op)
1616 __run_delayed_extent_op(extent_op, leaf, ei);
1617
1618 ptr = (unsigned long)ei + item_offset;
1619 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1620 if (ptr < end - size)
1621 memmove_extent_buffer(leaf, ptr + size, ptr,
1622 end - size - ptr);
1623
1624 iref = (struct btrfs_extent_inline_ref *)ptr;
1625 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1626 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1627 struct btrfs_extent_data_ref *dref;
1628 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1629 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1630 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1631 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1632 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1633 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1634 struct btrfs_shared_data_ref *sref;
1635 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1636 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1637 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1638 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1639 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1640 } else {
1641 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1642 }
1643 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1644}
1645
1646static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1647 struct btrfs_root *root,
1648 struct btrfs_path *path,
1649 struct btrfs_extent_inline_ref **ref_ret,
1650 u64 bytenr, u64 num_bytes, u64 parent,
1651 u64 root_objectid, u64 owner, u64 offset)
1652{
1653 int ret;
1654
1655 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1656 bytenr, num_bytes, parent,
1657 root_objectid, owner, offset, 0);
1658 if (ret != -ENOENT)
54aa1f4d 1659 return ret;
5d4f98a2 1660
b3b4aa74 1661 btrfs_release_path(path);
5d4f98a2
YZ
1662 *ref_ret = NULL;
1663
1664 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1665 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1666 root_objectid);
1667 } else {
1668 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1669 root_objectid, owner, offset);
b9473439 1670 }
5d4f98a2
YZ
1671 return ret;
1672}
31840ae1 1673
5d4f98a2
YZ
1674/*
1675 * helper to update/remove inline back ref
1676 */
1677static noinline_for_stack
143bede5
JM
1678void update_inline_extent_backref(struct btrfs_trans_handle *trans,
1679 struct btrfs_root *root,
1680 struct btrfs_path *path,
1681 struct btrfs_extent_inline_ref *iref,
1682 int refs_to_mod,
1683 struct btrfs_delayed_extent_op *extent_op)
5d4f98a2
YZ
1684{
1685 struct extent_buffer *leaf;
1686 struct btrfs_extent_item *ei;
1687 struct btrfs_extent_data_ref *dref = NULL;
1688 struct btrfs_shared_data_ref *sref = NULL;
1689 unsigned long ptr;
1690 unsigned long end;
1691 u32 item_size;
1692 int size;
1693 int type;
5d4f98a2
YZ
1694 u64 refs;
1695
1696 leaf = path->nodes[0];
1697 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1698 refs = btrfs_extent_refs(leaf, ei);
1699 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1700 refs += refs_to_mod;
1701 btrfs_set_extent_refs(leaf, ei, refs);
1702 if (extent_op)
1703 __run_delayed_extent_op(extent_op, leaf, ei);
1704
1705 type = btrfs_extent_inline_ref_type(leaf, iref);
1706
1707 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1708 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1709 refs = btrfs_extent_data_ref_count(leaf, dref);
1710 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1711 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1712 refs = btrfs_shared_data_ref_count(leaf, sref);
1713 } else {
1714 refs = 1;
1715 BUG_ON(refs_to_mod != -1);
56bec294 1716 }
31840ae1 1717
5d4f98a2
YZ
1718 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1719 refs += refs_to_mod;
1720
1721 if (refs > 0) {
1722 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1723 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1724 else
1725 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1726 } else {
1727 size = btrfs_extent_inline_ref_size(type);
1728 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1729 ptr = (unsigned long)iref;
1730 end = (unsigned long)ei + item_size;
1731 if (ptr + size < end)
1732 memmove_extent_buffer(leaf, ptr, ptr + size,
1733 end - ptr - size);
1734 item_size -= size;
143bede5 1735 btrfs_truncate_item(trans, root, path, item_size, 1);
5d4f98a2
YZ
1736 }
1737 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1738}
1739
1740static noinline_for_stack
1741int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1742 struct btrfs_root *root,
1743 struct btrfs_path *path,
1744 u64 bytenr, u64 num_bytes, u64 parent,
1745 u64 root_objectid, u64 owner,
1746 u64 offset, int refs_to_add,
1747 struct btrfs_delayed_extent_op *extent_op)
1748{
1749 struct btrfs_extent_inline_ref *iref;
1750 int ret;
1751
1752 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1753 bytenr, num_bytes, parent,
1754 root_objectid, owner, offset, 1);
1755 if (ret == 0) {
1756 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
143bede5
JM
1757 update_inline_extent_backref(trans, root, path, iref,
1758 refs_to_add, extent_op);
5d4f98a2 1759 } else if (ret == -ENOENT) {
143bede5
JM
1760 setup_inline_extent_backref(trans, root, path, iref, parent,
1761 root_objectid, owner, offset,
1762 refs_to_add, extent_op);
1763 ret = 0;
771ed689 1764 }
5d4f98a2
YZ
1765 return ret;
1766}
31840ae1 1767
5d4f98a2
YZ
1768static int insert_extent_backref(struct btrfs_trans_handle *trans,
1769 struct btrfs_root *root,
1770 struct btrfs_path *path,
1771 u64 bytenr, u64 parent, u64 root_objectid,
1772 u64 owner, u64 offset, int refs_to_add)
1773{
1774 int ret;
1775 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1776 BUG_ON(refs_to_add != 1);
1777 ret = insert_tree_block_ref(trans, root, path, bytenr,
1778 parent, root_objectid);
1779 } else {
1780 ret = insert_extent_data_ref(trans, root, path, bytenr,
1781 parent, root_objectid,
1782 owner, offset, refs_to_add);
1783 }
1784 return ret;
1785}
56bec294 1786
5d4f98a2
YZ
1787static int remove_extent_backref(struct btrfs_trans_handle *trans,
1788 struct btrfs_root *root,
1789 struct btrfs_path *path,
1790 struct btrfs_extent_inline_ref *iref,
1791 int refs_to_drop, int is_data)
1792{
143bede5 1793 int ret = 0;
b9473439 1794
5d4f98a2
YZ
1795 BUG_ON(!is_data && refs_to_drop != 1);
1796 if (iref) {
143bede5
JM
1797 update_inline_extent_backref(trans, root, path, iref,
1798 -refs_to_drop, NULL);
5d4f98a2
YZ
1799 } else if (is_data) {
1800 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1801 } else {
1802 ret = btrfs_del_item(trans, root, path);
1803 }
1804 return ret;
1805}
1806
5378e607 1807static int btrfs_issue_discard(struct block_device *bdev,
5d4f98a2
YZ
1808 u64 start, u64 len)
1809{
5378e607 1810 return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
5d4f98a2 1811}
5d4f98a2
YZ
1812
1813static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
5378e607 1814 u64 num_bytes, u64 *actual_bytes)
5d4f98a2 1815{
5d4f98a2 1816 int ret;
5378e607 1817 u64 discarded_bytes = 0;
a1d3c478 1818 struct btrfs_bio *bbio = NULL;
5d4f98a2 1819
e244a0ae 1820
5d4f98a2 1821 /* Tell the block device(s) that the sectors can be discarded */
3ec706c8 1822 ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
a1d3c478 1823 bytenr, &num_bytes, &bbio, 0);
79787eaa 1824 /* Error condition is -ENOMEM */
5d4f98a2 1825 if (!ret) {
a1d3c478 1826 struct btrfs_bio_stripe *stripe = bbio->stripes;
5d4f98a2
YZ
1827 int i;
1828
5d4f98a2 1829
a1d3c478 1830 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
d5e2003c
JB
1831 if (!stripe->dev->can_discard)
1832 continue;
1833
5378e607
LD
1834 ret = btrfs_issue_discard(stripe->dev->bdev,
1835 stripe->physical,
1836 stripe->length);
1837 if (!ret)
1838 discarded_bytes += stripe->length;
1839 else if (ret != -EOPNOTSUPP)
79787eaa 1840 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
d5e2003c
JB
1841
1842 /*
1843 * Just in case we get back EOPNOTSUPP for some reason,
1844 * just ignore the return value so we don't screw up
1845 * people calling discard_extent.
1846 */
1847 ret = 0;
5d4f98a2 1848 }
a1d3c478 1849 kfree(bbio);
5d4f98a2 1850 }
5378e607
LD
1851
1852 if (actual_bytes)
1853 *actual_bytes = discarded_bytes;
1854
5d4f98a2 1855
53b381b3
DW
1856 if (ret == -EOPNOTSUPP)
1857 ret = 0;
5d4f98a2 1858 return ret;
5d4f98a2
YZ
1859}
1860
79787eaa 1861/* Can return -ENOMEM */
5d4f98a2
YZ
1862int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1863 struct btrfs_root *root,
1864 u64 bytenr, u64 num_bytes, u64 parent,
66d7e7f0 1865 u64 root_objectid, u64 owner, u64 offset, int for_cow)
5d4f98a2
YZ
1866{
1867 int ret;
66d7e7f0
AJ
1868 struct btrfs_fs_info *fs_info = root->fs_info;
1869
5d4f98a2
YZ
1870 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1871 root_objectid == BTRFS_TREE_LOG_OBJECTID);
1872
1873 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0
AJ
1874 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
1875 num_bytes,
5d4f98a2 1876 parent, root_objectid, (int)owner,
66d7e7f0 1877 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
5d4f98a2 1878 } else {
66d7e7f0
AJ
1879 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
1880 num_bytes,
5d4f98a2 1881 parent, root_objectid, owner, offset,
66d7e7f0 1882 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
5d4f98a2
YZ
1883 }
1884 return ret;
1885}
1886
1887static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1888 struct btrfs_root *root,
1889 u64 bytenr, u64 num_bytes,
1890 u64 parent, u64 root_objectid,
1891 u64 owner, u64 offset, int refs_to_add,
1892 struct btrfs_delayed_extent_op *extent_op)
1893{
1894 struct btrfs_path *path;
1895 struct extent_buffer *leaf;
1896 struct btrfs_extent_item *item;
1897 u64 refs;
1898 int ret;
1899 int err = 0;
1900
1901 path = btrfs_alloc_path();
1902 if (!path)
1903 return -ENOMEM;
1904
1905 path->reada = 1;
1906 path->leave_spinning = 1;
1907 /* this will setup the path even if it fails to insert the back ref */
1908 ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1909 path, bytenr, num_bytes, parent,
1910 root_objectid, owner, offset,
1911 refs_to_add, extent_op);
1912 if (ret == 0)
1913 goto out;
1914
1915 if (ret != -EAGAIN) {
1916 err = ret;
1917 goto out;
1918 }
1919
1920 leaf = path->nodes[0];
1921 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1922 refs = btrfs_extent_refs(leaf, item);
1923 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1924 if (extent_op)
1925 __run_delayed_extent_op(extent_op, leaf, item);
56bec294 1926
5d4f98a2 1927 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 1928 btrfs_release_path(path);
56bec294
CM
1929
1930 path->reada = 1;
b9473439
CM
1931 path->leave_spinning = 1;
1932
56bec294
CM
1933 /* now insert the actual backref */
1934 ret = insert_extent_backref(trans, root->fs_info->extent_root,
5d4f98a2
YZ
1935 path, bytenr, parent, root_objectid,
1936 owner, offset, refs_to_add);
79787eaa
JM
1937 if (ret)
1938 btrfs_abort_transaction(trans, root, ret);
5d4f98a2 1939out:
56bec294 1940 btrfs_free_path(path);
5d4f98a2 1941 return err;
56bec294
CM
1942}
1943
5d4f98a2
YZ
1944static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1945 struct btrfs_root *root,
1946 struct btrfs_delayed_ref_node *node,
1947 struct btrfs_delayed_extent_op *extent_op,
1948 int insert_reserved)
56bec294 1949{
5d4f98a2
YZ
1950 int ret = 0;
1951 struct btrfs_delayed_data_ref *ref;
1952 struct btrfs_key ins;
1953 u64 parent = 0;
1954 u64 ref_root = 0;
1955 u64 flags = 0;
1956
1957 ins.objectid = node->bytenr;
1958 ins.offset = node->num_bytes;
1959 ins.type = BTRFS_EXTENT_ITEM_KEY;
1960
1961 ref = btrfs_delayed_node_to_data_ref(node);
1962 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1963 parent = ref->parent;
1964 else
1965 ref_root = ref->root;
1966
1967 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1968 if (extent_op) {
1969 BUG_ON(extent_op->update_key);
1970 flags |= extent_op->flags_to_set;
1971 }
1972 ret = alloc_reserved_file_extent(trans, root,
1973 parent, ref_root, flags,
1974 ref->objectid, ref->offset,
1975 &ins, node->ref_mod);
5d4f98a2
YZ
1976 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1977 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1978 node->num_bytes, parent,
1979 ref_root, ref->objectid,
1980 ref->offset, node->ref_mod,
1981 extent_op);
1982 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1983 ret = __btrfs_free_extent(trans, root, node->bytenr,
1984 node->num_bytes, parent,
1985 ref_root, ref->objectid,
1986 ref->offset, node->ref_mod,
1987 extent_op);
1988 } else {
1989 BUG();
1990 }
1991 return ret;
1992}
1993
1994static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1995 struct extent_buffer *leaf,
1996 struct btrfs_extent_item *ei)
1997{
1998 u64 flags = btrfs_extent_flags(leaf, ei);
1999 if (extent_op->update_flags) {
2000 flags |= extent_op->flags_to_set;
2001 btrfs_set_extent_flags(leaf, ei, flags);
2002 }
2003
2004 if (extent_op->update_key) {
2005 struct btrfs_tree_block_info *bi;
2006 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2007 bi = (struct btrfs_tree_block_info *)(ei + 1);
2008 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2009 }
2010}
2011
2012static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2013 struct btrfs_root *root,
2014 struct btrfs_delayed_ref_node *node,
2015 struct btrfs_delayed_extent_op *extent_op)
2016{
2017 struct btrfs_key key;
2018 struct btrfs_path *path;
2019 struct btrfs_extent_item *ei;
2020 struct extent_buffer *leaf;
2021 u32 item_size;
56bec294 2022 int ret;
5d4f98a2
YZ
2023 int err = 0;
2024
79787eaa
JM
2025 if (trans->aborted)
2026 return 0;
2027
5d4f98a2
YZ
2028 path = btrfs_alloc_path();
2029 if (!path)
2030 return -ENOMEM;
2031
2032 key.objectid = node->bytenr;
2033 key.type = BTRFS_EXTENT_ITEM_KEY;
2034 key.offset = node->num_bytes;
2035
2036 path->reada = 1;
2037 path->leave_spinning = 1;
2038 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2039 path, 0, 1);
2040 if (ret < 0) {
2041 err = ret;
2042 goto out;
2043 }
2044 if (ret > 0) {
2045 err = -EIO;
2046 goto out;
2047 }
2048
2049 leaf = path->nodes[0];
2050 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2051#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2052 if (item_size < sizeof(*ei)) {
2053 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2054 path, (u64)-1, 0);
2055 if (ret < 0) {
2056 err = ret;
2057 goto out;
2058 }
2059 leaf = path->nodes[0];
2060 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2061 }
2062#endif
2063 BUG_ON(item_size < sizeof(*ei));
2064 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2065 __run_delayed_extent_op(extent_op, leaf, ei);
56bec294 2066
5d4f98a2
YZ
2067 btrfs_mark_buffer_dirty(leaf);
2068out:
2069 btrfs_free_path(path);
2070 return err;
56bec294
CM
2071}
2072
5d4f98a2
YZ
2073static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2074 struct btrfs_root *root,
2075 struct btrfs_delayed_ref_node *node,
2076 struct btrfs_delayed_extent_op *extent_op,
2077 int insert_reserved)
56bec294
CM
2078{
2079 int ret = 0;
5d4f98a2
YZ
2080 struct btrfs_delayed_tree_ref *ref;
2081 struct btrfs_key ins;
2082 u64 parent = 0;
2083 u64 ref_root = 0;
56bec294 2084
5d4f98a2
YZ
2085 ins.objectid = node->bytenr;
2086 ins.offset = node->num_bytes;
2087 ins.type = BTRFS_EXTENT_ITEM_KEY;
56bec294 2088
5d4f98a2
YZ
2089 ref = btrfs_delayed_node_to_tree_ref(node);
2090 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2091 parent = ref->parent;
2092 else
2093 ref_root = ref->root;
2094
2095 BUG_ON(node->ref_mod != 1);
2096 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2097 BUG_ON(!extent_op || !extent_op->update_flags ||
2098 !extent_op->update_key);
2099 ret = alloc_reserved_tree_block(trans, root,
2100 parent, ref_root,
2101 extent_op->flags_to_set,
2102 &extent_op->key,
2103 ref->level, &ins);
5d4f98a2
YZ
2104 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2105 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2106 node->num_bytes, parent, ref_root,
2107 ref->level, 0, 1, extent_op);
2108 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2109 ret = __btrfs_free_extent(trans, root, node->bytenr,
2110 node->num_bytes, parent, ref_root,
2111 ref->level, 0, 1, extent_op);
2112 } else {
2113 BUG();
2114 }
56bec294
CM
2115 return ret;
2116}
2117
2118/* helper function to actually process a single delayed ref entry */
5d4f98a2
YZ
2119static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2120 struct btrfs_root *root,
2121 struct btrfs_delayed_ref_node *node,
2122 struct btrfs_delayed_extent_op *extent_op,
2123 int insert_reserved)
56bec294 2124{
79787eaa
JM
2125 int ret = 0;
2126
2127 if (trans->aborted)
2128 return 0;
2129
5d4f98a2 2130 if (btrfs_delayed_ref_is_head(node)) {
56bec294
CM
2131 struct btrfs_delayed_ref_head *head;
2132 /*
2133 * we've hit the end of the chain and we were supposed
2134 * to insert this extent into the tree. But, it got
2135 * deleted before we ever needed to insert it, so all
2136 * we have to do is clean up the accounting
2137 */
5d4f98a2
YZ
2138 BUG_ON(extent_op);
2139 head = btrfs_delayed_node_to_head(node);
56bec294 2140 if (insert_reserved) {
f0486c68
YZ
2141 btrfs_pin_extent(root, node->bytenr,
2142 node->num_bytes, 1);
5d4f98a2
YZ
2143 if (head->is_data) {
2144 ret = btrfs_del_csums(trans, root,
2145 node->bytenr,
2146 node->num_bytes);
5d4f98a2 2147 }
56bec294 2148 }
79787eaa 2149 return ret;
56bec294
CM
2150 }
2151
5d4f98a2
YZ
2152 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2153 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2154 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2155 insert_reserved);
2156 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2157 node->type == BTRFS_SHARED_DATA_REF_KEY)
2158 ret = run_delayed_data_ref(trans, root, node, extent_op,
2159 insert_reserved);
2160 else
2161 BUG();
2162 return ret;
56bec294
CM
2163}
2164
2165static noinline struct btrfs_delayed_ref_node *
2166select_delayed_ref(struct btrfs_delayed_ref_head *head)
2167{
2168 struct rb_node *node;
2169 struct btrfs_delayed_ref_node *ref;
2170 int action = BTRFS_ADD_DELAYED_REF;
2171again:
2172 /*
2173 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2174 * this prevents ref count from going down to zero when
2175 * there still are pending delayed ref.
2176 */
2177 node = rb_prev(&head->node.rb_node);
2178 while (1) {
2179 if (!node)
2180 break;
2181 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2182 rb_node);
2183 if (ref->bytenr != head->node.bytenr)
2184 break;
5d4f98a2 2185 if (ref->action == action)
56bec294
CM
2186 return ref;
2187 node = rb_prev(node);
2188 }
2189 if (action == BTRFS_ADD_DELAYED_REF) {
2190 action = BTRFS_DROP_DELAYED_REF;
2191 goto again;
2192 }
2193 return NULL;
2194}
2195
79787eaa
JM
2196/*
2197 * Returns 0 on success or if called with an already aborted transaction.
2198 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2199 */
c3e69d58
CM
2200static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2201 struct btrfs_root *root,
2202 struct list_head *cluster)
56bec294 2203{
56bec294
CM
2204 struct btrfs_delayed_ref_root *delayed_refs;
2205 struct btrfs_delayed_ref_node *ref;
2206 struct btrfs_delayed_ref_head *locked_ref = NULL;
5d4f98a2 2207 struct btrfs_delayed_extent_op *extent_op;
097b8a7c 2208 struct btrfs_fs_info *fs_info = root->fs_info;
56bec294 2209 int ret;
c3e69d58 2210 int count = 0;
56bec294 2211 int must_insert_reserved = 0;
56bec294
CM
2212
2213 delayed_refs = &trans->transaction->delayed_refs;
56bec294
CM
2214 while (1) {
2215 if (!locked_ref) {
c3e69d58
CM
2216 /* pick a new head ref from the cluster list */
2217 if (list_empty(cluster))
56bec294 2218 break;
56bec294 2219
c3e69d58
CM
2220 locked_ref = list_entry(cluster->next,
2221 struct btrfs_delayed_ref_head, cluster);
2222
2223 /* grab the lock that says we are going to process
2224 * all the refs for this head */
2225 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2226
2227 /*
2228 * we may have dropped the spin lock to get the head
2229 * mutex lock, and that might have given someone else
2230 * time to free the head. If that's true, it has been
2231 * removed from our list and we can move on.
2232 */
2233 if (ret == -EAGAIN) {
2234 locked_ref = NULL;
2235 count++;
2236 continue;
56bec294
CM
2237 }
2238 }
a28ec197 2239
ae1e206b
JB
2240 /*
2241 * We need to try and merge add/drops of the same ref since we
2242 * can run into issues with relocate dropping the implicit ref
2243 * and then it being added back again before the drop can
2244 * finish. If we merged anything we need to re-loop so we can
2245 * get a good ref.
2246 */
2247 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2248 locked_ref);
2249
d1270cd9
AJ
2250 /*
2251 * locked_ref is the head node, so we have to go one
2252 * node back for any delayed ref updates
2253 */
2254 ref = select_delayed_ref(locked_ref);
2255
2256 if (ref && ref->seq &&
097b8a7c 2257 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
d1270cd9
AJ
2258 /*
2259 * there are still refs with lower seq numbers in the
2260 * process of being added. Don't run this ref yet.
2261 */
2262 list_del_init(&locked_ref->cluster);
093486c4 2263 btrfs_delayed_ref_unlock(locked_ref);
d1270cd9
AJ
2264 locked_ref = NULL;
2265 delayed_refs->num_heads_ready++;
2266 spin_unlock(&delayed_refs->lock);
2267 cond_resched();
2268 spin_lock(&delayed_refs->lock);
2269 continue;
2270 }
2271
56bec294
CM
2272 /*
2273 * record the must insert reserved flag before we
2274 * drop the spin lock.
2275 */
2276 must_insert_reserved = locked_ref->must_insert_reserved;
2277 locked_ref->must_insert_reserved = 0;
7bb86316 2278
5d4f98a2
YZ
2279 extent_op = locked_ref->extent_op;
2280 locked_ref->extent_op = NULL;
2281
56bec294
CM
2282 if (!ref) {
2283 /* All delayed refs have been processed, Go ahead
2284 * and send the head node to run_one_delayed_ref,
2285 * so that any accounting fixes can happen
2286 */
2287 ref = &locked_ref->node;
5d4f98a2
YZ
2288
2289 if (extent_op && must_insert_reserved) {
78a6184a 2290 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
2291 extent_op = NULL;
2292 }
2293
2294 if (extent_op) {
2295 spin_unlock(&delayed_refs->lock);
2296
2297 ret = run_delayed_extent_op(trans, root,
2298 ref, extent_op);
78a6184a 2299 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2 2300
79787eaa 2301 if (ret) {
093486c4
MX
2302 printk(KERN_DEBUG
2303 "btrfs: run_delayed_extent_op "
2304 "returned %d\n", ret);
253beebd 2305 spin_lock(&delayed_refs->lock);
093486c4 2306 btrfs_delayed_ref_unlock(locked_ref);
79787eaa
JM
2307 return ret;
2308 }
2309
203bf287 2310 goto next;
5d4f98a2 2311 }
56bec294 2312 }
02217ed2 2313
56bec294
CM
2314 ref->in_tree = 0;
2315 rb_erase(&ref->rb_node, &delayed_refs->root);
2316 delayed_refs->num_entries--;
093486c4 2317 if (!btrfs_delayed_ref_is_head(ref)) {
22cd2e7d
AJ
2318 /*
2319 * when we play the delayed ref, also correct the
2320 * ref_mod on head
2321 */
2322 switch (ref->action) {
2323 case BTRFS_ADD_DELAYED_REF:
2324 case BTRFS_ADD_DELAYED_EXTENT:
2325 locked_ref->node.ref_mod -= ref->ref_mod;
2326 break;
2327 case BTRFS_DROP_DELAYED_REF:
2328 locked_ref->node.ref_mod += ref->ref_mod;
2329 break;
2330 default:
2331 WARN_ON(1);
2332 }
2333 }
56bec294 2334 spin_unlock(&delayed_refs->lock);
925baedd 2335
5d4f98a2 2336 ret = run_one_delayed_ref(trans, root, ref, extent_op,
56bec294 2337 must_insert_reserved);
eb099670 2338
78a6184a 2339 btrfs_free_delayed_extent_op(extent_op);
79787eaa 2340 if (ret) {
093486c4
MX
2341 btrfs_delayed_ref_unlock(locked_ref);
2342 btrfs_put_delayed_ref(ref);
2343 printk(KERN_DEBUG
2344 "btrfs: run_one_delayed_ref returned %d\n", ret);
253beebd 2345 spin_lock(&delayed_refs->lock);
79787eaa
JM
2346 return ret;
2347 }
2348
093486c4
MX
2349 /*
2350 * If this node is a head, that means all the refs in this head
2351 * have been dealt with, and we will pick the next head to deal
2352 * with, so we must unlock the head and drop it from the cluster
2353 * list before we release it.
2354 */
2355 if (btrfs_delayed_ref_is_head(ref)) {
2356 list_del_init(&locked_ref->cluster);
2357 btrfs_delayed_ref_unlock(locked_ref);
2358 locked_ref = NULL;
2359 }
2360 btrfs_put_delayed_ref(ref);
2361 count++;
203bf287 2362next:
c3e69d58
CM
2363 cond_resched();
2364 spin_lock(&delayed_refs->lock);
2365 }
2366 return count;
2367}
2368
709c0486
AJ
2369#ifdef SCRAMBLE_DELAYED_REFS
2370/*
2371 * Normally delayed refs get processed in ascending bytenr order. This
2372 * correlates in most cases to the order added. To expose dependencies on this
2373 * order, we start to process the tree in the middle instead of the beginning
2374 */
2375static u64 find_middle(struct rb_root *root)
2376{
2377 struct rb_node *n = root->rb_node;
2378 struct btrfs_delayed_ref_node *entry;
2379 int alt = 1;
2380 u64 middle;
2381 u64 first = 0, last = 0;
2382
2383 n = rb_first(root);
2384 if (n) {
2385 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2386 first = entry->bytenr;
2387 }
2388 n = rb_last(root);
2389 if (n) {
2390 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2391 last = entry->bytenr;
2392 }
2393 n = root->rb_node;
2394
2395 while (n) {
2396 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2397 WARN_ON(!entry->in_tree);
2398
2399 middle = entry->bytenr;
2400
2401 if (alt)
2402 n = n->rb_left;
2403 else
2404 n = n->rb_right;
2405
2406 alt = 1 - alt;
2407 }
2408 return middle;
2409}
2410#endif
2411
bed92eae
AJ
2412int btrfs_delayed_refs_qgroup_accounting(struct btrfs_trans_handle *trans,
2413 struct btrfs_fs_info *fs_info)
2414{
2415 struct qgroup_update *qgroup_update;
2416 int ret = 0;
2417
2418 if (list_empty(&trans->qgroup_ref_list) !=
2419 !trans->delayed_ref_elem.seq) {
2420 /* list without seq or seq without list */
2421 printk(KERN_ERR "btrfs: qgroup accounting update error, list is%s empty, seq is %llu\n",
2422 list_empty(&trans->qgroup_ref_list) ? "" : " not",
2423 trans->delayed_ref_elem.seq);
2424 BUG();
2425 }
2426
2427 if (!trans->delayed_ref_elem.seq)
2428 return 0;
2429
2430 while (!list_empty(&trans->qgroup_ref_list)) {
2431 qgroup_update = list_first_entry(&trans->qgroup_ref_list,
2432 struct qgroup_update, list);
2433 list_del(&qgroup_update->list);
2434 if (!ret)
2435 ret = btrfs_qgroup_account_ref(
2436 trans, fs_info, qgroup_update->node,
2437 qgroup_update->extent_op);
2438 kfree(qgroup_update);
2439 }
2440
2441 btrfs_put_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
2442
2443 return ret;
2444}
2445
bb721703
CM
2446static int refs_newer(struct btrfs_delayed_ref_root *delayed_refs, int seq,
2447 int count)
2448{
2449 int val = atomic_read(&delayed_refs->ref_seq);
2450
2451 if (val < seq || val >= seq + count)
2452 return 1;
2453 return 0;
2454}
2455
c3e69d58
CM
2456/*
2457 * this starts processing the delayed reference count updates and
2458 * extent insertions we have queued up so far. count can be
2459 * 0, which means to process everything in the tree at the start
2460 * of the run (but not newly added entries), or it can be some target
2461 * number you'd like to process.
79787eaa
JM
2462 *
2463 * Returns 0 on success or if called with an aborted transaction
2464 * Returns <0 on error and aborts the transaction
c3e69d58
CM
2465 */
2466int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2467 struct btrfs_root *root, unsigned long count)
2468{
2469 struct rb_node *node;
2470 struct btrfs_delayed_ref_root *delayed_refs;
2471 struct btrfs_delayed_ref_node *ref;
2472 struct list_head cluster;
2473 int ret;
a168650c 2474 u64 delayed_start;
c3e69d58
CM
2475 int run_all = count == (unsigned long)-1;
2476 int run_most = 0;
1fa11e26 2477 int loops;
c3e69d58 2478
79787eaa
JM
2479 /* We'll clean this up in btrfs_cleanup_transaction */
2480 if (trans->aborted)
2481 return 0;
2482
c3e69d58
CM
2483 if (root == root->fs_info->extent_root)
2484 root = root->fs_info->tree_root;
2485
edf39272
JS
2486 btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
2487
c3e69d58
CM
2488 delayed_refs = &trans->transaction->delayed_refs;
2489 INIT_LIST_HEAD(&cluster);
bb721703
CM
2490 if (count == 0) {
2491 count = delayed_refs->num_entries * 2;
2492 run_most = 1;
2493 }
2494
2495 if (!run_all && !run_most) {
2496 int old;
2497 int seq = atomic_read(&delayed_refs->ref_seq);
2498
2499progress:
2500 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2501 if (old) {
2502 DEFINE_WAIT(__wait);
2503 if (delayed_refs->num_entries < 16348)
2504 return 0;
2505
2506 prepare_to_wait(&delayed_refs->wait, &__wait,
2507 TASK_UNINTERRUPTIBLE);
2508
2509 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2510 if (old) {
2511 schedule();
2512 finish_wait(&delayed_refs->wait, &__wait);
2513
2514 if (!refs_newer(delayed_refs, seq, 256))
2515 goto progress;
2516 else
2517 return 0;
2518 } else {
2519 finish_wait(&delayed_refs->wait, &__wait);
2520 goto again;
2521 }
2522 }
2523
2524 } else {
2525 atomic_inc(&delayed_refs->procs_running_refs);
2526 }
2527
c3e69d58 2528again:
1fa11e26 2529 loops = 0;
c3e69d58 2530 spin_lock(&delayed_refs->lock);
097b8a7c 2531
709c0486
AJ
2532#ifdef SCRAMBLE_DELAYED_REFS
2533 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2534#endif
2535
c3e69d58
CM
2536 while (1) {
2537 if (!(run_all || run_most) &&
2538 delayed_refs->num_heads_ready < 64)
2539 break;
eb099670 2540
56bec294 2541 /*
c3e69d58
CM
2542 * go find something we can process in the rbtree. We start at
2543 * the beginning of the tree, and then build a cluster
2544 * of refs to process starting at the first one we are able to
2545 * lock
56bec294 2546 */
a168650c 2547 delayed_start = delayed_refs->run_delayed_start;
c3e69d58
CM
2548 ret = btrfs_find_ref_cluster(trans, &cluster,
2549 delayed_refs->run_delayed_start);
2550 if (ret)
56bec294
CM
2551 break;
2552
c3e69d58 2553 ret = run_clustered_refs(trans, root, &cluster);
79787eaa 2554 if (ret < 0) {
093486c4 2555 btrfs_release_ref_cluster(&cluster);
79787eaa
JM
2556 spin_unlock(&delayed_refs->lock);
2557 btrfs_abort_transaction(trans, root, ret);
bb721703 2558 atomic_dec(&delayed_refs->procs_running_refs);
79787eaa
JM
2559 return ret;
2560 }
c3e69d58 2561
bb721703
CM
2562 atomic_add(ret, &delayed_refs->ref_seq);
2563
c3e69d58
CM
2564 count -= min_t(unsigned long, ret, count);
2565
2566 if (count == 0)
2567 break;
a168650c 2568
1fa11e26
AJ
2569 if (delayed_start >= delayed_refs->run_delayed_start) {
2570 if (loops == 0) {
2571 /*
2572 * btrfs_find_ref_cluster looped. let's do one
2573 * more cycle. if we don't run any delayed ref
2574 * during that cycle (because we can't because
2575 * all of them are blocked), bail out.
2576 */
2577 loops = 1;
2578 } else {
2579 /*
2580 * no runnable refs left, stop trying
2581 */
2582 BUG_ON(run_all);
2583 break;
2584 }
2585 }
2586 if (ret) {
a168650c 2587 /* refs were run, let's reset staleness detection */
1fa11e26 2588 loops = 0;
a168650c 2589 }
eb099670 2590 }
c3e69d58 2591
56bec294 2592 if (run_all) {
ea658bad
JB
2593 if (!list_empty(&trans->new_bgs)) {
2594 spin_unlock(&delayed_refs->lock);
2595 btrfs_create_pending_block_groups(trans, root);
2596 spin_lock(&delayed_refs->lock);
2597 }
2598
56bec294 2599 node = rb_first(&delayed_refs->root);
c3e69d58 2600 if (!node)
56bec294 2601 goto out;
c3e69d58 2602 count = (unsigned long)-1;
e9d0b13b 2603
56bec294
CM
2604 while (node) {
2605 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2606 rb_node);
2607 if (btrfs_delayed_ref_is_head(ref)) {
2608 struct btrfs_delayed_ref_head *head;
5caf2a00 2609
56bec294
CM
2610 head = btrfs_delayed_node_to_head(ref);
2611 atomic_inc(&ref->refs);
2612
2613 spin_unlock(&delayed_refs->lock);
8cc33e5c
DS
2614 /*
2615 * Mutex was contended, block until it's
2616 * released and try again
2617 */
56bec294
CM
2618 mutex_lock(&head->mutex);
2619 mutex_unlock(&head->mutex);
2620
2621 btrfs_put_delayed_ref(ref);
1887be66 2622 cond_resched();
56bec294
CM
2623 goto again;
2624 }
2625 node = rb_next(node);
2626 }
2627 spin_unlock(&delayed_refs->lock);
56bec294
CM
2628 schedule_timeout(1);
2629 goto again;
5f39d397 2630 }
54aa1f4d 2631out:
bb721703
CM
2632 atomic_dec(&delayed_refs->procs_running_refs);
2633 smp_mb();
2634 if (waitqueue_active(&delayed_refs->wait))
2635 wake_up(&delayed_refs->wait);
2636
c3e69d58 2637 spin_unlock(&delayed_refs->lock);
edf39272 2638 assert_qgroups_uptodate(trans);
a28ec197
CM
2639 return 0;
2640}
2641
5d4f98a2
YZ
2642int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2643 struct btrfs_root *root,
2644 u64 bytenr, u64 num_bytes, u64 flags,
2645 int is_data)
2646{
2647 struct btrfs_delayed_extent_op *extent_op;
2648 int ret;
2649
78a6184a 2650 extent_op = btrfs_alloc_delayed_extent_op();
5d4f98a2
YZ
2651 if (!extent_op)
2652 return -ENOMEM;
2653
2654 extent_op->flags_to_set = flags;
2655 extent_op->update_flags = 1;
2656 extent_op->update_key = 0;
2657 extent_op->is_data = is_data ? 1 : 0;
2658
66d7e7f0
AJ
2659 ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2660 num_bytes, extent_op);
5d4f98a2 2661 if (ret)
78a6184a 2662 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
2663 return ret;
2664}
2665
2666static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2667 struct btrfs_root *root,
2668 struct btrfs_path *path,
2669 u64 objectid, u64 offset, u64 bytenr)
2670{
2671 struct btrfs_delayed_ref_head *head;
2672 struct btrfs_delayed_ref_node *ref;
2673 struct btrfs_delayed_data_ref *data_ref;
2674 struct btrfs_delayed_ref_root *delayed_refs;
2675 struct rb_node *node;
2676 int ret = 0;
2677
2678 ret = -ENOENT;
2679 delayed_refs = &trans->transaction->delayed_refs;
2680 spin_lock(&delayed_refs->lock);
2681 head = btrfs_find_delayed_ref_head(trans, bytenr);
2682 if (!head)
2683 goto out;
2684
2685 if (!mutex_trylock(&head->mutex)) {
2686 atomic_inc(&head->node.refs);
2687 spin_unlock(&delayed_refs->lock);
2688
b3b4aa74 2689 btrfs_release_path(path);
5d4f98a2 2690
8cc33e5c
DS
2691 /*
2692 * Mutex was contended, block until it's released and let
2693 * caller try again
2694 */
5d4f98a2
YZ
2695 mutex_lock(&head->mutex);
2696 mutex_unlock(&head->mutex);
2697 btrfs_put_delayed_ref(&head->node);
2698 return -EAGAIN;
2699 }
2700
2701 node = rb_prev(&head->node.rb_node);
2702 if (!node)
2703 goto out_unlock;
2704
2705 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2706
2707 if (ref->bytenr != bytenr)
2708 goto out_unlock;
2709
2710 ret = 1;
2711 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2712 goto out_unlock;
2713
2714 data_ref = btrfs_delayed_node_to_data_ref(ref);
2715
2716 node = rb_prev(node);
2717 if (node) {
df57dbe6
LB
2718 int seq = ref->seq;
2719
5d4f98a2 2720 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
df57dbe6 2721 if (ref->bytenr == bytenr && ref->seq == seq)
5d4f98a2
YZ
2722 goto out_unlock;
2723 }
2724
2725 if (data_ref->root != root->root_key.objectid ||
2726 data_ref->objectid != objectid || data_ref->offset != offset)
2727 goto out_unlock;
2728
2729 ret = 0;
2730out_unlock:
2731 mutex_unlock(&head->mutex);
2732out:
2733 spin_unlock(&delayed_refs->lock);
2734 return ret;
2735}
2736
2737static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2738 struct btrfs_root *root,
2739 struct btrfs_path *path,
2740 u64 objectid, u64 offset, u64 bytenr)
be20aa9d
CM
2741{
2742 struct btrfs_root *extent_root = root->fs_info->extent_root;
f321e491 2743 struct extent_buffer *leaf;
5d4f98a2
YZ
2744 struct btrfs_extent_data_ref *ref;
2745 struct btrfs_extent_inline_ref *iref;
2746 struct btrfs_extent_item *ei;
f321e491 2747 struct btrfs_key key;
5d4f98a2 2748 u32 item_size;
be20aa9d 2749 int ret;
925baedd 2750
be20aa9d 2751 key.objectid = bytenr;
31840ae1 2752 key.offset = (u64)-1;
f321e491 2753 key.type = BTRFS_EXTENT_ITEM_KEY;
be20aa9d 2754
be20aa9d
CM
2755 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2756 if (ret < 0)
2757 goto out;
79787eaa 2758 BUG_ON(ret == 0); /* Corruption */
80ff3856
YZ
2759
2760 ret = -ENOENT;
2761 if (path->slots[0] == 0)
31840ae1 2762 goto out;
be20aa9d 2763
31840ae1 2764 path->slots[0]--;
f321e491 2765 leaf = path->nodes[0];
5d4f98a2 2766 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
be20aa9d 2767
5d4f98a2 2768 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
be20aa9d 2769 goto out;
f321e491 2770
5d4f98a2
YZ
2771 ret = 1;
2772 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2773#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2774 if (item_size < sizeof(*ei)) {
2775 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2776 goto out;
2777 }
2778#endif
2779 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
bd09835d 2780
5d4f98a2
YZ
2781 if (item_size != sizeof(*ei) +
2782 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2783 goto out;
be20aa9d 2784
5d4f98a2
YZ
2785 if (btrfs_extent_generation(leaf, ei) <=
2786 btrfs_root_last_snapshot(&root->root_item))
2787 goto out;
2788
2789 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2790 if (btrfs_extent_inline_ref_type(leaf, iref) !=
2791 BTRFS_EXTENT_DATA_REF_KEY)
2792 goto out;
2793
2794 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2795 if (btrfs_extent_refs(leaf, ei) !=
2796 btrfs_extent_data_ref_count(leaf, ref) ||
2797 btrfs_extent_data_ref_root(leaf, ref) !=
2798 root->root_key.objectid ||
2799 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2800 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2801 goto out;
2802
2803 ret = 0;
2804out:
2805 return ret;
2806}
2807
2808int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2809 struct btrfs_root *root,
2810 u64 objectid, u64 offset, u64 bytenr)
2811{
2812 struct btrfs_path *path;
2813 int ret;
2814 int ret2;
2815
2816 path = btrfs_alloc_path();
2817 if (!path)
2818 return -ENOENT;
2819
2820 do {
2821 ret = check_committed_ref(trans, root, path, objectid,
2822 offset, bytenr);
2823 if (ret && ret != -ENOENT)
f321e491 2824 goto out;
80ff3856 2825
5d4f98a2
YZ
2826 ret2 = check_delayed_ref(trans, root, path, objectid,
2827 offset, bytenr);
2828 } while (ret2 == -EAGAIN);
2829
2830 if (ret2 && ret2 != -ENOENT) {
2831 ret = ret2;
2832 goto out;
f321e491 2833 }
5d4f98a2
YZ
2834
2835 if (ret != -ENOENT || ret2 != -ENOENT)
2836 ret = 0;
be20aa9d 2837out:
80ff3856 2838 btrfs_free_path(path);
f0486c68
YZ
2839 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2840 WARN_ON(ret > 0);
f321e491 2841 return ret;
be20aa9d 2842}
c5739bba 2843
5d4f98a2 2844static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
b7a9f29f 2845 struct btrfs_root *root,
5d4f98a2 2846 struct extent_buffer *buf,
66d7e7f0 2847 int full_backref, int inc, int for_cow)
31840ae1
ZY
2848{
2849 u64 bytenr;
5d4f98a2
YZ
2850 u64 num_bytes;
2851 u64 parent;
31840ae1 2852 u64 ref_root;
31840ae1 2853 u32 nritems;
31840ae1
ZY
2854 struct btrfs_key key;
2855 struct btrfs_file_extent_item *fi;
2856 int i;
2857 int level;
2858 int ret = 0;
31840ae1 2859 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
66d7e7f0 2860 u64, u64, u64, u64, u64, u64, int);
31840ae1
ZY
2861
2862 ref_root = btrfs_header_owner(buf);
31840ae1
ZY
2863 nritems = btrfs_header_nritems(buf);
2864 level = btrfs_header_level(buf);
2865
5d4f98a2
YZ
2866 if (!root->ref_cows && level == 0)
2867 return 0;
31840ae1 2868
5d4f98a2
YZ
2869 if (inc)
2870 process_func = btrfs_inc_extent_ref;
2871 else
2872 process_func = btrfs_free_extent;
31840ae1 2873
5d4f98a2
YZ
2874 if (full_backref)
2875 parent = buf->start;
2876 else
2877 parent = 0;
2878
2879 for (i = 0; i < nritems; i++) {
31840ae1 2880 if (level == 0) {
5d4f98a2 2881 btrfs_item_key_to_cpu(buf, &key, i);
31840ae1
ZY
2882 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2883 continue;
5d4f98a2 2884 fi = btrfs_item_ptr(buf, i,
31840ae1
ZY
2885 struct btrfs_file_extent_item);
2886 if (btrfs_file_extent_type(buf, fi) ==
2887 BTRFS_FILE_EXTENT_INLINE)
2888 continue;
2889 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2890 if (bytenr == 0)
2891 continue;
5d4f98a2
YZ
2892
2893 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2894 key.offset -= btrfs_file_extent_offset(buf, fi);
2895 ret = process_func(trans, root, bytenr, num_bytes,
2896 parent, ref_root, key.objectid,
66d7e7f0 2897 key.offset, for_cow);
31840ae1
ZY
2898 if (ret)
2899 goto fail;
2900 } else {
5d4f98a2
YZ
2901 bytenr = btrfs_node_blockptr(buf, i);
2902 num_bytes = btrfs_level_size(root, level - 1);
2903 ret = process_func(trans, root, bytenr, num_bytes,
66d7e7f0
AJ
2904 parent, ref_root, level - 1, 0,
2905 for_cow);
31840ae1
ZY
2906 if (ret)
2907 goto fail;
2908 }
2909 }
2910 return 0;
2911fail:
5d4f98a2
YZ
2912 return ret;
2913}
2914
2915int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
66d7e7f0 2916 struct extent_buffer *buf, int full_backref, int for_cow)
5d4f98a2 2917{
66d7e7f0 2918 return __btrfs_mod_ref(trans, root, buf, full_backref, 1, for_cow);
5d4f98a2
YZ
2919}
2920
2921int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
66d7e7f0 2922 struct extent_buffer *buf, int full_backref, int for_cow)
5d4f98a2 2923{
66d7e7f0 2924 return __btrfs_mod_ref(trans, root, buf, full_backref, 0, for_cow);
31840ae1
ZY
2925}
2926
9078a3e1
CM
2927static int write_one_cache_group(struct btrfs_trans_handle *trans,
2928 struct btrfs_root *root,
2929 struct btrfs_path *path,
2930 struct btrfs_block_group_cache *cache)
2931{
2932 int ret;
9078a3e1 2933 struct btrfs_root *extent_root = root->fs_info->extent_root;
5f39d397
CM
2934 unsigned long bi;
2935 struct extent_buffer *leaf;
9078a3e1 2936
9078a3e1 2937 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
54aa1f4d
CM
2938 if (ret < 0)
2939 goto fail;
79787eaa 2940 BUG_ON(ret); /* Corruption */
5f39d397
CM
2941
2942 leaf = path->nodes[0];
2943 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2944 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2945 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 2946 btrfs_release_path(path);
54aa1f4d 2947fail:
79787eaa
JM
2948 if (ret) {
2949 btrfs_abort_transaction(trans, root, ret);
9078a3e1 2950 return ret;
79787eaa 2951 }
9078a3e1
CM
2952 return 0;
2953
2954}
2955
4a8c9a62
YZ
2956static struct btrfs_block_group_cache *
2957next_block_group(struct btrfs_root *root,
2958 struct btrfs_block_group_cache *cache)
2959{
2960 struct rb_node *node;
2961 spin_lock(&root->fs_info->block_group_cache_lock);
2962 node = rb_next(&cache->cache_node);
2963 btrfs_put_block_group(cache);
2964 if (node) {
2965 cache = rb_entry(node, struct btrfs_block_group_cache,
2966 cache_node);
11dfe35a 2967 btrfs_get_block_group(cache);
4a8c9a62
YZ
2968 } else
2969 cache = NULL;
2970 spin_unlock(&root->fs_info->block_group_cache_lock);
2971 return cache;
2972}
2973
0af3d00b
JB
2974static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2975 struct btrfs_trans_handle *trans,
2976 struct btrfs_path *path)
2977{
2978 struct btrfs_root *root = block_group->fs_info->tree_root;
2979 struct inode *inode = NULL;
2980 u64 alloc_hint = 0;
2b20982e 2981 int dcs = BTRFS_DC_ERROR;
0af3d00b
JB
2982 int num_pages = 0;
2983 int retries = 0;
2984 int ret = 0;
2985
2986 /*
2987 * If this block group is smaller than 100 megs don't bother caching the
2988 * block group.
2989 */
2990 if (block_group->key.offset < (100 * 1024 * 1024)) {
2991 spin_lock(&block_group->lock);
2992 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2993 spin_unlock(&block_group->lock);
2994 return 0;
2995 }
2996
2997again:
2998 inode = lookup_free_space_inode(root, block_group, path);
2999 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3000 ret = PTR_ERR(inode);
b3b4aa74 3001 btrfs_release_path(path);
0af3d00b
JB
3002 goto out;
3003 }
3004
3005 if (IS_ERR(inode)) {
3006 BUG_ON(retries);
3007 retries++;
3008
3009 if (block_group->ro)
3010 goto out_free;
3011
3012 ret = create_free_space_inode(root, trans, block_group, path);
3013 if (ret)
3014 goto out_free;
3015 goto again;
3016 }
3017
5b0e95bf
JB
3018 /* We've already setup this transaction, go ahead and exit */
3019 if (block_group->cache_generation == trans->transid &&
3020 i_size_read(inode)) {
3021 dcs = BTRFS_DC_SETUP;
3022 goto out_put;
3023 }
3024
0af3d00b
JB
3025 /*
3026 * We want to set the generation to 0, that way if anything goes wrong
3027 * from here on out we know not to trust this cache when we load up next
3028 * time.
3029 */
3030 BTRFS_I(inode)->generation = 0;
3031 ret = btrfs_update_inode(trans, root, inode);
3032 WARN_ON(ret);
3033
3034 if (i_size_read(inode) > 0) {
3035 ret = btrfs_truncate_free_space_cache(root, trans, path,
3036 inode);
3037 if (ret)
3038 goto out_put;
3039 }
3040
3041 spin_lock(&block_group->lock);
cf7c1ef6
LB
3042 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3043 !btrfs_test_opt(root, SPACE_CACHE)) {
3044 /*
3045 * don't bother trying to write stuff out _if_
3046 * a) we're not cached,
3047 * b) we're with nospace_cache mount option.
3048 */
2b20982e 3049 dcs = BTRFS_DC_WRITTEN;
0af3d00b
JB
3050 spin_unlock(&block_group->lock);
3051 goto out_put;
3052 }
3053 spin_unlock(&block_group->lock);
3054
6fc823b1
JB
3055 /*
3056 * Try to preallocate enough space based on how big the block group is.
3057 * Keep in mind this has to include any pinned space which could end up
3058 * taking up quite a bit since it's not folded into the other space
3059 * cache.
3060 */
3061 num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
0af3d00b
JB
3062 if (!num_pages)
3063 num_pages = 1;
3064
0af3d00b
JB
3065 num_pages *= 16;
3066 num_pages *= PAGE_CACHE_SIZE;
3067
3068 ret = btrfs_check_data_free_space(inode, num_pages);
3069 if (ret)
3070 goto out_put;
3071
3072 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3073 num_pages, num_pages,
3074 &alloc_hint);
2b20982e
JB
3075 if (!ret)
3076 dcs = BTRFS_DC_SETUP;
0af3d00b 3077 btrfs_free_reserved_data_space(inode, num_pages);
c09544e0 3078
0af3d00b
JB
3079out_put:
3080 iput(inode);
3081out_free:
b3b4aa74 3082 btrfs_release_path(path);
0af3d00b
JB
3083out:
3084 spin_lock(&block_group->lock);
e65cbb94 3085 if (!ret && dcs == BTRFS_DC_SETUP)
5b0e95bf 3086 block_group->cache_generation = trans->transid;
2b20982e 3087 block_group->disk_cache_state = dcs;
0af3d00b
JB
3088 spin_unlock(&block_group->lock);
3089
3090 return ret;
3091}
3092
96b5179d
CM
3093int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3094 struct btrfs_root *root)
9078a3e1 3095{
4a8c9a62 3096 struct btrfs_block_group_cache *cache;
9078a3e1 3097 int err = 0;
9078a3e1 3098 struct btrfs_path *path;
96b5179d 3099 u64 last = 0;
9078a3e1
CM
3100
3101 path = btrfs_alloc_path();
3102 if (!path)
3103 return -ENOMEM;
3104
0af3d00b
JB
3105again:
3106 while (1) {
3107 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3108 while (cache) {
3109 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3110 break;
3111 cache = next_block_group(root, cache);
3112 }
3113 if (!cache) {
3114 if (last == 0)
3115 break;
3116 last = 0;
3117 continue;
3118 }
3119 err = cache_save_setup(cache, trans, path);
3120 last = cache->key.objectid + cache->key.offset;
3121 btrfs_put_block_group(cache);
3122 }
3123
d397712b 3124 while (1) {
4a8c9a62
YZ
3125 if (last == 0) {
3126 err = btrfs_run_delayed_refs(trans, root,
3127 (unsigned long)-1);
79787eaa
JM
3128 if (err) /* File system offline */
3129 goto out;
0f9dd46c 3130 }
54aa1f4d 3131
4a8c9a62
YZ
3132 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3133 while (cache) {
0af3d00b
JB
3134 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3135 btrfs_put_block_group(cache);
3136 goto again;
3137 }
3138
4a8c9a62
YZ
3139 if (cache->dirty)
3140 break;
3141 cache = next_block_group(root, cache);
3142 }
3143 if (!cache) {
3144 if (last == 0)
3145 break;
3146 last = 0;
3147 continue;
3148 }
0f9dd46c 3149
0cb59c99
JB
3150 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3151 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
e8569813 3152 cache->dirty = 0;
4a8c9a62 3153 last = cache->key.objectid + cache->key.offset;
0f9dd46c 3154
4a8c9a62 3155 err = write_one_cache_group(trans, root, path, cache);
79787eaa
JM
3156 if (err) /* File system offline */
3157 goto out;
3158
4a8c9a62 3159 btrfs_put_block_group(cache);
9078a3e1 3160 }
4a8c9a62 3161
0cb59c99
JB
3162 while (1) {
3163 /*
3164 * I don't think this is needed since we're just marking our
3165 * preallocated extent as written, but just in case it can't
3166 * hurt.
3167 */
3168 if (last == 0) {
3169 err = btrfs_run_delayed_refs(trans, root,
3170 (unsigned long)-1);
79787eaa
JM
3171 if (err) /* File system offline */
3172 goto out;
0cb59c99
JB
3173 }
3174
3175 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3176 while (cache) {
3177 /*
3178 * Really this shouldn't happen, but it could if we
3179 * couldn't write the entire preallocated extent and
3180 * splitting the extent resulted in a new block.
3181 */
3182 if (cache->dirty) {
3183 btrfs_put_block_group(cache);
3184 goto again;
3185 }
3186 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3187 break;
3188 cache = next_block_group(root, cache);
3189 }
3190 if (!cache) {
3191 if (last == 0)
3192 break;
3193 last = 0;
3194 continue;
3195 }
3196
79787eaa 3197 err = btrfs_write_out_cache(root, trans, cache, path);
0cb59c99
JB
3198
3199 /*
3200 * If we didn't have an error then the cache state is still
3201 * NEED_WRITE, so we can set it to WRITTEN.
3202 */
79787eaa 3203 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
0cb59c99
JB
3204 cache->disk_cache_state = BTRFS_DC_WRITTEN;
3205 last = cache->key.objectid + cache->key.offset;
3206 btrfs_put_block_group(cache);
3207 }
79787eaa 3208out:
0cb59c99 3209
9078a3e1 3210 btrfs_free_path(path);
79787eaa 3211 return err;
9078a3e1
CM
3212}
3213
d2fb3437
YZ
3214int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3215{
3216 struct btrfs_block_group_cache *block_group;
3217 int readonly = 0;
3218
3219 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3220 if (!block_group || block_group->ro)
3221 readonly = 1;
3222 if (block_group)
fa9c0d79 3223 btrfs_put_block_group(block_group);
d2fb3437
YZ
3224 return readonly;
3225}
3226
593060d7
CM
3227static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3228 u64 total_bytes, u64 bytes_used,
3229 struct btrfs_space_info **space_info)
3230{
3231 struct btrfs_space_info *found;
b742bb82
YZ
3232 int i;
3233 int factor;
3234
3235 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3236 BTRFS_BLOCK_GROUP_RAID10))
3237 factor = 2;
3238 else
3239 factor = 1;
593060d7
CM
3240
3241 found = __find_space_info(info, flags);
3242 if (found) {
25179201 3243 spin_lock(&found->lock);
593060d7 3244 found->total_bytes += total_bytes;
89a55897 3245 found->disk_total += total_bytes * factor;
593060d7 3246 found->bytes_used += bytes_used;
b742bb82 3247 found->disk_used += bytes_used * factor;
8f18cf13 3248 found->full = 0;
25179201 3249 spin_unlock(&found->lock);
593060d7
CM
3250 *space_info = found;
3251 return 0;
3252 }
c146afad 3253 found = kzalloc(sizeof(*found), GFP_NOFS);
593060d7
CM
3254 if (!found)
3255 return -ENOMEM;
3256
b742bb82
YZ
3257 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3258 INIT_LIST_HEAD(&found->block_groups[i]);
80eb234a 3259 init_rwsem(&found->groups_sem);
0f9dd46c 3260 spin_lock_init(&found->lock);
52ba6929 3261 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
593060d7 3262 found->total_bytes = total_bytes;
89a55897 3263 found->disk_total = total_bytes * factor;
593060d7 3264 found->bytes_used = bytes_used;
b742bb82 3265 found->disk_used = bytes_used * factor;
593060d7 3266 found->bytes_pinned = 0;
e8569813 3267 found->bytes_reserved = 0;
c146afad 3268 found->bytes_readonly = 0;
f0486c68 3269 found->bytes_may_use = 0;
593060d7 3270 found->full = 0;
0e4f8f88 3271 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
6d74119f 3272 found->chunk_alloc = 0;
fdb5effd
JB
3273 found->flush = 0;
3274 init_waitqueue_head(&found->wait);
593060d7 3275 *space_info = found;
4184ea7f 3276 list_add_rcu(&found->list, &info->space_info);
b4d7c3c9
LZ
3277 if (flags & BTRFS_BLOCK_GROUP_DATA)
3278 info->data_sinfo = found;
593060d7
CM
3279 return 0;
3280}
3281
8790d502
CM
3282static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3283{
899c81ea
ID
3284 u64 extra_flags = chunk_to_extended(flags) &
3285 BTRFS_EXTENDED_PROFILE_MASK;
a46d11a8 3286
de98ced9 3287 write_seqlock(&fs_info->profiles_lock);
a46d11a8
ID
3288 if (flags & BTRFS_BLOCK_GROUP_DATA)
3289 fs_info->avail_data_alloc_bits |= extra_flags;
3290 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3291 fs_info->avail_metadata_alloc_bits |= extra_flags;
3292 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3293 fs_info->avail_system_alloc_bits |= extra_flags;
de98ced9 3294 write_sequnlock(&fs_info->profiles_lock);
8790d502 3295}
593060d7 3296
fc67c450
ID
3297/*
3298 * returns target flags in extended format or 0 if restripe for this
3299 * chunk_type is not in progress
c6664b42
ID
3300 *
3301 * should be called with either volume_mutex or balance_lock held
fc67c450
ID
3302 */
3303static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3304{
3305 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3306 u64 target = 0;
3307
fc67c450
ID
3308 if (!bctl)
3309 return 0;
3310
3311 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3312 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3313 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3314 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3315 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3316 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3317 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3318 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3319 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3320 }
3321
3322 return target;
3323}
3324
a46d11a8
ID
3325/*
3326 * @flags: available profiles in extended format (see ctree.h)
3327 *
e4d8ec0f
ID
3328 * Returns reduced profile in chunk format. If profile changing is in
3329 * progress (either running or paused) picks the target profile (if it's
3330 * already available), otherwise falls back to plain reducing.
a46d11a8 3331 */
2b82032c 3332u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
ec44a35c 3333{
cd02dca5
CM
3334 /*
3335 * we add in the count of missing devices because we want
3336 * to make sure that any RAID levels on a degraded FS
3337 * continue to be honored.
3338 */
3339 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3340 root->fs_info->fs_devices->missing_devices;
fc67c450 3341 u64 target;
53b381b3 3342 u64 tmp;
a061fc8d 3343
fc67c450
ID
3344 /*
3345 * see if restripe for this chunk_type is in progress, if so
3346 * try to reduce to the target profile
3347 */
e4d8ec0f 3348 spin_lock(&root->fs_info->balance_lock);
fc67c450
ID
3349 target = get_restripe_target(root->fs_info, flags);
3350 if (target) {
3351 /* pick target profile only if it's already available */
3352 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
e4d8ec0f 3353 spin_unlock(&root->fs_info->balance_lock);
fc67c450 3354 return extended_to_chunk(target);
e4d8ec0f
ID
3355 }
3356 }
3357 spin_unlock(&root->fs_info->balance_lock);
3358
53b381b3 3359 /* First, mask out the RAID levels which aren't possible */
a061fc8d 3360 if (num_devices == 1)
53b381b3
DW
3361 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
3362 BTRFS_BLOCK_GROUP_RAID5);
3363 if (num_devices < 3)
3364 flags &= ~BTRFS_BLOCK_GROUP_RAID6;
a061fc8d
CM
3365 if (num_devices < 4)
3366 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3367
53b381b3
DW
3368 tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3369 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
3370 BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
3371 flags &= ~tmp;
ec44a35c 3372
53b381b3
DW
3373 if (tmp & BTRFS_BLOCK_GROUP_RAID6)
3374 tmp = BTRFS_BLOCK_GROUP_RAID6;
3375 else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
3376 tmp = BTRFS_BLOCK_GROUP_RAID5;
3377 else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
3378 tmp = BTRFS_BLOCK_GROUP_RAID10;
3379 else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
3380 tmp = BTRFS_BLOCK_GROUP_RAID1;
3381 else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
3382 tmp = BTRFS_BLOCK_GROUP_RAID0;
a46d11a8 3383
53b381b3 3384 return extended_to_chunk(flags | tmp);
ec44a35c
CM
3385}
3386
b742bb82 3387static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
6a63209f 3388{
de98ced9
MX
3389 unsigned seq;
3390
3391 do {
3392 seq = read_seqbegin(&root->fs_info->profiles_lock);
3393
3394 if (flags & BTRFS_BLOCK_GROUP_DATA)
3395 flags |= root->fs_info->avail_data_alloc_bits;
3396 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3397 flags |= root->fs_info->avail_system_alloc_bits;
3398 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3399 flags |= root->fs_info->avail_metadata_alloc_bits;
3400 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
6fef8df1 3401
b742bb82 3402 return btrfs_reduce_alloc_profile(root, flags);
6a63209f
JB
3403}
3404
6d07bcec 3405u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
9ed74f2d 3406{
b742bb82 3407 u64 flags;
53b381b3 3408 u64 ret;
9ed74f2d 3409
b742bb82
YZ
3410 if (data)
3411 flags = BTRFS_BLOCK_GROUP_DATA;
3412 else if (root == root->fs_info->chunk_root)
3413 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9ed74f2d 3414 else
b742bb82 3415 flags = BTRFS_BLOCK_GROUP_METADATA;
9ed74f2d 3416
53b381b3
DW
3417 ret = get_alloc_profile(root, flags);
3418 return ret;
6a63209f 3419}
9ed74f2d 3420
6a63209f 3421/*
6a63209f
JB
3422 * This will check the space that the inode allocates from to make sure we have
3423 * enough space for bytes.
6a63209f 3424 */
0ca1f7ce 3425int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
6a63209f 3426{
6a63209f 3427 struct btrfs_space_info *data_sinfo;
0ca1f7ce 3428 struct btrfs_root *root = BTRFS_I(inode)->root;
b4d7c3c9 3429 struct btrfs_fs_info *fs_info = root->fs_info;
ab6e2410 3430 u64 used;
0af3d00b 3431 int ret = 0, committed = 0, alloc_chunk = 1;
6a63209f 3432
6a63209f 3433 /* make sure bytes are sectorsize aligned */
fda2832f 3434 bytes = ALIGN(bytes, root->sectorsize);
6a63209f 3435
82d5902d
LZ
3436 if (root == root->fs_info->tree_root ||
3437 BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
0af3d00b
JB
3438 alloc_chunk = 0;
3439 committed = 1;
3440 }
3441
b4d7c3c9 3442 data_sinfo = fs_info->data_sinfo;
33b4d47f
CM
3443 if (!data_sinfo)
3444 goto alloc;
9ed74f2d 3445
6a63209f
JB
3446again:
3447 /* make sure we have enough space to handle the data first */
3448 spin_lock(&data_sinfo->lock);
8929ecfa
YZ
3449 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3450 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3451 data_sinfo->bytes_may_use;
ab6e2410
JB
3452
3453 if (used + bytes > data_sinfo->total_bytes) {
4e06bdd6 3454 struct btrfs_trans_handle *trans;
9ed74f2d 3455
6a63209f
JB
3456 /*
3457 * if we don't have enough free bytes in this space then we need
3458 * to alloc a new chunk.
3459 */
0af3d00b 3460 if (!data_sinfo->full && alloc_chunk) {
6a63209f 3461 u64 alloc_target;
9ed74f2d 3462
0e4f8f88 3463 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
6a63209f 3464 spin_unlock(&data_sinfo->lock);
33b4d47f 3465alloc:
6a63209f 3466 alloc_target = btrfs_get_alloc_profile(root, 1);
7a7eaa40 3467 trans = btrfs_join_transaction(root);
a22285a6
YZ
3468 if (IS_ERR(trans))
3469 return PTR_ERR(trans);
9ed74f2d 3470
6a63209f 3471 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0e4f8f88
CM
3472 alloc_target,
3473 CHUNK_ALLOC_NO_FORCE);
6a63209f 3474 btrfs_end_transaction(trans, root);
d52a5b5f
MX
3475 if (ret < 0) {
3476 if (ret != -ENOSPC)
3477 return ret;
3478 else
3479 goto commit_trans;
3480 }
9ed74f2d 3481
b4d7c3c9
LZ
3482 if (!data_sinfo)
3483 data_sinfo = fs_info->data_sinfo;
3484
6a63209f
JB
3485 goto again;
3486 }
f2bb8f5c
JB
3487
3488 /*
3489 * If we have less pinned bytes than we want to allocate then
3490 * don't bother committing the transaction, it won't help us.
3491 */
3492 if (data_sinfo->bytes_pinned < bytes)
3493 committed = 1;
6a63209f 3494 spin_unlock(&data_sinfo->lock);
6a63209f 3495
4e06bdd6 3496 /* commit the current transaction and try again */
d52a5b5f 3497commit_trans:
a4abeea4
JB
3498 if (!committed &&
3499 !atomic_read(&root->fs_info->open_ioctl_trans)) {
4e06bdd6 3500 committed = 1;
7a7eaa40 3501 trans = btrfs_join_transaction(root);
a22285a6
YZ
3502 if (IS_ERR(trans))
3503 return PTR_ERR(trans);
4e06bdd6
JB
3504 ret = btrfs_commit_transaction(trans, root);
3505 if (ret)
3506 return ret;
3507 goto again;
3508 }
9ed74f2d 3509
6a63209f
JB
3510 return -ENOSPC;
3511 }
3512 data_sinfo->bytes_may_use += bytes;
8c2a3ca2 3513 trace_btrfs_space_reservation(root->fs_info, "space_info",
2bcc0328 3514 data_sinfo->flags, bytes, 1);
6a63209f 3515 spin_unlock(&data_sinfo->lock);
6a63209f 3516
9ed74f2d 3517 return 0;
9ed74f2d 3518}
6a63209f 3519
6a63209f 3520/*
fb25e914 3521 * Called if we need to clear a data reservation for this inode.
6a63209f 3522 */
0ca1f7ce 3523void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
e3ccfa98 3524{
0ca1f7ce 3525 struct btrfs_root *root = BTRFS_I(inode)->root;
6a63209f 3526 struct btrfs_space_info *data_sinfo;
e3ccfa98 3527
6a63209f 3528 /* make sure bytes are sectorsize aligned */
fda2832f 3529 bytes = ALIGN(bytes, root->sectorsize);
e3ccfa98 3530
b4d7c3c9 3531 data_sinfo = root->fs_info->data_sinfo;
6a63209f
JB
3532 spin_lock(&data_sinfo->lock);
3533 data_sinfo->bytes_may_use -= bytes;
8c2a3ca2 3534 trace_btrfs_space_reservation(root->fs_info, "space_info",
2bcc0328 3535 data_sinfo->flags, bytes, 0);
6a63209f 3536 spin_unlock(&data_sinfo->lock);
e3ccfa98
JB
3537}
3538
97e728d4 3539static void force_metadata_allocation(struct btrfs_fs_info *info)
e3ccfa98 3540{
97e728d4
JB
3541 struct list_head *head = &info->space_info;
3542 struct btrfs_space_info *found;
e3ccfa98 3543
97e728d4
JB
3544 rcu_read_lock();
3545 list_for_each_entry_rcu(found, head, list) {
3546 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
0e4f8f88 3547 found->force_alloc = CHUNK_ALLOC_FORCE;
e3ccfa98 3548 }
97e728d4 3549 rcu_read_unlock();
e3ccfa98
JB
3550}
3551
e5bc2458 3552static int should_alloc_chunk(struct btrfs_root *root,
698d0082 3553 struct btrfs_space_info *sinfo, int force)
32c00aff 3554{
fb25e914 3555 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
424499db 3556 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
0e4f8f88 3557 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
e5bc2458 3558 u64 thresh;
e3ccfa98 3559
0e4f8f88
CM
3560 if (force == CHUNK_ALLOC_FORCE)
3561 return 1;
3562
fb25e914
JB
3563 /*
3564 * We need to take into account the global rsv because for all intents
3565 * and purposes it's used space. Don't worry about locking the
3566 * global_rsv, it doesn't change except when the transaction commits.
3567 */
54338b5c
JB
3568 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3569 num_allocated += global_rsv->size;
fb25e914 3570
0e4f8f88
CM
3571 /*
3572 * in limited mode, we want to have some free space up to
3573 * about 1% of the FS size.
3574 */
3575 if (force == CHUNK_ALLOC_LIMITED) {
6c41761f 3576 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
0e4f8f88
CM
3577 thresh = max_t(u64, 64 * 1024 * 1024,
3578 div_factor_fine(thresh, 1));
3579
3580 if (num_bytes - num_allocated < thresh)
3581 return 1;
3582 }
0e4f8f88 3583
698d0082 3584 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
14ed0ca6 3585 return 0;
424499db 3586 return 1;
32c00aff
JB
3587}
3588
15d1ff81
LB
3589static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3590{
3591 u64 num_dev;
3592
53b381b3
DW
3593 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
3594 BTRFS_BLOCK_GROUP_RAID0 |
3595 BTRFS_BLOCK_GROUP_RAID5 |
3596 BTRFS_BLOCK_GROUP_RAID6))
15d1ff81
LB
3597 num_dev = root->fs_info->fs_devices->rw_devices;
3598 else if (type & BTRFS_BLOCK_GROUP_RAID1)
3599 num_dev = 2;
3600 else
3601 num_dev = 1; /* DUP or single */
3602
3603 /* metadata for updaing devices and chunk tree */
3604 return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3605}
3606
3607static void check_system_chunk(struct btrfs_trans_handle *trans,
3608 struct btrfs_root *root, u64 type)
3609{
3610 struct btrfs_space_info *info;
3611 u64 left;
3612 u64 thresh;
3613
3614 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3615 spin_lock(&info->lock);
3616 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3617 info->bytes_reserved - info->bytes_readonly;
3618 spin_unlock(&info->lock);
3619
3620 thresh = get_system_chunk_thresh(root, type);
3621 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
3622 printk(KERN_INFO "left=%llu, need=%llu, flags=%llu\n",
3623 left, thresh, type);
3624 dump_space_info(info, 0, 0);
3625 }
3626
3627 if (left < thresh) {
3628 u64 flags;
3629
3630 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3631 btrfs_alloc_chunk(trans, root, flags);
3632 }
3633}
3634
6324fbf3 3635static int do_chunk_alloc(struct btrfs_trans_handle *trans,
698d0082 3636 struct btrfs_root *extent_root, u64 flags, int force)
9ed74f2d 3637{
6324fbf3 3638 struct btrfs_space_info *space_info;
97e728d4 3639 struct btrfs_fs_info *fs_info = extent_root->fs_info;
6d74119f 3640 int wait_for_alloc = 0;
9ed74f2d 3641 int ret = 0;
9ed74f2d 3642
c6b305a8
JB
3643 /* Don't re-enter if we're already allocating a chunk */
3644 if (trans->allocating_chunk)
3645 return -ENOSPC;
3646
6324fbf3 3647 space_info = __find_space_info(extent_root->fs_info, flags);
593060d7
CM
3648 if (!space_info) {
3649 ret = update_space_info(extent_root->fs_info, flags,
3650 0, 0, &space_info);
79787eaa 3651 BUG_ON(ret); /* -ENOMEM */
9ed74f2d 3652 }
79787eaa 3653 BUG_ON(!space_info); /* Logic error */
9ed74f2d 3654
6d74119f 3655again:
25179201 3656 spin_lock(&space_info->lock);
9e622d6b 3657 if (force < space_info->force_alloc)
0e4f8f88 3658 force = space_info->force_alloc;
25179201
JB
3659 if (space_info->full) {
3660 spin_unlock(&space_info->lock);
6d74119f 3661 return 0;
9ed74f2d
JB
3662 }
3663
698d0082 3664 if (!should_alloc_chunk(extent_root, space_info, force)) {
25179201 3665 spin_unlock(&space_info->lock);
6d74119f
JB
3666 return 0;
3667 } else if (space_info->chunk_alloc) {
3668 wait_for_alloc = 1;
3669 } else {
3670 space_info->chunk_alloc = 1;
9ed74f2d 3671 }
0e4f8f88 3672
25179201 3673 spin_unlock(&space_info->lock);
9ed74f2d 3674
6d74119f
JB
3675 mutex_lock(&fs_info->chunk_mutex);
3676
3677 /*
3678 * The chunk_mutex is held throughout the entirety of a chunk
3679 * allocation, so once we've acquired the chunk_mutex we know that the
3680 * other guy is done and we need to recheck and see if we should
3681 * allocate.
3682 */
3683 if (wait_for_alloc) {
3684 mutex_unlock(&fs_info->chunk_mutex);
3685 wait_for_alloc = 0;
3686 goto again;
3687 }
3688
c6b305a8
JB
3689 trans->allocating_chunk = true;
3690
67377734
JB
3691 /*
3692 * If we have mixed data/metadata chunks we want to make sure we keep
3693 * allocating mixed chunks instead of individual chunks.
3694 */
3695 if (btrfs_mixed_space_info(space_info))
3696 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3697
97e728d4
JB
3698 /*
3699 * if we're doing a data chunk, go ahead and make sure that
3700 * we keep a reasonable number of metadata chunks allocated in the
3701 * FS as well.
3702 */
9ed74f2d 3703 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
97e728d4
JB
3704 fs_info->data_chunk_allocations++;
3705 if (!(fs_info->data_chunk_allocations %
3706 fs_info->metadata_ratio))
3707 force_metadata_allocation(fs_info);
9ed74f2d
JB
3708 }
3709
15d1ff81
LB
3710 /*
3711 * Check if we have enough space in SYSTEM chunk because we may need
3712 * to update devices.
3713 */
3714 check_system_chunk(trans, extent_root, flags);
3715
2b82032c 3716 ret = btrfs_alloc_chunk(trans, extent_root, flags);
c6b305a8 3717 trans->allocating_chunk = false;
92b8e897 3718
9ed74f2d 3719 spin_lock(&space_info->lock);
a81cb9a2
AO
3720 if (ret < 0 && ret != -ENOSPC)
3721 goto out;
9ed74f2d 3722 if (ret)
6324fbf3 3723 space_info->full = 1;
424499db
YZ
3724 else
3725 ret = 1;
6d74119f 3726
0e4f8f88 3727 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
a81cb9a2 3728out:
6d74119f 3729 space_info->chunk_alloc = 0;
9ed74f2d 3730 spin_unlock(&space_info->lock);
a25c75d5 3731 mutex_unlock(&fs_info->chunk_mutex);
0f9dd46c 3732 return ret;
6324fbf3 3733}
9ed74f2d 3734
a80c8dcf
JB
3735static int can_overcommit(struct btrfs_root *root,
3736 struct btrfs_space_info *space_info, u64 bytes,
08e007d2 3737 enum btrfs_reserve_flush_enum flush)
a80c8dcf 3738{
96f1bb57 3739 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
a80c8dcf 3740 u64 profile = btrfs_get_alloc_profile(root, 0);
96f1bb57 3741 u64 rsv_size = 0;
a80c8dcf
JB
3742 u64 avail;
3743 u64 used;
70afa399 3744 u64 to_add;
a80c8dcf
JB
3745
3746 used = space_info->bytes_used + space_info->bytes_reserved +
96f1bb57
JB
3747 space_info->bytes_pinned + space_info->bytes_readonly;
3748
3749 spin_lock(&global_rsv->lock);
3750 rsv_size = global_rsv->size;
3751 spin_unlock(&global_rsv->lock);
3752
3753 /*
3754 * We only want to allow over committing if we have lots of actual space
3755 * free, but if we don't have enough space to handle the global reserve
3756 * space then we could end up having a real enospc problem when trying
3757 * to allocate a chunk or some other such important allocation.
3758 */
3759 rsv_size <<= 1;
3760 if (used + rsv_size >= space_info->total_bytes)
3761 return 0;
3762
3763 used += space_info->bytes_may_use;
a80c8dcf
JB
3764
3765 spin_lock(&root->fs_info->free_chunk_lock);
3766 avail = root->fs_info->free_chunk_space;
3767 spin_unlock(&root->fs_info->free_chunk_lock);
3768
3769 /*
3770 * If we have dup, raid1 or raid10 then only half of the free
53b381b3
DW
3771 * space is actually useable. For raid56, the space info used
3772 * doesn't include the parity drive, so we don't have to
3773 * change the math
a80c8dcf
JB
3774 */
3775 if (profile & (BTRFS_BLOCK_GROUP_DUP |
3776 BTRFS_BLOCK_GROUP_RAID1 |
3777 BTRFS_BLOCK_GROUP_RAID10))
3778 avail >>= 1;
3779
70afa399
JB
3780 to_add = space_info->total_bytes;
3781
a80c8dcf 3782 /*
561c294d
MX
3783 * If we aren't flushing all things, let us overcommit up to
3784 * 1/2th of the space. If we can flush, don't let us overcommit
3785 * too much, let it overcommit up to 1/8 of the space.
a80c8dcf 3786 */
08e007d2 3787 if (flush == BTRFS_RESERVE_FLUSH_ALL)
70afa399 3788 to_add >>= 3;
a80c8dcf 3789 else
70afa399 3790 to_add >>= 1;
a80c8dcf 3791
70afa399
JB
3792 /*
3793 * Limit the overcommit to the amount of free space we could possibly
3794 * allocate for chunks.
3795 */
3796 to_add = min(avail, to_add);
a80c8dcf 3797
70afa399 3798 if (used + bytes < space_info->total_bytes + to_add)
a80c8dcf
JB
3799 return 1;
3800 return 0;
3801}
3802
da633a42
MX
3803static inline int writeback_inodes_sb_nr_if_idle_safe(struct super_block *sb,
3804 unsigned long nr_pages,
3805 enum wb_reason reason)
1135d6df 3806{
da633a42
MX
3807 /* the flusher is dealing with the dirty inodes now. */
3808 if (writeback_in_progress(sb->s_bdi))
3809 return 1;
3810
3811 if (down_read_trylock(&sb->s_umount)) {
1135d6df
JB
3812 writeback_inodes_sb_nr(sb, nr_pages, reason);
3813 up_read(&sb->s_umount);
3814 return 1;
3815 }
3816
3817 return 0;
3818}
3819
da633a42
MX
3820void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
3821 unsigned long nr_pages)
3822{
3823 struct super_block *sb = root->fs_info->sb;
3824 int started;
3825
3826 /* If we can not start writeback, just sync all the delalloc file. */
3827 started = writeback_inodes_sb_nr_if_idle_safe(sb, nr_pages,
3828 WB_REASON_FS_FREE_SPACE);
3829 if (!started) {
3830 /*
3831 * We needn't worry the filesystem going from r/w to r/o though
3832 * we don't acquire ->s_umount mutex, because the filesystem
3833 * should guarantee the delalloc inodes list be empty after
3834 * the filesystem is readonly(all dirty pages are written to
3835 * the disk).
3836 */
3837 btrfs_start_delalloc_inodes(root, 0);
3838 btrfs_wait_ordered_extents(root, 0);
3839 }
3840}
3841
9ed74f2d 3842/*
5da9d01b 3843 * shrink metadata reservation for delalloc
9ed74f2d 3844 */
f4c738c2
JB
3845static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
3846 bool wait_ordered)
5da9d01b 3847{
0ca1f7ce 3848 struct btrfs_block_rsv *block_rsv;
0019f10d 3849 struct btrfs_space_info *space_info;
663350ac 3850 struct btrfs_trans_handle *trans;
f4c738c2 3851 u64 delalloc_bytes;
5da9d01b 3852 u64 max_reclaim;
b1953bce 3853 long time_left;
877da174 3854 unsigned long nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
b1953bce 3855 int loops = 0;
08e007d2 3856 enum btrfs_reserve_flush_enum flush;
5da9d01b 3857
663350ac 3858 trans = (struct btrfs_trans_handle *)current->journal_info;
0ca1f7ce 3859 block_rsv = &root->fs_info->delalloc_block_rsv;
0019f10d 3860 space_info = block_rsv->space_info;
bf9022e0
CM
3861
3862 smp_mb();
963d678b
MX
3863 delalloc_bytes = percpu_counter_sum_positive(
3864 &root->fs_info->delalloc_bytes);
f4c738c2 3865 if (delalloc_bytes == 0) {
fdb5effd 3866 if (trans)
f4c738c2 3867 return;
6bbe3a9c 3868 btrfs_wait_ordered_extents(root, 0);
f4c738c2 3869 return;
fdb5effd
JB
3870 }
3871
f4c738c2
JB
3872 while (delalloc_bytes && loops < 3) {
3873 max_reclaim = min(delalloc_bytes, to_reclaim);
3874 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
da633a42 3875 btrfs_writeback_inodes_sb_nr(root, nr_pages);
dea31f52
JB
3876 /*
3877 * We need to wait for the async pages to actually start before
3878 * we do anything.
3879 */
3880 wait_event(root->fs_info->async_submit_wait,
3881 !atomic_read(&root->fs_info->async_delalloc_pages));
3882
08e007d2
MX
3883 if (!trans)
3884 flush = BTRFS_RESERVE_FLUSH_ALL;
3885 else
3886 flush = BTRFS_RESERVE_NO_FLUSH;
0019f10d 3887 spin_lock(&space_info->lock);
08e007d2 3888 if (can_overcommit(root, space_info, orig, flush)) {
f4c738c2
JB
3889 spin_unlock(&space_info->lock);
3890 break;
3891 }
0019f10d 3892 spin_unlock(&space_info->lock);
5da9d01b 3893
36e39c40 3894 loops++;
f104d044 3895 if (wait_ordered && !trans) {
6bbe3a9c 3896 btrfs_wait_ordered_extents(root, 0);
f104d044 3897 } else {
f4c738c2 3898 time_left = schedule_timeout_killable(1);
f104d044
JB
3899 if (time_left)
3900 break;
3901 }
f4c738c2 3902 smp_mb();
963d678b
MX
3903 delalloc_bytes = percpu_counter_sum_positive(
3904 &root->fs_info->delalloc_bytes);
5da9d01b 3905 }
5da9d01b
YZ
3906}
3907
663350ac
JB
3908/**
3909 * maybe_commit_transaction - possibly commit the transaction if its ok to
3910 * @root - the root we're allocating for
3911 * @bytes - the number of bytes we want to reserve
3912 * @force - force the commit
8bb8ab2e 3913 *
663350ac
JB
3914 * This will check to make sure that committing the transaction will actually
3915 * get us somewhere and then commit the transaction if it does. Otherwise it
3916 * will return -ENOSPC.
8bb8ab2e 3917 */
663350ac
JB
3918static int may_commit_transaction(struct btrfs_root *root,
3919 struct btrfs_space_info *space_info,
3920 u64 bytes, int force)
3921{
3922 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
3923 struct btrfs_trans_handle *trans;
3924
3925 trans = (struct btrfs_trans_handle *)current->journal_info;
3926 if (trans)
3927 return -EAGAIN;
3928
3929 if (force)
3930 goto commit;
3931
3932 /* See if there is enough pinned space to make this reservation */
3933 spin_lock(&space_info->lock);
3934 if (space_info->bytes_pinned >= bytes) {
3935 spin_unlock(&space_info->lock);
3936 goto commit;
3937 }
3938 spin_unlock(&space_info->lock);
3939
3940 /*
3941 * See if there is some space in the delayed insertion reservation for
3942 * this reservation.
3943 */
3944 if (space_info != delayed_rsv->space_info)
3945 return -ENOSPC;
3946
d9b0218f 3947 spin_lock(&space_info->lock);
663350ac 3948 spin_lock(&delayed_rsv->lock);
d9b0218f 3949 if (space_info->bytes_pinned + delayed_rsv->size < bytes) {
663350ac 3950 spin_unlock(&delayed_rsv->lock);
d9b0218f 3951 spin_unlock(&space_info->lock);
663350ac
JB
3952 return -ENOSPC;
3953 }
3954 spin_unlock(&delayed_rsv->lock);
d9b0218f 3955 spin_unlock(&space_info->lock);
663350ac
JB
3956
3957commit:
3958 trans = btrfs_join_transaction(root);
3959 if (IS_ERR(trans))
3960 return -ENOSPC;
3961
3962 return btrfs_commit_transaction(trans, root);
3963}
3964
96c3f433 3965enum flush_state {
67b0fd63
JB
3966 FLUSH_DELAYED_ITEMS_NR = 1,
3967 FLUSH_DELAYED_ITEMS = 2,
3968 FLUSH_DELALLOC = 3,
3969 FLUSH_DELALLOC_WAIT = 4,
ea658bad
JB
3970 ALLOC_CHUNK = 5,
3971 COMMIT_TRANS = 6,
96c3f433
JB
3972};
3973
3974static int flush_space(struct btrfs_root *root,
3975 struct btrfs_space_info *space_info, u64 num_bytes,
3976 u64 orig_bytes, int state)
3977{
3978 struct btrfs_trans_handle *trans;
3979 int nr;
f4c738c2 3980 int ret = 0;
96c3f433
JB
3981
3982 switch (state) {
96c3f433
JB
3983 case FLUSH_DELAYED_ITEMS_NR:
3984 case FLUSH_DELAYED_ITEMS:
3985 if (state == FLUSH_DELAYED_ITEMS_NR) {
3986 u64 bytes = btrfs_calc_trans_metadata_size(root, 1);
3987
3988 nr = (int)div64_u64(num_bytes, bytes);
3989 if (!nr)
3990 nr = 1;
3991 nr *= 2;
3992 } else {
3993 nr = -1;
3994 }
3995 trans = btrfs_join_transaction(root);
3996 if (IS_ERR(trans)) {
3997 ret = PTR_ERR(trans);
3998 break;
3999 }
4000 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4001 btrfs_end_transaction(trans, root);
4002 break;
67b0fd63
JB
4003 case FLUSH_DELALLOC:
4004 case FLUSH_DELALLOC_WAIT:
4005 shrink_delalloc(root, num_bytes, orig_bytes,
4006 state == FLUSH_DELALLOC_WAIT);
4007 break;
ea658bad
JB
4008 case ALLOC_CHUNK:
4009 trans = btrfs_join_transaction(root);
4010 if (IS_ERR(trans)) {
4011 ret = PTR_ERR(trans);
4012 break;
4013 }
4014 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
ea658bad
JB
4015 btrfs_get_alloc_profile(root, 0),
4016 CHUNK_ALLOC_NO_FORCE);
4017 btrfs_end_transaction(trans, root);
4018 if (ret == -ENOSPC)
4019 ret = 0;
4020 break;
96c3f433
JB
4021 case COMMIT_TRANS:
4022 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4023 break;
4024 default:
4025 ret = -ENOSPC;
4026 break;
4027 }
4028
4029 return ret;
4030}
4a92b1b8
JB
4031/**
4032 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4033 * @root - the root we're allocating for
4034 * @block_rsv - the block_rsv we're allocating for
4035 * @orig_bytes - the number of bytes we want
48fc7f7e 4036 * @flush - whether or not we can flush to make our reservation
8bb8ab2e 4037 *
4a92b1b8
JB
4038 * This will reserve orgi_bytes number of bytes from the space info associated
4039 * with the block_rsv. If there is not enough space it will make an attempt to
4040 * flush out space to make room. It will do this by flushing delalloc if
4041 * possible or committing the transaction. If flush is 0 then no attempts to
4042 * regain reservations will be made and this will fail if there is not enough
4043 * space already.
8bb8ab2e 4044 */
4a92b1b8 4045static int reserve_metadata_bytes(struct btrfs_root *root,
8bb8ab2e 4046 struct btrfs_block_rsv *block_rsv,
08e007d2
MX
4047 u64 orig_bytes,
4048 enum btrfs_reserve_flush_enum flush)
9ed74f2d 4049{
f0486c68 4050 struct btrfs_space_info *space_info = block_rsv->space_info;
2bf64758 4051 u64 used;
8bb8ab2e 4052 u64 num_bytes = orig_bytes;
67b0fd63 4053 int flush_state = FLUSH_DELAYED_ITEMS_NR;
8bb8ab2e 4054 int ret = 0;
fdb5effd 4055 bool flushing = false;
9ed74f2d 4056
8bb8ab2e 4057again:
fdb5effd 4058 ret = 0;
8bb8ab2e 4059 spin_lock(&space_info->lock);
fdb5effd 4060 /*
08e007d2
MX
4061 * We only want to wait if somebody other than us is flushing and we
4062 * are actually allowed to flush all things.
fdb5effd 4063 */
08e007d2
MX
4064 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4065 space_info->flush) {
fdb5effd
JB
4066 spin_unlock(&space_info->lock);
4067 /*
4068 * If we have a trans handle we can't wait because the flusher
4069 * may have to commit the transaction, which would mean we would
4070 * deadlock since we are waiting for the flusher to finish, but
4071 * hold the current transaction open.
4072 */
663350ac 4073 if (current->journal_info)
fdb5effd 4074 return -EAGAIN;
b9688bb8
AJ
4075 ret = wait_event_killable(space_info->wait, !space_info->flush);
4076 /* Must have been killed, return */
4077 if (ret)
fdb5effd
JB
4078 return -EINTR;
4079
4080 spin_lock(&space_info->lock);
4081 }
4082
4083 ret = -ENOSPC;
2bf64758
JB
4084 used = space_info->bytes_used + space_info->bytes_reserved +
4085 space_info->bytes_pinned + space_info->bytes_readonly +
4086 space_info->bytes_may_use;
9ed74f2d 4087
8bb8ab2e
JB
4088 /*
4089 * The idea here is that we've not already over-reserved the block group
4090 * then we can go ahead and save our reservation first and then start
4091 * flushing if we need to. Otherwise if we've already overcommitted
4092 * lets start flushing stuff first and then come back and try to make
4093 * our reservation.
4094 */
2bf64758
JB
4095 if (used <= space_info->total_bytes) {
4096 if (used + orig_bytes <= space_info->total_bytes) {
fb25e914 4097 space_info->bytes_may_use += orig_bytes;
8c2a3ca2 4098 trace_btrfs_space_reservation(root->fs_info,
2bcc0328 4099 "space_info", space_info->flags, orig_bytes, 1);
8bb8ab2e
JB
4100 ret = 0;
4101 } else {
4102 /*
4103 * Ok set num_bytes to orig_bytes since we aren't
4104 * overocmmitted, this way we only try and reclaim what
4105 * we need.
4106 */
4107 num_bytes = orig_bytes;
4108 }
4109 } else {
4110 /*
4111 * Ok we're over committed, set num_bytes to the overcommitted
4112 * amount plus the amount of bytes that we need for this
4113 * reservation.
4114 */
2bf64758 4115 num_bytes = used - space_info->total_bytes +
96c3f433 4116 (orig_bytes * 2);
8bb8ab2e 4117 }
9ed74f2d 4118
44734ed1
JB
4119 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4120 space_info->bytes_may_use += orig_bytes;
4121 trace_btrfs_space_reservation(root->fs_info, "space_info",
4122 space_info->flags, orig_bytes,
4123 1);
4124 ret = 0;
2bf64758
JB
4125 }
4126
8bb8ab2e
JB
4127 /*
4128 * Couldn't make our reservation, save our place so while we're trying
4129 * to reclaim space we can actually use it instead of somebody else
4130 * stealing it from us.
08e007d2
MX
4131 *
4132 * We make the other tasks wait for the flush only when we can flush
4133 * all things.
8bb8ab2e 4134 */
72bcd99d 4135 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
fdb5effd
JB
4136 flushing = true;
4137 space_info->flush = 1;
8bb8ab2e 4138 }
9ed74f2d 4139
f0486c68 4140 spin_unlock(&space_info->lock);
9ed74f2d 4141
08e007d2 4142 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
8bb8ab2e 4143 goto out;
f0486c68 4144
96c3f433
JB
4145 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4146 flush_state);
4147 flush_state++;
08e007d2
MX
4148
4149 /*
4150 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4151 * would happen. So skip delalloc flush.
4152 */
4153 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4154 (flush_state == FLUSH_DELALLOC ||
4155 flush_state == FLUSH_DELALLOC_WAIT))
4156 flush_state = ALLOC_CHUNK;
4157
96c3f433 4158 if (!ret)
8bb8ab2e 4159 goto again;
08e007d2
MX
4160 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4161 flush_state < COMMIT_TRANS)
4162 goto again;
4163 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4164 flush_state <= COMMIT_TRANS)
8bb8ab2e
JB
4165 goto again;
4166
4167out:
5d80366e
JB
4168 if (ret == -ENOSPC &&
4169 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
4170 struct btrfs_block_rsv *global_rsv =
4171 &root->fs_info->global_block_rsv;
4172
4173 if (block_rsv != global_rsv &&
4174 !block_rsv_use_bytes(global_rsv, orig_bytes))
4175 ret = 0;
4176 }
fdb5effd 4177 if (flushing) {
8bb8ab2e 4178 spin_lock(&space_info->lock);
fdb5effd
JB
4179 space_info->flush = 0;
4180 wake_up_all(&space_info->wait);
8bb8ab2e 4181 spin_unlock(&space_info->lock);
f0486c68 4182 }
f0486c68
YZ
4183 return ret;
4184}
4185
79787eaa
JM
4186static struct btrfs_block_rsv *get_block_rsv(
4187 const struct btrfs_trans_handle *trans,
4188 const struct btrfs_root *root)
f0486c68 4189{
4c13d758
JB
4190 struct btrfs_block_rsv *block_rsv = NULL;
4191
0e721106
JB
4192 if (root->ref_cows)
4193 block_rsv = trans->block_rsv;
4194
4195 if (root == root->fs_info->csum_root && trans->adding_csums)
f0486c68 4196 block_rsv = trans->block_rsv;
4c13d758
JB
4197
4198 if (!block_rsv)
f0486c68
YZ
4199 block_rsv = root->block_rsv;
4200
4201 if (!block_rsv)
4202 block_rsv = &root->fs_info->empty_block_rsv;
4203
4204 return block_rsv;
4205}
4206
4207static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4208 u64 num_bytes)
4209{
4210 int ret = -ENOSPC;
4211 spin_lock(&block_rsv->lock);
4212 if (block_rsv->reserved >= num_bytes) {
4213 block_rsv->reserved -= num_bytes;
4214 if (block_rsv->reserved < block_rsv->size)
4215 block_rsv->full = 0;
4216 ret = 0;
4217 }
4218 spin_unlock(&block_rsv->lock);
4219 return ret;
4220}
4221
4222static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4223 u64 num_bytes, int update_size)
4224{
4225 spin_lock(&block_rsv->lock);
4226 block_rsv->reserved += num_bytes;
4227 if (update_size)
4228 block_rsv->size += num_bytes;
4229 else if (block_rsv->reserved >= block_rsv->size)
4230 block_rsv->full = 1;
4231 spin_unlock(&block_rsv->lock);
4232}
4233
8c2a3ca2
JB
4234static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4235 struct btrfs_block_rsv *block_rsv,
62a45b60 4236 struct btrfs_block_rsv *dest, u64 num_bytes)
f0486c68
YZ
4237{
4238 struct btrfs_space_info *space_info = block_rsv->space_info;
4239
4240 spin_lock(&block_rsv->lock);
4241 if (num_bytes == (u64)-1)
4242 num_bytes = block_rsv->size;
4243 block_rsv->size -= num_bytes;
4244 if (block_rsv->reserved >= block_rsv->size) {
4245 num_bytes = block_rsv->reserved - block_rsv->size;
4246 block_rsv->reserved = block_rsv->size;
4247 block_rsv->full = 1;
4248 } else {
4249 num_bytes = 0;
4250 }
4251 spin_unlock(&block_rsv->lock);
4252
4253 if (num_bytes > 0) {
4254 if (dest) {
e9e22899
JB
4255 spin_lock(&dest->lock);
4256 if (!dest->full) {
4257 u64 bytes_to_add;
4258
4259 bytes_to_add = dest->size - dest->reserved;
4260 bytes_to_add = min(num_bytes, bytes_to_add);
4261 dest->reserved += bytes_to_add;
4262 if (dest->reserved >= dest->size)
4263 dest->full = 1;
4264 num_bytes -= bytes_to_add;
4265 }
4266 spin_unlock(&dest->lock);
4267 }
4268 if (num_bytes) {
f0486c68 4269 spin_lock(&space_info->lock);
fb25e914 4270 space_info->bytes_may_use -= num_bytes;
8c2a3ca2 4271 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4272 space_info->flags, num_bytes, 0);
36e39c40 4273 space_info->reservation_progress++;
f0486c68 4274 spin_unlock(&space_info->lock);
4e06bdd6 4275 }
9ed74f2d 4276 }
f0486c68 4277}
4e06bdd6 4278
f0486c68
YZ
4279static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4280 struct btrfs_block_rsv *dst, u64 num_bytes)
4281{
4282 int ret;
9ed74f2d 4283
f0486c68
YZ
4284 ret = block_rsv_use_bytes(src, num_bytes);
4285 if (ret)
4286 return ret;
9ed74f2d 4287
f0486c68 4288 block_rsv_add_bytes(dst, num_bytes, 1);
9ed74f2d
JB
4289 return 0;
4290}
4291
66d8f3dd 4292void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
9ed74f2d 4293{
f0486c68
YZ
4294 memset(rsv, 0, sizeof(*rsv));
4295 spin_lock_init(&rsv->lock);
66d8f3dd 4296 rsv->type = type;
f0486c68
YZ
4297}
4298
66d8f3dd
MX
4299struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4300 unsigned short type)
f0486c68
YZ
4301{
4302 struct btrfs_block_rsv *block_rsv;
4303 struct btrfs_fs_info *fs_info = root->fs_info;
9ed74f2d 4304
f0486c68
YZ
4305 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4306 if (!block_rsv)
4307 return NULL;
9ed74f2d 4308
66d8f3dd 4309 btrfs_init_block_rsv(block_rsv, type);
f0486c68
YZ
4310 block_rsv->space_info = __find_space_info(fs_info,
4311 BTRFS_BLOCK_GROUP_METADATA);
f0486c68
YZ
4312 return block_rsv;
4313}
9ed74f2d 4314
f0486c68
YZ
4315void btrfs_free_block_rsv(struct btrfs_root *root,
4316 struct btrfs_block_rsv *rsv)
4317{
2aaa6655
JB
4318 if (!rsv)
4319 return;
dabdb640
JB
4320 btrfs_block_rsv_release(root, rsv, (u64)-1);
4321 kfree(rsv);
9ed74f2d
JB
4322}
4323
08e007d2
MX
4324int btrfs_block_rsv_add(struct btrfs_root *root,
4325 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4326 enum btrfs_reserve_flush_enum flush)
9ed74f2d 4327{
f0486c68 4328 int ret;
9ed74f2d 4329
f0486c68
YZ
4330 if (num_bytes == 0)
4331 return 0;
8bb8ab2e 4332
61b520a9 4333 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
f0486c68
YZ
4334 if (!ret) {
4335 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4336 return 0;
4337 }
9ed74f2d 4338
f0486c68 4339 return ret;
f0486c68 4340}
9ed74f2d 4341
4a92b1b8 4342int btrfs_block_rsv_check(struct btrfs_root *root,
36ba022a 4343 struct btrfs_block_rsv *block_rsv, int min_factor)
f0486c68
YZ
4344{
4345 u64 num_bytes = 0;
f0486c68 4346 int ret = -ENOSPC;
9ed74f2d 4347
f0486c68
YZ
4348 if (!block_rsv)
4349 return 0;
9ed74f2d 4350
f0486c68 4351 spin_lock(&block_rsv->lock);
36ba022a
JB
4352 num_bytes = div_factor(block_rsv->size, min_factor);
4353 if (block_rsv->reserved >= num_bytes)
4354 ret = 0;
4355 spin_unlock(&block_rsv->lock);
9ed74f2d 4356
36ba022a
JB
4357 return ret;
4358}
4359
08e007d2
MX
4360int btrfs_block_rsv_refill(struct btrfs_root *root,
4361 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4362 enum btrfs_reserve_flush_enum flush)
36ba022a
JB
4363{
4364 u64 num_bytes = 0;
4365 int ret = -ENOSPC;
4366
4367 if (!block_rsv)
4368 return 0;
4369
4370 spin_lock(&block_rsv->lock);
4371 num_bytes = min_reserved;
13553e52 4372 if (block_rsv->reserved >= num_bytes)
f0486c68 4373 ret = 0;
13553e52 4374 else
f0486c68 4375 num_bytes -= block_rsv->reserved;
f0486c68 4376 spin_unlock(&block_rsv->lock);
13553e52 4377
f0486c68
YZ
4378 if (!ret)
4379 return 0;
4380
aa38a711 4381 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
dabdb640
JB
4382 if (!ret) {
4383 block_rsv_add_bytes(block_rsv, num_bytes, 0);
f0486c68 4384 return 0;
6a63209f 4385 }
9ed74f2d 4386
13553e52 4387 return ret;
f0486c68
YZ
4388}
4389
4390int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4391 struct btrfs_block_rsv *dst_rsv,
4392 u64 num_bytes)
4393{
4394 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4395}
4396
4397void btrfs_block_rsv_release(struct btrfs_root *root,
4398 struct btrfs_block_rsv *block_rsv,
4399 u64 num_bytes)
4400{
4401 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4402 if (global_rsv->full || global_rsv == block_rsv ||
4403 block_rsv->space_info != global_rsv->space_info)
4404 global_rsv = NULL;
8c2a3ca2
JB
4405 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4406 num_bytes);
6a63209f
JB
4407}
4408
4409/*
8929ecfa
YZ
4410 * helper to calculate size of global block reservation.
4411 * the desired value is sum of space used by extent tree,
4412 * checksum tree and root tree
6a63209f 4413 */
8929ecfa 4414static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
6a63209f 4415{
8929ecfa
YZ
4416 struct btrfs_space_info *sinfo;
4417 u64 num_bytes;
4418 u64 meta_used;
4419 u64 data_used;
6c41761f 4420 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
6a63209f 4421
8929ecfa
YZ
4422 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4423 spin_lock(&sinfo->lock);
4424 data_used = sinfo->bytes_used;
4425 spin_unlock(&sinfo->lock);
33b4d47f 4426
8929ecfa
YZ
4427 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4428 spin_lock(&sinfo->lock);
6d48755d
JB
4429 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4430 data_used = 0;
8929ecfa
YZ
4431 meta_used = sinfo->bytes_used;
4432 spin_unlock(&sinfo->lock);
ab6e2410 4433
8929ecfa
YZ
4434 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4435 csum_size * 2;
4436 num_bytes += div64_u64(data_used + meta_used, 50);
4e06bdd6 4437
8929ecfa 4438 if (num_bytes * 3 > meta_used)
8e62c2de 4439 num_bytes = div64_u64(meta_used, 3);
ab6e2410 4440
8929ecfa
YZ
4441 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4442}
6a63209f 4443
8929ecfa
YZ
4444static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4445{
4446 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4447 struct btrfs_space_info *sinfo = block_rsv->space_info;
4448 u64 num_bytes;
6a63209f 4449
8929ecfa 4450 num_bytes = calc_global_metadata_size(fs_info);
33b4d47f 4451
8929ecfa 4452 spin_lock(&sinfo->lock);
1f699d38 4453 spin_lock(&block_rsv->lock);
4e06bdd6 4454
8929ecfa 4455 block_rsv->size = num_bytes;
4e06bdd6 4456
8929ecfa 4457 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
6d48755d
JB
4458 sinfo->bytes_reserved + sinfo->bytes_readonly +
4459 sinfo->bytes_may_use;
8929ecfa
YZ
4460
4461 if (sinfo->total_bytes > num_bytes) {
4462 num_bytes = sinfo->total_bytes - num_bytes;
4463 block_rsv->reserved += num_bytes;
fb25e914 4464 sinfo->bytes_may_use += num_bytes;
8c2a3ca2 4465 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4466 sinfo->flags, num_bytes, 1);
6a63209f 4467 }
6a63209f 4468
8929ecfa
YZ
4469 if (block_rsv->reserved >= block_rsv->size) {
4470 num_bytes = block_rsv->reserved - block_rsv->size;
fb25e914 4471 sinfo->bytes_may_use -= num_bytes;
8c2a3ca2 4472 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4473 sinfo->flags, num_bytes, 0);
36e39c40 4474 sinfo->reservation_progress++;
8929ecfa
YZ
4475 block_rsv->reserved = block_rsv->size;
4476 block_rsv->full = 1;
4477 }
182608c8 4478
8929ecfa 4479 spin_unlock(&block_rsv->lock);
1f699d38 4480 spin_unlock(&sinfo->lock);
6a63209f
JB
4481}
4482
f0486c68 4483static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 4484{
f0486c68 4485 struct btrfs_space_info *space_info;
6a63209f 4486
f0486c68
YZ
4487 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4488 fs_info->chunk_block_rsv.space_info = space_info;
6a63209f 4489
f0486c68 4490 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
8929ecfa 4491 fs_info->global_block_rsv.space_info = space_info;
8929ecfa 4492 fs_info->delalloc_block_rsv.space_info = space_info;
f0486c68
YZ
4493 fs_info->trans_block_rsv.space_info = space_info;
4494 fs_info->empty_block_rsv.space_info = space_info;
6d668dda 4495 fs_info->delayed_block_rsv.space_info = space_info;
f0486c68 4496
8929ecfa
YZ
4497 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4498 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4499 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4500 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
f0486c68 4501 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
8929ecfa 4502
8929ecfa 4503 update_global_block_rsv(fs_info);
6a63209f
JB
4504}
4505
8929ecfa 4506static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 4507{
8c2a3ca2
JB
4508 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4509 (u64)-1);
8929ecfa
YZ
4510 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4511 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4512 WARN_ON(fs_info->trans_block_rsv.size > 0);
4513 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4514 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4515 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
6d668dda
JB
4516 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4517 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
fcb80c2a
JB
4518}
4519
a22285a6
YZ
4520void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4521 struct btrfs_root *root)
6a63209f 4522{
0e721106
JB
4523 if (!trans->block_rsv)
4524 return;
4525
a22285a6
YZ
4526 if (!trans->bytes_reserved)
4527 return;
6a63209f 4528
e77266e4 4529 trace_btrfs_space_reservation(root->fs_info, "transaction",
2bcc0328 4530 trans->transid, trans->bytes_reserved, 0);
b24e03db 4531 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
a22285a6
YZ
4532 trans->bytes_reserved = 0;
4533}
6a63209f 4534
79787eaa 4535/* Can only return 0 or -ENOSPC */
d68fc57b
YZ
4536int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4537 struct inode *inode)
4538{
4539 struct btrfs_root *root = BTRFS_I(inode)->root;
4540 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4541 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4542
4543 /*
fcb80c2a
JB
4544 * We need to hold space in order to delete our orphan item once we've
4545 * added it, so this takes the reservation so we can release it later
4546 * when we are truly done with the orphan item.
d68fc57b 4547 */
ff5714cc 4548 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
4549 trace_btrfs_space_reservation(root->fs_info, "orphan",
4550 btrfs_ino(inode), num_bytes, 1);
d68fc57b 4551 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
6a63209f
JB
4552}
4553
d68fc57b 4554void btrfs_orphan_release_metadata(struct inode *inode)
97e728d4 4555{
d68fc57b 4556 struct btrfs_root *root = BTRFS_I(inode)->root;
ff5714cc 4557 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
4558 trace_btrfs_space_reservation(root->fs_info, "orphan",
4559 btrfs_ino(inode), num_bytes, 0);
d68fc57b
YZ
4560 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4561}
97e728d4 4562
a22285a6
YZ
4563int btrfs_snap_reserve_metadata(struct btrfs_trans_handle *trans,
4564 struct btrfs_pending_snapshot *pending)
4565{
4566 struct btrfs_root *root = pending->root;
4567 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4568 struct btrfs_block_rsv *dst_rsv = &pending->block_rsv;
4569 /*
48c03c4b
MX
4570 * two for root back/forward refs, two for directory entries,
4571 * one for root of the snapshot and one for parent inode.
a22285a6 4572 */
48c03c4b 4573 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 6);
a22285a6
YZ
4574 dst_rsv->space_info = src_rsv->space_info;
4575 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
97e728d4
JB
4576}
4577
7709cde3
JB
4578/**
4579 * drop_outstanding_extent - drop an outstanding extent
4580 * @inode: the inode we're dropping the extent for
4581 *
4582 * This is called when we are freeing up an outstanding extent, either called
4583 * after an error or after an extent is written. This will return the number of
4584 * reserved extents that need to be freed. This must be called with
4585 * BTRFS_I(inode)->lock held.
4586 */
9e0baf60
JB
4587static unsigned drop_outstanding_extent(struct inode *inode)
4588{
7fd2ae21 4589 unsigned drop_inode_space = 0;
9e0baf60
JB
4590 unsigned dropped_extents = 0;
4591
9e0baf60
JB
4592 BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4593 BTRFS_I(inode)->outstanding_extents--;
4594
7fd2ae21 4595 if (BTRFS_I(inode)->outstanding_extents == 0 &&
72ac3c0d
JB
4596 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4597 &BTRFS_I(inode)->runtime_flags))
7fd2ae21 4598 drop_inode_space = 1;
7fd2ae21 4599
9e0baf60
JB
4600 /*
4601 * If we have more or the same amount of outsanding extents than we have
4602 * reserved then we need to leave the reserved extents count alone.
4603 */
4604 if (BTRFS_I(inode)->outstanding_extents >=
4605 BTRFS_I(inode)->reserved_extents)
7fd2ae21 4606 return drop_inode_space;
9e0baf60
JB
4607
4608 dropped_extents = BTRFS_I(inode)->reserved_extents -
4609 BTRFS_I(inode)->outstanding_extents;
4610 BTRFS_I(inode)->reserved_extents -= dropped_extents;
7fd2ae21 4611 return dropped_extents + drop_inode_space;
9e0baf60
JB
4612}
4613
7709cde3
JB
4614/**
4615 * calc_csum_metadata_size - return the amount of metada space that must be
4616 * reserved/free'd for the given bytes.
4617 * @inode: the inode we're manipulating
4618 * @num_bytes: the number of bytes in question
4619 * @reserve: 1 if we are reserving space, 0 if we are freeing space
4620 *
4621 * This adjusts the number of csum_bytes in the inode and then returns the
4622 * correct amount of metadata that must either be reserved or freed. We
4623 * calculate how many checksums we can fit into one leaf and then divide the
4624 * number of bytes that will need to be checksumed by this value to figure out
4625 * how many checksums will be required. If we are adding bytes then the number
4626 * may go up and we will return the number of additional bytes that must be
4627 * reserved. If it is going down we will return the number of bytes that must
4628 * be freed.
4629 *
4630 * This must be called with BTRFS_I(inode)->lock held.
4631 */
4632static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
4633 int reserve)
6324fbf3 4634{
7709cde3
JB
4635 struct btrfs_root *root = BTRFS_I(inode)->root;
4636 u64 csum_size;
4637 int num_csums_per_leaf;
4638 int num_csums;
4639 int old_csums;
4640
4641 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
4642 BTRFS_I(inode)->csum_bytes == 0)
4643 return 0;
4644
4645 old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4646 if (reserve)
4647 BTRFS_I(inode)->csum_bytes += num_bytes;
4648 else
4649 BTRFS_I(inode)->csum_bytes -= num_bytes;
4650 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
4651 num_csums_per_leaf = (int)div64_u64(csum_size,
4652 sizeof(struct btrfs_csum_item) +
4653 sizeof(struct btrfs_disk_key));
4654 num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4655 num_csums = num_csums + num_csums_per_leaf - 1;
4656 num_csums = num_csums / num_csums_per_leaf;
4657
4658 old_csums = old_csums + num_csums_per_leaf - 1;
4659 old_csums = old_csums / num_csums_per_leaf;
4660
4661 /* No change, no need to reserve more */
4662 if (old_csums == num_csums)
4663 return 0;
4664
4665 if (reserve)
4666 return btrfs_calc_trans_metadata_size(root,
4667 num_csums - old_csums);
4668
4669 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
0ca1f7ce 4670}
c146afad 4671
0ca1f7ce
YZ
4672int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
4673{
4674 struct btrfs_root *root = BTRFS_I(inode)->root;
4675 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
9e0baf60 4676 u64 to_reserve = 0;
660d3f6c 4677 u64 csum_bytes;
9e0baf60 4678 unsigned nr_extents = 0;
660d3f6c 4679 int extra_reserve = 0;
08e007d2 4680 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
eb6b88d9 4681 int ret = 0;
c64c2bd8 4682 bool delalloc_lock = true;
6324fbf3 4683
c64c2bd8
JB
4684 /* If we are a free space inode we need to not flush since we will be in
4685 * the middle of a transaction commit. We also don't need the delalloc
4686 * mutex since we won't race with anybody. We need this mostly to make
4687 * lockdep shut its filthy mouth.
4688 */
4689 if (btrfs_is_free_space_inode(inode)) {
08e007d2 4690 flush = BTRFS_RESERVE_NO_FLUSH;
c64c2bd8
JB
4691 delalloc_lock = false;
4692 }
c09544e0 4693
08e007d2
MX
4694 if (flush != BTRFS_RESERVE_NO_FLUSH &&
4695 btrfs_transaction_in_commit(root->fs_info))
0ca1f7ce 4696 schedule_timeout(1);
ec44a35c 4697
c64c2bd8
JB
4698 if (delalloc_lock)
4699 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
4700
0ca1f7ce 4701 num_bytes = ALIGN(num_bytes, root->sectorsize);
8bb8ab2e 4702
9e0baf60
JB
4703 spin_lock(&BTRFS_I(inode)->lock);
4704 BTRFS_I(inode)->outstanding_extents++;
4705
4706 if (BTRFS_I(inode)->outstanding_extents >
660d3f6c 4707 BTRFS_I(inode)->reserved_extents)
9e0baf60
JB
4708 nr_extents = BTRFS_I(inode)->outstanding_extents -
4709 BTRFS_I(inode)->reserved_extents;
57a45ced 4710
7fd2ae21
JB
4711 /*
4712 * Add an item to reserve for updating the inode when we complete the
4713 * delalloc io.
4714 */
72ac3c0d
JB
4715 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4716 &BTRFS_I(inode)->runtime_flags)) {
7fd2ae21 4717 nr_extents++;
660d3f6c 4718 extra_reserve = 1;
593060d7 4719 }
7fd2ae21
JB
4720
4721 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
7709cde3 4722 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
660d3f6c 4723 csum_bytes = BTRFS_I(inode)->csum_bytes;
9e0baf60 4724 spin_unlock(&BTRFS_I(inode)->lock);
57a45ced 4725
eb6b88d9 4726 if (root->fs_info->quota_enabled)
c5567237
AJ
4727 ret = btrfs_qgroup_reserve(root, num_bytes +
4728 nr_extents * root->leafsize);
c5567237 4729
eb6b88d9
JS
4730 /*
4731 * ret != 0 here means the qgroup reservation failed, we go straight to
4732 * the shared error handling then.
4733 */
4734 if (ret == 0)
4735 ret = reserve_metadata_bytes(root, block_rsv,
4736 to_reserve, flush);
4737
9e0baf60 4738 if (ret) {
7ed49f18 4739 u64 to_free = 0;
9e0baf60 4740 unsigned dropped;
7ed49f18 4741
7709cde3 4742 spin_lock(&BTRFS_I(inode)->lock);
9e0baf60 4743 dropped = drop_outstanding_extent(inode);
9e0baf60 4744 /*
660d3f6c
JB
4745 * If the inodes csum_bytes is the same as the original
4746 * csum_bytes then we know we haven't raced with any free()ers
4747 * so we can just reduce our inodes csum bytes and carry on.
4748 * Otherwise we have to do the normal free thing to account for
4749 * the case that the free side didn't free up its reserve
4750 * because of this outstanding reservation.
9e0baf60 4751 */
660d3f6c
JB
4752 if (BTRFS_I(inode)->csum_bytes == csum_bytes)
4753 calc_csum_metadata_size(inode, num_bytes, 0);
4754 else
4755 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
4756 spin_unlock(&BTRFS_I(inode)->lock);
4757 if (dropped)
4758 to_free += btrfs_calc_trans_metadata_size(root, dropped);
4759
8c2a3ca2 4760 if (to_free) {
7ed49f18 4761 btrfs_block_rsv_release(root, block_rsv, to_free);
8c2a3ca2
JB
4762 trace_btrfs_space_reservation(root->fs_info,
4763 "delalloc",
4764 btrfs_ino(inode),
4765 to_free, 0);
4766 }
4b5829a8
MX
4767 if (root->fs_info->quota_enabled) {
4768 btrfs_qgroup_free(root, num_bytes +
4769 nr_extents * root->leafsize);
4770 }
c64c2bd8
JB
4771 if (delalloc_lock)
4772 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
0ca1f7ce 4773 return ret;
9e0baf60 4774 }
25179201 4775
660d3f6c
JB
4776 spin_lock(&BTRFS_I(inode)->lock);
4777 if (extra_reserve) {
72ac3c0d
JB
4778 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4779 &BTRFS_I(inode)->runtime_flags);
660d3f6c
JB
4780 nr_extents--;
4781 }
4782 BTRFS_I(inode)->reserved_extents += nr_extents;
4783 spin_unlock(&BTRFS_I(inode)->lock);
c64c2bd8
JB
4784
4785 if (delalloc_lock)
4786 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
660d3f6c 4787
8c2a3ca2
JB
4788 if (to_reserve)
4789 trace_btrfs_space_reservation(root->fs_info,"delalloc",
4790 btrfs_ino(inode), to_reserve, 1);
0ca1f7ce
YZ
4791 block_rsv_add_bytes(block_rsv, to_reserve, 1);
4792
0ca1f7ce
YZ
4793 return 0;
4794}
4795
7709cde3
JB
4796/**
4797 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
4798 * @inode: the inode to release the reservation for
4799 * @num_bytes: the number of bytes we're releasing
4800 *
4801 * This will release the metadata reservation for an inode. This can be called
4802 * once we complete IO for a given set of bytes to release their metadata
4803 * reservations.
4804 */
0ca1f7ce
YZ
4805void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
4806{
4807 struct btrfs_root *root = BTRFS_I(inode)->root;
9e0baf60
JB
4808 u64 to_free = 0;
4809 unsigned dropped;
0ca1f7ce
YZ
4810
4811 num_bytes = ALIGN(num_bytes, root->sectorsize);
7709cde3 4812 spin_lock(&BTRFS_I(inode)->lock);
9e0baf60 4813 dropped = drop_outstanding_extent(inode);
97e728d4 4814
0934856d
MX
4815 if (num_bytes)
4816 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
7709cde3 4817 spin_unlock(&BTRFS_I(inode)->lock);
9e0baf60
JB
4818 if (dropped > 0)
4819 to_free += btrfs_calc_trans_metadata_size(root, dropped);
0ca1f7ce 4820
8c2a3ca2
JB
4821 trace_btrfs_space_reservation(root->fs_info, "delalloc",
4822 btrfs_ino(inode), to_free, 0);
c5567237
AJ
4823 if (root->fs_info->quota_enabled) {
4824 btrfs_qgroup_free(root, num_bytes +
4825 dropped * root->leafsize);
4826 }
4827
0ca1f7ce
YZ
4828 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
4829 to_free);
4830}
4831
7709cde3
JB
4832/**
4833 * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
4834 * @inode: inode we're writing to
4835 * @num_bytes: the number of bytes we want to allocate
4836 *
4837 * This will do the following things
4838 *
4839 * o reserve space in the data space info for num_bytes
4840 * o reserve space in the metadata space info based on number of outstanding
4841 * extents and how much csums will be needed
4842 * o add to the inodes ->delalloc_bytes
4843 * o add it to the fs_info's delalloc inodes list.
4844 *
4845 * This will return 0 for success and -ENOSPC if there is no space left.
4846 */
0ca1f7ce
YZ
4847int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
4848{
4849 int ret;
4850
4851 ret = btrfs_check_data_free_space(inode, num_bytes);
d397712b 4852 if (ret)
0ca1f7ce
YZ
4853 return ret;
4854
4855 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4856 if (ret) {
4857 btrfs_free_reserved_data_space(inode, num_bytes);
4858 return ret;
4859 }
4860
4861 return 0;
4862}
4863
7709cde3
JB
4864/**
4865 * btrfs_delalloc_release_space - release data and metadata space for delalloc
4866 * @inode: inode we're releasing space for
4867 * @num_bytes: the number of bytes we want to free up
4868 *
4869 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
4870 * called in the case that we don't need the metadata AND data reservations
4871 * anymore. So if there is an error or we insert an inline extent.
4872 *
4873 * This function will release the metadata space that was not used and will
4874 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
4875 * list if there are no delalloc bytes left.
4876 */
0ca1f7ce
YZ
4877void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4878{
4879 btrfs_delalloc_release_metadata(inode, num_bytes);
4880 btrfs_free_reserved_data_space(inode, num_bytes);
6324fbf3
CM
4881}
4882
c53d613e 4883static int update_block_group(struct btrfs_root *root,
f0486c68 4884 u64 bytenr, u64 num_bytes, int alloc)
9078a3e1 4885{
0af3d00b 4886 struct btrfs_block_group_cache *cache = NULL;
9078a3e1 4887 struct btrfs_fs_info *info = root->fs_info;
db94535d 4888 u64 total = num_bytes;
9078a3e1 4889 u64 old_val;
db94535d 4890 u64 byte_in_group;
0af3d00b 4891 int factor;
3e1ad54f 4892
5d4f98a2
YZ
4893 /* block accounting for super block */
4894 spin_lock(&info->delalloc_lock);
6c41761f 4895 old_val = btrfs_super_bytes_used(info->super_copy);
5d4f98a2
YZ
4896 if (alloc)
4897 old_val += num_bytes;
4898 else
4899 old_val -= num_bytes;
6c41761f 4900 btrfs_set_super_bytes_used(info->super_copy, old_val);
5d4f98a2
YZ
4901 spin_unlock(&info->delalloc_lock);
4902
d397712b 4903 while (total) {
db94535d 4904 cache = btrfs_lookup_block_group(info, bytenr);
f3465ca4 4905 if (!cache)
79787eaa 4906 return -ENOENT;
b742bb82
YZ
4907 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4908 BTRFS_BLOCK_GROUP_RAID1 |
4909 BTRFS_BLOCK_GROUP_RAID10))
4910 factor = 2;
4911 else
4912 factor = 1;
9d66e233
JB
4913 /*
4914 * If this block group has free space cache written out, we
4915 * need to make sure to load it if we are removing space. This
4916 * is because we need the unpinning stage to actually add the
4917 * space back to the block group, otherwise we will leak space.
4918 */
4919 if (!alloc && cache->cached == BTRFS_CACHE_NO)
f6373bf3 4920 cache_block_group(cache, 1);
0af3d00b 4921
db94535d
CM
4922 byte_in_group = bytenr - cache->key.objectid;
4923 WARN_ON(byte_in_group > cache->key.offset);
9078a3e1 4924
25179201 4925 spin_lock(&cache->space_info->lock);
c286ac48 4926 spin_lock(&cache->lock);
0af3d00b 4927
73bc1876 4928 if (btrfs_test_opt(root, SPACE_CACHE) &&
0af3d00b
JB
4929 cache->disk_cache_state < BTRFS_DC_CLEAR)
4930 cache->disk_cache_state = BTRFS_DC_CLEAR;
4931
0f9dd46c 4932 cache->dirty = 1;
9078a3e1 4933 old_val = btrfs_block_group_used(&cache->item);
db94535d 4934 num_bytes = min(total, cache->key.offset - byte_in_group);
cd1bc465 4935 if (alloc) {
db94535d 4936 old_val += num_bytes;
11833d66
YZ
4937 btrfs_set_block_group_used(&cache->item, old_val);
4938 cache->reserved -= num_bytes;
11833d66 4939 cache->space_info->bytes_reserved -= num_bytes;
b742bb82
YZ
4940 cache->space_info->bytes_used += num_bytes;
4941 cache->space_info->disk_used += num_bytes * factor;
c286ac48 4942 spin_unlock(&cache->lock);
25179201 4943 spin_unlock(&cache->space_info->lock);
cd1bc465 4944 } else {
db94535d 4945 old_val -= num_bytes;
c286ac48 4946 btrfs_set_block_group_used(&cache->item, old_val);
f0486c68
YZ
4947 cache->pinned += num_bytes;
4948 cache->space_info->bytes_pinned += num_bytes;
6324fbf3 4949 cache->space_info->bytes_used -= num_bytes;
b742bb82 4950 cache->space_info->disk_used -= num_bytes * factor;
c286ac48 4951 spin_unlock(&cache->lock);
25179201 4952 spin_unlock(&cache->space_info->lock);
1f3c79a2 4953
f0486c68
YZ
4954 set_extent_dirty(info->pinned_extents,
4955 bytenr, bytenr + num_bytes - 1,
4956 GFP_NOFS | __GFP_NOFAIL);
cd1bc465 4957 }
fa9c0d79 4958 btrfs_put_block_group(cache);
db94535d
CM
4959 total -= num_bytes;
4960 bytenr += num_bytes;
9078a3e1
CM
4961 }
4962 return 0;
4963}
6324fbf3 4964
a061fc8d
CM
4965static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
4966{
0f9dd46c 4967 struct btrfs_block_group_cache *cache;
d2fb3437 4968 u64 bytenr;
0f9dd46c 4969
a1897fdd
LB
4970 spin_lock(&root->fs_info->block_group_cache_lock);
4971 bytenr = root->fs_info->first_logical_byte;
4972 spin_unlock(&root->fs_info->block_group_cache_lock);
4973
4974 if (bytenr < (u64)-1)
4975 return bytenr;
4976
0f9dd46c
JB
4977 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
4978 if (!cache)
a061fc8d 4979 return 0;
0f9dd46c 4980
d2fb3437 4981 bytenr = cache->key.objectid;
fa9c0d79 4982 btrfs_put_block_group(cache);
d2fb3437
YZ
4983
4984 return bytenr;
a061fc8d
CM
4985}
4986
f0486c68
YZ
4987static int pin_down_extent(struct btrfs_root *root,
4988 struct btrfs_block_group_cache *cache,
4989 u64 bytenr, u64 num_bytes, int reserved)
324ae4df 4990{
11833d66
YZ
4991 spin_lock(&cache->space_info->lock);
4992 spin_lock(&cache->lock);
4993 cache->pinned += num_bytes;
4994 cache->space_info->bytes_pinned += num_bytes;
4995 if (reserved) {
4996 cache->reserved -= num_bytes;
4997 cache->space_info->bytes_reserved -= num_bytes;
4998 }
4999 spin_unlock(&cache->lock);
5000 spin_unlock(&cache->space_info->lock);
68b38550 5001
f0486c68
YZ
5002 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5003 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5004 return 0;
5005}
68b38550 5006
f0486c68
YZ
5007/*
5008 * this function must be called within transaction
5009 */
5010int btrfs_pin_extent(struct btrfs_root *root,
5011 u64 bytenr, u64 num_bytes, int reserved)
5012{
5013 struct btrfs_block_group_cache *cache;
68b38550 5014
f0486c68 5015 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
79787eaa 5016 BUG_ON(!cache); /* Logic error */
f0486c68
YZ
5017
5018 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
5019
5020 btrfs_put_block_group(cache);
11833d66
YZ
5021 return 0;
5022}
5023
f0486c68 5024/*
e688b725
CM
5025 * this function must be called within transaction
5026 */
dcfac415 5027int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
e688b725
CM
5028 u64 bytenr, u64 num_bytes)
5029{
5030 struct btrfs_block_group_cache *cache;
5031
5032 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
79787eaa 5033 BUG_ON(!cache); /* Logic error */
e688b725
CM
5034
5035 /*
5036 * pull in the free space cache (if any) so that our pin
5037 * removes the free space from the cache. We have load_only set
5038 * to one because the slow code to read in the free extents does check
5039 * the pinned extents.
5040 */
f6373bf3 5041 cache_block_group(cache, 1);
e688b725
CM
5042
5043 pin_down_extent(root, cache, bytenr, num_bytes, 0);
5044
5045 /* remove us from the free space cache (if we're there at all) */
5046 btrfs_remove_free_space(cache, bytenr, num_bytes);
5047 btrfs_put_block_group(cache);
5048 return 0;
5049}
5050
fb25e914
JB
5051/**
5052 * btrfs_update_reserved_bytes - update the block_group and space info counters
5053 * @cache: The cache we are manipulating
5054 * @num_bytes: The number of bytes in question
5055 * @reserve: One of the reservation enums
5056 *
5057 * This is called by the allocator when it reserves space, or by somebody who is
5058 * freeing space that was never actually used on disk. For example if you
5059 * reserve some space for a new leaf in transaction A and before transaction A
5060 * commits you free that leaf, you call this with reserve set to 0 in order to
5061 * clear the reservation.
5062 *
5063 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
5064 * ENOSPC accounting. For data we handle the reservation through clearing the
5065 * delalloc bits in the io_tree. We have to do this since we could end up
5066 * allocating less disk space for the amount of data we have reserved in the
5067 * case of compression.
5068 *
5069 * If this is a reservation and the block group has become read only we cannot
5070 * make the reservation and return -EAGAIN, otherwise this function always
5071 * succeeds.
f0486c68 5072 */
fb25e914
JB
5073static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
5074 u64 num_bytes, int reserve)
11833d66 5075{
fb25e914 5076 struct btrfs_space_info *space_info = cache->space_info;
f0486c68 5077 int ret = 0;
79787eaa 5078
fb25e914
JB
5079 spin_lock(&space_info->lock);
5080 spin_lock(&cache->lock);
5081 if (reserve != RESERVE_FREE) {
f0486c68
YZ
5082 if (cache->ro) {
5083 ret = -EAGAIN;
5084 } else {
fb25e914
JB
5085 cache->reserved += num_bytes;
5086 space_info->bytes_reserved += num_bytes;
5087 if (reserve == RESERVE_ALLOC) {
8c2a3ca2 5088 trace_btrfs_space_reservation(cache->fs_info,
2bcc0328
LB
5089 "space_info", space_info->flags,
5090 num_bytes, 0);
fb25e914
JB
5091 space_info->bytes_may_use -= num_bytes;
5092 }
f0486c68 5093 }
fb25e914
JB
5094 } else {
5095 if (cache->ro)
5096 space_info->bytes_readonly += num_bytes;
5097 cache->reserved -= num_bytes;
5098 space_info->bytes_reserved -= num_bytes;
5099 space_info->reservation_progress++;
324ae4df 5100 }
fb25e914
JB
5101 spin_unlock(&cache->lock);
5102 spin_unlock(&space_info->lock);
f0486c68 5103 return ret;
324ae4df 5104}
9078a3e1 5105
143bede5 5106void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
11833d66 5107 struct btrfs_root *root)
e8569813 5108{
e8569813 5109 struct btrfs_fs_info *fs_info = root->fs_info;
11833d66
YZ
5110 struct btrfs_caching_control *next;
5111 struct btrfs_caching_control *caching_ctl;
5112 struct btrfs_block_group_cache *cache;
e8569813 5113
11833d66 5114 down_write(&fs_info->extent_commit_sem);
25179201 5115
11833d66
YZ
5116 list_for_each_entry_safe(caching_ctl, next,
5117 &fs_info->caching_block_groups, list) {
5118 cache = caching_ctl->block_group;
5119 if (block_group_cache_done(cache)) {
5120 cache->last_byte_to_unpin = (u64)-1;
5121 list_del_init(&caching_ctl->list);
5122 put_caching_control(caching_ctl);
e8569813 5123 } else {
11833d66 5124 cache->last_byte_to_unpin = caching_ctl->progress;
e8569813 5125 }
e8569813 5126 }
11833d66
YZ
5127
5128 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5129 fs_info->pinned_extents = &fs_info->freed_extents[1];
5130 else
5131 fs_info->pinned_extents = &fs_info->freed_extents[0];
5132
5133 up_write(&fs_info->extent_commit_sem);
8929ecfa
YZ
5134
5135 update_global_block_rsv(fs_info);
e8569813
ZY
5136}
5137
11833d66 5138static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
ccd467d6 5139{
11833d66
YZ
5140 struct btrfs_fs_info *fs_info = root->fs_info;
5141 struct btrfs_block_group_cache *cache = NULL;
7b398f8e
JB
5142 struct btrfs_space_info *space_info;
5143 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
11833d66 5144 u64 len;
7b398f8e 5145 bool readonly;
ccd467d6 5146
11833d66 5147 while (start <= end) {
7b398f8e 5148 readonly = false;
11833d66
YZ
5149 if (!cache ||
5150 start >= cache->key.objectid + cache->key.offset) {
5151 if (cache)
5152 btrfs_put_block_group(cache);
5153 cache = btrfs_lookup_block_group(fs_info, start);
79787eaa 5154 BUG_ON(!cache); /* Logic error */
11833d66
YZ
5155 }
5156
5157 len = cache->key.objectid + cache->key.offset - start;
5158 len = min(len, end + 1 - start);
5159
5160 if (start < cache->last_byte_to_unpin) {
5161 len = min(len, cache->last_byte_to_unpin - start);
5162 btrfs_add_free_space(cache, start, len);
5163 }
5164
f0486c68 5165 start += len;
7b398f8e 5166 space_info = cache->space_info;
f0486c68 5167
7b398f8e 5168 spin_lock(&space_info->lock);
11833d66
YZ
5169 spin_lock(&cache->lock);
5170 cache->pinned -= len;
7b398f8e
JB
5171 space_info->bytes_pinned -= len;
5172 if (cache->ro) {
5173 space_info->bytes_readonly += len;
5174 readonly = true;
5175 }
11833d66 5176 spin_unlock(&cache->lock);
7b398f8e
JB
5177 if (!readonly && global_rsv->space_info == space_info) {
5178 spin_lock(&global_rsv->lock);
5179 if (!global_rsv->full) {
5180 len = min(len, global_rsv->size -
5181 global_rsv->reserved);
5182 global_rsv->reserved += len;
5183 space_info->bytes_may_use += len;
5184 if (global_rsv->reserved >= global_rsv->size)
5185 global_rsv->full = 1;
5186 }
5187 spin_unlock(&global_rsv->lock);
5188 }
5189 spin_unlock(&space_info->lock);
ccd467d6 5190 }
11833d66
YZ
5191
5192 if (cache)
5193 btrfs_put_block_group(cache);
ccd467d6
CM
5194 return 0;
5195}
5196
5197int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
11833d66 5198 struct btrfs_root *root)
a28ec197 5199{
11833d66
YZ
5200 struct btrfs_fs_info *fs_info = root->fs_info;
5201 struct extent_io_tree *unpin;
1a5bc167
CM
5202 u64 start;
5203 u64 end;
a28ec197 5204 int ret;
a28ec197 5205
79787eaa
JM
5206 if (trans->aborted)
5207 return 0;
5208
11833d66
YZ
5209 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5210 unpin = &fs_info->freed_extents[1];
5211 else
5212 unpin = &fs_info->freed_extents[0];
5213
d397712b 5214 while (1) {
1a5bc167 5215 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 5216 EXTENT_DIRTY, NULL);
1a5bc167 5217 if (ret)
a28ec197 5218 break;
1f3c79a2 5219
5378e607
LD
5220 if (btrfs_test_opt(root, DISCARD))
5221 ret = btrfs_discard_extent(root, start,
5222 end + 1 - start, NULL);
1f3c79a2 5223
1a5bc167 5224 clear_extent_dirty(unpin, start, end, GFP_NOFS);
11833d66 5225 unpin_extent_range(root, start, end);
b9473439 5226 cond_resched();
a28ec197 5227 }
817d52f8 5228
e20d96d6
CM
5229 return 0;
5230}
5231
5d4f98a2
YZ
5232static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5233 struct btrfs_root *root,
5234 u64 bytenr, u64 num_bytes, u64 parent,
5235 u64 root_objectid, u64 owner_objectid,
5236 u64 owner_offset, int refs_to_drop,
5237 struct btrfs_delayed_extent_op *extent_op)
a28ec197 5238{
e2fa7227 5239 struct btrfs_key key;
5d4f98a2 5240 struct btrfs_path *path;
1261ec42
CM
5241 struct btrfs_fs_info *info = root->fs_info;
5242 struct btrfs_root *extent_root = info->extent_root;
5f39d397 5243 struct extent_buffer *leaf;
5d4f98a2
YZ
5244 struct btrfs_extent_item *ei;
5245 struct btrfs_extent_inline_ref *iref;
a28ec197 5246 int ret;
5d4f98a2 5247 int is_data;
952fccac
CM
5248 int extent_slot = 0;
5249 int found_extent = 0;
5250 int num_to_del = 1;
5d4f98a2
YZ
5251 u32 item_size;
5252 u64 refs;
037e6390 5253
5caf2a00 5254 path = btrfs_alloc_path();
54aa1f4d
CM
5255 if (!path)
5256 return -ENOMEM;
5f26f772 5257
3c12ac72 5258 path->reada = 1;
b9473439 5259 path->leave_spinning = 1;
5d4f98a2
YZ
5260
5261 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5262 BUG_ON(!is_data && refs_to_drop != 1);
5263
5264 ret = lookup_extent_backref(trans, extent_root, path, &iref,
5265 bytenr, num_bytes, parent,
5266 root_objectid, owner_objectid,
5267 owner_offset);
7bb86316 5268 if (ret == 0) {
952fccac 5269 extent_slot = path->slots[0];
5d4f98a2
YZ
5270 while (extent_slot >= 0) {
5271 btrfs_item_key_to_cpu(path->nodes[0], &key,
952fccac 5272 extent_slot);
5d4f98a2 5273 if (key.objectid != bytenr)
952fccac 5274 break;
5d4f98a2
YZ
5275 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5276 key.offset == num_bytes) {
952fccac
CM
5277 found_extent = 1;
5278 break;
5279 }
5280 if (path->slots[0] - extent_slot > 5)
5281 break;
5d4f98a2 5282 extent_slot--;
952fccac 5283 }
5d4f98a2
YZ
5284#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5285 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5286 if (found_extent && item_size < sizeof(*ei))
5287 found_extent = 0;
5288#endif
31840ae1 5289 if (!found_extent) {
5d4f98a2 5290 BUG_ON(iref);
56bec294 5291 ret = remove_extent_backref(trans, extent_root, path,
5d4f98a2
YZ
5292 NULL, refs_to_drop,
5293 is_data);
005d6427
DS
5294 if (ret) {
5295 btrfs_abort_transaction(trans, extent_root, ret);
5296 goto out;
5297 }
b3b4aa74 5298 btrfs_release_path(path);
b9473439 5299 path->leave_spinning = 1;
5d4f98a2
YZ
5300
5301 key.objectid = bytenr;
5302 key.type = BTRFS_EXTENT_ITEM_KEY;
5303 key.offset = num_bytes;
5304
31840ae1
ZY
5305 ret = btrfs_search_slot(trans, extent_root,
5306 &key, path, -1, 1);
f3465ca4
JB
5307 if (ret) {
5308 printk(KERN_ERR "umm, got %d back from search"
d397712b
CM
5309 ", was looking for %llu\n", ret,
5310 (unsigned long long)bytenr);
b783e62d
JB
5311 if (ret > 0)
5312 btrfs_print_leaf(extent_root,
5313 path->nodes[0]);
f3465ca4 5314 }
005d6427
DS
5315 if (ret < 0) {
5316 btrfs_abort_transaction(trans, extent_root, ret);
5317 goto out;
5318 }
31840ae1
ZY
5319 extent_slot = path->slots[0];
5320 }
79787eaa 5321 } else if (ret == -ENOENT) {
7bb86316
CM
5322 btrfs_print_leaf(extent_root, path->nodes[0]);
5323 WARN_ON(1);
d397712b 5324 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
5d4f98a2 5325 "parent %llu root %llu owner %llu offset %llu\n",
d397712b 5326 (unsigned long long)bytenr,
56bec294 5327 (unsigned long long)parent,
d397712b 5328 (unsigned long long)root_objectid,
5d4f98a2
YZ
5329 (unsigned long long)owner_objectid,
5330 (unsigned long long)owner_offset);
79787eaa 5331 } else {
005d6427
DS
5332 btrfs_abort_transaction(trans, extent_root, ret);
5333 goto out;
7bb86316 5334 }
5f39d397
CM
5335
5336 leaf = path->nodes[0];
5d4f98a2
YZ
5337 item_size = btrfs_item_size_nr(leaf, extent_slot);
5338#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5339 if (item_size < sizeof(*ei)) {
5340 BUG_ON(found_extent || extent_slot != path->slots[0]);
5341 ret = convert_extent_item_v0(trans, extent_root, path,
5342 owner_objectid, 0);
005d6427
DS
5343 if (ret < 0) {
5344 btrfs_abort_transaction(trans, extent_root, ret);
5345 goto out;
5346 }
5d4f98a2 5347
b3b4aa74 5348 btrfs_release_path(path);
5d4f98a2
YZ
5349 path->leave_spinning = 1;
5350
5351 key.objectid = bytenr;
5352 key.type = BTRFS_EXTENT_ITEM_KEY;
5353 key.offset = num_bytes;
5354
5355 ret = btrfs_search_slot(trans, extent_root, &key, path,
5356 -1, 1);
5357 if (ret) {
5358 printk(KERN_ERR "umm, got %d back from search"
5359 ", was looking for %llu\n", ret,
5360 (unsigned long long)bytenr);
5361 btrfs_print_leaf(extent_root, path->nodes[0]);
5362 }
005d6427
DS
5363 if (ret < 0) {
5364 btrfs_abort_transaction(trans, extent_root, ret);
5365 goto out;
5366 }
5367
5d4f98a2
YZ
5368 extent_slot = path->slots[0];
5369 leaf = path->nodes[0];
5370 item_size = btrfs_item_size_nr(leaf, extent_slot);
5371 }
5372#endif
5373 BUG_ON(item_size < sizeof(*ei));
952fccac 5374 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 5375 struct btrfs_extent_item);
5d4f98a2
YZ
5376 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
5377 struct btrfs_tree_block_info *bi;
5378 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5379 bi = (struct btrfs_tree_block_info *)(ei + 1);
5380 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5381 }
56bec294 5382
5d4f98a2 5383 refs = btrfs_extent_refs(leaf, ei);
56bec294
CM
5384 BUG_ON(refs < refs_to_drop);
5385 refs -= refs_to_drop;
5f39d397 5386
5d4f98a2
YZ
5387 if (refs > 0) {
5388 if (extent_op)
5389 __run_delayed_extent_op(extent_op, leaf, ei);
5390 /*
5391 * In the case of inline back ref, reference count will
5392 * be updated by remove_extent_backref
952fccac 5393 */
5d4f98a2
YZ
5394 if (iref) {
5395 BUG_ON(!found_extent);
5396 } else {
5397 btrfs_set_extent_refs(leaf, ei, refs);
5398 btrfs_mark_buffer_dirty(leaf);
5399 }
5400 if (found_extent) {
5401 ret = remove_extent_backref(trans, extent_root, path,
5402 iref, refs_to_drop,
5403 is_data);
005d6427
DS
5404 if (ret) {
5405 btrfs_abort_transaction(trans, extent_root, ret);
5406 goto out;
5407 }
952fccac 5408 }
5d4f98a2 5409 } else {
5d4f98a2
YZ
5410 if (found_extent) {
5411 BUG_ON(is_data && refs_to_drop !=
5412 extent_data_ref_count(root, path, iref));
5413 if (iref) {
5414 BUG_ON(path->slots[0] != extent_slot);
5415 } else {
5416 BUG_ON(path->slots[0] != extent_slot + 1);
5417 path->slots[0] = extent_slot;
5418 num_to_del = 2;
5419 }
78fae27e 5420 }
b9473439 5421
952fccac
CM
5422 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5423 num_to_del);
005d6427
DS
5424 if (ret) {
5425 btrfs_abort_transaction(trans, extent_root, ret);
5426 goto out;
5427 }
b3b4aa74 5428 btrfs_release_path(path);
21af804c 5429
5d4f98a2 5430 if (is_data) {
459931ec 5431 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
005d6427
DS
5432 if (ret) {
5433 btrfs_abort_transaction(trans, extent_root, ret);
5434 goto out;
5435 }
459931ec
CM
5436 }
5437
c53d613e 5438 ret = update_block_group(root, bytenr, num_bytes, 0);
005d6427
DS
5439 if (ret) {
5440 btrfs_abort_transaction(trans, extent_root, ret);
5441 goto out;
5442 }
a28ec197 5443 }
79787eaa 5444out:
5caf2a00 5445 btrfs_free_path(path);
a28ec197
CM
5446 return ret;
5447}
5448
1887be66 5449/*
f0486c68 5450 * when we free an block, it is possible (and likely) that we free the last
1887be66
CM
5451 * delayed ref for that extent as well. This searches the delayed ref tree for
5452 * a given extent, and if there are no other delayed refs to be processed, it
5453 * removes it from the tree.
5454 */
5455static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
5456 struct btrfs_root *root, u64 bytenr)
5457{
5458 struct btrfs_delayed_ref_head *head;
5459 struct btrfs_delayed_ref_root *delayed_refs;
5460 struct btrfs_delayed_ref_node *ref;
5461 struct rb_node *node;
f0486c68 5462 int ret = 0;
1887be66
CM
5463
5464 delayed_refs = &trans->transaction->delayed_refs;
5465 spin_lock(&delayed_refs->lock);
5466 head = btrfs_find_delayed_ref_head(trans, bytenr);
5467 if (!head)
5468 goto out;
5469
5470 node = rb_prev(&head->node.rb_node);
5471 if (!node)
5472 goto out;
5473
5474 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
5475
5476 /* there are still entries for this ref, we can't drop it */
5477 if (ref->bytenr == bytenr)
5478 goto out;
5479
5d4f98a2
YZ
5480 if (head->extent_op) {
5481 if (!head->must_insert_reserved)
5482 goto out;
78a6184a 5483 btrfs_free_delayed_extent_op(head->extent_op);
5d4f98a2
YZ
5484 head->extent_op = NULL;
5485 }
5486
1887be66
CM
5487 /*
5488 * waiting for the lock here would deadlock. If someone else has it
5489 * locked they are already in the process of dropping it anyway
5490 */
5491 if (!mutex_trylock(&head->mutex))
5492 goto out;
5493
5494 /*
5495 * at this point we have a head with no other entries. Go
5496 * ahead and process it.
5497 */
5498 head->node.in_tree = 0;
5499 rb_erase(&head->node.rb_node, &delayed_refs->root);
c3e69d58 5500
1887be66
CM
5501 delayed_refs->num_entries--;
5502
5503 /*
5504 * we don't take a ref on the node because we're removing it from the
5505 * tree, so we just steal the ref the tree was holding.
5506 */
c3e69d58
CM
5507 delayed_refs->num_heads--;
5508 if (list_empty(&head->cluster))
5509 delayed_refs->num_heads_ready--;
5510
5511 list_del_init(&head->cluster);
1887be66
CM
5512 spin_unlock(&delayed_refs->lock);
5513
f0486c68
YZ
5514 BUG_ON(head->extent_op);
5515 if (head->must_insert_reserved)
5516 ret = 1;
5517
5518 mutex_unlock(&head->mutex);
1887be66 5519 btrfs_put_delayed_ref(&head->node);
f0486c68 5520 return ret;
1887be66
CM
5521out:
5522 spin_unlock(&delayed_refs->lock);
5523 return 0;
5524}
5525
f0486c68
YZ
5526void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
5527 struct btrfs_root *root,
5528 struct extent_buffer *buf,
5581a51a 5529 u64 parent, int last_ref)
f0486c68 5530{
f0486c68
YZ
5531 struct btrfs_block_group_cache *cache = NULL;
5532 int ret;
5533
5534 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
66d7e7f0
AJ
5535 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
5536 buf->start, buf->len,
5537 parent, root->root_key.objectid,
5538 btrfs_header_level(buf),
5581a51a 5539 BTRFS_DROP_DELAYED_REF, NULL, 0);
79787eaa 5540 BUG_ON(ret); /* -ENOMEM */
f0486c68
YZ
5541 }
5542
5543 if (!last_ref)
5544 return;
5545
f0486c68 5546 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
f0486c68
YZ
5547
5548 if (btrfs_header_generation(buf) == trans->transid) {
5549 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5550 ret = check_ref_cleanup(trans, root, buf->start);
5551 if (!ret)
37be25bc 5552 goto out;
f0486c68
YZ
5553 }
5554
5555 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
5556 pin_down_extent(root, cache, buf->start, buf->len, 1);
37be25bc 5557 goto out;
f0486c68
YZ
5558 }
5559
5560 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
5561
5562 btrfs_add_free_space(cache, buf->start, buf->len);
fb25e914 5563 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
f0486c68
YZ
5564 }
5565out:
a826d6dc
JB
5566 /*
5567 * Deleting the buffer, clear the corrupt flag since it doesn't matter
5568 * anymore.
5569 */
5570 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
f0486c68
YZ
5571 btrfs_put_block_group(cache);
5572}
5573
79787eaa 5574/* Can return -ENOMEM */
66d7e7f0
AJ
5575int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5576 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
5577 u64 owner, u64 offset, int for_cow)
925baedd
CM
5578{
5579 int ret;
66d7e7f0 5580 struct btrfs_fs_info *fs_info = root->fs_info;
925baedd 5581
56bec294
CM
5582 /*
5583 * tree log blocks never actually go into the extent allocation
5584 * tree, just update pinning info and exit early.
56bec294 5585 */
5d4f98a2
YZ
5586 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
5587 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
b9473439 5588 /* unlocks the pinned mutex */
11833d66 5589 btrfs_pin_extent(root, bytenr, num_bytes, 1);
56bec294 5590 ret = 0;
5d4f98a2 5591 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0
AJ
5592 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
5593 num_bytes,
5d4f98a2 5594 parent, root_objectid, (int)owner,
66d7e7f0 5595 BTRFS_DROP_DELAYED_REF, NULL, for_cow);
5d4f98a2 5596 } else {
66d7e7f0
AJ
5597 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
5598 num_bytes,
5599 parent, root_objectid, owner,
5600 offset, BTRFS_DROP_DELAYED_REF,
5601 NULL, for_cow);
56bec294 5602 }
925baedd
CM
5603 return ret;
5604}
5605
53b381b3
DW
5606static u64 stripe_align(struct btrfs_root *root,
5607 struct btrfs_block_group_cache *cache,
5608 u64 val, u64 num_bytes)
87ee04eb 5609{
fda2832f 5610 u64 ret = ALIGN(val, root->stripesize);
87ee04eb
CM
5611 return ret;
5612}
5613
817d52f8
JB
5614/*
5615 * when we wait for progress in the block group caching, its because
5616 * our allocation attempt failed at least once. So, we must sleep
5617 * and let some progress happen before we try again.
5618 *
5619 * This function will sleep at least once waiting for new free space to
5620 * show up, and then it will check the block group free space numbers
5621 * for our min num_bytes. Another option is to have it go ahead
5622 * and look in the rbtree for a free extent of a given size, but this
5623 * is a good start.
5624 */
5625static noinline int
5626wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
5627 u64 num_bytes)
5628{
11833d66 5629 struct btrfs_caching_control *caching_ctl;
817d52f8 5630
11833d66
YZ
5631 caching_ctl = get_caching_control(cache);
5632 if (!caching_ctl)
817d52f8 5633 return 0;
817d52f8 5634
11833d66 5635 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
34d52cb6 5636 (cache->free_space_ctl->free_space >= num_bytes));
11833d66
YZ
5637
5638 put_caching_control(caching_ctl);
5639 return 0;
5640}
5641
5642static noinline int
5643wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
5644{
5645 struct btrfs_caching_control *caching_ctl;
11833d66
YZ
5646
5647 caching_ctl = get_caching_control(cache);
5648 if (!caching_ctl)
5649 return 0;
5650
5651 wait_event(caching_ctl->wait, block_group_cache_done(cache));
5652
5653 put_caching_control(caching_ctl);
817d52f8
JB
5654 return 0;
5655}
5656
31e50229 5657int __get_raid_index(u64 flags)
b742bb82 5658{
7738a53a 5659 if (flags & BTRFS_BLOCK_GROUP_RAID10)
e6ec716f 5660 return BTRFS_RAID_RAID10;
7738a53a 5661 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
e6ec716f 5662 return BTRFS_RAID_RAID1;
7738a53a 5663 else if (flags & BTRFS_BLOCK_GROUP_DUP)
e6ec716f 5664 return BTRFS_RAID_DUP;
7738a53a 5665 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
e6ec716f 5666 return BTRFS_RAID_RAID0;
53b381b3 5667 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
e942f883 5668 return BTRFS_RAID_RAID5;
53b381b3 5669 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
e942f883
CM
5670 return BTRFS_RAID_RAID6;
5671
5672 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
b742bb82
YZ
5673}
5674
7738a53a
ID
5675static int get_block_group_index(struct btrfs_block_group_cache *cache)
5676{
31e50229 5677 return __get_raid_index(cache->flags);
7738a53a
ID
5678}
5679
817d52f8 5680enum btrfs_loop_type {
285ff5af
JB
5681 LOOP_CACHING_NOWAIT = 0,
5682 LOOP_CACHING_WAIT = 1,
5683 LOOP_ALLOC_CHUNK = 2,
5684 LOOP_NO_EMPTY_SIZE = 3,
817d52f8
JB
5685};
5686
fec577fb
CM
5687/*
5688 * walks the btree of allocated extents and find a hole of a given size.
5689 * The key ins is changed to record the hole:
5690 * ins->objectid == block start
62e2749e 5691 * ins->flags = BTRFS_EXTENT_ITEM_KEY
fec577fb
CM
5692 * ins->offset == number of blocks
5693 * Any available blocks before search_start are skipped.
5694 */
d397712b 5695static noinline int find_free_extent(struct btrfs_trans_handle *trans,
98ed5174
CM
5696 struct btrfs_root *orig_root,
5697 u64 num_bytes, u64 empty_size,
98ed5174 5698 u64 hint_byte, struct btrfs_key *ins,
e0f54067 5699 u64 data)
fec577fb 5700{
80eb234a 5701 int ret = 0;
d397712b 5702 struct btrfs_root *root = orig_root->fs_info->extent_root;
fa9c0d79 5703 struct btrfs_free_cluster *last_ptr = NULL;
80eb234a 5704 struct btrfs_block_group_cache *block_group = NULL;
274bd4fb 5705 struct btrfs_block_group_cache *used_block_group;
81c9ad23 5706 u64 search_start = 0;
239b14b3 5707 int empty_cluster = 2 * 1024 * 1024;
80eb234a 5708 struct btrfs_space_info *space_info;
fa9c0d79 5709 int loop = 0;
ac5c9300 5710 int index = __get_raid_index(data);
fb25e914
JB
5711 int alloc_type = (data & BTRFS_BLOCK_GROUP_DATA) ?
5712 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
817d52f8 5713 bool found_uncached_bg = false;
0a24325e 5714 bool failed_cluster_refill = false;
1cdda9b8 5715 bool failed_alloc = false;
67377734 5716 bool use_cluster = true;
60d2adbb 5717 bool have_caching_bg = false;
fec577fb 5718
db94535d 5719 WARN_ON(num_bytes < root->sectorsize);
b1a4d965 5720 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
80eb234a
JB
5721 ins->objectid = 0;
5722 ins->offset = 0;
b1a4d965 5723
3f7de037
JB
5724 trace_find_free_extent(orig_root, num_bytes, empty_size, data);
5725
2552d17e 5726 space_info = __find_space_info(root->fs_info, data);
1b1d1f66 5727 if (!space_info) {
e0f54067 5728 printk(KERN_ERR "No space info for %llu\n", data);
1b1d1f66
JB
5729 return -ENOSPC;
5730 }
2552d17e 5731
67377734
JB
5732 /*
5733 * If the space info is for both data and metadata it means we have a
5734 * small filesystem and we can't use the clustering stuff.
5735 */
5736 if (btrfs_mixed_space_info(space_info))
5737 use_cluster = false;
5738
67377734 5739 if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
fa9c0d79 5740 last_ptr = &root->fs_info->meta_alloc_cluster;
536ac8ae
CM
5741 if (!btrfs_test_opt(root, SSD))
5742 empty_cluster = 64 * 1024;
239b14b3
CM
5743 }
5744
67377734
JB
5745 if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
5746 btrfs_test_opt(root, SSD)) {
fa9c0d79
CM
5747 last_ptr = &root->fs_info->data_alloc_cluster;
5748 }
0f9dd46c 5749
239b14b3 5750 if (last_ptr) {
fa9c0d79
CM
5751 spin_lock(&last_ptr->lock);
5752 if (last_ptr->block_group)
5753 hint_byte = last_ptr->window_start;
5754 spin_unlock(&last_ptr->lock);
239b14b3 5755 }
fa9c0d79 5756
a061fc8d 5757 search_start = max(search_start, first_logical_byte(root, 0));
239b14b3 5758 search_start = max(search_start, hint_byte);
0b86a832 5759
817d52f8 5760 if (!last_ptr)
fa9c0d79 5761 empty_cluster = 0;
fa9c0d79 5762
2552d17e 5763 if (search_start == hint_byte) {
2552d17e
JB
5764 block_group = btrfs_lookup_block_group(root->fs_info,
5765 search_start);
274bd4fb 5766 used_block_group = block_group;
817d52f8
JB
5767 /*
5768 * we don't want to use the block group if it doesn't match our
5769 * allocation bits, or if its not cached.
ccf0e725
JB
5770 *
5771 * However if we are re-searching with an ideal block group
5772 * picked out then we don't care that the block group is cached.
817d52f8
JB
5773 */
5774 if (block_group && block_group_bits(block_group, data) &&
285ff5af 5775 block_group->cached != BTRFS_CACHE_NO) {
2552d17e 5776 down_read(&space_info->groups_sem);
44fb5511
CM
5777 if (list_empty(&block_group->list) ||
5778 block_group->ro) {
5779 /*
5780 * someone is removing this block group,
5781 * we can't jump into the have_block_group
5782 * target because our list pointers are not
5783 * valid
5784 */
5785 btrfs_put_block_group(block_group);
5786 up_read(&space_info->groups_sem);
ccf0e725 5787 } else {
b742bb82 5788 index = get_block_group_index(block_group);
44fb5511 5789 goto have_block_group;
ccf0e725 5790 }
2552d17e 5791 } else if (block_group) {
fa9c0d79 5792 btrfs_put_block_group(block_group);
2552d17e 5793 }
42e70e7a 5794 }
2552d17e 5795search:
60d2adbb 5796 have_caching_bg = false;
80eb234a 5797 down_read(&space_info->groups_sem);
b742bb82
YZ
5798 list_for_each_entry(block_group, &space_info->block_groups[index],
5799 list) {
6226cb0a 5800 u64 offset;
817d52f8 5801 int cached;
8a1413a2 5802
274bd4fb 5803 used_block_group = block_group;
11dfe35a 5804 btrfs_get_block_group(block_group);
2552d17e 5805 search_start = block_group->key.objectid;
42e70e7a 5806
83a50de9
CM
5807 /*
5808 * this can happen if we end up cycling through all the
5809 * raid types, but we want to make sure we only allocate
5810 * for the proper type.
5811 */
5812 if (!block_group_bits(block_group, data)) {
5813 u64 extra = BTRFS_BLOCK_GROUP_DUP |
5814 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
5815 BTRFS_BLOCK_GROUP_RAID5 |
5816 BTRFS_BLOCK_GROUP_RAID6 |
83a50de9
CM
5817 BTRFS_BLOCK_GROUP_RAID10;
5818
5819 /*
5820 * if they asked for extra copies and this block group
5821 * doesn't provide them, bail. This does allow us to
5822 * fill raid0 from raid1.
5823 */
5824 if ((data & extra) && !(block_group->flags & extra))
5825 goto loop;
5826 }
5827
2552d17e 5828have_block_group:
291c7d2f
JB
5829 cached = block_group_cache_done(block_group);
5830 if (unlikely(!cached)) {
291c7d2f 5831 found_uncached_bg = true;
f6373bf3 5832 ret = cache_block_group(block_group, 0);
1d4284bd
CM
5833 BUG_ON(ret < 0);
5834 ret = 0;
817d52f8
JB
5835 }
5836
ea6a478e 5837 if (unlikely(block_group->ro))
2552d17e 5838 goto loop;
0f9dd46c 5839
0a24325e 5840 /*
062c05c4
AO
5841 * Ok we want to try and use the cluster allocator, so
5842 * lets look there
0a24325e 5843 */
062c05c4 5844 if (last_ptr) {
8de972b4 5845 unsigned long aligned_cluster;
fa9c0d79
CM
5846 /*
5847 * the refill lock keeps out other
5848 * people trying to start a new cluster
5849 */
5850 spin_lock(&last_ptr->refill_lock);
274bd4fb
AO
5851 used_block_group = last_ptr->block_group;
5852 if (used_block_group != block_group &&
5853 (!used_block_group ||
5854 used_block_group->ro ||
5855 !block_group_bits(used_block_group, data))) {
5856 used_block_group = block_group;
44fb5511 5857 goto refill_cluster;
274bd4fb
AO
5858 }
5859
5860 if (used_block_group != block_group)
5861 btrfs_get_block_group(used_block_group);
44fb5511 5862
274bd4fb
AO
5863 offset = btrfs_alloc_from_cluster(used_block_group,
5864 last_ptr, num_bytes, used_block_group->key.objectid);
fa9c0d79
CM
5865 if (offset) {
5866 /* we have a block, we're done */
5867 spin_unlock(&last_ptr->refill_lock);
3f7de037
JB
5868 trace_btrfs_reserve_extent_cluster(root,
5869 block_group, search_start, num_bytes);
fa9c0d79
CM
5870 goto checks;
5871 }
5872
274bd4fb
AO
5873 WARN_ON(last_ptr->block_group != used_block_group);
5874 if (used_block_group != block_group) {
5875 btrfs_put_block_group(used_block_group);
5876 used_block_group = block_group;
fa9c0d79 5877 }
44fb5511 5878refill_cluster:
274bd4fb 5879 BUG_ON(used_block_group != block_group);
062c05c4
AO
5880 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
5881 * set up a new clusters, so lets just skip it
5882 * and let the allocator find whatever block
5883 * it can find. If we reach this point, we
5884 * will have tried the cluster allocator
5885 * plenty of times and not have found
5886 * anything, so we are likely way too
5887 * fragmented for the clustering stuff to find
a5f6f719
AO
5888 * anything.
5889 *
5890 * However, if the cluster is taken from the
5891 * current block group, release the cluster
5892 * first, so that we stand a better chance of
5893 * succeeding in the unclustered
5894 * allocation. */
5895 if (loop >= LOOP_NO_EMPTY_SIZE &&
5896 last_ptr->block_group != block_group) {
062c05c4
AO
5897 spin_unlock(&last_ptr->refill_lock);
5898 goto unclustered_alloc;
5899 }
5900
fa9c0d79
CM
5901 /*
5902 * this cluster didn't work out, free it and
5903 * start over
5904 */
5905 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5906
a5f6f719
AO
5907 if (loop >= LOOP_NO_EMPTY_SIZE) {
5908 spin_unlock(&last_ptr->refill_lock);
5909 goto unclustered_alloc;
5910 }
5911
8de972b4
CM
5912 aligned_cluster = max_t(unsigned long,
5913 empty_cluster + empty_size,
5914 block_group->full_stripe_len);
5915
fa9c0d79 5916 /* allocate a cluster in this block group */
451d7585 5917 ret = btrfs_find_space_cluster(trans, root,
fa9c0d79 5918 block_group, last_ptr,
1b22bad7 5919 search_start, num_bytes,
8de972b4 5920 aligned_cluster);
fa9c0d79
CM
5921 if (ret == 0) {
5922 /*
5923 * now pull our allocation out of this
5924 * cluster
5925 */
5926 offset = btrfs_alloc_from_cluster(block_group,
5927 last_ptr, num_bytes,
5928 search_start);
5929 if (offset) {
5930 /* we found one, proceed */
5931 spin_unlock(&last_ptr->refill_lock);
3f7de037
JB
5932 trace_btrfs_reserve_extent_cluster(root,
5933 block_group, search_start,
5934 num_bytes);
fa9c0d79
CM
5935 goto checks;
5936 }
0a24325e
JB
5937 } else if (!cached && loop > LOOP_CACHING_NOWAIT
5938 && !failed_cluster_refill) {
817d52f8
JB
5939 spin_unlock(&last_ptr->refill_lock);
5940
0a24325e 5941 failed_cluster_refill = true;
817d52f8
JB
5942 wait_block_group_cache_progress(block_group,
5943 num_bytes + empty_cluster + empty_size);
5944 goto have_block_group;
fa9c0d79 5945 }
817d52f8 5946
fa9c0d79
CM
5947 /*
5948 * at this point we either didn't find a cluster
5949 * or we weren't able to allocate a block from our
5950 * cluster. Free the cluster we've been trying
5951 * to use, and go to the next block group
5952 */
0a24325e 5953 btrfs_return_cluster_to_free_space(NULL, last_ptr);
fa9c0d79 5954 spin_unlock(&last_ptr->refill_lock);
0a24325e 5955 goto loop;
fa9c0d79
CM
5956 }
5957
062c05c4 5958unclustered_alloc:
a5f6f719
AO
5959 spin_lock(&block_group->free_space_ctl->tree_lock);
5960 if (cached &&
5961 block_group->free_space_ctl->free_space <
5962 num_bytes + empty_cluster + empty_size) {
5963 spin_unlock(&block_group->free_space_ctl->tree_lock);
5964 goto loop;
5965 }
5966 spin_unlock(&block_group->free_space_ctl->tree_lock);
5967
6226cb0a
JB
5968 offset = btrfs_find_space_for_alloc(block_group, search_start,
5969 num_bytes, empty_size);
1cdda9b8
JB
5970 /*
5971 * If we didn't find a chunk, and we haven't failed on this
5972 * block group before, and this block group is in the middle of
5973 * caching and we are ok with waiting, then go ahead and wait
5974 * for progress to be made, and set failed_alloc to true.
5975 *
5976 * If failed_alloc is true then we've already waited on this
5977 * block group once and should move on to the next block group.
5978 */
5979 if (!offset && !failed_alloc && !cached &&
5980 loop > LOOP_CACHING_NOWAIT) {
817d52f8 5981 wait_block_group_cache_progress(block_group,
1cdda9b8
JB
5982 num_bytes + empty_size);
5983 failed_alloc = true;
817d52f8 5984 goto have_block_group;
1cdda9b8 5985 } else if (!offset) {
60d2adbb
MX
5986 if (!cached)
5987 have_caching_bg = true;
1cdda9b8 5988 goto loop;
817d52f8 5989 }
fa9c0d79 5990checks:
53b381b3
DW
5991 search_start = stripe_align(root, used_block_group,
5992 offset, num_bytes);
25179201 5993
2552d17e
JB
5994 /* move on to the next group */
5995 if (search_start + num_bytes >
274bd4fb
AO
5996 used_block_group->key.objectid + used_block_group->key.offset) {
5997 btrfs_add_free_space(used_block_group, offset, num_bytes);
2552d17e 5998 goto loop;
6226cb0a 5999 }
f5a31e16 6000
f0486c68 6001 if (offset < search_start)
274bd4fb 6002 btrfs_add_free_space(used_block_group, offset,
f0486c68
YZ
6003 search_start - offset);
6004 BUG_ON(offset > search_start);
2552d17e 6005
274bd4fb 6006 ret = btrfs_update_reserved_bytes(used_block_group, num_bytes,
fb25e914 6007 alloc_type);
f0486c68 6008 if (ret == -EAGAIN) {
274bd4fb 6009 btrfs_add_free_space(used_block_group, offset, num_bytes);
2552d17e 6010 goto loop;
0f9dd46c 6011 }
0b86a832 6012
f0486c68 6013 /* we are all good, lets return */
2552d17e
JB
6014 ins->objectid = search_start;
6015 ins->offset = num_bytes;
d2fb3437 6016
3f7de037
JB
6017 trace_btrfs_reserve_extent(orig_root, block_group,
6018 search_start, num_bytes);
274bd4fb
AO
6019 if (used_block_group != block_group)
6020 btrfs_put_block_group(used_block_group);
d82a6f1d 6021 btrfs_put_block_group(block_group);
2552d17e
JB
6022 break;
6023loop:
0a24325e 6024 failed_cluster_refill = false;
1cdda9b8 6025 failed_alloc = false;
b742bb82 6026 BUG_ON(index != get_block_group_index(block_group));
274bd4fb
AO
6027 if (used_block_group != block_group)
6028 btrfs_put_block_group(used_block_group);
fa9c0d79 6029 btrfs_put_block_group(block_group);
2552d17e
JB
6030 }
6031 up_read(&space_info->groups_sem);
6032
60d2adbb
MX
6033 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
6034 goto search;
6035
b742bb82
YZ
6036 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
6037 goto search;
6038
285ff5af 6039 /*
ccf0e725
JB
6040 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6041 * caching kthreads as we move along
817d52f8
JB
6042 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6043 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6044 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6045 * again
fa9c0d79 6046 */
723bda20 6047 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
b742bb82 6048 index = 0;
723bda20 6049 loop++;
817d52f8 6050 if (loop == LOOP_ALLOC_CHUNK) {
698d0082 6051 ret = do_chunk_alloc(trans, root, data,
ea658bad
JB
6052 CHUNK_ALLOC_FORCE);
6053 /*
6054 * Do not bail out on ENOSPC since we
6055 * can do more things.
6056 */
6057 if (ret < 0 && ret != -ENOSPC) {
6058 btrfs_abort_transaction(trans,
6059 root, ret);
6060 goto out;
723bda20 6061 }
2552d17e
JB
6062 }
6063
723bda20
JB
6064 if (loop == LOOP_NO_EMPTY_SIZE) {
6065 empty_size = 0;
6066 empty_cluster = 0;
fa9c0d79 6067 }
723bda20
JB
6068
6069 goto search;
2552d17e
JB
6070 } else if (!ins->objectid) {
6071 ret = -ENOSPC;
d82a6f1d 6072 } else if (ins->objectid) {
80eb234a 6073 ret = 0;
be744175 6074 }
79787eaa 6075out:
be744175 6076
0f70abe2 6077 return ret;
fec577fb 6078}
ec44a35c 6079
9ed74f2d
JB
6080static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
6081 int dump_block_groups)
0f9dd46c
JB
6082{
6083 struct btrfs_block_group_cache *cache;
b742bb82 6084 int index = 0;
0f9dd46c 6085
9ed74f2d 6086 spin_lock(&info->lock);
fb25e914
JB
6087 printk(KERN_INFO "space_info %llu has %llu free, is %sfull\n",
6088 (unsigned long long)info->flags,
d397712b 6089 (unsigned long long)(info->total_bytes - info->bytes_used -
9ed74f2d 6090 info->bytes_pinned - info->bytes_reserved -
8929ecfa 6091 info->bytes_readonly),
d397712b 6092 (info->full) ? "" : "not ");
8929ecfa
YZ
6093 printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
6094 "reserved=%llu, may_use=%llu, readonly=%llu\n",
21380931 6095 (unsigned long long)info->total_bytes,
8929ecfa 6096 (unsigned long long)info->bytes_used,
21380931 6097 (unsigned long long)info->bytes_pinned,
8929ecfa 6098 (unsigned long long)info->bytes_reserved,
21380931 6099 (unsigned long long)info->bytes_may_use,
8929ecfa 6100 (unsigned long long)info->bytes_readonly);
9ed74f2d
JB
6101 spin_unlock(&info->lock);
6102
6103 if (!dump_block_groups)
6104 return;
0f9dd46c 6105
80eb234a 6106 down_read(&info->groups_sem);
b742bb82
YZ
6107again:
6108 list_for_each_entry(cache, &info->block_groups[index], list) {
0f9dd46c 6109 spin_lock(&cache->lock);
799ffc3c 6110 printk(KERN_INFO "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s\n",
d397712b
CM
6111 (unsigned long long)cache->key.objectid,
6112 (unsigned long long)cache->key.offset,
6113 (unsigned long long)btrfs_block_group_used(&cache->item),
6114 (unsigned long long)cache->pinned,
799ffc3c
LB
6115 (unsigned long long)cache->reserved,
6116 cache->ro ? "[readonly]" : "");
0f9dd46c
JB
6117 btrfs_dump_free_space(cache, bytes);
6118 spin_unlock(&cache->lock);
6119 }
b742bb82
YZ
6120 if (++index < BTRFS_NR_RAID_TYPES)
6121 goto again;
80eb234a 6122 up_read(&info->groups_sem);
0f9dd46c 6123}
e8569813 6124
11833d66
YZ
6125int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
6126 struct btrfs_root *root,
6127 u64 num_bytes, u64 min_alloc_size,
6128 u64 empty_size, u64 hint_byte,
81c9ad23 6129 struct btrfs_key *ins, u64 data)
fec577fb 6130{
9e622d6b 6131 bool final_tried = false;
fec577fb 6132 int ret;
925baedd 6133
6a63209f 6134 data = btrfs_get_alloc_profile(root, data);
98d20f67 6135again:
db94535d
CM
6136 WARN_ON(num_bytes < root->sectorsize);
6137 ret = find_free_extent(trans, root, num_bytes, empty_size,
81c9ad23 6138 hint_byte, ins, data);
3b951516 6139
9e622d6b
MX
6140 if (ret == -ENOSPC) {
6141 if (!final_tried) {
6142 num_bytes = num_bytes >> 1;
24542bf7 6143 num_bytes = round_down(num_bytes, root->sectorsize);
9e622d6b 6144 num_bytes = max(num_bytes, min_alloc_size);
9e622d6b
MX
6145 if (num_bytes == min_alloc_size)
6146 final_tried = true;
6147 goto again;
6148 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6149 struct btrfs_space_info *sinfo;
6150
6151 sinfo = __find_space_info(root->fs_info, data);
6152 printk(KERN_ERR "btrfs allocation failed flags %llu, "
6153 "wanted %llu\n", (unsigned long long)data,
6154 (unsigned long long)num_bytes);
53804280
JM
6155 if (sinfo)
6156 dump_space_info(sinfo, num_bytes, 1);
9e622d6b 6157 }
925baedd 6158 }
0f9dd46c 6159
1abe9b8a 6160 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
6161
0f9dd46c 6162 return ret;
e6dcd2dc
CM
6163}
6164
e688b725
CM
6165static int __btrfs_free_reserved_extent(struct btrfs_root *root,
6166 u64 start, u64 len, int pin)
65b51a00 6167{
0f9dd46c 6168 struct btrfs_block_group_cache *cache;
1f3c79a2 6169 int ret = 0;
0f9dd46c 6170
0f9dd46c
JB
6171 cache = btrfs_lookup_block_group(root->fs_info, start);
6172 if (!cache) {
d397712b
CM
6173 printk(KERN_ERR "Unable to find block group for %llu\n",
6174 (unsigned long long)start);
0f9dd46c
JB
6175 return -ENOSPC;
6176 }
1f3c79a2 6177
5378e607
LD
6178 if (btrfs_test_opt(root, DISCARD))
6179 ret = btrfs_discard_extent(root, start, len, NULL);
1f3c79a2 6180
e688b725
CM
6181 if (pin)
6182 pin_down_extent(root, cache, start, len, 1);
6183 else {
6184 btrfs_add_free_space(cache, start, len);
6185 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
6186 }
fa9c0d79 6187 btrfs_put_block_group(cache);
817d52f8 6188
1abe9b8a 6189 trace_btrfs_reserved_extent_free(root, start, len);
6190
e6dcd2dc
CM
6191 return ret;
6192}
6193
e688b725
CM
6194int btrfs_free_reserved_extent(struct btrfs_root *root,
6195 u64 start, u64 len)
6196{
6197 return __btrfs_free_reserved_extent(root, start, len, 0);
6198}
6199
6200int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
6201 u64 start, u64 len)
6202{
6203 return __btrfs_free_reserved_extent(root, start, len, 1);
6204}
6205
5d4f98a2
YZ
6206static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6207 struct btrfs_root *root,
6208 u64 parent, u64 root_objectid,
6209 u64 flags, u64 owner, u64 offset,
6210 struct btrfs_key *ins, int ref_mod)
e6dcd2dc
CM
6211{
6212 int ret;
5d4f98a2 6213 struct btrfs_fs_info *fs_info = root->fs_info;
e6dcd2dc 6214 struct btrfs_extent_item *extent_item;
5d4f98a2 6215 struct btrfs_extent_inline_ref *iref;
e6dcd2dc 6216 struct btrfs_path *path;
5d4f98a2
YZ
6217 struct extent_buffer *leaf;
6218 int type;
6219 u32 size;
26b8003f 6220
5d4f98a2
YZ
6221 if (parent > 0)
6222 type = BTRFS_SHARED_DATA_REF_KEY;
6223 else
6224 type = BTRFS_EXTENT_DATA_REF_KEY;
58176a96 6225
5d4f98a2 6226 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7bb86316
CM
6227
6228 path = btrfs_alloc_path();
db5b493a
TI
6229 if (!path)
6230 return -ENOMEM;
47e4bb98 6231
b9473439 6232 path->leave_spinning = 1;
5d4f98a2
YZ
6233 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6234 ins, size);
79787eaa
JM
6235 if (ret) {
6236 btrfs_free_path(path);
6237 return ret;
6238 }
0f9dd46c 6239
5d4f98a2
YZ
6240 leaf = path->nodes[0];
6241 extent_item = btrfs_item_ptr(leaf, path->slots[0],
47e4bb98 6242 struct btrfs_extent_item);
5d4f98a2
YZ
6243 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6244 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6245 btrfs_set_extent_flags(leaf, extent_item,
6246 flags | BTRFS_EXTENT_FLAG_DATA);
6247
6248 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6249 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6250 if (parent > 0) {
6251 struct btrfs_shared_data_ref *ref;
6252 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6253 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6254 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6255 } else {
6256 struct btrfs_extent_data_ref *ref;
6257 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6258 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6259 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6260 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6261 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6262 }
47e4bb98
CM
6263
6264 btrfs_mark_buffer_dirty(path->nodes[0]);
7bb86316 6265 btrfs_free_path(path);
f510cfec 6266
c53d613e 6267 ret = update_block_group(root, ins->objectid, ins->offset, 1);
79787eaa 6268 if (ret) { /* -ENOENT, logic error */
d397712b
CM
6269 printk(KERN_ERR "btrfs update block group failed for %llu "
6270 "%llu\n", (unsigned long long)ins->objectid,
6271 (unsigned long long)ins->offset);
f5947066
CM
6272 BUG();
6273 }
e6dcd2dc
CM
6274 return ret;
6275}
6276
5d4f98a2
YZ
6277static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6278 struct btrfs_root *root,
6279 u64 parent, u64 root_objectid,
6280 u64 flags, struct btrfs_disk_key *key,
6281 int level, struct btrfs_key *ins)
e6dcd2dc
CM
6282{
6283 int ret;
5d4f98a2
YZ
6284 struct btrfs_fs_info *fs_info = root->fs_info;
6285 struct btrfs_extent_item *extent_item;
6286 struct btrfs_tree_block_info *block_info;
6287 struct btrfs_extent_inline_ref *iref;
6288 struct btrfs_path *path;
6289 struct extent_buffer *leaf;
6290 u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
1c2308f8 6291
5d4f98a2 6292 path = btrfs_alloc_path();
d8926bb3
MF
6293 if (!path)
6294 return -ENOMEM;
56bec294 6295
5d4f98a2
YZ
6296 path->leave_spinning = 1;
6297 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6298 ins, size);
79787eaa
JM
6299 if (ret) {
6300 btrfs_free_path(path);
6301 return ret;
6302 }
5d4f98a2
YZ
6303
6304 leaf = path->nodes[0];
6305 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6306 struct btrfs_extent_item);
6307 btrfs_set_extent_refs(leaf, extent_item, 1);
6308 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6309 btrfs_set_extent_flags(leaf, extent_item,
6310 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6311 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6312
6313 btrfs_set_tree_block_key(leaf, block_info, key);
6314 btrfs_set_tree_block_level(leaf, block_info, level);
6315
6316 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6317 if (parent > 0) {
6318 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6319 btrfs_set_extent_inline_ref_type(leaf, iref,
6320 BTRFS_SHARED_BLOCK_REF_KEY);
6321 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6322 } else {
6323 btrfs_set_extent_inline_ref_type(leaf, iref,
6324 BTRFS_TREE_BLOCK_REF_KEY);
6325 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6326 }
6327
6328 btrfs_mark_buffer_dirty(leaf);
6329 btrfs_free_path(path);
6330
c53d613e 6331 ret = update_block_group(root, ins->objectid, ins->offset, 1);
79787eaa 6332 if (ret) { /* -ENOENT, logic error */
5d4f98a2
YZ
6333 printk(KERN_ERR "btrfs update block group failed for %llu "
6334 "%llu\n", (unsigned long long)ins->objectid,
6335 (unsigned long long)ins->offset);
6336 BUG();
6337 }
6338 return ret;
6339}
6340
6341int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6342 struct btrfs_root *root,
6343 u64 root_objectid, u64 owner,
6344 u64 offset, struct btrfs_key *ins)
6345{
6346 int ret;
6347
6348 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
6349
66d7e7f0
AJ
6350 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
6351 ins->offset, 0,
6352 root_objectid, owner, offset,
6353 BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
e6dcd2dc
CM
6354 return ret;
6355}
e02119d5
CM
6356
6357/*
6358 * this is used by the tree logging recovery code. It records that
6359 * an extent has been allocated and makes sure to clear the free
6360 * space cache bits as well
6361 */
5d4f98a2
YZ
6362int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6363 struct btrfs_root *root,
6364 u64 root_objectid, u64 owner, u64 offset,
6365 struct btrfs_key *ins)
e02119d5
CM
6366{
6367 int ret;
6368 struct btrfs_block_group_cache *block_group;
11833d66
YZ
6369 struct btrfs_caching_control *caching_ctl;
6370 u64 start = ins->objectid;
6371 u64 num_bytes = ins->offset;
e02119d5 6372
e02119d5 6373 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
f6373bf3 6374 cache_block_group(block_group, 0);
11833d66 6375 caching_ctl = get_caching_control(block_group);
e02119d5 6376
11833d66
YZ
6377 if (!caching_ctl) {
6378 BUG_ON(!block_group_cache_done(block_group));
6379 ret = btrfs_remove_free_space(block_group, start, num_bytes);
79787eaa 6380 BUG_ON(ret); /* -ENOMEM */
11833d66
YZ
6381 } else {
6382 mutex_lock(&caching_ctl->mutex);
6383
6384 if (start >= caching_ctl->progress) {
6385 ret = add_excluded_extent(root, start, num_bytes);
79787eaa 6386 BUG_ON(ret); /* -ENOMEM */
11833d66
YZ
6387 } else if (start + num_bytes <= caching_ctl->progress) {
6388 ret = btrfs_remove_free_space(block_group,
6389 start, num_bytes);
79787eaa 6390 BUG_ON(ret); /* -ENOMEM */
11833d66
YZ
6391 } else {
6392 num_bytes = caching_ctl->progress - start;
6393 ret = btrfs_remove_free_space(block_group,
6394 start, num_bytes);
79787eaa 6395 BUG_ON(ret); /* -ENOMEM */
11833d66
YZ
6396
6397 start = caching_ctl->progress;
6398 num_bytes = ins->objectid + ins->offset -
6399 caching_ctl->progress;
6400 ret = add_excluded_extent(root, start, num_bytes);
79787eaa 6401 BUG_ON(ret); /* -ENOMEM */
11833d66
YZ
6402 }
6403
6404 mutex_unlock(&caching_ctl->mutex);
6405 put_caching_control(caching_ctl);
6406 }
6407
fb25e914
JB
6408 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
6409 RESERVE_ALLOC_NO_ACCOUNT);
79787eaa 6410 BUG_ON(ret); /* logic error */
fa9c0d79 6411 btrfs_put_block_group(block_group);
5d4f98a2
YZ
6412 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
6413 0, owner, offset, ins, 1);
e02119d5
CM
6414 return ret;
6415}
6416
65b51a00
CM
6417struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
6418 struct btrfs_root *root,
4008c04a
CM
6419 u64 bytenr, u32 blocksize,
6420 int level)
65b51a00
CM
6421{
6422 struct extent_buffer *buf;
6423
6424 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
6425 if (!buf)
6426 return ERR_PTR(-ENOMEM);
6427 btrfs_set_header_generation(buf, trans->transid);
85d4e461 6428 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
65b51a00
CM
6429 btrfs_tree_lock(buf);
6430 clean_tree_block(trans, root, buf);
3083ee2e 6431 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
b4ce94de
CM
6432
6433 btrfs_set_lock_blocking(buf);
65b51a00 6434 btrfs_set_buffer_uptodate(buf);
b4ce94de 6435
d0c803c4 6436 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8cef4e16
YZ
6437 /*
6438 * we allow two log transactions at a time, use different
6439 * EXENT bit to differentiate dirty pages.
6440 */
6441 if (root->log_transid % 2 == 0)
6442 set_extent_dirty(&root->dirty_log_pages, buf->start,
6443 buf->start + buf->len - 1, GFP_NOFS);
6444 else
6445 set_extent_new(&root->dirty_log_pages, buf->start,
6446 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4
CM
6447 } else {
6448 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 6449 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 6450 }
65b51a00 6451 trans->blocks_used++;
b4ce94de 6452 /* this returns a buffer locked for blocking */
65b51a00
CM
6453 return buf;
6454}
6455
f0486c68
YZ
6456static struct btrfs_block_rsv *
6457use_block_rsv(struct btrfs_trans_handle *trans,
6458 struct btrfs_root *root, u32 blocksize)
6459{
6460 struct btrfs_block_rsv *block_rsv;
68a82277 6461 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
f0486c68
YZ
6462 int ret;
6463
6464 block_rsv = get_block_rsv(trans, root);
6465
6466 if (block_rsv->size == 0) {
08e007d2
MX
6467 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6468 BTRFS_RESERVE_NO_FLUSH);
68a82277
JB
6469 /*
6470 * If we couldn't reserve metadata bytes try and use some from
6471 * the global reserve.
6472 */
6473 if (ret && block_rsv != global_rsv) {
6474 ret = block_rsv_use_bytes(global_rsv, blocksize);
6475 if (!ret)
6476 return global_rsv;
f0486c68 6477 return ERR_PTR(ret);
68a82277 6478 } else if (ret) {
f0486c68 6479 return ERR_PTR(ret);
68a82277 6480 }
f0486c68
YZ
6481 return block_rsv;
6482 }
6483
6484 ret = block_rsv_use_bytes(block_rsv, blocksize);
6485 if (!ret)
6486 return block_rsv;
ca7e70f5 6487 if (ret && !block_rsv->failfast) {
b069e0c3
DS
6488 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6489 static DEFINE_RATELIMIT_STATE(_rs,
6490 DEFAULT_RATELIMIT_INTERVAL * 10,
6491 /*DEFAULT_RATELIMIT_BURST*/ 1);
6492 if (__ratelimit(&_rs))
6493 WARN(1, KERN_DEBUG
6494 "btrfs: block rsv returned %d\n", ret);
6495 }
08e007d2
MX
6496 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6497 BTRFS_RESERVE_NO_FLUSH);
68a82277 6498 if (!ret) {
68a82277
JB
6499 return block_rsv;
6500 } else if (ret && block_rsv != global_rsv) {
6501 ret = block_rsv_use_bytes(global_rsv, blocksize);
6502 if (!ret)
6503 return global_rsv;
6504 }
6505 }
f0486c68 6506
f0486c68
YZ
6507 return ERR_PTR(-ENOSPC);
6508}
6509
8c2a3ca2
JB
6510static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
6511 struct btrfs_block_rsv *block_rsv, u32 blocksize)
f0486c68
YZ
6512{
6513 block_rsv_add_bytes(block_rsv, blocksize, 0);
8c2a3ca2 6514 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
f0486c68
YZ
6515}
6516
fec577fb 6517/*
f0486c68
YZ
6518 * finds a free extent and does all the dirty work required for allocation
6519 * returns the key for the extent through ins, and a tree buffer for
6520 * the first block of the extent through buf.
6521 *
fec577fb
CM
6522 * returns the tree buffer or NULL.
6523 */
5f39d397 6524struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5d4f98a2
YZ
6525 struct btrfs_root *root, u32 blocksize,
6526 u64 parent, u64 root_objectid,
6527 struct btrfs_disk_key *key, int level,
5581a51a 6528 u64 hint, u64 empty_size)
fec577fb 6529{
e2fa7227 6530 struct btrfs_key ins;
f0486c68 6531 struct btrfs_block_rsv *block_rsv;
5f39d397 6532 struct extent_buffer *buf;
f0486c68
YZ
6533 u64 flags = 0;
6534 int ret;
6535
fec577fb 6536
f0486c68
YZ
6537 block_rsv = use_block_rsv(trans, root, blocksize);
6538 if (IS_ERR(block_rsv))
6539 return ERR_CAST(block_rsv);
6540
6541 ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
81c9ad23 6542 empty_size, hint, &ins, 0);
fec577fb 6543 if (ret) {
8c2a3ca2 6544 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
54aa1f4d 6545 return ERR_PTR(ret);
fec577fb 6546 }
55c69072 6547
4008c04a
CM
6548 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
6549 blocksize, level);
79787eaa 6550 BUG_ON(IS_ERR(buf)); /* -ENOMEM */
f0486c68
YZ
6551
6552 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6553 if (parent == 0)
6554 parent = ins.objectid;
6555 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6556 } else
6557 BUG_ON(parent > 0);
6558
6559 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6560 struct btrfs_delayed_extent_op *extent_op;
78a6184a 6561 extent_op = btrfs_alloc_delayed_extent_op();
79787eaa 6562 BUG_ON(!extent_op); /* -ENOMEM */
f0486c68
YZ
6563 if (key)
6564 memcpy(&extent_op->key, key, sizeof(extent_op->key));
6565 else
6566 memset(&extent_op->key, 0, sizeof(extent_op->key));
6567 extent_op->flags_to_set = flags;
6568 extent_op->update_key = 1;
6569 extent_op->update_flags = 1;
6570 extent_op->is_data = 0;
6571
66d7e7f0
AJ
6572 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6573 ins.objectid,
f0486c68
YZ
6574 ins.offset, parent, root_objectid,
6575 level, BTRFS_ADD_DELAYED_EXTENT,
5581a51a 6576 extent_op, 0);
79787eaa 6577 BUG_ON(ret); /* -ENOMEM */
f0486c68 6578 }
fec577fb
CM
6579 return buf;
6580}
a28ec197 6581
2c47e605
YZ
6582struct walk_control {
6583 u64 refs[BTRFS_MAX_LEVEL];
6584 u64 flags[BTRFS_MAX_LEVEL];
6585 struct btrfs_key update_progress;
6586 int stage;
6587 int level;
6588 int shared_level;
6589 int update_ref;
6590 int keep_locks;
1c4850e2
YZ
6591 int reada_slot;
6592 int reada_count;
66d7e7f0 6593 int for_reloc;
2c47e605
YZ
6594};
6595
6596#define DROP_REFERENCE 1
6597#define UPDATE_BACKREF 2
6598
1c4850e2
YZ
6599static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6600 struct btrfs_root *root,
6601 struct walk_control *wc,
6602 struct btrfs_path *path)
6407bf6d 6603{
1c4850e2
YZ
6604 u64 bytenr;
6605 u64 generation;
6606 u64 refs;
94fcca9f 6607 u64 flags;
5d4f98a2 6608 u32 nritems;
1c4850e2
YZ
6609 u32 blocksize;
6610 struct btrfs_key key;
6611 struct extent_buffer *eb;
6407bf6d 6612 int ret;
1c4850e2
YZ
6613 int slot;
6614 int nread = 0;
6407bf6d 6615
1c4850e2
YZ
6616 if (path->slots[wc->level] < wc->reada_slot) {
6617 wc->reada_count = wc->reada_count * 2 / 3;
6618 wc->reada_count = max(wc->reada_count, 2);
6619 } else {
6620 wc->reada_count = wc->reada_count * 3 / 2;
6621 wc->reada_count = min_t(int, wc->reada_count,
6622 BTRFS_NODEPTRS_PER_BLOCK(root));
6623 }
7bb86316 6624
1c4850e2
YZ
6625 eb = path->nodes[wc->level];
6626 nritems = btrfs_header_nritems(eb);
6627 blocksize = btrfs_level_size(root, wc->level - 1);
bd56b302 6628
1c4850e2
YZ
6629 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
6630 if (nread >= wc->reada_count)
6631 break;
bd56b302 6632
2dd3e67b 6633 cond_resched();
1c4850e2
YZ
6634 bytenr = btrfs_node_blockptr(eb, slot);
6635 generation = btrfs_node_ptr_generation(eb, slot);
2dd3e67b 6636
1c4850e2
YZ
6637 if (slot == path->slots[wc->level])
6638 goto reada;
5d4f98a2 6639
1c4850e2
YZ
6640 if (wc->stage == UPDATE_BACKREF &&
6641 generation <= root->root_key.offset)
bd56b302
CM
6642 continue;
6643
94fcca9f
YZ
6644 /* We don't lock the tree block, it's OK to be racy here */
6645 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6646 &refs, &flags);
79787eaa
JM
6647 /* We don't care about errors in readahead. */
6648 if (ret < 0)
6649 continue;
94fcca9f
YZ
6650 BUG_ON(refs == 0);
6651
1c4850e2 6652 if (wc->stage == DROP_REFERENCE) {
1c4850e2
YZ
6653 if (refs == 1)
6654 goto reada;
bd56b302 6655
94fcca9f
YZ
6656 if (wc->level == 1 &&
6657 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6658 continue;
1c4850e2
YZ
6659 if (!wc->update_ref ||
6660 generation <= root->root_key.offset)
6661 continue;
6662 btrfs_node_key_to_cpu(eb, &key, slot);
6663 ret = btrfs_comp_cpu_keys(&key,
6664 &wc->update_progress);
6665 if (ret < 0)
6666 continue;
94fcca9f
YZ
6667 } else {
6668 if (wc->level == 1 &&
6669 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6670 continue;
6407bf6d 6671 }
1c4850e2
YZ
6672reada:
6673 ret = readahead_tree_block(root, bytenr, blocksize,
6674 generation);
6675 if (ret)
bd56b302 6676 break;
1c4850e2 6677 nread++;
20524f02 6678 }
1c4850e2 6679 wc->reada_slot = slot;
20524f02 6680}
2c47e605 6681
f82d02d9 6682/*
2c47e605
YZ
6683 * hepler to process tree block while walking down the tree.
6684 *
2c47e605
YZ
6685 * when wc->stage == UPDATE_BACKREF, this function updates
6686 * back refs for pointers in the block.
6687 *
6688 * NOTE: return value 1 means we should stop walking down.
f82d02d9 6689 */
2c47e605 6690static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5d4f98a2 6691 struct btrfs_root *root,
2c47e605 6692 struct btrfs_path *path,
94fcca9f 6693 struct walk_control *wc, int lookup_info)
f82d02d9 6694{
2c47e605
YZ
6695 int level = wc->level;
6696 struct extent_buffer *eb = path->nodes[level];
2c47e605 6697 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
f82d02d9
YZ
6698 int ret;
6699
2c47e605
YZ
6700 if (wc->stage == UPDATE_BACKREF &&
6701 btrfs_header_owner(eb) != root->root_key.objectid)
6702 return 1;
f82d02d9 6703
2c47e605
YZ
6704 /*
6705 * when reference count of tree block is 1, it won't increase
6706 * again. once full backref flag is set, we never clear it.
6707 */
94fcca9f
YZ
6708 if (lookup_info &&
6709 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
6710 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
2c47e605
YZ
6711 BUG_ON(!path->locks[level]);
6712 ret = btrfs_lookup_extent_info(trans, root,
6713 eb->start, eb->len,
6714 &wc->refs[level],
6715 &wc->flags[level]);
79787eaa
JM
6716 BUG_ON(ret == -ENOMEM);
6717 if (ret)
6718 return ret;
2c47e605
YZ
6719 BUG_ON(wc->refs[level] == 0);
6720 }
5d4f98a2 6721
2c47e605
YZ
6722 if (wc->stage == DROP_REFERENCE) {
6723 if (wc->refs[level] > 1)
6724 return 1;
f82d02d9 6725
2c47e605 6726 if (path->locks[level] && !wc->keep_locks) {
bd681513 6727 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
6728 path->locks[level] = 0;
6729 }
6730 return 0;
6731 }
f82d02d9 6732
2c47e605
YZ
6733 /* wc->stage == UPDATE_BACKREF */
6734 if (!(wc->flags[level] & flag)) {
6735 BUG_ON(!path->locks[level]);
66d7e7f0 6736 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
79787eaa 6737 BUG_ON(ret); /* -ENOMEM */
66d7e7f0 6738 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
79787eaa 6739 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
6740 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
6741 eb->len, flag, 0);
79787eaa 6742 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
6743 wc->flags[level] |= flag;
6744 }
6745
6746 /*
6747 * the block is shared by multiple trees, so it's not good to
6748 * keep the tree lock
6749 */
6750 if (path->locks[level] && level > 0) {
bd681513 6751 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
6752 path->locks[level] = 0;
6753 }
6754 return 0;
6755}
6756
1c4850e2
YZ
6757/*
6758 * hepler to process tree block pointer.
6759 *
6760 * when wc->stage == DROP_REFERENCE, this function checks
6761 * reference count of the block pointed to. if the block
6762 * is shared and we need update back refs for the subtree
6763 * rooted at the block, this function changes wc->stage to
6764 * UPDATE_BACKREF. if the block is shared and there is no
6765 * need to update back, this function drops the reference
6766 * to the block.
6767 *
6768 * NOTE: return value 1 means we should stop walking down.
6769 */
6770static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6771 struct btrfs_root *root,
6772 struct btrfs_path *path,
94fcca9f 6773 struct walk_control *wc, int *lookup_info)
1c4850e2
YZ
6774{
6775 u64 bytenr;
6776 u64 generation;
6777 u64 parent;
6778 u32 blocksize;
6779 struct btrfs_key key;
6780 struct extent_buffer *next;
6781 int level = wc->level;
6782 int reada = 0;
6783 int ret = 0;
6784
6785 generation = btrfs_node_ptr_generation(path->nodes[level],
6786 path->slots[level]);
6787 /*
6788 * if the lower level block was created before the snapshot
6789 * was created, we know there is no need to update back refs
6790 * for the subtree
6791 */
6792 if (wc->stage == UPDATE_BACKREF &&
94fcca9f
YZ
6793 generation <= root->root_key.offset) {
6794 *lookup_info = 1;
1c4850e2 6795 return 1;
94fcca9f 6796 }
1c4850e2
YZ
6797
6798 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6799 blocksize = btrfs_level_size(root, level - 1);
6800
6801 next = btrfs_find_tree_block(root, bytenr, blocksize);
6802 if (!next) {
6803 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
90d2c51d
MX
6804 if (!next)
6805 return -ENOMEM;
1c4850e2
YZ
6806 reada = 1;
6807 }
6808 btrfs_tree_lock(next);
6809 btrfs_set_lock_blocking(next);
6810
94fcca9f
YZ
6811 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6812 &wc->refs[level - 1],
6813 &wc->flags[level - 1]);
79787eaa
JM
6814 if (ret < 0) {
6815 btrfs_tree_unlock(next);
6816 return ret;
6817 }
6818
94fcca9f
YZ
6819 BUG_ON(wc->refs[level - 1] == 0);
6820 *lookup_info = 0;
1c4850e2 6821
94fcca9f 6822 if (wc->stage == DROP_REFERENCE) {
1c4850e2 6823 if (wc->refs[level - 1] > 1) {
94fcca9f
YZ
6824 if (level == 1 &&
6825 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6826 goto skip;
6827
1c4850e2
YZ
6828 if (!wc->update_ref ||
6829 generation <= root->root_key.offset)
6830 goto skip;
6831
6832 btrfs_node_key_to_cpu(path->nodes[level], &key,
6833 path->slots[level]);
6834 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6835 if (ret < 0)
6836 goto skip;
6837
6838 wc->stage = UPDATE_BACKREF;
6839 wc->shared_level = level - 1;
6840 }
94fcca9f
YZ
6841 } else {
6842 if (level == 1 &&
6843 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6844 goto skip;
1c4850e2
YZ
6845 }
6846
b9fab919 6847 if (!btrfs_buffer_uptodate(next, generation, 0)) {
1c4850e2
YZ
6848 btrfs_tree_unlock(next);
6849 free_extent_buffer(next);
6850 next = NULL;
94fcca9f 6851 *lookup_info = 1;
1c4850e2
YZ
6852 }
6853
6854 if (!next) {
6855 if (reada && level == 1)
6856 reada_walk_down(trans, root, wc, path);
6857 next = read_tree_block(root, bytenr, blocksize, generation);
97d9a8a4
TI
6858 if (!next)
6859 return -EIO;
1c4850e2
YZ
6860 btrfs_tree_lock(next);
6861 btrfs_set_lock_blocking(next);
6862 }
6863
6864 level--;
6865 BUG_ON(level != btrfs_header_level(next));
6866 path->nodes[level] = next;
6867 path->slots[level] = 0;
bd681513 6868 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
1c4850e2
YZ
6869 wc->level = level;
6870 if (wc->level == 1)
6871 wc->reada_slot = 0;
6872 return 0;
6873skip:
6874 wc->refs[level - 1] = 0;
6875 wc->flags[level - 1] = 0;
94fcca9f
YZ
6876 if (wc->stage == DROP_REFERENCE) {
6877 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6878 parent = path->nodes[level]->start;
6879 } else {
6880 BUG_ON(root->root_key.objectid !=
6881 btrfs_header_owner(path->nodes[level]));
6882 parent = 0;
6883 }
1c4850e2 6884
94fcca9f 6885 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
66d7e7f0 6886 root->root_key.objectid, level - 1, 0, 0);
79787eaa 6887 BUG_ON(ret); /* -ENOMEM */
1c4850e2 6888 }
1c4850e2
YZ
6889 btrfs_tree_unlock(next);
6890 free_extent_buffer(next);
94fcca9f 6891 *lookup_info = 1;
1c4850e2
YZ
6892 return 1;
6893}
6894
2c47e605
YZ
6895/*
6896 * hepler to process tree block while walking up the tree.
6897 *
6898 * when wc->stage == DROP_REFERENCE, this function drops
6899 * reference count on the block.
6900 *
6901 * when wc->stage == UPDATE_BACKREF, this function changes
6902 * wc->stage back to DROP_REFERENCE if we changed wc->stage
6903 * to UPDATE_BACKREF previously while processing the block.
6904 *
6905 * NOTE: return value 1 means we should stop walking up.
6906 */
6907static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6908 struct btrfs_root *root,
6909 struct btrfs_path *path,
6910 struct walk_control *wc)
6911{
f0486c68 6912 int ret;
2c47e605
YZ
6913 int level = wc->level;
6914 struct extent_buffer *eb = path->nodes[level];
6915 u64 parent = 0;
6916
6917 if (wc->stage == UPDATE_BACKREF) {
6918 BUG_ON(wc->shared_level < level);
6919 if (level < wc->shared_level)
6920 goto out;
6921
2c47e605
YZ
6922 ret = find_next_key(path, level + 1, &wc->update_progress);
6923 if (ret > 0)
6924 wc->update_ref = 0;
6925
6926 wc->stage = DROP_REFERENCE;
6927 wc->shared_level = -1;
6928 path->slots[level] = 0;
6929
6930 /*
6931 * check reference count again if the block isn't locked.
6932 * we should start walking down the tree again if reference
6933 * count is one.
6934 */
6935 if (!path->locks[level]) {
6936 BUG_ON(level == 0);
6937 btrfs_tree_lock(eb);
6938 btrfs_set_lock_blocking(eb);
bd681513 6939 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
6940
6941 ret = btrfs_lookup_extent_info(trans, root,
6942 eb->start, eb->len,
6943 &wc->refs[level],
6944 &wc->flags[level]);
79787eaa
JM
6945 if (ret < 0) {
6946 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 6947 path->locks[level] = 0;
79787eaa
JM
6948 return ret;
6949 }
2c47e605
YZ
6950 BUG_ON(wc->refs[level] == 0);
6951 if (wc->refs[level] == 1) {
bd681513 6952 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 6953 path->locks[level] = 0;
2c47e605
YZ
6954 return 1;
6955 }
f82d02d9 6956 }
2c47e605 6957 }
f82d02d9 6958
2c47e605
YZ
6959 /* wc->stage == DROP_REFERENCE */
6960 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5d4f98a2 6961
2c47e605
YZ
6962 if (wc->refs[level] == 1) {
6963 if (level == 0) {
6964 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
66d7e7f0
AJ
6965 ret = btrfs_dec_ref(trans, root, eb, 1,
6966 wc->for_reloc);
2c47e605 6967 else
66d7e7f0
AJ
6968 ret = btrfs_dec_ref(trans, root, eb, 0,
6969 wc->for_reloc);
79787eaa 6970 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
6971 }
6972 /* make block locked assertion in clean_tree_block happy */
6973 if (!path->locks[level] &&
6974 btrfs_header_generation(eb) == trans->transid) {
6975 btrfs_tree_lock(eb);
6976 btrfs_set_lock_blocking(eb);
bd681513 6977 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
6978 }
6979 clean_tree_block(trans, root, eb);
6980 }
6981
6982 if (eb == root->node) {
6983 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6984 parent = eb->start;
6985 else
6986 BUG_ON(root->root_key.objectid !=
6987 btrfs_header_owner(eb));
6988 } else {
6989 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6990 parent = path->nodes[level + 1]->start;
6991 else
6992 BUG_ON(root->root_key.objectid !=
6993 btrfs_header_owner(path->nodes[level + 1]));
f82d02d9 6994 }
f82d02d9 6995
5581a51a 6996 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
2c47e605
YZ
6997out:
6998 wc->refs[level] = 0;
6999 wc->flags[level] = 0;
f0486c68 7000 return 0;
2c47e605
YZ
7001}
7002
7003static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
7004 struct btrfs_root *root,
7005 struct btrfs_path *path,
7006 struct walk_control *wc)
7007{
2c47e605 7008 int level = wc->level;
94fcca9f 7009 int lookup_info = 1;
2c47e605
YZ
7010 int ret;
7011
7012 while (level >= 0) {
94fcca9f 7013 ret = walk_down_proc(trans, root, path, wc, lookup_info);
2c47e605
YZ
7014 if (ret > 0)
7015 break;
7016
7017 if (level == 0)
7018 break;
7019
7a7965f8
YZ
7020 if (path->slots[level] >=
7021 btrfs_header_nritems(path->nodes[level]))
7022 break;
7023
94fcca9f 7024 ret = do_walk_down(trans, root, path, wc, &lookup_info);
1c4850e2
YZ
7025 if (ret > 0) {
7026 path->slots[level]++;
7027 continue;
90d2c51d
MX
7028 } else if (ret < 0)
7029 return ret;
1c4850e2 7030 level = wc->level;
f82d02d9 7031 }
f82d02d9
YZ
7032 return 0;
7033}
7034
d397712b 7035static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 7036 struct btrfs_root *root,
f82d02d9 7037 struct btrfs_path *path,
2c47e605 7038 struct walk_control *wc, int max_level)
20524f02 7039{
2c47e605 7040 int level = wc->level;
20524f02 7041 int ret;
9f3a7427 7042
2c47e605
YZ
7043 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
7044 while (level < max_level && path->nodes[level]) {
7045 wc->level = level;
7046 if (path->slots[level] + 1 <
7047 btrfs_header_nritems(path->nodes[level])) {
7048 path->slots[level]++;
20524f02
CM
7049 return 0;
7050 } else {
2c47e605
YZ
7051 ret = walk_up_proc(trans, root, path, wc);
7052 if (ret > 0)
7053 return 0;
bd56b302 7054
2c47e605 7055 if (path->locks[level]) {
bd681513
CM
7056 btrfs_tree_unlock_rw(path->nodes[level],
7057 path->locks[level]);
2c47e605 7058 path->locks[level] = 0;
f82d02d9 7059 }
2c47e605
YZ
7060 free_extent_buffer(path->nodes[level]);
7061 path->nodes[level] = NULL;
7062 level++;
20524f02
CM
7063 }
7064 }
7065 return 1;
7066}
7067
9aca1d51 7068/*
2c47e605
YZ
7069 * drop a subvolume tree.
7070 *
7071 * this function traverses the tree freeing any blocks that only
7072 * referenced by the tree.
7073 *
7074 * when a shared tree block is found. this function decreases its
7075 * reference count by one. if update_ref is true, this function
7076 * also make sure backrefs for the shared block and all lower level
7077 * blocks are properly updated.
9aca1d51 7078 */
2c536799 7079int btrfs_drop_snapshot(struct btrfs_root *root,
66d7e7f0
AJ
7080 struct btrfs_block_rsv *block_rsv, int update_ref,
7081 int for_reloc)
20524f02 7082{
5caf2a00 7083 struct btrfs_path *path;
2c47e605
YZ
7084 struct btrfs_trans_handle *trans;
7085 struct btrfs_root *tree_root = root->fs_info->tree_root;
9f3a7427 7086 struct btrfs_root_item *root_item = &root->root_item;
2c47e605
YZ
7087 struct walk_control *wc;
7088 struct btrfs_key key;
7089 int err = 0;
7090 int ret;
7091 int level;
20524f02 7092
5caf2a00 7093 path = btrfs_alloc_path();
cb1b69f4
TI
7094 if (!path) {
7095 err = -ENOMEM;
7096 goto out;
7097 }
20524f02 7098
2c47e605 7099 wc = kzalloc(sizeof(*wc), GFP_NOFS);
38a1a919
MF
7100 if (!wc) {
7101 btrfs_free_path(path);
cb1b69f4
TI
7102 err = -ENOMEM;
7103 goto out;
38a1a919 7104 }
2c47e605 7105
a22285a6 7106 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
7107 if (IS_ERR(trans)) {
7108 err = PTR_ERR(trans);
7109 goto out_free;
7110 }
98d5dc13 7111
3fd0a558
YZ
7112 if (block_rsv)
7113 trans->block_rsv = block_rsv;
2c47e605 7114
9f3a7427 7115 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2c47e605 7116 level = btrfs_header_level(root->node);
5d4f98a2
YZ
7117 path->nodes[level] = btrfs_lock_root_node(root);
7118 btrfs_set_lock_blocking(path->nodes[level]);
9f3a7427 7119 path->slots[level] = 0;
bd681513 7120 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7121 memset(&wc->update_progress, 0,
7122 sizeof(wc->update_progress));
9f3a7427 7123 } else {
9f3a7427 7124 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2c47e605
YZ
7125 memcpy(&wc->update_progress, &key,
7126 sizeof(wc->update_progress));
7127
6702ed49 7128 level = root_item->drop_level;
2c47e605 7129 BUG_ON(level == 0);
6702ed49 7130 path->lowest_level = level;
2c47e605
YZ
7131 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7132 path->lowest_level = 0;
7133 if (ret < 0) {
7134 err = ret;
79787eaa 7135 goto out_end_trans;
9f3a7427 7136 }
1c4850e2 7137 WARN_ON(ret > 0);
2c47e605 7138
7d9eb12c
CM
7139 /*
7140 * unlock our path, this is safe because only this
7141 * function is allowed to delete this snapshot
7142 */
5d4f98a2 7143 btrfs_unlock_up_safe(path, 0);
2c47e605
YZ
7144
7145 level = btrfs_header_level(root->node);
7146 while (1) {
7147 btrfs_tree_lock(path->nodes[level]);
7148 btrfs_set_lock_blocking(path->nodes[level]);
7149
7150 ret = btrfs_lookup_extent_info(trans, root,
7151 path->nodes[level]->start,
7152 path->nodes[level]->len,
7153 &wc->refs[level],
7154 &wc->flags[level]);
79787eaa
JM
7155 if (ret < 0) {
7156 err = ret;
7157 goto out_end_trans;
7158 }
2c47e605
YZ
7159 BUG_ON(wc->refs[level] == 0);
7160
7161 if (level == root_item->drop_level)
7162 break;
7163
7164 btrfs_tree_unlock(path->nodes[level]);
7165 WARN_ON(wc->refs[level] != 1);
7166 level--;
7167 }
9f3a7427 7168 }
2c47e605
YZ
7169
7170 wc->level = level;
7171 wc->shared_level = -1;
7172 wc->stage = DROP_REFERENCE;
7173 wc->update_ref = update_ref;
7174 wc->keep_locks = 0;
66d7e7f0 7175 wc->for_reloc = for_reloc;
1c4850e2 7176 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
2c47e605 7177
d397712b 7178 while (1) {
2c47e605
YZ
7179 ret = walk_down_tree(trans, root, path, wc);
7180 if (ret < 0) {
7181 err = ret;
20524f02 7182 break;
2c47e605 7183 }
9aca1d51 7184
2c47e605
YZ
7185 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7186 if (ret < 0) {
7187 err = ret;
20524f02 7188 break;
2c47e605
YZ
7189 }
7190
7191 if (ret > 0) {
7192 BUG_ON(wc->stage != DROP_REFERENCE);
e7a84565
CM
7193 break;
7194 }
2c47e605
YZ
7195
7196 if (wc->stage == DROP_REFERENCE) {
7197 level = wc->level;
7198 btrfs_node_key(path->nodes[level],
7199 &root_item->drop_progress,
7200 path->slots[level]);
7201 root_item->drop_level = level;
7202 }
7203
7204 BUG_ON(wc->level == 0);
3fd0a558 7205 if (btrfs_should_end_transaction(trans, tree_root)) {
2c47e605
YZ
7206 ret = btrfs_update_root(trans, tree_root,
7207 &root->root_key,
7208 root_item);
79787eaa
JM
7209 if (ret) {
7210 btrfs_abort_transaction(trans, tree_root, ret);
7211 err = ret;
7212 goto out_end_trans;
7213 }
2c47e605 7214
3fd0a558 7215 btrfs_end_transaction_throttle(trans, tree_root);
a22285a6 7216 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
7217 if (IS_ERR(trans)) {
7218 err = PTR_ERR(trans);
7219 goto out_free;
7220 }
3fd0a558
YZ
7221 if (block_rsv)
7222 trans->block_rsv = block_rsv;
c3e69d58 7223 }
20524f02 7224 }
b3b4aa74 7225 btrfs_release_path(path);
79787eaa
JM
7226 if (err)
7227 goto out_end_trans;
2c47e605
YZ
7228
7229 ret = btrfs_del_root(trans, tree_root, &root->root_key);
79787eaa
JM
7230 if (ret) {
7231 btrfs_abort_transaction(trans, tree_root, ret);
7232 goto out_end_trans;
7233 }
2c47e605 7234
76dda93c
YZ
7235 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7236 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
7237 NULL, NULL);
79787eaa
JM
7238 if (ret < 0) {
7239 btrfs_abort_transaction(trans, tree_root, ret);
7240 err = ret;
7241 goto out_end_trans;
7242 } else if (ret > 0) {
84cd948c
JB
7243 /* if we fail to delete the orphan item this time
7244 * around, it'll get picked up the next time.
7245 *
7246 * The most common failure here is just -ENOENT.
7247 */
7248 btrfs_del_orphan_item(trans, tree_root,
7249 root->root_key.objectid);
76dda93c
YZ
7250 }
7251 }
7252
7253 if (root->in_radix) {
7254 btrfs_free_fs_root(tree_root->fs_info, root);
7255 } else {
7256 free_extent_buffer(root->node);
7257 free_extent_buffer(root->commit_root);
7258 kfree(root);
7259 }
79787eaa 7260out_end_trans:
3fd0a558 7261 btrfs_end_transaction_throttle(trans, tree_root);
79787eaa 7262out_free:
2c47e605 7263 kfree(wc);
5caf2a00 7264 btrfs_free_path(path);
cb1b69f4
TI
7265out:
7266 if (err)
7267 btrfs_std_error(root->fs_info, err);
2c536799 7268 return err;
20524f02 7269}
9078a3e1 7270
2c47e605
YZ
7271/*
7272 * drop subtree rooted at tree block 'node'.
7273 *
7274 * NOTE: this function will unlock and release tree block 'node'
66d7e7f0 7275 * only used by relocation code
2c47e605 7276 */
f82d02d9
YZ
7277int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7278 struct btrfs_root *root,
7279 struct extent_buffer *node,
7280 struct extent_buffer *parent)
7281{
7282 struct btrfs_path *path;
2c47e605 7283 struct walk_control *wc;
f82d02d9
YZ
7284 int level;
7285 int parent_level;
7286 int ret = 0;
7287 int wret;
7288
2c47e605
YZ
7289 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7290
f82d02d9 7291 path = btrfs_alloc_path();
db5b493a
TI
7292 if (!path)
7293 return -ENOMEM;
f82d02d9 7294
2c47e605 7295 wc = kzalloc(sizeof(*wc), GFP_NOFS);
db5b493a
TI
7296 if (!wc) {
7297 btrfs_free_path(path);
7298 return -ENOMEM;
7299 }
2c47e605 7300
b9447ef8 7301 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
7302 parent_level = btrfs_header_level(parent);
7303 extent_buffer_get(parent);
7304 path->nodes[parent_level] = parent;
7305 path->slots[parent_level] = btrfs_header_nritems(parent);
7306
b9447ef8 7307 btrfs_assert_tree_locked(node);
f82d02d9 7308 level = btrfs_header_level(node);
f82d02d9
YZ
7309 path->nodes[level] = node;
7310 path->slots[level] = 0;
bd681513 7311 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7312
7313 wc->refs[parent_level] = 1;
7314 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7315 wc->level = level;
7316 wc->shared_level = -1;
7317 wc->stage = DROP_REFERENCE;
7318 wc->update_ref = 0;
7319 wc->keep_locks = 1;
66d7e7f0 7320 wc->for_reloc = 1;
1c4850e2 7321 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
f82d02d9
YZ
7322
7323 while (1) {
2c47e605
YZ
7324 wret = walk_down_tree(trans, root, path, wc);
7325 if (wret < 0) {
f82d02d9 7326 ret = wret;
f82d02d9 7327 break;
2c47e605 7328 }
f82d02d9 7329
2c47e605 7330 wret = walk_up_tree(trans, root, path, wc, parent_level);
f82d02d9
YZ
7331 if (wret < 0)
7332 ret = wret;
7333 if (wret != 0)
7334 break;
7335 }
7336
2c47e605 7337 kfree(wc);
f82d02d9
YZ
7338 btrfs_free_path(path);
7339 return ret;
7340}
7341
ec44a35c
CM
7342static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7343{
7344 u64 num_devices;
fc67c450 7345 u64 stripped;
e4d8ec0f 7346
fc67c450
ID
7347 /*
7348 * if restripe for this chunk_type is on pick target profile and
7349 * return, otherwise do the usual balance
7350 */
7351 stripped = get_restripe_target(root->fs_info, flags);
7352 if (stripped)
7353 return extended_to_chunk(stripped);
e4d8ec0f 7354
cd02dca5
CM
7355 /*
7356 * we add in the count of missing devices because we want
7357 * to make sure that any RAID levels on a degraded FS
7358 * continue to be honored.
7359 */
7360 num_devices = root->fs_info->fs_devices->rw_devices +
7361 root->fs_info->fs_devices->missing_devices;
7362
fc67c450 7363 stripped = BTRFS_BLOCK_GROUP_RAID0 |
53b381b3 7364 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
fc67c450
ID
7365 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7366
ec44a35c
CM
7367 if (num_devices == 1) {
7368 stripped |= BTRFS_BLOCK_GROUP_DUP;
7369 stripped = flags & ~stripped;
7370
7371 /* turn raid0 into single device chunks */
7372 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7373 return stripped;
7374
7375 /* turn mirroring into duplication */
7376 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7377 BTRFS_BLOCK_GROUP_RAID10))
7378 return stripped | BTRFS_BLOCK_GROUP_DUP;
ec44a35c
CM
7379 } else {
7380 /* they already had raid on here, just return */
ec44a35c
CM
7381 if (flags & stripped)
7382 return flags;
7383
7384 stripped |= BTRFS_BLOCK_GROUP_DUP;
7385 stripped = flags & ~stripped;
7386
7387 /* switch duplicated blocks with raid1 */
7388 if (flags & BTRFS_BLOCK_GROUP_DUP)
7389 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7390
e3176ca2 7391 /* this is drive concat, leave it alone */
ec44a35c 7392 }
e3176ca2 7393
ec44a35c
CM
7394 return flags;
7395}
7396
199c36ea 7397static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
0ef3e66b 7398{
f0486c68
YZ
7399 struct btrfs_space_info *sinfo = cache->space_info;
7400 u64 num_bytes;
199c36ea 7401 u64 min_allocable_bytes;
f0486c68 7402 int ret = -ENOSPC;
0ef3e66b 7403
c286ac48 7404
199c36ea
MX
7405 /*
7406 * We need some metadata space and system metadata space for
7407 * allocating chunks in some corner cases until we force to set
7408 * it to be readonly.
7409 */
7410 if ((sinfo->flags &
7411 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7412 !force)
7413 min_allocable_bytes = 1 * 1024 * 1024;
7414 else
7415 min_allocable_bytes = 0;
7416
f0486c68
YZ
7417 spin_lock(&sinfo->lock);
7418 spin_lock(&cache->lock);
61cfea9b
W
7419
7420 if (cache->ro) {
7421 ret = 0;
7422 goto out;
7423 }
7424
f0486c68
YZ
7425 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7426 cache->bytes_super - btrfs_block_group_used(&cache->item);
7427
7428 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
37be25bc
JB
7429 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
7430 min_allocable_bytes <= sinfo->total_bytes) {
f0486c68 7431 sinfo->bytes_readonly += num_bytes;
f0486c68
YZ
7432 cache->ro = 1;
7433 ret = 0;
7434 }
61cfea9b 7435out:
f0486c68
YZ
7436 spin_unlock(&cache->lock);
7437 spin_unlock(&sinfo->lock);
7438 return ret;
7439}
7d9eb12c 7440
f0486c68
YZ
7441int btrfs_set_block_group_ro(struct btrfs_root *root,
7442 struct btrfs_block_group_cache *cache)
c286ac48 7443
f0486c68
YZ
7444{
7445 struct btrfs_trans_handle *trans;
7446 u64 alloc_flags;
7447 int ret;
7d9eb12c 7448
f0486c68 7449 BUG_ON(cache->ro);
0ef3e66b 7450
ff5714cc 7451 trans = btrfs_join_transaction(root);
79787eaa
JM
7452 if (IS_ERR(trans))
7453 return PTR_ERR(trans);
5d4f98a2 7454
f0486c68 7455 alloc_flags = update_block_group_flags(root, cache->flags);
79787eaa 7456 if (alloc_flags != cache->flags) {
698d0082 7457 ret = do_chunk_alloc(trans, root, alloc_flags,
79787eaa
JM
7458 CHUNK_ALLOC_FORCE);
7459 if (ret < 0)
7460 goto out;
7461 }
5d4f98a2 7462
199c36ea 7463 ret = set_block_group_ro(cache, 0);
f0486c68
YZ
7464 if (!ret)
7465 goto out;
7466 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
698d0082 7467 ret = do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 7468 CHUNK_ALLOC_FORCE);
f0486c68
YZ
7469 if (ret < 0)
7470 goto out;
199c36ea 7471 ret = set_block_group_ro(cache, 0);
f0486c68
YZ
7472out:
7473 btrfs_end_transaction(trans, root);
7474 return ret;
7475}
5d4f98a2 7476
c87f08ca
CM
7477int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
7478 struct btrfs_root *root, u64 type)
7479{
7480 u64 alloc_flags = get_alloc_profile(root, type);
698d0082 7481 return do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 7482 CHUNK_ALLOC_FORCE);
c87f08ca
CM
7483}
7484
6d07bcec
MX
7485/*
7486 * helper to account the unused space of all the readonly block group in the
7487 * list. takes mirrors into account.
7488 */
7489static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
7490{
7491 struct btrfs_block_group_cache *block_group;
7492 u64 free_bytes = 0;
7493 int factor;
7494
7495 list_for_each_entry(block_group, groups_list, list) {
7496 spin_lock(&block_group->lock);
7497
7498 if (!block_group->ro) {
7499 spin_unlock(&block_group->lock);
7500 continue;
7501 }
7502
7503 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
7504 BTRFS_BLOCK_GROUP_RAID10 |
7505 BTRFS_BLOCK_GROUP_DUP))
7506 factor = 2;
7507 else
7508 factor = 1;
7509
7510 free_bytes += (block_group->key.offset -
7511 btrfs_block_group_used(&block_group->item)) *
7512 factor;
7513
7514 spin_unlock(&block_group->lock);
7515 }
7516
7517 return free_bytes;
7518}
7519
7520/*
7521 * helper to account the unused space of all the readonly block group in the
7522 * space_info. takes mirrors into account.
7523 */
7524u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7525{
7526 int i;
7527 u64 free_bytes = 0;
7528
7529 spin_lock(&sinfo->lock);
7530
7531 for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
7532 if (!list_empty(&sinfo->block_groups[i]))
7533 free_bytes += __btrfs_get_ro_block_group_free_space(
7534 &sinfo->block_groups[i]);
7535
7536 spin_unlock(&sinfo->lock);
7537
7538 return free_bytes;
7539}
7540
143bede5 7541void btrfs_set_block_group_rw(struct btrfs_root *root,
f0486c68 7542 struct btrfs_block_group_cache *cache)
5d4f98a2 7543{
f0486c68
YZ
7544 struct btrfs_space_info *sinfo = cache->space_info;
7545 u64 num_bytes;
7546
7547 BUG_ON(!cache->ro);
7548
7549 spin_lock(&sinfo->lock);
7550 spin_lock(&cache->lock);
7551 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7552 cache->bytes_super - btrfs_block_group_used(&cache->item);
7553 sinfo->bytes_readonly -= num_bytes;
7554 cache->ro = 0;
7555 spin_unlock(&cache->lock);
7556 spin_unlock(&sinfo->lock);
5d4f98a2
YZ
7557}
7558
ba1bf481
JB
7559/*
7560 * checks to see if its even possible to relocate this block group.
7561 *
7562 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7563 * ok to go ahead and try.
7564 */
7565int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
1a40e23b 7566{
ba1bf481
JB
7567 struct btrfs_block_group_cache *block_group;
7568 struct btrfs_space_info *space_info;
7569 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7570 struct btrfs_device *device;
cdcb725c 7571 u64 min_free;
6719db6a
JB
7572 u64 dev_min = 1;
7573 u64 dev_nr = 0;
4a5e98f5 7574 u64 target;
cdcb725c 7575 int index;
ba1bf481
JB
7576 int full = 0;
7577 int ret = 0;
1a40e23b 7578
ba1bf481 7579 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1a40e23b 7580
ba1bf481
JB
7581 /* odd, couldn't find the block group, leave it alone */
7582 if (!block_group)
7583 return -1;
1a40e23b 7584
cdcb725c 7585 min_free = btrfs_block_group_used(&block_group->item);
7586
ba1bf481 7587 /* no bytes used, we're good */
cdcb725c 7588 if (!min_free)
1a40e23b
ZY
7589 goto out;
7590
ba1bf481
JB
7591 space_info = block_group->space_info;
7592 spin_lock(&space_info->lock);
17d217fe 7593
ba1bf481 7594 full = space_info->full;
17d217fe 7595
ba1bf481
JB
7596 /*
7597 * if this is the last block group we have in this space, we can't
7ce618db
CM
7598 * relocate it unless we're able to allocate a new chunk below.
7599 *
7600 * Otherwise, we need to make sure we have room in the space to handle
7601 * all of the extents from this block group. If we can, we're good
ba1bf481 7602 */
7ce618db 7603 if ((space_info->total_bytes != block_group->key.offset) &&
cdcb725c 7604 (space_info->bytes_used + space_info->bytes_reserved +
7605 space_info->bytes_pinned + space_info->bytes_readonly +
7606 min_free < space_info->total_bytes)) {
ba1bf481
JB
7607 spin_unlock(&space_info->lock);
7608 goto out;
17d217fe 7609 }
ba1bf481 7610 spin_unlock(&space_info->lock);
ea8c2819 7611
ba1bf481
JB
7612 /*
7613 * ok we don't have enough space, but maybe we have free space on our
7614 * devices to allocate new chunks for relocation, so loop through our
4a5e98f5
ID
7615 * alloc devices and guess if we have enough space. if this block
7616 * group is going to be restriped, run checks against the target
7617 * profile instead of the current one.
ba1bf481
JB
7618 */
7619 ret = -1;
ea8c2819 7620
cdcb725c 7621 /*
7622 * index:
7623 * 0: raid10
7624 * 1: raid1
7625 * 2: dup
7626 * 3: raid0
7627 * 4: single
7628 */
4a5e98f5
ID
7629 target = get_restripe_target(root->fs_info, block_group->flags);
7630 if (target) {
31e50229 7631 index = __get_raid_index(extended_to_chunk(target));
4a5e98f5
ID
7632 } else {
7633 /*
7634 * this is just a balance, so if we were marked as full
7635 * we know there is no space for a new chunk
7636 */
7637 if (full)
7638 goto out;
7639
7640 index = get_block_group_index(block_group);
7641 }
7642
e6ec716f 7643 if (index == BTRFS_RAID_RAID10) {
cdcb725c 7644 dev_min = 4;
6719db6a
JB
7645 /* Divide by 2 */
7646 min_free >>= 1;
e6ec716f 7647 } else if (index == BTRFS_RAID_RAID1) {
cdcb725c 7648 dev_min = 2;
e6ec716f 7649 } else if (index == BTRFS_RAID_DUP) {
6719db6a
JB
7650 /* Multiply by 2 */
7651 min_free <<= 1;
e6ec716f 7652 } else if (index == BTRFS_RAID_RAID0) {
cdcb725c 7653 dev_min = fs_devices->rw_devices;
6719db6a 7654 do_div(min_free, dev_min);
cdcb725c 7655 }
7656
ba1bf481
JB
7657 mutex_lock(&root->fs_info->chunk_mutex);
7658 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7bfc837d 7659 u64 dev_offset;
56bec294 7660
ba1bf481
JB
7661 /*
7662 * check to make sure we can actually find a chunk with enough
7663 * space to fit our block group in.
7664 */
63a212ab
SB
7665 if (device->total_bytes > device->bytes_used + min_free &&
7666 !device->is_tgtdev_for_dev_replace) {
125ccb0a 7667 ret = find_free_dev_extent(device, min_free,
7bfc837d 7668 &dev_offset, NULL);
ba1bf481 7669 if (!ret)
cdcb725c 7670 dev_nr++;
7671
7672 if (dev_nr >= dev_min)
73e48b27 7673 break;
cdcb725c 7674
ba1bf481 7675 ret = -1;
725c8463 7676 }
edbd8d4e 7677 }
ba1bf481 7678 mutex_unlock(&root->fs_info->chunk_mutex);
edbd8d4e 7679out:
ba1bf481 7680 btrfs_put_block_group(block_group);
edbd8d4e
CM
7681 return ret;
7682}
7683
b2950863
CH
7684static int find_first_block_group(struct btrfs_root *root,
7685 struct btrfs_path *path, struct btrfs_key *key)
0b86a832 7686{
925baedd 7687 int ret = 0;
0b86a832
CM
7688 struct btrfs_key found_key;
7689 struct extent_buffer *leaf;
7690 int slot;
edbd8d4e 7691
0b86a832
CM
7692 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7693 if (ret < 0)
925baedd
CM
7694 goto out;
7695
d397712b 7696 while (1) {
0b86a832 7697 slot = path->slots[0];
edbd8d4e 7698 leaf = path->nodes[0];
0b86a832
CM
7699 if (slot >= btrfs_header_nritems(leaf)) {
7700 ret = btrfs_next_leaf(root, path);
7701 if (ret == 0)
7702 continue;
7703 if (ret < 0)
925baedd 7704 goto out;
0b86a832 7705 break;
edbd8d4e 7706 }
0b86a832 7707 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 7708
0b86a832 7709 if (found_key.objectid >= key->objectid &&
925baedd
CM
7710 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7711 ret = 0;
7712 goto out;
7713 }
0b86a832 7714 path->slots[0]++;
edbd8d4e 7715 }
925baedd 7716out:
0b86a832 7717 return ret;
edbd8d4e
CM
7718}
7719
0af3d00b
JB
7720void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
7721{
7722 struct btrfs_block_group_cache *block_group;
7723 u64 last = 0;
7724
7725 while (1) {
7726 struct inode *inode;
7727
7728 block_group = btrfs_lookup_first_block_group(info, last);
7729 while (block_group) {
7730 spin_lock(&block_group->lock);
7731 if (block_group->iref)
7732 break;
7733 spin_unlock(&block_group->lock);
7734 block_group = next_block_group(info->tree_root,
7735 block_group);
7736 }
7737 if (!block_group) {
7738 if (last == 0)
7739 break;
7740 last = 0;
7741 continue;
7742 }
7743
7744 inode = block_group->inode;
7745 block_group->iref = 0;
7746 block_group->inode = NULL;
7747 spin_unlock(&block_group->lock);
7748 iput(inode);
7749 last = block_group->key.objectid + block_group->key.offset;
7750 btrfs_put_block_group(block_group);
7751 }
7752}
7753
1a40e23b
ZY
7754int btrfs_free_block_groups(struct btrfs_fs_info *info)
7755{
7756 struct btrfs_block_group_cache *block_group;
4184ea7f 7757 struct btrfs_space_info *space_info;
11833d66 7758 struct btrfs_caching_control *caching_ctl;
1a40e23b
ZY
7759 struct rb_node *n;
7760
11833d66
YZ
7761 down_write(&info->extent_commit_sem);
7762 while (!list_empty(&info->caching_block_groups)) {
7763 caching_ctl = list_entry(info->caching_block_groups.next,
7764 struct btrfs_caching_control, list);
7765 list_del(&caching_ctl->list);
7766 put_caching_control(caching_ctl);
7767 }
7768 up_write(&info->extent_commit_sem);
7769
1a40e23b
ZY
7770 spin_lock(&info->block_group_cache_lock);
7771 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7772 block_group = rb_entry(n, struct btrfs_block_group_cache,
7773 cache_node);
1a40e23b
ZY
7774 rb_erase(&block_group->cache_node,
7775 &info->block_group_cache_tree);
d899e052
YZ
7776 spin_unlock(&info->block_group_cache_lock);
7777
80eb234a 7778 down_write(&block_group->space_info->groups_sem);
1a40e23b 7779 list_del(&block_group->list);
80eb234a 7780 up_write(&block_group->space_info->groups_sem);
d2fb3437 7781
817d52f8 7782 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 7783 wait_block_group_cache_done(block_group);
817d52f8 7784
3c14874a
JB
7785 /*
7786 * We haven't cached this block group, which means we could
7787 * possibly have excluded extents on this block group.
7788 */
7789 if (block_group->cached == BTRFS_CACHE_NO)
7790 free_excluded_extents(info->extent_root, block_group);
7791
817d52f8 7792 btrfs_remove_free_space_cache(block_group);
11dfe35a 7793 btrfs_put_block_group(block_group);
d899e052
YZ
7794
7795 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
7796 }
7797 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
7798
7799 /* now that all the block groups are freed, go through and
7800 * free all the space_info structs. This is only called during
7801 * the final stages of unmount, and so we know nobody is
7802 * using them. We call synchronize_rcu() once before we start,
7803 * just to be on the safe side.
7804 */
7805 synchronize_rcu();
7806
8929ecfa
YZ
7807 release_global_block_rsv(info);
7808
4184ea7f
CM
7809 while(!list_empty(&info->space_info)) {
7810 space_info = list_entry(info->space_info.next,
7811 struct btrfs_space_info,
7812 list);
b069e0c3
DS
7813 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
7814 if (space_info->bytes_pinned > 0 ||
7815 space_info->bytes_reserved > 0 ||
7816 space_info->bytes_may_use > 0) {
7817 WARN_ON(1);
7818 dump_space_info(space_info, 0, 0);
7819 }
f0486c68 7820 }
4184ea7f
CM
7821 list_del(&space_info->list);
7822 kfree(space_info);
7823 }
1a40e23b
ZY
7824 return 0;
7825}
7826
b742bb82
YZ
7827static void __link_block_group(struct btrfs_space_info *space_info,
7828 struct btrfs_block_group_cache *cache)
7829{
7830 int index = get_block_group_index(cache);
7831
7832 down_write(&space_info->groups_sem);
7833 list_add_tail(&cache->list, &space_info->block_groups[index]);
7834 up_write(&space_info->groups_sem);
7835}
7836
9078a3e1
CM
7837int btrfs_read_block_groups(struct btrfs_root *root)
7838{
7839 struct btrfs_path *path;
7840 int ret;
9078a3e1 7841 struct btrfs_block_group_cache *cache;
be744175 7842 struct btrfs_fs_info *info = root->fs_info;
6324fbf3 7843 struct btrfs_space_info *space_info;
9078a3e1
CM
7844 struct btrfs_key key;
7845 struct btrfs_key found_key;
5f39d397 7846 struct extent_buffer *leaf;
0af3d00b
JB
7847 int need_clear = 0;
7848 u64 cache_gen;
96b5179d 7849
be744175 7850 root = info->extent_root;
9078a3e1 7851 key.objectid = 0;
0b86a832 7852 key.offset = 0;
9078a3e1 7853 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
9078a3e1
CM
7854 path = btrfs_alloc_path();
7855 if (!path)
7856 return -ENOMEM;
026fd317 7857 path->reada = 1;
9078a3e1 7858
6c41761f 7859 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
73bc1876 7860 if (btrfs_test_opt(root, SPACE_CACHE) &&
6c41761f 7861 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
0af3d00b 7862 need_clear = 1;
88c2ba3b
JB
7863 if (btrfs_test_opt(root, CLEAR_CACHE))
7864 need_clear = 1;
0af3d00b 7865
d397712b 7866 while (1) {
0b86a832 7867 ret = find_first_block_group(root, path, &key);
b742bb82
YZ
7868 if (ret > 0)
7869 break;
0b86a832
CM
7870 if (ret != 0)
7871 goto error;
5f39d397
CM
7872 leaf = path->nodes[0];
7873 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8f18cf13 7874 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9078a3e1 7875 if (!cache) {
0b86a832 7876 ret = -ENOMEM;
f0486c68 7877 goto error;
9078a3e1 7878 }
34d52cb6
LZ
7879 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7880 GFP_NOFS);
7881 if (!cache->free_space_ctl) {
7882 kfree(cache);
7883 ret = -ENOMEM;
7884 goto error;
7885 }
3e1ad54f 7886
d2fb3437 7887 atomic_set(&cache->count, 1);
c286ac48 7888 spin_lock_init(&cache->lock);
817d52f8 7889 cache->fs_info = info;
0f9dd46c 7890 INIT_LIST_HEAD(&cache->list);
fa9c0d79 7891 INIT_LIST_HEAD(&cache->cluster_list);
96303081 7892
cf7c1ef6
LB
7893 if (need_clear) {
7894 /*
7895 * When we mount with old space cache, we need to
7896 * set BTRFS_DC_CLEAR and set dirty flag.
7897 *
7898 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
7899 * truncate the old free space cache inode and
7900 * setup a new one.
7901 * b) Setting 'dirty flag' makes sure that we flush
7902 * the new space cache info onto disk.
7903 */
0af3d00b 7904 cache->disk_cache_state = BTRFS_DC_CLEAR;
cf7c1ef6
LB
7905 if (btrfs_test_opt(root, SPACE_CACHE))
7906 cache->dirty = 1;
7907 }
0af3d00b 7908
5f39d397
CM
7909 read_extent_buffer(leaf, &cache->item,
7910 btrfs_item_ptr_offset(leaf, path->slots[0]),
7911 sizeof(cache->item));
9078a3e1 7912 memcpy(&cache->key, &found_key, sizeof(found_key));
0b86a832 7913
9078a3e1 7914 key.objectid = found_key.objectid + found_key.offset;
b3b4aa74 7915 btrfs_release_path(path);
0b86a832 7916 cache->flags = btrfs_block_group_flags(&cache->item);
817d52f8 7917 cache->sectorsize = root->sectorsize;
53b381b3
DW
7918 cache->full_stripe_len = btrfs_full_stripe_len(root,
7919 &root->fs_info->mapping_tree,
7920 found_key.objectid);
34d52cb6
LZ
7921 btrfs_init_free_space_ctl(cache);
7922
3c14874a
JB
7923 /*
7924 * We need to exclude the super stripes now so that the space
7925 * info has super bytes accounted for, otherwise we'll think
7926 * we have more space than we actually do.
7927 */
7928 exclude_super_stripes(root, cache);
7929
817d52f8
JB
7930 /*
7931 * check for two cases, either we are full, and therefore
7932 * don't need to bother with the caching work since we won't
7933 * find any space, or we are empty, and we can just add all
7934 * the space in and be done with it. This saves us _alot_ of
7935 * time, particularly in the full case.
7936 */
7937 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
11833d66 7938 cache->last_byte_to_unpin = (u64)-1;
817d52f8 7939 cache->cached = BTRFS_CACHE_FINISHED;
1b2da372 7940 free_excluded_extents(root, cache);
817d52f8 7941 } else if (btrfs_block_group_used(&cache->item) == 0) {
11833d66 7942 cache->last_byte_to_unpin = (u64)-1;
817d52f8
JB
7943 cache->cached = BTRFS_CACHE_FINISHED;
7944 add_new_free_space(cache, root->fs_info,
7945 found_key.objectid,
7946 found_key.objectid +
7947 found_key.offset);
11833d66 7948 free_excluded_extents(root, cache);
817d52f8 7949 }
96b5179d 7950
6324fbf3
CM
7951 ret = update_space_info(info, cache->flags, found_key.offset,
7952 btrfs_block_group_used(&cache->item),
7953 &space_info);
79787eaa 7954 BUG_ON(ret); /* -ENOMEM */
6324fbf3 7955 cache->space_info = space_info;
1b2da372 7956 spin_lock(&cache->space_info->lock);
f0486c68 7957 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
7958 spin_unlock(&cache->space_info->lock);
7959
b742bb82 7960 __link_block_group(space_info, cache);
0f9dd46c
JB
7961
7962 ret = btrfs_add_block_group_cache(root->fs_info, cache);
79787eaa 7963 BUG_ON(ret); /* Logic error */
75ccf47d
CM
7964
7965 set_avail_alloc_bits(root->fs_info, cache->flags);
2b82032c 7966 if (btrfs_chunk_readonly(root, cache->key.objectid))
199c36ea 7967 set_block_group_ro(cache, 1);
9078a3e1 7968 }
b742bb82
YZ
7969
7970 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
7971 if (!(get_alloc_profile(root, space_info->flags) &
7972 (BTRFS_BLOCK_GROUP_RAID10 |
7973 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
7974 BTRFS_BLOCK_GROUP_RAID5 |
7975 BTRFS_BLOCK_GROUP_RAID6 |
b742bb82
YZ
7976 BTRFS_BLOCK_GROUP_DUP)))
7977 continue;
7978 /*
7979 * avoid allocating from un-mirrored block group if there are
7980 * mirrored block groups.
7981 */
7982 list_for_each_entry(cache, &space_info->block_groups[3], list)
199c36ea 7983 set_block_group_ro(cache, 1);
b742bb82 7984 list_for_each_entry(cache, &space_info->block_groups[4], list)
199c36ea 7985 set_block_group_ro(cache, 1);
9078a3e1 7986 }
f0486c68
YZ
7987
7988 init_global_block_rsv(info);
0b86a832
CM
7989 ret = 0;
7990error:
9078a3e1 7991 btrfs_free_path(path);
0b86a832 7992 return ret;
9078a3e1 7993}
6324fbf3 7994
ea658bad
JB
7995void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
7996 struct btrfs_root *root)
7997{
7998 struct btrfs_block_group_cache *block_group, *tmp;
7999 struct btrfs_root *extent_root = root->fs_info->extent_root;
8000 struct btrfs_block_group_item item;
8001 struct btrfs_key key;
8002 int ret = 0;
8003
8004 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
8005 new_bg_list) {
8006 list_del_init(&block_group->new_bg_list);
8007
8008 if (ret)
8009 continue;
8010
8011 spin_lock(&block_group->lock);
8012 memcpy(&item, &block_group->item, sizeof(item));
8013 memcpy(&key, &block_group->key, sizeof(key));
8014 spin_unlock(&block_group->lock);
8015
8016 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8017 sizeof(item));
8018 if (ret)
8019 btrfs_abort_transaction(trans, extent_root, ret);
8020 }
8021}
8022
6324fbf3
CM
8023int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8024 struct btrfs_root *root, u64 bytes_used,
e17cade2 8025 u64 type, u64 chunk_objectid, u64 chunk_offset,
6324fbf3
CM
8026 u64 size)
8027{
8028 int ret;
6324fbf3
CM
8029 struct btrfs_root *extent_root;
8030 struct btrfs_block_group_cache *cache;
6324fbf3
CM
8031
8032 extent_root = root->fs_info->extent_root;
6324fbf3 8033
12fcfd22 8034 root->fs_info->last_trans_log_full_commit = trans->transid;
e02119d5 8035
8f18cf13 8036 cache = kzalloc(sizeof(*cache), GFP_NOFS);
0f9dd46c
JB
8037 if (!cache)
8038 return -ENOMEM;
34d52cb6
LZ
8039 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8040 GFP_NOFS);
8041 if (!cache->free_space_ctl) {
8042 kfree(cache);
8043 return -ENOMEM;
8044 }
0f9dd46c 8045
e17cade2 8046 cache->key.objectid = chunk_offset;
6324fbf3 8047 cache->key.offset = size;
d2fb3437 8048 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
96303081 8049 cache->sectorsize = root->sectorsize;
0af3d00b 8050 cache->fs_info = root->fs_info;
53b381b3
DW
8051 cache->full_stripe_len = btrfs_full_stripe_len(root,
8052 &root->fs_info->mapping_tree,
8053 chunk_offset);
96303081 8054
d2fb3437 8055 atomic_set(&cache->count, 1);
c286ac48 8056 spin_lock_init(&cache->lock);
0f9dd46c 8057 INIT_LIST_HEAD(&cache->list);
fa9c0d79 8058 INIT_LIST_HEAD(&cache->cluster_list);
ea658bad 8059 INIT_LIST_HEAD(&cache->new_bg_list);
0ef3e66b 8060
34d52cb6
LZ
8061 btrfs_init_free_space_ctl(cache);
8062
6324fbf3 8063 btrfs_set_block_group_used(&cache->item, bytes_used);
6324fbf3
CM
8064 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8065 cache->flags = type;
8066 btrfs_set_block_group_flags(&cache->item, type);
8067
11833d66 8068 cache->last_byte_to_unpin = (u64)-1;
817d52f8 8069 cache->cached = BTRFS_CACHE_FINISHED;
11833d66 8070 exclude_super_stripes(root, cache);
96303081 8071
817d52f8
JB
8072 add_new_free_space(cache, root->fs_info, chunk_offset,
8073 chunk_offset + size);
8074
11833d66
YZ
8075 free_excluded_extents(root, cache);
8076
6324fbf3
CM
8077 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8078 &cache->space_info);
79787eaa 8079 BUG_ON(ret); /* -ENOMEM */
c7c144db 8080 update_global_block_rsv(root->fs_info);
1b2da372
JB
8081
8082 spin_lock(&cache->space_info->lock);
f0486c68 8083 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
8084 spin_unlock(&cache->space_info->lock);
8085
b742bb82 8086 __link_block_group(cache->space_info, cache);
6324fbf3 8087
0f9dd46c 8088 ret = btrfs_add_block_group_cache(root->fs_info, cache);
79787eaa 8089 BUG_ON(ret); /* Logic error */
c286ac48 8090
ea658bad 8091 list_add_tail(&cache->new_bg_list, &trans->new_bgs);
6324fbf3 8092
d18a2c44 8093 set_avail_alloc_bits(extent_root->fs_info, type);
925baedd 8094
6324fbf3
CM
8095 return 0;
8096}
1a40e23b 8097
10ea00f5
ID
8098static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8099{
899c81ea
ID
8100 u64 extra_flags = chunk_to_extended(flags) &
8101 BTRFS_EXTENDED_PROFILE_MASK;
10ea00f5 8102
de98ced9 8103 write_seqlock(&fs_info->profiles_lock);
10ea00f5
ID
8104 if (flags & BTRFS_BLOCK_GROUP_DATA)
8105 fs_info->avail_data_alloc_bits &= ~extra_flags;
8106 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8107 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8108 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8109 fs_info->avail_system_alloc_bits &= ~extra_flags;
de98ced9 8110 write_sequnlock(&fs_info->profiles_lock);
10ea00f5
ID
8111}
8112
1a40e23b
ZY
8113int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8114 struct btrfs_root *root, u64 group_start)
8115{
8116 struct btrfs_path *path;
8117 struct btrfs_block_group_cache *block_group;
44fb5511 8118 struct btrfs_free_cluster *cluster;
0af3d00b 8119 struct btrfs_root *tree_root = root->fs_info->tree_root;
1a40e23b 8120 struct btrfs_key key;
0af3d00b 8121 struct inode *inode;
1a40e23b 8122 int ret;
10ea00f5 8123 int index;
89a55897 8124 int factor;
1a40e23b 8125
1a40e23b
ZY
8126 root = root->fs_info->extent_root;
8127
8128 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8129 BUG_ON(!block_group);
c146afad 8130 BUG_ON(!block_group->ro);
1a40e23b 8131
9f7c43c9 8132 /*
8133 * Free the reserved super bytes from this block group before
8134 * remove it.
8135 */
8136 free_excluded_extents(root, block_group);
8137
1a40e23b 8138 memcpy(&key, &block_group->key, sizeof(key));
10ea00f5 8139 index = get_block_group_index(block_group);
89a55897
JB
8140 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8141 BTRFS_BLOCK_GROUP_RAID1 |
8142 BTRFS_BLOCK_GROUP_RAID10))
8143 factor = 2;
8144 else
8145 factor = 1;
1a40e23b 8146
44fb5511
CM
8147 /* make sure this block group isn't part of an allocation cluster */
8148 cluster = &root->fs_info->data_alloc_cluster;
8149 spin_lock(&cluster->refill_lock);
8150 btrfs_return_cluster_to_free_space(block_group, cluster);
8151 spin_unlock(&cluster->refill_lock);
8152
8153 /*
8154 * make sure this block group isn't part of a metadata
8155 * allocation cluster
8156 */
8157 cluster = &root->fs_info->meta_alloc_cluster;
8158 spin_lock(&cluster->refill_lock);
8159 btrfs_return_cluster_to_free_space(block_group, cluster);
8160 spin_unlock(&cluster->refill_lock);
8161
1a40e23b 8162 path = btrfs_alloc_path();
d8926bb3
MF
8163 if (!path) {
8164 ret = -ENOMEM;
8165 goto out;
8166 }
1a40e23b 8167
10b2f34d 8168 inode = lookup_free_space_inode(tree_root, block_group, path);
0af3d00b 8169 if (!IS_ERR(inode)) {
b532402e 8170 ret = btrfs_orphan_add(trans, inode);
79787eaa
JM
8171 if (ret) {
8172 btrfs_add_delayed_iput(inode);
8173 goto out;
8174 }
0af3d00b
JB
8175 clear_nlink(inode);
8176 /* One for the block groups ref */
8177 spin_lock(&block_group->lock);
8178 if (block_group->iref) {
8179 block_group->iref = 0;
8180 block_group->inode = NULL;
8181 spin_unlock(&block_group->lock);
8182 iput(inode);
8183 } else {
8184 spin_unlock(&block_group->lock);
8185 }
8186 /* One for our lookup ref */
455757c3 8187 btrfs_add_delayed_iput(inode);
0af3d00b
JB
8188 }
8189
8190 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8191 key.offset = block_group->key.objectid;
8192 key.type = 0;
8193
8194 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8195 if (ret < 0)
8196 goto out;
8197 if (ret > 0)
b3b4aa74 8198 btrfs_release_path(path);
0af3d00b
JB
8199 if (ret == 0) {
8200 ret = btrfs_del_item(trans, tree_root, path);
8201 if (ret)
8202 goto out;
b3b4aa74 8203 btrfs_release_path(path);
0af3d00b
JB
8204 }
8205
3dfdb934 8206 spin_lock(&root->fs_info->block_group_cache_lock);
1a40e23b
ZY
8207 rb_erase(&block_group->cache_node,
8208 &root->fs_info->block_group_cache_tree);
a1897fdd
LB
8209
8210 if (root->fs_info->first_logical_byte == block_group->key.objectid)
8211 root->fs_info->first_logical_byte = (u64)-1;
3dfdb934 8212 spin_unlock(&root->fs_info->block_group_cache_lock);
817d52f8 8213
80eb234a 8214 down_write(&block_group->space_info->groups_sem);
44fb5511
CM
8215 /*
8216 * we must use list_del_init so people can check to see if they
8217 * are still on the list after taking the semaphore
8218 */
8219 list_del_init(&block_group->list);
10ea00f5
ID
8220 if (list_empty(&block_group->space_info->block_groups[index]))
8221 clear_avail_alloc_bits(root->fs_info, block_group->flags);
80eb234a 8222 up_write(&block_group->space_info->groups_sem);
1a40e23b 8223
817d52f8 8224 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 8225 wait_block_group_cache_done(block_group);
817d52f8
JB
8226
8227 btrfs_remove_free_space_cache(block_group);
8228
c146afad
YZ
8229 spin_lock(&block_group->space_info->lock);
8230 block_group->space_info->total_bytes -= block_group->key.offset;
8231 block_group->space_info->bytes_readonly -= block_group->key.offset;
89a55897 8232 block_group->space_info->disk_total -= block_group->key.offset * factor;
c146afad 8233 spin_unlock(&block_group->space_info->lock);
283bb197 8234
0af3d00b
JB
8235 memcpy(&key, &block_group->key, sizeof(key));
8236
283bb197 8237 btrfs_clear_space_info_full(root->fs_info);
c146afad 8238
fa9c0d79
CM
8239 btrfs_put_block_group(block_group);
8240 btrfs_put_block_group(block_group);
1a40e23b
ZY
8241
8242 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8243 if (ret > 0)
8244 ret = -EIO;
8245 if (ret < 0)
8246 goto out;
8247
8248 ret = btrfs_del_item(trans, root, path);
8249out:
8250 btrfs_free_path(path);
8251 return ret;
8252}
acce952b 8253
c59021f8 8254int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8255{
8256 struct btrfs_space_info *space_info;
1aba86d6 8257 struct btrfs_super_block *disk_super;
8258 u64 features;
8259 u64 flags;
8260 int mixed = 0;
c59021f8 8261 int ret;
8262
6c41761f 8263 disk_super = fs_info->super_copy;
1aba86d6 8264 if (!btrfs_super_root(disk_super))
8265 return 1;
c59021f8 8266
1aba86d6 8267 features = btrfs_super_incompat_flags(disk_super);
8268 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
8269 mixed = 1;
c59021f8 8270
1aba86d6 8271 flags = BTRFS_BLOCK_GROUP_SYSTEM;
8272 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
c59021f8 8273 if (ret)
1aba86d6 8274 goto out;
c59021f8 8275
1aba86d6 8276 if (mixed) {
8277 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
8278 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8279 } else {
8280 flags = BTRFS_BLOCK_GROUP_METADATA;
8281 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8282 if (ret)
8283 goto out;
8284
8285 flags = BTRFS_BLOCK_GROUP_DATA;
8286 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8287 }
8288out:
c59021f8 8289 return ret;
8290}
8291
acce952b 8292int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
8293{
8294 return unpin_extent_range(root, start, end);
8295}
8296
8297int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
5378e607 8298 u64 num_bytes, u64 *actual_bytes)
acce952b 8299{
5378e607 8300 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
acce952b 8301}
f7039b1d
LD
8302
8303int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
8304{
8305 struct btrfs_fs_info *fs_info = root->fs_info;
8306 struct btrfs_block_group_cache *cache = NULL;
8307 u64 group_trimmed;
8308 u64 start;
8309 u64 end;
8310 u64 trimmed = 0;
2cac13e4 8311 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
f7039b1d
LD
8312 int ret = 0;
8313
2cac13e4
LB
8314 /*
8315 * try to trim all FS space, our block group may start from non-zero.
8316 */
8317 if (range->len == total_bytes)
8318 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8319 else
8320 cache = btrfs_lookup_block_group(fs_info, range->start);
f7039b1d
LD
8321
8322 while (cache) {
8323 if (cache->key.objectid >= (range->start + range->len)) {
8324 btrfs_put_block_group(cache);
8325 break;
8326 }
8327
8328 start = max(range->start, cache->key.objectid);
8329 end = min(range->start + range->len,
8330 cache->key.objectid + cache->key.offset);
8331
8332 if (end - start >= range->minlen) {
8333 if (!block_group_cache_done(cache)) {
f6373bf3 8334 ret = cache_block_group(cache, 0);
f7039b1d
LD
8335 if (!ret)
8336 wait_block_group_cache_done(cache);
8337 }
8338 ret = btrfs_trim_block_group(cache,
8339 &group_trimmed,
8340 start,
8341 end,
8342 range->minlen);
8343
8344 trimmed += group_trimmed;
8345 if (ret) {
8346 btrfs_put_block_group(cache);
8347 break;
8348 }
8349 }
8350
8351 cache = next_block_group(fs_info->tree_root, cache);
8352 }
8353
8354 range->len = trimmed;
8355 return ret;
8356}
This page took 0.968345 seconds and 5 git commands to generate.