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