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