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