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