xref: /freebsd/sys/kern/kern_sig.c (revision e1e636193db45630c7881246d25902e57c43d24e)
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 
37 #include <sys/cdefs.h>
38 #include "opt_capsicum.h"
39 #include "opt_ktrace.h"
40 
41 #include <sys/param.h>
42 #include <sys/capsicum.h>
43 #include <sys/ctype.h>
44 #include <sys/systm.h>
45 #include <sys/signalvar.h>
46 #include <sys/vnode.h>
47 #include <sys/acct.h>
48 #include <sys/capsicum.h>
49 #include <sys/compressor.h>
50 #include <sys/condvar.h>
51 #include <sys/devctl.h>
52 #include <sys/event.h>
53 #include <sys/fcntl.h>
54 #include <sys/imgact.h>
55 #include <sys/jail.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/ktrace.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mutex.h>
63 #include <sys/refcount.h>
64 #include <sys/namei.h>
65 #include <sys/proc.h>
66 #include <sys/procdesc.h>
67 #include <sys/ptrace.h>
68 #include <sys/posix4.h>
69 #include <sys/racct.h>
70 #include <sys/resourcevar.h>
71 #include <sys/sdt.h>
72 #include <sys/sbuf.h>
73 #include <sys/sleepqueue.h>
74 #include <sys/smp.h>
75 #include <sys/stat.h>
76 #include <sys/sx.h>
77 #include <sys/syscall.h>
78 #include <sys/syscallsubr.h>
79 #include <sys/sysctl.h>
80 #include <sys/sysent.h>
81 #include <sys/syslog.h>
82 #include <sys/sysproto.h>
83 #include <sys/timers.h>
84 #include <sys/unistd.h>
85 #include <sys/vmmeter.h>
86 #include <sys/wait.h>
87 #include <vm/vm.h>
88 #include <vm/vm_extern.h>
89 #include <vm/uma.h>
90 
91 #include <machine/cpu.h>
92 
93 #include <security/audit/audit.h>
94 
95 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
96 
97 SDT_PROVIDER_DECLARE(proc);
98 SDT_PROBE_DEFINE3(proc, , , signal__send,
99     "struct thread *", "struct proc *", "int");
100 SDT_PROBE_DEFINE2(proc, , , signal__clear,
101     "int", "ksiginfo_t *");
102 SDT_PROBE_DEFINE3(proc, , , signal__discard,
103     "struct thread *", "struct proc *", "int");
104 
105 static int	coredump(struct thread *);
106 static int	killpg1(struct thread *td, int sig, int pgid, int all,
107 		    ksiginfo_t *ksi);
108 static int	issignal(struct thread *td);
109 static void	reschedule_signals(struct proc *p, sigset_t block, int flags);
110 static int	sigprop(int sig);
111 static void	tdsigwakeup(struct thread *, int, sig_t, int);
112 static int	sig_suspend_threads(struct thread *, struct proc *);
113 static int	filt_sigattach(struct knote *kn);
114 static void	filt_sigdetach(struct knote *kn);
115 static int	filt_signal(struct knote *kn, long hint);
116 static struct thread *sigtd(struct proc *p, int sig, bool fast_sigblock);
117 static void	sigqueue_start(void);
118 static void	sigfastblock_setpend(struct thread *td, bool resched);
119 
120 static uma_zone_t	ksiginfo_zone = NULL;
121 struct filterops sig_filtops = {
122 	.f_isfd = 0,
123 	.f_attach = filt_sigattach,
124 	.f_detach = filt_sigdetach,
125 	.f_event = filt_signal,
126 };
127 
128 static int	kern_logsigexit = 1;
129 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
130     &kern_logsigexit, 0,
131     "Log processes quitting on abnormal signals to syslog(3)");
132 
133 static int	kern_forcesigexit = 1;
134 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
135     &kern_forcesigexit, 0, "Force trap signal to be handled");
136 
137 static SYSCTL_NODE(_kern, OID_AUTO, sigqueue, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
138     "POSIX real time signal");
139 
140 static int	max_pending_per_proc = 128;
141 SYSCTL_INT(_kern_sigqueue, OID_AUTO, max_pending_per_proc, CTLFLAG_RW,
142     &max_pending_per_proc, 0, "Max pending signals per proc");
143 
144 static int	preallocate_siginfo = 1024;
145 SYSCTL_INT(_kern_sigqueue, OID_AUTO, preallocate, CTLFLAG_RDTUN,
146     &preallocate_siginfo, 0, "Preallocated signal memory size");
147 
148 static int	signal_overflow = 0;
149 SYSCTL_INT(_kern_sigqueue, OID_AUTO, overflow, CTLFLAG_RD,
150     &signal_overflow, 0, "Number of signals overflew");
151 
152 static int	signal_alloc_fail = 0;
153 SYSCTL_INT(_kern_sigqueue, OID_AUTO, alloc_fail, CTLFLAG_RD,
154     &signal_alloc_fail, 0, "signals failed to be allocated");
155 
156 static int	kern_lognosys = 0;
157 SYSCTL_INT(_kern, OID_AUTO, lognosys, CTLFLAG_RWTUN, &kern_lognosys, 0,
158     "Log invalid syscalls");
159 
160 static int	kern_signosys = 1;
161 SYSCTL_INT(_kern, OID_AUTO, signosys, CTLFLAG_RWTUN, &kern_signosys, 0,
162     "Send SIGSYS on return from invalid syscall");
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 (pid != td->td_proc->p_pid) {
1910 		if (CAP_TRACING(td))
1911 			ktrcapfail(CAPFAIL_SIGNAL, &signum);
1912 		if (IN_CAPABILITY_MODE(td))
1913 			return (ECAPMODE);
1914 	}
1915 
1916 	AUDIT_ARG_SIGNUM(signum);
1917 	AUDIT_ARG_PID(pid);
1918 	if ((u_int)signum > _SIG_MAXSIG)
1919 		return (EINVAL);
1920 
1921 	ksiginfo_init(&ksi);
1922 	ksi.ksi_signo = signum;
1923 	ksi.ksi_code = SI_USER;
1924 	ksi.ksi_pid = td->td_proc->p_pid;
1925 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1926 
1927 	if (pid > 0) {
1928 		/* kill single process */
1929 		if ((p = pfind_any(pid)) == NULL)
1930 			return (ESRCH);
1931 		AUDIT_ARG_PROCESS(p);
1932 		error = p_cansignal(td, p, signum);
1933 		if (error == 0 && signum)
1934 			pksignal(p, signum, &ksi);
1935 		PROC_UNLOCK(p);
1936 		return (error);
1937 	}
1938 	switch (pid) {
1939 	case -1:		/* broadcast signal */
1940 		return (killpg1(td, signum, 0, 1, &ksi));
1941 	case 0:			/* signal own process group */
1942 		return (killpg1(td, signum, 0, 0, &ksi));
1943 	default:		/* negative explicit process group */
1944 		return (killpg1(td, signum, -pid, 0, &ksi));
1945 	}
1946 	/* NOTREACHED */
1947 }
1948 
1949 int
1950 sys_pdkill(struct thread *td, struct pdkill_args *uap)
1951 {
1952 	struct proc *p;
1953 	int error;
1954 
1955 	AUDIT_ARG_SIGNUM(uap->signum);
1956 	AUDIT_ARG_FD(uap->fd);
1957 	if ((u_int)uap->signum > _SIG_MAXSIG)
1958 		return (EINVAL);
1959 
1960 	error = procdesc_find(td, uap->fd, &cap_pdkill_rights, &p);
1961 	if (error)
1962 		return (error);
1963 	AUDIT_ARG_PROCESS(p);
1964 	error = p_cansignal(td, p, uap->signum);
1965 	if (error == 0 && uap->signum)
1966 		kern_psignal(p, uap->signum);
1967 	PROC_UNLOCK(p);
1968 	return (error);
1969 }
1970 
1971 #if defined(COMPAT_43)
1972 #ifndef _SYS_SYSPROTO_H_
1973 struct okillpg_args {
1974 	int	pgid;
1975 	int	signum;
1976 };
1977 #endif
1978 /* ARGSUSED */
1979 int
1980 okillpg(struct thread *td, struct okillpg_args *uap)
1981 {
1982 	ksiginfo_t ksi;
1983 
1984 	AUDIT_ARG_SIGNUM(uap->signum);
1985 	AUDIT_ARG_PID(uap->pgid);
1986 	if ((u_int)uap->signum > _SIG_MAXSIG)
1987 		return (EINVAL);
1988 
1989 	ksiginfo_init(&ksi);
1990 	ksi.ksi_signo = uap->signum;
1991 	ksi.ksi_code = SI_USER;
1992 	ksi.ksi_pid = td->td_proc->p_pid;
1993 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1994 	return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1995 }
1996 #endif /* COMPAT_43 */
1997 
1998 #ifndef _SYS_SYSPROTO_H_
1999 struct sigqueue_args {
2000 	pid_t pid;
2001 	int signum;
2002 	/* union sigval */ void *value;
2003 };
2004 #endif
2005 int
2006 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
2007 {
2008 	union sigval sv;
2009 
2010 	sv.sival_ptr = uap->value;
2011 
2012 	return (kern_sigqueue(td, uap->pid, uap->signum, &sv));
2013 }
2014 
2015 int
2016 kern_sigqueue(struct thread *td, pid_t pid, int signum, union sigval *value)
2017 {
2018 	ksiginfo_t ksi;
2019 	struct proc *p;
2020 	int error;
2021 
2022 	if ((u_int)signum > _SIG_MAXSIG)
2023 		return (EINVAL);
2024 
2025 	/*
2026 	 * Specification says sigqueue can only send signal to
2027 	 * single process.
2028 	 */
2029 	if (pid <= 0)
2030 		return (EINVAL);
2031 
2032 	if ((p = pfind_any(pid)) == NULL)
2033 		return (ESRCH);
2034 	error = p_cansignal(td, p, signum);
2035 	if (error == 0 && signum != 0) {
2036 		ksiginfo_init(&ksi);
2037 		ksi.ksi_flags = KSI_SIGQ;
2038 		ksi.ksi_signo = signum;
2039 		ksi.ksi_code = SI_QUEUE;
2040 		ksi.ksi_pid = td->td_proc->p_pid;
2041 		ksi.ksi_uid = td->td_ucred->cr_ruid;
2042 		ksi.ksi_value = *value;
2043 		error = pksignal(p, ksi.ksi_signo, &ksi);
2044 	}
2045 	PROC_UNLOCK(p);
2046 	return (error);
2047 }
2048 
2049 /*
2050  * Send a signal to a process group.  If checktty is 1,
2051  * limit to members which have a controlling terminal.
2052  */
2053 void
2054 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
2055 {
2056 	struct proc *p;
2057 
2058 	if (pgrp) {
2059 		PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
2060 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
2061 			PROC_LOCK(p);
2062 			if (p->p_state == PRS_NORMAL &&
2063 			    (checkctty == 0 || p->p_flag & P_CONTROLT))
2064 				pksignal(p, sig, ksi);
2065 			PROC_UNLOCK(p);
2066 		}
2067 	}
2068 }
2069 
2070 /*
2071  * Recalculate the signal mask and reset the signal disposition after
2072  * usermode frame for delivery is formed.  Should be called after
2073  * mach-specific routine, because sysent->sv_sendsig() needs correct
2074  * ps_siginfo and signal mask.
2075  */
2076 static void
2077 postsig_done(int sig, struct thread *td, struct sigacts *ps)
2078 {
2079 	sigset_t mask;
2080 
2081 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2082 	td->td_ru.ru_nsignals++;
2083 	mask = ps->ps_catchmask[_SIG_IDX(sig)];
2084 	if (!SIGISMEMBER(ps->ps_signodefer, sig))
2085 		SIGADDSET(mask, sig);
2086 	kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
2087 	    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
2088 	if (SIGISMEMBER(ps->ps_sigreset, sig))
2089 		sigdflt(ps, sig);
2090 }
2091 
2092 /*
2093  * Send a signal caused by a trap to the current thread.  If it will be
2094  * caught immediately, deliver it with correct code.  Otherwise, post it
2095  * normally.
2096  */
2097 void
2098 trapsignal(struct thread *td, ksiginfo_t *ksi)
2099 {
2100 	struct sigacts *ps;
2101 	struct proc *p;
2102 	sigset_t sigmask;
2103 	int sig;
2104 
2105 	p = td->td_proc;
2106 	sig = ksi->ksi_signo;
2107 	KASSERT(_SIG_VALID(sig), ("invalid signal"));
2108 
2109 	sigfastblock_fetch(td);
2110 	PROC_LOCK(p);
2111 	ps = p->p_sigacts;
2112 	mtx_lock(&ps->ps_mtx);
2113 	sigmask = td->td_sigmask;
2114 	if (td->td_sigblock_val != 0)
2115 		SIGSETOR(sigmask, fastblock_mask);
2116 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
2117 	    !SIGISMEMBER(sigmask, sig)) {
2118 #ifdef KTRACE
2119 		if (KTRPOINT(curthread, KTR_PSIG))
2120 			ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
2121 			    &td->td_sigmask, ksi->ksi_code);
2122 #endif
2123 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
2124 		    ksi, &td->td_sigmask);
2125 		postsig_done(sig, td, ps);
2126 		mtx_unlock(&ps->ps_mtx);
2127 	} else {
2128 		/*
2129 		 * Avoid a possible infinite loop if the thread
2130 		 * masking the signal or process is ignoring the
2131 		 * signal.
2132 		 */
2133 		if (kern_forcesigexit && (SIGISMEMBER(sigmask, sig) ||
2134 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
2135 			SIGDELSET(td->td_sigmask, sig);
2136 			SIGDELSET(ps->ps_sigcatch, sig);
2137 			SIGDELSET(ps->ps_sigignore, sig);
2138 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2139 			td->td_pflags &= ~TDP_SIGFASTBLOCK;
2140 			td->td_sigblock_val = 0;
2141 		}
2142 		mtx_unlock(&ps->ps_mtx);
2143 		p->p_sig = sig;		/* XXX to verify code */
2144 		tdsendsignal(p, td, sig, ksi);
2145 	}
2146 	PROC_UNLOCK(p);
2147 }
2148 
2149 static struct thread *
2150 sigtd(struct proc *p, int sig, bool fast_sigblock)
2151 {
2152 	struct thread *td, *signal_td;
2153 
2154 	PROC_LOCK_ASSERT(p, MA_OWNED);
2155 	MPASS(!fast_sigblock || p == curproc);
2156 
2157 	/*
2158 	 * Check if current thread can handle the signal without
2159 	 * switching context to another thread.
2160 	 */
2161 	if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig) &&
2162 	    (!fast_sigblock || curthread->td_sigblock_val == 0))
2163 		return (curthread);
2164 
2165 	/* Find a non-stopped thread that does not mask the signal. */
2166 	signal_td = NULL;
2167 	FOREACH_THREAD_IN_PROC(p, td) {
2168 		if (!SIGISMEMBER(td->td_sigmask, sig) && (!fast_sigblock ||
2169 		    td != curthread || td->td_sigblock_val == 0) &&
2170 		    (td->td_flags & TDF_BOUNDARY) == 0) {
2171 			signal_td = td;
2172 			break;
2173 		}
2174 	}
2175 	/* Select random (first) thread if no better match was found. */
2176 	if (signal_td == NULL)
2177 		signal_td = FIRST_THREAD_IN_PROC(p);
2178 	return (signal_td);
2179 }
2180 
2181 /*
2182  * Send the signal to the process.  If the signal has an action, the action
2183  * is usually performed by the target process rather than the caller; we add
2184  * the signal to the set of pending signals for the process.
2185  *
2186  * Exceptions:
2187  *   o When a stop signal is sent to a sleeping process that takes the
2188  *     default action, the process is stopped without awakening it.
2189  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2190  *     regardless of the signal action (eg, blocked or ignored).
2191  *
2192  * Other ignored signals are discarded immediately.
2193  *
2194  * NB: This function may be entered from the debugger via the "kill" DDB
2195  * command.  There is little that can be done to mitigate the possibly messy
2196  * side effects of this unwise possibility.
2197  */
2198 void
2199 kern_psignal(struct proc *p, int sig)
2200 {
2201 	ksiginfo_t ksi;
2202 
2203 	ksiginfo_init(&ksi);
2204 	ksi.ksi_signo = sig;
2205 	ksi.ksi_code = SI_KERNEL;
2206 	(void) tdsendsignal(p, NULL, sig, &ksi);
2207 }
2208 
2209 int
2210 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
2211 {
2212 
2213 	return (tdsendsignal(p, NULL, sig, ksi));
2214 }
2215 
2216 /* Utility function for finding a thread to send signal event to. */
2217 int
2218 sigev_findtd(struct proc *p, struct sigevent *sigev, struct thread **ttd)
2219 {
2220 	struct thread *td;
2221 
2222 	if (sigev->sigev_notify == SIGEV_THREAD_ID) {
2223 		td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
2224 		if (td == NULL)
2225 			return (ESRCH);
2226 		*ttd = td;
2227 	} else {
2228 		*ttd = NULL;
2229 		PROC_LOCK(p);
2230 	}
2231 	return (0);
2232 }
2233 
2234 void
2235 tdsignal(struct thread *td, int sig)
2236 {
2237 	ksiginfo_t ksi;
2238 
2239 	ksiginfo_init(&ksi);
2240 	ksi.ksi_signo = sig;
2241 	ksi.ksi_code = SI_KERNEL;
2242 	(void) tdsendsignal(td->td_proc, td, sig, &ksi);
2243 }
2244 
2245 void
2246 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2247 {
2248 
2249 	(void) tdsendsignal(td->td_proc, td, sig, ksi);
2250 }
2251 
2252 static int
2253 sig_sleepq_abort(struct thread *td, int intrval)
2254 {
2255 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2256 
2257 	if (intrval == 0 && (td->td_flags & TDF_SIGWAIT) == 0) {
2258 		thread_unlock(td);
2259 		return (0);
2260 	}
2261 	return (sleepq_abort(td, intrval));
2262 }
2263 
2264 int
2265 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2266 {
2267 	sig_t action;
2268 	sigqueue_t *sigqueue;
2269 	int prop;
2270 	struct sigacts *ps;
2271 	int intrval;
2272 	int ret = 0;
2273 	int wakeup_swapper;
2274 
2275 	MPASS(td == NULL || p == td->td_proc);
2276 	PROC_LOCK_ASSERT(p, MA_OWNED);
2277 
2278 	if (!_SIG_VALID(sig))
2279 		panic("%s(): invalid signal %d", __func__, sig);
2280 
2281 	KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2282 
2283 	/*
2284 	 * IEEE Std 1003.1-2001: return success when killing a zombie.
2285 	 */
2286 	if (p->p_state == PRS_ZOMBIE) {
2287 		if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2288 			ksiginfo_tryfree(ksi);
2289 		return (ret);
2290 	}
2291 
2292 	ps = p->p_sigacts;
2293 	KNOTE_LOCKED(p->p_klist, NOTE_SIGNAL | sig);
2294 	prop = sigprop(sig);
2295 
2296 	if (td == NULL) {
2297 		td = sigtd(p, sig, false);
2298 		sigqueue = &p->p_sigqueue;
2299 	} else
2300 		sigqueue = &td->td_sigqueue;
2301 
2302 	SDT_PROBE3(proc, , , signal__send, td, p, sig);
2303 
2304 	/*
2305 	 * If the signal is being ignored, then we forget about it
2306 	 * immediately, except when the target process executes
2307 	 * sigwait().  (Note: we don't set SIGCONT in ps_sigignore,
2308 	 * and if it is set to SIG_IGN, action will be SIG_DFL here.)
2309 	 */
2310 	mtx_lock(&ps->ps_mtx);
2311 	if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2312 		if (kern_sig_discard_ign &&
2313 		    (p->p_sysent->sv_flags & SV_SIG_DISCIGN) == 0) {
2314 			SDT_PROBE3(proc, , , signal__discard, td, p, sig);
2315 
2316 			mtx_unlock(&ps->ps_mtx);
2317 			if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2318 				ksiginfo_tryfree(ksi);
2319 			return (ret);
2320 		} else {
2321 			action = SIG_CATCH;
2322 			intrval = 0;
2323 		}
2324 	} else {
2325 		if (SIGISMEMBER(td->td_sigmask, sig))
2326 			action = SIG_HOLD;
2327 		else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2328 			action = SIG_CATCH;
2329 		else
2330 			action = SIG_DFL;
2331 		if (SIGISMEMBER(ps->ps_sigintr, sig))
2332 			intrval = EINTR;
2333 		else
2334 			intrval = ERESTART;
2335 	}
2336 	mtx_unlock(&ps->ps_mtx);
2337 
2338 	if (prop & SIGPROP_CONT)
2339 		sigqueue_delete_stopmask_proc(p);
2340 	else if (prop & SIGPROP_STOP) {
2341 		/*
2342 		 * If sending a tty stop signal to a member of an orphaned
2343 		 * process group, discard the signal here if the action
2344 		 * is default; don't stop the process below if sleeping,
2345 		 * and don't clear any pending SIGCONT.
2346 		 */
2347 		if ((prop & SIGPROP_TTYSTOP) != 0 &&
2348 		    (p->p_pgrp->pg_flags & PGRP_ORPHANED) != 0 &&
2349 		    action == SIG_DFL) {
2350 			if (ksi != NULL && (ksi->ksi_flags & KSI_INS) != 0)
2351 				ksiginfo_tryfree(ksi);
2352 			return (ret);
2353 		}
2354 		sigqueue_delete_proc(p, SIGCONT);
2355 		if (p->p_flag & P_CONTINUED) {
2356 			p->p_flag &= ~P_CONTINUED;
2357 			PROC_LOCK(p->p_pptr);
2358 			sigqueue_take(p->p_ksi);
2359 			PROC_UNLOCK(p->p_pptr);
2360 		}
2361 	}
2362 
2363 	ret = sigqueue_add(sigqueue, sig, ksi);
2364 	if (ret != 0)
2365 		return (ret);
2366 	signotify(td);
2367 	/*
2368 	 * Defer further processing for signals which are held,
2369 	 * except that stopped processes must be continued by SIGCONT.
2370 	 */
2371 	if (action == SIG_HOLD &&
2372 	    !((prop & SIGPROP_CONT) && (p->p_flag & P_STOPPED_SIG)))
2373 		return (ret);
2374 
2375 	wakeup_swapper = 0;
2376 
2377 	/*
2378 	 * Some signals have a process-wide effect and a per-thread
2379 	 * component.  Most processing occurs when the process next
2380 	 * tries to cross the user boundary, however there are some
2381 	 * times when processing needs to be done immediately, such as
2382 	 * waking up threads so that they can cross the user boundary.
2383 	 * We try to do the per-process part here.
2384 	 */
2385 	if (P_SHOULDSTOP(p)) {
2386 		KASSERT(!(p->p_flag & P_WEXIT),
2387 		    ("signal to stopped but exiting process"));
2388 		if (sig == SIGKILL) {
2389 			/*
2390 			 * If traced process is already stopped,
2391 			 * then no further action is necessary.
2392 			 */
2393 			if (p->p_flag & P_TRACED)
2394 				goto out;
2395 			/*
2396 			 * SIGKILL sets process running.
2397 			 * It will die elsewhere.
2398 			 * All threads must be restarted.
2399 			 */
2400 			p->p_flag &= ~P_STOPPED_SIG;
2401 			goto runfast;
2402 		}
2403 
2404 		if (prop & SIGPROP_CONT) {
2405 			/*
2406 			 * If traced process is already stopped,
2407 			 * then no further action is necessary.
2408 			 */
2409 			if (p->p_flag & P_TRACED)
2410 				goto out;
2411 			/*
2412 			 * If SIGCONT is default (or ignored), we continue the
2413 			 * process but don't leave the signal in sigqueue as
2414 			 * it has no further action.  If SIGCONT is held, we
2415 			 * continue the process and leave the signal in
2416 			 * sigqueue.  If the process catches SIGCONT, let it
2417 			 * handle the signal itself.  If it isn't waiting on
2418 			 * an event, it goes back to run state.
2419 			 * Otherwise, process goes back to sleep state.
2420 			 */
2421 			p->p_flag &= ~P_STOPPED_SIG;
2422 			PROC_SLOCK(p);
2423 			if (p->p_numthreads == p->p_suspcount) {
2424 				PROC_SUNLOCK(p);
2425 				p->p_flag |= P_CONTINUED;
2426 				p->p_xsig = SIGCONT;
2427 				PROC_LOCK(p->p_pptr);
2428 				childproc_continued(p);
2429 				PROC_UNLOCK(p->p_pptr);
2430 				PROC_SLOCK(p);
2431 			}
2432 			if (action == SIG_DFL) {
2433 				thread_unsuspend(p);
2434 				PROC_SUNLOCK(p);
2435 				sigqueue_delete(sigqueue, sig);
2436 				goto out_cont;
2437 			}
2438 			if (action == SIG_CATCH) {
2439 				/*
2440 				 * The process wants to catch it so it needs
2441 				 * to run at least one thread, but which one?
2442 				 */
2443 				PROC_SUNLOCK(p);
2444 				goto runfast;
2445 			}
2446 			/*
2447 			 * The signal is not ignored or caught.
2448 			 */
2449 			thread_unsuspend(p);
2450 			PROC_SUNLOCK(p);
2451 			goto out_cont;
2452 		}
2453 
2454 		if (prop & SIGPROP_STOP) {
2455 			/*
2456 			 * If traced process is already stopped,
2457 			 * then no further action is necessary.
2458 			 */
2459 			if (p->p_flag & P_TRACED)
2460 				goto out;
2461 			/*
2462 			 * Already stopped, don't need to stop again
2463 			 * (If we did the shell could get confused).
2464 			 * Just make sure the signal STOP bit set.
2465 			 */
2466 			p->p_flag |= P_STOPPED_SIG;
2467 			sigqueue_delete(sigqueue, sig);
2468 			goto out;
2469 		}
2470 
2471 		/*
2472 		 * All other kinds of signals:
2473 		 * If a thread is sleeping interruptibly, simulate a
2474 		 * wakeup so that when it is continued it will be made
2475 		 * runnable and can look at the signal.  However, don't make
2476 		 * the PROCESS runnable, leave it stopped.
2477 		 * It may run a bit until it hits a thread_suspend_check().
2478 		 */
2479 		PROC_SLOCK(p);
2480 		thread_lock(td);
2481 		if (TD_CAN_ABORT(td))
2482 			wakeup_swapper = sig_sleepq_abort(td, intrval);
2483 		else
2484 			thread_unlock(td);
2485 		PROC_SUNLOCK(p);
2486 		goto out;
2487 		/*
2488 		 * Mutexes are short lived. Threads waiting on them will
2489 		 * hit thread_suspend_check() soon.
2490 		 */
2491 	} else if (p->p_state == PRS_NORMAL) {
2492 		if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2493 			tdsigwakeup(td, sig, action, intrval);
2494 			goto out;
2495 		}
2496 
2497 		MPASS(action == SIG_DFL);
2498 
2499 		if (prop & SIGPROP_STOP) {
2500 			if (p->p_flag & (P_PPWAIT|P_WEXIT))
2501 				goto out;
2502 			p->p_flag |= P_STOPPED_SIG;
2503 			p->p_xsig = sig;
2504 			PROC_SLOCK(p);
2505 			wakeup_swapper = sig_suspend_threads(td, p);
2506 			if (p->p_numthreads == p->p_suspcount) {
2507 				/*
2508 				 * only thread sending signal to another
2509 				 * process can reach here, if thread is sending
2510 				 * signal to its process, because thread does
2511 				 * not suspend itself here, p_numthreads
2512 				 * should never be equal to p_suspcount.
2513 				 */
2514 				thread_stopped(p);
2515 				PROC_SUNLOCK(p);
2516 				sigqueue_delete_proc(p, p->p_xsig);
2517 			} else
2518 				PROC_SUNLOCK(p);
2519 			goto out;
2520 		}
2521 	} else {
2522 		/* Not in "NORMAL" state. discard the signal. */
2523 		sigqueue_delete(sigqueue, sig);
2524 		goto out;
2525 	}
2526 
2527 	/*
2528 	 * The process is not stopped so we need to apply the signal to all the
2529 	 * running threads.
2530 	 */
2531 runfast:
2532 	tdsigwakeup(td, sig, action, intrval);
2533 	PROC_SLOCK(p);
2534 	thread_unsuspend(p);
2535 	PROC_SUNLOCK(p);
2536 out_cont:
2537 	itimer_proc_continue(p);
2538 	kqtimer_proc_continue(p);
2539 out:
2540 	/* If we jump here, proc slock should not be owned. */
2541 	PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2542 	if (wakeup_swapper)
2543 		kick_proc0();
2544 
2545 	return (ret);
2546 }
2547 
2548 /*
2549  * The force of a signal has been directed against a single
2550  * thread.  We need to see what we can do about knocking it
2551  * out of any sleep it may be in etc.
2552  */
2553 static void
2554 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2555 {
2556 	struct proc *p = td->td_proc;
2557 	int prop, wakeup_swapper;
2558 
2559 	PROC_LOCK_ASSERT(p, MA_OWNED);
2560 	prop = sigprop(sig);
2561 
2562 	PROC_SLOCK(p);
2563 	thread_lock(td);
2564 	/*
2565 	 * Bring the priority of a thread up if we want it to get
2566 	 * killed in this lifetime.  Be careful to avoid bumping the
2567 	 * priority of the idle thread, since we still allow to signal
2568 	 * kernel processes.
2569 	 */
2570 	if (action == SIG_DFL && (prop & SIGPROP_KILL) != 0 &&
2571 	    td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2572 		sched_prio(td, PUSER);
2573 	if (TD_ON_SLEEPQ(td)) {
2574 		/*
2575 		 * If thread is sleeping uninterruptibly
2576 		 * we can't interrupt the sleep... the signal will
2577 		 * be noticed when the process returns through
2578 		 * trap() or syscall().
2579 		 */
2580 		if ((td->td_flags & TDF_SINTR) == 0)
2581 			goto out;
2582 		/*
2583 		 * If SIGCONT is default (or ignored) and process is
2584 		 * asleep, we are finished; the process should not
2585 		 * be awakened.
2586 		 */
2587 		if ((prop & SIGPROP_CONT) && action == SIG_DFL) {
2588 			thread_unlock(td);
2589 			PROC_SUNLOCK(p);
2590 			sigqueue_delete(&p->p_sigqueue, sig);
2591 			/*
2592 			 * It may be on either list in this state.
2593 			 * Remove from both for now.
2594 			 */
2595 			sigqueue_delete(&td->td_sigqueue, sig);
2596 			return;
2597 		}
2598 
2599 		/*
2600 		 * Don't awaken a sleeping thread for SIGSTOP if the
2601 		 * STOP signal is deferred.
2602 		 */
2603 		if ((prop & SIGPROP_STOP) != 0 && (td->td_flags & (TDF_SBDRY |
2604 		    TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2605 			goto out;
2606 
2607 		/*
2608 		 * Give low priority threads a better chance to run.
2609 		 */
2610 		if (td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2611 			sched_prio(td, PUSER);
2612 
2613 		wakeup_swapper = sig_sleepq_abort(td, intrval);
2614 		PROC_SUNLOCK(p);
2615 		if (wakeup_swapper)
2616 			kick_proc0();
2617 		return;
2618 	}
2619 
2620 	/*
2621 	 * Other states do nothing with the signal immediately,
2622 	 * other than kicking ourselves if we are running.
2623 	 * It will either never be noticed, or noticed very soon.
2624 	 */
2625 #ifdef SMP
2626 	if (TD_IS_RUNNING(td) && td != curthread)
2627 		forward_signal(td);
2628 #endif
2629 
2630 out:
2631 	PROC_SUNLOCK(p);
2632 	thread_unlock(td);
2633 }
2634 
2635 static void
2636 ptrace_coredumpreq(struct thread *td, struct proc *p,
2637     struct thr_coredump_req *tcq)
2638 {
2639 	void *rl_cookie;
2640 
2641 	if (p->p_sysent->sv_coredump == NULL) {
2642 		tcq->tc_error = ENOSYS;
2643 		return;
2644 	}
2645 
2646 	rl_cookie = vn_rangelock_wlock(tcq->tc_vp, 0, OFF_MAX);
2647 	tcq->tc_error = p->p_sysent->sv_coredump(td, tcq->tc_vp,
2648 	    tcq->tc_limit, tcq->tc_flags);
2649 	vn_rangelock_unlock(tcq->tc_vp, rl_cookie);
2650 }
2651 
2652 static void
2653 ptrace_syscallreq(struct thread *td, struct proc *p,
2654     struct thr_syscall_req *tsr)
2655 {
2656 	struct sysentvec *sv;
2657 	struct sysent *se;
2658 	register_t rv_saved[2];
2659 	int error, nerror;
2660 	int sc;
2661 	bool audited, sy_thr_static;
2662 
2663 	sv = p->p_sysent;
2664 	if (sv->sv_table == NULL || sv->sv_size < tsr->ts_sa.code) {
2665 		tsr->ts_ret.sr_error = ENOSYS;
2666 		return;
2667 	}
2668 
2669 	sc = tsr->ts_sa.code;
2670 	if (sc == SYS_syscall || sc == SYS___syscall) {
2671 		sc = tsr->ts_sa.args[0];
2672 		memmove(&tsr->ts_sa.args[0], &tsr->ts_sa.args[1],
2673 		    sizeof(register_t) * (tsr->ts_nargs - 1));
2674 	}
2675 
2676 	tsr->ts_sa.callp = se = &sv->sv_table[sc];
2677 
2678 	VM_CNT_INC(v_syscall);
2679 	td->td_pticks = 0;
2680 	if (__predict_false(td->td_cowgen != atomic_load_int(
2681 	    &td->td_proc->p_cowgen)))
2682 		thread_cow_update(td);
2683 
2684 	td->td_sa = tsr->ts_sa;
2685 
2686 #ifdef CAPABILITY_MODE
2687 	if ((se->sy_flags & SYF_CAPENABLED) == 0) {
2688 		if (CAP_TRACING(td))
2689 			ktrcapfail(CAPFAIL_SYSCALL, NULL);
2690 		if (IN_CAPABILITY_MODE(td)) {
2691 			tsr->ts_ret.sr_error = ECAPMODE;
2692 			return;
2693 		}
2694 	}
2695 #endif
2696 
2697 	sy_thr_static = (se->sy_thrcnt & SY_THR_STATIC) != 0;
2698 	audited = AUDIT_SYSCALL_ENTER(sc, td) != 0;
2699 
2700 	if (!sy_thr_static) {
2701 		error = syscall_thread_enter(td, &se);
2702 		sy_thr_static = (se->sy_thrcnt & SY_THR_STATIC) != 0;
2703 		if (error != 0) {
2704 			tsr->ts_ret.sr_error = error;
2705 			return;
2706 		}
2707 	}
2708 
2709 	rv_saved[0] = td->td_retval[0];
2710 	rv_saved[1] = td->td_retval[1];
2711 	nerror = td->td_errno;
2712 	td->td_retval[0] = 0;
2713 	td->td_retval[1] = 0;
2714 
2715 #ifdef KDTRACE_HOOKS
2716 	if (se->sy_entry != 0)
2717 		(*systrace_probe_func)(&tsr->ts_sa, SYSTRACE_ENTRY, 0);
2718 #endif
2719 	tsr->ts_ret.sr_error = se->sy_call(td, tsr->ts_sa.args);
2720 #ifdef KDTRACE_HOOKS
2721 	if (se->sy_return != 0)
2722 		(*systrace_probe_func)(&tsr->ts_sa, SYSTRACE_RETURN,
2723 		    tsr->ts_ret.sr_error != 0 ? -1 : td->td_retval[0]);
2724 #endif
2725 
2726 	tsr->ts_ret.sr_retval[0] = td->td_retval[0];
2727 	tsr->ts_ret.sr_retval[1] = td->td_retval[1];
2728 	td->td_retval[0] = rv_saved[0];
2729 	td->td_retval[1] = rv_saved[1];
2730 	td->td_errno = nerror;
2731 
2732 	if (audited)
2733 		AUDIT_SYSCALL_EXIT(error, td);
2734 	if (!sy_thr_static)
2735 		syscall_thread_exit(td, se);
2736 }
2737 
2738 static void
2739 ptrace_remotereq(struct thread *td, int flag)
2740 {
2741 	struct proc *p;
2742 
2743 	MPASS(td == curthread);
2744 	p = td->td_proc;
2745 	PROC_LOCK_ASSERT(p, MA_OWNED);
2746 	if ((td->td_dbgflags & flag) == 0)
2747 		return;
2748 	KASSERT((p->p_flag & P_STOPPED_TRACE) != 0, ("not stopped"));
2749 	KASSERT(td->td_remotereq != NULL, ("td_remotereq is NULL"));
2750 
2751 	PROC_UNLOCK(p);
2752 	switch (flag) {
2753 	case TDB_COREDUMPREQ:
2754 		ptrace_coredumpreq(td, p, td->td_remotereq);
2755 		break;
2756 	case TDB_SCREMOTEREQ:
2757 		ptrace_syscallreq(td, p, td->td_remotereq);
2758 		break;
2759 	default:
2760 		__unreachable();
2761 	}
2762 	PROC_LOCK(p);
2763 
2764 	MPASS((td->td_dbgflags & flag) != 0);
2765 	td->td_dbgflags &= ~flag;
2766 	td->td_remotereq = NULL;
2767 	wakeup(p);
2768 }
2769 
2770 static int
2771 sig_suspend_threads(struct thread *td, struct proc *p)
2772 {
2773 	struct thread *td2;
2774 	int wakeup_swapper;
2775 
2776 	PROC_LOCK_ASSERT(p, MA_OWNED);
2777 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2778 
2779 	wakeup_swapper = 0;
2780 	FOREACH_THREAD_IN_PROC(p, td2) {
2781 		thread_lock(td2);
2782 		ast_sched_locked(td2, TDA_SUSPEND);
2783 		if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2784 		    (td2->td_flags & TDF_SINTR)) {
2785 			if (td2->td_flags & TDF_SBDRY) {
2786 				/*
2787 				 * Once a thread is asleep with
2788 				 * TDF_SBDRY and without TDF_SERESTART
2789 				 * or TDF_SEINTR set, it should never
2790 				 * become suspended due to this check.
2791 				 */
2792 				KASSERT(!TD_IS_SUSPENDED(td2),
2793 				    ("thread with deferred stops suspended"));
2794 				if (TD_SBDRY_INTR(td2)) {
2795 					wakeup_swapper |= sleepq_abort(td2,
2796 					    TD_SBDRY_ERRNO(td2));
2797 					continue;
2798 				}
2799 			} else if (!TD_IS_SUSPENDED(td2))
2800 				thread_suspend_one(td2);
2801 		} else if (!TD_IS_SUSPENDED(td2)) {
2802 #ifdef SMP
2803 			if (TD_IS_RUNNING(td2) && td2 != td)
2804 				forward_signal(td2);
2805 #endif
2806 		}
2807 		thread_unlock(td2);
2808 	}
2809 	return (wakeup_swapper);
2810 }
2811 
2812 /*
2813  * Stop the process for an event deemed interesting to the debugger. If si is
2814  * non-NULL, this is a signal exchange; the new signal requested by the
2815  * debugger will be returned for handling. If si is NULL, this is some other
2816  * type of interesting event. The debugger may request a signal be delivered in
2817  * that case as well, however it will be deferred until it can be handled.
2818  */
2819 int
2820 ptracestop(struct thread *td, int sig, ksiginfo_t *si)
2821 {
2822 	struct proc *p = td->td_proc;
2823 	struct thread *td2;
2824 	ksiginfo_t ksi;
2825 
2826 	PROC_LOCK_ASSERT(p, MA_OWNED);
2827 	KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2828 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2829 	    &p->p_mtx.lock_object, "Stopping for traced signal");
2830 
2831 	td->td_xsig = sig;
2832 
2833 	if (si == NULL || (si->ksi_flags & KSI_PTRACE) == 0) {
2834 		td->td_dbgflags |= TDB_XSIG;
2835 		CTR4(KTR_PTRACE, "ptracestop: tid %d (pid %d) flags %#x sig %d",
2836 		    td->td_tid, p->p_pid, td->td_dbgflags, sig);
2837 		PROC_SLOCK(p);
2838 		while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2839 			if (P_KILLED(p)) {
2840 				/*
2841 				 * Ensure that, if we've been PT_KILLed, the
2842 				 * exit status reflects that. Another thread
2843 				 * may also be in ptracestop(), having just
2844 				 * received the SIGKILL, but this thread was
2845 				 * unsuspended first.
2846 				 */
2847 				td->td_dbgflags &= ~TDB_XSIG;
2848 				td->td_xsig = SIGKILL;
2849 				p->p_ptevents = 0;
2850 				break;
2851 			}
2852 			if (p->p_flag & P_SINGLE_EXIT &&
2853 			    !(td->td_dbgflags & TDB_EXIT)) {
2854 				/*
2855 				 * Ignore ptrace stops except for thread exit
2856 				 * events when the process exits.
2857 				 */
2858 				td->td_dbgflags &= ~TDB_XSIG;
2859 				PROC_SUNLOCK(p);
2860 				return (0);
2861 			}
2862 
2863 			/*
2864 			 * Make wait(2) work.  Ensure that right after the
2865 			 * attach, the thread which was decided to become the
2866 			 * leader of attach gets reported to the waiter.
2867 			 * Otherwise, just avoid overwriting another thread's
2868 			 * assignment to p_xthread.  If another thread has
2869 			 * already set p_xthread, the current thread will get
2870 			 * a chance to report itself upon the next iteration.
2871 			 */
2872 			if ((td->td_dbgflags & TDB_FSTP) != 0 ||
2873 			    ((p->p_flag2 & P2_PTRACE_FSTP) == 0 &&
2874 			    p->p_xthread == NULL)) {
2875 				p->p_xsig = sig;
2876 				p->p_xthread = td;
2877 
2878 				/*
2879 				 * If we are on sleepqueue already,
2880 				 * let sleepqueue code decide if it
2881 				 * needs to go sleep after attach.
2882 				 */
2883 				if (td->td_wchan == NULL)
2884 					td->td_dbgflags &= ~TDB_FSTP;
2885 
2886 				p->p_flag2 &= ~P2_PTRACE_FSTP;
2887 				p->p_flag |= P_STOPPED_SIG | P_STOPPED_TRACE;
2888 				sig_suspend_threads(td, p);
2889 			}
2890 			if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2891 				td->td_dbgflags &= ~TDB_STOPATFORK;
2892 			}
2893 stopme:
2894 			td->td_dbgflags |= TDB_SSWITCH;
2895 			thread_suspend_switch(td, p);
2896 			td->td_dbgflags &= ~TDB_SSWITCH;
2897 			if ((td->td_dbgflags & (TDB_COREDUMPREQ |
2898 			    TDB_SCREMOTEREQ)) != 0) {
2899 				MPASS((td->td_dbgflags & (TDB_COREDUMPREQ |
2900 				    TDB_SCREMOTEREQ)) !=
2901 				    (TDB_COREDUMPREQ | TDB_SCREMOTEREQ));
2902 				PROC_SUNLOCK(p);
2903 				ptrace_remotereq(td, td->td_dbgflags &
2904 				    (TDB_COREDUMPREQ | TDB_SCREMOTEREQ));
2905 				PROC_SLOCK(p);
2906 				goto stopme;
2907 			}
2908 			if (p->p_xthread == td)
2909 				p->p_xthread = NULL;
2910 			if (!(p->p_flag & P_TRACED))
2911 				break;
2912 			if (td->td_dbgflags & TDB_SUSPEND) {
2913 				if (p->p_flag & P_SINGLE_EXIT)
2914 					break;
2915 				goto stopme;
2916 			}
2917 		}
2918 		PROC_SUNLOCK(p);
2919 	}
2920 
2921 	if (si != NULL && sig == td->td_xsig) {
2922 		/* Parent wants us to take the original signal unchanged. */
2923 		si->ksi_flags |= KSI_HEAD;
2924 		if (sigqueue_add(&td->td_sigqueue, sig, si) != 0)
2925 			si->ksi_signo = 0;
2926 	} else if (td->td_xsig != 0) {
2927 		/*
2928 		 * If parent wants us to take a new signal, then it will leave
2929 		 * it in td->td_xsig; otherwise we just look for signals again.
2930 		 */
2931 		ksiginfo_init(&ksi);
2932 		ksi.ksi_signo = td->td_xsig;
2933 		ksi.ksi_flags |= KSI_PTRACE;
2934 		td2 = sigtd(p, td->td_xsig, false);
2935 		tdsendsignal(p, td2, td->td_xsig, &ksi);
2936 		if (td != td2)
2937 			return (0);
2938 	}
2939 
2940 	return (td->td_xsig);
2941 }
2942 
2943 static void
2944 reschedule_signals(struct proc *p, sigset_t block, int flags)
2945 {
2946 	struct sigacts *ps;
2947 	struct thread *td;
2948 	int sig;
2949 	bool fastblk, pslocked;
2950 
2951 	PROC_LOCK_ASSERT(p, MA_OWNED);
2952 	ps = p->p_sigacts;
2953 	pslocked = (flags & SIGPROCMASK_PS_LOCKED) != 0;
2954 	mtx_assert(&ps->ps_mtx, pslocked ? MA_OWNED : MA_NOTOWNED);
2955 	if (SIGISEMPTY(p->p_siglist))
2956 		return;
2957 	SIGSETAND(block, p->p_siglist);
2958 	fastblk = (flags & SIGPROCMASK_FASTBLK) != 0;
2959 	SIG_FOREACH(sig, &block) {
2960 		td = sigtd(p, sig, fastblk);
2961 
2962 		/*
2963 		 * If sigtd() selected us despite sigfastblock is
2964 		 * blocking, do not activate AST or wake us, to avoid
2965 		 * loop in AST handler.
2966 		 */
2967 		if (fastblk && td == curthread)
2968 			continue;
2969 
2970 		signotify(td);
2971 		if (!pslocked)
2972 			mtx_lock(&ps->ps_mtx);
2973 		if (p->p_flag & P_TRACED ||
2974 		    (SIGISMEMBER(ps->ps_sigcatch, sig) &&
2975 		    !SIGISMEMBER(td->td_sigmask, sig))) {
2976 			tdsigwakeup(td, sig, SIG_CATCH,
2977 			    (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2978 			    ERESTART));
2979 		}
2980 		if (!pslocked)
2981 			mtx_unlock(&ps->ps_mtx);
2982 	}
2983 }
2984 
2985 void
2986 tdsigcleanup(struct thread *td)
2987 {
2988 	struct proc *p;
2989 	sigset_t unblocked;
2990 
2991 	p = td->td_proc;
2992 	PROC_LOCK_ASSERT(p, MA_OWNED);
2993 
2994 	sigqueue_flush(&td->td_sigqueue);
2995 	if (p->p_numthreads == 1)
2996 		return;
2997 
2998 	/*
2999 	 * Since we cannot handle signals, notify signal post code
3000 	 * about this by filling the sigmask.
3001 	 *
3002 	 * Also, if needed, wake up thread(s) that do not block the
3003 	 * same signals as the exiting thread, since the thread might
3004 	 * have been selected for delivery and woken up.
3005 	 */
3006 	SIGFILLSET(unblocked);
3007 	SIGSETNAND(unblocked, td->td_sigmask);
3008 	SIGFILLSET(td->td_sigmask);
3009 	reschedule_signals(p, unblocked, 0);
3010 
3011 }
3012 
3013 static int
3014 sigdeferstop_curr_flags(int cflags)
3015 {
3016 
3017 	MPASS((cflags & (TDF_SEINTR | TDF_SERESTART)) == 0 ||
3018 	    (cflags & TDF_SBDRY) != 0);
3019 	return (cflags & (TDF_SBDRY | TDF_SEINTR | TDF_SERESTART));
3020 }
3021 
3022 /*
3023  * Defer the delivery of SIGSTOP for the current thread, according to
3024  * the requested mode.  Returns previous flags, which must be restored
3025  * by sigallowstop().
3026  *
3027  * TDF_SBDRY, TDF_SEINTR, and TDF_SERESTART flags are only set and
3028  * cleared by the current thread, which allow the lock-less read-only
3029  * accesses below.
3030  */
3031 int
3032 sigdeferstop_impl(int mode)
3033 {
3034 	struct thread *td;
3035 	int cflags, nflags;
3036 
3037 	td = curthread;
3038 	cflags = sigdeferstop_curr_flags(td->td_flags);
3039 	switch (mode) {
3040 	case SIGDEFERSTOP_NOP:
3041 		nflags = cflags;
3042 		break;
3043 	case SIGDEFERSTOP_OFF:
3044 		nflags = 0;
3045 		break;
3046 	case SIGDEFERSTOP_SILENT:
3047 		nflags = (cflags | TDF_SBDRY) & ~(TDF_SEINTR | TDF_SERESTART);
3048 		break;
3049 	case SIGDEFERSTOP_EINTR:
3050 		nflags = (cflags | TDF_SBDRY | TDF_SEINTR) & ~TDF_SERESTART;
3051 		break;
3052 	case SIGDEFERSTOP_ERESTART:
3053 		nflags = (cflags | TDF_SBDRY | TDF_SERESTART) & ~TDF_SEINTR;
3054 		break;
3055 	default:
3056 		panic("sigdeferstop: invalid mode %x", mode);
3057 		break;
3058 	}
3059 	if (cflags == nflags)
3060 		return (SIGDEFERSTOP_VAL_NCHG);
3061 	thread_lock(td);
3062 	td->td_flags = (td->td_flags & ~cflags) | nflags;
3063 	thread_unlock(td);
3064 	return (cflags);
3065 }
3066 
3067 /*
3068  * Restores the STOP handling mode, typically permitting the delivery
3069  * of SIGSTOP for the current thread.  This does not immediately
3070  * suspend if a stop was posted.  Instead, the thread will suspend
3071  * either via ast() or a subsequent interruptible sleep.
3072  */
3073 void
3074 sigallowstop_impl(int prev)
3075 {
3076 	struct thread *td;
3077 	int cflags;
3078 
3079 	KASSERT(prev != SIGDEFERSTOP_VAL_NCHG, ("failed sigallowstop"));
3080 	KASSERT((prev & ~(TDF_SBDRY | TDF_SEINTR | TDF_SERESTART)) == 0,
3081 	    ("sigallowstop: incorrect previous mode %x", prev));
3082 	td = curthread;
3083 	cflags = sigdeferstop_curr_flags(td->td_flags);
3084 	if (cflags != prev) {
3085 		thread_lock(td);
3086 		td->td_flags = (td->td_flags & ~cflags) | prev;
3087 		thread_unlock(td);
3088 	}
3089 }
3090 
3091 enum sigstatus {
3092 	SIGSTATUS_HANDLE,
3093 	SIGSTATUS_HANDLED,
3094 	SIGSTATUS_IGNORE,
3095 	SIGSTATUS_SBDRY_STOP,
3096 };
3097 
3098 /*
3099  * The thread has signal "sig" pending.  Figure out what to do with it:
3100  *
3101  * _HANDLE     -> the caller should handle the signal
3102  * _HANDLED    -> handled internally, reload pending signal set
3103  * _IGNORE     -> ignored, remove from the set of pending signals and try the
3104  *                next pending signal
3105  * _SBDRY_STOP -> the signal should stop the thread but this is not
3106  *                permitted in the current context
3107  */
3108 static enum sigstatus
3109 sigprocess(struct thread *td, int sig)
3110 {
3111 	struct proc *p;
3112 	struct sigacts *ps;
3113 	struct sigqueue *queue;
3114 	ksiginfo_t ksi;
3115 	int prop;
3116 
3117 	KASSERT(_SIG_VALID(sig), ("%s: invalid signal %d", __func__, sig));
3118 
3119 	p = td->td_proc;
3120 	ps = p->p_sigacts;
3121 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3122 	PROC_LOCK_ASSERT(p, MA_OWNED);
3123 
3124 	/*
3125 	 * We should allow pending but ignored signals below
3126 	 * if there is sigwait() active, or P_TRACED was
3127 	 * on when they were posted.
3128 	 */
3129 	if (SIGISMEMBER(ps->ps_sigignore, sig) &&
3130 	    (p->p_flag & P_TRACED) == 0 &&
3131 	    (td->td_flags & TDF_SIGWAIT) == 0) {
3132 		return (SIGSTATUS_IGNORE);
3133 	}
3134 
3135 	/*
3136 	 * If the process is going to single-thread mode to prepare
3137 	 * for exit, there is no sense in delivering any signal
3138 	 * to usermode.  Another important consequence is that
3139 	 * msleep(..., PCATCH, ...) now is only interruptible by a
3140 	 * suspend request.
3141 	 */
3142 	if ((p->p_flag2 & P2_WEXIT) != 0)
3143 		return (SIGSTATUS_IGNORE);
3144 
3145 	if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED) {
3146 		/*
3147 		 * If traced, always stop.
3148 		 * Remove old signal from queue before the stop.
3149 		 * XXX shrug off debugger, it causes siginfo to
3150 		 * be thrown away.
3151 		 */
3152 		queue = &td->td_sigqueue;
3153 		ksiginfo_init(&ksi);
3154 		if (sigqueue_get(queue, sig, &ksi) == 0) {
3155 			queue = &p->p_sigqueue;
3156 			sigqueue_get(queue, sig, &ksi);
3157 		}
3158 		td->td_si = ksi.ksi_info;
3159 
3160 		mtx_unlock(&ps->ps_mtx);
3161 		sig = ptracestop(td, sig, &ksi);
3162 		mtx_lock(&ps->ps_mtx);
3163 
3164 		td->td_si.si_signo = 0;
3165 
3166 		/*
3167 		 * Keep looking if the debugger discarded or
3168 		 * replaced the signal.
3169 		 */
3170 		if (sig == 0)
3171 			return (SIGSTATUS_HANDLED);
3172 
3173 		/*
3174 		 * If the signal became masked, re-queue it.
3175 		 */
3176 		if (SIGISMEMBER(td->td_sigmask, sig)) {
3177 			ksi.ksi_flags |= KSI_HEAD;
3178 			sigqueue_add(&p->p_sigqueue, sig, &ksi);
3179 			return (SIGSTATUS_HANDLED);
3180 		}
3181 
3182 		/*
3183 		 * If the traced bit got turned off, requeue the signal and
3184 		 * reload the set of pending signals.  This ensures that p_sig*
3185 		 * and p_sigact are consistent.
3186 		 */
3187 		if ((p->p_flag & P_TRACED) == 0) {
3188 			if ((ksi.ksi_flags & KSI_PTRACE) == 0) {
3189 				ksi.ksi_flags |= KSI_HEAD;
3190 				sigqueue_add(queue, sig, &ksi);
3191 			}
3192 			return (SIGSTATUS_HANDLED);
3193 		}
3194 	}
3195 
3196 	/*
3197 	 * Decide whether the signal should be returned.
3198 	 * Return the signal's number, or fall through
3199 	 * to clear it from the pending mask.
3200 	 */
3201 	switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
3202 	case (intptr_t)SIG_DFL:
3203 		/*
3204 		 * Don't take default actions on system processes.
3205 		 */
3206 		if (p->p_pid <= 1) {
3207 #ifdef DIAGNOSTIC
3208 			/*
3209 			 * Are you sure you want to ignore SIGSEGV
3210 			 * in init? XXX
3211 			 */
3212 			printf("Process (pid %lu) got signal %d\n",
3213 				(u_long)p->p_pid, sig);
3214 #endif
3215 			return (SIGSTATUS_IGNORE);
3216 		}
3217 
3218 		/*
3219 		 * If there is a pending stop signal to process with
3220 		 * default action, stop here, then clear the signal.
3221 		 * Traced or exiting processes should ignore stops.
3222 		 * Additionally, a member of an orphaned process group
3223 		 * should ignore tty stops.
3224 		 */
3225 		prop = sigprop(sig);
3226 		if (prop & SIGPROP_STOP) {
3227 			mtx_unlock(&ps->ps_mtx);
3228 			if ((p->p_flag & (P_TRACED | P_WEXIT |
3229 			    P_SINGLE_EXIT)) != 0 || ((p->p_pgrp->
3230 			    pg_flags & PGRP_ORPHANED) != 0 &&
3231 			    (prop & SIGPROP_TTYSTOP) != 0)) {
3232 				mtx_lock(&ps->ps_mtx);
3233 				return (SIGSTATUS_IGNORE);
3234 			}
3235 			if (TD_SBDRY_INTR(td)) {
3236 				KASSERT((td->td_flags & TDF_SBDRY) != 0,
3237 				    ("lost TDF_SBDRY"));
3238 				mtx_lock(&ps->ps_mtx);
3239 				return (SIGSTATUS_SBDRY_STOP);
3240 			}
3241 			WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
3242 			    &p->p_mtx.lock_object, "Catching SIGSTOP");
3243 			sigqueue_delete(&td->td_sigqueue, sig);
3244 			sigqueue_delete(&p->p_sigqueue, sig);
3245 			p->p_flag |= P_STOPPED_SIG;
3246 			p->p_xsig = sig;
3247 			PROC_SLOCK(p);
3248 			sig_suspend_threads(td, p);
3249 			thread_suspend_switch(td, p);
3250 			PROC_SUNLOCK(p);
3251 			mtx_lock(&ps->ps_mtx);
3252 			return (SIGSTATUS_HANDLED);
3253 		} else if ((prop & SIGPROP_IGNORE) != 0 &&
3254 		    (td->td_flags & TDF_SIGWAIT) == 0) {
3255 			/*
3256 			 * Default action is to ignore; drop it if
3257 			 * not in kern_sigtimedwait().
3258 			 */
3259 			return (SIGSTATUS_IGNORE);
3260 		} else {
3261 			return (SIGSTATUS_HANDLE);
3262 		}
3263 
3264 	case (intptr_t)SIG_IGN:
3265 		if ((td->td_flags & TDF_SIGWAIT) == 0)
3266 			return (SIGSTATUS_IGNORE);
3267 		else
3268 			return (SIGSTATUS_HANDLE);
3269 
3270 	default:
3271 		/*
3272 		 * This signal has an action, let postsig() process it.
3273 		 */
3274 		return (SIGSTATUS_HANDLE);
3275 	}
3276 }
3277 
3278 /*
3279  * If the current process has received a signal (should be caught or cause
3280  * termination, should interrupt current syscall), return the signal number.
3281  * Stop signals with default action are processed immediately, then cleared;
3282  * they aren't returned.  This is checked after each entry to the system for
3283  * a syscall or trap (though this can usually be done without calling
3284  * issignal by checking the pending signal masks in cursig.) The normal call
3285  * sequence is
3286  *
3287  *	while (sig = cursig(curthread))
3288  *		postsig(sig);
3289  */
3290 static int
3291 issignal(struct thread *td)
3292 {
3293 	struct proc *p;
3294 	sigset_t sigpending;
3295 	int sig;
3296 
3297 	p = td->td_proc;
3298 	PROC_LOCK_ASSERT(p, MA_OWNED);
3299 
3300 	for (;;) {
3301 		sigpending = td->td_sigqueue.sq_signals;
3302 		SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
3303 		SIGSETNAND(sigpending, td->td_sigmask);
3304 
3305 		if ((p->p_flag & P_PPWAIT) != 0 || (td->td_flags &
3306 		    (TDF_SBDRY | TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
3307 			SIG_STOPSIGMASK(sigpending);
3308 		if (SIGISEMPTY(sigpending))	/* no signal to send */
3309 			return (0);
3310 
3311 		/*
3312 		 * Do fast sigblock if requested by usermode.  Since
3313 		 * we do know that there was a signal pending at this
3314 		 * point, set the FAST_SIGBLOCK_PEND as indicator for
3315 		 * usermode to perform a dummy call to
3316 		 * FAST_SIGBLOCK_UNBLOCK, which causes immediate
3317 		 * delivery of postponed pending signal.
3318 		 */
3319 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
3320 			if (td->td_sigblock_val != 0)
3321 				SIGSETNAND(sigpending, fastblock_mask);
3322 			if (SIGISEMPTY(sigpending)) {
3323 				td->td_pflags |= TDP_SIGFASTPENDING;
3324 				return (0);
3325 			}
3326 		}
3327 
3328 		if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED &&
3329 		    (p->p_flag2 & P2_PTRACE_FSTP) != 0 &&
3330 		    SIGISMEMBER(sigpending, SIGSTOP)) {
3331 			/*
3332 			 * If debugger just attached, always consume
3333 			 * SIGSTOP from ptrace(PT_ATTACH) first, to
3334 			 * execute the debugger attach ritual in
3335 			 * order.
3336 			 */
3337 			td->td_dbgflags |= TDB_FSTP;
3338 			SIGEMPTYSET(sigpending);
3339 			SIGADDSET(sigpending, SIGSTOP);
3340 		}
3341 
3342 		SIG_FOREACH(sig, &sigpending) {
3343 			switch (sigprocess(td, sig)) {
3344 			case SIGSTATUS_HANDLE:
3345 				return (sig);
3346 			case SIGSTATUS_HANDLED:
3347 				goto next;
3348 			case SIGSTATUS_IGNORE:
3349 				sigqueue_delete(&td->td_sigqueue, sig);
3350 				sigqueue_delete(&p->p_sigqueue, sig);
3351 				break;
3352 			case SIGSTATUS_SBDRY_STOP:
3353 				return (-1);
3354 			}
3355 		}
3356 next:;
3357 	}
3358 }
3359 
3360 void
3361 thread_stopped(struct proc *p)
3362 {
3363 	int n;
3364 
3365 	PROC_LOCK_ASSERT(p, MA_OWNED);
3366 	PROC_SLOCK_ASSERT(p, MA_OWNED);
3367 	n = p->p_suspcount;
3368 	if (p == curproc)
3369 		n++;
3370 	if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
3371 		PROC_SUNLOCK(p);
3372 		p->p_flag &= ~P_WAITED;
3373 		PROC_LOCK(p->p_pptr);
3374 		childproc_stopped(p, (p->p_flag & P_TRACED) ?
3375 			CLD_TRAPPED : CLD_STOPPED);
3376 		PROC_UNLOCK(p->p_pptr);
3377 		PROC_SLOCK(p);
3378 	}
3379 }
3380 
3381 /*
3382  * Take the action for the specified signal
3383  * from the current set of pending signals.
3384  */
3385 int
3386 postsig(int sig)
3387 {
3388 	struct thread *td;
3389 	struct proc *p;
3390 	struct sigacts *ps;
3391 	sig_t action;
3392 	ksiginfo_t ksi;
3393 	sigset_t returnmask;
3394 
3395 	KASSERT(sig != 0, ("postsig"));
3396 
3397 	td = curthread;
3398 	p = td->td_proc;
3399 	PROC_LOCK_ASSERT(p, MA_OWNED);
3400 	ps = p->p_sigacts;
3401 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3402 	ksiginfo_init(&ksi);
3403 	if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
3404 	    sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
3405 		return (0);
3406 	ksi.ksi_signo = sig;
3407 	if (ksi.ksi_code == SI_TIMER)
3408 		itimer_accept(p, ksi.ksi_timerid, &ksi);
3409 	action = ps->ps_sigact[_SIG_IDX(sig)];
3410 #ifdef KTRACE
3411 	if (KTRPOINT(td, KTR_PSIG))
3412 		ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
3413 		    &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
3414 #endif
3415 
3416 	if (action == SIG_DFL) {
3417 		/*
3418 		 * Default action, where the default is to kill
3419 		 * the process.  (Other cases were ignored above.)
3420 		 */
3421 		mtx_unlock(&ps->ps_mtx);
3422 		proc_td_siginfo_capture(td, &ksi.ksi_info);
3423 		sigexit(td, sig);
3424 		/* NOTREACHED */
3425 	} else {
3426 		/*
3427 		 * If we get here, the signal must be caught.
3428 		 */
3429 		KASSERT(action != SIG_IGN, ("postsig action %p", action));
3430 		KASSERT(!SIGISMEMBER(td->td_sigmask, sig),
3431 		    ("postsig action: blocked sig %d", sig));
3432 
3433 		/*
3434 		 * Set the new mask value and also defer further
3435 		 * occurrences of this signal.
3436 		 *
3437 		 * Special case: user has done a sigsuspend.  Here the
3438 		 * current mask is not of interest, but rather the
3439 		 * mask from before the sigsuspend is what we want
3440 		 * restored after the signal processing is completed.
3441 		 */
3442 		if (td->td_pflags & TDP_OLDMASK) {
3443 			returnmask = td->td_oldsigmask;
3444 			td->td_pflags &= ~TDP_OLDMASK;
3445 		} else
3446 			returnmask = td->td_sigmask;
3447 
3448 		if (p->p_sig == sig) {
3449 			p->p_sig = 0;
3450 		}
3451 		(*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
3452 		postsig_done(sig, td, ps);
3453 	}
3454 	return (1);
3455 }
3456 
3457 int
3458 sig_ast_checksusp(struct thread *td)
3459 {
3460 	struct proc *p __diagused;
3461 	int ret;
3462 
3463 	p = td->td_proc;
3464 	PROC_LOCK_ASSERT(p, MA_OWNED);
3465 
3466 	if (!td_ast_pending(td, TDA_SUSPEND))
3467 		return (0);
3468 
3469 	ret = thread_suspend_check(1);
3470 	MPASS(ret == 0 || ret == EINTR || ret == ERESTART);
3471 	return (ret);
3472 }
3473 
3474 int
3475 sig_ast_needsigchk(struct thread *td)
3476 {
3477 	struct proc *p;
3478 	struct sigacts *ps;
3479 	int ret, sig;
3480 
3481 	p = td->td_proc;
3482 	PROC_LOCK_ASSERT(p, MA_OWNED);
3483 
3484 	if (!td_ast_pending(td, TDA_SIG))
3485 		return (0);
3486 
3487 	ps = p->p_sigacts;
3488 	mtx_lock(&ps->ps_mtx);
3489 	sig = cursig(td);
3490 	if (sig == -1) {
3491 		mtx_unlock(&ps->ps_mtx);
3492 		KASSERT((td->td_flags & TDF_SBDRY) != 0, ("lost TDF_SBDRY"));
3493 		KASSERT(TD_SBDRY_INTR(td),
3494 		    ("lost TDF_SERESTART of TDF_SEINTR"));
3495 		KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
3496 		    (TDF_SEINTR | TDF_SERESTART),
3497 		    ("both TDF_SEINTR and TDF_SERESTART"));
3498 		ret = TD_SBDRY_ERRNO(td);
3499 	} else if (sig != 0) {
3500 		ret = SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR : ERESTART;
3501 		mtx_unlock(&ps->ps_mtx);
3502 	} else {
3503 		mtx_unlock(&ps->ps_mtx);
3504 		ret = 0;
3505 	}
3506 
3507 	/*
3508 	 * Do not go into sleep if this thread was the ptrace(2)
3509 	 * attach leader.  cursig() consumed SIGSTOP from PT_ATTACH,
3510 	 * but we usually act on the signal by interrupting sleep, and
3511 	 * should do that here as well.
3512 	 */
3513 	if ((td->td_dbgflags & TDB_FSTP) != 0) {
3514 		if (ret == 0)
3515 			ret = EINTR;
3516 		td->td_dbgflags &= ~TDB_FSTP;
3517 	}
3518 
3519 	return (ret);
3520 }
3521 
3522 int
3523 sig_intr(void)
3524 {
3525 	struct thread *td;
3526 	struct proc *p;
3527 	int ret;
3528 
3529 	td = curthread;
3530 	if (!td_ast_pending(td, TDA_SIG) && !td_ast_pending(td, TDA_SUSPEND))
3531 		return (0);
3532 
3533 	p = td->td_proc;
3534 
3535 	PROC_LOCK(p);
3536 	ret = sig_ast_checksusp(td);
3537 	if (ret == 0)
3538 		ret = sig_ast_needsigchk(td);
3539 	PROC_UNLOCK(p);
3540 	return (ret);
3541 }
3542 
3543 bool
3544 curproc_sigkilled(void)
3545 {
3546 	struct thread *td;
3547 	struct proc *p;
3548 	struct sigacts *ps;
3549 	bool res;
3550 
3551 	td = curthread;
3552 	if (!td_ast_pending(td, TDA_SIG))
3553 		return (false);
3554 
3555 	p = td->td_proc;
3556 	PROC_LOCK(p);
3557 	ps = p->p_sigacts;
3558 	mtx_lock(&ps->ps_mtx);
3559 	res = SIGISMEMBER(td->td_sigqueue.sq_signals, SIGKILL) ||
3560 	    SIGISMEMBER(p->p_sigqueue.sq_signals, SIGKILL);
3561 	mtx_unlock(&ps->ps_mtx);
3562 	PROC_UNLOCK(p);
3563 	return (res);
3564 }
3565 
3566 void
3567 proc_wkilled(struct proc *p)
3568 {
3569 
3570 	PROC_LOCK_ASSERT(p, MA_OWNED);
3571 	if ((p->p_flag & P_WKILLED) == 0) {
3572 		p->p_flag |= P_WKILLED;
3573 		/*
3574 		 * Notify swapper that there is a process to swap in.
3575 		 * The notification is racy, at worst it would take 10
3576 		 * seconds for the swapper process to notice.
3577 		 */
3578 		if ((p->p_flag & (P_INMEM | P_SWAPPINGIN)) == 0)
3579 			wakeup(&proc0);
3580 	}
3581 }
3582 
3583 /*
3584  * Kill the current process for stated reason.
3585  */
3586 void
3587 killproc(struct proc *p, const char *why)
3588 {
3589 
3590 	PROC_LOCK_ASSERT(p, MA_OWNED);
3591 	CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
3592 	    p->p_comm);
3593 	log(LOG_ERR, "pid %d (%s), jid %d, uid %d, was killed: %s\n",
3594 	    p->p_pid, p->p_comm, p->p_ucred->cr_prison->pr_id,
3595 	    p->p_ucred->cr_uid, why);
3596 	proc_wkilled(p);
3597 	kern_psignal(p, SIGKILL);
3598 }
3599 
3600 /*
3601  * Force the current process to exit with the specified signal, dumping core
3602  * if appropriate.  We bypass the normal tests for masked and caught signals,
3603  * allowing unrecoverable failures to terminate the process without changing
3604  * signal state.  Mark the accounting record with the signal termination.
3605  * If dumping core, save the signal number for the debugger.  Calls exit and
3606  * does not return.
3607  */
3608 void
3609 sigexit(struct thread *td, int sig)
3610 {
3611 	struct proc *p = td->td_proc;
3612 	const char *coreinfo;
3613 	int rv;
3614 
3615 	PROC_LOCK_ASSERT(p, MA_OWNED);
3616 	proc_set_p2_wexit(p);
3617 
3618 	p->p_acflag |= AXSIG;
3619 	/*
3620 	 * We must be single-threading to generate a core dump.  This
3621 	 * ensures that the registers in the core file are up-to-date.
3622 	 * Also, the ELF dump handler assumes that the thread list doesn't
3623 	 * change out from under it.
3624 	 *
3625 	 * XXX If another thread attempts to single-thread before us
3626 	 *     (e.g. via fork()), we won't get a dump at all.
3627 	 */
3628 	if ((sigprop(sig) & SIGPROP_CORE) &&
3629 	    thread_single(p, SINGLE_NO_EXIT) == 0) {
3630 		p->p_sig = sig;
3631 		/*
3632 		 * Log signals which would cause core dumps
3633 		 * (Log as LOG_INFO to appease those who don't want
3634 		 * these messages.)
3635 		 * XXX : Todo, as well as euid, write out ruid too
3636 		 * Note that coredump() drops proc lock.
3637 		 */
3638 		rv = coredump(td);
3639 		switch (rv) {
3640 		case 0:
3641 			sig |= WCOREFLAG;
3642 			coreinfo = " (core dumped)";
3643 			break;
3644 		case EFAULT:
3645 			coreinfo = " (no core dump - bad address)";
3646 			break;
3647 		case EINVAL:
3648 			coreinfo = " (no core dump - invalid argument)";
3649 			break;
3650 		case EFBIG:
3651 			coreinfo = " (no core dump - too large)";
3652 			break;
3653 		default:
3654 			coreinfo = " (no core dump - other error)";
3655 			break;
3656 		}
3657 		if (kern_logsigexit)
3658 			log(LOG_INFO,
3659 			    "pid %d (%s), jid %d, uid %d: exited on "
3660 			    "signal %d%s\n", p->p_pid, p->p_comm,
3661 			    p->p_ucred->cr_prison->pr_id,
3662 			    td->td_ucred->cr_uid,
3663 			    sig &~ WCOREFLAG, coreinfo);
3664 	} else
3665 		PROC_UNLOCK(p);
3666 	exit1(td, 0, sig);
3667 	/* NOTREACHED */
3668 }
3669 
3670 /*
3671  * Send queued SIGCHLD to parent when child process's state
3672  * is changed.
3673  */
3674 static void
3675 sigparent(struct proc *p, int reason, int status)
3676 {
3677 	PROC_LOCK_ASSERT(p, MA_OWNED);
3678 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3679 
3680 	if (p->p_ksi != NULL) {
3681 		p->p_ksi->ksi_signo  = SIGCHLD;
3682 		p->p_ksi->ksi_code   = reason;
3683 		p->p_ksi->ksi_status = status;
3684 		p->p_ksi->ksi_pid    = p->p_pid;
3685 		p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
3686 		if (KSI_ONQ(p->p_ksi))
3687 			return;
3688 	}
3689 	pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
3690 }
3691 
3692 static void
3693 childproc_jobstate(struct proc *p, int reason, int sig)
3694 {
3695 	struct sigacts *ps;
3696 
3697 	PROC_LOCK_ASSERT(p, MA_OWNED);
3698 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3699 
3700 	/*
3701 	 * Wake up parent sleeping in kern_wait(), also send
3702 	 * SIGCHLD to parent, but SIGCHLD does not guarantee
3703 	 * that parent will awake, because parent may masked
3704 	 * the signal.
3705 	 */
3706 	p->p_pptr->p_flag |= P_STATCHILD;
3707 	wakeup(p->p_pptr);
3708 
3709 	ps = p->p_pptr->p_sigacts;
3710 	mtx_lock(&ps->ps_mtx);
3711 	if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
3712 		mtx_unlock(&ps->ps_mtx);
3713 		sigparent(p, reason, sig);
3714 	} else
3715 		mtx_unlock(&ps->ps_mtx);
3716 }
3717 
3718 void
3719 childproc_stopped(struct proc *p, int reason)
3720 {
3721 
3722 	childproc_jobstate(p, reason, p->p_xsig);
3723 }
3724 
3725 void
3726 childproc_continued(struct proc *p)
3727 {
3728 	childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
3729 }
3730 
3731 void
3732 childproc_exited(struct proc *p)
3733 {
3734 	int reason, status;
3735 
3736 	if (WCOREDUMP(p->p_xsig)) {
3737 		reason = CLD_DUMPED;
3738 		status = WTERMSIG(p->p_xsig);
3739 	} else if (WIFSIGNALED(p->p_xsig)) {
3740 		reason = CLD_KILLED;
3741 		status = WTERMSIG(p->p_xsig);
3742 	} else {
3743 		reason = CLD_EXITED;
3744 		status = p->p_xexit;
3745 	}
3746 	/*
3747 	 * XXX avoid calling wakeup(p->p_pptr), the work is
3748 	 * done in exit1().
3749 	 */
3750 	sigparent(p, reason, status);
3751 }
3752 
3753 #define	MAX_NUM_CORE_FILES 100000
3754 #ifndef NUM_CORE_FILES
3755 #define	NUM_CORE_FILES 5
3756 #endif
3757 CTASSERT(NUM_CORE_FILES >= 0 && NUM_CORE_FILES <= MAX_NUM_CORE_FILES);
3758 static int num_cores = NUM_CORE_FILES;
3759 
3760 static int
3761 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3762 {
3763 	int error;
3764 	int new_val;
3765 
3766 	new_val = num_cores;
3767 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3768 	if (error != 0 || req->newptr == NULL)
3769 		return (error);
3770 	if (new_val > MAX_NUM_CORE_FILES)
3771 		new_val = MAX_NUM_CORE_FILES;
3772 	if (new_val < 0)
3773 		new_val = 0;
3774 	num_cores = new_val;
3775 	return (0);
3776 }
3777 SYSCTL_PROC(_debug, OID_AUTO, ncores,
3778     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(int),
3779     sysctl_debug_num_cores_check, "I",
3780     "Maximum number of generated process corefiles while using index format");
3781 
3782 #define	GZIP_SUFFIX	".gz"
3783 #define	ZSTD_SUFFIX	".zst"
3784 
3785 int compress_user_cores = 0;
3786 
3787 static int
3788 sysctl_compress_user_cores(SYSCTL_HANDLER_ARGS)
3789 {
3790 	int error, val;
3791 
3792 	val = compress_user_cores;
3793 	error = sysctl_handle_int(oidp, &val, 0, req);
3794 	if (error != 0 || req->newptr == NULL)
3795 		return (error);
3796 	if (val != 0 && !compressor_avail(val))
3797 		return (EINVAL);
3798 	compress_user_cores = val;
3799 	return (error);
3800 }
3801 SYSCTL_PROC(_kern, OID_AUTO, compress_user_cores,
3802     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, 0, sizeof(int),
3803     sysctl_compress_user_cores, "I",
3804     "Enable compression of user corefiles ("
3805     __XSTRING(COMPRESS_GZIP) " = gzip, "
3806     __XSTRING(COMPRESS_ZSTD) " = zstd)");
3807 
3808 int compress_user_cores_level = 6;
3809 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_level, CTLFLAG_RWTUN,
3810     &compress_user_cores_level, 0,
3811     "Corefile compression level");
3812 
3813 /*
3814  * Protect the access to corefilename[] by allproc_lock.
3815  */
3816 #define	corefilename_lock	allproc_lock
3817 
3818 static char corefilename[MAXPATHLEN] = {"%N.core"};
3819 TUNABLE_STR("kern.corefile", corefilename, sizeof(corefilename));
3820 
3821 static int
3822 sysctl_kern_corefile(SYSCTL_HANDLER_ARGS)
3823 {
3824 	int error;
3825 
3826 	sx_xlock(&corefilename_lock);
3827 	error = sysctl_handle_string(oidp, corefilename, sizeof(corefilename),
3828 	    req);
3829 	sx_xunlock(&corefilename_lock);
3830 
3831 	return (error);
3832 }
3833 SYSCTL_PROC(_kern, OID_AUTO, corefile, CTLTYPE_STRING | CTLFLAG_RW |
3834     CTLFLAG_MPSAFE, 0, 0, sysctl_kern_corefile, "A",
3835     "Process corefile name format string");
3836 
3837 static void
3838 vnode_close_locked(struct thread *td, struct vnode *vp)
3839 {
3840 
3841 	VOP_UNLOCK(vp);
3842 	vn_close(vp, FWRITE, td->td_ucred, td);
3843 }
3844 
3845 /*
3846  * If the core format has a %I in it, then we need to check
3847  * for existing corefiles before defining a name.
3848  * To do this we iterate over 0..ncores to find a
3849  * non-existing core file name to use. If all core files are
3850  * already used we choose the oldest one.
3851  */
3852 static int
3853 corefile_open_last(struct thread *td, char *name, int indexpos,
3854     int indexlen, int ncores, struct vnode **vpp)
3855 {
3856 	struct vnode *oldvp, *nextvp, *vp;
3857 	struct vattr vattr;
3858 	struct nameidata nd;
3859 	int error, i, flags, oflags, cmode;
3860 	char ch;
3861 	struct timespec lasttime;
3862 
3863 	nextvp = oldvp = NULL;
3864 	cmode = S_IRUSR | S_IWUSR;
3865 	oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3866 	    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3867 
3868 	for (i = 0; i < ncores; i++) {
3869 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
3870 
3871 		ch = name[indexpos + indexlen];
3872 		(void)snprintf(name + indexpos, indexlen + 1, "%.*u", indexlen,
3873 		    i);
3874 		name[indexpos + indexlen] = ch;
3875 
3876 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name);
3877 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3878 		    NULL);
3879 		if (error != 0)
3880 			break;
3881 
3882 		vp = nd.ni_vp;
3883 		NDFREE_PNBUF(&nd);
3884 		if ((flags & O_CREAT) == O_CREAT) {
3885 			nextvp = vp;
3886 			break;
3887 		}
3888 
3889 		error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3890 		if (error != 0) {
3891 			vnode_close_locked(td, vp);
3892 			break;
3893 		}
3894 
3895 		if (oldvp == NULL ||
3896 		    lasttime.tv_sec > vattr.va_mtime.tv_sec ||
3897 		    (lasttime.tv_sec == vattr.va_mtime.tv_sec &&
3898 		    lasttime.tv_nsec >= vattr.va_mtime.tv_nsec)) {
3899 			if (oldvp != NULL)
3900 				vn_close(oldvp, FWRITE, td->td_ucred, td);
3901 			oldvp = vp;
3902 			VOP_UNLOCK(oldvp);
3903 			lasttime = vattr.va_mtime;
3904 		} else {
3905 			vnode_close_locked(td, vp);
3906 		}
3907 	}
3908 
3909 	if (oldvp != NULL) {
3910 		if (nextvp == NULL) {
3911 			if ((td->td_proc->p_flag & P_SUGID) != 0) {
3912 				error = EFAULT;
3913 				vn_close(oldvp, FWRITE, td->td_ucred, td);
3914 			} else {
3915 				nextvp = oldvp;
3916 				error = vn_lock(nextvp, LK_EXCLUSIVE);
3917 				if (error != 0) {
3918 					vn_close(nextvp, FWRITE, td->td_ucred,
3919 					    td);
3920 					nextvp = NULL;
3921 				}
3922 			}
3923 		} else {
3924 			vn_close(oldvp, FWRITE, td->td_ucred, td);
3925 		}
3926 	}
3927 	if (error != 0) {
3928 		if (nextvp != NULL)
3929 			vnode_close_locked(td, oldvp);
3930 	} else {
3931 		*vpp = nextvp;
3932 	}
3933 
3934 	return (error);
3935 }
3936 
3937 /*
3938  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3939  * Expand the name described in corefilename, using name, uid, and pid
3940  * and open/create core file.
3941  * corefilename is a printf-like string, with three format specifiers:
3942  *	%N	name of process ("name")
3943  *	%P	process id (pid)
3944  *	%U	user id (uid)
3945  * For example, "%N.core" is the default; they can be disabled completely
3946  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3947  * This is controlled by the sysctl variable kern.corefile (see above).
3948  */
3949 static int
3950 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3951     int compress, int signum, struct vnode **vpp, char **namep)
3952 {
3953 	struct sbuf sb;
3954 	struct nameidata nd;
3955 	const char *format;
3956 	char *hostname, *name;
3957 	int cmode, error, flags, i, indexpos, indexlen, oflags, ncores;
3958 
3959 	hostname = NULL;
3960 	format = corefilename;
3961 	name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3962 	indexlen = 0;
3963 	indexpos = -1;
3964 	ncores = num_cores;
3965 	(void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3966 	sx_slock(&corefilename_lock);
3967 	for (i = 0; format[i] != '\0'; i++) {
3968 		switch (format[i]) {
3969 		case '%':	/* Format character */
3970 			i++;
3971 			switch (format[i]) {
3972 			case '%':
3973 				sbuf_putc(&sb, '%');
3974 				break;
3975 			case 'H':	/* hostname */
3976 				if (hostname == NULL) {
3977 					hostname = malloc(MAXHOSTNAMELEN,
3978 					    M_TEMP, M_WAITOK);
3979 				}
3980 				getcredhostname(td->td_ucred, hostname,
3981 				    MAXHOSTNAMELEN);
3982 				sbuf_cat(&sb, hostname);
3983 				break;
3984 			case 'I':	/* autoincrementing index */
3985 				if (indexpos != -1) {
3986 					sbuf_printf(&sb, "%%I");
3987 					break;
3988 				}
3989 
3990 				indexpos = sbuf_len(&sb);
3991 				sbuf_printf(&sb, "%u", ncores - 1);
3992 				indexlen = sbuf_len(&sb) - indexpos;
3993 				break;
3994 			case 'N':	/* process name */
3995 				sbuf_printf(&sb, "%s", comm);
3996 				break;
3997 			case 'P':	/* process id */
3998 				sbuf_printf(&sb, "%u", pid);
3999 				break;
4000 			case 'S':	/* signal number */
4001 				sbuf_printf(&sb, "%i", signum);
4002 				break;
4003 			case 'U':	/* user id */
4004 				sbuf_printf(&sb, "%u", uid);
4005 				break;
4006 			default:
4007 				log(LOG_ERR,
4008 				    "Unknown format character %c in "
4009 				    "corename `%s'\n", format[i], format);
4010 				break;
4011 			}
4012 			break;
4013 		default:
4014 			sbuf_putc(&sb, format[i]);
4015 			break;
4016 		}
4017 	}
4018 	sx_sunlock(&corefilename_lock);
4019 	free(hostname, M_TEMP);
4020 	if (compress == COMPRESS_GZIP)
4021 		sbuf_cat(&sb, GZIP_SUFFIX);
4022 	else if (compress == COMPRESS_ZSTD)
4023 		sbuf_cat(&sb, ZSTD_SUFFIX);
4024 	if (sbuf_error(&sb) != 0) {
4025 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
4026 		    "long\n", (long)pid, comm, (u_long)uid);
4027 		sbuf_delete(&sb);
4028 		free(name, M_TEMP);
4029 		return (ENOMEM);
4030 	}
4031 	sbuf_finish(&sb);
4032 	sbuf_delete(&sb);
4033 
4034 	if (indexpos != -1) {
4035 		error = corefile_open_last(td, name, indexpos, indexlen, ncores,
4036 		    vpp);
4037 		if (error != 0) {
4038 			log(LOG_ERR,
4039 			    "pid %d (%s), uid (%u):  Path `%s' failed "
4040 			    "on initial open test, error = %d\n",
4041 			    pid, comm, uid, name, error);
4042 		}
4043 	} else {
4044 		cmode = S_IRUSR | S_IWUSR;
4045 		oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
4046 		    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
4047 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
4048 		if ((td->td_proc->p_flag & P_SUGID) != 0)
4049 			flags |= O_EXCL;
4050 
4051 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name);
4052 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
4053 		    NULL);
4054 		if (error == 0) {
4055 			*vpp = nd.ni_vp;
4056 			NDFREE_PNBUF(&nd);
4057 		}
4058 	}
4059 
4060 	if (error != 0) {
4061 #ifdef AUDIT
4062 		audit_proc_coredump(td, name, error);
4063 #endif
4064 		free(name, M_TEMP);
4065 		return (error);
4066 	}
4067 	*namep = name;
4068 	return (0);
4069 }
4070 
4071 /*
4072  * Dump a process' core.  The main routine does some
4073  * policy checking, and creates the name of the coredump;
4074  * then it passes on a vnode and a size limit to the process-specific
4075  * coredump routine if there is one; if there _is not_ one, it returns
4076  * ENOSYS; otherwise it returns the error from the process-specific routine.
4077  */
4078 
4079 static int
4080 coredump(struct thread *td)
4081 {
4082 	struct proc *p = td->td_proc;
4083 	struct ucred *cred = td->td_ucred;
4084 	struct vnode *vp;
4085 	struct flock lf;
4086 	struct vattr vattr;
4087 	size_t fullpathsize;
4088 	int error, error1, locked;
4089 	char *name;			/* name of corefile */
4090 	void *rl_cookie;
4091 	off_t limit;
4092 	char *fullpath, *freepath = NULL;
4093 	struct sbuf *sb;
4094 
4095 	PROC_LOCK_ASSERT(p, MA_OWNED);
4096 	MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
4097 
4098 	if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0) ||
4099 	    (p->p_flag2 & P2_NOTRACE) != 0) {
4100 		PROC_UNLOCK(p);
4101 		return (EFAULT);
4102 	}
4103 
4104 	/*
4105 	 * Note that the bulk of limit checking is done after
4106 	 * the corefile is created.  The exception is if the limit
4107 	 * for corefiles is 0, in which case we don't bother
4108 	 * creating the corefile at all.  This layout means that
4109 	 * a corefile is truncated instead of not being created,
4110 	 * if it is larger than the limit.
4111 	 */
4112 	limit = (off_t)lim_cur(td, RLIMIT_CORE);
4113 	if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
4114 		PROC_UNLOCK(p);
4115 		return (EFBIG);
4116 	}
4117 	PROC_UNLOCK(p);
4118 
4119 	error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td,
4120 	    compress_user_cores, p->p_sig, &vp, &name);
4121 	if (error != 0)
4122 		return (error);
4123 
4124 	/*
4125 	 * Don't dump to non-regular files or files with links.
4126 	 * Do not dump into system files. Effective user must own the corefile.
4127 	 */
4128 	if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
4129 	    vattr.va_nlink != 1 || (vp->v_vflag & VV_SYSTEM) != 0 ||
4130 	    vattr.va_uid != cred->cr_uid) {
4131 		VOP_UNLOCK(vp);
4132 		error = EFAULT;
4133 		goto out;
4134 	}
4135 
4136 	VOP_UNLOCK(vp);
4137 
4138 	/* Postpone other writers, including core dumps of other processes. */
4139 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
4140 
4141 	lf.l_whence = SEEK_SET;
4142 	lf.l_start = 0;
4143 	lf.l_len = 0;
4144 	lf.l_type = F_WRLCK;
4145 	locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
4146 
4147 	VATTR_NULL(&vattr);
4148 	vattr.va_size = 0;
4149 	if (set_core_nodump_flag)
4150 		vattr.va_flags = UF_NODUMP;
4151 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4152 	VOP_SETATTR(vp, &vattr, cred);
4153 	VOP_UNLOCK(vp);
4154 	PROC_LOCK(p);
4155 	p->p_acflag |= ACORE;
4156 	PROC_UNLOCK(p);
4157 
4158 	if (p->p_sysent->sv_coredump != NULL) {
4159 		error = p->p_sysent->sv_coredump(td, vp, limit, 0);
4160 	} else {
4161 		error = ENOSYS;
4162 	}
4163 
4164 	if (locked) {
4165 		lf.l_type = F_UNLCK;
4166 		VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
4167 	}
4168 	vn_rangelock_unlock(vp, rl_cookie);
4169 
4170 	/*
4171 	 * Notify the userland helper that a process triggered a core dump.
4172 	 * This allows the helper to run an automated debugging session.
4173 	 */
4174 	if (error != 0 || coredump_devctl == 0)
4175 		goto out;
4176 	sb = sbuf_new_auto();
4177 	if (vn_fullpath_global(p->p_textvp, &fullpath, &freepath) != 0)
4178 		goto out2;
4179 	sbuf_cat(sb, "comm=\"");
4180 	devctl_safe_quote_sb(sb, fullpath);
4181 	free(freepath, M_TEMP);
4182 	sbuf_cat(sb, "\" core=\"");
4183 
4184 	/*
4185 	 * We can't lookup core file vp directly. When we're replacing a core, and
4186 	 * other random times, we flush the name cache, so it will fail. Instead,
4187 	 * if the path of the core is relative, add the current dir in front if it.
4188 	 */
4189 	if (name[0] != '/') {
4190 		fullpathsize = MAXPATHLEN;
4191 		freepath = malloc(fullpathsize, M_TEMP, M_WAITOK);
4192 		if (vn_getcwd(freepath, &fullpath, &fullpathsize) != 0) {
4193 			free(freepath, M_TEMP);
4194 			goto out2;
4195 		}
4196 		devctl_safe_quote_sb(sb, fullpath);
4197 		free(freepath, M_TEMP);
4198 		sbuf_putc(sb, '/');
4199 	}
4200 	devctl_safe_quote_sb(sb, name);
4201 	sbuf_putc(sb, '"');
4202 	if (sbuf_finish(sb) == 0)
4203 		devctl_notify("kernel", "signal", "coredump", sbuf_data(sb));
4204 out2:
4205 	sbuf_delete(sb);
4206 out:
4207 	error1 = vn_close(vp, FWRITE, cred, td);
4208 	if (error == 0)
4209 		error = error1;
4210 #ifdef AUDIT
4211 	audit_proc_coredump(td, name, error);
4212 #endif
4213 	free(name, M_TEMP);
4214 	return (error);
4215 }
4216 
4217 /*
4218  * Nonexistent system call-- signal process (may want to handle it).  Flag
4219  * error in case process won't see signal immediately (blocked or ignored).
4220  */
4221 #ifndef _SYS_SYSPROTO_H_
4222 struct nosys_args {
4223 	int	dummy;
4224 };
4225 #endif
4226 /* ARGSUSED */
4227 int
4228 nosys(struct thread *td, struct nosys_args *args)
4229 {
4230 	struct proc *p;
4231 
4232 	p = td->td_proc;
4233 
4234 	if (SV_PROC_FLAG(p, SV_SIGSYS) != 0 && kern_signosys) {
4235 		PROC_LOCK(p);
4236 		tdsignal(td, SIGSYS);
4237 		PROC_UNLOCK(p);
4238 	}
4239 	if (kern_lognosys == 1 || kern_lognosys == 3) {
4240 		uprintf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
4241 		    td->td_sa.code);
4242 	}
4243 	if (kern_lognosys == 2 || kern_lognosys == 3 ||
4244 	    (p->p_pid == 1 && (kern_lognosys & 3) == 0)) {
4245 		printf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
4246 		    td->td_sa.code);
4247 	}
4248 	return (ENOSYS);
4249 }
4250 
4251 /*
4252  * Send a SIGIO or SIGURG signal to a process or process group using stored
4253  * credentials rather than those of the current process.
4254  */
4255 void
4256 pgsigio(struct sigio **sigiop, int sig, int checkctty)
4257 {
4258 	ksiginfo_t ksi;
4259 	struct sigio *sigio;
4260 
4261 	ksiginfo_init(&ksi);
4262 	ksi.ksi_signo = sig;
4263 	ksi.ksi_code = SI_KERNEL;
4264 
4265 	SIGIO_LOCK();
4266 	sigio = *sigiop;
4267 	if (sigio == NULL) {
4268 		SIGIO_UNLOCK();
4269 		return;
4270 	}
4271 	if (sigio->sio_pgid > 0) {
4272 		PROC_LOCK(sigio->sio_proc);
4273 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
4274 			kern_psignal(sigio->sio_proc, sig);
4275 		PROC_UNLOCK(sigio->sio_proc);
4276 	} else if (sigio->sio_pgid < 0) {
4277 		struct proc *p;
4278 
4279 		PGRP_LOCK(sigio->sio_pgrp);
4280 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
4281 			PROC_LOCK(p);
4282 			if (p->p_state == PRS_NORMAL &&
4283 			    CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
4284 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
4285 				kern_psignal(p, sig);
4286 			PROC_UNLOCK(p);
4287 		}
4288 		PGRP_UNLOCK(sigio->sio_pgrp);
4289 	}
4290 	SIGIO_UNLOCK();
4291 }
4292 
4293 static int
4294 filt_sigattach(struct knote *kn)
4295 {
4296 	struct proc *p = curproc;
4297 
4298 	kn->kn_ptr.p_proc = p;
4299 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
4300 
4301 	knlist_add(p->p_klist, kn, 0);
4302 
4303 	return (0);
4304 }
4305 
4306 static void
4307 filt_sigdetach(struct knote *kn)
4308 {
4309 	knlist_remove(kn->kn_knlist, kn, 0);
4310 }
4311 
4312 /*
4313  * signal knotes are shared with proc knotes, so we apply a mask to
4314  * the hint in order to differentiate them from process hints.  This
4315  * could be avoided by using a signal-specific knote list, but probably
4316  * isn't worth the trouble.
4317  */
4318 static int
4319 filt_signal(struct knote *kn, long hint)
4320 {
4321 
4322 	if (hint & NOTE_SIGNAL) {
4323 		hint &= ~NOTE_SIGNAL;
4324 
4325 		if (kn->kn_id == hint)
4326 			kn->kn_data++;
4327 	}
4328 	return (kn->kn_data != 0);
4329 }
4330 
4331 struct sigacts *
4332 sigacts_alloc(void)
4333 {
4334 	struct sigacts *ps;
4335 
4336 	ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
4337 	refcount_init(&ps->ps_refcnt, 1);
4338 	mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
4339 	return (ps);
4340 }
4341 
4342 void
4343 sigacts_free(struct sigacts *ps)
4344 {
4345 
4346 	if (refcount_release(&ps->ps_refcnt) == 0)
4347 		return;
4348 	mtx_destroy(&ps->ps_mtx);
4349 	free(ps, M_SUBPROC);
4350 }
4351 
4352 struct sigacts *
4353 sigacts_hold(struct sigacts *ps)
4354 {
4355 
4356 	refcount_acquire(&ps->ps_refcnt);
4357 	return (ps);
4358 }
4359 
4360 void
4361 sigacts_copy(struct sigacts *dest, struct sigacts *src)
4362 {
4363 
4364 	KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
4365 	mtx_lock(&src->ps_mtx);
4366 	bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
4367 	mtx_unlock(&src->ps_mtx);
4368 }
4369 
4370 int
4371 sigacts_shared(struct sigacts *ps)
4372 {
4373 
4374 	return (ps->ps_refcnt > 1);
4375 }
4376 
4377 void
4378 sig_drop_caught(struct proc *p)
4379 {
4380 	int sig;
4381 	struct sigacts *ps;
4382 
4383 	ps = p->p_sigacts;
4384 	PROC_LOCK_ASSERT(p, MA_OWNED);
4385 	mtx_assert(&ps->ps_mtx, MA_OWNED);
4386 	SIG_FOREACH(sig, &ps->ps_sigcatch) {
4387 		sigdflt(ps, sig);
4388 		if ((sigprop(sig) & SIGPROP_IGNORE) != 0)
4389 			sigqueue_delete_proc(p, sig);
4390 	}
4391 }
4392 
4393 static void
4394 sigfastblock_failed(struct thread *td, bool sendsig, bool write)
4395 {
4396 	ksiginfo_t ksi;
4397 
4398 	/*
4399 	 * Prevent further fetches and SIGSEGVs, allowing thread to
4400 	 * issue syscalls despite corruption.
4401 	 */
4402 	sigfastblock_clear(td);
4403 
4404 	if (!sendsig)
4405 		return;
4406 	ksiginfo_init_trap(&ksi);
4407 	ksi.ksi_signo = SIGSEGV;
4408 	ksi.ksi_code = write ? SEGV_ACCERR : SEGV_MAPERR;
4409 	ksi.ksi_addr = td->td_sigblock_ptr;
4410 	trapsignal(td, &ksi);
4411 }
4412 
4413 static bool
4414 sigfastblock_fetch_sig(struct thread *td, bool sendsig, uint32_t *valp)
4415 {
4416 	uint32_t res;
4417 
4418 	if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4419 		return (true);
4420 	if (fueword32((void *)td->td_sigblock_ptr, &res) == -1) {
4421 		sigfastblock_failed(td, sendsig, false);
4422 		return (false);
4423 	}
4424 	*valp = res;
4425 	td->td_sigblock_val = res & ~SIGFASTBLOCK_FLAGS;
4426 	return (true);
4427 }
4428 
4429 static void
4430 sigfastblock_resched(struct thread *td, bool resched)
4431 {
4432 	struct proc *p;
4433 
4434 	if (resched) {
4435 		p = td->td_proc;
4436 		PROC_LOCK(p);
4437 		reschedule_signals(p, td->td_sigmask, 0);
4438 		PROC_UNLOCK(p);
4439 	}
4440 	ast_sched(td, TDA_SIG);
4441 }
4442 
4443 int
4444 sys_sigfastblock(struct thread *td, struct sigfastblock_args *uap)
4445 {
4446 	struct proc *p;
4447 	int error, res;
4448 	uint32_t oldval;
4449 
4450 	error = 0;
4451 	p = td->td_proc;
4452 	switch (uap->cmd) {
4453 	case SIGFASTBLOCK_SETPTR:
4454 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
4455 			error = EBUSY;
4456 			break;
4457 		}
4458 		if (((uintptr_t)(uap->ptr) & (sizeof(uint32_t) - 1)) != 0) {
4459 			error = EINVAL;
4460 			break;
4461 		}
4462 		td->td_pflags |= TDP_SIGFASTBLOCK;
4463 		td->td_sigblock_ptr = uap->ptr;
4464 		break;
4465 
4466 	case SIGFASTBLOCK_UNBLOCK:
4467 		if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4468 			error = EINVAL;
4469 			break;
4470 		}
4471 
4472 		for (;;) {
4473 			res = casueword32(td->td_sigblock_ptr,
4474 			    SIGFASTBLOCK_PEND, &oldval, 0);
4475 			if (res == -1) {
4476 				error = EFAULT;
4477 				sigfastblock_failed(td, false, true);
4478 				break;
4479 			}
4480 			if (res == 0)
4481 				break;
4482 			MPASS(res == 1);
4483 			if (oldval != SIGFASTBLOCK_PEND) {
4484 				error = EBUSY;
4485 				break;
4486 			}
4487 			error = thread_check_susp(td, false);
4488 			if (error != 0)
4489 				break;
4490 		}
4491 		if (error != 0)
4492 			break;
4493 
4494 		/*
4495 		 * td_sigblock_val is cleared there, but not on a
4496 		 * syscall exit.  The end effect is that a single
4497 		 * interruptible sleep, while user sigblock word is
4498 		 * set, might return EINTR or ERESTART to usermode
4499 		 * without delivering signal.  All further sleeps,
4500 		 * until userspace clears the word and does
4501 		 * sigfastblock(UNBLOCK), observe current word and no
4502 		 * longer get interrupted.  It is slight
4503 		 * non-conformance, with alternative to have read the
4504 		 * sigblock word on each syscall entry.
4505 		 */
4506 		td->td_sigblock_val = 0;
4507 
4508 		/*
4509 		 * Rely on normal ast mechanism to deliver pending
4510 		 * signals to current thread.  But notify others about
4511 		 * fake unblock.
4512 		 */
4513 		sigfastblock_resched(td, error == 0 && p->p_numthreads != 1);
4514 
4515 		break;
4516 
4517 	case SIGFASTBLOCK_UNSETPTR:
4518 		if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4519 			error = EINVAL;
4520 			break;
4521 		}
4522 		if (!sigfastblock_fetch_sig(td, false, &oldval)) {
4523 			error = EFAULT;
4524 			break;
4525 		}
4526 		if (oldval != 0 && oldval != SIGFASTBLOCK_PEND) {
4527 			error = EBUSY;
4528 			break;
4529 		}
4530 		sigfastblock_clear(td);
4531 		break;
4532 
4533 	default:
4534 		error = EINVAL;
4535 		break;
4536 	}
4537 	return (error);
4538 }
4539 
4540 void
4541 sigfastblock_clear(struct thread *td)
4542 {
4543 	bool resched;
4544 
4545 	if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4546 		return;
4547 	td->td_sigblock_val = 0;
4548 	resched = (td->td_pflags & TDP_SIGFASTPENDING) != 0 ||
4549 	    SIGPENDING(td);
4550 	td->td_pflags &= ~(TDP_SIGFASTBLOCK | TDP_SIGFASTPENDING);
4551 	sigfastblock_resched(td, resched);
4552 }
4553 
4554 void
4555 sigfastblock_fetch(struct thread *td)
4556 {
4557 	uint32_t val;
4558 
4559 	(void)sigfastblock_fetch_sig(td, true, &val);
4560 }
4561 
4562 static void
4563 sigfastblock_setpend1(struct thread *td)
4564 {
4565 	int res;
4566 	uint32_t oldval;
4567 
4568 	if ((td->td_pflags & TDP_SIGFASTPENDING) == 0)
4569 		return;
4570 	res = fueword32((void *)td->td_sigblock_ptr, &oldval);
4571 	if (res == -1) {
4572 		sigfastblock_failed(td, true, false);
4573 		return;
4574 	}
4575 	for (;;) {
4576 		res = casueword32(td->td_sigblock_ptr, oldval, &oldval,
4577 		    oldval | SIGFASTBLOCK_PEND);
4578 		if (res == -1) {
4579 			sigfastblock_failed(td, true, true);
4580 			return;
4581 		}
4582 		if (res == 0) {
4583 			td->td_sigblock_val = oldval & ~SIGFASTBLOCK_FLAGS;
4584 			td->td_pflags &= ~TDP_SIGFASTPENDING;
4585 			break;
4586 		}
4587 		MPASS(res == 1);
4588 		if (thread_check_susp(td, false) != 0)
4589 			break;
4590 	}
4591 }
4592 
4593 static void
4594 sigfastblock_setpend(struct thread *td, bool resched)
4595 {
4596 	struct proc *p;
4597 
4598 	sigfastblock_setpend1(td);
4599 	if (resched) {
4600 		p = td->td_proc;
4601 		PROC_LOCK(p);
4602 		reschedule_signals(p, fastblock_mask, SIGPROCMASK_FASTBLK);
4603 		PROC_UNLOCK(p);
4604 	}
4605 }
4606