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