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