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