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