]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - fs/btrfs/extent-tree.c
d0c5d5d92d1cea0d0ada8cdf764bc251c343f354
[mirror_ubuntu-artful-kernel.git] / fs / btrfs / extent-tree.c
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 */
18 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include <linux/rcupdate.h>
24 #include <linux/kthread.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/percpu_counter.h>
28 #include "hash.h"
29 #include "tree-log.h"
30 #include "disk-io.h"
31 #include "print-tree.h"
32 #include "volumes.h"
33 #include "raid56.h"
34 #include "locking.h"
35 #include "free-space-cache.h"
36 #include "free-space-tree.h"
37 #include "math.h"
38 #include "sysfs.h"
39 #include "qgroup.h"
40
41 #undef SCRAMBLE_DELAYED_REFS
42
43 /*
44 * control flags for do_chunk_alloc's force field
45 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
46 * if we really need one.
47 *
48 * CHUNK_ALLOC_LIMITED means to only try and allocate one
49 * if we have very few chunks already allocated. This is
50 * used as part of the clustering code to help make sure
51 * we have a good pool of storage to cluster in, without
52 * filling the FS with empty chunks
53 *
54 * CHUNK_ALLOC_FORCE means it must try to allocate one
55 *
56 */
57 enum {
58 CHUNK_ALLOC_NO_FORCE = 0,
59 CHUNK_ALLOC_LIMITED = 1,
60 CHUNK_ALLOC_FORCE = 2,
61 };
62
63 static int update_block_group(struct btrfs_trans_handle *trans,
64 struct btrfs_fs_info *fs_info, u64 bytenr,
65 u64 num_bytes, int alloc);
66 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
67 struct btrfs_root *root,
68 struct btrfs_delayed_ref_node *node, u64 parent,
69 u64 root_objectid, u64 owner_objectid,
70 u64 owner_offset, int refs_to_drop,
71 struct btrfs_delayed_extent_op *extra_op);
72 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
73 struct extent_buffer *leaf,
74 struct btrfs_extent_item *ei);
75 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
76 struct btrfs_root *root,
77 u64 parent, u64 root_objectid,
78 u64 flags, u64 owner, u64 offset,
79 struct btrfs_key *ins, int ref_mod);
80 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
81 struct btrfs_root *root,
82 u64 parent, u64 root_objectid,
83 u64 flags, struct btrfs_disk_key *key,
84 int level, struct btrfs_key *ins);
85 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
86 struct btrfs_root *extent_root, u64 flags,
87 int force);
88 static int find_next_key(struct btrfs_path *path, int level,
89 struct btrfs_key *key);
90 static void dump_space_info(struct btrfs_fs_info *fs_info,
91 struct btrfs_space_info *info, u64 bytes,
92 int dump_block_groups);
93 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
94 u64 ram_bytes, u64 num_bytes, int delalloc);
95 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
96 u64 num_bytes, int delalloc);
97 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
98 u64 num_bytes);
99 int btrfs_pin_extent(struct btrfs_root *root,
100 u64 bytenr, u64 num_bytes, int reserved);
101 static int __reserve_metadata_bytes(struct btrfs_root *root,
102 struct btrfs_space_info *space_info,
103 u64 orig_bytes,
104 enum btrfs_reserve_flush_enum flush);
105 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
106 struct btrfs_space_info *space_info,
107 u64 num_bytes);
108 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
109 struct btrfs_space_info *space_info,
110 u64 num_bytes);
111
112 static noinline int
113 block_group_cache_done(struct btrfs_block_group_cache *cache)
114 {
115 smp_mb();
116 return cache->cached == BTRFS_CACHE_FINISHED ||
117 cache->cached == BTRFS_CACHE_ERROR;
118 }
119
120 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
121 {
122 return (cache->flags & bits) == bits;
123 }
124
125 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
126 {
127 atomic_inc(&cache->count);
128 }
129
130 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
131 {
132 if (atomic_dec_and_test(&cache->count)) {
133 WARN_ON(cache->pinned > 0);
134 WARN_ON(cache->reserved > 0);
135 kfree(cache->free_space_ctl);
136 kfree(cache);
137 }
138 }
139
140 /*
141 * this adds the block group to the fs_info rb tree for the block group
142 * cache
143 */
144 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
145 struct btrfs_block_group_cache *block_group)
146 {
147 struct rb_node **p;
148 struct rb_node *parent = NULL;
149 struct btrfs_block_group_cache *cache;
150
151 spin_lock(&info->block_group_cache_lock);
152 p = &info->block_group_cache_tree.rb_node;
153
154 while (*p) {
155 parent = *p;
156 cache = rb_entry(parent, struct btrfs_block_group_cache,
157 cache_node);
158 if (block_group->key.objectid < cache->key.objectid) {
159 p = &(*p)->rb_left;
160 } else if (block_group->key.objectid > cache->key.objectid) {
161 p = &(*p)->rb_right;
162 } else {
163 spin_unlock(&info->block_group_cache_lock);
164 return -EEXIST;
165 }
166 }
167
168 rb_link_node(&block_group->cache_node, parent, p);
169 rb_insert_color(&block_group->cache_node,
170 &info->block_group_cache_tree);
171
172 if (info->first_logical_byte > block_group->key.objectid)
173 info->first_logical_byte = block_group->key.objectid;
174
175 spin_unlock(&info->block_group_cache_lock);
176
177 return 0;
178 }
179
180 /*
181 * This will return the block group at or after bytenr if contains is 0, else
182 * it will return the block group that contains the bytenr
183 */
184 static struct btrfs_block_group_cache *
185 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
186 int contains)
187 {
188 struct btrfs_block_group_cache *cache, *ret = NULL;
189 struct rb_node *n;
190 u64 end, start;
191
192 spin_lock(&info->block_group_cache_lock);
193 n = info->block_group_cache_tree.rb_node;
194
195 while (n) {
196 cache = rb_entry(n, struct btrfs_block_group_cache,
197 cache_node);
198 end = cache->key.objectid + cache->key.offset - 1;
199 start = cache->key.objectid;
200
201 if (bytenr < start) {
202 if (!contains && (!ret || start < ret->key.objectid))
203 ret = cache;
204 n = n->rb_left;
205 } else if (bytenr > start) {
206 if (contains && bytenr <= end) {
207 ret = cache;
208 break;
209 }
210 n = n->rb_right;
211 } else {
212 ret = cache;
213 break;
214 }
215 }
216 if (ret) {
217 btrfs_get_block_group(ret);
218 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
219 info->first_logical_byte = ret->key.objectid;
220 }
221 spin_unlock(&info->block_group_cache_lock);
222
223 return ret;
224 }
225
226 static int add_excluded_extent(struct btrfs_root *root,
227 u64 start, u64 num_bytes)
228 {
229 struct btrfs_fs_info *fs_info = root->fs_info;
230 u64 end = start + num_bytes - 1;
231 set_extent_bits(&fs_info->freed_extents[0],
232 start, end, EXTENT_UPTODATE);
233 set_extent_bits(&fs_info->freed_extents[1],
234 start, end, EXTENT_UPTODATE);
235 return 0;
236 }
237
238 static void free_excluded_extents(struct btrfs_root *root,
239 struct btrfs_block_group_cache *cache)
240 {
241 struct btrfs_fs_info *fs_info = root->fs_info;
242 u64 start, end;
243
244 start = cache->key.objectid;
245 end = start + cache->key.offset - 1;
246
247 clear_extent_bits(&fs_info->freed_extents[0],
248 start, end, EXTENT_UPTODATE);
249 clear_extent_bits(&fs_info->freed_extents[1],
250 start, end, EXTENT_UPTODATE);
251 }
252
253 static int exclude_super_stripes(struct btrfs_root *root,
254 struct btrfs_block_group_cache *cache)
255 {
256 struct btrfs_fs_info *fs_info = root->fs_info;
257 u64 bytenr;
258 u64 *logical;
259 int stripe_len;
260 int i, nr, ret;
261
262 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
263 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
264 cache->bytes_super += stripe_len;
265 ret = add_excluded_extent(root, cache->key.objectid,
266 stripe_len);
267 if (ret)
268 return ret;
269 }
270
271 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
272 bytenr = btrfs_sb_offset(i);
273 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
274 bytenr, 0, &logical, &nr, &stripe_len);
275 if (ret)
276 return ret;
277
278 while (nr--) {
279 u64 start, len;
280
281 if (logical[nr] > cache->key.objectid +
282 cache->key.offset)
283 continue;
284
285 if (logical[nr] + stripe_len <= cache->key.objectid)
286 continue;
287
288 start = logical[nr];
289 if (start < cache->key.objectid) {
290 start = cache->key.objectid;
291 len = (logical[nr] + stripe_len) - start;
292 } else {
293 len = min_t(u64, stripe_len,
294 cache->key.objectid +
295 cache->key.offset - start);
296 }
297
298 cache->bytes_super += len;
299 ret = add_excluded_extent(root, start, len);
300 if (ret) {
301 kfree(logical);
302 return ret;
303 }
304 }
305
306 kfree(logical);
307 }
308 return 0;
309 }
310
311 static struct btrfs_caching_control *
312 get_caching_control(struct btrfs_block_group_cache *cache)
313 {
314 struct btrfs_caching_control *ctl;
315
316 spin_lock(&cache->lock);
317 if (!cache->caching_ctl) {
318 spin_unlock(&cache->lock);
319 return NULL;
320 }
321
322 ctl = cache->caching_ctl;
323 atomic_inc(&ctl->count);
324 spin_unlock(&cache->lock);
325 return ctl;
326 }
327
328 static void put_caching_control(struct btrfs_caching_control *ctl)
329 {
330 if (atomic_dec_and_test(&ctl->count))
331 kfree(ctl);
332 }
333
334 #ifdef CONFIG_BTRFS_DEBUG
335 static void fragment_free_space(struct btrfs_root *root,
336 struct btrfs_block_group_cache *block_group)
337 {
338 struct btrfs_fs_info *fs_info = root->fs_info;
339
340 u64 start = block_group->key.objectid;
341 u64 len = block_group->key.offset;
342 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
343 fs_info->nodesize : fs_info->sectorsize;
344 u64 step = chunk << 1;
345
346 while (len > chunk) {
347 btrfs_remove_free_space(block_group, start, chunk);
348 start += step;
349 if (len < step)
350 len = 0;
351 else
352 len -= step;
353 }
354 }
355 #endif
356
357 /*
358 * this is only called by cache_block_group, since we could have freed extents
359 * we need to check the pinned_extents for any extents that can't be used yet
360 * since their free space will be released as soon as the transaction commits.
361 */
362 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
363 struct btrfs_fs_info *info, u64 start, u64 end)
364 {
365 u64 extent_start, extent_end, size, total_added = 0;
366 int ret;
367
368 while (start < end) {
369 ret = find_first_extent_bit(info->pinned_extents, start,
370 &extent_start, &extent_end,
371 EXTENT_DIRTY | EXTENT_UPTODATE,
372 NULL);
373 if (ret)
374 break;
375
376 if (extent_start <= start) {
377 start = extent_end + 1;
378 } else if (extent_start > start && extent_start < end) {
379 size = extent_start - start;
380 total_added += size;
381 ret = btrfs_add_free_space(block_group, start,
382 size);
383 BUG_ON(ret); /* -ENOMEM or logic error */
384 start = extent_end + 1;
385 } else {
386 break;
387 }
388 }
389
390 if (start < end) {
391 size = end - start;
392 total_added += size;
393 ret = btrfs_add_free_space(block_group, start, size);
394 BUG_ON(ret); /* -ENOMEM or logic error */
395 }
396
397 return total_added;
398 }
399
400 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
401 {
402 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
403 struct btrfs_fs_info *fs_info = block_group->fs_info;
404 struct btrfs_root *extent_root = fs_info->extent_root;
405 struct btrfs_path *path;
406 struct extent_buffer *leaf;
407 struct btrfs_key key;
408 u64 total_found = 0;
409 u64 last = 0;
410 u32 nritems;
411 int ret;
412 bool wakeup = true;
413
414 path = btrfs_alloc_path();
415 if (!path)
416 return -ENOMEM;
417
418 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
419
420 #ifdef CONFIG_BTRFS_DEBUG
421 /*
422 * If we're fragmenting we don't want to make anybody think we can
423 * allocate from this block group until we've had a chance to fragment
424 * the free space.
425 */
426 if (btrfs_should_fragment_free_space(extent_root, block_group))
427 wakeup = false;
428 #endif
429 /*
430 * We don't want to deadlock with somebody trying to allocate a new
431 * extent for the extent root while also trying to search the extent
432 * root to add free space. So we skip locking and search the commit
433 * root, since its read-only
434 */
435 path->skip_locking = 1;
436 path->search_commit_root = 1;
437 path->reada = READA_FORWARD;
438
439 key.objectid = last;
440 key.offset = 0;
441 key.type = BTRFS_EXTENT_ITEM_KEY;
442
443 next:
444 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
445 if (ret < 0)
446 goto out;
447
448 leaf = path->nodes[0];
449 nritems = btrfs_header_nritems(leaf);
450
451 while (1) {
452 if (btrfs_fs_closing(fs_info) > 1) {
453 last = (u64)-1;
454 break;
455 }
456
457 if (path->slots[0] < nritems) {
458 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
459 } else {
460 ret = find_next_key(path, 0, &key);
461 if (ret)
462 break;
463
464 if (need_resched() ||
465 rwsem_is_contended(&fs_info->commit_root_sem)) {
466 if (wakeup)
467 caching_ctl->progress = last;
468 btrfs_release_path(path);
469 up_read(&fs_info->commit_root_sem);
470 mutex_unlock(&caching_ctl->mutex);
471 cond_resched();
472 mutex_lock(&caching_ctl->mutex);
473 down_read(&fs_info->commit_root_sem);
474 goto next;
475 }
476
477 ret = btrfs_next_leaf(extent_root, path);
478 if (ret < 0)
479 goto out;
480 if (ret)
481 break;
482 leaf = path->nodes[0];
483 nritems = btrfs_header_nritems(leaf);
484 continue;
485 }
486
487 if (key.objectid < last) {
488 key.objectid = last;
489 key.offset = 0;
490 key.type = BTRFS_EXTENT_ITEM_KEY;
491
492 if (wakeup)
493 caching_ctl->progress = last;
494 btrfs_release_path(path);
495 goto next;
496 }
497
498 if (key.objectid < block_group->key.objectid) {
499 path->slots[0]++;
500 continue;
501 }
502
503 if (key.objectid >= block_group->key.objectid +
504 block_group->key.offset)
505 break;
506
507 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
508 key.type == BTRFS_METADATA_ITEM_KEY) {
509 total_found += add_new_free_space(block_group,
510 fs_info, last,
511 key.objectid);
512 if (key.type == BTRFS_METADATA_ITEM_KEY)
513 last = key.objectid +
514 fs_info->nodesize;
515 else
516 last = key.objectid + key.offset;
517
518 if (total_found > CACHING_CTL_WAKE_UP) {
519 total_found = 0;
520 if (wakeup)
521 wake_up(&caching_ctl->wait);
522 }
523 }
524 path->slots[0]++;
525 }
526 ret = 0;
527
528 total_found += add_new_free_space(block_group, fs_info, last,
529 block_group->key.objectid +
530 block_group->key.offset);
531 caching_ctl->progress = (u64)-1;
532
533 out:
534 btrfs_free_path(path);
535 return ret;
536 }
537
538 static noinline void caching_thread(struct btrfs_work *work)
539 {
540 struct btrfs_block_group_cache *block_group;
541 struct btrfs_fs_info *fs_info;
542 struct btrfs_caching_control *caching_ctl;
543 struct btrfs_root *extent_root;
544 int ret;
545
546 caching_ctl = container_of(work, struct btrfs_caching_control, work);
547 block_group = caching_ctl->block_group;
548 fs_info = block_group->fs_info;
549 extent_root = fs_info->extent_root;
550
551 mutex_lock(&caching_ctl->mutex);
552 down_read(&fs_info->commit_root_sem);
553
554 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
555 ret = load_free_space_tree(caching_ctl);
556 else
557 ret = load_extent_tree_free(caching_ctl);
558
559 spin_lock(&block_group->lock);
560 block_group->caching_ctl = NULL;
561 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
562 spin_unlock(&block_group->lock);
563
564 #ifdef CONFIG_BTRFS_DEBUG
565 if (btrfs_should_fragment_free_space(extent_root, block_group)) {
566 u64 bytes_used;
567
568 spin_lock(&block_group->space_info->lock);
569 spin_lock(&block_group->lock);
570 bytes_used = block_group->key.offset -
571 btrfs_block_group_used(&block_group->item);
572 block_group->space_info->bytes_used += bytes_used >> 1;
573 spin_unlock(&block_group->lock);
574 spin_unlock(&block_group->space_info->lock);
575 fragment_free_space(extent_root, block_group);
576 }
577 #endif
578
579 caching_ctl->progress = (u64)-1;
580
581 up_read(&fs_info->commit_root_sem);
582 free_excluded_extents(fs_info->extent_root, block_group);
583 mutex_unlock(&caching_ctl->mutex);
584
585 wake_up(&caching_ctl->wait);
586
587 put_caching_control(caching_ctl);
588 btrfs_put_block_group(block_group);
589 }
590
591 static int cache_block_group(struct btrfs_block_group_cache *cache,
592 int load_cache_only)
593 {
594 DEFINE_WAIT(wait);
595 struct btrfs_fs_info *fs_info = cache->fs_info;
596 struct btrfs_caching_control *caching_ctl;
597 int ret = 0;
598
599 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
600 if (!caching_ctl)
601 return -ENOMEM;
602
603 INIT_LIST_HEAD(&caching_ctl->list);
604 mutex_init(&caching_ctl->mutex);
605 init_waitqueue_head(&caching_ctl->wait);
606 caching_ctl->block_group = cache;
607 caching_ctl->progress = cache->key.objectid;
608 atomic_set(&caching_ctl->count, 1);
609 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
610 caching_thread, NULL, NULL);
611
612 spin_lock(&cache->lock);
613 /*
614 * This should be a rare occasion, but this could happen I think in the
615 * case where one thread starts to load the space cache info, and then
616 * some other thread starts a transaction commit which tries to do an
617 * allocation while the other thread is still loading the space cache
618 * info. The previous loop should have kept us from choosing this block
619 * group, but if we've moved to the state where we will wait on caching
620 * block groups we need to first check if we're doing a fast load here,
621 * so we can wait for it to finish, otherwise we could end up allocating
622 * from a block group who's cache gets evicted for one reason or
623 * another.
624 */
625 while (cache->cached == BTRFS_CACHE_FAST) {
626 struct btrfs_caching_control *ctl;
627
628 ctl = cache->caching_ctl;
629 atomic_inc(&ctl->count);
630 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
631 spin_unlock(&cache->lock);
632
633 schedule();
634
635 finish_wait(&ctl->wait, &wait);
636 put_caching_control(ctl);
637 spin_lock(&cache->lock);
638 }
639
640 if (cache->cached != BTRFS_CACHE_NO) {
641 spin_unlock(&cache->lock);
642 kfree(caching_ctl);
643 return 0;
644 }
645 WARN_ON(cache->caching_ctl);
646 cache->caching_ctl = caching_ctl;
647 cache->cached = BTRFS_CACHE_FAST;
648 spin_unlock(&cache->lock);
649
650 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
651 mutex_lock(&caching_ctl->mutex);
652 ret = load_free_space_cache(fs_info, cache);
653
654 spin_lock(&cache->lock);
655 if (ret == 1) {
656 cache->caching_ctl = NULL;
657 cache->cached = BTRFS_CACHE_FINISHED;
658 cache->last_byte_to_unpin = (u64)-1;
659 caching_ctl->progress = (u64)-1;
660 } else {
661 if (load_cache_only) {
662 cache->caching_ctl = NULL;
663 cache->cached = BTRFS_CACHE_NO;
664 } else {
665 cache->cached = BTRFS_CACHE_STARTED;
666 cache->has_caching_ctl = 1;
667 }
668 }
669 spin_unlock(&cache->lock);
670 #ifdef CONFIG_BTRFS_DEBUG
671 if (ret == 1 &&
672 btrfs_should_fragment_free_space(fs_info->extent_root,
673 cache)) {
674 u64 bytes_used;
675
676 spin_lock(&cache->space_info->lock);
677 spin_lock(&cache->lock);
678 bytes_used = cache->key.offset -
679 btrfs_block_group_used(&cache->item);
680 cache->space_info->bytes_used += bytes_used >> 1;
681 spin_unlock(&cache->lock);
682 spin_unlock(&cache->space_info->lock);
683 fragment_free_space(fs_info->extent_root, cache);
684 }
685 #endif
686 mutex_unlock(&caching_ctl->mutex);
687
688 wake_up(&caching_ctl->wait);
689 if (ret == 1) {
690 put_caching_control(caching_ctl);
691 free_excluded_extents(fs_info->extent_root, cache);
692 return 0;
693 }
694 } else {
695 /*
696 * We're either using the free space tree or no caching at all.
697 * Set cached to the appropriate value and wakeup any waiters.
698 */
699 spin_lock(&cache->lock);
700 if (load_cache_only) {
701 cache->caching_ctl = NULL;
702 cache->cached = BTRFS_CACHE_NO;
703 } else {
704 cache->cached = BTRFS_CACHE_STARTED;
705 cache->has_caching_ctl = 1;
706 }
707 spin_unlock(&cache->lock);
708 wake_up(&caching_ctl->wait);
709 }
710
711 if (load_cache_only) {
712 put_caching_control(caching_ctl);
713 return 0;
714 }
715
716 down_write(&fs_info->commit_root_sem);
717 atomic_inc(&caching_ctl->count);
718 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
719 up_write(&fs_info->commit_root_sem);
720
721 btrfs_get_block_group(cache);
722
723 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
724
725 return ret;
726 }
727
728 /*
729 * return the block group that starts at or after bytenr
730 */
731 static struct btrfs_block_group_cache *
732 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
733 {
734 return block_group_cache_tree_search(info, bytenr, 0);
735 }
736
737 /*
738 * return the block group that contains the given bytenr
739 */
740 struct btrfs_block_group_cache *btrfs_lookup_block_group(
741 struct btrfs_fs_info *info,
742 u64 bytenr)
743 {
744 return block_group_cache_tree_search(info, bytenr, 1);
745 }
746
747 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
748 u64 flags)
749 {
750 struct list_head *head = &info->space_info;
751 struct btrfs_space_info *found;
752
753 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
754
755 rcu_read_lock();
756 list_for_each_entry_rcu(found, head, list) {
757 if (found->flags & flags) {
758 rcu_read_unlock();
759 return found;
760 }
761 }
762 rcu_read_unlock();
763 return NULL;
764 }
765
766 /*
767 * after adding space to the filesystem, we need to clear the full flags
768 * on all the space infos.
769 */
770 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
771 {
772 struct list_head *head = &info->space_info;
773 struct btrfs_space_info *found;
774
775 rcu_read_lock();
776 list_for_each_entry_rcu(found, head, list)
777 found->full = 0;
778 rcu_read_unlock();
779 }
780
781 /* simple helper to search for an existing data extent at a given offset */
782 int btrfs_lookup_data_extent(struct btrfs_root *root, u64 start, u64 len)
783 {
784 struct btrfs_fs_info *fs_info = root->fs_info;
785 int ret;
786 struct btrfs_key key;
787 struct btrfs_path *path;
788
789 path = btrfs_alloc_path();
790 if (!path)
791 return -ENOMEM;
792
793 key.objectid = start;
794 key.offset = len;
795 key.type = BTRFS_EXTENT_ITEM_KEY;
796 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
797 btrfs_free_path(path);
798 return ret;
799 }
800
801 /*
802 * helper function to lookup reference count and flags of a tree block.
803 *
804 * the head node for delayed ref is used to store the sum of all the
805 * reference count modifications queued up in the rbtree. the head
806 * node may also store the extent flags to set. This way you can check
807 * to see what the reference count and extent flags would be if all of
808 * the delayed refs are not processed.
809 */
810 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
811 struct btrfs_root *root, u64 bytenr,
812 u64 offset, int metadata, u64 *refs, u64 *flags)
813 {
814 struct btrfs_fs_info *fs_info = root->fs_info;
815 struct btrfs_delayed_ref_head *head;
816 struct btrfs_delayed_ref_root *delayed_refs;
817 struct btrfs_path *path;
818 struct btrfs_extent_item *ei;
819 struct extent_buffer *leaf;
820 struct btrfs_key key;
821 u32 item_size;
822 u64 num_refs;
823 u64 extent_flags;
824 int ret;
825
826 /*
827 * If we don't have skinny metadata, don't bother doing anything
828 * different
829 */
830 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
831 offset = fs_info->nodesize;
832 metadata = 0;
833 }
834
835 path = btrfs_alloc_path();
836 if (!path)
837 return -ENOMEM;
838
839 if (!trans) {
840 path->skip_locking = 1;
841 path->search_commit_root = 1;
842 }
843
844 search_again:
845 key.objectid = bytenr;
846 key.offset = offset;
847 if (metadata)
848 key.type = BTRFS_METADATA_ITEM_KEY;
849 else
850 key.type = BTRFS_EXTENT_ITEM_KEY;
851
852 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
853 if (ret < 0)
854 goto out_free;
855
856 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
857 if (path->slots[0]) {
858 path->slots[0]--;
859 btrfs_item_key_to_cpu(path->nodes[0], &key,
860 path->slots[0]);
861 if (key.objectid == bytenr &&
862 key.type == BTRFS_EXTENT_ITEM_KEY &&
863 key.offset == fs_info->nodesize)
864 ret = 0;
865 }
866 }
867
868 if (ret == 0) {
869 leaf = path->nodes[0];
870 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
871 if (item_size >= sizeof(*ei)) {
872 ei = btrfs_item_ptr(leaf, path->slots[0],
873 struct btrfs_extent_item);
874 num_refs = btrfs_extent_refs(leaf, ei);
875 extent_flags = btrfs_extent_flags(leaf, ei);
876 } else {
877 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
878 struct btrfs_extent_item_v0 *ei0;
879 BUG_ON(item_size != sizeof(*ei0));
880 ei0 = btrfs_item_ptr(leaf, path->slots[0],
881 struct btrfs_extent_item_v0);
882 num_refs = btrfs_extent_refs_v0(leaf, ei0);
883 /* FIXME: this isn't correct for data */
884 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
885 #else
886 BUG();
887 #endif
888 }
889 BUG_ON(num_refs == 0);
890 } else {
891 num_refs = 0;
892 extent_flags = 0;
893 ret = 0;
894 }
895
896 if (!trans)
897 goto out;
898
899 delayed_refs = &trans->transaction->delayed_refs;
900 spin_lock(&delayed_refs->lock);
901 head = btrfs_find_delayed_ref_head(trans, bytenr);
902 if (head) {
903 if (!mutex_trylock(&head->mutex)) {
904 atomic_inc(&head->node.refs);
905 spin_unlock(&delayed_refs->lock);
906
907 btrfs_release_path(path);
908
909 /*
910 * Mutex was contended, block until it's released and try
911 * again
912 */
913 mutex_lock(&head->mutex);
914 mutex_unlock(&head->mutex);
915 btrfs_put_delayed_ref(&head->node);
916 goto search_again;
917 }
918 spin_lock(&head->lock);
919 if (head->extent_op && head->extent_op->update_flags)
920 extent_flags |= head->extent_op->flags_to_set;
921 else
922 BUG_ON(num_refs == 0);
923
924 num_refs += head->node.ref_mod;
925 spin_unlock(&head->lock);
926 mutex_unlock(&head->mutex);
927 }
928 spin_unlock(&delayed_refs->lock);
929 out:
930 WARN_ON(num_refs == 0);
931 if (refs)
932 *refs = num_refs;
933 if (flags)
934 *flags = extent_flags;
935 out_free:
936 btrfs_free_path(path);
937 return ret;
938 }
939
940 /*
941 * Back reference rules. Back refs have three main goals:
942 *
943 * 1) differentiate between all holders of references to an extent so that
944 * when a reference is dropped we can make sure it was a valid reference
945 * before freeing the extent.
946 *
947 * 2) Provide enough information to quickly find the holders of an extent
948 * if we notice a given block is corrupted or bad.
949 *
950 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
951 * maintenance. This is actually the same as #2, but with a slightly
952 * different use case.
953 *
954 * There are two kinds of back refs. The implicit back refs is optimized
955 * for pointers in non-shared tree blocks. For a given pointer in a block,
956 * back refs of this kind provide information about the block's owner tree
957 * and the pointer's key. These information allow us to find the block by
958 * b-tree searching. The full back refs is for pointers in tree blocks not
959 * referenced by their owner trees. The location of tree block is recorded
960 * in the back refs. Actually the full back refs is generic, and can be
961 * used in all cases the implicit back refs is used. The major shortcoming
962 * of the full back refs is its overhead. Every time a tree block gets
963 * COWed, we have to update back refs entry for all pointers in it.
964 *
965 * For a newly allocated tree block, we use implicit back refs for
966 * pointers in it. This means most tree related operations only involve
967 * implicit back refs. For a tree block created in old transaction, the
968 * only way to drop a reference to it is COW it. So we can detect the
969 * event that tree block loses its owner tree's reference and do the
970 * back refs conversion.
971 *
972 * When a tree block is COWed through a tree, there are four cases:
973 *
974 * The reference count of the block is one and the tree is the block's
975 * owner tree. Nothing to do in this case.
976 *
977 * The reference count of the block is one and the tree is not the
978 * block's owner tree. In this case, full back refs is used for pointers
979 * in the block. Remove these full back refs, add implicit back refs for
980 * every pointers in the new block.
981 *
982 * The reference count of the block is greater than one and the tree is
983 * the block's owner tree. In this case, implicit back refs is used for
984 * pointers in the block. Add full back refs for every pointers in the
985 * block, increase lower level extents' reference counts. The original
986 * implicit back refs are entailed to the new block.
987 *
988 * The reference count of the block is greater than one and the tree is
989 * not the block's owner tree. Add implicit back refs for every pointer in
990 * the new block, increase lower level extents' reference count.
991 *
992 * Back Reference Key composing:
993 *
994 * The key objectid corresponds to the first byte in the extent,
995 * The key type is used to differentiate between types of back refs.
996 * There are different meanings of the key offset for different types
997 * of back refs.
998 *
999 * File extents can be referenced by:
1000 *
1001 * - multiple snapshots, subvolumes, or different generations in one subvol
1002 * - different files inside a single subvolume
1003 * - different offsets inside a file (bookend extents in file.c)
1004 *
1005 * The extent ref structure for the implicit back refs has fields for:
1006 *
1007 * - Objectid of the subvolume root
1008 * - objectid of the file holding the reference
1009 * - original offset in the file
1010 * - how many bookend extents
1011 *
1012 * The key offset for the implicit back refs is hash of the first
1013 * three fields.
1014 *
1015 * The extent ref structure for the full back refs has field for:
1016 *
1017 * - number of pointers in the tree leaf
1018 *
1019 * The key offset for the implicit back refs is the first byte of
1020 * the tree leaf
1021 *
1022 * When a file extent is allocated, The implicit back refs is used.
1023 * the fields are filled in:
1024 *
1025 * (root_key.objectid, inode objectid, offset in file, 1)
1026 *
1027 * When a file extent is removed file truncation, we find the
1028 * corresponding implicit back refs and check the following fields:
1029 *
1030 * (btrfs_header_owner(leaf), inode objectid, offset in file)
1031 *
1032 * Btree extents can be referenced by:
1033 *
1034 * - Different subvolumes
1035 *
1036 * Both the implicit back refs and the full back refs for tree blocks
1037 * only consist of key. The key offset for the implicit back refs is
1038 * objectid of block's owner tree. The key offset for the full back refs
1039 * is the first byte of parent block.
1040 *
1041 * When implicit back refs is used, information about the lowest key and
1042 * level of the tree block are required. These information are stored in
1043 * tree block info structure.
1044 */
1045
1046 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1047 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
1048 struct btrfs_root *root,
1049 struct btrfs_path *path,
1050 u64 owner, u32 extra_size)
1051 {
1052 struct btrfs_extent_item *item;
1053 struct btrfs_extent_item_v0 *ei0;
1054 struct btrfs_extent_ref_v0 *ref0;
1055 struct btrfs_tree_block_info *bi;
1056 struct extent_buffer *leaf;
1057 struct btrfs_key key;
1058 struct btrfs_key found_key;
1059 u32 new_size = sizeof(*item);
1060 u64 refs;
1061 int ret;
1062
1063 leaf = path->nodes[0];
1064 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1065
1066 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1067 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1068 struct btrfs_extent_item_v0);
1069 refs = btrfs_extent_refs_v0(leaf, ei0);
1070
1071 if (owner == (u64)-1) {
1072 while (1) {
1073 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1074 ret = btrfs_next_leaf(root, path);
1075 if (ret < 0)
1076 return ret;
1077 BUG_ON(ret > 0); /* Corruption */
1078 leaf = path->nodes[0];
1079 }
1080 btrfs_item_key_to_cpu(leaf, &found_key,
1081 path->slots[0]);
1082 BUG_ON(key.objectid != found_key.objectid);
1083 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1084 path->slots[0]++;
1085 continue;
1086 }
1087 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1088 struct btrfs_extent_ref_v0);
1089 owner = btrfs_ref_objectid_v0(leaf, ref0);
1090 break;
1091 }
1092 }
1093 btrfs_release_path(path);
1094
1095 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1096 new_size += sizeof(*bi);
1097
1098 new_size -= sizeof(*ei0);
1099 ret = btrfs_search_slot(trans, root, &key, path,
1100 new_size + extra_size, 1);
1101 if (ret < 0)
1102 return ret;
1103 BUG_ON(ret); /* Corruption */
1104
1105 btrfs_extend_item(root, path, new_size);
1106
1107 leaf = path->nodes[0];
1108 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1109 btrfs_set_extent_refs(leaf, item, refs);
1110 /* FIXME: get real generation */
1111 btrfs_set_extent_generation(leaf, item, 0);
1112 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1113 btrfs_set_extent_flags(leaf, item,
1114 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1115 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1116 bi = (struct btrfs_tree_block_info *)(item + 1);
1117 /* FIXME: get first key of the block */
1118 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
1119 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1120 } else {
1121 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1122 }
1123 btrfs_mark_buffer_dirty(leaf);
1124 return 0;
1125 }
1126 #endif
1127
1128 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1129 {
1130 u32 high_crc = ~(u32)0;
1131 u32 low_crc = ~(u32)0;
1132 __le64 lenum;
1133
1134 lenum = cpu_to_le64(root_objectid);
1135 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1136 lenum = cpu_to_le64(owner);
1137 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1138 lenum = cpu_to_le64(offset);
1139 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1140
1141 return ((u64)high_crc << 31) ^ (u64)low_crc;
1142 }
1143
1144 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1145 struct btrfs_extent_data_ref *ref)
1146 {
1147 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1148 btrfs_extent_data_ref_objectid(leaf, ref),
1149 btrfs_extent_data_ref_offset(leaf, ref));
1150 }
1151
1152 static int match_extent_data_ref(struct extent_buffer *leaf,
1153 struct btrfs_extent_data_ref *ref,
1154 u64 root_objectid, u64 owner, u64 offset)
1155 {
1156 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1157 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1158 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1159 return 0;
1160 return 1;
1161 }
1162
1163 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1164 struct btrfs_root *root,
1165 struct btrfs_path *path,
1166 u64 bytenr, u64 parent,
1167 u64 root_objectid,
1168 u64 owner, u64 offset)
1169 {
1170 struct btrfs_key key;
1171 struct btrfs_extent_data_ref *ref;
1172 struct extent_buffer *leaf;
1173 u32 nritems;
1174 int ret;
1175 int recow;
1176 int err = -ENOENT;
1177
1178 key.objectid = bytenr;
1179 if (parent) {
1180 key.type = BTRFS_SHARED_DATA_REF_KEY;
1181 key.offset = parent;
1182 } else {
1183 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1184 key.offset = hash_extent_data_ref(root_objectid,
1185 owner, offset);
1186 }
1187 again:
1188 recow = 0;
1189 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1190 if (ret < 0) {
1191 err = ret;
1192 goto fail;
1193 }
1194
1195 if (parent) {
1196 if (!ret)
1197 return 0;
1198 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1199 key.type = BTRFS_EXTENT_REF_V0_KEY;
1200 btrfs_release_path(path);
1201 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1202 if (ret < 0) {
1203 err = ret;
1204 goto fail;
1205 }
1206 if (!ret)
1207 return 0;
1208 #endif
1209 goto fail;
1210 }
1211
1212 leaf = path->nodes[0];
1213 nritems = btrfs_header_nritems(leaf);
1214 while (1) {
1215 if (path->slots[0] >= nritems) {
1216 ret = btrfs_next_leaf(root, path);
1217 if (ret < 0)
1218 err = ret;
1219 if (ret)
1220 goto fail;
1221
1222 leaf = path->nodes[0];
1223 nritems = btrfs_header_nritems(leaf);
1224 recow = 1;
1225 }
1226
1227 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1228 if (key.objectid != bytenr ||
1229 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1230 goto fail;
1231
1232 ref = btrfs_item_ptr(leaf, path->slots[0],
1233 struct btrfs_extent_data_ref);
1234
1235 if (match_extent_data_ref(leaf, ref, root_objectid,
1236 owner, offset)) {
1237 if (recow) {
1238 btrfs_release_path(path);
1239 goto again;
1240 }
1241 err = 0;
1242 break;
1243 }
1244 path->slots[0]++;
1245 }
1246 fail:
1247 return err;
1248 }
1249
1250 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1251 struct btrfs_root *root,
1252 struct btrfs_path *path,
1253 u64 bytenr, u64 parent,
1254 u64 root_objectid, u64 owner,
1255 u64 offset, int refs_to_add)
1256 {
1257 struct btrfs_key key;
1258 struct extent_buffer *leaf;
1259 u32 size;
1260 u32 num_refs;
1261 int ret;
1262
1263 key.objectid = bytenr;
1264 if (parent) {
1265 key.type = BTRFS_SHARED_DATA_REF_KEY;
1266 key.offset = parent;
1267 size = sizeof(struct btrfs_shared_data_ref);
1268 } else {
1269 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1270 key.offset = hash_extent_data_ref(root_objectid,
1271 owner, offset);
1272 size = sizeof(struct btrfs_extent_data_ref);
1273 }
1274
1275 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1276 if (ret && ret != -EEXIST)
1277 goto fail;
1278
1279 leaf = path->nodes[0];
1280 if (parent) {
1281 struct btrfs_shared_data_ref *ref;
1282 ref = btrfs_item_ptr(leaf, path->slots[0],
1283 struct btrfs_shared_data_ref);
1284 if (ret == 0) {
1285 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1286 } else {
1287 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1288 num_refs += refs_to_add;
1289 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1290 }
1291 } else {
1292 struct btrfs_extent_data_ref *ref;
1293 while (ret == -EEXIST) {
1294 ref = btrfs_item_ptr(leaf, path->slots[0],
1295 struct btrfs_extent_data_ref);
1296 if (match_extent_data_ref(leaf, ref, root_objectid,
1297 owner, offset))
1298 break;
1299 btrfs_release_path(path);
1300 key.offset++;
1301 ret = btrfs_insert_empty_item(trans, root, path, &key,
1302 size);
1303 if (ret && ret != -EEXIST)
1304 goto fail;
1305
1306 leaf = path->nodes[0];
1307 }
1308 ref = btrfs_item_ptr(leaf, path->slots[0],
1309 struct btrfs_extent_data_ref);
1310 if (ret == 0) {
1311 btrfs_set_extent_data_ref_root(leaf, ref,
1312 root_objectid);
1313 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1314 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1315 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1316 } else {
1317 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1318 num_refs += refs_to_add;
1319 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1320 }
1321 }
1322 btrfs_mark_buffer_dirty(leaf);
1323 ret = 0;
1324 fail:
1325 btrfs_release_path(path);
1326 return ret;
1327 }
1328
1329 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1330 struct btrfs_root *root,
1331 struct btrfs_path *path,
1332 int refs_to_drop, int *last_ref)
1333 {
1334 struct btrfs_key key;
1335 struct btrfs_extent_data_ref *ref1 = NULL;
1336 struct btrfs_shared_data_ref *ref2 = NULL;
1337 struct extent_buffer *leaf;
1338 u32 num_refs = 0;
1339 int ret = 0;
1340
1341 leaf = path->nodes[0];
1342 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1343
1344 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1345 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1346 struct btrfs_extent_data_ref);
1347 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1348 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1349 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1350 struct btrfs_shared_data_ref);
1351 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1352 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1353 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1354 struct btrfs_extent_ref_v0 *ref0;
1355 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1356 struct btrfs_extent_ref_v0);
1357 num_refs = btrfs_ref_count_v0(leaf, ref0);
1358 #endif
1359 } else {
1360 BUG();
1361 }
1362
1363 BUG_ON(num_refs < refs_to_drop);
1364 num_refs -= refs_to_drop;
1365
1366 if (num_refs == 0) {
1367 ret = btrfs_del_item(trans, root, path);
1368 *last_ref = 1;
1369 } else {
1370 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1371 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1372 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1373 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1374 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1375 else {
1376 struct btrfs_extent_ref_v0 *ref0;
1377 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1378 struct btrfs_extent_ref_v0);
1379 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1380 }
1381 #endif
1382 btrfs_mark_buffer_dirty(leaf);
1383 }
1384 return ret;
1385 }
1386
1387 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1388 struct btrfs_extent_inline_ref *iref)
1389 {
1390 struct btrfs_key key;
1391 struct extent_buffer *leaf;
1392 struct btrfs_extent_data_ref *ref1;
1393 struct btrfs_shared_data_ref *ref2;
1394 u32 num_refs = 0;
1395
1396 leaf = path->nodes[0];
1397 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1398 if (iref) {
1399 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1400 BTRFS_EXTENT_DATA_REF_KEY) {
1401 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1402 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1403 } else {
1404 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1405 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1406 }
1407 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1408 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1409 struct btrfs_extent_data_ref);
1410 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1411 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1412 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1413 struct btrfs_shared_data_ref);
1414 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1415 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1416 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1417 struct btrfs_extent_ref_v0 *ref0;
1418 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1419 struct btrfs_extent_ref_v0);
1420 num_refs = btrfs_ref_count_v0(leaf, ref0);
1421 #endif
1422 } else {
1423 WARN_ON(1);
1424 }
1425 return num_refs;
1426 }
1427
1428 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1429 struct btrfs_root *root,
1430 struct btrfs_path *path,
1431 u64 bytenr, u64 parent,
1432 u64 root_objectid)
1433 {
1434 struct btrfs_key key;
1435 int ret;
1436
1437 key.objectid = bytenr;
1438 if (parent) {
1439 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1440 key.offset = parent;
1441 } else {
1442 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1443 key.offset = root_objectid;
1444 }
1445
1446 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1447 if (ret > 0)
1448 ret = -ENOENT;
1449 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1450 if (ret == -ENOENT && parent) {
1451 btrfs_release_path(path);
1452 key.type = BTRFS_EXTENT_REF_V0_KEY;
1453 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1454 if (ret > 0)
1455 ret = -ENOENT;
1456 }
1457 #endif
1458 return ret;
1459 }
1460
1461 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1462 struct btrfs_root *root,
1463 struct btrfs_path *path,
1464 u64 bytenr, u64 parent,
1465 u64 root_objectid)
1466 {
1467 struct btrfs_key key;
1468 int ret;
1469
1470 key.objectid = bytenr;
1471 if (parent) {
1472 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1473 key.offset = parent;
1474 } else {
1475 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1476 key.offset = root_objectid;
1477 }
1478
1479 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1480 btrfs_release_path(path);
1481 return ret;
1482 }
1483
1484 static inline int extent_ref_type(u64 parent, u64 owner)
1485 {
1486 int type;
1487 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1488 if (parent > 0)
1489 type = BTRFS_SHARED_BLOCK_REF_KEY;
1490 else
1491 type = BTRFS_TREE_BLOCK_REF_KEY;
1492 } else {
1493 if (parent > 0)
1494 type = BTRFS_SHARED_DATA_REF_KEY;
1495 else
1496 type = BTRFS_EXTENT_DATA_REF_KEY;
1497 }
1498 return type;
1499 }
1500
1501 static int find_next_key(struct btrfs_path *path, int level,
1502 struct btrfs_key *key)
1503
1504 {
1505 for (; level < BTRFS_MAX_LEVEL; level++) {
1506 if (!path->nodes[level])
1507 break;
1508 if (path->slots[level] + 1 >=
1509 btrfs_header_nritems(path->nodes[level]))
1510 continue;
1511 if (level == 0)
1512 btrfs_item_key_to_cpu(path->nodes[level], key,
1513 path->slots[level] + 1);
1514 else
1515 btrfs_node_key_to_cpu(path->nodes[level], key,
1516 path->slots[level] + 1);
1517 return 0;
1518 }
1519 return 1;
1520 }
1521
1522 /*
1523 * look for inline back ref. if back ref is found, *ref_ret is set
1524 * to the address of inline back ref, and 0 is returned.
1525 *
1526 * if back ref isn't found, *ref_ret is set to the address where it
1527 * should be inserted, and -ENOENT is returned.
1528 *
1529 * if insert is true and there are too many inline back refs, the path
1530 * points to the extent item, and -EAGAIN is returned.
1531 *
1532 * NOTE: inline back refs are ordered in the same way that back ref
1533 * items in the tree are ordered.
1534 */
1535 static noinline_for_stack
1536 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1537 struct btrfs_root *root,
1538 struct btrfs_path *path,
1539 struct btrfs_extent_inline_ref **ref_ret,
1540 u64 bytenr, u64 num_bytes,
1541 u64 parent, u64 root_objectid,
1542 u64 owner, u64 offset, int insert)
1543 {
1544 struct btrfs_fs_info *fs_info = root->fs_info;
1545 struct btrfs_key key;
1546 struct extent_buffer *leaf;
1547 struct btrfs_extent_item *ei;
1548 struct btrfs_extent_inline_ref *iref;
1549 u64 flags;
1550 u64 item_size;
1551 unsigned long ptr;
1552 unsigned long end;
1553 int extra_size;
1554 int type;
1555 int want;
1556 int ret;
1557 int err = 0;
1558 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1559
1560 key.objectid = bytenr;
1561 key.type = BTRFS_EXTENT_ITEM_KEY;
1562 key.offset = num_bytes;
1563
1564 want = extent_ref_type(parent, owner);
1565 if (insert) {
1566 extra_size = btrfs_extent_inline_ref_size(want);
1567 path->keep_locks = 1;
1568 } else
1569 extra_size = -1;
1570
1571 /*
1572 * Owner is our parent level, so we can just add one to get the level
1573 * for the block we are interested in.
1574 */
1575 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1576 key.type = BTRFS_METADATA_ITEM_KEY;
1577 key.offset = owner;
1578 }
1579
1580 again:
1581 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1582 if (ret < 0) {
1583 err = ret;
1584 goto out;
1585 }
1586
1587 /*
1588 * We may be a newly converted file system which still has the old fat
1589 * extent entries for metadata, so try and see if we have one of those.
1590 */
1591 if (ret > 0 && skinny_metadata) {
1592 skinny_metadata = false;
1593 if (path->slots[0]) {
1594 path->slots[0]--;
1595 btrfs_item_key_to_cpu(path->nodes[0], &key,
1596 path->slots[0]);
1597 if (key.objectid == bytenr &&
1598 key.type == BTRFS_EXTENT_ITEM_KEY &&
1599 key.offset == num_bytes)
1600 ret = 0;
1601 }
1602 if (ret) {
1603 key.objectid = bytenr;
1604 key.type = BTRFS_EXTENT_ITEM_KEY;
1605 key.offset = num_bytes;
1606 btrfs_release_path(path);
1607 goto again;
1608 }
1609 }
1610
1611 if (ret && !insert) {
1612 err = -ENOENT;
1613 goto out;
1614 } else if (WARN_ON(ret)) {
1615 err = -EIO;
1616 goto out;
1617 }
1618
1619 leaf = path->nodes[0];
1620 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1621 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1622 if (item_size < sizeof(*ei)) {
1623 if (!insert) {
1624 err = -ENOENT;
1625 goto out;
1626 }
1627 ret = convert_extent_item_v0(trans, root, path, owner,
1628 extra_size);
1629 if (ret < 0) {
1630 err = ret;
1631 goto out;
1632 }
1633 leaf = path->nodes[0];
1634 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1635 }
1636 #endif
1637 BUG_ON(item_size < sizeof(*ei));
1638
1639 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1640 flags = btrfs_extent_flags(leaf, ei);
1641
1642 ptr = (unsigned long)(ei + 1);
1643 end = (unsigned long)ei + item_size;
1644
1645 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1646 ptr += sizeof(struct btrfs_tree_block_info);
1647 BUG_ON(ptr > end);
1648 }
1649
1650 err = -ENOENT;
1651 while (1) {
1652 if (ptr >= end) {
1653 WARN_ON(ptr > end);
1654 break;
1655 }
1656 iref = (struct btrfs_extent_inline_ref *)ptr;
1657 type = btrfs_extent_inline_ref_type(leaf, iref);
1658 if (want < type)
1659 break;
1660 if (want > type) {
1661 ptr += btrfs_extent_inline_ref_size(type);
1662 continue;
1663 }
1664
1665 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1666 struct btrfs_extent_data_ref *dref;
1667 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1668 if (match_extent_data_ref(leaf, dref, root_objectid,
1669 owner, offset)) {
1670 err = 0;
1671 break;
1672 }
1673 if (hash_extent_data_ref_item(leaf, dref) <
1674 hash_extent_data_ref(root_objectid, owner, offset))
1675 break;
1676 } else {
1677 u64 ref_offset;
1678 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1679 if (parent > 0) {
1680 if (parent == ref_offset) {
1681 err = 0;
1682 break;
1683 }
1684 if (ref_offset < parent)
1685 break;
1686 } else {
1687 if (root_objectid == ref_offset) {
1688 err = 0;
1689 break;
1690 }
1691 if (ref_offset < root_objectid)
1692 break;
1693 }
1694 }
1695 ptr += btrfs_extent_inline_ref_size(type);
1696 }
1697 if (err == -ENOENT && insert) {
1698 if (item_size + extra_size >=
1699 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1700 err = -EAGAIN;
1701 goto out;
1702 }
1703 /*
1704 * To add new inline back ref, we have to make sure
1705 * there is no corresponding back ref item.
1706 * For simplicity, we just do not add new inline back
1707 * ref if there is any kind of item for this block
1708 */
1709 if (find_next_key(path, 0, &key) == 0 &&
1710 key.objectid == bytenr &&
1711 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1712 err = -EAGAIN;
1713 goto out;
1714 }
1715 }
1716 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1717 out:
1718 if (insert) {
1719 path->keep_locks = 0;
1720 btrfs_unlock_up_safe(path, 1);
1721 }
1722 return err;
1723 }
1724
1725 /*
1726 * helper to add new inline back ref
1727 */
1728 static noinline_for_stack
1729 void setup_inline_extent_backref(struct btrfs_root *root,
1730 struct btrfs_path *path,
1731 struct btrfs_extent_inline_ref *iref,
1732 u64 parent, u64 root_objectid,
1733 u64 owner, u64 offset, int refs_to_add,
1734 struct btrfs_delayed_extent_op *extent_op)
1735 {
1736 struct extent_buffer *leaf;
1737 struct btrfs_extent_item *ei;
1738 unsigned long ptr;
1739 unsigned long end;
1740 unsigned long item_offset;
1741 u64 refs;
1742 int size;
1743 int type;
1744
1745 leaf = path->nodes[0];
1746 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1747 item_offset = (unsigned long)iref - (unsigned long)ei;
1748
1749 type = extent_ref_type(parent, owner);
1750 size = btrfs_extent_inline_ref_size(type);
1751
1752 btrfs_extend_item(root, path, size);
1753
1754 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1755 refs = btrfs_extent_refs(leaf, ei);
1756 refs += refs_to_add;
1757 btrfs_set_extent_refs(leaf, ei, refs);
1758 if (extent_op)
1759 __run_delayed_extent_op(extent_op, leaf, ei);
1760
1761 ptr = (unsigned long)ei + item_offset;
1762 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1763 if (ptr < end - size)
1764 memmove_extent_buffer(leaf, ptr + size, ptr,
1765 end - size - ptr);
1766
1767 iref = (struct btrfs_extent_inline_ref *)ptr;
1768 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1769 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1770 struct btrfs_extent_data_ref *dref;
1771 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1772 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1773 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1774 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1775 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1776 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1777 struct btrfs_shared_data_ref *sref;
1778 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1779 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1780 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1781 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1782 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1783 } else {
1784 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1785 }
1786 btrfs_mark_buffer_dirty(leaf);
1787 }
1788
1789 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1790 struct btrfs_root *root,
1791 struct btrfs_path *path,
1792 struct btrfs_extent_inline_ref **ref_ret,
1793 u64 bytenr, u64 num_bytes, u64 parent,
1794 u64 root_objectid, u64 owner, u64 offset)
1795 {
1796 int ret;
1797
1798 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1799 bytenr, num_bytes, parent,
1800 root_objectid, owner, offset, 0);
1801 if (ret != -ENOENT)
1802 return ret;
1803
1804 btrfs_release_path(path);
1805 *ref_ret = NULL;
1806
1807 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1808 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1809 root_objectid);
1810 } else {
1811 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1812 root_objectid, owner, offset);
1813 }
1814 return ret;
1815 }
1816
1817 /*
1818 * helper to update/remove inline back ref
1819 */
1820 static noinline_for_stack
1821 void update_inline_extent_backref(struct btrfs_root *root,
1822 struct btrfs_path *path,
1823 struct btrfs_extent_inline_ref *iref,
1824 int refs_to_mod,
1825 struct btrfs_delayed_extent_op *extent_op,
1826 int *last_ref)
1827 {
1828 struct extent_buffer *leaf;
1829 struct btrfs_extent_item *ei;
1830 struct btrfs_extent_data_ref *dref = NULL;
1831 struct btrfs_shared_data_ref *sref = NULL;
1832 unsigned long ptr;
1833 unsigned long end;
1834 u32 item_size;
1835 int size;
1836 int type;
1837 u64 refs;
1838
1839 leaf = path->nodes[0];
1840 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1841 refs = btrfs_extent_refs(leaf, ei);
1842 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1843 refs += refs_to_mod;
1844 btrfs_set_extent_refs(leaf, ei, refs);
1845 if (extent_op)
1846 __run_delayed_extent_op(extent_op, leaf, ei);
1847
1848 type = btrfs_extent_inline_ref_type(leaf, iref);
1849
1850 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1851 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1852 refs = btrfs_extent_data_ref_count(leaf, dref);
1853 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1854 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1855 refs = btrfs_shared_data_ref_count(leaf, sref);
1856 } else {
1857 refs = 1;
1858 BUG_ON(refs_to_mod != -1);
1859 }
1860
1861 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1862 refs += refs_to_mod;
1863
1864 if (refs > 0) {
1865 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1866 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1867 else
1868 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1869 } else {
1870 *last_ref = 1;
1871 size = btrfs_extent_inline_ref_size(type);
1872 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1873 ptr = (unsigned long)iref;
1874 end = (unsigned long)ei + item_size;
1875 if (ptr + size < end)
1876 memmove_extent_buffer(leaf, ptr, ptr + size,
1877 end - ptr - size);
1878 item_size -= size;
1879 btrfs_truncate_item(root, path, item_size, 1);
1880 }
1881 btrfs_mark_buffer_dirty(leaf);
1882 }
1883
1884 static noinline_for_stack
1885 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1886 struct btrfs_root *root,
1887 struct btrfs_path *path,
1888 u64 bytenr, u64 num_bytes, u64 parent,
1889 u64 root_objectid, u64 owner,
1890 u64 offset, int refs_to_add,
1891 struct btrfs_delayed_extent_op *extent_op)
1892 {
1893 struct btrfs_extent_inline_ref *iref;
1894 int ret;
1895
1896 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1897 bytenr, num_bytes, parent,
1898 root_objectid, owner, offset, 1);
1899 if (ret == 0) {
1900 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1901 update_inline_extent_backref(root, path, iref,
1902 refs_to_add, extent_op, NULL);
1903 } else if (ret == -ENOENT) {
1904 setup_inline_extent_backref(root, path, iref, parent,
1905 root_objectid, owner, offset,
1906 refs_to_add, extent_op);
1907 ret = 0;
1908 }
1909 return ret;
1910 }
1911
1912 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1913 struct btrfs_root *root,
1914 struct btrfs_path *path,
1915 u64 bytenr, u64 parent, u64 root_objectid,
1916 u64 owner, u64 offset, int refs_to_add)
1917 {
1918 int ret;
1919 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1920 BUG_ON(refs_to_add != 1);
1921 ret = insert_tree_block_ref(trans, root, path, bytenr,
1922 parent, root_objectid);
1923 } else {
1924 ret = insert_extent_data_ref(trans, root, path, bytenr,
1925 parent, root_objectid,
1926 owner, offset, refs_to_add);
1927 }
1928 return ret;
1929 }
1930
1931 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1932 struct btrfs_root *root,
1933 struct btrfs_path *path,
1934 struct btrfs_extent_inline_ref *iref,
1935 int refs_to_drop, int is_data, int *last_ref)
1936 {
1937 int ret = 0;
1938
1939 BUG_ON(!is_data && refs_to_drop != 1);
1940 if (iref) {
1941 update_inline_extent_backref(root, path, iref,
1942 -refs_to_drop, NULL, last_ref);
1943 } else if (is_data) {
1944 ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
1945 last_ref);
1946 } else {
1947 *last_ref = 1;
1948 ret = btrfs_del_item(trans, root, path);
1949 }
1950 return ret;
1951 }
1952
1953 #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
1954 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1955 u64 *discarded_bytes)
1956 {
1957 int j, ret = 0;
1958 u64 bytes_left, end;
1959 u64 aligned_start = ALIGN(start, 1 << 9);
1960
1961 if (WARN_ON(start != aligned_start)) {
1962 len -= aligned_start - start;
1963 len = round_down(len, 1 << 9);
1964 start = aligned_start;
1965 }
1966
1967 *discarded_bytes = 0;
1968
1969 if (!len)
1970 return 0;
1971
1972 end = start + len;
1973 bytes_left = len;
1974
1975 /* Skip any superblocks on this device. */
1976 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1977 u64 sb_start = btrfs_sb_offset(j);
1978 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1979 u64 size = sb_start - start;
1980
1981 if (!in_range(sb_start, start, bytes_left) &&
1982 !in_range(sb_end, start, bytes_left) &&
1983 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1984 continue;
1985
1986 /*
1987 * Superblock spans beginning of range. Adjust start and
1988 * try again.
1989 */
1990 if (sb_start <= start) {
1991 start += sb_end - start;
1992 if (start > end) {
1993 bytes_left = 0;
1994 break;
1995 }
1996 bytes_left = end - start;
1997 continue;
1998 }
1999
2000 if (size) {
2001 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
2002 GFP_NOFS, 0);
2003 if (!ret)
2004 *discarded_bytes += size;
2005 else if (ret != -EOPNOTSUPP)
2006 return ret;
2007 }
2008
2009 start = sb_end;
2010 if (start > end) {
2011 bytes_left = 0;
2012 break;
2013 }
2014 bytes_left = end - start;
2015 }
2016
2017 if (bytes_left) {
2018 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2019 GFP_NOFS, 0);
2020 if (!ret)
2021 *discarded_bytes += bytes_left;
2022 }
2023 return ret;
2024 }
2025
2026 int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
2027 u64 num_bytes, u64 *actual_bytes)
2028 {
2029 struct btrfs_fs_info *fs_info = root->fs_info;
2030 int ret;
2031 u64 discarded_bytes = 0;
2032 struct btrfs_bio *bbio = NULL;
2033
2034
2035 /*
2036 * Avoid races with device replace and make sure our bbio has devices
2037 * associated to its stripes that don't go away while we are discarding.
2038 */
2039 btrfs_bio_counter_inc_blocked(fs_info);
2040 /* Tell the block device(s) that the sectors can be discarded */
2041 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2042 &bbio, 0);
2043 /* Error condition is -ENOMEM */
2044 if (!ret) {
2045 struct btrfs_bio_stripe *stripe = bbio->stripes;
2046 int i;
2047
2048
2049 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2050 u64 bytes;
2051 if (!stripe->dev->can_discard)
2052 continue;
2053
2054 ret = btrfs_issue_discard(stripe->dev->bdev,
2055 stripe->physical,
2056 stripe->length,
2057 &bytes);
2058 if (!ret)
2059 discarded_bytes += bytes;
2060 else if (ret != -EOPNOTSUPP)
2061 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2062
2063 /*
2064 * Just in case we get back EOPNOTSUPP for some reason,
2065 * just ignore the return value so we don't screw up
2066 * people calling discard_extent.
2067 */
2068 ret = 0;
2069 }
2070 btrfs_put_bbio(bbio);
2071 }
2072 btrfs_bio_counter_dec(fs_info);
2073
2074 if (actual_bytes)
2075 *actual_bytes = discarded_bytes;
2076
2077
2078 if (ret == -EOPNOTSUPP)
2079 ret = 0;
2080 return ret;
2081 }
2082
2083 /* Can return -ENOMEM */
2084 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2085 struct btrfs_root *root,
2086 u64 bytenr, u64 num_bytes, u64 parent,
2087 u64 root_objectid, u64 owner, u64 offset)
2088 {
2089 int ret;
2090 struct btrfs_fs_info *fs_info = root->fs_info;
2091
2092 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2093 root_objectid == BTRFS_TREE_LOG_OBJECTID);
2094
2095 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2096 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2097 num_bytes,
2098 parent, root_objectid, (int)owner,
2099 BTRFS_ADD_DELAYED_REF, NULL);
2100 } else {
2101 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
2102 num_bytes, parent, root_objectid,
2103 owner, offset, 0,
2104 BTRFS_ADD_DELAYED_REF, NULL);
2105 }
2106 return ret;
2107 }
2108
2109 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2110 struct btrfs_root *root,
2111 struct btrfs_delayed_ref_node *node,
2112 u64 parent, u64 root_objectid,
2113 u64 owner, u64 offset, int refs_to_add,
2114 struct btrfs_delayed_extent_op *extent_op)
2115 {
2116 struct btrfs_fs_info *fs_info = root->fs_info;
2117 struct btrfs_path *path;
2118 struct extent_buffer *leaf;
2119 struct btrfs_extent_item *item;
2120 struct btrfs_key key;
2121 u64 bytenr = node->bytenr;
2122 u64 num_bytes = node->num_bytes;
2123 u64 refs;
2124 int ret;
2125
2126 path = btrfs_alloc_path();
2127 if (!path)
2128 return -ENOMEM;
2129
2130 path->reada = READA_FORWARD;
2131 path->leave_spinning = 1;
2132 /* this will setup the path even if it fails to insert the back ref */
2133 ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
2134 bytenr, num_bytes, parent,
2135 root_objectid, owner, offset,
2136 refs_to_add, extent_op);
2137 if ((ret < 0 && ret != -EAGAIN) || !ret)
2138 goto out;
2139
2140 /*
2141 * Ok we had -EAGAIN which means we didn't have space to insert and
2142 * inline extent ref, so just update the reference count and add a
2143 * normal backref.
2144 */
2145 leaf = path->nodes[0];
2146 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2147 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2148 refs = btrfs_extent_refs(leaf, item);
2149 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2150 if (extent_op)
2151 __run_delayed_extent_op(extent_op, leaf, item);
2152
2153 btrfs_mark_buffer_dirty(leaf);
2154 btrfs_release_path(path);
2155
2156 path->reada = READA_FORWARD;
2157 path->leave_spinning = 1;
2158 /* now insert the actual backref */
2159 ret = insert_extent_backref(trans, fs_info->extent_root,
2160 path, bytenr, parent, root_objectid,
2161 owner, offset, refs_to_add);
2162 if (ret)
2163 btrfs_abort_transaction(trans, ret);
2164 out:
2165 btrfs_free_path(path);
2166 return ret;
2167 }
2168
2169 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2170 struct btrfs_root *root,
2171 struct btrfs_delayed_ref_node *node,
2172 struct btrfs_delayed_extent_op *extent_op,
2173 int insert_reserved)
2174 {
2175 struct btrfs_fs_info *fs_info = root->fs_info;
2176 int ret = 0;
2177 struct btrfs_delayed_data_ref *ref;
2178 struct btrfs_key ins;
2179 u64 parent = 0;
2180 u64 ref_root = 0;
2181 u64 flags = 0;
2182
2183 ins.objectid = node->bytenr;
2184 ins.offset = node->num_bytes;
2185 ins.type = BTRFS_EXTENT_ITEM_KEY;
2186
2187 ref = btrfs_delayed_node_to_data_ref(node);
2188 trace_run_delayed_data_ref(fs_info, node, ref, node->action);
2189
2190 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2191 parent = ref->parent;
2192 ref_root = ref->root;
2193
2194 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2195 if (extent_op)
2196 flags |= extent_op->flags_to_set;
2197 ret = alloc_reserved_file_extent(trans, root,
2198 parent, ref_root, flags,
2199 ref->objectid, ref->offset,
2200 &ins, node->ref_mod);
2201 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2202 ret = __btrfs_inc_extent_ref(trans, root, node, parent,
2203 ref_root, ref->objectid,
2204 ref->offset, node->ref_mod,
2205 extent_op);
2206 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2207 ret = __btrfs_free_extent(trans, root, node, parent,
2208 ref_root, ref->objectid,
2209 ref->offset, node->ref_mod,
2210 extent_op);
2211 } else {
2212 BUG();
2213 }
2214 return ret;
2215 }
2216
2217 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2218 struct extent_buffer *leaf,
2219 struct btrfs_extent_item *ei)
2220 {
2221 u64 flags = btrfs_extent_flags(leaf, ei);
2222 if (extent_op->update_flags) {
2223 flags |= extent_op->flags_to_set;
2224 btrfs_set_extent_flags(leaf, ei, flags);
2225 }
2226
2227 if (extent_op->update_key) {
2228 struct btrfs_tree_block_info *bi;
2229 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2230 bi = (struct btrfs_tree_block_info *)(ei + 1);
2231 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2232 }
2233 }
2234
2235 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2236 struct btrfs_root *root,
2237 struct btrfs_delayed_ref_node *node,
2238 struct btrfs_delayed_extent_op *extent_op)
2239 {
2240 struct btrfs_fs_info *fs_info = root->fs_info;
2241 struct btrfs_key key;
2242 struct btrfs_path *path;
2243 struct btrfs_extent_item *ei;
2244 struct extent_buffer *leaf;
2245 u32 item_size;
2246 int ret;
2247 int err = 0;
2248 int metadata = !extent_op->is_data;
2249
2250 if (trans->aborted)
2251 return 0;
2252
2253 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2254 metadata = 0;
2255
2256 path = btrfs_alloc_path();
2257 if (!path)
2258 return -ENOMEM;
2259
2260 key.objectid = node->bytenr;
2261
2262 if (metadata) {
2263 key.type = BTRFS_METADATA_ITEM_KEY;
2264 key.offset = extent_op->level;
2265 } else {
2266 key.type = BTRFS_EXTENT_ITEM_KEY;
2267 key.offset = node->num_bytes;
2268 }
2269
2270 again:
2271 path->reada = READA_FORWARD;
2272 path->leave_spinning = 1;
2273 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2274 if (ret < 0) {
2275 err = ret;
2276 goto out;
2277 }
2278 if (ret > 0) {
2279 if (metadata) {
2280 if (path->slots[0] > 0) {
2281 path->slots[0]--;
2282 btrfs_item_key_to_cpu(path->nodes[0], &key,
2283 path->slots[0]);
2284 if (key.objectid == node->bytenr &&
2285 key.type == BTRFS_EXTENT_ITEM_KEY &&
2286 key.offset == node->num_bytes)
2287 ret = 0;
2288 }
2289 if (ret > 0) {
2290 btrfs_release_path(path);
2291 metadata = 0;
2292
2293 key.objectid = node->bytenr;
2294 key.offset = node->num_bytes;
2295 key.type = BTRFS_EXTENT_ITEM_KEY;
2296 goto again;
2297 }
2298 } else {
2299 err = -EIO;
2300 goto out;
2301 }
2302 }
2303
2304 leaf = path->nodes[0];
2305 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2306 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2307 if (item_size < sizeof(*ei)) {
2308 ret = convert_extent_item_v0(trans, fs_info->extent_root,
2309 path, (u64)-1, 0);
2310 if (ret < 0) {
2311 err = ret;
2312 goto out;
2313 }
2314 leaf = path->nodes[0];
2315 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2316 }
2317 #endif
2318 BUG_ON(item_size < sizeof(*ei));
2319 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2320 __run_delayed_extent_op(extent_op, leaf, ei);
2321
2322 btrfs_mark_buffer_dirty(leaf);
2323 out:
2324 btrfs_free_path(path);
2325 return err;
2326 }
2327
2328 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2329 struct btrfs_root *root,
2330 struct btrfs_delayed_ref_node *node,
2331 struct btrfs_delayed_extent_op *extent_op,
2332 int insert_reserved)
2333 {
2334 struct btrfs_fs_info *fs_info = root->fs_info;
2335 int ret = 0;
2336 struct btrfs_delayed_tree_ref *ref;
2337 struct btrfs_key ins;
2338 u64 parent = 0;
2339 u64 ref_root = 0;
2340 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
2341
2342 ref = btrfs_delayed_node_to_tree_ref(node);
2343 trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
2344
2345 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2346 parent = ref->parent;
2347 ref_root = ref->root;
2348
2349 ins.objectid = node->bytenr;
2350 if (skinny_metadata) {
2351 ins.offset = ref->level;
2352 ins.type = BTRFS_METADATA_ITEM_KEY;
2353 } else {
2354 ins.offset = node->num_bytes;
2355 ins.type = BTRFS_EXTENT_ITEM_KEY;
2356 }
2357
2358 if (node->ref_mod != 1) {
2359 btrfs_err(root->fs_info,
2360 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2361 node->bytenr, node->ref_mod, node->action, ref_root,
2362 parent);
2363 return -EIO;
2364 }
2365 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2366 BUG_ON(!extent_op || !extent_op->update_flags);
2367 ret = alloc_reserved_tree_block(trans, root,
2368 parent, ref_root,
2369 extent_op->flags_to_set,
2370 &extent_op->key,
2371 ref->level, &ins);
2372 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2373 ret = __btrfs_inc_extent_ref(trans, root, node,
2374 parent, ref_root,
2375 ref->level, 0, 1,
2376 extent_op);
2377 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2378 ret = __btrfs_free_extent(trans, root, node,
2379 parent, ref_root,
2380 ref->level, 0, 1, extent_op);
2381 } else {
2382 BUG();
2383 }
2384 return ret;
2385 }
2386
2387 /* helper function to actually process a single delayed ref entry */
2388 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2389 struct btrfs_root *root,
2390 struct btrfs_delayed_ref_node *node,
2391 struct btrfs_delayed_extent_op *extent_op,
2392 int insert_reserved)
2393 {
2394 struct btrfs_fs_info *fs_info = root->fs_info;
2395 int ret = 0;
2396
2397 if (trans->aborted) {
2398 if (insert_reserved)
2399 btrfs_pin_extent(root, node->bytenr,
2400 node->num_bytes, 1);
2401 return 0;
2402 }
2403
2404 if (btrfs_delayed_ref_is_head(node)) {
2405 struct btrfs_delayed_ref_head *head;
2406 /*
2407 * we've hit the end of the chain and we were supposed
2408 * to insert this extent into the tree. But, it got
2409 * deleted before we ever needed to insert it, so all
2410 * we have to do is clean up the accounting
2411 */
2412 BUG_ON(extent_op);
2413 head = btrfs_delayed_node_to_head(node);
2414 trace_run_delayed_ref_head(fs_info, node, head, node->action);
2415
2416 if (insert_reserved) {
2417 btrfs_pin_extent(root, node->bytenr,
2418 node->num_bytes, 1);
2419 if (head->is_data) {
2420 ret = btrfs_del_csums(trans, fs_info,
2421 node->bytenr,
2422 node->num_bytes);
2423 }
2424 }
2425
2426 /* Also free its reserved qgroup space */
2427 btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2428 head->qgroup_reserved);
2429 return ret;
2430 }
2431
2432 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2433 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2434 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2435 insert_reserved);
2436 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2437 node->type == BTRFS_SHARED_DATA_REF_KEY)
2438 ret = run_delayed_data_ref(trans, root, node, extent_op,
2439 insert_reserved);
2440 else
2441 BUG();
2442 return ret;
2443 }
2444
2445 static inline struct btrfs_delayed_ref_node *
2446 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2447 {
2448 struct btrfs_delayed_ref_node *ref;
2449
2450 if (list_empty(&head->ref_list))
2451 return NULL;
2452
2453 /*
2454 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2455 * This is to prevent a ref count from going down to zero, which deletes
2456 * the extent item from the extent tree, when there still are references
2457 * to add, which would fail because they would not find the extent item.
2458 */
2459 if (!list_empty(&head->ref_add_list))
2460 return list_first_entry(&head->ref_add_list,
2461 struct btrfs_delayed_ref_node, add_list);
2462
2463 ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
2464 list);
2465 ASSERT(list_empty(&ref->add_list));
2466 return ref;
2467 }
2468
2469 /*
2470 * Returns 0 on success or if called with an already aborted transaction.
2471 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2472 */
2473 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2474 struct btrfs_root *root,
2475 unsigned long nr)
2476 {
2477 struct btrfs_delayed_ref_root *delayed_refs;
2478 struct btrfs_delayed_ref_node *ref;
2479 struct btrfs_delayed_ref_head *locked_ref = NULL;
2480 struct btrfs_delayed_extent_op *extent_op;
2481 struct btrfs_fs_info *fs_info = root->fs_info;
2482 ktime_t start = ktime_get();
2483 int ret;
2484 unsigned long count = 0;
2485 unsigned long actual_count = 0;
2486 int must_insert_reserved = 0;
2487
2488 delayed_refs = &trans->transaction->delayed_refs;
2489 while (1) {
2490 if (!locked_ref) {
2491 if (count >= nr)
2492 break;
2493
2494 spin_lock(&delayed_refs->lock);
2495 locked_ref = btrfs_select_ref_head(trans);
2496 if (!locked_ref) {
2497 spin_unlock(&delayed_refs->lock);
2498 break;
2499 }
2500
2501 /* grab the lock that says we are going to process
2502 * all the refs for this head */
2503 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2504 spin_unlock(&delayed_refs->lock);
2505 /*
2506 * we may have dropped the spin lock to get the head
2507 * mutex lock, and that might have given someone else
2508 * time to free the head. If that's true, it has been
2509 * removed from our list and we can move on.
2510 */
2511 if (ret == -EAGAIN) {
2512 locked_ref = NULL;
2513 count++;
2514 continue;
2515 }
2516 }
2517
2518 /*
2519 * We need to try and merge add/drops of the same ref since we
2520 * can run into issues with relocate dropping the implicit ref
2521 * and then it being added back again before the drop can
2522 * finish. If we merged anything we need to re-loop so we can
2523 * get a good ref.
2524 * Or we can get node references of the same type that weren't
2525 * merged when created due to bumps in the tree mod seq, and
2526 * we need to merge them to prevent adding an inline extent
2527 * backref before dropping it (triggering a BUG_ON at
2528 * insert_inline_extent_backref()).
2529 */
2530 spin_lock(&locked_ref->lock);
2531 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2532 locked_ref);
2533
2534 /*
2535 * locked_ref is the head node, so we have to go one
2536 * node back for any delayed ref updates
2537 */
2538 ref = select_delayed_ref(locked_ref);
2539
2540 if (ref && ref->seq &&
2541 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2542 spin_unlock(&locked_ref->lock);
2543 btrfs_delayed_ref_unlock(locked_ref);
2544 spin_lock(&delayed_refs->lock);
2545 locked_ref->processing = 0;
2546 delayed_refs->num_heads_ready++;
2547 spin_unlock(&delayed_refs->lock);
2548 locked_ref = NULL;
2549 cond_resched();
2550 count++;
2551 continue;
2552 }
2553
2554 /*
2555 * record the must insert reserved flag before we
2556 * drop the spin lock.
2557 */
2558 must_insert_reserved = locked_ref->must_insert_reserved;
2559 locked_ref->must_insert_reserved = 0;
2560
2561 extent_op = locked_ref->extent_op;
2562 locked_ref->extent_op = NULL;
2563
2564 if (!ref) {
2565
2566
2567 /* All delayed refs have been processed, Go ahead
2568 * and send the head node to run_one_delayed_ref,
2569 * so that any accounting fixes can happen
2570 */
2571 ref = &locked_ref->node;
2572
2573 if (extent_op && must_insert_reserved) {
2574 btrfs_free_delayed_extent_op(extent_op);
2575 extent_op = NULL;
2576 }
2577
2578 if (extent_op) {
2579 spin_unlock(&locked_ref->lock);
2580 ret = run_delayed_extent_op(trans, root,
2581 ref, extent_op);
2582 btrfs_free_delayed_extent_op(extent_op);
2583
2584 if (ret) {
2585 /*
2586 * Need to reset must_insert_reserved if
2587 * there was an error so the abort stuff
2588 * can cleanup the reserved space
2589 * properly.
2590 */
2591 if (must_insert_reserved)
2592 locked_ref->must_insert_reserved = 1;
2593 locked_ref->processing = 0;
2594 btrfs_debug(fs_info,
2595 "run_delayed_extent_op returned %d",
2596 ret);
2597 btrfs_delayed_ref_unlock(locked_ref);
2598 return ret;
2599 }
2600 continue;
2601 }
2602
2603 /*
2604 * Need to drop our head ref lock and re-acquire the
2605 * delayed ref lock and then re-check to make sure
2606 * nobody got added.
2607 */
2608 spin_unlock(&locked_ref->lock);
2609 spin_lock(&delayed_refs->lock);
2610 spin_lock(&locked_ref->lock);
2611 if (!list_empty(&locked_ref->ref_list) ||
2612 locked_ref->extent_op) {
2613 spin_unlock(&locked_ref->lock);
2614 spin_unlock(&delayed_refs->lock);
2615 continue;
2616 }
2617 ref->in_tree = 0;
2618 delayed_refs->num_heads--;
2619 rb_erase(&locked_ref->href_node,
2620 &delayed_refs->href_root);
2621 spin_unlock(&delayed_refs->lock);
2622 } else {
2623 actual_count++;
2624 ref->in_tree = 0;
2625 list_del(&ref->list);
2626 if (!list_empty(&ref->add_list))
2627 list_del(&ref->add_list);
2628 }
2629 atomic_dec(&delayed_refs->num_entries);
2630
2631 if (!btrfs_delayed_ref_is_head(ref)) {
2632 /*
2633 * when we play the delayed ref, also correct the
2634 * ref_mod on head
2635 */
2636 switch (ref->action) {
2637 case BTRFS_ADD_DELAYED_REF:
2638 case BTRFS_ADD_DELAYED_EXTENT:
2639 locked_ref->node.ref_mod -= ref->ref_mod;
2640 break;
2641 case BTRFS_DROP_DELAYED_REF:
2642 locked_ref->node.ref_mod += ref->ref_mod;
2643 break;
2644 default:
2645 WARN_ON(1);
2646 }
2647 }
2648 spin_unlock(&locked_ref->lock);
2649
2650 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2651 must_insert_reserved);
2652
2653 btrfs_free_delayed_extent_op(extent_op);
2654 if (ret) {
2655 spin_lock(&delayed_refs->lock);
2656 locked_ref->processing = 0;
2657 delayed_refs->num_heads_ready++;
2658 spin_unlock(&delayed_refs->lock);
2659 btrfs_delayed_ref_unlock(locked_ref);
2660 btrfs_put_delayed_ref(ref);
2661 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2662 ret);
2663 return ret;
2664 }
2665
2666 /*
2667 * If this node is a head, that means all the refs in this head
2668 * have been dealt with, and we will pick the next head to deal
2669 * with, so we must unlock the head and drop it from the cluster
2670 * list before we release it.
2671 */
2672 if (btrfs_delayed_ref_is_head(ref)) {
2673 if (locked_ref->is_data &&
2674 locked_ref->total_ref_mod < 0) {
2675 spin_lock(&delayed_refs->lock);
2676 delayed_refs->pending_csums -= ref->num_bytes;
2677 spin_unlock(&delayed_refs->lock);
2678 }
2679 btrfs_delayed_ref_unlock(locked_ref);
2680 locked_ref = NULL;
2681 }
2682 btrfs_put_delayed_ref(ref);
2683 count++;
2684 cond_resched();
2685 }
2686
2687 /*
2688 * We don't want to include ref heads since we can have empty ref heads
2689 * and those will drastically skew our runtime down since we just do
2690 * accounting, no actual extent tree updates.
2691 */
2692 if (actual_count > 0) {
2693 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2694 u64 avg;
2695
2696 /*
2697 * We weigh the current average higher than our current runtime
2698 * to avoid large swings in the average.
2699 */
2700 spin_lock(&delayed_refs->lock);
2701 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2702 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2703 spin_unlock(&delayed_refs->lock);
2704 }
2705 return 0;
2706 }
2707
2708 #ifdef SCRAMBLE_DELAYED_REFS
2709 /*
2710 * Normally delayed refs get processed in ascending bytenr order. This
2711 * correlates in most cases to the order added. To expose dependencies on this
2712 * order, we start to process the tree in the middle instead of the beginning
2713 */
2714 static u64 find_middle(struct rb_root *root)
2715 {
2716 struct rb_node *n = root->rb_node;
2717 struct btrfs_delayed_ref_node *entry;
2718 int alt = 1;
2719 u64 middle;
2720 u64 first = 0, last = 0;
2721
2722 n = rb_first(root);
2723 if (n) {
2724 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2725 first = entry->bytenr;
2726 }
2727 n = rb_last(root);
2728 if (n) {
2729 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2730 last = entry->bytenr;
2731 }
2732 n = root->rb_node;
2733
2734 while (n) {
2735 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2736 WARN_ON(!entry->in_tree);
2737
2738 middle = entry->bytenr;
2739
2740 if (alt)
2741 n = n->rb_left;
2742 else
2743 n = n->rb_right;
2744
2745 alt = 1 - alt;
2746 }
2747 return middle;
2748 }
2749 #endif
2750
2751 static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
2752 {
2753 struct btrfs_fs_info *fs_info = root->fs_info;
2754 u64 num_bytes;
2755
2756 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2757 sizeof(struct btrfs_extent_inline_ref));
2758 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2759 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2760
2761 /*
2762 * We don't ever fill up leaves all the way so multiply by 2 just to be
2763 * closer to what we're really going to want to use.
2764 */
2765 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2766 }
2767
2768 /*
2769 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2770 * would require to store the csums for that many bytes.
2771 */
2772 u64 btrfs_csum_bytes_to_leaves(struct btrfs_root *root, u64 csum_bytes)
2773 {
2774 struct btrfs_fs_info *fs_info = root->fs_info;
2775 u64 csum_size;
2776 u64 num_csums_per_leaf;
2777 u64 num_csums;
2778
2779 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2780 num_csums_per_leaf = div64_u64(csum_size,
2781 (u64)btrfs_super_csum_size(fs_info->super_copy));
2782 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2783 num_csums += num_csums_per_leaf - 1;
2784 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2785 return num_csums;
2786 }
2787
2788 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2789 struct btrfs_root *root)
2790 {
2791 struct btrfs_fs_info *fs_info = root->fs_info;
2792 struct btrfs_block_rsv *global_rsv;
2793 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2794 u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2795 u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2796 u64 num_bytes, num_dirty_bgs_bytes;
2797 int ret = 0;
2798
2799 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2800 num_heads = heads_to_leaves(root, num_heads);
2801 if (num_heads > 1)
2802 num_bytes += (num_heads - 1) * fs_info->nodesize;
2803 num_bytes <<= 1;
2804 num_bytes += btrfs_csum_bytes_to_leaves(root, csum_bytes) * fs_info->nodesize;
2805 num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2806 num_dirty_bgs);
2807 global_rsv = &fs_info->global_block_rsv;
2808
2809 /*
2810 * If we can't allocate any more chunks lets make sure we have _lots_ of
2811 * wiggle room since running delayed refs can create more delayed refs.
2812 */
2813 if (global_rsv->space_info->full) {
2814 num_dirty_bgs_bytes <<= 1;
2815 num_bytes <<= 1;
2816 }
2817
2818 spin_lock(&global_rsv->lock);
2819 if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2820 ret = 1;
2821 spin_unlock(&global_rsv->lock);
2822 return ret;
2823 }
2824
2825 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2826 struct btrfs_root *root)
2827 {
2828 struct btrfs_fs_info *fs_info = root->fs_info;
2829 u64 num_entries =
2830 atomic_read(&trans->transaction->delayed_refs.num_entries);
2831 u64 avg_runtime;
2832 u64 val;
2833
2834 smp_mb();
2835 avg_runtime = fs_info->avg_delayed_ref_runtime;
2836 val = num_entries * avg_runtime;
2837 if (val >= NSEC_PER_SEC)
2838 return 1;
2839 if (val >= NSEC_PER_SEC / 2)
2840 return 2;
2841
2842 return btrfs_check_space_for_delayed_refs(trans, root);
2843 }
2844
2845 struct async_delayed_refs {
2846 struct btrfs_root *root;
2847 u64 transid;
2848 int count;
2849 int error;
2850 int sync;
2851 struct completion wait;
2852 struct btrfs_work work;
2853 };
2854
2855 static void delayed_ref_async_start(struct btrfs_work *work)
2856 {
2857 struct async_delayed_refs *async;
2858 struct btrfs_trans_handle *trans;
2859 int ret;
2860
2861 async = container_of(work, struct async_delayed_refs, work);
2862
2863 /* if the commit is already started, we don't need to wait here */
2864 if (btrfs_transaction_blocked(async->root->fs_info))
2865 goto done;
2866
2867 trans = btrfs_join_transaction(async->root);
2868 if (IS_ERR(trans)) {
2869 async->error = PTR_ERR(trans);
2870 goto done;
2871 }
2872
2873 /*
2874 * trans->sync means that when we call end_transaction, we won't
2875 * wait on delayed refs
2876 */
2877 trans->sync = true;
2878
2879 /* Don't bother flushing if we got into a different transaction */
2880 if (trans->transid > async->transid)
2881 goto end;
2882
2883 ret = btrfs_run_delayed_refs(trans, async->root, async->count);
2884 if (ret)
2885 async->error = ret;
2886 end:
2887 ret = btrfs_end_transaction(trans, async->root);
2888 if (ret && !async->error)
2889 async->error = ret;
2890 done:
2891 if (async->sync)
2892 complete(&async->wait);
2893 else
2894 kfree(async);
2895 }
2896
2897 int btrfs_async_run_delayed_refs(struct btrfs_root *root,
2898 unsigned long count, u64 transid, int wait)
2899 {
2900 struct btrfs_fs_info *fs_info = root->fs_info;
2901 struct async_delayed_refs *async;
2902 int ret;
2903
2904 async = kmalloc(sizeof(*async), GFP_NOFS);
2905 if (!async)
2906 return -ENOMEM;
2907
2908 async->root = fs_info->tree_root;
2909 async->count = count;
2910 async->error = 0;
2911 async->transid = transid;
2912 if (wait)
2913 async->sync = 1;
2914 else
2915 async->sync = 0;
2916 init_completion(&async->wait);
2917
2918 btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2919 delayed_ref_async_start, NULL, NULL);
2920
2921 btrfs_queue_work(fs_info->extent_workers, &async->work);
2922
2923 if (wait) {
2924 wait_for_completion(&async->wait);
2925 ret = async->error;
2926 kfree(async);
2927 return ret;
2928 }
2929 return 0;
2930 }
2931
2932 /*
2933 * this starts processing the delayed reference count updates and
2934 * extent insertions we have queued up so far. count can be
2935 * 0, which means to process everything in the tree at the start
2936 * of the run (but not newly added entries), or it can be some target
2937 * number you'd like to process.
2938 *
2939 * Returns 0 on success or if called with an aborted transaction
2940 * Returns <0 on error and aborts the transaction
2941 */
2942 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2943 struct btrfs_root *root, unsigned long count)
2944 {
2945 struct btrfs_fs_info *fs_info = root->fs_info;
2946 struct rb_node *node;
2947 struct btrfs_delayed_ref_root *delayed_refs;
2948 struct btrfs_delayed_ref_head *head;
2949 int ret;
2950 int run_all = count == (unsigned long)-1;
2951 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
2952
2953 /* We'll clean this up in btrfs_cleanup_transaction */
2954 if (trans->aborted)
2955 return 0;
2956
2957 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2958 return 0;
2959
2960 if (root == fs_info->extent_root)
2961 root = fs_info->tree_root;
2962
2963 delayed_refs = &trans->transaction->delayed_refs;
2964 if (count == 0)
2965 count = atomic_read(&delayed_refs->num_entries) * 2;
2966
2967 again:
2968 #ifdef SCRAMBLE_DELAYED_REFS
2969 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2970 #endif
2971 trans->can_flush_pending_bgs = false;
2972 ret = __btrfs_run_delayed_refs(trans, root, count);
2973 if (ret < 0) {
2974 btrfs_abort_transaction(trans, ret);
2975 return ret;
2976 }
2977
2978 if (run_all) {
2979 if (!list_empty(&trans->new_bgs))
2980 btrfs_create_pending_block_groups(trans, root);
2981
2982 spin_lock(&delayed_refs->lock);
2983 node = rb_first(&delayed_refs->href_root);
2984 if (!node) {
2985 spin_unlock(&delayed_refs->lock);
2986 goto out;
2987 }
2988
2989 while (node) {
2990 head = rb_entry(node, struct btrfs_delayed_ref_head,
2991 href_node);
2992 if (btrfs_delayed_ref_is_head(&head->node)) {
2993 struct btrfs_delayed_ref_node *ref;
2994
2995 ref = &head->node;
2996 atomic_inc(&ref->refs);
2997
2998 spin_unlock(&delayed_refs->lock);
2999 /*
3000 * Mutex was contended, block until it's
3001 * released and try again
3002 */
3003 mutex_lock(&head->mutex);
3004 mutex_unlock(&head->mutex);
3005
3006 btrfs_put_delayed_ref(ref);
3007 cond_resched();
3008 goto again;
3009 } else {
3010 WARN_ON(1);
3011 }
3012 node = rb_next(node);
3013 }
3014 spin_unlock(&delayed_refs->lock);
3015 cond_resched();
3016 goto again;
3017 }
3018 out:
3019 assert_qgroups_uptodate(trans);
3020 trans->can_flush_pending_bgs = can_flush_pending_bgs;
3021 return 0;
3022 }
3023
3024 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
3025 struct btrfs_root *root,
3026 u64 bytenr, u64 num_bytes, u64 flags,
3027 int level, int is_data)
3028 {
3029 struct btrfs_fs_info *fs_info = root->fs_info;
3030 struct btrfs_delayed_extent_op *extent_op;
3031 int ret;
3032
3033 extent_op = btrfs_alloc_delayed_extent_op();
3034 if (!extent_op)
3035 return -ENOMEM;
3036
3037 extent_op->flags_to_set = flags;
3038 extent_op->update_flags = true;
3039 extent_op->update_key = false;
3040 extent_op->is_data = is_data ? true : false;
3041 extent_op->level = level;
3042
3043 ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
3044 num_bytes, extent_op);
3045 if (ret)
3046 btrfs_free_delayed_extent_op(extent_op);
3047 return ret;
3048 }
3049
3050 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
3051 struct btrfs_root *root,
3052 struct btrfs_path *path,
3053 u64 objectid, u64 offset, u64 bytenr)
3054 {
3055 struct btrfs_delayed_ref_head *head;
3056 struct btrfs_delayed_ref_node *ref;
3057 struct btrfs_delayed_data_ref *data_ref;
3058 struct btrfs_delayed_ref_root *delayed_refs;
3059 int ret = 0;
3060
3061 delayed_refs = &trans->transaction->delayed_refs;
3062 spin_lock(&delayed_refs->lock);
3063 head = btrfs_find_delayed_ref_head(trans, bytenr);
3064 if (!head) {
3065 spin_unlock(&delayed_refs->lock);
3066 return 0;
3067 }
3068
3069 if (!mutex_trylock(&head->mutex)) {
3070 atomic_inc(&head->node.refs);
3071 spin_unlock(&delayed_refs->lock);
3072
3073 btrfs_release_path(path);
3074
3075 /*
3076 * Mutex was contended, block until it's released and let
3077 * caller try again
3078 */
3079 mutex_lock(&head->mutex);
3080 mutex_unlock(&head->mutex);
3081 btrfs_put_delayed_ref(&head->node);
3082 return -EAGAIN;
3083 }
3084 spin_unlock(&delayed_refs->lock);
3085
3086 spin_lock(&head->lock);
3087 list_for_each_entry(ref, &head->ref_list, list) {
3088 /* If it's a shared ref we know a cross reference exists */
3089 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3090 ret = 1;
3091 break;
3092 }
3093
3094 data_ref = btrfs_delayed_node_to_data_ref(ref);
3095
3096 /*
3097 * If our ref doesn't match the one we're currently looking at
3098 * then we have a cross reference.
3099 */
3100 if (data_ref->root != root->root_key.objectid ||
3101 data_ref->objectid != objectid ||
3102 data_ref->offset != offset) {
3103 ret = 1;
3104 break;
3105 }
3106 }
3107 spin_unlock(&head->lock);
3108 mutex_unlock(&head->mutex);
3109 return ret;
3110 }
3111
3112 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
3113 struct btrfs_root *root,
3114 struct btrfs_path *path,
3115 u64 objectid, u64 offset, u64 bytenr)
3116 {
3117 struct btrfs_fs_info *fs_info = root->fs_info;
3118 struct btrfs_root *extent_root = fs_info->extent_root;
3119 struct extent_buffer *leaf;
3120 struct btrfs_extent_data_ref *ref;
3121 struct btrfs_extent_inline_ref *iref;
3122 struct btrfs_extent_item *ei;
3123 struct btrfs_key key;
3124 u32 item_size;
3125 int ret;
3126
3127 key.objectid = bytenr;
3128 key.offset = (u64)-1;
3129 key.type = BTRFS_EXTENT_ITEM_KEY;
3130
3131 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3132 if (ret < 0)
3133 goto out;
3134 BUG_ON(ret == 0); /* Corruption */
3135
3136 ret = -ENOENT;
3137 if (path->slots[0] == 0)
3138 goto out;
3139
3140 path->slots[0]--;
3141 leaf = path->nodes[0];
3142 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3143
3144 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3145 goto out;
3146
3147 ret = 1;
3148 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3149 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3150 if (item_size < sizeof(*ei)) {
3151 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3152 goto out;
3153 }
3154 #endif
3155 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3156
3157 if (item_size != sizeof(*ei) +
3158 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3159 goto out;
3160
3161 if (btrfs_extent_generation(leaf, ei) <=
3162 btrfs_root_last_snapshot(&root->root_item))
3163 goto out;
3164
3165 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3166 if (btrfs_extent_inline_ref_type(leaf, iref) !=
3167 BTRFS_EXTENT_DATA_REF_KEY)
3168 goto out;
3169
3170 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3171 if (btrfs_extent_refs(leaf, ei) !=
3172 btrfs_extent_data_ref_count(leaf, ref) ||
3173 btrfs_extent_data_ref_root(leaf, ref) !=
3174 root->root_key.objectid ||
3175 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3176 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3177 goto out;
3178
3179 ret = 0;
3180 out:
3181 return ret;
3182 }
3183
3184 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
3185 struct btrfs_root *root,
3186 u64 objectid, u64 offset, u64 bytenr)
3187 {
3188 struct btrfs_path *path;
3189 int ret;
3190 int ret2;
3191
3192 path = btrfs_alloc_path();
3193 if (!path)
3194 return -ENOENT;
3195
3196 do {
3197 ret = check_committed_ref(trans, root, path, objectid,
3198 offset, bytenr);
3199 if (ret && ret != -ENOENT)
3200 goto out;
3201
3202 ret2 = check_delayed_ref(trans, root, path, objectid,
3203 offset, bytenr);
3204 } while (ret2 == -EAGAIN);
3205
3206 if (ret2 && ret2 != -ENOENT) {
3207 ret = ret2;
3208 goto out;
3209 }
3210
3211 if (ret != -ENOENT || ret2 != -ENOENT)
3212 ret = 0;
3213 out:
3214 btrfs_free_path(path);
3215 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3216 WARN_ON(ret > 0);
3217 return ret;
3218 }
3219
3220 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3221 struct btrfs_root *root,
3222 struct extent_buffer *buf,
3223 int full_backref, int inc)
3224 {
3225 struct btrfs_fs_info *fs_info = root->fs_info;
3226 u64 bytenr;
3227 u64 num_bytes;
3228 u64 parent;
3229 u64 ref_root;
3230 u32 nritems;
3231 struct btrfs_key key;
3232 struct btrfs_file_extent_item *fi;
3233 int i;
3234 int level;
3235 int ret = 0;
3236 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
3237 u64, u64, u64, u64, u64, u64);
3238
3239
3240 if (btrfs_is_testing(fs_info))
3241 return 0;
3242
3243 ref_root = btrfs_header_owner(buf);
3244 nritems = btrfs_header_nritems(buf);
3245 level = btrfs_header_level(buf);
3246
3247 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3248 return 0;
3249
3250 if (inc)
3251 process_func = btrfs_inc_extent_ref;
3252 else
3253 process_func = btrfs_free_extent;
3254
3255 if (full_backref)
3256 parent = buf->start;
3257 else
3258 parent = 0;
3259
3260 for (i = 0; i < nritems; i++) {
3261 if (level == 0) {
3262 btrfs_item_key_to_cpu(buf, &key, i);
3263 if (key.type != BTRFS_EXTENT_DATA_KEY)
3264 continue;
3265 fi = btrfs_item_ptr(buf, i,
3266 struct btrfs_file_extent_item);
3267 if (btrfs_file_extent_type(buf, fi) ==
3268 BTRFS_FILE_EXTENT_INLINE)
3269 continue;
3270 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3271 if (bytenr == 0)
3272 continue;
3273
3274 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3275 key.offset -= btrfs_file_extent_offset(buf, fi);
3276 ret = process_func(trans, root, bytenr, num_bytes,
3277 parent, ref_root, key.objectid,
3278 key.offset);
3279 if (ret)
3280 goto fail;
3281 } else {
3282 bytenr = btrfs_node_blockptr(buf, i);
3283 num_bytes = fs_info->nodesize;
3284 ret = process_func(trans, root, bytenr, num_bytes,
3285 parent, ref_root, level - 1, 0);
3286 if (ret)
3287 goto fail;
3288 }
3289 }
3290 return 0;
3291 fail:
3292 return ret;
3293 }
3294
3295 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3296 struct extent_buffer *buf, int full_backref)
3297 {
3298 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3299 }
3300
3301 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3302 struct extent_buffer *buf, int full_backref)
3303 {
3304 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3305 }
3306
3307 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3308 struct btrfs_root *root,
3309 struct btrfs_path *path,
3310 struct btrfs_block_group_cache *cache)
3311 {
3312 int ret;
3313 struct btrfs_fs_info *fs_info = root->fs_info;
3314 struct btrfs_root *extent_root = fs_info->extent_root;
3315 unsigned long bi;
3316 struct extent_buffer *leaf;
3317
3318 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3319 if (ret) {
3320 if (ret > 0)
3321 ret = -ENOENT;
3322 goto fail;
3323 }
3324
3325 leaf = path->nodes[0];
3326 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3327 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3328 btrfs_mark_buffer_dirty(leaf);
3329 fail:
3330 btrfs_release_path(path);
3331 return ret;
3332
3333 }
3334
3335 static struct btrfs_block_group_cache *
3336 next_block_group(struct btrfs_root *root,
3337 struct btrfs_block_group_cache *cache)
3338 {
3339 struct btrfs_fs_info *fs_info = root->fs_info;
3340 struct rb_node *node;
3341
3342 spin_lock(&fs_info->block_group_cache_lock);
3343
3344 /* If our block group was removed, we need a full search. */
3345 if (RB_EMPTY_NODE(&cache->cache_node)) {
3346 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3347
3348 spin_unlock(&fs_info->block_group_cache_lock);
3349 btrfs_put_block_group(cache);
3350 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3351 }
3352 node = rb_next(&cache->cache_node);
3353 btrfs_put_block_group(cache);
3354 if (node) {
3355 cache = rb_entry(node, struct btrfs_block_group_cache,
3356 cache_node);
3357 btrfs_get_block_group(cache);
3358 } else
3359 cache = NULL;
3360 spin_unlock(&fs_info->block_group_cache_lock);
3361 return cache;
3362 }
3363
3364 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3365 struct btrfs_trans_handle *trans,
3366 struct btrfs_path *path)
3367 {
3368 struct btrfs_fs_info *fs_info = block_group->fs_info;
3369 struct btrfs_root *root = fs_info->tree_root;
3370 struct inode *inode = NULL;
3371 u64 alloc_hint = 0;
3372 int dcs = BTRFS_DC_ERROR;
3373 u64 num_pages = 0;
3374 int retries = 0;
3375 int ret = 0;
3376
3377 /*
3378 * If this block group is smaller than 100 megs don't bother caching the
3379 * block group.
3380 */
3381 if (block_group->key.offset < (100 * SZ_1M)) {
3382 spin_lock(&block_group->lock);
3383 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3384 spin_unlock(&block_group->lock);
3385 return 0;
3386 }
3387
3388 if (trans->aborted)
3389 return 0;
3390 again:
3391 inode = lookup_free_space_inode(root, block_group, path);
3392 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3393 ret = PTR_ERR(inode);
3394 btrfs_release_path(path);
3395 goto out;
3396 }
3397
3398 if (IS_ERR(inode)) {
3399 BUG_ON(retries);
3400 retries++;
3401
3402 if (block_group->ro)
3403 goto out_free;
3404
3405 ret = create_free_space_inode(root, trans, block_group, path);
3406 if (ret)
3407 goto out_free;
3408 goto again;
3409 }
3410
3411 /* We've already setup this transaction, go ahead and exit */
3412 if (block_group->cache_generation == trans->transid &&
3413 i_size_read(inode)) {
3414 dcs = BTRFS_DC_SETUP;
3415 goto out_put;
3416 }
3417
3418 /*
3419 * We want to set the generation to 0, that way if anything goes wrong
3420 * from here on out we know not to trust this cache when we load up next
3421 * time.
3422 */
3423 BTRFS_I(inode)->generation = 0;
3424 ret = btrfs_update_inode(trans, root, inode);
3425 if (ret) {
3426 /*
3427 * So theoretically we could recover from this, simply set the
3428 * super cache generation to 0 so we know to invalidate the
3429 * cache, but then we'd have to keep track of the block groups
3430 * that fail this way so we know we _have_ to reset this cache
3431 * before the next commit or risk reading stale cache. So to
3432 * limit our exposure to horrible edge cases lets just abort the
3433 * transaction, this only happens in really bad situations
3434 * anyway.
3435 */
3436 btrfs_abort_transaction(trans, ret);
3437 goto out_put;
3438 }
3439 WARN_ON(ret);
3440
3441 if (i_size_read(inode) > 0) {
3442 ret = btrfs_check_trunc_cache_free_space(root,
3443 &fs_info->global_block_rsv);
3444 if (ret)
3445 goto out_put;
3446
3447 ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
3448 if (ret)
3449 goto out_put;
3450 }
3451
3452 spin_lock(&block_group->lock);
3453 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3454 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3455 /*
3456 * don't bother trying to write stuff out _if_
3457 * a) we're not cached,
3458 * b) we're with nospace_cache mount option.
3459 */
3460 dcs = BTRFS_DC_WRITTEN;
3461 spin_unlock(&block_group->lock);
3462 goto out_put;
3463 }
3464 spin_unlock(&block_group->lock);
3465
3466 /*
3467 * We hit an ENOSPC when setting up the cache in this transaction, just
3468 * skip doing the setup, we've already cleared the cache so we're safe.
3469 */
3470 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3471 ret = -ENOSPC;
3472 goto out_put;
3473 }
3474
3475 /*
3476 * Try to preallocate enough space based on how big the block group is.
3477 * Keep in mind this has to include any pinned space which could end up
3478 * taking up quite a bit since it's not folded into the other space
3479 * cache.
3480 */
3481 num_pages = div_u64(block_group->key.offset, SZ_256M);
3482 if (!num_pages)
3483 num_pages = 1;
3484
3485 num_pages *= 16;
3486 num_pages *= PAGE_SIZE;
3487
3488 ret = btrfs_check_data_free_space(inode, 0, num_pages);
3489 if (ret)
3490 goto out_put;
3491
3492 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3493 num_pages, num_pages,
3494 &alloc_hint);
3495 /*
3496 * Our cache requires contiguous chunks so that we don't modify a bunch
3497 * of metadata or split extents when writing the cache out, which means
3498 * we can enospc if we are heavily fragmented in addition to just normal
3499 * out of space conditions. So if we hit this just skip setting up any
3500 * other block groups for this transaction, maybe we'll unpin enough
3501 * space the next time around.
3502 */
3503 if (!ret)
3504 dcs = BTRFS_DC_SETUP;
3505 else if (ret == -ENOSPC)
3506 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3507
3508 out_put:
3509 iput(inode);
3510 out_free:
3511 btrfs_release_path(path);
3512 out:
3513 spin_lock(&block_group->lock);
3514 if (!ret && dcs == BTRFS_DC_SETUP)
3515 block_group->cache_generation = trans->transid;
3516 block_group->disk_cache_state = dcs;
3517 spin_unlock(&block_group->lock);
3518
3519 return ret;
3520 }
3521
3522 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3523 struct btrfs_root *root)
3524 {
3525 struct btrfs_fs_info *fs_info = root->fs_info;
3526 struct btrfs_block_group_cache *cache, *tmp;
3527 struct btrfs_transaction *cur_trans = trans->transaction;
3528 struct btrfs_path *path;
3529
3530 if (list_empty(&cur_trans->dirty_bgs) ||
3531 !btrfs_test_opt(fs_info, SPACE_CACHE))
3532 return 0;
3533
3534 path = btrfs_alloc_path();
3535 if (!path)
3536 return -ENOMEM;
3537
3538 /* Could add new block groups, use _safe just in case */
3539 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3540 dirty_list) {
3541 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3542 cache_save_setup(cache, trans, path);
3543 }
3544
3545 btrfs_free_path(path);
3546 return 0;
3547 }
3548
3549 /*
3550 * transaction commit does final block group cache writeback during a
3551 * critical section where nothing is allowed to change the FS. This is
3552 * required in order for the cache to actually match the block group,
3553 * but can introduce a lot of latency into the commit.
3554 *
3555 * So, btrfs_start_dirty_block_groups is here to kick off block group
3556 * cache IO. There's a chance we'll have to redo some of it if the
3557 * block group changes again during the commit, but it greatly reduces
3558 * the commit latency by getting rid of the easy block groups while
3559 * we're still allowing others to join the commit.
3560 */
3561 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
3562 struct btrfs_root *root)
3563 {
3564 struct btrfs_fs_info *fs_info = root->fs_info;
3565 struct btrfs_block_group_cache *cache;
3566 struct btrfs_transaction *cur_trans = trans->transaction;
3567 int ret = 0;
3568 int should_put;
3569 struct btrfs_path *path = NULL;
3570 LIST_HEAD(dirty);
3571 struct list_head *io = &cur_trans->io_bgs;
3572 int num_started = 0;
3573 int loops = 0;
3574
3575 spin_lock(&cur_trans->dirty_bgs_lock);
3576 if (list_empty(&cur_trans->dirty_bgs)) {
3577 spin_unlock(&cur_trans->dirty_bgs_lock);
3578 return 0;
3579 }
3580 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3581 spin_unlock(&cur_trans->dirty_bgs_lock);
3582
3583 again:
3584 /*
3585 * make sure all the block groups on our dirty list actually
3586 * exist
3587 */
3588 btrfs_create_pending_block_groups(trans, root);
3589
3590 if (!path) {
3591 path = btrfs_alloc_path();
3592 if (!path)
3593 return -ENOMEM;
3594 }
3595
3596 /*
3597 * cache_write_mutex is here only to save us from balance or automatic
3598 * removal of empty block groups deleting this block group while we are
3599 * writing out the cache
3600 */
3601 mutex_lock(&trans->transaction->cache_write_mutex);
3602 while (!list_empty(&dirty)) {
3603 cache = list_first_entry(&dirty,
3604 struct btrfs_block_group_cache,
3605 dirty_list);
3606 /*
3607 * this can happen if something re-dirties a block
3608 * group that is already under IO. Just wait for it to
3609 * finish and then do it all again
3610 */
3611 if (!list_empty(&cache->io_list)) {
3612 list_del_init(&cache->io_list);
3613 btrfs_wait_cache_io(trans, cache, path);
3614 btrfs_put_block_group(cache);
3615 }
3616
3617
3618 /*
3619 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3620 * if it should update the cache_state. Don't delete
3621 * until after we wait.
3622 *
3623 * Since we're not running in the commit critical section
3624 * we need the dirty_bgs_lock to protect from update_block_group
3625 */
3626 spin_lock(&cur_trans->dirty_bgs_lock);
3627 list_del_init(&cache->dirty_list);
3628 spin_unlock(&cur_trans->dirty_bgs_lock);
3629
3630 should_put = 1;
3631
3632 cache_save_setup(cache, trans, path);
3633
3634 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3635 cache->io_ctl.inode = NULL;
3636 ret = btrfs_write_out_cache(fs_info, trans,
3637 cache, path);
3638 if (ret == 0 && cache->io_ctl.inode) {
3639 num_started++;
3640 should_put = 0;
3641
3642 /*
3643 * the cache_write_mutex is protecting
3644 * the io_list
3645 */
3646 list_add_tail(&cache->io_list, io);
3647 } else {
3648 /*
3649 * if we failed to write the cache, the
3650 * generation will be bad and life goes on
3651 */
3652 ret = 0;
3653 }
3654 }
3655 if (!ret) {
3656 ret = write_one_cache_group(trans, root, path, cache);
3657 /*
3658 * Our block group might still be attached to the list
3659 * of new block groups in the transaction handle of some
3660 * other task (struct btrfs_trans_handle->new_bgs). This
3661 * means its block group item isn't yet in the extent
3662 * tree. If this happens ignore the error, as we will
3663 * try again later in the critical section of the
3664 * transaction commit.
3665 */
3666 if (ret == -ENOENT) {
3667 ret = 0;
3668 spin_lock(&cur_trans->dirty_bgs_lock);
3669 if (list_empty(&cache->dirty_list)) {
3670 list_add_tail(&cache->dirty_list,
3671 &cur_trans->dirty_bgs);
3672 btrfs_get_block_group(cache);
3673 }
3674 spin_unlock(&cur_trans->dirty_bgs_lock);
3675 } else if (ret) {
3676 btrfs_abort_transaction(trans, ret);
3677 }
3678 }
3679
3680 /* if its not on the io list, we need to put the block group */
3681 if (should_put)
3682 btrfs_put_block_group(cache);
3683
3684 if (ret)
3685 break;
3686
3687 /*
3688 * Avoid blocking other tasks for too long. It might even save
3689 * us from writing caches for block groups that are going to be
3690 * removed.
3691 */
3692 mutex_unlock(&trans->transaction->cache_write_mutex);
3693 mutex_lock(&trans->transaction->cache_write_mutex);
3694 }
3695 mutex_unlock(&trans->transaction->cache_write_mutex);
3696
3697 /*
3698 * go through delayed refs for all the stuff we've just kicked off
3699 * and then loop back (just once)
3700 */
3701 ret = btrfs_run_delayed_refs(trans, root, 0);
3702 if (!ret && loops == 0) {
3703 loops++;
3704 spin_lock(&cur_trans->dirty_bgs_lock);
3705 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3706 /*
3707 * dirty_bgs_lock protects us from concurrent block group
3708 * deletes too (not just cache_write_mutex).
3709 */
3710 if (!list_empty(&dirty)) {
3711 spin_unlock(&cur_trans->dirty_bgs_lock);
3712 goto again;
3713 }
3714 spin_unlock(&cur_trans->dirty_bgs_lock);
3715 } else if (ret < 0) {
3716 btrfs_cleanup_dirty_bgs(cur_trans, root);
3717 }
3718
3719 btrfs_free_path(path);
3720 return ret;
3721 }
3722
3723 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3724 struct btrfs_root *root)
3725 {
3726 struct btrfs_fs_info *fs_info = root->fs_info;
3727 struct btrfs_block_group_cache *cache;
3728 struct btrfs_transaction *cur_trans = trans->transaction;
3729 int ret = 0;
3730 int should_put;
3731 struct btrfs_path *path;
3732 struct list_head *io = &cur_trans->io_bgs;
3733 int num_started = 0;
3734
3735 path = btrfs_alloc_path();
3736 if (!path)
3737 return -ENOMEM;
3738
3739 /*
3740 * Even though we are in the critical section of the transaction commit,
3741 * we can still have concurrent tasks adding elements to this
3742 * transaction's list of dirty block groups. These tasks correspond to
3743 * endio free space workers started when writeback finishes for a
3744 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3745 * allocate new block groups as a result of COWing nodes of the root
3746 * tree when updating the free space inode. The writeback for the space
3747 * caches is triggered by an earlier call to
3748 * btrfs_start_dirty_block_groups() and iterations of the following
3749 * loop.
3750 * Also we want to do the cache_save_setup first and then run the
3751 * delayed refs to make sure we have the best chance at doing this all
3752 * in one shot.
3753 */
3754 spin_lock(&cur_trans->dirty_bgs_lock);
3755 while (!list_empty(&cur_trans->dirty_bgs)) {
3756 cache = list_first_entry(&cur_trans->dirty_bgs,
3757 struct btrfs_block_group_cache,
3758 dirty_list);
3759
3760 /*
3761 * this can happen if cache_save_setup re-dirties a block
3762 * group that is already under IO. Just wait for it to
3763 * finish and then do it all again
3764 */
3765 if (!list_empty(&cache->io_list)) {
3766 spin_unlock(&cur_trans->dirty_bgs_lock);
3767 list_del_init(&cache->io_list);
3768 btrfs_wait_cache_io(trans, cache, path);
3769 btrfs_put_block_group(cache);
3770 spin_lock(&cur_trans->dirty_bgs_lock);
3771 }
3772
3773 /*
3774 * don't remove from the dirty list until after we've waited
3775 * on any pending IO
3776 */
3777 list_del_init(&cache->dirty_list);
3778 spin_unlock(&cur_trans->dirty_bgs_lock);
3779 should_put = 1;
3780
3781 cache_save_setup(cache, trans, path);
3782
3783 if (!ret)
3784 ret = btrfs_run_delayed_refs(trans, root, (unsigned long) -1);
3785
3786 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3787 cache->io_ctl.inode = NULL;
3788 ret = btrfs_write_out_cache(fs_info, trans,
3789 cache, path);
3790 if (ret == 0 && cache->io_ctl.inode) {
3791 num_started++;
3792 should_put = 0;
3793 list_add_tail(&cache->io_list, io);
3794 } else {
3795 /*
3796 * if we failed to write the cache, the
3797 * generation will be bad and life goes on
3798 */
3799 ret = 0;
3800 }
3801 }
3802 if (!ret) {
3803 ret = write_one_cache_group(trans, root, path, cache);
3804 /*
3805 * One of the free space endio workers might have
3806 * created a new block group while updating a free space
3807 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3808 * and hasn't released its transaction handle yet, in
3809 * which case the new block group is still attached to
3810 * its transaction handle and its creation has not
3811 * finished yet (no block group item in the extent tree
3812 * yet, etc). If this is the case, wait for all free
3813 * space endio workers to finish and retry. This is a
3814 * a very rare case so no need for a more efficient and
3815 * complex approach.
3816 */
3817 if (ret == -ENOENT) {
3818 wait_event(cur_trans->writer_wait,
3819 atomic_read(&cur_trans->num_writers) == 1);
3820 ret = write_one_cache_group(trans, root, path,
3821 cache);
3822 }
3823 if (ret)
3824 btrfs_abort_transaction(trans, ret);
3825 }
3826
3827 /* if its not on the io list, we need to put the block group */
3828 if (should_put)
3829 btrfs_put_block_group(cache);
3830 spin_lock(&cur_trans->dirty_bgs_lock);
3831 }
3832 spin_unlock(&cur_trans->dirty_bgs_lock);
3833
3834 while (!list_empty(io)) {
3835 cache = list_first_entry(io, struct btrfs_block_group_cache,
3836 io_list);
3837 list_del_init(&cache->io_list);
3838 btrfs_wait_cache_io(trans, cache, path);
3839 btrfs_put_block_group(cache);
3840 }
3841
3842 btrfs_free_path(path);
3843 return ret;
3844 }
3845
3846 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3847 {
3848 struct btrfs_fs_info *fs_info = root->fs_info;
3849 struct btrfs_block_group_cache *block_group;
3850 int readonly = 0;
3851
3852 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3853 if (!block_group || block_group->ro)
3854 readonly = 1;
3855 if (block_group)
3856 btrfs_put_block_group(block_group);
3857 return readonly;
3858 }
3859
3860 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3861 {
3862 struct btrfs_block_group_cache *bg;
3863 bool ret = true;
3864
3865 bg = btrfs_lookup_block_group(fs_info, bytenr);
3866 if (!bg)
3867 return false;
3868
3869 spin_lock(&bg->lock);
3870 if (bg->ro)
3871 ret = false;
3872 else
3873 atomic_inc(&bg->nocow_writers);
3874 spin_unlock(&bg->lock);
3875
3876 /* no put on block group, done by btrfs_dec_nocow_writers */
3877 if (!ret)
3878 btrfs_put_block_group(bg);
3879
3880 return ret;
3881
3882 }
3883
3884 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3885 {
3886 struct btrfs_block_group_cache *bg;
3887
3888 bg = btrfs_lookup_block_group(fs_info, bytenr);
3889 ASSERT(bg);
3890 if (atomic_dec_and_test(&bg->nocow_writers))
3891 wake_up_atomic_t(&bg->nocow_writers);
3892 /*
3893 * Once for our lookup and once for the lookup done by a previous call
3894 * to btrfs_inc_nocow_writers()
3895 */
3896 btrfs_put_block_group(bg);
3897 btrfs_put_block_group(bg);
3898 }
3899
3900 static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
3901 {
3902 schedule();
3903 return 0;
3904 }
3905
3906 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3907 {
3908 wait_on_atomic_t(&bg->nocow_writers,
3909 btrfs_wait_nocow_writers_atomic_t,
3910 TASK_UNINTERRUPTIBLE);
3911 }
3912
3913 static const char *alloc_name(u64 flags)
3914 {
3915 switch (flags) {
3916 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3917 return "mixed";
3918 case BTRFS_BLOCK_GROUP_METADATA:
3919 return "metadata";
3920 case BTRFS_BLOCK_GROUP_DATA:
3921 return "data";
3922 case BTRFS_BLOCK_GROUP_SYSTEM:
3923 return "system";
3924 default:
3925 WARN_ON(1);
3926 return "invalid-combination";
3927 };
3928 }
3929
3930 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3931 u64 total_bytes, u64 bytes_used,
3932 u64 bytes_readonly,
3933 struct btrfs_space_info **space_info)
3934 {
3935 struct btrfs_space_info *found;
3936 int i;
3937 int factor;
3938 int ret;
3939
3940 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3941 BTRFS_BLOCK_GROUP_RAID10))
3942 factor = 2;
3943 else
3944 factor = 1;
3945
3946 found = __find_space_info(info, flags);
3947 if (found) {
3948 spin_lock(&found->lock);
3949 found->total_bytes += total_bytes;
3950 found->disk_total += total_bytes * factor;
3951 found->bytes_used += bytes_used;
3952 found->disk_used += bytes_used * factor;
3953 found->bytes_readonly += bytes_readonly;
3954 if (total_bytes > 0)
3955 found->full = 0;
3956 space_info_add_new_bytes(info, found, total_bytes -
3957 bytes_used - bytes_readonly);
3958 spin_unlock(&found->lock);
3959 *space_info = found;
3960 return 0;
3961 }
3962 found = kzalloc(sizeof(*found), GFP_NOFS);
3963 if (!found)
3964 return -ENOMEM;
3965
3966 ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
3967 if (ret) {
3968 kfree(found);
3969 return ret;
3970 }
3971
3972 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3973 INIT_LIST_HEAD(&found->block_groups[i]);
3974 init_rwsem(&found->groups_sem);
3975 spin_lock_init(&found->lock);
3976 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3977 found->total_bytes = total_bytes;
3978 found->disk_total = total_bytes * factor;
3979 found->bytes_used = bytes_used;
3980 found->disk_used = bytes_used * factor;
3981 found->bytes_pinned = 0;
3982 found->bytes_reserved = 0;
3983 found->bytes_readonly = bytes_readonly;
3984 found->bytes_may_use = 0;
3985 found->full = 0;
3986 found->max_extent_size = 0;
3987 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3988 found->chunk_alloc = 0;
3989 found->flush = 0;
3990 init_waitqueue_head(&found->wait);
3991 INIT_LIST_HEAD(&found->ro_bgs);
3992 INIT_LIST_HEAD(&found->tickets);
3993 INIT_LIST_HEAD(&found->priority_tickets);
3994
3995 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3996 info->space_info_kobj, "%s",
3997 alloc_name(found->flags));
3998 if (ret) {
3999 kfree(found);
4000 return ret;
4001 }
4002
4003 *space_info = found;
4004 list_add_rcu(&found->list, &info->space_info);
4005 if (flags & BTRFS_BLOCK_GROUP_DATA)
4006 info->data_sinfo = found;
4007
4008 return ret;
4009 }
4010
4011 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
4012 {
4013 u64 extra_flags = chunk_to_extended(flags) &
4014 BTRFS_EXTENDED_PROFILE_MASK;
4015
4016 write_seqlock(&fs_info->profiles_lock);
4017 if (flags & BTRFS_BLOCK_GROUP_DATA)
4018 fs_info->avail_data_alloc_bits |= extra_flags;
4019 if (flags & BTRFS_BLOCK_GROUP_METADATA)
4020 fs_info->avail_metadata_alloc_bits |= extra_flags;
4021 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4022 fs_info->avail_system_alloc_bits |= extra_flags;
4023 write_sequnlock(&fs_info->profiles_lock);
4024 }
4025
4026 /*
4027 * returns target flags in extended format or 0 if restripe for this
4028 * chunk_type is not in progress
4029 *
4030 * should be called with either volume_mutex or balance_lock held
4031 */
4032 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
4033 {
4034 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4035 u64 target = 0;
4036
4037 if (!bctl)
4038 return 0;
4039
4040 if (flags & BTRFS_BLOCK_GROUP_DATA &&
4041 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4042 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
4043 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
4044 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4045 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
4046 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
4047 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4048 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
4049 }
4050
4051 return target;
4052 }
4053
4054 /*
4055 * @flags: available profiles in extended format (see ctree.h)
4056 *
4057 * Returns reduced profile in chunk format. If profile changing is in
4058 * progress (either running or paused) picks the target profile (if it's
4059 * already available), otherwise falls back to plain reducing.
4060 */
4061 static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
4062 {
4063 struct btrfs_fs_info *fs_info = root->fs_info;
4064 u64 num_devices = fs_info->fs_devices->rw_devices;
4065 u64 target;
4066 u64 raid_type;
4067 u64 allowed = 0;
4068
4069 /*
4070 * see if restripe for this chunk_type is in progress, if so
4071 * try to reduce to the target profile
4072 */
4073 spin_lock(&fs_info->balance_lock);
4074 target = get_restripe_target(fs_info, flags);
4075 if (target) {
4076 /* pick target profile only if it's already available */
4077 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4078 spin_unlock(&fs_info->balance_lock);
4079 return extended_to_chunk(target);
4080 }
4081 }
4082 spin_unlock(&fs_info->balance_lock);
4083
4084 /* First, mask out the RAID levels which aren't possible */
4085 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4086 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4087 allowed |= btrfs_raid_group[raid_type];
4088 }
4089 allowed &= flags;
4090
4091 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4092 allowed = BTRFS_BLOCK_GROUP_RAID6;
4093 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4094 allowed = BTRFS_BLOCK_GROUP_RAID5;
4095 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4096 allowed = BTRFS_BLOCK_GROUP_RAID10;
4097 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4098 allowed = BTRFS_BLOCK_GROUP_RAID1;
4099 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4100 allowed = BTRFS_BLOCK_GROUP_RAID0;
4101
4102 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4103
4104 return extended_to_chunk(flags | allowed);
4105 }
4106
4107 static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
4108 {
4109 struct btrfs_fs_info *fs_info = root->fs_info;
4110 unsigned seq;
4111 u64 flags;
4112
4113 do {
4114 flags = orig_flags;
4115 seq = read_seqbegin(&fs_info->profiles_lock);
4116
4117 if (flags & BTRFS_BLOCK_GROUP_DATA)
4118 flags |= fs_info->avail_data_alloc_bits;
4119 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4120 flags |= fs_info->avail_system_alloc_bits;
4121 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4122 flags |= fs_info->avail_metadata_alloc_bits;
4123 } while (read_seqretry(&fs_info->profiles_lock, seq));
4124
4125 return btrfs_reduce_alloc_profile(root, flags);
4126 }
4127
4128 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
4129 {
4130 struct btrfs_fs_info *fs_info = root->fs_info;
4131 u64 flags;
4132 u64 ret;
4133
4134 if (data)
4135 flags = BTRFS_BLOCK_GROUP_DATA;
4136 else if (root == fs_info->chunk_root)
4137 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4138 else
4139 flags = BTRFS_BLOCK_GROUP_METADATA;
4140
4141 ret = get_alloc_profile(root, flags);
4142 return ret;
4143 }
4144
4145 int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
4146 {
4147 struct btrfs_space_info *data_sinfo;
4148 struct btrfs_root *root = BTRFS_I(inode)->root;
4149 struct btrfs_fs_info *fs_info = root->fs_info;
4150 u64 used;
4151 int ret = 0;
4152 int need_commit = 2;
4153 int have_pinned_space;
4154
4155 /* make sure bytes are sectorsize aligned */
4156 bytes = ALIGN(bytes, fs_info->sectorsize);
4157
4158 if (btrfs_is_free_space_inode(inode)) {
4159 need_commit = 0;
4160 ASSERT(current->journal_info);
4161 }
4162
4163 data_sinfo = fs_info->data_sinfo;
4164 if (!data_sinfo)
4165 goto alloc;
4166
4167 again:
4168 /* make sure we have enough space to handle the data first */
4169 spin_lock(&data_sinfo->lock);
4170 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
4171 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
4172 data_sinfo->bytes_may_use;
4173
4174 if (used + bytes > data_sinfo->total_bytes) {
4175 struct btrfs_trans_handle *trans;
4176
4177 /*
4178 * if we don't have enough free bytes in this space then we need
4179 * to alloc a new chunk.
4180 */
4181 if (!data_sinfo->full) {
4182 u64 alloc_target;
4183
4184 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4185 spin_unlock(&data_sinfo->lock);
4186 alloc:
4187 alloc_target = btrfs_get_alloc_profile(root, 1);
4188 /*
4189 * It is ugly that we don't call nolock join
4190 * transaction for the free space inode case here.
4191 * But it is safe because we only do the data space
4192 * reservation for the free space cache in the
4193 * transaction context, the common join transaction
4194 * just increase the counter of the current transaction
4195 * handler, doesn't try to acquire the trans_lock of
4196 * the fs.
4197 */
4198 trans = btrfs_join_transaction(root);
4199 if (IS_ERR(trans))
4200 return PTR_ERR(trans);
4201
4202 ret = do_chunk_alloc(trans, fs_info->extent_root,
4203 alloc_target,
4204 CHUNK_ALLOC_NO_FORCE);
4205 btrfs_end_transaction(trans, root);
4206 if (ret < 0) {
4207 if (ret != -ENOSPC)
4208 return ret;
4209 else {
4210 have_pinned_space = 1;
4211 goto commit_trans;
4212 }
4213 }
4214
4215 if (!data_sinfo)
4216 data_sinfo = fs_info->data_sinfo;
4217
4218 goto again;
4219 }
4220
4221 /*
4222 * If we don't have enough pinned space to deal with this
4223 * allocation, and no removed chunk in current transaction,
4224 * don't bother committing the transaction.
4225 */
4226 have_pinned_space = percpu_counter_compare(
4227 &data_sinfo->total_bytes_pinned,
4228 used + bytes - data_sinfo->total_bytes);
4229 spin_unlock(&data_sinfo->lock);
4230
4231 /* commit the current transaction and try again */
4232 commit_trans:
4233 if (need_commit &&
4234 !atomic_read(&fs_info->open_ioctl_trans)) {
4235 need_commit--;
4236
4237 if (need_commit > 0) {
4238 btrfs_start_delalloc_roots(fs_info, 0, -1);
4239 btrfs_wait_ordered_roots(fs_info, -1, 0,
4240 (u64)-1);
4241 }
4242
4243 trans = btrfs_join_transaction(root);
4244 if (IS_ERR(trans))
4245 return PTR_ERR(trans);
4246 if (have_pinned_space >= 0 ||
4247 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4248 &trans->transaction->flags) ||
4249 need_commit > 0) {
4250 ret = btrfs_commit_transaction(trans, root);
4251 if (ret)
4252 return ret;
4253 /*
4254 * The cleaner kthread might still be doing iput
4255 * operations. Wait for it to finish so that
4256 * more space is released.
4257 */
4258 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4259 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
4260 goto again;
4261 } else {
4262 btrfs_end_transaction(trans, root);
4263 }
4264 }
4265
4266 trace_btrfs_space_reservation(fs_info,
4267 "space_info:enospc",
4268 data_sinfo->flags, bytes, 1);
4269 return -ENOSPC;
4270 }
4271 data_sinfo->bytes_may_use += bytes;
4272 trace_btrfs_space_reservation(fs_info, "space_info",
4273 data_sinfo->flags, bytes, 1);
4274 spin_unlock(&data_sinfo->lock);
4275
4276 return ret;
4277 }
4278
4279 /*
4280 * New check_data_free_space() with ability for precious data reservation
4281 * Will replace old btrfs_check_data_free_space(), but for patch split,
4282 * add a new function first and then replace it.
4283 */
4284 int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4285 {
4286 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4287 int ret;
4288
4289 /* align the range */
4290 len = round_up(start + len, fs_info->sectorsize) -
4291 round_down(start, fs_info->sectorsize);
4292 start = round_down(start, fs_info->sectorsize);
4293
4294 ret = btrfs_alloc_data_chunk_ondemand(inode, len);
4295 if (ret < 0)
4296 return ret;
4297
4298 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4299 ret = btrfs_qgroup_reserve_data(inode, start, len);
4300 if (ret)
4301 btrfs_free_reserved_data_space_noquota(inode, start, len);
4302 return ret;
4303 }
4304
4305 /*
4306 * Called if we need to clear a data reservation for this inode
4307 * Normally in a error case.
4308 *
4309 * This one will *NOT* use accurate qgroup reserved space API, just for case
4310 * which we can't sleep and is sure it won't affect qgroup reserved space.
4311 * Like clear_bit_hook().
4312 */
4313 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4314 u64 len)
4315 {
4316 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4317 struct btrfs_space_info *data_sinfo;
4318
4319 /* Make sure the range is aligned to sectorsize */
4320 len = round_up(start + len, fs_info->sectorsize) -
4321 round_down(start, fs_info->sectorsize);
4322 start = round_down(start, fs_info->sectorsize);
4323
4324 data_sinfo = fs_info->data_sinfo;
4325 spin_lock(&data_sinfo->lock);
4326 if (WARN_ON(data_sinfo->bytes_may_use < len))
4327 data_sinfo->bytes_may_use = 0;
4328 else
4329 data_sinfo->bytes_may_use -= len;
4330 trace_btrfs_space_reservation(fs_info, "space_info",
4331 data_sinfo->flags, len, 0);
4332 spin_unlock(&data_sinfo->lock);
4333 }
4334
4335 /*
4336 * Called if we need to clear a data reservation for this inode
4337 * Normally in a error case.
4338 *
4339 * This one will handle the per-inode data rsv map for accurate reserved
4340 * space framework.
4341 */
4342 void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4343 {
4344 struct btrfs_root *root = BTRFS_I(inode)->root;
4345
4346 /* Make sure the range is aligned to sectorsize */
4347 len = round_up(start + len, root->fs_info->sectorsize) -
4348 round_down(start, root->fs_info->sectorsize);
4349 start = round_down(start, root->fs_info->sectorsize);
4350
4351 btrfs_free_reserved_data_space_noquota(inode, start, len);
4352 btrfs_qgroup_free_data(inode, start, len);
4353 }
4354
4355 static void force_metadata_allocation(struct btrfs_fs_info *info)
4356 {
4357 struct list_head *head = &info->space_info;
4358 struct btrfs_space_info *found;
4359
4360 rcu_read_lock();
4361 list_for_each_entry_rcu(found, head, list) {
4362 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4363 found->force_alloc = CHUNK_ALLOC_FORCE;
4364 }
4365 rcu_read_unlock();
4366 }
4367
4368 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4369 {
4370 return (global->size << 1);
4371 }
4372
4373 static int should_alloc_chunk(struct btrfs_root *root,
4374 struct btrfs_space_info *sinfo, int force)
4375 {
4376 struct btrfs_fs_info *fs_info = root->fs_info;
4377 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4378 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
4379 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
4380 u64 thresh;
4381
4382 if (force == CHUNK_ALLOC_FORCE)
4383 return 1;
4384
4385 /*
4386 * We need to take into account the global rsv because for all intents
4387 * and purposes it's used space. Don't worry about locking the
4388 * global_rsv, it doesn't change except when the transaction commits.
4389 */
4390 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4391 num_allocated += calc_global_rsv_need_space(global_rsv);
4392
4393 /*
4394 * in limited mode, we want to have some free space up to
4395 * about 1% of the FS size.
4396 */
4397 if (force == CHUNK_ALLOC_LIMITED) {
4398 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4399 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4400
4401 if (num_bytes - num_allocated < thresh)
4402 return 1;
4403 }
4404
4405 if (num_allocated + SZ_2M < div_factor(num_bytes, 8))
4406 return 0;
4407 return 1;
4408 }
4409
4410 static u64 get_profile_num_devs(struct btrfs_root *root, u64 type)
4411 {
4412 struct btrfs_fs_info *fs_info = root->fs_info;
4413 u64 num_dev;
4414
4415 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4416 BTRFS_BLOCK_GROUP_RAID0 |
4417 BTRFS_BLOCK_GROUP_RAID5 |
4418 BTRFS_BLOCK_GROUP_RAID6))
4419 num_dev = fs_info->fs_devices->rw_devices;
4420 else if (type & BTRFS_BLOCK_GROUP_RAID1)
4421 num_dev = 2;
4422 else
4423 num_dev = 1; /* DUP or single */
4424
4425 return num_dev;
4426 }
4427
4428 /*
4429 * If @is_allocation is true, reserve space in the system space info necessary
4430 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4431 * removing a chunk.
4432 */
4433 void check_system_chunk(struct btrfs_trans_handle *trans,
4434 struct btrfs_root *root,
4435 u64 type)
4436 {
4437 struct btrfs_fs_info *fs_info = root->fs_info;
4438 struct btrfs_space_info *info;
4439 u64 left;
4440 u64 thresh;
4441 int ret = 0;
4442 u64 num_devs;
4443
4444 /*
4445 * Needed because we can end up allocating a system chunk and for an
4446 * atomic and race free space reservation in the chunk block reserve.
4447 */
4448 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4449
4450 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4451 spin_lock(&info->lock);
4452 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
4453 info->bytes_reserved - info->bytes_readonly -
4454 info->bytes_may_use;
4455 spin_unlock(&info->lock);
4456
4457 num_devs = get_profile_num_devs(root, type);
4458
4459 /* num_devs device items to update and 1 chunk item to add or remove */
4460 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4461 btrfs_calc_trans_metadata_size(fs_info, 1);
4462
4463 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4464 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4465 left, thresh, type);
4466 dump_space_info(fs_info, info, 0, 0);
4467 }
4468
4469 if (left < thresh) {
4470 u64 flags;
4471
4472 flags = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4473 /*
4474 * Ignore failure to create system chunk. We might end up not
4475 * needing it, as we might not need to COW all nodes/leafs from
4476 * the paths we visit in the chunk tree (they were already COWed
4477 * or created in the current transaction for example).
4478 */
4479 ret = btrfs_alloc_chunk(trans, root, flags);
4480 }
4481
4482 if (!ret) {
4483 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4484 &fs_info->chunk_block_rsv,
4485 thresh, BTRFS_RESERVE_NO_FLUSH);
4486 if (!ret)
4487 trans->chunk_bytes_reserved += thresh;
4488 }
4489 }
4490
4491 /*
4492 * If force is CHUNK_ALLOC_FORCE:
4493 * - return 1 if it successfully allocates a chunk,
4494 * - return errors including -ENOSPC otherwise.
4495 * If force is NOT CHUNK_ALLOC_FORCE:
4496 * - return 0 if it doesn't need to allocate a new chunk,
4497 * - return 1 if it successfully allocates a chunk,
4498 * - return errors including -ENOSPC otherwise.
4499 */
4500 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
4501 struct btrfs_root *extent_root, u64 flags, int force)
4502 {
4503 struct btrfs_space_info *space_info;
4504 struct btrfs_fs_info *fs_info = extent_root->fs_info;
4505 int wait_for_alloc = 0;
4506 int ret = 0;
4507
4508 /* Don't re-enter if we're already allocating a chunk */
4509 if (trans->allocating_chunk)
4510 return -ENOSPC;
4511
4512 space_info = __find_space_info(fs_info, flags);
4513 if (!space_info) {
4514 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
4515 BUG_ON(ret); /* -ENOMEM */
4516 }
4517 BUG_ON(!space_info); /* Logic error */
4518
4519 again:
4520 spin_lock(&space_info->lock);
4521 if (force < space_info->force_alloc)
4522 force = space_info->force_alloc;
4523 if (space_info->full) {
4524 if (should_alloc_chunk(extent_root, space_info, force))
4525 ret = -ENOSPC;
4526 else
4527 ret = 0;
4528 spin_unlock(&space_info->lock);
4529 return ret;
4530 }
4531
4532 if (!should_alloc_chunk(extent_root, space_info, force)) {
4533 spin_unlock(&space_info->lock);
4534 return 0;
4535 } else if (space_info->chunk_alloc) {
4536 wait_for_alloc = 1;
4537 } else {
4538 space_info->chunk_alloc = 1;
4539 }
4540
4541 spin_unlock(&space_info->lock);
4542
4543 mutex_lock(&fs_info->chunk_mutex);
4544
4545 /*
4546 * The chunk_mutex is held throughout the entirety of a chunk
4547 * allocation, so once we've acquired the chunk_mutex we know that the
4548 * other guy is done and we need to recheck and see if we should
4549 * allocate.
4550 */
4551 if (wait_for_alloc) {
4552 mutex_unlock(&fs_info->chunk_mutex);
4553 wait_for_alloc = 0;
4554 goto again;
4555 }
4556
4557 trans->allocating_chunk = true;
4558
4559 /*
4560 * If we have mixed data/metadata chunks we want to make sure we keep
4561 * allocating mixed chunks instead of individual chunks.
4562 */
4563 if (btrfs_mixed_space_info(space_info))
4564 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4565
4566 /*
4567 * if we're doing a data chunk, go ahead and make sure that
4568 * we keep a reasonable number of metadata chunks allocated in the
4569 * FS as well.
4570 */
4571 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4572 fs_info->data_chunk_allocations++;
4573 if (!(fs_info->data_chunk_allocations %
4574 fs_info->metadata_ratio))
4575 force_metadata_allocation(fs_info);
4576 }
4577
4578 /*
4579 * Check if we have enough space in SYSTEM chunk because we may need
4580 * to update devices.
4581 */
4582 check_system_chunk(trans, extent_root, flags);
4583
4584 ret = btrfs_alloc_chunk(trans, extent_root, flags);
4585 trans->allocating_chunk = false;
4586
4587 spin_lock(&space_info->lock);
4588 if (ret < 0 && ret != -ENOSPC)
4589 goto out;
4590 if (ret)
4591 space_info->full = 1;
4592 else
4593 ret = 1;
4594
4595 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4596 out:
4597 space_info->chunk_alloc = 0;
4598 spin_unlock(&space_info->lock);
4599 mutex_unlock(&fs_info->chunk_mutex);
4600 /*
4601 * When we allocate a new chunk we reserve space in the chunk block
4602 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4603 * add new nodes/leafs to it if we end up needing to do it when
4604 * inserting the chunk item and updating device items as part of the
4605 * second phase of chunk allocation, performed by
4606 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4607 * large number of new block groups to create in our transaction
4608 * handle's new_bgs list to avoid exhausting the chunk block reserve
4609 * in extreme cases - like having a single transaction create many new
4610 * block groups when starting to write out the free space caches of all
4611 * the block groups that were made dirty during the lifetime of the
4612 * transaction.
4613 */
4614 if (trans->can_flush_pending_bgs &&
4615 trans->chunk_bytes_reserved >= (u64)SZ_2M) {
4616 btrfs_create_pending_block_groups(trans, extent_root);
4617 btrfs_trans_release_chunk_metadata(trans);
4618 }
4619 return ret;
4620 }
4621
4622 static int can_overcommit(struct btrfs_root *root,
4623 struct btrfs_space_info *space_info, u64 bytes,
4624 enum btrfs_reserve_flush_enum flush)
4625 {
4626 struct btrfs_fs_info *fs_info = root->fs_info;
4627 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4628 u64 profile;
4629 u64 space_size;
4630 u64 avail;
4631 u64 used;
4632
4633 /* Don't overcommit when in mixed mode. */
4634 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4635 return 0;
4636
4637 profile = btrfs_get_alloc_profile(root, 0);
4638 used = space_info->bytes_used + space_info->bytes_reserved +
4639 space_info->bytes_pinned + space_info->bytes_readonly;
4640
4641 /*
4642 * We only want to allow over committing if we have lots of actual space
4643 * free, but if we don't have enough space to handle the global reserve
4644 * space then we could end up having a real enospc problem when trying
4645 * to allocate a chunk or some other such important allocation.
4646 */
4647 spin_lock(&global_rsv->lock);
4648 space_size = calc_global_rsv_need_space(global_rsv);
4649 spin_unlock(&global_rsv->lock);
4650 if (used + space_size >= space_info->total_bytes)
4651 return 0;
4652
4653 used += space_info->bytes_may_use;
4654
4655 spin_lock(&fs_info->free_chunk_lock);
4656 avail = fs_info->free_chunk_space;
4657 spin_unlock(&fs_info->free_chunk_lock);
4658
4659 /*
4660 * If we have dup, raid1 or raid10 then only half of the free
4661 * space is actually useable. For raid56, the space info used
4662 * doesn't include the parity drive, so we don't have to
4663 * change the math
4664 */
4665 if (profile & (BTRFS_BLOCK_GROUP_DUP |
4666 BTRFS_BLOCK_GROUP_RAID1 |
4667 BTRFS_BLOCK_GROUP_RAID10))
4668 avail >>= 1;
4669
4670 /*
4671 * If we aren't flushing all things, let us overcommit up to
4672 * 1/2th of the space. If we can flush, don't let us overcommit
4673 * too much, let it overcommit up to 1/8 of the space.
4674 */
4675 if (flush == BTRFS_RESERVE_FLUSH_ALL)
4676 avail >>= 3;
4677 else
4678 avail >>= 1;
4679
4680 if (used + bytes < space_info->total_bytes + avail)
4681 return 1;
4682 return 0;
4683 }
4684
4685 static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
4686 unsigned long nr_pages, int nr_items)
4687 {
4688 struct btrfs_fs_info *fs_info = root->fs_info;
4689 struct super_block *sb = fs_info->sb;
4690
4691 if (down_read_trylock(&sb->s_umount)) {
4692 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4693 up_read(&sb->s_umount);
4694 } else {
4695 /*
4696 * We needn't worry the filesystem going from r/w to r/o though
4697 * we don't acquire ->s_umount mutex, because the filesystem
4698 * should guarantee the delalloc inodes list be empty after
4699 * the filesystem is readonly(all dirty pages are written to
4700 * the disk).
4701 */
4702 btrfs_start_delalloc_roots(fs_info, 0, nr_items);
4703 if (!current->journal_info)
4704 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4705 }
4706 }
4707
4708 static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
4709 {
4710 u64 bytes;
4711 int nr;
4712
4713 bytes = btrfs_calc_trans_metadata_size(root->fs_info, 1);
4714 nr = (int)div64_u64(to_reclaim, bytes);
4715 if (!nr)
4716 nr = 1;
4717 return nr;
4718 }
4719
4720 #define EXTENT_SIZE_PER_ITEM SZ_256K
4721
4722 /*
4723 * shrink metadata reservation for delalloc
4724 */
4725 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4726 bool wait_ordered)
4727 {
4728 struct btrfs_fs_info *fs_info = root->fs_info;
4729 struct btrfs_block_rsv *block_rsv;
4730 struct btrfs_space_info *space_info;
4731 struct btrfs_trans_handle *trans;
4732 u64 delalloc_bytes;
4733 u64 max_reclaim;
4734 long time_left;
4735 unsigned long nr_pages;
4736 int loops;
4737 int items;
4738 enum btrfs_reserve_flush_enum flush;
4739
4740 /* Calc the number of the pages we need flush for space reservation */
4741 items = calc_reclaim_items_nr(root, to_reclaim);
4742 to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
4743
4744 trans = (struct btrfs_trans_handle *)current->journal_info;
4745 block_rsv = &fs_info->delalloc_block_rsv;
4746 space_info = block_rsv->space_info;
4747
4748 delalloc_bytes = percpu_counter_sum_positive(
4749 &fs_info->delalloc_bytes);
4750 if (delalloc_bytes == 0) {
4751 if (trans)
4752 return;
4753 if (wait_ordered)
4754 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4755 return;
4756 }
4757
4758 loops = 0;
4759 while (delalloc_bytes && loops < 3) {
4760 max_reclaim = min(delalloc_bytes, to_reclaim);
4761 nr_pages = max_reclaim >> PAGE_SHIFT;
4762 btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
4763 /*
4764 * We need to wait for the async pages to actually start before
4765 * we do anything.
4766 */
4767 max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
4768 if (!max_reclaim)
4769 goto skip_async;
4770
4771 if (max_reclaim <= nr_pages)
4772 max_reclaim = 0;
4773 else
4774 max_reclaim -= nr_pages;
4775
4776 wait_event(fs_info->async_submit_wait,
4777 atomic_read(&fs_info->async_delalloc_pages) <=
4778 (int)max_reclaim);
4779 skip_async:
4780 if (!trans)
4781 flush = BTRFS_RESERVE_FLUSH_ALL;
4782 else
4783 flush = BTRFS_RESERVE_NO_FLUSH;
4784 spin_lock(&space_info->lock);
4785 if (can_overcommit(root, space_info, orig, flush)) {
4786 spin_unlock(&space_info->lock);
4787 break;
4788 }
4789 if (list_empty(&space_info->tickets) &&
4790 list_empty(&space_info->priority_tickets)) {
4791 spin_unlock(&space_info->lock);
4792 break;
4793 }
4794 spin_unlock(&space_info->lock);
4795
4796 loops++;
4797 if (wait_ordered && !trans) {
4798 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4799 } else {
4800 time_left = schedule_timeout_killable(1);
4801 if (time_left)
4802 break;
4803 }
4804 delalloc_bytes = percpu_counter_sum_positive(
4805 &fs_info->delalloc_bytes);
4806 }
4807 }
4808
4809 /**
4810 * maybe_commit_transaction - possibly commit the transaction if its ok to
4811 * @root - the root we're allocating for
4812 * @bytes - the number of bytes we want to reserve
4813 * @force - force the commit
4814 *
4815 * This will check to make sure that committing the transaction will actually
4816 * get us somewhere and then commit the transaction if it does. Otherwise it
4817 * will return -ENOSPC.
4818 */
4819 static int may_commit_transaction(struct btrfs_root *root,
4820 struct btrfs_space_info *space_info,
4821 u64 bytes, int force)
4822 {
4823 struct btrfs_fs_info *fs_info = root->fs_info;
4824 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4825 struct btrfs_trans_handle *trans;
4826
4827 trans = (struct btrfs_trans_handle *)current->journal_info;
4828 if (trans)
4829 return -EAGAIN;
4830
4831 if (force)
4832 goto commit;
4833
4834 /* See if there is enough pinned space to make this reservation */
4835 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4836 bytes) >= 0)
4837 goto commit;
4838
4839 /*
4840 * See if there is some space in the delayed insertion reservation for
4841 * this reservation.
4842 */
4843 if (space_info != delayed_rsv->space_info)
4844 return -ENOSPC;
4845
4846 spin_lock(&delayed_rsv->lock);
4847 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4848 bytes - delayed_rsv->size) >= 0) {
4849 spin_unlock(&delayed_rsv->lock);
4850 return -ENOSPC;
4851 }
4852 spin_unlock(&delayed_rsv->lock);
4853
4854 commit:
4855 trans = btrfs_join_transaction(root);
4856 if (IS_ERR(trans))
4857 return -ENOSPC;
4858
4859 return btrfs_commit_transaction(trans, root);
4860 }
4861
4862 struct reserve_ticket {
4863 u64 bytes;
4864 int error;
4865 struct list_head list;
4866 wait_queue_head_t wait;
4867 };
4868
4869 static int flush_space(struct btrfs_root *root,
4870 struct btrfs_space_info *space_info, u64 num_bytes,
4871 u64 orig_bytes, int state)
4872 {
4873 struct btrfs_fs_info *fs_info = root->fs_info;
4874 struct btrfs_trans_handle *trans;
4875 int nr;
4876 int ret = 0;
4877
4878 switch (state) {
4879 case FLUSH_DELAYED_ITEMS_NR:
4880 case FLUSH_DELAYED_ITEMS:
4881 if (state == FLUSH_DELAYED_ITEMS_NR)
4882 nr = calc_reclaim_items_nr(root, num_bytes) * 2;
4883 else
4884 nr = -1;
4885
4886 trans = btrfs_join_transaction(root);
4887 if (IS_ERR(trans)) {
4888 ret = PTR_ERR(trans);
4889 break;
4890 }
4891 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4892 btrfs_end_transaction(trans, root);
4893 break;
4894 case FLUSH_DELALLOC:
4895 case FLUSH_DELALLOC_WAIT:
4896 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4897 state == FLUSH_DELALLOC_WAIT);
4898 break;
4899 case ALLOC_CHUNK:
4900 trans = btrfs_join_transaction(root);
4901 if (IS_ERR(trans)) {
4902 ret = PTR_ERR(trans);
4903 break;
4904 }
4905 ret = do_chunk_alloc(trans, fs_info->extent_root,
4906 btrfs_get_alloc_profile(root, 0),
4907 CHUNK_ALLOC_NO_FORCE);
4908 btrfs_end_transaction(trans, root);
4909 if (ret > 0 || ret == -ENOSPC)
4910 ret = 0;
4911 break;
4912 case COMMIT_TRANS:
4913 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4914 break;
4915 default:
4916 ret = -ENOSPC;
4917 break;
4918 }
4919
4920 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes,
4921 orig_bytes, state, ret);
4922 return ret;
4923 }
4924
4925 static inline u64
4926 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4927 struct btrfs_space_info *space_info)
4928 {
4929 struct reserve_ticket *ticket;
4930 u64 used;
4931 u64 expected;
4932 u64 to_reclaim = 0;
4933
4934 list_for_each_entry(ticket, &space_info->tickets, list)
4935 to_reclaim += ticket->bytes;
4936 list_for_each_entry(ticket, &space_info->priority_tickets, list)
4937 to_reclaim += ticket->bytes;
4938 if (to_reclaim)
4939 return to_reclaim;
4940
4941 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4942 if (can_overcommit(root, space_info, to_reclaim,
4943 BTRFS_RESERVE_FLUSH_ALL))
4944 return 0;
4945
4946 used = space_info->bytes_used + space_info->bytes_reserved +
4947 space_info->bytes_pinned + space_info->bytes_readonly +
4948 space_info->bytes_may_use;
4949 if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
4950 expected = div_factor_fine(space_info->total_bytes, 95);
4951 else
4952 expected = div_factor_fine(space_info->total_bytes, 90);
4953
4954 if (used > expected)
4955 to_reclaim = used - expected;
4956 else
4957 to_reclaim = 0;
4958 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4959 space_info->bytes_reserved);
4960 return to_reclaim;
4961 }
4962
4963 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4964 struct btrfs_root *root, u64 used)
4965 {
4966 struct btrfs_fs_info *fs_info = root->fs_info;
4967 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4968
4969 /* If we're just plain full then async reclaim just slows us down. */
4970 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4971 return 0;
4972
4973 if (!btrfs_calc_reclaim_metadata_size(root, space_info))
4974 return 0;
4975
4976 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4977 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4978 }
4979
4980 static void wake_all_tickets(struct list_head *head)
4981 {
4982 struct reserve_ticket *ticket;
4983
4984 while (!list_empty(head)) {
4985 ticket = list_first_entry(head, struct reserve_ticket, list);
4986 list_del_init(&ticket->list);
4987 ticket->error = -ENOSPC;
4988 wake_up(&ticket->wait);
4989 }
4990 }
4991
4992 /*
4993 * This is for normal flushers, we can wait all goddamned day if we want to. We
4994 * will loop and continuously try to flush as long as we are making progress.
4995 * We count progress as clearing off tickets each time we have to loop.
4996 */
4997 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4998 {
4999 struct btrfs_fs_info *fs_info;
5000 struct btrfs_space_info *space_info;
5001 u64 to_reclaim;
5002 int flush_state;
5003 int commit_cycles = 0;
5004 u64 last_tickets_id;
5005
5006 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
5007 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5008
5009 spin_lock(&space_info->lock);
5010 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5011 space_info);
5012 if (!to_reclaim) {
5013 space_info->flush = 0;
5014 spin_unlock(&space_info->lock);
5015 return;
5016 }
5017 last_tickets_id = space_info->tickets_id;
5018 spin_unlock(&space_info->lock);
5019
5020 flush_state = FLUSH_DELAYED_ITEMS_NR;
5021 do {
5022 struct reserve_ticket *ticket;
5023 int ret;
5024
5025 ret = flush_space(fs_info->fs_root, space_info, to_reclaim,
5026 to_reclaim, flush_state);
5027 spin_lock(&space_info->lock);
5028 if (list_empty(&space_info->tickets)) {
5029 space_info->flush = 0;
5030 spin_unlock(&space_info->lock);
5031 return;
5032 }
5033 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5034 space_info);
5035 ticket = list_first_entry(&space_info->tickets,
5036 struct reserve_ticket, list);
5037 if (last_tickets_id == space_info->tickets_id) {
5038 flush_state++;
5039 } else {
5040 last_tickets_id = space_info->tickets_id;
5041 flush_state = FLUSH_DELAYED_ITEMS_NR;
5042 if (commit_cycles)
5043 commit_cycles--;
5044 }
5045
5046 if (flush_state > COMMIT_TRANS) {
5047 commit_cycles++;
5048 if (commit_cycles > 2) {
5049 wake_all_tickets(&space_info->tickets);
5050 space_info->flush = 0;
5051 } else {
5052 flush_state = FLUSH_DELAYED_ITEMS_NR;
5053 }
5054 }
5055 spin_unlock(&space_info->lock);
5056 } while (flush_state <= COMMIT_TRANS);
5057 }
5058
5059 void btrfs_init_async_reclaim_work(struct work_struct *work)
5060 {
5061 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5062 }
5063
5064 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5065 struct btrfs_space_info *space_info,
5066 struct reserve_ticket *ticket)
5067 {
5068 u64 to_reclaim;
5069 int flush_state = FLUSH_DELAYED_ITEMS_NR;
5070
5071 spin_lock(&space_info->lock);
5072 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5073 space_info);
5074 if (!to_reclaim) {
5075 spin_unlock(&space_info->lock);
5076 return;
5077 }
5078 spin_unlock(&space_info->lock);
5079
5080 do {
5081 flush_space(fs_info->fs_root, space_info, to_reclaim,
5082 to_reclaim, flush_state);
5083 flush_state++;
5084 spin_lock(&space_info->lock);
5085 if (ticket->bytes == 0) {
5086 spin_unlock(&space_info->lock);
5087 return;
5088 }
5089 spin_unlock(&space_info->lock);
5090
5091 /*
5092 * Priority flushers can't wait on delalloc without
5093 * deadlocking.
5094 */
5095 if (flush_state == FLUSH_DELALLOC ||
5096 flush_state == FLUSH_DELALLOC_WAIT)
5097 flush_state = ALLOC_CHUNK;
5098 } while (flush_state < COMMIT_TRANS);
5099 }
5100
5101 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5102 struct btrfs_space_info *space_info,
5103 struct reserve_ticket *ticket, u64 orig_bytes)
5104
5105 {
5106 DEFINE_WAIT(wait);
5107 int ret = 0;
5108
5109 spin_lock(&space_info->lock);
5110 while (ticket->bytes > 0 && ticket->error == 0) {
5111 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5112 if (ret) {
5113 ret = -EINTR;
5114 break;
5115 }
5116 spin_unlock(&space_info->lock);
5117
5118 schedule();
5119
5120 finish_wait(&ticket->wait, &wait);
5121 spin_lock(&space_info->lock);
5122 }
5123 if (!ret)
5124 ret = ticket->error;
5125 if (!list_empty(&ticket->list))
5126 list_del_init(&ticket->list);
5127 if (ticket->bytes && ticket->bytes < orig_bytes) {
5128 u64 num_bytes = orig_bytes - ticket->bytes;
5129 space_info->bytes_may_use -= num_bytes;
5130 trace_btrfs_space_reservation(fs_info, "space_info",
5131 space_info->flags, num_bytes, 0);
5132 }
5133 spin_unlock(&space_info->lock);
5134
5135 return ret;
5136 }
5137
5138 /**
5139 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5140 * @root - the root we're allocating for
5141 * @space_info - the space info we want to allocate from
5142 * @orig_bytes - the number of bytes we want
5143 * @flush - whether or not we can flush to make our reservation
5144 *
5145 * This will reserve orig_bytes number of bytes from the space info associated
5146 * with the block_rsv. If there is not enough space it will make an attempt to
5147 * flush out space to make room. It will do this by flushing delalloc if
5148 * possible or committing the transaction. If flush is 0 then no attempts to
5149 * regain reservations will be made and this will fail if there is not enough
5150 * space already.
5151 */
5152 static int __reserve_metadata_bytes(struct btrfs_root *root,
5153 struct btrfs_space_info *space_info,
5154 u64 orig_bytes,
5155 enum btrfs_reserve_flush_enum flush)
5156 {
5157 struct btrfs_fs_info *fs_info = root->fs_info;
5158 struct reserve_ticket ticket;
5159 u64 used;
5160 int ret = 0;
5161
5162 ASSERT(orig_bytes);
5163 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5164
5165 spin_lock(&space_info->lock);
5166 ret = -ENOSPC;
5167 used = space_info->bytes_used + space_info->bytes_reserved +
5168 space_info->bytes_pinned + space_info->bytes_readonly +
5169 space_info->bytes_may_use;
5170
5171 /*
5172 * If we have enough space then hooray, make our reservation and carry
5173 * on. If not see if we can overcommit, and if we can, hooray carry on.
5174 * If not things get more complicated.
5175 */
5176 if (used + orig_bytes <= space_info->total_bytes) {
5177 space_info->bytes_may_use += orig_bytes;
5178 trace_btrfs_space_reservation(fs_info, "space_info",
5179 space_info->flags, orig_bytes, 1);
5180 ret = 0;
5181 } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
5182 space_info->bytes_may_use += orig_bytes;
5183 trace_btrfs_space_reservation(fs_info, "space_info",
5184 space_info->flags, orig_bytes, 1);
5185 ret = 0;
5186 }
5187
5188 /*
5189 * If we couldn't make a reservation then setup our reservation ticket
5190 * and kick the async worker if it's not already running.
5191 *
5192 * If we are a priority flusher then we just need to add our ticket to
5193 * the list and we will do our own flushing further down.
5194 */
5195 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5196 ticket.bytes = orig_bytes;
5197 ticket.error = 0;
5198 init_waitqueue_head(&ticket.wait);
5199 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5200 list_add_tail(&ticket.list, &space_info->tickets);
5201 if (!space_info->flush) {
5202 space_info->flush = 1;
5203 trace_btrfs_trigger_flush(fs_info,
5204 space_info->flags,
5205 orig_bytes, flush,
5206 "enospc");
5207 queue_work(system_unbound_wq,
5208 &root->fs_info->async_reclaim_work);
5209 }
5210 } else {
5211 list_add_tail(&ticket.list,
5212 &space_info->priority_tickets);
5213 }
5214 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5215 used += orig_bytes;
5216 /*
5217 * We will do the space reservation dance during log replay,
5218 * which means we won't have fs_info->fs_root set, so don't do
5219 * the async reclaim as we will panic.
5220 */
5221 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5222 need_do_async_reclaim(space_info, root, used) &&
5223 !work_busy(&fs_info->async_reclaim_work)) {
5224 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5225 orig_bytes, flush, "preempt");
5226 queue_work(system_unbound_wq,
5227 &fs_info->async_reclaim_work);
5228 }
5229 }
5230 spin_unlock(&space_info->lock);
5231 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5232 return ret;
5233
5234 if (flush == BTRFS_RESERVE_FLUSH_ALL)
5235 return wait_reserve_ticket(fs_info, space_info, &ticket,
5236 orig_bytes);
5237
5238 ret = 0;
5239 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5240 spin_lock(&space_info->lock);
5241 if (ticket.bytes) {
5242 if (ticket.bytes < orig_bytes) {
5243 u64 num_bytes = orig_bytes - ticket.bytes;
5244 space_info->bytes_may_use -= num_bytes;
5245 trace_btrfs_space_reservation(fs_info, "space_info",
5246 space_info->flags,
5247 num_bytes, 0);
5248
5249 }
5250 list_del_init(&ticket.list);
5251 ret = -ENOSPC;
5252 }
5253 spin_unlock(&space_info->lock);
5254 ASSERT(list_empty(&ticket.list));
5255 return ret;
5256 }
5257
5258 /**
5259 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5260 * @root - the root we're allocating for
5261 * @block_rsv - the block_rsv we're allocating for
5262 * @orig_bytes - the number of bytes we want
5263 * @flush - whether or not we can flush to make our reservation
5264 *
5265 * This will reserve orgi_bytes number of bytes from the space info associated
5266 * with the block_rsv. If there is not enough space it will make an attempt to
5267 * flush out space to make room. It will do this by flushing delalloc if
5268 * possible or committing the transaction. If flush is 0 then no attempts to
5269 * regain reservations will be made and this will fail if there is not enough
5270 * space already.
5271 */
5272 static int reserve_metadata_bytes(struct btrfs_root *root,
5273 struct btrfs_block_rsv *block_rsv,
5274 u64 orig_bytes,
5275 enum btrfs_reserve_flush_enum flush)
5276 {
5277 struct btrfs_fs_info *fs_info = root->fs_info;
5278 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5279 int ret;
5280
5281 ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
5282 flush);
5283 if (ret == -ENOSPC &&
5284 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5285 if (block_rsv != global_rsv &&
5286 !block_rsv_use_bytes(global_rsv, orig_bytes))
5287 ret = 0;
5288 }
5289 if (ret == -ENOSPC)
5290 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5291 block_rsv->space_info->flags,
5292 orig_bytes, 1);
5293 return ret;
5294 }
5295
5296 static struct btrfs_block_rsv *get_block_rsv(
5297 const struct btrfs_trans_handle *trans,
5298 const struct btrfs_root *root)
5299 {
5300 struct btrfs_fs_info *fs_info = root->fs_info;
5301 struct btrfs_block_rsv *block_rsv = NULL;
5302
5303 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5304 (root == fs_info->csum_root && trans->adding_csums) ||
5305 (root == fs_info->uuid_root))
5306 block_rsv = trans->block_rsv;
5307
5308 if (!block_rsv)
5309 block_rsv = root->block_rsv;
5310
5311 if (!block_rsv)
5312 block_rsv = &fs_info->empty_block_rsv;
5313
5314 return block_rsv;
5315 }
5316
5317 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5318 u64 num_bytes)
5319 {
5320 int ret = -ENOSPC;
5321 spin_lock(&block_rsv->lock);
5322 if (block_rsv->reserved >= num_bytes) {
5323 block_rsv->reserved -= num_bytes;
5324 if (block_rsv->reserved < block_rsv->size)
5325 block_rsv->full = 0;
5326 ret = 0;
5327 }
5328 spin_unlock(&block_rsv->lock);
5329 return ret;
5330 }
5331
5332 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5333 u64 num_bytes, int update_size)
5334 {
5335 spin_lock(&block_rsv->lock);
5336 block_rsv->reserved += num_bytes;
5337 if (update_size)
5338 block_rsv->size += num_bytes;
5339 else if (block_rsv->reserved >= block_rsv->size)
5340 block_rsv->full = 1;
5341 spin_unlock(&block_rsv->lock);
5342 }
5343
5344 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5345 struct btrfs_block_rsv *dest, u64 num_bytes,
5346 int min_factor)
5347 {
5348 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5349 u64 min_bytes;
5350
5351 if (global_rsv->space_info != dest->space_info)
5352 return -ENOSPC;
5353
5354 spin_lock(&global_rsv->lock);
5355 min_bytes = div_factor(global_rsv->size, min_factor);
5356 if (global_rsv->reserved < min_bytes + num_bytes) {
5357 spin_unlock(&global_rsv->lock);
5358 return -ENOSPC;
5359 }
5360 global_rsv->reserved -= num_bytes;
5361 if (global_rsv->reserved < global_rsv->size)
5362 global_rsv->full = 0;
5363 spin_unlock(&global_rsv->lock);
5364
5365 block_rsv_add_bytes(dest, num_bytes, 1);
5366 return 0;
5367 }
5368
5369 /*
5370 * This is for space we already have accounted in space_info->bytes_may_use, so
5371 * basically when we're returning space from block_rsv's.
5372 */
5373 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5374 struct btrfs_space_info *space_info,
5375 u64 num_bytes)
5376 {
5377 struct reserve_ticket *ticket;
5378 struct list_head *head;
5379 u64 used;
5380 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5381 bool check_overcommit = false;
5382
5383 spin_lock(&space_info->lock);
5384 head = &space_info->priority_tickets;
5385
5386 /*
5387 * If we are over our limit then we need to check and see if we can
5388 * overcommit, and if we can't then we just need to free up our space
5389 * and not satisfy any requests.
5390 */
5391 used = space_info->bytes_used + space_info->bytes_reserved +
5392 space_info->bytes_pinned + space_info->bytes_readonly +
5393 space_info->bytes_may_use;
5394 if (used - num_bytes >= space_info->total_bytes)
5395 check_overcommit = true;
5396 again:
5397 while (!list_empty(head) && num_bytes) {
5398 ticket = list_first_entry(head, struct reserve_ticket,
5399 list);
5400 /*
5401 * We use 0 bytes because this space is already reserved, so
5402 * adding the ticket space would be a double count.
5403 */
5404 if (check_overcommit &&
5405 !can_overcommit(fs_info->extent_root, space_info, 0,
5406 flush))
5407 break;
5408 if (num_bytes >= ticket->bytes) {
5409 list_del_init(&ticket->list);
5410 num_bytes -= ticket->bytes;
5411 ticket->bytes = 0;
5412 space_info->tickets_id++;
5413 wake_up(&ticket->wait);
5414 } else {
5415 ticket->bytes -= num_bytes;
5416 num_bytes = 0;
5417 }
5418 }
5419
5420 if (num_bytes && head == &space_info->priority_tickets) {
5421 head = &space_info->tickets;
5422 flush = BTRFS_RESERVE_FLUSH_ALL;
5423 goto again;
5424 }
5425 space_info->bytes_may_use -= num_bytes;
5426 trace_btrfs_space_reservation(fs_info, "space_info",
5427 space_info->flags, num_bytes, 0);
5428 spin_unlock(&space_info->lock);
5429 }
5430
5431 /*
5432 * This is for newly allocated space that isn't accounted in
5433 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5434 * we use this helper.
5435 */
5436 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5437 struct btrfs_space_info *space_info,
5438 u64 num_bytes)
5439 {
5440 struct reserve_ticket *ticket;
5441 struct list_head *head = &space_info->priority_tickets;
5442
5443 again:
5444 while (!list_empty(head) && num_bytes) {
5445 ticket = list_first_entry(head, struct reserve_ticket,
5446 list);
5447 if (num_bytes >= ticket->bytes) {
5448 trace_btrfs_space_reservation(fs_info, "space_info",
5449 space_info->flags,
5450 ticket->bytes, 1);
5451 list_del_init(&ticket->list);
5452 num_bytes -= ticket->bytes;
5453 space_info->bytes_may_use += ticket->bytes;
5454 ticket->bytes = 0;
5455 space_info->tickets_id++;
5456 wake_up(&ticket->wait);
5457 } else {
5458 trace_btrfs_space_reservation(fs_info, "space_info",
5459 space_info->flags,
5460 num_bytes, 1);
5461 space_info->bytes_may_use += num_bytes;
5462 ticket->bytes -= num_bytes;
5463 num_bytes = 0;
5464 }
5465 }
5466
5467 if (num_bytes && head == &space_info->priority_tickets) {
5468 head = &space_info->tickets;
5469 goto again;
5470 }
5471 }
5472
5473 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5474 struct btrfs_block_rsv *block_rsv,
5475 struct btrfs_block_rsv *dest, u64 num_bytes)
5476 {
5477 struct btrfs_space_info *space_info = block_rsv->space_info;
5478
5479 spin_lock(&block_rsv->lock);
5480 if (num_bytes == (u64)-1)
5481 num_bytes = block_rsv->size;
5482 block_rsv->size -= num_bytes;
5483 if (block_rsv->reserved >= block_rsv->size) {
5484 num_bytes = block_rsv->reserved - block_rsv->size;
5485 block_rsv->reserved = block_rsv->size;
5486 block_rsv->full = 1;
5487 } else {
5488 num_bytes = 0;
5489 }
5490 spin_unlock(&block_rsv->lock);
5491
5492 if (num_bytes > 0) {
5493 if (dest) {
5494 spin_lock(&dest->lock);
5495 if (!dest->full) {
5496 u64 bytes_to_add;
5497
5498 bytes_to_add = dest->size - dest->reserved;
5499 bytes_to_add = min(num_bytes, bytes_to_add);
5500 dest->reserved += bytes_to_add;
5501 if (dest->reserved >= dest->size)
5502 dest->full = 1;
5503 num_bytes -= bytes_to_add;
5504 }
5505 spin_unlock(&dest->lock);
5506 }
5507 if (num_bytes)
5508 space_info_add_old_bytes(fs_info, space_info,
5509 num_bytes);
5510 }
5511 }
5512
5513 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5514 struct btrfs_block_rsv *dst, u64 num_bytes,
5515 int update_size)
5516 {
5517 int ret;
5518
5519 ret = block_rsv_use_bytes(src, num_bytes);
5520 if (ret)
5521 return ret;
5522
5523 block_rsv_add_bytes(dst, num_bytes, update_size);
5524 return 0;
5525 }
5526
5527 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5528 {
5529 memset(rsv, 0, sizeof(*rsv));
5530 spin_lock_init(&rsv->lock);
5531 rsv->type = type;
5532 }
5533
5534 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
5535 unsigned short type)
5536 {
5537 struct btrfs_block_rsv *block_rsv;
5538 struct btrfs_fs_info *fs_info = root->fs_info;
5539
5540 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5541 if (!block_rsv)
5542 return NULL;
5543
5544 btrfs_init_block_rsv(block_rsv, type);
5545 block_rsv->space_info = __find_space_info(fs_info,
5546 BTRFS_BLOCK_GROUP_METADATA);
5547 return block_rsv;
5548 }
5549
5550 void btrfs_free_block_rsv(struct btrfs_root *root,
5551 struct btrfs_block_rsv *rsv)
5552 {
5553 if (!rsv)
5554 return;
5555 btrfs_block_rsv_release(root, rsv, (u64)-1);
5556 kfree(rsv);
5557 }
5558
5559 void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5560 {
5561 kfree(rsv);
5562 }
5563
5564 int btrfs_block_rsv_add(struct btrfs_root *root,
5565 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5566 enum btrfs_reserve_flush_enum flush)
5567 {
5568 int ret;
5569
5570 if (num_bytes == 0)
5571 return 0;
5572
5573 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5574 if (!ret) {
5575 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5576 return 0;
5577 }
5578
5579 return ret;
5580 }
5581
5582 int btrfs_block_rsv_check(struct btrfs_root *root,
5583 struct btrfs_block_rsv *block_rsv, int min_factor)
5584 {
5585 u64 num_bytes = 0;
5586 int ret = -ENOSPC;
5587
5588 if (!block_rsv)
5589 return 0;
5590
5591 spin_lock(&block_rsv->lock);
5592 num_bytes = div_factor(block_rsv->size, min_factor);
5593 if (block_rsv->reserved >= num_bytes)
5594 ret = 0;
5595 spin_unlock(&block_rsv->lock);
5596
5597 return ret;
5598 }
5599
5600 int btrfs_block_rsv_refill(struct btrfs_root *root,
5601 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5602 enum btrfs_reserve_flush_enum flush)
5603 {
5604 u64 num_bytes = 0;
5605 int ret = -ENOSPC;
5606
5607 if (!block_rsv)
5608 return 0;
5609
5610 spin_lock(&block_rsv->lock);
5611 num_bytes = min_reserved;
5612 if (block_rsv->reserved >= num_bytes)
5613 ret = 0;
5614 else
5615 num_bytes -= block_rsv->reserved;
5616 spin_unlock(&block_rsv->lock);
5617
5618 if (!ret)
5619 return 0;
5620
5621 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5622 if (!ret) {
5623 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5624 return 0;
5625 }
5626
5627 return ret;
5628 }
5629
5630 void btrfs_block_rsv_release(struct btrfs_root *root,
5631 struct btrfs_block_rsv *block_rsv,
5632 u64 num_bytes)
5633 {
5634 struct btrfs_fs_info *fs_info = root->fs_info;
5635 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5636
5637 if (global_rsv == block_rsv ||
5638 block_rsv->space_info != global_rsv->space_info)
5639 global_rsv = NULL;
5640 block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
5641 }
5642
5643 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5644 {
5645 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5646 struct btrfs_space_info *sinfo = block_rsv->space_info;
5647 u64 num_bytes;
5648
5649 /*
5650 * The global block rsv is based on the size of the extent tree, the
5651 * checksum tree and the root tree. If the fs is empty we want to set
5652 * it to a minimal amount for safety.
5653 */
5654 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5655 btrfs_root_used(&fs_info->csum_root->root_item) +
5656 btrfs_root_used(&fs_info->tree_root->root_item);
5657 num_bytes = max_t(u64, num_bytes, SZ_16M);
5658
5659 spin_lock(&sinfo->lock);
5660 spin_lock(&block_rsv->lock);
5661
5662 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5663
5664 if (block_rsv->reserved < block_rsv->size) {
5665 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
5666 sinfo->bytes_reserved + sinfo->bytes_readonly +
5667 sinfo->bytes_may_use;
5668 if (sinfo->total_bytes > num_bytes) {
5669 num_bytes = sinfo->total_bytes - num_bytes;
5670 num_bytes = min(num_bytes,
5671 block_rsv->size - block_rsv->reserved);
5672 block_rsv->reserved += num_bytes;
5673 sinfo->bytes_may_use += num_bytes;
5674 trace_btrfs_space_reservation(fs_info, "space_info",
5675 sinfo->flags, num_bytes,
5676 1);
5677 }
5678 } else if (block_rsv->reserved > block_rsv->size) {
5679 num_bytes = block_rsv->reserved - block_rsv->size;
5680 sinfo->bytes_may_use -= num_bytes;
5681 trace_btrfs_space_reservation(fs_info, "space_info",
5682 sinfo->flags, num_bytes, 0);
5683 block_rsv->reserved = block_rsv->size;
5684 }
5685
5686 if (block_rsv->reserved == block_rsv->size)
5687 block_rsv->full = 1;
5688 else
5689 block_rsv->full = 0;
5690
5691 spin_unlock(&block_rsv->lock);
5692 spin_unlock(&sinfo->lock);
5693 }
5694
5695 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5696 {
5697 struct btrfs_space_info *space_info;
5698
5699 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5700 fs_info->chunk_block_rsv.space_info = space_info;
5701
5702 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5703 fs_info->global_block_rsv.space_info = space_info;
5704 fs_info->delalloc_block_rsv.space_info = space_info;
5705 fs_info->trans_block_rsv.space_info = space_info;
5706 fs_info->empty_block_rsv.space_info = space_info;
5707 fs_info->delayed_block_rsv.space_info = space_info;
5708
5709 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5710 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5711 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5712 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5713 if (fs_info->quota_root)
5714 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5715 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5716
5717 update_global_block_rsv(fs_info);
5718 }
5719
5720 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5721 {
5722 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5723 (u64)-1);
5724 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5725 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5726 WARN_ON(fs_info->trans_block_rsv.size > 0);
5727 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5728 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5729 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5730 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5731 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5732 }
5733
5734 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5735 struct btrfs_root *root)
5736 {
5737 struct btrfs_fs_info *fs_info = root->fs_info;
5738
5739 if (!trans->block_rsv)
5740 return;
5741
5742 if (!trans->bytes_reserved)
5743 return;
5744
5745 trace_btrfs_space_reservation(fs_info, "transaction",
5746 trans->transid, trans->bytes_reserved, 0);
5747 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
5748 trans->bytes_reserved = 0;
5749 }
5750
5751 /*
5752 * To be called after all the new block groups attached to the transaction
5753 * handle have been created (btrfs_create_pending_block_groups()).
5754 */
5755 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5756 {
5757 struct btrfs_fs_info *fs_info = trans->fs_info;
5758
5759 if (!trans->chunk_bytes_reserved)
5760 return;
5761
5762 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5763
5764 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5765 trans->chunk_bytes_reserved);
5766 trans->chunk_bytes_reserved = 0;
5767 }
5768
5769 /* Can only return 0 or -ENOSPC */
5770 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5771 struct inode *inode)
5772 {
5773 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5774 struct btrfs_root *root = BTRFS_I(inode)->root;
5775 /*
5776 * We always use trans->block_rsv here as we will have reserved space
5777 * for our orphan when starting the transaction, using get_block_rsv()
5778 * here will sometimes make us choose the wrong block rsv as we could be
5779 * doing a reloc inode for a non refcounted root.
5780 */
5781 struct btrfs_block_rsv *src_rsv = trans->block_rsv;
5782 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5783
5784 /*
5785 * We need to hold space in order to delete our orphan item once we've
5786 * added it, so this takes the reservation so we can release it later
5787 * when we are truly done with the orphan item.
5788 */
5789 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5790
5791 trace_btrfs_space_reservation(fs_info, "orphan",
5792 btrfs_ino(inode), num_bytes, 1);
5793 return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
5794 }
5795
5796 void btrfs_orphan_release_metadata(struct inode *inode)
5797 {
5798 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5799 struct btrfs_root *root = BTRFS_I(inode)->root;
5800 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5801
5802 trace_btrfs_space_reservation(fs_info, "orphan",
5803 btrfs_ino(inode), num_bytes, 0);
5804 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
5805 }
5806
5807 /*
5808 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5809 * root: the root of the parent directory
5810 * rsv: block reservation
5811 * items: the number of items that we need do reservation
5812 * qgroup_reserved: used to return the reserved size in qgroup
5813 *
5814 * This function is used to reserve the space for snapshot/subvolume
5815 * creation and deletion. Those operations are different with the
5816 * common file/directory operations, they change two fs/file trees
5817 * and root tree, the number of items that the qgroup reserves is
5818 * different with the free space reservation. So we can not use
5819 * the space reservation mechanism in start_transaction().
5820 */
5821 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5822 struct btrfs_block_rsv *rsv,
5823 int items,
5824 u64 *qgroup_reserved,
5825 bool use_global_rsv)
5826 {
5827 u64 num_bytes;
5828 int ret;
5829 struct btrfs_fs_info *fs_info = root->fs_info;
5830 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5831
5832 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5833 /* One for parent inode, two for dir entries */
5834 num_bytes = 3 * fs_info->nodesize;
5835 ret = btrfs_qgroup_reserve_meta(root, num_bytes);
5836 if (ret)
5837 return ret;
5838 } else {
5839 num_bytes = 0;
5840 }
5841
5842 *qgroup_reserved = num_bytes;
5843
5844 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5845 rsv->space_info = __find_space_info(fs_info,
5846 BTRFS_BLOCK_GROUP_METADATA);
5847 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5848 BTRFS_RESERVE_FLUSH_ALL);
5849
5850 if (ret == -ENOSPC && use_global_rsv)
5851 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
5852
5853 if (ret && *qgroup_reserved)
5854 btrfs_qgroup_free_meta(root, *qgroup_reserved);
5855
5856 return ret;
5857 }
5858
5859 void btrfs_subvolume_release_metadata(struct btrfs_root *root,
5860 struct btrfs_block_rsv *rsv,
5861 u64 qgroup_reserved)
5862 {
5863 btrfs_block_rsv_release(root, rsv, (u64)-1);
5864 }
5865
5866 /**
5867 * drop_outstanding_extent - drop an outstanding extent
5868 * @inode: the inode we're dropping the extent for
5869 * @num_bytes: the number of bytes we're releasing.
5870 *
5871 * This is called when we are freeing up an outstanding extent, either called
5872 * after an error or after an extent is written. This will return the number of
5873 * reserved extents that need to be freed. This must be called with
5874 * BTRFS_I(inode)->lock held.
5875 */
5876 static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
5877 {
5878 unsigned drop_inode_space = 0;
5879 unsigned dropped_extents = 0;
5880 unsigned num_extents = 0;
5881
5882 num_extents = (unsigned)div64_u64(num_bytes +
5883 BTRFS_MAX_EXTENT_SIZE - 1,
5884 BTRFS_MAX_EXTENT_SIZE);
5885 ASSERT(num_extents);
5886 ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
5887 BTRFS_I(inode)->outstanding_extents -= num_extents;
5888
5889 if (BTRFS_I(inode)->outstanding_extents == 0 &&
5890 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5891 &BTRFS_I(inode)->runtime_flags))
5892 drop_inode_space = 1;
5893
5894 /*
5895 * If we have more or the same amount of outstanding extents than we have
5896 * reserved then we need to leave the reserved extents count alone.
5897 */
5898 if (BTRFS_I(inode)->outstanding_extents >=
5899 BTRFS_I(inode)->reserved_extents)
5900 return drop_inode_space;
5901
5902 dropped_extents = BTRFS_I(inode)->reserved_extents -
5903 BTRFS_I(inode)->outstanding_extents;
5904 BTRFS_I(inode)->reserved_extents -= dropped_extents;
5905 return dropped_extents + drop_inode_space;
5906 }
5907
5908 /**
5909 * calc_csum_metadata_size - return the amount of metadata space that must be
5910 * reserved/freed for the given bytes.
5911 * @inode: the inode we're manipulating
5912 * @num_bytes: the number of bytes in question
5913 * @reserve: 1 if we are reserving space, 0 if we are freeing space
5914 *
5915 * This adjusts the number of csum_bytes in the inode and then returns the
5916 * correct amount of metadata that must either be reserved or freed. We
5917 * calculate how many checksums we can fit into one leaf and then divide the
5918 * number of bytes that will need to be checksumed by this value to figure out
5919 * how many checksums will be required. If we are adding bytes then the number
5920 * may go up and we will return the number of additional bytes that must be
5921 * reserved. If it is going down we will return the number of bytes that must
5922 * be freed.
5923 *
5924 * This must be called with BTRFS_I(inode)->lock held.
5925 */
5926 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5927 int reserve)
5928 {
5929 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5930 struct btrfs_root *root = BTRFS_I(inode)->root;
5931 u64 old_csums, num_csums;
5932
5933 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5934 BTRFS_I(inode)->csum_bytes == 0)
5935 return 0;
5936
5937 old_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
5938 if (reserve)
5939 BTRFS_I(inode)->csum_bytes += num_bytes;
5940 else
5941 BTRFS_I(inode)->csum_bytes -= num_bytes;
5942 num_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
5943
5944 /* No change, no need to reserve more */
5945 if (old_csums == num_csums)
5946 return 0;
5947
5948 if (reserve)
5949 return btrfs_calc_trans_metadata_size(fs_info,
5950 num_csums - old_csums);
5951
5952 return btrfs_calc_trans_metadata_size(fs_info, old_csums - num_csums);
5953 }
5954
5955 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5956 {
5957 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5958 struct btrfs_root *root = BTRFS_I(inode)->root;
5959 struct btrfs_block_rsv *block_rsv = &fs_info->delalloc_block_rsv;
5960 u64 to_reserve = 0;
5961 u64 csum_bytes;
5962 unsigned nr_extents = 0;
5963 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5964 int ret = 0;
5965 bool delalloc_lock = true;
5966 u64 to_free = 0;
5967 unsigned dropped;
5968 bool release_extra = false;
5969
5970 /* If we are a free space inode we need to not flush since we will be in
5971 * the middle of a transaction commit. We also don't need the delalloc
5972 * mutex since we won't race with anybody. We need this mostly to make
5973 * lockdep shut its filthy mouth.
5974 *
5975 * If we have a transaction open (can happen if we call truncate_block
5976 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5977 */
5978 if (btrfs_is_free_space_inode(inode)) {
5979 flush = BTRFS_RESERVE_NO_FLUSH;
5980 delalloc_lock = false;
5981 } else if (current->journal_info) {
5982 flush = BTRFS_RESERVE_FLUSH_LIMIT;
5983 }
5984
5985 if (flush != BTRFS_RESERVE_NO_FLUSH &&
5986 btrfs_transaction_in_commit(fs_info))
5987 schedule_timeout(1);
5988
5989 if (delalloc_lock)
5990 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5991
5992 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5993
5994 spin_lock(&BTRFS_I(inode)->lock);
5995 nr_extents = (unsigned)div64_u64(num_bytes +
5996 BTRFS_MAX_EXTENT_SIZE - 1,
5997 BTRFS_MAX_EXTENT_SIZE);
5998 BTRFS_I(inode)->outstanding_extents += nr_extents;
5999
6000 nr_extents = 0;
6001 if (BTRFS_I(inode)->outstanding_extents >
6002 BTRFS_I(inode)->reserved_extents)
6003 nr_extents += BTRFS_I(inode)->outstanding_extents -
6004 BTRFS_I(inode)->reserved_extents;
6005
6006 /* We always want to reserve a slot for updating the inode. */
6007 to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
6008 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
6009 csum_bytes = BTRFS_I(inode)->csum_bytes;
6010 spin_unlock(&BTRFS_I(inode)->lock);
6011
6012 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
6013 ret = btrfs_qgroup_reserve_meta(root,
6014 nr_extents * fs_info->nodesize);
6015 if (ret)
6016 goto out_fail;
6017 }
6018
6019 ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
6020 if (unlikely(ret)) {
6021 btrfs_qgroup_free_meta(root,
6022 nr_extents * fs_info->nodesize);
6023 goto out_fail;
6024 }
6025
6026 spin_lock(&BTRFS_I(inode)->lock);
6027 if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
6028 &BTRFS_I(inode)->runtime_flags)) {
6029 to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
6030 release_extra = true;
6031 }
6032 BTRFS_I(inode)->reserved_extents += nr_extents;
6033 spin_unlock(&BTRFS_I(inode)->lock);
6034
6035 if (delalloc_lock)
6036 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6037
6038 if (to_reserve)
6039 trace_btrfs_space_reservation(fs_info, "delalloc",
6040 btrfs_ino(inode), to_reserve, 1);
6041 if (release_extra)
6042 btrfs_block_rsv_release(root, block_rsv,
6043 btrfs_calc_trans_metadata_size(fs_info, 1));
6044 return 0;
6045
6046 out_fail:
6047 spin_lock(&BTRFS_I(inode)->lock);
6048 dropped = drop_outstanding_extent(inode, num_bytes);
6049 /*
6050 * If the inodes csum_bytes is the same as the original
6051 * csum_bytes then we know we haven't raced with any free()ers
6052 * so we can just reduce our inodes csum bytes and carry on.
6053 */
6054 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
6055 calc_csum_metadata_size(inode, num_bytes, 0);
6056 } else {
6057 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
6058 u64 bytes;
6059
6060 /*
6061 * This is tricky, but first we need to figure out how much we
6062 * freed from any free-ers that occurred during this
6063 * reservation, so we reset ->csum_bytes to the csum_bytes
6064 * before we dropped our lock, and then call the free for the
6065 * number of bytes that were freed while we were trying our
6066 * reservation.
6067 */
6068 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
6069 BTRFS_I(inode)->csum_bytes = csum_bytes;
6070 to_free = calc_csum_metadata_size(inode, bytes, 0);
6071
6072
6073 /*
6074 * Now we need to see how much we would have freed had we not
6075 * been making this reservation and our ->csum_bytes were not
6076 * artificially inflated.
6077 */
6078 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
6079 bytes = csum_bytes - orig_csum_bytes;
6080 bytes = calc_csum_metadata_size(inode, bytes, 0);
6081
6082 /*
6083 * Now reset ->csum_bytes to what it should be. If bytes is
6084 * more than to_free then we would have freed more space had we
6085 * not had an artificially high ->csum_bytes, so we need to free
6086 * the remainder. If bytes is the same or less then we don't
6087 * need to do anything, the other free-ers did the correct
6088 * thing.
6089 */
6090 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
6091 if (bytes > to_free)
6092 to_free = bytes - to_free;
6093 else
6094 to_free = 0;
6095 }
6096 spin_unlock(&BTRFS_I(inode)->lock);
6097 if (dropped)
6098 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6099
6100 if (to_free) {
6101 btrfs_block_rsv_release(root, block_rsv, to_free);
6102 trace_btrfs_space_reservation(fs_info, "delalloc",
6103 btrfs_ino(inode), to_free, 0);
6104 }
6105 if (delalloc_lock)
6106 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6107 return ret;
6108 }
6109
6110 /**
6111 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6112 * @inode: the inode to release the reservation for
6113 * @num_bytes: the number of bytes we're releasing
6114 *
6115 * This will release the metadata reservation for an inode. This can be called
6116 * once we complete IO for a given set of bytes to release their metadata
6117 * reservations.
6118 */
6119 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
6120 {
6121 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6122 struct btrfs_root *root = BTRFS_I(inode)->root;
6123 u64 to_free = 0;
6124 unsigned dropped;
6125
6126 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6127 spin_lock(&BTRFS_I(inode)->lock);
6128 dropped = drop_outstanding_extent(inode, num_bytes);
6129
6130 if (num_bytes)
6131 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
6132 spin_unlock(&BTRFS_I(inode)->lock);
6133 if (dropped > 0)
6134 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6135
6136 if (btrfs_is_testing(fs_info))
6137 return;
6138
6139 trace_btrfs_space_reservation(fs_info, "delalloc",
6140 btrfs_ino(inode), to_free, 0);
6141
6142 btrfs_block_rsv_release(root, &fs_info->delalloc_block_rsv, to_free);
6143 }
6144
6145 /**
6146 * btrfs_delalloc_reserve_space - reserve data and metadata space for
6147 * delalloc
6148 * @inode: inode we're writing to
6149 * @start: start range we are writing to
6150 * @len: how long the range we are writing to
6151 *
6152 * This will do the following things
6153 *
6154 * o reserve space in data space info for num bytes
6155 * and reserve precious corresponding qgroup space
6156 * (Done in check_data_free_space)
6157 *
6158 * o reserve space for metadata space, based on the number of outstanding
6159 * extents and how much csums will be needed
6160 * also reserve metadata space in a per root over-reserve method.
6161 * o add to the inodes->delalloc_bytes
6162 * o add it to the fs_info's delalloc inodes list.
6163 * (Above 3 all done in delalloc_reserve_metadata)
6164 *
6165 * Return 0 for success
6166 * Return <0 for error(-ENOSPC or -EQUOT)
6167 */
6168 int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
6169 {
6170 int ret;
6171
6172 ret = btrfs_check_data_free_space(inode, start, len);
6173 if (ret < 0)
6174 return ret;
6175 ret = btrfs_delalloc_reserve_metadata(inode, len);
6176 if (ret < 0)
6177 btrfs_free_reserved_data_space(inode, start, len);
6178 return ret;
6179 }
6180
6181 /**
6182 * btrfs_delalloc_release_space - release data and metadata space for delalloc
6183 * @inode: inode we're releasing space for
6184 * @start: start position of the space already reserved
6185 * @len: the len of the space already reserved
6186 *
6187 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
6188 * called in the case that we don't need the metadata AND data reservations
6189 * anymore. So if there is an error or we insert an inline extent.
6190 *
6191 * This function will release the metadata space that was not used and will
6192 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6193 * list if there are no delalloc bytes left.
6194 * Also it will handle the qgroup reserved space.
6195 */
6196 void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
6197 {
6198 btrfs_delalloc_release_metadata(inode, len);
6199 btrfs_free_reserved_data_space(inode, start, len);
6200 }
6201
6202 static int update_block_group(struct btrfs_trans_handle *trans,
6203 struct btrfs_fs_info *info, u64 bytenr,
6204 u64 num_bytes, int alloc)
6205 {
6206 struct btrfs_block_group_cache *cache = NULL;
6207 u64 total = num_bytes;
6208 u64 old_val;
6209 u64 byte_in_group;
6210 int factor;
6211
6212 /* block accounting for super block */
6213 spin_lock(&info->delalloc_root_lock);
6214 old_val = btrfs_super_bytes_used(info->super_copy);
6215 if (alloc)
6216 old_val += num_bytes;
6217 else
6218 old_val -= num_bytes;
6219 btrfs_set_super_bytes_used(info->super_copy, old_val);
6220 spin_unlock(&info->delalloc_root_lock);
6221
6222 while (total) {
6223 cache = btrfs_lookup_block_group(info, bytenr);
6224 if (!cache)
6225 return -ENOENT;
6226 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
6227 BTRFS_BLOCK_GROUP_RAID1 |
6228 BTRFS_BLOCK_GROUP_RAID10))
6229 factor = 2;
6230 else
6231 factor = 1;
6232 /*
6233 * If this block group has free space cache written out, we
6234 * need to make sure to load it if we are removing space. This
6235 * is because we need the unpinning stage to actually add the
6236 * space back to the block group, otherwise we will leak space.
6237 */
6238 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6239 cache_block_group(cache, 1);
6240
6241 byte_in_group = bytenr - cache->key.objectid;
6242 WARN_ON(byte_in_group > cache->key.offset);
6243
6244 spin_lock(&cache->space_info->lock);
6245 spin_lock(&cache->lock);
6246
6247 if (btrfs_test_opt(info, SPACE_CACHE) &&
6248 cache->disk_cache_state < BTRFS_DC_CLEAR)
6249 cache->disk_cache_state = BTRFS_DC_CLEAR;
6250
6251 old_val = btrfs_block_group_used(&cache->item);
6252 num_bytes = min(total, cache->key.offset - byte_in_group);
6253 if (alloc) {
6254 old_val += num_bytes;
6255 btrfs_set_block_group_used(&cache->item, old_val);
6256 cache->reserved -= num_bytes;
6257 cache->space_info->bytes_reserved -= num_bytes;
6258 cache->space_info->bytes_used += num_bytes;
6259 cache->space_info->disk_used += num_bytes * factor;
6260 spin_unlock(&cache->lock);
6261 spin_unlock(&cache->space_info->lock);
6262 } else {
6263 old_val -= num_bytes;
6264 btrfs_set_block_group_used(&cache->item, old_val);
6265 cache->pinned += num_bytes;
6266 cache->space_info->bytes_pinned += num_bytes;
6267 cache->space_info->bytes_used -= num_bytes;
6268 cache->space_info->disk_used -= num_bytes * factor;
6269 spin_unlock(&cache->lock);
6270 spin_unlock(&cache->space_info->lock);
6271
6272 trace_btrfs_space_reservation(info, "pinned",
6273 cache->space_info->flags,
6274 num_bytes, 1);
6275 set_extent_dirty(info->pinned_extents,
6276 bytenr, bytenr + num_bytes - 1,
6277 GFP_NOFS | __GFP_NOFAIL);
6278 }
6279
6280 spin_lock(&trans->transaction->dirty_bgs_lock);
6281 if (list_empty(&cache->dirty_list)) {
6282 list_add_tail(&cache->dirty_list,
6283 &trans->transaction->dirty_bgs);
6284 trans->transaction->num_dirty_bgs++;
6285 btrfs_get_block_group(cache);
6286 }
6287 spin_unlock(&trans->transaction->dirty_bgs_lock);
6288
6289 /*
6290 * No longer have used bytes in this block group, queue it for
6291 * deletion. We do this after adding the block group to the
6292 * dirty list to avoid races between cleaner kthread and space
6293 * cache writeout.
6294 */
6295 if (!alloc && old_val == 0) {
6296 spin_lock(&info->unused_bgs_lock);
6297 if (list_empty(&cache->bg_list)) {
6298 btrfs_get_block_group(cache);
6299 list_add_tail(&cache->bg_list,
6300 &info->unused_bgs);
6301 }
6302 spin_unlock(&info->unused_bgs_lock);
6303 }
6304
6305 btrfs_put_block_group(cache);
6306 total -= num_bytes;
6307 bytenr += num_bytes;
6308 }
6309 return 0;
6310 }
6311
6312 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
6313 {
6314 struct btrfs_fs_info *fs_info = root->fs_info;
6315 struct btrfs_block_group_cache *cache;
6316 u64 bytenr;
6317
6318 spin_lock(&fs_info->block_group_cache_lock);
6319 bytenr = fs_info->first_logical_byte;
6320 spin_unlock(&fs_info->block_group_cache_lock);
6321
6322 if (bytenr < (u64)-1)
6323 return bytenr;
6324
6325 cache = btrfs_lookup_first_block_group(fs_info, search_start);
6326 if (!cache)
6327 return 0;
6328
6329 bytenr = cache->key.objectid;
6330 btrfs_put_block_group(cache);
6331
6332 return bytenr;
6333 }
6334
6335 static int pin_down_extent(struct btrfs_root *root,
6336 struct btrfs_block_group_cache *cache,
6337 u64 bytenr, u64 num_bytes, int reserved)
6338 {
6339 struct btrfs_fs_info *fs_info = cache->fs_info;
6340
6341 spin_lock(&cache->space_info->lock);
6342 spin_lock(&cache->lock);
6343 cache->pinned += num_bytes;
6344 cache->space_info->bytes_pinned += num_bytes;
6345 if (reserved) {
6346 cache->reserved -= num_bytes;
6347 cache->space_info->bytes_reserved -= num_bytes;
6348 }
6349 spin_unlock(&cache->lock);
6350 spin_unlock(&cache->space_info->lock);
6351
6352 trace_btrfs_space_reservation(fs_info, "pinned",
6353 cache->space_info->flags, num_bytes, 1);
6354 set_extent_dirty(fs_info->pinned_extents, bytenr,
6355 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6356 return 0;
6357 }
6358
6359 /*
6360 * this function must be called within transaction
6361 */
6362 int btrfs_pin_extent(struct btrfs_root *root,
6363 u64 bytenr, u64 num_bytes, int reserved)
6364 {
6365 struct btrfs_fs_info *fs_info = root->fs_info;
6366 struct btrfs_block_group_cache *cache;
6367
6368 cache = btrfs_lookup_block_group(fs_info, bytenr);
6369 BUG_ON(!cache); /* Logic error */
6370
6371 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
6372
6373 btrfs_put_block_group(cache);
6374 return 0;
6375 }
6376
6377 /*
6378 * this function must be called within transaction
6379 */
6380 int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
6381 u64 bytenr, u64 num_bytes)
6382 {
6383 struct btrfs_fs_info *fs_info = root->fs_info;
6384 struct btrfs_block_group_cache *cache;
6385 int ret;
6386
6387 cache = btrfs_lookup_block_group(fs_info, bytenr);
6388 if (!cache)
6389 return -EINVAL;
6390
6391 /*
6392 * pull in the free space cache (if any) so that our pin
6393 * removes the free space from the cache. We have load_only set
6394 * to one because the slow code to read in the free extents does check
6395 * the pinned extents.
6396 */
6397 cache_block_group(cache, 1);
6398
6399 pin_down_extent(root, cache, bytenr, num_bytes, 0);
6400
6401 /* remove us from the free space cache (if we're there at all) */
6402 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6403 btrfs_put_block_group(cache);
6404 return ret;
6405 }
6406
6407 static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
6408 {
6409 struct btrfs_fs_info *fs_info = root->fs_info;
6410 int ret;
6411 struct btrfs_block_group_cache *block_group;
6412 struct btrfs_caching_control *caching_ctl;
6413
6414 block_group = btrfs_lookup_block_group(fs_info, start);
6415 if (!block_group)
6416 return -EINVAL;
6417
6418 cache_block_group(block_group, 0);
6419 caching_ctl = get_caching_control(block_group);
6420
6421 if (!caching_ctl) {
6422 /* Logic error */
6423 BUG_ON(!block_group_cache_done(block_group));
6424 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6425 } else {
6426 mutex_lock(&caching_ctl->mutex);
6427
6428 if (start >= caching_ctl->progress) {
6429 ret = add_excluded_extent(root, start, num_bytes);
6430 } else if (start + num_bytes <= caching_ctl->progress) {
6431 ret = btrfs_remove_free_space(block_group,
6432 start, num_bytes);
6433 } else {
6434 num_bytes = caching_ctl->progress - start;
6435 ret = btrfs_remove_free_space(block_group,
6436 start, num_bytes);
6437 if (ret)
6438 goto out_lock;
6439
6440 num_bytes = (start + num_bytes) -
6441 caching_ctl->progress;
6442 start = caching_ctl->progress;
6443 ret = add_excluded_extent(root, start, num_bytes);
6444 }
6445 out_lock:
6446 mutex_unlock(&caching_ctl->mutex);
6447 put_caching_control(caching_ctl);
6448 }
6449 btrfs_put_block_group(block_group);
6450 return ret;
6451 }
6452
6453 int btrfs_exclude_logged_extents(struct btrfs_root *log,
6454 struct extent_buffer *eb)
6455 {
6456 struct btrfs_file_extent_item *item;
6457 struct btrfs_key key;
6458 int found_type;
6459 int i;
6460
6461 if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
6462 return 0;
6463
6464 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6465 btrfs_item_key_to_cpu(eb, &key, i);
6466 if (key.type != BTRFS_EXTENT_DATA_KEY)
6467 continue;
6468 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6469 found_type = btrfs_file_extent_type(eb, item);
6470 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6471 continue;
6472 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6473 continue;
6474 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6475 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6476 __exclude_logged_extent(log, key.objectid, key.offset);
6477 }
6478
6479 return 0;
6480 }
6481
6482 static void
6483 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6484 {
6485 atomic_inc(&bg->reservations);
6486 }
6487
6488 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6489 const u64 start)
6490 {
6491 struct btrfs_block_group_cache *bg;
6492
6493 bg = btrfs_lookup_block_group(fs_info, start);
6494 ASSERT(bg);
6495 if (atomic_dec_and_test(&bg->reservations))
6496 wake_up_atomic_t(&bg->reservations);
6497 btrfs_put_block_group(bg);
6498 }
6499
6500 static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
6501 {
6502 schedule();
6503 return 0;
6504 }
6505
6506 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6507 {
6508 struct btrfs_space_info *space_info = bg->space_info;
6509
6510 ASSERT(bg->ro);
6511
6512 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6513 return;
6514
6515 /*
6516 * Our block group is read only but before we set it to read only,
6517 * some task might have had allocated an extent from it already, but it
6518 * has not yet created a respective ordered extent (and added it to a
6519 * root's list of ordered extents).
6520 * Therefore wait for any task currently allocating extents, since the
6521 * block group's reservations counter is incremented while a read lock
6522 * on the groups' semaphore is held and decremented after releasing
6523 * the read access on that semaphore and creating the ordered extent.
6524 */
6525 down_write(&space_info->groups_sem);
6526 up_write(&space_info->groups_sem);
6527
6528 wait_on_atomic_t(&bg->reservations,
6529 btrfs_wait_bg_reservations_atomic_t,
6530 TASK_UNINTERRUPTIBLE);
6531 }
6532
6533 /**
6534 * btrfs_add_reserved_bytes - update the block_group and space info counters
6535 * @cache: The cache we are manipulating
6536 * @ram_bytes: The number of bytes of file content, and will be same to
6537 * @num_bytes except for the compress path.
6538 * @num_bytes: The number of bytes in question
6539 * @delalloc: The blocks are allocated for the delalloc write
6540 *
6541 * This is called by the allocator when it reserves space. If this is a
6542 * reservation and the block group has become read only we cannot make the
6543 * reservation and return -EAGAIN, otherwise this function always succeeds.
6544 */
6545 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6546 u64 ram_bytes, u64 num_bytes, int delalloc)
6547 {
6548 struct btrfs_space_info *space_info = cache->space_info;
6549 int ret = 0;
6550
6551 spin_lock(&space_info->lock);
6552 spin_lock(&cache->lock);
6553 if (cache->ro) {
6554 ret = -EAGAIN;
6555 } else {
6556 cache->reserved += num_bytes;
6557 space_info->bytes_reserved += num_bytes;
6558
6559 trace_btrfs_space_reservation(cache->fs_info,
6560 "space_info", space_info->flags,
6561 ram_bytes, 0);
6562 space_info->bytes_may_use -= ram_bytes;
6563 if (delalloc)
6564 cache->delalloc_bytes += num_bytes;
6565 }
6566 spin_unlock(&cache->lock);
6567 spin_unlock(&space_info->lock);
6568 return ret;
6569 }
6570
6571 /**
6572 * btrfs_free_reserved_bytes - update the block_group and space info counters
6573 * @cache: The cache we are manipulating
6574 * @num_bytes: The number of bytes in question
6575 * @delalloc: The blocks are allocated for the delalloc write
6576 *
6577 * This is called by somebody who is freeing space that was never actually used
6578 * on disk. For example if you reserve some space for a new leaf in transaction
6579 * A and before transaction A commits you free that leaf, you call this with
6580 * reserve set to 0 in order to clear the reservation.
6581 */
6582
6583 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6584 u64 num_bytes, int delalloc)
6585 {
6586 struct btrfs_space_info *space_info = cache->space_info;
6587 int ret = 0;
6588
6589 spin_lock(&space_info->lock);
6590 spin_lock(&cache->lock);
6591 if (cache->ro)
6592 space_info->bytes_readonly += num_bytes;
6593 cache->reserved -= num_bytes;
6594 space_info->bytes_reserved -= num_bytes;
6595
6596 if (delalloc)
6597 cache->delalloc_bytes -= num_bytes;
6598 spin_unlock(&cache->lock);
6599 spin_unlock(&space_info->lock);
6600 return ret;
6601 }
6602 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
6603 struct btrfs_root *root)
6604 {
6605 struct btrfs_fs_info *fs_info = root->fs_info;
6606 struct btrfs_caching_control *next;
6607 struct btrfs_caching_control *caching_ctl;
6608 struct btrfs_block_group_cache *cache;
6609
6610 down_write(&fs_info->commit_root_sem);
6611
6612 list_for_each_entry_safe(caching_ctl, next,
6613 &fs_info->caching_block_groups, list) {
6614 cache = caching_ctl->block_group;
6615 if (block_group_cache_done(cache)) {
6616 cache->last_byte_to_unpin = (u64)-1;
6617 list_del_init(&caching_ctl->list);
6618 put_caching_control(caching_ctl);
6619 } else {
6620 cache->last_byte_to_unpin = caching_ctl->progress;
6621 }
6622 }
6623
6624 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6625 fs_info->pinned_extents = &fs_info->freed_extents[1];
6626 else
6627 fs_info->pinned_extents = &fs_info->freed_extents[0];
6628
6629 up_write(&fs_info->commit_root_sem);
6630
6631 update_global_block_rsv(fs_info);
6632 }
6633
6634 /*
6635 * Returns the free cluster for the given space info and sets empty_cluster to
6636 * what it should be based on the mount options.
6637 */
6638 static struct btrfs_free_cluster *
6639 fetch_cluster_info(struct btrfs_root *root, struct btrfs_space_info *space_info,
6640 u64 *empty_cluster)
6641 {
6642 struct btrfs_fs_info *fs_info = root->fs_info;
6643 struct btrfs_free_cluster *ret = NULL;
6644 bool ssd = btrfs_test_opt(fs_info, SSD);
6645
6646 *empty_cluster = 0;
6647 if (btrfs_mixed_space_info(space_info))
6648 return ret;
6649
6650 if (ssd)
6651 *empty_cluster = SZ_2M;
6652 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6653 ret = &fs_info->meta_alloc_cluster;
6654 if (!ssd)
6655 *empty_cluster = SZ_64K;
6656 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6657 ret = &fs_info->data_alloc_cluster;
6658 }
6659
6660 return ret;
6661 }
6662
6663 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end,
6664 const bool return_free_space)
6665 {
6666 struct btrfs_fs_info *fs_info = root->fs_info;
6667 struct btrfs_block_group_cache *cache = NULL;
6668 struct btrfs_space_info *space_info;
6669 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6670 struct btrfs_free_cluster *cluster = NULL;
6671 u64 len;
6672 u64 total_unpinned = 0;
6673 u64 empty_cluster = 0;
6674 bool readonly;
6675
6676 while (start <= end) {
6677 readonly = false;
6678 if (!cache ||
6679 start >= cache->key.objectid + cache->key.offset) {
6680 if (cache)
6681 btrfs_put_block_group(cache);
6682 total_unpinned = 0;
6683 cache = btrfs_lookup_block_group(fs_info, start);
6684 BUG_ON(!cache); /* Logic error */
6685
6686 cluster = fetch_cluster_info(root,
6687 cache->space_info,
6688 &empty_cluster);
6689 empty_cluster <<= 1;
6690 }
6691
6692 len = cache->key.objectid + cache->key.offset - start;
6693 len = min(len, end + 1 - start);
6694
6695 if (start < cache->last_byte_to_unpin) {
6696 len = min(len, cache->last_byte_to_unpin - start);
6697 if (return_free_space)
6698 btrfs_add_free_space(cache, start, len);
6699 }
6700
6701 start += len;
6702 total_unpinned += len;
6703 space_info = cache->space_info;
6704
6705 /*
6706 * If this space cluster has been marked as fragmented and we've
6707 * unpinned enough in this block group to potentially allow a
6708 * cluster to be created inside of it go ahead and clear the
6709 * fragmented check.
6710 */
6711 if (cluster && cluster->fragmented &&
6712 total_unpinned > empty_cluster) {
6713 spin_lock(&cluster->lock);
6714 cluster->fragmented = 0;
6715 spin_unlock(&cluster->lock);
6716 }
6717
6718 spin_lock(&space_info->lock);
6719 spin_lock(&cache->lock);
6720 cache->pinned -= len;
6721 space_info->bytes_pinned -= len;
6722
6723 trace_btrfs_space_reservation(fs_info, "pinned",
6724 space_info->flags, len, 0);
6725 space_info->max_extent_size = 0;
6726 percpu_counter_add(&space_info->total_bytes_pinned, -len);
6727 if (cache->ro) {
6728 space_info->bytes_readonly += len;
6729 readonly = true;
6730 }
6731 spin_unlock(&cache->lock);
6732 if (!readonly && return_free_space &&
6733 global_rsv->space_info == space_info) {
6734 u64 to_add = len;
6735 WARN_ON(!return_free_space);
6736 spin_lock(&global_rsv->lock);
6737 if (!global_rsv->full) {
6738 to_add = min(len, global_rsv->size -
6739 global_rsv->reserved);
6740 global_rsv->reserved += to_add;
6741 space_info->bytes_may_use += to_add;
6742 if (global_rsv->reserved >= global_rsv->size)
6743 global_rsv->full = 1;
6744 trace_btrfs_space_reservation(fs_info,
6745 "space_info",
6746 space_info->flags,
6747 to_add, 1);
6748 len -= to_add;
6749 }
6750 spin_unlock(&global_rsv->lock);
6751 /* Add to any tickets we may have */
6752 if (len)
6753 space_info_add_new_bytes(fs_info, space_info,
6754 len);
6755 }
6756 spin_unlock(&space_info->lock);
6757 }
6758
6759 if (cache)
6760 btrfs_put_block_group(cache);
6761 return 0;
6762 }
6763
6764 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
6765 struct btrfs_root *root)
6766 {
6767 struct btrfs_fs_info *fs_info = root->fs_info;
6768 struct btrfs_block_group_cache *block_group, *tmp;
6769 struct list_head *deleted_bgs;
6770 struct extent_io_tree *unpin;
6771 u64 start;
6772 u64 end;
6773 int ret;
6774
6775 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6776 unpin = &fs_info->freed_extents[1];
6777 else
6778 unpin = &fs_info->freed_extents[0];
6779
6780 while (!trans->aborted) {
6781 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6782 ret = find_first_extent_bit(unpin, 0, &start, &end,
6783 EXTENT_DIRTY, NULL);
6784 if (ret) {
6785 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6786 break;
6787 }
6788
6789 if (btrfs_test_opt(fs_info, DISCARD))
6790 ret = btrfs_discard_extent(root, start,
6791 end + 1 - start, NULL);
6792
6793 clear_extent_dirty(unpin, start, end);
6794 unpin_extent_range(root, start, end, true);
6795 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6796 cond_resched();
6797 }
6798
6799 /*
6800 * Transaction is finished. We don't need the lock anymore. We
6801 * do need to clean up the block groups in case of a transaction
6802 * abort.
6803 */
6804 deleted_bgs = &trans->transaction->deleted_bgs;
6805 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6806 u64 trimmed = 0;
6807
6808 ret = -EROFS;
6809 if (!trans->aborted)
6810 ret = btrfs_discard_extent(root,
6811 block_group->key.objectid,
6812 block_group->key.offset,
6813 &trimmed);
6814
6815 list_del_init(&block_group->bg_list);
6816 btrfs_put_block_group_trimming(block_group);
6817 btrfs_put_block_group(block_group);
6818
6819 if (ret) {
6820 const char *errstr = btrfs_decode_error(ret);
6821 btrfs_warn(fs_info,
6822 "Discard failed while removing blockgroup: errno=%d %s\n",
6823 ret, errstr);
6824 }
6825 }
6826
6827 return 0;
6828 }
6829
6830 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6831 u64 owner, u64 root_objectid)
6832 {
6833 struct btrfs_space_info *space_info;
6834 u64 flags;
6835
6836 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6837 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6838 flags = BTRFS_BLOCK_GROUP_SYSTEM;
6839 else
6840 flags = BTRFS_BLOCK_GROUP_METADATA;
6841 } else {
6842 flags = BTRFS_BLOCK_GROUP_DATA;
6843 }
6844
6845 space_info = __find_space_info(fs_info, flags);
6846 BUG_ON(!space_info); /* Logic bug */
6847 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6848 }
6849
6850
6851 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6852 struct btrfs_root *root,
6853 struct btrfs_delayed_ref_node *node, u64 parent,
6854 u64 root_objectid, u64 owner_objectid,
6855 u64 owner_offset, int refs_to_drop,
6856 struct btrfs_delayed_extent_op *extent_op)
6857 {
6858 struct btrfs_key key;
6859 struct btrfs_path *path;
6860 struct btrfs_fs_info *info = root->fs_info;
6861 struct btrfs_root *extent_root = info->extent_root;
6862 struct extent_buffer *leaf;
6863 struct btrfs_extent_item *ei;
6864 struct btrfs_extent_inline_ref *iref;
6865 int ret;
6866 int is_data;
6867 int extent_slot = 0;
6868 int found_extent = 0;
6869 int num_to_del = 1;
6870 u32 item_size;
6871 u64 refs;
6872 u64 bytenr = node->bytenr;
6873 u64 num_bytes = node->num_bytes;
6874 int last_ref = 0;
6875 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6876
6877 path = btrfs_alloc_path();
6878 if (!path)
6879 return -ENOMEM;
6880
6881 path->reada = READA_FORWARD;
6882 path->leave_spinning = 1;
6883
6884 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6885 BUG_ON(!is_data && refs_to_drop != 1);
6886
6887 if (is_data)
6888 skinny_metadata = 0;
6889
6890 ret = lookup_extent_backref(trans, extent_root, path, &iref,
6891 bytenr, num_bytes, parent,
6892 root_objectid, owner_objectid,
6893 owner_offset);
6894 if (ret == 0) {
6895 extent_slot = path->slots[0];
6896 while (extent_slot >= 0) {
6897 btrfs_item_key_to_cpu(path->nodes[0], &key,
6898 extent_slot);
6899 if (key.objectid != bytenr)
6900 break;
6901 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6902 key.offset == num_bytes) {
6903 found_extent = 1;
6904 break;
6905 }
6906 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6907 key.offset == owner_objectid) {
6908 found_extent = 1;
6909 break;
6910 }
6911 if (path->slots[0] - extent_slot > 5)
6912 break;
6913 extent_slot--;
6914 }
6915 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6916 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6917 if (found_extent && item_size < sizeof(*ei))
6918 found_extent = 0;
6919 #endif
6920 if (!found_extent) {
6921 BUG_ON(iref);
6922 ret = remove_extent_backref(trans, extent_root, path,
6923 NULL, refs_to_drop,
6924 is_data, &last_ref);
6925 if (ret) {
6926 btrfs_abort_transaction(trans, ret);
6927 goto out;
6928 }
6929 btrfs_release_path(path);
6930 path->leave_spinning = 1;
6931
6932 key.objectid = bytenr;
6933 key.type = BTRFS_EXTENT_ITEM_KEY;
6934 key.offset = num_bytes;
6935
6936 if (!is_data && skinny_metadata) {
6937 key.type = BTRFS_METADATA_ITEM_KEY;
6938 key.offset = owner_objectid;
6939 }
6940
6941 ret = btrfs_search_slot(trans, extent_root,
6942 &key, path, -1, 1);
6943 if (ret > 0 && skinny_metadata && path->slots[0]) {
6944 /*
6945 * Couldn't find our skinny metadata item,
6946 * see if we have ye olde extent item.
6947 */
6948 path->slots[0]--;
6949 btrfs_item_key_to_cpu(path->nodes[0], &key,
6950 path->slots[0]);
6951 if (key.objectid == bytenr &&
6952 key.type == BTRFS_EXTENT_ITEM_KEY &&
6953 key.offset == num_bytes)
6954 ret = 0;
6955 }
6956
6957 if (ret > 0 && skinny_metadata) {
6958 skinny_metadata = false;
6959 key.objectid = bytenr;
6960 key.type = BTRFS_EXTENT_ITEM_KEY;
6961 key.offset = num_bytes;
6962 btrfs_release_path(path);
6963 ret = btrfs_search_slot(trans, extent_root,
6964 &key, path, -1, 1);
6965 }
6966
6967 if (ret) {
6968 btrfs_err(info,
6969 "umm, got %d back from search, was looking for %llu",
6970 ret, bytenr);
6971 if (ret > 0)
6972 btrfs_print_leaf(extent_root,
6973 path->nodes[0]);
6974 }
6975 if (ret < 0) {
6976 btrfs_abort_transaction(trans, ret);
6977 goto out;
6978 }
6979 extent_slot = path->slots[0];
6980 }
6981 } else if (WARN_ON(ret == -ENOENT)) {
6982 btrfs_print_leaf(extent_root, path->nodes[0]);
6983 btrfs_err(info,
6984 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
6985 bytenr, parent, root_objectid, owner_objectid,
6986 owner_offset);
6987 btrfs_abort_transaction(trans, ret);
6988 goto out;
6989 } else {
6990 btrfs_abort_transaction(trans, ret);
6991 goto out;
6992 }
6993
6994 leaf = path->nodes[0];
6995 item_size = btrfs_item_size_nr(leaf, extent_slot);
6996 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6997 if (item_size < sizeof(*ei)) {
6998 BUG_ON(found_extent || extent_slot != path->slots[0]);
6999 ret = convert_extent_item_v0(trans, extent_root, path,
7000 owner_objectid, 0);
7001 if (ret < 0) {
7002 btrfs_abort_transaction(trans, ret);
7003 goto out;
7004 }
7005
7006 btrfs_release_path(path);
7007 path->leave_spinning = 1;
7008
7009 key.objectid = bytenr;
7010 key.type = BTRFS_EXTENT_ITEM_KEY;
7011 key.offset = num_bytes;
7012
7013 ret = btrfs_search_slot(trans, extent_root, &key, path,
7014 -1, 1);
7015 if (ret) {
7016 btrfs_err(info,
7017 "umm, got %d back from search, was looking for %llu",
7018 ret, bytenr);
7019 btrfs_print_leaf(extent_root, path->nodes[0]);
7020 }
7021 if (ret < 0) {
7022 btrfs_abort_transaction(trans, ret);
7023 goto out;
7024 }
7025
7026 extent_slot = path->slots[0];
7027 leaf = path->nodes[0];
7028 item_size = btrfs_item_size_nr(leaf, extent_slot);
7029 }
7030 #endif
7031 BUG_ON(item_size < sizeof(*ei));
7032 ei = btrfs_item_ptr(leaf, extent_slot,
7033 struct btrfs_extent_item);
7034 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
7035 key.type == BTRFS_EXTENT_ITEM_KEY) {
7036 struct btrfs_tree_block_info *bi;
7037 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
7038 bi = (struct btrfs_tree_block_info *)(ei + 1);
7039 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
7040 }
7041
7042 refs = btrfs_extent_refs(leaf, ei);
7043 if (refs < refs_to_drop) {
7044 btrfs_err(info,
7045 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7046 refs_to_drop, refs, bytenr);
7047 ret = -EINVAL;
7048 btrfs_abort_transaction(trans, ret);
7049 goto out;
7050 }
7051 refs -= refs_to_drop;
7052
7053 if (refs > 0) {
7054 if (extent_op)
7055 __run_delayed_extent_op(extent_op, leaf, ei);
7056 /*
7057 * In the case of inline back ref, reference count will
7058 * be updated by remove_extent_backref
7059 */
7060 if (iref) {
7061 BUG_ON(!found_extent);
7062 } else {
7063 btrfs_set_extent_refs(leaf, ei, refs);
7064 btrfs_mark_buffer_dirty(leaf);
7065 }
7066 if (found_extent) {
7067 ret = remove_extent_backref(trans, extent_root, path,
7068 iref, refs_to_drop,
7069 is_data, &last_ref);
7070 if (ret) {
7071 btrfs_abort_transaction(trans, ret);
7072 goto out;
7073 }
7074 }
7075 add_pinned_bytes(info, -num_bytes, owner_objectid,
7076 root_objectid);
7077 } else {
7078 if (found_extent) {
7079 BUG_ON(is_data && refs_to_drop !=
7080 extent_data_ref_count(path, iref));
7081 if (iref) {
7082 BUG_ON(path->slots[0] != extent_slot);
7083 } else {
7084 BUG_ON(path->slots[0] != extent_slot + 1);
7085 path->slots[0] = extent_slot;
7086 num_to_del = 2;
7087 }
7088 }
7089
7090 last_ref = 1;
7091 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7092 num_to_del);
7093 if (ret) {
7094 btrfs_abort_transaction(trans, ret);
7095 goto out;
7096 }
7097 btrfs_release_path(path);
7098
7099 if (is_data) {
7100 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7101 if (ret) {
7102 btrfs_abort_transaction(trans, ret);
7103 goto out;
7104 }
7105 }
7106
7107 ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
7108 if (ret) {
7109 btrfs_abort_transaction(trans, ret);
7110 goto out;
7111 }
7112
7113 ret = update_block_group(trans, info, bytenr, num_bytes, 0);
7114 if (ret) {
7115 btrfs_abort_transaction(trans, ret);
7116 goto out;
7117 }
7118 }
7119 btrfs_release_path(path);
7120
7121 out:
7122 btrfs_free_path(path);
7123 return ret;
7124 }
7125
7126 /*
7127 * when we free an block, it is possible (and likely) that we free the last
7128 * delayed ref for that extent as well. This searches the delayed ref tree for
7129 * a given extent, and if there are no other delayed refs to be processed, it
7130 * removes it from the tree.
7131 */
7132 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7133 struct btrfs_root *root, u64 bytenr)
7134 {
7135 struct btrfs_delayed_ref_head *head;
7136 struct btrfs_delayed_ref_root *delayed_refs;
7137 int ret = 0;
7138
7139 delayed_refs = &trans->transaction->delayed_refs;
7140 spin_lock(&delayed_refs->lock);
7141 head = btrfs_find_delayed_ref_head(trans, bytenr);
7142 if (!head)
7143 goto out_delayed_unlock;
7144
7145 spin_lock(&head->lock);
7146 if (!list_empty(&head->ref_list))
7147 goto out;
7148
7149 if (head->extent_op) {
7150 if (!head->must_insert_reserved)
7151 goto out;
7152 btrfs_free_delayed_extent_op(head->extent_op);
7153 head->extent_op = NULL;
7154 }
7155
7156 /*
7157 * waiting for the lock here would deadlock. If someone else has it
7158 * locked they are already in the process of dropping it anyway
7159 */
7160 if (!mutex_trylock(&head->mutex))
7161 goto out;
7162
7163 /*
7164 * at this point we have a head with no other entries. Go
7165 * ahead and process it.
7166 */
7167 head->node.in_tree = 0;
7168 rb_erase(&head->href_node, &delayed_refs->href_root);
7169
7170 atomic_dec(&delayed_refs->num_entries);
7171
7172 /*
7173 * we don't take a ref on the node because we're removing it from the
7174 * tree, so we just steal the ref the tree was holding.
7175 */
7176 delayed_refs->num_heads--;
7177 if (head->processing == 0)
7178 delayed_refs->num_heads_ready--;
7179 head->processing = 0;
7180 spin_unlock(&head->lock);
7181 spin_unlock(&delayed_refs->lock);
7182
7183 BUG_ON(head->extent_op);
7184 if (head->must_insert_reserved)
7185 ret = 1;
7186
7187 mutex_unlock(&head->mutex);
7188 btrfs_put_delayed_ref(&head->node);
7189 return ret;
7190 out:
7191 spin_unlock(&head->lock);
7192
7193 out_delayed_unlock:
7194 spin_unlock(&delayed_refs->lock);
7195 return 0;
7196 }
7197
7198 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7199 struct btrfs_root *root,
7200 struct extent_buffer *buf,
7201 u64 parent, int last_ref)
7202 {
7203 struct btrfs_fs_info *fs_info = root->fs_info;
7204 int pin = 1;
7205 int ret;
7206
7207 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7208 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
7209 buf->start, buf->len,
7210 parent,
7211 root->root_key.objectid,
7212 btrfs_header_level(buf),
7213 BTRFS_DROP_DELAYED_REF, NULL);
7214 BUG_ON(ret); /* -ENOMEM */
7215 }
7216
7217 if (!last_ref)
7218 return;
7219
7220 if (btrfs_header_generation(buf) == trans->transid) {
7221 struct btrfs_block_group_cache *cache;
7222
7223 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7224 ret = check_ref_cleanup(trans, root, buf->start);
7225 if (!ret)
7226 goto out;
7227 }
7228
7229 cache = btrfs_lookup_block_group(fs_info, buf->start);
7230
7231 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7232 pin_down_extent(root, cache, buf->start, buf->len, 1);
7233 btrfs_put_block_group(cache);
7234 goto out;
7235 }
7236
7237 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7238
7239 btrfs_add_free_space(cache, buf->start, buf->len);
7240 btrfs_free_reserved_bytes(cache, buf->len, 0);
7241 btrfs_put_block_group(cache);
7242 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7243 pin = 0;
7244 }
7245 out:
7246 if (pin)
7247 add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
7248 root->root_key.objectid);
7249
7250 /*
7251 * Deleting the buffer, clear the corrupt flag since it doesn't matter
7252 * anymore.
7253 */
7254 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7255 }
7256
7257 /* Can return -ENOMEM */
7258 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7259 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
7260 u64 owner, u64 offset)
7261 {
7262 int ret;
7263 struct btrfs_fs_info *fs_info = root->fs_info;
7264
7265 if (btrfs_is_testing(fs_info))
7266 return 0;
7267
7268 add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
7269
7270 /*
7271 * tree log blocks never actually go into the extent allocation
7272 * tree, just update pinning info and exit early.
7273 */
7274 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7275 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
7276 /* unlocks the pinned mutex */
7277 btrfs_pin_extent(root, bytenr, num_bytes, 1);
7278 ret = 0;
7279 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
7280 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7281 num_bytes,
7282 parent, root_objectid, (int)owner,
7283 BTRFS_DROP_DELAYED_REF, NULL);
7284 } else {
7285 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7286 num_bytes,
7287 parent, root_objectid, owner,
7288 offset, 0,
7289 BTRFS_DROP_DELAYED_REF, NULL);
7290 }
7291 return ret;
7292 }
7293
7294 /*
7295 * when we wait for progress in the block group caching, its because
7296 * our allocation attempt failed at least once. So, we must sleep
7297 * and let some progress happen before we try again.
7298 *
7299 * This function will sleep at least once waiting for new free space to
7300 * show up, and then it will check the block group free space numbers
7301 * for our min num_bytes. Another option is to have it go ahead
7302 * and look in the rbtree for a free extent of a given size, but this
7303 * is a good start.
7304 *
7305 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7306 * any of the information in this block group.
7307 */
7308 static noinline void
7309 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7310 u64 num_bytes)
7311 {
7312 struct btrfs_caching_control *caching_ctl;
7313
7314 caching_ctl = get_caching_control(cache);
7315 if (!caching_ctl)
7316 return;
7317
7318 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7319 (cache->free_space_ctl->free_space >= num_bytes));
7320
7321 put_caching_control(caching_ctl);
7322 }
7323
7324 static noinline int
7325 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7326 {
7327 struct btrfs_caching_control *caching_ctl;
7328 int ret = 0;
7329
7330 caching_ctl = get_caching_control(cache);
7331 if (!caching_ctl)
7332 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7333
7334 wait_event(caching_ctl->wait, block_group_cache_done(cache));
7335 if (cache->cached == BTRFS_CACHE_ERROR)
7336 ret = -EIO;
7337 put_caching_control(caching_ctl);
7338 return ret;
7339 }
7340
7341 int __get_raid_index(u64 flags)
7342 {
7343 if (flags & BTRFS_BLOCK_GROUP_RAID10)
7344 return BTRFS_RAID_RAID10;
7345 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
7346 return BTRFS_RAID_RAID1;
7347 else if (flags & BTRFS_BLOCK_GROUP_DUP)
7348 return BTRFS_RAID_DUP;
7349 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
7350 return BTRFS_RAID_RAID0;
7351 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
7352 return BTRFS_RAID_RAID5;
7353 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
7354 return BTRFS_RAID_RAID6;
7355
7356 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
7357 }
7358
7359 int get_block_group_index(struct btrfs_block_group_cache *cache)
7360 {
7361 return __get_raid_index(cache->flags);
7362 }
7363
7364 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
7365 [BTRFS_RAID_RAID10] = "raid10",
7366 [BTRFS_RAID_RAID1] = "raid1",
7367 [BTRFS_RAID_DUP] = "dup",
7368 [BTRFS_RAID_RAID0] = "raid0",
7369 [BTRFS_RAID_SINGLE] = "single",
7370 [BTRFS_RAID_RAID5] = "raid5",
7371 [BTRFS_RAID_RAID6] = "raid6",
7372 };
7373
7374 static const char *get_raid_name(enum btrfs_raid_types type)
7375 {
7376 if (type >= BTRFS_NR_RAID_TYPES)
7377 return NULL;
7378
7379 return btrfs_raid_type_names[type];
7380 }
7381
7382 enum btrfs_loop_type {
7383 LOOP_CACHING_NOWAIT = 0,
7384 LOOP_CACHING_WAIT = 1,
7385 LOOP_ALLOC_CHUNK = 2,
7386 LOOP_NO_EMPTY_SIZE = 3,
7387 };
7388
7389 static inline void
7390 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7391 int delalloc)
7392 {
7393 if (delalloc)
7394 down_read(&cache->data_rwsem);
7395 }
7396
7397 static inline void
7398 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7399 int delalloc)
7400 {
7401 btrfs_get_block_group(cache);
7402 if (delalloc)
7403 down_read(&cache->data_rwsem);
7404 }
7405
7406 static struct btrfs_block_group_cache *
7407 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7408 struct btrfs_free_cluster *cluster,
7409 int delalloc)
7410 {
7411 struct btrfs_block_group_cache *used_bg = NULL;
7412
7413 spin_lock(&cluster->refill_lock);
7414 while (1) {
7415 used_bg = cluster->block_group;
7416 if (!used_bg)
7417 return NULL;
7418
7419 if (used_bg == block_group)
7420 return used_bg;
7421
7422 btrfs_get_block_group(used_bg);
7423
7424 if (!delalloc)
7425 return used_bg;
7426
7427 if (down_read_trylock(&used_bg->data_rwsem))
7428 return used_bg;
7429
7430 spin_unlock(&cluster->refill_lock);
7431
7432 down_read(&used_bg->data_rwsem);
7433
7434 spin_lock(&cluster->refill_lock);
7435 if (used_bg == cluster->block_group)
7436 return used_bg;
7437
7438 up_read(&used_bg->data_rwsem);
7439 btrfs_put_block_group(used_bg);
7440 }
7441 }
7442
7443 static inline void
7444 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7445 int delalloc)
7446 {
7447 if (delalloc)
7448 up_read(&cache->data_rwsem);
7449 btrfs_put_block_group(cache);
7450 }
7451
7452 /*
7453 * walks the btree of allocated extents and find a hole of a given size.
7454 * The key ins is changed to record the hole:
7455 * ins->objectid == start position
7456 * ins->flags = BTRFS_EXTENT_ITEM_KEY
7457 * ins->offset == the size of the hole.
7458 * Any available blocks before search_start are skipped.
7459 *
7460 * If there is no suitable free space, we will record the max size of
7461 * the free space extent currently.
7462 */
7463 static noinline int find_free_extent(struct btrfs_root *orig_root,
7464 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7465 u64 hint_byte, struct btrfs_key *ins,
7466 u64 flags, int delalloc)
7467 {
7468 struct btrfs_fs_info *fs_info = orig_root->fs_info;
7469 int ret = 0;
7470 struct btrfs_root *root = fs_info->extent_root;
7471 struct btrfs_free_cluster *last_ptr = NULL;
7472 struct btrfs_block_group_cache *block_group = NULL;
7473 u64 search_start = 0;
7474 u64 max_extent_size = 0;
7475 u64 empty_cluster = 0;
7476 struct btrfs_space_info *space_info;
7477 int loop = 0;
7478 int index = __get_raid_index(flags);
7479 bool failed_cluster_refill = false;
7480 bool failed_alloc = false;
7481 bool use_cluster = true;
7482 bool have_caching_bg = false;
7483 bool orig_have_caching_bg = false;
7484 bool full_search = false;
7485
7486 WARN_ON(num_bytes < fs_info->sectorsize);
7487 ins->type = BTRFS_EXTENT_ITEM_KEY;
7488 ins->objectid = 0;
7489 ins->offset = 0;
7490
7491 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7492
7493 space_info = __find_space_info(fs_info, flags);
7494 if (!space_info) {
7495 btrfs_err(fs_info, "No space info for %llu", flags);
7496 return -ENOSPC;
7497 }
7498
7499 /*
7500 * If our free space is heavily fragmented we may not be able to make
7501 * big contiguous allocations, so instead of doing the expensive search
7502 * for free space, simply return ENOSPC with our max_extent_size so we
7503 * can go ahead and search for a more manageable chunk.
7504 *
7505 * If our max_extent_size is large enough for our allocation simply
7506 * disable clustering since we will likely not be able to find enough
7507 * space to create a cluster and induce latency trying.
7508 */
7509 if (unlikely(space_info->max_extent_size)) {
7510 spin_lock(&space_info->lock);
7511 if (space_info->max_extent_size &&
7512 num_bytes > space_info->max_extent_size) {
7513 ins->offset = space_info->max_extent_size;
7514 spin_unlock(&space_info->lock);
7515 return -ENOSPC;
7516 } else if (space_info->max_extent_size) {
7517 use_cluster = false;
7518 }
7519 spin_unlock(&space_info->lock);
7520 }
7521
7522 last_ptr = fetch_cluster_info(orig_root, space_info, &empty_cluster);
7523 if (last_ptr) {
7524 spin_lock(&last_ptr->lock);
7525 if (last_ptr->block_group)
7526 hint_byte = last_ptr->window_start;
7527 if (last_ptr->fragmented) {
7528 /*
7529 * We still set window_start so we can keep track of the
7530 * last place we found an allocation to try and save
7531 * some time.
7532 */
7533 hint_byte = last_ptr->window_start;
7534 use_cluster = false;
7535 }
7536 spin_unlock(&last_ptr->lock);
7537 }
7538
7539 search_start = max(search_start, first_logical_byte(root, 0));
7540 search_start = max(search_start, hint_byte);
7541 if (search_start == hint_byte) {
7542 block_group = btrfs_lookup_block_group(fs_info, search_start);
7543 /*
7544 * we don't want to use the block group if it doesn't match our
7545 * allocation bits, or if its not cached.
7546 *
7547 * However if we are re-searching with an ideal block group
7548 * picked out then we don't care that the block group is cached.
7549 */
7550 if (block_group && block_group_bits(block_group, flags) &&
7551 block_group->cached != BTRFS_CACHE_NO) {
7552 down_read(&space_info->groups_sem);
7553 if (list_empty(&block_group->list) ||
7554 block_group->ro) {
7555 /*
7556 * someone is removing this block group,
7557 * we can't jump into the have_block_group
7558 * target because our list pointers are not
7559 * valid
7560 */
7561 btrfs_put_block_group(block_group);
7562 up_read(&space_info->groups_sem);
7563 } else {
7564 index = get_block_group_index(block_group);
7565 btrfs_lock_block_group(block_group, delalloc);
7566 goto have_block_group;
7567 }
7568 } else if (block_group) {
7569 btrfs_put_block_group(block_group);
7570 }
7571 }
7572 search:
7573 have_caching_bg = false;
7574 if (index == 0 || index == __get_raid_index(flags))
7575 full_search = true;
7576 down_read(&space_info->groups_sem);
7577 list_for_each_entry(block_group, &space_info->block_groups[index],
7578 list) {
7579 u64 offset;
7580 int cached;
7581
7582 btrfs_grab_block_group(block_group, delalloc);
7583 search_start = block_group->key.objectid;
7584
7585 /*
7586 * this can happen if we end up cycling through all the
7587 * raid types, but we want to make sure we only allocate
7588 * for the proper type.
7589 */
7590 if (!block_group_bits(block_group, flags)) {
7591 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7592 BTRFS_BLOCK_GROUP_RAID1 |
7593 BTRFS_BLOCK_GROUP_RAID5 |
7594 BTRFS_BLOCK_GROUP_RAID6 |
7595 BTRFS_BLOCK_GROUP_RAID10;
7596
7597 /*
7598 * if they asked for extra copies and this block group
7599 * doesn't provide them, bail. This does allow us to
7600 * fill raid0 from raid1.
7601 */
7602 if ((flags & extra) && !(block_group->flags & extra))
7603 goto loop;
7604 }
7605
7606 have_block_group:
7607 cached = block_group_cache_done(block_group);
7608 if (unlikely(!cached)) {
7609 have_caching_bg = true;
7610 ret = cache_block_group(block_group, 0);
7611 BUG_ON(ret < 0);
7612 ret = 0;
7613 }
7614
7615 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7616 goto loop;
7617 if (unlikely(block_group->ro))
7618 goto loop;
7619
7620 /*
7621 * Ok we want to try and use the cluster allocator, so
7622 * lets look there
7623 */
7624 if (last_ptr && use_cluster) {
7625 struct btrfs_block_group_cache *used_block_group;
7626 unsigned long aligned_cluster;
7627 /*
7628 * the refill lock keeps out other
7629 * people trying to start a new cluster
7630 */
7631 used_block_group = btrfs_lock_cluster(block_group,
7632 last_ptr,
7633 delalloc);
7634 if (!used_block_group)
7635 goto refill_cluster;
7636
7637 if (used_block_group != block_group &&
7638 (used_block_group->ro ||
7639 !block_group_bits(used_block_group, flags)))
7640 goto release_cluster;
7641
7642 offset = btrfs_alloc_from_cluster(used_block_group,
7643 last_ptr,
7644 num_bytes,
7645 used_block_group->key.objectid,
7646 &max_extent_size);
7647 if (offset) {
7648 /* we have a block, we're done */
7649 spin_unlock(&last_ptr->refill_lock);
7650 trace_btrfs_reserve_extent_cluster(fs_info,
7651 used_block_group,
7652 search_start, num_bytes);
7653 if (used_block_group != block_group) {
7654 btrfs_release_block_group(block_group,
7655 delalloc);
7656 block_group = used_block_group;
7657 }
7658 goto checks;
7659 }
7660
7661 WARN_ON(last_ptr->block_group != used_block_group);
7662 release_cluster:
7663 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7664 * set up a new clusters, so lets just skip it
7665 * and let the allocator find whatever block
7666 * it can find. If we reach this point, we
7667 * will have tried the cluster allocator
7668 * plenty of times and not have found
7669 * anything, so we are likely way too
7670 * fragmented for the clustering stuff to find
7671 * anything.
7672 *
7673 * However, if the cluster is taken from the
7674 * current block group, release the cluster
7675 * first, so that we stand a better chance of
7676 * succeeding in the unclustered
7677 * allocation. */
7678 if (loop >= LOOP_NO_EMPTY_SIZE &&
7679 used_block_group != block_group) {
7680 spin_unlock(&last_ptr->refill_lock);
7681 btrfs_release_block_group(used_block_group,
7682 delalloc);
7683 goto unclustered_alloc;
7684 }
7685
7686 /*
7687 * this cluster didn't work out, free it and
7688 * start over
7689 */
7690 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7691
7692 if (used_block_group != block_group)
7693 btrfs_release_block_group(used_block_group,
7694 delalloc);
7695 refill_cluster:
7696 if (loop >= LOOP_NO_EMPTY_SIZE) {
7697 spin_unlock(&last_ptr->refill_lock);
7698 goto unclustered_alloc;
7699 }
7700
7701 aligned_cluster = max_t(unsigned long,
7702 empty_cluster + empty_size,
7703 block_group->full_stripe_len);
7704
7705 /* allocate a cluster in this block group */
7706 ret = btrfs_find_space_cluster(root, block_group,
7707 last_ptr, search_start,
7708 num_bytes,
7709 aligned_cluster);
7710 if (ret == 0) {
7711 /*
7712 * now pull our allocation out of this
7713 * cluster
7714 */
7715 offset = btrfs_alloc_from_cluster(block_group,
7716 last_ptr,
7717 num_bytes,
7718 search_start,
7719 &max_extent_size);
7720 if (offset) {
7721 /* we found one, proceed */
7722 spin_unlock(&last_ptr->refill_lock);
7723 trace_btrfs_reserve_extent_cluster(fs_info,
7724 block_group, search_start,
7725 num_bytes);
7726 goto checks;
7727 }
7728 } else if (!cached && loop > LOOP_CACHING_NOWAIT
7729 && !failed_cluster_refill) {
7730 spin_unlock(&last_ptr->refill_lock);
7731
7732 failed_cluster_refill = true;
7733 wait_block_group_cache_progress(block_group,
7734 num_bytes + empty_cluster + empty_size);
7735 goto have_block_group;
7736 }
7737
7738 /*
7739 * at this point we either didn't find a cluster
7740 * or we weren't able to allocate a block from our
7741 * cluster. Free the cluster we've been trying
7742 * to use, and go to the next block group
7743 */
7744 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7745 spin_unlock(&last_ptr->refill_lock);
7746 goto loop;
7747 }
7748
7749 unclustered_alloc:
7750 /*
7751 * We are doing an unclustered alloc, set the fragmented flag so
7752 * we don't bother trying to setup a cluster again until we get
7753 * more space.
7754 */
7755 if (unlikely(last_ptr)) {
7756 spin_lock(&last_ptr->lock);
7757 last_ptr->fragmented = 1;
7758 spin_unlock(&last_ptr->lock);
7759 }
7760 spin_lock(&block_group->free_space_ctl->tree_lock);
7761 if (cached &&
7762 block_group->free_space_ctl->free_space <
7763 num_bytes + empty_cluster + empty_size) {
7764 if (block_group->free_space_ctl->free_space >
7765 max_extent_size)
7766 max_extent_size =
7767 block_group->free_space_ctl->free_space;
7768 spin_unlock(&block_group->free_space_ctl->tree_lock);
7769 goto loop;
7770 }
7771 spin_unlock(&block_group->free_space_ctl->tree_lock);
7772
7773 offset = btrfs_find_space_for_alloc(block_group, search_start,
7774 num_bytes, empty_size,
7775 &max_extent_size);
7776 /*
7777 * If we didn't find a chunk, and we haven't failed on this
7778 * block group before, and this block group is in the middle of
7779 * caching and we are ok with waiting, then go ahead and wait
7780 * for progress to be made, and set failed_alloc to true.
7781 *
7782 * If failed_alloc is true then we've already waited on this
7783 * block group once and should move on to the next block group.
7784 */
7785 if (!offset && !failed_alloc && !cached &&
7786 loop > LOOP_CACHING_NOWAIT) {
7787 wait_block_group_cache_progress(block_group,
7788 num_bytes + empty_size);
7789 failed_alloc = true;
7790 goto have_block_group;
7791 } else if (!offset) {
7792 goto loop;
7793 }
7794 checks:
7795 search_start = ALIGN(offset, fs_info->stripesize);
7796
7797 /* move on to the next group */
7798 if (search_start + num_bytes >
7799 block_group->key.objectid + block_group->key.offset) {
7800 btrfs_add_free_space(block_group, offset, num_bytes);
7801 goto loop;
7802 }
7803
7804 if (offset < search_start)
7805 btrfs_add_free_space(block_group, offset,
7806 search_start - offset);
7807 BUG_ON(offset > search_start);
7808
7809 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7810 num_bytes, delalloc);
7811 if (ret == -EAGAIN) {
7812 btrfs_add_free_space(block_group, offset, num_bytes);
7813 goto loop;
7814 }
7815 btrfs_inc_block_group_reservations(block_group);
7816
7817 /* we are all good, lets return */
7818 ins->objectid = search_start;
7819 ins->offset = num_bytes;
7820
7821 trace_btrfs_reserve_extent(fs_info, block_group,
7822 search_start, num_bytes);
7823 btrfs_release_block_group(block_group, delalloc);
7824 break;
7825 loop:
7826 failed_cluster_refill = false;
7827 failed_alloc = false;
7828 BUG_ON(index != get_block_group_index(block_group));
7829 btrfs_release_block_group(block_group, delalloc);
7830 }
7831 up_read(&space_info->groups_sem);
7832
7833 if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7834 && !orig_have_caching_bg)
7835 orig_have_caching_bg = true;
7836
7837 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7838 goto search;
7839
7840 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7841 goto search;
7842
7843 /*
7844 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7845 * caching kthreads as we move along
7846 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7847 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7848 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7849 * again
7850 */
7851 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7852 index = 0;
7853 if (loop == LOOP_CACHING_NOWAIT) {
7854 /*
7855 * We want to skip the LOOP_CACHING_WAIT step if we
7856 * don't have any uncached bgs and we've already done a
7857 * full search through.
7858 */
7859 if (orig_have_caching_bg || !full_search)
7860 loop = LOOP_CACHING_WAIT;
7861 else
7862 loop = LOOP_ALLOC_CHUNK;
7863 } else {
7864 loop++;
7865 }
7866
7867 if (loop == LOOP_ALLOC_CHUNK) {
7868 struct btrfs_trans_handle *trans;
7869 int exist = 0;
7870
7871 trans = current->journal_info;
7872 if (trans)
7873 exist = 1;
7874 else
7875 trans = btrfs_join_transaction(root);
7876
7877 if (IS_ERR(trans)) {
7878 ret = PTR_ERR(trans);
7879 goto out;
7880 }
7881
7882 ret = do_chunk_alloc(trans, root, flags,
7883 CHUNK_ALLOC_FORCE);
7884
7885 /*
7886 * If we can't allocate a new chunk we've already looped
7887 * through at least once, move on to the NO_EMPTY_SIZE
7888 * case.
7889 */
7890 if (ret == -ENOSPC)
7891 loop = LOOP_NO_EMPTY_SIZE;
7892
7893 /*
7894 * Do not bail out on ENOSPC since we
7895 * can do more things.
7896 */
7897 if (ret < 0 && ret != -ENOSPC)
7898 btrfs_abort_transaction(trans, ret);
7899 else
7900 ret = 0;
7901 if (!exist)
7902 btrfs_end_transaction(trans, root);
7903 if (ret)
7904 goto out;
7905 }
7906
7907 if (loop == LOOP_NO_EMPTY_SIZE) {
7908 /*
7909 * Don't loop again if we already have no empty_size and
7910 * no empty_cluster.
7911 */
7912 if (empty_size == 0 &&
7913 empty_cluster == 0) {
7914 ret = -ENOSPC;
7915 goto out;
7916 }
7917 empty_size = 0;
7918 empty_cluster = 0;
7919 }
7920
7921 goto search;
7922 } else if (!ins->objectid) {
7923 ret = -ENOSPC;
7924 } else if (ins->objectid) {
7925 if (!use_cluster && last_ptr) {
7926 spin_lock(&last_ptr->lock);
7927 last_ptr->window_start = ins->objectid;
7928 spin_unlock(&last_ptr->lock);
7929 }
7930 ret = 0;
7931 }
7932 out:
7933 if (ret == -ENOSPC) {
7934 spin_lock(&space_info->lock);
7935 space_info->max_extent_size = max_extent_size;
7936 spin_unlock(&space_info->lock);
7937 ins->offset = max_extent_size;
7938 }
7939 return ret;
7940 }
7941
7942 static void dump_space_info(struct btrfs_fs_info *fs_info,
7943 struct btrfs_space_info *info, u64 bytes,
7944 int dump_block_groups)
7945 {
7946 struct btrfs_block_group_cache *cache;
7947 int index = 0;
7948
7949 spin_lock(&info->lock);
7950 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7951 info->flags,
7952 info->total_bytes - info->bytes_used - info->bytes_pinned -
7953 info->bytes_reserved - info->bytes_readonly -
7954 info->bytes_may_use, (info->full) ? "" : "not ");
7955 btrfs_info(fs_info,
7956 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7957 info->total_bytes, info->bytes_used, info->bytes_pinned,
7958 info->bytes_reserved, info->bytes_may_use,
7959 info->bytes_readonly);
7960 spin_unlock(&info->lock);
7961
7962 if (!dump_block_groups)
7963 return;
7964
7965 down_read(&info->groups_sem);
7966 again:
7967 list_for_each_entry(cache, &info->block_groups[index], list) {
7968 spin_lock(&cache->lock);
7969 btrfs_info(fs_info,
7970 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
7971 cache->key.objectid, cache->key.offset,
7972 btrfs_block_group_used(&cache->item), cache->pinned,
7973 cache->reserved, cache->ro ? "[readonly]" : "");
7974 btrfs_dump_free_space(cache, bytes);
7975 spin_unlock(&cache->lock);
7976 }
7977 if (++index < BTRFS_NR_RAID_TYPES)
7978 goto again;
7979 up_read(&info->groups_sem);
7980 }
7981
7982 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
7983 u64 num_bytes, u64 min_alloc_size,
7984 u64 empty_size, u64 hint_byte,
7985 struct btrfs_key *ins, int is_data, int delalloc)
7986 {
7987 struct btrfs_fs_info *fs_info = root->fs_info;
7988 bool final_tried = num_bytes == min_alloc_size;
7989 u64 flags;
7990 int ret;
7991
7992 flags = btrfs_get_alloc_profile(root, is_data);
7993 again:
7994 WARN_ON(num_bytes < fs_info->sectorsize);
7995 ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
7996 hint_byte, ins, flags, delalloc);
7997 if (!ret && !is_data) {
7998 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7999 } else if (ret == -ENOSPC) {
8000 if (!final_tried && ins->offset) {
8001 num_bytes = min(num_bytes >> 1, ins->offset);
8002 num_bytes = round_down(num_bytes,
8003 fs_info->sectorsize);
8004 num_bytes = max(num_bytes, min_alloc_size);
8005 ram_bytes = num_bytes;
8006 if (num_bytes == min_alloc_size)
8007 final_tried = true;
8008 goto again;
8009 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8010 struct btrfs_space_info *sinfo;
8011
8012 sinfo = __find_space_info(fs_info, flags);
8013 btrfs_err(fs_info,
8014 "allocation failed flags %llu, wanted %llu",
8015 flags, num_bytes);
8016 if (sinfo)
8017 dump_space_info(fs_info, sinfo, num_bytes, 1);
8018 }
8019 }
8020
8021 return ret;
8022 }
8023
8024 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
8025 u64 start, u64 len,
8026 int pin, int delalloc)
8027 {
8028 struct btrfs_fs_info *fs_info = root->fs_info;
8029 struct btrfs_block_group_cache *cache;
8030 int ret = 0;
8031
8032 cache = btrfs_lookup_block_group(fs_info, start);
8033 if (!cache) {
8034 btrfs_err(fs_info, "Unable to find block group for %llu",
8035 start);
8036 return -ENOSPC;
8037 }
8038
8039 if (pin)
8040 pin_down_extent(root, cache, start, len, 1);
8041 else {
8042 if (btrfs_test_opt(fs_info, DISCARD))
8043 ret = btrfs_discard_extent(root, start, len, NULL);
8044 btrfs_add_free_space(cache, start, len);
8045 btrfs_free_reserved_bytes(cache, len, delalloc);
8046 trace_btrfs_reserved_extent_free(fs_info, start, len);
8047 }
8048
8049 btrfs_put_block_group(cache);
8050 return ret;
8051 }
8052
8053 int btrfs_free_reserved_extent(struct btrfs_root *root,
8054 u64 start, u64 len, int delalloc)
8055 {
8056 return __btrfs_free_reserved_extent(root, start, len, 0, delalloc);
8057 }
8058
8059 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
8060 u64 start, u64 len)
8061 {
8062 return __btrfs_free_reserved_extent(root, start, len, 1, 0);
8063 }
8064
8065 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8066 struct btrfs_root *root,
8067 u64 parent, u64 root_objectid,
8068 u64 flags, u64 owner, u64 offset,
8069 struct btrfs_key *ins, int ref_mod)
8070 {
8071 int ret;
8072 struct btrfs_fs_info *fs_info = root->fs_info;
8073 struct btrfs_extent_item *extent_item;
8074 struct btrfs_extent_inline_ref *iref;
8075 struct btrfs_path *path;
8076 struct extent_buffer *leaf;
8077 int type;
8078 u32 size;
8079
8080 if (parent > 0)
8081 type = BTRFS_SHARED_DATA_REF_KEY;
8082 else
8083 type = BTRFS_EXTENT_DATA_REF_KEY;
8084
8085 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8086
8087 path = btrfs_alloc_path();
8088 if (!path)
8089 return -ENOMEM;
8090
8091 path->leave_spinning = 1;
8092 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8093 ins, size);
8094 if (ret) {
8095 btrfs_free_path(path);
8096 return ret;
8097 }
8098
8099 leaf = path->nodes[0];
8100 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8101 struct btrfs_extent_item);
8102 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8103 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8104 btrfs_set_extent_flags(leaf, extent_item,
8105 flags | BTRFS_EXTENT_FLAG_DATA);
8106
8107 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8108 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8109 if (parent > 0) {
8110 struct btrfs_shared_data_ref *ref;
8111 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8112 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8113 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8114 } else {
8115 struct btrfs_extent_data_ref *ref;
8116 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8117 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8118 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8119 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8120 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8121 }
8122
8123 btrfs_mark_buffer_dirty(path->nodes[0]);
8124 btrfs_free_path(path);
8125
8126 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8127 ins->offset);
8128 if (ret)
8129 return ret;
8130
8131 ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
8132 if (ret) { /* -ENOENT, logic error */
8133 btrfs_err(fs_info, "update block group failed for %llu %llu",
8134 ins->objectid, ins->offset);
8135 BUG();
8136 }
8137 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8138 return ret;
8139 }
8140
8141 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8142 struct btrfs_root *root,
8143 u64 parent, u64 root_objectid,
8144 u64 flags, struct btrfs_disk_key *key,
8145 int level, struct btrfs_key *ins)
8146 {
8147 int ret;
8148 struct btrfs_fs_info *fs_info = root->fs_info;
8149 struct btrfs_extent_item *extent_item;
8150 struct btrfs_tree_block_info *block_info;
8151 struct btrfs_extent_inline_ref *iref;
8152 struct btrfs_path *path;
8153 struct extent_buffer *leaf;
8154 u32 size = sizeof(*extent_item) + sizeof(*iref);
8155 u64 num_bytes = ins->offset;
8156 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8157
8158 if (!skinny_metadata)
8159 size += sizeof(*block_info);
8160
8161 path = btrfs_alloc_path();
8162 if (!path) {
8163 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
8164 fs_info->nodesize);
8165 return -ENOMEM;
8166 }
8167
8168 path->leave_spinning = 1;
8169 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8170 ins, size);
8171 if (ret) {
8172 btrfs_free_path(path);
8173 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
8174 fs_info->nodesize);
8175 return ret;
8176 }
8177
8178 leaf = path->nodes[0];
8179 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8180 struct btrfs_extent_item);
8181 btrfs_set_extent_refs(leaf, extent_item, 1);
8182 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8183 btrfs_set_extent_flags(leaf, extent_item,
8184 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8185
8186 if (skinny_metadata) {
8187 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8188 num_bytes = fs_info->nodesize;
8189 } else {
8190 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8191 btrfs_set_tree_block_key(leaf, block_info, key);
8192 btrfs_set_tree_block_level(leaf, block_info, level);
8193 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8194 }
8195
8196 if (parent > 0) {
8197 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8198 btrfs_set_extent_inline_ref_type(leaf, iref,
8199 BTRFS_SHARED_BLOCK_REF_KEY);
8200 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8201 } else {
8202 btrfs_set_extent_inline_ref_type(leaf, iref,
8203 BTRFS_TREE_BLOCK_REF_KEY);
8204 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
8205 }
8206
8207 btrfs_mark_buffer_dirty(leaf);
8208 btrfs_free_path(path);
8209
8210 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8211 num_bytes);
8212 if (ret)
8213 return ret;
8214
8215 ret = update_block_group(trans, fs_info, ins->objectid,
8216 fs_info->nodesize, 1);
8217 if (ret) { /* -ENOENT, logic error */
8218 btrfs_err(fs_info, "update block group failed for %llu %llu",
8219 ins->objectid, ins->offset);
8220 BUG();
8221 }
8222
8223 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
8224 fs_info->nodesize);
8225 return ret;
8226 }
8227
8228 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8229 struct btrfs_root *root,
8230 u64 root_objectid, u64 owner,
8231 u64 offset, u64 ram_bytes,
8232 struct btrfs_key *ins)
8233 {
8234 struct btrfs_fs_info *fs_info = root->fs_info;
8235 int ret;
8236
8237 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
8238
8239 ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
8240 ins->offset, 0,
8241 root_objectid, owner, offset,
8242 ram_bytes, BTRFS_ADD_DELAYED_EXTENT,
8243 NULL);
8244 return ret;
8245 }
8246
8247 /*
8248 * this is used by the tree logging recovery code. It records that
8249 * an extent has been allocated and makes sure to clear the free
8250 * space cache bits as well
8251 */
8252 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8253 struct btrfs_root *root,
8254 u64 root_objectid, u64 owner, u64 offset,
8255 struct btrfs_key *ins)
8256 {
8257 struct btrfs_fs_info *fs_info = root->fs_info;
8258 int ret;
8259 struct btrfs_block_group_cache *block_group;
8260 struct btrfs_space_info *space_info;
8261
8262 /*
8263 * Mixed block groups will exclude before processing the log so we only
8264 * need to do the exclude dance if this fs isn't mixed.
8265 */
8266 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8267 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
8268 if (ret)
8269 return ret;
8270 }
8271
8272 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8273 if (!block_group)
8274 return -EINVAL;
8275
8276 space_info = block_group->space_info;
8277 spin_lock(&space_info->lock);
8278 spin_lock(&block_group->lock);
8279 space_info->bytes_reserved += ins->offset;
8280 block_group->reserved += ins->offset;
8281 spin_unlock(&block_group->lock);
8282 spin_unlock(&space_info->lock);
8283
8284 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
8285 0, owner, offset, ins, 1);
8286 btrfs_put_block_group(block_group);
8287 return ret;
8288 }
8289
8290 static struct extent_buffer *
8291 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8292 u64 bytenr, int level)
8293 {
8294 struct btrfs_fs_info *fs_info = root->fs_info;
8295 struct extent_buffer *buf;
8296
8297 buf = btrfs_find_create_tree_block(root, bytenr);
8298 if (IS_ERR(buf))
8299 return buf;
8300
8301 btrfs_set_header_generation(buf, trans->transid);
8302 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8303 btrfs_tree_lock(buf);
8304 clean_tree_block(trans, fs_info, buf);
8305 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8306
8307 btrfs_set_lock_blocking(buf);
8308 set_extent_buffer_uptodate(buf);
8309
8310 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8311 buf->log_index = root->log_transid % 2;
8312 /*
8313 * we allow two log transactions at a time, use different
8314 * EXENT bit to differentiate dirty pages.
8315 */
8316 if (buf->log_index == 0)
8317 set_extent_dirty(&root->dirty_log_pages, buf->start,
8318 buf->start + buf->len - 1, GFP_NOFS);
8319 else
8320 set_extent_new(&root->dirty_log_pages, buf->start,
8321 buf->start + buf->len - 1);
8322 } else {
8323 buf->log_index = -1;
8324 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8325 buf->start + buf->len - 1, GFP_NOFS);
8326 }
8327 trans->dirty = true;
8328 /* this returns a buffer locked for blocking */
8329 return buf;
8330 }
8331
8332 static struct btrfs_block_rsv *
8333 use_block_rsv(struct btrfs_trans_handle *trans,
8334 struct btrfs_root *root, u32 blocksize)
8335 {
8336 struct btrfs_fs_info *fs_info = root->fs_info;
8337 struct btrfs_block_rsv *block_rsv;
8338 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8339 int ret;
8340 bool global_updated = false;
8341
8342 block_rsv = get_block_rsv(trans, root);
8343
8344 if (unlikely(block_rsv->size == 0))
8345 goto try_reserve;
8346 again:
8347 ret = block_rsv_use_bytes(block_rsv, blocksize);
8348 if (!ret)
8349 return block_rsv;
8350
8351 if (block_rsv->failfast)
8352 return ERR_PTR(ret);
8353
8354 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8355 global_updated = true;
8356 update_global_block_rsv(fs_info);
8357 goto again;
8358 }
8359
8360 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8361 static DEFINE_RATELIMIT_STATE(_rs,
8362 DEFAULT_RATELIMIT_INTERVAL * 10,
8363 /*DEFAULT_RATELIMIT_BURST*/ 1);
8364 if (__ratelimit(&_rs))
8365 WARN(1, KERN_DEBUG
8366 "BTRFS: block rsv returned %d\n", ret);
8367 }
8368 try_reserve:
8369 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8370 BTRFS_RESERVE_NO_FLUSH);
8371 if (!ret)
8372 return block_rsv;
8373 /*
8374 * If we couldn't reserve metadata bytes try and use some from
8375 * the global reserve if its space type is the same as the global
8376 * reservation.
8377 */
8378 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8379 block_rsv->space_info == global_rsv->space_info) {
8380 ret = block_rsv_use_bytes(global_rsv, blocksize);
8381 if (!ret)
8382 return global_rsv;
8383 }
8384 return ERR_PTR(ret);
8385 }
8386
8387 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8388 struct btrfs_block_rsv *block_rsv, u32 blocksize)
8389 {
8390 block_rsv_add_bytes(block_rsv, blocksize, 0);
8391 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
8392 }
8393
8394 /*
8395 * finds a free extent and does all the dirty work required for allocation
8396 * returns the tree buffer or an ERR_PTR on error.
8397 */
8398 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8399 struct btrfs_root *root,
8400 u64 parent, u64 root_objectid,
8401 struct btrfs_disk_key *key, int level,
8402 u64 hint, u64 empty_size)
8403 {
8404 struct btrfs_fs_info *fs_info = root->fs_info;
8405 struct btrfs_key ins;
8406 struct btrfs_block_rsv *block_rsv;
8407 struct extent_buffer *buf;
8408 struct btrfs_delayed_extent_op *extent_op;
8409 u64 flags = 0;
8410 int ret;
8411 u32 blocksize = fs_info->nodesize;
8412 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8413
8414 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8415 if (btrfs_is_testing(fs_info)) {
8416 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8417 level);
8418 if (!IS_ERR(buf))
8419 root->alloc_bytenr += blocksize;
8420 return buf;
8421 }
8422 #endif
8423
8424 block_rsv = use_block_rsv(trans, root, blocksize);
8425 if (IS_ERR(block_rsv))
8426 return ERR_CAST(block_rsv);
8427
8428 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8429 empty_size, hint, &ins, 0, 0);
8430 if (ret)
8431 goto out_unuse;
8432
8433 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
8434 if (IS_ERR(buf)) {
8435 ret = PTR_ERR(buf);
8436 goto out_free_reserved;
8437 }
8438
8439 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8440 if (parent == 0)
8441 parent = ins.objectid;
8442 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8443 } else
8444 BUG_ON(parent > 0);
8445
8446 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8447 extent_op = btrfs_alloc_delayed_extent_op();
8448 if (!extent_op) {
8449 ret = -ENOMEM;
8450 goto out_free_buf;
8451 }
8452 if (key)
8453 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8454 else
8455 memset(&extent_op->key, 0, sizeof(extent_op->key));
8456 extent_op->flags_to_set = flags;
8457 extent_op->update_key = skinny_metadata ? false : true;
8458 extent_op->update_flags = true;
8459 extent_op->is_data = false;
8460 extent_op->level = level;
8461
8462 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
8463 ins.objectid, ins.offset,
8464 parent, root_objectid, level,
8465 BTRFS_ADD_DELAYED_EXTENT,
8466 extent_op);
8467 if (ret)
8468 goto out_free_delayed;
8469 }
8470 return buf;
8471
8472 out_free_delayed:
8473 btrfs_free_delayed_extent_op(extent_op);
8474 out_free_buf:
8475 free_extent_buffer(buf);
8476 out_free_reserved:
8477 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0);
8478 out_unuse:
8479 unuse_block_rsv(fs_info, block_rsv, blocksize);
8480 return ERR_PTR(ret);
8481 }
8482
8483 struct walk_control {
8484 u64 refs[BTRFS_MAX_LEVEL];
8485 u64 flags[BTRFS_MAX_LEVEL];
8486 struct btrfs_key update_progress;
8487 int stage;
8488 int level;
8489 int shared_level;
8490 int update_ref;
8491 int keep_locks;
8492 int reada_slot;
8493 int reada_count;
8494 int for_reloc;
8495 };
8496
8497 #define DROP_REFERENCE 1
8498 #define UPDATE_BACKREF 2
8499
8500 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8501 struct btrfs_root *root,
8502 struct walk_control *wc,
8503 struct btrfs_path *path)
8504 {
8505 struct btrfs_fs_info *fs_info = root->fs_info;
8506 u64 bytenr;
8507 u64 generation;
8508 u64 refs;
8509 u64 flags;
8510 u32 nritems;
8511 struct btrfs_key key;
8512 struct extent_buffer *eb;
8513 int ret;
8514 int slot;
8515 int nread = 0;
8516
8517 if (path->slots[wc->level] < wc->reada_slot) {
8518 wc->reada_count = wc->reada_count * 2 / 3;
8519 wc->reada_count = max(wc->reada_count, 2);
8520 } else {
8521 wc->reada_count = wc->reada_count * 3 / 2;
8522 wc->reada_count = min_t(int, wc->reada_count,
8523 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8524 }
8525
8526 eb = path->nodes[wc->level];
8527 nritems = btrfs_header_nritems(eb);
8528
8529 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8530 if (nread >= wc->reada_count)
8531 break;
8532
8533 cond_resched();
8534 bytenr = btrfs_node_blockptr(eb, slot);
8535 generation = btrfs_node_ptr_generation(eb, slot);
8536
8537 if (slot == path->slots[wc->level])
8538 goto reada;
8539
8540 if (wc->stage == UPDATE_BACKREF &&
8541 generation <= root->root_key.offset)
8542 continue;
8543
8544 /* We don't lock the tree block, it's OK to be racy here */
8545 ret = btrfs_lookup_extent_info(trans, root, bytenr,
8546 wc->level - 1, 1, &refs,
8547 &flags);
8548 /* We don't care about errors in readahead. */
8549 if (ret < 0)
8550 continue;
8551 BUG_ON(refs == 0);
8552
8553 if (wc->stage == DROP_REFERENCE) {
8554 if (refs == 1)
8555 goto reada;
8556
8557 if (wc->level == 1 &&
8558 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8559 continue;
8560 if (!wc->update_ref ||
8561 generation <= root->root_key.offset)
8562 continue;
8563 btrfs_node_key_to_cpu(eb, &key, slot);
8564 ret = btrfs_comp_cpu_keys(&key,
8565 &wc->update_progress);
8566 if (ret < 0)
8567 continue;
8568 } else {
8569 if (wc->level == 1 &&
8570 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8571 continue;
8572 }
8573 reada:
8574 readahead_tree_block(root, bytenr);
8575 nread++;
8576 }
8577 wc->reada_slot = slot;
8578 }
8579
8580 /*
8581 * helper to process tree block while walking down the tree.
8582 *
8583 * when wc->stage == UPDATE_BACKREF, this function updates
8584 * back refs for pointers in the block.
8585 *
8586 * NOTE: return value 1 means we should stop walking down.
8587 */
8588 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8589 struct btrfs_root *root,
8590 struct btrfs_path *path,
8591 struct walk_control *wc, int lookup_info)
8592 {
8593 int level = wc->level;
8594 struct extent_buffer *eb = path->nodes[level];
8595 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8596 int ret;
8597
8598 if (wc->stage == UPDATE_BACKREF &&
8599 btrfs_header_owner(eb) != root->root_key.objectid)
8600 return 1;
8601
8602 /*
8603 * when reference count of tree block is 1, it won't increase
8604 * again. once full backref flag is set, we never clear it.
8605 */
8606 if (lookup_info &&
8607 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8608 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8609 BUG_ON(!path->locks[level]);
8610 ret = btrfs_lookup_extent_info(trans, root,
8611 eb->start, level, 1,
8612 &wc->refs[level],
8613 &wc->flags[level]);
8614 BUG_ON(ret == -ENOMEM);
8615 if (ret)
8616 return ret;
8617 BUG_ON(wc->refs[level] == 0);
8618 }
8619
8620 if (wc->stage == DROP_REFERENCE) {
8621 if (wc->refs[level] > 1)
8622 return 1;
8623
8624 if (path->locks[level] && !wc->keep_locks) {
8625 btrfs_tree_unlock_rw(eb, path->locks[level]);
8626 path->locks[level] = 0;
8627 }
8628 return 0;
8629 }
8630
8631 /* wc->stage == UPDATE_BACKREF */
8632 if (!(wc->flags[level] & flag)) {
8633 BUG_ON(!path->locks[level]);
8634 ret = btrfs_inc_ref(trans, root, eb, 1);
8635 BUG_ON(ret); /* -ENOMEM */
8636 ret = btrfs_dec_ref(trans, root, eb, 0);
8637 BUG_ON(ret); /* -ENOMEM */
8638 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
8639 eb->len, flag,
8640 btrfs_header_level(eb), 0);
8641 BUG_ON(ret); /* -ENOMEM */
8642 wc->flags[level] |= flag;
8643 }
8644
8645 /*
8646 * the block is shared by multiple trees, so it's not good to
8647 * keep the tree lock
8648 */
8649 if (path->locks[level] && level > 0) {
8650 btrfs_tree_unlock_rw(eb, path->locks[level]);
8651 path->locks[level] = 0;
8652 }
8653 return 0;
8654 }
8655
8656 /*
8657 * helper to process tree block pointer.
8658 *
8659 * when wc->stage == DROP_REFERENCE, this function checks
8660 * reference count of the block pointed to. if the block
8661 * is shared and we need update back refs for the subtree
8662 * rooted at the block, this function changes wc->stage to
8663 * UPDATE_BACKREF. if the block is shared and there is no
8664 * need to update back, this function drops the reference
8665 * to the block.
8666 *
8667 * NOTE: return value 1 means we should stop walking down.
8668 */
8669 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8670 struct btrfs_root *root,
8671 struct btrfs_path *path,
8672 struct walk_control *wc, int *lookup_info)
8673 {
8674 struct btrfs_fs_info *fs_info = root->fs_info;
8675 u64 bytenr;
8676 u64 generation;
8677 u64 parent;
8678 u32 blocksize;
8679 struct btrfs_key key;
8680 struct extent_buffer *next;
8681 int level = wc->level;
8682 int reada = 0;
8683 int ret = 0;
8684 bool need_account = false;
8685
8686 generation = btrfs_node_ptr_generation(path->nodes[level],
8687 path->slots[level]);
8688 /*
8689 * if the lower level block was created before the snapshot
8690 * was created, we know there is no need to update back refs
8691 * for the subtree
8692 */
8693 if (wc->stage == UPDATE_BACKREF &&
8694 generation <= root->root_key.offset) {
8695 *lookup_info = 1;
8696 return 1;
8697 }
8698
8699 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8700 blocksize = fs_info->nodesize;
8701
8702 next = find_extent_buffer(fs_info, bytenr);
8703 if (!next) {
8704 next = btrfs_find_create_tree_block(root, bytenr);
8705 if (IS_ERR(next))
8706 return PTR_ERR(next);
8707
8708 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8709 level - 1);
8710 reada = 1;
8711 }
8712 btrfs_tree_lock(next);
8713 btrfs_set_lock_blocking(next);
8714
8715 ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
8716 &wc->refs[level - 1],
8717 &wc->flags[level - 1]);
8718 if (ret < 0)
8719 goto out_unlock;
8720
8721 if (unlikely(wc->refs[level - 1] == 0)) {
8722 btrfs_err(fs_info, "Missing references.");
8723 ret = -EIO;
8724 goto out_unlock;
8725 }
8726 *lookup_info = 0;
8727
8728 if (wc->stage == DROP_REFERENCE) {
8729 if (wc->refs[level - 1] > 1) {
8730 need_account = true;
8731 if (level == 1 &&
8732 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8733 goto skip;
8734
8735 if (!wc->update_ref ||
8736 generation <= root->root_key.offset)
8737 goto skip;
8738
8739 btrfs_node_key_to_cpu(path->nodes[level], &key,
8740 path->slots[level]);
8741 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8742 if (ret < 0)
8743 goto skip;
8744
8745 wc->stage = UPDATE_BACKREF;
8746 wc->shared_level = level - 1;
8747 }
8748 } else {
8749 if (level == 1 &&
8750 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8751 goto skip;
8752 }
8753
8754 if (!btrfs_buffer_uptodate(next, generation, 0)) {
8755 btrfs_tree_unlock(next);
8756 free_extent_buffer(next);
8757 next = NULL;
8758 *lookup_info = 1;
8759 }
8760
8761 if (!next) {
8762 if (reada && level == 1)
8763 reada_walk_down(trans, root, wc, path);
8764 next = read_tree_block(root, bytenr, generation);
8765 if (IS_ERR(next)) {
8766 return PTR_ERR(next);
8767 } else if (!extent_buffer_uptodate(next)) {
8768 free_extent_buffer(next);
8769 return -EIO;
8770 }
8771 btrfs_tree_lock(next);
8772 btrfs_set_lock_blocking(next);
8773 }
8774
8775 level--;
8776 ASSERT(level == btrfs_header_level(next));
8777 if (level != btrfs_header_level(next)) {
8778 btrfs_err(root->fs_info, "mismatched level");
8779 ret = -EIO;
8780 goto out_unlock;
8781 }
8782 path->nodes[level] = next;
8783 path->slots[level] = 0;
8784 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8785 wc->level = level;
8786 if (wc->level == 1)
8787 wc->reada_slot = 0;
8788 return 0;
8789 skip:
8790 wc->refs[level - 1] = 0;
8791 wc->flags[level - 1] = 0;
8792 if (wc->stage == DROP_REFERENCE) {
8793 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8794 parent = path->nodes[level]->start;
8795 } else {
8796 ASSERT(root->root_key.objectid ==
8797 btrfs_header_owner(path->nodes[level]));
8798 if (root->root_key.objectid !=
8799 btrfs_header_owner(path->nodes[level])) {
8800 btrfs_err(root->fs_info,
8801 "mismatched block owner");
8802 ret = -EIO;
8803 goto out_unlock;
8804 }
8805 parent = 0;
8806 }
8807
8808 if (need_account) {
8809 ret = btrfs_qgroup_trace_subtree(trans, root, next,
8810 generation, level - 1);
8811 if (ret) {
8812 btrfs_err_rl(fs_info,
8813 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8814 ret);
8815 }
8816 }
8817 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
8818 root->root_key.objectid, level - 1, 0);
8819 if (ret)
8820 goto out_unlock;
8821 }
8822
8823 *lookup_info = 1;
8824 ret = 1;
8825
8826 out_unlock:
8827 btrfs_tree_unlock(next);
8828 free_extent_buffer(next);
8829
8830 return ret;
8831 }
8832
8833 /*
8834 * helper to process tree block while walking up the tree.
8835 *
8836 * when wc->stage == DROP_REFERENCE, this function drops
8837 * reference count on the block.
8838 *
8839 * when wc->stage == UPDATE_BACKREF, this function changes
8840 * wc->stage back to DROP_REFERENCE if we changed wc->stage
8841 * to UPDATE_BACKREF previously while processing the block.
8842 *
8843 * NOTE: return value 1 means we should stop walking up.
8844 */
8845 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8846 struct btrfs_root *root,
8847 struct btrfs_path *path,
8848 struct walk_control *wc)
8849 {
8850 struct btrfs_fs_info *fs_info = root->fs_info;
8851 int ret;
8852 int level = wc->level;
8853 struct extent_buffer *eb = path->nodes[level];
8854 u64 parent = 0;
8855
8856 if (wc->stage == UPDATE_BACKREF) {
8857 BUG_ON(wc->shared_level < level);
8858 if (level < wc->shared_level)
8859 goto out;
8860
8861 ret = find_next_key(path, level + 1, &wc->update_progress);
8862 if (ret > 0)
8863 wc->update_ref = 0;
8864
8865 wc->stage = DROP_REFERENCE;
8866 wc->shared_level = -1;
8867 path->slots[level] = 0;
8868
8869 /*
8870 * check reference count again if the block isn't locked.
8871 * we should start walking down the tree again if reference
8872 * count is one.
8873 */
8874 if (!path->locks[level]) {
8875 BUG_ON(level == 0);
8876 btrfs_tree_lock(eb);
8877 btrfs_set_lock_blocking(eb);
8878 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8879
8880 ret = btrfs_lookup_extent_info(trans, root,
8881 eb->start, level, 1,
8882 &wc->refs[level],
8883 &wc->flags[level]);
8884 if (ret < 0) {
8885 btrfs_tree_unlock_rw(eb, path->locks[level]);
8886 path->locks[level] = 0;
8887 return ret;
8888 }
8889 BUG_ON(wc->refs[level] == 0);
8890 if (wc->refs[level] == 1) {
8891 btrfs_tree_unlock_rw(eb, path->locks[level]);
8892 path->locks[level] = 0;
8893 return 1;
8894 }
8895 }
8896 }
8897
8898 /* wc->stage == DROP_REFERENCE */
8899 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8900
8901 if (wc->refs[level] == 1) {
8902 if (level == 0) {
8903 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8904 ret = btrfs_dec_ref(trans, root, eb, 1);
8905 else
8906 ret = btrfs_dec_ref(trans, root, eb, 0);
8907 BUG_ON(ret); /* -ENOMEM */
8908 ret = btrfs_qgroup_trace_leaf_items(trans, root, eb);
8909 if (ret) {
8910 btrfs_err_rl(fs_info,
8911 "error %d accounting leaf items. Quota is out of sync, rescan required.",
8912 ret);
8913 }
8914 }
8915 /* make block locked assertion in clean_tree_block happy */
8916 if (!path->locks[level] &&
8917 btrfs_header_generation(eb) == trans->transid) {
8918 btrfs_tree_lock(eb);
8919 btrfs_set_lock_blocking(eb);
8920 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8921 }
8922 clean_tree_block(trans, fs_info, eb);
8923 }
8924
8925 if (eb == root->node) {
8926 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8927 parent = eb->start;
8928 else
8929 BUG_ON(root->root_key.objectid !=
8930 btrfs_header_owner(eb));
8931 } else {
8932 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8933 parent = path->nodes[level + 1]->start;
8934 else
8935 BUG_ON(root->root_key.objectid !=
8936 btrfs_header_owner(path->nodes[level + 1]));
8937 }
8938
8939 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8940 out:
8941 wc->refs[level] = 0;
8942 wc->flags[level] = 0;
8943 return 0;
8944 }
8945
8946 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8947 struct btrfs_root *root,
8948 struct btrfs_path *path,
8949 struct walk_control *wc)
8950 {
8951 int level = wc->level;
8952 int lookup_info = 1;
8953 int ret;
8954
8955 while (level >= 0) {
8956 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8957 if (ret > 0)
8958 break;
8959
8960 if (level == 0)
8961 break;
8962
8963 if (path->slots[level] >=
8964 btrfs_header_nritems(path->nodes[level]))
8965 break;
8966
8967 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8968 if (ret > 0) {
8969 path->slots[level]++;
8970 continue;
8971 } else if (ret < 0)
8972 return ret;
8973 level = wc->level;
8974 }
8975 return 0;
8976 }
8977
8978 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8979 struct btrfs_root *root,
8980 struct btrfs_path *path,
8981 struct walk_control *wc, int max_level)
8982 {
8983 int level = wc->level;
8984 int ret;
8985
8986 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8987 while (level < max_level && path->nodes[level]) {
8988 wc->level = level;
8989 if (path->slots[level] + 1 <
8990 btrfs_header_nritems(path->nodes[level])) {
8991 path->slots[level]++;
8992 return 0;
8993 } else {
8994 ret = walk_up_proc(trans, root, path, wc);
8995 if (ret > 0)
8996 return 0;
8997
8998 if (path->locks[level]) {
8999 btrfs_tree_unlock_rw(path->nodes[level],
9000 path->locks[level]);
9001 path->locks[level] = 0;
9002 }
9003 free_extent_buffer(path->nodes[level]);
9004 path->nodes[level] = NULL;
9005 level++;
9006 }
9007 }
9008 return 1;
9009 }
9010
9011 /*
9012 * drop a subvolume tree.
9013 *
9014 * this function traverses the tree freeing any blocks that only
9015 * referenced by the tree.
9016 *
9017 * when a shared tree block is found. this function decreases its
9018 * reference count by one. if update_ref is true, this function
9019 * also make sure backrefs for the shared block and all lower level
9020 * blocks are properly updated.
9021 *
9022 * If called with for_reloc == 0, may exit early with -EAGAIN
9023 */
9024 int btrfs_drop_snapshot(struct btrfs_root *root,
9025 struct btrfs_block_rsv *block_rsv, int update_ref,
9026 int for_reloc)
9027 {
9028 struct btrfs_fs_info *fs_info = root->fs_info;
9029 struct btrfs_path *path;
9030 struct btrfs_trans_handle *trans;
9031 struct btrfs_root *tree_root = fs_info->tree_root;
9032 struct btrfs_root_item *root_item = &root->root_item;
9033 struct walk_control *wc;
9034 struct btrfs_key key;
9035 int err = 0;
9036 int ret;
9037 int level;
9038 bool root_dropped = false;
9039
9040 btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
9041
9042 path = btrfs_alloc_path();
9043 if (!path) {
9044 err = -ENOMEM;
9045 goto out;
9046 }
9047
9048 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9049 if (!wc) {
9050 btrfs_free_path(path);
9051 err = -ENOMEM;
9052 goto out;
9053 }
9054
9055 trans = btrfs_start_transaction(tree_root, 0);
9056 if (IS_ERR(trans)) {
9057 err = PTR_ERR(trans);
9058 goto out_free;
9059 }
9060
9061 if (block_rsv)
9062 trans->block_rsv = block_rsv;
9063
9064 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9065 level = btrfs_header_level(root->node);
9066 path->nodes[level] = btrfs_lock_root_node(root);
9067 btrfs_set_lock_blocking(path->nodes[level]);
9068 path->slots[level] = 0;
9069 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9070 memset(&wc->update_progress, 0,
9071 sizeof(wc->update_progress));
9072 } else {
9073 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9074 memcpy(&wc->update_progress, &key,
9075 sizeof(wc->update_progress));
9076
9077 level = root_item->drop_level;
9078 BUG_ON(level == 0);
9079 path->lowest_level = level;
9080 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9081 path->lowest_level = 0;
9082 if (ret < 0) {
9083 err = ret;
9084 goto out_end_trans;
9085 }
9086 WARN_ON(ret > 0);
9087
9088 /*
9089 * unlock our path, this is safe because only this
9090 * function is allowed to delete this snapshot
9091 */
9092 btrfs_unlock_up_safe(path, 0);
9093
9094 level = btrfs_header_level(root->node);
9095 while (1) {
9096 btrfs_tree_lock(path->nodes[level]);
9097 btrfs_set_lock_blocking(path->nodes[level]);
9098 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9099
9100 ret = btrfs_lookup_extent_info(trans, root,
9101 path->nodes[level]->start,
9102 level, 1, &wc->refs[level],
9103 &wc->flags[level]);
9104 if (ret < 0) {
9105 err = ret;
9106 goto out_end_trans;
9107 }
9108 BUG_ON(wc->refs[level] == 0);
9109
9110 if (level == root_item->drop_level)
9111 break;
9112
9113 btrfs_tree_unlock(path->nodes[level]);
9114 path->locks[level] = 0;
9115 WARN_ON(wc->refs[level] != 1);
9116 level--;
9117 }
9118 }
9119
9120 wc->level = level;
9121 wc->shared_level = -1;
9122 wc->stage = DROP_REFERENCE;
9123 wc->update_ref = update_ref;
9124 wc->keep_locks = 0;
9125 wc->for_reloc = for_reloc;
9126 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9127
9128 while (1) {
9129
9130 ret = walk_down_tree(trans, root, path, wc);
9131 if (ret < 0) {
9132 err = ret;
9133 break;
9134 }
9135
9136 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9137 if (ret < 0) {
9138 err = ret;
9139 break;
9140 }
9141
9142 if (ret > 0) {
9143 BUG_ON(wc->stage != DROP_REFERENCE);
9144 break;
9145 }
9146
9147 if (wc->stage == DROP_REFERENCE) {
9148 level = wc->level;
9149 btrfs_node_key(path->nodes[level],
9150 &root_item->drop_progress,
9151 path->slots[level]);
9152 root_item->drop_level = level;
9153 }
9154
9155 BUG_ON(wc->level == 0);
9156 if (btrfs_should_end_transaction(trans, tree_root) ||
9157 (!for_reloc && btrfs_need_cleaner_sleep(root))) {
9158 ret = btrfs_update_root(trans, tree_root,
9159 &root->root_key,
9160 root_item);
9161 if (ret) {
9162 btrfs_abort_transaction(trans, ret);
9163 err = ret;
9164 goto out_end_trans;
9165 }
9166
9167 btrfs_end_transaction_throttle(trans, tree_root);
9168 if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
9169 btrfs_debug(fs_info,
9170 "drop snapshot early exit");
9171 err = -EAGAIN;
9172 goto out_free;
9173 }
9174
9175 trans = btrfs_start_transaction(tree_root, 0);
9176 if (IS_ERR(trans)) {
9177 err = PTR_ERR(trans);
9178 goto out_free;
9179 }
9180 if (block_rsv)
9181 trans->block_rsv = block_rsv;
9182 }
9183 }
9184 btrfs_release_path(path);
9185 if (err)
9186 goto out_end_trans;
9187
9188 ret = btrfs_del_root(trans, tree_root, &root->root_key);
9189 if (ret) {
9190 btrfs_abort_transaction(trans, ret);
9191 goto out_end_trans;
9192 }
9193
9194 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9195 ret = btrfs_find_root(tree_root, &root->root_key, path,
9196 NULL, NULL);
9197 if (ret < 0) {
9198 btrfs_abort_transaction(trans, ret);
9199 err = ret;
9200 goto out_end_trans;
9201 } else if (ret > 0) {
9202 /* if we fail to delete the orphan item this time
9203 * around, it'll get picked up the next time.
9204 *
9205 * The most common failure here is just -ENOENT.
9206 */
9207 btrfs_del_orphan_item(trans, tree_root,
9208 root->root_key.objectid);
9209 }
9210 }
9211
9212 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9213 btrfs_add_dropped_root(trans, root);
9214 } else {
9215 free_extent_buffer(root->node);
9216 free_extent_buffer(root->commit_root);
9217 btrfs_put_fs_root(root);
9218 }
9219 root_dropped = true;
9220 out_end_trans:
9221 btrfs_end_transaction_throttle(trans, tree_root);
9222 out_free:
9223 kfree(wc);
9224 btrfs_free_path(path);
9225 out:
9226 /*
9227 * So if we need to stop dropping the snapshot for whatever reason we
9228 * need to make sure to add it back to the dead root list so that we
9229 * keep trying to do the work later. This also cleans up roots if we
9230 * don't have it in the radix (like when we recover after a power fail
9231 * or unmount) so we don't leak memory.
9232 */
9233 if (!for_reloc && root_dropped == false)
9234 btrfs_add_dead_root(root);
9235 if (err && err != -EAGAIN)
9236 btrfs_handle_fs_error(fs_info, err, NULL);
9237 return err;
9238 }
9239
9240 /*
9241 * drop subtree rooted at tree block 'node'.
9242 *
9243 * NOTE: this function will unlock and release tree block 'node'
9244 * only used by relocation code
9245 */
9246 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9247 struct btrfs_root *root,
9248 struct extent_buffer *node,
9249 struct extent_buffer *parent)
9250 {
9251 struct btrfs_fs_info *fs_info = root->fs_info;
9252 struct btrfs_path *path;
9253 struct walk_control *wc;
9254 int level;
9255 int parent_level;
9256 int ret = 0;
9257 int wret;
9258
9259 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9260
9261 path = btrfs_alloc_path();
9262 if (!path)
9263 return -ENOMEM;
9264
9265 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9266 if (!wc) {
9267 btrfs_free_path(path);
9268 return -ENOMEM;
9269 }
9270
9271 btrfs_assert_tree_locked(parent);
9272 parent_level = btrfs_header_level(parent);
9273 extent_buffer_get(parent);
9274 path->nodes[parent_level] = parent;
9275 path->slots[parent_level] = btrfs_header_nritems(parent);
9276
9277 btrfs_assert_tree_locked(node);
9278 level = btrfs_header_level(node);
9279 path->nodes[level] = node;
9280 path->slots[level] = 0;
9281 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9282
9283 wc->refs[parent_level] = 1;
9284 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9285 wc->level = level;
9286 wc->shared_level = -1;
9287 wc->stage = DROP_REFERENCE;
9288 wc->update_ref = 0;
9289 wc->keep_locks = 1;
9290 wc->for_reloc = 1;
9291 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9292
9293 while (1) {
9294 wret = walk_down_tree(trans, root, path, wc);
9295 if (wret < 0) {
9296 ret = wret;
9297 break;
9298 }
9299
9300 wret = walk_up_tree(trans, root, path, wc, parent_level);
9301 if (wret < 0)
9302 ret = wret;
9303 if (wret != 0)
9304 break;
9305 }
9306
9307 kfree(wc);
9308 btrfs_free_path(path);
9309 return ret;
9310 }
9311
9312 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9313 {
9314 u64 num_devices;
9315 u64 stripped;
9316
9317 /*
9318 * if restripe for this chunk_type is on pick target profile and
9319 * return, otherwise do the usual balance
9320 */
9321 stripped = get_restripe_target(fs_info, flags);
9322 if (stripped)
9323 return extended_to_chunk(stripped);
9324
9325 num_devices = fs_info->fs_devices->rw_devices;
9326
9327 stripped = BTRFS_BLOCK_GROUP_RAID0 |
9328 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9329 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9330
9331 if (num_devices == 1) {
9332 stripped |= BTRFS_BLOCK_GROUP_DUP;
9333 stripped = flags & ~stripped;
9334
9335 /* turn raid0 into single device chunks */
9336 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9337 return stripped;
9338
9339 /* turn mirroring into duplication */
9340 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9341 BTRFS_BLOCK_GROUP_RAID10))
9342 return stripped | BTRFS_BLOCK_GROUP_DUP;
9343 } else {
9344 /* they already had raid on here, just return */
9345 if (flags & stripped)
9346 return flags;
9347
9348 stripped |= BTRFS_BLOCK_GROUP_DUP;
9349 stripped = flags & ~stripped;
9350
9351 /* switch duplicated blocks with raid1 */
9352 if (flags & BTRFS_BLOCK_GROUP_DUP)
9353 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9354
9355 /* this is drive concat, leave it alone */
9356 }
9357
9358 return flags;
9359 }
9360
9361 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9362 {
9363 struct btrfs_space_info *sinfo = cache->space_info;
9364 u64 num_bytes;
9365 u64 min_allocable_bytes;
9366 int ret = -ENOSPC;
9367
9368 /*
9369 * We need some metadata space and system metadata space for
9370 * allocating chunks in some corner cases until we force to set
9371 * it to be readonly.
9372 */
9373 if ((sinfo->flags &
9374 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9375 !force)
9376 min_allocable_bytes = SZ_1M;
9377 else
9378 min_allocable_bytes = 0;
9379
9380 spin_lock(&sinfo->lock);
9381 spin_lock(&cache->lock);
9382
9383 if (cache->ro) {
9384 cache->ro++;
9385 ret = 0;
9386 goto out;
9387 }
9388
9389 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9390 cache->bytes_super - btrfs_block_group_used(&cache->item);
9391
9392 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
9393 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
9394 min_allocable_bytes <= sinfo->total_bytes) {
9395 sinfo->bytes_readonly += num_bytes;
9396 cache->ro++;
9397 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9398 ret = 0;
9399 }
9400 out:
9401 spin_unlock(&cache->lock);
9402 spin_unlock(&sinfo->lock);
9403 return ret;
9404 }
9405
9406 int btrfs_inc_block_group_ro(struct btrfs_root *root,
9407 struct btrfs_block_group_cache *cache)
9408
9409 {
9410 struct btrfs_fs_info *fs_info = root->fs_info;
9411 struct btrfs_trans_handle *trans;
9412 u64 alloc_flags;
9413 int ret;
9414
9415 again:
9416 trans = btrfs_join_transaction(root);
9417 if (IS_ERR(trans))
9418 return PTR_ERR(trans);
9419
9420 /*
9421 * we're not allowed to set block groups readonly after the dirty
9422 * block groups cache has started writing. If it already started,
9423 * back off and let this transaction commit
9424 */
9425 mutex_lock(&fs_info->ro_block_group_mutex);
9426 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9427 u64 transid = trans->transid;
9428
9429 mutex_unlock(&fs_info->ro_block_group_mutex);
9430 btrfs_end_transaction(trans, root);
9431
9432 ret = btrfs_wait_for_commit(root, transid);
9433 if (ret)
9434 return ret;
9435 goto again;
9436 }
9437
9438 /*
9439 * if we are changing raid levels, try to allocate a corresponding
9440 * block group with the new raid level.
9441 */
9442 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9443 if (alloc_flags != cache->flags) {
9444 ret = do_chunk_alloc(trans, root, alloc_flags,
9445 CHUNK_ALLOC_FORCE);
9446 /*
9447 * ENOSPC is allowed here, we may have enough space
9448 * already allocated at the new raid level to
9449 * carry on
9450 */
9451 if (ret == -ENOSPC)
9452 ret = 0;
9453 if (ret < 0)
9454 goto out;
9455 }
9456
9457 ret = inc_block_group_ro(cache, 0);
9458 if (!ret)
9459 goto out;
9460 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
9461 ret = do_chunk_alloc(trans, root, alloc_flags,
9462 CHUNK_ALLOC_FORCE);
9463 if (ret < 0)
9464 goto out;
9465 ret = inc_block_group_ro(cache, 0);
9466 out:
9467 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9468 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9469 lock_chunks(fs_info);
9470 check_system_chunk(trans, root, alloc_flags);
9471 unlock_chunks(fs_info);
9472 }
9473 mutex_unlock(&fs_info->ro_block_group_mutex);
9474
9475 btrfs_end_transaction(trans, root);
9476 return ret;
9477 }
9478
9479 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
9480 struct btrfs_root *root, u64 type)
9481 {
9482 u64 alloc_flags = get_alloc_profile(root, type);
9483 return do_chunk_alloc(trans, root, alloc_flags,
9484 CHUNK_ALLOC_FORCE);
9485 }
9486
9487 /*
9488 * helper to account the unused space of all the readonly block group in the
9489 * space_info. takes mirrors into account.
9490 */
9491 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9492 {
9493 struct btrfs_block_group_cache *block_group;
9494 u64 free_bytes = 0;
9495 int factor;
9496
9497 /* It's df, we don't care if it's racy */
9498 if (list_empty(&sinfo->ro_bgs))
9499 return 0;
9500
9501 spin_lock(&sinfo->lock);
9502 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9503 spin_lock(&block_group->lock);
9504
9505 if (!block_group->ro) {
9506 spin_unlock(&block_group->lock);
9507 continue;
9508 }
9509
9510 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9511 BTRFS_BLOCK_GROUP_RAID10 |
9512 BTRFS_BLOCK_GROUP_DUP))
9513 factor = 2;
9514 else
9515 factor = 1;
9516
9517 free_bytes += (block_group->key.offset -
9518 btrfs_block_group_used(&block_group->item)) *
9519 factor;
9520
9521 spin_unlock(&block_group->lock);
9522 }
9523 spin_unlock(&sinfo->lock);
9524
9525 return free_bytes;
9526 }
9527
9528 void btrfs_dec_block_group_ro(struct btrfs_root *root,
9529 struct btrfs_block_group_cache *cache)
9530 {
9531 struct btrfs_space_info *sinfo = cache->space_info;
9532 u64 num_bytes;
9533
9534 BUG_ON(!cache->ro);
9535
9536 spin_lock(&sinfo->lock);
9537 spin_lock(&cache->lock);
9538 if (!--cache->ro) {
9539 num_bytes = cache->key.offset - cache->reserved -
9540 cache->pinned - cache->bytes_super -
9541 btrfs_block_group_used(&cache->item);
9542 sinfo->bytes_readonly -= num_bytes;
9543 list_del_init(&cache->ro_list);
9544 }
9545 spin_unlock(&cache->lock);
9546 spin_unlock(&sinfo->lock);
9547 }
9548
9549 /*
9550 * checks to see if its even possible to relocate this block group.
9551 *
9552 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9553 * ok to go ahead and try.
9554 */
9555 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9556 {
9557 struct btrfs_root *root = fs_info->extent_root;
9558 struct btrfs_block_group_cache *block_group;
9559 struct btrfs_space_info *space_info;
9560 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9561 struct btrfs_device *device;
9562 struct btrfs_trans_handle *trans;
9563 u64 min_free;
9564 u64 dev_min = 1;
9565 u64 dev_nr = 0;
9566 u64 target;
9567 int debug;
9568 int index;
9569 int full = 0;
9570 int ret = 0;
9571
9572 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9573
9574 block_group = btrfs_lookup_block_group(fs_info, bytenr);
9575
9576 /* odd, couldn't find the block group, leave it alone */
9577 if (!block_group) {
9578 if (debug)
9579 btrfs_warn(fs_info,
9580 "can't find block group for bytenr %llu",
9581 bytenr);
9582 return -1;
9583 }
9584
9585 min_free = btrfs_block_group_used(&block_group->item);
9586
9587 /* no bytes used, we're good */
9588 if (!min_free)
9589 goto out;
9590
9591 space_info = block_group->space_info;
9592 spin_lock(&space_info->lock);
9593
9594 full = space_info->full;
9595
9596 /*
9597 * if this is the last block group we have in this space, we can't
9598 * relocate it unless we're able to allocate a new chunk below.
9599 *
9600 * Otherwise, we need to make sure we have room in the space to handle
9601 * all of the extents from this block group. If we can, we're good
9602 */
9603 if ((space_info->total_bytes != block_group->key.offset) &&
9604 (space_info->bytes_used + space_info->bytes_reserved +
9605 space_info->bytes_pinned + space_info->bytes_readonly +
9606 min_free < space_info->total_bytes)) {
9607 spin_unlock(&space_info->lock);
9608 goto out;
9609 }
9610 spin_unlock(&space_info->lock);
9611
9612 /*
9613 * ok we don't have enough space, but maybe we have free space on our
9614 * devices to allocate new chunks for relocation, so loop through our
9615 * alloc devices and guess if we have enough space. if this block
9616 * group is going to be restriped, run checks against the target
9617 * profile instead of the current one.
9618 */
9619 ret = -1;
9620
9621 /*
9622 * index:
9623 * 0: raid10
9624 * 1: raid1
9625 * 2: dup
9626 * 3: raid0
9627 * 4: single
9628 */
9629 target = get_restripe_target(fs_info, block_group->flags);
9630 if (target) {
9631 index = __get_raid_index(extended_to_chunk(target));
9632 } else {
9633 /*
9634 * this is just a balance, so if we were marked as full
9635 * we know there is no space for a new chunk
9636 */
9637 if (full) {
9638 if (debug)
9639 btrfs_warn(fs_info,
9640 "no space to alloc new chunk for block group %llu",
9641 block_group->key.objectid);
9642 goto out;
9643 }
9644
9645 index = get_block_group_index(block_group);
9646 }
9647
9648 if (index == BTRFS_RAID_RAID10) {
9649 dev_min = 4;
9650 /* Divide by 2 */
9651 min_free >>= 1;
9652 } else if (index == BTRFS_RAID_RAID1) {
9653 dev_min = 2;
9654 } else if (index == BTRFS_RAID_DUP) {
9655 /* Multiply by 2 */
9656 min_free <<= 1;
9657 } else if (index == BTRFS_RAID_RAID0) {
9658 dev_min = fs_devices->rw_devices;
9659 min_free = div64_u64(min_free, dev_min);
9660 }
9661
9662 /* We need to do this so that we can look at pending chunks */
9663 trans = btrfs_join_transaction(root);
9664 if (IS_ERR(trans)) {
9665 ret = PTR_ERR(trans);
9666 goto out;
9667 }
9668
9669 mutex_lock(&fs_info->chunk_mutex);
9670 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9671 u64 dev_offset;
9672
9673 /*
9674 * check to make sure we can actually find a chunk with enough
9675 * space to fit our block group in.
9676 */
9677 if (device->total_bytes > device->bytes_used + min_free &&
9678 !device->is_tgtdev_for_dev_replace) {
9679 ret = find_free_dev_extent(trans, device, min_free,
9680 &dev_offset, NULL);
9681 if (!ret)
9682 dev_nr++;
9683
9684 if (dev_nr >= dev_min)
9685 break;
9686
9687 ret = -1;
9688 }
9689 }
9690 if (debug && ret == -1)
9691 btrfs_warn(fs_info,
9692 "no space to allocate a new chunk for block group %llu",
9693 block_group->key.objectid);
9694 mutex_unlock(&fs_info->chunk_mutex);
9695 btrfs_end_transaction(trans, root);
9696 out:
9697 btrfs_put_block_group(block_group);
9698 return ret;
9699 }
9700
9701 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9702 struct btrfs_path *path,
9703 struct btrfs_key *key)
9704 {
9705 struct btrfs_root *root = fs_info->extent_root;
9706 int ret = 0;
9707 struct btrfs_key found_key;
9708 struct extent_buffer *leaf;
9709 int slot;
9710
9711 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9712 if (ret < 0)
9713 goto out;
9714
9715 while (1) {
9716 slot = path->slots[0];
9717 leaf = path->nodes[0];
9718 if (slot >= btrfs_header_nritems(leaf)) {
9719 ret = btrfs_next_leaf(root, path);
9720 if (ret == 0)
9721 continue;
9722 if (ret < 0)
9723 goto out;
9724 break;
9725 }
9726 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9727
9728 if (found_key.objectid >= key->objectid &&
9729 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9730 struct extent_map_tree *em_tree;
9731 struct extent_map *em;
9732
9733 em_tree = &root->fs_info->mapping_tree.map_tree;
9734 read_lock(&em_tree->lock);
9735 em = lookup_extent_mapping(em_tree, found_key.objectid,
9736 found_key.offset);
9737 read_unlock(&em_tree->lock);
9738 if (!em) {
9739 btrfs_err(fs_info,
9740 "logical %llu len %llu found bg but no related chunk",
9741 found_key.objectid, found_key.offset);
9742 ret = -ENOENT;
9743 } else {
9744 ret = 0;
9745 }
9746 free_extent_map(em);
9747 goto out;
9748 }
9749 path->slots[0]++;
9750 }
9751 out:
9752 return ret;
9753 }
9754
9755 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9756 {
9757 struct btrfs_block_group_cache *block_group;
9758 u64 last = 0;
9759
9760 while (1) {
9761 struct inode *inode;
9762
9763 block_group = btrfs_lookup_first_block_group(info, last);
9764 while (block_group) {
9765 spin_lock(&block_group->lock);
9766 if (block_group->iref)
9767 break;
9768 spin_unlock(&block_group->lock);
9769 block_group = next_block_group(info->tree_root,
9770 block_group);
9771 }
9772 if (!block_group) {
9773 if (last == 0)
9774 break;
9775 last = 0;
9776 continue;
9777 }
9778
9779 inode = block_group->inode;
9780 block_group->iref = 0;
9781 block_group->inode = NULL;
9782 spin_unlock(&block_group->lock);
9783 ASSERT(block_group->io_ctl.inode == NULL);
9784 iput(inode);
9785 last = block_group->key.objectid + block_group->key.offset;
9786 btrfs_put_block_group(block_group);
9787 }
9788 }
9789
9790 int btrfs_free_block_groups(struct btrfs_fs_info *info)
9791 {
9792 struct btrfs_block_group_cache *block_group;
9793 struct btrfs_space_info *space_info;
9794 struct btrfs_caching_control *caching_ctl;
9795 struct rb_node *n;
9796
9797 down_write(&info->commit_root_sem);
9798 while (!list_empty(&info->caching_block_groups)) {
9799 caching_ctl = list_entry(info->caching_block_groups.next,
9800 struct btrfs_caching_control, list);
9801 list_del(&caching_ctl->list);
9802 put_caching_control(caching_ctl);
9803 }
9804 up_write(&info->commit_root_sem);
9805
9806 spin_lock(&info->unused_bgs_lock);
9807 while (!list_empty(&info->unused_bgs)) {
9808 block_group = list_first_entry(&info->unused_bgs,
9809 struct btrfs_block_group_cache,
9810 bg_list);
9811 list_del_init(&block_group->bg_list);
9812 btrfs_put_block_group(block_group);
9813 }
9814 spin_unlock(&info->unused_bgs_lock);
9815
9816 spin_lock(&info->block_group_cache_lock);
9817 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9818 block_group = rb_entry(n, struct btrfs_block_group_cache,
9819 cache_node);
9820 rb_erase(&block_group->cache_node,
9821 &info->block_group_cache_tree);
9822 RB_CLEAR_NODE(&block_group->cache_node);
9823 spin_unlock(&info->block_group_cache_lock);
9824
9825 down_write(&block_group->space_info->groups_sem);
9826 list_del(&block_group->list);
9827 up_write(&block_group->space_info->groups_sem);
9828
9829 if (block_group->cached == BTRFS_CACHE_STARTED)
9830 wait_block_group_cache_done(block_group);
9831
9832 /*
9833 * We haven't cached this block group, which means we could
9834 * possibly have excluded extents on this block group.
9835 */
9836 if (block_group->cached == BTRFS_CACHE_NO ||
9837 block_group->cached == BTRFS_CACHE_ERROR)
9838 free_excluded_extents(info->extent_root, block_group);
9839
9840 btrfs_remove_free_space_cache(block_group);
9841 ASSERT(list_empty(&block_group->dirty_list));
9842 ASSERT(list_empty(&block_group->io_list));
9843 ASSERT(list_empty(&block_group->bg_list));
9844 ASSERT(atomic_read(&block_group->count) == 1);
9845 btrfs_put_block_group(block_group);
9846
9847 spin_lock(&info->block_group_cache_lock);
9848 }
9849 spin_unlock(&info->block_group_cache_lock);
9850
9851 /* now that all the block groups are freed, go through and
9852 * free all the space_info structs. This is only called during
9853 * the final stages of unmount, and so we know nobody is
9854 * using them. We call synchronize_rcu() once before we start,
9855 * just to be on the safe side.
9856 */
9857 synchronize_rcu();
9858
9859 release_global_block_rsv(info);
9860
9861 while (!list_empty(&info->space_info)) {
9862 int i;
9863
9864 space_info = list_entry(info->space_info.next,
9865 struct btrfs_space_info,
9866 list);
9867
9868 /*
9869 * Do not hide this behind enospc_debug, this is actually
9870 * important and indicates a real bug if this happens.
9871 */
9872 if (WARN_ON(space_info->bytes_pinned > 0 ||
9873 space_info->bytes_reserved > 0 ||
9874 space_info->bytes_may_use > 0))
9875 dump_space_info(info, space_info, 0, 0);
9876 list_del(&space_info->list);
9877 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9878 struct kobject *kobj;
9879 kobj = space_info->block_group_kobjs[i];
9880 space_info->block_group_kobjs[i] = NULL;
9881 if (kobj) {
9882 kobject_del(kobj);
9883 kobject_put(kobj);
9884 }
9885 }
9886 kobject_del(&space_info->kobj);
9887 kobject_put(&space_info->kobj);
9888 }
9889 return 0;
9890 }
9891
9892 static void __link_block_group(struct btrfs_space_info *space_info,
9893 struct btrfs_block_group_cache *cache)
9894 {
9895 int index = get_block_group_index(cache);
9896 bool first = false;
9897
9898 down_write(&space_info->groups_sem);
9899 if (list_empty(&space_info->block_groups[index]))
9900 first = true;
9901 list_add_tail(&cache->list, &space_info->block_groups[index]);
9902 up_write(&space_info->groups_sem);
9903
9904 if (first) {
9905 struct raid_kobject *rkobj;
9906 int ret;
9907
9908 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9909 if (!rkobj)
9910 goto out_err;
9911 rkobj->raid_type = index;
9912 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9913 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9914 "%s", get_raid_name(index));
9915 if (ret) {
9916 kobject_put(&rkobj->kobj);
9917 goto out_err;
9918 }
9919 space_info->block_group_kobjs[index] = &rkobj->kobj;
9920 }
9921
9922 return;
9923 out_err:
9924 btrfs_warn(cache->fs_info,
9925 "failed to add kobject for block cache, ignoring");
9926 }
9927
9928 static struct btrfs_block_group_cache *
9929 btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
9930 {
9931 struct btrfs_fs_info *fs_info = root->fs_info;
9932 struct btrfs_block_group_cache *cache;
9933
9934 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9935 if (!cache)
9936 return NULL;
9937
9938 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9939 GFP_NOFS);
9940 if (!cache->free_space_ctl) {
9941 kfree(cache);
9942 return NULL;
9943 }
9944
9945 cache->key.objectid = start;
9946 cache->key.offset = size;
9947 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9948
9949 cache->sectorsize = fs_info->sectorsize;
9950 cache->fs_info = fs_info;
9951 cache->full_stripe_len = btrfs_full_stripe_len(root,
9952 &fs_info->mapping_tree, start);
9953 set_free_space_tree_thresholds(cache);
9954
9955 atomic_set(&cache->count, 1);
9956 spin_lock_init(&cache->lock);
9957 init_rwsem(&cache->data_rwsem);
9958 INIT_LIST_HEAD(&cache->list);
9959 INIT_LIST_HEAD(&cache->cluster_list);
9960 INIT_LIST_HEAD(&cache->bg_list);
9961 INIT_LIST_HEAD(&cache->ro_list);
9962 INIT_LIST_HEAD(&cache->dirty_list);
9963 INIT_LIST_HEAD(&cache->io_list);
9964 btrfs_init_free_space_ctl(cache);
9965 atomic_set(&cache->trimming, 0);
9966 mutex_init(&cache->free_space_lock);
9967
9968 return cache;
9969 }
9970
9971 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9972 {
9973 struct btrfs_root *root = info->extent_root;
9974 struct btrfs_path *path;
9975 int ret;
9976 struct btrfs_block_group_cache *cache;
9977 struct btrfs_space_info *space_info;
9978 struct btrfs_key key;
9979 struct btrfs_key found_key;
9980 struct extent_buffer *leaf;
9981 int need_clear = 0;
9982 u64 cache_gen;
9983 u64 feature;
9984 int mixed;
9985
9986 feature = btrfs_super_incompat_flags(info->super_copy);
9987 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9988
9989 key.objectid = 0;
9990 key.offset = 0;
9991 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9992 path = btrfs_alloc_path();
9993 if (!path)
9994 return -ENOMEM;
9995 path->reada = READA_FORWARD;
9996
9997 cache_gen = btrfs_super_cache_generation(info->super_copy);
9998 if (btrfs_test_opt(info, SPACE_CACHE) &&
9999 btrfs_super_generation(info->super_copy) != cache_gen)
10000 need_clear = 1;
10001 if (btrfs_test_opt(info, CLEAR_CACHE))
10002 need_clear = 1;
10003
10004 while (1) {
10005 ret = find_first_block_group(info, path, &key);
10006 if (ret > 0)
10007 break;
10008 if (ret != 0)
10009 goto error;
10010
10011 leaf = path->nodes[0];
10012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
10013
10014 cache = btrfs_create_block_group_cache(root, found_key.objectid,
10015 found_key.offset);
10016 if (!cache) {
10017 ret = -ENOMEM;
10018 goto error;
10019 }
10020
10021 if (need_clear) {
10022 /*
10023 * When we mount with old space cache, we need to
10024 * set BTRFS_DC_CLEAR and set dirty flag.
10025 *
10026 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
10027 * truncate the old free space cache inode and
10028 * setup a new one.
10029 * b) Setting 'dirty flag' makes sure that we flush
10030 * the new space cache info onto disk.
10031 */
10032 if (btrfs_test_opt(info, SPACE_CACHE))
10033 cache->disk_cache_state = BTRFS_DC_CLEAR;
10034 }
10035
10036 read_extent_buffer(leaf, &cache->item,
10037 btrfs_item_ptr_offset(leaf, path->slots[0]),
10038 sizeof(cache->item));
10039 cache->flags = btrfs_block_group_flags(&cache->item);
10040 if (!mixed &&
10041 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
10042 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10043 btrfs_err(info,
10044 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10045 cache->key.objectid);
10046 ret = -EINVAL;
10047 goto error;
10048 }
10049
10050 key.objectid = found_key.objectid + found_key.offset;
10051 btrfs_release_path(path);
10052
10053 /*
10054 * We need to exclude the super stripes now so that the space
10055 * info has super bytes accounted for, otherwise we'll think
10056 * we have more space than we actually do.
10057 */
10058 ret = exclude_super_stripes(root, cache);
10059 if (ret) {
10060 /*
10061 * We may have excluded something, so call this just in
10062 * case.
10063 */
10064 free_excluded_extents(root, cache);
10065 btrfs_put_block_group(cache);
10066 goto error;
10067 }
10068
10069 /*
10070 * check for two cases, either we are full, and therefore
10071 * don't need to bother with the caching work since we won't
10072 * find any space, or we are empty, and we can just add all
10073 * the space in and be done with it. This saves us _alot_ of
10074 * time, particularly in the full case.
10075 */
10076 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10077 cache->last_byte_to_unpin = (u64)-1;
10078 cache->cached = BTRFS_CACHE_FINISHED;
10079 free_excluded_extents(root, cache);
10080 } else if (btrfs_block_group_used(&cache->item) == 0) {
10081 cache->last_byte_to_unpin = (u64)-1;
10082 cache->cached = BTRFS_CACHE_FINISHED;
10083 add_new_free_space(cache, info,
10084 found_key.objectid,
10085 found_key.objectid +
10086 found_key.offset);
10087 free_excluded_extents(root, cache);
10088 }
10089
10090 ret = btrfs_add_block_group_cache(info, cache);
10091 if (ret) {
10092 btrfs_remove_free_space_cache(cache);
10093 btrfs_put_block_group(cache);
10094 goto error;
10095 }
10096
10097 trace_btrfs_add_block_group(info, cache, 0);
10098 ret = update_space_info(info, cache->flags, found_key.offset,
10099 btrfs_block_group_used(&cache->item),
10100 cache->bytes_super, &space_info);
10101 if (ret) {
10102 btrfs_remove_free_space_cache(cache);
10103 spin_lock(&info->block_group_cache_lock);
10104 rb_erase(&cache->cache_node,
10105 &info->block_group_cache_tree);
10106 RB_CLEAR_NODE(&cache->cache_node);
10107 spin_unlock(&info->block_group_cache_lock);
10108 btrfs_put_block_group(cache);
10109 goto error;
10110 }
10111
10112 cache->space_info = space_info;
10113
10114 __link_block_group(space_info, cache);
10115
10116 set_avail_alloc_bits(info, cache->flags);
10117 if (btrfs_chunk_readonly(root, cache->key.objectid)) {
10118 inc_block_group_ro(cache, 1);
10119 } else if (btrfs_block_group_used(&cache->item) == 0) {
10120 spin_lock(&info->unused_bgs_lock);
10121 /* Should always be true but just in case. */
10122 if (list_empty(&cache->bg_list)) {
10123 btrfs_get_block_group(cache);
10124 list_add_tail(&cache->bg_list,
10125 &info->unused_bgs);
10126 }
10127 spin_unlock(&info->unused_bgs_lock);
10128 }
10129 }
10130
10131 list_for_each_entry_rcu(space_info, &info->space_info, list) {
10132 if (!(get_alloc_profile(root, space_info->flags) &
10133 (BTRFS_BLOCK_GROUP_RAID10 |
10134 BTRFS_BLOCK_GROUP_RAID1 |
10135 BTRFS_BLOCK_GROUP_RAID5 |
10136 BTRFS_BLOCK_GROUP_RAID6 |
10137 BTRFS_BLOCK_GROUP_DUP)))
10138 continue;
10139 /*
10140 * avoid allocating from un-mirrored block group if there are
10141 * mirrored block groups.
10142 */
10143 list_for_each_entry(cache,
10144 &space_info->block_groups[BTRFS_RAID_RAID0],
10145 list)
10146 inc_block_group_ro(cache, 1);
10147 list_for_each_entry(cache,
10148 &space_info->block_groups[BTRFS_RAID_SINGLE],
10149 list)
10150 inc_block_group_ro(cache, 1);
10151 }
10152
10153 init_global_block_rsv(info);
10154 ret = 0;
10155 error:
10156 btrfs_free_path(path);
10157 return ret;
10158 }
10159
10160 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
10161 struct btrfs_root *root)
10162 {
10163 struct btrfs_fs_info *fs_info = root->fs_info;
10164 struct btrfs_block_group_cache *block_group, *tmp;
10165 struct btrfs_root *extent_root = fs_info->extent_root;
10166 struct btrfs_block_group_item item;
10167 struct btrfs_key key;
10168 int ret = 0;
10169 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
10170
10171 trans->can_flush_pending_bgs = false;
10172 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
10173 if (ret)
10174 goto next;
10175
10176 spin_lock(&block_group->lock);
10177 memcpy(&item, &block_group->item, sizeof(item));
10178 memcpy(&key, &block_group->key, sizeof(key));
10179 spin_unlock(&block_group->lock);
10180
10181 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10182 sizeof(item));
10183 if (ret)
10184 btrfs_abort_transaction(trans, ret);
10185 ret = btrfs_finish_chunk_alloc(trans, fs_info, key.objectid,
10186 key.offset);
10187 if (ret)
10188 btrfs_abort_transaction(trans, ret);
10189 add_block_group_free_space(trans, fs_info, block_group);
10190 /* already aborted the transaction if it failed. */
10191 next:
10192 list_del_init(&block_group->bg_list);
10193 }
10194 trans->can_flush_pending_bgs = can_flush_pending_bgs;
10195 }
10196
10197 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
10198 struct btrfs_root *root, u64 bytes_used,
10199 u64 type, u64 chunk_objectid, u64 chunk_offset,
10200 u64 size)
10201 {
10202 struct btrfs_fs_info *fs_info = root->fs_info;
10203 struct btrfs_block_group_cache *cache;
10204 int ret;
10205
10206 btrfs_set_log_full_commit(fs_info, trans);
10207
10208 cache = btrfs_create_block_group_cache(root, chunk_offset, size);
10209 if (!cache)
10210 return -ENOMEM;
10211
10212 btrfs_set_block_group_used(&cache->item, bytes_used);
10213 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
10214 btrfs_set_block_group_flags(&cache->item, type);
10215
10216 cache->flags = type;
10217 cache->last_byte_to_unpin = (u64)-1;
10218 cache->cached = BTRFS_CACHE_FINISHED;
10219 cache->needs_free_space = 1;
10220 ret = exclude_super_stripes(root, cache);
10221 if (ret) {
10222 /*
10223 * We may have excluded something, so call this just in
10224 * case.
10225 */
10226 free_excluded_extents(root, cache);
10227 btrfs_put_block_group(cache);
10228 return ret;
10229 }
10230
10231 add_new_free_space(cache, fs_info, chunk_offset, chunk_offset + size);
10232
10233 free_excluded_extents(root, cache);
10234
10235 #ifdef CONFIG_BTRFS_DEBUG
10236 if (btrfs_should_fragment_free_space(root, cache)) {
10237 u64 new_bytes_used = size - bytes_used;
10238
10239 bytes_used += new_bytes_used >> 1;
10240 fragment_free_space(root, cache);
10241 }
10242 #endif
10243 /*
10244 * Call to ensure the corresponding space_info object is created and
10245 * assigned to our block group, but don't update its counters just yet.
10246 * We want our bg to be added to the rbtree with its ->space_info set.
10247 */
10248 ret = update_space_info(fs_info, cache->flags, 0, 0, 0,
10249 &cache->space_info);
10250 if (ret) {
10251 btrfs_remove_free_space_cache(cache);
10252 btrfs_put_block_group(cache);
10253 return ret;
10254 }
10255
10256 ret = btrfs_add_block_group_cache(fs_info, cache);
10257 if (ret) {
10258 btrfs_remove_free_space_cache(cache);
10259 btrfs_put_block_group(cache);
10260 return ret;
10261 }
10262
10263 /*
10264 * Now that our block group has its ->space_info set and is inserted in
10265 * the rbtree, update the space info's counters.
10266 */
10267 trace_btrfs_add_block_group(fs_info, cache, 1);
10268 ret = update_space_info(fs_info, cache->flags, size, bytes_used,
10269 cache->bytes_super, &cache->space_info);
10270 if (ret) {
10271 btrfs_remove_free_space_cache(cache);
10272 spin_lock(&fs_info->block_group_cache_lock);
10273 rb_erase(&cache->cache_node,
10274 &fs_info->block_group_cache_tree);
10275 RB_CLEAR_NODE(&cache->cache_node);
10276 spin_unlock(&fs_info->block_group_cache_lock);
10277 btrfs_put_block_group(cache);
10278 return ret;
10279 }
10280 update_global_block_rsv(fs_info);
10281
10282 __link_block_group(cache->space_info, cache);
10283
10284 list_add_tail(&cache->bg_list, &trans->new_bgs);
10285
10286 set_avail_alloc_bits(fs_info, type);
10287 return 0;
10288 }
10289
10290 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10291 {
10292 u64 extra_flags = chunk_to_extended(flags) &
10293 BTRFS_EXTENDED_PROFILE_MASK;
10294
10295 write_seqlock(&fs_info->profiles_lock);
10296 if (flags & BTRFS_BLOCK_GROUP_DATA)
10297 fs_info->avail_data_alloc_bits &= ~extra_flags;
10298 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10299 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10300 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10301 fs_info->avail_system_alloc_bits &= ~extra_flags;
10302 write_sequnlock(&fs_info->profiles_lock);
10303 }
10304
10305 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10306 struct btrfs_fs_info *fs_info, u64 group_start,
10307 struct extent_map *em)
10308 {
10309 struct btrfs_root *root = fs_info->extent_root;
10310 struct btrfs_path *path;
10311 struct btrfs_block_group_cache *block_group;
10312 struct btrfs_free_cluster *cluster;
10313 struct btrfs_root *tree_root = fs_info->tree_root;
10314 struct btrfs_key key;
10315 struct inode *inode;
10316 struct kobject *kobj = NULL;
10317 int ret;
10318 int index;
10319 int factor;
10320 struct btrfs_caching_control *caching_ctl = NULL;
10321 bool remove_em;
10322
10323 block_group = btrfs_lookup_block_group(fs_info, group_start);
10324 BUG_ON(!block_group);
10325 BUG_ON(!block_group->ro);
10326
10327 /*
10328 * Free the reserved super bytes from this block group before
10329 * remove it.
10330 */
10331 free_excluded_extents(root, block_group);
10332
10333 memcpy(&key, &block_group->key, sizeof(key));
10334 index = get_block_group_index(block_group);
10335 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
10336 BTRFS_BLOCK_GROUP_RAID1 |
10337 BTRFS_BLOCK_GROUP_RAID10))
10338 factor = 2;
10339 else
10340 factor = 1;
10341
10342 /* make sure this block group isn't part of an allocation cluster */
10343 cluster = &fs_info->data_alloc_cluster;
10344 spin_lock(&cluster->refill_lock);
10345 btrfs_return_cluster_to_free_space(block_group, cluster);
10346 spin_unlock(&cluster->refill_lock);
10347
10348 /*
10349 * make sure this block group isn't part of a metadata
10350 * allocation cluster
10351 */
10352 cluster = &fs_info->meta_alloc_cluster;
10353 spin_lock(&cluster->refill_lock);
10354 btrfs_return_cluster_to_free_space(block_group, cluster);
10355 spin_unlock(&cluster->refill_lock);
10356
10357 path = btrfs_alloc_path();
10358 if (!path) {
10359 ret = -ENOMEM;
10360 goto out;
10361 }
10362
10363 /*
10364 * get the inode first so any iput calls done for the io_list
10365 * aren't the final iput (no unlinks allowed now)
10366 */
10367 inode = lookup_free_space_inode(tree_root, block_group, path);
10368
10369 mutex_lock(&trans->transaction->cache_write_mutex);
10370 /*
10371 * make sure our free spache cache IO is done before remove the
10372 * free space inode
10373 */
10374 spin_lock(&trans->transaction->dirty_bgs_lock);
10375 if (!list_empty(&block_group->io_list)) {
10376 list_del_init(&block_group->io_list);
10377
10378 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10379
10380 spin_unlock(&trans->transaction->dirty_bgs_lock);
10381 btrfs_wait_cache_io(trans, block_group, path);
10382 btrfs_put_block_group(block_group);
10383 spin_lock(&trans->transaction->dirty_bgs_lock);
10384 }
10385
10386 if (!list_empty(&block_group->dirty_list)) {
10387 list_del_init(&block_group->dirty_list);
10388 btrfs_put_block_group(block_group);
10389 }
10390 spin_unlock(&trans->transaction->dirty_bgs_lock);
10391 mutex_unlock(&trans->transaction->cache_write_mutex);
10392
10393 if (!IS_ERR(inode)) {
10394 ret = btrfs_orphan_add(trans, inode);
10395 if (ret) {
10396 btrfs_add_delayed_iput(inode);
10397 goto out;
10398 }
10399 clear_nlink(inode);
10400 /* One for the block groups ref */
10401 spin_lock(&block_group->lock);
10402 if (block_group->iref) {
10403 block_group->iref = 0;
10404 block_group->inode = NULL;
10405 spin_unlock(&block_group->lock);
10406 iput(inode);
10407 } else {
10408 spin_unlock(&block_group->lock);
10409 }
10410 /* One for our lookup ref */
10411 btrfs_add_delayed_iput(inode);
10412 }
10413
10414 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10415 key.offset = block_group->key.objectid;
10416 key.type = 0;
10417
10418 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10419 if (ret < 0)
10420 goto out;
10421 if (ret > 0)
10422 btrfs_release_path(path);
10423 if (ret == 0) {
10424 ret = btrfs_del_item(trans, tree_root, path);
10425 if (ret)
10426 goto out;
10427 btrfs_release_path(path);
10428 }
10429
10430 spin_lock(&fs_info->block_group_cache_lock);
10431 rb_erase(&block_group->cache_node,
10432 &fs_info->block_group_cache_tree);
10433 RB_CLEAR_NODE(&block_group->cache_node);
10434
10435 if (fs_info->first_logical_byte == block_group->key.objectid)
10436 fs_info->first_logical_byte = (u64)-1;
10437 spin_unlock(&fs_info->block_group_cache_lock);
10438
10439 down_write(&block_group->space_info->groups_sem);
10440 /*
10441 * we must use list_del_init so people can check to see if they
10442 * are still on the list after taking the semaphore
10443 */
10444 list_del_init(&block_group->list);
10445 if (list_empty(&block_group->space_info->block_groups[index])) {
10446 kobj = block_group->space_info->block_group_kobjs[index];
10447 block_group->space_info->block_group_kobjs[index] = NULL;
10448 clear_avail_alloc_bits(fs_info, block_group->flags);
10449 }
10450 up_write(&block_group->space_info->groups_sem);
10451 if (kobj) {
10452 kobject_del(kobj);
10453 kobject_put(kobj);
10454 }
10455
10456 if (block_group->has_caching_ctl)
10457 caching_ctl = get_caching_control(block_group);
10458 if (block_group->cached == BTRFS_CACHE_STARTED)
10459 wait_block_group_cache_done(block_group);
10460 if (block_group->has_caching_ctl) {
10461 down_write(&fs_info->commit_root_sem);
10462 if (!caching_ctl) {
10463 struct btrfs_caching_control *ctl;
10464
10465 list_for_each_entry(ctl,
10466 &fs_info->caching_block_groups, list)
10467 if (ctl->block_group == block_group) {
10468 caching_ctl = ctl;
10469 atomic_inc(&caching_ctl->count);
10470 break;
10471 }
10472 }
10473 if (caching_ctl)
10474 list_del_init(&caching_ctl->list);
10475 up_write(&fs_info->commit_root_sem);
10476 if (caching_ctl) {
10477 /* Once for the caching bgs list and once for us. */
10478 put_caching_control(caching_ctl);
10479 put_caching_control(caching_ctl);
10480 }
10481 }
10482
10483 spin_lock(&trans->transaction->dirty_bgs_lock);
10484 if (!list_empty(&block_group->dirty_list)) {
10485 WARN_ON(1);
10486 }
10487 if (!list_empty(&block_group->io_list)) {
10488 WARN_ON(1);
10489 }
10490 spin_unlock(&trans->transaction->dirty_bgs_lock);
10491 btrfs_remove_free_space_cache(block_group);
10492
10493 spin_lock(&block_group->space_info->lock);
10494 list_del_init(&block_group->ro_list);
10495
10496 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10497 WARN_ON(block_group->space_info->total_bytes
10498 < block_group->key.offset);
10499 WARN_ON(block_group->space_info->bytes_readonly
10500 < block_group->key.offset);
10501 WARN_ON(block_group->space_info->disk_total
10502 < block_group->key.offset * factor);
10503 }
10504 block_group->space_info->total_bytes -= block_group->key.offset;
10505 block_group->space_info->bytes_readonly -= block_group->key.offset;
10506 block_group->space_info->disk_total -= block_group->key.offset * factor;
10507
10508 spin_unlock(&block_group->space_info->lock);
10509
10510 memcpy(&key, &block_group->key, sizeof(key));
10511
10512 lock_chunks(fs_info);
10513 if (!list_empty(&em->list)) {
10514 /* We're in the transaction->pending_chunks list. */
10515 free_extent_map(em);
10516 }
10517 spin_lock(&block_group->lock);
10518 block_group->removed = 1;
10519 /*
10520 * At this point trimming can't start on this block group, because we
10521 * removed the block group from the tree fs_info->block_group_cache_tree
10522 * so no one can't find it anymore and even if someone already got this
10523 * block group before we removed it from the rbtree, they have already
10524 * incremented block_group->trimming - if they didn't, they won't find
10525 * any free space entries because we already removed them all when we
10526 * called btrfs_remove_free_space_cache().
10527 *
10528 * And we must not remove the extent map from the fs_info->mapping_tree
10529 * to prevent the same logical address range and physical device space
10530 * ranges from being reused for a new block group. This is because our
10531 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10532 * completely transactionless, so while it is trimming a range the
10533 * currently running transaction might finish and a new one start,
10534 * allowing for new block groups to be created that can reuse the same
10535 * physical device locations unless we take this special care.
10536 *
10537 * There may also be an implicit trim operation if the file system
10538 * is mounted with -odiscard. The same protections must remain
10539 * in place until the extents have been discarded completely when
10540 * the transaction commit has completed.
10541 */
10542 remove_em = (atomic_read(&block_group->trimming) == 0);
10543 /*
10544 * Make sure a trimmer task always sees the em in the pinned_chunks list
10545 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10546 * before checking block_group->removed).
10547 */
10548 if (!remove_em) {
10549 /*
10550 * Our em might be in trans->transaction->pending_chunks which
10551 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10552 * and so is the fs_info->pinned_chunks list.
10553 *
10554 * So at this point we must be holding the chunk_mutex to avoid
10555 * any races with chunk allocation (more specifically at
10556 * volumes.c:contains_pending_extent()), to ensure it always
10557 * sees the em, either in the pending_chunks list or in the
10558 * pinned_chunks list.
10559 */
10560 list_move_tail(&em->list, &fs_info->pinned_chunks);
10561 }
10562 spin_unlock(&block_group->lock);
10563
10564 if (remove_em) {
10565 struct extent_map_tree *em_tree;
10566
10567 em_tree = &fs_info->mapping_tree.map_tree;
10568 write_lock(&em_tree->lock);
10569 /*
10570 * The em might be in the pending_chunks list, so make sure the
10571 * chunk mutex is locked, since remove_extent_mapping() will
10572 * delete us from that list.
10573 */
10574 remove_extent_mapping(em_tree, em);
10575 write_unlock(&em_tree->lock);
10576 /* once for the tree */
10577 free_extent_map(em);
10578 }
10579
10580 unlock_chunks(fs_info);
10581
10582 ret = remove_block_group_free_space(trans, fs_info, block_group);
10583 if (ret)
10584 goto out;
10585
10586 btrfs_put_block_group(block_group);
10587 btrfs_put_block_group(block_group);
10588
10589 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10590 if (ret > 0)
10591 ret = -EIO;
10592 if (ret < 0)
10593 goto out;
10594
10595 ret = btrfs_del_item(trans, root, path);
10596 out:
10597 btrfs_free_path(path);
10598 return ret;
10599 }
10600
10601 struct btrfs_trans_handle *
10602 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10603 const u64 chunk_offset)
10604 {
10605 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10606 struct extent_map *em;
10607 struct map_lookup *map;
10608 unsigned int num_items;
10609
10610 read_lock(&em_tree->lock);
10611 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10612 read_unlock(&em_tree->lock);
10613 ASSERT(em && em->start == chunk_offset);
10614
10615 /*
10616 * We need to reserve 3 + N units from the metadata space info in order
10617 * to remove a block group (done at btrfs_remove_chunk() and at
10618 * btrfs_remove_block_group()), which are used for:
10619 *
10620 * 1 unit for adding the free space inode's orphan (located in the tree
10621 * of tree roots).
10622 * 1 unit for deleting the block group item (located in the extent
10623 * tree).
10624 * 1 unit for deleting the free space item (located in tree of tree
10625 * roots).
10626 * N units for deleting N device extent items corresponding to each
10627 * stripe (located in the device tree).
10628 *
10629 * In order to remove a block group we also need to reserve units in the
10630 * system space info in order to update the chunk tree (update one or
10631 * more device items and remove one chunk item), but this is done at
10632 * btrfs_remove_chunk() through a call to check_system_chunk().
10633 */
10634 map = em->map_lookup;
10635 num_items = 3 + map->num_stripes;
10636 free_extent_map(em);
10637
10638 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10639 num_items, 1);
10640 }
10641
10642 /*
10643 * Process the unused_bgs list and remove any that don't have any allocated
10644 * space inside of them.
10645 */
10646 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10647 {
10648 struct btrfs_block_group_cache *block_group;
10649 struct btrfs_space_info *space_info;
10650 struct btrfs_root *root = fs_info->extent_root;
10651 struct btrfs_trans_handle *trans;
10652 int ret = 0;
10653
10654 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10655 return;
10656
10657 spin_lock(&fs_info->unused_bgs_lock);
10658 while (!list_empty(&fs_info->unused_bgs)) {
10659 u64 start, end;
10660 int trimming;
10661
10662 block_group = list_first_entry(&fs_info->unused_bgs,
10663 struct btrfs_block_group_cache,
10664 bg_list);
10665 list_del_init(&block_group->bg_list);
10666
10667 space_info = block_group->space_info;
10668
10669 if (ret || btrfs_mixed_space_info(space_info)) {
10670 btrfs_put_block_group(block_group);
10671 continue;
10672 }
10673 spin_unlock(&fs_info->unused_bgs_lock);
10674
10675 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10676
10677 /* Don't want to race with allocators so take the groups_sem */
10678 down_write(&space_info->groups_sem);
10679 spin_lock(&block_group->lock);
10680 if (block_group->reserved ||
10681 btrfs_block_group_used(&block_group->item) ||
10682 block_group->ro ||
10683 list_is_singular(&block_group->list)) {
10684 /*
10685 * We want to bail if we made new allocations or have
10686 * outstanding allocations in this block group. We do
10687 * the ro check in case balance is currently acting on
10688 * this block group.
10689 */
10690 spin_unlock(&block_group->lock);
10691 up_write(&space_info->groups_sem);
10692 goto next;
10693 }
10694 spin_unlock(&block_group->lock);
10695
10696 /* We don't want to force the issue, only flip if it's ok. */
10697 ret = inc_block_group_ro(block_group, 0);
10698 up_write(&space_info->groups_sem);
10699 if (ret < 0) {
10700 ret = 0;
10701 goto next;
10702 }
10703
10704 /*
10705 * Want to do this before we do anything else so we can recover
10706 * properly if we fail to join the transaction.
10707 */
10708 trans = btrfs_start_trans_remove_block_group(fs_info,
10709 block_group->key.objectid);
10710 if (IS_ERR(trans)) {
10711 btrfs_dec_block_group_ro(root, block_group);
10712 ret = PTR_ERR(trans);
10713 goto next;
10714 }
10715
10716 /*
10717 * We could have pending pinned extents for this block group,
10718 * just delete them, we don't care about them anymore.
10719 */
10720 start = block_group->key.objectid;
10721 end = start + block_group->key.offset - 1;
10722 /*
10723 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10724 * btrfs_finish_extent_commit(). If we are at transaction N,
10725 * another task might be running finish_extent_commit() for the
10726 * previous transaction N - 1, and have seen a range belonging
10727 * to the block group in freed_extents[] before we were able to
10728 * clear the whole block group range from freed_extents[]. This
10729 * means that task can lookup for the block group after we
10730 * unpinned it from freed_extents[] and removed it, leading to
10731 * a BUG_ON() at btrfs_unpin_extent_range().
10732 */
10733 mutex_lock(&fs_info->unused_bg_unpin_mutex);
10734 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
10735 EXTENT_DIRTY);
10736 if (ret) {
10737 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10738 btrfs_dec_block_group_ro(root, block_group);
10739 goto end_trans;
10740 }
10741 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
10742 EXTENT_DIRTY);
10743 if (ret) {
10744 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10745 btrfs_dec_block_group_ro(root, block_group);
10746 goto end_trans;
10747 }
10748 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10749
10750 /* Reset pinned so btrfs_put_block_group doesn't complain */
10751 spin_lock(&space_info->lock);
10752 spin_lock(&block_group->lock);
10753
10754 space_info->bytes_pinned -= block_group->pinned;
10755 space_info->bytes_readonly += block_group->pinned;
10756 percpu_counter_add(&space_info->total_bytes_pinned,
10757 -block_group->pinned);
10758 block_group->pinned = 0;
10759
10760 spin_unlock(&block_group->lock);
10761 spin_unlock(&space_info->lock);
10762
10763 /* DISCARD can flip during remount */
10764 trimming = btrfs_test_opt(fs_info, DISCARD);
10765
10766 /* Implicit trim during transaction commit. */
10767 if (trimming)
10768 btrfs_get_block_group_trimming(block_group);
10769
10770 /*
10771 * Btrfs_remove_chunk will abort the transaction if things go
10772 * horribly wrong.
10773 */
10774 ret = btrfs_remove_chunk(trans, fs_info,
10775 block_group->key.objectid);
10776
10777 if (ret) {
10778 if (trimming)
10779 btrfs_put_block_group_trimming(block_group);
10780 goto end_trans;
10781 }
10782
10783 /*
10784 * If we're not mounted with -odiscard, we can just forget
10785 * about this block group. Otherwise we'll need to wait
10786 * until transaction commit to do the actual discard.
10787 */
10788 if (trimming) {
10789 spin_lock(&fs_info->unused_bgs_lock);
10790 /*
10791 * A concurrent scrub might have added us to the list
10792 * fs_info->unused_bgs, so use a list_move operation
10793 * to add the block group to the deleted_bgs list.
10794 */
10795 list_move(&block_group->bg_list,
10796 &trans->transaction->deleted_bgs);
10797 spin_unlock(&fs_info->unused_bgs_lock);
10798 btrfs_get_block_group(block_group);
10799 }
10800 end_trans:
10801 btrfs_end_transaction(trans, root);
10802 next:
10803 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10804 btrfs_put_block_group(block_group);
10805 spin_lock(&fs_info->unused_bgs_lock);
10806 }
10807 spin_unlock(&fs_info->unused_bgs_lock);
10808 }
10809
10810 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10811 {
10812 struct btrfs_space_info *space_info;
10813 struct btrfs_super_block *disk_super;
10814 u64 features;
10815 u64 flags;
10816 int mixed = 0;
10817 int ret;
10818
10819 disk_super = fs_info->super_copy;
10820 if (!btrfs_super_root(disk_super))
10821 return -EINVAL;
10822
10823 features = btrfs_super_incompat_flags(disk_super);
10824 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10825 mixed = 1;
10826
10827 flags = BTRFS_BLOCK_GROUP_SYSTEM;
10828 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10829 if (ret)
10830 goto out;
10831
10832 if (mixed) {
10833 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10834 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10835 } else {
10836 flags = BTRFS_BLOCK_GROUP_METADATA;
10837 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10838 if (ret)
10839 goto out;
10840
10841 flags = BTRFS_BLOCK_GROUP_DATA;
10842 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10843 }
10844 out:
10845 return ret;
10846 }
10847
10848 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
10849 {
10850 return unpin_extent_range(root, start, end, false);
10851 }
10852
10853 /*
10854 * It used to be that old block groups would be left around forever.
10855 * Iterating over them would be enough to trim unused space. Since we
10856 * now automatically remove them, we also need to iterate over unallocated
10857 * space.
10858 *
10859 * We don't want a transaction for this since the discard may take a
10860 * substantial amount of time. We don't require that a transaction be
10861 * running, but we do need to take a running transaction into account
10862 * to ensure that we're not discarding chunks that were released in
10863 * the current transaction.
10864 *
10865 * Holding the chunks lock will prevent other threads from allocating
10866 * or releasing chunks, but it won't prevent a running transaction
10867 * from committing and releasing the memory that the pending chunks
10868 * list head uses. For that, we need to take a reference to the
10869 * transaction.
10870 */
10871 static int btrfs_trim_free_extents(struct btrfs_device *device,
10872 u64 minlen, u64 *trimmed)
10873 {
10874 u64 start = 0, len = 0;
10875 int ret;
10876
10877 *trimmed = 0;
10878
10879 /* Not writeable = nothing to do. */
10880 if (!device->writeable)
10881 return 0;
10882
10883 /* No free space = nothing to do. */
10884 if (device->total_bytes <= device->bytes_used)
10885 return 0;
10886
10887 ret = 0;
10888
10889 while (1) {
10890 struct btrfs_fs_info *fs_info = device->fs_info;
10891 struct btrfs_transaction *trans;
10892 u64 bytes;
10893
10894 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10895 if (ret)
10896 return ret;
10897
10898 down_read(&fs_info->commit_root_sem);
10899
10900 spin_lock(&fs_info->trans_lock);
10901 trans = fs_info->running_transaction;
10902 if (trans)
10903 atomic_inc(&trans->use_count);
10904 spin_unlock(&fs_info->trans_lock);
10905
10906 ret = find_free_dev_extent_start(trans, device, minlen, start,
10907 &start, &len);
10908 if (trans)
10909 btrfs_put_transaction(trans);
10910
10911 if (ret) {
10912 up_read(&fs_info->commit_root_sem);
10913 mutex_unlock(&fs_info->chunk_mutex);
10914 if (ret == -ENOSPC)
10915 ret = 0;
10916 break;
10917 }
10918
10919 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10920 up_read(&fs_info->commit_root_sem);
10921 mutex_unlock(&fs_info->chunk_mutex);
10922
10923 if (ret)
10924 break;
10925
10926 start += len;
10927 *trimmed += bytes;
10928
10929 if (fatal_signal_pending(current)) {
10930 ret = -ERESTARTSYS;
10931 break;
10932 }
10933
10934 cond_resched();
10935 }
10936
10937 return ret;
10938 }
10939
10940 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
10941 {
10942 struct btrfs_fs_info *fs_info = root->fs_info;
10943 struct btrfs_block_group_cache *cache = NULL;
10944 struct btrfs_device *device;
10945 struct list_head *devices;
10946 u64 group_trimmed;
10947 u64 start;
10948 u64 end;
10949 u64 trimmed = 0;
10950 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
10951 int ret = 0;
10952
10953 /*
10954 * try to trim all FS space, our block group may start from non-zero.
10955 */
10956 if (range->len == total_bytes)
10957 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10958 else
10959 cache = btrfs_lookup_block_group(fs_info, range->start);
10960
10961 while (cache) {
10962 if (cache->key.objectid >= (range->start + range->len)) {
10963 btrfs_put_block_group(cache);
10964 break;
10965 }
10966
10967 start = max(range->start, cache->key.objectid);
10968 end = min(range->start + range->len,
10969 cache->key.objectid + cache->key.offset);
10970
10971 if (end - start >= range->minlen) {
10972 if (!block_group_cache_done(cache)) {
10973 ret = cache_block_group(cache, 0);
10974 if (ret) {
10975 btrfs_put_block_group(cache);
10976 break;
10977 }
10978 ret = wait_block_group_cache_done(cache);
10979 if (ret) {
10980 btrfs_put_block_group(cache);
10981 break;
10982 }
10983 }
10984 ret = btrfs_trim_block_group(cache,
10985 &group_trimmed,
10986 start,
10987 end,
10988 range->minlen);
10989
10990 trimmed += group_trimmed;
10991 if (ret) {
10992 btrfs_put_block_group(cache);
10993 break;
10994 }
10995 }
10996
10997 cache = next_block_group(fs_info->tree_root, cache);
10998 }
10999
11000 mutex_lock(&fs_info->fs_devices->device_list_mutex);
11001 devices = &fs_info->fs_devices->alloc_list;
11002 list_for_each_entry(device, devices, dev_alloc_list) {
11003 ret = btrfs_trim_free_extents(device, range->minlen,
11004 &group_trimmed);
11005 if (ret)
11006 break;
11007
11008 trimmed += group_trimmed;
11009 }
11010 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
11011
11012 range->len = trimmed;
11013 return ret;
11014 }
11015
11016 /*
11017 * btrfs_{start,end}_write_no_snapshoting() are similar to
11018 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
11019 * data into the page cache through nocow before the subvolume is snapshoted,
11020 * but flush the data into disk after the snapshot creation, or to prevent
11021 * operations while snapshoting is ongoing and that cause the snapshot to be
11022 * inconsistent (writes followed by expanding truncates for example).
11023 */
11024 void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
11025 {
11026 percpu_counter_dec(&root->subv_writers->counter);
11027 /*
11028 * Make sure counter is updated before we wake up waiters.
11029 */
11030 smp_mb();
11031 if (waitqueue_active(&root->subv_writers->wait))
11032 wake_up(&root->subv_writers->wait);
11033 }
11034
11035 int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
11036 {
11037 if (atomic_read(&root->will_be_snapshoted))
11038 return 0;
11039
11040 percpu_counter_inc(&root->subv_writers->counter);
11041 /*
11042 * Make sure counter is updated before we check for snapshot creation.
11043 */
11044 smp_mb();
11045 if (atomic_read(&root->will_be_snapshoted)) {
11046 btrfs_end_write_no_snapshoting(root);
11047 return 0;
11048 }
11049 return 1;
11050 }
11051
11052 static int wait_snapshoting_atomic_t(atomic_t *a)
11053 {
11054 schedule();
11055 return 0;
11056 }
11057
11058 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11059 {
11060 while (true) {
11061 int ret;
11062
11063 ret = btrfs_start_write_no_snapshoting(root);
11064 if (ret)
11065 break;
11066 wait_on_atomic_t(&root->will_be_snapshoted,
11067 wait_snapshoting_atomic_t,
11068 TASK_UNINTERRUPTIBLE);
11069 }
11070 }