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