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