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