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