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