xref: /dflybsd-src/sys/kern/kern_sig.c (revision dae741e33c840b92a8a53bf9f01157ede145e256)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
39  * $FreeBSD: src/sys/kern/kern_sig.c,v 1.72.2.17 2003/05/16 16:34:34 obrien Exp $
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/sysproto.h>
48 #include <sys/signalvar.h>
49 #include <sys/resourcevar.h>
50 #include <sys/vnode.h>
51 #include <sys/event.h>
52 #include <sys/proc.h>
53 #include <sys/nlookup.h>
54 #include <sys/pioctl.h>
55 #include <sys/acct.h>
56 #include <sys/fcntl.h>
57 #include <sys/lock.h>
58 #include <sys/wait.h>
59 #include <sys/ktrace.h>
60 #include <sys/syslog.h>
61 #include <sys/stat.h>
62 #include <sys/sysent.h>
63 #include <sys/sysctl.h>
64 #include <sys/malloc.h>
65 #include <sys/interrupt.h>
66 #include <sys/unistd.h>
67 #include <sys/kern_syscall.h>
68 #include <sys/vkernel.h>
69 
70 #include <sys/signal2.h>
71 #include <sys/thread2.h>
72 
73 #include <machine/cpu.h>
74 #include <machine/smp.h>
75 
76 static int	coredump(struct lwp *, int);
77 static char	*expand_name(const char *, uid_t, pid_t);
78 static int	dokillpg(int sig, int pgid, int all);
79 static int	sig_ffs(sigset_t *set);
80 static int	sigprop(int sig);
81 static void	lwp_signotify(struct lwp *lp);
82 #ifdef SMP
83 static void	signotify_remote(void *arg);
84 #endif
85 static int	kern_sigtimedwait(sigset_t set, siginfo_t *info,
86 		    struct timespec *timeout);
87 
88 static int	filt_sigattach(struct knote *kn);
89 static void	filt_sigdetach(struct knote *kn);
90 static int	filt_signal(struct knote *kn, long hint);
91 
92 struct filterops sig_filtops =
93 	{ 0, filt_sigattach, filt_sigdetach, filt_signal };
94 
95 static int	kern_logsigexit = 1;
96 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
97     &kern_logsigexit, 0,
98     "Log processes quitting on abnormal signals to syslog(3)");
99 
100 /*
101  * Can process p, with pcred pc, send the signal sig to process q?
102  */
103 #define CANSIGNAL(q, sig) \
104 	(!p_trespass(curproc->p_ucred, (q)->p_ucred) || \
105 	((sig) == SIGCONT && (q)->p_session == curproc->p_session))
106 
107 /*
108  * Policy -- Can real uid ruid with ucred uc send a signal to process q?
109  */
110 #define CANSIGIO(ruid, uc, q) \
111 	((uc)->cr_uid == 0 || \
112 	    (ruid) == (q)->p_ucred->cr_ruid || \
113 	    (uc)->cr_uid == (q)->p_ucred->cr_ruid || \
114 	    (ruid) == (q)->p_ucred->cr_uid || \
115 	    (uc)->cr_uid == (q)->p_ucred->cr_uid)
116 
117 int sugid_coredump;
118 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RW,
119 	&sugid_coredump, 0, "Enable coredumping set user/group ID processes");
120 
121 static int	do_coredump = 1;
122 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
123 	&do_coredump, 0, "Enable/Disable coredumps");
124 
125 /*
126  * Signal properties and actions.
127  * The array below categorizes the signals and their default actions
128  * according to the following properties:
129  */
130 #define	SA_KILL		0x01		/* terminates process by default */
131 #define	SA_CORE		0x02		/* ditto and coredumps */
132 #define	SA_STOP		0x04		/* suspend process */
133 #define	SA_TTYSTOP	0x08		/* ditto, from tty */
134 #define	SA_IGNORE	0x10		/* ignore by default */
135 #define	SA_CONT		0x20		/* continue if suspended */
136 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
137 #define SA_CKPT         0x80            /* checkpoint process */
138 
139 
140 static int sigproptbl[NSIG] = {
141         SA_KILL,                /* SIGHUP */
142         SA_KILL,                /* SIGINT */
143         SA_KILL|SA_CORE,        /* SIGQUIT */
144         SA_KILL|SA_CORE,        /* SIGILL */
145         SA_KILL|SA_CORE,        /* SIGTRAP */
146         SA_KILL|SA_CORE,        /* SIGABRT */
147         SA_KILL|SA_CORE,        /* SIGEMT */
148         SA_KILL|SA_CORE,        /* SIGFPE */
149         SA_KILL,                /* SIGKILL */
150         SA_KILL|SA_CORE,        /* SIGBUS */
151         SA_KILL|SA_CORE,        /* SIGSEGV */
152         SA_KILL|SA_CORE,        /* SIGSYS */
153         SA_KILL,                /* SIGPIPE */
154         SA_KILL,                /* SIGALRM */
155         SA_KILL,                /* SIGTERM */
156         SA_IGNORE,              /* SIGURG */
157         SA_STOP,                /* SIGSTOP */
158         SA_STOP|SA_TTYSTOP,     /* SIGTSTP */
159         SA_IGNORE|SA_CONT,      /* SIGCONT */
160         SA_IGNORE,              /* SIGCHLD */
161         SA_STOP|SA_TTYSTOP,     /* SIGTTIN */
162         SA_STOP|SA_TTYSTOP,     /* SIGTTOU */
163         SA_IGNORE,              /* SIGIO */
164         SA_KILL,                /* SIGXCPU */
165         SA_KILL,                /* SIGXFSZ */
166         SA_KILL,                /* SIGVTALRM */
167         SA_KILL,                /* SIGPROF */
168         SA_IGNORE,              /* SIGWINCH  */
169         SA_IGNORE,              /* SIGINFO */
170         SA_KILL,                /* SIGUSR1 */
171         SA_KILL,                /* SIGUSR2 */
172 	SA_IGNORE,              /* SIGTHR */
173 	SA_CKPT,                /* SIGCKPT */
174 	SA_KILL|SA_CKPT,        /* SIGCKPTEXIT */
175 	SA_IGNORE,
176 	SA_IGNORE,
177 	SA_IGNORE,
178 	SA_IGNORE,
179 	SA_IGNORE,
180 	SA_IGNORE,
181 	SA_IGNORE,
182 	SA_IGNORE,
183 	SA_IGNORE,
184 	SA_IGNORE,
185 	SA_IGNORE,
186 	SA_IGNORE,
187 	SA_IGNORE,
188 	SA_IGNORE,
189 	SA_IGNORE,
190 	SA_IGNORE,
191 	SA_IGNORE,
192 	SA_IGNORE,
193 	SA_IGNORE,
194 	SA_IGNORE,
195 	SA_IGNORE,
196 	SA_IGNORE,
197 	SA_IGNORE,
198 	SA_IGNORE,
199 	SA_IGNORE,
200 	SA_IGNORE,
201 	SA_IGNORE,
202 	SA_IGNORE,
203 	SA_IGNORE,
204 	SA_IGNORE,
205 
206 };
207 
208 static __inline int
209 sigprop(int sig)
210 {
211 
212 	if (sig > 0 && sig < NSIG)
213 		return (sigproptbl[_SIG_IDX(sig)]);
214 	return (0);
215 }
216 
217 static __inline int
218 sig_ffs(sigset_t *set)
219 {
220 	int i;
221 
222 	for (i = 0; i < _SIG_WORDS; i++)
223 		if (set->__bits[i])
224 			return (ffs(set->__bits[i]) + (i * 32));
225 	return (0);
226 }
227 
228 /*
229  * No requirements.
230  */
231 int
232 kern_sigaction(int sig, struct sigaction *act, struct sigaction *oact)
233 {
234 	struct thread *td = curthread;
235 	struct proc *p = td->td_proc;
236 	struct lwp *lp;
237 	struct sigacts *ps = p->p_sigacts;
238 
239 	if (sig <= 0 || sig > _SIG_MAXSIG)
240 		return (EINVAL);
241 
242 	lwkt_gettoken(&p->p_token);
243 
244 	if (oact) {
245 		oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
246 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
247 		oact->sa_flags = 0;
248 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
249 			oact->sa_flags |= SA_ONSTACK;
250 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
251 			oact->sa_flags |= SA_RESTART;
252 		if (SIGISMEMBER(ps->ps_sigreset, sig))
253 			oact->sa_flags |= SA_RESETHAND;
254 		if (SIGISMEMBER(ps->ps_signodefer, sig))
255 			oact->sa_flags |= SA_NODEFER;
256 		if (SIGISMEMBER(ps->ps_siginfo, sig))
257 			oact->sa_flags |= SA_SIGINFO;
258 		if (SIGISMEMBER(ps->ps_sigmailbox, sig))
259 			oact->sa_flags |= SA_MAILBOX;
260 		if (sig == SIGCHLD && p->p_sigacts->ps_flag & PS_NOCLDSTOP)
261 			oact->sa_flags |= SA_NOCLDSTOP;
262 		if (sig == SIGCHLD && p->p_sigacts->ps_flag & PS_NOCLDWAIT)
263 			oact->sa_flags |= SA_NOCLDWAIT;
264 	}
265 	if (act) {
266 		/*
267 		 * Check for invalid requests.  KILL and STOP cannot be
268 		 * caught.
269 		 */
270 		if (sig == SIGKILL || sig == SIGSTOP) {
271 			if (act->sa_handler != SIG_DFL) {
272 				lwkt_reltoken(&p->p_token);
273 				return (EINVAL);
274 			}
275 #if 0
276 			/* (not needed, SIG_DFL forces action to occur) */
277 			if (act->sa_flags & SA_MAILBOX) {
278 				lwkt_reltoken(&p->p_token);
279 				return (EINVAL);
280 			}
281 #endif
282 		}
283 
284 		/*
285 		 * Change setting atomically.
286 		 */
287 		crit_enter();
288 
289 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
290 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
291 		if (act->sa_flags & SA_SIGINFO) {
292 			ps->ps_sigact[_SIG_IDX(sig)] =
293 			    (__sighandler_t *)act->sa_sigaction;
294 			SIGADDSET(ps->ps_siginfo, sig);
295 		} else {
296 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
297 			SIGDELSET(ps->ps_siginfo, sig);
298 		}
299 		if (!(act->sa_flags & SA_RESTART))
300 			SIGADDSET(ps->ps_sigintr, sig);
301 		else
302 			SIGDELSET(ps->ps_sigintr, sig);
303 		if (act->sa_flags & SA_ONSTACK)
304 			SIGADDSET(ps->ps_sigonstack, sig);
305 		else
306 			SIGDELSET(ps->ps_sigonstack, sig);
307 		if (act->sa_flags & SA_RESETHAND)
308 			SIGADDSET(ps->ps_sigreset, sig);
309 		else
310 			SIGDELSET(ps->ps_sigreset, sig);
311 		if (act->sa_flags & SA_NODEFER)
312 			SIGADDSET(ps->ps_signodefer, sig);
313 		else
314 			SIGDELSET(ps->ps_signodefer, sig);
315 		if (act->sa_flags & SA_MAILBOX)
316 			SIGADDSET(ps->ps_sigmailbox, sig);
317 		else
318 			SIGDELSET(ps->ps_sigmailbox, sig);
319 		if (sig == SIGCHLD) {
320 			if (act->sa_flags & SA_NOCLDSTOP)
321 				p->p_sigacts->ps_flag |= PS_NOCLDSTOP;
322 			else
323 				p->p_sigacts->ps_flag &= ~PS_NOCLDSTOP;
324 			if (act->sa_flags & SA_NOCLDWAIT) {
325 				/*
326 				 * Paranoia: since SA_NOCLDWAIT is implemented
327 				 * by reparenting the dying child to PID 1 (and
328 				 * trust it to reap the zombie), PID 1 itself
329 				 * is forbidden to set SA_NOCLDWAIT.
330 				 */
331 				if (p->p_pid == 1)
332 					p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
333 				else
334 					p->p_sigacts->ps_flag |= PS_NOCLDWAIT;
335 			} else {
336 				p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
337 			}
338 		}
339 		/*
340 		 * Set bit in p_sigignore for signals that are set to SIG_IGN,
341 		 * and for signals set to SIG_DFL where the default is to
342 		 * ignore. However, don't put SIGCONT in p_sigignore, as we
343 		 * have to restart the process.
344 		 */
345 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
346 		    (sigprop(sig) & SA_IGNORE &&
347 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
348 			/* never to be seen again */
349 			SIGDELSET(p->p_siglist, sig);
350 			/*
351 			 * Remove the signal also from the thread lists.
352 			 */
353 			FOREACH_LWP_IN_PROC(lp, p) {
354 				LWPHOLD(lp);
355 				lwkt_gettoken(&lp->lwp_token);
356 				SIGDELSET(lp->lwp_siglist, sig);
357 				lwkt_reltoken(&lp->lwp_token);
358 				LWPRELE(lp);
359 			}
360 			if (sig != SIGCONT) {
361 				/* easier in ksignal */
362 				SIGADDSET(p->p_sigignore, sig);
363 			}
364 			SIGDELSET(p->p_sigcatch, sig);
365 		} else {
366 			SIGDELSET(p->p_sigignore, sig);
367 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
368 				SIGDELSET(p->p_sigcatch, sig);
369 			else
370 				SIGADDSET(p->p_sigcatch, sig);
371 		}
372 
373 		crit_exit();
374 	}
375 	lwkt_reltoken(&p->p_token);
376 	return (0);
377 }
378 
379 int
380 sys_sigaction(struct sigaction_args *uap)
381 {
382 	struct sigaction act, oact;
383 	struct sigaction *actp, *oactp;
384 	int error;
385 
386 	actp = (uap->act != NULL) ? &act : NULL;
387 	oactp = (uap->oact != NULL) ? &oact : NULL;
388 	if (actp) {
389 		error = copyin(uap->act, actp, sizeof(act));
390 		if (error)
391 			return (error);
392 	}
393 	error = kern_sigaction(uap->sig, actp, oactp);
394 	if (oactp && !error) {
395 		error = copyout(oactp, uap->oact, sizeof(oact));
396 	}
397 	return (error);
398 }
399 
400 /*
401  * Initialize signal state for process 0;
402  * set to ignore signals that are ignored by default.
403  */
404 void
405 siginit(struct proc *p)
406 {
407 	int i;
408 
409 	for (i = 1; i <= NSIG; i++)
410 		if (sigprop(i) & SA_IGNORE && i != SIGCONT)
411 			SIGADDSET(p->p_sigignore, i);
412 }
413 
414 /*
415  * Reset signals for an exec of the specified process.
416  */
417 void
418 execsigs(struct proc *p)
419 {
420 	struct sigacts *ps = p->p_sigacts;
421 	struct lwp *lp;
422 	int sig;
423 
424 	lp = ONLY_LWP_IN_PROC(p);
425 
426 	/*
427 	 * Reset caught signals.  Held signals remain held
428 	 * through p_sigmask (unless they were caught,
429 	 * and are now ignored by default).
430 	 */
431 	while (SIGNOTEMPTY(p->p_sigcatch)) {
432 		sig = sig_ffs(&p->p_sigcatch);
433 		SIGDELSET(p->p_sigcatch, sig);
434 		if (sigprop(sig) & SA_IGNORE) {
435 			if (sig != SIGCONT)
436 				SIGADDSET(p->p_sigignore, sig);
437 			SIGDELSET(p->p_siglist, sig);
438 			SIGDELSET(lp->lwp_siglist, sig);
439 		}
440 		ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
441 	}
442 
443 	/*
444 	 * Reset stack state to the user stack.
445 	 * Clear set of signals caught on the signal stack.
446 	 */
447 	lp->lwp_sigstk.ss_flags = SS_DISABLE;
448 	lp->lwp_sigstk.ss_size = 0;
449 	lp->lwp_sigstk.ss_sp = 0;
450 	lp->lwp_flag &= ~LWP_ALTSTACK;
451 	/*
452 	 * Reset no zombies if child dies flag as Solaris does.
453 	 */
454 	p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
455 }
456 
457 /*
458  * kern_sigprocmask() - MP SAFE ONLY IF p == curproc
459  *
460  *	Manipulate signal mask.  This routine is MP SAFE *ONLY* if
461  *	p == curproc.
462  */
463 int
464 kern_sigprocmask(int how, sigset_t *set, sigset_t *oset)
465 {
466 	struct thread *td = curthread;
467 	struct lwp *lp = td->td_lwp;
468 	struct proc *p = td->td_proc;
469 	int error;
470 
471 	lwkt_gettoken(&p->p_token);
472 
473 	if (oset != NULL)
474 		*oset = lp->lwp_sigmask;
475 
476 	error = 0;
477 	if (set != NULL) {
478 		switch (how) {
479 		case SIG_BLOCK:
480 			SIG_CANTMASK(*set);
481 			SIGSETOR(lp->lwp_sigmask, *set);
482 			break;
483 		case SIG_UNBLOCK:
484 			SIGSETNAND(lp->lwp_sigmask, *set);
485 			break;
486 		case SIG_SETMASK:
487 			SIG_CANTMASK(*set);
488 			lp->lwp_sigmask = *set;
489 			break;
490 		default:
491 			error = EINVAL;
492 			break;
493 		}
494 	}
495 
496 	lwkt_reltoken(&p->p_token);
497 
498 	return (error);
499 }
500 
501 /*
502  * sigprocmask()
503  *
504  * MPSAFE
505  */
506 int
507 sys_sigprocmask(struct sigprocmask_args *uap)
508 {
509 	sigset_t set, oset;
510 	sigset_t *setp, *osetp;
511 	int error;
512 
513 	setp = (uap->set != NULL) ? &set : NULL;
514 	osetp = (uap->oset != NULL) ? &oset : NULL;
515 	if (setp) {
516 		error = copyin(uap->set, setp, sizeof(set));
517 		if (error)
518 			return (error);
519 	}
520 	error = kern_sigprocmask(uap->how, setp, osetp);
521 	if (osetp && !error) {
522 		error = copyout(osetp, uap->oset, sizeof(oset));
523 	}
524 	return (error);
525 }
526 
527 /*
528  * MPSAFE
529  */
530 int
531 kern_sigpending(struct __sigset *set)
532 {
533 	struct lwp *lp = curthread->td_lwp;
534 
535 	*set = lwp_sigpend(lp);
536 
537 	return (0);
538 }
539 
540 /*
541  * MPSAFE
542  */
543 int
544 sys_sigpending(struct sigpending_args *uap)
545 {
546 	sigset_t set;
547 	int error;
548 
549 	error = kern_sigpending(&set);
550 
551 	if (error == 0)
552 		error = copyout(&set, uap->set, sizeof(set));
553 	return (error);
554 }
555 
556 /*
557  * Suspend process until signal, providing mask to be set
558  * in the meantime.
559  *
560  * MPSAFE
561  */
562 int
563 kern_sigsuspend(struct __sigset *set)
564 {
565 	struct thread *td = curthread;
566 	struct lwp *lp = td->td_lwp;
567 	struct proc *p = td->td_proc;
568 	struct sigacts *ps = p->p_sigacts;
569 
570 	/*
571 	 * When returning from sigsuspend, we want
572 	 * the old mask to be restored after the
573 	 * signal handler has finished.  Thus, we
574 	 * save it here and mark the sigacts structure
575 	 * to indicate this.
576 	 */
577 	lp->lwp_oldsigmask = lp->lwp_sigmask;
578 	lp->lwp_flag |= LWP_OLDMASK;
579 
580 	SIG_CANTMASK(*set);
581 	lp->lwp_sigmask = *set;
582 	while (tsleep(ps, PCATCH, "pause", 0) == 0)
583 		/* void */;
584 	/* always return EINTR rather than ERESTART... */
585 	return (EINTR);
586 }
587 
588 /*
589  * Note nonstandard calling convention: libc stub passes mask, not
590  * pointer, to save a copyin.
591  *
592  * MPSAFE
593  */
594 int
595 sys_sigsuspend(struct sigsuspend_args *uap)
596 {
597 	sigset_t mask;
598 	int error;
599 
600 	error = copyin(uap->sigmask, &mask, sizeof(mask));
601 	if (error)
602 		return (error);
603 
604 	error = kern_sigsuspend(&mask);
605 
606 	return (error);
607 }
608 
609 /*
610  * MPSAFE
611  */
612 int
613 kern_sigaltstack(struct sigaltstack *ss, struct sigaltstack *oss)
614 {
615 	struct thread *td = curthread;
616 	struct lwp *lp = td->td_lwp;
617 	struct proc *p = td->td_proc;
618 
619 	if ((lp->lwp_flag & LWP_ALTSTACK) == 0)
620 		lp->lwp_sigstk.ss_flags |= SS_DISABLE;
621 
622 	if (oss)
623 		*oss = lp->lwp_sigstk;
624 
625 	if (ss) {
626 		if (ss->ss_flags & SS_DISABLE) {
627 			if (lp->lwp_sigstk.ss_flags & SS_ONSTACK)
628 				return (EINVAL);
629 			lp->lwp_flag &= ~LWP_ALTSTACK;
630 			lp->lwp_sigstk.ss_flags = ss->ss_flags;
631 		} else {
632 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
633 				return (ENOMEM);
634 			lp->lwp_flag |= LWP_ALTSTACK;
635 			lp->lwp_sigstk = *ss;
636 		}
637 	}
638 
639 	return (0);
640 }
641 
642 /*
643  * MPSAFE
644  */
645 int
646 sys_sigaltstack(struct sigaltstack_args *uap)
647 {
648 	stack_t ss, oss;
649 	int error;
650 
651 	if (uap->ss) {
652 		error = copyin(uap->ss, &ss, sizeof(ss));
653 		if (error)
654 			return (error);
655 	}
656 
657 	error = kern_sigaltstack(uap->ss ? &ss : NULL,
658 	    uap->oss ? &oss : NULL);
659 
660 	if (error == 0 && uap->oss)
661 		error = copyout(&oss, uap->oss, sizeof(*uap->oss));
662 	return (error);
663 }
664 
665 /*
666  * Common code for kill process group/broadcast kill.
667  * cp is calling process.
668  */
669 struct killpg_info {
670 	int nfound;
671 	int sig;
672 };
673 
674 static int killpg_all_callback(struct proc *p, void *data);
675 
676 static int
677 dokillpg(int sig, int pgid, int all)
678 {
679 	struct killpg_info info;
680 	struct proc *cp = curproc;
681 	struct proc *p;
682 	struct pgrp *pgrp;
683 
684 	info.nfound = 0;
685 	info.sig = sig;
686 
687 	if (all) {
688 		/*
689 		 * broadcast
690 		 */
691 		allproc_scan(killpg_all_callback, &info);
692 	} else {
693 		if (pgid == 0) {
694 			/*
695 			 * zero pgid means send to my process group.
696 			 */
697 			pgrp = cp->p_pgrp;
698 			pgref(pgrp);
699 		} else {
700 			pgrp = pgfind(pgid);
701 			if (pgrp == NULL)
702 				return (ESRCH);
703 		}
704 
705 		/*
706 		 * Must interlock all signals against fork
707 		 */
708 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
709 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
710 			if (p->p_pid <= 1 ||
711 			    p->p_stat == SZOMB ||
712 			    (p->p_flag & P_SYSTEM) ||
713 			    !CANSIGNAL(p, sig)) {
714 				continue;
715 			}
716 			++info.nfound;
717 			if (sig)
718 				ksignal(p, sig);
719 		}
720 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
721 		pgrel(pgrp);
722 	}
723 	return (info.nfound ? 0 : ESRCH);
724 }
725 
726 static int
727 killpg_all_callback(struct proc *p, void *data)
728 {
729 	struct killpg_info *info = data;
730 
731 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) ||
732 	    p == curproc || !CANSIGNAL(p, info->sig)) {
733 		return (0);
734 	}
735 	++info->nfound;
736 	if (info->sig)
737 		ksignal(p, info->sig);
738 	return(0);
739 }
740 
741 /*
742  * Send a general signal to a process or LWPs within that process.  Note
743  * that new signals cannot be sent if a process is exiting.
744  *
745  * No requirements.
746  */
747 int
748 kern_kill(int sig, pid_t pid, lwpid_t tid)
749 {
750 	int t;
751 
752 	if ((u_int)sig > _SIG_MAXSIG)
753 		return (EINVAL);
754 
755 	lwkt_gettoken(&proc_token);
756 
757 	if (pid > 0) {
758 		struct proc *p;
759 		struct lwp *lp = NULL;
760 
761 		/* kill single process */
762 		if ((p = pfind(pid)) == NULL) {
763 			lwkt_reltoken(&proc_token);
764 			return (ESRCH);
765 		}
766 		lwkt_gettoken(&p->p_token);
767 		if (!CANSIGNAL(p, sig)) {
768 			lwkt_reltoken(&p->p_token);
769 			PRELE(p);
770 			lwkt_reltoken(&proc_token);
771 			return (EPERM);
772 		}
773 
774 		/*
775 		 * NOP if the process is exiting.  Note that lwpsignal() is
776 		 * called directly with P_WEXIT set to kill individual LWPs
777 		 * during exit, which is allowed.
778 		 */
779 		if (p->p_flag & P_WEXIT) {
780 			lwkt_reltoken(&p->p_token);
781 			PRELE(p);
782 			lwkt_reltoken(&proc_token);
783 			return (0);
784 		}
785 		if (tid != -1) {
786 			lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, tid);
787 			if (lp == NULL) {
788 				lwkt_reltoken(&p->p_token);
789 				PRELE(p);
790 				lwkt_reltoken(&proc_token);
791 				return (ESRCH);
792 			}
793 		}
794 		if (sig)
795 			lwpsignal(p, lp, sig);
796 		lwkt_reltoken(&p->p_token);
797 		PRELE(p);
798 		lwkt_reltoken(&proc_token);
799 		return (0);
800 	}
801 
802 	/*
803 	 * If we come here, pid is a special broadcast pid.
804 	 * This doesn't mix with a tid.
805 	 */
806 	if (tid != -1) {
807 		lwkt_reltoken(&proc_token);
808 		return (EINVAL);
809 	}
810 	switch (pid) {
811 	case -1:		/* broadcast signal */
812 		t = (dokillpg(sig, 0, 1));
813 		break;
814 	case 0:			/* signal own process group */
815 		t = (dokillpg(sig, 0, 0));
816 		break;
817 	default:		/* negative explicit process group */
818 		t = (dokillpg(sig, -pid, 0));
819 		break;
820 	}
821 	lwkt_reltoken(&proc_token);
822 	return t;
823 }
824 
825 int
826 sys_kill(struct kill_args *uap)
827 {
828 	int error;
829 
830 	error = kern_kill(uap->signum, uap->pid, -1);
831 	return (error);
832 }
833 
834 int
835 sys_lwp_kill(struct lwp_kill_args *uap)
836 {
837 	int error;
838 	pid_t pid = uap->pid;
839 
840 	/*
841 	 * A tid is mandatory for lwp_kill(), otherwise
842 	 * you could simply use kill().
843 	 */
844 	if (uap->tid == -1)
845 		return (EINVAL);
846 
847 	/*
848 	 * To save on a getpid() function call for intra-process
849 	 * signals, pid == -1 means current process.
850 	 */
851 	if (pid == -1)
852 		pid = curproc->p_pid;
853 
854 	error = kern_kill(uap->signum, pid, uap->tid);
855 	return (error);
856 }
857 
858 /*
859  * Send a signal to a process group.
860  */
861 void
862 gsignal(int pgid, int sig)
863 {
864 	struct pgrp *pgrp;
865 
866 	if (pgid && (pgrp = pgfind(pgid)))
867 		pgsignal(pgrp, sig, 0);
868 }
869 
870 /*
871  * Send a signal to a process group.  If checktty is 1,
872  * limit to members which have a controlling terminal.
873  *
874  * pg_lock interlocks against a fork that might be in progress, to
875  * ensure that the new child process picks up the signal.
876  */
877 void
878 pgsignal(struct pgrp *pgrp, int sig, int checkctty)
879 {
880 	struct proc *p;
881 
882 	/*
883 	 * Must interlock all signals against fork
884 	 */
885 	if (pgrp) {
886 		pgref(pgrp);
887 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
888 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
889 			if (checkctty == 0 || p->p_flag & P_CONTROLT)
890 				ksignal(p, sig);
891 		}
892 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
893 		pgrel(pgrp);
894 	}
895 }
896 
897 /*
898  * Send a signal caused by a trap to the current lwp.  If it will be caught
899  * immediately, deliver it with correct code.  Otherwise, post it normally.
900  *
901  * These signals may ONLY be delivered to the specified lwp and may never
902  * be delivered to the process generically.
903  */
904 void
905 trapsignal(struct lwp *lp, int sig, u_long code)
906 {
907 	struct proc *p = lp->lwp_proc;
908 	struct sigacts *ps = p->p_sigacts;
909 
910 	/*
911 	 * If we are a virtual kernel running an emulated user process
912 	 * context, switch back to the virtual kernel context before
913 	 * trying to post the signal.
914 	 */
915 	if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
916 		struct trapframe *tf = lp->lwp_md.md_regs;
917 		tf->tf_trapno = 0;
918 		vkernel_trap(lp, tf);
919 	}
920 
921 
922 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(p->p_sigcatch, sig) &&
923 	    !SIGISMEMBER(lp->lwp_sigmask, sig)) {
924 		lp->lwp_ru.ru_nsignals++;
925 #ifdef KTRACE
926 		if (KTRPOINT(lp->lwp_thread, KTR_PSIG))
927 			ktrpsig(lp, sig, ps->ps_sigact[_SIG_IDX(sig)],
928 				&lp->lwp_sigmask, code);
929 #endif
930 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)], sig,
931 						&lp->lwp_sigmask, code);
932 		SIGSETOR(lp->lwp_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
933 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
934 			SIGADDSET(lp->lwp_sigmask, sig);
935 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
936 			/*
937 			 * See kern_sigaction() for origin of this code.
938 			 */
939 			SIGDELSET(p->p_sigcatch, sig);
940 			if (sig != SIGCONT &&
941 			    sigprop(sig) & SA_IGNORE)
942 				SIGADDSET(p->p_sigignore, sig);
943 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
944 		}
945 	} else {
946 		lp->lwp_code = code;	/* XXX for core dump/debugger */
947 		lp->lwp_sig = sig;	/* XXX to verify code */
948 		lwpsignal(p, lp, sig);
949 	}
950 }
951 
952 /*
953  * Find a suitable lwp to deliver the signal to.  Returns NULL if all
954  * lwps hold the signal blocked.
955  *
956  * Caller must hold p->p_token.
957  *
958  * Returns a lp or NULL.  If non-NULL the lp is held and its token is
959  * acquired.
960  */
961 static struct lwp *
962 find_lwp_for_signal(struct proc *p, int sig)
963 {
964 	struct lwp *lp;
965 	struct lwp *run, *sleep, *stop;
966 
967 	/*
968 	 * If the running/preempted thread belongs to the proc to which
969 	 * the signal is being delivered and this thread does not block
970 	 * the signal, then we can avoid a context switch by delivering
971 	 * the signal to this thread, because it will return to userland
972 	 * soon anyways.
973 	 */
974 	lp = lwkt_preempted_proc();
975 	if (lp != NULL && lp->lwp_proc == p) {
976 		LWPHOLD(lp);
977 		lwkt_gettoken(&lp->lwp_token);
978 		if (!SIGISMEMBER(lp->lwp_sigmask, sig)) {
979 			/* return w/ token held */
980 			return (lp);
981 		}
982 		lwkt_reltoken(&lp->lwp_token);
983 		LWPRELE(lp);
984 	}
985 
986 	run = sleep = stop = NULL;
987 	FOREACH_LWP_IN_PROC(lp, p) {
988 		/*
989 		 * If the signal is being blocked by the lwp, then this
990 		 * lwp is not eligible for receiving the signal.
991 		 */
992 		LWPHOLD(lp);
993 		lwkt_gettoken(&lp->lwp_token);
994 
995 		if (SIGISMEMBER(lp->lwp_sigmask, sig)) {
996 			lwkt_reltoken(&lp->lwp_token);
997 			LWPRELE(lp);
998 			continue;
999 		}
1000 
1001 		switch (lp->lwp_stat) {
1002 		case LSRUN:
1003 			if (sleep) {
1004 				lwkt_token_swap();
1005 				lwkt_reltoken(&sleep->lwp_token);
1006 				LWPRELE(sleep);
1007 				sleep = NULL;
1008 				run = lp;
1009 			} else if (stop) {
1010 				lwkt_token_swap();
1011 				lwkt_reltoken(&stop->lwp_token);
1012 				LWPRELE(stop);
1013 				stop = NULL;
1014 				run = lp;
1015 			} else {
1016 				run = lp;
1017 			}
1018 			break;
1019 		case LSSLEEP:
1020 			if (lp->lwp_flag & LWP_SINTR) {
1021 				if (sleep) {
1022 					lwkt_reltoken(&lp->lwp_token);
1023 					LWPRELE(lp);
1024 				} else if (stop) {
1025 					lwkt_token_swap();
1026 					lwkt_reltoken(&stop->lwp_token);
1027 					LWPRELE(stop);
1028 					stop = NULL;
1029 					sleep = lp;
1030 				} else {
1031 					sleep = lp;
1032 				}
1033 			} else {
1034 				lwkt_reltoken(&lp->lwp_token);
1035 				LWPRELE(lp);
1036 			}
1037 			break;
1038 		case LSSTOP:
1039 			if (sleep) {
1040 				lwkt_reltoken(&lp->lwp_token);
1041 				LWPRELE(lp);
1042 			} else if (stop) {
1043 				lwkt_reltoken(&lp->lwp_token);
1044 				LWPRELE(lp);
1045 			} else {
1046 				stop = lp;
1047 			}
1048 			break;
1049 		}
1050 		if (run)
1051 			break;
1052 	}
1053 
1054 	if (run != NULL)
1055 		return (run);
1056 	else if (sleep != NULL)
1057 		return (sleep);
1058 	else
1059 		return (stop);
1060 }
1061 
1062 /*
1063  * Send the signal to the process.  If the signal has an action, the action
1064  * is usually performed by the target process rather than the caller; we add
1065  * the signal to the set of pending signals for the process.
1066  *
1067  * Exceptions:
1068  *   o When a stop signal is sent to a sleeping process that takes the
1069  *     default action, the process is stopped without awakening it.
1070  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
1071  *     regardless of the signal action (eg, blocked or ignored).
1072  *
1073  * Other ignored signals are discarded immediately.
1074  *
1075  * If the caller wishes to call this function from a hard code section the
1076  * caller must already hold p->p_token (see kern_clock.c).
1077  *
1078  * No requirements.
1079  */
1080 void
1081 ksignal(struct proc *p, int sig)
1082 {
1083 	lwpsignal(p, NULL, sig);
1084 }
1085 
1086 /*
1087  * The core for ksignal.  lp may be NULL, then a suitable thread
1088  * will be chosen.  If not, lp MUST be a member of p.
1089  *
1090  * If the caller wishes to call this function from a hard code section the
1091  * caller must already hold p->p_token.
1092  *
1093  * No requirements.
1094  */
1095 void
1096 lwpsignal(struct proc *p, struct lwp *lp, int sig)
1097 {
1098 	struct proc *q;
1099 	sig_t action;
1100 	int prop;
1101 
1102 	if (sig > _SIG_MAXSIG || sig <= 0) {
1103 		kprintf("lwpsignal: signal %d\n", sig);
1104 		panic("lwpsignal signal number");
1105 	}
1106 
1107 	KKASSERT(lp == NULL || lp->lwp_proc == p);
1108 
1109 	PHOLD(p);
1110 	lwkt_gettoken(&p->p_token);
1111 	if (lp) {
1112 		LWPHOLD(lp);
1113 		lwkt_gettoken(&lp->lwp_token);
1114 	}
1115 
1116 	prop = sigprop(sig);
1117 
1118 	/*
1119 	 * If proc is traced, always give parent a chance;
1120 	 * if signal event is tracked by procfs, give *that*
1121 	 * a chance, as well.
1122 	 */
1123 	if ((p->p_flag & P_TRACED) || (p->p_stops & S_SIG)) {
1124 		action = SIG_DFL;
1125 	} else {
1126 		/*
1127 		 * Do not try to deliver signals to an exiting lwp.  Note
1128 		 * that we must still deliver the signal if P_WEXIT is set
1129 		 * in the process flags.
1130 		 */
1131 		if (lp && (lp->lwp_flag & LWP_WEXIT)) {
1132 			if (lp) {
1133 				lwkt_reltoken(&lp->lwp_token);
1134 				LWPRELE(lp);
1135 			}
1136 			lwkt_reltoken(&p->p_token);
1137 			PRELE(p);
1138 			return;
1139 		}
1140 
1141 		/*
1142 		 * If the signal is being ignored, then we forget about
1143 		 * it immediately.  NOTE: We don't set SIGCONT in p_sigignore,
1144 		 * and if it is set to SIG_IGN, action will be SIG_DFL here.
1145 		 */
1146 		if (SIGISMEMBER(p->p_sigignore, sig)) {
1147 			/*
1148 			 * Even if a signal is set SIG_IGN, it may still be
1149 			 * lurking in a kqueue.
1150 			 */
1151 			KNOTE(&p->p_klist, NOTE_SIGNAL | sig);
1152 			if (lp) {
1153 				lwkt_reltoken(&lp->lwp_token);
1154 				LWPRELE(lp);
1155 			}
1156 			lwkt_reltoken(&p->p_token);
1157 			PRELE(p);
1158 			return;
1159 		}
1160 		if (SIGISMEMBER(p->p_sigcatch, sig))
1161 			action = SIG_CATCH;
1162 		else
1163 			action = SIG_DFL;
1164 	}
1165 
1166 	/*
1167 	 * If continuing, clear any pending STOP signals.
1168 	 */
1169 	if (prop & SA_CONT)
1170 		SIG_STOPSIGMASK(p->p_siglist);
1171 
1172 	if (prop & SA_STOP) {
1173 		/*
1174 		 * If sending a tty stop signal to a member of an orphaned
1175 		 * process group, discard the signal here if the action
1176 		 * is default; don't stop the process below if sleeping,
1177 		 * and don't clear any pending SIGCONT.
1178 		 */
1179 		if (prop & SA_TTYSTOP && p->p_pgrp->pg_jobc == 0 &&
1180 		    action == SIG_DFL) {
1181 			lwkt_reltoken(&p->p_token);
1182 			PRELE(p);
1183 		        return;
1184 		}
1185 		SIG_CONTSIGMASK(p->p_siglist);
1186 		p->p_flag &= ~P_CONTINUED;
1187 	}
1188 
1189 	crit_enter();
1190 
1191 	if (p->p_stat == SSTOP) {
1192 		/*
1193 		 * Nobody can handle this signal, add it to the lwp or
1194 		 * process pending list
1195 		 */
1196 		if (lp)
1197 			SIGADDSET(lp->lwp_siglist, sig);
1198 		else
1199 			SIGADDSET(p->p_siglist, sig);
1200 
1201 		/*
1202 		 * If the process is stopped and is being traced, then no
1203 		 * further action is necessary.
1204 		 */
1205 		if (p->p_flag & P_TRACED)
1206 			goto out;
1207 
1208 		/*
1209 		 * If the process is stopped and receives a KILL signal,
1210 		 * make the process runnable.
1211 		 */
1212 		if (sig == SIGKILL) {
1213 			proc_unstop(p);
1214 			goto active_process;
1215 		}
1216 
1217 		/*
1218 		 * If the process is stopped and receives a CONT signal,
1219 		 * then try to make the process runnable again.
1220 		 */
1221 		if (prop & SA_CONT) {
1222 			/*
1223 			 * If SIGCONT is default (or ignored), we continue the
1224 			 * process but don't leave the signal in p_siglist, as
1225 			 * it has no further action.  If SIGCONT is held, we
1226 			 * continue the process and leave the signal in
1227 			 * p_siglist.  If the process catches SIGCONT, let it
1228 			 * handle the signal itself.
1229 			 *
1230 			 * XXX what if the signal is being held blocked?
1231 			 *
1232 			 * Token required to interlock kern_wait().
1233 			 * Reparenting can also cause a race so we have to
1234 			 * hold (q).
1235 			 */
1236 			q = p->p_pptr;
1237 			PHOLD(q);
1238 			lwkt_gettoken(&q->p_token);
1239 			p->p_flag |= P_CONTINUED;
1240 			wakeup(q);
1241 			if (action == SIG_DFL)
1242 				SIGDELSET(p->p_siglist, sig);
1243 			proc_unstop(p);
1244 			lwkt_reltoken(&q->p_token);
1245 			PRELE(q);
1246 			if (action == SIG_CATCH)
1247 				goto active_process;
1248 			goto out;
1249 		}
1250 
1251 		/*
1252 		 * If the process is stopped and receives another STOP
1253 		 * signal, we do not need to stop it again.  If we did
1254 		 * the shell could get confused.
1255 		 *
1256 		 * However, if the current/preempted lwp is part of the
1257 		 * process receiving the signal, we need to keep it,
1258 		 * so that this lwp can stop in issignal() later, as
1259 		 * we don't want to wait until it reaches userret!
1260 		 */
1261 		if (prop & SA_STOP) {
1262 			if (lwkt_preempted_proc() == NULL ||
1263 			    lwkt_preempted_proc()->lwp_proc != p)
1264 				SIGDELSET(p->p_siglist, sig);
1265 		}
1266 
1267 		/*
1268 		 * Otherwise the process is stopped and it received some
1269 		 * signal, which does not change its stopped state.
1270 		 *
1271 		 * We have to select one thread to set LWP_BREAKTSLEEP,
1272 		 * so that the current signal will break the sleep
1273 		 * as soon as a SA_CONT signal will unstop the process.
1274 		 */
1275 		if (lp == NULL) {
1276 			/* NOTE: returns lp w/ token held */
1277 			lp = find_lwp_for_signal(p, sig);
1278 		}
1279 		if (lp != NULL &&
1280 		    (lp->lwp_stat == LSSLEEP || lp->lwp_stat == LSSTOP))
1281 			lp->lwp_flag |= LWP_BREAKTSLEEP;
1282 		goto out;
1283 
1284 		/* NOTREACHED */
1285 	}
1286 	/* else not stopped */
1287 active_process:
1288 
1289 	/*
1290 	 * Never deliver a lwp-specific signal to a random lwp.
1291 	 */
1292 	if (lp == NULL) {
1293 		/* NOTE: returns lp w/ token held */
1294 		lp = find_lwp_for_signal(p, sig);
1295 		if (lp) {
1296 			if (SIGISMEMBER(lp->lwp_sigmask, sig)) {
1297 				lwkt_reltoken(&lp->lwp_token);
1298 				LWPRELE(lp);
1299 				lp = NULL;
1300 			}
1301 		}
1302 	}
1303 
1304 	/*
1305 	 * Deliver to the process generically if (1) the signal is being
1306 	 * sent to any thread or (2) we could not find a thread to deliver
1307 	 * it to.
1308 	 */
1309 	if (lp == NULL) {
1310 		SIGADDSET(p->p_siglist, sig);
1311 		goto out;
1312 	}
1313 
1314 	/*
1315 	 * Deliver to a specific LWP whether it masks it or not.  It will
1316 	 * not be dispatched if masked but we must still deliver it.
1317 	 */
1318 	if (p->p_nice > NZERO && action == SIG_DFL && (prop & SA_KILL) &&
1319 	    (p->p_flag & P_TRACED) == 0) {
1320 		p->p_nice = NZERO;
1321 	}
1322 
1323 	/*
1324 	 * If the process receives a STOP signal which indeed needs to
1325 	 * stop the process, do so.  If the process chose to catch the
1326 	 * signal, it will be treated like any other signal.
1327 	 */
1328 	if ((prop & SA_STOP) && action == SIG_DFL) {
1329 		/*
1330 		 * If a child holding parent blocked, stopping
1331 		 * could cause deadlock.  Take no action at this
1332 		 * time.
1333 		 */
1334 		if (p->p_flag & P_PPWAIT) {
1335 			SIGADDSET(p->p_siglist, sig);
1336 			goto out;
1337 		}
1338 
1339 		/*
1340 		 * Do not actually try to manipulate the process, but simply
1341 		 * stop it.  Lwps will stop as soon as they safely can.
1342 		 */
1343 		p->p_xstat = sig;
1344 		proc_stop(p);
1345 		goto out;
1346 	}
1347 
1348 	/*
1349 	 * If it is a CONT signal with default action, just ignore it.
1350 	 */
1351 	if ((prop & SA_CONT) && action == SIG_DFL)
1352 		goto out;
1353 
1354 	/*
1355 	 * Mark signal pending at this specific thread.
1356 	 */
1357 	SIGADDSET(lp->lwp_siglist, sig);
1358 
1359 	lwp_signotify(lp);
1360 
1361 out:
1362 	if (lp) {
1363 		lwkt_reltoken(&lp->lwp_token);
1364 		LWPRELE(lp);
1365 	}
1366 	lwkt_reltoken(&p->p_token);
1367 	PRELE(p);
1368 	crit_exit();
1369 }
1370 
1371 /*
1372  * p->p_token must be held
1373  */
1374 static void
1375 lwp_signotify(struct lwp *lp)
1376 {
1377 	ASSERT_LWKT_TOKEN_HELD(&lp->lwp_proc->p_token);
1378 	crit_enter();
1379 
1380 	if (lp->lwp_stat == LSSLEEP || lp->lwp_stat == LSSTOP) {
1381 		/*
1382 		 * Thread is in tsleep.
1383 		 */
1384 
1385 		/*
1386 		 * If the thread is sleeping uninterruptibly
1387 		 * we can't interrupt the sleep... the signal will
1388 		 * be noticed when the lwp returns through
1389 		 * trap() or syscall().
1390 		 *
1391 		 * Otherwise the signal can interrupt the sleep.
1392 		 *
1393 		 * If the process is traced, the lwp will handle the
1394 		 * tracing in issignal() when it returns to userland.
1395 		 */
1396 		if (lp->lwp_flag & LWP_SINTR) {
1397 			/*
1398 			 * Make runnable and break out of any tsleep as well.
1399 			 */
1400 			lp->lwp_flag |= LWP_BREAKTSLEEP;
1401 			setrunnable(lp);
1402 		}
1403 	} else {
1404 		/*
1405 		 * Otherwise the thread is running
1406 		 *
1407 		 * LSRUN does nothing with the signal, other than kicking
1408 		 * ourselves if we are running.
1409 		 * SZOMB and SIDL mean that it will either never be noticed,
1410 		 * or noticed very soon.
1411 		 *
1412 		 * Note that lwp_thread may be NULL or may not be completely
1413 		 * initialized if the process is in the SIDL or SZOMB state.
1414 		 *
1415 		 * For SMP we may have to forward the request to another cpu.
1416 		 * YYY the MP lock prevents the target process from moving
1417 		 * to another cpu, see kern/kern_switch.c
1418 		 *
1419 		 * If the target thread is waiting on its message port,
1420 		 * wakeup the target thread so it can check (or ignore)
1421 		 * the new signal.  YYY needs cleanup.
1422 		 */
1423 		if (lp == lwkt_preempted_proc()) {
1424 			signotify();
1425 		} else if (lp->lwp_stat == LSRUN) {
1426 			struct thread *td = lp->lwp_thread;
1427 			struct proc *p __debugvar = lp->lwp_proc;
1428 
1429 			KASSERT(td != NULL,
1430 			    ("pid %d/%d NULL lwp_thread stat %d flags %08x/%08x",
1431 			    p->p_pid, lp->lwp_tid, lp->lwp_stat,
1432 			    p->p_flag, lp->lwp_flag));
1433 
1434 			/*
1435 			 * To prevent a MP race with TDF_SINTR we must
1436 			 * schedule the thread on the correct cpu.
1437 			 */
1438 #ifdef SMP
1439 			if (td->td_gd != mycpu) {
1440 				LWPHOLD(lp);
1441 				lwkt_send_ipiq(td->td_gd, signotify_remote, lp);
1442 			} else
1443 #endif
1444 			if (td->td_flags & TDF_SINTR)
1445 				lwkt_schedule(td);
1446 		}
1447 	}
1448 	crit_exit();
1449 }
1450 
1451 #ifdef SMP
1452 
1453 /*
1454  * This function is called via an IPI.  We will be in a critical section but
1455  * the MP lock will NOT be held.  The passed lp will be held.
1456  *
1457  * We must essentially repeat the code at the end of lwp_signotify(),
1458  * in particular rechecking all races.  If we are still not on the
1459  * correct cpu we leave the lwp ref intact and continue the chase.
1460  *
1461  * XXX this may still not be entirely correct, since we are checking
1462  *     lwp_stat asynchronously.
1463  */
1464 static void
1465 signotify_remote(void *arg)
1466 {
1467 	struct lwp *lp = arg;
1468 	thread_t td;
1469 
1470 	if (lp == lwkt_preempted_proc()) {
1471 		signotify();
1472 	} else if (lp->lwp_stat == LSRUN) {
1473 		/*
1474 		 * To prevent a MP race with TDF_SINTR we must
1475 		 * schedule the thread on the correct cpu.
1476 		 */
1477 		td = lp->lwp_thread;
1478 		if (td->td_gd != mycpu) {
1479 			lwkt_send_ipiq(td->td_gd, signotify_remote, lp);
1480 			return;
1481 			/* NOT REACHED */
1482 		}
1483 		if (td->td_flags & TDF_SINTR)
1484 			lwkt_schedule(td);
1485 	}
1486 	LWPRELE(lp);
1487 }
1488 
1489 #endif
1490 
1491 /*
1492  * Caller must hold p->p_token
1493  */
1494 void
1495 proc_stop(struct proc *p)
1496 {
1497 	struct proc *q;
1498 	struct lwp *lp;
1499 
1500 	ASSERT_LWKT_TOKEN_HELD(&p->p_token);
1501 	crit_enter();
1502 
1503 	/* If somebody raced us, be happy with it */
1504 	if (p->p_stat == SSTOP || p->p_stat == SZOMB) {
1505 		crit_exit();
1506 		return;
1507 	}
1508 	p->p_stat = SSTOP;
1509 
1510 	FOREACH_LWP_IN_PROC(lp, p) {
1511 		LWPHOLD(lp);
1512 		lwkt_gettoken(&lp->lwp_token);
1513 
1514 		switch (lp->lwp_stat) {
1515 		case LSSTOP:
1516 			/*
1517 			 * Do nothing, we are already counted in
1518 			 * p_nstopped.
1519 			 */
1520 			break;
1521 
1522 		case LSSLEEP:
1523 			/*
1524 			 * We're sleeping, but we will stop before
1525 			 * returning to userspace, so count us
1526 			 * as stopped as well.  We set LWP_WSTOP
1527 			 * to signal the lwp that it should not
1528 			 * increase p_nstopped when reaching tstop().
1529 			 */
1530 			if ((lp->lwp_flag & LWP_WSTOP) == 0) {
1531 				lp->lwp_flag |= LWP_WSTOP;
1532 				++p->p_nstopped;
1533 			}
1534 			break;
1535 
1536 		case LSRUN:
1537 			/*
1538 			 * We might notify ourself, but that's not
1539 			 * a problem.
1540 			 */
1541 			lwp_signotify(lp);
1542 			break;
1543 		}
1544 		lwkt_reltoken(&lp->lwp_token);
1545 		LWPRELE(lp);
1546 	}
1547 
1548 	if (p->p_nstopped == p->p_nthreads) {
1549 		/*
1550 		 * Token required to interlock kern_wait().  Reparenting can
1551 		 * also cause a race so we have to hold (q).
1552 		 */
1553 		q = p->p_pptr;
1554 		PHOLD(q);
1555 		lwkt_gettoken(&q->p_token);
1556 		p->p_flag &= ~P_WAITED;
1557 		wakeup(q);
1558 		if ((q->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1559 			ksignal(p->p_pptr, SIGCHLD);
1560 		lwkt_reltoken(&q->p_token);
1561 		PRELE(q);
1562 	}
1563 	crit_exit();
1564 }
1565 
1566 /*
1567  * Caller must hold proc_token
1568  */
1569 void
1570 proc_unstop(struct proc *p)
1571 {
1572 	struct lwp *lp;
1573 
1574 	ASSERT_LWKT_TOKEN_HELD(&p->p_token);
1575 	crit_enter();
1576 
1577 	if (p->p_stat != SSTOP) {
1578 		crit_exit();
1579 		return;
1580 	}
1581 
1582 	p->p_stat = SACTIVE;
1583 
1584 	FOREACH_LWP_IN_PROC(lp, p) {
1585 		LWPHOLD(lp);
1586 		lwkt_gettoken(&lp->lwp_token);
1587 
1588 		switch (lp->lwp_stat) {
1589 		case LSRUN:
1590 			/*
1591 			 * Uh?  Not stopped?  Well, I guess that's okay.
1592 			 */
1593 			if (bootverbose)
1594 				kprintf("proc_unstop: lwp %d/%d not sleeping\n",
1595 					p->p_pid, lp->lwp_tid);
1596 			break;
1597 
1598 		case LSSLEEP:
1599 			/*
1600 			 * Still sleeping.  Don't bother waking it up.
1601 			 * However, if this thread was counted as
1602 			 * stopped, undo this.
1603 			 *
1604 			 * Nevertheless we call setrunnable() so that it
1605 			 * will wake up in case a signal or timeout arrived
1606 			 * in the meantime.
1607 			 */
1608 			if (lp->lwp_flag & LWP_WSTOP) {
1609 				lp->lwp_flag &= ~LWP_WSTOP;
1610 				--p->p_nstopped;
1611 			} else {
1612 				if (bootverbose)
1613 					kprintf("proc_unstop: lwp %d/%d sleeping, not stopped\n",
1614 						p->p_pid, lp->lwp_tid);
1615 			}
1616 			/* FALLTHROUGH */
1617 
1618 		case LSSTOP:
1619 			setrunnable(lp);
1620 			break;
1621 
1622 		}
1623 		lwkt_reltoken(&lp->lwp_token);
1624 		LWPRELE(lp);
1625 	}
1626 	crit_exit();
1627 }
1628 
1629 /*
1630  * No requirements.
1631  */
1632 static int
1633 kern_sigtimedwait(sigset_t waitset, siginfo_t *info, struct timespec *timeout)
1634 {
1635 	sigset_t savedmask, set;
1636 	struct proc *p = curproc;
1637 	struct lwp *lp = curthread->td_lwp;
1638 	int error, sig, hz, timevalid = 0;
1639 	struct timespec rts, ets, ts;
1640 	struct timeval tv;
1641 
1642 	error = 0;
1643 	sig = 0;
1644 	ets.tv_sec = 0;		/* silence compiler warning */
1645 	ets.tv_nsec = 0;	/* silence compiler warning */
1646 	SIG_CANTMASK(waitset);
1647 	savedmask = lp->lwp_sigmask;
1648 
1649 	if (timeout) {
1650 		if (timeout->tv_sec >= 0 && timeout->tv_nsec >= 0 &&
1651 		    timeout->tv_nsec < 1000000000) {
1652 			timevalid = 1;
1653 			getnanouptime(&rts);
1654 		 	ets = rts;
1655 			timespecadd(&ets, timeout);
1656 		}
1657 	}
1658 
1659 	for (;;) {
1660 		set = lwp_sigpend(lp);
1661 		SIGSETAND(set, waitset);
1662 		if ((sig = sig_ffs(&set)) != 0) {
1663 			SIGFILLSET(lp->lwp_sigmask);
1664 			SIGDELSET(lp->lwp_sigmask, sig);
1665 			SIG_CANTMASK(lp->lwp_sigmask);
1666 			sig = issignal(lp, 1);
1667 			/*
1668 			 * It may be a STOP signal, in the case, issignal
1669 			 * returns 0, because we may stop there, and new
1670 			 * signal can come in, we should restart if we got
1671 			 * nothing.
1672 			 */
1673 			if (sig == 0)
1674 				continue;
1675 			else
1676 				break;
1677 		}
1678 
1679 		/*
1680 		 * Previous checking got nothing, and we retried but still
1681 		 * got nothing, we should return the error status.
1682 		 */
1683 		if (error)
1684 			break;
1685 
1686 		/*
1687 		 * POSIX says this must be checked after looking for pending
1688 		 * signals.
1689 		 */
1690 		if (timeout) {
1691 			if (timevalid == 0) {
1692 				error = EINVAL;
1693 				break;
1694 			}
1695 			getnanouptime(&rts);
1696 			if (timespeccmp(&rts, &ets, >=)) {
1697 				error = EAGAIN;
1698 				break;
1699 			}
1700 			ts = ets;
1701 			timespecsub(&ts, &rts);
1702 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1703 			hz = tvtohz_high(&tv);
1704 		} else {
1705 			hz = 0;
1706 		}
1707 
1708 		lp->lwp_sigmask = savedmask;
1709 		SIGSETNAND(lp->lwp_sigmask, waitset);
1710 		/*
1711 		 * We won't ever be woken up.  Instead, our sleep will
1712 		 * be broken in lwpsignal().
1713 		 */
1714 		error = tsleep(&p->p_sigacts, PCATCH, "sigwt", hz);
1715 		if (timeout) {
1716 			if (error == ERESTART) {
1717 				/* can not restart a timeout wait. */
1718 				error = EINTR;
1719 			} else if (error == EAGAIN) {
1720 				/* will calculate timeout by ourself. */
1721 				error = 0;
1722 			}
1723 		}
1724 		/* Retry ... */
1725 	}
1726 
1727 	lp->lwp_sigmask = savedmask;
1728 	if (sig) {
1729 		error = 0;
1730 		bzero(info, sizeof(*info));
1731 		info->si_signo = sig;
1732 		lwp_delsig(lp, sig);	/* take the signal! */
1733 
1734 		if (sig == SIGKILL) {
1735 			sigexit(lp, sig);
1736 			/* NOT REACHED */
1737 		}
1738 	}
1739 
1740 	return (error);
1741 }
1742 
1743 /*
1744  * MPALMOSTSAFE
1745  */
1746 int
1747 sys_sigtimedwait(struct sigtimedwait_args *uap)
1748 {
1749 	struct timespec ts;
1750 	struct timespec *timeout;
1751 	sigset_t set;
1752 	siginfo_t info;
1753 	int error;
1754 
1755 	if (uap->timeout) {
1756 		error = copyin(uap->timeout, &ts, sizeof(ts));
1757 		if (error)
1758 			return (error);
1759 		timeout = &ts;
1760 	} else {
1761 		timeout = NULL;
1762 	}
1763 	error = copyin(uap->set, &set, sizeof(set));
1764 	if (error)
1765 		return (error);
1766 	error = kern_sigtimedwait(set, &info, timeout);
1767 	if (error)
1768 		return (error);
1769  	if (uap->info)
1770 		error = copyout(&info, uap->info, sizeof(info));
1771 	/* Repost if we got an error. */
1772 	/*
1773 	 * XXX lwp
1774 	 *
1775 	 * This could transform a thread-specific signal to another
1776 	 * thread / process pending signal.
1777 	 */
1778 	if (error) {
1779 		ksignal(curproc, info.si_signo);
1780 	} else {
1781 		uap->sysmsg_result = info.si_signo;
1782 	}
1783 	return (error);
1784 }
1785 
1786 /*
1787  * MPALMOSTSAFE
1788  */
1789 int
1790 sys_sigwaitinfo(struct sigwaitinfo_args *uap)
1791 {
1792 	siginfo_t info;
1793 	sigset_t set;
1794 	int error;
1795 
1796 	error = copyin(uap->set, &set, sizeof(set));
1797 	if (error)
1798 		return (error);
1799 	error = kern_sigtimedwait(set, &info, NULL);
1800 	if (error)
1801 		return (error);
1802 	if (uap->info)
1803 		error = copyout(&info, uap->info, sizeof(info));
1804 	/* Repost if we got an error. */
1805 	/*
1806 	 * XXX lwp
1807 	 *
1808 	 * This could transform a thread-specific signal to another
1809 	 * thread / process pending signal.
1810 	 */
1811 	if (error) {
1812 		ksignal(curproc, info.si_signo);
1813 	} else {
1814 		uap->sysmsg_result = info.si_signo;
1815 	}
1816 	return (error);
1817 }
1818 
1819 /*
1820  * If the current process has received a signal that would interrupt a
1821  * system call, return EINTR or ERESTART as appropriate.
1822  */
1823 int
1824 iscaught(struct lwp *lp)
1825 {
1826 	struct proc *p = lp->lwp_proc;
1827 	int sig;
1828 
1829 	if (p) {
1830 		if ((sig = CURSIG(lp)) != 0) {
1831 			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
1832 				return (EINTR);
1833 			return (ERESTART);
1834 		}
1835 	}
1836 	return(EWOULDBLOCK);
1837 }
1838 
1839 /*
1840  * If the current process has received a signal (should be caught or cause
1841  * termination, should interrupt current syscall), return the signal number.
1842  * Stop signals with default action are processed immediately, then cleared;
1843  * they aren't returned.  This is checked after each entry to the system for
1844  * a syscall or trap (though this can usually be done without calling issignal
1845  * by checking the pending signal masks in the CURSIG macro).
1846  *
1847  * This routine is called via CURSIG/__cursig.  We will acquire and release
1848  * p->p_token but if the caller needs to interlock the test the caller must
1849  * also hold p->p_token.
1850  *
1851  *	while (sig = CURSIG(curproc))
1852  *		postsig(sig);
1853  *
1854  * MPSAFE
1855  */
1856 int
1857 issignal(struct lwp *lp, int maytrace)
1858 {
1859 	struct proc *p = lp->lwp_proc;
1860 	sigset_t mask;
1861 	int sig, prop;
1862 
1863 	lwkt_gettoken(&p->p_token);
1864 
1865 	for (;;) {
1866 		int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
1867 
1868 		/*
1869 		 * If this process is supposed to stop, stop this thread.
1870 		 */
1871 		if (p->p_stat == SSTOP)
1872 			tstop();
1873 
1874 		mask = lwp_sigpend(lp);
1875 		SIGSETNAND(mask, lp->lwp_sigmask);
1876 		if (p->p_flag & P_PPWAIT)
1877 			SIG_STOPSIGMASK(mask);
1878 		if (SIGISEMPTY(mask)) {		/* no signal to send */
1879 			lwkt_reltoken(&p->p_token);
1880 			return (0);
1881 		}
1882 		sig = sig_ffs(&mask);
1883 
1884 		STOPEVENT(p, S_SIG, sig);
1885 
1886 		/*
1887 		 * We should see pending but ignored signals
1888 		 * only if P_TRACED was on when they were posted.
1889 		 */
1890 		if (SIGISMEMBER(p->p_sigignore, sig) && (traced == 0)) {
1891 			lwp_delsig(lp, sig);
1892 			continue;
1893 		}
1894 		if (maytrace && (p->p_flag & P_TRACED) && (p->p_flag & P_PPWAIT) == 0) {
1895 			/*
1896 			 * If traced, always stop, and stay stopped until
1897 			 * released by the parent.
1898 			 *
1899 			 * NOTE: SSTOP may get cleared during the loop,
1900 			 * but we do not re-notify the parent if we have
1901 			 * to loop several times waiting for the parent
1902 			 * to let us continue.
1903 			 *
1904 			 * XXX not sure if this is still true
1905 			 */
1906 			p->p_xstat = sig;
1907 			proc_stop(p);
1908 			do {
1909 				tstop();
1910 			} while (!trace_req(p) && (p->p_flag & P_TRACED));
1911 
1912 			/*
1913 			 * If parent wants us to take the signal,
1914 			 * then it will leave it in p->p_xstat;
1915 			 * otherwise we just look for signals again.
1916 			 */
1917 			lwp_delsig(lp, sig);	/* clear old signal */
1918 			sig = p->p_xstat;
1919 			if (sig == 0)
1920 				continue;
1921 
1922 			/*
1923 			 * Put the new signal into p_siglist.  If the
1924 			 * signal is being masked, look for other signals.
1925 			 *
1926 			 * XXX lwp might need a call to ksignal()
1927 			 */
1928 			SIGADDSET(p->p_siglist, sig);
1929 			if (SIGISMEMBER(lp->lwp_sigmask, sig))
1930 				continue;
1931 
1932 			/*
1933 			 * If the traced bit got turned off, go back up
1934 			 * to the top to rescan signals.  This ensures
1935 			 * that p_sig* and ps_sigact are consistent.
1936 			 */
1937 			if ((p->p_flag & P_TRACED) == 0)
1938 				continue;
1939 		}
1940 
1941 		prop = sigprop(sig);
1942 
1943 		/*
1944 		 * Decide whether the signal should be returned.
1945 		 * Return the signal's number, or fall through
1946 		 * to clear it from the pending mask.
1947 		 */
1948 		switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
1949 		case (intptr_t)SIG_DFL:
1950 			/*
1951 			 * Don't take default actions on system processes.
1952 			 */
1953 			if (p->p_pid <= 1) {
1954 #ifdef DIAGNOSTIC
1955 				/*
1956 				 * Are you sure you want to ignore SIGSEGV
1957 				 * in init? XXX
1958 				 */
1959 				kprintf("Process (pid %lu) got signal %d\n",
1960 					(u_long)p->p_pid, sig);
1961 #endif
1962 				break;		/* == ignore */
1963 			}
1964 
1965 			/*
1966 			 * Handle the in-kernel checkpoint action
1967 			 */
1968 			if (prop & SA_CKPT) {
1969 				checkpoint_signal_handler(lp);
1970 				break;
1971 			}
1972 
1973 			/*
1974 			 * If there is a pending stop signal to process
1975 			 * with default action, stop here,
1976 			 * then clear the signal.  However,
1977 			 * if process is member of an orphaned
1978 			 * process group, ignore tty stop signals.
1979 			 */
1980 			if (prop & SA_STOP) {
1981 				if (p->p_flag & P_TRACED ||
1982 		    		    (p->p_pgrp->pg_jobc == 0 &&
1983 				    prop & SA_TTYSTOP))
1984 					break;	/* == ignore */
1985 				p->p_xstat = sig;
1986 				proc_stop(p);
1987 				tstop();
1988 				break;
1989 			} else if (prop & SA_IGNORE) {
1990 				/*
1991 				 * Except for SIGCONT, shouldn't get here.
1992 				 * Default action is to ignore; drop it.
1993 				 */
1994 				break;		/* == ignore */
1995 			} else {
1996 				lwkt_reltoken(&p->p_token);
1997 				return (sig);
1998 			}
1999 
2000 			/*NOTREACHED*/
2001 
2002 		case (intptr_t)SIG_IGN:
2003 			/*
2004 			 * Masking above should prevent us ever trying
2005 			 * to take action on an ignored signal other
2006 			 * than SIGCONT, unless process is traced.
2007 			 */
2008 			if ((prop & SA_CONT) == 0 &&
2009 			    (p->p_flag & P_TRACED) == 0)
2010 				kprintf("issignal\n");
2011 			break;		/* == ignore */
2012 
2013 		default:
2014 			/*
2015 			 * This signal has an action, let
2016 			 * postsig() process it.
2017 			 */
2018 			lwkt_reltoken(&p->p_token);
2019 			return (sig);
2020 		}
2021 		lwp_delsig(lp, sig);		/* take the signal! */
2022 	}
2023 	/* NOTREACHED */
2024 }
2025 
2026 /*
2027  * Take the action for the specified signal
2028  * from the current set of pending signals.
2029  *
2030  * Caller must hold p->p_token
2031  */
2032 void
2033 postsig(int sig)
2034 {
2035 	struct lwp *lp = curthread->td_lwp;
2036 	struct proc *p = lp->lwp_proc;
2037 	struct sigacts *ps = p->p_sigacts;
2038 	sig_t action;
2039 	sigset_t returnmask;
2040 	int code;
2041 
2042 	KASSERT(sig != 0, ("postsig"));
2043 
2044 	KNOTE(&p->p_klist, NOTE_SIGNAL | sig);
2045 
2046 	/*
2047 	 * If we are a virtual kernel running an emulated user process
2048 	 * context, switch back to the virtual kernel context before
2049 	 * trying to post the signal.
2050 	 */
2051 	if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
2052 		struct trapframe *tf = lp->lwp_md.md_regs;
2053 		tf->tf_trapno = 0;
2054 		vkernel_trap(lp, tf);
2055 	}
2056 
2057 	lwp_delsig(lp, sig);
2058 	action = ps->ps_sigact[_SIG_IDX(sig)];
2059 #ifdef KTRACE
2060 	if (KTRPOINT(lp->lwp_thread, KTR_PSIG))
2061 		ktrpsig(lp, sig, action, lp->lwp_flag & LWP_OLDMASK ?
2062 			&lp->lwp_oldsigmask : &lp->lwp_sigmask, 0);
2063 #endif
2064 	STOPEVENT(p, S_SIG, sig);
2065 
2066 	if (action == SIG_DFL) {
2067 		/*
2068 		 * Default action, where the default is to kill
2069 		 * the process.  (Other cases were ignored above.)
2070 		 */
2071 		sigexit(lp, sig);
2072 		/* NOTREACHED */
2073 	} else {
2074 		/*
2075 		 * If we get here, the signal must be caught.
2076 		 */
2077 		KASSERT(action != SIG_IGN && !SIGISMEMBER(lp->lwp_sigmask, sig),
2078 		    ("postsig action"));
2079 
2080 		crit_enter();
2081 
2082 		/*
2083 		 * Reset the signal handler if asked to
2084 		 */
2085 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
2086 			/*
2087 			 * See kern_sigaction() for origin of this code.
2088 			 */
2089 			SIGDELSET(p->p_sigcatch, sig);
2090 			if (sig != SIGCONT &&
2091 			    sigprop(sig) & SA_IGNORE)
2092 				SIGADDSET(p->p_sigignore, sig);
2093 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2094 		}
2095 
2096 		/*
2097 		 * Handle the mailbox case.  Copyout to the appropriate
2098 		 * location but do not generate a signal frame.  The system
2099 		 * call simply returns EINTR and the user is responsible for
2100 		 * polling the mailbox.
2101 		 */
2102 		if (SIGISMEMBER(ps->ps_sigmailbox, sig)) {
2103 			int sig_copy = sig;
2104 			copyout(&sig_copy, (void *)action, sizeof(int));
2105 			lwkt_gettoken(&curproc->p_token);
2106 			curproc->p_flag |= P_MAILBOX;
2107 			lwkt_reltoken(&curproc->p_token);
2108 			crit_exit();
2109 			goto done;
2110 		}
2111 
2112 		/*
2113 		 * Set the signal mask and calculate the mask to restore
2114 		 * when the signal function returns.
2115 		 *
2116 		 * Special case: user has done a sigsuspend.  Here the
2117 		 * current mask is not of interest, but rather the
2118 		 * mask from before the sigsuspend is what we want
2119 		 * restored after the signal processing is completed.
2120 		 */
2121 		if (lp->lwp_flag & LWP_OLDMASK) {
2122 			returnmask = lp->lwp_oldsigmask;
2123 			lp->lwp_flag &= ~LWP_OLDMASK;
2124 		} else {
2125 			returnmask = lp->lwp_sigmask;
2126 		}
2127 
2128 		SIGSETOR(lp->lwp_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
2129 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
2130 			SIGADDSET(lp->lwp_sigmask, sig);
2131 
2132 		crit_exit();
2133 		lp->lwp_ru.ru_nsignals++;
2134 		if (lp->lwp_sig != sig) {
2135 			code = 0;
2136 		} else {
2137 			code = lp->lwp_code;
2138 			lp->lwp_code = 0;
2139 			lp->lwp_sig = 0;
2140 		}
2141 		(*p->p_sysent->sv_sendsig)(action, sig, &returnmask, code);
2142 	}
2143 done:
2144 	;
2145 }
2146 
2147 /*
2148  * Kill the current process for stated reason.
2149  */
2150 void
2151 killproc(struct proc *p, char *why)
2152 {
2153 	log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n",
2154 		p->p_pid, p->p_comm,
2155 		p->p_ucred ? p->p_ucred->cr_uid : -1, why);
2156 	ksignal(p, SIGKILL);
2157 }
2158 
2159 /*
2160  * Force the current process to exit with the specified signal, dumping core
2161  * if appropriate.  We bypass the normal tests for masked and caught signals,
2162  * allowing unrecoverable failures to terminate the process without changing
2163  * signal state.  Mark the accounting record with the signal termination.
2164  * If dumping core, save the signal number for the debugger.  Calls exit and
2165  * does not return.
2166  *
2167  * This routine does not return.
2168  */
2169 void
2170 sigexit(struct lwp *lp, int sig)
2171 {
2172 	struct proc *p = lp->lwp_proc;
2173 
2174 	lwkt_gettoken(&p->p_token);
2175 	p->p_acflag |= AXSIG;
2176 	if (sigprop(sig) & SA_CORE) {
2177 		lp->lwp_sig = sig;
2178 		/*
2179 		 * Log signals which would cause core dumps
2180 		 * (Log as LOG_INFO to appease those who don't want
2181 		 * these messages.)
2182 		 * XXX : Todo, as well as euid, write out ruid too
2183 		 */
2184 		if (coredump(lp, sig) == 0)
2185 			sig |= WCOREFLAG;
2186 		if (kern_logsigexit)
2187 			log(LOG_INFO,
2188 			    "pid %d (%s), uid %d: exited on signal %d%s\n",
2189 			    p->p_pid, p->p_comm,
2190 			    p->p_ucred ? p->p_ucred->cr_uid : -1,
2191 			    sig &~ WCOREFLAG,
2192 			    sig & WCOREFLAG ? " (core dumped)" : "");
2193 	}
2194 	lwkt_reltoken(&p->p_token);
2195 	exit1(W_EXITCODE(0, sig));
2196 	/* NOTREACHED */
2197 }
2198 
2199 static char corefilename[MAXPATHLEN+1] = {"%N.core"};
2200 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RW, corefilename,
2201 	      sizeof(corefilename), "process corefile name format string");
2202 
2203 /*
2204  * expand_name(name, uid, pid)
2205  * Expand the name described in corefilename, using name, uid, and pid.
2206  * corefilename is a kprintf-like string, with three format specifiers:
2207  *	%N	name of process ("name")
2208  *	%P	process id (pid)
2209  *	%U	user id (uid)
2210  * For example, "%N.core" is the default; they can be disabled completely
2211  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
2212  * This is controlled by the sysctl variable kern.corefile (see above).
2213  */
2214 
2215 static char *
2216 expand_name(const char *name, uid_t uid, pid_t pid)
2217 {
2218 	char *temp;
2219 	char buf[11];		/* Buffer for pid/uid -- max 4B */
2220 	int i, n;
2221 	char *format = corefilename;
2222 	size_t namelen;
2223 
2224 	temp = kmalloc(MAXPATHLEN + 1, M_TEMP, M_NOWAIT);
2225 	if (temp == NULL)
2226 		return NULL;
2227 	namelen = strlen(name);
2228 	for (i = 0, n = 0; n < MAXPATHLEN && format[i]; i++) {
2229 		int l;
2230 		switch (format[i]) {
2231 		case '%':	/* Format character */
2232 			i++;
2233 			switch (format[i]) {
2234 			case '%':
2235 				temp[n++] = '%';
2236 				break;
2237 			case 'N':	/* process name */
2238 				if ((n + namelen) > MAXPATHLEN) {
2239 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2240 					    pid, name, uid, temp, name);
2241 					kfree(temp, M_TEMP);
2242 					return NULL;
2243 				}
2244 				memcpy(temp+n, name, namelen);
2245 				n += namelen;
2246 				break;
2247 			case 'P':	/* process id */
2248 				l = ksprintf(buf, "%u", pid);
2249 				if ((n + l) > MAXPATHLEN) {
2250 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2251 					    pid, name, uid, temp, name);
2252 					kfree(temp, M_TEMP);
2253 					return NULL;
2254 				}
2255 				memcpy(temp+n, buf, l);
2256 				n += l;
2257 				break;
2258 			case 'U':	/* user id */
2259 				l = ksprintf(buf, "%u", uid);
2260 				if ((n + l) > MAXPATHLEN) {
2261 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2262 					    pid, name, uid, temp, name);
2263 					kfree(temp, M_TEMP);
2264 					return NULL;
2265 				}
2266 				memcpy(temp+n, buf, l);
2267 				n += l;
2268 				break;
2269 			default:
2270 			  	log(LOG_ERR, "Unknown format character %c in `%s'\n", format[i], format);
2271 			}
2272 			break;
2273 		default:
2274 			temp[n++] = format[i];
2275 		}
2276 	}
2277 	temp[n] = '\0';
2278 	return temp;
2279 }
2280 
2281 /*
2282  * Dump a process' core.  The main routine does some
2283  * policy checking, and creates the name of the coredump;
2284  * then it passes on a vnode and a size limit to the process-specific
2285  * coredump routine if there is one; if there _is not_ one, it returns
2286  * ENOSYS; otherwise it returns the error from the process-specific routine.
2287  *
2288  * The parameter `lp' is the lwp which triggered the coredump.
2289  */
2290 
2291 static int
2292 coredump(struct lwp *lp, int sig)
2293 {
2294 	struct proc *p = lp->lwp_proc;
2295 	struct vnode *vp;
2296 	struct ucred *cred = p->p_ucred;
2297 	struct flock lf;
2298 	struct nlookupdata nd;
2299 	struct vattr vattr;
2300 	int error, error1;
2301 	char *name;			/* name of corefile */
2302 	off_t limit;
2303 
2304 	STOPEVENT(p, S_CORE, 0);
2305 
2306 	if (((sugid_coredump == 0) && p->p_flag & P_SUGID) || do_coredump == 0)
2307 		return (EFAULT);
2308 
2309 	/*
2310 	 * Note that the bulk of limit checking is done after
2311 	 * the corefile is created.  The exception is if the limit
2312 	 * for corefiles is 0, in which case we don't bother
2313 	 * creating the corefile at all.  This layout means that
2314 	 * a corefile is truncated instead of not being created,
2315 	 * if it is larger than the limit.
2316 	 */
2317 	limit = p->p_rlimit[RLIMIT_CORE].rlim_cur;
2318 	if (limit == 0)
2319 		return EFBIG;
2320 
2321 	name = expand_name(p->p_comm, p->p_ucred->cr_uid, p->p_pid);
2322 	if (name == NULL)
2323 		return (EINVAL);
2324 	error = nlookup_init(&nd, name, UIO_SYSSPACE, NLC_LOCKVP);
2325 	if (error == 0)
2326 		error = vn_open(&nd, NULL, O_CREAT | FWRITE | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2327 	kfree(name, M_TEMP);
2328 	if (error) {
2329 		nlookup_done(&nd);
2330 		return (error);
2331 	}
2332 	vp = nd.nl_open_vp;
2333 	nd.nl_open_vp = NULL;
2334 	nlookup_done(&nd);
2335 
2336 	vn_unlock(vp);
2337 	lf.l_whence = SEEK_SET;
2338 	lf.l_start = 0;
2339 	lf.l_len = 0;
2340 	lf.l_type = F_WRLCK;
2341 	error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, 0);
2342 	if (error)
2343 		goto out2;
2344 
2345 	/* Don't dump to non-regular files or files with links. */
2346 	if (vp->v_type != VREG ||
2347 	    VOP_GETATTR(vp, &vattr) || vattr.va_nlink != 1) {
2348 		error = EFAULT;
2349 		goto out1;
2350 	}
2351 
2352 	/* Don't dump to files current user does not own */
2353 	if (vattr.va_uid != p->p_ucred->cr_uid) {
2354 		error = EFAULT;
2355 		goto out1;
2356 	}
2357 
2358 	VATTR_NULL(&vattr);
2359 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2360 	vattr.va_size = 0;
2361 	VOP_SETATTR(vp, &vattr, cred);
2362 	p->p_acflag |= ACORE;
2363 	vn_unlock(vp);
2364 
2365 	error = p->p_sysent->sv_coredump ?
2366 		  p->p_sysent->sv_coredump(lp, sig, vp, limit) : ENOSYS;
2367 
2368 out1:
2369 	lf.l_type = F_UNLCK;
2370 	VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, 0);
2371 out2:
2372 	error1 = vn_close(vp, FWRITE);
2373 	if (error == 0)
2374 		error = error1;
2375 	return (error);
2376 }
2377 
2378 /*
2379  * Nonexistent system call-- signal process (may want to handle it).
2380  * Flag error in case process won't see signal immediately (blocked or ignored).
2381  *
2382  * MPALMOSTSAFE
2383  */
2384 /* ARGSUSED */
2385 int
2386 sys_nosys(struct nosys_args *args)
2387 {
2388 	lwpsignal(curproc, curthread->td_lwp, SIGSYS);
2389 	return (EINVAL);
2390 }
2391 
2392 /*
2393  * Send a SIGIO or SIGURG signal to a process or process group using
2394  * stored credentials rather than those of the current process.
2395  */
2396 void
2397 pgsigio(struct sigio *sigio, int sig, int checkctty)
2398 {
2399 	if (sigio == NULL)
2400 		return;
2401 
2402 	if (sigio->sio_pgid > 0) {
2403 		if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred,
2404 		             sigio->sio_proc))
2405 			ksignal(sigio->sio_proc, sig);
2406 	} else if (sigio->sio_pgid < 0) {
2407 		struct proc *p;
2408 		struct pgrp *pg = sigio->sio_pgrp;
2409 
2410 		/*
2411 		 * Must interlock all signals against fork
2412 		 */
2413 		pgref(pg);
2414 		lockmgr(&pg->pg_lock, LK_EXCLUSIVE);
2415 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
2416 			if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred, p) &&
2417 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
2418 				ksignal(p, sig);
2419 		}
2420 		lockmgr(&pg->pg_lock, LK_RELEASE);
2421 		pgrel(pg);
2422 	}
2423 }
2424 
2425 static int
2426 filt_sigattach(struct knote *kn)
2427 {
2428 	struct proc *p = curproc;
2429 
2430 	kn->kn_ptr.p_proc = p;
2431 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
2432 
2433 	/* XXX lock the proc here while adding to the list? */
2434 	knote_insert(&p->p_klist, kn);
2435 
2436 	return (0);
2437 }
2438 
2439 static void
2440 filt_sigdetach(struct knote *kn)
2441 {
2442 	struct proc *p = kn->kn_ptr.p_proc;
2443 
2444 	knote_remove(&p->p_klist, kn);
2445 }
2446 
2447 /*
2448  * signal knotes are shared with proc knotes, so we apply a mask to
2449  * the hint in order to differentiate them from process hints.  This
2450  * could be avoided by using a signal-specific knote list, but probably
2451  * isn't worth the trouble.
2452  */
2453 static int
2454 filt_signal(struct knote *kn, long hint)
2455 {
2456 	if (hint & NOTE_SIGNAL) {
2457 		hint &= ~NOTE_SIGNAL;
2458 
2459 		if (kn->kn_id == hint)
2460 			kn->kn_data++;
2461 	}
2462 	return (kn->kn_data != 0);
2463 }
2464