]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_exit.c
MFC r269656:
[FreeBSD/stable/10.git] / sys / kern / kern_exit.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_exit.c 8.7 (Berkeley) 2/12/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_procdesc.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/capability.h>
49 #include <sys/eventhandler.h>
50 #include <sys/kernel.h>
51 #include <sys/malloc.h>
52 #include <sys/lock.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/procdesc.h>
56 #include <sys/pioctl.h>
57 #include <sys/jail.h>
58 #include <sys/tty.h>
59 #include <sys/wait.h>
60 #include <sys/vmmeter.h>
61 #include <sys/vnode.h>
62 #include <sys/racct.h>
63 #include <sys/resourcevar.h>
64 #include <sys/sbuf.h>
65 #include <sys/signalvar.h>
66 #include <sys/sched.h>
67 #include <sys/sx.h>
68 #include <sys/syscallsubr.h>
69 #include <sys/syslog.h>
70 #include <sys/ptrace.h>
71 #include <sys/acct.h>           /* for acct_process() function prototype */
72 #include <sys/filedesc.h>
73 #include <sys/sdt.h>
74 #include <sys/shm.h>
75 #include <sys/sem.h>
76 #ifdef KTRACE
77 #include <sys/ktrace.h>
78 #endif
79
80 #include <security/audit/audit.h>
81 #include <security/mac/mac_framework.h>
82
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/uma.h>
90
91 #ifdef KDTRACE_HOOKS
92 #include <sys/dtrace_bsd.h>
93 dtrace_execexit_func_t  dtrace_fasttrap_exit;
94 #endif
95
96 SDT_PROVIDER_DECLARE(proc);
97 SDT_PROBE_DEFINE1(proc, kernel, , exit, "int");
98
99 /* Hook for NFS teardown procedure. */
100 void (*nlminfo_release_p)(struct proc *p);
101
102 struct proc *
103 proc_realparent(struct proc *child)
104 {
105         struct proc *p, *parent;
106
107         sx_assert(&proctree_lock, SX_LOCKED);
108         if ((child->p_treeflag & P_TREE_ORPHANED) == 0) {
109                 return (child->p_pptr->p_pid == child->p_oppid ?
110                     child->p_pptr : initproc);
111         }
112         for (p = child; (p->p_treeflag & P_TREE_FIRST_ORPHAN) == 0;) {
113                 /* Cannot use LIST_PREV(), since the list head is not known. */
114                 p = __containerof(p->p_orphan.le_prev, struct proc,
115                     p_orphan.le_next);
116                 KASSERT((p->p_treeflag & P_TREE_ORPHANED) != 0,
117                     ("missing P_ORPHAN %p", p));
118         }
119         parent = __containerof(p->p_orphan.le_prev, struct proc,
120             p_orphans.lh_first);
121         return (parent);
122 }
123
124 static void
125 clear_orphan(struct proc *p)
126 {
127         struct proc *p1;
128
129         sx_assert(&proctree_lock, SA_XLOCKED);
130         if ((p->p_treeflag & P_TREE_ORPHANED) == 0)
131                 return;
132         if ((p->p_treeflag & P_TREE_FIRST_ORPHAN) != 0) {
133                 p1 = LIST_NEXT(p, p_orphan);
134                 if (p1 != NULL)
135                         p1->p_treeflag |= P_TREE_FIRST_ORPHAN;
136                 p->p_treeflag &= ~P_TREE_FIRST_ORPHAN;
137         }
138         LIST_REMOVE(p, p_orphan);
139         p->p_treeflag &= ~P_TREE_ORPHANED;
140 }
141
142 /*
143  * exit -- death of process.
144  */
145 void
146 sys_sys_exit(struct thread *td, struct sys_exit_args *uap)
147 {
148
149         exit1(td, W_EXITCODE(uap->rval, 0));
150         /* NOTREACHED */
151 }
152
153 /*
154  * Exit: deallocate address space and other resources, change proc state to
155  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
156  * and rusage for wait().  Check for child processes and orphan them.
157  */
158 void
159 exit1(struct thread *td, int rv)
160 {
161         struct proc *p, *nq, *q;
162         struct vnode *ttyvp = NULL;
163
164         mtx_assert(&Giant, MA_NOTOWNED);
165
166         p = td->td_proc;
167         /*
168          * XXX in case we're rebooting we just let init die in order to
169          * work around an unsolved stack overflow seen very late during
170          * shutdown on sparc64 when the gmirror worker process exists.
171          */
172         if (p == initproc && rebooting == 0) {
173                 printf("init died (signal %d, exit %d)\n",
174                     WTERMSIG(rv), WEXITSTATUS(rv));
175                 panic("Going nowhere without my init!");
176         }
177
178         /*
179          * MUST abort all other threads before proceeding past here.
180          */
181         PROC_LOCK(p);
182         while (p->p_flag & P_HADTHREADS) {
183                 /*
184                  * First check if some other thread got here before us.
185                  * If so, act appropriately: exit or suspend.
186                  */
187                 thread_suspend_check(0);
188
189                 /*
190                  * Kill off the other threads. This requires
191                  * some co-operation from other parts of the kernel
192                  * so it may not be instantaneous.  With this state set
193                  * any thread entering the kernel from userspace will
194                  * thread_exit() in trap().  Any thread attempting to
195                  * sleep will return immediately with EINTR or EWOULDBLOCK
196                  * which will hopefully force them to back out to userland
197                  * freeing resources as they go.  Any thread attempting
198                  * to return to userland will thread_exit() from userret().
199                  * thread_exit() will unsuspend us when the last of the
200                  * other threads exits.
201                  * If there is already a thread singler after resumption,
202                  * calling thread_single will fail; in that case, we just
203                  * re-check all suspension request, the thread should
204                  * either be suspended there or exit.
205                  */
206                 if (!thread_single(SINGLE_EXIT))
207                         break;
208
209                 /*
210                  * All other activity in this process is now stopped.
211                  * Threading support has been turned off.
212                  */
213         }
214         KASSERT(p->p_numthreads == 1,
215             ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
216         racct_sub(p, RACCT_NTHR, 1);
217         /*
218          * Wakeup anyone in procfs' PIOCWAIT.  They should have a hold
219          * on our vmspace, so we should block below until they have
220          * released their reference to us.  Note that if they have
221          * requested S_EXIT stops we will block here until they ack
222          * via PIOCCONT.
223          */
224         _STOPEVENT(p, S_EXIT, rv);
225
226         /*
227          * Ignore any pending request to stop due to a stop signal.
228          * Once P_WEXIT is set, future requests will be ignored as
229          * well.
230          */
231         p->p_flag &= ~P_STOPPED_SIG;
232         KASSERT(!P_SHOULDSTOP(p), ("exiting process is stopped"));
233
234         /*
235          * Note that we are exiting and do another wakeup of anyone in
236          * PIOCWAIT in case they aren't listening for S_EXIT stops or
237          * decided to wait again after we told them we are exiting.
238          */
239         p->p_flag |= P_WEXIT;
240         wakeup(&p->p_stype);
241
242         /*
243          * Wait for any processes that have a hold on our vmspace to
244          * release their reference.
245          */
246         while (p->p_lock > 0)
247                 msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
248
249         p->p_xstat = rv;        /* Let event handler change exit status */
250         PROC_UNLOCK(p);
251         /* Drain the limit callout while we don't have the proc locked */
252         callout_drain(&p->p_limco);
253
254 #ifdef AUDIT
255         /*
256          * The Sun BSM exit token contains two components: an exit status as
257          * passed to exit(), and a return value to indicate what sort of exit
258          * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
259          * what the return value is.
260          */
261         AUDIT_ARG_EXIT(WEXITSTATUS(rv), 0);
262         AUDIT_SYSCALL_EXIT(0, td);
263 #endif
264
265         /* Are we a task leader? */
266         if (p == p->p_leader) {
267                 mtx_lock(&ppeers_lock);
268                 q = p->p_peers;
269                 while (q != NULL) {
270                         PROC_LOCK(q);
271                         kern_psignal(q, SIGKILL);
272                         PROC_UNLOCK(q);
273                         q = q->p_peers;
274                 }
275                 while (p->p_peers != NULL)
276                         msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
277                 mtx_unlock(&ppeers_lock);
278         }
279
280         /*
281          * Check if any loadable modules need anything done at process exit.
282          * E.g. SYSV IPC stuff
283          * XXX what if one of these generates an error?
284          */
285         EVENTHANDLER_INVOKE(process_exit, p);
286
287         /*
288          * If parent is waiting for us to exit or exec,
289          * P_PPWAIT is set; we will wakeup the parent below.
290          */
291         PROC_LOCK(p);
292         rv = p->p_xstat;        /* Event handler could change exit status */
293         stopprofclock(p);
294         p->p_flag &= ~(P_TRACED | P_PPWAIT | P_PPTRACE);
295
296         /*
297          * Stop the real interval timer.  If the handler is currently
298          * executing, prevent it from rearming itself and let it finish.
299          */
300         if (timevalisset(&p->p_realtimer.it_value) &&
301             callout_stop(&p->p_itcallout) == 0) {
302                 timevalclear(&p->p_realtimer.it_interval);
303                 msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
304                 KASSERT(!timevalisset(&p->p_realtimer.it_value),
305                     ("realtime timer is still armed"));
306         }
307         PROC_UNLOCK(p);
308
309         /*
310          * Reset any sigio structures pointing to us as a result of
311          * F_SETOWN with our pid.
312          */
313         funsetownlst(&p->p_sigiolst);
314
315         /*
316          * If this process has an nlminfo data area (for lockd), release it
317          */
318         if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
319                 (*nlminfo_release_p)(p);
320
321         /*
322          * Close open files and release open-file table.
323          * This may block!
324          */
325         fdescfree(td);
326
327         /*
328          * If this thread tickled GEOM, we need to wait for the giggling to
329          * stop before we return to userland
330          */
331         if (td->td_pflags & TDP_GEOM)
332                 g_waitidle();
333
334         /*
335          * Remove ourself from our leader's peer list and wake our leader.
336          */
337         mtx_lock(&ppeers_lock);
338         if (p->p_leader->p_peers) {
339                 q = p->p_leader;
340                 while (q->p_peers != p)
341                         q = q->p_peers;
342                 q->p_peers = p->p_peers;
343                 wakeup(p->p_leader);
344         }
345         mtx_unlock(&ppeers_lock);
346
347         vmspace_exit(td);
348
349         sx_xlock(&proctree_lock);
350         if (SESS_LEADER(p)) {
351                 struct session *sp = p->p_session;
352                 struct tty *tp;
353
354                 /*
355                  * s_ttyp is not zero'd; we use this to indicate that
356                  * the session once had a controlling terminal. (for
357                  * logging and informational purposes)
358                  */
359                 SESS_LOCK(sp);
360                 ttyvp = sp->s_ttyvp;
361                 tp = sp->s_ttyp;
362                 sp->s_ttyvp = NULL;
363                 sp->s_ttydp = NULL;
364                 sp->s_leader = NULL;
365                 SESS_UNLOCK(sp);
366
367                 /*
368                  * Signal foreground pgrp and revoke access to
369                  * controlling terminal if it has not been revoked
370                  * already.
371                  *
372                  * Because the TTY may have been revoked in the mean
373                  * time and could already have a new session associated
374                  * with it, make sure we don't send a SIGHUP to a
375                  * foreground process group that does not belong to this
376                  * session.
377                  */
378
379                 if (tp != NULL) {
380                         tty_lock(tp);
381                         if (tp->t_session == sp)
382                                 tty_signal_pgrp(tp, SIGHUP);
383                         tty_unlock(tp);
384                 }
385
386                 if (ttyvp != NULL) {
387                         sx_xunlock(&proctree_lock);
388                         if (vn_lock(ttyvp, LK_EXCLUSIVE) == 0) {
389                                 VOP_REVOKE(ttyvp, REVOKEALL);
390                                 VOP_UNLOCK(ttyvp, 0);
391                         }
392                         sx_xlock(&proctree_lock);
393                 }
394         }
395         fixjobc(p, p->p_pgrp, 0);
396         sx_xunlock(&proctree_lock);
397         (void)acct_process(td);
398
399         /* Release the TTY now we've unlocked everything. */
400         if (ttyvp != NULL)
401                 vrele(ttyvp);
402 #ifdef KTRACE
403         ktrprocexit(td);
404 #endif
405         /*
406          * Release reference to text vnode
407          */
408         if (p->p_textvp != NULL) {
409                 vrele(p->p_textvp);
410                 p->p_textvp = NULL;
411         }
412
413         /*
414          * Release our limits structure.
415          */
416         lim_free(p->p_limit);
417         p->p_limit = NULL;
418
419         tidhash_remove(td);
420
421         /*
422          * Remove proc from allproc queue and pidhash chain.
423          * Place onto zombproc.  Unlink from parent's child list.
424          */
425         sx_xlock(&allproc_lock);
426         LIST_REMOVE(p, p_list);
427         LIST_INSERT_HEAD(&zombproc, p, p_list);
428         LIST_REMOVE(p, p_hash);
429         sx_xunlock(&allproc_lock);
430
431         /*
432          * Call machine-dependent code to release any
433          * machine-dependent resources other than the address space.
434          * The address space is released by "vmspace_exitfree(p)" in
435          * vm_waitproc().
436          */
437         cpu_exit(td);
438
439         WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
440
441         /*
442          * Reparent all of our children to init.
443          */
444         sx_xlock(&proctree_lock);
445         q = LIST_FIRST(&p->p_children);
446         if (q != NULL)          /* only need this if any child is S_ZOMB */
447                 wakeup(initproc);
448         for (; q != NULL; q = nq) {
449                 nq = LIST_NEXT(q, p_sibling);
450                 PROC_LOCK(q);
451                 proc_reparent(q, initproc);
452                 q->p_sigparent = SIGCHLD;
453                 /*
454                  * Traced processes are killed
455                  * since their existence means someone is screwing up.
456                  */
457                 if (q->p_flag & P_TRACED) {
458                         struct thread *temp;
459
460                         /*
461                          * Since q was found on our children list, the
462                          * proc_reparent() call moved q to the orphan
463                          * list due to present P_TRACED flag. Clear
464                          * orphan link for q now while q is locked.
465                          */
466                         clear_orphan(q);
467                         q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
468                         FOREACH_THREAD_IN_PROC(q, temp)
469                                 temp->td_dbgflags &= ~TDB_SUSPEND;
470                         kern_psignal(q, SIGKILL);
471                 }
472                 PROC_UNLOCK(q);
473         }
474
475         /*
476          * Also get rid of our orphans.
477          */
478         while ((q = LIST_FIRST(&p->p_orphans)) != NULL) {
479                 PROC_LOCK(q);
480                 clear_orphan(q);
481                 PROC_UNLOCK(q);
482         }
483
484         /* Save exit status. */
485         PROC_LOCK(p);
486         p->p_xthread = td;
487
488         /* Tell the prison that we are gone. */
489         prison_proc_free(p->p_ucred->cr_prison);
490
491 #ifdef KDTRACE_HOOKS
492         /*
493          * Tell the DTrace fasttrap provider about the exit if it
494          * has declared an interest.
495          */
496         if (dtrace_fasttrap_exit)
497                 dtrace_fasttrap_exit(p);
498 #endif
499
500         /*
501          * Notify interested parties of our demise.
502          */
503         KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
504
505 #ifdef KDTRACE_HOOKS
506         int reason = CLD_EXITED;
507         if (WCOREDUMP(rv))
508                 reason = CLD_DUMPED;
509         else if (WIFSIGNALED(rv))
510                 reason = CLD_KILLED;
511         SDT_PROBE(proc, kernel, , exit, reason, 0, 0, 0, 0);
512 #endif
513
514         /*
515          * Just delete all entries in the p_klist. At this point we won't
516          * report any more events, and there are nasty race conditions that
517          * can beat us if we don't.
518          */
519         knlist_clear(&p->p_klist, 1);
520
521         /*
522          * If this is a process with a descriptor, we may not need to deliver
523          * a signal to the parent.  proctree_lock is held over
524          * procdesc_exit() to serialize concurrent calls to close() and
525          * exit().
526          */
527 #ifdef PROCDESC
528         if (p->p_procdesc == NULL || procdesc_exit(p)) {
529 #endif
530                 /*
531                  * Notify parent that we're gone.  If parent has the
532                  * PS_NOCLDWAIT flag set, or if the handler is set to SIG_IGN,
533                  * notify process 1 instead (and hope it will handle this
534                  * situation).
535                  */
536                 PROC_LOCK(p->p_pptr);
537                 mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
538                 if (p->p_pptr->p_sigacts->ps_flag &
539                     (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
540                         struct proc *pp;
541
542                         mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
543                         pp = p->p_pptr;
544                         PROC_UNLOCK(pp);
545                         proc_reparent(p, initproc);
546                         p->p_sigparent = SIGCHLD;
547                         PROC_LOCK(p->p_pptr);
548
549                         /*
550                          * Notify parent, so in case he was wait(2)ing or
551                          * executing waitpid(2) with our pid, he will
552                          * continue.
553                          */
554                         wakeup(pp);
555                 } else
556                         mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
557
558                 if (p->p_pptr == initproc)
559                         kern_psignal(p->p_pptr, SIGCHLD);
560                 else if (p->p_sigparent != 0) {
561                         if (p->p_sigparent == SIGCHLD)
562                                 childproc_exited(p);
563                         else    /* LINUX thread */
564                                 kern_psignal(p->p_pptr, p->p_sigparent);
565                 }
566 #ifdef PROCDESC
567         } else
568                 PROC_LOCK(p->p_pptr);
569 #endif
570         sx_xunlock(&proctree_lock);
571
572         /*
573          * The state PRS_ZOMBIE prevents other proesses from sending
574          * signal to the process, to avoid memory leak, we free memory
575          * for signal queue at the time when the state is set.
576          */
577         sigqueue_flush(&p->p_sigqueue);
578         sigqueue_flush(&td->td_sigqueue);
579
580         /*
581          * We have to wait until after acquiring all locks before
582          * changing p_state.  We need to avoid all possible context
583          * switches (including ones from blocking on a mutex) while
584          * marked as a zombie.  We also have to set the zombie state
585          * before we release the parent process' proc lock to avoid
586          * a lost wakeup.  So, we first call wakeup, then we grab the
587          * sched lock, update the state, and release the parent process'
588          * proc lock.
589          */
590         wakeup(p->p_pptr);
591         cv_broadcast(&p->p_pwait);
592         sched_exit(p->p_pptr, td);
593         PROC_SLOCK(p);
594         p->p_state = PRS_ZOMBIE;
595         PROC_UNLOCK(p->p_pptr);
596
597         /*
598          * Hopefully no one will try to deliver a signal to the process this
599          * late in the game.
600          */
601         knlist_destroy(&p->p_klist);
602
603         /*
604          * Save our children's rusage information in our exit rusage.
605          */
606         ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
607
608         /*
609          * Make sure the scheduler takes this thread out of its tables etc.
610          * This will also release this thread's reference to the ucred.
611          * Other thread parts to release include pcb bits and such.
612          */
613         thread_exit();
614 }
615
616
617 #ifndef _SYS_SYSPROTO_H_
618 struct abort2_args {
619         char *why;
620         int nargs;
621         void **args;
622 };
623 #endif
624
625 int
626 sys_abort2(struct thread *td, struct abort2_args *uap)
627 {
628         struct proc *p = td->td_proc;
629         struct sbuf *sb;
630         void *uargs[16];
631         int error, i, sig;
632
633         /*
634          * Do it right now so we can log either proper call of abort2(), or
635          * note, that invalid argument was passed. 512 is big enough to
636          * handle 16 arguments' descriptions with additional comments.
637          */
638         sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
639         sbuf_clear(sb);
640         sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
641             p->p_comm, p->p_pid, td->td_ucred->cr_uid);
642         /*
643          * Since we can't return from abort2(), send SIGKILL in cases, where
644          * abort2() was called improperly
645          */
646         sig = SIGKILL;
647         /* Prevent from DoSes from user-space. */
648         if (uap->nargs < 0 || uap->nargs > 16)
649                 goto out;
650         if (uap->nargs > 0) {
651                 if (uap->args == NULL)
652                         goto out;
653                 error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
654                 if (error != 0)
655                         goto out;
656         }
657         /*
658          * Limit size of 'reason' string to 128. Will fit even when
659          * maximal number of arguments was chosen to be logged.
660          */
661         if (uap->why != NULL) {
662                 error = sbuf_copyin(sb, uap->why, 128);
663                 if (error < 0)
664                         goto out;
665         } else {
666                 sbuf_printf(sb, "(null)");
667         }
668         if (uap->nargs > 0) {
669                 sbuf_printf(sb, "(");
670                 for (i = 0;i < uap->nargs; i++)
671                         sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
672                 sbuf_printf(sb, ")");
673         }
674         /*
675          * Final stage: arguments were proper, string has been
676          * successfully copied from userspace, and copying pointers
677          * from user-space succeed.
678          */
679         sig = SIGABRT;
680 out:
681         if (sig == SIGKILL) {
682                 sbuf_trim(sb);
683                 sbuf_printf(sb, " (Reason text inaccessible)");
684         }
685         sbuf_cat(sb, "\n");
686         sbuf_finish(sb);
687         log(LOG_INFO, "%s", sbuf_data(sb));
688         sbuf_delete(sb);
689         exit1(td, W_EXITCODE(0, sig));
690         return (0);
691 }
692
693
694 #ifdef COMPAT_43
695 /*
696  * The dirty work is handled by kern_wait().
697  */
698 int
699 owait(struct thread *td, struct owait_args *uap __unused)
700 {
701         int error, status;
702
703         error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
704         if (error == 0)
705                 td->td_retval[1] = status;
706         return (error);
707 }
708 #endif /* COMPAT_43 */
709
710 /*
711  * The dirty work is handled by kern_wait().
712  */
713 int
714 sys_wait4(struct thread *td, struct wait4_args *uap)
715 {
716         struct rusage ru, *rup;
717         int error, status;
718
719         if (uap->rusage != NULL)
720                 rup = &ru;
721         else
722                 rup = NULL;
723         error = kern_wait(td, uap->pid, &status, uap->options, rup);
724         if (uap->status != NULL && error == 0)
725                 error = copyout(&status, uap->status, sizeof(status));
726         if (uap->rusage != NULL && error == 0)
727                 error = copyout(&ru, uap->rusage, sizeof(struct rusage));
728         return (error);
729 }
730
731 int
732 sys_wait6(struct thread *td, struct wait6_args *uap)
733 {
734         struct __wrusage wru, *wrup;
735         siginfo_t si, *sip;
736         idtype_t idtype;
737         id_t id;
738         int error, status;
739
740         idtype = uap->idtype;
741         id = uap->id;
742
743         if (uap->wrusage != NULL)
744                 wrup = &wru;
745         else
746                 wrup = NULL;
747
748         if (uap->info != NULL) {
749                 sip = &si;
750                 bzero(sip, sizeof(*sip));
751         } else
752                 sip = NULL;
753
754         /*
755          *  We expect all callers of wait6() to know about WEXITED and
756          *  WTRAPPED.
757          */
758         error = kern_wait6(td, idtype, id, &status, uap->options, wrup, sip);
759
760         if (uap->status != NULL && error == 0)
761                 error = copyout(&status, uap->status, sizeof(status));
762         if (uap->wrusage != NULL && error == 0)
763                 error = copyout(&wru, uap->wrusage, sizeof(wru));
764         if (uap->info != NULL && error == 0)
765                 error = copyout(&si, uap->info, sizeof(si));
766         return (error);
767 }
768
769 /*
770  * Reap the remains of a zombie process and optionally return status and
771  * rusage.  Asserts and will release both the proctree_lock and the process
772  * lock as part of its work.
773  */
774 void
775 proc_reap(struct thread *td, struct proc *p, int *status, int options)
776 {
777         struct proc *q, *t;
778
779         sx_assert(&proctree_lock, SA_XLOCKED);
780         PROC_LOCK_ASSERT(p, MA_OWNED);
781         PROC_SLOCK_ASSERT(p, MA_OWNED);
782         KASSERT(p->p_state == PRS_ZOMBIE, ("proc_reap: !PRS_ZOMBIE"));
783
784         q = td->td_proc;
785
786         PROC_SUNLOCK(p);
787         td->td_retval[0] = p->p_pid;
788         if (status)
789                 *status = p->p_xstat;   /* convert to int */
790         if (options & WNOWAIT) {
791                 /*
792                  *  Only poll, returning the status.  Caller does not wish to
793                  * release the proc struct just yet.
794                  */
795                 PROC_UNLOCK(p);
796                 sx_xunlock(&proctree_lock);
797                 return;
798         }
799
800         PROC_LOCK(q);
801         sigqueue_take(p->p_ksi);
802         PROC_UNLOCK(q);
803         PROC_UNLOCK(p);
804
805         /*
806          * If we got the child via a ptrace 'attach', we need to give it back
807          * to the old parent.
808          */
809         if (p->p_oppid != 0) {
810                 t = proc_realparent(p);
811                 PROC_LOCK(t);
812                 PROC_LOCK(p);
813                 proc_reparent(p, t);
814                 p->p_oppid = 0;
815                 PROC_UNLOCK(p);
816                 pksignal(t, SIGCHLD, p->p_ksi);
817                 wakeup(t);
818                 cv_broadcast(&p->p_pwait);
819                 PROC_UNLOCK(t);
820                 sx_xunlock(&proctree_lock);
821                 return;
822         }
823
824         /*
825          * Remove other references to this process to ensure we have an
826          * exclusive reference.
827          */
828         sx_xlock(&allproc_lock);
829         LIST_REMOVE(p, p_list); /* off zombproc */
830         sx_xunlock(&allproc_lock);
831         LIST_REMOVE(p, p_sibling);
832         PROC_LOCK(p);
833         clear_orphan(p);
834         PROC_UNLOCK(p);
835         leavepgrp(p);
836 #ifdef PROCDESC
837         if (p->p_procdesc != NULL)
838                 procdesc_reap(p);
839 #endif
840         sx_xunlock(&proctree_lock);
841
842         /*
843          * As a side effect of this lock, we know that all other writes to
844          * this proc are visible now, so no more locking is needed for p.
845          */
846         PROC_LOCK(p);
847         p->p_xstat = 0;         /* XXX: why? */
848         PROC_UNLOCK(p);
849         PROC_LOCK(q);
850         ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru, &p->p_rux);
851         PROC_UNLOCK(q);
852
853         /*
854          * Decrement the count of procs running with this uid.
855          */
856         (void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
857
858         /*
859          * Destroy resource accounting information associated with the process.
860          */
861 #ifdef RACCT
862         PROC_LOCK(p);
863         racct_sub(p, RACCT_NPROC, 1);
864         PROC_UNLOCK(p);
865 #endif
866         racct_proc_exit(p);
867
868         /*
869          * Free credentials, arguments, and sigacts.
870          */
871         crfree(p->p_ucred);
872         p->p_ucred = NULL;
873         pargs_drop(p->p_args);
874         p->p_args = NULL;
875         sigacts_free(p->p_sigacts);
876         p->p_sigacts = NULL;
877
878         /*
879          * Do any thread-system specific cleanups.
880          */
881         thread_wait(p);
882
883         /*
884          * Give vm and machine-dependent layer a chance to free anything that
885          * cpu_exit couldn't release while still running in process context.
886          */
887         vm_waitproc(p);
888 #ifdef MAC
889         mac_proc_destroy(p);
890 #endif
891         KASSERT(FIRST_THREAD_IN_PROC(p),
892             ("proc_reap: no residual thread!"));
893         uma_zfree(proc_zone, p);
894         sx_xlock(&allproc_lock);
895         nprocs--;
896         sx_xunlock(&allproc_lock);
897 }
898
899 static int
900 proc_to_reap(struct thread *td, struct proc *p, idtype_t idtype, id_t id,
901     int *status, int options, struct __wrusage *wrusage, siginfo_t *siginfo)
902 {
903         struct proc *q;
904         struct rusage *rup;
905
906         sx_assert(&proctree_lock, SA_XLOCKED);
907
908         q = td->td_proc;
909         PROC_LOCK(p);
910
911         switch (idtype) {
912         case P_ALL:
913                 break;
914         case P_PID:
915                 if (p->p_pid != (pid_t)id) {
916                         PROC_UNLOCK(p);
917                         return (0);
918                 }
919                 break;
920         case P_PGID:
921                 if (p->p_pgid != (pid_t)id) {
922                         PROC_UNLOCK(p);
923                         return (0);
924                 }
925                 break;
926         case P_SID:
927                 if (p->p_session->s_sid != (pid_t)id) {
928                         PROC_UNLOCK(p);
929                         return (0);
930                 }
931                 break;
932         case P_UID:
933                 if (p->p_ucred->cr_uid != (uid_t)id) {
934                         PROC_UNLOCK(p);
935                         return (0);
936                 }
937                 break;
938         case P_GID:
939                 if (p->p_ucred->cr_gid != (gid_t)id) {
940                         PROC_UNLOCK(p);
941                         return (0);
942                 }
943                 break;
944         case P_JAILID:
945                 if (p->p_ucred->cr_prison->pr_id != (int)id) {
946                         PROC_UNLOCK(p);
947                         return (0);
948                 }
949                 break;
950         /*
951          * It seems that the thread structures get zeroed out
952          * at process exit.  This makes it impossible to
953          * support P_SETID, P_CID or P_CPUID.
954          */
955         default:
956                 PROC_UNLOCK(p);
957                 return (0);
958         }
959
960         if (p_canwait(td, p)) {
961                 PROC_UNLOCK(p);
962                 return (0);
963         }
964
965         if (((options & WEXITED) == 0) && (p->p_state == PRS_ZOMBIE)) {
966                 PROC_UNLOCK(p);
967                 return (0);
968         }
969
970         /*
971          * This special case handles a kthread spawned by linux_clone
972          * (see linux_misc.c).  The linux_wait4 and linux_waitpid
973          * functions need to be able to distinguish between waiting
974          * on a process and waiting on a thread.  It is a thread if
975          * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
976          * signifies we want to wait for threads and not processes.
977          */
978         if ((p->p_sigparent != SIGCHLD) ^
979             ((options & WLINUXCLONE) != 0)) {
980                 PROC_UNLOCK(p);
981                 return (0);
982         }
983
984         PROC_SLOCK(p);
985
986         if (siginfo != NULL) {
987                 bzero(siginfo, sizeof(*siginfo));
988                 siginfo->si_errno = 0;
989
990                 /*
991                  * SUSv4 requires that the si_signo value is always
992                  * SIGCHLD. Obey it despite the rfork(2) interface
993                  * allows to request other signal for child exit
994                  * notification.
995                  */
996                 siginfo->si_signo = SIGCHLD;
997
998                 /*
999                  *  This is still a rough estimate.  We will fix the
1000                  *  cases TRAPPED, STOPPED, and CONTINUED later.
1001                  */
1002                 if (WCOREDUMP(p->p_xstat)) {
1003                         siginfo->si_code = CLD_DUMPED;
1004                         siginfo->si_status = WTERMSIG(p->p_xstat);
1005                 } else if (WIFSIGNALED(p->p_xstat)) {
1006                         siginfo->si_code = CLD_KILLED;
1007                         siginfo->si_status = WTERMSIG(p->p_xstat);
1008                 } else {
1009                         siginfo->si_code = CLD_EXITED;
1010                         siginfo->si_status = WEXITSTATUS(p->p_xstat);
1011                 }
1012
1013                 siginfo->si_pid = p->p_pid;
1014                 siginfo->si_uid = p->p_ucred->cr_uid;
1015
1016                 /*
1017                  * The si_addr field would be useful additional
1018                  * detail, but apparently the PC value may be lost
1019                  * when we reach this point.  bzero() above sets
1020                  * siginfo->si_addr to NULL.
1021                  */
1022         }
1023
1024         /*
1025          * There should be no reason to limit resources usage info to
1026          * exited processes only.  A snapshot about any resources used
1027          * by a stopped process may be exactly what is needed.
1028          */
1029         if (wrusage != NULL) {
1030                 rup = &wrusage->wru_self;
1031                 *rup = p->p_ru;
1032                 calcru(p, &rup->ru_utime, &rup->ru_stime);
1033
1034                 rup = &wrusage->wru_children;
1035                 *rup = p->p_stats->p_cru;
1036                 calccru(p, &rup->ru_utime, &rup->ru_stime);
1037         }
1038
1039         if (p->p_state == PRS_ZOMBIE) {
1040                 proc_reap(td, p, status, options);
1041                 return (-1);
1042         }
1043         PROC_SUNLOCK(p);
1044         PROC_UNLOCK(p);
1045         return (1);
1046 }
1047
1048 int
1049 kern_wait(struct thread *td, pid_t pid, int *status, int options,
1050     struct rusage *rusage)
1051 {
1052         struct __wrusage wru, *wrup;
1053         idtype_t idtype;
1054         id_t id;
1055         int ret;
1056
1057         /*
1058          * Translate the special pid values into the (idtype, pid)
1059          * pair for kern_wait6.  The WAIT_MYPGRP case is handled by
1060          * kern_wait6() on its own.
1061          */
1062         if (pid == WAIT_ANY) {
1063                 idtype = P_ALL;
1064                 id = 0;
1065         } else if (pid < 0) {
1066                 idtype = P_PGID;
1067                 id = (id_t)-pid;
1068         } else {
1069                 idtype = P_PID;
1070                 id = (id_t)pid;
1071         }
1072
1073         if (rusage != NULL)
1074                 wrup = &wru;
1075         else
1076                 wrup = NULL;
1077
1078         /*
1079          * For backward compatibility we implicitly add flags WEXITED
1080          * and WTRAPPED here.
1081          */
1082         options |= WEXITED | WTRAPPED;
1083         ret = kern_wait6(td, idtype, id, status, options, wrup, NULL);
1084         if (rusage != NULL)
1085                 *rusage = wru.wru_self;
1086         return (ret);
1087 }
1088
1089 int
1090 kern_wait6(struct thread *td, idtype_t idtype, id_t id, int *status,
1091     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1092 {
1093         struct proc *p, *q;
1094         int error, nfound, ret;
1095
1096         AUDIT_ARG_VALUE((int)idtype);   /* XXX - This is likely wrong! */
1097         AUDIT_ARG_PID((pid_t)id);       /* XXX - This may be wrong! */
1098         AUDIT_ARG_VALUE(options);
1099
1100         q = td->td_proc;
1101
1102         if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1103                 PROC_LOCK(q);
1104                 id = (id_t)q->p_pgid;
1105                 PROC_UNLOCK(q);
1106                 idtype = P_PGID;
1107         }
1108
1109         /* If we don't know the option, just return. */
1110         if ((options & ~(WUNTRACED | WNOHANG | WCONTINUED | WNOWAIT |
1111             WEXITED | WTRAPPED | WLINUXCLONE)) != 0)
1112                 return (EINVAL);
1113         if ((options & (WEXITED | WUNTRACED | WCONTINUED | WTRAPPED)) == 0) {
1114                 /*
1115                  * We will be unable to find any matching processes,
1116                  * because there are no known events to look for.
1117                  * Prefer to return error instead of blocking
1118                  * indefinitely.
1119                  */
1120                 return (EINVAL);
1121         }
1122
1123 loop:
1124         if (q->p_flag & P_STATCHILD) {
1125                 PROC_LOCK(q);
1126                 q->p_flag &= ~P_STATCHILD;
1127                 PROC_UNLOCK(q);
1128         }
1129         nfound = 0;
1130         sx_xlock(&proctree_lock);
1131         LIST_FOREACH(p, &q->p_children, p_sibling) {
1132                 ret = proc_to_reap(td, p, idtype, id, status, options,
1133                     wrusage, siginfo);
1134                 if (ret == 0)
1135                         continue;
1136                 else if (ret == 1)
1137                         nfound++;
1138                 else
1139                         return (0);
1140
1141                 PROC_LOCK(p);
1142                 PROC_SLOCK(p);
1143
1144                 if ((options & WTRAPPED) != 0 &&
1145                     (p->p_flag & P_TRACED) != 0 &&
1146                     (p->p_flag & (P_STOPPED_TRACE | P_STOPPED_SIG)) != 0 &&
1147                     (p->p_suspcount == p->p_numthreads) &&
1148                     ((p->p_flag & P_WAITED) == 0)) {
1149                         PROC_SUNLOCK(p);
1150                         if ((options & WNOWAIT) == 0)
1151                                 p->p_flag |= P_WAITED;
1152                         sx_xunlock(&proctree_lock);
1153                         td->td_retval[0] = p->p_pid;
1154
1155                         if (status != NULL)
1156                                 *status = W_STOPCODE(p->p_xstat);
1157                         if (siginfo != NULL) {
1158                                 siginfo->si_status = p->p_xstat;
1159                                 siginfo->si_code = CLD_TRAPPED;
1160                         }
1161                         if ((options & WNOWAIT) == 0) {
1162                                 PROC_LOCK(q);
1163                                 sigqueue_take(p->p_ksi);
1164                                 PROC_UNLOCK(q);
1165                         }
1166
1167                         PROC_UNLOCK(p);
1168                         return (0);
1169                 }
1170                 if ((options & WUNTRACED) != 0 &&
1171                     (p->p_flag & P_STOPPED_SIG) != 0 &&
1172                     (p->p_suspcount == p->p_numthreads) &&
1173                     ((p->p_flag & P_WAITED) == 0)) {
1174                         PROC_SUNLOCK(p);
1175                         if ((options & WNOWAIT) == 0)
1176                                 p->p_flag |= P_WAITED;
1177                         sx_xunlock(&proctree_lock);
1178                         td->td_retval[0] = p->p_pid;
1179
1180                         if (status != NULL)
1181                                 *status = W_STOPCODE(p->p_xstat);
1182                         if (siginfo != NULL) {
1183                                 siginfo->si_status = p->p_xstat;
1184                                 siginfo->si_code = CLD_STOPPED;
1185                         }
1186                         if ((options & WNOWAIT) == 0) {
1187                                 PROC_LOCK(q);
1188                                 sigqueue_take(p->p_ksi);
1189                                 PROC_UNLOCK(q);
1190                         }
1191
1192                         PROC_UNLOCK(p);
1193                         return (0);
1194                 }
1195                 PROC_SUNLOCK(p);
1196                 if ((options & WCONTINUED) != 0 &&
1197                     (p->p_flag & P_CONTINUED) != 0) {
1198                         sx_xunlock(&proctree_lock);
1199                         td->td_retval[0] = p->p_pid;
1200                         if ((options & WNOWAIT) == 0) {
1201                                 p->p_flag &= ~P_CONTINUED;
1202                                 PROC_LOCK(q);
1203                                 sigqueue_take(p->p_ksi);
1204                                 PROC_UNLOCK(q);
1205                         }
1206                         PROC_UNLOCK(p);
1207
1208                         if (status != NULL)
1209                                 *status = SIGCONT;
1210                         if (siginfo != NULL) {
1211                                 siginfo->si_status = SIGCONT;
1212                                 siginfo->si_code = CLD_CONTINUED;
1213                         }
1214                         return (0);
1215                 }
1216                 PROC_UNLOCK(p);
1217         }
1218
1219         /*
1220          * Look in the orphans list too, to allow the parent to
1221          * collect it's child exit status even if child is being
1222          * debugged.
1223          *
1224          * Debugger detaches from the parent upon successful
1225          * switch-over from parent to child.  At this point due to
1226          * re-parenting the parent loses the child to debugger and a
1227          * wait4(2) call would report that it has no children to wait
1228          * for.  By maintaining a list of orphans we allow the parent
1229          * to successfully wait until the child becomes a zombie.
1230          */
1231         LIST_FOREACH(p, &q->p_orphans, p_orphan) {
1232                 ret = proc_to_reap(td, p, idtype, id, status, options,
1233                     wrusage, siginfo);
1234                 if (ret == 0)
1235                         continue;
1236                 else if (ret == 1)
1237                         nfound++;
1238                 else
1239                         return (0);
1240         }
1241         if (nfound == 0) {
1242                 sx_xunlock(&proctree_lock);
1243                 return (ECHILD);
1244         }
1245         if (options & WNOHANG) {
1246                 sx_xunlock(&proctree_lock);
1247                 td->td_retval[0] = 0;
1248                 return (0);
1249         }
1250         PROC_LOCK(q);
1251         sx_xunlock(&proctree_lock);
1252         if (q->p_flag & P_STATCHILD) {
1253                 q->p_flag &= ~P_STATCHILD;
1254                 error = 0;
1255         } else
1256                 error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
1257         PROC_UNLOCK(q);
1258         if (error)
1259                 return (error);
1260         goto loop;
1261 }
1262
1263 /*
1264  * Make process 'parent' the new parent of process 'child'.
1265  * Must be called with an exclusive hold of proctree lock.
1266  */
1267 void
1268 proc_reparent(struct proc *child, struct proc *parent)
1269 {
1270
1271         sx_assert(&proctree_lock, SX_XLOCKED);
1272         PROC_LOCK_ASSERT(child, MA_OWNED);
1273         if (child->p_pptr == parent)
1274                 return;
1275
1276         PROC_LOCK(child->p_pptr);
1277         sigqueue_take(child->p_ksi);
1278         PROC_UNLOCK(child->p_pptr);
1279         LIST_REMOVE(child, p_sibling);
1280         LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1281
1282         clear_orphan(child);
1283         if (child->p_flag & P_TRACED) {
1284                 if (LIST_EMPTY(&child->p_pptr->p_orphans)) {
1285                         child->p_treeflag |= P_TREE_FIRST_ORPHAN;
1286                         LIST_INSERT_HEAD(&child->p_pptr->p_orphans, child,
1287                             p_orphan);
1288                 } else {
1289                         LIST_INSERT_AFTER(LIST_FIRST(&child->p_pptr->p_orphans),
1290                             child, p_orphan);
1291                 }
1292                 child->p_treeflag |= P_TREE_ORPHANED;
1293         }
1294
1295         child->p_pptr = parent;
1296 }