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