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