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