xref: /freebsd/sys/kern/kern_sig.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/capsicum.h>
47 #include <sys/ctype.h>
48 #include <sys/systm.h>
49 #include <sys/signalvar.h>
50 #include <sys/vnode.h>
51 #include <sys/acct.h>
52 #include <sys/capsicum.h>
53 #include <sys/compressor.h>
54 #include <sys/condvar.h>
55 #include <sys/devctl.h>
56 #include <sys/event.h>
57 #include <sys/fcntl.h>
58 #include <sys/imgact.h>
59 #include <sys/jail.h>
60 #include <sys/kernel.h>
61 #include <sys/ktr.h>
62 #include <sys/ktrace.h>
63 #include <sys/limits.h>
64 #include <sys/lock.h>
65 #include <sys/malloc.h>
66 #include <sys/mutex.h>
67 #include <sys/refcount.h>
68 #include <sys/namei.h>
69 #include <sys/proc.h>
70 #include <sys/procdesc.h>
71 #include <sys/ptrace.h>
72 #include <sys/posix4.h>
73 #include <sys/racct.h>
74 #include <sys/resourcevar.h>
75 #include <sys/sdt.h>
76 #include <sys/sbuf.h>
77 #include <sys/sleepqueue.h>
78 #include <sys/smp.h>
79 #include <sys/stat.h>
80 #include <sys/sx.h>
81 #include <sys/syscall.h>
82 #include <sys/syscallsubr.h>
83 #include <sys/sysctl.h>
84 #include <sys/sysent.h>
85 #include <sys/syslog.h>
86 #include <sys/sysproto.h>
87 #include <sys/timers.h>
88 #include <sys/unistd.h>
89 #include <sys/vmmeter.h>
90 #include <sys/wait.h>
91 #include <vm/vm.h>
92 #include <vm/vm_extern.h>
93 #include <vm/uma.h>
94 
95 #include <machine/cpu.h>
96 
97 #include <security/audit/audit.h>
98 
99 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
100 
101 SDT_PROVIDER_DECLARE(proc);
102 SDT_PROBE_DEFINE3(proc, , , signal__send,
103     "struct thread *", "struct proc *", "int");
104 SDT_PROBE_DEFINE2(proc, , , signal__clear,
105     "int", "ksiginfo_t *");
106 SDT_PROBE_DEFINE3(proc, , , signal__discard,
107     "struct thread *", "struct proc *", "int");
108 
109 static int	coredump(struct thread *);
110 static int	killpg1(struct thread *td, int sig, int pgid, int all,
111 		    ksiginfo_t *ksi);
112 static int	issignal(struct thread *td);
113 static void	reschedule_signals(struct proc *p, sigset_t block, int flags);
114 static int	sigprop(int sig);
115 static void	tdsigwakeup(struct thread *, int, sig_t, int);
116 static int	sig_suspend_threads(struct thread *, struct proc *);
117 static int	filt_sigattach(struct knote *kn);
118 static void	filt_sigdetach(struct knote *kn);
119 static int	filt_signal(struct knote *kn, long hint);
120 static struct thread *sigtd(struct proc *p, int sig, bool fast_sigblock);
121 static void	sigqueue_start(void);
122 static void	sigfastblock_setpend(struct thread *td, bool resched);
123 
124 static uma_zone_t	ksiginfo_zone = NULL;
125 struct filterops sig_filtops = {
126 	.f_isfd = 0,
127 	.f_attach = filt_sigattach,
128 	.f_detach = filt_sigdetach,
129 	.f_event = filt_signal,
130 };
131 
132 static int	kern_logsigexit = 1;
133 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
134     &kern_logsigexit, 0,
135     "Log processes quitting on abnormal signals to syslog(3)");
136 
137 static int	kern_forcesigexit = 1;
138 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
139     &kern_forcesigexit, 0, "Force trap signal to be handled");
140 
141 static SYSCTL_NODE(_kern, OID_AUTO, sigqueue, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
142     "POSIX real time signal");
143 
144 static int	max_pending_per_proc = 128;
145 SYSCTL_INT(_kern_sigqueue, OID_AUTO, max_pending_per_proc, CTLFLAG_RW,
146     &max_pending_per_proc, 0, "Max pending signals per proc");
147 
148 static int	preallocate_siginfo = 1024;
149 SYSCTL_INT(_kern_sigqueue, OID_AUTO, preallocate, CTLFLAG_RDTUN,
150     &preallocate_siginfo, 0, "Preallocated signal memory size");
151 
152 static int	signal_overflow = 0;
153 SYSCTL_INT(_kern_sigqueue, OID_AUTO, overflow, CTLFLAG_RD,
154     &signal_overflow, 0, "Number of signals overflew");
155 
156 static int	signal_alloc_fail = 0;
157 SYSCTL_INT(_kern_sigqueue, OID_AUTO, alloc_fail, CTLFLAG_RD,
158     &signal_alloc_fail, 0, "signals failed to be allocated");
159 
160 static int	kern_lognosys = 0;
161 SYSCTL_INT(_kern, OID_AUTO, lognosys, CTLFLAG_RWTUN, &kern_lognosys, 0,
162     "Log invalid syscalls");
163 
164 __read_frequently bool sigfastblock_fetch_always = false;
165 SYSCTL_BOOL(_kern, OID_AUTO, sigfastblock_fetch_always, CTLFLAG_RWTUN,
166     &sigfastblock_fetch_always, 0,
167     "Fetch sigfastblock word on each syscall entry for proper "
168     "blocking semantic");
169 
170 static bool	kern_sig_discard_ign = true;
171 SYSCTL_BOOL(_kern, OID_AUTO, sig_discard_ign, CTLFLAG_RWTUN,
172     &kern_sig_discard_ign, 0,
173     "Discard ignored signals on delivery, otherwise queue them to "
174     "the target queue");
175 
176 SYSINIT(signal, SI_SUB_P1003_1B, SI_ORDER_FIRST+3, sigqueue_start, NULL);
177 
178 /*
179  * Policy -- Can ucred cr1 send SIGIO to process cr2?
180  * Should use cr_cansignal() once cr_cansignal() allows SIGIO and SIGURG
181  * in the right situations.
182  */
183 #define CANSIGIO(cr1, cr2) \
184 	((cr1)->cr_uid == 0 || \
185 	    (cr1)->cr_ruid == (cr2)->cr_ruid || \
186 	    (cr1)->cr_uid == (cr2)->cr_ruid || \
187 	    (cr1)->cr_ruid == (cr2)->cr_uid || \
188 	    (cr1)->cr_uid == (cr2)->cr_uid)
189 
190 static int	sugid_coredump;
191 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RWTUN,
192     &sugid_coredump, 0, "Allow setuid and setgid processes to dump core");
193 
194 static int	capmode_coredump;
195 SYSCTL_INT(_kern, OID_AUTO, capmode_coredump, CTLFLAG_RWTUN,
196     &capmode_coredump, 0, "Allow processes in capability mode to dump core");
197 
198 static int	do_coredump = 1;
199 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
200 	&do_coredump, 0, "Enable/Disable coredumps");
201 
202 static int	set_core_nodump_flag = 0;
203 SYSCTL_INT(_kern, OID_AUTO, nodump_coredump, CTLFLAG_RW, &set_core_nodump_flag,
204 	0, "Enable setting the NODUMP flag on coredump files");
205 
206 static int	coredump_devctl = 0;
207 SYSCTL_INT(_kern, OID_AUTO, coredump_devctl, CTLFLAG_RW, &coredump_devctl,
208 	0, "Generate a devctl notification when processes coredump");
209 
210 /*
211  * Signal properties and actions.
212  * The array below categorizes the signals and their default actions
213  * according to the following properties:
214  */
215 #define	SIGPROP_KILL		0x01	/* terminates process by default */
216 #define	SIGPROP_CORE		0x02	/* ditto and coredumps */
217 #define	SIGPROP_STOP		0x04	/* suspend process */
218 #define	SIGPROP_TTYSTOP		0x08	/* ditto, from tty */
219 #define	SIGPROP_IGNORE		0x10	/* ignore by default */
220 #define	SIGPROP_CONT		0x20	/* continue if suspended */
221 
222 static const int sigproptbl[NSIG] = {
223 	[SIGHUP] =	SIGPROP_KILL,
224 	[SIGINT] =	SIGPROP_KILL,
225 	[SIGQUIT] =	SIGPROP_KILL | SIGPROP_CORE,
226 	[SIGILL] =	SIGPROP_KILL | SIGPROP_CORE,
227 	[SIGTRAP] =	SIGPROP_KILL | SIGPROP_CORE,
228 	[SIGABRT] =	SIGPROP_KILL | SIGPROP_CORE,
229 	[SIGEMT] =	SIGPROP_KILL | SIGPROP_CORE,
230 	[SIGFPE] =	SIGPROP_KILL | SIGPROP_CORE,
231 	[SIGKILL] =	SIGPROP_KILL,
232 	[SIGBUS] =	SIGPROP_KILL | SIGPROP_CORE,
233 	[SIGSEGV] =	SIGPROP_KILL | SIGPROP_CORE,
234 	[SIGSYS] =	SIGPROP_KILL | SIGPROP_CORE,
235 	[SIGPIPE] =	SIGPROP_KILL,
236 	[SIGALRM] =	SIGPROP_KILL,
237 	[SIGTERM] =	SIGPROP_KILL,
238 	[SIGURG] =	SIGPROP_IGNORE,
239 	[SIGSTOP] =	SIGPROP_STOP,
240 	[SIGTSTP] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
241 	[SIGCONT] =	SIGPROP_IGNORE | SIGPROP_CONT,
242 	[SIGCHLD] =	SIGPROP_IGNORE,
243 	[SIGTTIN] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
244 	[SIGTTOU] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
245 	[SIGIO] =	SIGPROP_IGNORE,
246 	[SIGXCPU] =	SIGPROP_KILL,
247 	[SIGXFSZ] =	SIGPROP_KILL,
248 	[SIGVTALRM] =	SIGPROP_KILL,
249 	[SIGPROF] =	SIGPROP_KILL,
250 	[SIGWINCH] =	SIGPROP_IGNORE,
251 	[SIGINFO] =	SIGPROP_IGNORE,
252 	[SIGUSR1] =	SIGPROP_KILL,
253 	[SIGUSR2] =	SIGPROP_KILL,
254 };
255 
256 #define	_SIG_FOREACH_ADVANCE(i, set) ({					\
257 	int __found;							\
258 	for (;;) {							\
259 		if (__bits != 0) {					\
260 			int __sig = ffs(__bits);			\
261 			__bits &= ~(1u << (__sig - 1));			\
262 			sig = __i * sizeof((set)->__bits[0]) * NBBY + __sig; \
263 			__found = 1;					\
264 			break;						\
265 		}							\
266 		if (++__i == _SIG_WORDS) {				\
267 			__found = 0;					\
268 			break;						\
269 		}							\
270 		__bits = (set)->__bits[__i];				\
271 	}								\
272 	__found != 0;							\
273 })
274 
275 #define	SIG_FOREACH(i, set)						\
276 	for (int32_t __i = -1, __bits = 0;				\
277 	    _SIG_FOREACH_ADVANCE(i, set); )				\
278 
279 static sigset_t fastblock_mask;
280 
281 static void
282 ast_sig(struct thread *td, int tda)
283 {
284 	struct proc *p;
285 	int old_boundary, sig;
286 	bool resched_sigs;
287 
288 	p = td->td_proc;
289 
290 #ifdef DIAGNOSTIC
291 	if (p->p_numthreads == 1 && (tda & (TDAI(TDA_SIG) |
292 	    TDAI(TDA_AST))) == 0) {
293 		PROC_LOCK(p);
294 		thread_lock(td);
295 		/*
296 		 * Note that TDA_SIG should be re-read from
297 		 * td_ast, since signal might have been delivered
298 		 * after we cleared td_flags above.  This is one of
299 		 * the reason for looping check for AST condition.
300 		 * See comment in userret() about P_PPWAIT.
301 		 */
302 		if ((p->p_flag & P_PPWAIT) == 0 &&
303 		    (td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
304 			if (SIGPENDING(td) && ((tda | td->td_ast) &
305 			    (TDAI(TDA_SIG) | TDAI(TDA_AST))) == 0) {
306 				thread_unlock(td); /* fix dumps */
307 				panic(
308 				    "failed2 to set signal flags for ast p %p "
309 				    "td %p tda %#x td_ast %#x fl %#x",
310 				    p, td, tda, td->td_ast, td->td_flags);
311 			}
312 		}
313 		thread_unlock(td);
314 		PROC_UNLOCK(p);
315 	}
316 #endif
317 
318 	/*
319 	 * Check for signals. Unlocked reads of p_pendingcnt or
320 	 * p_siglist might cause process-directed signal to be handled
321 	 * later.
322 	 */
323 	if ((tda & TDAI(TDA_SIG)) != 0 || p->p_pendingcnt > 0 ||
324 	    !SIGISEMPTY(p->p_siglist)) {
325 		sigfastblock_fetch(td);
326 		PROC_LOCK(p);
327 		old_boundary = ~TDB_BOUNDARY | (td->td_dbgflags & TDB_BOUNDARY);
328 		td->td_dbgflags |= TDB_BOUNDARY;
329 		mtx_lock(&p->p_sigacts->ps_mtx);
330 		while ((sig = cursig(td)) != 0) {
331 			KASSERT(sig >= 0, ("sig %d", sig));
332 			postsig(sig);
333 		}
334 		mtx_unlock(&p->p_sigacts->ps_mtx);
335 		td->td_dbgflags &= old_boundary;
336 		PROC_UNLOCK(p);
337 		resched_sigs = true;
338 	} else {
339 		resched_sigs = false;
340 	}
341 
342 	/*
343 	 * Handle deferred update of the fast sigblock value, after
344 	 * the postsig() loop was performed.
345 	 */
346 	sigfastblock_setpend(td, resched_sigs);
347 }
348 
349 static void
350 ast_sigsuspend(struct thread *td, int tda __unused)
351 {
352 	MPASS((td->td_pflags & TDP_OLDMASK) != 0);
353 	td->td_pflags &= ~TDP_OLDMASK;
354 	kern_sigprocmask(td, SIG_SETMASK, &td->td_oldsigmask, NULL, 0);
355 }
356 
357 static void
358 sigqueue_start(void)
359 {
360 	ksiginfo_zone = uma_zcreate("ksiginfo", sizeof(ksiginfo_t),
361 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
362 	uma_prealloc(ksiginfo_zone, preallocate_siginfo);
363 	p31b_setcfg(CTL_P1003_1B_REALTIME_SIGNALS, _POSIX_REALTIME_SIGNALS);
364 	p31b_setcfg(CTL_P1003_1B_RTSIG_MAX, SIGRTMAX - SIGRTMIN + 1);
365 	p31b_setcfg(CTL_P1003_1B_SIGQUEUE_MAX, max_pending_per_proc);
366 	SIGFILLSET(fastblock_mask);
367 	SIG_CANTMASK(fastblock_mask);
368 	ast_register(TDA_SIG, ASTR_UNCOND, 0, ast_sig);
369 	ast_register(TDA_SIGSUSPEND, ASTR_ASTF_REQUIRED | ASTR_TDP,
370 	    TDP_OLDMASK, ast_sigsuspend);
371 }
372 
373 ksiginfo_t *
374 ksiginfo_alloc(int mwait)
375 {
376 	MPASS(mwait == M_WAITOK || mwait == M_NOWAIT);
377 
378 	if (ksiginfo_zone == NULL)
379 		return (NULL);
380 	return (uma_zalloc(ksiginfo_zone, mwait | M_ZERO));
381 }
382 
383 void
384 ksiginfo_free(ksiginfo_t *ksi)
385 {
386 	uma_zfree(ksiginfo_zone, ksi);
387 }
388 
389 static __inline bool
390 ksiginfo_tryfree(ksiginfo_t *ksi)
391 {
392 	if ((ksi->ksi_flags & KSI_EXT) == 0) {
393 		uma_zfree(ksiginfo_zone, ksi);
394 		return (true);
395 	}
396 	return (false);
397 }
398 
399 void
400 sigqueue_init(sigqueue_t *list, struct proc *p)
401 {
402 	SIGEMPTYSET(list->sq_signals);
403 	SIGEMPTYSET(list->sq_kill);
404 	SIGEMPTYSET(list->sq_ptrace);
405 	TAILQ_INIT(&list->sq_list);
406 	list->sq_proc = p;
407 	list->sq_flags = SQ_INIT;
408 }
409 
410 /*
411  * Get a signal's ksiginfo.
412  * Return:
413  *	0	-	signal not found
414  *	others	-	signal number
415  */
416 static int
417 sigqueue_get(sigqueue_t *sq, int signo, ksiginfo_t *si)
418 {
419 	struct proc *p = sq->sq_proc;
420 	struct ksiginfo *ksi, *next;
421 	int count = 0;
422 
423 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
424 
425 	if (!SIGISMEMBER(sq->sq_signals, signo))
426 		return (0);
427 
428 	if (SIGISMEMBER(sq->sq_ptrace, signo)) {
429 		count++;
430 		SIGDELSET(sq->sq_ptrace, signo);
431 		si->ksi_flags |= KSI_PTRACE;
432 	}
433 	if (SIGISMEMBER(sq->sq_kill, signo)) {
434 		count++;
435 		if (count == 1)
436 			SIGDELSET(sq->sq_kill, signo);
437 	}
438 
439 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
440 		if (ksi->ksi_signo == signo) {
441 			if (count == 0) {
442 				TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
443 				ksi->ksi_sigq = NULL;
444 				ksiginfo_copy(ksi, si);
445 				if (ksiginfo_tryfree(ksi) && p != NULL)
446 					p->p_pendingcnt--;
447 			}
448 			if (++count > 1)
449 				break;
450 		}
451 	}
452 
453 	if (count <= 1)
454 		SIGDELSET(sq->sq_signals, signo);
455 	si->ksi_signo = signo;
456 	return (signo);
457 }
458 
459 void
460 sigqueue_take(ksiginfo_t *ksi)
461 {
462 	struct ksiginfo *kp;
463 	struct proc	*p;
464 	sigqueue_t	*sq;
465 
466 	if (ksi == NULL || (sq = ksi->ksi_sigq) == NULL)
467 		return;
468 
469 	p = sq->sq_proc;
470 	TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
471 	ksi->ksi_sigq = NULL;
472 	if (!(ksi->ksi_flags & KSI_EXT) && p != NULL)
473 		p->p_pendingcnt--;
474 
475 	for (kp = TAILQ_FIRST(&sq->sq_list); kp != NULL;
476 	     kp = TAILQ_NEXT(kp, ksi_link)) {
477 		if (kp->ksi_signo == ksi->ksi_signo)
478 			break;
479 	}
480 	if (kp == NULL && !SIGISMEMBER(sq->sq_kill, ksi->ksi_signo) &&
481 	    !SIGISMEMBER(sq->sq_ptrace, ksi->ksi_signo))
482 		SIGDELSET(sq->sq_signals, ksi->ksi_signo);
483 }
484 
485 static int
486 sigqueue_add(sigqueue_t *sq, int signo, ksiginfo_t *si)
487 {
488 	struct proc *p = sq->sq_proc;
489 	struct ksiginfo *ksi;
490 	int ret = 0;
491 
492 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
493 
494 	/*
495 	 * SIGKILL/SIGSTOP cannot be caught or masked, so take the fast path
496 	 * for these signals.
497 	 */
498 	if (signo == SIGKILL || signo == SIGSTOP || si == NULL) {
499 		SIGADDSET(sq->sq_kill, signo);
500 		goto out_set_bit;
501 	}
502 
503 	/* directly insert the ksi, don't copy it */
504 	if (si->ksi_flags & KSI_INS) {
505 		if (si->ksi_flags & KSI_HEAD)
506 			TAILQ_INSERT_HEAD(&sq->sq_list, si, ksi_link);
507 		else
508 			TAILQ_INSERT_TAIL(&sq->sq_list, si, ksi_link);
509 		si->ksi_sigq = sq;
510 		goto out_set_bit;
511 	}
512 
513 	if (__predict_false(ksiginfo_zone == NULL)) {
514 		SIGADDSET(sq->sq_kill, signo);
515 		goto out_set_bit;
516 	}
517 
518 	if (p != NULL && p->p_pendingcnt >= max_pending_per_proc) {
519 		signal_overflow++;
520 		ret = EAGAIN;
521 	} else if ((ksi = ksiginfo_alloc(M_NOWAIT)) == NULL) {
522 		signal_alloc_fail++;
523 		ret = EAGAIN;
524 	} else {
525 		if (p != NULL)
526 			p->p_pendingcnt++;
527 		ksiginfo_copy(si, ksi);
528 		ksi->ksi_signo = signo;
529 		if (si->ksi_flags & KSI_HEAD)
530 			TAILQ_INSERT_HEAD(&sq->sq_list, ksi, ksi_link);
531 		else
532 			TAILQ_INSERT_TAIL(&sq->sq_list, ksi, ksi_link);
533 		ksi->ksi_sigq = sq;
534 	}
535 
536 	if (ret != 0) {
537 		if ((si->ksi_flags & KSI_PTRACE) != 0) {
538 			SIGADDSET(sq->sq_ptrace, signo);
539 			ret = 0;
540 			goto out_set_bit;
541 		} else if ((si->ksi_flags & KSI_TRAP) != 0 ||
542 		    (si->ksi_flags & KSI_SIGQ) == 0) {
543 			SIGADDSET(sq->sq_kill, signo);
544 			ret = 0;
545 			goto out_set_bit;
546 		}
547 		return (ret);
548 	}
549 
550 out_set_bit:
551 	SIGADDSET(sq->sq_signals, signo);
552 	return (ret);
553 }
554 
555 void
556 sigqueue_flush(sigqueue_t *sq)
557 {
558 	struct proc *p = sq->sq_proc;
559 	ksiginfo_t *ksi;
560 
561 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
562 
563 	if (p != NULL)
564 		PROC_LOCK_ASSERT(p, MA_OWNED);
565 
566 	while ((ksi = TAILQ_FIRST(&sq->sq_list)) != NULL) {
567 		TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
568 		ksi->ksi_sigq = NULL;
569 		if (ksiginfo_tryfree(ksi) && p != NULL)
570 			p->p_pendingcnt--;
571 	}
572 
573 	SIGEMPTYSET(sq->sq_signals);
574 	SIGEMPTYSET(sq->sq_kill);
575 	SIGEMPTYSET(sq->sq_ptrace);
576 }
577 
578 static void
579 sigqueue_move_set(sigqueue_t *src, sigqueue_t *dst, const sigset_t *set)
580 {
581 	sigset_t tmp;
582 	struct proc *p1, *p2;
583 	ksiginfo_t *ksi, *next;
584 
585 	KASSERT(src->sq_flags & SQ_INIT, ("src sigqueue not inited"));
586 	KASSERT(dst->sq_flags & SQ_INIT, ("dst sigqueue not inited"));
587 	p1 = src->sq_proc;
588 	p2 = dst->sq_proc;
589 	/* Move siginfo to target list */
590 	TAILQ_FOREACH_SAFE(ksi, &src->sq_list, ksi_link, next) {
591 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
592 			TAILQ_REMOVE(&src->sq_list, ksi, ksi_link);
593 			if (p1 != NULL)
594 				p1->p_pendingcnt--;
595 			TAILQ_INSERT_TAIL(&dst->sq_list, ksi, ksi_link);
596 			ksi->ksi_sigq = dst;
597 			if (p2 != NULL)
598 				p2->p_pendingcnt++;
599 		}
600 	}
601 
602 	/* Move pending bits to target list */
603 	tmp = src->sq_kill;
604 	SIGSETAND(tmp, *set);
605 	SIGSETOR(dst->sq_kill, tmp);
606 	SIGSETNAND(src->sq_kill, tmp);
607 
608 	tmp = src->sq_ptrace;
609 	SIGSETAND(tmp, *set);
610 	SIGSETOR(dst->sq_ptrace, tmp);
611 	SIGSETNAND(src->sq_ptrace, tmp);
612 
613 	tmp = src->sq_signals;
614 	SIGSETAND(tmp, *set);
615 	SIGSETOR(dst->sq_signals, tmp);
616 	SIGSETNAND(src->sq_signals, tmp);
617 }
618 
619 #if 0
620 static void
621 sigqueue_move(sigqueue_t *src, sigqueue_t *dst, int signo)
622 {
623 	sigset_t set;
624 
625 	SIGEMPTYSET(set);
626 	SIGADDSET(set, signo);
627 	sigqueue_move_set(src, dst, &set);
628 }
629 #endif
630 
631 static void
632 sigqueue_delete_set(sigqueue_t *sq, const sigset_t *set)
633 {
634 	struct proc *p = sq->sq_proc;
635 	ksiginfo_t *ksi, *next;
636 
637 	KASSERT(sq->sq_flags & SQ_INIT, ("src sigqueue not inited"));
638 
639 	/* Remove siginfo queue */
640 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
641 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
642 			TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
643 			ksi->ksi_sigq = NULL;
644 			if (ksiginfo_tryfree(ksi) && p != NULL)
645 				p->p_pendingcnt--;
646 		}
647 	}
648 	SIGSETNAND(sq->sq_kill, *set);
649 	SIGSETNAND(sq->sq_ptrace, *set);
650 	SIGSETNAND(sq->sq_signals, *set);
651 }
652 
653 void
654 sigqueue_delete(sigqueue_t *sq, int signo)
655 {
656 	sigset_t set;
657 
658 	SIGEMPTYSET(set);
659 	SIGADDSET(set, signo);
660 	sigqueue_delete_set(sq, &set);
661 }
662 
663 /* Remove a set of signals for a process */
664 static void
665 sigqueue_delete_set_proc(struct proc *p, const sigset_t *set)
666 {
667 	sigqueue_t worklist;
668 	struct thread *td0;
669 
670 	PROC_LOCK_ASSERT(p, MA_OWNED);
671 
672 	sigqueue_init(&worklist, NULL);
673 	sigqueue_move_set(&p->p_sigqueue, &worklist, set);
674 
675 	FOREACH_THREAD_IN_PROC(p, td0)
676 		sigqueue_move_set(&td0->td_sigqueue, &worklist, set);
677 
678 	sigqueue_flush(&worklist);
679 }
680 
681 void
682 sigqueue_delete_proc(struct proc *p, int signo)
683 {
684 	sigset_t set;
685 
686 	SIGEMPTYSET(set);
687 	SIGADDSET(set, signo);
688 	sigqueue_delete_set_proc(p, &set);
689 }
690 
691 static void
692 sigqueue_delete_stopmask_proc(struct proc *p)
693 {
694 	sigset_t set;
695 
696 	SIGEMPTYSET(set);
697 	SIGADDSET(set, SIGSTOP);
698 	SIGADDSET(set, SIGTSTP);
699 	SIGADDSET(set, SIGTTIN);
700 	SIGADDSET(set, SIGTTOU);
701 	sigqueue_delete_set_proc(p, &set);
702 }
703 
704 /*
705  * Determine signal that should be delivered to thread td, the current
706  * thread, 0 if none.  If there is a pending stop signal with default
707  * action, the process stops in issignal().
708  */
709 int
710 cursig(struct thread *td)
711 {
712 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
713 	mtx_assert(&td->td_proc->p_sigacts->ps_mtx, MA_OWNED);
714 	THREAD_LOCK_ASSERT(td, MA_NOTOWNED);
715 	return (SIGPENDING(td) ? issignal(td) : 0);
716 }
717 
718 /*
719  * Arrange for ast() to handle unmasked pending signals on return to user
720  * mode.  This must be called whenever a signal is added to td_sigqueue or
721  * unmasked in td_sigmask.
722  */
723 void
724 signotify(struct thread *td)
725 {
726 
727 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
728 
729 	if (SIGPENDING(td))
730 		ast_sched(td, TDA_SIG);
731 }
732 
733 /*
734  * Returns 1 (true) if altstack is configured for the thread, and the
735  * passed stack bottom address falls into the altstack range.  Handles
736  * the 43 compat special case where the alt stack size is zero.
737  */
738 int
739 sigonstack(size_t sp)
740 {
741 	struct thread *td;
742 
743 	td = curthread;
744 	if ((td->td_pflags & TDP_ALTSTACK) == 0)
745 		return (0);
746 #if defined(COMPAT_43)
747 	if (SV_PROC_FLAG(td->td_proc, SV_AOUT) && td->td_sigstk.ss_size == 0)
748 		return ((td->td_sigstk.ss_flags & SS_ONSTACK) != 0);
749 #endif
750 	return (sp >= (size_t)td->td_sigstk.ss_sp &&
751 	    sp < td->td_sigstk.ss_size + (size_t)td->td_sigstk.ss_sp);
752 }
753 
754 static __inline int
755 sigprop(int sig)
756 {
757 
758 	if (sig > 0 && sig < nitems(sigproptbl))
759 		return (sigproptbl[sig]);
760 	return (0);
761 }
762 
763 static bool
764 sigact_flag_test(const struct sigaction *act, int flag)
765 {
766 
767 	/*
768 	 * SA_SIGINFO is reset when signal disposition is set to
769 	 * ignore or default.  Other flags are kept according to user
770 	 * settings.
771 	 */
772 	return ((act->sa_flags & flag) != 0 && (flag != SA_SIGINFO ||
773 	    ((__sighandler_t *)act->sa_sigaction != SIG_IGN &&
774 	    (__sighandler_t *)act->sa_sigaction != SIG_DFL)));
775 }
776 
777 /*
778  * kern_sigaction
779  * sigaction
780  * freebsd4_sigaction
781  * osigaction
782  */
783 int
784 kern_sigaction(struct thread *td, int sig, const struct sigaction *act,
785     struct sigaction *oact, int flags)
786 {
787 	struct sigacts *ps;
788 	struct proc *p = td->td_proc;
789 
790 	if (!_SIG_VALID(sig))
791 		return (EINVAL);
792 	if (act != NULL && act->sa_handler != SIG_DFL &&
793 	    act->sa_handler != SIG_IGN && (act->sa_flags & ~(SA_ONSTACK |
794 	    SA_RESTART | SA_RESETHAND | SA_NOCLDSTOP | SA_NODEFER |
795 	    SA_NOCLDWAIT | SA_SIGINFO)) != 0)
796 		return (EINVAL);
797 
798 	PROC_LOCK(p);
799 	ps = p->p_sigacts;
800 	mtx_lock(&ps->ps_mtx);
801 	if (oact) {
802 		memset(oact, 0, sizeof(*oact));
803 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
804 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
805 			oact->sa_flags |= SA_ONSTACK;
806 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
807 			oact->sa_flags |= SA_RESTART;
808 		if (SIGISMEMBER(ps->ps_sigreset, sig))
809 			oact->sa_flags |= SA_RESETHAND;
810 		if (SIGISMEMBER(ps->ps_signodefer, sig))
811 			oact->sa_flags |= SA_NODEFER;
812 		if (SIGISMEMBER(ps->ps_siginfo, sig)) {
813 			oact->sa_flags |= SA_SIGINFO;
814 			oact->sa_sigaction =
815 			    (__siginfohandler_t *)ps->ps_sigact[_SIG_IDX(sig)];
816 		} else
817 			oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
818 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDSTOP)
819 			oact->sa_flags |= SA_NOCLDSTOP;
820 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDWAIT)
821 			oact->sa_flags |= SA_NOCLDWAIT;
822 	}
823 	if (act) {
824 		if ((sig == SIGKILL || sig == SIGSTOP) &&
825 		    act->sa_handler != SIG_DFL) {
826 			mtx_unlock(&ps->ps_mtx);
827 			PROC_UNLOCK(p);
828 			return (EINVAL);
829 		}
830 
831 		/*
832 		 * Change setting atomically.
833 		 */
834 
835 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
836 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
837 		if (sigact_flag_test(act, SA_SIGINFO)) {
838 			ps->ps_sigact[_SIG_IDX(sig)] =
839 			    (__sighandler_t *)act->sa_sigaction;
840 			SIGADDSET(ps->ps_siginfo, sig);
841 		} else {
842 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
843 			SIGDELSET(ps->ps_siginfo, sig);
844 		}
845 		if (!sigact_flag_test(act, SA_RESTART))
846 			SIGADDSET(ps->ps_sigintr, sig);
847 		else
848 			SIGDELSET(ps->ps_sigintr, sig);
849 		if (sigact_flag_test(act, SA_ONSTACK))
850 			SIGADDSET(ps->ps_sigonstack, sig);
851 		else
852 			SIGDELSET(ps->ps_sigonstack, sig);
853 		if (sigact_flag_test(act, SA_RESETHAND))
854 			SIGADDSET(ps->ps_sigreset, sig);
855 		else
856 			SIGDELSET(ps->ps_sigreset, sig);
857 		if (sigact_flag_test(act, SA_NODEFER))
858 			SIGADDSET(ps->ps_signodefer, sig);
859 		else
860 			SIGDELSET(ps->ps_signodefer, sig);
861 		if (sig == SIGCHLD) {
862 			if (act->sa_flags & SA_NOCLDSTOP)
863 				ps->ps_flag |= PS_NOCLDSTOP;
864 			else
865 				ps->ps_flag &= ~PS_NOCLDSTOP;
866 			if (act->sa_flags & SA_NOCLDWAIT) {
867 				/*
868 				 * Paranoia: since SA_NOCLDWAIT is implemented
869 				 * by reparenting the dying child to PID 1 (and
870 				 * trust it to reap the zombie), PID 1 itself
871 				 * is forbidden to set SA_NOCLDWAIT.
872 				 */
873 				if (p->p_pid == 1)
874 					ps->ps_flag &= ~PS_NOCLDWAIT;
875 				else
876 					ps->ps_flag |= PS_NOCLDWAIT;
877 			} else
878 				ps->ps_flag &= ~PS_NOCLDWAIT;
879 			if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
880 				ps->ps_flag |= PS_CLDSIGIGN;
881 			else
882 				ps->ps_flag &= ~PS_CLDSIGIGN;
883 		}
884 		/*
885 		 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
886 		 * and for signals set to SIG_DFL where the default is to
887 		 * ignore. However, don't put SIGCONT in ps_sigignore, as we
888 		 * have to restart the process.
889 		 */
890 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
891 		    (sigprop(sig) & SIGPROP_IGNORE &&
892 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
893 			/* never to be seen again */
894 			sigqueue_delete_proc(p, sig);
895 			if (sig != SIGCONT)
896 				/* easier in psignal */
897 				SIGADDSET(ps->ps_sigignore, sig);
898 			SIGDELSET(ps->ps_sigcatch, sig);
899 		} else {
900 			SIGDELSET(ps->ps_sigignore, sig);
901 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
902 				SIGDELSET(ps->ps_sigcatch, sig);
903 			else
904 				SIGADDSET(ps->ps_sigcatch, sig);
905 		}
906 #ifdef COMPAT_FREEBSD4
907 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
908 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
909 		    (flags & KSA_FREEBSD4) == 0)
910 			SIGDELSET(ps->ps_freebsd4, sig);
911 		else
912 			SIGADDSET(ps->ps_freebsd4, sig);
913 #endif
914 #ifdef COMPAT_43
915 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
916 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
917 		    (flags & KSA_OSIGSET) == 0)
918 			SIGDELSET(ps->ps_osigset, sig);
919 		else
920 			SIGADDSET(ps->ps_osigset, sig);
921 #endif
922 	}
923 	mtx_unlock(&ps->ps_mtx);
924 	PROC_UNLOCK(p);
925 	return (0);
926 }
927 
928 #ifndef _SYS_SYSPROTO_H_
929 struct sigaction_args {
930 	int	sig;
931 	struct	sigaction *act;
932 	struct	sigaction *oact;
933 };
934 #endif
935 int
936 sys_sigaction(struct thread *td, struct sigaction_args *uap)
937 {
938 	struct sigaction act, oact;
939 	struct sigaction *actp, *oactp;
940 	int error;
941 
942 	actp = (uap->act != NULL) ? &act : NULL;
943 	oactp = (uap->oact != NULL) ? &oact : NULL;
944 	if (actp) {
945 		error = copyin(uap->act, actp, sizeof(act));
946 		if (error)
947 			return (error);
948 	}
949 	error = kern_sigaction(td, uap->sig, actp, oactp, 0);
950 	if (oactp && !error)
951 		error = copyout(oactp, uap->oact, sizeof(oact));
952 	return (error);
953 }
954 
955 #ifdef COMPAT_FREEBSD4
956 #ifndef _SYS_SYSPROTO_H_
957 struct freebsd4_sigaction_args {
958 	int	sig;
959 	struct	sigaction *act;
960 	struct	sigaction *oact;
961 };
962 #endif
963 int
964 freebsd4_sigaction(struct thread *td, struct freebsd4_sigaction_args *uap)
965 {
966 	struct sigaction act, oact;
967 	struct sigaction *actp, *oactp;
968 	int error;
969 
970 	actp = (uap->act != NULL) ? &act : NULL;
971 	oactp = (uap->oact != NULL) ? &oact : NULL;
972 	if (actp) {
973 		error = copyin(uap->act, actp, sizeof(act));
974 		if (error)
975 			return (error);
976 	}
977 	error = kern_sigaction(td, uap->sig, actp, oactp, KSA_FREEBSD4);
978 	if (oactp && !error)
979 		error = copyout(oactp, uap->oact, sizeof(oact));
980 	return (error);
981 }
982 #endif	/* COMAPT_FREEBSD4 */
983 
984 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
985 #ifndef _SYS_SYSPROTO_H_
986 struct osigaction_args {
987 	int	signum;
988 	struct	osigaction *nsa;
989 	struct	osigaction *osa;
990 };
991 #endif
992 int
993 osigaction(struct thread *td, struct osigaction_args *uap)
994 {
995 	struct osigaction sa;
996 	struct sigaction nsa, osa;
997 	struct sigaction *nsap, *osap;
998 	int error;
999 
1000 	if (uap->signum <= 0 || uap->signum >= ONSIG)
1001 		return (EINVAL);
1002 
1003 	nsap = (uap->nsa != NULL) ? &nsa : NULL;
1004 	osap = (uap->osa != NULL) ? &osa : NULL;
1005 
1006 	if (nsap) {
1007 		error = copyin(uap->nsa, &sa, sizeof(sa));
1008 		if (error)
1009 			return (error);
1010 		nsap->sa_handler = sa.sa_handler;
1011 		nsap->sa_flags = sa.sa_flags;
1012 		OSIG2SIG(sa.sa_mask, nsap->sa_mask);
1013 	}
1014 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
1015 	if (osap && !error) {
1016 		sa.sa_handler = osap->sa_handler;
1017 		sa.sa_flags = osap->sa_flags;
1018 		SIG2OSIG(osap->sa_mask, sa.sa_mask);
1019 		error = copyout(&sa, uap->osa, sizeof(sa));
1020 	}
1021 	return (error);
1022 }
1023 
1024 #if !defined(__i386__)
1025 /* Avoid replicating the same stub everywhere */
1026 int
1027 osigreturn(struct thread *td, struct osigreturn_args *uap)
1028 {
1029 
1030 	return (nosys(td, (struct nosys_args *)uap));
1031 }
1032 #endif
1033 #endif /* COMPAT_43 */
1034 
1035 /*
1036  * Initialize signal state for process 0;
1037  * set to ignore signals that are ignored by default.
1038  */
1039 void
1040 siginit(struct proc *p)
1041 {
1042 	int i;
1043 	struct sigacts *ps;
1044 
1045 	PROC_LOCK(p);
1046 	ps = p->p_sigacts;
1047 	mtx_lock(&ps->ps_mtx);
1048 	for (i = 1; i <= NSIG; i++) {
1049 		if (sigprop(i) & SIGPROP_IGNORE && i != SIGCONT) {
1050 			SIGADDSET(ps->ps_sigignore, i);
1051 		}
1052 	}
1053 	mtx_unlock(&ps->ps_mtx);
1054 	PROC_UNLOCK(p);
1055 }
1056 
1057 /*
1058  * Reset specified signal to the default disposition.
1059  */
1060 static void
1061 sigdflt(struct sigacts *ps, int sig)
1062 {
1063 
1064 	mtx_assert(&ps->ps_mtx, MA_OWNED);
1065 	SIGDELSET(ps->ps_sigcatch, sig);
1066 	if ((sigprop(sig) & SIGPROP_IGNORE) != 0 && sig != SIGCONT)
1067 		SIGADDSET(ps->ps_sigignore, sig);
1068 	ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1069 	SIGDELSET(ps->ps_siginfo, sig);
1070 }
1071 
1072 /*
1073  * Reset signals for an exec of the specified process.
1074  */
1075 void
1076 execsigs(struct proc *p)
1077 {
1078 	struct sigacts *ps;
1079 	struct thread *td;
1080 
1081 	/*
1082 	 * Reset caught signals.  Held signals remain held
1083 	 * through td_sigmask (unless they were caught,
1084 	 * and are now ignored by default).
1085 	 */
1086 	PROC_LOCK_ASSERT(p, MA_OWNED);
1087 	ps = p->p_sigacts;
1088 	mtx_lock(&ps->ps_mtx);
1089 	sig_drop_caught(p);
1090 
1091 	/*
1092 	 * Reset stack state to the user stack.
1093 	 * Clear set of signals caught on the signal stack.
1094 	 */
1095 	td = curthread;
1096 	MPASS(td->td_proc == p);
1097 	td->td_sigstk.ss_flags = SS_DISABLE;
1098 	td->td_sigstk.ss_size = 0;
1099 	td->td_sigstk.ss_sp = 0;
1100 	td->td_pflags &= ~TDP_ALTSTACK;
1101 	/*
1102 	 * Reset no zombies if child dies flag as Solaris does.
1103 	 */
1104 	ps->ps_flag &= ~(PS_NOCLDWAIT | PS_CLDSIGIGN);
1105 	if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
1106 		ps->ps_sigact[_SIG_IDX(SIGCHLD)] = SIG_DFL;
1107 	mtx_unlock(&ps->ps_mtx);
1108 }
1109 
1110 /*
1111  * kern_sigprocmask()
1112  *
1113  *	Manipulate signal mask.
1114  */
1115 int
1116 kern_sigprocmask(struct thread *td, int how, sigset_t *set, sigset_t *oset,
1117     int flags)
1118 {
1119 	sigset_t new_block, oset1;
1120 	struct proc *p;
1121 	int error;
1122 
1123 	p = td->td_proc;
1124 	if ((flags & SIGPROCMASK_PROC_LOCKED) != 0)
1125 		PROC_LOCK_ASSERT(p, MA_OWNED);
1126 	else
1127 		PROC_LOCK(p);
1128 	mtx_assert(&p->p_sigacts->ps_mtx, (flags & SIGPROCMASK_PS_LOCKED) != 0
1129 	    ? MA_OWNED : MA_NOTOWNED);
1130 	if (oset != NULL)
1131 		*oset = td->td_sigmask;
1132 
1133 	error = 0;
1134 	if (set != NULL) {
1135 		switch (how) {
1136 		case SIG_BLOCK:
1137 			SIG_CANTMASK(*set);
1138 			oset1 = td->td_sigmask;
1139 			SIGSETOR(td->td_sigmask, *set);
1140 			new_block = td->td_sigmask;
1141 			SIGSETNAND(new_block, oset1);
1142 			break;
1143 		case SIG_UNBLOCK:
1144 			SIGSETNAND(td->td_sigmask, *set);
1145 			signotify(td);
1146 			goto out;
1147 		case SIG_SETMASK:
1148 			SIG_CANTMASK(*set);
1149 			oset1 = td->td_sigmask;
1150 			if (flags & SIGPROCMASK_OLD)
1151 				SIGSETLO(td->td_sigmask, *set);
1152 			else
1153 				td->td_sigmask = *set;
1154 			new_block = td->td_sigmask;
1155 			SIGSETNAND(new_block, oset1);
1156 			signotify(td);
1157 			break;
1158 		default:
1159 			error = EINVAL;
1160 			goto out;
1161 		}
1162 
1163 		/*
1164 		 * The new_block set contains signals that were not previously
1165 		 * blocked, but are blocked now.
1166 		 *
1167 		 * In case we block any signal that was not previously blocked
1168 		 * for td, and process has the signal pending, try to schedule
1169 		 * signal delivery to some thread that does not block the
1170 		 * signal, possibly waking it up.
1171 		 */
1172 		if (p->p_numthreads != 1)
1173 			reschedule_signals(p, new_block, flags);
1174 	}
1175 
1176 out:
1177 	if (!(flags & SIGPROCMASK_PROC_LOCKED))
1178 		PROC_UNLOCK(p);
1179 	return (error);
1180 }
1181 
1182 #ifndef _SYS_SYSPROTO_H_
1183 struct sigprocmask_args {
1184 	int	how;
1185 	const sigset_t *set;
1186 	sigset_t *oset;
1187 };
1188 #endif
1189 int
1190 sys_sigprocmask(struct thread *td, struct sigprocmask_args *uap)
1191 {
1192 	sigset_t set, oset;
1193 	sigset_t *setp, *osetp;
1194 	int error;
1195 
1196 	setp = (uap->set != NULL) ? &set : NULL;
1197 	osetp = (uap->oset != NULL) ? &oset : NULL;
1198 	if (setp) {
1199 		error = copyin(uap->set, setp, sizeof(set));
1200 		if (error)
1201 			return (error);
1202 	}
1203 	error = kern_sigprocmask(td, uap->how, setp, osetp, 0);
1204 	if (osetp && !error) {
1205 		error = copyout(osetp, uap->oset, sizeof(oset));
1206 	}
1207 	return (error);
1208 }
1209 
1210 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1211 #ifndef _SYS_SYSPROTO_H_
1212 struct osigprocmask_args {
1213 	int	how;
1214 	osigset_t mask;
1215 };
1216 #endif
1217 int
1218 osigprocmask(struct thread *td, struct osigprocmask_args *uap)
1219 {
1220 	sigset_t set, oset;
1221 	int error;
1222 
1223 	OSIG2SIG(uap->mask, set);
1224 	error = kern_sigprocmask(td, uap->how, &set, &oset, 1);
1225 	SIG2OSIG(oset, td->td_retval[0]);
1226 	return (error);
1227 }
1228 #endif /* COMPAT_43 */
1229 
1230 int
1231 sys_sigwait(struct thread *td, struct sigwait_args *uap)
1232 {
1233 	ksiginfo_t ksi;
1234 	sigset_t set;
1235 	int error;
1236 
1237 	error = copyin(uap->set, &set, sizeof(set));
1238 	if (error) {
1239 		td->td_retval[0] = error;
1240 		return (0);
1241 	}
1242 
1243 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1244 	if (error) {
1245 		/*
1246 		 * sigwait() function shall not return EINTR, but
1247 		 * the syscall does.  Non-ancient libc provides the
1248 		 * wrapper which hides EINTR.  Otherwise, EINTR return
1249 		 * is used by libthr to handle required cancellation
1250 		 * point in the sigwait().
1251 		 */
1252 		if (error == EINTR && td->td_proc->p_osrel < P_OSREL_SIGWAIT)
1253 			return (ERESTART);
1254 		td->td_retval[0] = error;
1255 		return (0);
1256 	}
1257 
1258 	error = copyout(&ksi.ksi_signo, uap->sig, sizeof(ksi.ksi_signo));
1259 	td->td_retval[0] = error;
1260 	return (0);
1261 }
1262 
1263 int
1264 sys_sigtimedwait(struct thread *td, struct sigtimedwait_args *uap)
1265 {
1266 	struct timespec ts;
1267 	struct timespec *timeout;
1268 	sigset_t set;
1269 	ksiginfo_t ksi;
1270 	int error;
1271 
1272 	if (uap->timeout) {
1273 		error = copyin(uap->timeout, &ts, sizeof(ts));
1274 		if (error)
1275 			return (error);
1276 
1277 		timeout = &ts;
1278 	} else
1279 		timeout = NULL;
1280 
1281 	error = copyin(uap->set, &set, sizeof(set));
1282 	if (error)
1283 		return (error);
1284 
1285 	error = kern_sigtimedwait(td, set, &ksi, timeout);
1286 	if (error)
1287 		return (error);
1288 
1289 	if (uap->info)
1290 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1291 
1292 	if (error == 0)
1293 		td->td_retval[0] = ksi.ksi_signo;
1294 	return (error);
1295 }
1296 
1297 int
1298 sys_sigwaitinfo(struct thread *td, struct sigwaitinfo_args *uap)
1299 {
1300 	ksiginfo_t ksi;
1301 	sigset_t set;
1302 	int error;
1303 
1304 	error = copyin(uap->set, &set, sizeof(set));
1305 	if (error)
1306 		return (error);
1307 
1308 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1309 	if (error)
1310 		return (error);
1311 
1312 	if (uap->info)
1313 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1314 
1315 	if (error == 0)
1316 		td->td_retval[0] = ksi.ksi_signo;
1317 	return (error);
1318 }
1319 
1320 static void
1321 proc_td_siginfo_capture(struct thread *td, siginfo_t *si)
1322 {
1323 	struct thread *thr;
1324 
1325 	FOREACH_THREAD_IN_PROC(td->td_proc, thr) {
1326 		if (thr == td)
1327 			thr->td_si = *si;
1328 		else
1329 			thr->td_si.si_signo = 0;
1330 	}
1331 }
1332 
1333 int
1334 kern_sigtimedwait(struct thread *td, sigset_t waitset, ksiginfo_t *ksi,
1335 	struct timespec *timeout)
1336 {
1337 	struct sigacts *ps;
1338 	sigset_t saved_mask, new_block;
1339 	struct proc *p;
1340 	int error, sig, timevalid = 0;
1341 	sbintime_t sbt, precision, tsbt;
1342 	struct timespec ts;
1343 	bool traced;
1344 
1345 	p = td->td_proc;
1346 	error = 0;
1347 	traced = false;
1348 
1349 	/* Ensure the sigfastblock value is up to date. */
1350 	sigfastblock_fetch(td);
1351 
1352 	if (timeout != NULL) {
1353 		if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) {
1354 			timevalid = 1;
1355 			ts = *timeout;
1356 			if (ts.tv_sec < INT32_MAX / 2) {
1357 				tsbt = tstosbt(ts);
1358 				precision = tsbt;
1359 				precision >>= tc_precexp;
1360 				if (TIMESEL(&sbt, tsbt))
1361 					sbt += tc_tick_sbt;
1362 				sbt += tsbt;
1363 			} else
1364 				precision = sbt = 0;
1365 		}
1366 	} else
1367 		precision = sbt = 0;
1368 	ksiginfo_init(ksi);
1369 	/* Some signals can not be waited for. */
1370 	SIG_CANTMASK(waitset);
1371 	ps = p->p_sigacts;
1372 	PROC_LOCK(p);
1373 	saved_mask = td->td_sigmask;
1374 	SIGSETNAND(td->td_sigmask, waitset);
1375 	if ((p->p_sysent->sv_flags & SV_SIG_DISCIGN) != 0 ||
1376 	    !kern_sig_discard_ign) {
1377 		thread_lock(td);
1378 		td->td_flags |= TDF_SIGWAIT;
1379 		thread_unlock(td);
1380 	}
1381 	for (;;) {
1382 		mtx_lock(&ps->ps_mtx);
1383 		sig = cursig(td);
1384 		mtx_unlock(&ps->ps_mtx);
1385 		KASSERT(sig >= 0, ("sig %d", sig));
1386 		if (sig != 0 && SIGISMEMBER(waitset, sig)) {
1387 			if (sigqueue_get(&td->td_sigqueue, sig, ksi) != 0 ||
1388 			    sigqueue_get(&p->p_sigqueue, sig, ksi) != 0) {
1389 				error = 0;
1390 				break;
1391 			}
1392 		}
1393 
1394 		if (error != 0)
1395 			break;
1396 
1397 		/*
1398 		 * POSIX says this must be checked after looking for pending
1399 		 * signals.
1400 		 */
1401 		if (timeout != NULL && !timevalid) {
1402 			error = EINVAL;
1403 			break;
1404 		}
1405 
1406 		if (traced) {
1407 			error = EINTR;
1408 			break;
1409 		}
1410 
1411 		error = msleep_sbt(&p->p_sigacts, &p->p_mtx, PPAUSE | PCATCH,
1412 		    "sigwait", sbt, precision, C_ABSOLUTE);
1413 
1414 		/* The syscalls can not be restarted. */
1415 		if (error == ERESTART)
1416 			error = EINTR;
1417 
1418 		/*
1419 		 * If PTRACE_SCE or PTRACE_SCX were set after
1420 		 * userspace entered the syscall, return spurious
1421 		 * EINTR after wait was done.  Only do this as last
1422 		 * resort after rechecking for possible queued signals
1423 		 * and expired timeouts.
1424 		 */
1425 		if (error == 0 && (p->p_ptevents & PTRACE_SYSCALL) != 0)
1426 			traced = true;
1427 	}
1428 	thread_lock(td);
1429 	td->td_flags &= ~TDF_SIGWAIT;
1430 	thread_unlock(td);
1431 
1432 	new_block = saved_mask;
1433 	SIGSETNAND(new_block, td->td_sigmask);
1434 	td->td_sigmask = saved_mask;
1435 	/*
1436 	 * Fewer signals can be delivered to us, reschedule signal
1437 	 * notification.
1438 	 */
1439 	if (p->p_numthreads != 1)
1440 		reschedule_signals(p, new_block, 0);
1441 
1442 	if (error == 0) {
1443 		SDT_PROBE2(proc, , , signal__clear, sig, ksi);
1444 
1445 		if (ksi->ksi_code == SI_TIMER)
1446 			itimer_accept(p, ksi->ksi_timerid, ksi);
1447 
1448 #ifdef KTRACE
1449 		if (KTRPOINT(td, KTR_PSIG)) {
1450 			sig_t action;
1451 
1452 			mtx_lock(&ps->ps_mtx);
1453 			action = ps->ps_sigact[_SIG_IDX(sig)];
1454 			mtx_unlock(&ps->ps_mtx);
1455 			ktrpsig(sig, action, &td->td_sigmask, ksi->ksi_code);
1456 		}
1457 #endif
1458 		if (sig == SIGKILL) {
1459 			proc_td_siginfo_capture(td, &ksi->ksi_info);
1460 			sigexit(td, sig);
1461 		}
1462 	}
1463 	PROC_UNLOCK(p);
1464 	return (error);
1465 }
1466 
1467 #ifndef _SYS_SYSPROTO_H_
1468 struct sigpending_args {
1469 	sigset_t	*set;
1470 };
1471 #endif
1472 int
1473 sys_sigpending(struct thread *td, struct sigpending_args *uap)
1474 {
1475 	struct proc *p = td->td_proc;
1476 	sigset_t pending;
1477 
1478 	PROC_LOCK(p);
1479 	pending = p->p_sigqueue.sq_signals;
1480 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1481 	PROC_UNLOCK(p);
1482 	return (copyout(&pending, uap->set, sizeof(sigset_t)));
1483 }
1484 
1485 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1486 #ifndef _SYS_SYSPROTO_H_
1487 struct osigpending_args {
1488 	int	dummy;
1489 };
1490 #endif
1491 int
1492 osigpending(struct thread *td, struct osigpending_args *uap)
1493 {
1494 	struct proc *p = td->td_proc;
1495 	sigset_t pending;
1496 
1497 	PROC_LOCK(p);
1498 	pending = p->p_sigqueue.sq_signals;
1499 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1500 	PROC_UNLOCK(p);
1501 	SIG2OSIG(pending, td->td_retval[0]);
1502 	return (0);
1503 }
1504 #endif /* COMPAT_43 */
1505 
1506 #if defined(COMPAT_43)
1507 /*
1508  * Generalized interface signal handler, 4.3-compatible.
1509  */
1510 #ifndef _SYS_SYSPROTO_H_
1511 struct osigvec_args {
1512 	int	signum;
1513 	struct	sigvec *nsv;
1514 	struct	sigvec *osv;
1515 };
1516 #endif
1517 /* ARGSUSED */
1518 int
1519 osigvec(struct thread *td, struct osigvec_args *uap)
1520 {
1521 	struct sigvec vec;
1522 	struct sigaction nsa, osa;
1523 	struct sigaction *nsap, *osap;
1524 	int error;
1525 
1526 	if (uap->signum <= 0 || uap->signum >= ONSIG)
1527 		return (EINVAL);
1528 	nsap = (uap->nsv != NULL) ? &nsa : NULL;
1529 	osap = (uap->osv != NULL) ? &osa : NULL;
1530 	if (nsap) {
1531 		error = copyin(uap->nsv, &vec, sizeof(vec));
1532 		if (error)
1533 			return (error);
1534 		nsap->sa_handler = vec.sv_handler;
1535 		OSIG2SIG(vec.sv_mask, nsap->sa_mask);
1536 		nsap->sa_flags = vec.sv_flags;
1537 		nsap->sa_flags ^= SA_RESTART;	/* opposite of SV_INTERRUPT */
1538 	}
1539 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
1540 	if (osap && !error) {
1541 		vec.sv_handler = osap->sa_handler;
1542 		SIG2OSIG(osap->sa_mask, vec.sv_mask);
1543 		vec.sv_flags = osap->sa_flags;
1544 		vec.sv_flags &= ~SA_NOCLDWAIT;
1545 		vec.sv_flags ^= SA_RESTART;
1546 		error = copyout(&vec, uap->osv, sizeof(vec));
1547 	}
1548 	return (error);
1549 }
1550 
1551 #ifndef _SYS_SYSPROTO_H_
1552 struct osigblock_args {
1553 	int	mask;
1554 };
1555 #endif
1556 int
1557 osigblock(struct thread *td, struct osigblock_args *uap)
1558 {
1559 	sigset_t set, oset;
1560 
1561 	OSIG2SIG(uap->mask, set);
1562 	kern_sigprocmask(td, SIG_BLOCK, &set, &oset, 0);
1563 	SIG2OSIG(oset, td->td_retval[0]);
1564 	return (0);
1565 }
1566 
1567 #ifndef _SYS_SYSPROTO_H_
1568 struct osigsetmask_args {
1569 	int	mask;
1570 };
1571 #endif
1572 int
1573 osigsetmask(struct thread *td, struct osigsetmask_args *uap)
1574 {
1575 	sigset_t set, oset;
1576 
1577 	OSIG2SIG(uap->mask, set);
1578 	kern_sigprocmask(td, SIG_SETMASK, &set, &oset, 0);
1579 	SIG2OSIG(oset, td->td_retval[0]);
1580 	return (0);
1581 }
1582 #endif /* COMPAT_43 */
1583 
1584 /*
1585  * Suspend calling thread until signal, providing mask to be set in the
1586  * meantime.
1587  */
1588 #ifndef _SYS_SYSPROTO_H_
1589 struct sigsuspend_args {
1590 	const sigset_t *sigmask;
1591 };
1592 #endif
1593 /* ARGSUSED */
1594 int
1595 sys_sigsuspend(struct thread *td, struct sigsuspend_args *uap)
1596 {
1597 	sigset_t mask;
1598 	int error;
1599 
1600 	error = copyin(uap->sigmask, &mask, sizeof(mask));
1601 	if (error)
1602 		return (error);
1603 	return (kern_sigsuspend(td, mask));
1604 }
1605 
1606 int
1607 kern_sigsuspend(struct thread *td, sigset_t mask)
1608 {
1609 	struct proc *p = td->td_proc;
1610 	int has_sig, sig;
1611 
1612 	/* Ensure the sigfastblock value is up to date. */
1613 	sigfastblock_fetch(td);
1614 
1615 	/*
1616 	 * When returning from sigsuspend, we want
1617 	 * the old mask to be restored after the
1618 	 * signal handler has finished.  Thus, we
1619 	 * save it here and mark the sigacts structure
1620 	 * to indicate this.
1621 	 */
1622 	PROC_LOCK(p);
1623 	kern_sigprocmask(td, SIG_SETMASK, &mask, &td->td_oldsigmask,
1624 	    SIGPROCMASK_PROC_LOCKED);
1625 	td->td_pflags |= TDP_OLDMASK;
1626 	ast_sched(td, TDA_SIGSUSPEND);
1627 
1628 	/*
1629 	 * Process signals now. Otherwise, we can get spurious wakeup
1630 	 * due to signal entered process queue, but delivered to other
1631 	 * thread. But sigsuspend should return only on signal
1632 	 * delivery.
1633 	 */
1634 	(p->p_sysent->sv_set_syscall_retval)(td, EINTR);
1635 	for (has_sig = 0; !has_sig;) {
1636 		while (msleep(&p->p_sigacts, &p->p_mtx, PPAUSE|PCATCH, "pause",
1637 			0) == 0)
1638 			/* void */;
1639 		thread_suspend_check(0);
1640 		mtx_lock(&p->p_sigacts->ps_mtx);
1641 		while ((sig = cursig(td)) != 0) {
1642 			KASSERT(sig >= 0, ("sig %d", sig));
1643 			has_sig += postsig(sig);
1644 		}
1645 		mtx_unlock(&p->p_sigacts->ps_mtx);
1646 
1647 		/*
1648 		 * If PTRACE_SCE or PTRACE_SCX were set after
1649 		 * userspace entered the syscall, return spurious
1650 		 * EINTR.
1651 		 */
1652 		if ((p->p_ptevents & PTRACE_SYSCALL) != 0)
1653 			has_sig += 1;
1654 	}
1655 	PROC_UNLOCK(p);
1656 	td->td_errno = EINTR;
1657 	td->td_pflags |= TDP_NERRNO;
1658 	return (EJUSTRETURN);
1659 }
1660 
1661 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1662 /*
1663  * Compatibility sigsuspend call for old binaries.  Note nonstandard calling
1664  * convention: libc stub passes mask, not pointer, to save a copyin.
1665  */
1666 #ifndef _SYS_SYSPROTO_H_
1667 struct osigsuspend_args {
1668 	osigset_t mask;
1669 };
1670 #endif
1671 /* ARGSUSED */
1672 int
1673 osigsuspend(struct thread *td, struct osigsuspend_args *uap)
1674 {
1675 	sigset_t mask;
1676 
1677 	OSIG2SIG(uap->mask, mask);
1678 	return (kern_sigsuspend(td, mask));
1679 }
1680 #endif /* COMPAT_43 */
1681 
1682 #if defined(COMPAT_43)
1683 #ifndef _SYS_SYSPROTO_H_
1684 struct osigstack_args {
1685 	struct	sigstack *nss;
1686 	struct	sigstack *oss;
1687 };
1688 #endif
1689 /* ARGSUSED */
1690 int
1691 osigstack(struct thread *td, struct osigstack_args *uap)
1692 {
1693 	struct sigstack nss, oss;
1694 	int error = 0;
1695 
1696 	if (uap->nss != NULL) {
1697 		error = copyin(uap->nss, &nss, sizeof(nss));
1698 		if (error)
1699 			return (error);
1700 	}
1701 	oss.ss_sp = td->td_sigstk.ss_sp;
1702 	oss.ss_onstack = sigonstack(cpu_getstack(td));
1703 	if (uap->nss != NULL) {
1704 		td->td_sigstk.ss_sp = nss.ss_sp;
1705 		td->td_sigstk.ss_size = 0;
1706 		td->td_sigstk.ss_flags |= nss.ss_onstack & SS_ONSTACK;
1707 		td->td_pflags |= TDP_ALTSTACK;
1708 	}
1709 	if (uap->oss != NULL)
1710 		error = copyout(&oss, uap->oss, sizeof(oss));
1711 
1712 	return (error);
1713 }
1714 #endif /* COMPAT_43 */
1715 
1716 #ifndef _SYS_SYSPROTO_H_
1717 struct sigaltstack_args {
1718 	stack_t	*ss;
1719 	stack_t	*oss;
1720 };
1721 #endif
1722 /* ARGSUSED */
1723 int
1724 sys_sigaltstack(struct thread *td, struct sigaltstack_args *uap)
1725 {
1726 	stack_t ss, oss;
1727 	int error;
1728 
1729 	if (uap->ss != NULL) {
1730 		error = copyin(uap->ss, &ss, sizeof(ss));
1731 		if (error)
1732 			return (error);
1733 	}
1734 	error = kern_sigaltstack(td, (uap->ss != NULL) ? &ss : NULL,
1735 	    (uap->oss != NULL) ? &oss : NULL);
1736 	if (error)
1737 		return (error);
1738 	if (uap->oss != NULL)
1739 		error = copyout(&oss, uap->oss, sizeof(stack_t));
1740 	return (error);
1741 }
1742 
1743 int
1744 kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
1745 {
1746 	struct proc *p = td->td_proc;
1747 	int oonstack;
1748 
1749 	oonstack = sigonstack(cpu_getstack(td));
1750 
1751 	if (oss != NULL) {
1752 		*oss = td->td_sigstk;
1753 		oss->ss_flags = (td->td_pflags & TDP_ALTSTACK)
1754 		    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1755 	}
1756 
1757 	if (ss != NULL) {
1758 		if (oonstack)
1759 			return (EPERM);
1760 		if ((ss->ss_flags & ~SS_DISABLE) != 0)
1761 			return (EINVAL);
1762 		if (!(ss->ss_flags & SS_DISABLE)) {
1763 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
1764 				return (ENOMEM);
1765 
1766 			td->td_sigstk = *ss;
1767 			td->td_pflags |= TDP_ALTSTACK;
1768 		} else {
1769 			td->td_pflags &= ~TDP_ALTSTACK;
1770 		}
1771 	}
1772 	return (0);
1773 }
1774 
1775 struct killpg1_ctx {
1776 	struct thread *td;
1777 	ksiginfo_t *ksi;
1778 	int sig;
1779 	bool sent;
1780 	bool found;
1781 	int ret;
1782 };
1783 
1784 static void
1785 killpg1_sendsig_locked(struct proc *p, struct killpg1_ctx *arg)
1786 {
1787 	int err;
1788 
1789 	err = p_cansignal(arg->td, p, arg->sig);
1790 	if (err == 0 && arg->sig != 0)
1791 		pksignal(p, arg->sig, arg->ksi);
1792 	if (err != ESRCH)
1793 		arg->found = true;
1794 	if (err == 0)
1795 		arg->sent = true;
1796 	else if (arg->ret == 0 && err != ESRCH && err != EPERM)
1797 		arg->ret = err;
1798 }
1799 
1800 static void
1801 killpg1_sendsig(struct proc *p, bool notself, struct killpg1_ctx *arg)
1802 {
1803 
1804 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) != 0 ||
1805 	    (notself && p == arg->td->td_proc) || p->p_state == PRS_NEW)
1806 		return;
1807 
1808 	PROC_LOCK(p);
1809 	killpg1_sendsig_locked(p, arg);
1810 	PROC_UNLOCK(p);
1811 }
1812 
1813 static void
1814 kill_processes_prison_cb(struct proc *p, void *arg)
1815 {
1816 	struct killpg1_ctx *ctx = arg;
1817 
1818 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) != 0 ||
1819 	    (p == ctx->td->td_proc) || p->p_state == PRS_NEW)
1820 		return;
1821 
1822 	killpg1_sendsig_locked(p, ctx);
1823 }
1824 
1825 /*
1826  * Common code for kill process group/broadcast kill.
1827  * td is the calling thread, as usual.
1828  */
1829 static int
1830 killpg1(struct thread *td, int sig, int pgid, int all, ksiginfo_t *ksi)
1831 {
1832 	struct proc *p;
1833 	struct pgrp *pgrp;
1834 	struct killpg1_ctx arg;
1835 
1836 	arg.td = td;
1837 	arg.ksi = ksi;
1838 	arg.sig = sig;
1839 	arg.sent = false;
1840 	arg.found = false;
1841 	arg.ret = 0;
1842 	if (all) {
1843 		/*
1844 		 * broadcast
1845 		 */
1846 		prison_proc_iterate(td->td_ucred->cr_prison,
1847 		    kill_processes_prison_cb, &arg);
1848 	} else {
1849 again:
1850 		sx_slock(&proctree_lock);
1851 		if (pgid == 0) {
1852 			/*
1853 			 * zero pgid means send to my process group.
1854 			 */
1855 			pgrp = td->td_proc->p_pgrp;
1856 			PGRP_LOCK(pgrp);
1857 		} else {
1858 			pgrp = pgfind(pgid);
1859 			if (pgrp == NULL) {
1860 				sx_sunlock(&proctree_lock);
1861 				return (ESRCH);
1862 			}
1863 		}
1864 		sx_sunlock(&proctree_lock);
1865 		if (!sx_try_xlock(&pgrp->pg_killsx)) {
1866 			PGRP_UNLOCK(pgrp);
1867 			sx_xlock(&pgrp->pg_killsx);
1868 			sx_xunlock(&pgrp->pg_killsx);
1869 			goto again;
1870 		}
1871 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1872 			killpg1_sendsig(p, false, &arg);
1873 		}
1874 		PGRP_UNLOCK(pgrp);
1875 		sx_xunlock(&pgrp->pg_killsx);
1876 	}
1877 	MPASS(arg.ret != 0 || arg.found || !arg.sent);
1878 	if (arg.ret == 0 && !arg.sent)
1879 		arg.ret = arg.found ? EPERM : ESRCH;
1880 	return (arg.ret);
1881 }
1882 
1883 #ifndef _SYS_SYSPROTO_H_
1884 struct kill_args {
1885 	int	pid;
1886 	int	signum;
1887 };
1888 #endif
1889 /* ARGSUSED */
1890 int
1891 sys_kill(struct thread *td, struct kill_args *uap)
1892 {
1893 
1894 	return (kern_kill(td, uap->pid, uap->signum));
1895 }
1896 
1897 int
1898 kern_kill(struct thread *td, pid_t pid, int signum)
1899 {
1900 	ksiginfo_t ksi;
1901 	struct proc *p;
1902 	int error;
1903 
1904 	/*
1905 	 * A process in capability mode can send signals only to himself.
1906 	 * The main rationale behind this is that abort(3) is implemented as
1907 	 * kill(getpid(), SIGABRT).
1908 	 */
1909 	if (IN_CAPABILITY_MODE(td) && pid != td->td_proc->p_pid)
1910 		return (ECAPMODE);
1911 
1912 	AUDIT_ARG_SIGNUM(signum);
1913 	AUDIT_ARG_PID(pid);
1914 	if ((u_int)signum > _SIG_MAXSIG)
1915 		return (EINVAL);
1916 
1917 	ksiginfo_init(&ksi);
1918 	ksi.ksi_signo = signum;
1919 	ksi.ksi_code = SI_USER;
1920 	ksi.ksi_pid = td->td_proc->p_pid;
1921 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1922 
1923 	if (pid > 0) {
1924 		/* kill single process */
1925 		if ((p = pfind_any(pid)) == NULL)
1926 			return (ESRCH);
1927 		AUDIT_ARG_PROCESS(p);
1928 		error = p_cansignal(td, p, signum);
1929 		if (error == 0 && signum)
1930 			pksignal(p, signum, &ksi);
1931 		PROC_UNLOCK(p);
1932 		return (error);
1933 	}
1934 	switch (pid) {
1935 	case -1:		/* broadcast signal */
1936 		return (killpg1(td, signum, 0, 1, &ksi));
1937 	case 0:			/* signal own process group */
1938 		return (killpg1(td, signum, 0, 0, &ksi));
1939 	default:		/* negative explicit process group */
1940 		return (killpg1(td, signum, -pid, 0, &ksi));
1941 	}
1942 	/* NOTREACHED */
1943 }
1944 
1945 int
1946 sys_pdkill(struct thread *td, struct pdkill_args *uap)
1947 {
1948 	struct proc *p;
1949 	int error;
1950 
1951 	AUDIT_ARG_SIGNUM(uap->signum);
1952 	AUDIT_ARG_FD(uap->fd);
1953 	if ((u_int)uap->signum > _SIG_MAXSIG)
1954 		return (EINVAL);
1955 
1956 	error = procdesc_find(td, uap->fd, &cap_pdkill_rights, &p);
1957 	if (error)
1958 		return (error);
1959 	AUDIT_ARG_PROCESS(p);
1960 	error = p_cansignal(td, p, uap->signum);
1961 	if (error == 0 && uap->signum)
1962 		kern_psignal(p, uap->signum);
1963 	PROC_UNLOCK(p);
1964 	return (error);
1965 }
1966 
1967 #if defined(COMPAT_43)
1968 #ifndef _SYS_SYSPROTO_H_
1969 struct okillpg_args {
1970 	int	pgid;
1971 	int	signum;
1972 };
1973 #endif
1974 /* ARGSUSED */
1975 int
1976 okillpg(struct thread *td, struct okillpg_args *uap)
1977 {
1978 	ksiginfo_t ksi;
1979 
1980 	AUDIT_ARG_SIGNUM(uap->signum);
1981 	AUDIT_ARG_PID(uap->pgid);
1982 	if ((u_int)uap->signum > _SIG_MAXSIG)
1983 		return (EINVAL);
1984 
1985 	ksiginfo_init(&ksi);
1986 	ksi.ksi_signo = uap->signum;
1987 	ksi.ksi_code = SI_USER;
1988 	ksi.ksi_pid = td->td_proc->p_pid;
1989 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1990 	return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1991 }
1992 #endif /* COMPAT_43 */
1993 
1994 #ifndef _SYS_SYSPROTO_H_
1995 struct sigqueue_args {
1996 	pid_t pid;
1997 	int signum;
1998 	/* union sigval */ void *value;
1999 };
2000 #endif
2001 int
2002 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
2003 {
2004 	union sigval sv;
2005 
2006 	sv.sival_ptr = uap->value;
2007 
2008 	return (kern_sigqueue(td, uap->pid, uap->signum, &sv));
2009 }
2010 
2011 int
2012 kern_sigqueue(struct thread *td, pid_t pid, int signum, union sigval *value)
2013 {
2014 	ksiginfo_t ksi;
2015 	struct proc *p;
2016 	int error;
2017 
2018 	if ((u_int)signum > _SIG_MAXSIG)
2019 		return (EINVAL);
2020 
2021 	/*
2022 	 * Specification says sigqueue can only send signal to
2023 	 * single process.
2024 	 */
2025 	if (pid <= 0)
2026 		return (EINVAL);
2027 
2028 	if ((p = pfind_any(pid)) == NULL)
2029 		return (ESRCH);
2030 	error = p_cansignal(td, p, signum);
2031 	if (error == 0 && signum != 0) {
2032 		ksiginfo_init(&ksi);
2033 		ksi.ksi_flags = KSI_SIGQ;
2034 		ksi.ksi_signo = signum;
2035 		ksi.ksi_code = SI_QUEUE;
2036 		ksi.ksi_pid = td->td_proc->p_pid;
2037 		ksi.ksi_uid = td->td_ucred->cr_ruid;
2038 		ksi.ksi_value = *value;
2039 		error = pksignal(p, ksi.ksi_signo, &ksi);
2040 	}
2041 	PROC_UNLOCK(p);
2042 	return (error);
2043 }
2044 
2045 /*
2046  * Send a signal to a process group.  If checktty is 1,
2047  * limit to members which have a controlling terminal.
2048  */
2049 void
2050 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
2051 {
2052 	struct proc *p;
2053 
2054 	if (pgrp) {
2055 		PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
2056 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
2057 			PROC_LOCK(p);
2058 			if (p->p_state == PRS_NORMAL &&
2059 			    (checkctty == 0 || p->p_flag & P_CONTROLT))
2060 				pksignal(p, sig, ksi);
2061 			PROC_UNLOCK(p);
2062 		}
2063 	}
2064 }
2065 
2066 /*
2067  * Recalculate the signal mask and reset the signal disposition after
2068  * usermode frame for delivery is formed.  Should be called after
2069  * mach-specific routine, because sysent->sv_sendsig() needs correct
2070  * ps_siginfo and signal mask.
2071  */
2072 static void
2073 postsig_done(int sig, struct thread *td, struct sigacts *ps)
2074 {
2075 	sigset_t mask;
2076 
2077 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2078 	td->td_ru.ru_nsignals++;
2079 	mask = ps->ps_catchmask[_SIG_IDX(sig)];
2080 	if (!SIGISMEMBER(ps->ps_signodefer, sig))
2081 		SIGADDSET(mask, sig);
2082 	kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
2083 	    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
2084 	if (SIGISMEMBER(ps->ps_sigreset, sig))
2085 		sigdflt(ps, sig);
2086 }
2087 
2088 /*
2089  * Send a signal caused by a trap to the current thread.  If it will be
2090  * caught immediately, deliver it with correct code.  Otherwise, post it
2091  * normally.
2092  */
2093 void
2094 trapsignal(struct thread *td, ksiginfo_t *ksi)
2095 {
2096 	struct sigacts *ps;
2097 	struct proc *p;
2098 	sigset_t sigmask;
2099 	int sig;
2100 
2101 	p = td->td_proc;
2102 	sig = ksi->ksi_signo;
2103 	KASSERT(_SIG_VALID(sig), ("invalid signal"));
2104 
2105 	sigfastblock_fetch(td);
2106 	PROC_LOCK(p);
2107 	ps = p->p_sigacts;
2108 	mtx_lock(&ps->ps_mtx);
2109 	sigmask = td->td_sigmask;
2110 	if (td->td_sigblock_val != 0)
2111 		SIGSETOR(sigmask, fastblock_mask);
2112 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
2113 	    !SIGISMEMBER(sigmask, sig)) {
2114 #ifdef KTRACE
2115 		if (KTRPOINT(curthread, KTR_PSIG))
2116 			ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
2117 			    &td->td_sigmask, ksi->ksi_code);
2118 #endif
2119 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
2120 		    ksi, &td->td_sigmask);
2121 		postsig_done(sig, td, ps);
2122 		mtx_unlock(&ps->ps_mtx);
2123 	} else {
2124 		/*
2125 		 * Avoid a possible infinite loop if the thread
2126 		 * masking the signal or process is ignoring the
2127 		 * signal.
2128 		 */
2129 		if (kern_forcesigexit && (SIGISMEMBER(sigmask, sig) ||
2130 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
2131 			SIGDELSET(td->td_sigmask, sig);
2132 			SIGDELSET(ps->ps_sigcatch, sig);
2133 			SIGDELSET(ps->ps_sigignore, sig);
2134 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2135 			td->td_pflags &= ~TDP_SIGFASTBLOCK;
2136 			td->td_sigblock_val = 0;
2137 		}
2138 		mtx_unlock(&ps->ps_mtx);
2139 		p->p_sig = sig;		/* XXX to verify code */
2140 		tdsendsignal(p, td, sig, ksi);
2141 	}
2142 	PROC_UNLOCK(p);
2143 }
2144 
2145 static struct thread *
2146 sigtd(struct proc *p, int sig, bool fast_sigblock)
2147 {
2148 	struct thread *td, *signal_td;
2149 
2150 	PROC_LOCK_ASSERT(p, MA_OWNED);
2151 	MPASS(!fast_sigblock || p == curproc);
2152 
2153 	/*
2154 	 * Check if current thread can handle the signal without
2155 	 * switching context to another thread.
2156 	 */
2157 	if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig) &&
2158 	    (!fast_sigblock || curthread->td_sigblock_val == 0))
2159 		return (curthread);
2160 
2161 	/* Find a non-stopped thread that does not mask the signal. */
2162 	signal_td = NULL;
2163 	FOREACH_THREAD_IN_PROC(p, td) {
2164 		if (!SIGISMEMBER(td->td_sigmask, sig) && (!fast_sigblock ||
2165 		    td != curthread || td->td_sigblock_val == 0) &&
2166 		    (td->td_flags & TDF_BOUNDARY) == 0) {
2167 			signal_td = td;
2168 			break;
2169 		}
2170 	}
2171 	/* Select random (first) thread if no better match was found. */
2172 	if (signal_td == NULL)
2173 		signal_td = FIRST_THREAD_IN_PROC(p);
2174 	return (signal_td);
2175 }
2176 
2177 /*
2178  * Send the signal to the process.  If the signal has an action, the action
2179  * is usually performed by the target process rather than the caller; we add
2180  * the signal to the set of pending signals for the process.
2181  *
2182  * Exceptions:
2183  *   o When a stop signal is sent to a sleeping process that takes the
2184  *     default action, the process is stopped without awakening it.
2185  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2186  *     regardless of the signal action (eg, blocked or ignored).
2187  *
2188  * Other ignored signals are discarded immediately.
2189  *
2190  * NB: This function may be entered from the debugger via the "kill" DDB
2191  * command.  There is little that can be done to mitigate the possibly messy
2192  * side effects of this unwise possibility.
2193  */
2194 void
2195 kern_psignal(struct proc *p, int sig)
2196 {
2197 	ksiginfo_t ksi;
2198 
2199 	ksiginfo_init(&ksi);
2200 	ksi.ksi_signo = sig;
2201 	ksi.ksi_code = SI_KERNEL;
2202 	(void) tdsendsignal(p, NULL, sig, &ksi);
2203 }
2204 
2205 int
2206 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
2207 {
2208 
2209 	return (tdsendsignal(p, NULL, sig, ksi));
2210 }
2211 
2212 /* Utility function for finding a thread to send signal event to. */
2213 int
2214 sigev_findtd(struct proc *p, struct sigevent *sigev, struct thread **ttd)
2215 {
2216 	struct thread *td;
2217 
2218 	if (sigev->sigev_notify == SIGEV_THREAD_ID) {
2219 		td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
2220 		if (td == NULL)
2221 			return (ESRCH);
2222 		*ttd = td;
2223 	} else {
2224 		*ttd = NULL;
2225 		PROC_LOCK(p);
2226 	}
2227 	return (0);
2228 }
2229 
2230 void
2231 tdsignal(struct thread *td, int sig)
2232 {
2233 	ksiginfo_t ksi;
2234 
2235 	ksiginfo_init(&ksi);
2236 	ksi.ksi_signo = sig;
2237 	ksi.ksi_code = SI_KERNEL;
2238 	(void) tdsendsignal(td->td_proc, td, sig, &ksi);
2239 }
2240 
2241 void
2242 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2243 {
2244 
2245 	(void) tdsendsignal(td->td_proc, td, sig, ksi);
2246 }
2247 
2248 static int
2249 sig_sleepq_abort(struct thread *td, int intrval)
2250 {
2251 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2252 
2253 	if (intrval == 0 && (td->td_flags & TDF_SIGWAIT) == 0) {
2254 		thread_unlock(td);
2255 		return (0);
2256 	}
2257 	return (sleepq_abort(td, intrval));
2258 }
2259 
2260 int
2261 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2262 {
2263 	sig_t action;
2264 	sigqueue_t *sigqueue;
2265 	int prop;
2266 	struct sigacts *ps;
2267 	int intrval;
2268 	int ret = 0;
2269 	int wakeup_swapper;
2270 
2271 	MPASS(td == NULL || p == td->td_proc);
2272 	PROC_LOCK_ASSERT(p, MA_OWNED);
2273 
2274 	if (!_SIG_VALID(sig))
2275 		panic("%s(): invalid signal %d", __func__, sig);
2276 
2277 	KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2278 
2279 	/*
2280 	 * IEEE Std 1003.1-2001: return success when killing a zombie.
2281 	 */
2282 	if (p->p_state == PRS_ZOMBIE) {
2283 		if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2284 			ksiginfo_tryfree(ksi);
2285 		return (ret);
2286 	}
2287 
2288 	ps = p->p_sigacts;
2289 	KNOTE_LOCKED(p->p_klist, NOTE_SIGNAL | sig);
2290 	prop = sigprop(sig);
2291 
2292 	if (td == NULL) {
2293 		td = sigtd(p, sig, false);
2294 		sigqueue = &p->p_sigqueue;
2295 	} else
2296 		sigqueue = &td->td_sigqueue;
2297 
2298 	SDT_PROBE3(proc, , , signal__send, td, p, sig);
2299 
2300 	/*
2301 	 * If the signal is being ignored, then we forget about it
2302 	 * immediately, except when the target process executes
2303 	 * sigwait().  (Note: we don't set SIGCONT in ps_sigignore,
2304 	 * and if it is set to SIG_IGN, action will be SIG_DFL here.)
2305 	 */
2306 	mtx_lock(&ps->ps_mtx);
2307 	if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2308 		if (kern_sig_discard_ign &&
2309 		    (p->p_sysent->sv_flags & SV_SIG_DISCIGN) == 0) {
2310 			SDT_PROBE3(proc, , , signal__discard, td, p, sig);
2311 
2312 			mtx_unlock(&ps->ps_mtx);
2313 			if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2314 				ksiginfo_tryfree(ksi);
2315 			return (ret);
2316 		} else {
2317 			action = SIG_CATCH;
2318 			intrval = 0;
2319 		}
2320 	} else {
2321 		if (SIGISMEMBER(td->td_sigmask, sig))
2322 			action = SIG_HOLD;
2323 		else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2324 			action = SIG_CATCH;
2325 		else
2326 			action = SIG_DFL;
2327 		if (SIGISMEMBER(ps->ps_sigintr, sig))
2328 			intrval = EINTR;
2329 		else
2330 			intrval = ERESTART;
2331 	}
2332 	mtx_unlock(&ps->ps_mtx);
2333 
2334 	if (prop & SIGPROP_CONT)
2335 		sigqueue_delete_stopmask_proc(p);
2336 	else if (prop & SIGPROP_STOP) {
2337 		/*
2338 		 * If sending a tty stop signal to a member of an orphaned
2339 		 * process group, discard the signal here if the action
2340 		 * is default; don't stop the process below if sleeping,
2341 		 * and don't clear any pending SIGCONT.
2342 		 */
2343 		if ((prop & SIGPROP_TTYSTOP) != 0 &&
2344 		    (p->p_pgrp->pg_flags & PGRP_ORPHANED) != 0 &&
2345 		    action == SIG_DFL) {
2346 			if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2347 				ksiginfo_tryfree(ksi);
2348 			return (ret);
2349 		}
2350 		sigqueue_delete_proc(p, SIGCONT);
2351 		if (p->p_flag & P_CONTINUED) {
2352 			p->p_flag &= ~P_CONTINUED;
2353 			PROC_LOCK(p->p_pptr);
2354 			sigqueue_take(p->p_ksi);
2355 			PROC_UNLOCK(p->p_pptr);
2356 		}
2357 	}
2358 
2359 	ret = sigqueue_add(sigqueue, sig, ksi);
2360 	if (ret != 0)
2361 		return (ret);
2362 	signotify(td);
2363 	/*
2364 	 * Defer further processing for signals which are held,
2365 	 * except that stopped processes must be continued by SIGCONT.
2366 	 */
2367 	if (action == SIG_HOLD &&
2368 	    !((prop & SIGPROP_CONT) && (p->p_flag & P_STOPPED_SIG)))
2369 		return (ret);
2370 
2371 	wakeup_swapper = 0;
2372 
2373 	/*
2374 	 * Some signals have a process-wide effect and a per-thread
2375 	 * component.  Most processing occurs when the process next
2376 	 * tries to cross the user boundary, however there are some
2377 	 * times when processing needs to be done immediately, such as
2378 	 * waking up threads so that they can cross the user boundary.
2379 	 * We try to do the per-process part here.
2380 	 */
2381 	if (P_SHOULDSTOP(p)) {
2382 		KASSERT(!(p->p_flag & P_WEXIT),
2383 		    ("signal to stopped but exiting process"));
2384 		if (sig == SIGKILL) {
2385 			/*
2386 			 * If traced process is already stopped,
2387 			 * then no further action is necessary.
2388 			 */
2389 			if (p->p_flag & P_TRACED)
2390 				goto out;
2391 			/*
2392 			 * SIGKILL sets process running.
2393 			 * It will die elsewhere.
2394 			 * All threads must be restarted.
2395 			 */
2396 			p->p_flag &= ~P_STOPPED_SIG;
2397 			goto runfast;
2398 		}
2399 
2400 		if (prop & SIGPROP_CONT) {
2401 			/*
2402 			 * If traced process is already stopped,
2403 			 * then no further action is necessary.
2404 			 */
2405 			if (p->p_flag & P_TRACED)
2406 				goto out;
2407 			/*
2408 			 * If SIGCONT is default (or ignored), we continue the
2409 			 * process but don't leave the signal in sigqueue as
2410 			 * it has no further action.  If SIGCONT is held, we
2411 			 * continue the process and leave the signal in
2412 			 * sigqueue.  If the process catches SIGCONT, let it
2413 			 * handle the signal itself.  If it isn't waiting on
2414 			 * an event, it goes back to run state.
2415 			 * Otherwise, process goes back to sleep state.
2416 			 */
2417 			p->p_flag &= ~P_STOPPED_SIG;
2418 			PROC_SLOCK(p);
2419 			if (p->p_numthreads == p->p_suspcount) {
2420 				PROC_SUNLOCK(p);
2421 				p->p_flag |= P_CONTINUED;
2422 				p->p_xsig = SIGCONT;
2423 				PROC_LOCK(p->p_pptr);
2424 				childproc_continued(p);
2425 				PROC_UNLOCK(p->p_pptr);
2426 				PROC_SLOCK(p);
2427 			}
2428 			if (action == SIG_DFL) {
2429 				thread_unsuspend(p);
2430 				PROC_SUNLOCK(p);
2431 				sigqueue_delete(sigqueue, sig);
2432 				goto out_cont;
2433 			}
2434 			if (action == SIG_CATCH) {
2435 				/*
2436 				 * The process wants to catch it so it needs
2437 				 * to run at least one thread, but which one?
2438 				 */
2439 				PROC_SUNLOCK(p);
2440 				goto runfast;
2441 			}
2442 			/*
2443 			 * The signal is not ignored or caught.
2444 			 */
2445 			thread_unsuspend(p);
2446 			PROC_SUNLOCK(p);
2447 			goto out_cont;
2448 		}
2449 
2450 		if (prop & SIGPROP_STOP) {
2451 			/*
2452 			 * If traced process is already stopped,
2453 			 * then no further action is necessary.
2454 			 */
2455 			if (p->p_flag & P_TRACED)
2456 				goto out;
2457 			/*
2458 			 * Already stopped, don't need to stop again
2459 			 * (If we did the shell could get confused).
2460 			 * Just make sure the signal STOP bit set.
2461 			 */
2462 			p->p_flag |= P_STOPPED_SIG;
2463 			sigqueue_delete(sigqueue, sig);
2464 			goto out;
2465 		}
2466 
2467 		/*
2468 		 * All other kinds of signals:
2469 		 * If a thread is sleeping interruptibly, simulate a
2470 		 * wakeup so that when it is continued it will be made
2471 		 * runnable and can look at the signal.  However, don't make
2472 		 * the PROCESS runnable, leave it stopped.
2473 		 * It may run a bit until it hits a thread_suspend_check().
2474 		 */
2475 		PROC_SLOCK(p);
2476 		thread_lock(td);
2477 		if (TD_CAN_ABORT(td))
2478 			wakeup_swapper = sig_sleepq_abort(td, intrval);
2479 		else
2480 			thread_unlock(td);
2481 		PROC_SUNLOCK(p);
2482 		goto out;
2483 		/*
2484 		 * Mutexes are short lived. Threads waiting on them will
2485 		 * hit thread_suspend_check() soon.
2486 		 */
2487 	} else if (p->p_state == PRS_NORMAL) {
2488 		if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2489 			tdsigwakeup(td, sig, action, intrval);
2490 			goto out;
2491 		}
2492 
2493 		MPASS(action == SIG_DFL);
2494 
2495 		if (prop & SIGPROP_STOP) {
2496 			if (p->p_flag & (P_PPWAIT|P_WEXIT))
2497 				goto out;
2498 			p->p_flag |= P_STOPPED_SIG;
2499 			p->p_xsig = sig;
2500 			PROC_SLOCK(p);
2501 			wakeup_swapper = sig_suspend_threads(td, p);
2502 			if (p->p_numthreads == p->p_suspcount) {
2503 				/*
2504 				 * only thread sending signal to another
2505 				 * process can reach here, if thread is sending
2506 				 * signal to its process, because thread does
2507 				 * not suspend itself here, p_numthreads
2508 				 * should never be equal to p_suspcount.
2509 				 */
2510 				thread_stopped(p);
2511 				PROC_SUNLOCK(p);
2512 				sigqueue_delete_proc(p, p->p_xsig);
2513 			} else
2514 				PROC_SUNLOCK(p);
2515 			goto out;
2516 		}
2517 	} else {
2518 		/* Not in "NORMAL" state. discard the signal. */
2519 		sigqueue_delete(sigqueue, sig);
2520 		goto out;
2521 	}
2522 
2523 	/*
2524 	 * The process is not stopped so we need to apply the signal to all the
2525 	 * running threads.
2526 	 */
2527 runfast:
2528 	tdsigwakeup(td, sig, action, intrval);
2529 	PROC_SLOCK(p);
2530 	thread_unsuspend(p);
2531 	PROC_SUNLOCK(p);
2532 out_cont:
2533 	itimer_proc_continue(p);
2534 	kqtimer_proc_continue(p);
2535 out:
2536 	/* If we jump here, proc slock should not be owned. */
2537 	PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2538 	if (wakeup_swapper)
2539 		kick_proc0();
2540 
2541 	return (ret);
2542 }
2543 
2544 /*
2545  * The force of a signal has been directed against a single
2546  * thread.  We need to see what we can do about knocking it
2547  * out of any sleep it may be in etc.
2548  */
2549 static void
2550 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2551 {
2552 	struct proc *p = td->td_proc;
2553 	int prop, wakeup_swapper;
2554 
2555 	PROC_LOCK_ASSERT(p, MA_OWNED);
2556 	prop = sigprop(sig);
2557 
2558 	PROC_SLOCK(p);
2559 	thread_lock(td);
2560 	/*
2561 	 * Bring the priority of a thread up if we want it to get
2562 	 * killed in this lifetime.  Be careful to avoid bumping the
2563 	 * priority of the idle thread, since we still allow to signal
2564 	 * kernel processes.
2565 	 */
2566 	if (action == SIG_DFL && (prop & SIGPROP_KILL) != 0 &&
2567 	    td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2568 		sched_prio(td, PUSER);
2569 	if (TD_ON_SLEEPQ(td)) {
2570 		/*
2571 		 * If thread is sleeping uninterruptibly
2572 		 * we can't interrupt the sleep... the signal will
2573 		 * be noticed when the process returns through
2574 		 * trap() or syscall().
2575 		 */
2576 		if ((td->td_flags & TDF_SINTR) == 0)
2577 			goto out;
2578 		/*
2579 		 * If SIGCONT is default (or ignored) and process is
2580 		 * asleep, we are finished; the process should not
2581 		 * be awakened.
2582 		 */
2583 		if ((prop & SIGPROP_CONT) && action == SIG_DFL) {
2584 			thread_unlock(td);
2585 			PROC_SUNLOCK(p);
2586 			sigqueue_delete(&p->p_sigqueue, sig);
2587 			/*
2588 			 * It may be on either list in this state.
2589 			 * Remove from both for now.
2590 			 */
2591 			sigqueue_delete(&td->td_sigqueue, sig);
2592 			return;
2593 		}
2594 
2595 		/*
2596 		 * Don't awaken a sleeping thread for SIGSTOP if the
2597 		 * STOP signal is deferred.
2598 		 */
2599 		if ((prop & SIGPROP_STOP) != 0 && (td->td_flags & (TDF_SBDRY |
2600 		    TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2601 			goto out;
2602 
2603 		/*
2604 		 * Give low priority threads a better chance to run.
2605 		 */
2606 		if (td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2607 			sched_prio(td, PUSER);
2608 
2609 		wakeup_swapper = sig_sleepq_abort(td, intrval);
2610 		PROC_SUNLOCK(p);
2611 		if (wakeup_swapper)
2612 			kick_proc0();
2613 		return;
2614 	}
2615 
2616 	/*
2617 	 * Other states do nothing with the signal immediately,
2618 	 * other than kicking ourselves if we are running.
2619 	 * It will either never be noticed, or noticed very soon.
2620 	 */
2621 #ifdef SMP
2622 	if (TD_IS_RUNNING(td) && td != curthread)
2623 		forward_signal(td);
2624 #endif
2625 
2626 out:
2627 	PROC_SUNLOCK(p);
2628 	thread_unlock(td);
2629 }
2630 
2631 static void
2632 ptrace_coredumpreq(struct thread *td, struct proc *p,
2633     struct thr_coredump_req *tcq)
2634 {
2635 	void *rl_cookie;
2636 
2637 	if (p->p_sysent->sv_coredump == NULL) {
2638 		tcq->tc_error = ENOSYS;
2639 		return;
2640 	}
2641 
2642 	rl_cookie = vn_rangelock_wlock(tcq->tc_vp, 0, OFF_MAX);
2643 	tcq->tc_error = p->p_sysent->sv_coredump(td, tcq->tc_vp,
2644 	    tcq->tc_limit, tcq->tc_flags);
2645 	vn_rangelock_unlock(tcq->tc_vp, rl_cookie);
2646 }
2647 
2648 static void
2649 ptrace_syscallreq(struct thread *td, struct proc *p,
2650     struct thr_syscall_req *tsr)
2651 {
2652 	struct sysentvec *sv;
2653 	struct sysent *se;
2654 	register_t rv_saved[2];
2655 	int error, nerror;
2656 	int sc;
2657 	bool audited, sy_thr_static;
2658 
2659 	sv = p->p_sysent;
2660 	if (sv->sv_table == NULL || sv->sv_size < tsr->ts_sa.code) {
2661 		tsr->ts_ret.sr_error = ENOSYS;
2662 		return;
2663 	}
2664 
2665 	sc = tsr->ts_sa.code;
2666 	if (sc == SYS_syscall || sc == SYS___syscall) {
2667 		sc = tsr->ts_sa.args[0];
2668 		memmove(&tsr->ts_sa.args[0], &tsr->ts_sa.args[1],
2669 		    sizeof(register_t) * (tsr->ts_nargs - 1));
2670 	}
2671 
2672 	tsr->ts_sa.callp = se = &sv->sv_table[sc];
2673 
2674 	VM_CNT_INC(v_syscall);
2675 	td->td_pticks = 0;
2676 	if (__predict_false(td->td_cowgen != atomic_load_int(
2677 	    &td->td_proc->p_cowgen)))
2678 		thread_cow_update(td);
2679 
2680 #ifdef CAPABILITY_MODE
2681 	if (IN_CAPABILITY_MODE(td) && (se->sy_flags & SYF_CAPENABLED) == 0) {
2682 		tsr->ts_ret.sr_error = ECAPMODE;
2683 		return;
2684 	}
2685 #endif
2686 
2687 	sy_thr_static = (se->sy_thrcnt & SY_THR_STATIC) != 0;
2688 	audited = AUDIT_SYSCALL_ENTER(sc, td) != 0;
2689 
2690 	if (!sy_thr_static) {
2691 		error = syscall_thread_enter(td, se);
2692 		if (error != 0) {
2693 			tsr->ts_ret.sr_error = error;
2694 			return;
2695 		}
2696 	}
2697 
2698 	rv_saved[0] = td->td_retval[0];
2699 	rv_saved[1] = td->td_retval[1];
2700 	nerror = td->td_errno;
2701 	td->td_retval[0] = 0;
2702 	td->td_retval[1] = 0;
2703 
2704 #ifdef KDTRACE_HOOKS
2705 	if (se->sy_entry != 0)
2706 		(*systrace_probe_func)(&tsr->ts_sa, SYSTRACE_ENTRY, 0);
2707 #endif
2708 	tsr->ts_ret.sr_error = se->sy_call(td, tsr->ts_sa.args);
2709 #ifdef KDTRACE_HOOKS
2710 	if (se->sy_return != 0)
2711 		(*systrace_probe_func)(&tsr->ts_sa, SYSTRACE_RETURN,
2712 		    tsr->ts_ret.sr_error != 0 ? -1 : td->td_retval[0]);
2713 #endif
2714 
2715 	tsr->ts_ret.sr_retval[0] = td->td_retval[0];
2716 	tsr->ts_ret.sr_retval[1] = td->td_retval[1];
2717 	td->td_retval[0] = rv_saved[0];
2718 	td->td_retval[1] = rv_saved[1];
2719 	td->td_errno = nerror;
2720 
2721 	if (audited)
2722 		AUDIT_SYSCALL_EXIT(error, td);
2723 	if (!sy_thr_static)
2724 		syscall_thread_exit(td, se);
2725 }
2726 
2727 static void
2728 ptrace_remotereq(struct thread *td, int flag)
2729 {
2730 	struct proc *p;
2731 
2732 	MPASS(td == curthread);
2733 	p = td->td_proc;
2734 	PROC_LOCK_ASSERT(p, MA_OWNED);
2735 	if ((td->td_dbgflags & flag) == 0)
2736 		return;
2737 	KASSERT((p->p_flag & P_STOPPED_TRACE) != 0, ("not stopped"));
2738 	KASSERT(td->td_remotereq != NULL, ("td_remotereq is NULL"));
2739 
2740 	PROC_UNLOCK(p);
2741 	switch (flag) {
2742 	case TDB_COREDUMPREQ:
2743 		ptrace_coredumpreq(td, p, td->td_remotereq);
2744 		break;
2745 	case TDB_SCREMOTEREQ:
2746 		ptrace_syscallreq(td, p, td->td_remotereq);
2747 		break;
2748 	default:
2749 		__unreachable();
2750 	}
2751 	PROC_LOCK(p);
2752 
2753 	MPASS((td->td_dbgflags & flag) != 0);
2754 	td->td_dbgflags &= ~flag;
2755 	td->td_remotereq = NULL;
2756 	wakeup(p);
2757 }
2758 
2759 static int
2760 sig_suspend_threads(struct thread *td, struct proc *p)
2761 {
2762 	struct thread *td2;
2763 	int wakeup_swapper;
2764 
2765 	PROC_LOCK_ASSERT(p, MA_OWNED);
2766 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2767 
2768 	wakeup_swapper = 0;
2769 	FOREACH_THREAD_IN_PROC(p, td2) {
2770 		thread_lock(td2);
2771 		ast_sched_locked(td2, TDA_SUSPEND);
2772 		if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2773 		    (td2->td_flags & TDF_SINTR)) {
2774 			if (td2->td_flags & TDF_SBDRY) {
2775 				/*
2776 				 * Once a thread is asleep with
2777 				 * TDF_SBDRY and without TDF_SERESTART
2778 				 * or TDF_SEINTR set, it should never
2779 				 * become suspended due to this check.
2780 				 */
2781 				KASSERT(!TD_IS_SUSPENDED(td2),
2782 				    ("thread with deferred stops suspended"));
2783 				if (TD_SBDRY_INTR(td2)) {
2784 					wakeup_swapper |= sleepq_abort(td2,
2785 					    TD_SBDRY_ERRNO(td2));
2786 					continue;
2787 				}
2788 			} else if (!TD_IS_SUSPENDED(td2))
2789 				thread_suspend_one(td2);
2790 		} else if (!TD_IS_SUSPENDED(td2)) {
2791 #ifdef SMP
2792 			if (TD_IS_RUNNING(td2) && td2 != td)
2793 				forward_signal(td2);
2794 #endif
2795 		}
2796 		thread_unlock(td2);
2797 	}
2798 	return (wakeup_swapper);
2799 }
2800 
2801 /*
2802  * Stop the process for an event deemed interesting to the debugger. If si is
2803  * non-NULL, this is a signal exchange; the new signal requested by the
2804  * debugger will be returned for handling. If si is NULL, this is some other
2805  * type of interesting event. The debugger may request a signal be delivered in
2806  * that case as well, however it will be deferred until it can be handled.
2807  */
2808 int
2809 ptracestop(struct thread *td, int sig, ksiginfo_t *si)
2810 {
2811 	struct proc *p = td->td_proc;
2812 	struct thread *td2;
2813 	ksiginfo_t ksi;
2814 
2815 	PROC_LOCK_ASSERT(p, MA_OWNED);
2816 	KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2817 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2818 	    &p->p_mtx.lock_object, "Stopping for traced signal");
2819 
2820 	td->td_xsig = sig;
2821 
2822 	if (si == NULL || (si->ksi_flags & KSI_PTRACE) == 0) {
2823 		td->td_dbgflags |= TDB_XSIG;
2824 		CTR4(KTR_PTRACE, "ptracestop: tid %d (pid %d) flags %#x sig %d",
2825 		    td->td_tid, p->p_pid, td->td_dbgflags, sig);
2826 		PROC_SLOCK(p);
2827 		while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2828 			if (P_KILLED(p)) {
2829 				/*
2830 				 * Ensure that, if we've been PT_KILLed, the
2831 				 * exit status reflects that. Another thread
2832 				 * may also be in ptracestop(), having just
2833 				 * received the SIGKILL, but this thread was
2834 				 * unsuspended first.
2835 				 */
2836 				td->td_dbgflags &= ~TDB_XSIG;
2837 				td->td_xsig = SIGKILL;
2838 				p->p_ptevents = 0;
2839 				break;
2840 			}
2841 			if (p->p_flag & P_SINGLE_EXIT &&
2842 			    !(td->td_dbgflags & TDB_EXIT)) {
2843 				/*
2844 				 * Ignore ptrace stops except for thread exit
2845 				 * events when the process exits.
2846 				 */
2847 				td->td_dbgflags &= ~TDB_XSIG;
2848 				PROC_SUNLOCK(p);
2849 				return (0);
2850 			}
2851 
2852 			/*
2853 			 * Make wait(2) work.  Ensure that right after the
2854 			 * attach, the thread which was decided to become the
2855 			 * leader of attach gets reported to the waiter.
2856 			 * Otherwise, just avoid overwriting another thread's
2857 			 * assignment to p_xthread.  If another thread has
2858 			 * already set p_xthread, the current thread will get
2859 			 * a chance to report itself upon the next iteration.
2860 			 */
2861 			if ((td->td_dbgflags & TDB_FSTP) != 0 ||
2862 			    ((p->p_flag2 & P2_PTRACE_FSTP) == 0 &&
2863 			    p->p_xthread == NULL)) {
2864 				p->p_xsig = sig;
2865 				p->p_xthread = td;
2866 
2867 				/*
2868 				 * If we are on sleepqueue already,
2869 				 * let sleepqueue code decide if it
2870 				 * needs to go sleep after attach.
2871 				 */
2872 				if (td->td_wchan == NULL)
2873 					td->td_dbgflags &= ~TDB_FSTP;
2874 
2875 				p->p_flag2 &= ~P2_PTRACE_FSTP;
2876 				p->p_flag |= P_STOPPED_SIG | P_STOPPED_TRACE;
2877 				sig_suspend_threads(td, p);
2878 			}
2879 			if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2880 				td->td_dbgflags &= ~TDB_STOPATFORK;
2881 			}
2882 stopme:
2883 			td->td_dbgflags |= TDB_SSWITCH;
2884 			thread_suspend_switch(td, p);
2885 			td->td_dbgflags &= ~TDB_SSWITCH;
2886 			if ((td->td_dbgflags & (TDB_COREDUMPREQ |
2887 			    TDB_SCREMOTEREQ)) != 0) {
2888 				MPASS((td->td_dbgflags & (TDB_COREDUMPREQ |
2889 				    TDB_SCREMOTEREQ)) !=
2890 				    (TDB_COREDUMPREQ | TDB_SCREMOTEREQ));
2891 				PROC_SUNLOCK(p);
2892 				ptrace_remotereq(td, td->td_dbgflags &
2893 				    (TDB_COREDUMPREQ | TDB_SCREMOTEREQ));
2894 				PROC_SLOCK(p);
2895 				goto stopme;
2896 			}
2897 			if (p->p_xthread == td)
2898 				p->p_xthread = NULL;
2899 			if (!(p->p_flag & P_TRACED))
2900 				break;
2901 			if (td->td_dbgflags & TDB_SUSPEND) {
2902 				if (p->p_flag & P_SINGLE_EXIT)
2903 					break;
2904 				goto stopme;
2905 			}
2906 		}
2907 		PROC_SUNLOCK(p);
2908 	}
2909 
2910 	if (si != NULL && sig == td->td_xsig) {
2911 		/* Parent wants us to take the original signal unchanged. */
2912 		si->ksi_flags |= KSI_HEAD;
2913 		if (sigqueue_add(&td->td_sigqueue, sig, si) != 0)
2914 			si->ksi_signo = 0;
2915 	} else if (td->td_xsig != 0) {
2916 		/*
2917 		 * If parent wants us to take a new signal, then it will leave
2918 		 * it in td->td_xsig; otherwise we just look for signals again.
2919 		 */
2920 		ksiginfo_init(&ksi);
2921 		ksi.ksi_signo = td->td_xsig;
2922 		ksi.ksi_flags |= KSI_PTRACE;
2923 		td2 = sigtd(p, td->td_xsig, false);
2924 		tdsendsignal(p, td2, td->td_xsig, &ksi);
2925 		if (td != td2)
2926 			return (0);
2927 	}
2928 
2929 	return (td->td_xsig);
2930 }
2931 
2932 static void
2933 reschedule_signals(struct proc *p, sigset_t block, int flags)
2934 {
2935 	struct sigacts *ps;
2936 	struct thread *td;
2937 	int sig;
2938 	bool fastblk, pslocked;
2939 
2940 	PROC_LOCK_ASSERT(p, MA_OWNED);
2941 	ps = p->p_sigacts;
2942 	pslocked = (flags & SIGPROCMASK_PS_LOCKED) != 0;
2943 	mtx_assert(&ps->ps_mtx, pslocked ? MA_OWNED : MA_NOTOWNED);
2944 	if (SIGISEMPTY(p->p_siglist))
2945 		return;
2946 	SIGSETAND(block, p->p_siglist);
2947 	fastblk = (flags & SIGPROCMASK_FASTBLK) != 0;
2948 	SIG_FOREACH(sig, &block) {
2949 		td = sigtd(p, sig, fastblk);
2950 
2951 		/*
2952 		 * If sigtd() selected us despite sigfastblock is
2953 		 * blocking, do not activate AST or wake us, to avoid
2954 		 * loop in AST handler.
2955 		 */
2956 		if (fastblk && td == curthread)
2957 			continue;
2958 
2959 		signotify(td);
2960 		if (!pslocked)
2961 			mtx_lock(&ps->ps_mtx);
2962 		if (p->p_flag & P_TRACED ||
2963 		    (SIGISMEMBER(ps->ps_sigcatch, sig) &&
2964 		    !SIGISMEMBER(td->td_sigmask, sig))) {
2965 			tdsigwakeup(td, sig, SIG_CATCH,
2966 			    (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2967 			    ERESTART));
2968 		}
2969 		if (!pslocked)
2970 			mtx_unlock(&ps->ps_mtx);
2971 	}
2972 }
2973 
2974 void
2975 tdsigcleanup(struct thread *td)
2976 {
2977 	struct proc *p;
2978 	sigset_t unblocked;
2979 
2980 	p = td->td_proc;
2981 	PROC_LOCK_ASSERT(p, MA_OWNED);
2982 
2983 	sigqueue_flush(&td->td_sigqueue);
2984 	if (p->p_numthreads == 1)
2985 		return;
2986 
2987 	/*
2988 	 * Since we cannot handle signals, notify signal post code
2989 	 * about this by filling the sigmask.
2990 	 *
2991 	 * Also, if needed, wake up thread(s) that do not block the
2992 	 * same signals as the exiting thread, since the thread might
2993 	 * have been selected for delivery and woken up.
2994 	 */
2995 	SIGFILLSET(unblocked);
2996 	SIGSETNAND(unblocked, td->td_sigmask);
2997 	SIGFILLSET(td->td_sigmask);
2998 	reschedule_signals(p, unblocked, 0);
2999 
3000 }
3001 
3002 static int
3003 sigdeferstop_curr_flags(int cflags)
3004 {
3005 
3006 	MPASS((cflags & (TDF_SEINTR | TDF_SERESTART)) == 0 ||
3007 	    (cflags & TDF_SBDRY) != 0);
3008 	return (cflags & (TDF_SBDRY | TDF_SEINTR | TDF_SERESTART));
3009 }
3010 
3011 /*
3012  * Defer the delivery of SIGSTOP for the current thread, according to
3013  * the requested mode.  Returns previous flags, which must be restored
3014  * by sigallowstop().
3015  *
3016  * TDF_SBDRY, TDF_SEINTR, and TDF_SERESTART flags are only set and
3017  * cleared by the current thread, which allow the lock-less read-only
3018  * accesses below.
3019  */
3020 int
3021 sigdeferstop_impl(int mode)
3022 {
3023 	struct thread *td;
3024 	int cflags, nflags;
3025 
3026 	td = curthread;
3027 	cflags = sigdeferstop_curr_flags(td->td_flags);
3028 	switch (mode) {
3029 	case SIGDEFERSTOP_NOP:
3030 		nflags = cflags;
3031 		break;
3032 	case SIGDEFERSTOP_OFF:
3033 		nflags = 0;
3034 		break;
3035 	case SIGDEFERSTOP_SILENT:
3036 		nflags = (cflags | TDF_SBDRY) & ~(TDF_SEINTR | TDF_SERESTART);
3037 		break;
3038 	case SIGDEFERSTOP_EINTR:
3039 		nflags = (cflags | TDF_SBDRY | TDF_SEINTR) & ~TDF_SERESTART;
3040 		break;
3041 	case SIGDEFERSTOP_ERESTART:
3042 		nflags = (cflags | TDF_SBDRY | TDF_SERESTART) & ~TDF_SEINTR;
3043 		break;
3044 	default:
3045 		panic("sigdeferstop: invalid mode %x", mode);
3046 		break;
3047 	}
3048 	if (cflags == nflags)
3049 		return (SIGDEFERSTOP_VAL_NCHG);
3050 	thread_lock(td);
3051 	td->td_flags = (td->td_flags & ~cflags) | nflags;
3052 	thread_unlock(td);
3053 	return (cflags);
3054 }
3055 
3056 /*
3057  * Restores the STOP handling mode, typically permitting the delivery
3058  * of SIGSTOP for the current thread.  This does not immediately
3059  * suspend if a stop was posted.  Instead, the thread will suspend
3060  * either via ast() or a subsequent interruptible sleep.
3061  */
3062 void
3063 sigallowstop_impl(int prev)
3064 {
3065 	struct thread *td;
3066 	int cflags;
3067 
3068 	KASSERT(prev != SIGDEFERSTOP_VAL_NCHG, ("failed sigallowstop"));
3069 	KASSERT((prev & ~(TDF_SBDRY | TDF_SEINTR | TDF_SERESTART)) == 0,
3070 	    ("sigallowstop: incorrect previous mode %x", prev));
3071 	td = curthread;
3072 	cflags = sigdeferstop_curr_flags(td->td_flags);
3073 	if (cflags != prev) {
3074 		thread_lock(td);
3075 		td->td_flags = (td->td_flags & ~cflags) | prev;
3076 		thread_unlock(td);
3077 	}
3078 }
3079 
3080 enum sigstatus {
3081 	SIGSTATUS_HANDLE,
3082 	SIGSTATUS_HANDLED,
3083 	SIGSTATUS_IGNORE,
3084 	SIGSTATUS_SBDRY_STOP,
3085 };
3086 
3087 /*
3088  * The thread has signal "sig" pending.  Figure out what to do with it:
3089  *
3090  * _HANDLE     -> the caller should handle the signal
3091  * _HANDLED    -> handled internally, reload pending signal set
3092  * _IGNORE     -> ignored, remove from the set of pending signals and try the
3093  *                next pending signal
3094  * _SBDRY_STOP -> the signal should stop the thread but this is not
3095  *                permitted in the current context
3096  */
3097 static enum sigstatus
3098 sigprocess(struct thread *td, int sig)
3099 {
3100 	struct proc *p;
3101 	struct sigacts *ps;
3102 	struct sigqueue *queue;
3103 	ksiginfo_t ksi;
3104 	int prop;
3105 
3106 	KASSERT(_SIG_VALID(sig), ("%s: invalid signal %d", __func__, sig));
3107 
3108 	p = td->td_proc;
3109 	ps = p->p_sigacts;
3110 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3111 	PROC_LOCK_ASSERT(p, MA_OWNED);
3112 
3113 	/*
3114 	 * We should allow pending but ignored signals below
3115 	 * if there is sigwait() active, or P_TRACED was
3116 	 * on when they were posted.
3117 	 */
3118 	if (SIGISMEMBER(ps->ps_sigignore, sig) &&
3119 	    (p->p_flag & P_TRACED) == 0 &&
3120 	    (td->td_flags & TDF_SIGWAIT) == 0) {
3121 		return (SIGSTATUS_IGNORE);
3122 	}
3123 
3124 	/*
3125 	 * If the process is going to single-thread mode to prepare
3126 	 * for exit, there is no sense in delivering any signal
3127 	 * to usermode.  Another important consequence is that
3128 	 * msleep(..., PCATCH, ...) now is only interruptible by a
3129 	 * suspend request.
3130 	 */
3131 	if ((p->p_flag2 & P2_WEXIT) != 0)
3132 		return (SIGSTATUS_IGNORE);
3133 
3134 	if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED) {
3135 		/*
3136 		 * If traced, always stop.
3137 		 * Remove old signal from queue before the stop.
3138 		 * XXX shrug off debugger, it causes siginfo to
3139 		 * be thrown away.
3140 		 */
3141 		queue = &td->td_sigqueue;
3142 		ksiginfo_init(&ksi);
3143 		if (sigqueue_get(queue, sig, &ksi) == 0) {
3144 			queue = &p->p_sigqueue;
3145 			sigqueue_get(queue, sig, &ksi);
3146 		}
3147 		td->td_si = ksi.ksi_info;
3148 
3149 		mtx_unlock(&ps->ps_mtx);
3150 		sig = ptracestop(td, sig, &ksi);
3151 		mtx_lock(&ps->ps_mtx);
3152 
3153 		td->td_si.si_signo = 0;
3154 
3155 		/*
3156 		 * Keep looking if the debugger discarded or
3157 		 * replaced the signal.
3158 		 */
3159 		if (sig == 0)
3160 			return (SIGSTATUS_HANDLED);
3161 
3162 		/*
3163 		 * If the signal became masked, re-queue it.
3164 		 */
3165 		if (SIGISMEMBER(td->td_sigmask, sig)) {
3166 			ksi.ksi_flags |= KSI_HEAD;
3167 			sigqueue_add(&p->p_sigqueue, sig, &ksi);
3168 			return (SIGSTATUS_HANDLED);
3169 		}
3170 
3171 		/*
3172 		 * If the traced bit got turned off, requeue the signal and
3173 		 * reload the set of pending signals.  This ensures that p_sig*
3174 		 * and p_sigact are consistent.
3175 		 */
3176 		if ((p->p_flag & P_TRACED) == 0) {
3177 			if ((ksi.ksi_flags & KSI_PTRACE) == 0) {
3178 				ksi.ksi_flags |= KSI_HEAD;
3179 				sigqueue_add(queue, sig, &ksi);
3180 			}
3181 			return (SIGSTATUS_HANDLED);
3182 		}
3183 	}
3184 
3185 	/*
3186 	 * Decide whether the signal should be returned.
3187 	 * Return the signal's number, or fall through
3188 	 * to clear it from the pending mask.
3189 	 */
3190 	switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
3191 	case (intptr_t)SIG_DFL:
3192 		/*
3193 		 * Don't take default actions on system processes.
3194 		 */
3195 		if (p->p_pid <= 1) {
3196 #ifdef DIAGNOSTIC
3197 			/*
3198 			 * Are you sure you want to ignore SIGSEGV
3199 			 * in init? XXX
3200 			 */
3201 			printf("Process (pid %lu) got signal %d\n",
3202 				(u_long)p->p_pid, sig);
3203 #endif
3204 			return (SIGSTATUS_IGNORE);
3205 		}
3206 
3207 		/*
3208 		 * If there is a pending stop signal to process with
3209 		 * default action, stop here, then clear the signal.
3210 		 * Traced or exiting processes should ignore stops.
3211 		 * Additionally, a member of an orphaned process group
3212 		 * should ignore tty stops.
3213 		 */
3214 		prop = sigprop(sig);
3215 		if (prop & SIGPROP_STOP) {
3216 			mtx_unlock(&ps->ps_mtx);
3217 			if ((p->p_flag & (P_TRACED | P_WEXIT |
3218 			    P_SINGLE_EXIT)) != 0 || ((p->p_pgrp->
3219 			    pg_flags & PGRP_ORPHANED) != 0 &&
3220 			    (prop & SIGPROP_TTYSTOP) != 0)) {
3221 				mtx_lock(&ps->ps_mtx);
3222 				return (SIGSTATUS_IGNORE);
3223 			}
3224 			if (TD_SBDRY_INTR(td)) {
3225 				KASSERT((td->td_flags & TDF_SBDRY) != 0,
3226 				    ("lost TDF_SBDRY"));
3227 				mtx_lock(&ps->ps_mtx);
3228 				return (SIGSTATUS_SBDRY_STOP);
3229 			}
3230 			WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
3231 			    &p->p_mtx.lock_object, "Catching SIGSTOP");
3232 			sigqueue_delete(&td->td_sigqueue, sig);
3233 			sigqueue_delete(&p->p_sigqueue, sig);
3234 			p->p_flag |= P_STOPPED_SIG;
3235 			p->p_xsig = sig;
3236 			PROC_SLOCK(p);
3237 			sig_suspend_threads(td, p);
3238 			thread_suspend_switch(td, p);
3239 			PROC_SUNLOCK(p);
3240 			mtx_lock(&ps->ps_mtx);
3241 			return (SIGSTATUS_HANDLED);
3242 		} else if ((prop & SIGPROP_IGNORE) != 0 &&
3243 		    (td->td_flags & TDF_SIGWAIT) == 0) {
3244 			/*
3245 			 * Default action is to ignore; drop it if
3246 			 * not in kern_sigtimedwait().
3247 			 */
3248 			return (SIGSTATUS_IGNORE);
3249 		} else {
3250 			return (SIGSTATUS_HANDLE);
3251 		}
3252 
3253 	case (intptr_t)SIG_IGN:
3254 		if ((td->td_flags & TDF_SIGWAIT) == 0)
3255 			return (SIGSTATUS_IGNORE);
3256 		else
3257 			return (SIGSTATUS_HANDLE);
3258 
3259 	default:
3260 		/*
3261 		 * This signal has an action, let postsig() process it.
3262 		 */
3263 		return (SIGSTATUS_HANDLE);
3264 	}
3265 }
3266 
3267 /*
3268  * If the current process has received a signal (should be caught or cause
3269  * termination, should interrupt current syscall), return the signal number.
3270  * Stop signals with default action are processed immediately, then cleared;
3271  * they aren't returned.  This is checked after each entry to the system for
3272  * a syscall or trap (though this can usually be done without calling
3273  * issignal by checking the pending signal masks in cursig.) The normal call
3274  * sequence is
3275  *
3276  *	while (sig = cursig(curthread))
3277  *		postsig(sig);
3278  */
3279 static int
3280 issignal(struct thread *td)
3281 {
3282 	struct proc *p;
3283 	sigset_t sigpending;
3284 	int sig;
3285 
3286 	p = td->td_proc;
3287 	PROC_LOCK_ASSERT(p, MA_OWNED);
3288 
3289 	for (;;) {
3290 		sigpending = td->td_sigqueue.sq_signals;
3291 		SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
3292 		SIGSETNAND(sigpending, td->td_sigmask);
3293 
3294 		if ((p->p_flag & P_PPWAIT) != 0 || (td->td_flags &
3295 		    (TDF_SBDRY | TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
3296 			SIG_STOPSIGMASK(sigpending);
3297 		if (SIGISEMPTY(sigpending))	/* no signal to send */
3298 			return (0);
3299 
3300 		/*
3301 		 * Do fast sigblock if requested by usermode.  Since
3302 		 * we do know that there was a signal pending at this
3303 		 * point, set the FAST_SIGBLOCK_PEND as indicator for
3304 		 * usermode to perform a dummy call to
3305 		 * FAST_SIGBLOCK_UNBLOCK, which causes immediate
3306 		 * delivery of postponed pending signal.
3307 		 */
3308 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
3309 			if (td->td_sigblock_val != 0)
3310 				SIGSETNAND(sigpending, fastblock_mask);
3311 			if (SIGISEMPTY(sigpending)) {
3312 				td->td_pflags |= TDP_SIGFASTPENDING;
3313 				return (0);
3314 			}
3315 		}
3316 
3317 		if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED &&
3318 		    (p->p_flag2 & P2_PTRACE_FSTP) != 0 &&
3319 		    SIGISMEMBER(sigpending, SIGSTOP)) {
3320 			/*
3321 			 * If debugger just attached, always consume
3322 			 * SIGSTOP from ptrace(PT_ATTACH) first, to
3323 			 * execute the debugger attach ritual in
3324 			 * order.
3325 			 */
3326 			td->td_dbgflags |= TDB_FSTP;
3327 			SIGEMPTYSET(sigpending);
3328 			SIGADDSET(sigpending, SIGSTOP);
3329 		}
3330 
3331 		SIG_FOREACH(sig, &sigpending) {
3332 			switch (sigprocess(td, sig)) {
3333 			case SIGSTATUS_HANDLE:
3334 				return (sig);
3335 			case SIGSTATUS_HANDLED:
3336 				goto next;
3337 			case SIGSTATUS_IGNORE:
3338 				sigqueue_delete(&td->td_sigqueue, sig);
3339 				sigqueue_delete(&p->p_sigqueue, sig);
3340 				break;
3341 			case SIGSTATUS_SBDRY_STOP:
3342 				return (-1);
3343 			}
3344 		}
3345 next:;
3346 	}
3347 }
3348 
3349 void
3350 thread_stopped(struct proc *p)
3351 {
3352 	int n;
3353 
3354 	PROC_LOCK_ASSERT(p, MA_OWNED);
3355 	PROC_SLOCK_ASSERT(p, MA_OWNED);
3356 	n = p->p_suspcount;
3357 	if (p == curproc)
3358 		n++;
3359 	if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
3360 		PROC_SUNLOCK(p);
3361 		p->p_flag &= ~P_WAITED;
3362 		PROC_LOCK(p->p_pptr);
3363 		childproc_stopped(p, (p->p_flag & P_TRACED) ?
3364 			CLD_TRAPPED : CLD_STOPPED);
3365 		PROC_UNLOCK(p->p_pptr);
3366 		PROC_SLOCK(p);
3367 	}
3368 }
3369 
3370 /*
3371  * Take the action for the specified signal
3372  * from the current set of pending signals.
3373  */
3374 int
3375 postsig(int sig)
3376 {
3377 	struct thread *td;
3378 	struct proc *p;
3379 	struct sigacts *ps;
3380 	sig_t action;
3381 	ksiginfo_t ksi;
3382 	sigset_t returnmask;
3383 
3384 	KASSERT(sig != 0, ("postsig"));
3385 
3386 	td = curthread;
3387 	p = td->td_proc;
3388 	PROC_LOCK_ASSERT(p, MA_OWNED);
3389 	ps = p->p_sigacts;
3390 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3391 	ksiginfo_init(&ksi);
3392 	if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
3393 	    sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
3394 		return (0);
3395 	ksi.ksi_signo = sig;
3396 	if (ksi.ksi_code == SI_TIMER)
3397 		itimer_accept(p, ksi.ksi_timerid, &ksi);
3398 	action = ps->ps_sigact[_SIG_IDX(sig)];
3399 #ifdef KTRACE
3400 	if (KTRPOINT(td, KTR_PSIG))
3401 		ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
3402 		    &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
3403 #endif
3404 
3405 	if (action == SIG_DFL) {
3406 		/*
3407 		 * Default action, where the default is to kill
3408 		 * the process.  (Other cases were ignored above.)
3409 		 */
3410 		mtx_unlock(&ps->ps_mtx);
3411 		proc_td_siginfo_capture(td, &ksi.ksi_info);
3412 		sigexit(td, sig);
3413 		/* NOTREACHED */
3414 	} else {
3415 		/*
3416 		 * If we get here, the signal must be caught.
3417 		 */
3418 		KASSERT(action != SIG_IGN, ("postsig action %p", action));
3419 		KASSERT(!SIGISMEMBER(td->td_sigmask, sig),
3420 		    ("postsig action: blocked sig %d", sig));
3421 
3422 		/*
3423 		 * Set the new mask value and also defer further
3424 		 * occurrences of this signal.
3425 		 *
3426 		 * Special case: user has done a sigsuspend.  Here the
3427 		 * current mask is not of interest, but rather the
3428 		 * mask from before the sigsuspend is what we want
3429 		 * restored after the signal processing is completed.
3430 		 */
3431 		if (td->td_pflags & TDP_OLDMASK) {
3432 			returnmask = td->td_oldsigmask;
3433 			td->td_pflags &= ~TDP_OLDMASK;
3434 		} else
3435 			returnmask = td->td_sigmask;
3436 
3437 		if (p->p_sig == sig) {
3438 			p->p_sig = 0;
3439 		}
3440 		(*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
3441 		postsig_done(sig, td, ps);
3442 	}
3443 	return (1);
3444 }
3445 
3446 int
3447 sig_ast_checksusp(struct thread *td)
3448 {
3449 	struct proc *p __diagused;
3450 	int ret;
3451 
3452 	p = td->td_proc;
3453 	PROC_LOCK_ASSERT(p, MA_OWNED);
3454 
3455 	if (!td_ast_pending(td, TDA_SUSPEND))
3456 		return (0);
3457 
3458 	ret = thread_suspend_check(1);
3459 	MPASS(ret == 0 || ret == EINTR || ret == ERESTART);
3460 	return (ret);
3461 }
3462 
3463 int
3464 sig_ast_needsigchk(struct thread *td)
3465 {
3466 	struct proc *p;
3467 	struct sigacts *ps;
3468 	int ret, sig;
3469 
3470 	p = td->td_proc;
3471 	PROC_LOCK_ASSERT(p, MA_OWNED);
3472 
3473 	if (!td_ast_pending(td, TDA_SIG))
3474 		return (0);
3475 
3476 	ps = p->p_sigacts;
3477 	mtx_lock(&ps->ps_mtx);
3478 	sig = cursig(td);
3479 	if (sig == -1) {
3480 		mtx_unlock(&ps->ps_mtx);
3481 		KASSERT((td->td_flags & TDF_SBDRY) != 0, ("lost TDF_SBDRY"));
3482 		KASSERT(TD_SBDRY_INTR(td),
3483 		    ("lost TDF_SERESTART of TDF_SEINTR"));
3484 		KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
3485 		    (TDF_SEINTR | TDF_SERESTART),
3486 		    ("both TDF_SEINTR and TDF_SERESTART"));
3487 		ret = TD_SBDRY_ERRNO(td);
3488 	} else if (sig != 0) {
3489 		ret = SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR : ERESTART;
3490 		mtx_unlock(&ps->ps_mtx);
3491 	} else {
3492 		mtx_unlock(&ps->ps_mtx);
3493 		ret = 0;
3494 	}
3495 
3496 	/*
3497 	 * Do not go into sleep if this thread was the ptrace(2)
3498 	 * attach leader.  cursig() consumed SIGSTOP from PT_ATTACH,
3499 	 * but we usually act on the signal by interrupting sleep, and
3500 	 * should do that here as well.
3501 	 */
3502 	if ((td->td_dbgflags & TDB_FSTP) != 0) {
3503 		if (ret == 0)
3504 			ret = EINTR;
3505 		td->td_dbgflags &= ~TDB_FSTP;
3506 	}
3507 
3508 	return (ret);
3509 }
3510 
3511 int
3512 sig_intr(void)
3513 {
3514 	struct thread *td;
3515 	struct proc *p;
3516 	int ret;
3517 
3518 	td = curthread;
3519 	if (!td_ast_pending(td, TDA_SIG) && !td_ast_pending(td, TDA_SUSPEND))
3520 		return (0);
3521 
3522 	p = td->td_proc;
3523 
3524 	PROC_LOCK(p);
3525 	ret = sig_ast_checksusp(td);
3526 	if (ret == 0)
3527 		ret = sig_ast_needsigchk(td);
3528 	PROC_UNLOCK(p);
3529 	return (ret);
3530 }
3531 
3532 bool
3533 curproc_sigkilled(void)
3534 {
3535 	struct thread *td;
3536 	struct proc *p;
3537 	struct sigacts *ps;
3538 	bool res;
3539 
3540 	td = curthread;
3541 	if (!td_ast_pending(td, TDA_SIG))
3542 		return (false);
3543 
3544 	p = td->td_proc;
3545 	PROC_LOCK(p);
3546 	ps = p->p_sigacts;
3547 	mtx_lock(&ps->ps_mtx);
3548 	res = SIGISMEMBER(td->td_sigqueue.sq_signals, SIGKILL) ||
3549 	    SIGISMEMBER(p->p_sigqueue.sq_signals, SIGKILL);
3550 	mtx_unlock(&ps->ps_mtx);
3551 	PROC_UNLOCK(p);
3552 	return (res);
3553 }
3554 
3555 void
3556 proc_wkilled(struct proc *p)
3557 {
3558 
3559 	PROC_LOCK_ASSERT(p, MA_OWNED);
3560 	if ((p->p_flag & P_WKILLED) == 0) {
3561 		p->p_flag |= P_WKILLED;
3562 		/*
3563 		 * Notify swapper that there is a process to swap in.
3564 		 * The notification is racy, at worst it would take 10
3565 		 * seconds for the swapper process to notice.
3566 		 */
3567 		if ((p->p_flag & (P_INMEM | P_SWAPPINGIN)) == 0)
3568 			wakeup(&proc0);
3569 	}
3570 }
3571 
3572 /*
3573  * Kill the current process for stated reason.
3574  */
3575 void
3576 killproc(struct proc *p, const char *why)
3577 {
3578 
3579 	PROC_LOCK_ASSERT(p, MA_OWNED);
3580 	CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
3581 	    p->p_comm);
3582 	log(LOG_ERR, "pid %d (%s), jid %d, uid %d, was killed: %s\n",
3583 	    p->p_pid, p->p_comm, p->p_ucred->cr_prison->pr_id,
3584 	    p->p_ucred->cr_uid, why);
3585 	proc_wkilled(p);
3586 	kern_psignal(p, SIGKILL);
3587 }
3588 
3589 /*
3590  * Force the current process to exit with the specified signal, dumping core
3591  * if appropriate.  We bypass the normal tests for masked and caught signals,
3592  * allowing unrecoverable failures to terminate the process without changing
3593  * signal state.  Mark the accounting record with the signal termination.
3594  * If dumping core, save the signal number for the debugger.  Calls exit and
3595  * does not return.
3596  */
3597 void
3598 sigexit(struct thread *td, int sig)
3599 {
3600 	struct proc *p = td->td_proc;
3601 	const char *coreinfo;
3602 	int rv;
3603 
3604 	PROC_LOCK_ASSERT(p, MA_OWNED);
3605 	proc_set_p2_wexit(p);
3606 
3607 	p->p_acflag |= AXSIG;
3608 	/*
3609 	 * We must be single-threading to generate a core dump.  This
3610 	 * ensures that the registers in the core file are up-to-date.
3611 	 * Also, the ELF dump handler assumes that the thread list doesn't
3612 	 * change out from under it.
3613 	 *
3614 	 * XXX If another thread attempts to single-thread before us
3615 	 *     (e.g. via fork()), we won't get a dump at all.
3616 	 */
3617 	if ((sigprop(sig) & SIGPROP_CORE) &&
3618 	    thread_single(p, SINGLE_NO_EXIT) == 0) {
3619 		p->p_sig = sig;
3620 		/*
3621 		 * Log signals which would cause core dumps
3622 		 * (Log as LOG_INFO to appease those who don't want
3623 		 * these messages.)
3624 		 * XXX : Todo, as well as euid, write out ruid too
3625 		 * Note that coredump() drops proc lock.
3626 		 */
3627 		rv = coredump(td);
3628 		switch (rv) {
3629 		case 0:
3630 			sig |= WCOREFLAG;
3631 			coreinfo = " (core dumped)";
3632 			break;
3633 		case EFAULT:
3634 			coreinfo = " (no core dump - bad address)";
3635 			break;
3636 		case EINVAL:
3637 			coreinfo = " (no core dump - invalid argument)";
3638 			break;
3639 		case EFBIG:
3640 			coreinfo = " (no core dump - too large)";
3641 			break;
3642 		default:
3643 			coreinfo = " (no core dump - other error)";
3644 			break;
3645 		}
3646 		if (kern_logsigexit)
3647 			log(LOG_INFO,
3648 			    "pid %d (%s), jid %d, uid %d: exited on "
3649 			    "signal %d%s\n", p->p_pid, p->p_comm,
3650 			    p->p_ucred->cr_prison->pr_id,
3651 			    td->td_ucred->cr_uid,
3652 			    sig &~ WCOREFLAG, coreinfo);
3653 	} else
3654 		PROC_UNLOCK(p);
3655 	exit1(td, 0, sig);
3656 	/* NOTREACHED */
3657 }
3658 
3659 /*
3660  * Send queued SIGCHLD to parent when child process's state
3661  * is changed.
3662  */
3663 static void
3664 sigparent(struct proc *p, int reason, int status)
3665 {
3666 	PROC_LOCK_ASSERT(p, MA_OWNED);
3667 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3668 
3669 	if (p->p_ksi != NULL) {
3670 		p->p_ksi->ksi_signo  = SIGCHLD;
3671 		p->p_ksi->ksi_code   = reason;
3672 		p->p_ksi->ksi_status = status;
3673 		p->p_ksi->ksi_pid    = p->p_pid;
3674 		p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
3675 		if (KSI_ONQ(p->p_ksi))
3676 			return;
3677 	}
3678 	pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
3679 }
3680 
3681 static void
3682 childproc_jobstate(struct proc *p, int reason, int sig)
3683 {
3684 	struct sigacts *ps;
3685 
3686 	PROC_LOCK_ASSERT(p, MA_OWNED);
3687 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3688 
3689 	/*
3690 	 * Wake up parent sleeping in kern_wait(), also send
3691 	 * SIGCHLD to parent, but SIGCHLD does not guarantee
3692 	 * that parent will awake, because parent may masked
3693 	 * the signal.
3694 	 */
3695 	p->p_pptr->p_flag |= P_STATCHILD;
3696 	wakeup(p->p_pptr);
3697 
3698 	ps = p->p_pptr->p_sigacts;
3699 	mtx_lock(&ps->ps_mtx);
3700 	if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
3701 		mtx_unlock(&ps->ps_mtx);
3702 		sigparent(p, reason, sig);
3703 	} else
3704 		mtx_unlock(&ps->ps_mtx);
3705 }
3706 
3707 void
3708 childproc_stopped(struct proc *p, int reason)
3709 {
3710 
3711 	childproc_jobstate(p, reason, p->p_xsig);
3712 }
3713 
3714 void
3715 childproc_continued(struct proc *p)
3716 {
3717 	childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
3718 }
3719 
3720 void
3721 childproc_exited(struct proc *p)
3722 {
3723 	int reason, status;
3724 
3725 	if (WCOREDUMP(p->p_xsig)) {
3726 		reason = CLD_DUMPED;
3727 		status = WTERMSIG(p->p_xsig);
3728 	} else if (WIFSIGNALED(p->p_xsig)) {
3729 		reason = CLD_KILLED;
3730 		status = WTERMSIG(p->p_xsig);
3731 	} else {
3732 		reason = CLD_EXITED;
3733 		status = p->p_xexit;
3734 	}
3735 	/*
3736 	 * XXX avoid calling wakeup(p->p_pptr), the work is
3737 	 * done in exit1().
3738 	 */
3739 	sigparent(p, reason, status);
3740 }
3741 
3742 #define	MAX_NUM_CORE_FILES 100000
3743 #ifndef NUM_CORE_FILES
3744 #define	NUM_CORE_FILES 5
3745 #endif
3746 CTASSERT(NUM_CORE_FILES >= 0 && NUM_CORE_FILES <= MAX_NUM_CORE_FILES);
3747 static int num_cores = NUM_CORE_FILES;
3748 
3749 static int
3750 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3751 {
3752 	int error;
3753 	int new_val;
3754 
3755 	new_val = num_cores;
3756 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3757 	if (error != 0 || req->newptr == NULL)
3758 		return (error);
3759 	if (new_val > MAX_NUM_CORE_FILES)
3760 		new_val = MAX_NUM_CORE_FILES;
3761 	if (new_val < 0)
3762 		new_val = 0;
3763 	num_cores = new_val;
3764 	return (0);
3765 }
3766 SYSCTL_PROC(_debug, OID_AUTO, ncores,
3767     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(int),
3768     sysctl_debug_num_cores_check, "I",
3769     "Maximum number of generated process corefiles while using index format");
3770 
3771 #define	GZIP_SUFFIX	".gz"
3772 #define	ZSTD_SUFFIX	".zst"
3773 
3774 int compress_user_cores = 0;
3775 
3776 static int
3777 sysctl_compress_user_cores(SYSCTL_HANDLER_ARGS)
3778 {
3779 	int error, val;
3780 
3781 	val = compress_user_cores;
3782 	error = sysctl_handle_int(oidp, &val, 0, req);
3783 	if (error != 0 || req->newptr == NULL)
3784 		return (error);
3785 	if (val != 0 && !compressor_avail(val))
3786 		return (EINVAL);
3787 	compress_user_cores = val;
3788 	return (error);
3789 }
3790 SYSCTL_PROC(_kern, OID_AUTO, compress_user_cores,
3791     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, 0, sizeof(int),
3792     sysctl_compress_user_cores, "I",
3793     "Enable compression of user corefiles ("
3794     __XSTRING(COMPRESS_GZIP) " = gzip, "
3795     __XSTRING(COMPRESS_ZSTD) " = zstd)");
3796 
3797 int compress_user_cores_level = 6;
3798 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_level, CTLFLAG_RWTUN,
3799     &compress_user_cores_level, 0,
3800     "Corefile compression level");
3801 
3802 /*
3803  * Protect the access to corefilename[] by allproc_lock.
3804  */
3805 #define	corefilename_lock	allproc_lock
3806 
3807 static char corefilename[MAXPATHLEN] = {"%N.core"};
3808 TUNABLE_STR("kern.corefile", corefilename, sizeof(corefilename));
3809 
3810 static int
3811 sysctl_kern_corefile(SYSCTL_HANDLER_ARGS)
3812 {
3813 	int error;
3814 
3815 	sx_xlock(&corefilename_lock);
3816 	error = sysctl_handle_string(oidp, corefilename, sizeof(corefilename),
3817 	    req);
3818 	sx_xunlock(&corefilename_lock);
3819 
3820 	return (error);
3821 }
3822 SYSCTL_PROC(_kern, OID_AUTO, corefile, CTLTYPE_STRING | CTLFLAG_RW |
3823     CTLFLAG_MPSAFE, 0, 0, sysctl_kern_corefile, "A",
3824     "Process corefile name format string");
3825 
3826 static void
3827 vnode_close_locked(struct thread *td, struct vnode *vp)
3828 {
3829 
3830 	VOP_UNLOCK(vp);
3831 	vn_close(vp, FWRITE, td->td_ucred, td);
3832 }
3833 
3834 /*
3835  * If the core format has a %I in it, then we need to check
3836  * for existing corefiles before defining a name.
3837  * To do this we iterate over 0..ncores to find a
3838  * non-existing core file name to use. If all core files are
3839  * already used we choose the oldest one.
3840  */
3841 static int
3842 corefile_open_last(struct thread *td, char *name, int indexpos,
3843     int indexlen, int ncores, struct vnode **vpp)
3844 {
3845 	struct vnode *oldvp, *nextvp, *vp;
3846 	struct vattr vattr;
3847 	struct nameidata nd;
3848 	int error, i, flags, oflags, cmode;
3849 	char ch;
3850 	struct timespec lasttime;
3851 
3852 	nextvp = oldvp = NULL;
3853 	cmode = S_IRUSR | S_IWUSR;
3854 	oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3855 	    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3856 
3857 	for (i = 0; i < ncores; i++) {
3858 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
3859 
3860 		ch = name[indexpos + indexlen];
3861 		(void)snprintf(name + indexpos, indexlen + 1, "%.*u", indexlen,
3862 		    i);
3863 		name[indexpos + indexlen] = ch;
3864 
3865 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name);
3866 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3867 		    NULL);
3868 		if (error != 0)
3869 			break;
3870 
3871 		vp = nd.ni_vp;
3872 		NDFREE_PNBUF(&nd);
3873 		if ((flags & O_CREAT) == O_CREAT) {
3874 			nextvp = vp;
3875 			break;
3876 		}
3877 
3878 		error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3879 		if (error != 0) {
3880 			vnode_close_locked(td, vp);
3881 			break;
3882 		}
3883 
3884 		if (oldvp == NULL ||
3885 		    lasttime.tv_sec > vattr.va_mtime.tv_sec ||
3886 		    (lasttime.tv_sec == vattr.va_mtime.tv_sec &&
3887 		    lasttime.tv_nsec >= vattr.va_mtime.tv_nsec)) {
3888 			if (oldvp != NULL)
3889 				vn_close(oldvp, FWRITE, td->td_ucred, td);
3890 			oldvp = vp;
3891 			VOP_UNLOCK(oldvp);
3892 			lasttime = vattr.va_mtime;
3893 		} else {
3894 			vnode_close_locked(td, vp);
3895 		}
3896 	}
3897 
3898 	if (oldvp != NULL) {
3899 		if (nextvp == NULL) {
3900 			if ((td->td_proc->p_flag & P_SUGID) != 0) {
3901 				error = EFAULT;
3902 				vn_close(oldvp, FWRITE, td->td_ucred, td);
3903 			} else {
3904 				nextvp = oldvp;
3905 				error = vn_lock(nextvp, LK_EXCLUSIVE);
3906 				if (error != 0) {
3907 					vn_close(nextvp, FWRITE, td->td_ucred,
3908 					    td);
3909 					nextvp = NULL;
3910 				}
3911 			}
3912 		} else {
3913 			vn_close(oldvp, FWRITE, td->td_ucred, td);
3914 		}
3915 	}
3916 	if (error != 0) {
3917 		if (nextvp != NULL)
3918 			vnode_close_locked(td, oldvp);
3919 	} else {
3920 		*vpp = nextvp;
3921 	}
3922 
3923 	return (error);
3924 }
3925 
3926 /*
3927  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3928  * Expand the name described in corefilename, using name, uid, and pid
3929  * and open/create core file.
3930  * corefilename is a printf-like string, with three format specifiers:
3931  *	%N	name of process ("name")
3932  *	%P	process id (pid)
3933  *	%U	user id (uid)
3934  * For example, "%N.core" is the default; they can be disabled completely
3935  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3936  * This is controlled by the sysctl variable kern.corefile (see above).
3937  */
3938 static int
3939 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3940     int compress, int signum, struct vnode **vpp, char **namep)
3941 {
3942 	struct sbuf sb;
3943 	struct nameidata nd;
3944 	const char *format;
3945 	char *hostname, *name;
3946 	int cmode, error, flags, i, indexpos, indexlen, oflags, ncores;
3947 
3948 	hostname = NULL;
3949 	format = corefilename;
3950 	name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3951 	indexlen = 0;
3952 	indexpos = -1;
3953 	ncores = num_cores;
3954 	(void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3955 	sx_slock(&corefilename_lock);
3956 	for (i = 0; format[i] != '\0'; i++) {
3957 		switch (format[i]) {
3958 		case '%':	/* Format character */
3959 			i++;
3960 			switch (format[i]) {
3961 			case '%':
3962 				sbuf_putc(&sb, '%');
3963 				break;
3964 			case 'H':	/* hostname */
3965 				if (hostname == NULL) {
3966 					hostname = malloc(MAXHOSTNAMELEN,
3967 					    M_TEMP, M_WAITOK);
3968 				}
3969 				getcredhostname(td->td_ucred, hostname,
3970 				    MAXHOSTNAMELEN);
3971 				sbuf_printf(&sb, "%s", hostname);
3972 				break;
3973 			case 'I':	/* autoincrementing index */
3974 				if (indexpos != -1) {
3975 					sbuf_printf(&sb, "%%I");
3976 					break;
3977 				}
3978 
3979 				indexpos = sbuf_len(&sb);
3980 				sbuf_printf(&sb, "%u", ncores - 1);
3981 				indexlen = sbuf_len(&sb) - indexpos;
3982 				break;
3983 			case 'N':	/* process name */
3984 				sbuf_printf(&sb, "%s", comm);
3985 				break;
3986 			case 'P':	/* process id */
3987 				sbuf_printf(&sb, "%u", pid);
3988 				break;
3989 			case 'S':	/* signal number */
3990 				sbuf_printf(&sb, "%i", signum);
3991 				break;
3992 			case 'U':	/* user id */
3993 				sbuf_printf(&sb, "%u", uid);
3994 				break;
3995 			default:
3996 				log(LOG_ERR,
3997 				    "Unknown format character %c in "
3998 				    "corename `%s'\n", format[i], format);
3999 				break;
4000 			}
4001 			break;
4002 		default:
4003 			sbuf_putc(&sb, format[i]);
4004 			break;
4005 		}
4006 	}
4007 	sx_sunlock(&corefilename_lock);
4008 	free(hostname, M_TEMP);
4009 	if (compress == COMPRESS_GZIP)
4010 		sbuf_printf(&sb, GZIP_SUFFIX);
4011 	else if (compress == COMPRESS_ZSTD)
4012 		sbuf_printf(&sb, ZSTD_SUFFIX);
4013 	if (sbuf_error(&sb) != 0) {
4014 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
4015 		    "long\n", (long)pid, comm, (u_long)uid);
4016 		sbuf_delete(&sb);
4017 		free(name, M_TEMP);
4018 		return (ENOMEM);
4019 	}
4020 	sbuf_finish(&sb);
4021 	sbuf_delete(&sb);
4022 
4023 	if (indexpos != -1) {
4024 		error = corefile_open_last(td, name, indexpos, indexlen, ncores,
4025 		    vpp);
4026 		if (error != 0) {
4027 			log(LOG_ERR,
4028 			    "pid %d (%s), uid (%u):  Path `%s' failed "
4029 			    "on initial open test, error = %d\n",
4030 			    pid, comm, uid, name, error);
4031 		}
4032 	} else {
4033 		cmode = S_IRUSR | S_IWUSR;
4034 		oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
4035 		    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
4036 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
4037 		if ((td->td_proc->p_flag & P_SUGID) != 0)
4038 			flags |= O_EXCL;
4039 
4040 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name);
4041 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
4042 		    NULL);
4043 		if (error == 0) {
4044 			*vpp = nd.ni_vp;
4045 			NDFREE_PNBUF(&nd);
4046 		}
4047 	}
4048 
4049 	if (error != 0) {
4050 #ifdef AUDIT
4051 		audit_proc_coredump(td, name, error);
4052 #endif
4053 		free(name, M_TEMP);
4054 		return (error);
4055 	}
4056 	*namep = name;
4057 	return (0);
4058 }
4059 
4060 /*
4061  * Dump a process' core.  The main routine does some
4062  * policy checking, and creates the name of the coredump;
4063  * then it passes on a vnode and a size limit to the process-specific
4064  * coredump routine if there is one; if there _is not_ one, it returns
4065  * ENOSYS; otherwise it returns the error from the process-specific routine.
4066  */
4067 
4068 static int
4069 coredump(struct thread *td)
4070 {
4071 	struct proc *p = td->td_proc;
4072 	struct ucred *cred = td->td_ucred;
4073 	struct vnode *vp;
4074 	struct flock lf;
4075 	struct vattr vattr;
4076 	size_t fullpathsize;
4077 	int error, error1, locked;
4078 	char *name;			/* name of corefile */
4079 	void *rl_cookie;
4080 	off_t limit;
4081 	char *fullpath, *freepath = NULL;
4082 	struct sbuf *sb;
4083 
4084 	PROC_LOCK_ASSERT(p, MA_OWNED);
4085 	MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
4086 
4087 	if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0) ||
4088 	    (p->p_flag2 & P2_NOTRACE) != 0) {
4089 		PROC_UNLOCK(p);
4090 		return (EFAULT);
4091 	}
4092 
4093 	/*
4094 	 * Note that the bulk of limit checking is done after
4095 	 * the corefile is created.  The exception is if the limit
4096 	 * for corefiles is 0, in which case we don't bother
4097 	 * creating the corefile at all.  This layout means that
4098 	 * a corefile is truncated instead of not being created,
4099 	 * if it is larger than the limit.
4100 	 */
4101 	limit = (off_t)lim_cur(td, RLIMIT_CORE);
4102 	if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
4103 		PROC_UNLOCK(p);
4104 		return (EFBIG);
4105 	}
4106 	PROC_UNLOCK(p);
4107 
4108 	error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td,
4109 	    compress_user_cores, p->p_sig, &vp, &name);
4110 	if (error != 0)
4111 		return (error);
4112 
4113 	/*
4114 	 * Don't dump to non-regular files or files with links.
4115 	 * Do not dump into system files. Effective user must own the corefile.
4116 	 */
4117 	if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
4118 	    vattr.va_nlink != 1 || (vp->v_vflag & VV_SYSTEM) != 0 ||
4119 	    vattr.va_uid != cred->cr_uid) {
4120 		VOP_UNLOCK(vp);
4121 		error = EFAULT;
4122 		goto out;
4123 	}
4124 
4125 	VOP_UNLOCK(vp);
4126 
4127 	/* Postpone other writers, including core dumps of other processes. */
4128 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
4129 
4130 	lf.l_whence = SEEK_SET;
4131 	lf.l_start = 0;
4132 	lf.l_len = 0;
4133 	lf.l_type = F_WRLCK;
4134 	locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
4135 
4136 	VATTR_NULL(&vattr);
4137 	vattr.va_size = 0;
4138 	if (set_core_nodump_flag)
4139 		vattr.va_flags = UF_NODUMP;
4140 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4141 	VOP_SETATTR(vp, &vattr, cred);
4142 	VOP_UNLOCK(vp);
4143 	PROC_LOCK(p);
4144 	p->p_acflag |= ACORE;
4145 	PROC_UNLOCK(p);
4146 
4147 	if (p->p_sysent->sv_coredump != NULL) {
4148 		error = p->p_sysent->sv_coredump(td, vp, limit, 0);
4149 	} else {
4150 		error = ENOSYS;
4151 	}
4152 
4153 	if (locked) {
4154 		lf.l_type = F_UNLCK;
4155 		VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
4156 	}
4157 	vn_rangelock_unlock(vp, rl_cookie);
4158 
4159 	/*
4160 	 * Notify the userland helper that a process triggered a core dump.
4161 	 * This allows the helper to run an automated debugging session.
4162 	 */
4163 	if (error != 0 || coredump_devctl == 0)
4164 		goto out;
4165 	sb = sbuf_new_auto();
4166 	if (vn_fullpath_global(p->p_textvp, &fullpath, &freepath) != 0)
4167 		goto out2;
4168 	sbuf_printf(sb, "comm=\"");
4169 	devctl_safe_quote_sb(sb, fullpath);
4170 	free(freepath, M_TEMP);
4171 	sbuf_printf(sb, "\" core=\"");
4172 
4173 	/*
4174 	 * We can't lookup core file vp directly. When we're replacing a core, and
4175 	 * other random times, we flush the name cache, so it will fail. Instead,
4176 	 * if the path of the core is relative, add the current dir in front if it.
4177 	 */
4178 	if (name[0] != '/') {
4179 		fullpathsize = MAXPATHLEN;
4180 		freepath = malloc(fullpathsize, M_TEMP, M_WAITOK);
4181 		if (vn_getcwd(freepath, &fullpath, &fullpathsize) != 0) {
4182 			free(freepath, M_TEMP);
4183 			goto out2;
4184 		}
4185 		devctl_safe_quote_sb(sb, fullpath);
4186 		free(freepath, M_TEMP);
4187 		sbuf_putc(sb, '/');
4188 	}
4189 	devctl_safe_quote_sb(sb, name);
4190 	sbuf_printf(sb, "\"");
4191 	if (sbuf_finish(sb) == 0)
4192 		devctl_notify("kernel", "signal", "coredump", sbuf_data(sb));
4193 out2:
4194 	sbuf_delete(sb);
4195 out:
4196 	error1 = vn_close(vp, FWRITE, cred, td);
4197 	if (error == 0)
4198 		error = error1;
4199 #ifdef AUDIT
4200 	audit_proc_coredump(td, name, error);
4201 #endif
4202 	free(name, M_TEMP);
4203 	return (error);
4204 }
4205 
4206 /*
4207  * Nonexistent system call-- signal process (may want to handle it).  Flag
4208  * error in case process won't see signal immediately (blocked or ignored).
4209  */
4210 #ifndef _SYS_SYSPROTO_H_
4211 struct nosys_args {
4212 	int	dummy;
4213 };
4214 #endif
4215 /* ARGSUSED */
4216 int
4217 nosys(struct thread *td, struct nosys_args *args)
4218 {
4219 	struct proc *p;
4220 
4221 	p = td->td_proc;
4222 
4223 	PROC_LOCK(p);
4224 	tdsignal(td, SIGSYS);
4225 	PROC_UNLOCK(p);
4226 	if (kern_lognosys == 1 || kern_lognosys == 3) {
4227 		uprintf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
4228 		    td->td_sa.code);
4229 	}
4230 	if (kern_lognosys == 2 || kern_lognosys == 3 ||
4231 	    (p->p_pid == 1 && (kern_lognosys & 3) == 0)) {
4232 		printf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
4233 		    td->td_sa.code);
4234 	}
4235 	return (ENOSYS);
4236 }
4237 
4238 /*
4239  * Send a SIGIO or SIGURG signal to a process or process group using stored
4240  * credentials rather than those of the current process.
4241  */
4242 void
4243 pgsigio(struct sigio **sigiop, int sig, int checkctty)
4244 {
4245 	ksiginfo_t ksi;
4246 	struct sigio *sigio;
4247 
4248 	ksiginfo_init(&ksi);
4249 	ksi.ksi_signo = sig;
4250 	ksi.ksi_code = SI_KERNEL;
4251 
4252 	SIGIO_LOCK();
4253 	sigio = *sigiop;
4254 	if (sigio == NULL) {
4255 		SIGIO_UNLOCK();
4256 		return;
4257 	}
4258 	if (sigio->sio_pgid > 0) {
4259 		PROC_LOCK(sigio->sio_proc);
4260 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
4261 			kern_psignal(sigio->sio_proc, sig);
4262 		PROC_UNLOCK(sigio->sio_proc);
4263 	} else if (sigio->sio_pgid < 0) {
4264 		struct proc *p;
4265 
4266 		PGRP_LOCK(sigio->sio_pgrp);
4267 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
4268 			PROC_LOCK(p);
4269 			if (p->p_state == PRS_NORMAL &&
4270 			    CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
4271 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
4272 				kern_psignal(p, sig);
4273 			PROC_UNLOCK(p);
4274 		}
4275 		PGRP_UNLOCK(sigio->sio_pgrp);
4276 	}
4277 	SIGIO_UNLOCK();
4278 }
4279 
4280 static int
4281 filt_sigattach(struct knote *kn)
4282 {
4283 	struct proc *p = curproc;
4284 
4285 	kn->kn_ptr.p_proc = p;
4286 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
4287 
4288 	knlist_add(p->p_klist, kn, 0);
4289 
4290 	return (0);
4291 }
4292 
4293 static void
4294 filt_sigdetach(struct knote *kn)
4295 {
4296 	struct proc *p = kn->kn_ptr.p_proc;
4297 
4298 	knlist_remove(p->p_klist, kn, 0);
4299 }
4300 
4301 /*
4302  * signal knotes are shared with proc knotes, so we apply a mask to
4303  * the hint in order to differentiate them from process hints.  This
4304  * could be avoided by using a signal-specific knote list, but probably
4305  * isn't worth the trouble.
4306  */
4307 static int
4308 filt_signal(struct knote *kn, long hint)
4309 {
4310 
4311 	if (hint & NOTE_SIGNAL) {
4312 		hint &= ~NOTE_SIGNAL;
4313 
4314 		if (kn->kn_id == hint)
4315 			kn->kn_data++;
4316 	}
4317 	return (kn->kn_data != 0);
4318 }
4319 
4320 struct sigacts *
4321 sigacts_alloc(void)
4322 {
4323 	struct sigacts *ps;
4324 
4325 	ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
4326 	refcount_init(&ps->ps_refcnt, 1);
4327 	mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
4328 	return (ps);
4329 }
4330 
4331 void
4332 sigacts_free(struct sigacts *ps)
4333 {
4334 
4335 	if (refcount_release(&ps->ps_refcnt) == 0)
4336 		return;
4337 	mtx_destroy(&ps->ps_mtx);
4338 	free(ps, M_SUBPROC);
4339 }
4340 
4341 struct sigacts *
4342 sigacts_hold(struct sigacts *ps)
4343 {
4344 
4345 	refcount_acquire(&ps->ps_refcnt);
4346 	return (ps);
4347 }
4348 
4349 void
4350 sigacts_copy(struct sigacts *dest, struct sigacts *src)
4351 {
4352 
4353 	KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
4354 	mtx_lock(&src->ps_mtx);
4355 	bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
4356 	mtx_unlock(&src->ps_mtx);
4357 }
4358 
4359 int
4360 sigacts_shared(struct sigacts *ps)
4361 {
4362 
4363 	return (ps->ps_refcnt > 1);
4364 }
4365 
4366 void
4367 sig_drop_caught(struct proc *p)
4368 {
4369 	int sig;
4370 	struct sigacts *ps;
4371 
4372 	ps = p->p_sigacts;
4373 	PROC_LOCK_ASSERT(p, MA_OWNED);
4374 	mtx_assert(&ps->ps_mtx, MA_OWNED);
4375 	SIG_FOREACH(sig, &ps->ps_sigcatch) {
4376 		sigdflt(ps, sig);
4377 		if ((sigprop(sig) & SIGPROP_IGNORE) != 0)
4378 			sigqueue_delete_proc(p, sig);
4379 	}
4380 }
4381 
4382 static void
4383 sigfastblock_failed(struct thread *td, bool sendsig, bool write)
4384 {
4385 	ksiginfo_t ksi;
4386 
4387 	/*
4388 	 * Prevent further fetches and SIGSEGVs, allowing thread to
4389 	 * issue syscalls despite corruption.
4390 	 */
4391 	sigfastblock_clear(td);
4392 
4393 	if (!sendsig)
4394 		return;
4395 	ksiginfo_init_trap(&ksi);
4396 	ksi.ksi_signo = SIGSEGV;
4397 	ksi.ksi_code = write ? SEGV_ACCERR : SEGV_MAPERR;
4398 	ksi.ksi_addr = td->td_sigblock_ptr;
4399 	trapsignal(td, &ksi);
4400 }
4401 
4402 static bool
4403 sigfastblock_fetch_sig(struct thread *td, bool sendsig, uint32_t *valp)
4404 {
4405 	uint32_t res;
4406 
4407 	if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4408 		return (true);
4409 	if (fueword32((void *)td->td_sigblock_ptr, &res) == -1) {
4410 		sigfastblock_failed(td, sendsig, false);
4411 		return (false);
4412 	}
4413 	*valp = res;
4414 	td->td_sigblock_val = res & ~SIGFASTBLOCK_FLAGS;
4415 	return (true);
4416 }
4417 
4418 static void
4419 sigfastblock_resched(struct thread *td, bool resched)
4420 {
4421 	struct proc *p;
4422 
4423 	if (resched) {
4424 		p = td->td_proc;
4425 		PROC_LOCK(p);
4426 		reschedule_signals(p, td->td_sigmask, 0);
4427 		PROC_UNLOCK(p);
4428 	}
4429 	ast_sched(td, TDA_SIG);
4430 }
4431 
4432 int
4433 sys_sigfastblock(struct thread *td, struct sigfastblock_args *uap)
4434 {
4435 	struct proc *p;
4436 	int error, res;
4437 	uint32_t oldval;
4438 
4439 	error = 0;
4440 	p = td->td_proc;
4441 	switch (uap->cmd) {
4442 	case SIGFASTBLOCK_SETPTR:
4443 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
4444 			error = EBUSY;
4445 			break;
4446 		}
4447 		if (((uintptr_t)(uap->ptr) & (sizeof(uint32_t) - 1)) != 0) {
4448 			error = EINVAL;
4449 			break;
4450 		}
4451 		td->td_pflags |= TDP_SIGFASTBLOCK;
4452 		td->td_sigblock_ptr = uap->ptr;
4453 		break;
4454 
4455 	case SIGFASTBLOCK_UNBLOCK:
4456 		if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4457 			error = EINVAL;
4458 			break;
4459 		}
4460 
4461 		for (;;) {
4462 			res = casueword32(td->td_sigblock_ptr,
4463 			    SIGFASTBLOCK_PEND, &oldval, 0);
4464 			if (res == -1) {
4465 				error = EFAULT;
4466 				sigfastblock_failed(td, false, true);
4467 				break;
4468 			}
4469 			if (res == 0)
4470 				break;
4471 			MPASS(res == 1);
4472 			if (oldval != SIGFASTBLOCK_PEND) {
4473 				error = EBUSY;
4474 				break;
4475 			}
4476 			error = thread_check_susp(td, false);
4477 			if (error != 0)
4478 				break;
4479 		}
4480 		if (error != 0)
4481 			break;
4482 
4483 		/*
4484 		 * td_sigblock_val is cleared there, but not on a
4485 		 * syscall exit.  The end effect is that a single
4486 		 * interruptible sleep, while user sigblock word is
4487 		 * set, might return EINTR or ERESTART to usermode
4488 		 * without delivering signal.  All further sleeps,
4489 		 * until userspace clears the word and does
4490 		 * sigfastblock(UNBLOCK), observe current word and no
4491 		 * longer get interrupted.  It is slight
4492 		 * non-conformance, with alternative to have read the
4493 		 * sigblock word on each syscall entry.
4494 		 */
4495 		td->td_sigblock_val = 0;
4496 
4497 		/*
4498 		 * Rely on normal ast mechanism to deliver pending
4499 		 * signals to current thread.  But notify others about
4500 		 * fake unblock.
4501 		 */
4502 		sigfastblock_resched(td, error == 0 && p->p_numthreads != 1);
4503 
4504 		break;
4505 
4506 	case SIGFASTBLOCK_UNSETPTR:
4507 		if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4508 			error = EINVAL;
4509 			break;
4510 		}
4511 		if (!sigfastblock_fetch_sig(td, false, &oldval)) {
4512 			error = EFAULT;
4513 			break;
4514 		}
4515 		if (oldval != 0 && oldval != SIGFASTBLOCK_PEND) {
4516 			error = EBUSY;
4517 			break;
4518 		}
4519 		sigfastblock_clear(td);
4520 		break;
4521 
4522 	default:
4523 		error = EINVAL;
4524 		break;
4525 	}
4526 	return (error);
4527 }
4528 
4529 void
4530 sigfastblock_clear(struct thread *td)
4531 {
4532 	bool resched;
4533 
4534 	if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4535 		return;
4536 	td->td_sigblock_val = 0;
4537 	resched = (td->td_pflags & TDP_SIGFASTPENDING) != 0 ||
4538 	    SIGPENDING(td);
4539 	td->td_pflags &= ~(TDP_SIGFASTBLOCK | TDP_SIGFASTPENDING);
4540 	sigfastblock_resched(td, resched);
4541 }
4542 
4543 void
4544 sigfastblock_fetch(struct thread *td)
4545 {
4546 	uint32_t val;
4547 
4548 	(void)sigfastblock_fetch_sig(td, true, &val);
4549 }
4550 
4551 static void
4552 sigfastblock_setpend1(struct thread *td)
4553 {
4554 	int res;
4555 	uint32_t oldval;
4556 
4557 	if ((td->td_pflags & TDP_SIGFASTPENDING) == 0)
4558 		return;
4559 	res = fueword32((void *)td->td_sigblock_ptr, &oldval);
4560 	if (res == -1) {
4561 		sigfastblock_failed(td, true, false);
4562 		return;
4563 	}
4564 	for (;;) {
4565 		res = casueword32(td->td_sigblock_ptr, oldval, &oldval,
4566 		    oldval | SIGFASTBLOCK_PEND);
4567 		if (res == -1) {
4568 			sigfastblock_failed(td, true, true);
4569 			return;
4570 		}
4571 		if (res == 0) {
4572 			td->td_sigblock_val = oldval & ~SIGFASTBLOCK_FLAGS;
4573 			td->td_pflags &= ~TDP_SIGFASTPENDING;
4574 			break;
4575 		}
4576 		MPASS(res == 1);
4577 		if (thread_check_susp(td, false) != 0)
4578 			break;
4579 	}
4580 }
4581 
4582 static void
4583 sigfastblock_setpend(struct thread *td, bool resched)
4584 {
4585 	struct proc *p;
4586 
4587 	sigfastblock_setpend1(td);
4588 	if (resched) {
4589 		p = td->td_proc;
4590 		PROC_LOCK(p);
4591 		reschedule_signals(p, fastblock_mask, SIGPROCMASK_FASTBLK);
4592 		PROC_UNLOCK(p);
4593 	}
4594 }
4595