1 /* $OpenBSD: init_main.c,v 1.322 2023/08/29 16:19:34 claudio 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-2023 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 taskq_init(void); 144 void timeout_proc_init(void); 145 void pool_gc_pages(void *); 146 void percpu_init(void); 147 148 #ifdef DIAGNOSTIC 149 int pdevinit_done = 0; 150 #endif 151 152 /* 153 * System startup; initialize the world, create process 0, mount root 154 * filesystem, and fork to create init and pagedaemon. Most of the 155 * hard work is done in the lower-level initialization routines including 156 * startup(), which does memory initialization and autoconfiguration. 157 */ 158 /* XXX return int, so gcc -Werror won't complain */ 159 int 160 main(void *framep) 161 { 162 struct proc *p; 163 struct process *pr; 164 struct pdevinit *pdev; 165 extern struct pdevinit pdevinit[]; 166 extern void disk_init(void); 167 168 /* 169 * Initialize the current process pointer (curproc) before 170 * any possible traps/probes to simplify trap processing. 171 */ 172 curproc = p = &proc0; 173 p->p_cpu = curcpu(); 174 175 /* 176 * Initialize timeouts. 177 */ 178 timeout_startup(); 179 180 /* 181 * Attempt to find console and initialize 182 * in case of early panic or other messages. 183 */ 184 config_init(); /* init autoconfiguration data structures */ 185 consinit(); 186 187 printf("%s\n", copyright); 188 189 #ifdef KUBSAN 190 /* Initialize kubsan. */ 191 kubsan_init(); 192 #endif 193 194 WITNESS_INITIALIZE(); 195 196 KERNEL_LOCK_INIT(); 197 SCHED_LOCK_INIT(); 198 199 rw_obj_init(); 200 uvm_init(); 201 disk_init(); /* must come before autoconfiguration */ 202 tty_init(); /* initialise tty's */ 203 cpu_startup(); 204 205 random_start(boothowto & RB_GOODRANDOM); /* Start the flow */ 206 207 /* 208 * Initialize mbuf's. Do this now because we might attempt to 209 * allocate mbufs or mbuf clusters during autoconfiguration. 210 */ 211 mbinit(); 212 213 #if NSTOEPLITZ > 0 214 stoeplitz_init(); 215 #endif 216 217 /* Initialize sockets. */ 218 soinit(); 219 220 /* Initialize SRP subsystem. */ 221 srp_startup(); 222 223 /* Initialize SMR subsystem. */ 224 smr_startup(); 225 226 /* 227 * Initialize process and pgrp structures. 228 */ 229 procinit(); 230 231 /* Initialize file locking. */ 232 lf_init(); 233 234 /* 235 * Initialize filedescriptors. 236 */ 237 filedesc_init(); 238 239 /* 240 * Initialize pipes. 241 */ 242 pipe_init(); 243 244 /* 245 * Initialize kqueues. 246 */ 247 kqueue_init(); 248 249 /* 250 * Initialize futexes. 251 */ 252 futex_init(); 253 254 /* Create credentials. */ 255 p->p_ucred = crget(); 256 p->p_ucred->cr_ngroups = 1; /* group 0 */ 257 258 /* 259 * Create process 0 (the swapper). 260 */ 261 pr = &process0; 262 process_initialize(pr, p); 263 264 LIST_INSERT_HEAD(&allprocess, pr, ps_list); 265 LIST_INSERT_HEAD(PIDHASH(0), pr, ps_hash); 266 atomic_setbits_int(&pr->ps_flags, PS_SYSTEM); 267 268 /* Set the default routing table/domain. */ 269 process0.ps_rtableid = 0; 270 271 LIST_INSERT_HEAD(&allproc, p, p_list); 272 pr->ps_pgrp = &pgrp0; 273 LIST_INSERT_HEAD(TIDHASH(0), p, p_hash); 274 LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash); 275 LIST_INIT(&pgrp0.pg_members); 276 LIST_INSERT_HEAD(&pgrp0.pg_members, pr, ps_pglist); 277 278 pgrp0.pg_session = &session0; 279 session0.s_count = 1; 280 session0.s_leader = pr; 281 282 atomic_setbits_int(&p->p_flag, P_SYSTEM); 283 p->p_stat = SONPROC; 284 pr->ps_nice = NZERO; 285 strlcpy(pr->ps_comm, "swapper", sizeof(pr->ps_comm)); 286 287 /* Init timeouts. */ 288 timeout_set(&p->p_sleep_to, endtsleep, p); 289 290 /* Initialize signal state for process 0. */ 291 signal_init(); 292 siginit(&sigacts0); 293 pr->ps_sigacts = &sigacts0; 294 295 /* Create the file descriptor table. */ 296 p->p_fd = pr->ps_fd = fdinit(); 297 298 /* Create the limits structures. */ 299 lim_startup(&limit0); 300 pr->ps_limit = &limit0; 301 302 /* Allocate a prototype map so we have something to fork. */ 303 uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS), 304 trunc_page(VM_MAX_ADDRESS), TRUE, TRUE); 305 p->p_vmspace = pr->ps_vmspace = &vmspace0; 306 307 p->p_addr = proc0paddr; /* XXX */ 308 309 /* 310 * Charge root for one process. 311 */ 312 (void)chgproccnt(0, 1); 313 314 /* Initialize run queues */ 315 sched_init_runqueues(); 316 sleep_queue_init(); 317 clockqueue_init(&curcpu()->ci_queue); 318 sched_init_cpu(curcpu()); 319 p->p_cpu->ci_randseed = (arc4random() & 0x7fffffff) + 1; 320 321 /* Initialize timeouts in process context. */ 322 timeout_proc_init(); 323 324 /* Initialize task queues */ 325 taskq_init(); 326 327 /* Initialize the interface/address trees */ 328 ifinit(); 329 330 /* Lock the kernel on behalf of proc0. */ 331 KERNEL_LOCK(); 332 333 #if NMPATH > 0 334 /* Attach mpath before hardware */ 335 config_rootfound("mpath", NULL); 336 #endif 337 338 /* Configure the devices */ 339 cpu_configure(); 340 341 /* Configure virtual memory system, set vm rlimits. */ 342 uvm_init_limits(&limit0); 343 344 /* Per CPU memory allocation */ 345 percpu_init(); 346 347 /* Initialize the file systems. */ 348 #if defined(NFSSERVER) || defined(NFSCLIENT) 349 nfs_init(); /* initialize server/shared data */ 350 #endif 351 vfsinit(); 352 353 /* Start real time and statistics clocks. */ 354 initclocks(); 355 356 #ifdef SYSVSHM 357 /* Initialize System V style shared memory. */ 358 shminit(); 359 #endif 360 361 #ifdef SYSVSEM 362 /* Initialize System V style semaphores. */ 363 seminit(); 364 #endif 365 366 #ifdef SYSVMSG 367 /* Initialize System V style message queues. */ 368 msginit(); 369 #endif 370 371 /* Create default routing table before attaching lo0. */ 372 rtable_init(); 373 374 /* Attach pseudo-devices. */ 375 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++) 376 if (pdev->pdev_count > 0) 377 (*pdev->pdev_attach)(pdev->pdev_count); 378 #ifdef DIAGNOSTIC 379 pdevinit_done = 1; 380 #endif 381 382 #ifdef CRYPTO 383 crypto_init(); 384 swcr_init(); 385 #endif /* CRYPTO */ 386 387 /* 388 * Initialize protocols. 389 */ 390 domaininit(); 391 392 initconsbuf(); 393 394 #if defined(GPROF) || defined(DDBPROF) 395 /* Initialize kernel profiling. */ 396 prof_init(); 397 #endif 398 399 /* Enable per-CPU data. */ 400 mbcpuinit(); 401 kqueue_init_percpu(); 402 uvm_init_percpu(); 403 evcount_init_percpu(); 404 405 /* init exec */ 406 init_exec(); 407 408 /* Start the scheduler */ 409 scheduler_start(); 410 411 /* 412 * Create process 1 (init(8)). We do this now, as Unix has 413 * historically had init be process 1, and changing this would 414 * probably upset a lot of people. 415 * 416 * Note that process 1 won't immediately exec init(8), but will 417 * wait for us to inform it that the root file system has been 418 * mounted. 419 */ 420 { 421 struct proc *initproc; 422 423 if (fork1(p, FORK_FORK, start_init, NULL, NULL, &initproc)) 424 panic("fork init"); 425 initprocess = initproc->p_p; 426 } 427 428 /* 429 * Create any kernel threads whose creation was deferred because 430 * initprocess had not yet been created. 431 */ 432 kthread_run_deferred_queue(); 433 434 /* 435 * Now that device driver threads have been created, wait for 436 * them to finish any deferred autoconfiguration. Note we don't 437 * need to lock this semaphore, since we haven't booted any 438 * secondary processors, yet. 439 */ 440 while (config_pending) 441 tsleep_nsec(&config_pending, PWAIT, "cfpend", INFSLP); 442 443 dostartuphooks(); 444 445 #if NVSCSI > 0 446 config_rootfound("vscsi", NULL); 447 #endif 448 #if NSOFTRAID > 0 449 config_rootfound("softraid", NULL); 450 #endif 451 452 /* Configure root/swap devices */ 453 diskconf(); 454 455 #ifdef DDB 456 /* Make debug symbols available in ddb. */ 457 db_ctf_init(); 458 #endif 459 460 if (mountroot == NULL || ((*mountroot)() != 0)) 461 panic("cannot mount root"); 462 463 TAILQ_FIRST(&mountlist)->mnt_flag |= MNT_ROOTFS; 464 465 /* Get the vnode for '/'. Set p->p_fd->fd_cdir to reference it. */ 466 if (VFS_ROOT(TAILQ_FIRST(&mountlist), &rootvnode)) 467 panic("cannot find root vnode"); 468 p->p_fd->fd_cdir = rootvnode; 469 vref(p->p_fd->fd_cdir); 470 VOP_UNLOCK(rootvnode); 471 p->p_fd->fd_rdir = NULL; 472 473 /* 474 * Now that root is mounted, we can fixup initprocess's CWD 475 * info. All other processes are kthreads, which merely 476 * share proc0's CWD info. 477 */ 478 initprocess->ps_fd->fd_cdir = rootvnode; 479 vref(initprocess->ps_fd->fd_cdir); 480 initprocess->ps_fd->fd_rdir = NULL; 481 482 /* 483 * Now can look at time, having had a chance to verify the time 484 * from the file system. 485 */ 486 LIST_FOREACH(pr, &allprocess, ps_list) { 487 nanouptime(&pr->ps_start); 488 } 489 nanouptime(&curcpu()->ci_schedstate.spc_runtime); 490 491 uvm_swap_init(); 492 493 /* Create the pageout daemon kernel thread. */ 494 if (kthread_create(uvm_pageout, NULL, NULL, "pagedaemon")) 495 panic("fork pagedaemon"); 496 497 /* Create the reaper daemon kernel thread. */ 498 if (kthread_create(reaper, NULL, &reaperproc, "reaper")) 499 panic("fork reaper"); 500 501 /* Create the cleaner daemon kernel thread. */ 502 if (kthread_create(buf_daemon, NULL, &cleanerproc, "cleaner")) 503 panic("fork cleaner"); 504 505 /* Create the update daemon kernel thread. */ 506 if (kthread_create(syncer_thread, NULL, &syncerproc, "update")) 507 panic("fork update"); 508 509 /* Create the aiodone daemon kernel thread. */ 510 if (kthread_create(uvm_aiodone_daemon, NULL, NULL, "aiodoned")) 511 panic("fork aiodoned"); 512 513 #if !defined(__hppa__) 514 /* Create the page zeroing kernel thread. */ 515 if (kthread_create(uvm_pagezero_thread, NULL, NULL, "zerothread")) 516 panic("fork zerothread"); 517 #endif 518 519 #if defined(MULTIPROCESSOR) 520 /* Boot the secondary processors. */ 521 cpu_boot_secondary_processors(); 522 #endif 523 524 /* Now that all CPUs partake in scheduling, start SMR thread. */ 525 smr_startup_thread(); 526 527 config_process_deferred_mountroot(); 528 529 /* 530 * Okay, now we can let init(8) exec! It's off to userland! 531 */ 532 start_init_exec = 1; 533 wakeup((void *)&start_init_exec); 534 535 /* 536 * Start the idle pool page garbage collector 537 */ 538 #if !(defined(__m88k__) && defined(MULTIPROCESSOR)) /* XXX */ 539 pool_gc_pages(NULL); 540 #endif 541 542 start_periodic_resettodr(); 543 544 /* 545 * proc0: nothing to do, back to sleep 546 */ 547 while (1) 548 tsleep_nsec(&proc0, PVM, "scheduler", INFSLP); 549 /* NOTREACHED */ 550 } 551 552 /* 553 * List of paths to try when searching for "init". 554 */ 555 static char *initpaths[] = { 556 "/sbin/init", 557 "/sbin/oinit", 558 "/sbin/init.bak", 559 NULL, 560 }; 561 562 void 563 check_console(struct proc *p) 564 { 565 struct nameidata nd; 566 int error; 567 568 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", p); 569 error = namei(&nd); 570 if (error) { 571 if (error == ENOENT) 572 printf("warning: /dev/console does not exist\n"); 573 else 574 printf("warning: /dev/console error %d\n", error); 575 } else 576 vrele(nd.ni_vp); 577 } 578 579 /* 580 * Start the initial user process; try exec'ing each pathname in "initpaths". 581 * The program is invoked with one argument containing the boot flags. 582 */ 583 void 584 start_init(void *arg) 585 { 586 struct proc *p = arg; 587 vaddr_t addr; 588 struct sys_execve_args /* { 589 syscallarg(const char *) path; 590 syscallarg(char *const *) argp; 591 syscallarg(char *const *) envp; 592 } */ args; 593 int options, error; 594 long i; 595 register_t retval[2]; 596 char flags[4], *flagsp; 597 char **pathp, *path, *ucp, **uap, *arg0, *arg1 = NULL; 598 599 /* 600 * Now in process 1. 601 */ 602 603 /* 604 * Wait for main() to tell us that it's safe to exec. 605 */ 606 while (start_init_exec == 0) 607 tsleep_nsec(&start_init_exec, PWAIT, "initexec", INFSLP); 608 609 check_console(p); 610 611 /* process 0 ignores SIGCHLD, but we can't */ 612 p->p_p->ps_sigacts->ps_sigflags = 0; 613 614 /* 615 * Need just enough stack to hold the faked-up "execve()" arguments. 616 */ 617 #ifdef MACHINE_STACK_GROWS_UP 618 addr = USRSTACK; 619 #else 620 addr = USRSTACK - PAGE_SIZE; 621 #endif 622 p->p_vmspace->vm_maxsaddr = (caddr_t)addr; 623 p->p_vmspace->vm_minsaddr = (caddr_t)(addr + PAGE_SIZE); 624 if (uvm_map(&p->p_vmspace->vm_map, &addr, PAGE_SIZE, 625 NULL, UVM_UNKNOWN_OFFSET, 0, 626 UVM_MAPFLAG(PROT_READ | PROT_WRITE, PROT_MASK, MAP_INHERIT_COPY, 627 MADV_NORMAL, 628 UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW|UVM_FLAG_STACK|UVM_FLAG_SYSCALL))) 629 panic("init: couldn't allocate argument space"); 630 631 for (pathp = &initpaths[0]; (path = *pathp) != NULL; pathp++) { 632 #ifdef MACHINE_STACK_GROWS_UP 633 ucp = (char *)addr; 634 #else 635 ucp = (char *)(addr + PAGE_SIZE); 636 #endif 637 /* 638 * Construct the boot flag argument. 639 */ 640 flagsp = flags; 641 *flagsp++ = '-'; 642 options = 0; 643 644 if (boothowto & RB_SINGLE) { 645 *flagsp++ = 's'; 646 options = 1; 647 } 648 #ifdef notyet 649 if (boothowto & RB_FASTBOOT) { 650 *flagsp++ = 'f'; 651 options = 1; 652 } 653 #endif 654 655 /* 656 * Move out the flags (arg 1), if necessary. 657 */ 658 if (options != 0) { 659 *flagsp++ = '\0'; 660 i = flagsp - flags; 661 #ifdef DEBUG 662 printf("init: copying out flags `%s' %ld\n", flags, i); 663 #endif 664 #ifdef MACHINE_STACK_GROWS_UP 665 arg1 = ucp; 666 (void)copyout((caddr_t)flags, (caddr_t)ucp, i); 667 ucp += i; 668 #else 669 (void)copyout((caddr_t)flags, (caddr_t)(ucp -= i), i); 670 arg1 = ucp; 671 #endif 672 } 673 674 /* 675 * Move out the file name (also arg 0). 676 */ 677 i = strlen(path) + 1; 678 #ifdef DEBUG 679 printf("init: copying out path `%s' %ld\n", path, i); 680 #endif 681 #ifdef MACHINE_STACK_GROWS_UP 682 arg0 = ucp; 683 (void)copyout((caddr_t)path, (caddr_t)ucp, i); 684 ucp += i; 685 ucp = (caddr_t)ALIGN((u_long)ucp); 686 uap = (char **)ucp + 3; 687 #else 688 (void)copyout((caddr_t)path, (caddr_t)(ucp -= i), i); 689 arg0 = ucp; 690 uap = (char **)((u_long)ucp & ~ALIGNBYTES); 691 #endif 692 693 /* 694 * Move out the arg pointers. 695 */ 696 i = 0; 697 copyout(&i, (caddr_t)--uap, sizeof(register_t)); /* terminator */ 698 if (options != 0) 699 copyout(&arg1, (caddr_t)--uap, sizeof(register_t)); 700 copyout(&arg0, (caddr_t)--uap, sizeof(register_t)); 701 702 /* 703 * Point at the arguments. 704 */ 705 SCARG(&args, path) = arg0; 706 SCARG(&args, argp) = uap; 707 SCARG(&args, envp) = NULL; 708 709 /* 710 * Now try to exec the program. If can't for any reason 711 * other than it doesn't exist, complain. 712 */ 713 if ((error = sys_execve(p, &args, retval)) == EJUSTRETURN) { 714 KERNEL_UNLOCK(); 715 return; 716 } 717 if (error != ENOENT) 718 printf("exec %s: error %d\n", path, error); 719 } 720 printf("init: not found\n"); 721 panic("no init"); 722 } 723