xref: /openbsd-src/sys/kern/kern_fork.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /*	$OpenBSD: kern_fork.c,v 1.253 2023/10/24 13:20:11 claudio Exp $	*/
2 /*	$NetBSD: kern_fork.c,v 1.29 1996/02/09 18:59:34 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/filedesc.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/proc.h>
46 #include <sys/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/vnode.h>
49 #include <sys/vmmeter.h>
50 #include <sys/acct.h>
51 #include <sys/ktrace.h>
52 #include <sys/sched.h>
53 #include <sys/smr.h>
54 #include <sys/sysctl.h>
55 #include <sys/pool.h>
56 #include <sys/mman.h>
57 #include <sys/ptrace.h>
58 #include <sys/atomic.h>
59 #include <sys/unistd.h>
60 #include <sys/tracepoint.h>
61 
62 #include <sys/syscallargs.h>
63 
64 #include <uvm/uvm.h>
65 #include <machine/tcb.h>
66 
67 int	nprocesses = 1;		/* process 0 */
68 int	nthreads = 1;		/* proc 0 */
69 struct	forkstat forkstat;
70 
71 void fork_return(void *);
72 pid_t alloctid(void);
73 pid_t allocpid(void);
74 int ispidtaken(pid_t);
75 
76 void unveil_copy(struct process *parent, struct process *child);
77 
78 struct proc *thread_new(struct proc *_parent, vaddr_t _uaddr);
79 struct process *process_new(struct proc *, struct process *, int);
80 int fork_check_maxthread(uid_t _uid);
81 
82 void
83 fork_return(void *arg)
84 {
85 	struct proc *p = (struct proc *)arg;
86 
87 	if (p->p_p->ps_flags & PS_TRACED)
88 		psignal(p, SIGTRAP);
89 
90 	child_return(p);
91 }
92 
93 int
94 sys_fork(struct proc *p, void *v, register_t *retval)
95 {
96 	void (*func)(void *) = child_return;
97 	int flags;
98 
99 	flags = FORK_FORK;
100 	if (p->p_p->ps_ptmask & PTRACE_FORK) {
101 		flags |= FORK_PTRACE;
102 		func = fork_return;
103 	}
104 	return fork1(p, flags, func, NULL, retval, NULL);
105 }
106 
107 int
108 sys_vfork(struct proc *p, void *v, register_t *retval)
109 {
110 	return fork1(p, FORK_VFORK|FORK_PPWAIT, child_return, NULL,
111 	    retval, NULL);
112 }
113 
114 int
115 sys___tfork(struct proc *p, void *v, register_t *retval)
116 {
117 	struct sys___tfork_args /* {
118 		syscallarg(const struct __tfork) *param;
119 		syscallarg(size_t) psize;
120 	} */ *uap = v;
121 	size_t psize = SCARG(uap, psize);
122 	struct __tfork param = { 0 };
123 	int error;
124 
125 	if (psize == 0 || psize > sizeof(param))
126 		return EINVAL;
127 	if ((error = copyin(SCARG(uap, param), &param, psize)))
128 		return error;
129 #ifdef KTRACE
130 	if (KTRPOINT(p, KTR_STRUCT))
131 		ktrstruct(p, "tfork", &param, sizeof(param));
132 #endif
133 #ifdef TCB_INVALID
134 	if (TCB_INVALID(param.tf_tcb))
135 		return EINVAL;
136 #endif /* TCB_INVALID */
137 
138 	return thread_fork(p, param.tf_stack, param.tf_tcb, param.tf_tid,
139 	    retval);
140 }
141 
142 /*
143  * Allocate and initialize a thread (proc) structure, given the parent thread.
144  */
145 struct proc *
146 thread_new(struct proc *parent, vaddr_t uaddr)
147 {
148 	struct proc *p;
149 
150 	p = pool_get(&proc_pool, PR_WAITOK);
151 	p->p_stat = SIDL;			/* protect against others */
152 	p->p_runpri = 0;
153 	p->p_flag = 0;
154 
155 	/*
156 	 * Make a proc table entry for the new process.
157 	 * Start by zeroing the section of proc that is zero-initialized,
158 	 * then copy the section that is copied directly from the parent.
159 	 */
160 	memset(&p->p_startzero, 0,
161 	    (caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero);
162 	memcpy(&p->p_startcopy, &parent->p_startcopy,
163 	    (caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy);
164 	crhold(p->p_ucred);
165 	p->p_addr = (struct user *)uaddr;
166 
167 	/*
168 	 * Initialize the timeouts.
169 	 */
170 	timeout_set(&p->p_sleep_to, endtsleep, p);
171 
172 	return p;
173 }
174 
175 /*
176  * Initialize common bits of a process structure, given the initial thread.
177  */
178 void
179 process_initialize(struct process *pr, struct proc *p)
180 {
181 	/* initialize the thread links */
182 	pr->ps_mainproc = p;
183 	TAILQ_INIT(&pr->ps_threads);
184 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
185 	pr->ps_threadcnt = 1;
186 	p->p_p = pr;
187 
188 	/* give the process the same creds as the initial thread */
189 	pr->ps_ucred = p->p_ucred;
190 	crhold(pr->ps_ucred);
191 	/* new thread and new process */
192 	KASSERT(p->p_ucred->cr_refcnt.r_refs >= 2);
193 
194 	LIST_INIT(&pr->ps_children);
195 	LIST_INIT(&pr->ps_orphans);
196 	LIST_INIT(&pr->ps_ftlist);
197 	LIST_INIT(&pr->ps_sigiolst);
198 	TAILQ_INIT(&pr->ps_tslpqueue);
199 
200 	rw_init(&pr->ps_lock, "pslock");
201 	mtx_init(&pr->ps_mtx, IPL_HIGH);
202 
203 	timeout_set_flags(&pr->ps_realit_to, realitexpire, pr,
204 	    KCLOCK_UPTIME, 0);
205 	timeout_set(&pr->ps_rucheck_to, rucheck, pr);
206 }
207 
208 
209 /*
210  * Allocate and initialize a new process.
211  */
212 struct process *
213 process_new(struct proc *p, struct process *parent, int flags)
214 {
215 	struct process *pr;
216 
217 	pr = pool_get(&process_pool, PR_WAITOK);
218 
219 	/*
220 	 * Make a process structure for the new process.
221 	 * Start by zeroing the section of proc that is zero-initialized,
222 	 * then copy the section that is copied directly from the parent.
223 	 */
224 	memset(&pr->ps_startzero, 0,
225 	    (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero);
226 	memcpy(&pr->ps_startcopy, &parent->ps_startcopy,
227 	    (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy);
228 
229 	process_initialize(pr, p);
230 	pr->ps_pid = allocpid();
231 	lim_fork(parent, pr);
232 
233 	/* post-copy fixups */
234 	pr->ps_pptr = parent;
235 	pr->ps_ppid = parent->ps_pid;
236 
237 	/* bump references to the text vnode (for sysctl) */
238 	pr->ps_textvp = parent->ps_textvp;
239 	if (pr->ps_textvp)
240 		vref(pr->ps_textvp);
241 
242 	/* copy unveil if unveil is active */
243 	unveil_copy(parent, pr);
244 
245 	pr->ps_flags = parent->ps_flags &
246 	    (PS_SUGID | PS_SUGIDEXEC | PS_PLEDGE | PS_EXECPLEDGE |
247 	    PS_WXNEEDED | PS_CHROOT);
248 	if (parent->ps_session->s_ttyvp != NULL)
249 		pr->ps_flags |= parent->ps_flags & PS_CONTROLT;
250 
251 	/*
252 	 * Duplicate sub-structures as needed.
253 	 * Increase reference counts on shared objects.
254 	 */
255 	if (flags & FORK_SHAREFILES)
256 		pr->ps_fd = fdshare(parent);
257 	else
258 		pr->ps_fd = fdcopy(parent);
259 	pr->ps_sigacts = sigactsinit(parent);
260 	if (flags & FORK_SHAREVM)
261 		pr->ps_vmspace = uvmspace_share(parent);
262 	else
263 		pr->ps_vmspace = uvmspace_fork(parent);
264 
265 	if (parent->ps_flags & PS_PROFIL)
266 		startprofclock(pr);
267 	if (flags & FORK_PTRACE)
268 		pr->ps_flags |= parent->ps_flags & PS_TRACED;
269 	if (flags & FORK_NOZOMBIE)
270 		pr->ps_flags |= PS_NOZOMBIE;
271 	if (flags & FORK_SYSTEM)
272 		pr->ps_flags |= PS_SYSTEM;
273 
274 	/* mark as embryo to protect against others */
275 	pr->ps_flags |= PS_EMBRYO;
276 
277 	/* Force visibility of all of the above changes */
278 	membar_producer();
279 
280 	/* it's sufficiently inited to be globally visible */
281 	LIST_INSERT_HEAD(&allprocess, pr, ps_list);
282 
283 	return pr;
284 }
285 
286 /* print the 'table full' message once per 10 seconds */
287 struct timeval fork_tfmrate = { 10, 0 };
288 
289 int
290 fork_check_maxthread(uid_t uid)
291 {
292 	/*
293 	 * Although process entries are dynamically created, we still keep
294 	 * a global limit on the maximum number we will create. We reserve
295 	 * the last 5 processes to root. The variable nprocesses is the
296 	 * current number of processes, maxprocess is the limit.  Similar
297 	 * rules for threads (struct proc): we reserve the last 5 to root;
298 	 * the variable nthreads is the current number of procs, maxthread is
299 	 * the limit.
300 	 */
301 	if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) {
302 		static struct timeval lasttfm;
303 
304 		if (ratecheck(&lasttfm, &fork_tfmrate))
305 			tablefull("thread");
306 		return EAGAIN;
307 	}
308 	nthreads++;
309 
310 	return 0;
311 }
312 
313 static inline void
314 fork_thread_start(struct proc *p, struct proc *parent, int flags)
315 {
316 	struct cpu_info *ci;
317 	int s;
318 
319 	SCHED_LOCK(s);
320 	ci = sched_choosecpu_fork(parent, flags);
321 	TRACEPOINT(sched, fork, p->p_tid + THREAD_PID_OFFSET,
322 	    p->p_p->ps_pid, CPU_INFO_UNIT(ci));
323 	setrunqueue(ci, p, p->p_usrpri);
324 	SCHED_UNLOCK(s);
325 }
326 
327 int
328 fork1(struct proc *curp, int flags, void (*func)(void *), void *arg,
329     register_t *retval, struct proc **rnewprocp)
330 {
331 	struct process *curpr = curp->p_p;
332 	struct process *pr;
333 	struct proc *p;
334 	uid_t uid = curp->p_ucred->cr_ruid;
335 	struct vmspace *vm;
336 	int count;
337 	vaddr_t uaddr;
338 	int error;
339 	struct  ptrace_state *newptstat = NULL;
340 
341 	KASSERT((flags & ~(FORK_FORK | FORK_VFORK | FORK_PPWAIT | FORK_PTRACE
342 	    | FORK_IDLE | FORK_SHAREVM | FORK_SHAREFILES | FORK_NOZOMBIE
343 	    | FORK_SYSTEM)) == 0);
344 	KASSERT(func != NULL);
345 
346 	if ((error = fork_check_maxthread(uid)))
347 		return error;
348 
349 	if ((nprocesses >= maxprocess - 5 && uid != 0) ||
350 	    nprocesses >= maxprocess) {
351 		static struct timeval lasttfm;
352 
353 		if (ratecheck(&lasttfm, &fork_tfmrate))
354 			tablefull("process");
355 		nthreads--;
356 		return EAGAIN;
357 	}
358 	nprocesses++;
359 
360 	/*
361 	 * Increment the count of processes running with this uid.
362 	 * Don't allow a nonprivileged user to exceed their current limit.
363 	 */
364 	count = chgproccnt(uid, 1);
365 	if (uid != 0 && count > lim_cur(RLIMIT_NPROC)) {
366 		(void)chgproccnt(uid, -1);
367 		nprocesses--;
368 		nthreads--;
369 		return EAGAIN;
370 	}
371 
372 	uaddr = uvm_uarea_alloc();
373 	if (uaddr == 0) {
374 		(void)chgproccnt(uid, -1);
375 		nprocesses--;
376 		nthreads--;
377 		return (ENOMEM);
378 	}
379 
380 	/*
381 	 * From now on, we're committed to the fork and cannot fail.
382 	 */
383 	p = thread_new(curp, uaddr);
384 	pr = process_new(p, curpr, flags);
385 
386 	p->p_fd		= pr->ps_fd;
387 	p->p_vmspace	= pr->ps_vmspace;
388 	if (pr->ps_flags & PS_SYSTEM)
389 		atomic_setbits_int(&p->p_flag, P_SYSTEM);
390 
391 	if (flags & FORK_PPWAIT) {
392 		atomic_setbits_int(&pr->ps_flags, PS_PPWAIT);
393 		atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT);
394 	}
395 
396 #ifdef KTRACE
397 	/*
398 	 * Copy traceflag and tracefile if enabled.
399 	 * If not inherited, these were zeroed above.
400 	 */
401 	if (curpr->ps_traceflag & KTRFAC_INHERIT)
402 		ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp,
403 		    curpr->ps_tracecred);
404 #endif
405 
406 	/*
407 	 * Finish creating the child thread.  cpu_fork() will copy
408 	 * and update the pcb and make the child ready to run.  If
409 	 * this is a normal user fork, the child will exit directly
410 	 * to user mode via child_return() on its first time slice
411 	 * and will not return here.  If this is a kernel thread,
412 	 * the specified entry point will be executed.
413 	 */
414 	cpu_fork(curp, p, NULL, NULL, func, arg ? arg : p);
415 
416 	vm = pr->ps_vmspace;
417 
418 	if (flags & FORK_FORK) {
419 		forkstat.cntfork++;
420 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
421 	} else if (flags & FORK_VFORK) {
422 		forkstat.cntvfork++;
423 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
424 	} else {
425 		forkstat.cntkthread++;
426 	}
427 
428 	if (pr->ps_flags & PS_TRACED && flags & FORK_FORK)
429 		newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK);
430 
431 	p->p_tid = alloctid();
432 
433 	LIST_INSERT_HEAD(&allproc, p, p_list);
434 	LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash);
435 	LIST_INSERT_HEAD(PIDHASH(pr->ps_pid), pr, ps_hash);
436 	LIST_INSERT_AFTER(curpr, pr, ps_pglist);
437 	LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling);
438 
439 	if (pr->ps_flags & PS_TRACED) {
440 		pr->ps_oppid = curpr->ps_pid;
441 		process_reparent(pr, curpr->ps_pptr);
442 
443 		/*
444 		 * Set ptrace status.
445 		 */
446 		if (newptstat != NULL) {
447 			pr->ps_ptstat = newptstat;
448 			newptstat = NULL;
449 			curpr->ps_ptstat->pe_report_event = PTRACE_FORK;
450 			pr->ps_ptstat->pe_report_event = PTRACE_FORK;
451 			curpr->ps_ptstat->pe_other_pid = pr->ps_pid;
452 			pr->ps_ptstat->pe_other_pid = curpr->ps_pid;
453 		}
454 	}
455 
456 	/*
457 	 * For new processes, set accounting bits and mark as complete.
458 	 */
459 	nanouptime(&pr->ps_start);
460 	pr->ps_acflag = AFORK;
461 	atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO);
462 
463 	if ((flags & FORK_IDLE) == 0)
464 		fork_thread_start(p, curp, flags);
465 	else
466 		p->p_cpu = arg;
467 
468 	free(newptstat, M_SUBPROC, sizeof(*newptstat));
469 
470 	/*
471 	 * Notify any interested parties about the new process.
472 	 */
473 	knote_locked(&curpr->ps_klist, NOTE_FORK | pr->ps_pid);
474 
475 	/*
476 	 * Update stats now that we know the fork was successful.
477 	 */
478 	uvmexp.forks++;
479 	if (flags & FORK_PPWAIT)
480 		uvmexp.forks_ppwait++;
481 	if (flags & FORK_SHAREVM)
482 		uvmexp.forks_sharevm++;
483 
484 	/*
485 	 * Pass a pointer to the new process to the caller.
486 	 */
487 	if (rnewprocp != NULL)
488 		*rnewprocp = p;
489 
490 	/*
491 	 * Preserve synchronization semantics of vfork.  If waiting for
492 	 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT
493 	 * on ourselves, and sleep on our process for the latter flag
494 	 * to go away.
495 	 * XXX Need to stop other rthreads in the parent
496 	 */
497 	if (flags & FORK_PPWAIT)
498 		while (curpr->ps_flags & PS_ISPWAIT)
499 			tsleep_nsec(curpr, PWAIT, "ppwait", INFSLP);
500 
501 	/*
502 	 * If we're tracing the child, alert the parent too.
503 	 */
504 	if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED))
505 		psignal(curp, SIGTRAP);
506 
507 	/*
508 	 * Return child pid to parent process
509 	 */
510 	if (retval != NULL)
511 		*retval = pr->ps_pid;
512 	return (0);
513 }
514 
515 int
516 thread_fork(struct proc *curp, void *stack, void *tcb, pid_t *tidptr,
517     register_t *retval)
518 {
519 	struct process *pr = curp->p_p;
520 	struct proc *p;
521 	pid_t tid;
522 	vaddr_t uaddr;
523 	int s, error;
524 
525 	if (stack == NULL)
526 		return EINVAL;
527 
528 	if ((error = fork_check_maxthread(curp->p_ucred->cr_ruid)))
529 		return error;
530 
531 	uaddr = uvm_uarea_alloc();
532 	if (uaddr == 0) {
533 		nthreads--;
534 		return ENOMEM;
535 	}
536 
537 	/*
538 	 * From now on, we're committed to the fork and cannot fail.
539 	 */
540 	p = thread_new(curp, uaddr);
541 	atomic_setbits_int(&p->p_flag, P_THREAD);
542 	sigstkinit(&p->p_sigstk);
543 	memset(p->p_name, 0, sizeof p->p_name);
544 
545 	/* other links */
546 	p->p_p = pr;
547 	pr->ps_threadcnt++;
548 
549 	/* local copies */
550 	p->p_fd		= pr->ps_fd;
551 	p->p_vmspace	= pr->ps_vmspace;
552 
553 	/*
554 	 * Finish creating the child thread.  cpu_fork() will copy
555 	 * and update the pcb and make the child ready to run.  The
556 	 * child will exit directly to user mode via child_return()
557 	 * on its first time slice and will not return here.
558 	 */
559 	cpu_fork(curp, p, stack, tcb, child_return, p);
560 
561 	p->p_tid = alloctid();
562 
563 	LIST_INSERT_HEAD(&allproc, p, p_list);
564 	LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash);
565 
566 	SCHED_LOCK(s);
567 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
568 
569 	/*
570 	 * if somebody else wants to take us to single threaded mode,
571 	 * count ourselves in.
572 	 */
573 	if (pr->ps_single) {
574 		atomic_inc_int(&pr->ps_singlecount);
575 		atomic_setbits_int(&p->p_flag, P_SUSPSINGLE);
576 	}
577 	SCHED_UNLOCK(s);
578 
579 	/*
580 	 * Return tid to parent thread and copy it out to userspace
581 	 */
582 	*retval = tid = p->p_tid + THREAD_PID_OFFSET;
583 	if (tidptr != NULL) {
584 		if (copyout(&tid, tidptr, sizeof(tid)))
585 			psignal(curp, SIGSEGV);
586 	}
587 
588 	fork_thread_start(p, curp, 0);
589 
590 	/*
591 	 * Update stats now that we know the fork was successful.
592 	 */
593 	forkstat.cnttfork++;
594 	uvmexp.forks++;
595 	uvmexp.forks_sharevm++;
596 
597 	return 0;
598 }
599 
600 
601 /* Find an unused tid */
602 pid_t
603 alloctid(void)
604 {
605 	pid_t tid;
606 
607 	do {
608 		/* (0 .. TID_MASK+1] */
609 		tid = 1 + (arc4random() & TID_MASK);
610 	} while (tfind(tid) != NULL);
611 
612 	return (tid);
613 }
614 
615 /*
616  * Checks for current use of a pid, either as a pid or pgid.
617  */
618 pid_t oldpids[128];
619 int
620 ispidtaken(pid_t pid)
621 {
622 	uint32_t i;
623 
624 	for (i = 0; i < nitems(oldpids); i++)
625 		if (pid == oldpids[i])
626 			return (1);
627 
628 	if (prfind(pid) != NULL)
629 		return (1);
630 	if (pgfind(pid) != NULL)
631 		return (1);
632 	if (zombiefind(pid) != NULL)
633 		return (1);
634 	return (0);
635 }
636 
637 /* Find an unused pid */
638 pid_t
639 allocpid(void)
640 {
641 	static int first = 1;
642 	pid_t pid;
643 
644 	/* The first PID allocated is always 1. */
645 	if (first) {
646 		first = 0;
647 		return 1;
648 	}
649 
650 	/*
651 	 * All subsequent PIDs are chosen randomly.  We need to
652 	 * find an unused PID in the range [2, PID_MAX].
653 	 */
654 	do {
655 		pid = 2 + arc4random_uniform(PID_MAX - 1);
656 	} while (ispidtaken(pid));
657 	return pid;
658 }
659 
660 void
661 freepid(pid_t pid)
662 {
663 	static uint32_t idx;
664 
665 	oldpids[idx++ % nitems(oldpids)] = pid;
666 }
667 
668 /* Do machine independent parts of switching to a new process */
669 void
670 proc_trampoline_mi(void)
671 {
672 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
673 	struct proc *p = curproc;
674 
675 	SCHED_ASSERT_LOCKED();
676 
677 	clear_resched(curcpu());
678 
679 #if defined(MULTIPROCESSOR)
680 	__mp_unlock(&sched_lock);
681 #endif
682 	spl0();
683 
684 	SCHED_ASSERT_UNLOCKED();
685 	KERNEL_ASSERT_UNLOCKED();
686 	assertwaitok();
687 	smr_idle();
688 
689 	/* Start any optional clock interrupts needed by the thread. */
690 	if (ISSET(p->p_p->ps_flags, PS_ITIMER)) {
691 		atomic_setbits_int(&spc->spc_schedflags, SPCF_ITIMER);
692 		clockintr_advance(spc->spc_itimer, hardclock_period);
693 	}
694 	if (ISSET(p->p_p->ps_flags, PS_PROFIL)) {
695 		atomic_setbits_int(&spc->spc_schedflags, SPCF_PROFCLOCK);
696 		clockintr_advance(spc->spc_profclock, profclock_period);
697 	}
698 
699 	nanouptime(&spc->spc_runtime);
700 	KERNEL_LOCK();
701 }
702