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