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