1 /* $OpenBSD: kern_fork.c,v 1.116 2010/06/29 20:25:57 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 int nprocs = 1; /* process 0 */ 69 int randompid; /* when set to 1, pid's go random */ 70 pid_t lastpid; 71 struct forkstat forkstat; 72 73 void fork_return(void *); 74 int pidtaken(pid_t); 75 76 void process_new(struct proc *, struct proc *); 77 78 void 79 fork_return(void *arg) 80 { 81 struct proc *p = (struct proc *)arg; 82 83 if (p->p_flag & P_TRACED) 84 psignal(p, SIGTRAP); 85 86 child_return(p); 87 } 88 89 /*ARGSUSED*/ 90 int 91 sys_fork(struct proc *p, void *v, register_t *retval) 92 { 93 int flags; 94 95 flags = FORK_FORK; 96 if (p->p_ptmask & PTRACE_FORK) 97 flags |= FORK_PTRACE; 98 return (fork1(p, SIGCHLD, flags, NULL, 0, 99 fork_return, NULL, retval, NULL)); 100 } 101 102 /*ARGSUSED*/ 103 int 104 sys_vfork(struct proc *p, void *v, register_t *retval) 105 { 106 return (fork1(p, SIGCHLD, FORK_VFORK|FORK_PPWAIT, NULL, 0, NULL, 107 NULL, retval, NULL)); 108 } 109 110 int 111 sys_rfork(struct proc *p, void *v, register_t *retval) 112 { 113 struct sys_rfork_args /* { 114 syscallarg(int) flags; 115 } */ *uap = v; 116 117 int rforkflags; 118 int flags; 119 120 flags = FORK_RFORK; 121 rforkflags = SCARG(uap, flags); 122 123 if ((rforkflags & RFPROC) == 0) 124 return (EINVAL); 125 126 switch(rforkflags & (RFFDG|RFCFDG)) { 127 case (RFFDG|RFCFDG): 128 return EINVAL; 129 case RFCFDG: 130 flags |= FORK_CLEANFILES; 131 break; 132 case RFFDG: 133 break; 134 default: 135 flags |= FORK_SHAREFILES; 136 break; 137 } 138 139 if (rforkflags & RFNOWAIT) 140 flags |= FORK_NOZOMBIE; 141 142 if (rforkflags & RFMEM) 143 flags |= FORK_SHAREVM; 144 145 if (rforkflags & RFTHREAD) 146 flags |= FORK_THREAD | FORK_SIGHAND | FORK_NOZOMBIE; 147 148 return (fork1(p, SIGCHLD, flags, NULL, 0, NULL, NULL, retval, NULL)); 149 } 150 151 /* 152 * Allocate and initialize a new process. 153 */ 154 void 155 process_new(struct proc *newproc, struct proc *parentproc) 156 { 157 struct process *pr, *parent; 158 159 pr = pool_get(&process_pool, PR_WAITOK | PR_ZERO); 160 pr->ps_mainproc = newproc; 161 TAILQ_INIT(&pr->ps_threads); 162 TAILQ_INSERT_TAIL(&pr->ps_threads, newproc, p_thr_link); 163 pr->ps_refcnt = 1; 164 165 parent = parentproc->p_p; 166 pr->ps_rdomain = parent->ps_rdomain; 167 168 newproc->p_p = pr; 169 } 170 171 /* print the 'table full' message once per 10 seconds */ 172 struct timeval fork_tfmrate = { 10, 0 }; 173 174 int 175 fork1(struct proc *p1, int exitsig, int flags, void *stack, size_t stacksize, 176 void (*func)(void *), void *arg, register_t *retval, 177 struct proc **rnewprocp) 178 { 179 struct proc *p2; 180 uid_t uid; 181 struct vmspace *vm; 182 int count; 183 vaddr_t uaddr; 184 int s; 185 extern void endtsleep(void *); 186 extern void realitexpire(void *); 187 struct ptrace_state *newptstat = NULL; 188 #if NSYSTRACE > 0 189 void *newstrp = NULL; 190 #endif 191 192 /* sanity check some flag combinations */ 193 if (flags & FORK_THREAD) 194 { 195 if (!rthreads_enabled) 196 return (ENOTSUP); 197 if ((flags & (FORK_SIGHAND | FORK_NOZOMBIE)) != 198 (FORK_SIGHAND | FORK_NOZOMBIE)) 199 return (EINVAL); 200 } 201 if (flags & FORK_SIGHAND && (flags & FORK_SHAREVM) == 0) 202 return (EINVAL); 203 204 /* 205 * Although process entries are dynamically created, we still keep 206 * a global limit on the maximum number we will create. We reserve 207 * the last 5 processes to root. The variable nprocs is the current 208 * number of processes, maxproc is the limit. 209 */ 210 uid = p1->p_cred->p_ruid; 211 if ((nprocs >= maxproc - 5 && uid != 0) || nprocs >= maxproc) { 212 static struct timeval lasttfm; 213 214 if (ratecheck(&lasttfm, &fork_tfmrate)) 215 tablefull("proc"); 216 return (EAGAIN); 217 } 218 nprocs++; 219 220 /* 221 * Increment the count of procs running with this uid. Don't allow 222 * a nonprivileged user to exceed their current limit. 223 */ 224 count = chgproccnt(uid, 1); 225 if (uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) { 226 (void)chgproccnt(uid, -1); 227 nprocs--; 228 return (EAGAIN); 229 } 230 231 uaddr = uvm_km_alloc1(kernel_map, USPACE, USPACE_ALIGN, 1); 232 if (uaddr == 0) { 233 chgproccnt(uid, -1); 234 nprocs--; 235 return (ENOMEM); 236 } 237 238 /* 239 * From now on, we're committed to the fork and cannot fail. 240 */ 241 242 /* Allocate new proc. */ 243 p2 = pool_get(&proc_pool, PR_WAITOK); 244 245 p2->p_stat = SIDL; /* protect against others */ 246 p2->p_exitsig = exitsig; 247 p2->p_flag = 0; 248 249 if (flags & FORK_THREAD) { 250 atomic_setbits_int(&p2->p_flag, P_THREAD); 251 p2->p_p = p1->p_p; 252 TAILQ_INSERT_TAIL(&p2->p_p->ps_threads, p2, p_thr_link); 253 p2->p_p->ps_refcnt++; 254 } else { 255 process_new(p2, p1); 256 } 257 258 /* 259 * Make a proc table entry for the new process. 260 * Start by zeroing the section of proc that is zero-initialized, 261 * then copy the section that is copied directly from the parent. 262 */ 263 bzero(&p2->p_startzero, 264 (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero)); 265 bcopy(&p1->p_startcopy, &p2->p_startcopy, 266 (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy)); 267 268 /* 269 * Initialize the timeouts. 270 */ 271 timeout_set(&p2->p_sleep_to, endtsleep, p2); 272 timeout_set(&p2->p_realit_to, realitexpire, p2); 273 274 /* 275 * Duplicate sub-structures as needed. 276 * Increase reference counts on shared objects. 277 * The p_stats and p_sigacts substructs are set in vm_fork. 278 */ 279 if (p1->p_flag & P_PROFIL) 280 startprofclock(p2); 281 atomic_setbits_int(&p2->p_flag, p1->p_flag & (P_SUGID | P_SUGIDEXEC)); 282 if (flags & FORK_PTRACE) 283 atomic_setbits_int(&p2->p_flag, p1->p_flag & P_TRACED); 284 if ((flags & FORK_THREAD) == 0) { 285 p2->p_p->ps_cred = pool_get(&pcred_pool, PR_WAITOK); 286 bcopy(p1->p_p->ps_cred, p2->p_p->ps_cred, sizeof(*p2->p_p->ps_cred)); 287 crhold(p1->p_ucred); 288 } 289 290 /* bump references to the text vnode (for procfs) */ 291 p2->p_textvp = p1->p_textvp; 292 if (p2->p_textvp) 293 vref(p2->p_textvp); 294 295 if (flags & FORK_CLEANFILES) 296 p2->p_fd = fdinit(p1); 297 else if (flags & FORK_SHAREFILES) 298 p2->p_fd = fdshare(p1); 299 else 300 p2->p_fd = fdcopy(p1); 301 302 if ((flags & FORK_THREAD) == 0) { 303 p2->p_p->ps_limit = p1->p_p->ps_limit; 304 p2->p_p->ps_limit->p_refcnt++; 305 } 306 307 if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT) 308 atomic_setbits_int(&p2->p_flag, P_CONTROLT); 309 if (flags & FORK_PPWAIT) 310 atomic_setbits_int(&p2->p_flag, P_PPWAIT); 311 p2->p_pptr = p1; 312 if (flags & FORK_NOZOMBIE) 313 atomic_setbits_int(&p2->p_flag, P_NOZOMBIE); 314 LIST_INIT(&p2->p_children); 315 316 #ifdef KTRACE 317 /* 318 * Copy traceflag and tracefile if enabled. 319 * If not inherited, these were zeroed above. 320 */ 321 if (p1->p_traceflag & KTRFAC_INHERIT) { 322 p2->p_traceflag = p1->p_traceflag; 323 if ((p2->p_tracep = p1->p_tracep) != NULL) 324 vref(p2->p_tracep); 325 } 326 #endif 327 328 /* 329 * set priority of child to be that of parent 330 * XXX should move p_estcpu into the region of struct proc which gets 331 * copied. 332 */ 333 scheduler_fork_hook(p1, p2); 334 335 /* 336 * Create signal actions for the child process. 337 */ 338 if (flags & FORK_SIGHAND) 339 sigactsshare(p1, p2); 340 else 341 p2->p_sigacts = sigactsinit(p1); 342 343 /* 344 * If emulation has process fork hook, call it now. 345 */ 346 if (p2->p_emul->e_proc_fork) 347 (*p2->p_emul->e_proc_fork)(p2, p1); 348 349 p2->p_addr = (struct user *)uaddr; 350 351 /* 352 * Finish creating the child process. It will return through a 353 * different path later. 354 */ 355 uvm_fork(p1, p2, ((flags & FORK_SHAREVM) ? TRUE : FALSE), stack, 356 stacksize, func ? func : child_return, arg ? arg : p2); 357 358 timeout_set(&p2->p_stats->p_virt_to, virttimer_trampoline, p2); 359 timeout_set(&p2->p_stats->p_prof_to, proftimer_trampoline, p2); 360 361 vm = p2->p_vmspace; 362 363 if (flags & FORK_FORK) { 364 forkstat.cntfork++; 365 forkstat.sizfork += vm->vm_dsize + vm->vm_ssize; 366 } else if (flags & FORK_VFORK) { 367 forkstat.cntvfork++; 368 forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize; 369 } else if (flags & FORK_RFORK) { 370 forkstat.cntrfork++; 371 forkstat.sizrfork += vm->vm_dsize + vm->vm_ssize; 372 } else { 373 forkstat.cntkthread++; 374 forkstat.sizkthread += vm->vm_dsize + vm->vm_ssize; 375 } 376 377 if (p2->p_flag & P_TRACED && flags & FORK_FORK) 378 newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK); 379 #if NSYSTRACE > 0 380 if (ISSET(p1->p_flag, P_SYSTRACE)) 381 newstrp = systrace_getproc(); 382 #endif 383 384 /* Find an unused pid satisfying 1 <= lastpid <= PID_MAX */ 385 rw_enter_write(&allproclk); 386 do { 387 lastpid = 1 + (randompid ? arc4random() : lastpid) % PID_MAX; 388 } while (pidtaken(lastpid)); 389 p2->p_pid = lastpid; 390 391 LIST_INSERT_HEAD(&allproc, p2, p_list); 392 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash); 393 rw_exit_write(&allproclk); 394 LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling); 395 LIST_INSERT_AFTER(p1, p2, p_pglist); 396 if (p2->p_flag & P_TRACED) { 397 p2->p_oppid = p1->p_pid; 398 if (p2->p_pptr != p1->p_pptr) 399 proc_reparent(p2, p1->p_pptr); 400 401 /* 402 * Set ptrace status. 403 */ 404 if (flags & FORK_FORK) { 405 p2->p_ptstat = newptstat; 406 newptstat = NULL; 407 p1->p_ptstat->pe_report_event = PTRACE_FORK; 408 p2->p_ptstat->pe_report_event = PTRACE_FORK; 409 p1->p_ptstat->pe_other_pid = p2->p_pid; 410 p2->p_ptstat->pe_other_pid = p1->p_pid; 411 } 412 } 413 414 #if NSYSTRACE > 0 415 if (newstrp) 416 systrace_fork(p1, p2, newstrp); 417 #endif 418 419 /* 420 * Make child runnable, set start time, and add to run queue. 421 */ 422 SCHED_LOCK(s); 423 getmicrotime(&p2->p_stats->p_start); 424 p2->p_acflag = AFORK; 425 p2->p_stat = SRUN; 426 p2->p_cpu = sched_choosecpu_fork(p1, flags); 427 setrunqueue(p2); 428 SCHED_UNLOCK(s); 429 430 if (newptstat) 431 free(newptstat, M_SUBPROC); 432 433 /* 434 * Notify any interested parties about the new process. 435 */ 436 if ((flags & FORK_THREAD) == 0) 437 KNOTE(&p1->p_p->ps_klist, NOTE_FORK | p2->p_pid); 438 439 /* 440 * Update stats now that we know the fork was successful. 441 */ 442 uvmexp.forks++; 443 if (flags & FORK_PPWAIT) 444 uvmexp.forks_ppwait++; 445 if (flags & FORK_SHAREVM) 446 uvmexp.forks_sharevm++; 447 448 /* 449 * Pass a pointer to the new process to the caller. 450 */ 451 if (rnewprocp != NULL) 452 *rnewprocp = p2; 453 454 /* 455 * Preserve synchronization semantics of vfork. If waiting for 456 * child to exec or exit, set P_PPWAIT on child, and sleep on our 457 * proc (in case of exit). 458 */ 459 if (flags & FORK_PPWAIT) 460 while (p2->p_flag & P_PPWAIT) 461 tsleep(p1, PWAIT, "ppwait", 0); 462 463 /* 464 * If we're tracing the child, alert the parent too. 465 */ 466 if ((flags & FORK_PTRACE) && (p1->p_flag & P_TRACED)) 467 psignal(p1, SIGTRAP); 468 469 /* 470 * Return child pid to parent process, 471 * marking us as parent via retval[1]. 472 */ 473 if (retval != NULL) { 474 retval[0] = p2->p_pid; 475 retval[1] = 0; 476 } 477 return (0); 478 } 479 480 /* 481 * Checks for current use of a pid, either as a pid or pgid. 482 */ 483 int 484 pidtaken(pid_t pid) 485 { 486 struct proc *p; 487 488 if (pfind(pid) != NULL) 489 return (1); 490 if (pgfind(pid) != NULL) 491 return (1); 492 LIST_FOREACH(p, &zombproc, p_list) 493 if (p->p_pid == pid || (p->p_pgrp && p->p_pgrp->pg_id == pid)) 494 return (1); 495 return (0); 496 } 497 498 #if defined(MULTIPROCESSOR) 499 /* 500 * XXX This is a slight hack to get newly-formed processes to 501 * XXX acquire the kernel lock as soon as they run. 502 */ 503 void 504 proc_trampoline_mp(void) 505 { 506 struct proc *p; 507 508 p = curproc; 509 510 SCHED_ASSERT_LOCKED(); 511 __mp_unlock(&sched_lock); 512 spl0(); 513 SCHED_ASSERT_UNLOCKED(); 514 KASSERT(__mp_lock_held(&kernel_lock) == 0); 515 516 KERNEL_PROC_LOCK(p); 517 } 518 #endif 519