xref: /openbsd-src/sys/kern/kern_exit.c (revision 7e4992814da25ff0192f39c21961a23e3099612a)
1 /*	$OpenBSD: kern_exit.c,v 1.122 2013/04/06 03:44:34 tedu 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 SYSVSEM
64 #include <sys/sem.h>
65 #endif
66 
67 #include "systrace.h"
68 #include <dev/systrace.h>
69 
70 #include <sys/mount.h>
71 #include <sys/syscallargs.h>
72 
73 
74 #include <uvm/uvm_extern.h>
75 
76 /*
77  * exit --
78  *	Death of process.
79  */
80 int
81 sys_exit(struct proc *p, void *v, register_t *retval)
82 {
83 	struct sys_exit_args /* {
84 		syscallarg(int) rval;
85 	} */ *uap = v;
86 
87 	exit1(p, W_EXITCODE(SCARG(uap, rval), 0), EXIT_NORMAL);
88 	/* NOTREACHED */
89 	return (0);
90 }
91 
92 int
93 sys___threxit(struct proc *p, void *v, register_t *retval)
94 {
95 	struct sys___threxit_args /* {
96 		syscallarg(pid_t *) notdead;
97 	} */ *uap = v;
98 
99 	if (SCARG(uap, notdead) != NULL) {
100 		pid_t zero = 0;
101 		if (copyout(&zero, SCARG(uap, notdead), sizeof(zero))) {
102 			psignal(p, SIGSEGV);
103 		}
104 	}
105 	exit1(p, 0, EXIT_THREAD);
106 
107 	return (0);
108 }
109 
110 /*
111  * Exit: deallocate address space and other resources, change proc state
112  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
113  * status and rusage for wait().  Check for child processes and orphan them.
114  */
115 void
116 exit1(struct proc *p, int rv, int flags)
117 {
118 	struct process *pr, *qr, *nqr;
119 	struct rusage *rup;
120 	struct vnode *ovp;
121 
122 	if (p->p_pid == 1)
123 		panic("init died (signal %d, exit %d)",
124 		    WTERMSIG(rv), WEXITSTATUS(rv));
125 
126 	atomic_setbits_int(&p->p_flag, P_WEXIT);
127 
128 	pr = p->p_p;
129 
130 	/* single-threaded? */
131 	if (TAILQ_FIRST(&pr->ps_threads) == p &&
132 	    TAILQ_NEXT(p, p_thr_link) == NULL)
133 		flags = EXIT_NORMAL;
134 	else {
135 		/* nope, multi-threaded */
136 		if (flags == EXIT_NORMAL)
137 			single_thread_set(p, SINGLE_EXIT, 0);
138 		else if (flags == EXIT_THREAD)
139 			single_thread_check(p, 0);
140 	}
141 
142 	if (flags == EXIT_NORMAL) {
143 		atomic_setbits_int(&pr->ps_flags, PS_EXITING);
144 		pr->ps_mainproc->p_xstat = rv;
145 
146 		/*
147 		 * If parent is waiting for us to exit or exec, PS_PPWAIT
148 		 * is set; we wake up the parent early to avoid deadlock.
149 		 */
150 		if (pr->ps_flags & PS_PPWAIT) {
151 			atomic_clearbits_int(&pr->ps_flags, PS_PPWAIT);
152 			atomic_clearbits_int(&pr->ps_pptr->ps_flags,
153 			    PS_ISPWAIT);
154 			wakeup(pr->ps_pptr);
155 		}
156 	}
157 
158 	/* unlink ourselves from the active threads */
159 	TAILQ_REMOVE(&pr->ps_threads, p, p_thr_link);
160 	if ((p->p_flag & P_THREAD) == 0) {
161 		/* main thread gotta wait because it has the pid, et al */
162 		while (! TAILQ_EMPTY(&pr->ps_threads))
163 			tsleep(&pr->ps_threads, PUSER, "thrdeath", 0);
164 		if (pr->ps_flags & PS_PROFIL)
165 			stopprofclock(pr);
166 	} else if (TAILQ_EMPTY(&pr->ps_threads))
167 		wakeup(&pr->ps_threads);
168 
169 	rup = pr->ps_ru;
170 	if (rup == NULL) {
171 		rup = pool_get(&rusage_pool, PR_WAITOK | PR_ZERO);
172 
173 		if (pr->ps_ru == NULL)
174 			pr->ps_ru = rup;
175 		else {
176 			pool_put(&rusage_pool, rup);
177 			rup = pr->ps_ru;
178 		}
179 	}
180 	p->p_siglist = 0;
181 
182 	/*
183 	 * Close open files and release open-file table.
184 	 */
185 	fdfree(p);
186 
187 	if ((p->p_flag & P_THREAD) == 0) {
188 		timeout_del(&pr->ps_realit_to);
189 		timeout_del(&pr->ps_virt_to);
190 		timeout_del(&pr->ps_prof_to);
191 #ifdef SYSVSEM
192 		semexit(pr);
193 #endif
194 		if (SESS_LEADER(pr)) {
195 			struct session *sp = pr->ps_session;
196 
197 			if (sp->s_ttyvp) {
198 				/*
199 				 * Controlling process.
200 				 * Signal foreground pgrp,
201 				 * drain controlling terminal
202 				 * and revoke access to controlling terminal.
203 				 */
204 				if (sp->s_ttyp->t_session == sp) {
205 					if (sp->s_ttyp->t_pgrp)
206 						pgsignal(sp->s_ttyp->t_pgrp,
207 						    SIGHUP, 1);
208 					(void) ttywait(sp->s_ttyp);
209 					/*
210 					 * The tty could have been revoked
211 					 * if we blocked.
212 					 */
213 					if (sp->s_ttyvp)
214 						VOP_REVOKE(sp->s_ttyvp,
215 						    REVOKEALL);
216 				}
217 				ovp = sp->s_ttyvp;
218 				sp->s_ttyvp = NULL;
219 				if (ovp)
220 					vrele(ovp);
221 				/*
222 				 * s_ttyp is not zero'd; we use this to
223 				 * indicate that the session once had a
224 				 * controlling terminal.  (for logging and
225 				 * informational purposes)
226 				 */
227 			}
228 			sp->s_leader = NULL;
229 		}
230 		fixjobc(pr, pr->ps_pgrp, 0);
231 
232 #ifdef ACCOUNTING
233 		(void)acct_process(p);
234 #endif
235 
236 #ifdef KTRACE
237 		/* release trace file */
238 		if (pr->ps_tracevp)
239 			ktrcleartrace(pr);
240 #endif
241 	}
242 
243 #if NSYSTRACE > 0
244 	if (ISSET(p->p_flag, P_SYSTRACE))
245 		systrace_exit(p);
246 #endif
247 
248 	/*
249 	 * If emulation has process exit hook, call it now.
250 	 */
251 	if (p->p_emul->e_proc_exit)
252 		(*p->p_emul->e_proc_exit)(p);
253 
254         /*
255          * Remove proc from pidhash chain so looking it up won't
256          * work.  Move it from allproc to zombproc, but do not yet
257          * wake up the reaper.  We will put the proc on the
258          * deadproc list later (using the p_hash member), and
259          * wake up the reaper when we do.
260          */
261 	/*
262 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
263 	 */
264 	p->p_stat = SDEAD;
265 
266 	LIST_REMOVE(p, p_hash);
267 	LIST_REMOVE(p, p_list);
268 	LIST_INSERT_HEAD(&zombproc, p, p_list);
269 
270 	/*
271 	 * Give orphaned children to init(8).
272 	 */
273 	if ((p->p_flag & P_THREAD) == 0) {
274 		qr = LIST_FIRST(&pr->ps_children);
275 		if (qr)		/* only need this if any child is S_ZOMB */
276 			wakeup(initproc->p_p);
277 		for (; qr != 0; qr = nqr) {
278 			nqr = LIST_NEXT(qr, ps_sibling);
279 			proc_reparent(qr, initproc->p_p);
280 			/*
281 			 * Traced processes are killed since their
282 			 * existence means someone is screwing up.
283 			 */
284 			if (qr->ps_flags & PS_TRACED &&
285 			    !(qr->ps_flags & PS_EXITING)) {
286 				atomic_clearbits_int(&qr->ps_flags, PS_TRACED);
287 				/*
288 				 * If single threading is active,
289 				 * direct the signal to the active
290 				 * thread to avoid deadlock.
291 				 */
292 				if (qr->ps_single)
293 					ptsignal(qr->ps_single, SIGKILL,
294 					    STHREAD);
295 				else
296 					prsignal(qr, SIGKILL);
297 			}
298 		}
299 	}
300 
301 
302 	/* add thread's accumulated rusage into the process's total */
303 	ruadd(rup, &p->p_ru);
304 
305 	/*
306 	 * clear %cpu usage during swap
307 	 */
308 	p->p_pctcpu = 0;
309 
310 	if ((p->p_flag & P_THREAD) == 0) {
311 		/*
312 		 * Final thread has died, so add on our children's rusage
313 		 * and calculate the total times
314 		 */
315 		calcru(&pr->ps_tu, &rup->ru_utime, &rup->ru_stime, NULL);
316 		ruadd(rup, &pr->ps_cru);
317 
318 		/* notify interested parties of our demise and clean up */
319 		knote_processexit(pr);
320 
321 		/*
322 		 * Notify parent that we're gone.  If we have P_NOZOMBIE
323 		 * or parent has the SAS_NOCLDWAIT flag set, notify process 1
324 		 * instead (and hope it will handle this situation).
325 		 */
326 		if ((p->p_flag & P_NOZOMBIE) ||
327 		    (pr->ps_pptr->ps_mainproc->p_sigacts->ps_flags &
328 		    SAS_NOCLDWAIT)) {
329 			struct process *ppr = pr->ps_pptr;
330 			proc_reparent(pr, initproc->p_p);
331 			/*
332 			 * If this was the last child of our parent, notify
333 			 * parent, so in case he was wait(2)ing, he will
334 			 * continue.
335 			 */
336 			if (LIST_EMPTY(&ppr->ps_children))
337 				wakeup(ppr);
338 		}
339 	}
340 
341 	/*
342 	 * Release the process's signal state.
343 	 */
344 	sigactsfree(p);
345 
346 	/*
347 	 * Other substructures are freed from reaper and wait().
348 	 */
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 	uvmexp.swtch++;
361 	cpu_exit(p);
362 	panic("cpu_exit returned");
363 }
364 
365 /*
366  * Locking of this proclist is special; it's accessed in a
367  * critical section of process exit, and thus locking it can't
368  * modify interrupt state.  We use a simple spin lock for this
369  * proclist.  Processes on this proclist are also on zombproc;
370  * we use the p_hash member to linkup to deadproc.
371  */
372 struct mutex deadproc_mutex = MUTEX_INITIALIZER(IPL_NONE);
373 struct proclist deadproc = LIST_HEAD_INITIALIZER(deadproc);
374 
375 /*
376  * We are called from cpu_exit() once it is safe to schedule the
377  * dead process's resources to be freed.
378  *
379  * NOTE: One must be careful with locking in this routine.  It's
380  * called from a critical section in machine-dependent code, so
381  * we should refrain from changing any interrupt state.
382  *
383  * We lock the deadproc list, place the proc on that list (using
384  * the p_hash member), and wake up the reaper.
385  */
386 void
387 exit2(struct proc *p)
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 
396 /*
397  * Process reaper.  This is run by a kernel thread to free the resources
398  * of a dead process.  Once the resources are free, the process becomes
399  * a zombie, and the parent is allowed to read the undead's status.
400  */
401 void
402 reaper(void)
403 {
404 	struct proc *p;
405 
406 	KERNEL_UNLOCK();
407 
408 	SCHED_ASSERT_UNLOCKED();
409 
410 	for (;;) {
411 		mtx_enter(&deadproc_mutex);
412 		while ((p = LIST_FIRST(&deadproc)) == NULL)
413 			msleep(&deadproc, &deadproc_mutex, PVM, "reaper", 0);
414 
415 		/* Remove us from the deadproc list. */
416 		LIST_REMOVE(p, p_hash);
417 		mtx_leave(&deadproc_mutex);
418 
419 		KERNEL_LOCK();
420 
421 		/*
422 		 * Free the VM resources we're still holding on to.
423 		 * We must do this from a valid thread because doing
424 		 * so may block.
425 		 */
426 		uvm_exit(p);
427 
428 		/* Process is now a true zombie. */
429 		if ((p->p_flag & P_NOZOMBIE) == 0) {
430 			p->p_stat = SZOMB;
431 
432 			if (P_EXITSIG(p) != 0)
433 				prsignal(p->p_p->ps_pptr, P_EXITSIG(p));
434 			/* Wake up the parent so it can get exit status. */
435 			wakeup(p->p_p->ps_pptr);
436 		} else {
437 			/* Noone will wait for us. Just zap the process now */
438 			proc_zap(p);
439 		}
440 
441 		KERNEL_UNLOCK();
442 	}
443 }
444 
445 int
446 sys_wait4(struct proc *q, void *v, register_t *retval)
447 {
448 	struct sys_wait4_args /* {
449 		syscallarg(pid_t) pid;
450 		syscallarg(int *) status;
451 		syscallarg(int) options;
452 		syscallarg(struct rusage *) rusage;
453 	} */ *uap = v;
454 	int nfound;
455 	struct process *pr;
456 	struct proc *p;
457 	int status, error;
458 
459 	if (SCARG(uap, pid) == 0)
460 		SCARG(uap, pid) = -q->p_p->ps_pgid;
461 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG|WCONTINUED))
462 		return (EINVAL);
463 
464 loop:
465 	nfound = 0;
466 	LIST_FOREACH(pr, &q->p_p->ps_children, ps_sibling) {
467 		p = pr->ps_mainproc;
468 		if ((p->p_flag & P_NOZOMBIE) ||
469 		    (SCARG(uap, pid) != WAIT_ANY &&
470 		    p->p_pid != SCARG(uap, pid) &&
471 		    pr->ps_pgid != -SCARG(uap, pid)))
472 			continue;
473 
474 		/*
475 		 * Wait for processes with p_exitsig != SIGCHLD processes only
476 		 * if WALTSIG is set; wait for processes with pexitsig ==
477 		 * SIGCHLD only if WALTSIG is clear.
478 		 */
479 		if ((SCARG(uap, options) & WALTSIG) ?
480 		    (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD))
481 			continue;
482 
483 		nfound++;
484 		if (p->p_stat == SZOMB) {
485 			retval[0] = p->p_pid;
486 
487 			if (SCARG(uap, status)) {
488 				status = p->p_xstat;	/* convert to int */
489 				error = copyout(&status,
490 				    SCARG(uap, status), sizeof(status));
491 				if (error)
492 					return (error);
493 			}
494 			if (SCARG(uap, rusage) &&
495 			    (error = copyout(pr->ps_ru,
496 			    SCARG(uap, rusage), sizeof(struct rusage))))
497 				return (error);
498 			proc_finish_wait(q, p);
499 			return (0);
500 		}
501 		if (pr->ps_flags & PS_TRACED &&
502 		    (pr->ps_flags & PS_WAITED) == 0 && pr->ps_single &&
503 		    pr->ps_single->p_stat == SSTOP &&
504 		    (pr->ps_single->p_flag & P_SUSPSINGLE) == 0) {
505 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
506 			retval[0] = p->p_pid;
507 
508 			if (SCARG(uap, status)) {
509 				status = W_STOPCODE(pr->ps_single->p_xstat);
510 				error = copyout(&status, SCARG(uap, status),
511 				    sizeof(status));
512 			} else
513 				error = 0;
514 			return (error);
515 		}
516 		if (p->p_stat == SSTOP &&
517 		    (pr->ps_flags & PS_WAITED) == 0 &&
518 		    (p->p_flag & P_SUSPSINGLE) == 0 &&
519 		    (pr->ps_flags & PS_TRACED ||
520 		    SCARG(uap, options) & WUNTRACED)) {
521 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
522 			retval[0] = p->p_pid;
523 
524 			if (SCARG(uap, status)) {
525 				status = W_STOPCODE(p->p_xstat);
526 				error = copyout(&status, SCARG(uap, status),
527 				    sizeof(status));
528 			} else
529 				error = 0;
530 			return (error);
531 		}
532 		if ((SCARG(uap, options) & WCONTINUED) && (p->p_flag & P_CONTINUED)) {
533 			atomic_clearbits_int(&p->p_flag, P_CONTINUED);
534 			retval[0] = p->p_pid;
535 
536 			if (SCARG(uap, status)) {
537 				status = _WCONTINUED;
538 				error = copyout(&status, SCARG(uap, status),
539 				    sizeof(status));
540 			} else
541 				error = 0;
542 			return (error);
543 		}
544 	}
545 	if (nfound == 0)
546 		return (ECHILD);
547 	if (SCARG(uap, options) & WNOHANG) {
548 		retval[0] = 0;
549 		return (0);
550 	}
551 	if ((error = tsleep(q->p_p, PWAIT | PCATCH, "wait", 0)) != 0)
552 		return (error);
553 	goto loop;
554 }
555 
556 void
557 proc_finish_wait(struct proc *waiter, struct proc *p)
558 {
559 	struct process *pr, *tr;
560 	struct rusage *rup;
561 
562 	/*
563 	 * If we got the child via a ptrace 'attach',
564 	 * we need to give it back to the old parent.
565 	 */
566 	pr = p->p_p;
567 	if ((p->p_flag & P_THREAD) == 0 && pr->ps_oppid &&
568 	    (tr = prfind(pr->ps_oppid))) {
569 		atomic_clearbits_int(&pr->ps_flags, PS_TRACED);
570 		pr->ps_oppid = 0;
571 		proc_reparent(pr, tr);
572 		if (p->p_exitsig != 0)
573 			prsignal(tr, p->p_exitsig);
574 		wakeup(tr);
575 	} else {
576 		scheduler_wait_hook(waiter, p);
577 		p->p_xstat = 0;
578 		rup = &waiter->p_p->ps_cru;
579 		ruadd(rup, pr->ps_ru);
580 		proc_zap(p);
581 	}
582 }
583 
584 /*
585  * make process 'parent' the new parent of process 'child'.
586  */
587 void
588 proc_reparent(struct process *child, struct process *parent)
589 {
590 
591 	if (child->ps_pptr == parent)
592 		return;
593 
594 	if (parent == initproc->p_p)
595 		child->ps_mainproc->p_exitsig = SIGCHLD;
596 
597 	LIST_REMOVE(child, ps_sibling);
598 	LIST_INSERT_HEAD(&parent->ps_children, child, ps_sibling);
599 	child->ps_pptr = parent;
600 }
601 
602 void
603 proc_zap(struct proc *p)
604 {
605 	struct process *pr = p->p_p;
606 	struct vnode *otvp;
607 
608 	/*
609 	 * Finally finished with old proc entry.
610 	 * Unlink it from its process group and free it.
611 	 */
612 	if ((p->p_flag & P_THREAD) == 0)
613 		leavepgrp(pr);
614 	LIST_REMOVE(p, p_list);	/* off zombproc */
615 	if ((p->p_flag & P_THREAD) == 0) {
616 		LIST_REMOVE(pr, ps_sibling);
617 
618 		/*
619 		 * Decrement the count of procs running with this uid.
620 		 */
621 		(void)chgproccnt(p->p_cred->p_ruid, -1);
622 	}
623 
624 	/*
625 	 * Release reference to text vnode
626 	 */
627 	otvp = p->p_textvp;
628 	p->p_textvp = NULL;
629 	if (otvp)
630 		vrele(otvp);
631 
632 	/*
633 	 * Remove us from our process list, possibly killing the process
634 	 * in the process (pun intended).
635 	 */
636 	if (--pr->ps_refcnt == 0) {
637 		if (pr->ps_ptstat != NULL)
638 			free(pr->ps_ptstat, M_SUBPROC);
639 		pool_put(&rusage_pool, pr->ps_ru);
640 		KASSERT(TAILQ_EMPTY(&pr->ps_threads));
641 		limfree(pr->ps_limit);
642 		crfree(pr->ps_cred->pc_ucred);
643 		pool_put(&pcred_pool, pr->ps_cred);
644 		pool_put(&process_pool, pr);
645 		nprocesses--;
646 	}
647 
648 	pool_put(&proc_pool, p);
649 	nthreads--;
650 }
651