git: 58d317169834 - main - Add fget_remote()

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Wed, 24 Jan 2024 05:12:14 UTC
The branch main has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=58d3171698341c664d7c676541b86385a924ae93

commit 58d3171698341c664d7c676541b86385a924ae93
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2024-01-22 22:31:55 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2024-01-24 05:11:26 +0000

    Add fget_remote()
    
    The function holds and returns struct file for a file descriptor index
    in the given process.
    
    Reviewed by:    brooks, markj
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D43518
---
 sys/kern/kern_descrip.c | 32 ++++++++++++++++++++++++++++++++
 sys/sys/file.h          |  1 +
 2 files changed, 33 insertions(+)

diff --git a/sys/kern/kern_descrip.c b/sys/kern/kern_descrip.c
index a0130842aacb..e8e08f57196b 100644
--- a/sys/kern/kern_descrip.c
+++ b/sys/kern/kern_descrip.c
@@ -2960,6 +2960,38 @@ fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
 }
 #endif
 
+int
+fget_remote(struct thread *td, struct proc *p, int fd, struct file **fpp)
+{
+	struct filedesc *fdp;
+	struct file *fp;
+	int error;
+
+	if (p == td->td_proc)	/* curproc */
+		return (fget_unlocked(td, fd, &cap_no_rights, fpp));
+
+	PROC_LOCK(p);
+	fdp = fdhold(p);
+	PROC_UNLOCK(p);
+	if (fdp == NULL)
+		return (ENOENT);
+	FILEDESC_SLOCK(fdp);
+	if (refcount_load(&fdp->fd_refcnt) != 0) {
+		fp = fget_noref(fdp, fd);
+		if (fp != NULL && fhold(fp)) {
+			*fpp = fp;
+			error = 0;
+		} else {
+			error = EBADF;
+		}
+	} else {
+		error = ENOENT;
+	}
+	FILEDESC_SUNLOCK(fdp);
+	fddrop(fdp);
+	return (error);
+}
+
 #ifdef CAPABILITIES
 int
 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
diff --git a/sys/sys/file.h b/sys/sys/file.h
index 0bdf7e9baa7b..83da5105ad2b 100644
--- a/sys/sys/file.h
+++ b/sys/sys/file.h
@@ -261,6 +261,7 @@ int fget_write(struct thread *td, int fd, cap_rights_t *rightsp,
 int fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp,
     int needfcntl, struct file **fpp);
 int _fdrop(struct file *fp, struct thread *td);
+int fget_remote(struct thread *td, struct proc *p, int fd, struct file **fpp);
 
 fo_rdwr_t	invfo_rdwr;
 fo_truncate_t	invfo_truncate;