xref: /dragonfly/sys/kern/kern_exit.c (revision 38a690d7)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
39  * $FreeBSD: src/sys/kern/kern_exit.c,v 1.92.2.11 2003/01/13 22:51:16 dillon Exp $
40  * $DragonFly: src/sys/kern/kern_exit.c,v 1.22 2003/07/30 00:19:14 dillon Exp $
41  */
42 
43 #include "opt_compat.h"
44 #include "opt_ktrace.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/sysproto.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/proc.h>
52 #include <sys/pioctl.h>
53 #include <sys/tty.h>
54 #include <sys/wait.h>
55 #include <sys/vnode.h>
56 #include <sys/resourcevar.h>
57 #include <sys/signalvar.h>
58 #include <sys/ptrace.h>
59 #include <sys/acct.h>		/* for acct_process() function prototype */
60 #include <sys/filedesc.h>
61 #include <sys/shm.h>
62 #include <sys/sem.h>
63 #include <sys/aio.h>
64 #include <sys/jail.h>
65 
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <sys/lock.h>
69 #include <vm/pmap.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_zone.h>
72 #include <vm/vm_extern.h>
73 #include <sys/user.h>
74 
75 /* Required to be non-static for SysVR4 emulator */
76 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
77 
78 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
79 
80 static int wait1 __P((struct wait_args *, int));
81 
82 /*
83  * callout list for things to do at exit time
84  */
85 struct exitlist {
86 	exitlist_fn function;
87 	TAILQ_ENTRY(exitlist) next;
88 };
89 
90 TAILQ_HEAD(exit_list_head, exitlist);
91 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
92 
93 /*
94  * exit --
95  *	Death of process.
96  *
97  * SYS_EXIT_ARGS(int rval)
98  */
99 void
100 sys_exit(struct sys_exit_args *uap)
101 {
102 	exit1(W_EXITCODE(uap->rval, 0));
103 	/* NOTREACHED */
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(int rv)
113 {
114 	struct proc *p = curproc;
115 	struct proc *q, *nq;
116 	struct vmspace *vm;
117 	struct vnode *vtmp;
118 	struct exitlist *ep;
119 
120 	if (p->p_pid == 1) {
121 		printf("init died (signal %d, exit %d)\n",
122 		    WTERMSIG(rv), WEXITSTATUS(rv));
123 		panic("Going nowhere without my init!");
124 	}
125 
126 	aio_proc_rundown(p);
127 
128 	/* are we a task leader? */
129 	if(p == p->p_leader) {
130         	struct kill_args killArgs;
131 		killArgs.signum = SIGKILL;
132 		q = p->p_peers;
133 		while(q) {
134 			killArgs.pid = q->p_pid;
135 			/*
136 		         * The interface for kill is better
137 			 * than the internal signal
138 			 */
139 			kill(&killArgs);
140 			nq = q;
141 			q = q->p_peers;
142 		}
143 		while (p->p_peers)
144 		  tsleep((caddr_t)p, 0, "exit1", 0);
145 	}
146 
147 #ifdef PGINPROF
148 	vmsizmon();
149 #endif
150 	STOPEVENT(p, S_EXIT, rv);
151 	wakeup(&p->p_stype);	/* Wakeup anyone in procfs' PIOCWAIT */
152 
153 	/*
154 	 * Check if any loadable modules need anything done at process exit.
155 	 * e.g. SYSV IPC stuff
156 	 * XXX what if one of these generates an error?
157 	 */
158 	TAILQ_FOREACH(ep, &exit_list, next)
159 		(*ep->function)(p->p_thread);
160 
161 	if (p->p_flag & P_PROFIL)
162 		stopprofclock(p);
163 	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
164 		M_ZOMBIE, M_WAITOK);
165 	/*
166 	 * If parent is waiting for us to exit or exec,
167 	 * P_PPWAIT is set; we will wakeup the parent below.
168 	 */
169 	p->p_flag &= ~(P_TRACED | P_PPWAIT);
170 	p->p_flag |= P_WEXIT;
171 	SIGEMPTYSET(p->p_siglist);
172 	if (timevalisset(&p->p_realtimer.it_value))
173 		untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
174 
175 	/*
176 	 * Reset any sigio structures pointing to us as a result of
177 	 * F_SETOWN with our pid.
178 	 */
179 	funsetownlst(&p->p_sigiolst);
180 
181 	/*
182 	 * Close open files and release open-file table.
183 	 * This may block!
184 	 */
185 	fdfree(p);
186 
187 	if(p->p_leader->p_peers) {
188 		q = p->p_leader;
189 		while(q->p_peers != p)
190 			q = q->p_peers;
191 		q->p_peers = p->p_peers;
192 		wakeup((caddr_t)p->p_leader);
193 	}
194 
195 	/*
196 	 * XXX Shutdown SYSV semaphores
197 	 */
198 	semexit(p);
199 
200 	/* The next two chunks should probably be moved to vmspace_exit. */
201 	vm = p->p_vmspace;
202 	/*
203 	 * Release user portion of address space.
204 	 * This releases references to vnodes,
205 	 * which could cause I/O if the file has been unlinked.
206 	 * Need to do this early enough that we can still sleep.
207 	 * Can't free the entire vmspace as the kernel stack
208 	 * may be mapped within that space also.
209 	 *
210 	 * Processes sharing the same vmspace may exit in one order, and
211 	 * get cleaned up by vmspace_exit() in a different order.  The
212 	 * last exiting process to reach this point releases as much of
213 	 * the environment as it can, and the last process cleaned up
214 	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
215 	 * remainder.
216 	 */
217 	++vm->vm_exitingcnt;
218 	if (--vm->vm_refcnt == 0) {
219 		shmexit(vm);
220 		pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
221 		    VM_MAXUSER_ADDRESS);
222 		(void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
223 		    VM_MAXUSER_ADDRESS);
224 	}
225 
226 	if (SESS_LEADER(p)) {
227 		struct session *sp = p->p_session;
228 
229 		if (sp->s_ttyvp) {
230 			/*
231 			 * Controlling process.
232 			 * Signal foreground pgrp,
233 			 * drain controlling terminal
234 			 * and revoke access to controlling terminal.
235 			 */
236 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
237 				if (sp->s_ttyp->t_pgrp)
238 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
239 				(void) ttywait(sp->s_ttyp);
240 				/*
241 				 * The tty could have been revoked
242 				 * if we blocked.
243 				 */
244 				if (sp->s_ttyvp)
245 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
246 			}
247 			if (sp->s_ttyvp)
248 				vrele(sp->s_ttyvp);
249 			sp->s_ttyvp = NULL;
250 			/*
251 			 * s_ttyp is not zero'd; we use this to indicate
252 			 * that the session once had a controlling terminal.
253 			 * (for logging and informational purposes)
254 			 */
255 		}
256 		sp->s_leader = NULL;
257 	}
258 	fixjobc(p, p->p_pgrp, 0);
259 	(void)acct_process(p);
260 #ifdef KTRACE
261 	/*
262 	 * release trace file
263 	 */
264 	p->p_traceflag = 0;	/* don't trace the vrele() */
265 	if ((vtmp = p->p_tracep) != NULL) {
266 		p->p_tracep = NULL;
267 		vrele(vtmp);
268 	}
269 #endif
270 	/*
271 	 * Release reference to text vnode
272 	 */
273 	if ((vtmp = p->p_textvp) != NULL) {
274 		p->p_textvp = NULL;
275 		vrele(vtmp);
276 	}
277 
278 	/*
279 	 * Once we set SZOMB the process can get reaped.  The wait1 code
280 	 * will also wait for TDF_RUNNING to be cleared in the thread's flags,
281 	 * indicating that it has been completely switched out.
282 	 */
283 
284 	/*
285 	 * Remove proc from allproc queue and pidhash chain.
286 	 * Place onto zombproc.  Unlink from parent's child list.
287 	 */
288 	LIST_REMOVE(p, p_list);
289 	LIST_INSERT_HEAD(&zombproc, p, p_list);
290 	p->p_stat = SZOMB;
291 
292 	LIST_REMOVE(p, p_hash);
293 
294 	q = LIST_FIRST(&p->p_children);
295 	if (q)		/* only need this if any child is S_ZOMB */
296 		wakeup((caddr_t) initproc);
297 	for (; q != 0; q = nq) {
298 		nq = LIST_NEXT(q, p_sibling);
299 		LIST_REMOVE(q, p_sibling);
300 		LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
301 		q->p_pptr = initproc;
302 		q->p_sigparent = SIGCHLD;
303 		/*
304 		 * Traced processes are killed
305 		 * since their existence means someone is screwing up.
306 		 */
307 		if (q->p_flag & P_TRACED) {
308 			q->p_flag &= ~P_TRACED;
309 			psignal(q, SIGKILL);
310 		}
311 	}
312 
313 	/*
314 	 * Save exit status and final rusage info, adding in child rusage
315 	 * info and self times.
316 	 */
317 	p->p_xstat = rv;
318 	*p->p_ru = p->p_stats->p_ru;
319 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
320 	ruadd(p->p_ru, &p->p_stats->p_cru);
321 
322 	/*
323 	 * notify interested parties of our demise.
324 	 */
325 	KNOTE(&p->p_klist, NOTE_EXIT);
326 
327 	/*
328 	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
329 	 * flag set, notify process 1 instead (and hope it will handle
330 	 * this situation).
331 	 */
332 	if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
333 		struct proc *pp = p->p_pptr;
334 		proc_reparent(p, initproc);
335 		/*
336 		 * If this was the last child of our parent, notify
337 		 * parent, so in case he was wait(2)ing, he will
338 		 * continue.
339 		 */
340 		if (LIST_EMPTY(&pp->p_children))
341 			wakeup((caddr_t)pp);
342 	}
343 
344 	if (p->p_sigparent && p->p_pptr != initproc) {
345 	        psignal(p->p_pptr, p->p_sigparent);
346 	} else {
347 	        psignal(p->p_pptr, SIGCHLD);
348 	}
349 
350 	wakeup((caddr_t)p->p_pptr);
351 #if defined(tahoe)
352 	/* move this to cpu_exit */
353 	p->p_thread->td_pcb->pcb_saveacc.faddr = (float *)NULL;
354 #endif
355 	/*
356 	 * cpu_exit is responsible for clearing curproc, since
357 	 * it is heavily integrated with the thread/switching sequence.
358 	 *
359 	 * Other substructures are freed from wait().
360 	 */
361 	if (--p->p_limit->p_refcnt == 0) {
362 		FREE(p->p_limit, M_SUBPROC);
363 		p->p_limit = NULL;
364 	}
365 
366 	/*
367 	 * Release the P_CURPROC designation on the process so the userland
368 	 * scheduler can work in someone else.
369 	 */
370 	release_curproc(p);
371 
372 	/*
373 	 * Finally, call machine-dependent code to release the remaining
374 	 * resources including address space, the kernel stack and pcb.
375 	 * The address space is released by "vmspace_free(p->p_vmspace)";
376 	 * This is machine-dependent, as we may have to change stacks
377 	 * or ensure that the current one isn't reallocated before we
378 	 * finish.  cpu_exit will end with a call to cpu_switch(), finishing
379 	 * our execution (pun intended).
380 	 */
381 	cpu_proc_exit();
382 }
383 
384 #ifdef COMPAT_43
385 /*
386  * owait()
387  *
388  * owait_args(int dummy)
389  */
390 int
391 owait(struct owait_args *uap)
392 {
393 	struct wait_args w;
394 
395 	w.options = 0;
396 	w.rusage = NULL;
397 	w.pid = WAIT_ANY;
398 	w.status = NULL;
399 	return (wait1(&w, 1));
400 }
401 #endif /* COMPAT_43 */
402 
403 int
404 wait4(struct wait_args *uap)
405 {
406 	return (wait1(uap, 0));
407 }
408 
409 /*
410  * wait1()
411  *
412  * wait_args(int pid, int *status, int options, struct rusage *rusage)
413  */
414 static int
415 wait1(struct wait_args *uap, int compat)
416 {
417 	struct proc *q = curproc;
418 	struct proc *p, *t;
419 	int status, nfound, error;
420 
421 	if (uap->pid == 0)
422 		uap->pid = -q->p_pgid;
423 	if (uap->options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
424 		return (EINVAL);
425 loop:
426 	nfound = 0;
427 	LIST_FOREACH(p, &q->p_children, p_sibling) {
428 		if (uap->pid != WAIT_ANY &&
429 		    p->p_pid != uap->pid && p->p_pgid != -uap->pid)
430 			continue;
431 
432 		/* This special case handles a kthread spawned by linux_clone
433 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid functions
434 		 * need to be able to distinguish between waiting on a process and
435 		 * waiting on a thread.  It is a thread if p_sigparent is not SIGCHLD,
436 		 * and the WLINUXCLONE option signifies we want to wait for threads
437 		 * and not processes.
438 		 */
439 		if ((p->p_sigparent != SIGCHLD) ^ ((uap->options & WLINUXCLONE) != 0))
440 			continue;
441 
442 		nfound++;
443 		if (p->p_stat == SZOMB) {
444 			/*
445 			 * The process's thread may still be in the middle
446 			 * of switching away, we can't rip its stack out from
447 			 * under it until TDF_RUNNING clears!
448 			 *
449 			 * YYY no wakeup occurs so we depend on the timeout.
450 			 */
451 			if ((p->p_thread->td_flags & TDF_RUNNING) != 0) {
452 				tsleep(p->p_thread, 0, "reap", 1);
453 				goto loop;
454 			}
455 
456 			/*
457 			 * Other kernel threads may be in the middle of
458 			 * accessing the proc.  For example, kern/kern_proc.c
459 			 * could be blocked writing proc data to a sysctl.
460 			 * At the moment, if this occurs, we are not woken
461 			 * up and rely on a one-second retry.
462 			 */
463 			if (p->p_lock) {
464 				printf("Diagnostic: waiting for p_lock\n");
465 				while (p->p_lock)
466 					tsleep(p, 0, "reap2", hz);
467 			}
468 			lwkt_wait_free(p->p_thread);
469 
470 			/* charge childs scheduling cpu usage to parent */
471 			if (curproc->p_pid != 1) {
472 				curproc->p_estcpu =
473 				    ESTCPULIM(curproc->p_estcpu + p->p_estcpu);
474 			}
475 
476 			uap->sysmsg_fds[0] = p->p_pid;
477 #ifdef COMPAT_43
478 			if (compat)
479 				uap->sysmsg_fds[1] = p->p_xstat;
480 			else
481 #endif
482 			if (uap->status) {
483 				status = p->p_xstat;	/* convert to int */
484 				if ((error = copyout((caddr_t)&status,
485 				    (caddr_t)uap->status, sizeof(status))))
486 					return (error);
487 			}
488 			if (uap->rusage && (error = copyout((caddr_t)p->p_ru,
489 			    (caddr_t)uap->rusage, sizeof (struct rusage))))
490 				return (error);
491 			/*
492 			 * If we got the child via a ptrace 'attach',
493 			 * we need to give it back to the old parent.
494 			 */
495 			if (p->p_oppid && (t = pfind(p->p_oppid))) {
496 				p->p_oppid = 0;
497 				proc_reparent(p, t);
498 				psignal(t, SIGCHLD);
499 				wakeup((caddr_t)t);
500 				return (0);
501 			}
502 			p->p_xstat = 0;
503 			ruadd(&q->p_stats->p_cru, p->p_ru);
504 			FREE(p->p_ru, M_ZOMBIE);
505 			p->p_ru = NULL;
506 
507 			/*
508 			 * Decrement the count of procs running with this uid.
509 			 */
510 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
511 
512 			/*
513 			 * Free up credentials.
514 			 */
515 			crfree(p->p_ucred);
516 			p->p_ucred = NULL;
517 
518 			/*
519 			 * Remove unused arguments
520 			 */
521 			if (p->p_args && --p->p_args->ar_ref == 0)
522 				FREE(p->p_args, M_PARGS);
523 
524 			/*
525 			 * Finally finished with old proc entry.
526 			 * Unlink it from its process group and free it.
527 			 */
528 			leavepgrp(p);
529 			LIST_REMOVE(p, p_list);	/* off zombproc */
530 			LIST_REMOVE(p, p_sibling);
531 
532 			if (--p->p_procsig->ps_refcnt == 0) {
533 				if (p->p_sigacts != &p->p_addr->u_sigacts)
534 					FREE(p->p_sigacts, M_SUBPROC);
535 			        FREE(p->p_procsig, M_SUBPROC);
536 				p->p_procsig = NULL;
537 			}
538 
539 			vm_waitproc(p);
540 			zfree(proc_zone, p);
541 			nprocs--;
542 			return (0);
543 		}
544 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
545 		    (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
546 			p->p_flag |= P_WAITED;
547 			uap->sysmsg_fds[0] = p->p_pid;
548 #ifdef COMPAT_43
549 			if (compat) {
550 				uap->sysmsg_fds[1] = W_STOPCODE(p->p_xstat);
551 				error = 0;
552 			} else
553 #endif
554 			if (uap->status) {
555 				status = W_STOPCODE(p->p_xstat);
556 				error = copyout((caddr_t)&status,
557 					(caddr_t)uap->status, sizeof(status));
558 			} else
559 				error = 0;
560 			return (error);
561 		}
562 	}
563 	if (nfound == 0)
564 		return (ECHILD);
565 	if (uap->options & WNOHANG) {
566 		uap->sysmsg_fds[0] = 0;
567 		return (0);
568 	}
569 	if ((error = tsleep((caddr_t)q, PCATCH, "wait", 0)))
570 		return (error);
571 	goto loop;
572 }
573 
574 /*
575  * make process 'parent' the new parent of process 'child'.
576  */
577 void
578 proc_reparent(child, parent)
579 	struct proc *child;
580 	struct proc *parent;
581 {
582 
583 	if (child->p_pptr == parent)
584 		return;
585 
586 	LIST_REMOVE(child, p_sibling);
587 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
588 	child->p_pptr = parent;
589 }
590 
591 /*
592  * The next two functions are to handle adding/deleting items on the
593  * exit callout list
594  *
595  * at_exit():
596  * Take the arguments given and put them onto the exit callout list,
597  * However first make sure that it's not already there.
598  * returns 0 on success.
599  */
600 
601 int
602 at_exit(function)
603 	exitlist_fn function;
604 {
605 	struct exitlist *ep;
606 
607 #ifdef INVARIANTS
608 	/* Be noisy if the programmer has lost track of things */
609 	if (rm_at_exit(function))
610 		printf("WARNING: exit callout entry (%p) already present\n",
611 		    function);
612 #endif
613 	ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
614 	if (ep == NULL)
615 		return (ENOMEM);
616 	ep->function = function;
617 	TAILQ_INSERT_TAIL(&exit_list, ep, next);
618 	return (0);
619 }
620 
621 /*
622  * Scan the exit callout list for the given item and remove it.
623  * Returns the number of items removed (0 or 1)
624  */
625 int
626 rm_at_exit(function)
627 	exitlist_fn function;
628 {
629 	struct exitlist *ep;
630 
631 	TAILQ_FOREACH(ep, &exit_list, next) {
632 		if (ep->function == function) {
633 			TAILQ_REMOVE(&exit_list, ep, next);
634 			free(ep, M_ATEXIT);
635 			return(1);
636 		}
637 	}
638 	return (0);
639 }
640 
641 void check_sigacts (void)
642 {
643 	struct proc *p = curproc;
644 	struct sigacts *pss;
645 	int s;
646 
647 	if (p->p_procsig->ps_refcnt == 1 &&
648 	    p->p_sigacts != &p->p_addr->u_sigacts) {
649 		pss = p->p_sigacts;
650 		s = splhigh();
651 		p->p_addr->u_sigacts = *pss;
652 		p->p_sigacts = &p->p_addr->u_sigacts;
653 		splx(s);
654 		FREE(pss, M_SUBPROC);
655 	}
656 }
657 
658