xref: /illumos-gate/usr/src/uts/common/os/fork.c (revision 8f73539958be1bc23745fa29e1409be440461957)
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 2006 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 	/*
411 	 * Duplicate process context ops, if any.
412 	 */
413 	if (p->p_pctx)
414 		forkpctx(p, cp);
415 
416 #ifdef __sparc
417 	utrap_dup(p, cp);
418 #endif
419 	/*
420 	 * If the child process has been marked to stop on exit
421 	 * from this fork, arrange for all other lwps to stop in
422 	 * sympathy with the active lwp.
423 	 */
424 	if (PTOU(cp)->u_systrap &&
425 	    prismember(&PTOU(cp)->u_exitmask, curthread->t_sysnum)) {
426 		mutex_enter(&cp->p_lock);
427 		t = cp->p_tlist;
428 		do {
429 			t->t_proc_flag |= TP_PRSTOP;
430 			aston(t);	/* so TP_PRSTOP will be seen */
431 		} while ((t = t->t_forw) != cp->p_tlist);
432 		mutex_exit(&cp->p_lock);
433 	}
434 	/*
435 	 * If the parent process has been marked to stop on exit
436 	 * from this fork, and its asynchronous-stop flag has not
437 	 * been set, arrange for all other lwps to stop before
438 	 * they return back to user level.
439 	 */
440 	if (!(p->p_proc_flag & P_PR_ASYNC) && PTOU(p)->u_systrap &&
441 	    prismember(&PTOU(p)->u_exitmask, curthread->t_sysnum)) {
442 		mutex_enter(&p->p_lock);
443 		t = p->p_tlist;
444 		do {
445 			t->t_proc_flag |= TP_PRSTOP;
446 			aston(t);	/* so TP_PRSTOP will be seen */
447 		} while ((t = t->t_forw) != p->p_tlist);
448 		mutex_exit(&p->p_lock);
449 	}
450 
451 	/* set return values for child */
452 	lwp_setrval(clone, p->p_pid, 1);
453 
454 	/* set return values for parent */
455 	r.r_val1 = (int)cp->p_pid;
456 	r.r_val2 = 0;
457 
458 	/*
459 	 * pool_barrier_exit() can now be called because the child process has:
460 	 * - all identifying features cloned or set (p_pid, p_task, p_pool)
461 	 * - all resource sets associated (p_tlist->*->t_cpupart, p_as->a_mset)
462 	 * - any other fields set which are used in resource set binding.
463 	 */
464 	mutex_enter(&p->p_lock);
465 	pool_barrier_exit();
466 	mutex_exit(&p->p_lock);
467 
468 	mutex_enter(&pidlock);
469 	mutex_enter(&cp->p_lock);
470 
471 	/*
472 	 * Now that there are lwps and threads attached, add the new
473 	 * process to the process group.
474 	 */
475 	pgjoin(cp, p->p_pgidp);
476 	cp->p_stat = SRUN;
477 	/*
478 	 * We are now done with all the lwps in the child process.
479 	 */
480 	t = cp->p_tlist;
481 	do {
482 		/*
483 		 * Set the lwp_suspend()ed lwps running.
484 		 * They will suspend properly at syscall exit.
485 		 */
486 		if (t->t_proc_flag & TP_HOLDLWP)
487 			lwp_create_done(t);
488 		else {
489 			/* set TS_CREATE to allow continuelwps() to work */
490 			thread_lock(t);
491 			ASSERT(t->t_state == TS_STOPPED &&
492 			    !(t->t_schedflag & (TS_CREATE|TS_CSTART)));
493 			t->t_schedflag |= TS_CREATE;
494 			thread_unlock(t);
495 		}
496 	} while ((t = t->t_forw) != cp->p_tlist);
497 	mutex_exit(&cp->p_lock);
498 
499 	if (isvfork) {
500 		CPU_STATS_ADDQ(CPU, sys, sysvfork, 1);
501 		mutex_enter(&p->p_lock);
502 		p->p_flag |= SVFWAIT;
503 		DTRACE_PROC1(create, proc_t *, cp);
504 		cv_broadcast(&pr_pid_cv[p->p_slot]);	/* inform /proc */
505 		mutex_exit(&p->p_lock);
506 		/*
507 		 * Grab child's p_lock before dropping pidlock to ensure
508 		 * the process will not disappear before we set it running.
509 		 */
510 		mutex_enter(&cp->p_lock);
511 		mutex_exit(&pidlock);
512 		sigdefault(cp);
513 		continuelwps(cp);
514 		mutex_exit(&cp->p_lock);
515 	} else {
516 		CPU_STATS_ADDQ(CPU, sys, sysfork, 1);
517 		DTRACE_PROC1(create, proc_t *, cp);
518 		/*
519 		 * It is CL_FORKRET's job to drop pidlock.
520 		 * If we do it here, the process could be set running
521 		 * and disappear before CL_FORKRET() is called.
522 		 */
523 		CL_FORKRET(curthread, cp->p_tlist);
524 		ASSERT(MUTEX_NOT_HELD(&pidlock));
525 	}
526 
527 	return (r.r_vals);
528 
529 forklwperr:
530 	if (isvfork) {
531 		if (avl_numnodes(&p->p_wpage) != 0) {
532 			/* restore watchpoints to parent */
533 			as = p->p_as;
534 			AS_LOCK_ENTER(as, &as->a_lock,
535 				RW_WRITER);
536 			as->a_wpage = p->p_wpage;
537 			avl_create(&p->p_wpage, wp_compare,
538 			    sizeof (struct watched_page),
539 			    offsetof(struct watched_page, wp_link));
540 			as_setwatch(as);
541 			AS_LOCK_EXIT(as, &as->a_lock);
542 		}
543 	} else {
544 		if (cp->p_segacct)
545 			shmexit(cp);
546 		as = cp->p_as;
547 		cp->p_as = &kas;
548 		as_free(as);
549 	}
550 
551 	if (cp->p_lwpdir) {
552 		for (i = 0, ldp = cp->p_lwpdir; i < cp->p_lwpdir_sz; i++, ldp++)
553 			if ((lep = ldp->ld_entry) != NULL)
554 				kmem_free(lep, sizeof (*lep));
555 		kmem_free(cp->p_lwpdir,
556 		    cp->p_lwpdir_sz * sizeof (*cp->p_lwpdir));
557 	}
558 	cp->p_lwpdir = NULL;
559 	cp->p_lwpfree = NULL;
560 	cp->p_lwpdir_sz = 0;
561 
562 	if (cp->p_tidhash)
563 		kmem_free(cp->p_tidhash,
564 		    cp->p_tidhash_sz * sizeof (*cp->p_tidhash));
565 	cp->p_tidhash = NULL;
566 	cp->p_tidhash_sz = 0;
567 
568 	forklwp_fail(cp);
569 	fork_fail(cp);
570 	rctl_set_free(cp->p_rctls);
571 	mutex_enter(&pidlock);
572 
573 	/*
574 	 * Detach failed child from task.
575 	 */
576 	mutex_enter(&cp->p_lock);
577 	tk = cp->p_task;
578 	task_detach(cp);
579 	ASSERT(cp->p_pool->pool_ref > 0);
580 	atomic_add_32(&cp->p_pool->pool_ref, -1);
581 	mutex_exit(&cp->p_lock);
582 
583 	orphpp = &p->p_orphan;
584 	while (*orphpp != cp)
585 		orphpp = &(*orphpp)->p_nextorph;
586 	*orphpp = cp->p_nextorph;
587 	ASSERT(p->p_child == cp);
588 	p->p_child = cp->p_sibling;
589 	if (p->p_child) {
590 		p->p_child->p_psibling = NULL;
591 	}
592 	pid_exit(cp);
593 	mutex_exit(&pidlock);
594 
595 	task_rele(tk);
596 
597 	mutex_enter(&p->p_lock);
598 	pool_barrier_exit();
599 	continuelwps(p);
600 	mutex_exit(&p->p_lock);
601 	error = EAGAIN;
602 forkerr:
603 	return ((int64_t)set_errno(error));
604 }
605 
606 /*
607  * Free allocated resources from getproc() if a fork failed.
608  */
609 static void
610 fork_fail(proc_t *cp)
611 {
612 	uf_info_t *fip = P_FINFO(cp);
613 
614 	fcnt_add(fip, -1);
615 	sigdelq(cp, NULL, 0);
616 
617 	mutex_enter(&pidlock);
618 	upcount_dec(crgetruid(cp->p_cred), crgetzoneid(cp->p_cred));
619 	mutex_exit(&pidlock);
620 
621 	/*
622 	 * single threaded, so no locking needed here
623 	 */
624 	crfree(cp->p_cred);
625 
626 	kmem_free(fip->fi_list, fip->fi_nfiles * sizeof (uf_entry_t));
627 
628 	VN_RELE(u.u_cdir);
629 	if (u.u_rdir)
630 		VN_RELE(u.u_rdir);
631 	if (cp->p_exec)
632 		VN_RELE(cp->p_exec);
633 	if (cp->p_execdir)
634 		VN_RELE(cp->p_execdir);
635 	if (u.u_cwd)
636 		refstr_rele(u.u_cwd);
637 }
638 
639 /*
640  * Clean up the lwps already created for this child process.
641  * The fork failed while duplicating all the lwps of the parent
642  * and those lwps already created must be freed.
643  * This process is invisible to the rest of the system,
644  * so we don't need to hold p->p_lock to protect the list.
645  */
646 static void
647 forklwp_fail(proc_t *p)
648 {
649 	kthread_t *t;
650 	task_t *tk;
651 
652 	while ((t = p->p_tlist) != NULL) {
653 		/*
654 		 * First remove the lwp from the process's p_tlist.
655 		 */
656 		if (t != t->t_forw)
657 			p->p_tlist = t->t_forw;
658 		else
659 			p->p_tlist = NULL;
660 		p->p_lwpcnt--;
661 		t->t_forw->t_back = t->t_back;
662 		t->t_back->t_forw = t->t_forw;
663 
664 		tk = p->p_task;
665 		mutex_enter(&p->p_zone->zone_nlwps_lock);
666 		tk->tk_nlwps--;
667 		tk->tk_proj->kpj_nlwps--;
668 		p->p_zone->zone_nlwps--;
669 		mutex_exit(&p->p_zone->zone_nlwps_lock);
670 
671 		ASSERT(t->t_schedctl == NULL);
672 
673 		if (t->t_door != NULL) {
674 			kmem_free(t->t_door, sizeof (door_data_t));
675 			t->t_door = NULL;
676 		}
677 		lwp_ctmpl_clear(ttolwp(t));
678 
679 		/*
680 		 * Remove the thread from the all threads list.
681 		 * We need to hold pidlock for this.
682 		 */
683 		mutex_enter(&pidlock);
684 		t->t_next->t_prev = t->t_prev;
685 		t->t_prev->t_next = t->t_next;
686 		CL_EXIT(t);	/* tell the scheduler that we're exiting */
687 		cv_broadcast(&t->t_joincv);	/* tell anyone in thread_join */
688 		mutex_exit(&pidlock);
689 
690 		/*
691 		 * Let the lgroup load averages know that this thread isn't
692 		 * going to show up (i.e. un-do what was done on behalf of
693 		 * this thread by the earlier lgrp_move_thread()).
694 		 */
695 		kpreempt_disable();
696 		lgrp_move_thread(t, NULL, 1);
697 		kpreempt_enable();
698 
699 		/*
700 		 * The thread was created TS_STOPPED.
701 		 * We change it to TS_FREE to avoid an
702 		 * ASSERT() panic in thread_free().
703 		 */
704 		t->t_state = TS_FREE;
705 		thread_rele(t);
706 		thread_free(t);
707 	}
708 }
709 
710 extern struct as kas;
711 
712 /*
713  * fork a kernel process.
714  */
715 int
716 newproc(void (*pc)(), caddr_t arg, id_t cid, int pri, struct contract **ct)
717 {
718 	proc_t *p;
719 	struct user *up;
720 	klwp_t *lwp;
721 	cont_process_t *ctp = NULL;
722 	rctl_entity_p_t e;
723 
724 	ASSERT(!(cid == syscid && ct != NULL));
725 	if (cid == syscid) {
726 		rctl_alloc_gp_t *init_gp;
727 		rctl_set_t *init_set;
728 
729 		if (getproc(&p, 1) < 0)
730 			return (EAGAIN);
731 
732 		p->p_flag |= SNOWAIT;
733 		p->p_exec = NULL;
734 		p->p_execdir = NULL;
735 
736 		init_set = rctl_set_create();
737 		init_gp = rctl_set_init_prealloc(RCENTITY_PROCESS);
738 
739 		/*
740 		 * kernel processes do not inherit /proc tracing flags.
741 		 */
742 		sigemptyset(&p->p_sigmask);
743 		premptyset(&p->p_fltmask);
744 		up = PTOU(p);
745 		up->u_systrap = 0;
746 		premptyset(&(up->u_entrymask));
747 		premptyset(&(up->u_exitmask));
748 		mutex_enter(&p->p_lock);
749 		e.rcep_p.proc = p;
750 		e.rcep_t = RCENTITY_PROCESS;
751 		p->p_rctls = rctl_set_init(RCENTITY_PROCESS, p, &e, init_set,
752 		    init_gp);
753 		mutex_exit(&p->p_lock);
754 
755 		rctl_prealloc_destroy(init_gp);
756 	} else  {
757 		rctl_alloc_gp_t *init_gp, *default_gp;
758 		rctl_set_t *init_set;
759 		task_t *tk, *tk_old;
760 
761 		if (getproc(&p, 0) < 0)
762 			return (EAGAIN);
763 		/*
764 		 * init creates a new task, distinct from the task
765 		 * containing kernel "processes".
766 		 */
767 		tk = task_create(0, p->p_zone);
768 		mutex_enter(&tk->tk_zone->zone_nlwps_lock);
769 		tk->tk_proj->kpj_ntasks++;
770 		mutex_exit(&tk->tk_zone->zone_nlwps_lock);
771 
772 		default_gp = rctl_rlimit_set_prealloc(RLIM_NLIMITS);
773 		init_gp = rctl_set_init_prealloc(RCENTITY_PROCESS);
774 		init_set = rctl_set_create();
775 
776 		mutex_enter(&pidlock);
777 		mutex_enter(&p->p_lock);
778 		tk_old = p->p_task;	/* switch to new task */
779 
780 		task_detach(p);
781 		task_begin(tk, p);
782 		mutex_exit(&pidlock);
783 
784 		e.rcep_p.proc = p;
785 		e.rcep_t = RCENTITY_PROCESS;
786 		p->p_rctls = rctl_set_init(RCENTITY_PROCESS, p, &e, init_set,
787 		    init_gp);
788 		rctlproc_default_init(p, default_gp);
789 		mutex_exit(&p->p_lock);
790 
791 		task_rele(tk_old);
792 		rctl_prealloc_destroy(default_gp);
793 		rctl_prealloc_destroy(init_gp);
794 	}
795 
796 	p->p_as = &kas;
797 
798 	if ((lwp = lwp_create(pc, arg, 0, p, TS_STOPPED, pri,
799 	    &curthread->t_hold, cid, 1)) == NULL) {
800 		task_t *tk;
801 		fork_fail(p);
802 		mutex_enter(&pidlock);
803 		mutex_enter(&p->p_lock);
804 		tk = p->p_task;
805 		task_detach(p);
806 		ASSERT(p->p_pool->pool_ref > 0);
807 		atomic_add_32(&p->p_pool->pool_ref, -1);
808 		mutex_exit(&p->p_lock);
809 		pid_exit(p);
810 		mutex_exit(&pidlock);
811 		task_rele(tk);
812 
813 		return (EAGAIN);
814 	}
815 
816 	if (cid != syscid) {
817 		ctp = contract_process_fork(sys_process_tmpl, p, curproc,
818 		    B_FALSE);
819 		ASSERT(ctp != NULL);
820 		if (ct != NULL)
821 			*ct = &ctp->conp_contract;
822 	}
823 
824 	p->p_lwpid = 1;
825 	mutex_enter(&pidlock);
826 	pgjoin(p, curproc->p_pgidp);
827 	p->p_stat = SRUN;
828 	mutex_enter(&p->p_lock);
829 	lwptot(lwp)->t_proc_flag &= ~TP_HOLDLWP;
830 	lwp_create_done(lwptot(lwp));
831 	mutex_exit(&p->p_lock);
832 	mutex_exit(&pidlock);
833 	return (0);
834 }
835 
836 /*
837  * create a child proc struct.
838  */
839 static int
840 getproc(proc_t **cpp, int kernel)
841 {
842 	proc_t		*pp, *cp;
843 	pid_t		newpid;
844 	struct user	*uarea;
845 	extern uint_t	nproc;
846 	struct cred	*cr;
847 	uid_t		ruid;
848 	zoneid_t	zoneid;
849 
850 	if (!page_mem_avail(tune.t_minarmem))
851 		return (-1);
852 	if (zone_status_get(curproc->p_zone) >= ZONE_IS_SHUTTING_DOWN)
853 		return (-1);	/* no point in starting new processes */
854 
855 	pp = curproc;
856 	cp = kmem_cache_alloc(process_cache, KM_SLEEP);
857 	bzero(cp, sizeof (proc_t));
858 
859 	/*
860 	 * Make proc entry for child process
861 	 */
862 	mutex_init(&cp->p_crlock, NULL, MUTEX_DEFAULT, NULL);
863 	mutex_init(&cp->p_pflock, NULL, MUTEX_DEFAULT, NULL);
864 #if defined(__x86)
865 	mutex_init(&cp->p_ldtlock, NULL, MUTEX_DEFAULT, NULL);
866 #endif
867 	mutex_init(&cp->p_maplock, NULL, MUTEX_DEFAULT, NULL);
868 	cp->p_stat = SIDL;
869 	cp->p_mstart = gethrtime();
870 
871 	if ((newpid = pid_assign(cp)) == -1) {
872 		if (nproc == v.v_proc) {
873 			CPU_STATS_ADDQ(CPU, sys, procovf, 1);
874 			cmn_err(CE_WARN, "out of processes");
875 		}
876 		goto bad;
877 	}
878 
879 	/*
880 	 * If not privileged make sure that this user hasn't exceeded
881 	 * v.v_maxup processes, and that users collectively haven't
882 	 * exceeded v.v_maxupttl processes.
883 	 */
884 	mutex_enter(&pidlock);
885 	ASSERT(nproc < v.v_proc);	/* otherwise how'd we get our pid? */
886 	cr = CRED();
887 	ruid = crgetruid(cr);
888 	zoneid = crgetzoneid(cr);
889 	if (nproc >= v.v_maxup && 	/* short-circuit; usually false */
890 	    (nproc >= v.v_maxupttl ||
891 	    upcount_get(ruid, zoneid) >= v.v_maxup) &&
892 	    secpolicy_newproc(cr) != 0) {
893 		mutex_exit(&pidlock);
894 		zcmn_err(zoneid, CE_NOTE,
895 		    "out of per-user processes for uid %d", ruid);
896 		goto bad;
897 	}
898 
899 	/*
900 	 * Everything is cool, put the new proc on the active process list.
901 	 * It is already on the pid list and in /proc.
902 	 * Increment the per uid process count (upcount).
903 	 */
904 	nproc++;
905 	upcount_inc(ruid, zoneid);
906 
907 	cp->p_next = practive;
908 	practive->p_prev = cp;
909 	practive = cp;
910 
911 	cp->p_ignore = pp->p_ignore;
912 	cp->p_siginfo = pp->p_siginfo;
913 	cp->p_flag = pp->p_flag & (SJCTL|SNOWAIT|SNOCD);
914 	cp->p_sessp = pp->p_sessp;
915 	SESS_HOLD(pp->p_sessp);
916 	cp->p_exec = pp->p_exec;
917 	cp->p_execdir = pp->p_execdir;
918 	cp->p_zone = pp->p_zone;
919 
920 	cp->p_bssbase = pp->p_bssbase;
921 	cp->p_brkbase = pp->p_brkbase;
922 	cp->p_brksize = pp->p_brksize;
923 	cp->p_brkpageszc = pp->p_brkpageszc;
924 	cp->p_stksize = pp->p_stksize;
925 	cp->p_stkpageszc = pp->p_stkpageszc;
926 	cp->p_stkprot = pp->p_stkprot;
927 	cp->p_datprot = pp->p_datprot;
928 	cp->p_usrstack = pp->p_usrstack;
929 	cp->p_model = pp->p_model;
930 	cp->p_ppid = pp->p_pid;
931 	cp->p_ancpid = pp->p_pid;
932 	cp->p_portcnt = pp->p_portcnt;
933 
934 	/*
935 	 * Initialize watchpoint structures
936 	 */
937 	avl_create(&cp->p_warea, wa_compare, sizeof (struct watched_area),
938 	    offsetof(struct watched_area, wa_link));
939 
940 	/*
941 	 * Initialize immediate resource control values.
942 	 */
943 	cp->p_stk_ctl = pp->p_stk_ctl;
944 	cp->p_fsz_ctl = pp->p_fsz_ctl;
945 	cp->p_vmem_ctl = pp->p_vmem_ctl;
946 	cp->p_fno_ctl = pp->p_fno_ctl;
947 
948 	/*
949 	 * Link up to parent-child-sibling chain.  No need to lock
950 	 * in general since only a call to freeproc() (done by the
951 	 * same parent as newproc()) diddles with the child chain.
952 	 */
953 	cp->p_sibling = pp->p_child;
954 	if (pp->p_child)
955 		pp->p_child->p_psibling = cp;
956 
957 	cp->p_parent = pp;
958 	pp->p_child = cp;
959 
960 	cp->p_child_ns = NULL;
961 	cp->p_sibling_ns = NULL;
962 
963 	cp->p_nextorph = pp->p_orphan;
964 	cp->p_nextofkin = pp;
965 	pp->p_orphan = cp;
966 
967 	/*
968 	 * Inherit profiling state; do not inherit REALPROF profiling state.
969 	 */
970 	cp->p_prof = pp->p_prof;
971 	cp->p_rprof_cyclic = CYCLIC_NONE;
972 
973 	/*
974 	 * Inherit pool pointer from the parent.  Kernel processes are
975 	 * always bound to the default pool.
976 	 */
977 	mutex_enter(&pp->p_lock);
978 	if (kernel) {
979 		cp->p_pool = pool_default;
980 		cp->p_flag |= SSYS;
981 	} else {
982 		cp->p_pool = pp->p_pool;
983 	}
984 	atomic_add_32(&cp->p_pool->pool_ref, 1);
985 	mutex_exit(&pp->p_lock);
986 
987 	/*
988 	 * Add the child process to the current task.  Kernel processes
989 	 * are always attached to task0.
990 	 */
991 	mutex_enter(&cp->p_lock);
992 	if (kernel)
993 		task_attach(task0p, cp);
994 	else
995 		task_attach(pp->p_task, cp);
996 	mutex_exit(&cp->p_lock);
997 	mutex_exit(&pidlock);
998 
999 	avl_create(&cp->p_ct_held, contract_compar, sizeof (contract_t),
1000 	    offsetof(contract_t, ct_ctlist));
1001 
1002 	/*
1003 	 * Duplicate any audit information kept in the process table
1004 	 */
1005 #ifdef C2_AUDIT
1006 	if (audit_active)	/* copy audit data to cp */
1007 		audit_newproc(cp);
1008 #endif
1009 
1010 	crhold(cp->p_cred = cr);
1011 
1012 	/*
1013 	 * Bump up the counts on the file structures pointed at by the
1014 	 * parent's file table since the child will point at them too.
1015 	 */
1016 	fcnt_add(P_FINFO(pp), 1);
1017 
1018 	VN_HOLD(u.u_cdir);
1019 	if (u.u_rdir)
1020 		VN_HOLD(u.u_rdir);
1021 	if (u.u_cwd)
1022 		refstr_hold(u.u_cwd);
1023 
1024 	/*
1025 	 * copy the parent's uarea.
1026 	 */
1027 	uarea = PTOU(cp);
1028 	bcopy(PTOU(pp), uarea, sizeof (user_t));
1029 	flist_fork(P_FINFO(pp), P_FINFO(cp));
1030 
1031 	gethrestime(&uarea->u_start);
1032 	uarea->u_ticks = lbolt;
1033 	uarea->u_mem = rm_asrss(pp->p_as);
1034 	uarea->u_acflag = AFORK;
1035 
1036 	/*
1037 	 * If inherit-on-fork, copy /proc tracing flags to child.
1038 	 */
1039 	if ((pp->p_proc_flag & P_PR_FORK) != 0) {
1040 		cp->p_proc_flag |= pp->p_proc_flag & (P_PR_TRACE|P_PR_FORK);
1041 		cp->p_sigmask = pp->p_sigmask;
1042 		cp->p_fltmask = pp->p_fltmask;
1043 	} else {
1044 		sigemptyset(&cp->p_sigmask);
1045 		premptyset(&cp->p_fltmask);
1046 		uarea->u_systrap = 0;
1047 		premptyset(&uarea->u_entrymask);
1048 		premptyset(&uarea->u_exitmask);
1049 	}
1050 	/*
1051 	 * If microstate accounting is being inherited, mark child
1052 	 */
1053 	if ((pp->p_flag & SMSFORK) != 0)
1054 		cp->p_flag |= pp->p_flag & (SMSFORK|SMSACCT);
1055 
1056 	/*
1057 	 * Inherit fixalignment flag from the parent
1058 	 */
1059 	cp->p_fixalignment = pp->p_fixalignment;
1060 
1061 	if (cp->p_exec)
1062 		VN_HOLD(cp->p_exec);
1063 	if (cp->p_execdir)
1064 		VN_HOLD(cp->p_execdir);
1065 	*cpp = cp;
1066 	return (0);
1067 
1068 bad:
1069 	ASSERT(MUTEX_NOT_HELD(&pidlock));
1070 
1071 	mutex_destroy(&cp->p_crlock);
1072 	mutex_destroy(&cp->p_pflock);
1073 #if defined(__x86)
1074 	mutex_destroy(&cp->p_ldtlock);
1075 #endif
1076 	if (newpid != -1) {
1077 		proc_entry_free(cp->p_pidp);
1078 		(void) pid_rele(cp->p_pidp);
1079 	}
1080 	kmem_cache_free(process_cache, cp);
1081 
1082 	/*
1083 	 * We most likely got into this situation because some process is
1084 	 * forking out of control.  As punishment, put it to sleep for a
1085 	 * bit so it can't eat the machine alive.  Sleep interval is chosen
1086 	 * to allow no more than one fork failure per cpu per clock tick
1087 	 * on average (yes, I just made this up).  This has two desirable
1088 	 * properties: (1) it sets a constant limit on the fork failure
1089 	 * rate, and (2) the busier the system is, the harsher the penalty
1090 	 * for abusing it becomes.
1091 	 */
1092 	INCR_COUNT(&fork_fail_pending, &pidlock);
1093 	delay(fork_fail_pending / ncpus + 1);
1094 	DECR_COUNT(&fork_fail_pending, &pidlock);
1095 
1096 	return (-1); /* out of memory or proc slots */
1097 }
1098 
1099 /*
1100  * Release virtual memory.
1101  * In the case of vfork(), the child was given exclusive access to its
1102  * parent's address space.  The parent is waiting in vfwait() for the
1103  * child to release its exclusive claim via relvm().
1104  */
1105 void
1106 relvm()
1107 {
1108 	proc_t *p = curproc;
1109 
1110 	ASSERT((unsigned)p->p_lwpcnt <= 1);
1111 
1112 	prrelvm();	/* inform /proc */
1113 
1114 	if (p->p_flag & SVFORK) {
1115 		proc_t *pp = p->p_parent;
1116 		/*
1117 		 * The child process is either exec'ing or exit'ing.
1118 		 * The child is now separated from the parent's address
1119 		 * space.  The parent process is made dispatchable.
1120 		 *
1121 		 * This is a delicate locking maneuver, involving
1122 		 * both the parent's p_lock and the child's p_lock.
1123 		 * As soon as the SVFORK flag is turned off, the
1124 		 * parent is free to run, but it must not run until
1125 		 * we wake it up using its p_cv because it might
1126 		 * exit and we would be referencing invalid memory.
1127 		 * Therefore, we hold the parent with its p_lock
1128 		 * while protecting our p_flags with our own p_lock.
1129 		 */
1130 try_again:
1131 		mutex_enter(&p->p_lock);	/* grab child's lock first */
1132 		prbarrier(p);		/* make sure /proc is blocked out */
1133 		mutex_enter(&pp->p_lock);
1134 
1135 		/*
1136 		 * Check if parent is locked by /proc.
1137 		 */
1138 		if (pp->p_proc_flag & P_PR_LOCK) {
1139 			/*
1140 			 * Delay until /proc is done with the parent.
1141 			 * We must drop our (the child's) p->p_lock, wait
1142 			 * via prbarrier() on the parent, then start over.
1143 			 */
1144 			mutex_exit(&p->p_lock);
1145 			prbarrier(pp);
1146 			mutex_exit(&pp->p_lock);
1147 			goto try_again;
1148 		}
1149 		p->p_flag &= ~SVFORK;
1150 		kpreempt_disable();
1151 		p->p_as = &kas;
1152 
1153 		/*
1154 		 * notify hat of change in thread's address space
1155 		 */
1156 		hat_thread_exit(curthread);
1157 		kpreempt_enable();
1158 
1159 		/*
1160 		 * child sizes are copied back to parent because
1161 		 * child may have grown.
1162 		 */
1163 		pp->p_brkbase = p->p_brkbase;
1164 		pp->p_brksize = p->p_brksize;
1165 		pp->p_stksize = p->p_stksize;
1166 		/*
1167 		 * The parent is no longer waiting for the vfork()d child.
1168 		 * Restore the parent's watched pages, if any.  This is
1169 		 * safe because we know the parent is not locked by /proc
1170 		 */
1171 		pp->p_flag &= ~SVFWAIT;
1172 		if (avl_numnodes(&pp->p_wpage) != 0) {
1173 			pp->p_as->a_wpage = pp->p_wpage;
1174 			avl_create(&pp->p_wpage, wp_compare,
1175 			    sizeof (struct watched_page),
1176 			    offsetof(struct watched_page, wp_link));
1177 		}
1178 		cv_signal(&pp->p_cv);
1179 		mutex_exit(&pp->p_lock);
1180 		mutex_exit(&p->p_lock);
1181 	} else {
1182 		if (p->p_as != &kas) {
1183 			struct as *as;
1184 
1185 			if (p->p_segacct)
1186 				shmexit(p);
1187 			/*
1188 			 * We grab p_lock for the benefit of /proc
1189 			 */
1190 			kpreempt_disable();
1191 			mutex_enter(&p->p_lock);
1192 			prbarrier(p);	/* make sure /proc is blocked out */
1193 			as = p->p_as;
1194 			p->p_as = &kas;
1195 			mutex_exit(&p->p_lock);
1196 
1197 			/*
1198 			 * notify hat of change in thread's address space
1199 			 */
1200 			hat_thread_exit(curthread);
1201 			kpreempt_enable();
1202 
1203 			as_free(as);
1204 		}
1205 	}
1206 }
1207 
1208 /*
1209  * Wait for child to exec or exit.
1210  * Called by parent of vfork'ed process.
1211  * See important comments in relvm(), above.
1212  */
1213 void
1214 vfwait(pid_t pid)
1215 {
1216 	int signalled = 0;
1217 	proc_t *pp = ttoproc(curthread);
1218 	proc_t *cp;
1219 
1220 	/*
1221 	 * Wait for child to exec or exit.
1222 	 */
1223 	for (;;) {
1224 		mutex_enter(&pidlock);
1225 		cp = prfind(pid);
1226 		if (cp == NULL || cp->p_parent != pp) {
1227 			/*
1228 			 * Child has exit()ed.
1229 			 */
1230 			mutex_exit(&pidlock);
1231 			break;
1232 		}
1233 		/*
1234 		 * Grab the child's p_lock before releasing pidlock.
1235 		 * Otherwise, the child could exit and we would be
1236 		 * referencing invalid memory.
1237 		 */
1238 		mutex_enter(&cp->p_lock);
1239 		mutex_exit(&pidlock);
1240 		if (!(cp->p_flag & SVFORK)) {
1241 			/*
1242 			 * Child has exec()ed or is exit()ing.
1243 			 */
1244 			mutex_exit(&cp->p_lock);
1245 			break;
1246 		}
1247 		mutex_enter(&pp->p_lock);
1248 		mutex_exit(&cp->p_lock);
1249 		/*
1250 		 * We might be waked up spuriously from the cv_wait().
1251 		 * We have to do the whole operation over again to be
1252 		 * sure the child's SVFORK flag really is turned off.
1253 		 * We cannot make reference to the child because it can
1254 		 * exit before we return and we would be referencing
1255 		 * invalid memory.
1256 		 *
1257 		 * Because this is potentially a very long-term wait,
1258 		 * we call cv_wait_sig() (for its jobcontrol and /proc
1259 		 * side-effects) unless there is a current signal, in
1260 		 * which case we use cv_wait() because we cannot return
1261 		 * from this function until the child has released the
1262 		 * address space.  Calling cv_wait_sig() with a current
1263 		 * signal would lead to an indefinite loop here because
1264 		 * cv_wait_sig() returns immediately in this case.
1265 		 */
1266 		if (signalled)
1267 			cv_wait(&pp->p_cv, &pp->p_lock);
1268 		else
1269 			signalled = !cv_wait_sig(&pp->p_cv, &pp->p_lock);
1270 		mutex_exit(&pp->p_lock);
1271 	}
1272 
1273 	/* restore watchpoints to parent */
1274 	if (pr_watch_active(pp)) {
1275 		struct as *as = pp->p_as;
1276 		AS_LOCK_ENTER(as, &as->a_lock, RW_WRITER);
1277 		as_setwatch(as);
1278 		AS_LOCK_EXIT(as, &as->a_lock);
1279 	}
1280 
1281 	mutex_enter(&pp->p_lock);
1282 	prbarrier(pp);	/* barrier against /proc locking */
1283 	continuelwps(pp);
1284 	mutex_exit(&pp->p_lock);
1285 }
1286