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