xref: /freebsd/sys/kern/kern_sig.c (revision cc16dea626cf2fc80cde667ac4798065108e596c)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_compat.h"
41 #include "opt_kdtrace.h"
42 #include "opt_ktrace.h"
43 #include "opt_core.h"
44 #include "opt_procdesc.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/signalvar.h>
49 #include <sys/vnode.h>
50 #include <sys/acct.h>
51 #include <sys/capability.h>
52 #include <sys/condvar.h>
53 #include <sys/event.h>
54 #include <sys/fcntl.h>
55 #include <sys/imgact.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/ktrace.h>
59 #include <sys/lock.h>
60 #include <sys/malloc.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/proc.h>
64 #include <sys/procdesc.h>
65 #include <sys/posix4.h>
66 #include <sys/pioctl.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
69 #include <sys/sdt.h>
70 #include <sys/sbuf.h>
71 #include <sys/sleepqueue.h>
72 #include <sys/smp.h>
73 #include <sys/stat.h>
74 #include <sys/sx.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysent.h>
78 #include <sys/syslog.h>
79 #include <sys/sysproto.h>
80 #include <sys/timers.h>
81 #include <sys/unistd.h>
82 #include <sys/wait.h>
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/uma.h>
86 
87 #include <sys/jail.h>
88 
89 #include <machine/cpu.h>
90 
91 #include <security/audit/audit.h>
92 
93 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
94 
95 SDT_PROVIDER_DECLARE(proc);
96 SDT_PROBE_DEFINE3(proc, kernel, , signal_send, signal-send, "struct thread *",
97     "struct proc *", "int");
98 SDT_PROBE_DEFINE2(proc, kernel, , signal_clear, signal-clear, "int",
99     "ksiginfo_t *");
100 SDT_PROBE_DEFINE3(proc, kernel, , signal_discard, signal-discard,
101     "struct thread *", "struct proc *", "int");
102 
103 static int	coredump(struct thread *);
104 static int	killpg1(struct thread *td, int sig, int pgid, int all,
105 		    ksiginfo_t *ksi);
106 static int	issignal(struct thread *td);
107 static int	sigprop(int sig);
108 static void	tdsigwakeup(struct thread *, int, sig_t, int);
109 static void	sig_suspend_threads(struct thread *, struct proc *, int);
110 static int	filt_sigattach(struct knote *kn);
111 static void	filt_sigdetach(struct knote *kn);
112 static int	filt_signal(struct knote *kn, long hint);
113 static struct thread *sigtd(struct proc *p, int sig, int prop);
114 static void	sigqueue_start(void);
115 
116 static uma_zone_t	ksiginfo_zone = NULL;
117 struct filterops sig_filtops = {
118 	.f_isfd = 0,
119 	.f_attach = filt_sigattach,
120 	.f_detach = filt_sigdetach,
121 	.f_event = filt_signal,
122 };
123 
124 static int	kern_logsigexit = 1;
125 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
126     &kern_logsigexit, 0,
127     "Log processes quitting on abnormal signals to syslog(3)");
128 
129 static int	kern_forcesigexit = 1;
130 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
131     &kern_forcesigexit, 0, "Force trap signal to be handled");
132 
133 static SYSCTL_NODE(_kern, OID_AUTO, sigqueue, CTLFLAG_RW, 0,
134     "POSIX real time signal");
135 
136 static int	max_pending_per_proc = 128;
137 SYSCTL_INT(_kern_sigqueue, OID_AUTO, max_pending_per_proc, CTLFLAG_RW,
138     &max_pending_per_proc, 0, "Max pending signals per proc");
139 
140 static int	preallocate_siginfo = 1024;
141 TUNABLE_INT("kern.sigqueue.preallocate", &preallocate_siginfo);
142 SYSCTL_INT(_kern_sigqueue, OID_AUTO, preallocate, CTLFLAG_RD,
143     &preallocate_siginfo, 0, "Preallocated signal memory size");
144 
145 static int	signal_overflow = 0;
146 SYSCTL_INT(_kern_sigqueue, OID_AUTO, overflow, CTLFLAG_RD,
147     &signal_overflow, 0, "Number of signals overflew");
148 
149 static int	signal_alloc_fail = 0;
150 SYSCTL_INT(_kern_sigqueue, OID_AUTO, alloc_fail, CTLFLAG_RD,
151     &signal_alloc_fail, 0, "signals failed to be allocated");
152 
153 SYSINIT(signal, SI_SUB_P1003_1B, SI_ORDER_FIRST+3, sigqueue_start, NULL);
154 
155 /*
156  * Policy -- Can ucred cr1 send SIGIO to process cr2?
157  * Should use cr_cansignal() once cr_cansignal() allows SIGIO and SIGURG
158  * in the right situations.
159  */
160 #define CANSIGIO(cr1, cr2) \
161 	((cr1)->cr_uid == 0 || \
162 	    (cr1)->cr_ruid == (cr2)->cr_ruid || \
163 	    (cr1)->cr_uid == (cr2)->cr_ruid || \
164 	    (cr1)->cr_ruid == (cr2)->cr_uid || \
165 	    (cr1)->cr_uid == (cr2)->cr_uid)
166 
167 static int	sugid_coredump;
168 TUNABLE_INT("kern.sugid_coredump", &sugid_coredump);
169 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RW,
170     &sugid_coredump, 0, "Allow setuid and setgid processes to dump core");
171 
172 static int	capmode_coredump;
173 TUNABLE_INT("kern.capmode_coredump", &capmode_coredump);
174 SYSCTL_INT(_kern, OID_AUTO, capmode_coredump, CTLFLAG_RW,
175     &capmode_coredump, 0, "Allow processes in capability mode to dump core");
176 
177 static int	do_coredump = 1;
178 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
179 	&do_coredump, 0, "Enable/Disable coredumps");
180 
181 static int	set_core_nodump_flag = 0;
182 SYSCTL_INT(_kern, OID_AUTO, nodump_coredump, CTLFLAG_RW, &set_core_nodump_flag,
183 	0, "Enable setting the NODUMP flag on coredump files");
184 
185 /*
186  * Signal properties and actions.
187  * The array below categorizes the signals and their default actions
188  * according to the following properties:
189  */
190 #define	SA_KILL		0x01		/* terminates process by default */
191 #define	SA_CORE		0x02		/* ditto and coredumps */
192 #define	SA_STOP		0x04		/* suspend process */
193 #define	SA_TTYSTOP	0x08		/* ditto, from tty */
194 #define	SA_IGNORE	0x10		/* ignore by default */
195 #define	SA_CONT		0x20		/* continue if suspended */
196 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
197 
198 static int sigproptbl[NSIG] = {
199 	SA_KILL,			/* SIGHUP */
200 	SA_KILL,			/* SIGINT */
201 	SA_KILL|SA_CORE,		/* SIGQUIT */
202 	SA_KILL|SA_CORE,		/* SIGILL */
203 	SA_KILL|SA_CORE,		/* SIGTRAP */
204 	SA_KILL|SA_CORE,		/* SIGABRT */
205 	SA_KILL|SA_CORE,		/* SIGEMT */
206 	SA_KILL|SA_CORE,		/* SIGFPE */
207 	SA_KILL,			/* SIGKILL */
208 	SA_KILL|SA_CORE,		/* SIGBUS */
209 	SA_KILL|SA_CORE,		/* SIGSEGV */
210 	SA_KILL|SA_CORE,		/* SIGSYS */
211 	SA_KILL,			/* SIGPIPE */
212 	SA_KILL,			/* SIGALRM */
213 	SA_KILL,			/* SIGTERM */
214 	SA_IGNORE,			/* SIGURG */
215 	SA_STOP,			/* SIGSTOP */
216 	SA_STOP|SA_TTYSTOP,		/* SIGTSTP */
217 	SA_IGNORE|SA_CONT,		/* SIGCONT */
218 	SA_IGNORE,			/* SIGCHLD */
219 	SA_STOP|SA_TTYSTOP,		/* SIGTTIN */
220 	SA_STOP|SA_TTYSTOP,		/* SIGTTOU */
221 	SA_IGNORE,			/* SIGIO */
222 	SA_KILL,			/* SIGXCPU */
223 	SA_KILL,			/* SIGXFSZ */
224 	SA_KILL,			/* SIGVTALRM */
225 	SA_KILL,			/* SIGPROF */
226 	SA_IGNORE,			/* SIGWINCH  */
227 	SA_IGNORE,			/* SIGINFO */
228 	SA_KILL,			/* SIGUSR1 */
229 	SA_KILL,			/* SIGUSR2 */
230 };
231 
232 static void reschedule_signals(struct proc *p, sigset_t block, int flags);
233 
234 static void
235 sigqueue_start(void)
236 {
237 	ksiginfo_zone = uma_zcreate("ksiginfo", sizeof(ksiginfo_t),
238 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
239 	uma_prealloc(ksiginfo_zone, preallocate_siginfo);
240 	p31b_setcfg(CTL_P1003_1B_REALTIME_SIGNALS, _POSIX_REALTIME_SIGNALS);
241 	p31b_setcfg(CTL_P1003_1B_RTSIG_MAX, SIGRTMAX - SIGRTMIN + 1);
242 	p31b_setcfg(CTL_P1003_1B_SIGQUEUE_MAX, max_pending_per_proc);
243 }
244 
245 ksiginfo_t *
246 ksiginfo_alloc(int wait)
247 {
248 	int flags;
249 
250 	flags = M_ZERO;
251 	if (! wait)
252 		flags |= M_NOWAIT;
253 	if (ksiginfo_zone != NULL)
254 		return ((ksiginfo_t *)uma_zalloc(ksiginfo_zone, flags));
255 	return (NULL);
256 }
257 
258 void
259 ksiginfo_free(ksiginfo_t *ksi)
260 {
261 	uma_zfree(ksiginfo_zone, ksi);
262 }
263 
264 static __inline int
265 ksiginfo_tryfree(ksiginfo_t *ksi)
266 {
267 	if (!(ksi->ksi_flags & KSI_EXT)) {
268 		uma_zfree(ksiginfo_zone, ksi);
269 		return (1);
270 	}
271 	return (0);
272 }
273 
274 void
275 sigqueue_init(sigqueue_t *list, struct proc *p)
276 {
277 	SIGEMPTYSET(list->sq_signals);
278 	SIGEMPTYSET(list->sq_kill);
279 	TAILQ_INIT(&list->sq_list);
280 	list->sq_proc = p;
281 	list->sq_flags = SQ_INIT;
282 }
283 
284 /*
285  * Get a signal's ksiginfo.
286  * Return:
287  *	0	-	signal not found
288  *	others	-	signal number
289  */
290 static int
291 sigqueue_get(sigqueue_t *sq, int signo, ksiginfo_t *si)
292 {
293 	struct proc *p = sq->sq_proc;
294 	struct ksiginfo *ksi, *next;
295 	int count = 0;
296 
297 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
298 
299 	if (!SIGISMEMBER(sq->sq_signals, signo))
300 		return (0);
301 
302 	if (SIGISMEMBER(sq->sq_kill, signo)) {
303 		count++;
304 		SIGDELSET(sq->sq_kill, signo);
305 	}
306 
307 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
308 		if (ksi->ksi_signo == signo) {
309 			if (count == 0) {
310 				TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
311 				ksi->ksi_sigq = NULL;
312 				ksiginfo_copy(ksi, si);
313 				if (ksiginfo_tryfree(ksi) && p != NULL)
314 					p->p_pendingcnt--;
315 			}
316 			if (++count > 1)
317 				break;
318 		}
319 	}
320 
321 	if (count <= 1)
322 		SIGDELSET(sq->sq_signals, signo);
323 	si->ksi_signo = signo;
324 	return (signo);
325 }
326 
327 void
328 sigqueue_take(ksiginfo_t *ksi)
329 {
330 	struct ksiginfo *kp;
331 	struct proc	*p;
332 	sigqueue_t	*sq;
333 
334 	if (ksi == NULL || (sq = ksi->ksi_sigq) == NULL)
335 		return;
336 
337 	p = sq->sq_proc;
338 	TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
339 	ksi->ksi_sigq = NULL;
340 	if (!(ksi->ksi_flags & KSI_EXT) && p != NULL)
341 		p->p_pendingcnt--;
342 
343 	for (kp = TAILQ_FIRST(&sq->sq_list); kp != NULL;
344 	     kp = TAILQ_NEXT(kp, ksi_link)) {
345 		if (kp->ksi_signo == ksi->ksi_signo)
346 			break;
347 	}
348 	if (kp == NULL && !SIGISMEMBER(sq->sq_kill, ksi->ksi_signo))
349 		SIGDELSET(sq->sq_signals, ksi->ksi_signo);
350 }
351 
352 static int
353 sigqueue_add(sigqueue_t *sq, int signo, ksiginfo_t *si)
354 {
355 	struct proc *p = sq->sq_proc;
356 	struct ksiginfo *ksi;
357 	int ret = 0;
358 
359 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
360 
361 	if (signo == SIGKILL || signo == SIGSTOP || si == NULL) {
362 		SIGADDSET(sq->sq_kill, signo);
363 		goto out_set_bit;
364 	}
365 
366 	/* directly insert the ksi, don't copy it */
367 	if (si->ksi_flags & KSI_INS) {
368 		if (si->ksi_flags & KSI_HEAD)
369 			TAILQ_INSERT_HEAD(&sq->sq_list, si, ksi_link);
370 		else
371 			TAILQ_INSERT_TAIL(&sq->sq_list, si, ksi_link);
372 		si->ksi_sigq = sq;
373 		goto out_set_bit;
374 	}
375 
376 	if (__predict_false(ksiginfo_zone == NULL)) {
377 		SIGADDSET(sq->sq_kill, signo);
378 		goto out_set_bit;
379 	}
380 
381 	if (p != NULL && p->p_pendingcnt >= max_pending_per_proc) {
382 		signal_overflow++;
383 		ret = EAGAIN;
384 	} else if ((ksi = ksiginfo_alloc(0)) == NULL) {
385 		signal_alloc_fail++;
386 		ret = EAGAIN;
387 	} else {
388 		if (p != NULL)
389 			p->p_pendingcnt++;
390 		ksiginfo_copy(si, ksi);
391 		ksi->ksi_signo = signo;
392 		if (si->ksi_flags & KSI_HEAD)
393 			TAILQ_INSERT_HEAD(&sq->sq_list, ksi, ksi_link);
394 		else
395 			TAILQ_INSERT_TAIL(&sq->sq_list, ksi, ksi_link);
396 		ksi->ksi_sigq = sq;
397 	}
398 
399 	if ((si->ksi_flags & KSI_TRAP) != 0 ||
400 	    (si->ksi_flags & KSI_SIGQ) == 0) {
401 		if (ret != 0)
402 			SIGADDSET(sq->sq_kill, signo);
403 		ret = 0;
404 		goto out_set_bit;
405 	}
406 
407 	if (ret != 0)
408 		return (ret);
409 
410 out_set_bit:
411 	SIGADDSET(sq->sq_signals, signo);
412 	return (ret);
413 }
414 
415 void
416 sigqueue_flush(sigqueue_t *sq)
417 {
418 	struct proc *p = sq->sq_proc;
419 	ksiginfo_t *ksi;
420 
421 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
422 
423 	if (p != NULL)
424 		PROC_LOCK_ASSERT(p, MA_OWNED);
425 
426 	while ((ksi = TAILQ_FIRST(&sq->sq_list)) != NULL) {
427 		TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
428 		ksi->ksi_sigq = NULL;
429 		if (ksiginfo_tryfree(ksi) && p != NULL)
430 			p->p_pendingcnt--;
431 	}
432 
433 	SIGEMPTYSET(sq->sq_signals);
434 	SIGEMPTYSET(sq->sq_kill);
435 }
436 
437 static void
438 sigqueue_move_set(sigqueue_t *src, sigqueue_t *dst, const sigset_t *set)
439 {
440 	sigset_t tmp;
441 	struct proc *p1, *p2;
442 	ksiginfo_t *ksi, *next;
443 
444 	KASSERT(src->sq_flags & SQ_INIT, ("src sigqueue not inited"));
445 	KASSERT(dst->sq_flags & SQ_INIT, ("dst sigqueue not inited"));
446 	p1 = src->sq_proc;
447 	p2 = dst->sq_proc;
448 	/* Move siginfo to target list */
449 	TAILQ_FOREACH_SAFE(ksi, &src->sq_list, ksi_link, next) {
450 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
451 			TAILQ_REMOVE(&src->sq_list, ksi, ksi_link);
452 			if (p1 != NULL)
453 				p1->p_pendingcnt--;
454 			TAILQ_INSERT_TAIL(&dst->sq_list, ksi, ksi_link);
455 			ksi->ksi_sigq = dst;
456 			if (p2 != NULL)
457 				p2->p_pendingcnt++;
458 		}
459 	}
460 
461 	/* Move pending bits to target list */
462 	tmp = src->sq_kill;
463 	SIGSETAND(tmp, *set);
464 	SIGSETOR(dst->sq_kill, tmp);
465 	SIGSETNAND(src->sq_kill, tmp);
466 
467 	tmp = src->sq_signals;
468 	SIGSETAND(tmp, *set);
469 	SIGSETOR(dst->sq_signals, tmp);
470 	SIGSETNAND(src->sq_signals, tmp);
471 }
472 
473 #if 0
474 static void
475 sigqueue_move(sigqueue_t *src, sigqueue_t *dst, int signo)
476 {
477 	sigset_t set;
478 
479 	SIGEMPTYSET(set);
480 	SIGADDSET(set, signo);
481 	sigqueue_move_set(src, dst, &set);
482 }
483 #endif
484 
485 static void
486 sigqueue_delete_set(sigqueue_t *sq, const sigset_t *set)
487 {
488 	struct proc *p = sq->sq_proc;
489 	ksiginfo_t *ksi, *next;
490 
491 	KASSERT(sq->sq_flags & SQ_INIT, ("src sigqueue not inited"));
492 
493 	/* Remove siginfo queue */
494 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
495 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
496 			TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
497 			ksi->ksi_sigq = NULL;
498 			if (ksiginfo_tryfree(ksi) && p != NULL)
499 				p->p_pendingcnt--;
500 		}
501 	}
502 	SIGSETNAND(sq->sq_kill, *set);
503 	SIGSETNAND(sq->sq_signals, *set);
504 }
505 
506 void
507 sigqueue_delete(sigqueue_t *sq, int signo)
508 {
509 	sigset_t set;
510 
511 	SIGEMPTYSET(set);
512 	SIGADDSET(set, signo);
513 	sigqueue_delete_set(sq, &set);
514 }
515 
516 /* Remove a set of signals for a process */
517 static void
518 sigqueue_delete_set_proc(struct proc *p, const sigset_t *set)
519 {
520 	sigqueue_t worklist;
521 	struct thread *td0;
522 
523 	PROC_LOCK_ASSERT(p, MA_OWNED);
524 
525 	sigqueue_init(&worklist, NULL);
526 	sigqueue_move_set(&p->p_sigqueue, &worklist, set);
527 
528 	FOREACH_THREAD_IN_PROC(p, td0)
529 		sigqueue_move_set(&td0->td_sigqueue, &worklist, set);
530 
531 	sigqueue_flush(&worklist);
532 }
533 
534 void
535 sigqueue_delete_proc(struct proc *p, int signo)
536 {
537 	sigset_t set;
538 
539 	SIGEMPTYSET(set);
540 	SIGADDSET(set, signo);
541 	sigqueue_delete_set_proc(p, &set);
542 }
543 
544 static void
545 sigqueue_delete_stopmask_proc(struct proc *p)
546 {
547 	sigset_t set;
548 
549 	SIGEMPTYSET(set);
550 	SIGADDSET(set, SIGSTOP);
551 	SIGADDSET(set, SIGTSTP);
552 	SIGADDSET(set, SIGTTIN);
553 	SIGADDSET(set, SIGTTOU);
554 	sigqueue_delete_set_proc(p, &set);
555 }
556 
557 /*
558  * Determine signal that should be delivered to thread td, the current
559  * thread, 0 if none.  If there is a pending stop signal with default
560  * action, the process stops in issignal().
561  */
562 int
563 cursig(struct thread *td)
564 {
565 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
566 	mtx_assert(&td->td_proc->p_sigacts->ps_mtx, MA_OWNED);
567 	THREAD_LOCK_ASSERT(td, MA_NOTOWNED);
568 	return (SIGPENDING(td) ? issignal(td) : 0);
569 }
570 
571 /*
572  * Arrange for ast() to handle unmasked pending signals on return to user
573  * mode.  This must be called whenever a signal is added to td_sigqueue or
574  * unmasked in td_sigmask.
575  */
576 void
577 signotify(struct thread *td)
578 {
579 	struct proc *p;
580 
581 	p = td->td_proc;
582 
583 	PROC_LOCK_ASSERT(p, MA_OWNED);
584 
585 	if (SIGPENDING(td)) {
586 		thread_lock(td);
587 		td->td_flags |= TDF_NEEDSIGCHK | TDF_ASTPENDING;
588 		thread_unlock(td);
589 	}
590 }
591 
592 int
593 sigonstack(size_t sp)
594 {
595 	struct thread *td = curthread;
596 
597 	return ((td->td_pflags & TDP_ALTSTACK) ?
598 #if defined(COMPAT_43)
599 	    ((td->td_sigstk.ss_size == 0) ?
600 		(td->td_sigstk.ss_flags & SS_ONSTACK) :
601 		((sp - (size_t)td->td_sigstk.ss_sp) < td->td_sigstk.ss_size))
602 #else
603 	    ((sp - (size_t)td->td_sigstk.ss_sp) < td->td_sigstk.ss_size)
604 #endif
605 	    : 0);
606 }
607 
608 static __inline int
609 sigprop(int sig)
610 {
611 
612 	if (sig > 0 && sig < NSIG)
613 		return (sigproptbl[_SIG_IDX(sig)]);
614 	return (0);
615 }
616 
617 int
618 sig_ffs(sigset_t *set)
619 {
620 	int i;
621 
622 	for (i = 0; i < _SIG_WORDS; i++)
623 		if (set->__bits[i])
624 			return (ffs(set->__bits[i]) + (i * 32));
625 	return (0);
626 }
627 
628 /*
629  * kern_sigaction
630  * sigaction
631  * freebsd4_sigaction
632  * osigaction
633  */
634 int
635 kern_sigaction(td, sig, act, oact, flags)
636 	struct thread *td;
637 	register int sig;
638 	struct sigaction *act, *oact;
639 	int flags;
640 {
641 	struct sigacts *ps;
642 	struct proc *p = td->td_proc;
643 
644 	if (!_SIG_VALID(sig))
645 		return (EINVAL);
646 
647 	PROC_LOCK(p);
648 	ps = p->p_sigacts;
649 	mtx_lock(&ps->ps_mtx);
650 	if (oact) {
651 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
652 		oact->sa_flags = 0;
653 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
654 			oact->sa_flags |= SA_ONSTACK;
655 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
656 			oact->sa_flags |= SA_RESTART;
657 		if (SIGISMEMBER(ps->ps_sigreset, sig))
658 			oact->sa_flags |= SA_RESETHAND;
659 		if (SIGISMEMBER(ps->ps_signodefer, sig))
660 			oact->sa_flags |= SA_NODEFER;
661 		if (SIGISMEMBER(ps->ps_siginfo, sig)) {
662 			oact->sa_flags |= SA_SIGINFO;
663 			oact->sa_sigaction =
664 			    (__siginfohandler_t *)ps->ps_sigact[_SIG_IDX(sig)];
665 		} else
666 			oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
667 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDSTOP)
668 			oact->sa_flags |= SA_NOCLDSTOP;
669 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDWAIT)
670 			oact->sa_flags |= SA_NOCLDWAIT;
671 	}
672 	if (act) {
673 		if ((sig == SIGKILL || sig == SIGSTOP) &&
674 		    act->sa_handler != SIG_DFL) {
675 			mtx_unlock(&ps->ps_mtx);
676 			PROC_UNLOCK(p);
677 			return (EINVAL);
678 		}
679 
680 		/*
681 		 * Change setting atomically.
682 		 */
683 
684 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
685 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
686 		if (act->sa_flags & SA_SIGINFO) {
687 			ps->ps_sigact[_SIG_IDX(sig)] =
688 			    (__sighandler_t *)act->sa_sigaction;
689 			SIGADDSET(ps->ps_siginfo, sig);
690 		} else {
691 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
692 			SIGDELSET(ps->ps_siginfo, sig);
693 		}
694 		if (!(act->sa_flags & SA_RESTART))
695 			SIGADDSET(ps->ps_sigintr, sig);
696 		else
697 			SIGDELSET(ps->ps_sigintr, sig);
698 		if (act->sa_flags & SA_ONSTACK)
699 			SIGADDSET(ps->ps_sigonstack, sig);
700 		else
701 			SIGDELSET(ps->ps_sigonstack, sig);
702 		if (act->sa_flags & SA_RESETHAND)
703 			SIGADDSET(ps->ps_sigreset, sig);
704 		else
705 			SIGDELSET(ps->ps_sigreset, sig);
706 		if (act->sa_flags & SA_NODEFER)
707 			SIGADDSET(ps->ps_signodefer, sig);
708 		else
709 			SIGDELSET(ps->ps_signodefer, sig);
710 		if (sig == SIGCHLD) {
711 			if (act->sa_flags & SA_NOCLDSTOP)
712 				ps->ps_flag |= PS_NOCLDSTOP;
713 			else
714 				ps->ps_flag &= ~PS_NOCLDSTOP;
715 			if (act->sa_flags & SA_NOCLDWAIT) {
716 				/*
717 				 * Paranoia: since SA_NOCLDWAIT is implemented
718 				 * by reparenting the dying child to PID 1 (and
719 				 * trust it to reap the zombie), PID 1 itself
720 				 * is forbidden to set SA_NOCLDWAIT.
721 				 */
722 				if (p->p_pid == 1)
723 					ps->ps_flag &= ~PS_NOCLDWAIT;
724 				else
725 					ps->ps_flag |= PS_NOCLDWAIT;
726 			} else
727 				ps->ps_flag &= ~PS_NOCLDWAIT;
728 			if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
729 				ps->ps_flag |= PS_CLDSIGIGN;
730 			else
731 				ps->ps_flag &= ~PS_CLDSIGIGN;
732 		}
733 		/*
734 		 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
735 		 * and for signals set to SIG_DFL where the default is to
736 		 * ignore. However, don't put SIGCONT in ps_sigignore, as we
737 		 * have to restart the process.
738 		 */
739 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
740 		    (sigprop(sig) & SA_IGNORE &&
741 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
742 			/* never to be seen again */
743 			sigqueue_delete_proc(p, sig);
744 			if (sig != SIGCONT)
745 				/* easier in psignal */
746 				SIGADDSET(ps->ps_sigignore, sig);
747 			SIGDELSET(ps->ps_sigcatch, sig);
748 		} else {
749 			SIGDELSET(ps->ps_sigignore, sig);
750 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
751 				SIGDELSET(ps->ps_sigcatch, sig);
752 			else
753 				SIGADDSET(ps->ps_sigcatch, sig);
754 		}
755 #ifdef COMPAT_FREEBSD4
756 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
757 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
758 		    (flags & KSA_FREEBSD4) == 0)
759 			SIGDELSET(ps->ps_freebsd4, sig);
760 		else
761 			SIGADDSET(ps->ps_freebsd4, sig);
762 #endif
763 #ifdef COMPAT_43
764 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
765 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
766 		    (flags & KSA_OSIGSET) == 0)
767 			SIGDELSET(ps->ps_osigset, sig);
768 		else
769 			SIGADDSET(ps->ps_osigset, sig);
770 #endif
771 	}
772 	mtx_unlock(&ps->ps_mtx);
773 	PROC_UNLOCK(p);
774 	return (0);
775 }
776 
777 #ifndef _SYS_SYSPROTO_H_
778 struct sigaction_args {
779 	int	sig;
780 	struct	sigaction *act;
781 	struct	sigaction *oact;
782 };
783 #endif
784 int
785 sys_sigaction(td, uap)
786 	struct thread *td;
787 	register struct sigaction_args *uap;
788 {
789 	struct sigaction act, oact;
790 	register struct sigaction *actp, *oactp;
791 	int error;
792 
793 	actp = (uap->act != NULL) ? &act : NULL;
794 	oactp = (uap->oact != NULL) ? &oact : NULL;
795 	if (actp) {
796 		error = copyin(uap->act, actp, sizeof(act));
797 		if (error)
798 			return (error);
799 	}
800 	error = kern_sigaction(td, uap->sig, actp, oactp, 0);
801 	if (oactp && !error)
802 		error = copyout(oactp, uap->oact, sizeof(oact));
803 	return (error);
804 }
805 
806 #ifdef COMPAT_FREEBSD4
807 #ifndef _SYS_SYSPROTO_H_
808 struct freebsd4_sigaction_args {
809 	int	sig;
810 	struct	sigaction *act;
811 	struct	sigaction *oact;
812 };
813 #endif
814 int
815 freebsd4_sigaction(td, uap)
816 	struct thread *td;
817 	register struct freebsd4_sigaction_args *uap;
818 {
819 	struct sigaction act, oact;
820 	register struct sigaction *actp, *oactp;
821 	int error;
822 
823 
824 	actp = (uap->act != NULL) ? &act : NULL;
825 	oactp = (uap->oact != NULL) ? &oact : NULL;
826 	if (actp) {
827 		error = copyin(uap->act, actp, sizeof(act));
828 		if (error)
829 			return (error);
830 	}
831 	error = kern_sigaction(td, uap->sig, actp, oactp, KSA_FREEBSD4);
832 	if (oactp && !error)
833 		error = copyout(oactp, uap->oact, sizeof(oact));
834 	return (error);
835 }
836 #endif	/* COMAPT_FREEBSD4 */
837 
838 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
839 #ifndef _SYS_SYSPROTO_H_
840 struct osigaction_args {
841 	int	signum;
842 	struct	osigaction *nsa;
843 	struct	osigaction *osa;
844 };
845 #endif
846 int
847 osigaction(td, uap)
848 	struct thread *td;
849 	register struct osigaction_args *uap;
850 {
851 	struct osigaction sa;
852 	struct sigaction nsa, osa;
853 	register struct sigaction *nsap, *osap;
854 	int error;
855 
856 	if (uap->signum <= 0 || uap->signum >= ONSIG)
857 		return (EINVAL);
858 
859 	nsap = (uap->nsa != NULL) ? &nsa : NULL;
860 	osap = (uap->osa != NULL) ? &osa : NULL;
861 
862 	if (nsap) {
863 		error = copyin(uap->nsa, &sa, sizeof(sa));
864 		if (error)
865 			return (error);
866 		nsap->sa_handler = sa.sa_handler;
867 		nsap->sa_flags = sa.sa_flags;
868 		OSIG2SIG(sa.sa_mask, nsap->sa_mask);
869 	}
870 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
871 	if (osap && !error) {
872 		sa.sa_handler = osap->sa_handler;
873 		sa.sa_flags = osap->sa_flags;
874 		SIG2OSIG(osap->sa_mask, sa.sa_mask);
875 		error = copyout(&sa, uap->osa, sizeof(sa));
876 	}
877 	return (error);
878 }
879 
880 #if !defined(__i386__)
881 /* Avoid replicating the same stub everywhere */
882 int
883 osigreturn(td, uap)
884 	struct thread *td;
885 	struct osigreturn_args *uap;
886 {
887 
888 	return (nosys(td, (struct nosys_args *)uap));
889 }
890 #endif
891 #endif /* COMPAT_43 */
892 
893 /*
894  * Initialize signal state for process 0;
895  * set to ignore signals that are ignored by default.
896  */
897 void
898 siginit(p)
899 	struct proc *p;
900 {
901 	register int i;
902 	struct sigacts *ps;
903 
904 	PROC_LOCK(p);
905 	ps = p->p_sigacts;
906 	mtx_lock(&ps->ps_mtx);
907 	for (i = 1; i <= NSIG; i++)
908 		if (sigprop(i) & SA_IGNORE && i != SIGCONT)
909 			SIGADDSET(ps->ps_sigignore, i);
910 	mtx_unlock(&ps->ps_mtx);
911 	PROC_UNLOCK(p);
912 }
913 
914 /*
915  * Reset signals for an exec of the specified process.
916  */
917 void
918 execsigs(struct proc *p)
919 {
920 	struct sigacts *ps;
921 	int sig;
922 	struct thread *td;
923 
924 	/*
925 	 * Reset caught signals.  Held signals remain held
926 	 * through td_sigmask (unless they were caught,
927 	 * and are now ignored by default).
928 	 */
929 	PROC_LOCK_ASSERT(p, MA_OWNED);
930 	td = FIRST_THREAD_IN_PROC(p);
931 	ps = p->p_sigacts;
932 	mtx_lock(&ps->ps_mtx);
933 	while (SIGNOTEMPTY(ps->ps_sigcatch)) {
934 		sig = sig_ffs(&ps->ps_sigcatch);
935 		SIGDELSET(ps->ps_sigcatch, sig);
936 		if (sigprop(sig) & SA_IGNORE) {
937 			if (sig != SIGCONT)
938 				SIGADDSET(ps->ps_sigignore, sig);
939 			sigqueue_delete_proc(p, sig);
940 		}
941 		ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
942 	}
943 	/*
944 	 * Reset stack state to the user stack.
945 	 * Clear set of signals caught on the signal stack.
946 	 */
947 	td->td_sigstk.ss_flags = SS_DISABLE;
948 	td->td_sigstk.ss_size = 0;
949 	td->td_sigstk.ss_sp = 0;
950 	td->td_pflags &= ~TDP_ALTSTACK;
951 	/*
952 	 * Reset no zombies if child dies flag as Solaris does.
953 	 */
954 	ps->ps_flag &= ~(PS_NOCLDWAIT | PS_CLDSIGIGN);
955 	if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
956 		ps->ps_sigact[_SIG_IDX(SIGCHLD)] = SIG_DFL;
957 	mtx_unlock(&ps->ps_mtx);
958 }
959 
960 /*
961  * kern_sigprocmask()
962  *
963  *	Manipulate signal mask.
964  */
965 int
966 kern_sigprocmask(struct thread *td, int how, sigset_t *set, sigset_t *oset,
967     int flags)
968 {
969 	sigset_t new_block, oset1;
970 	struct proc *p;
971 	int error;
972 
973 	p = td->td_proc;
974 	if (!(flags & SIGPROCMASK_PROC_LOCKED))
975 		PROC_LOCK(p);
976 	if (oset != NULL)
977 		*oset = td->td_sigmask;
978 
979 	error = 0;
980 	if (set != NULL) {
981 		switch (how) {
982 		case SIG_BLOCK:
983 			SIG_CANTMASK(*set);
984 			oset1 = td->td_sigmask;
985 			SIGSETOR(td->td_sigmask, *set);
986 			new_block = td->td_sigmask;
987 			SIGSETNAND(new_block, oset1);
988 			break;
989 		case SIG_UNBLOCK:
990 			SIGSETNAND(td->td_sigmask, *set);
991 			signotify(td);
992 			goto out;
993 		case SIG_SETMASK:
994 			SIG_CANTMASK(*set);
995 			oset1 = td->td_sigmask;
996 			if (flags & SIGPROCMASK_OLD)
997 				SIGSETLO(td->td_sigmask, *set);
998 			else
999 				td->td_sigmask = *set;
1000 			new_block = td->td_sigmask;
1001 			SIGSETNAND(new_block, oset1);
1002 			signotify(td);
1003 			break;
1004 		default:
1005 			error = EINVAL;
1006 			goto out;
1007 		}
1008 
1009 		/*
1010 		 * The new_block set contains signals that were not previously
1011 		 * blocked, but are blocked now.
1012 		 *
1013 		 * In case we block any signal that was not previously blocked
1014 		 * for td, and process has the signal pending, try to schedule
1015 		 * signal delivery to some thread that does not block the
1016 		 * signal, possibly waking it up.
1017 		 */
1018 		if (p->p_numthreads != 1)
1019 			reschedule_signals(p, new_block, flags);
1020 	}
1021 
1022 out:
1023 	if (!(flags & SIGPROCMASK_PROC_LOCKED))
1024 		PROC_UNLOCK(p);
1025 	return (error);
1026 }
1027 
1028 #ifndef _SYS_SYSPROTO_H_
1029 struct sigprocmask_args {
1030 	int	how;
1031 	const sigset_t *set;
1032 	sigset_t *oset;
1033 };
1034 #endif
1035 int
1036 sys_sigprocmask(td, uap)
1037 	register struct thread *td;
1038 	struct sigprocmask_args *uap;
1039 {
1040 	sigset_t set, oset;
1041 	sigset_t *setp, *osetp;
1042 	int error;
1043 
1044 	setp = (uap->set != NULL) ? &set : NULL;
1045 	osetp = (uap->oset != NULL) ? &oset : NULL;
1046 	if (setp) {
1047 		error = copyin(uap->set, setp, sizeof(set));
1048 		if (error)
1049 			return (error);
1050 	}
1051 	error = kern_sigprocmask(td, uap->how, setp, osetp, 0);
1052 	if (osetp && !error) {
1053 		error = copyout(osetp, uap->oset, sizeof(oset));
1054 	}
1055 	return (error);
1056 }
1057 
1058 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1059 #ifndef _SYS_SYSPROTO_H_
1060 struct osigprocmask_args {
1061 	int	how;
1062 	osigset_t mask;
1063 };
1064 #endif
1065 int
1066 osigprocmask(td, uap)
1067 	register struct thread *td;
1068 	struct osigprocmask_args *uap;
1069 {
1070 	sigset_t set, oset;
1071 	int error;
1072 
1073 	OSIG2SIG(uap->mask, set);
1074 	error = kern_sigprocmask(td, uap->how, &set, &oset, 1);
1075 	SIG2OSIG(oset, td->td_retval[0]);
1076 	return (error);
1077 }
1078 #endif /* COMPAT_43 */
1079 
1080 int
1081 sys_sigwait(struct thread *td, struct sigwait_args *uap)
1082 {
1083 	ksiginfo_t ksi;
1084 	sigset_t set;
1085 	int error;
1086 
1087 	error = copyin(uap->set, &set, sizeof(set));
1088 	if (error) {
1089 		td->td_retval[0] = error;
1090 		return (0);
1091 	}
1092 
1093 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1094 	if (error) {
1095 		if (error == EINTR && td->td_proc->p_osrel < P_OSREL_SIGWAIT)
1096 			error = ERESTART;
1097 		if (error == ERESTART)
1098 			return (error);
1099 		td->td_retval[0] = error;
1100 		return (0);
1101 	}
1102 
1103 	error = copyout(&ksi.ksi_signo, uap->sig, sizeof(ksi.ksi_signo));
1104 	td->td_retval[0] = error;
1105 	return (0);
1106 }
1107 
1108 int
1109 sys_sigtimedwait(struct thread *td, struct sigtimedwait_args *uap)
1110 {
1111 	struct timespec ts;
1112 	struct timespec *timeout;
1113 	sigset_t set;
1114 	ksiginfo_t ksi;
1115 	int error;
1116 
1117 	if (uap->timeout) {
1118 		error = copyin(uap->timeout, &ts, sizeof(ts));
1119 		if (error)
1120 			return (error);
1121 
1122 		timeout = &ts;
1123 	} else
1124 		timeout = NULL;
1125 
1126 	error = copyin(uap->set, &set, sizeof(set));
1127 	if (error)
1128 		return (error);
1129 
1130 	error = kern_sigtimedwait(td, set, &ksi, timeout);
1131 	if (error)
1132 		return (error);
1133 
1134 	if (uap->info)
1135 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1136 
1137 	if (error == 0)
1138 		td->td_retval[0] = ksi.ksi_signo;
1139 	return (error);
1140 }
1141 
1142 int
1143 sys_sigwaitinfo(struct thread *td, struct sigwaitinfo_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 		return (error);
1152 
1153 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1154 	if (error)
1155 		return (error);
1156 
1157 	if (uap->info)
1158 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1159 
1160 	if (error == 0)
1161 		td->td_retval[0] = ksi.ksi_signo;
1162 	return (error);
1163 }
1164 
1165 int
1166 kern_sigtimedwait(struct thread *td, sigset_t waitset, ksiginfo_t *ksi,
1167 	struct timespec *timeout)
1168 {
1169 	struct sigacts *ps;
1170 	sigset_t saved_mask, new_block;
1171 	struct proc *p;
1172 	int error, sig, timo, timevalid = 0;
1173 	struct timespec rts, ets, ts;
1174 	struct timeval tv;
1175 
1176 	p = td->td_proc;
1177 	error = 0;
1178 	ets.tv_sec = 0;
1179 	ets.tv_nsec = 0;
1180 
1181 	if (timeout != NULL) {
1182 		if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) {
1183 			timevalid = 1;
1184 			getnanouptime(&rts);
1185 			ets = rts;
1186 			timespecadd(&ets, timeout);
1187 		}
1188 	}
1189 	ksiginfo_init(ksi);
1190 	/* Some signals can not be waited for. */
1191 	SIG_CANTMASK(waitset);
1192 	ps = p->p_sigacts;
1193 	PROC_LOCK(p);
1194 	saved_mask = td->td_sigmask;
1195 	SIGSETNAND(td->td_sigmask, waitset);
1196 	for (;;) {
1197 		mtx_lock(&ps->ps_mtx);
1198 		sig = cursig(td);
1199 		mtx_unlock(&ps->ps_mtx);
1200 		if (sig != 0 && SIGISMEMBER(waitset, sig)) {
1201 			if (sigqueue_get(&td->td_sigqueue, sig, ksi) != 0 ||
1202 			    sigqueue_get(&p->p_sigqueue, sig, ksi) != 0) {
1203 				error = 0;
1204 				break;
1205 			}
1206 		}
1207 
1208 		if (error != 0)
1209 			break;
1210 
1211 		/*
1212 		 * POSIX says this must be checked after looking for pending
1213 		 * signals.
1214 		 */
1215 		if (timeout != NULL) {
1216 			if (!timevalid) {
1217 				error = EINVAL;
1218 				break;
1219 			}
1220 			getnanouptime(&rts);
1221 			if (timespeccmp(&rts, &ets, >=)) {
1222 				error = EAGAIN;
1223 				break;
1224 			}
1225 			ts = ets;
1226 			timespecsub(&ts, &rts);
1227 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1228 			timo = tvtohz(&tv);
1229 		} else {
1230 			timo = 0;
1231 		}
1232 
1233 		error = msleep(ps, &p->p_mtx, PPAUSE|PCATCH, "sigwait", timo);
1234 
1235 		if (timeout != NULL) {
1236 			if (error == ERESTART) {
1237 				/* Timeout can not be restarted. */
1238 				error = EINTR;
1239 			} else if (error == EAGAIN) {
1240 				/* We will calculate timeout by ourself. */
1241 				error = 0;
1242 			}
1243 		}
1244 	}
1245 
1246 	new_block = saved_mask;
1247 	SIGSETNAND(new_block, td->td_sigmask);
1248 	td->td_sigmask = saved_mask;
1249 	/*
1250 	 * Fewer signals can be delivered to us, reschedule signal
1251 	 * notification.
1252 	 */
1253 	if (p->p_numthreads != 1)
1254 		reschedule_signals(p, new_block, 0);
1255 
1256 	if (error == 0) {
1257 		SDT_PROBE(proc, kernel, , signal_clear, sig, ksi, 0, 0, 0);
1258 
1259 		if (ksi->ksi_code == SI_TIMER)
1260 			itimer_accept(p, ksi->ksi_timerid, ksi);
1261 
1262 #ifdef KTRACE
1263 		if (KTRPOINT(td, KTR_PSIG)) {
1264 			sig_t action;
1265 
1266 			mtx_lock(&ps->ps_mtx);
1267 			action = ps->ps_sigact[_SIG_IDX(sig)];
1268 			mtx_unlock(&ps->ps_mtx);
1269 			ktrpsig(sig, action, &td->td_sigmask, ksi->ksi_code);
1270 		}
1271 #endif
1272 		if (sig == SIGKILL)
1273 			sigexit(td, sig);
1274 	}
1275 	PROC_UNLOCK(p);
1276 	return (error);
1277 }
1278 
1279 #ifndef _SYS_SYSPROTO_H_
1280 struct sigpending_args {
1281 	sigset_t	*set;
1282 };
1283 #endif
1284 int
1285 sys_sigpending(td, uap)
1286 	struct thread *td;
1287 	struct sigpending_args *uap;
1288 {
1289 	struct proc *p = td->td_proc;
1290 	sigset_t pending;
1291 
1292 	PROC_LOCK(p);
1293 	pending = p->p_sigqueue.sq_signals;
1294 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1295 	PROC_UNLOCK(p);
1296 	return (copyout(&pending, uap->set, sizeof(sigset_t)));
1297 }
1298 
1299 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1300 #ifndef _SYS_SYSPROTO_H_
1301 struct osigpending_args {
1302 	int	dummy;
1303 };
1304 #endif
1305 int
1306 osigpending(td, uap)
1307 	struct thread *td;
1308 	struct osigpending_args *uap;
1309 {
1310 	struct proc *p = td->td_proc;
1311 	sigset_t pending;
1312 
1313 	PROC_LOCK(p);
1314 	pending = p->p_sigqueue.sq_signals;
1315 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1316 	PROC_UNLOCK(p);
1317 	SIG2OSIG(pending, td->td_retval[0]);
1318 	return (0);
1319 }
1320 #endif /* COMPAT_43 */
1321 
1322 #if defined(COMPAT_43)
1323 /*
1324  * Generalized interface signal handler, 4.3-compatible.
1325  */
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct osigvec_args {
1328 	int	signum;
1329 	struct	sigvec *nsv;
1330 	struct	sigvec *osv;
1331 };
1332 #endif
1333 /* ARGSUSED */
1334 int
1335 osigvec(td, uap)
1336 	struct thread *td;
1337 	register struct osigvec_args *uap;
1338 {
1339 	struct sigvec vec;
1340 	struct sigaction nsa, osa;
1341 	register struct sigaction *nsap, *osap;
1342 	int error;
1343 
1344 	if (uap->signum <= 0 || uap->signum >= ONSIG)
1345 		return (EINVAL);
1346 	nsap = (uap->nsv != NULL) ? &nsa : NULL;
1347 	osap = (uap->osv != NULL) ? &osa : NULL;
1348 	if (nsap) {
1349 		error = copyin(uap->nsv, &vec, sizeof(vec));
1350 		if (error)
1351 			return (error);
1352 		nsap->sa_handler = vec.sv_handler;
1353 		OSIG2SIG(vec.sv_mask, nsap->sa_mask);
1354 		nsap->sa_flags = vec.sv_flags;
1355 		nsap->sa_flags ^= SA_RESTART;	/* opposite of SV_INTERRUPT */
1356 	}
1357 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
1358 	if (osap && !error) {
1359 		vec.sv_handler = osap->sa_handler;
1360 		SIG2OSIG(osap->sa_mask, vec.sv_mask);
1361 		vec.sv_flags = osap->sa_flags;
1362 		vec.sv_flags &= ~SA_NOCLDWAIT;
1363 		vec.sv_flags ^= SA_RESTART;
1364 		error = copyout(&vec, uap->osv, sizeof(vec));
1365 	}
1366 	return (error);
1367 }
1368 
1369 #ifndef _SYS_SYSPROTO_H_
1370 struct osigblock_args {
1371 	int	mask;
1372 };
1373 #endif
1374 int
1375 osigblock(td, uap)
1376 	register struct thread *td;
1377 	struct osigblock_args *uap;
1378 {
1379 	sigset_t set, oset;
1380 
1381 	OSIG2SIG(uap->mask, set);
1382 	kern_sigprocmask(td, SIG_BLOCK, &set, &oset, 0);
1383 	SIG2OSIG(oset, td->td_retval[0]);
1384 	return (0);
1385 }
1386 
1387 #ifndef _SYS_SYSPROTO_H_
1388 struct osigsetmask_args {
1389 	int	mask;
1390 };
1391 #endif
1392 int
1393 osigsetmask(td, uap)
1394 	struct thread *td;
1395 	struct osigsetmask_args *uap;
1396 {
1397 	sigset_t set, oset;
1398 
1399 	OSIG2SIG(uap->mask, set);
1400 	kern_sigprocmask(td, SIG_SETMASK, &set, &oset, 0);
1401 	SIG2OSIG(oset, td->td_retval[0]);
1402 	return (0);
1403 }
1404 #endif /* COMPAT_43 */
1405 
1406 /*
1407  * Suspend calling thread until signal, providing mask to be set in the
1408  * meantime.
1409  */
1410 #ifndef _SYS_SYSPROTO_H_
1411 struct sigsuspend_args {
1412 	const sigset_t *sigmask;
1413 };
1414 #endif
1415 /* ARGSUSED */
1416 int
1417 sys_sigsuspend(td, uap)
1418 	struct thread *td;
1419 	struct sigsuspend_args *uap;
1420 {
1421 	sigset_t mask;
1422 	int error;
1423 
1424 	error = copyin(uap->sigmask, &mask, sizeof(mask));
1425 	if (error)
1426 		return (error);
1427 	return (kern_sigsuspend(td, mask));
1428 }
1429 
1430 int
1431 kern_sigsuspend(struct thread *td, sigset_t mask)
1432 {
1433 	struct proc *p = td->td_proc;
1434 	int has_sig, sig;
1435 
1436 	/*
1437 	 * When returning from sigsuspend, we want
1438 	 * the old mask to be restored after the
1439 	 * signal handler has finished.  Thus, we
1440 	 * save it here and mark the sigacts structure
1441 	 * to indicate this.
1442 	 */
1443 	PROC_LOCK(p);
1444 	kern_sigprocmask(td, SIG_SETMASK, &mask, &td->td_oldsigmask,
1445 	    SIGPROCMASK_PROC_LOCKED);
1446 	td->td_pflags |= TDP_OLDMASK;
1447 
1448 	/*
1449 	 * Process signals now. Otherwise, we can get spurious wakeup
1450 	 * due to signal entered process queue, but delivered to other
1451 	 * thread. But sigsuspend should return only on signal
1452 	 * delivery.
1453 	 */
1454 	(p->p_sysent->sv_set_syscall_retval)(td, EINTR);
1455 	for (has_sig = 0; !has_sig;) {
1456 		while (msleep(&p->p_sigacts, &p->p_mtx, PPAUSE|PCATCH, "pause",
1457 			0) == 0)
1458 			/* void */;
1459 		thread_suspend_check(0);
1460 		mtx_lock(&p->p_sigacts->ps_mtx);
1461 		while ((sig = cursig(td)) != 0)
1462 			has_sig += postsig(sig);
1463 		mtx_unlock(&p->p_sigacts->ps_mtx);
1464 	}
1465 	PROC_UNLOCK(p);
1466 	td->td_errno = EINTR;
1467 	td->td_pflags |= TDP_NERRNO;
1468 	return (EJUSTRETURN);
1469 }
1470 
1471 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1472 /*
1473  * Compatibility sigsuspend call for old binaries.  Note nonstandard calling
1474  * convention: libc stub passes mask, not pointer, to save a copyin.
1475  */
1476 #ifndef _SYS_SYSPROTO_H_
1477 struct osigsuspend_args {
1478 	osigset_t mask;
1479 };
1480 #endif
1481 /* ARGSUSED */
1482 int
1483 osigsuspend(td, uap)
1484 	struct thread *td;
1485 	struct osigsuspend_args *uap;
1486 {
1487 	sigset_t mask;
1488 
1489 	OSIG2SIG(uap->mask, mask);
1490 	return (kern_sigsuspend(td, mask));
1491 }
1492 #endif /* COMPAT_43 */
1493 
1494 #if defined(COMPAT_43)
1495 #ifndef _SYS_SYSPROTO_H_
1496 struct osigstack_args {
1497 	struct	sigstack *nss;
1498 	struct	sigstack *oss;
1499 };
1500 #endif
1501 /* ARGSUSED */
1502 int
1503 osigstack(td, uap)
1504 	struct thread *td;
1505 	register struct osigstack_args *uap;
1506 {
1507 	struct sigstack nss, oss;
1508 	int error = 0;
1509 
1510 	if (uap->nss != NULL) {
1511 		error = copyin(uap->nss, &nss, sizeof(nss));
1512 		if (error)
1513 			return (error);
1514 	}
1515 	oss.ss_sp = td->td_sigstk.ss_sp;
1516 	oss.ss_onstack = sigonstack(cpu_getstack(td));
1517 	if (uap->nss != NULL) {
1518 		td->td_sigstk.ss_sp = nss.ss_sp;
1519 		td->td_sigstk.ss_size = 0;
1520 		td->td_sigstk.ss_flags |= nss.ss_onstack & SS_ONSTACK;
1521 		td->td_pflags |= TDP_ALTSTACK;
1522 	}
1523 	if (uap->oss != NULL)
1524 		error = copyout(&oss, uap->oss, sizeof(oss));
1525 
1526 	return (error);
1527 }
1528 #endif /* COMPAT_43 */
1529 
1530 #ifndef _SYS_SYSPROTO_H_
1531 struct sigaltstack_args {
1532 	stack_t	*ss;
1533 	stack_t	*oss;
1534 };
1535 #endif
1536 /* ARGSUSED */
1537 int
1538 sys_sigaltstack(td, uap)
1539 	struct thread *td;
1540 	register struct sigaltstack_args *uap;
1541 {
1542 	stack_t ss, oss;
1543 	int error;
1544 
1545 	if (uap->ss != NULL) {
1546 		error = copyin(uap->ss, &ss, sizeof(ss));
1547 		if (error)
1548 			return (error);
1549 	}
1550 	error = kern_sigaltstack(td, (uap->ss != NULL) ? &ss : NULL,
1551 	    (uap->oss != NULL) ? &oss : NULL);
1552 	if (error)
1553 		return (error);
1554 	if (uap->oss != NULL)
1555 		error = copyout(&oss, uap->oss, sizeof(stack_t));
1556 	return (error);
1557 }
1558 
1559 int
1560 kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
1561 {
1562 	struct proc *p = td->td_proc;
1563 	int oonstack;
1564 
1565 	oonstack = sigonstack(cpu_getstack(td));
1566 
1567 	if (oss != NULL) {
1568 		*oss = td->td_sigstk;
1569 		oss->ss_flags = (td->td_pflags & TDP_ALTSTACK)
1570 		    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1571 	}
1572 
1573 	if (ss != NULL) {
1574 		if (oonstack)
1575 			return (EPERM);
1576 		if ((ss->ss_flags & ~SS_DISABLE) != 0)
1577 			return (EINVAL);
1578 		if (!(ss->ss_flags & SS_DISABLE)) {
1579 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
1580 				return (ENOMEM);
1581 
1582 			td->td_sigstk = *ss;
1583 			td->td_pflags |= TDP_ALTSTACK;
1584 		} else {
1585 			td->td_pflags &= ~TDP_ALTSTACK;
1586 		}
1587 	}
1588 	return (0);
1589 }
1590 
1591 /*
1592  * Common code for kill process group/broadcast kill.
1593  * cp is calling process.
1594  */
1595 static int
1596 killpg1(struct thread *td, int sig, int pgid, int all, ksiginfo_t *ksi)
1597 {
1598 	struct proc *p;
1599 	struct pgrp *pgrp;
1600 	int err;
1601 	int ret;
1602 
1603 	ret = ESRCH;
1604 	if (all) {
1605 		/*
1606 		 * broadcast
1607 		 */
1608 		sx_slock(&allproc_lock);
1609 		FOREACH_PROC_IN_SYSTEM(p) {
1610 			PROC_LOCK(p);
1611 			if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1612 			    p == td->td_proc || p->p_state == PRS_NEW) {
1613 				PROC_UNLOCK(p);
1614 				continue;
1615 			}
1616 			err = p_cansignal(td, p, sig);
1617 			if (err == 0) {
1618 				if (sig)
1619 					pksignal(p, sig, ksi);
1620 				ret = err;
1621 			}
1622 			else if (ret == ESRCH)
1623 				ret = err;
1624 			PROC_UNLOCK(p);
1625 		}
1626 		sx_sunlock(&allproc_lock);
1627 	} else {
1628 		sx_slock(&proctree_lock);
1629 		if (pgid == 0) {
1630 			/*
1631 			 * zero pgid means send to my process group.
1632 			 */
1633 			pgrp = td->td_proc->p_pgrp;
1634 			PGRP_LOCK(pgrp);
1635 		} else {
1636 			pgrp = pgfind(pgid);
1637 			if (pgrp == NULL) {
1638 				sx_sunlock(&proctree_lock);
1639 				return (ESRCH);
1640 			}
1641 		}
1642 		sx_sunlock(&proctree_lock);
1643 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1644 			PROC_LOCK(p);
1645 			if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1646 			    p->p_state == PRS_NEW) {
1647 				PROC_UNLOCK(p);
1648 				continue;
1649 			}
1650 			err = p_cansignal(td, p, sig);
1651 			if (err == 0) {
1652 				if (sig)
1653 					pksignal(p, sig, ksi);
1654 				ret = err;
1655 			}
1656 			else if (ret == ESRCH)
1657 				ret = err;
1658 			PROC_UNLOCK(p);
1659 		}
1660 		PGRP_UNLOCK(pgrp);
1661 	}
1662 	return (ret);
1663 }
1664 
1665 #ifndef _SYS_SYSPROTO_H_
1666 struct kill_args {
1667 	int	pid;
1668 	int	signum;
1669 };
1670 #endif
1671 /* ARGSUSED */
1672 int
1673 sys_kill(struct thread *td, struct kill_args *uap)
1674 {
1675 	ksiginfo_t ksi;
1676 	struct proc *p;
1677 	int error;
1678 
1679 	/*
1680 	 * A process in capability mode can send signals only to himself.
1681 	 * The main rationale behind this is that abort(3) is implemented as
1682 	 * kill(getpid(), SIGABRT).
1683 	 */
1684 	if (IN_CAPABILITY_MODE(td) && uap->pid != td->td_proc->p_pid)
1685 		return (ECAPMODE);
1686 
1687 	AUDIT_ARG_SIGNUM(uap->signum);
1688 	AUDIT_ARG_PID(uap->pid);
1689 	if ((u_int)uap->signum > _SIG_MAXSIG)
1690 		return (EINVAL);
1691 
1692 	ksiginfo_init(&ksi);
1693 	ksi.ksi_signo = uap->signum;
1694 	ksi.ksi_code = SI_USER;
1695 	ksi.ksi_pid = td->td_proc->p_pid;
1696 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1697 
1698 	if (uap->pid > 0) {
1699 		/* kill single process */
1700 		if ((p = pfind(uap->pid)) == NULL) {
1701 			if ((p = zpfind(uap->pid)) == NULL)
1702 				return (ESRCH);
1703 		}
1704 		AUDIT_ARG_PROCESS(p);
1705 		error = p_cansignal(td, p, uap->signum);
1706 		if (error == 0 && uap->signum)
1707 			pksignal(p, uap->signum, &ksi);
1708 		PROC_UNLOCK(p);
1709 		return (error);
1710 	}
1711 	switch (uap->pid) {
1712 	case -1:		/* broadcast signal */
1713 		return (killpg1(td, uap->signum, 0, 1, &ksi));
1714 	case 0:			/* signal own process group */
1715 		return (killpg1(td, uap->signum, 0, 0, &ksi));
1716 	default:		/* negative explicit process group */
1717 		return (killpg1(td, uap->signum, -uap->pid, 0, &ksi));
1718 	}
1719 	/* NOTREACHED */
1720 }
1721 
1722 int
1723 sys_pdkill(td, uap)
1724 	struct thread *td;
1725 	struct pdkill_args *uap;
1726 {
1727 #ifdef PROCDESC
1728 	struct proc *p;
1729 	int error;
1730 
1731 	AUDIT_ARG_SIGNUM(uap->signum);
1732 	AUDIT_ARG_FD(uap->fd);
1733 	if ((u_int)uap->signum > _SIG_MAXSIG)
1734 		return (EINVAL);
1735 
1736 	error = procdesc_find(td, uap->fd, CAP_PDKILL, &p);
1737 	if (error)
1738 		return (error);
1739 	AUDIT_ARG_PROCESS(p);
1740 	error = p_cansignal(td, p, uap->signum);
1741 	if (error == 0 && uap->signum)
1742 		kern_psignal(p, uap->signum);
1743 	PROC_UNLOCK(p);
1744 	return (error);
1745 #else
1746 	return (ENOSYS);
1747 #endif
1748 }
1749 
1750 #if defined(COMPAT_43)
1751 #ifndef _SYS_SYSPROTO_H_
1752 struct okillpg_args {
1753 	int	pgid;
1754 	int	signum;
1755 };
1756 #endif
1757 /* ARGSUSED */
1758 int
1759 okillpg(struct thread *td, struct okillpg_args *uap)
1760 {
1761 	ksiginfo_t ksi;
1762 
1763 	AUDIT_ARG_SIGNUM(uap->signum);
1764 	AUDIT_ARG_PID(uap->pgid);
1765 	if ((u_int)uap->signum > _SIG_MAXSIG)
1766 		return (EINVAL);
1767 
1768 	ksiginfo_init(&ksi);
1769 	ksi.ksi_signo = uap->signum;
1770 	ksi.ksi_code = SI_USER;
1771 	ksi.ksi_pid = td->td_proc->p_pid;
1772 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1773 	return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1774 }
1775 #endif /* COMPAT_43 */
1776 
1777 #ifndef _SYS_SYSPROTO_H_
1778 struct sigqueue_args {
1779 	pid_t pid;
1780 	int signum;
1781 	/* union sigval */ void *value;
1782 };
1783 #endif
1784 int
1785 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
1786 {
1787 	ksiginfo_t ksi;
1788 	struct proc *p;
1789 	int error;
1790 
1791 	if ((u_int)uap->signum > _SIG_MAXSIG)
1792 		return (EINVAL);
1793 
1794 	/*
1795 	 * Specification says sigqueue can only send signal to
1796 	 * single process.
1797 	 */
1798 	if (uap->pid <= 0)
1799 		return (EINVAL);
1800 
1801 	if ((p = pfind(uap->pid)) == NULL) {
1802 		if ((p = zpfind(uap->pid)) == NULL)
1803 			return (ESRCH);
1804 	}
1805 	error = p_cansignal(td, p, uap->signum);
1806 	if (error == 0 && uap->signum != 0) {
1807 		ksiginfo_init(&ksi);
1808 		ksi.ksi_flags = KSI_SIGQ;
1809 		ksi.ksi_signo = uap->signum;
1810 		ksi.ksi_code = SI_QUEUE;
1811 		ksi.ksi_pid = td->td_proc->p_pid;
1812 		ksi.ksi_uid = td->td_ucred->cr_ruid;
1813 		ksi.ksi_value.sival_ptr = uap->value;
1814 		error = pksignal(p, ksi.ksi_signo, &ksi);
1815 	}
1816 	PROC_UNLOCK(p);
1817 	return (error);
1818 }
1819 
1820 /*
1821  * Send a signal to a process group.
1822  */
1823 void
1824 gsignal(int pgid, int sig, ksiginfo_t *ksi)
1825 {
1826 	struct pgrp *pgrp;
1827 
1828 	if (pgid != 0) {
1829 		sx_slock(&proctree_lock);
1830 		pgrp = pgfind(pgid);
1831 		sx_sunlock(&proctree_lock);
1832 		if (pgrp != NULL) {
1833 			pgsignal(pgrp, sig, 0, ksi);
1834 			PGRP_UNLOCK(pgrp);
1835 		}
1836 	}
1837 }
1838 
1839 /*
1840  * Send a signal to a process group.  If checktty is 1,
1841  * limit to members which have a controlling terminal.
1842  */
1843 void
1844 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
1845 {
1846 	struct proc *p;
1847 
1848 	if (pgrp) {
1849 		PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
1850 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1851 			PROC_LOCK(p);
1852 			if (p->p_state == PRS_NORMAL &&
1853 			    (checkctty == 0 || p->p_flag & P_CONTROLT))
1854 				pksignal(p, sig, ksi);
1855 			PROC_UNLOCK(p);
1856 		}
1857 	}
1858 }
1859 
1860 /*
1861  * Send a signal caused by a trap to the current thread.  If it will be
1862  * caught immediately, deliver it with correct code.  Otherwise, post it
1863  * normally.
1864  */
1865 void
1866 trapsignal(struct thread *td, ksiginfo_t *ksi)
1867 {
1868 	struct sigacts *ps;
1869 	sigset_t mask;
1870 	struct proc *p;
1871 	int sig;
1872 	int code;
1873 
1874 	p = td->td_proc;
1875 	sig = ksi->ksi_signo;
1876 	code = ksi->ksi_code;
1877 	KASSERT(_SIG_VALID(sig), ("invalid signal"));
1878 
1879 	PROC_LOCK(p);
1880 	ps = p->p_sigacts;
1881 	mtx_lock(&ps->ps_mtx);
1882 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
1883 	    !SIGISMEMBER(td->td_sigmask, sig)) {
1884 		td->td_ru.ru_nsignals++;
1885 #ifdef KTRACE
1886 		if (KTRPOINT(curthread, KTR_PSIG))
1887 			ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
1888 			    &td->td_sigmask, code);
1889 #endif
1890 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
1891 				ksi, &td->td_sigmask);
1892 		mask = ps->ps_catchmask[_SIG_IDX(sig)];
1893 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
1894 			SIGADDSET(mask, sig);
1895 		kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
1896 		    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
1897 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
1898 			/*
1899 			 * See kern_sigaction() for origin of this code.
1900 			 */
1901 			SIGDELSET(ps->ps_sigcatch, sig);
1902 			if (sig != SIGCONT &&
1903 			    sigprop(sig) & SA_IGNORE)
1904 				SIGADDSET(ps->ps_sigignore, sig);
1905 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1906 		}
1907 		mtx_unlock(&ps->ps_mtx);
1908 	} else {
1909 		/*
1910 		 * Avoid a possible infinite loop if the thread
1911 		 * masking the signal or process is ignoring the
1912 		 * signal.
1913 		 */
1914 		if (kern_forcesigexit &&
1915 		    (SIGISMEMBER(td->td_sigmask, sig) ||
1916 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
1917 			SIGDELSET(td->td_sigmask, sig);
1918 			SIGDELSET(ps->ps_sigcatch, sig);
1919 			SIGDELSET(ps->ps_sigignore, sig);
1920 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1921 		}
1922 		mtx_unlock(&ps->ps_mtx);
1923 		p->p_code = code;	/* XXX for core dump/debugger */
1924 		p->p_sig = sig;		/* XXX to verify code */
1925 		tdsendsignal(p, td, sig, ksi);
1926 	}
1927 	PROC_UNLOCK(p);
1928 }
1929 
1930 static struct thread *
1931 sigtd(struct proc *p, int sig, int prop)
1932 {
1933 	struct thread *td, *signal_td;
1934 
1935 	PROC_LOCK_ASSERT(p, MA_OWNED);
1936 
1937 	/*
1938 	 * Check if current thread can handle the signal without
1939 	 * switching context to another thread.
1940 	 */
1941 	if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig))
1942 		return (curthread);
1943 	signal_td = NULL;
1944 	FOREACH_THREAD_IN_PROC(p, td) {
1945 		if (!SIGISMEMBER(td->td_sigmask, sig)) {
1946 			signal_td = td;
1947 			break;
1948 		}
1949 	}
1950 	if (signal_td == NULL)
1951 		signal_td = FIRST_THREAD_IN_PROC(p);
1952 	return (signal_td);
1953 }
1954 
1955 /*
1956  * Send the signal to the process.  If the signal has an action, the action
1957  * is usually performed by the target process rather than the caller; we add
1958  * the signal to the set of pending signals for the process.
1959  *
1960  * Exceptions:
1961  *   o When a stop signal is sent to a sleeping process that takes the
1962  *     default action, the process is stopped without awakening it.
1963  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
1964  *     regardless of the signal action (eg, blocked or ignored).
1965  *
1966  * Other ignored signals are discarded immediately.
1967  *
1968  * NB: This function may be entered from the debugger via the "kill" DDB
1969  * command.  There is little that can be done to mitigate the possibly messy
1970  * side effects of this unwise possibility.
1971  */
1972 void
1973 kern_psignal(struct proc *p, int sig)
1974 {
1975 	ksiginfo_t ksi;
1976 
1977 	ksiginfo_init(&ksi);
1978 	ksi.ksi_signo = sig;
1979 	ksi.ksi_code = SI_KERNEL;
1980 	(void) tdsendsignal(p, NULL, sig, &ksi);
1981 }
1982 
1983 int
1984 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
1985 {
1986 
1987 	return (tdsendsignal(p, NULL, sig, ksi));
1988 }
1989 
1990 /* Utility function for finding a thread to send signal event to. */
1991 int
1992 sigev_findtd(struct proc *p ,struct sigevent *sigev, struct thread **ttd)
1993 {
1994 	struct thread *td;
1995 
1996 	if (sigev->sigev_notify == SIGEV_THREAD_ID) {
1997 		td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
1998 		if (td == NULL)
1999 			return (ESRCH);
2000 		*ttd = td;
2001 	} else {
2002 		*ttd = NULL;
2003 		PROC_LOCK(p);
2004 	}
2005 	return (0);
2006 }
2007 
2008 void
2009 tdsignal(struct thread *td, int sig)
2010 {
2011 	ksiginfo_t ksi;
2012 
2013 	ksiginfo_init(&ksi);
2014 	ksi.ksi_signo = sig;
2015 	ksi.ksi_code = SI_KERNEL;
2016 	(void) tdsendsignal(td->td_proc, td, sig, &ksi);
2017 }
2018 
2019 void
2020 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2021 {
2022 
2023 	(void) tdsendsignal(td->td_proc, td, sig, ksi);
2024 }
2025 
2026 int
2027 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2028 {
2029 	sig_t action;
2030 	sigqueue_t *sigqueue;
2031 	int prop;
2032 	struct sigacts *ps;
2033 	int intrval;
2034 	int ret = 0;
2035 	int wakeup_swapper;
2036 
2037 	MPASS(td == NULL || p == td->td_proc);
2038 	PROC_LOCK_ASSERT(p, MA_OWNED);
2039 
2040 	if (!_SIG_VALID(sig))
2041 		panic("%s(): invalid signal %d", __func__, sig);
2042 
2043 	KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2044 
2045 	/*
2046 	 * IEEE Std 1003.1-2001: return success when killing a zombie.
2047 	 */
2048 	if (p->p_state == PRS_ZOMBIE) {
2049 		if (ksi && (ksi->ksi_flags & KSI_INS))
2050 			ksiginfo_tryfree(ksi);
2051 		return (ret);
2052 	}
2053 
2054 	ps = p->p_sigacts;
2055 	KNOTE_LOCKED(&p->p_klist, NOTE_SIGNAL | sig);
2056 	prop = sigprop(sig);
2057 
2058 	if (td == NULL) {
2059 		td = sigtd(p, sig, prop);
2060 		sigqueue = &p->p_sigqueue;
2061 	} else
2062 		sigqueue = &td->td_sigqueue;
2063 
2064 	SDT_PROBE(proc, kernel, , signal_send, td, p, sig, 0, 0 );
2065 
2066 	/*
2067 	 * If the signal is being ignored,
2068 	 * then we forget about it immediately.
2069 	 * (Note: we don't set SIGCONT in ps_sigignore,
2070 	 * and if it is set to SIG_IGN,
2071 	 * action will be SIG_DFL here.)
2072 	 */
2073 	mtx_lock(&ps->ps_mtx);
2074 	if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2075 		SDT_PROBE(proc, kernel, , signal_discard, td, p, sig, 0, 0 );
2076 
2077 		mtx_unlock(&ps->ps_mtx);
2078 		if (ksi && (ksi->ksi_flags & KSI_INS))
2079 			ksiginfo_tryfree(ksi);
2080 		return (ret);
2081 	}
2082 	if (SIGISMEMBER(td->td_sigmask, sig))
2083 		action = SIG_HOLD;
2084 	else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2085 		action = SIG_CATCH;
2086 	else
2087 		action = SIG_DFL;
2088 	if (SIGISMEMBER(ps->ps_sigintr, sig))
2089 		intrval = EINTR;
2090 	else
2091 		intrval = ERESTART;
2092 	mtx_unlock(&ps->ps_mtx);
2093 
2094 	if (prop & SA_CONT)
2095 		sigqueue_delete_stopmask_proc(p);
2096 	else if (prop & SA_STOP) {
2097 		/*
2098 		 * If sending a tty stop signal to a member of an orphaned
2099 		 * process group, discard the signal here if the action
2100 		 * is default; don't stop the process below if sleeping,
2101 		 * and don't clear any pending SIGCONT.
2102 		 */
2103 		if ((prop & SA_TTYSTOP) &&
2104 		    (p->p_pgrp->pg_jobc == 0) &&
2105 		    (action == SIG_DFL)) {
2106 			if (ksi && (ksi->ksi_flags & KSI_INS))
2107 				ksiginfo_tryfree(ksi);
2108 			return (ret);
2109 		}
2110 		sigqueue_delete_proc(p, SIGCONT);
2111 		if (p->p_flag & P_CONTINUED) {
2112 			p->p_flag &= ~P_CONTINUED;
2113 			PROC_LOCK(p->p_pptr);
2114 			sigqueue_take(p->p_ksi);
2115 			PROC_UNLOCK(p->p_pptr);
2116 		}
2117 	}
2118 
2119 	ret = sigqueue_add(sigqueue, sig, ksi);
2120 	if (ret != 0)
2121 		return (ret);
2122 	signotify(td);
2123 	/*
2124 	 * Defer further processing for signals which are held,
2125 	 * except that stopped processes must be continued by SIGCONT.
2126 	 */
2127 	if (action == SIG_HOLD &&
2128 	    !((prop & SA_CONT) && (p->p_flag & P_STOPPED_SIG)))
2129 		return (ret);
2130 	/*
2131 	 * SIGKILL: Remove procfs STOPEVENTs.
2132 	 */
2133 	if (sig == SIGKILL) {
2134 		/* from procfs_ioctl.c: PIOCBIC */
2135 		p->p_stops = 0;
2136 		/* from procfs_ioctl.c: PIOCCONT */
2137 		p->p_step = 0;
2138 		wakeup(&p->p_step);
2139 	}
2140 	/*
2141 	 * Some signals have a process-wide effect and a per-thread
2142 	 * component.  Most processing occurs when the process next
2143 	 * tries to cross the user boundary, however there are some
2144 	 * times when processing needs to be done immediately, such as
2145 	 * waking up threads so that they can cross the user boundary.
2146 	 * We try to do the per-process part here.
2147 	 */
2148 	if (P_SHOULDSTOP(p)) {
2149 		KASSERT(!(p->p_flag & P_WEXIT),
2150 		    ("signal to stopped but exiting process"));
2151 		if (sig == SIGKILL) {
2152 			/*
2153 			 * If traced process is already stopped,
2154 			 * then no further action is necessary.
2155 			 */
2156 			if (p->p_flag & P_TRACED)
2157 				goto out;
2158 			/*
2159 			 * SIGKILL sets process running.
2160 			 * It will die elsewhere.
2161 			 * All threads must be restarted.
2162 			 */
2163 			p->p_flag &= ~P_STOPPED_SIG;
2164 			goto runfast;
2165 		}
2166 
2167 		if (prop & SA_CONT) {
2168 			/*
2169 			 * If traced process is already stopped,
2170 			 * then no further action is necessary.
2171 			 */
2172 			if (p->p_flag & P_TRACED)
2173 				goto out;
2174 			/*
2175 			 * If SIGCONT is default (or ignored), we continue the
2176 			 * process but don't leave the signal in sigqueue as
2177 			 * it has no further action.  If SIGCONT is held, we
2178 			 * continue the process and leave the signal in
2179 			 * sigqueue.  If the process catches SIGCONT, let it
2180 			 * handle the signal itself.  If it isn't waiting on
2181 			 * an event, it goes back to run state.
2182 			 * Otherwise, process goes back to sleep state.
2183 			 */
2184 			p->p_flag &= ~P_STOPPED_SIG;
2185 			PROC_SLOCK(p);
2186 			if (p->p_numthreads == p->p_suspcount) {
2187 				PROC_SUNLOCK(p);
2188 				p->p_flag |= P_CONTINUED;
2189 				p->p_xstat = SIGCONT;
2190 				PROC_LOCK(p->p_pptr);
2191 				childproc_continued(p);
2192 				PROC_UNLOCK(p->p_pptr);
2193 				PROC_SLOCK(p);
2194 			}
2195 			if (action == SIG_DFL) {
2196 				thread_unsuspend(p);
2197 				PROC_SUNLOCK(p);
2198 				sigqueue_delete(sigqueue, sig);
2199 				goto out;
2200 			}
2201 			if (action == SIG_CATCH) {
2202 				/*
2203 				 * The process wants to catch it so it needs
2204 				 * to run at least one thread, but which one?
2205 				 */
2206 				PROC_SUNLOCK(p);
2207 				goto runfast;
2208 			}
2209 			/*
2210 			 * The signal is not ignored or caught.
2211 			 */
2212 			thread_unsuspend(p);
2213 			PROC_SUNLOCK(p);
2214 			goto out;
2215 		}
2216 
2217 		if (prop & SA_STOP) {
2218 			/*
2219 			 * If traced process is already stopped,
2220 			 * then no further action is necessary.
2221 			 */
2222 			if (p->p_flag & P_TRACED)
2223 				goto out;
2224 			/*
2225 			 * Already stopped, don't need to stop again
2226 			 * (If we did the shell could get confused).
2227 			 * Just make sure the signal STOP bit set.
2228 			 */
2229 			p->p_flag |= P_STOPPED_SIG;
2230 			sigqueue_delete(sigqueue, sig);
2231 			goto out;
2232 		}
2233 
2234 		/*
2235 		 * All other kinds of signals:
2236 		 * If a thread is sleeping interruptibly, simulate a
2237 		 * wakeup so that when it is continued it will be made
2238 		 * runnable and can look at the signal.  However, don't make
2239 		 * the PROCESS runnable, leave it stopped.
2240 		 * It may run a bit until it hits a thread_suspend_check().
2241 		 */
2242 		wakeup_swapper = 0;
2243 		PROC_SLOCK(p);
2244 		thread_lock(td);
2245 		if (TD_ON_SLEEPQ(td) && (td->td_flags & TDF_SINTR))
2246 			wakeup_swapper = sleepq_abort(td, intrval);
2247 		thread_unlock(td);
2248 		PROC_SUNLOCK(p);
2249 		if (wakeup_swapper)
2250 			kick_proc0();
2251 		goto out;
2252 		/*
2253 		 * Mutexes are short lived. Threads waiting on them will
2254 		 * hit thread_suspend_check() soon.
2255 		 */
2256 	} else if (p->p_state == PRS_NORMAL) {
2257 		if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2258 			tdsigwakeup(td, sig, action, intrval);
2259 			goto out;
2260 		}
2261 
2262 		MPASS(action == SIG_DFL);
2263 
2264 		if (prop & SA_STOP) {
2265 			if (p->p_flag & (P_PPWAIT|P_WEXIT))
2266 				goto out;
2267 			p->p_flag |= P_STOPPED_SIG;
2268 			p->p_xstat = sig;
2269 			PROC_SLOCK(p);
2270 			sig_suspend_threads(td, p, 1);
2271 			if (p->p_numthreads == p->p_suspcount) {
2272 				/*
2273 				 * only thread sending signal to another
2274 				 * process can reach here, if thread is sending
2275 				 * signal to its process, because thread does
2276 				 * not suspend itself here, p_numthreads
2277 				 * should never be equal to p_suspcount.
2278 				 */
2279 				thread_stopped(p);
2280 				PROC_SUNLOCK(p);
2281 				sigqueue_delete_proc(p, p->p_xstat);
2282 			} else
2283 				PROC_SUNLOCK(p);
2284 			goto out;
2285 		}
2286 	} else {
2287 		/* Not in "NORMAL" state. discard the signal. */
2288 		sigqueue_delete(sigqueue, sig);
2289 		goto out;
2290 	}
2291 
2292 	/*
2293 	 * The process is not stopped so we need to apply the signal to all the
2294 	 * running threads.
2295 	 */
2296 runfast:
2297 	tdsigwakeup(td, sig, action, intrval);
2298 	PROC_SLOCK(p);
2299 	thread_unsuspend(p);
2300 	PROC_SUNLOCK(p);
2301 out:
2302 	/* If we jump here, proc slock should not be owned. */
2303 	PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2304 	return (ret);
2305 }
2306 
2307 /*
2308  * The force of a signal has been directed against a single
2309  * thread.  We need to see what we can do about knocking it
2310  * out of any sleep it may be in etc.
2311  */
2312 static void
2313 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2314 {
2315 	struct proc *p = td->td_proc;
2316 	register int prop;
2317 	int wakeup_swapper;
2318 
2319 	wakeup_swapper = 0;
2320 	PROC_LOCK_ASSERT(p, MA_OWNED);
2321 	prop = sigprop(sig);
2322 
2323 	PROC_SLOCK(p);
2324 	thread_lock(td);
2325 	/*
2326 	 * Bring the priority of a thread up if we want it to get
2327 	 * killed in this lifetime.
2328 	 */
2329 	if (action == SIG_DFL && (prop & SA_KILL) && td->td_priority > PUSER)
2330 		sched_prio(td, PUSER);
2331 	if (TD_ON_SLEEPQ(td)) {
2332 		/*
2333 		 * If thread is sleeping uninterruptibly
2334 		 * we can't interrupt the sleep... the signal will
2335 		 * be noticed when the process returns through
2336 		 * trap() or syscall().
2337 		 */
2338 		if ((td->td_flags & TDF_SINTR) == 0)
2339 			goto out;
2340 		/*
2341 		 * If SIGCONT is default (or ignored) and process is
2342 		 * asleep, we are finished; the process should not
2343 		 * be awakened.
2344 		 */
2345 		if ((prop & SA_CONT) && action == SIG_DFL) {
2346 			thread_unlock(td);
2347 			PROC_SUNLOCK(p);
2348 			sigqueue_delete(&p->p_sigqueue, sig);
2349 			/*
2350 			 * It may be on either list in this state.
2351 			 * Remove from both for now.
2352 			 */
2353 			sigqueue_delete(&td->td_sigqueue, sig);
2354 			return;
2355 		}
2356 
2357 		/*
2358 		 * Don't awaken a sleeping thread for SIGSTOP if the
2359 		 * STOP signal is deferred.
2360 		 */
2361 		if ((prop & SA_STOP) && (td->td_flags & TDF_SBDRY))
2362 			goto out;
2363 
2364 		/*
2365 		 * Give low priority threads a better chance to run.
2366 		 */
2367 		if (td->td_priority > PUSER)
2368 			sched_prio(td, PUSER);
2369 
2370 		wakeup_swapper = sleepq_abort(td, intrval);
2371 	} else {
2372 		/*
2373 		 * Other states do nothing with the signal immediately,
2374 		 * other than kicking ourselves if we are running.
2375 		 * It will either never be noticed, or noticed very soon.
2376 		 */
2377 #ifdef SMP
2378 		if (TD_IS_RUNNING(td) && td != curthread)
2379 			forward_signal(td);
2380 #endif
2381 	}
2382 out:
2383 	PROC_SUNLOCK(p);
2384 	thread_unlock(td);
2385 	if (wakeup_swapper)
2386 		kick_proc0();
2387 }
2388 
2389 static void
2390 sig_suspend_threads(struct thread *td, struct proc *p, int sending)
2391 {
2392 	struct thread *td2;
2393 
2394 	PROC_LOCK_ASSERT(p, MA_OWNED);
2395 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2396 
2397 	FOREACH_THREAD_IN_PROC(p, td2) {
2398 		thread_lock(td2);
2399 		td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
2400 		if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2401 		    (td2->td_flags & TDF_SINTR)) {
2402 			if (td2->td_flags & TDF_SBDRY) {
2403 				/*
2404 				 * Once a thread is asleep with
2405 				 * TDF_SBDRY set, it should never
2406 				 * become suspended due to this check.
2407 				 */
2408 				KASSERT(!TD_IS_SUSPENDED(td2),
2409 				    ("thread with deferred stops suspended"));
2410 			} else if (!TD_IS_SUSPENDED(td2)) {
2411 				thread_suspend_one(td2);
2412 			}
2413 		} else if (!TD_IS_SUSPENDED(td2)) {
2414 			if (sending || td != td2)
2415 				td2->td_flags |= TDF_ASTPENDING;
2416 #ifdef SMP
2417 			if (TD_IS_RUNNING(td2) && td2 != td)
2418 				forward_signal(td2);
2419 #endif
2420 		}
2421 		thread_unlock(td2);
2422 	}
2423 }
2424 
2425 int
2426 ptracestop(struct thread *td, int sig)
2427 {
2428 	struct proc *p = td->td_proc;
2429 
2430 	PROC_LOCK_ASSERT(p, MA_OWNED);
2431 	KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2432 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2433 	    &p->p_mtx.lock_object, "Stopping for traced signal");
2434 
2435 	td->td_dbgflags |= TDB_XSIG;
2436 	td->td_xsig = sig;
2437 	PROC_SLOCK(p);
2438 	while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2439 		if (p->p_flag & P_SINGLE_EXIT) {
2440 			td->td_dbgflags &= ~TDB_XSIG;
2441 			PROC_SUNLOCK(p);
2442 			return (sig);
2443 		}
2444 		/*
2445 		 * Just make wait() to work, the last stopped thread
2446 		 * will win.
2447 		 */
2448 		p->p_xstat = sig;
2449 		p->p_xthread = td;
2450 		p->p_flag |= (P_STOPPED_SIG|P_STOPPED_TRACE);
2451 		sig_suspend_threads(td, p, 0);
2452 		if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2453 			td->td_dbgflags &= ~TDB_STOPATFORK;
2454 			cv_broadcast(&p->p_dbgwait);
2455 		}
2456 stopme:
2457 		thread_suspend_switch(td);
2458 		if (p->p_xthread == td)
2459 			p->p_xthread = NULL;
2460 		if (!(p->p_flag & P_TRACED))
2461 			break;
2462 		if (td->td_dbgflags & TDB_SUSPEND) {
2463 			if (p->p_flag & P_SINGLE_EXIT)
2464 				break;
2465 			goto stopme;
2466 		}
2467 	}
2468 	PROC_SUNLOCK(p);
2469 	return (td->td_xsig);
2470 }
2471 
2472 static void
2473 reschedule_signals(struct proc *p, sigset_t block, int flags)
2474 {
2475 	struct sigacts *ps;
2476 	struct thread *td;
2477 	int sig;
2478 
2479 	PROC_LOCK_ASSERT(p, MA_OWNED);
2480 	if (SIGISEMPTY(p->p_siglist))
2481 		return;
2482 	ps = p->p_sigacts;
2483 	SIGSETAND(block, p->p_siglist);
2484 	while ((sig = sig_ffs(&block)) != 0) {
2485 		SIGDELSET(block, sig);
2486 		td = sigtd(p, sig, 0);
2487 		signotify(td);
2488 		if (!(flags & SIGPROCMASK_PS_LOCKED))
2489 			mtx_lock(&ps->ps_mtx);
2490 		if (p->p_flag & P_TRACED || SIGISMEMBER(ps->ps_sigcatch, sig))
2491 			tdsigwakeup(td, sig, SIG_CATCH,
2492 			    (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2493 			     ERESTART));
2494 		if (!(flags & SIGPROCMASK_PS_LOCKED))
2495 			mtx_unlock(&ps->ps_mtx);
2496 	}
2497 }
2498 
2499 void
2500 tdsigcleanup(struct thread *td)
2501 {
2502 	struct proc *p;
2503 	sigset_t unblocked;
2504 
2505 	p = td->td_proc;
2506 	PROC_LOCK_ASSERT(p, MA_OWNED);
2507 
2508 	sigqueue_flush(&td->td_sigqueue);
2509 	if (p->p_numthreads == 1)
2510 		return;
2511 
2512 	/*
2513 	 * Since we cannot handle signals, notify signal post code
2514 	 * about this by filling the sigmask.
2515 	 *
2516 	 * Also, if needed, wake up thread(s) that do not block the
2517 	 * same signals as the exiting thread, since the thread might
2518 	 * have been selected for delivery and woken up.
2519 	 */
2520 	SIGFILLSET(unblocked);
2521 	SIGSETNAND(unblocked, td->td_sigmask);
2522 	SIGFILLSET(td->td_sigmask);
2523 	reschedule_signals(p, unblocked, 0);
2524 
2525 }
2526 
2527 /*
2528  * Defer the delivery of SIGSTOP for the current thread.  Returns true
2529  * if stops were deferred and false if they were already deferred.
2530  */
2531 int
2532 sigdeferstop(void)
2533 {
2534 	struct thread *td;
2535 
2536 	td = curthread;
2537 	if (td->td_flags & TDF_SBDRY)
2538 		return (0);
2539 	thread_lock(td);
2540 	td->td_flags |= TDF_SBDRY;
2541 	thread_unlock(td);
2542 	return (1);
2543 }
2544 
2545 /*
2546  * Permit the delivery of SIGSTOP for the current thread.  This does
2547  * not immediately suspend if a stop was posted.  Instead, the thread
2548  * will suspend either via ast() or a subsequent interruptible sleep.
2549  */
2550 void
2551 sigallowstop()
2552 {
2553 	struct thread *td;
2554 
2555 	td = curthread;
2556 	thread_lock(td);
2557 	td->td_flags &= ~TDF_SBDRY;
2558 	thread_unlock(td);
2559 }
2560 
2561 /*
2562  * If the current process has received a signal (should be caught or cause
2563  * termination, should interrupt current syscall), return the signal number.
2564  * Stop signals with default action are processed immediately, then cleared;
2565  * they aren't returned.  This is checked after each entry to the system for
2566  * a syscall or trap (though this can usually be done without calling issignal
2567  * by checking the pending signal masks in cursig.) The normal call
2568  * sequence is
2569  *
2570  *	while (sig = cursig(curthread))
2571  *		postsig(sig);
2572  */
2573 static int
2574 issignal(struct thread *td)
2575 {
2576 	struct proc *p;
2577 	struct sigacts *ps;
2578 	struct sigqueue *queue;
2579 	sigset_t sigpending;
2580 	int sig, prop, newsig;
2581 
2582 	p = td->td_proc;
2583 	ps = p->p_sigacts;
2584 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2585 	PROC_LOCK_ASSERT(p, MA_OWNED);
2586 	for (;;) {
2587 		int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
2588 
2589 		sigpending = td->td_sigqueue.sq_signals;
2590 		SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
2591 		SIGSETNAND(sigpending, td->td_sigmask);
2592 
2593 		if (p->p_flag & P_PPWAIT || td->td_flags & TDF_SBDRY)
2594 			SIG_STOPSIGMASK(sigpending);
2595 		if (SIGISEMPTY(sigpending))	/* no signal to send */
2596 			return (0);
2597 		sig = sig_ffs(&sigpending);
2598 
2599 		if (p->p_stops & S_SIG) {
2600 			mtx_unlock(&ps->ps_mtx);
2601 			stopevent(p, S_SIG, sig);
2602 			mtx_lock(&ps->ps_mtx);
2603 		}
2604 
2605 		/*
2606 		 * We should see pending but ignored signals
2607 		 * only if P_TRACED was on when they were posted.
2608 		 */
2609 		if (SIGISMEMBER(ps->ps_sigignore, sig) && (traced == 0)) {
2610 			sigqueue_delete(&td->td_sigqueue, sig);
2611 			sigqueue_delete(&p->p_sigqueue, sig);
2612 			continue;
2613 		}
2614 		if (p->p_flag & P_TRACED && (p->p_flag & P_PPTRACE) == 0) {
2615 			/*
2616 			 * If traced, always stop.
2617 			 * Remove old signal from queue before the stop.
2618 			 * XXX shrug off debugger, it causes siginfo to
2619 			 * be thrown away.
2620 			 */
2621 			queue = &td->td_sigqueue;
2622 			td->td_dbgksi.ksi_signo = 0;
2623 			if (sigqueue_get(queue, sig, &td->td_dbgksi) == 0) {
2624 				queue = &p->p_sigqueue;
2625 				sigqueue_get(queue, sig, &td->td_dbgksi);
2626 			}
2627 
2628 			mtx_unlock(&ps->ps_mtx);
2629 			newsig = ptracestop(td, sig);
2630 			mtx_lock(&ps->ps_mtx);
2631 
2632 			if (sig != newsig) {
2633 
2634 				/*
2635 				 * If parent wants us to take the signal,
2636 				 * then it will leave it in p->p_xstat;
2637 				 * otherwise we just look for signals again.
2638 				*/
2639 				if (newsig == 0)
2640 					continue;
2641 				sig = newsig;
2642 
2643 				/*
2644 				 * Put the new signal into td_sigqueue. If the
2645 				 * signal is being masked, look for other
2646 				 * signals.
2647 				 */
2648 				sigqueue_add(queue, sig, NULL);
2649 				if (SIGISMEMBER(td->td_sigmask, sig))
2650 					continue;
2651 				signotify(td);
2652 			} else {
2653 				if (td->td_dbgksi.ksi_signo != 0) {
2654 					td->td_dbgksi.ksi_flags |= KSI_HEAD;
2655 					if (sigqueue_add(&td->td_sigqueue, sig,
2656 					    &td->td_dbgksi) != 0)
2657 						td->td_dbgksi.ksi_signo = 0;
2658 				}
2659 				if (td->td_dbgksi.ksi_signo == 0)
2660 					sigqueue_add(&td->td_sigqueue, sig,
2661 					    NULL);
2662 			}
2663 
2664 			/*
2665 			 * If the traced bit got turned off, go back up
2666 			 * to the top to rescan signals.  This ensures
2667 			 * that p_sig* and p_sigact are consistent.
2668 			 */
2669 			if ((p->p_flag & P_TRACED) == 0)
2670 				continue;
2671 		}
2672 
2673 		prop = sigprop(sig);
2674 
2675 		/*
2676 		 * Decide whether the signal should be returned.
2677 		 * Return the signal's number, or fall through
2678 		 * to clear it from the pending mask.
2679 		 */
2680 		switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
2681 
2682 		case (intptr_t)SIG_DFL:
2683 			/*
2684 			 * Don't take default actions on system processes.
2685 			 */
2686 			if (p->p_pid <= 1) {
2687 #ifdef DIAGNOSTIC
2688 				/*
2689 				 * Are you sure you want to ignore SIGSEGV
2690 				 * in init? XXX
2691 				 */
2692 				printf("Process (pid %lu) got signal %d\n",
2693 					(u_long)p->p_pid, sig);
2694 #endif
2695 				break;		/* == ignore */
2696 			}
2697 			/*
2698 			 * If there is a pending stop signal to process
2699 			 * with default action, stop here,
2700 			 * then clear the signal.  However,
2701 			 * if process is member of an orphaned
2702 			 * process group, ignore tty stop signals.
2703 			 */
2704 			if (prop & SA_STOP) {
2705 				if (p->p_flag & (P_TRACED|P_WEXIT) ||
2706 				    (p->p_pgrp->pg_jobc == 0 &&
2707 				     prop & SA_TTYSTOP))
2708 					break;	/* == ignore */
2709 				mtx_unlock(&ps->ps_mtx);
2710 				WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2711 				    &p->p_mtx.lock_object, "Catching SIGSTOP");
2712 				p->p_flag |= P_STOPPED_SIG;
2713 				p->p_xstat = sig;
2714 				PROC_SLOCK(p);
2715 				sig_suspend_threads(td, p, 0);
2716 				thread_suspend_switch(td);
2717 				PROC_SUNLOCK(p);
2718 				mtx_lock(&ps->ps_mtx);
2719 				break;
2720 			} else if (prop & SA_IGNORE) {
2721 				/*
2722 				 * Except for SIGCONT, shouldn't get here.
2723 				 * Default action is to ignore; drop it.
2724 				 */
2725 				break;		/* == ignore */
2726 			} else
2727 				return (sig);
2728 			/*NOTREACHED*/
2729 
2730 		case (intptr_t)SIG_IGN:
2731 			/*
2732 			 * Masking above should prevent us ever trying
2733 			 * to take action on an ignored signal other
2734 			 * than SIGCONT, unless process is traced.
2735 			 */
2736 			if ((prop & SA_CONT) == 0 &&
2737 			    (p->p_flag & P_TRACED) == 0)
2738 				printf("issignal\n");
2739 			break;		/* == ignore */
2740 
2741 		default:
2742 			/*
2743 			 * This signal has an action, let
2744 			 * postsig() process it.
2745 			 */
2746 			return (sig);
2747 		}
2748 		sigqueue_delete(&td->td_sigqueue, sig);	/* take the signal! */
2749 		sigqueue_delete(&p->p_sigqueue, sig);
2750 	}
2751 	/* NOTREACHED */
2752 }
2753 
2754 void
2755 thread_stopped(struct proc *p)
2756 {
2757 	int n;
2758 
2759 	PROC_LOCK_ASSERT(p, MA_OWNED);
2760 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2761 	n = p->p_suspcount;
2762 	if (p == curproc)
2763 		n++;
2764 	if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
2765 		PROC_SUNLOCK(p);
2766 		p->p_flag &= ~P_WAITED;
2767 		PROC_LOCK(p->p_pptr);
2768 		childproc_stopped(p, (p->p_flag & P_TRACED) ?
2769 			CLD_TRAPPED : CLD_STOPPED);
2770 		PROC_UNLOCK(p->p_pptr);
2771 		PROC_SLOCK(p);
2772 	}
2773 }
2774 
2775 /*
2776  * Take the action for the specified signal
2777  * from the current set of pending signals.
2778  */
2779 int
2780 postsig(sig)
2781 	register int sig;
2782 {
2783 	struct thread *td = curthread;
2784 	register struct proc *p = td->td_proc;
2785 	struct sigacts *ps;
2786 	sig_t action;
2787 	ksiginfo_t ksi;
2788 	sigset_t returnmask, mask;
2789 
2790 	KASSERT(sig != 0, ("postsig"));
2791 
2792 	PROC_LOCK_ASSERT(p, MA_OWNED);
2793 	ps = p->p_sigacts;
2794 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2795 	ksiginfo_init(&ksi);
2796 	if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
2797 	    sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
2798 		return (0);
2799 	ksi.ksi_signo = sig;
2800 	if (ksi.ksi_code == SI_TIMER)
2801 		itimer_accept(p, ksi.ksi_timerid, &ksi);
2802 	action = ps->ps_sigact[_SIG_IDX(sig)];
2803 #ifdef KTRACE
2804 	if (KTRPOINT(td, KTR_PSIG))
2805 		ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
2806 		    &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
2807 #endif
2808 	if (p->p_stops & S_SIG) {
2809 		mtx_unlock(&ps->ps_mtx);
2810 		stopevent(p, S_SIG, sig);
2811 		mtx_lock(&ps->ps_mtx);
2812 	}
2813 
2814 	if (action == SIG_DFL) {
2815 		/*
2816 		 * Default action, where the default is to kill
2817 		 * the process.  (Other cases were ignored above.)
2818 		 */
2819 		mtx_unlock(&ps->ps_mtx);
2820 		sigexit(td, sig);
2821 		/* NOTREACHED */
2822 	} else {
2823 		/*
2824 		 * If we get here, the signal must be caught.
2825 		 */
2826 		KASSERT(action != SIG_IGN && !SIGISMEMBER(td->td_sigmask, sig),
2827 		    ("postsig action"));
2828 		/*
2829 		 * Set the new mask value and also defer further
2830 		 * occurrences of this signal.
2831 		 *
2832 		 * Special case: user has done a sigsuspend.  Here the
2833 		 * current mask is not of interest, but rather the
2834 		 * mask from before the sigsuspend is what we want
2835 		 * restored after the signal processing is completed.
2836 		 */
2837 		if (td->td_pflags & TDP_OLDMASK) {
2838 			returnmask = td->td_oldsigmask;
2839 			td->td_pflags &= ~TDP_OLDMASK;
2840 		} else
2841 			returnmask = td->td_sigmask;
2842 
2843 		mask = ps->ps_catchmask[_SIG_IDX(sig)];
2844 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
2845 			SIGADDSET(mask, sig);
2846 		kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
2847 		    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
2848 
2849 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
2850 			/*
2851 			 * See kern_sigaction() for origin of this code.
2852 			 */
2853 			SIGDELSET(ps->ps_sigcatch, sig);
2854 			if (sig != SIGCONT &&
2855 			    sigprop(sig) & SA_IGNORE)
2856 				SIGADDSET(ps->ps_sigignore, sig);
2857 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2858 		}
2859 		td->td_ru.ru_nsignals++;
2860 		if (p->p_sig == sig) {
2861 			p->p_code = 0;
2862 			p->p_sig = 0;
2863 		}
2864 		(*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
2865 	}
2866 	return (1);
2867 }
2868 
2869 /*
2870  * Kill the current process for stated reason.
2871  */
2872 void
2873 killproc(p, why)
2874 	struct proc *p;
2875 	char *why;
2876 {
2877 
2878 	PROC_LOCK_ASSERT(p, MA_OWNED);
2879 	CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
2880 	    p->p_comm);
2881 	log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n", p->p_pid,
2882 	    p->p_comm, p->p_ucred ? p->p_ucred->cr_uid : -1, why);
2883 	p->p_flag |= P_WKILLED;
2884 	kern_psignal(p, SIGKILL);
2885 }
2886 
2887 /*
2888  * Force the current process to exit with the specified signal, dumping core
2889  * if appropriate.  We bypass the normal tests for masked and caught signals,
2890  * allowing unrecoverable failures to terminate the process without changing
2891  * signal state.  Mark the accounting record with the signal termination.
2892  * If dumping core, save the signal number for the debugger.  Calls exit and
2893  * does not return.
2894  */
2895 void
2896 sigexit(td, sig)
2897 	struct thread *td;
2898 	int sig;
2899 {
2900 	struct proc *p = td->td_proc;
2901 
2902 	PROC_LOCK_ASSERT(p, MA_OWNED);
2903 	p->p_acflag |= AXSIG;
2904 	/*
2905 	 * We must be single-threading to generate a core dump.  This
2906 	 * ensures that the registers in the core file are up-to-date.
2907 	 * Also, the ELF dump handler assumes that the thread list doesn't
2908 	 * change out from under it.
2909 	 *
2910 	 * XXX If another thread attempts to single-thread before us
2911 	 *     (e.g. via fork()), we won't get a dump at all.
2912 	 */
2913 	if ((sigprop(sig) & SA_CORE) && (thread_single(SINGLE_NO_EXIT) == 0)) {
2914 		p->p_sig = sig;
2915 		/*
2916 		 * Log signals which would cause core dumps
2917 		 * (Log as LOG_INFO to appease those who don't want
2918 		 * these messages.)
2919 		 * XXX : Todo, as well as euid, write out ruid too
2920 		 * Note that coredump() drops proc lock.
2921 		 */
2922 		if (coredump(td) == 0)
2923 			sig |= WCOREFLAG;
2924 		if (kern_logsigexit)
2925 			log(LOG_INFO,
2926 			    "pid %d (%s), uid %d: exited on signal %d%s\n",
2927 			    p->p_pid, p->p_comm,
2928 			    td->td_ucred ? td->td_ucred->cr_uid : -1,
2929 			    sig &~ WCOREFLAG,
2930 			    sig & WCOREFLAG ? " (core dumped)" : "");
2931 	} else
2932 		PROC_UNLOCK(p);
2933 	exit1(td, W_EXITCODE(0, sig));
2934 	/* NOTREACHED */
2935 }
2936 
2937 /*
2938  * Send queued SIGCHLD to parent when child process's state
2939  * is changed.
2940  */
2941 static void
2942 sigparent(struct proc *p, int reason, int status)
2943 {
2944 	PROC_LOCK_ASSERT(p, MA_OWNED);
2945 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2946 
2947 	if (p->p_ksi != NULL) {
2948 		p->p_ksi->ksi_signo  = SIGCHLD;
2949 		p->p_ksi->ksi_code   = reason;
2950 		p->p_ksi->ksi_status = status;
2951 		p->p_ksi->ksi_pid    = p->p_pid;
2952 		p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
2953 		if (KSI_ONQ(p->p_ksi))
2954 			return;
2955 	}
2956 	pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
2957 }
2958 
2959 static void
2960 childproc_jobstate(struct proc *p, int reason, int status)
2961 {
2962 	struct sigacts *ps;
2963 
2964 	PROC_LOCK_ASSERT(p, MA_OWNED);
2965 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2966 
2967 	/*
2968 	 * Wake up parent sleeping in kern_wait(), also send
2969 	 * SIGCHLD to parent, but SIGCHLD does not guarantee
2970 	 * that parent will awake, because parent may masked
2971 	 * the signal.
2972 	 */
2973 	p->p_pptr->p_flag |= P_STATCHILD;
2974 	wakeup(p->p_pptr);
2975 
2976 	ps = p->p_pptr->p_sigacts;
2977 	mtx_lock(&ps->ps_mtx);
2978 	if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
2979 		mtx_unlock(&ps->ps_mtx);
2980 		sigparent(p, reason, status);
2981 	} else
2982 		mtx_unlock(&ps->ps_mtx);
2983 }
2984 
2985 void
2986 childproc_stopped(struct proc *p, int reason)
2987 {
2988 	childproc_jobstate(p, reason, p->p_xstat);
2989 }
2990 
2991 void
2992 childproc_continued(struct proc *p)
2993 {
2994 	childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
2995 }
2996 
2997 void
2998 childproc_exited(struct proc *p)
2999 {
3000 	int reason;
3001 	int status = p->p_xstat; /* convert to int */
3002 
3003 	reason = CLD_EXITED;
3004 	if (WCOREDUMP(status))
3005 		reason = CLD_DUMPED;
3006 	else if (WIFSIGNALED(status))
3007 		reason = CLD_KILLED;
3008 	/*
3009 	 * XXX avoid calling wakeup(p->p_pptr), the work is
3010 	 * done in exit1().
3011 	 */
3012 	sigparent(p, reason, status);
3013 }
3014 
3015 /*
3016  * We only have 1 character for the core count in the format
3017  * string, so the range will be 0-9
3018  */
3019 #define MAX_NUM_CORES 10
3020 static int num_cores = 5;
3021 
3022 static int
3023 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3024 {
3025 	int error;
3026 	int new_val;
3027 
3028 	new_val = num_cores;
3029 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3030 	if (error != 0 || req->newptr == NULL)
3031 		return (error);
3032 	if (new_val > MAX_NUM_CORES)
3033 		new_val = MAX_NUM_CORES;
3034 	if (new_val < 0)
3035 		new_val = 0;
3036 	num_cores = new_val;
3037 	return (0);
3038 }
3039 SYSCTL_PROC(_debug, OID_AUTO, ncores, CTLTYPE_INT|CTLFLAG_RW,
3040 	    0, sizeof(int), sysctl_debug_num_cores_check, "I", "");
3041 
3042 #if defined(COMPRESS_USER_CORES)
3043 int compress_user_cores = 1;
3044 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores, CTLFLAG_RW,
3045     &compress_user_cores, 0, "Compression of user corefiles");
3046 
3047 int compress_user_cores_gzlevel = -1; /* default level */
3048 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_gzlevel, CTLFLAG_RW,
3049     &compress_user_cores_gzlevel, -1, "Corefile gzip compression level");
3050 
3051 #define GZ_SUFFIX	".gz"
3052 #define GZ_SUFFIX_LEN	3
3053 #endif
3054 
3055 static char corefilename[MAXPATHLEN] = {"%N.core"};
3056 TUNABLE_STR("kern.corefile", corefilename, sizeof(corefilename));
3057 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RW, corefilename,
3058     sizeof(corefilename), "Process corefile name format string");
3059 
3060 /*
3061  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3062  * Expand the name described in corefilename, using name, uid, and pid
3063  * and open/create core file.
3064  * corefilename is a printf-like string, with three format specifiers:
3065  *	%N	name of process ("name")
3066  *	%P	process id (pid)
3067  *	%U	user id (uid)
3068  * For example, "%N.core" is the default; they can be disabled completely
3069  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3070  * This is controlled by the sysctl variable kern.corefile (see above).
3071  */
3072 static int
3073 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3074     int compress, struct vnode **vpp, char **namep)
3075 {
3076 	struct nameidata nd;
3077 	struct sbuf sb;
3078 	const char *format;
3079 	char *hostname, *name;
3080 	int indexpos, i, error, cmode, flags, oflags;
3081 
3082 	hostname = NULL;
3083 	format = corefilename;
3084 	name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3085 	indexpos = -1;
3086 	(void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3087 	for (i = 0; format[i] != '\0'; i++) {
3088 		switch (format[i]) {
3089 		case '%':	/* Format character */
3090 			i++;
3091 			switch (format[i]) {
3092 			case '%':
3093 				sbuf_putc(&sb, '%');
3094 				break;
3095 			case 'H':	/* hostname */
3096 				if (hostname == NULL) {
3097 					hostname = malloc(MAXHOSTNAMELEN,
3098 					    M_TEMP, M_WAITOK);
3099 				}
3100 				getcredhostname(td->td_ucred, hostname,
3101 				    MAXHOSTNAMELEN);
3102 				sbuf_printf(&sb, "%s", hostname);
3103 				break;
3104 			case 'I':	/* autoincrementing index */
3105 				sbuf_printf(&sb, "0");
3106 				indexpos = sbuf_len(&sb) - 1;
3107 				break;
3108 			case 'N':	/* process name */
3109 				sbuf_printf(&sb, "%s", comm);
3110 				break;
3111 			case 'P':	/* process id */
3112 				sbuf_printf(&sb, "%u", pid);
3113 				break;
3114 			case 'U':	/* user id */
3115 				sbuf_printf(&sb, "%u", uid);
3116 				break;
3117 			default:
3118 				log(LOG_ERR,
3119 				    "Unknown format character %c in "
3120 				    "corename `%s'\n", format[i], format);
3121 				break;
3122 			}
3123 			break;
3124 		default:
3125 			sbuf_putc(&sb, format[i]);
3126 			break;
3127 		}
3128 	}
3129 	free(hostname, M_TEMP);
3130 #ifdef COMPRESS_USER_CORES
3131 	if (compress)
3132 		sbuf_printf(&sb, GZ_SUFFIX);
3133 #endif
3134 	if (sbuf_error(&sb) != 0) {
3135 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
3136 		    "long\n", (long)pid, comm, (u_long)uid);
3137 		sbuf_delete(&sb);
3138 		free(name, M_TEMP);
3139 		return (ENOMEM);
3140 	}
3141 	sbuf_finish(&sb);
3142 	sbuf_delete(&sb);
3143 
3144 	cmode = S_IRUSR | S_IWUSR;
3145 	oflags = VN_OPEN_NOAUDIT | (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3146 
3147 	/*
3148 	 * If the core format has a %I in it, then we need to check
3149 	 * for existing corefiles before returning a name.
3150 	 * To do this we iterate over 0..num_cores to find a
3151 	 * non-existing core file name to use.
3152 	 */
3153 	if (indexpos != -1) {
3154 		for (i = 0; i < num_cores; i++) {
3155 			flags = O_CREAT | O_EXCL | FWRITE | O_NOFOLLOW;
3156 			name[indexpos] = '0' + i;
3157 			NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3158 			error = vn_open_cred(&nd, &flags, cmode, oflags,
3159 			    td->td_ucred, NULL);
3160 			if (error) {
3161 				if (error == EEXIST)
3162 					continue;
3163 				log(LOG_ERR,
3164 				    "pid %d (%s), uid (%u):  Path `%s' failed "
3165 				    "on initial open test, error = %d\n",
3166 				    pid, comm, uid, name, error);
3167 			}
3168 			goto out;
3169 		}
3170 	}
3171 
3172 	flags = O_CREAT | FWRITE | O_NOFOLLOW;
3173 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3174 	error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred, NULL);
3175 out:
3176 	if (error) {
3177 #ifdef AUDIT
3178 		audit_proc_coredump(td, name, error);
3179 #endif
3180 		free(name, M_TEMP);
3181 		return (error);
3182 	}
3183 	NDFREE(&nd, NDF_ONLY_PNBUF);
3184 	*vpp = nd.ni_vp;
3185 	*namep = name;
3186 	return (0);
3187 }
3188 
3189 /*
3190  * Dump a process' core.  The main routine does some
3191  * policy checking, and creates the name of the coredump;
3192  * then it passes on a vnode and a size limit to the process-specific
3193  * coredump routine if there is one; if there _is not_ one, it returns
3194  * ENOSYS; otherwise it returns the error from the process-specific routine.
3195  */
3196 
3197 static int
3198 coredump(struct thread *td)
3199 {
3200 	struct proc *p = td->td_proc;
3201 	struct ucred *cred = td->td_ucred;
3202 	struct vnode *vp;
3203 	struct flock lf;
3204 	struct vattr vattr;
3205 	int error, error1, locked;
3206 	struct mount *mp;
3207 	char *name;			/* name of corefile */
3208 	off_t limit;
3209 	int compress;
3210 
3211 #ifdef COMPRESS_USER_CORES
3212 	compress = compress_user_cores;
3213 #else
3214 	compress = 0;
3215 #endif
3216 	PROC_LOCK_ASSERT(p, MA_OWNED);
3217 	MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
3218 	_STOPEVENT(p, S_CORE, 0);
3219 
3220 	if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0)) {
3221 		PROC_UNLOCK(p);
3222 		return (EFAULT);
3223 	}
3224 
3225 	/*
3226 	 * Note that the bulk of limit checking is done after
3227 	 * the corefile is created.  The exception is if the limit
3228 	 * for corefiles is 0, in which case we don't bother
3229 	 * creating the corefile at all.  This layout means that
3230 	 * a corefile is truncated instead of not being created,
3231 	 * if it is larger than the limit.
3232 	 */
3233 	limit = (off_t)lim_cur(p, RLIMIT_CORE);
3234 	if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
3235 		PROC_UNLOCK(p);
3236 		return (EFBIG);
3237 	}
3238 	PROC_UNLOCK(p);
3239 
3240 restart:
3241 	error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td, compress,
3242 	    &vp, &name);
3243 	if (error != 0)
3244 		return (error);
3245 
3246 	/* Don't dump to non-regular files or files with links. */
3247 	if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
3248 	    vattr.va_nlink != 1) {
3249 		VOP_UNLOCK(vp, 0);
3250 		error = EFAULT;
3251 		goto close;
3252 	}
3253 
3254 	VOP_UNLOCK(vp, 0);
3255 	lf.l_whence = SEEK_SET;
3256 	lf.l_start = 0;
3257 	lf.l_len = 0;
3258 	lf.l_type = F_WRLCK;
3259 	locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
3260 
3261 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3262 		lf.l_type = F_UNLCK;
3263 		if (locked)
3264 			VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3265 		if ((error = vn_close(vp, FWRITE, cred, td)) != 0)
3266 			goto out;
3267 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3268 			goto out;
3269 		free(name, M_TEMP);
3270 		goto restart;
3271 	}
3272 
3273 	VATTR_NULL(&vattr);
3274 	vattr.va_size = 0;
3275 	if (set_core_nodump_flag)
3276 		vattr.va_flags = UF_NODUMP;
3277 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3278 	VOP_SETATTR(vp, &vattr, cred);
3279 	VOP_UNLOCK(vp, 0);
3280 	vn_finished_write(mp);
3281 	PROC_LOCK(p);
3282 	p->p_acflag |= ACORE;
3283 	PROC_UNLOCK(p);
3284 
3285 	if (p->p_sysent->sv_coredump != NULL) {
3286 		error = p->p_sysent->sv_coredump(td, vp, limit,
3287 		    compress ? IMGACT_CORE_COMPRESS : 0);
3288 	} else {
3289 		error = ENOSYS;
3290 	}
3291 
3292 	if (locked) {
3293 		lf.l_type = F_UNLCK;
3294 		VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3295 	}
3296 close:
3297 	error1 = vn_close(vp, FWRITE, cred, td);
3298 	if (error == 0)
3299 		error = error1;
3300 out:
3301 #ifdef AUDIT
3302 	audit_proc_coredump(td, name, error);
3303 #endif
3304 	free(name, M_TEMP);
3305 	return (error);
3306 }
3307 
3308 /*
3309  * Nonexistent system call-- signal process (may want to handle it).  Flag
3310  * error in case process won't see signal immediately (blocked or ignored).
3311  */
3312 #ifndef _SYS_SYSPROTO_H_
3313 struct nosys_args {
3314 	int	dummy;
3315 };
3316 #endif
3317 /* ARGSUSED */
3318 int
3319 nosys(td, args)
3320 	struct thread *td;
3321 	struct nosys_args *args;
3322 {
3323 	struct proc *p = td->td_proc;
3324 
3325 	PROC_LOCK(p);
3326 	tdsignal(td, SIGSYS);
3327 	PROC_UNLOCK(p);
3328 	return (ENOSYS);
3329 }
3330 
3331 /*
3332  * Send a SIGIO or SIGURG signal to a process or process group using stored
3333  * credentials rather than those of the current process.
3334  */
3335 void
3336 pgsigio(sigiop, sig, checkctty)
3337 	struct sigio **sigiop;
3338 	int sig, checkctty;
3339 {
3340 	ksiginfo_t ksi;
3341 	struct sigio *sigio;
3342 
3343 	ksiginfo_init(&ksi);
3344 	ksi.ksi_signo = sig;
3345 	ksi.ksi_code = SI_KERNEL;
3346 
3347 	SIGIO_LOCK();
3348 	sigio = *sigiop;
3349 	if (sigio == NULL) {
3350 		SIGIO_UNLOCK();
3351 		return;
3352 	}
3353 	if (sigio->sio_pgid > 0) {
3354 		PROC_LOCK(sigio->sio_proc);
3355 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
3356 			kern_psignal(sigio->sio_proc, sig);
3357 		PROC_UNLOCK(sigio->sio_proc);
3358 	} else if (sigio->sio_pgid < 0) {
3359 		struct proc *p;
3360 
3361 		PGRP_LOCK(sigio->sio_pgrp);
3362 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
3363 			PROC_LOCK(p);
3364 			if (p->p_state == PRS_NORMAL &&
3365 			    CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
3366 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
3367 				kern_psignal(p, sig);
3368 			PROC_UNLOCK(p);
3369 		}
3370 		PGRP_UNLOCK(sigio->sio_pgrp);
3371 	}
3372 	SIGIO_UNLOCK();
3373 }
3374 
3375 static int
3376 filt_sigattach(struct knote *kn)
3377 {
3378 	struct proc *p = curproc;
3379 
3380 	kn->kn_ptr.p_proc = p;
3381 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
3382 
3383 	knlist_add(&p->p_klist, kn, 0);
3384 
3385 	return (0);
3386 }
3387 
3388 static void
3389 filt_sigdetach(struct knote *kn)
3390 {
3391 	struct proc *p = kn->kn_ptr.p_proc;
3392 
3393 	knlist_remove(&p->p_klist, kn, 0);
3394 }
3395 
3396 /*
3397  * signal knotes are shared with proc knotes, so we apply a mask to
3398  * the hint in order to differentiate them from process hints.  This
3399  * could be avoided by using a signal-specific knote list, but probably
3400  * isn't worth the trouble.
3401  */
3402 static int
3403 filt_signal(struct knote *kn, long hint)
3404 {
3405 
3406 	if (hint & NOTE_SIGNAL) {
3407 		hint &= ~NOTE_SIGNAL;
3408 
3409 		if (kn->kn_id == hint)
3410 			kn->kn_data++;
3411 	}
3412 	return (kn->kn_data != 0);
3413 }
3414 
3415 struct sigacts *
3416 sigacts_alloc(void)
3417 {
3418 	struct sigacts *ps;
3419 
3420 	ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
3421 	ps->ps_refcnt = 1;
3422 	mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
3423 	return (ps);
3424 }
3425 
3426 void
3427 sigacts_free(struct sigacts *ps)
3428 {
3429 
3430 	mtx_lock(&ps->ps_mtx);
3431 	ps->ps_refcnt--;
3432 	if (ps->ps_refcnt == 0) {
3433 		mtx_destroy(&ps->ps_mtx);
3434 		free(ps, M_SUBPROC);
3435 	} else
3436 		mtx_unlock(&ps->ps_mtx);
3437 }
3438 
3439 struct sigacts *
3440 sigacts_hold(struct sigacts *ps)
3441 {
3442 	mtx_lock(&ps->ps_mtx);
3443 	ps->ps_refcnt++;
3444 	mtx_unlock(&ps->ps_mtx);
3445 	return (ps);
3446 }
3447 
3448 void
3449 sigacts_copy(struct sigacts *dest, struct sigacts *src)
3450 {
3451 
3452 	KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
3453 	mtx_lock(&src->ps_mtx);
3454 	bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
3455 	mtx_unlock(&src->ps_mtx);
3456 }
3457 
3458 int
3459 sigacts_shared(struct sigacts *ps)
3460 {
3461 	int shared;
3462 
3463 	mtx_lock(&ps->ps_mtx);
3464 	shared = ps->ps_refcnt > 1;
3465 	mtx_unlock(&ps->ps_mtx);
3466 	return (shared);
3467 }
3468