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