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