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