2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_fork.c 8.6 (Berkeley) 4/8/94
39 #include <sys/cdefs.h>
40 #include "opt_ktrace.h"
41 #include "opt_kstack_pages.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/bitstring.h>
46 #include <sys/sysproto.h>
47 #include <sys/eventhandler.h>
48 #include <sys/fcntl.h>
49 #include <sys/filedesc.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/sysctl.h>
55 #include <sys/malloc.h>
56 #include <sys/mutex.h>
59 #include <sys/procdesc.h>
60 #include <sys/ptrace.h>
61 #include <sys/racct.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sched.h>
64 #include <sys/syscall.h>
65 #include <sys/vmmeter.h>
66 #include <sys/vnode.h>
69 #include <sys/ktrace.h>
70 #include <sys/unistd.h>
73 #include <sys/sysent.h>
74 #include <sys/signalvar.h>
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_extern.h>
86 #include <sys/dtrace_bsd.h>
87 dtrace_fork_func_t dtrace_fasttrap_fork;
90 SDT_PROVIDER_DECLARE(proc);
91 SDT_PROBE_DEFINE3(proc, , , create, "struct proc *", "struct proc *", "int");
93 #ifndef _SYS_SYSPROTO_H_
101 sys_fork(struct thread *td, struct fork_args *uap)
106 bzero(&fr, sizeof(fr));
107 fr.fr_flags = RFFDG | RFPROC;
109 error = fork1(td, &fr);
111 td->td_retval[0] = pid;
112 td->td_retval[1] = 0;
119 sys_pdfork(struct thread *td, struct pdfork_args *uap)
124 bzero(&fr, sizeof(fr));
125 fr.fr_flags = RFFDG | RFPROC | RFPROCDESC;
128 fr.fr_pd_flags = uap->flags;
129 AUDIT_ARG_FFLAGS(uap->flags);
131 * It is necessary to return fd by reference because 0 is a valid file
132 * descriptor number, and the child needs to be able to distinguish
133 * itself from the parent using the return value.
135 error = fork1(td, &fr);
137 td->td_retval[0] = pid;
138 td->td_retval[1] = 0;
139 error = copyout(&fd, uap->fdp, sizeof(fd));
146 sys_vfork(struct thread *td, struct vfork_args *uap)
151 bzero(&fr, sizeof(fr));
152 fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
154 error = fork1(td, &fr);
156 td->td_retval[0] = pid;
157 td->td_retval[1] = 0;
163 sys_rfork(struct thread *td, struct rfork_args *uap)
168 /* Don't allow kernel-only flags. */
169 if ((uap->flags & RFKERNELONLY) != 0)
171 /* RFSPAWN must not appear with others */
172 if ((uap->flags & RFSPAWN) != 0 && uap->flags != RFSPAWN)
175 AUDIT_ARG_FFLAGS(uap->flags);
176 bzero(&fr, sizeof(fr));
177 if ((uap->flags & RFSPAWN) != 0) {
178 fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
179 fr.fr_flags2 = FR2_DROPSIG_CAUGHT;
181 fr.fr_flags = uap->flags;
184 error = fork1(td, &fr);
186 td->td_retval[0] = pid;
187 td->td_retval[1] = 0;
192 int __exclusive_cache_line nprocs = 1; /* process 0 */
194 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
198 * Random component to lastpid generation. We mix in a random factor to make
199 * it a little harder to predict. We sanity check the modulus value to avoid
200 * doing it in critical paths. Don't let it be too small or we pointlessly
201 * waste randomness entropy, and don't let it be impossibly large. Using a
202 * modulus that is too big causes a LOT more process table scans and slows
203 * down fork processing as the pidchecked caching is defeated.
205 static int randompid = 0;
208 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
212 error = sysctl_wire_old_buffer(req, sizeof(int));
215 sx_xlock(&allproc_lock);
217 error = sysctl_handle_int(oidp, &pid, 0, req);
218 if (error == 0 && req->newptr != NULL) {
222 /* generate a random PID modulus between 100 and 1123 */
223 randompid = 100 + arc4random() % 1024;
224 else if (pid < 0 || pid > pid_max - 100)
226 randompid = pid_max - 100;
228 /* Make it reasonable */
233 sx_xunlock(&allproc_lock);
237 SYSCTL_PROC(_kern, OID_AUTO, randompid,
238 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
239 sysctl_kern_randompid, "I",
240 "Random PID modulus. Special values: 0: disable, 1: choose random value");
242 extern bitstr_t proc_id_pidmap;
243 extern bitstr_t proc_id_grpidmap;
244 extern bitstr_t proc_id_sessidmap;
245 extern bitstr_t proc_id_reapmap;
248 * Find an unused process ID
250 * If RFHIGHPID is set (used during system boot), do not allocate
254 fork_findpid(int flags)
260 * Avoid calling arc4random with procid_lock held.
263 if (__predict_false(randompid))
264 random = arc4random() % randompid;
266 mtx_lock(&procid_lock);
268 trypid = lastpid + 1;
269 if (flags & RFHIGHPID) {
276 if (trypid >= pid_max)
279 bit_ffc_at(&proc_id_pidmap, trypid, pid_max, &result);
281 KASSERT(trypid != 2, ("unexpectedly ran out of IDs"));
285 if (bit_test(&proc_id_grpidmap, result) ||
286 bit_test(&proc_id_sessidmap, result) ||
287 bit_test(&proc_id_reapmap, result)) {
293 * RFHIGHPID does not mess with the lastpid counter during boot.
295 if ((flags & RFHIGHPID) == 0)
298 bit_set(&proc_id_pidmap, result);
299 mtx_unlock(&procid_lock);
305 fork_norfproc(struct thread *td, int flags)
310 KASSERT((flags & RFPROC) == 0,
311 ("fork_norfproc called with RFPROC set"));
315 * Quiesce other threads if necessary. If RFMEM is not specified we
316 * must ensure that other threads do not concurrently create a second
317 * process sharing the vmspace, see vmspace_unshare().
319 if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
320 ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
322 if (thread_single(p1, SINGLE_BOUNDARY)) {
329 error = vm_forkproc(td, NULL, NULL, NULL, flags);
334 * Close all file descriptors.
336 if ((flags & RFCFDG) != 0) {
337 struct filedesc *fdtmp;
338 struct pwddesc *pdtmp;
340 pdtmp = pdinit(td->td_proc->p_pd, false);
341 fdtmp = fdinit(td->td_proc->p_fd, false, NULL);
349 * Unshare file descriptors (from parent).
351 if ((flags & RFFDG) != 0) {
357 if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
358 ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
360 thread_single_end(p1, SINGLE_BOUNDARY);
367 do_fork(struct thread *td, struct fork_req *fr, struct proc *p2, struct thread *td2,
368 struct vmspace *vm2, struct file *fp_procdesc)
370 struct proc *p1, *pptr;
372 struct filedesc_to_leader *fdtol;
374 struct sigacts *newsigacts;
379 bcopy(&p1->p_startcopy, &p2->p_startcopy,
380 __rangeof(struct proc, p_startcopy, p_endcopy));
381 pargs_hold(p2->p_args);
382 p2->p_umtx_min_timeout = p1->p_umtx_min_timeout;
385 bzero(&p2->p_startzero,
386 __rangeof(struct proc, p_startzero, p_endzero));
388 /* Tell the prison that we exist. */
389 prison_proc_hold(p2->p_ucred->cr_prison);
391 p2->p_state = PRS_NEW; /* protect against others */
392 p2->p_pid = fork_findpid(fr->fr_flags);
393 AUDIT_ARG_PID(p2->p_pid);
394 TSFORK(p2->p_pid, p1->p_pid);
396 sx_xlock(&allproc_lock);
397 LIST_INSERT_HEAD(&allproc, p2, p_list);
399 sx_xunlock(&allproc_lock);
401 sx_xlock(PIDHASHLOCK(p2->p_pid));
402 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
403 sx_xunlock(PIDHASHLOCK(p2->p_pid));
408 * Malloc things while we don't hold any locks.
410 if (fr->fr_flags & RFSIGSHARE)
413 newsigacts = sigacts_alloc();
418 if (fr->fr_flags & RFCFDG) {
419 pd = pdinit(p1->p_pd, false);
420 fd = fdinit(p1->p_fd, false, NULL);
422 } else if (fr->fr_flags & RFFDG) {
423 if (fr->fr_flags2 & FR2_SHARE_PATHS)
424 pd = pdshare(p1->p_pd);
426 pd = pdcopy(p1->p_pd);
427 fd = fdcopy(p1->p_fd);
430 if (fr->fr_flags2 & FR2_SHARE_PATHS)
431 pd = pdcopy(p1->p_pd);
433 pd = pdshare(p1->p_pd);
434 fd = fdshare(p1->p_fd);
435 if (p1->p_fdtol == NULL)
436 p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL,
438 if ((fr->fr_flags & RFTHREAD) != 0) {
440 * Shared file descriptor table, and shared
443 fdtol = filedesc_to_leader_share(p1->p_fdtol, p1->p_fd);
446 * Shared file descriptor table, and different
449 fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
454 * Make a proc table entry for the new process.
455 * Start by zeroing the section of proc that is zero-initialized,
456 * then copy the section that is copied directly from the parent.
462 bzero(&td2->td_startzero,
463 __rangeof(struct thread, td_startzero, td_endzero));
465 bcopy(&td->td_startcopy, &td2->td_startcopy,
466 __rangeof(struct thread, td_startcopy, td_endcopy));
468 bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name));
469 td2->td_sigstk = td->td_sigstk;
470 td2->td_flags = TDF_INMEM;
471 td2->td_lend_user_pri = PRI_MAX;
475 td2->td_vnet_lpush = NULL;
479 * Allow the scheduler to initialize the child.
486 * Duplicate sub-structures as needed.
487 * Increase reference counts on shared objects.
489 p2->p_flag = P_INMEM;
490 p2->p_flag2 = p1->p_flag2 & (P2_ASLR_DISABLE | P2_ASLR_ENABLE |
491 P2_ASLR_IGNSTART | P2_NOTRACE | P2_NOTRACE_EXEC |
492 P2_PROTMAX_ENABLE | P2_PROTMAX_DISABLE | P2_TRAPCAP |
493 P2_STKGAP_DISABLE | P2_STKGAP_DISABLE_EXEC | P2_NO_NEW_PRIVS |
494 P2_WXORX_DISABLE | P2_WXORX_ENABLE_EXEC);
495 p2->p_swtick = ticks;
496 if (p1->p_flag & P_PROFIL)
499 if (fr->fr_flags & RFSIGSHARE) {
500 p2->p_sigacts = sigacts_hold(p1->p_sigacts);
502 sigacts_copy(newsigacts, p1->p_sigacts);
503 p2->p_sigacts = newsigacts;
504 if ((fr->fr_flags2 & (FR2_DROPSIG_CAUGHT | FR2_KPROC)) != 0) {
505 mtx_lock(&p2->p_sigacts->ps_mtx);
506 if ((fr->fr_flags2 & FR2_DROPSIG_CAUGHT) != 0)
508 if ((fr->fr_flags2 & FR2_KPROC) != 0)
509 p2->p_sigacts->ps_flag |= PS_NOCLDWAIT;
510 mtx_unlock(&p2->p_sigacts->ps_mtx);
514 if (fr->fr_flags & RFTSIGZMB)
515 p2->p_sigparent = RFTSIGNUM(fr->fr_flags);
516 else if (fr->fr_flags & RFLINUXTHPN)
517 p2->p_sigparent = SIGUSR1;
519 p2->p_sigparent = SIGCHLD;
521 if ((fr->fr_flags2 & FR2_KPROC) != 0) {
522 p2->p_flag |= P_SYSTEM | P_KPROC;
523 td2->td_pflags |= TDP_KTHREAD;
526 p2->p_textvp = p1->p_textvp;
527 p2->p_textdvp = p1->p_textdvp;
531 p2->p_elf_brandinfo = p1->p_elf_brandinfo;
533 if (p1->p_flag2 & P2_INHERIT_PROTECTED) {
534 p2->p_flag |= P_PROTECTED;
535 p2->p_flag2 |= P2_INHERIT_PROTECTED;
539 * p_limit is copy-on-write. Bump its refcount.
543 thread_cow_get_proc(td2, p2);
545 pstats_fork(p1->p_stats, p2->p_stats);
551 * Bump references to the text vnode and directory, and copy
554 if (p2->p_textvp != NULL)
555 vrefact(p2->p_textvp);
556 if (p2->p_textdvp != NULL)
557 vrefact(p2->p_textdvp);
558 p2->p_binname = p1->p_binname == NULL ? NULL :
559 strdup(p1->p_binname, M_PARGS);
562 * Set up linkage for kernel based threading.
564 if ((fr->fr_flags & RFTHREAD) != 0) {
565 mtx_lock(&ppeers_lock);
566 p2->p_peers = p1->p_peers;
568 p2->p_leader = p1->p_leader;
569 mtx_unlock(&ppeers_lock);
570 PROC_LOCK(p1->p_leader);
571 if ((p1->p_leader->p_flag & P_WEXIT) != 0) {
572 PROC_UNLOCK(p1->p_leader);
574 * The task leader is exiting, so process p1 is
575 * going to be killed shortly. Since p1 obviously
576 * isn't dead yet, we know that the leader is either
577 * sending SIGKILL's to all the processes in this
578 * task or is sleeping waiting for all the peers to
579 * exit. We let p1 complete the fork, but we need
580 * to go ahead and kill the new process p2 since
581 * the task leader may not get a chance to send
582 * SIGKILL to it. We leave it on the list so that
583 * the task leader will wait for this new process
587 kern_psignal(p2, SIGKILL);
590 PROC_UNLOCK(p1->p_leader);
596 sx_xlock(&proctree_lock);
597 PGRP_LOCK(p1->p_pgrp);
602 * Preserve some more flags in subprocess. P_PROFIL has already
605 p2->p_flag |= p1->p_flag & P_SUGID;
606 td2->td_pflags |= (td->td_pflags & (TDP_ALTSTACK |
607 TDP_SIGFASTBLOCK)) | TDP_FORKING;
608 SESS_LOCK(p1->p_session);
609 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
610 p2->p_flag |= P_CONTROLT;
611 SESS_UNLOCK(p1->p_session);
612 if (fr->fr_flags & RFPPWAIT)
613 p2->p_flag |= P_PPWAIT;
615 p2->p_pgrp = p1->p_pgrp;
616 LIST_INSERT_AFTER(p1, p2, p_pglist);
617 PGRP_UNLOCK(p1->p_pgrp);
618 LIST_INIT(&p2->p_children);
619 LIST_INIT(&p2->p_orphans);
621 callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0);
622 TAILQ_INIT(&p2->p_kqtim_stop);
625 * This begins the section where we must prevent the parent
626 * from being swapped.
632 * Attach the new process to its parent.
634 * If RFNOWAIT is set, the newly created process becomes a child
635 * of init. This effectively disassociates the child from the
638 if ((fr->fr_flags & RFNOWAIT) != 0) {
642 p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ?
647 p2->p_oppid = pptr->p_pid;
648 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
649 LIST_INIT(&p2->p_reaplist);
650 LIST_INSERT_HEAD(&p2->p_reaper->p_reaplist, p2, p_reapsibling);
651 if (p2->p_reaper == p1 && p1 != initproc) {
652 p2->p_reapsubtree = p2->p_pid;
653 proc_id_set_cond(PROC_ID_REAP, p2->p_pid);
655 sx_xunlock(&proctree_lock);
657 /* Inform accounting that we have forked. */
658 p2->p_acflag = AFORK;
666 * Finish creating the child process. It will return via a different
667 * execution path later. (ie: directly into user mode)
669 vm_forkproc(td, p2, td2, vm2, fr->fr_flags);
671 if (fr->fr_flags == (RFFDG | RFPROC)) {
673 VM_CNT_ADD(v_forkpages, p2->p_vmspace->vm_dsize +
674 p2->p_vmspace->vm_ssize);
675 } else if (fr->fr_flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
676 VM_CNT_INC(v_vforks);
677 VM_CNT_ADD(v_vforkpages, p2->p_vmspace->vm_dsize +
678 p2->p_vmspace->vm_ssize);
679 } else if (p1 == &proc0) {
680 VM_CNT_INC(v_kthreads);
681 VM_CNT_ADD(v_kthreadpages, p2->p_vmspace->vm_dsize +
682 p2->p_vmspace->vm_ssize);
684 VM_CNT_INC(v_rforks);
685 VM_CNT_ADD(v_rforkpages, p2->p_vmspace->vm_dsize +
686 p2->p_vmspace->vm_ssize);
690 * Associate the process descriptor with the process before anything
691 * can happen that might cause that process to need the descriptor.
692 * However, don't do this until after fork(2) can no longer fail.
694 if (fr->fr_flags & RFPROCDESC)
695 procdesc_new(p2, fr->fr_pd_flags);
698 * Both processes are set up, now check if any loadable modules want
699 * to adjust anything.
701 EVENTHANDLER_DIRECT_INVOKE(process_fork, p1, p2, fr->fr_flags);
704 * Set the child start time and mark the process as being complete.
708 microuptime(&p2->p_stats->p_start);
710 p2->p_state = PRS_NORMAL;
715 * Tell the DTrace fasttrap provider about the new process so that any
716 * tracepoints inherited from the parent can be removed. We have to do
717 * this only after p_state is PRS_NORMAL since the fasttrap module will
718 * use pfind() later on.
720 if ((fr->fr_flags & RFMEM) == 0 && dtrace_fasttrap_fork)
721 dtrace_fasttrap_fork(p1, p2);
723 if (fr->fr_flags & RFPPWAIT) {
724 td->td_pflags |= TDP_RFPPWAIT;
725 td->td_rfppwait_p = p2;
726 td->td_dbgflags |= TDB_VFORK;
731 * Tell any interested parties about the new process.
733 knote_fork(p1->p_klist, p2->p_pid);
736 * Now can be swapped.
740 SDT_PROBE3(proc, , , create, p2, p1, fr->fr_flags);
742 if (fr->fr_flags & RFPROCDESC) {
743 procdesc_finit(p2->p_procdesc, fp_procdesc);
744 fdrop(fp_procdesc, td);
748 * Speculative check for PTRACE_FORK. PTRACE_FORK is not
749 * synced with forks in progress so it is OK if we miss it
752 if ((p1->p_ptevents & PTRACE_FORK) != 0) {
753 sx_xlock(&proctree_lock);
757 * p1->p_ptevents & p1->p_pptr are protected by both
758 * process and proctree locks for modifications,
759 * so owning proctree_lock allows the race-free read.
761 if ((p1->p_ptevents & PTRACE_FORK) != 0) {
763 * Arrange for debugger to receive the fork event.
765 * We can report PL_FLAG_FORKED regardless of
766 * P_FOLLOWFORK settings, but it does not make a sense
769 td->td_dbgflags |= TDB_FORK;
770 td->td_dbg_forked = p2->p_pid;
771 td2->td_dbgflags |= TDB_STOPATFORK;
772 proc_set_traced(p2, true);
774 "do_fork: attaching to new child pid %d: oppid %d",
775 p2->p_pid, p2->p_oppid);
776 proc_reparent(p2, p1->p_pptr, false);
779 sx_xunlock(&proctree_lock);
782 racct_proc_fork_done(p2);
784 if ((fr->fr_flags & RFSTOPPED) == 0) {
785 if (fr->fr_pidp != NULL)
786 *fr->fr_pidp = p2->p_pid;
788 * If RFSTOPPED not requested, make child runnable and
793 sched_add(td2, SRQ_BORING);
800 fork_rfppwait(struct thread *td)
804 MPASS(td->td_pflags & TDP_RFPPWAIT);
808 * Preserve synchronization semantics of vfork. If
809 * waiting for child to exec or exit, fork set
810 * P_PPWAIT on child, and there we sleep on our proc
813 * Do it after the ptracestop() above is finished, to
814 * not block our debugger until child execs or exits
815 * to finish vfork wait.
817 td->td_pflags &= ~TDP_RFPPWAIT;
818 p2 = td->td_rfppwait_p;
821 while (p2->p_flag & P_PPWAIT) {
823 if (thread_suspend_check_needed()) {
825 thread_suspend_check(0);
831 cv_timedwait(&p2->p_pwait, &p2->p_mtx, hz);
835 if (td->td_dbgflags & TDB_VFORK) {
837 if (p->p_ptevents & PTRACE_VFORK)
838 ptracestop(td, SIGTRAP, NULL);
839 td->td_dbgflags &= ~TDB_VFORK;
845 fork1(struct thread *td, struct fork_req *fr)
847 struct proc *p1, *newproc;
851 struct file *fp_procdesc;
853 vm_ooffset_t mem_charged;
854 int error, nprocs_new;
856 static struct timeval lastfail;
858 bool killsx_locked, singlethreaded;
860 flags = fr->fr_flags;
861 pages = fr->fr_pages;
863 if ((flags & RFSTOPPED) != 0)
864 MPASS(fr->fr_procp != NULL && fr->fr_pidp == NULL);
866 MPASS(fr->fr_procp == NULL);
868 /* Check for the undefined or unimplemented flags. */
869 if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
872 /* Signal value requires RFTSIGZMB. */
873 if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
876 /* Can't copy and clear. */
877 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
880 /* Check the validity of the signal number. */
881 if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
884 if ((flags & RFPROCDESC) != 0) {
885 /* Can't not create a process yet get a process descriptor. */
886 if ((flags & RFPROC) == 0)
889 /* Must provide a place to put a procdesc if creating one. */
890 if (fr->fr_pd_fd == NULL)
893 /* Check if we are using supported flags. */
894 if ((fr->fr_pd_flags & ~PD_ALLOWED_AT_FORK) != 0)
901 * Here we don't create a new process, but we divorce
902 * certain parts of a process from itself.
904 if ((flags & RFPROC) == 0) {
905 if (fr->fr_procp != NULL)
906 *fr->fr_procp = NULL;
907 else if (fr->fr_pidp != NULL)
909 return (fork_norfproc(td, flags));
915 killsx_locked = false;
916 singlethreaded = false;
919 * Increment the nprocs resource before allocations occur.
920 * Although process entries are dynamically created, we still
921 * keep a global limit on the maximum number we will
922 * create. There are hard-limits as to the number of processes
923 * that can run, established by the KVA and memory usage for
926 * Don't allow a nonprivileged user to use the last ten
927 * processes; don't let root exceed the limit.
929 nprocs_new = atomic_fetchadd_int(&nprocs, 1) + 1;
930 if (nprocs_new >= maxproc - 10) {
931 if (priv_check_cred(td->td_ucred, PRIV_MAXPROC) != 0 ||
932 nprocs_new >= maxproc) {
934 sx_xlock(&allproc_lock);
935 if (ppsratecheck(&lastfail, &curfail, 1)) {
936 printf("maxproc limit exceeded by uid %u "
937 "(pid %d); see tuning(7) and "
939 td->td_ucred->cr_ruid, p1->p_pid);
941 sx_xunlock(&allproc_lock);
947 * If we are possibly multi-threaded, and there is a process
948 * sending a signal to our group right now, ensure that our
949 * other threads cannot be chosen for the signal queueing.
950 * Otherwise, this might delay signal action, and make the new
951 * child escape the signaling.
954 if (p1->p_numthreads > 1) {
955 if (sx_try_slock(&pg->pg_killsx) != 0) {
956 killsx_locked = true;
959 if (thread_single(p1, SINGLE_BOUNDARY)) {
965 singlethreaded = true;
970 * Atomically check for signals and block processes from sending
971 * a signal to our process group until the child is visible.
973 if (!killsx_locked && sx_slock_sig(&pg->pg_killsx) != 0) {
977 if (__predict_false(p1->p_pgrp != pg || sig_intr() != 0)) {
979 * Either the process was moved to other process
980 * group, or there is pending signal. sx_slock_sig()
981 * does not check for signals if not sleeping for the
984 sx_sunlock(&pg->pg_killsx);
985 killsx_locked = false;
989 killsx_locked = true;
993 * If required, create a process descriptor in the parent first; we
994 * will abandon it if something goes wrong. We don't finit() until
997 if (flags & RFPROCDESC) {
998 error = procdesc_falloc(td, &fp_procdesc, fr->fr_pd_fd,
999 fr->fr_pd_flags, fr->fr_pd_fcaps);
1002 AUDIT_ARG_FD(*fr->fr_pd_fd);
1007 pages = kstack_pages;
1008 /* Allocate new proc. */
1009 newproc = uma_zalloc(proc_zone, M_WAITOK);
1010 td2 = FIRST_THREAD_IN_PROC(newproc);
1012 td2 = thread_alloc(pages);
1017 proc_linkup(newproc, td2);
1019 if (td2->td_kstack == 0 || td2->td_kstack_pages != pages) {
1020 if (td2->td_kstack != 0)
1021 vm_thread_dispose(td2);
1022 if (!thread_alloc_stack(td2, pages)) {
1029 if ((flags & RFMEM) == 0) {
1030 vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
1035 if (!swap_reserve(mem_charged)) {
1037 * The swap reservation failed. The accounting
1038 * from the entries of the copied vm2 will be
1039 * subtracted in vmspace_free(), so force the
1040 * reservation there.
1042 swap_reserve_force(mem_charged);
1050 * XXX: This is ugly; when we copy resource usage, we need to bump
1051 * per-cred resource counters.
1053 proc_set_cred_init(newproc, td->td_ucred);
1056 * Initialize resource accounting for the child process.
1058 error = racct_proc_fork(p1, newproc);
1065 mac_proc_init(newproc);
1067 newproc->p_klist = knlist_alloc(&newproc->p_mtx);
1068 STAILQ_INIT(&newproc->p_ktr);
1071 * Increment the count of procs running with this uid. Don't allow
1072 * a nonprivileged user to exceed their current limit.
1074 cred = td->td_ucred;
1075 if (!chgproccnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPROC))) {
1076 if (priv_check_cred(cred, PRIV_PROC_LIMIT) != 0)
1078 chgproccnt(cred->cr_ruidinfo, 1, 0);
1081 do_fork(td, fr, newproc, td2, vm2, fp_procdesc);
1087 mac_proc_destroy(newproc);
1089 racct_proc_exit(newproc);
1091 proc_unset_cred(newproc);
1095 uma_zfree(proc_zone, newproc);
1096 if ((flags & RFPROCDESC) != 0 && fp_procdesc != NULL) {
1097 fdclose(td, fp_procdesc, *fr->fr_pd_fd);
1098 fdrop(fp_procdesc, td);
1100 atomic_add_int(&nprocs, -1);
1103 sx_sunlock(&pg->pg_killsx);
1104 if (singlethreaded) {
1106 thread_single_end(p1, SINGLE_BOUNDARY);
1110 pause("fork", hz / 2);
1115 * Handle the return of a child process from fork1(). This function
1116 * is called from the MD fork_trampoline() entry point.
1119 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
1120 struct trapframe *frame)
1128 KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
1130 CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)",
1131 td, td_get_sched(td), p->p_pid, td->td_name);
1133 sched_fork_exit(td);
1136 * Processes normally resume in mi_switch() after being
1137 * cpu_switch()'ed to, but when children start up they arrive here
1138 * instead, so we must do much the same things as mi_switch() would.
1140 if ((dtd = PCPU_GET(deadthread))) {
1141 PCPU_SET(deadthread, NULL);
1147 * cpu_fork_kthread_handler intercepts this function call to
1148 * have this call a non-return function to stay in kernel mode.
1149 * initproc has its own fork handler, but it does return.
1151 KASSERT(callout != NULL, ("NULL callout in fork_exit"));
1152 callout(arg, frame);
1155 * Check if a kernel thread misbehaved and returned from its main
1158 if (p->p_flag & P_KPROC) {
1159 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
1160 td->td_name, p->p_pid);
1163 mtx_assert(&Giant, MA_NOTOWNED);
1165 if (p->p_sysent->sv_schedtail != NULL)
1166 (p->p_sysent->sv_schedtail)(td);
1167 td->td_pflags &= ~TDP_FORKING;
1171 * Simplified back end of syscall(), used when returning from fork()
1172 * directly into user mode. This function is passed in to fork_exit()
1173 * as the first parameter and is called when returning to a new
1177 fork_return(struct thread *td, struct trapframe *frame)
1182 if (td->td_dbgflags & TDB_STOPATFORK) {
1184 if ((p->p_flag & P_TRACED) != 0) {
1186 * Inform the debugger if one is still present.
1188 td->td_dbgflags |= TDB_CHILD | TDB_SCX | TDB_FSTP;
1189 ptracestop(td, SIGSTOP, NULL);
1190 td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX);
1193 * ... otherwise clear the request.
1195 td->td_dbgflags &= ~TDB_STOPATFORK;
1198 } else if (p->p_flag & P_TRACED) {
1200 * This is the start of a new thread in a traced
1201 * process. Report a system call exit event.
1204 td->td_dbgflags |= TDB_SCX;
1205 if ((p->p_ptevents & PTRACE_SCX) != 0 ||
1206 (td->td_dbgflags & TDB_BORN) != 0)
1207 ptracestop(td, SIGTRAP, NULL);
1208 td->td_dbgflags &= ~(TDB_SCX | TDB_BORN);
1213 * If the prison was killed mid-fork, die along with it.
1215 if (!prison_isalive(td->td_ucred->cr_prison))
1216 exit1(td, 0, SIGKILL);
1221 if (KTRPOINT(td, KTR_SYSRET))
1222 ktrsysret(td->td_sa.code, 0, 0);