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

55-freebsd-126-freebsd-12
Last change on this file since 3489e3b was 3489e3b, checked in by Sebastian Huber <sebastian.huber@…>, on 08/22/18 at 12:59:50

Update to FreeBSD head 2018-09-17

Git mirror commit 6c2192b1ef8c50788c751f878552526800b1e319.

Update #3472.

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