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