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