]> git.ipfire.org Git - people/arne_f/kernel.git/blame - fs/btrfs/extent-tree.c
btrfs: require only sector size alignment for parent eb bytenr
[people/arne_f/kernel.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>
f361bf4a 19#include <linux/sched/signal.h>
edbd8d4e 20#include <linux/pagemap.h>
ec44a35c 21#include <linux/writeback.h>
21af804c 22#include <linux/blkdev.h>
b7a9f29f 23#include <linux/sort.h>
4184ea7f 24#include <linux/rcupdate.h>
817d52f8 25#include <linux/kthread.h>
5a0e3ad6 26#include <linux/slab.h>
dff51cd1 27#include <linux/ratelimit.h>
b150a4f1 28#include <linux/percpu_counter.h>
74493f7a 29#include "hash.h"
995946dd 30#include "tree-log.h"
fec577fb
CM
31#include "disk-io.h"
32#include "print-tree.h"
0b86a832 33#include "volumes.h"
53b381b3 34#include "raid56.h"
925baedd 35#include "locking.h"
fa9c0d79 36#include "free-space-cache.h"
1e144fb8 37#include "free-space-tree.h"
3fed40cc 38#include "math.h"
6ab0a202 39#include "sysfs.h"
fcebe456 40#include "qgroup.h"
fec577fb 41
709c0486
AJ
42#undef SCRAMBLE_DELAYED_REFS
43
9e622d6b
MX
44/*
45 * control flags for do_chunk_alloc's force field
0e4f8f88
CM
46 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
47 * if we really need one.
48 *
0e4f8f88
CM
49 * CHUNK_ALLOC_LIMITED means to only try and allocate one
50 * if we have very few chunks already allocated. This is
51 * used as part of the clustering code to help make sure
52 * we have a good pool of storage to cluster in, without
53 * filling the FS with empty chunks
54 *
9e622d6b
MX
55 * CHUNK_ALLOC_FORCE means it must try to allocate one
56 *
0e4f8f88
CM
57 */
58enum {
59 CHUNK_ALLOC_NO_FORCE = 0,
9e622d6b
MX
60 CHUNK_ALLOC_LIMITED = 1,
61 CHUNK_ALLOC_FORCE = 2,
0e4f8f88
CM
62};
63
ce93ec54 64static int update_block_group(struct btrfs_trans_handle *trans,
6202df69 65 struct btrfs_fs_info *fs_info, u64 bytenr,
ce93ec54 66 u64 num_bytes, int alloc);
5d4f98a2 67static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2ff7e61e 68 struct btrfs_fs_info *fs_info,
c682f9b3 69 struct btrfs_delayed_ref_node *node, u64 parent,
5d4f98a2
YZ
70 u64 root_objectid, u64 owner_objectid,
71 u64 owner_offset, int refs_to_drop,
c682f9b3 72 struct btrfs_delayed_extent_op *extra_op);
5d4f98a2
YZ
73static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
74 struct extent_buffer *leaf,
75 struct btrfs_extent_item *ei);
76static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
2ff7e61e 77 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
78 u64 parent, u64 root_objectid,
79 u64 flags, u64 owner, u64 offset,
80 struct btrfs_key *ins, int ref_mod);
81static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
2ff7e61e 82 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
83 u64 parent, u64 root_objectid,
84 u64 flags, struct btrfs_disk_key *key,
b06c4bf5 85 int level, struct btrfs_key *ins);
6a63209f 86static int do_chunk_alloc(struct btrfs_trans_handle *trans,
2ff7e61e 87 struct btrfs_fs_info *fs_info, u64 flags,
698d0082 88 int force);
11833d66
YZ
89static int find_next_key(struct btrfs_path *path, int level,
90 struct btrfs_key *key);
ab8d0fc4
JM
91static void dump_space_info(struct btrfs_fs_info *fs_info,
92 struct btrfs_space_info *info, u64 bytes,
9ed74f2d 93 int dump_block_groups);
4824f1f4 94static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
18513091 95 u64 ram_bytes, u64 num_bytes, int delalloc);
4824f1f4
WX
96static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
97 u64 num_bytes, int delalloc);
5d80366e
JB
98static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
99 u64 num_bytes);
c1c4919b 100static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
957780eb
JB
101 struct btrfs_space_info *space_info,
102 u64 orig_bytes,
c1c4919b
JM
103 enum btrfs_reserve_flush_enum flush,
104 bool system_chunk);
957780eb
JB
105static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
106 struct btrfs_space_info *space_info,
107 u64 num_bytes);
108static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
109 struct btrfs_space_info *space_info,
110 u64 num_bytes);
6a63209f 111
817d52f8
JB
112static noinline int
113block_group_cache_done(struct btrfs_block_group_cache *cache)
114{
115 smp_mb();
36cce922
JB
116 return cache->cached == BTRFS_CACHE_FINISHED ||
117 cache->cached == BTRFS_CACHE_ERROR;
817d52f8
JB
118}
119
0f9dd46c
JB
120static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
121{
122 return (cache->flags & bits) == bits;
123}
124
758f2dfc 125void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
11dfe35a
JB
126{
127 atomic_inc(&cache->count);
128}
129
130void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
131{
f0486c68
YZ
132 if (atomic_dec_and_test(&cache->count)) {
133 WARN_ON(cache->pinned > 0);
134 WARN_ON(cache->reserved > 0);
0966a7b1
QW
135
136 /*
137 * If not empty, someone is still holding mutex of
138 * full_stripe_lock, which can only be released by caller.
139 * And it will definitely cause use-after-free when caller
140 * tries to release full stripe lock.
141 *
142 * No better way to resolve, but only to warn.
143 */
144 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
34d52cb6 145 kfree(cache->free_space_ctl);
11dfe35a 146 kfree(cache);
f0486c68 147 }
11dfe35a
JB
148}
149
0f9dd46c
JB
150/*
151 * this adds the block group to the fs_info rb tree for the block group
152 * cache
153 */
b2950863 154static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
0f9dd46c
JB
155 struct btrfs_block_group_cache *block_group)
156{
157 struct rb_node **p;
158 struct rb_node *parent = NULL;
159 struct btrfs_block_group_cache *cache;
160
161 spin_lock(&info->block_group_cache_lock);
162 p = &info->block_group_cache_tree.rb_node;
163
164 while (*p) {
165 parent = *p;
166 cache = rb_entry(parent, struct btrfs_block_group_cache,
167 cache_node);
168 if (block_group->key.objectid < cache->key.objectid) {
169 p = &(*p)->rb_left;
170 } else if (block_group->key.objectid > cache->key.objectid) {
171 p = &(*p)->rb_right;
172 } else {
173 spin_unlock(&info->block_group_cache_lock);
174 return -EEXIST;
175 }
176 }
177
178 rb_link_node(&block_group->cache_node, parent, p);
179 rb_insert_color(&block_group->cache_node,
180 &info->block_group_cache_tree);
a1897fdd
LB
181
182 if (info->first_logical_byte > block_group->key.objectid)
183 info->first_logical_byte = block_group->key.objectid;
184
0f9dd46c
JB
185 spin_unlock(&info->block_group_cache_lock);
186
187 return 0;
188}
189
190/*
191 * This will return the block group at or after bytenr if contains is 0, else
192 * it will return the block group that contains the bytenr
193 */
194static struct btrfs_block_group_cache *
195block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
196 int contains)
197{
198 struct btrfs_block_group_cache *cache, *ret = NULL;
199 struct rb_node *n;
200 u64 end, start;
201
202 spin_lock(&info->block_group_cache_lock);
203 n = info->block_group_cache_tree.rb_node;
204
205 while (n) {
206 cache = rb_entry(n, struct btrfs_block_group_cache,
207 cache_node);
208 end = cache->key.objectid + cache->key.offset - 1;
209 start = cache->key.objectid;
210
211 if (bytenr < start) {
212 if (!contains && (!ret || start < ret->key.objectid))
213 ret = cache;
214 n = n->rb_left;
215 } else if (bytenr > start) {
216 if (contains && bytenr <= end) {
217 ret = cache;
218 break;
219 }
220 n = n->rb_right;
221 } else {
222 ret = cache;
223 break;
224 }
225 }
a1897fdd 226 if (ret) {
11dfe35a 227 btrfs_get_block_group(ret);
a1897fdd
LB
228 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
229 info->first_logical_byte = ret->key.objectid;
230 }
0f9dd46c
JB
231 spin_unlock(&info->block_group_cache_lock);
232
233 return ret;
234}
235
2ff7e61e 236static int add_excluded_extent(struct btrfs_fs_info *fs_info,
11833d66 237 u64 start, u64 num_bytes)
817d52f8 238{
11833d66 239 u64 end = start + num_bytes - 1;
0b246afa 240 set_extent_bits(&fs_info->freed_extents[0],
ceeb0ae7 241 start, end, EXTENT_UPTODATE);
0b246afa 242 set_extent_bits(&fs_info->freed_extents[1],
ceeb0ae7 243 start, end, EXTENT_UPTODATE);
11833d66
YZ
244 return 0;
245}
817d52f8 246
2ff7e61e 247static void free_excluded_extents(struct btrfs_fs_info *fs_info,
11833d66
YZ
248 struct btrfs_block_group_cache *cache)
249{
250 u64 start, end;
817d52f8 251
11833d66
YZ
252 start = cache->key.objectid;
253 end = start + cache->key.offset - 1;
254
0b246afa 255 clear_extent_bits(&fs_info->freed_extents[0],
91166212 256 start, end, EXTENT_UPTODATE);
0b246afa 257 clear_extent_bits(&fs_info->freed_extents[1],
91166212 258 start, end, EXTENT_UPTODATE);
817d52f8
JB
259}
260
2ff7e61e 261static int exclude_super_stripes(struct btrfs_fs_info *fs_info,
11833d66 262 struct btrfs_block_group_cache *cache)
817d52f8 263{
817d52f8
JB
264 u64 bytenr;
265 u64 *logical;
266 int stripe_len;
267 int i, nr, ret;
268
06b2331f
YZ
269 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
270 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
271 cache->bytes_super += stripe_len;
2ff7e61e 272 ret = add_excluded_extent(fs_info, cache->key.objectid,
06b2331f 273 stripe_len);
835d974f
JB
274 if (ret)
275 return ret;
06b2331f
YZ
276 }
277
817d52f8
JB
278 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
279 bytenr = btrfs_sb_offset(i);
0b246afa 280 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
ab8d0fc4 281 bytenr, 0, &logical, &nr, &stripe_len);
835d974f
JB
282 if (ret)
283 return ret;
11833d66 284
817d52f8 285 while (nr--) {
51bf5f0b
JB
286 u64 start, len;
287
288 if (logical[nr] > cache->key.objectid +
289 cache->key.offset)
290 continue;
291
292 if (logical[nr] + stripe_len <= cache->key.objectid)
293 continue;
294
295 start = logical[nr];
296 if (start < cache->key.objectid) {
297 start = cache->key.objectid;
298 len = (logical[nr] + stripe_len) - start;
299 } else {
300 len = min_t(u64, stripe_len,
301 cache->key.objectid +
302 cache->key.offset - start);
303 }
304
305 cache->bytes_super += len;
2ff7e61e 306 ret = add_excluded_extent(fs_info, start, len);
835d974f
JB
307 if (ret) {
308 kfree(logical);
309 return ret;
310 }
817d52f8 311 }
11833d66 312
817d52f8
JB
313 kfree(logical);
314 }
817d52f8
JB
315 return 0;
316}
317
11833d66
YZ
318static struct btrfs_caching_control *
319get_caching_control(struct btrfs_block_group_cache *cache)
320{
321 struct btrfs_caching_control *ctl;
322
323 spin_lock(&cache->lock);
dde5abee
JB
324 if (!cache->caching_ctl) {
325 spin_unlock(&cache->lock);
11833d66
YZ
326 return NULL;
327 }
328
329 ctl = cache->caching_ctl;
1e4f4714 330 refcount_inc(&ctl->count);
11833d66
YZ
331 spin_unlock(&cache->lock);
332 return ctl;
333}
334
335static void put_caching_control(struct btrfs_caching_control *ctl)
336{
1e4f4714 337 if (refcount_dec_and_test(&ctl->count))
11833d66
YZ
338 kfree(ctl);
339}
340
d0bd4560 341#ifdef CONFIG_BTRFS_DEBUG
2ff7e61e 342static void fragment_free_space(struct btrfs_block_group_cache *block_group)
d0bd4560 343{
2ff7e61e 344 struct btrfs_fs_info *fs_info = block_group->fs_info;
d0bd4560
JB
345 u64 start = block_group->key.objectid;
346 u64 len = block_group->key.offset;
347 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
0b246afa 348 fs_info->nodesize : fs_info->sectorsize;
d0bd4560
JB
349 u64 step = chunk << 1;
350
351 while (len > chunk) {
352 btrfs_remove_free_space(block_group, start, chunk);
353 start += step;
354 if (len < step)
355 len = 0;
356 else
357 len -= step;
358 }
359}
360#endif
361
0f9dd46c
JB
362/*
363 * this is only called by cache_block_group, since we could have freed extents
364 * we need to check the pinned_extents for any extents that can't be used yet
365 * since their free space will be released as soon as the transaction commits.
366 */
a5ed9182
OS
367u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
368 struct btrfs_fs_info *info, u64 start, u64 end)
0f9dd46c 369{
817d52f8 370 u64 extent_start, extent_end, size, total_added = 0;
0f9dd46c
JB
371 int ret;
372
373 while (start < end) {
11833d66 374 ret = find_first_extent_bit(info->pinned_extents, start,
0f9dd46c 375 &extent_start, &extent_end,
e6138876
JB
376 EXTENT_DIRTY | EXTENT_UPTODATE,
377 NULL);
0f9dd46c
JB
378 if (ret)
379 break;
380
06b2331f 381 if (extent_start <= start) {
0f9dd46c
JB
382 start = extent_end + 1;
383 } else if (extent_start > start && extent_start < end) {
384 size = extent_start - start;
817d52f8 385 total_added += size;
ea6a478e
JB
386 ret = btrfs_add_free_space(block_group, start,
387 size);
79787eaa 388 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
389 start = extent_end + 1;
390 } else {
391 break;
392 }
393 }
394
395 if (start < end) {
396 size = end - start;
817d52f8 397 total_added += size;
ea6a478e 398 ret = btrfs_add_free_space(block_group, start, size);
79787eaa 399 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
400 }
401
817d52f8 402 return total_added;
0f9dd46c
JB
403}
404
73fa48b6 405static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
e37c9e69 406{
0b246afa
JM
407 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
408 struct btrfs_fs_info *fs_info = block_group->fs_info;
409 struct btrfs_root *extent_root = fs_info->extent_root;
e37c9e69 410 struct btrfs_path *path;
5f39d397 411 struct extent_buffer *leaf;
11833d66 412 struct btrfs_key key;
817d52f8 413 u64 total_found = 0;
11833d66
YZ
414 u64 last = 0;
415 u32 nritems;
73fa48b6 416 int ret;
d0bd4560 417 bool wakeup = true;
f510cfec 418
e37c9e69
CM
419 path = btrfs_alloc_path();
420 if (!path)
73fa48b6 421 return -ENOMEM;
7d7d6068 422
817d52f8 423 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
11833d66 424
d0bd4560
JB
425#ifdef CONFIG_BTRFS_DEBUG
426 /*
427 * If we're fragmenting we don't want to make anybody think we can
428 * allocate from this block group until we've had a chance to fragment
429 * the free space.
430 */
2ff7e61e 431 if (btrfs_should_fragment_free_space(block_group))
d0bd4560
JB
432 wakeup = false;
433#endif
5cd57b2c 434 /*
817d52f8
JB
435 * We don't want to deadlock with somebody trying to allocate a new
436 * extent for the extent root while also trying to search the extent
437 * root to add free space. So we skip locking and search the commit
438 * root, since its read-only
5cd57b2c
CM
439 */
440 path->skip_locking = 1;
817d52f8 441 path->search_commit_root = 1;
e4058b54 442 path->reada = READA_FORWARD;
817d52f8 443
e4404d6e 444 key.objectid = last;
e37c9e69 445 key.offset = 0;
11833d66 446 key.type = BTRFS_EXTENT_ITEM_KEY;
013f1b12 447
52ee28d2 448next:
11833d66 449 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
e37c9e69 450 if (ret < 0)
73fa48b6 451 goto out;
a512bbf8 452
11833d66
YZ
453 leaf = path->nodes[0];
454 nritems = btrfs_header_nritems(leaf);
455
d397712b 456 while (1) {
7841cb28 457 if (btrfs_fs_closing(fs_info) > 1) {
f25784b3 458 last = (u64)-1;
817d52f8 459 break;
f25784b3 460 }
817d52f8 461
11833d66
YZ
462 if (path->slots[0] < nritems) {
463 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
464 } else {
465 ret = find_next_key(path, 0, &key);
466 if (ret)
e37c9e69 467 break;
817d52f8 468
c9ea7b24 469 if (need_resched() ||
9e351cc8 470 rwsem_is_contended(&fs_info->commit_root_sem)) {
d0bd4560
JB
471 if (wakeup)
472 caching_ctl->progress = last;
ff5714cc 473 btrfs_release_path(path);
9e351cc8 474 up_read(&fs_info->commit_root_sem);
589d8ade 475 mutex_unlock(&caching_ctl->mutex);
11833d66 476 cond_resched();
73fa48b6
OS
477 mutex_lock(&caching_ctl->mutex);
478 down_read(&fs_info->commit_root_sem);
479 goto next;
589d8ade 480 }
0a3896d0
JB
481
482 ret = btrfs_next_leaf(extent_root, path);
483 if (ret < 0)
73fa48b6 484 goto out;
0a3896d0
JB
485 if (ret)
486 break;
589d8ade
JB
487 leaf = path->nodes[0];
488 nritems = btrfs_header_nritems(leaf);
489 continue;
11833d66 490 }
817d52f8 491
52ee28d2
LB
492 if (key.objectid < last) {
493 key.objectid = last;
494 key.offset = 0;
495 key.type = BTRFS_EXTENT_ITEM_KEY;
496
d0bd4560
JB
497 if (wakeup)
498 caching_ctl->progress = last;
52ee28d2
LB
499 btrfs_release_path(path);
500 goto next;
501 }
502
11833d66
YZ
503 if (key.objectid < block_group->key.objectid) {
504 path->slots[0]++;
817d52f8 505 continue;
e37c9e69 506 }
0f9dd46c 507
e37c9e69 508 if (key.objectid >= block_group->key.objectid +
0f9dd46c 509 block_group->key.offset)
e37c9e69 510 break;
7d7d6068 511
3173a18f
JB
512 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
513 key.type == BTRFS_METADATA_ITEM_KEY) {
817d52f8
JB
514 total_found += add_new_free_space(block_group,
515 fs_info, last,
516 key.objectid);
3173a18f
JB
517 if (key.type == BTRFS_METADATA_ITEM_KEY)
518 last = key.objectid +
da17066c 519 fs_info->nodesize;
3173a18f
JB
520 else
521 last = key.objectid + key.offset;
817d52f8 522
73fa48b6 523 if (total_found > CACHING_CTL_WAKE_UP) {
11833d66 524 total_found = 0;
d0bd4560
JB
525 if (wakeup)
526 wake_up(&caching_ctl->wait);
11833d66 527 }
817d52f8 528 }
e37c9e69
CM
529 path->slots[0]++;
530 }
817d52f8 531 ret = 0;
e37c9e69 532
817d52f8
JB
533 total_found += add_new_free_space(block_group, fs_info, last,
534 block_group->key.objectid +
535 block_group->key.offset);
11833d66 536 caching_ctl->progress = (u64)-1;
817d52f8 537
73fa48b6
OS
538out:
539 btrfs_free_path(path);
540 return ret;
541}
542
543static noinline void caching_thread(struct btrfs_work *work)
544{
545 struct btrfs_block_group_cache *block_group;
546 struct btrfs_fs_info *fs_info;
547 struct btrfs_caching_control *caching_ctl;
b4570aa9 548 struct btrfs_root *extent_root;
73fa48b6
OS
549 int ret;
550
551 caching_ctl = container_of(work, struct btrfs_caching_control, work);
552 block_group = caching_ctl->block_group;
553 fs_info = block_group->fs_info;
b4570aa9 554 extent_root = fs_info->extent_root;
73fa48b6
OS
555
556 mutex_lock(&caching_ctl->mutex);
557 down_read(&fs_info->commit_root_sem);
558
1e144fb8
OS
559 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
560 ret = load_free_space_tree(caching_ctl);
561 else
562 ret = load_extent_tree_free(caching_ctl);
73fa48b6 563
817d52f8 564 spin_lock(&block_group->lock);
11833d66 565 block_group->caching_ctl = NULL;
73fa48b6 566 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
817d52f8 567 spin_unlock(&block_group->lock);
0f9dd46c 568
d0bd4560 569#ifdef CONFIG_BTRFS_DEBUG
2ff7e61e 570 if (btrfs_should_fragment_free_space(block_group)) {
d0bd4560
JB
571 u64 bytes_used;
572
573 spin_lock(&block_group->space_info->lock);
574 spin_lock(&block_group->lock);
575 bytes_used = block_group->key.offset -
576 btrfs_block_group_used(&block_group->item);
577 block_group->space_info->bytes_used += bytes_used >> 1;
578 spin_unlock(&block_group->lock);
579 spin_unlock(&block_group->space_info->lock);
2ff7e61e 580 fragment_free_space(block_group);
d0bd4560
JB
581 }
582#endif
583
584 caching_ctl->progress = (u64)-1;
11833d66 585
9e351cc8 586 up_read(&fs_info->commit_root_sem);
2ff7e61e 587 free_excluded_extents(fs_info, block_group);
11833d66 588 mutex_unlock(&caching_ctl->mutex);
73fa48b6 589
11833d66
YZ
590 wake_up(&caching_ctl->wait);
591
592 put_caching_control(caching_ctl);
11dfe35a 593 btrfs_put_block_group(block_group);
817d52f8
JB
594}
595
9d66e233 596static int cache_block_group(struct btrfs_block_group_cache *cache,
9d66e233 597 int load_cache_only)
817d52f8 598{
291c7d2f 599 DEFINE_WAIT(wait);
11833d66
YZ
600 struct btrfs_fs_info *fs_info = cache->fs_info;
601 struct btrfs_caching_control *caching_ctl;
817d52f8
JB
602 int ret = 0;
603
291c7d2f 604 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
79787eaa
JM
605 if (!caching_ctl)
606 return -ENOMEM;
291c7d2f
JB
607
608 INIT_LIST_HEAD(&caching_ctl->list);
609 mutex_init(&caching_ctl->mutex);
610 init_waitqueue_head(&caching_ctl->wait);
611 caching_ctl->block_group = cache;
612 caching_ctl->progress = cache->key.objectid;
1e4f4714 613 refcount_set(&caching_ctl->count, 1);
9e0af237
LB
614 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
615 caching_thread, NULL, NULL);
291c7d2f
JB
616
617 spin_lock(&cache->lock);
618 /*
619 * This should be a rare occasion, but this could happen I think in the
620 * case where one thread starts to load the space cache info, and then
621 * some other thread starts a transaction commit which tries to do an
622 * allocation while the other thread is still loading the space cache
623 * info. The previous loop should have kept us from choosing this block
624 * group, but if we've moved to the state where we will wait on caching
625 * block groups we need to first check if we're doing a fast load here,
626 * so we can wait for it to finish, otherwise we could end up allocating
627 * from a block group who's cache gets evicted for one reason or
628 * another.
629 */
630 while (cache->cached == BTRFS_CACHE_FAST) {
631 struct btrfs_caching_control *ctl;
632
633 ctl = cache->caching_ctl;
1e4f4714 634 refcount_inc(&ctl->count);
291c7d2f
JB
635 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
636 spin_unlock(&cache->lock);
637
638 schedule();
639
640 finish_wait(&ctl->wait, &wait);
641 put_caching_control(ctl);
642 spin_lock(&cache->lock);
643 }
644
645 if (cache->cached != BTRFS_CACHE_NO) {
646 spin_unlock(&cache->lock);
647 kfree(caching_ctl);
11833d66 648 return 0;
291c7d2f
JB
649 }
650 WARN_ON(cache->caching_ctl);
651 cache->caching_ctl = caching_ctl;
652 cache->cached = BTRFS_CACHE_FAST;
653 spin_unlock(&cache->lock);
11833d66 654
d53ba474 655 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
cb83b7b8 656 mutex_lock(&caching_ctl->mutex);
9d66e233
JB
657 ret = load_free_space_cache(fs_info, cache);
658
659 spin_lock(&cache->lock);
660 if (ret == 1) {
291c7d2f 661 cache->caching_ctl = NULL;
9d66e233
JB
662 cache->cached = BTRFS_CACHE_FINISHED;
663 cache->last_byte_to_unpin = (u64)-1;
cb83b7b8 664 caching_ctl->progress = (u64)-1;
9d66e233 665 } else {
291c7d2f
JB
666 if (load_cache_only) {
667 cache->caching_ctl = NULL;
668 cache->cached = BTRFS_CACHE_NO;
669 } else {
670 cache->cached = BTRFS_CACHE_STARTED;
4f69cb98 671 cache->has_caching_ctl = 1;
291c7d2f 672 }
9d66e233
JB
673 }
674 spin_unlock(&cache->lock);
d0bd4560
JB
675#ifdef CONFIG_BTRFS_DEBUG
676 if (ret == 1 &&
2ff7e61e 677 btrfs_should_fragment_free_space(cache)) {
d0bd4560
JB
678 u64 bytes_used;
679
680 spin_lock(&cache->space_info->lock);
681 spin_lock(&cache->lock);
682 bytes_used = cache->key.offset -
683 btrfs_block_group_used(&cache->item);
684 cache->space_info->bytes_used += bytes_used >> 1;
685 spin_unlock(&cache->lock);
686 spin_unlock(&cache->space_info->lock);
2ff7e61e 687 fragment_free_space(cache);
d0bd4560
JB
688 }
689#endif
cb83b7b8
JB
690 mutex_unlock(&caching_ctl->mutex);
691
291c7d2f 692 wake_up(&caching_ctl->wait);
3c14874a 693 if (ret == 1) {
291c7d2f 694 put_caching_control(caching_ctl);
2ff7e61e 695 free_excluded_extents(fs_info, cache);
9d66e233 696 return 0;
3c14874a 697 }
291c7d2f
JB
698 } else {
699 /*
1e144fb8
OS
700 * We're either using the free space tree or no caching at all.
701 * Set cached to the appropriate value and wakeup any waiters.
291c7d2f
JB
702 */
703 spin_lock(&cache->lock);
704 if (load_cache_only) {
705 cache->caching_ctl = NULL;
706 cache->cached = BTRFS_CACHE_NO;
707 } else {
708 cache->cached = BTRFS_CACHE_STARTED;
4f69cb98 709 cache->has_caching_ctl = 1;
291c7d2f
JB
710 }
711 spin_unlock(&cache->lock);
712 wake_up(&caching_ctl->wait);
9d66e233
JB
713 }
714
291c7d2f
JB
715 if (load_cache_only) {
716 put_caching_control(caching_ctl);
11833d66 717 return 0;
817d52f8 718 }
817d52f8 719
9e351cc8 720 down_write(&fs_info->commit_root_sem);
1e4f4714 721 refcount_inc(&caching_ctl->count);
11833d66 722 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
9e351cc8 723 up_write(&fs_info->commit_root_sem);
11833d66 724
11dfe35a 725 btrfs_get_block_group(cache);
11833d66 726
e66f0bb1 727 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
817d52f8 728
ef8bbdfe 729 return ret;
e37c9e69
CM
730}
731
0f9dd46c
JB
732/*
733 * return the block group that starts at or after bytenr
734 */
d397712b
CM
735static struct btrfs_block_group_cache *
736btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
0ef3e66b 737{
e2c89907 738 return block_group_cache_tree_search(info, bytenr, 0);
0ef3e66b
CM
739}
740
0f9dd46c 741/*
9f55684c 742 * return the block group that contains the given bytenr
0f9dd46c 743 */
d397712b
CM
744struct btrfs_block_group_cache *btrfs_lookup_block_group(
745 struct btrfs_fs_info *info,
746 u64 bytenr)
be744175 747{
e2c89907 748 return block_group_cache_tree_search(info, bytenr, 1);
be744175 749}
0b86a832 750
0f9dd46c
JB
751static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
752 u64 flags)
6324fbf3 753{
0f9dd46c 754 struct list_head *head = &info->space_info;
0f9dd46c 755 struct btrfs_space_info *found;
4184ea7f 756
52ba6929 757 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
b742bb82 758
4184ea7f
CM
759 rcu_read_lock();
760 list_for_each_entry_rcu(found, head, list) {
67377734 761 if (found->flags & flags) {
4184ea7f 762 rcu_read_unlock();
0f9dd46c 763 return found;
4184ea7f 764 }
0f9dd46c 765 }
4184ea7f 766 rcu_read_unlock();
0f9dd46c 767 return NULL;
6324fbf3
CM
768}
769
0d9f824d
OS
770static void add_pinned_bytes(struct btrfs_fs_info *fs_info, s64 num_bytes,
771 u64 owner, u64 root_objectid)
772{
773 struct btrfs_space_info *space_info;
774 u64 flags;
775
776 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
777 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
778 flags = BTRFS_BLOCK_GROUP_SYSTEM;
779 else
780 flags = BTRFS_BLOCK_GROUP_METADATA;
781 } else {
782 flags = BTRFS_BLOCK_GROUP_DATA;
783 }
784
785 space_info = __find_space_info(fs_info, flags);
55e8196a 786 ASSERT(space_info);
0d9f824d
OS
787 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
788}
789
4184ea7f
CM
790/*
791 * after adding space to the filesystem, we need to clear the full flags
792 * on all the space infos.
793 */
794void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
795{
796 struct list_head *head = &info->space_info;
797 struct btrfs_space_info *found;
798
799 rcu_read_lock();
800 list_for_each_entry_rcu(found, head, list)
801 found->full = 0;
802 rcu_read_unlock();
803}
804
1a4ed8fd 805/* simple helper to search for an existing data extent at a given offset */
2ff7e61e 806int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
e02119d5
CM
807{
808 int ret;
809 struct btrfs_key key;
31840ae1 810 struct btrfs_path *path;
e02119d5 811
31840ae1 812 path = btrfs_alloc_path();
d8926bb3
MF
813 if (!path)
814 return -ENOMEM;
815
e02119d5
CM
816 key.objectid = start;
817 key.offset = len;
3173a18f 818 key.type = BTRFS_EXTENT_ITEM_KEY;
0b246afa 819 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
31840ae1 820 btrfs_free_path(path);
7bb86316
CM
821 return ret;
822}
823
a22285a6 824/*
3173a18f 825 * helper function to lookup reference count and flags of a tree block.
a22285a6
YZ
826 *
827 * the head node for delayed ref is used to store the sum of all the
828 * reference count modifications queued up in the rbtree. the head
829 * node may also store the extent flags to set. This way you can check
830 * to see what the reference count and extent flags would be if all of
831 * the delayed refs are not processed.
832 */
833int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
2ff7e61e 834 struct btrfs_fs_info *fs_info, u64 bytenr,
3173a18f 835 u64 offset, int metadata, u64 *refs, u64 *flags)
a22285a6
YZ
836{
837 struct btrfs_delayed_ref_head *head;
838 struct btrfs_delayed_ref_root *delayed_refs;
839 struct btrfs_path *path;
840 struct btrfs_extent_item *ei;
841 struct extent_buffer *leaf;
842 struct btrfs_key key;
843 u32 item_size;
844 u64 num_refs;
845 u64 extent_flags;
846 int ret;
847
3173a18f
JB
848 /*
849 * If we don't have skinny metadata, don't bother doing anything
850 * different
851 */
0b246afa
JM
852 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
853 offset = fs_info->nodesize;
3173a18f
JB
854 metadata = 0;
855 }
856
a22285a6
YZ
857 path = btrfs_alloc_path();
858 if (!path)
859 return -ENOMEM;
860
a22285a6
YZ
861 if (!trans) {
862 path->skip_locking = 1;
863 path->search_commit_root = 1;
864 }
639eefc8
FDBM
865
866search_again:
867 key.objectid = bytenr;
868 key.offset = offset;
869 if (metadata)
870 key.type = BTRFS_METADATA_ITEM_KEY;
871 else
872 key.type = BTRFS_EXTENT_ITEM_KEY;
873
0b246afa 874 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
a22285a6
YZ
875 if (ret < 0)
876 goto out_free;
877
3173a18f 878 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
74be9510
FDBM
879 if (path->slots[0]) {
880 path->slots[0]--;
881 btrfs_item_key_to_cpu(path->nodes[0], &key,
882 path->slots[0]);
883 if (key.objectid == bytenr &&
884 key.type == BTRFS_EXTENT_ITEM_KEY &&
0b246afa 885 key.offset == fs_info->nodesize)
74be9510
FDBM
886 ret = 0;
887 }
3173a18f
JB
888 }
889
a22285a6
YZ
890 if (ret == 0) {
891 leaf = path->nodes[0];
892 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
893 if (item_size >= sizeof(*ei)) {
894 ei = btrfs_item_ptr(leaf, path->slots[0],
895 struct btrfs_extent_item);
896 num_refs = btrfs_extent_refs(leaf, ei);
897 extent_flags = btrfs_extent_flags(leaf, ei);
898 } else {
899#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
900 struct btrfs_extent_item_v0 *ei0;
901 BUG_ON(item_size != sizeof(*ei0));
902 ei0 = btrfs_item_ptr(leaf, path->slots[0],
903 struct btrfs_extent_item_v0);
904 num_refs = btrfs_extent_refs_v0(leaf, ei0);
905 /* FIXME: this isn't correct for data */
906 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
907#else
908 BUG();
909#endif
910 }
911 BUG_ON(num_refs == 0);
912 } else {
913 num_refs = 0;
914 extent_flags = 0;
915 ret = 0;
916 }
917
918 if (!trans)
919 goto out;
920
921 delayed_refs = &trans->transaction->delayed_refs;
922 spin_lock(&delayed_refs->lock);
f72ad18e 923 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
a22285a6
YZ
924 if (head) {
925 if (!mutex_trylock(&head->mutex)) {
6df8cdf5 926 refcount_inc(&head->node.refs);
a22285a6
YZ
927 spin_unlock(&delayed_refs->lock);
928
b3b4aa74 929 btrfs_release_path(path);
a22285a6 930
8cc33e5c
DS
931 /*
932 * Mutex was contended, block until it's released and try
933 * again
934 */
a22285a6
YZ
935 mutex_lock(&head->mutex);
936 mutex_unlock(&head->mutex);
937 btrfs_put_delayed_ref(&head->node);
639eefc8 938 goto search_again;
a22285a6 939 }
d7df2c79 940 spin_lock(&head->lock);
a22285a6
YZ
941 if (head->extent_op && head->extent_op->update_flags)
942 extent_flags |= head->extent_op->flags_to_set;
943 else
944 BUG_ON(num_refs == 0);
945
946 num_refs += head->node.ref_mod;
d7df2c79 947 spin_unlock(&head->lock);
a22285a6
YZ
948 mutex_unlock(&head->mutex);
949 }
950 spin_unlock(&delayed_refs->lock);
951out:
952 WARN_ON(num_refs == 0);
953 if (refs)
954 *refs = num_refs;
955 if (flags)
956 *flags = extent_flags;
957out_free:
958 btrfs_free_path(path);
959 return ret;
960}
961
d8d5f3e1
CM
962/*
963 * Back reference rules. Back refs have three main goals:
964 *
965 * 1) differentiate between all holders of references to an extent so that
966 * when a reference is dropped we can make sure it was a valid reference
967 * before freeing the extent.
968 *
969 * 2) Provide enough information to quickly find the holders of an extent
970 * if we notice a given block is corrupted or bad.
971 *
972 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
973 * maintenance. This is actually the same as #2, but with a slightly
974 * different use case.
975 *
5d4f98a2
YZ
976 * There are two kinds of back refs. The implicit back refs is optimized
977 * for pointers in non-shared tree blocks. For a given pointer in a block,
978 * back refs of this kind provide information about the block's owner tree
979 * and the pointer's key. These information allow us to find the block by
980 * b-tree searching. The full back refs is for pointers in tree blocks not
981 * referenced by their owner trees. The location of tree block is recorded
982 * in the back refs. Actually the full back refs is generic, and can be
983 * used in all cases the implicit back refs is used. The major shortcoming
984 * of the full back refs is its overhead. Every time a tree block gets
985 * COWed, we have to update back refs entry for all pointers in it.
986 *
987 * For a newly allocated tree block, we use implicit back refs for
988 * pointers in it. This means most tree related operations only involve
989 * implicit back refs. For a tree block created in old transaction, the
990 * only way to drop a reference to it is COW it. So we can detect the
991 * event that tree block loses its owner tree's reference and do the
992 * back refs conversion.
993 *
01327610 994 * When a tree block is COWed through a tree, there are four cases:
5d4f98a2
YZ
995 *
996 * The reference count of the block is one and the tree is the block's
997 * owner tree. Nothing to do in this case.
998 *
999 * The reference count of the block is one and the tree is not the
1000 * block's owner tree. In this case, full back refs is used for pointers
1001 * in the block. Remove these full back refs, add implicit back refs for
1002 * every pointers in the new block.
1003 *
1004 * The reference count of the block is greater than one and the tree is
1005 * the block's owner tree. In this case, implicit back refs is used for
1006 * pointers in the block. Add full back refs for every pointers in the
1007 * block, increase lower level extents' reference counts. The original
1008 * implicit back refs are entailed to the new block.
1009 *
1010 * The reference count of the block is greater than one and the tree is
1011 * not the block's owner tree. Add implicit back refs for every pointer in
1012 * the new block, increase lower level extents' reference count.
1013 *
1014 * Back Reference Key composing:
1015 *
1016 * The key objectid corresponds to the first byte in the extent,
1017 * The key type is used to differentiate between types of back refs.
1018 * There are different meanings of the key offset for different types
1019 * of back refs.
1020 *
d8d5f3e1
CM
1021 * File extents can be referenced by:
1022 *
1023 * - multiple snapshots, subvolumes, or different generations in one subvol
31840ae1 1024 * - different files inside a single subvolume
d8d5f3e1
CM
1025 * - different offsets inside a file (bookend extents in file.c)
1026 *
5d4f98a2 1027 * The extent ref structure for the implicit back refs has fields for:
d8d5f3e1
CM
1028 *
1029 * - Objectid of the subvolume root
d8d5f3e1 1030 * - objectid of the file holding the reference
5d4f98a2
YZ
1031 * - original offset in the file
1032 * - how many bookend extents
d8d5f3e1 1033 *
5d4f98a2
YZ
1034 * The key offset for the implicit back refs is hash of the first
1035 * three fields.
d8d5f3e1 1036 *
5d4f98a2 1037 * The extent ref structure for the full back refs has field for:
d8d5f3e1 1038 *
5d4f98a2 1039 * - number of pointers in the tree leaf
d8d5f3e1 1040 *
5d4f98a2
YZ
1041 * The key offset for the implicit back refs is the first byte of
1042 * the tree leaf
d8d5f3e1 1043 *
5d4f98a2
YZ
1044 * When a file extent is allocated, The implicit back refs is used.
1045 * the fields are filled in:
d8d5f3e1 1046 *
5d4f98a2 1047 * (root_key.objectid, inode objectid, offset in file, 1)
d8d5f3e1 1048 *
5d4f98a2
YZ
1049 * When a file extent is removed file truncation, we find the
1050 * corresponding implicit back refs and check the following fields:
d8d5f3e1 1051 *
5d4f98a2 1052 * (btrfs_header_owner(leaf), inode objectid, offset in file)
d8d5f3e1 1053 *
5d4f98a2 1054 * Btree extents can be referenced by:
d8d5f3e1 1055 *
5d4f98a2 1056 * - Different subvolumes
d8d5f3e1 1057 *
5d4f98a2
YZ
1058 * Both the implicit back refs and the full back refs for tree blocks
1059 * only consist of key. The key offset for the implicit back refs is
1060 * objectid of block's owner tree. The key offset for the full back refs
1061 * is the first byte of parent block.
d8d5f3e1 1062 *
5d4f98a2
YZ
1063 * When implicit back refs is used, information about the lowest key and
1064 * level of the tree block are required. These information are stored in
1065 * tree block info structure.
d8d5f3e1 1066 */
31840ae1 1067
5d4f98a2
YZ
1068#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1069static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
87bde3cd 1070 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1071 struct btrfs_path *path,
1072 u64 owner, u32 extra_size)
7bb86316 1073{
87bde3cd 1074 struct btrfs_root *root = fs_info->extent_root;
5d4f98a2
YZ
1075 struct btrfs_extent_item *item;
1076 struct btrfs_extent_item_v0 *ei0;
1077 struct btrfs_extent_ref_v0 *ref0;
1078 struct btrfs_tree_block_info *bi;
1079 struct extent_buffer *leaf;
7bb86316 1080 struct btrfs_key key;
5d4f98a2
YZ
1081 struct btrfs_key found_key;
1082 u32 new_size = sizeof(*item);
1083 u64 refs;
1084 int ret;
1085
1086 leaf = path->nodes[0];
1087 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1088
1089 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1090 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1091 struct btrfs_extent_item_v0);
1092 refs = btrfs_extent_refs_v0(leaf, ei0);
1093
1094 if (owner == (u64)-1) {
1095 while (1) {
1096 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1097 ret = btrfs_next_leaf(root, path);
1098 if (ret < 0)
1099 return ret;
79787eaa 1100 BUG_ON(ret > 0); /* Corruption */
5d4f98a2
YZ
1101 leaf = path->nodes[0];
1102 }
1103 btrfs_item_key_to_cpu(leaf, &found_key,
1104 path->slots[0]);
1105 BUG_ON(key.objectid != found_key.objectid);
1106 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1107 path->slots[0]++;
1108 continue;
1109 }
1110 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1111 struct btrfs_extent_ref_v0);
1112 owner = btrfs_ref_objectid_v0(leaf, ref0);
1113 break;
1114 }
1115 }
b3b4aa74 1116 btrfs_release_path(path);
5d4f98a2
YZ
1117
1118 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1119 new_size += sizeof(*bi);
1120
1121 new_size -= sizeof(*ei0);
1122 ret = btrfs_search_slot(trans, root, &key, path,
1123 new_size + extra_size, 1);
1124 if (ret < 0)
1125 return ret;
79787eaa 1126 BUG_ON(ret); /* Corruption */
5d4f98a2 1127
87bde3cd 1128 btrfs_extend_item(fs_info, path, new_size);
5d4f98a2
YZ
1129
1130 leaf = path->nodes[0];
1131 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1132 btrfs_set_extent_refs(leaf, item, refs);
1133 /* FIXME: get real generation */
1134 btrfs_set_extent_generation(leaf, item, 0);
1135 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1136 btrfs_set_extent_flags(leaf, item,
1137 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1138 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1139 bi = (struct btrfs_tree_block_info *)(item + 1);
1140 /* FIXME: get first key of the block */
b159fa28 1141 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
5d4f98a2
YZ
1142 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1143 } else {
1144 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1145 }
1146 btrfs_mark_buffer_dirty(leaf);
1147 return 0;
1148}
1149#endif
1150
167ce953
LB
1151/*
1152 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1153 * is_data == BTRFS_REF_TYPE_DATA, data type is requried,
1154 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1155 */
1156int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1157 struct btrfs_extent_inline_ref *iref,
1158 enum btrfs_inline_ref_type is_data)
1159{
1160 int type = btrfs_extent_inline_ref_type(eb, iref);
64ecdb64 1161 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
167ce953
LB
1162
1163 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1164 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1165 type == BTRFS_SHARED_DATA_REF_KEY ||
1166 type == BTRFS_EXTENT_DATA_REF_KEY) {
1167 if (is_data == BTRFS_REF_TYPE_BLOCK) {
64ecdb64 1168 if (type == BTRFS_TREE_BLOCK_REF_KEY)
167ce953 1169 return type;
64ecdb64
LB
1170 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1171 ASSERT(eb->fs_info);
1172 /*
e24ef300
QW
1173 * Every shared one has parent tree block,
1174 * which must be aligned to sector size.
64ecdb64
LB
1175 */
1176 if (offset &&
e24ef300 1177 IS_ALIGNED(offset, eb->fs_info->sectorsize))
64ecdb64
LB
1178 return type;
1179 }
167ce953 1180 } else if (is_data == BTRFS_REF_TYPE_DATA) {
64ecdb64 1181 if (type == BTRFS_EXTENT_DATA_REF_KEY)
167ce953 1182 return type;
64ecdb64
LB
1183 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1184 ASSERT(eb->fs_info);
1185 /*
e24ef300
QW
1186 * Every shared one has parent tree block,
1187 * which must be aligned to sector size.
64ecdb64
LB
1188 */
1189 if (offset &&
e24ef300 1190 IS_ALIGNED(offset, eb->fs_info->sectorsize))
64ecdb64
LB
1191 return type;
1192 }
167ce953
LB
1193 } else {
1194 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1195 return type;
1196 }
1197 }
1198
1199 btrfs_print_leaf((struct extent_buffer *)eb);
e24ef300
QW
1200 btrfs_err(eb->fs_info,
1201 "eb %llu iref 0x%lx invalid extent inline ref type %d",
1202 eb->start, (unsigned long)iref, type);
167ce953
LB
1203 WARN_ON(1);
1204
1205 return BTRFS_REF_TYPE_INVALID;
1206}
1207
5d4f98a2
YZ
1208static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1209{
1210 u32 high_crc = ~(u32)0;
1211 u32 low_crc = ~(u32)0;
1212 __le64 lenum;
1213
1214 lenum = cpu_to_le64(root_objectid);
14a958e6 1215 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
5d4f98a2 1216 lenum = cpu_to_le64(owner);
14a958e6 1217 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2 1218 lenum = cpu_to_le64(offset);
14a958e6 1219 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2
YZ
1220
1221 return ((u64)high_crc << 31) ^ (u64)low_crc;
1222}
1223
1224static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1225 struct btrfs_extent_data_ref *ref)
1226{
1227 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1228 btrfs_extent_data_ref_objectid(leaf, ref),
1229 btrfs_extent_data_ref_offset(leaf, ref));
1230}
1231
1232static int match_extent_data_ref(struct extent_buffer *leaf,
1233 struct btrfs_extent_data_ref *ref,
1234 u64 root_objectid, u64 owner, u64 offset)
1235{
1236 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1237 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1238 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1239 return 0;
1240 return 1;
1241}
1242
1243static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
87bde3cd 1244 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1245 struct btrfs_path *path,
1246 u64 bytenr, u64 parent,
1247 u64 root_objectid,
1248 u64 owner, u64 offset)
1249{
87bde3cd 1250 struct btrfs_root *root = fs_info->extent_root;
5d4f98a2
YZ
1251 struct btrfs_key key;
1252 struct btrfs_extent_data_ref *ref;
31840ae1 1253 struct extent_buffer *leaf;
5d4f98a2 1254 u32 nritems;
74493f7a 1255 int ret;
5d4f98a2
YZ
1256 int recow;
1257 int err = -ENOENT;
74493f7a 1258
31840ae1 1259 key.objectid = bytenr;
5d4f98a2
YZ
1260 if (parent) {
1261 key.type = BTRFS_SHARED_DATA_REF_KEY;
1262 key.offset = parent;
1263 } else {
1264 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1265 key.offset = hash_extent_data_ref(root_objectid,
1266 owner, offset);
1267 }
1268again:
1269 recow = 0;
1270 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1271 if (ret < 0) {
1272 err = ret;
1273 goto fail;
1274 }
31840ae1 1275
5d4f98a2
YZ
1276 if (parent) {
1277 if (!ret)
1278 return 0;
1279#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1280 key.type = BTRFS_EXTENT_REF_V0_KEY;
b3b4aa74 1281 btrfs_release_path(path);
5d4f98a2
YZ
1282 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1283 if (ret < 0) {
1284 err = ret;
1285 goto fail;
1286 }
1287 if (!ret)
1288 return 0;
1289#endif
1290 goto fail;
31840ae1
ZY
1291 }
1292
1293 leaf = path->nodes[0];
5d4f98a2
YZ
1294 nritems = btrfs_header_nritems(leaf);
1295 while (1) {
1296 if (path->slots[0] >= nritems) {
1297 ret = btrfs_next_leaf(root, path);
1298 if (ret < 0)
1299 err = ret;
1300 if (ret)
1301 goto fail;
1302
1303 leaf = path->nodes[0];
1304 nritems = btrfs_header_nritems(leaf);
1305 recow = 1;
1306 }
1307
1308 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1309 if (key.objectid != bytenr ||
1310 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1311 goto fail;
1312
1313 ref = btrfs_item_ptr(leaf, path->slots[0],
1314 struct btrfs_extent_data_ref);
1315
1316 if (match_extent_data_ref(leaf, ref, root_objectid,
1317 owner, offset)) {
1318 if (recow) {
b3b4aa74 1319 btrfs_release_path(path);
5d4f98a2
YZ
1320 goto again;
1321 }
1322 err = 0;
1323 break;
1324 }
1325 path->slots[0]++;
31840ae1 1326 }
5d4f98a2
YZ
1327fail:
1328 return err;
31840ae1
ZY
1329}
1330
5d4f98a2 1331static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
87bde3cd 1332 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1333 struct btrfs_path *path,
1334 u64 bytenr, u64 parent,
1335 u64 root_objectid, u64 owner,
1336 u64 offset, int refs_to_add)
31840ae1 1337{
87bde3cd 1338 struct btrfs_root *root = fs_info->extent_root;
31840ae1
ZY
1339 struct btrfs_key key;
1340 struct extent_buffer *leaf;
5d4f98a2 1341 u32 size;
31840ae1
ZY
1342 u32 num_refs;
1343 int ret;
74493f7a 1344
74493f7a 1345 key.objectid = bytenr;
5d4f98a2
YZ
1346 if (parent) {
1347 key.type = BTRFS_SHARED_DATA_REF_KEY;
1348 key.offset = parent;
1349 size = sizeof(struct btrfs_shared_data_ref);
1350 } else {
1351 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1352 key.offset = hash_extent_data_ref(root_objectid,
1353 owner, offset);
1354 size = sizeof(struct btrfs_extent_data_ref);
1355 }
74493f7a 1356
5d4f98a2
YZ
1357 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1358 if (ret && ret != -EEXIST)
1359 goto fail;
1360
1361 leaf = path->nodes[0];
1362 if (parent) {
1363 struct btrfs_shared_data_ref *ref;
31840ae1 1364 ref = btrfs_item_ptr(leaf, path->slots[0],
5d4f98a2
YZ
1365 struct btrfs_shared_data_ref);
1366 if (ret == 0) {
1367 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1368 } else {
1369 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1370 num_refs += refs_to_add;
1371 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
31840ae1 1372 }
5d4f98a2
YZ
1373 } else {
1374 struct btrfs_extent_data_ref *ref;
1375 while (ret == -EEXIST) {
1376 ref = btrfs_item_ptr(leaf, path->slots[0],
1377 struct btrfs_extent_data_ref);
1378 if (match_extent_data_ref(leaf, ref, root_objectid,
1379 owner, offset))
1380 break;
b3b4aa74 1381 btrfs_release_path(path);
5d4f98a2
YZ
1382 key.offset++;
1383 ret = btrfs_insert_empty_item(trans, root, path, &key,
1384 size);
1385 if (ret && ret != -EEXIST)
1386 goto fail;
31840ae1 1387
5d4f98a2
YZ
1388 leaf = path->nodes[0];
1389 }
1390 ref = btrfs_item_ptr(leaf, path->slots[0],
1391 struct btrfs_extent_data_ref);
1392 if (ret == 0) {
1393 btrfs_set_extent_data_ref_root(leaf, ref,
1394 root_objectid);
1395 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1396 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1397 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1398 } else {
1399 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1400 num_refs += refs_to_add;
1401 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
31840ae1 1402 }
31840ae1 1403 }
5d4f98a2
YZ
1404 btrfs_mark_buffer_dirty(leaf);
1405 ret = 0;
1406fail:
b3b4aa74 1407 btrfs_release_path(path);
7bb86316 1408 return ret;
74493f7a
CM
1409}
1410
5d4f98a2 1411static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
87bde3cd 1412 struct btrfs_fs_info *fs_info,
5d4f98a2 1413 struct btrfs_path *path,
fcebe456 1414 int refs_to_drop, int *last_ref)
31840ae1 1415{
5d4f98a2
YZ
1416 struct btrfs_key key;
1417 struct btrfs_extent_data_ref *ref1 = NULL;
1418 struct btrfs_shared_data_ref *ref2 = NULL;
31840ae1 1419 struct extent_buffer *leaf;
5d4f98a2 1420 u32 num_refs = 0;
31840ae1
ZY
1421 int ret = 0;
1422
1423 leaf = path->nodes[0];
5d4f98a2
YZ
1424 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1425
1426 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1427 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1428 struct btrfs_extent_data_ref);
1429 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1430 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1431 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1432 struct btrfs_shared_data_ref);
1433 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1434#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1435 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1436 struct btrfs_extent_ref_v0 *ref0;
1437 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1438 struct btrfs_extent_ref_v0);
1439 num_refs = btrfs_ref_count_v0(leaf, ref0);
1440#endif
1441 } else {
1442 BUG();
1443 }
1444
56bec294
CM
1445 BUG_ON(num_refs < refs_to_drop);
1446 num_refs -= refs_to_drop;
5d4f98a2 1447
31840ae1 1448 if (num_refs == 0) {
87bde3cd 1449 ret = btrfs_del_item(trans, fs_info->extent_root, path);
fcebe456 1450 *last_ref = 1;
31840ae1 1451 } else {
5d4f98a2
YZ
1452 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1453 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1454 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1455 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1456#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1457 else {
1458 struct btrfs_extent_ref_v0 *ref0;
1459 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1460 struct btrfs_extent_ref_v0);
1461 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1462 }
1463#endif
31840ae1
ZY
1464 btrfs_mark_buffer_dirty(leaf);
1465 }
31840ae1
ZY
1466 return ret;
1467}
1468
9ed0dea0 1469static noinline u32 extent_data_ref_count(struct btrfs_path *path,
5d4f98a2 1470 struct btrfs_extent_inline_ref *iref)
15916de8 1471{
5d4f98a2
YZ
1472 struct btrfs_key key;
1473 struct extent_buffer *leaf;
1474 struct btrfs_extent_data_ref *ref1;
1475 struct btrfs_shared_data_ref *ref2;
1476 u32 num_refs = 0;
3de28d57 1477 int type;
5d4f98a2
YZ
1478
1479 leaf = path->nodes[0];
1480 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1481 if (iref) {
3de28d57
LB
1482 /*
1483 * If type is invalid, we should have bailed out earlier than
1484 * this call.
1485 */
1486 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1487 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1488 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
5d4f98a2
YZ
1489 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1490 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1491 } else {
1492 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1493 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1494 }
1495 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1496 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1497 struct btrfs_extent_data_ref);
1498 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1499 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1500 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1501 struct btrfs_shared_data_ref);
1502 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1503#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1504 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1505 struct btrfs_extent_ref_v0 *ref0;
1506 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1507 struct btrfs_extent_ref_v0);
1508 num_refs = btrfs_ref_count_v0(leaf, ref0);
4b4e25f2 1509#endif
5d4f98a2
YZ
1510 } else {
1511 WARN_ON(1);
1512 }
1513 return num_refs;
1514}
15916de8 1515
5d4f98a2 1516static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
87bde3cd 1517 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1518 struct btrfs_path *path,
1519 u64 bytenr, u64 parent,
1520 u64 root_objectid)
1f3c79a2 1521{
87bde3cd 1522 struct btrfs_root *root = fs_info->extent_root;
5d4f98a2 1523 struct btrfs_key key;
1f3c79a2 1524 int ret;
1f3c79a2 1525
5d4f98a2
YZ
1526 key.objectid = bytenr;
1527 if (parent) {
1528 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1529 key.offset = parent;
1530 } else {
1531 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1532 key.offset = root_objectid;
1f3c79a2
LH
1533 }
1534
5d4f98a2
YZ
1535 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1536 if (ret > 0)
1537 ret = -ENOENT;
1538#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1539 if (ret == -ENOENT && parent) {
b3b4aa74 1540 btrfs_release_path(path);
5d4f98a2
YZ
1541 key.type = BTRFS_EXTENT_REF_V0_KEY;
1542 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1543 if (ret > 0)
1544 ret = -ENOENT;
1545 }
1f3c79a2 1546#endif
5d4f98a2 1547 return ret;
1f3c79a2
LH
1548}
1549
5d4f98a2 1550static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
87bde3cd 1551 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1552 struct btrfs_path *path,
1553 u64 bytenr, u64 parent,
1554 u64 root_objectid)
31840ae1 1555{
5d4f98a2 1556 struct btrfs_key key;
31840ae1 1557 int ret;
31840ae1 1558
5d4f98a2
YZ
1559 key.objectid = bytenr;
1560 if (parent) {
1561 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1562 key.offset = parent;
1563 } else {
1564 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1565 key.offset = root_objectid;
1566 }
1567
87bde3cd
JM
1568 ret = btrfs_insert_empty_item(trans, fs_info->extent_root,
1569 path, &key, 0);
b3b4aa74 1570 btrfs_release_path(path);
31840ae1
ZY
1571 return ret;
1572}
1573
5d4f98a2 1574static inline int extent_ref_type(u64 parent, u64 owner)
31840ae1 1575{
5d4f98a2
YZ
1576 int type;
1577 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1578 if (parent > 0)
1579 type = BTRFS_SHARED_BLOCK_REF_KEY;
1580 else
1581 type = BTRFS_TREE_BLOCK_REF_KEY;
1582 } else {
1583 if (parent > 0)
1584 type = BTRFS_SHARED_DATA_REF_KEY;
1585 else
1586 type = BTRFS_EXTENT_DATA_REF_KEY;
1587 }
1588 return type;
31840ae1 1589}
56bec294 1590
2c47e605
YZ
1591static int find_next_key(struct btrfs_path *path, int level,
1592 struct btrfs_key *key)
56bec294 1593
02217ed2 1594{
2c47e605 1595 for (; level < BTRFS_MAX_LEVEL; level++) {
5d4f98a2
YZ
1596 if (!path->nodes[level])
1597 break;
5d4f98a2
YZ
1598 if (path->slots[level] + 1 >=
1599 btrfs_header_nritems(path->nodes[level]))
1600 continue;
1601 if (level == 0)
1602 btrfs_item_key_to_cpu(path->nodes[level], key,
1603 path->slots[level] + 1);
1604 else
1605 btrfs_node_key_to_cpu(path->nodes[level], key,
1606 path->slots[level] + 1);
1607 return 0;
1608 }
1609 return 1;
1610}
037e6390 1611
5d4f98a2
YZ
1612/*
1613 * look for inline back ref. if back ref is found, *ref_ret is set
1614 * to the address of inline back ref, and 0 is returned.
1615 *
1616 * if back ref isn't found, *ref_ret is set to the address where it
1617 * should be inserted, and -ENOENT is returned.
1618 *
1619 * if insert is true and there are too many inline back refs, the path
1620 * points to the extent item, and -EAGAIN is returned.
1621 *
1622 * NOTE: inline back refs are ordered in the same way that back ref
1623 * items in the tree are ordered.
1624 */
1625static noinline_for_stack
1626int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
87bde3cd 1627 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1628 struct btrfs_path *path,
1629 struct btrfs_extent_inline_ref **ref_ret,
1630 u64 bytenr, u64 num_bytes,
1631 u64 parent, u64 root_objectid,
1632 u64 owner, u64 offset, int insert)
1633{
87bde3cd 1634 struct btrfs_root *root = fs_info->extent_root;
5d4f98a2
YZ
1635 struct btrfs_key key;
1636 struct extent_buffer *leaf;
1637 struct btrfs_extent_item *ei;
1638 struct btrfs_extent_inline_ref *iref;
1639 u64 flags;
1640 u64 item_size;
1641 unsigned long ptr;
1642 unsigned long end;
1643 int extra_size;
1644 int type;
1645 int want;
1646 int ret;
1647 int err = 0;
0b246afa 1648 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
3de28d57 1649 int needed;
26b8003f 1650
db94535d 1651 key.objectid = bytenr;
31840ae1 1652 key.type = BTRFS_EXTENT_ITEM_KEY;
56bec294 1653 key.offset = num_bytes;
31840ae1 1654
5d4f98a2
YZ
1655 want = extent_ref_type(parent, owner);
1656 if (insert) {
1657 extra_size = btrfs_extent_inline_ref_size(want);
85d4198e 1658 path->keep_locks = 1;
5d4f98a2
YZ
1659 } else
1660 extra_size = -1;
3173a18f
JB
1661
1662 /*
1663 * Owner is our parent level, so we can just add one to get the level
1664 * for the block we are interested in.
1665 */
1666 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1667 key.type = BTRFS_METADATA_ITEM_KEY;
1668 key.offset = owner;
1669 }
1670
1671again:
5d4f98a2 1672 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
b9473439 1673 if (ret < 0) {
5d4f98a2
YZ
1674 err = ret;
1675 goto out;
1676 }
3173a18f
JB
1677
1678 /*
1679 * We may be a newly converted file system which still has the old fat
1680 * extent entries for metadata, so try and see if we have one of those.
1681 */
1682 if (ret > 0 && skinny_metadata) {
1683 skinny_metadata = false;
1684 if (path->slots[0]) {
1685 path->slots[0]--;
1686 btrfs_item_key_to_cpu(path->nodes[0], &key,
1687 path->slots[0]);
1688 if (key.objectid == bytenr &&
1689 key.type == BTRFS_EXTENT_ITEM_KEY &&
1690 key.offset == num_bytes)
1691 ret = 0;
1692 }
1693 if (ret) {
9ce49a0b 1694 key.objectid = bytenr;
3173a18f
JB
1695 key.type = BTRFS_EXTENT_ITEM_KEY;
1696 key.offset = num_bytes;
1697 btrfs_release_path(path);
1698 goto again;
1699 }
1700 }
1701
79787eaa
JM
1702 if (ret && !insert) {
1703 err = -ENOENT;
1704 goto out;
fae7f21c 1705 } else if (WARN_ON(ret)) {
492104c8 1706 err = -EIO;
492104c8 1707 goto out;
79787eaa 1708 }
5d4f98a2
YZ
1709
1710 leaf = path->nodes[0];
1711 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1712#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1713 if (item_size < sizeof(*ei)) {
1714 if (!insert) {
1715 err = -ENOENT;
1716 goto out;
1717 }
87bde3cd 1718 ret = convert_extent_item_v0(trans, fs_info, path, owner,
5d4f98a2
YZ
1719 extra_size);
1720 if (ret < 0) {
1721 err = ret;
1722 goto out;
1723 }
1724 leaf = path->nodes[0];
1725 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1726 }
1727#endif
1728 BUG_ON(item_size < sizeof(*ei));
1729
5d4f98a2
YZ
1730 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1731 flags = btrfs_extent_flags(leaf, ei);
1732
1733 ptr = (unsigned long)(ei + 1);
1734 end = (unsigned long)ei + item_size;
1735
3173a18f 1736 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
5d4f98a2
YZ
1737 ptr += sizeof(struct btrfs_tree_block_info);
1738 BUG_ON(ptr > end);
5d4f98a2
YZ
1739 }
1740
3de28d57
LB
1741 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1742 needed = BTRFS_REF_TYPE_DATA;
1743 else
1744 needed = BTRFS_REF_TYPE_BLOCK;
1745
5d4f98a2
YZ
1746 err = -ENOENT;
1747 while (1) {
1748 if (ptr >= end) {
1749 WARN_ON(ptr > end);
1750 break;
1751 }
1752 iref = (struct btrfs_extent_inline_ref *)ptr;
3de28d57
LB
1753 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1754 if (type == BTRFS_REF_TYPE_INVALID) {
1755 err = -EINVAL;
1756 goto out;
1757 }
1758
5d4f98a2
YZ
1759 if (want < type)
1760 break;
1761 if (want > type) {
1762 ptr += btrfs_extent_inline_ref_size(type);
1763 continue;
1764 }
1765
1766 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1767 struct btrfs_extent_data_ref *dref;
1768 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1769 if (match_extent_data_ref(leaf, dref, root_objectid,
1770 owner, offset)) {
1771 err = 0;
1772 break;
1773 }
1774 if (hash_extent_data_ref_item(leaf, dref) <
1775 hash_extent_data_ref(root_objectid, owner, offset))
1776 break;
1777 } else {
1778 u64 ref_offset;
1779 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1780 if (parent > 0) {
1781 if (parent == ref_offset) {
1782 err = 0;
1783 break;
1784 }
1785 if (ref_offset < parent)
1786 break;
1787 } else {
1788 if (root_objectid == ref_offset) {
1789 err = 0;
1790 break;
1791 }
1792 if (ref_offset < root_objectid)
1793 break;
1794 }
1795 }
1796 ptr += btrfs_extent_inline_ref_size(type);
1797 }
1798 if (err == -ENOENT && insert) {
1799 if (item_size + extra_size >=
1800 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1801 err = -EAGAIN;
1802 goto out;
1803 }
1804 /*
1805 * To add new inline back ref, we have to make sure
1806 * there is no corresponding back ref item.
1807 * For simplicity, we just do not add new inline back
1808 * ref if there is any kind of item for this block
1809 */
2c47e605
YZ
1810 if (find_next_key(path, 0, &key) == 0 &&
1811 key.objectid == bytenr &&
85d4198e 1812 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
5d4f98a2
YZ
1813 err = -EAGAIN;
1814 goto out;
1815 }
1816 }
1817 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1818out:
85d4198e 1819 if (insert) {
5d4f98a2
YZ
1820 path->keep_locks = 0;
1821 btrfs_unlock_up_safe(path, 1);
1822 }
1823 return err;
1824}
1825
1826/*
1827 * helper to add new inline back ref
1828 */
1829static noinline_for_stack
87bde3cd 1830void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
143bede5
JM
1831 struct btrfs_path *path,
1832 struct btrfs_extent_inline_ref *iref,
1833 u64 parent, u64 root_objectid,
1834 u64 owner, u64 offset, int refs_to_add,
1835 struct btrfs_delayed_extent_op *extent_op)
5d4f98a2
YZ
1836{
1837 struct extent_buffer *leaf;
1838 struct btrfs_extent_item *ei;
1839 unsigned long ptr;
1840 unsigned long end;
1841 unsigned long item_offset;
1842 u64 refs;
1843 int size;
1844 int type;
5d4f98a2
YZ
1845
1846 leaf = path->nodes[0];
1847 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1848 item_offset = (unsigned long)iref - (unsigned long)ei;
1849
1850 type = extent_ref_type(parent, owner);
1851 size = btrfs_extent_inline_ref_size(type);
1852
87bde3cd 1853 btrfs_extend_item(fs_info, path, size);
5d4f98a2
YZ
1854
1855 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1856 refs = btrfs_extent_refs(leaf, ei);
1857 refs += refs_to_add;
1858 btrfs_set_extent_refs(leaf, ei, refs);
1859 if (extent_op)
1860 __run_delayed_extent_op(extent_op, leaf, ei);
1861
1862 ptr = (unsigned long)ei + item_offset;
1863 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1864 if (ptr < end - size)
1865 memmove_extent_buffer(leaf, ptr + size, ptr,
1866 end - size - ptr);
1867
1868 iref = (struct btrfs_extent_inline_ref *)ptr;
1869 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1870 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1871 struct btrfs_extent_data_ref *dref;
1872 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1873 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1874 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1875 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1876 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1877 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1878 struct btrfs_shared_data_ref *sref;
1879 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1880 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1881 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1882 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1883 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1884 } else {
1885 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1886 }
1887 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1888}
1889
1890static int lookup_extent_backref(struct btrfs_trans_handle *trans,
87bde3cd 1891 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1892 struct btrfs_path *path,
1893 struct btrfs_extent_inline_ref **ref_ret,
1894 u64 bytenr, u64 num_bytes, u64 parent,
1895 u64 root_objectid, u64 owner, u64 offset)
1896{
1897 int ret;
1898
87bde3cd 1899 ret = lookup_inline_extent_backref(trans, fs_info, path, ref_ret,
5d4f98a2
YZ
1900 bytenr, num_bytes, parent,
1901 root_objectid, owner, offset, 0);
1902 if (ret != -ENOENT)
54aa1f4d 1903 return ret;
5d4f98a2 1904
b3b4aa74 1905 btrfs_release_path(path);
5d4f98a2
YZ
1906 *ref_ret = NULL;
1907
1908 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
87bde3cd
JM
1909 ret = lookup_tree_block_ref(trans, fs_info, path, bytenr,
1910 parent, root_objectid);
5d4f98a2 1911 } else {
87bde3cd
JM
1912 ret = lookup_extent_data_ref(trans, fs_info, path, bytenr,
1913 parent, root_objectid, owner,
1914 offset);
b9473439 1915 }
5d4f98a2
YZ
1916 return ret;
1917}
31840ae1 1918
5d4f98a2
YZ
1919/*
1920 * helper to update/remove inline back ref
1921 */
1922static noinline_for_stack
87bde3cd 1923void update_inline_extent_backref(struct btrfs_fs_info *fs_info,
143bede5
JM
1924 struct btrfs_path *path,
1925 struct btrfs_extent_inline_ref *iref,
1926 int refs_to_mod,
fcebe456
JB
1927 struct btrfs_delayed_extent_op *extent_op,
1928 int *last_ref)
5d4f98a2
YZ
1929{
1930 struct extent_buffer *leaf;
1931 struct btrfs_extent_item *ei;
1932 struct btrfs_extent_data_ref *dref = NULL;
1933 struct btrfs_shared_data_ref *sref = NULL;
1934 unsigned long ptr;
1935 unsigned long end;
1936 u32 item_size;
1937 int size;
1938 int type;
5d4f98a2
YZ
1939 u64 refs;
1940
1941 leaf = path->nodes[0];
1942 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1943 refs = btrfs_extent_refs(leaf, ei);
1944 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1945 refs += refs_to_mod;
1946 btrfs_set_extent_refs(leaf, ei, refs);
1947 if (extent_op)
1948 __run_delayed_extent_op(extent_op, leaf, ei);
1949
3de28d57
LB
1950 /*
1951 * If type is invalid, we should have bailed out after
1952 * lookup_inline_extent_backref().
1953 */
1954 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1955 ASSERT(type != BTRFS_REF_TYPE_INVALID);
5d4f98a2
YZ
1956
1957 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1958 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1959 refs = btrfs_extent_data_ref_count(leaf, dref);
1960 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1961 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1962 refs = btrfs_shared_data_ref_count(leaf, sref);
1963 } else {
1964 refs = 1;
1965 BUG_ON(refs_to_mod != -1);
56bec294 1966 }
31840ae1 1967
5d4f98a2
YZ
1968 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1969 refs += refs_to_mod;
1970
1971 if (refs > 0) {
1972 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1973 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1974 else
1975 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1976 } else {
fcebe456 1977 *last_ref = 1;
5d4f98a2
YZ
1978 size = btrfs_extent_inline_ref_size(type);
1979 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1980 ptr = (unsigned long)iref;
1981 end = (unsigned long)ei + item_size;
1982 if (ptr + size < end)
1983 memmove_extent_buffer(leaf, ptr, ptr + size,
1984 end - ptr - size);
1985 item_size -= size;
87bde3cd 1986 btrfs_truncate_item(fs_info, path, item_size, 1);
5d4f98a2
YZ
1987 }
1988 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1989}
1990
1991static noinline_for_stack
1992int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
87bde3cd 1993 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
1994 struct btrfs_path *path,
1995 u64 bytenr, u64 num_bytes, u64 parent,
1996 u64 root_objectid, u64 owner,
1997 u64 offset, int refs_to_add,
1998 struct btrfs_delayed_extent_op *extent_op)
1999{
2000 struct btrfs_extent_inline_ref *iref;
2001 int ret;
2002
87bde3cd 2003 ret = lookup_inline_extent_backref(trans, fs_info, path, &iref,
5d4f98a2
YZ
2004 bytenr, num_bytes, parent,
2005 root_objectid, owner, offset, 1);
2006 if (ret == 0) {
2007 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
87bde3cd 2008 update_inline_extent_backref(fs_info, path, iref,
fcebe456 2009 refs_to_add, extent_op, NULL);
5d4f98a2 2010 } else if (ret == -ENOENT) {
87bde3cd 2011 setup_inline_extent_backref(fs_info, path, iref, parent,
143bede5
JM
2012 root_objectid, owner, offset,
2013 refs_to_add, extent_op);
2014 ret = 0;
771ed689 2015 }
5d4f98a2
YZ
2016 return ret;
2017}
31840ae1 2018
5d4f98a2 2019static int insert_extent_backref(struct btrfs_trans_handle *trans,
87bde3cd 2020 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2021 struct btrfs_path *path,
2022 u64 bytenr, u64 parent, u64 root_objectid,
2023 u64 owner, u64 offset, int refs_to_add)
2024{
2025 int ret;
2026 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2027 BUG_ON(refs_to_add != 1);
87bde3cd 2028 ret = insert_tree_block_ref(trans, fs_info, path, bytenr,
5d4f98a2
YZ
2029 parent, root_objectid);
2030 } else {
87bde3cd 2031 ret = insert_extent_data_ref(trans, fs_info, path, bytenr,
5d4f98a2
YZ
2032 parent, root_objectid,
2033 owner, offset, refs_to_add);
2034 }
2035 return ret;
2036}
56bec294 2037
5d4f98a2 2038static int remove_extent_backref(struct btrfs_trans_handle *trans,
87bde3cd 2039 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2040 struct btrfs_path *path,
2041 struct btrfs_extent_inline_ref *iref,
fcebe456 2042 int refs_to_drop, int is_data, int *last_ref)
5d4f98a2 2043{
143bede5 2044 int ret = 0;
b9473439 2045
5d4f98a2
YZ
2046 BUG_ON(!is_data && refs_to_drop != 1);
2047 if (iref) {
87bde3cd 2048 update_inline_extent_backref(fs_info, path, iref,
fcebe456 2049 -refs_to_drop, NULL, last_ref);
5d4f98a2 2050 } else if (is_data) {
87bde3cd 2051 ret = remove_extent_data_ref(trans, fs_info, path, refs_to_drop,
fcebe456 2052 last_ref);
5d4f98a2 2053 } else {
fcebe456 2054 *last_ref = 1;
87bde3cd 2055 ret = btrfs_del_item(trans, fs_info->extent_root, path);
5d4f98a2
YZ
2056 }
2057 return ret;
2058}
2059
86557861 2060#define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
d04c6b88
JM
2061static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
2062 u64 *discarded_bytes)
5d4f98a2 2063{
86557861
JM
2064 int j, ret = 0;
2065 u64 bytes_left, end;
4d89d377 2066 u64 aligned_start = ALIGN(start, 1 << 9);
d04c6b88 2067
4d89d377
JM
2068 if (WARN_ON(start != aligned_start)) {
2069 len -= aligned_start - start;
2070 len = round_down(len, 1 << 9);
2071 start = aligned_start;
2072 }
d04c6b88 2073
4d89d377 2074 *discarded_bytes = 0;
86557861
JM
2075
2076 if (!len)
2077 return 0;
2078
2079 end = start + len;
2080 bytes_left = len;
2081
2082 /* Skip any superblocks on this device. */
2083 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
2084 u64 sb_start = btrfs_sb_offset(j);
2085 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
2086 u64 size = sb_start - start;
2087
2088 if (!in_range(sb_start, start, bytes_left) &&
2089 !in_range(sb_end, start, bytes_left) &&
2090 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
2091 continue;
2092
2093 /*
2094 * Superblock spans beginning of range. Adjust start and
2095 * try again.
2096 */
2097 if (sb_start <= start) {
2098 start += sb_end - start;
2099 if (start > end) {
2100 bytes_left = 0;
2101 break;
2102 }
2103 bytes_left = end - start;
2104 continue;
2105 }
2106
2107 if (size) {
2108 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
2109 GFP_NOFS, 0);
2110 if (!ret)
2111 *discarded_bytes += size;
2112 else if (ret != -EOPNOTSUPP)
2113 return ret;
2114 }
2115
2116 start = sb_end;
2117 if (start > end) {
2118 bytes_left = 0;
2119 break;
2120 }
2121 bytes_left = end - start;
2122 }
2123
2124 if (bytes_left) {
2125 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
4d89d377
JM
2126 GFP_NOFS, 0);
2127 if (!ret)
86557861 2128 *discarded_bytes += bytes_left;
4d89d377 2129 }
d04c6b88 2130 return ret;
5d4f98a2 2131}
5d4f98a2 2132
2ff7e61e 2133int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1edb647b 2134 u64 num_bytes, u64 *actual_bytes)
5d4f98a2 2135{
5d4f98a2 2136 int ret;
5378e607 2137 u64 discarded_bytes = 0;
a1d3c478 2138 struct btrfs_bio *bbio = NULL;
5d4f98a2 2139
e244a0ae 2140
2999241d
FM
2141 /*
2142 * Avoid races with device replace and make sure our bbio has devices
2143 * associated to its stripes that don't go away while we are discarding.
2144 */
0b246afa 2145 btrfs_bio_counter_inc_blocked(fs_info);
5d4f98a2 2146 /* Tell the block device(s) that the sectors can be discarded */
0b246afa
JM
2147 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2148 &bbio, 0);
79787eaa 2149 /* Error condition is -ENOMEM */
5d4f98a2 2150 if (!ret) {
a1d3c478 2151 struct btrfs_bio_stripe *stripe = bbio->stripes;
5d4f98a2
YZ
2152 int i;
2153
5d4f98a2 2154
a1d3c478 2155 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
d04c6b88 2156 u64 bytes;
d5e2003c
JB
2157 if (!stripe->dev->can_discard)
2158 continue;
2159
5378e607
LD
2160 ret = btrfs_issue_discard(stripe->dev->bdev,
2161 stripe->physical,
d04c6b88
JM
2162 stripe->length,
2163 &bytes);
5378e607 2164 if (!ret)
d04c6b88 2165 discarded_bytes += bytes;
5378e607 2166 else if (ret != -EOPNOTSUPP)
79787eaa 2167 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
d5e2003c
JB
2168
2169 /*
2170 * Just in case we get back EOPNOTSUPP for some reason,
2171 * just ignore the return value so we don't screw up
2172 * people calling discard_extent.
2173 */
2174 ret = 0;
5d4f98a2 2175 }
6e9606d2 2176 btrfs_put_bbio(bbio);
5d4f98a2 2177 }
0b246afa 2178 btrfs_bio_counter_dec(fs_info);
5378e607
LD
2179
2180 if (actual_bytes)
2181 *actual_bytes = discarded_bytes;
2182
5d4f98a2 2183
53b381b3
DW
2184 if (ret == -EOPNOTSUPP)
2185 ret = 0;
5d4f98a2 2186 return ret;
5d4f98a2
YZ
2187}
2188
79787eaa 2189/* Can return -ENOMEM */
5d4f98a2 2190int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2ff7e61e 2191 struct btrfs_fs_info *fs_info,
5d4f98a2 2192 u64 bytenr, u64 num_bytes, u64 parent,
b06c4bf5 2193 u64 root_objectid, u64 owner, u64 offset)
5d4f98a2 2194{
d7eae340 2195 int old_ref_mod, new_ref_mod;
5d4f98a2 2196 int ret;
66d7e7f0 2197
5d4f98a2
YZ
2198 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2199 root_objectid == BTRFS_TREE_LOG_OBJECTID);
2200
2201 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0 2202 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7be07912
OS
2203 num_bytes, parent,
2204 root_objectid, (int)owner,
2205 BTRFS_ADD_DELAYED_REF, NULL,
d7eae340 2206 &old_ref_mod, &new_ref_mod);
5d4f98a2 2207 } else {
66d7e7f0 2208 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7be07912
OS
2209 num_bytes, parent,
2210 root_objectid, owner, offset,
d7eae340
OS
2211 0, BTRFS_ADD_DELAYED_REF,
2212 &old_ref_mod, &new_ref_mod);
5d4f98a2 2213 }
d7eae340
OS
2214
2215 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2216 add_pinned_bytes(fs_info, -num_bytes, owner, root_objectid);
2217
5d4f98a2
YZ
2218 return ret;
2219}
2220
2221static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2ff7e61e 2222 struct btrfs_fs_info *fs_info,
c682f9b3 2223 struct btrfs_delayed_ref_node *node,
5d4f98a2
YZ
2224 u64 parent, u64 root_objectid,
2225 u64 owner, u64 offset, int refs_to_add,
2226 struct btrfs_delayed_extent_op *extent_op)
2227{
2228 struct btrfs_path *path;
2229 struct extent_buffer *leaf;
2230 struct btrfs_extent_item *item;
fcebe456 2231 struct btrfs_key key;
c682f9b3
QW
2232 u64 bytenr = node->bytenr;
2233 u64 num_bytes = node->num_bytes;
5d4f98a2
YZ
2234 u64 refs;
2235 int ret;
5d4f98a2
YZ
2236
2237 path = btrfs_alloc_path();
2238 if (!path)
2239 return -ENOMEM;
2240
e4058b54 2241 path->reada = READA_FORWARD;
5d4f98a2
YZ
2242 path->leave_spinning = 1;
2243 /* this will setup the path even if it fails to insert the back ref */
87bde3cd
JM
2244 ret = insert_inline_extent_backref(trans, fs_info, path, bytenr,
2245 num_bytes, parent, root_objectid,
2246 owner, offset,
5d4f98a2 2247 refs_to_add, extent_op);
0ed4792a 2248 if ((ret < 0 && ret != -EAGAIN) || !ret)
5d4f98a2 2249 goto out;
fcebe456
JB
2250
2251 /*
2252 * Ok we had -EAGAIN which means we didn't have space to insert and
2253 * inline extent ref, so just update the reference count and add a
2254 * normal backref.
2255 */
5d4f98a2 2256 leaf = path->nodes[0];
fcebe456 2257 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5d4f98a2
YZ
2258 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2259 refs = btrfs_extent_refs(leaf, item);
2260 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2261 if (extent_op)
2262 __run_delayed_extent_op(extent_op, leaf, item);
56bec294 2263
5d4f98a2 2264 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 2265 btrfs_release_path(path);
56bec294 2266
e4058b54 2267 path->reada = READA_FORWARD;
b9473439 2268 path->leave_spinning = 1;
56bec294 2269 /* now insert the actual backref */
87bde3cd
JM
2270 ret = insert_extent_backref(trans, fs_info, path, bytenr, parent,
2271 root_objectid, owner, offset, refs_to_add);
79787eaa 2272 if (ret)
66642832 2273 btrfs_abort_transaction(trans, ret);
5d4f98a2 2274out:
56bec294 2275 btrfs_free_path(path);
30d133fc 2276 return ret;
56bec294
CM
2277}
2278
5d4f98a2 2279static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2ff7e61e 2280 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2281 struct btrfs_delayed_ref_node *node,
2282 struct btrfs_delayed_extent_op *extent_op,
2283 int insert_reserved)
56bec294 2284{
5d4f98a2
YZ
2285 int ret = 0;
2286 struct btrfs_delayed_data_ref *ref;
2287 struct btrfs_key ins;
2288 u64 parent = 0;
2289 u64 ref_root = 0;
2290 u64 flags = 0;
2291
2292 ins.objectid = node->bytenr;
2293 ins.offset = node->num_bytes;
2294 ins.type = BTRFS_EXTENT_ITEM_KEY;
2295
2296 ref = btrfs_delayed_node_to_data_ref(node);
0b246afa 2297 trace_run_delayed_data_ref(fs_info, node, ref, node->action);
599c75ec 2298
5d4f98a2
YZ
2299 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2300 parent = ref->parent;
fcebe456 2301 ref_root = ref->root;
5d4f98a2
YZ
2302
2303 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
3173a18f 2304 if (extent_op)
5d4f98a2 2305 flags |= extent_op->flags_to_set;
2ff7e61e 2306 ret = alloc_reserved_file_extent(trans, fs_info,
5d4f98a2
YZ
2307 parent, ref_root, flags,
2308 ref->objectid, ref->offset,
2309 &ins, node->ref_mod);
5d4f98a2 2310 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2ff7e61e 2311 ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
5d4f98a2
YZ
2312 ref_root, ref->objectid,
2313 ref->offset, node->ref_mod,
c682f9b3 2314 extent_op);
5d4f98a2 2315 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2ff7e61e 2316 ret = __btrfs_free_extent(trans, fs_info, node, parent,
5d4f98a2
YZ
2317 ref_root, ref->objectid,
2318 ref->offset, node->ref_mod,
c682f9b3 2319 extent_op);
5d4f98a2
YZ
2320 } else {
2321 BUG();
2322 }
2323 return ret;
2324}
2325
2326static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2327 struct extent_buffer *leaf,
2328 struct btrfs_extent_item *ei)
2329{
2330 u64 flags = btrfs_extent_flags(leaf, ei);
2331 if (extent_op->update_flags) {
2332 flags |= extent_op->flags_to_set;
2333 btrfs_set_extent_flags(leaf, ei, flags);
2334 }
2335
2336 if (extent_op->update_key) {
2337 struct btrfs_tree_block_info *bi;
2338 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2339 bi = (struct btrfs_tree_block_info *)(ei + 1);
2340 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2341 }
2342}
2343
2344static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2ff7e61e 2345 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2346 struct btrfs_delayed_ref_node *node,
2347 struct btrfs_delayed_extent_op *extent_op)
2348{
2349 struct btrfs_key key;
2350 struct btrfs_path *path;
2351 struct btrfs_extent_item *ei;
2352 struct extent_buffer *leaf;
2353 u32 item_size;
56bec294 2354 int ret;
5d4f98a2 2355 int err = 0;
b1c79e09 2356 int metadata = !extent_op->is_data;
5d4f98a2 2357
79787eaa
JM
2358 if (trans->aborted)
2359 return 0;
2360
0b246afa 2361 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
3173a18f
JB
2362 metadata = 0;
2363
5d4f98a2
YZ
2364 path = btrfs_alloc_path();
2365 if (!path)
2366 return -ENOMEM;
2367
2368 key.objectid = node->bytenr;
5d4f98a2 2369
3173a18f 2370 if (metadata) {
3173a18f 2371 key.type = BTRFS_METADATA_ITEM_KEY;
b1c79e09 2372 key.offset = extent_op->level;
3173a18f
JB
2373 } else {
2374 key.type = BTRFS_EXTENT_ITEM_KEY;
2375 key.offset = node->num_bytes;
2376 }
2377
2378again:
e4058b54 2379 path->reada = READA_FORWARD;
5d4f98a2 2380 path->leave_spinning = 1;
0b246afa 2381 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
5d4f98a2
YZ
2382 if (ret < 0) {
2383 err = ret;
2384 goto out;
2385 }
2386 if (ret > 0) {
3173a18f 2387 if (metadata) {
55994887
FDBM
2388 if (path->slots[0] > 0) {
2389 path->slots[0]--;
2390 btrfs_item_key_to_cpu(path->nodes[0], &key,
2391 path->slots[0]);
2392 if (key.objectid == node->bytenr &&
2393 key.type == BTRFS_EXTENT_ITEM_KEY &&
2394 key.offset == node->num_bytes)
2395 ret = 0;
2396 }
2397 if (ret > 0) {
2398 btrfs_release_path(path);
2399 metadata = 0;
3173a18f 2400
55994887
FDBM
2401 key.objectid = node->bytenr;
2402 key.offset = node->num_bytes;
2403 key.type = BTRFS_EXTENT_ITEM_KEY;
2404 goto again;
2405 }
2406 } else {
2407 err = -EIO;
2408 goto out;
3173a18f 2409 }
5d4f98a2
YZ
2410 }
2411
2412 leaf = path->nodes[0];
2413 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2414#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2415 if (item_size < sizeof(*ei)) {
87bde3cd 2416 ret = convert_extent_item_v0(trans, fs_info, path, (u64)-1, 0);
5d4f98a2
YZ
2417 if (ret < 0) {
2418 err = ret;
2419 goto out;
2420 }
2421 leaf = path->nodes[0];
2422 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2423 }
2424#endif
2425 BUG_ON(item_size < sizeof(*ei));
2426 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2427 __run_delayed_extent_op(extent_op, leaf, ei);
56bec294 2428
5d4f98a2
YZ
2429 btrfs_mark_buffer_dirty(leaf);
2430out:
2431 btrfs_free_path(path);
2432 return err;
56bec294
CM
2433}
2434
5d4f98a2 2435static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2ff7e61e 2436 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2437 struct btrfs_delayed_ref_node *node,
2438 struct btrfs_delayed_extent_op *extent_op,
2439 int insert_reserved)
56bec294
CM
2440{
2441 int ret = 0;
5d4f98a2
YZ
2442 struct btrfs_delayed_tree_ref *ref;
2443 struct btrfs_key ins;
2444 u64 parent = 0;
2445 u64 ref_root = 0;
0b246afa 2446 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
56bec294 2447
5d4f98a2 2448 ref = btrfs_delayed_node_to_tree_ref(node);
0b246afa 2449 trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
599c75ec 2450
5d4f98a2
YZ
2451 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2452 parent = ref->parent;
fcebe456 2453 ref_root = ref->root;
5d4f98a2 2454
3173a18f
JB
2455 ins.objectid = node->bytenr;
2456 if (skinny_metadata) {
2457 ins.offset = ref->level;
2458 ins.type = BTRFS_METADATA_ITEM_KEY;
2459 } else {
2460 ins.offset = node->num_bytes;
2461 ins.type = BTRFS_EXTENT_ITEM_KEY;
2462 }
2463
02794222 2464 if (node->ref_mod != 1) {
2ff7e61e 2465 btrfs_err(fs_info,
02794222
LB
2466 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2467 node->bytenr, node->ref_mod, node->action, ref_root,
2468 parent);
2469 return -EIO;
2470 }
5d4f98a2 2471 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
3173a18f 2472 BUG_ON(!extent_op || !extent_op->update_flags);
2ff7e61e 2473 ret = alloc_reserved_tree_block(trans, fs_info,
5d4f98a2
YZ
2474 parent, ref_root,
2475 extent_op->flags_to_set,
2476 &extent_op->key,
b06c4bf5 2477 ref->level, &ins);
5d4f98a2 2478 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2ff7e61e 2479 ret = __btrfs_inc_extent_ref(trans, fs_info, node,
c682f9b3
QW
2480 parent, ref_root,
2481 ref->level, 0, 1,
fcebe456 2482 extent_op);
5d4f98a2 2483 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2ff7e61e 2484 ret = __btrfs_free_extent(trans, fs_info, node,
c682f9b3
QW
2485 parent, ref_root,
2486 ref->level, 0, 1, extent_op);
5d4f98a2
YZ
2487 } else {
2488 BUG();
2489 }
56bec294
CM
2490 return ret;
2491}
2492
2493/* helper function to actually process a single delayed ref entry */
5d4f98a2 2494static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2ff7e61e 2495 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2496 struct btrfs_delayed_ref_node *node,
2497 struct btrfs_delayed_extent_op *extent_op,
2498 int insert_reserved)
56bec294 2499{
79787eaa
JM
2500 int ret = 0;
2501
857cc2fc
JB
2502 if (trans->aborted) {
2503 if (insert_reserved)
2ff7e61e 2504 btrfs_pin_extent(fs_info, node->bytenr,
857cc2fc 2505 node->num_bytes, 1);
79787eaa 2506 return 0;
857cc2fc 2507 }
79787eaa 2508
5d4f98a2 2509 if (btrfs_delayed_ref_is_head(node)) {
56bec294
CM
2510 struct btrfs_delayed_ref_head *head;
2511 /*
2512 * we've hit the end of the chain and we were supposed
2513 * to insert this extent into the tree. But, it got
2514 * deleted before we ever needed to insert it, so all
2515 * we have to do is clean up the accounting
2516 */
5d4f98a2
YZ
2517 BUG_ON(extent_op);
2518 head = btrfs_delayed_node_to_head(node);
0b246afa 2519 trace_run_delayed_ref_head(fs_info, node, head, node->action);
599c75ec 2520
d7eae340
OS
2521 if (head->total_ref_mod < 0) {
2522 struct btrfs_block_group_cache *cache;
2523
2524 cache = btrfs_lookup_block_group(fs_info, node->bytenr);
2525 ASSERT(cache);
2526 percpu_counter_add(&cache->space_info->total_bytes_pinned,
2527 -node->num_bytes);
2528 btrfs_put_block_group(cache);
2529 }
2530
56bec294 2531 if (insert_reserved) {
2ff7e61e 2532 btrfs_pin_extent(fs_info, node->bytenr,
f0486c68 2533 node->num_bytes, 1);
5d4f98a2 2534 if (head->is_data) {
0b246afa 2535 ret = btrfs_del_csums(trans, fs_info,
5d4f98a2
YZ
2536 node->bytenr,
2537 node->num_bytes);
5d4f98a2 2538 }
56bec294 2539 }
297d750b
QW
2540
2541 /* Also free its reserved qgroup space */
0b246afa 2542 btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
297d750b 2543 head->qgroup_reserved);
79787eaa 2544 return ret;
56bec294
CM
2545 }
2546
5d4f98a2
YZ
2547 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2548 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2ff7e61e 2549 ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
5d4f98a2
YZ
2550 insert_reserved);
2551 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2552 node->type == BTRFS_SHARED_DATA_REF_KEY)
2ff7e61e 2553 ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
5d4f98a2
YZ
2554 insert_reserved);
2555 else
2556 BUG();
2557 return ret;
56bec294
CM
2558}
2559
c6fc2454 2560static inline struct btrfs_delayed_ref_node *
56bec294
CM
2561select_delayed_ref(struct btrfs_delayed_ref_head *head)
2562{
cffc3374
FM
2563 struct btrfs_delayed_ref_node *ref;
2564
c6fc2454
QW
2565 if (list_empty(&head->ref_list))
2566 return NULL;
d7df2c79 2567
cffc3374
FM
2568 /*
2569 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2570 * This is to prevent a ref count from going down to zero, which deletes
2571 * the extent item from the extent tree, when there still are references
2572 * to add, which would fail because they would not find the extent item.
2573 */
1d57ee94
WX
2574 if (!list_empty(&head->ref_add_list))
2575 return list_first_entry(&head->ref_add_list,
2576 struct btrfs_delayed_ref_node, add_list);
2577
2578 ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
2579 list);
2580 ASSERT(list_empty(&ref->add_list));
2581 return ref;
56bec294
CM
2582}
2583
79787eaa
JM
2584/*
2585 * Returns 0 on success or if called with an already aborted transaction.
2586 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2587 */
d7df2c79 2588static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2ff7e61e 2589 struct btrfs_fs_info *fs_info,
d7df2c79 2590 unsigned long nr)
56bec294 2591{
56bec294
CM
2592 struct btrfs_delayed_ref_root *delayed_refs;
2593 struct btrfs_delayed_ref_node *ref;
2594 struct btrfs_delayed_ref_head *locked_ref = NULL;
5d4f98a2 2595 struct btrfs_delayed_extent_op *extent_op;
0a2b2a84 2596 ktime_t start = ktime_get();
56bec294 2597 int ret;
d7df2c79 2598 unsigned long count = 0;
0a2b2a84 2599 unsigned long actual_count = 0;
56bec294 2600 int must_insert_reserved = 0;
56bec294
CM
2601
2602 delayed_refs = &trans->transaction->delayed_refs;
56bec294
CM
2603 while (1) {
2604 if (!locked_ref) {
d7df2c79 2605 if (count >= nr)
56bec294 2606 break;
56bec294 2607
d7df2c79
JB
2608 spin_lock(&delayed_refs->lock);
2609 locked_ref = btrfs_select_ref_head(trans);
2610 if (!locked_ref) {
2611 spin_unlock(&delayed_refs->lock);
2612 break;
2613 }
c3e69d58
CM
2614
2615 /* grab the lock that says we are going to process
2616 * all the refs for this head */
2617 ret = btrfs_delayed_ref_lock(trans, locked_ref);
d7df2c79 2618 spin_unlock(&delayed_refs->lock);
c3e69d58
CM
2619 /*
2620 * we may have dropped the spin lock to get the head
2621 * mutex lock, and that might have given someone else
2622 * time to free the head. If that's true, it has been
2623 * removed from our list and we can move on.
2624 */
2625 if (ret == -EAGAIN) {
2626 locked_ref = NULL;
2627 count++;
2628 continue;
56bec294
CM
2629 }
2630 }
a28ec197 2631
2c3cf7d5
FM
2632 /*
2633 * We need to try and merge add/drops of the same ref since we
2634 * can run into issues with relocate dropping the implicit ref
2635 * and then it being added back again before the drop can
2636 * finish. If we merged anything we need to re-loop so we can
2637 * get a good ref.
2638 * Or we can get node references of the same type that weren't
2639 * merged when created due to bumps in the tree mod seq, and
2640 * we need to merge them to prevent adding an inline extent
2641 * backref before dropping it (triggering a BUG_ON at
2642 * insert_inline_extent_backref()).
2643 */
d7df2c79 2644 spin_lock(&locked_ref->lock);
2c3cf7d5
FM
2645 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2646 locked_ref);
ae1e206b 2647
d1270cd9
AJ
2648 /*
2649 * locked_ref is the head node, so we have to go one
2650 * node back for any delayed ref updates
2651 */
2652 ref = select_delayed_ref(locked_ref);
2653
2654 if (ref && ref->seq &&
097b8a7c 2655 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
d7df2c79 2656 spin_unlock(&locked_ref->lock);
d7df2c79
JB
2657 spin_lock(&delayed_refs->lock);
2658 locked_ref->processing = 0;
d1270cd9
AJ
2659 delayed_refs->num_heads_ready++;
2660 spin_unlock(&delayed_refs->lock);
d0280996 2661 btrfs_delayed_ref_unlock(locked_ref);
d7df2c79 2662 locked_ref = NULL;
d1270cd9 2663 cond_resched();
27a377db 2664 count++;
d1270cd9
AJ
2665 continue;
2666 }
2667
56bec294
CM
2668 /*
2669 * record the must insert reserved flag before we
2670 * drop the spin lock.
2671 */
2672 must_insert_reserved = locked_ref->must_insert_reserved;
2673 locked_ref->must_insert_reserved = 0;
7bb86316 2674
5d4f98a2
YZ
2675 extent_op = locked_ref->extent_op;
2676 locked_ref->extent_op = NULL;
2677
56bec294 2678 if (!ref) {
d7df2c79
JB
2679
2680
56bec294
CM
2681 /* All delayed refs have been processed, Go ahead
2682 * and send the head node to run_one_delayed_ref,
2683 * so that any accounting fixes can happen
2684 */
2685 ref = &locked_ref->node;
5d4f98a2
YZ
2686
2687 if (extent_op && must_insert_reserved) {
78a6184a 2688 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
2689 extent_op = NULL;
2690 }
2691
2692 if (extent_op) {
d7df2c79 2693 spin_unlock(&locked_ref->lock);
2ff7e61e 2694 ret = run_delayed_extent_op(trans, fs_info,
5d4f98a2 2695 ref, extent_op);
78a6184a 2696 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2 2697
79787eaa 2698 if (ret) {
857cc2fc
JB
2699 /*
2700 * Need to reset must_insert_reserved if
2701 * there was an error so the abort stuff
2702 * can cleanup the reserved space
2703 * properly.
2704 */
2705 if (must_insert_reserved)
2706 locked_ref->must_insert_reserved = 1;
aa7c8da3 2707 spin_lock(&delayed_refs->lock);
d7df2c79 2708 locked_ref->processing = 0;
aa7c8da3
JM
2709 delayed_refs->num_heads_ready++;
2710 spin_unlock(&delayed_refs->lock);
5d163e0e
JM
2711 btrfs_debug(fs_info,
2712 "run_delayed_extent_op returned %d",
2713 ret);
093486c4 2714 btrfs_delayed_ref_unlock(locked_ref);
79787eaa
JM
2715 return ret;
2716 }
d7df2c79 2717 continue;
5d4f98a2 2718 }
02217ed2 2719
d7df2c79 2720 /*
01327610 2721 * Need to drop our head ref lock and re-acquire the
d7df2c79
JB
2722 * delayed ref lock and then re-check to make sure
2723 * nobody got added.
2724 */
2725 spin_unlock(&locked_ref->lock);
2726 spin_lock(&delayed_refs->lock);
2727 spin_lock(&locked_ref->lock);
c6fc2454 2728 if (!list_empty(&locked_ref->ref_list) ||
573a0755 2729 locked_ref->extent_op) {
d7df2c79
JB
2730 spin_unlock(&locked_ref->lock);
2731 spin_unlock(&delayed_refs->lock);
2732 continue;
2733 }
2734 ref->in_tree = 0;
2735 delayed_refs->num_heads--;
c46effa6
LB
2736 rb_erase(&locked_ref->href_node,
2737 &delayed_refs->href_root);
d7df2c79
JB
2738 spin_unlock(&delayed_refs->lock);
2739 } else {
0a2b2a84 2740 actual_count++;
d7df2c79 2741 ref->in_tree = 0;
c6fc2454 2742 list_del(&ref->list);
1d57ee94
WX
2743 if (!list_empty(&ref->add_list))
2744 list_del(&ref->add_list);
c46effa6 2745 }
d7df2c79
JB
2746 atomic_dec(&delayed_refs->num_entries);
2747
093486c4 2748 if (!btrfs_delayed_ref_is_head(ref)) {
22cd2e7d
AJ
2749 /*
2750 * when we play the delayed ref, also correct the
2751 * ref_mod on head
2752 */
2753 switch (ref->action) {
2754 case BTRFS_ADD_DELAYED_REF:
2755 case BTRFS_ADD_DELAYED_EXTENT:
2756 locked_ref->node.ref_mod -= ref->ref_mod;
2757 break;
2758 case BTRFS_DROP_DELAYED_REF:
2759 locked_ref->node.ref_mod += ref->ref_mod;
2760 break;
2761 default:
2762 WARN_ON(1);
2763 }
2764 }
d7df2c79 2765 spin_unlock(&locked_ref->lock);
925baedd 2766
2ff7e61e 2767 ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
56bec294 2768 must_insert_reserved);
eb099670 2769
78a6184a 2770 btrfs_free_delayed_extent_op(extent_op);
79787eaa 2771 if (ret) {
9d1032cc 2772 spin_lock(&delayed_refs->lock);
d7df2c79 2773 locked_ref->processing = 0;
9d1032cc
WX
2774 delayed_refs->num_heads_ready++;
2775 spin_unlock(&delayed_refs->lock);
093486c4
MX
2776 btrfs_delayed_ref_unlock(locked_ref);
2777 btrfs_put_delayed_ref(ref);
5d163e0e
JM
2778 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2779 ret);
79787eaa
JM
2780 return ret;
2781 }
2782
093486c4
MX
2783 /*
2784 * If this node is a head, that means all the refs in this head
2785 * have been dealt with, and we will pick the next head to deal
2786 * with, so we must unlock the head and drop it from the cluster
2787 * list before we release it.
2788 */
2789 if (btrfs_delayed_ref_is_head(ref)) {
1262133b
JB
2790 if (locked_ref->is_data &&
2791 locked_ref->total_ref_mod < 0) {
2792 spin_lock(&delayed_refs->lock);
2793 delayed_refs->pending_csums -= ref->num_bytes;
2794 spin_unlock(&delayed_refs->lock);
2795 }
093486c4
MX
2796 btrfs_delayed_ref_unlock(locked_ref);
2797 locked_ref = NULL;
2798 }
2799 btrfs_put_delayed_ref(ref);
2800 count++;
c3e69d58 2801 cond_resched();
c3e69d58 2802 }
0a2b2a84
JB
2803
2804 /*
2805 * We don't want to include ref heads since we can have empty ref heads
2806 * and those will drastically skew our runtime down since we just do
2807 * accounting, no actual extent tree updates.
2808 */
2809 if (actual_count > 0) {
2810 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2811 u64 avg;
2812
2813 /*
2814 * We weigh the current average higher than our current runtime
2815 * to avoid large swings in the average.
2816 */
2817 spin_lock(&delayed_refs->lock);
2818 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
f8c269d7 2819 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
0a2b2a84
JB
2820 spin_unlock(&delayed_refs->lock);
2821 }
d7df2c79 2822 return 0;
c3e69d58
CM
2823}
2824
709c0486
AJ
2825#ifdef SCRAMBLE_DELAYED_REFS
2826/*
2827 * Normally delayed refs get processed in ascending bytenr order. This
2828 * correlates in most cases to the order added. To expose dependencies on this
2829 * order, we start to process the tree in the middle instead of the beginning
2830 */
2831static u64 find_middle(struct rb_root *root)
2832{
2833 struct rb_node *n = root->rb_node;
2834 struct btrfs_delayed_ref_node *entry;
2835 int alt = 1;
2836 u64 middle;
2837 u64 first = 0, last = 0;
2838
2839 n = rb_first(root);
2840 if (n) {
2841 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2842 first = entry->bytenr;
2843 }
2844 n = rb_last(root);
2845 if (n) {
2846 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2847 last = entry->bytenr;
2848 }
2849 n = root->rb_node;
2850
2851 while (n) {
2852 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2853 WARN_ON(!entry->in_tree);
2854
2855 middle = entry->bytenr;
2856
2857 if (alt)
2858 n = n->rb_left;
2859 else
2860 n = n->rb_right;
2861
2862 alt = 1 - alt;
2863 }
2864 return middle;
2865}
2866#endif
2867
2ff7e61e 2868static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
1be41b78
JB
2869{
2870 u64 num_bytes;
2871
2872 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2873 sizeof(struct btrfs_extent_inline_ref));
0b246afa 2874 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1be41b78
JB
2875 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2876
2877 /*
2878 * We don't ever fill up leaves all the way so multiply by 2 just to be
01327610 2879 * closer to what we're really going to want to use.
1be41b78 2880 */
0b246afa 2881 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
1be41b78
JB
2882}
2883
1262133b
JB
2884/*
2885 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2886 * would require to store the csums for that many bytes.
2887 */
2ff7e61e 2888u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
1262133b
JB
2889{
2890 u64 csum_size;
2891 u64 num_csums_per_leaf;
2892 u64 num_csums;
2893
0b246afa 2894 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
1262133b 2895 num_csums_per_leaf = div64_u64(csum_size,
0b246afa
JM
2896 (u64)btrfs_super_csum_size(fs_info->super_copy));
2897 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
1262133b
JB
2898 num_csums += num_csums_per_leaf - 1;
2899 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2900 return num_csums;
2901}
2902
0a2b2a84 2903int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2ff7e61e 2904 struct btrfs_fs_info *fs_info)
1be41b78
JB
2905{
2906 struct btrfs_block_rsv *global_rsv;
2907 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
1262133b 2908 u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
cb723e49
JB
2909 u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2910 u64 num_bytes, num_dirty_bgs_bytes;
1be41b78
JB
2911 int ret = 0;
2912
0b246afa 2913 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2ff7e61e 2914 num_heads = heads_to_leaves(fs_info, num_heads);
1be41b78 2915 if (num_heads > 1)
0b246afa 2916 num_bytes += (num_heads - 1) * fs_info->nodesize;
1be41b78 2917 num_bytes <<= 1;
2ff7e61e
JM
2918 num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2919 fs_info->nodesize;
0b246afa 2920 num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
cb723e49 2921 num_dirty_bgs);
0b246afa 2922 global_rsv = &fs_info->global_block_rsv;
1be41b78
JB
2923
2924 /*
2925 * If we can't allocate any more chunks lets make sure we have _lots_ of
2926 * wiggle room since running delayed refs can create more delayed refs.
2927 */
cb723e49
JB
2928 if (global_rsv->space_info->full) {
2929 num_dirty_bgs_bytes <<= 1;
1be41b78 2930 num_bytes <<= 1;
cb723e49 2931 }
1be41b78
JB
2932
2933 spin_lock(&global_rsv->lock);
cb723e49 2934 if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
1be41b78
JB
2935 ret = 1;
2936 spin_unlock(&global_rsv->lock);
2937 return ret;
2938}
2939
0a2b2a84 2940int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2ff7e61e 2941 struct btrfs_fs_info *fs_info)
0a2b2a84 2942{
0a2b2a84
JB
2943 u64 num_entries =
2944 atomic_read(&trans->transaction->delayed_refs.num_entries);
2945 u64 avg_runtime;
a79b7d4b 2946 u64 val;
0a2b2a84
JB
2947
2948 smp_mb();
2949 avg_runtime = fs_info->avg_delayed_ref_runtime;
a79b7d4b 2950 val = num_entries * avg_runtime;
dc1a90c6 2951 if (val >= NSEC_PER_SEC)
0a2b2a84 2952 return 1;
a79b7d4b
CM
2953 if (val >= NSEC_PER_SEC / 2)
2954 return 2;
0a2b2a84 2955
2ff7e61e 2956 return btrfs_check_space_for_delayed_refs(trans, fs_info);
0a2b2a84
JB
2957}
2958
a79b7d4b
CM
2959struct async_delayed_refs {
2960 struct btrfs_root *root;
31b9655f 2961 u64 transid;
a79b7d4b
CM
2962 int count;
2963 int error;
2964 int sync;
2965 struct completion wait;
2966 struct btrfs_work work;
2967};
2968
2ff7e61e
JM
2969static inline struct async_delayed_refs *
2970to_async_delayed_refs(struct btrfs_work *work)
2971{
2972 return container_of(work, struct async_delayed_refs, work);
2973}
2974
a79b7d4b
CM
2975static void delayed_ref_async_start(struct btrfs_work *work)
2976{
2ff7e61e 2977 struct async_delayed_refs *async = to_async_delayed_refs(work);
a79b7d4b 2978 struct btrfs_trans_handle *trans;
2ff7e61e 2979 struct btrfs_fs_info *fs_info = async->root->fs_info;
a79b7d4b
CM
2980 int ret;
2981
0f873eca 2982 /* if the commit is already started, we don't need to wait here */
2ff7e61e 2983 if (btrfs_transaction_blocked(fs_info))
31b9655f 2984 goto done;
31b9655f 2985
0f873eca
CM
2986 trans = btrfs_join_transaction(async->root);
2987 if (IS_ERR(trans)) {
2988 async->error = PTR_ERR(trans);
a79b7d4b
CM
2989 goto done;
2990 }
2991
2992 /*
01327610 2993 * trans->sync means that when we call end_transaction, we won't
a79b7d4b
CM
2994 * wait on delayed refs
2995 */
2996 trans->sync = true;
0f873eca
CM
2997
2998 /* Don't bother flushing if we got into a different transaction */
2999 if (trans->transid > async->transid)
3000 goto end;
3001
2ff7e61e 3002 ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
a79b7d4b
CM
3003 if (ret)
3004 async->error = ret;
0f873eca 3005end:
3a45bb20 3006 ret = btrfs_end_transaction(trans);
a79b7d4b
CM
3007 if (ret && !async->error)
3008 async->error = ret;
3009done:
3010 if (async->sync)
3011 complete(&async->wait);
3012 else
3013 kfree(async);
3014}
3015
2ff7e61e 3016int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
31b9655f 3017 unsigned long count, u64 transid, int wait)
a79b7d4b
CM
3018{
3019 struct async_delayed_refs *async;
3020 int ret;
3021
3022 async = kmalloc(sizeof(*async), GFP_NOFS);
3023 if (!async)
3024 return -ENOMEM;
3025
0b246afa 3026 async->root = fs_info->tree_root;
a79b7d4b
CM
3027 async->count = count;
3028 async->error = 0;
31b9655f 3029 async->transid = transid;
a79b7d4b
CM
3030 if (wait)
3031 async->sync = 1;
3032 else
3033 async->sync = 0;
3034 init_completion(&async->wait);
3035
9e0af237
LB
3036 btrfs_init_work(&async->work, btrfs_extent_refs_helper,
3037 delayed_ref_async_start, NULL, NULL);
a79b7d4b 3038
0b246afa 3039 btrfs_queue_work(fs_info->extent_workers, &async->work);
a79b7d4b
CM
3040
3041 if (wait) {
3042 wait_for_completion(&async->wait);
3043 ret = async->error;
3044 kfree(async);
3045 return ret;
3046 }
3047 return 0;
3048}
3049
c3e69d58
CM
3050/*
3051 * this starts processing the delayed reference count updates and
3052 * extent insertions we have queued up so far. count can be
3053 * 0, which means to process everything in the tree at the start
3054 * of the run (but not newly added entries), or it can be some target
3055 * number you'd like to process.
79787eaa
JM
3056 *
3057 * Returns 0 on success or if called with an aborted transaction
3058 * Returns <0 on error and aborts the transaction
c3e69d58
CM
3059 */
3060int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2ff7e61e 3061 struct btrfs_fs_info *fs_info, unsigned long count)
c3e69d58
CM
3062{
3063 struct rb_node *node;
3064 struct btrfs_delayed_ref_root *delayed_refs;
c46effa6 3065 struct btrfs_delayed_ref_head *head;
c3e69d58
CM
3066 int ret;
3067 int run_all = count == (unsigned long)-1;
d9a0540a 3068 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
c3e69d58 3069
79787eaa
JM
3070 /* We'll clean this up in btrfs_cleanup_transaction */
3071 if (trans->aborted)
3072 return 0;
3073
0b246afa 3074 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
511711af
CM
3075 return 0;
3076
c3e69d58 3077 delayed_refs = &trans->transaction->delayed_refs;
26455d33 3078 if (count == 0)
d7df2c79 3079 count = atomic_read(&delayed_refs->num_entries) * 2;
bb721703 3080
c3e69d58 3081again:
709c0486
AJ
3082#ifdef SCRAMBLE_DELAYED_REFS
3083 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
3084#endif
d9a0540a 3085 trans->can_flush_pending_bgs = false;
2ff7e61e 3086 ret = __btrfs_run_delayed_refs(trans, fs_info, count);
d7df2c79 3087 if (ret < 0) {
66642832 3088 btrfs_abort_transaction(trans, ret);
d7df2c79 3089 return ret;
eb099670 3090 }
c3e69d58 3091
56bec294 3092 if (run_all) {
d7df2c79 3093 if (!list_empty(&trans->new_bgs))
2ff7e61e 3094 btrfs_create_pending_block_groups(trans, fs_info);
ea658bad 3095
d7df2c79 3096 spin_lock(&delayed_refs->lock);
c46effa6 3097 node = rb_first(&delayed_refs->href_root);
d7df2c79
JB
3098 if (!node) {
3099 spin_unlock(&delayed_refs->lock);
56bec294 3100 goto out;
d7df2c79 3101 }
e9d0b13b 3102
56bec294 3103 while (node) {
c46effa6
LB
3104 head = rb_entry(node, struct btrfs_delayed_ref_head,
3105 href_node);
3106 if (btrfs_delayed_ref_is_head(&head->node)) {
3107 struct btrfs_delayed_ref_node *ref;
5caf2a00 3108
c46effa6 3109 ref = &head->node;
6df8cdf5 3110 refcount_inc(&ref->refs);
56bec294
CM
3111
3112 spin_unlock(&delayed_refs->lock);
8cc33e5c
DS
3113 /*
3114 * Mutex was contended, block until it's
3115 * released and try again
3116 */
56bec294
CM
3117 mutex_lock(&head->mutex);
3118 mutex_unlock(&head->mutex);
3119
3120 btrfs_put_delayed_ref(ref);
1887be66 3121 cond_resched();
56bec294 3122 goto again;
c46effa6
LB
3123 } else {
3124 WARN_ON(1);
56bec294
CM
3125 }
3126 node = rb_next(node);
3127 }
3128 spin_unlock(&delayed_refs->lock);
d7df2c79 3129 cond_resched();
56bec294 3130 goto again;
5f39d397 3131 }
54aa1f4d 3132out:
d9a0540a 3133 trans->can_flush_pending_bgs = can_flush_pending_bgs;
a28ec197
CM
3134 return 0;
3135}
3136
5d4f98a2 3137int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2ff7e61e 3138 struct btrfs_fs_info *fs_info,
5d4f98a2 3139 u64 bytenr, u64 num_bytes, u64 flags,
b1c79e09 3140 int level, int is_data)
5d4f98a2
YZ
3141{
3142 struct btrfs_delayed_extent_op *extent_op;
3143 int ret;
3144
78a6184a 3145 extent_op = btrfs_alloc_delayed_extent_op();
5d4f98a2
YZ
3146 if (!extent_op)
3147 return -ENOMEM;
3148
3149 extent_op->flags_to_set = flags;
35b3ad50
DS
3150 extent_op->update_flags = true;
3151 extent_op->update_key = false;
3152 extent_op->is_data = is_data ? true : false;
b1c79e09 3153 extent_op->level = level;
5d4f98a2 3154
0b246afa 3155 ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
66d7e7f0 3156 num_bytes, extent_op);
5d4f98a2 3157 if (ret)
78a6184a 3158 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
3159 return ret;
3160}
3161
e4c3b2dc 3162static noinline int check_delayed_ref(struct btrfs_root *root,
5d4f98a2
YZ
3163 struct btrfs_path *path,
3164 u64 objectid, u64 offset, u64 bytenr)
3165{
3166 struct btrfs_delayed_ref_head *head;
3167 struct btrfs_delayed_ref_node *ref;
3168 struct btrfs_delayed_data_ref *data_ref;
3169 struct btrfs_delayed_ref_root *delayed_refs;
e4c3b2dc 3170 struct btrfs_transaction *cur_trans;
5d4f98a2
YZ
3171 int ret = 0;
3172
b0e5b437 3173 spin_lock(&root->fs_info->trans_lock);
e4c3b2dc 3174 cur_trans = root->fs_info->running_transaction;
b0e5b437 3175 if (cur_trans)
3176 refcount_inc(&cur_trans->use_count);
3177 spin_unlock(&root->fs_info->trans_lock);
e4c3b2dc
LB
3178 if (!cur_trans)
3179 return 0;
3180
3181 delayed_refs = &cur_trans->delayed_refs;
5d4f98a2 3182 spin_lock(&delayed_refs->lock);
f72ad18e 3183 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
d7df2c79
JB
3184 if (!head) {
3185 spin_unlock(&delayed_refs->lock);
b0e5b437 3186 btrfs_put_transaction(cur_trans);
d7df2c79
JB
3187 return 0;
3188 }
5d4f98a2
YZ
3189
3190 if (!mutex_trylock(&head->mutex)) {
6df8cdf5 3191 refcount_inc(&head->node.refs);
5d4f98a2
YZ
3192 spin_unlock(&delayed_refs->lock);
3193
b3b4aa74 3194 btrfs_release_path(path);
5d4f98a2 3195
8cc33e5c
DS
3196 /*
3197 * Mutex was contended, block until it's released and let
3198 * caller try again
3199 */
5d4f98a2
YZ
3200 mutex_lock(&head->mutex);
3201 mutex_unlock(&head->mutex);
3202 btrfs_put_delayed_ref(&head->node);
b0e5b437 3203 btrfs_put_transaction(cur_trans);
5d4f98a2
YZ
3204 return -EAGAIN;
3205 }
d7df2c79 3206 spin_unlock(&delayed_refs->lock);
5d4f98a2 3207
d7df2c79 3208 spin_lock(&head->lock);
c6fc2454 3209 list_for_each_entry(ref, &head->ref_list, list) {
d7df2c79
JB
3210 /* If it's a shared ref we know a cross reference exists */
3211 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3212 ret = 1;
3213 break;
3214 }
5d4f98a2 3215
d7df2c79 3216 data_ref = btrfs_delayed_node_to_data_ref(ref);
5d4f98a2 3217
d7df2c79
JB
3218 /*
3219 * If our ref doesn't match the one we're currently looking at
3220 * then we have a cross reference.
3221 */
3222 if (data_ref->root != root->root_key.objectid ||
3223 data_ref->objectid != objectid ||
3224 data_ref->offset != offset) {
3225 ret = 1;
3226 break;
3227 }
5d4f98a2 3228 }
d7df2c79 3229 spin_unlock(&head->lock);
5d4f98a2 3230 mutex_unlock(&head->mutex);
b0e5b437 3231 btrfs_put_transaction(cur_trans);
5d4f98a2
YZ
3232 return ret;
3233}
3234
e4c3b2dc 3235static noinline int check_committed_ref(struct btrfs_root *root,
5d4f98a2
YZ
3236 struct btrfs_path *path,
3237 u64 objectid, u64 offset, u64 bytenr)
be20aa9d 3238{
0b246afa
JM
3239 struct btrfs_fs_info *fs_info = root->fs_info;
3240 struct btrfs_root *extent_root = fs_info->extent_root;
f321e491 3241 struct extent_buffer *leaf;
5d4f98a2
YZ
3242 struct btrfs_extent_data_ref *ref;
3243 struct btrfs_extent_inline_ref *iref;
3244 struct btrfs_extent_item *ei;
f321e491 3245 struct btrfs_key key;
5d4f98a2 3246 u32 item_size;
3de28d57 3247 int type;
be20aa9d 3248 int ret;
925baedd 3249
be20aa9d 3250 key.objectid = bytenr;
31840ae1 3251 key.offset = (u64)-1;
f321e491 3252 key.type = BTRFS_EXTENT_ITEM_KEY;
be20aa9d 3253
be20aa9d
CM
3254 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3255 if (ret < 0)
3256 goto out;
79787eaa 3257 BUG_ON(ret == 0); /* Corruption */
80ff3856
YZ
3258
3259 ret = -ENOENT;
3260 if (path->slots[0] == 0)
31840ae1 3261 goto out;
be20aa9d 3262
31840ae1 3263 path->slots[0]--;
f321e491 3264 leaf = path->nodes[0];
5d4f98a2 3265 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
be20aa9d 3266
5d4f98a2 3267 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
be20aa9d 3268 goto out;
f321e491 3269
5d4f98a2
YZ
3270 ret = 1;
3271 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3272#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3273 if (item_size < sizeof(*ei)) {
3274 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3275 goto out;
3276 }
3277#endif
3278 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
bd09835d 3279
5d4f98a2
YZ
3280 if (item_size != sizeof(*ei) +
3281 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3282 goto out;
be20aa9d 3283
5d4f98a2
YZ
3284 if (btrfs_extent_generation(leaf, ei) <=
3285 btrfs_root_last_snapshot(&root->root_item))
3286 goto out;
3287
3288 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3de28d57
LB
3289
3290 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3291 if (type != BTRFS_EXTENT_DATA_REF_KEY)
5d4f98a2
YZ
3292 goto out;
3293
3294 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3295 if (btrfs_extent_refs(leaf, ei) !=
3296 btrfs_extent_data_ref_count(leaf, ref) ||
3297 btrfs_extent_data_ref_root(leaf, ref) !=
3298 root->root_key.objectid ||
3299 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3300 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3301 goto out;
3302
3303 ret = 0;
3304out:
3305 return ret;
3306}
3307
e4c3b2dc
LB
3308int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3309 u64 bytenr)
5d4f98a2
YZ
3310{
3311 struct btrfs_path *path;
3312 int ret;
3313 int ret2;
3314
3315 path = btrfs_alloc_path();
3316 if (!path)
3317 return -ENOENT;
3318
3319 do {
e4c3b2dc 3320 ret = check_committed_ref(root, path, objectid,
5d4f98a2
YZ
3321 offset, bytenr);
3322 if (ret && ret != -ENOENT)
f321e491 3323 goto out;
80ff3856 3324
e4c3b2dc 3325 ret2 = check_delayed_ref(root, path, objectid,
5d4f98a2
YZ
3326 offset, bytenr);
3327 } while (ret2 == -EAGAIN);
3328
3329 if (ret2 && ret2 != -ENOENT) {
3330 ret = ret2;
3331 goto out;
f321e491 3332 }
5d4f98a2
YZ
3333
3334 if (ret != -ENOENT || ret2 != -ENOENT)
3335 ret = 0;
be20aa9d 3336out:
80ff3856 3337 btrfs_free_path(path);
f0486c68
YZ
3338 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3339 WARN_ON(ret > 0);
f321e491 3340 return ret;
be20aa9d 3341}
c5739bba 3342
5d4f98a2 3343static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
b7a9f29f 3344 struct btrfs_root *root,
5d4f98a2 3345 struct extent_buffer *buf,
e339a6b0 3346 int full_backref, int inc)
31840ae1 3347{
0b246afa 3348 struct btrfs_fs_info *fs_info = root->fs_info;
31840ae1 3349 u64 bytenr;
5d4f98a2
YZ
3350 u64 num_bytes;
3351 u64 parent;
31840ae1 3352 u64 ref_root;
31840ae1 3353 u32 nritems;
31840ae1
ZY
3354 struct btrfs_key key;
3355 struct btrfs_file_extent_item *fi;
3356 int i;
3357 int level;
3358 int ret = 0;
2ff7e61e
JM
3359 int (*process_func)(struct btrfs_trans_handle *,
3360 struct btrfs_fs_info *,
b06c4bf5 3361 u64, u64, u64, u64, u64, u64);
31840ae1 3362
fccb84c9 3363
0b246afa 3364 if (btrfs_is_testing(fs_info))
faa2dbf0 3365 return 0;
fccb84c9 3366
31840ae1 3367 ref_root = btrfs_header_owner(buf);
31840ae1
ZY
3368 nritems = btrfs_header_nritems(buf);
3369 level = btrfs_header_level(buf);
3370
27cdeb70 3371 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
5d4f98a2 3372 return 0;
31840ae1 3373
5d4f98a2
YZ
3374 if (inc)
3375 process_func = btrfs_inc_extent_ref;
3376 else
3377 process_func = btrfs_free_extent;
31840ae1 3378
5d4f98a2
YZ
3379 if (full_backref)
3380 parent = buf->start;
3381 else
3382 parent = 0;
3383
3384 for (i = 0; i < nritems; i++) {
31840ae1 3385 if (level == 0) {
5d4f98a2 3386 btrfs_item_key_to_cpu(buf, &key, i);
962a298f 3387 if (key.type != BTRFS_EXTENT_DATA_KEY)
31840ae1 3388 continue;
5d4f98a2 3389 fi = btrfs_item_ptr(buf, i,
31840ae1
ZY
3390 struct btrfs_file_extent_item);
3391 if (btrfs_file_extent_type(buf, fi) ==
3392 BTRFS_FILE_EXTENT_INLINE)
3393 continue;
3394 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3395 if (bytenr == 0)
3396 continue;
5d4f98a2
YZ
3397
3398 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3399 key.offset -= btrfs_file_extent_offset(buf, fi);
2ff7e61e 3400 ret = process_func(trans, fs_info, bytenr, num_bytes,
5d4f98a2 3401 parent, ref_root, key.objectid,
b06c4bf5 3402 key.offset);
31840ae1
ZY
3403 if (ret)
3404 goto fail;
3405 } else {
5d4f98a2 3406 bytenr = btrfs_node_blockptr(buf, i);
0b246afa 3407 num_bytes = fs_info->nodesize;
2ff7e61e 3408 ret = process_func(trans, fs_info, bytenr, num_bytes,
b06c4bf5 3409 parent, ref_root, level - 1, 0);
31840ae1
ZY
3410 if (ret)
3411 goto fail;
3412 }
3413 }
3414 return 0;
3415fail:
5d4f98a2
YZ
3416 return ret;
3417}
3418
3419int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
e339a6b0 3420 struct extent_buffer *buf, int full_backref)
5d4f98a2 3421{
e339a6b0 3422 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
5d4f98a2
YZ
3423}
3424
3425int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
e339a6b0 3426 struct extent_buffer *buf, int full_backref)
5d4f98a2 3427{
e339a6b0 3428 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
31840ae1
ZY
3429}
3430
9078a3e1 3431static int write_one_cache_group(struct btrfs_trans_handle *trans,
2ff7e61e 3432 struct btrfs_fs_info *fs_info,
9078a3e1
CM
3433 struct btrfs_path *path,
3434 struct btrfs_block_group_cache *cache)
3435{
3436 int ret;
0b246afa 3437 struct btrfs_root *extent_root = fs_info->extent_root;
5f39d397
CM
3438 unsigned long bi;
3439 struct extent_buffer *leaf;
9078a3e1 3440
9078a3e1 3441 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
df95e7f0
JB
3442 if (ret) {
3443 if (ret > 0)
3444 ret = -ENOENT;
54aa1f4d 3445 goto fail;
df95e7f0 3446 }
5f39d397
CM
3447
3448 leaf = path->nodes[0];
3449 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3450 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3451 btrfs_mark_buffer_dirty(leaf);
54aa1f4d 3452fail:
24b89d08 3453 btrfs_release_path(path);
df95e7f0 3454 return ret;
9078a3e1
CM
3455
3456}
3457
4a8c9a62 3458static struct btrfs_block_group_cache *
2ff7e61e 3459next_block_group(struct btrfs_fs_info *fs_info,
4a8c9a62
YZ
3460 struct btrfs_block_group_cache *cache)
3461{
3462 struct rb_node *node;
292cbd51 3463
0b246afa 3464 spin_lock(&fs_info->block_group_cache_lock);
292cbd51
FM
3465
3466 /* If our block group was removed, we need a full search. */
3467 if (RB_EMPTY_NODE(&cache->cache_node)) {
3468 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3469
0b246afa 3470 spin_unlock(&fs_info->block_group_cache_lock);
292cbd51 3471 btrfs_put_block_group(cache);
0b246afa 3472 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
292cbd51 3473 }
4a8c9a62
YZ
3474 node = rb_next(&cache->cache_node);
3475 btrfs_put_block_group(cache);
3476 if (node) {
3477 cache = rb_entry(node, struct btrfs_block_group_cache,
3478 cache_node);
11dfe35a 3479 btrfs_get_block_group(cache);
4a8c9a62
YZ
3480 } else
3481 cache = NULL;
0b246afa 3482 spin_unlock(&fs_info->block_group_cache_lock);
4a8c9a62
YZ
3483 return cache;
3484}
3485
0af3d00b
JB
3486static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3487 struct btrfs_trans_handle *trans,
3488 struct btrfs_path *path)
3489{
0b246afa
JM
3490 struct btrfs_fs_info *fs_info = block_group->fs_info;
3491 struct btrfs_root *root = fs_info->tree_root;
0af3d00b 3492 struct inode *inode = NULL;
364ecf36 3493 struct extent_changeset *data_reserved = NULL;
0af3d00b 3494 u64 alloc_hint = 0;
2b20982e 3495 int dcs = BTRFS_DC_ERROR;
f8c269d7 3496 u64 num_pages = 0;
0af3d00b
JB
3497 int retries = 0;
3498 int ret = 0;
3499
3500 /*
3501 * If this block group is smaller than 100 megs don't bother caching the
3502 * block group.
3503 */
ee22184b 3504 if (block_group->key.offset < (100 * SZ_1M)) {
0af3d00b
JB
3505 spin_lock(&block_group->lock);
3506 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3507 spin_unlock(&block_group->lock);
3508 return 0;
3509 }
3510
0c0ef4bc
JB
3511 if (trans->aborted)
3512 return 0;
0af3d00b 3513again:
77ab86bf 3514 inode = lookup_free_space_inode(fs_info, block_group, path);
0af3d00b
JB
3515 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3516 ret = PTR_ERR(inode);
b3b4aa74 3517 btrfs_release_path(path);
0af3d00b
JB
3518 goto out;
3519 }
3520
3521 if (IS_ERR(inode)) {
3522 BUG_ON(retries);
3523 retries++;
3524
3525 if (block_group->ro)
3526 goto out_free;
3527
77ab86bf
JM
3528 ret = create_free_space_inode(fs_info, trans, block_group,
3529 path);
0af3d00b
JB
3530 if (ret)
3531 goto out_free;
3532 goto again;
3533 }
3534
3535 /*
3536 * We want to set the generation to 0, that way if anything goes wrong
3537 * from here on out we know not to trust this cache when we load up next
3538 * time.
3539 */
3540 BTRFS_I(inode)->generation = 0;
3541 ret = btrfs_update_inode(trans, root, inode);
0c0ef4bc
JB
3542 if (ret) {
3543 /*
3544 * So theoretically we could recover from this, simply set the
3545 * super cache generation to 0 so we know to invalidate the
3546 * cache, but then we'd have to keep track of the block groups
3547 * that fail this way so we know we _have_ to reset this cache
3548 * before the next commit or risk reading stale cache. So to
3549 * limit our exposure to horrible edge cases lets just abort the
3550 * transaction, this only happens in really bad situations
3551 * anyway.
3552 */
66642832 3553 btrfs_abort_transaction(trans, ret);
0c0ef4bc
JB
3554 goto out_put;
3555 }
0af3d00b
JB
3556 WARN_ON(ret);
3557
28580e75
JB
3558 /* We've already setup this transaction, go ahead and exit */
3559 if (block_group->cache_generation == trans->transid &&
3560 i_size_read(inode)) {
3561 dcs = BTRFS_DC_SETUP;
3562 goto out_put;
3563 }
3564
0af3d00b 3565 if (i_size_read(inode) > 0) {
2ff7e61e 3566 ret = btrfs_check_trunc_cache_free_space(fs_info,
0b246afa 3567 &fs_info->global_block_rsv);
7b61cd92
MX
3568 if (ret)
3569 goto out_put;
3570
77ab86bf 3571 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
0af3d00b
JB
3572 if (ret)
3573 goto out_put;
3574 }
3575
3576 spin_lock(&block_group->lock);
cf7c1ef6 3577 if (block_group->cached != BTRFS_CACHE_FINISHED ||
0b246afa 3578 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
cf7c1ef6
LB
3579 /*
3580 * don't bother trying to write stuff out _if_
3581 * a) we're not cached,
1a79c1f2
LB
3582 * b) we're with nospace_cache mount option,
3583 * c) we're with v2 space_cache (FREE_SPACE_TREE).
cf7c1ef6 3584 */
2b20982e 3585 dcs = BTRFS_DC_WRITTEN;
0af3d00b
JB
3586 spin_unlock(&block_group->lock);
3587 goto out_put;
3588 }
3589 spin_unlock(&block_group->lock);
3590
2968b1f4
JB
3591 /*
3592 * We hit an ENOSPC when setting up the cache in this transaction, just
3593 * skip doing the setup, we've already cleared the cache so we're safe.
3594 */
3595 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3596 ret = -ENOSPC;
3597 goto out_put;
3598 }
3599
6fc823b1
JB
3600 /*
3601 * Try to preallocate enough space based on how big the block group is.
3602 * Keep in mind this has to include any pinned space which could end up
3603 * taking up quite a bit since it's not folded into the other space
3604 * cache.
3605 */
ee22184b 3606 num_pages = div_u64(block_group->key.offset, SZ_256M);
0af3d00b
JB
3607 if (!num_pages)
3608 num_pages = 1;
3609
0af3d00b 3610 num_pages *= 16;
09cbfeaf 3611 num_pages *= PAGE_SIZE;
0af3d00b 3612
364ecf36 3613 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
0af3d00b
JB
3614 if (ret)
3615 goto out_put;
3616
3617 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3618 num_pages, num_pages,
3619 &alloc_hint);
2968b1f4
JB
3620 /*
3621 * Our cache requires contiguous chunks so that we don't modify a bunch
3622 * of metadata or split extents when writing the cache out, which means
3623 * we can enospc if we are heavily fragmented in addition to just normal
3624 * out of space conditions. So if we hit this just skip setting up any
3625 * other block groups for this transaction, maybe we'll unpin enough
3626 * space the next time around.
3627 */
2b20982e
JB
3628 if (!ret)
3629 dcs = BTRFS_DC_SETUP;
2968b1f4
JB
3630 else if (ret == -ENOSPC)
3631 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
c09544e0 3632
0af3d00b
JB
3633out_put:
3634 iput(inode);
3635out_free:
b3b4aa74 3636 btrfs_release_path(path);
0af3d00b
JB
3637out:
3638 spin_lock(&block_group->lock);
e65cbb94 3639 if (!ret && dcs == BTRFS_DC_SETUP)
5b0e95bf 3640 block_group->cache_generation = trans->transid;
2b20982e 3641 block_group->disk_cache_state = dcs;
0af3d00b
JB
3642 spin_unlock(&block_group->lock);
3643
364ecf36 3644 extent_changeset_free(data_reserved);
0af3d00b
JB
3645 return ret;
3646}
3647
dcdf7f6d 3648int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
2ff7e61e 3649 struct btrfs_fs_info *fs_info)
dcdf7f6d
JB
3650{
3651 struct btrfs_block_group_cache *cache, *tmp;
3652 struct btrfs_transaction *cur_trans = trans->transaction;
3653 struct btrfs_path *path;
3654
3655 if (list_empty(&cur_trans->dirty_bgs) ||
0b246afa 3656 !btrfs_test_opt(fs_info, SPACE_CACHE))
dcdf7f6d
JB
3657 return 0;
3658
3659 path = btrfs_alloc_path();
3660 if (!path)
3661 return -ENOMEM;
3662
3663 /* Could add new block groups, use _safe just in case */
3664 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3665 dirty_list) {
3666 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3667 cache_save_setup(cache, trans, path);
3668 }
3669
3670 btrfs_free_path(path);
3671 return 0;
3672}
3673
1bbc621e
CM
3674/*
3675 * transaction commit does final block group cache writeback during a
3676 * critical section where nothing is allowed to change the FS. This is
3677 * required in order for the cache to actually match the block group,
3678 * but can introduce a lot of latency into the commit.
3679 *
3680 * So, btrfs_start_dirty_block_groups is here to kick off block group
3681 * cache IO. There's a chance we'll have to redo some of it if the
3682 * block group changes again during the commit, but it greatly reduces
3683 * the commit latency by getting rid of the easy block groups while
3684 * we're still allowing others to join the commit.
3685 */
3686int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
2ff7e61e 3687 struct btrfs_fs_info *fs_info)
9078a3e1 3688{
4a8c9a62 3689 struct btrfs_block_group_cache *cache;
ce93ec54
JB
3690 struct btrfs_transaction *cur_trans = trans->transaction;
3691 int ret = 0;
c9dc4c65 3692 int should_put;
1bbc621e
CM
3693 struct btrfs_path *path = NULL;
3694 LIST_HEAD(dirty);
3695 struct list_head *io = &cur_trans->io_bgs;
c9dc4c65 3696 int num_started = 0;
1bbc621e
CM
3697 int loops = 0;
3698
3699 spin_lock(&cur_trans->dirty_bgs_lock);
b58d1a9e
FM
3700 if (list_empty(&cur_trans->dirty_bgs)) {
3701 spin_unlock(&cur_trans->dirty_bgs_lock);
3702 return 0;
1bbc621e 3703 }
b58d1a9e 3704 list_splice_init(&cur_trans->dirty_bgs, &dirty);
1bbc621e 3705 spin_unlock(&cur_trans->dirty_bgs_lock);
ce93ec54 3706
1bbc621e 3707again:
1bbc621e
CM
3708 /*
3709 * make sure all the block groups on our dirty list actually
3710 * exist
3711 */
2ff7e61e 3712 btrfs_create_pending_block_groups(trans, fs_info);
1bbc621e
CM
3713
3714 if (!path) {
3715 path = btrfs_alloc_path();
3716 if (!path)
3717 return -ENOMEM;
3718 }
3719
b58d1a9e
FM
3720 /*
3721 * cache_write_mutex is here only to save us from balance or automatic
3722 * removal of empty block groups deleting this block group while we are
3723 * writing out the cache
3724 */
3725 mutex_lock(&trans->transaction->cache_write_mutex);
1bbc621e
CM
3726 while (!list_empty(&dirty)) {
3727 cache = list_first_entry(&dirty,
3728 struct btrfs_block_group_cache,
3729 dirty_list);
1bbc621e
CM
3730 /*
3731 * this can happen if something re-dirties a block
3732 * group that is already under IO. Just wait for it to
3733 * finish and then do it all again
3734 */
3735 if (!list_empty(&cache->io_list)) {
3736 list_del_init(&cache->io_list);
afdb5718 3737 btrfs_wait_cache_io(trans, cache, path);
1bbc621e
CM
3738 btrfs_put_block_group(cache);
3739 }
3740
3741
3742 /*
3743 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3744 * if it should update the cache_state. Don't delete
3745 * until after we wait.
3746 *
3747 * Since we're not running in the commit critical section
3748 * we need the dirty_bgs_lock to protect from update_block_group
3749 */
3750 spin_lock(&cur_trans->dirty_bgs_lock);
3751 list_del_init(&cache->dirty_list);
3752 spin_unlock(&cur_trans->dirty_bgs_lock);
3753
3754 should_put = 1;
3755
3756 cache_save_setup(cache, trans, path);
3757
3758 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3759 cache->io_ctl.inode = NULL;
0b246afa 3760 ret = btrfs_write_out_cache(fs_info, trans,
5b4aacef 3761 cache, path);
1bbc621e
CM
3762 if (ret == 0 && cache->io_ctl.inode) {
3763 num_started++;
3764 should_put = 0;
3765
3766 /*
3767 * the cache_write_mutex is protecting
3768 * the io_list
3769 */
3770 list_add_tail(&cache->io_list, io);
3771 } else {
3772 /*
3773 * if we failed to write the cache, the
3774 * generation will be bad and life goes on
3775 */
3776 ret = 0;
3777 }
3778 }
ff1f8250 3779 if (!ret) {
2ff7e61e
JM
3780 ret = write_one_cache_group(trans, fs_info,
3781 path, cache);
ff1f8250
FM
3782 /*
3783 * Our block group might still be attached to the list
3784 * of new block groups in the transaction handle of some
3785 * other task (struct btrfs_trans_handle->new_bgs). This
3786 * means its block group item isn't yet in the extent
3787 * tree. If this happens ignore the error, as we will
3788 * try again later in the critical section of the
3789 * transaction commit.
3790 */
3791 if (ret == -ENOENT) {
3792 ret = 0;
3793 spin_lock(&cur_trans->dirty_bgs_lock);
3794 if (list_empty(&cache->dirty_list)) {
3795 list_add_tail(&cache->dirty_list,
3796 &cur_trans->dirty_bgs);
3797 btrfs_get_block_group(cache);
3798 }
3799 spin_unlock(&cur_trans->dirty_bgs_lock);
3800 } else if (ret) {
66642832 3801 btrfs_abort_transaction(trans, ret);
ff1f8250
FM
3802 }
3803 }
1bbc621e
CM
3804
3805 /* if its not on the io list, we need to put the block group */
3806 if (should_put)
3807 btrfs_put_block_group(cache);
3808
3809 if (ret)
3810 break;
b58d1a9e
FM
3811
3812 /*
3813 * Avoid blocking other tasks for too long. It might even save
3814 * us from writing caches for block groups that are going to be
3815 * removed.
3816 */
3817 mutex_unlock(&trans->transaction->cache_write_mutex);
3818 mutex_lock(&trans->transaction->cache_write_mutex);
1bbc621e 3819 }
b58d1a9e 3820 mutex_unlock(&trans->transaction->cache_write_mutex);
1bbc621e
CM
3821
3822 /*
3823 * go through delayed refs for all the stuff we've just kicked off
3824 * and then loop back (just once)
3825 */
2ff7e61e 3826 ret = btrfs_run_delayed_refs(trans, fs_info, 0);
1bbc621e
CM
3827 if (!ret && loops == 0) {
3828 loops++;
3829 spin_lock(&cur_trans->dirty_bgs_lock);
3830 list_splice_init(&cur_trans->dirty_bgs, &dirty);
b58d1a9e
FM
3831 /*
3832 * dirty_bgs_lock protects us from concurrent block group
3833 * deletes too (not just cache_write_mutex).
3834 */
3835 if (!list_empty(&dirty)) {
3836 spin_unlock(&cur_trans->dirty_bgs_lock);
3837 goto again;
3838 }
1bbc621e 3839 spin_unlock(&cur_trans->dirty_bgs_lock);
c79a1751 3840 } else if (ret < 0) {
2ff7e61e 3841 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
1bbc621e
CM
3842 }
3843
3844 btrfs_free_path(path);
3845 return ret;
3846}
3847
3848int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2ff7e61e 3849 struct btrfs_fs_info *fs_info)
1bbc621e
CM
3850{
3851 struct btrfs_block_group_cache *cache;
3852 struct btrfs_transaction *cur_trans = trans->transaction;
3853 int ret = 0;
3854 int should_put;
3855 struct btrfs_path *path;
3856 struct list_head *io = &cur_trans->io_bgs;
3857 int num_started = 0;
9078a3e1
CM
3858
3859 path = btrfs_alloc_path();
3860 if (!path)
3861 return -ENOMEM;
3862
ce93ec54 3863 /*
e44081ef
FM
3864 * Even though we are in the critical section of the transaction commit,
3865 * we can still have concurrent tasks adding elements to this
3866 * transaction's list of dirty block groups. These tasks correspond to
3867 * endio free space workers started when writeback finishes for a
3868 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3869 * allocate new block groups as a result of COWing nodes of the root
3870 * tree when updating the free space inode. The writeback for the space
3871 * caches is triggered by an earlier call to
3872 * btrfs_start_dirty_block_groups() and iterations of the following
3873 * loop.
3874 * Also we want to do the cache_save_setup first and then run the
ce93ec54
JB
3875 * delayed refs to make sure we have the best chance at doing this all
3876 * in one shot.
3877 */
e44081ef 3878 spin_lock(&cur_trans->dirty_bgs_lock);
ce93ec54
JB
3879 while (!list_empty(&cur_trans->dirty_bgs)) {
3880 cache = list_first_entry(&cur_trans->dirty_bgs,
3881 struct btrfs_block_group_cache,
3882 dirty_list);
c9dc4c65
CM
3883
3884 /*
3885 * this can happen if cache_save_setup re-dirties a block
3886 * group that is already under IO. Just wait for it to
3887 * finish and then do it all again
3888 */
3889 if (!list_empty(&cache->io_list)) {
e44081ef 3890 spin_unlock(&cur_trans->dirty_bgs_lock);
c9dc4c65 3891 list_del_init(&cache->io_list);
afdb5718 3892 btrfs_wait_cache_io(trans, cache, path);
c9dc4c65 3893 btrfs_put_block_group(cache);
e44081ef 3894 spin_lock(&cur_trans->dirty_bgs_lock);
c9dc4c65
CM
3895 }
3896
1bbc621e
CM
3897 /*
3898 * don't remove from the dirty list until after we've waited
3899 * on any pending IO
3900 */
ce93ec54 3901 list_del_init(&cache->dirty_list);
e44081ef 3902 spin_unlock(&cur_trans->dirty_bgs_lock);
c9dc4c65
CM
3903 should_put = 1;
3904
1bbc621e 3905 cache_save_setup(cache, trans, path);
c9dc4c65 3906
ce93ec54 3907 if (!ret)
2ff7e61e
JM
3908 ret = btrfs_run_delayed_refs(trans, fs_info,
3909 (unsigned long) -1);
c9dc4c65
CM
3910
3911 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3912 cache->io_ctl.inode = NULL;
0b246afa 3913 ret = btrfs_write_out_cache(fs_info, trans,
5b4aacef 3914 cache, path);
c9dc4c65
CM
3915 if (ret == 0 && cache->io_ctl.inode) {
3916 num_started++;
3917 should_put = 0;
1bbc621e 3918 list_add_tail(&cache->io_list, io);
c9dc4c65
CM
3919 } else {
3920 /*
3921 * if we failed to write the cache, the
3922 * generation will be bad and life goes on
3923 */
3924 ret = 0;
3925 }
3926 }
ff1f8250 3927 if (!ret) {
2ff7e61e
JM
3928 ret = write_one_cache_group(trans, fs_info,
3929 path, cache);
2bc0bb5f
FM
3930 /*
3931 * One of the free space endio workers might have
3932 * created a new block group while updating a free space
3933 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3934 * and hasn't released its transaction handle yet, in
3935 * which case the new block group is still attached to
3936 * its transaction handle and its creation has not
3937 * finished yet (no block group item in the extent tree
3938 * yet, etc). If this is the case, wait for all free
3939 * space endio workers to finish and retry. This is a
3940 * a very rare case so no need for a more efficient and
3941 * complex approach.
3942 */
3943 if (ret == -ENOENT) {
3944 wait_event(cur_trans->writer_wait,
3945 atomic_read(&cur_trans->num_writers) == 1);
2ff7e61e
JM
3946 ret = write_one_cache_group(trans, fs_info,
3947 path, cache);
2bc0bb5f 3948 }
ff1f8250 3949 if (ret)
66642832 3950 btrfs_abort_transaction(trans, ret);
ff1f8250 3951 }
c9dc4c65
CM
3952
3953 /* if its not on the io list, we need to put the block group */
3954 if (should_put)
3955 btrfs_put_block_group(cache);
e44081ef 3956 spin_lock(&cur_trans->dirty_bgs_lock);
c9dc4c65 3957 }
e44081ef 3958 spin_unlock(&cur_trans->dirty_bgs_lock);
c9dc4c65 3959
1bbc621e
CM
3960 while (!list_empty(io)) {
3961 cache = list_first_entry(io, struct btrfs_block_group_cache,
c9dc4c65
CM
3962 io_list);
3963 list_del_init(&cache->io_list);
afdb5718 3964 btrfs_wait_cache_io(trans, cache, path);
0cb59c99
JB
3965 btrfs_put_block_group(cache);
3966 }
3967
9078a3e1 3968 btrfs_free_path(path);
ce93ec54 3969 return ret;
9078a3e1
CM
3970}
3971
2ff7e61e 3972int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
d2fb3437
YZ
3973{
3974 struct btrfs_block_group_cache *block_group;
3975 int readonly = 0;
3976
0b246afa 3977 block_group = btrfs_lookup_block_group(fs_info, bytenr);
d2fb3437
YZ
3978 if (!block_group || block_group->ro)
3979 readonly = 1;
3980 if (block_group)
fa9c0d79 3981 btrfs_put_block_group(block_group);
d2fb3437
YZ
3982 return readonly;
3983}
3984
f78c436c
FM
3985bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3986{
3987 struct btrfs_block_group_cache *bg;
3988 bool ret = true;
3989
3990 bg = btrfs_lookup_block_group(fs_info, bytenr);
3991 if (!bg)
3992 return false;
3993
3994 spin_lock(&bg->lock);
3995 if (bg->ro)
3996 ret = false;
3997 else
3998 atomic_inc(&bg->nocow_writers);
3999 spin_unlock(&bg->lock);
4000
4001 /* no put on block group, done by btrfs_dec_nocow_writers */
4002 if (!ret)
4003 btrfs_put_block_group(bg);
4004
4005 return ret;
4006
4007}
4008
4009void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
4010{
4011 struct btrfs_block_group_cache *bg;
4012
4013 bg = btrfs_lookup_block_group(fs_info, bytenr);
4014 ASSERT(bg);
4015 if (atomic_dec_and_test(&bg->nocow_writers))
4016 wake_up_atomic_t(&bg->nocow_writers);
4017 /*
4018 * Once for our lookup and once for the lookup done by a previous call
4019 * to btrfs_inc_nocow_writers()
4020 */
4021 btrfs_put_block_group(bg);
4022 btrfs_put_block_group(bg);
4023}
4024
4025static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
4026{
4027 schedule();
4028 return 0;
4029}
4030
4031void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
4032{
4033 wait_on_atomic_t(&bg->nocow_writers,
4034 btrfs_wait_nocow_writers_atomic_t,
4035 TASK_UNINTERRUPTIBLE);
4036}
4037
6ab0a202
JM
4038static const char *alloc_name(u64 flags)
4039{
4040 switch (flags) {
4041 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
4042 return "mixed";
4043 case BTRFS_BLOCK_GROUP_METADATA:
4044 return "metadata";
4045 case BTRFS_BLOCK_GROUP_DATA:
4046 return "data";
4047 case BTRFS_BLOCK_GROUP_SYSTEM:
4048 return "system";
4049 default:
4050 WARN_ON(1);
4051 return "invalid-combination";
4052 };
4053}
4054
2be12ef7
NB
4055static int create_space_info(struct btrfs_fs_info *info, u64 flags,
4056 struct btrfs_space_info **new)
4057{
4058
4059 struct btrfs_space_info *space_info;
4060 int i;
4061 int ret;
4062
4063 space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
4064 if (!space_info)
4065 return -ENOMEM;
4066
4067 ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
4068 GFP_KERNEL);
4069 if (ret) {
4070 kfree(space_info);
4071 return ret;
4072 }
4073
4074 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
4075 INIT_LIST_HEAD(&space_info->block_groups[i]);
4076 init_rwsem(&space_info->groups_sem);
4077 spin_lock_init(&space_info->lock);
4078 space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
4079 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4080 init_waitqueue_head(&space_info->wait);
4081 INIT_LIST_HEAD(&space_info->ro_bgs);
4082 INIT_LIST_HEAD(&space_info->tickets);
4083 INIT_LIST_HEAD(&space_info->priority_tickets);
4084
4085 ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
4086 info->space_info_kobj, "%s",
4087 alloc_name(space_info->flags));
4088 if (ret) {
535dedd9 4089 kobject_put(&space_info->kobj);
2be12ef7
NB
4090 return ret;
4091 }
4092
4093 *new = space_info;
4094 list_add_rcu(&space_info->list, &info->space_info);
4095 if (flags & BTRFS_BLOCK_GROUP_DATA)
4096 info->data_sinfo = space_info;
4097
4098 return ret;
4099}
4100
d2006e6d 4101static void update_space_info(struct btrfs_fs_info *info, u64 flags,
593060d7 4102 u64 total_bytes, u64 bytes_used,
e40edf2d 4103 u64 bytes_readonly,
593060d7
CM
4104 struct btrfs_space_info **space_info)
4105{
4106 struct btrfs_space_info *found;
b742bb82
YZ
4107 int factor;
4108
4109 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
4110 BTRFS_BLOCK_GROUP_RAID10))
4111 factor = 2;
4112 else
4113 factor = 1;
593060d7
CM
4114
4115 found = __find_space_info(info, flags);
d2006e6d
NB
4116 ASSERT(found);
4117 spin_lock(&found->lock);
4118 found->total_bytes += total_bytes;
4119 found->disk_total += total_bytes * factor;
4120 found->bytes_used += bytes_used;
4121 found->disk_used += bytes_used * factor;
4122 found->bytes_readonly += bytes_readonly;
4123 if (total_bytes > 0)
4124 found->full = 0;
4125 space_info_add_new_bytes(info, found, total_bytes -
4126 bytes_used - bytes_readonly);
4127 spin_unlock(&found->lock);
4128 *space_info = found;
593060d7
CM
4129}
4130
8790d502
CM
4131static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
4132{
899c81ea
ID
4133 u64 extra_flags = chunk_to_extended(flags) &
4134 BTRFS_EXTENDED_PROFILE_MASK;
a46d11a8 4135
de98ced9 4136 write_seqlock(&fs_info->profiles_lock);
a46d11a8
ID
4137 if (flags & BTRFS_BLOCK_GROUP_DATA)
4138 fs_info->avail_data_alloc_bits |= extra_flags;
4139 if (flags & BTRFS_BLOCK_GROUP_METADATA)
4140 fs_info->avail_metadata_alloc_bits |= extra_flags;
4141 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4142 fs_info->avail_system_alloc_bits |= extra_flags;
de98ced9 4143 write_sequnlock(&fs_info->profiles_lock);
8790d502 4144}
593060d7 4145
fc67c450
ID
4146/*
4147 * returns target flags in extended format or 0 if restripe for this
4148 * chunk_type is not in progress
c6664b42
ID
4149 *
4150 * should be called with either volume_mutex or balance_lock held
fc67c450
ID
4151 */
4152static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
4153{
4154 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4155 u64 target = 0;
4156
fc67c450
ID
4157 if (!bctl)
4158 return 0;
4159
4160 if (flags & BTRFS_BLOCK_GROUP_DATA &&
4161 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4162 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
4163 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
4164 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4165 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
4166 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
4167 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4168 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
4169 }
4170
4171 return target;
4172}
4173
a46d11a8
ID
4174/*
4175 * @flags: available profiles in extended format (see ctree.h)
4176 *
e4d8ec0f
ID
4177 * Returns reduced profile in chunk format. If profile changing is in
4178 * progress (either running or paused) picks the target profile (if it's
4179 * already available), otherwise falls back to plain reducing.
a46d11a8 4180 */
2ff7e61e 4181static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
ec44a35c 4182{
0b246afa 4183 u64 num_devices = fs_info->fs_devices->rw_devices;
fc67c450 4184 u64 target;
9c170b26
ZL
4185 u64 raid_type;
4186 u64 allowed = 0;
a061fc8d 4187
fc67c450
ID
4188 /*
4189 * see if restripe for this chunk_type is in progress, if so
4190 * try to reduce to the target profile
4191 */
0b246afa
JM
4192 spin_lock(&fs_info->balance_lock);
4193 target = get_restripe_target(fs_info, flags);
fc67c450
ID
4194 if (target) {
4195 /* pick target profile only if it's already available */
4196 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
0b246afa 4197 spin_unlock(&fs_info->balance_lock);
fc67c450 4198 return extended_to_chunk(target);
e4d8ec0f
ID
4199 }
4200 }
0b246afa 4201 spin_unlock(&fs_info->balance_lock);
e4d8ec0f 4202
53b381b3 4203 /* First, mask out the RAID levels which aren't possible */
9c170b26
ZL
4204 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4205 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4206 allowed |= btrfs_raid_group[raid_type];
4207 }
4208 allowed &= flags;
4209
4210 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4211 allowed = BTRFS_BLOCK_GROUP_RAID6;
4212 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4213 allowed = BTRFS_BLOCK_GROUP_RAID5;
4214 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4215 allowed = BTRFS_BLOCK_GROUP_RAID10;
4216 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4217 allowed = BTRFS_BLOCK_GROUP_RAID1;
4218 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4219 allowed = BTRFS_BLOCK_GROUP_RAID0;
4220
4221 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4222
4223 return extended_to_chunk(flags | allowed);
ec44a35c
CM
4224}
4225
2ff7e61e 4226static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
6a63209f 4227{
de98ced9 4228 unsigned seq;
f8213bdc 4229 u64 flags;
de98ced9
MX
4230
4231 do {
f8213bdc 4232 flags = orig_flags;
0b246afa 4233 seq = read_seqbegin(&fs_info->profiles_lock);
de98ced9
MX
4234
4235 if (flags & BTRFS_BLOCK_GROUP_DATA)
0b246afa 4236 flags |= fs_info->avail_data_alloc_bits;
de98ced9 4237 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
0b246afa 4238 flags |= fs_info->avail_system_alloc_bits;
de98ced9 4239 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
0b246afa
JM
4240 flags |= fs_info->avail_metadata_alloc_bits;
4241 } while (read_seqretry(&fs_info->profiles_lock, seq));
6fef8df1 4242
2ff7e61e 4243 return btrfs_reduce_alloc_profile(fs_info, flags);
6a63209f
JB
4244}
4245
1b86826d 4246static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
9ed74f2d 4247{
0b246afa 4248 struct btrfs_fs_info *fs_info = root->fs_info;
b742bb82 4249 u64 flags;
53b381b3 4250 u64 ret;
9ed74f2d 4251
b742bb82
YZ
4252 if (data)
4253 flags = BTRFS_BLOCK_GROUP_DATA;
0b246afa 4254 else if (root == fs_info->chunk_root)
b742bb82 4255 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9ed74f2d 4256 else
b742bb82 4257 flags = BTRFS_BLOCK_GROUP_METADATA;
9ed74f2d 4258
2ff7e61e 4259 ret = get_alloc_profile(fs_info, flags);
53b381b3 4260 return ret;
6a63209f 4261}
9ed74f2d 4262
1b86826d
JM
4263u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
4264{
4265 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
4266}
4267
4268u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
4269{
4270 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4271}
4272
4273u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
4274{
4275 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4276}
4277
4136135b
LB
4278static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4279 bool may_use_included)
4280{
4281 ASSERT(s_info);
4282 return s_info->bytes_used + s_info->bytes_reserved +
4283 s_info->bytes_pinned + s_info->bytes_readonly +
4284 (may_use_included ? s_info->bytes_may_use : 0);
4285}
4286
04f4f916 4287int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
6a63209f 4288{
04f4f916 4289 struct btrfs_root *root = inode->root;
b4d7c3c9 4290 struct btrfs_fs_info *fs_info = root->fs_info;
1174cade 4291 struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
ab6e2410 4292 u64 used;
94b947b2 4293 int ret = 0;
c99f1b0c
ZL
4294 int need_commit = 2;
4295 int have_pinned_space;
6a63209f 4296
6a63209f 4297 /* make sure bytes are sectorsize aligned */
0b246afa 4298 bytes = ALIGN(bytes, fs_info->sectorsize);
6a63209f 4299
9dced186 4300 if (btrfs_is_free_space_inode(inode)) {
c99f1b0c 4301 need_commit = 0;
9dced186 4302 ASSERT(current->journal_info);
0af3d00b
JB
4303 }
4304
6a63209f
JB
4305again:
4306 /* make sure we have enough space to handle the data first */
4307 spin_lock(&data_sinfo->lock);
4136135b 4308 used = btrfs_space_info_used(data_sinfo, true);
ab6e2410
JB
4309
4310 if (used + bytes > data_sinfo->total_bytes) {
4e06bdd6 4311 struct btrfs_trans_handle *trans;
9ed74f2d 4312
6a63209f
JB
4313 /*
4314 * if we don't have enough free bytes in this space then we need
4315 * to alloc a new chunk.
4316 */
b9fd47cd 4317 if (!data_sinfo->full) {
6a63209f 4318 u64 alloc_target;
9ed74f2d 4319
0e4f8f88 4320 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
6a63209f 4321 spin_unlock(&data_sinfo->lock);
1174cade 4322
1b86826d 4323 alloc_target = btrfs_data_alloc_profile(fs_info);
9dced186
MX
4324 /*
4325 * It is ugly that we don't call nolock join
4326 * transaction for the free space inode case here.
4327 * But it is safe because we only do the data space
4328 * reservation for the free space cache in the
4329 * transaction context, the common join transaction
4330 * just increase the counter of the current transaction
4331 * handler, doesn't try to acquire the trans_lock of
4332 * the fs.
4333 */
7a7eaa40 4334 trans = btrfs_join_transaction(root);
a22285a6
YZ
4335 if (IS_ERR(trans))
4336 return PTR_ERR(trans);
9ed74f2d 4337
2ff7e61e 4338 ret = do_chunk_alloc(trans, fs_info, alloc_target,
0e4f8f88 4339 CHUNK_ALLOC_NO_FORCE);
3a45bb20 4340 btrfs_end_transaction(trans);
d52a5b5f
MX
4341 if (ret < 0) {
4342 if (ret != -ENOSPC)
4343 return ret;
c99f1b0c
ZL
4344 else {
4345 have_pinned_space = 1;
d52a5b5f 4346 goto commit_trans;
c99f1b0c 4347 }
d52a5b5f 4348 }
9ed74f2d 4349
6a63209f
JB
4350 goto again;
4351 }
f2bb8f5c
JB
4352
4353 /*
b150a4f1 4354 * If we don't have enough pinned space to deal with this
94b947b2
ZL
4355 * allocation, and no removed chunk in current transaction,
4356 * don't bother committing the transaction.
f2bb8f5c 4357 */
c99f1b0c
ZL
4358 have_pinned_space = percpu_counter_compare(
4359 &data_sinfo->total_bytes_pinned,
4360 used + bytes - data_sinfo->total_bytes);
6a63209f 4361 spin_unlock(&data_sinfo->lock);
6a63209f 4362
4e06bdd6 4363 /* commit the current transaction and try again */
d52a5b5f 4364commit_trans:
c99f1b0c 4365 if (need_commit &&
0b246afa 4366 !atomic_read(&fs_info->open_ioctl_trans)) {
c99f1b0c 4367 need_commit--;
b150a4f1 4368
e1746e83
ZL
4369 if (need_commit > 0) {
4370 btrfs_start_delalloc_roots(fs_info, 0, -1);
6374e57a 4371 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
0b246afa 4372 (u64)-1);
e1746e83 4373 }
9a4e7276 4374
7a7eaa40 4375 trans = btrfs_join_transaction(root);
a22285a6
YZ
4376 if (IS_ERR(trans))
4377 return PTR_ERR(trans);
c99f1b0c 4378 if (have_pinned_space >= 0 ||
3204d33c
JB
4379 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4380 &trans->transaction->flags) ||
c99f1b0c 4381 need_commit > 0) {
3a45bb20 4382 ret = btrfs_commit_transaction(trans);
94b947b2
ZL
4383 if (ret)
4384 return ret;
d7c15171 4385 /*
c2d6cb16
FM
4386 * The cleaner kthread might still be doing iput
4387 * operations. Wait for it to finish so that
4388 * more space is released.
d7c15171 4389 */
0b246afa
JM
4390 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4391 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
94b947b2
ZL
4392 goto again;
4393 } else {
3a45bb20 4394 btrfs_end_transaction(trans);
94b947b2 4395 }
4e06bdd6 4396 }
9ed74f2d 4397
0b246afa 4398 trace_btrfs_space_reservation(fs_info,
cab45e22
JM
4399 "space_info:enospc",
4400 data_sinfo->flags, bytes, 1);
6a63209f
JB
4401 return -ENOSPC;
4402 }
4403 data_sinfo->bytes_may_use += bytes;
0b246afa 4404 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4405 data_sinfo->flags, bytes, 1);
6a63209f 4406 spin_unlock(&data_sinfo->lock);
6a63209f 4407
e7457f97 4408 return 0;
9ed74f2d 4409}
6a63209f 4410
364ecf36
QW
4411int btrfs_check_data_free_space(struct inode *inode,
4412 struct extent_changeset **reserved, u64 start, u64 len)
4ceff079 4413{
0b246afa 4414 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4ceff079
QW
4415 int ret;
4416
4417 /* align the range */
0b246afa
JM
4418 len = round_up(start + len, fs_info->sectorsize) -
4419 round_down(start, fs_info->sectorsize);
4420 start = round_down(start, fs_info->sectorsize);
4ceff079 4421
04f4f916 4422 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4ceff079
QW
4423 if (ret < 0)
4424 return ret;
4425
1e5ec2e7 4426 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
364ecf36 4427 ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
7bc329c1 4428 if (ret < 0)
1e5ec2e7 4429 btrfs_free_reserved_data_space_noquota(inode, start, len);
364ecf36
QW
4430 else
4431 ret = 0;
4ceff079
QW
4432 return ret;
4433}
4434
4ceff079
QW
4435/*
4436 * Called if we need to clear a data reservation for this inode
4437 * Normally in a error case.
4438 *
51773bec
QW
4439 * This one will *NOT* use accurate qgroup reserved space API, just for case
4440 * which we can't sleep and is sure it won't affect qgroup reserved space.
4441 * Like clear_bit_hook().
4ceff079 4442 */
51773bec
QW
4443void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4444 u64 len)
4ceff079 4445{
0b246afa 4446 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4ceff079
QW
4447 struct btrfs_space_info *data_sinfo;
4448
4449 /* Make sure the range is aligned to sectorsize */
0b246afa
JM
4450 len = round_up(start + len, fs_info->sectorsize) -
4451 round_down(start, fs_info->sectorsize);
4452 start = round_down(start, fs_info->sectorsize);
4ceff079 4453
0b246afa 4454 data_sinfo = fs_info->data_sinfo;
4ceff079
QW
4455 spin_lock(&data_sinfo->lock);
4456 if (WARN_ON(data_sinfo->bytes_may_use < len))
4457 data_sinfo->bytes_may_use = 0;
4458 else
4459 data_sinfo->bytes_may_use -= len;
0b246afa 4460 trace_btrfs_space_reservation(fs_info, "space_info",
4ceff079
QW
4461 data_sinfo->flags, len, 0);
4462 spin_unlock(&data_sinfo->lock);
4463}
4464
51773bec
QW
4465/*
4466 * Called if we need to clear a data reservation for this inode
4467 * Normally in a error case.
4468 *
01327610 4469 * This one will handle the per-inode data rsv map for accurate reserved
51773bec
QW
4470 * space framework.
4471 */
bc42bda2
QW
4472void btrfs_free_reserved_data_space(struct inode *inode,
4473 struct extent_changeset *reserved, u64 start, u64 len)
51773bec 4474{
0c476a5d
JM
4475 struct btrfs_root *root = BTRFS_I(inode)->root;
4476
4477 /* Make sure the range is aligned to sectorsize */
da17066c
JM
4478 len = round_up(start + len, root->fs_info->sectorsize) -
4479 round_down(start, root->fs_info->sectorsize);
4480 start = round_down(start, root->fs_info->sectorsize);
0c476a5d 4481
51773bec 4482 btrfs_free_reserved_data_space_noquota(inode, start, len);
bc42bda2 4483 btrfs_qgroup_free_data(inode, reserved, start, len);
51773bec
QW
4484}
4485
97e728d4 4486static void force_metadata_allocation(struct btrfs_fs_info *info)
e3ccfa98 4487{
97e728d4
JB
4488 struct list_head *head = &info->space_info;
4489 struct btrfs_space_info *found;
e3ccfa98 4490
97e728d4
JB
4491 rcu_read_lock();
4492 list_for_each_entry_rcu(found, head, list) {
4493 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
0e4f8f88 4494 found->force_alloc = CHUNK_ALLOC_FORCE;
e3ccfa98 4495 }
97e728d4 4496 rcu_read_unlock();
e3ccfa98
JB
4497}
4498
3c76cd84
MX
4499static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4500{
4501 return (global->size << 1);
4502}
4503
2ff7e61e 4504static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
698d0082 4505 struct btrfs_space_info *sinfo, int force)
32c00aff 4506{
0b246afa 4507 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8d8aafee 4508 u64 bytes_used = btrfs_space_info_used(sinfo, false);
e5bc2458 4509 u64 thresh;
e3ccfa98 4510
0e4f8f88
CM
4511 if (force == CHUNK_ALLOC_FORCE)
4512 return 1;
4513
fb25e914
JB
4514 /*
4515 * We need to take into account the global rsv because for all intents
4516 * and purposes it's used space. Don't worry about locking the
4517 * global_rsv, it doesn't change except when the transaction commits.
4518 */
54338b5c 4519 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
8d8aafee 4520 bytes_used += calc_global_rsv_need_space(global_rsv);
fb25e914 4521
0e4f8f88
CM
4522 /*
4523 * in limited mode, we want to have some free space up to
4524 * about 1% of the FS size.
4525 */
4526 if (force == CHUNK_ALLOC_LIMITED) {
0b246afa 4527 thresh = btrfs_super_total_bytes(fs_info->super_copy);
ee22184b 4528 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
0e4f8f88 4529
8d8aafee 4530 if (sinfo->total_bytes - bytes_used < thresh)
0e4f8f88
CM
4531 return 1;
4532 }
0e4f8f88 4533
8d8aafee 4534 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
14ed0ca6 4535 return 0;
424499db 4536 return 1;
32c00aff
JB
4537}
4538
2ff7e61e 4539static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
15d1ff81
LB
4540{
4541 u64 num_dev;
4542
53b381b3
DW
4543 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4544 BTRFS_BLOCK_GROUP_RAID0 |
4545 BTRFS_BLOCK_GROUP_RAID5 |
4546 BTRFS_BLOCK_GROUP_RAID6))
0b246afa 4547 num_dev = fs_info->fs_devices->rw_devices;
15d1ff81
LB
4548 else if (type & BTRFS_BLOCK_GROUP_RAID1)
4549 num_dev = 2;
4550 else
4551 num_dev = 1; /* DUP or single */
4552
39c2d7fa 4553 return num_dev;
15d1ff81
LB
4554}
4555
39c2d7fa
FM
4556/*
4557 * If @is_allocation is true, reserve space in the system space info necessary
4558 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4559 * removing a chunk.
4560 */
4561void check_system_chunk(struct btrfs_trans_handle *trans,
2ff7e61e 4562 struct btrfs_fs_info *fs_info, u64 type)
15d1ff81
LB
4563{
4564 struct btrfs_space_info *info;
4565 u64 left;
4566 u64 thresh;
4fbcdf66 4567 int ret = 0;
39c2d7fa 4568 u64 num_devs;
4fbcdf66
FM
4569
4570 /*
4571 * Needed because we can end up allocating a system chunk and for an
4572 * atomic and race free space reservation in the chunk block reserve.
4573 */
0b246afa 4574 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
15d1ff81 4575
0b246afa 4576 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
15d1ff81 4577 spin_lock(&info->lock);
4136135b 4578 left = info->total_bytes - btrfs_space_info_used(info, true);
15d1ff81
LB
4579 spin_unlock(&info->lock);
4580
2ff7e61e 4581 num_devs = get_profile_num_devs(fs_info, type);
39c2d7fa
FM
4582
4583 /* num_devs device items to update and 1 chunk item to add or remove */
0b246afa
JM
4584 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4585 btrfs_calc_trans_metadata_size(fs_info, 1);
39c2d7fa 4586
0b246afa
JM
4587 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4588 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4589 left, thresh, type);
4590 dump_space_info(fs_info, info, 0, 0);
15d1ff81
LB
4591 }
4592
4593 if (left < thresh) {
1b86826d 4594 u64 flags = btrfs_system_alloc_profile(fs_info);
15d1ff81 4595
4fbcdf66
FM
4596 /*
4597 * Ignore failure to create system chunk. We might end up not
4598 * needing it, as we might not need to COW all nodes/leafs from
4599 * the paths we visit in the chunk tree (they were already COWed
4600 * or created in the current transaction for example).
4601 */
2ff7e61e 4602 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4fbcdf66
FM
4603 }
4604
4605 if (!ret) {
0b246afa
JM
4606 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4607 &fs_info->chunk_block_rsv,
4fbcdf66
FM
4608 thresh, BTRFS_RESERVE_NO_FLUSH);
4609 if (!ret)
4610 trans->chunk_bytes_reserved += thresh;
15d1ff81
LB
4611 }
4612}
4613
28b737f6
LB
4614/*
4615 * If force is CHUNK_ALLOC_FORCE:
4616 * - return 1 if it successfully allocates a chunk,
4617 * - return errors including -ENOSPC otherwise.
4618 * If force is NOT CHUNK_ALLOC_FORCE:
4619 * - return 0 if it doesn't need to allocate a new chunk,
4620 * - return 1 if it successfully allocates a chunk,
4621 * - return errors including -ENOSPC otherwise.
4622 */
6324fbf3 4623static int do_chunk_alloc(struct btrfs_trans_handle *trans,
2ff7e61e 4624 struct btrfs_fs_info *fs_info, u64 flags, int force)
9ed74f2d 4625{
6324fbf3 4626 struct btrfs_space_info *space_info;
6d74119f 4627 int wait_for_alloc = 0;
9ed74f2d 4628 int ret = 0;
9ed74f2d 4629
c6b305a8
JB
4630 /* Don't re-enter if we're already allocating a chunk */
4631 if (trans->allocating_chunk)
4632 return -ENOSPC;
4633
0b246afa 4634 space_info = __find_space_info(fs_info, flags);
593060d7 4635 if (!space_info) {
2be12ef7
NB
4636 ret = create_space_info(fs_info, flags, &space_info);
4637 if (ret)
4638 return ret;
9ed74f2d
JB
4639 }
4640
6d74119f 4641again:
25179201 4642 spin_lock(&space_info->lock);
9e622d6b 4643 if (force < space_info->force_alloc)
0e4f8f88 4644 force = space_info->force_alloc;
25179201 4645 if (space_info->full) {
2ff7e61e 4646 if (should_alloc_chunk(fs_info, space_info, force))
09fb99a6
FDBM
4647 ret = -ENOSPC;
4648 else
4649 ret = 0;
25179201 4650 spin_unlock(&space_info->lock);
09fb99a6 4651 return ret;
9ed74f2d
JB
4652 }
4653
2ff7e61e 4654 if (!should_alloc_chunk(fs_info, space_info, force)) {
25179201 4655 spin_unlock(&space_info->lock);
6d74119f
JB
4656 return 0;
4657 } else if (space_info->chunk_alloc) {
4658 wait_for_alloc = 1;
4659 } else {
4660 space_info->chunk_alloc = 1;
9ed74f2d 4661 }
0e4f8f88 4662
25179201 4663 spin_unlock(&space_info->lock);
9ed74f2d 4664
6d74119f
JB
4665 mutex_lock(&fs_info->chunk_mutex);
4666
4667 /*
4668 * The chunk_mutex is held throughout the entirety of a chunk
4669 * allocation, so once we've acquired the chunk_mutex we know that the
4670 * other guy is done and we need to recheck and see if we should
4671 * allocate.
4672 */
4673 if (wait_for_alloc) {
4674 mutex_unlock(&fs_info->chunk_mutex);
4675 wait_for_alloc = 0;
370b3353 4676 cond_resched();
6d74119f
JB
4677 goto again;
4678 }
4679
c6b305a8
JB
4680 trans->allocating_chunk = true;
4681
67377734
JB
4682 /*
4683 * If we have mixed data/metadata chunks we want to make sure we keep
4684 * allocating mixed chunks instead of individual chunks.
4685 */
4686 if (btrfs_mixed_space_info(space_info))
4687 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4688
97e728d4
JB
4689 /*
4690 * if we're doing a data chunk, go ahead and make sure that
4691 * we keep a reasonable number of metadata chunks allocated in the
4692 * FS as well.
4693 */
9ed74f2d 4694 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
97e728d4
JB
4695 fs_info->data_chunk_allocations++;
4696 if (!(fs_info->data_chunk_allocations %
4697 fs_info->metadata_ratio))
4698 force_metadata_allocation(fs_info);
9ed74f2d
JB
4699 }
4700
15d1ff81
LB
4701 /*
4702 * Check if we have enough space in SYSTEM chunk because we may need
4703 * to update devices.
4704 */
2ff7e61e 4705 check_system_chunk(trans, fs_info, flags);
15d1ff81 4706
2ff7e61e 4707 ret = btrfs_alloc_chunk(trans, fs_info, flags);
c6b305a8 4708 trans->allocating_chunk = false;
92b8e897 4709
9ed74f2d 4710 spin_lock(&space_info->lock);
a81cb9a2
AO
4711 if (ret < 0 && ret != -ENOSPC)
4712 goto out;
9ed74f2d 4713 if (ret)
6324fbf3 4714 space_info->full = 1;
424499db
YZ
4715 else
4716 ret = 1;
6d74119f 4717
0e4f8f88 4718 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
a81cb9a2 4719out:
6d74119f 4720 space_info->chunk_alloc = 0;
9ed74f2d 4721 spin_unlock(&space_info->lock);
a25c75d5 4722 mutex_unlock(&fs_info->chunk_mutex);
00d80e34
FM
4723 /*
4724 * When we allocate a new chunk we reserve space in the chunk block
4725 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4726 * add new nodes/leafs to it if we end up needing to do it when
4727 * inserting the chunk item and updating device items as part of the
4728 * second phase of chunk allocation, performed by
4729 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4730 * large number of new block groups to create in our transaction
4731 * handle's new_bgs list to avoid exhausting the chunk block reserve
4732 * in extreme cases - like having a single transaction create many new
4733 * block groups when starting to write out the free space caches of all
4734 * the block groups that were made dirty during the lifetime of the
4735 * transaction.
4736 */
d9a0540a 4737 if (trans->can_flush_pending_bgs &&
ee22184b 4738 trans->chunk_bytes_reserved >= (u64)SZ_2M) {
2ff7e61e 4739 btrfs_create_pending_block_groups(trans, fs_info);
00d80e34
FM
4740 btrfs_trans_release_chunk_metadata(trans);
4741 }
0f9dd46c 4742 return ret;
6324fbf3 4743}
9ed74f2d 4744
c1c4919b 4745static int can_overcommit(struct btrfs_fs_info *fs_info,
a80c8dcf 4746 struct btrfs_space_info *space_info, u64 bytes,
c1c4919b
JM
4747 enum btrfs_reserve_flush_enum flush,
4748 bool system_chunk)
a80c8dcf 4749{
0b246afa 4750 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
957780eb 4751 u64 profile;
3c76cd84 4752 u64 space_size;
a80c8dcf
JB
4753 u64 avail;
4754 u64 used;
4755
957780eb
JB
4756 /* Don't overcommit when in mixed mode. */
4757 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4758 return 0;
4759
c1c4919b
JM
4760 if (system_chunk)
4761 profile = btrfs_system_alloc_profile(fs_info);
4762 else
4763 profile = btrfs_metadata_alloc_profile(fs_info);
4764
4136135b 4765 used = btrfs_space_info_used(space_info, false);
96f1bb57 4766
96f1bb57
JB
4767 /*
4768 * We only want to allow over committing if we have lots of actual space
4769 * free, but if we don't have enough space to handle the global reserve
4770 * space then we could end up having a real enospc problem when trying
4771 * to allocate a chunk or some other such important allocation.
4772 */
3c76cd84
MX
4773 spin_lock(&global_rsv->lock);
4774 space_size = calc_global_rsv_need_space(global_rsv);
4775 spin_unlock(&global_rsv->lock);
4776 if (used + space_size >= space_info->total_bytes)
96f1bb57
JB
4777 return 0;
4778
4779 used += space_info->bytes_may_use;
a80c8dcf 4780
a5ed45f8 4781 avail = atomic64_read(&fs_info->free_chunk_space);
a80c8dcf
JB
4782
4783 /*
4784 * If we have dup, raid1 or raid10 then only half of the free
53b381b3
DW
4785 * space is actually useable. For raid56, the space info used
4786 * doesn't include the parity drive, so we don't have to
4787 * change the math
a80c8dcf
JB
4788 */
4789 if (profile & (BTRFS_BLOCK_GROUP_DUP |
4790 BTRFS_BLOCK_GROUP_RAID1 |
4791 BTRFS_BLOCK_GROUP_RAID10))
4792 avail >>= 1;
4793
4794 /*
561c294d
MX
4795 * If we aren't flushing all things, let us overcommit up to
4796 * 1/2th of the space. If we can flush, don't let us overcommit
4797 * too much, let it overcommit up to 1/8 of the space.
a80c8dcf 4798 */
08e007d2 4799 if (flush == BTRFS_RESERVE_FLUSH_ALL)
14575aef 4800 avail >>= 3;
a80c8dcf 4801 else
14575aef 4802 avail >>= 1;
a80c8dcf 4803
14575aef 4804 if (used + bytes < space_info->total_bytes + avail)
a80c8dcf
JB
4805 return 1;
4806 return 0;
4807}
4808
2ff7e61e 4809static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
6c255e67 4810 unsigned long nr_pages, int nr_items)
da633a42 4811{
0b246afa 4812 struct super_block *sb = fs_info->sb;
da633a42 4813
925a6efb
JB
4814 if (down_read_trylock(&sb->s_umount)) {
4815 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4816 up_read(&sb->s_umount);
4817 } else {
da633a42
MX
4818 /*
4819 * We needn't worry the filesystem going from r/w to r/o though
4820 * we don't acquire ->s_umount mutex, because the filesystem
4821 * should guarantee the delalloc inodes list be empty after
4822 * the filesystem is readonly(all dirty pages are written to
4823 * the disk).
4824 */
0b246afa 4825 btrfs_start_delalloc_roots(fs_info, 0, nr_items);
98ad69cf 4826 if (!current->journal_info)
0b246afa 4827 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
da633a42
MX
4828 }
4829}
4830
6374e57a 4831static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
2ff7e61e 4832 u64 to_reclaim)
18cd8ea6
MX
4833{
4834 u64 bytes;
6374e57a 4835 u64 nr;
18cd8ea6 4836
2ff7e61e 4837 bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
6374e57a 4838 nr = div64_u64(to_reclaim, bytes);
18cd8ea6
MX
4839 if (!nr)
4840 nr = 1;
4841 return nr;
4842}
4843
ee22184b 4844#define EXTENT_SIZE_PER_ITEM SZ_256K
c61a16a7 4845
9ed74f2d 4846/*
5da9d01b 4847 * shrink metadata reservation for delalloc
9ed74f2d 4848 */
c1c4919b
JM
4849static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
4850 u64 orig, bool wait_ordered)
5da9d01b 4851{
0ca1f7ce 4852 struct btrfs_block_rsv *block_rsv;
0019f10d 4853 struct btrfs_space_info *space_info;
663350ac 4854 struct btrfs_trans_handle *trans;
f4c738c2 4855 u64 delalloc_bytes;
5da9d01b 4856 u64 max_reclaim;
6374e57a 4857 u64 items;
b1953bce 4858 long time_left;
d3ee29e3
MX
4859 unsigned long nr_pages;
4860 int loops;
08e007d2 4861 enum btrfs_reserve_flush_enum flush;
5da9d01b 4862
c61a16a7 4863 /* Calc the number of the pages we need flush for space reservation */
2ff7e61e 4864 items = calc_reclaim_items_nr(fs_info, to_reclaim);
6374e57a 4865 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
c61a16a7 4866
663350ac 4867 trans = (struct btrfs_trans_handle *)current->journal_info;
0b246afa 4868 block_rsv = &fs_info->delalloc_block_rsv;
0019f10d 4869 space_info = block_rsv->space_info;
bf9022e0 4870
963d678b 4871 delalloc_bytes = percpu_counter_sum_positive(
0b246afa 4872 &fs_info->delalloc_bytes);
f4c738c2 4873 if (delalloc_bytes == 0) {
fdb5effd 4874 if (trans)
f4c738c2 4875 return;
38c135af 4876 if (wait_ordered)
0b246afa 4877 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
f4c738c2 4878 return;
fdb5effd
JB
4879 }
4880
d3ee29e3 4881 loops = 0;
f4c738c2
JB
4882 while (delalloc_bytes && loops < 3) {
4883 max_reclaim = min(delalloc_bytes, to_reclaim);
09cbfeaf 4884 nr_pages = max_reclaim >> PAGE_SHIFT;
2ff7e61e 4885 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
dea31f52
JB
4886 /*
4887 * We need to wait for the async pages to actually start before
4888 * we do anything.
4889 */
0b246afa 4890 max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
9f3a074d
MX
4891 if (!max_reclaim)
4892 goto skip_async;
4893
4894 if (max_reclaim <= nr_pages)
4895 max_reclaim = 0;
4896 else
4897 max_reclaim -= nr_pages;
dea31f52 4898
0b246afa
JM
4899 wait_event(fs_info->async_submit_wait,
4900 atomic_read(&fs_info->async_delalloc_pages) <=
9f3a074d
MX
4901 (int)max_reclaim);
4902skip_async:
08e007d2
MX
4903 if (!trans)
4904 flush = BTRFS_RESERVE_FLUSH_ALL;
4905 else
4906 flush = BTRFS_RESERVE_NO_FLUSH;
0019f10d 4907 spin_lock(&space_info->lock);
957780eb
JB
4908 if (list_empty(&space_info->tickets) &&
4909 list_empty(&space_info->priority_tickets)) {
4910 spin_unlock(&space_info->lock);
4911 break;
4912 }
0019f10d 4913 spin_unlock(&space_info->lock);
5da9d01b 4914
36e39c40 4915 loops++;
f104d044 4916 if (wait_ordered && !trans) {
0b246afa 4917 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
f104d044 4918 } else {
f4c738c2 4919 time_left = schedule_timeout_killable(1);
f104d044
JB
4920 if (time_left)
4921 break;
4922 }
963d678b 4923 delalloc_bytes = percpu_counter_sum_positive(
0b246afa 4924 &fs_info->delalloc_bytes);
5da9d01b 4925 }
5da9d01b
YZ
4926}
4927
f1117628
JB
4928struct reserve_ticket {
4929 u64 bytes;
4930 int error;
4931 struct list_head list;
4932 wait_queue_head_t wait;
4933};
4934
663350ac
JB
4935/**
4936 * maybe_commit_transaction - possibly commit the transaction if its ok to
4937 * @root - the root we're allocating for
4938 * @bytes - the number of bytes we want to reserve
4939 * @force - force the commit
8bb8ab2e 4940 *
663350ac
JB
4941 * This will check to make sure that committing the transaction will actually
4942 * get us somewhere and then commit the transaction if it does. Otherwise it
4943 * will return -ENOSPC.
8bb8ab2e 4944 */
0c9ab349 4945static int may_commit_transaction(struct btrfs_fs_info *fs_info,
f1117628 4946 struct btrfs_space_info *space_info)
663350ac 4947{
f1117628 4948 struct reserve_ticket *ticket = NULL;
0b246afa 4949 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
663350ac 4950 struct btrfs_trans_handle *trans;
f1117628 4951 u64 bytes;
663350ac
JB
4952
4953 trans = (struct btrfs_trans_handle *)current->journal_info;
4954 if (trans)
4955 return -EAGAIN;
4956
f1117628
JB
4957 spin_lock(&space_info->lock);
4958 if (!list_empty(&space_info->priority_tickets))
4959 ticket = list_first_entry(&space_info->priority_tickets,
4960 struct reserve_ticket, list);
4961 else if (!list_empty(&space_info->tickets))
4962 ticket = list_first_entry(&space_info->tickets,
4963 struct reserve_ticket, list);
4964 bytes = (ticket) ? ticket->bytes : 0;
4965 spin_unlock(&space_info->lock);
4966
4967 if (!bytes)
4968 return 0;
663350ac
JB
4969
4970 /* See if there is enough pinned space to make this reservation */
b150a4f1 4971 if (percpu_counter_compare(&space_info->total_bytes_pinned,
0424c548 4972 bytes) >= 0)
663350ac 4973 goto commit;
663350ac
JB
4974
4975 /*
4976 * See if there is some space in the delayed insertion reservation for
4977 * this reservation.
4978 */
4979 if (space_info != delayed_rsv->space_info)
4980 return -ENOSPC;
4981
4982 spin_lock(&delayed_rsv->lock);
f1117628
JB
4983 if (delayed_rsv->size > bytes)
4984 bytes = 0;
4985 else
4986 bytes -= delayed_rsv->size;
b150a4f1 4987 if (percpu_counter_compare(&space_info->total_bytes_pinned,
f1117628 4988 bytes) < 0) {
663350ac
JB
4989 spin_unlock(&delayed_rsv->lock);
4990 return -ENOSPC;
4991 }
4992 spin_unlock(&delayed_rsv->lock);
4993
4994commit:
a9b3311e 4995 trans = btrfs_join_transaction(fs_info->extent_root);
663350ac
JB
4996 if (IS_ERR(trans))
4997 return -ENOSPC;
4998
3a45bb20 4999 return btrfs_commit_transaction(trans);
663350ac
JB
5000}
5001
e38ae7a0
NB
5002/*
5003 * Try to flush some data based on policy set by @state. This is only advisory
5004 * and may fail for various reasons. The caller is supposed to examine the
5005 * state of @space_info to detect the outcome.
5006 */
5007static void flush_space(struct btrfs_fs_info *fs_info,
96c3f433 5008 struct btrfs_space_info *space_info, u64 num_bytes,
7bdd6277 5009 int state)
96c3f433 5010{
a9b3311e 5011 struct btrfs_root *root = fs_info->extent_root;
96c3f433
JB
5012 struct btrfs_trans_handle *trans;
5013 int nr;
f4c738c2 5014 int ret = 0;
96c3f433
JB
5015
5016 switch (state) {
96c3f433
JB
5017 case FLUSH_DELAYED_ITEMS_NR:
5018 case FLUSH_DELAYED_ITEMS:
18cd8ea6 5019 if (state == FLUSH_DELAYED_ITEMS_NR)
2ff7e61e 5020 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
18cd8ea6 5021 else
96c3f433 5022 nr = -1;
18cd8ea6 5023
96c3f433
JB
5024 trans = btrfs_join_transaction(root);
5025 if (IS_ERR(trans)) {
5026 ret = PTR_ERR(trans);
5027 break;
5028 }
2ff7e61e 5029 ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
3a45bb20 5030 btrfs_end_transaction(trans);
96c3f433 5031 break;
67b0fd63
JB
5032 case FLUSH_DELALLOC:
5033 case FLUSH_DELALLOC_WAIT:
7bdd6277 5034 shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
67b0fd63
JB
5035 state == FLUSH_DELALLOC_WAIT);
5036 break;
ea658bad
JB
5037 case ALLOC_CHUNK:
5038 trans = btrfs_join_transaction(root);
5039 if (IS_ERR(trans)) {
5040 ret = PTR_ERR(trans);
5041 break;
5042 }
2ff7e61e 5043 ret = do_chunk_alloc(trans, fs_info,
1b86826d 5044 btrfs_metadata_alloc_profile(fs_info),
ea658bad 5045 CHUNK_ALLOC_NO_FORCE);
3a45bb20 5046 btrfs_end_transaction(trans);
eecba891 5047 if (ret > 0 || ret == -ENOSPC)
ea658bad
JB
5048 ret = 0;
5049 break;
96c3f433 5050 case COMMIT_TRANS:
f1117628 5051 ret = may_commit_transaction(fs_info, space_info);
96c3f433
JB
5052 break;
5053 default:
5054 ret = -ENOSPC;
5055 break;
5056 }
5057
7bdd6277
NB
5058 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
5059 ret);
e38ae7a0 5060 return;
96c3f433 5061}
21c7e756
MX
5062
5063static inline u64
c1c4919b
JM
5064btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
5065 struct btrfs_space_info *space_info,
5066 bool system_chunk)
21c7e756 5067{
957780eb 5068 struct reserve_ticket *ticket;
21c7e756
MX
5069 u64 used;
5070 u64 expected;
957780eb 5071 u64 to_reclaim = 0;
21c7e756 5072
957780eb
JB
5073 list_for_each_entry(ticket, &space_info->tickets, list)
5074 to_reclaim += ticket->bytes;
5075 list_for_each_entry(ticket, &space_info->priority_tickets, list)
5076 to_reclaim += ticket->bytes;
5077 if (to_reclaim)
5078 return to_reclaim;
21c7e756 5079
e0af2484 5080 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
c1c4919b
JM
5081 if (can_overcommit(fs_info, space_info, to_reclaim,
5082 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
e0af2484
WX
5083 return 0;
5084
0eee8a49
NB
5085 used = btrfs_space_info_used(space_info, true);
5086
c1c4919b
JM
5087 if (can_overcommit(fs_info, space_info, SZ_1M,
5088 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
21c7e756
MX
5089 expected = div_factor_fine(space_info->total_bytes, 95);
5090 else
5091 expected = div_factor_fine(space_info->total_bytes, 90);
5092
5093 if (used > expected)
5094 to_reclaim = used - expected;
5095 else
5096 to_reclaim = 0;
5097 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
5098 space_info->bytes_reserved);
21c7e756
MX
5099 return to_reclaim;
5100}
5101
c1c4919b
JM
5102static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
5103 struct btrfs_space_info *space_info,
5104 u64 used, bool system_chunk)
21c7e756 5105{
365c5313
JB
5106 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
5107
5108 /* If we're just plain full then async reclaim just slows us down. */
baee8790 5109 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
365c5313
JB
5110 return 0;
5111
c1c4919b
JM
5112 if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5113 system_chunk))
d38b349c
JB
5114 return 0;
5115
0b246afa
JM
5116 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
5117 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
21c7e756
MX
5118}
5119
957780eb 5120static void wake_all_tickets(struct list_head *head)
21c7e756 5121{
957780eb 5122 struct reserve_ticket *ticket;
25ce459c 5123
957780eb
JB
5124 while (!list_empty(head)) {
5125 ticket = list_first_entry(head, struct reserve_ticket, list);
5126 list_del_init(&ticket->list);
5127 ticket->error = -ENOSPC;
5128 wake_up(&ticket->wait);
21c7e756 5129 }
21c7e756
MX
5130}
5131
957780eb
JB
5132/*
5133 * This is for normal flushers, we can wait all goddamned day if we want to. We
5134 * will loop and continuously try to flush as long as we are making progress.
5135 * We count progress as clearing off tickets each time we have to loop.
5136 */
21c7e756
MX
5137static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
5138{
5139 struct btrfs_fs_info *fs_info;
5140 struct btrfs_space_info *space_info;
5141 u64 to_reclaim;
5142 int flush_state;
957780eb 5143 int commit_cycles = 0;
ce129655 5144 u64 last_tickets_id;
21c7e756
MX
5145
5146 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
5147 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5148
957780eb 5149 spin_lock(&space_info->lock);
c1c4919b
JM
5150 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5151 false);
957780eb
JB
5152 if (!to_reclaim) {
5153 space_info->flush = 0;
5154 spin_unlock(&space_info->lock);
21c7e756 5155 return;
957780eb 5156 }
ce129655 5157 last_tickets_id = space_info->tickets_id;
957780eb 5158 spin_unlock(&space_info->lock);
21c7e756
MX
5159
5160 flush_state = FLUSH_DELAYED_ITEMS_NR;
957780eb 5161 do {
e38ae7a0 5162 flush_space(fs_info, space_info, to_reclaim, flush_state);
957780eb
JB
5163 spin_lock(&space_info->lock);
5164 if (list_empty(&space_info->tickets)) {
5165 space_info->flush = 0;
5166 spin_unlock(&space_info->lock);
5167 return;
5168 }
c1c4919b
JM
5169 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
5170 space_info,
5171 false);
ce129655 5172 if (last_tickets_id == space_info->tickets_id) {
957780eb
JB
5173 flush_state++;
5174 } else {
ce129655 5175 last_tickets_id = space_info->tickets_id;
957780eb
JB
5176 flush_state = FLUSH_DELAYED_ITEMS_NR;
5177 if (commit_cycles)
5178 commit_cycles--;
5179 }
5180
5181 if (flush_state > COMMIT_TRANS) {
5182 commit_cycles++;
5183 if (commit_cycles > 2) {
5184 wake_all_tickets(&space_info->tickets);
5185 space_info->flush = 0;
5186 } else {
5187 flush_state = FLUSH_DELAYED_ITEMS_NR;
5188 }
5189 }
5190 spin_unlock(&space_info->lock);
5191 } while (flush_state <= COMMIT_TRANS);
5192}
5193
5194void btrfs_init_async_reclaim_work(struct work_struct *work)
5195{
5196 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5197}
5198
5199static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5200 struct btrfs_space_info *space_info,
5201 struct reserve_ticket *ticket)
5202{
5203 u64 to_reclaim;
5204 int flush_state = FLUSH_DELAYED_ITEMS_NR;
5205
5206 spin_lock(&space_info->lock);
c1c4919b
JM
5207 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5208 false);
957780eb
JB
5209 if (!to_reclaim) {
5210 spin_unlock(&space_info->lock);
5211 return;
5212 }
5213 spin_unlock(&space_info->lock);
5214
21c7e756 5215 do {
7bdd6277 5216 flush_space(fs_info, space_info, to_reclaim, flush_state);
21c7e756 5217 flush_state++;
957780eb
JB
5218 spin_lock(&space_info->lock);
5219 if (ticket->bytes == 0) {
5220 spin_unlock(&space_info->lock);
21c7e756 5221 return;
957780eb
JB
5222 }
5223 spin_unlock(&space_info->lock);
5224
5225 /*
5226 * Priority flushers can't wait on delalloc without
5227 * deadlocking.
5228 */
5229 if (flush_state == FLUSH_DELALLOC ||
5230 flush_state == FLUSH_DELALLOC_WAIT)
5231 flush_state = ALLOC_CHUNK;
365c5313 5232 } while (flush_state < COMMIT_TRANS);
21c7e756
MX
5233}
5234
957780eb
JB
5235static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5236 struct btrfs_space_info *space_info,
5237 struct reserve_ticket *ticket, u64 orig_bytes)
5238
21c7e756 5239{
957780eb
JB
5240 DEFINE_WAIT(wait);
5241 int ret = 0;
5242
5243 spin_lock(&space_info->lock);
5244 while (ticket->bytes > 0 && ticket->error == 0) {
5245 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5246 if (ret) {
5247 ret = -EINTR;
5248 break;
5249 }
5250 spin_unlock(&space_info->lock);
5251
5252 schedule();
5253
5254 finish_wait(&ticket->wait, &wait);
5255 spin_lock(&space_info->lock);
5256 }
5257 if (!ret)
5258 ret = ticket->error;
5259 if (!list_empty(&ticket->list))
5260 list_del_init(&ticket->list);
5261 if (ticket->bytes && ticket->bytes < orig_bytes) {
5262 u64 num_bytes = orig_bytes - ticket->bytes;
5263 space_info->bytes_may_use -= num_bytes;
5264 trace_btrfs_space_reservation(fs_info, "space_info",
5265 space_info->flags, num_bytes, 0);
5266 }
5267 spin_unlock(&space_info->lock);
5268
5269 return ret;
21c7e756
MX
5270}
5271
4a92b1b8
JB
5272/**
5273 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5274 * @root - the root we're allocating for
957780eb 5275 * @space_info - the space info we want to allocate from
4a92b1b8 5276 * @orig_bytes - the number of bytes we want
48fc7f7e 5277 * @flush - whether or not we can flush to make our reservation
8bb8ab2e 5278 *
01327610 5279 * This will reserve orig_bytes number of bytes from the space info associated
4a92b1b8
JB
5280 * with the block_rsv. If there is not enough space it will make an attempt to
5281 * flush out space to make room. It will do this by flushing delalloc if
5282 * possible or committing the transaction. If flush is 0 then no attempts to
5283 * regain reservations will be made and this will fail if there is not enough
5284 * space already.
8bb8ab2e 5285 */
c1c4919b 5286static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
957780eb
JB
5287 struct btrfs_space_info *space_info,
5288 u64 orig_bytes,
c1c4919b
JM
5289 enum btrfs_reserve_flush_enum flush,
5290 bool system_chunk)
9ed74f2d 5291{
957780eb 5292 struct reserve_ticket ticket;
2bf64758 5293 u64 used;
8bb8ab2e 5294 int ret = 0;
9ed74f2d 5295
957780eb 5296 ASSERT(orig_bytes);
8ca17f0f 5297 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
fdb5effd 5298
8bb8ab2e 5299 spin_lock(&space_info->lock);
fdb5effd 5300 ret = -ENOSPC;
4136135b 5301 used = btrfs_space_info_used(space_info, true);
9ed74f2d 5302
8bb8ab2e 5303 /*
957780eb
JB
5304 * If we have enough space then hooray, make our reservation and carry
5305 * on. If not see if we can overcommit, and if we can, hooray carry on.
5306 * If not things get more complicated.
8bb8ab2e 5307 */
957780eb
JB
5308 if (used + orig_bytes <= space_info->total_bytes) {
5309 space_info->bytes_may_use += orig_bytes;
0b246afa
JM
5310 trace_btrfs_space_reservation(fs_info, "space_info",
5311 space_info->flags, orig_bytes, 1);
957780eb 5312 ret = 0;
c1c4919b
JM
5313 } else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
5314 system_chunk)) {
44734ed1 5315 space_info->bytes_may_use += orig_bytes;
0b246afa
JM
5316 trace_btrfs_space_reservation(fs_info, "space_info",
5317 space_info->flags, orig_bytes, 1);
44734ed1 5318 ret = 0;
2bf64758
JB
5319 }
5320
8bb8ab2e 5321 /*
957780eb
JB
5322 * If we couldn't make a reservation then setup our reservation ticket
5323 * and kick the async worker if it's not already running.
08e007d2 5324 *
957780eb
JB
5325 * If we are a priority flusher then we just need to add our ticket to
5326 * the list and we will do our own flushing further down.
8bb8ab2e 5327 */
72bcd99d 5328 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
957780eb
JB
5329 ticket.bytes = orig_bytes;
5330 ticket.error = 0;
5331 init_waitqueue_head(&ticket.wait);
5332 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5333 list_add_tail(&ticket.list, &space_info->tickets);
5334 if (!space_info->flush) {
5335 space_info->flush = 1;
0b246afa 5336 trace_btrfs_trigger_flush(fs_info,
f376df2b
JB
5337 space_info->flags,
5338 orig_bytes, flush,
5339 "enospc");
957780eb 5340 queue_work(system_unbound_wq,
c1c4919b 5341 &fs_info->async_reclaim_work);
957780eb
JB
5342 }
5343 } else {
5344 list_add_tail(&ticket.list,
5345 &space_info->priority_tickets);
5346 }
21c7e756
MX
5347 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5348 used += orig_bytes;
f6acfd50
JB
5349 /*
5350 * We will do the space reservation dance during log replay,
5351 * which means we won't have fs_info->fs_root set, so don't do
5352 * the async reclaim as we will panic.
5353 */
0b246afa 5354 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
c1c4919b
JM
5355 need_do_async_reclaim(fs_info, space_info,
5356 used, system_chunk) &&
0b246afa
JM
5357 !work_busy(&fs_info->async_reclaim_work)) {
5358 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5359 orig_bytes, flush, "preempt");
21c7e756 5360 queue_work(system_unbound_wq,
0b246afa 5361 &fs_info->async_reclaim_work);
f376df2b 5362 }
8bb8ab2e 5363 }
f0486c68 5364 spin_unlock(&space_info->lock);
08e007d2 5365 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
957780eb 5366 return ret;
f0486c68 5367
957780eb 5368 if (flush == BTRFS_RESERVE_FLUSH_ALL)
0b246afa 5369 return wait_reserve_ticket(fs_info, space_info, &ticket,
957780eb 5370 orig_bytes);
08e007d2 5371
957780eb 5372 ret = 0;
0b246afa 5373 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
957780eb
JB
5374 spin_lock(&space_info->lock);
5375 if (ticket.bytes) {
5376 if (ticket.bytes < orig_bytes) {
5377 u64 num_bytes = orig_bytes - ticket.bytes;
5378 space_info->bytes_may_use -= num_bytes;
0b246afa
JM
5379 trace_btrfs_space_reservation(fs_info, "space_info",
5380 space_info->flags,
5381 num_bytes, 0);
08e007d2 5382
957780eb
JB
5383 }
5384 list_del_init(&ticket.list);
5385 ret = -ENOSPC;
5386 }
5387 spin_unlock(&space_info->lock);
5388 ASSERT(list_empty(&ticket.list));
5389 return ret;
5390}
8bb8ab2e 5391
957780eb
JB
5392/**
5393 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5394 * @root - the root we're allocating for
5395 * @block_rsv - the block_rsv we're allocating for
5396 * @orig_bytes - the number of bytes we want
5397 * @flush - whether or not we can flush to make our reservation
5398 *
5399 * This will reserve orgi_bytes number of bytes from the space info associated
5400 * with the block_rsv. If there is not enough space it will make an attempt to
5401 * flush out space to make room. It will do this by flushing delalloc if
5402 * possible or committing the transaction. If flush is 0 then no attempts to
5403 * regain reservations will be made and this will fail if there is not enough
5404 * space already.
5405 */
5406static int reserve_metadata_bytes(struct btrfs_root *root,
5407 struct btrfs_block_rsv *block_rsv,
5408 u64 orig_bytes,
5409 enum btrfs_reserve_flush_enum flush)
5410{
0b246afa
JM
5411 struct btrfs_fs_info *fs_info = root->fs_info;
5412 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
957780eb 5413 int ret;
c1c4919b 5414 bool system_chunk = (root == fs_info->chunk_root);
957780eb 5415
c1c4919b
JM
5416 ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
5417 orig_bytes, flush, system_chunk);
5d80366e
JB
5418 if (ret == -ENOSPC &&
5419 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5d80366e
JB
5420 if (block_rsv != global_rsv &&
5421 !block_rsv_use_bytes(global_rsv, orig_bytes))
5422 ret = 0;
5423 }
cab45e22 5424 if (ret == -ENOSPC)
0b246afa 5425 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
957780eb
JB
5426 block_rsv->space_info->flags,
5427 orig_bytes, 1);
f0486c68
YZ
5428 return ret;
5429}
5430
79787eaa
JM
5431static struct btrfs_block_rsv *get_block_rsv(
5432 const struct btrfs_trans_handle *trans,
5433 const struct btrfs_root *root)
f0486c68 5434{
0b246afa 5435 struct btrfs_fs_info *fs_info = root->fs_info;
4c13d758
JB
5436 struct btrfs_block_rsv *block_rsv = NULL;
5437
e9cf439f 5438 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa
JM
5439 (root == fs_info->csum_root && trans->adding_csums) ||
5440 (root == fs_info->uuid_root))
f7a81ea4
SB
5441 block_rsv = trans->block_rsv;
5442
4c13d758 5443 if (!block_rsv)
f0486c68
YZ
5444 block_rsv = root->block_rsv;
5445
5446 if (!block_rsv)
0b246afa 5447 block_rsv = &fs_info->empty_block_rsv;
f0486c68
YZ
5448
5449 return block_rsv;
5450}
5451
5452static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5453 u64 num_bytes)
5454{
5455 int ret = -ENOSPC;
5456 spin_lock(&block_rsv->lock);
5457 if (block_rsv->reserved >= num_bytes) {
5458 block_rsv->reserved -= num_bytes;
5459 if (block_rsv->reserved < block_rsv->size)
5460 block_rsv->full = 0;
5461 ret = 0;
5462 }
5463 spin_unlock(&block_rsv->lock);
5464 return ret;
5465}
5466
5467static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5468 u64 num_bytes, int update_size)
5469{
5470 spin_lock(&block_rsv->lock);
5471 block_rsv->reserved += num_bytes;
5472 if (update_size)
5473 block_rsv->size += num_bytes;
5474 else if (block_rsv->reserved >= block_rsv->size)
5475 block_rsv->full = 1;
5476 spin_unlock(&block_rsv->lock);
5477}
5478
d52be818
JB
5479int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5480 struct btrfs_block_rsv *dest, u64 num_bytes,
5481 int min_factor)
5482{
5483 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5484 u64 min_bytes;
5485
5486 if (global_rsv->space_info != dest->space_info)
5487 return -ENOSPC;
5488
5489 spin_lock(&global_rsv->lock);
5490 min_bytes = div_factor(global_rsv->size, min_factor);
5491 if (global_rsv->reserved < min_bytes + num_bytes) {
5492 spin_unlock(&global_rsv->lock);
5493 return -ENOSPC;
5494 }
5495 global_rsv->reserved -= num_bytes;
5496 if (global_rsv->reserved < global_rsv->size)
5497 global_rsv->full = 0;
5498 spin_unlock(&global_rsv->lock);
5499
5500 block_rsv_add_bytes(dest, num_bytes, 1);
5501 return 0;
5502}
5503
957780eb
JB
5504/*
5505 * This is for space we already have accounted in space_info->bytes_may_use, so
5506 * basically when we're returning space from block_rsv's.
5507 */
5508static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5509 struct btrfs_space_info *space_info,
5510 u64 num_bytes)
5511{
5512 struct reserve_ticket *ticket;
5513 struct list_head *head;
5514 u64 used;
5515 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5516 bool check_overcommit = false;
5517
5518 spin_lock(&space_info->lock);
5519 head = &space_info->priority_tickets;
5520
5521 /*
5522 * If we are over our limit then we need to check and see if we can
5523 * overcommit, and if we can't then we just need to free up our space
5524 * and not satisfy any requests.
5525 */
0eee8a49 5526 used = btrfs_space_info_used(space_info, true);
957780eb
JB
5527 if (used - num_bytes >= space_info->total_bytes)
5528 check_overcommit = true;
5529again:
5530 while (!list_empty(head) && num_bytes) {
5531 ticket = list_first_entry(head, struct reserve_ticket,
5532 list);
5533 /*
5534 * We use 0 bytes because this space is already reserved, so
5535 * adding the ticket space would be a double count.
5536 */
5537 if (check_overcommit &&
c1c4919b 5538 !can_overcommit(fs_info, space_info, 0, flush, false))
957780eb
JB
5539 break;
5540 if (num_bytes >= ticket->bytes) {
5541 list_del_init(&ticket->list);
5542 num_bytes -= ticket->bytes;
5543 ticket->bytes = 0;
ce129655 5544 space_info->tickets_id++;
957780eb
JB
5545 wake_up(&ticket->wait);
5546 } else {
5547 ticket->bytes -= num_bytes;
5548 num_bytes = 0;
5549 }
5550 }
5551
5552 if (num_bytes && head == &space_info->priority_tickets) {
5553 head = &space_info->tickets;
5554 flush = BTRFS_RESERVE_FLUSH_ALL;
5555 goto again;
5556 }
5557 space_info->bytes_may_use -= num_bytes;
5558 trace_btrfs_space_reservation(fs_info, "space_info",
5559 space_info->flags, num_bytes, 0);
5560 spin_unlock(&space_info->lock);
5561}
5562
5563/*
5564 * This is for newly allocated space that isn't accounted in
5565 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5566 * we use this helper.
5567 */
5568static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5569 struct btrfs_space_info *space_info,
5570 u64 num_bytes)
5571{
5572 struct reserve_ticket *ticket;
5573 struct list_head *head = &space_info->priority_tickets;
5574
5575again:
5576 while (!list_empty(head) && num_bytes) {
5577 ticket = list_first_entry(head, struct reserve_ticket,
5578 list);
5579 if (num_bytes >= ticket->bytes) {
5580 trace_btrfs_space_reservation(fs_info, "space_info",
5581 space_info->flags,
5582 ticket->bytes, 1);
5583 list_del_init(&ticket->list);
5584 num_bytes -= ticket->bytes;
5585 space_info->bytes_may_use += ticket->bytes;
5586 ticket->bytes = 0;
ce129655 5587 space_info->tickets_id++;
957780eb
JB
5588 wake_up(&ticket->wait);
5589 } else {
5590 trace_btrfs_space_reservation(fs_info, "space_info",
5591 space_info->flags,
5592 num_bytes, 1);
5593 space_info->bytes_may_use += num_bytes;
5594 ticket->bytes -= num_bytes;
5595 num_bytes = 0;
5596 }
5597 }
5598
5599 if (num_bytes && head == &space_info->priority_tickets) {
5600 head = &space_info->tickets;
5601 goto again;
5602 }
5603}
5604
8c2a3ca2
JB
5605static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5606 struct btrfs_block_rsv *block_rsv,
62a45b60 5607 struct btrfs_block_rsv *dest, u64 num_bytes)
f0486c68
YZ
5608{
5609 struct btrfs_space_info *space_info = block_rsv->space_info;
5610
5611 spin_lock(&block_rsv->lock);
5612 if (num_bytes == (u64)-1)
5613 num_bytes = block_rsv->size;
5614 block_rsv->size -= num_bytes;
5615 if (block_rsv->reserved >= block_rsv->size) {
5616 num_bytes = block_rsv->reserved - block_rsv->size;
5617 block_rsv->reserved = block_rsv->size;
5618 block_rsv->full = 1;
5619 } else {
5620 num_bytes = 0;
5621 }
5622 spin_unlock(&block_rsv->lock);
5623
5624 if (num_bytes > 0) {
5625 if (dest) {
e9e22899
JB
5626 spin_lock(&dest->lock);
5627 if (!dest->full) {
5628 u64 bytes_to_add;
5629
5630 bytes_to_add = dest->size - dest->reserved;
5631 bytes_to_add = min(num_bytes, bytes_to_add);
5632 dest->reserved += bytes_to_add;
5633 if (dest->reserved >= dest->size)
5634 dest->full = 1;
5635 num_bytes -= bytes_to_add;
5636 }
5637 spin_unlock(&dest->lock);
5638 }
957780eb
JB
5639 if (num_bytes)
5640 space_info_add_old_bytes(fs_info, space_info,
5641 num_bytes);
9ed74f2d 5642 }
f0486c68 5643}
4e06bdd6 5644
25d609f8
JB
5645int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5646 struct btrfs_block_rsv *dst, u64 num_bytes,
5647 int update_size)
f0486c68
YZ
5648{
5649 int ret;
9ed74f2d 5650
f0486c68
YZ
5651 ret = block_rsv_use_bytes(src, num_bytes);
5652 if (ret)
5653 return ret;
9ed74f2d 5654
25d609f8 5655 block_rsv_add_bytes(dst, num_bytes, update_size);
9ed74f2d
JB
5656 return 0;
5657}
5658
66d8f3dd 5659void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
9ed74f2d 5660{
f0486c68
YZ
5661 memset(rsv, 0, sizeof(*rsv));
5662 spin_lock_init(&rsv->lock);
66d8f3dd 5663 rsv->type = type;
f0486c68
YZ
5664}
5665
2ff7e61e 5666struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
66d8f3dd 5667 unsigned short type)
f0486c68
YZ
5668{
5669 struct btrfs_block_rsv *block_rsv;
9ed74f2d 5670
f0486c68
YZ
5671 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5672 if (!block_rsv)
5673 return NULL;
9ed74f2d 5674
66d8f3dd 5675 btrfs_init_block_rsv(block_rsv, type);
f0486c68
YZ
5676 block_rsv->space_info = __find_space_info(fs_info,
5677 BTRFS_BLOCK_GROUP_METADATA);
f0486c68
YZ
5678 return block_rsv;
5679}
9ed74f2d 5680
2ff7e61e 5681void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
f0486c68
YZ
5682 struct btrfs_block_rsv *rsv)
5683{
2aaa6655
JB
5684 if (!rsv)
5685 return;
2ff7e61e 5686 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
dabdb640 5687 kfree(rsv);
9ed74f2d
JB
5688}
5689
cdfb080e
CM
5690void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5691{
5692 kfree(rsv);
5693}
5694
08e007d2
MX
5695int btrfs_block_rsv_add(struct btrfs_root *root,
5696 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5697 enum btrfs_reserve_flush_enum flush)
9ed74f2d 5698{
f0486c68 5699 int ret;
9ed74f2d 5700
f0486c68
YZ
5701 if (num_bytes == 0)
5702 return 0;
8bb8ab2e 5703
61b520a9 5704 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
f0486c68
YZ
5705 if (!ret) {
5706 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5707 return 0;
5708 }
9ed74f2d 5709
f0486c68 5710 return ret;
f0486c68 5711}
9ed74f2d 5712
2ff7e61e 5713int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
f0486c68
YZ
5714{
5715 u64 num_bytes = 0;
f0486c68 5716 int ret = -ENOSPC;
9ed74f2d 5717
f0486c68
YZ
5718 if (!block_rsv)
5719 return 0;
9ed74f2d 5720
f0486c68 5721 spin_lock(&block_rsv->lock);
36ba022a
JB
5722 num_bytes = div_factor(block_rsv->size, min_factor);
5723 if (block_rsv->reserved >= num_bytes)
5724 ret = 0;
5725 spin_unlock(&block_rsv->lock);
9ed74f2d 5726
36ba022a
JB
5727 return ret;
5728}
5729
08e007d2
MX
5730int btrfs_block_rsv_refill(struct btrfs_root *root,
5731 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5732 enum btrfs_reserve_flush_enum flush)
36ba022a
JB
5733{
5734 u64 num_bytes = 0;
5735 int ret = -ENOSPC;
5736
5737 if (!block_rsv)
5738 return 0;
5739
5740 spin_lock(&block_rsv->lock);
5741 num_bytes = min_reserved;
13553e52 5742 if (block_rsv->reserved >= num_bytes)
f0486c68 5743 ret = 0;
13553e52 5744 else
f0486c68 5745 num_bytes -= block_rsv->reserved;
f0486c68 5746 spin_unlock(&block_rsv->lock);
13553e52 5747
f0486c68
YZ
5748 if (!ret)
5749 return 0;
5750
aa38a711 5751 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
dabdb640
JB
5752 if (!ret) {
5753 block_rsv_add_bytes(block_rsv, num_bytes, 0);
f0486c68 5754 return 0;
6a63209f 5755 }
9ed74f2d 5756
13553e52 5757 return ret;
f0486c68
YZ
5758}
5759
2ff7e61e 5760void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
f0486c68
YZ
5761 struct btrfs_block_rsv *block_rsv,
5762 u64 num_bytes)
5763{
0b246afa
JM
5764 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5765
17504584 5766 if (global_rsv == block_rsv ||
f0486c68
YZ
5767 block_rsv->space_info != global_rsv->space_info)
5768 global_rsv = NULL;
0b246afa 5769 block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
6a63209f
JB
5770}
5771
8929ecfa
YZ
5772static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5773{
5774 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5775 struct btrfs_space_info *sinfo = block_rsv->space_info;
5776 u64 num_bytes;
6a63209f 5777
ae2e4728
JB
5778 /*
5779 * The global block rsv is based on the size of the extent tree, the
5780 * checksum tree and the root tree. If the fs is empty we want to set
5781 * it to a minimal amount for safety.
5782 */
5783 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5784 btrfs_root_used(&fs_info->csum_root->root_item) +
5785 btrfs_root_used(&fs_info->tree_root->root_item);
5786 num_bytes = max_t(u64, num_bytes, SZ_16M);
33b4d47f 5787
8929ecfa 5788 spin_lock(&sinfo->lock);
1f699d38 5789 spin_lock(&block_rsv->lock);
4e06bdd6 5790
ee22184b 5791 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
4e06bdd6 5792
fb4b10e5 5793 if (block_rsv->reserved < block_rsv->size) {
4136135b 5794 num_bytes = btrfs_space_info_used(sinfo, true);
fb4b10e5
JB
5795 if (sinfo->total_bytes > num_bytes) {
5796 num_bytes = sinfo->total_bytes - num_bytes;
5797 num_bytes = min(num_bytes,
5798 block_rsv->size - block_rsv->reserved);
5799 block_rsv->reserved += num_bytes;
5800 sinfo->bytes_may_use += num_bytes;
5801 trace_btrfs_space_reservation(fs_info, "space_info",
5802 sinfo->flags, num_bytes,
5803 1);
5804 }
5805 } else if (block_rsv->reserved > block_rsv->size) {
8929ecfa 5806 num_bytes = block_rsv->reserved - block_rsv->size;
fb25e914 5807 sinfo->bytes_may_use -= num_bytes;
8c2a3ca2 5808 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 5809 sinfo->flags, num_bytes, 0);
8929ecfa 5810 block_rsv->reserved = block_rsv->size;
8929ecfa 5811 }
182608c8 5812
fb4b10e5
JB
5813 if (block_rsv->reserved == block_rsv->size)
5814 block_rsv->full = 1;
5815 else
5816 block_rsv->full = 0;
5817
8929ecfa 5818 spin_unlock(&block_rsv->lock);
1f699d38 5819 spin_unlock(&sinfo->lock);
6a63209f
JB
5820}
5821
f0486c68 5822static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 5823{
f0486c68 5824 struct btrfs_space_info *space_info;
6a63209f 5825
f0486c68
YZ
5826 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5827 fs_info->chunk_block_rsv.space_info = space_info;
6a63209f 5828
f0486c68 5829 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
8929ecfa 5830 fs_info->global_block_rsv.space_info = space_info;
8929ecfa 5831 fs_info->delalloc_block_rsv.space_info = space_info;
f0486c68
YZ
5832 fs_info->trans_block_rsv.space_info = space_info;
5833 fs_info->empty_block_rsv.space_info = space_info;
6d668dda 5834 fs_info->delayed_block_rsv.space_info = space_info;
f0486c68 5835
8929ecfa
YZ
5836 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5837 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5838 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5839 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3a6cad90
SB
5840 if (fs_info->quota_root)
5841 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
f0486c68 5842 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
8929ecfa 5843
8929ecfa 5844 update_global_block_rsv(fs_info);
6a63209f
JB
5845}
5846
8929ecfa 5847static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 5848{
8c2a3ca2
JB
5849 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5850 (u64)-1);
8929ecfa
YZ
5851 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5852 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5853 WARN_ON(fs_info->trans_block_rsv.size > 0);
5854 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5855 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5856 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
6d668dda
JB
5857 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5858 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
fcb80c2a
JB
5859}
5860
a22285a6 5861void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
2ff7e61e 5862 struct btrfs_fs_info *fs_info)
6a63209f 5863{
0e721106
JB
5864 if (!trans->block_rsv)
5865 return;
5866
a22285a6
YZ
5867 if (!trans->bytes_reserved)
5868 return;
6a63209f 5869
0b246afa 5870 trace_btrfs_space_reservation(fs_info, "transaction",
2bcc0328 5871 trans->transid, trans->bytes_reserved, 0);
2ff7e61e
JM
5872 btrfs_block_rsv_release(fs_info, trans->block_rsv,
5873 trans->bytes_reserved);
a22285a6
YZ
5874 trans->bytes_reserved = 0;
5875}
6a63209f 5876
4fbcdf66
FM
5877/*
5878 * To be called after all the new block groups attached to the transaction
5879 * handle have been created (btrfs_create_pending_block_groups()).
5880 */
5881void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5882{
64b63580 5883 struct btrfs_fs_info *fs_info = trans->fs_info;
4fbcdf66
FM
5884
5885 if (!trans->chunk_bytes_reserved)
5886 return;
5887
5888 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5889
5890 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5891 trans->chunk_bytes_reserved);
5892 trans->chunk_bytes_reserved = 0;
5893}
5894
79787eaa 5895/* Can only return 0 or -ENOSPC */
d68fc57b 5896int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
8ed7a2a0 5897 struct btrfs_inode *inode)
d68fc57b 5898{
8ed7a2a0
NB
5899 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
5900 struct btrfs_root *root = inode->root;
40acc3ee
JB
5901 /*
5902 * We always use trans->block_rsv here as we will have reserved space
5903 * for our orphan when starting the transaction, using get_block_rsv()
5904 * here will sometimes make us choose the wrong block rsv as we could be
5905 * doing a reloc inode for a non refcounted root.
5906 */
5907 struct btrfs_block_rsv *src_rsv = trans->block_rsv;
d68fc57b
YZ
5908 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5909
5910 /*
fcb80c2a
JB
5911 * We need to hold space in order to delete our orphan item once we've
5912 * added it, so this takes the reservation so we can release it later
5913 * when we are truly done with the orphan item.
d68fc57b 5914 */
0b246afa
JM
5915 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5916
8ed7a2a0
NB
5917 trace_btrfs_space_reservation(fs_info, "orphan", btrfs_ino(inode),
5918 num_bytes, 1);
25d609f8 5919 return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
6a63209f
JB
5920}
5921
703b391a 5922void btrfs_orphan_release_metadata(struct btrfs_inode *inode)
97e728d4 5923{
703b391a
NB
5924 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
5925 struct btrfs_root *root = inode->root;
0b246afa
JM
5926 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5927
703b391a
NB
5928 trace_btrfs_space_reservation(fs_info, "orphan", btrfs_ino(inode),
5929 num_bytes, 0);
2ff7e61e 5930 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
d68fc57b 5931}
97e728d4 5932
d5c12070
MX
5933/*
5934 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5935 * root: the root of the parent directory
5936 * rsv: block reservation
5937 * items: the number of items that we need do reservation
5938 * qgroup_reserved: used to return the reserved size in qgroup
5939 *
5940 * This function is used to reserve the space for snapshot/subvolume
5941 * creation and deletion. Those operations are different with the
5942 * common file/directory operations, they change two fs/file trees
5943 * and root tree, the number of items that the qgroup reserves is
5944 * different with the free space reservation. So we can not use
01327610 5945 * the space reservation mechanism in start_transaction().
d5c12070
MX
5946 */
5947int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5948 struct btrfs_block_rsv *rsv,
5949 int items,
ee3441b4
JM
5950 u64 *qgroup_reserved,
5951 bool use_global_rsv)
a22285a6 5952{
d5c12070
MX
5953 u64 num_bytes;
5954 int ret;
0b246afa
JM
5955 struct btrfs_fs_info *fs_info = root->fs_info;
5956 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
d5c12070 5957
0b246afa 5958 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
d5c12070 5959 /* One for parent inode, two for dir entries */
0b246afa 5960 num_bytes = 3 * fs_info->nodesize;
003d7c59 5961 ret = btrfs_qgroup_reserve_meta(root, num_bytes, true);
d5c12070
MX
5962 if (ret)
5963 return ret;
5964 } else {
5965 num_bytes = 0;
5966 }
5967
5968 *qgroup_reserved = num_bytes;
5969
0b246afa
JM
5970 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5971 rsv->space_info = __find_space_info(fs_info,
d5c12070
MX
5972 BTRFS_BLOCK_GROUP_METADATA);
5973 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5974 BTRFS_RESERVE_FLUSH_ALL);
ee3441b4
JM
5975
5976 if (ret == -ENOSPC && use_global_rsv)
25d609f8 5977 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
ee3441b4 5978
7174109c
QW
5979 if (ret && *qgroup_reserved)
5980 btrfs_qgroup_free_meta(root, *qgroup_reserved);
d5c12070
MX
5981
5982 return ret;
5983}
5984
2ff7e61e 5985void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
7775c818 5986 struct btrfs_block_rsv *rsv)
d5c12070 5987{
2ff7e61e 5988 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
97e728d4
JB
5989}
5990
7709cde3
JB
5991/**
5992 * drop_outstanding_extent - drop an outstanding extent
5993 * @inode: the inode we're dropping the extent for
01327610 5994 * @num_bytes: the number of bytes we're releasing.
7709cde3
JB
5995 *
5996 * This is called when we are freeing up an outstanding extent, either called
5997 * after an error or after an extent is written. This will return the number of
5998 * reserved extents that need to be freed. This must be called with
5999 * BTRFS_I(inode)->lock held.
6000 */
baa3ba39
NB
6001static unsigned drop_outstanding_extent(struct btrfs_inode *inode,
6002 u64 num_bytes)
9e0baf60 6003{
7fd2ae21 6004 unsigned drop_inode_space = 0;
9e0baf60 6005 unsigned dropped_extents = 0;
823bb20a 6006 unsigned num_extents;
9e0baf60 6007
823bb20a 6008 num_extents = count_max_extents(num_bytes);
dcab6a3b 6009 ASSERT(num_extents);
baa3ba39
NB
6010 ASSERT(inode->outstanding_extents >= num_extents);
6011 inode->outstanding_extents -= num_extents;
9e0baf60 6012
baa3ba39 6013 if (inode->outstanding_extents == 0 &&
72ac3c0d 6014 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
baa3ba39 6015 &inode->runtime_flags))
7fd2ae21 6016 drop_inode_space = 1;
7fd2ae21 6017
9e0baf60 6018 /*
01327610 6019 * If we have more or the same amount of outstanding extents than we have
9e0baf60
JB
6020 * reserved then we need to leave the reserved extents count alone.
6021 */
baa3ba39 6022 if (inode->outstanding_extents >= inode->reserved_extents)
7fd2ae21 6023 return drop_inode_space;
9e0baf60 6024
baa3ba39
NB
6025 dropped_extents = inode->reserved_extents - inode->outstanding_extents;
6026 inode->reserved_extents -= dropped_extents;
7fd2ae21 6027 return dropped_extents + drop_inode_space;
9e0baf60
JB
6028}
6029
7709cde3 6030/**
01327610
NS
6031 * calc_csum_metadata_size - return the amount of metadata space that must be
6032 * reserved/freed for the given bytes.
7709cde3
JB
6033 * @inode: the inode we're manipulating
6034 * @num_bytes: the number of bytes in question
6035 * @reserve: 1 if we are reserving space, 0 if we are freeing space
6036 *
6037 * This adjusts the number of csum_bytes in the inode and then returns the
6038 * correct amount of metadata that must either be reserved or freed. We
6039 * calculate how many checksums we can fit into one leaf and then divide the
6040 * number of bytes that will need to be checksumed by this value to figure out
6041 * how many checksums will be required. If we are adding bytes then the number
6042 * may go up and we will return the number of additional bytes that must be
6043 * reserved. If it is going down we will return the number of bytes that must
6044 * be freed.
6045 *
6046 * This must be called with BTRFS_I(inode)->lock held.
6047 */
0e6bf9b1 6048static u64 calc_csum_metadata_size(struct btrfs_inode *inode, u64 num_bytes,
7709cde3 6049 int reserve)
6324fbf3 6050{
0e6bf9b1 6051 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1262133b 6052 u64 old_csums, num_csums;
7709cde3 6053
0e6bf9b1 6054 if (inode->flags & BTRFS_INODE_NODATASUM && inode->csum_bytes == 0)
7709cde3
JB
6055 return 0;
6056
0e6bf9b1 6057 old_csums = btrfs_csum_bytes_to_leaves(fs_info, inode->csum_bytes);
7709cde3 6058 if (reserve)
0e6bf9b1 6059 inode->csum_bytes += num_bytes;
7709cde3 6060 else
0e6bf9b1
NB
6061 inode->csum_bytes -= num_bytes;
6062 num_csums = btrfs_csum_bytes_to_leaves(fs_info, inode->csum_bytes);
7709cde3
JB
6063
6064 /* No change, no need to reserve more */
6065 if (old_csums == num_csums)
6066 return 0;
6067
6068 if (reserve)
0b246afa 6069 return btrfs_calc_trans_metadata_size(fs_info,
7709cde3
JB
6070 num_csums - old_csums);
6071
0b246afa 6072 return btrfs_calc_trans_metadata_size(fs_info, old_csums - num_csums);
0ca1f7ce 6073}
c146afad 6074
9f3db423 6075int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
0ca1f7ce 6076{
9f3db423
NB
6077 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6078 struct btrfs_root *root = inode->root;
0b246afa 6079 struct btrfs_block_rsv *block_rsv = &fs_info->delalloc_block_rsv;
9e0baf60 6080 u64 to_reserve = 0;
660d3f6c 6081 u64 csum_bytes;
823bb20a 6082 unsigned nr_extents;
08e007d2 6083 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
eb6b88d9 6084 int ret = 0;
c64c2bd8 6085 bool delalloc_lock = true;
88e081bf
WS
6086 u64 to_free = 0;
6087 unsigned dropped;
48c3d480 6088 bool release_extra = false;
6324fbf3 6089
c64c2bd8
JB
6090 /* If we are a free space inode we need to not flush since we will be in
6091 * the middle of a transaction commit. We also don't need the delalloc
6092 * mutex since we won't race with anybody. We need this mostly to make
6093 * lockdep shut its filthy mouth.
bac357dc
JB
6094 *
6095 * If we have a transaction open (can happen if we call truncate_block
6096 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
c64c2bd8
JB
6097 */
6098 if (btrfs_is_free_space_inode(inode)) {
08e007d2 6099 flush = BTRFS_RESERVE_NO_FLUSH;
c64c2bd8 6100 delalloc_lock = false;
bac357dc
JB
6101 } else if (current->journal_info) {
6102 flush = BTRFS_RESERVE_FLUSH_LIMIT;
c64c2bd8 6103 }
c09544e0 6104
08e007d2 6105 if (flush != BTRFS_RESERVE_NO_FLUSH &&
0b246afa 6106 btrfs_transaction_in_commit(fs_info))
0ca1f7ce 6107 schedule_timeout(1);
ec44a35c 6108
c64c2bd8 6109 if (delalloc_lock)
9f3db423 6110 mutex_lock(&inode->delalloc_mutex);
c64c2bd8 6111
0b246afa 6112 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
8bb8ab2e 6113
9f3db423 6114 spin_lock(&inode->lock);
823bb20a 6115 nr_extents = count_max_extents(num_bytes);
9f3db423 6116 inode->outstanding_extents += nr_extents;
9e0baf60 6117
48c3d480 6118 nr_extents = 0;
9f3db423
NB
6119 if (inode->outstanding_extents > inode->reserved_extents)
6120 nr_extents += inode->outstanding_extents -
6121 inode->reserved_extents;
57a45ced 6122
48c3d480 6123 /* We always want to reserve a slot for updating the inode. */
0b246afa 6124 to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
7709cde3 6125 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
9f3db423
NB
6126 csum_bytes = inode->csum_bytes;
6127 spin_unlock(&inode->lock);
57a45ced 6128
0b246afa 6129 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
7174109c 6130 ret = btrfs_qgroup_reserve_meta(root,
003d7c59 6131 nr_extents * fs_info->nodesize, true);
88e081bf
WS
6132 if (ret)
6133 goto out_fail;
6134 }
c5567237 6135
48c3d480 6136 ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
88e081bf 6137 if (unlikely(ret)) {
da17066c 6138 btrfs_qgroup_free_meta(root,
0b246afa 6139 nr_extents * fs_info->nodesize);
88e081bf 6140 goto out_fail;
9e0baf60 6141 }
25179201 6142
9f3db423 6143 spin_lock(&inode->lock);
48c3d480 6144 if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
9f3db423 6145 &inode->runtime_flags)) {
0b246afa 6146 to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
48c3d480 6147 release_extra = true;
660d3f6c 6148 }
9f3db423
NB
6149 inode->reserved_extents += nr_extents;
6150 spin_unlock(&inode->lock);
c64c2bd8
JB
6151
6152 if (delalloc_lock)
9f3db423 6153 mutex_unlock(&inode->delalloc_mutex);
660d3f6c 6154
8c2a3ca2 6155 if (to_reserve)
0b246afa 6156 trace_btrfs_space_reservation(fs_info, "delalloc",
9f3db423 6157 btrfs_ino(inode), to_reserve, 1);
48c3d480 6158 if (release_extra)
2ff7e61e 6159 btrfs_block_rsv_release(fs_info, block_rsv,
0b246afa 6160 btrfs_calc_trans_metadata_size(fs_info, 1));
0ca1f7ce 6161 return 0;
88e081bf
WS
6162
6163out_fail:
9f3db423 6164 spin_lock(&inode->lock);
dcab6a3b 6165 dropped = drop_outstanding_extent(inode, num_bytes);
88e081bf
WS
6166 /*
6167 * If the inodes csum_bytes is the same as the original
6168 * csum_bytes then we know we haven't raced with any free()ers
6169 * so we can just reduce our inodes csum bytes and carry on.
88e081bf 6170 */
9f3db423 6171 if (inode->csum_bytes == csum_bytes) {
88e081bf 6172 calc_csum_metadata_size(inode, num_bytes, 0);
f4881bc7 6173 } else {
9f3db423 6174 u64 orig_csum_bytes = inode->csum_bytes;
f4881bc7
JB
6175 u64 bytes;
6176
6177 /*
6178 * This is tricky, but first we need to figure out how much we
01327610 6179 * freed from any free-ers that occurred during this
f4881bc7
JB
6180 * reservation, so we reset ->csum_bytes to the csum_bytes
6181 * before we dropped our lock, and then call the free for the
6182 * number of bytes that were freed while we were trying our
6183 * reservation.
6184 */
9f3db423
NB
6185 bytes = csum_bytes - inode->csum_bytes;
6186 inode->csum_bytes = csum_bytes;
f4881bc7
JB
6187 to_free = calc_csum_metadata_size(inode, bytes, 0);
6188
6189
6190 /*
6191 * Now we need to see how much we would have freed had we not
6192 * been making this reservation and our ->csum_bytes were not
6193 * artificially inflated.
6194 */
9f3db423 6195 inode->csum_bytes = csum_bytes - num_bytes;
f4881bc7
JB
6196 bytes = csum_bytes - orig_csum_bytes;
6197 bytes = calc_csum_metadata_size(inode, bytes, 0);
6198
6199 /*
6200 * Now reset ->csum_bytes to what it should be. If bytes is
01327610 6201 * more than to_free then we would have freed more space had we
f4881bc7
JB
6202 * not had an artificially high ->csum_bytes, so we need to free
6203 * the remainder. If bytes is the same or less then we don't
6204 * need to do anything, the other free-ers did the correct
6205 * thing.
6206 */
9f3db423 6207 inode->csum_bytes = orig_csum_bytes - num_bytes;
f4881bc7
JB
6208 if (bytes > to_free)
6209 to_free = bytes - to_free;
6210 else
6211 to_free = 0;
6212 }
9f3db423 6213 spin_unlock(&inode->lock);
e2d1f923 6214 if (dropped)
0b246afa 6215 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
88e081bf
WS
6216
6217 if (to_free) {
2ff7e61e 6218 btrfs_block_rsv_release(fs_info, block_rsv, to_free);
0b246afa 6219 trace_btrfs_space_reservation(fs_info, "delalloc",
9f3db423 6220 btrfs_ino(inode), to_free, 0);
88e081bf
WS
6221 }
6222 if (delalloc_lock)
9f3db423 6223 mutex_unlock(&inode->delalloc_mutex);
88e081bf 6224 return ret;
0ca1f7ce
YZ
6225}
6226
7709cde3
JB
6227/**
6228 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6229 * @inode: the inode to release the reservation for
6230 * @num_bytes: the number of bytes we're releasing
6231 *
6232 * This will release the metadata reservation for an inode. This can be called
6233 * once we complete IO for a given set of bytes to release their metadata
6234 * reservations.
6235 */
691fa059 6236void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes)
0ca1f7ce 6237{
691fa059 6238 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
9e0baf60
JB
6239 u64 to_free = 0;
6240 unsigned dropped;
0ca1f7ce 6241
0b246afa 6242 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
691fa059 6243 spin_lock(&inode->lock);
dcab6a3b 6244 dropped = drop_outstanding_extent(inode, num_bytes);
97e728d4 6245
0934856d
MX
6246 if (num_bytes)
6247 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
691fa059 6248 spin_unlock(&inode->lock);
9e0baf60 6249 if (dropped > 0)
0b246afa 6250 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
0ca1f7ce 6251
0b246afa 6252 if (btrfs_is_testing(fs_info))
6a3891c5
JB
6253 return;
6254
691fa059
NB
6255 trace_btrfs_space_reservation(fs_info, "delalloc", btrfs_ino(inode),
6256 to_free, 0);
c5567237 6257
2ff7e61e 6258 btrfs_block_rsv_release(fs_info, &fs_info->delalloc_block_rsv, to_free);
0ca1f7ce
YZ
6259}
6260
1ada3a62 6261/**
7cf5b976 6262 * btrfs_delalloc_reserve_space - reserve data and metadata space for
1ada3a62
QW
6263 * delalloc
6264 * @inode: inode we're writing to
6265 * @start: start range we are writing to
6266 * @len: how long the range we are writing to
364ecf36
QW
6267 * @reserved: mandatory parameter, record actually reserved qgroup ranges of
6268 * current reservation.
1ada3a62 6269 *
1ada3a62
QW
6270 * This will do the following things
6271 *
6272 * o reserve space in data space info for num bytes
6273 * and reserve precious corresponding qgroup space
6274 * (Done in check_data_free_space)
6275 *
6276 * o reserve space for metadata space, based on the number of outstanding
6277 * extents and how much csums will be needed
6278 * also reserve metadata space in a per root over-reserve method.
6279 * o add to the inodes->delalloc_bytes
6280 * o add it to the fs_info's delalloc inodes list.
6281 * (Above 3 all done in delalloc_reserve_metadata)
6282 *
6283 * Return 0 for success
6284 * Return <0 for error(-ENOSPC or -EQUOT)
6285 */
364ecf36
QW
6286int btrfs_delalloc_reserve_space(struct inode *inode,
6287 struct extent_changeset **reserved, u64 start, u64 len)
1ada3a62
QW
6288{
6289 int ret;
6290
364ecf36 6291 ret = btrfs_check_data_free_space(inode, reserved, start, len);
1ada3a62
QW
6292 if (ret < 0)
6293 return ret;
9f3db423 6294 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
1ada3a62 6295 if (ret < 0)
bc42bda2 6296 btrfs_free_reserved_data_space(inode, *reserved, start, len);
1ada3a62
QW
6297 return ret;
6298}
6299
7709cde3 6300/**
7cf5b976 6301 * btrfs_delalloc_release_space - release data and metadata space for delalloc
1ada3a62
QW
6302 * @inode: inode we're releasing space for
6303 * @start: start position of the space already reserved
6304 * @len: the len of the space already reserved
6305 *
6306 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
6307 * called in the case that we don't need the metadata AND data reservations
6308 * anymore. So if there is an error or we insert an inline extent.
6309 *
6310 * This function will release the metadata space that was not used and will
6311 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6312 * list if there are no delalloc bytes left.
6313 * Also it will handle the qgroup reserved space.
6314 */
bc42bda2
QW
6315void btrfs_delalloc_release_space(struct inode *inode,
6316 struct extent_changeset *reserved, u64 start, u64 len)
1ada3a62 6317{
691fa059 6318 btrfs_delalloc_release_metadata(BTRFS_I(inode), len);
bc42bda2 6319 btrfs_free_reserved_data_space(inode, reserved, start, len);
6324fbf3
CM
6320}
6321
ce93ec54 6322static int update_block_group(struct btrfs_trans_handle *trans,
6202df69 6323 struct btrfs_fs_info *info, u64 bytenr,
ce93ec54 6324 u64 num_bytes, int alloc)
9078a3e1 6325{
0af3d00b 6326 struct btrfs_block_group_cache *cache = NULL;
db94535d 6327 u64 total = num_bytes;
9078a3e1 6328 u64 old_val;
db94535d 6329 u64 byte_in_group;
0af3d00b 6330 int factor;
3e1ad54f 6331
5d4f98a2 6332 /* block accounting for super block */
eb73c1b7 6333 spin_lock(&info->delalloc_root_lock);
6c41761f 6334 old_val = btrfs_super_bytes_used(info->super_copy);
5d4f98a2
YZ
6335 if (alloc)
6336 old_val += num_bytes;
6337 else
6338 old_val -= num_bytes;
6c41761f 6339 btrfs_set_super_bytes_used(info->super_copy, old_val);
eb73c1b7 6340 spin_unlock(&info->delalloc_root_lock);
5d4f98a2 6341
d397712b 6342 while (total) {
db94535d 6343 cache = btrfs_lookup_block_group(info, bytenr);
f3465ca4 6344 if (!cache)
79787eaa 6345 return -ENOENT;
b742bb82
YZ
6346 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
6347 BTRFS_BLOCK_GROUP_RAID1 |
6348 BTRFS_BLOCK_GROUP_RAID10))
6349 factor = 2;
6350 else
6351 factor = 1;
9d66e233
JB
6352 /*
6353 * If this block group has free space cache written out, we
6354 * need to make sure to load it if we are removing space. This
6355 * is because we need the unpinning stage to actually add the
6356 * space back to the block group, otherwise we will leak space.
6357 */
6358 if (!alloc && cache->cached == BTRFS_CACHE_NO)
f6373bf3 6359 cache_block_group(cache, 1);
0af3d00b 6360
db94535d
CM
6361 byte_in_group = bytenr - cache->key.objectid;
6362 WARN_ON(byte_in_group > cache->key.offset);
9078a3e1 6363
25179201 6364 spin_lock(&cache->space_info->lock);
c286ac48 6365 spin_lock(&cache->lock);
0af3d00b 6366
6202df69 6367 if (btrfs_test_opt(info, SPACE_CACHE) &&
0af3d00b
JB
6368 cache->disk_cache_state < BTRFS_DC_CLEAR)
6369 cache->disk_cache_state = BTRFS_DC_CLEAR;
6370
9078a3e1 6371 old_val = btrfs_block_group_used(&cache->item);
db94535d 6372 num_bytes = min(total, cache->key.offset - byte_in_group);
cd1bc465 6373 if (alloc) {
db94535d 6374 old_val += num_bytes;
11833d66
YZ
6375 btrfs_set_block_group_used(&cache->item, old_val);
6376 cache->reserved -= num_bytes;
11833d66 6377 cache->space_info->bytes_reserved -= num_bytes;
b742bb82
YZ
6378 cache->space_info->bytes_used += num_bytes;
6379 cache->space_info->disk_used += num_bytes * factor;
c286ac48 6380 spin_unlock(&cache->lock);
25179201 6381 spin_unlock(&cache->space_info->lock);
cd1bc465 6382 } else {
db94535d 6383 old_val -= num_bytes;
ae0ab003
FM
6384 btrfs_set_block_group_used(&cache->item, old_val);
6385 cache->pinned += num_bytes;
6386 cache->space_info->bytes_pinned += num_bytes;
6387 cache->space_info->bytes_used -= num_bytes;
6388 cache->space_info->disk_used -= num_bytes * factor;
6389 spin_unlock(&cache->lock);
6390 spin_unlock(&cache->space_info->lock);
47ab2a6c 6391
0b246afa 6392 trace_btrfs_space_reservation(info, "pinned",
c51e7bb1
JB
6393 cache->space_info->flags,
6394 num_bytes, 1);
d7eae340
OS
6395 percpu_counter_add(&cache->space_info->total_bytes_pinned,
6396 num_bytes);
ae0ab003
FM
6397 set_extent_dirty(info->pinned_extents,
6398 bytenr, bytenr + num_bytes - 1,
6399 GFP_NOFS | __GFP_NOFAIL);
cd1bc465 6400 }
1bbc621e
CM
6401
6402 spin_lock(&trans->transaction->dirty_bgs_lock);
6403 if (list_empty(&cache->dirty_list)) {
6404 list_add_tail(&cache->dirty_list,
6405 &trans->transaction->dirty_bgs);
6406 trans->transaction->num_dirty_bgs++;
6407 btrfs_get_block_group(cache);
6408 }
6409 spin_unlock(&trans->transaction->dirty_bgs_lock);
6410
036a9348
FM
6411 /*
6412 * No longer have used bytes in this block group, queue it for
6413 * deletion. We do this after adding the block group to the
6414 * dirty list to avoid races between cleaner kthread and space
6415 * cache writeout.
6416 */
6417 if (!alloc && old_val == 0) {
6418 spin_lock(&info->unused_bgs_lock);
6419 if (list_empty(&cache->bg_list)) {
6420 btrfs_get_block_group(cache);
6421 list_add_tail(&cache->bg_list,
6422 &info->unused_bgs);
6423 }
6424 spin_unlock(&info->unused_bgs_lock);
6425 }
6426
fa9c0d79 6427 btrfs_put_block_group(cache);
db94535d
CM
6428 total -= num_bytes;
6429 bytenr += num_bytes;
9078a3e1
CM
6430 }
6431 return 0;
6432}
6324fbf3 6433
2ff7e61e 6434static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
a061fc8d 6435{
0f9dd46c 6436 struct btrfs_block_group_cache *cache;
d2fb3437 6437 u64 bytenr;
0f9dd46c 6438
0b246afa
JM
6439 spin_lock(&fs_info->block_group_cache_lock);
6440 bytenr = fs_info->first_logical_byte;
6441 spin_unlock(&fs_info->block_group_cache_lock);
a1897fdd
LB
6442
6443 if (bytenr < (u64)-1)
6444 return bytenr;
6445
0b246afa 6446 cache = btrfs_lookup_first_block_group(fs_info, search_start);
0f9dd46c 6447 if (!cache)
a061fc8d 6448 return 0;
0f9dd46c 6449
d2fb3437 6450 bytenr = cache->key.objectid;
fa9c0d79 6451 btrfs_put_block_group(cache);
d2fb3437
YZ
6452
6453 return bytenr;
a061fc8d
CM
6454}
6455
2ff7e61e 6456static int pin_down_extent(struct btrfs_fs_info *fs_info,
f0486c68
YZ
6457 struct btrfs_block_group_cache *cache,
6458 u64 bytenr, u64 num_bytes, int reserved)
324ae4df 6459{
11833d66
YZ
6460 spin_lock(&cache->space_info->lock);
6461 spin_lock(&cache->lock);
6462 cache->pinned += num_bytes;
6463 cache->space_info->bytes_pinned += num_bytes;
6464 if (reserved) {
6465 cache->reserved -= num_bytes;
6466 cache->space_info->bytes_reserved -= num_bytes;
6467 }
6468 spin_unlock(&cache->lock);
6469 spin_unlock(&cache->space_info->lock);
68b38550 6470
0b246afa 6471 trace_btrfs_space_reservation(fs_info, "pinned",
c51e7bb1 6472 cache->space_info->flags, num_bytes, 1);
4da8b76d 6473 percpu_counter_add(&cache->space_info->total_bytes_pinned, num_bytes);
0b246afa 6474 set_extent_dirty(fs_info->pinned_extents, bytenr,
f0486c68
YZ
6475 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6476 return 0;
6477}
68b38550 6478
f0486c68
YZ
6479/*
6480 * this function must be called within transaction
6481 */
2ff7e61e 6482int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
f0486c68
YZ
6483 u64 bytenr, u64 num_bytes, int reserved)
6484{
6485 struct btrfs_block_group_cache *cache;
68b38550 6486
0b246afa 6487 cache = btrfs_lookup_block_group(fs_info, bytenr);
79787eaa 6488 BUG_ON(!cache); /* Logic error */
f0486c68 6489
2ff7e61e 6490 pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
f0486c68
YZ
6491
6492 btrfs_put_block_group(cache);
11833d66
YZ
6493 return 0;
6494}
6495
f0486c68 6496/*
e688b725
CM
6497 * this function must be called within transaction
6498 */
2ff7e61e 6499int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
e688b725
CM
6500 u64 bytenr, u64 num_bytes)
6501{
6502 struct btrfs_block_group_cache *cache;
b50c6e25 6503 int ret;
e688b725 6504
0b246afa 6505 cache = btrfs_lookup_block_group(fs_info, bytenr);
b50c6e25
JB
6506 if (!cache)
6507 return -EINVAL;
e688b725
CM
6508
6509 /*
6510 * pull in the free space cache (if any) so that our pin
6511 * removes the free space from the cache. We have load_only set
6512 * to one because the slow code to read in the free extents does check
6513 * the pinned extents.
6514 */
f6373bf3 6515 cache_block_group(cache, 1);
e688b725 6516
2ff7e61e 6517 pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
e688b725
CM
6518
6519 /* remove us from the free space cache (if we're there at all) */
b50c6e25 6520 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
e688b725 6521 btrfs_put_block_group(cache);
b50c6e25 6522 return ret;
e688b725
CM
6523}
6524
2ff7e61e
JM
6525static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6526 u64 start, u64 num_bytes)
8c2a1a30
JB
6527{
6528 int ret;
6529 struct btrfs_block_group_cache *block_group;
6530 struct btrfs_caching_control *caching_ctl;
6531
0b246afa 6532 block_group = btrfs_lookup_block_group(fs_info, start);
8c2a1a30
JB
6533 if (!block_group)
6534 return -EINVAL;
6535
6536 cache_block_group(block_group, 0);
6537 caching_ctl = get_caching_control(block_group);
6538
6539 if (!caching_ctl) {
6540 /* Logic error */
6541 BUG_ON(!block_group_cache_done(block_group));
6542 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6543 } else {
6544 mutex_lock(&caching_ctl->mutex);
6545
6546 if (start >= caching_ctl->progress) {
2ff7e61e 6547 ret = add_excluded_extent(fs_info, start, num_bytes);
8c2a1a30
JB
6548 } else if (start + num_bytes <= caching_ctl->progress) {
6549 ret = btrfs_remove_free_space(block_group,
6550 start, num_bytes);
6551 } else {
6552 num_bytes = caching_ctl->progress - start;
6553 ret = btrfs_remove_free_space(block_group,
6554 start, num_bytes);
6555 if (ret)
6556 goto out_lock;
6557
6558 num_bytes = (start + num_bytes) -
6559 caching_ctl->progress;
6560 start = caching_ctl->progress;
2ff7e61e 6561 ret = add_excluded_extent(fs_info, start, num_bytes);
8c2a1a30
JB
6562 }
6563out_lock:
6564 mutex_unlock(&caching_ctl->mutex);
6565 put_caching_control(caching_ctl);
6566 }
6567 btrfs_put_block_group(block_group);
6568 return ret;
6569}
6570
2ff7e61e 6571int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
8c2a1a30
JB
6572 struct extent_buffer *eb)
6573{
6574 struct btrfs_file_extent_item *item;
6575 struct btrfs_key key;
6576 int found_type;
6577 int i;
6578
2ff7e61e 6579 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
8c2a1a30
JB
6580 return 0;
6581
6582 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6583 btrfs_item_key_to_cpu(eb, &key, i);
6584 if (key.type != BTRFS_EXTENT_DATA_KEY)
6585 continue;
6586 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6587 found_type = btrfs_file_extent_type(eb, item);
6588 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6589 continue;
6590 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6591 continue;
6592 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6593 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2ff7e61e 6594 __exclude_logged_extent(fs_info, key.objectid, key.offset);
8c2a1a30
JB
6595 }
6596
6597 return 0;
6598}
6599
9cfa3e34
FM
6600static void
6601btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6602{
6603 atomic_inc(&bg->reservations);
6604}
6605
6606void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6607 const u64 start)
6608{
6609 struct btrfs_block_group_cache *bg;
6610
6611 bg = btrfs_lookup_block_group(fs_info, start);
6612 ASSERT(bg);
6613 if (atomic_dec_and_test(&bg->reservations))
6614 wake_up_atomic_t(&bg->reservations);
6615 btrfs_put_block_group(bg);
6616}
6617
6618static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
6619{
6620 schedule();
6621 return 0;
6622}
6623
6624void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6625{
6626 struct btrfs_space_info *space_info = bg->space_info;
6627
6628 ASSERT(bg->ro);
6629
6630 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6631 return;
6632
6633 /*
6634 * Our block group is read only but before we set it to read only,
6635 * some task might have had allocated an extent from it already, but it
6636 * has not yet created a respective ordered extent (and added it to a
6637 * root's list of ordered extents).
6638 * Therefore wait for any task currently allocating extents, since the
6639 * block group's reservations counter is incremented while a read lock
6640 * on the groups' semaphore is held and decremented after releasing
6641 * the read access on that semaphore and creating the ordered extent.
6642 */
6643 down_write(&space_info->groups_sem);
6644 up_write(&space_info->groups_sem);
6645
6646 wait_on_atomic_t(&bg->reservations,
6647 btrfs_wait_bg_reservations_atomic_t,
6648 TASK_UNINTERRUPTIBLE);
6649}
6650
fb25e914 6651/**
4824f1f4 6652 * btrfs_add_reserved_bytes - update the block_group and space info counters
fb25e914 6653 * @cache: The cache we are manipulating
18513091
WX
6654 * @ram_bytes: The number of bytes of file content, and will be same to
6655 * @num_bytes except for the compress path.
fb25e914 6656 * @num_bytes: The number of bytes in question
e570fd27 6657 * @delalloc: The blocks are allocated for the delalloc write
fb25e914 6658 *
745699ef
XW
6659 * This is called by the allocator when it reserves space. If this is a
6660 * reservation and the block group has become read only we cannot make the
6661 * reservation and return -EAGAIN, otherwise this function always succeeds.
f0486c68 6662 */
4824f1f4 6663static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
18513091 6664 u64 ram_bytes, u64 num_bytes, int delalloc)
11833d66 6665{
fb25e914 6666 struct btrfs_space_info *space_info = cache->space_info;
f0486c68 6667 int ret = 0;
79787eaa 6668
fb25e914
JB
6669 spin_lock(&space_info->lock);
6670 spin_lock(&cache->lock);
4824f1f4
WX
6671 if (cache->ro) {
6672 ret = -EAGAIN;
fb25e914 6673 } else {
4824f1f4
WX
6674 cache->reserved += num_bytes;
6675 space_info->bytes_reserved += num_bytes;
e570fd27 6676
18513091
WX
6677 trace_btrfs_space_reservation(cache->fs_info,
6678 "space_info", space_info->flags,
6679 ram_bytes, 0);
6680 space_info->bytes_may_use -= ram_bytes;
e570fd27 6681 if (delalloc)
4824f1f4 6682 cache->delalloc_bytes += num_bytes;
324ae4df 6683 }
fb25e914
JB
6684 spin_unlock(&cache->lock);
6685 spin_unlock(&space_info->lock);
f0486c68 6686 return ret;
324ae4df 6687}
9078a3e1 6688
4824f1f4
WX
6689/**
6690 * btrfs_free_reserved_bytes - update the block_group and space info counters
6691 * @cache: The cache we are manipulating
6692 * @num_bytes: The number of bytes in question
6693 * @delalloc: The blocks are allocated for the delalloc write
6694 *
6695 * This is called by somebody who is freeing space that was never actually used
6696 * on disk. For example if you reserve some space for a new leaf in transaction
6697 * A and before transaction A commits you free that leaf, you call this with
6698 * reserve set to 0 in order to clear the reservation.
6699 */
6700
6701static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6702 u64 num_bytes, int delalloc)
6703{
6704 struct btrfs_space_info *space_info = cache->space_info;
6705 int ret = 0;
6706
6707 spin_lock(&space_info->lock);
6708 spin_lock(&cache->lock);
6709 if (cache->ro)
6710 space_info->bytes_readonly += num_bytes;
6711 cache->reserved -= num_bytes;
6712 space_info->bytes_reserved -= num_bytes;
6713
6714 if (delalloc)
6715 cache->delalloc_bytes -= num_bytes;
6716 spin_unlock(&cache->lock);
6717 spin_unlock(&space_info->lock);
6718 return ret;
6719}
8b74c03e 6720void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
e8569813 6721{
11833d66
YZ
6722 struct btrfs_caching_control *next;
6723 struct btrfs_caching_control *caching_ctl;
6724 struct btrfs_block_group_cache *cache;
e8569813 6725
9e351cc8 6726 down_write(&fs_info->commit_root_sem);
25179201 6727
11833d66
YZ
6728 list_for_each_entry_safe(caching_ctl, next,
6729 &fs_info->caching_block_groups, list) {
6730 cache = caching_ctl->block_group;
6731 if (block_group_cache_done(cache)) {
6732 cache->last_byte_to_unpin = (u64)-1;
6733 list_del_init(&caching_ctl->list);
6734 put_caching_control(caching_ctl);
e8569813 6735 } else {
11833d66 6736 cache->last_byte_to_unpin = caching_ctl->progress;
e8569813 6737 }
e8569813 6738 }
11833d66
YZ
6739
6740 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6741 fs_info->pinned_extents = &fs_info->freed_extents[1];
6742 else
6743 fs_info->pinned_extents = &fs_info->freed_extents[0];
6744
9e351cc8 6745 up_write(&fs_info->commit_root_sem);
8929ecfa
YZ
6746
6747 update_global_block_rsv(fs_info);
e8569813
ZY
6748}
6749
c759c4e1
JB
6750/*
6751 * Returns the free cluster for the given space info and sets empty_cluster to
6752 * what it should be based on the mount options.
6753 */
6754static struct btrfs_free_cluster *
2ff7e61e
JM
6755fetch_cluster_info(struct btrfs_fs_info *fs_info,
6756 struct btrfs_space_info *space_info, u64 *empty_cluster)
c759c4e1
JB
6757{
6758 struct btrfs_free_cluster *ret = NULL;
c759c4e1
JB
6759
6760 *empty_cluster = 0;
6761 if (btrfs_mixed_space_info(space_info))
6762 return ret;
6763
c759c4e1 6764 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
0b246afa 6765 ret = &fs_info->meta_alloc_cluster;
583b7231
HK
6766 if (btrfs_test_opt(fs_info, SSD))
6767 *empty_cluster = SZ_2M;
6768 else
ee22184b 6769 *empty_cluster = SZ_64K;
583b7231
HK
6770 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
6771 btrfs_test_opt(fs_info, SSD_SPREAD)) {
6772 *empty_cluster = SZ_2M;
0b246afa 6773 ret = &fs_info->data_alloc_cluster;
c759c4e1
JB
6774 }
6775
6776 return ret;
6777}
6778
2ff7e61e
JM
6779static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6780 u64 start, u64 end,
678886bd 6781 const bool return_free_space)
ccd467d6 6782{
11833d66 6783 struct btrfs_block_group_cache *cache = NULL;
7b398f8e
JB
6784 struct btrfs_space_info *space_info;
6785 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
c759c4e1 6786 struct btrfs_free_cluster *cluster = NULL;
11833d66 6787 u64 len;
c759c4e1
JB
6788 u64 total_unpinned = 0;
6789 u64 empty_cluster = 0;
7b398f8e 6790 bool readonly;
ccd467d6 6791
11833d66 6792 while (start <= end) {
7b398f8e 6793 readonly = false;
11833d66
YZ
6794 if (!cache ||
6795 start >= cache->key.objectid + cache->key.offset) {
6796 if (cache)
6797 btrfs_put_block_group(cache);
c759c4e1 6798 total_unpinned = 0;
11833d66 6799 cache = btrfs_lookup_block_group(fs_info, start);
79787eaa 6800 BUG_ON(!cache); /* Logic error */
c759c4e1 6801
2ff7e61e 6802 cluster = fetch_cluster_info(fs_info,
c759c4e1
JB
6803 cache->space_info,
6804 &empty_cluster);
6805 empty_cluster <<= 1;
11833d66
YZ
6806 }
6807
6808 len = cache->key.objectid + cache->key.offset - start;
6809 len = min(len, end + 1 - start);
6810
6811 if (start < cache->last_byte_to_unpin) {
6812 len = min(len, cache->last_byte_to_unpin - start);
678886bd
FM
6813 if (return_free_space)
6814 btrfs_add_free_space(cache, start, len);
11833d66
YZ
6815 }
6816
f0486c68 6817 start += len;
c759c4e1 6818 total_unpinned += len;
7b398f8e 6819 space_info = cache->space_info;
f0486c68 6820
c759c4e1
JB
6821 /*
6822 * If this space cluster has been marked as fragmented and we've
6823 * unpinned enough in this block group to potentially allow a
6824 * cluster to be created inside of it go ahead and clear the
6825 * fragmented check.
6826 */
6827 if (cluster && cluster->fragmented &&
6828 total_unpinned > empty_cluster) {
6829 spin_lock(&cluster->lock);
6830 cluster->fragmented = 0;
6831 spin_unlock(&cluster->lock);
6832 }
6833
7b398f8e 6834 spin_lock(&space_info->lock);
11833d66
YZ
6835 spin_lock(&cache->lock);
6836 cache->pinned -= len;
7b398f8e 6837 space_info->bytes_pinned -= len;
c51e7bb1
JB
6838
6839 trace_btrfs_space_reservation(fs_info, "pinned",
6840 space_info->flags, len, 0);
4f4db217 6841 space_info->max_extent_size = 0;
d288db5d 6842 percpu_counter_add(&space_info->total_bytes_pinned, -len);
7b398f8e
JB
6843 if (cache->ro) {
6844 space_info->bytes_readonly += len;
6845 readonly = true;
6846 }
11833d66 6847 spin_unlock(&cache->lock);
957780eb
JB
6848 if (!readonly && return_free_space &&
6849 global_rsv->space_info == space_info) {
6850 u64 to_add = len;
92ac58ec 6851
7b398f8e
JB
6852 spin_lock(&global_rsv->lock);
6853 if (!global_rsv->full) {
957780eb
JB
6854 to_add = min(len, global_rsv->size -
6855 global_rsv->reserved);
6856 global_rsv->reserved += to_add;
6857 space_info->bytes_may_use += to_add;
7b398f8e
JB
6858 if (global_rsv->reserved >= global_rsv->size)
6859 global_rsv->full = 1;
957780eb
JB
6860 trace_btrfs_space_reservation(fs_info,
6861 "space_info",
6862 space_info->flags,
6863 to_add, 1);
6864 len -= to_add;
7b398f8e
JB
6865 }
6866 spin_unlock(&global_rsv->lock);
957780eb
JB
6867 /* Add to any tickets we may have */
6868 if (len)
6869 space_info_add_new_bytes(fs_info, space_info,
6870 len);
7b398f8e
JB
6871 }
6872 spin_unlock(&space_info->lock);
ccd467d6 6873 }
11833d66
YZ
6874
6875 if (cache)
6876 btrfs_put_block_group(cache);
ccd467d6
CM
6877 return 0;
6878}
6879
6880int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
2ff7e61e 6881 struct btrfs_fs_info *fs_info)
a28ec197 6882{
e33e17ee
JM
6883 struct btrfs_block_group_cache *block_group, *tmp;
6884 struct list_head *deleted_bgs;
11833d66 6885 struct extent_io_tree *unpin;
1a5bc167
CM
6886 u64 start;
6887 u64 end;
a28ec197 6888 int ret;
a28ec197 6889
11833d66
YZ
6890 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6891 unpin = &fs_info->freed_extents[1];
6892 else
6893 unpin = &fs_info->freed_extents[0];
6894
e33e17ee 6895 while (!trans->aborted) {
d4b450cd 6896 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1a5bc167 6897 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 6898 EXTENT_DIRTY, NULL);
d4b450cd
FM
6899 if (ret) {
6900 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
a28ec197 6901 break;
d4b450cd 6902 }
1f3c79a2 6903
0b246afa 6904 if (btrfs_test_opt(fs_info, DISCARD))
2ff7e61e 6905 ret = btrfs_discard_extent(fs_info, start,
5378e607 6906 end + 1 - start, NULL);
1f3c79a2 6907
af6f8f60 6908 clear_extent_dirty(unpin, start, end);
2ff7e61e 6909 unpin_extent_range(fs_info, start, end, true);
d4b450cd 6910 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
b9473439 6911 cond_resched();
a28ec197 6912 }
817d52f8 6913
e33e17ee
JM
6914 /*
6915 * Transaction is finished. We don't need the lock anymore. We
6916 * do need to clean up the block groups in case of a transaction
6917 * abort.
6918 */
6919 deleted_bgs = &trans->transaction->deleted_bgs;
6920 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6921 u64 trimmed = 0;
6922
6923 ret = -EROFS;
6924 if (!trans->aborted)
2ff7e61e 6925 ret = btrfs_discard_extent(fs_info,
e33e17ee
JM
6926 block_group->key.objectid,
6927 block_group->key.offset,
6928 &trimmed);
6929
6930 list_del_init(&block_group->bg_list);
6931 btrfs_put_block_group_trimming(block_group);
6932 btrfs_put_block_group(block_group);
6933
6934 if (ret) {
6935 const char *errstr = btrfs_decode_error(ret);
6936 btrfs_warn(fs_info,
913e1535 6937 "discard failed while removing blockgroup: errno=%d %s",
e33e17ee
JM
6938 ret, errstr);
6939 }
6940 }
6941
e20d96d6
CM
6942 return 0;
6943}
6944
5d4f98a2 6945static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2ff7e61e 6946 struct btrfs_fs_info *info,
c682f9b3 6947 struct btrfs_delayed_ref_node *node, u64 parent,
5d4f98a2
YZ
6948 u64 root_objectid, u64 owner_objectid,
6949 u64 owner_offset, int refs_to_drop,
c682f9b3 6950 struct btrfs_delayed_extent_op *extent_op)
a28ec197 6951{
e2fa7227 6952 struct btrfs_key key;
5d4f98a2 6953 struct btrfs_path *path;
1261ec42 6954 struct btrfs_root *extent_root = info->extent_root;
5f39d397 6955 struct extent_buffer *leaf;
5d4f98a2
YZ
6956 struct btrfs_extent_item *ei;
6957 struct btrfs_extent_inline_ref *iref;
a28ec197 6958 int ret;
5d4f98a2 6959 int is_data;
952fccac
CM
6960 int extent_slot = 0;
6961 int found_extent = 0;
6962 int num_to_del = 1;
5d4f98a2
YZ
6963 u32 item_size;
6964 u64 refs;
c682f9b3
QW
6965 u64 bytenr = node->bytenr;
6966 u64 num_bytes = node->num_bytes;
fcebe456 6967 int last_ref = 0;
0b246afa 6968 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
037e6390 6969
5caf2a00 6970 path = btrfs_alloc_path();
54aa1f4d
CM
6971 if (!path)
6972 return -ENOMEM;
5f26f772 6973
e4058b54 6974 path->reada = READA_FORWARD;
b9473439 6975 path->leave_spinning = 1;
5d4f98a2
YZ
6976
6977 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6978 BUG_ON(!is_data && refs_to_drop != 1);
6979
3173a18f
JB
6980 if (is_data)
6981 skinny_metadata = 0;
6982
87bde3cd 6983 ret = lookup_extent_backref(trans, info, path, &iref,
5d4f98a2
YZ
6984 bytenr, num_bytes, parent,
6985 root_objectid, owner_objectid,
6986 owner_offset);
7bb86316 6987 if (ret == 0) {
952fccac 6988 extent_slot = path->slots[0];
5d4f98a2
YZ
6989 while (extent_slot >= 0) {
6990 btrfs_item_key_to_cpu(path->nodes[0], &key,
952fccac 6991 extent_slot);
5d4f98a2 6992 if (key.objectid != bytenr)
952fccac 6993 break;
5d4f98a2
YZ
6994 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6995 key.offset == num_bytes) {
952fccac
CM
6996 found_extent = 1;
6997 break;
6998 }
3173a18f
JB
6999 if (key.type == BTRFS_METADATA_ITEM_KEY &&
7000 key.offset == owner_objectid) {
7001 found_extent = 1;
7002 break;
7003 }
952fccac
CM
7004 if (path->slots[0] - extent_slot > 5)
7005 break;
5d4f98a2 7006 extent_slot--;
952fccac 7007 }
5d4f98a2
YZ
7008#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
7009 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
7010 if (found_extent && item_size < sizeof(*ei))
7011 found_extent = 0;
7012#endif
31840ae1 7013 if (!found_extent) {
5d4f98a2 7014 BUG_ON(iref);
87bde3cd
JM
7015 ret = remove_extent_backref(trans, info, path, NULL,
7016 refs_to_drop,
fcebe456 7017 is_data, &last_ref);
005d6427 7018 if (ret) {
66642832 7019 btrfs_abort_transaction(trans, ret);
005d6427
DS
7020 goto out;
7021 }
b3b4aa74 7022 btrfs_release_path(path);
b9473439 7023 path->leave_spinning = 1;
5d4f98a2
YZ
7024
7025 key.objectid = bytenr;
7026 key.type = BTRFS_EXTENT_ITEM_KEY;
7027 key.offset = num_bytes;
7028
3173a18f
JB
7029 if (!is_data && skinny_metadata) {
7030 key.type = BTRFS_METADATA_ITEM_KEY;
7031 key.offset = owner_objectid;
7032 }
7033
31840ae1
ZY
7034 ret = btrfs_search_slot(trans, extent_root,
7035 &key, path, -1, 1);
3173a18f
JB
7036 if (ret > 0 && skinny_metadata && path->slots[0]) {
7037 /*
7038 * Couldn't find our skinny metadata item,
7039 * see if we have ye olde extent item.
7040 */
7041 path->slots[0]--;
7042 btrfs_item_key_to_cpu(path->nodes[0], &key,
7043 path->slots[0]);
7044 if (key.objectid == bytenr &&
7045 key.type == BTRFS_EXTENT_ITEM_KEY &&
7046 key.offset == num_bytes)
7047 ret = 0;
7048 }
7049
7050 if (ret > 0 && skinny_metadata) {
7051 skinny_metadata = false;
9ce49a0b 7052 key.objectid = bytenr;
3173a18f
JB
7053 key.type = BTRFS_EXTENT_ITEM_KEY;
7054 key.offset = num_bytes;
7055 btrfs_release_path(path);
7056 ret = btrfs_search_slot(trans, extent_root,
7057 &key, path, -1, 1);
7058 }
7059
f3465ca4 7060 if (ret) {
5d163e0e
JM
7061 btrfs_err(info,
7062 "umm, got %d back from search, was looking for %llu",
7063 ret, bytenr);
b783e62d 7064 if (ret > 0)
a4f78750 7065 btrfs_print_leaf(path->nodes[0]);
f3465ca4 7066 }
005d6427 7067 if (ret < 0) {
66642832 7068 btrfs_abort_transaction(trans, ret);
005d6427
DS
7069 goto out;
7070 }
31840ae1
ZY
7071 extent_slot = path->slots[0];
7072 }
fae7f21c 7073 } else if (WARN_ON(ret == -ENOENT)) {
a4f78750 7074 btrfs_print_leaf(path->nodes[0]);
c2cf52eb
SK
7075 btrfs_err(info,
7076 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
c1c9ff7c
GU
7077 bytenr, parent, root_objectid, owner_objectid,
7078 owner_offset);
66642832 7079 btrfs_abort_transaction(trans, ret);
c4a050bb 7080 goto out;
79787eaa 7081 } else {
66642832 7082 btrfs_abort_transaction(trans, ret);
005d6427 7083 goto out;
7bb86316 7084 }
5f39d397
CM
7085
7086 leaf = path->nodes[0];
5d4f98a2
YZ
7087 item_size = btrfs_item_size_nr(leaf, extent_slot);
7088#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
7089 if (item_size < sizeof(*ei)) {
7090 BUG_ON(found_extent || extent_slot != path->slots[0]);
87bde3cd
JM
7091 ret = convert_extent_item_v0(trans, info, path, owner_objectid,
7092 0);
005d6427 7093 if (ret < 0) {
66642832 7094 btrfs_abort_transaction(trans, ret);
005d6427
DS
7095 goto out;
7096 }
5d4f98a2 7097
b3b4aa74 7098 btrfs_release_path(path);
5d4f98a2
YZ
7099 path->leave_spinning = 1;
7100
7101 key.objectid = bytenr;
7102 key.type = BTRFS_EXTENT_ITEM_KEY;
7103 key.offset = num_bytes;
7104
7105 ret = btrfs_search_slot(trans, extent_root, &key, path,
7106 -1, 1);
7107 if (ret) {
5d163e0e
JM
7108 btrfs_err(info,
7109 "umm, got %d back from search, was looking for %llu",
c1c9ff7c 7110 ret, bytenr);
a4f78750 7111 btrfs_print_leaf(path->nodes[0]);
5d4f98a2 7112 }
005d6427 7113 if (ret < 0) {
66642832 7114 btrfs_abort_transaction(trans, ret);
005d6427
DS
7115 goto out;
7116 }
7117
5d4f98a2
YZ
7118 extent_slot = path->slots[0];
7119 leaf = path->nodes[0];
7120 item_size = btrfs_item_size_nr(leaf, extent_slot);
7121 }
7122#endif
7123 BUG_ON(item_size < sizeof(*ei));
952fccac 7124 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 7125 struct btrfs_extent_item);
3173a18f
JB
7126 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
7127 key.type == BTRFS_EXTENT_ITEM_KEY) {
5d4f98a2
YZ
7128 struct btrfs_tree_block_info *bi;
7129 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
7130 bi = (struct btrfs_tree_block_info *)(ei + 1);
7131 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
7132 }
56bec294 7133
5d4f98a2 7134 refs = btrfs_extent_refs(leaf, ei);
32b02538 7135 if (refs < refs_to_drop) {
5d163e0e
JM
7136 btrfs_err(info,
7137 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7138 refs_to_drop, refs, bytenr);
32b02538 7139 ret = -EINVAL;
66642832 7140 btrfs_abort_transaction(trans, ret);
32b02538
JB
7141 goto out;
7142 }
56bec294 7143 refs -= refs_to_drop;
5f39d397 7144
5d4f98a2
YZ
7145 if (refs > 0) {
7146 if (extent_op)
7147 __run_delayed_extent_op(extent_op, leaf, ei);
7148 /*
7149 * In the case of inline back ref, reference count will
7150 * be updated by remove_extent_backref
952fccac 7151 */
5d4f98a2
YZ
7152 if (iref) {
7153 BUG_ON(!found_extent);
7154 } else {
7155 btrfs_set_extent_refs(leaf, ei, refs);
7156 btrfs_mark_buffer_dirty(leaf);
7157 }
7158 if (found_extent) {
87bde3cd 7159 ret = remove_extent_backref(trans, info, path,
5d4f98a2 7160 iref, refs_to_drop,
fcebe456 7161 is_data, &last_ref);
005d6427 7162 if (ret) {
66642832 7163 btrfs_abort_transaction(trans, ret);
005d6427
DS
7164 goto out;
7165 }
952fccac 7166 }
5d4f98a2 7167 } else {
5d4f98a2
YZ
7168 if (found_extent) {
7169 BUG_ON(is_data && refs_to_drop !=
9ed0dea0 7170 extent_data_ref_count(path, iref));
5d4f98a2
YZ
7171 if (iref) {
7172 BUG_ON(path->slots[0] != extent_slot);
7173 } else {
7174 BUG_ON(path->slots[0] != extent_slot + 1);
7175 path->slots[0] = extent_slot;
7176 num_to_del = 2;
7177 }
78fae27e 7178 }
b9473439 7179
fcebe456 7180 last_ref = 1;
952fccac
CM
7181 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7182 num_to_del);
005d6427 7183 if (ret) {
66642832 7184 btrfs_abort_transaction(trans, ret);
005d6427
DS
7185 goto out;
7186 }
b3b4aa74 7187 btrfs_release_path(path);
21af804c 7188
5d4f98a2 7189 if (is_data) {
5b4aacef 7190 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
005d6427 7191 if (ret) {
66642832 7192 btrfs_abort_transaction(trans, ret);
005d6427
DS
7193 goto out;
7194 }
459931ec
CM
7195 }
7196
0b246afa 7197 ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
1e144fb8 7198 if (ret) {
66642832 7199 btrfs_abort_transaction(trans, ret);
1e144fb8
OS
7200 goto out;
7201 }
7202
0b246afa 7203 ret = update_block_group(trans, info, bytenr, num_bytes, 0);
005d6427 7204 if (ret) {
66642832 7205 btrfs_abort_transaction(trans, ret);
005d6427
DS
7206 goto out;
7207 }
a28ec197 7208 }
fcebe456
JB
7209 btrfs_release_path(path);
7210
79787eaa 7211out:
5caf2a00 7212 btrfs_free_path(path);
a28ec197
CM
7213 return ret;
7214}
7215
1887be66 7216/*
f0486c68 7217 * when we free an block, it is possible (and likely) that we free the last
1887be66
CM
7218 * delayed ref for that extent as well. This searches the delayed ref tree for
7219 * a given extent, and if there are no other delayed refs to be processed, it
7220 * removes it from the tree.
7221 */
7222static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
2ff7e61e 7223 u64 bytenr)
1887be66
CM
7224{
7225 struct btrfs_delayed_ref_head *head;
7226 struct btrfs_delayed_ref_root *delayed_refs;
f0486c68 7227 int ret = 0;
1887be66
CM
7228
7229 delayed_refs = &trans->transaction->delayed_refs;
7230 spin_lock(&delayed_refs->lock);
f72ad18e 7231 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
1887be66 7232 if (!head)
cf93da7b 7233 goto out_delayed_unlock;
1887be66 7234
d7df2c79 7235 spin_lock(&head->lock);
c6fc2454 7236 if (!list_empty(&head->ref_list))
1887be66
CM
7237 goto out;
7238
5d4f98a2
YZ
7239 if (head->extent_op) {
7240 if (!head->must_insert_reserved)
7241 goto out;
78a6184a 7242 btrfs_free_delayed_extent_op(head->extent_op);
5d4f98a2
YZ
7243 head->extent_op = NULL;
7244 }
7245
1887be66
CM
7246 /*
7247 * waiting for the lock here would deadlock. If someone else has it
7248 * locked they are already in the process of dropping it anyway
7249 */
7250 if (!mutex_trylock(&head->mutex))
7251 goto out;
7252
7253 /*
7254 * at this point we have a head with no other entries. Go
7255 * ahead and process it.
7256 */
7257 head->node.in_tree = 0;
c46effa6 7258 rb_erase(&head->href_node, &delayed_refs->href_root);
c3e69d58 7259
d7df2c79 7260 atomic_dec(&delayed_refs->num_entries);
1887be66
CM
7261
7262 /*
7263 * we don't take a ref on the node because we're removing it from the
7264 * tree, so we just steal the ref the tree was holding.
7265 */
c3e69d58 7266 delayed_refs->num_heads--;
d7df2c79 7267 if (head->processing == 0)
c3e69d58 7268 delayed_refs->num_heads_ready--;
d7df2c79
JB
7269 head->processing = 0;
7270 spin_unlock(&head->lock);
1887be66
CM
7271 spin_unlock(&delayed_refs->lock);
7272
f0486c68
YZ
7273 BUG_ON(head->extent_op);
7274 if (head->must_insert_reserved)
7275 ret = 1;
7276
7277 mutex_unlock(&head->mutex);
1887be66 7278 btrfs_put_delayed_ref(&head->node);
f0486c68 7279 return ret;
1887be66 7280out:
d7df2c79 7281 spin_unlock(&head->lock);
cf93da7b
CM
7282
7283out_delayed_unlock:
1887be66
CM
7284 spin_unlock(&delayed_refs->lock);
7285 return 0;
7286}
7287
f0486c68
YZ
7288void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7289 struct btrfs_root *root,
7290 struct extent_buffer *buf,
5581a51a 7291 u64 parent, int last_ref)
f0486c68 7292{
0b246afa 7293 struct btrfs_fs_info *fs_info = root->fs_info;
b150a4f1 7294 int pin = 1;
f0486c68
YZ
7295 int ret;
7296
7297 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
d7eae340
OS
7298 int old_ref_mod, new_ref_mod;
7299
7be07912
OS
7300 ret = btrfs_add_delayed_tree_ref(fs_info, trans, buf->start,
7301 buf->len, parent,
0b246afa
JM
7302 root->root_key.objectid,
7303 btrfs_header_level(buf),
7be07912 7304 BTRFS_DROP_DELAYED_REF, NULL,
d7eae340 7305 &old_ref_mod, &new_ref_mod);
79787eaa 7306 BUG_ON(ret); /* -ENOMEM */
d7eae340 7307 pin = old_ref_mod >= 0 && new_ref_mod < 0;
f0486c68
YZ
7308 }
7309
0a16c7d7 7310 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
6219872d
FM
7311 struct btrfs_block_group_cache *cache;
7312
f0486c68 7313 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
2ff7e61e 7314 ret = check_ref_cleanup(trans, buf->start);
f0486c68 7315 if (!ret)
37be25bc 7316 goto out;
f0486c68
YZ
7317 }
7318
4da8b76d 7319 pin = 0;
0b246afa 7320 cache = btrfs_lookup_block_group(fs_info, buf->start);
6219872d 7321
f0486c68 7322 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
2ff7e61e
JM
7323 pin_down_extent(fs_info, cache, buf->start,
7324 buf->len, 1);
6219872d 7325 btrfs_put_block_group(cache);
37be25bc 7326 goto out;
f0486c68
YZ
7327 }
7328
7329 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7330
7331 btrfs_add_free_space(cache, buf->start, buf->len);
4824f1f4 7332 btrfs_free_reserved_bytes(cache, buf->len, 0);
6219872d 7333 btrfs_put_block_group(cache);
71ff6437 7334 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
f0486c68
YZ
7335 }
7336out:
b150a4f1 7337 if (pin)
0b246afa 7338 add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
b150a4f1
JB
7339 root->root_key.objectid);
7340
0a16c7d7
OS
7341 if (last_ref) {
7342 /*
7343 * Deleting the buffer, clear the corrupt flag since it doesn't
7344 * matter anymore.
7345 */
7346 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7347 }
f0486c68
YZ
7348}
7349
79787eaa 7350/* Can return -ENOMEM */
2ff7e61e
JM
7351int btrfs_free_extent(struct btrfs_trans_handle *trans,
7352 struct btrfs_fs_info *fs_info,
66d7e7f0 7353 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
b06c4bf5 7354 u64 owner, u64 offset)
925baedd 7355{
d7eae340 7356 int old_ref_mod, new_ref_mod;
925baedd
CM
7357 int ret;
7358
f5ee5c9a 7359 if (btrfs_is_testing(fs_info))
faa2dbf0 7360 return 0;
fccb84c9 7361
b150a4f1 7362
56bec294
CM
7363 /*
7364 * tree log blocks never actually go into the extent allocation
7365 * tree, just update pinning info and exit early.
56bec294 7366 */
5d4f98a2
YZ
7367 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7368 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
b9473439 7369 /* unlocks the pinned mutex */
2ff7e61e 7370 btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
d7eae340 7371 old_ref_mod = new_ref_mod = 0;
56bec294 7372 ret = 0;
5d4f98a2 7373 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0 7374 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7be07912
OS
7375 num_bytes, parent,
7376 root_objectid, (int)owner,
7377 BTRFS_DROP_DELAYED_REF, NULL,
d7eae340 7378 &old_ref_mod, &new_ref_mod);
5d4f98a2 7379 } else {
66d7e7f0 7380 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7be07912
OS
7381 num_bytes, parent,
7382 root_objectid, owner, offset,
7383 0, BTRFS_DROP_DELAYED_REF,
d7eae340 7384 &old_ref_mod, &new_ref_mod);
56bec294 7385 }
d7eae340
OS
7386
7387 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
7388 add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
7389
925baedd
CM
7390 return ret;
7391}
7392
817d52f8
JB
7393/*
7394 * when we wait for progress in the block group caching, its because
7395 * our allocation attempt failed at least once. So, we must sleep
7396 * and let some progress happen before we try again.
7397 *
7398 * This function will sleep at least once waiting for new free space to
7399 * show up, and then it will check the block group free space numbers
7400 * for our min num_bytes. Another option is to have it go ahead
7401 * and look in the rbtree for a free extent of a given size, but this
7402 * is a good start.
36cce922
JB
7403 *
7404 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7405 * any of the information in this block group.
817d52f8 7406 */
36cce922 7407static noinline void
817d52f8
JB
7408wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7409 u64 num_bytes)
7410{
11833d66 7411 struct btrfs_caching_control *caching_ctl;
817d52f8 7412
11833d66
YZ
7413 caching_ctl = get_caching_control(cache);
7414 if (!caching_ctl)
36cce922 7415 return;
817d52f8 7416
11833d66 7417 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
34d52cb6 7418 (cache->free_space_ctl->free_space >= num_bytes));
11833d66
YZ
7419
7420 put_caching_control(caching_ctl);
11833d66
YZ
7421}
7422
7423static noinline int
7424wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7425{
7426 struct btrfs_caching_control *caching_ctl;
36cce922 7427 int ret = 0;
11833d66
YZ
7428
7429 caching_ctl = get_caching_control(cache);
7430 if (!caching_ctl)
36cce922 7431 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
11833d66
YZ
7432
7433 wait_event(caching_ctl->wait, block_group_cache_done(cache));
36cce922
JB
7434 if (cache->cached == BTRFS_CACHE_ERROR)
7435 ret = -EIO;
11833d66 7436 put_caching_control(caching_ctl);
36cce922 7437 return ret;
817d52f8
JB
7438}
7439
31e50229 7440int __get_raid_index(u64 flags)
b742bb82 7441{
7738a53a 7442 if (flags & BTRFS_BLOCK_GROUP_RAID10)
e6ec716f 7443 return BTRFS_RAID_RAID10;
7738a53a 7444 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
e6ec716f 7445 return BTRFS_RAID_RAID1;
7738a53a 7446 else if (flags & BTRFS_BLOCK_GROUP_DUP)
e6ec716f 7447 return BTRFS_RAID_DUP;
7738a53a 7448 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
e6ec716f 7449 return BTRFS_RAID_RAID0;
53b381b3 7450 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
e942f883 7451 return BTRFS_RAID_RAID5;
53b381b3 7452 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
e942f883 7453 return BTRFS_RAID_RAID6;
7738a53a 7454
e942f883 7455 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
b742bb82
YZ
7456}
7457
6ab0a202 7458int get_block_group_index(struct btrfs_block_group_cache *cache)
7738a53a 7459{
31e50229 7460 return __get_raid_index(cache->flags);
7738a53a
ID
7461}
7462
6ab0a202
JM
7463static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
7464 [BTRFS_RAID_RAID10] = "raid10",
7465 [BTRFS_RAID_RAID1] = "raid1",
7466 [BTRFS_RAID_DUP] = "dup",
7467 [BTRFS_RAID_RAID0] = "raid0",
7468 [BTRFS_RAID_SINGLE] = "single",
7469 [BTRFS_RAID_RAID5] = "raid5",
7470 [BTRFS_RAID_RAID6] = "raid6",
7471};
7472
1b8e5df6 7473static const char *get_raid_name(enum btrfs_raid_types type)
6ab0a202
JM
7474{
7475 if (type >= BTRFS_NR_RAID_TYPES)
7476 return NULL;
7477
7478 return btrfs_raid_type_names[type];
7479}
7480
817d52f8 7481enum btrfs_loop_type {
285ff5af
JB
7482 LOOP_CACHING_NOWAIT = 0,
7483 LOOP_CACHING_WAIT = 1,
7484 LOOP_ALLOC_CHUNK = 2,
7485 LOOP_NO_EMPTY_SIZE = 3,
817d52f8
JB
7486};
7487
e570fd27
MX
7488static inline void
7489btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7490 int delalloc)
7491{
7492 if (delalloc)
7493 down_read(&cache->data_rwsem);
7494}
7495
7496static inline void
7497btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7498 int delalloc)
7499{
7500 btrfs_get_block_group(cache);
7501 if (delalloc)
7502 down_read(&cache->data_rwsem);
7503}
7504
7505static struct btrfs_block_group_cache *
7506btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7507 struct btrfs_free_cluster *cluster,
7508 int delalloc)
7509{
89771cc9 7510 struct btrfs_block_group_cache *used_bg = NULL;
6719afdc 7511
e570fd27 7512 spin_lock(&cluster->refill_lock);
6719afdc
GU
7513 while (1) {
7514 used_bg = cluster->block_group;
7515 if (!used_bg)
7516 return NULL;
7517
7518 if (used_bg == block_group)
e570fd27
MX
7519 return used_bg;
7520
6719afdc 7521 btrfs_get_block_group(used_bg);
e570fd27 7522
6719afdc
GU
7523 if (!delalloc)
7524 return used_bg;
e570fd27 7525
6719afdc
GU
7526 if (down_read_trylock(&used_bg->data_rwsem))
7527 return used_bg;
e570fd27 7528
6719afdc 7529 spin_unlock(&cluster->refill_lock);
e570fd27 7530
e321f8a8
LB
7531 /* We should only have one-level nested. */
7532 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
e570fd27 7533
6719afdc
GU
7534 spin_lock(&cluster->refill_lock);
7535 if (used_bg == cluster->block_group)
7536 return used_bg;
e570fd27 7537
6719afdc
GU
7538 up_read(&used_bg->data_rwsem);
7539 btrfs_put_block_group(used_bg);
7540 }
e570fd27
MX
7541}
7542
7543static inline void
7544btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7545 int delalloc)
7546{
7547 if (delalloc)
7548 up_read(&cache->data_rwsem);
7549 btrfs_put_block_group(cache);
7550}
7551
fec577fb
CM
7552/*
7553 * walks the btree of allocated extents and find a hole of a given size.
7554 * The key ins is changed to record the hole:
a4820398 7555 * ins->objectid == start position
62e2749e 7556 * ins->flags = BTRFS_EXTENT_ITEM_KEY
a4820398 7557 * ins->offset == the size of the hole.
fec577fb 7558 * Any available blocks before search_start are skipped.
a4820398
MX
7559 *
7560 * If there is no suitable free space, we will record the max size of
7561 * the free space extent currently.
fec577fb 7562 */
87bde3cd 7563static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
18513091
WX
7564 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7565 u64 hint_byte, struct btrfs_key *ins,
7566 u64 flags, int delalloc)
fec577fb 7567{
80eb234a 7568 int ret = 0;
0b246afa 7569 struct btrfs_root *root = fs_info->extent_root;
fa9c0d79 7570 struct btrfs_free_cluster *last_ptr = NULL;
80eb234a 7571 struct btrfs_block_group_cache *block_group = NULL;
81c9ad23 7572 u64 search_start = 0;
a4820398 7573 u64 max_extent_size = 0;
7509d4f9 7574 u64 max_free_space = 0;
c759c4e1 7575 u64 empty_cluster = 0;
80eb234a 7576 struct btrfs_space_info *space_info;
fa9c0d79 7577 int loop = 0;
b6919a58 7578 int index = __get_raid_index(flags);
0a24325e 7579 bool failed_cluster_refill = false;
1cdda9b8 7580 bool failed_alloc = false;
67377734 7581 bool use_cluster = true;
60d2adbb 7582 bool have_caching_bg = false;
13a0db5a 7583 bool orig_have_caching_bg = false;
a5e681d9 7584 bool full_search = false;
fec577fb 7585
0b246afa 7586 WARN_ON(num_bytes < fs_info->sectorsize);
962a298f 7587 ins->type = BTRFS_EXTENT_ITEM_KEY;
80eb234a
JB
7588 ins->objectid = 0;
7589 ins->offset = 0;
b1a4d965 7590
71ff6437 7591 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
3f7de037 7592
0b246afa 7593 space_info = __find_space_info(fs_info, flags);
1b1d1f66 7594 if (!space_info) {
0b246afa 7595 btrfs_err(fs_info, "No space info for %llu", flags);
1b1d1f66
JB
7596 return -ENOSPC;
7597 }
2552d17e 7598
67377734 7599 /*
4f4db217
JB
7600 * If our free space is heavily fragmented we may not be able to make
7601 * big contiguous allocations, so instead of doing the expensive search
7602 * for free space, simply return ENOSPC with our max_extent_size so we
7603 * can go ahead and search for a more manageable chunk.
7604 *
7605 * If our max_extent_size is large enough for our allocation simply
7606 * disable clustering since we will likely not be able to find enough
7607 * space to create a cluster and induce latency trying.
67377734 7608 */
4f4db217
JB
7609 if (unlikely(space_info->max_extent_size)) {
7610 spin_lock(&space_info->lock);
7611 if (space_info->max_extent_size &&
7612 num_bytes > space_info->max_extent_size) {
7613 ins->offset = space_info->max_extent_size;
7614 spin_unlock(&space_info->lock);
7615 return -ENOSPC;
7616 } else if (space_info->max_extent_size) {
7617 use_cluster = false;
7618 }
7619 spin_unlock(&space_info->lock);
fa9c0d79 7620 }
0f9dd46c 7621
2ff7e61e 7622 last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
239b14b3 7623 if (last_ptr) {
fa9c0d79
CM
7624 spin_lock(&last_ptr->lock);
7625 if (last_ptr->block_group)
7626 hint_byte = last_ptr->window_start;
c759c4e1
JB
7627 if (last_ptr->fragmented) {
7628 /*
7629 * We still set window_start so we can keep track of the
7630 * last place we found an allocation to try and save
7631 * some time.
7632 */
7633 hint_byte = last_ptr->window_start;
7634 use_cluster = false;
7635 }
fa9c0d79 7636 spin_unlock(&last_ptr->lock);
239b14b3 7637 }
fa9c0d79 7638
2ff7e61e 7639 search_start = max(search_start, first_logical_byte(fs_info, 0));
239b14b3 7640 search_start = max(search_start, hint_byte);
2552d17e 7641 if (search_start == hint_byte) {
0b246afa 7642 block_group = btrfs_lookup_block_group(fs_info, search_start);
817d52f8
JB
7643 /*
7644 * we don't want to use the block group if it doesn't match our
7645 * allocation bits, or if its not cached.
ccf0e725
JB
7646 *
7647 * However if we are re-searching with an ideal block group
7648 * picked out then we don't care that the block group is cached.
817d52f8 7649 */
b6919a58 7650 if (block_group && block_group_bits(block_group, flags) &&
285ff5af 7651 block_group->cached != BTRFS_CACHE_NO) {
2552d17e 7652 down_read(&space_info->groups_sem);
44fb5511
CM
7653 if (list_empty(&block_group->list) ||
7654 block_group->ro) {
7655 /*
7656 * someone is removing this block group,
7657 * we can't jump into the have_block_group
7658 * target because our list pointers are not
7659 * valid
7660 */
7661 btrfs_put_block_group(block_group);
7662 up_read(&space_info->groups_sem);
ccf0e725 7663 } else {
b742bb82 7664 index = get_block_group_index(block_group);
e570fd27 7665 btrfs_lock_block_group(block_group, delalloc);
44fb5511 7666 goto have_block_group;
ccf0e725 7667 }
2552d17e 7668 } else if (block_group) {
fa9c0d79 7669 btrfs_put_block_group(block_group);
2552d17e 7670 }
42e70e7a 7671 }
2552d17e 7672search:
60d2adbb 7673 have_caching_bg = false;
a5e681d9
JB
7674 if (index == 0 || index == __get_raid_index(flags))
7675 full_search = true;
80eb234a 7676 down_read(&space_info->groups_sem);
b742bb82
YZ
7677 list_for_each_entry(block_group, &space_info->block_groups[index],
7678 list) {
6226cb0a 7679 u64 offset;
817d52f8 7680 int cached;
8a1413a2 7681
14443937
JM
7682 /* If the block group is read-only, we can skip it entirely. */
7683 if (unlikely(block_group->ro))
7684 continue;
7685
e570fd27 7686 btrfs_grab_block_group(block_group, delalloc);
2552d17e 7687 search_start = block_group->key.objectid;
42e70e7a 7688
83a50de9
CM
7689 /*
7690 * this can happen if we end up cycling through all the
7691 * raid types, but we want to make sure we only allocate
7692 * for the proper type.
7693 */
b6919a58 7694 if (!block_group_bits(block_group, flags)) {
83a50de9
CM
7695 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7696 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
7697 BTRFS_BLOCK_GROUP_RAID5 |
7698 BTRFS_BLOCK_GROUP_RAID6 |
83a50de9
CM
7699 BTRFS_BLOCK_GROUP_RAID10;
7700
7701 /*
7702 * if they asked for extra copies and this block group
7703 * doesn't provide them, bail. This does allow us to
7704 * fill raid0 from raid1.
7705 */
b6919a58 7706 if ((flags & extra) && !(block_group->flags & extra))
83a50de9 7707 goto loop;
cd107319
QW
7708
7709 /*
7710 * This block group has different flags than we want.
7711 * It's possible that we have MIXED_GROUP flag but no
7712 * block group is mixed. Just skip such block group.
7713 */
7714 btrfs_release_block_group(block_group, delalloc);
7715 continue;
83a50de9
CM
7716 }
7717
2552d17e 7718have_block_group:
291c7d2f
JB
7719 cached = block_group_cache_done(block_group);
7720 if (unlikely(!cached)) {
a5e681d9 7721 have_caching_bg = true;
f6373bf3 7722 ret = cache_block_group(block_group, 0);
1d4284bd
CM
7723 BUG_ON(ret < 0);
7724 ret = 0;
817d52f8
JB
7725 }
7726
36cce922
JB
7727 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7728 goto loop;
0f9dd46c 7729
0a24325e 7730 /*
062c05c4
AO
7731 * Ok we want to try and use the cluster allocator, so
7732 * lets look there
0a24325e 7733 */
c759c4e1 7734 if (last_ptr && use_cluster) {
215a63d1 7735 struct btrfs_block_group_cache *used_block_group;
8de972b4 7736 unsigned long aligned_cluster;
fa9c0d79
CM
7737 /*
7738 * the refill lock keeps out other
7739 * people trying to start a new cluster
7740 */
e570fd27
MX
7741 used_block_group = btrfs_lock_cluster(block_group,
7742 last_ptr,
7743 delalloc);
7744 if (!used_block_group)
44fb5511 7745 goto refill_cluster;
274bd4fb 7746
e570fd27
MX
7747 if (used_block_group != block_group &&
7748 (used_block_group->ro ||
7749 !block_group_bits(used_block_group, flags)))
7750 goto release_cluster;
44fb5511 7751
274bd4fb 7752 offset = btrfs_alloc_from_cluster(used_block_group,
a4820398
MX
7753 last_ptr,
7754 num_bytes,
7755 used_block_group->key.objectid,
7756 &max_extent_size);
fa9c0d79
CM
7757 if (offset) {
7758 /* we have a block, we're done */
7759 spin_unlock(&last_ptr->refill_lock);
71ff6437 7760 trace_btrfs_reserve_extent_cluster(fs_info,
89d4346a
MX
7761 used_block_group,
7762 search_start, num_bytes);
215a63d1 7763 if (used_block_group != block_group) {
e570fd27
MX
7764 btrfs_release_block_group(block_group,
7765 delalloc);
215a63d1
MX
7766 block_group = used_block_group;
7767 }
fa9c0d79
CM
7768 goto checks;
7769 }
7770
274bd4fb 7771 WARN_ON(last_ptr->block_group != used_block_group);
e570fd27 7772release_cluster:
062c05c4
AO
7773 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7774 * set up a new clusters, so lets just skip it
7775 * and let the allocator find whatever block
7776 * it can find. If we reach this point, we
7777 * will have tried the cluster allocator
7778 * plenty of times and not have found
7779 * anything, so we are likely way too
7780 * fragmented for the clustering stuff to find
a5f6f719
AO
7781 * anything.
7782 *
7783 * However, if the cluster is taken from the
7784 * current block group, release the cluster
7785 * first, so that we stand a better chance of
7786 * succeeding in the unclustered
7787 * allocation. */
7788 if (loop >= LOOP_NO_EMPTY_SIZE &&
e570fd27 7789 used_block_group != block_group) {
062c05c4 7790 spin_unlock(&last_ptr->refill_lock);
e570fd27
MX
7791 btrfs_release_block_group(used_block_group,
7792 delalloc);
062c05c4
AO
7793 goto unclustered_alloc;
7794 }
7795
fa9c0d79
CM
7796 /*
7797 * this cluster didn't work out, free it and
7798 * start over
7799 */
7800 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7801
e570fd27
MX
7802 if (used_block_group != block_group)
7803 btrfs_release_block_group(used_block_group,
7804 delalloc);
7805refill_cluster:
a5f6f719
AO
7806 if (loop >= LOOP_NO_EMPTY_SIZE) {
7807 spin_unlock(&last_ptr->refill_lock);
7808 goto unclustered_alloc;
7809 }
7810
8de972b4
CM
7811 aligned_cluster = max_t(unsigned long,
7812 empty_cluster + empty_size,
7813 block_group->full_stripe_len);
7814
fa9c0d79 7815 /* allocate a cluster in this block group */
2ff7e61e 7816 ret = btrfs_find_space_cluster(fs_info, block_group,
00361589
JB
7817 last_ptr, search_start,
7818 num_bytes,
7819 aligned_cluster);
fa9c0d79
CM
7820 if (ret == 0) {
7821 /*
7822 * now pull our allocation out of this
7823 * cluster
7824 */
7825 offset = btrfs_alloc_from_cluster(block_group,
a4820398
MX
7826 last_ptr,
7827 num_bytes,
7828 search_start,
7829 &max_extent_size);
fa9c0d79
CM
7830 if (offset) {
7831 /* we found one, proceed */
7832 spin_unlock(&last_ptr->refill_lock);
71ff6437 7833 trace_btrfs_reserve_extent_cluster(fs_info,
3f7de037
JB
7834 block_group, search_start,
7835 num_bytes);
fa9c0d79
CM
7836 goto checks;
7837 }
0a24325e
JB
7838 } else if (!cached && loop > LOOP_CACHING_NOWAIT
7839 && !failed_cluster_refill) {
817d52f8
JB
7840 spin_unlock(&last_ptr->refill_lock);
7841
0a24325e 7842 failed_cluster_refill = true;
817d52f8
JB
7843 wait_block_group_cache_progress(block_group,
7844 num_bytes + empty_cluster + empty_size);
7845 goto have_block_group;
fa9c0d79 7846 }
817d52f8 7847
fa9c0d79
CM
7848 /*
7849 * at this point we either didn't find a cluster
7850 * or we weren't able to allocate a block from our
7851 * cluster. Free the cluster we've been trying
7852 * to use, and go to the next block group
7853 */
0a24325e 7854 btrfs_return_cluster_to_free_space(NULL, last_ptr);
fa9c0d79 7855 spin_unlock(&last_ptr->refill_lock);
0a24325e 7856 goto loop;
fa9c0d79
CM
7857 }
7858
062c05c4 7859unclustered_alloc:
c759c4e1
JB
7860 /*
7861 * We are doing an unclustered alloc, set the fragmented flag so
7862 * we don't bother trying to setup a cluster again until we get
7863 * more space.
7864 */
7865 if (unlikely(last_ptr)) {
7866 spin_lock(&last_ptr->lock);
7867 last_ptr->fragmented = 1;
7868 spin_unlock(&last_ptr->lock);
7869 }
0c9b36e0
LB
7870 if (cached) {
7871 struct btrfs_free_space_ctl *ctl =
7872 block_group->free_space_ctl;
7873
7874 spin_lock(&ctl->tree_lock);
7875 if (ctl->free_space <
7876 num_bytes + empty_cluster + empty_size) {
7509d4f9
JB
7877 max_free_space = max(max_free_space,
7878 ctl->free_space);
0c9b36e0
LB
7879 spin_unlock(&ctl->tree_lock);
7880 goto loop;
7881 }
7882 spin_unlock(&ctl->tree_lock);
a5f6f719 7883 }
a5f6f719 7884
6226cb0a 7885 offset = btrfs_find_space_for_alloc(block_group, search_start,
a4820398
MX
7886 num_bytes, empty_size,
7887 &max_extent_size);
1cdda9b8
JB
7888 /*
7889 * If we didn't find a chunk, and we haven't failed on this
7890 * block group before, and this block group is in the middle of
7891 * caching and we are ok with waiting, then go ahead and wait
7892 * for progress to be made, and set failed_alloc to true.
7893 *
7894 * If failed_alloc is true then we've already waited on this
7895 * block group once and should move on to the next block group.
7896 */
7897 if (!offset && !failed_alloc && !cached &&
7898 loop > LOOP_CACHING_NOWAIT) {
817d52f8 7899 wait_block_group_cache_progress(block_group,
1cdda9b8
JB
7900 num_bytes + empty_size);
7901 failed_alloc = true;
817d52f8 7902 goto have_block_group;
1cdda9b8
JB
7903 } else if (!offset) {
7904 goto loop;
817d52f8 7905 }
fa9c0d79 7906checks:
0b246afa 7907 search_start = ALIGN(offset, fs_info->stripesize);
25179201 7908
2552d17e
JB
7909 /* move on to the next group */
7910 if (search_start + num_bytes >
215a63d1
MX
7911 block_group->key.objectid + block_group->key.offset) {
7912 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 7913 goto loop;
6226cb0a 7914 }
f5a31e16 7915
f0486c68 7916 if (offset < search_start)
215a63d1 7917 btrfs_add_free_space(block_group, offset,
f0486c68
YZ
7918 search_start - offset);
7919 BUG_ON(offset > search_start);
2552d17e 7920
18513091
WX
7921 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7922 num_bytes, delalloc);
f0486c68 7923 if (ret == -EAGAIN) {
215a63d1 7924 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 7925 goto loop;
0f9dd46c 7926 }
9cfa3e34 7927 btrfs_inc_block_group_reservations(block_group);
0b86a832 7928
f0486c68 7929 /* we are all good, lets return */
2552d17e
JB
7930 ins->objectid = search_start;
7931 ins->offset = num_bytes;
d2fb3437 7932
71ff6437 7933 trace_btrfs_reserve_extent(fs_info, block_group,
3f7de037 7934 search_start, num_bytes);
e570fd27 7935 btrfs_release_block_group(block_group, delalloc);
2552d17e
JB
7936 break;
7937loop:
0a24325e 7938 failed_cluster_refill = false;
1cdda9b8 7939 failed_alloc = false;
b742bb82 7940 BUG_ON(index != get_block_group_index(block_group));
e570fd27 7941 btrfs_release_block_group(block_group, delalloc);
14443937 7942 cond_resched();
2552d17e
JB
7943 }
7944 up_read(&space_info->groups_sem);
7945
13a0db5a 7946 if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7947 && !orig_have_caching_bg)
7948 orig_have_caching_bg = true;
7949
60d2adbb
MX
7950 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7951 goto search;
7952
b742bb82
YZ
7953 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7954 goto search;
7955
285ff5af 7956 /*
ccf0e725
JB
7957 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7958 * caching kthreads as we move along
817d52f8
JB
7959 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7960 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7961 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7962 * again
fa9c0d79 7963 */
723bda20 7964 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
b742bb82 7965 index = 0;
a5e681d9
JB
7966 if (loop == LOOP_CACHING_NOWAIT) {
7967 /*
7968 * We want to skip the LOOP_CACHING_WAIT step if we
01327610 7969 * don't have any uncached bgs and we've already done a
a5e681d9
JB
7970 * full search through.
7971 */
13a0db5a 7972 if (orig_have_caching_bg || !full_search)
a5e681d9
JB
7973 loop = LOOP_CACHING_WAIT;
7974 else
7975 loop = LOOP_ALLOC_CHUNK;
7976 } else {
7977 loop++;
7978 }
7979
817d52f8 7980 if (loop == LOOP_ALLOC_CHUNK) {
00361589 7981 struct btrfs_trans_handle *trans;
f017f15f
WS
7982 int exist = 0;
7983
7984 trans = current->journal_info;
7985 if (trans)
7986 exist = 1;
7987 else
7988 trans = btrfs_join_transaction(root);
00361589 7989
00361589
JB
7990 if (IS_ERR(trans)) {
7991 ret = PTR_ERR(trans);
7992 goto out;
7993 }
7994
2ff7e61e 7995 ret = do_chunk_alloc(trans, fs_info, flags,
ea658bad 7996 CHUNK_ALLOC_FORCE);
a5e681d9
JB
7997
7998 /*
7999 * If we can't allocate a new chunk we've already looped
8000 * through at least once, move on to the NO_EMPTY_SIZE
8001 * case.
8002 */
8003 if (ret == -ENOSPC)
8004 loop = LOOP_NO_EMPTY_SIZE;
8005
ea658bad
JB
8006 /*
8007 * Do not bail out on ENOSPC since we
8008 * can do more things.
8009 */
00361589 8010 if (ret < 0 && ret != -ENOSPC)
66642832 8011 btrfs_abort_transaction(trans, ret);
00361589
JB
8012 else
8013 ret = 0;
f017f15f 8014 if (!exist)
3a45bb20 8015 btrfs_end_transaction(trans);
00361589 8016 if (ret)
ea658bad 8017 goto out;
2552d17e
JB
8018 }
8019
723bda20 8020 if (loop == LOOP_NO_EMPTY_SIZE) {
a5e681d9
JB
8021 /*
8022 * Don't loop again if we already have no empty_size and
8023 * no empty_cluster.
8024 */
8025 if (empty_size == 0 &&
8026 empty_cluster == 0) {
8027 ret = -ENOSPC;
8028 goto out;
8029 }
723bda20
JB
8030 empty_size = 0;
8031 empty_cluster = 0;
fa9c0d79 8032 }
723bda20
JB
8033
8034 goto search;
2552d17e
JB
8035 } else if (!ins->objectid) {
8036 ret = -ENOSPC;
d82a6f1d 8037 } else if (ins->objectid) {
c759c4e1
JB
8038 if (!use_cluster && last_ptr) {
8039 spin_lock(&last_ptr->lock);
8040 last_ptr->window_start = ins->objectid;
8041 spin_unlock(&last_ptr->lock);
8042 }
80eb234a 8043 ret = 0;
be744175 8044 }
79787eaa 8045out:
4f4db217 8046 if (ret == -ENOSPC) {
7509d4f9
JB
8047 if (!max_extent_size)
8048 max_extent_size = max_free_space;
4f4db217
JB
8049 spin_lock(&space_info->lock);
8050 space_info->max_extent_size = max_extent_size;
8051 spin_unlock(&space_info->lock);
a4820398 8052 ins->offset = max_extent_size;
4f4db217 8053 }
0f70abe2 8054 return ret;
fec577fb 8055}
ec44a35c 8056
ab8d0fc4
JM
8057static void dump_space_info(struct btrfs_fs_info *fs_info,
8058 struct btrfs_space_info *info, u64 bytes,
9ed74f2d 8059 int dump_block_groups)
0f9dd46c
JB
8060{
8061 struct btrfs_block_group_cache *cache;
b742bb82 8062 int index = 0;
0f9dd46c 8063
9ed74f2d 8064 spin_lock(&info->lock);
ab8d0fc4
JM
8065 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
8066 info->flags,
4136135b
LB
8067 info->total_bytes - btrfs_space_info_used(info, true),
8068 info->full ? "" : "not ");
ab8d0fc4
JM
8069 btrfs_info(fs_info,
8070 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
8071 info->total_bytes, info->bytes_used, info->bytes_pinned,
8072 info->bytes_reserved, info->bytes_may_use,
8073 info->bytes_readonly);
9ed74f2d
JB
8074 spin_unlock(&info->lock);
8075
8076 if (!dump_block_groups)
8077 return;
0f9dd46c 8078
80eb234a 8079 down_read(&info->groups_sem);
b742bb82
YZ
8080again:
8081 list_for_each_entry(cache, &info->block_groups[index], list) {
0f9dd46c 8082 spin_lock(&cache->lock);
ab8d0fc4
JM
8083 btrfs_info(fs_info,
8084 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
8085 cache->key.objectid, cache->key.offset,
8086 btrfs_block_group_used(&cache->item), cache->pinned,
8087 cache->reserved, cache->ro ? "[readonly]" : "");
0f9dd46c
JB
8088 btrfs_dump_free_space(cache, bytes);
8089 spin_unlock(&cache->lock);
8090 }
b742bb82
YZ
8091 if (++index < BTRFS_NR_RAID_TYPES)
8092 goto again;
80eb234a 8093 up_read(&info->groups_sem);
0f9dd46c 8094}
e8569813 8095
18513091 8096int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
11833d66
YZ
8097 u64 num_bytes, u64 min_alloc_size,
8098 u64 empty_size, u64 hint_byte,
e570fd27 8099 struct btrfs_key *ins, int is_data, int delalloc)
fec577fb 8100{
ab8d0fc4 8101 struct btrfs_fs_info *fs_info = root->fs_info;
36af4e07 8102 bool final_tried = num_bytes == min_alloc_size;
b6919a58 8103 u64 flags;
fec577fb 8104 int ret;
925baedd 8105
1b86826d 8106 flags = get_alloc_profile_by_root(root, is_data);
98d20f67 8107again:
0b246afa 8108 WARN_ON(num_bytes < fs_info->sectorsize);
87bde3cd 8109 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
18513091 8110 hint_byte, ins, flags, delalloc);
9cfa3e34 8111 if (!ret && !is_data) {
ab8d0fc4 8112 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
9cfa3e34 8113 } else if (ret == -ENOSPC) {
a4820398
MX
8114 if (!final_tried && ins->offset) {
8115 num_bytes = min(num_bytes >> 1, ins->offset);
da17066c 8116 num_bytes = round_down(num_bytes,
0b246afa 8117 fs_info->sectorsize);
9e622d6b 8118 num_bytes = max(num_bytes, min_alloc_size);
18513091 8119 ram_bytes = num_bytes;
9e622d6b
MX
8120 if (num_bytes == min_alloc_size)
8121 final_tried = true;
8122 goto again;
ab8d0fc4 8123 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
9e622d6b
MX
8124 struct btrfs_space_info *sinfo;
8125
ab8d0fc4 8126 sinfo = __find_space_info(fs_info, flags);
0b246afa 8127 btrfs_err(fs_info,
5d163e0e
JM
8128 "allocation failed flags %llu, wanted %llu",
8129 flags, num_bytes);
53804280 8130 if (sinfo)
ab8d0fc4 8131 dump_space_info(fs_info, sinfo, num_bytes, 1);
9e622d6b 8132 }
925baedd 8133 }
0f9dd46c
JB
8134
8135 return ret;
e6dcd2dc
CM
8136}
8137
2ff7e61e 8138static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
e570fd27
MX
8139 u64 start, u64 len,
8140 int pin, int delalloc)
65b51a00 8141{
0f9dd46c 8142 struct btrfs_block_group_cache *cache;
1f3c79a2 8143 int ret = 0;
0f9dd46c 8144
0b246afa 8145 cache = btrfs_lookup_block_group(fs_info, start);
0f9dd46c 8146 if (!cache) {
0b246afa
JM
8147 btrfs_err(fs_info, "Unable to find block group for %llu",
8148 start);
0f9dd46c
JB
8149 return -ENOSPC;
8150 }
1f3c79a2 8151
e688b725 8152 if (pin)
2ff7e61e 8153 pin_down_extent(fs_info, cache, start, len, 1);
e688b725 8154 else {
0b246afa 8155 if (btrfs_test_opt(fs_info, DISCARD))
2ff7e61e 8156 ret = btrfs_discard_extent(fs_info, start, len, NULL);
e688b725 8157 btrfs_add_free_space(cache, start, len);
4824f1f4 8158 btrfs_free_reserved_bytes(cache, len, delalloc);
71ff6437 8159 trace_btrfs_reserved_extent_free(fs_info, start, len);
e688b725 8160 }
31193213 8161
fa9c0d79 8162 btrfs_put_block_group(cache);
e6dcd2dc
CM
8163 return ret;
8164}
8165
2ff7e61e 8166int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
e570fd27 8167 u64 start, u64 len, int delalloc)
e688b725 8168{
2ff7e61e 8169 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
e688b725
CM
8170}
8171
2ff7e61e 8172int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
e688b725
CM
8173 u64 start, u64 len)
8174{
2ff7e61e 8175 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
e688b725
CM
8176}
8177
5d4f98a2 8178static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
2ff7e61e 8179 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
8180 u64 parent, u64 root_objectid,
8181 u64 flags, u64 owner, u64 offset,
8182 struct btrfs_key *ins, int ref_mod)
e6dcd2dc
CM
8183{
8184 int ret;
e6dcd2dc 8185 struct btrfs_extent_item *extent_item;
5d4f98a2 8186 struct btrfs_extent_inline_ref *iref;
e6dcd2dc 8187 struct btrfs_path *path;
5d4f98a2
YZ
8188 struct extent_buffer *leaf;
8189 int type;
8190 u32 size;
26b8003f 8191
5d4f98a2
YZ
8192 if (parent > 0)
8193 type = BTRFS_SHARED_DATA_REF_KEY;
8194 else
8195 type = BTRFS_EXTENT_DATA_REF_KEY;
58176a96 8196
5d4f98a2 8197 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7bb86316
CM
8198
8199 path = btrfs_alloc_path();
db5b493a
TI
8200 if (!path)
8201 return -ENOMEM;
47e4bb98 8202
b9473439 8203 path->leave_spinning = 1;
5d4f98a2
YZ
8204 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8205 ins, size);
79787eaa
JM
8206 if (ret) {
8207 btrfs_free_path(path);
8208 return ret;
8209 }
0f9dd46c 8210
5d4f98a2
YZ
8211 leaf = path->nodes[0];
8212 extent_item = btrfs_item_ptr(leaf, path->slots[0],
47e4bb98 8213 struct btrfs_extent_item);
5d4f98a2
YZ
8214 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8215 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8216 btrfs_set_extent_flags(leaf, extent_item,
8217 flags | BTRFS_EXTENT_FLAG_DATA);
8218
8219 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8220 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8221 if (parent > 0) {
8222 struct btrfs_shared_data_ref *ref;
8223 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8224 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8225 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8226 } else {
8227 struct btrfs_extent_data_ref *ref;
8228 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8229 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8230 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8231 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8232 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8233 }
47e4bb98
CM
8234
8235 btrfs_mark_buffer_dirty(path->nodes[0]);
7bb86316 8236 btrfs_free_path(path);
f510cfec 8237
1e144fb8
OS
8238 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8239 ins->offset);
8240 if (ret)
8241 return ret;
8242
6202df69 8243 ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
79787eaa 8244 if (ret) { /* -ENOENT, logic error */
c2cf52eb 8245 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 8246 ins->objectid, ins->offset);
f5947066
CM
8247 BUG();
8248 }
71ff6437 8249 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
e6dcd2dc
CM
8250 return ret;
8251}
8252
5d4f98a2 8253static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
2ff7e61e 8254 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
8255 u64 parent, u64 root_objectid,
8256 u64 flags, struct btrfs_disk_key *key,
b06c4bf5 8257 int level, struct btrfs_key *ins)
e6dcd2dc
CM
8258{
8259 int ret;
5d4f98a2
YZ
8260 struct btrfs_extent_item *extent_item;
8261 struct btrfs_tree_block_info *block_info;
8262 struct btrfs_extent_inline_ref *iref;
8263 struct btrfs_path *path;
8264 struct extent_buffer *leaf;
3173a18f 8265 u32 size = sizeof(*extent_item) + sizeof(*iref);
fcebe456 8266 u64 num_bytes = ins->offset;
0b246afa 8267 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
3173a18f
JB
8268
8269 if (!skinny_metadata)
8270 size += sizeof(*block_info);
1c2308f8 8271
5d4f98a2 8272 path = btrfs_alloc_path();
857cc2fc 8273 if (!path) {
2ff7e61e 8274 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
0b246afa 8275 fs_info->nodesize);
d8926bb3 8276 return -ENOMEM;
857cc2fc 8277 }
56bec294 8278
5d4f98a2
YZ
8279 path->leave_spinning = 1;
8280 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8281 ins, size);
79787eaa 8282 if (ret) {
dd825259 8283 btrfs_free_path(path);
2ff7e61e 8284 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
0b246afa 8285 fs_info->nodesize);
79787eaa
JM
8286 return ret;
8287 }
5d4f98a2
YZ
8288
8289 leaf = path->nodes[0];
8290 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8291 struct btrfs_extent_item);
8292 btrfs_set_extent_refs(leaf, extent_item, 1);
8293 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8294 btrfs_set_extent_flags(leaf, extent_item,
8295 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5d4f98a2 8296
3173a18f
JB
8297 if (skinny_metadata) {
8298 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
0b246afa 8299 num_bytes = fs_info->nodesize;
3173a18f
JB
8300 } else {
8301 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8302 btrfs_set_tree_block_key(leaf, block_info, key);
8303 btrfs_set_tree_block_level(leaf, block_info, level);
8304 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8305 }
5d4f98a2 8306
5d4f98a2
YZ
8307 if (parent > 0) {
8308 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8309 btrfs_set_extent_inline_ref_type(leaf, iref,
8310 BTRFS_SHARED_BLOCK_REF_KEY);
8311 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8312 } else {
8313 btrfs_set_extent_inline_ref_type(leaf, iref,
8314 BTRFS_TREE_BLOCK_REF_KEY);
8315 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
8316 }
8317
8318 btrfs_mark_buffer_dirty(leaf);
8319 btrfs_free_path(path);
8320
1e144fb8
OS
8321 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8322 num_bytes);
8323 if (ret)
8324 return ret;
8325
6202df69
JM
8326 ret = update_block_group(trans, fs_info, ins->objectid,
8327 fs_info->nodesize, 1);
79787eaa 8328 if (ret) { /* -ENOENT, logic error */
c2cf52eb 8329 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 8330 ins->objectid, ins->offset);
5d4f98a2
YZ
8331 BUG();
8332 }
0be5dc67 8333
71ff6437 8334 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
0b246afa 8335 fs_info->nodesize);
5d4f98a2
YZ
8336 return ret;
8337}
8338
8339int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5d4f98a2 8340 u64 root_objectid, u64 owner,
5846a3c2
QW
8341 u64 offset, u64 ram_bytes,
8342 struct btrfs_key *ins)
5d4f98a2 8343{
2ff7e61e 8344 struct btrfs_fs_info *fs_info = trans->fs_info;
5d4f98a2
YZ
8345 int ret;
8346
8347 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
8348
0b246afa 8349 ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
7be07912
OS
8350 ins->offset, 0, root_objectid, owner,
8351 offset, ram_bytes,
8352 BTRFS_ADD_DELAYED_EXTENT, NULL, NULL);
e6dcd2dc
CM
8353 return ret;
8354}
e02119d5
CM
8355
8356/*
8357 * this is used by the tree logging recovery code. It records that
8358 * an extent has been allocated and makes sure to clear the free
8359 * space cache bits as well
8360 */
5d4f98a2 8361int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
2ff7e61e 8362 struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
8363 u64 root_objectid, u64 owner, u64 offset,
8364 struct btrfs_key *ins)
e02119d5
CM
8365{
8366 int ret;
8367 struct btrfs_block_group_cache *block_group;
ed7a6948 8368 struct btrfs_space_info *space_info;
11833d66 8369
8c2a1a30
JB
8370 /*
8371 * Mixed block groups will exclude before processing the log so we only
01327610 8372 * need to do the exclude dance if this fs isn't mixed.
8c2a1a30 8373 */
0b246afa 8374 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
2ff7e61e
JM
8375 ret = __exclude_logged_extent(fs_info, ins->objectid,
8376 ins->offset);
b50c6e25 8377 if (ret)
8c2a1a30 8378 return ret;
11833d66
YZ
8379 }
8380
0b246afa 8381 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8c2a1a30
JB
8382 if (!block_group)
8383 return -EINVAL;
8384
ed7a6948
WX
8385 space_info = block_group->space_info;
8386 spin_lock(&space_info->lock);
8387 spin_lock(&block_group->lock);
8388 space_info->bytes_reserved += ins->offset;
8389 block_group->reserved += ins->offset;
8390 spin_unlock(&block_group->lock);
8391 spin_unlock(&space_info->lock);
8392
2ff7e61e 8393 ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
5d4f98a2 8394 0, owner, offset, ins, 1);
b50c6e25 8395 btrfs_put_block_group(block_group);
e02119d5
CM
8396 return ret;
8397}
8398
48a3b636
ES
8399static struct extent_buffer *
8400btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
fe864576 8401 u64 bytenr, int level)
65b51a00 8402{
0b246afa 8403 struct btrfs_fs_info *fs_info = root->fs_info;
65b51a00
CM
8404 struct extent_buffer *buf;
8405
2ff7e61e 8406 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2
LB
8407 if (IS_ERR(buf))
8408 return buf;
8409
d36ac4a3
QW
8410 /*
8411 * Extra safety check in case the extent tree is corrupted and extent
8412 * allocator chooses to use a tree block which is already used and
8413 * locked.
8414 */
8415 if (buf->lock_owner == current->pid) {
8416 btrfs_err_rl(fs_info,
8417"tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
8418 buf->start, btrfs_header_owner(buf), current->pid);
8419 free_extent_buffer(buf);
8420 return ERR_PTR(-EUCLEAN);
8421 }
8422
65b51a00 8423 btrfs_set_header_generation(buf, trans->transid);
85d4e461 8424 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
65b51a00 8425 btrfs_tree_lock(buf);
7c302b49 8426 clean_tree_block(fs_info, buf);
3083ee2e 8427 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
b4ce94de
CM
8428
8429 btrfs_set_lock_blocking(buf);
4db8c528 8430 set_extent_buffer_uptodate(buf);
b4ce94de 8431
d0c803c4 8432 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
656f30db 8433 buf->log_index = root->log_transid % 2;
8cef4e16
YZ
8434 /*
8435 * we allow two log transactions at a time, use different
8436 * EXENT bit to differentiate dirty pages.
8437 */
656f30db 8438 if (buf->log_index == 0)
8cef4e16
YZ
8439 set_extent_dirty(&root->dirty_log_pages, buf->start,
8440 buf->start + buf->len - 1, GFP_NOFS);
8441 else
8442 set_extent_new(&root->dirty_log_pages, buf->start,
3744dbeb 8443 buf->start + buf->len - 1);
d0c803c4 8444 } else {
656f30db 8445 buf->log_index = -1;
d0c803c4 8446 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 8447 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 8448 }
64c12921 8449 trans->dirty = true;
b4ce94de 8450 /* this returns a buffer locked for blocking */
65b51a00
CM
8451 return buf;
8452}
8453
f0486c68
YZ
8454static struct btrfs_block_rsv *
8455use_block_rsv(struct btrfs_trans_handle *trans,
8456 struct btrfs_root *root, u32 blocksize)
8457{
0b246afa 8458 struct btrfs_fs_info *fs_info = root->fs_info;
f0486c68 8459 struct btrfs_block_rsv *block_rsv;
0b246afa 8460 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
f0486c68 8461 int ret;
d88033db 8462 bool global_updated = false;
f0486c68
YZ
8463
8464 block_rsv = get_block_rsv(trans, root);
8465
b586b323
MX
8466 if (unlikely(block_rsv->size == 0))
8467 goto try_reserve;
d88033db 8468again:
f0486c68
YZ
8469 ret = block_rsv_use_bytes(block_rsv, blocksize);
8470 if (!ret)
8471 return block_rsv;
8472
b586b323
MX
8473 if (block_rsv->failfast)
8474 return ERR_PTR(ret);
8475
d88033db
MX
8476 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8477 global_updated = true;
0b246afa 8478 update_global_block_rsv(fs_info);
d88033db
MX
8479 goto again;
8480 }
8481
0b246afa 8482 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
b586b323
MX
8483 static DEFINE_RATELIMIT_STATE(_rs,
8484 DEFAULT_RATELIMIT_INTERVAL * 10,
8485 /*DEFAULT_RATELIMIT_BURST*/ 1);
8486 if (__ratelimit(&_rs))
8487 WARN(1, KERN_DEBUG
efe120a0 8488 "BTRFS: block rsv returned %d\n", ret);
b586b323
MX
8489 }
8490try_reserve:
8491 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8492 BTRFS_RESERVE_NO_FLUSH);
8493 if (!ret)
8494 return block_rsv;
8495 /*
8496 * If we couldn't reserve metadata bytes try and use some from
5881cfc9
MX
8497 * the global reserve if its space type is the same as the global
8498 * reservation.
b586b323 8499 */
5881cfc9
MX
8500 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8501 block_rsv->space_info == global_rsv->space_info) {
b586b323
MX
8502 ret = block_rsv_use_bytes(global_rsv, blocksize);
8503 if (!ret)
8504 return global_rsv;
8505 }
8506 return ERR_PTR(ret);
f0486c68
YZ
8507}
8508
8c2a3ca2
JB
8509static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8510 struct btrfs_block_rsv *block_rsv, u32 blocksize)
f0486c68
YZ
8511{
8512 block_rsv_add_bytes(block_rsv, blocksize, 0);
8c2a3ca2 8513 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
f0486c68
YZ
8514}
8515
fec577fb 8516/*
f0486c68 8517 * finds a free extent and does all the dirty work required for allocation
67b7859e 8518 * returns the tree buffer or an ERR_PTR on error.
fec577fb 8519 */
4d75f8a9 8520struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
310712b2
OS
8521 struct btrfs_root *root,
8522 u64 parent, u64 root_objectid,
8523 const struct btrfs_disk_key *key,
8524 int level, u64 hint,
8525 u64 empty_size)
fec577fb 8526{
0b246afa 8527 struct btrfs_fs_info *fs_info = root->fs_info;
e2fa7227 8528 struct btrfs_key ins;
f0486c68 8529 struct btrfs_block_rsv *block_rsv;
5f39d397 8530 struct extent_buffer *buf;
67b7859e 8531 struct btrfs_delayed_extent_op *extent_op;
f0486c68
YZ
8532 u64 flags = 0;
8533 int ret;
0b246afa
JM
8534 u32 blocksize = fs_info->nodesize;
8535 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
fec577fb 8536
05653ef3 8537#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
0b246afa 8538 if (btrfs_is_testing(fs_info)) {
faa2dbf0 8539 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
fe864576 8540 level);
faa2dbf0
JB
8541 if (!IS_ERR(buf))
8542 root->alloc_bytenr += blocksize;
8543 return buf;
8544 }
05653ef3 8545#endif
fccb84c9 8546
f0486c68
YZ
8547 block_rsv = use_block_rsv(trans, root, blocksize);
8548 if (IS_ERR(block_rsv))
8549 return ERR_CAST(block_rsv);
8550
18513091 8551 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
e570fd27 8552 empty_size, hint, &ins, 0, 0);
67b7859e
OS
8553 if (ret)
8554 goto out_unuse;
55c69072 8555
fe864576 8556 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
67b7859e
OS
8557 if (IS_ERR(buf)) {
8558 ret = PTR_ERR(buf);
8559 goto out_free_reserved;
8560 }
f0486c68
YZ
8561
8562 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8563 if (parent == 0)
8564 parent = ins.objectid;
8565 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8566 } else
8567 BUG_ON(parent > 0);
8568
8569 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
78a6184a 8570 extent_op = btrfs_alloc_delayed_extent_op();
67b7859e
OS
8571 if (!extent_op) {
8572 ret = -ENOMEM;
8573 goto out_free_buf;
8574 }
f0486c68
YZ
8575 if (key)
8576 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8577 else
8578 memset(&extent_op->key, 0, sizeof(extent_op->key));
8579 extent_op->flags_to_set = flags;
35b3ad50
DS
8580 extent_op->update_key = skinny_metadata ? false : true;
8581 extent_op->update_flags = true;
8582 extent_op->is_data = false;
b1c79e09 8583 extent_op->level = level;
f0486c68 8584
7be07912
OS
8585 ret = btrfs_add_delayed_tree_ref(fs_info, trans, ins.objectid,
8586 ins.offset, parent,
8587 root_objectid, level,
67b7859e 8588 BTRFS_ADD_DELAYED_EXTENT,
7be07912 8589 extent_op, NULL, NULL);
67b7859e
OS
8590 if (ret)
8591 goto out_free_delayed;
f0486c68 8592 }
fec577fb 8593 return buf;
67b7859e
OS
8594
8595out_free_delayed:
8596 btrfs_free_delayed_extent_op(extent_op);
8597out_free_buf:
8598 free_extent_buffer(buf);
8599out_free_reserved:
2ff7e61e 8600 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
67b7859e 8601out_unuse:
0b246afa 8602 unuse_block_rsv(fs_info, block_rsv, blocksize);
67b7859e 8603 return ERR_PTR(ret);
fec577fb 8604}
a28ec197 8605
2c47e605
YZ
8606struct walk_control {
8607 u64 refs[BTRFS_MAX_LEVEL];
8608 u64 flags[BTRFS_MAX_LEVEL];
8609 struct btrfs_key update_progress;
8610 int stage;
8611 int level;
8612 int shared_level;
8613 int update_ref;
8614 int keep_locks;
1c4850e2
YZ
8615 int reada_slot;
8616 int reada_count;
66d7e7f0 8617 int for_reloc;
2c47e605
YZ
8618};
8619
8620#define DROP_REFERENCE 1
8621#define UPDATE_BACKREF 2
8622
1c4850e2
YZ
8623static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8624 struct btrfs_root *root,
8625 struct walk_control *wc,
8626 struct btrfs_path *path)
6407bf6d 8627{
0b246afa 8628 struct btrfs_fs_info *fs_info = root->fs_info;
1c4850e2
YZ
8629 u64 bytenr;
8630 u64 generation;
8631 u64 refs;
94fcca9f 8632 u64 flags;
5d4f98a2 8633 u32 nritems;
1c4850e2
YZ
8634 struct btrfs_key key;
8635 struct extent_buffer *eb;
6407bf6d 8636 int ret;
1c4850e2
YZ
8637 int slot;
8638 int nread = 0;
6407bf6d 8639
1c4850e2
YZ
8640 if (path->slots[wc->level] < wc->reada_slot) {
8641 wc->reada_count = wc->reada_count * 2 / 3;
8642 wc->reada_count = max(wc->reada_count, 2);
8643 } else {
8644 wc->reada_count = wc->reada_count * 3 / 2;
8645 wc->reada_count = min_t(int, wc->reada_count,
0b246afa 8646 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1c4850e2 8647 }
7bb86316 8648
1c4850e2
YZ
8649 eb = path->nodes[wc->level];
8650 nritems = btrfs_header_nritems(eb);
bd56b302 8651
1c4850e2
YZ
8652 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8653 if (nread >= wc->reada_count)
8654 break;
bd56b302 8655
2dd3e67b 8656 cond_resched();
1c4850e2
YZ
8657 bytenr = btrfs_node_blockptr(eb, slot);
8658 generation = btrfs_node_ptr_generation(eb, slot);
2dd3e67b 8659
1c4850e2
YZ
8660 if (slot == path->slots[wc->level])
8661 goto reada;
5d4f98a2 8662
1c4850e2
YZ
8663 if (wc->stage == UPDATE_BACKREF &&
8664 generation <= root->root_key.offset)
bd56b302
CM
8665 continue;
8666
94fcca9f 8667 /* We don't lock the tree block, it's OK to be racy here */
2ff7e61e 8668 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
3173a18f
JB
8669 wc->level - 1, 1, &refs,
8670 &flags);
79787eaa
JM
8671 /* We don't care about errors in readahead. */
8672 if (ret < 0)
8673 continue;
94fcca9f
YZ
8674 BUG_ON(refs == 0);
8675
1c4850e2 8676 if (wc->stage == DROP_REFERENCE) {
1c4850e2
YZ
8677 if (refs == 1)
8678 goto reada;
bd56b302 8679
94fcca9f
YZ
8680 if (wc->level == 1 &&
8681 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8682 continue;
1c4850e2
YZ
8683 if (!wc->update_ref ||
8684 generation <= root->root_key.offset)
8685 continue;
8686 btrfs_node_key_to_cpu(eb, &key, slot);
8687 ret = btrfs_comp_cpu_keys(&key,
8688 &wc->update_progress);
8689 if (ret < 0)
8690 continue;
94fcca9f
YZ
8691 } else {
8692 if (wc->level == 1 &&
8693 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8694 continue;
6407bf6d 8695 }
1c4850e2 8696reada:
2ff7e61e 8697 readahead_tree_block(fs_info, bytenr);
1c4850e2 8698 nread++;
20524f02 8699 }
1c4850e2 8700 wc->reada_slot = slot;
20524f02 8701}
2c47e605 8702
f82d02d9 8703/*
2c016dc2 8704 * helper to process tree block while walking down the tree.
2c47e605 8705 *
2c47e605
YZ
8706 * when wc->stage == UPDATE_BACKREF, this function updates
8707 * back refs for pointers in the block.
8708 *
8709 * NOTE: return value 1 means we should stop walking down.
f82d02d9 8710 */
2c47e605 8711static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5d4f98a2 8712 struct btrfs_root *root,
2c47e605 8713 struct btrfs_path *path,
94fcca9f 8714 struct walk_control *wc, int lookup_info)
f82d02d9 8715{
2ff7e61e 8716 struct btrfs_fs_info *fs_info = root->fs_info;
2c47e605
YZ
8717 int level = wc->level;
8718 struct extent_buffer *eb = path->nodes[level];
2c47e605 8719 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
f82d02d9
YZ
8720 int ret;
8721
2c47e605
YZ
8722 if (wc->stage == UPDATE_BACKREF &&
8723 btrfs_header_owner(eb) != root->root_key.objectid)
8724 return 1;
f82d02d9 8725
2c47e605
YZ
8726 /*
8727 * when reference count of tree block is 1, it won't increase
8728 * again. once full backref flag is set, we never clear it.
8729 */
94fcca9f
YZ
8730 if (lookup_info &&
8731 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8732 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
2c47e605 8733 BUG_ON(!path->locks[level]);
2ff7e61e 8734 ret = btrfs_lookup_extent_info(trans, fs_info,
3173a18f 8735 eb->start, level, 1,
2c47e605
YZ
8736 &wc->refs[level],
8737 &wc->flags[level]);
79787eaa
JM
8738 BUG_ON(ret == -ENOMEM);
8739 if (ret)
8740 return ret;
2c47e605
YZ
8741 BUG_ON(wc->refs[level] == 0);
8742 }
5d4f98a2 8743
2c47e605
YZ
8744 if (wc->stage == DROP_REFERENCE) {
8745 if (wc->refs[level] > 1)
8746 return 1;
f82d02d9 8747
2c47e605 8748 if (path->locks[level] && !wc->keep_locks) {
bd681513 8749 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
8750 path->locks[level] = 0;
8751 }
8752 return 0;
8753 }
f82d02d9 8754
2c47e605
YZ
8755 /* wc->stage == UPDATE_BACKREF */
8756 if (!(wc->flags[level] & flag)) {
8757 BUG_ON(!path->locks[level]);
e339a6b0 8758 ret = btrfs_inc_ref(trans, root, eb, 1);
79787eaa 8759 BUG_ON(ret); /* -ENOMEM */
e339a6b0 8760 ret = btrfs_dec_ref(trans, root, eb, 0);
79787eaa 8761 BUG_ON(ret); /* -ENOMEM */
2ff7e61e 8762 ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
b1c79e09
JB
8763 eb->len, flag,
8764 btrfs_header_level(eb), 0);
79787eaa 8765 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
8766 wc->flags[level] |= flag;
8767 }
8768
8769 /*
8770 * the block is shared by multiple trees, so it's not good to
8771 * keep the tree lock
8772 */
8773 if (path->locks[level] && level > 0) {
bd681513 8774 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
8775 path->locks[level] = 0;
8776 }
8777 return 0;
8778}
8779
1c4850e2 8780/*
2c016dc2 8781 * helper to process tree block pointer.
1c4850e2
YZ
8782 *
8783 * when wc->stage == DROP_REFERENCE, this function checks
8784 * reference count of the block pointed to. if the block
8785 * is shared and we need update back refs for the subtree
8786 * rooted at the block, this function changes wc->stage to
8787 * UPDATE_BACKREF. if the block is shared and there is no
8788 * need to update back, this function drops the reference
8789 * to the block.
8790 *
8791 * NOTE: return value 1 means we should stop walking down.
8792 */
8793static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8794 struct btrfs_root *root,
8795 struct btrfs_path *path,
94fcca9f 8796 struct walk_control *wc, int *lookup_info)
1c4850e2 8797{
0b246afa 8798 struct btrfs_fs_info *fs_info = root->fs_info;
1c4850e2
YZ
8799 u64 bytenr;
8800 u64 generation;
8801 u64 parent;
8802 u32 blocksize;
8803 struct btrfs_key key;
8804 struct extent_buffer *next;
8805 int level = wc->level;
8806 int reada = 0;
8807 int ret = 0;
1152651a 8808 bool need_account = false;
1c4850e2
YZ
8809
8810 generation = btrfs_node_ptr_generation(path->nodes[level],
8811 path->slots[level]);
8812 /*
8813 * if the lower level block was created before the snapshot
8814 * was created, we know there is no need to update back refs
8815 * for the subtree
8816 */
8817 if (wc->stage == UPDATE_BACKREF &&
94fcca9f
YZ
8818 generation <= root->root_key.offset) {
8819 *lookup_info = 1;
1c4850e2 8820 return 1;
94fcca9f 8821 }
1c4850e2
YZ
8822
8823 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
0b246afa 8824 blocksize = fs_info->nodesize;
1c4850e2 8825
0b246afa 8826 next = find_extent_buffer(fs_info, bytenr);
1c4850e2 8827 if (!next) {
2ff7e61e 8828 next = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2
LB
8829 if (IS_ERR(next))
8830 return PTR_ERR(next);
8831
b2aaaa3b
JB
8832 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8833 level - 1);
1c4850e2
YZ
8834 reada = 1;
8835 }
8836 btrfs_tree_lock(next);
8837 btrfs_set_lock_blocking(next);
8838
2ff7e61e 8839 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
94fcca9f
YZ
8840 &wc->refs[level - 1],
8841 &wc->flags[level - 1]);
4867268c
JB
8842 if (ret < 0)
8843 goto out_unlock;
79787eaa 8844
c2cf52eb 8845 if (unlikely(wc->refs[level - 1] == 0)) {
0b246afa 8846 btrfs_err(fs_info, "Missing references.");
4867268c
JB
8847 ret = -EIO;
8848 goto out_unlock;
c2cf52eb 8849 }
94fcca9f 8850 *lookup_info = 0;
1c4850e2 8851
94fcca9f 8852 if (wc->stage == DROP_REFERENCE) {
1c4850e2 8853 if (wc->refs[level - 1] > 1) {
1152651a 8854 need_account = true;
94fcca9f
YZ
8855 if (level == 1 &&
8856 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8857 goto skip;
8858
1c4850e2
YZ
8859 if (!wc->update_ref ||
8860 generation <= root->root_key.offset)
8861 goto skip;
8862
8863 btrfs_node_key_to_cpu(path->nodes[level], &key,
8864 path->slots[level]);
8865 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8866 if (ret < 0)
8867 goto skip;
8868
8869 wc->stage = UPDATE_BACKREF;
8870 wc->shared_level = level - 1;
8871 }
94fcca9f
YZ
8872 } else {
8873 if (level == 1 &&
8874 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8875 goto skip;
1c4850e2
YZ
8876 }
8877
b9fab919 8878 if (!btrfs_buffer_uptodate(next, generation, 0)) {
1c4850e2
YZ
8879 btrfs_tree_unlock(next);
8880 free_extent_buffer(next);
8881 next = NULL;
94fcca9f 8882 *lookup_info = 1;
1c4850e2
YZ
8883 }
8884
8885 if (!next) {
8886 if (reada && level == 1)
8887 reada_walk_down(trans, root, wc, path);
2ff7e61e 8888 next = read_tree_block(fs_info, bytenr, generation);
64c043de
LB
8889 if (IS_ERR(next)) {
8890 return PTR_ERR(next);
8891 } else if (!extent_buffer_uptodate(next)) {
416bc658 8892 free_extent_buffer(next);
97d9a8a4 8893 return -EIO;
416bc658 8894 }
1c4850e2
YZ
8895 btrfs_tree_lock(next);
8896 btrfs_set_lock_blocking(next);
8897 }
8898
8899 level--;
4867268c
JB
8900 ASSERT(level == btrfs_header_level(next));
8901 if (level != btrfs_header_level(next)) {
8902 btrfs_err(root->fs_info, "mismatched level");
8903 ret = -EIO;
8904 goto out_unlock;
8905 }
1c4850e2
YZ
8906 path->nodes[level] = next;
8907 path->slots[level] = 0;
bd681513 8908 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
1c4850e2
YZ
8909 wc->level = level;
8910 if (wc->level == 1)
8911 wc->reada_slot = 0;
8912 return 0;
8913skip:
8914 wc->refs[level - 1] = 0;
8915 wc->flags[level - 1] = 0;
94fcca9f
YZ
8916 if (wc->stage == DROP_REFERENCE) {
8917 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8918 parent = path->nodes[level]->start;
8919 } else {
4867268c 8920 ASSERT(root->root_key.objectid ==
94fcca9f 8921 btrfs_header_owner(path->nodes[level]));
4867268c
JB
8922 if (root->root_key.objectid !=
8923 btrfs_header_owner(path->nodes[level])) {
8924 btrfs_err(root->fs_info,
8925 "mismatched block owner");
8926 ret = -EIO;
8927 goto out_unlock;
8928 }
94fcca9f
YZ
8929 parent = 0;
8930 }
1c4850e2 8931
1152651a 8932 if (need_account) {
33d1f05c
QW
8933 ret = btrfs_qgroup_trace_subtree(trans, root, next,
8934 generation, level - 1);
1152651a 8935 if (ret) {
0b246afa 8936 btrfs_err_rl(fs_info,
5d163e0e
JM
8937 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8938 ret);
1152651a
MF
8939 }
8940 }
2ff7e61e
JM
8941 ret = btrfs_free_extent(trans, fs_info, bytenr, blocksize,
8942 parent, root->root_key.objectid,
8943 level - 1, 0);
4867268c
JB
8944 if (ret)
8945 goto out_unlock;
1c4850e2 8946 }
4867268c
JB
8947
8948 *lookup_info = 1;
8949 ret = 1;
8950
8951out_unlock:
1c4850e2
YZ
8952 btrfs_tree_unlock(next);
8953 free_extent_buffer(next);
4867268c
JB
8954
8955 return ret;
1c4850e2
YZ
8956}
8957
2c47e605 8958/*
2c016dc2 8959 * helper to process tree block while walking up the tree.
2c47e605
YZ
8960 *
8961 * when wc->stage == DROP_REFERENCE, this function drops
8962 * reference count on the block.
8963 *
8964 * when wc->stage == UPDATE_BACKREF, this function changes
8965 * wc->stage back to DROP_REFERENCE if we changed wc->stage
8966 * to UPDATE_BACKREF previously while processing the block.
8967 *
8968 * NOTE: return value 1 means we should stop walking up.
8969 */
8970static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8971 struct btrfs_root *root,
8972 struct btrfs_path *path,
8973 struct walk_control *wc)
8974{
0b246afa 8975 struct btrfs_fs_info *fs_info = root->fs_info;
f0486c68 8976 int ret;
2c47e605
YZ
8977 int level = wc->level;
8978 struct extent_buffer *eb = path->nodes[level];
8979 u64 parent = 0;
8980
8981 if (wc->stage == UPDATE_BACKREF) {
8982 BUG_ON(wc->shared_level < level);
8983 if (level < wc->shared_level)
8984 goto out;
8985
2c47e605
YZ
8986 ret = find_next_key(path, level + 1, &wc->update_progress);
8987 if (ret > 0)
8988 wc->update_ref = 0;
8989
8990 wc->stage = DROP_REFERENCE;
8991 wc->shared_level = -1;
8992 path->slots[level] = 0;
8993
8994 /*
8995 * check reference count again if the block isn't locked.
8996 * we should start walking down the tree again if reference
8997 * count is one.
8998 */
8999 if (!path->locks[level]) {
9000 BUG_ON(level == 0);
9001 btrfs_tree_lock(eb);
9002 btrfs_set_lock_blocking(eb);
bd681513 9003 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605 9004
2ff7e61e 9005 ret = btrfs_lookup_extent_info(trans, fs_info,
3173a18f 9006 eb->start, level, 1,
2c47e605
YZ
9007 &wc->refs[level],
9008 &wc->flags[level]);
79787eaa
JM
9009 if (ret < 0) {
9010 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 9011 path->locks[level] = 0;
79787eaa
JM
9012 return ret;
9013 }
2c47e605
YZ
9014 BUG_ON(wc->refs[level] == 0);
9015 if (wc->refs[level] == 1) {
bd681513 9016 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 9017 path->locks[level] = 0;
2c47e605
YZ
9018 return 1;
9019 }
f82d02d9 9020 }
2c47e605 9021 }
f82d02d9 9022
2c47e605
YZ
9023 /* wc->stage == DROP_REFERENCE */
9024 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5d4f98a2 9025
2c47e605
YZ
9026 if (wc->refs[level] == 1) {
9027 if (level == 0) {
9028 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
e339a6b0 9029 ret = btrfs_dec_ref(trans, root, eb, 1);
2c47e605 9030 else
e339a6b0 9031 ret = btrfs_dec_ref(trans, root, eb, 0);
79787eaa 9032 BUG_ON(ret); /* -ENOMEM */
2ff7e61e 9033 ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
1152651a 9034 if (ret) {
0b246afa 9035 btrfs_err_rl(fs_info,
5d163e0e
JM
9036 "error %d accounting leaf items. Quota is out of sync, rescan required.",
9037 ret);
1152651a 9038 }
2c47e605
YZ
9039 }
9040 /* make block locked assertion in clean_tree_block happy */
9041 if (!path->locks[level] &&
9042 btrfs_header_generation(eb) == trans->transid) {
9043 btrfs_tree_lock(eb);
9044 btrfs_set_lock_blocking(eb);
bd681513 9045 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605 9046 }
7c302b49 9047 clean_tree_block(fs_info, eb);
2c47e605
YZ
9048 }
9049
9050 if (eb == root->node) {
9051 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9052 parent = eb->start;
61e3643d
QW
9053 else if (root->root_key.objectid != btrfs_header_owner(eb))
9054 goto owner_mismatch;
2c47e605
YZ
9055 } else {
9056 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9057 parent = path->nodes[level + 1]->start;
61e3643d
QW
9058 else if (root->root_key.objectid !=
9059 btrfs_header_owner(path->nodes[level + 1]))
9060 goto owner_mismatch;
f82d02d9 9061 }
f82d02d9 9062
5581a51a 9063 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
2c47e605
YZ
9064out:
9065 wc->refs[level] = 0;
9066 wc->flags[level] = 0;
f0486c68 9067 return 0;
61e3643d
QW
9068
9069owner_mismatch:
9070 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
9071 btrfs_header_owner(eb), root->root_key.objectid);
9072 return -EUCLEAN;
2c47e605
YZ
9073}
9074
9075static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
9076 struct btrfs_root *root,
9077 struct btrfs_path *path,
9078 struct walk_control *wc)
9079{
2c47e605 9080 int level = wc->level;
94fcca9f 9081 int lookup_info = 1;
2c47e605
YZ
9082 int ret;
9083
9084 while (level >= 0) {
94fcca9f 9085 ret = walk_down_proc(trans, root, path, wc, lookup_info);
2c47e605
YZ
9086 if (ret > 0)
9087 break;
9088
9089 if (level == 0)
9090 break;
9091
7a7965f8
YZ
9092 if (path->slots[level] >=
9093 btrfs_header_nritems(path->nodes[level]))
9094 break;
9095
94fcca9f 9096 ret = do_walk_down(trans, root, path, wc, &lookup_info);
1c4850e2
YZ
9097 if (ret > 0) {
9098 path->slots[level]++;
9099 continue;
90d2c51d
MX
9100 } else if (ret < 0)
9101 return ret;
1c4850e2 9102 level = wc->level;
f82d02d9 9103 }
f82d02d9
YZ
9104 return 0;
9105}
9106
d397712b 9107static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 9108 struct btrfs_root *root,
f82d02d9 9109 struct btrfs_path *path,
2c47e605 9110 struct walk_control *wc, int max_level)
20524f02 9111{
2c47e605 9112 int level = wc->level;
20524f02 9113 int ret;
9f3a7427 9114
2c47e605
YZ
9115 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
9116 while (level < max_level && path->nodes[level]) {
9117 wc->level = level;
9118 if (path->slots[level] + 1 <
9119 btrfs_header_nritems(path->nodes[level])) {
9120 path->slots[level]++;
20524f02
CM
9121 return 0;
9122 } else {
2c47e605
YZ
9123 ret = walk_up_proc(trans, root, path, wc);
9124 if (ret > 0)
9125 return 0;
61e3643d
QW
9126 if (ret < 0)
9127 return ret;
bd56b302 9128
2c47e605 9129 if (path->locks[level]) {
bd681513
CM
9130 btrfs_tree_unlock_rw(path->nodes[level],
9131 path->locks[level]);
2c47e605 9132 path->locks[level] = 0;
f82d02d9 9133 }
2c47e605
YZ
9134 free_extent_buffer(path->nodes[level]);
9135 path->nodes[level] = NULL;
9136 level++;
20524f02
CM
9137 }
9138 }
9139 return 1;
9140}
9141
9aca1d51 9142/*
2c47e605
YZ
9143 * drop a subvolume tree.
9144 *
9145 * this function traverses the tree freeing any blocks that only
9146 * referenced by the tree.
9147 *
9148 * when a shared tree block is found. this function decreases its
9149 * reference count by one. if update_ref is true, this function
9150 * also make sure backrefs for the shared block and all lower level
9151 * blocks are properly updated.
9d1a2a3a
DS
9152 *
9153 * If called with for_reloc == 0, may exit early with -EAGAIN
9aca1d51 9154 */
2c536799 9155int btrfs_drop_snapshot(struct btrfs_root *root,
66d7e7f0
AJ
9156 struct btrfs_block_rsv *block_rsv, int update_ref,
9157 int for_reloc)
20524f02 9158{
ab8d0fc4 9159 struct btrfs_fs_info *fs_info = root->fs_info;
5caf2a00 9160 struct btrfs_path *path;
2c47e605 9161 struct btrfs_trans_handle *trans;
ab8d0fc4 9162 struct btrfs_root *tree_root = fs_info->tree_root;
9f3a7427 9163 struct btrfs_root_item *root_item = &root->root_item;
2c47e605
YZ
9164 struct walk_control *wc;
9165 struct btrfs_key key;
9166 int err = 0;
9167 int ret;
9168 int level;
d29a9f62 9169 bool root_dropped = false;
20524f02 9170
ab8d0fc4 9171 btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
1152651a 9172
5caf2a00 9173 path = btrfs_alloc_path();
cb1b69f4
TI
9174 if (!path) {
9175 err = -ENOMEM;
9176 goto out;
9177 }
20524f02 9178
2c47e605 9179 wc = kzalloc(sizeof(*wc), GFP_NOFS);
38a1a919
MF
9180 if (!wc) {
9181 btrfs_free_path(path);
cb1b69f4
TI
9182 err = -ENOMEM;
9183 goto out;
38a1a919 9184 }
2c47e605 9185
a22285a6 9186 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
9187 if (IS_ERR(trans)) {
9188 err = PTR_ERR(trans);
9189 goto out_free;
9190 }
98d5dc13 9191
3fd0a558
YZ
9192 if (block_rsv)
9193 trans->block_rsv = block_rsv;
2c47e605 9194
9f3a7427 9195 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2c47e605 9196 level = btrfs_header_level(root->node);
5d4f98a2
YZ
9197 path->nodes[level] = btrfs_lock_root_node(root);
9198 btrfs_set_lock_blocking(path->nodes[level]);
9f3a7427 9199 path->slots[level] = 0;
bd681513 9200 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
9201 memset(&wc->update_progress, 0,
9202 sizeof(wc->update_progress));
9f3a7427 9203 } else {
9f3a7427 9204 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2c47e605
YZ
9205 memcpy(&wc->update_progress, &key,
9206 sizeof(wc->update_progress));
9207
6702ed49 9208 level = root_item->drop_level;
2c47e605 9209 BUG_ON(level == 0);
6702ed49 9210 path->lowest_level = level;
2c47e605
YZ
9211 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9212 path->lowest_level = 0;
9213 if (ret < 0) {
9214 err = ret;
79787eaa 9215 goto out_end_trans;
9f3a7427 9216 }
1c4850e2 9217 WARN_ON(ret > 0);
2c47e605 9218
7d9eb12c
CM
9219 /*
9220 * unlock our path, this is safe because only this
9221 * function is allowed to delete this snapshot
9222 */
5d4f98a2 9223 btrfs_unlock_up_safe(path, 0);
2c47e605
YZ
9224
9225 level = btrfs_header_level(root->node);
9226 while (1) {
9227 btrfs_tree_lock(path->nodes[level]);
9228 btrfs_set_lock_blocking(path->nodes[level]);
fec386ac 9229 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605 9230
2ff7e61e 9231 ret = btrfs_lookup_extent_info(trans, fs_info,
2c47e605 9232 path->nodes[level]->start,
3173a18f 9233 level, 1, &wc->refs[level],
2c47e605 9234 &wc->flags[level]);
79787eaa
JM
9235 if (ret < 0) {
9236 err = ret;
9237 goto out_end_trans;
9238 }
2c47e605
YZ
9239 BUG_ON(wc->refs[level] == 0);
9240
9241 if (level == root_item->drop_level)
9242 break;
9243
9244 btrfs_tree_unlock(path->nodes[level]);
fec386ac 9245 path->locks[level] = 0;
2c47e605
YZ
9246 WARN_ON(wc->refs[level] != 1);
9247 level--;
9248 }
9f3a7427 9249 }
2c47e605
YZ
9250
9251 wc->level = level;
9252 wc->shared_level = -1;
9253 wc->stage = DROP_REFERENCE;
9254 wc->update_ref = update_ref;
9255 wc->keep_locks = 0;
66d7e7f0 9256 wc->for_reloc = for_reloc;
0b246afa 9257 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
2c47e605 9258
d397712b 9259 while (1) {
9d1a2a3a 9260
2c47e605
YZ
9261 ret = walk_down_tree(trans, root, path, wc);
9262 if (ret < 0) {
9263 err = ret;
20524f02 9264 break;
2c47e605 9265 }
9aca1d51 9266
2c47e605
YZ
9267 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9268 if (ret < 0) {
9269 err = ret;
20524f02 9270 break;
2c47e605
YZ
9271 }
9272
9273 if (ret > 0) {
9274 BUG_ON(wc->stage != DROP_REFERENCE);
e7a84565
CM
9275 break;
9276 }
2c47e605
YZ
9277
9278 if (wc->stage == DROP_REFERENCE) {
9279 level = wc->level;
9280 btrfs_node_key(path->nodes[level],
9281 &root_item->drop_progress,
9282 path->slots[level]);
9283 root_item->drop_level = level;
9284 }
9285
9286 BUG_ON(wc->level == 0);
3a45bb20 9287 if (btrfs_should_end_transaction(trans) ||
2ff7e61e 9288 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
2c47e605
YZ
9289 ret = btrfs_update_root(trans, tree_root,
9290 &root->root_key,
9291 root_item);
79787eaa 9292 if (ret) {
66642832 9293 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9294 err = ret;
9295 goto out_end_trans;
9296 }
2c47e605 9297
3a45bb20 9298 btrfs_end_transaction_throttle(trans);
2ff7e61e 9299 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
ab8d0fc4
JM
9300 btrfs_debug(fs_info,
9301 "drop snapshot early exit");
3c8f2422
JB
9302 err = -EAGAIN;
9303 goto out_free;
9304 }
9305
a22285a6 9306 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
9307 if (IS_ERR(trans)) {
9308 err = PTR_ERR(trans);
9309 goto out_free;
9310 }
3fd0a558
YZ
9311 if (block_rsv)
9312 trans->block_rsv = block_rsv;
c3e69d58 9313 }
20524f02 9314 }
b3b4aa74 9315 btrfs_release_path(path);
79787eaa
JM
9316 if (err)
9317 goto out_end_trans;
2c47e605 9318
1cd5447e 9319 ret = btrfs_del_root(trans, fs_info, &root->root_key);
79787eaa 9320 if (ret) {
66642832 9321 btrfs_abort_transaction(trans, ret);
85ab61fd 9322 err = ret;
79787eaa
JM
9323 goto out_end_trans;
9324 }
2c47e605 9325
76dda93c 9326 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
cb517eab
MX
9327 ret = btrfs_find_root(tree_root, &root->root_key, path,
9328 NULL, NULL);
79787eaa 9329 if (ret < 0) {
66642832 9330 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9331 err = ret;
9332 goto out_end_trans;
9333 } else if (ret > 0) {
84cd948c
JB
9334 /* if we fail to delete the orphan item this time
9335 * around, it'll get picked up the next time.
9336 *
9337 * The most common failure here is just -ENOENT.
9338 */
9339 btrfs_del_orphan_item(trans, tree_root,
9340 root->root_key.objectid);
76dda93c
YZ
9341 }
9342 }
9343
27cdeb70 9344 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
2b9dbef2 9345 btrfs_add_dropped_root(trans, root);
76dda93c
YZ
9346 } else {
9347 free_extent_buffer(root->node);
9348 free_extent_buffer(root->commit_root);
b0feb9d9 9349 btrfs_put_fs_root(root);
76dda93c 9350 }
d29a9f62 9351 root_dropped = true;
79787eaa 9352out_end_trans:
3a45bb20 9353 btrfs_end_transaction_throttle(trans);
79787eaa 9354out_free:
2c47e605 9355 kfree(wc);
5caf2a00 9356 btrfs_free_path(path);
cb1b69f4 9357out:
d29a9f62
JB
9358 /*
9359 * So if we need to stop dropping the snapshot for whatever reason we
9360 * need to make sure to add it back to the dead root list so that we
9361 * keep trying to do the work later. This also cleans up roots if we
9362 * don't have it in the radix (like when we recover after a power fail
9363 * or unmount) so we don't leak memory.
9364 */
b37b39cd 9365 if (!for_reloc && root_dropped == false)
d29a9f62 9366 btrfs_add_dead_root(root);
90515e7f 9367 if (err && err != -EAGAIN)
ab8d0fc4 9368 btrfs_handle_fs_error(fs_info, err, NULL);
2c536799 9369 return err;
20524f02 9370}
9078a3e1 9371
2c47e605
YZ
9372/*
9373 * drop subtree rooted at tree block 'node'.
9374 *
9375 * NOTE: this function will unlock and release tree block 'node'
66d7e7f0 9376 * only used by relocation code
2c47e605 9377 */
f82d02d9
YZ
9378int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9379 struct btrfs_root *root,
9380 struct extent_buffer *node,
9381 struct extent_buffer *parent)
9382{
0b246afa 9383 struct btrfs_fs_info *fs_info = root->fs_info;
f82d02d9 9384 struct btrfs_path *path;
2c47e605 9385 struct walk_control *wc;
f82d02d9
YZ
9386 int level;
9387 int parent_level;
9388 int ret = 0;
9389 int wret;
9390
2c47e605
YZ
9391 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9392
f82d02d9 9393 path = btrfs_alloc_path();
db5b493a
TI
9394 if (!path)
9395 return -ENOMEM;
f82d02d9 9396
2c47e605 9397 wc = kzalloc(sizeof(*wc), GFP_NOFS);
db5b493a
TI
9398 if (!wc) {
9399 btrfs_free_path(path);
9400 return -ENOMEM;
9401 }
2c47e605 9402
b9447ef8 9403 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
9404 parent_level = btrfs_header_level(parent);
9405 extent_buffer_get(parent);
9406 path->nodes[parent_level] = parent;
9407 path->slots[parent_level] = btrfs_header_nritems(parent);
9408
b9447ef8 9409 btrfs_assert_tree_locked(node);
f82d02d9 9410 level = btrfs_header_level(node);
f82d02d9
YZ
9411 path->nodes[level] = node;
9412 path->slots[level] = 0;
bd681513 9413 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
9414
9415 wc->refs[parent_level] = 1;
9416 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9417 wc->level = level;
9418 wc->shared_level = -1;
9419 wc->stage = DROP_REFERENCE;
9420 wc->update_ref = 0;
9421 wc->keep_locks = 1;
66d7e7f0 9422 wc->for_reloc = 1;
0b246afa 9423 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
f82d02d9
YZ
9424
9425 while (1) {
2c47e605
YZ
9426 wret = walk_down_tree(trans, root, path, wc);
9427 if (wret < 0) {
f82d02d9 9428 ret = wret;
f82d02d9 9429 break;
2c47e605 9430 }
f82d02d9 9431
2c47e605 9432 wret = walk_up_tree(trans, root, path, wc, parent_level);
f82d02d9
YZ
9433 if (wret < 0)
9434 ret = wret;
9435 if (wret != 0)
9436 break;
9437 }
9438
2c47e605 9439 kfree(wc);
f82d02d9
YZ
9440 btrfs_free_path(path);
9441 return ret;
9442}
9443
6202df69 9444static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
ec44a35c
CM
9445{
9446 u64 num_devices;
fc67c450 9447 u64 stripped;
e4d8ec0f 9448
fc67c450
ID
9449 /*
9450 * if restripe for this chunk_type is on pick target profile and
9451 * return, otherwise do the usual balance
9452 */
6202df69 9453 stripped = get_restripe_target(fs_info, flags);
fc67c450
ID
9454 if (stripped)
9455 return extended_to_chunk(stripped);
e4d8ec0f 9456
6202df69 9457 num_devices = fs_info->fs_devices->rw_devices;
cd02dca5 9458
fc67c450 9459 stripped = BTRFS_BLOCK_GROUP_RAID0 |
53b381b3 9460 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
fc67c450
ID
9461 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9462
ec44a35c
CM
9463 if (num_devices == 1) {
9464 stripped |= BTRFS_BLOCK_GROUP_DUP;
9465 stripped = flags & ~stripped;
9466
9467 /* turn raid0 into single device chunks */
9468 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9469 return stripped;
9470
9471 /* turn mirroring into duplication */
9472 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9473 BTRFS_BLOCK_GROUP_RAID10))
9474 return stripped | BTRFS_BLOCK_GROUP_DUP;
ec44a35c
CM
9475 } else {
9476 /* they already had raid on here, just return */
ec44a35c
CM
9477 if (flags & stripped)
9478 return flags;
9479
9480 stripped |= BTRFS_BLOCK_GROUP_DUP;
9481 stripped = flags & ~stripped;
9482
9483 /* switch duplicated blocks with raid1 */
9484 if (flags & BTRFS_BLOCK_GROUP_DUP)
9485 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9486
e3176ca2 9487 /* this is drive concat, leave it alone */
ec44a35c 9488 }
e3176ca2 9489
ec44a35c
CM
9490 return flags;
9491}
9492
868f401a 9493static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
0ef3e66b 9494{
f0486c68
YZ
9495 struct btrfs_space_info *sinfo = cache->space_info;
9496 u64 num_bytes;
199c36ea 9497 u64 min_allocable_bytes;
f0486c68 9498 int ret = -ENOSPC;
0ef3e66b 9499
199c36ea
MX
9500 /*
9501 * We need some metadata space and system metadata space for
9502 * allocating chunks in some corner cases until we force to set
9503 * it to be readonly.
9504 */
9505 if ((sinfo->flags &
9506 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9507 !force)
ee22184b 9508 min_allocable_bytes = SZ_1M;
199c36ea
MX
9509 else
9510 min_allocable_bytes = 0;
9511
f0486c68
YZ
9512 spin_lock(&sinfo->lock);
9513 spin_lock(&cache->lock);
61cfea9b
W
9514
9515 if (cache->ro) {
868f401a 9516 cache->ro++;
61cfea9b
W
9517 ret = 0;
9518 goto out;
9519 }
9520
f0486c68
YZ
9521 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9522 cache->bytes_super - btrfs_block_group_used(&cache->item);
9523
4136135b 9524 if (btrfs_space_info_used(sinfo, true) + num_bytes +
37be25bc 9525 min_allocable_bytes <= sinfo->total_bytes) {
f0486c68 9526 sinfo->bytes_readonly += num_bytes;
868f401a 9527 cache->ro++;
633c0aad 9528 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
f0486c68
YZ
9529 ret = 0;
9530 }
61cfea9b 9531out:
f0486c68
YZ
9532 spin_unlock(&cache->lock);
9533 spin_unlock(&sinfo->lock);
9534 return ret;
9535}
7d9eb12c 9536
5e00f193 9537int btrfs_inc_block_group_ro(struct btrfs_fs_info *fs_info,
f0486c68 9538 struct btrfs_block_group_cache *cache)
c286ac48 9539
f0486c68
YZ
9540{
9541 struct btrfs_trans_handle *trans;
9542 u64 alloc_flags;
9543 int ret;
7d9eb12c 9544
1bbc621e 9545again:
5e00f193 9546 trans = btrfs_join_transaction(fs_info->extent_root);
79787eaa
JM
9547 if (IS_ERR(trans))
9548 return PTR_ERR(trans);
5d4f98a2 9549
1bbc621e
CM
9550 /*
9551 * we're not allowed to set block groups readonly after the dirty
9552 * block groups cache has started writing. If it already started,
9553 * back off and let this transaction commit
9554 */
0b246afa 9555 mutex_lock(&fs_info->ro_block_group_mutex);
3204d33c 9556 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
1bbc621e
CM
9557 u64 transid = trans->transid;
9558
0b246afa 9559 mutex_unlock(&fs_info->ro_block_group_mutex);
3a45bb20 9560 btrfs_end_transaction(trans);
1bbc621e 9561
2ff7e61e 9562 ret = btrfs_wait_for_commit(fs_info, transid);
1bbc621e
CM
9563 if (ret)
9564 return ret;
9565 goto again;
9566 }
9567
153c35b6
CM
9568 /*
9569 * if we are changing raid levels, try to allocate a corresponding
9570 * block group with the new raid level.
9571 */
0b246afa 9572 alloc_flags = update_block_group_flags(fs_info, cache->flags);
153c35b6 9573 if (alloc_flags != cache->flags) {
2ff7e61e 9574 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
153c35b6
CM
9575 CHUNK_ALLOC_FORCE);
9576 /*
9577 * ENOSPC is allowed here, we may have enough space
9578 * already allocated at the new raid level to
9579 * carry on
9580 */
9581 if (ret == -ENOSPC)
9582 ret = 0;
9583 if (ret < 0)
9584 goto out;
9585 }
1bbc621e 9586
868f401a 9587 ret = inc_block_group_ro(cache, 0);
f0486c68
YZ
9588 if (!ret)
9589 goto out;
2ff7e61e
JM
9590 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9591 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
0e4f8f88 9592 CHUNK_ALLOC_FORCE);
f0486c68
YZ
9593 if (ret < 0)
9594 goto out;
868f401a 9595 ret = inc_block_group_ro(cache, 0);
f0486c68 9596out:
2f081088 9597 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
0b246afa 9598 alloc_flags = update_block_group_flags(fs_info, cache->flags);
34441361 9599 mutex_lock(&fs_info->chunk_mutex);
2ff7e61e 9600 check_system_chunk(trans, fs_info, alloc_flags);
34441361 9601 mutex_unlock(&fs_info->chunk_mutex);
2f081088 9602 }
0b246afa 9603 mutex_unlock(&fs_info->ro_block_group_mutex);
2f081088 9604
3a45bb20 9605 btrfs_end_transaction(trans);
f0486c68
YZ
9606 return ret;
9607}
5d4f98a2 9608
c87f08ca 9609int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
2ff7e61e 9610 struct btrfs_fs_info *fs_info, u64 type)
c87f08ca 9611{
2ff7e61e
JM
9612 u64 alloc_flags = get_alloc_profile(fs_info, type);
9613
9614 return do_chunk_alloc(trans, fs_info, alloc_flags, CHUNK_ALLOC_FORCE);
c87f08ca
CM
9615}
9616
6d07bcec
MX
9617/*
9618 * helper to account the unused space of all the readonly block group in the
633c0aad 9619 * space_info. takes mirrors into account.
6d07bcec 9620 */
633c0aad 9621u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
6d07bcec
MX
9622{
9623 struct btrfs_block_group_cache *block_group;
9624 u64 free_bytes = 0;
9625 int factor;
9626
01327610 9627 /* It's df, we don't care if it's racy */
633c0aad
JB
9628 if (list_empty(&sinfo->ro_bgs))
9629 return 0;
9630
9631 spin_lock(&sinfo->lock);
9632 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
6d07bcec
MX
9633 spin_lock(&block_group->lock);
9634
9635 if (!block_group->ro) {
9636 spin_unlock(&block_group->lock);
9637 continue;
9638 }
9639
9640 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9641 BTRFS_BLOCK_GROUP_RAID10 |
9642 BTRFS_BLOCK_GROUP_DUP))
9643 factor = 2;
9644 else
9645 factor = 1;
9646
9647 free_bytes += (block_group->key.offset -
9648 btrfs_block_group_used(&block_group->item)) *
9649 factor;
9650
9651 spin_unlock(&block_group->lock);
9652 }
6d07bcec
MX
9653 spin_unlock(&sinfo->lock);
9654
9655 return free_bytes;
9656}
9657
2ff7e61e 9658void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
5d4f98a2 9659{
f0486c68
YZ
9660 struct btrfs_space_info *sinfo = cache->space_info;
9661 u64 num_bytes;
9662
9663 BUG_ON(!cache->ro);
9664
9665 spin_lock(&sinfo->lock);
9666 spin_lock(&cache->lock);
868f401a
Z
9667 if (!--cache->ro) {
9668 num_bytes = cache->key.offset - cache->reserved -
9669 cache->pinned - cache->bytes_super -
9670 btrfs_block_group_used(&cache->item);
9671 sinfo->bytes_readonly -= num_bytes;
9672 list_del_init(&cache->ro_list);
9673 }
f0486c68
YZ
9674 spin_unlock(&cache->lock);
9675 spin_unlock(&sinfo->lock);
5d4f98a2
YZ
9676}
9677
ba1bf481
JB
9678/*
9679 * checks to see if its even possible to relocate this block group.
9680 *
9681 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9682 * ok to go ahead and try.
9683 */
6bccf3ab 9684int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
1a40e23b 9685{
6bccf3ab 9686 struct btrfs_root *root = fs_info->extent_root;
ba1bf481
JB
9687 struct btrfs_block_group_cache *block_group;
9688 struct btrfs_space_info *space_info;
0b246afa 9689 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
ba1bf481 9690 struct btrfs_device *device;
6df9a95e 9691 struct btrfs_trans_handle *trans;
cdcb725c 9692 u64 min_free;
6719db6a
JB
9693 u64 dev_min = 1;
9694 u64 dev_nr = 0;
4a5e98f5 9695 u64 target;
0305bc27 9696 int debug;
cdcb725c 9697 int index;
ba1bf481
JB
9698 int full = 0;
9699 int ret = 0;
1a40e23b 9700
0b246afa 9701 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
0305bc27 9702
0b246afa 9703 block_group = btrfs_lookup_block_group(fs_info, bytenr);
1a40e23b 9704
ba1bf481 9705 /* odd, couldn't find the block group, leave it alone */
0305bc27
QW
9706 if (!block_group) {
9707 if (debug)
0b246afa 9708 btrfs_warn(fs_info,
0305bc27
QW
9709 "can't find block group for bytenr %llu",
9710 bytenr);
ba1bf481 9711 return -1;
0305bc27 9712 }
1a40e23b 9713
cdcb725c 9714 min_free = btrfs_block_group_used(&block_group->item);
9715
ba1bf481 9716 /* no bytes used, we're good */
cdcb725c 9717 if (!min_free)
1a40e23b
ZY
9718 goto out;
9719
ba1bf481
JB
9720 space_info = block_group->space_info;
9721 spin_lock(&space_info->lock);
17d217fe 9722
ba1bf481 9723 full = space_info->full;
17d217fe 9724
ba1bf481
JB
9725 /*
9726 * if this is the last block group we have in this space, we can't
7ce618db
CM
9727 * relocate it unless we're able to allocate a new chunk below.
9728 *
9729 * Otherwise, we need to make sure we have room in the space to handle
9730 * all of the extents from this block group. If we can, we're good
ba1bf481 9731 */
7ce618db 9732 if ((space_info->total_bytes != block_group->key.offset) &&
4136135b
LB
9733 (btrfs_space_info_used(space_info, false) + min_free <
9734 space_info->total_bytes)) {
ba1bf481
JB
9735 spin_unlock(&space_info->lock);
9736 goto out;
17d217fe 9737 }
ba1bf481 9738 spin_unlock(&space_info->lock);
ea8c2819 9739
ba1bf481
JB
9740 /*
9741 * ok we don't have enough space, but maybe we have free space on our
9742 * devices to allocate new chunks for relocation, so loop through our
4a5e98f5
ID
9743 * alloc devices and guess if we have enough space. if this block
9744 * group is going to be restriped, run checks against the target
9745 * profile instead of the current one.
ba1bf481
JB
9746 */
9747 ret = -1;
ea8c2819 9748
cdcb725c 9749 /*
9750 * index:
9751 * 0: raid10
9752 * 1: raid1
9753 * 2: dup
9754 * 3: raid0
9755 * 4: single
9756 */
0b246afa 9757 target = get_restripe_target(fs_info, block_group->flags);
4a5e98f5 9758 if (target) {
31e50229 9759 index = __get_raid_index(extended_to_chunk(target));
4a5e98f5
ID
9760 } else {
9761 /*
9762 * this is just a balance, so if we were marked as full
9763 * we know there is no space for a new chunk
9764 */
0305bc27
QW
9765 if (full) {
9766 if (debug)
0b246afa
JM
9767 btrfs_warn(fs_info,
9768 "no space to alloc new chunk for block group %llu",
9769 block_group->key.objectid);
4a5e98f5 9770 goto out;
0305bc27 9771 }
4a5e98f5
ID
9772
9773 index = get_block_group_index(block_group);
9774 }
9775
e6ec716f 9776 if (index == BTRFS_RAID_RAID10) {
cdcb725c 9777 dev_min = 4;
6719db6a
JB
9778 /* Divide by 2 */
9779 min_free >>= 1;
e6ec716f 9780 } else if (index == BTRFS_RAID_RAID1) {
cdcb725c 9781 dev_min = 2;
e6ec716f 9782 } else if (index == BTRFS_RAID_DUP) {
6719db6a
JB
9783 /* Multiply by 2 */
9784 min_free <<= 1;
e6ec716f 9785 } else if (index == BTRFS_RAID_RAID0) {
cdcb725c 9786 dev_min = fs_devices->rw_devices;
47c5713f 9787 min_free = div64_u64(min_free, dev_min);
cdcb725c 9788 }
9789
6df9a95e
JB
9790 /* We need to do this so that we can look at pending chunks */
9791 trans = btrfs_join_transaction(root);
9792 if (IS_ERR(trans)) {
9793 ret = PTR_ERR(trans);
9794 goto out;
9795 }
9796
0b246afa 9797 mutex_lock(&fs_info->chunk_mutex);
ba1bf481 9798 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7bfc837d 9799 u64 dev_offset;
56bec294 9800
ba1bf481
JB
9801 /*
9802 * check to make sure we can actually find a chunk with enough
9803 * space to fit our block group in.
9804 */
63a212ab
SB
9805 if (device->total_bytes > device->bytes_used + min_free &&
9806 !device->is_tgtdev_for_dev_replace) {
6df9a95e 9807 ret = find_free_dev_extent(trans, device, min_free,
7bfc837d 9808 &dev_offset, NULL);
ba1bf481 9809 if (!ret)
cdcb725c 9810 dev_nr++;
9811
9812 if (dev_nr >= dev_min)
73e48b27 9813 break;
cdcb725c 9814
ba1bf481 9815 ret = -1;
725c8463 9816 }
edbd8d4e 9817 }
0305bc27 9818 if (debug && ret == -1)
0b246afa
JM
9819 btrfs_warn(fs_info,
9820 "no space to allocate a new chunk for block group %llu",
9821 block_group->key.objectid);
9822 mutex_unlock(&fs_info->chunk_mutex);
3a45bb20 9823 btrfs_end_transaction(trans);
edbd8d4e 9824out:
ba1bf481 9825 btrfs_put_block_group(block_group);
edbd8d4e
CM
9826 return ret;
9827}
9828
6bccf3ab
JM
9829static int find_first_block_group(struct btrfs_fs_info *fs_info,
9830 struct btrfs_path *path,
9831 struct btrfs_key *key)
0b86a832 9832{
6bccf3ab 9833 struct btrfs_root *root = fs_info->extent_root;
925baedd 9834 int ret = 0;
0b86a832
CM
9835 struct btrfs_key found_key;
9836 struct extent_buffer *leaf;
34407a17
QW
9837 struct btrfs_block_group_item bg;
9838 u64 flags;
0b86a832 9839 int slot;
edbd8d4e 9840
0b86a832
CM
9841 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9842 if (ret < 0)
925baedd
CM
9843 goto out;
9844
d397712b 9845 while (1) {
0b86a832 9846 slot = path->slots[0];
edbd8d4e 9847 leaf = path->nodes[0];
0b86a832
CM
9848 if (slot >= btrfs_header_nritems(leaf)) {
9849 ret = btrfs_next_leaf(root, path);
9850 if (ret == 0)
9851 continue;
9852 if (ret < 0)
925baedd 9853 goto out;
0b86a832 9854 break;
edbd8d4e 9855 }
0b86a832 9856 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 9857
0b86a832 9858 if (found_key.objectid >= key->objectid &&
925baedd 9859 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
6fb37b75
LB
9860 struct extent_map_tree *em_tree;
9861 struct extent_map *em;
9862
9863 em_tree = &root->fs_info->mapping_tree.map_tree;
9864 read_lock(&em_tree->lock);
9865 em = lookup_extent_mapping(em_tree, found_key.objectid,
9866 found_key.offset);
9867 read_unlock(&em_tree->lock);
9868 if (!em) {
0b246afa 9869 btrfs_err(fs_info,
6fb37b75
LB
9870 "logical %llu len %llu found bg but no related chunk",
9871 found_key.objectid, found_key.offset);
9872 ret = -ENOENT;
34407a17
QW
9873 } else if (em->start != found_key.objectid ||
9874 em->len != found_key.offset) {
9875 btrfs_err(fs_info,
9876 "block group %llu len %llu mismatch with chunk %llu len %llu",
9877 found_key.objectid, found_key.offset,
9878 em->start, em->len);
9879 ret = -EUCLEAN;
6fb37b75 9880 } else {
34407a17
QW
9881 read_extent_buffer(leaf, &bg,
9882 btrfs_item_ptr_offset(leaf, slot),
9883 sizeof(bg));
9884 flags = btrfs_block_group_flags(&bg) &
9885 BTRFS_BLOCK_GROUP_TYPE_MASK;
9886
9887 if (flags != (em->map_lookup->type &
9888 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9889 btrfs_err(fs_info,
9890"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
9891 found_key.objectid,
9892 found_key.offset, flags,
9893 (BTRFS_BLOCK_GROUP_TYPE_MASK &
9894 em->map_lookup->type));
9895 ret = -EUCLEAN;
9896 } else {
9897 ret = 0;
9898 }
6fb37b75 9899 }
187ee58c 9900 free_extent_map(em);
925baedd
CM
9901 goto out;
9902 }
0b86a832 9903 path->slots[0]++;
edbd8d4e 9904 }
925baedd 9905out:
0b86a832 9906 return ret;
edbd8d4e
CM
9907}
9908
0af3d00b
JB
9909void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9910{
9911 struct btrfs_block_group_cache *block_group;
9912 u64 last = 0;
9913
9914 while (1) {
9915 struct inode *inode;
9916
9917 block_group = btrfs_lookup_first_block_group(info, last);
9918 while (block_group) {
9ce0f8b6 9919 wait_block_group_cache_done(block_group);
0af3d00b
JB
9920 spin_lock(&block_group->lock);
9921 if (block_group->iref)
9922 break;
9923 spin_unlock(&block_group->lock);
2ff7e61e 9924 block_group = next_block_group(info, block_group);
0af3d00b
JB
9925 }
9926 if (!block_group) {
9927 if (last == 0)
9928 break;
9929 last = 0;
9930 continue;
9931 }
9932
9933 inode = block_group->inode;
9934 block_group->iref = 0;
9935 block_group->inode = NULL;
9936 spin_unlock(&block_group->lock);
f3bca802 9937 ASSERT(block_group->io_ctl.inode == NULL);
0af3d00b
JB
9938 iput(inode);
9939 last = block_group->key.objectid + block_group->key.offset;
9940 btrfs_put_block_group(block_group);
9941 }
9942}
9943
5cdd7db6
FM
9944/*
9945 * Must be called only after stopping all workers, since we could have block
9946 * group caching kthreads running, and therefore they could race with us if we
9947 * freed the block groups before stopping them.
9948 */
1a40e23b
ZY
9949int btrfs_free_block_groups(struct btrfs_fs_info *info)
9950{
9951 struct btrfs_block_group_cache *block_group;
4184ea7f 9952 struct btrfs_space_info *space_info;
11833d66 9953 struct btrfs_caching_control *caching_ctl;
1a40e23b
ZY
9954 struct rb_node *n;
9955
9e351cc8 9956 down_write(&info->commit_root_sem);
11833d66
YZ
9957 while (!list_empty(&info->caching_block_groups)) {
9958 caching_ctl = list_entry(info->caching_block_groups.next,
9959 struct btrfs_caching_control, list);
9960 list_del(&caching_ctl->list);
9961 put_caching_control(caching_ctl);
9962 }
9e351cc8 9963 up_write(&info->commit_root_sem);
11833d66 9964
47ab2a6c
JB
9965 spin_lock(&info->unused_bgs_lock);
9966 while (!list_empty(&info->unused_bgs)) {
9967 block_group = list_first_entry(&info->unused_bgs,
9968 struct btrfs_block_group_cache,
9969 bg_list);
9970 list_del_init(&block_group->bg_list);
9971 btrfs_put_block_group(block_group);
9972 }
9973 spin_unlock(&info->unused_bgs_lock);
9974
1a40e23b
ZY
9975 spin_lock(&info->block_group_cache_lock);
9976 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9977 block_group = rb_entry(n, struct btrfs_block_group_cache,
9978 cache_node);
1a40e23b
ZY
9979 rb_erase(&block_group->cache_node,
9980 &info->block_group_cache_tree);
01eacb27 9981 RB_CLEAR_NODE(&block_group->cache_node);
d899e052
YZ
9982 spin_unlock(&info->block_group_cache_lock);
9983
80eb234a 9984 down_write(&block_group->space_info->groups_sem);
1a40e23b 9985 list_del(&block_group->list);
80eb234a 9986 up_write(&block_group->space_info->groups_sem);
d2fb3437 9987
3c14874a
JB
9988 /*
9989 * We haven't cached this block group, which means we could
9990 * possibly have excluded extents on this block group.
9991 */
36cce922
JB
9992 if (block_group->cached == BTRFS_CACHE_NO ||
9993 block_group->cached == BTRFS_CACHE_ERROR)
2ff7e61e 9994 free_excluded_extents(info, block_group);
3c14874a 9995
817d52f8 9996 btrfs_remove_free_space_cache(block_group);
5cdd7db6 9997 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
f3bca802
LB
9998 ASSERT(list_empty(&block_group->dirty_list));
9999 ASSERT(list_empty(&block_group->io_list));
10000 ASSERT(list_empty(&block_group->bg_list));
10001 ASSERT(atomic_read(&block_group->count) == 1);
11dfe35a 10002 btrfs_put_block_group(block_group);
d899e052
YZ
10003
10004 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
10005 }
10006 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
10007
10008 /* now that all the block groups are freed, go through and
10009 * free all the space_info structs. This is only called during
10010 * the final stages of unmount, and so we know nobody is
10011 * using them. We call synchronize_rcu() once before we start,
10012 * just to be on the safe side.
10013 */
10014 synchronize_rcu();
10015
8929ecfa
YZ
10016 release_global_block_rsv(info);
10017
67871254 10018 while (!list_empty(&info->space_info)) {
6ab0a202
JM
10019 int i;
10020
4184ea7f
CM
10021 space_info = list_entry(info->space_info.next,
10022 struct btrfs_space_info,
10023 list);
d555b6c3
JB
10024
10025 /*
10026 * Do not hide this behind enospc_debug, this is actually
10027 * important and indicates a real bug if this happens.
10028 */
10029 if (WARN_ON(space_info->bytes_pinned > 0 ||
b069e0c3 10030 space_info->bytes_reserved > 0 ||
d555b6c3 10031 space_info->bytes_may_use > 0))
ab8d0fc4 10032 dump_space_info(info, space_info, 0, 0);
4184ea7f 10033 list_del(&space_info->list);
6ab0a202
JM
10034 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
10035 struct kobject *kobj;
c1895442
JM
10036 kobj = space_info->block_group_kobjs[i];
10037 space_info->block_group_kobjs[i] = NULL;
10038 if (kobj) {
6ab0a202
JM
10039 kobject_del(kobj);
10040 kobject_put(kobj);
10041 }
10042 }
10043 kobject_del(&space_info->kobj);
10044 kobject_put(&space_info->kobj);
4184ea7f 10045 }
1a40e23b
ZY
10046 return 0;
10047}
10048
b742bb82
YZ
10049static void __link_block_group(struct btrfs_space_info *space_info,
10050 struct btrfs_block_group_cache *cache)
10051{
10052 int index = get_block_group_index(cache);
ed55b6ac 10053 bool first = false;
b742bb82
YZ
10054
10055 down_write(&space_info->groups_sem);
ed55b6ac
JM
10056 if (list_empty(&space_info->block_groups[index]))
10057 first = true;
10058 list_add_tail(&cache->list, &space_info->block_groups[index]);
10059 up_write(&space_info->groups_sem);
10060
10061 if (first) {
c1895442 10062 struct raid_kobject *rkobj;
6ab0a202
JM
10063 int ret;
10064
c1895442
JM
10065 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
10066 if (!rkobj)
10067 goto out_err;
10068 rkobj->raid_type = index;
10069 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
10070 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
10071 "%s", get_raid_name(index));
6ab0a202 10072 if (ret) {
c1895442
JM
10073 kobject_put(&rkobj->kobj);
10074 goto out_err;
6ab0a202 10075 }
c1895442 10076 space_info->block_group_kobjs[index] = &rkobj->kobj;
6ab0a202 10077 }
c1895442
JM
10078
10079 return;
10080out_err:
ab8d0fc4
JM
10081 btrfs_warn(cache->fs_info,
10082 "failed to add kobject for block cache, ignoring");
b742bb82
YZ
10083}
10084
920e4a58 10085static struct btrfs_block_group_cache *
2ff7e61e
JM
10086btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
10087 u64 start, u64 size)
920e4a58
MX
10088{
10089 struct btrfs_block_group_cache *cache;
10090
10091 cache = kzalloc(sizeof(*cache), GFP_NOFS);
10092 if (!cache)
10093 return NULL;
10094
10095 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
10096 GFP_NOFS);
10097 if (!cache->free_space_ctl) {
10098 kfree(cache);
10099 return NULL;
10100 }
10101
10102 cache->key.objectid = start;
10103 cache->key.offset = size;
10104 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10105
0b246afa 10106 cache->fs_info = fs_info;
e4ff5fb5 10107 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1e144fb8
OS
10108 set_free_space_tree_thresholds(cache);
10109
920e4a58
MX
10110 atomic_set(&cache->count, 1);
10111 spin_lock_init(&cache->lock);
e570fd27 10112 init_rwsem(&cache->data_rwsem);
920e4a58
MX
10113 INIT_LIST_HEAD(&cache->list);
10114 INIT_LIST_HEAD(&cache->cluster_list);
47ab2a6c 10115 INIT_LIST_HEAD(&cache->bg_list);
633c0aad 10116 INIT_LIST_HEAD(&cache->ro_list);
ce93ec54 10117 INIT_LIST_HEAD(&cache->dirty_list);
c9dc4c65 10118 INIT_LIST_HEAD(&cache->io_list);
920e4a58 10119 btrfs_init_free_space_ctl(cache);
04216820 10120 atomic_set(&cache->trimming, 0);
a5ed9182 10121 mutex_init(&cache->free_space_lock);
0966a7b1 10122 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
920e4a58
MX
10123
10124 return cache;
10125}
10126
895586ec
QW
10127
10128/*
10129 * Iterate all chunks and verify that each of them has the corresponding block
10130 * group
10131 */
10132static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
10133{
10134 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
10135 struct extent_map *em;
10136 struct btrfs_block_group_cache *bg;
10137 u64 start = 0;
10138 int ret = 0;
10139
10140 while (1) {
10141 read_lock(&map_tree->map_tree.lock);
10142 /*
10143 * lookup_extent_mapping will return the first extent map
10144 * intersecting the range, so setting @len to 1 is enough to
10145 * get the first chunk.
10146 */
10147 em = lookup_extent_mapping(&map_tree->map_tree, start, 1);
10148 read_unlock(&map_tree->map_tree.lock);
10149 if (!em)
10150 break;
10151
10152 bg = btrfs_lookup_block_group(fs_info, em->start);
10153 if (!bg) {
10154 btrfs_err(fs_info,
10155 "chunk start=%llu len=%llu doesn't have corresponding block group",
10156 em->start, em->len);
10157 ret = -EUCLEAN;
10158 free_extent_map(em);
10159 break;
10160 }
10161 if (bg->key.objectid != em->start ||
10162 bg->key.offset != em->len ||
10163 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
10164 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
10165 btrfs_err(fs_info,
10166"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
10167 em->start, em->len,
10168 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
10169 bg->key.objectid, bg->key.offset,
10170 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
10171 ret = -EUCLEAN;
10172 free_extent_map(em);
10173 btrfs_put_block_group(bg);
10174 break;
10175 }
10176 start = em->start + em->len;
10177 free_extent_map(em);
10178 btrfs_put_block_group(bg);
10179 }
10180 return ret;
10181}
10182
5b4aacef 10183int btrfs_read_block_groups(struct btrfs_fs_info *info)
9078a3e1
CM
10184{
10185 struct btrfs_path *path;
10186 int ret;
9078a3e1 10187 struct btrfs_block_group_cache *cache;
6324fbf3 10188 struct btrfs_space_info *space_info;
9078a3e1
CM
10189 struct btrfs_key key;
10190 struct btrfs_key found_key;
5f39d397 10191 struct extent_buffer *leaf;
0af3d00b
JB
10192 int need_clear = 0;
10193 u64 cache_gen;
49303381
LB
10194 u64 feature;
10195 int mixed;
10196
10197 feature = btrfs_super_incompat_flags(info->super_copy);
10198 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
96b5179d 10199
9078a3e1 10200 key.objectid = 0;
0b86a832 10201 key.offset = 0;
962a298f 10202 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9078a3e1
CM
10203 path = btrfs_alloc_path();
10204 if (!path)
10205 return -ENOMEM;
e4058b54 10206 path->reada = READA_FORWARD;
9078a3e1 10207
0b246afa
JM
10208 cache_gen = btrfs_super_cache_generation(info->super_copy);
10209 if (btrfs_test_opt(info, SPACE_CACHE) &&
10210 btrfs_super_generation(info->super_copy) != cache_gen)
0af3d00b 10211 need_clear = 1;
0b246afa 10212 if (btrfs_test_opt(info, CLEAR_CACHE))
88c2ba3b 10213 need_clear = 1;
0af3d00b 10214
d397712b 10215 while (1) {
6bccf3ab 10216 ret = find_first_block_group(info, path, &key);
b742bb82
YZ
10217 if (ret > 0)
10218 break;
0b86a832
CM
10219 if (ret != 0)
10220 goto error;
920e4a58 10221
5f39d397
CM
10222 leaf = path->nodes[0];
10223 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
920e4a58 10224
2ff7e61e 10225 cache = btrfs_create_block_group_cache(info, found_key.objectid,
920e4a58 10226 found_key.offset);
9078a3e1 10227 if (!cache) {
0b86a832 10228 ret = -ENOMEM;
f0486c68 10229 goto error;
9078a3e1 10230 }
96303081 10231
cf7c1ef6
LB
10232 if (need_clear) {
10233 /*
10234 * When we mount with old space cache, we need to
10235 * set BTRFS_DC_CLEAR and set dirty flag.
10236 *
10237 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
10238 * truncate the old free space cache inode and
10239 * setup a new one.
10240 * b) Setting 'dirty flag' makes sure that we flush
10241 * the new space cache info onto disk.
10242 */
0b246afa 10243 if (btrfs_test_opt(info, SPACE_CACHE))
ce93ec54 10244 cache->disk_cache_state = BTRFS_DC_CLEAR;
cf7c1ef6 10245 }
0af3d00b 10246
5f39d397
CM
10247 read_extent_buffer(leaf, &cache->item,
10248 btrfs_item_ptr_offset(leaf, path->slots[0]),
10249 sizeof(cache->item));
920e4a58 10250 cache->flags = btrfs_block_group_flags(&cache->item);
49303381
LB
10251 if (!mixed &&
10252 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
10253 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10254 btrfs_err(info,
10255"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10256 cache->key.objectid);
e06e89fe 10257 btrfs_put_block_group(cache);
49303381
LB
10258 ret = -EINVAL;
10259 goto error;
10260 }
0b86a832 10261
9078a3e1 10262 key.objectid = found_key.objectid + found_key.offset;
b3b4aa74 10263 btrfs_release_path(path);
34d52cb6 10264
3c14874a
JB
10265 /*
10266 * We need to exclude the super stripes now so that the space
10267 * info has super bytes accounted for, otherwise we'll think
10268 * we have more space than we actually do.
10269 */
2ff7e61e 10270 ret = exclude_super_stripes(info, cache);
835d974f
JB
10271 if (ret) {
10272 /*
10273 * We may have excluded something, so call this just in
10274 * case.
10275 */
2ff7e61e 10276 free_excluded_extents(info, cache);
920e4a58 10277 btrfs_put_block_group(cache);
835d974f
JB
10278 goto error;
10279 }
3c14874a 10280
817d52f8
JB
10281 /*
10282 * check for two cases, either we are full, and therefore
10283 * don't need to bother with the caching work since we won't
10284 * find any space, or we are empty, and we can just add all
10285 * the space in and be done with it. This saves us _alot_ of
10286 * time, particularly in the full case.
10287 */
10288 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
11833d66 10289 cache->last_byte_to_unpin = (u64)-1;
817d52f8 10290 cache->cached = BTRFS_CACHE_FINISHED;
2ff7e61e 10291 free_excluded_extents(info, cache);
817d52f8 10292 } else if (btrfs_block_group_used(&cache->item) == 0) {
11833d66 10293 cache->last_byte_to_unpin = (u64)-1;
817d52f8 10294 cache->cached = BTRFS_CACHE_FINISHED;
0b246afa 10295 add_new_free_space(cache, info,
817d52f8
JB
10296 found_key.objectid,
10297 found_key.objectid +
10298 found_key.offset);
2ff7e61e 10299 free_excluded_extents(info, cache);
817d52f8 10300 }
96b5179d 10301
0b246afa 10302 ret = btrfs_add_block_group_cache(info, cache);
8c579fe7
JB
10303 if (ret) {
10304 btrfs_remove_free_space_cache(cache);
10305 btrfs_put_block_group(cache);
10306 goto error;
10307 }
10308
0b246afa 10309 trace_btrfs_add_block_group(info, cache, 0);
d2006e6d
NB
10310 update_space_info(info, cache->flags, found_key.offset,
10311 btrfs_block_group_used(&cache->item),
10312 cache->bytes_super, &space_info);
8c579fe7 10313
6324fbf3 10314 cache->space_info = space_info;
1b2da372 10315
b742bb82 10316 __link_block_group(space_info, cache);
0f9dd46c 10317
0b246afa 10318 set_avail_alloc_bits(info, cache->flags);
2ff7e61e 10319 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
868f401a 10320 inc_block_group_ro(cache, 1);
47ab2a6c
JB
10321 } else if (btrfs_block_group_used(&cache->item) == 0) {
10322 spin_lock(&info->unused_bgs_lock);
10323 /* Should always be true but just in case. */
10324 if (list_empty(&cache->bg_list)) {
10325 btrfs_get_block_group(cache);
10326 list_add_tail(&cache->bg_list,
10327 &info->unused_bgs);
10328 }
10329 spin_unlock(&info->unused_bgs_lock);
10330 }
9078a3e1 10331 }
b742bb82 10332
0b246afa 10333 list_for_each_entry_rcu(space_info, &info->space_info, list) {
2ff7e61e 10334 if (!(get_alloc_profile(info, space_info->flags) &
b742bb82
YZ
10335 (BTRFS_BLOCK_GROUP_RAID10 |
10336 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
10337 BTRFS_BLOCK_GROUP_RAID5 |
10338 BTRFS_BLOCK_GROUP_RAID6 |
b742bb82
YZ
10339 BTRFS_BLOCK_GROUP_DUP)))
10340 continue;
10341 /*
10342 * avoid allocating from un-mirrored block group if there are
10343 * mirrored block groups.
10344 */
1095cc0d 10345 list_for_each_entry(cache,
10346 &space_info->block_groups[BTRFS_RAID_RAID0],
10347 list)
868f401a 10348 inc_block_group_ro(cache, 1);
1095cc0d 10349 list_for_each_entry(cache,
10350 &space_info->block_groups[BTRFS_RAID_SINGLE],
10351 list)
868f401a 10352 inc_block_group_ro(cache, 1);
9078a3e1 10353 }
f0486c68
YZ
10354
10355 init_global_block_rsv(info);
895586ec 10356 ret = check_chunk_block_group_mappings(info);
0b86a832 10357error:
9078a3e1 10358 btrfs_free_path(path);
0b86a832 10359 return ret;
9078a3e1 10360}
6324fbf3 10361
ea658bad 10362void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
2ff7e61e 10363 struct btrfs_fs_info *fs_info)
ea658bad 10364{
0ae66cf1 10365 struct btrfs_block_group_cache *block_group;
0b246afa 10366 struct btrfs_root *extent_root = fs_info->extent_root;
ea658bad
JB
10367 struct btrfs_block_group_item item;
10368 struct btrfs_key key;
10369 int ret = 0;
d9a0540a 10370 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
ea658bad 10371
d9a0540a 10372 trans->can_flush_pending_bgs = false;
0ae66cf1
JB
10373 while (!list_empty(&trans->new_bgs)) {
10374 block_group = list_first_entry(&trans->new_bgs,
10375 struct btrfs_block_group_cache,
10376 bg_list);
ea658bad 10377 if (ret)
c92f6be3 10378 goto next;
ea658bad
JB
10379
10380 spin_lock(&block_group->lock);
10381 memcpy(&item, &block_group->item, sizeof(item));
10382 memcpy(&key, &block_group->key, sizeof(key));
10383 spin_unlock(&block_group->lock);
10384
10385 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10386 sizeof(item));
10387 if (ret)
66642832 10388 btrfs_abort_transaction(trans, ret);
0b246afa
JM
10389 ret = btrfs_finish_chunk_alloc(trans, fs_info, key.objectid,
10390 key.offset);
6df9a95e 10391 if (ret)
66642832 10392 btrfs_abort_transaction(trans, ret);
0b246afa 10393 add_block_group_free_space(trans, fs_info, block_group);
1e144fb8 10394 /* already aborted the transaction if it failed. */
c92f6be3
FM
10395next:
10396 list_del_init(&block_group->bg_list);
ea658bad 10397 }
d9a0540a 10398 trans->can_flush_pending_bgs = can_flush_pending_bgs;
ea658bad
JB
10399}
10400
6324fbf3 10401int btrfs_make_block_group(struct btrfs_trans_handle *trans,
2ff7e61e 10402 struct btrfs_fs_info *fs_info, u64 bytes_used,
0174484d 10403 u64 type, u64 chunk_offset, u64 size)
6324fbf3 10404{
6324fbf3 10405 struct btrfs_block_group_cache *cache;
0b246afa 10406 int ret;
6324fbf3 10407
0b246afa 10408 btrfs_set_log_full_commit(fs_info, trans);
e02119d5 10409
2ff7e61e 10410 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
0f9dd46c
JB
10411 if (!cache)
10412 return -ENOMEM;
34d52cb6 10413
6324fbf3 10414 btrfs_set_block_group_used(&cache->item, bytes_used);
0174484d
NB
10415 btrfs_set_block_group_chunk_objectid(&cache->item,
10416 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
6324fbf3
CM
10417 btrfs_set_block_group_flags(&cache->item, type);
10418
920e4a58 10419 cache->flags = type;
11833d66 10420 cache->last_byte_to_unpin = (u64)-1;
817d52f8 10421 cache->cached = BTRFS_CACHE_FINISHED;
1e144fb8 10422 cache->needs_free_space = 1;
2ff7e61e 10423 ret = exclude_super_stripes(fs_info, cache);
835d974f
JB
10424 if (ret) {
10425 /*
10426 * We may have excluded something, so call this just in
10427 * case.
10428 */
2ff7e61e 10429 free_excluded_extents(fs_info, cache);
920e4a58 10430 btrfs_put_block_group(cache);
835d974f
JB
10431 return ret;
10432 }
96303081 10433
0b246afa 10434 add_new_free_space(cache, fs_info, chunk_offset, chunk_offset + size);
817d52f8 10435
2ff7e61e 10436 free_excluded_extents(fs_info, cache);
11833d66 10437
d0bd4560 10438#ifdef CONFIG_BTRFS_DEBUG
2ff7e61e 10439 if (btrfs_should_fragment_free_space(cache)) {
d0bd4560
JB
10440 u64 new_bytes_used = size - bytes_used;
10441
10442 bytes_used += new_bytes_used >> 1;
2ff7e61e 10443 fragment_free_space(cache);
d0bd4560
JB
10444 }
10445#endif
2e6e5183 10446 /*
2be12ef7
NB
10447 * Ensure the corresponding space_info object is created and
10448 * assigned to our block group. We want our bg to be added to the rbtree
10449 * with its ->space_info set.
2e6e5183 10450 */
2be12ef7
NB
10451 cache->space_info = __find_space_info(fs_info, cache->flags);
10452 if (!cache->space_info) {
10453 ret = create_space_info(fs_info, cache->flags,
10454 &cache->space_info);
10455 if (ret) {
10456 btrfs_remove_free_space_cache(cache);
10457 btrfs_put_block_group(cache);
10458 return ret;
10459 }
2e6e5183
FM
10460 }
10461
0b246afa 10462 ret = btrfs_add_block_group_cache(fs_info, cache);
8c579fe7
JB
10463 if (ret) {
10464 btrfs_remove_free_space_cache(cache);
10465 btrfs_put_block_group(cache);
10466 return ret;
10467 }
10468
2e6e5183
FM
10469 /*
10470 * Now that our block group has its ->space_info set and is inserted in
10471 * the rbtree, update the space info's counters.
10472 */
0b246afa 10473 trace_btrfs_add_block_group(fs_info, cache, 1);
d2006e6d 10474 update_space_info(fs_info, cache->flags, size, bytes_used,
e40edf2d 10475 cache->bytes_super, &cache->space_info);
0b246afa 10476 update_global_block_rsv(fs_info);
1b2da372 10477
b742bb82 10478 __link_block_group(cache->space_info, cache);
6324fbf3 10479
47ab2a6c 10480 list_add_tail(&cache->bg_list, &trans->new_bgs);
6324fbf3 10481
0b246afa 10482 set_avail_alloc_bits(fs_info, type);
6324fbf3
CM
10483 return 0;
10484}
1a40e23b 10485
10ea00f5
ID
10486static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10487{
899c81ea
ID
10488 u64 extra_flags = chunk_to_extended(flags) &
10489 BTRFS_EXTENDED_PROFILE_MASK;
10ea00f5 10490
de98ced9 10491 write_seqlock(&fs_info->profiles_lock);
10ea00f5
ID
10492 if (flags & BTRFS_BLOCK_GROUP_DATA)
10493 fs_info->avail_data_alloc_bits &= ~extra_flags;
10494 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10495 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10496 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10497 fs_info->avail_system_alloc_bits &= ~extra_flags;
de98ced9 10498 write_sequnlock(&fs_info->profiles_lock);
10ea00f5
ID
10499}
10500
1a40e23b 10501int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
6bccf3ab 10502 struct btrfs_fs_info *fs_info, u64 group_start,
04216820 10503 struct extent_map *em)
1a40e23b 10504{
6bccf3ab 10505 struct btrfs_root *root = fs_info->extent_root;
1a40e23b
ZY
10506 struct btrfs_path *path;
10507 struct btrfs_block_group_cache *block_group;
44fb5511 10508 struct btrfs_free_cluster *cluster;
0b246afa 10509 struct btrfs_root *tree_root = fs_info->tree_root;
1a40e23b 10510 struct btrfs_key key;
0af3d00b 10511 struct inode *inode;
c1895442 10512 struct kobject *kobj = NULL;
1a40e23b 10513 int ret;
10ea00f5 10514 int index;
89a55897 10515 int factor;
4f69cb98 10516 struct btrfs_caching_control *caching_ctl = NULL;
04216820 10517 bool remove_em;
1a40e23b 10518
6bccf3ab 10519 block_group = btrfs_lookup_block_group(fs_info, group_start);
1a40e23b 10520 BUG_ON(!block_group);
c146afad 10521 BUG_ON(!block_group->ro);
1a40e23b 10522
9f7c43c9 10523 /*
10524 * Free the reserved super bytes from this block group before
10525 * remove it.
10526 */
2ff7e61e 10527 free_excluded_extents(fs_info, block_group);
9f7c43c9 10528
1a40e23b 10529 memcpy(&key, &block_group->key, sizeof(key));
10ea00f5 10530 index = get_block_group_index(block_group);
89a55897
JB
10531 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
10532 BTRFS_BLOCK_GROUP_RAID1 |
10533 BTRFS_BLOCK_GROUP_RAID10))
10534 factor = 2;
10535 else
10536 factor = 1;
1a40e23b 10537
44fb5511 10538 /* make sure this block group isn't part of an allocation cluster */
0b246afa 10539 cluster = &fs_info->data_alloc_cluster;
44fb5511
CM
10540 spin_lock(&cluster->refill_lock);
10541 btrfs_return_cluster_to_free_space(block_group, cluster);
10542 spin_unlock(&cluster->refill_lock);
10543
10544 /*
10545 * make sure this block group isn't part of a metadata
10546 * allocation cluster
10547 */
0b246afa 10548 cluster = &fs_info->meta_alloc_cluster;
44fb5511
CM
10549 spin_lock(&cluster->refill_lock);
10550 btrfs_return_cluster_to_free_space(block_group, cluster);
10551 spin_unlock(&cluster->refill_lock);
10552
1a40e23b 10553 path = btrfs_alloc_path();
d8926bb3
MF
10554 if (!path) {
10555 ret = -ENOMEM;
b74639ca 10556 goto out;
d8926bb3 10557 }
1a40e23b 10558
1bbc621e
CM
10559 /*
10560 * get the inode first so any iput calls done for the io_list
10561 * aren't the final iput (no unlinks allowed now)
10562 */
77ab86bf 10563 inode = lookup_free_space_inode(fs_info, block_group, path);
1bbc621e
CM
10564
10565 mutex_lock(&trans->transaction->cache_write_mutex);
10566 /*
10567 * make sure our free spache cache IO is done before remove the
10568 * free space inode
10569 */
10570 spin_lock(&trans->transaction->dirty_bgs_lock);
10571 if (!list_empty(&block_group->io_list)) {
10572 list_del_init(&block_group->io_list);
10573
10574 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10575
10576 spin_unlock(&trans->transaction->dirty_bgs_lock);
afdb5718 10577 btrfs_wait_cache_io(trans, block_group, path);
1bbc621e
CM
10578 btrfs_put_block_group(block_group);
10579 spin_lock(&trans->transaction->dirty_bgs_lock);
10580 }
10581
10582 if (!list_empty(&block_group->dirty_list)) {
10583 list_del_init(&block_group->dirty_list);
10584 btrfs_put_block_group(block_group);
10585 }
10586 spin_unlock(&trans->transaction->dirty_bgs_lock);
10587 mutex_unlock(&trans->transaction->cache_write_mutex);
10588
0af3d00b 10589 if (!IS_ERR(inode)) {
73f2e545 10590 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
79787eaa
JM
10591 if (ret) {
10592 btrfs_add_delayed_iput(inode);
b74639ca 10593 goto out;
79787eaa 10594 }
0af3d00b
JB
10595 clear_nlink(inode);
10596 /* One for the block groups ref */
10597 spin_lock(&block_group->lock);
10598 if (block_group->iref) {
10599 block_group->iref = 0;
10600 block_group->inode = NULL;
10601 spin_unlock(&block_group->lock);
10602 iput(inode);
10603 } else {
10604 spin_unlock(&block_group->lock);
10605 }
10606 /* One for our lookup ref */
455757c3 10607 btrfs_add_delayed_iput(inode);
0af3d00b
JB
10608 }
10609
10610 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10611 key.offset = block_group->key.objectid;
10612 key.type = 0;
10613
10614 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10615 if (ret < 0)
b74639ca 10616 goto out;
0af3d00b 10617 if (ret > 0)
b3b4aa74 10618 btrfs_release_path(path);
0af3d00b
JB
10619 if (ret == 0) {
10620 ret = btrfs_del_item(trans, tree_root, path);
10621 if (ret)
b74639ca 10622 goto out;
b3b4aa74 10623 btrfs_release_path(path);
0af3d00b
JB
10624 }
10625
0b246afa 10626 spin_lock(&fs_info->block_group_cache_lock);
1a40e23b 10627 rb_erase(&block_group->cache_node,
0b246afa 10628 &fs_info->block_group_cache_tree);
292cbd51 10629 RB_CLEAR_NODE(&block_group->cache_node);
a1897fdd 10630
b74639ca
FM
10631 /* Once for the block groups rbtree */
10632 btrfs_put_block_group(block_group);
10633
0b246afa
JM
10634 if (fs_info->first_logical_byte == block_group->key.objectid)
10635 fs_info->first_logical_byte = (u64)-1;
10636 spin_unlock(&fs_info->block_group_cache_lock);
817d52f8 10637
80eb234a 10638 down_write(&block_group->space_info->groups_sem);
44fb5511
CM
10639 /*
10640 * we must use list_del_init so people can check to see if they
10641 * are still on the list after taking the semaphore
10642 */
10643 list_del_init(&block_group->list);
6ab0a202 10644 if (list_empty(&block_group->space_info->block_groups[index])) {
c1895442
JM
10645 kobj = block_group->space_info->block_group_kobjs[index];
10646 block_group->space_info->block_group_kobjs[index] = NULL;
0b246afa 10647 clear_avail_alloc_bits(fs_info, block_group->flags);
6ab0a202 10648 }
80eb234a 10649 up_write(&block_group->space_info->groups_sem);
c1895442
JM
10650 if (kobj) {
10651 kobject_del(kobj);
10652 kobject_put(kobj);
10653 }
1a40e23b 10654
4f69cb98
FM
10655 if (block_group->has_caching_ctl)
10656 caching_ctl = get_caching_control(block_group);
817d52f8 10657 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 10658 wait_block_group_cache_done(block_group);
4f69cb98 10659 if (block_group->has_caching_ctl) {
0b246afa 10660 down_write(&fs_info->commit_root_sem);
4f69cb98
FM
10661 if (!caching_ctl) {
10662 struct btrfs_caching_control *ctl;
10663
10664 list_for_each_entry(ctl,
0b246afa 10665 &fs_info->caching_block_groups, list)
4f69cb98
FM
10666 if (ctl->block_group == block_group) {
10667 caching_ctl = ctl;
1e4f4714 10668 refcount_inc(&caching_ctl->count);
4f69cb98
FM
10669 break;
10670 }
10671 }
10672 if (caching_ctl)
10673 list_del_init(&caching_ctl->list);
0b246afa 10674 up_write(&fs_info->commit_root_sem);
4f69cb98
FM
10675 if (caching_ctl) {
10676 /* Once for the caching bgs list and once for us. */
10677 put_caching_control(caching_ctl);
10678 put_caching_control(caching_ctl);
10679 }
10680 }
817d52f8 10681
ce93ec54
JB
10682 spin_lock(&trans->transaction->dirty_bgs_lock);
10683 if (!list_empty(&block_group->dirty_list)) {
1bbc621e
CM
10684 WARN_ON(1);
10685 }
10686 if (!list_empty(&block_group->io_list)) {
10687 WARN_ON(1);
ce93ec54
JB
10688 }
10689 spin_unlock(&trans->transaction->dirty_bgs_lock);
817d52f8
JB
10690 btrfs_remove_free_space_cache(block_group);
10691
c146afad 10692 spin_lock(&block_group->space_info->lock);
75c68e9f 10693 list_del_init(&block_group->ro_list);
18d018ad 10694
0b246afa 10695 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
18d018ad
ZL
10696 WARN_ON(block_group->space_info->total_bytes
10697 < block_group->key.offset);
10698 WARN_ON(block_group->space_info->bytes_readonly
10699 < block_group->key.offset);
10700 WARN_ON(block_group->space_info->disk_total
10701 < block_group->key.offset * factor);
10702 }
c146afad
YZ
10703 block_group->space_info->total_bytes -= block_group->key.offset;
10704 block_group->space_info->bytes_readonly -= block_group->key.offset;
89a55897 10705 block_group->space_info->disk_total -= block_group->key.offset * factor;
18d018ad 10706
c146afad 10707 spin_unlock(&block_group->space_info->lock);
283bb197 10708
0af3d00b
JB
10709 memcpy(&key, &block_group->key, sizeof(key));
10710
34441361 10711 mutex_lock(&fs_info->chunk_mutex);
495e64f4
FM
10712 if (!list_empty(&em->list)) {
10713 /* We're in the transaction->pending_chunks list. */
10714 free_extent_map(em);
10715 }
04216820
FM
10716 spin_lock(&block_group->lock);
10717 block_group->removed = 1;
10718 /*
10719 * At this point trimming can't start on this block group, because we
10720 * removed the block group from the tree fs_info->block_group_cache_tree
10721 * so no one can't find it anymore and even if someone already got this
10722 * block group before we removed it from the rbtree, they have already
10723 * incremented block_group->trimming - if they didn't, they won't find
10724 * any free space entries because we already removed them all when we
10725 * called btrfs_remove_free_space_cache().
10726 *
10727 * And we must not remove the extent map from the fs_info->mapping_tree
10728 * to prevent the same logical address range and physical device space
10729 * ranges from being reused for a new block group. This is because our
10730 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10731 * completely transactionless, so while it is trimming a range the
10732 * currently running transaction might finish and a new one start,
10733 * allowing for new block groups to be created that can reuse the same
10734 * physical device locations unless we take this special care.
e33e17ee
JM
10735 *
10736 * There may also be an implicit trim operation if the file system
10737 * is mounted with -odiscard. The same protections must remain
10738 * in place until the extents have been discarded completely when
10739 * the transaction commit has completed.
04216820
FM
10740 */
10741 remove_em = (atomic_read(&block_group->trimming) == 0);
10742 /*
10743 * Make sure a trimmer task always sees the em in the pinned_chunks list
10744 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10745 * before checking block_group->removed).
10746 */
10747 if (!remove_em) {
10748 /*
10749 * Our em might be in trans->transaction->pending_chunks which
10750 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10751 * and so is the fs_info->pinned_chunks list.
10752 *
10753 * So at this point we must be holding the chunk_mutex to avoid
10754 * any races with chunk allocation (more specifically at
10755 * volumes.c:contains_pending_extent()), to ensure it always
10756 * sees the em, either in the pending_chunks list or in the
10757 * pinned_chunks list.
10758 */
0b246afa 10759 list_move_tail(&em->list, &fs_info->pinned_chunks);
04216820
FM
10760 }
10761 spin_unlock(&block_group->lock);
04216820
FM
10762
10763 if (remove_em) {
10764 struct extent_map_tree *em_tree;
10765
0b246afa 10766 em_tree = &fs_info->mapping_tree.map_tree;
04216820 10767 write_lock(&em_tree->lock);
8dbcd10f
FM
10768 /*
10769 * The em might be in the pending_chunks list, so make sure the
10770 * chunk mutex is locked, since remove_extent_mapping() will
10771 * delete us from that list.
10772 */
04216820
FM
10773 remove_extent_mapping(em_tree, em);
10774 write_unlock(&em_tree->lock);
10775 /* once for the tree */
10776 free_extent_map(em);
10777 }
10778
34441361 10779 mutex_unlock(&fs_info->chunk_mutex);
8dbcd10f 10780
0b246afa 10781 ret = remove_block_group_free_space(trans, fs_info, block_group);
1e144fb8 10782 if (ret)
b74639ca 10783 goto out;
1a40e23b
ZY
10784
10785 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10786 if (ret > 0)
10787 ret = -EIO;
10788 if (ret < 0)
10789 goto out;
10790
10791 ret = btrfs_del_item(trans, root, path);
4f7ade41 10792
b74639ca 10793out:
4f7ade41
XY
10794 /* Once for the lookup reference */
10795 btrfs_put_block_group(block_group);
1a40e23b
ZY
10796 btrfs_free_path(path);
10797 return ret;
10798}
acce952b 10799
8eab77ff 10800struct btrfs_trans_handle *
7fd01182
FM
10801btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10802 const u64 chunk_offset)
8eab77ff 10803{
7fd01182
FM
10804 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10805 struct extent_map *em;
10806 struct map_lookup *map;
10807 unsigned int num_items;
10808
10809 read_lock(&em_tree->lock);
10810 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10811 read_unlock(&em_tree->lock);
10812 ASSERT(em && em->start == chunk_offset);
10813
8eab77ff 10814 /*
7fd01182
FM
10815 * We need to reserve 3 + N units from the metadata space info in order
10816 * to remove a block group (done at btrfs_remove_chunk() and at
10817 * btrfs_remove_block_group()), which are used for:
10818 *
8eab77ff
FM
10819 * 1 unit for adding the free space inode's orphan (located in the tree
10820 * of tree roots).
7fd01182
FM
10821 * 1 unit for deleting the block group item (located in the extent
10822 * tree).
10823 * 1 unit for deleting the free space item (located in tree of tree
10824 * roots).
10825 * N units for deleting N device extent items corresponding to each
10826 * stripe (located in the device tree).
10827 *
10828 * In order to remove a block group we also need to reserve units in the
10829 * system space info in order to update the chunk tree (update one or
10830 * more device items and remove one chunk item), but this is done at
10831 * btrfs_remove_chunk() through a call to check_system_chunk().
8eab77ff 10832 */
95617d69 10833 map = em->map_lookup;
7fd01182
FM
10834 num_items = 3 + map->num_stripes;
10835 free_extent_map(em);
10836
8eab77ff 10837 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
7fd01182 10838 num_items, 1);
8eab77ff
FM
10839}
10840
47ab2a6c
JB
10841/*
10842 * Process the unused_bgs list and remove any that don't have any allocated
10843 * space inside of them.
10844 */
10845void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10846{
10847 struct btrfs_block_group_cache *block_group;
10848 struct btrfs_space_info *space_info;
47ab2a6c
JB
10849 struct btrfs_trans_handle *trans;
10850 int ret = 0;
10851
afcdd129 10852 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
47ab2a6c
JB
10853 return;
10854
10855 spin_lock(&fs_info->unused_bgs_lock);
10856 while (!list_empty(&fs_info->unused_bgs)) {
10857 u64 start, end;
e33e17ee 10858 int trimming;
47ab2a6c
JB
10859
10860 block_group = list_first_entry(&fs_info->unused_bgs,
10861 struct btrfs_block_group_cache,
10862 bg_list);
47ab2a6c 10863 list_del_init(&block_group->bg_list);
aefbe9a6
ZL
10864
10865 space_info = block_group->space_info;
10866
47ab2a6c
JB
10867 if (ret || btrfs_mixed_space_info(space_info)) {
10868 btrfs_put_block_group(block_group);
10869 continue;
10870 }
10871 spin_unlock(&fs_info->unused_bgs_lock);
10872
d5f2e33b 10873 mutex_lock(&fs_info->delete_unused_bgs_mutex);
67c5e7d4 10874
47ab2a6c
JB
10875 /* Don't want to race with allocators so take the groups_sem */
10876 down_write(&space_info->groups_sem);
10877 spin_lock(&block_group->lock);
33f4c5c6 10878 if (block_group->reserved || block_group->pinned ||
47ab2a6c 10879 btrfs_block_group_used(&block_group->item) ||
19c4d2f9 10880 block_group->ro ||
aefbe9a6 10881 list_is_singular(&block_group->list)) {
47ab2a6c
JB
10882 /*
10883 * We want to bail if we made new allocations or have
10884 * outstanding allocations in this block group. We do
10885 * the ro check in case balance is currently acting on
10886 * this block group.
10887 */
10888 spin_unlock(&block_group->lock);
10889 up_write(&space_info->groups_sem);
10890 goto next;
10891 }
10892 spin_unlock(&block_group->lock);
10893
10894 /* We don't want to force the issue, only flip if it's ok. */
868f401a 10895 ret = inc_block_group_ro(block_group, 0);
47ab2a6c
JB
10896 up_write(&space_info->groups_sem);
10897 if (ret < 0) {
10898 ret = 0;
10899 goto next;
10900 }
10901
10902 /*
10903 * Want to do this before we do anything else so we can recover
10904 * properly if we fail to join the transaction.
10905 */
7fd01182
FM
10906 trans = btrfs_start_trans_remove_block_group(fs_info,
10907 block_group->key.objectid);
47ab2a6c 10908 if (IS_ERR(trans)) {
2ff7e61e 10909 btrfs_dec_block_group_ro(block_group);
47ab2a6c
JB
10910 ret = PTR_ERR(trans);
10911 goto next;
10912 }
10913
10914 /*
10915 * We could have pending pinned extents for this block group,
10916 * just delete them, we don't care about them anymore.
10917 */
10918 start = block_group->key.objectid;
10919 end = start + block_group->key.offset - 1;
d4b450cd
FM
10920 /*
10921 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10922 * btrfs_finish_extent_commit(). If we are at transaction N,
10923 * another task might be running finish_extent_commit() for the
10924 * previous transaction N - 1, and have seen a range belonging
10925 * to the block group in freed_extents[] before we were able to
10926 * clear the whole block group range from freed_extents[]. This
10927 * means that task can lookup for the block group after we
10928 * unpinned it from freed_extents[] and removed it, leading to
10929 * a BUG_ON() at btrfs_unpin_extent_range().
10930 */
10931 mutex_lock(&fs_info->unused_bg_unpin_mutex);
758eb51e 10932 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
91166212 10933 EXTENT_DIRTY);
758eb51e 10934 if (ret) {
d4b450cd 10935 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2ff7e61e 10936 btrfs_dec_block_group_ro(block_group);
758eb51e
FM
10937 goto end_trans;
10938 }
10939 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
91166212 10940 EXTENT_DIRTY);
758eb51e 10941 if (ret) {
d4b450cd 10942 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2ff7e61e 10943 btrfs_dec_block_group_ro(block_group);
758eb51e
FM
10944 goto end_trans;
10945 }
d4b450cd 10946 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
47ab2a6c
JB
10947
10948 /* Reset pinned so btrfs_put_block_group doesn't complain */
c30666d4
ZL
10949 spin_lock(&space_info->lock);
10950 spin_lock(&block_group->lock);
10951
10952 space_info->bytes_pinned -= block_group->pinned;
10953 space_info->bytes_readonly += block_group->pinned;
10954 percpu_counter_add(&space_info->total_bytes_pinned,
10955 -block_group->pinned);
47ab2a6c
JB
10956 block_group->pinned = 0;
10957
c30666d4
ZL
10958 spin_unlock(&block_group->lock);
10959 spin_unlock(&space_info->lock);
10960
e33e17ee 10961 /* DISCARD can flip during remount */
0b246afa 10962 trimming = btrfs_test_opt(fs_info, DISCARD);
e33e17ee
JM
10963
10964 /* Implicit trim during transaction commit. */
10965 if (trimming)
10966 btrfs_get_block_group_trimming(block_group);
10967
47ab2a6c
JB
10968 /*
10969 * Btrfs_remove_chunk will abort the transaction if things go
10970 * horribly wrong.
10971 */
5b4aacef 10972 ret = btrfs_remove_chunk(trans, fs_info,
47ab2a6c 10973 block_group->key.objectid);
e33e17ee
JM
10974
10975 if (ret) {
10976 if (trimming)
10977 btrfs_put_block_group_trimming(block_group);
10978 goto end_trans;
10979 }
10980
10981 /*
10982 * If we're not mounted with -odiscard, we can just forget
10983 * about this block group. Otherwise we'll need to wait
10984 * until transaction commit to do the actual discard.
10985 */
10986 if (trimming) {
348a0013
FM
10987 spin_lock(&fs_info->unused_bgs_lock);
10988 /*
10989 * A concurrent scrub might have added us to the list
10990 * fs_info->unused_bgs, so use a list_move operation
10991 * to add the block group to the deleted_bgs list.
10992 */
e33e17ee
JM
10993 list_move(&block_group->bg_list,
10994 &trans->transaction->deleted_bgs);
348a0013 10995 spin_unlock(&fs_info->unused_bgs_lock);
e33e17ee
JM
10996 btrfs_get_block_group(block_group);
10997 }
758eb51e 10998end_trans:
3a45bb20 10999 btrfs_end_transaction(trans);
47ab2a6c 11000next:
d5f2e33b 11001 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
47ab2a6c
JB
11002 btrfs_put_block_group(block_group);
11003 spin_lock(&fs_info->unused_bgs_lock);
11004 }
11005 spin_unlock(&fs_info->unused_bgs_lock);
11006}
11007
c59021f8 11008int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
11009{
11010 struct btrfs_space_info *space_info;
1aba86d6 11011 struct btrfs_super_block *disk_super;
11012 u64 features;
11013 u64 flags;
11014 int mixed = 0;
c59021f8 11015 int ret;
11016
6c41761f 11017 disk_super = fs_info->super_copy;
1aba86d6 11018 if (!btrfs_super_root(disk_super))
0dc924c5 11019 return -EINVAL;
c59021f8 11020
1aba86d6 11021 features = btrfs_super_incompat_flags(disk_super);
11022 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
11023 mixed = 1;
c59021f8 11024
1aba86d6 11025 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2be12ef7 11026 ret = create_space_info(fs_info, flags, &space_info);
c59021f8 11027 if (ret)
1aba86d6 11028 goto out;
c59021f8 11029
1aba86d6 11030 if (mixed) {
11031 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
2be12ef7 11032 ret = create_space_info(fs_info, flags, &space_info);
1aba86d6 11033 } else {
11034 flags = BTRFS_BLOCK_GROUP_METADATA;
2be12ef7 11035 ret = create_space_info(fs_info, flags, &space_info);
1aba86d6 11036 if (ret)
11037 goto out;
11038
11039 flags = BTRFS_BLOCK_GROUP_DATA;
2be12ef7 11040 ret = create_space_info(fs_info, flags, &space_info);
1aba86d6 11041 }
11042out:
c59021f8 11043 return ret;
11044}
11045
2ff7e61e
JM
11046int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
11047 u64 start, u64 end)
acce952b 11048{
2ff7e61e 11049 return unpin_extent_range(fs_info, start, end, false);
acce952b 11050}
11051
499f377f
JM
11052/*
11053 * It used to be that old block groups would be left around forever.
11054 * Iterating over them would be enough to trim unused space. Since we
11055 * now automatically remove them, we also need to iterate over unallocated
11056 * space.
11057 *
11058 * We don't want a transaction for this since the discard may take a
11059 * substantial amount of time. We don't require that a transaction be
11060 * running, but we do need to take a running transaction into account
11061 * to ensure that we're not discarding chunks that were released in
11062 * the current transaction.
11063 *
11064 * Holding the chunks lock will prevent other threads from allocating
11065 * or releasing chunks, but it won't prevent a running transaction
11066 * from committing and releasing the memory that the pending chunks
11067 * list head uses. For that, we need to take a reference to the
11068 * transaction.
11069 */
11070static int btrfs_trim_free_extents(struct btrfs_device *device,
6250c25a 11071 u64 minlen, u64 *trimmed)
499f377f 11072{
6250c25a 11073 u64 start = 0, len = 0;
499f377f
JM
11074 int ret;
11075
11076 *trimmed = 0;
11077
da05e937
JM
11078 /* Discard not supported = nothing to do. */
11079 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
11080 return 0;
11081
499f377f
JM
11082 /* Not writeable = nothing to do. */
11083 if (!device->writeable)
11084 return 0;
11085
11086 /* No free space = nothing to do. */
11087 if (device->total_bytes <= device->bytes_used)
11088 return 0;
11089
11090 ret = 0;
11091
11092 while (1) {
fb456252 11093 struct btrfs_fs_info *fs_info = device->fs_info;
499f377f
JM
11094 struct btrfs_transaction *trans;
11095 u64 bytes;
11096
11097 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
11098 if (ret)
11099 return ret;
11100
11101 down_read(&fs_info->commit_root_sem);
11102
11103 spin_lock(&fs_info->trans_lock);
11104 trans = fs_info->running_transaction;
11105 if (trans)
9b64f57d 11106 refcount_inc(&trans->use_count);
499f377f
JM
11107 spin_unlock(&fs_info->trans_lock);
11108
6250c25a
DS
11109 ret = find_free_dev_extent_start(trans, device, minlen, start,
11110 &start, &len);
499f377f
JM
11111 if (trans)
11112 btrfs_put_transaction(trans);
11113
11114 if (ret) {
11115 up_read(&fs_info->commit_root_sem);
11116 mutex_unlock(&fs_info->chunk_mutex);
11117 if (ret == -ENOSPC)
11118 ret = 0;
11119 break;
11120 }
11121
11122 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
11123 up_read(&fs_info->commit_root_sem);
11124 mutex_unlock(&fs_info->chunk_mutex);
11125
11126 if (ret)
11127 break;
11128
11129 start += len;
11130 *trimmed += bytes;
11131
11132 if (fatal_signal_pending(current)) {
11133 ret = -ERESTARTSYS;
11134 break;
11135 }
11136
11137 cond_resched();
11138 }
11139
11140 return ret;
11141}
11142
7b23644c
QW
11143/*
11144 * Trim the whole filesystem by:
11145 * 1) trimming the free space in each block group
11146 * 2) trimming the unallocated space on each device
11147 *
11148 * This will also continue trimming even if a block group or device encounters
11149 * an error. The return value will be the last error, or 0 if nothing bad
11150 * happens.
11151 */
2ff7e61e 11152int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
f7039b1d 11153{
f7039b1d 11154 struct btrfs_block_group_cache *cache = NULL;
499f377f
JM
11155 struct btrfs_device *device;
11156 struct list_head *devices;
f7039b1d
LD
11157 u64 group_trimmed;
11158 u64 start;
11159 u64 end;
11160 u64 trimmed = 0;
7b23644c
QW
11161 u64 bg_failed = 0;
11162 u64 dev_failed = 0;
11163 int bg_ret = 0;
11164 int dev_ret = 0;
f7039b1d
LD
11165 int ret = 0;
11166
2fdb337b 11167 cache = btrfs_lookup_first_block_group(fs_info, range->start);
7b23644c 11168 for (; cache; cache = next_block_group(fs_info, cache)) {
f7039b1d
LD
11169 if (cache->key.objectid >= (range->start + range->len)) {
11170 btrfs_put_block_group(cache);
11171 break;
11172 }
11173
11174 start = max(range->start, cache->key.objectid);
11175 end = min(range->start + range->len,
11176 cache->key.objectid + cache->key.offset);
11177
11178 if (end - start >= range->minlen) {
11179 if (!block_group_cache_done(cache)) {
f6373bf3 11180 ret = cache_block_group(cache, 0);
1be41b78 11181 if (ret) {
7b23644c
QW
11182 bg_failed++;
11183 bg_ret = ret;
11184 continue;
1be41b78
JB
11185 }
11186 ret = wait_block_group_cache_done(cache);
11187 if (ret) {
7b23644c
QW
11188 bg_failed++;
11189 bg_ret = ret;
11190 continue;
1be41b78 11191 }
f7039b1d
LD
11192 }
11193 ret = btrfs_trim_block_group(cache,
11194 &group_trimmed,
11195 start,
11196 end,
11197 range->minlen);
11198
11199 trimmed += group_trimmed;
11200 if (ret) {
7b23644c
QW
11201 bg_failed++;
11202 bg_ret = ret;
11203 continue;
f7039b1d
LD
11204 }
11205 }
f7039b1d
LD
11206 }
11207
7b23644c
QW
11208 if (bg_failed)
11209 btrfs_warn(fs_info,
11210 "failed to trim %llu block group(s), last error %d",
11211 bg_failed, bg_ret);
0b246afa 11212 mutex_lock(&fs_info->fs_devices->device_list_mutex);
a7d24c89
JM
11213 devices = &fs_info->fs_devices->devices;
11214 list_for_each_entry(device, devices, dev_list) {
6250c25a
DS
11215 ret = btrfs_trim_free_extents(device, range->minlen,
11216 &group_trimmed);
7b23644c
QW
11217 if (ret) {
11218 dev_failed++;
11219 dev_ret = ret;
499f377f 11220 break;
7b23644c 11221 }
499f377f
JM
11222
11223 trimmed += group_trimmed;
11224 }
0b246afa 11225 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
499f377f 11226
7b23644c
QW
11227 if (dev_failed)
11228 btrfs_warn(fs_info,
11229 "failed to trim %llu device(s), last error %d",
11230 dev_failed, dev_ret);
f7039b1d 11231 range->len = trimmed;
7b23644c
QW
11232 if (bg_ret)
11233 return bg_ret;
11234 return dev_ret;
f7039b1d 11235}
8257b2dc
MX
11236
11237/*
ea14b57f 11238 * btrfs_{start,end}_write_no_snapshotting() are similar to
9ea24bbe
FM
11239 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
11240 * data into the page cache through nocow before the subvolume is snapshoted,
11241 * but flush the data into disk after the snapshot creation, or to prevent
ea14b57f 11242 * operations while snapshotting is ongoing and that cause the snapshot to be
9ea24bbe 11243 * inconsistent (writes followed by expanding truncates for example).
8257b2dc 11244 */
ea14b57f 11245void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
8257b2dc
MX
11246{
11247 percpu_counter_dec(&root->subv_writers->counter);
11248 /*
a83342aa 11249 * Make sure counter is updated before we wake up waiters.
8257b2dc
MX
11250 */
11251 smp_mb();
11252 if (waitqueue_active(&root->subv_writers->wait))
11253 wake_up(&root->subv_writers->wait);
11254}
11255
ea14b57f 11256int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
8257b2dc 11257{
ea14b57f 11258 if (atomic_read(&root->will_be_snapshotted))
8257b2dc
MX
11259 return 0;
11260
11261 percpu_counter_inc(&root->subv_writers->counter);
11262 /*
11263 * Make sure counter is updated before we check for snapshot creation.
11264 */
11265 smp_mb();
ea14b57f
DS
11266 if (atomic_read(&root->will_be_snapshotted)) {
11267 btrfs_end_write_no_snapshotting(root);
8257b2dc
MX
11268 return 0;
11269 }
11270 return 1;
11271}
0bc19f90 11272
ea14b57f 11273static int wait_snapshotting_atomic_t(atomic_t *a)
0bc19f90
ZL
11274{
11275 schedule();
11276 return 0;
11277}
11278
11279void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11280{
11281 while (true) {
11282 int ret;
11283
ea14b57f 11284 ret = btrfs_start_write_no_snapshotting(root);
0bc19f90
ZL
11285 if (ret)
11286 break;
ea14b57f
DS
11287 wait_on_atomic_t(&root->will_be_snapshotted,
11288 wait_snapshotting_atomic_t,
0bc19f90
ZL
11289 TASK_UNINTERRUPTIBLE);
11290 }
11291}