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