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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Channel and mount space.

use crate::{
    dev::Device,
    error::{Error, Result},
    vm::VmObject,
};
use alloc::{
    sync::{Arc, Weak},
    vec::Vec,
};
use core::{convert::TryFrom, fmt::Debug, iter, mem::MaybeUninit, str};
use kalloc::wrapper::vec_push;
use ksched::{
    sync::{Mutex, RwLock},
    task::yield_now,
};

/// File type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChanKind {
    /// Directory.
    Dir,
    /// Plain file.
    File,
}

/// Permission control on a file.
pub enum Perm {
    /// Execute, == read but check execute permission.
    EXEC,
    /// Read-only.
    READ,
    /// Write-only.
    WRITE,
    /// Read and write.
    RDWR,
}

/// Machine-independent directory entry.
///
/// A directory entry represents information of a file(or directory file).
/// Timestamps are measured in seconds since the epoch(Jan 1 00:00 1970 GMT).
pub struct Dirent {
    /// Length of file in bytes. Cannot changed by a wstat.
    pub len: u64,
    /// Timestamp of last change of the content.
    ///
    /// For a plain file, mtime is the time of the most recent create, open with truncation, or
    /// write; for a directory it is the time of the most recent remove, create, or wstat of a
    /// file in the directory.
    ///
    /// It can be changed by the owner of the file or the group leader of the file's current group.
    pub mtime: u32,
    /// Timestamp of last read of the content. Cannot changed by a wstat.
    ///
    /// It's also set whenever mtime is set. In addition, for a directory, it is set by an attach,
    /// walk, or create, all whether successful or not.
    pub atime: u32,
}

#[derive(Copy, Clone, Debug)]
/// File identification within a device, analogous to the i-number.
pub struct ChanId {
    /// The path is a unique file number assigned by a device driver or file server when
    /// a file is created.
    /// This can also used to determine whether a PnP device has been removed.
    pub path: u64,
    /// The version number is updated whenever the file is modified, which can be used­ ­
    /// to maintain cache coherency between clients and servers.
    pub version: u32,
    /// Type of the file.
    pub kind: ChanKind,
}

/// A key representing one client handle of the file.
/// Basically, it's used to check if we have forgotten to close a file.
pub struct ChanKey {
    /// Which driver to used for this channel, analogous to UNIX's major number.
    dev: Arc<dyn Device + Send + Sync>,
    id: ChanId,

    /// To check if we have close the channel.
    /// FIXME: Once we have async drop in Rust, it can be removed.
    dropped: bool,
}

impl ChanKey {
    async fn dup(&self) -> Result<ChanKey> {
        self.dev.open(&self.id, b"", None)?.await?.map_or(
            Err(Error::Gone("failed to rekey")),
            |id| {
                Ok(ChanKey {
                    dev: self.dev.clone(),
                    id,
                    dropped: false,
                })
            },
        )
    }

    /// FIXME: pre-allocate the future on creation.
    async fn close(mut self) {
        self.dropped = true;
        loop {
            if let Ok(f) = self.dev.close(self.id) {
                f.await;
                break;
            }
            yield_now().await;
        }
    }
}

impl Debug for ChanKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ChanKey")
            .field("id", &self.id)
            .field("dropped", &self.dropped)
            .finish()
    }
}

impl Drop for ChanKey {
    /// Use [`Self::close`] instead, since Rust doesn't support async drop.
    ///
    /// FIXME: How to statically assert some function is unreachable?
    fn drop(&mut self) {
        assert!(self.dropped, "forgot to close: {:?}", self);
    }
}

/// Channel represents a virtual file from kernel's perspective.
#[derive(Debug)]
pub struct Chan {
    key: ChanKey,
    parent: Option<Arc<Chan>>,
    name: Vec<u8>,

    /// Union mount point that derives Chan.
    /// Use ChanKey instead of Chan to avoid cycle in the graph.
    umnt: RwLock<Vec<ChanKey>>,
    /// The weak pointer must be able to upgrade.
    child: Mutex<Vec<Weak<Chan>>>,

    /// Managing all memory mapped pages from this chan.
    pub(crate) vmobj: VmObject,
}

impl Chan {
    /// Create a new mount space from the root of a device.
    pub async fn attach(dev: Arc<dyn Device + Send + Sync>, aname: &[u8]) -> Result<Arc<Self>> {
        let mut name = Vec::new();
        name.try_reserve(aname.len())?;
        for x in aname {
            name.push(*x);
        }
        let a = Arc::<Chan>::try_new_uninit()?;
        let id = dev.clone().attach(aname)?.await?;
        let key = ChanKey {
            dev,
            id,
            dropped: false,
        };
        Ok(unsafe { Self::new1(key, None, a) })
    }

    /// Get the absolute path string of this chan.
    pub async fn path(self: &Arc<Chan>) -> Result<Vec<u8>> {
        let name1 = |u: &Arc<Chan>| -> Result<Vec<u8>> {
            let mut buf = Vec::new();
            for b in &u.name {
                vec_push(&mut buf, *b)?;
            }
            Ok(buf)
        };
        let mut u = self.clone();
        let mut ret = Vec::new();
        while let Some(fa) = &u.parent {
            let name = name1(&u)?;
            for b in name.iter().rev() {
                vec_push(&mut ret, *b)?;
            }
            u = fa.clone();
        }
        vec_push(&mut ret, b'/')?;
        ret.reverse();
        Ok(ret)
    }

    /// Create a new mount space rooted at a chan.
    pub async fn new(chan: &Arc<Chan>) -> Result<Arc<Self>> {
        let a = Arc::<Chan>::try_new_uninit()?;
        let key = chan.key.dup().await?;
        Ok(unsafe { Self::new1(key, None, a) })
    }

    unsafe fn new1(
        key: ChanKey,
        parent: Option<Arc<Chan>>,
        mut a: Arc<MaybeUninit<Chan>>,
    ) -> Arc<Self> {
        Arc::get_mut_unchecked(&mut a).as_mut_ptr().write(Self {
            parent,
            umnt: RwLock::new(Vec::new()),
            child: Mutex::new(Vec::new()),
            key,
            name: Vec::new(),
            vmobj: VmObject::new(),
        });
        a.assume_init()
    }

    /// Mount directory to this chan.
    ///
    /// This will mount all union directories from old to this chan.
    pub async fn mount(&self, old: &Arc<Self>) -> Result<()> {
        if !(self.is_dir() && old.is_dir()) {
            return Err(Error::BadRequest("cannot mount file"));
        }

        let mut umnt = Vec::new();
        let result = async {
            let g = old.umnt.read().await;
            umnt.try_reserve(g.len() + 1)?;
            for key in iter::once(&old.key).chain(g.iter()) {
                umnt.push(key.dup().await?);
            }
            drop(g);

            let mut g = self.umnt.write().await;
            g.try_reserve(umnt.len())?;
            umnt.reverse();
            while let Some(k) = umnt.pop() {
                g.push(k);
            }
            Ok(())
        }
        .await;

        while let Some(key) = umnt.pop() {
            key.close().await;
        }
        result
    }

    /// Bind file to this chan.
    ///
    /// Drop any previously bound chan.
    pub async fn bind(&self, old: &Arc<Self>) -> Result<()> {
        if self.is_dir() || old.is_dir() {
            return Err(Error::BadRequest("cannot bind dir"));
        }
        let mut g = self.umnt.write().await;
        if g.is_empty() {
            g.try_reserve(1)?;
        }
        let key = old.key.dup().await?;
        if let Some(key) = g.pop() {
            key.close().await;
        }
        g.push(key);
        debug_assert_eq!(g.len(), 1);
        Ok(())
    }

    /// Remove all mount point of this chan.
    pub async fn clear_mount(&self) {
        let mut g = self.umnt.write().await;
        while let Some(key) = g.pop() {
            key.close().await;
        }
    }

    /// Caller should guarantee `name` is non-empty.
    async fn open1(
        self: &Arc<Self>,
        name: &[u8],
        create_dir: Option<bool>,
    ) -> Result<Option<Arc<Chan>>> {
        debug_assert_eq!(name.is_empty(), false);
        if !self.is_dir() {
            return Ok(None);
        }

        let mut child = self.child.lock().await;
        for u in child.iter() {
            let u = u.upgrade().unwrap();
            if u.name == name {
                return Ok(Some(u.clone()));
            }
        }

        // Pre allocation.
        let mut names = Vec::new();
        for x in name {
            vec_push(&mut names, *x)?;
        }
        child.try_reserve(1)?;
        let a = Arc::<Self>::try_new_uninit()?;

        let mut some_chan = None;
        let g = self.umnt.read().await;
        for key in iter::once(&self.key).chain(g.iter()) {
            debug_assert_eq!(key.id.kind, ChanKind::Dir);
            if let Some(id) = key.dev.open(&key.id, name, create_dir)?.await? {
                let u = unsafe {
                    Self::new1(
                        ChanKey {
                            dev: key.dev.clone(),
                            id,
                            dropped: false,
                        },
                        Some(self.clone()),
                        a,
                    )
                };
                some_chan = Some(u);
                break;
            }
        }
        Ok(some_chan.map(|c| {
            child.push(Arc::<Self>::downgrade(&c));
            c
        }))
    }

    /// Open a file located at path starting from this chan.
    ///
    /// Return [NotFound](Error::NotFound) if failed to find any directory components within the path.
    /// Otherwise it can find the parent directory.
    pub async fn open(
        self: &Arc<Self>,
        path: &[u8],
        create_dir: Option<bool>,
    ) -> Result<Option<Arc<Self>>> {
        let path = Path::try_from(path)?;
        let mut cur = self.clone();
        for _ in 0..path.dotdots {
            if let Some(fa) = &cur.parent {
                cur = fa.clone();
            }
        }

        for (i, name) in path.names.iter().enumerate() {
            let last = i == path.names.len() - 1;
            match cur
                .open1(name.as_bytes(), if last { create_dir } else { None })
                .await
            {
                Ok(Some(u)) => {
                    // Since u is the child of cur and chan that has children won't be close.
                    // just drop cur.
                    cur = u;
                }
                Ok(None) => {
                    cur.close().await;
                    return if last {
                        Ok(None)
                    } else {
                        Err(Error::NotFound("failed to find intermediate directory"))
                    };
                }
                Err(e) => {
                    cur.close().await;
                    return Err(e);
                }
            }
        }

        Ok(Some(cur))
    }

    async fn close1(u: Arc<Self>) -> Option<Arc<Self>> {
        let fa = &u.parent;

        let ug = u.child.lock().await;
        let mut fg = if let Some(fa) = fa {
            Some(fa.child.lock().await)
        } else {
            None
        };
        // Once we have locked this node and its parent, the reference count won't
        // decrease(but may be increased by dup) since every close operation also need to
        // enter this function. And if we are the last one, the reference count won't change.
        let last = Arc::<Self>::strong_count(&u) == 1;

        if last {
            assert_eq!(ug.len(), 0);
            while let Some(ck) = u.umnt.try_write().unwrap().pop() {
                ck.close().await;
            }

            if let Some(mut fg) = fg.take() {
                let w = Arc::<Self>::downgrade(&u);
                let i = fg.iter().position(|x| Weak::<Self>::ptr_eq(&w, x)).unwrap();
                fg.swap_remove(i);
            }
            drop(fg);
            drop(ug);

            let c = Arc::<Self>::try_unwrap(u).unwrap();
            c.key.close().await;
            c.parent
        } else {
            None
        }
    }

    /// Close a file. The async destructor.
    pub async fn close(self: Arc<Self>) {
        let mut cur = self;
        while let Some(fa) = Self::close1(cur).await {
            cur = fa;
        }
    }

    /// Duplicate a handle of file.
    pub fn dup(self: &Arc<Self>) -> Arc<Self> {
        self.clone()
    }

    /// Check if this chan is directory.
    /// Chans in umnt are of same type of itself.
    pub fn is_dir(&self) -> bool {
        self.key.id.kind == ChanKind::Dir
    }

    /// Remove wrapper.
    pub async fn remove(&self) -> Result<bool> {
        self.key.dev.remove(&self.key.id)?.await
    }

    /// Stat wrapper.
    pub async fn stat(&self) -> Result<Dirent> {
        todo!()
    }

    /// Wstat wrapper.
    pub async fn wstat(&self, dirent: &Dirent) -> Result<()> {
        todo!()
    }

    /// Read wrapper.
    pub async fn read(&self, buf: &mut [u8], off: usize) -> Result<usize> {
        if self.is_dir() {
            return Err(Error::BadRequest("read dir"));
        }
        off.checked_add(buf.len())
            .ok_or(Error::BadRequest("read buffer len overflow"))?;

        let umnt = self.umnt.read().await;
        let key = umnt.first().unwrap_or(&self.key);
        let ret = key.dev.read(&key.id, buf, off)?.await;
        drop(umnt);
        ret
    }
    /// Write wrapper.
    pub async fn write(&self, buf: &[u8], off: usize) -> Result<usize> {
        if self.is_dir() {
            return Err(Error::BadRequest("write dir"));
        }
        off.checked_add(buf.len())
            .ok_or(Error::BadRequest("write buffer len overflow"))?;

        let umnt = self.umnt.read().await;
        let key = umnt.first().unwrap_or(&self.key);
        let ret = key.dev.write(&key.id, buf, off)?.await;
        drop(umnt);
        ret
    }

    /// Truncate wrapper.
    pub async fn truncate(&self, size: usize) -> Result<usize> {
        if self.is_dir() {
            return Err(Error::BadRequest("truncate dir"));
        }
        let umnt = self.umnt.read().await;
        let key = umnt.first().unwrap_or(&self.key);
        let ret = key.dev.truncate(&key.id, size)?.await;
        drop(umnt);
        ret
    }
}

struct Path<'a> {
    dotdots: usize,
    names: Vec<&'a str>,
}

impl<'a> TryFrom<&'a [u8]> for Path<'a> {
    type Error = Error;

    fn try_from(value: &'a [u8]) -> Result<Self> {
        let path: &str =
            str::from_utf8(value).map_err(|_| Error::BadRequest("path is not valid utf-8"))?;
        let mut dotdots = 0;
        let mut names = Vec::new();

        let mut eat = |name: &'a str| -> Result<()> {
            if name == ".." {
                if names.pop().is_none() {
                    dotdots += 1;
                }
            } else if !name.is_empty() && name != "." {
                vec_push(&mut names, name)?;
            }
            Ok(())
        };

        let mut l = 0;
        for (i, c) in path.char_indices() {
            if c == b'/' as char {
                eat(&path[l..i])?;
                l = i + 1;
            }
        }
        eat(&path[l..path.len()])?;
        Ok(Self { dotdots, names })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_path() {
        let p = Path::try_from("".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names.is_empty(), true);

        let p = Path::try_from("a/b/c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names, &["a", "b", "c"]);

        let p = Path::try_from("a/b/c/".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names, &["a", "b", "c"]);

        let p = Path::try_from("a/b/c////d".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names, &["a", "b", "c", "d"]);

        let p = Path::try_from("a/./b/c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names, &["a", "b", "c"]);

        let p = Path::try_from("a/b/../c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 0);
        assert_eq!(p.names, &["a", "c"]);

        let p = Path::try_from("../a../b/c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 1);
        assert_eq!(p.names, &["a..", "b", "c"]);

        let p = Path::try_from("../a/b/c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 1);
        assert_eq!(p.names, &["a", "b", "c"]);

        let p = Path::try_from("../a/b/../../c".as_bytes()).unwrap();
        assert_eq!(p.dotdots, 1);
        assert_eq!(p.names, &["c"]);
    }
}