xref: /openbsd-src/sys/kern/kern_exit.c (revision c4071fd13883b3f74b90a411bbb39755a785aeaa)
1 /*	$OpenBSD: kern_exit.c,v 1.41 2002/03/14 01:27:04 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. 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 <sys/mount.h>
75 #include <sys/syscallargs.h>
76 
77 #include <machine/cpu.h>
78 
79 #include <uvm/uvm_extern.h>
80 
81 void proc_zap(struct proc *);
82 
83 /*
84  * exit --
85  *	Death of process.
86  */
87 int
88 sys_exit(p, v, retval)
89 	struct proc *p;
90 	void *v;
91 	register_t *retval;
92 {
93 	struct sys_exit_args /* {
94 		syscallarg(int) rval;
95 	} */ *uap = v;
96 
97 	exit1(p, W_EXITCODE(SCARG(uap, rval), 0));
98 	/* NOTREACHED */
99 	return (0);
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 	struct proc *p;
110 	int rv;
111 {
112 	struct proc *q, *nq;
113 	struct vmspace *vm;
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 	/* The next three chunks should probably be moved to vmspace_exit. */
143 	vm = p->p_vmspace;
144 #ifdef SYSVSEM
145 	semexit(p);
146 #endif
147 	/*
148 	 * Release user portion of address space.
149 	 * This releases references to vnodes,
150 	 * which could cause I/O if the file has been unlinked.
151 	 * Need to do this early enough that we can still sleep.
152 	 * Can't free the entire vmspace as the kernel stack
153 	 * may be mapped within that space also.
154 	 */
155 	if (vm->vm_refcnt == 1)
156 		(void) uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
157 		    VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
158 
159 	if (SESS_LEADER(p)) {
160 		register struct session *sp = p->p_session;
161 
162 		if (sp->s_ttyvp) {
163 			/*
164 			 * Controlling process.
165 			 * Signal foreground pgrp,
166 			 * drain controlling terminal
167 			 * and revoke access to controlling terminal.
168 			 */
169 			if (sp->s_ttyp->t_session == sp) {
170 				if (sp->s_ttyp->t_pgrp)
171 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
172 				(void) ttywait(sp->s_ttyp);
173 				/*
174 				 * The tty could have been revoked
175 				 * if we blocked.
176 				 */
177 				if (sp->s_ttyvp)
178 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
179 			}
180 			if (sp->s_ttyvp)
181 				vrele(sp->s_ttyvp);
182 			sp->s_ttyvp = NULL;
183 			/*
184 			 * s_ttyp is not zero'd; we use this to indicate
185 			 * that the session once had a controlling terminal.
186 			 * (for logging and informational purposes)
187 			 */
188 		}
189 		sp->s_leader = NULL;
190 	}
191 	fixjobc(p, p->p_pgrp, 0);
192 	(void)acct_process(p);
193 #ifdef KTRACE
194 	/*
195 	 * release trace file
196 	 */
197 	p->p_traceflag = 0;	/* don't trace the vrele() */
198 	if (p->p_tracep)
199 		ktrsettracevnode(p, NULL);
200 #endif
201 	/*
202 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
203 	 */
204 	p->p_stat = SDEAD;
205 
206         /*
207          * Remove proc from pidhash chain so looking it up won't
208          * work.  Move it from allproc to zombproc, but do not yet
209          * wake up the reaper.  We will put the proc on the
210          * deadproc list later (using the p_hash member), and
211          * wake up the reaper when we do.
212          */
213 	LIST_REMOVE(p, p_hash);
214 	LIST_REMOVE(p, p_list);
215 	LIST_INSERT_HEAD(&zombproc, p, p_list);
216 
217 	/*
218 	 * Give orphaned children to init(8).
219 	 */
220 	q = p->p_children.lh_first;
221 	if (q)		/* only need this if any child is S_ZOMB */
222 		wakeup((caddr_t)initproc);
223 	for (; q != 0; q = nq) {
224 		nq = q->p_sibling.le_next;
225 		proc_reparent(q, initproc);
226 		/*
227 		 * Traced processes are killed
228 		 * since their existence means someone is screwing up.
229 		 */
230 		if (q->p_flag & P_TRACED) {
231 			q->p_flag &= ~P_TRACED;
232 			psignal(q, SIGKILL);
233 		}
234 	}
235 
236 	/*
237 	 * Save exit status and final rusage info, adding in child rusage
238 	 * info and self times.
239 	 */
240 	p->p_xstat = rv;
241 	*p->p_ru = p->p_stats->p_ru;
242 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
243 	ruadd(p->p_ru, &p->p_stats->p_cru);
244 
245 	/*
246 	 * clear %cpu usage during swap
247 	 */
248 	p->p_pctcpu = 0;
249 
250 	/*
251 	 * notify interested parties of our demise.
252 	 */
253 	KNOTE(&p->p_klist, NOTE_EXIT);
254 
255 	/*
256 	 * Notify parent that we're gone.  If we have P_NOZOMBIE or parent has
257 	 * the P_NOCLDWAIT flag set, notify process 1 instead (and hope it
258 	 * will handle this situation).
259 	 */
260 	if ((p->p_flag & P_NOZOMBIE) || (p->p_pptr->p_flag & P_NOCLDWAIT)) {
261 		struct proc *pp = p->p_pptr;
262 		proc_reparent(p, initproc);
263 		/*
264 		 * If this was the last child of our parent, notify
265 		 * parent, so in case he was wait(2)ing, he will
266 		 * continue.
267 		 */
268 		if (pp->p_children.lh_first == NULL)
269 			wakeup((caddr_t)pp);
270 	}
271 
272 	if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
273 		psignal(p->p_pptr, P_EXITSIG(p));
274 	wakeup((caddr_t)p->p_pptr);
275 
276 	/*
277 	 * Notify procfs debugger
278 	 */
279 	if (p->p_flag & P_FSTRACE)
280 		wakeup((caddr_t)p);
281 
282 	/*
283 	 * Release the process's signal state.
284 	 */
285 	sigactsfree(p);
286 
287 	/*
288 	 * Clear curproc after we've done all operations
289 	 * that could block, and before tearing down the rest
290 	 * of the process state that might be used from clock, etc.
291 	 * Also, can't clear curproc while we're still runnable,
292 	 * as we're not on a run queue (we are current, just not
293 	 * a proper proc any longer!).
294 	 *
295 	 * Other substructures are freed from wait().
296 	 */
297 	curproc = NULL;
298 	limfree(p->p_limit);
299 	p->p_limit = NULL;
300 
301 	/*
302 	 * Finally, call machine-dependent code to switch to a new
303 	 * context (possibly the idle context).  Once we are no longer
304 	 * using the dead process's vmspace and stack, exit2() will be
305 	 * called to schedule those resources to be released by the
306 	 * reaper thread.
307 	 *
308 	 * Note that cpu_exit() will end with a call equivalent to
309 	 * cpu_switch(), finishing our execution (pun intended).
310 	 */
311 	cpu_exit(p);
312 }
313 
314 /*
315  * We are called from cpu_exit() once it is safe to schedule the
316  * dead process's resources to be freed.
317  *
318  * NOTE: One must be careful with locking in this routine.  It's
319  * called from a critical section in machine-dependent code, so
320  * we should refrain from changing any interrupt state.
321  *
322  * We lock the deadproc list (a spin lock), place the proc on that
323  * list (using the p_hash member), and wake up the reaper.
324  */
325 void
326 exit2(p)
327 	struct proc *p;
328 {
329 
330 	simple_lock(&deadproc_slock);
331 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
332 	simple_unlock(&deadproc_slock);
333 
334 	wakeup(&deadproc);
335 }
336 
337 /*
338  * Process reaper.  This is run by a kernel thread to free the resources
339  * of a dead process.  Once the resources are free, the process becomes
340  * a zombie, and the parent is allowed to read the undead's status.
341  */
342 void
343 reaper()
344 {
345 	struct proc *p;
346 
347 	for (;;) {
348 		simple_lock(&deadproc_slock);
349 		p = LIST_FIRST(&deadproc);
350 		if (p == NULL) {
351 			/* No work for us; go to sleep until someone exits. */
352 			simple_unlock(&deadproc_slock);
353 			(void) tsleep(&deadproc, PVM, "reaper", 0);
354 			continue;
355 		}
356 
357 		/* Remove us from the deadproc list. */
358 		LIST_REMOVE(p, p_hash);
359 		simple_unlock(&deadproc_slock);
360 
361 		/*
362 		 * Give machine-dependent code a chance to free any
363 		 * resources it couldn't free while still running on
364 		 * that process's context.  This must be done before
365 		 * uvm_exit(), in case these resources are in the PCB.
366 		 */
367 		cpu_wait(p);
368 
369 		/*
370 		 * Free the VM resources we're still holding on to.
371 		 * We must do this from a valid thread because doing
372 		 * so may block.
373 		 */
374 		uvm_exit(p);
375 
376 		/* Process is now a true zombie. */
377 		if ((p->p_flag & P_NOZOMBIE) == 0) {
378 			p->p_stat = SZOMB;
379 
380 			/* Wake up the parent so it can get exit status. */
381 			psignal(p->p_pptr, SIGCHLD);
382 			wakeup((caddr_t)p->p_pptr);
383 		} else {
384 			/* Noone will wait for us. Just zap the process now */
385 			proc_zap(p);
386 		}
387 	}
388 }
389 
390 int
391 sys_wait4(q, v, retval)
392 	register struct proc *q;
393 	void *v;
394 	register_t *retval;
395 {
396 	register struct sys_wait4_args /* {
397 		syscallarg(int) pid;
398 		syscallarg(int *) status;
399 		syscallarg(int) options;
400 		syscallarg(struct rusage *) rusage;
401 	} */ *uap = v;
402 	register int nfound;
403 	register struct proc *p, *t;
404 	int status, error;
405 
406 	if (SCARG(uap, pid) == 0)
407 		SCARG(uap, pid) = -q->p_pgid;
408 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG))
409 		return (EINVAL);
410 
411 loop:
412 	nfound = 0;
413 	for (p = q->p_children.lh_first; p != 0; p = p->p_sibling.le_next) {
414 		if ((p->p_flag & P_NOZOMBIE) ||
415 		    (SCARG(uap, pid) != WAIT_ANY &&
416 		    p->p_pid != SCARG(uap, pid) &&
417 		    p->p_pgid != -SCARG(uap, pid)))
418 			continue;
419 
420 		/*
421 		 * Wait for processes with p_exitsig != SIGCHLD processes only
422 		 * if WALTSIG is set; wait for processes with pexitsig ==
423 		 * SIGCHLD only if WALTSIG is clear.
424 		 */
425 		if ((SCARG(uap, options) & WALTSIG) ?
426 		    (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD))
427 			continue;
428 
429 		nfound++;
430 		if (p->p_stat == SZOMB) {
431 			retval[0] = p->p_pid;
432 
433 			if (SCARG(uap, status)) {
434 				status = p->p_xstat;	/* convert to int */
435 				error = copyout((caddr_t)&status,
436 						(caddr_t)SCARG(uap, status),
437 						sizeof(status));
438 				if (error)
439 					return (error);
440 			}
441 			if (SCARG(uap, rusage) &&
442 			    (error = copyout((caddr_t)p->p_ru,
443 			    (caddr_t)SCARG(uap, rusage),
444 			    sizeof(struct rusage))))
445 				return (error);
446 
447 			/*
448 			 * If we got the child via a ptrace 'attach',
449 			 * we need to give it back to the old parent.
450 			 */
451 			if (p->p_oppid && (t = pfind(p->p_oppid))) {
452 				p->p_oppid = 0;
453 				proc_reparent(p, t);
454 				if (p->p_exitsig != 0)
455 					psignal(t, P_EXITSIG(p));
456 				wakeup((caddr_t)t);
457 				return (0);
458 			}
459 
460 			scheduler_wait_hook(q, p);
461 			p->p_xstat = 0;
462 			ruadd(&q->p_stats->p_cru, p->p_ru);
463 
464 			proc_zap(p);
465 
466 			return (0);
467 		}
468 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
469 		    (p->p_flag & P_TRACED || SCARG(uap, options) & WUNTRACED)) {
470 			p->p_flag |= P_WAITED;
471 			retval[0] = p->p_pid;
472 
473 			if (SCARG(uap, status)) {
474 				status = W_STOPCODE(p->p_xstat);
475 				error = copyout((caddr_t)&status,
476 				    (caddr_t)SCARG(uap, status),
477 				    sizeof(status));
478 			} else
479 				error = 0;
480 			return (error);
481 		}
482 	}
483 	if (nfound == 0)
484 		return (ECHILD);
485 	if (SCARG(uap, options) & WNOHANG) {
486 		retval[0] = 0;
487 		return (0);
488 	}
489 	if ((error = tsleep((caddr_t)q, PWAIT | PCATCH, "wait", 0)) != 0)
490 		return (error);
491 	goto loop;
492 }
493 
494 /*
495  * make process 'parent' the new parent of process 'child'.
496  */
497 void
498 proc_reparent(child, parent)
499 	register struct proc *child;
500 	register struct proc *parent;
501 {
502 
503 	if (child->p_pptr == parent)
504 		return;
505 
506 	if (parent == initproc)
507 		child->p_exitsig = SIGCHLD;
508 
509 	LIST_REMOVE(child, p_sibling);
510 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
511 	child->p_pptr = parent;
512 }
513 
514 void
515 proc_zap(p)
516 	struct proc *p;
517 {
518 
519 	pool_put(&rusage_pool, p->p_ru);
520 
521 	/*
522 	 * Finally finished with old proc entry.
523 	 * Unlink it from its process group and free it.
524 	 */
525 	leavepgrp(p);
526 	LIST_REMOVE(p, p_list);	/* off zombproc */
527 	LIST_REMOVE(p, p_sibling);
528 
529 	/*
530 	 * Decrement the count of procs running with this uid.
531 	 */
532 	(void)chgproccnt(p->p_cred->p_ruid, -1);
533 
534 	/*
535 	 * Free up credentials.
536 	 */
537 	if (--p->p_cred->p_refcnt == 0) {
538 		crfree(p->p_cred->pc_ucred);
539 		pool_put(&pcred_pool, p->p_cred);
540 	}
541 
542 	/*
543 	 * Release reference to text vnode
544 	 */
545 	if (p->p_textvp)
546 		vrele(p->p_textvp);
547 
548 	pool_put(&proc_pool, p);
549 	nprocs--;
550 }
551 
552