From add3e844cf9eaf49010fbee2aa73977086e47428 Mon Sep 17 00:00:00 2001
From: Ian Moffett <ian@osmora.org>
Date: Mon, 25 Mar 2024 21:59:24 -0400
Subject: kernel: filedesc: Return status in fd_alloc()

It is better for fd_alloc() to return the status and have
one of the arguments point to an output than have fd_alloc()
return the allocated file descriptor just like that.

Signed-off-by: Ian Moffett <ian@osmora.org>
---
 sys/include/sys/filedesc.h |  2 +-
 sys/kern/kern_filedesc.c   | 20 +++++++++++++++-----
 sys/kern/kern_sched.c      |  6 +++---
 3 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/sys/include/sys/filedesc.h b/sys/include/sys/filedesc.h
index df30c69..49d8d52 100644
--- a/sys/include/sys/filedesc.h
+++ b/sys/include/sys/filedesc.h
@@ -46,7 +46,7 @@ struct filedesc {
 };
 
 #if defined(_KERNEL)
-struct filedesc *fd_alloc(struct proc *td);
+int fd_alloc(struct proc *td, struct filedesc **fd_out);
 struct filedesc *fd_from_fdnum(const struct proc *td, int fdno);
 void fd_close_fdnum(struct proc *td, int fdno);
 ssize_t write(int fd, const void *buf, size_t count);
diff --git a/sys/kern/kern_filedesc.c b/sys/kern/kern_filedesc.c
index 72f9c06..0037f55 100644
--- a/sys/kern/kern_filedesc.c
+++ b/sys/kern/kern_filedesc.c
@@ -111,9 +111,15 @@ do_write(struct vnode *vp, const char *buf, size_t count)
  * Allocate a file descriptor.
  *
  * @td: Thread to allocate from, NULL for current thread.
+ * @fd_out: Pointer to allocated file descriptor output.
+ *
+ * This routine will create a new file descriptor
+ * table entry.
+ *
+ * Returns 0 on success.
  */
-struct filedesc *
-fd_alloc(struct proc *td)
+int
+fd_alloc(struct proc *td, struct filedesc **fd_out)
 {
     struct filedesc *fd;
 
@@ -131,15 +137,19 @@ fd_alloc(struct proc *td)
         memset(fd, 0, sizeof(struct filedesc));
 
         if (fd == NULL) {
-            return NULL;
+            return -ENOMEM;
         }
 
         fd->fdno = i;
         td->fds[i] = fd;
-        return fd;
+
+        if (fd_out != NULL)
+            *fd_out = fd;
+
+        return 0;
     }
 
-    return NULL;
+    return -EMFILE;
 }
 
 /*
diff --git a/sys/kern/kern_sched.c b/sys/kern/kern_sched.c
index 776aaff..055b11a 100644
--- a/sys/kern/kern_sched.c
+++ b/sys/kern/kern_sched.c
@@ -271,9 +271,9 @@ sched_create_td(uintptr_t rip, char *argvp[], char *envp[], struct auxval auxv,
     processor_init_pcb(td);
 
     /* Allocate standard file descriptors */
-    __assert(fd_alloc(td) != NULL);       /* STDIN */
-    __assert(fd_alloc(td) != NULL);       /* STDOUT */
-    __assert(fd_alloc(td) != NULL);       /* STDERR */
+    __assert(fd_alloc(td, NULL) == 0);       /* STDIN */
+    __assert(fd_alloc(td, NULL) == 0);       /* STDOUT */
+    __assert(fd_alloc(td, NULL) == 0);       /* STDERR */
 
     /* Setup trapframe */
     if (!is_user) {
-- 
cgit v1.2.3