xref: /titanic_50/usr/src/uts/common/os/fork.c (revision 550493b6bddb57fa79e20290a3af2ef61db79468)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
29 /*	  All Rights Reserved  	*/
30 
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/sysmacros.h>
37 #include <sys/signal.h>
38 #include <sys/cred.h>
39 #include <sys/policy.h>
40 #include <sys/user.h>
41 #include <sys/systm.h>
42 #include <sys/cpuvar.h>
43 #include <sys/vfs.h>
44 #include <sys/vnode.h>
45 #include <sys/file.h>
46 #include <sys/errno.h>
47 #include <sys/time.h>
48 #include <sys/proc.h>
49 #include <sys/cmn_err.h>
50 #include <sys/acct.h>
51 #include <sys/tuneable.h>
52 #include <sys/class.h>
53 #include <sys/kmem.h>
54 #include <sys/session.h>
55 #include <sys/ucontext.h>
56 #include <sys/stack.h>
57 #include <sys/procfs.h>
58 #include <sys/prsystm.h>
59 #include <sys/vmsystm.h>
60 #include <sys/vtrace.h>
61 #include <sys/debug.h>
62 #include <sys/shm_impl.h>
63 #include <sys/door_data.h>
64 #include <vm/as.h>
65 #include <vm/rm.h>
66 #include <c2/audit.h>
67 #include <sys/var.h>
68 #include <sys/schedctl.h>
69 #include <sys/utrap.h>
70 #include <sys/task.h>
71 #include <sys/resource.h>
72 #include <sys/cyclic.h>
73 #include <sys/lgrp.h>
74 #include <sys/rctl.h>
75 #include <sys/contract_impl.h>
76 #include <sys/contract/process_impl.h>
77 #include <sys/list.h>
78 #include <sys/dtrace.h>
79 #include <sys/pool.h>
80 #include <sys/zone.h>
81 #include <sys/sdt.h>
82 #include <sys/class.h>
83 #include <sys/corectl.h>
84 
85 static int64_t cfork(int, int);
86 static int getproc(proc_t **, int);
87 static void fork_fail(proc_t *);
88 static void forklwp_fail(proc_t *);
89 
90 int fork_fail_pending;
91 
92 extern struct kmem_cache *process_cache;
93 
94 /*
95  * forkall system call.
96  */
97 int64_t
98 forkall(void)
99 {
100 	return (cfork(0, 0));
101 }
102 
103 /*
104  * The parent is stopped until the child invokes relvm().
105  */
106 int64_t
107 vfork(void)
108 {
109 	curthread->t_post_sys = 1;	/* so vfwait() will be called */
110 	return (cfork(1, 1));
111 }
112 
113 /*
114  * fork1 system call
115  */
116 int64_t
117 fork1(void)
118 {
119 	return (cfork(0, 1));
120 }
121 
122 /* ARGSUSED */
123 static int64_t
124 cfork(int isvfork, int isfork1)
125 {
126 	proc_t *p = ttoproc(curthread);
127 	struct as *as;
128 	proc_t *cp, **orphpp;
129 	klwp_t *clone;
130 	kthread_t *t;
131 	task_t *tk;
132 	rval_t	r;
133 	int error;
134 	int i;
135 	rctl_set_t *dup_set;
136 	rctl_alloc_gp_t *dup_gp;
137 	rctl_entity_p_t e;
138 	lwpdir_t *ldp;
139 	lwpent_t *lep;
140 	lwpent_t *clep;
141 
142 	/*
143 	 * fork is not supported for the /proc agent lwp.
144 	 */
145 	if (curthread == p->p_agenttp) {
146 		error = ENOTSUP;
147 		goto forkerr;
148 	}
149 
150 	if ((error = secpolicy_basic_fork(CRED())) != 0)
151 		goto forkerr;
152 
153 	/*
154 	 * If the calling lwp is doing a fork1() then the
155 	 * other lwps in this process are not duplicated and
156 	 * don't need to be held where their kernel stacks can be
157 	 * cloned.  If doing forkall(), the process is held with
158 	 * SHOLDFORK, so that the lwps are at a point where their
159 	 * stacks can be copied which is on entry or exit from
160 	 * the kernel.
161 	 */
162 	if (!holdlwps(isfork1 ? SHOLDFORK1 : SHOLDFORK)) {
163 		aston(curthread);
164 		error = EINTR;
165 		goto forkerr;
166 	}
167 
168 #if defined(__sparc)
169 	/*
170 	 * Ensure that the user stack is fully constructed
171 	 * before creating the child process structure.
172 	 */
173 	(void) flush_user_windows_to_stack(NULL);
174 #endif
175 
176 	mutex_enter(&p->p_lock);
177 	/*
178 	 * If this is vfork(), cancel any suspend request we might
179 	 * have gotten from some other thread via lwp_suspend().
180 	 * Otherwise we could end up with a deadlock on return
181 	 * from the vfork() in both the parent and the child.
182 	 */
183 	if (isvfork)
184 		curthread->t_proc_flag &= ~TP_HOLDLWP;
185 	/*
186 	 * Prevent our resource set associations from being changed during fork.
187 	 */
188 	pool_barrier_enter();
189 	mutex_exit(&p->p_lock);
190 
191 	/*
192 	 * Create a child proc struct. Place a VN_HOLD on appropriate vnodes.
193 	 */
194 	if (getproc(&cp, 0) < 0) {
195 		mutex_enter(&p->p_lock);
196 		pool_barrier_exit();
197 		continuelwps(p);
198 		mutex_exit(&p->p_lock);
199 		error = EAGAIN;
200 		goto forkerr;
201 	}
202 
203 	TRACE_2(TR_FAC_PROC, TR_PROC_FORK, "proc_fork:cp %p p %p", cp, p);
204 
205 	/*
206 	 * Assign an address space to child
207 	 */
208 	if (isvfork) {
209 		/*
210 		 * Clear any watched areas and remember the
211 		 * watched pages for restoring in vfwait().
212 		 */
213 		as = p->p_as;
214 		if (avl_numnodes(&as->a_wpage) != 0) {
215 			AS_LOCK_ENTER(as, &as->a_lock, RW_WRITER);
216 			as_clearwatch(as);
217 			p->p_wpage = as->a_wpage;
218 			avl_create(&as->a_wpage, wp_compare,
219 			    sizeof (struct watched_page),
220 			    offsetof(struct watched_page, wp_link));
221 			AS_LOCK_EXIT(as, &as->a_lock);
222 		}
223 		cp->p_as = as;
224 		cp->p_flag |= SVFORK;
225 	} else {
226 		/*
227 		 * We need to hold P_PR_LOCK until the address space has
228 		 * been duplicated and we've had a chance to remove from the
229 		 * child any DTrace probes that were in the parent. Holding
230 		 * P_PR_LOCK prevents any new probes from being added and any
231 		 * extant probes from being removed.
232 		 */
233 		mutex_enter(&p->p_lock);
234 		sprlock_proc(p);
235 		mutex_exit(&p->p_lock);
236 
237 		error = as_dup(p->p_as, &cp->p_as);
238 		if (error != 0) {
239 			fork_fail(cp);
240 			mutex_enter(&pidlock);
241 			orphpp = &p->p_orphan;
242 			while (*orphpp != cp)
243 				orphpp = &(*orphpp)->p_nextorph;
244 			*orphpp = cp->p_nextorph;
245 			ASSERT(p->p_child == cp);
246 			p->p_child = cp->p_sibling;
247 			if (p->p_child) {
248 				p->p_child->p_psibling = NULL;
249 			}
250 			mutex_enter(&cp->p_lock);
251 			tk = cp->p_task;
252 			task_detach(cp);
253 			ASSERT(cp->p_pool->pool_ref > 0);
254 			atomic_add_32(&cp->p_pool->pool_ref, -1);
255 			mutex_exit(&cp->p_lock);
256 			pid_exit(cp);
257 			mutex_exit(&pidlock);
258 			task_rele(tk);
259 
260 			mutex_enter(&p->p_lock);
261 			pool_barrier_exit();
262 			continuelwps(p);
263 			sprunlock(p);
264 			/*
265 			 * Preserve ENOMEM error condition but
266 			 * map all others to EAGAIN.
267 			 */
268 			error = (error == ENOMEM) ? ENOMEM : EAGAIN;
269 			goto forkerr;
270 		}
271 		/* Duplicate parent's shared memory */
272 		if (p->p_segacct)
273 			shmfork(p, cp);
274 
275 		if (p->p_dtrace_helpers != NULL) {
276 			ASSERT(dtrace_helpers_fork != NULL);
277 			(*dtrace_helpers_fork)(p, cp);
278 		}
279 
280 		/*
281 		 * Remove all DTrace tracepoints from the child process.
282 		 */
283 		mutex_enter(&p->p_lock);
284 		if (p->p_dtrace_count > 0)
285 			dtrace_fasttrap_fork(p, cp);
286 		sprunlock(p);
287 	}
288 
289 	/*
290 	 * Duplicate parent's resource controls.
291 	 */
292 	dup_set = rctl_set_create();
293 	for (;;) {
294 		dup_gp = rctl_set_dup_prealloc(p->p_rctls);
295 		mutex_enter(&p->p_rctls->rcs_lock);
296 		if (rctl_set_dup_ready(p->p_rctls, dup_gp))
297 			break;
298 		mutex_exit(&p->p_rctls->rcs_lock);
299 		rctl_prealloc_destroy(dup_gp);
300 	}
301 	e.rcep_p.proc = cp;
302 	e.rcep_t = RCENTITY_PROCESS;
303 	cp->p_rctls = rctl_set_dup(p->p_rctls, p, cp, &e, dup_set, dup_gp,
304 	    RCD_DUP | RCD_CALLBACK);
305 	mutex_exit(&p->p_rctls->rcs_lock);
306 
307 	rctl_prealloc_destroy(dup_gp);
308 
309 	/*
310 	 * Allocate the child's lwp directory and lwpid hash table.
311 	 */
312 	if (isfork1)
313 		cp->p_lwpdir_sz = 2;
314 	else
315 		cp->p_lwpdir_sz = p->p_lwpdir_sz;
316 	cp->p_lwpdir = cp->p_lwpfree = ldp =
317 		kmem_zalloc(cp->p_lwpdir_sz * sizeof (lwpdir_t), KM_SLEEP);
318 	for (i = 1; i < cp->p_lwpdir_sz; i++, ldp++)
319 		ldp->ld_next = ldp + 1;
320 	cp->p_tidhash_sz = (cp->p_lwpdir_sz + 2) / 2;
321 	cp->p_tidhash =
322 		kmem_zalloc(cp->p_tidhash_sz * sizeof (lwpdir_t *), KM_SLEEP);
323 
324 	/*
325 	 * Duplicate parent's lwps.
326 	 * Mutual exclusion is not needed because the process is
327 	 * in the hold state and only the current lwp is running.
328 	 */
329 	klgrpset_clear(cp->p_lgrpset);
330 	if (isfork1) {
331 		clone = forklwp(ttolwp(curthread), cp, curthread->t_tid);
332 		if (clone == NULL)
333 			goto forklwperr;
334 		/*
335 		 * Inherit only the lwp_wait()able flag,
336 		 * Daemon threads should not call fork1(), but oh well...
337 		 */
338 		lwptot(clone)->t_proc_flag |=
339 			(curthread->t_proc_flag & TP_TWAIT);
340 	} else {
341 		/* this is forkall(), no one can be in lwp_wait() */
342 		ASSERT(p->p_lwpwait == 0 && p->p_lwpdwait == 0);
343 		/* for each entry in the parent's lwp directory... */
344 		for (i = 0, ldp = p->p_lwpdir; i < p->p_lwpdir_sz; i++, ldp++) {
345 			klwp_t *clwp;
346 			kthread_t *ct;
347 
348 			if ((lep = ldp->ld_entry) == NULL)
349 				continue;
350 
351 			if ((t = lep->le_thread) != NULL) {
352 				clwp = forklwp(ttolwp(t), cp, t->t_tid);
353 				if (clwp == NULL)
354 					goto forklwperr;
355 				ct = lwptot(clwp);
356 				/*
357 				 * Inherit lwp_wait()able and daemon flags.
358 				 */
359 				ct->t_proc_flag |=
360 				    (t->t_proc_flag & (TP_TWAIT|TP_DAEMON));
361 				/*
362 				 * Keep track of the clone of curthread to
363 				 * post return values through lwp_setrval().
364 				 * Mark other threads for special treatment
365 				 * by lwp_rtt() / post_syscall().
366 				 */
367 				if (t == curthread)
368 					clone = clwp;
369 				else
370 					ct->t_flag |= T_FORKALL;
371 			} else {
372 				/*
373 				 * Replicate zombie lwps in the child.
374 				 */
375 				clep = kmem_zalloc(sizeof (*clep), KM_SLEEP);
376 				clep->le_lwpid = lep->le_lwpid;
377 				clep->le_start = lep->le_start;
378 				lwp_hash_in(cp, clep);
379 			}
380 		}
381 	}
382 
383 	/*
384 	 * Put new process in the parent's process contract, or put it
385 	 * in a new one if there is an active process template.  Send a
386 	 * fork event (if requested) to whatever contract the child is
387 	 * a member of.  Fails if the parent has been SIGKILLed.
388 	 */
389 	if (contract_process_fork(NULL, cp, p, B_TRUE) == NULL)
390 		goto forklwperr;
391 
392 	/*
393 	 * No fork failures occur beyond this point.
394 	 */
395 
396 	cp->p_lwpid = p->p_lwpid;
397 	if (!isfork1) {
398 		cp->p_lwpdaemon = p->p_lwpdaemon;
399 		cp->p_zombcnt = p->p_zombcnt;
400 		/*
401 		 * If the parent's lwp ids have wrapped around, so have the
402 		 * child's.
403 		 */
404 		cp->p_flag |= p->p_flag & SLWPWRAP;
405 	}
406 
407 	corectl_path_hold(cp->p_corefile = p->p_corefile);
408 	corectl_content_hold(cp->p_content = p->p_content);
409 
410 #if defined(__x86)
411 	/*
412 	 * Get the right ldt descr for the child.
413 	 */
414 	(void) ldt_dup(p, cp);
415 #endif
416 
417 #ifdef __sparc
418 	utrap_dup(p, cp);
419 #endif
420 	/*
421 	 * If the child process has been marked to stop on exit
422 	 * from this fork, arrange for all other lwps to stop in
423 	 * sympathy with the active lwp.
424 	 */
425 	if (PTOU(cp)->u_systrap &&
426 	    prismember(&PTOU(cp)->u_exitmask, curthread->t_sysnum)) {
427 		mutex_enter(&cp->p_lock);
428 		t = cp->p_tlist;
429 		do {
430 			t->t_proc_flag |= TP_PRSTOP;
431 			aston(t);	/* so TP_PRSTOP will be seen */
432 		} while ((t = t->t_forw) != cp->p_tlist);
433 		mutex_exit(&cp->p_lock);
434 	}
435 	/*
436 	 * If the parent process has been marked to stop on exit
437 	 * from this fork, and its asynchronous-stop flag has not
438 	 * been set, arrange for all other lwps to stop before
439 	 * they return back to user level.
440 	 */
441 	if (!(p->p_proc_flag & P_PR_ASYNC) && PTOU(p)->u_systrap &&
442 	    prismember(&PTOU(p)->u_exitmask, curthread->t_sysnum)) {
443 		mutex_enter(&p->p_lock);
444 		t = p->p_tlist;
445 		do {
446 			t->t_proc_flag |= TP_PRSTOP;
447 			aston(t);	/* so TP_PRSTOP will be seen */
448 		} while ((t = t->t_forw) != p->p_tlist);
449 		mutex_exit(&p->p_lock);
450 	}
451 
452 	/* set return values for child */
453 	lwp_setrval(clone, p->p_pid, 1);
454 
455 	/* set return values for parent */
456 	r.r_val1 = (int)cp->p_pid;
457 	r.r_val2 = 0;
458 
459 	/*
460 	 * pool_barrier_exit() can now be called because the child process has:
461 	 * - all identifying features cloned or set (p_pid, p_task, p_pool)
462 	 * - all resource sets associated (p_tlist->*->t_cpupart, p_as->a_mset)
463 	 * - any other fields set which are used in resource set binding.
464 	 */
465 	mutex_enter(&p->p_lock);
466 	pool_barrier_exit();
467 	mutex_exit(&p->p_lock);
468 
469 	mutex_enter(&pidlock);
470 	mutex_enter(&cp->p_lock);
471 
472 	/*
473 	 * Now that there are lwps and threads attached, add the new
474 	 * process to the process group.
475 	 */
476 	pgjoin(cp, p->p_pgidp);
477 	cp->p_stat = SRUN;
478 	/*
479 	 * We are now done with all the lwps in the child process.
480 	 */
481 	t = cp->p_tlist;
482 	do {
483 		/*
484 		 * Set the lwp_suspend()ed lwps running.
485 		 * They will suspend properly at syscall exit.
486 		 */
487 		if (t->t_proc_flag & TP_HOLDLWP)
488 			lwp_create_done(t);
489 		else {
490 			/* set TS_CREATE to allow continuelwps() to work */
491 			thread_lock(t);
492 			ASSERT(t->t_state == TS_STOPPED &&
493 			    !(t->t_schedflag & (TS_CREATE|TS_CSTART)));
494 			t->t_schedflag |= TS_CREATE;
495 			thread_unlock(t);
496 		}
497 	} while ((t = t->t_forw) != cp->p_tlist);
498 	mutex_exit(&cp->p_lock);
499 
500 	if (isvfork) {
501 		CPU_STATS_ADDQ(CPU, sys, sysvfork, 1);
502 		mutex_enter(&p->p_lock);
503 		p->p_flag |= SVFWAIT;
504 		DTRACE_PROC1(create, proc_t *, cp);
505 		cv_broadcast(&pr_pid_cv[p->p_slot]);	/* inform /proc */
506 		mutex_exit(&p->p_lock);
507 		/*
508 		 * Grab child's p_lock before dropping pidlock to ensure
509 		 * the process will not disappear before we set it running.
510 		 */
511 		mutex_enter(&cp->p_lock);
512 		mutex_exit(&pidlock);
513 		sigdefault(cp);
514 		continuelwps(cp);
515 		mutex_exit(&cp->p_lock);
516 	} else {
517 		CPU_STATS_ADDQ(CPU, sys, sysfork, 1);
518 		DTRACE_PROC1(create, proc_t *, cp);
519 		/*
520 		 * It is CL_FORKRET's job to drop pidlock.
521 		 * If we do it here, the process could be set running
522 		 * and disappear before CL_FORKRET() is called.
523 		 */
524 		CL_FORKRET(curthread, cp->p_tlist);
525 		ASSERT(MUTEX_NOT_HELD(&pidlock));
526 	}
527 
528 	return (r.r_vals);
529 
530 forklwperr:
531 	if (isvfork) {
532 		if (avl_numnodes(&p->p_wpage) != 0) {
533 			/* restore watchpoints to parent */
534 			as = p->p_as;
535 			AS_LOCK_ENTER(as, &as->a_lock,
536 				RW_WRITER);
537 			as->a_wpage = p->p_wpage;
538 			avl_create(&p->p_wpage, wp_compare,
539 			    sizeof (struct watched_page),
540 			    offsetof(struct watched_page, wp_link));
541 			as_setwatch(as);
542 			AS_LOCK_EXIT(as, &as->a_lock);
543 		}
544 	} else {
545 		if (cp->p_segacct)
546 			shmexit(cp);
547 		as = cp->p_as;
548 		cp->p_as = &kas;
549 		as_free(as);
550 	}
551 
552 	if (cp->p_lwpdir) {
553 		for (i = 0, ldp = cp->p_lwpdir; i < cp->p_lwpdir_sz; i++, ldp++)
554 			if ((lep = ldp->ld_entry) != NULL)
555 				kmem_free(lep, sizeof (*lep));
556 		kmem_free(cp->p_lwpdir,
557 		    cp->p_lwpdir_sz * sizeof (*cp->p_lwpdir));
558 	}
559 	cp->p_lwpdir = NULL;
560 	cp->p_lwpfree = NULL;
561 	cp->p_lwpdir_sz = 0;
562 
563 	if (cp->p_tidhash)
564 		kmem_free(cp->p_tidhash,
565 		    cp->p_tidhash_sz * sizeof (*cp->p_tidhash));
566 	cp->p_tidhash = NULL;
567 	cp->p_tidhash_sz = 0;
568 
569 	forklwp_fail(cp);
570 	fork_fail(cp);
571 	rctl_set_free(cp->p_rctls);
572 	mutex_enter(&pidlock);
573 
574 	/*
575 	 * Detach failed child from task.
576 	 */
577 	mutex_enter(&cp->p_lock);
578 	tk = cp->p_task;
579 	task_detach(cp);
580 	ASSERT(cp->p_pool->pool_ref > 0);
581 	atomic_add_32(&cp->p_pool->pool_ref, -1);
582 	mutex_exit(&cp->p_lock);
583 
584 	orphpp = &p->p_orphan;
585 	while (*orphpp != cp)
586 		orphpp = &(*orphpp)->p_nextorph;
587 	*orphpp = cp->p_nextorph;
588 	ASSERT(p->p_child == cp);
589 	p->p_child = cp->p_sibling;
590 	if (p->p_child) {
591 		p->p_child->p_psibling = NULL;
592 	}
593 	pid_exit(cp);
594 	mutex_exit(&pidlock);
595 
596 	task_rele(tk);
597 
598 	mutex_enter(&p->p_lock);
599 	pool_barrier_exit();
600 	continuelwps(p);
601 	mutex_exit(&p->p_lock);
602 	error = EAGAIN;
603 forkerr:
604 	return ((int64_t)set_errno(error));
605 }
606 
607 /*
608  * Free allocated resources from getproc() if a fork failed.
609  */
610 static void
611 fork_fail(proc_t *cp)
612 {
613 	uf_info_t *fip = P_FINFO(cp);
614 
615 	fcnt_add(fip, -1);
616 	sigdelq(cp, NULL, 0);
617 
618 	mutex_enter(&pidlock);
619 	upcount_dec(crgetruid(cp->p_cred), crgetzoneid(cp->p_cred));
620 	mutex_exit(&pidlock);
621 
622 	/*
623 	 * single threaded, so no locking needed here
624 	 */
625 	crfree(cp->p_cred);
626 
627 	kmem_free(fip->fi_list, fip->fi_nfiles * sizeof (uf_entry_t));
628 
629 	VN_RELE(u.u_cdir);
630 	if (u.u_rdir)
631 		VN_RELE(u.u_rdir);
632 	if (cp->p_exec)
633 		VN_RELE(cp->p_exec);
634 	if (cp->p_execdir)
635 		VN_RELE(cp->p_execdir);
636 	if (u.u_cwd)
637 		refstr_rele(u.u_cwd);
638 }
639 
640 /*
641  * Clean up the lwps already created for this child process.
642  * The fork failed while duplicating all the lwps of the parent
643  * and those lwps already created must be freed.
644  * This process is invisible to the rest of the system,
645  * so we don't need to hold p->p_lock to protect the list.
646  */
647 static void
648 forklwp_fail(proc_t *p)
649 {
650 	kthread_t *t;
651 	task_t *tk;
652 
653 	while ((t = p->p_tlist) != NULL) {
654 		/*
655 		 * First remove the lwp from the process's p_tlist.
656 		 */
657 		if (t != t->t_forw)
658 			p->p_tlist = t->t_forw;
659 		else
660 			p->p_tlist = NULL;
661 		p->p_lwpcnt--;
662 		t->t_forw->t_back = t->t_back;
663 		t->t_back->t_forw = t->t_forw;
664 
665 		tk = p->p_task;
666 		mutex_enter(&p->p_zone->zone_nlwps_lock);
667 		tk->tk_nlwps--;
668 		tk->tk_proj->kpj_nlwps--;
669 		p->p_zone->zone_nlwps--;
670 		mutex_exit(&p->p_zone->zone_nlwps_lock);
671 
672 		ASSERT(t->t_schedctl == NULL);
673 
674 		if (t->t_door != NULL) {
675 			kmem_free(t->t_door, sizeof (door_data_t));
676 			t->t_door = NULL;
677 		}
678 		lwp_ctmpl_clear(ttolwp(t));
679 
680 		/*
681 		 * Remove the thread from the all threads list.
682 		 * We need to hold pidlock for this.
683 		 */
684 		mutex_enter(&pidlock);
685 		t->t_next->t_prev = t->t_prev;
686 		t->t_prev->t_next = t->t_next;
687 		CL_EXIT(t);	/* tell the scheduler that we're exiting */
688 		cv_broadcast(&t->t_joincv);	/* tell anyone in thread_join */
689 		mutex_exit(&pidlock);
690 
691 		/*
692 		 * Let the lgroup load averages know that this thread isn't
693 		 * going to show up (i.e. un-do what was done on behalf of
694 		 * this thread by the earlier lgrp_move_thread()).
695 		 */
696 		kpreempt_disable();
697 		lgrp_move_thread(t, NULL, 1);
698 		kpreempt_enable();
699 
700 		/*
701 		 * The thread was created TS_STOPPED.
702 		 * We change it to TS_FREE to avoid an
703 		 * ASSERT() panic in thread_free().
704 		 */
705 		t->t_state = TS_FREE;
706 		thread_rele(t);
707 		thread_free(t);
708 	}
709 }
710 
711 extern struct as kas;
712 
713 /*
714  * fork a kernel process.
715  */
716 int
717 newproc(void (*pc)(), caddr_t arg, id_t cid, int pri, struct contract **ct)
718 {
719 	proc_t *p;
720 	struct user *up;
721 	klwp_t *lwp;
722 	cont_process_t *ctp = NULL;
723 	rctl_entity_p_t e;
724 
725 	ASSERT(!(cid == syscid && ct != NULL));
726 	if (cid == syscid) {
727 		rctl_alloc_gp_t *init_gp;
728 		rctl_set_t *init_set;
729 
730 		if (getproc(&p, 1) < 0)
731 			return (EAGAIN);
732 
733 		p->p_flag |= SNOWAIT;
734 		p->p_exec = NULL;
735 		p->p_execdir = NULL;
736 
737 		init_set = rctl_set_create();
738 		init_gp = rctl_set_init_prealloc(RCENTITY_PROCESS);
739 
740 		/*
741 		 * kernel processes do not inherit /proc tracing flags.
742 		 */
743 		sigemptyset(&p->p_sigmask);
744 		premptyset(&p->p_fltmask);
745 		up = PTOU(p);
746 		up->u_systrap = 0;
747 		premptyset(&(up->u_entrymask));
748 		premptyset(&(up->u_exitmask));
749 		mutex_enter(&p->p_lock);
750 		e.rcep_p.proc = p;
751 		e.rcep_t = RCENTITY_PROCESS;
752 		p->p_rctls = rctl_set_init(RCENTITY_PROCESS, p, &e, init_set,
753 		    init_gp);
754 		mutex_exit(&p->p_lock);
755 
756 		rctl_prealloc_destroy(init_gp);
757 	} else  {
758 		rctl_alloc_gp_t *init_gp, *default_gp;
759 		rctl_set_t *init_set;
760 		task_t *tk, *tk_old;
761 
762 		if (getproc(&p, 0) < 0)
763 			return (EAGAIN);
764 		/*
765 		 * init creates a new task, distinct from the task
766 		 * containing kernel "processes".
767 		 */
768 		tk = task_create(0, p->p_zone);
769 		mutex_enter(&tk->tk_zone->zone_nlwps_lock);
770 		tk->tk_proj->kpj_ntasks++;
771 		mutex_exit(&tk->tk_zone->zone_nlwps_lock);
772 
773 		default_gp = rctl_rlimit_set_prealloc(RLIM_NLIMITS);
774 		init_gp = rctl_set_init_prealloc(RCENTITY_PROCESS);
775 		init_set = rctl_set_create();
776 
777 		mutex_enter(&pidlock);
778 		mutex_enter(&p->p_lock);
779 		tk_old = p->p_task;	/* switch to new task */
780 
781 		task_detach(p);
782 		task_begin(tk, p);
783 		mutex_exit(&pidlock);
784 
785 		e.rcep_p.proc = p;
786 		e.rcep_t = RCENTITY_PROCESS;
787 		p->p_rctls = rctl_set_init(RCENTITY_PROCESS, p, &e, init_set,
788 		    init_gp);
789 		rctlproc_default_init(p, default_gp);
790 		mutex_exit(&p->p_lock);
791 
792 		task_rele(tk_old);
793 		rctl_prealloc_destroy(default_gp);
794 		rctl_prealloc_destroy(init_gp);
795 	}
796 
797 	p->p_as = &kas;
798 
799 #if defined(__x86)
800 	(void) ldt_dup(&p0, p);		/* Get the default ldt descr */
801 #endif
802 
803 	if ((lwp = lwp_create(pc, arg, 0, p, TS_STOPPED, pri,
804 	    &curthread->t_hold, cid, 1)) == NULL) {
805 		task_t *tk;
806 		fork_fail(p);
807 		mutex_enter(&pidlock);
808 		mutex_enter(&p->p_lock);
809 		tk = p->p_task;
810 		task_detach(p);
811 		ASSERT(p->p_pool->pool_ref > 0);
812 		atomic_add_32(&p->p_pool->pool_ref, -1);
813 		mutex_exit(&p->p_lock);
814 		pid_exit(p);
815 		mutex_exit(&pidlock);
816 		task_rele(tk);
817 
818 		return (EAGAIN);
819 	}
820 
821 	if (cid != syscid) {
822 		ctp = contract_process_fork(sys_process_tmpl, p, curproc,
823 		    B_FALSE);
824 		ASSERT(ctp != NULL);
825 		if (ct != NULL)
826 			*ct = &ctp->conp_contract;
827 	}
828 
829 	p->p_lwpid = 1;
830 	mutex_enter(&pidlock);
831 	pgjoin(p, curproc->p_pgidp);
832 	p->p_stat = SRUN;
833 	mutex_enter(&p->p_lock);
834 	lwptot(lwp)->t_proc_flag &= ~TP_HOLDLWP;
835 	lwp_create_done(lwptot(lwp));
836 	mutex_exit(&p->p_lock);
837 	mutex_exit(&pidlock);
838 	return (0);
839 }
840 
841 /*
842  * create a child proc struct.
843  */
844 static int
845 getproc(proc_t **cpp, int kernel)
846 {
847 	proc_t		*pp, *cp;
848 	pid_t		newpid;
849 	struct user	*uarea;
850 	extern uint_t	nproc;
851 	struct cred	*cr;
852 	uid_t		ruid;
853 	zoneid_t	zoneid;
854 
855 	if (!page_mem_avail(tune.t_minarmem))
856 		return (-1);
857 	if (zone_status_get(curproc->p_zone) >= ZONE_IS_SHUTTING_DOWN)
858 		return (-1);	/* no point in starting new processes */
859 
860 	pp = curproc;
861 	cp = kmem_cache_alloc(process_cache, KM_SLEEP);
862 	bzero(cp, sizeof (proc_t));
863 
864 	/*
865 	 * Make proc entry for child process
866 	 */
867 	mutex_init(&cp->p_crlock, NULL, MUTEX_DEFAULT, NULL);
868 	mutex_init(&cp->p_pflock, NULL, MUTEX_DEFAULT, NULL);
869 #if defined(__x86)
870 	mutex_init(&cp->p_ldtlock, NULL, MUTEX_DEFAULT, NULL);
871 #endif
872 	mutex_init(&cp->p_maplock, NULL, MUTEX_DEFAULT, NULL);
873 	cp->p_stat = SIDL;
874 	cp->p_mstart = gethrtime();
875 
876 	if ((newpid = pid_assign(cp)) == -1) {
877 		if (nproc == v.v_proc) {
878 			CPU_STATS_ADDQ(CPU, sys, procovf, 1);
879 			cmn_err(CE_WARN, "out of processes");
880 		}
881 		goto bad;
882 	}
883 
884 	/*
885 	 * If not privileged make sure that this user hasn't exceeded
886 	 * v.v_maxup processes, and that users collectively haven't
887 	 * exceeded v.v_maxupttl processes.
888 	 */
889 	mutex_enter(&pidlock);
890 	ASSERT(nproc < v.v_proc);	/* otherwise how'd we get our pid? */
891 	cr = CRED();
892 	ruid = crgetruid(cr);
893 	zoneid = crgetzoneid(cr);
894 	if (nproc >= v.v_maxup && 	/* short-circuit; usually false */
895 	    (nproc >= v.v_maxupttl ||
896 	    upcount_get(ruid, zoneid) >= v.v_maxup) &&
897 	    secpolicy_newproc(cr) != 0) {
898 		mutex_exit(&pidlock);
899 		zcmn_err(zoneid, CE_NOTE,
900 		    "out of per-user processes for uid %d", ruid);
901 		goto bad;
902 	}
903 
904 	/*
905 	 * Everything is cool, put the new proc on the active process list.
906 	 * It is already on the pid list and in /proc.
907 	 * Increment the per uid process count (upcount).
908 	 */
909 	nproc++;
910 	upcount_inc(ruid, zoneid);
911 
912 	cp->p_next = practive;
913 	practive->p_prev = cp;
914 	practive = cp;
915 
916 	cp->p_ignore = pp->p_ignore;
917 	cp->p_siginfo = pp->p_siginfo;
918 	cp->p_flag = pp->p_flag & (SJCTL|SNOWAIT|SNOCD);
919 	cp->p_sessp = pp->p_sessp;
920 	SESS_HOLD(pp->p_sessp);
921 	cp->p_exec = pp->p_exec;
922 	cp->p_execdir = pp->p_execdir;
923 	cp->p_zone = pp->p_zone;
924 
925 	cp->p_bssbase = pp->p_bssbase;
926 	cp->p_brkbase = pp->p_brkbase;
927 	cp->p_brksize = pp->p_brksize;
928 	cp->p_brkpageszc = pp->p_brkpageszc;
929 	cp->p_stksize = pp->p_stksize;
930 	cp->p_stkpageszc = pp->p_stkpageszc;
931 	cp->p_stkprot = pp->p_stkprot;
932 	cp->p_datprot = pp->p_datprot;
933 	cp->p_usrstack = pp->p_usrstack;
934 	cp->p_model = pp->p_model;
935 	cp->p_ppid = pp->p_pid;
936 	cp->p_ancpid = pp->p_pid;
937 	cp->p_portcnt = pp->p_portcnt;
938 
939 	/*
940 	 * Initialize watchpoint structures
941 	 */
942 	avl_create(&cp->p_warea, wa_compare, sizeof (struct watched_area),
943 	    offsetof(struct watched_area, wa_link));
944 
945 	/*
946 	 * Initialize immediate resource control values.
947 	 */
948 	cp->p_stk_ctl = pp->p_stk_ctl;
949 	cp->p_fsz_ctl = pp->p_fsz_ctl;
950 	cp->p_vmem_ctl = pp->p_vmem_ctl;
951 	cp->p_fno_ctl = pp->p_fno_ctl;
952 
953 	/*
954 	 * Link up to parent-child-sibling chain.  No need to lock
955 	 * in general since only a call to freeproc() (done by the
956 	 * same parent as newproc()) diddles with the child chain.
957 	 */
958 	cp->p_sibling = pp->p_child;
959 	if (pp->p_child)
960 		pp->p_child->p_psibling = cp;
961 
962 	cp->p_parent = pp;
963 	pp->p_child = cp;
964 
965 	cp->p_child_ns = NULL;
966 	cp->p_sibling_ns = NULL;
967 
968 	cp->p_nextorph = pp->p_orphan;
969 	cp->p_nextofkin = pp;
970 	pp->p_orphan = cp;
971 
972 	/*
973 	 * Inherit profiling state; do not inherit REALPROF profiling state.
974 	 */
975 	cp->p_prof = pp->p_prof;
976 	cp->p_rprof_cyclic = CYCLIC_NONE;
977 
978 	/*
979 	 * Inherit pool pointer from the parent.  Kernel processes are
980 	 * always bound to the default pool.
981 	 */
982 	mutex_enter(&pp->p_lock);
983 	if (kernel) {
984 		cp->p_pool = pool_default;
985 		cp->p_flag |= SSYS;
986 	} else {
987 		cp->p_pool = pp->p_pool;
988 	}
989 	atomic_add_32(&cp->p_pool->pool_ref, 1);
990 	mutex_exit(&pp->p_lock);
991 
992 	/*
993 	 * Add the child process to the current task.  Kernel processes
994 	 * are always attached to task0.
995 	 */
996 	mutex_enter(&cp->p_lock);
997 	if (kernel)
998 		task_attach(task0p, cp);
999 	else
1000 		task_attach(pp->p_task, cp);
1001 	mutex_exit(&cp->p_lock);
1002 	mutex_exit(&pidlock);
1003 
1004 	avl_create(&cp->p_ct_held, contract_compar, sizeof (contract_t),
1005 	    offsetof(contract_t, ct_ctlist));
1006 
1007 	/*
1008 	 * Duplicate any audit information kept in the process table
1009 	 */
1010 #ifdef C2_AUDIT
1011 	if (audit_active)	/* copy audit data to cp */
1012 		audit_newproc(cp);
1013 #endif
1014 
1015 	crhold(cp->p_cred = cr);
1016 
1017 	/*
1018 	 * Bump up the counts on the file structures pointed at by the
1019 	 * parent's file table since the child will point at them too.
1020 	 */
1021 	fcnt_add(P_FINFO(pp), 1);
1022 
1023 	VN_HOLD(u.u_cdir);
1024 	if (u.u_rdir)
1025 		VN_HOLD(u.u_rdir);
1026 	if (u.u_cwd)
1027 		refstr_hold(u.u_cwd);
1028 
1029 	/*
1030 	 * copy the parent's uarea.
1031 	 */
1032 	uarea = PTOU(cp);
1033 	bcopy(PTOU(pp), uarea, sizeof (user_t));
1034 	flist_fork(P_FINFO(pp), P_FINFO(cp));
1035 
1036 	gethrestime(&uarea->u_start);
1037 	uarea->u_ticks = lbolt;
1038 	uarea->u_mem = rm_asrss(pp->p_as);
1039 	uarea->u_acflag = AFORK;
1040 
1041 	/*
1042 	 * If inherit-on-fork, copy /proc tracing flags to child.
1043 	 */
1044 	if ((pp->p_proc_flag & P_PR_FORK) != 0) {
1045 		cp->p_proc_flag |= pp->p_proc_flag & (P_PR_TRACE|P_PR_FORK);
1046 		cp->p_sigmask = pp->p_sigmask;
1047 		cp->p_fltmask = pp->p_fltmask;
1048 	} else {
1049 		sigemptyset(&cp->p_sigmask);
1050 		premptyset(&cp->p_fltmask);
1051 		uarea->u_systrap = 0;
1052 		premptyset(&uarea->u_entrymask);
1053 		premptyset(&uarea->u_exitmask);
1054 	}
1055 	/*
1056 	 * If microstate accounting is being inherited, mark child
1057 	 */
1058 	if ((pp->p_flag & SMSFORK) != 0)
1059 		cp->p_flag |= pp->p_flag & (SMSFORK|SMSACCT);
1060 
1061 	/*
1062 	 * Inherit fixalignment flag from the parent
1063 	 */
1064 	cp->p_fixalignment = pp->p_fixalignment;
1065 
1066 	if (cp->p_exec)
1067 		VN_HOLD(cp->p_exec);
1068 	if (cp->p_execdir)
1069 		VN_HOLD(cp->p_execdir);
1070 	*cpp = cp;
1071 	return (0);
1072 
1073 bad:
1074 	ASSERT(MUTEX_NOT_HELD(&pidlock));
1075 
1076 	mutex_destroy(&cp->p_crlock);
1077 	mutex_destroy(&cp->p_pflock);
1078 #if defined(__x86)
1079 	mutex_destroy(&cp->p_ldtlock);
1080 #endif
1081 	if (newpid != -1) {
1082 		proc_entry_free(cp->p_pidp);
1083 		(void) pid_rele(cp->p_pidp);
1084 	}
1085 	kmem_cache_free(process_cache, cp);
1086 
1087 	/*
1088 	 * We most likely got into this situation because some process is
1089 	 * forking out of control.  As punishment, put it to sleep for a
1090 	 * bit so it can't eat the machine alive.  Sleep interval is chosen
1091 	 * to allow no more than one fork failure per cpu per clock tick
1092 	 * on average (yes, I just made this up).  This has two desirable
1093 	 * properties: (1) it sets a constant limit on the fork failure
1094 	 * rate, and (2) the busier the system is, the harsher the penalty
1095 	 * for abusing it becomes.
1096 	 */
1097 	INCR_COUNT(&fork_fail_pending, &pidlock);
1098 	delay(fork_fail_pending / ncpus + 1);
1099 	DECR_COUNT(&fork_fail_pending, &pidlock);
1100 
1101 	return (-1); /* out of memory or proc slots */
1102 }
1103 
1104 /*
1105  * Release virtual memory.
1106  * In the case of vfork(), the child was given exclusive access to its
1107  * parent's address space.  The parent is waiting in vfwait() for the
1108  * child to release its exclusive claim via relvm().
1109  */
1110 void
1111 relvm()
1112 {
1113 	proc_t *p = curproc;
1114 
1115 	ASSERT((unsigned)p->p_lwpcnt <= 1);
1116 
1117 	prrelvm();	/* inform /proc */
1118 
1119 	if (p->p_flag & SVFORK) {
1120 		proc_t *pp = p->p_parent;
1121 		/*
1122 		 * The child process is either exec'ing or exit'ing.
1123 		 * The child is now separated from the parent's address
1124 		 * space.  The parent process is made dispatchable.
1125 		 *
1126 		 * This is a delicate locking maneuver, involving
1127 		 * both the parent's p_lock and the child's p_lock.
1128 		 * As soon as the SVFORK flag is turned off, the
1129 		 * parent is free to run, but it must not run until
1130 		 * we wake it up using its p_cv because it might
1131 		 * exit and we would be referencing invalid memory.
1132 		 * Therefore, we hold the parent with its p_lock
1133 		 * while protecting our p_flags with our own p_lock.
1134 		 */
1135 try_again:
1136 		mutex_enter(&p->p_lock);	/* grab child's lock first */
1137 		prbarrier(p);		/* make sure /proc is blocked out */
1138 		mutex_enter(&pp->p_lock);
1139 
1140 		/*
1141 		 * Check if parent is locked by /proc.
1142 		 */
1143 		if (pp->p_proc_flag & P_PR_LOCK) {
1144 			/*
1145 			 * Delay until /proc is done with the parent.
1146 			 * We must drop our (the child's) p->p_lock, wait
1147 			 * via prbarrier() on the parent, then start over.
1148 			 */
1149 			mutex_exit(&p->p_lock);
1150 			prbarrier(pp);
1151 			mutex_exit(&pp->p_lock);
1152 			goto try_again;
1153 		}
1154 		p->p_flag &= ~SVFORK;
1155 		kpreempt_disable();
1156 		p->p_as = &kas;
1157 
1158 		/*
1159 		 * notify hat of change in thread's address space
1160 		 */
1161 		hat_thread_exit(curthread);
1162 		kpreempt_enable();
1163 
1164 		/*
1165 		 * child sizes are copied back to parent because
1166 		 * child may have grown.
1167 		 */
1168 		pp->p_brkbase = p->p_brkbase;
1169 		pp->p_brksize = p->p_brksize;
1170 		pp->p_stksize = p->p_stksize;
1171 		/*
1172 		 * The parent is no longer waiting for the vfork()d child.
1173 		 * Restore the parent's watched pages, if any.  This is
1174 		 * safe because we know the parent is not locked by /proc
1175 		 */
1176 		pp->p_flag &= ~SVFWAIT;
1177 		if (avl_numnodes(&pp->p_wpage) != 0) {
1178 			pp->p_as->a_wpage = pp->p_wpage;
1179 			avl_create(&pp->p_wpage, wp_compare,
1180 			    sizeof (struct watched_page),
1181 			    offsetof(struct watched_page, wp_link));
1182 		}
1183 		cv_signal(&pp->p_cv);
1184 		mutex_exit(&pp->p_lock);
1185 		mutex_exit(&p->p_lock);
1186 	} else {
1187 		if (p->p_as != &kas) {
1188 			struct as *as;
1189 
1190 			if (p->p_segacct)
1191 				shmexit(p);
1192 			/*
1193 			 * We grab p_lock for the benefit of /proc
1194 			 */
1195 			kpreempt_disable();
1196 			mutex_enter(&p->p_lock);
1197 			prbarrier(p);	/* make sure /proc is blocked out */
1198 			as = p->p_as;
1199 			p->p_as = &kas;
1200 			mutex_exit(&p->p_lock);
1201 
1202 			/*
1203 			 * notify hat of change in thread's address space
1204 			 */
1205 			hat_thread_exit(curthread);
1206 			kpreempt_enable();
1207 
1208 			as_free(as);
1209 		}
1210 	}
1211 }
1212 
1213 /*
1214  * Wait for child to exec or exit.
1215  * Called by parent of vfork'ed process.
1216  * See important comments in relvm(), above.
1217  */
1218 void
1219 vfwait(pid_t pid)
1220 {
1221 	int signalled = 0;
1222 	proc_t *pp = ttoproc(curthread);
1223 	proc_t *cp;
1224 
1225 	/*
1226 	 * Wait for child to exec or exit.
1227 	 */
1228 	for (;;) {
1229 		mutex_enter(&pidlock);
1230 		cp = prfind(pid);
1231 		if (cp == NULL || cp->p_parent != pp) {
1232 			/*
1233 			 * Child has exit()ed.
1234 			 */
1235 			mutex_exit(&pidlock);
1236 			break;
1237 		}
1238 		/*
1239 		 * Grab the child's p_lock before releasing pidlock.
1240 		 * Otherwise, the child could exit and we would be
1241 		 * referencing invalid memory.
1242 		 */
1243 		mutex_enter(&cp->p_lock);
1244 		mutex_exit(&pidlock);
1245 		if (!(cp->p_flag & SVFORK)) {
1246 			/*
1247 			 * Child has exec()ed or is exit()ing.
1248 			 */
1249 			mutex_exit(&cp->p_lock);
1250 			break;
1251 		}
1252 		mutex_enter(&pp->p_lock);
1253 		mutex_exit(&cp->p_lock);
1254 		/*
1255 		 * We might be waked up spuriously from the cv_wait().
1256 		 * We have to do the whole operation over again to be
1257 		 * sure the child's SVFORK flag really is turned off.
1258 		 * We cannot make reference to the child because it can
1259 		 * exit before we return and we would be referencing
1260 		 * invalid memory.
1261 		 *
1262 		 * Because this is potentially a very long-term wait,
1263 		 * we call cv_wait_sig() (for its jobcontrol and /proc
1264 		 * side-effects) unless there is a current signal, in
1265 		 * which case we use cv_wait() because we cannot return
1266 		 * from this function until the child has released the
1267 		 * address space.  Calling cv_wait_sig() with a current
1268 		 * signal would lead to an indefinite loop here because
1269 		 * cv_wait_sig() returns immediately in this case.
1270 		 */
1271 		if (signalled)
1272 			cv_wait(&pp->p_cv, &pp->p_lock);
1273 		else
1274 			signalled = !cv_wait_sig(&pp->p_cv, &pp->p_lock);
1275 		mutex_exit(&pp->p_lock);
1276 	}
1277 
1278 	/* restore watchpoints to parent */
1279 	if (pr_watch_active(pp)) {
1280 		struct as *as = pp->p_as;
1281 		AS_LOCK_ENTER(as, &as->a_lock, RW_WRITER);
1282 		as_setwatch(as);
1283 		AS_LOCK_EXIT(as, &as->a_lock);
1284 	}
1285 
1286 	mutex_enter(&pp->p_lock);
1287 	prbarrier(pp);	/* barrier against /proc locking */
1288 	continuelwps(pp);
1289 	mutex_exit(&pp->p_lock);
1290 }
1291