1 /* $OpenBSD: kern_fork.c,v 1.249 2023/08/14 08:33:24 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/malloc.h> 44 #include <sys/mount.h> 45 #include <sys/proc.h> 46 #include <sys/resourcevar.h> 47 #include <sys/signalvar.h> 48 #include <sys/vnode.h> 49 #include <sys/vmmeter.h> 50 #include <sys/acct.h> 51 #include <sys/ktrace.h> 52 #include <sys/sched.h> 53 #include <sys/sysctl.h> 54 #include <sys/pool.h> 55 #include <sys/mman.h> 56 #include <sys/ptrace.h> 57 #include <sys/atomic.h> 58 #include <sys/unistd.h> 59 #include <sys/tracepoint.h> 60 61 #include <sys/syscallargs.h> 62 63 #include <uvm/uvm.h> 64 #include <machine/tcb.h> 65 66 int nprocesses = 1; /* process 0 */ 67 int nthreads = 1; /* proc 0 */ 68 struct forkstat forkstat; 69 70 void fork_return(void *); 71 pid_t alloctid(void); 72 pid_t allocpid(void); 73 int ispidtaken(pid_t); 74 75 void unveil_copy(struct process *parent, struct process *child); 76 77 struct proc *thread_new(struct proc *_parent, vaddr_t _uaddr); 78 struct process *process_new(struct proc *, struct process *, int); 79 int fork_check_maxthread(uid_t _uid); 80 81 void 82 fork_return(void *arg) 83 { 84 struct proc *p = (struct proc *)arg; 85 86 if (p->p_p->ps_flags & PS_TRACED) 87 psignal(p, SIGTRAP); 88 89 child_return(p); 90 } 91 92 int 93 sys_fork(struct proc *p, void *v, register_t *retval) 94 { 95 void (*func)(void *) = child_return; 96 int flags; 97 98 flags = FORK_FORK; 99 if (p->p_p->ps_ptmask & PTRACE_FORK) { 100 flags |= FORK_PTRACE; 101 func = fork_return; 102 } 103 return fork1(p, flags, func, 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_threadcnt = 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 /* new thread and new process */ 191 KASSERT(p->p_ucred->cr_refcnt.r_refs >= 2); 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_HIGH); 201 202 timeout_set_flags(&pr->ps_realit_to, realitexpire, pr, 203 KCLOCK_UPTIME, 0); 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 | 246 PS_WXNEEDED | PS_CHROOT); 247 if (parent->ps_session->s_ttyvp != NULL) 248 pr->ps_flags |= parent->ps_flags & PS_CONTROLT; 249 250 /* 251 * Duplicate sub-structures as needed. 252 * Increase reference counts on shared objects. 253 */ 254 if (flags & FORK_SHAREFILES) 255 pr->ps_fd = fdshare(parent); 256 else 257 pr->ps_fd = fdcopy(parent); 258 pr->ps_sigacts = sigactsinit(parent); 259 if (flags & FORK_SHAREVM) 260 pr->ps_vmspace = uvmspace_share(parent); 261 else 262 pr->ps_vmspace = uvmspace_fork(parent); 263 264 if (parent->ps_flags & PS_PROFIL) 265 startprofclock(pr); 266 if (flags & FORK_PTRACE) 267 pr->ps_flags |= parent->ps_flags & PS_TRACED; 268 if (flags & FORK_NOZOMBIE) 269 pr->ps_flags |= PS_NOZOMBIE; 270 if (flags & FORK_SYSTEM) 271 pr->ps_flags |= PS_SYSTEM; 272 273 /* mark as embryo to protect against others */ 274 pr->ps_flags |= PS_EMBRYO; 275 276 /* Force visibility of all of the above changes */ 277 membar_producer(); 278 279 /* it's sufficiently inited to be globally visible */ 280 LIST_INSERT_HEAD(&allprocess, pr, ps_list); 281 282 return pr; 283 } 284 285 /* print the 'table full' message once per 10 seconds */ 286 struct timeval fork_tfmrate = { 10, 0 }; 287 288 int 289 fork_check_maxthread(uid_t uid) 290 { 291 /* 292 * Although process entries are dynamically created, we still keep 293 * a global limit on the maximum number we will create. We reserve 294 * the last 5 processes to root. The variable nprocesses is the 295 * current number of processes, maxprocess is the limit. Similar 296 * rules for threads (struct proc): we reserve the last 5 to root; 297 * the variable nthreads is the current number of procs, maxthread is 298 * the limit. 299 */ 300 if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) { 301 static struct timeval lasttfm; 302 303 if (ratecheck(&lasttfm, &fork_tfmrate)) 304 tablefull("thread"); 305 return EAGAIN; 306 } 307 nthreads++; 308 309 return 0; 310 } 311 312 static inline void 313 fork_thread_start(struct proc *p, struct proc *parent, int flags) 314 { 315 struct cpu_info *ci; 316 int s; 317 318 SCHED_LOCK(s); 319 ci = sched_choosecpu_fork(parent, flags); 320 TRACEPOINT(sched, fork, p->p_tid + THREAD_PID_OFFSET, 321 p->p_p->ps_pid, CPU_INFO_UNIT(ci)); 322 setrunqueue(ci, p, p->p_usrpri); 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)) == 0); 343 KASSERT(func != NULL); 344 345 if ((error = fork_check_maxthread(uid))) 346 return error; 347 348 if ((nprocesses >= maxprocess - 5 && uid != 0) || 349 nprocesses >= maxprocess) { 350 static struct timeval lasttfm; 351 352 if (ratecheck(&lasttfm, &fork_tfmrate)) 353 tablefull("process"); 354 nthreads--; 355 return EAGAIN; 356 } 357 nprocesses++; 358 359 /* 360 * Increment the count of processes running with this uid. 361 * Don't allow a nonprivileged user to exceed their current limit. 362 */ 363 count = chgproccnt(uid, 1); 364 if (uid != 0 && count > lim_cur(RLIMIT_NPROC)) { 365 (void)chgproccnt(uid, -1); 366 nprocesses--; 367 nthreads--; 368 return EAGAIN; 369 } 370 371 uaddr = uvm_uarea_alloc(); 372 if (uaddr == 0) { 373 (void)chgproccnt(uid, -1); 374 nprocesses--; 375 nthreads--; 376 return (ENOMEM); 377 } 378 379 /* 380 * From now on, we're committed to the fork and cannot fail. 381 */ 382 p = thread_new(curp, uaddr); 383 pr = process_new(p, curpr, flags); 384 385 p->p_fd = pr->ps_fd; 386 p->p_vmspace = pr->ps_vmspace; 387 if (pr->ps_flags & PS_SYSTEM) 388 atomic_setbits_int(&p->p_flag, P_SYSTEM); 389 390 if (flags & FORK_PPWAIT) { 391 atomic_setbits_int(&pr->ps_flags, PS_PPWAIT); 392 atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT); 393 } 394 395 #ifdef KTRACE 396 /* 397 * Copy traceflag and tracefile if enabled. 398 * If not inherited, these were zeroed above. 399 */ 400 if (curpr->ps_traceflag & KTRFAC_INHERIT) 401 ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp, 402 curpr->ps_tracecred); 403 #endif 404 405 /* 406 * Finish creating the child thread. cpu_fork() will copy 407 * and update the pcb and make the child ready to run. If 408 * this is a normal user fork, the child will exit directly 409 * to user mode via child_return() on its first time slice 410 * and will not return here. If this is a kernel thread, 411 * the specified entry point will be executed. 412 */ 413 cpu_fork(curp, p, NULL, NULL, func, arg ? arg : p); 414 415 vm = pr->ps_vmspace; 416 417 if (flags & FORK_FORK) { 418 forkstat.cntfork++; 419 forkstat.sizfork += vm->vm_dsize + vm->vm_ssize; 420 } else if (flags & FORK_VFORK) { 421 forkstat.cntvfork++; 422 forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize; 423 } else { 424 forkstat.cntkthread++; 425 } 426 427 if (pr->ps_flags & PS_TRACED && flags & FORK_FORK) 428 newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK); 429 430 p->p_tid = alloctid(); 431 432 LIST_INSERT_HEAD(&allproc, p, p_list); 433 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 434 LIST_INSERT_HEAD(PIDHASH(pr->ps_pid), pr, ps_hash); 435 LIST_INSERT_AFTER(curpr, pr, ps_pglist); 436 LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling); 437 438 if (pr->ps_flags & PS_TRACED) { 439 pr->ps_oppid = curpr->ps_pid; 440 process_reparent(pr, curpr->ps_pptr); 441 442 /* 443 * Set ptrace status. 444 */ 445 if (newptstat != NULL) { 446 pr->ps_ptstat = newptstat; 447 newptstat = NULL; 448 curpr->ps_ptstat->pe_report_event = PTRACE_FORK; 449 pr->ps_ptstat->pe_report_event = PTRACE_FORK; 450 curpr->ps_ptstat->pe_other_pid = pr->ps_pid; 451 pr->ps_ptstat->pe_other_pid = curpr->ps_pid; 452 } 453 } 454 455 /* 456 * For new processes, set accounting bits and mark as complete. 457 */ 458 nanouptime(&pr->ps_start); 459 pr->ps_acflag = AFORK; 460 atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO); 461 462 if ((flags & FORK_IDLE) == 0) 463 fork_thread_start(p, curp, flags); 464 else 465 p->p_cpu = arg; 466 467 free(newptstat, M_SUBPROC, sizeof(*newptstat)); 468 469 /* 470 * Notify any interested parties about the new process. 471 */ 472 knote_locked(&curpr->ps_klist, NOTE_FORK | pr->ps_pid); 473 474 /* 475 * Update stats now that we know the fork was successful. 476 */ 477 uvmexp.forks++; 478 if (flags & FORK_PPWAIT) 479 uvmexp.forks_ppwait++; 480 if (flags & FORK_SHAREVM) 481 uvmexp.forks_sharevm++; 482 483 /* 484 * Pass a pointer to the new process to the caller. 485 */ 486 if (rnewprocp != NULL) 487 *rnewprocp = p; 488 489 /* 490 * Preserve synchronization semantics of vfork. If waiting for 491 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT 492 * on ourselves, and sleep on our process for the latter flag 493 * to go away. 494 * XXX Need to stop other rthreads in the parent 495 */ 496 if (flags & FORK_PPWAIT) 497 while (curpr->ps_flags & PS_ISPWAIT) 498 tsleep_nsec(curpr, PWAIT, "ppwait", INFSLP); 499 500 /* 501 * If we're tracing the child, alert the parent too. 502 */ 503 if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED)) 504 psignal(curp, SIGTRAP); 505 506 /* 507 * Return child pid to parent process 508 */ 509 if (retval != NULL) 510 *retval = pr->ps_pid; 511 return (0); 512 } 513 514 int 515 thread_fork(struct proc *curp, void *stack, void *tcb, pid_t *tidptr, 516 register_t *retval) 517 { 518 struct process *pr = curp->p_p; 519 struct proc *p; 520 pid_t tid; 521 vaddr_t uaddr; 522 int s, error; 523 524 if (stack == NULL) 525 return EINVAL; 526 527 if ((error = fork_check_maxthread(curp->p_ucred->cr_ruid))) 528 return error; 529 530 uaddr = uvm_uarea_alloc(); 531 if (uaddr == 0) { 532 nthreads--; 533 return ENOMEM; 534 } 535 536 /* 537 * From now on, we're committed to the fork and cannot fail. 538 */ 539 p = thread_new(curp, uaddr); 540 atomic_setbits_int(&p->p_flag, P_THREAD); 541 sigstkinit(&p->p_sigstk); 542 memset(p->p_name, 0, sizeof p->p_name); 543 544 /* other links */ 545 p->p_p = pr; 546 pr->ps_threadcnt++; 547 548 /* local copies */ 549 p->p_fd = pr->ps_fd; 550 p->p_vmspace = pr->ps_vmspace; 551 552 /* 553 * Finish creating the child thread. cpu_fork() will copy 554 * and update the pcb and make the child ready to run. The 555 * child will exit directly to user mode via child_return() 556 * on its first time slice and will not return here. 557 */ 558 cpu_fork(curp, p, stack, tcb, child_return, p); 559 560 p->p_tid = alloctid(); 561 562 LIST_INSERT_HEAD(&allproc, p, p_list); 563 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 564 565 SCHED_LOCK(s); 566 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 567 568 /* 569 * if somebody else wants to take us to single threaded mode, 570 * count ourselves in. 571 */ 572 if (pr->ps_single) { 573 atomic_inc_int(&pr->ps_singlecount); 574 atomic_setbits_int(&p->p_flag, P_SUSPSINGLE); 575 } 576 SCHED_UNLOCK(s); 577 578 /* 579 * Return tid to parent thread and copy it out to userspace 580 */ 581 *retval = tid = p->p_tid + THREAD_PID_OFFSET; 582 if (tidptr != NULL) { 583 if (copyout(&tid, tidptr, sizeof(tid))) 584 psignal(curp, SIGSEGV); 585 } 586 587 fork_thread_start(p, curp, 0); 588 589 /* 590 * Update stats now that we know the fork was successful. 591 */ 592 forkstat.cnttfork++; 593 uvmexp.forks++; 594 uvmexp.forks_sharevm++; 595 596 return 0; 597 } 598 599 600 /* Find an unused tid */ 601 pid_t 602 alloctid(void) 603 { 604 pid_t tid; 605 606 do { 607 /* (0 .. TID_MASK+1] */ 608 tid = 1 + (arc4random() & TID_MASK); 609 } while (tfind(tid) != NULL); 610 611 return (tid); 612 } 613 614 /* 615 * Checks for current use of a pid, either as a pid or pgid. 616 */ 617 pid_t oldpids[128]; 618 int 619 ispidtaken(pid_t pid) 620 { 621 uint32_t i; 622 623 for (i = 0; i < nitems(oldpids); i++) 624 if (pid == oldpids[i]) 625 return (1); 626 627 if (prfind(pid) != NULL) 628 return (1); 629 if (pgfind(pid) != NULL) 630 return (1); 631 if (zombiefind(pid) != NULL) 632 return (1); 633 return (0); 634 } 635 636 /* Find an unused pid */ 637 pid_t 638 allocpid(void) 639 { 640 static int first = 1; 641 pid_t pid; 642 643 /* The first PID allocated is always 1. */ 644 if (first) { 645 first = 0; 646 return 1; 647 } 648 649 /* 650 * All subsequent PIDs are chosen randomly. We need to 651 * find an unused PID in the range [2, PID_MAX]. 652 */ 653 do { 654 pid = 2 + arc4random_uniform(PID_MAX - 1); 655 } while (ispidtaken(pid)); 656 return pid; 657 } 658 659 void 660 freepid(pid_t pid) 661 { 662 static uint32_t idx; 663 664 oldpids[idx++ % nitems(oldpids)] = pid; 665 } 666 667 #if defined(MULTIPROCESSOR) 668 /* 669 * XXX This is a slight hack to get newly-formed processes to 670 * XXX acquire the kernel lock as soon as they run. 671 */ 672 void 673 proc_trampoline_mp(void) 674 { 675 SCHED_ASSERT_LOCKED(); 676 __mp_unlock(&sched_lock); 677 spl0(); 678 SCHED_ASSERT_UNLOCKED(); 679 KERNEL_ASSERT_UNLOCKED(); 680 681 KERNEL_LOCK(); 682 } 683 #endif 684