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