xref: /titanic_44/usr/src/uts/common/os/exit.c (revision 16ba0fac26f672b18447f2e17a2f91f14ed3ce40)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/sysmacros.h>
32 #include <sys/systm.h>
33 #include <sys/cred.h>
34 #include <sys/user.h>
35 #include <sys/errno.h>
36 #include <sys/proc.h>
37 #include <sys/ucontext.h>
38 #include <sys/procfs.h>
39 #include <sys/vnode.h>
40 #include <sys/acct.h>
41 #include <sys/var.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/wait.h>
45 #include <sys/siginfo.h>
46 #include <sys/procset.h>
47 #include <sys/class.h>
48 #include <sys/file.h>
49 #include <sys/session.h>
50 #include <sys/kmem.h>
51 #include <sys/vtrace.h>
52 #include <sys/prsystm.h>
53 #include <sys/ipc.h>
54 #include <sys/sem_impl.h>
55 #include <c2/audit.h>
56 #include <sys/aio_impl.h>
57 #include <vm/as.h>
58 #include <sys/poll.h>
59 #include <sys/door.h>
60 #include <sys/lwpchan_impl.h>
61 #include <sys/utrap.h>
62 #include <sys/task.h>
63 #include <sys/exacct.h>
64 #include <sys/cyclic.h>
65 #include <sys/schedctl.h>
66 #include <sys/rctl.h>
67 #include <sys/contract_impl.h>
68 #include <sys/contract/process_impl.h>
69 #include <sys/list.h>
70 #include <sys/dtrace.h>
71 #include <sys/pool.h>
72 #include <sys/sdt.h>
73 #include <sys/corectl.h>
74 #include <sys/brand.h>
75 #include <sys/libc_kernel.h>
76 
77 /*
78  * convert code/data pair into old style wait status
79  */
80 int
81 wstat(int code, int data)
82 {
83 	int stat = (data & 0377);
84 
85 	switch (code) {
86 	case CLD_EXITED:
87 		stat <<= 8;
88 		break;
89 	case CLD_DUMPED:
90 		stat |= WCOREFLG;
91 		break;
92 	case CLD_KILLED:
93 		break;
94 	case CLD_TRAPPED:
95 	case CLD_STOPPED:
96 		stat <<= 8;
97 		stat |= WSTOPFLG;
98 		break;
99 	case CLD_CONTINUED:
100 		stat = WCONTFLG;
101 		break;
102 	default:
103 		cmn_err(CE_PANIC, "wstat: bad code");
104 		/* NOTREACHED */
105 	}
106 	return (stat);
107 }
108 
109 static char *
110 exit_reason(char *buf, size_t bufsz, int what, int why)
111 {
112 	switch (why) {
113 	case CLD_EXITED:
114 		(void) snprintf(buf, bufsz, "exited with status %d", what);
115 		break;
116 	case CLD_KILLED:
117 		(void) snprintf(buf, bufsz, "exited on fatal signal %d", what);
118 		break;
119 	case CLD_DUMPED:
120 		(void) snprintf(buf, bufsz, "core dumped on signal %d", what);
121 		break;
122 	default:
123 		(void) snprintf(buf, bufsz, "encountered unknown error "
124 		    "(%d, %d)", why, what);
125 		break;
126 	}
127 
128 	return (buf);
129 }
130 
131 /*
132  * exit system call: pass back caller's arg.
133  */
134 void
135 rexit(int rval)
136 {
137 	exit(CLD_EXITED, rval);
138 }
139 
140 /*
141  * Called by proc_exit() when a zone's init exits, presumably because
142  * it failed.  As long as the given zone is still in the "running"
143  * state, we will re-exec() init, but first we need to reset things
144  * which are usually inherited across exec() but will break init's
145  * assumption that it is being exec()'d from a virgin process.  Most
146  * importantly this includes closing all file descriptors (exec only
147  * closes those marked close-on-exec) and resetting signals (exec only
148  * resets handled signals, and we need to clear any signals which
149  * killed init).  Anything else that exec(2) says would be inherited,
150  * but would affect the execution of init, needs to be reset.
151  */
152 static int
153 restart_init(int what, int why)
154 {
155 	kthread_t *t = curthread;
156 	klwp_t *lwp = ttolwp(t);
157 	proc_t *p = ttoproc(t);
158 	user_t *up = PTOU(p);
159 
160 	vnode_t *oldcd, *oldrd;
161 	int i, err;
162 	char reason_buf[64];
163 
164 	/*
165 	 * Let zone admin (and global zone admin if this is for a non-global
166 	 * zone) know that init has failed and will be restarted.
167 	 */
168 	zcmn_err(p->p_zone->zone_id, CE_WARN,
169 	    "init(1M) %s: restarting automatically",
170 	    exit_reason(reason_buf, sizeof (reason_buf), what, why));
171 
172 	if (!INGLOBALZONE(p)) {
173 		cmn_err(CE_WARN, "init(1M) for zone %s (pid %d) %s: "
174 		    "restarting automatically",
175 		    p->p_zone->zone_name, p->p_pid, reason_buf);
176 	}
177 
178 	/*
179 	 * Remove any fpollinfo_t's for this (last) thread from our file
180 	 * descriptors so closeall() can ASSERT() that they're all gone.
181 	 * Then close all open file descriptors in the process.
182 	 */
183 	pollcleanup();
184 	closeall(P_FINFO(p));
185 
186 	/*
187 	 * Grab p_lock and begin clearing miscellaneous global process
188 	 * state that needs to be reset before we exec the new init(1M).
189 	 */
190 
191 	mutex_enter(&p->p_lock);
192 	prbarrier(p);
193 
194 	p->p_flag &= ~(SKILLED | SEXTKILLED | SEXITING | SDOCORE);
195 	up->u_cmask = CMASK;
196 
197 	sigemptyset(&t->t_hold);
198 	sigemptyset(&t->t_sig);
199 	sigemptyset(&t->t_extsig);
200 
201 	sigemptyset(&p->p_sig);
202 	sigemptyset(&p->p_extsig);
203 
204 	sigdelq(p, t, 0);
205 	sigdelq(p, NULL, 0);
206 
207 	if (p->p_killsqp) {
208 		siginfofree(p->p_killsqp);
209 		p->p_killsqp = NULL;
210 	}
211 
212 	/*
213 	 * Reset any signals that are ignored back to the default disposition.
214 	 * Other u_signal members will be cleared when exec calls sigdefault().
215 	 */
216 	for (i = 1; i < NSIG; i++) {
217 		if (up->u_signal[i - 1] == SIG_IGN) {
218 			up->u_signal[i - 1] = SIG_DFL;
219 			sigemptyset(&up->u_sigmask[i - 1]);
220 		}
221 	}
222 
223 	/*
224 	 * Clear the current signal, any signal info associated with it, and
225 	 * any signal information from contracts and/or contract templates.
226 	 */
227 	lwp->lwp_cursig = 0;
228 	lwp->lwp_extsig = 0;
229 	if (lwp->lwp_curinfo != NULL) {
230 		siginfofree(lwp->lwp_curinfo);
231 		lwp->lwp_curinfo = NULL;
232 	}
233 	lwp_ctmpl_clear(lwp);
234 
235 	/*
236 	 * Reset both the process root directory and the current working
237 	 * directory to the root of the zone just as we do during boot.
238 	 */
239 	VN_HOLD(p->p_zone->zone_rootvp);
240 	oldrd = up->u_rdir;
241 	up->u_rdir = p->p_zone->zone_rootvp;
242 
243 	VN_HOLD(p->p_zone->zone_rootvp);
244 	oldcd = up->u_cdir;
245 	up->u_cdir = p->p_zone->zone_rootvp;
246 
247 	if (up->u_cwd != NULL) {
248 		refstr_rele(up->u_cwd);
249 		up->u_cwd = NULL;
250 	}
251 
252 	mutex_exit(&p->p_lock);
253 
254 	if (oldrd != NULL)
255 		VN_RELE(oldrd);
256 	if (oldcd != NULL)
257 		VN_RELE(oldcd);
258 
259 	/* Free the controlling tty.  (freectty() always assumes curproc.) */
260 	ASSERT(p == curproc);
261 	(void) freectty(B_TRUE);
262 
263 	/*
264 	 * Now exec() the new init(1M) on top of the current process.  If we
265 	 * succeed, the caller will treat this like a successful system call.
266 	 * If we fail, we issue messages and the caller will proceed with exit.
267 	 */
268 	err = exec_init(p->p_zone->zone_initname, NULL);
269 
270 	if (err == 0)
271 		return (0);
272 
273 	zcmn_err(p->p_zone->zone_id, CE_WARN,
274 	    "failed to restart init(1M) (err=%d): system reboot required", err);
275 
276 	if (!INGLOBALZONE(p)) {
277 		cmn_err(CE_WARN, "failed to restart init(1M) for zone %s "
278 		    "(pid %d, err=%d): zoneadm(1M) boot required",
279 		    p->p_zone->zone_name, p->p_pid, err);
280 	}
281 
282 	return (-1);
283 }
284 
285 /*
286  * Release resources.
287  * Enter zombie state.
288  * Wake up parent and init processes,
289  * and dispose of children.
290  */
291 void
292 exit(int why, int what)
293 {
294 	/*
295 	 * If proc_exit() fails, then some other lwp in the process
296 	 * got there first.  We just have to call lwp_exit() to allow
297 	 * the other lwp to finish exiting the process.  Otherwise we're
298 	 * restarting init, and should return.
299 	 */
300 	if (proc_exit(why, what) != 0) {
301 		mutex_enter(&curproc->p_lock);
302 		ASSERT(curproc->p_flag & SEXITLWPS);
303 		lwp_exit();
304 		/* NOTREACHED */
305 	}
306 }
307 
308 /*
309  * Set the SEXITING flag on the process, after making sure /proc does
310  * not have it locked.  This is done in more places than proc_exit(),
311  * so it is a separate function.
312  */
313 void
314 proc_is_exiting(proc_t *p)
315 {
316 	mutex_enter(&p->p_lock);
317 	prbarrier(p);
318 	p->p_flag |= SEXITING;
319 	mutex_exit(&p->p_lock);
320 }
321 
322 /*
323  * Return value:
324  *   1 - exitlwps() failed, call (or continue) lwp_exit()
325  *   0 - restarting init.  Return through system call path
326  */
327 int
328 proc_exit(int why, int what)
329 {
330 	kthread_t *t = curthread;
331 	klwp_t *lwp = ttolwp(t);
332 	proc_t *p = ttoproc(t);
333 	zone_t *z = p->p_zone;
334 	timeout_id_t tmp_id;
335 	int rv;
336 	proc_t *q;
337 	task_t *tk;
338 	vnode_t *exec_vp, *execdir_vp, *cdir, *rdir;
339 	sigqueue_t *sqp;
340 	lwpdir_t *lwpdir;
341 	uint_t lwpdir_sz;
342 	tidhash_t *tidhash;
343 	uint_t tidhash_sz;
344 	ret_tidhash_t *ret_tidhash;
345 	refstr_t *cwd;
346 	hrtime_t hrutime, hrstime;
347 	int evaporate;
348 
349 	/*
350 	 * Stop and discard the process's lwps except for the current one,
351 	 * unless some other lwp beat us to it.  If exitlwps() fails then
352 	 * return and the calling lwp will call (or continue in) lwp_exit().
353 	 */
354 	proc_is_exiting(p);
355 	if (exitlwps(0) != 0)
356 		return (1);
357 
358 	mutex_enter(&p->p_lock);
359 	if (p->p_ttime > 0) {
360 		/*
361 		 * Account any remaining ticks charged to this process
362 		 * on its way out.
363 		 */
364 		(void) task_cpu_time_incr(p->p_task, p->p_ttime);
365 		p->p_ttime = 0;
366 	}
367 	mutex_exit(&p->p_lock);
368 
369 	DTRACE_PROC(lwp__exit);
370 	DTRACE_PROC1(exit, int, why);
371 
372 	/*
373 	 * Will perform any brand specific proc exit processing, since this
374 	 * is always the last lwp, will also perform lwp_exit and free brand
375 	 * data
376 	 */
377 	if (PROC_IS_BRANDED(p)) {
378 		lwp_detach_brand_hdlrs(lwp);
379 		brand_clearbrand(p);
380 	}
381 
382 	/*
383 	 * Don't let init exit unless zone_start_init() failed its exec, or
384 	 * we are shutting down the zone or the machine.
385 	 *
386 	 * Since we are single threaded, we don't need to lock the
387 	 * following accesses to zone_proc_initpid.
388 	 */
389 	if (p->p_pid == z->zone_proc_initpid) {
390 		if (z->zone_boot_err == 0 &&
391 		    zone_status_get(z) < ZONE_IS_SHUTTING_DOWN &&
392 		    zone_status_get(global_zone) < ZONE_IS_SHUTTING_DOWN &&
393 		    z->zone_restart_init == B_TRUE &&
394 		    restart_init(what, why) == 0)
395 			return (0);
396 		/*
397 		 * Since we didn't or couldn't restart init, we clear
398 		 * the zone's init state and proceed with exit
399 		 * processing.
400 		 */
401 		z->zone_proc_initpid = -1;
402 	}
403 
404 	/*
405 	 * Allocate a sigqueue now, before we grab locks.
406 	 * It will be given to sigcld(), below.
407 	 * Special case:  If we will be making the process disappear
408 	 * without a trace because it is either:
409 	 *	* an exiting SSYS process, or
410 	 *	* a posix_spawn() vfork child who requests it,
411 	 * we don't bother to allocate a useless sigqueue.
412 	 */
413 	evaporate = (p->p_flag & SSYS) || ((p->p_flag & SVFORK) &&
414 	    why == CLD_EXITED && what == _EVAPORATE);
415 	if (!evaporate)
416 		sqp = kmem_zalloc(sizeof (sigqueue_t), KM_SLEEP);
417 
418 	/*
419 	 * revoke any doors created by the process.
420 	 */
421 	if (p->p_door_list)
422 		door_exit();
423 
424 	/*
425 	 * Release schedctl data structures.
426 	 */
427 	if (p->p_pagep)
428 		schedctl_proc_cleanup();
429 
430 	/*
431 	 * make sure all pending kaio has completed.
432 	 */
433 	if (p->p_aio)
434 		aio_cleanup_exit();
435 
436 	/*
437 	 * discard the lwpchan cache.
438 	 */
439 	if (p->p_lcp != NULL)
440 		lwpchan_destroy_cache(0);
441 
442 	/*
443 	 * Clean up any DTrace helper actions or probes for the process.
444 	 */
445 	if (p->p_dtrace_helpers != NULL) {
446 		ASSERT(dtrace_helpers_cleanup != NULL);
447 		(*dtrace_helpers_cleanup)();
448 	}
449 
450 	/* untimeout the realtime timers */
451 	if (p->p_itimer != NULL)
452 		timer_exit();
453 
454 	if ((tmp_id = p->p_alarmid) != 0) {
455 		p->p_alarmid = 0;
456 		(void) untimeout(tmp_id);
457 	}
458 
459 	/*
460 	 * Remove any fpollinfo_t's for this (last) thread from our file
461 	 * descriptors so closeall() can ASSERT() that they're all gone.
462 	 */
463 	pollcleanup();
464 
465 	if (p->p_rprof_cyclic != CYCLIC_NONE) {
466 		mutex_enter(&cpu_lock);
467 		cyclic_remove(p->p_rprof_cyclic);
468 		mutex_exit(&cpu_lock);
469 	}
470 
471 	mutex_enter(&p->p_lock);
472 
473 	/*
474 	 * Clean up any DTrace probes associated with this process.
475 	 */
476 	if (p->p_dtrace_probes) {
477 		ASSERT(dtrace_fasttrap_exit_ptr != NULL);
478 		dtrace_fasttrap_exit_ptr(p);
479 	}
480 
481 	while ((tmp_id = p->p_itimerid) != 0) {
482 		p->p_itimerid = 0;
483 		mutex_exit(&p->p_lock);
484 		(void) untimeout(tmp_id);
485 		mutex_enter(&p->p_lock);
486 	}
487 
488 	lwp_cleanup();
489 
490 	/*
491 	 * We are about to exit; prevent our resource associations from
492 	 * being changed.
493 	 */
494 	pool_barrier_enter();
495 
496 	/*
497 	 * Block the process against /proc now that we have really
498 	 * acquired p->p_lock (to manipulate p_tlist at least).
499 	 */
500 	prbarrier(p);
501 
502 #ifdef	SUN_SRC_COMPAT
503 	if (code == CLD_KILLED)
504 		u.u_acflag |= AXSIG;
505 #endif
506 	sigfillset(&p->p_ignore);
507 	sigemptyset(&p->p_siginfo);
508 	sigemptyset(&p->p_sig);
509 	sigemptyset(&p->p_extsig);
510 	sigemptyset(&t->t_sig);
511 	sigemptyset(&t->t_extsig);
512 	sigemptyset(&p->p_sigmask);
513 	sigdelq(p, t, 0);
514 	lwp->lwp_cursig = 0;
515 	lwp->lwp_extsig = 0;
516 	p->p_flag &= ~(SKILLED | SEXTKILLED);
517 	if (lwp->lwp_curinfo) {
518 		siginfofree(lwp->lwp_curinfo);
519 		lwp->lwp_curinfo = NULL;
520 	}
521 
522 	t->t_proc_flag |= TP_LWPEXIT;
523 	ASSERT(p->p_lwpcnt == 1 && p->p_zombcnt == 0);
524 	prlwpexit(t);		/* notify /proc */
525 	lwp_hash_out(p, t->t_tid);
526 	prexit(p);
527 
528 	p->p_lwpcnt = 0;
529 	p->p_tlist = NULL;
530 	sigqfree(p);
531 	term_mstate(t);
532 	p->p_mterm = gethrtime();
533 
534 	exec_vp = p->p_exec;
535 	execdir_vp = p->p_execdir;
536 	p->p_exec = NULLVP;
537 	p->p_execdir = NULLVP;
538 	mutex_exit(&p->p_lock);
539 	if (exec_vp)
540 		VN_RELE(exec_vp);
541 	if (execdir_vp)
542 		VN_RELE(execdir_vp);
543 
544 	pr_free_watched_pages(p);
545 
546 	closeall(P_FINFO(p));
547 
548 	/* Free the controlling tty.  (freectty() always assumes curproc.) */
549 	ASSERT(p == curproc);
550 	(void) freectty(B_TRUE);
551 
552 #if defined(__sparc)
553 	if (p->p_utraps != NULL)
554 		utrap_free(p);
555 #endif
556 	if (p->p_semacct)			/* IPC semaphore exit */
557 		semexit(p);
558 	rv = wstat(why, what);
559 
560 	acct(rv & 0xff);
561 	exacct_commit_proc(p, rv);
562 
563 	/*
564 	 * Release any resources associated with C2 auditing
565 	 */
566 	if (audit_active) {
567 		/*
568 		 * audit exit system call
569 		 */
570 		audit_exit(why, what);
571 	}
572 
573 	/*
574 	 * Free address space.
575 	 */
576 	relvm();
577 
578 	/*
579 	 * Release held contracts.
580 	 */
581 	contract_exit(p);
582 
583 	/*
584 	 * Depart our encapsulating process contract.
585 	 */
586 	if ((p->p_flag & SSYS) == 0) {
587 		ASSERT(p->p_ct_process);
588 		contract_process_exit(p->p_ct_process, p, rv);
589 	}
590 
591 	/*
592 	 * Remove pool association, and block if requested by pool_do_bind.
593 	 */
594 	mutex_enter(&p->p_lock);
595 	ASSERT(p->p_pool->pool_ref > 0);
596 	atomic_add_32(&p->p_pool->pool_ref, -1);
597 	p->p_pool = pool_default;
598 	/*
599 	 * Now that our address space has been freed and all other threads
600 	 * in this process have exited, set the PEXITED pool flag.  This
601 	 * tells the pools subsystems to ignore this process if it was
602 	 * requested to rebind this process to a new pool.
603 	 */
604 	p->p_poolflag |= PEXITED;
605 	pool_barrier_exit();
606 	mutex_exit(&p->p_lock);
607 
608 	mutex_enter(&pidlock);
609 
610 	/*
611 	 * Delete this process from the newstate list of its parent. We
612 	 * will put it in the right place in the sigcld in the end.
613 	 */
614 	delete_ns(p->p_parent, p);
615 
616 	/*
617 	 * Reassign the orphans to the next of kin.
618 	 * Don't rearrange init's orphanage.
619 	 */
620 	if ((q = p->p_orphan) != NULL && p != proc_init) {
621 
622 		proc_t *nokp = p->p_nextofkin;
623 
624 		for (;;) {
625 			q->p_nextofkin = nokp;
626 			if (q->p_nextorph == NULL)
627 				break;
628 			q = q->p_nextorph;
629 		}
630 		q->p_nextorph = nokp->p_orphan;
631 		nokp->p_orphan = p->p_orphan;
632 		p->p_orphan = NULL;
633 	}
634 
635 	/*
636 	 * Reassign the children to init.
637 	 * Don't try to assign init's children to init.
638 	 */
639 	if ((q = p->p_child) != NULL && p != proc_init) {
640 		struct proc	*np;
641 		struct proc	*initp = proc_init;
642 		boolean_t	setzonetop = B_FALSE;
643 
644 		if (!INGLOBALZONE(curproc))
645 			setzonetop = B_TRUE;
646 
647 		pgdetach(p);
648 
649 		do {
650 			np = q->p_sibling;
651 			/*
652 			 * Delete it from its current parent new state
653 			 * list and add it to init new state list
654 			 */
655 			delete_ns(q->p_parent, q);
656 
657 			q->p_ppid = 1;
658 			q->p_pidflag &= ~(CLDNOSIGCHLD | CLDWAITPID);
659 			if (setzonetop) {
660 				mutex_enter(&q->p_lock);
661 				q->p_flag |= SZONETOP;
662 				mutex_exit(&q->p_lock);
663 			}
664 			q->p_parent = initp;
665 
666 			/*
667 			 * Since q will be the first child,
668 			 * it will not have a previous sibling.
669 			 */
670 			q->p_psibling = NULL;
671 			if (initp->p_child) {
672 				initp->p_child->p_psibling = q;
673 			}
674 			q->p_sibling = initp->p_child;
675 			initp->p_child = q;
676 			if (q->p_proc_flag & P_PR_PTRACE) {
677 				mutex_enter(&q->p_lock);
678 				sigtoproc(q, NULL, SIGKILL);
679 				mutex_exit(&q->p_lock);
680 			}
681 			/*
682 			 * sigcld() will add the child to parents
683 			 * newstate list.
684 			 */
685 			if (q->p_stat == SZOMB)
686 				sigcld(q, NULL);
687 		} while ((q = np) != NULL);
688 
689 		p->p_child = NULL;
690 		ASSERT(p->p_child_ns == NULL);
691 	}
692 
693 	TRACE_1(TR_FAC_PROC, TR_PROC_EXIT, "proc_exit: %p", p);
694 
695 	mutex_enter(&p->p_lock);
696 	CL_EXIT(curthread); /* tell the scheduler that curthread is exiting */
697 
698 	/*
699 	 * Have our task accummulate our resource usage data before they
700 	 * become contaminated by p_cacct etc., and before we renounce
701 	 * membership of the task.
702 	 *
703 	 * We do this regardless of whether or not task accounting is active.
704 	 * This is to avoid having nonsense data reported for this task if
705 	 * task accounting is subsequently enabled. The overhead is minimal;
706 	 * by this point, this process has accounted for the usage of all its
707 	 * LWPs. We nonetheless do the work here, and under the protection of
708 	 * pidlock, so that the movement of the process's usage to the task
709 	 * happens at the same time as the removal of the process from the
710 	 * task, from the point of view of exacct_snapshot_task_usage().
711 	 */
712 	exacct_update_task_mstate(p);
713 
714 	hrutime = mstate_aggr_state(p, LMS_USER);
715 	hrstime = mstate_aggr_state(p, LMS_SYSTEM);
716 	p->p_utime = (clock_t)NSEC_TO_TICK(hrutime) + p->p_cutime;
717 	p->p_stime = (clock_t)NSEC_TO_TICK(hrstime) + p->p_cstime;
718 
719 	p->p_acct[LMS_USER]	+= p->p_cacct[LMS_USER];
720 	p->p_acct[LMS_SYSTEM]	+= p->p_cacct[LMS_SYSTEM];
721 	p->p_acct[LMS_TRAP]	+= p->p_cacct[LMS_TRAP];
722 	p->p_acct[LMS_TFAULT]	+= p->p_cacct[LMS_TFAULT];
723 	p->p_acct[LMS_DFAULT]	+= p->p_cacct[LMS_DFAULT];
724 	p->p_acct[LMS_KFAULT]	+= p->p_cacct[LMS_KFAULT];
725 	p->p_acct[LMS_USER_LOCK] += p->p_cacct[LMS_USER_LOCK];
726 	p->p_acct[LMS_SLEEP]	+= p->p_cacct[LMS_SLEEP];
727 	p->p_acct[LMS_WAIT_CPU]	+= p->p_cacct[LMS_WAIT_CPU];
728 	p->p_acct[LMS_STOPPED]	+= p->p_cacct[LMS_STOPPED];
729 
730 	p->p_ru.minflt	+= p->p_cru.minflt;
731 	p->p_ru.majflt	+= p->p_cru.majflt;
732 	p->p_ru.nswap	+= p->p_cru.nswap;
733 	p->p_ru.inblock	+= p->p_cru.inblock;
734 	p->p_ru.oublock	+= p->p_cru.oublock;
735 	p->p_ru.msgsnd	+= p->p_cru.msgsnd;
736 	p->p_ru.msgrcv	+= p->p_cru.msgrcv;
737 	p->p_ru.nsignals += p->p_cru.nsignals;
738 	p->p_ru.nvcsw	+= p->p_cru.nvcsw;
739 	p->p_ru.nivcsw	+= p->p_cru.nivcsw;
740 	p->p_ru.sysc	+= p->p_cru.sysc;
741 	p->p_ru.ioch	+= p->p_cru.ioch;
742 
743 	p->p_stat = SZOMB;
744 	p->p_proc_flag &= ~P_PR_PTRACE;
745 	p->p_wdata = what;
746 	p->p_wcode = (char)why;
747 
748 	cdir = PTOU(p)->u_cdir;
749 	rdir = PTOU(p)->u_rdir;
750 	cwd = PTOU(p)->u_cwd;
751 
752 	ASSERT(cdir != NULL || p->p_parent == &p0);
753 
754 	/*
755 	 * Release resource controls, as they are no longer enforceable.
756 	 */
757 	rctl_set_free(p->p_rctls);
758 
759 	/*
760 	 * Give up task and project memberships.  Decrement tk_nlwps counter
761 	 * for our task.max-lwps resource control.  An extended accounting
762 	 * record, if that facility is active, is scheduled to be written.
763 	 * Zombie processes are false members of task0 for the remainder of
764 	 * their lifetime; no accounting information is recorded for them.
765 	 */
766 	tk = p->p_task;
767 
768 	mutex_enter(&p->p_zone->zone_nlwps_lock);
769 	tk->tk_nlwps--;
770 	tk->tk_proj->kpj_nlwps--;
771 	p->p_zone->zone_nlwps--;
772 	mutex_exit(&p->p_zone->zone_nlwps_lock);
773 	task_detach(p);
774 	p->p_task = task0p;
775 
776 	/*
777 	 * Clear the lwp directory and the lwpid hash table
778 	 * now that /proc can't bother us any more.
779 	 * We free the memory below, after dropping p->p_lock.
780 	 */
781 	lwpdir = p->p_lwpdir;
782 	lwpdir_sz = p->p_lwpdir_sz;
783 	tidhash = p->p_tidhash;
784 	tidhash_sz = p->p_tidhash_sz;
785 	ret_tidhash = p->p_ret_tidhash;
786 	p->p_lwpdir = NULL;
787 	p->p_lwpfree = NULL;
788 	p->p_lwpdir_sz = 0;
789 	p->p_tidhash = NULL;
790 	p->p_tidhash_sz = 0;
791 	p->p_ret_tidhash = NULL;
792 
793 	/*
794 	 * If the process has context ops installed, call the exit routine
795 	 * on behalf of this last remaining thread. Normally exitpctx() is
796 	 * called during thread_exit() or lwp_exit(), but because this is the
797 	 * last thread in the process, we must call it here. By the time
798 	 * thread_exit() is called (below), the association with the relevant
799 	 * process has been lost.
800 	 *
801 	 * We also free the context here.
802 	 */
803 	if (p->p_pctx) {
804 		kpreempt_disable();
805 		exitpctx(p);
806 		kpreempt_enable();
807 
808 		freepctx(p, 0);
809 	}
810 
811 	/*
812 	 * curthread's proc pointer is changed to point to the 'sched'
813 	 * process for the corresponding zone, except in the case when
814 	 * the exiting process is in fact a zsched instance, in which
815 	 * case the proc pointer is set to p0.  We do so, so that the
816 	 * process still points at the right zone when we call the VN_RELE()
817 	 * below.
818 	 *
819 	 * This is because curthread's original proc pointer can be freed as
820 	 * soon as the child sends a SIGCLD to its parent.  We use zsched so
821 	 * that for user processes, even in the final moments of death, the
822 	 * process is still associated with its zone.
823 	 */
824 	if (p != t->t_procp->p_zone->zone_zsched)
825 		t->t_procp = t->t_procp->p_zone->zone_zsched;
826 	else
827 		t->t_procp = &p0;
828 
829 	mutex_exit(&p->p_lock);
830 	if (!evaporate) {
831 		p->p_pidflag &= ~CLDPEND;
832 		sigcld(p, sqp);
833 	} else {
834 		/*
835 		 * Do what sigcld() would do if the disposition
836 		 * of the SIGCHLD signal were set to be ignored.
837 		 */
838 		cv_broadcast(&p->p_srwchan_cv);
839 		freeproc(p);
840 	}
841 	mutex_exit(&pidlock);
842 
843 	/*
844 	 * We don't release u_cdir and u_rdir until SZOMB is set.
845 	 * This protects us against dofusers().
846 	 */
847 	if (cdir)
848 		VN_RELE(cdir);
849 	if (rdir)
850 		VN_RELE(rdir);
851 	if (cwd)
852 		refstr_rele(cwd);
853 
854 	/*
855 	 * task_rele() may ultimately cause the zone to go away (or
856 	 * may cause the last user process in a zone to go away, which
857 	 * signals zsched to go away).  So prior to this call, we must
858 	 * no longer point at zsched.
859 	 */
860 	t->t_procp = &p0;
861 	task_rele(tk);
862 
863 	kmem_free(lwpdir, lwpdir_sz * sizeof (lwpdir_t));
864 	kmem_free(tidhash, tidhash_sz * sizeof (tidhash_t));
865 	while (ret_tidhash != NULL) {
866 		ret_tidhash_t *next = ret_tidhash->rth_next;
867 		kmem_free(ret_tidhash->rth_tidhash,
868 		    ret_tidhash->rth_tidhash_sz * sizeof (tidhash_t));
869 		kmem_free(ret_tidhash, sizeof (*ret_tidhash));
870 		ret_tidhash = next;
871 	}
872 
873 	lwp_pcb_exit();
874 
875 	thread_exit();
876 	/* NOTREACHED */
877 }
878 
879 /*
880  * Format siginfo structure for wait system calls.
881  */
882 void
883 winfo(proc_t *pp, k_siginfo_t *ip, int waitflag)
884 {
885 	ASSERT(MUTEX_HELD(&pidlock));
886 
887 	bzero(ip, sizeof (k_siginfo_t));
888 	ip->si_signo = SIGCLD;
889 	ip->si_code = pp->p_wcode;
890 	ip->si_pid = pp->p_pid;
891 	ip->si_ctid = PRCTID(pp);
892 	ip->si_zoneid = pp->p_zone->zone_id;
893 	ip->si_status = pp->p_wdata;
894 	ip->si_stime = pp->p_stime;
895 	ip->si_utime = pp->p_utime;
896 
897 	if (waitflag) {
898 		pp->p_wcode = 0;
899 		pp->p_wdata = 0;
900 		pp->p_pidflag &= ~CLDPEND;
901 	}
902 }
903 
904 /*
905  * Wait system call.
906  * Search for a terminated (zombie) child,
907  * finally lay it to rest, and collect its status.
908  * Look also for stopped children,
909  * and pass back status from them.
910  */
911 int
912 waitid(idtype_t idtype, id_t id, k_siginfo_t *ip, int options)
913 {
914 	int found;
915 	proc_t *cp, *pp;
916 	int proc_gone;
917 	int waitflag = !(options & WNOWAIT);
918 
919 	/*
920 	 * Obsolete flag, defined here only for binary compatibility
921 	 * with old statically linked executables.  Delete this when
922 	 * we no longer care about these old and broken applications.
923 	 */
924 #define	_WNOCHLD	0400
925 	options &= ~_WNOCHLD;
926 
927 	if (options == 0 || (options & ~WOPTMASK))
928 		return (EINVAL);
929 
930 	switch (idtype) {
931 	case P_PID:
932 	case P_PGID:
933 		if (id < 0 || id >= maxpid)
934 			return (EINVAL);
935 		/* FALLTHROUGH */
936 	case P_ALL:
937 		break;
938 	default:
939 		return (EINVAL);
940 	}
941 
942 	pp = ttoproc(curthread);
943 
944 	/*
945 	 * lock parent mutex so that sibling chain can be searched.
946 	 */
947 	mutex_enter(&pidlock);
948 
949 	/*
950 	 * if we are only looking for exited processes and child_ns list
951 	 * is empty no reason to look at all children.
952 	 */
953 	if (idtype == P_ALL &&
954 	    (options & ~WNOWAIT) == (WNOHANG | WEXITED) &&
955 	    pp->p_child_ns == NULL) {
956 		if (pp->p_child) {
957 			mutex_exit(&pidlock);
958 			bzero(ip, sizeof (k_siginfo_t));
959 			return (0);
960 		}
961 		mutex_exit(&pidlock);
962 		return (ECHILD);
963 	}
964 
965 	while (pp->p_child != NULL) {
966 
967 		proc_gone = 0;
968 
969 		for (cp = pp->p_child_ns; cp != NULL; cp = cp->p_sibling_ns) {
970 			if (idtype != P_PID && (cp->p_pidflag & CLDWAITPID))
971 				continue;
972 			if (idtype == P_PID && id != cp->p_pid)
973 				continue;
974 			if (idtype == P_PGID && id != cp->p_pgrp)
975 				continue;
976 
977 			switch (cp->p_wcode) {
978 
979 			case CLD_TRAPPED:
980 			case CLD_STOPPED:
981 			case CLD_CONTINUED:
982 				cmn_err(CE_PANIC,
983 				    "waitid: wrong state %d on the p_newstate"
984 				    " list", cp->p_wcode);
985 				break;
986 
987 			case CLD_EXITED:
988 			case CLD_DUMPED:
989 			case CLD_KILLED:
990 				if (!(options & WEXITED)) {
991 					/*
992 					 * Count how many are already gone
993 					 * for good.
994 					 */
995 					proc_gone++;
996 					break;
997 				}
998 				if (!waitflag) {
999 					winfo(cp, ip, 0);
1000 				} else {
1001 					winfo(cp, ip, 1);
1002 					freeproc(cp);
1003 				}
1004 				mutex_exit(&pidlock);
1005 				if (waitflag) {		/* accept SIGCLD */
1006 					sigcld_delete(ip);
1007 					sigcld_repost();
1008 				}
1009 				return (0);
1010 			}
1011 
1012 			if (idtype == P_PID)
1013 				break;
1014 		}
1015 
1016 		/*
1017 		 * Wow! None of the threads on the p_sibling_ns list were
1018 		 * interesting threads. Check all the kids!
1019 		 */
1020 		found = 0;
1021 		for (cp = pp->p_child; cp != NULL; cp = cp->p_sibling) {
1022 			if (idtype == P_PID && id != cp->p_pid)
1023 				continue;
1024 			if (idtype == P_PGID && id != cp->p_pgrp)
1025 				continue;
1026 
1027 			switch (cp->p_wcode) {
1028 			case CLD_TRAPPED:
1029 				if (!(options & WTRAPPED))
1030 					break;
1031 				winfo(cp, ip, waitflag);
1032 				mutex_exit(&pidlock);
1033 				if (waitflag) {		/* accept SIGCLD */
1034 					sigcld_delete(ip);
1035 					sigcld_repost();
1036 				}
1037 				return (0);
1038 
1039 			case CLD_STOPPED:
1040 				if (!(options & WSTOPPED))
1041 					break;
1042 				/* Is it still stopped? */
1043 				mutex_enter(&cp->p_lock);
1044 				if (!jobstopped(cp)) {
1045 					mutex_exit(&cp->p_lock);
1046 					break;
1047 				}
1048 				mutex_exit(&cp->p_lock);
1049 				winfo(cp, ip, waitflag);
1050 				mutex_exit(&pidlock);
1051 				if (waitflag) {		/* accept SIGCLD */
1052 					sigcld_delete(ip);
1053 					sigcld_repost();
1054 				}
1055 				return (0);
1056 
1057 			case CLD_CONTINUED:
1058 				if (!(options & WCONTINUED))
1059 					break;
1060 				winfo(cp, ip, waitflag);
1061 				mutex_exit(&pidlock);
1062 				if (waitflag) {		/* accept SIGCLD */
1063 					sigcld_delete(ip);
1064 					sigcld_repost();
1065 				}
1066 				return (0);
1067 
1068 			case CLD_EXITED:
1069 			case CLD_DUMPED:
1070 			case CLD_KILLED:
1071 				if (idtype != P_PID &&
1072 				    (cp->p_pidflag & CLDWAITPID))
1073 					continue;
1074 				/*
1075 				 * Don't complain if a process was found in
1076 				 * the first loop but we broke out of the loop
1077 				 * because of the arguments passed to us.
1078 				 */
1079 				if (proc_gone == 0) {
1080 					cmn_err(CE_PANIC,
1081 					    "waitid: wrong state on the"
1082 					    " p_child list");
1083 				} else {
1084 					break;
1085 				}
1086 			}
1087 
1088 			found++;
1089 
1090 			if (idtype == P_PID)
1091 				break;
1092 		}
1093 
1094 		/*
1095 		 * If we found no interesting processes at all,
1096 		 * break out and return ECHILD.
1097 		 */
1098 		if (found + proc_gone == 0)
1099 			break;
1100 
1101 		if (options & WNOHANG) {
1102 			mutex_exit(&pidlock);
1103 			bzero(ip, sizeof (k_siginfo_t));
1104 			/*
1105 			 * We should set ip->si_signo = SIGCLD,
1106 			 * but there is an SVVS test that expects
1107 			 * ip->si_signo to be zero in this case.
1108 			 */
1109 			return (0);
1110 		}
1111 
1112 		/*
1113 		 * If we found no processes of interest that could
1114 		 * change state while we wait, we don't wait at all.
1115 		 * Get out with ECHILD according to SVID.
1116 		 */
1117 		if (found == proc_gone)
1118 			break;
1119 
1120 		if (!cv_wait_sig_swap(&pp->p_cv, &pidlock)) {
1121 			mutex_exit(&pidlock);
1122 			return (EINTR);
1123 		}
1124 	}
1125 	mutex_exit(&pidlock);
1126 	return (ECHILD);
1127 }
1128 
1129 /*
1130  * The wait() system call trap is no longer invoked by libc.
1131  * It is retained only for the benefit of statically linked applications.
1132  * Delete this when we no longer care about these old and broken applications.
1133  */
1134 int64_t
1135 wait(void)
1136 {
1137 	int error;
1138 	k_siginfo_t info;
1139 	rval_t	r;
1140 
1141 	if (error =  waitid(P_ALL, (id_t)0, &info, WEXITED|WTRAPPED))
1142 		return (set_errno(error));
1143 	r.r_val1 = info.si_pid;
1144 	r.r_val2 = wstat(info.si_code, info.si_status);
1145 	return (r.r_vals);
1146 }
1147 
1148 int
1149 waitsys(idtype_t idtype, id_t id, siginfo_t *infop, int options)
1150 {
1151 	int error;
1152 	k_siginfo_t info;
1153 
1154 	if (error = waitid(idtype, id, &info, options))
1155 		return (set_errno(error));
1156 	if (copyout(&info, infop, sizeof (k_siginfo_t)))
1157 		return (set_errno(EFAULT));
1158 	return (0);
1159 }
1160 
1161 #ifdef _SYSCALL32_IMPL
1162 
1163 int
1164 waitsys32(idtype_t idtype, id_t id, siginfo_t *infop, int options)
1165 {
1166 	int error;
1167 	k_siginfo_t info;
1168 	siginfo32_t info32;
1169 
1170 	if (error = waitid(idtype, id, &info, options))
1171 		return (set_errno(error));
1172 	siginfo_kto32(&info, &info32);
1173 	if (copyout(&info32, infop, sizeof (info32)))
1174 		return (set_errno(EFAULT));
1175 	return (0);
1176 }
1177 
1178 #endif	/* _SYSCALL32_IMPL */
1179 
1180 void
1181 proc_detach(proc_t *p)
1182 {
1183 	proc_t *q;
1184 
1185 	ASSERT(MUTEX_HELD(&pidlock));
1186 
1187 	q = p->p_parent;
1188 	ASSERT(q != NULL);
1189 
1190 	/*
1191 	 * Take it off the newstate list of its parent
1192 	 */
1193 	delete_ns(q, p);
1194 
1195 	if (q->p_child == p) {
1196 		q->p_child = p->p_sibling;
1197 		/*
1198 		 * If the parent has no children, it better not
1199 		 * have any with new states either!
1200 		 */
1201 		ASSERT(q->p_child ? 1 : q->p_child_ns == NULL);
1202 	}
1203 
1204 	if (p->p_sibling) {
1205 		p->p_sibling->p_psibling = p->p_psibling;
1206 	}
1207 
1208 	if (p->p_psibling) {
1209 		p->p_psibling->p_sibling = p->p_sibling;
1210 	}
1211 }
1212 
1213 /*
1214  * Remove zombie children from the process table.
1215  */
1216 void
1217 freeproc(proc_t *p)
1218 {
1219 	proc_t *q;
1220 
1221 	ASSERT(p->p_stat == SZOMB);
1222 	ASSERT(p->p_tlist == NULL);
1223 	ASSERT(MUTEX_HELD(&pidlock));
1224 
1225 	sigdelq(p, NULL, 0);
1226 	if (p->p_killsqp) {
1227 		siginfofree(p->p_killsqp);
1228 		p->p_killsqp = NULL;
1229 	}
1230 
1231 	prfree(p);	/* inform /proc */
1232 
1233 	/*
1234 	 * Don't free the init processes.
1235 	 * Other dying processes will access it.
1236 	 */
1237 	if (p == proc_init)
1238 		return;
1239 
1240 
1241 	/*
1242 	 * We wait until now to free the cred structure because a
1243 	 * zombie process's credentials may be examined by /proc.
1244 	 * No cred locking needed because there are no threads at this point.
1245 	 */
1246 	upcount_dec(crgetruid(p->p_cred), crgetzoneid(p->p_cred));
1247 	crfree(p->p_cred);
1248 	if (p->p_corefile != NULL) {
1249 		corectl_path_rele(p->p_corefile);
1250 		p->p_corefile = NULL;
1251 	}
1252 	if (p->p_content != NULL) {
1253 		corectl_content_rele(p->p_content);
1254 		p->p_content = NULL;
1255 	}
1256 
1257 	if (p->p_nextofkin && !((p->p_nextofkin->p_flag & SNOWAIT) ||
1258 	    (PTOU(p->p_nextofkin)->u_signal[SIGCLD - 1] == SIG_IGN))) {
1259 		/*
1260 		 * This should still do the right thing since p_utime/stime
1261 		 * get set to the correct value on process exit, so it
1262 		 * should get properly updated
1263 		 */
1264 		p->p_nextofkin->p_cutime += p->p_utime;
1265 		p->p_nextofkin->p_cstime += p->p_stime;
1266 
1267 		p->p_nextofkin->p_cacct[LMS_USER] += p->p_acct[LMS_USER];
1268 		p->p_nextofkin->p_cacct[LMS_SYSTEM] += p->p_acct[LMS_SYSTEM];
1269 		p->p_nextofkin->p_cacct[LMS_TRAP] += p->p_acct[LMS_TRAP];
1270 		p->p_nextofkin->p_cacct[LMS_TFAULT] += p->p_acct[LMS_TFAULT];
1271 		p->p_nextofkin->p_cacct[LMS_DFAULT] += p->p_acct[LMS_DFAULT];
1272 		p->p_nextofkin->p_cacct[LMS_KFAULT] += p->p_acct[LMS_KFAULT];
1273 		p->p_nextofkin->p_cacct[LMS_USER_LOCK]
1274 		    += p->p_acct[LMS_USER_LOCK];
1275 		p->p_nextofkin->p_cacct[LMS_SLEEP] += p->p_acct[LMS_SLEEP];
1276 		p->p_nextofkin->p_cacct[LMS_WAIT_CPU]
1277 		    += p->p_acct[LMS_WAIT_CPU];
1278 		p->p_nextofkin->p_cacct[LMS_STOPPED] += p->p_acct[LMS_STOPPED];
1279 
1280 		p->p_nextofkin->p_cru.minflt	+= p->p_ru.minflt;
1281 		p->p_nextofkin->p_cru.majflt	+= p->p_ru.majflt;
1282 		p->p_nextofkin->p_cru.nswap	+= p->p_ru.nswap;
1283 		p->p_nextofkin->p_cru.inblock	+= p->p_ru.inblock;
1284 		p->p_nextofkin->p_cru.oublock	+= p->p_ru.oublock;
1285 		p->p_nextofkin->p_cru.msgsnd	+= p->p_ru.msgsnd;
1286 		p->p_nextofkin->p_cru.msgrcv	+= p->p_ru.msgrcv;
1287 		p->p_nextofkin->p_cru.nsignals	+= p->p_ru.nsignals;
1288 		p->p_nextofkin->p_cru.nvcsw	+= p->p_ru.nvcsw;
1289 		p->p_nextofkin->p_cru.nivcsw	+= p->p_ru.nivcsw;
1290 		p->p_nextofkin->p_cru.sysc	+= p->p_ru.sysc;
1291 		p->p_nextofkin->p_cru.ioch	+= p->p_ru.ioch;
1292 
1293 	}
1294 
1295 	q = p->p_nextofkin;
1296 	if (q && q->p_orphan == p)
1297 		q->p_orphan = p->p_nextorph;
1298 	else if (q) {
1299 		for (q = q->p_orphan; q; q = q->p_nextorph)
1300 			if (q->p_nextorph == p)
1301 				break;
1302 		ASSERT(q && q->p_nextorph == p);
1303 		q->p_nextorph = p->p_nextorph;
1304 	}
1305 
1306 	proc_detach(p);
1307 	pid_exit(p);	/* frees pid and proc structure */
1308 }
1309 
1310 /*
1311  * Delete process "child" from the newstate list of process "parent"
1312  */
1313 void
1314 delete_ns(proc_t *parent, proc_t *child)
1315 {
1316 	proc_t **ns;
1317 
1318 	ASSERT(MUTEX_HELD(&pidlock));
1319 	ASSERT(child->p_parent == parent);
1320 	for (ns = &parent->p_child_ns; *ns != NULL; ns = &(*ns)->p_sibling_ns) {
1321 		if (*ns == child) {
1322 
1323 			ASSERT((*ns)->p_parent == parent);
1324 
1325 			*ns = child->p_sibling_ns;
1326 			child->p_sibling_ns = NULL;
1327 			return;
1328 		}
1329 	}
1330 }
1331 
1332 /*
1333  * Add process "child" to the new state list of process "parent"
1334  */
1335 void
1336 add_ns(proc_t *parent, proc_t *child)
1337 {
1338 	ASSERT(child->p_sibling_ns == NULL);
1339 	child->p_sibling_ns = parent->p_child_ns;
1340 	parent->p_child_ns = child;
1341 }
1342