summaryrefslogtreecommitdiff
path: root/Kernel/FileSystem/InodeWatcher.h
blob: 041e3ece77fcb3d5bee4687cfa0a297c21e02934 (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
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Badge.h>
#include <AK/Checked.h>
#include <AK/CircularQueue.h>
#include <AK/HashMap.h>
#include <AK/NonnullOwnPtr.h>
#include <Kernel/API/InodeWatcherEvent.h>
#include <Kernel/FileSystem/File.h>
#include <Kernel/Forward.h>

namespace Kernel {

// A specific description of a watch.
struct WatchDescription {
    int wd;
    Inode& inode;
    unsigned event_mask;

    static KResultOr<NonnullOwnPtr<WatchDescription>> create(int wd, Inode& inode, unsigned event_mask)
    {
        return adopt_nonnull_own_or_enomem(new (nothrow) WatchDescription(wd, inode, event_mask));
    }

private:
    WatchDescription(int wd, Inode& inode, unsigned event_mask)
        : wd(wd)
        , inode(inode)
        , event_mask(event_mask)
    {
    }
};

class InodeWatcher final : public File {
public:
    static KResultOr<NonnullRefPtr<InodeWatcher>> try_create();
    virtual ~InodeWatcher() override;

    virtual bool can_read(const OpenFileDescription&, size_t) const override;
    virtual KResultOr<size_t> read(OpenFileDescription&, u64, UserOrKernelBuffer&, size_t) override;
    // Can't write to an inode watcher.
    virtual bool can_write(const OpenFileDescription&, size_t) const override { return true; }
    virtual KResultOr<size_t> write(OpenFileDescription&, u64, const UserOrKernelBuffer&, size_t) override { return EIO; }
    virtual KResult close() override;

    virtual String absolute_path(const OpenFileDescription&) const override;
    virtual StringView class_name() const override { return "InodeWatcher"; };
    virtual bool is_inode_watcher() const override { return true; }

    void notify_inode_event(Badge<Inode>, InodeIdentifier, InodeWatcherEvent::Type, String const& name = {});

    KResultOr<int> register_inode(Inode&, unsigned event_mask);
    KResult unregister_by_wd(int);
    void unregister_by_inode(Badge<Inode>, InodeIdentifier);

private:
    explicit InodeWatcher() { }

    mutable Mutex m_lock;

    struct Event {
        int wd { 0 };
        InodeWatcherEvent::Type type { InodeWatcherEvent::Type::Invalid };
        String path;
    };
    CircularQueue<Event, 32> m_queue;
    Checked<int> m_wd_counter { 1 };

    // NOTE: These two hashmaps provide two different ways of reaching the same
    // watch description, so they will overlap.
    HashMap<int, NonnullOwnPtr<WatchDescription>> m_wd_to_watches;
    HashMap<InodeIdentifier, WatchDescription*> m_inode_to_watches;
};

}