1 /* $OpenBSD: init_main.c,v 1.328 2025/01/01 07:44:54 jsg Exp $ */ 2 /* $NetBSD: init_main.c,v 1.84.4.1 1996/06/02 09:08:06 mrg Exp $ */ 3 4 /* 5 * Copyright (c) 1995 Christopher G. Demetriou. All rights reserved. 6 * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993 7 * The Regents of the University of California. All rights reserved. 8 * (c) UNIX System Laboratories, Inc. 9 * All or some portions of this file are derived from material licensed 10 * to the University of California by American Telephone and Telegraph 11 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 12 * the permission of UNIX System Laboratories, Inc. 13 * 14 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions 16 * are met: 17 * 1. Redistributions of source code must retain the above copyright 18 * notice, this list of conditions and the following disclaimer. 19 * 2. Redistributions in binary form must reproduce the above copyright 20 * notice, this list of conditions and the following disclaimer in the 21 * documentation and/or other materials provided with the distribution. 22 * 3. Neither the name of the University nor the names of its contributors 23 * may be used to endorse or promote products derived from this software 24 * without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 * SUCH DAMAGE. 37 * 38 * @(#)init_main.c 8.9 (Berkeley) 1/21/94 39 */ 40 41 #include <sys/param.h> 42 #include <sys/filedesc.h> 43 #include <sys/errno.h> 44 #include <sys/kthread.h> 45 #include <sys/mount.h> 46 #include <sys/proc.h> 47 #include <sys/resourcevar.h> 48 #include <sys/signalvar.h> 49 #include <sys/systm.h> 50 #include <sys/clockintr.h> 51 #include <sys/namei.h> 52 #include <sys/vnode.h> 53 #include <sys/tty.h> 54 #include <sys/buf.h> 55 #include <sys/device.h> 56 #include <sys/socketvar.h> 57 #include <sys/lockf.h> 58 #include <sys/reboot.h> 59 #ifdef SYSVSHM 60 #include <sys/shm.h> 61 #endif 62 #ifdef SYSVSEM 63 #include <sys/sem.h> 64 #endif 65 #ifdef SYSVMSG 66 #include <sys/msg.h> 67 #endif 68 #include <sys/domain.h> 69 #include <sys/event.h> 70 #include <sys/msgbuf.h> 71 #include <sys/mbuf.h> 72 #include <sys/pipe.h> 73 #include <sys/witness.h> 74 #include <sys/smr.h> 75 #include <sys/evcount.h> 76 77 #include <sys/syscallargs.h> 78 79 #include <uvm/uvm_extern.h> 80 81 #include <net/if.h> 82 #include <net/rtable.h> 83 84 #if defined(CRYPTO) 85 #include <crypto/cryptodev.h> 86 #include <crypto/cryptosoft.h> 87 #endif 88 89 #if defined(KUBSAN) 90 extern void kubsan_init(void); 91 #endif 92 93 #if defined(NFSSERVER) || defined(NFSCLIENT) 94 extern void nfs_init(void); 95 #endif 96 97 #include "stoeplitz.h" 98 #if NSTOEPLITZ > 0 99 extern void stoeplitz_init(void); 100 #endif 101 102 #include "mpath.h" 103 #include "vscsi.h" 104 #include "softraid.h" 105 106 const char copyright[] = 107 "Copyright (c) 1982, 1986, 1989, 1991, 1993\n" 108 "\tThe Regents of the University of California. All rights reserved.\n" 109 "Copyright (c) 1995-2025 OpenBSD. All rights reserved. https://www.OpenBSD.org\n"; 110 111 /* Components of the first process -- never freed. */ 112 struct session session0; 113 struct pgrp pgrp0; 114 struct proc proc0; 115 struct process process0; 116 struct plimit limit0; 117 struct vmspace vmspace0; 118 struct sigacts sigacts0; 119 struct process *initprocess; 120 struct proc *reaperproc; 121 122 extern struct user *proc0paddr; 123 124 struct vnode *rootvp, *swapdev_vp; 125 int boothowto; 126 int db_active = 0; 127 int ncpus = 1; 128 int ncpusfound = 1; /* number of cpus we find */ 129 volatile int start_init_exec; /* semaphore for start_init() */ 130 131 #if !defined(NO_PROPOLICE) 132 long __guard_local __attribute__((section(".openbsd.randomdata"))); 133 #endif 134 135 /* XXX return int so gcc -Werror won't complain */ 136 int main(void *); 137 void check_console(struct proc *); 138 void start_init(void *); 139 void db_ctf_init(void); 140 void prof_init(void); 141 void init_exec(void); 142 void futex_init(void); 143 void tslp_init(void); 144 void taskq_init(void); 145 void timeout_proc_init(void); 146 void pool_gc_pages(void *); 147 void percpu_init(void); 148 149 #ifdef DIAGNOSTIC 150 int pdevinit_done = 0; 151 #endif 152 153 /* 154 * System startup; initialize the world, create process 0, mount root 155 * filesystem, and fork to create init and pagedaemon. Most of the 156 * hard work is done in the lower-level initialization routines including 157 * startup(), which does memory initialization and autoconfiguration. 158 */ 159 /* XXX return int, so gcc -Werror won't complain */ 160 int 161 main(void *framep) 162 { 163 struct proc *p; 164 struct process *pr; 165 struct pdevinit *pdev; 166 extern struct pdevinit pdevinit[]; 167 extern void disk_init(void); 168 169 /* 170 * Initialize the current process pointer (curproc) before 171 * any possible traps/probes to simplify trap processing. 172 */ 173 curproc = p = &proc0; 174 p->p_cpu = curcpu(); 175 176 /* 177 * Initialize timeouts. 178 */ 179 timeout_startup(); 180 181 /* 182 * Attempt to find console and initialize 183 * in case of early panic or other messages. 184 */ 185 config_init(); /* init autoconfiguration data structures */ 186 consinit(); 187 188 printf("%s\n", copyright); 189 190 #ifdef KUBSAN 191 /* Initialize kubsan. */ 192 kubsan_init(); 193 #endif 194 195 WITNESS_INITIALIZE(); 196 197 KERNEL_LOCK_INIT(); 198 SCHED_LOCK_INIT(); 199 200 rw_obj_init(); 201 uvm_init(); 202 disk_init(); /* must come before autoconfiguration */ 203 tty_init(); /* initialise tty's */ 204 cpu_startup(); 205 206 random_start(boothowto & RB_GOODRANDOM); /* Start the flow */ 207 208 /* 209 * Initialize mbuf's. Do this now because we might attempt to 210 * allocate mbufs or mbuf clusters during autoconfiguration. 211 */ 212 mbinit(); 213 214 #if NSTOEPLITZ > 0 215 stoeplitz_init(); 216 #endif 217 218 /* Initialize sockets. */ 219 soinit(); 220 221 /* Initialize SRP subsystem. */ 222 srp_startup(); 223 224 /* Initialize SMR subsystem. */ 225 smr_startup(); 226 227 /* 228 * Initialize process and pgrp structures. 229 */ 230 procinit(); 231 232 /* Initialize file locking. */ 233 lf_init(); 234 235 /* 236 * Initialize filedescriptors. 237 */ 238 filedesc_init(); 239 240 /* 241 * Initialize pipes. 242 */ 243 pipe_init(); 244 245 /* 246 * Initialize kqueues. 247 */ 248 kqueue_init(); 249 250 /* 251 * Initialize futexes. 252 */ 253 futex_init(); 254 tslp_init(); 255 256 /* Create credentials. */ 257 p->p_ucred = crget(); 258 p->p_ucred->cr_ngroups = 1; /* group 0 */ 259 260 /* 261 * Create process 0 (the swapper). 262 */ 263 pr = &process0; 264 process_initialize(pr, p); 265 266 LIST_INSERT_HEAD(&allprocess, pr, ps_list); 267 LIST_INSERT_HEAD(PIDHASH(0), pr, ps_hash); 268 atomic_setbits_int(&pr->ps_flags, PS_SYSTEM); 269 270 /* Set the default routing table/domain. */ 271 process0.ps_rtableid = 0; 272 273 LIST_INSERT_HEAD(&allproc, p, p_list); 274 pr->ps_pgrp = &pgrp0; 275 LIST_INSERT_HEAD(TIDHASH(0), p, p_hash); 276 LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash); 277 LIST_INIT(&pgrp0.pg_members); 278 LIST_INSERT_HEAD(&pgrp0.pg_members, pr, ps_pglist); 279 280 pgrp0.pg_session = &session0; 281 session0.s_count = 1; 282 session0.s_leader = pr; 283 284 atomic_setbits_int(&p->p_flag, P_SYSTEM); 285 p->p_stat = SONPROC; 286 pr->ps_nice = NZERO; 287 strlcpy(pr->ps_comm, "swapper", sizeof(pr->ps_comm)); 288 289 /* Init timeouts. */ 290 timeout_set(&p->p_sleep_to, endtsleep, p); 291 292 /* Initialize signal state for process 0. */ 293 signal_init(); 294 siginit(&sigacts0); 295 pr->ps_sigacts = &sigacts0; 296 297 /* Create the file descriptor table. */ 298 p->p_fd = pr->ps_fd = fdinit(); 299 300 /* Create the limits structures. */ 301 lim_startup(&limit0); 302 pr->ps_limit = &limit0; 303 304 /* Allocate a prototype map so we have something to fork. */ 305 uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS), 306 trunc_page(VM_MAX_ADDRESS), TRUE, TRUE); 307 p->p_vmspace = pr->ps_vmspace = &vmspace0; 308 309 p->p_addr = proc0paddr; /* XXX */ 310 311 /* 312 * Charge root for one process. 313 */ 314 (void)chgproccnt(0, 1); 315 316 /* Initialize run queues */ 317 sched_init_runqueues(); 318 sleep_queue_init(); 319 clockqueue_init(&curcpu()->ci_queue); 320 sched_init_cpu(curcpu()); 321 p->p_cpu->ci_randseed = (arc4random() & 0x7fffffff) + 1; 322 323 /* Initialize timeouts in process context. */ 324 timeout_proc_init(); 325 326 /* Initialize task queues */ 327 taskq_init(); 328 329 /* Initialize the interface/address trees */ 330 ifinit(); 331 332 /* Lock the kernel on behalf of proc0. */ 333 KERNEL_LOCK(); 334 335 #if NMPATH > 0 336 /* Attach mpath before hardware */ 337 config_rootfound("mpath", NULL); 338 #endif 339 340 /* Configure the devices */ 341 cpu_configure(); 342 343 /* Configure virtual memory system, set vm rlimits. */ 344 uvm_init_limits(&limit0); 345 346 /* Per CPU memory allocation */ 347 percpu_init(); 348 349 /* Initialize the file systems. */ 350 #if defined(NFSSERVER) || defined(NFSCLIENT) 351 nfs_init(); /* initialize server/shared data */ 352 #endif 353 vfsinit(); 354 355 /* Start real time and statistics clocks. */ 356 initclocks(); 357 358 #ifdef SYSVSHM 359 /* Initialize System V style shared memory. */ 360 shminit(); 361 #endif 362 363 #ifdef SYSVSEM 364 /* Initialize System V style semaphores. */ 365 seminit(); 366 #endif 367 368 #ifdef SYSVMSG 369 /* Initialize System V style message queues. */ 370 msginit(); 371 #endif 372 373 /* Create default routing table before attaching lo0. */ 374 rtable_init(); 375 376 /* Attach pseudo-devices. */ 377 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++) 378 if (pdev->pdev_count > 0) 379 (*pdev->pdev_attach)(pdev->pdev_count); 380 #ifdef DIAGNOSTIC 381 pdevinit_done = 1; 382 #endif 383 384 #ifdef CRYPTO 385 crypto_init(); 386 swcr_init(); 387 #endif /* CRYPTO */ 388 389 /* 390 * Initialize protocols. 391 */ 392 domaininit(); 393 394 initconsbuf(); 395 396 #if defined(GPROF) || defined(DDBPROF) 397 /* Initialize kernel profiling. */ 398 prof_init(); 399 #endif 400 401 /* Enable per-CPU data. */ 402 mbcpuinit(); 403 kqueue_init_percpu(); 404 pmap_init_percpu(); 405 uvm_init_percpu(); 406 evcount_init_percpu(); 407 408 /* init exec */ 409 init_exec(); 410 411 /* Start the scheduler */ 412 scheduler_start(); 413 414 /* 415 * Create process 1 (init(8)). We do this now, as Unix has 416 * historically had init be process 1, and changing this would 417 * probably upset a lot of people. 418 * 419 * Note that process 1 won't immediately exec init(8), but will 420 * wait for us to inform it that the root file system has been 421 * mounted. 422 */ 423 { 424 struct proc *initproc; 425 426 if (fork1(p, FORK_FORK, start_init, NULL, NULL, &initproc)) 427 panic("fork init"); 428 initprocess = initproc->p_p; 429 } 430 431 /* 432 * Create any kernel threads whose creation was deferred because 433 * initprocess had not yet been created. 434 */ 435 kthread_run_deferred_queue(); 436 437 /* 438 * Now that device driver threads have been created, wait for 439 * them to finish any deferred autoconfiguration. Note we don't 440 * need to lock this semaphore, since we haven't booted any 441 * secondary processors, yet. 442 */ 443 while (config_pending) 444 tsleep_nsec(&config_pending, PWAIT, "cfpend", INFSLP); 445 446 dostartuphooks(); 447 448 #if NVSCSI > 0 449 config_rootfound("vscsi", NULL); 450 #endif 451 #if NSOFTRAID > 0 452 config_rootfound("softraid", NULL); 453 #endif 454 455 /* Configure root/swap devices */ 456 diskconf(); 457 458 #ifdef DDB 459 /* Make debug symbols available in ddb. */ 460 db_ctf_init(); 461 #endif 462 463 if (mountroot == NULL || ((*mountroot)() != 0)) 464 panic("cannot mount root"); 465 466 TAILQ_FIRST(&mountlist)->mnt_flag |= MNT_ROOTFS; 467 468 /* Get the vnode for '/'. Set p->p_fd->fd_cdir to reference it. */ 469 if (VFS_ROOT(TAILQ_FIRST(&mountlist), &rootvnode)) 470 panic("cannot find root vnode"); 471 p->p_fd->fd_cdir = rootvnode; 472 vref(p->p_fd->fd_cdir); 473 VOP_UNLOCK(rootvnode); 474 p->p_fd->fd_rdir = NULL; 475 476 /* 477 * Now that root is mounted, we can fixup initprocess's CWD 478 * info. All other processes are kthreads, which merely 479 * share proc0's CWD info. 480 */ 481 initprocess->ps_fd->fd_cdir = rootvnode; 482 vref(initprocess->ps_fd->fd_cdir); 483 initprocess->ps_fd->fd_rdir = NULL; 484 485 /* 486 * Now can look at time, having had a chance to verify the time 487 * from the file system. 488 */ 489 LIST_FOREACH(pr, &allprocess, ps_list) { 490 nanouptime(&pr->ps_start); 491 } 492 nanouptime(&curcpu()->ci_schedstate.spc_runtime); 493 494 uvm_swap_init(); 495 496 /* Create the pageout daemon kernel thread. */ 497 if (kthread_create(uvm_pageout, NULL, NULL, "pagedaemon")) 498 panic("fork pagedaemon"); 499 500 /* Create the reaper daemon kernel thread. */ 501 if (kthread_create(reaper, NULL, &reaperproc, "reaper")) 502 panic("fork reaper"); 503 504 /* Create the cleaner daemon kernel thread. */ 505 if (kthread_create(buf_daemon, NULL, &cleanerproc, "cleaner")) 506 panic("fork cleaner"); 507 508 /* Create the update daemon kernel thread. */ 509 if (kthread_create(syncer_thread, NULL, &syncerproc, "update")) 510 panic("fork update"); 511 512 /* Create the aiodone daemon kernel thread. */ 513 if (kthread_create(uvm_aiodone_daemon, NULL, NULL, "aiodoned")) 514 panic("fork aiodoned"); 515 516 #if !defined(__hppa__) 517 /* Create the page zeroing kernel thread. */ 518 if (kthread_create(uvm_pagezero_thread, NULL, NULL, "zerothread")) 519 panic("fork zerothread"); 520 #endif 521 522 #if defined(MULTIPROCESSOR) 523 /* Boot the secondary processors. */ 524 cpu_boot_secondary_processors(); 525 #endif 526 527 /* Now that all CPUs partake in scheduling, start SMR thread. */ 528 smr_startup_thread(); 529 530 config_process_deferred_mountroot(); 531 532 /* 533 * Okay, now we can let init(8) exec! It's off to userland! 534 */ 535 start_init_exec = 1; 536 wakeup((void *)&start_init_exec); 537 538 /* 539 * Start the idle pool page garbage collector 540 */ 541 #if defined(MULTIPROCESSOR) 542 pool_gc_pages(NULL); 543 #endif 544 545 start_periodic_resettodr(); 546 547 /* 548 * proc0: nothing to do, back to sleep 549 */ 550 while (1) 551 tsleep_nsec(&proc0, PVM, "scheduler", INFSLP); 552 /* NOTREACHED */ 553 } 554 555 /* 556 * List of paths to try when searching for "init". 557 */ 558 static char *initpaths[] = { 559 "/sbin/init", 560 "/sbin/oinit", 561 "/sbin/init.bak", 562 NULL, 563 }; 564 565 void 566 check_console(struct proc *p) 567 { 568 struct nameidata nd; 569 int error; 570 571 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", p); 572 error = namei(&nd); 573 if (error) { 574 if (error == ENOENT) 575 printf("warning: /dev/console does not exist\n"); 576 else 577 printf("warning: /dev/console error %d\n", error); 578 } else 579 vrele(nd.ni_vp); 580 } 581 582 /* 583 * Start the initial user process; try exec'ing each pathname in "initpaths". 584 * The program is invoked with one argument containing the boot flags. 585 */ 586 void 587 start_init(void *arg) 588 { 589 struct proc *p = arg; 590 vaddr_t addr; 591 struct sys_execve_args /* { 592 syscallarg(const char *) path; 593 syscallarg(char *const *) argp; 594 syscallarg(char *const *) envp; 595 } */ args; 596 int options, error; 597 long i; 598 register_t retval[2]; 599 char flags[4], *flagsp; 600 char **pathp, *path, *ucp, **uap, *arg0, *arg1 = NULL; 601 602 /* 603 * Now in process 1. 604 */ 605 606 /* 607 * Wait for main() to tell us that it's safe to exec. 608 */ 609 while (start_init_exec == 0) 610 tsleep_nsec(&start_init_exec, PWAIT, "initexec", INFSLP); 611 612 check_console(p); 613 614 /* process 0 ignores SIGCHLD, but we can't */ 615 p->p_p->ps_sigacts->ps_sigflags = 0; 616 617 /* 618 * Need just enough stack to hold the faked-up "execve()" arguments. 619 */ 620 #ifdef MACHINE_STACK_GROWS_UP 621 addr = USRSTACK; 622 #else 623 addr = USRSTACK - PAGE_SIZE; 624 #endif 625 p->p_vmspace->vm_maxsaddr = (caddr_t)addr; 626 p->p_vmspace->vm_minsaddr = (caddr_t)(addr + PAGE_SIZE); 627 if (uvm_map(&p->p_vmspace->vm_map, &addr, PAGE_SIZE, 628 NULL, UVM_UNKNOWN_OFFSET, 0, 629 UVM_MAPFLAG(PROT_READ | PROT_WRITE, PROT_MASK, MAP_INHERIT_COPY, 630 MADV_NORMAL, 631 UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW|UVM_FLAG_STACK))) 632 panic("init: couldn't allocate argument space"); 633 634 for (pathp = &initpaths[0]; (path = *pathp) != NULL; pathp++) { 635 #ifdef MACHINE_STACK_GROWS_UP 636 ucp = (char *)addr; 637 #else 638 ucp = (char *)(addr + PAGE_SIZE); 639 #endif 640 /* 641 * Construct the boot flag argument. 642 */ 643 flagsp = flags; 644 *flagsp++ = '-'; 645 options = 0; 646 647 if (boothowto & RB_SINGLE) { 648 *flagsp++ = 's'; 649 options = 1; 650 } 651 #ifdef notyet 652 if (boothowto & RB_FASTBOOT) { 653 *flagsp++ = 'f'; 654 options = 1; 655 } 656 #endif 657 658 /* 659 * Move out the flags (arg 1), if necessary. 660 */ 661 if (options != 0) { 662 *flagsp++ = '\0'; 663 i = flagsp - flags; 664 #ifdef DEBUG 665 printf("init: copying out flags `%s' %ld\n", flags, i); 666 #endif 667 #ifdef MACHINE_STACK_GROWS_UP 668 arg1 = ucp; 669 (void)copyout((caddr_t)flags, (caddr_t)ucp, i); 670 ucp += i; 671 #else 672 (void)copyout((caddr_t)flags, (caddr_t)(ucp -= i), i); 673 arg1 = ucp; 674 #endif 675 } 676 677 /* 678 * Move out the file name (also arg 0). 679 */ 680 i = strlen(path) + 1; 681 #ifdef DEBUG 682 printf("init: copying out path `%s' %ld\n", path, i); 683 #endif 684 #ifdef MACHINE_STACK_GROWS_UP 685 arg0 = ucp; 686 (void)copyout((caddr_t)path, (caddr_t)ucp, i); 687 ucp += i; 688 ucp = (caddr_t)ALIGN((u_long)ucp); 689 uap = (char **)ucp + 3; 690 #else 691 (void)copyout((caddr_t)path, (caddr_t)(ucp -= i), i); 692 arg0 = ucp; 693 uap = (char **)((u_long)ucp & ~ALIGNBYTES); 694 #endif 695 696 /* 697 * Move out the arg pointers. 698 */ 699 i = 0; 700 copyout(&i, (caddr_t)--uap, sizeof(register_t)); /* terminator */ 701 if (options != 0) 702 copyout(&arg1, (caddr_t)--uap, sizeof(register_t)); 703 copyout(&arg0, (caddr_t)--uap, sizeof(register_t)); 704 705 /* 706 * Point at the arguments. 707 */ 708 SCARG(&args, path) = arg0; 709 SCARG(&args, argp) = uap; 710 SCARG(&args, envp) = NULL; 711 712 /* 713 * Now try to exec the program. If can't for any reason 714 * other than it doesn't exist, complain. 715 */ 716 if ((error = sys_execve(p, &args, retval)) == EJUSTRETURN) { 717 KERNEL_UNLOCK(); 718 return; 719 } 720 if (error != ENOENT) 721 printf("exec %s: error %d\n", path, error); 722 } 723 printf("init: not found\n"); 724 panic("no init"); 725 } 726