starry-kernel 0.7.7

A Linux-compatible OS kernel built on ArceOS unikernel
Documentation
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use alloc::{borrow::Cow, string::ToString, sync::Arc};
use core::{
    ffi::c_int,
    hint::likely,
    sync::atomic::{AtomicBool, Ordering},
    task::Context,
};

use ax_errno::{AxError, AxResult};
use ax_fs_ng::vfs::{FileBackend, FileFlags, FsContext};
use ax_io::{Seek, SeekFrom};
use ax_sync::Mutex;
use ax_task::future::{block_on, poll_io};
use axfs_ng_vfs::{FsIoEvents, FsPollable, Location, Metadata, NodeFlags};
use axpoll::{IoEvents, Pollable};
use linux_raw_sys::{
    general::{AT_EMPTY_PATH, AT_FDCWD, AT_SYMLINK_NOFOLLOW, O_APPEND, O_EXCL},
    ioctl::TIOCSCTTY,
};
use starry_vm::VmPtr;

use super::{FileLike, Kstat, get_file_like};
use crate::{
    file::{IoDst, IoSrc},
    pseudofs::Device,
};

// FusionIO/directFS atomic-write toggle used by MySQL.
const DFS_IOCTL_ATOMIC_WRITE_SET: u32 = 0x4004_9502;

pub fn with_fs<R>(dirfd: c_int, f: impl FnOnce(&mut FsContext) -> AxResult<R>) -> AxResult<R> {
    let fs_context = ax_fs_ng::vfs::current_fs_context();
    let mut fs = fs_context.lock();
    if dirfd == AT_FDCWD {
        f(&mut fs)
    } else {
        let dir = Directory::from_fd(dirfd)?.inner.clone();
        f(&mut fs.with_current_dir(dir)?)
    }
}

pub enum ResolveAtResult {
    File(Location),
    Other(Arc<dyn FileLike>),
}

impl ResolveAtResult {
    pub fn into_file(self) -> Option<Location> {
        match self {
            Self::File(file) => Some(file),
            Self::Other(_) => None,
        }
    }

    pub fn stat(&self) -> AxResult<Kstat> {
        match self {
            Self::File(file) => file.metadata().map(|it| metadata_to_kstat(&it)),
            Self::Other(file_like) => file_like.stat(),
        }
    }
}

pub fn resolve_at(dirfd: c_int, path: Option<&str>, flags: u32) -> AxResult<ResolveAtResult> {
    match path {
        Some("") | None => {
            if flags & AT_EMPTY_PATH == 0 {
                return Err(AxError::NotFound);
            }
            let file_like = get_file_like(dirfd)?;
            let f = file_like.clone();
            Ok(if let Some(file) = f.downcast_ref::<File>() {
                // Use location() directly: backend() rejects PATH-only fds
                // (BadFileDescriptor) which would break fstat(O_PATH-fd).
                // man "O_PATH": fstat(2) is in the allowed-operations list.
                // Fixes bug-open-path-fstat-ebadf.
                ResolveAtResult::File(file.inner().location().clone())
            } else if let Some(dir) = f.downcast_ref::<Directory>() {
                ResolveAtResult::File(dir.inner().clone())
            } else {
                ResolveAtResult::Other(file_like)
            })
        }
        Some(path) => {
            let dirfd = if path.starts_with('/') {
                AT_FDCWD
            } else {
                dirfd
            };
            with_fs(dirfd, |fs| {
                if flags & AT_SYMLINK_NOFOLLOW != 0 {
                    fs.resolve_no_follow(path)
                } else {
                    fs.resolve(path)
                }
                .map(ResolveAtResult::File)
            })
        }
    }
}

pub fn metadata_to_kstat(metadata: &Metadata) -> Kstat {
    let ty = metadata.node_type as u8;
    let perm = metadata.mode.bits() as u32;
    let mode = ((ty as u32) << 12) | perm;
    Kstat {
        dev: metadata.device,
        ino: metadata.inode,
        mode,
        nlink: metadata.nlink as _,
        uid: metadata.uid,
        gid: metadata.gid,
        size: metadata.size,
        blksize: metadata.block_size as _,
        blocks: metadata.blocks,
        rdev: metadata.rdev,
        atime: metadata.atime,
        mtime: metadata.mtime,
        ctime: metadata.ctime,
    }
}

/// File wrapper for `ax_fs_ng::fops::File`.
pub struct File {
    inner: ax_fs_ng::File,
    open_flags: u32,
    nonblock: AtomicBool,
    append: AtomicBool,
}

impl File {
    pub fn new(inner: ax_fs_ng::File, open_flags: u32) -> Self {
        Self {
            inner,
            open_flags,
            nonblock: AtomicBool::new(false),
            append: AtomicBool::new(open_flags & O_APPEND != 0),
        }
    }

    pub fn inner(&self) -> &ax_fs_ng::File {
        &self.inner
    }
}

impl Drop for File {
    fn drop(&mut self) {
        if let Ok(device) = self.inner.location().entry().downcast::<Device>() {
            device.inner().close(self.open_flags & O_EXCL != 0);
        }
    }
}

impl File {
    fn is_blocking(&self) -> bool {
        self.inner.location().flags().contains(NodeFlags::BLOCKING)
    }
}

fn path_for(loc: &Location) -> Cow<'static, str> {
    loc.absolute_path()
        .map_or_else(|_| "<error>".into(), |f| Cow::Owned(f.to_string()))
}

fn fs_events_to_io(events: FsIoEvents) -> IoEvents {
    IoEvents::from_bits_truncate(events.bits())
}

fn io_events_to_fs(events: IoEvents) -> FsIoEvents {
    FsIoEvents::from_bits_truncate(events.bits())
}

impl FileLike for File {
    fn read(&self, dst: &mut IoDst) -> AxResult<usize> {
        let inner = self.inner();
        if likely(self.is_blocking()) {
            inner.read(dst)
        } else {
            block_on(poll_io(self, IoEvents::IN, self.nonblocking(), || {
                inner.read(&mut *dst)
            }))
        }
    }

    fn write(&self, src: &mut IoSrc) -> AxResult<usize> {
        let mut inner = self.inner();
        if self.append() {
            inner.seek(SeekFrom::End(0))?;
        }
        let result = if likely(self.is_blocking()) {
            inner.write(src)
        } else {
            block_on(poll_io(self, IoEvents::OUT, self.nonblocking(), || {
                inner.write(&mut *src)
            }))
        };
        if let Ok(bytes) = result
            && bytes > 0
        {
            let path = path_for(inner.location()).into_owned();
            crate::file::inotify::notify_modify_path(&path);
        }
        result
    }

    fn stat(&self) -> AxResult<Kstat> {
        Ok(metadata_to_kstat(&self.inner().location().metadata()?))
    }

    fn inode_key(&self) -> Option<(u64, u64)> {
        let m = self.inner().location().metadata().ok()?;
        Some((m.device, m.inode))
    }

    fn ioctl(&self, cmd: u32, arg: usize) -> AxResult<usize> {
        let loc = self.inner().backend()?.location();
        if cmd == TIOCSCTTY
            && let Some(result) = crate::pseudofs::dev::tty::bind_pty_at_location(loc.clone())
        {
            return result;
        }
        match cmd {
            DFS_IOCTL_ATOMIC_WRITE_SET => {
                let _enabled: u32 = (arg as *const u32).vm_read()?;
                Ok(0)
            }
            _ => loc.ioctl(cmd, arg),
        }
    }

    fn file_mmap(&self) -> AxResult<(FileBackend, FileFlags)> {
        Ok((self.inner().backend()?.clone(), self.inner().flags()))
    }

    fn set_nonblocking(&self, flag: bool) -> AxResult {
        self.nonblock.store(flag, Ordering::Release);
        Ok(())
    }

    fn nonblocking(&self) -> bool {
        self.nonblock.load(Ordering::Acquire)
    }

    fn append(&self) -> bool {
        self.append.load(Ordering::Acquire)
    }

    fn set_append(&self, flag: bool) -> AxResult {
        self.append.store(flag, Ordering::Release);
        self.inner().set_flag(FileFlags::APPEND, flag);
        Ok(())
    }

    fn open_flags(&self) -> u32 {
        self.open_flags
    }

    fn path(&self) -> Cow<'_, str> {
        path_for(self.inner.location())
    }

    fn from_fd(fd: c_int) -> AxResult<Arc<Self>>
    where
        Self: Sized + 'static,
    {
        let any = get_file_like(fd)?;
        if let Ok(file) = any.clone().downcast_arc::<File>() {
            return Ok(file);
        }
        // Memfd wraps a regular File and is meant to behave as one for
        // every read-data / size-changing syscall (lseek, fallocate,
        // sendfile, pread, pwrite, ...). Hand back the inner File so
        // those paths don't trip on the wrapper. Seal-aware ftruncate
        // already takes a separate Memfd::from_fd branch upstream.
        if let Ok(memfd) = any.clone().downcast_arc::<crate::file::memfd::Memfd>() {
            return Ok(memfd.inner().clone());
        }
        if let Ok(mount_table) = any.clone().downcast_arc::<crate::file::MountTableFile>() {
            return Ok(mount_table.inner().clone());
        }
        Err(if any.is::<Directory>() {
            AxError::IsADirectory
        } else {
            AxError::InvalidInput
        })
    }
}
impl Pollable for File {
    fn poll(&self) -> IoEvents {
        fs_events_to_io(self.inner().location().poll())
    }

    fn register(&self, context: &mut Context<'_>, events: IoEvents) {
        self.inner()
            .location()
            .register(context, io_events_to_fs(events));
    }
}

/// Directory wrapper for `ax_fs_ng::fops::Directory`.
pub struct Directory {
    inner: Location,
    pub offset: Mutex<u64>,
    /// Original open flags (used by fd_is_path / sys_fchmodat to detect
    /// O_PATH on directory descriptors — open(dir, O_PATH|O_DIRECTORY)
    /// must reject fchmod just like O_PATH on a regular file).
    open_flags: u32,
    /// Whether this is the original handle returned by fsmount(2).
    /// Reopening it as a normal directory deliberately drops this authority.
    detached_mount_handle: bool,
}

impl Directory {
    pub fn new(inner: Location, open_flags: u32) -> Self {
        Self {
            inner,
            offset: Mutex::new(0),
            open_flags,
            detached_mount_handle: false,
        }
    }

    pub(crate) fn new_detached_mount(inner: Location, open_flags: u32) -> Self {
        Self {
            inner,
            offset: Mutex::new(0),
            open_flags,
            detached_mount_handle: true,
        }
    }

    /// Get the inner node of the directory.
    pub fn inner(&self) -> &Location {
        &self.inner
    }

    pub(crate) fn is_detached_mount_handle(&self) -> bool {
        self.detached_mount_handle
    }
}

impl FileLike for Directory {
    fn read(&self, _dst: &mut IoDst) -> AxResult<usize> {
        Err(AxError::IsADirectory)
    }

    fn write(&self, _src: &mut IoSrc) -> AxResult<usize> {
        // Directories cannot be opened for writing, so any write attempt
        // means the fd is not open for writing → EBADF.
        // Linux VFS checks FMODE_WRITE before reaching the filesystem layer.
        Err(AxError::BadFileDescriptor)
    }

    fn stat(&self) -> AxResult<Kstat> {
        Ok(metadata_to_kstat(&self.inner.metadata()?))
    }

    fn inode_key(&self) -> Option<(u64, u64)> {
        let m = self.inner.metadata().ok()?;
        Some((m.device, m.inode))
    }

    fn open_flags(&self) -> u32 {
        self.open_flags
    }

    fn path(&self) -> Cow<'_, str> {
        path_for(&self.inner)
    }

    fn from_fd(fd: c_int) -> AxResult<Arc<Self>> {
        get_file_like(fd)?
            .downcast_arc()
            .map_err(|_| AxError::NotADirectory)
    }
}
impl Pollable for Directory {
    fn poll(&self) -> IoEvents {
        fs_events_to_io(FsIoEvents::IN | FsIoEvents::OUT)
    }

    fn register(&self, _context: &mut Context<'_>, _events: IoEvents) {}
}
#[cfg(axtest)]
pub(crate) fn metadata_to_kstat_conversion_rules_hold_for_test() -> bool {
    use core::time::Duration;

    use axfs_ng_vfs::{DeviceId, Metadata};

    // Create a Metadata with known values.
    let meta = Metadata {
        device: 42,
        inode: 100,
        nlink: 3,
        mode: axfs_ng_vfs::NodePermission::from_bits_truncate(0o644),
        node_type: axfs_ng_vfs::NodeType::RegularFile,
        uid: 1000,
        gid: 1000,
        size: 4096,
        block_size: 512,
        blocks: 8,
        rdev: DeviceId::default(),
        atime: Duration::from_secs(1000),
        mtime: Duration::from_millis(2000500),
        ctime: Duration::from_nanos(3000999999000),
    };

    let kstat = metadata_to_kstat(&meta);

    // Verify key fields are correctly transferred.
    kstat.dev == 42
        && kstat.ino == 100
        && kstat.nlink == 3
        && kstat.uid == 1000
        && kstat.gid == 1000
        && kstat.size == 4096
        && kstat.blksize == 512
        && kstat.blocks == 8
        // mode should have type bits (S_IFREG=0100000) OR'd with 0644.
        && (kstat.mode >> 12) == (axfs_ng_vfs::NodeType::RegularFile as u32)
}