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