1 /* $OpenBSD: kern_fork.c,v 1.205 2018/07/20 07:28:36 beck Exp $ */ 2 /* $NetBSD: kern_fork.c,v 1.29 1996/02/09 18:59:34 christos Exp $ */ 3 4 /* 5 * Copyright (c) 1982, 1986, 1989, 1991, 1993 6 * The Regents of the University of California. All rights reserved. 7 * (c) UNIX System Laboratories, Inc. 8 * All or some portions of this file are derived from material licensed 9 * to the University of California by American Telephone and Telegraph 10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 11 * the permission of UNIX System Laboratories, Inc. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. Neither the name of the University nor the names of its contributors 22 * may be used to endorse or promote products derived from this software 23 * without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 * 37 * @(#)kern_fork.c 8.6 (Berkeley) 4/8/94 38 */ 39 40 #include <sys/param.h> 41 #include <sys/systm.h> 42 #include <sys/filedesc.h> 43 #include <sys/kernel.h> 44 #include <sys/malloc.h> 45 #include <sys/mount.h> 46 #include <sys/proc.h> 47 #include <sys/exec.h> 48 #include <sys/resourcevar.h> 49 #include <sys/signalvar.h> 50 #include <sys/vnode.h> 51 #include <sys/vmmeter.h> 52 #include <sys/acct.h> 53 #include <sys/ktrace.h> 54 #include <sys/sched.h> 55 #include <sys/sysctl.h> 56 #include <sys/pool.h> 57 #include <sys/mman.h> 58 #include <sys/ptrace.h> 59 #include <sys/atomic.h> 60 #include <sys/pledge.h> 61 #include <sys/unistd.h> 62 63 #include <sys/syscallargs.h> 64 65 #include <uvm/uvm.h> 66 #include <machine/tcb.h> 67 68 int nprocesses = 1; /* process 0 */ 69 int nthreads = 1; /* proc 0 */ 70 int randompid; /* when set to 1, pid's go random */ 71 struct forkstat forkstat; 72 73 void fork_return(void *); 74 pid_t alloctid(void); 75 pid_t allocpid(void); 76 int ispidtaken(pid_t); 77 78 void unveil_copy(struct process *parent, struct process *child); 79 80 struct proc *thread_new(struct proc *_parent, vaddr_t _uaddr); 81 struct process *process_new(struct proc *, struct process *, int); 82 int fork_check_maxthread(uid_t _uid); 83 84 void 85 fork_return(void *arg) 86 { 87 struct proc *p = (struct proc *)arg; 88 89 if (p->p_p->ps_flags & PS_TRACED) 90 psignal(p, SIGTRAP); 91 92 child_return(p); 93 } 94 95 int 96 sys_fork(struct proc *p, void *v, register_t *retval) 97 { 98 int flags; 99 100 flags = FORK_FORK; 101 if (p->p_p->ps_ptmask & PTRACE_FORK) 102 flags |= FORK_PTRACE; 103 return fork1(p, flags, fork_return, NULL, retval, NULL); 104 } 105 106 int 107 sys_vfork(struct proc *p, void *v, register_t *retval) 108 { 109 return fork1(p, FORK_VFORK|FORK_PPWAIT, child_return, NULL, 110 retval, NULL); 111 } 112 113 int 114 sys___tfork(struct proc *p, void *v, register_t *retval) 115 { 116 struct sys___tfork_args /* { 117 syscallarg(const struct __tfork) *param; 118 syscallarg(size_t) psize; 119 } */ *uap = v; 120 size_t psize = SCARG(uap, psize); 121 struct __tfork param = { 0 }; 122 int error; 123 124 if (psize == 0 || psize > sizeof(param)) 125 return EINVAL; 126 if ((error = copyin(SCARG(uap, param), ¶m, psize))) 127 return error; 128 #ifdef KTRACE 129 if (KTRPOINT(p, KTR_STRUCT)) 130 ktrstruct(p, "tfork", ¶m, sizeof(param)); 131 #endif 132 #ifdef TCB_INVALID 133 if (TCB_INVALID(param.tf_tcb)) 134 return EINVAL; 135 #endif /* TCB_INVALID */ 136 137 return thread_fork(p, param.tf_stack, param.tf_tcb, param.tf_tid, 138 retval); 139 } 140 141 /* 142 * Allocate and initialize a thread (proc) structure, given the parent thread. 143 */ 144 struct proc * 145 thread_new(struct proc *parent, vaddr_t uaddr) 146 { 147 struct proc *p; 148 149 p = pool_get(&proc_pool, PR_WAITOK); 150 p->p_stat = SIDL; /* protect against others */ 151 p->p_flag = 0; 152 153 /* 154 * Make a proc table entry for the new process. 155 * Start by zeroing the section of proc that is zero-initialized, 156 * then copy the section that is copied directly from the parent. 157 */ 158 memset(&p->p_startzero, 0, 159 (caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero); 160 memcpy(&p->p_startcopy, &parent->p_startcopy, 161 (caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy); 162 crhold(p->p_ucred); 163 p->p_addr = (struct user *)uaddr; 164 165 /* 166 * Initialize the timeouts. 167 */ 168 timeout_set(&p->p_sleep_to, endtsleep, p); 169 170 /* 171 * set priority of child to be that of parent 172 * XXX should move p_estcpu into the region of struct proc which gets 173 * copied. 174 */ 175 scheduler_fork_hook(parent, p); 176 177 #ifdef WITNESS 178 p->p_sleeplocks = NULL; 179 #endif 180 181 return p; 182 } 183 184 /* 185 * Initialize common bits of a process structure, given the initial thread. 186 */ 187 void 188 process_initialize(struct process *pr, struct proc *p) 189 { 190 /* initialize the thread links */ 191 pr->ps_mainproc = p; 192 TAILQ_INIT(&pr->ps_threads); 193 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 194 pr->ps_refcnt = 1; 195 p->p_p = pr; 196 197 /* give the process the same creds as the initial thread */ 198 pr->ps_ucred = p->p_ucred; 199 crhold(pr->ps_ucred); 200 KASSERT(p->p_ucred->cr_ref >= 2); /* new thread and new process */ 201 202 LIST_INIT(&pr->ps_children); 203 LIST_INIT(&pr->ps_kqlist); 204 205 timeout_set(&pr->ps_realit_to, realitexpire, pr); 206 } 207 208 209 /* 210 * Allocate and initialize a new process. 211 */ 212 struct process * 213 process_new(struct proc *p, struct process *parent, int flags) 214 { 215 struct process *pr; 216 217 pr = pool_get(&process_pool, PR_WAITOK); 218 219 /* 220 * Make a process structure for the new process. 221 * Start by zeroing the section of proc that is zero-initialized, 222 * then copy the section that is copied directly from the parent. 223 */ 224 memset(&pr->ps_startzero, 0, 225 (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero); 226 memcpy(&pr->ps_startcopy, &parent->ps_startcopy, 227 (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy); 228 229 process_initialize(pr, p); 230 pr->ps_pid = allocpid(); 231 232 /* post-copy fixups */ 233 pr->ps_pptr = parent; 234 pr->ps_limit->p_refcnt++; 235 236 /* bump references to the text vnode (for sysctl) */ 237 pr->ps_textvp = parent->ps_textvp; 238 if (pr->ps_textvp) 239 vref(pr->ps_textvp); 240 241 /* copy unveil if unveil is active */ 242 unveil_copy(parent, pr); 243 244 pr->ps_flags = parent->ps_flags & 245 (PS_SUGID | PS_SUGIDEXEC | PS_PLEDGE | PS_EXECPLEDGE | PS_WXNEEDED); 246 if (parent->ps_session->s_ttyvp != NULL) 247 pr->ps_flags |= parent->ps_flags & PS_CONTROLT; 248 249 /* 250 * Duplicate sub-structures as needed. 251 * Increase reference counts on shared objects. 252 */ 253 if (flags & FORK_SHAREFILES) 254 pr->ps_fd = fdshare(parent); 255 else 256 pr->ps_fd = fdcopy(parent); 257 if (flags & FORK_SIGHAND) 258 pr->ps_sigacts = sigactsshare(parent); 259 else 260 pr->ps_sigacts = sigactsinit(parent); 261 if (flags & FORK_SHAREVM) 262 pr->ps_vmspace = uvmspace_share(parent); 263 else 264 pr->ps_vmspace = uvmspace_fork(parent); 265 266 if (parent->ps_flags & PS_PROFIL) 267 startprofclock(pr); 268 if (flags & FORK_PTRACE) 269 pr->ps_flags |= parent->ps_flags & PS_TRACED; 270 if (flags & FORK_NOZOMBIE) 271 pr->ps_flags |= PS_NOZOMBIE; 272 if (flags & FORK_SYSTEM) 273 pr->ps_flags |= PS_SYSTEM; 274 275 /* mark as embryo to protect against others */ 276 pr->ps_flags |= PS_EMBRYO; 277 278 /* Force visibility of all of the above changes */ 279 membar_producer(); 280 281 /* it's sufficiently inited to be globally visible */ 282 LIST_INSERT_HEAD(&allprocess, pr, ps_list); 283 284 return pr; 285 } 286 287 /* print the 'table full' message once per 10 seconds */ 288 struct timeval fork_tfmrate = { 10, 0 }; 289 290 int 291 fork_check_maxthread(uid_t uid) 292 { 293 /* 294 * Although process entries are dynamically created, we still keep 295 * a global limit on the maximum number we will create. We reserve 296 * the last 5 processes to root. The variable nprocesses is the 297 * current number of processes, maxprocess is the limit. Similar 298 * rules for threads (struct proc): we reserve the last 5 to root; 299 * the variable nthreads is the current number of procs, maxthread is 300 * the limit. 301 */ 302 if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) { 303 static struct timeval lasttfm; 304 305 if (ratecheck(&lasttfm, &fork_tfmrate)) 306 tablefull("proc"); 307 return EAGAIN; 308 } 309 nthreads++; 310 311 return 0; 312 } 313 314 static inline void 315 fork_thread_start(struct proc *p, struct proc *parent, int flags) 316 { 317 int s; 318 319 SCHED_LOCK(s); 320 p->p_stat = SRUN; 321 p->p_cpu = sched_choosecpu_fork(parent, flags); 322 setrunqueue(p); 323 SCHED_UNLOCK(s); 324 } 325 326 int 327 fork1(struct proc *curp, int flags, void (*func)(void *), void *arg, 328 register_t *retval, struct proc **rnewprocp) 329 { 330 struct process *curpr = curp->p_p; 331 struct process *pr; 332 struct proc *p; 333 uid_t uid = curp->p_ucred->cr_ruid; 334 struct vmspace *vm; 335 int count; 336 vaddr_t uaddr; 337 int error; 338 struct ptrace_state *newptstat = NULL; 339 340 KASSERT((flags & ~(FORK_FORK | FORK_VFORK | FORK_PPWAIT | FORK_PTRACE 341 | FORK_IDLE | FORK_SHAREVM | FORK_SHAREFILES | FORK_NOZOMBIE 342 | FORK_SYSTEM | FORK_SIGHAND)) == 0); 343 KASSERT((flags & FORK_SIGHAND) == 0 || (flags & FORK_SHAREVM)); 344 KASSERT(func != NULL); 345 346 if ((error = fork_check_maxthread(uid))) 347 return error; 348 349 if ((nprocesses >= maxprocess - 5 && uid != 0) || 350 nprocesses >= maxprocess) { 351 static struct timeval lasttfm; 352 353 if (ratecheck(&lasttfm, &fork_tfmrate)) 354 tablefull("process"); 355 nthreads--; 356 return EAGAIN; 357 } 358 nprocesses++; 359 360 /* 361 * Increment the count of processes running with this uid. 362 * Don't allow a nonprivileged user to exceed their current limit. 363 */ 364 count = chgproccnt(uid, 1); 365 if (uid != 0 && count > curp->p_rlimit[RLIMIT_NPROC].rlim_cur) { 366 (void)chgproccnt(uid, -1); 367 nprocesses--; 368 nthreads--; 369 return EAGAIN; 370 } 371 372 uaddr = uvm_uarea_alloc(); 373 if (uaddr == 0) { 374 (void)chgproccnt(uid, -1); 375 nprocesses--; 376 nthreads--; 377 return (ENOMEM); 378 } 379 380 /* 381 * From now on, we're committed to the fork and cannot fail. 382 */ 383 p = thread_new(curp, uaddr); 384 pr = process_new(p, curpr, flags); 385 386 p->p_fd = pr->ps_fd; 387 p->p_vmspace = pr->ps_vmspace; 388 if (pr->ps_flags & PS_SYSTEM) 389 atomic_setbits_int(&p->p_flag, P_SYSTEM); 390 391 if (flags & FORK_PPWAIT) { 392 atomic_setbits_int(&pr->ps_flags, PS_PPWAIT); 393 atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT); 394 } 395 396 #ifdef KTRACE 397 /* 398 * Copy traceflag and tracefile if enabled. 399 * If not inherited, these were zeroed above. 400 */ 401 if (curpr->ps_traceflag & KTRFAC_INHERIT) 402 ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp, 403 curpr->ps_tracecred); 404 #endif 405 406 /* 407 * Finish creating the child thread. cpu_fork() will copy 408 * and update the pcb and make the child ready to run. If 409 * this is a normal user fork, the child will exit directly 410 * to user mode via child_return() on its first time slice 411 * and will not return here. If this is a kernel thread, 412 * the specified entry point will be executed. 413 */ 414 cpu_fork(curp, p, NULL, NULL, func, arg ? arg : p); 415 416 vm = pr->ps_vmspace; 417 418 if (flags & FORK_FORK) { 419 forkstat.cntfork++; 420 forkstat.sizfork += vm->vm_dsize + vm->vm_ssize; 421 } else if (flags & FORK_VFORK) { 422 forkstat.cntvfork++; 423 forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize; 424 } else { 425 forkstat.cntkthread++; 426 } 427 428 if (pr->ps_flags & PS_TRACED && flags & FORK_FORK) 429 newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK); 430 431 p->p_tid = alloctid(); 432 433 LIST_INSERT_HEAD(&allproc, p, p_list); 434 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 435 LIST_INSERT_HEAD(PIDHASH(pr->ps_pid), pr, ps_hash); 436 LIST_INSERT_AFTER(curpr, pr, ps_pglist); 437 LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling); 438 439 if (pr->ps_flags & PS_TRACED) { 440 pr->ps_oppid = curpr->ps_pid; 441 if (pr->ps_pptr != curpr->ps_pptr) 442 proc_reparent(pr, curpr->ps_pptr); 443 444 /* 445 * Set ptrace status. 446 */ 447 if (newptstat != NULL) { 448 pr->ps_ptstat = newptstat; 449 newptstat = NULL; 450 curpr->ps_ptstat->pe_report_event = PTRACE_FORK; 451 pr->ps_ptstat->pe_report_event = PTRACE_FORK; 452 curpr->ps_ptstat->pe_other_pid = pr->ps_pid; 453 pr->ps_ptstat->pe_other_pid = curpr->ps_pid; 454 } 455 } 456 457 /* 458 * For new processes, set accounting bits and mark as complete. 459 */ 460 getnanotime(&pr->ps_start); 461 pr->ps_acflag = AFORK; 462 atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO); 463 464 if ((flags & FORK_IDLE) == 0) 465 fork_thread_start(p, curp, flags); 466 else 467 p->p_cpu = arg; 468 469 free(newptstat, M_SUBPROC, sizeof(*newptstat)); 470 471 /* 472 * Notify any interested parties about the new process. 473 */ 474 KNOTE(&curpr->ps_klist, NOTE_FORK | pr->ps_pid); 475 476 /* 477 * Update stats now that we know the fork was successful. 478 */ 479 uvmexp.forks++; 480 if (flags & FORK_PPWAIT) 481 uvmexp.forks_ppwait++; 482 if (flags & FORK_SHAREVM) 483 uvmexp.forks_sharevm++; 484 485 /* 486 * Pass a pointer to the new process to the caller. 487 */ 488 if (rnewprocp != NULL) 489 *rnewprocp = p; 490 491 /* 492 * Preserve synchronization semantics of vfork. If waiting for 493 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT 494 * on ourselves, and sleep on our process for the latter flag 495 * to go away. 496 * XXX Need to stop other rthreads in the parent 497 */ 498 if (flags & FORK_PPWAIT) 499 while (curpr->ps_flags & PS_ISPWAIT) 500 tsleep(curpr, PWAIT, "ppwait", 0); 501 502 /* 503 * If we're tracing the child, alert the parent too. 504 */ 505 if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED)) 506 psignal(curp, SIGTRAP); 507 508 /* 509 * Return child pid to parent process 510 */ 511 if (retval != NULL) { 512 retval[0] = pr->ps_pid; 513 retval[1] = 0; 514 } 515 return (0); 516 } 517 518 int 519 thread_fork(struct proc *curp, void *stack, void *tcb, pid_t *tidptr, 520 register_t *retval) 521 { 522 struct process *pr = curp->p_p; 523 struct proc *p; 524 pid_t tid; 525 vaddr_t uaddr; 526 int error; 527 528 if (stack == NULL) 529 return EINVAL; 530 531 if ((error = fork_check_maxthread(curp->p_ucred->cr_ruid))) 532 return error; 533 534 uaddr = uvm_uarea_alloc(); 535 if (uaddr == 0) { 536 nthreads--; 537 return ENOMEM; 538 } 539 540 /* 541 * From now on, we're committed to the fork and cannot fail. 542 */ 543 p = thread_new(curp, uaddr); 544 atomic_setbits_int(&p->p_flag, P_THREAD); 545 sigstkinit(&p->p_sigstk); 546 547 /* other links */ 548 p->p_p = pr; 549 pr->ps_refcnt++; 550 551 /* local copies */ 552 p->p_fd = pr->ps_fd; 553 p->p_vmspace = pr->ps_vmspace; 554 555 /* 556 * Finish creating the child thread. cpu_fork() will copy 557 * and update the pcb and make the child ready to run. The 558 * child will exit directly to user mode via child_return() 559 * on its first time slice and will not return here. 560 */ 561 cpu_fork(curp, p, stack, tcb, child_return, p); 562 563 p->p_tid = alloctid(); 564 565 LIST_INSERT_HEAD(&allproc, p, p_list); 566 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 567 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 568 569 /* 570 * if somebody else wants to take us to single threaded mode, 571 * count ourselves in. 572 */ 573 if (pr->ps_single) { 574 pr->ps_singlecount++; 575 atomic_setbits_int(&p->p_flag, P_SUSPSINGLE); 576 } 577 578 /* 579 * Return tid to parent thread and copy it out to userspace 580 */ 581 retval[0] = tid = p->p_tid + THREAD_PID_OFFSET; 582 retval[1] = 0; 583 if (tidptr != NULL) { 584 if (copyout(&tid, tidptr, sizeof(tid))) 585 psignal(curp, SIGSEGV); 586 } 587 588 fork_thread_start(p, curp, 0); 589 590 /* 591 * Update stats now that we know the fork was successful. 592 */ 593 forkstat.cnttfork++; 594 uvmexp.forks++; 595 uvmexp.forks_sharevm++; 596 597 return 0; 598 } 599 600 601 /* Find an unused tid */ 602 pid_t 603 alloctid(void) 604 { 605 pid_t tid; 606 607 do { 608 /* (0 .. TID_MASK+1] */ 609 tid = 1 + (arc4random() & TID_MASK); 610 } while (tfind(tid) != NULL); 611 612 return (tid); 613 } 614 615 /* 616 * Checks for current use of a pid, either as a pid or pgid. 617 */ 618 pid_t oldpids[128]; 619 int 620 ispidtaken(pid_t pid) 621 { 622 uint32_t i; 623 624 for (i = 0; i < nitems(oldpids); i++) 625 if (pid == oldpids[i]) 626 return (1); 627 628 if (prfind(pid) != NULL) 629 return (1); 630 if (pgfind(pid) != NULL) 631 return (1); 632 if (zombiefind(pid) != NULL) 633 return (1); 634 return (0); 635 } 636 637 /* Find an unused pid */ 638 pid_t 639 allocpid(void) 640 { 641 static pid_t lastpid; 642 pid_t pid; 643 644 if (!randompid) { 645 /* only used early on for system processes */ 646 pid = ++lastpid; 647 } else { 648 /* Find an unused pid satisfying lastpid < pid <= PID_MAX */ 649 do { 650 pid = arc4random_uniform(PID_MAX - lastpid) + 1 + 651 lastpid; 652 } while (ispidtaken(pid)); 653 } 654 655 return pid; 656 } 657 658 void 659 freepid(pid_t pid) 660 { 661 static uint32_t idx; 662 663 oldpids[idx++ % nitems(oldpids)] = pid; 664 } 665 666 #if defined(MULTIPROCESSOR) 667 /* 668 * XXX This is a slight hack to get newly-formed processes to 669 * XXX acquire the kernel lock as soon as they run. 670 */ 671 void 672 proc_trampoline_mp(void) 673 { 674 SCHED_ASSERT_LOCKED(); 675 __mp_unlock(&sched_lock); 676 spl0(); 677 SCHED_ASSERT_UNLOCKED(); 678 KERNEL_ASSERT_UNLOCKED(); 679 680 KERNEL_LOCK(); 681 } 682 #endif 683