]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_fork.c
zfs: merge openzfs/zfs@eb62221ff (zfs-2.1-release) into stable/13
[FreeBSD/FreeBSD.git] / sys / kern / kern_fork.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  *
36  *      @(#)kern_fork.c 8.6 (Berkeley) 4/8/94
37  */
38
39 #include <sys/cdefs.h>
40 #include "opt_ktrace.h"
41 #include "opt_kstack_pages.h"
42
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>
50 #include <sys/jail.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/sysctl.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mutex.h>
57 #include <sys/priv.h>
58 #include <sys/proc.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>
67 #include <sys/acct.h>
68 #include <sys/ktr.h>
69 #include <sys/ktrace.h>
70 #include <sys/unistd.h>
71 #include <sys/sdt.h>
72 #include <sys/sx.h>
73 #include <sys/sysent.h>
74 #include <sys/signalvar.h>
75
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
78
79 #include <vm/vm.h>
80 #include <vm/pmap.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_extern.h>
83 #include <vm/uma.h>
84
85 #ifdef KDTRACE_HOOKS
86 #include <sys/dtrace_bsd.h>
87 dtrace_fork_func_t      dtrace_fasttrap_fork;
88 #endif
89
90 SDT_PROVIDER_DECLARE(proc);
91 SDT_PROBE_DEFINE3(proc, , , create, "struct proc *", "struct proc *", "int");
92
93 #ifndef _SYS_SYSPROTO_H_
94 struct fork_args {
95         int     dummy;
96 };
97 #endif
98
99 /* ARGSUSED */
100 int
101 sys_fork(struct thread *td, struct fork_args *uap)
102 {
103         struct fork_req fr;
104         int error, pid;
105
106         bzero(&fr, sizeof(fr));
107         fr.fr_flags = RFFDG | RFPROC;
108         fr.fr_pidp = &pid;
109         error = fork1(td, &fr);
110         if (error == 0) {
111                 td->td_retval[0] = pid;
112                 td->td_retval[1] = 0;
113         }
114         return (error);
115 }
116
117 /* ARGUSED */
118 int
119 sys_pdfork(struct thread *td, struct pdfork_args *uap)
120 {
121         struct fork_req fr;
122         int error, fd, pid;
123
124         bzero(&fr, sizeof(fr));
125         fr.fr_flags = RFFDG | RFPROC | RFPROCDESC;
126         fr.fr_pidp = &pid;
127         fr.fr_pd_fd = &fd;
128         fr.fr_pd_flags = uap->flags;
129         AUDIT_ARG_FFLAGS(uap->flags);
130         /*
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.
134          */
135         error = fork1(td, &fr);
136         if (error == 0) {
137                 td->td_retval[0] = pid;
138                 td->td_retval[1] = 0;
139                 error = copyout(&fd, uap->fdp, sizeof(fd));
140         }
141         return (error);
142 }
143
144 /* ARGSUSED */
145 int
146 sys_vfork(struct thread *td, struct vfork_args *uap)
147 {
148         struct fork_req fr;
149         int error, pid;
150
151         bzero(&fr, sizeof(fr));
152         fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM;
153         fr.fr_pidp = &pid;
154         error = fork1(td, &fr);
155         if (error == 0) {
156                 td->td_retval[0] = pid;
157                 td->td_retval[1] = 0;
158         }
159         return (error);
160 }
161
162 int
163 sys_rfork(struct thread *td, struct rfork_args *uap)
164 {
165         struct fork_req fr;
166         int error, pid;
167
168         /* Don't allow kernel-only flags. */
169         if ((uap->flags & RFKERNELONLY) != 0)
170                 return (EINVAL);
171         /* RFSPAWN must not appear with others */
172         if ((uap->flags & RFSPAWN) != 0 && uap->flags != RFSPAWN)
173                 return (EINVAL);
174
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;
180         } else {
181                 fr.fr_flags = uap->flags;
182         }
183         fr.fr_pidp = &pid;
184         error = fork1(td, &fr);
185         if (error == 0) {
186                 td->td_retval[0] = pid;
187                 td->td_retval[1] = 0;
188         }
189         return (error);
190 }
191
192 int __exclusive_cache_line      nprocs = 1;             /* process 0 */
193 int     lastpid = 0;
194 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
195     "Last used PID");
196
197 /*
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.
204  */
205 static int randompid = 0;
206
207 static int
208 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
209 {
210         int error, pid;
211
212         error = sysctl_wire_old_buffer(req, sizeof(int));
213         if (error != 0)
214                 return(error);
215         sx_xlock(&allproc_lock);
216         pid = randompid;
217         error = sysctl_handle_int(oidp, &pid, 0, req);
218         if (error == 0 && req->newptr != NULL) {
219                 if (pid == 0)
220                         randompid = 0;
221                 else if (pid == 1)
222                         /* generate a random PID modulus between 100 and 1123 */
223                         randompid = 100 + arc4random() % 1024;
224                 else if (pid < 0 || pid > pid_max - 100)
225                         /* out of range */
226                         randompid = pid_max - 100;
227                 else if (pid < 100)
228                         /* Make it reasonable */
229                         randompid = 100;
230                 else
231                         randompid = pid;
232         }
233         sx_xunlock(&allproc_lock);
234         return (error);
235 }
236
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");
241
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;
246
247 /*
248  * Find an unused process ID
249  *
250  * If RFHIGHPID is set (used during system boot), do not allocate
251  * low-numbered pids.
252  */
253 static int
254 fork_findpid(int flags)
255 {
256         pid_t result;
257         int trypid, random;
258
259         /*
260          * Avoid calling arc4random with procid_lock held.
261          */
262         random = 0;
263         if (__predict_false(randompid))
264                 random = arc4random() % randompid;
265
266         mtx_lock(&procid_lock);
267
268         trypid = lastpid + 1;
269         if (flags & RFHIGHPID) {
270                 if (trypid < 10)
271                         trypid = 10;
272         } else {
273                 trypid += random;
274         }
275 retry:
276         if (trypid >= pid_max)
277                 trypid = 2;
278
279         bit_ffc_at(&proc_id_pidmap, trypid, pid_max, &result);
280         if (result == -1) {
281                 KASSERT(trypid != 2, ("unexpectedly ran out of IDs"));
282                 trypid = 2;
283                 goto retry;
284         }
285         if (bit_test(&proc_id_grpidmap, result) ||
286             bit_test(&proc_id_sessidmap, result) ||
287             bit_test(&proc_id_reapmap, result)) {
288                 trypid = result + 1;
289                 goto retry;
290         }
291
292         /*
293          * RFHIGHPID does not mess with the lastpid counter during boot.
294          */
295         if ((flags & RFHIGHPID) == 0)
296                 lastpid = result;
297
298         bit_set(&proc_id_pidmap, result);
299         mtx_unlock(&procid_lock);
300
301         return (result);
302 }
303
304 static int
305 fork_norfproc(struct thread *td, int flags)
306 {
307         struct proc *p1;
308         int error;
309
310         KASSERT((flags & RFPROC) == 0,
311             ("fork_norfproc called with RFPROC set"));
312         p1 = td->td_proc;
313
314         /*
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().
318          */
319         if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
320             ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
321                 PROC_LOCK(p1);
322                 if (thread_single(p1, SINGLE_BOUNDARY)) {
323                         PROC_UNLOCK(p1);
324                         return (ERESTART);
325                 }
326                 PROC_UNLOCK(p1);
327         }
328
329         error = vm_forkproc(td, NULL, NULL, NULL, flags);
330         if (error != 0)
331                 goto fail;
332
333         /*
334          * Close all file descriptors.
335          */
336         if ((flags & RFCFDG) != 0) {
337                 struct filedesc *fdtmp;
338                 struct pwddesc *pdtmp;
339
340                 pdtmp = pdinit(td->td_proc->p_pd, false);
341                 fdtmp = fdinit(td->td_proc->p_fd, false, NULL);
342                 pdescfree(td);
343                 fdescfree(td);
344                 p1->p_fd = fdtmp;
345                 p1->p_pd = pdtmp;
346         }
347
348         /*
349          * Unshare file descriptors (from parent).
350          */
351         if ((flags & RFFDG) != 0) {
352                 fdunshare(td);
353                 pdunshare(td);
354         }
355
356 fail:
357         if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS &&
358             ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) {
359                 PROC_LOCK(p1);
360                 thread_single_end(p1, SINGLE_BOUNDARY);
361                 PROC_UNLOCK(p1);
362         }
363         return (error);
364 }
365
366 static void
367 do_fork(struct thread *td, struct fork_req *fr, struct proc *p2, struct thread *td2,
368     struct vmspace *vm2, struct file *fp_procdesc)
369 {
370         struct proc *p1, *pptr;
371         struct filedesc *fd;
372         struct filedesc_to_leader *fdtol;
373         struct pwddesc *pd;
374         struct sigacts *newsigacts;
375
376         p1 = td->td_proc;
377
378         PROC_LOCK(p1);
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;
383         PROC_UNLOCK(p1);
384
385         bzero(&p2->p_startzero,
386             __rangeof(struct proc, p_startzero, p_endzero));
387
388         /* Tell the prison that we exist. */
389         prison_proc_hold(p2->p_ucred->cr_prison);
390
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);
395
396         sx_xlock(&allproc_lock);
397         LIST_INSERT_HEAD(&allproc, p2, p_list);
398         allproc_gen++;
399         sx_xunlock(&allproc_lock);
400
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));
404
405         tidhash_add(td2);
406
407         /*
408          * Malloc things while we don't hold any locks.
409          */
410         if (fr->fr_flags & RFSIGSHARE)
411                 newsigacts = NULL;
412         else
413                 newsigacts = sigacts_alloc();
414
415         /*
416          * Copy filedesc.
417          */
418         if (fr->fr_flags & RFCFDG) {
419                 pd = pdinit(p1->p_pd, false);
420                 fd = fdinit(p1->p_fd, false, NULL);
421                 fdtol = NULL;
422         } else if (fr->fr_flags & RFFDG) {
423                 if (fr->fr_flags2 & FR2_SHARE_PATHS)
424                         pd = pdshare(p1->p_pd);
425                 else
426                         pd = pdcopy(p1->p_pd);
427                 fd = fdcopy(p1->p_fd);
428                 fdtol = NULL;
429         } else {
430                 if (fr->fr_flags2 & FR2_SHARE_PATHS)
431                         pd = pdcopy(p1->p_pd);
432                 else
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,
437                             p1->p_leader);
438                 if ((fr->fr_flags & RFTHREAD) != 0) {
439                         /*
440                          * Shared file descriptor table, and shared
441                          * process leaders.
442                          */
443                         fdtol = filedesc_to_leader_share(p1->p_fdtol, p1->p_fd);
444                 } else {
445                         /*
446                          * Shared file descriptor table, and different
447                          * process leaders.
448                          */
449                         fdtol = filedesc_to_leader_alloc(p1->p_fdtol,
450                             p1->p_fd, p2);
451                 }
452         }
453         /*
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.
457          */
458
459         PROC_LOCK(p2);
460         PROC_LOCK(p1);
461
462         bzero(&td2->td_startzero,
463             __rangeof(struct thread, td_startzero, td_endzero));
464
465         bcopy(&td->td_startcopy, &td2->td_startcopy,
466             __rangeof(struct thread, td_startcopy, td_endcopy));
467
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;
472
473 #ifdef VIMAGE
474         td2->td_vnet = NULL;
475         td2->td_vnet_lpush = NULL;
476 #endif
477
478         /*
479          * Allow the scheduler to initialize the child.
480          */
481         thread_lock(td);
482         sched_fork(td, td2);
483         thread_unlock(td);
484
485         /*
486          * Duplicate sub-structures as needed.
487          * Increase reference counts on shared objects.
488          */
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)
497                 startprofclock(p2);
498
499         if (fr->fr_flags & RFSIGSHARE) {
500                 p2->p_sigacts = sigacts_hold(p1->p_sigacts);
501         } else {
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)
507                                 sig_drop_caught(p2);
508                         if ((fr->fr_flags2 & FR2_KPROC) != 0)
509                                 p2->p_sigacts->ps_flag |= PS_NOCLDWAIT;
510                         mtx_unlock(&p2->p_sigacts->ps_mtx);
511                 }
512         }
513
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;
518         else
519                 p2->p_sigparent = SIGCHLD;
520
521         if ((fr->fr_flags2 & FR2_KPROC) != 0) {
522                 p2->p_flag |= P_SYSTEM | P_KPROC;
523                 td2->td_pflags |= TDP_KTHREAD;
524         }
525
526         p2->p_textvp = p1->p_textvp;
527         p2->p_textdvp = p1->p_textdvp;
528         p2->p_fd = fd;
529         p2->p_fdtol = fdtol;
530         p2->p_pd = pd;
531         p2->p_elf_brandinfo = p1->p_elf_brandinfo;
532
533         if (p1->p_flag2 & P2_INHERIT_PROTECTED) {
534                 p2->p_flag |= P_PROTECTED;
535                 p2->p_flag2 |= P2_INHERIT_PROTECTED;
536         }
537
538         /*
539          * p_limit is copy-on-write.  Bump its refcount.
540          */
541         lim_fork(p1, p2);
542
543         thread_cow_get_proc(td2, p2);
544
545         pstats_fork(p1->p_stats, p2->p_stats);
546
547         PROC_UNLOCK(p1);
548         PROC_UNLOCK(p2);
549
550         /*
551          * Bump references to the text vnode and directory, and copy
552          * the hardlink name.
553          */
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);
560
561         /*
562          * Set up linkage for kernel based threading.
563          */
564         if ((fr->fr_flags & RFTHREAD) != 0) {
565                 mtx_lock(&ppeers_lock);
566                 p2->p_peers = p1->p_peers;
567                 p1->p_peers = p2;
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);
573                         /*
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
584                          * to commit suicide.
585                          */
586                         PROC_LOCK(p2);
587                         kern_psignal(p2, SIGKILL);
588                         PROC_UNLOCK(p2);
589                 } else
590                         PROC_UNLOCK(p1->p_leader);
591         } else {
592                 p2->p_peers = NULL;
593                 p2->p_leader = p2;
594         }
595
596         sx_xlock(&proctree_lock);
597         PGRP_LOCK(p1->p_pgrp);
598         PROC_LOCK(p2);
599         PROC_LOCK(p1);
600
601         /*
602          * Preserve some more flags in subprocess.  P_PROFIL has already
603          * been preserved.
604          */
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;
614
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);
620
621         callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0);
622         TAILQ_INIT(&p2->p_kqtim_stop);
623
624         /*
625          * This begins the section where we must prevent the parent
626          * from being swapped.
627          */
628         _PHOLD(p1);
629         PROC_UNLOCK(p1);
630
631         /*
632          * Attach the new process to its parent.
633          *
634          * If RFNOWAIT is set, the newly created process becomes a child
635          * of init.  This effectively disassociates the child from the
636          * parent.
637          */
638         if ((fr->fr_flags & RFNOWAIT) != 0) {
639                 pptr = p1->p_reaper;
640                 p2->p_reaper = pptr;
641         } else {
642                 p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ?
643                     p1 : p1->p_reaper;
644                 pptr = p1;
645         }
646         p2->p_pptr = pptr;
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);
654         }
655         sx_xunlock(&proctree_lock);
656
657         /* Inform accounting that we have forked. */
658         p2->p_acflag = AFORK;
659         PROC_UNLOCK(p2);
660
661 #ifdef KTRACE
662         ktrprocfork(p1, p2);
663 #endif
664
665         /*
666          * Finish creating the child process.  It will return via a different
667          * execution path later.  (ie: directly into user mode)
668          */
669         vm_forkproc(td, p2, td2, vm2, fr->fr_flags);
670
671         if (fr->fr_flags == (RFFDG | RFPROC)) {
672                 VM_CNT_INC(v_forks);
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);
683         } else {
684                 VM_CNT_INC(v_rforks);
685                 VM_CNT_ADD(v_rforkpages, p2->p_vmspace->vm_dsize +
686                     p2->p_vmspace->vm_ssize);
687         }
688
689         /*
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.
693          */
694         if (fr->fr_flags & RFPROCDESC)
695                 procdesc_new(p2, fr->fr_pd_flags);
696
697         /*
698          * Both processes are set up, now check if any loadable modules want
699          * to adjust anything.
700          */
701         EVENTHANDLER_DIRECT_INVOKE(process_fork, p1, p2, fr->fr_flags);
702
703         /*
704          * Set the child start time and mark the process as being complete.
705          */
706         PROC_LOCK(p2);
707         PROC_LOCK(p1);
708         microuptime(&p2->p_stats->p_start);
709         PROC_SLOCK(p2);
710         p2->p_state = PRS_NORMAL;
711         PROC_SUNLOCK(p2);
712
713 #ifdef KDTRACE_HOOKS
714         /*
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.
719          */
720         if ((fr->fr_flags & RFMEM) == 0 && dtrace_fasttrap_fork)
721                 dtrace_fasttrap_fork(p1, p2);
722 #endif
723         if (fr->fr_flags & RFPPWAIT) {
724                 td->td_pflags |= TDP_RFPPWAIT;
725                 td->td_rfppwait_p = p2;
726                 td->td_dbgflags |= TDB_VFORK;
727         }
728         PROC_UNLOCK(p2);
729
730         /*
731          * Tell any interested parties about the new process.
732          */
733         knote_fork(p1->p_klist, p2->p_pid);
734
735         /*
736          * Now can be swapped.
737          */
738         _PRELE(p1);
739         PROC_UNLOCK(p1);
740         SDT_PROBE3(proc, , , create, p2, p1, fr->fr_flags);
741
742         if (fr->fr_flags & RFPROCDESC) {
743                 procdesc_finit(p2->p_procdesc, fp_procdesc);
744                 fdrop(fp_procdesc, td);
745         }
746
747         /*
748          * Speculative check for PTRACE_FORK. PTRACE_FORK is not
749          * synced with forks in progress so it is OK if we miss it
750          * if being set atm.
751          */
752         if ((p1->p_ptevents & PTRACE_FORK) != 0) {
753                 sx_xlock(&proctree_lock);
754                 PROC_LOCK(p2);
755
756                 /*
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.
760                  */
761                 if ((p1->p_ptevents & PTRACE_FORK) != 0) {
762                         /*
763                          * Arrange for debugger to receive the fork event.
764                          *
765                          * We can report PL_FLAG_FORKED regardless of
766                          * P_FOLLOWFORK settings, but it does not make a sense
767                          * for runaway child.
768                          */
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);
773                         CTR2(KTR_PTRACE,
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);
777                 }
778                 PROC_UNLOCK(p2);
779                 sx_xunlock(&proctree_lock);
780         }
781
782         racct_proc_fork_done(p2);
783
784         if ((fr->fr_flags & RFSTOPPED) == 0) {
785                 if (fr->fr_pidp != NULL)
786                         *fr->fr_pidp = p2->p_pid;
787                 /*
788                  * If RFSTOPPED not requested, make child runnable and
789                  * add to run queue.
790                  */
791                 thread_lock(td2);
792                 TD_SET_CAN_RUN(td2);
793                 sched_add(td2, SRQ_BORING);
794         } else {
795                 *fr->fr_procp = p2;
796         }
797 }
798
799 void
800 fork_rfppwait(struct thread *td)
801 {
802         struct proc *p, *p2;
803
804         MPASS(td->td_pflags & TDP_RFPPWAIT);
805
806         p = td->td_proc;
807         /*
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
811          * (in case of exit).
812          *
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.
816          */
817         td->td_pflags &= ~TDP_RFPPWAIT;
818         p2 = td->td_rfppwait_p;
819 again:
820         PROC_LOCK(p2);
821         while (p2->p_flag & P_PPWAIT) {
822                 PROC_LOCK(p);
823                 if (thread_suspend_check_needed()) {
824                         PROC_UNLOCK(p2);
825                         thread_suspend_check(0);
826                         PROC_UNLOCK(p);
827                         goto again;
828                 } else {
829                         PROC_UNLOCK(p);
830                 }
831                 cv_timedwait(&p2->p_pwait, &p2->p_mtx, hz);
832         }
833         PROC_UNLOCK(p2);
834
835         if (td->td_dbgflags & TDB_VFORK) {
836                 PROC_LOCK(p);
837                 if (p->p_ptevents & PTRACE_VFORK)
838                         ptracestop(td, SIGTRAP, NULL);
839                 td->td_dbgflags &= ~TDB_VFORK;
840                 PROC_UNLOCK(p);
841         }
842 }
843
844 int
845 fork1(struct thread *td, struct fork_req *fr)
846 {
847         struct proc *p1, *newproc;
848         struct thread *td2;
849         struct vmspace *vm2;
850         struct ucred *cred;
851         struct file *fp_procdesc;
852         struct pgrp *pg;
853         vm_ooffset_t mem_charged;
854         int error, nprocs_new;
855         static int curfail;
856         static struct timeval lastfail;
857         int flags, pages;
858         bool killsx_locked, singlethreaded;
859
860         flags = fr->fr_flags;
861         pages = fr->fr_pages;
862
863         if ((flags & RFSTOPPED) != 0)
864                 MPASS(fr->fr_procp != NULL && fr->fr_pidp == NULL);
865         else
866                 MPASS(fr->fr_procp == NULL);
867
868         /* Check for the undefined or unimplemented flags. */
869         if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0)
870                 return (EINVAL);
871
872         /* Signal value requires RFTSIGZMB. */
873         if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0)
874                 return (EINVAL);
875
876         /* Can't copy and clear. */
877         if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
878                 return (EINVAL);
879
880         /* Check the validity of the signal number. */
881         if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG)
882                 return (EINVAL);
883
884         if ((flags & RFPROCDESC) != 0) {
885                 /* Can't not create a process yet get a process descriptor. */
886                 if ((flags & RFPROC) == 0)
887                         return (EINVAL);
888
889                 /* Must provide a place to put a procdesc if creating one. */
890                 if (fr->fr_pd_fd == NULL)
891                         return (EINVAL);
892
893                 /* Check if we are using supported flags. */
894                 if ((fr->fr_pd_flags & ~PD_ALLOWED_AT_FORK) != 0)
895                         return (EINVAL);
896         }
897
898         p1 = td->td_proc;
899
900         /*
901          * Here we don't create a new process, but we divorce
902          * certain parts of a process from itself.
903          */
904         if ((flags & RFPROC) == 0) {
905                 if (fr->fr_procp != NULL)
906                         *fr->fr_procp = NULL;
907                 else if (fr->fr_pidp != NULL)
908                         *fr->fr_pidp = 0;
909                 return (fork_norfproc(td, flags));
910         }
911
912         fp_procdesc = NULL;
913         newproc = NULL;
914         vm2 = NULL;
915         killsx_locked = false;
916         singlethreaded = false;
917
918         /*
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
924          * the process data.
925          *
926          * Don't allow a nonprivileged user to use the last ten
927          * processes; don't let root exceed the limit.
928          */
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) {
933                         error = EAGAIN;
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 "
938                                     "login.conf(5)\n",
939                                     td->td_ucred->cr_ruid, p1->p_pid);
940                         }
941                         sx_xunlock(&allproc_lock);
942                         goto fail2;
943                 }
944         }
945
946         /*
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.
952          */
953         pg = p1->p_pgrp;
954         if (p1->p_numthreads > 1) {
955                 if (sx_try_slock(&pg->pg_killsx) != 0) {
956                         killsx_locked = true;
957                 } else {
958                         PROC_LOCK(p1);
959                         if (thread_single(p1, SINGLE_BOUNDARY)) {
960                                 PROC_UNLOCK(p1);
961                                 error = ERESTART;
962                                 goto fail2;
963                         }
964                         PROC_UNLOCK(p1);
965                         singlethreaded = true;
966                 }
967         }
968
969         /*
970          * Atomically check for signals and block processes from sending
971          * a signal to our process group until the child is visible.
972          */
973         if (!killsx_locked && sx_slock_sig(&pg->pg_killsx) != 0) {
974                 error = ERESTART;
975                 goto fail2;
976         }
977         if (__predict_false(p1->p_pgrp != pg || sig_intr() != 0)) {
978                 /*
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
982                  * lock.
983                  */
984                 sx_sunlock(&pg->pg_killsx);
985                 killsx_locked = false;
986                 error = ERESTART;
987                 goto fail2;
988         } else {
989                 killsx_locked = true;
990         }
991
992         /*
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
995          * later.
996          */
997         if (flags & RFPROCDESC) {
998                 error = procdesc_falloc(td, &fp_procdesc, fr->fr_pd_fd,
999                     fr->fr_pd_flags, fr->fr_pd_fcaps);
1000                 if (error != 0)
1001                         goto fail2;
1002                 AUDIT_ARG_FD(*fr->fr_pd_fd);
1003         }
1004
1005         mem_charged = 0;
1006         if (pages == 0)
1007                 pages = kstack_pages;
1008         /* Allocate new proc. */
1009         newproc = uma_zalloc(proc_zone, M_WAITOK);
1010         td2 = FIRST_THREAD_IN_PROC(newproc);
1011         if (td2 == NULL) {
1012                 td2 = thread_alloc(pages);
1013                 if (td2 == NULL) {
1014                         error = ENOMEM;
1015                         goto fail2;
1016                 }
1017                 proc_linkup(newproc, td2);
1018         } else {
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)) {
1023                                 error = ENOMEM;
1024                                 goto fail2;
1025                         }
1026                 }
1027         }
1028
1029         if ((flags & RFMEM) == 0) {
1030                 vm2 = vmspace_fork(p1->p_vmspace, &mem_charged);
1031                 if (vm2 == NULL) {
1032                         error = ENOMEM;
1033                         goto fail2;
1034                 }
1035                 if (!swap_reserve(mem_charged)) {
1036                         /*
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.
1041                          */
1042                         swap_reserve_force(mem_charged);
1043                         error = ENOMEM;
1044                         goto fail2;
1045                 }
1046         } else
1047                 vm2 = NULL;
1048
1049         /*
1050          * XXX: This is ugly; when we copy resource usage, we need to bump
1051          *      per-cred resource counters.
1052          */
1053         proc_set_cred_init(newproc, td->td_ucred);
1054
1055         /*
1056          * Initialize resource accounting for the child process.
1057          */
1058         error = racct_proc_fork(p1, newproc);
1059         if (error != 0) {
1060                 error = EAGAIN;
1061                 goto fail1;
1062         }
1063
1064 #ifdef MAC
1065         mac_proc_init(newproc);
1066 #endif
1067         newproc->p_klist = knlist_alloc(&newproc->p_mtx);
1068         STAILQ_INIT(&newproc->p_ktr);
1069
1070         /*
1071          * Increment the count of procs running with this uid. Don't allow
1072          * a nonprivileged user to exceed their current limit.
1073          */
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)
1077                         goto fail0;
1078                 chgproccnt(cred->cr_ruidinfo, 1, 0);
1079         }
1080
1081         do_fork(td, fr, newproc, td2, vm2, fp_procdesc);
1082         error = 0;
1083         goto cleanup;
1084 fail0:
1085         error = EAGAIN;
1086 #ifdef MAC
1087         mac_proc_destroy(newproc);
1088 #endif
1089         racct_proc_exit(newproc);
1090 fail1:
1091         proc_unset_cred(newproc);
1092 fail2:
1093         if (vm2 != NULL)
1094                 vmspace_free(vm2);
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);
1099         }
1100         atomic_add_int(&nprocs, -1);
1101 cleanup:
1102         if (killsx_locked)
1103                 sx_sunlock(&pg->pg_killsx);
1104         if (singlethreaded) {
1105                 PROC_LOCK(p1);
1106                 thread_single_end(p1, SINGLE_BOUNDARY);
1107                 PROC_UNLOCK(p1);
1108         }
1109         if (error != 0)
1110                 pause("fork", hz / 2);
1111         return (error);
1112 }
1113
1114 /*
1115  * Handle the return of a child process from fork1().  This function
1116  * is called from the MD fork_trampoline() entry point.
1117  */
1118 void
1119 fork_exit(void (*callout)(void *, struct trapframe *), void *arg,
1120     struct trapframe *frame)
1121 {
1122         struct proc *p;
1123         struct thread *td;
1124         struct thread *dtd;
1125
1126         td = curthread;
1127         p = td->td_proc;
1128         KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new"));
1129
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);
1132
1133         sched_fork_exit(td);
1134
1135         /*
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.
1139          */
1140         if ((dtd = PCPU_GET(deadthread))) {
1141                 PCPU_SET(deadthread, NULL);
1142                 thread_stash(dtd);
1143         }
1144         thread_unlock(td);
1145
1146         /*
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.
1150          */
1151         KASSERT(callout != NULL, ("NULL callout in fork_exit"));
1152         callout(arg, frame);
1153
1154         /*
1155          * Check if a kernel thread misbehaved and returned from its main
1156          * function.
1157          */
1158         if (p->p_flag & P_KPROC) {
1159                 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
1160                     td->td_name, p->p_pid);
1161                 kthread_exit();
1162         }
1163         mtx_assert(&Giant, MA_NOTOWNED);
1164
1165         if (p->p_sysent->sv_schedtail != NULL)
1166                 (p->p_sysent->sv_schedtail)(td);
1167         td->td_pflags &= ~TDP_FORKING;
1168 }
1169
1170 /*
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
1174  * userland process.
1175  */
1176 void
1177 fork_return(struct thread *td, struct trapframe *frame)
1178 {
1179         struct proc *p;
1180
1181         p = td->td_proc;
1182         if (td->td_dbgflags & TDB_STOPATFORK) {
1183                 PROC_LOCK(p);
1184                 if ((p->p_flag & P_TRACED) != 0) {
1185                         /*
1186                          * Inform the debugger if one is still present.
1187                          */
1188                         td->td_dbgflags |= TDB_CHILD | TDB_SCX | TDB_FSTP;
1189                         ptracestop(td, SIGSTOP, NULL);
1190                         td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX);
1191                 } else {
1192                         /*
1193                          * ... otherwise clear the request.
1194                          */
1195                         td->td_dbgflags &= ~TDB_STOPATFORK;
1196                 }
1197                 PROC_UNLOCK(p);
1198         } else if (p->p_flag & P_TRACED) {
1199                 /*
1200                  * This is the start of a new thread in a traced
1201                  * process.  Report a system call exit event.
1202                  */
1203                 PROC_LOCK(p);
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);
1209                 PROC_UNLOCK(p);
1210         }
1211
1212         /*
1213          * If the prison was killed mid-fork, die along with it.
1214          */
1215         if (!prison_isalive(td->td_ucred->cr_prison))
1216                 exit1(td, 0, SIGKILL);
1217
1218         userret(td, frame);
1219
1220 #ifdef KTRACE
1221         if (KTRPOINT(td, KTR_SYSRET))
1222                 ktrsysret(td->td_sa.code, 0, 0);
1223 #endif
1224 }