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