xref: /openbsd-src/sys/kern/kern_exit.c (revision 26a45e40c64199e50627b576f136ec38eef723cd)
1 /*	$OpenBSD: kern_exit.c,v 1.47 2003/08/03 19:25:49 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(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(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(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(p->p_pptr);
261 
262 	/*
263 	 * Notify procfs debugger
264 	 */
265 	if (p->p_flag & P_FSTRACE)
266 		wakeup(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 	 * If emulation has process exit hook, call it now.
289 	 */
290 	if (p->p_emul->e_proc_exit)
291 		(*p->p_emul->e_proc_exit)(p);
292 
293 	/*
294 	 * Finally, call machine-dependent code to switch to a new
295 	 * context (possibly the idle context).  Once we are no longer
296 	 * using the dead process's vmspace and stack, exit2() will be
297 	 * called to schedule those resources to be released by the
298 	 * reaper thread.
299 	 *
300 	 * Note that cpu_exit() will end with a call equivalent to
301 	 * cpu_switch(), finishing our execution (pun intended).
302 	 */
303 	cpu_exit(p);
304 }
305 
306 /*
307  * We are called from cpu_exit() once it is safe to schedule the
308  * dead process's resources to be freed.
309  *
310  * NOTE: One must be careful with locking in this routine.  It's
311  * called from a critical section in machine-dependent code, so
312  * we should refrain from changing any interrupt state.
313  *
314  * We lock the deadproc list (a spin lock), place the proc on that
315  * list (using the p_hash member), and wake up the reaper.
316  */
317 void
318 exit2(p)
319 	struct proc *p;
320 {
321 
322 	simple_lock(&deadproc_slock);
323 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
324 	simple_unlock(&deadproc_slock);
325 
326 	wakeup(&deadproc);
327 }
328 
329 /*
330  * Process reaper.  This is run by a kernel thread to free the resources
331  * of a dead process.  Once the resources are free, the process becomes
332  * a zombie, and the parent is allowed to read the undead's status.
333  */
334 void
335 reaper(void)
336 {
337 	struct proc *p;
338 
339 	for (;;) {
340 		simple_lock(&deadproc_slock);
341 		p = LIST_FIRST(&deadproc);
342 		if (p == NULL) {
343 			/* No work for us; go to sleep until someone exits. */
344 			simple_unlock(&deadproc_slock);
345 			(void) tsleep(&deadproc, PVM, "reaper", 0);
346 			continue;
347 		}
348 
349 		/* Remove us from the deadproc list. */
350 		LIST_REMOVE(p, p_hash);
351 		simple_unlock(&deadproc_slock);
352 
353 		/*
354 		 * Give machine-dependent code a chance to free any
355 		 * resources it couldn't free while still running on
356 		 * that process's context.  This must be done before
357 		 * uvm_exit(), in case these resources are in the PCB.
358 		 */
359 		cpu_wait(p);
360 
361 		/*
362 		 * Free the VM resources we're still holding on to.
363 		 * We must do this from a valid thread because doing
364 		 * so may block.
365 		 */
366 		uvm_exit(p);
367 
368 		/* Process is now a true zombie. */
369 		if ((p->p_flag & P_NOZOMBIE) == 0) {
370 			p->p_stat = SZOMB;
371 
372 			/* Wake up the parent so it can get exit status. */
373 			psignal(p->p_pptr, SIGCHLD);
374 			wakeup(p->p_pptr);
375 		} else {
376 			/* Noone will wait for us. Just zap the process now */
377 			proc_zap(p);
378 		}
379 	}
380 }
381 
382 int
383 sys_wait4(q, v, retval)
384 	register struct proc *q;
385 	void *v;
386 	register_t *retval;
387 {
388 	register struct sys_wait4_args /* {
389 		syscallarg(int) pid;
390 		syscallarg(int *) status;
391 		syscallarg(int) options;
392 		syscallarg(struct rusage *) rusage;
393 	} */ *uap = v;
394 	register int nfound;
395 	register struct proc *p, *t;
396 	int status, error;
397 
398 	if (SCARG(uap, pid) == 0)
399 		SCARG(uap, pid) = -q->p_pgid;
400 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG|WCONTINUED))
401 		return (EINVAL);
402 
403 loop:
404 	nfound = 0;
405 	for (p = q->p_children.lh_first; p != 0; p = p->p_sibling.le_next) {
406 		if ((p->p_flag & P_NOZOMBIE) ||
407 		    (SCARG(uap, pid) != WAIT_ANY &&
408 		    p->p_pid != SCARG(uap, pid) &&
409 		    p->p_pgid != -SCARG(uap, pid)))
410 			continue;
411 
412 		/*
413 		 * Wait for processes with p_exitsig != SIGCHLD processes only
414 		 * if WALTSIG is set; wait for processes with pexitsig ==
415 		 * SIGCHLD only if WALTSIG is clear.
416 		 */
417 		if ((SCARG(uap, options) & WALTSIG) ?
418 		    (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD))
419 			continue;
420 
421 		nfound++;
422 		if (p->p_stat == SZOMB) {
423 			retval[0] = p->p_pid;
424 
425 			if (SCARG(uap, status)) {
426 				status = p->p_xstat;	/* convert to int */
427 				error = copyout(&status,
428 				    SCARG(uap, status), sizeof(status));
429 				if (error)
430 					return (error);
431 			}
432 			if (SCARG(uap, rusage) &&
433 			    (error = copyout(p->p_ru,
434 			    SCARG(uap, rusage), 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(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(&status, SCARG(uap, status),
466 				    sizeof(status));
467 			} else
468 				error = 0;
469 			return (error);
470 		}
471 		if ((SCARG(uap, options) & WCONTINUED) && (p->p_flag & P_CONTINUED)) {
472 			p->p_flag &= ~P_CONTINUED;
473 			retval[0] = p->p_pid;
474 
475 			if (SCARG(uap, status)) {
476 				status = _WCONTINUED;
477 				error = copyout(&status, SCARG(uap, status),
478 				    sizeof(status));
479 			} else
480 				error = 0;
481 			return (error);
482 		}
483 	}
484 	if (nfound == 0)
485 		return (ECHILD);
486 	if (SCARG(uap, options) & WNOHANG) {
487 		retval[0] = 0;
488 		return (0);
489 	}
490 	if ((error = tsleep(q, PWAIT | PCATCH, "wait", 0)) != 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 	if (parent == initproc)
508 		child->p_exitsig = SIGCHLD;
509 
510 	LIST_REMOVE(child, p_sibling);
511 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
512 	child->p_pptr = parent;
513 }
514 
515 void
516 proc_zap(struct proc *p)
517 {
518 	pool_put(&rusage_pool, p->p_ru);
519 
520 	/*
521 	 * Finally finished with old proc entry.
522 	 * Unlink it from its process group and free it.
523 	 */
524 	leavepgrp(p);
525 	LIST_REMOVE(p, p_list);	/* off zombproc */
526 	LIST_REMOVE(p, p_sibling);
527 
528 	/*
529 	 * Decrement the count of procs running with this uid.
530 	 */
531 	(void)chgproccnt(p->p_cred->p_ruid, -1);
532 
533 	/*
534 	 * Free up credentials.
535 	 */
536 	if (--p->p_cred->p_refcnt == 0) {
537 		crfree(p->p_cred->pc_ucred);
538 		pool_put(&pcred_pool, p->p_cred);
539 	}
540 
541 	/*
542 	 * Release reference to text vnode
543 	 */
544 	if (p->p_textvp)
545 		vrele(p->p_textvp);
546 
547 	pool_put(&proc_pool, p);
548 	nprocs--;
549 }
550 
551