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