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