~aleteoryx/muditaos

ref: 90117445f1372a9d302c5cb226510cb39c6dba21 muditaos/module-vfs/include/user/purefs/fs/filesystem.hpp -rw-r--r-- 11.7 KiB
90117445 — Przemyslaw Brudny Merge remote-tracking branch 'origin/stable' 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once
#include <string>
#include <memory>
#include <list>
#include <array>
#include <map>
#include <functional>
#include <ctime>
#include <unordered_set>
#include <purefs/fs/handle_mapper.hpp>
#include <purefs/fs/file_handle.hpp>
#include <purefs/fs/directory_handle.hpp>
#include <purefs/fs/mount_point.hpp>
#include <purefs/fs/mount_flags.hpp>
#include <purefs/fs/fsnotify.hpp>
#include <type_traits>

struct statvfs;
struct stat;

namespace purefs::blkdev
{
    class disk_manager;
}

namespace cpp_freertos
{
    class MutexRecursive;
}

namespace sys
{
    class Service;
}

namespace purefs::fs
{
    /** This is the filesystem class layer
     * All methods can be called from the user thread
     * but generally those functions are for internal use for
     * example for newlib or glibc syscalls
     */
    class filesystem_operations;
    namespace internal
    {
        class directory_handle;
        class notifier;
    }
    class filesystem
    {
        static constexpr auto path_separator = '/';
        /** NOTE: Current implementation doesn't allow to open
         * device and return fd. In the next release it will be fixed
         * so default stdin,stdout,stderr will be registered so this
         * first fd will not be longer needed.
         */
        static constexpr auto first_file_descriptor = 3;

      public:
        using fsdir                    = std::shared_ptr<internal::directory_handle>;
        using fsfile                         = std::shared_ptr<internal::file_handle>;
        explicit filesystem(std::shared_ptr<blkdev::disk_manager> diskmm);
        ~filesystem();
        filesystem(const filesystem &) = delete;
        auto operator=(const filesystem &) = delete;
        /** Utility API */
        /** Register filesystem driver
         * @param[in] fsname Unique filesystem name for example fat
         * @param[in] fops Filesystem operation structure
         * @return zero on sucess otherwise error
         */
        template <typename T> auto register_filesystem(std::string_view fsname, std::shared_ptr<T> fops) -> int
        {
            if (!fops || !std::is_convertible_v<T *, filesystem_operations *>) {
                return -EINVAL;
            }
            return register_filesystem(fsname, std::shared_ptr<filesystem_operations>(fops));
        }
        auto register_filesystem(std::string_view fsname, std::shared_ptr<filesystem_operations> fops) -> int;
        /** Unregister filesystem driver
         * @param[in] fsname Unique filesystem name for example fat
         * @return zero on success otherwise error
         **/
        auto unregister_filesystem(std::string_view fsname) -> int;

        /** Mount filesystem to the the specified mount point
         * see man(2) mount
         * @param[in] dev_or_part Device or partition for mount
         * @param[in] target Target path where the fs will be mounted
         * @param[in] flags  Mount flags
         * @param[in] data   Filesystem specific configuration
         * @return zero on success otherwise error
         */
        auto mount(std::string_view dev_or_part,
                   std::string_view target,
                   std::string_view fs_type,
                   unsigned flags   = 0,
                   const void *data = nullptr) -> int;
        /** Unmont filesystem from selected mount point
         * @param[in] mount_point Mount point where the fs is mounted
         * @return zero on success otherwise error
         */
        auto umount(std::string_view mount_point) -> int;
        /** Return actually mounted filesystem list
         * @param[out] mountpoints List of mount points
         * @return zero on success otherwise error
         */
        auto read_mountpoints(std::list<std::string> &mountpoints) const -> int;
        /** Get actual filesystem statistics *  @see man statvfs
         * @param[in] path Pathname of any file within the mounted filesystem
         * @param[out] stat Pointer to a statvfs structure
         * @return zero on success otherwise error
         */
        auto stat_vfs(std::string_view path, struct statvfs &stat) const noexcept -> int;
        /** Standard file access API */
        auto open(std::string_view path, int flags, int mode) noexcept -> int;
        auto close(int fd) noexcept -> int;
        auto write(int fd, const char *ptr, size_t len) noexcept -> ssize_t;
        auto read(int fd, char *ptr, size_t len) noexcept -> ssize_t;
        auto seek(int fd, off_t pos, int dir) noexcept -> off_t;
        auto fstat(int fd, struct stat &st) noexcept -> int;
        auto stat(std::string_view file, struct stat &st) noexcept -> int;
        auto link(std::string_view existing, std::string_view newlink) noexcept -> int;
        auto symlink(std::string_view existing, std::string_view newlink) noexcept -> int;
        auto unlink(std::string_view name) noexcept -> int;
        auto rename(std::string_view oldname, std::string_view newname) noexcept -> int;
        auto mkdir(std::string_view path, int mode) noexcept -> int;
        auto rmdir(std::string_view path) noexcept -> int;

        /** Directory support API */
        auto diropen(std::string_view path) noexcept -> fsdir;
        auto dirreset(fsdir) noexcept -> int;
        auto dirnext(fsdir dirstate, std::string &filename, struct stat &filestat) noexcept -> int;
        auto dirclose(fsdir dirstate) noexcept -> int;

        /** Other fops API */
        auto ftruncate(int fd, off_t len) noexcept -> int;
        auto fsync(int fd) noexcept -> int;
        auto ioctl(std::string_view path, int cmd, void *arg) noexcept -> int;
        auto utimens(std::string_view path, std::array<timespec, 2> &tv) noexcept -> int;
        auto flock(int fd, int cmd) noexcept -> int;
        auto isatty(int fd) noexcept -> int;

        auto chmod(std::string_view path, mode_t mode) noexcept -> int;
        auto fchmod(int fd, mode_t mode) noexcept -> int;

        auto getcwd() noexcept -> std::string_view;
        auto chdir(std::string_view name) noexcept -> int;

        /** Inotify API */
        [[nodiscard]] auto inotify_create(std::shared_ptr<sys::Service> svc) -> std::shared_ptr<inotify>;

      private:
        /** Unregister filesystem driver
         * @param[in] fsname Unique filesystem name for example fat
         * @return zero on success otherwise error
         **/
        /** Find the mount point object matching to the mount point path
         * @param[in] path Absolute input path
         * @return mount point object and the matching shortest path
         */
        auto find_mount_point(std::string_view path) const noexcept
            -> std::tuple<std::shared_ptr<internal::mount_point>, size_t>;
        /** Return absolute path from the relative path
         * @param[in] path Unormalized path
         * @return Full Normalized path
         */
        static auto absolute_path(std::string_view path) noexcept -> std::string;
        /** Normalize full path
         * @param[in] path Unnormalized full path
         * @param[out] Normalized path
         */
        static auto normalize_path(std::string_view path) noexcept -> std::string;
        /** Add handle to file descriptor
         */
        auto add_filehandle(fsfile file) noexcept -> int;
        auto remove_filehandle(int fds) noexcept -> fsfile;
        auto find_filehandle(int fds) const noexcept -> fsfile;
        auto autodetect_filesystem_type(std::string_view dev_or_part) const noexcept -> std::string;

        enum class iaccess : bool
        {
            ro, //! Syscall is RO
            rw  //! Syscall is RW
        };
        template <class Base, class T, typename... Args>
        inline auto invoke_fops(T Base::*method, int fds, Args &&... args)
            -> decltype((static_cast<Base *>(nullptr)->*method)(0, std::forward<Args>(args)...))
        {
            auto fil = find_filehandle(fds);
            if (!fil) {
                return -EBADF;
            }
            else {
                auto mp = fil->mntpoint();
                if (!mp) {
                    return -ENOENT;
                }
                auto fsops = mp->fs_ops();
                if (!fsops) {
                    return -EIO;
                }
                else {
                    return (fsops.get()->*method)(fil, std::forward<Args>(args)...);
                }
            }
        }

        template <class Base, class T, typename... Args>
        inline auto invoke_fops(iaccess acc, T Base::*method, std::string_view path, Args &&... args) const
            -> decltype((static_cast<Base *>(nullptr)->*method)(nullptr, {}, std::forward<Args>(args)...))
        {
            if (path.empty()) {
                return -ENOENT;
            }
            const auto abspath     = absolute_path(path);
            auto [mountp, pathpos] = find_mount_point(abspath);
            if (!mountp) {
                return -ENOENT;
            }
            if (acc == iaccess::rw && mountp->is_ro()) {
                return -EACCES;
            }
            auto fsops = mountp->fs_ops();
            if (fsops)
                return (fsops.get()->*method)(mountp, abspath, std::forward<Args>(args)...);
            else
                return -EIO;
        }

        template <class Base, class T, typename... Args>
        inline auto invoke_fops_same_mp(T Base::*method,
                                        std::string_view path,
                                        std::string_view path2,
                                        Args &&... args) const
            -> decltype((static_cast<Base *>(nullptr)->*method)(nullptr, {}, {}, std::forward<Args>(args)...))
        {
            if (path.empty() || path2.empty()) {
                return -ENOENT;
            }
            const auto abspath     = absolute_path(path);
            const auto abspath2    = absolute_path(path2);
            auto [mountp, pathpos] = find_mount_point(abspath);
            if (!mountp) {
                return -ENOENT;
            }
            if (mountp->is_ro()) {
                return -EACCES;
            }
            if (path.compare(0, pathpos, path2, 0, pathpos) != 0) {
                // Mount points are not the same
                return -EXDEV;
            }
            auto fsops = mountp->fs_ops();
            if (fsops)
                return (fsops.get()->*method)(mountp, abspath, abspath2, std::forward<Args>(args)...);
            else
                return -EIO;
        }
        template <class Base, class T, typename... Args>
        inline auto invoke_fops(T Base::*method, fsdir dirp, Args &&... args)
            -> decltype((static_cast<Base *>(nullptr)->*method)(nullptr, std::forward<Args>(args)...))
        {
            const auto err = dirp->error();
            if (err) {
                return err;
            }
            else {
                auto mp = dirp->mntpoint();
                if (!mp) {
                    return -ENOENT;
                }
                auto fsops = mp->fs_ops();
                if (!fsops) {
                    return -EIO;
                }
                else {
                    return (fsops.get()->*method)(dirp, std::forward<Args>(args)...);
                }
            }
        }
        auto cleanup_opened_files(std::string_view mount_point) -> void;

      private:
        std::weak_ptr<blkdev::disk_manager> m_diskmm;
        std::unordered_map<std::string, std::shared_ptr<filesystem_operations>> m_fstypes;
        std::map<std::string, std::shared_ptr<internal::mount_point>> m_mounts;
        std::unordered_set<std::string> m_partitions;
        internal::handle_mapper<fsfile> m_fds;
        std::unique_ptr<cpp_freertos::MutexRecursive> m_lock;
        std::shared_ptr<internal::notifier> m_notifier;
    };
} // namespace purefs::fs