xref: /openbsd-src/sys/kern/kern_sig.c (revision 235013eb5537fda09d0d291a941de9da1d382d62)
1 /*	$OpenBSD: kern_sig.c,v 1.336 2024/07/29 12:42:53 claudio Exp $	*/
2 /*	$NetBSD: kern_sig.c,v 1.54 1996/04/22 01:38:32 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1997 Theo de Raadt. All rights reserved.
6  * Copyright (c) 1982, 1986, 1989, 1991, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
39  */
40 
41 #include <sys/param.h>
42 #include <sys/signalvar.h>
43 #include <sys/queue.h>
44 #include <sys/namei.h>
45 #include <sys/vnode.h>
46 #include <sys/event.h>
47 #include <sys/proc.h>
48 #include <sys/systm.h>
49 #include <sys/acct.h>
50 #include <sys/fcntl.h>
51 #include <sys/filedesc.h>
52 #include <sys/wait.h>
53 #include <sys/ktrace.h>
54 #include <sys/stat.h>
55 #include <sys/malloc.h>
56 #include <sys/pool.h>
57 #include <sys/sched.h>
58 #include <sys/user.h>
59 #include <sys/syslog.h>
60 #include <sys/ttycom.h>
61 #include <sys/pledge.h>
62 #include <sys/witness.h>
63 #include <sys/exec_elf.h>
64 
65 #include <sys/mount.h>
66 #include <sys/syscallargs.h>
67 
68 #include <uvm/uvm_extern.h>
69 #include <machine/tcb.h>
70 
71 int nosuidcoredump = 1;
72 
73 /*
74  * The array below categorizes the signals and their default actions.
75  */
76 const int sigprop[NSIG] = {
77 	0,			/* unused */
78 	SA_KILL,		/* SIGHUP */
79 	SA_KILL,		/* SIGINT */
80 	SA_KILL|SA_CORE,	/* SIGQUIT */
81 	SA_KILL|SA_CORE,	/* SIGILL */
82 	SA_KILL|SA_CORE,	/* SIGTRAP */
83 	SA_KILL|SA_CORE,	/* SIGABRT */
84 	SA_KILL|SA_CORE,	/* SIGEMT */
85 	SA_KILL|SA_CORE,	/* SIGFPE */
86 	SA_KILL,		/* SIGKILL */
87 	SA_KILL|SA_CORE,	/* SIGBUS */
88 	SA_KILL|SA_CORE,	/* SIGSEGV */
89 	SA_KILL|SA_CORE,	/* SIGSYS */
90 	SA_KILL,		/* SIGPIPE */
91 	SA_KILL,		/* SIGALRM */
92 	SA_KILL,		/* SIGTERM */
93 	SA_IGNORE,		/* SIGURG */
94 	SA_STOP,		/* SIGSTOP */
95 	SA_STOP|SA_TTYSTOP,	/* SIGTSTP */
96 	SA_IGNORE|SA_CONT,	/* SIGCONT */
97 	SA_IGNORE,		/* SIGCHLD */
98 	SA_STOP|SA_TTYSTOP,	/* SIGTTIN */
99 	SA_STOP|SA_TTYSTOP,	/* SIGTTOU */
100 	SA_IGNORE,		/* SIGIO */
101 	SA_KILL,		/* SIGXCPU */
102 	SA_KILL,		/* SIGXFSZ */
103 	SA_KILL,		/* SIGVTALRM */
104 	SA_KILL,		/* SIGPROF */
105 	SA_IGNORE,		/* SIGWINCH  */
106 	SA_IGNORE,		/* SIGINFO */
107 	SA_KILL,		/* SIGUSR1 */
108 	SA_KILL,		/* SIGUSR2 */
109 	SA_IGNORE,		/* SIGTHR */
110 };
111 
112 #define	CONTSIGMASK	(sigmask(SIGCONT))
113 #define	STOPSIGMASK	(sigmask(SIGSTOP) | sigmask(SIGTSTP) | \
114 			    sigmask(SIGTTIN) | sigmask(SIGTTOU))
115 
116 void setsigvec(struct proc *, int, struct sigaction *);
117 
118 void proc_stop(struct proc *p, int);
119 void proc_stop_sweep(void *);
120 void *proc_stop_si;
121 
122 void setsigctx(struct proc *, int, struct sigctx *);
123 void postsig_done(struct proc *, int, sigset_t, int);
124 void postsig(struct proc *, int, struct sigctx *);
125 int cansignal(struct proc *, struct process *, int);
126 
127 struct pool sigacts_pool;	/* memory pool for sigacts structures */
128 
129 void sigio_del(struct sigiolst *);
130 void sigio_unlink(struct sigio_ref *, struct sigiolst *);
131 struct mutex sigio_lock = MUTEX_INITIALIZER(IPL_HIGH);
132 
133 /*
134  * Can thread p, send the signal signum to process qr?
135  */
136 int
137 cansignal(struct proc *p, struct process *qr, int signum)
138 {
139 	struct process *pr = p->p_p;
140 	struct ucred *uc = p->p_ucred;
141 	struct ucred *quc = qr->ps_ucred;
142 
143 	if (uc->cr_uid == 0)
144 		return (1);		/* root can always signal */
145 
146 	if (pr == qr)
147 		return (1);		/* process can always signal itself */
148 
149 	/* optimization: if the same creds then the tests below will pass */
150 	if (uc == quc)
151 		return (1);
152 
153 	if (signum == SIGCONT && qr->ps_session == pr->ps_session)
154 		return (1);		/* SIGCONT in session */
155 
156 	/*
157 	 * Using kill(), only certain signals can be sent to setugid
158 	 * child processes
159 	 */
160 	if (qr->ps_flags & PS_SUGID) {
161 		switch (signum) {
162 		case 0:
163 		case SIGKILL:
164 		case SIGINT:
165 		case SIGTERM:
166 		case SIGALRM:
167 		case SIGSTOP:
168 		case SIGTTIN:
169 		case SIGTTOU:
170 		case SIGTSTP:
171 		case SIGHUP:
172 		case SIGUSR1:
173 		case SIGUSR2:
174 			if (uc->cr_ruid == quc->cr_ruid ||
175 			    uc->cr_uid == quc->cr_ruid)
176 				return (1);
177 		}
178 		return (0);
179 	}
180 
181 	if (uc->cr_ruid == quc->cr_ruid ||
182 	    uc->cr_ruid == quc->cr_svuid ||
183 	    uc->cr_uid == quc->cr_ruid ||
184 	    uc->cr_uid == quc->cr_svuid)
185 		return (1);
186 	return (0);
187 }
188 
189 /*
190  * Initialize signal-related data structures.
191  */
192 void
193 signal_init(void)
194 {
195 	proc_stop_si = softintr_establish(IPL_SOFTCLOCK, proc_stop_sweep,
196 	    NULL);
197 	if (proc_stop_si == NULL)
198 		panic("signal_init failed to register softintr");
199 
200 	pool_init(&sigacts_pool, sizeof(struct sigacts), 0, IPL_NONE,
201 	    PR_WAITOK, "sigapl", NULL);
202 }
203 
204 /*
205  * Initialize a new sigaltstack structure.
206  */
207 void
208 sigstkinit(struct sigaltstack *ss)
209 {
210 	ss->ss_flags = SS_DISABLE;
211 	ss->ss_size = 0;
212 	ss->ss_sp = NULL;
213 }
214 
215 /*
216  * Create an initial sigacts structure, using the same signal state
217  * as pr.
218  */
219 struct sigacts *
220 sigactsinit(struct process *pr)
221 {
222 	struct sigacts *ps;
223 
224 	ps = pool_get(&sigacts_pool, PR_WAITOK);
225 	memcpy(ps, pr->ps_sigacts, sizeof(struct sigacts));
226 	return (ps);
227 }
228 
229 /*
230  * Release a sigacts structure.
231  */
232 void
233 sigactsfree(struct sigacts *ps)
234 {
235 	pool_put(&sigacts_pool, ps);
236 }
237 
238 int
239 sys_sigaction(struct proc *p, void *v, register_t *retval)
240 {
241 	struct sys_sigaction_args /* {
242 		syscallarg(int) signum;
243 		syscallarg(const struct sigaction *) nsa;
244 		syscallarg(struct sigaction *) osa;
245 	} */ *uap = v;
246 	struct sigaction vec;
247 #ifdef KTRACE
248 	struct sigaction ovec;
249 #endif
250 	struct sigaction *sa;
251 	const struct sigaction *nsa;
252 	struct sigaction *osa;
253 	struct sigacts *ps = p->p_p->ps_sigacts;
254 	int signum;
255 	int bit, error;
256 
257 	signum = SCARG(uap, signum);
258 	nsa = SCARG(uap, nsa);
259 	osa = SCARG(uap, osa);
260 
261 	if (signum <= 0 || signum >= NSIG ||
262 	    (nsa && (signum == SIGKILL || signum == SIGSTOP)))
263 		return (EINVAL);
264 	sa = &vec;
265 	if (osa) {
266 		mtx_enter(&p->p_p->ps_mtx);
267 		sa->sa_handler = ps->ps_sigact[signum];
268 		sa->sa_mask = ps->ps_catchmask[signum];
269 		bit = sigmask(signum);
270 		sa->sa_flags = 0;
271 		if ((ps->ps_sigonstack & bit) != 0)
272 			sa->sa_flags |= SA_ONSTACK;
273 		if ((ps->ps_sigintr & bit) == 0)
274 			sa->sa_flags |= SA_RESTART;
275 		if ((ps->ps_sigreset & bit) != 0)
276 			sa->sa_flags |= SA_RESETHAND;
277 		if ((ps->ps_siginfo & bit) != 0)
278 			sa->sa_flags |= SA_SIGINFO;
279 		if (signum == SIGCHLD) {
280 			if ((ps->ps_sigflags & SAS_NOCLDSTOP) != 0)
281 				sa->sa_flags |= SA_NOCLDSTOP;
282 			if ((ps->ps_sigflags & SAS_NOCLDWAIT) != 0)
283 				sa->sa_flags |= SA_NOCLDWAIT;
284 		}
285 		mtx_leave(&p->p_p->ps_mtx);
286 		if ((sa->sa_mask & bit) == 0)
287 			sa->sa_flags |= SA_NODEFER;
288 		sa->sa_mask &= ~bit;
289 		error = copyout(sa, osa, sizeof (vec));
290 		if (error)
291 			return (error);
292 #ifdef KTRACE
293 		if (KTRPOINT(p, KTR_STRUCT))
294 			ovec = vec;
295 #endif
296 	}
297 	if (nsa) {
298 		error = copyin(nsa, sa, sizeof (vec));
299 		if (error)
300 			return (error);
301 #ifdef KTRACE
302 		if (KTRPOINT(p, KTR_STRUCT))
303 			ktrsigaction(p, sa);
304 #endif
305 		setsigvec(p, signum, sa);
306 	}
307 #ifdef KTRACE
308 	if (osa && KTRPOINT(p, KTR_STRUCT))
309 		ktrsigaction(p, &ovec);
310 #endif
311 	return (0);
312 }
313 
314 void
315 setsigvec(struct proc *p, int signum, struct sigaction *sa)
316 {
317 	struct sigacts *ps = p->p_p->ps_sigacts;
318 	int bit;
319 
320 	bit = sigmask(signum);
321 
322 	mtx_enter(&p->p_p->ps_mtx);
323 	ps->ps_sigact[signum] = sa->sa_handler;
324 	if ((sa->sa_flags & SA_NODEFER) == 0)
325 		sa->sa_mask |= sigmask(signum);
326 	ps->ps_catchmask[signum] = sa->sa_mask &~ sigcantmask;
327 	if (signum == SIGCHLD) {
328 		if (sa->sa_flags & SA_NOCLDSTOP)
329 			atomic_setbits_int(&ps->ps_sigflags, SAS_NOCLDSTOP);
330 		else
331 			atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDSTOP);
332 		/*
333 		 * If the SA_NOCLDWAIT flag is set or the handler
334 		 * is SIG_IGN we reparent the dying child to PID 1
335 		 * (init) which will reap the zombie.  Because we use
336 		 * init to do our dirty work we never set SAS_NOCLDWAIT
337 		 * for PID 1.
338 		 * XXX exit1 rework means this is unnecessary?
339 		 */
340 		if (initprocess->ps_sigacts != ps &&
341 		    ((sa->sa_flags & SA_NOCLDWAIT) ||
342 		    sa->sa_handler == SIG_IGN))
343 			atomic_setbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
344 		else
345 			atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
346 	}
347 	if ((sa->sa_flags & SA_RESETHAND) != 0)
348 		ps->ps_sigreset |= bit;
349 	else
350 		ps->ps_sigreset &= ~bit;
351 	if ((sa->sa_flags & SA_SIGINFO) != 0)
352 		ps->ps_siginfo |= bit;
353 	else
354 		ps->ps_siginfo &= ~bit;
355 	if ((sa->sa_flags & SA_RESTART) == 0)
356 		ps->ps_sigintr |= bit;
357 	else
358 		ps->ps_sigintr &= ~bit;
359 	if ((sa->sa_flags & SA_ONSTACK) != 0)
360 		ps->ps_sigonstack |= bit;
361 	else
362 		ps->ps_sigonstack &= ~bit;
363 	/*
364 	 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
365 	 * and for signals set to SIG_DFL where the default is to ignore.
366 	 * However, don't put SIGCONT in ps_sigignore,
367 	 * as we have to restart the process.
368 	 */
369 	if (sa->sa_handler == SIG_IGN ||
370 	    (sigprop[signum] & SA_IGNORE && sa->sa_handler == SIG_DFL)) {
371 		atomic_clearbits_int(&p->p_siglist, bit);
372 		atomic_clearbits_int(&p->p_p->ps_siglist, bit);
373 		if (signum != SIGCONT)
374 			ps->ps_sigignore |= bit;	/* easier in psignal */
375 		ps->ps_sigcatch &= ~bit;
376 	} else {
377 		ps->ps_sigignore &= ~bit;
378 		if (sa->sa_handler == SIG_DFL)
379 			ps->ps_sigcatch &= ~bit;
380 		else
381 			ps->ps_sigcatch |= bit;
382 	}
383 	mtx_leave(&p->p_p->ps_mtx);
384 }
385 
386 /*
387  * Initialize signal state for process 0;
388  * set to ignore signals that are ignored by default.
389  */
390 void
391 siginit(struct sigacts *ps)
392 {
393 	int i;
394 
395 	for (i = 0; i < NSIG; i++)
396 		if (sigprop[i] & SA_IGNORE && i != SIGCONT)
397 			ps->ps_sigignore |= sigmask(i);
398 	ps->ps_sigflags = SAS_NOCLDWAIT | SAS_NOCLDSTOP;
399 }
400 
401 /*
402  * Reset signals for an exec by the specified thread.
403  */
404 void
405 execsigs(struct proc *p)
406 {
407 	struct sigacts *ps;
408 	int nc, mask;
409 
410 	ps = p->p_p->ps_sigacts;
411 	mtx_enter(&p->p_p->ps_mtx);
412 
413 	/*
414 	 * Reset caught signals.  Held signals remain held
415 	 * through p_sigmask (unless they were caught,
416 	 * and are now ignored by default).
417 	 */
418 	while (ps->ps_sigcatch) {
419 		nc = ffs((long)ps->ps_sigcatch);
420 		mask = sigmask(nc);
421 		ps->ps_sigcatch &= ~mask;
422 		if (sigprop[nc] & SA_IGNORE) {
423 			if (nc != SIGCONT)
424 				ps->ps_sigignore |= mask;
425 			atomic_clearbits_int(&p->p_siglist, mask);
426 			atomic_clearbits_int(&p->p_p->ps_siglist, mask);
427 		}
428 		ps->ps_sigact[nc] = SIG_DFL;
429 	}
430 	/*
431 	 * Reset stack state to the user stack.
432 	 * Clear set of signals caught on the signal stack.
433 	 */
434 	sigstkinit(&p->p_sigstk);
435 	atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
436 	if (ps->ps_sigact[SIGCHLD] == SIG_IGN)
437 		ps->ps_sigact[SIGCHLD] = SIG_DFL;
438 	mtx_leave(&p->p_p->ps_mtx);
439 }
440 
441 /*
442  * Manipulate signal mask.
443  * Note that we receive new mask, not pointer,
444  * and return old mask as return value;
445  * the library stub does the rest.
446  */
447 int
448 sys_sigprocmask(struct proc *p, void *v, register_t *retval)
449 {
450 	struct sys_sigprocmask_args /* {
451 		syscallarg(int) how;
452 		syscallarg(sigset_t) mask;
453 	} */ *uap = v;
454 	int error = 0;
455 	sigset_t mask;
456 
457 	KASSERT(p == curproc);
458 
459 	*retval = p->p_sigmask;
460 	mask = SCARG(uap, mask) &~ sigcantmask;
461 
462 	switch (SCARG(uap, how)) {
463 	case SIG_BLOCK:
464 		SET(p->p_sigmask, mask);
465 		break;
466 	case SIG_UNBLOCK:
467 		CLR(p->p_sigmask, mask);
468 		break;
469 	case SIG_SETMASK:
470 		p->p_sigmask = mask;
471 		break;
472 	default:
473 		error = EINVAL;
474 		break;
475 	}
476 	return (error);
477 }
478 
479 int
480 sys_sigpending(struct proc *p, void *v, register_t *retval)
481 {
482 	*retval = p->p_siglist | p->p_p->ps_siglist;
483 	return (0);
484 }
485 
486 /*
487  * Temporarily replace calling proc's signal mask for the duration of a
488  * system call.  Original signal mask will be restored by userret().
489  */
490 void
491 dosigsuspend(struct proc *p, sigset_t newmask)
492 {
493 	KASSERT(p == curproc);
494 
495 	p->p_oldmask = p->p_sigmask;
496 	p->p_sigmask = newmask;
497 	atomic_setbits_int(&p->p_flag, P_SIGSUSPEND);
498 }
499 
500 /*
501  * Suspend thread until signal, providing mask to be set
502  * in the meantime.  Note nonstandard calling convention:
503  * libc stub passes mask, not pointer, to save a copyin.
504  */
505 int
506 sys_sigsuspend(struct proc *p, void *v, register_t *retval)
507 {
508 	struct sys_sigsuspend_args /* {
509 		syscallarg(int) mask;
510 	} */ *uap = v;
511 
512 	dosigsuspend(p, SCARG(uap, mask) &~ sigcantmask);
513 	while (tsleep_nsec(&nowake, PPAUSE|PCATCH, "sigsusp", INFSLP) == 0)
514 		continue;
515 	/* always return EINTR rather than ERESTART... */
516 	return (EINTR);
517 }
518 
519 int
520 sigonstack(size_t stack)
521 {
522 	const struct sigaltstack *ss = &curproc->p_sigstk;
523 
524 	return (ss->ss_flags & SS_DISABLE ? 0 :
525 	    (stack - (size_t)ss->ss_sp < ss->ss_size));
526 }
527 
528 int
529 sys_sigaltstack(struct proc *p, void *v, register_t *retval)
530 {
531 	struct sys_sigaltstack_args /* {
532 		syscallarg(const struct sigaltstack *) nss;
533 		syscallarg(struct sigaltstack *) oss;
534 	} */ *uap = v;
535 	struct sigaltstack ss;
536 	const struct sigaltstack *nss;
537 	struct sigaltstack *oss;
538 	int onstack = sigonstack(PROC_STACK(p));
539 	int error;
540 
541 	nss = SCARG(uap, nss);
542 	oss = SCARG(uap, oss);
543 
544 	if (oss != NULL) {
545 		ss = p->p_sigstk;
546 		if (onstack)
547 			ss.ss_flags |= SS_ONSTACK;
548 		if ((error = copyout(&ss, oss, sizeof(ss))))
549 			return (error);
550 	}
551 	if (nss == NULL)
552 		return (0);
553 	error = copyin(nss, &ss, sizeof(ss));
554 	if (error)
555 		return (error);
556 	if (onstack)
557 		return (EPERM);
558 	if (ss.ss_flags & ~SS_DISABLE)
559 		return (EINVAL);
560 	if (ss.ss_flags & SS_DISABLE) {
561 		p->p_sigstk.ss_flags = ss.ss_flags;
562 		return (0);
563 	}
564 	if (ss.ss_size < MINSIGSTKSZ)
565 		return (ENOMEM);
566 
567 	error = uvm_map_remap_as_stack(p, (vaddr_t)ss.ss_sp, ss.ss_size);
568 	if (error)
569 		return (error);
570 
571 	p->p_sigstk = ss;
572 	return (0);
573 }
574 
575 int
576 sys_kill(struct proc *cp, void *v, register_t *retval)
577 {
578 	struct sys_kill_args /* {
579 		syscallarg(int) pid;
580 		syscallarg(int) signum;
581 	} */ *uap = v;
582 	struct process *pr;
583 	int pid = SCARG(uap, pid);
584 	int signum = SCARG(uap, signum);
585 	int error;
586 	int zombie = 0;
587 
588 	if ((error = pledge_kill(cp, pid)) != 0)
589 		return (error);
590 	if (((u_int)signum) >= NSIG)
591 		return (EINVAL);
592 	if (pid > 0) {
593 		if ((pr = prfind(pid)) == NULL) {
594 			if ((pr = zombiefind(pid)) == NULL)
595 				return (ESRCH);
596 			else
597 				zombie = 1;
598 		}
599 		if (!cansignal(cp, pr, signum))
600 			return (EPERM);
601 
602 		/* kill single process */
603 		if (signum && !zombie)
604 			prsignal(pr, signum);
605 		return (0);
606 	}
607 	switch (pid) {
608 	case -1:		/* broadcast signal */
609 		return (killpg1(cp, signum, 0, 1));
610 	case 0:			/* signal own process group */
611 		return (killpg1(cp, signum, 0, 0));
612 	default:		/* negative explicit process group */
613 		return (killpg1(cp, signum, -pid, 0));
614 	}
615 }
616 
617 int
618 sys_thrkill(struct proc *cp, void *v, register_t *retval)
619 {
620 	struct sys_thrkill_args /* {
621 		syscallarg(pid_t) tid;
622 		syscallarg(int) signum;
623 		syscallarg(void *) tcb;
624 	} */ *uap = v;
625 	struct proc *p;
626 	int tid = SCARG(uap, tid);
627 	int signum = SCARG(uap, signum);
628 	void *tcb;
629 
630 	if (((u_int)signum) >= NSIG)
631 		return (EINVAL);
632 
633 	p = tid ? tfind_user(tid, cp->p_p) : cp;
634 	if (p == NULL)
635 		return (ESRCH);
636 
637 	/* optionally require the target thread to have the given tcb addr */
638 	tcb = SCARG(uap, tcb);
639 	if (tcb != NULL && tcb != TCB_GET(p))
640 		return (ESRCH);
641 
642 	if (signum)
643 		ptsignal(p, signum, STHREAD);
644 	return (0);
645 }
646 
647 /*
648  * Common code for kill process group/broadcast kill.
649  * cp is calling process.
650  */
651 int
652 killpg1(struct proc *cp, int signum, int pgid, int all)
653 {
654 	struct process *pr;
655 	struct pgrp *pgrp;
656 	int nfound = 0;
657 
658 	if (all) {
659 		/*
660 		 * broadcast
661 		 */
662 		LIST_FOREACH(pr, &allprocess, ps_list) {
663 			if (pr->ps_pid <= 1 ||
664 			    pr->ps_flags & (PS_SYSTEM | PS_NOBROADCASTKILL) ||
665 			    pr == cp->p_p || !cansignal(cp, pr, signum))
666 				continue;
667 			nfound++;
668 			if (signum)
669 				prsignal(pr, signum);
670 		}
671 	} else {
672 		if (pgid == 0)
673 			/*
674 			 * zero pgid means send to my process group.
675 			 */
676 			pgrp = cp->p_p->ps_pgrp;
677 		else {
678 			pgrp = pgfind(pgid);
679 			if (pgrp == NULL)
680 				return (ESRCH);
681 		}
682 		LIST_FOREACH(pr, &pgrp->pg_members, ps_pglist) {
683 			if (pr->ps_pid <= 1 || pr->ps_flags & PS_SYSTEM ||
684 			    !cansignal(cp, pr, signum))
685 				continue;
686 			nfound++;
687 			if (signum)
688 				prsignal(pr, signum);
689 		}
690 	}
691 	return (nfound ? 0 : ESRCH);
692 }
693 
694 #define CANDELIVER(uid, euid, pr) \
695 	(euid == 0 || \
696 	(uid) == (pr)->ps_ucred->cr_ruid || \
697 	(uid) == (pr)->ps_ucred->cr_svuid || \
698 	(uid) == (pr)->ps_ucred->cr_uid || \
699 	(euid) == (pr)->ps_ucred->cr_ruid || \
700 	(euid) == (pr)->ps_ucred->cr_svuid || \
701 	(euid) == (pr)->ps_ucred->cr_uid)
702 
703 #define CANSIGIO(cr, pr) \
704 	CANDELIVER((cr)->cr_ruid, (cr)->cr_uid, (pr))
705 
706 /*
707  * Send a signal to a process group.  If checktty is 1,
708  * limit to members which have a controlling terminal.
709  */
710 void
711 pgsignal(struct pgrp *pgrp, int signum, int checkctty)
712 {
713 	struct process *pr;
714 
715 	if (pgrp)
716 		LIST_FOREACH(pr, &pgrp->pg_members, ps_pglist)
717 			if (checkctty == 0 || pr->ps_flags & PS_CONTROLT)
718 				prsignal(pr, signum);
719 }
720 
721 /*
722  * Send a SIGIO or SIGURG signal to a process or process group using stored
723  * credentials rather than those of the current process.
724  */
725 void
726 pgsigio(struct sigio_ref *sir, int sig, int checkctty)
727 {
728 	struct process *pr;
729 	struct sigio *sigio;
730 
731 	if (sir->sir_sigio == NULL)
732 		return;
733 
734 	KERNEL_LOCK();
735 	mtx_enter(&sigio_lock);
736 	sigio = sir->sir_sigio;
737 	if (sigio == NULL)
738 		goto out;
739 	if (sigio->sio_pgid > 0) {
740 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc))
741 			prsignal(sigio->sio_proc, sig);
742 	} else if (sigio->sio_pgid < 0) {
743 		LIST_FOREACH(pr, &sigio->sio_pgrp->pg_members, ps_pglist) {
744 			if (CANSIGIO(sigio->sio_ucred, pr) &&
745 			    (checkctty == 0 || (pr->ps_flags & PS_CONTROLT)))
746 				prsignal(pr, sig);
747 		}
748 	}
749 out:
750 	mtx_leave(&sigio_lock);
751 	KERNEL_UNLOCK();
752 }
753 
754 /*
755  * Recalculate the signal mask and reset the signal disposition after
756  * usermode frame for delivery is formed.
757  */
758 void
759 postsig_done(struct proc *p, int signum, sigset_t catchmask, int reset)
760 {
761 	p->p_ru.ru_nsignals++;
762 	SET(p->p_sigmask, catchmask);
763 	if (reset != 0) {
764 		sigset_t mask = sigmask(signum);
765 		struct sigacts *ps = p->p_p->ps_sigacts;
766 
767 		mtx_enter(&p->p_p->ps_mtx);
768 		ps->ps_sigcatch &= ~mask;
769 		if (signum != SIGCONT && sigprop[signum] & SA_IGNORE)
770 			ps->ps_sigignore |= mask;
771 		ps->ps_sigact[signum] = SIG_DFL;
772 		mtx_leave(&p->p_p->ps_mtx);
773 	}
774 }
775 
776 /*
777  * Send a signal caused by a trap to the current thread
778  * If it will be caught immediately, deliver it with correct code.
779  * Otherwise, post it normally.
780  */
781 void
782 trapsignal(struct proc *p, int signum, u_long trapno, int code,
783     union sigval sigval)
784 {
785 	struct process *pr = p->p_p;
786 	struct sigctx ctx;
787 	int mask;
788 
789 	switch (signum) {
790 	case SIGILL:
791 		if (code == ILL_BTCFI) {
792 			pr->ps_acflag |= ABTCFI;
793 			break;
794 		}
795 		/* FALLTHROUGH */
796 	case SIGBUS:
797 	case SIGSEGV:
798 		pr->ps_acflag |= ATRAP;
799 		break;
800 	}
801 
802 	mask = sigmask(signum);
803 	setsigctx(p, signum, &ctx);
804 	if ((pr->ps_flags & PS_TRACED) == 0 && ctx.sig_catch != 0 &&
805 	    (p->p_sigmask & mask) == 0) {
806 		siginfo_t si;
807 
808 		initsiginfo(&si, signum, trapno, code, sigval);
809 #ifdef KTRACE
810 		if (KTRPOINT(p, KTR_PSIG)) {
811 			ktrpsig(p, signum, ctx.sig_action,
812 			    p->p_sigmask, code, &si);
813 		}
814 #endif
815 		if (sendsig(ctx.sig_action, signum, p->p_sigmask, &si,
816 		    ctx.sig_info, ctx.sig_onstack)) {
817 			KERNEL_LOCK();
818 			sigexit(p, SIGILL);
819 			/* NOTREACHED */
820 		}
821 		postsig_done(p, signum, ctx.sig_catchmask, ctx.sig_reset);
822 	} else {
823 		p->p_sisig = signum;
824 		p->p_sitrapno = trapno;	/* XXX for core dump/debugger */
825 		p->p_sicode = code;
826 		p->p_sigval = sigval;
827 
828 		/*
829 		 * If traced, stop if signal is masked, and stay stopped
830 		 * until released by the debugger.  If our parent process
831 		 * is waiting for us, don't hang as we could deadlock.
832 		 */
833 		if (((pr->ps_flags & (PS_TRACED | PS_PPWAIT)) == PS_TRACED) &&
834 		    signum != SIGKILL && (p->p_sigmask & mask) != 0) {
835 			single_thread_set(p, SINGLE_SUSPEND | SINGLE_NOWAIT);
836 			pr->ps_xsig = signum;
837 
838 			SCHED_LOCK();
839 			proc_stop(p, 1);
840 			SCHED_UNLOCK();
841 
842 			signum = pr->ps_xsig;
843 			single_thread_clear(p, 0);
844 
845 			/*
846 			 * If we are no longer being traced, or the parent
847 			 * didn't give us a signal, skip sending the signal.
848 			 */
849 			if ((pr->ps_flags & PS_TRACED) == 0 ||
850 			    signum == 0)
851 				return;
852 
853 			/* update signal info */
854 			p->p_sisig = signum;
855 			mask = sigmask(signum);
856 		}
857 
858 		/*
859 		 * Signals like SIGBUS and SIGSEGV should not, when
860 		 * generated by the kernel, be ignorable or blockable.
861 		 * If it is and we're not being traced, then just kill
862 		 * the process.
863 		 * After vfs_shutdown(9), init(8) cannot receive signals
864 		 * because new code pages of the signal handler cannot be
865 		 * mapped from halted storage.  init(8) may not die or the
866 		 * kernel panics.  Better loop between signal handler and
867 		 * page fault trap until the machine is halted.
868 		 */
869 		if ((pr->ps_flags & PS_TRACED) == 0 &&
870 		    (sigprop[signum] & SA_KILL) &&
871 		    ((p->p_sigmask & mask) || ctx.sig_ignore) &&
872 		    pr->ps_pid != 1) {
873 			KERNEL_LOCK();
874 			sigexit(p, signum);
875 			/* NOTREACHED */
876 		}
877 		KERNEL_LOCK();
878 		ptsignal(p, signum, STHREAD);
879 		KERNEL_UNLOCK();
880 	}
881 }
882 
883 /*
884  * Send the signal to the process.  If the signal has an action, the action
885  * is usually performed by the target process rather than the caller; we add
886  * the signal to the set of pending signals for the process.
887  *
888  * Exceptions:
889  *   o When a stop signal is sent to a sleeping process that takes the
890  *     default action, the process is stopped without awakening it.
891  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
892  *     regardless of the signal action (eg, blocked or ignored).
893  *
894  * Other ignored signals are discarded immediately.
895  */
896 void
897 psignal(struct proc *p, int signum)
898 {
899 	ptsignal(p, signum, SPROCESS);
900 }
901 
902 /*
903  * type = SPROCESS	process signal, can be diverted (sigwait())
904  * type = STHREAD	thread signal, but should be propagated if unhandled
905  * type = SPROPAGATED	propagated to this thread, so don't propagate again
906  */
907 void
908 ptsignal(struct proc *p, int signum, enum signal_type type)
909 {
910 	int prop;
911 	sig_t action, altaction = SIG_DFL;
912 	sigset_t mask, sigmask;
913 	int *siglist;
914 	struct process *pr = p->p_p;
915 	struct proc *q;
916 	int wakeparent = 0;
917 
918 	KERNEL_ASSERT_LOCKED();
919 
920 #ifdef DIAGNOSTIC
921 	if ((u_int)signum >= NSIG || signum == 0)
922 		panic("psignal signal number");
923 #endif
924 
925 	/* Ignore signal if the target process is exiting */
926 	if (pr->ps_flags & PS_EXITING)
927 		return;
928 
929 	mask = sigmask(signum);
930 	sigmask = READ_ONCE(p->p_sigmask);
931 
932 	if (type == SPROCESS) {
933 		sigset_t tmpmask;
934 
935 		/* Accept SIGKILL to coredumping processes */
936 		if (pr->ps_flags & PS_COREDUMP && signum == SIGKILL) {
937 			atomic_setbits_int(&pr->ps_siglist, mask);
938 			return;
939 		}
940 
941 		/*
942 		 * If the current thread can process the signal
943 		 * immediately (it's unblocked) then have it take it.
944 		 */
945 		q = curproc;
946 		tmpmask = READ_ONCE(q->p_sigmask);
947 		if (q->p_p == pr && (q->p_flag & P_WEXIT) == 0 &&
948 		    (tmpmask & mask) == 0) {
949 			p = q;
950 			sigmask = tmpmask;
951 		} else {
952 			/*
953 			 * A process-wide signal can be diverted to a
954 			 * different thread that's in sigwait() for this
955 			 * signal.  If there isn't such a thread, then
956 			 * pick a thread that doesn't have it blocked so
957 			 * that the stop/kill consideration isn't
958 			 * delayed.  Otherwise, mark it pending on the
959 			 * main thread.
960 			 */
961 			TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
962 
963 				/* ignore exiting threads */
964 				if (q->p_flag & P_WEXIT)
965 					continue;
966 
967 				/* skip threads that have the signal blocked */
968 				tmpmask = READ_ONCE(q->p_sigmask);
969 				if ((tmpmask & mask) != 0)
970 					continue;
971 
972 				/* okay, could send to this thread */
973 				p = q;
974 				sigmask = tmpmask;
975 
976 				/*
977 				 * sigsuspend, sigwait, ppoll/pselect, etc?
978 				 * Definitely go to this thread, as it's
979 				 * already blocked in the kernel.
980 				 */
981 				if (q->p_flag & P_SIGSUSPEND)
982 					break;
983 			}
984 		}
985 	}
986 
987 	if (type != SPROPAGATED)
988 		knote_locked(&pr->ps_klist, NOTE_SIGNAL | signum);
989 
990 	prop = sigprop[signum];
991 
992 	/*
993 	 * If proc is traced, always give parent a chance.
994 	 */
995 	if (pr->ps_flags & PS_TRACED) {
996 		action = SIG_DFL;
997 	} else {
998 		sigset_t sigcatch, sigignore;
999 
1000 		/*
1001 		 * If the signal is being ignored,
1002 		 * then we forget about it immediately.
1003 		 * (Note: we don't set SIGCONT in ps_sigignore,
1004 		 * and if it is set to SIG_IGN,
1005 		 * action will be SIG_DFL here.)
1006 		 */
1007 		mtx_enter(&pr->ps_mtx);
1008 		sigignore = pr->ps_sigacts->ps_sigignore;
1009 		sigcatch = pr->ps_sigacts->ps_sigcatch;
1010 		mtx_leave(&pr->ps_mtx);
1011 
1012 		if (sigignore & mask)
1013 			return;
1014 		if (sigmask & mask) {
1015 			action = SIG_HOLD;
1016 			if (sigcatch & mask)
1017 				altaction = SIG_CATCH;
1018 		} else if (sigcatch & mask) {
1019 			action = SIG_CATCH;
1020 		} else {
1021 			action = SIG_DFL;
1022 
1023 			if (prop & SA_KILL && pr->ps_nice > NZERO)
1024 				 pr->ps_nice = NZERO;
1025 
1026 			/*
1027 			 * If sending a tty stop signal to a member of an
1028 			 * orphaned process group, discard the signal here if
1029 			 * the action is default; don't stop the process below
1030 			 * if sleeping, and don't clear any pending SIGCONT.
1031 			 */
1032 			if (prop & SA_TTYSTOP && pr->ps_pgrp->pg_jobc == 0)
1033 				return;
1034 		}
1035 	}
1036 	/*
1037 	 * If delivered to process, mark as pending there.  Continue and stop
1038 	 * signals will be propagated to all threads.  So they are always
1039 	 * marked at thread level.
1040 	 */
1041 	siglist = (type == SPROCESS) ? &pr->ps_siglist : &p->p_siglist;
1042 	if (prop & (SA_CONT | SA_STOP))
1043 		siglist = &p->p_siglist;
1044 
1045 	/*
1046 	 * XXX delay processing of SA_STOP signals unless action == SIG_DFL?
1047 	 */
1048 	if (prop & (SA_CONT | SA_STOP) && type != SPROPAGATED)
1049 		TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link)
1050 			if (q != p)
1051 				ptsignal(q, signum, SPROPAGATED);
1052 
1053 	SCHED_LOCK();
1054 
1055 	switch (p->p_stat) {
1056 
1057 	case SSTOP:
1058 		/*
1059 		 * If traced process is already stopped,
1060 		 * then no further action is necessary.
1061 		 */
1062 		if (pr->ps_flags & PS_TRACED)
1063 			goto out;
1064 
1065 		/*
1066 		 * Kill signal always sets processes running.
1067 		 */
1068 		if (signum == SIGKILL) {
1069 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1070 			/* Raise priority to at least PUSER. */
1071 			if (p->p_usrpri > PUSER)
1072 				p->p_usrpri = PUSER;
1073 			unsleep(p);
1074 			setrunnable(p);
1075 			goto out;
1076 		}
1077 
1078 		if (prop & SA_CONT) {
1079 			/*
1080 			 * If SIGCONT is default (or ignored), we continue the
1081 			 * process but don't leave the signal in p_siglist, as
1082 			 * it has no further action.  If SIGCONT is held, we
1083 			 * continue the process and leave the signal in
1084 			 * p_siglist.  If the process catches SIGCONT, let it
1085 			 * handle the signal itself.  If it isn't waiting on
1086 			 * an event, then it goes back to run state.
1087 			 * Otherwise, process goes back to sleep state.
1088 			 */
1089 			atomic_setbits_int(&pr->ps_flags, PS_CONTINUED);
1090 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1091 			wakeparent = 1;
1092 			if (action == SIG_DFL)
1093 				mask = 0;
1094 			if (action == SIG_CATCH) {
1095 				/* Raise priority to at least PUSER. */
1096 				if (p->p_usrpri > PUSER)
1097 					p->p_usrpri = PUSER;
1098 				unsleep(p);
1099 				setrunnable(p);
1100 				goto out;
1101 			}
1102 			if (p->p_wchan == NULL) {
1103 				unsleep(p);
1104 				setrunnable(p);
1105 				goto out;
1106 			}
1107 			atomic_clearbits_int(&p->p_flag, P_WSLEEP);
1108 			p->p_stat = SSLEEP;
1109 			goto out;
1110 		}
1111 
1112 		/*
1113 		 * Defer further processing for signals which are held,
1114 		 * except that stopped processes must be continued by SIGCONT.
1115 		 */
1116 		if (action == SIG_HOLD)
1117 			goto out;
1118 
1119 		if (prop & SA_STOP) {
1120 			/*
1121 			 * Already stopped, don't need to stop again.
1122 			 * (If we did the shell could get confused.)
1123 			 */
1124 			mask = 0;
1125 			goto out;
1126 		}
1127 
1128 		/*
1129 		 * If process is sleeping interruptibly, then simulate a
1130 		 * wakeup so that when it is continued, it will be made
1131 		 * runnable and can look at the signal.  But don't make
1132 		 * the process runnable, leave it stopped.
1133 		 */
1134 		if (p->p_flag & P_SINTR)
1135 			unsleep(p);
1136 		goto out;
1137 
1138 	case SSLEEP:
1139 		/*
1140 		 * If process is sleeping uninterruptibly
1141 		 * we can't interrupt the sleep... the signal will
1142 		 * be noticed when the process returns through
1143 		 * trap() or syscall().
1144 		 */
1145 		if ((p->p_flag & P_SINTR) == 0)
1146 			goto out;
1147 		/*
1148 		 * Process is sleeping and traced... make it runnable
1149 		 * so it can discover the signal in cursig() and stop
1150 		 * for the parent.
1151 		 */
1152 		if (pr->ps_flags & PS_TRACED) {
1153 			unsleep(p);
1154 			setrunnable(p);
1155 			goto out;
1156 		}
1157 
1158 		/*
1159 		 * Recheck sigmask before waking up the process,
1160 		 * there is a chance that while sending the signal
1161 		 * the process changed sigmask and went to sleep.
1162 		 */
1163 		sigmask = READ_ONCE(p->p_sigmask);
1164 		if (sigmask & mask)
1165 			goto out;
1166 		else if (action == SIG_HOLD) {
1167 			/* signal got unmasked, get proper action */
1168 			action = altaction;
1169 
1170 			if (action == SIG_DFL) {
1171 				if (prop & SA_KILL && pr->ps_nice > NZERO)
1172 					 pr->ps_nice = NZERO;
1173 
1174 				/*
1175 				 * Discard tty stop signals sent to an
1176 				 * orphaned process group, see above.
1177 				 */
1178 				if (prop & SA_TTYSTOP &&
1179 				    pr->ps_pgrp->pg_jobc == 0) {
1180 					mask = 0;
1181 					prop = 0;
1182 					goto out;
1183 				}
1184 			}
1185 		}
1186 
1187 		/*
1188 		 * If SIGCONT is default (or ignored) and process is
1189 		 * asleep, we are finished; the process should not
1190 		 * be awakened.
1191 		 */
1192 		if ((prop & SA_CONT) && action == SIG_DFL) {
1193 			mask = 0;
1194 			goto out;
1195 		}
1196 		/*
1197 		 * When a sleeping process receives a stop
1198 		 * signal, process immediately if possible.
1199 		 */
1200 		if ((prop & SA_STOP) && action == SIG_DFL) {
1201 			/*
1202 			 * If a child holding parent blocked,
1203 			 * stopping could cause deadlock.
1204 			 */
1205 			if (pr->ps_flags & PS_PPWAIT)
1206 				goto out;
1207 			mask = 0;
1208 			pr->ps_xsig = signum;
1209 			proc_stop(p, 0);
1210 			goto out;
1211 		}
1212 		/*
1213 		 * All other (caught or default) signals
1214 		 * cause the process to run.
1215 		 * Raise priority to at least PUSER.
1216 		 */
1217 		if (p->p_usrpri > PUSER)
1218 			p->p_usrpri = PUSER;
1219 		unsleep(p);
1220 		setrunnable(p);
1221 		goto out;
1222 		/* NOTREACHED */
1223 
1224 	case SONPROC:
1225 		if (action == SIG_HOLD)
1226 			goto out;
1227 
1228 		/* set siglist before issuing the ast */
1229 		atomic_setbits_int(siglist, mask);
1230 		mask = 0;
1231 		signotify(p);
1232 		/* FALLTHROUGH */
1233 	default:
1234 		/*
1235 		 * SRUN, SIDL, SDEAD do nothing with the signal,
1236 		 * other than kicking ourselves if we are running.
1237 		 * It will either never be noticed, or noticed very soon.
1238 		 */
1239 		goto out;
1240 	}
1241 	/* NOTREACHED */
1242 
1243 out:
1244 	/* finally adjust siglist */
1245 	if (mask)
1246 		atomic_setbits_int(siglist, mask);
1247 	if (prop & SA_CONT) {
1248 		atomic_clearbits_int(siglist, STOPSIGMASK);
1249 	}
1250 	if (prop & SA_STOP) {
1251 		atomic_clearbits_int(siglist, CONTSIGMASK);
1252 		atomic_clearbits_int(&pr->ps_flags, PS_CONTINUED);
1253 	}
1254 
1255 	SCHED_UNLOCK();
1256 	if (wakeparent)
1257 		wakeup(pr->ps_pptr);
1258 }
1259 
1260 /* fill the signal context which should be used by postsig() and issignal() */
1261 void
1262 setsigctx(struct proc *p, int signum, struct sigctx *sctx)
1263 {
1264 	struct sigacts *ps = p->p_p->ps_sigacts;
1265 	sigset_t mask;
1266 
1267 	mtx_enter(&p->p_p->ps_mtx);
1268 	mask = sigmask(signum);
1269 	sctx->sig_action = ps->ps_sigact[signum];
1270 	sctx->sig_catchmask = ps->ps_catchmask[signum];
1271 	sctx->sig_reset = (ps->ps_sigreset & mask) != 0;
1272 	sctx->sig_info = (ps->ps_siginfo & mask) != 0;
1273 	sctx->sig_intr = (ps->ps_sigintr & mask) != 0;
1274 	sctx->sig_onstack = (ps->ps_sigonstack & mask) != 0;
1275 	sctx->sig_ignore = (ps->ps_sigignore & mask) != 0;
1276 	sctx->sig_catch = (ps->ps_sigcatch & mask) != 0;
1277 	mtx_leave(&p->p_p->ps_mtx);
1278 }
1279 
1280 /*
1281  * Determine signal that should be delivered to process p, the current
1282  * process, 0 if none.
1283  *
1284  * If the current process has received a signal (should be caught or cause
1285  * termination, should interrupt current syscall), return the signal number.
1286  * Stop signals with default action are processed immediately, then cleared;
1287  * they aren't returned.  This is checked after each entry to the system for
1288  * a syscall or trap. The normal call sequence is
1289  *
1290  *	while (signum = cursig(curproc, &ctx))
1291  *		postsig(signum, &ctx);
1292  *
1293  * Assumes that if the P_SINTR flag is set, we're holding both the
1294  * kernel and scheduler locks.
1295  */
1296 int
1297 cursig(struct proc *p, struct sigctx *sctx)
1298 {
1299 	struct process *pr = p->p_p;
1300 	int signum, mask, prop;
1301 	sigset_t ps_siglist;
1302 
1303 	KASSERT(p == curproc);
1304 
1305 	for (;;) {
1306 		ps_siglist = READ_ONCE(pr->ps_siglist);
1307 		membar_consumer();
1308 		mask = SIGPENDING(p);
1309 		if (pr->ps_flags & PS_PPWAIT)
1310 			mask &= ~STOPSIGMASK;
1311 		if (mask == 0)	 	/* no signal to send */
1312 			return (0);
1313 		signum = ffs((long)mask);
1314 		mask = sigmask(signum);
1315 
1316 		/* take the signal! */
1317 		if (atomic_cas_uint(&pr->ps_siglist, ps_siglist,
1318 		    ps_siglist & ~mask) != ps_siglist) {
1319 			/* lost race taking the process signal, restart */
1320 			continue;
1321 		}
1322 		atomic_clearbits_int(&p->p_siglist, mask);
1323 		setsigctx(p, signum, sctx);
1324 
1325 		/*
1326 		 * We should see pending but ignored signals
1327 		 * only if PS_TRACED was on when they were posted.
1328 		 */
1329 		if (sctx->sig_ignore && (pr->ps_flags & PS_TRACED) == 0)
1330 			continue;
1331 
1332 		/*
1333 		 * If traced, always stop, and stay stopped until released
1334 		 * by the debugger.  If our parent process is waiting for
1335 		 * us, don't hang as we could deadlock.
1336 		 */
1337 		if (((pr->ps_flags & (PS_TRACED | PS_PPWAIT)) == PS_TRACED) &&
1338 		    signum != SIGKILL) {
1339 			single_thread_set(p, SINGLE_SUSPEND | SINGLE_NOWAIT);
1340 			pr->ps_xsig = signum;
1341 
1342 			SCHED_LOCK();
1343 			proc_stop(p, 1);
1344 			SCHED_UNLOCK();
1345 
1346 			/*
1347 			 * re-take the signal before releasing
1348 			 * the other threads. Must check the continue
1349 			 * conditions below and only take the signal if
1350 			 * those are not true.
1351 			 */
1352 			signum = pr->ps_xsig;
1353 			mask = sigmask(signum);
1354 			setsigctx(p, signum, sctx);
1355 			if (!((pr->ps_flags & PS_TRACED) == 0 ||
1356 			    signum == 0 ||
1357 			    (p->p_sigmask & mask) != 0)) {
1358 				atomic_clearbits_int(&p->p_siglist, mask);
1359 				atomic_clearbits_int(&pr->ps_siglist, mask);
1360 			}
1361 
1362 			single_thread_clear(p, 0);
1363 
1364 			/*
1365 			 * If we are no longer being traced, or the parent
1366 			 * didn't give us a signal, look for more signals.
1367 			 */
1368 			if ((pr->ps_flags & PS_TRACED) == 0 ||
1369 			    signum == 0)
1370 				continue;
1371 
1372 			/*
1373 			 * If the new signal is being masked, look for other
1374 			 * signals.
1375 			 */
1376 			if ((p->p_sigmask & mask) != 0)
1377 				continue;
1378 
1379 		}
1380 
1381 		prop = sigprop[signum];
1382 
1383 		/*
1384 		 * Decide whether the signal should be returned.
1385 		 * Return the signal's number, or fall through
1386 		 * to clear it from the pending mask.
1387 		 */
1388 		switch ((long)sctx->sig_action) {
1389 		case (long)SIG_DFL:
1390 			/*
1391 			 * Don't take default actions on system processes.
1392 			 */
1393 			if (pr->ps_pid <= 1) {
1394 #ifdef DIAGNOSTIC
1395 				/*
1396 				 * Are you sure you want to ignore SIGSEGV
1397 				 * in init? XXX
1398 				 */
1399 				printf("Process (pid %d) got signal"
1400 				    " %d\n", pr->ps_pid, signum);
1401 #endif
1402 				break;		/* == ignore */
1403 			}
1404 			/*
1405 			 * If there is a pending stop signal to process
1406 			 * with default action, stop here,
1407 			 * then clear the signal.  However,
1408 			 * if process is member of an orphaned
1409 			 * process group, ignore tty stop signals.
1410 			 */
1411 			if (prop & SA_STOP) {
1412 				if (pr->ps_flags & PS_TRACED ||
1413 		    		    (pr->ps_pgrp->pg_jobc == 0 &&
1414 				    prop & SA_TTYSTOP))
1415 					break;	/* == ignore */
1416 				pr->ps_xsig = signum;
1417 				SCHED_LOCK();
1418 				proc_stop(p, 1);
1419 				SCHED_UNLOCK();
1420 				break;
1421 			} else if (prop & SA_IGNORE) {
1422 				/*
1423 				 * Except for SIGCONT, shouldn't get here.
1424 				 * Default action is to ignore; drop it.
1425 				 */
1426 				break;		/* == ignore */
1427 			} else
1428 				goto keep;
1429 			/* NOTREACHED */
1430 		case (long)SIG_IGN:
1431 			/*
1432 			 * Masking above should prevent us ever trying
1433 			 * to take action on an ignored signal other
1434 			 * than SIGCONT, unless process is traced.
1435 			 */
1436 			if ((prop & SA_CONT) == 0 &&
1437 			    (pr->ps_flags & PS_TRACED) == 0)
1438 				printf("%s\n", __func__);
1439 			break;		/* == ignore */
1440 		default:
1441 			/*
1442 			 * This signal has an action, let
1443 			 * postsig() process it.
1444 			 */
1445 			goto keep;
1446 		}
1447 	}
1448 	/* NOTREACHED */
1449 
1450 keep:
1451 	atomic_setbits_int(&p->p_siglist, mask); /*leave the signal for later */
1452 	return (signum);
1453 }
1454 
1455 /*
1456  * Put the argument process into the stopped state and notify the parent
1457  * via wakeup.  Signals are handled elsewhere.  The process must not be
1458  * on the run queue.
1459  */
1460 void
1461 proc_stop(struct proc *p, int sw)
1462 {
1463 	struct process *pr = p->p_p;
1464 
1465 #ifdef MULTIPROCESSOR
1466 	SCHED_ASSERT_LOCKED();
1467 #endif
1468 	/* do not stop exiting procs */
1469 	if (ISSET(p->p_flag, P_WEXIT))
1470 		return;
1471 
1472 	p->p_stat = SSTOP;
1473 	atomic_clearbits_int(&pr->ps_flags, PS_WAITED);
1474 	atomic_setbits_int(&pr->ps_flags, PS_STOPPING);
1475 	atomic_setbits_int(&p->p_flag, P_SUSPSIG);
1476 	/*
1477 	 * We need this soft interrupt to be handled fast.
1478 	 * Extra calls to softclock don't hurt.
1479 	 */
1480 	softintr_schedule(proc_stop_si);
1481 	if (sw)
1482 		mi_switch();
1483 }
1484 
1485 /*
1486  * Called from a soft interrupt to send signals to the parents of stopped
1487  * processes.
1488  * We can't do this in proc_stop because it's called with nasty locks held
1489  * and we would need recursive scheduler lock to deal with that.
1490  */
1491 void
1492 proc_stop_sweep(void *v)
1493 {
1494 	struct process *pr;
1495 
1496 	LIST_FOREACH(pr, &allprocess, ps_list) {
1497 		if ((pr->ps_flags & PS_STOPPING) == 0)
1498 			continue;
1499 		atomic_clearbits_int(&pr->ps_flags, PS_STOPPING);
1500 
1501 		if ((pr->ps_pptr->ps_sigacts->ps_sigflags & SAS_NOCLDSTOP) == 0)
1502 			prsignal(pr->ps_pptr, SIGCHLD);
1503 		wakeup(pr->ps_pptr);
1504 	}
1505 }
1506 
1507 /*
1508  * Take the action for the specified signal
1509  * from the current set of pending signals.
1510  */
1511 void
1512 postsig(struct proc *p, int signum, struct sigctx *sctx)
1513 {
1514 	u_long trapno;
1515 	int mask, returnmask;
1516 	siginfo_t si;
1517 	union sigval sigval;
1518 	int code;
1519 
1520 	KASSERT(signum != 0);
1521 
1522 	mask = sigmask(signum);
1523 	atomic_clearbits_int(&p->p_siglist, mask);
1524 	sigval.sival_ptr = NULL;
1525 
1526 	if (p->p_sisig != signum) {
1527 		trapno = 0;
1528 		code = SI_USER;
1529 		sigval.sival_ptr = NULL;
1530 	} else {
1531 		trapno = p->p_sitrapno;
1532 		code = p->p_sicode;
1533 		sigval = p->p_sigval;
1534 	}
1535 	initsiginfo(&si, signum, trapno, code, sigval);
1536 
1537 #ifdef KTRACE
1538 	if (KTRPOINT(p, KTR_PSIG)) {
1539 		ktrpsig(p, signum, sctx->sig_action, p->p_flag & P_SIGSUSPEND ?
1540 		    p->p_oldmask : p->p_sigmask, code, &si);
1541 	}
1542 #endif
1543 	if (sctx->sig_action == SIG_DFL) {
1544 		/*
1545 		 * Default action, where the default is to kill
1546 		 * the process.  (Other cases were ignored above.)
1547 		 */
1548 		KERNEL_LOCK();
1549 		sigexit(p, signum);
1550 		/* NOTREACHED */
1551 	} else {
1552 		/*
1553 		 * If we get here, the signal must be caught.
1554 		 */
1555 #ifdef DIAGNOSTIC
1556 		if (sctx->sig_action == SIG_IGN || (p->p_sigmask & mask))
1557 			panic("postsig action");
1558 #endif
1559 		/*
1560 		 * Set the new mask value and also defer further
1561 		 * occurrences of this signal.
1562 		 *
1563 		 * Special case: user has done a sigpause.  Here the
1564 		 * current mask is not of interest, but rather the
1565 		 * mask from before the sigpause is what we want
1566 		 * restored after the signal processing is completed.
1567 		 */
1568 		if (p->p_flag & P_SIGSUSPEND) {
1569 			atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
1570 			returnmask = p->p_oldmask;
1571 		} else {
1572 			returnmask = p->p_sigmask;
1573 		}
1574 		if (p->p_sisig == signum) {
1575 			p->p_sisig = 0;
1576 			p->p_sitrapno = 0;
1577 			p->p_sicode = SI_USER;
1578 			p->p_sigval.sival_ptr = NULL;
1579 		}
1580 
1581 		if (sendsig(sctx->sig_action, signum, returnmask, &si,
1582 		    sctx->sig_info, sctx->sig_onstack)) {
1583 			KERNEL_LOCK();
1584 			sigexit(p, SIGILL);
1585 			/* NOTREACHED */
1586 		}
1587 		postsig_done(p, signum, sctx->sig_catchmask, sctx->sig_reset);
1588 	}
1589 }
1590 
1591 /*
1592  * Force the current process to exit with the specified signal, dumping core
1593  * if appropriate.  We bypass the normal tests for masked and caught signals,
1594  * allowing unrecoverable failures to terminate the process without changing
1595  * signal state.  Mark the accounting record with the signal termination.
1596  * If dumping core, save the signal number for the debugger.  Calls exit and
1597  * does not return.
1598  */
1599 void
1600 sigexit(struct proc *p, int signum)
1601 {
1602 	/* Mark process as going away */
1603 	atomic_setbits_int(&p->p_flag, P_WEXIT);
1604 
1605 	p->p_p->ps_acflag |= AXSIG;
1606 	if (sigprop[signum] & SA_CORE) {
1607 		p->p_sisig = signum;
1608 
1609 		/* if there are other threads, pause them */
1610 		if (P_HASSIBLING(p))
1611 			single_thread_set(p, SINGLE_UNWIND);
1612 
1613 		if (coredump(p) == 0)
1614 			signum |= WCOREFLAG;
1615 	}
1616 	exit1(p, 0, signum, EXIT_NORMAL);
1617 	/* NOTREACHED */
1618 }
1619 
1620 /*
1621  * Send uncatchable SIGABRT for coredump.
1622  */
1623 void
1624 sigabort(struct proc *p)
1625 {
1626 	struct sigaction sa;
1627 
1628 	KASSERT(p == curproc || panicstr || db_active);
1629 
1630 	memset(&sa, 0, sizeof sa);
1631 	sa.sa_handler = SIG_DFL;
1632 	setsigvec(p, SIGABRT, &sa);
1633 	CLR(p->p_sigmask, sigmask(SIGABRT));
1634 	psignal(p, SIGABRT);
1635 }
1636 
1637 /*
1638  * Return 1 if `sig', a given signal, is ignored or masked for `p', a given
1639  * thread, and 0 otherwise.
1640  */
1641 int
1642 sigismasked(struct proc *p, int sig)
1643 {
1644 	struct process *pr = p->p_p;
1645 	int rv;
1646 
1647 	KASSERT(p == curproc);
1648 
1649 	mtx_enter(&pr->ps_mtx);
1650 	rv = (pr->ps_sigacts->ps_sigignore & sigmask(sig)) ||
1651 	    (p->p_sigmask & sigmask(sig));
1652 	mtx_leave(&pr->ps_mtx);
1653 
1654 	return !!rv;
1655 }
1656 
1657 struct coredump_iostate {
1658 	struct proc *io_proc;
1659 	struct vnode *io_vp;
1660 	struct ucred *io_cred;
1661 	off_t io_offset;
1662 };
1663 
1664 /*
1665  * Dump core, into a file named "progname.core", unless the process was
1666  * setuid/setgid.
1667  */
1668 int
1669 coredump(struct proc *p)
1670 {
1671 #ifdef SMALL_KERNEL
1672 	return EPERM;
1673 #else
1674 	struct process *pr = p->p_p;
1675 	struct vnode *vp;
1676 	struct ucred *cred = p->p_ucred;
1677 	struct vmspace *vm = p->p_vmspace;
1678 	struct nameidata nd;
1679 	struct vattr vattr;
1680 	struct coredump_iostate	io;
1681 	int error, len, incrash = 0;
1682 	char *name;
1683 	const char *dir = "/var/crash";
1684 
1685 	atomic_setbits_int(&pr->ps_flags, PS_COREDUMP);
1686 
1687 #ifdef PMAP_CHECK_COPYIN
1688 	/* disable copyin checks, so we can write out text sections if needed */
1689 	p->p_vmspace->vm_map.check_copyin_count = 0;
1690 #endif
1691 
1692 	/* Don't dump if will exceed file size limit. */
1693 	if (USPACE + ptoa(vm->vm_dsize + vm->vm_ssize) >= lim_cur(RLIMIT_CORE))
1694 		return (EFBIG);
1695 
1696 	name = pool_get(&namei_pool, PR_WAITOK);
1697 
1698 	/*
1699 	 * If the process has inconsistent uids, nosuidcoredump
1700 	 * determines coredump placement policy.
1701 	 */
1702 	if (((pr->ps_flags & PS_SUGID) && (error = suser(p))) ||
1703 	   ((pr->ps_flags & PS_SUGID) && nosuidcoredump)) {
1704 		if (nosuidcoredump == 3) {
1705 			/*
1706 			 * If the program directory does not exist, dumps of
1707 			 * that core will silently fail.
1708 			 */
1709 			len = snprintf(name, MAXPATHLEN, "%s/%s/%u.core",
1710 			    dir, pr->ps_comm, pr->ps_pid);
1711 			incrash = KERNELPATH;
1712 		} else if (nosuidcoredump == 2) {
1713 			len = snprintf(name, MAXPATHLEN, "%s/%s.core",
1714 			    dir, pr->ps_comm);
1715 			incrash = KERNELPATH;
1716 		} else {
1717 			pool_put(&namei_pool, name);
1718 			return (EPERM);
1719 		}
1720 	} else
1721 		len = snprintf(name, MAXPATHLEN, "%s.core", pr->ps_comm);
1722 
1723 	if (len >= MAXPATHLEN) {
1724 		pool_put(&namei_pool, name);
1725 		return (EACCES);
1726 	}
1727 
1728 	/*
1729 	 * Control the UID used to write out.  The normal case uses
1730 	 * the real UID.  If the sugid case is going to write into the
1731 	 * controlled directory, we do so as root.
1732 	 */
1733 	if (incrash == 0) {
1734 		cred = crdup(cred);
1735 		cred->cr_uid = cred->cr_ruid;
1736 		cred->cr_gid = cred->cr_rgid;
1737 	} else {
1738 		if (p->p_fd->fd_rdir) {
1739 			vrele(p->p_fd->fd_rdir);
1740 			p->p_fd->fd_rdir = NULL;
1741 		}
1742 		p->p_ucred = crdup(p->p_ucred);
1743 		crfree(cred);
1744 		cred = p->p_ucred;
1745 		crhold(cred);
1746 		cred->cr_uid = 0;
1747 		cred->cr_gid = 0;
1748 	}
1749 
1750 	/* incrash should be 0 or KERNELPATH only */
1751 	NDINIT(&nd, 0, BYPASSUNVEIL | incrash, UIO_SYSSPACE, name, p);
1752 
1753 	error = vn_open(&nd, O_CREAT | FWRITE | O_NOFOLLOW | O_NONBLOCK,
1754 	    S_IRUSR | S_IWUSR);
1755 
1756 	if (error)
1757 		goto out;
1758 
1759 	/*
1760 	 * Don't dump to non-regular files, files with links, or files
1761 	 * owned by someone else.
1762 	 */
1763 	vp = nd.ni_vp;
1764 	if ((error = VOP_GETATTR(vp, &vattr, cred, p)) != 0) {
1765 		VOP_UNLOCK(vp);
1766 		vn_close(vp, FWRITE, cred, p);
1767 		goto out;
1768 	}
1769 	if (vp->v_type != VREG || vattr.va_nlink != 1 ||
1770 	    vattr.va_mode & ((VREAD | VWRITE) >> 3 | (VREAD | VWRITE) >> 6) ||
1771 	    vattr.va_uid != cred->cr_uid) {
1772 		error = EACCES;
1773 		VOP_UNLOCK(vp);
1774 		vn_close(vp, FWRITE, cred, p);
1775 		goto out;
1776 	}
1777 	VATTR_NULL(&vattr);
1778 	vattr.va_size = 0;
1779 	VOP_SETATTR(vp, &vattr, cred, p);
1780 	pr->ps_acflag |= ACORE;
1781 
1782 	io.io_proc = p;
1783 	io.io_vp = vp;
1784 	io.io_cred = cred;
1785 	io.io_offset = 0;
1786 	VOP_UNLOCK(vp);
1787 	vref(vp);
1788 	error = vn_close(vp, FWRITE, cred, p);
1789 	if (error == 0)
1790 		error = coredump_elf(p, &io);
1791 	vrele(vp);
1792 out:
1793 	crfree(cred);
1794 	pool_put(&namei_pool, name);
1795 	return (error);
1796 #endif
1797 }
1798 
1799 #ifndef SMALL_KERNEL
1800 int
1801 coredump_write(void *cookie, enum uio_seg segflg, const void *data, size_t len,
1802     int isvnode)
1803 {
1804 	struct coredump_iostate *io = cookie;
1805 	off_t coffset = 0;
1806 	size_t csize;
1807 	int chunk, error;
1808 
1809 	csize = len;
1810 	do {
1811 		if (sigmask(SIGKILL) &
1812 		    (io->io_proc->p_siglist | io->io_proc->p_p->ps_siglist))
1813 			return (EINTR);
1814 
1815 		/* Rest of the loop sleeps with lock held, so... */
1816 		yield();
1817 
1818 		chunk = MIN(csize, MAXPHYS);
1819 		error = vn_rdwr(UIO_WRITE, io->io_vp,
1820 		    (caddr_t)data + coffset, chunk,
1821 		    io->io_offset + coffset, segflg,
1822 		    IO_UNIT, io->io_cred, NULL, io->io_proc);
1823 		if (error && (error != EFAULT || !isvnode)) {
1824 			struct process *pr = io->io_proc->p_p;
1825 
1826 			if (error == ENOSPC)
1827 				log(LOG_ERR,
1828 				    "coredump of %s(%d) failed, filesystem full\n",
1829 				    pr->ps_comm, pr->ps_pid);
1830 			else
1831 				log(LOG_ERR,
1832 				    "coredump of %s(%d), write failed: errno %d\n",
1833 				    pr->ps_comm, pr->ps_pid, error);
1834 			return (error);
1835 		}
1836 
1837 		coffset += chunk;
1838 		csize -= chunk;
1839 	} while (csize > 0);
1840 
1841 	io->io_offset += len;
1842 	return (0);
1843 }
1844 
1845 void
1846 coredump_unmap(void *cookie, vaddr_t start, vaddr_t end)
1847 {
1848 	struct coredump_iostate *io = cookie;
1849 
1850 	uvm_unmap(&io->io_proc->p_vmspace->vm_map, start, end);
1851 }
1852 
1853 #endif	/* !SMALL_KERNEL */
1854 
1855 /*
1856  * Nonexistent system call-- signal process (may want to handle it).
1857  * Flag error in case process won't see signal immediately (blocked or ignored).
1858  */
1859 int
1860 sys_nosys(struct proc *p, void *v, register_t *retval)
1861 {
1862 	ptsignal(p, SIGSYS, STHREAD);
1863 	return (ENOSYS);
1864 }
1865 
1866 int
1867 sys___thrsigdivert(struct proc *p, void *v, register_t *retval)
1868 {
1869 	struct sys___thrsigdivert_args /* {
1870 		syscallarg(sigset_t) sigmask;
1871 		syscallarg(siginfo_t *) info;
1872 		syscallarg(const struct timespec *) timeout;
1873 	} */ *uap = v;
1874 	struct sigctx ctx;
1875 	sigset_t mask = SCARG(uap, sigmask) &~ sigcantmask;
1876 	siginfo_t si;
1877 	uint64_t nsecs = INFSLP;
1878 	int timeinvalid = 0;
1879 	int error = 0;
1880 
1881 	memset(&si, 0, sizeof(si));
1882 
1883 	if (SCARG(uap, timeout) != NULL) {
1884 		struct timespec ts;
1885 		if ((error = copyin(SCARG(uap, timeout), &ts, sizeof(ts))) != 0)
1886 			return (error);
1887 #ifdef KTRACE
1888 		if (KTRPOINT(p, KTR_STRUCT))
1889 			ktrreltimespec(p, &ts);
1890 #endif
1891 		if (!timespecisvalid(&ts))
1892 			timeinvalid = 1;
1893 		else
1894 			nsecs = TIMESPEC_TO_NSEC(&ts);
1895 	}
1896 
1897 	dosigsuspend(p, p->p_sigmask &~ mask);
1898 	for (;;) {
1899 		si.si_signo = cursig(p, &ctx);
1900 		if (si.si_signo != 0) {
1901 			sigset_t smask = sigmask(si.si_signo);
1902 			if (smask & mask) {
1903 				atomic_clearbits_int(&p->p_siglist, smask);
1904 				error = 0;
1905 				break;
1906 			}
1907 		}
1908 
1909 		/* per-POSIX, delay this error until after the above */
1910 		if (timeinvalid)
1911 			error = EINVAL;
1912 		/* per-POSIX, return immediately if timeout is zero-valued */
1913 		if (nsecs == 0)
1914 			error = EAGAIN;
1915 
1916 		if (error != 0)
1917 			break;
1918 
1919 		error = tsleep_nsec(&nowake, PPAUSE|PCATCH, "sigwait", nsecs);
1920 	}
1921 
1922 	if (error == 0) {
1923 		*retval = si.si_signo;
1924 		if (SCARG(uap, info) != NULL) {
1925 			error = copyout(&si, SCARG(uap, info), sizeof(si));
1926 #ifdef KTRACE
1927 			if (error == 0 && KTRPOINT(p, KTR_STRUCT))
1928 				ktrsiginfo(p, &si);
1929 #endif
1930 		}
1931 	} else if (error == ERESTART && SCARG(uap, timeout) != NULL) {
1932 		/*
1933 		 * Restarting is wrong if there's a timeout, as it'll be
1934 		 * for the same interval again
1935 		 */
1936 		error = EINTR;
1937 	}
1938 
1939 	return (error);
1940 }
1941 
1942 void
1943 initsiginfo(siginfo_t *si, int sig, u_long trapno, int code, union sigval val)
1944 {
1945 	memset(si, 0, sizeof(*si));
1946 
1947 	si->si_signo = sig;
1948 	si->si_code = code;
1949 	if (code == SI_USER) {
1950 		si->si_value = val;
1951 	} else {
1952 		switch (sig) {
1953 		case SIGSEGV:
1954 		case SIGILL:
1955 		case SIGBUS:
1956 		case SIGFPE:
1957 			si->si_addr = val.sival_ptr;
1958 			si->si_trapno = trapno;
1959 			break;
1960 		case SIGXFSZ:
1961 			break;
1962 		}
1963 	}
1964 }
1965 
1966 void
1967 userret(struct proc *p)
1968 {
1969 	struct sigctx ctx;
1970 	int signum;
1971 
1972 	if (p->p_flag & P_SUSPSINGLE)
1973 		single_thread_check(p, 0);
1974 
1975 	/* send SIGPROF or SIGVTALRM if their timers interrupted this thread */
1976 	if (p->p_flag & P_PROFPEND) {
1977 		atomic_clearbits_int(&p->p_flag, P_PROFPEND);
1978 		KERNEL_LOCK();
1979 		psignal(p, SIGPROF);
1980 		KERNEL_UNLOCK();
1981 	}
1982 	if (p->p_flag & P_ALRMPEND) {
1983 		atomic_clearbits_int(&p->p_flag, P_ALRMPEND);
1984 		KERNEL_LOCK();
1985 		psignal(p, SIGVTALRM);
1986 		KERNEL_UNLOCK();
1987 	}
1988 
1989 	if (SIGPENDING(p) != 0) {
1990 		while ((signum = cursig(p, &ctx)) != 0)
1991 			postsig(p, signum, &ctx);
1992 	}
1993 
1994 	/*
1995 	 * If P_SIGSUSPEND is still set here, then we still need to restore
1996 	 * the original sigmask before returning to userspace.  Also, this
1997 	 * might unmask some pending signals, so we need to check a second
1998 	 * time for signals to post.
1999 	 */
2000 	if (p->p_flag & P_SIGSUSPEND) {
2001 		p->p_sigmask = p->p_oldmask;
2002 		atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
2003 
2004 		while ((signum = cursig(p, &ctx)) != 0)
2005 			postsig(p, signum, &ctx);
2006 	}
2007 
2008 	WITNESS_WARN(WARN_PANIC, NULL, "userret: returning");
2009 
2010 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
2011 }
2012 
2013 int
2014 single_thread_check_locked(struct proc *p, int deep)
2015 {
2016 	struct process *pr = p->p_p;
2017 
2018 	MUTEX_ASSERT_LOCKED(&pr->ps_mtx);
2019 
2020 	if (pr->ps_single == NULL || pr->ps_single == p)
2021 		return (0);
2022 
2023 	do {
2024 		/* if we're in deep, we need to unwind to the edge */
2025 		if (deep) {
2026 			if (pr->ps_flags & PS_SINGLEUNWIND)
2027 				return (ERESTART);
2028 			if (pr->ps_flags & PS_SINGLEEXIT)
2029 				return (EINTR);
2030 		}
2031 
2032 		if (pr->ps_flags & PS_SINGLEEXIT) {
2033 			mtx_leave(&pr->ps_mtx);
2034 			KERNEL_LOCK();
2035 			exit1(p, 0, 0, EXIT_THREAD_NOCHECK);
2036 			/* NOTREACHED */
2037 		}
2038 
2039 		if (--pr->ps_singlecnt == 0)
2040 			wakeup(&pr->ps_singlecnt);
2041 
2042 		/* not exiting and don't need to unwind, so suspend */
2043 		mtx_leave(&pr->ps_mtx);
2044 
2045 		SCHED_LOCK();
2046 		p->p_stat = SSTOP;
2047 		mi_switch();
2048 		SCHED_UNLOCK();
2049 		mtx_enter(&pr->ps_mtx);
2050 	} while (pr->ps_single != NULL);
2051 
2052 	return (0);
2053 }
2054 
2055 int
2056 single_thread_check(struct proc *p, int deep)
2057 {
2058 	int error;
2059 
2060 	mtx_enter(&p->p_p->ps_mtx);
2061 	error = single_thread_check_locked(p, deep);
2062 	mtx_leave(&p->p_p->ps_mtx);
2063 
2064 	return error;
2065 }
2066 
2067 /*
2068  * Stop other threads in the process.  The mode controls how and
2069  * where the other threads should stop:
2070  *  - SINGLE_SUSPEND: stop wherever they are, will later be released (via
2071  *    single_thread_clear())
2072  *  - SINGLE_UNWIND: just unwind to kernel boundary, will be told to exit
2073  *    (by setting to SINGLE_EXIT) or released as with SINGLE_SUSPEND
2074  *  - SINGLE_EXIT: unwind to kernel boundary and exit
2075  */
2076 int
2077 single_thread_set(struct proc *p, int flags)
2078 {
2079 	struct process *pr = p->p_p;
2080 	struct proc *q;
2081 	int error, mode = flags & SINGLE_MASK;
2082 
2083 	KASSERT(curproc == p);
2084 
2085 	mtx_enter(&pr->ps_mtx);
2086 	error = single_thread_check_locked(p, flags & SINGLE_DEEP);
2087 	if (error) {
2088 		mtx_leave(&pr->ps_mtx);
2089 		return error;
2090 	}
2091 
2092 	switch (mode) {
2093 	case SINGLE_SUSPEND:
2094 		break;
2095 	case SINGLE_UNWIND:
2096 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2097 		break;
2098 	case SINGLE_EXIT:
2099 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEEXIT);
2100 		atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2101 		break;
2102 #ifdef DIAGNOSTIC
2103 	default:
2104 		panic("single_thread_mode = %d", mode);
2105 #endif
2106 	}
2107 	KASSERT((p->p_flag & P_SUSPSINGLE) == 0);
2108 	pr->ps_single = p;
2109 	pr->ps_singlecnt = pr->ps_threadcnt;
2110 
2111 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2112 		if (q == p)
2113 			continue;
2114 		SCHED_LOCK();
2115 		atomic_setbits_int(&q->p_flag, P_SUSPSINGLE);
2116 		switch (q->p_stat) {
2117 		case SSTOP:
2118 			if (mode == SINGLE_EXIT) {
2119 				unsleep(q);
2120 				setrunnable(q);
2121 			} else
2122 				--pr->ps_singlecnt;
2123 			break;
2124 		case SSLEEP:
2125 			/* if it's not interruptible, then just have to wait */
2126 			if (q->p_flag & P_SINTR) {
2127 				/* merely need to suspend?  just stop it */
2128 				if (mode == SINGLE_SUSPEND) {
2129 					q->p_stat = SSTOP;
2130 					--pr->ps_singlecnt;
2131 					break;
2132 				}
2133 				/* need to unwind or exit, so wake it */
2134 				unsleep(q);
2135 				setrunnable(q);
2136 			}
2137 			break;
2138 		case SONPROC:
2139 			signotify(q);
2140 			break;
2141 		case SRUN:
2142 		case SIDL:
2143 		case SDEAD:
2144 			break;
2145 		}
2146 		SCHED_UNLOCK();
2147 	}
2148 
2149 	/* count ourselfs out */
2150 	--pr->ps_singlecnt;
2151 	mtx_leave(&pr->ps_mtx);
2152 
2153 	if ((flags & SINGLE_NOWAIT) == 0)
2154 		single_thread_wait(pr, 1);
2155 
2156 	return 0;
2157 }
2158 
2159 /*
2160  * Wait for other threads to stop. If recheck is false then the function
2161  * returns non-zero if the caller needs to restart the check else 0 is
2162  * returned. If recheck is true the return value is always 0.
2163  */
2164 int
2165 single_thread_wait(struct process *pr, int recheck)
2166 {
2167 	int wait;
2168 
2169 	/* wait until they're all suspended */
2170 	mtx_enter(&pr->ps_mtx);
2171 	while ((wait = pr->ps_singlecnt > 0)) {
2172 		msleep_nsec(&pr->ps_singlecnt, &pr->ps_mtx, PWAIT, "suspend",
2173 		    INFSLP);
2174 		if (!recheck)
2175 			break;
2176 	}
2177 	KASSERT((pr->ps_single->p_flag & P_SUSPSINGLE) == 0);
2178 	mtx_leave(&pr->ps_mtx);
2179 
2180 	return wait;
2181 }
2182 
2183 void
2184 single_thread_clear(struct proc *p, int flag)
2185 {
2186 	struct process *pr = p->p_p;
2187 	struct proc *q;
2188 
2189 	KASSERT(pr->ps_single == p);
2190 	KASSERT(curproc == p);
2191 
2192 	mtx_enter(&pr->ps_mtx);
2193 	pr->ps_single = NULL;
2194 	atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND | PS_SINGLEEXIT);
2195 
2196 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2197 		if (q == p || (q->p_flag & P_SUSPSINGLE) == 0)
2198 			continue;
2199 		atomic_clearbits_int(&q->p_flag, P_SUSPSINGLE);
2200 
2201 		/*
2202 		 * if the thread was only stopped for single threading
2203 		 * then clearing that either makes it runnable or puts
2204 		 * it back into some sleep queue
2205 		 */
2206 		SCHED_LOCK();
2207 		if (q->p_stat == SSTOP && (q->p_flag & flag) == 0) {
2208 			if (q->p_wchan == NULL)
2209 				setrunnable(q);
2210 			else {
2211 				atomic_clearbits_int(&q->p_flag, P_WSLEEP);
2212 				q->p_stat = SSLEEP;
2213 			}
2214 		}
2215 		SCHED_UNLOCK();
2216 	}
2217 	mtx_leave(&pr->ps_mtx);
2218 }
2219 
2220 void
2221 sigio_del(struct sigiolst *rmlist)
2222 {
2223 	struct sigio *sigio;
2224 
2225 	while ((sigio = LIST_FIRST(rmlist)) != NULL) {
2226 		LIST_REMOVE(sigio, sio_pgsigio);
2227 		crfree(sigio->sio_ucred);
2228 		free(sigio, M_SIGIO, sizeof(*sigio));
2229 	}
2230 }
2231 
2232 void
2233 sigio_unlink(struct sigio_ref *sir, struct sigiolst *rmlist)
2234 {
2235 	struct sigio *sigio;
2236 
2237 	MUTEX_ASSERT_LOCKED(&sigio_lock);
2238 
2239 	sigio = sir->sir_sigio;
2240 	if (sigio != NULL) {
2241 		KASSERT(sigio->sio_myref == sir);
2242 		sir->sir_sigio = NULL;
2243 
2244 		if (sigio->sio_pgid > 0)
2245 			sigio->sio_proc = NULL;
2246 		else
2247 			sigio->sio_pgrp = NULL;
2248 		LIST_REMOVE(sigio, sio_pgsigio);
2249 
2250 		LIST_INSERT_HEAD(rmlist, sigio, sio_pgsigio);
2251 	}
2252 }
2253 
2254 void
2255 sigio_free(struct sigio_ref *sir)
2256 {
2257 	struct sigiolst rmlist;
2258 
2259 	if (sir->sir_sigio == NULL)
2260 		return;
2261 
2262 	LIST_INIT(&rmlist);
2263 
2264 	mtx_enter(&sigio_lock);
2265 	sigio_unlink(sir, &rmlist);
2266 	mtx_leave(&sigio_lock);
2267 
2268 	sigio_del(&rmlist);
2269 }
2270 
2271 void
2272 sigio_freelist(struct sigiolst *sigiolst)
2273 {
2274 	struct sigiolst rmlist;
2275 	struct sigio *sigio;
2276 
2277 	if (LIST_EMPTY(sigiolst))
2278 		return;
2279 
2280 	LIST_INIT(&rmlist);
2281 
2282 	mtx_enter(&sigio_lock);
2283 	while ((sigio = LIST_FIRST(sigiolst)) != NULL)
2284 		sigio_unlink(sigio->sio_myref, &rmlist);
2285 	mtx_leave(&sigio_lock);
2286 
2287 	sigio_del(&rmlist);
2288 }
2289 
2290 int
2291 sigio_setown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2292 {
2293 	struct sigiolst rmlist;
2294 	struct proc *p = curproc;
2295 	struct pgrp *pgrp = NULL;
2296 	struct process *pr = NULL;
2297 	struct sigio *sigio;
2298 	int error;
2299 	pid_t pgid = *(int *)data;
2300 
2301 	if (pgid == 0) {
2302 		sigio_free(sir);
2303 		return (0);
2304 	}
2305 
2306 	if (cmd == TIOCSPGRP) {
2307 		if (pgid < 0)
2308 			return (EINVAL);
2309 		pgid = -pgid;
2310 	}
2311 
2312 	sigio = malloc(sizeof(*sigio), M_SIGIO, M_WAITOK);
2313 	sigio->sio_pgid = pgid;
2314 	sigio->sio_ucred = crhold(p->p_ucred);
2315 	sigio->sio_myref = sir;
2316 
2317 	LIST_INIT(&rmlist);
2318 
2319 	/*
2320 	 * The kernel lock, and not sleeping between prfind()/pgfind() and
2321 	 * linking of the sigio ensure that the process or process group does
2322 	 * not disappear unexpectedly.
2323 	 */
2324 	KERNEL_LOCK();
2325 	mtx_enter(&sigio_lock);
2326 
2327 	if (pgid > 0) {
2328 		pr = prfind(pgid);
2329 		if (pr == NULL) {
2330 			error = ESRCH;
2331 			goto fail;
2332 		}
2333 
2334 		/*
2335 		 * Policy - Don't allow a process to FSETOWN a process
2336 		 * in another session.
2337 		 *
2338 		 * Remove this test to allow maximum flexibility or
2339 		 * restrict FSETOWN to the current process or process
2340 		 * group for maximum safety.
2341 		 */
2342 		if (pr->ps_session != p->p_p->ps_session) {
2343 			error = EPERM;
2344 			goto fail;
2345 		}
2346 
2347 		if ((pr->ps_flags & PS_EXITING) != 0) {
2348 			error = ESRCH;
2349 			goto fail;
2350 		}
2351 	} else /* if (pgid < 0) */ {
2352 		pgrp = pgfind(-pgid);
2353 		if (pgrp == NULL) {
2354 			error = ESRCH;
2355 			goto fail;
2356 		}
2357 
2358 		/*
2359 		 * Policy - Don't allow a process to FSETOWN a process
2360 		 * in another session.
2361 		 *
2362 		 * Remove this test to allow maximum flexibility or
2363 		 * restrict FSETOWN to the current process or process
2364 		 * group for maximum safety.
2365 		 */
2366 		if (pgrp->pg_session != p->p_p->ps_session) {
2367 			error = EPERM;
2368 			goto fail;
2369 		}
2370 	}
2371 
2372 	if (pgid > 0) {
2373 		sigio->sio_proc = pr;
2374 		LIST_INSERT_HEAD(&pr->ps_sigiolst, sigio, sio_pgsigio);
2375 	} else {
2376 		sigio->sio_pgrp = pgrp;
2377 		LIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
2378 	}
2379 
2380 	sigio_unlink(sir, &rmlist);
2381 	sir->sir_sigio = sigio;
2382 
2383 	mtx_leave(&sigio_lock);
2384 	KERNEL_UNLOCK();
2385 
2386 	sigio_del(&rmlist);
2387 
2388 	return (0);
2389 
2390 fail:
2391 	mtx_leave(&sigio_lock);
2392 	KERNEL_UNLOCK();
2393 
2394 	crfree(sigio->sio_ucred);
2395 	free(sigio, M_SIGIO, sizeof(*sigio));
2396 
2397 	return (error);
2398 }
2399 
2400 void
2401 sigio_getown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2402 {
2403 	struct sigio *sigio;
2404 	pid_t pgid = 0;
2405 
2406 	mtx_enter(&sigio_lock);
2407 	sigio = sir->sir_sigio;
2408 	if (sigio != NULL)
2409 		pgid = sigio->sio_pgid;
2410 	mtx_leave(&sigio_lock);
2411 
2412 	if (cmd == TIOCGPGRP)
2413 		pgid = -pgid;
2414 
2415 	*(int *)data = pgid;
2416 }
2417 
2418 void
2419 sigio_copy(struct sigio_ref *dst, struct sigio_ref *src)
2420 {
2421 	struct sigiolst rmlist;
2422 	struct sigio *newsigio, *sigio;
2423 
2424 	sigio_free(dst);
2425 
2426 	if (src->sir_sigio == NULL)
2427 		return;
2428 
2429 	newsigio = malloc(sizeof(*newsigio), M_SIGIO, M_WAITOK);
2430 	LIST_INIT(&rmlist);
2431 
2432 	mtx_enter(&sigio_lock);
2433 
2434 	sigio = src->sir_sigio;
2435 	if (sigio == NULL) {
2436 		mtx_leave(&sigio_lock);
2437 		free(newsigio, M_SIGIO, sizeof(*newsigio));
2438 		return;
2439 	}
2440 
2441 	newsigio->sio_pgid = sigio->sio_pgid;
2442 	newsigio->sio_ucred = crhold(sigio->sio_ucred);
2443 	newsigio->sio_myref = dst;
2444 	if (newsigio->sio_pgid > 0) {
2445 		newsigio->sio_proc = sigio->sio_proc;
2446 		LIST_INSERT_HEAD(&newsigio->sio_proc->ps_sigiolst, newsigio,
2447 		    sio_pgsigio);
2448 	} else {
2449 		newsigio->sio_pgrp = sigio->sio_pgrp;
2450 		LIST_INSERT_HEAD(&newsigio->sio_pgrp->pg_sigiolst, newsigio,
2451 		    sio_pgsigio);
2452 	}
2453 
2454 	sigio_unlink(dst, &rmlist);
2455 	dst->sir_sigio = newsigio;
2456 
2457 	mtx_leave(&sigio_lock);
2458 
2459 	sigio_del(&rmlist);
2460 }
2461