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