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