summaryrefslogtreecommitdiff
path: root/Kernel/FileSystem/Inode.cpp
blob: abf4b1128aee52c1df0bd6e0ec964b20030e01e8 (plain)
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/NonnullRefPtrVector.h>
#include <AK/Singleton.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <Kernel/API/InodeWatcherEvent.h>
#include <Kernel/FileSystem/Custody.h>
#include <Kernel/FileSystem/FileDescription.h>
#include <Kernel/FileSystem/Inode.h>
#include <Kernel/FileSystem/InodeWatcher.h>
#include <Kernel/FileSystem/VirtualFileSystem.h>
#include <Kernel/KBufferBuilder.h>
#include <Kernel/Net/LocalSocket.h>
#include <Kernel/Process.h>
#include <Kernel/VM/SharedInodeVMObject.h>

namespace Kernel {

static SpinLock s_all_inodes_lock;
static AK::Singleton<Inode::List> s_list;

static Inode::List& all_with_lock()
{
    VERIFY(s_all_inodes_lock.is_locked());

    return *s_list;
}

void Inode::sync()
{
    NonnullRefPtrVector<Inode, 32> inodes;
    {
        ScopedSpinLock all_inodes_lock(s_all_inodes_lock);
        for (auto& inode : all_with_lock()) {
            if (inode.is_metadata_dirty())
                inodes.append(inode);
        }
    }

    for (auto& inode : inodes) {
        VERIFY(inode.is_metadata_dirty());
        inode.flush_metadata();
    }
}

KResultOr<NonnullOwnPtr<KBuffer>> Inode::read_entire(FileDescription* description) const
{
    KBufferBuilder builder;

    size_t nread;
    u8 buffer[4096];
    off_t offset = 0;
    for (;;) {
        auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
        auto result = read_bytes(offset, sizeof(buffer), buf, description);
        if (result.is_error())
            return result.error();
        nread = result.value();
        VERIFY(nread <= sizeof(buffer));
        if (nread == 0)
            break;
        builder.append((const char*)buffer, nread);
        offset += nread;
        if (nread < sizeof(buffer))
            break;
    }

    auto entire_file = builder.build();
    if (!entire_file)
        return ENOMEM;
    return entire_file.release_nonnull();
}

KResultOr<NonnullRefPtr<Custody>> Inode::resolve_as_link(Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level) const
{
    // The default implementation simply treats the stored
    // contents as a path and resolves that. That is, it
    // behaves exactly how you would expect a symlink to work.
    auto contents_or = read_entire();
    if (contents_or.is_error())
        return contents_or.error();

    auto& contents = contents_or.value();
    auto path = StringView(contents->data(), contents->size());
    return VirtualFileSystem::the().resolve_path(path, base, out_parent, options, symlink_recursion_level);
}

Inode::Inode(FileSystem& fs, InodeIndex index)
    : m_file_system(fs)
    , m_index(index)
{
    ScopedSpinLock all_inodes_lock(s_all_inodes_lock);
    all_with_lock().append(*this);
}

Inode::~Inode()
{
    ScopedSpinLock all_inodes_lock(s_all_inodes_lock);
    all_with_lock().remove(*this);

    for (auto& watcher : m_watchers) {
        watcher->unregister_by_inode({}, identifier());
    }
}

void Inode::will_be_destroyed()
{
    MutexLocker locker(m_inode_lock);
    if (m_metadata_dirty)
        flush_metadata();
}

KResult Inode::set_atime(time_t)
{
    return ENOTIMPL;
}

KResult Inode::set_ctime(time_t)
{
    return ENOTIMPL;
}

KResult Inode::set_mtime(time_t)
{
    return ENOTIMPL;
}

KResult Inode::increment_link_count()
{
    return ENOTIMPL;
}

KResult Inode::decrement_link_count()
{
    return ENOTIMPL;
}

void Inode::set_shared_vmobject(SharedInodeVMObject& vmobject)
{
    MutexLocker locker(m_inode_lock);
    m_shared_vmobject = vmobject;
}

bool Inode::bind_socket(LocalSocket& socket)
{
    MutexLocker locker(m_inode_lock);
    if (m_socket)
        return false;
    m_socket = socket;
    return true;
}

bool Inode::unbind_socket()
{
    MutexLocker locker(m_inode_lock);
    if (!m_socket)
        return false;
    m_socket = nullptr;
    return true;
}

void Inode::register_watcher(Badge<InodeWatcher>, InodeWatcher& watcher)
{
    MutexLocker locker(m_inode_lock);
    VERIFY(!m_watchers.contains(&watcher));
    m_watchers.set(&watcher);
}

void Inode::unregister_watcher(Badge<InodeWatcher>, InodeWatcher& watcher)
{
    MutexLocker locker(m_inode_lock);
    VERIFY(m_watchers.contains(&watcher));
    m_watchers.remove(&watcher);
}

NonnullRefPtr<FIFO> Inode::fifo()
{
    MutexLocker locker(m_inode_lock);
    VERIFY(metadata().is_fifo());

    // FIXME: Release m_fifo when it is closed by all readers and writers
    if (!m_fifo) {
        m_fifo = FIFO::try_create(metadata().uid);
        // FIXME: We need to be able to observe OOM here.
        VERIFY(!m_fifo.is_null());
    }

    VERIFY(m_fifo);
    return *m_fifo;
}

void Inode::set_metadata_dirty(bool metadata_dirty)
{
    MutexLocker locker(m_inode_lock);

    if (metadata_dirty) {
        // Sanity check.
        VERIFY(!fs().is_readonly());
    }

    if (m_metadata_dirty == metadata_dirty)
        return;

    m_metadata_dirty = metadata_dirty;
    if (m_metadata_dirty) {
        // FIXME: Maybe we should hook into modification events somewhere else, I'm not sure where.
        //        We don't always end up on this particular code path, for instance when writing to an ext2fs file.
        for (auto& watcher : m_watchers) {
            watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::MetadataModified);
        }
    }
}

void Inode::did_add_child(InodeIdentifier const&, String const& name)
{
    MutexLocker locker(m_inode_lock);

    for (auto& watcher : m_watchers) {
        watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ChildCreated, name);
    }
}

void Inode::did_remove_child(InodeIdentifier const&, String const& name)
{
    MutexLocker locker(m_inode_lock);

    if (name == "." || name == "..") {
        // These are just aliases and are not interesting to userspace.
        return;
    }

    for (auto& watcher : m_watchers) {
        watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ChildDeleted, name);
    }
}

void Inode::did_modify_contents()
{
    MutexLocker locker(m_inode_lock);
    for (auto& watcher : m_watchers) {
        watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ContentModified);
    }
}

void Inode::did_delete_self()
{
    MutexLocker locker(m_inode_lock);
    for (auto& watcher : m_watchers) {
        watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::Deleted);
    }
}

KResult Inode::prepare_to_write_data()
{
    // FIXME: It's a poor design that filesystems are expected to call this before writing out data.
    //        We should funnel everything through an interface at the VirtualFileSystem layer so this can happen from a single place.
    MutexLocker locker(m_inode_lock);
    if (fs().is_readonly())
        return EROFS;
    auto metadata = this->metadata();
    if (metadata.is_setuid() || metadata.is_setgid()) {
        dbgln("Inode::prepare_to_write_data(): Stripping SUID/SGID bits from {}", identifier());
        return chmod(metadata.mode & ~(04000 | 02000));
    }
    return KSuccess;
}

RefPtr<SharedInodeVMObject> Inode::shared_vmobject() const
{
    MutexLocker locker(m_inode_lock);
    return m_shared_vmobject.strong_ref();
}

template<typename T>
static inline bool range_overlap(T start1, T len1, T start2, T len2)
{
    return ((start1 < start2 + len2) || len2 == 0) && ((start2 < start1 + len1) || len1 == 0);
}

static inline KResult normalize_flock(FileDescription const& description, flock& lock)
{
    off_t start;
    switch (lock.l_whence) {
    case SEEK_SET:
        start = lock.l_start;
        break;
    case SEEK_CUR:
        start = description.offset() + lock.l_start;
        break;
    case SEEK_END:
        // FIXME: Implement SEEK_END and negative lengths.
        return ENOTSUP;
    default:
        return EINVAL;
    }
    lock = { lock.l_type, SEEK_SET, start, lock.l_len, 0 };
    return KSuccess;
}

KResult Inode::can_apply_flock(FileDescription const& description, flock const& new_lock) const
{
    VERIFY(new_lock.l_whence == SEEK_SET);

    MutexLocker locker(m_inode_lock, Mutex::Mode::Shared);

    if (new_lock.l_type == F_UNLCK) {
        for (auto& lock : m_flocks) {
            if (&description == lock.owner && lock.start == new_lock.l_start && lock.len == new_lock.l_len)
                return KSuccess;
        }
        return EINVAL;
    }

    for (auto& lock : m_flocks) {
        if (!range_overlap(lock.start, lock.len, new_lock.l_start, new_lock.l_len))
            continue;

        if (new_lock.l_type == F_RDLCK && lock.type == F_WRLCK)
            return EAGAIN;

        if (new_lock.l_type == F_WRLCK)
            return EAGAIN;
    }
    return KSuccess;
}

KResult Inode::apply_flock(Process const& process, FileDescription const& description, Userspace<flock const*> input_lock)
{
    flock new_lock;
    if (!copy_from_user(&new_lock, input_lock))
        return EFAULT;

    auto rc = normalize_flock(description, new_lock);
    if (rc.is_error())
        return rc;

    MutexLocker locker(m_inode_lock);

    rc = can_apply_flock(description, new_lock);
    if (rc.is_error())
        return rc;

    if (new_lock.l_type == F_UNLCK) {
        for (size_t i = 0; i < m_flocks.size(); ++i) {
            if (&description == m_flocks[i].owner && m_flocks[i].start == new_lock.l_start && m_flocks[i].len == new_lock.l_len) {
                m_flocks.remove(i);
                return KSuccess;
            }
        }
        return EINVAL;
    }

    m_flocks.append(Flock { new_lock.l_type, new_lock.l_start, new_lock.l_len, &description, process.pid().value() });
    return KSuccess;
}

KResult Inode::get_flock(FileDescription const& description, Userspace<flock*> reference_lock) const
{
    flock lookup;
    if (!copy_from_user(&lookup, reference_lock))
        return EFAULT;

    auto rc = normalize_flock(description, lookup);
    if (rc.is_error())
        return rc;

    MutexLocker locker(m_inode_lock, Mutex::Mode::Shared);

    for (auto& lock : m_flocks) {
        if (!range_overlap(lock.start, lock.len, lookup.l_start, lookup.l_len))
            continue;

        if ((lookup.l_type == F_RDLCK && lock.type == F_WRLCK) || lookup.l_type == F_WRLCK) {
            lookup = { lock.type, SEEK_SET, lock.start, lock.len, lock.pid };
            if (!copy_to_user(reference_lock, &lookup))
                return EFAULT;
            return KSuccess;
        }
    }

    lookup.l_type = F_UNLCK;
    if (!copy_to_user(reference_lock, &lookup))
        return EFAULT;
    return KSuccess;
}

void Inode::remove_flocks_for_description(FileDescription const& description)
{
    MutexLocker locker(m_inode_lock);

    for (size_t i = 0; i < m_flocks.size(); ++i) {
        if (&description == m_flocks[i].owner)
            m_flocks.remove(i--);
    }
}
}