All PIDs after we fork init(8) are random. This has been the case for over 8 years:
https://cvsweb.openbsd.org/src/sys/kern/init_main.c?rev=1.193&content-type=text/x-cvsweb-markup Are we keeping this "randompid" global around to make it possible to disable random PIDs by toggling it in ddb(4)? Maybe we need it because some future platform might have difficulty gathering the necessary entropy before this point in the kernel main()? ... or can we just remove it like this? ok? Index: sys/proc.h =================================================================== RCS file: /cvs/src/sys/sys/proc.h,v retrieving revision 1.330 diff -u -p -r1.330 proc.h --- sys/proc.h 13 May 2022 15:32:00 -0000 1.330 +++ sys/proc.h 16 Jun 2022 00:18:13 -0000 @@ -499,7 +499,6 @@ extern struct proc proc0; /* Process sl extern struct process process0; /* Process slot for kernel threads. */ extern int nprocesses, maxprocess; /* Cur and max number of processes. */ extern int nthreads, maxthread; /* Cur and max number of threads. */ -extern int randompid; /* fork() should create random pid's */ LIST_HEAD(proclist, proc); LIST_HEAD(processlist, process); Index: kern/init_main.c =================================================================== RCS file: /cvs/src/sys/kern/init_main.c,v retrieving revision 1.315 diff -u -p -r1.315 init_main.c --- kern/init_main.c 22 Feb 2022 01:15:01 -0000 1.315 +++ kern/init_main.c 16 Jun 2022 00:18:13 -0000 @@ -431,8 +431,6 @@ main(void *framep) initprocess = initproc->p_p; } - randompid = 1; - /* * Create any kernel threads whose creation was deferred because * initprocess had not yet been created. Index: kern/kern_fork.c =================================================================== RCS file: /cvs/src/sys/kern/kern_fork.c,v retrieving revision 1.240 diff -u -p -r1.240 kern_fork.c --- kern/kern_fork.c 13 May 2022 15:32:00 -0000 1.240 +++ kern/kern_fork.c 16 Jun 2022 00:18:13 -0000 @@ -67,7 +67,6 @@ int nprocesses = 1; /* process 0 */ int nthreads = 1; /* proc 0 */ -int randompid; /* when set to 1, pid's go random */ struct forkstat forkstat; void fork_return(void *); @@ -638,20 +637,22 @@ ispidtaken(pid_t pid) pid_t allocpid(void) { - static pid_t lastpid; + static int first = 1; pid_t pid; - if (!randompid) { - /* only used early on for system processes */ - pid = ++lastpid; - } else { - /* Find an unused pid satisfying lastpid < pid <= PID_MAX */ - do { - pid = arc4random_uniform(PID_MAX - lastpid) + 1 + - lastpid; - } while (ispidtaken(pid)); + /* The first PID allocated is always 1. */ + if (__predict_false(first)) { + first = 0; + return 1; } + /* + * All subsequent PIDs are chosen randomly. We need to + * find an unused PID in the range [2, PID_MAX]. + */ + do { + pid = arc4random_uniform(PID_MAX - 1) + 2; + } while (ispidtaken(pid)); return pid; }
