Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
4 */
5
6#include <linux/fs.h>
7#include <linux/blkdev.h>
8#include <linux/radix-tree.h>
9#include <linux/writeback.h>
10#include <linux/workqueue.h>
11#include <linux/kthread.h>
12#include <linux/slab.h>
13#include <linux/migrate.h>
14#include <linux/ratelimit.h>
15#include <linux/uuid.h>
16#include <linux/semaphore.h>
17#include <linux/error-injection.h>
18#include <linux/crc32c.h>
19#include <linux/sched/mm.h>
20#include <linux/unaligned.h>
21#include <crypto/hash.h>
22#include "ctree.h"
23#include "disk-io.h"
24#include "transaction.h"
25#include "btrfs_inode.h"
26#include "bio.h"
27#include "print-tree.h"
28#include "locking.h"
29#include "tree-log.h"
30#include "free-space-cache.h"
31#include "free-space-tree.h"
32#include "dev-replace.h"
33#include "raid56.h"
34#include "sysfs.h"
35#include "qgroup.h"
36#include "compression.h"
37#include "tree-checker.h"
38#include "ref-verify.h"
39#include "block-group.h"
40#include "discard.h"
41#include "space-info.h"
42#include "zoned.h"
43#include "subpage.h"
44#include "fs.h"
45#include "accessors.h"
46#include "extent-tree.h"
47#include "root-tree.h"
48#include "defrag.h"
49#include "uuid-tree.h"
50#include "relocation.h"
51#include "scrub.h"
52#include "super.h"
53#include "delayed-inode.h"
54
55#define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
56 BTRFS_HEADER_FLAG_RELOC |\
57 BTRFS_SUPER_FLAG_ERROR |\
58 BTRFS_SUPER_FLAG_SEEDING |\
59 BTRFS_SUPER_FLAG_METADUMP |\
60 BTRFS_SUPER_FLAG_METADUMP_V2)
61
62static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
63static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
64
65static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
66{
67 if (fs_info->csum_shash)
68 crypto_free_shash(fs_info->csum_shash);
69}
70
71/*
72 * Compute the csum of a btree block and store the result to provided buffer.
73 */
74static void csum_tree_block(struct extent_buffer *buf, u8 *result)
75{
76 struct btrfs_fs_info *fs_info = buf->fs_info;
77 int num_pages;
78 u32 first_page_part;
79 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
80 char *kaddr;
81 int i;
82
83 shash->tfm = fs_info->csum_shash;
84 crypto_shash_init(shash);
85
86 if (buf->addr) {
87 /* Pages are contiguous, handle them as a big one. */
88 kaddr = buf->addr;
89 first_page_part = fs_info->nodesize;
90 num_pages = 1;
91 } else {
92 kaddr = folio_address(buf->folios[0]);
93 first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
94 num_pages = num_extent_pages(buf);
95 }
96
97 crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
98 first_page_part - BTRFS_CSUM_SIZE);
99
100 /*
101 * Multiple single-page folios case would reach here.
102 *
103 * nodesize <= PAGE_SIZE and large folio all handled by above
104 * crypto_shash_update() already.
105 */
106 for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
107 kaddr = folio_address(buf->folios[i]);
108 crypto_shash_update(shash, kaddr, PAGE_SIZE);
109 }
110 memset(result, 0, BTRFS_CSUM_SIZE);
111 crypto_shash_final(shash, result);
112}
113
114/*
115 * we can't consider a given block up to date unless the transid of the
116 * block matches the transid in the parent node's pointer. This is how we
117 * detect blocks that either didn't get written at all or got written
118 * in the wrong place.
119 */
120int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid, bool atomic)
121{
122 if (!extent_buffer_uptodate(eb))
123 return 0;
124
125 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
126 return 1;
127
128 if (atomic)
129 return -EAGAIN;
130
131 if (!extent_buffer_uptodate(eb) ||
132 btrfs_header_generation(eb) != parent_transid) {
133 btrfs_err_rl(eb->fs_info,
134"parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
135 eb->start, eb->read_mirror,
136 parent_transid, btrfs_header_generation(eb));
137 clear_extent_buffer_uptodate(eb);
138 return 0;
139 }
140 return 1;
141}
142
143static bool btrfs_supported_super_csum(u16 csum_type)
144{
145 switch (csum_type) {
146 case BTRFS_CSUM_TYPE_CRC32:
147 case BTRFS_CSUM_TYPE_XXHASH:
148 case BTRFS_CSUM_TYPE_SHA256:
149 case BTRFS_CSUM_TYPE_BLAKE2:
150 return true;
151 default:
152 return false;
153 }
154}
155
156/*
157 * Return 0 if the superblock checksum type matches the checksum value of that
158 * algorithm. Pass the raw disk superblock data.
159 */
160int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
161 const struct btrfs_super_block *disk_sb)
162{
163 char result[BTRFS_CSUM_SIZE];
164 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
165
166 shash->tfm = fs_info->csum_shash;
167
168 /*
169 * The super_block structure does not span the whole
170 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
171 * filled with zeros and is included in the checksum.
172 */
173 crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
174 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
175
176 if (memcmp(disk_sb->csum, result, fs_info->csum_size))
177 return 1;
178
179 return 0;
180}
181
182static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
183 int mirror_num)
184{
185 struct btrfs_fs_info *fs_info = eb->fs_info;
186 const u32 step = min(fs_info->nodesize, PAGE_SIZE);
187 const u32 nr_steps = eb->len / step;
188 phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
189 int ret = 0;
190
191 if (sb_rdonly(fs_info->sb))
192 return -EROFS;
193
194 for (int i = 0; i < num_extent_pages(eb); i++) {
195 struct folio *folio = eb->folios[i];
196
197 /* No large folio support yet. */
198 ASSERT(folio_order(folio) == 0);
199 ASSERT(i < nr_steps);
200
201 /*
202 * For nodesize < page size, there is just one paddr, with some
203 * offset inside the page.
204 *
205 * For nodesize >= page size, it's one or more paddrs, and eb->start
206 * must be aligned to page boundary.
207 */
208 paddrs[i] = page_to_phys(&folio->page) + offset_in_page(eb->start);
209 }
210
211 ret = btrfs_repair_io_failure(fs_info, 0, eb->start, eb->len, eb->start,
212 paddrs, step, mirror_num);
213 return ret;
214}
215
216/*
217 * helper to read a given tree block, doing retries as required when
218 * the checksums don't match and we have alternate mirrors to try.
219 *
220 * @check: expected tree parentness check, see the comments of the
221 * structure for details.
222 */
223int btrfs_read_extent_buffer(struct extent_buffer *eb,
224 const struct btrfs_tree_parent_check *check)
225{
226 struct btrfs_fs_info *fs_info = eb->fs_info;
227 int failed = 0;
228 int ret;
229 int num_copies = 0;
230 int mirror_num = 0;
231 int failed_mirror = 0;
232
233 ASSERT(check);
234
235 while (1) {
236 ret = read_extent_buffer_pages(eb, mirror_num, check);
237 if (!ret)
238 break;
239
240 num_copies = btrfs_num_copies(fs_info,
241 eb->start, eb->len);
242 if (num_copies == 1)
243 break;
244
245 if (!failed_mirror) {
246 failed = 1;
247 failed_mirror = eb->read_mirror;
248 }
249
250 mirror_num++;
251 if (mirror_num == failed_mirror)
252 mirror_num++;
253
254 if (mirror_num > num_copies)
255 break;
256 }
257
258 if (failed && !ret && failed_mirror)
259 btrfs_repair_eb_io_failure(eb, failed_mirror);
260
261 return ret;
262}
263
264/*
265 * Checksum a dirty tree block before IO.
266 */
267int btree_csum_one_bio(struct btrfs_bio *bbio)
268{
269 struct extent_buffer *eb = bbio->private;
270 struct btrfs_fs_info *fs_info = eb->fs_info;
271 u64 found_start = btrfs_header_bytenr(eb);
272 u64 last_trans;
273 u8 result[BTRFS_CSUM_SIZE];
274 int ret;
275
276 /* Btree blocks are always contiguous on disk. */
277 if (WARN_ON_ONCE(bbio->file_offset != eb->start))
278 return -EIO;
279 if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
280 return -EIO;
281
282 /*
283 * If an extent_buffer is marked as EXTENT_BUFFER_ZONED_ZEROOUT, don't
284 * checksum it but zero-out its content. This is done to preserve
285 * ordering of I/O without unnecessarily writing out data.
286 */
287 if (test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags)) {
288 memzero_extent_buffer(eb, 0, eb->len);
289 return 0;
290 }
291
292 if (WARN_ON_ONCE(found_start != eb->start))
293 return -EIO;
294 if (WARN_ON(!btrfs_meta_folio_test_uptodate(eb->folios[0], eb)))
295 return -EIO;
296
297 ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
298 offsetof(struct btrfs_header, fsid),
299 BTRFS_FSID_SIZE) == 0);
300 csum_tree_block(eb, result);
301
302 if (btrfs_header_level(eb))
303 ret = btrfs_check_node(eb);
304 else
305 ret = btrfs_check_leaf(eb);
306
307 if (ret < 0)
308 goto error;
309
310 /*
311 * Also check the generation, the eb reached here must be newer than
312 * last committed. Or something seriously wrong happened.
313 */
314 last_trans = btrfs_get_last_trans_committed(fs_info);
315 if (unlikely(btrfs_header_generation(eb) <= last_trans)) {
316 ret = -EUCLEAN;
317 btrfs_err(fs_info,
318 "block=%llu bad generation, have %llu expect > %llu",
319 eb->start, btrfs_header_generation(eb), last_trans);
320 goto error;
321 }
322 write_extent_buffer(eb, result, 0, fs_info->csum_size);
323 return 0;
324
325error:
326 btrfs_print_tree(eb, 0);
327 btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
328 eb->start);
329 /*
330 * Be noisy if this is an extent buffer from a log tree. We don't abort
331 * a transaction in case there's a bad log tree extent buffer, we just
332 * fallback to a transaction commit. Still we want to know when there is
333 * a bad log tree extent buffer, as that may signal a bug somewhere.
334 */
335 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
336 btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
337 return ret;
338}
339
340static bool check_tree_block_fsid(struct extent_buffer *eb)
341{
342 struct btrfs_fs_info *fs_info = eb->fs_info;
343 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
344 u8 fsid[BTRFS_FSID_SIZE];
345
346 read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
347 BTRFS_FSID_SIZE);
348
349 /*
350 * alloc_fsid_devices() copies the fsid into fs_devices::metadata_uuid.
351 * This is then overwritten by metadata_uuid if it is present in the
352 * device_list_add(). The same true for a seed device as well. So use of
353 * fs_devices::metadata_uuid is appropriate here.
354 */
355 if (memcmp(fsid, fs_info->fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0)
356 return false;
357
358 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
359 if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
360 return false;
361
362 return true;
363}
364
365/* Do basic extent buffer checks at read time */
366int btrfs_validate_extent_buffer(struct extent_buffer *eb,
367 const struct btrfs_tree_parent_check *check)
368{
369 struct btrfs_fs_info *fs_info = eb->fs_info;
370 u64 found_start;
371 const u32 csum_size = fs_info->csum_size;
372 u8 found_level;
373 u8 result[BTRFS_CSUM_SIZE];
374 const u8 *header_csum;
375 int ret = 0;
376 const bool ignore_csum = btrfs_test_opt(fs_info, IGNOREMETACSUMS);
377
378 ASSERT(check);
379
380 found_start = btrfs_header_bytenr(eb);
381 if (unlikely(found_start != eb->start)) {
382 btrfs_err_rl(fs_info,
383 "bad tree block start, mirror %u want %llu have %llu",
384 eb->read_mirror, eb->start, found_start);
385 ret = -EIO;
386 goto out;
387 }
388 if (unlikely(check_tree_block_fsid(eb))) {
389 btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
390 eb->start, eb->read_mirror);
391 ret = -EIO;
392 goto out;
393 }
394 found_level = btrfs_header_level(eb);
395 if (unlikely(found_level >= BTRFS_MAX_LEVEL)) {
396 btrfs_err(fs_info,
397 "bad tree block level, mirror %u level %d on logical %llu",
398 eb->read_mirror, btrfs_header_level(eb), eb->start);
399 ret = -EIO;
400 goto out;
401 }
402
403 csum_tree_block(eb, result);
404 header_csum = folio_address(eb->folios[0]) +
405 get_eb_offset_in_folio(eb, offsetof(struct btrfs_header, csum));
406
407 if (memcmp(result, header_csum, csum_size) != 0) {
408 btrfs_warn_rl(fs_info,
409"checksum verify failed on logical %llu mirror %u wanted " BTRFS_CSUM_FMT " found " BTRFS_CSUM_FMT " level %d%s",
410 eb->start, eb->read_mirror,
411 BTRFS_CSUM_FMT_VALUE(csum_size, header_csum),
412 BTRFS_CSUM_FMT_VALUE(csum_size, result),
413 btrfs_header_level(eb),
414 ignore_csum ? ", ignored" : "");
415 if (unlikely(!ignore_csum)) {
416 ret = -EUCLEAN;
417 goto out;
418 }
419 }
420
421 if (unlikely(found_level != check->level)) {
422 btrfs_err(fs_info,
423 "level verify failed on logical %llu mirror %u wanted %u found %u",
424 eb->start, eb->read_mirror, check->level, found_level);
425 ret = -EIO;
426 goto out;
427 }
428 if (unlikely(check->transid &&
429 btrfs_header_generation(eb) != check->transid)) {
430 btrfs_err_rl(eb->fs_info,
431"parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
432 eb->start, eb->read_mirror, check->transid,
433 btrfs_header_generation(eb));
434 ret = -EIO;
435 goto out;
436 }
437 if (check->has_first_key) {
438 const struct btrfs_key *expect_key = &check->first_key;
439 struct btrfs_key found_key;
440
441 if (found_level)
442 btrfs_node_key_to_cpu(eb, &found_key, 0);
443 else
444 btrfs_item_key_to_cpu(eb, &found_key, 0);
445 if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
446 btrfs_err(fs_info,
447"tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
448 eb->start, check->transid,
449 expect_key->objectid,
450 expect_key->type, expect_key->offset,
451 found_key.objectid, found_key.type,
452 found_key.offset);
453 ret = -EUCLEAN;
454 goto out;
455 }
456 }
457 if (check->owner_root) {
458 ret = btrfs_check_eb_owner(eb, check->owner_root);
459 if (ret < 0)
460 goto out;
461 }
462
463 /* If this is a leaf block and it is corrupt, just return -EIO. */
464 if (found_level == 0 && btrfs_check_leaf(eb))
465 ret = -EIO;
466
467 if (found_level > 0 && btrfs_check_node(eb))
468 ret = -EIO;
469
470 if (ret)
471 btrfs_err(fs_info,
472 "read time tree block corruption detected on logical %llu mirror %u",
473 eb->start, eb->read_mirror);
474out:
475 return ret;
476}
477
478#ifdef CONFIG_MIGRATION
479static int btree_migrate_folio(struct address_space *mapping,
480 struct folio *dst, struct folio *src, enum migrate_mode mode)
481{
482 /*
483 * we can't safely write a btree page from here,
484 * we haven't done the locking hook
485 */
486 if (folio_test_dirty(src))
487 return -EAGAIN;
488 /*
489 * Buffers may be managed in a filesystem specific way.
490 * We must have no buffers or drop them.
491 */
492 if (folio_get_private(src) &&
493 !filemap_release_folio(src, GFP_KERNEL))
494 return -EAGAIN;
495 return migrate_folio(mapping, dst, src, mode);
496}
497#else
498#define btree_migrate_folio NULL
499#endif
500
501static int btree_writepages(struct address_space *mapping,
502 struct writeback_control *wbc)
503{
504 int ret;
505
506 if (wbc->sync_mode == WB_SYNC_NONE) {
507 struct btrfs_fs_info *fs_info;
508
509 if (wbc->for_kupdate)
510 return 0;
511
512 fs_info = inode_to_fs_info(mapping->host);
513 /* this is a bit racy, but that's ok */
514 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
515 BTRFS_DIRTY_METADATA_THRESH,
516 fs_info->dirty_metadata_batch);
517 if (ret < 0)
518 return 0;
519 }
520 return btree_write_cache_pages(mapping, wbc);
521}
522
523static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
524{
525 if (folio_test_writeback(folio) || folio_test_dirty(folio))
526 return false;
527
528 return try_release_extent_buffer(folio);
529}
530
531static void btree_invalidate_folio(struct folio *folio, size_t offset,
532 size_t length)
533{
534 struct extent_io_tree *tree;
535
536 tree = &folio_to_inode(folio)->io_tree;
537 extent_invalidate_folio(tree, folio, offset);
538 btree_release_folio(folio, GFP_NOFS);
539 if (folio_get_private(folio)) {
540 btrfs_warn(folio_to_fs_info(folio),
541 "folio private not zero on folio %llu",
542 (unsigned long long)folio_pos(folio));
543 folio_detach_private(folio);
544 }
545}
546
547#ifdef DEBUG
548static bool btree_dirty_folio(struct address_space *mapping,
549 struct folio *folio)
550{
551 struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
552 struct btrfs_subpage_info *spi = fs_info->subpage_info;
553 struct btrfs_subpage *subpage;
554 struct extent_buffer *eb;
555 int cur_bit = 0;
556 u64 page_start = folio_pos(folio);
557
558 if (fs_info->sectorsize == PAGE_SIZE) {
559 eb = folio_get_private(folio);
560 BUG_ON(!eb);
561 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
562 BUG_ON(!atomic_read(&eb->refs));
563 btrfs_assert_tree_write_locked(eb);
564 return filemap_dirty_folio(mapping, folio);
565 }
566
567 ASSERT(spi);
568 subpage = folio_get_private(folio);
569
570 for (cur_bit = spi->dirty_offset;
571 cur_bit < spi->dirty_offset + spi->bitmap_nr_bits;
572 cur_bit++) {
573 unsigned long flags;
574 u64 cur;
575
576 spin_lock_irqsave(&subpage->lock, flags);
577 if (!test_bit(cur_bit, subpage->bitmaps)) {
578 spin_unlock_irqrestore(&subpage->lock, flags);
579 continue;
580 }
581 spin_unlock_irqrestore(&subpage->lock, flags);
582 cur = page_start + cur_bit * fs_info->sectorsize;
583
584 eb = find_extent_buffer(fs_info, cur);
585 ASSERT(eb);
586 ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
587 ASSERT(atomic_read(&eb->refs));
588 btrfs_assert_tree_write_locked(eb);
589 free_extent_buffer(eb);
590
591 cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits) - 1;
592 }
593 return filemap_dirty_folio(mapping, folio);
594}
595#else
596#define btree_dirty_folio filemap_dirty_folio
597#endif
598
599static const struct address_space_operations btree_aops = {
600 .writepages = btree_writepages,
601 .release_folio = btree_release_folio,
602 .invalidate_folio = btree_invalidate_folio,
603 .migrate_folio = btree_migrate_folio,
604 .dirty_folio = btree_dirty_folio,
605};
606
607struct extent_buffer *btrfs_find_create_tree_block(
608 struct btrfs_fs_info *fs_info,
609 u64 bytenr, u64 owner_root,
610 int level)
611{
612 if (btrfs_is_testing(fs_info))
613 return alloc_test_extent_buffer(fs_info, bytenr);
614 return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
615}
616
617/*
618 * Read tree block at logical address @bytenr and do variant basic but critical
619 * verification.
620 *
621 * @check: expected tree parentness check, see comments of the
622 * structure for details.
623 */
624struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
625 struct btrfs_tree_parent_check *check)
626{
627 struct extent_buffer *buf = NULL;
628 int ret;
629
630 ASSERT(check);
631
632 buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
633 check->level);
634 if (IS_ERR(buf))
635 return buf;
636
637 ret = btrfs_read_extent_buffer(buf, check);
638 if (ret) {
639 free_extent_buffer_stale(buf);
640 return ERR_PTR(ret);
641 }
642 return buf;
643
644}
645
646static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
647 u64 objectid, gfp_t flags)
648{
649 struct btrfs_root *root;
650
651 root = kzalloc(sizeof(*root), flags);
652 if (!root)
653 return NULL;
654
655 root->fs_info = fs_info;
656 root->root_key.objectid = objectid;
657 RB_CLEAR_NODE(&root->rb_node);
658
659 xa_init(&root->inodes);
660 xa_init(&root->delayed_nodes);
661
662 btrfs_init_root_block_rsv(root);
663
664 INIT_LIST_HEAD(&root->dirty_list);
665 INIT_LIST_HEAD(&root->root_list);
666 INIT_LIST_HEAD(&root->delalloc_inodes);
667 INIT_LIST_HEAD(&root->delalloc_root);
668 INIT_LIST_HEAD(&root->ordered_extents);
669 INIT_LIST_HEAD(&root->ordered_root);
670 INIT_LIST_HEAD(&root->reloc_dirty_list);
671 spin_lock_init(&root->delalloc_lock);
672 spin_lock_init(&root->ordered_extent_lock);
673 spin_lock_init(&root->accounting_lock);
674 spin_lock_init(&root->qgroup_meta_rsv_lock);
675 mutex_init(&root->objectid_mutex);
676 mutex_init(&root->log_mutex);
677 mutex_init(&root->ordered_extent_mutex);
678 mutex_init(&root->delalloc_mutex);
679 init_waitqueue_head(&root->qgroup_flush_wait);
680 init_waitqueue_head(&root->log_writer_wait);
681 init_waitqueue_head(&root->log_commit_wait[0]);
682 init_waitqueue_head(&root->log_commit_wait[1]);
683 INIT_LIST_HEAD(&root->log_ctxs[0]);
684 INIT_LIST_HEAD(&root->log_ctxs[1]);
685 atomic_set(&root->log_commit[0], 0);
686 atomic_set(&root->log_commit[1], 0);
687 atomic_set(&root->log_writers, 0);
688 atomic_set(&root->log_batch, 0);
689 refcount_set(&root->refs, 1);
690 atomic_set(&root->snapshot_force_cow, 0);
691 atomic_set(&root->nr_swapfiles, 0);
692 root->log_transid_committed = -1;
693 if (!btrfs_is_testing(fs_info)) {
694 btrfs_extent_io_tree_init(fs_info, &root->dirty_log_pages,
695 IO_TREE_ROOT_DIRTY_LOG_PAGES);
696 btrfs_extent_io_tree_init(fs_info, &root->log_csum_range,
697 IO_TREE_LOG_CSUM_RANGE);
698 }
699
700 spin_lock_init(&root->root_item_lock);
701 btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
702#ifdef CONFIG_BTRFS_DEBUG
703 INIT_LIST_HEAD(&root->leak_list);
704 spin_lock(&fs_info->fs_roots_radix_lock);
705 list_add_tail(&root->leak_list, &fs_info->allocated_roots);
706 spin_unlock(&fs_info->fs_roots_radix_lock);
707#endif
708
709 return root;
710}
711
712#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
713/* Should only be used by the testing infrastructure */
714struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
715{
716 struct btrfs_root *root;
717
718 if (!fs_info)
719 return ERR_PTR(-EINVAL);
720
721 root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
722 if (!root)
723 return ERR_PTR(-ENOMEM);
724
725 /* We don't use the stripesize in selftest, set it as sectorsize */
726 root->alloc_bytenr = 0;
727
728 return root;
729}
730#endif
731
732static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
733{
734 const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
735 const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
736
737 return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
738}
739
740static int global_root_key_cmp(const void *k, const struct rb_node *node)
741{
742 const struct btrfs_key *key = k;
743 const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
744
745 return btrfs_comp_cpu_keys(key, &root->root_key);
746}
747
748int btrfs_global_root_insert(struct btrfs_root *root)
749{
750 struct btrfs_fs_info *fs_info = root->fs_info;
751 struct rb_node *tmp;
752 int ret = 0;
753
754 write_lock(&fs_info->global_root_lock);
755 tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
756 write_unlock(&fs_info->global_root_lock);
757
758 if (tmp) {
759 ret = -EEXIST;
760 btrfs_warn(fs_info, "global root %llu %llu already exists",
761 btrfs_root_id(root), root->root_key.offset);
762 }
763 return ret;
764}
765
766void btrfs_global_root_delete(struct btrfs_root *root)
767{
768 struct btrfs_fs_info *fs_info = root->fs_info;
769
770 write_lock(&fs_info->global_root_lock);
771 rb_erase(&root->rb_node, &fs_info->global_root_tree);
772 write_unlock(&fs_info->global_root_lock);
773}
774
775struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
776 struct btrfs_key *key)
777{
778 struct rb_node *node;
779 struct btrfs_root *root = NULL;
780
781 read_lock(&fs_info->global_root_lock);
782 node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
783 if (node)
784 root = container_of(node, struct btrfs_root, rb_node);
785 read_unlock(&fs_info->global_root_lock);
786
787 return root;
788}
789
790static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
791{
792 struct btrfs_block_group *block_group;
793 u64 ret;
794
795 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
796 return 0;
797
798 if (bytenr)
799 block_group = btrfs_lookup_block_group(fs_info, bytenr);
800 else
801 block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
802 ASSERT(block_group);
803 if (!block_group)
804 return 0;
805 ret = block_group->global_root_id;
806 btrfs_put_block_group(block_group);
807
808 return ret;
809}
810
811struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
812{
813 struct btrfs_key key = {
814 .objectid = BTRFS_CSUM_TREE_OBJECTID,
815 .type = BTRFS_ROOT_ITEM_KEY,
816 .offset = btrfs_global_root_id(fs_info, bytenr),
817 };
818
819 return btrfs_global_root(fs_info, &key);
820}
821
822struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
823{
824 struct btrfs_key key = {
825 .objectid = BTRFS_EXTENT_TREE_OBJECTID,
826 .type = BTRFS_ROOT_ITEM_KEY,
827 .offset = btrfs_global_root_id(fs_info, bytenr),
828 };
829
830 return btrfs_global_root(fs_info, &key);
831}
832
833struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
834 u64 objectid)
835{
836 struct btrfs_fs_info *fs_info = trans->fs_info;
837 struct extent_buffer *leaf;
838 struct btrfs_root *tree_root = fs_info->tree_root;
839 struct btrfs_root *root;
840 struct btrfs_key key;
841 unsigned int nofs_flag;
842 int ret = 0;
843
844 /*
845 * We're holding a transaction handle, so use a NOFS memory allocation
846 * context to avoid deadlock if reclaim happens.
847 */
848 nofs_flag = memalloc_nofs_save();
849 root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
850 memalloc_nofs_restore(nofs_flag);
851 if (!root)
852 return ERR_PTR(-ENOMEM);
853
854 root->root_key.objectid = objectid;
855 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
856 root->root_key.offset = 0;
857
858 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
859 0, BTRFS_NESTING_NORMAL);
860 if (IS_ERR(leaf)) {
861 ret = PTR_ERR(leaf);
862 leaf = NULL;
863 goto fail;
864 }
865
866 root->node = leaf;
867 btrfs_mark_buffer_dirty(trans, leaf);
868
869 root->commit_root = btrfs_root_node(root);
870 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
871
872 btrfs_set_root_flags(&root->root_item, 0);
873 btrfs_set_root_limit(&root->root_item, 0);
874 btrfs_set_root_bytenr(&root->root_item, leaf->start);
875 btrfs_set_root_generation(&root->root_item, trans->transid);
876 btrfs_set_root_level(&root->root_item, 0);
877 btrfs_set_root_refs(&root->root_item, 1);
878 btrfs_set_root_used(&root->root_item, leaf->len);
879 btrfs_set_root_last_snapshot(&root->root_item, 0);
880 btrfs_set_root_dirid(&root->root_item, 0);
881 if (btrfs_is_fstree(objectid))
882 generate_random_guid(root->root_item.uuid);
883 else
884 export_guid(root->root_item.uuid, &guid_null);
885 btrfs_set_root_drop_level(&root->root_item, 0);
886
887 btrfs_tree_unlock(leaf);
888
889 key.objectid = objectid;
890 key.type = BTRFS_ROOT_ITEM_KEY;
891 key.offset = 0;
892 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
893 if (ret)
894 goto fail;
895
896 return root;
897
898fail:
899 btrfs_put_root(root);
900
901 return ERR_PTR(ret);
902}
903
904static struct btrfs_root *alloc_log_tree(struct btrfs_fs_info *fs_info)
905{
906 struct btrfs_root *root;
907
908 root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
909 if (!root)
910 return ERR_PTR(-ENOMEM);
911
912 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
913 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
914 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
915
916 return root;
917}
918
919int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
920 struct btrfs_root *root)
921{
922 struct extent_buffer *leaf;
923
924 /*
925 * DON'T set SHAREABLE bit for log trees.
926 *
927 * Log trees are not exposed to user space thus can't be snapshotted,
928 * and they go away before a real commit is actually done.
929 *
930 * They do store pointers to file data extents, and those reference
931 * counts still get updated (along with back refs to the log tree).
932 */
933
934 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
935 NULL, 0, 0, 0, 0, BTRFS_NESTING_NORMAL);
936 if (IS_ERR(leaf))
937 return PTR_ERR(leaf);
938
939 root->node = leaf;
940
941 btrfs_mark_buffer_dirty(trans, root->node);
942 btrfs_tree_unlock(root->node);
943
944 return 0;
945}
946
947int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
948 struct btrfs_fs_info *fs_info)
949{
950 struct btrfs_root *log_root;
951
952 log_root = alloc_log_tree(fs_info);
953 if (IS_ERR(log_root))
954 return PTR_ERR(log_root);
955
956 if (!btrfs_is_zoned(fs_info)) {
957 int ret = btrfs_alloc_log_tree_node(trans, log_root);
958
959 if (ret) {
960 btrfs_put_root(log_root);
961 return ret;
962 }
963 }
964
965 WARN_ON(fs_info->log_root_tree);
966 fs_info->log_root_tree = log_root;
967 return 0;
968}
969
970int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
971 struct btrfs_root *root)
972{
973 struct btrfs_fs_info *fs_info = root->fs_info;
974 struct btrfs_root *log_root;
975 struct btrfs_inode_item *inode_item;
976 int ret;
977
978 log_root = alloc_log_tree(fs_info);
979 if (IS_ERR(log_root))
980 return PTR_ERR(log_root);
981
982 ret = btrfs_alloc_log_tree_node(trans, log_root);
983 if (ret) {
984 btrfs_put_root(log_root);
985 return ret;
986 }
987
988 btrfs_set_root_last_trans(log_root, trans->transid);
989 log_root->root_key.offset = btrfs_root_id(root);
990
991 inode_item = &log_root->root_item.inode;
992 btrfs_set_stack_inode_generation(inode_item, 1);
993 btrfs_set_stack_inode_size(inode_item, 3);
994 btrfs_set_stack_inode_nlink(inode_item, 1);
995 btrfs_set_stack_inode_nbytes(inode_item,
996 fs_info->nodesize);
997 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
998
999 btrfs_set_root_node(&log_root->root_item, log_root->node);
1000
1001 WARN_ON(root->log_root);
1002 root->log_root = log_root;
1003 btrfs_set_root_log_transid(root, 0);
1004 root->log_transid_committed = -1;
1005 btrfs_set_root_last_log_commit(root, 0);
1006 return 0;
1007}
1008
1009static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
1010 struct btrfs_path *path,
1011 const struct btrfs_key *key)
1012{
1013 struct btrfs_root *root;
1014 struct btrfs_tree_parent_check check = { 0 };
1015 struct btrfs_fs_info *fs_info = tree_root->fs_info;
1016 u64 generation;
1017 int ret;
1018 int level;
1019
1020 root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1021 if (!root)
1022 return ERR_PTR(-ENOMEM);
1023
1024 ret = btrfs_find_root(tree_root, key, path,
1025 &root->root_item, &root->root_key);
1026 if (ret) {
1027 if (ret > 0)
1028 ret = -ENOENT;
1029 goto fail;
1030 }
1031
1032 generation = btrfs_root_generation(&root->root_item);
1033 level = btrfs_root_level(&root->root_item);
1034 check.level = level;
1035 check.transid = generation;
1036 check.owner_root = key->objectid;
1037 root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1038 &check);
1039 if (IS_ERR(root->node)) {
1040 ret = PTR_ERR(root->node);
1041 root->node = NULL;
1042 goto fail;
1043 }
1044 if (unlikely(!btrfs_buffer_uptodate(root->node, generation, false))) {
1045 ret = -EIO;
1046 goto fail;
1047 }
1048
1049 /*
1050 * For real fs, and not log/reloc trees, root owner must
1051 * match its root node owner
1052 */
1053 if (unlikely(!btrfs_is_testing(fs_info) &&
1054 btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1055 btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
1056 btrfs_root_id(root) != btrfs_header_owner(root->node))) {
1057 btrfs_crit(fs_info,
1058"root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
1059 btrfs_root_id(root), root->node->start,
1060 btrfs_header_owner(root->node),
1061 btrfs_root_id(root));
1062 ret = -EUCLEAN;
1063 goto fail;
1064 }
1065 root->commit_root = btrfs_root_node(root);
1066 return root;
1067fail:
1068 btrfs_put_root(root);
1069 return ERR_PTR(ret);
1070}
1071
1072struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1073 const struct btrfs_key *key)
1074{
1075 struct btrfs_root *root;
1076 BTRFS_PATH_AUTO_FREE(path);
1077
1078 path = btrfs_alloc_path();
1079 if (!path)
1080 return ERR_PTR(-ENOMEM);
1081 root = read_tree_root_path(tree_root, path, key);
1082
1083 return root;
1084}
1085
1086/*
1087 * Initialize subvolume root in-memory structure.
1088 *
1089 * @anon_dev: anonymous device to attach to the root, if zero, allocate new
1090 *
1091 * In case of failure the caller is responsible to call btrfs_free_fs_root()
1092 */
1093static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1094{
1095 int ret;
1096
1097 btrfs_drew_lock_init(&root->snapshot_lock);
1098
1099 if (btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1100 !btrfs_is_data_reloc_root(root) &&
1101 btrfs_is_fstree(btrfs_root_id(root))) {
1102 set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1103 btrfs_check_and_init_root_item(&root->root_item);
1104 }
1105
1106 /*
1107 * Don't assign anonymous block device to roots that are not exposed to
1108 * userspace, the id pool is limited to 1M
1109 */
1110 if (btrfs_is_fstree(btrfs_root_id(root)) &&
1111 btrfs_root_refs(&root->root_item) > 0) {
1112 if (!anon_dev) {
1113 ret = get_anon_bdev(&root->anon_dev);
1114 if (ret)
1115 return ret;
1116 } else {
1117 root->anon_dev = anon_dev;
1118 }
1119 }
1120
1121 mutex_lock(&root->objectid_mutex);
1122 ret = btrfs_init_root_free_objectid(root);
1123 if (ret) {
1124 mutex_unlock(&root->objectid_mutex);
1125 return ret;
1126 }
1127
1128 ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1129
1130 mutex_unlock(&root->objectid_mutex);
1131
1132 return 0;
1133}
1134
1135static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1136 u64 root_id)
1137{
1138 struct btrfs_root *root;
1139
1140 spin_lock(&fs_info->fs_roots_radix_lock);
1141 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1142 (unsigned long)root_id);
1143 root = btrfs_grab_root(root);
1144 spin_unlock(&fs_info->fs_roots_radix_lock);
1145 return root;
1146}
1147
1148static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
1149 u64 objectid)
1150{
1151 struct btrfs_key key = {
1152 .objectid = objectid,
1153 .type = BTRFS_ROOT_ITEM_KEY,
1154 .offset = 0,
1155 };
1156
1157 switch (objectid) {
1158 case BTRFS_ROOT_TREE_OBJECTID:
1159 return btrfs_grab_root(fs_info->tree_root);
1160 case BTRFS_EXTENT_TREE_OBJECTID:
1161 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1162 case BTRFS_CHUNK_TREE_OBJECTID:
1163 return btrfs_grab_root(fs_info->chunk_root);
1164 case BTRFS_DEV_TREE_OBJECTID:
1165 return btrfs_grab_root(fs_info->dev_root);
1166 case BTRFS_CSUM_TREE_OBJECTID:
1167 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1168 case BTRFS_QUOTA_TREE_OBJECTID:
1169 return btrfs_grab_root(fs_info->quota_root);
1170 case BTRFS_UUID_TREE_OBJECTID:
1171 return btrfs_grab_root(fs_info->uuid_root);
1172 case BTRFS_BLOCK_GROUP_TREE_OBJECTID:
1173 return btrfs_grab_root(fs_info->block_group_root);
1174 case BTRFS_FREE_SPACE_TREE_OBJECTID:
1175 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1176 case BTRFS_RAID_STRIPE_TREE_OBJECTID:
1177 return btrfs_grab_root(fs_info->stripe_root);
1178 default:
1179 return NULL;
1180 }
1181}
1182
1183int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1184 struct btrfs_root *root)
1185{
1186 int ret;
1187
1188 ret = radix_tree_preload(GFP_NOFS);
1189 if (ret)
1190 return ret;
1191
1192 spin_lock(&fs_info->fs_roots_radix_lock);
1193 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1194 (unsigned long)btrfs_root_id(root),
1195 root);
1196 if (ret == 0) {
1197 btrfs_grab_root(root);
1198 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1199 }
1200 spin_unlock(&fs_info->fs_roots_radix_lock);
1201 radix_tree_preload_end();
1202
1203 return ret;
1204}
1205
1206void btrfs_check_leaked_roots(const struct btrfs_fs_info *fs_info)
1207{
1208#ifdef CONFIG_BTRFS_DEBUG
1209 struct btrfs_root *root;
1210
1211 while (!list_empty(&fs_info->allocated_roots)) {
1212 char buf[BTRFS_ROOT_NAME_BUF_LEN];
1213
1214 root = list_first_entry(&fs_info->allocated_roots,
1215 struct btrfs_root, leak_list);
1216 btrfs_err(fs_info, "leaked root %s refcount %d",
1217 btrfs_root_name(&root->root_key, buf),
1218 refcount_read(&root->refs));
1219 WARN_ON_ONCE(1);
1220 while (refcount_read(&root->refs) > 1)
1221 btrfs_put_root(root);
1222 btrfs_put_root(root);
1223 }
1224#endif
1225}
1226
1227static void free_global_roots(struct btrfs_fs_info *fs_info)
1228{
1229 struct btrfs_root *root;
1230 struct rb_node *node;
1231
1232 while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1233 root = rb_entry(node, struct btrfs_root, rb_node);
1234 rb_erase(&root->rb_node, &fs_info->global_root_tree);
1235 btrfs_put_root(root);
1236 }
1237}
1238
1239void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
1240{
1241 struct percpu_counter *em_counter = &fs_info->evictable_extent_maps;
1242
1243 if (fs_info->fs_devices)
1244 btrfs_close_devices(fs_info->fs_devices);
1245 btrfs_free_compress_wsm(fs_info);
1246 percpu_counter_destroy(&fs_info->stats_read_blocks);
1247 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1248 percpu_counter_destroy(&fs_info->delalloc_bytes);
1249 percpu_counter_destroy(&fs_info->ordered_bytes);
1250 if (percpu_counter_initialized(em_counter))
1251 ASSERT(percpu_counter_sum_positive(em_counter) == 0);
1252 percpu_counter_destroy(em_counter);
1253 percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1254 btrfs_free_csum_hash(fs_info);
1255 btrfs_free_stripe_hash_table(fs_info);
1256 btrfs_free_ref_cache(fs_info);
1257 kfree(fs_info->balance_ctl);
1258 kfree(fs_info->delayed_root);
1259 free_global_roots(fs_info);
1260 btrfs_put_root(fs_info->tree_root);
1261 btrfs_put_root(fs_info->chunk_root);
1262 btrfs_put_root(fs_info->dev_root);
1263 btrfs_put_root(fs_info->quota_root);
1264 btrfs_put_root(fs_info->uuid_root);
1265 btrfs_put_root(fs_info->fs_root);
1266 btrfs_put_root(fs_info->data_reloc_root);
1267 btrfs_put_root(fs_info->block_group_root);
1268 btrfs_put_root(fs_info->stripe_root);
1269 btrfs_check_leaked_roots(fs_info);
1270 btrfs_extent_buffer_leak_debug_check(fs_info);
1271 kfree(fs_info->super_copy);
1272 kfree(fs_info->super_for_commit);
1273 kvfree(fs_info);
1274}
1275
1276
1277/*
1278 * Get an in-memory reference of a root structure.
1279 *
1280 * For essential trees like root/extent tree, we grab it from fs_info directly.
1281 * For subvolume trees, we check the cached filesystem roots first. If not
1282 * found, then read it from disk and add it to cached fs roots.
1283 *
1284 * Caller should release the root by calling btrfs_put_root() after the usage.
1285 *
1286 * NOTE: Reloc and log trees can't be read by this function as they share the
1287 * same root objectid.
1288 *
1289 * @objectid: root id
1290 * @anon_dev: preallocated anonymous block device number for new roots,
1291 * pass NULL for a new allocation.
1292 * @check_ref: whether to check root item references, If true, return -ENOENT
1293 * for orphan roots
1294 */
1295static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
1296 u64 objectid, dev_t *anon_dev,
1297 bool check_ref)
1298{
1299 struct btrfs_root *root;
1300 struct btrfs_path *path;
1301 struct btrfs_key key;
1302 int ret;
1303
1304 root = btrfs_get_global_root(fs_info, objectid);
1305 if (root)
1306 return root;
1307
1308 /*
1309 * If we're called for non-subvolume trees, and above function didn't
1310 * find one, do not try to read it from disk.
1311 *
1312 * This is namely for free-space-tree and quota tree, which can change
1313 * at runtime and should only be grabbed from fs_info.
1314 */
1315 if (!btrfs_is_fstree(objectid) && objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1316 return ERR_PTR(-ENOENT);
1317again:
1318 root = btrfs_lookup_fs_root(fs_info, objectid);
1319 if (root) {
1320 /*
1321 * Some other caller may have read out the newly inserted
1322 * subvolume already (for things like backref walk etc). Not
1323 * that common but still possible. In that case, we just need
1324 * to free the anon_dev.
1325 */
1326 if (unlikely(anon_dev && *anon_dev)) {
1327 free_anon_bdev(*anon_dev);
1328 *anon_dev = 0;
1329 }
1330
1331 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1332 btrfs_put_root(root);
1333 return ERR_PTR(-ENOENT);
1334 }
1335 return root;
1336 }
1337
1338 key.objectid = objectid;
1339 key.type = BTRFS_ROOT_ITEM_KEY;
1340 key.offset = (u64)-1;
1341 root = btrfs_read_tree_root(fs_info->tree_root, &key);
1342 if (IS_ERR(root))
1343 return root;
1344
1345 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1346 ret = -ENOENT;
1347 goto fail;
1348 }
1349
1350 ret = btrfs_init_fs_root(root, anon_dev ? *anon_dev : 0);
1351 if (ret)
1352 goto fail;
1353
1354 path = btrfs_alloc_path();
1355 if (!path) {
1356 ret = -ENOMEM;
1357 goto fail;
1358 }
1359 key.objectid = BTRFS_ORPHAN_OBJECTID;
1360 key.type = BTRFS_ORPHAN_ITEM_KEY;
1361 key.offset = objectid;
1362
1363 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1364 btrfs_free_path(path);
1365 if (ret < 0)
1366 goto fail;
1367 if (ret == 0)
1368 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1369
1370 ret = btrfs_insert_fs_root(fs_info, root);
1371 if (ret) {
1372 if (ret == -EEXIST) {
1373 btrfs_put_root(root);
1374 goto again;
1375 }
1376 goto fail;
1377 }
1378 return root;
1379fail:
1380 /*
1381 * If our caller provided us an anonymous device, then it's his
1382 * responsibility to free it in case we fail. So we have to set our
1383 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
1384 * and once again by our caller.
1385 */
1386 if (anon_dev && *anon_dev)
1387 root->anon_dev = 0;
1388 btrfs_put_root(root);
1389 return ERR_PTR(ret);
1390}
1391
1392/*
1393 * Get in-memory reference of a root structure
1394 *
1395 * @objectid: tree objectid
1396 * @check_ref: if set, verify that the tree exists and the item has at least
1397 * one reference
1398 */
1399struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1400 u64 objectid, bool check_ref)
1401{
1402 return btrfs_get_root_ref(fs_info, objectid, NULL, check_ref);
1403}
1404
1405/*
1406 * Get in-memory reference of a root structure, created as new, optionally pass
1407 * the anonymous block device id
1408 *
1409 * @objectid: tree objectid
1410 * @anon_dev: if NULL, allocate a new anonymous block device or use the
1411 * parameter value if not NULL
1412 */
1413struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
1414 u64 objectid, dev_t *anon_dev)
1415{
1416 return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
1417}
1418
1419/*
1420 * Return a root for the given objectid.
1421 *
1422 * @fs_info: the fs_info
1423 * @objectid: the objectid we need to lookup
1424 *
1425 * This is exclusively used for backref walking, and exists specifically because
1426 * of how qgroups does lookups. Qgroups will do a backref lookup at delayed ref
1427 * creation time, which means we may have to read the tree_root in order to look
1428 * up a fs root that is not in memory. If the root is not in memory we will
1429 * read the tree root commit root and look up the fs root from there. This is a
1430 * temporary root, it will not be inserted into the radix tree as it doesn't
1431 * have the most uptodate information, it'll simply be discarded once the
1432 * backref code is finished using the root.
1433 */
1434struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
1435 struct btrfs_path *path,
1436 u64 objectid)
1437{
1438 struct btrfs_root *root;
1439 struct btrfs_key key;
1440
1441 ASSERT(path->search_commit_root && path->skip_locking);
1442
1443 /*
1444 * This can return -ENOENT if we ask for a root that doesn't exist, but
1445 * since this is called via the backref walking code we won't be looking
1446 * up a root that doesn't exist, unless there's corruption. So if root
1447 * != NULL just return it.
1448 */
1449 root = btrfs_get_global_root(fs_info, objectid);
1450 if (root)
1451 return root;
1452
1453 root = btrfs_lookup_fs_root(fs_info, objectid);
1454 if (root)
1455 return root;
1456
1457 key.objectid = objectid;
1458 key.type = BTRFS_ROOT_ITEM_KEY;
1459 key.offset = (u64)-1;
1460 root = read_tree_root_path(fs_info->tree_root, path, &key);
1461 btrfs_release_path(path);
1462
1463 return root;
1464}
1465
1466static int cleaner_kthread(void *arg)
1467{
1468 struct btrfs_fs_info *fs_info = arg;
1469 int again;
1470
1471 while (1) {
1472 again = 0;
1473
1474 set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1475
1476 /* Make the cleaner go to sleep early. */
1477 if (btrfs_need_cleaner_sleep(fs_info))
1478 goto sleep;
1479
1480 /*
1481 * Do not do anything if we might cause open_ctree() to block
1482 * before we have finished mounting the filesystem.
1483 */
1484 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1485 goto sleep;
1486
1487 if (!mutex_trylock(&fs_info->cleaner_mutex))
1488 goto sleep;
1489
1490 /*
1491 * Avoid the problem that we change the status of the fs
1492 * during the above check and trylock.
1493 */
1494 if (btrfs_need_cleaner_sleep(fs_info)) {
1495 mutex_unlock(&fs_info->cleaner_mutex);
1496 goto sleep;
1497 }
1498
1499 if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1500 btrfs_sysfs_feature_update(fs_info);
1501
1502 btrfs_run_delayed_iputs(fs_info);
1503
1504 again = btrfs_clean_one_deleted_snapshot(fs_info);
1505 mutex_unlock(&fs_info->cleaner_mutex);
1506
1507 /*
1508 * The defragger has dealt with the R/O remount and umount,
1509 * needn't do anything special here.
1510 */
1511 btrfs_run_defrag_inodes(fs_info);
1512
1513 /*
1514 * Acquires fs_info->reclaim_bgs_lock to avoid racing
1515 * with relocation (btrfs_relocate_chunk) and relocation
1516 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1517 * after acquiring fs_info->reclaim_bgs_lock. So we
1518 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1519 * unused block groups.
1520 */
1521 btrfs_delete_unused_bgs(fs_info);
1522
1523 /*
1524 * Reclaim block groups in the reclaim_bgs list after we deleted
1525 * all unused block_groups. This possibly gives us some more free
1526 * space.
1527 */
1528 btrfs_reclaim_bgs(fs_info);
1529sleep:
1530 clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1531 if (kthread_should_park())
1532 kthread_parkme();
1533 if (kthread_should_stop())
1534 return 0;
1535 if (!again) {
1536 set_current_state(TASK_INTERRUPTIBLE);
1537 schedule();
1538 __set_current_state(TASK_RUNNING);
1539 }
1540 }
1541}
1542
1543static int transaction_kthread(void *arg)
1544{
1545 struct btrfs_root *root = arg;
1546 struct btrfs_fs_info *fs_info = root->fs_info;
1547 struct btrfs_trans_handle *trans;
1548 struct btrfs_transaction *cur;
1549 u64 transid;
1550 time64_t delta;
1551 unsigned long delay;
1552 bool cannot_commit;
1553
1554 do {
1555 cannot_commit = false;
1556 delay = secs_to_jiffies(fs_info->commit_interval);
1557 mutex_lock(&fs_info->transaction_kthread_mutex);
1558
1559 spin_lock(&fs_info->trans_lock);
1560 cur = fs_info->running_transaction;
1561 if (!cur) {
1562 spin_unlock(&fs_info->trans_lock);
1563 goto sleep;
1564 }
1565
1566 delta = ktime_get_seconds() - cur->start_time;
1567 if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1568 cur->state < TRANS_STATE_COMMIT_PREP &&
1569 delta < fs_info->commit_interval) {
1570 spin_unlock(&fs_info->trans_lock);
1571 delay -= secs_to_jiffies(delta - 1);
1572 delay = min(delay,
1573 secs_to_jiffies(fs_info->commit_interval));
1574 goto sleep;
1575 }
1576 transid = cur->transid;
1577 spin_unlock(&fs_info->trans_lock);
1578
1579 /* If the file system is aborted, this will always fail. */
1580 trans = btrfs_attach_transaction(root);
1581 if (IS_ERR(trans)) {
1582 if (PTR_ERR(trans) != -ENOENT)
1583 cannot_commit = true;
1584 goto sleep;
1585 }
1586 if (transid == trans->transid) {
1587 btrfs_commit_transaction(trans);
1588 } else {
1589 btrfs_end_transaction(trans);
1590 }
1591sleep:
1592 wake_up_process(fs_info->cleaner_kthread);
1593 mutex_unlock(&fs_info->transaction_kthread_mutex);
1594
1595 if (BTRFS_FS_ERROR(fs_info))
1596 btrfs_cleanup_transaction(fs_info);
1597 if (!kthread_should_stop() &&
1598 (!btrfs_transaction_blocked(fs_info) ||
1599 cannot_commit))
1600 schedule_timeout_interruptible(delay);
1601 } while (!kthread_should_stop());
1602 return 0;
1603}
1604
1605/*
1606 * This will find the highest generation in the array of root backups. The
1607 * index of the highest array is returned, or -EINVAL if we can't find
1608 * anything.
1609 *
1610 * We check to make sure the array is valid by comparing the
1611 * generation of the latest root in the array with the generation
1612 * in the super block. If they don't match we pitch it.
1613 */
1614static int find_newest_super_backup(struct btrfs_fs_info *info)
1615{
1616 const u64 newest_gen = btrfs_super_generation(info->super_copy);
1617 u64 cur;
1618 struct btrfs_root_backup *root_backup;
1619 int i;
1620
1621 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1622 root_backup = info->super_copy->super_roots + i;
1623 cur = btrfs_backup_tree_root_gen(root_backup);
1624 if (cur == newest_gen)
1625 return i;
1626 }
1627
1628 return -EINVAL;
1629}
1630
1631/*
1632 * copy all the root pointers into the super backup array.
1633 * this will bump the backup pointer by one when it is
1634 * done
1635 */
1636static void backup_super_roots(struct btrfs_fs_info *info)
1637{
1638 const int next_backup = info->backup_root_index;
1639 struct btrfs_root_backup *root_backup;
1640
1641 root_backup = info->super_for_commit->super_roots + next_backup;
1642
1643 /*
1644 * make sure all of our padding and empty slots get zero filled
1645 * regardless of which ones we use today
1646 */
1647 memset(root_backup, 0, sizeof(*root_backup));
1648
1649 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1650
1651 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1652 btrfs_set_backup_tree_root_gen(root_backup,
1653 btrfs_header_generation(info->tree_root->node));
1654
1655 btrfs_set_backup_tree_root_level(root_backup,
1656 btrfs_header_level(info->tree_root->node));
1657
1658 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1659 btrfs_set_backup_chunk_root_gen(root_backup,
1660 btrfs_header_generation(info->chunk_root->node));
1661 btrfs_set_backup_chunk_root_level(root_backup,
1662 btrfs_header_level(info->chunk_root->node));
1663
1664 if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
1665 struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1666 struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
1667
1668 btrfs_set_backup_extent_root(root_backup,
1669 extent_root->node->start);
1670 btrfs_set_backup_extent_root_gen(root_backup,
1671 btrfs_header_generation(extent_root->node));
1672 btrfs_set_backup_extent_root_level(root_backup,
1673 btrfs_header_level(extent_root->node));
1674
1675 btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1676 btrfs_set_backup_csum_root_gen(root_backup,
1677 btrfs_header_generation(csum_root->node));
1678 btrfs_set_backup_csum_root_level(root_backup,
1679 btrfs_header_level(csum_root->node));
1680 }
1681
1682 /*
1683 * we might commit during log recovery, which happens before we set
1684 * the fs_root. Make sure it is valid before we fill it in.
1685 */
1686 if (info->fs_root && info->fs_root->node) {
1687 btrfs_set_backup_fs_root(root_backup,
1688 info->fs_root->node->start);
1689 btrfs_set_backup_fs_root_gen(root_backup,
1690 btrfs_header_generation(info->fs_root->node));
1691 btrfs_set_backup_fs_root_level(root_backup,
1692 btrfs_header_level(info->fs_root->node));
1693 }
1694
1695 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1696 btrfs_set_backup_dev_root_gen(root_backup,
1697 btrfs_header_generation(info->dev_root->node));
1698 btrfs_set_backup_dev_root_level(root_backup,
1699 btrfs_header_level(info->dev_root->node));
1700
1701 btrfs_set_backup_total_bytes(root_backup,
1702 btrfs_super_total_bytes(info->super_copy));
1703 btrfs_set_backup_bytes_used(root_backup,
1704 btrfs_super_bytes_used(info->super_copy));
1705 btrfs_set_backup_num_devices(root_backup,
1706 btrfs_super_num_devices(info->super_copy));
1707
1708 /*
1709 * if we don't copy this out to the super_copy, it won't get remembered
1710 * for the next commit
1711 */
1712 memcpy(&info->super_copy->super_roots,
1713 &info->super_for_commit->super_roots,
1714 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1715}
1716
1717/*
1718 * Reads a backup root based on the passed priority. Prio 0 is the newest, prio
1719 * 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1720 *
1721 * @fs_info: filesystem whose backup roots need to be read
1722 * @priority: priority of backup root required
1723 *
1724 * Returns backup root index on success and -EINVAL otherwise.
1725 */
1726static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1727{
1728 int backup_index = find_newest_super_backup(fs_info);
1729 struct btrfs_super_block *super = fs_info->super_copy;
1730 struct btrfs_root_backup *root_backup;
1731
1732 if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1733 if (priority == 0)
1734 return backup_index;
1735
1736 backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1737 backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1738 } else {
1739 return -EINVAL;
1740 }
1741
1742 root_backup = super->super_roots + backup_index;
1743
1744 btrfs_set_super_generation(super,
1745 btrfs_backup_tree_root_gen(root_backup));
1746 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1747 btrfs_set_super_root_level(super,
1748 btrfs_backup_tree_root_level(root_backup));
1749 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1750
1751 /*
1752 * Fixme: the total bytes and num_devices need to match or we should
1753 * need a fsck
1754 */
1755 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1756 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1757
1758 return backup_index;
1759}
1760
1761/* helper to cleanup workers */
1762static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
1763{
1764 btrfs_destroy_workqueue(fs_info->fixup_workers);
1765 btrfs_destroy_workqueue(fs_info->delalloc_workers);
1766 btrfs_destroy_workqueue(fs_info->workers);
1767 if (fs_info->endio_workers)
1768 destroy_workqueue(fs_info->endio_workers);
1769 if (fs_info->rmw_workers)
1770 destroy_workqueue(fs_info->rmw_workers);
1771 btrfs_destroy_workqueue(fs_info->endio_write_workers);
1772 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
1773 btrfs_destroy_workqueue(fs_info->delayed_workers);
1774 btrfs_destroy_workqueue(fs_info->caching_workers);
1775 btrfs_destroy_workqueue(fs_info->flush_workers);
1776 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1777 if (fs_info->discard_ctl.discard_workers)
1778 destroy_workqueue(fs_info->discard_ctl.discard_workers);
1779 /*
1780 * Now that all other work queues are destroyed, we can safely destroy
1781 * the queues used for metadata I/O, since tasks from those other work
1782 * queues can do metadata I/O operations.
1783 */
1784 if (fs_info->endio_meta_workers)
1785 destroy_workqueue(fs_info->endio_meta_workers);
1786}
1787
1788static void free_root_extent_buffers(struct btrfs_root *root)
1789{
1790 if (root) {
1791 free_extent_buffer(root->node);
1792 free_extent_buffer(root->commit_root);
1793 root->node = NULL;
1794 root->commit_root = NULL;
1795 }
1796}
1797
1798static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1799{
1800 struct btrfs_root *root, *tmp;
1801
1802 rbtree_postorder_for_each_entry_safe(root, tmp,
1803 &fs_info->global_root_tree,
1804 rb_node)
1805 free_root_extent_buffers(root);
1806}
1807
1808/* helper to cleanup tree roots */
1809static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1810{
1811 free_root_extent_buffers(info->tree_root);
1812
1813 free_global_root_pointers(info);
1814 free_root_extent_buffers(info->dev_root);
1815 free_root_extent_buffers(info->quota_root);
1816 free_root_extent_buffers(info->uuid_root);
1817 free_root_extent_buffers(info->fs_root);
1818 free_root_extent_buffers(info->data_reloc_root);
1819 free_root_extent_buffers(info->block_group_root);
1820 free_root_extent_buffers(info->stripe_root);
1821 if (free_chunk_root)
1822 free_root_extent_buffers(info->chunk_root);
1823}
1824
1825void btrfs_put_root(struct btrfs_root *root)
1826{
1827 if (!root)
1828 return;
1829
1830 if (refcount_dec_and_test(&root->refs)) {
1831 if (WARN_ON(!xa_empty(&root->inodes)))
1832 xa_destroy(&root->inodes);
1833 if (WARN_ON(!xa_empty(&root->delayed_nodes)))
1834 xa_destroy(&root->delayed_nodes);
1835 WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
1836 if (root->anon_dev)
1837 free_anon_bdev(root->anon_dev);
1838 free_root_extent_buffers(root);
1839#ifdef CONFIG_BTRFS_DEBUG
1840 spin_lock(&root->fs_info->fs_roots_radix_lock);
1841 list_del_init(&root->leak_list);
1842 spin_unlock(&root->fs_info->fs_roots_radix_lock);
1843#endif
1844 kfree(root);
1845 }
1846}
1847
1848void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1849{
1850 int ret;
1851 struct btrfs_root *gang[8];
1852 int i;
1853
1854 while (!list_empty(&fs_info->dead_roots)) {
1855 gang[0] = list_first_entry(&fs_info->dead_roots,
1856 struct btrfs_root, root_list);
1857 list_del(&gang[0]->root_list);
1858
1859 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1860 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1861 btrfs_put_root(gang[0]);
1862 }
1863
1864 while (1) {
1865 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1866 (void **)gang, 0,
1867 ARRAY_SIZE(gang));
1868 if (!ret)
1869 break;
1870 for (i = 0; i < ret; i++)
1871 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1872 }
1873}
1874
1875static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1876{
1877 mutex_init(&fs_info->scrub_lock);
1878 atomic_set(&fs_info->scrubs_running, 0);
1879 atomic_set(&fs_info->scrub_pause_req, 0);
1880 atomic_set(&fs_info->scrubs_paused, 0);
1881 atomic_set(&fs_info->scrub_cancel_req, 0);
1882 init_waitqueue_head(&fs_info->scrub_pause_wait);
1883 refcount_set(&fs_info->scrub_workers_refcnt, 0);
1884}
1885
1886static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1887{
1888 spin_lock_init(&fs_info->balance_lock);
1889 mutex_init(&fs_info->balance_mutex);
1890 atomic_set(&fs_info->balance_pause_req, 0);
1891 atomic_set(&fs_info->balance_cancel_req, 0);
1892 fs_info->balance_ctl = NULL;
1893 init_waitqueue_head(&fs_info->balance_wait_q);
1894 atomic_set(&fs_info->reloc_cancel_req, 0);
1895}
1896
1897static int btrfs_init_btree_inode(struct super_block *sb)
1898{
1899 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1900 unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1901 fs_info->tree_root);
1902 struct inode *inode;
1903
1904 inode = new_inode(sb);
1905 if (!inode)
1906 return -ENOMEM;
1907
1908 btrfs_set_inode_number(BTRFS_I(inode), BTRFS_BTREE_INODE_OBJECTID);
1909 set_nlink(inode, 1);
1910 /*
1911 * we set the i_size on the btree inode to the max possible int.
1912 * the real end of the address space is determined by all of
1913 * the devices in the system
1914 */
1915 inode->i_size = OFFSET_MAX;
1916 inode->i_mapping->a_ops = &btree_aops;
1917 mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1918
1919 btrfs_extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
1920 IO_TREE_BTREE_INODE_IO);
1921 btrfs_extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1922
1923 BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1924 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1925 __insert_inode_hash(inode, hash);
1926 set_bit(AS_KERNEL_FILE, &inode->i_mapping->flags);
1927 fs_info->btree_inode = inode;
1928
1929 return 0;
1930}
1931
1932static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1933{
1934 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1935 init_rwsem(&fs_info->dev_replace.rwsem);
1936 init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1937}
1938
1939static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1940{
1941 spin_lock_init(&fs_info->qgroup_lock);
1942 mutex_init(&fs_info->qgroup_ioctl_lock);
1943 fs_info->qgroup_tree = RB_ROOT;
1944 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1945 fs_info->qgroup_seq = 1;
1946 fs_info->qgroup_rescan_running = false;
1947 fs_info->qgroup_drop_subtree_thres = BTRFS_QGROUP_DROP_SUBTREE_THRES_DEFAULT;
1948 mutex_init(&fs_info->qgroup_rescan_lock);
1949}
1950
1951static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
1952{
1953 u32 max_active = fs_info->thread_pool_size;
1954 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
1955 unsigned int ordered_flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_PERCPU;
1956
1957 fs_info->workers =
1958 btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
1959
1960 fs_info->delalloc_workers =
1961 btrfs_alloc_workqueue(fs_info, "delalloc",
1962 flags, max_active, 2);
1963
1964 fs_info->flush_workers =
1965 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1966 flags, max_active, 0);
1967
1968 fs_info->caching_workers =
1969 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
1970
1971 fs_info->fixup_workers =
1972 btrfs_alloc_ordered_workqueue(fs_info, "fixup", ordered_flags);
1973
1974 fs_info->endio_workers =
1975 alloc_workqueue("btrfs-endio", flags, max_active);
1976 fs_info->endio_meta_workers =
1977 alloc_workqueue("btrfs-endio-meta", flags, max_active);
1978 fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
1979 fs_info->endio_write_workers =
1980 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1981 max_active, 2);
1982 fs_info->endio_freespace_worker =
1983 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
1984 max_active, 0);
1985 fs_info->delayed_workers =
1986 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1987 max_active, 0);
1988 fs_info->qgroup_rescan_workers =
1989 btrfs_alloc_ordered_workqueue(fs_info, "qgroup-rescan",
1990 ordered_flags);
1991 fs_info->discard_ctl.discard_workers =
1992 alloc_ordered_workqueue("btrfs-discard", WQ_FREEZABLE);
1993
1994 if (!(fs_info->workers &&
1995 fs_info->delalloc_workers && fs_info->flush_workers &&
1996 fs_info->endio_workers && fs_info->endio_meta_workers &&
1997 fs_info->endio_write_workers &&
1998 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
1999 fs_info->caching_workers && fs_info->fixup_workers &&
2000 fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2001 fs_info->discard_ctl.discard_workers)) {
2002 return -ENOMEM;
2003 }
2004
2005 return 0;
2006}
2007
2008static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
2009{
2010 struct crypto_shash *csum_shash;
2011 const char *csum_driver = btrfs_super_csum_driver(csum_type);
2012
2013 csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
2014
2015 if (IS_ERR(csum_shash)) {
2016 btrfs_err(fs_info, "error allocating %s hash for checksum",
2017 csum_driver);
2018 return PTR_ERR(csum_shash);
2019 }
2020
2021 fs_info->csum_shash = csum_shash;
2022
2023 /* Check if the checksum implementation is a fast accelerated one. */
2024 switch (csum_type) {
2025 case BTRFS_CSUM_TYPE_CRC32:
2026 if (crc32_optimizations() & CRC32C_OPTIMIZATION)
2027 set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2028 break;
2029 case BTRFS_CSUM_TYPE_XXHASH:
2030 set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2031 break;
2032 default:
2033 break;
2034 }
2035
2036 btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2037 btrfs_super_csum_name(csum_type),
2038 crypto_shash_driver_name(csum_shash));
2039 return 0;
2040}
2041
2042static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2043 struct btrfs_fs_devices *fs_devices)
2044{
2045 int ret;
2046 struct btrfs_tree_parent_check check = { 0 };
2047 struct btrfs_root *log_tree_root;
2048 struct btrfs_super_block *disk_super = fs_info->super_copy;
2049 u64 bytenr = btrfs_super_log_root(disk_super);
2050 int level = btrfs_super_log_root_level(disk_super);
2051
2052 if (unlikely(fs_devices->rw_devices == 0)) {
2053 btrfs_warn(fs_info, "log replay required on RO media");
2054 return -EIO;
2055 }
2056
2057 log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
2058 GFP_KERNEL);
2059 if (!log_tree_root)
2060 return -ENOMEM;
2061
2062 check.level = level;
2063 check.transid = fs_info->generation + 1;
2064 check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2065 log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
2066 if (IS_ERR(log_tree_root->node)) {
2067 btrfs_warn(fs_info, "failed to read log tree");
2068 ret = PTR_ERR(log_tree_root->node);
2069 log_tree_root->node = NULL;
2070 btrfs_put_root(log_tree_root);
2071 return ret;
2072 }
2073 if (unlikely(!extent_buffer_uptodate(log_tree_root->node))) {
2074 btrfs_err(fs_info, "failed to read log tree");
2075 btrfs_put_root(log_tree_root);
2076 return -EIO;
2077 }
2078
2079 /* returns with log_tree_root freed on success */
2080 ret = btrfs_recover_log_trees(log_tree_root);
2081 btrfs_put_root(log_tree_root);
2082 if (ret) {
2083 btrfs_handle_fs_error(fs_info, ret,
2084 "Failed to recover log tree");
2085 return ret;
2086 }
2087
2088 if (sb_rdonly(fs_info->sb)) {
2089 ret = btrfs_commit_super(fs_info);
2090 if (ret)
2091 return ret;
2092 }
2093
2094 return 0;
2095}
2096
2097static int load_global_roots_objectid(struct btrfs_root *tree_root,
2098 struct btrfs_path *path, u64 objectid,
2099 const char *name)
2100{
2101 struct btrfs_fs_info *fs_info = tree_root->fs_info;
2102 struct btrfs_root *root;
2103 u64 max_global_id = 0;
2104 int ret;
2105 struct btrfs_key key = {
2106 .objectid = objectid,
2107 .type = BTRFS_ROOT_ITEM_KEY,
2108 .offset = 0,
2109 };
2110 bool found = false;
2111
2112 /* If we have IGNOREDATACSUMS skip loading these roots. */
2113 if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2114 btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2115 set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2116 return 0;
2117 }
2118
2119 while (1) {
2120 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2121 if (ret < 0)
2122 break;
2123
2124 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2125 ret = btrfs_next_leaf(tree_root, path);
2126 if (ret) {
2127 if (ret > 0)
2128 ret = 0;
2129 break;
2130 }
2131 }
2132 ret = 0;
2133
2134 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2135 if (key.objectid != objectid)
2136 break;
2137 btrfs_release_path(path);
2138
2139 /*
2140 * Just worry about this for extent tree, it'll be the same for
2141 * everybody.
2142 */
2143 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2144 max_global_id = max(max_global_id, key.offset);
2145
2146 found = true;
2147 root = read_tree_root_path(tree_root, path, &key);
2148 if (IS_ERR(root)) {
2149 ret = PTR_ERR(root);
2150 break;
2151 }
2152 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2153 ret = btrfs_global_root_insert(root);
2154 if (ret) {
2155 btrfs_put_root(root);
2156 break;
2157 }
2158 key.offset++;
2159 }
2160 btrfs_release_path(path);
2161
2162 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2163 fs_info->nr_global_roots = max_global_id + 1;
2164
2165 if (!found || ret) {
2166 if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2167 set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2168
2169 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2170 ret = ret ? ret : -ENOENT;
2171 else
2172 ret = 0;
2173 btrfs_err(fs_info, "failed to load root %s", name);
2174 }
2175 return ret;
2176}
2177
2178static int load_global_roots(struct btrfs_root *tree_root)
2179{
2180 BTRFS_PATH_AUTO_FREE(path);
2181 int ret;
2182
2183 path = btrfs_alloc_path();
2184 if (!path)
2185 return -ENOMEM;
2186
2187 ret = load_global_roots_objectid(tree_root, path,
2188 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2189 if (ret)
2190 return ret;
2191 ret = load_global_roots_objectid(tree_root, path,
2192 BTRFS_CSUM_TREE_OBJECTID, "csum");
2193 if (ret)
2194 return ret;
2195 if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2196 return ret;
2197 ret = load_global_roots_objectid(tree_root, path,
2198 BTRFS_FREE_SPACE_TREE_OBJECTID,
2199 "free space");
2200
2201 return ret;
2202}
2203
2204static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2205{
2206 struct btrfs_root *tree_root = fs_info->tree_root;
2207 struct btrfs_root *root;
2208 struct btrfs_key location;
2209 int ret;
2210
2211 ASSERT(fs_info->tree_root);
2212
2213 ret = load_global_roots(tree_root);
2214 if (ret)
2215 return ret;
2216
2217 location.type = BTRFS_ROOT_ITEM_KEY;
2218 location.offset = 0;
2219
2220 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
2221 location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
2222 root = btrfs_read_tree_root(tree_root, &location);
2223 if (IS_ERR(root)) {
2224 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2225 ret = PTR_ERR(root);
2226 goto out;
2227 }
2228 } else {
2229 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2230 fs_info->block_group_root = root;
2231 }
2232 }
2233
2234 location.objectid = BTRFS_DEV_TREE_OBJECTID;
2235 root = btrfs_read_tree_root(tree_root, &location);
2236 if (IS_ERR(root)) {
2237 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2238 ret = PTR_ERR(root);
2239 goto out;
2240 }
2241 } else {
2242 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2243 fs_info->dev_root = root;
2244 }
2245 /* Initialize fs_info for all devices in any case */
2246 ret = btrfs_init_devices_late(fs_info);
2247 if (ret)
2248 goto out;
2249
2250 /*
2251 * This tree can share blocks with some other fs tree during relocation
2252 * and we need a proper setup by btrfs_get_fs_root
2253 */
2254 root = btrfs_get_fs_root(tree_root->fs_info,
2255 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2256 if (IS_ERR(root)) {
2257 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2258 location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
2259 ret = PTR_ERR(root);
2260 goto out;
2261 }
2262 } else {
2263 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2264 fs_info->data_reloc_root = root;
2265 }
2266
2267 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2268 root = btrfs_read_tree_root(tree_root, &location);
2269 if (!IS_ERR(root)) {
2270 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2271 fs_info->quota_root = root;
2272 }
2273
2274 location.objectid = BTRFS_UUID_TREE_OBJECTID;
2275 root = btrfs_read_tree_root(tree_root, &location);
2276 if (IS_ERR(root)) {
2277 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2278 ret = PTR_ERR(root);
2279 if (ret != -ENOENT)
2280 goto out;
2281 }
2282 } else {
2283 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2284 fs_info->uuid_root = root;
2285 }
2286
2287 if (btrfs_fs_incompat(fs_info, RAID_STRIPE_TREE)) {
2288 location.objectid = BTRFS_RAID_STRIPE_TREE_OBJECTID;
2289 root = btrfs_read_tree_root(tree_root, &location);
2290 if (IS_ERR(root)) {
2291 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2292 ret = PTR_ERR(root);
2293 goto out;
2294 }
2295 } else {
2296 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2297 fs_info->stripe_root = root;
2298 }
2299 }
2300
2301 return 0;
2302out:
2303 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2304 location.objectid, ret);
2305 return ret;
2306}
2307
2308static int validate_sys_chunk_array(const struct btrfs_fs_info *fs_info,
2309 const struct btrfs_super_block *sb)
2310{
2311 unsigned int cur = 0; /* Offset inside the sys chunk array */
2312 /*
2313 * At sb read time, fs_info is not fully initialized. Thus we have
2314 * to use super block sectorsize, which should have been validated.
2315 */
2316 const u32 sectorsize = btrfs_super_sectorsize(sb);
2317 u32 sys_array_size = btrfs_super_sys_array_size(sb);
2318
2319 if (unlikely(sys_array_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)) {
2320 btrfs_err(fs_info, "system chunk array too big %u > %u",
2321 sys_array_size, BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2322 return -EUCLEAN;
2323 }
2324
2325 while (cur < sys_array_size) {
2326 struct btrfs_disk_key *disk_key;
2327 struct btrfs_chunk *chunk;
2328 struct btrfs_key key;
2329 u64 type;
2330 u16 num_stripes;
2331 u32 len;
2332 int ret;
2333
2334 disk_key = (struct btrfs_disk_key *)(sb->sys_chunk_array + cur);
2335 len = sizeof(*disk_key);
2336
2337 if (unlikely(cur + len > sys_array_size))
2338 goto short_read;
2339 cur += len;
2340
2341 btrfs_disk_key_to_cpu(&key, disk_key);
2342 if (unlikely(key.type != BTRFS_CHUNK_ITEM_KEY)) {
2343 btrfs_err(fs_info,
2344 "unexpected item type %u in sys_array at offset %u",
2345 key.type, cur);
2346 return -EUCLEAN;
2347 }
2348 chunk = (struct btrfs_chunk *)(sb->sys_chunk_array + cur);
2349 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2350 if (unlikely(cur + btrfs_chunk_item_size(num_stripes) > sys_array_size))
2351 goto short_read;
2352 type = btrfs_stack_chunk_type(chunk);
2353 if (unlikely(!(type & BTRFS_BLOCK_GROUP_SYSTEM))) {
2354 btrfs_err(fs_info,
2355 "invalid chunk type %llu in sys_array at offset %u",
2356 type, cur);
2357 return -EUCLEAN;
2358 }
2359 ret = btrfs_check_chunk_valid(fs_info, NULL, chunk, key.offset,
2360 sectorsize);
2361 if (ret < 0)
2362 return ret;
2363 cur += btrfs_chunk_item_size(num_stripes);
2364 }
2365 return 0;
2366short_read:
2367 btrfs_err(fs_info,
2368 "super block sys chunk array short read, cur=%u sys_array_size=%u",
2369 cur, sys_array_size);
2370 return -EUCLEAN;
2371}
2372
2373/*
2374 * Real super block validation
2375 * NOTE: super csum type and incompat features will not be checked here.
2376 *
2377 * @sb: super block to check
2378 * @mirror_num: the super block number to check its bytenr:
2379 * 0 the primary (1st) sb
2380 * 1, 2 2nd and 3rd backup copy
2381 * -1 skip bytenr check
2382 */
2383int btrfs_validate_super(const struct btrfs_fs_info *fs_info,
2384 const struct btrfs_super_block *sb, int mirror_num)
2385{
2386 u64 nodesize = btrfs_super_nodesize(sb);
2387 u64 sectorsize = btrfs_super_sectorsize(sb);
2388 int ret = 0;
2389 const bool ignore_flags = btrfs_test_opt(fs_info, IGNORESUPERFLAGS);
2390
2391 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2392 btrfs_err(fs_info, "no valid FS found");
2393 ret = -EINVAL;
2394 }
2395 if ((btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP)) {
2396 if (!ignore_flags) {
2397 btrfs_err(fs_info,
2398 "unrecognized or unsupported super flag 0x%llx",
2399 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2400 ret = -EINVAL;
2401 } else {
2402 btrfs_info(fs_info,
2403 "unrecognized or unsupported super flags: 0x%llx, ignored",
2404 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2405 }
2406 }
2407 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2408 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2409 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2410 ret = -EINVAL;
2411 }
2412 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2413 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2414 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2415 ret = -EINVAL;
2416 }
2417 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2418 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2419 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2420 ret = -EINVAL;
2421 }
2422
2423 /*
2424 * Check sectorsize and nodesize first, other check will need it.
2425 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2426 */
2427 if (!is_power_of_2(sectorsize) || sectorsize < BTRFS_MIN_BLOCKSIZE ||
2428 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2429 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2430 ret = -EINVAL;
2431 }
2432
2433 if (!btrfs_supported_blocksize(sectorsize)) {
2434 btrfs_err(fs_info,
2435 "sectorsize %llu not yet supported for page size %lu",
2436 sectorsize, PAGE_SIZE);
2437 ret = -EINVAL;
2438 }
2439
2440 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2441 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2442 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2443 ret = -EINVAL;
2444 }
2445 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2446 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2447 le32_to_cpu(sb->__unused_leafsize), nodesize);
2448 ret = -EINVAL;
2449 }
2450
2451 /* Root alignment check */
2452 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2453 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2454 btrfs_super_root(sb));
2455 ret = -EINVAL;
2456 }
2457 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2458 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2459 btrfs_super_chunk_root(sb));
2460 ret = -EINVAL;
2461 }
2462 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2463 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2464 btrfs_super_log_root(sb));
2465 ret = -EINVAL;
2466 }
2467
2468 if (!fs_info->fs_devices->temp_fsid &&
2469 memcmp(fs_info->fs_devices->fsid, sb->fsid, BTRFS_FSID_SIZE) != 0) {
2470 btrfs_err(fs_info,
2471 "superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2472 sb->fsid, fs_info->fs_devices->fsid);
2473 ret = -EINVAL;
2474 }
2475
2476 if (memcmp(fs_info->fs_devices->metadata_uuid, btrfs_sb_fsid_ptr(sb),
2477 BTRFS_FSID_SIZE) != 0) {
2478 btrfs_err(fs_info,
2479"superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2480 btrfs_sb_fsid_ptr(sb), fs_info->fs_devices->metadata_uuid);
2481 ret = -EINVAL;
2482 }
2483
2484 if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2485 BTRFS_FSID_SIZE) != 0) {
2486 btrfs_err(fs_info,
2487 "dev_item UUID does not match metadata fsid: %pU != %pU",
2488 fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2489 ret = -EINVAL;
2490 }
2491
2492 /*
2493 * Artificial requirement for block-group-tree to force newer features
2494 * (free-space-tree, no-holes) so the test matrix is smaller.
2495 */
2496 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
2497 (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
2498 !btrfs_fs_incompat(fs_info, NO_HOLES))) {
2499 btrfs_err(fs_info,
2500 "block-group-tree feature requires free-space-tree and no-holes");
2501 ret = -EINVAL;
2502 }
2503
2504 /*
2505 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2506 * done later
2507 */
2508 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2509 btrfs_err(fs_info, "bytes_used is too small %llu",
2510 btrfs_super_bytes_used(sb));
2511 ret = -EINVAL;
2512 }
2513 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2514 btrfs_err(fs_info, "invalid stripesize %u",
2515 btrfs_super_stripesize(sb));
2516 ret = -EINVAL;
2517 }
2518 if (btrfs_super_num_devices(sb) > (1UL << 31))
2519 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2520 btrfs_super_num_devices(sb));
2521 if (btrfs_super_num_devices(sb) == 0) {
2522 btrfs_err(fs_info, "number of devices is 0");
2523 ret = -EINVAL;
2524 }
2525
2526 if (mirror_num >= 0 &&
2527 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2528 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2529 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2530 ret = -EINVAL;
2531 }
2532
2533 if (ret)
2534 return ret;
2535
2536 ret = validate_sys_chunk_array(fs_info, sb);
2537
2538 /*
2539 * Obvious sys_chunk_array corruptions, it must hold at least one key
2540 * and one chunk
2541 */
2542 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2543 btrfs_err(fs_info, "system chunk array too big %u > %u",
2544 btrfs_super_sys_array_size(sb),
2545 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2546 ret = -EINVAL;
2547 }
2548 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2549 + sizeof(struct btrfs_chunk)) {
2550 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2551 btrfs_super_sys_array_size(sb),
2552 sizeof(struct btrfs_disk_key)
2553 + sizeof(struct btrfs_chunk));
2554 ret = -EINVAL;
2555 }
2556
2557 /*
2558 * The generation is a global counter, we'll trust it more than the others
2559 * but it's still possible that it's the one that's wrong.
2560 */
2561 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2562 btrfs_warn(fs_info,
2563 "suspicious: generation < chunk_root_generation: %llu < %llu",
2564 btrfs_super_generation(sb),
2565 btrfs_super_chunk_root_generation(sb));
2566 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2567 && btrfs_super_cache_generation(sb) != (u64)-1)
2568 btrfs_warn(fs_info,
2569 "suspicious: generation < cache_generation: %llu < %llu",
2570 btrfs_super_generation(sb),
2571 btrfs_super_cache_generation(sb));
2572
2573 return ret;
2574}
2575
2576/*
2577 * Validation of super block at mount time.
2578 * Some checks already done early at mount time, like csum type and incompat
2579 * flags will be skipped.
2580 */
2581static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2582{
2583 return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2584}
2585
2586/*
2587 * Validation of super block at write time.
2588 * Some checks like bytenr check will be skipped as their values will be
2589 * overwritten soon.
2590 * Extra checks like csum type and incompat flags will be done here.
2591 */
2592static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2593 struct btrfs_super_block *sb)
2594{
2595 int ret;
2596
2597 ret = btrfs_validate_super(fs_info, sb, -1);
2598 if (ret < 0)
2599 goto out;
2600 if (unlikely(!btrfs_supported_super_csum(btrfs_super_csum_type(sb)))) {
2601 ret = -EUCLEAN;
2602 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2603 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2604 goto out;
2605 }
2606 if (unlikely(btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP)) {
2607 ret = -EUCLEAN;
2608 btrfs_err(fs_info,
2609 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2610 btrfs_super_incompat_flags(sb),
2611 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2612 goto out;
2613 }
2614out:
2615 if (ret < 0)
2616 btrfs_err(fs_info,
2617 "super block corruption detected before writing it to disk");
2618 return ret;
2619}
2620
2621static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2622{
2623 struct btrfs_tree_parent_check check = {
2624 .level = level,
2625 .transid = gen,
2626 .owner_root = btrfs_root_id(root)
2627 };
2628 int ret = 0;
2629
2630 root->node = read_tree_block(root->fs_info, bytenr, &check);
2631 if (IS_ERR(root->node)) {
2632 ret = PTR_ERR(root->node);
2633 root->node = NULL;
2634 return ret;
2635 }
2636 if (unlikely(!extent_buffer_uptodate(root->node))) {
2637 free_extent_buffer(root->node);
2638 root->node = NULL;
2639 return -EIO;
2640 }
2641
2642 btrfs_set_root_node(&root->root_item, root->node);
2643 root->commit_root = btrfs_root_node(root);
2644 btrfs_set_root_refs(&root->root_item, 1);
2645 return ret;
2646}
2647
2648static int load_important_roots(struct btrfs_fs_info *fs_info)
2649{
2650 struct btrfs_super_block *sb = fs_info->super_copy;
2651 u64 gen, bytenr;
2652 int level, ret;
2653
2654 bytenr = btrfs_super_root(sb);
2655 gen = btrfs_super_generation(sb);
2656 level = btrfs_super_root_level(sb);
2657 ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
2658 if (ret) {
2659 btrfs_warn(fs_info, "couldn't read tree root");
2660 return ret;
2661 }
2662 return 0;
2663}
2664
2665static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2666{
2667 int backup_index = find_newest_super_backup(fs_info);
2668 struct btrfs_super_block *sb = fs_info->super_copy;
2669 struct btrfs_root *tree_root = fs_info->tree_root;
2670 bool handle_error = false;
2671 int ret = 0;
2672 int i;
2673
2674 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2675 if (handle_error) {
2676 if (!IS_ERR(tree_root->node))
2677 free_extent_buffer(tree_root->node);
2678 tree_root->node = NULL;
2679
2680 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2681 break;
2682
2683 free_root_pointers(fs_info, 0);
2684
2685 /*
2686 * Don't use the log in recovery mode, it won't be
2687 * valid
2688 */
2689 btrfs_set_super_log_root(sb, 0);
2690
2691 btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2692 ret = read_backup_root(fs_info, i);
2693 backup_index = ret;
2694 if (ret < 0)
2695 return ret;
2696 }
2697
2698 ret = load_important_roots(fs_info);
2699 if (ret) {
2700 handle_error = true;
2701 continue;
2702 }
2703
2704 /*
2705 * No need to hold btrfs_root::objectid_mutex since the fs
2706 * hasn't been fully initialised and we are the only user
2707 */
2708 ret = btrfs_init_root_free_objectid(tree_root);
2709 if (ret < 0) {
2710 handle_error = true;
2711 continue;
2712 }
2713
2714 ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2715
2716 ret = btrfs_read_roots(fs_info);
2717 if (ret < 0) {
2718 handle_error = true;
2719 continue;
2720 }
2721
2722 /* All successful */
2723 fs_info->generation = btrfs_header_generation(tree_root->node);
2724 btrfs_set_last_trans_committed(fs_info, fs_info->generation);
2725 fs_info->last_reloc_trans = 0;
2726
2727 /* Always begin writing backup roots after the one being used */
2728 if (backup_index < 0) {
2729 fs_info->backup_root_index = 0;
2730 } else {
2731 fs_info->backup_root_index = backup_index + 1;
2732 fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
2733 }
2734 break;
2735 }
2736
2737 return ret;
2738}
2739
2740/*
2741 * Lockdep gets confused between our buffer_tree which requires IRQ locking because
2742 * we modify marks in the IRQ context, and our delayed inode xarray which doesn't
2743 * have these requirements. Use a class key so lockdep doesn't get them mixed up.
2744 */
2745static struct lock_class_key buffer_xa_class;
2746
2747void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2748{
2749 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2750
2751 /* Use the same flags as mapping->i_pages. */
2752 xa_init_flags(&fs_info->buffer_tree, XA_FLAGS_LOCK_IRQ | XA_FLAGS_ACCOUNT);
2753 lockdep_set_class(&fs_info->buffer_tree.xa_lock, &buffer_xa_class);
2754
2755 INIT_LIST_HEAD(&fs_info->trans_list);
2756 INIT_LIST_HEAD(&fs_info->dead_roots);
2757 INIT_LIST_HEAD(&fs_info->delayed_iputs);
2758 INIT_LIST_HEAD(&fs_info->delalloc_roots);
2759 INIT_LIST_HEAD(&fs_info->caching_block_groups);
2760 spin_lock_init(&fs_info->delalloc_root_lock);
2761 spin_lock_init(&fs_info->trans_lock);
2762 spin_lock_init(&fs_info->fs_roots_radix_lock);
2763 spin_lock_init(&fs_info->delayed_iput_lock);
2764 spin_lock_init(&fs_info->defrag_inodes_lock);
2765 spin_lock_init(&fs_info->super_lock);
2766 spin_lock_init(&fs_info->unused_bgs_lock);
2767 spin_lock_init(&fs_info->treelog_bg_lock);
2768 spin_lock_init(&fs_info->zone_active_bgs_lock);
2769 spin_lock_init(&fs_info->relocation_bg_lock);
2770 rwlock_init(&fs_info->tree_mod_log_lock);
2771 rwlock_init(&fs_info->global_root_lock);
2772 mutex_init(&fs_info->unused_bg_unpin_mutex);
2773 mutex_init(&fs_info->reclaim_bgs_lock);
2774 mutex_init(&fs_info->reloc_mutex);
2775 mutex_init(&fs_info->delalloc_root_mutex);
2776 mutex_init(&fs_info->zoned_meta_io_lock);
2777 mutex_init(&fs_info->zoned_data_reloc_io_lock);
2778 seqlock_init(&fs_info->profiles_lock);
2779
2780 btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
2781 btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
2782 btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
2783 btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
2784 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_prep,
2785 BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2786 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
2787 BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2788 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
2789 BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2790 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
2791 BTRFS_LOCKDEP_TRANS_COMPLETED);
2792
2793 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2794 INIT_LIST_HEAD(&fs_info->space_info);
2795 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2796 INIT_LIST_HEAD(&fs_info->unused_bgs);
2797 INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2798 INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2799#ifdef CONFIG_BTRFS_DEBUG
2800 INIT_LIST_HEAD(&fs_info->allocated_roots);
2801 INIT_LIST_HEAD(&fs_info->allocated_ebs);
2802 spin_lock_init(&fs_info->eb_leak_lock);
2803#endif
2804 fs_info->mapping_tree = RB_ROOT_CACHED;
2805 rwlock_init(&fs_info->mapping_tree_lock);
2806 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2807 BTRFS_BLOCK_RSV_GLOBAL);
2808 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2809 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2810 btrfs_init_block_rsv(&fs_info->treelog_rsv, BTRFS_BLOCK_RSV_TREELOG);
2811 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2812 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2813 BTRFS_BLOCK_RSV_DELOPS);
2814 btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2815 BTRFS_BLOCK_RSV_DELREFS);
2816
2817 atomic_set(&fs_info->async_delalloc_pages, 0);
2818 atomic_set(&fs_info->defrag_running, 0);
2819 atomic_set(&fs_info->nr_delayed_iputs, 0);
2820 atomic64_set(&fs_info->tree_mod_seq, 0);
2821 fs_info->global_root_tree = RB_ROOT;
2822 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2823 fs_info->metadata_ratio = 0;
2824 fs_info->defrag_inodes = RB_ROOT;
2825 atomic64_set(&fs_info->free_chunk_space, 0);
2826 fs_info->tree_mod_log = RB_ROOT;
2827 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2828 btrfs_init_ref_verify(fs_info);
2829
2830 fs_info->thread_pool_size = min_t(unsigned long,
2831 num_online_cpus() + 2, 8);
2832
2833 INIT_LIST_HEAD(&fs_info->ordered_roots);
2834 spin_lock_init(&fs_info->ordered_root_lock);
2835
2836 btrfs_init_scrub(fs_info);
2837 btrfs_init_balance(fs_info);
2838 btrfs_init_async_reclaim_work(fs_info);
2839 btrfs_init_extent_map_shrinker_work(fs_info);
2840
2841 rwlock_init(&fs_info->block_group_cache_lock);
2842 fs_info->block_group_cache_tree = RB_ROOT_CACHED;
2843
2844 btrfs_extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2845 IO_TREE_FS_EXCLUDED_EXTENTS);
2846
2847 mutex_init(&fs_info->ordered_operations_mutex);
2848 mutex_init(&fs_info->tree_log_mutex);
2849 mutex_init(&fs_info->chunk_mutex);
2850 mutex_init(&fs_info->transaction_kthread_mutex);
2851 mutex_init(&fs_info->cleaner_mutex);
2852 mutex_init(&fs_info->ro_block_group_mutex);
2853 init_rwsem(&fs_info->commit_root_sem);
2854 init_rwsem(&fs_info->cleanup_work_sem);
2855 init_rwsem(&fs_info->subvol_sem);
2856 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2857
2858 btrfs_init_dev_replace_locks(fs_info);
2859 btrfs_init_qgroup(fs_info);
2860 btrfs_discard_init(fs_info);
2861
2862 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2863 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2864
2865 init_waitqueue_head(&fs_info->transaction_throttle);
2866 init_waitqueue_head(&fs_info->transaction_wait);
2867 init_waitqueue_head(&fs_info->transaction_blocked_wait);
2868 init_waitqueue_head(&fs_info->async_submit_wait);
2869 init_waitqueue_head(&fs_info->delayed_iputs_wait);
2870
2871 /* Usable values until the real ones are cached from the superblock */
2872 fs_info->nodesize = 4096;
2873 fs_info->sectorsize = 4096;
2874 fs_info->sectorsize_bits = ilog2(4096);
2875 fs_info->stripesize = 4096;
2876
2877 /* Default compress algorithm when user does -o compress */
2878 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2879
2880 fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2881
2882 spin_lock_init(&fs_info->swapfile_pins_lock);
2883 fs_info->swapfile_pins = RB_ROOT;
2884
2885 fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
2886 INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
2887}
2888
2889static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
2890{
2891 int ret;
2892
2893 fs_info->sb = sb;
2894 /* Temporary fixed values for block size until we read the superblock. */
2895 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2896 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2897
2898 ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2899 if (ret)
2900 return ret;
2901
2902 ret = percpu_counter_init(&fs_info->evictable_extent_maps, 0, GFP_KERNEL);
2903 if (ret)
2904 return ret;
2905
2906 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2907 if (ret)
2908 return ret;
2909
2910 ret = percpu_counter_init(&fs_info->stats_read_blocks, 0, GFP_KERNEL);
2911 if (ret)
2912 return ret;
2913
2914 fs_info->dirty_metadata_batch = PAGE_SIZE *
2915 (1 + ilog2(nr_cpu_ids));
2916
2917 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2918 if (ret)
2919 return ret;
2920
2921 ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2922 GFP_KERNEL);
2923 if (ret)
2924 return ret;
2925
2926 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2927 GFP_KERNEL);
2928 if (!fs_info->delayed_root)
2929 return -ENOMEM;
2930 btrfs_init_delayed_root(fs_info->delayed_root);
2931
2932 if (sb_rdonly(sb))
2933 set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2934 if (btrfs_test_opt(fs_info, IGNOREMETACSUMS))
2935 set_bit(BTRFS_FS_STATE_SKIP_META_CSUMS, &fs_info->fs_state);
2936
2937 return btrfs_alloc_stripe_hash_table(fs_info);
2938}
2939
2940static int btrfs_uuid_rescan_kthread(void *data)
2941{
2942 struct btrfs_fs_info *fs_info = data;
2943 int ret;
2944
2945 /*
2946 * 1st step is to iterate through the existing UUID tree and
2947 * to delete all entries that contain outdated data.
2948 * 2nd step is to add all missing entries to the UUID tree.
2949 */
2950 ret = btrfs_uuid_tree_iterate(fs_info);
2951 if (ret < 0) {
2952 if (ret != -EINTR)
2953 btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2954 ret);
2955 up(&fs_info->uuid_tree_rescan_sem);
2956 return ret;
2957 }
2958 return btrfs_uuid_scan_kthread(data);
2959}
2960
2961static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
2962{
2963 struct task_struct *task;
2964
2965 down(&fs_info->uuid_tree_rescan_sem);
2966 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
2967 if (IS_ERR(task)) {
2968 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
2969 btrfs_warn(fs_info, "failed to start uuid_rescan task");
2970 up(&fs_info->uuid_tree_rescan_sem);
2971 return PTR_ERR(task);
2972 }
2973
2974 return 0;
2975}
2976
2977static int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
2978{
2979 u64 root_objectid = 0;
2980 struct btrfs_root *gang[8];
2981 int ret = 0;
2982
2983 while (1) {
2984 unsigned int found;
2985
2986 spin_lock(&fs_info->fs_roots_radix_lock);
2987 found = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2988 (void **)gang, root_objectid,
2989 ARRAY_SIZE(gang));
2990 if (!found) {
2991 spin_unlock(&fs_info->fs_roots_radix_lock);
2992 break;
2993 }
2994 root_objectid = btrfs_root_id(gang[found - 1]) + 1;
2995
2996 for (int i = 0; i < found; i++) {
2997 /* Avoid to grab roots in dead_roots. */
2998 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
2999 gang[i] = NULL;
3000 continue;
3001 }
3002 /* Grab all the search result for later use. */
3003 gang[i] = btrfs_grab_root(gang[i]);
3004 }
3005 spin_unlock(&fs_info->fs_roots_radix_lock);
3006
3007 for (int i = 0; i < found; i++) {
3008 if (!gang[i])
3009 continue;
3010 root_objectid = btrfs_root_id(gang[i]);
3011 /*
3012 * Continue to release the remaining roots after the first
3013 * error without cleanup and preserve the first error
3014 * for the return.
3015 */
3016 if (!ret)
3017 ret = btrfs_orphan_cleanup(gang[i]);
3018 btrfs_put_root(gang[i]);
3019 }
3020 if (ret)
3021 break;
3022
3023 root_objectid++;
3024 }
3025 return ret;
3026}
3027
3028/*
3029 * Mounting logic specific to read-write file systems. Shared by open_ctree
3030 * and btrfs_remount when remounting from read-only to read-write.
3031 */
3032int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
3033{
3034 int ret;
3035 const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
3036 bool rebuild_free_space_tree = false;
3037
3038 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3039 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3040 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
3041 btrfs_warn(fs_info,
3042 "'clear_cache' option is ignored with extent tree v2");
3043 else
3044 rebuild_free_space_tree = true;
3045 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3046 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3047 btrfs_warn(fs_info, "free space tree is invalid");
3048 rebuild_free_space_tree = true;
3049 }
3050
3051 if (rebuild_free_space_tree) {
3052 btrfs_info(fs_info, "rebuilding free space tree");
3053 ret = btrfs_rebuild_free_space_tree(fs_info);
3054 if (ret) {
3055 btrfs_warn(fs_info,
3056 "failed to rebuild free space tree: %d", ret);
3057 goto out;
3058 }
3059 }
3060
3061 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3062 !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
3063 btrfs_info(fs_info, "disabling free space tree");
3064 ret = btrfs_delete_free_space_tree(fs_info);
3065 if (ret) {
3066 btrfs_warn(fs_info,
3067 "failed to disable free space tree: %d", ret);
3068 goto out;
3069 }
3070 }
3071
3072 /*
3073 * btrfs_find_orphan_roots() is responsible for finding all the dead
3074 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3075 * them into the fs_info->fs_roots_radix tree. This must be done before
3076 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
3077 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
3078 * item before the root's tree is deleted - this means that if we unmount
3079 * or crash before the deletion completes, on the next mount we will not
3080 * delete what remains of the tree because the orphan item does not
3081 * exists anymore, which is what tells us we have a pending deletion.
3082 */
3083 ret = btrfs_find_orphan_roots(fs_info);
3084 if (ret)
3085 goto out;
3086
3087 ret = btrfs_cleanup_fs_roots(fs_info);
3088 if (ret)
3089 goto out;
3090
3091 down_read(&fs_info->cleanup_work_sem);
3092 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3093 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3094 up_read(&fs_info->cleanup_work_sem);
3095 goto out;
3096 }
3097 up_read(&fs_info->cleanup_work_sem);
3098
3099 mutex_lock(&fs_info->cleaner_mutex);
3100 ret = btrfs_recover_relocation(fs_info);
3101 mutex_unlock(&fs_info->cleaner_mutex);
3102 if (ret < 0) {
3103 btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
3104 goto out;
3105 }
3106
3107 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3108 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3109 btrfs_info(fs_info, "creating free space tree");
3110 ret = btrfs_create_free_space_tree(fs_info);
3111 if (ret) {
3112 btrfs_warn(fs_info,
3113 "failed to create free space tree: %d", ret);
3114 goto out;
3115 }
3116 }
3117
3118 if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
3119 ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
3120 if (ret)
3121 goto out;
3122 }
3123
3124 ret = btrfs_resume_balance_async(fs_info);
3125 if (ret)
3126 goto out;
3127
3128 ret = btrfs_resume_dev_replace_async(fs_info);
3129 if (ret) {
3130 btrfs_warn(fs_info, "failed to resume dev_replace");
3131 goto out;
3132 }
3133
3134 btrfs_qgroup_rescan_resume(fs_info);
3135
3136 if (!fs_info->uuid_root) {
3137 btrfs_info(fs_info, "creating UUID tree");
3138 ret = btrfs_create_uuid_tree(fs_info);
3139 if (ret) {
3140 btrfs_warn(fs_info,
3141 "failed to create the UUID tree %d", ret);
3142 goto out;
3143 }
3144 }
3145
3146out:
3147 return ret;
3148}
3149
3150/*
3151 * Do various sanity and dependency checks of different features.
3152 *
3153 * @is_rw_mount: If the mount is read-write.
3154 *
3155 * This is the place for less strict checks (like for subpage or artificial
3156 * feature dependencies).
3157 *
3158 * For strict checks or possible corruption detection, see
3159 * btrfs_validate_super().
3160 *
3161 * This should be called after btrfs_parse_options(), as some mount options
3162 * (space cache related) can modify on-disk format like free space tree and
3163 * screw up certain feature dependencies.
3164 */
3165int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3166{
3167 struct btrfs_super_block *disk_super = fs_info->super_copy;
3168 u64 incompat = btrfs_super_incompat_flags(disk_super);
3169 const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3170 const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3171
3172 if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3173 btrfs_err(fs_info,
3174 "cannot mount because of unknown incompat features (0x%llx)",
3175 incompat);
3176 return -EINVAL;
3177 }
3178
3179 /* Runtime limitation for mixed block groups. */
3180 if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3181 (fs_info->sectorsize != fs_info->nodesize)) {
3182 btrfs_err(fs_info,
3183"unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3184 fs_info->nodesize, fs_info->sectorsize);
3185 return -EINVAL;
3186 }
3187
3188 /* Mixed backref is an always-enabled feature. */
3189 incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3190
3191 /* Set compression related flags just in case. */
3192 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3193 incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3194 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3195 incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3196
3197 /*
3198 * An ancient flag, which should really be marked deprecated.
3199 * Such runtime limitation doesn't really need a incompat flag.
3200 */
3201 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3202 incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3203
3204 if (compat_ro_unsupp && is_rw_mount) {
3205 btrfs_err(fs_info,
3206 "cannot mount read-write because of unknown compat_ro features (0x%llx)",
3207 compat_ro);
3208 return -EINVAL;
3209 }
3210
3211 /*
3212 * We have unsupported RO compat features, although RO mounted, we
3213 * should not cause any metadata writes, including log replay.
3214 * Or we could screw up whatever the new feature requires.
3215 */
3216 if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3217 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3218 btrfs_err(fs_info,
3219"cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3220 compat_ro);
3221 return -EINVAL;
3222 }
3223
3224 /*
3225 * Artificial limitations for block group tree, to force
3226 * block-group-tree to rely on no-holes and free-space-tree.
3227 */
3228 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3229 (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3230 !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3231 btrfs_err(fs_info,
3232"block-group-tree feature requires no-holes and free-space-tree features");
3233 return -EINVAL;
3234 }
3235
3236 /*
3237 * Subpage/bs > ps runtime limitation on v1 cache.
3238 *
3239 * V1 space cache still has some hard coded PAGE_SIZE usage, while
3240 * we're already defaulting to v2 cache, no need to bother v1 as it's
3241 * going to be deprecated anyway.
3242 */
3243 if (fs_info->sectorsize != PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3244 btrfs_warn(fs_info,
3245 "v1 space cache is not supported for page size %lu with sectorsize %u",
3246 PAGE_SIZE, fs_info->sectorsize);
3247 return -EINVAL;
3248 }
3249
3250 /* This can be called by remount, we need to protect the super block. */
3251 spin_lock(&fs_info->super_lock);
3252 btrfs_set_super_incompat_flags(disk_super, incompat);
3253 spin_unlock(&fs_info->super_lock);
3254
3255 return 0;
3256}
3257
3258int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices)
3259{
3260 u32 sectorsize;
3261 u32 nodesize;
3262 u32 stripesize;
3263 u64 generation;
3264 u16 csum_type;
3265 struct btrfs_super_block *disk_super;
3266 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3267 struct btrfs_root *tree_root;
3268 struct btrfs_root *chunk_root;
3269 int ret;
3270 int level;
3271
3272 ret = init_mount_fs_info(fs_info, sb);
3273 if (ret)
3274 goto fail;
3275
3276 /* These need to be init'ed before we start creating inodes and such. */
3277 tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3278 GFP_KERNEL);
3279 fs_info->tree_root = tree_root;
3280 chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3281 GFP_KERNEL);
3282 fs_info->chunk_root = chunk_root;
3283 if (!tree_root || !chunk_root) {
3284 ret = -ENOMEM;
3285 goto fail;
3286 }
3287
3288 ret = btrfs_init_btree_inode(sb);
3289 if (ret)
3290 goto fail;
3291
3292 invalidate_bdev(fs_devices->latest_dev->bdev);
3293
3294 /*
3295 * Read super block and check the signature bytes only
3296 */
3297 disk_super = btrfs_read_disk_super(fs_devices->latest_dev->bdev, 0, false);
3298 if (IS_ERR(disk_super)) {
3299 ret = PTR_ERR(disk_super);
3300 goto fail_alloc;
3301 }
3302
3303 btrfs_info(fs_info, "first mount of filesystem %pU", disk_super->fsid);
3304 /*
3305 * Verify the type first, if that or the checksum value are
3306 * corrupted, we'll find out
3307 */
3308 csum_type = btrfs_super_csum_type(disk_super);
3309 if (!btrfs_supported_super_csum(csum_type)) {
3310 btrfs_err(fs_info, "unsupported checksum algorithm: %u",
3311 csum_type);
3312 ret = -EINVAL;
3313 btrfs_release_disk_super(disk_super);
3314 goto fail_alloc;
3315 }
3316
3317 fs_info->csum_size = btrfs_super_csum_size(disk_super);
3318
3319 ret = btrfs_init_csum_hash(fs_info, csum_type);
3320 if (ret) {
3321 btrfs_release_disk_super(disk_super);
3322 goto fail_alloc;
3323 }
3324
3325 /*
3326 * We want to check superblock checksum, the type is stored inside.
3327 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
3328 */
3329 if (btrfs_check_super_csum(fs_info, disk_super)) {
3330 btrfs_err(fs_info, "superblock checksum mismatch");
3331 ret = -EINVAL;
3332 btrfs_release_disk_super(disk_super);
3333 goto fail_alloc;
3334 }
3335
3336 /*
3337 * super_copy is zeroed at allocation time and we never touch the
3338 * following bytes up to INFO_SIZE, the checksum is calculated from
3339 * the whole block of INFO_SIZE
3340 */
3341 memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
3342 btrfs_release_disk_super(disk_super);
3343
3344 disk_super = fs_info->super_copy;
3345
3346 memcpy(fs_info->super_for_commit, fs_info->super_copy,
3347 sizeof(*fs_info->super_for_commit));
3348
3349 ret = btrfs_validate_mount_super(fs_info);
3350 if (ret) {
3351 btrfs_err(fs_info, "superblock contains fatal errors");
3352 ret = -EINVAL;
3353 goto fail_alloc;
3354 }
3355
3356 if (!btrfs_super_root(disk_super)) {
3357 btrfs_err(fs_info, "invalid superblock tree root bytenr");
3358 ret = -EINVAL;
3359 goto fail_alloc;
3360 }
3361
3362 /* check FS state, whether FS is broken. */
3363 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
3364 WRITE_ONCE(fs_info->fs_error, -EUCLEAN);
3365
3366 /* Set up fs_info before parsing mount options */
3367 nodesize = btrfs_super_nodesize(disk_super);
3368 sectorsize = btrfs_super_sectorsize(disk_super);
3369 stripesize = sectorsize;
3370 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3371 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3372
3373 fs_info->nodesize = nodesize;
3374 fs_info->nodesize_bits = ilog2(nodesize);
3375 fs_info->sectorsize = sectorsize;
3376 fs_info->sectorsize_bits = ilog2(sectorsize);
3377 fs_info->block_min_order = ilog2(round_up(sectorsize, PAGE_SIZE) >> PAGE_SHIFT);
3378 fs_info->block_max_order = ilog2((BITS_PER_LONG << fs_info->sectorsize_bits) >> PAGE_SHIFT);
3379 fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3380 fs_info->stripesize = stripesize;
3381 fs_info->fs_devices->fs_info = fs_info;
3382
3383 if (fs_info->sectorsize > PAGE_SIZE)
3384 btrfs_warn(fs_info,
3385 "support for block size %u with page size %lu is experimental, some features may be missing",
3386 fs_info->sectorsize, PAGE_SIZE);
3387 /*
3388 * Handle the space caching options appropriately now that we have the
3389 * super block loaded and validated.
3390 */
3391 btrfs_set_free_space_cache_settings(fs_info);
3392
3393 if (!btrfs_check_options(fs_info, &fs_info->mount_opt, sb->s_flags)) {
3394 ret = -EINVAL;
3395 goto fail_alloc;
3396 }
3397
3398 ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
3399 if (ret < 0)
3400 goto fail_alloc;
3401
3402 /*
3403 * At this point our mount options are validated, if we set ->max_inline
3404 * to something non-standard make sure we truncate it to sectorsize.
3405 */
3406 fs_info->max_inline = min_t(u64, fs_info->max_inline, fs_info->sectorsize);
3407
3408 ret = btrfs_alloc_compress_wsm(fs_info);
3409 if (ret)
3410 goto fail_sb_buffer;
3411 ret = btrfs_init_workqueues(fs_info);
3412 if (ret)
3413 goto fail_sb_buffer;
3414
3415 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
3416 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
3417
3418 /* Update the values for the current filesystem. */
3419 sb->s_blocksize = sectorsize;
3420 sb->s_blocksize_bits = blksize_bits(sectorsize);
3421 memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3422
3423 mutex_lock(&fs_info->chunk_mutex);
3424 ret = btrfs_read_sys_array(fs_info);
3425 mutex_unlock(&fs_info->chunk_mutex);
3426 if (ret) {
3427 btrfs_err(fs_info, "failed to read the system array: %d", ret);
3428 goto fail_sb_buffer;
3429 }
3430
3431 generation = btrfs_super_chunk_root_generation(disk_super);
3432 level = btrfs_super_chunk_root_level(disk_super);
3433 ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3434 generation, level);
3435 if (ret) {
3436 btrfs_err(fs_info, "failed to read chunk root");
3437 goto fail_tree_roots;
3438 }
3439
3440 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3441 offsetof(struct btrfs_header, chunk_tree_uuid),
3442 BTRFS_UUID_SIZE);
3443
3444 ret = btrfs_read_chunk_tree(fs_info);
3445 if (ret) {
3446 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3447 goto fail_tree_roots;
3448 }
3449
3450 /*
3451 * At this point we know all the devices that make this filesystem,
3452 * including the seed devices but we don't know yet if the replace
3453 * target is required. So free devices that are not part of this
3454 * filesystem but skip the replace target device which is checked
3455 * below in btrfs_init_dev_replace().
3456 */
3457 btrfs_free_extra_devids(fs_devices);
3458 if (unlikely(!fs_devices->latest_dev->bdev)) {
3459 btrfs_err(fs_info, "failed to read devices");
3460 ret = -EIO;
3461 goto fail_tree_roots;
3462 }
3463
3464 ret = init_tree_roots(fs_info);
3465 if (ret)
3466 goto fail_tree_roots;
3467
3468 /*
3469 * Get zone type information of zoned block devices. This will also
3470 * handle emulation of a zoned filesystem if a regular device has the
3471 * zoned incompat feature flag set.
3472 */
3473 ret = btrfs_get_dev_zone_info_all_devices(fs_info);
3474 if (ret) {
3475 btrfs_err(fs_info,
3476 "zoned: failed to read device zone info: %d", ret);
3477 goto fail_block_groups;
3478 }
3479
3480 /*
3481 * If we have a uuid root and we're not being told to rescan we need to
3482 * check the generation here so we can set the
3483 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit. Otherwise we could commit the
3484 * transaction during a balance or the log replay without updating the
3485 * uuid generation, and then if we crash we would rescan the uuid tree,
3486 * even though it was perfectly fine.
3487 */
3488 if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
3489 fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
3490 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3491
3492 ret = btrfs_verify_dev_extents(fs_info);
3493 if (ret) {
3494 btrfs_err(fs_info,
3495 "failed to verify dev extents against chunks: %d",
3496 ret);
3497 goto fail_block_groups;
3498 }
3499 ret = btrfs_recover_balance(fs_info);
3500 if (ret) {
3501 btrfs_err(fs_info, "failed to recover balance: %d", ret);
3502 goto fail_block_groups;
3503 }
3504
3505 ret = btrfs_init_dev_stats(fs_info);
3506 if (ret) {
3507 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3508 goto fail_block_groups;
3509 }
3510
3511 ret = btrfs_init_dev_replace(fs_info);
3512 if (ret) {
3513 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3514 goto fail_block_groups;
3515 }
3516
3517 ret = btrfs_check_zoned_mode(fs_info);
3518 if (ret) {
3519 btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3520 ret);
3521 goto fail_block_groups;
3522 }
3523
3524 ret = btrfs_sysfs_add_fsid(fs_devices);
3525 if (ret) {
3526 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3527 ret);
3528 goto fail_block_groups;
3529 }
3530
3531 ret = btrfs_sysfs_add_mounted(fs_info);
3532 if (ret) {
3533 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3534 goto fail_fsdev_sysfs;
3535 }
3536
3537 ret = btrfs_init_space_info(fs_info);
3538 if (ret) {
3539 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3540 goto fail_sysfs;
3541 }
3542
3543 ret = btrfs_read_block_groups(fs_info);
3544 if (ret) {
3545 btrfs_err(fs_info, "failed to read block groups: %d", ret);
3546 goto fail_sysfs;
3547 }
3548
3549 btrfs_zoned_reserve_data_reloc_bg(fs_info);
3550 btrfs_free_zone_cache(fs_info);
3551
3552 btrfs_check_active_zone_reservation(fs_info);
3553
3554 if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
3555 !btrfs_check_rw_degradable(fs_info, NULL)) {
3556 btrfs_warn(fs_info,
3557 "writable mount is not allowed due to too many missing devices");
3558 ret = -EINVAL;
3559 goto fail_sysfs;
3560 }
3561
3562 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3563 "btrfs-cleaner");
3564 if (IS_ERR(fs_info->cleaner_kthread)) {
3565 ret = PTR_ERR(fs_info->cleaner_kthread);
3566 goto fail_sysfs;
3567 }
3568
3569 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3570 tree_root,
3571 "btrfs-transaction");
3572 if (IS_ERR(fs_info->transaction_kthread)) {
3573 ret = PTR_ERR(fs_info->transaction_kthread);
3574 goto fail_cleaner;
3575 }
3576
3577 ret = btrfs_read_qgroup_config(fs_info);
3578 if (ret)
3579 goto fail_trans_kthread;
3580
3581 if (btrfs_build_ref_tree(fs_info))
3582 btrfs_err(fs_info, "couldn't build ref tree");
3583
3584 /* do not make disk changes in broken FS or nologreplay is given */
3585 if (btrfs_super_log_root(disk_super) != 0 &&
3586 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3587 btrfs_info(fs_info, "start tree-log replay");
3588 ret = btrfs_replay_log(fs_info, fs_devices);
3589 if (ret)
3590 goto fail_qgroup;
3591 }
3592
3593 fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
3594 if (IS_ERR(fs_info->fs_root)) {
3595 ret = PTR_ERR(fs_info->fs_root);
3596 btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3597 fs_info->fs_root = NULL;
3598 goto fail_qgroup;
3599 }
3600
3601 if (sb_rdonly(sb))
3602 return 0;
3603
3604 ret = btrfs_start_pre_rw_mount(fs_info);
3605 if (ret) {
3606 close_ctree(fs_info);
3607 return ret;
3608 }
3609 btrfs_discard_resume(fs_info);
3610
3611 if (fs_info->uuid_root &&
3612 (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3613 fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
3614 btrfs_info(fs_info, "checking UUID tree");
3615 ret = btrfs_check_uuid_tree(fs_info);
3616 if (ret) {
3617 btrfs_warn(fs_info,
3618 "failed to check the UUID tree: %d", ret);
3619 close_ctree(fs_info);
3620 return ret;
3621 }
3622 }
3623
3624 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3625
3626 /* Kick the cleaner thread so it'll start deleting snapshots. */
3627 if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3628 wake_up_process(fs_info->cleaner_kthread);
3629
3630 return 0;
3631
3632fail_qgroup:
3633 btrfs_free_qgroup_config(fs_info);
3634fail_trans_kthread:
3635 kthread_stop(fs_info->transaction_kthread);
3636 btrfs_cleanup_transaction(fs_info);
3637 btrfs_free_fs_roots(fs_info);
3638fail_cleaner:
3639 kthread_stop(fs_info->cleaner_kthread);
3640
3641 /*
3642 * make sure we're done with the btree inode before we stop our
3643 * kthreads
3644 */
3645 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3646
3647fail_sysfs:
3648 btrfs_sysfs_remove_mounted(fs_info);
3649
3650fail_fsdev_sysfs:
3651 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3652
3653fail_block_groups:
3654 btrfs_put_block_group_cache(fs_info);
3655
3656fail_tree_roots:
3657 if (fs_info->data_reloc_root)
3658 btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
3659 free_root_pointers(fs_info, true);
3660 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3661
3662fail_sb_buffer:
3663 btrfs_stop_all_workers(fs_info);
3664 btrfs_free_block_groups(fs_info);
3665fail_alloc:
3666 btrfs_mapping_tree_free(fs_info);
3667
3668 iput(fs_info->btree_inode);
3669fail:
3670 ASSERT(ret < 0);
3671 return ret;
3672}
3673ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3674
3675static void btrfs_end_super_write(struct bio *bio)
3676{
3677 struct btrfs_device *device = bio->bi_private;
3678 struct folio_iter fi;
3679
3680 bio_for_each_folio_all(fi, bio) {
3681 if (bio->bi_status) {
3682 btrfs_warn_rl(device->fs_info,
3683 "lost super block write due to IO error on %s (%d)",
3684 btrfs_dev_name(device),
3685 blk_status_to_errno(bio->bi_status));
3686 btrfs_dev_stat_inc_and_print(device,
3687 BTRFS_DEV_STAT_WRITE_ERRS);
3688 /* Ensure failure if the primary sb fails. */
3689 if (bio->bi_opf & REQ_FUA)
3690 atomic_add(BTRFS_SUPER_PRIMARY_WRITE_ERROR,
3691 &device->sb_write_errors);
3692 else
3693 atomic_inc(&device->sb_write_errors);
3694 }
3695 folio_unlock(fi.folio);
3696 folio_put(fi.folio);
3697 }
3698
3699 bio_put(bio);
3700}
3701
3702/*
3703 * Write superblock @sb to the @device. Do not wait for completion, all the
3704 * folios we use for writing are locked.
3705 *
3706 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3707 * the expected device size at commit time. Note that max_mirrors must be
3708 * same for write and wait phases.
3709 *
3710 * Return number of errors when folio is not found or submission fails.
3711 */
3712static int write_dev_supers(struct btrfs_device *device,
3713 struct btrfs_super_block *sb, int max_mirrors)
3714{
3715 struct btrfs_fs_info *fs_info = device->fs_info;
3716 struct address_space *mapping = device->bdev->bd_mapping;
3717 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3718 int i;
3719 int ret;
3720 u64 bytenr, bytenr_orig;
3721
3722 atomic_set(&device->sb_write_errors, 0);
3723
3724 if (max_mirrors == 0)
3725 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3726
3727 shash->tfm = fs_info->csum_shash;
3728
3729 for (i = 0; i < max_mirrors; i++) {
3730 struct folio *folio;
3731 struct bio *bio;
3732 struct btrfs_super_block *disk_super;
3733 size_t offset;
3734
3735 bytenr_orig = btrfs_sb_offset(i);
3736 ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
3737 if (ret == -ENOENT) {
3738 continue;
3739 } else if (ret < 0) {
3740 btrfs_err(device->fs_info,
3741 "couldn't get super block location for mirror %d error %d",
3742 i, ret);
3743 atomic_inc(&device->sb_write_errors);
3744 continue;
3745 }
3746 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3747 device->commit_total_bytes)
3748 break;
3749
3750 btrfs_set_super_bytenr(sb, bytenr_orig);
3751
3752 crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3753 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3754 sb->csum);
3755
3756 folio = __filemap_get_folio(mapping, bytenr >> PAGE_SHIFT,
3757 FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3758 GFP_NOFS);
3759 if (IS_ERR(folio)) {
3760 btrfs_err(device->fs_info,
3761 "couldn't get super block page for bytenr %llu error %ld",
3762 bytenr, PTR_ERR(folio));
3763 atomic_inc(&device->sb_write_errors);
3764 continue;
3765 }
3766
3767 offset = offset_in_folio(folio, bytenr);
3768 disk_super = folio_address(folio) + offset;
3769 memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3770
3771 /*
3772 * Directly use bios here instead of relying on the page cache
3773 * to do I/O, so we don't lose the ability to do integrity
3774 * checking.
3775 */
3776 bio = bio_alloc(device->bdev, 1,
3777 REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
3778 GFP_NOFS);
3779 bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3780 bio->bi_private = device;
3781 bio->bi_end_io = btrfs_end_super_write;
3782 bio_add_folio_nofail(bio, folio, BTRFS_SUPER_INFO_SIZE, offset);
3783
3784 /*
3785 * We FUA only the first super block. The others we allow to
3786 * go down lazy and there's a short window where the on-disk
3787 * copies might still contain the older version.
3788 */
3789 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3790 bio->bi_opf |= REQ_FUA;
3791 submit_bio(bio);
3792
3793 if (btrfs_advance_sb_log(device, i))
3794 atomic_inc(&device->sb_write_errors);
3795 }
3796 return atomic_read(&device->sb_write_errors) < i ? 0 : -1;
3797}
3798
3799/*
3800 * Wait for write completion of superblocks done by write_dev_supers,
3801 * @max_mirrors same for write and wait phases.
3802 *
3803 * Return -1 if primary super block write failed or when there were no super block
3804 * copies written. Otherwise 0.
3805 */
3806static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3807{
3808 int i;
3809 int errors = 0;
3810 bool primary_failed = false;
3811 int ret;
3812 u64 bytenr;
3813
3814 if (max_mirrors == 0)
3815 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3816
3817 for (i = 0; i < max_mirrors; i++) {
3818 struct folio *folio;
3819
3820 ret = btrfs_sb_log_location(device, i, READ, &bytenr);
3821 if (ret == -ENOENT) {
3822 break;
3823 } else if (ret < 0) {
3824 errors++;
3825 if (i == 0)
3826 primary_failed = true;
3827 continue;
3828 }
3829 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3830 device->commit_total_bytes)
3831 break;
3832
3833 folio = filemap_get_folio(device->bdev->bd_mapping,
3834 bytenr >> PAGE_SHIFT);
3835 /* If the folio has been removed, then we know it completed. */
3836 if (IS_ERR(folio))
3837 continue;
3838
3839 /* Folio will be unlocked once the write completes. */
3840 folio_wait_locked(folio);
3841 folio_put(folio);
3842 }
3843
3844 errors += atomic_read(&device->sb_write_errors);
3845 if (errors >= BTRFS_SUPER_PRIMARY_WRITE_ERROR)
3846 primary_failed = true;
3847 if (primary_failed) {
3848 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3849 device->devid);
3850 return -1;
3851 }
3852
3853 return errors < i ? 0 : -1;
3854}
3855
3856/*
3857 * endio for the write_dev_flush, this will wake anyone waiting
3858 * for the barrier when it is done
3859 */
3860static void btrfs_end_empty_barrier(struct bio *bio)
3861{
3862 bio_uninit(bio);
3863 complete(bio->bi_private);
3864}
3865
3866/*
3867 * Submit a flush request to the device if it supports it. Error handling is
3868 * done in the waiting counterpart.
3869 */
3870static void write_dev_flush(struct btrfs_device *device)
3871{
3872 struct bio *bio = &device->flush_bio;
3873
3874 device->last_flush_error = BLK_STS_OK;
3875
3876 bio_init(bio, device->bdev, NULL, 0,
3877 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
3878 bio->bi_end_io = btrfs_end_empty_barrier;
3879 init_completion(&device->flush_wait);
3880 bio->bi_private = &device->flush_wait;
3881 submit_bio(bio);
3882 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3883}
3884
3885/*
3886 * If the flush bio has been submitted by write_dev_flush, wait for it.
3887 * Return true for any error, and false otherwise.
3888 */
3889static bool wait_dev_flush(struct btrfs_device *device)
3890{
3891 struct bio *bio = &device->flush_bio;
3892
3893 if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3894 return false;
3895
3896 wait_for_completion_io(&device->flush_wait);
3897
3898 if (bio->bi_status) {
3899 device->last_flush_error = bio->bi_status;
3900 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
3901 return true;
3902 }
3903
3904 return false;
3905}
3906
3907/*
3908 * send an empty flush down to each device in parallel,
3909 * then wait for them
3910 */
3911static int barrier_all_devices(struct btrfs_fs_info *info)
3912{
3913 struct list_head *head;
3914 struct btrfs_device *dev;
3915 int errors_wait = 0;
3916
3917 lockdep_assert_held(&info->fs_devices->device_list_mutex);
3918 /* send down all the barriers */
3919 head = &info->fs_devices->devices;
3920 list_for_each_entry(dev, head, dev_list) {
3921 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3922 continue;
3923 if (!dev->bdev)
3924 continue;
3925 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3926 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3927 continue;
3928
3929 write_dev_flush(dev);
3930 }
3931
3932 /* wait for all the barriers */
3933 list_for_each_entry(dev, head, dev_list) {
3934 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3935 continue;
3936 if (!dev->bdev) {
3937 errors_wait++;
3938 continue;
3939 }
3940 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3941 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3942 continue;
3943
3944 if (wait_dev_flush(dev))
3945 errors_wait++;
3946 }
3947
3948 /*
3949 * Checks last_flush_error of disks in order to determine the device
3950 * state.
3951 */
3952 if (unlikely(errors_wait && !btrfs_check_rw_degradable(info, NULL)))
3953 return -EIO;
3954
3955 return 0;
3956}
3957
3958int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3959{
3960 int raid_type;
3961 int min_tolerated = INT_MAX;
3962
3963 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3964 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3965 min_tolerated = min_t(int, min_tolerated,
3966 btrfs_raid_array[BTRFS_RAID_SINGLE].
3967 tolerated_failures);
3968
3969 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3970 if (raid_type == BTRFS_RAID_SINGLE)
3971 continue;
3972 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3973 continue;
3974 min_tolerated = min_t(int, min_tolerated,
3975 btrfs_raid_array[raid_type].
3976 tolerated_failures);
3977 }
3978
3979 if (min_tolerated == INT_MAX) {
3980 btrfs_warn(NULL, "unknown raid flag: %llu", flags);
3981 min_tolerated = 0;
3982 }
3983
3984 return min_tolerated;
3985}
3986
3987int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3988{
3989 struct list_head *head;
3990 struct btrfs_device *dev;
3991 struct btrfs_super_block *sb;
3992 struct btrfs_dev_item *dev_item;
3993 int ret;
3994 int do_barriers;
3995 int max_errors;
3996 int total_errors = 0;
3997 u64 flags;
3998
3999 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4000
4001 /*
4002 * max_mirrors == 0 indicates we're from commit_transaction,
4003 * not from fsync where the tree roots in fs_info have not
4004 * been consistent on disk.
4005 */
4006 if (max_mirrors == 0)
4007 backup_super_roots(fs_info);
4008
4009 sb = fs_info->super_for_commit;
4010 dev_item = &sb->dev_item;
4011
4012 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4013 head = &fs_info->fs_devices->devices;
4014 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4015
4016 if (do_barriers) {
4017 ret = barrier_all_devices(fs_info);
4018 if (ret) {
4019 mutex_unlock(
4020 &fs_info->fs_devices->device_list_mutex);
4021 btrfs_handle_fs_error(fs_info, ret,
4022 "errors while submitting device barriers.");
4023 return ret;
4024 }
4025 }
4026
4027 list_for_each_entry(dev, head, dev_list) {
4028 if (!dev->bdev) {
4029 total_errors++;
4030 continue;
4031 }
4032 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4033 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4034 continue;
4035
4036 btrfs_set_stack_device_generation(dev_item, 0);
4037 btrfs_set_stack_device_type(dev_item, dev->type);
4038 btrfs_set_stack_device_id(dev_item, dev->devid);
4039 btrfs_set_stack_device_total_bytes(dev_item,
4040 dev->commit_total_bytes);
4041 btrfs_set_stack_device_bytes_used(dev_item,
4042 dev->commit_bytes_used);
4043 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4044 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4045 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4046 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
4047 memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
4048 BTRFS_FSID_SIZE);
4049
4050 flags = btrfs_super_flags(sb);
4051 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4052
4053 ret = btrfs_validate_write_super(fs_info, sb);
4054 if (unlikely(ret < 0)) {
4055 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4056 btrfs_handle_fs_error(fs_info, -EUCLEAN,
4057 "unexpected superblock corruption detected");
4058 return -EUCLEAN;
4059 }
4060
4061 ret = write_dev_supers(dev, sb, max_mirrors);
4062 if (ret)
4063 total_errors++;
4064 }
4065 if (unlikely(total_errors > max_errors)) {
4066 btrfs_err(fs_info, "%d errors while writing supers",
4067 total_errors);
4068 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4069
4070 /* FUA is masked off if unsupported and can't be the reason */
4071 btrfs_handle_fs_error(fs_info, -EIO,
4072 "%d errors while writing supers",
4073 total_errors);
4074 return -EIO;
4075 }
4076
4077 total_errors = 0;
4078 list_for_each_entry(dev, head, dev_list) {
4079 if (!dev->bdev)
4080 continue;
4081 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4082 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4083 continue;
4084
4085 ret = wait_dev_supers(dev, max_mirrors);
4086 if (ret)
4087 total_errors++;
4088 }
4089 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4090 if (unlikely(total_errors > max_errors)) {
4091 btrfs_handle_fs_error(fs_info, -EIO,
4092 "%d errors while writing supers",
4093 total_errors);
4094 return -EIO;
4095 }
4096 return 0;
4097}
4098
4099/* Drop a fs root from the radix tree and free it. */
4100void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4101 struct btrfs_root *root)
4102{
4103 bool drop_ref = false;
4104
4105 spin_lock(&fs_info->fs_roots_radix_lock);
4106 radix_tree_delete(&fs_info->fs_roots_radix,
4107 (unsigned long)btrfs_root_id(root));
4108 if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
4109 drop_ref = true;
4110 spin_unlock(&fs_info->fs_roots_radix_lock);
4111
4112 if (BTRFS_FS_ERROR(fs_info)) {
4113 ASSERT(root->log_root == NULL);
4114 if (root->reloc_root) {
4115 btrfs_put_root(root->reloc_root);
4116 root->reloc_root = NULL;
4117 }
4118 }
4119
4120 if (drop_ref)
4121 btrfs_put_root(root);
4122}
4123
4124int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4125{
4126 mutex_lock(&fs_info->cleaner_mutex);
4127 btrfs_run_delayed_iputs(fs_info);
4128 mutex_unlock(&fs_info->cleaner_mutex);
4129 wake_up_process(fs_info->cleaner_kthread);
4130
4131 /* wait until ongoing cleanup work done */
4132 down_write(&fs_info->cleanup_work_sem);
4133 up_write(&fs_info->cleanup_work_sem);
4134
4135 return btrfs_commit_current_transaction(fs_info->tree_root);
4136}
4137
4138static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
4139{
4140 struct btrfs_transaction *trans;
4141 struct btrfs_transaction *tmp;
4142 bool found = false;
4143
4144 /*
4145 * This function is only called at the very end of close_ctree(),
4146 * thus no other running transaction, no need to take trans_lock.
4147 */
4148 ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
4149 list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
4150 struct extent_state *cached = NULL;
4151 u64 dirty_bytes = 0;
4152 u64 cur = 0;
4153 u64 found_start;
4154 u64 found_end;
4155
4156 found = true;
4157 while (btrfs_find_first_extent_bit(&trans->dirty_pages, cur,
4158 &found_start, &found_end,
4159 EXTENT_DIRTY, &cached)) {
4160 dirty_bytes += found_end + 1 - found_start;
4161 cur = found_end + 1;
4162 }
4163 btrfs_warn(fs_info,
4164 "transaction %llu (with %llu dirty metadata bytes) is not committed",
4165 trans->transid, dirty_bytes);
4166 btrfs_cleanup_one_transaction(trans);
4167
4168 if (trans == fs_info->running_transaction)
4169 fs_info->running_transaction = NULL;
4170 list_del_init(&trans->list);
4171
4172 btrfs_put_transaction(trans);
4173 trace_btrfs_transaction_commit(fs_info);
4174 }
4175 ASSERT(!found);
4176}
4177
4178void __cold close_ctree(struct btrfs_fs_info *fs_info)
4179{
4180 int ret;
4181
4182 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4183
4184 /*
4185 * If we had UNFINISHED_DROPS we could still be processing them, so
4186 * clear that bit and wake up relocation so it can stop.
4187 * We must do this before stopping the block group reclaim task, because
4188 * at btrfs_relocate_block_group() we wait for this bit, and after the
4189 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
4190 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
4191 * return 1.
4192 */
4193 btrfs_wake_unfinished_drop(fs_info);
4194
4195 /*
4196 * We may have the reclaim task running and relocating a data block group,
4197 * in which case it may create delayed iputs. So stop it before we park
4198 * the cleaner kthread otherwise we can get new delayed iputs after
4199 * parking the cleaner, and that can make the async reclaim task to hang
4200 * if it's waiting for delayed iputs to complete, since the cleaner is
4201 * parked and can not run delayed iputs - this will make us hang when
4202 * trying to stop the async reclaim task.
4203 */
4204 cancel_work_sync(&fs_info->reclaim_bgs_work);
4205 /*
4206 * We don't want the cleaner to start new transactions, add more delayed
4207 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4208 * because that frees the task_struct, and the transaction kthread might
4209 * still try to wake up the cleaner.
4210 */
4211 kthread_park(fs_info->cleaner_kthread);
4212
4213 /* wait for the qgroup rescan worker to stop */
4214 btrfs_qgroup_wait_for_completion(fs_info, false);
4215
4216 /* wait for the uuid_scan task to finish */
4217 down(&fs_info->uuid_tree_rescan_sem);
4218 /* avoid complains from lockdep et al., set sem back to initial state */
4219 up(&fs_info->uuid_tree_rescan_sem);
4220
4221 /* pause restriper - we want to resume on mount */
4222 btrfs_pause_balance(fs_info);
4223
4224 btrfs_dev_replace_suspend_for_unmount(fs_info);
4225
4226 btrfs_scrub_cancel(fs_info);
4227
4228 /* wait for any defraggers to finish */
4229 wait_event(fs_info->transaction_wait,
4230 (atomic_read(&fs_info->defrag_running) == 0));
4231
4232 /* clear out the rbtree of defraggable inodes */
4233 btrfs_cleanup_defrag_inodes(fs_info);
4234
4235 /*
4236 * Handle the error fs first, as it will flush and wait for all ordered
4237 * extents. This will generate delayed iputs, thus we want to handle
4238 * it first.
4239 */
4240 if (unlikely(BTRFS_FS_ERROR(fs_info)))
4241 btrfs_error_commit_super(fs_info);
4242
4243 /*
4244 * Wait for any fixup workers to complete.
4245 * If we don't wait for them here and they are still running by the time
4246 * we call kthread_stop() against the cleaner kthread further below, we
4247 * get an use-after-free on the cleaner because the fixup worker adds an
4248 * inode to the list of delayed iputs and then attempts to wakeup the
4249 * cleaner kthread, which was already stopped and destroyed. We parked
4250 * already the cleaner, but below we run all pending delayed iputs.
4251 */
4252 btrfs_flush_workqueue(fs_info->fixup_workers);
4253 /*
4254 * Similar case here, we have to wait for delalloc workers before we
4255 * proceed below and stop the cleaner kthread, otherwise we trigger a
4256 * use-after-tree on the cleaner kthread task_struct when a delalloc
4257 * worker running submit_compressed_extents() adds a delayed iput, which
4258 * does a wake up on the cleaner kthread, which was already freed below
4259 * when we call kthread_stop().
4260 */
4261 btrfs_flush_workqueue(fs_info->delalloc_workers);
4262
4263 /*
4264 * We can have ordered extents getting their last reference dropped from
4265 * the fs_info->workers queue because for async writes for data bios we
4266 * queue a work for that queue, at btrfs_wq_submit_bio(), that runs
4267 * run_one_async_done() which calls btrfs_bio_end_io() in case the bio
4268 * has an error, and that later function can do the final
4269 * btrfs_put_ordered_extent() on the ordered extent attached to the bio,
4270 * which adds a delayed iput for the inode. So we must flush the queue
4271 * so that we don't have delayed iputs after committing the current
4272 * transaction below and stopping the cleaner and transaction kthreads.
4273 */
4274 btrfs_flush_workqueue(fs_info->workers);
4275
4276 /*
4277 * When finishing a compressed write bio we schedule a work queue item
4278 * to finish an ordered extent - end_bbio_compressed_write()
4279 * calls btrfs_finish_ordered_extent() which in turns does a call to
4280 * btrfs_queue_ordered_fn(), and that queues the ordered extent
4281 * completion either in the endio_write_workers work queue or in the
4282 * fs_info->endio_freespace_worker work queue. We flush those queues
4283 * below, so before we flush them we must flush this queue for the
4284 * workers of compressed writes.
4285 */
4286 flush_workqueue(fs_info->endio_workers);
4287
4288 /*
4289 * After we parked the cleaner kthread, ordered extents may have
4290 * completed and created new delayed iputs. If one of the async reclaim
4291 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4292 * can hang forever trying to stop it, because if a delayed iput is
4293 * added after it ran btrfs_run_delayed_iputs() and before it called
4294 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4295 * no one else to run iputs.
4296 *
4297 * So wait for all ongoing ordered extents to complete and then run
4298 * delayed iputs. This works because once we reach this point no one
4299 * can create new ordered extents, but delayed iputs can still be added
4300 * by a reclaim worker (see comments further below).
4301 *
4302 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4303 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4304 * but the delayed iput for the respective inode is made only when doing
4305 * the final btrfs_put_ordered_extent() (which must happen at
4306 * btrfs_finish_ordered_io() when we are unmounting).
4307 */
4308 btrfs_flush_workqueue(fs_info->endio_write_workers);
4309 /* Ordered extents for free space inodes. */
4310 btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4311 /*
4312 * Run delayed iputs in case an async reclaim worker is waiting for them
4313 * to be run as mentioned above.
4314 */
4315 btrfs_run_delayed_iputs(fs_info);
4316
4317 cancel_work_sync(&fs_info->async_reclaim_work);
4318 cancel_work_sync(&fs_info->async_data_reclaim_work);
4319 cancel_work_sync(&fs_info->preempt_reclaim_work);
4320 cancel_work_sync(&fs_info->em_shrinker_work);
4321
4322 /*
4323 * Run delayed iputs again because an async reclaim worker may have
4324 * added new ones if it was flushing delalloc:
4325 *
4326 * shrink_delalloc() -> btrfs_start_delalloc_roots() ->
4327 * start_delalloc_inodes() -> btrfs_add_delayed_iput()
4328 */
4329 btrfs_run_delayed_iputs(fs_info);
4330
4331 /* There should be no more workload to generate new delayed iputs. */
4332 set_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state);
4333
4334 /* Cancel or finish ongoing discard work */
4335 btrfs_discard_cleanup(fs_info);
4336
4337 if (!sb_rdonly(fs_info->sb)) {
4338 /*
4339 * The cleaner kthread is stopped, so do one final pass over
4340 * unused block groups.
4341 */
4342 btrfs_delete_unused_bgs(fs_info);
4343
4344 /*
4345 * There might be existing delayed inode workers still running
4346 * and holding an empty delayed inode item. We must wait for
4347 * them to complete first because they can create a transaction.
4348 * This happens when someone calls btrfs_balance_delayed_items()
4349 * and then a transaction commit runs the same delayed nodes
4350 * before any delayed worker has done something with the nodes.
4351 * We must wait for any worker here and not at transaction
4352 * commit time since that could cause a deadlock.
4353 * This is a very rare case.
4354 */
4355 btrfs_flush_workqueue(fs_info->delayed_workers);
4356
4357 ret = btrfs_commit_super(fs_info);
4358 if (ret)
4359 btrfs_err(fs_info, "commit super ret %d", ret);
4360 }
4361
4362 kthread_stop(fs_info->transaction_kthread);
4363 kthread_stop(fs_info->cleaner_kthread);
4364
4365 ASSERT(list_empty(&fs_info->delayed_iputs));
4366 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4367
4368 if (btrfs_check_quota_leak(fs_info)) {
4369 DEBUG_WARN("qgroup reserved space leaked");
4370 btrfs_err(fs_info, "qgroup reserved space leaked");
4371 }
4372
4373 btrfs_free_qgroup_config(fs_info);
4374 ASSERT(list_empty(&fs_info->delalloc_roots));
4375
4376 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
4377 btrfs_info(fs_info, "at unmount delalloc count %lld",
4378 percpu_counter_sum(&fs_info->delalloc_bytes));
4379 }
4380
4381 if (percpu_counter_sum(&fs_info->ordered_bytes))
4382 btrfs_info(fs_info, "at unmount dio bytes count %lld",
4383 percpu_counter_sum(&fs_info->ordered_bytes));
4384
4385 btrfs_sysfs_remove_mounted(fs_info);
4386 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
4387
4388 btrfs_put_block_group_cache(fs_info);
4389
4390 /*
4391 * we must make sure there is not any read request to
4392 * submit after we stopping all workers.
4393 */
4394 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
4395 btrfs_stop_all_workers(fs_info);
4396
4397 /* We shouldn't have any transaction open at this point */
4398 warn_about_uncommitted_trans(fs_info);
4399
4400 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
4401 free_root_pointers(fs_info, true);
4402 btrfs_free_fs_roots(fs_info);
4403
4404 /*
4405 * We must free the block groups after dropping the fs_roots as we could
4406 * have had an IO error and have left over tree log blocks that aren't
4407 * cleaned up until the fs roots are freed. This makes the block group
4408 * accounting appear to be wrong because there's pending reserved bytes,
4409 * so make sure we do the block group cleanup afterwards.
4410 */
4411 btrfs_free_block_groups(fs_info);
4412
4413 iput(fs_info->btree_inode);
4414
4415 btrfs_mapping_tree_free(fs_info);
4416}
4417
4418void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans,
4419 struct extent_buffer *buf)
4420{
4421 struct btrfs_fs_info *fs_info = buf->fs_info;
4422 u64 transid = btrfs_header_generation(buf);
4423
4424#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4425 /*
4426 * This is a fast path so only do this check if we have sanity tests
4427 * enabled. Normal people shouldn't be using unmapped buffers as dirty
4428 * outside of the sanity tests.
4429 */
4430 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
4431 return;
4432#endif
4433 /* This is an active transaction (its state < TRANS_STATE_UNBLOCKED). */
4434 ASSERT(trans->transid == fs_info->generation);
4435 btrfs_assert_tree_write_locked(buf);
4436 if (unlikely(transid != fs_info->generation)) {
4437 btrfs_abort_transaction(trans, -EUCLEAN);
4438 btrfs_crit(fs_info,
4439"dirty buffer transid mismatch, logical %llu found transid %llu running transid %llu",
4440 buf->start, transid, fs_info->generation);
4441 }
4442 set_extent_buffer_dirty(buf);
4443}
4444
4445static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4446 int flush_delayed)
4447{
4448 /*
4449 * looks as though older kernels can get into trouble with
4450 * this code, they end up stuck in balance_dirty_pages forever
4451 */
4452 int ret;
4453
4454 if (current->flags & PF_MEMALLOC)
4455 return;
4456
4457 if (flush_delayed)
4458 btrfs_balance_delayed_items(fs_info);
4459
4460 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4461 BTRFS_DIRTY_METADATA_THRESH,
4462 fs_info->dirty_metadata_batch);
4463 if (ret > 0) {
4464 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
4465 }
4466}
4467
4468void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
4469{
4470 __btrfs_btree_balance_dirty(fs_info, 1);
4471}
4472
4473void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4474{
4475 __btrfs_btree_balance_dirty(fs_info, 0);
4476}
4477
4478static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4479{
4480 /* cleanup FS via transaction */
4481 btrfs_cleanup_transaction(fs_info);
4482
4483 down_write(&fs_info->cleanup_work_sem);
4484 up_write(&fs_info->cleanup_work_sem);
4485}
4486
4487static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4488{
4489 struct btrfs_root *gang[8];
4490 u64 root_objectid = 0;
4491 int ret;
4492
4493 spin_lock(&fs_info->fs_roots_radix_lock);
4494 while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4495 (void **)gang, root_objectid,
4496 ARRAY_SIZE(gang))) != 0) {
4497 int i;
4498
4499 for (i = 0; i < ret; i++)
4500 gang[i] = btrfs_grab_root(gang[i]);
4501 spin_unlock(&fs_info->fs_roots_radix_lock);
4502
4503 for (i = 0; i < ret; i++) {
4504 if (!gang[i])
4505 continue;
4506 root_objectid = btrfs_root_id(gang[i]);
4507 btrfs_free_log(NULL, gang[i]);
4508 btrfs_put_root(gang[i]);
4509 }
4510 root_objectid++;
4511 spin_lock(&fs_info->fs_roots_radix_lock);
4512 }
4513 spin_unlock(&fs_info->fs_roots_radix_lock);
4514 btrfs_free_log_root_tree(NULL, fs_info);
4515}
4516
4517static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4518{
4519 struct btrfs_ordered_extent *ordered;
4520
4521 spin_lock(&root->ordered_extent_lock);
4522 /*
4523 * This will just short circuit the ordered completion stuff which will
4524 * make sure the ordered extent gets properly cleaned up.
4525 */
4526 list_for_each_entry(ordered, &root->ordered_extents,
4527 root_extent_list)
4528 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4529 spin_unlock(&root->ordered_extent_lock);
4530}
4531
4532static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4533{
4534 struct btrfs_root *root;
4535 LIST_HEAD(splice);
4536
4537 spin_lock(&fs_info->ordered_root_lock);
4538 list_splice_init(&fs_info->ordered_roots, &splice);
4539 while (!list_empty(&splice)) {
4540 root = list_first_entry(&splice, struct btrfs_root,
4541 ordered_root);
4542 list_move_tail(&root->ordered_root,
4543 &fs_info->ordered_roots);
4544
4545 spin_unlock(&fs_info->ordered_root_lock);
4546 btrfs_destroy_ordered_extents(root);
4547
4548 cond_resched();
4549 spin_lock(&fs_info->ordered_root_lock);
4550 }
4551 spin_unlock(&fs_info->ordered_root_lock);
4552
4553 /*
4554 * We need this here because if we've been flipped read-only we won't
4555 * get sync() from the umount, so we need to make sure any ordered
4556 * extents that haven't had their dirty pages IO start writeout yet
4557 * actually get run and error out properly.
4558 */
4559 btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
4560}
4561
4562static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4563{
4564 struct btrfs_inode *btrfs_inode;
4565 LIST_HEAD(splice);
4566
4567 spin_lock(&root->delalloc_lock);
4568 list_splice_init(&root->delalloc_inodes, &splice);
4569
4570 while (!list_empty(&splice)) {
4571 struct inode *inode = NULL;
4572 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4573 delalloc_inodes);
4574 btrfs_del_delalloc_inode(btrfs_inode);
4575 spin_unlock(&root->delalloc_lock);
4576
4577 /*
4578 * Make sure we get a live inode and that it'll not disappear
4579 * meanwhile.
4580 */
4581 inode = igrab(&btrfs_inode->vfs_inode);
4582 if (inode) {
4583 unsigned int nofs_flag;
4584
4585 nofs_flag = memalloc_nofs_save();
4586 invalidate_inode_pages2(inode->i_mapping);
4587 memalloc_nofs_restore(nofs_flag);
4588 iput(inode);
4589 }
4590 spin_lock(&root->delalloc_lock);
4591 }
4592 spin_unlock(&root->delalloc_lock);
4593}
4594
4595static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4596{
4597 struct btrfs_root *root;
4598 LIST_HEAD(splice);
4599
4600 spin_lock(&fs_info->delalloc_root_lock);
4601 list_splice_init(&fs_info->delalloc_roots, &splice);
4602 while (!list_empty(&splice)) {
4603 root = list_first_entry(&splice, struct btrfs_root,
4604 delalloc_root);
4605 root = btrfs_grab_root(root);
4606 BUG_ON(!root);
4607 spin_unlock(&fs_info->delalloc_root_lock);
4608
4609 btrfs_destroy_delalloc_inodes(root);
4610 btrfs_put_root(root);
4611
4612 spin_lock(&fs_info->delalloc_root_lock);
4613 }
4614 spin_unlock(&fs_info->delalloc_root_lock);
4615}
4616
4617static void btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4618 struct extent_io_tree *dirty_pages,
4619 int mark)
4620{
4621 struct extent_buffer *eb;
4622 u64 start = 0;
4623 u64 end;
4624
4625 while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
4626 mark, NULL)) {
4627 btrfs_clear_extent_bit(dirty_pages, start, end, mark, NULL);
4628 while (start <= end) {
4629 eb = find_extent_buffer(fs_info, start);
4630 start += fs_info->nodesize;
4631 if (!eb)
4632 continue;
4633
4634 btrfs_tree_lock(eb);
4635 wait_on_extent_buffer_writeback(eb);
4636 btrfs_clear_buffer_dirty(NULL, eb);
4637 btrfs_tree_unlock(eb);
4638
4639 free_extent_buffer_stale(eb);
4640 }
4641 }
4642}
4643
4644static void btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4645 struct extent_io_tree *unpin)
4646{
4647 u64 start;
4648 u64 end;
4649
4650 while (1) {
4651 struct extent_state *cached_state = NULL;
4652
4653 /*
4654 * The btrfs_finish_extent_commit() may get the same range as
4655 * ours between find_first_extent_bit and clear_extent_dirty.
4656 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4657 * the same extent range.
4658 */
4659 mutex_lock(&fs_info->unused_bg_unpin_mutex);
4660 if (!btrfs_find_first_extent_bit(unpin, 0, &start, &end,
4661 EXTENT_DIRTY, &cached_state)) {
4662 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4663 break;
4664 }
4665
4666 btrfs_clear_extent_dirty(unpin, start, end, &cached_state);
4667 btrfs_free_extent_state(cached_state);
4668 btrfs_error_unpin_extent_range(fs_info, start, end);
4669 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4670 cond_resched();
4671 }
4672}
4673
4674static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4675{
4676 struct inode *inode;
4677
4678 inode = cache->io_ctl.inode;
4679 if (inode) {
4680 unsigned int nofs_flag;
4681
4682 nofs_flag = memalloc_nofs_save();
4683 invalidate_inode_pages2(inode->i_mapping);
4684 memalloc_nofs_restore(nofs_flag);
4685
4686 BTRFS_I(inode)->generation = 0;
4687 cache->io_ctl.inode = NULL;
4688 iput(inode);
4689 }
4690 ASSERT(cache->io_ctl.pages == NULL);
4691 btrfs_put_block_group(cache);
4692}
4693
4694void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
4695 struct btrfs_fs_info *fs_info)
4696{
4697 struct btrfs_block_group *cache;
4698
4699 spin_lock(&cur_trans->dirty_bgs_lock);
4700 while (!list_empty(&cur_trans->dirty_bgs)) {
4701 cache = list_first_entry(&cur_trans->dirty_bgs,
4702 struct btrfs_block_group,
4703 dirty_list);
4704
4705 if (!list_empty(&cache->io_list)) {
4706 spin_unlock(&cur_trans->dirty_bgs_lock);
4707 list_del_init(&cache->io_list);
4708 btrfs_cleanup_bg_io(cache);
4709 spin_lock(&cur_trans->dirty_bgs_lock);
4710 }
4711
4712 list_del_init(&cache->dirty_list);
4713 spin_lock(&cache->lock);
4714 cache->disk_cache_state = BTRFS_DC_ERROR;
4715 spin_unlock(&cache->lock);
4716
4717 spin_unlock(&cur_trans->dirty_bgs_lock);
4718 btrfs_put_block_group(cache);
4719 btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
4720 spin_lock(&cur_trans->dirty_bgs_lock);
4721 }
4722 spin_unlock(&cur_trans->dirty_bgs_lock);
4723
4724 /*
4725 * Refer to the definition of io_bgs member for details why it's safe
4726 * to use it without any locking
4727 */
4728 while (!list_empty(&cur_trans->io_bgs)) {
4729 cache = list_first_entry(&cur_trans->io_bgs,
4730 struct btrfs_block_group,
4731 io_list);
4732
4733 list_del_init(&cache->io_list);
4734 spin_lock(&cache->lock);
4735 cache->disk_cache_state = BTRFS_DC_ERROR;
4736 spin_unlock(&cache->lock);
4737 btrfs_cleanup_bg_io(cache);
4738 }
4739}
4740
4741static void btrfs_free_all_qgroup_pertrans(struct btrfs_fs_info *fs_info)
4742{
4743 struct btrfs_root *gang[8];
4744 int i;
4745 int ret;
4746
4747 spin_lock(&fs_info->fs_roots_radix_lock);
4748 while (1) {
4749 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
4750 (void **)gang, 0,
4751 ARRAY_SIZE(gang),
4752 BTRFS_ROOT_TRANS_TAG);
4753 if (ret == 0)
4754 break;
4755 for (i = 0; i < ret; i++) {
4756 struct btrfs_root *root = gang[i];
4757
4758 btrfs_qgroup_free_meta_all_pertrans(root);
4759 radix_tree_tag_clear(&fs_info->fs_roots_radix,
4760 (unsigned long)btrfs_root_id(root),
4761 BTRFS_ROOT_TRANS_TAG);
4762 }
4763 }
4764 spin_unlock(&fs_info->fs_roots_radix_lock);
4765}
4766
4767void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans)
4768{
4769 struct btrfs_fs_info *fs_info = cur_trans->fs_info;
4770 struct btrfs_device *dev, *tmp;
4771
4772 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4773 ASSERT(list_empty(&cur_trans->dirty_bgs));
4774 ASSERT(list_empty(&cur_trans->io_bgs));
4775
4776 list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4777 post_commit_list) {
4778 list_del_init(&dev->post_commit_list);
4779 }
4780
4781 btrfs_destroy_delayed_refs(cur_trans);
4782
4783 cur_trans->state = TRANS_STATE_COMMIT_START;
4784 wake_up(&fs_info->transaction_blocked_wait);
4785
4786 cur_trans->state = TRANS_STATE_UNBLOCKED;
4787 wake_up(&fs_info->transaction_wait);
4788
4789 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
4790 EXTENT_DIRTY);
4791 btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
4792
4793 cur_trans->state =TRANS_STATE_COMPLETED;
4794 wake_up(&cur_trans->commit_wait);
4795}
4796
4797static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4798{
4799 struct btrfs_transaction *t;
4800
4801 mutex_lock(&fs_info->transaction_kthread_mutex);
4802
4803 spin_lock(&fs_info->trans_lock);
4804 while (!list_empty(&fs_info->trans_list)) {
4805 t = list_first_entry(&fs_info->trans_list,
4806 struct btrfs_transaction, list);
4807 if (t->state >= TRANS_STATE_COMMIT_PREP) {
4808 refcount_inc(&t->use_count);
4809 spin_unlock(&fs_info->trans_lock);
4810 btrfs_wait_for_commit(fs_info, t->transid);
4811 btrfs_put_transaction(t);
4812 spin_lock(&fs_info->trans_lock);
4813 continue;
4814 }
4815 if (t == fs_info->running_transaction) {
4816 t->state = TRANS_STATE_COMMIT_DOING;
4817 spin_unlock(&fs_info->trans_lock);
4818 /*
4819 * We wait for 0 num_writers since we don't hold a trans
4820 * handle open currently for this transaction.
4821 */
4822 wait_event(t->writer_wait,
4823 atomic_read(&t->num_writers) == 0);
4824 } else {
4825 spin_unlock(&fs_info->trans_lock);
4826 }
4827 btrfs_cleanup_one_transaction(t);
4828
4829 spin_lock(&fs_info->trans_lock);
4830 if (t == fs_info->running_transaction)
4831 fs_info->running_transaction = NULL;
4832 list_del_init(&t->list);
4833 spin_unlock(&fs_info->trans_lock);
4834
4835 btrfs_put_transaction(t);
4836 trace_btrfs_transaction_commit(fs_info);
4837 spin_lock(&fs_info->trans_lock);
4838 }
4839 spin_unlock(&fs_info->trans_lock);
4840 btrfs_destroy_all_ordered_extents(fs_info);
4841 btrfs_destroy_delayed_inodes(fs_info);
4842 btrfs_assert_delayed_root_empty(fs_info);
4843 btrfs_destroy_all_delalloc_inodes(fs_info);
4844 btrfs_drop_all_logs(fs_info);
4845 btrfs_free_all_qgroup_pertrans(fs_info);
4846 mutex_unlock(&fs_info->transaction_kthread_mutex);
4847
4848 return 0;
4849}
4850
4851int btrfs_init_root_free_objectid(struct btrfs_root *root)
4852{
4853 BTRFS_PATH_AUTO_FREE(path);
4854 int ret;
4855 struct extent_buffer *l;
4856 struct btrfs_key search_key;
4857 struct btrfs_key found_key;
4858 int slot;
4859
4860 path = btrfs_alloc_path();
4861 if (!path)
4862 return -ENOMEM;
4863
4864 search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4865 search_key.type = -1;
4866 search_key.offset = (u64)-1;
4867 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4868 if (ret < 0)
4869 return ret;
4870 if (unlikely(ret == 0)) {
4871 /*
4872 * Key with offset -1 found, there would have to exist a root
4873 * with such id, but this is out of valid range.
4874 */
4875 return -EUCLEAN;
4876 }
4877 if (path->slots[0] > 0) {
4878 slot = path->slots[0] - 1;
4879 l = path->nodes[0];
4880 btrfs_item_key_to_cpu(l, &found_key, slot);
4881 root->free_objectid = max_t(u64, found_key.objectid + 1,
4882 BTRFS_FIRST_FREE_OBJECTID);
4883 } else {
4884 root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4885 }
4886
4887 return 0;
4888}
4889
4890int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4891{
4892 int ret;
4893 mutex_lock(&root->objectid_mutex);
4894
4895 if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4896 btrfs_warn(root->fs_info,
4897 "the objectid of root %llu reaches its highest value",
4898 btrfs_root_id(root));
4899 ret = -ENOSPC;
4900 goto out;
4901 }
4902
4903 *objectid = root->free_objectid++;
4904 ret = 0;
4905out:
4906 mutex_unlock(&root->objectid_mutex);
4907 return ret;
4908}