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