xref: /openbsd-src/sys/kern/kern_fork.c (revision c7735c59e17935eb6c3526463bca8d0825697222)
1 /*	$OpenBSD: kern_fork.c,v 1.265 2024/08/21 03:07:45 deraadt 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;		/* [a] 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 	refcnt_init(&pr->ps_refcnt);
182 
183 	/* initialize the thread links */
184 	pr->ps_mainproc = p;
185 	TAILQ_INIT(&pr->ps_threads);
186 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
187 	pr->ps_threadcnt = 1;
188 	p->p_p = pr;
189 
190 	/* give the process the same creds as the initial thread */
191 	pr->ps_ucred = p->p_ucred;
192 	crhold(pr->ps_ucred);
193 	/* new thread and new process */
194 	KASSERT(p->p_ucred->cr_refcnt.r_refs >= 2);
195 
196 	LIST_INIT(&pr->ps_children);
197 	LIST_INIT(&pr->ps_orphans);
198 	LIST_INIT(&pr->ps_ftlist);
199 	LIST_INIT(&pr->ps_sigiolst);
200 	TAILQ_INIT(&pr->ps_tslpqueue);
201 
202 	rw_init(&pr->ps_lock, "pslock");
203 	mtx_init(&pr->ps_mtx, IPL_HIGH);
204 	klist_init_mutex(&pr->ps_klist, &pr->ps_mtx);
205 
206 	timeout_set_flags(&pr->ps_realit_to, realitexpire, pr,
207 	    KCLOCK_UPTIME, 0);
208 	timeout_set(&pr->ps_rucheck_to, rucheck, pr);
209 }
210 
211 
212 /*
213  * Allocate and initialize a new process.
214  */
215 struct process *
216 process_new(struct proc *p, struct process *parent, int flags)
217 {
218 	struct process *pr;
219 
220 	pr = pool_get(&process_pool, PR_WAITOK);
221 
222 	/*
223 	 * Make a process structure for the new process.
224 	 * Start by zeroing the section of proc that is zero-initialized,
225 	 * then copy the section that is copied directly from the parent.
226 	 */
227 	memset(&pr->ps_startzero, 0,
228 	    (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero);
229 	memcpy(&pr->ps_startcopy, &parent->ps_startcopy,
230 	    (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy);
231 
232 	process_initialize(pr, p);
233 	pr->ps_pid = allocpid();
234 	lim_fork(parent, pr);
235 
236 	/* post-copy fixups */
237 	pr->ps_pptr = parent;
238 	pr->ps_ppid = parent->ps_pid;
239 
240 	/* bump references to the text vnode (for sysctl) */
241 	pr->ps_textvp = parent->ps_textvp;
242 	if (pr->ps_textvp)
243 		vref(pr->ps_textvp);
244 
245 	/* copy unveil if unveil is active */
246 	unveil_copy(parent, pr);
247 
248 	pr->ps_flags = parent->ps_flags &
249 	    (PS_SUGID | PS_SUGIDEXEC | PS_PLEDGE | PS_EXECPLEDGE |
250 	    PS_WXNEEDED | PS_CHROOT);
251 	if (parent->ps_session->s_ttyvp != NULL)
252 		pr->ps_flags |= parent->ps_flags & PS_CONTROLT;
253 
254 	if (parent->ps_pin.pn_pins) {
255 		pr->ps_pin.pn_pins = mallocarray(parent->ps_pin.pn_npins,
256 		    sizeof(u_int), M_PINSYSCALL, M_WAITOK);
257 		memcpy(pr->ps_pin.pn_pins, parent->ps_pin.pn_pins,
258 		    parent->ps_pin.pn_npins * sizeof(u_int));
259 	}
260 	if (parent->ps_libcpin.pn_pins) {
261 		pr->ps_libcpin.pn_pins = mallocarray(parent->ps_libcpin.pn_npins,
262 		    sizeof(u_int), M_PINSYSCALL, M_WAITOK);
263 		memcpy(pr->ps_libcpin.pn_pins, parent->ps_libcpin.pn_pins,
264 		    parent->ps_libcpin.pn_npins * sizeof(u_int));
265 	}
266 
267 	/*
268 	 * Duplicate sub-structures as needed.
269 	 * Increase reference counts on shared objects.
270 	 */
271 	if (flags & FORK_SHAREFILES)
272 		pr->ps_fd = fdshare(parent);
273 	else
274 		pr->ps_fd = fdcopy(parent);
275 	pr->ps_sigacts = sigactsinit(parent);
276 	if (flags & FORK_SHAREVM)
277 		pr->ps_vmspace = uvmspace_share(parent);
278 	else
279 		pr->ps_vmspace = uvmspace_fork(parent);
280 
281 	if (parent->ps_flags & PS_PROFIL)
282 		startprofclock(pr);
283 	if (flags & FORK_PTRACE)
284 		pr->ps_flags |= parent->ps_flags & PS_TRACED;
285 	if (flags & FORK_NOZOMBIE)
286 		pr->ps_flags |= PS_NOZOMBIE;
287 	if (flags & FORK_SYSTEM)
288 		pr->ps_flags |= PS_SYSTEM;
289 
290 	/* mark as embryo to protect against others */
291 	pr->ps_flags |= PS_EMBRYO;
292 
293 	/* Force visibility of all of the above changes */
294 	membar_producer();
295 
296 	/* it's sufficiently inited to be globally visible */
297 	LIST_INSERT_HEAD(&allprocess, pr, ps_list);
298 
299 	return pr;
300 }
301 
302 /* print the 'table full' message once per 10 seconds */
303 struct timeval fork_tfmrate = { 10, 0 };
304 
305 int
306 fork_check_maxthread(uid_t uid)
307 {
308 	int maxthread_local, val;
309 
310 	/*
311 	 * Although process entries are dynamically created, we still keep
312 	 * a global limit on the maximum number we will create. We reserve
313 	 * the last 5 processes to root. The variable nprocesses is the
314 	 * current number of processes, maxprocess is the limit.  Similar
315 	 * rules for threads (struct proc): we reserve the last 5 to root;
316 	 * the variable nthreads is the current number of procs, maxthread is
317 	 * the limit.
318 	 */
319 	maxthread_local = atomic_load_int(&maxthread);
320 	val = atomic_inc_int_nv(&nthreads);
321 	if ((val > maxthread_local - 5 && uid != 0) ||
322 	    val > maxthread_local) {
323 		static struct timeval lasttfm;
324 
325 		if (ratecheck(&lasttfm, &fork_tfmrate))
326 			tablefull("thread");
327 		atomic_dec_int(&nthreads);
328 		return EAGAIN;
329 	}
330 
331 	return 0;
332 }
333 
334 static inline void
335 fork_thread_start(struct proc *p, struct proc *parent, int flags)
336 {
337 	struct cpu_info *ci;
338 
339 	SCHED_LOCK();
340 	ci = sched_choosecpu_fork(parent, flags);
341 	TRACEPOINT(sched, fork, p->p_tid + THREAD_PID_OFFSET,
342 	    p->p_p->ps_pid, CPU_INFO_UNIT(ci));
343 	setrunqueue(ci, p, p->p_usrpri);
344 	SCHED_UNLOCK();
345 }
346 
347 int
348 fork1(struct proc *curp, int flags, void (*func)(void *), void *arg,
349     register_t *retval, struct proc **rnewprocp)
350 {
351 	struct process *curpr = curp->p_p;
352 	struct process *pr;
353 	struct proc *p;
354 	uid_t uid = curp->p_ucred->cr_ruid;
355 	struct vmspace *vm;
356 	int count, maxprocess_local;
357 	vaddr_t uaddr;
358 	int error;
359 	struct  ptrace_state *newptstat = NULL;
360 
361 	KASSERT((flags & ~(FORK_FORK | FORK_VFORK | FORK_PPWAIT | FORK_PTRACE
362 	    | FORK_IDLE | FORK_SHAREVM | FORK_SHAREFILES | FORK_NOZOMBIE
363 	    | FORK_SYSTEM)) == 0);
364 	KASSERT(func != NULL);
365 
366 	if ((error = fork_check_maxthread(uid)))
367 		return error;
368 
369 	maxprocess_local = atomic_load_int(&maxprocess);
370 	if ((nprocesses >= maxprocess_local - 5 && uid != 0) ||
371 	    nprocesses >= maxprocess_local) {
372 		static struct timeval lasttfm;
373 
374 		if (ratecheck(&lasttfm, &fork_tfmrate))
375 			tablefull("process");
376 		atomic_dec_int(&nthreads);
377 		return EAGAIN;
378 	}
379 	nprocesses++;
380 
381 	/*
382 	 * Increment the count of processes running with this uid.
383 	 * Don't allow a nonprivileged user to exceed their current limit.
384 	 */
385 	count = chgproccnt(uid, 1);
386 	if (uid != 0 && count > lim_cur(RLIMIT_NPROC)) {
387 		(void)chgproccnt(uid, -1);
388 		nprocesses--;
389 		atomic_dec_int(&nthreads);
390 		return EAGAIN;
391 	}
392 
393 	uaddr = uvm_uarea_alloc();
394 	if (uaddr == 0) {
395 		(void)chgproccnt(uid, -1);
396 		nprocesses--;
397 		atomic_dec_int(&nthreads);
398 		return (ENOMEM);
399 	}
400 
401 	/*
402 	 * From now on, we're committed to the fork and cannot fail.
403 	 */
404 	p = thread_new(curp, uaddr);
405 	pr = process_new(p, curpr, flags);
406 
407 	p->p_fd		= pr->ps_fd;
408 	p->p_vmspace	= pr->ps_vmspace;
409 	if (pr->ps_flags & PS_SYSTEM)
410 		atomic_setbits_int(&p->p_flag, P_SYSTEM);
411 
412 	if (flags & FORK_PPWAIT) {
413 		atomic_setbits_int(&pr->ps_flags, PS_PPWAIT);
414 		atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT);
415 	}
416 
417 #ifdef KTRACE
418 	/*
419 	 * Copy traceflag and tracefile if enabled.
420 	 * If not inherited, these were zeroed above.
421 	 */
422 	if (curpr->ps_traceflag & KTRFAC_INHERIT)
423 		ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp,
424 		    curpr->ps_tracecred);
425 #endif
426 
427 	/*
428 	 * Finish creating the child thread.  cpu_fork() will copy
429 	 * and update the pcb and make the child ready to run.  If
430 	 * this is a normal user fork, the child will exit directly
431 	 * to user mode via child_return() on its first time slice
432 	 * and will not return here.  If this is a kernel thread,
433 	 * the specified entry point will be executed.
434 	 */
435 	cpu_fork(curp, p, NULL, NULL, func, arg ? arg : p);
436 
437 	vm = pr->ps_vmspace;
438 
439 	if (flags & FORK_FORK) {
440 		forkstat.cntfork++;
441 		forkstat.sizfork += vm->vm_dsize + vm->vm_ssize;
442 	} else if (flags & FORK_VFORK) {
443 		forkstat.cntvfork++;
444 		forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize;
445 	} else {
446 		forkstat.cntkthread++;
447 	}
448 
449 	if (pr->ps_flags & PS_TRACED && flags & FORK_FORK)
450 		newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK);
451 
452 	p->p_tid = alloctid();
453 
454 	LIST_INSERT_HEAD(&allproc, p, p_list);
455 	LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash);
456 	LIST_INSERT_HEAD(PIDHASH(pr->ps_pid), pr, ps_hash);
457 	LIST_INSERT_AFTER(curpr, pr, ps_pglist);
458 	LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling);
459 
460 	if (pr->ps_flags & PS_TRACED) {
461 		pr->ps_oppid = curpr->ps_pid;
462 		process_reparent(pr, curpr->ps_pptr);
463 
464 		/*
465 		 * Set ptrace status.
466 		 */
467 		if (newptstat != NULL) {
468 			pr->ps_ptstat = newptstat;
469 			newptstat = NULL;
470 			curpr->ps_ptstat->pe_report_event = PTRACE_FORK;
471 			pr->ps_ptstat->pe_report_event = PTRACE_FORK;
472 			curpr->ps_ptstat->pe_other_pid = pr->ps_pid;
473 			pr->ps_ptstat->pe_other_pid = curpr->ps_pid;
474 		}
475 	}
476 
477 	/*
478 	 * For new processes, set accounting bits and mark as complete.
479 	 */
480 	nanouptime(&pr->ps_start);
481 	pr->ps_acflag = AFORK;
482 	atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO);
483 
484 	if ((flags & FORK_IDLE) == 0)
485 		fork_thread_start(p, curp, flags);
486 	else
487 		p->p_cpu = arg;
488 
489 	free(newptstat, M_SUBPROC, sizeof(*newptstat));
490 
491 	/*
492 	 * Notify any interested parties about the new process.
493 	 */
494 	knote_processfork(curpr, pr->ps_pid);
495 
496 	/*
497 	 * Update stats now that we know the fork was successful.
498 	 */
499 	uvmexp.forks++;
500 	if (flags & FORK_PPWAIT)
501 		uvmexp.forks_ppwait++;
502 	if (flags & FORK_SHAREVM)
503 		uvmexp.forks_sharevm++;
504 
505 	/*
506 	 * Pass a pointer to the new process to the caller.
507 	 */
508 	if (rnewprocp != NULL)
509 		*rnewprocp = p;
510 
511 	/*
512 	 * Preserve synchronization semantics of vfork.  If waiting for
513 	 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT
514 	 * on ourselves, and sleep on our process for the latter flag
515 	 * to go away.
516 	 * XXX Need to stop other rthreads in the parent
517 	 */
518 	if (flags & FORK_PPWAIT)
519 		while (curpr->ps_flags & PS_ISPWAIT)
520 			tsleep_nsec(curpr, PWAIT, "ppwait", INFSLP);
521 
522 	/*
523 	 * If we're tracing the child, alert the parent too.
524 	 */
525 	if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED))
526 		psignal(curp, SIGTRAP);
527 
528 	/*
529 	 * Return child pid to parent process
530 	 */
531 	if (retval != NULL)
532 		*retval = pr->ps_pid;
533 	return (0);
534 }
535 
536 int
537 thread_fork(struct proc *curp, void *stack, void *tcb, pid_t *tidptr,
538     register_t *retval)
539 {
540 	struct process *pr = curp->p_p;
541 	struct proc *p;
542 	pid_t tid;
543 	vaddr_t uaddr;
544 	int error;
545 
546 	if (stack == NULL)
547 		return EINVAL;
548 
549 	if ((error = fork_check_maxthread(curp->p_ucred->cr_ruid)))
550 		return error;
551 
552 	uaddr = uvm_uarea_alloc();
553 	if (uaddr == 0) {
554 		atomic_dec_int(&nthreads);
555 		return ENOMEM;
556 	}
557 
558 	/*
559 	 * From now on, we're committed to the fork and cannot fail.
560 	 */
561 	p = thread_new(curp, uaddr);
562 	atomic_setbits_int(&p->p_flag, P_THREAD);
563 	sigstkinit(&p->p_sigstk);
564 	memset(p->p_name, 0, sizeof p->p_name);
565 
566 	/* other links */
567 	p->p_p = pr;
568 
569 	/* local copies */
570 	p->p_fd		= pr->ps_fd;
571 	p->p_vmspace	= pr->ps_vmspace;
572 
573 	/*
574 	 * Finish creating the child thread.  cpu_fork() will copy
575 	 * and update the pcb and make the child ready to run.  The
576 	 * child will exit directly to user mode via child_return()
577 	 * on its first time slice and will not return here.
578 	 */
579 	cpu_fork(curp, p, stack, tcb, child_return, p);
580 
581 	p->p_tid = alloctid();
582 
583 	LIST_INSERT_HEAD(&allproc, p, p_list);
584 	LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash);
585 
586 	mtx_enter(&pr->ps_mtx);
587 	TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link);
588 	pr->ps_threadcnt++;
589 
590 	/*
591 	 * if somebody else wants to take us to single threaded mode,
592 	 * count ourselves in.
593 	 */
594 	if (pr->ps_single) {
595 		pr->ps_singlecnt++;
596 		atomic_setbits_int(&p->p_flag, P_SUSPSINGLE);
597 	}
598 	mtx_leave(&pr->ps_mtx);
599 
600 	/*
601 	 * Return tid to parent thread and copy it out to userspace
602 	 */
603 	*retval = tid = p->p_tid + THREAD_PID_OFFSET;
604 	if (tidptr != NULL) {
605 		if (copyout(&tid, tidptr, sizeof(tid)))
606 			psignal(curp, SIGSEGV);
607 	}
608 
609 	fork_thread_start(p, curp, 0);
610 
611 	/*
612 	 * Update stats now that we know the fork was successful.
613 	 */
614 	forkstat.cnttfork++;
615 	uvmexp.forks++;
616 	uvmexp.forks_sharevm++;
617 
618 	return 0;
619 }
620 
621 
622 /* Find an unused tid */
623 pid_t
624 alloctid(void)
625 {
626 	pid_t tid;
627 
628 	do {
629 		/* (0 .. TID_MASK+1] */
630 		tid = 1 + (arc4random() & TID_MASK);
631 	} while (tfind(tid) != NULL);
632 
633 	return (tid);
634 }
635 
636 /*
637  * Checks for current use of a pid, either as a pid or pgid.
638  */
639 pid_t oldpids[128];
640 int
641 ispidtaken(pid_t pid)
642 {
643 	uint32_t i;
644 
645 	for (i = 0; i < nitems(oldpids); i++)
646 		if (pid == oldpids[i])
647 			return (1);
648 
649 	if (prfind(pid) != NULL)
650 		return (1);
651 	if (pgfind(pid) != NULL)
652 		return (1);
653 	if (zombiefind(pid) != NULL)
654 		return (1);
655 	return (0);
656 }
657 
658 /* Find an unused pid */
659 pid_t
660 allocpid(void)
661 {
662 	static int first = 1;
663 	pid_t pid;
664 
665 	/* The first PID allocated is always 1. */
666 	if (first) {
667 		first = 0;
668 		return 1;
669 	}
670 
671 	/*
672 	 * All subsequent PIDs are chosen randomly.  We need to
673 	 * find an unused PID in the range [2, PID_MAX].
674 	 */
675 	do {
676 		pid = 2 + arc4random_uniform(PID_MAX - 1);
677 	} while (ispidtaken(pid));
678 	return pid;
679 }
680 
681 void
682 freepid(pid_t pid)
683 {
684 	static uint32_t idx;
685 
686 	oldpids[idx++ % nitems(oldpids)] = pid;
687 }
688 
689 /* Do machine independent parts of switching to a new process */
690 void
691 proc_trampoline_mi(void)
692 {
693 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
694 	struct proc *p = curproc;
695 
696 	SCHED_ASSERT_LOCKED();
697 	clear_resched(curcpu());
698 	mtx_leave(&sched_lock);
699 	spl0();
700 
701 	SCHED_ASSERT_UNLOCKED();
702 	KERNEL_ASSERT_UNLOCKED();
703 	assertwaitok();
704 	smr_idle();
705 
706 	/* Start any optional clock interrupts needed by the thread. */
707 	if (ISSET(p->p_p->ps_flags, PS_ITIMER)) {
708 		atomic_setbits_int(&spc->spc_schedflags, SPCF_ITIMER);
709 		clockintr_advance(&spc->spc_itimer, hardclock_period);
710 	}
711 	if (ISSET(p->p_p->ps_flags, PS_PROFIL)) {
712 		atomic_setbits_int(&spc->spc_schedflags, SPCF_PROFCLOCK);
713 		clockintr_advance(&spc->spc_profclock, profclock_period);
714 	}
715 
716 	nanouptime(&spc->spc_runtime);
717 	KERNEL_LOCK();
718 }
719