source: rtems-libbsd/freebsd/sys/kern/init_main.c

6-freebsd-12
Last change on this file was c7427fc, checked in by Chris Johns <chrisj@…>, on 07/21/21 at 03:46:45

kern: Add a proc0

  • Provides the thread's proc pointer and with that access to creds

Update #4475

  • Property mode set to 100644
File size: 24.7 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3/*-
4 * SPDX-License-Identifier: BSD-4-Clause
5 *
6 * Copyright (c) 1995 Terrence R. Lambert
7 * All rights reserved.
8 *
9 * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
10 *      The Regents of the University of California.  All rights reserved.
11 * (c) UNIX System Laboratories, Inc.
12 * All or some portions of this file are derived from material licensed
13 * to the University of California by American Telephone and Telegraph
14 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
15 * the permission of UNIX System Laboratories, Inc.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 *    notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 *    notice, this list of conditions and the following disclaimer in the
24 *    documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 *    must display the following acknowledgement:
27 *      This product includes software developed by the University of
28 *      California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 *    may be used to endorse or promote products derived from this software
31 *    without specific prior written permission.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * SUCH DAMAGE.
44 *
45 *      @(#)init_main.c 8.9 (Berkeley) 1/21/94
46 */
47
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD$");
50
51#include <rtems/bsd/local/opt_ddb.h>
52#include <rtems/bsd/local/opt_init_path.h>
53#include <rtems/bsd/local/opt_verbose_sysinit.h>
54
55#include <sys/param.h>
56#include <sys/kernel.h>
57#include <sys/exec.h>
58#include <sys/file.h>
59#include <sys/filedesc.h>
60#include <sys/jail.h>
61#include <sys/ktr.h>
62#include <sys/lock.h>
63#include <sys/loginclass.h>
64#include <sys/mount.h>
65#include <sys/mutex.h>
66#include <sys/syscallsubr.h>
67#include <sys/sysctl.h>
68#include <sys/proc.h>
69#include <sys/racct.h>
70#include <sys/resourcevar.h>
71#include <sys/systm.h>
72#include <sys/signalvar.h>
73#include <sys/vnode.h>
74#include <sys/sysent.h>
75#include <sys/reboot.h>
76#include <sys/sched.h>
77#include <sys/sx.h>
78#include <sys/sysproto.h>
79#include <sys/vmmeter.h>
80#include <rtems/bsd/sys/unistd.h>
81#include <sys/malloc.h>
82#include <sys/conf.h>
83#include <sys/cpuset.h>
84
85#include <machine/cpu.h>
86
87#include <security/audit/audit.h>
88#include <security/mac/mac_framework.h>
89
90#include <vm/vm.h>
91#include <vm/vm_param.h>
92#include <vm/vm_extern.h>
93#include <vm/pmap.h>
94#include <vm/vm_map.h>
95#include <sys/copyright.h>
96
97#include <ddb/ddb.h>
98#include <ddb/db_sym.h>
99
100void mi_startup(void);                          /* Should be elsewhere */
101
102#ifndef __rtems__
103/* Components of the first process -- never freed. */
104static struct session session0;
105static struct pgrp pgrp0;
106#endif /* __rtems__ */
107struct  proc proc0;
108#ifndef __rtems__
109struct thread0_storage thread0_st __aligned(32);
110struct  vmspace vmspace0;
111struct  proc *initproc;
112
113#ifndef BOOTHOWTO
114#define BOOTHOWTO       0
115#endif
116int     boothowto = BOOTHOWTO;  /* initialized so that it can be patched */
117SYSCTL_INT(_debug, OID_AUTO, boothowto, CTLFLAG_RD, &boothowto, 0,
118        "Boot control flags, passed from loader");
119
120#ifndef BOOTVERBOSE
121#define BOOTVERBOSE     0
122#endif
123int     bootverbose = BOOTVERBOSE;
124SYSCTL_INT(_debug, OID_AUTO, bootverbose, CTLFLAG_RW, &bootverbose, 0,
125        "Control the output of verbose kernel messages");
126#endif /* __rtems__ */
127
128#ifdef VERBOSE_SYSINIT
129/*
130 * We'll use the defined value of VERBOSE_SYSINIT from the kernel config to
131 * dictate the default VERBOSE_SYSINIT behavior.  Significant values for this
132 * option and associated tunable are:
133 * - 0, 'compiled in but silent by default'
134 * - 1, 'compiled in but verbose by default' (default)
135 */
136int     verbose_sysinit = VERBOSE_SYSINIT;
137TUNABLE_INT("debug.verbose_sysinit", &verbose_sysinit);
138#endif
139
140#ifndef __rtems__
141#ifdef INVARIANTS
142FEATURE(invariants, "Kernel compiled with INVARIANTS, may affect performance");
143#endif
144
145/*
146 * This ensures that there is at least one entry so that the sysinit_set
147 * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
148 * executed.
149 */
150SYSINIT(placeholder, SI_SUB_DUMMY, SI_ORDER_ANY, NULL, NULL);
151
152/*
153 * The sysinit table itself.  Items are checked off as the are run.
154 * If we want to register new sysinit types, add them to newsysinit.
155 */
156SET_DECLARE(sysinit_set, struct sysinit);
157struct sysinit **sysinit, **sysinit_end;
158struct sysinit **newsysinit, **newsysinit_end;
159
160EVENTHANDLER_LIST_DECLARE(process_init);
161EVENTHANDLER_LIST_DECLARE(thread_init);
162EVENTHANDLER_LIST_DECLARE(process_ctor);
163EVENTHANDLER_LIST_DECLARE(thread_ctor);
164
165/*
166 * Merge a new sysinit set into the current set, reallocating it if
167 * necessary.  This can only be called after malloc is running.
168 */
169void
170sysinit_add(struct sysinit **set, struct sysinit **set_end)
171{
172        struct sysinit **newset;
173        struct sysinit **sipp;
174        struct sysinit **xipp;
175        int count;
176
177        count = set_end - set;
178        if (newsysinit)
179                count += newsysinit_end - newsysinit;
180        else
181                count += sysinit_end - sysinit;
182        newset = malloc(count * sizeof(*sipp), M_TEMP, M_NOWAIT);
183        if (newset == NULL)
184                panic("cannot malloc for sysinit");
185        xipp = newset;
186        if (newsysinit)
187                for (sipp = newsysinit; sipp < newsysinit_end; sipp++)
188                        *xipp++ = *sipp;
189        else
190                for (sipp = sysinit; sipp < sysinit_end; sipp++)
191                        *xipp++ = *sipp;
192        for (sipp = set; sipp < set_end; sipp++)
193                *xipp++ = *sipp;
194        if (newsysinit)
195                free(newsysinit, M_TEMP);
196        newsysinit = newset;
197        newsysinit_end = newset + count;
198}
199#else /* __rtems__ */
200#ifdef BOOTVERBOSE
201int     bootverbose = 1;
202SYSCTL_INT(_debug, OID_AUTO, bootverbose, CTLFLAG_RW, &bootverbose, 0,
203        "Control the output of verbose kernel messages");
204#endif
205RWSET_DECLARE(sysinit_set, struct sysinit);
206#endif /* __rtems__ */
207
208#if defined (DDB) && defined(VERBOSE_SYSINIT)
209static const char *
210symbol_name(vm_offset_t va, db_strategy_t strategy)
211{
212        const char *name;
213        c_db_sym_t sym;
214        db_expr_t  offset;
215
216        if (va == 0)
217                return (NULL);
218        sym = db_search_symbol(va, strategy, &offset);
219        if (offset != 0)
220                return (NULL);
221        db_symbol_values(sym, &name, NULL);
222        return (name);
223}
224#endif
225
226/*
227 * System startup; initialize the world, create process 0, mount root
228 * filesystem, and fork to create init and pagedaemon.  Most of the
229 * hard work is done in the lower-level initialization routines including
230 * startup(), which does memory initialization and autoconfiguration.
231 *
232 * This allows simple addition of new kernel subsystems that require
233 * boot time initialization.  It also allows substitution of subsystem
234 * (for instance, a scheduler, kernel profiler, or VM system) by object
235 * module.  Finally, it allows for optional "kernel threads".
236 */
237void
238mi_startup(void)
239{
240
241        struct sysinit **sipp;  /* system initialization*/
242        struct sysinit **xipp;  /* interior loop of sort*/
243        struct sysinit *save;   /* bubble*/
244#ifdef __rtems__
245        struct sysinit **sysinit = NULL;
246        struct sysinit **sysinit_end = NULL;
247#endif /* __rtems__ */
248
249#if defined(VERBOSE_SYSINIT)
250        int last;
251        int verbose;
252#endif
253
254        TSENTER();
255
256#ifndef __rtems__
257        if (boothowto & RB_VERBOSE)
258                bootverbose++;
259#endif /* __rtems__ */
260
261        if (sysinit == NULL) {
262                sysinit = SET_BEGIN(sysinit_set);
263                sysinit_end = SET_LIMIT(sysinit_set);
264        }
265
266#ifndef __rtems__
267restart:
268#endif /* __rtems__ */
269        /*
270         * Perform a bubble sort of the system initialization objects by
271         * their subsystem (primary key) and order (secondary key).
272         */
273        for (sipp = sysinit; sipp < sysinit_end; sipp++) {
274                for (xipp = sipp + 1; xipp < sysinit_end; xipp++) {
275                        if ((*sipp)->subsystem < (*xipp)->subsystem ||
276                             ((*sipp)->subsystem == (*xipp)->subsystem &&
277                              (*sipp)->order <= (*xipp)->order))
278                                continue;       /* skip*/
279                        save = *sipp;
280                        *sipp = *xipp;
281                        *xipp = save;
282                }
283        }
284
285#if defined(VERBOSE_SYSINIT)
286        last = SI_SUB_COPYRIGHT;
287        verbose = 0;
288#if !defined(DDB)
289        printf("VERBOSE_SYSINIT: DDB not enabled, symbol lookups disabled.\n");
290#endif
291#endif
292
293        /*
294         * Traverse the (now) ordered list of system initialization tasks.
295         * Perform each task, and continue on to the next task.
296         */
297        for (sipp = sysinit; sipp < sysinit_end; sipp++) {
298
299                if ((*sipp)->subsystem == SI_SUB_DUMMY)
300                        continue;       /* skip dummy task(s)*/
301
302                if ((*sipp)->subsystem == SI_SUB_DONE)
303                        continue;
304
305#if defined(VERBOSE_SYSINIT)
306                if ((*sipp)->subsystem > last && verbose_sysinit != 0) {
307                        verbose = 1;
308                        last = (*sipp)->subsystem;
309                        printf("subsystem %x\n", last);
310                }
311                if (verbose) {
312#if defined(DDB)
313                        const char *func, *data;
314
315                        func = symbol_name((vm_offset_t)(*sipp)->func,
316                            DB_STGY_PROC);
317                        data = symbol_name((vm_offset_t)(*sipp)->udata,
318                            DB_STGY_ANY);
319                        if (func != NULL && data != NULL)
320                                printf("   %s(&%s)... ", func, data);
321                        else if (func != NULL)
322                                printf("   %s(%p)... ", func, (*sipp)->udata);
323                        else
324#endif
325                                printf("   %p(%p)... ", (*sipp)->func,
326                                    (*sipp)->udata);
327                }
328#endif
329
330                /* Call function */
331                (*((*sipp)->func))((*sipp)->udata);
332
333#if defined(VERBOSE_SYSINIT)
334                if (verbose)
335                        printf("done.\n");
336#endif
337
338                /* Check off the one we're just done */
339                (*sipp)->subsystem = SI_SUB_DONE;
340
341#ifndef __rtems__
342                /* Check if we've installed more sysinit items via KLD */
343                if (newsysinit != NULL) {
344                        if (sysinit != SET_BEGIN(sysinit_set))
345                                free(sysinit, M_TEMP);
346                        sysinit = newsysinit;
347                        sysinit_end = newsysinit_end;
348                        newsysinit = NULL;
349                        newsysinit_end = NULL;
350                        goto restart;
351                }
352#endif /* __rtems__ */
353        }
354
355        TSEXIT();       /* Here so we don't overlap with start_init. */
356
357#ifndef __rtems__
358        mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
359        mtx_unlock(&Giant);
360#else /* __rtems__ */
361        /* Giant is unlocked in rtems_bsd_timeout_init_late() */
362#endif /* __rtems__ */
363
364#ifndef __rtems__
365        /*
366         * Now hand over this thread to swapper.
367         */
368        swapper();
369        /* NOTREACHED*/
370#endif /* __rtems__ */
371}
372
373#ifndef __rtems__
374static void
375print_caddr_t(void *data)
376{
377        printf("%s", (char *)data);
378}
379
380static void
381print_version(void *data __unused)
382{
383        int len;
384
385        /* Strip a trailing newline from version. */
386        len = strlen(version);
387        while (len > 0 && version[len - 1] == '\n')
388                len--;
389        printf("%.*s %s\n", len, version, machine);
390        printf("%s\n", compiler_version);
391}
392
393SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t,
394    copyright);
395SYSINIT(trademark, SI_SUB_COPYRIGHT, SI_ORDER_SECOND, print_caddr_t,
396    trademark);
397SYSINIT(version, SI_SUB_COPYRIGHT, SI_ORDER_THIRD, print_version, NULL);
398
399#ifdef WITNESS
400static char wit_warn[] =
401     "WARNING: WITNESS option enabled, expect reduced performance.\n";
402SYSINIT(witwarn, SI_SUB_COPYRIGHT, SI_ORDER_THIRD + 1,
403   print_caddr_t, wit_warn);
404SYSINIT(witwarn2, SI_SUB_LAST, SI_ORDER_THIRD + 1,
405   print_caddr_t, wit_warn);
406#endif
407
408#ifdef DIAGNOSTIC
409static char diag_warn[] =
410     "WARNING: DIAGNOSTIC option enabled, expect reduced performance.\n";
411SYSINIT(diagwarn, SI_SUB_COPYRIGHT, SI_ORDER_THIRD + 2,
412    print_caddr_t, diag_warn);
413SYSINIT(diagwarn2, SI_SUB_LAST, SI_ORDER_THIRD + 2,
414    print_caddr_t, diag_warn);
415#endif
416
417static int
418null_fetch_syscall_args(struct thread *td __unused)
419{
420
421        panic("null_fetch_syscall_args");
422}
423
424static void
425null_set_syscall_retval(struct thread *td __unused, int error __unused)
426{
427
428        panic("null_set_syscall_retval");
429}
430
431struct sysentvec null_sysvec = {
432        .sv_size        = 0,
433        .sv_table       = NULL,
434        .sv_mask        = 0,
435        .sv_errsize     = 0,
436        .sv_errtbl      = NULL,
437        .sv_transtrap   = NULL,
438        .sv_fixup       = NULL,
439        .sv_sendsig     = NULL,
440        .sv_sigcode     = NULL,
441        .sv_szsigcode   = NULL,
442        .sv_name        = "null",
443        .sv_coredump    = NULL,
444        .sv_imgact_try  = NULL,
445        .sv_minsigstksz = 0,
446        .sv_minuser     = VM_MIN_ADDRESS,
447        .sv_maxuser     = VM_MAXUSER_ADDRESS,
448        .sv_usrstack    = USRSTACK,
449        .sv_psstrings   = PS_STRINGS,
450        .sv_stackprot   = VM_PROT_ALL,
451        .sv_copyout_strings     = NULL,
452        .sv_setregs     = NULL,
453        .sv_fixlimit    = NULL,
454        .sv_maxssiz     = NULL,
455        .sv_flags       = 0,
456        .sv_set_syscall_retval = null_set_syscall_retval,
457        .sv_fetch_syscall_args = null_fetch_syscall_args,
458        .sv_syscallnames = NULL,
459        .sv_schedtail   = NULL,
460        .sv_thread_detach = NULL,
461        .sv_trap        = NULL,
462};
463
464/*
465 * The two following SYSINIT's are proc0 specific glue code.  I am not
466 * convinced that they can not be safely combined, but their order of
467 * operation has been maintained as the same as the original init_main.c
468 * for right now.
469 */
470/* ARGSUSED*/
471static void
472proc0_init(void *dummy __unused)
473{
474        struct proc *p;
475        struct thread *td;
476        struct ucred *newcred;
477        struct uidinfo tmpuinfo;
478        struct loginclass tmplc = {
479                .lc_name = "",
480        };
481        vm_paddr_t pageablemem;
482        int i;
483
484        GIANT_REQUIRED;
485        p = &proc0;
486        td = &thread0;
487       
488        /*
489         * Initialize magic number and osrel.
490         */
491        p->p_magic = P_MAGIC;
492        p->p_osrel = osreldate;
493
494        /*
495         * Initialize thread and process structures.
496         */
497        procinit();     /* set up proc zone */
498        threadinit();   /* set up UMA zones */
499
500        /*
501         * Initialise scheduler resources.
502         * Add scheduler specific parts to proc, thread as needed.
503         */
504        schedinit();    /* scheduler gets its house in order */
505
506        /*
507         * Create process 0 (the swapper).
508         */
509        LIST_INSERT_HEAD(&allproc, p, p_list);
510        LIST_INSERT_HEAD(PIDHASH(0), p, p_hash);
511        mtx_init(&pgrp0.pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
512        p->p_pgrp = &pgrp0;
513        LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
514        LIST_INIT(&pgrp0.pg_members);
515        LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
516
517        pgrp0.pg_session = &session0;
518        mtx_init(&session0.s_mtx, "session", NULL, MTX_DEF);
519        refcount_init(&session0.s_count, 1);
520        session0.s_leader = p;
521
522        p->p_sysent = &null_sysvec;
523        p->p_flag = P_SYSTEM | P_INMEM | P_KPROC;
524        p->p_flag2 = 0;
525        p->p_state = PRS_NORMAL;
526        p->p_klist = knlist_alloc(&p->p_mtx);
527        STAILQ_INIT(&p->p_ktr);
528        p->p_nice = NZERO;
529        /* pid_max cannot be greater than PID_MAX */
530        td->td_tid = PID_MAX + 1;
531        LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
532        td->td_state = TDS_RUNNING;
533        td->td_pri_class = PRI_TIMESHARE;
534        td->td_user_pri = PUSER;
535        td->td_base_user_pri = PUSER;
536        td->td_lend_user_pri = PRI_MAX;
537        td->td_priority = PVM;
538        td->td_base_pri = PVM;
539        td->td_oncpu = curcpu;
540        td->td_flags = TDF_INMEM;
541        td->td_pflags = TDP_KTHREAD;
542        td->td_cpuset = cpuset_thread0();
543        td->td_domain.dr_policy = td->td_cpuset->cs_domain;
544        prison0_init();
545        p->p_peers = 0;
546        p->p_leader = p;
547        p->p_reaper = p;
548        p->p_treeflag |= P_TREE_REAPER;
549        LIST_INIT(&p->p_reaplist);
550
551        strncpy(p->p_comm, "kernel", sizeof (p->p_comm));
552        strncpy(td->td_name, "swapper", sizeof (td->td_name));
553
554        callout_init_mtx(&p->p_itcallout, &p->p_mtx, 0);
555        callout_init_mtx(&p->p_limco, &p->p_mtx, 0);
556        callout_init(&td->td_slpcallout, 1);
557
558        /* Create credentials. */
559        newcred = crget();
560        newcred->cr_ngroups = 1;        /* group 0 */
561        /* A hack to prevent uifind from tripping over NULL pointers. */
562        curthread->td_ucred = newcred;
563        tmpuinfo.ui_uid = 1;
564        newcred->cr_uidinfo = newcred->cr_ruidinfo = &tmpuinfo;
565        newcred->cr_uidinfo = uifind(0);
566        newcred->cr_ruidinfo = uifind(0);
567        newcred->cr_loginclass = &tmplc;
568        newcred->cr_loginclass = loginclass_find("default");
569        /* End hack. creds get properly set later with thread_cow_get_proc */
570        curthread->td_ucred = NULL;
571        newcred->cr_prison = &prison0;
572        proc_set_cred_init(p, newcred);
573#ifdef AUDIT
574        audit_cred_kproc0(newcred);
575#endif
576#ifdef MAC
577        mac_cred_create_swapper(newcred);
578#endif
579        /* Create sigacts. */
580        p->p_sigacts = sigacts_alloc();
581
582        /* Initialize signal state for process 0. */
583        siginit(&proc0);
584
585        /* Create the file descriptor table. */
586        p->p_fd = fdinit(NULL, false);
587        p->p_fdtol = NULL;
588
589        /* Create the limits structures. */
590        p->p_limit = lim_alloc();
591        for (i = 0; i < RLIM_NLIMITS; i++)
592                p->p_limit->pl_rlimit[i].rlim_cur =
593                    p->p_limit->pl_rlimit[i].rlim_max = RLIM_INFINITY;
594        p->p_limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur =
595            p->p_limit->pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
596        p->p_limit->pl_rlimit[RLIMIT_NPROC].rlim_cur =
597            p->p_limit->pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
598        p->p_limit->pl_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
599        p->p_limit->pl_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
600        p->p_limit->pl_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
601        p->p_limit->pl_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
602        /* Cast to avoid overflow on i386/PAE. */
603        pageablemem = ptoa((vm_paddr_t)vm_free_count());
604        p->p_limit->pl_rlimit[RLIMIT_RSS].rlim_cur =
605            p->p_limit->pl_rlimit[RLIMIT_RSS].rlim_max = pageablemem;
606        p->p_limit->pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = pageablemem / 3;
607        p->p_limit->pl_rlimit[RLIMIT_MEMLOCK].rlim_max = pageablemem;
608        p->p_cpulimit = RLIM_INFINITY;
609
610        PROC_LOCK(p);
611        thread_cow_get_proc(td, p);
612        PROC_UNLOCK(p);
613
614        /* Initialize resource accounting structures. */
615        racct_create(&p->p_racct);
616
617        p->p_stats = pstats_alloc();
618
619        /* Allocate a prototype map so we have something to fork. */
620        p->p_vmspace = &vmspace0;
621        vmspace0.vm_refcnt = 1;
622        pmap_pinit0(vmspace_pmap(&vmspace0));
623
624        /*
625         * proc0 is not expected to enter usermode, so there is no special
626         * handling for sv_minuser here, like is done for exec_new_vmspace().
627         */
628        vm_map_init(&vmspace0.vm_map, vmspace_pmap(&vmspace0),
629            p->p_sysent->sv_minuser, p->p_sysent->sv_maxuser);
630
631        /*
632         * Call the init and ctor for the new thread and proc.  We wait
633         * to do this until all other structures are fairly sane.
634         */
635        EVENTHANDLER_DIRECT_INVOKE(process_init, p);
636        EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
637        EVENTHANDLER_DIRECT_INVOKE(process_ctor, p);
638        EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
639
640        /*
641         * Charge root for one process.
642         */
643        (void)chgproccnt(p->p_ucred->cr_ruidinfo, 1, 0);
644        PROC_LOCK(p);
645        racct_add_force(p, RACCT_NPROC, 1);
646        PROC_UNLOCK(p);
647}
648SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL);
649
650/* ARGSUSED*/
651static void
652proc0_post(void *dummy __unused)
653{
654        struct timespec ts;
655        struct proc *p;
656        struct rusage ru;
657        struct thread *td;
658
659        /*
660         * Now we can look at the time, having had a chance to verify the
661         * time from the filesystem.  Pretend that proc0 started now.
662         */
663        sx_slock(&allproc_lock);
664        FOREACH_PROC_IN_SYSTEM(p) {
665                PROC_LOCK(p);
666                if (p->p_state == PRS_NEW) {
667                        PROC_UNLOCK(p);
668                        continue;
669                }
670                microuptime(&p->p_stats->p_start);
671                PROC_STATLOCK(p);
672                rufetch(p, &ru);        /* Clears thread stats */
673                p->p_rux.rux_runtime = 0;
674                p->p_rux.rux_uticks = 0;
675                p->p_rux.rux_sticks = 0;
676                p->p_rux.rux_iticks = 0;
677                PROC_STATUNLOCK(p);
678                FOREACH_THREAD_IN_PROC(p, td) {
679                        td->td_runtime = 0;
680                }
681                PROC_UNLOCK(p);
682        }
683        sx_sunlock(&allproc_lock);
684        PCPU_SET(switchtime, cpu_ticks());
685        PCPU_SET(switchticks, ticks);
686
687        /*
688         * Give the ``random'' number generator a thump.
689         */
690        nanotime(&ts);
691        srandom(ts.tv_sec ^ ts.tv_nsec);
692}
693SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL);
694
695static void
696random_init(void *dummy __unused)
697{
698
699        /*
700         * After CPU has been started we have some randomness on most
701         * platforms via get_cyclecount().  For platforms that don't
702         * we will reseed random(9) in proc0_post() as well.
703         */
704        srandom(get_cyclecount());
705}
706SYSINIT(random, SI_SUB_RANDOM, SI_ORDER_FIRST, random_init, NULL);
707
708/*
709 ***************************************************************************
710 ****
711 **** The following SYSINIT's and glue code should be moved to the
712 **** respective files on a per subsystem basis.
713 ****
714 ***************************************************************************
715 */
716
717/*
718 * List of paths to try when searching for "init".
719 */
720static char init_path[MAXPATHLEN] =
721#ifdef  INIT_PATH
722    __XSTRING(INIT_PATH);
723#else
724    "/sbin/init:/sbin/oinit:/sbin/init.bak:/rescue/init";
725#endif
726SYSCTL_STRING(_kern, OID_AUTO, init_path, CTLFLAG_RD, init_path, 0,
727        "Path used to search the init process");
728
729/*
730 * Shutdown timeout of init(8).
731 * Unused within kernel, but used to control init(8), hence do not remove.
732 */
733#ifndef INIT_SHUTDOWN_TIMEOUT
734#define INIT_SHUTDOWN_TIMEOUT 120
735#endif
736static int init_shutdown_timeout = INIT_SHUTDOWN_TIMEOUT;
737SYSCTL_INT(_kern, OID_AUTO, init_shutdown_timeout,
738        CTLFLAG_RW, &init_shutdown_timeout, 0, "Shutdown timeout of init(8). "
739        "Unused within kernel, but used to control init(8)");
740
741/*
742 * Start the initial user process; try exec'ing each pathname in init_path.
743 * The program is invoked with one argument containing the boot flags.
744 */
745static void
746start_init(void *dummy)
747{
748        vm_offset_t addr;
749        struct execve_args args;
750        int options, error;
751        size_t pathlen;
752        char *var, *path;
753        char *free_init_path, *tmp_init_path;
754        char *ucp, **uap, *arg0, *arg1;
755        struct thread *td;
756        struct proc *p;
757
758        TSENTER();      /* Here so we don't overlap with mi_startup. */
759
760        td = curthread;
761        p = td->td_proc;
762
763        vfs_mountroot();
764
765        /* Wipe GELI passphrase from the environment. */
766        kern_unsetenv("kern.geom.eli.passphrase");
767
768        /*
769         * Need just enough stack to hold the faked-up "execve()" arguments.
770         */
771        addr = p->p_sysent->sv_usrstack - PAGE_SIZE;
772        if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE, 0,
773            VMFS_NO_SPACE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
774                panic("init: couldn't allocate argument space");
775        p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
776        p->p_vmspace->vm_ssize = 1;
777
778        if ((var = kern_getenv("init_path")) != NULL) {
779                strlcpy(init_path, var, sizeof(init_path));
780                freeenv(var);
781        }
782        free_init_path = tmp_init_path = strdup(init_path, M_TEMP);
783       
784        while ((path = strsep(&tmp_init_path, ":")) != NULL) {
785                pathlen = strlen(path) + 1;
786                if (bootverbose)
787                        printf("start_init: trying %s\n", path);
788                       
789                /*
790                 * Move out the boot flag argument.
791                 */
792                options = 0;
793                ucp = (char *)p->p_sysent->sv_usrstack;
794                (void)subyte(--ucp, 0);         /* trailing zero */
795                if (boothowto & RB_SINGLE) {
796                        (void)subyte(--ucp, 's');
797                        options = 1;
798                }
799#ifdef notyet
800                if (boothowto & RB_FASTBOOT) {
801                        (void)subyte(--ucp, 'f');
802                        options = 1;
803                }
804#endif
805
806#ifdef BOOTCDROM
807                (void)subyte(--ucp, 'C');
808                options = 1;
809#endif
810
811                if (options == 0)
812                        (void)subyte(--ucp, '-');
813                (void)subyte(--ucp, '-');               /* leading hyphen */
814                arg1 = ucp;
815
816                /*
817                 * Move out the file name (also arg 0).
818                 */
819                ucp -= pathlen;
820                copyout(path, ucp, pathlen);
821                arg0 = ucp;
822
823                /*
824                 * Move out the arg pointers.
825                 */
826                uap = (char **)rounddown2((intptr_t)ucp, sizeof(intptr_t));
827                (void)suword((caddr_t)--uap, (long)0);  /* terminator */
828                (void)suword((caddr_t)--uap, (long)(intptr_t)arg1);
829                (void)suword((caddr_t)--uap, (long)(intptr_t)arg0);
830
831                /*
832                 * Point at the arguments.
833                 */
834                args.fname = arg0;
835                args.argv = uap;
836                args.envv = NULL;
837
838                /*
839                 * Now try to exec the program.  If can't for any reason
840                 * other than it doesn't exist, complain.
841                 *
842                 * Otherwise, return via fork_trampoline() all the way
843                 * to user mode as init!
844                 */
845                if ((error = sys_execve(td, &args)) == EJUSTRETURN) {
846                        free(free_init_path, M_TEMP);
847                        TSEXIT();
848                        return;
849                }
850                if (error != ENOENT)
851                        printf("exec %s: error %d\n", path, error);
852        }
853        free(free_init_path, M_TEMP);
854        printf("init: not found in path %s\n", init_path);
855        panic("no init");
856}
857
858/*
859 * Like kproc_create(), but runs in its own address space.  We do this
860 * early to reserve pid 1.  Note special case - do not make it
861 * runnable yet, init execution is started when userspace can be served.
862 */
863static void
864create_init(const void *udata __unused)
865{
866        struct fork_req fr;
867        struct ucred *newcred, *oldcred;
868        struct thread *td;
869        int error;
870
871        bzero(&fr, sizeof(fr));
872        fr.fr_flags = RFFDG | RFPROC | RFSTOPPED;
873        fr.fr_procp = &initproc;
874        error = fork1(&thread0, &fr);
875        if (error)
876                panic("cannot fork init: %d\n", error);
877        KASSERT(initproc->p_pid == 1, ("create_init: initproc->p_pid != 1"));
878        /* divorce init's credentials from the kernel's */
879        newcred = crget();
880        sx_xlock(&proctree_lock);
881        PROC_LOCK(initproc);
882        initproc->p_flag |= P_SYSTEM | P_INMEM;
883        initproc->p_treeflag |= P_TREE_REAPER;
884        oldcred = initproc->p_ucred;
885        crcopy(newcred, oldcred);
886#ifdef MAC
887        mac_cred_create_init(newcred);
888#endif
889#ifdef AUDIT
890        audit_cred_proc1(newcred);
891#endif
892        proc_set_cred(initproc, newcred);
893        td = FIRST_THREAD_IN_PROC(initproc);
894        crfree(td->td_ucred);
895        td->td_ucred = crhold(initproc->p_ucred);
896        PROC_UNLOCK(initproc);
897        sx_xunlock(&proctree_lock);
898        crfree(oldcred);
899        cpu_fork_kthread_handler(FIRST_THREAD_IN_PROC(initproc),
900            start_init, NULL);
901}
902SYSINIT(init, SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL);
903
904/*
905 * Make it runnable now.
906 */
907static void
908kick_init(const void *udata __unused)
909{
910        struct thread *td;
911
912        td = FIRST_THREAD_IN_PROC(initproc);
913        thread_lock(td);
914        TD_SET_CAN_RUN(td);
915        sched_add(td, SRQ_BORING);
916        thread_unlock(td);
917}
918SYSINIT(kickinit, SI_SUB_KTHREAD_INIT, SI_ORDER_MIDDLE, kick_init, NULL);
919#endif /* __rtems__ */
Note: See TracBrowser for help on using the repository browser.