git: 99a58803f9a3 - main - fdcopy(): properly update fd_freefile when skipping non-copyable fd

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Fri, 30 Oct 2026 19:08:28 UTC
The branch main has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=99a58803f9a306253df36c82f11991bc1e36e5a5

commit 99a58803f9a306253df36c82f11991bc1e36e5a5
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2026-10-30 16:02:34 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2026-10-30 19:07:39 +0000

    fdcopy(): properly update fd_freefile when skipping non-copyable fd
    
    fd_freefile is maintained to fulfill the POSIX guarantee that the lowest
    possible file descriptor is allocated on open.  If we skip copying an
    fd, it is a possible candidate for the lowest index.
    
    First, the file descriptor installed with a kqueue created
    without KQUEUE_CPONFORK missed this handling [*].
    
    Second, fd_freefile should be updated only when the current fd index is
    below it.  A skipped fd above fd_freefile could raise it past a free slot.
    
    PR:     300234 [*]
    Reported by:    Andrea Venturoli <freebsd@netfence.it>
    Reviewed by:    markj
    Fixes:  1265516c5c61 ("struct file: add DFLAG_FORK, indicate copying on fork")
    Fixes:  809f3121be66 ("fd: assign fd_freefile early when copying")
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D61054
---
 sys/kern/kern_descrip.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/sys/kern/kern_descrip.c b/sys/kern/kern_descrip.c
index 80735e0b4c0c..0aafaa8bdb9f 100644
--- a/sys/kern/kern_descrip.c
+++ b/sys/kern/kern_descrip.c
@@ -2644,13 +2644,16 @@ fdcopy(struct filedesc *fdp, struct proc *p1)
 		if ((ops->fo_flags & DFLAG_FORK) != 0 &&
 		    (ofde->fde_flags & UF_FOCLOSE) == 0) {
 			if (ops->fo_fork(newfdp, ofde->fde_file, &fp, p1,
-			    curthread) != 0)
+			    curthread) != 0) {
+				if (newfdp->fd_freefile > i)
+					newfdp->fd_freefile = i;
 				continue;
+			}
 			fork_pass = true;
 		} else if ((ops->fo_flags & DFLAG_PASSABLE) == 0 ||
 		    (ofde->fde_flags & UF_FOCLOSE) != 0 ||
 		    !fhold(ofde->fde_file)) {
-			if (newfdp->fd_freefile == fdp->fd_freefile)
+			if (newfdp->fd_freefile > i)
 				newfdp->fd_freefile = i;
 			continue;
 		}