1 /* $OpenBSD: kern_fork.c,v 1.136 2012/04/10 15:50:52 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_extern.h> 66 #include <uvm/uvm_map.h> 67 68 #ifdef __HAVE_MD_TCB 69 # include <machine/tcb.h> 70 #endif 71 72 int nprocesses = 1; /* process 0 */ 73 int nthreads = 1; /* proc 0 */ 74 int randompid; /* when set to 1, pid's go random */ 75 pid_t lastpid; 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 *); 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, SIGCHLD, flags, NULL, 0, 105 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, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL, 113 NULL, retval, NULL)); 114 } 115 116 int 117 sys_rfork(struct proc *p, void *v, register_t *retval) 118 { 119 struct sys_rfork_args /* { 120 syscallarg(int) flags; 121 } */ *uap = v; 122 123 int rforkflags; 124 int flags; 125 126 flags = FORK_RFORK; 127 rforkflags = SCARG(uap, flags); 128 129 if ((rforkflags & RFPROC) == 0) 130 return (EINVAL); 131 132 switch(rforkflags & (RFFDG|RFCFDG)) { 133 case (RFFDG|RFCFDG): 134 return EINVAL; 135 case RFCFDG: 136 flags |= FORK_CLEANFILES; 137 break; 138 case RFFDG: 139 break; 140 default: 141 flags |= FORK_SHAREFILES; 142 break; 143 } 144 145 if (rforkflags & RFNOWAIT) 146 flags |= FORK_NOZOMBIE; 147 148 if (rforkflags & RFMEM) 149 flags |= FORK_SHAREVM; 150 151 if (rforkflags & RFTHREAD) 152 flags |= FORK_THREAD | FORK_SIGHAND | FORK_NOZOMBIE; 153 154 return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval, NULL)); 155 } 156 157 int 158 sys___tfork(struct proc *p, void *v, register_t *retval) 159 { 160 struct sys___tfork_args /* { 161 syscallarg(struct __tfork) *param; 162 } */ *uap = v; 163 struct __tfork param; 164 int flags; 165 int error; 166 167 if ((error = copyin(SCARG(uap, param), ¶m, sizeof(param)))) 168 return (error); 169 170 /* XXX will supersede rfork at some point... */ 171 if (param.tf_flags != 0) 172 return (EINVAL); 173 174 flags = FORK_TFORK | FORK_THREAD | FORK_SIGHAND | FORK_SHAREVM 175 | FORK_NOZOMBIE | FORK_SHAREFILES; 176 177 return (fork1(p, 0, flags, NULL, param.tf_tid, tfork_child_return, 178 param.tf_tcb, retval, NULL)); 179 } 180 181 void 182 tfork_child_return(void *arg) 183 { 184 struct proc *p = curproc; 185 186 TCB_SET(p, arg); 187 child_return(p); 188 } 189 190 /* 191 * Allocate and initialize a new process. 192 */ 193 void 194 process_new(struct proc *p, struct process *parent) 195 { 196 struct process *pr; 197 198 pr = pool_get(&process_pool, PR_WAITOK); 199 pr->ps_mainproc = p; 200 201 TAILQ_INIT(&pr->ps_threads); 202 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 203 pr->ps_pptr = parent; 204 LIST_INIT(&pr->ps_children); 205 pr->ps_refcnt = 1; 206 207 /* 208 * Make a process structure for the new process. 209 * Start by zeroing the section of proc that is zero-initialized, 210 * then copy the section that is copied directly from the parent. 211 */ 212 bzero(&pr->ps_startzero, 213 (unsigned) ((caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero)); 214 bcopy(&parent->ps_startcopy, &pr->ps_startcopy, 215 (unsigned) ((caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy)); 216 217 /* post-copy fixups */ 218 pr->ps_cred = pool_get(&pcred_pool, PR_WAITOK); 219 bcopy(parent->ps_cred, pr->ps_cred, sizeof(*pr->ps_cred)); 220 crhold(parent->ps_cred->pc_ucred); 221 pr->ps_limit->p_refcnt++; 222 223 timeout_set(&pr->ps_realit_to, realitexpire, pr); 224 timeout_set(&pr->ps_virt_to, virttimer_trampoline, pr); 225 timeout_set(&pr->ps_prof_to, proftimer_trampoline, pr); 226 227 pr->ps_flags = parent->ps_flags & (PS_SUGID | PS_SUGIDEXEC); 228 if (parent->ps_session->s_ttyvp != NULL && 229 parent->ps_flags & PS_CONTROLT) 230 atomic_setbits_int(&pr->ps_flags, PS_CONTROLT); 231 232 p->p_p = pr; 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 exitsig, 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 (!rthreads_enabled) 259 return (ENOTSUP); 260 if ((flags & (FORK_SIGHAND | FORK_NOZOMBIE)) != 261 (FORK_SIGHAND | FORK_NOZOMBIE)) 262 return (EINVAL); 263 } 264 if (flags & FORK_SIGHAND && (flags & FORK_SHAREVM) == 0) 265 return (EINVAL); 266 267 /* 268 * Although process entries are dynamically created, we still keep 269 * a global limit on the maximum number we will create. We reserve 270 * the last 5 processes to root. The variable nprocesses is the 271 * current number of processes, maxprocess is the limit. Similar 272 * rules for threads (struct proc): we reserve the last 5 to root; 273 * the variable nthreads is the current number of procs, maxthread is 274 * the limit. 275 */ 276 uid = curp->p_cred->p_ruid; 277 if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) { 278 static struct timeval lasttfm; 279 280 if (ratecheck(&lasttfm, &fork_tfmrate)) 281 tablefull("proc"); 282 return (EAGAIN); 283 } 284 nthreads++; 285 286 if ((flags & FORK_THREAD) == 0) { 287 if ((nprocesses >= maxprocess - 5 && uid != 0) || 288 nprocesses >= maxprocess) { 289 static struct timeval lasttfm; 290 291 if (ratecheck(&lasttfm, &fork_tfmrate)) 292 tablefull("process"); 293 nthreads--; 294 return (EAGAIN); 295 } 296 nprocesses++; 297 298 /* 299 * Increment the count of processes running with 300 * this uid. Don't allow a nonprivileged user to 301 * exceed their current limit. 302 */ 303 count = chgproccnt(uid, 1); 304 if (uid != 0 && count > curp->p_rlimit[RLIMIT_NPROC].rlim_cur) { 305 (void)chgproccnt(uid, -1); 306 nprocesses--; 307 nthreads--; 308 return (EAGAIN); 309 } 310 } 311 312 uaddr = uvm_km_kmemalloc_pla(kernel_map, uvm.kernel_object, USPACE, 313 USPACE_ALIGN, UVM_KMF_ZERO, 314 no_constraint.ucr_low, no_constraint.ucr_high, 315 0, 0, USPACE/PAGE_SIZE); 316 if (uaddr == 0) { 317 chgproccnt(uid, -1); 318 nprocesses--; 319 nthreads--; 320 return (ENOMEM); 321 } 322 323 /* 324 * From now on, we're committed to the fork and cannot fail. 325 */ 326 327 /* Allocate new proc. */ 328 p = pool_get(&proc_pool, PR_WAITOK); 329 330 p->p_stat = SIDL; /* protect against others */ 331 p->p_exitsig = exitsig; 332 p->p_flag = 0; 333 334 if (flags & FORK_THREAD) { 335 atomic_setbits_int(&p->p_flag, P_THREAD); 336 p->p_p = pr = curpr; 337 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 338 pr->ps_refcnt++; 339 } else { 340 process_new(p, curpr); 341 pr = p->p_p; 342 } 343 344 /* 345 * Make a proc table entry for the new process. 346 * Start by zeroing the section of proc that is zero-initialized, 347 * then copy the section that is copied directly from the parent. 348 */ 349 bzero(&p->p_startzero, 350 (unsigned) ((caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero)); 351 bcopy(&curp->p_startcopy, &p->p_startcopy, 352 (unsigned) ((caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy)); 353 354 /* 355 * Initialize the timeouts. 356 */ 357 timeout_set(&p->p_sleep_to, endtsleep, p); 358 359 /* 360 * Duplicate sub-structures as needed. 361 * Increase reference counts on shared objects. 362 */ 363 if (curp->p_flag & P_PROFIL) 364 startprofclock(p); 365 if (flags & FORK_PTRACE) 366 atomic_setbits_int(&pr->ps_flags, curpr->ps_flags & PS_TRACED); 367 368 /* bump references to the text vnode (for procfs) */ 369 p->p_textvp = curp->p_textvp; 370 if (p->p_textvp) 371 vref(p->p_textvp); 372 373 if (flags & FORK_CLEANFILES) 374 p->p_fd = fdinit(curp); 375 else if (flags & FORK_SHAREFILES) 376 p->p_fd = fdshare(curp); 377 else 378 p->p_fd = fdcopy(curp); 379 380 if (flags & FORK_PPWAIT) { 381 atomic_setbits_int(&pr->ps_flags, PS_PPWAIT); 382 atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT); 383 } 384 if (flags & FORK_NOZOMBIE) 385 atomic_setbits_int(&p->p_flag, P_NOZOMBIE); 386 387 #ifdef KTRACE 388 /* 389 * Copy traceflag and tracefile if enabled. 390 * If not inherited, these were zeroed above. 391 */ 392 if ((flags & FORK_THREAD) == 0 && curpr->ps_traceflag & KTRFAC_INHERIT) 393 ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp, 394 curpr->ps_tracecred); 395 #endif 396 397 /* 398 * set priority of child to be that of parent 399 * XXX should move p_estcpu into the region of struct proc which gets 400 * copied. 401 */ 402 scheduler_fork_hook(curp, p); 403 404 /* 405 * Create signal actions for the child process. 406 */ 407 if (flags & FORK_SIGHAND) 408 p->p_sigacts = sigactsshare(curp); 409 else 410 p->p_sigacts = sigactsinit(curp); 411 if (flags & FORK_THREAD) 412 sigstkinit(&p->p_sigstk); 413 414 /* 415 * If emulation has process fork hook, call it now. 416 */ 417 if (p->p_emul->e_proc_fork) 418 (*p->p_emul->e_proc_fork)(p, curp); 419 420 p->p_addr = (struct user *)uaddr; 421 422 /* 423 * Finish creating the child process. It will return through a 424 * different path later. 425 */ 426 uvm_fork(curp, p, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack, 427 0, func ? func : child_return, arg ? arg : p); 428 429 vm = p->p_vmspace; 430 431 if (flags & FORK_FORK) { 432 forkstat.cntfork++; 433 forkstat.sizfork += vm->vm_dsize + vm->vm_ssize; 434 } else if (flags & FORK_VFORK) { 435 forkstat.cntvfork++; 436 forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize; 437 #if 0 438 } else if (flags & FORK_TFORK) { 439 forkstat.cnttfork++; 440 #endif 441 } else if (flags & FORK_RFORK) { 442 forkstat.cntrfork++; 443 forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize; 444 } else { 445 forkstat.cntkthread++; 446 forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize; 447 } 448 449 if (pr->ps_flags & PS_TRACED && flags & FORK_FORK) 450 newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK); 451 #if NSYSTRACE > 0 452 if (ISSET(curp->p_flag, P_SYSTRACE)) 453 newstrp = systrace_getproc(); 454 #endif 455 456 /* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */ 457 do { 458 lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX; 459 } while (pidtaken(lastpid)); 460 p->p_pid = lastpid; 461 462 LIST_INSERT_HEAD(&allproc, p, p_list); 463 LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash); 464 if ((flags & FORK_THREAD) == 0) { 465 LIST_INSERT_AFTER(curpr, pr, ps_pglist); 466 LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling); 467 468 if (pr->ps_flags & PS_TRACED) { 469 pr->ps_oppid = curpr->ps_pid; 470 if (pr->ps_pptr != curpr->ps_pptr) 471 proc_reparent(pr, curpr->ps_pptr); 472 473 /* 474 * Set ptrace status. 475 */ 476 if (flags & FORK_FORK) { 477 pr->ps_ptstat = newptstat; 478 newptstat = NULL; 479 curpr->ps_ptstat->pe_report_event = PTRACE_FORK; 480 pr->ps_ptstat->pe_report_event = PTRACE_FORK; 481 curpr->ps_ptstat->pe_other_pid = pr->ps_pid; 482 pr->ps_ptstat->pe_other_pid = curpr->ps_pid; 483 } 484 } 485 } 486 487 #if NSYSTRACE > 0 488 if (newstrp) 489 systrace_fork(curp, p, newstrp); 490 #endif 491 492 if (tidptr != NULL) { 493 pid_t pid = p->p_pid + THREAD_PID_OFFSET; 494 495 if (copyout(&pid, tidptr, sizeof(pid))) 496 psignal(curp, SIGSEGV); 497 } 498 499 /* 500 * Make child runnable, set start time, and add to run queue. 501 */ 502 SCHED_LOCK(s); 503 getmicrotime(&pr->ps_start); 504 p->p_acflag = AFORK; 505 p->p_stat = SRUN; 506 p->p_cpu = sched_choosecpu_fork(curp, flags); 507 setrunqueue(p); 508 SCHED_UNLOCK(s); 509 510 if (newptstat) 511 free(newptstat, M_SUBPROC); 512 513 /* 514 * Notify any interested parties about the new process. 515 */ 516 if ((flags & FORK_THREAD) == 0) 517 KNOTE(&curpr->ps_klist, NOTE_FORK | p->p_pid); 518 519 /* 520 * Update stats now that we know the fork was successful. 521 */ 522 uvmexp.forks++; 523 if (flags & FORK_PPWAIT) 524 uvmexp.forks_ppwait++; 525 if (flags & FORK_SHAREVM) 526 uvmexp.forks_sharevm++; 527 528 /* 529 * Pass a pointer to the new process to the caller. 530 */ 531 if (rnewprocp != NULL) 532 *rnewprocp = p; 533 534 /* 535 * Preserve synchronization semantics of vfork. If waiting for 536 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT 537 * on ourselves, and sleep on our process for the latter flag 538 * to go away. 539 * XXX Need to stop other rthreads in the parent 540 */ 541 if (flags & FORK_PPWAIT) 542 while (curpr->ps_flags & PS_ISPWAIT) 543 tsleep(curpr, PWAIT, "ppwait", 0); 544 545 /* 546 * If we're tracing the child, alert the parent too. 547 */ 548 if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED)) 549 psignal(curp, SIGTRAP); 550 551 /* 552 * Return child pid to parent process, 553 * marking us as parent via retval[1]. 554 */ 555 if (retval != NULL) { 556 retval[0] = p->p_pid + 557 (flags & FORK_THREAD ? THREAD_PID_OFFSET : 0); 558 retval[1] = 0; 559 } 560 return (0); 561 } 562 563 /* 564 * Checks for current use of a pid, either as a pid or pgid. 565 */ 566 int 567 pidtaken(pid_t pid) 568 { 569 struct proc *p; 570 571 if (pfind(pid) != NULL) 572 return (1); 573 if (pgfind(pid) != NULL) 574 return (1); 575 LIST_FOREACH(p, &zombproc, p_list) { 576 if (p->p_pid == pid || (p->p_p->ps_pgrp && p->p_p->ps_pgrp->pg_id == pid)) 577 return (1); 578 } 579 return (0); 580 } 581 582 #if defined(MULTIPROCESSOR) 583 /* 584 * XXX This is a slight hack to get newly-formed processes to 585 * XXX acquire the kernel lock as soon as they run. 586 */ 587 void 588 proc_trampoline_mp(void) 589 { 590 struct proc *p; 591 592 p = curproc; 593 594 SCHED_ASSERT_LOCKED(); 595 __mp_unlock(&sched_lock); 596 spl0(); 597 SCHED_ASSERT_UNLOCKED(); 598 KASSERT(__mp_lock_held(&kernel_lock) == 0); 599 600 KERNEL_LOCK(); 601 } 602 #endif 603