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