twizzler_abi/runtime/
fs.rs

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
use core::{
    cmp::{max, min},
    intrinsics::size_of,
    num::NonZeroUsize,
};

use lazy_static::lazy_static;
use lru::LruCache;
use rustc_alloc::{string::ToString, sync::Arc};
use stable_vec::{self, StableVec};
use twizzler_rt_abi::{
    bindings::io_vec,
    fd::{OpenError, RawFd},
    io::{IoError, IoFlags, SeekFrom},
    object::{MapFlags, ObjectHandle},
};

use super::{object, MinimalRuntime};
use crate::{
    object::{ObjID, NULLPAGE_SIZE},
    print_err,
    runtime::simple_mutex::Mutex,
    syscall::{sys_object_create, BackingType, LifetimeType, ObjectCreate, ObjectCreateFlags},
};

#[derive(Clone)]
struct FileDesc {
    pos: u64,
    handle: ObjectHandle,
    map: LruCache<usize, ObjectHandle>, // Lazily loads object handles when using extensible files
}

#[derive(Clone)]
enum FdKind {
    File(Arc<Mutex<FileDesc>>),
    Stdio,
}

#[repr(C)]
#[derive(Clone, Copy)]
struct FileMetadata {
    magic: u64,
    size: u64,
    direct: [ObjID; DIRECT_OBJECT_COUNT],
}

const MAGIC_NUMBER: u64 = 0xBEEFDEAD;
// 64 megabytes
const WRITABLE_BYTES: u64 = (1 << 26) - size_of::<FileMetadata>() as u64 - NULLPAGE_SIZE as u64;
const OBJECT_COUNT: usize = 256;
const DIRECT_OBJECT_COUNT: usize = 255; // The number of objects reachable from the direct pointer list
const MAX_FILE_SIZE: u64 = WRITABLE_BYTES * 256;
const MAX_LOADABLE_OBJECTS: usize = 16;
lazy_static! {
    static ref FD_SLOTS: Mutex<StableVec<FdKind>> = Mutex::new(StableVec::from([
        FdKind::Stdio,
        FdKind::Stdio,
        FdKind::Stdio
    ]));
}

fn get_fd_slots() -> &'static Mutex<StableVec<FdKind>> {
    &FD_SLOTS
}

impl MinimalRuntime {
    pub fn open(&self, path: &str) -> Result<RawFd, OpenError> {
        let obj_id = ObjID::new(
            path.parse::<u128>()
                .map_err(|_err| (OpenError::InvalidArgument))?,
        );
        let flags = MapFlags::READ | MapFlags::WRITE;

        let handle = self.map_object(obj_id, flags).unwrap();

        let metadata_handle = unsafe {
            handle
                .start()
                .offset(NULLPAGE_SIZE as isize)
                .cast::<FileMetadata>()
        };
        if (unsafe { *metadata_handle }).magic != MAGIC_NUMBER {
            unsafe {
                *metadata_handle = FileMetadata {
                    magic: MAGIC_NUMBER,
                    size: 0,
                    direct: [ObjID::new(0); DIRECT_OBJECT_COUNT],
                }
            };
        }

        let mut binding = get_fd_slots().lock();

        let elem = FdKind::File(Arc::new(Mutex::new(FileDesc {
            pos: 0,
            handle,
            map: LruCache::<usize, ObjectHandle>::new(NonZeroUsize::new(1).unwrap()),
        })));

        let fd = if binding.is_compact() {
            binding.push(elem)
        } else {
            let fd = binding.first_empty_slot_from(0).unwrap();
            binding.insert(fd, elem);
            fd
        };

        Ok(fd.try_into().unwrap())
    }

    pub fn read(&self, fd: RawFd, buf: &mut [u8]) -> Result<usize, IoError> {
        let binding = get_fd_slots().lock();
        let file_desc = binding
            .get(fd.try_into().unwrap())
            .ok_or(IoError::InvalidDesc)?;

        let FdKind::File(file_desc) = &file_desc else {
            // Just do basic stdio via kernel console
            let len = crate::syscall::sys_kernel_console_read(
                buf,
                crate::syscall::KernelConsoleReadFlags::empty(),
            )
            .map_err(|_| IoError::Other)?;
            return Ok(len);
        };

        let mut binding = file_desc.lock();

        let metadata_handle = unsafe {
            binding
                .handle
                .start()
                .offset(NULLPAGE_SIZE as isize)
                .cast::<FileMetadata>()
        };

        let mut bytes_read = 0;
        while bytes_read < buf.len() {
            if binding.pos > (unsafe { *metadata_handle }).size {
                break;
            }

            let available_bytes = (unsafe { *metadata_handle }).size - binding.pos;

            let object_window: usize = ((binding.pos) / WRITABLE_BYTES) as usize;
            let offset = (binding.pos) % WRITABLE_BYTES;

            if object_window > OBJECT_COUNT || available_bytes == 0 {
                break;
            }
            // If the offset is in the first object, then

            // OBJECT_SIZE - offset, is the bytes you can write in one object. Offset is bound by
            // modulo of OBJECT_SIZE. available_bytes is the total bytes you can write
            // to the file, this is bound by the writer since the writer can modify the size of the
            // file buf.len() - bytes_read is the bytes you have left to read, this is
            // bound by buf.len() > bytes_read
            let bytes_to_read = min(
                min(WRITABLE_BYTES - offset, available_bytes),
                (buf.len() - bytes_read) as u64,
            );

            let object_ptr = if object_window == 0 {
                binding.handle.start()
            } else {
                if let Some(new_handle) = binding.map.get(&object_window) {
                    new_handle.start()
                } else {
                    let obj_id =
                        ((unsafe { *metadata_handle }).direct)[(object_window - 1) as usize];
                    let flags = MapFlags::READ | MapFlags::WRITE;
                    let handle = self.map_object(obj_id, flags).unwrap();
                    binding.map.put(object_window, handle.clone());
                    handle.start()
                }
            };

            unsafe {
                buf.as_mut_ptr().offset(bytes_read as isize).copy_from(
                    object_ptr.offset(
                        NULLPAGE_SIZE as isize
                            + size_of::<FileMetadata>() as isize
                            + offset as isize,
                    ),
                    bytes_to_read as usize,
                )
            }

            binding.pos += bytes_to_read;

            bytes_read += bytes_to_read as usize;
        }

        Ok(bytes_read)
    }

    pub fn fd_pread(
        &self,
        fd: RawFd,
        off: Option<u64>,
        buf: &mut [u8],
        flags: IoFlags,
    ) -> Result<usize, IoError> {
        if off.is_some() {
            return Err(IoError::SeekError);
        }
        self.read(fd, buf)
    }

    pub fn fd_pwrite(
        &self,
        fd: RawFd,
        off: Option<u64>,
        buf: &[u8],
        flags: IoFlags,
    ) -> Result<usize, IoError> {
        if off.is_some() {
            return Err(IoError::SeekError);
        }
        self.write(fd, buf)
    }

    pub fn fd_pwritev(
        &self,
        fd: RawFd,
        off: Option<u64>,
        buf: &[io_vec],
        flags: IoFlags,
    ) -> Result<usize, IoError> {
        return Err(IoError::Other);
    }

    pub fn fd_preadv(
        &self,
        fd: RawFd,
        off: Option<u64>,
        buf: &[io_vec],
        flags: IoFlags,
    ) -> Result<usize, IoError> {
        return Err(IoError::Other);
    }

    pub fn fd_get_info(&self, fd: RawFd) -> Option<twizzler_rt_abi::bindings::fd_info> {
        let binding = get_fd_slots().lock();
        if binding.get(fd.try_into().unwrap()).is_none() {
            return None;
        }
        Some(twizzler_rt_abi::bindings::fd_info { flags: 0 })
    }

    pub fn write(&self, fd: RawFd, buf: &[u8]) -> Result<usize, IoError> {
        if fd == 0 || fd == 1 || fd == 2 {
            crate::syscall::sys_kernel_console_write(
                buf,
                crate::syscall::KernelConsoleWriteFlags::empty(),
            );
            return Ok(buf.len());
        }
        let binding = get_fd_slots().lock();
        let file_desc = binding
            .get(fd.try_into().unwrap())
            .ok_or(IoError::InvalidDesc)?;

        let FdKind::File(file_desc) = &file_desc else {
            // Just do basic stdio via kernel console
            crate::syscall::sys_kernel_console_write(
                buf,
                crate::syscall::KernelConsoleWriteFlags::empty(),
            );
            return Ok(buf.len());
        };

        let mut binding = file_desc.lock();

        let metadata_handle = unsafe {
            binding
                .handle
                .start()
                .offset(NULLPAGE_SIZE as isize)
                .cast::<FileMetadata>()
        };

        let mut bytes_written = 0;
        while bytes_written < buf.len() {
            // The available bytes for writing is the OBJECT_SIZE * OBJECT_COUNT
            // The metadata fills some bytes, the rest is defined by binding.pos which overlays the
            // rest of the object space
            let available_bytes = MAX_FILE_SIZE - binding.pos;

            let object_window: usize = (binding.pos / WRITABLE_BYTES) as usize;
            let offset = binding.pos % WRITABLE_BYTES;

            if object_window > OBJECT_COUNT || available_bytes == 0 {
                break;
            }

            // OBJECT_SIZE - offset, 0 is the bytes you can write in one object. Offset is bound by
            // modulo of OBJECT_SIZE. available_bytes is the total bytes you can write
            // to the file, available_bytes is always bound by the max file size
            // buf.len() - bytes_written is the bytes you have left to write
            let bytes_to_write = min(
                min(WRITABLE_BYTES - offset, available_bytes),
                (buf.len() - bytes_written) as u64,
            );

            let object_ptr = if object_window == 0 {
                binding.handle.start()
            } else {
                // If the object is already mapped, return it's pointer
                if let Some(new_handle) = binding.map.get(&object_window) {
                    new_handle.start()
                }
                // Otherwise check the direct map, if the ID is valid then map it, otherwise create
                // the object, store it, then map it.
                else {
                    let obj_id =
                        ((unsafe { *metadata_handle }).direct)[(object_window - 1) as usize];

                    let flags = MapFlags::READ | MapFlags::WRITE;

                    let mapped_id = if obj_id == 0.into() {
                        let create = ObjectCreate::new(
                            BackingType::Normal,
                            LifetimeType::Volatile,
                            None,
                            ObjectCreateFlags::empty(),
                        );
                        let new_id = sys_object_create(create, &[], &[]).unwrap();
                        unsafe {
                            (*metadata_handle).direct[(object_window - 1) as usize] = new_id;
                        }
                        new_id
                    } else {
                        obj_id
                    };

                    let handle = self.map_object(mapped_id, flags).unwrap();
                    binding.map.push(object_window, handle.clone());

                    handle.start()
                }
            };

            unsafe {
                object_ptr
                    .offset(
                        NULLPAGE_SIZE as isize
                            + size_of::<FileMetadata>() as isize
                            + offset as isize,
                    )
                    .copy_from(
                        buf.as_ptr().offset(bytes_written as isize),
                        (bytes_to_write) as usize,
                    )
            }
            binding.pos += bytes_to_write as u64;
            unsafe { ((*metadata_handle).size) = max(binding.pos, (*metadata_handle).size) };
            bytes_written += bytes_to_write as usize;
        }

        Ok(bytes_written)
    }

    pub fn close(&self, fd: RawFd) -> Option<()> {
        let file_desc = get_fd_slots().lock().remove(fd.try_into().unwrap())?;

        Some(())
    }

    pub fn seek(&self, fd: RawFd, pos: SeekFrom) -> Result<usize, IoError> {
        let binding = get_fd_slots().lock();
        let file_desc = binding
            .get(fd.try_into().unwrap())
            .ok_or(IoError::InvalidDesc)?;

        let FdKind::File(file_desc) = &file_desc else {
            return Err(IoError::SeekError);
        };

        let mut binding = file_desc.lock();

        let metadata_handle = unsafe {
            &mut *binding
                .handle
                .start()
                .offset(NULLPAGE_SIZE as isize)
                .cast::<FileMetadata>()
        };

        let new_pos: i64 = match pos {
            SeekFrom::Start(x) => x as i64,
            SeekFrom::End(x) => (metadata_handle.size as i64) - x,
            SeekFrom::Current(x) => (binding.pos as i64) + x,
        };

        if new_pos < 0 {
            Err(IoError::SeekError)
        } else {
            binding.pos = new_pos as u64;
            Ok(binding.pos.try_into().unwrap())
        }
    }
}