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