]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/kern/kern_sig.c
MFC: r227309 (partial)
[FreeBSD/stable/9.git] / sys / kern / kern_sig.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_sig.c  8.7 (Berkeley) 4/18/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_compat.h"
41 #include "opt_kdtrace.h"
42 #include "opt_ktrace.h"
43 #include "opt_core.h"
44 #include "opt_procdesc.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/signalvar.h>
49 #include <sys/vnode.h>
50 #include <sys/acct.h>
51 #include <sys/capability.h>
52 #include <sys/condvar.h>
53 #include <sys/event.h>
54 #include <sys/fcntl.h>
55 #include <sys/imgact.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/ktrace.h>
59 #include <sys/lock.h>
60 #include <sys/malloc.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/proc.h>
64 #include <sys/procdesc.h>
65 #include <sys/posix4.h>
66 #include <sys/pioctl.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
69 #include <sys/sdt.h>
70 #include <sys/sbuf.h>
71 #include <sys/sleepqueue.h>
72 #include <sys/smp.h>
73 #include <sys/stat.h>
74 #include <sys/sx.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysent.h>
78 #include <sys/syslog.h>
79 #include <sys/sysproto.h>
80 #include <sys/timers.h>
81 #include <sys/unistd.h>
82 #include <sys/wait.h>
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/uma.h>
86
87 #include <sys/jail.h>
88
89 #include <machine/cpu.h>
90
91 #include <security/audit/audit.h>
92
93 #define ONSIG   32              /* NSIG for osig* syscalls.  XXX. */
94
95 SDT_PROVIDER_DECLARE(proc);
96 SDT_PROBE_DEFINE(proc, kernel, , signal_send, signal-send);
97 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 0, "struct thread *");
98 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 1, "struct proc *");
99 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 2, "int");
100 SDT_PROBE_DEFINE(proc, kernel, , signal_clear, signal-clear);
101 SDT_PROBE_ARGTYPE(proc, kernel, , signal_clear, 0, "int");
102 SDT_PROBE_ARGTYPE(proc, kernel, , signal_clear, 1, "ksiginfo_t *");
103 SDT_PROBE_DEFINE(proc, kernel, , signal_discard, signal-discard);
104 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 0, "struct thread *");
105 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 1, "struct proc *");
106 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 2, "int");
107
108 static int      coredump(struct thread *);
109 static char     *expand_name(const char *, uid_t, pid_t, struct thread *, int);
110 static int      killpg1(struct thread *td, int sig, int pgid, int all,
111                     ksiginfo_t *ksi);
112 static int      issignal(struct thread *td, int stop_allowed);
113 static int      sigprop(int sig);
114 static void     tdsigwakeup(struct thread *, int, sig_t, int);
115 static void     sig_suspend_threads(struct thread *, struct proc *, int);
116 static int      filt_sigattach(struct knote *kn);
117 static void     filt_sigdetach(struct knote *kn);
118 static int      filt_signal(struct knote *kn, long hint);
119 static struct thread *sigtd(struct proc *p, int sig, int prop);
120 static void     sigqueue_start(void);
121
122 static uma_zone_t       ksiginfo_zone = NULL;
123 struct filterops sig_filtops = {
124         .f_isfd = 0,
125         .f_attach = filt_sigattach,
126         .f_detach = filt_sigdetach,
127         .f_event = filt_signal,
128 };
129
130 static int      kern_logsigexit = 1;
131 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW, 
132     &kern_logsigexit, 0, 
133     "Log processes quitting on abnormal signals to syslog(3)");
134
135 static int      kern_forcesigexit = 1;
136 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
137     &kern_forcesigexit, 0, "Force trap signal to be handled");
138
139 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         td->td_errno = EINTR;
1470         td->td_pflags |= TDP_NERRNO;
1471         return (EJUSTRETURN);
1472 }
1473
1474 #ifdef COMPAT_43        /* XXX - COMPAT_FBSD3 */
1475 /*
1476  * Compatibility sigsuspend call for old binaries.  Note nonstandard calling
1477  * convention: libc stub passes mask, not pointer, to save a copyin.
1478  */
1479 #ifndef _SYS_SYSPROTO_H_
1480 struct osigsuspend_args {
1481         osigset_t mask;
1482 };
1483 #endif
1484 /* ARGSUSED */
1485 int
1486 osigsuspend(td, uap)
1487         struct thread *td;
1488         struct osigsuspend_args *uap;
1489 {
1490         sigset_t mask;
1491
1492         OSIG2SIG(uap->mask, mask);
1493         return (kern_sigsuspend(td, mask));
1494 }
1495 #endif /* COMPAT_43 */
1496
1497 #if defined(COMPAT_43)
1498 #ifndef _SYS_SYSPROTO_H_
1499 struct osigstack_args {
1500         struct  sigstack *nss;
1501         struct  sigstack *oss;
1502 };
1503 #endif
1504 /* ARGSUSED */
1505 int
1506 osigstack(td, uap)
1507         struct thread *td;
1508         register struct osigstack_args *uap;
1509 {
1510         struct sigstack nss, oss;
1511         int error = 0;
1512
1513         if (uap->nss != NULL) {
1514                 error = copyin(uap->nss, &nss, sizeof(nss));
1515                 if (error)
1516                         return (error);
1517         }
1518         oss.ss_sp = td->td_sigstk.ss_sp;
1519         oss.ss_onstack = sigonstack(cpu_getstack(td));
1520         if (uap->nss != NULL) {
1521                 td->td_sigstk.ss_sp = nss.ss_sp;
1522                 td->td_sigstk.ss_size = 0;
1523                 td->td_sigstk.ss_flags |= nss.ss_onstack & SS_ONSTACK;
1524                 td->td_pflags |= TDP_ALTSTACK;
1525         }
1526         if (uap->oss != NULL)
1527                 error = copyout(&oss, uap->oss, sizeof(oss));
1528
1529         return (error);
1530 }
1531 #endif /* COMPAT_43 */
1532
1533 #ifndef _SYS_SYSPROTO_H_
1534 struct sigaltstack_args {
1535         stack_t *ss;
1536         stack_t *oss;
1537 };
1538 #endif
1539 /* ARGSUSED */
1540 int
1541 sys_sigaltstack(td, uap)
1542         struct thread *td;
1543         register struct sigaltstack_args *uap;
1544 {
1545         stack_t ss, oss;
1546         int error;
1547
1548         if (uap->ss != NULL) {
1549                 error = copyin(uap->ss, &ss, sizeof(ss));
1550                 if (error)
1551                         return (error);
1552         }
1553         error = kern_sigaltstack(td, (uap->ss != NULL) ? &ss : NULL,
1554             (uap->oss != NULL) ? &oss : NULL);
1555         if (error)
1556                 return (error);
1557         if (uap->oss != NULL)
1558                 error = copyout(&oss, uap->oss, sizeof(stack_t));
1559         return (error);
1560 }
1561
1562 int
1563 kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
1564 {
1565         struct proc *p = td->td_proc;
1566         int oonstack;
1567
1568         oonstack = sigonstack(cpu_getstack(td));
1569
1570         if (oss != NULL) {
1571                 *oss = td->td_sigstk;
1572                 oss->ss_flags = (td->td_pflags & TDP_ALTSTACK)
1573                     ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1574         }
1575
1576         if (ss != NULL) {
1577                 if (oonstack)
1578                         return (EPERM);
1579                 if ((ss->ss_flags & ~SS_DISABLE) != 0)
1580                         return (EINVAL);
1581                 if (!(ss->ss_flags & SS_DISABLE)) {
1582                         if (ss->ss_size < p->p_sysent->sv_minsigstksz)
1583                                 return (ENOMEM);
1584
1585                         td->td_sigstk = *ss;
1586                         td->td_pflags |= TDP_ALTSTACK;
1587                 } else {
1588                         td->td_pflags &= ~TDP_ALTSTACK;
1589                 }
1590         }
1591         return (0);
1592 }
1593
1594 /*
1595  * Common code for kill process group/broadcast kill.
1596  * cp is calling process.
1597  */
1598 static int
1599 killpg1(struct thread *td, int sig, int pgid, int all, ksiginfo_t *ksi)
1600 {
1601         struct proc *p;
1602         struct pgrp *pgrp;
1603         int err;
1604         int ret;
1605
1606         ret = ESRCH;
1607         if (all) {
1608                 /*
1609                  * broadcast
1610                  */
1611                 sx_slock(&allproc_lock);
1612                 FOREACH_PROC_IN_SYSTEM(p) {
1613                         PROC_LOCK(p);
1614                         if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1615                             p == td->td_proc || p->p_state == PRS_NEW) {
1616                                 PROC_UNLOCK(p);
1617                                 continue;
1618                         }
1619                         err = p_cansignal(td, p, sig);
1620                         if (err == 0) {
1621                                 if (sig)
1622                                         pksignal(p, sig, ksi);
1623                                 ret = err;
1624                         }
1625                         else if (ret == ESRCH)
1626                                 ret = err;
1627                         PROC_UNLOCK(p);
1628                 }
1629                 sx_sunlock(&allproc_lock);
1630         } else {
1631                 sx_slock(&proctree_lock);
1632                 if (pgid == 0) {
1633                         /*
1634                          * zero pgid means send to my process group.
1635                          */
1636                         pgrp = td->td_proc->p_pgrp;
1637                         PGRP_LOCK(pgrp);
1638                 } else {
1639                         pgrp = pgfind(pgid);
1640                         if (pgrp == NULL) {
1641                                 sx_sunlock(&proctree_lock);
1642                                 return (ESRCH);
1643                         }
1644                 }
1645                 sx_sunlock(&proctree_lock);
1646                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1647                         PROC_LOCK(p);         
1648                         if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1649                             p->p_state == PRS_NEW) {
1650                                 PROC_UNLOCK(p);
1651                                 continue;
1652                         }
1653                         err = p_cansignal(td, p, sig);
1654                         if (err == 0) {
1655                                 if (sig)
1656                                         pksignal(p, sig, ksi);
1657                                 ret = err;
1658                         }
1659                         else if (ret == ESRCH)
1660                                 ret = err;
1661                         PROC_UNLOCK(p);
1662                 }
1663                 PGRP_UNLOCK(pgrp);
1664         }
1665         return (ret);
1666 }
1667
1668 #ifndef _SYS_SYSPROTO_H_
1669 struct kill_args {
1670         int     pid;
1671         int     signum;
1672 };
1673 #endif
1674 /* ARGSUSED */
1675 int
1676 sys_kill(struct thread *td, struct kill_args *uap)
1677 {
1678         ksiginfo_t ksi;
1679         struct proc *p;
1680         int error;
1681
1682         AUDIT_ARG_SIGNUM(uap->signum);
1683         AUDIT_ARG_PID(uap->pid);
1684         if ((u_int)uap->signum > _SIG_MAXSIG)
1685                 return (EINVAL);
1686
1687         ksiginfo_init(&ksi);
1688         ksi.ksi_signo = uap->signum;
1689         ksi.ksi_code = SI_USER;
1690         ksi.ksi_pid = td->td_proc->p_pid;
1691         ksi.ksi_uid = td->td_ucred->cr_ruid;
1692
1693         if (uap->pid > 0) {
1694                 /* kill single process */
1695                 if ((p = pfind(uap->pid)) == NULL) {
1696                         if ((p = zpfind(uap->pid)) == NULL)
1697                                 return (ESRCH);
1698                 }
1699                 AUDIT_ARG_PROCESS(p);
1700                 error = p_cansignal(td, p, uap->signum);
1701                 if (error == 0 && uap->signum)
1702                         pksignal(p, uap->signum, &ksi);
1703                 PROC_UNLOCK(p);
1704                 return (error);
1705         }
1706         switch (uap->pid) {
1707         case -1:                /* broadcast signal */
1708                 return (killpg1(td, uap->signum, 0, 1, &ksi));
1709         case 0:                 /* signal own process group */
1710                 return (killpg1(td, uap->signum, 0, 0, &ksi));
1711         default:                /* negative explicit process group */
1712                 return (killpg1(td, uap->signum, -uap->pid, 0, &ksi));
1713         }
1714         /* NOTREACHED */
1715 }
1716
1717 int
1718 sys_pdkill(td, uap)
1719         struct thread *td;
1720         struct pdkill_args *uap;
1721 {
1722 #ifdef PROCDESC
1723         struct proc *p;
1724         int error;
1725
1726         AUDIT_ARG_SIGNUM(uap->signum);
1727         AUDIT_ARG_FD(uap->fd);
1728         if ((u_int)uap->signum > _SIG_MAXSIG)
1729                 return (EINVAL);
1730
1731         error = procdesc_find(td, uap->fd, CAP_PDKILL, &p);
1732         if (error)
1733                 return (error);
1734         AUDIT_ARG_PROCESS(p);
1735         error = p_cansignal(td, p, uap->signum);
1736         if (error == 0 && uap->signum)
1737                 kern_psignal(p, uap->signum);
1738         PROC_UNLOCK(p);
1739         return (error);
1740 #else
1741         return (ENOSYS);
1742 #endif
1743 }
1744
1745 #if defined(COMPAT_43)
1746 #ifndef _SYS_SYSPROTO_H_
1747 struct okillpg_args {
1748         int     pgid;
1749         int     signum;
1750 };
1751 #endif
1752 /* ARGSUSED */
1753 int
1754 okillpg(struct thread *td, struct okillpg_args *uap)
1755 {
1756         ksiginfo_t ksi;
1757
1758         AUDIT_ARG_SIGNUM(uap->signum);
1759         AUDIT_ARG_PID(uap->pgid);
1760         if ((u_int)uap->signum > _SIG_MAXSIG)
1761                 return (EINVAL);
1762
1763         ksiginfo_init(&ksi);
1764         ksi.ksi_signo = uap->signum;
1765         ksi.ksi_code = SI_USER;
1766         ksi.ksi_pid = td->td_proc->p_pid;
1767         ksi.ksi_uid = td->td_ucred->cr_ruid;
1768         return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1769 }
1770 #endif /* COMPAT_43 */
1771
1772 #ifndef _SYS_SYSPROTO_H_
1773 struct sigqueue_args {
1774         pid_t pid;
1775         int signum;
1776         /* union sigval */ void *value;
1777 };
1778 #endif
1779 int
1780 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
1781 {
1782         ksiginfo_t ksi;
1783         struct proc *p;
1784         int error;
1785
1786         if ((u_int)uap->signum > _SIG_MAXSIG)
1787                 return (EINVAL);
1788
1789         /*
1790          * Specification says sigqueue can only send signal to
1791          * single process.
1792          */
1793         if (uap->pid <= 0)
1794                 return (EINVAL);
1795
1796         if ((p = pfind(uap->pid)) == NULL) {
1797                 if ((p = zpfind(uap->pid)) == NULL)
1798                         return (ESRCH);
1799         }
1800         error = p_cansignal(td, p, uap->signum);
1801         if (error == 0 && uap->signum != 0) {
1802                 ksiginfo_init(&ksi);
1803                 ksi.ksi_flags = KSI_SIGQ;
1804                 ksi.ksi_signo = uap->signum;
1805                 ksi.ksi_code = SI_QUEUE;
1806                 ksi.ksi_pid = td->td_proc->p_pid;
1807                 ksi.ksi_uid = td->td_ucred->cr_ruid;
1808                 ksi.ksi_value.sival_ptr = uap->value;
1809                 error = pksignal(p, ksi.ksi_signo, &ksi);
1810         }
1811         PROC_UNLOCK(p);
1812         return (error);
1813 }
1814
1815 /*
1816  * Send a signal to a process group.
1817  */
1818 void
1819 gsignal(int pgid, int sig, ksiginfo_t *ksi)
1820 {
1821         struct pgrp *pgrp;
1822
1823         if (pgid != 0) {
1824                 sx_slock(&proctree_lock);
1825                 pgrp = pgfind(pgid);
1826                 sx_sunlock(&proctree_lock);
1827                 if (pgrp != NULL) {
1828                         pgsignal(pgrp, sig, 0, ksi);
1829                         PGRP_UNLOCK(pgrp);
1830                 }
1831         }
1832 }
1833
1834 /*
1835  * Send a signal to a process group.  If checktty is 1,
1836  * limit to members which have a controlling terminal.
1837  */
1838 void
1839 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
1840 {
1841         struct proc *p;
1842
1843         if (pgrp) {
1844                 PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
1845                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1846                         PROC_LOCK(p);
1847                         if (p->p_state == PRS_NORMAL &&
1848                             (checkctty == 0 || p->p_flag & P_CONTROLT))
1849                                 pksignal(p, sig, ksi);
1850                         PROC_UNLOCK(p);
1851                 }
1852         }
1853 }
1854
1855 /*
1856  * Send a signal caused by a trap to the current thread.  If it will be
1857  * caught immediately, deliver it with correct code.  Otherwise, post it
1858  * normally.
1859  */
1860 void
1861 trapsignal(struct thread *td, ksiginfo_t *ksi)
1862 {
1863         struct sigacts *ps;
1864         sigset_t mask;
1865         struct proc *p;
1866         int sig;
1867         int code;
1868
1869         p = td->td_proc;
1870         sig = ksi->ksi_signo;
1871         code = ksi->ksi_code;
1872         KASSERT(_SIG_VALID(sig), ("invalid signal"));
1873
1874         PROC_LOCK(p);
1875         ps = p->p_sigacts;
1876         mtx_lock(&ps->ps_mtx);
1877         if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
1878             !SIGISMEMBER(td->td_sigmask, sig)) {
1879                 td->td_ru.ru_nsignals++;
1880 #ifdef KTRACE
1881                 if (KTRPOINT(curthread, KTR_PSIG))
1882                         ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
1883                             &td->td_sigmask, code);
1884 #endif
1885                 (*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)], 
1886                                 ksi, &td->td_sigmask);
1887                 mask = ps->ps_catchmask[_SIG_IDX(sig)];
1888                 if (!SIGISMEMBER(ps->ps_signodefer, sig))
1889                         SIGADDSET(mask, sig);
1890                 kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
1891                     SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
1892                 if (SIGISMEMBER(ps->ps_sigreset, sig)) {
1893                         /*
1894                          * See kern_sigaction() for origin of this code.
1895                          */
1896                         SIGDELSET(ps->ps_sigcatch, sig);
1897                         if (sig != SIGCONT &&
1898                             sigprop(sig) & SA_IGNORE)
1899                                 SIGADDSET(ps->ps_sigignore, sig);
1900                         ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1901                 }
1902                 mtx_unlock(&ps->ps_mtx);
1903         } else {
1904                 /*
1905                  * Avoid a possible infinite loop if the thread
1906                  * masking the signal or process is ignoring the
1907                  * signal.
1908                  */
1909                 if (kern_forcesigexit &&
1910                     (SIGISMEMBER(td->td_sigmask, sig) ||
1911                      ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
1912                         SIGDELSET(td->td_sigmask, sig);
1913                         SIGDELSET(ps->ps_sigcatch, sig);
1914                         SIGDELSET(ps->ps_sigignore, sig);
1915                         ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1916                 }
1917                 mtx_unlock(&ps->ps_mtx);
1918                 p->p_code = code;       /* XXX for core dump/debugger */
1919                 p->p_sig = sig;         /* XXX to verify code */
1920                 tdsendsignal(p, td, sig, ksi);
1921         }
1922         PROC_UNLOCK(p);
1923 }
1924
1925 static struct thread *
1926 sigtd(struct proc *p, int sig, int prop)
1927 {
1928         struct thread *td, *signal_td;
1929
1930         PROC_LOCK_ASSERT(p, MA_OWNED);
1931
1932         /*
1933          * Check if current thread can handle the signal without
1934          * switching context to another thread.
1935          */
1936         if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig))
1937                 return (curthread);
1938         signal_td = NULL;
1939         FOREACH_THREAD_IN_PROC(p, td) {
1940                 if (!SIGISMEMBER(td->td_sigmask, sig)) {
1941                         signal_td = td;
1942                         break;
1943                 }
1944         }
1945         if (signal_td == NULL)
1946                 signal_td = FIRST_THREAD_IN_PROC(p);
1947         return (signal_td);
1948 }
1949
1950 /*
1951  * Send the signal to the process.  If the signal has an action, the action
1952  * is usually performed by the target process rather than the caller; we add
1953  * the signal to the set of pending signals for the process.
1954  *
1955  * Exceptions:
1956  *   o When a stop signal is sent to a sleeping process that takes the
1957  *     default action, the process is stopped without awakening it.
1958  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
1959  *     regardless of the signal action (eg, blocked or ignored).
1960  *
1961  * Other ignored signals are discarded immediately.
1962  * 
1963  * NB: This function may be entered from the debugger via the "kill" DDB
1964  * command.  There is little that can be done to mitigate the possibly messy
1965  * side effects of this unwise possibility.
1966  */
1967 void
1968 kern_psignal(struct proc *p, int sig)
1969 {
1970         ksiginfo_t ksi;
1971
1972         ksiginfo_init(&ksi);
1973         ksi.ksi_signo = sig;
1974         ksi.ksi_code = SI_KERNEL;
1975         (void) tdsendsignal(p, NULL, sig, &ksi);
1976 }
1977
1978 int
1979 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
1980 {
1981
1982         return (tdsendsignal(p, NULL, sig, ksi));
1983 }
1984
1985 /* Utility function for finding a thread to send signal event to. */
1986 int
1987 sigev_findtd(struct proc *p ,struct sigevent *sigev, struct thread **ttd)
1988 {
1989         struct thread *td;
1990
1991         if (sigev->sigev_notify == SIGEV_THREAD_ID) {
1992                 td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
1993                 if (td == NULL)
1994                         return (ESRCH);
1995                 *ttd = td;
1996         } else {
1997                 *ttd = NULL;
1998                 PROC_LOCK(p);
1999         }
2000         return (0);
2001 }
2002
2003 void
2004 tdsignal(struct thread *td, int sig)
2005 {
2006         ksiginfo_t ksi;
2007
2008         ksiginfo_init(&ksi);
2009         ksi.ksi_signo = sig;
2010         ksi.ksi_code = SI_KERNEL;
2011         (void) tdsendsignal(td->td_proc, td, sig, &ksi);
2012 }
2013
2014 void
2015 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2016 {
2017
2018         (void) tdsendsignal(td->td_proc, td, sig, ksi);
2019 }
2020
2021 int
2022 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2023 {
2024         sig_t action;
2025         sigqueue_t *sigqueue;
2026         int prop;
2027         struct sigacts *ps;
2028         int intrval;
2029         int ret = 0;
2030         int wakeup_swapper;
2031
2032         MPASS(td == NULL || p == td->td_proc);
2033         PROC_LOCK_ASSERT(p, MA_OWNED);
2034
2035         if (!_SIG_VALID(sig))
2036                 panic("%s(): invalid signal %d", __func__, sig);
2037
2038         KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2039
2040         /*
2041          * IEEE Std 1003.1-2001: return success when killing a zombie.
2042          */
2043         if (p->p_state == PRS_ZOMBIE) {
2044                 if (ksi && (ksi->ksi_flags & KSI_INS))
2045                         ksiginfo_tryfree(ksi);
2046                 return (ret);
2047         }
2048
2049         ps = p->p_sigacts;
2050         KNOTE_LOCKED(&p->p_klist, NOTE_SIGNAL | sig);
2051         prop = sigprop(sig);
2052
2053         if (td == NULL) {
2054                 td = sigtd(p, sig, prop);
2055                 sigqueue = &p->p_sigqueue;
2056         } else {
2057                 KASSERT(td->td_proc == p, ("invalid thread"));
2058                 sigqueue = &td->td_sigqueue;
2059         }
2060
2061         SDT_PROBE(proc, kernel, , signal_send, td, p, sig, 0, 0 );
2062
2063         /*
2064          * If the signal is being ignored,
2065          * then we forget about it immediately.
2066          * (Note: we don't set SIGCONT in ps_sigignore,
2067          * and if it is set to SIG_IGN,
2068          * action will be SIG_DFL here.)
2069          */
2070         mtx_lock(&ps->ps_mtx);
2071         if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2072                 SDT_PROBE(proc, kernel, , signal_discard, td, p, sig, 0, 0 );
2073
2074                 mtx_unlock(&ps->ps_mtx);
2075                 if (ksi && (ksi->ksi_flags & KSI_INS))
2076                         ksiginfo_tryfree(ksi);
2077                 return (ret);
2078         }
2079         if (SIGISMEMBER(td->td_sigmask, sig))
2080                 action = SIG_HOLD;
2081         else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2082                 action = SIG_CATCH;
2083         else
2084                 action = SIG_DFL;
2085         if (SIGISMEMBER(ps->ps_sigintr, sig))
2086                 intrval = EINTR;
2087         else
2088                 intrval = ERESTART;
2089         mtx_unlock(&ps->ps_mtx);
2090
2091         if (prop & SA_CONT)
2092                 sigqueue_delete_stopmask_proc(p);
2093         else if (prop & SA_STOP) {
2094                 /*
2095                  * If sending a tty stop signal to a member of an orphaned
2096                  * process group, discard the signal here if the action
2097                  * is default; don't stop the process below if sleeping,
2098                  * and don't clear any pending SIGCONT.
2099                  */
2100                 if ((prop & SA_TTYSTOP) &&
2101                     (p->p_pgrp->pg_jobc == 0) &&
2102                     (action == SIG_DFL)) {
2103                         if (ksi && (ksi->ksi_flags & KSI_INS))
2104                                 ksiginfo_tryfree(ksi);
2105                         return (ret);
2106                 }
2107                 sigqueue_delete_proc(p, SIGCONT);
2108                 if (p->p_flag & P_CONTINUED) {
2109                         p->p_flag &= ~P_CONTINUED;
2110                         PROC_LOCK(p->p_pptr);
2111                         sigqueue_take(p->p_ksi);
2112                         PROC_UNLOCK(p->p_pptr);
2113                 }
2114         }
2115
2116         ret = sigqueue_add(sigqueue, sig, ksi);
2117         if (ret != 0)
2118                 return (ret);
2119         signotify(td);
2120         /*
2121          * Defer further processing for signals which are held,
2122          * except that stopped processes must be continued by SIGCONT.
2123          */
2124         if (action == SIG_HOLD &&
2125             !((prop & SA_CONT) && (p->p_flag & P_STOPPED_SIG)))
2126                 return (ret);
2127         /*
2128          * SIGKILL: Remove procfs STOPEVENTs.
2129          */
2130         if (sig == SIGKILL) {
2131                 /* from procfs_ioctl.c: PIOCBIC */
2132                 p->p_stops = 0;
2133                 /* from procfs_ioctl.c: PIOCCONT */
2134                 p->p_step = 0;
2135                 wakeup(&p->p_step);
2136         }
2137         /*
2138          * Some signals have a process-wide effect and a per-thread
2139          * component.  Most processing occurs when the process next
2140          * tries to cross the user boundary, however there are some
2141          * times when processing needs to be done immediatly, such as
2142          * waking up threads so that they can cross the user boundary.
2143          * We try do the per-process part here.
2144          */
2145         if (P_SHOULDSTOP(p)) {
2146                 KASSERT(!(p->p_flag & P_WEXIT),
2147                     ("signal to stopped but exiting process"));
2148                 if (sig == SIGKILL) {
2149                         /*
2150                          * If traced process is already stopped,
2151                          * then no further action is necessary.
2152                          */
2153                         if (p->p_flag & P_TRACED)
2154                                 goto out;
2155                         /*
2156                          * SIGKILL sets process running.
2157                          * It will die elsewhere.
2158                          * All threads must be restarted.
2159                          */
2160                         p->p_flag &= ~P_STOPPED_SIG;
2161                         goto runfast;
2162                 }
2163
2164                 if (prop & SA_CONT) {
2165                         /*
2166                          * If traced process is already stopped,
2167                          * then no further action is necessary.
2168                          */
2169                         if (p->p_flag & P_TRACED)
2170                                 goto out;
2171                         /*
2172                          * If SIGCONT is default (or ignored), we continue the
2173                          * process but don't leave the signal in sigqueue as
2174                          * it has no further action.  If SIGCONT is held, we
2175                          * continue the process and leave the signal in
2176                          * sigqueue.  If the process catches SIGCONT, let it
2177                          * handle the signal itself.  If it isn't waiting on
2178                          * an event, it goes back to run state.
2179                          * Otherwise, process goes back to sleep state.
2180                          */
2181                         p->p_flag &= ~P_STOPPED_SIG;
2182                         PROC_SLOCK(p);
2183                         if (p->p_numthreads == p->p_suspcount) {
2184                                 PROC_SUNLOCK(p);
2185                                 p->p_flag |= P_CONTINUED;
2186                                 p->p_xstat = SIGCONT;
2187                                 PROC_LOCK(p->p_pptr);
2188                                 childproc_continued(p);
2189                                 PROC_UNLOCK(p->p_pptr);
2190                                 PROC_SLOCK(p);
2191                         }
2192                         if (action == SIG_DFL) {
2193                                 thread_unsuspend(p);
2194                                 PROC_SUNLOCK(p);
2195                                 sigqueue_delete(sigqueue, sig);
2196                                 goto out;
2197                         }
2198                         if (action == SIG_CATCH) {
2199                                 /*
2200                                  * The process wants to catch it so it needs
2201                                  * to run at least one thread, but which one?
2202                                  */
2203                                 PROC_SUNLOCK(p);
2204                                 goto runfast;
2205                         }
2206                         /*
2207                          * The signal is not ignored or caught.
2208                          */
2209                         thread_unsuspend(p);
2210                         PROC_SUNLOCK(p);
2211                         goto out;
2212                 }
2213
2214                 if (prop & SA_STOP) {
2215                         /*
2216                          * If traced process is already stopped,
2217                          * then no further action is necessary.
2218                          */
2219                         if (p->p_flag & P_TRACED)
2220                                 goto out;
2221                         /*
2222                          * Already stopped, don't need to stop again
2223                          * (If we did the shell could get confused).
2224                          * Just make sure the signal STOP bit set.
2225                          */
2226                         p->p_flag |= P_STOPPED_SIG;
2227                         sigqueue_delete(sigqueue, sig);
2228                         goto out;
2229                 }
2230
2231                 /*
2232                  * All other kinds of signals:
2233                  * If a thread is sleeping interruptibly, simulate a
2234                  * wakeup so that when it is continued it will be made
2235                  * runnable and can look at the signal.  However, don't make
2236                  * the PROCESS runnable, leave it stopped.
2237                  * It may run a bit until it hits a thread_suspend_check().
2238                  */
2239                 wakeup_swapper = 0;
2240                 PROC_SLOCK(p);
2241                 thread_lock(td);
2242                 if (TD_ON_SLEEPQ(td) && (td->td_flags & TDF_SINTR))
2243                         wakeup_swapper = sleepq_abort(td, intrval);
2244                 thread_unlock(td);
2245                 PROC_SUNLOCK(p);
2246                 if (wakeup_swapper)
2247                         kick_proc0();
2248                 goto out;
2249                 /*
2250                  * Mutexes are short lived. Threads waiting on them will
2251                  * hit thread_suspend_check() soon.
2252                  */
2253         } else if (p->p_state == PRS_NORMAL) {
2254                 if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2255                         tdsigwakeup(td, sig, action, intrval);
2256                         goto out;
2257                 }
2258
2259                 MPASS(action == SIG_DFL);
2260
2261                 if (prop & SA_STOP) {
2262                         if (p->p_flag & (P_PPWAIT|P_WEXIT))
2263                                 goto out;
2264                         p->p_flag |= P_STOPPED_SIG;
2265                         p->p_xstat = sig;
2266                         PROC_SLOCK(p);
2267                         sig_suspend_threads(td, p, 1);
2268                         if (p->p_numthreads == p->p_suspcount) {
2269                                 /*
2270                                  * only thread sending signal to another
2271                                  * process can reach here, if thread is sending
2272                                  * signal to its process, because thread does
2273                                  * not suspend itself here, p_numthreads
2274                                  * should never be equal to p_suspcount.
2275                                  */
2276                                 thread_stopped(p);
2277                                 PROC_SUNLOCK(p);
2278                                 sigqueue_delete_proc(p, p->p_xstat);
2279                         } else
2280                                 PROC_SUNLOCK(p);
2281                         goto out;
2282                 }
2283         } else {
2284                 /* Not in "NORMAL" state. discard the signal. */
2285                 sigqueue_delete(sigqueue, sig);
2286                 goto out;
2287         }
2288
2289         /*
2290          * The process is not stopped so we need to apply the signal to all the
2291          * running threads.
2292          */
2293 runfast:
2294         tdsigwakeup(td, sig, action, intrval);
2295         PROC_SLOCK(p);
2296         thread_unsuspend(p);
2297         PROC_SUNLOCK(p);
2298 out:
2299         /* If we jump here, proc slock should not be owned. */
2300         PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2301         return (ret);
2302 }
2303
2304 /*
2305  * The force of a signal has been directed against a single
2306  * thread.  We need to see what we can do about knocking it
2307  * out of any sleep it may be in etc.
2308  */
2309 static void
2310 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2311 {
2312         struct proc *p = td->td_proc;
2313         register int prop;
2314         int wakeup_swapper;
2315
2316         wakeup_swapper = 0;
2317         PROC_LOCK_ASSERT(p, MA_OWNED);
2318         prop = sigprop(sig);
2319
2320         PROC_SLOCK(p);
2321         thread_lock(td);
2322         /*
2323          * Bring the priority of a thread up if we want it to get
2324          * killed in this lifetime.
2325          */
2326         if (action == SIG_DFL && (prop & SA_KILL) && td->td_priority > PUSER)
2327                 sched_prio(td, PUSER);
2328         if (TD_ON_SLEEPQ(td)) {
2329                 /*
2330                  * If thread is sleeping uninterruptibly
2331                  * we can't interrupt the sleep... the signal will
2332                  * be noticed when the process returns through
2333                  * trap() or syscall().
2334                  */
2335                 if ((td->td_flags & TDF_SINTR) == 0)
2336                         goto out;
2337                 /*
2338                  * If SIGCONT is default (or ignored) and process is
2339                  * asleep, we are finished; the process should not
2340                  * be awakened.
2341                  */
2342                 if ((prop & SA_CONT) && action == SIG_DFL) {
2343                         thread_unlock(td);
2344                         PROC_SUNLOCK(p);
2345                         sigqueue_delete(&p->p_sigqueue, sig);
2346                         /*
2347                          * It may be on either list in this state.
2348                          * Remove from both for now.
2349                          */
2350                         sigqueue_delete(&td->td_sigqueue, sig);
2351                         return;
2352                 }
2353
2354                 /*
2355                  * Give low priority threads a better chance to run.
2356                  */
2357                 if (td->td_priority > PUSER)
2358                         sched_prio(td, PUSER);
2359
2360                 wakeup_swapper = sleepq_abort(td, intrval);
2361         } else {
2362                 /*
2363                  * Other states do nothing with the signal immediately,
2364                  * other than kicking ourselves if we are running.
2365                  * It will either never be noticed, or noticed very soon.
2366                  */
2367 #ifdef SMP
2368                 if (TD_IS_RUNNING(td) && td != curthread)
2369                         forward_signal(td);
2370 #endif
2371         }
2372 out:
2373         PROC_SUNLOCK(p);
2374         thread_unlock(td);
2375         if (wakeup_swapper)
2376                 kick_proc0();
2377 }
2378
2379 static void
2380 sig_suspend_threads(struct thread *td, struct proc *p, int sending)
2381 {
2382         struct thread *td2;
2383         int wakeup_swapper;
2384
2385         PROC_LOCK_ASSERT(p, MA_OWNED);
2386         PROC_SLOCK_ASSERT(p, MA_OWNED);
2387
2388         wakeup_swapper = 0;
2389         FOREACH_THREAD_IN_PROC(p, td2) {
2390                 thread_lock(td2);
2391                 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
2392                 if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2393                     (td2->td_flags & TDF_SINTR)) {
2394                         if (td2->td_flags & TDF_SBDRY) {
2395                                 if (TD_IS_SUSPENDED(td2))
2396                                         wakeup_swapper |=
2397                                             thread_unsuspend_one(td2);
2398                                 if (TD_ON_SLEEPQ(td2))
2399                                         wakeup_swapper |=
2400                                             sleepq_abort(td2, ERESTART);
2401                         } else if (!TD_IS_SUSPENDED(td2)) {
2402                                 thread_suspend_one(td2);
2403                         }
2404                 } else if (!TD_IS_SUSPENDED(td2)) {
2405                         if (sending || td != td2)
2406                                 td2->td_flags |= TDF_ASTPENDING;
2407 #ifdef SMP
2408                         if (TD_IS_RUNNING(td2) && td2 != td)
2409                                 forward_signal(td2);
2410 #endif
2411                 }
2412                 thread_unlock(td2);
2413         }
2414         if (wakeup_swapper)
2415                 kick_proc0();
2416 }
2417
2418 int
2419 ptracestop(struct thread *td, int sig)
2420 {
2421         struct proc *p = td->td_proc;
2422
2423         PROC_LOCK_ASSERT(p, MA_OWNED);
2424         KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2425         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2426             &p->p_mtx.lock_object, "Stopping for traced signal");
2427
2428         td->td_dbgflags |= TDB_XSIG;
2429         td->td_xsig = sig;
2430         PROC_SLOCK(p);
2431         while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2432                 if (p->p_flag & P_SINGLE_EXIT) {
2433                         td->td_dbgflags &= ~TDB_XSIG;
2434                         PROC_SUNLOCK(p);
2435                         return (sig);
2436                 }
2437                 /*
2438                  * Just make wait() to work, the last stopped thread
2439                  * will win.
2440                  */
2441                 p->p_xstat = sig;
2442                 p->p_xthread = td;
2443                 p->p_flag |= (P_STOPPED_SIG|P_STOPPED_TRACE);
2444                 sig_suspend_threads(td, p, 0);
2445                 if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2446                         td->td_dbgflags &= ~TDB_STOPATFORK;
2447                         cv_broadcast(&p->p_dbgwait);
2448                 }
2449 stopme:
2450                 thread_suspend_switch(td);
2451                 if (!(p->p_flag & P_TRACED)) {
2452                         break;
2453                 }
2454                 if (td->td_dbgflags & TDB_SUSPEND) {
2455                         if (p->p_flag & P_SINGLE_EXIT)
2456                                 break;
2457                         goto stopme;
2458                 }
2459         }
2460         PROC_SUNLOCK(p);
2461         return (td->td_xsig);
2462 }
2463
2464 static void
2465 reschedule_signals(struct proc *p, sigset_t block, int flags)
2466 {
2467         struct sigacts *ps;
2468         struct thread *td;
2469         int sig;
2470
2471         PROC_LOCK_ASSERT(p, MA_OWNED);
2472         if (SIGISEMPTY(p->p_siglist))
2473                 return;
2474         ps = p->p_sigacts;
2475         SIGSETAND(block, p->p_siglist);
2476         while ((sig = sig_ffs(&block)) != 0) {
2477                 SIGDELSET(block, sig);
2478                 td = sigtd(p, sig, 0);
2479                 signotify(td);
2480                 if (!(flags & SIGPROCMASK_PS_LOCKED))
2481                         mtx_lock(&ps->ps_mtx);
2482                 if (p->p_flag & P_TRACED || SIGISMEMBER(ps->ps_sigcatch, sig))
2483                         tdsigwakeup(td, sig, SIG_CATCH,
2484                             (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2485                              ERESTART));
2486                 if (!(flags & SIGPROCMASK_PS_LOCKED))
2487                         mtx_unlock(&ps->ps_mtx);
2488         }
2489 }
2490
2491 void
2492 tdsigcleanup(struct thread *td)
2493 {
2494         struct proc *p;
2495         sigset_t unblocked;
2496
2497         p = td->td_proc;
2498         PROC_LOCK_ASSERT(p, MA_OWNED);
2499
2500         sigqueue_flush(&td->td_sigqueue);
2501         if (p->p_numthreads == 1)
2502                 return;
2503
2504         /*
2505          * Since we cannot handle signals, notify signal post code
2506          * about this by filling the sigmask.
2507          *
2508          * Also, if needed, wake up thread(s) that do not block the
2509          * same signals as the exiting thread, since the thread might
2510          * have been selected for delivery and woken up.
2511          */
2512         SIGFILLSET(unblocked);
2513         SIGSETNAND(unblocked, td->td_sigmask);
2514         SIGFILLSET(td->td_sigmask);
2515         reschedule_signals(p, unblocked, 0);
2516
2517 }
2518
2519 /*
2520  * If the current process has received a signal (should be caught or cause
2521  * termination, should interrupt current syscall), return the signal number.
2522  * Stop signals with default action are processed immediately, then cleared;
2523  * they aren't returned.  This is checked after each entry to the system for
2524  * a syscall or trap (though this can usually be done without calling issignal
2525  * by checking the pending signal masks in cursig.) The normal call
2526  * sequence is
2527  *
2528  *      while (sig = cursig(curthread))
2529  *              postsig(sig);
2530  */
2531 static int
2532 issignal(struct thread *td, int stop_allowed)
2533 {
2534         struct proc *p;
2535         struct sigacts *ps;
2536         struct sigqueue *queue;
2537         sigset_t sigpending;
2538         int sig, prop, newsig;
2539
2540         p = td->td_proc;
2541         ps = p->p_sigacts;
2542         mtx_assert(&ps->ps_mtx, MA_OWNED);
2543         PROC_LOCK_ASSERT(p, MA_OWNED);
2544         for (;;) {
2545                 int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
2546
2547                 sigpending = td->td_sigqueue.sq_signals;
2548                 SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
2549                 SIGSETNAND(sigpending, td->td_sigmask);
2550
2551                 if (p->p_flag & P_PPWAIT)
2552                         SIG_STOPSIGMASK(sigpending);
2553                 if (SIGISEMPTY(sigpending))     /* no signal to send */
2554                         return (0);
2555                 sig = sig_ffs(&sigpending);
2556
2557                 if (p->p_stops & S_SIG) {
2558                         mtx_unlock(&ps->ps_mtx);
2559                         stopevent(p, S_SIG, sig);
2560                         mtx_lock(&ps->ps_mtx);
2561                 }
2562
2563                 /*
2564                  * We should see pending but ignored signals
2565                  * only if P_TRACED was on when they were posted.
2566                  */
2567                 if (SIGISMEMBER(ps->ps_sigignore, sig) && (traced == 0)) {
2568                         sigqueue_delete(&td->td_sigqueue, sig);
2569                         sigqueue_delete(&p->p_sigqueue, sig);
2570                         continue;
2571                 }
2572                 if (p->p_flag & P_TRACED && (p->p_flag & P_PPTRACE) == 0) {
2573                         /*
2574                          * If traced, always stop.
2575                          * Remove old signal from queue before the stop.
2576                          * XXX shrug off debugger, it causes siginfo to
2577                          * be thrown away.
2578                          */
2579                         queue = &td->td_sigqueue;
2580                         td->td_dbgksi.ksi_signo = 0;
2581                         if (sigqueue_get(queue, sig, &td->td_dbgksi) == 0) {
2582                                 queue = &p->p_sigqueue;
2583                                 sigqueue_get(queue, sig, &td->td_dbgksi);
2584                         }
2585
2586                         mtx_unlock(&ps->ps_mtx);
2587                         newsig = ptracestop(td, sig);
2588                         mtx_lock(&ps->ps_mtx);
2589
2590                         if (sig != newsig) {
2591
2592                                 /*
2593                                  * If parent wants us to take the signal,
2594                                  * then it will leave it in p->p_xstat;
2595                                  * otherwise we just look for signals again.
2596                                 */
2597                                 if (newsig == 0)
2598                                         continue;
2599                                 sig = newsig;
2600
2601                                 /*
2602                                  * Put the new signal into td_sigqueue. If the
2603                                  * signal is being masked, look for other signals.
2604                                  */
2605                                 sigqueue_add(queue, sig, NULL);
2606                                 if (SIGISMEMBER(td->td_sigmask, sig))
2607                                         continue;
2608                                 signotify(td);
2609                         } else {
2610                                 if (td->td_dbgksi.ksi_signo != 0) {
2611                                         td->td_dbgksi.ksi_flags |= KSI_HEAD;
2612                                         if (sigqueue_add(&td->td_sigqueue, sig,
2613                                             &td->td_dbgksi) != 0)
2614                                                 td->td_dbgksi.ksi_signo = 0;
2615                                 }
2616                                 if (td->td_dbgksi.ksi_signo == 0)
2617                                         sigqueue_add(&td->td_sigqueue, sig,
2618                                             NULL);
2619                         }
2620
2621                         /*
2622                          * If the traced bit got turned off, go back up
2623                          * to the top to rescan signals.  This ensures
2624                          * that p_sig* and p_sigact are consistent.
2625                          */
2626                         if ((p->p_flag & P_TRACED) == 0)
2627                                 continue;
2628                 }
2629
2630                 prop = sigprop(sig);
2631
2632                 /*
2633                  * Decide whether the signal should be returned.
2634                  * Return the signal's number, or fall through
2635                  * to clear it from the pending mask.
2636                  */
2637                 switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
2638
2639                 case (intptr_t)SIG_DFL:
2640                         /*
2641                          * Don't take default actions on system processes.
2642                          */
2643                         if (p->p_pid <= 1) {
2644 #ifdef DIAGNOSTIC
2645                                 /*
2646                                  * Are you sure you want to ignore SIGSEGV
2647                                  * in init? XXX
2648                                  */
2649                                 printf("Process (pid %lu) got signal %d\n",
2650                                         (u_long)p->p_pid, sig);
2651 #endif
2652                                 break;          /* == ignore */
2653                         }
2654                         /*
2655                          * If there is a pending stop signal to process
2656                          * with default action, stop here,
2657                          * then clear the signal.  However,
2658                          * if process is member of an orphaned
2659                          * process group, ignore tty stop signals.
2660                          */
2661                         if (prop & SA_STOP) {
2662                                 if (p->p_flag & (P_TRACED|P_WEXIT) ||
2663                                     (p->p_pgrp->pg_jobc == 0 &&
2664                                      prop & SA_TTYSTOP))
2665                                         break;  /* == ignore */
2666
2667                                 /* Ignore, but do not drop the stop signal. */
2668                                 if (stop_allowed != SIG_STOP_ALLOWED)
2669                                         return (sig);
2670                                 mtx_unlock(&ps->ps_mtx);
2671                                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2672                                     &p->p_mtx.lock_object, "Catching SIGSTOP");
2673                                 p->p_flag |= P_STOPPED_SIG;
2674                                 p->p_xstat = sig;
2675                                 PROC_SLOCK(p);
2676                                 sig_suspend_threads(td, p, 0);
2677                                 thread_suspend_switch(td);
2678                                 PROC_SUNLOCK(p);
2679                                 mtx_lock(&ps->ps_mtx);
2680                                 break;
2681                         } else if (prop & SA_IGNORE) {
2682                                 /*
2683                                  * Except for SIGCONT, shouldn't get here.
2684                                  * Default action is to ignore; drop it.
2685                                  */
2686                                 break;          /* == ignore */
2687                         } else
2688                                 return (sig);
2689                         /*NOTREACHED*/
2690
2691                 case (intptr_t)SIG_IGN:
2692                         /*
2693                          * Masking above should prevent us ever trying
2694                          * to take action on an ignored signal other
2695                          * than SIGCONT, unless process is traced.
2696                          */
2697                         if ((prop & SA_CONT) == 0 &&
2698                             (p->p_flag & P_TRACED) == 0)
2699                                 printf("issignal\n");
2700                         break;          /* == ignore */
2701
2702                 default:
2703                         /*
2704                          * This signal has an action, let
2705                          * postsig() process it.
2706                          */
2707                         return (sig);
2708                 }
2709                 sigqueue_delete(&td->td_sigqueue, sig);         /* take the signal! */
2710                 sigqueue_delete(&p->p_sigqueue, sig);
2711         }
2712         /* NOTREACHED */
2713 }
2714
2715 void
2716 thread_stopped(struct proc *p)
2717 {
2718         int n;
2719
2720         PROC_LOCK_ASSERT(p, MA_OWNED);
2721         PROC_SLOCK_ASSERT(p, MA_OWNED);
2722         n = p->p_suspcount;
2723         if (p == curproc)
2724                 n++;
2725         if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
2726                 PROC_SUNLOCK(p);
2727                 p->p_flag &= ~P_WAITED;
2728                 PROC_LOCK(p->p_pptr);
2729                 childproc_stopped(p, (p->p_flag & P_TRACED) ?
2730                         CLD_TRAPPED : CLD_STOPPED);
2731                 PROC_UNLOCK(p->p_pptr);
2732                 PROC_SLOCK(p);
2733         }
2734 }
2735  
2736 /*
2737  * Take the action for the specified signal
2738  * from the current set of pending signals.
2739  */
2740 int
2741 postsig(sig)
2742         register int sig;
2743 {
2744         struct thread *td = curthread;
2745         register struct proc *p = td->td_proc;
2746         struct sigacts *ps;
2747         sig_t action;
2748         ksiginfo_t ksi;
2749         sigset_t returnmask, mask;
2750
2751         KASSERT(sig != 0, ("postsig"));
2752
2753         PROC_LOCK_ASSERT(p, MA_OWNED);
2754         ps = p->p_sigacts;
2755         mtx_assert(&ps->ps_mtx, MA_OWNED);
2756         ksiginfo_init(&ksi);
2757         if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
2758             sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
2759                 return (0);
2760         ksi.ksi_signo = sig;
2761         if (ksi.ksi_code == SI_TIMER)
2762                 itimer_accept(p, ksi.ksi_timerid, &ksi);
2763         action = ps->ps_sigact[_SIG_IDX(sig)];
2764 #ifdef KTRACE
2765         if (KTRPOINT(td, KTR_PSIG))
2766                 ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
2767                     &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
2768 #endif
2769         if (p->p_stops & S_SIG) {
2770                 mtx_unlock(&ps->ps_mtx);
2771                 stopevent(p, S_SIG, sig);
2772                 mtx_lock(&ps->ps_mtx);
2773         }
2774
2775         if (action == SIG_DFL) {
2776                 /*
2777                  * Default action, where the default is to kill
2778                  * the process.  (Other cases were ignored above.)
2779                  */
2780                 mtx_unlock(&ps->ps_mtx);
2781                 sigexit(td, sig);
2782                 /* NOTREACHED */
2783         } else {
2784                 /*
2785                  * If we get here, the signal must be caught.
2786                  */
2787                 KASSERT(action != SIG_IGN && !SIGISMEMBER(td->td_sigmask, sig),
2788                     ("postsig action"));
2789                 /*
2790                  * Set the new mask value and also defer further
2791                  * occurrences of this signal.
2792                  *
2793                  * Special case: user has done a sigsuspend.  Here the
2794                  * current mask is not of interest, but rather the
2795                  * mask from before the sigsuspend is what we want
2796                  * restored after the signal processing is completed.
2797                  */
2798                 if (td->td_pflags & TDP_OLDMASK) {
2799                         returnmask = td->td_oldsigmask;
2800                         td->td_pflags &= ~TDP_OLDMASK;
2801                 } else
2802                         returnmask = td->td_sigmask;
2803
2804                 mask = ps->ps_catchmask[_SIG_IDX(sig)];
2805                 if (!SIGISMEMBER(ps->ps_signodefer, sig))
2806                         SIGADDSET(mask, sig);
2807                 kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
2808                     SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
2809
2810                 if (SIGISMEMBER(ps->ps_sigreset, sig)) {
2811                         /*
2812                          * See kern_sigaction() for origin of this code.
2813                          */
2814                         SIGDELSET(ps->ps_sigcatch, sig);
2815                         if (sig != SIGCONT &&
2816                             sigprop(sig) & SA_IGNORE)
2817                                 SIGADDSET(ps->ps_sigignore, sig);
2818                         ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2819                 }
2820                 td->td_ru.ru_nsignals++;
2821                 if (p->p_sig == sig) {
2822                         p->p_code = 0;
2823                         p->p_sig = 0;
2824                 }
2825                 (*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
2826         }
2827         return (1);
2828 }
2829
2830 /*
2831  * Kill the current process for stated reason.
2832  */
2833 void
2834 killproc(p, why)
2835         struct proc *p;
2836         char *why;
2837 {
2838
2839         PROC_LOCK_ASSERT(p, MA_OWNED);
2840         CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)",
2841                 p, p->p_pid, p->p_comm);
2842         log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n", p->p_pid, p->p_comm,
2843                 p->p_ucred ? p->p_ucred->cr_uid : -1, why);
2844         p->p_flag |= P_WKILLED;
2845         kern_psignal(p, SIGKILL);
2846 }
2847
2848 /*
2849  * Force the current process to exit with the specified signal, dumping core
2850  * if appropriate.  We bypass the normal tests for masked and caught signals,
2851  * allowing unrecoverable failures to terminate the process without changing
2852  * signal state.  Mark the accounting record with the signal termination.
2853  * If dumping core, save the signal number for the debugger.  Calls exit and
2854  * does not return.
2855  */
2856 void
2857 sigexit(td, sig)
2858         struct thread *td;
2859         int sig;
2860 {
2861         struct proc *p = td->td_proc;
2862
2863         PROC_LOCK_ASSERT(p, MA_OWNED);
2864         p->p_acflag |= AXSIG;
2865         /*
2866          * We must be single-threading to generate a core dump.  This
2867          * ensures that the registers in the core file are up-to-date.
2868          * Also, the ELF dump handler assumes that the thread list doesn't
2869          * change out from under it.
2870          *
2871          * XXX If another thread attempts to single-thread before us
2872          *     (e.g. via fork()), we won't get a dump at all.
2873          */
2874         if ((sigprop(sig) & SA_CORE) && (thread_single(SINGLE_NO_EXIT) == 0)) {
2875                 p->p_sig = sig;
2876                 /*
2877                  * Log signals which would cause core dumps
2878                  * (Log as LOG_INFO to appease those who don't want
2879                  * these messages.)
2880                  * XXX : Todo, as well as euid, write out ruid too
2881                  * Note that coredump() drops proc lock.
2882                  */
2883                 if (coredump(td) == 0)
2884                         sig |= WCOREFLAG;
2885                 if (kern_logsigexit)
2886                         log(LOG_INFO,
2887                             "pid %d (%s), uid %d: exited on signal %d%s\n",
2888                             p->p_pid, p->p_comm,
2889                             td->td_ucred ? td->td_ucred->cr_uid : -1,
2890                             sig &~ WCOREFLAG,
2891                             sig & WCOREFLAG ? " (core dumped)" : "");
2892         } else
2893                 PROC_UNLOCK(p);
2894         exit1(td, W_EXITCODE(0, sig));
2895         /* NOTREACHED */
2896 }
2897
2898 /*
2899  * Send queued SIGCHLD to parent when child process's state
2900  * is changed.
2901  */
2902 static void
2903 sigparent(struct proc *p, int reason, int status)
2904 {
2905         PROC_LOCK_ASSERT(p, MA_OWNED);
2906         PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2907
2908         if (p->p_ksi != NULL) {
2909                 p->p_ksi->ksi_signo  = SIGCHLD;
2910                 p->p_ksi->ksi_code   = reason;
2911                 p->p_ksi->ksi_status = status;
2912                 p->p_ksi->ksi_pid    = p->p_pid;
2913                 p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
2914                 if (KSI_ONQ(p->p_ksi))
2915                         return;
2916         }
2917         pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
2918 }
2919
2920 static void
2921 childproc_jobstate(struct proc *p, int reason, int status)
2922 {
2923         struct sigacts *ps;
2924
2925         PROC_LOCK_ASSERT(p, MA_OWNED);
2926         PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2927
2928         /*
2929          * Wake up parent sleeping in kern_wait(), also send
2930          * SIGCHLD to parent, but SIGCHLD does not guarantee
2931          * that parent will awake, because parent may masked
2932          * the signal.
2933          */
2934         p->p_pptr->p_flag |= P_STATCHILD;
2935         wakeup(p->p_pptr);
2936
2937         ps = p->p_pptr->p_sigacts;
2938         mtx_lock(&ps->ps_mtx);
2939         if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
2940                 mtx_unlock(&ps->ps_mtx);
2941                 sigparent(p, reason, status);
2942         } else
2943                 mtx_unlock(&ps->ps_mtx);
2944 }
2945
2946 void
2947 childproc_stopped(struct proc *p, int reason)
2948 {
2949         childproc_jobstate(p, reason, p->p_xstat);
2950 }
2951
2952 void
2953 childproc_continued(struct proc *p)
2954 {
2955         childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
2956 }
2957
2958 void
2959 childproc_exited(struct proc *p)
2960 {
2961         int reason;
2962         int status = p->p_xstat; /* convert to int */
2963
2964         reason = CLD_EXITED;
2965         if (WCOREDUMP(status))
2966                 reason = CLD_DUMPED;
2967         else if (WIFSIGNALED(status))
2968                 reason = CLD_KILLED;
2969         /*
2970          * XXX avoid calling wakeup(p->p_pptr), the work is
2971          * done in exit1().
2972          */
2973         sigparent(p, reason, status);
2974 }
2975
2976 /*
2977  * We only have 1 character for the core count in the format
2978  * string, so the range will be 0-9
2979  */
2980 #define MAX_NUM_CORES 10
2981 static int num_cores = 5;
2982
2983 static int
2984 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
2985 {
2986         int error;
2987         int new_val;
2988
2989         new_val = num_cores;
2990         error = sysctl_handle_int(oidp, &new_val, 0, req);
2991         if (error != 0 || req->newptr == NULL)
2992                 return (error);
2993         if (new_val > MAX_NUM_CORES)
2994                 new_val = MAX_NUM_CORES;
2995         if (new_val < 0)
2996                 new_val = 0;
2997         num_cores = new_val;
2998         return (0);
2999 }
3000 SYSCTL_PROC(_debug, OID_AUTO, ncores, CTLTYPE_INT|CTLFLAG_RW, 
3001             0, sizeof(int), sysctl_debug_num_cores_check, "I", "");
3002
3003 #if defined(COMPRESS_USER_CORES)
3004 int compress_user_cores = 1;
3005 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores, CTLFLAG_RW,
3006         &compress_user_cores, 0, "");
3007
3008 int compress_user_cores_gzlevel = -1; /* default level */
3009 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_gzlevel, CTLFLAG_RW,
3010     &compress_user_cores_gzlevel, -1, "user core gz compression level");
3011
3012 #define GZ_SUFFIX       ".gz"   
3013 #define GZ_SUFFIX_LEN   3       
3014 #endif
3015
3016 static char corefilename[MAXPATHLEN] = {"%N.core"};
3017 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RW, corefilename,
3018               sizeof(corefilename), "process corefile name format string");
3019
3020 /*
3021  * expand_name(name, uid, pid, td, compress)
3022  * Expand the name described in corefilename, using name, uid, and pid.
3023  * corefilename is a printf-like string, with three format specifiers:
3024  *      %N      name of process ("name")
3025  *      %P      process id (pid)
3026  *      %U      user id (uid)
3027  * For example, "%N.core" is the default; they can be disabled completely
3028  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3029  * This is controlled by the sysctl variable kern.corefile (see above).
3030  */
3031 static char *
3032 expand_name(const char *name, uid_t uid, pid_t pid, struct thread *td,
3033     int compress)
3034 {
3035         struct sbuf sb;
3036         const char *format;
3037         char *temp;
3038         size_t i;
3039         int indexpos;
3040         char *hostname;
3041         
3042         hostname = NULL;
3043         format = corefilename;
3044         temp = malloc(MAXPATHLEN, M_TEMP, M_NOWAIT | M_ZERO);
3045         if (temp == NULL)
3046                 return (NULL);
3047         indexpos = -1;
3048         (void)sbuf_new(&sb, temp, MAXPATHLEN, SBUF_FIXEDLEN);
3049         for (i = 0; format[i]; i++) {
3050                 switch (format[i]) {
3051                 case '%':       /* Format character */
3052                         i++;
3053                         switch (format[i]) {
3054                         case '%':
3055                                 sbuf_putc(&sb, '%');
3056                                 break;
3057                         case 'H':       /* hostname */
3058                                 if (hostname == NULL) {
3059                                         hostname = malloc(MAXHOSTNAMELEN,
3060                                             M_TEMP, M_NOWAIT);
3061                                         if (hostname == NULL) {
3062                                                 log(LOG_ERR,
3063                                                     "pid %ld (%s), uid (%lu): "
3064                                                     "unable to alloc memory "
3065                                                     "for corefile hostname\n",
3066                                                     (long)pid, name,
3067                                                     (u_long)uid);
3068                                                 goto nomem;
3069                                         }
3070                                 }
3071                                 getcredhostname(td->td_ucred, hostname,
3072                                     MAXHOSTNAMELEN);
3073                                 sbuf_printf(&sb, "%s", hostname);
3074                                 break;
3075                         case 'I':       /* autoincrementing index */
3076                                 sbuf_printf(&sb, "0");
3077                                 indexpos = sbuf_len(&sb) - 1;
3078                                 break;
3079                         case 'N':       /* process name */
3080                                 sbuf_printf(&sb, "%s", name);
3081                                 break;
3082                         case 'P':       /* process id */
3083                                 sbuf_printf(&sb, "%u", pid);
3084                                 break;
3085                         case 'U':       /* user id */
3086                                 sbuf_printf(&sb, "%u", uid);
3087                                 break;
3088                         default:
3089                                 log(LOG_ERR,
3090                                     "Unknown format character %c in "
3091                                     "corename `%s'\n", format[i], format);
3092                         }
3093                         break;
3094                 default:
3095                         sbuf_putc(&sb, format[i]);
3096                 }
3097         }
3098         free(hostname, M_TEMP);
3099 #ifdef COMPRESS_USER_CORES
3100         if (compress) {
3101                 sbuf_printf(&sb, GZ_SUFFIX);
3102         }
3103 #endif
3104         if (sbuf_error(&sb) != 0) {
3105                 log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
3106                     "long\n", (long)pid, name, (u_long)uid);
3107 nomem:
3108                 sbuf_delete(&sb);
3109                 free(temp, M_TEMP);
3110                 return (NULL);
3111         }
3112         sbuf_finish(&sb);
3113         sbuf_delete(&sb);
3114
3115         /*
3116          * If the core format has a %I in it, then we need to check
3117          * for existing corefiles before returning a name.
3118          * To do this we iterate over 0..num_cores to find a
3119          * non-existing core file name to use.
3120          */
3121         if (indexpos != -1) {
3122                 struct nameidata nd;
3123                 int error, n;
3124                 int flags = O_CREAT | O_EXCL | FWRITE | O_NOFOLLOW;
3125                 int cmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
3126                 int vfslocked;
3127
3128                 for (n = 0; n < num_cores; n++) {
3129                         temp[indexpos] = '0' + n;
3130                         NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE,
3131                             temp, td); 
3132                         error = vn_open(&nd, &flags, cmode, NULL);
3133                         if (error) {
3134                                 if (error == EEXIST) {
3135                                         continue;
3136                                 }
3137                                 log(LOG_ERR,
3138                                     "pid %d (%s), uid (%u):  Path `%s' failed "
3139                                     "on initial open test, error = %d\n",
3140                                     pid, name, uid, temp, error);
3141                                 free(temp, M_TEMP);
3142                                 return (NULL);
3143                         }
3144                         vfslocked = NDHASGIANT(&nd);
3145                         NDFREE(&nd, NDF_ONLY_PNBUF);
3146                         VOP_UNLOCK(nd.ni_vp, 0);
3147                         error = vn_close(nd.ni_vp, FWRITE, td->td_ucred, td);
3148                         VFS_UNLOCK_GIANT(vfslocked);
3149                         if (error) {
3150                                 log(LOG_ERR,
3151                                     "pid %d (%s), uid (%u):  Path `%s' failed "
3152                                     "on close after initial open test, "
3153                                     "error = %d\n",
3154                                     pid, name, uid, temp, error);
3155                                 free(temp, M_TEMP);
3156                                 return (NULL);
3157                         }
3158                         break;
3159                 }
3160         }
3161         return (temp);
3162 }
3163
3164 /*
3165  * Dump a process' core.  The main routine does some
3166  * policy checking, and creates the name of the coredump;
3167  * then it passes on a vnode and a size limit to the process-specific
3168  * coredump routine if there is one; if there _is not_ one, it returns
3169  * ENOSYS; otherwise it returns the error from the process-specific routine.
3170  */
3171
3172 static int
3173 coredump(struct thread *td)
3174 {
3175         struct proc *p = td->td_proc;
3176         register struct vnode *vp;
3177         register struct ucred *cred = td->td_ucred;
3178         struct flock lf;
3179         struct nameidata nd;
3180         struct vattr vattr;
3181         int error, error1, flags, locked;
3182         struct mount *mp;
3183         char *name;                     /* name of corefile */
3184         off_t limit;
3185         int vfslocked;
3186         int compress;
3187
3188 #ifdef COMPRESS_USER_CORES
3189         compress = compress_user_cores;
3190 #else
3191         compress = 0;
3192 #endif
3193         PROC_LOCK_ASSERT(p, MA_OWNED);
3194         MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
3195         _STOPEVENT(p, S_CORE, 0);
3196
3197         name = expand_name(p->p_comm, td->td_ucred->cr_uid, p->p_pid, td,
3198             compress);
3199         if (name == NULL) {
3200                 PROC_UNLOCK(p);
3201 #ifdef AUDIT
3202                 audit_proc_coredump(td, NULL, EINVAL);
3203 #endif
3204                 return (EINVAL);
3205         }
3206         if (((sugid_coredump == 0) && p->p_flag & P_SUGID) || do_coredump == 0) {
3207                 PROC_UNLOCK(p);
3208 #ifdef AUDIT
3209                 audit_proc_coredump(td, name, EFAULT);
3210 #endif
3211                 free(name, M_TEMP);
3212                 return (EFAULT);
3213         }
3214         
3215         /*
3216          * Note that the bulk of limit checking is done after
3217          * the corefile is created.  The exception is if the limit
3218          * for corefiles is 0, in which case we don't bother
3219          * creating the corefile at all.  This layout means that
3220          * a corefile is truncated instead of not being created,
3221          * if it is larger than the limit.
3222          */
3223         limit = (off_t)lim_cur(p, RLIMIT_CORE);
3224         if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
3225                 PROC_UNLOCK(p);
3226 #ifdef AUDIT
3227                 audit_proc_coredump(td, name, EFBIG);
3228 #endif
3229                 free(name, M_TEMP);
3230                 return (EFBIG);
3231         }
3232         PROC_UNLOCK(p);
3233
3234 restart:
3235         NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, name, td);
3236         flags = O_CREAT | FWRITE | O_NOFOLLOW;
3237         error = vn_open_cred(&nd, &flags, S_IRUSR | S_IWUSR, VN_OPEN_NOAUDIT,
3238             cred, NULL);
3239         if (error) {
3240 #ifdef AUDIT
3241                 audit_proc_coredump(td, name, error);
3242 #endif
3243                 free(name, M_TEMP);
3244                 return (error);
3245         }
3246         vfslocked = NDHASGIANT(&nd);
3247         NDFREE(&nd, NDF_ONLY_PNBUF);
3248         vp = nd.ni_vp;
3249
3250         /* Don't dump to non-regular files or files with links. */
3251         if (vp->v_type != VREG ||
3252             VOP_GETATTR(vp, &vattr, cred) || vattr.va_nlink != 1) {
3253                 VOP_UNLOCK(vp, 0);
3254                 error = EFAULT;
3255                 goto close;
3256         }
3257
3258         VOP_UNLOCK(vp, 0);
3259         lf.l_whence = SEEK_SET;
3260         lf.l_start = 0;
3261         lf.l_len = 0;
3262         lf.l_type = F_WRLCK;
3263         locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
3264
3265         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
3266                 lf.l_type = F_UNLCK;
3267                 if (locked)
3268                         VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3269                 if ((error = vn_close(vp, FWRITE, cred, td)) != 0)
3270                         goto out;
3271                 if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3272                         goto out;
3273                 VFS_UNLOCK_GIANT(vfslocked);
3274                 goto restart;
3275         }
3276
3277         VATTR_NULL(&vattr);
3278         vattr.va_size = 0;
3279         if (set_core_nodump_flag)
3280                 vattr.va_flags = UF_NODUMP;
3281         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3282         VOP_SETATTR(vp, &vattr, cred);
3283         VOP_UNLOCK(vp, 0);
3284         vn_finished_write(mp);
3285         PROC_LOCK(p);
3286         p->p_acflag |= ACORE;
3287         PROC_UNLOCK(p);
3288
3289         error = p->p_sysent->sv_coredump ?
3290           p->p_sysent->sv_coredump(td, vp, limit, compress ? IMGACT_CORE_COMPRESS : 0) :
3291           ENOSYS;
3292
3293         if (locked) {
3294                 lf.l_type = F_UNLCK;
3295                 VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3296         }
3297 close:
3298         error1 = vn_close(vp, FWRITE, cred, td);
3299         if (error == 0)
3300                 error = error1;
3301 out:
3302 #ifdef AUDIT
3303         audit_proc_coredump(td, name, error);
3304 #endif
3305         free(name, M_TEMP);
3306         VFS_UNLOCK_GIANT(vfslocked);
3307         return (error);
3308 }
3309
3310 /*
3311  * Nonexistent system call-- signal process (may want to handle it).  Flag
3312  * error in case process won't see signal immediately (blocked or ignored).
3313  */
3314 #ifndef _SYS_SYSPROTO_H_
3315 struct nosys_args {
3316         int     dummy;
3317 };
3318 #endif
3319 /* ARGSUSED */
3320 int
3321 nosys(td, args)
3322         struct thread *td;
3323         struct nosys_args *args;
3324 {
3325         struct proc *p = td->td_proc;
3326
3327         PROC_LOCK(p);
3328         tdsignal(td, SIGSYS);
3329         PROC_UNLOCK(p);
3330         return (ENOSYS);
3331 }
3332
3333 /*
3334  * Send a SIGIO or SIGURG signal to a process or process group using stored
3335  * credentials rather than those of the current process.
3336  */
3337 void
3338 pgsigio(sigiop, sig, checkctty)
3339         struct sigio **sigiop;
3340         int sig, checkctty;
3341 {
3342         ksiginfo_t ksi;
3343         struct sigio *sigio;
3344
3345         ksiginfo_init(&ksi);
3346         ksi.ksi_signo = sig;
3347         ksi.ksi_code = SI_KERNEL;
3348
3349         SIGIO_LOCK();
3350         sigio = *sigiop;
3351         if (sigio == NULL) {
3352                 SIGIO_UNLOCK();
3353                 return;
3354         }
3355         if (sigio->sio_pgid > 0) {
3356                 PROC_LOCK(sigio->sio_proc);
3357                 if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
3358                         kern_psignal(sigio->sio_proc, sig);
3359                 PROC_UNLOCK(sigio->sio_proc);
3360         } else if (sigio->sio_pgid < 0) {
3361                 struct proc *p;
3362
3363                 PGRP_LOCK(sigio->sio_pgrp);
3364                 LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
3365                         PROC_LOCK(p);
3366                         if (p->p_state == PRS_NORMAL &&
3367                             CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
3368                             (checkctty == 0 || (p->p_flag & P_CONTROLT)))
3369                                 kern_psignal(p, sig);
3370                         PROC_UNLOCK(p);
3371                 }
3372                 PGRP_UNLOCK(sigio->sio_pgrp);
3373         }
3374         SIGIO_UNLOCK();
3375 }
3376
3377 static int
3378 filt_sigattach(struct knote *kn)
3379 {
3380         struct proc *p = curproc;
3381
3382         kn->kn_ptr.p_proc = p;
3383         kn->kn_flags |= EV_CLEAR;               /* automatically set */
3384
3385         knlist_add(&p->p_klist, kn, 0);
3386
3387         return (0);
3388 }
3389
3390 static void
3391 filt_sigdetach(struct knote *kn)
3392 {
3393         struct proc *p = kn->kn_ptr.p_proc;
3394
3395         knlist_remove(&p->p_klist, kn, 0);
3396 }
3397
3398 /*
3399  * signal knotes are shared with proc knotes, so we apply a mask to 
3400  * the hint in order to differentiate them from process hints.  This
3401  * could be avoided by using a signal-specific knote list, but probably
3402  * isn't worth the trouble.
3403  */
3404 static int
3405 filt_signal(struct knote *kn, long hint)
3406 {
3407
3408         if (hint & NOTE_SIGNAL) {
3409                 hint &= ~NOTE_SIGNAL;
3410
3411                 if (kn->kn_id == hint)
3412                         kn->kn_data++;
3413         }
3414         return (kn->kn_data != 0);
3415 }
3416
3417 struct sigacts *
3418 sigacts_alloc(void)
3419 {
3420         struct sigacts *ps;
3421
3422         ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
3423         ps->ps_refcnt = 1;
3424         mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
3425         return (ps);
3426 }
3427
3428 void
3429 sigacts_free(struct sigacts *ps)
3430 {
3431
3432         mtx_lock(&ps->ps_mtx);
3433         ps->ps_refcnt--;
3434         if (ps->ps_refcnt == 0) {
3435                 mtx_destroy(&ps->ps_mtx);
3436                 free(ps, M_SUBPROC);
3437         } else
3438                 mtx_unlock(&ps->ps_mtx);
3439 }
3440
3441 struct sigacts *
3442 sigacts_hold(struct sigacts *ps)
3443 {
3444         mtx_lock(&ps->ps_mtx);
3445         ps->ps_refcnt++;
3446         mtx_unlock(&ps->ps_mtx);
3447         return (ps);
3448 }
3449
3450 void
3451 sigacts_copy(struct sigacts *dest, struct sigacts *src)
3452 {
3453
3454         KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
3455         mtx_lock(&src->ps_mtx);
3456         bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
3457         mtx_unlock(&src->ps_mtx);
3458 }
3459
3460 int
3461 sigacts_shared(struct sigacts *ps)
3462 {
3463         int shared;
3464
3465         mtx_lock(&ps->ps_mtx);
3466         shared = ps->ps_refcnt > 1;
3467         mtx_unlock(&ps->ps_mtx);
3468         return (shared);
3469 }