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/pioctl.h> 55 #include <sys/resourcevar.h> 56 #include <sys/syscall.h> 57 #include <sys/vnode.h> 58 #include <sys/acct.h> 59 #include <sys/ktr.h> 60 #include <sys/ktrace.h> 61 #include <sys/kthread.h> 62 #include <sys/unistd.h> 63 #include <sys/jail.h> 64 #include <sys/sx.h> 65 66 #include <vm/vm.h> 67 #include <vm/pmap.h> 68 #include <vm/vm_map.h> 69 #include <vm/vm_extern.h> 70 #include <vm/uma.h> 71 72 #include <sys/vmmeter.h> 73 #include <sys/user.h> 74 #include <machine/critical.h> 75 76 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback"); 77 78 /* 79 * These are the stuctures used to create a callout list for things to do 80 * when forking a process 81 */ 82 struct forklist { 83 forklist_fn function; 84 TAILQ_ENTRY(forklist) next; 85 }; 86 87 static struct sx fork_list_lock; 88 89 TAILQ_HEAD(forklist_head, forklist); 90 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list); 91 92 #ifndef _SYS_SYSPROTO_H_ 93 struct fork_args { 94 int dummy; 95 }; 96 #endif 97 98 int forksleep; /* Place for fork1() to sleep on. */ 99 100 static void 101 init_fork_list(void *data __unused) 102 { 103 104 sx_init(&fork_list_lock, "fork list"); 105 } 106 SYSINIT(fork_list, SI_SUB_INTRINSIC, SI_ORDER_ANY, init_fork_list, NULL); 107 108 /* 109 * MPSAFE 110 */ 111 /* ARGSUSED */ 112 int 113 fork(td, uap) 114 struct thread *td; 115 struct fork_args *uap; 116 { 117 int error; 118 struct proc *p2; 119 120 mtx_lock(&Giant); 121 error = fork1(td, RFFDG | RFPROC, &p2); 122 if (error == 0) { 123 td->td_retval[0] = p2->p_pid; 124 td->td_retval[1] = 0; 125 } 126 mtx_unlock(&Giant); 127 return error; 128 } 129 130 /* 131 * MPSAFE 132 */ 133 /* ARGSUSED */ 134 int 135 vfork(td, uap) 136 struct thread *td; 137 struct vfork_args *uap; 138 { 139 int error; 140 struct proc *p2; 141 142 mtx_lock(&Giant); 143 error = fork1(td, RFFDG | RFPROC | RFPPWAIT | RFMEM, &p2); 144 if (error == 0) { 145 td->td_retval[0] = p2->p_pid; 146 td->td_retval[1] = 0; 147 } 148 mtx_unlock(&Giant); 149 return error; 150 } 151 152 /* 153 * MPSAFE 154 */ 155 int 156 rfork(td, uap) 157 struct thread *td; 158 struct rfork_args *uap; 159 { 160 int error; 161 struct proc *p2; 162 163 /* Don't allow kernel only flags. */ 164 if ((uap->flags & RFKERNELONLY) != 0) 165 return (EINVAL); 166 mtx_lock(&Giant); 167 error = fork1(td, uap->flags, &p2); 168 if (error == 0) { 169 td->td_retval[0] = p2 ? p2->p_pid : 0; 170 td->td_retval[1] = 0; 171 } 172 mtx_unlock(&Giant); 173 return error; 174 } 175 176 177 int nprocs = 1; /* process 0 */ 178 int lastpid = 0; 179 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0, 180 "Last used PID"); 181 182 /* 183 * Random component to lastpid generation. We mix in a random factor to make 184 * it a little harder to predict. We sanity check the modulus value to avoid 185 * doing it in critical paths. Don't let it be too small or we pointlessly 186 * waste randomness entropy, and don't let it be impossibly large. Using a 187 * modulus that is too big causes a LOT more process table scans and slows 188 * down fork processing as the pidchecked caching is defeated. 189 */ 190 static int randompid = 0; 191 192 static int 193 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS) 194 { 195 int error, pid; 196 197 sysctl_wire_old_buffer(req, sizeof(int)); 198 sx_xlock(&allproc_lock); 199 pid = randompid; 200 error = sysctl_handle_int(oidp, &pid, 0, req); 201 if (error == 0 && req->newptr != NULL) { 202 if (pid < 0 || pid > PID_MAX - 100) /* out of range */ 203 pid = PID_MAX - 100; 204 else if (pid < 2) /* NOP */ 205 pid = 0; 206 else if (pid < 100) /* Make it reasonable */ 207 pid = 100; 208 randompid = pid; 209 } 210 sx_xunlock(&allproc_lock); 211 return (error); 212 } 213 214 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW, 215 0, 0, sysctl_kern_randompid, "I", "Random PID modulus"); 216 217 int 218 fork1(td, flags, procp) 219 struct thread *td; /* parent proc */ 220 int flags; 221 struct proc **procp; /* child proc */ 222 { 223 struct proc *p2, *pptr; 224 uid_t uid; 225 struct proc *newproc; 226 int trypid; 227 int ok; 228 static int pidchecked = 0; 229 struct forklist *ep; 230 struct filedesc *fd; 231 struct proc *p1 = td->td_proc; 232 struct thread *td2; 233 struct kse *ke2; 234 struct ksegrp *kg2; 235 struct sigacts *newsigacts; 236 struct procsig *newprocsig; 237 238 GIANT_REQUIRED; 239 240 /* Can't copy and clear */ 241 if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG)) 242 return (EINVAL); 243 244 /* 245 * Here we don't create a new process, but we divorce 246 * certain parts of a process from itself. 247 */ 248 if ((flags & RFPROC) == 0) { 249 vm_forkproc(td, NULL, NULL, flags); 250 251 /* 252 * Close all file descriptors. 253 */ 254 if (flags & RFCFDG) { 255 struct filedesc *fdtmp; 256 fdtmp = fdinit(td); /* XXXKSE */ 257 PROC_LOCK(p1); 258 fdfree(td); /* XXXKSE */ 259 p1->p_fd = fdtmp; 260 PROC_UNLOCK(p1); 261 } 262 263 /* 264 * Unshare file descriptors (from parent.) 265 */ 266 if (flags & RFFDG) { 267 FILEDESC_LOCK(p1->p_fd); 268 if (p1->p_fd->fd_refcnt > 1) { 269 struct filedesc *newfd; 270 271 newfd = fdcopy(td); 272 FILEDESC_UNLOCK(p1->p_fd); 273 PROC_LOCK(p1); 274 fdfree(td); 275 p1->p_fd = newfd; 276 PROC_UNLOCK(p1); 277 } else 278 FILEDESC_UNLOCK(p1->p_fd); 279 } 280 *procp = NULL; 281 return (0); 282 } 283 284 if (p1->p_flag & P_KSES) { 285 /* 286 * Idle the other threads for a second. 287 * Since the user space is copied, it must remain stable. 288 * In addition, all threads (from the user perspective) 289 * need to either be suspended or in the kernel, 290 * where they will try restart in the parent and will 291 * be aborted in the child. 292 */ 293 PROC_LOCK(p1); 294 if (thread_single(SINGLE_NO_EXIT)) { 295 /* Abort.. someone else is single threading before us */ 296 PROC_UNLOCK(p1); 297 return (ERESTART); 298 } 299 PROC_UNLOCK(p1); 300 /* 301 * All other activity in this process 302 * is now suspended at the user boundary, 303 * (or other safe places if we think of any). 304 */ 305 } 306 307 /* Allocate new proc. */ 308 newproc = uma_zalloc(proc_zone, M_WAITOK); 309 310 /* 311 * Although process entries are dynamically created, we still keep 312 * a global limit on the maximum number we will create. Don't allow 313 * a nonprivileged user to use the last ten processes; don't let root 314 * exceed the limit. The variable nprocs is the current number of 315 * processes, maxproc is the limit. 316 */ 317 sx_xlock(&allproc_lock); 318 uid = td->td_ucred->cr_ruid; 319 if ((nprocs >= maxproc - 10 && uid != 0) || nprocs >= maxproc) { 320 sx_xunlock(&allproc_lock); 321 uma_zfree(proc_zone, newproc); 322 if (p1->p_flag & P_KSES) { 323 PROC_LOCK(p1); 324 thread_single_end(); 325 PROC_UNLOCK(p1); 326 } 327 tsleep(&forksleep, PUSER, "fork", hz / 2); 328 return (EAGAIN); 329 } 330 /* 331 * Increment the count of procs running with this uid. Don't allow 332 * a nonprivileged user to exceed their current limit. 333 */ 334 PROC_LOCK(p1); 335 ok = chgproccnt(td->td_ucred->cr_ruidinfo, 1, 336 (uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0); 337 PROC_UNLOCK(p1); 338 if (!ok) { 339 sx_xunlock(&allproc_lock); 340 uma_zfree(proc_zone, newproc); 341 if (p1->p_flag & P_KSES) { 342 PROC_LOCK(p1); 343 thread_single_end(); 344 PROC_UNLOCK(p1); 345 } 346 tsleep(&forksleep, PUSER, "fork", hz / 2); 347 return (EAGAIN); 348 } 349 350 /* 351 * Increment the nprocs resource before blocking can occur. There 352 * are hard-limits as to the number of processes that can run. 353 */ 354 nprocs++; 355 356 /* 357 * Find an unused process ID. We remember a range of unused IDs 358 * ready to use (from lastpid+1 through pidchecked-1). 359 * 360 * If RFHIGHPID is set (used during system boot), do not allocate 361 * low-numbered pids. 362 */ 363 trypid = lastpid + 1; 364 if (flags & RFHIGHPID) { 365 if (trypid < 10) { 366 trypid = 10; 367 } 368 } else { 369 if (randompid) 370 trypid += arc4random() % randompid; 371 } 372 retry: 373 /* 374 * If the process ID prototype has wrapped around, 375 * restart somewhat above 0, as the low-numbered procs 376 * tend to include daemons that don't exit. 377 */ 378 if (trypid >= PID_MAX) { 379 trypid = trypid % PID_MAX; 380 if (trypid < 100) 381 trypid += 100; 382 pidchecked = 0; 383 } 384 if (trypid >= pidchecked) { 385 int doingzomb = 0; 386 387 pidchecked = PID_MAX; 388 /* 389 * Scan the active and zombie procs to check whether this pid 390 * is in use. Remember the lowest pid that's greater 391 * than trypid, so we can avoid checking for a while. 392 */ 393 p2 = LIST_FIRST(&allproc); 394 again: 395 for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) { 396 PROC_LOCK(p2); 397 while (p2->p_pid == trypid || 398 p2->p_pgrp->pg_id == trypid || 399 p2->p_session->s_sid == trypid) { 400 trypid++; 401 if (trypid >= pidchecked) { 402 PROC_UNLOCK(p2); 403 goto retry; 404 } 405 } 406 if (p2->p_pid > trypid && pidchecked > p2->p_pid) 407 pidchecked = p2->p_pid; 408 if (p2->p_pgrp->pg_id > trypid && 409 pidchecked > p2->p_pgrp->pg_id) 410 pidchecked = p2->p_pgrp->pg_id; 411 if (p2->p_session->s_sid > trypid && 412 pidchecked > p2->p_session->s_sid) 413 pidchecked = p2->p_session->s_sid; 414 PROC_UNLOCK(p2); 415 } 416 if (!doingzomb) { 417 doingzomb = 1; 418 p2 = LIST_FIRST(&zombproc); 419 goto again; 420 } 421 } 422 423 /* 424 * RFHIGHPID does not mess with the lastpid counter during boot. 425 */ 426 if (flags & RFHIGHPID) 427 pidchecked = 0; 428 else 429 lastpid = trypid; 430 431 p2 = newproc; 432 p2->p_state = PRS_NEW; /* protect against others */ 433 p2->p_pid = trypid; 434 LIST_INSERT_HEAD(&allproc, p2, p_list); 435 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash); 436 sx_xunlock(&allproc_lock); 437 438 /* 439 * Malloc things while we don't hold any locks. 440 */ 441 if (flags & RFSIGSHARE) { 442 MALLOC(newsigacts, struct sigacts *, 443 sizeof(struct sigacts), M_SUBPROC, M_WAITOK); 444 newprocsig = NULL; 445 } else { 446 newsigacts = NULL; 447 MALLOC(newprocsig, struct procsig *, sizeof(struct procsig), 448 M_SUBPROC, M_WAITOK); 449 } 450 451 /* 452 * Copy filedesc. 453 * XXX: This is busted. fd*() need to not take proc 454 * arguments or something. 455 */ 456 if (flags & RFCFDG) 457 fd = fdinit(td); 458 else if (flags & RFFDG) { 459 FILEDESC_LOCK(p1->p_fd); 460 fd = fdcopy(td); 461 FILEDESC_UNLOCK(p1->p_fd); 462 } else 463 fd = fdshare(p1); 464 465 /* 466 * Make a proc table entry for the new process. 467 * Start by zeroing the section of proc that is zero-initialized, 468 * then copy the section that is copied directly from the parent. 469 */ 470 td2 = FIRST_THREAD_IN_PROC(p2); 471 kg2 = FIRST_KSEGRP_IN_PROC(p2); 472 ke2 = FIRST_KSE_IN_KSEGRP(kg2); 473 474 #define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start)) 475 476 bzero(&p2->p_startzero, 477 (unsigned) RANGEOF(struct proc, p_startzero, p_endzero)); 478 bzero(&ke2->ke_startzero, 479 (unsigned) RANGEOF(struct kse, ke_startzero, ke_endzero)); 480 bzero(&td2->td_startzero, 481 (unsigned) RANGEOF(struct thread, td_startzero, td_endzero)); 482 bzero(&kg2->kg_startzero, 483 (unsigned) RANGEOF(struct ksegrp, kg_startzero, kg_endzero)); 484 485 mtx_init(&p2->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK); 486 PROC_LOCK(p2); 487 PROC_LOCK(p1); 488 489 bcopy(&p1->p_startcopy, &p2->p_startcopy, 490 (unsigned) RANGEOF(struct proc, p_startcopy, p_endcopy)); 491 bcopy(&td->td_kse->ke_startcopy, &ke2->ke_startcopy, 492 (unsigned) RANGEOF(struct kse, ke_startcopy, ke_endcopy)); 493 bcopy(&td->td_startcopy, &td2->td_startcopy, 494 (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy)); 495 bcopy(&td->td_ksegrp->kg_startcopy, &kg2->kg_startcopy, 496 (unsigned) RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy)); 497 #undef RANGEOF 498 499 /* Set up the thread as an active thread (as if runnable). */ 500 TAILQ_REMOVE(&kg2->kg_iq, ke2, ke_kgrlist); 501 kg2->kg_idle_kses--; 502 ke2->ke_state = KES_THREAD; 503 ke2->ke_thread = td2; 504 td2->td_kse = ke2; 505 td2->td_flags &= ~TDF_UNBOUND; /* For the rest of this syscall. */ 506 507 /* 508 * Duplicate sub-structures as needed. 509 * Increase reference counts on shared objects. 510 * The p_stats and p_sigacts substructs are set in vm_forkproc. 511 */ 512 p2->p_flag = 0; 513 mtx_lock_spin(&sched_lock); 514 p2->p_sflag = PS_INMEM; 515 if (p1->p_sflag & PS_PROFIL) 516 startprofclock(p2); 517 mtx_unlock_spin(&sched_lock); 518 p2->p_ucred = crhold(td->td_ucred); 519 td2->td_ucred = crhold(p2->p_ucred); /* XXXKSE */ 520 521 /* 522 * Setup linkage for kernel based threading 523 */ 524 if((flags & RFTHREAD) != 0) { 525 /* 526 * XXX: This assumes a leader is a parent or grandparent of 527 * all processes in a task. 528 */ 529 if (p1->p_leader != p1) 530 PROC_LOCK(p1->p_leader); 531 p2->p_peers = p1->p_peers; 532 p1->p_peers = p2; 533 p2->p_leader = p1->p_leader; 534 if (p1->p_leader != p1) 535 PROC_UNLOCK(p1->p_leader); 536 } else { 537 p2->p_peers = NULL; 538 p2->p_leader = p2; 539 } 540 541 pargs_hold(p2->p_args); 542 543 if (flags & RFSIGSHARE) { 544 p2->p_procsig = p1->p_procsig; 545 p2->p_procsig->ps_refcnt++; 546 if (p1->p_sigacts == &p1->p_uarea->u_sigacts) { 547 /* 548 * Set p_sigacts to the new shared structure. 549 * Note that this is updating p1->p_sigacts at the 550 * same time, since p_sigacts is just a pointer to 551 * the shared p_procsig->ps_sigacts. 552 */ 553 p2->p_sigacts = newsigacts; 554 newsigacts = NULL; 555 *p2->p_sigacts = p1->p_uarea->u_sigacts; 556 } 557 } else { 558 p2->p_procsig = newprocsig; 559 newprocsig = NULL; 560 bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig)); 561 p2->p_procsig->ps_refcnt = 1; 562 p2->p_sigacts = NULL; /* finished in vm_forkproc() */ 563 } 564 if (flags & RFLINUXTHPN) 565 p2->p_sigparent = SIGUSR1; 566 else 567 p2->p_sigparent = SIGCHLD; 568 569 /* Bump references to the text vnode (for procfs) */ 570 p2->p_textvp = p1->p_textvp; 571 if (p2->p_textvp) 572 VREF(p2->p_textvp); 573 p2->p_fd = fd; 574 PROC_UNLOCK(p1); 575 PROC_UNLOCK(p2); 576 577 /* 578 * If p_limit is still copy-on-write, bump refcnt, 579 * otherwise get a copy that won't be modified. 580 * (If PL_SHAREMOD is clear, the structure is shared 581 * copy-on-write.) 582 */ 583 if (p1->p_limit->p_lflags & PL_SHAREMOD) 584 p2->p_limit = limcopy(p1->p_limit); 585 else { 586 p2->p_limit = p1->p_limit; 587 p2->p_limit->p_refcnt++; 588 } 589 590 sx_xlock(&proctree_lock); 591 PGRP_LOCK(p1->p_pgrp); 592 PROC_LOCK(p2); 593 PROC_LOCK(p1); 594 595 /* 596 * Preserve some more flags in subprocess. PS_PROFIL has already 597 * been preserved. 598 */ 599 p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK); 600 SESS_LOCK(p1->p_session); 601 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT) 602 p2->p_flag |= P_CONTROLT; 603 SESS_UNLOCK(p1->p_session); 604 if (flags & RFPPWAIT) 605 p2->p_flag |= P_PPWAIT; 606 607 LIST_INSERT_AFTER(p1, p2, p_pglist); 608 PGRP_UNLOCK(p1->p_pgrp); 609 LIST_INIT(&p2->p_children); 610 611 callout_init(&p2->p_itcallout, 0); 612 613 #ifdef KTRACE 614 /* 615 * Copy traceflag and tracefile if enabled. 616 */ 617 mtx_lock(&ktrace_mtx); 618 KASSERT(p2->p_tracep == NULL, ("new process has a ktrace vnode")); 619 if (p1->p_traceflag & KTRFAC_INHERIT) { 620 p2->p_traceflag = p1->p_traceflag; 621 if ((p2->p_tracep = p1->p_tracep) != NULL) 622 VREF(p2->p_tracep); 623 } 624 mtx_unlock(&ktrace_mtx); 625 #endif 626 627 /* 628 * If PF_FORK is set, the child process inherits the 629 * procfs ioctl flags from its parent. 630 */ 631 if (p1->p_pfsflags & PF_FORK) { 632 p2->p_stops = p1->p_stops; 633 p2->p_pfsflags = p1->p_pfsflags; 634 } 635 636 /* 637 * set priority of child to be that of parent 638 * XXXKSE hey! copying the estcpu seems dodgy.. should split it.. 639 */ 640 mtx_lock_spin(&sched_lock); 641 p2->p_ksegrp.kg_estcpu = p1->p_ksegrp.kg_estcpu; 642 mtx_unlock_spin(&sched_lock); 643 644 /* 645 * This begins the section where we must prevent the parent 646 * from being swapped. 647 */ 648 _PHOLD(p1); 649 PROC_UNLOCK(p1); 650 651 /* 652 * Attach the new process to its parent. 653 * 654 * If RFNOWAIT is set, the newly created process becomes a child 655 * of init. This effectively disassociates the child from the 656 * parent. 657 */ 658 if (flags & RFNOWAIT) 659 pptr = initproc; 660 else 661 pptr = p1; 662 p2->p_pptr = pptr; 663 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling); 664 PROC_UNLOCK(p2); 665 sx_xunlock(&proctree_lock); 666 667 KASSERT(newprocsig == NULL, ("unused newprocsig")); 668 if (newsigacts != NULL) 669 FREE(newsigacts, M_SUBPROC); 670 /* 671 * Finish creating the child process. It will return via a different 672 * execution path later. (ie: directly into user mode) 673 */ 674 vm_forkproc(td, p2, td2, flags); 675 676 if (flags == (RFFDG | RFPROC)) { 677 cnt.v_forks++; 678 cnt.v_forkpages += p2->p_vmspace->vm_dsize + 679 p2->p_vmspace->vm_ssize; 680 } else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) { 681 cnt.v_vforks++; 682 cnt.v_vforkpages += p2->p_vmspace->vm_dsize + 683 p2->p_vmspace->vm_ssize; 684 } else if (p1 == &proc0) { 685 cnt.v_kthreads++; 686 cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + 687 p2->p_vmspace->vm_ssize; 688 } else { 689 cnt.v_rforks++; 690 cnt.v_rforkpages += p2->p_vmspace->vm_dsize + 691 p2->p_vmspace->vm_ssize; 692 } 693 694 /* 695 * Both processes are set up, now check if any loadable modules want 696 * to adjust anything. 697 * What if they have an error? XXX 698 */ 699 sx_slock(&fork_list_lock); 700 TAILQ_FOREACH(ep, &fork_list, next) { 701 (*ep->function)(p1, p2, flags); 702 } 703 sx_sunlock(&fork_list_lock); 704 705 /* 706 * If RFSTOPPED not requested, make child runnable and add to 707 * run queue. 708 */ 709 microtime(&(p2->p_stats->p_start)); 710 p2->p_acflag = AFORK; 711 if ((flags & RFSTOPPED) == 0) { 712 mtx_lock_spin(&sched_lock); 713 p2->p_state = PRS_NORMAL; 714 TD_SET_CAN_RUN(td2); 715 setrunqueue(td2); 716 mtx_unlock_spin(&sched_lock); 717 } 718 719 /* 720 * Now can be swapped. 721 */ 722 PROC_LOCK(p1); 723 _PRELE(p1); 724 725 /* 726 * tell any interested parties about the new process 727 */ 728 KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid); 729 PROC_UNLOCK(p1); 730 731 /* 732 * Preserve synchronization semantics of vfork. If waiting for 733 * child to exec or exit, set P_PPWAIT on child, and sleep on our 734 * proc (in case of exit). 735 */ 736 PROC_LOCK(p2); 737 while (p2->p_flag & P_PPWAIT) 738 msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0); 739 PROC_UNLOCK(p2); 740 741 /* 742 * If other threads are waiting, let them continue now 743 */ 744 if (p1->p_flag & P_KSES) { 745 PROC_LOCK(p1); 746 thread_single_end(); 747 PROC_UNLOCK(p1); 748 } 749 750 /* 751 * Return child proc pointer to parent. 752 */ 753 *procp = p2; 754 return (0); 755 } 756 757 /* 758 * The next two functionms are general routines to handle adding/deleting 759 * items on the fork callout list. 760 * 761 * at_fork(): 762 * Take the arguments given and put them onto the fork callout list, 763 * However first make sure that it's not already there. 764 * Returns 0 on success or a standard error number. 765 */ 766 767 int 768 at_fork(function) 769 forklist_fn function; 770 { 771 struct forklist *ep; 772 773 #ifdef INVARIANTS 774 /* let the programmer know if he's been stupid */ 775 if (rm_at_fork(function)) 776 printf("WARNING: fork callout entry (%p) already present\n", 777 function); 778 #endif 779 ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT); 780 if (ep == NULL) 781 return (ENOMEM); 782 ep->function = function; 783 sx_xlock(&fork_list_lock); 784 TAILQ_INSERT_TAIL(&fork_list, ep, next); 785 sx_xunlock(&fork_list_lock); 786 return (0); 787 } 788 789 /* 790 * Scan the exit callout list for the given item and remove it.. 791 * Returns the number of items removed (0 or 1) 792 */ 793 794 int 795 rm_at_fork(function) 796 forklist_fn function; 797 { 798 struct forklist *ep; 799 800 sx_xlock(&fork_list_lock); 801 TAILQ_FOREACH(ep, &fork_list, next) { 802 if (ep->function == function) { 803 TAILQ_REMOVE(&fork_list, ep, next); 804 sx_xunlock(&fork_list_lock); 805 free(ep, M_ATFORK); 806 return(1); 807 } 808 } 809 sx_xunlock(&fork_list_lock); 810 return (0); 811 } 812 813 /* 814 * Handle the return of a child process from fork1(). This function 815 * is called from the MD fork_trampoline() entry point. 816 */ 817 void 818 fork_exit(callout, arg, frame) 819 void (*callout)(void *, struct trapframe *); 820 void *arg; 821 struct trapframe *frame; 822 { 823 struct thread *td = curthread; 824 struct proc *p = td->td_proc; 825 826 td->td_kse->ke_oncpu = PCPU_GET(cpuid); 827 p->p_state = PRS_NORMAL; 828 /* 829 * Finish setting up thread glue. We need to initialize 830 * the thread into a td_critnest=1 state. Some platforms 831 * may have already partially or fully initialized td_critnest 832 * and/or td_md.md_savecrit (when applciable). 833 * 834 * see <arch>/<arch>/critical.c 835 */ 836 sched_lock.mtx_lock = (uintptr_t)td; 837 sched_lock.mtx_recurse = 0; 838 cpu_critical_fork_exit(); 839 CTR3(KTR_PROC, "fork_exit: new thread %p (pid %d, %s)", td, p->p_pid, 840 p->p_comm); 841 if (PCPU_GET(switchtime.sec) == 0) 842 binuptime(PCPU_PTR(switchtime)); 843 PCPU_SET(switchticks, ticks); 844 mtx_unlock_spin(&sched_lock); 845 846 /* 847 * cpu_set_fork_handler intercepts this function call to 848 * have this call a non-return function to stay in kernel mode. 849 * initproc has its own fork handler, but it does return. 850 */ 851 KASSERT(callout != NULL, ("NULL callout in fork_exit")); 852 callout(arg, frame); 853 854 /* 855 * Check if a kernel thread misbehaved and returned from its main 856 * function. 857 */ 858 PROC_LOCK(p); 859 if (p->p_flag & P_KTHREAD) { 860 PROC_UNLOCK(p); 861 mtx_lock(&Giant); 862 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n", 863 p->p_comm, p->p_pid); 864 kthread_exit(0); 865 } 866 PROC_UNLOCK(p); 867 #ifdef DIAGNOSTIC 868 cred_free_thread(td); 869 #endif 870 mtx_assert(&Giant, MA_NOTOWNED); 871 } 872 873 /* 874 * Simplified back end of syscall(), used when returning from fork() 875 * directly into user mode. Giant is not held on entry, and must not 876 * be held on return. This function is passed in to fork_exit() as the 877 * first parameter and is called when returning to a new userland process. 878 */ 879 void 880 fork_return(td, frame) 881 struct thread *td; 882 struct trapframe *frame; 883 { 884 885 userret(td, frame, 0); 886 #ifdef KTRACE 887 if (KTRPOINT(td, KTR_SYSRET)) 888 ktrsysret(SYS_fork, 0, 0); 889 #endif 890 mtx_assert(&Giant, MA_NOTOWNED); 891 } 892