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