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