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