git: eac624207ccf - main - Ensure "init" (PID 1) also executes userret() initially

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Thu, 02 Nov 2023 13:40:04 UTC
The branch main has been updated by markj:

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

commit eac624207ccf3a16225368d226861b06e3631d0d
Author:     Olivier Certner <olce.freebsd@certner.fr>
AuthorDate: 2023-10-10 17:36:20 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2023-11-02 13:30:03 +0000

    Ensure "init" (PID 1) also executes userret() initially
    
    Calling userret() from fork_return() misses the first return to
    userspace of the "init" (PID 1) process.  The latter is indeed created
    by fork1() followed by a call to cpu_fork_kthread_handler() call that
    replaces fork_return() by start_init() as the function to execute after
    fork.
    
    A new process' initial return to userspace in the end always happens
    through returning from fork_exit(), so move userret() there instead to
    fix the omission.
    
    This problem was discovered as part of a revamp of scheduling priorities
    that lead to experimenting with asserting and sometimes resetting
    priorities in sched_userret(), in the course of which the author
    stumbled on panics being triggered only in init() or only in other
    processes, depending on the modifications to sched_userret().  This
    change currently has no practical effect but will have some in the near
    future.
    
    Reviewed by:            markj, kib
    MFC after:              2 weeks
    Sponsored by:           The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D42257
---
 sys/kern/kern_fork.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sys/kern/kern_fork.c b/sys/kern/kern_fork.c
index 3080bd11123d..6127b7f05fe0 100644
--- a/sys/kern/kern_fork.c
+++ b/sys/kern/kern_fork.c
@@ -1170,8 +1170,14 @@ fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
 	}
 	mtx_assert(&Giant, MA_NOTOWNED);
 
+	/*
+	 * Now going to return to userland.
+	 */
+
 	if (p->p_sysent->sv_schedtail != NULL)
 		(p->p_sysent->sv_schedtail)(td);
+
+	userret(td, frame);
 }
 
 /*
@@ -1222,8 +1228,6 @@ fork_return(struct thread *td, struct trapframe *frame)
 	if (!prison_isalive(td->td_ucred->cr_prison))
 		exit1(td, 0, SIGKILL);
 
-	userret(td, frame);
-
 #ifdef KTRACE
 	if (KTRPOINT(td, KTR_SYSRET))
 		ktrsysret(td->td_sa.code, 0, 0);