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