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