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