]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_fork.c
If the credential on an incoming thread is correct, don't bother
[FreeBSD/FreeBSD.git] / sys / kern / kern_fork.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_fork.c 8.6 (Berkeley) 4/8/94
39  * $FreeBSD$
40  */
41
42 #include "opt_ktrace.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/sysctl.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/resourcevar.h>
55 #include <sys/syscall.h>
56 #include <sys/vnode.h>
57 #include <sys/acct.h>
58 #include <sys/ktr.h>
59 #include <sys/ktrace.h>
60 #include <sys/kthread.h>
61 #include <sys/unistd.h> 
62 #include <sys/jail.h>
63 #include <sys/sx.h>
64
65 #include <vm/vm.h>
66 #include <vm/pmap.h>
67 #include <vm/vm_map.h>
68 #include <vm/vm_extern.h>
69 #include <vm/vm_zone.h>
70
71 #include <sys/vmmeter.h>
72 #include <sys/user.h>
73
74 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback");
75
76 /*
77  * These are the stuctures used to create a callout list for things to do
78  * when forking a process
79  */
80 struct forklist {
81         forklist_fn function;
82         TAILQ_ENTRY(forklist) next;
83 };
84
85 static struct sx fork_list_lock;
86
87 TAILQ_HEAD(forklist_head, forklist);
88 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list);
89
90 #ifndef _SYS_SYSPROTO_H_
91 struct fork_args {
92         int     dummy;
93 };
94 #endif
95
96 static void
97 init_fork_list(void *data __unused)
98 {
99
100         sx_init(&fork_list_lock, "fork list");
101 }
102 SYSINIT(fork_list, SI_SUB_INTRINSIC, SI_ORDER_ANY, init_fork_list, NULL);
103
104 /*
105  * MPSAFE
106  */
107 /* ARGSUSED */
108 int
109 fork(td, uap)
110         struct thread *td;
111         struct fork_args *uap;
112 {
113         int error;
114         struct proc *p2;
115
116         mtx_lock(&Giant);
117         error = fork1(td, RFFDG | RFPROC, &p2);
118         if (error == 0) {
119                 td->td_retval[0] = p2->p_pid;
120                 td->td_retval[1] = 0;
121         }
122         mtx_unlock(&Giant);
123         return error;
124 }
125
126 /*
127  * MPSAFE
128  */
129 /* ARGSUSED */
130 int
131 vfork(td, uap)
132         struct thread *td;
133         struct vfork_args *uap;
134 {
135         int error;
136         struct proc *p2;
137
138         mtx_lock(&Giant);
139         error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, &p2);
140         if (error == 0) {
141                 td->td_retval[0] = p2->p_pid;
142                 td->td_retval[1] = 0;
143         }
144         mtx_unlock(&Giant);
145         return error;
146 }
147
148 /*
149  * MPSAFE
150  */
151 int
152 rfork(td, uap)
153         struct thread *td;
154         struct rfork_args *uap;
155 {
156         int error;
157         struct proc *p2;
158
159         /* Don't allow kernel only flags. */
160         if ((uap->flags & RFKERNELONLY) != 0)
161                 return (EINVAL);
162         mtx_lock(&Giant);
163         error = fork1(td, uap->flags, &p2);
164         if (error == 0) {
165                 td->td_retval[0] = p2 ? p2->p_pid : 0;
166                 td->td_retval[1] = 0;
167         }
168         mtx_unlock(&Giant);
169         return error;
170 }
171
172
173 int     nprocs = 1;                             /* process 0 */
174 int     lastpid = 0;
175 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0, 
176     "Last used PID");
177
178 /*
179  * Random component to lastpid generation.  We mix in a random factor to make
180  * it a little harder to predict.  We sanity check the modulus value to avoid
181  * doing it in critical paths.  Don't let it be too small or we pointlessly
182  * waste randomness entropy, and don't let it be impossibly large.  Using a
183  * modulus that is too big causes a LOT more process table scans and slows
184  * down fork processing as the pidchecked caching is defeated.
185  */
186 static int randompid = 0;
187
188 static int
189 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
190 {
191         int error, pid;
192
193         pid = randompid;
194         error = sysctl_handle_int(oidp, &pid, 0, req);
195         if (error || !req->newptr)
196                 return (error);
197         if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
198                 pid = PID_MAX - 100;
199         else if (pid < 2)                       /* NOP */
200                 pid = 0;
201         else if (pid < 100)                     /* Make it reasonable */
202                 pid = 100;
203         randompid = pid;
204         return (error);
205 }
206
207 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
208     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
209
210 #if 0
211 void
212 kse_init(struct kse *kse1, struct kse *kse2) 
213 {
214 }
215
216 void
217 thread_init(struct thread *thread1, struct thread *thread2) 
218 {
219 }
220
221 void
222 ksegrp_init(struct ksegrp *ksegrp1, struct ksegrp *ksegrp2) 
223 {
224 }
225 #endif
226
227 int
228 fork1(td, flags, procp)
229         struct thread *td;                      /* parent proc */
230         int flags;
231         struct proc **procp;                    /* child proc */
232 {
233         struct proc *p2, *pptr;
234         uid_t uid;
235         struct proc *newproc;
236         int trypid;
237         int ok;
238         static int pidchecked = 0;
239         struct forklist *ep;
240         struct filedesc *fd;
241         struct proc *p1 = td->td_proc;
242         struct thread *td2;
243         struct kse *ke2;
244         struct ksegrp *kg2;
245
246         GIANT_REQUIRED;
247
248         /* Can't copy and clear */
249         if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
250                 return (EINVAL);
251
252         /*
253          * Here we don't create a new process, but we divorce
254          * certain parts of a process from itself.
255          */
256         if ((flags & RFPROC) == 0) {
257                 vm_forkproc(td, NULL, NULL, flags);
258
259                 /*
260                  * Close all file descriptors.
261                  */
262                 if (flags & RFCFDG) {
263                         struct filedesc *fdtmp;
264                         fdtmp = fdinit(td);     /* XXXKSE */
265                         PROC_LOCK(p1);
266                         fdfree(td);             /* XXXKSE */
267                         p1->p_fd = fdtmp;
268                         PROC_UNLOCK(p1);
269                 }
270
271                 /*
272                  * Unshare file descriptors (from parent.)
273                  */
274                 if (flags & RFFDG) {
275                         FILEDESC_LOCK(p1->p_fd);
276                         if (p1->p_fd->fd_refcnt > 1) {
277                                 struct filedesc *newfd;
278
279                                 newfd = fdcopy(td);
280                                 FILEDESC_UNLOCK(p1->p_fd);
281                                 PROC_LOCK(p1);
282                                 fdfree(td);
283                                 p1->p_fd = newfd;
284                                 PROC_UNLOCK(p1);
285                         } else
286                                 FILEDESC_UNLOCK(p1->p_fd);
287                 }
288                 *procp = NULL;
289                 return (0);
290         }
291
292         /*
293          * Although process entries are dynamically created, we still keep
294          * a global limit on the maximum number we will create.  Don't allow
295          * a nonprivileged user to use the last process; don't let root
296          * exceed the limit. The variable nprocs is the current number of
297          * processes, maxproc is the limit.
298          */
299         uid = p1->p_ucred->cr_ruid;
300         if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
301                 tablefull("proc");
302                 return (EAGAIN);
303         }
304         /*
305          * Increment the nprocs resource before blocking can occur.  There
306          * are hard-limits as to the number of processes that can run.
307          */
308         nprocs++;
309
310         /*
311          * Increment the count of procs running with this uid. Don't allow
312          * a nonprivileged user to exceed their current limit.
313          */
314         ok = chgproccnt(p1->p_ucred->cr_ruidinfo, 1,
315                 (uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
316         if (!ok) {
317                 /*
318                  * Back out the process count
319                  */
320                 nprocs--;
321                 return (EAGAIN);
322         }
323
324         /* Allocate new proc. */
325         newproc = zalloc(proc_zone);
326
327         /*
328          * Setup linkage for kernel based threading
329          */
330         if((flags & RFTHREAD) != 0) {
331                 newproc->p_peers = p1->p_peers;
332                 p1->p_peers = newproc;
333                 newproc->p_leader = p1->p_leader;
334         } else {
335                 newproc->p_peers = NULL;
336                 newproc->p_leader = newproc;
337         }
338
339         newproc->p_vmspace = NULL;
340
341         /*
342          * Find an unused process ID.  We remember a range of unused IDs
343          * ready to use (from lastpid+1 through pidchecked-1).
344          *
345          * If RFHIGHPID is set (used during system boot), do not allocate
346          * low-numbered pids.
347          */
348         sx_xlock(&allproc_lock);
349         trypid = lastpid + 1;
350         if (flags & RFHIGHPID) {
351                 if (trypid < 10) {
352                         trypid = 10;
353                 }
354         } else {
355                 if (randompid)
356                         trypid += arc4random() % randompid;
357         }
358 retry:
359         /*
360          * If the process ID prototype has wrapped around,
361          * restart somewhat above 0, as the low-numbered procs
362          * tend to include daemons that don't exit.
363          */
364         if (trypid >= PID_MAX) {
365                 trypid = trypid % PID_MAX;
366                 if (trypid < 100)
367                         trypid += 100;
368                 pidchecked = 0;
369         }
370         if (trypid >= pidchecked) {
371                 int doingzomb = 0;
372
373                 pidchecked = PID_MAX;
374                 /*
375                  * Scan the active and zombie procs to check whether this pid
376                  * is in use.  Remember the lowest pid that's greater
377                  * than trypid, so we can avoid checking for a while.
378                  */
379                 p2 = LIST_FIRST(&allproc);
380 again:
381                 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
382                         while (p2->p_pid == trypid ||
383                             p2->p_pgrp->pg_id == trypid ||
384                             p2->p_session->s_sid == trypid) {
385                                 trypid++;
386                                 if (trypid >= pidchecked)
387                                         goto retry;
388                         }
389                         if (p2->p_pid > trypid && pidchecked > p2->p_pid)
390                                 pidchecked = p2->p_pid;
391                         if (p2->p_pgrp->pg_id > trypid &&
392                             pidchecked > p2->p_pgrp->pg_id)
393                                 pidchecked = p2->p_pgrp->pg_id;
394                         if (p2->p_session->s_sid > trypid &&
395                             pidchecked > p2->p_session->s_sid)
396                                 pidchecked = p2->p_session->s_sid;
397                 }
398                 if (!doingzomb) {
399                         doingzomb = 1;
400                         p2 = LIST_FIRST(&zombproc);
401                         goto again;
402                 }
403         }
404
405         /*
406          * RFHIGHPID does not mess with the lastpid counter during boot.
407          */
408         if (flags & RFHIGHPID)
409                 pidchecked = 0;
410         else
411                 lastpid = trypid;
412
413         p2 = newproc;
414         p2->p_stat = SIDL;                      /* protect against others */
415         p2->p_pid = trypid;
416         LIST_INSERT_HEAD(&allproc, p2, p_list);
417         LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
418         sx_xunlock(&allproc_lock);
419
420         /*
421          * Make a proc table entry for the new process.
422          * Start by zeroing the section of proc that is zero-initialized,
423          * then copy the section that is copied directly from the parent.
424          */
425         td2 = thread_get(p2);
426         ke2 = &p2->p_kse;
427         kg2 = &p2->p_ksegrp;
428
429 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
430
431         bzero(&p2->p_startzero,
432             (unsigned) RANGEOF(struct proc, p_startzero, p_endzero));
433         bzero(&ke2->ke_startzero,
434             (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero));
435         bzero(&td2->td_startzero,
436             (unsigned) RANGEOF(struct thread, td_startzero, td_endzero));
437         bzero(&kg2->kg_startzero,
438             (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero));
439
440         PROC_LOCK(p1);
441         bcopy(&p1->p_startcopy, &p2->p_startcopy,
442             (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy));
443         bcopy(&td->td_kse->ke_startcopy, &ke2->ke_startcopy,
444             (unsigned) RANGEOF(struct kse, ke_startcopy, ke_endcopy));
445         bcopy(&td->td_startcopy, &td2->td_startcopy,
446             (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
447         bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy,
448             (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
449 #undef RANGEOF
450         PROC_UNLOCK(p1);
451
452         /*
453          * XXXKSE Theoretically only the running thread would get copied 
454          * Others in the kernel would be 'aborted' in the child.
455          * i.e return E*something*
456          */
457         proc_linkup(p2, kg2, ke2, td2);
458
459         mtx_init(&p2->p_mtx, "process lock", MTX_DEF);
460         PROC_LOCK(p2);
461         /* note.. XXXKSE no pcb or u-area yet */
462
463         /*
464          * Duplicate sub-structures as needed.
465          * Increase reference counts on shared objects.
466          * The p_stats and p_sigacts substructs are set in vm_forkproc.
467          */
468         p2->p_flag = 0;
469         mtx_lock_spin(&sched_lock);
470         p2->p_sflag = PS_INMEM;
471         if (p1->p_sflag & PS_PROFIL)
472                 startprofclock(p2);
473         mtx_unlock_spin(&sched_lock);
474         PROC_LOCK(p1);
475         p2->p_ucred = crhold(p1->p_ucred);
476         td2->td_ucred = crhold(p2->p_ucred);    /* XXXKSE */
477
478         if (p2->p_args)
479                 p2->p_args->ar_ref++;
480
481         if (flags & RFSIGSHARE) {
482                 p2->p_procsig = p1->p_procsig;
483                 p2->p_procsig->ps_refcnt++;
484                 if (p1->p_sigacts == &p1->p_uarea->u_sigacts) {
485                         struct sigacts *newsigacts;
486
487                         PROC_UNLOCK(p1);
488                         PROC_UNLOCK(p2);
489                         /* Create the shared sigacts structure */
490                         MALLOC(newsigacts, struct sigacts *,
491                             sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
492                         PROC_LOCK(p2);
493                         PROC_LOCK(p1);
494                         /*
495                          * Set p_sigacts to the new shared structure.
496                          * Note that this is updating p1->p_sigacts at the
497                          * same time, since p_sigacts is just a pointer to
498                          * the shared p_procsig->ps_sigacts.
499                          */
500                         p2->p_sigacts  = newsigacts;
501                         *p2->p_sigacts = p1->p_uarea->u_sigacts;
502                 }
503         } else {
504                 PROC_UNLOCK(p1);
505                 PROC_UNLOCK(p2);
506                 MALLOC(p2->p_procsig, struct procsig *, sizeof(struct procsig),
507                     M_SUBPROC, M_WAITOK);
508                 PROC_LOCK(p2);
509                 PROC_LOCK(p1);
510                 bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
511                 p2->p_procsig->ps_refcnt = 1;
512                 p2->p_sigacts = NULL;   /* finished in vm_forkproc() */
513         }
514         if (flags & RFLINUXTHPN) 
515                 p2->p_sigparent = SIGUSR1;
516         else
517                 p2->p_sigparent = SIGCHLD;
518
519         /* bump references to the text vnode (for procfs) */
520         p2->p_textvp = p1->p_textvp;
521         PROC_UNLOCK(p1);
522         PROC_UNLOCK(p2);
523         if (p2->p_textvp)
524                 VREF(p2->p_textvp);
525
526         if (flags & RFCFDG)
527                 fd = fdinit(td);
528         else if (flags & RFFDG) {
529                 FILEDESC_LOCK(p1->p_fd);
530                 fd = fdcopy(td);
531                 FILEDESC_UNLOCK(p1->p_fd);
532         } else
533                 fd = fdshare(p1);
534         PROC_LOCK(p2);
535         p2->p_fd = fd;
536
537         /*
538          * If p_limit is still copy-on-write, bump refcnt,
539          * otherwise get a copy that won't be modified.
540          * (If PL_SHAREMOD is clear, the structure is shared
541          * copy-on-write.)
542          */
543         PROC_LOCK(p1);
544         if (p1->p_limit->p_lflags & PL_SHAREMOD)
545                 p2->p_limit = limcopy(p1->p_limit);
546         else {
547                 p2->p_limit = p1->p_limit;
548                 p2->p_limit->p_refcnt++;
549         }
550
551         /*
552          * Preserve some more flags in subprocess.  PS_PROFIL has already
553          * been preserved.
554          */
555         p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
556         if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
557                 p2->p_flag |= P_CONTROLT;
558         if (flags & RFPPWAIT)
559                 p2->p_flag |= P_PPWAIT;
560
561         LIST_INSERT_AFTER(p1, p2, p_pglist);
562         PROC_UNLOCK(p1);
563         PROC_UNLOCK(p2);
564
565         /*
566          * Attach the new process to its parent.
567          *
568          * If RFNOWAIT is set, the newly created process becomes a child
569          * of init.  This effectively disassociates the child from the
570          * parent.
571          */
572         if (flags & RFNOWAIT)
573                 pptr = initproc;
574         else
575                 pptr = p1;
576         sx_xlock(&proctree_lock);
577         PROC_LOCK(p2);
578         p2->p_pptr = pptr;
579         PROC_UNLOCK(p2);
580         LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
581         sx_xunlock(&proctree_lock);
582         PROC_LOCK(p2);
583         LIST_INIT(&p2->p_children);
584         LIST_INIT(&td2->td_contested); /* XXXKSE only 1 thread? */
585
586         callout_init(&p2->p_itcallout, 0);
587         callout_init(&td2->td_slpcallout, 1); /* XXXKSE */
588
589         PROC_LOCK(p1);
590 #ifdef KTRACE
591         /*
592          * Copy traceflag and tracefile if enabled.  If not inherited,
593          * these were zeroed above but we still could have a trace race
594          * so make sure p2's p_tracep is NULL.
595          */
596         if ((p1->p_traceflag & KTRFAC_INHERIT) && p2->p_tracep == NULL) {
597                 p2->p_traceflag = p1->p_traceflag;
598                 if ((p2->p_tracep = p1->p_tracep) != NULL) {
599                         PROC_UNLOCK(p1);
600                         PROC_UNLOCK(p2);
601                         VREF(p2->p_tracep);
602                         PROC_LOCK(p2);
603                         PROC_LOCK(p1);
604                 }
605         }
606 #endif
607
608         /*
609          * set priority of child to be that of parent
610          * XXXKSE hey! copying the estcpu seems dodgy.. should split it..
611          */
612         mtx_lock_spin(&sched_lock);
613         p2->p_ksegrp.kg_estcpu = p1->p_ksegrp.kg_estcpu;
614         mtx_unlock_spin(&sched_lock);
615
616         /*
617          * This begins the section where we must prevent the parent
618          * from being swapped.
619          */
620         _PHOLD(p1);
621         PROC_UNLOCK(p1);
622         PROC_UNLOCK(p2);
623
624         /*
625          * Finish creating the child process.  It will return via a different
626          * execution path later.  (ie: directly into user mode)
627          */
628         vm_forkproc(td, p2, td2, flags);
629
630         if (flags == (RFFDG | RFPROC)) {
631                 cnt.v_forks++;
632                 cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
633         } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
634                 cnt.v_vforks++;
635                 cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
636         } else if (p1 == &proc0) {
637                 cnt.v_kthreads++;
638                 cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
639         } else {
640                 cnt.v_rforks++;
641                 cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
642         }
643
644         /*
645          * Both processes are set up, now check if any loadable modules want
646          * to adjust anything.
647          *   What if they have an error? XXX
648          */
649         sx_slock(&fork_list_lock);
650         TAILQ_FOREACH(ep, &fork_list, next) {
651                 (*ep->function)(p1, p2, flags);
652         }
653         sx_sunlock(&fork_list_lock);
654
655         /*
656          * If RFSTOPPED not requested, make child runnable and add to
657          * run queue.
658          */
659         microtime(&(p2->p_stats->p_start));
660         p2->p_acflag = AFORK;
661         if ((flags & RFSTOPPED) == 0) {
662                 mtx_lock_spin(&sched_lock);
663                 p2->p_stat = SRUN;
664                 setrunqueue(td2);
665                 mtx_unlock_spin(&sched_lock);
666         }
667
668         /*
669          * Now can be swapped.
670          */
671         PROC_LOCK(p1);
672         _PRELE(p1);
673
674         /*
675          * tell any interested parties about the new process
676          */
677         KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
678         PROC_UNLOCK(p1);
679
680         /*
681          * Preserve synchronization semantics of vfork.  If waiting for
682          * child to exec or exit, set P_PPWAIT on child, and sleep on our
683          * proc (in case of exit).
684          */
685         PROC_LOCK(p2);
686         while (p2->p_flag & P_PPWAIT)
687                 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
688         PROC_UNLOCK(p2);
689
690         /*
691          * Return child proc pointer to parent.
692          */
693         *procp = p2;
694         return (0);
695 }
696
697 /*
698  * The next two functionms are general routines to handle adding/deleting
699  * items on the fork callout list.
700  *
701  * at_fork():
702  * Take the arguments given and put them onto the fork callout list,
703  * However first make sure that it's not already there.
704  * Returns 0 on success or a standard error number.
705  */
706
707 int
708 at_fork(function)
709         forklist_fn function;
710 {
711         struct forklist *ep;
712
713 #ifdef INVARIANTS
714         /* let the programmer know if he's been stupid */
715         if (rm_at_fork(function)) 
716                 printf("WARNING: fork callout entry (%p) already present\n",
717                     function);
718 #endif
719         ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
720         if (ep == NULL)
721                 return (ENOMEM);
722         ep->function = function;
723         sx_xlock(&fork_list_lock);
724         TAILQ_INSERT_TAIL(&fork_list, ep, next);
725         sx_xunlock(&fork_list_lock);
726         return (0);
727 }
728
729 /*
730  * Scan the exit callout list for the given item and remove it..
731  * Returns the number of items removed (0 or 1)
732  */
733
734 int
735 rm_at_fork(function)
736         forklist_fn function;
737 {
738         struct forklist *ep;
739
740         sx_xlock(&fork_list_lock);
741         TAILQ_FOREACH(ep, &fork_list, next) {
742                 if (ep->function == function) {
743                         TAILQ_REMOVE(&fork_list, ep, next);
744                         sx_xunlock(&fork_list_lock);
745                         free(ep, M_ATFORK);
746                         return(1);
747                 }
748         }
749         sx_xunlock(&fork_list_lock);
750         return (0);
751 }
752
753 /*
754  * Handle the return of a child process from fork1().  This function
755  * is called from the MD fork_trampoline() entry point.
756  */
757 void
758 fork_exit(callout, arg, frame)
759         void (*callout)(void *, struct trapframe *);
760         void *arg;
761         struct trapframe *frame;
762 {
763         struct thread *td = curthread;
764         struct proc *p = td->td_proc;
765
766         td->td_kse->ke_oncpu = PCPU_GET(cpuid);
767         /*
768          * Setup the sched_lock state so that we can release it.
769          */
770         sched_lock.mtx_lock = (uintptr_t)td;
771         sched_lock.mtx_recurse = 0;
772         td->td_critnest = 1;
773         td->td_savecrit = CRITICAL_FORK;
774         CTR3(KTR_PROC, "fork_exit: new proc %p (pid %d, %s)", p, p->p_pid,
775             p->p_comm);
776         if (PCPU_GET(switchtime.tv_sec) == 0)
777                 microuptime(PCPU_PTR(switchtime));
778         PCPU_SET(switchticks, ticks);
779         mtx_unlock_spin(&sched_lock);
780
781         /*
782          * cpu_set_fork_handler intercepts this function call to
783          * have this call a non-return function to stay in kernel mode.
784          * initproc has its own fork handler, but it does return.
785          */
786         KASSERT(callout != NULL, ("NULL callout in fork_exit"));
787         callout(arg, frame);
788
789         /*
790          * Check if a kernel thread misbehaved and returned from its main
791          * function.
792          */
793         PROC_LOCK(p);
794         if (p->p_flag & P_KTHREAD) {
795                 PROC_UNLOCK(p);
796                 mtx_lock(&Giant);
797                 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
798                     p->p_comm, p->p_pid);
799                 kthread_exit(0);
800         }
801         PROC_UNLOCK(p);
802 #ifdef  INVARIANTS
803         mtx_lock(&Giant);
804         crfree(td->td_ucred);
805         mtx_unlock(&Giant);
806         td->td_ucred = NULL;
807 #endif
808         mtx_assert(&Giant, MA_NOTOWNED);
809 }
810
811 /*
812  * Simplified back end of syscall(), used when returning from fork()
813  * directly into user mode.  Giant is not held on entry, and must not
814  * be held on return.  This function is passed in to fork_exit() as the
815  * first parameter and is called when returning to a new userland process.
816  */
817 void
818 fork_return(td, frame)
819         struct thread *td;
820         struct trapframe *frame;
821 {
822
823         userret(td, frame, 0);
824 #ifdef KTRACE
825         if (KTRPOINT(td->td_proc, KTR_SYSRET)) {
826                 ktrsysret(td->td_proc->p_tracep, SYS_fork, 0, 0);
827         }
828 #endif
829         mtx_assert(&Giant, MA_NOTOWNED);
830 }