1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #pragma once
6 
7 #include <fbl/macros.h>
8 #include <fbl/unique_ptr.h>
9 #include <fs/block-txn.h>
10 
11 #ifdef __Fuchsia__
12 #include <lib/fzl/owned-vmo-mapper.h>
13 #include <lib/zx/vmo.h>
14 #endif
15 
16 #include <minfs/format.h>
17 #include <minfs/fsck.h>
18 #include <minfs/block-txn.h>
19 
20 namespace minfs {
21 
22 // SuperblockManager contains all filesystem-global metadata.
23 //
24 // It also contains mechanisms for updating this information
25 // on persistent storage. Although these fields may be
26 // updated from multiple threads (and |Write| may be invoked
27 // to push a snapshot of the superblock to persistent storage),
28 // caution should be taken to avoid Writing a snapshot of the
29 // superblock to disk while another thread has only partially
30 // updated the superblock.
31 class SuperblockManager {
32 public:
33     SuperblockManager() = delete;
34     ~SuperblockManager();
35     DISALLOW_COPY_ASSIGN_AND_MOVE(SuperblockManager);
36 
37     static zx_status_t Create(Bcache* bc, const Superblock* info,
38                               fbl::unique_ptr<SuperblockManager>* out);
39 
Info()40     const Superblock& Info() const {
41 #ifdef __Fuchsia__
42         return *reinterpret_cast<const Superblock*>(mapping_.start());
43 #else
44         return *reinterpret_cast<const Superblock*>(&info_blk_[0]);
45 #endif
46     }
47 
48     // Acquire a pointer to the superblock, such that any
49     // modifications will be carried out to persistent storage
50     // the next time "Write" is invoked.
MutableInfo()51     Superblock* MutableInfo() {
52 #ifdef __Fuchsia__
53         return reinterpret_cast<Superblock*>(mapping_.start());
54 #else
55         return reinterpret_cast<Superblock*>(&info_blk_[0]);
56 #endif
57     }
58 
59     // Write the superblock back to persistent storage.
60     void Write(WriteTxn* txn);
61 
62 private:
63 #ifdef __Fuchsia__
64     SuperblockManager(const Superblock* info, fzl::OwnedVmoMapper mapper);
65 #else
66     SuperblockManager(const Superblock* info);
67 #endif
68 
69 #ifdef __Fuchsia__
70     fzl::OwnedVmoMapper mapping_;
71 #else
72     uint8_t info_blk_[kMinfsBlockSize];
73 #endif
74 };
75 
76 } // namespace minfs
77