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