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