xref: /openbsd-src/sys/kern/kern_exit.c (revision 29295d1c5caf158d3a732746704292e9a80a32d2)
1 /*	$OpenBSD: kern_exit.c,v 1.44 2003/06/02 23:28:05 millert Exp $	*/
2 /*	$NetBSD: kern_exit.c,v 1.39 1996/04/22 01:38:25 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/ioctl.h>
43 #include <sys/proc.h>
44 #include <sys/tty.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #include <sys/kernel.h>
48 #include <sys/proc.h>
49 #include <sys/buf.h>
50 #include <sys/wait.h>
51 #include <sys/file.h>
52 #include <sys/vnode.h>
53 #include <sys/syslog.h>
54 #include <sys/malloc.h>
55 #include <sys/resourcevar.h>
56 #include <sys/ptrace.h>
57 #include <sys/acct.h>
58 #include <sys/filedesc.h>
59 #include <sys/signalvar.h>
60 #include <sys/sched.h>
61 #include <sys/ktrace.h>
62 #include <sys/pool.h>
63 #ifdef SYSVSHM
64 #include <sys/shm.h>
65 #endif
66 #ifdef SYSVSEM
67 #include <sys/sem.h>
68 #endif
69 
70 #include "systrace.h"
71 #include <dev/systrace.h>
72 
73 #include <sys/mount.h>
74 #include <sys/syscallargs.h>
75 
76 #include <machine/cpu.h>
77 
78 #include <uvm/uvm_extern.h>
79 
80 /*
81  * exit --
82  *	Death of process.
83  */
84 int
85 sys_exit(p, v, retval)
86 	struct proc *p;
87 	void *v;
88 	register_t *retval;
89 {
90 	struct sys_exit_args /* {
91 		syscallarg(int) rval;
92 	} */ *uap = v;
93 
94 	exit1(p, W_EXITCODE(SCARG(uap, rval), 0));
95 	/* NOTREACHED */
96 	return (0);
97 }
98 
99 /*
100  * Exit: deallocate address space and other resources, change proc state
101  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
102  * status and rusage for wait().  Check for child processes and orphan them.
103  */
104 void
105 exit1(p, rv)
106 	struct proc *p;
107 	int rv;
108 {
109 	struct proc *q, *nq;
110 
111 	if (p->p_pid == 1)
112 		panic("init died (signal %d, exit %d)",
113 		    WTERMSIG(rv), WEXITSTATUS(rv));
114 
115 	if (p->p_flag & P_PROFIL)
116 		stopprofclock(p);
117 	p->p_ru = pool_get(&rusage_pool, PR_WAITOK);
118 	/*
119 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
120 	 * wake up the parent early to avoid deadlock.
121 	 */
122 	p->p_flag |= P_WEXIT;
123 	p->p_flag &= ~P_TRACED;
124 	if (p->p_flag & P_PPWAIT) {
125 		p->p_flag &= ~P_PPWAIT;
126 		wakeup((caddr_t)p->p_pptr);
127 	}
128 	p->p_sigignore = ~0;
129 	p->p_siglist = 0;
130 	timeout_del(&p->p_realit_to);
131 
132 	/*
133 	 * Close open files and release open-file table.
134 	 * This may block!
135 	 */
136 	fdfree(p);
137 
138 #ifdef SYSVSEM
139 	semexit(p);
140 #endif
141 	if (SESS_LEADER(p)) {
142 		register struct session *sp = p->p_session;
143 
144 		if (sp->s_ttyvp) {
145 			/*
146 			 * Controlling process.
147 			 * Signal foreground pgrp,
148 			 * drain controlling terminal
149 			 * and revoke access to controlling terminal.
150 			 */
151 			if (sp->s_ttyp->t_session == sp) {
152 				if (sp->s_ttyp->t_pgrp)
153 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
154 				(void) ttywait(sp->s_ttyp);
155 				/*
156 				 * The tty could have been revoked
157 				 * if we blocked.
158 				 */
159 				if (sp->s_ttyvp)
160 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
161 			}
162 			if (sp->s_ttyvp)
163 				vrele(sp->s_ttyvp);
164 			sp->s_ttyvp = NULL;
165 			/*
166 			 * s_ttyp is not zero'd; we use this to indicate
167 			 * that the session once had a controlling terminal.
168 			 * (for logging and informational purposes)
169 			 */
170 		}
171 		sp->s_leader = NULL;
172 	}
173 	fixjobc(p, p->p_pgrp, 0);
174 	(void)acct_process(p);
175 #ifdef KTRACE
176 	/*
177 	 * release trace file
178 	 */
179 	p->p_traceflag = 0;	/* don't trace the vrele() */
180 	if (p->p_tracep)
181 		ktrsettracevnode(p, NULL);
182 #endif
183 #if NSYSTRACE > 0
184 	if (ISSET(p->p_flag, P_SYSTRACE))
185 		systrace_exit(p);
186 #endif
187 	/*
188 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
189 	 */
190 	p->p_stat = SDEAD;
191 
192         /*
193          * Remove proc from pidhash chain so looking it up won't
194          * work.  Move it from allproc to zombproc, but do not yet
195          * wake up the reaper.  We will put the proc on the
196          * deadproc list later (using the p_hash member), and
197          * wake up the reaper when we do.
198          */
199 	LIST_REMOVE(p, p_hash);
200 	LIST_REMOVE(p, p_list);
201 	LIST_INSERT_HEAD(&zombproc, p, p_list);
202 
203 	/*
204 	 * Give orphaned children to init(8).
205 	 */
206 	q = p->p_children.lh_first;
207 	if (q)		/* only need this if any child is S_ZOMB */
208 		wakeup((caddr_t)initproc);
209 	for (; q != 0; q = nq) {
210 		nq = q->p_sibling.le_next;
211 		proc_reparent(q, initproc);
212 		/*
213 		 * Traced processes are killed
214 		 * since their existence means someone is screwing up.
215 		 */
216 		if (q->p_flag & P_TRACED) {
217 			q->p_flag &= ~P_TRACED;
218 			psignal(q, SIGKILL);
219 		}
220 	}
221 
222 	/*
223 	 * Save exit status and final rusage info, adding in child rusage
224 	 * info and self times.
225 	 */
226 	p->p_xstat = rv;
227 	*p->p_ru = p->p_stats->p_ru;
228 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
229 	ruadd(p->p_ru, &p->p_stats->p_cru);
230 
231 	/*
232 	 * clear %cpu usage during swap
233 	 */
234 	p->p_pctcpu = 0;
235 
236 	/*
237 	 * notify interested parties of our demise.
238 	 */
239 	KNOTE(&p->p_klist, NOTE_EXIT);
240 
241 	/*
242 	 * Notify parent that we're gone.  If we have P_NOZOMBIE or parent has
243 	 * the P_NOCLDWAIT flag set, notify process 1 instead (and hope it
244 	 * will handle this situation).
245 	 */
246 	if ((p->p_flag & P_NOZOMBIE) || (p->p_pptr->p_flag & P_NOCLDWAIT)) {
247 		struct proc *pp = p->p_pptr;
248 		proc_reparent(p, initproc);
249 		/*
250 		 * If this was the last child of our parent, notify
251 		 * parent, so in case he was wait(2)ing, he will
252 		 * continue.
253 		 */
254 		if (pp->p_children.lh_first == NULL)
255 			wakeup((caddr_t)pp);
256 	}
257 
258 	if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
259 		psignal(p->p_pptr, P_EXITSIG(p));
260 	wakeup((caddr_t)p->p_pptr);
261 
262 	/*
263 	 * Notify procfs debugger
264 	 */
265 	if (p->p_flag & P_FSTRACE)
266 		wakeup((caddr_t)p);
267 
268 	/*
269 	 * Release the process's signal state.
270 	 */
271 	sigactsfree(p);
272 
273 	/*
274 	 * Clear curproc after we've done all operations
275 	 * that could block, and before tearing down the rest
276 	 * of the process state that might be used from clock, etc.
277 	 * Also, can't clear curproc while we're still runnable,
278 	 * as we're not on a run queue (we are current, just not
279 	 * a proper proc any longer!).
280 	 *
281 	 * Other substructures are freed from wait().
282 	 */
283 	curproc = NULL;
284 	limfree(p->p_limit);
285 	p->p_limit = NULL;
286 
287 	/*
288 	 * Finally, call machine-dependent code to switch to a new
289 	 * context (possibly the idle context).  Once we are no longer
290 	 * using the dead process's vmspace and stack, exit2() will be
291 	 * called to schedule those resources to be released by the
292 	 * reaper thread.
293 	 *
294 	 * Note that cpu_exit() will end with a call equivalent to
295 	 * cpu_switch(), finishing our execution (pun intended).
296 	 */
297 	cpu_exit(p);
298 }
299 
300 /*
301  * We are called from cpu_exit() once it is safe to schedule the
302  * dead process's resources to be freed.
303  *
304  * NOTE: One must be careful with locking in this routine.  It's
305  * called from a critical section in machine-dependent code, so
306  * we should refrain from changing any interrupt state.
307  *
308  * We lock the deadproc list (a spin lock), place the proc on that
309  * list (using the p_hash member), and wake up the reaper.
310  */
311 void
312 exit2(p)
313 	struct proc *p;
314 {
315 
316 	simple_lock(&deadproc_slock);
317 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
318 	simple_unlock(&deadproc_slock);
319 
320 	wakeup(&deadproc);
321 }
322 
323 /*
324  * Process reaper.  This is run by a kernel thread to free the resources
325  * of a dead process.  Once the resources are free, the process becomes
326  * a zombie, and the parent is allowed to read the undead's status.
327  */
328 void
329 reaper(void)
330 {
331 	struct proc *p;
332 
333 	for (;;) {
334 		simple_lock(&deadproc_slock);
335 		p = LIST_FIRST(&deadproc);
336 		if (p == NULL) {
337 			/* No work for us; go to sleep until someone exits. */
338 			simple_unlock(&deadproc_slock);
339 			(void) tsleep(&deadproc, PVM, "reaper", 0);
340 			continue;
341 		}
342 
343 		/* Remove us from the deadproc list. */
344 		LIST_REMOVE(p, p_hash);
345 		simple_unlock(&deadproc_slock);
346 
347 		/*
348 		 * Give machine-dependent code a chance to free any
349 		 * resources it couldn't free while still running on
350 		 * that process's context.  This must be done before
351 		 * uvm_exit(), in case these resources are in the PCB.
352 		 */
353 		cpu_wait(p);
354 
355 		/*
356 		 * Free the VM resources we're still holding on to.
357 		 * We must do this from a valid thread because doing
358 		 * so may block.
359 		 */
360 		uvm_exit(p);
361 
362 		/* Process is now a true zombie. */
363 		if ((p->p_flag & P_NOZOMBIE) == 0) {
364 			p->p_stat = SZOMB;
365 
366 			/* Wake up the parent so it can get exit status. */
367 			psignal(p->p_pptr, SIGCHLD);
368 			wakeup((caddr_t)p->p_pptr);
369 		} else {
370 			/* Noone will wait for us. Just zap the process now */
371 			proc_zap(p);
372 		}
373 	}
374 }
375 
376 int
377 sys_wait4(q, v, retval)
378 	register struct proc *q;
379 	void *v;
380 	register_t *retval;
381 {
382 	register struct sys_wait4_args /* {
383 		syscallarg(int) pid;
384 		syscallarg(int *) status;
385 		syscallarg(int) options;
386 		syscallarg(struct rusage *) rusage;
387 	} */ *uap = v;
388 	register int nfound;
389 	register struct proc *p, *t;
390 	int status, error;
391 
392 	if (SCARG(uap, pid) == 0)
393 		SCARG(uap, pid) = -q->p_pgid;
394 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG))
395 		return (EINVAL);
396 
397 loop:
398 	nfound = 0;
399 	for (p = q->p_children.lh_first; p != 0; p = p->p_sibling.le_next) {
400 		if ((p->p_flag & P_NOZOMBIE) ||
401 		    (SCARG(uap, pid) != WAIT_ANY &&
402 		    p->p_pid != SCARG(uap, pid) &&
403 		    p->p_pgid != -SCARG(uap, pid)))
404 			continue;
405 
406 		/*
407 		 * Wait for processes with p_exitsig != SIGCHLD processes only
408 		 * if WALTSIG is set; wait for processes with pexitsig ==
409 		 * SIGCHLD only if WALTSIG is clear.
410 		 */
411 		if ((SCARG(uap, options) & WALTSIG) ?
412 		    (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD))
413 			continue;
414 
415 		nfound++;
416 		if (p->p_stat == SZOMB) {
417 			retval[0] = p->p_pid;
418 
419 			if (SCARG(uap, status)) {
420 				status = p->p_xstat;	/* convert to int */
421 				error = copyout((caddr_t)&status,
422 						(caddr_t)SCARG(uap, status),
423 						sizeof(status));
424 				if (error)
425 					return (error);
426 			}
427 			if (SCARG(uap, rusage) &&
428 			    (error = copyout((caddr_t)p->p_ru,
429 			    (caddr_t)SCARG(uap, rusage),
430 			    sizeof(struct rusage))))
431 				return (error);
432 
433 			/*
434 			 * If we got the child via a ptrace 'attach',
435 			 * we need to give it back to the old parent.
436 			 */
437 			if (p->p_oppid && (t = pfind(p->p_oppid))) {
438 				p->p_oppid = 0;
439 				proc_reparent(p, t);
440 				if (p->p_exitsig != 0)
441 					psignal(t, P_EXITSIG(p));
442 				wakeup((caddr_t)t);
443 				return (0);
444 			}
445 
446 			scheduler_wait_hook(q, p);
447 			p->p_xstat = 0;
448 			ruadd(&q->p_stats->p_cru, p->p_ru);
449 
450 			proc_zap(p);
451 
452 			return (0);
453 		}
454 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
455 		    (p->p_flag & P_TRACED || SCARG(uap, options) & WUNTRACED)) {
456 			p->p_flag |= P_WAITED;
457 			retval[0] = p->p_pid;
458 
459 			if (SCARG(uap, status)) {
460 				status = W_STOPCODE(p->p_xstat);
461 				error = copyout((caddr_t)&status,
462 				    (caddr_t)SCARG(uap, status),
463 				    sizeof(status));
464 			} else
465 				error = 0;
466 			return (error);
467 		}
468 	}
469 	if (nfound == 0)
470 		return (ECHILD);
471 	if (SCARG(uap, options) & WNOHANG) {
472 		retval[0] = 0;
473 		return (0);
474 	}
475 	if ((error = tsleep((caddr_t)q, PWAIT | PCATCH, "wait", 0)) != 0)
476 		return (error);
477 	goto loop;
478 }
479 
480 /*
481  * make process 'parent' the new parent of process 'child'.
482  */
483 void
484 proc_reparent(child, parent)
485 	register struct proc *child;
486 	register struct proc *parent;
487 {
488 
489 	if (child->p_pptr == parent)
490 		return;
491 
492 	if (parent == initproc)
493 		child->p_exitsig = SIGCHLD;
494 
495 	LIST_REMOVE(child, p_sibling);
496 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
497 	child->p_pptr = parent;
498 }
499 
500 void
501 proc_zap(struct proc *p)
502 {
503 	pool_put(&rusage_pool, p->p_ru);
504 
505 	/*
506 	 * Finally finished with old proc entry.
507 	 * Unlink it from its process group and free it.
508 	 */
509 	leavepgrp(p);
510 	LIST_REMOVE(p, p_list);	/* off zombproc */
511 	LIST_REMOVE(p, p_sibling);
512 
513 	/*
514 	 * Decrement the count of procs running with this uid.
515 	 */
516 	(void)chgproccnt(p->p_cred->p_ruid, -1);
517 
518 	/*
519 	 * Free up credentials.
520 	 */
521 	if (--p->p_cred->p_refcnt == 0) {
522 		crfree(p->p_cred->pc_ucred);
523 		pool_put(&pcred_pool, p->p_cred);
524 	}
525 
526 	/*
527 	 * Release reference to text vnode
528 	 */
529 	if (p->p_textvp)
530 		vrele(p->p_textvp);
531 
532 	pool_put(&proc_pool, p);
533 	nprocs--;
534 }
535 
536