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