xref: /openbsd-src/sys/kern/kern_exit.c (revision 7aa7a280db0b72c2800f108024286e920f283da7)
1 /*	$OpenBSD: kern_exit.c,v 1.52 2004/07/22 15:42:11 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. 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/buf.h>
49 #include <sys/wait.h>
50 #include <sys/file.h>
51 #include <sys/vnode.h>
52 #include <sys/syslog.h>
53 #include <sys/malloc.h>
54 #include <sys/resourcevar.h>
55 #include <sys/ptrace.h>
56 #include <sys/acct.h>
57 #include <sys/filedesc.h>
58 #include <sys/signalvar.h>
59 #include <sys/sched.h>
60 #include <sys/ktrace.h>
61 #include <sys/pool.h>
62 #include <sys/mutex.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 #ifdef ACCOUNTING
175 	(void)acct_process(p);
176 #endif
177 #ifdef KTRACE
178 	/*
179 	 * release trace file
180 	 */
181 	p->p_traceflag = 0;	/* don't trace the vrele() */
182 	if (p->p_tracep)
183 		ktrsettracevnode(p, NULL);
184 #endif
185 #if NSYSTRACE > 0
186 	if (ISSET(p->p_flag, P_SYSTRACE))
187 		systrace_exit(p);
188 #endif
189 	/*
190 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
191 	 */
192 	p->p_stat = SDEAD;
193 
194         /*
195          * Remove proc from pidhash chain so looking it up won't
196          * work.  Move it from allproc to zombproc, but do not yet
197          * wake up the reaper.  We will put the proc on the
198          * deadproc list later (using the p_hash member), and
199          * wake up the reaper when we do.
200          */
201 	LIST_REMOVE(p, p_hash);
202 	LIST_REMOVE(p, p_list);
203 	LIST_INSERT_HEAD(&zombproc, p, p_list);
204 
205 	/*
206 	 * Give orphaned children to init(8).
207 	 */
208 	q = p->p_children.lh_first;
209 	if (q)		/* only need this if any child is S_ZOMB */
210 		wakeup(initproc);
211 	for (; q != 0; q = nq) {
212 		nq = q->p_sibling.le_next;
213 		proc_reparent(q, initproc);
214 		/*
215 		 * Traced processes are killed
216 		 * since their existence means someone is screwing up.
217 		 */
218 		if (q->p_flag & P_TRACED) {
219 			q->p_flag &= ~P_TRACED;
220 			psignal(q, SIGKILL);
221 		}
222 	}
223 
224 	/*
225 	 * Save exit status and final rusage info, adding in child rusage
226 	 * info and self times.
227 	 */
228 	p->p_xstat = rv;
229 	*p->p_ru = p->p_stats->p_ru;
230 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
231 	ruadd(p->p_ru, &p->p_stats->p_cru);
232 
233 	/*
234 	 * clear %cpu usage during swap
235 	 */
236 	p->p_pctcpu = 0;
237 
238 	/*
239 	 * notify interested parties of our demise.
240 	 */
241 	KNOTE(&p->p_klist, NOTE_EXIT);
242 
243 	/*
244 	 * Notify parent that we're gone.  If we have P_NOZOMBIE or parent has
245 	 * the P_NOCLDWAIT flag set, notify process 1 instead (and hope it
246 	 * will handle this situation).
247 	 */
248 	if ((p->p_flag & P_NOZOMBIE) || (p->p_pptr->p_flag & P_NOCLDWAIT)) {
249 		struct proc *pp = p->p_pptr;
250 		proc_reparent(p, initproc);
251 		/*
252 		 * If this was the last child of our parent, notify
253 		 * parent, so in case he was wait(2)ing, he will
254 		 * continue.
255 		 */
256 		if (pp->p_children.lh_first == NULL)
257 			wakeup(pp);
258 	}
259 
260 	if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
261 		psignal(p->p_pptr, P_EXITSIG(p));
262 	wakeup(p->p_pptr);
263 
264 	/*
265 	 * Notify procfs debugger
266 	 */
267 	if (p->p_flag & P_FSTRACE)
268 		wakeup(p);
269 
270 	/*
271 	 * Release the process's signal state.
272 	 */
273 	sigactsfree(p);
274 
275 	/*
276 	 * Clear curproc after we've done all operations
277 	 * that could block, and before tearing down the rest
278 	 * of the process state that might be used from clock, etc.
279 	 * Also, can't clear curproc while we're still runnable,
280 	 * as we're not on a run queue (we are current, just not
281 	 * a proper proc any longer!).
282 	 *
283 	 * Other substructures are freed from wait().
284 	 */
285 	curproc = NULL;
286 	limfree(p->p_limit);
287 	p->p_limit = NULL;
288 
289 	/* This process no longer needs to hold the kernel lock. */
290 	KERNEL_PROC_UNLOCK(p);
291 
292 	/*
293 	 * If emulation has process exit hook, call it now.
294 	 */
295 	if (p->p_emul->e_proc_exit)
296 		(*p->p_emul->e_proc_exit)(p);
297 
298 	/*
299 	 * Finally, call machine-dependent code to switch to a new
300 	 * context (possibly the idle context).  Once we are no longer
301 	 * using the dead process's vmspace and stack, exit2() will be
302 	 * called to schedule those resources to be released by the
303 	 * reaper thread.
304 	 *
305 	 * Note that cpu_exit() will end with a call equivalent to
306 	 * cpu_switch(), finishing our execution (pun intended).
307 	 */
308 	cpu_exit(p);
309 }
310 
311 /*
312  * Locking of this proclist is special; it's accessed in a
313  * critical section of process exit, and thus locking it can't
314  * modify interrupt state.  We use a simple spin lock for this
315  * proclist.  Processes on this proclist are also on zombproc;
316  * we use the p_hash member to linkup to deadproc.
317  */
318 struct mutex deadproc_mutex = MUTEX_INITIALIZER(IPL_NONE);
319 struct proclist deadproc = LIST_HEAD_INITIALIZER(deadproc);
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, place the proc on that list (using
330  * the p_hash member), and wake up the reaper.
331  */
332 void
333 exit2(struct proc *p)
334 {
335 	int s;
336 
337 	mtx_enter(&deadproc_mutex);
338 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
339 	mtx_leave(&deadproc_mutex);
340 
341 	wakeup(&deadproc);
342 
343 	SCHED_LOCK(s);
344 }
345 
346 /*
347  * Process reaper.  This is run by a kernel thread to free the resources
348  * of a dead process.  Once the resources are free, the process becomes
349  * a zombie, and the parent is allowed to read the undead's status.
350  */
351 void
352 reaper(void)
353 {
354 	struct proc *p;
355 
356 	KERNEL_PROC_UNLOCK(curproc);
357 
358 	for (;;) {
359 		mtx_enter(&deadproc_mutex);
360 		p = LIST_FIRST(&deadproc);
361 		if (p == NULL) {
362 			/* No work for us; go to sleep until someone exits. */
363 			mtx_leave(&deadproc_mutex);
364 			(void) tsleep(&deadproc, PVM, "reaper", 0);
365 			continue;
366 		}
367 
368 		/* Remove us from the deadproc list. */
369 		LIST_REMOVE(p, p_hash);
370 		mtx_leave(&deadproc_mutex);
371 		KERNEL_PROC_LOCK(curproc);
372 
373 		/*
374 		 * Give machine-dependent code a chance to free any
375 		 * resources it couldn't free while still running on
376 		 * that process's context.  This must be done before
377 		 * uvm_exit(), in case these resources are in the PCB.
378 		 */
379 		cpu_wait(p);
380 
381 		/*
382 		 * Free the VM resources we're still holding on to.
383 		 * We must do this from a valid thread because doing
384 		 * so may block.
385 		 */
386 		uvm_exit(p);
387 
388 		/* Process is now a true zombie. */
389 		if ((p->p_flag & P_NOZOMBIE) == 0) {
390 			p->p_stat = SZOMB;
391 
392 			/* Wake up the parent so it can get exit status. */
393 			psignal(p->p_pptr, SIGCHLD);
394 			wakeup(p->p_pptr);
395 		} else {
396 			/* Noone will wait for us. Just zap the process now */
397 			proc_zap(p);
398 		}
399 
400 		KERNEL_PROC_UNLOCK(curproc);
401 	}
402 }
403 
404 pid_t
405 sys_wait4(q, v, retval)
406 	register struct proc *q;
407 	void *v;
408 	register_t *retval;
409 {
410 	register struct sys_wait4_args /* {
411 		syscallarg(pid_t) pid;
412 		syscallarg(int *) status;
413 		syscallarg(int) options;
414 		syscallarg(struct rusage *) rusage;
415 	} */ *uap = v;
416 	register int nfound;
417 	register struct proc *p, *t;
418 	int status, error;
419 
420 	if (SCARG(uap, pid) == 0)
421 		SCARG(uap, pid) = -q->p_pgid;
422 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG|WCONTINUED))
423 		return (EINVAL);
424 
425 loop:
426 	nfound = 0;
427 	for (p = q->p_children.lh_first; p != 0; p = p->p_sibling.le_next) {
428 		if ((p->p_flag & P_NOZOMBIE) ||
429 		    (SCARG(uap, pid) != WAIT_ANY &&
430 		    p->p_pid != SCARG(uap, pid) &&
431 		    p->p_pgid != -SCARG(uap, pid)))
432 			continue;
433 
434 		/*
435 		 * Wait for processes with p_exitsig != SIGCHLD processes only
436 		 * if WALTSIG is set; wait for processes with pexitsig ==
437 		 * SIGCHLD only if WALTSIG is clear.
438 		 */
439 		if ((SCARG(uap, options) & WALTSIG) ?
440 		    (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD))
441 			continue;
442 
443 		nfound++;
444 		if (p->p_stat == SZOMB) {
445 			retval[0] = p->p_pid;
446 
447 			if (SCARG(uap, status)) {
448 				status = p->p_xstat;	/* convert to int */
449 				error = copyout(&status,
450 				    SCARG(uap, status), sizeof(status));
451 				if (error)
452 					return (error);
453 			}
454 			if (SCARG(uap, rusage) &&
455 			    (error = copyout(p->p_ru,
456 			    SCARG(uap, rusage), sizeof(struct rusage))))
457 				return (error);
458 
459 			/*
460 			 * If we got the child via a ptrace 'attach',
461 			 * we need to give it back to the old parent.
462 			 */
463 			if (p->p_oppid && (t = pfind(p->p_oppid))) {
464 				p->p_oppid = 0;
465 				proc_reparent(p, t);
466 				if (p->p_exitsig != 0)
467 					psignal(t, P_EXITSIG(p));
468 				wakeup(t);
469 				return (0);
470 			}
471 
472 			scheduler_wait_hook(q, p);
473 			p->p_xstat = 0;
474 			ruadd(&q->p_stats->p_cru, p->p_ru);
475 
476 			proc_zap(p);
477 
478 			return (0);
479 		}
480 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
481 		    (p->p_flag & P_TRACED || SCARG(uap, options) & WUNTRACED)) {
482 			p->p_flag |= P_WAITED;
483 			retval[0] = p->p_pid;
484 
485 			if (SCARG(uap, status)) {
486 				status = W_STOPCODE(p->p_xstat);
487 				error = copyout(&status, SCARG(uap, status),
488 				    sizeof(status));
489 			} else
490 				error = 0;
491 			return (error);
492 		}
493 		if ((SCARG(uap, options) & WCONTINUED) && (p->p_flag & P_CONTINUED)) {
494 			p->p_flag &= ~P_CONTINUED;
495 			retval[0] = p->p_pid;
496 
497 			if (SCARG(uap, status)) {
498 				status = _WCONTINUED;
499 				error = copyout(&status, SCARG(uap, status),
500 				    sizeof(status));
501 			} else
502 				error = 0;
503 			return (error);
504 		}
505 	}
506 	if (nfound == 0)
507 		return (ECHILD);
508 	if (SCARG(uap, options) & WNOHANG) {
509 		retval[0] = 0;
510 		return (0);
511 	}
512 	if ((error = tsleep(q, PWAIT | PCATCH, "wait", 0)) != 0)
513 		return (error);
514 	goto loop;
515 }
516 
517 /*
518  * make process 'parent' the new parent of process 'child'.
519  */
520 void
521 proc_reparent(child, parent)
522 	register struct proc *child;
523 	register struct proc *parent;
524 {
525 
526 	if (child->p_pptr == parent)
527 		return;
528 
529 	if (parent == initproc)
530 		child->p_exitsig = SIGCHLD;
531 
532 	LIST_REMOVE(child, p_sibling);
533 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
534 	child->p_pptr = parent;
535 }
536 
537 void
538 proc_zap(struct proc *p)
539 {
540 	pool_put(&rusage_pool, p->p_ru);
541 
542 	/*
543 	 * Finally finished with old proc entry.
544 	 * Unlink it from its process group and free it.
545 	 */
546 	leavepgrp(p);
547 	LIST_REMOVE(p, p_list);	/* off zombproc */
548 	LIST_REMOVE(p, p_sibling);
549 
550 	/*
551 	 * Decrement the count of procs running with this uid.
552 	 */
553 	(void)chgproccnt(p->p_cred->p_ruid, -1);
554 
555 	/*
556 	 * Free up credentials.
557 	 */
558 	if (--p->p_cred->p_refcnt == 0) {
559 		crfree(p->p_cred->pc_ucred);
560 		pool_put(&pcred_pool, p->p_cred);
561 	}
562 
563 	/*
564 	 * Release reference to text vnode
565 	 */
566 	if (p->p_textvp)
567 		vrele(p->p_textvp);
568 
569 	pool_put(&proc_pool, p);
570 	nprocs--;
571 }
572 
573