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