xref: /dflybsd-src/sys/kern/kern_exit.c (revision cbebfd39b369a289776677fb72f2eb81722dd172)
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.44 2005/09/11 11:34:53 swildner 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 #include <sys/kern_syscall.h>
66 #include <sys/upcall.h>
67 #include <sys/caps.h>
68 
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <sys/lock.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_zone.h>
75 #include <vm/vm_extern.h>
76 #include <sys/user.h>
77 
78 #include <sys/thread2.h>
79 
80 /* Required to be non-static for SysVR4 emulator */
81 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
82 
83 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
84 
85 /*
86  * callout list for things to do at exit time
87  */
88 struct exitlist {
89 	exitlist_fn function;
90 	TAILQ_ENTRY(exitlist) next;
91 };
92 
93 TAILQ_HEAD(exit_list_head, exitlist);
94 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
95 
96 /*
97  * exit --
98  *	Death of process.
99  *
100  * SYS_EXIT_ARGS(int rval)
101  */
102 void
103 sys_exit(struct sys_exit_args *uap)
104 {
105 	exit1(W_EXITCODE(uap->rval, 0));
106 	/* NOTREACHED */
107 }
108 
109 /*
110  * Exit: deallocate address space and other resources, change proc state
111  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
112  * status and rusage for wait().  Check for child processes and orphan them.
113  */
114 void
115 exit1(int rv)
116 {
117 	struct proc *p = curproc;
118 	struct proc *q, *nq;
119 	struct vmspace *vm;
120 	struct vnode *vtmp;
121 	struct exitlist *ep;
122 
123 	if (p->p_pid == 1) {
124 		printf("init died (signal %d, exit %d)\n",
125 		    WTERMSIG(rv), WEXITSTATUS(rv));
126 		panic("Going nowhere without my init!");
127 	}
128 
129 	sysmsg_rundown(p, 1);
130 	caps_exit(p->p_thread);
131 	aio_proc_rundown(p);
132 
133 	/* are we a task leader? */
134 	if(p == p->p_leader) {
135         	struct kill_args killArgs;
136 		killArgs.signum = SIGKILL;
137 		q = p->p_peers;
138 		while(q) {
139 			killArgs.pid = q->p_pid;
140 			/*
141 		         * The interface for kill is better
142 			 * than the internal signal
143 			 */
144 			kill(&killArgs);
145 			nq = q;
146 			q = q->p_peers;
147 		}
148 		while (p->p_peers)
149 		  tsleep((caddr_t)p, 0, "exit1", 0);
150 	}
151 
152 #ifdef PGINPROF
153 	vmsizmon();
154 #endif
155 	STOPEVENT(p, S_EXIT, rv);
156 	wakeup(&p->p_stype);	/* Wakeup anyone in procfs' PIOCWAIT */
157 
158 	/*
159 	 * Check if any loadable modules need anything done at process exit.
160 	 * e.g. SYSV IPC stuff
161 	 * XXX what if one of these generates an error?
162 	 */
163 	TAILQ_FOREACH(ep, &exit_list, next)
164 		(*ep->function)(p->p_thread);
165 
166 	if (p->p_flag & P_PROFIL)
167 		stopprofclock(p);
168 	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
169 		M_ZOMBIE, M_WAITOK);
170 	/*
171 	 * If parent is waiting for us to exit or exec,
172 	 * P_PPWAIT is set; we will wakeup the parent below.
173 	 */
174 	p->p_flag &= ~(P_TRACED | P_PPWAIT);
175 	p->p_flag |= P_WEXIT;
176 	SIGEMPTYSET(p->p_siglist);
177 	if (timevalisset(&p->p_realtimer.it_value))
178 		callout_stop(&p->p_ithandle);
179 
180 	/*
181 	 * Reset any sigio structures pointing to us as a result of
182 	 * F_SETOWN with our pid.
183 	 */
184 	funsetownlst(&p->p_sigiolst);
185 
186 	/*
187 	 * Close open files and release open-file table.
188 	 * This may block!
189 	 */
190 	fdfree(p);
191 	p->p_fd = NULL;
192 
193 	if(p->p_leader->p_peers) {
194 		q = p->p_leader;
195 		while(q->p_peers != p)
196 			q = q->p_peers;
197 		q->p_peers = p->p_peers;
198 		wakeup((caddr_t)p->p_leader);
199 	}
200 
201 	/*
202 	 * XXX Shutdown SYSV semaphores
203 	 */
204 	semexit(p);
205 
206 	KKASSERT(p->p_numposixlocks == 0);
207 
208 	/* The next two chunks should probably be moved to vmspace_exit. */
209 	vm = p->p_vmspace;
210 
211 	/*
212 	 * Release upcalls associated with this process
213 	 */
214 	if (vm->vm_upcalls)
215 		upc_release(vm, p);
216 
217 	/*
218 	 * Release user portion of address space.
219 	 * This releases references to vnodes,
220 	 * which could cause I/O if the file has been unlinked.
221 	 * Need to do this early enough that we can still sleep.
222 	 * Can't free the entire vmspace as the kernel stack
223 	 * may be mapped within that space also.
224 	 *
225 	 * Processes sharing the same vmspace may exit in one order, and
226 	 * get cleaned up by vmspace_exit() in a different order.  The
227 	 * last exiting process to reach this point releases as much of
228 	 * the environment as it can, and the last process cleaned up
229 	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
230 	 * remainder.
231 	 */
232 	++vm->vm_exitingcnt;
233 	if (--vm->vm_refcnt == 0) {
234 		shmexit(vm);
235 		pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
236 		    VM_MAXUSER_ADDRESS);
237 		(void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
238 		    VM_MAXUSER_ADDRESS);
239 	}
240 
241 	if (SESS_LEADER(p)) {
242 		struct session *sp = p->p_session;
243 		struct vnode *vp;
244 
245 		if (sp->s_ttyvp) {
246 			/*
247 			 * We are the controlling process.  Signal the
248 			 * foreground process group, drain the controlling
249 			 * terminal, and revoke access to the controlling
250 			 * terminal.
251 			 *
252 			 * NOTE: while waiting for the process group to exit
253 			 * it is possible that one of the processes in the
254 			 * group will revoke the tty, so we have to recheck.
255 			 */
256 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
257 				if (sp->s_ttyp->t_pgrp)
258 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
259 				(void) ttywait(sp->s_ttyp);
260 				/*
261 				 * The tty could have been revoked
262 				 * if we blocked.
263 				 */
264 				if ((vp = sp->s_ttyvp) != NULL) {
265 					ttyclosesession(sp, 0);
266 					if (vx_lock(vp) == 0) {
267 						VOP_REVOKE(vp, REVOKEALL);
268 						vx_unlock(vp);
269 					}
270 					vrele(vp);	/* s_ttyvp ref */
271 				}
272 			}
273 			/*
274 			 * Release the tty.  If someone has it open via
275 			 * /dev/tty then close it (since they no longer can
276 			 * once we've NULL'd it out).
277 			 */
278 			if (sp->s_ttyvp)
279 				ttyclosesession(sp, 1);
280 			/*
281 			 * s_ttyp is not zero'd; we use this to indicate
282 			 * that the session once had a controlling terminal.
283 			 * (for logging and informational purposes)
284 			 */
285 		}
286 		sp->s_leader = NULL;
287 	}
288 	fixjobc(p, p->p_pgrp, 0);
289 	(void)acct_process(p);
290 #ifdef KTRACE
291 	/*
292 	 * release trace file
293 	 */
294 	p->p_traceflag = 0;	/* don't trace the vrele() */
295 	if ((vtmp = p->p_tracep) != NULL) {
296 		p->p_tracep = NULL;
297 		vrele(vtmp);
298 	}
299 #endif
300 	/*
301 	 * Release reference to text vnode
302 	 */
303 	if ((vtmp = p->p_textvp) != NULL) {
304 		p->p_textvp = NULL;
305 		vrele(vtmp);
306 	}
307 
308 	/*
309 	 * Once we set SZOMB the process can get reaped.  The wait1 code
310 	 * will also wait for TDF_RUNNING to be cleared in the thread's flags,
311 	 * indicating that it has been completely switched out.
312 	 */
313 
314 	/*
315 	 * Remove proc from allproc queue and pidhash chain.
316 	 * Place onto zombproc.  Unlink from parent's child list.
317 	 */
318 	LIST_REMOVE(p, p_list);
319 	LIST_INSERT_HEAD(&zombproc, p, p_list);
320 	p->p_stat = SZOMB;
321 
322 	LIST_REMOVE(p, p_hash);
323 
324 	q = LIST_FIRST(&p->p_children);
325 	if (q)		/* only need this if any child is S_ZOMB */
326 		wakeup((caddr_t) initproc);
327 	for (; q != 0; q = nq) {
328 		nq = LIST_NEXT(q, p_sibling);
329 		LIST_REMOVE(q, p_sibling);
330 		LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
331 		q->p_pptr = initproc;
332 		q->p_sigparent = SIGCHLD;
333 		/*
334 		 * Traced processes are killed
335 		 * since their existence means someone is screwing up.
336 		 */
337 		if (q->p_flag & P_TRACED) {
338 			q->p_flag &= ~P_TRACED;
339 			psignal(q, SIGKILL);
340 		}
341 	}
342 
343 	/*
344 	 * Save exit status and final rusage info, adding in child rusage
345 	 * info and self times.
346 	 */
347 	p->p_xstat = rv;
348 	*p->p_ru = p->p_stats->p_ru;
349 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
350 	ruadd(p->p_ru, &p->p_stats->p_cru);
351 
352 	/*
353 	 * notify interested parties of our demise.
354 	 */
355 	KNOTE(&p->p_klist, NOTE_EXIT);
356 
357 	/*
358 	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
359 	 * flag set, notify process 1 instead (and hope it will handle
360 	 * this situation).
361 	 */
362 	if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
363 		struct proc *pp = p->p_pptr;
364 		proc_reparent(p, initproc);
365 		/*
366 		 * If this was the last child of our parent, notify
367 		 * parent, so in case he was wait(2)ing, he will
368 		 * continue.
369 		 */
370 		if (LIST_EMPTY(&pp->p_children))
371 			wakeup((caddr_t)pp);
372 	}
373 
374 	if (p->p_sigparent && p->p_pptr != initproc) {
375 	        psignal(p->p_pptr, p->p_sigparent);
376 	} else {
377 	        psignal(p->p_pptr, SIGCHLD);
378 	}
379 
380 	wakeup((caddr_t)p->p_pptr);
381 	/*
382 	 * cpu_exit is responsible for clearing curproc, since
383 	 * it is heavily integrated with the thread/switching sequence.
384 	 *
385 	 * Other substructures are freed from wait().
386 	 */
387 	if (--p->p_limit->p_refcnt == 0) {
388 		FREE(p->p_limit, M_SUBPROC);
389 		p->p_limit = NULL;
390 	}
391 
392 	/*
393 	 * Release the current user process designation on the process so
394 	 * the userland scheduler can work in someone else.
395 	 */
396 	p->p_usched->release_curproc(p);
397 
398 	/*
399 	 * Finally, call machine-dependent code to release the remaining
400 	 * resources including address space, the kernel stack and pcb.
401 	 * The address space is released by "vmspace_free(p->p_vmspace)";
402 	 * This is machine-dependent, as we may have to change stacks
403 	 * or ensure that the current one isn't reallocated before we
404 	 * finish.  cpu_exit will end with a call to cpu_switch(), finishing
405 	 * our execution (pun intended).
406 	 */
407 	cpu_proc_exit();
408 }
409 
410 int
411 wait4(struct wait_args *uap)
412 {
413 	struct rusage rusage;
414 	int error, status;
415 
416 	error = kern_wait(uap->pid, uap->status ? &status : NULL,
417 	    uap->options, uap->rusage ? &rusage : NULL, &uap->sysmsg_fds[0]);
418 
419 	if (error == 0 && uap->status)
420 		error = copyout(&status, uap->status, sizeof(*uap->status));
421 	if (error == 0 && uap->rusage)
422 		error = copyout(&rusage, uap->rusage, sizeof(*uap->rusage));
423 	return (error);
424 }
425 
426 /*
427  * wait1()
428  *
429  * wait_args(int pid, int *status, int options, struct rusage *rusage)
430  */
431 int
432 kern_wait(pid_t pid, int *status, int options, struct rusage *rusage, int *res)
433 {
434 	struct thread *td = curthread;
435 	struct proc *q = td->td_proc;
436 	struct proc *p, *t;
437 	int nfound, error;
438 
439 	if (pid == 0)
440 		pid = -q->p_pgid;
441 	if (options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
442 		return (EINVAL);
443 loop:
444 	nfound = 0;
445 	LIST_FOREACH(p, &q->p_children, p_sibling) {
446 		if (pid != WAIT_ANY &&
447 		    p->p_pid != pid && p->p_pgid != -pid)
448 			continue;
449 
450 		/* This special case handles a kthread spawned by linux_clone
451 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
452 		 * functions need to be able to distinguish between waiting
453 		 * on a process and waiting on a thread.  It is a thread if
454 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
455 		 * signifies we want to wait for threads and not processes.
456 		 */
457 		if ((p->p_sigparent != SIGCHLD) ^
458 		    ((options & WLINUXCLONE) != 0)) {
459 			continue;
460 		}
461 
462 		nfound++;
463 		if (p->p_stat == SZOMB) {
464 			/*
465 			 * The process's thread may still be in the middle
466 			 * of switching away, we can't rip its stack out from
467 			 * under it until TDF_RUNNING clears!
468 			 *
469 			 * YYY no wakeup occurs so we depend on the timeout.
470 			 */
471 			if ((p->p_thread->td_flags & TDF_RUNNING) != 0) {
472 				tsleep(p->p_thread, 0, "reap", 1);
473 				goto loop;
474 			}
475 
476 			/*
477 			 * Other kernel threads may be in the middle of
478 			 * accessing the proc.  For example, kern/kern_proc.c
479 			 * could be blocked writing proc data to a sysctl.
480 			 * At the moment, if this occurs, we are not woken
481 			 * up and rely on a one-second retry.
482 			 */
483 			if (p->p_lock) {
484 				while (p->p_lock)
485 					tsleep(p, 0, "reap2", hz);
486 			}
487 			lwkt_wait_free(p->p_thread);
488 
489 			/* scheduling hook for heuristic */
490 			p->p_usched->heuristic_exiting(q, p);
491 
492 			/* Take care of our return values. */
493 			*res = p->p_pid;
494 			if (status)
495 				*status = p->p_xstat;
496 			if (rusage)
497 				*rusage = *p->p_ru;
498 			/*
499 			 * If we got the child via a ptrace 'attach',
500 			 * we need to give it back to the old parent.
501 			 */
502 			if (p->p_oppid && (t = pfind(p->p_oppid))) {
503 				p->p_oppid = 0;
504 				proc_reparent(p, t);
505 				psignal(t, SIGCHLD);
506 				wakeup((caddr_t)t);
507 				return (0);
508 			}
509 			p->p_xstat = 0;
510 			ruadd(&q->p_stats->p_cru, p->p_ru);
511 			FREE(p->p_ru, M_ZOMBIE);
512 			p->p_ru = NULL;
513 
514 			/*
515 			 * Decrement the count of procs running with this uid.
516 			 */
517 			chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
518 
519 			/*
520 			 * Free up credentials.
521 			 */
522 			crfree(p->p_ucred);
523 			p->p_ucred = NULL;
524 
525 			/*
526 			 * Remove unused arguments
527 			 */
528 			if (p->p_args && --p->p_args->ar_ref == 0)
529 				FREE(p->p_args, M_PARGS);
530 
531 			/*
532 			 * Finally finished with old proc entry.
533 			 * Unlink it from its process group and free it.
534 			 */
535 			leavepgrp(p);
536 			LIST_REMOVE(p, p_list);	/* off zombproc */
537 			LIST_REMOVE(p, p_sibling);
538 
539 			if (--p->p_procsig->ps_refcnt == 0) {
540 				if (p->p_sigacts != &p->p_addr->u_sigacts)
541 					FREE(p->p_sigacts, M_SUBPROC);
542 			        FREE(p->p_procsig, M_SUBPROC);
543 				p->p_procsig = NULL;
544 			}
545 
546 			vm_waitproc(p);
547 			zfree(proc_zone, p);
548 			nprocs--;
549 			return (0);
550 		}
551 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
552 		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
553 			p->p_flag |= P_WAITED;
554 
555 			*res = p->p_pid;
556 			if (status)
557 				*status = W_STOPCODE(p->p_xstat);
558 			/* Zero rusage so we get something consistent. */
559 			if (rusage)
560 				bzero(rusage, sizeof(rusage));
561 			return (0);
562 		}
563 	}
564 	if (nfound == 0)
565 		return (ECHILD);
566 	if (options & WNOHANG) {
567 		*res = 0;
568 		return (0);
569 	}
570 	error = tsleep((caddr_t)q, PCATCH, "wait", 0);
571 	if (error)
572 		return (error);
573 	goto loop;
574 }
575 
576 /*
577  * make process 'parent' the new parent of process 'child'.
578  */
579 void
580 proc_reparent(struct proc *child, 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(exitlist_fn function)
603 {
604 	struct exitlist *ep;
605 
606 #ifdef INVARIANTS
607 	/* Be noisy if the programmer has lost track of things */
608 	if (rm_at_exit(function))
609 		printf("WARNING: exit callout entry (%p) already present\n",
610 		    function);
611 #endif
612 	ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
613 	if (ep == NULL)
614 		return (ENOMEM);
615 	ep->function = function;
616 	TAILQ_INSERT_TAIL(&exit_list, ep, next);
617 	return (0);
618 }
619 
620 /*
621  * Scan the exit callout list for the given item and remove it.
622  * Returns the number of items removed (0 or 1)
623  */
624 int
625 rm_at_exit(exitlist_fn function)
626 {
627 	struct exitlist *ep;
628 
629 	TAILQ_FOREACH(ep, &exit_list, next) {
630 		if (ep->function == function) {
631 			TAILQ_REMOVE(&exit_list, ep, next);
632 			free(ep, M_ATEXIT);
633 			return(1);
634 		}
635 	}
636 	return (0);
637 }
638 
639 void
640 check_sigacts(void)
641 {
642 	struct proc *p = curproc;
643 	struct sigacts *pss;
644 
645 	if (p->p_procsig->ps_refcnt == 1 &&
646 	    p->p_sigacts != &p->p_addr->u_sigacts) {
647 		pss = p->p_sigacts;
648 		crit_enter();
649 		p->p_addr->u_sigacts = *pss;
650 		p->p_sigacts = &p->p_addr->u_sigacts;
651 		crit_exit();
652 		FREE(pss, M_SUBPROC);
653 	}
654 }
655 
656