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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#![no_std]

//! This crate contains the direcotires and files that comprise the taskfs, which is similar
//! to the /proc directory in linux. There are four main sections in this code:
//! 1) TaskFs: the top level directory that holds the individual TaskDirs
//! 2) TaskDir: the lazily computed directory that contains files and directories 
//!     relevant to that task
//! 3) TaskFile: lazily computed file that holds information about the task
//! 4) MmiDir: lazily computed directory that holds subdirectories and files
//!     about the task's memory management information
//! 5) MmiFile: lazily computed file that contains information about the task's
//!     memory management information
//! 
//! * Note that all the structs here are NOT persistent in the filesystem EXCEPT
//! for the TaskFs struct, which contains all the individual TaskDirs. This means 
//! that when a terminal cd's into a TaskDir or one of the subdirectories, it is the 
//! only entity that has a reference to that directory. When the terminal drops that 
//! reference (i.e. backs out of the directory), that directory is dropped from scope
//! 
//! The hierarchy (tree) is as follows:
//! 
//!             TaskDir
//!         TaskFile    MmiDir
//!                         MmiFile
//! 

#[macro_use] extern crate alloc;
#[macro_use] extern crate log;

extern crate spin;
extern crate fs_node;
extern crate memory;
extern crate task;
extern crate path;
extern crate root;
extern crate io;

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use spin::Mutex;
use alloc::sync::Arc;
use fs_node::{DirRef, WeakDirRef, Directory, FileOrDir, File, FileRef, FsNode};
use memory::MappedPages;
use task::WeakTaskRef;
use path::{Path, PathBuf};
use io::{ByteReader, ByteWriter, KnownLength, IoError};


/// The name of the VFS directory that exposes task info in the root. 
pub const TASKS_DIRECTORY_NAME: &str = "tasks";
/// The absolute path of the tasks directory, which is currently below the root
pub const TASKS_DIRECTORY_PATH: &str = "/tasks"; 


/// Initializes the tasks virtual filesystem directory within the root directory.
pub fn init() -> Result<(), &'static str> {
    TaskFs::create()?;
    Ok(())
}


/// The top level directory that includes a dynamically-generated list of all `Task`s,
/// each comprising a `TaskDir`.
/// This directory exists in the root directory.
pub struct TaskFs { }

impl TaskFs {
    fn create() -> Result<DirRef, &'static str> {
        let root = root::get_root();
        let dir_ref = Arc::new(Mutex::new(TaskFs { })) as DirRef;
        root.lock().insert(FileOrDir::Dir(dir_ref.clone()))?;
        Ok(dir_ref)
    }

    fn get_self_pointer(&self) -> Option<DirRef> {
        root::get_root().lock().get_dir(&self.get_name())
    }

    fn get_internal(&self, node: &str) -> Result<FileOrDir, &'static str> {
        let id = node.parse::<usize>().map_err(|_e| "could not parse Task ID as usize")?;
        let task_ref = task::get_task(id).ok_or("No task existed for Task ID")?;
        let parent_dir = self.get_self_pointer().ok_or("BUG: tasks directory wasn't in root")?;
        let dir_name = id.to_string(); 
        // lazily compute a new TaskDir everytime the caller wants to get a TaskDir
        let task_dir = TaskDir::new(dir_name, &parent_dir, id, task_ref)?;        
        let boxed_task_dir = Arc::new(Mutex::new(task_dir)) as DirRef;
        Ok(FileOrDir::Dir(boxed_task_dir))
    }
}

impl FsNode for TaskFs {
    fn get_absolute_path(&self) -> String {
        String::from(TASKS_DIRECTORY_PATH)
    }

    fn get_name(&self) -> String {
        String::from(TASKS_DIRECTORY_NAME)
    }

    fn get_parent_dir(&self) -> Option<DirRef> {
        Some(root::get_root().clone())
    }

    fn set_parent_dir(&mut self, _new_parent: WeakDirRef) {
        // do nothing
    }
}

impl Directory for TaskFs {
    /// This function adds a newly created fs node (the argument) to the TASKS directory's children map  
    fn insert(&mut self, _node: FileOrDir) -> Result<Option<FileOrDir>, &'static str> {
        Err("cannot insert node into read-only TaskFs")
    }

    fn get(&self, node: &str) -> Option<FileOrDir> {
        match self.get_internal(node) {
            Ok(d) => Some(d),
            Err(e) => {
                error!("TaskFs::get() error: {:?}", e);
                None
            }
        }
    }

    /// Returns a string listing all the children in the directory
    fn list(&self) -> Vec<String> {
        let mut tasks_string = Vec::new();
        for (id, _taskref) in task::all_tasks() {
            tasks_string.push(format!("{id}"));
        }
        tasks_string
    }

    fn remove(&mut self, _node: &FileOrDir) -> Option<FileOrDir> {
        None
    }

}




/// A lazily computed directory that holds files and subdirectories related
/// to information about this Task
pub struct TaskDir {
    /// The name of the directory
    pub name: String,
    /// The absolute path of the TaskDir
    path: PathBuf,
    task_id: usize,
    taskref: WeakTaskRef,
    /// We can store the parent (TaskFs) because it is a persistent directory
    parent: DirRef,
}

impl TaskDir {
    /// Creates a new directory and passes a pointer to the new directory created as output
    pub fn new(
        name: String,
        parent: &DirRef,
        task_id: usize,
        taskref: WeakTaskRef,
    ) -> Result<TaskDir, &'static str> {
        let directory = TaskDir {
            name,
            path: PathBuf::from(format!("{TASKS_DIRECTORY_PATH}/{task_id}")),
            task_id,
            taskref,
            parent: Arc::clone(parent),
        };
        Ok(directory)
    }
}

impl Directory for TaskDir {
    fn insert(&mut self, _node: FileOrDir) -> Result<Option<FileOrDir>, &'static str> {
        Err("cannot insert node into read-only TaskFs")
    }

    fn get(&self, child_name: &str) -> Option<FileOrDir> {
        if child_name == "taskInfo" {
            let task_file = TaskFile::new(self.task_id, self.taskref.clone());
            return Some(FileOrDir::File(Arc::new(Mutex::new(task_file)) as FileRef));
        }

        if child_name == "mmi" {
            let mmi_dir = MmiDir::new(self.task_id, self.taskref.clone());
            return Some(FileOrDir::Dir(Arc::new(Mutex::new(mmi_dir)) as DirRef));
        }

        None
    }

    /// Returns a string listing all the children in the directory
    fn list(&self) -> Vec<String> {
        let children = vec!["mmi".to_string(), "taskInfo".to_string()];
        children
    }

    fn remove(&mut self, _: &FileOrDir) -> Option<FileOrDir> { 
        None
    }
}

impl FsNode for TaskDir {
    fn get_absolute_path(&self) -> String {
        self.path.clone().into()
    }

    fn get_name(&self) -> String {
        self.name.clone()
    }

    fn get_parent_dir(&self) -> Option<DirRef> {
        Some(self.parent.clone())
    }

    fn set_parent_dir(&mut self, _: WeakDirRef) {
        // do nothing
    }
}



/// Lazily computed file that holds information about this task. This taskfile
/// does not exist witin the actual filesystem. 
pub struct TaskFile {
    taskref: WeakTaskRef,
    task_id: usize,
    path: PathBuf, 
}

impl TaskFile {
    pub fn new(task_id: usize, taskref: WeakTaskRef) -> TaskFile {
        TaskFile {
            taskref,
            task_id,
            path: PathBuf::from(format!("{TASKS_DIRECTORY_PATH}/{task_id}/task_info")), 
        }
    }

    /// Generates the task info string.
    fn generate(&self) -> String {
        let Some(taskref) = self.taskref.upgrade() else {
            return String::from("Task Not Found");
        };

        // Print all tasks
        let cpu = taskref.running_on_cpu().map(|cpu| format!("{cpu}")).unwrap_or_else(|| String::from("-"));
        let pinned = &taskref.pinned_cpu().map(|pin| format!("{pin}")).unwrap_or_else(|| String::from("-"));
        let task_type = if taskref.is_an_idle_task {
            "I"
        } else if taskref.is_application() {
            "A"
        } else {
            " "
        };  

        format!("{0:<10} {1}\n{2:<10} {3}\n{4:<10} {5:?}\n{6:<10} {7}\n{8:<10} {9}\n{10:<10} {11:<10}", 
            "name", taskref.name,
            "task id", taskref.id,
            "runstate", taskref.runstate(),
            "cpu", cpu,
            "pinned", pinned,
            "task type", task_type
        )
    }
}

impl FsNode for TaskFile {
    fn get_absolute_path(&self) -> String {
        self.path.clone().into()
    }

    fn get_name(&self) -> String {
        self.taskref.upgrade().map_or_else(
            || String::from("Task Not Found"),
            |taskref| taskref.name.clone(),
        )
    }

    fn get_parent_dir(&self) -> Option<DirRef> {
        let path = PathBuf::from(format!("{}/{}", TASKS_DIRECTORY_PATH, self.task_id));
        match Path::get_absolute(&path) {
            Some(FileOrDir::Dir(d)) => Some(d),
            _ => None,
        }
    }

    fn set_parent_dir(&mut self, _: WeakDirRef) {
        // do nothing
    }
}

impl ByteReader for TaskFile {
    fn read_at(&mut self, buf: &mut [u8], offset: usize) -> Result<usize, IoError> {
        let output = self.generate();
        if offset > output.len() {
            return Err(IoError::InvalidInput);
        }
        let count = core::cmp::min(buf.len(), output.len() - offset);
        buf[..count].copy_from_slice(&output.as_bytes()[offset..(offset + count)]);
        Ok(count)
    }
}

impl ByteWriter for TaskFile {
    fn write_at(&mut self, _buffer: &[u8], _offset: usize) -> Result<usize, IoError> {
        Err(IoError::from("not permitted to write task contents through the task VFS"))
    } 
    fn flush(&mut self) -> Result<(), IoError> { Ok(()) }
}

impl KnownLength for TaskFile {
    fn len(&self) -> usize {
        self.generate().len() 
    }
}

impl File for TaskFile {
    fn as_mapping(&self) -> Result<&MappedPages, &'static str> {
        Err("task files are autogenerated, cannot be memory mapped")
    }
}






/// Lazily computed directory that contains subfiles and directories 
/// relevant to the task's memory management information. 
pub struct MmiDir {
    taskref: WeakTaskRef,
    task_id: usize,
    path: PathBuf, 
}

impl MmiDir {
    /// Creates a new directory and passes a pointer to the new directory created as output
    pub fn new(task_id: usize, taskref: WeakTaskRef) -> MmiDir {
        MmiDir {
            taskref,
            task_id,
            path: PathBuf::from(format!("{TASKS_DIRECTORY_PATH}/{task_id}/mmi")),
        }
    }
}

impl Directory for MmiDir {
    fn insert(&mut self, _node: FileOrDir) -> Result<Option<FileOrDir>, &'static str> {
        Err("cannot insert node into read-only TaskFs")
    }

    fn get(&self, child_name: &str) -> Option<FileOrDir> {
        if child_name == "MmiInfo" {
            // create the new mmi dir here on demand
            let task_file = MmiFile::new(self.task_id, self.taskref.clone());
            Some(FileOrDir::File(Arc::new(Mutex::new(task_file)) as FileRef))
        } else {
            None
        }
    }

    /// Returns a string listing all the children in the directory
    fn list(&self) -> Vec<String> {
        let children = vec!["MmiInfo".to_string()];
        children
    }

    fn remove(&mut self, _: &FileOrDir) -> Option<FileOrDir> {
        None
    }
}

impl FsNode for MmiDir {
    fn get_absolute_path(&self) -> String {
        self.path.clone().into()
    }
    
    fn get_name(&self) -> String {
        "mmi".to_string()
    }

    fn get_parent_dir(&self) -> Option<DirRef> {
        let path = PathBuf::from(format!("{}/{}", TASKS_DIRECTORY_PATH, self.task_id));
        match Path::get_absolute(&path) {
            Some(FileOrDir::Dir(d)) => Some(d),
            _ => None,
        }
    }

    fn set_parent_dir(&mut self, _: WeakDirRef) {
        // do nothing
    }
}



/// Lazily computed file that contains information 
/// about a task's memory management information. 
pub struct MmiFile {
    taskref: WeakTaskRef,
    task_id: usize,
    path: PathBuf, 
}

impl MmiFile {
    pub fn new(task_id: usize, taskref: WeakTaskRef) -> MmiFile {
        MmiFile {
            taskref,
            task_id,
            path: PathBuf::from(format!("{TASKS_DIRECTORY_PATH}/{task_id}/mmi/MmiInfo")), 
        }
    }

    /// Generates the mmi info string.
    fn generate(&self) -> String {
        if let Some(taskref) = self.taskref.upgrade() {
            format!("Page table: {:?}\n", taskref.mmi.lock().page_table)
        } else {
            String::from("Task Not Found")
        }
    }
}

impl FsNode for MmiFile {
    fn get_absolute_path(&self) -> String {
        self.path.clone().into()
    }

    fn get_name(&self) -> String {
        "MmiInfo".to_string()
    }

    fn get_parent_dir(&self) -> Option<DirRef> {
        let path = PathBuf::from(format!("{}/{}/mmi", TASKS_DIRECTORY_PATH, self.task_id));
        match Path::get_absolute(&path) {
            Some(FileOrDir::Dir(d)) => Some(d),
            _ => None,
        }
    }

    fn set_parent_dir(&mut self, _: WeakDirRef) {
        // do nothing
    }
}

impl ByteReader for MmiFile {
    fn read_at(&mut self, buf: &mut [u8], offset: usize) -> Result<usize, IoError> {
        let output = self.generate();
        if offset > output.len() {
            return Err(IoError::InvalidInput);
        }
        let count = core::cmp::min(buf.len(), output.len() - offset);
        buf[..count].copy_from_slice(&output.as_bytes()[offset..(offset + count)]);
        Ok(count)
    }
}

impl ByteWriter for MmiFile {
    fn write_at(&mut self, _buffer: &[u8], _offset: usize) -> Result<usize, IoError> {
        Err(IoError::from("not permitted to write task contents through the task VFS"))
    } 
    fn flush(&mut self) -> Result<(), IoError> { Ok(()) }
}

impl KnownLength for MmiFile {
    fn len(&self) -> usize {
        self.generate().len() 
    }
}

impl File for MmiFile {
    fn as_mapping(&self) -> Result<&MappedPages, &'static str> {
        Err("task files are autogenerated, cannot be memory mapped")
    }
}