kern_exit.c revision 53823
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: head/sys/kern/kern_exit.c 53823 1999-11-28 12:12:14Z bde $
40 */
41
42#include "opt_compat.h"
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/sysproto.h>
48#include <sys/kernel.h>
49#include <sys/malloc.h>
50#include <sys/proc.h>
51#include <sys/pioctl.h>
52#include <sys/tty.h>
53#include <sys/wait.h>
54#include <sys/vnode.h>
55#include <sys/resourcevar.h>
56#include <sys/signalvar.h>
57#include <sys/ptrace.h>
58#include <sys/acct.h>		/* for acct_process() function prototype */
59#include <sys/filedesc.h>
60#include <sys/shm.h>
61#include <sys/sem.h>
62#include <sys/aio.h>
63#include <sys/jail.h>
64
65#include <vm/vm.h>
66#include <vm/vm_param.h>
67#include <sys/lock.h>
68#include <vm/pmap.h>
69#include <vm/vm_map.h>
70#include <vm/vm_zone.h>
71#include <sys/user.h>
72
73/* Required to be non-static for SysVR4 emulator */
74MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
75
76static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
77
78static int wait1 __P((struct proc *, struct wait_args *, int));
79
80/*
81 * callout list for things to do at exit time
82 */
83struct exitlist {
84	exitlist_fn function;
85	TAILQ_ENTRY(exitlist) next;
86};
87
88TAILQ_HEAD(exit_list_head, exitlist);
89static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
90
91/*
92 * exit --
93 *	Death of process.
94 */
95void
96exit(p, uap)
97	struct proc *p;
98	struct rexit_args /* {
99		int	rval;
100	} */ *uap;
101{
102
103	exit1(p, W_EXITCODE(uap->rval, 0));
104	/* NOTREACHED */
105}
106
107/*
108 * Exit: deallocate address space and other resources, change proc state
109 * to zombie, and unlink proc from allproc and parent's lists.  Save exit
110 * status and rusage for wait().  Check for child processes and orphan them.
111 */
112void
113exit1(p, rv)
114	register struct proc *p;
115	int rv;
116{
117	register struct proc *q, *nq;
118	register struct vmspace *vm;
119	struct exitlist *ep;
120
121	if (p->p_pid == 1) {
122		printf("init died (signal %d, exit %d)\n",
123		    WTERMSIG(rv), WEXITSTATUS(rv));
124		panic("Going nowhere without my init!");
125	}
126
127	aio_proc_rundown(p);
128
129	/* are we a task leader? */
130	if(p == p->p_leader) {
131        	struct kill_args killArgs;
132		killArgs.signum = SIGKILL;
133		q = p->p_peers;
134		while(q) {
135			killArgs.pid = q->p_pid;
136			/*
137		         * The interface for kill is better
138			 * than the internal signal
139			 */
140			kill(p, &killArgs);
141			nq = q;
142			q = q->p_peers;
143		}
144		while (p->p_peers)
145		  tsleep((caddr_t)p, PWAIT, "exit1", 0);
146	}
147
148#ifdef PGINPROF
149	vmsizmon();
150#endif
151	STOPEVENT(p, S_EXIT, rv);
152
153	/*
154	 * Check if any loadable modules need anything done at process exit.
155	 * e.g. SYSV IPC stuff
156	 * XXX what if one of these generates an error?
157	 */
158	TAILQ_FOREACH(ep, &exit_list, next)
159		(*ep->function)(p);
160
161	if (p->p_flag & P_PROFIL)
162		stopprofclock(p);
163	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
164		M_ZOMBIE, M_WAITOK);
165	/*
166	 * If parent is waiting for us to exit or exec,
167	 * P_PPWAIT is set; we will wakeup the parent below.
168	 */
169	p->p_flag &= ~(P_TRACED | P_PPWAIT);
170	p->p_flag |= P_WEXIT;
171	SIGEMPTYSET(p->p_siglist);
172	if (timevalisset(&p->p_realtimer.it_value))
173		untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
174
175	/*
176	 * Reset any sigio structures pointing to us as a result of
177	 * F_SETOWN with our pid.
178	 */
179	funsetownlst(&p->p_sigiolst);
180
181	/*
182	 * Close open files and release open-file table.
183	 * This may block!
184	 */
185	fdfree(p);
186
187	if(p->p_leader->p_peers) {
188		q = p->p_leader;
189		while(q->p_peers != p)
190			q = q->p_peers;
191		q->p_peers = p->p_peers;
192		wakeup((caddr_t)p->p_leader);
193	}
194
195	/*
196	 * XXX Shutdown SYSV semaphores
197	 */
198	semexit(p);
199
200	/* The next two chunks should probably be moved to vmspace_exit. */
201	vm = p->p_vmspace;
202	/*
203	 * Release user portion of address space.
204	 * This releases references to vnodes,
205	 * which could cause I/O if the file has been unlinked.
206	 * Need to do this early enough that we can still sleep.
207	 * Can't free the entire vmspace as the kernel stack
208	 * may be mapped within that space also.
209	 */
210	if (vm->vm_refcnt == 1) {
211		if (vm->vm_shm)
212			shmexit(p);
213		pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
214		    VM_MAXUSER_ADDRESS);
215		(void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
216		    VM_MAXUSER_ADDRESS);
217	}
218
219	if (SESS_LEADER(p)) {
220		register struct session *sp = p->p_session;
221
222		if (sp->s_ttyvp) {
223			/*
224			 * Controlling process.
225			 * Signal foreground pgrp,
226			 * drain controlling terminal
227			 * and revoke access to controlling terminal.
228			 */
229			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
230				if (sp->s_ttyp->t_pgrp)
231					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
232				(void) ttywait(sp->s_ttyp);
233				/*
234				 * The tty could have been revoked
235				 * if we blocked.
236				 */
237				if (sp->s_ttyvp)
238					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
239			}
240			if (sp->s_ttyvp)
241				vrele(sp->s_ttyvp);
242			sp->s_ttyvp = NULL;
243			/*
244			 * s_ttyp is not zero'd; we use this to indicate
245			 * that the session once had a controlling terminal.
246			 * (for logging and informational purposes)
247			 */
248		}
249		sp->s_leader = NULL;
250	}
251	fixjobc(p, p->p_pgrp, 0);
252	(void)acct_process(p);
253#ifdef KTRACE
254	/*
255	 * release trace file
256	 */
257	p->p_traceflag = 0;	/* don't trace the vrele() */
258	if (p->p_tracep)
259		vrele(p->p_tracep);
260#endif
261	/*
262	 * Remove proc from allproc queue and pidhash chain.
263	 * Place onto zombproc.  Unlink from parent's child list.
264	 */
265	LIST_REMOVE(p, p_list);
266	LIST_INSERT_HEAD(&zombproc, p, p_list);
267	p->p_stat = SZOMB;
268
269	LIST_REMOVE(p, p_hash);
270
271	q = LIST_FIRST(&p->p_children);
272	if (q)		/* only need this if any child is S_ZOMB */
273		wakeup((caddr_t) initproc);
274	for (; q != 0; q = nq) {
275		nq = LIST_NEXT(q, p_sibling);
276		LIST_REMOVE(q, p_sibling);
277		LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
278		q->p_pptr = initproc;
279		q->p_sigparent = SIGCHLD;
280		/*
281		 * Traced processes are killed
282		 * since their existence means someone is screwing up.
283		 */
284		if (q->p_flag & P_TRACED) {
285			q->p_flag &= ~P_TRACED;
286			psignal(q, SIGKILL);
287		}
288	}
289
290	/*
291	 * Save exit status and final rusage info, adding in child rusage
292	 * info and self times.
293	 */
294	p->p_xstat = rv;
295	*p->p_ru = p->p_stats->p_ru;
296	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
297	ruadd(p->p_ru, &p->p_stats->p_cru);
298
299	/*
300	 * Pretend that an mi_switch() to the next process occurs now.  We
301	 * must set `switchtime' directly since we will call cpu_switch()
302	 * directly.  Set it now so that the rest of the exit time gets
303	 * counted somewhere if possible.
304	 */
305	microuptime(&switchtime);
306	switchticks = ticks;
307
308	/*
309	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
310	 * flag set, notify process 1 instead (and hope it will handle
311	 * this situation).
312	 */
313	if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
314		struct proc *pp = p->p_pptr;
315		proc_reparent(p, initproc);
316		/*
317		 * If this was the last child of our parent, notify
318		 * parent, so in case he was wait(2)ing, he will
319		 * continue.
320		 */
321		if (LIST_EMPTY(&pp->p_children))
322			wakeup((caddr_t)pp);
323	}
324
325	if (p->p_sigparent && p->p_pptr != initproc) {
326	        psignal(p->p_pptr, p->p_sigparent);
327	} else {
328	        psignal(p->p_pptr, SIGCHLD);
329	}
330
331	wakeup((caddr_t)p->p_pptr);
332#if defined(tahoe)
333	/* move this to cpu_exit */
334	p->p_addr->u_pcb.pcb_savacc.faddr = (float *)NULL;
335#endif
336	/*
337	 * Clear curproc after we've done all operations
338	 * that could block, and before tearing down the rest
339	 * of the process state that might be used from clock, etc.
340	 * Also, can't clear curproc while we're still runnable,
341	 * as we're not on a run queue (we are current, just not
342	 * a proper proc any longer!).
343	 *
344	 * Other substructures are freed from wait().
345	 */
346	SET_CURPROC(NULL);
347	if (--p->p_limit->p_refcnt == 0) {
348		FREE(p->p_limit, M_SUBPROC);
349		p->p_limit = NULL;
350	}
351
352	/*
353	 * Finally, call machine-dependent code to release the remaining
354	 * resources including address space, the kernel stack and pcb.
355	 * The address space is released by "vmspace_free(p->p_vmspace)";
356	 * This is machine-dependent, as we may have to change stacks
357	 * or ensure that the current one isn't reallocated before we
358	 * finish.  cpu_exit will end with a call to cpu_switch(), finishing
359	 * our execution (pun intended).
360	 */
361	cpu_exit(p);
362}
363
364#ifdef COMPAT_43
365int
366owait(p, uap)
367	struct proc *p;
368	register struct owait_args /* {
369		int     dummy;
370	} */ *uap;
371{
372	struct wait_args w;
373
374	w.options = 0;
375	w.rusage = NULL;
376	w.pid = WAIT_ANY;
377	w.status = NULL;
378	return (wait1(p, &w, 1));
379}
380#endif /* COMPAT_43 */
381
382int
383wait4(p, uap)
384	struct proc *p;
385	struct wait_args *uap;
386{
387
388	return (wait1(p, uap, 0));
389}
390
391static int
392wait1(q, uap, compat)
393	register struct proc *q;
394	register struct wait_args /* {
395		int pid;
396		int *status;
397		int options;
398		struct rusage *rusage;
399	} */ *uap;
400	int compat;
401{
402	register int nfound;
403	register struct proc *p, *t;
404	int status, error;
405
406	if (uap->pid == 0)
407		uap->pid = -q->p_pgid;
408	if (uap->options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
409		return (EINVAL);
410loop:
411	nfound = 0;
412	LIST_FOREACH(p, &q->p_children, p_sibling) {
413		if (uap->pid != WAIT_ANY &&
414		    p->p_pid != uap->pid && p->p_pgid != -uap->pid)
415			continue;
416
417		/* This special case handles a kthread spawned by linux_clone
418		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid functions
419		 * need to be able to distinguish between waiting on a process and
420		 * waiting on a thread.  It is a thread if p_sigparent is not SIGCHLD,
421		 * and the WLINUXCLONE option signifies we want to wait for threads
422		 * and not processes.
423		 */
424		if ((p->p_sigparent != SIGCHLD) ^ ((uap->options & WLINUXCLONE) != 0))
425			continue;
426
427		nfound++;
428		if (p->p_stat == SZOMB) {
429			/* charge childs scheduling cpu usage to parent */
430			if (curproc->p_pid != 1) {
431				curproc->p_estcpu =
432				    ESTCPULIM(curproc->p_estcpu + p->p_estcpu);
433			}
434
435			q->p_retval[0] = p->p_pid;
436#ifdef COMPAT_43
437			if (compat)
438				q->p_retval[1] = p->p_xstat;
439			else
440#endif
441			if (uap->status) {
442				status = p->p_xstat;	/* convert to int */
443				if ((error = copyout((caddr_t)&status,
444				    (caddr_t)uap->status, sizeof(status))))
445					return (error);
446			}
447			if (uap->rusage && (error = copyout((caddr_t)p->p_ru,
448			    (caddr_t)uap->rusage, sizeof (struct rusage))))
449				return (error);
450			/*
451			 * If we got the child via a ptrace 'attach',
452			 * we need to give it back to the old parent.
453			 */
454			if (p->p_oppid && (t = pfind(p->p_oppid))) {
455				p->p_oppid = 0;
456				proc_reparent(p, t);
457				psignal(t, SIGCHLD);
458				wakeup((caddr_t)t);
459				return (0);
460			}
461			p->p_xstat = 0;
462			ruadd(&q->p_stats->p_cru, p->p_ru);
463			FREE(p->p_ru, M_ZOMBIE);
464			p->p_ru = NULL;
465
466			/*
467			 * Decrement the count of procs running with this uid.
468			 */
469			(void)chgproccnt(p->p_cred->p_ruid, -1);
470
471			/*
472			 * Release reference to text vnode
473			 */
474			if (p->p_textvp)
475				vrele(p->p_textvp);
476
477			/*
478			 * Free up credentials.
479			 */
480			if (--p->p_cred->p_refcnt == 0) {
481				crfree(p->p_ucred);
482				FREE(p->p_cred, M_SUBPROC);
483				p->p_cred = NULL;
484			}
485
486			/*
487			 * Destroy empty prisons
488			 */
489			if (p->p_prison && !--p->p_prison->pr_ref) {
490				if (p->p_prison->pr_linux != NULL)
491					FREE(p->p_prison->pr_linux, M_PRISON);
492				FREE(p->p_prison, M_PRISON);
493			}
494
495			/*
496			 * Remove unused arguments
497			 */
498			if (p->p_args && --p->p_args->ar_ref == 0)
499				FREE(p->p_args, M_PARGS);
500
501			/*
502			 * Finally finished with old proc entry.
503			 * Unlink it from its process group and free it.
504			 */
505			leavepgrp(p);
506			LIST_REMOVE(p, p_list);	/* off zombproc */
507			LIST_REMOVE(p, p_sibling);
508
509			if (--p->p_procsig->ps_refcnt == 0) {
510				if (p->p_sigacts != &p->p_addr->u_sigacts)
511					FREE(p->p_sigacts, M_SUBPROC);
512			        FREE(p->p_procsig, M_SUBPROC);
513				p->p_procsig = NULL;
514			}
515
516			/*
517			 * Give machine-dependent layer a chance
518			 * to free anything that cpu_exit couldn't
519			 * release while still running in process context.
520			 */
521			cpu_wait(p);
522			zfree(proc_zone, p);
523			nprocs--;
524			return (0);
525		}
526		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
527		    (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
528			p->p_flag |= P_WAITED;
529			q->p_retval[0] = p->p_pid;
530#ifdef COMPAT_43
531			if (compat) {
532				q->p_retval[1] = W_STOPCODE(p->p_xstat);
533				error = 0;
534			} else
535#endif
536			if (uap->status) {
537				status = W_STOPCODE(p->p_xstat);
538				error = copyout((caddr_t)&status,
539					(caddr_t)uap->status, sizeof(status));
540			} else
541				error = 0;
542			return (error);
543		}
544	}
545	if (nfound == 0)
546		return (ECHILD);
547	if (uap->options & WNOHANG) {
548		q->p_retval[0] = 0;
549		return (0);
550	}
551	if ((error = tsleep((caddr_t)q, PWAIT | PCATCH, "wait", 0)))
552		return (error);
553	goto loop;
554}
555
556/*
557 * make process 'parent' the new parent of process 'child'.
558 */
559void
560proc_reparent(child, parent)
561	register struct proc *child;
562	register struct proc *parent;
563{
564
565	if (child->p_pptr == parent)
566		return;
567
568	LIST_REMOVE(child, p_sibling);
569	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
570	child->p_pptr = parent;
571}
572
573/*
574 * The next two functions are to handle adding/deleting items on the
575 * exit callout list
576 *
577 * at_exit():
578 * Take the arguments given and put them onto the exit callout list,
579 * However first make sure that it's not already there.
580 * returns 0 on success.
581 */
582
583int
584at_exit(function)
585	exitlist_fn function;
586{
587	struct exitlist *ep;
588
589#ifdef INVARIANTS
590	/* Be noisy if the programmer has lost track of things */
591	if (rm_at_exit(function))
592		printf("WARNING: exit callout entry (%p) already present\n",
593		    function);
594#endif
595	ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
596	if (ep == NULL)
597		return (ENOMEM);
598	ep->function = function;
599	TAILQ_INSERT_TAIL(&exit_list, ep, next);
600	return (0);
601}
602
603/*
604 * Scan the exit callout list for the given item and remove it.
605 * Returns the number of items removed (0 or 1)
606 */
607int
608rm_at_exit(function)
609	exitlist_fn function;
610{
611	struct exitlist *ep;
612
613	TAILQ_FOREACH(ep, &exit_list, next) {
614		if (ep->function == function) {
615			TAILQ_REMOVE(&exit_list, ep, next);
616			free(ep, M_ATEXIT);
617			return(1);
618		}
619	}
620	return (0);
621}
622
623void check_sigacts (void)
624{
625	struct proc *p = curproc;
626	struct sigacts *pss;
627	int s;
628
629	if (p->p_procsig->ps_refcnt == 1 &&
630	    p->p_sigacts != &p->p_addr->u_sigacts) {
631		pss = p->p_sigacts;
632		s = splhigh();
633		p->p_addr->u_sigacts = *pss;
634		p->p_sigacts = &p->p_addr->u_sigacts;
635		splx(s);
636		FREE(pss, M_SUBPROC);
637	}
638}
639
640