From 02c0a70a3036a3583fb25f10e76aeeb01350b60b Mon Sep 17 00:00:00 2001 From: Michael Shaw Date: Wed, 21 Aug 2024 15:44:50 -0400 Subject: [PATCH] vfs: refcount file structs used in fdescs --- fs/vfs.c | 1 + include/fs/vfs.h | 3 +++ sched/proc.c | 14 +++++++++++--- sched/syscall.c | 4 ++++ usr.bin/shtest/shtest.c | 4 +++- 5 files changed, 22 insertions(+), 4 deletions(-) diff --git a/fs/vfs.c b/fs/vfs.c index 7567827..3481ae4 100644 --- a/fs/vfs.c +++ b/fs/vfs.c @@ -65,6 +65,7 @@ struct file *vfs_open(const char *pathname, int *err) { /* allocate a file */ struct file *file = slab_alloc(file_slab); + if (!file) { kprintf(LOG_ERROR "Failed to allocate file struct\n"); return NULL; diff --git a/include/fs/vfs.h b/include/fs/vfs.h index adb5f07..37e7bf0 100644 --- a/include/fs/vfs.h +++ b/include/fs/vfs.h @@ -91,6 +91,9 @@ struct dirent { struct file { struct vnode *vnode; + spinlock_t ref_lock; + uint64_t refcount; + ino_t ino_num; /* inode number */ uint32_t type; /* type of the file */ uint64_t size; /* size of the file */ diff --git a/sched/proc.c b/sched/proc.c index 0cc089c..3ac547d 100644 --- a/sched/proc.c +++ b/sched/proc.c @@ -84,12 +84,15 @@ void proc_term(pid_t pid) { struct rbnode *proc_node = rbt_search(proc_tree, pid); + struct proc_block_node *cur = proc_block_queue->head; + + struct proc_block_node *next; while (cur) { if (cur->proc->pid == pid) { + next = cur->next; proc_block_remove(cur); - cur = cur->next; - kfree(cur); + cur = next; continue; } @@ -113,7 +116,12 @@ void proc_term(pid_t pid) while (node) { struct rbnode *next = rbt_successor(node); struct file_descriptor *fdesc = (void *)node->value; - vfs_close(fdesc->file); + + spinlock_acquire(&fdesc->file->ref_lock); + fdesc->file->refcount--; + if (fdesc->file->refcount == 0) + vfs_close(fdesc->file); + spinlock_release(&fdesc->file->ref_lock); slab_free(fd_slab, fdesc); node = next; } diff --git a/sched/syscall.c b/sched/syscall.c index d69093b..f9e4eb8 100644 --- a/sched/syscall.c +++ b/sched/syscall.c @@ -126,6 +126,10 @@ int sys_open(const char *pathname, int flags) fdesc->pos = 0; fdesc->flags = flags; + spinlock_acquire(&file->ref_lock); + file->refcount++; + spinlock_release(&file->ref_lock); + struct rbnode *node = rbt_insert(&proc->fd_map, fdno); node->value = (uintptr_t)fdesc; diff --git a/usr.bin/shtest/shtest.c b/usr.bin/shtest/shtest.c index ccaff83..078c4e9 100644 --- a/usr.bin/shtest/shtest.c +++ b/usr.bin/shtest/shtest.c @@ -38,7 +38,9 @@ void _start() write(fd, "attempting to fork\n", 19); if (fork() == 0) { write(fd, "child\n", 6); - exit(0); + + while (1) + ; } else { write(fd, "parent\n", 7); }