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