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