aboutsummaryrefslogtreecommitdiff
path: root/src/lib/vfs.zig
blob: c70a375f1b50526333bbe0636958d57fc8e72089 (plain) (blame)
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
// SPDX-FileCopyrightText: 2024 Himbeer <himbeer@disroot.org>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

const std = @import("std");

const paging = @import("paging.zig");
const process = @import("process.zig");
const sysexchange = @import("sysexchange.zig");

const mem = std.mem;

var root: Node = .{ .data = .{ .name = "", .inode = .{ .resource = .{ .tag = .dir, .data = .{ .dir = undefined } }, .pid = 0 } } };

pub fn treeRoot() *const Tree {
    return root.data.inode.resource.data.dir;
}

pub const Error = error{
    NotFound,
    RelativePathNotAllowed,
    NotADirectory,
    NoAbsoluteContainingDirectory,
    TooManyReferences,
    ReadNotSupported,
    WriteNotSupported,
    InUse,
};

// A stream is a resource that provides a shared data stream with a driver.
pub const Stream = extern struct {
    readFn: ?ReadFn,
    writeFn: ?WriteFn,

    pub const ReadFn = *const fn (ptr: [*]u8, len: usize) callconv(.C) sysexchange.Result(usize);
    pub const WriteFn = *const fn (ptr: [*]const u8, len: usize) callconv(.C) sysexchange.Result(usize);
};

// A file is a resource that creates a unique data stream with a driver.
pub const File = extern struct {
    openFn: OpenFn,
    readFn: ?ReadFn,
    writeFn: ?WriteFn,
    closeFn: ?CloseFn,
    initializer: ?*anyopaque,

    pub const OpenFn = *allowzero const fn (initializer: ?*anyopaque, pid: u16) callconv(.C) sysexchange.Result(*anyopaque);
    pub const ReadFn = *const fn (context: *anyopaque, ptr: [*]u8, len: usize) callconv(.C) sysexchange.Result(usize);
    pub const WriteFn = *const fn (context: *anyopaque, ptr: [*]const u8, len: usize) callconv(.C) sysexchange.Result(usize);
    pub const CloseFn = *const fn (context: *anyopaque) callconv(.C) void;
};

// A hook is a resource that invokes raw driver callbacks when interacted with.
pub const Hook = extern struct {
    callback: Callback,

    pub const Callback = *allowzero const fn (pid: u16, data: usize) callconv(.C) sysexchange.Result(usize);
};

// A directory hook is a resource that provides other resources via driver callbacks.
pub const DirHook = extern struct {
    provideFn: ProvideFn,
    findFn: FindFn,
    removeFn: RemoveFn,

    pub const ProvideFn = *allowzero const fn (name_ptr: [*]const u8, name_len: usize, inode: Inode) callconv(.C) sysexchange.Result(void);
    pub const FindFn = *allowzero const fn (name_ptr: [*]const u8, name_len: usize) callconv(.C) ?*Inode;
    pub const RemoveFn = *allowzero const fn (name_ptr: [*]const u8, name_len: usize) callconv(.C) sysexchange.Result(void);
};

pub const ResourceKind = enum(u32) {
    stream,
    file,
    hook,
    dir,
    dir_hook,
};

pub const Resource = extern struct {
    tag: ResourceKind,
    data: extern union {
        stream: Stream,
        file: File,
        hook: Hook,
        dir: *Tree,
        dir_hook: DirHook,
    },
};

pub const Inode = extern struct {
    resource: Resource,
    refs: usize = 0,
    pid: u16,
};

pub const DirEntry = struct {
    name: []const u8,
    inode: Inode,
};

pub const Node = std.DoublyLinkedList(DirEntry).Node;

pub const Tree = struct {
    allocator: mem.Allocator,
    nodes: std.DoublyLinkedList(DirEntry),

    pub fn init(allocator: mem.Allocator) Tree {
        return .{
            .allocator = allocator,
            .nodes = std.DoublyLinkedList(DirEntry){},
        };
    }

    pub fn find(self: *const Tree, name: []const u8) ?*Node {
        var node = self.nodes.first;
        while (node) |current_node| {
            if (current_node.next == current_node) break;

            if (mem.eql(u8, current_node.data.name, name)) return current_node;
            node = current_node.next;
        }
        return null;
    }

    pub fn provideResource(self: *Tree, entry: DirEntry) !void {
        var node = try self.allocator.create(Node);
        node.data = entry;
        self.nodes.append(node);
    }

    pub fn remove(self: *Tree, name: []const u8) !void {
        if (self.find(name)) |node| {
            if (node.data.inode.refs > 0) return Error.InUse;
            self.nodes.remove(node);
        } else return Error.NotFound;
    }
};

pub const ResourceDescriptor = struct {
    inode: *Inode,

    pub fn init(inode: *Inode) !ResourceDescriptor {
        inode.refs = std.math.add(usize, inode.refs, 1) catch return Error.TooManyReferences;
        return .{
            .inode = inode,
        };
    }

    pub fn deinit(self: ResourceDescriptor) void {
        self.inode.refs -|= 1;
    }

    pub fn read(self: ResourceDescriptor, proc: *process.Info, buffer: []u8) !noreturn {
        return switch (self.inode.resource.tag) {
            .stream => {
                const stream = self.inode.resource.data.stream;

                const driver = process.latestThread(self.inode.pid).?;
                const copy = try driver.copyBuffer(buffer);

                const readFn = stream.readFn orelse return Error.ReadNotSupported;
                proc.state = .suspended;
                try call(driver, readFn, .{ copy.ptr, copy.len }, .{
                    .cleanupFn = moveBack,
                    .buffer = buffer,
                    .copy = copy,
                }, .{
                    .hookFn = crossProcessReturn,
                    .context = proc,
                });
            },
            .hook => Error.ReadNotSupported,
            else => Error.ReadNotSupported,
        };
    }

    pub fn write(self: ResourceDescriptor, proc: *process.Info, bytes: []const u8) !noreturn {
        return switch (self.inode.resource.tag) {
            .stream => {
                const stream = self.inode.resource.data.stream;

                const driver = process.latestThread(self.inode.pid).?;
                const copy = try driver.copyBytes(bytes);

                const writeFn = stream.writeFn orelse return Error.WriteNotSupported;
                proc.state = .suspended;
                try call(driver, writeFn, .{ copy.ptr, copy.len }, null, .{
                    .hookFn = crossProcessReturn,
                    .context = proc,
                });
            },
            .hook => Error.WriteNotSupported,
            else => Error.WriteNotSupported,
        };
    }

    fn moveBack(driver: *const process.Info, buffer: []u8, copy: []const u8) void {
        paging.setUserMemoryAccess(true);
        defer paging.setUserMemoryAccess(false);

        @memcpy(buffer, copy);

        var addr = @intFromPtr(copy.ptr);
        const limit = addr + copy.len;
        while (addr < limit) : (addr += paging.page_size) {
            driver.page_table.unmapEntry(addr);
        }
    }
};

pub const UserInfo = union(enum) {
    rd: ResourceDescriptor,
    value: sysexchange.Result(usize),
};

pub fn init(allocator: mem.Allocator) !void {
    const tree = try allocator.create(Tree);
    tree.* = Tree.init(allocator);
    root.data.inode.resource.data.dir = tree;
}

pub fn find(path: []const u8) ?*Inode {
    if (!std.fs.path.isAbsolutePosix(path)) return null;

    // Error set is empty.
    var it = std.fs.path.ComponentIterator(.posix, u8).init(path) catch unreachable;
    var resource = root.data.inode.resource;
    while (it.next()) |component| {
        const inode = switch (resource.tag) {
            .dir => blk: {
                const dir = resource.data.dir;
                break :blk if (dir.find(component.name)) |entry| &entry.data.inode else null;
            },
            .dir_hook => blk: {
                const dir_hook = resource.data.dir_hook;
                break :blk dir_hook.findFn(component.name.ptr, component.name.len);
            },
            else => null, // Not a directory (or directory hook).
        } orelse return null;

        if (mem.eql(u8, component.path, path)) {
            return inode;
        }
        resource = inode.resource;
    }

    // No components, this is the root directory (/).
    return &root.data.inode;
}

pub fn provideResource(path: []const u8, resource: Resource, pid: u16) !void {
    if (!std.fs.path.isAbsolutePosix(path)) return Error.RelativePathNotAllowed;

    const dirname = std.fs.path.dirnamePosix(path) orelse return Error.NoAbsoluteContainingDirectory;
    if (find(dirname)) |inode| {
        const basename = std.fs.path.basenamePosix(path);
        return switch (inode.resource.tag) {
            .dir => blk: {
                const dir = inode.resource.data.dir;

                break :blk dir.provideResource(.{
                    .name = basename,
                    .inode = .{
                        .resource = resource,
                        .pid = pid,
                    },
                });
            },
            .dir_hook => blk: {
                const dir_hook = inode.resource.data.dir_hook;

                break :blk dir_hook.provideFn(basename.ptr, basename.len, .{
                    .resource = resource,
                    .pid = pid,
                }).toErrorUnion();
            },
            else => Error.NotADirectory,
        };
    } else return Error.NotFound;
}

pub fn provideResourceZ(path_c: [*:0]const u8, resource: Resource, pid: u16) !void {
    return provideResource(mem.sliceTo(path_c, 0), resource, pid);
}

pub fn open(proc: *process.Info, path: []const u8, pid: u16, data: usize) !ResourceDescriptor {
    const inode = find(path) orelse return Error.NotFound;
    return switch (inode.resource.tag) {
        .hook => {
            const hook = inode.resource.data.hook;

            const driver = process.latestThread(inode.pid).?;

            proc.state = .suspended;
            try call(driver, hook.callback, .{ pid, data }, null, .{
                .hookFn = crossProcessReturn,
                .context = proc,
            });
        },
        else => ResourceDescriptor.init(inode),
    };
}

pub fn openZ(proc: *process.Info, path_c: [*:0]const u8, pid: u16, data: usize) !ResourceDescriptor {
    return open(proc, mem.sliceTo(path_c, 0), pid, data);
}

fn call(proc: *process.Info, function: *const anyopaque, args: anytype, cleanup_hook: ?process.Info.CleanupHook, term_hook: ?process.Info.TermHook) !noreturn {
    const callback_thread = try proc.createThread(null);
    callback_thread.call(@intFromPtr(function), args, cleanup_hook, term_hook);
}

fn crossProcessReturn(context: *anyopaque, driver: *const process.Info) void {
    const proc: *process.Info = @alignCast(@ptrCast(context));
    proc.trap_frame.general_purpose_registers[10] = driver.trap_frame.general_purpose_registers[10];
    proc.trap_frame.general_purpose_registers[11] = driver.trap_frame.general_purpose_registers[11];
    proc.pc += 4; // Skip ecall instruction
    proc.state = .waiting;
    // Scheduler is called by the "terminate" syscall after two layers of returning.
}