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