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