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