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