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