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