xref: /openbsd-src/sys/kern/kern_sig.c (revision c34760375439979984b84872f6678f1f4d7cda55)
1 /*	$OpenBSD: kern_sig.c,v 1.342 2024/10/15 13:49:26 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 			pr->ps_xsig = 0;
844 			if ((p->p_flag & P_TRACESINGLE) == 0)
845 				single_thread_clear(p, 0);
846 			atomic_clearbits_int(&p->p_flag, P_TRACESINGLE);
847 
848 			/*
849 			 * If we are no longer being traced, or the parent
850 			 * didn't give us a signal, skip sending the signal.
851 			 */
852 			if ((pr->ps_flags & PS_TRACED) == 0 ||
853 			    signum == 0)
854 				return;
855 
856 			/* update signal info */
857 			p->p_sisig = signum;
858 			mask = sigmask(signum);
859 		}
860 
861 		/*
862 		 * Signals like SIGBUS and SIGSEGV should not, when
863 		 * generated by the kernel, be ignorable or blockable.
864 		 * If it is and we're not being traced, then just kill
865 		 * the process.
866 		 * After vfs_shutdown(9), init(8) cannot receive signals
867 		 * because new code pages of the signal handler cannot be
868 		 * mapped from halted storage.  init(8) may not die or the
869 		 * kernel panics.  Better loop between signal handler and
870 		 * page fault trap until the machine is halted.
871 		 */
872 		if ((pr->ps_flags & PS_TRACED) == 0 &&
873 		    (sigprop[signum] & SA_KILL) &&
874 		    ((p->p_sigmask & mask) || ctx.sig_ignore) &&
875 		    pr->ps_pid != 1) {
876 			KERNEL_LOCK();
877 			sigexit(p, signum);
878 			/* NOTREACHED */
879 		}
880 		KERNEL_LOCK();
881 		ptsignal(p, signum, STHREAD);
882 		KERNEL_UNLOCK();
883 	}
884 }
885 
886 /*
887  * Send the signal to the process.  If the signal has an action, the action
888  * is usually performed by the target process rather than the caller; we add
889  * the signal to the set of pending signals for the process.
890  *
891  * Exceptions:
892  *   o When a stop signal is sent to a sleeping process that takes the
893  *     default action, the process is stopped without awakening it.
894  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
895  *     regardless of the signal action (eg, blocked or ignored).
896  *
897  * Other ignored signals are discarded immediately.
898  */
899 void
900 psignal(struct proc *p, int signum)
901 {
902 	ptsignal(p, signum, SPROCESS);
903 }
904 
905 void
906 prsignal(struct process *pr, int signum)
907 {
908 	/* Ignore signal if the target process is exiting */
909 	if (pr->ps_flags & PS_EXITING) {
910 		return;
911 	}
912 	ptsignal(TAILQ_FIRST(&pr->ps_threads), signum, SPROCESS);
913 }
914 
915 /*
916  * type = SPROCESS	process signal, can be diverted (sigwait())
917  * type = STHREAD	thread signal, but should be propagated if unhandled
918  * type = SPROPAGATED	propagated to this thread, so don't propagate again
919  */
920 void
921 ptsignal(struct proc *p, int signum, enum signal_type type)
922 {
923 	int prop;
924 	sig_t action, altaction = SIG_DFL;
925 	sigset_t mask, sigmask;
926 	int *siglist;
927 	struct process *pr = p->p_p;
928 	struct proc *q;
929 	int wakeparent = 0;
930 
931 	KERNEL_ASSERT_LOCKED();
932 
933 #ifdef DIAGNOSTIC
934 	if ((u_int)signum >= NSIG || signum == 0)
935 		panic("psignal signal number");
936 #endif
937 
938 	/* Ignore signal if the target process is exiting */
939 	if (pr->ps_flags & PS_EXITING)
940 		return;
941 
942 	mask = sigmask(signum);
943 	sigmask = READ_ONCE(p->p_sigmask);
944 
945 	if (type == SPROCESS) {
946 		sigset_t tmpmask;
947 
948 		/* Accept SIGKILL to coredumping processes */
949 		if (pr->ps_flags & PS_COREDUMP && signum == SIGKILL) {
950 			atomic_setbits_int(&pr->ps_siglist, mask);
951 			return;
952 		}
953 
954 		/*
955 		 * If the current thread can process the signal
956 		 * immediately (it's unblocked) then have it take it.
957 		 */
958 		q = curproc;
959 		tmpmask = READ_ONCE(q->p_sigmask);
960 		if (q->p_p == pr && (q->p_flag & P_WEXIT) == 0 &&
961 		    (tmpmask & mask) == 0) {
962 			p = q;
963 			sigmask = tmpmask;
964 		} else {
965 			/*
966 			 * A process-wide signal can be diverted to a
967 			 * different thread that's in sigwait() for this
968 			 * signal.  If there isn't such a thread, then
969 			 * pick a thread that doesn't have it blocked so
970 			 * that the stop/kill consideration isn't
971 			 * delayed.  Otherwise, mark it pending on the
972 			 * main thread.
973 			 */
974 			TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
975 
976 				/* ignore exiting threads */
977 				if (q->p_flag & P_WEXIT)
978 					continue;
979 
980 				/* skip threads that have the signal blocked */
981 				tmpmask = READ_ONCE(q->p_sigmask);
982 				if ((tmpmask & mask) != 0)
983 					continue;
984 
985 				/* okay, could send to this thread */
986 				p = q;
987 				sigmask = tmpmask;
988 
989 				/*
990 				 * sigsuspend, sigwait, ppoll/pselect, etc?
991 				 * Definitely go to this thread, as it's
992 				 * already blocked in the kernel.
993 				 */
994 				if (q->p_flag & P_SIGSUSPEND)
995 					break;
996 			}
997 		}
998 	}
999 
1000 	if (type != SPROPAGATED)
1001 		knote(&pr->ps_klist, NOTE_SIGNAL | signum);
1002 
1003 	prop = sigprop[signum];
1004 
1005 	/*
1006 	 * If proc is traced, always give parent a chance.
1007 	 */
1008 	if (pr->ps_flags & PS_TRACED) {
1009 		action = SIG_DFL;
1010 	} else {
1011 		sigset_t sigcatch, sigignore;
1012 
1013 		/*
1014 		 * If the signal is being ignored,
1015 		 * then we forget about it immediately.
1016 		 * (Note: we don't set SIGCONT in ps_sigignore,
1017 		 * and if it is set to SIG_IGN,
1018 		 * action will be SIG_DFL here.)
1019 		 */
1020 		mtx_enter(&pr->ps_mtx);
1021 		sigignore = pr->ps_sigacts->ps_sigignore;
1022 		sigcatch = pr->ps_sigacts->ps_sigcatch;
1023 		mtx_leave(&pr->ps_mtx);
1024 
1025 		if (sigignore & mask)
1026 			return;
1027 		if (sigmask & mask) {
1028 			action = SIG_HOLD;
1029 			if (sigcatch & mask)
1030 				altaction = SIG_CATCH;
1031 		} else if (sigcatch & mask) {
1032 			action = SIG_CATCH;
1033 		} else {
1034 			action = SIG_DFL;
1035 
1036 			if (prop & SA_KILL && pr->ps_nice > NZERO)
1037 				 pr->ps_nice = NZERO;
1038 
1039 			/*
1040 			 * If sending a tty stop signal to a member of an
1041 			 * orphaned process group, discard the signal here if
1042 			 * the action is default; don't stop the process below
1043 			 * if sleeping, and don't clear any pending SIGCONT.
1044 			 */
1045 			if (prop & SA_TTYSTOP && pr->ps_pgrp->pg_jobc == 0)
1046 				return;
1047 		}
1048 	}
1049 	/*
1050 	 * If delivered to process, mark as pending there.  Continue and stop
1051 	 * signals will be propagated to all threads.  So they are always
1052 	 * marked at thread level.
1053 	 */
1054 	siglist = (type == SPROCESS) ? &pr->ps_siglist : &p->p_siglist;
1055 	if (prop & (SA_CONT | SA_STOP))
1056 		siglist = &p->p_siglist;
1057 
1058 	/*
1059 	 * XXX delay processing of SA_STOP signals unless action == SIG_DFL?
1060 	 */
1061 	if (prop & (SA_CONT | SA_STOP) && type != SPROPAGATED)
1062 		TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link)
1063 			if (q != p)
1064 				ptsignal(q, signum, SPROPAGATED);
1065 
1066 	SCHED_LOCK();
1067 
1068 	switch (p->p_stat) {
1069 
1070 	case SSTOP:
1071 		/*
1072 		 * If traced process is already stopped,
1073 		 * then no further action is necessary.
1074 		 */
1075 		if (pr->ps_flags & PS_TRACED)
1076 			goto out;
1077 
1078 		/*
1079 		 * Kill signal always sets processes running.
1080 		 */
1081 		if (signum == SIGKILL) {
1082 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1083 			/* Raise priority to at least PUSER. */
1084 			if (p->p_usrpri > PUSER)
1085 				p->p_usrpri = PUSER;
1086 			unsleep(p);
1087 			setrunnable(p);
1088 			goto out;
1089 		}
1090 
1091 		if (prop & SA_CONT) {
1092 			/*
1093 			 * If SIGCONT is default (or ignored), we continue the
1094 			 * process but don't leave the signal in p_siglist, as
1095 			 * it has no further action.  If SIGCONT is held, we
1096 			 * continue the process and leave the signal in
1097 			 * p_siglist.  If the process catches SIGCONT, let it
1098 			 * handle the signal itself.  If it isn't waiting on
1099 			 * an event, then it goes back to run state.
1100 			 * Otherwise, process goes back to sleep state.
1101 			 */
1102 			atomic_setbits_int(&pr->ps_flags, PS_CONTINUED);
1103 			atomic_clearbits_int(&pr->ps_flags,
1104 			    PS_WAITED | PS_STOPPED);
1105 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1106 			wakeparent = 1;
1107 			if (action == SIG_DFL)
1108 				mask = 0;
1109 			if (action == SIG_CATCH) {
1110 				/* Raise priority to at least PUSER. */
1111 				if (p->p_usrpri > PUSER)
1112 					p->p_usrpri = PUSER;
1113 				unsleep(p);
1114 				setrunnable(p);
1115 				goto out;
1116 			}
1117 			if (p->p_wchan == NULL) {
1118 				unsleep(p);
1119 				setrunnable(p);
1120 				goto out;
1121 			}
1122 			atomic_clearbits_int(&p->p_flag, P_WSLEEP);
1123 			p->p_stat = SSLEEP;
1124 			goto out;
1125 		}
1126 
1127 		/*
1128 		 * Defer further processing for signals which are held,
1129 		 * except that stopped processes must be continued by SIGCONT.
1130 		 */
1131 		if (action == SIG_HOLD)
1132 			goto out;
1133 
1134 		if (prop & SA_STOP) {
1135 			/*
1136 			 * Already stopped, don't need to stop again.
1137 			 * (If we did the shell could get confused.)
1138 			 */
1139 			mask = 0;
1140 			goto out;
1141 		}
1142 
1143 		/*
1144 		 * If process is sleeping interruptibly, then simulate a
1145 		 * wakeup so that when it is continued, it will be made
1146 		 * runnable and can look at the signal.  But don't make
1147 		 * the process runnable, leave it stopped.
1148 		 */
1149 		if (p->p_flag & P_SINTR)
1150 			unsleep(p);
1151 		goto out;
1152 
1153 	case SSLEEP:
1154 		/*
1155 		 * If process is sleeping uninterruptibly
1156 		 * we can't interrupt the sleep... the signal will
1157 		 * be noticed when the process returns through
1158 		 * trap() or syscall().
1159 		 */
1160 		if ((p->p_flag & P_SINTR) == 0)
1161 			goto out;
1162 		/*
1163 		 * Process is sleeping and traced... make it runnable
1164 		 * so it can discover the signal in cursig() and stop
1165 		 * for the parent.
1166 		 */
1167 		if (pr->ps_flags & PS_TRACED) {
1168 			unsleep(p);
1169 			setrunnable(p);
1170 			goto out;
1171 		}
1172 
1173 		/*
1174 		 * Recheck sigmask before waking up the process,
1175 		 * there is a chance that while sending the signal
1176 		 * the process changed sigmask and went to sleep.
1177 		 */
1178 		sigmask = READ_ONCE(p->p_sigmask);
1179 		if (sigmask & mask)
1180 			goto out;
1181 		else if (action == SIG_HOLD) {
1182 			/* signal got unmasked, get proper action */
1183 			action = altaction;
1184 
1185 			if (action == SIG_DFL) {
1186 				if (prop & SA_KILL && pr->ps_nice > NZERO)
1187 					 pr->ps_nice = NZERO;
1188 
1189 				/*
1190 				 * Discard tty stop signals sent to an
1191 				 * orphaned process group, see above.
1192 				 */
1193 				if (prop & SA_TTYSTOP &&
1194 				    pr->ps_pgrp->pg_jobc == 0) {
1195 					mask = 0;
1196 					prop = 0;
1197 					goto out;
1198 				}
1199 			}
1200 		}
1201 
1202 		/*
1203 		 * If SIGCONT is default (or ignored) and process is
1204 		 * asleep, we are finished; the process should not
1205 		 * be awakened.
1206 		 */
1207 		if ((prop & SA_CONT) && action == SIG_DFL) {
1208 			mask = 0;
1209 			goto out;
1210 		}
1211 		/*
1212 		 * When a sleeping process receives a stop
1213 		 * signal, process immediately if possible.
1214 		 */
1215 		if ((prop & SA_STOP) && action == SIG_DFL) {
1216 			/*
1217 			 * If a child holding parent blocked,
1218 			 * stopping could cause deadlock.
1219 			 */
1220 			if (pr->ps_flags & PS_PPWAIT)
1221 				goto out;
1222 			mask = 0;
1223 			pr->ps_xsig = signum;
1224 			proc_stop(p, 0);
1225 			goto out;
1226 		}
1227 		/*
1228 		 * All other (caught or default) signals
1229 		 * cause the process to run.
1230 		 * Raise priority to at least PUSER.
1231 		 */
1232 		if (p->p_usrpri > PUSER)
1233 			p->p_usrpri = PUSER;
1234 		unsleep(p);
1235 		setrunnable(p);
1236 		goto out;
1237 		/* NOTREACHED */
1238 
1239 	case SONPROC:
1240 		if (action == SIG_HOLD)
1241 			goto out;
1242 
1243 		/* set siglist before issuing the ast */
1244 		atomic_setbits_int(siglist, mask);
1245 		mask = 0;
1246 		signotify(p);
1247 		/* FALLTHROUGH */
1248 	default:
1249 		/*
1250 		 * SRUN, SIDL, SDEAD do nothing with the signal,
1251 		 * other than kicking ourselves if we are running.
1252 		 * It will either never be noticed, or noticed very soon.
1253 		 */
1254 		goto out;
1255 	}
1256 	/* NOTREACHED */
1257 
1258 out:
1259 	/* finally adjust siglist */
1260 	if (mask)
1261 		atomic_setbits_int(siglist, mask);
1262 	if (prop & SA_CONT) {
1263 		atomic_clearbits_int(siglist, STOPSIGMASK);
1264 	}
1265 	if (prop & SA_STOP) {
1266 		atomic_clearbits_int(siglist, CONTSIGMASK);
1267 		atomic_clearbits_int(&pr->ps_flags, PS_CONTINUED);
1268 	}
1269 
1270 	SCHED_UNLOCK();
1271 	if (wakeparent)
1272 		wakeup(pr->ps_pptr);
1273 }
1274 
1275 /* fill the signal context which should be used by postsig() and issignal() */
1276 void
1277 setsigctx(struct proc *p, int signum, struct sigctx *sctx)
1278 {
1279 	struct sigacts *ps = p->p_p->ps_sigacts;
1280 	sigset_t mask;
1281 
1282 	mtx_enter(&p->p_p->ps_mtx);
1283 	mask = sigmask(signum);
1284 	sctx->sig_action = ps->ps_sigact[signum];
1285 	sctx->sig_catchmask = ps->ps_catchmask[signum];
1286 	sctx->sig_reset = (ps->ps_sigreset & mask) != 0;
1287 	sctx->sig_info = (ps->ps_siginfo & mask) != 0;
1288 	sctx->sig_intr = (ps->ps_sigintr & mask) != 0;
1289 	sctx->sig_onstack = (ps->ps_sigonstack & mask) != 0;
1290 	sctx->sig_ignore = (ps->ps_sigignore & mask) != 0;
1291 	sctx->sig_catch = (ps->ps_sigcatch & mask) != 0;
1292 	mtx_leave(&p->p_p->ps_mtx);
1293 }
1294 
1295 /*
1296  * Determine signal that should be delivered to process p, the current
1297  * process, 0 if none.
1298  *
1299  * If the current process has received a signal (should be caught or cause
1300  * termination, should interrupt current syscall), return the signal number.
1301  * Stop signals with default action are processed immediately, then cleared;
1302  * they aren't returned.  This is checked after each entry to the system for
1303  * a syscall or trap. The normal call sequence is
1304  *
1305  *	while (signum = cursig(curproc, &ctx))
1306  *		postsig(signum, &ctx);
1307  *
1308  * Assumes that if the P_SINTR flag is set, we're holding both the
1309  * kernel and scheduler locks.
1310  */
1311 int
1312 cursig(struct proc *p, struct sigctx *sctx)
1313 {
1314 	struct process *pr = p->p_p;
1315 	int signum, mask, prop;
1316 	sigset_t ps_siglist;
1317 
1318 	KASSERT(p == curproc);
1319 
1320 	for (;;) {
1321 		ps_siglist = READ_ONCE(pr->ps_siglist);
1322 		membar_consumer();
1323 		mask = SIGPENDING(p);
1324 		if (pr->ps_flags & PS_PPWAIT)
1325 			mask &= ~STOPSIGMASK;
1326 		if (mask == 0)	 	/* no signal to send */
1327 			return (0);
1328 		signum = ffs((long)mask);
1329 		mask = sigmask(signum);
1330 
1331 		/* take the signal! */
1332 		if (atomic_cas_uint(&pr->ps_siglist, ps_siglist,
1333 		    ps_siglist & ~mask) != ps_siglist) {
1334 			/* lost race taking the process signal, restart */
1335 			continue;
1336 		}
1337 		atomic_clearbits_int(&p->p_siglist, mask);
1338 		setsigctx(p, signum, sctx);
1339 
1340 		/*
1341 		 * We should see pending but ignored signals
1342 		 * only if PS_TRACED was on when they were posted.
1343 		 */
1344 		if (sctx->sig_ignore && (pr->ps_flags & PS_TRACED) == 0)
1345 			continue;
1346 
1347 		/*
1348 		 * If traced, always stop, and stay stopped until released
1349 		 * by the debugger.  If our parent process is waiting for
1350 		 * us, don't hang as we could deadlock.
1351 		 */
1352 		if (((pr->ps_flags & (PS_TRACED | PS_PPWAIT)) == PS_TRACED) &&
1353 		    signum != SIGKILL) {
1354 			single_thread_set(p, SINGLE_SUSPEND | SINGLE_NOWAIT);
1355 			pr->ps_xsig = signum;
1356 
1357 			SCHED_LOCK();
1358 			proc_stop(p, 1);
1359 			SCHED_UNLOCK();
1360 
1361 			/*
1362 			 * re-take the signal before releasing
1363 			 * the other threads. Must check the continue
1364 			 * conditions below and only take the signal if
1365 			 * those are not true.
1366 			 */
1367 			signum = pr->ps_xsig;
1368 			pr->ps_xsig = 0;
1369 			mask = sigmask(signum);
1370 			setsigctx(p, signum, sctx);
1371 			if (!((pr->ps_flags & PS_TRACED) == 0 ||
1372 			    signum == 0 ||
1373 			    (p->p_sigmask & mask) != 0)) {
1374 				atomic_clearbits_int(&p->p_siglist, mask);
1375 				atomic_clearbits_int(&pr->ps_siglist, mask);
1376 			}
1377 
1378 			if ((p->p_flag & P_TRACESINGLE) == 0)
1379 				single_thread_clear(p, 0);
1380 			atomic_clearbits_int(&p->p_flag, P_TRACESINGLE);
1381 
1382 			/*
1383 			 * If we are no longer being traced, or the parent
1384 			 * didn't give us a signal, look for more signals.
1385 			 */
1386 			if ((pr->ps_flags & PS_TRACED) == 0 ||
1387 			    signum == 0)
1388 				continue;
1389 
1390 			/*
1391 			 * If the new signal is being masked, look for other
1392 			 * signals.
1393 			 */
1394 			if ((p->p_sigmask & mask) != 0)
1395 				continue;
1396 
1397 		}
1398 
1399 		prop = sigprop[signum];
1400 
1401 		/*
1402 		 * Decide whether the signal should be returned.
1403 		 * Return the signal's number, or fall through
1404 		 * to clear it from the pending mask.
1405 		 */
1406 		switch ((long)sctx->sig_action) {
1407 		case (long)SIG_DFL:
1408 			/*
1409 			 * Don't take default actions on system processes.
1410 			 */
1411 			if (pr->ps_pid <= 1) {
1412 #ifdef DIAGNOSTIC
1413 				/*
1414 				 * Are you sure you want to ignore SIGSEGV
1415 				 * in init? XXX
1416 				 */
1417 				printf("Process (pid %d) got signal"
1418 				    " %d\n", pr->ps_pid, signum);
1419 #endif
1420 				break;		/* == ignore */
1421 			}
1422 			/*
1423 			 * If there is a pending stop signal to process
1424 			 * with default action, stop here,
1425 			 * then clear the signal.  However,
1426 			 * if process is member of an orphaned
1427 			 * process group, ignore tty stop signals.
1428 			 */
1429 			if (prop & SA_STOP) {
1430 				if (pr->ps_flags & PS_TRACED ||
1431 		    		    (pr->ps_pgrp->pg_jobc == 0 &&
1432 				    prop & SA_TTYSTOP))
1433 					break;	/* == ignore */
1434 				pr->ps_xsig = signum;
1435 				SCHED_LOCK();
1436 				proc_stop(p, 1);
1437 				SCHED_UNLOCK();
1438 				break;
1439 			} else if (prop & SA_IGNORE) {
1440 				/*
1441 				 * Except for SIGCONT, shouldn't get here.
1442 				 * Default action is to ignore; drop it.
1443 				 */
1444 				break;		/* == ignore */
1445 			} else
1446 				goto keep;
1447 			/* NOTREACHED */
1448 		case (long)SIG_IGN:
1449 			/*
1450 			 * Masking above should prevent us ever trying
1451 			 * to take action on an ignored signal other
1452 			 * than SIGCONT, unless process is traced.
1453 			 */
1454 			if ((prop & SA_CONT) == 0 &&
1455 			    (pr->ps_flags & PS_TRACED) == 0)
1456 				printf("%s\n", __func__);
1457 			break;		/* == ignore */
1458 		default:
1459 			/*
1460 			 * This signal has an action, let
1461 			 * postsig() process it.
1462 			 */
1463 			goto keep;
1464 		}
1465 	}
1466 	/* NOTREACHED */
1467 
1468 keep:
1469 	atomic_setbits_int(&p->p_siglist, mask); /*leave the signal for later */
1470 	return (signum);
1471 }
1472 
1473 /*
1474  * Put the argument process into the stopped state and notify the parent
1475  * via wakeup.  Signals are handled elsewhere.  The process must not be
1476  * on the run queue.
1477  */
1478 void
1479 proc_stop(struct proc *p, int sw)
1480 {
1481 	struct process *pr = p->p_p;
1482 
1483 #ifdef MULTIPROCESSOR
1484 	SCHED_ASSERT_LOCKED();
1485 #endif
1486 	/* do not stop exiting procs */
1487 	if (ISSET(p->p_flag, P_WEXIT))
1488 		return;
1489 
1490 	p->p_stat = SSTOP;
1491 	atomic_clearbits_int(&pr->ps_flags, PS_WAITED);
1492 	atomic_setbits_int(&pr->ps_flags, PS_STOPPING);
1493 	atomic_setbits_int(&p->p_flag, P_SUSPSIG);
1494 	/*
1495 	 * We need this soft interrupt to be handled fast.
1496 	 * Extra calls to softclock don't hurt.
1497 	 */
1498 	softintr_schedule(proc_stop_si);
1499 	if (sw)
1500 		mi_switch();
1501 }
1502 
1503 /*
1504  * Called from a soft interrupt to send signals to the parents of stopped
1505  * processes.
1506  * We can't do this in proc_stop because it's called with nasty locks held
1507  * and we would need recursive scheduler lock to deal with that.
1508  */
1509 void
1510 proc_stop_sweep(void *v)
1511 {
1512 	struct process *pr;
1513 
1514 	LIST_FOREACH(pr, &allprocess, ps_list) {
1515 		if ((pr->ps_flags & PS_STOPPING) == 0)
1516 			continue;
1517 		atomic_setbits_int(&pr->ps_flags, PS_STOPPED);
1518 		atomic_clearbits_int(&pr->ps_flags, PS_STOPPING);
1519 
1520 		if ((pr->ps_pptr->ps_sigacts->ps_sigflags & SAS_NOCLDSTOP) == 0)
1521 			prsignal(pr->ps_pptr, SIGCHLD);
1522 		wakeup(pr->ps_pptr);
1523 	}
1524 }
1525 
1526 /*
1527  * Take the action for the specified signal
1528  * from the current set of pending signals.
1529  */
1530 void
1531 postsig(struct proc *p, int signum, struct sigctx *sctx)
1532 {
1533 	u_long trapno;
1534 	int mask, returnmask;
1535 	siginfo_t si;
1536 	union sigval sigval;
1537 	int code;
1538 
1539 	KASSERT(signum != 0);
1540 
1541 	mask = sigmask(signum);
1542 	atomic_clearbits_int(&p->p_siglist, mask);
1543 	sigval.sival_ptr = NULL;
1544 
1545 	if (p->p_sisig != signum) {
1546 		trapno = 0;
1547 		code = SI_USER;
1548 		sigval.sival_ptr = NULL;
1549 	} else {
1550 		trapno = p->p_sitrapno;
1551 		code = p->p_sicode;
1552 		sigval = p->p_sigval;
1553 	}
1554 	initsiginfo(&si, signum, trapno, code, sigval);
1555 
1556 #ifdef KTRACE
1557 	if (KTRPOINT(p, KTR_PSIG)) {
1558 		ktrpsig(p, signum, sctx->sig_action, p->p_flag & P_SIGSUSPEND ?
1559 		    p->p_oldmask : p->p_sigmask, code, &si);
1560 	}
1561 #endif
1562 	if (sctx->sig_action == SIG_DFL) {
1563 		/*
1564 		 * Default action, where the default is to kill
1565 		 * the process.  (Other cases were ignored above.)
1566 		 */
1567 		KERNEL_LOCK();
1568 		sigexit(p, signum);
1569 		/* NOTREACHED */
1570 	} else {
1571 		/*
1572 		 * If we get here, the signal must be caught.
1573 		 */
1574 #ifdef DIAGNOSTIC
1575 		if (sctx->sig_action == SIG_IGN || (p->p_sigmask & mask))
1576 			panic("postsig action");
1577 #endif
1578 		/*
1579 		 * Set the new mask value and also defer further
1580 		 * occurrences of this signal.
1581 		 *
1582 		 * Special case: user has done a sigpause.  Here the
1583 		 * current mask is not of interest, but rather the
1584 		 * mask from before the sigpause is what we want
1585 		 * restored after the signal processing is completed.
1586 		 */
1587 		if (p->p_flag & P_SIGSUSPEND) {
1588 			atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
1589 			returnmask = p->p_oldmask;
1590 		} else {
1591 			returnmask = p->p_sigmask;
1592 		}
1593 		if (p->p_sisig == signum) {
1594 			p->p_sisig = 0;
1595 			p->p_sitrapno = 0;
1596 			p->p_sicode = SI_USER;
1597 			p->p_sigval.sival_ptr = NULL;
1598 		}
1599 
1600 		if (sendsig(sctx->sig_action, signum, returnmask, &si,
1601 		    sctx->sig_info, sctx->sig_onstack)) {
1602 			KERNEL_LOCK();
1603 			sigexit(p, SIGILL);
1604 			/* NOTREACHED */
1605 		}
1606 		postsig_done(p, signum, sctx->sig_catchmask, sctx->sig_reset);
1607 	}
1608 }
1609 
1610 /*
1611  * Force the current process to exit with the specified signal, dumping core
1612  * if appropriate.  We bypass the normal tests for masked and caught signals,
1613  * allowing unrecoverable failures to terminate the process without changing
1614  * signal state.  Mark the accounting record with the signal termination.
1615  * If dumping core, save the signal number for the debugger.  Calls exit and
1616  * does not return.
1617  */
1618 void
1619 sigexit(struct proc *p, int signum)
1620 {
1621 	/* Mark process as going away */
1622 	atomic_setbits_int(&p->p_flag, P_WEXIT);
1623 
1624 	p->p_p->ps_acflag |= AXSIG;
1625 	if (sigprop[signum] & SA_CORE) {
1626 		p->p_sisig = signum;
1627 
1628 		/* if there are other threads, pause them */
1629 		if (P_HASSIBLING(p))
1630 			single_thread_set(p, SINGLE_UNWIND);
1631 
1632 		if (coredump(p) == 0)
1633 			signum |= WCOREFLAG;
1634 	}
1635 	exit1(p, 0, signum, EXIT_NORMAL);
1636 	/* NOTREACHED */
1637 }
1638 
1639 /*
1640  * Send uncatchable SIGABRT for coredump.
1641  */
1642 void
1643 sigabort(struct proc *p)
1644 {
1645 	struct sigaction sa;
1646 
1647 	KASSERT(p == curproc || panicstr || db_active);
1648 
1649 	memset(&sa, 0, sizeof sa);
1650 	sa.sa_handler = SIG_DFL;
1651 	setsigvec(p, SIGABRT, &sa);
1652 	CLR(p->p_sigmask, sigmask(SIGABRT));
1653 	psignal(p, SIGABRT);
1654 }
1655 
1656 /*
1657  * Return 1 if `sig', a given signal, is ignored or masked for `p', a given
1658  * thread, and 0 otherwise.
1659  */
1660 int
1661 sigismasked(struct proc *p, int sig)
1662 {
1663 	struct process *pr = p->p_p;
1664 	int rv;
1665 
1666 	KASSERT(p == curproc);
1667 
1668 	mtx_enter(&pr->ps_mtx);
1669 	rv = (pr->ps_sigacts->ps_sigignore & sigmask(sig)) ||
1670 	    (p->p_sigmask & sigmask(sig));
1671 	mtx_leave(&pr->ps_mtx);
1672 
1673 	return !!rv;
1674 }
1675 
1676 struct coredump_iostate {
1677 	struct proc *io_proc;
1678 	struct vnode *io_vp;
1679 	struct ucred *io_cred;
1680 	off_t io_offset;
1681 };
1682 
1683 /*
1684  * Dump core, into a file named "progname.core", unless the process was
1685  * setuid/setgid.
1686  */
1687 int
1688 coredump(struct proc *p)
1689 {
1690 #ifdef SMALL_KERNEL
1691 	return EPERM;
1692 #else
1693 	struct process *pr = p->p_p;
1694 	struct vnode *vp;
1695 	struct ucred *cred = p->p_ucred;
1696 	struct vmspace *vm = p->p_vmspace;
1697 	struct nameidata nd;
1698 	struct vattr vattr;
1699 	struct coredump_iostate	io;
1700 	int error, len, incrash = 0;
1701 	char *name;
1702 	const char *dir = "/var/crash";
1703 
1704 	atomic_setbits_int(&pr->ps_flags, PS_COREDUMP);
1705 
1706 #ifdef PMAP_CHECK_COPYIN
1707 	/* disable copyin checks, so we can write out text sections if needed */
1708 	p->p_vmspace->vm_map.check_copyin_count = 0;
1709 #endif
1710 
1711 	/* Don't dump if will exceed file size limit. */
1712 	if (USPACE + ptoa(vm->vm_dsize + vm->vm_ssize) >= lim_cur(RLIMIT_CORE))
1713 		return (EFBIG);
1714 
1715 	name = pool_get(&namei_pool, PR_WAITOK);
1716 
1717 	/*
1718 	 * If the process has inconsistent uids, nosuidcoredump
1719 	 * determines coredump placement policy.
1720 	 */
1721 	if (((pr->ps_flags & PS_SUGID) && (error = suser(p))) ||
1722 	   ((pr->ps_flags & PS_SUGID) && nosuidcoredump)) {
1723 		if (nosuidcoredump == 3) {
1724 			/*
1725 			 * If the program directory does not exist, dumps of
1726 			 * that core will silently fail.
1727 			 */
1728 			len = snprintf(name, MAXPATHLEN, "%s/%s/%u.core",
1729 			    dir, pr->ps_comm, pr->ps_pid);
1730 			incrash = KERNELPATH;
1731 		} else if (nosuidcoredump == 2) {
1732 			len = snprintf(name, MAXPATHLEN, "%s/%s.core",
1733 			    dir, pr->ps_comm);
1734 			incrash = KERNELPATH;
1735 		} else {
1736 			pool_put(&namei_pool, name);
1737 			return (EPERM);
1738 		}
1739 	} else
1740 		len = snprintf(name, MAXPATHLEN, "%s.core", pr->ps_comm);
1741 
1742 	if (len >= MAXPATHLEN) {
1743 		pool_put(&namei_pool, name);
1744 		return (EACCES);
1745 	}
1746 
1747 	/*
1748 	 * Control the UID used to write out.  The normal case uses
1749 	 * the real UID.  If the sugid case is going to write into the
1750 	 * controlled directory, we do so as root.
1751 	 */
1752 	if (incrash == 0) {
1753 		cred = crdup(cred);
1754 		cred->cr_uid = cred->cr_ruid;
1755 		cred->cr_gid = cred->cr_rgid;
1756 	} else {
1757 		if (p->p_fd->fd_rdir) {
1758 			vrele(p->p_fd->fd_rdir);
1759 			p->p_fd->fd_rdir = NULL;
1760 		}
1761 		p->p_ucred = crdup(p->p_ucred);
1762 		crfree(cred);
1763 		cred = p->p_ucred;
1764 		crhold(cred);
1765 		cred->cr_uid = 0;
1766 		cred->cr_gid = 0;
1767 	}
1768 
1769 	/* incrash should be 0 or KERNELPATH only */
1770 	NDINIT(&nd, 0, BYPASSUNVEIL | incrash, UIO_SYSSPACE, name, p);
1771 
1772 	error = vn_open(&nd, O_CREAT | FWRITE | O_NOFOLLOW | O_NONBLOCK,
1773 	    S_IRUSR | S_IWUSR);
1774 
1775 	if (error)
1776 		goto out;
1777 
1778 	/*
1779 	 * Don't dump to non-regular files, files with links, or files
1780 	 * owned by someone else.
1781 	 */
1782 	vp = nd.ni_vp;
1783 	if ((error = VOP_GETATTR(vp, &vattr, cred, p)) != 0) {
1784 		VOP_UNLOCK(vp);
1785 		vn_close(vp, FWRITE, cred, p);
1786 		goto out;
1787 	}
1788 	if (vp->v_type != VREG || vattr.va_nlink != 1 ||
1789 	    vattr.va_mode & ((VREAD | VWRITE) >> 3 | (VREAD | VWRITE) >> 6) ||
1790 	    vattr.va_uid != cred->cr_uid) {
1791 		error = EACCES;
1792 		VOP_UNLOCK(vp);
1793 		vn_close(vp, FWRITE, cred, p);
1794 		goto out;
1795 	}
1796 	VATTR_NULL(&vattr);
1797 	vattr.va_size = 0;
1798 	VOP_SETATTR(vp, &vattr, cred, p);
1799 	pr->ps_acflag |= ACORE;
1800 
1801 	io.io_proc = p;
1802 	io.io_vp = vp;
1803 	io.io_cred = cred;
1804 	io.io_offset = 0;
1805 	VOP_UNLOCK(vp);
1806 	vref(vp);
1807 	error = vn_close(vp, FWRITE, cred, p);
1808 	if (error == 0)
1809 		error = coredump_elf(p, &io);
1810 	vrele(vp);
1811 out:
1812 	crfree(cred);
1813 	pool_put(&namei_pool, name);
1814 	return (error);
1815 #endif
1816 }
1817 
1818 #ifndef SMALL_KERNEL
1819 int
1820 coredump_write(void *cookie, enum uio_seg segflg, const void *data, size_t len,
1821     int isvnode)
1822 {
1823 	struct coredump_iostate *io = cookie;
1824 	off_t coffset = 0;
1825 	size_t csize;
1826 	int chunk, error;
1827 
1828 	csize = len;
1829 	do {
1830 		if (sigmask(SIGKILL) &
1831 		    (io->io_proc->p_siglist | io->io_proc->p_p->ps_siglist))
1832 			return (EINTR);
1833 
1834 		/* Rest of the loop sleeps with lock held, so... */
1835 		yield();
1836 
1837 		chunk = MIN(csize, MAXPHYS);
1838 		error = vn_rdwr(UIO_WRITE, io->io_vp,
1839 		    (caddr_t)data + coffset, chunk,
1840 		    io->io_offset + coffset, segflg,
1841 		    IO_UNIT, io->io_cred, NULL, io->io_proc);
1842 		if (error && (error != EFAULT || !isvnode)) {
1843 			struct process *pr = io->io_proc->p_p;
1844 
1845 			if (error == ENOSPC)
1846 				log(LOG_ERR,
1847 				    "coredump of %s(%d) failed, filesystem full\n",
1848 				    pr->ps_comm, pr->ps_pid);
1849 			else
1850 				log(LOG_ERR,
1851 				    "coredump of %s(%d), write failed: errno %d\n",
1852 				    pr->ps_comm, pr->ps_pid, error);
1853 			return (error);
1854 		}
1855 
1856 		coffset += chunk;
1857 		csize -= chunk;
1858 	} while (csize > 0);
1859 
1860 	io->io_offset += len;
1861 	return (0);
1862 }
1863 
1864 void
1865 coredump_unmap(void *cookie, vaddr_t start, vaddr_t end)
1866 {
1867 	struct coredump_iostate *io = cookie;
1868 
1869 	uvm_unmap(&io->io_proc->p_vmspace->vm_map, start, end);
1870 }
1871 
1872 #endif	/* !SMALL_KERNEL */
1873 
1874 /*
1875  * Nonexistent system call-- signal process (may want to handle it).
1876  * Flag error in case process won't see signal immediately (blocked or ignored).
1877  */
1878 int
1879 sys_nosys(struct proc *p, void *v, register_t *retval)
1880 {
1881 	ptsignal(p, SIGSYS, STHREAD);
1882 	return (ENOSYS);
1883 }
1884 
1885 int
1886 sys___thrsigdivert(struct proc *p, void *v, register_t *retval)
1887 {
1888 	struct sys___thrsigdivert_args /* {
1889 		syscallarg(sigset_t) sigmask;
1890 		syscallarg(siginfo_t *) info;
1891 		syscallarg(const struct timespec *) timeout;
1892 	} */ *uap = v;
1893 	struct sigctx ctx;
1894 	sigset_t mask = SCARG(uap, sigmask) &~ sigcantmask;
1895 	siginfo_t si;
1896 	uint64_t nsecs = INFSLP;
1897 	int timeinvalid = 0;
1898 	int error = 0;
1899 
1900 	memset(&si, 0, sizeof(si));
1901 
1902 	if (SCARG(uap, timeout) != NULL) {
1903 		struct timespec ts;
1904 		if ((error = copyin(SCARG(uap, timeout), &ts, sizeof(ts))) != 0)
1905 			return (error);
1906 #ifdef KTRACE
1907 		if (KTRPOINT(p, KTR_STRUCT))
1908 			ktrreltimespec(p, &ts);
1909 #endif
1910 		if (!timespecisvalid(&ts))
1911 			timeinvalid = 1;
1912 		else
1913 			nsecs = TIMESPEC_TO_NSEC(&ts);
1914 	}
1915 
1916 	dosigsuspend(p, p->p_sigmask &~ mask);
1917 	for (;;) {
1918 		si.si_signo = cursig(p, &ctx);
1919 		if (si.si_signo != 0) {
1920 			sigset_t smask = sigmask(si.si_signo);
1921 			if (smask & mask) {
1922 				atomic_clearbits_int(&p->p_siglist, smask);
1923 				error = 0;
1924 				break;
1925 			}
1926 		}
1927 
1928 		/* per-POSIX, delay this error until after the above */
1929 		if (timeinvalid)
1930 			error = EINVAL;
1931 		/* per-POSIX, return immediately if timeout is zero-valued */
1932 		if (nsecs == 0)
1933 			error = EAGAIN;
1934 
1935 		if (error != 0)
1936 			break;
1937 
1938 		error = tsleep_nsec(&nowake, PPAUSE|PCATCH, "sigwait", nsecs);
1939 	}
1940 
1941 	if (error == 0) {
1942 		*retval = si.si_signo;
1943 		if (SCARG(uap, info) != NULL) {
1944 			error = copyout(&si, SCARG(uap, info), sizeof(si));
1945 #ifdef KTRACE
1946 			if (error == 0 && KTRPOINT(p, KTR_STRUCT))
1947 				ktrsiginfo(p, &si);
1948 #endif
1949 		}
1950 	} else if (error == ERESTART && SCARG(uap, timeout) != NULL) {
1951 		/*
1952 		 * Restarting is wrong if there's a timeout, as it'll be
1953 		 * for the same interval again
1954 		 */
1955 		error = EINTR;
1956 	}
1957 
1958 	return (error);
1959 }
1960 
1961 void
1962 initsiginfo(siginfo_t *si, int sig, u_long trapno, int code, union sigval val)
1963 {
1964 	memset(si, 0, sizeof(*si));
1965 
1966 	si->si_signo = sig;
1967 	si->si_code = code;
1968 	if (code == SI_USER) {
1969 		si->si_value = val;
1970 	} else {
1971 		switch (sig) {
1972 		case SIGSEGV:
1973 		case SIGILL:
1974 		case SIGBUS:
1975 		case SIGFPE:
1976 			si->si_addr = val.sival_ptr;
1977 			si->si_trapno = trapno;
1978 			break;
1979 		case SIGXFSZ:
1980 			break;
1981 		}
1982 	}
1983 }
1984 
1985 void
1986 userret(struct proc *p)
1987 {
1988 	struct sigctx ctx;
1989 	int signum;
1990 
1991 	if (p->p_flag & P_SUSPSINGLE)
1992 		single_thread_check(p, 0);
1993 
1994 	/* send SIGPROF or SIGVTALRM if their timers interrupted this thread */
1995 	if (p->p_flag & P_PROFPEND) {
1996 		atomic_clearbits_int(&p->p_flag, P_PROFPEND);
1997 		KERNEL_LOCK();
1998 		psignal(p, SIGPROF);
1999 		KERNEL_UNLOCK();
2000 	}
2001 	if (p->p_flag & P_ALRMPEND) {
2002 		atomic_clearbits_int(&p->p_flag, P_ALRMPEND);
2003 		KERNEL_LOCK();
2004 		psignal(p, SIGVTALRM);
2005 		KERNEL_UNLOCK();
2006 	}
2007 
2008 	if (SIGPENDING(p) != 0) {
2009 		while ((signum = cursig(p, &ctx)) != 0)
2010 			postsig(p, signum, &ctx);
2011 	}
2012 
2013 	/*
2014 	 * If P_SIGSUSPEND is still set here, then we still need to restore
2015 	 * the original sigmask before returning to userspace.  Also, this
2016 	 * might unmask some pending signals, so we need to check a second
2017 	 * time for signals to post.
2018 	 */
2019 	if (p->p_flag & P_SIGSUSPEND) {
2020 		p->p_sigmask = p->p_oldmask;
2021 		atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
2022 
2023 		while ((signum = cursig(p, &ctx)) != 0)
2024 			postsig(p, signum, &ctx);
2025 	}
2026 
2027 	WITNESS_WARN(WARN_PANIC, NULL, "userret: returning");
2028 
2029 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
2030 }
2031 
2032 int
2033 single_thread_check_locked(struct proc *p, int deep)
2034 {
2035 	struct process *pr = p->p_p;
2036 
2037 	MUTEX_ASSERT_LOCKED(&pr->ps_mtx);
2038 
2039 	if (pr->ps_single == NULL || pr->ps_single == p)
2040 		return (0);
2041 
2042 	do {
2043 		/* if we're in deep, we need to unwind to the edge */
2044 		if (deep) {
2045 			if (pr->ps_flags & PS_SINGLEUNWIND)
2046 				return (ERESTART);
2047 			if (pr->ps_flags & PS_SINGLEEXIT)
2048 				return (EINTR);
2049 		}
2050 
2051 		if (pr->ps_flags & PS_SINGLEEXIT) {
2052 			mtx_leave(&pr->ps_mtx);
2053 			KERNEL_LOCK();
2054 			exit1(p, 0, 0, EXIT_THREAD_NOCHECK);
2055 			/* NOTREACHED */
2056 		}
2057 
2058 		if (--pr->ps_singlecnt == 0)
2059 			wakeup(&pr->ps_singlecnt);
2060 
2061 		/* not exiting and don't need to unwind, so suspend */
2062 		mtx_leave(&pr->ps_mtx);
2063 
2064 		SCHED_LOCK();
2065 		p->p_stat = SSTOP;
2066 		mi_switch();
2067 		SCHED_UNLOCK();
2068 		mtx_enter(&pr->ps_mtx);
2069 	} while (pr->ps_single != NULL);
2070 
2071 	return (0);
2072 }
2073 
2074 int
2075 single_thread_check(struct proc *p, int deep)
2076 {
2077 	int error;
2078 
2079 	mtx_enter(&p->p_p->ps_mtx);
2080 	error = single_thread_check_locked(p, deep);
2081 	mtx_leave(&p->p_p->ps_mtx);
2082 
2083 	return error;
2084 }
2085 
2086 /*
2087  * Stop other threads in the process.  The mode controls how and
2088  * where the other threads should stop:
2089  *  - SINGLE_SUSPEND: stop wherever they are, will later be released (via
2090  *    single_thread_clear())
2091  *  - SINGLE_UNWIND: just unwind to kernel boundary, will be told to exit
2092  *    (by setting to SINGLE_EXIT) or released as with SINGLE_SUSPEND
2093  *  - SINGLE_EXIT: unwind to kernel boundary and exit
2094  */
2095 int
2096 single_thread_set(struct proc *p, int flags)
2097 {
2098 	struct process *pr = p->p_p;
2099 	struct proc *q;
2100 	int error, mode = flags & SINGLE_MASK;
2101 
2102 	KASSERT(curproc == p);
2103 
2104 	mtx_enter(&pr->ps_mtx);
2105 	error = single_thread_check_locked(p, flags & SINGLE_DEEP);
2106 	if (error) {
2107 		mtx_leave(&pr->ps_mtx);
2108 		return error;
2109 	}
2110 
2111 	switch (mode) {
2112 	case SINGLE_SUSPEND:
2113 		break;
2114 	case SINGLE_UNWIND:
2115 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2116 		break;
2117 	case SINGLE_EXIT:
2118 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEEXIT);
2119 		atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2120 		break;
2121 #ifdef DIAGNOSTIC
2122 	default:
2123 		panic("single_thread_mode = %d", mode);
2124 #endif
2125 	}
2126 	KASSERT((p->p_flag & P_SUSPSINGLE) == 0);
2127 	pr->ps_single = p;
2128 	pr->ps_singlecnt = pr->ps_threadcnt;
2129 
2130 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2131 		if (q == p)
2132 			continue;
2133 		SCHED_LOCK();
2134 		atomic_setbits_int(&q->p_flag, P_SUSPSINGLE);
2135 		switch (q->p_stat) {
2136 		case SSTOP:
2137 			if (mode == SINGLE_EXIT) {
2138 				unsleep(q);
2139 				setrunnable(q);
2140 			} else
2141 				--pr->ps_singlecnt;
2142 			break;
2143 		case SSLEEP:
2144 			/* if it's not interruptible, then just have to wait */
2145 			if (q->p_flag & P_SINTR) {
2146 				/* merely need to suspend?  just stop it */
2147 				if (mode == SINGLE_SUSPEND) {
2148 					q->p_stat = SSTOP;
2149 					--pr->ps_singlecnt;
2150 					break;
2151 				}
2152 				/* need to unwind or exit, so wake it */
2153 				unsleep(q);
2154 				setrunnable(q);
2155 			}
2156 			break;
2157 		case SONPROC:
2158 			signotify(q);
2159 			break;
2160 		case SRUN:
2161 		case SIDL:
2162 		case SDEAD:
2163 			break;
2164 		}
2165 		SCHED_UNLOCK();
2166 	}
2167 
2168 	/* count ourself out */
2169 	--pr->ps_singlecnt;
2170 	mtx_leave(&pr->ps_mtx);
2171 
2172 	if ((flags & SINGLE_NOWAIT) == 0)
2173 		single_thread_wait(pr, 1);
2174 
2175 	return 0;
2176 }
2177 
2178 /*
2179  * Wait for other threads to stop. If recheck is false then the function
2180  * returns non-zero if the caller needs to restart the check else 0 is
2181  * returned. If recheck is true the return value is always 0.
2182  */
2183 int
2184 single_thread_wait(struct process *pr, int recheck)
2185 {
2186 	int wait;
2187 
2188 	/* wait until they're all suspended */
2189 	mtx_enter(&pr->ps_mtx);
2190 	while ((wait = pr->ps_singlecnt > 0)) {
2191 		msleep_nsec(&pr->ps_singlecnt, &pr->ps_mtx, PWAIT, "suspend",
2192 		    INFSLP);
2193 		if (!recheck)
2194 			break;
2195 	}
2196 	KASSERT((pr->ps_single->p_flag & P_SUSPSINGLE) == 0);
2197 	mtx_leave(&pr->ps_mtx);
2198 
2199 	return wait;
2200 }
2201 
2202 void
2203 single_thread_clear(struct proc *p, int flag)
2204 {
2205 	struct process *pr = p->p_p;
2206 	struct proc *q;
2207 
2208 	KASSERT(pr->ps_single == p);
2209 	KASSERT(curproc == p);
2210 
2211 	mtx_enter(&pr->ps_mtx);
2212 	pr->ps_single = NULL;
2213 	atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND | PS_SINGLEEXIT);
2214 
2215 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2216 		if (q == p || (q->p_flag & P_SUSPSINGLE) == 0)
2217 			continue;
2218 		atomic_clearbits_int(&q->p_flag, P_SUSPSINGLE);
2219 
2220 		/*
2221 		 * if the thread was only stopped for single threading
2222 		 * then clearing that either makes it runnable or puts
2223 		 * it back into some sleep queue
2224 		 */
2225 		SCHED_LOCK();
2226 		if (q->p_stat == SSTOP && (q->p_flag & flag) == 0) {
2227 			if (q->p_wchan == NULL)
2228 				setrunnable(q);
2229 			else {
2230 				atomic_clearbits_int(&q->p_flag, P_WSLEEP);
2231 				q->p_stat = SSLEEP;
2232 			}
2233 		}
2234 		SCHED_UNLOCK();
2235 	}
2236 	mtx_leave(&pr->ps_mtx);
2237 }
2238 
2239 void
2240 sigio_del(struct sigiolst *rmlist)
2241 {
2242 	struct sigio *sigio;
2243 
2244 	while ((sigio = LIST_FIRST(rmlist)) != NULL) {
2245 		LIST_REMOVE(sigio, sio_pgsigio);
2246 		crfree(sigio->sio_ucred);
2247 		free(sigio, M_SIGIO, sizeof(*sigio));
2248 	}
2249 }
2250 
2251 void
2252 sigio_unlink(struct sigio_ref *sir, struct sigiolst *rmlist)
2253 {
2254 	struct sigio *sigio;
2255 
2256 	MUTEX_ASSERT_LOCKED(&sigio_lock);
2257 
2258 	sigio = sir->sir_sigio;
2259 	if (sigio != NULL) {
2260 		KASSERT(sigio->sio_myref == sir);
2261 		sir->sir_sigio = NULL;
2262 
2263 		if (sigio->sio_pgid > 0)
2264 			sigio->sio_proc = NULL;
2265 		else
2266 			sigio->sio_pgrp = NULL;
2267 		LIST_REMOVE(sigio, sio_pgsigio);
2268 
2269 		LIST_INSERT_HEAD(rmlist, sigio, sio_pgsigio);
2270 	}
2271 }
2272 
2273 void
2274 sigio_free(struct sigio_ref *sir)
2275 {
2276 	struct sigiolst rmlist;
2277 
2278 	if (sir->sir_sigio == NULL)
2279 		return;
2280 
2281 	LIST_INIT(&rmlist);
2282 
2283 	mtx_enter(&sigio_lock);
2284 	sigio_unlink(sir, &rmlist);
2285 	mtx_leave(&sigio_lock);
2286 
2287 	sigio_del(&rmlist);
2288 }
2289 
2290 void
2291 sigio_freelist(struct sigiolst *sigiolst)
2292 {
2293 	struct sigiolst rmlist;
2294 	struct sigio *sigio;
2295 
2296 	if (LIST_EMPTY(sigiolst))
2297 		return;
2298 
2299 	LIST_INIT(&rmlist);
2300 
2301 	mtx_enter(&sigio_lock);
2302 	while ((sigio = LIST_FIRST(sigiolst)) != NULL)
2303 		sigio_unlink(sigio->sio_myref, &rmlist);
2304 	mtx_leave(&sigio_lock);
2305 
2306 	sigio_del(&rmlist);
2307 }
2308 
2309 int
2310 sigio_setown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2311 {
2312 	struct sigiolst rmlist;
2313 	struct proc *p = curproc;
2314 	struct pgrp *pgrp = NULL;
2315 	struct process *pr = NULL;
2316 	struct sigio *sigio;
2317 	int error;
2318 	pid_t pgid = *(int *)data;
2319 
2320 	if (pgid == 0) {
2321 		sigio_free(sir);
2322 		return (0);
2323 	}
2324 
2325 	if (cmd == TIOCSPGRP) {
2326 		if (pgid < 0)
2327 			return (EINVAL);
2328 		pgid = -pgid;
2329 	}
2330 
2331 	sigio = malloc(sizeof(*sigio), M_SIGIO, M_WAITOK);
2332 	sigio->sio_pgid = pgid;
2333 	sigio->sio_ucred = crhold(p->p_ucred);
2334 	sigio->sio_myref = sir;
2335 
2336 	LIST_INIT(&rmlist);
2337 
2338 	/*
2339 	 * The kernel lock, and not sleeping between prfind()/pgfind() and
2340 	 * linking of the sigio ensure that the process or process group does
2341 	 * not disappear unexpectedly.
2342 	 */
2343 	KERNEL_LOCK();
2344 	mtx_enter(&sigio_lock);
2345 
2346 	if (pgid > 0) {
2347 		pr = prfind(pgid);
2348 		if (pr == NULL) {
2349 			error = ESRCH;
2350 			goto fail;
2351 		}
2352 
2353 		/*
2354 		 * Policy - Don't allow a process to FSETOWN a process
2355 		 * in another session.
2356 		 *
2357 		 * Remove this test to allow maximum flexibility or
2358 		 * restrict FSETOWN to the current process or process
2359 		 * group for maximum safety.
2360 		 */
2361 		if (pr->ps_session != p->p_p->ps_session) {
2362 			error = EPERM;
2363 			goto fail;
2364 		}
2365 
2366 		if ((pr->ps_flags & PS_EXITING) != 0) {
2367 			error = ESRCH;
2368 			goto fail;
2369 		}
2370 	} else /* if (pgid < 0) */ {
2371 		pgrp = pgfind(-pgid);
2372 		if (pgrp == NULL) {
2373 			error = ESRCH;
2374 			goto fail;
2375 		}
2376 
2377 		/*
2378 		 * Policy - Don't allow a process to FSETOWN a process
2379 		 * in another session.
2380 		 *
2381 		 * Remove this test to allow maximum flexibility or
2382 		 * restrict FSETOWN to the current process or process
2383 		 * group for maximum safety.
2384 		 */
2385 		if (pgrp->pg_session != p->p_p->ps_session) {
2386 			error = EPERM;
2387 			goto fail;
2388 		}
2389 	}
2390 
2391 	if (pgid > 0) {
2392 		sigio->sio_proc = pr;
2393 		LIST_INSERT_HEAD(&pr->ps_sigiolst, sigio, sio_pgsigio);
2394 	} else {
2395 		sigio->sio_pgrp = pgrp;
2396 		LIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
2397 	}
2398 
2399 	sigio_unlink(sir, &rmlist);
2400 	sir->sir_sigio = sigio;
2401 
2402 	mtx_leave(&sigio_lock);
2403 	KERNEL_UNLOCK();
2404 
2405 	sigio_del(&rmlist);
2406 
2407 	return (0);
2408 
2409 fail:
2410 	mtx_leave(&sigio_lock);
2411 	KERNEL_UNLOCK();
2412 
2413 	crfree(sigio->sio_ucred);
2414 	free(sigio, M_SIGIO, sizeof(*sigio));
2415 
2416 	return (error);
2417 }
2418 
2419 void
2420 sigio_getown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2421 {
2422 	struct sigio *sigio;
2423 	pid_t pgid = 0;
2424 
2425 	mtx_enter(&sigio_lock);
2426 	sigio = sir->sir_sigio;
2427 	if (sigio != NULL)
2428 		pgid = sigio->sio_pgid;
2429 	mtx_leave(&sigio_lock);
2430 
2431 	if (cmd == TIOCGPGRP)
2432 		pgid = -pgid;
2433 
2434 	*(int *)data = pgid;
2435 }
2436 
2437 void
2438 sigio_copy(struct sigio_ref *dst, struct sigio_ref *src)
2439 {
2440 	struct sigiolst rmlist;
2441 	struct sigio *newsigio, *sigio;
2442 
2443 	sigio_free(dst);
2444 
2445 	if (src->sir_sigio == NULL)
2446 		return;
2447 
2448 	newsigio = malloc(sizeof(*newsigio), M_SIGIO, M_WAITOK);
2449 	LIST_INIT(&rmlist);
2450 
2451 	mtx_enter(&sigio_lock);
2452 
2453 	sigio = src->sir_sigio;
2454 	if (sigio == NULL) {
2455 		mtx_leave(&sigio_lock);
2456 		free(newsigio, M_SIGIO, sizeof(*newsigio));
2457 		return;
2458 	}
2459 
2460 	newsigio->sio_pgid = sigio->sio_pgid;
2461 	newsigio->sio_ucred = crhold(sigio->sio_ucred);
2462 	newsigio->sio_myref = dst;
2463 	if (newsigio->sio_pgid > 0) {
2464 		newsigio->sio_proc = sigio->sio_proc;
2465 		LIST_INSERT_HEAD(&newsigio->sio_proc->ps_sigiolst, newsigio,
2466 		    sio_pgsigio);
2467 	} else {
2468 		newsigio->sio_pgrp = sigio->sio_pgrp;
2469 		LIST_INSERT_HEAD(&newsigio->sio_pgrp->pg_sigiolst, newsigio,
2470 		    sio_pgsigio);
2471 	}
2472 
2473 	sigio_unlink(dst, &rmlist);
2474 	dst->sir_sigio = newsigio;
2475 
2476 	mtx_leave(&sigio_lock);
2477 
2478 	sigio_del(&rmlist);
2479 }
2480