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