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