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