Replace the linear search in file descriptor allocation with an O(log N)
[dragonfly.git] / sys / kern / init_main.c
1 /*
2  * Copyright (c) 1995 Terrence R. Lambert
3  * All rights reserved.
4  *
5  * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
6  *      The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *      @(#)init_main.c 8.9 (Berkeley) 1/21/94
42  * $FreeBSD: src/sys/kern/init_main.c,v 1.134.2.8 2003/06/06 20:21:32 tegge Exp $
43  * $DragonFly: src/sys/kern/init_main.c,v 1.43 2005/06/21 23:58:53 hsu Exp $
44  */
45
46 #include "opt_init_path.h"
47
48 #include <sys/param.h>
49 #include <sys/file.h>
50 #include <sys/filedesc.h>
51 #include <sys/kernel.h>
52 #include <sys/mount.h>
53 #include <sys/sysctl.h>
54 #include <sys/proc.h>
55 #include <sys/resourcevar.h>
56 #include <sys/signalvar.h>
57 #include <sys/systm.h>
58 #include <sys/vnode.h>
59 #include <sys/sysent.h>
60 #include <sys/reboot.h>
61 #include <sys/sysproto.h>
62 #include <sys/vmmeter.h>
63 #include <sys/unistd.h>
64 #include <sys/malloc.h>
65 #include <sys/file2.h>
66 #include <sys/thread2.h>
67
68 #include <machine/cpu.h>
69
70 #include <vm/vm.h>
71 #include <vm/vm_param.h>
72 #include <sys/lock.h>
73 #include <vm/pmap.h>
74 #include <vm/vm_map.h>
75 #include <sys/user.h>
76 #include <sys/copyright.h>
77
78 void mi_startup(void);                          /* Should be elsewhere */
79
80 /* Components of the first process -- never freed. */
81 static struct session session0;
82 static struct pgrp pgrp0;
83 static struct procsig procsig0;
84 static struct filedesc0 filedesc0;
85 static struct plimit limit0;
86 static struct vmspace vmspace0;
87 struct proc *initproc;
88 struct proc proc0;
89 struct thread thread0;
90
91 int cmask = CMASK;
92 extern  struct user *proc0paddr;
93 extern int fallback_elf_brand;
94
95 int     boothowto = 0;          /* initialized so that it can be patched */
96 SYSCTL_INT(_debug, OID_AUTO, boothowto, CTLFLAG_RD, &boothowto, 0, "");
97
98 /*
99  * This ensures that there is at least one entry so that the sysinit_set
100  * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
101  * executed.
102  */
103 SYSINIT(placeholder, SI_SUB_DUMMY, SI_ORDER_ANY, NULL, NULL)
104
105 /*
106  * The sysinit table itself.  Items are checked off as the are run.
107  * If we want to register new sysinit types, add them to newsysinit.
108  */
109 SET_DECLARE(sysinit_set, struct sysinit);
110 struct sysinit **sysinit, **sysinit_end;
111 struct sysinit **newsysinit, **newsysinit_end;
112
113
114 /*
115  * Merge a new sysinit set into the current set, reallocating it if
116  * necessary.  This can only be called after malloc is running.
117  */
118 void
119 sysinit_add(struct sysinit **set, struct sysinit **set_end)
120 {
121         struct sysinit **newset;
122         struct sysinit **sipp;
123         struct sysinit **xipp;
124         int count;
125
126         count = set_end - set;
127         if (newsysinit)
128                 count += newsysinit_end - newsysinit;
129         else
130                 count += sysinit_end - sysinit;
131         newset = malloc(count * sizeof(*sipp), M_TEMP, M_WAITOK);
132         if (newset == NULL)
133                 panic("cannot malloc for sysinit");
134         xipp = newset;
135         if (newsysinit) {
136                 for (sipp = newsysinit; sipp < newsysinit_end; sipp++)
137                         *xipp++ = *sipp;
138         } else {
139                 for (sipp = sysinit; sipp < sysinit_end; sipp++)
140                         *xipp++ = *sipp;
141         }
142         for (sipp = set; sipp < set_end; sipp++)
143                 *xipp++ = *sipp;
144         if (newsysinit)
145                 free(newsysinit, M_TEMP);
146         newsysinit = newset;
147         newsysinit_end = newset + count;
148 }
149
150 /*
151  * System startup; initialize the world, create process 0, mount root
152  * filesystem, and fork to create init and pagedaemon.  Most of the
153  * hard work is done in the lower-level initialization routines including
154  * startup(), which does memory initialization and autoconfiguration.
155  *
156  * This allows simple addition of new kernel subsystems that require
157  * boot time initialization.  It also allows substitution of subsystem
158  * (for instance, a scheduler, kernel profiler, or VM system) by object
159  * module.  Finally, it allows for optional "kernel threads".
160  */
161 void
162 mi_startup(void)
163 {
164         struct sysinit *sip;            /* system initialization*/
165         struct sysinit **sipp;          /* system initialization*/
166         struct sysinit **xipp;          /* interior loop of sort*/
167         struct sysinit *save;           /* bubble*/
168
169         if (sysinit == NULL) {
170                 sysinit = SET_BEGIN(sysinit_set);
171                 sysinit_end = SET_LIMIT(sysinit_set);
172         }
173
174 restart:
175         /*
176          * Perform a bubble sort of the system initialization objects by
177          * their subsystem (primary key) and order (secondary key).
178          */
179         for (sipp = sysinit; sipp < sysinit_end; sipp++) {
180                 for (xipp = sipp + 1; xipp < sysinit_end; xipp++) {
181                         if ((*sipp)->subsystem < (*xipp)->subsystem ||
182                              ((*sipp)->subsystem == (*xipp)->subsystem &&
183                               (*sipp)->order <= (*xipp)->order))
184                                 continue;       /* skip*/
185                         save = *sipp;
186                         *sipp = *xipp;
187                         *xipp = save;
188                 }
189         }
190
191         /*
192          * Traverse the (now) ordered list of system initialization tasks.
193          * Perform each task, and continue on to the next task.
194          *
195          * The last item on the list is expected to be the scheduler,
196          * which will not return.
197          */
198         for (sipp = sysinit; sipp < sysinit_end; sipp++) {
199                 sip = *sipp;
200                 if (sip->subsystem == SI_SUB_DUMMY)
201                         continue;       /* skip dummy task(s)*/
202
203                 if (sip->subsystem == SI_SUB_DONE)
204                         continue;
205
206                 /* Call function */
207                 (*(sip->func))(sip->udata);
208
209                 /* Check off the one we're just done */
210                 sip->subsystem = SI_SUB_DONE;
211
212                 /* Check if we've installed more sysinit items via KLD */
213                 if (newsysinit != NULL) {
214                         if (sysinit != SET_BEGIN(sysinit_set))
215                                 free(sysinit, M_TEMP);
216                         sysinit = newsysinit;
217                         sysinit_end = newsysinit_end;
218                         newsysinit = NULL;
219                         newsysinit_end = NULL;
220                         goto restart;
221                 }
222         }
223
224         panic("Shouldn't get here!");
225         /* NOTREACHED*/
226 }
227
228
229 /*
230  ***************************************************************************
231  ****
232  **** The following SYSINIT's belong elsewhere, but have not yet
233  **** been moved.
234  ****
235  ***************************************************************************
236  */
237 static void
238 print_caddr_t(void *data __unused)
239 {
240         printf("%s", (char *)data);
241 }
242 SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t, copyright)
243
244 /*
245  * Leave the critical section that protected us from spurious interrupts
246  * so device probes work.
247  */
248 static void
249 leavecrit(void *dummy __unused)
250 {
251         crit_exit();
252         KKASSERT(!IN_CRITICAL_SECT(curthread));
253         if (bootverbose)
254                 printf("Leaving critical section, allowing interrupts\n");
255 }
256 SYSINIT(leavecrit, SI_SUB_LEAVE_CRIT, SI_ORDER_ANY, leavecrit, NULL)
257
258 /*
259  ***************************************************************************
260  ****
261  **** The two following SYSINT's are proc0 specific glue code.  I am not
262  **** convinced that they can not be safely combined, but their order of
263  **** operation has been maintained as the same as the original init_main.c
264  **** for right now.
265  ****
266  **** These probably belong in init_proc.c or kern_proc.c, since they
267  **** deal with proc0 (the fork template process).
268  ****
269  ***************************************************************************
270  */
271 /* ARGSUSED*/
272 static void
273 proc0_init(void *dummy __unused)
274 {
275         struct proc             *p;
276         struct filedesc0        *fdp;
277         unsigned i;
278
279         p = &proc0;
280
281         /*
282          * Initialize process and pgrp structures.
283          */
284         procinit();
285
286         /*
287          * Initialize sleep queue hash table
288          */
289         sleepinit();
290
291         /*
292          * additional VM structures
293          */
294         vm_init2();
295
296         /*
297          * Create process 0 (the swapper).
298          */
299         LIST_INSERT_HEAD(&allproc, p, p_list);
300         p->p_pgrp = &pgrp0;
301         LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
302         LIST_INIT(&pgrp0.pg_members);
303         LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
304
305         pgrp0.pg_session = &session0;
306         session0.s_count = 1;
307         session0.s_leader = p;
308
309         p->p_sysent = &aout_sysvec;
310         TAILQ_INIT(&p->p_sysmsgq);
311
312         p->p_flag = P_INMEM | P_SYSTEM;
313         p->p_stat = SRUN;
314         p->p_nice = NZERO;
315         p->p_rtprio.type = RTP_PRIO_NORMAL;
316         p->p_rtprio.prio = 0;
317
318         p->p_peers = 0;
319         p->p_leader = p;
320
321         bcopy("swapper", p->p_comm, sizeof ("swapper"));
322
323         /* Create credentials. */
324         p->p_ucred = crget();
325         p->p_ucred->cr_ruidinfo = uifind(0);
326         p->p_ucred->cr_ngroups = 1;     /* group 0 */
327         p->p_ucred->cr_uidinfo = uifind(0);
328
329         /* Don't jail it */
330         p->p_ucred->cr_prison = NULL;
331
332         /* Create procsig. */
333         p->p_procsig = &procsig0;
334         p->p_procsig->ps_refcnt = 1;
335
336         /* Initialize signal state for process 0. */
337         siginit(&proc0);
338
339         /* Create the file descriptor table. */
340         fdp = &filedesc0;
341         p->p_fd = &fdp->fd_fd;
342         p->p_fdtol = NULL;
343         fdp->fd_fd.fd_refcnt = 1;
344         fdp->fd_fd.fd_cmask = cmask;
345         fdp->fd_fd.fd_ofiles = fdp->fd_dfiles;
346         fdp->fd_fd.fd_ofileflags = fdp->fd_dfileflags;
347         fdp->fd_fd.fd_oallocated = fdp->fd_dallocated;
348         fdp->fd_fd.fd_nfiles = NDFILE;
349
350         /* Create the limits structures. */
351         p->p_limit = &limit0;
352         for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
353                 limit0.pl_rlimit[i].rlim_cur =
354                     limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
355         limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
356             limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
357         limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
358             limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
359         i = ptoa(vmstats.v_free_count);
360         limit0.pl_rlimit[RLIMIT_RSS].rlim_max = i;
361         limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = i;
362         limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = i / 3;
363         limit0.p_cpulimit = RLIM_INFINITY;
364         limit0.p_refcnt = 1;
365
366         /* Allocate a prototype map so we have something to fork. */
367         pmap_pinit0(vmspace_pmap(&vmspace0));
368         p->p_vmspace = &vmspace0;
369         vmspace0.vm_refcnt = 1;
370         vm_map_init(&vmspace0.vm_map, round_page(VM_MIN_ADDRESS),
371             trunc_page(VM_MAXUSER_ADDRESS));
372         vmspace0.vm_map.pmap = vmspace_pmap(&vmspace0);
373
374         /*
375          * We continue to place resource usage info and signal
376          * actions in the user struct so they're pageable.
377          */
378         p->p_stats = &p->p_addr->u_stats;
379         p->p_sigacts = &p->p_addr->u_sigacts;
380
381         /*
382          * Charge root for one process.
383          */
384         (void)chgproccnt(p->p_ucred->cr_uidinfo, 1, 0);
385
386 }
387 SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL)
388
389 /* ARGSUSED*/
390 static void
391 proc0_post(void *dummy __unused)
392 {
393         struct timespec ts;
394         struct proc *p;
395
396         /*
397          * Now we can look at the time, having had a chance to verify the
398          * time from the file system.  Pretend that proc0 started now.
399          */
400         FOREACH_PROC_IN_SYSTEM(p) {
401                 microtime(&p->p_thread->td_start);
402         }
403
404         /*
405          * Give the ``random'' number generator a thump.
406          * XXX: Does read_random() contain enough bits to be used here ?
407          */
408         nanotime(&ts);
409         srandom(ts.tv_sec ^ ts.tv_nsec);
410 }
411 SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL)
412
413 /*
414  ***************************************************************************
415  ****
416  **** The following SYSINIT's and glue code should be moved to the
417  **** respective files on a per subsystem basis.
418  ****
419  ***************************************************************************
420  */
421
422
423 /*
424  ***************************************************************************
425  ****
426  **** The following code probably belongs in another file, like
427  **** kern/init_init.c.
428  ****
429  ***************************************************************************
430  */
431
432 /*
433  * List of paths to try when searching for "init".
434  */
435 static char init_path[MAXPATHLEN] =
436 #ifdef  INIT_PATH
437     __XSTRING(INIT_PATH);
438 #else
439     "/sbin/init:/sbin/oinit:/sbin/init.bak:/stand/sysinstall";
440 #endif
441 SYSCTL_STRING(_kern, OID_AUTO, init_path, CTLFLAG_RD, init_path, 0, "");
442
443 /*
444  * Start the initial user process; try exec'ing each pathname in init_path.
445  * The program is invoked with one argument containing the boot flags.
446  *
447  * The MP lock is held on entry.
448  */
449 static void
450 start_init(void *dummy)
451 {
452         vm_offset_t addr;
453         struct execve_args args;
454         int options, error;
455         char *var, *path, *next, *s;
456         char *ucp, **uap, *arg0, *arg1;
457         struct proc *p;
458         struct mount *mp;
459         struct vnode *vp;
460
461         p = curproc;
462
463         /* Get the vnode for '/'.  Set p->p_fd->fd_cdir to reference it. */
464         mp = mountlist_boot_getfirst();
465         if (VFS_ROOT(mp, &vp))
466                 panic("cannot find root vnode");
467         if (mp->mnt_ncp == NULL) {
468                 mp->mnt_ncp = cache_allocroot(mp, vp);
469                 cache_unlock(mp->mnt_ncp);      /* leave ref intact */
470         }
471         p->p_fd->fd_cdir = vp;
472         vref(p->p_fd->fd_cdir);
473         p->p_fd->fd_rdir = vp;
474         vref(p->p_fd->fd_rdir);
475         vfs_cache_setroot(vp, cache_hold(mp->mnt_ncp));
476         VOP_UNLOCK(vp, 0, curthread); /* leave ref intact */
477         p->p_fd->fd_ncdir = cache_hold(mp->mnt_ncp);
478         p->p_fd->fd_nrdir = cache_hold(mp->mnt_ncp);
479
480         /*
481          * Need just enough stack to hold the faked-up "execve()" arguments.
482          */
483         addr = trunc_page(USRSTACK - PAGE_SIZE);
484         if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE,
485                         FALSE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
486                 panic("init: couldn't allocate argument space");
487         p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
488         p->p_vmspace->vm_ssize = 1;
489
490         if ((var = getenv("init_path")) != NULL) {
491                 strncpy(init_path, var, sizeof init_path);
492                 init_path[sizeof init_path - 1] = 0;
493         }
494         if ((var = getenv("kern.fallback_elf_brand")) != NULL)
495                 fallback_elf_brand = strtol(var, NULL, 0);
496         
497         for (path = init_path; *path != '\0'; path = next) {
498                 while (*path == ':')
499                         path++;
500                 if (*path == '\0')
501                         break;
502                 for (next = path; *next != '\0' && *next != ':'; next++)
503                         /* nothing */ ;
504                 if (bootverbose)
505                         printf("start_init: trying %.*s\n", (int)(next - path),
506                             path);
507                         
508                 /*
509                  * Move out the boot flag argument.
510                  */
511                 options = 0;
512                 ucp = (char *)USRSTACK;
513                 (void)subyte(--ucp, 0);         /* trailing zero */
514                 if (boothowto & RB_SINGLE) {
515                         (void)subyte(--ucp, 's');
516                         options = 1;
517                 }
518 #ifdef notyet
519                 if (boothowto & RB_FASTBOOT) {
520                         (void)subyte(--ucp, 'f');
521                         options = 1;
522                 }
523 #endif
524
525 #ifdef BOOTCDROM
526                 (void)subyte(--ucp, 'C');
527                 options = 1;
528 #endif
529                 if (options == 0)
530                         (void)subyte(--ucp, '-');
531                 (void)subyte(--ucp, '-');               /* leading hyphen */
532                 arg1 = ucp;
533
534                 /*
535                  * Move out the file name (also arg 0).
536                  */
537                 (void)subyte(--ucp, 0);
538                 for (s = next - 1; s >= path; s--)
539                         (void)subyte(--ucp, *s);
540                 arg0 = ucp;
541
542                 /*
543                  * Move out the arg pointers.
544                  */
545                 uap = (char **)((intptr_t)ucp & ~(sizeof(intptr_t)-1));
546                 (void)suword((caddr_t)--uap, (long)0);  /* terminator */
547                 (void)suword((caddr_t)--uap, (long)(intptr_t)arg1);
548                 (void)suword((caddr_t)--uap, (long)(intptr_t)arg0);
549
550                 /*
551                  * Point at the arguments.
552                  */
553                 args.fname = arg0;
554                 args.argv = uap;
555                 args.envv = NULL;
556
557                 /*
558                  * Now try to exec the program.  If can't for any reason
559                  * other than it doesn't exist, complain.
560                  *
561                  * Otherwise, return via fork_trampoline() all the way
562                  * to user mode as init!
563                  *
564                  * WARNING!  We may have been moved to another cpu after
565                  * acquiring the current user process designation.  The
566                  * MP lock will migrate with us though so we still have to
567                  * release it.
568                  */
569                 if ((error = execve(&args)) == 0) {
570                         if (p->p_thread->td_gd->gd_uschedcp != p)
571                                 acquire_curproc(p);
572                         rel_mplock();
573                         return;
574                 }
575                 if (error != ENOENT)
576                         printf("exec %.*s: error %d\n", (int)(next - path), 
577                             path, error);
578         }
579         printf("init: not found in path %s\n", init_path);
580         panic("no init");
581 }
582
583 /*
584  * Like kthread_create(), but runs in it's own address space.
585  * We do this early to reserve pid 1.
586  *
587  * Note special case - do not make it runnable yet.  Other work
588  * in progress will change this more.
589  */
590 static void
591 create_init(const void *udata __unused)
592 {
593         int error;
594
595         crit_enter();
596         error = fork1(&proc0, RFFDG | RFPROC, &initproc);
597         if (error)
598                 panic("cannot fork init: %d", error);
599         initproc->p_flag |= P_INMEM | P_SYSTEM;
600         cpu_set_fork_handler(initproc, start_init, NULL);
601         crit_exit();
602 }
603 SYSINIT(init,SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL)
604
605 /*
606  * Make it runnable now.
607  */
608 static void
609 kick_init(const void *udata __unused)
610 {
611         start_forked_proc(&proc0, initproc);
612 }
613 SYSINIT(kickinit,SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST, kick_init, NULL)
614
615 /*
616  * Machine independant globaldata initialization
617  *
618  * WARNING!  Called from early boot, 'mycpu' may not work yet.
619  */
620 void
621 mi_gdinit(struct globaldata *gd, int cpuid)
622 {
623         TAILQ_INIT(&gd->gd_tdfreeq);    /* for pmap_{new,dispose}_thread() */
624         TAILQ_INIT(&gd->gd_systimerq);
625         gd->gd_cpuid = cpuid;
626         gd->gd_cpumask = (cpumask_t)1 << cpuid;
627         lwkt_gdinit(gd);
628         vm_map_entry_reserve_cpu_init(gd);
629 }
630
631