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