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