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