kernel - Fix race in multi-LWP exit
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
39  * $FreeBSD: src/sys/kern/kern_exit.c,v 1.92.2.11 2003/01/13 22:51:16 dillon Exp $
40  * $DragonFly: src/sys/kern/kern_exit.c,v 1.91 2008/05/18 20:02:02 nth Exp $
41  */
42
43 #include "opt_compat.h"
44 #include "opt_ktrace.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/sysproto.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/proc.h>
52 #include <sys/ktrace.h>
53 #include <sys/pioctl.h>
54 #include <sys/tty.h>
55 #include <sys/wait.h>
56 #include <sys/vnode.h>
57 #include <sys/resourcevar.h>
58 #include <sys/signalvar.h>
59 #include <sys/taskqueue.h>
60 #include <sys/ptrace.h>
61 #include <sys/acct.h>           /* for acct_process() function prototype */
62 #include <sys/filedesc.h>
63 #include <sys/shm.h>
64 #include <sys/sem.h>
65 #include <sys/jail.h>
66 #include <sys/kern_syscall.h>
67 #include <sys/upcall.h>
68 #include <sys/caps.h>
69 #include <sys/unistd.h>
70 #include <sys/eventhandler.h>
71 #include <sys/dsched.h>
72
73 #include <vm/vm.h>
74 #include <vm/vm_param.h>
75 #include <sys/lock.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_extern.h>
79 #include <sys/user.h>
80
81 #include <sys/refcount.h>
82 #include <sys/thread2.h>
83 #include <sys/sysref2.h>
84 #include <sys/mplock2.h>
85
86 static void reaplwps(void *context, int dummy);
87 static void reaplwp(struct lwp *lp);
88 static void killlwps(struct lwp *lp);
89
90 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
91 static MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
92
93 static struct lwkt_token deadlwp_token = LWKT_TOKEN_INITIALIZER(deadlwp_token);
94
95 /*
96  * callout list for things to do at exit time
97  */
98 struct exitlist {
99         exitlist_fn function;
100         TAILQ_ENTRY(exitlist) next;
101 };
102
103 TAILQ_HEAD(exit_list_head, exitlist);
104 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
105
106 /*
107  * LWP reaper data
108  */
109 struct task *deadlwp_task[MAXCPU];
110 struct lwplist deadlwp_list[MAXCPU];
111
112 /*
113  * exit --
114  *      Death of process.
115  *
116  * SYS_EXIT_ARGS(int rval)
117  */
118 int
119 sys_exit(struct exit_args *uap)
120 {
121         exit1(W_EXITCODE(uap->rval, 0));
122         /* NOTREACHED */
123 }
124
125 /*
126  * Extended exit --
127  *      Death of a lwp or process with optional bells and whistles.
128  *
129  * MPALMOSTSAFE
130  */
131 int
132 sys_extexit(struct extexit_args *uap)
133 {
134         struct proc *p = curproc;
135         int action, who;
136         int error;
137
138         action = EXTEXIT_ACTION(uap->how);
139         who = EXTEXIT_WHO(uap->how);
140
141         /* Check parameters before we might perform some action */
142         switch (who) {
143         case EXTEXIT_PROC:
144         case EXTEXIT_LWP:
145                 break;
146         default:
147                 return (EINVAL);
148         }
149
150         switch (action) {
151         case EXTEXIT_SIMPLE:
152                 break;
153         case EXTEXIT_SETINT:
154                 error = copyout(&uap->status, uap->addr, sizeof(uap->status));
155                 if (error)
156                         return (error);
157                 break;
158         default:
159                 return (EINVAL);
160         }
161
162         lwkt_gettoken(&p->p_token);
163
164         switch (who) {
165         case EXTEXIT_LWP:
166                 /*
167                  * Be sure only to perform a simple lwp exit if there is at
168                  * least one more lwp in the proc, which will call exit1()
169                  * later, otherwise the proc will be an UNDEAD and not even a
170                  * SZOMB!
171                  */
172                 if (p->p_nthreads > 1) {
173                         lwp_exit(0);    /* called w/ p_token held */
174                         /* NOT REACHED */
175                 }
176                 /* else last lwp in proc:  do the real thing */
177                 /* FALLTHROUGH */
178         default:        /* to help gcc */
179         case EXTEXIT_PROC:
180                 lwkt_reltoken(&p->p_token);
181                 exit1(W_EXITCODE(uap->status, 0));
182                 /* NOTREACHED */
183         }
184
185         /* NOTREACHED */
186         lwkt_reltoken(&p->p_token);     /* safety */
187 }
188
189 /*
190  * Kill all lwps associated with the current process except the
191  * current lwp.   Return an error if we race another thread trying to
192  * do the same thing and lose the race.
193  *
194  * If forexec is non-zero the current thread and process flags are
195  * cleaned up so they can be reused.
196  *
197  * Caller must hold curproc->p_token
198  */
199 int
200 killalllwps(int forexec)
201 {
202         struct lwp *lp = curthread->td_lwp;
203         struct proc *p = lp->lwp_proc;
204
205         /*
206          * Interlock against P_WEXIT.  Only one of the process's thread
207          * is allowed to do the master exit.
208          */
209         if (p->p_flags & P_WEXIT)
210                 return (EALREADY);
211         p->p_flags |= P_WEXIT;
212
213         /*
214          * Interlock with LWP_MP_WEXIT and kill any remaining LWPs
215          */
216         atomic_set_int(&lp->lwp_mpflags, LWP_MP_WEXIT);
217         if (p->p_nthreads > 1)
218                 killlwps(lp);
219
220         /*
221          * If doing this for an exec, clean up the remaining thread
222          * (us) for continuing operation after all the other threads
223          * have been killed.
224          */
225         if (forexec) {
226                 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_WEXIT);
227                 p->p_flags &= ~P_WEXIT;
228         }
229         return(0);
230 }
231
232 /*
233  * Kill all LWPs except the current one.  Do not try to signal
234  * LWPs which have exited on their own or have already been
235  * signaled.
236  */
237 static void
238 killlwps(struct lwp *lp)
239 {
240         struct proc *p = lp->lwp_proc;
241         struct lwp *tlp;
242
243         /*
244          * Kill the remaining LWPs.  We must send the signal before setting
245          * LWP_MP_WEXIT.  The setting of WEXIT is optional but helps reduce
246          * races.  tlp must be held across the call as it might block and
247          * allow the target lwp to rip itself out from under our loop.
248          */
249         FOREACH_LWP_IN_PROC(tlp, p) {
250                 LWPHOLD(tlp);
251                 lwkt_gettoken(&tlp->lwp_token);
252                 if ((tlp->lwp_mpflags & LWP_MP_WEXIT) == 0) {
253                         lwpsignal(p, tlp, SIGKILL);
254                         atomic_set_int(&tlp->lwp_mpflags, LWP_MP_WEXIT);
255                 }
256                 lwkt_reltoken(&tlp->lwp_token);
257                 LWPRELE(tlp);
258         }
259
260         /*
261          * Wait for everything to clear out.
262          */
263         while (p->p_nthreads > 1) {
264                 tsleep(&p->p_nthreads, 0, "killlwps", 0);
265         }
266 }
267
268 /*
269  * Exit: deallocate address space and other resources, change proc state
270  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
271  * status and rusage for wait().  Check for child processes and orphan them.
272  */
273 void
274 exit1(int rv)
275 {
276         struct thread *td = curthread;
277         struct proc *p = td->td_proc;
278         struct lwp *lp = td->td_lwp;
279         struct proc *q, *nq;
280         struct vmspace *vm;
281         struct vnode *vtmp;
282         struct exitlist *ep;
283         int error;
284
285         lwkt_gettoken(&p->p_token);
286
287         if (p->p_pid == 1) {
288                 kprintf("init died (signal %d, exit %d)\n",
289                     WTERMSIG(rv), WEXITSTATUS(rv));
290                 panic("Going nowhere without my init!");
291         }
292         varsymset_clean(&p->p_varsymset);
293         lockuninit(&p->p_varsymset.vx_lock);
294
295         /*
296          * Kill all lwps associated with the current process, return an
297          * error if we race another thread trying to do the same thing
298          * and lose the race.
299          */
300         error = killalllwps(0);
301         if (error) {
302                 lwp_exit(0);
303                 /* NOT REACHED */
304         }
305
306         caps_exit(lp->lwp_thread);
307
308         /* are we a task leader? */
309         if (p == p->p_leader) {
310                 struct kill_args killArgs;
311                 killArgs.signum = SIGKILL;
312                 q = p->p_peers;
313                 while(q) {
314                         killArgs.pid = q->p_pid;
315                         /*
316                          * The interface for kill is better
317                          * than the internal signal
318                          */
319                         sys_kill(&killArgs);
320                         nq = q;
321                         q = q->p_peers;
322                 }
323                 while (p->p_peers) 
324                         tsleep((caddr_t)p, 0, "exit1", 0);
325         }
326
327 #ifdef PGINPROF
328         vmsizmon();
329 #endif
330         STOPEVENT(p, S_EXIT, rv);
331         wakeup(&p->p_stype);    /* Wakeup anyone in procfs' PIOCWAIT */
332
333         /* 
334          * Check if any loadable modules need anything done at process exit.
335          * e.g. SYSV IPC stuff
336          * XXX what if one of these generates an error?
337          */
338         p->p_xstat = rv;
339         EVENTHANDLER_INVOKE(process_exit, p);
340
341         /*
342          * XXX: imho, the eventhandler stuff is much cleaner than this.
343          *      Maybe we should move everything to use eventhandler.
344          */
345         TAILQ_FOREACH(ep, &exit_list, next) 
346                 (*ep->function)(td);
347
348         if (p->p_flags & P_PROFIL)
349                 stopprofclock(p);
350         /*
351          * If parent is waiting for us to exit or exec,
352          * P_PPWAIT is set; we will wakeup the parent below.
353          */
354         p->p_flags &= ~(P_TRACED | P_PPWAIT);
355         SIGEMPTYSET(p->p_siglist);
356         SIGEMPTYSET(lp->lwp_siglist);
357         if (timevalisset(&p->p_realtimer.it_value))
358                 callout_stop(&p->p_ithandle);
359
360         /*
361          * Reset any sigio structures pointing to us as a result of
362          * F_SETOWN with our pid.
363          */
364         funsetownlst(&p->p_sigiolst);
365
366         /*
367          * Close open files and release open-file table.
368          * This may block!
369          */
370         fdfree(p, NULL);
371
372         if(p->p_leader->p_peers) {
373                 q = p->p_leader;
374                 while(q->p_peers != p)
375                         q = q->p_peers;
376                 q->p_peers = p->p_peers;
377                 wakeup((caddr_t)p->p_leader);
378         }
379
380         /*
381          * XXX Shutdown SYSV semaphores
382          */
383         semexit(p);
384
385         KKASSERT(p->p_numposixlocks == 0);
386
387         /* The next two chunks should probably be moved to vmspace_exit. */
388         vm = p->p_vmspace;
389
390         /*
391          * Release upcalls associated with this process
392          */
393         if (vm->vm_upcalls)
394                 upc_release(vm, lp);
395
396         /*
397          * Clean up data related to virtual kernel operation.  Clean up
398          * any vkernel context related to the current lwp now so we can
399          * destroy p_vkernel.
400          */
401         if (p->p_vkernel) {
402                 vkernel_lwp_exit(lp);
403                 vkernel_exit(p);
404         }
405
406         /*
407          * Release user portion of address space.
408          * This releases references to vnodes,
409          * which could cause I/O if the file has been unlinked.
410          * Need to do this early enough that we can still sleep.
411          * Can't free the entire vmspace as the kernel stack
412          * may be mapped within that space also.
413          *
414          * Processes sharing the same vmspace may exit in one order, and
415          * get cleaned up by vmspace_exit() in a different order.  The
416          * last exiting process to reach this point releases as much of
417          * the environment as it can, and the last process cleaned up
418          * by vmspace_exit() (which decrements exitingcnt) cleans up the
419          * remainder.
420          */
421         vmspace_exitbump(vm);
422         sysref_put(&vm->vm_sysref);
423
424         if (SESS_LEADER(p)) {
425                 struct session *sp = p->p_session;
426
427                 if (sp->s_ttyvp) {
428                         /*
429                          * We are the controlling process.  Signal the 
430                          * foreground process group, drain the controlling
431                          * terminal, and revoke access to the controlling
432                          * terminal.
433                          *
434                          * NOTE: while waiting for the process group to exit
435                          * it is possible that one of the processes in the
436                          * group will revoke the tty, so the ttyclosesession()
437                          * function will re-check sp->s_ttyvp.
438                          */
439                         if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
440                                 if (sp->s_ttyp->t_pgrp)
441                                         pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
442                                 ttywait(sp->s_ttyp);
443                                 ttyclosesession(sp, 1); /* also revoke */
444                         }
445                         /*
446                          * Release the tty.  If someone has it open via
447                          * /dev/tty then close it (since they no longer can
448                          * once we've NULL'd it out).
449                          */
450                         ttyclosesession(sp, 0);
451
452                         /*
453                          * s_ttyp is not zero'd; we use this to indicate
454                          * that the session once had a controlling terminal.
455                          * (for logging and informational purposes)
456                          */
457                 }
458                 sp->s_leader = NULL;
459         }
460         fixjobc(p, p->p_pgrp, 0);
461         (void)acct_process(p);
462 #ifdef KTRACE
463         /*
464          * release trace file
465          */
466         if (p->p_tracenode)
467                 ktrdestroy(&p->p_tracenode);
468         p->p_traceflag = 0;
469 #endif
470         /*
471          * Release reference to text vnode
472          */
473         if ((vtmp = p->p_textvp) != NULL) {
474                 p->p_textvp = NULL;
475                 vrele(vtmp);
476         }
477
478         /* Release namecache handle to text file */
479         if (p->p_textnch.ncp)
480                 cache_drop(&p->p_textnch);
481
482         /*
483          * Move the process to the zombie list.  This will block
484          * until the process p_lock count reaches 0.  The process will
485          * not be reaped until TDF_EXITING is set by cpu_thread_exit(),
486          * which is called from cpu_proc_exit().
487          */
488         proc_move_allproc_zombie(p);
489
490         /*
491          * Reparent all of this process's children to the init process.
492          * We must hold initproc->p_token in order to mess with
493          * initproc->p_children.  We already hold p->p_token (to remove
494          * the children from our list).
495          */
496         q = LIST_FIRST(&p->p_children);
497         if (q) {
498                 lwkt_gettoken(&initproc->p_token);
499                 while (q) {
500                         nq = LIST_NEXT(q, p_sibling);
501                         LIST_REMOVE(q, p_sibling);
502                         LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
503                         q->p_pptr = initproc;
504                         q->p_sigparent = SIGCHLD;
505                         /*
506                          * Traced processes are killed
507                          * since their existence means someone is screwing up.
508                          */
509                         if (q->p_flags & P_TRACED) {
510                                 q->p_flags &= ~P_TRACED;
511                                 ksignal(q, SIGKILL);
512                         }
513                         q = nq;
514                 }
515                 lwkt_reltoken(&initproc->p_token);
516                 wakeup(initproc);
517         }
518
519         /*
520          * Save exit status and final rusage info, adding in child rusage
521          * info and self times.
522          */
523         calcru_proc(p, &p->p_ru);
524         ruadd(&p->p_ru, &p->p_cru);
525
526         /*
527          * notify interested parties of our demise.
528          */
529         KNOTE(&p->p_klist, NOTE_EXIT);
530
531         /*
532          * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
533          * flag set, notify process 1 instead (and hope it will handle
534          * this situation).
535          */
536         if (p->p_pptr->p_sigacts->ps_flag & PS_NOCLDWAIT) {
537                 struct proc *pp = p->p_pptr;
538
539                 PHOLD(pp);
540                 proc_reparent(p, initproc);
541
542                 /*
543                  * If this was the last child of our parent, notify
544                  * parent, so in case he was wait(2)ing, he will
545                  * continue.  This function interlocks with pptr->p_token.
546                  */
547                 if (LIST_EMPTY(&pp->p_children))
548                         wakeup((caddr_t)pp);
549                 PRELE(pp);
550         }
551
552         /* lwkt_gettoken(&proc_token); */
553         q = p->p_pptr;
554         PHOLD(q);
555         if (p->p_sigparent && q != initproc) {
556                 ksignal(q, p->p_sigparent);
557         } else {
558                 ksignal(q, SIGCHLD);
559         }
560         wakeup(p->p_pptr);
561         PRELE(q);
562         /* lwkt_reltoken(&proc_token); */
563         /* NOTE: p->p_pptr can get ripped out */
564         /*
565          * cpu_exit is responsible for clearing curproc, since
566          * it is heavily integrated with the thread/switching sequence.
567          *
568          * Other substructures are freed from wait().
569          */
570         plimit_free(p);
571
572         /*
573          * Release the current user process designation on the process so
574          * the userland scheduler can work in someone else.
575          */
576         p->p_usched->release_curproc(lp);
577
578         /*
579          * Finally, call machine-dependent code to release as many of the
580          * lwp's resources as we can and halt execution of this thread.
581          */
582         lwp_exit(1);
583 }
584
585 /*
586  * Eventually called by every exiting LWP
587  *
588  * p->p_token must be held.  mplock may be held and will be released.
589  */
590 void
591 lwp_exit(int masterexit)
592 {
593         struct thread *td = curthread;
594         struct lwp *lp = td->td_lwp;
595         struct proc *p = lp->lwp_proc;
596         int dowake = 0;
597
598         /*
599          * lwp_exit() may be called without setting LWP_MP_WEXIT, so
600          * make sure it is set here.
601          */
602         ASSERT_LWKT_TOKEN_HELD(&p->p_token);
603         atomic_set_int(&lp->lwp_mpflags, LWP_MP_WEXIT);
604
605         /*
606          * Clean up any virtualization
607          */
608         if (lp->lwp_vkernel)
609                 vkernel_lwp_exit(lp);
610
611         /*
612          * Clean up select/poll support
613          */
614         kqueue_terminate(&lp->lwp_kqueue);
615
616         /*
617          * Clean up any syscall-cached ucred
618          */
619         if (td->td_ucred) {
620                 crfree(td->td_ucred);
621                 td->td_ucred = NULL;
622         }
623
624         /*
625          * Nobody actually wakes us when the lock
626          * count reaches zero, so just wait one tick.
627          */
628         while (lp->lwp_lock > 0)
629                 tsleep(lp, 0, "lwpexit", 1);
630
631         /* Hand down resource usage to our proc */
632         ruadd(&p->p_ru, &lp->lwp_ru);
633
634         /*
635          * If we don't hold the process until the LWP is reaped wait*()
636          * may try to dispose of its vmspace before all the LWPs have
637          * actually terminated.
638          */
639         PHOLD(p);
640
641         /*
642          * Do any remaining work that might block on us.  We should be
643          * coded such that further blocking is ok after decrementing
644          * p_nthreads but don't take the chance.
645          */
646         dsched_exit_thread(td);
647         biosched_done(curthread);
648
649         /*
650          * We have to use the reaper for all the LWPs except the one doing
651          * the master exit.  The LWP doing the master exit can just be
652          * left on p_lwps and the process reaper will deal with it
653          * synchronously, which is much faster.
654          *
655          * Wakeup anyone waiting on p_nthreads to drop to 1 or 0.
656          *
657          * The process is left held until the reaper calls lwp_dispose() on
658          * the lp (after calling lwp_wait()).
659          */
660         if (masterexit == 0) {
661                 lwp_rb_tree_RB_REMOVE(&p->p_lwp_tree, lp);
662                 --p->p_nthreads;
663                 if (p->p_nthreads <= 1)
664                         dowake = 1;
665                 lwkt_gettoken(&deadlwp_token);
666                 LIST_INSERT_HEAD(&deadlwp_list[mycpuid], lp, u.lwp_reap_entry);
667                 taskqueue_enqueue(taskqueue_thread[mycpuid],
668                                   deadlwp_task[mycpuid]);
669                 lwkt_reltoken(&deadlwp_token);
670         } else {
671                 --p->p_nthreads;
672                 if (p->p_nthreads <= 1)
673                         dowake = 1;
674         }
675
676         /*
677          * Release p_token.  Issue the wakeup() on p_nthreads if necessary,
678          * as late as possible to give us a chance to actually deschedule and
679          * switch away before another cpu core hits reaplwp().
680          */
681         lwkt_reltoken(&p->p_token);
682         if (dowake)
683                 wakeup(&p->p_nthreads);
684         cpu_lwp_exit();
685 }
686
687 /*
688  * Wait until a lwp is completely dead.  The final interlock in this drama
689  * is when TDF_EXITING is set in cpu_thread_exit() just before the final
690  * switchout.
691  *
692  * At the point TDF_EXITING is set a complete exit is accomplished when
693  * TDF_RUNNING and TDF_PREEMPT_LOCK are both clear.
694  *
695  * Returns non-zero on success, and zero if the caller needs to retry
696  * the lwp_wait().
697  */
698 static int
699 lwp_wait(struct lwp *lp)
700 {
701         struct thread *td = lp->lwp_thread;;
702
703         KKASSERT(lwkt_preempted_proc() != lp);
704
705         /*
706          * Wait until the lp has entered its low level exit and wait
707          * until other cores with refs on the lp (e.g. for ps or signaling)
708          * release them.
709          */
710         if (lp->lwp_lock > 0) {
711                 tsleep(lp, 0, "lwpwait1", 1);
712                 return(0);
713         }
714
715         /*
716          * Wait until the thread is no longer references and no longer
717          * runnable or preempted (i.e. finishes its low level exit).
718          */
719         if (td->td_refs) {
720                 tsleep(td, 0, "lwpwait2", 1);
721                 return(0);
722         }
723
724         /*
725          * The lwp's thread may still be in the middle
726          * of switching away, we can't rip its stack out from
727          * under it until TDF_EXITING is set and both
728          * TDF_RUNNING and TDF_PREEMPT_LOCK are clear.
729          * TDF_PREEMPT_LOCK must be checked because TDF_RUNNING
730          * will be cleared temporarily if a thread gets
731          * preempted.
732          *
733          * YYY no wakeup occurs, so we simply return failure
734          * and let the caller deal with sleeping and calling
735          * us again.
736          */
737         if ((td->td_flags & (TDF_RUNNING |
738                              TDF_PREEMPT_LOCK |
739                              TDF_EXITING)) != TDF_EXITING) {
740                 tsleep(lp, 0, "lwpwait2", 1);
741                 return (0);
742         }
743         KASSERT((td->td_flags & (TDF_RUNQ|TDF_TSLEEPQ)) == 0,
744                 ("lwp_wait: td %p (%s) still on run or sleep queue",
745                 td, td->td_comm));
746         return (1);
747 }
748
749 /*
750  * Release the resources associated with a lwp.
751  * The lwp must be completely dead.
752  */
753 void
754 lwp_dispose(struct lwp *lp)
755 {
756         struct thread *td = lp->lwp_thread;;
757
758         KKASSERT(lwkt_preempted_proc() != lp);
759         KKASSERT(td->td_refs == 0);
760         KKASSERT((td->td_flags & (TDF_RUNNING |
761                                   TDF_PREEMPT_LOCK |
762                                   TDF_EXITING)) == TDF_EXITING);
763
764         PRELE(lp->lwp_proc);
765         lp->lwp_proc = NULL;
766         if (td != NULL) {
767                 td->td_proc = NULL;
768                 td->td_lwp = NULL;
769                 lp->lwp_thread = NULL;
770                 lwkt_free_thread(td);
771         }
772         kfree(lp, M_LWP);
773 }
774
775 /*
776  * MPSAFE
777  */
778 int
779 sys_wait4(struct wait_args *uap)
780 {
781         struct rusage rusage;
782         int error, status;
783
784         error = kern_wait(uap->pid, (uap->status ? &status : NULL),
785                           uap->options, (uap->rusage ? &rusage : NULL),
786                           &uap->sysmsg_result);
787
788         if (error == 0 && uap->status)
789                 error = copyout(&status, uap->status, sizeof(*uap->status));
790         if (error == 0 && uap->rusage)
791                 error = copyout(&rusage, uap->rusage, sizeof(*uap->rusage));
792         return (error);
793 }
794
795 /*
796  * wait1()
797  *
798  * wait_args(int pid, int *status, int options, struct rusage *rusage)
799  *
800  * MPALMOSTSAFE
801  */
802 int
803 kern_wait(pid_t pid, int *status, int options, struct rusage *rusage, int *res)
804 {
805         struct thread *td = curthread;
806         struct lwp *lp;
807         struct proc *q = td->td_proc;
808         struct proc *p, *t;
809         struct pargs *pa;
810         struct sigacts *ps;
811         int nfound, error;
812
813         if (pid == 0)
814                 pid = -q->p_pgid;
815         if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
816                 return (EINVAL);
817
818         lwkt_gettoken(&q->p_token);
819 loop:
820         /*
821          * All sorts of things can change due to blocking so we have to loop
822          * all the way back up here.
823          *
824          * The problem is that if a process group is stopped and the parent
825          * is doing a wait*(..., WUNTRACED, ...), it will see the STOP
826          * of the child and then stop itself when it tries to return from the
827          * system call.  When the process group is resumed the parent will
828          * then get the STOP status even though the child has now resumed
829          * (a followup wait*() will get the CONT status).
830          *
831          * Previously the CONT would overwrite the STOP because the tstop
832          * was handled within tsleep(), and the parent would only see
833          * the CONT when both are stopped and continued together.  This little
834          * two-line hack restores this effect.
835          */
836         while (q->p_stat == SSTOP)
837             tstop();
838
839         nfound = 0;
840
841         /*
842          * Loop on children.
843          *
844          * NOTE: We don't want to break q's p_token in the loop for the
845          *       case where no children are found or we risk breaking the
846          *       interlock between child and parent.
847          */
848         LIST_FOREACH(p, &q->p_children, p_sibling) {
849                 if (pid != WAIT_ANY &&
850                     p->p_pid != pid && p->p_pgid != -pid) {
851                         continue;
852                 }
853
854                 /*
855                  * This special case handles a kthread spawned by linux_clone
856                  * (see linux_misc.c).  The linux_wait4 and linux_waitpid 
857                  * functions need to be able to distinguish between waiting
858                  * on a process and waiting on a thread.  It is a thread if
859                  * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
860                  * signifies we want to wait for threads and not processes.
861                  */
862                 if ((p->p_sigparent != SIGCHLD) ^ 
863                     ((options & WLINUXCLONE) != 0)) {
864                         continue;
865                 }
866
867                 nfound++;
868                 if (p->p_stat == SZOMB) {
869                         /*
870                          * We may go into SZOMB with threads still present.
871                          * We must wait for them to exit before we can reap
872                          * the master thread, otherwise we may race reaping
873                          * non-master threads.
874                          */
875                         lwkt_gettoken(&p->p_token);
876                         while (p->p_nthreads > 0) {
877                                 tsleep(&p->p_nthreads, 0, "lwpzomb", hz);
878                         }
879
880                         /*
881                          * Reap any LWPs left in p->p_lwps.  This is usually
882                          * just the last LWP.  This must be done before
883                          * we loop on p_lock since the lwps hold a ref on
884                          * it as a vmspace interlock.
885                          *
886                          * Once that is accomplished p_nthreads had better
887                          * be zero.
888                          */
889                         while ((lp = RB_ROOT(&p->p_lwp_tree)) != NULL) {
890                                 lwp_rb_tree_RB_REMOVE(&p->p_lwp_tree, lp);
891                                 reaplwp(lp);
892                         }
893                         KKASSERT(p->p_nthreads == 0);
894
895                         /*
896                          * Don't do anything really bad until all references
897                          * to the process go away.  This may include other
898                          * LWPs which are still in the process of being
899                          * reaped.  We can't just pull the rug out from under
900                          * them because they may still be using the VM space.
901                          *
902                          * Certain kernel facilities such as /proc will also
903                          * put a hold on the process for short periods of
904                          * time.
905                          */
906                         while (p->p_lock)
907                                 tsleep(p, 0, "reap3", hz);
908
909                         /* Take care of our return values. */
910                         *res = p->p_pid;
911                         p->p_usched->heuristic_exiting(td->td_lwp, p);
912
913                         if (status)
914                                 *status = p->p_xstat;
915                         if (rusage)
916                                 *rusage = p->p_ru;
917                         /*
918                          * If we got the child via a ptrace 'attach',
919                          * we need to give it back to the old parent.
920                          */
921                         if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
922                                 p->p_oppid = 0;
923                                 proc_reparent(p, t);
924                                 ksignal(t, SIGCHLD);
925                                 wakeup((caddr_t)t);
926                                 error = 0;
927                                 PRELE(t);
928                                 lwkt_reltoken(&p->p_token);
929                                 goto done;
930                         }
931
932                         /*
933                          * Unlink the proc from its process group so that
934                          * the following operations won't lead to an
935                          * inconsistent state for processes running down
936                          * the zombie list.
937                          */
938                         proc_remove_zombie(p);
939                         lwkt_reltoken(&p->p_token);
940                         leavepgrp(p);
941
942                         p->p_xstat = 0;
943                         ruadd(&q->p_cru, &p->p_ru);
944
945                         /*
946                          * Decrement the count of procs running with this uid.
947                          */
948                         chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
949
950                         /*
951                          * Free up credentials.
952                          */
953                         crfree(p->p_ucred);
954                         p->p_ucred = NULL;
955
956                         /*
957                          * Remove unused arguments
958                          */
959                         pa = p->p_args;
960                         p->p_args = NULL;
961                         if (pa && refcount_release(&pa->ar_ref)) {
962                                 kfree(pa, M_PARGS);
963                                 pa = NULL;
964                         }
965
966                         ps = p->p_sigacts;
967                         p->p_sigacts = NULL;
968                         if (ps && refcount_release(&ps->ps_refcnt)) {
969                                 kfree(ps, M_SUBPROC);
970                                 ps = NULL;
971                         }
972
973                         /*
974                          * Our exitingcount was incremented when the process
975                          * became a zombie, now that the process has been
976                          * removed from (almost) all lists we should be able
977                          * to safely destroy its vmspace.  Wait for any current
978                          * holders to go away (so the vmspace remains stable),
979                          * then scrap it.
980                          */
981                         while (p->p_lock)
982                                 tsleep(p, 0, "reap4", hz);
983                         vmspace_exitfree(p);
984                         while (p->p_lock)
985                                 tsleep(p, 0, "reap5", hz);
986
987                         kfree(p, M_PROC);
988                         atomic_add_int(&nprocs, -1);
989                         error = 0;
990                         goto done;
991                 }
992                 if (p->p_stat == SSTOP && (p->p_flags & P_WAITED) == 0 &&
993                     ((p->p_flags & P_TRACED) || (options & WUNTRACED))) {
994                         lwkt_gettoken(&p->p_token);
995                         p->p_flags |= P_WAITED;
996
997                         *res = p->p_pid;
998                         p->p_usched->heuristic_exiting(td->td_lwp, p);
999                         if (status)
1000                                 *status = W_STOPCODE(p->p_xstat);
1001                         /* Zero rusage so we get something consistent. */
1002                         if (rusage)
1003                                 bzero(rusage, sizeof(rusage));
1004                         error = 0;
1005                         lwkt_reltoken(&p->p_token);
1006                         goto done;
1007                 }
1008                 if ((options & WCONTINUED) && (p->p_flags & P_CONTINUED)) {
1009                         lwkt_gettoken(&p->p_token);
1010                         *res = p->p_pid;
1011                         p->p_usched->heuristic_exiting(td->td_lwp, p);
1012                         p->p_flags &= ~P_CONTINUED;
1013
1014                         if (status)
1015                                 *status = SIGCONT;
1016                         error = 0;
1017                         lwkt_reltoken(&p->p_token);
1018                         goto done;
1019                 }
1020         }
1021         if (nfound == 0) {
1022                 error = ECHILD;
1023                 goto done;
1024         }
1025         if (options & WNOHANG) {
1026                 *res = 0;
1027                 error = 0;
1028                 goto done;
1029         }
1030
1031         /*
1032          * Wait for signal - interlocked using q->p_token.
1033          */
1034         error = tsleep(q, PCATCH, "wait", 0);
1035         if (error) {
1036 done:
1037                 lwkt_reltoken(&q->p_token);
1038                 return (error);
1039         }
1040         goto loop;
1041 }
1042
1043 /*
1044  * Make process 'parent' the new parent of process 'child'.
1045  *
1046  * p_children/p_sibling requires the parent's token, and
1047  * changing pptr requires the child's token, so we have to
1048  * get three tokens to do this operation.
1049  */
1050 void
1051 proc_reparent(struct proc *child, struct proc *parent)
1052 {
1053         struct proc *opp = child->p_pptr;
1054
1055         if (opp == parent)
1056                 return;
1057         PHOLD(opp);
1058         PHOLD(parent);
1059         lwkt_gettoken(&opp->p_token);
1060         lwkt_gettoken(&child->p_token);
1061         lwkt_gettoken(&parent->p_token);
1062         KKASSERT(child->p_pptr == opp);
1063         LIST_REMOVE(child, p_sibling);
1064         LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1065         child->p_pptr = parent;
1066         lwkt_reltoken(&parent->p_token);
1067         lwkt_reltoken(&child->p_token);
1068         lwkt_reltoken(&opp->p_token);
1069         PRELE(parent);
1070         PRELE(opp);
1071 }
1072
1073 /*
1074  * The next two functions are to handle adding/deleting items on the
1075  * exit callout list
1076  * 
1077  * at_exit():
1078  * Take the arguments given and put them onto the exit callout list,
1079  * However first make sure that it's not already there.
1080  * returns 0 on success.
1081  */
1082
1083 int
1084 at_exit(exitlist_fn function)
1085 {
1086         struct exitlist *ep;
1087
1088 #ifdef INVARIANTS
1089         /* Be noisy if the programmer has lost track of things */
1090         if (rm_at_exit(function)) 
1091                 kprintf("WARNING: exit callout entry (%p) already present\n",
1092                     function);
1093 #endif
1094         ep = kmalloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
1095         if (ep == NULL)
1096                 return (ENOMEM);
1097         ep->function = function;
1098         TAILQ_INSERT_TAIL(&exit_list, ep, next);
1099         return (0);
1100 }
1101
1102 /*
1103  * Scan the exit callout list for the given item and remove it.
1104  * Returns the number of items removed (0 or 1)
1105  */
1106 int
1107 rm_at_exit(exitlist_fn function)
1108 {
1109         struct exitlist *ep;
1110
1111         TAILQ_FOREACH(ep, &exit_list, next) {
1112                 if (ep->function == function) {
1113                         TAILQ_REMOVE(&exit_list, ep, next);
1114                         kfree(ep, M_ATEXIT);
1115                         return(1);
1116                 }
1117         }       
1118         return (0);
1119 }
1120
1121 /*
1122  * LWP reaper related code.
1123  */
1124 static void
1125 reaplwps(void *context, int dummy)
1126 {
1127         struct lwplist *lwplist = context;
1128         struct lwp *lp;
1129
1130         lwkt_gettoken(&deadlwp_token);
1131         while ((lp = LIST_FIRST(lwplist))) {
1132                 LIST_REMOVE(lp, u.lwp_reap_entry);
1133                 reaplwp(lp);
1134         }
1135         lwkt_reltoken(&deadlwp_token);
1136 }
1137
1138 static void
1139 reaplwp(struct lwp *lp)
1140 {
1141         while (lwp_wait(lp) == 0)
1142                 ;
1143         lwp_dispose(lp);
1144 }
1145
1146 static void
1147 deadlwp_init(void)
1148 {
1149         int cpu;
1150
1151         for (cpu = 0; cpu < ncpus; cpu++) {
1152                 LIST_INIT(&deadlwp_list[cpu]);
1153                 deadlwp_task[cpu] = kmalloc(sizeof(*deadlwp_task[cpu]),
1154                                             M_DEVBUF, M_WAITOK);
1155                 TASK_INIT(deadlwp_task[cpu], 0, reaplwps, &deadlwp_list[cpu]);
1156         }
1157 }
1158
1159 SYSINIT(deadlwpinit, SI_SUB_CONFIGURE, SI_ORDER_ANY, deadlwp_init, NULL);