51bff71f69f9d036cdcbd512dffbe244fa132a38
[dragonfly.git] / sys / platform / vkernel / platform / init.c
1 /*
2  * Copyright (c) 2006 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/platform/vkernel/platform/init.c,v 1.42 2007/07/02 03:44:12 dillon Exp $
35  */
36
37 #include <sys/types.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/stat.h>
41 #include <sys/mman.h>
42 #include <sys/cons.h>
43 #include <sys/random.h>
44 #include <sys/vkernel.h>
45 #include <sys/tls.h>
46 #include <sys/reboot.h>
47 #include <sys/proc.h>
48 #include <sys/msgbuf.h>
49 #include <sys/vmspace.h>
50 #include <sys/socket.h>
51 #include <sys/sockio.h>
52 #include <vm/vm_page.h>
53
54 #include <machine/globaldata.h>
55 #include <machine/tls.h>
56 #include <machine/md_var.h>
57 #include <machine/vmparam.h>
58
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/ethernet.h>
62 #include <net/bridge/if_bridgevar.h>
63 #include <netinet/in.h>
64 #include <arpa/inet.h>
65
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <stdarg.h>
69 #include <unistd.h>
70 #include <fcntl.h>
71 #include <string.h>
72 #include <err.h>
73 #include <errno.h>
74 #include <assert.h>
75
76 vm_paddr_t phys_avail[16];
77 vm_paddr_t Maxmem;
78 vm_paddr_t Maxmem_bytes;
79 int MemImageFd = -1;
80 struct vkdisk_info DiskInfo[VKDISK_MAX];
81 int DiskNum;
82 struct vknetif_info NetifInfo[VKNETIF_MAX];
83 int NetifNum;
84 char *pid_file;
85 vm_offset_t KvaStart;
86 vm_offset_t KvaEnd;
87 vm_offset_t KvaSize;
88 vm_offset_t virtual_start;
89 vm_offset_t virtual_end;
90 vm_offset_t kernel_vm_end;
91 vm_offset_t crashdumpmap;
92 vm_offset_t clean_sva;
93 vm_offset_t clean_eva;
94 struct msgbuf *msgbufp;
95 caddr_t ptvmmap;
96 vpte_t  *KernelPTD;
97 vpte_t  *KernelPTA;     /* Warning: Offset for direct VA translation */
98 u_int cpu_feature;      /* XXX */
99 u_int tsc_present;      /* XXX */
100 int optcpus;            /* number of cpus - see mp_start() */
101
102 struct privatespace *CPU_prvspace;
103
104 static struct trapframe proc0_tf;
105 static void *proc0paddr;
106
107 static void init_sys_memory(char *imageFile);
108 static void init_kern_memory(void);
109 static void init_globaldata(void);
110 static void init_vkernel(void);
111 static void init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type); 
112 static void init_netif(char *netifExp[], int netifFileNum);
113 static void writepid( void );
114 static void cleanpid( void );
115 static void usage(const char *ctl, ...);
116
117 static int save_ac;
118 static char **save_av;
119
120 /*
121  * Kernel startup for virtual kernels - standard main() 
122  */
123 int
124 main(int ac, char **av)
125 {
126         char *memImageFile = NULL;
127         char *netifFile[VKNETIF_MAX];
128         char *diskFile[VKDISK_MAX];
129         char *cdFile[VKDISK_MAX];
130         char *suffix;
131         int netifFileNum = 0;
132         int diskFileNum = 0;
133         int cdFileNum = 0;
134         int c;
135         int i;
136         int n;
137         
138         save_ac = ac;
139         save_av = av;
140
141         /*
142          * Process options
143          */
144         kernel_mem_readonly = 1;
145 #ifdef SMP
146         optcpus = 2;
147 #endif
148
149         while ((c = getopt(ac, av, "c:svm:n:r:e:i:p:I:U")) != -1) {
150                 switch(c) {
151                 case 'e':
152                         /*
153                          * name=value:name=value:name=value...
154                          */
155                         n = strlen(optarg);
156                         kern_envp = malloc(n + 2);
157                         for (i = 0; i < n; ++i) {
158                                 if (optarg[i] == ':')
159                                         kern_envp[i] = 0;
160                                 else
161                                         kern_envp[i] = optarg[i];
162                         }
163                         kern_envp[i++] = 0;
164                         kern_envp[i++] = 0;
165                         break;
166                 case 's':
167                         boothowto |= RB_SINGLE;
168                         break;
169                 case 'v':
170                         bootverbose = 1;
171                         break;
172                 case 'i':
173                         memImageFile = optarg;
174                         break;
175                 case 'I':
176                         if (netifFileNum < VKNETIF_MAX)
177                                 netifFile[netifFileNum++] = strdup(optarg);
178                         break;
179                 case 'r':
180                         if (diskFileNum + cdFileNum < VKDISK_MAX)
181                                 diskFile[diskFileNum++] = strdup(optarg);
182                         break;
183                 case 'c':
184                         if (diskFileNum + cdFileNum < VKDISK_MAX)
185                                 cdFile[cdFileNum++] = strdup(optarg);
186                         break;
187                 case 'm':
188                         Maxmem_bytes = strtoull(optarg, &suffix, 0);
189                         if (suffix) {
190                                 switch(*suffix) {
191                                 case 'g':
192                                 case 'G':
193                                         Maxmem_bytes <<= 30;
194                                         break;
195                                 case 'm':
196                                 case 'M':
197                                         Maxmem_bytes <<= 20;
198                                         break;
199                                 case 'k':
200                                 case 'K':
201                                         Maxmem_bytes <<= 10;
202                                         break;
203                                 default:
204                                         Maxmem_bytes = 0;
205                                         usage("Bad maxmem option");
206                                         /* NOT REACHED */
207                                         break;
208                                 }
209                         }
210                         break;
211                 case 'n':
212                         /*
213                          * This value is set up by mp_start(), don't just
214                          * set ncpus here.
215                          */
216 #ifdef SMP
217                         optcpus = strtol(optarg, NULL, 0);
218                         if (optcpus < 1 || optcpus > MAXCPU)
219                                 usage("Bad ncpus, valid range is 1-%d", MAXCPU);
220 #else
221                         if (strtol(optarg, NULL, 0) != 1) {
222                                 usage("You built a UP vkernel, only 1 cpu!");
223                         }
224 #endif
225                         
226                 case 'p':
227                         pid_file = optarg;      
228                         break;
229                 case 'U':
230                         kernel_mem_readonly = 0;
231                         break;
232                 }
233         }
234
235         writepid();
236         cpu_disable_intr();
237         init_sys_memory(memImageFile);
238         init_kern_memory();
239         init_globaldata();
240         init_vkernel();
241         init_kqueue();
242         init_disk(diskFile, diskFileNum, VKD_DISK);
243         init_disk(cdFile, cdFileNum, VKD_CD);
244         init_netif(netifFile, netifFileNum);
245         init_exceptions();
246         mi_startup();
247         /* NOT REACHED */
248         exit(1);
249 }
250
251 /*
252  * Initialize system memory.  This is the virtual kernel's 'RAM'.
253  */
254 static
255 void
256 init_sys_memory(char *imageFile)
257 {
258         struct stat st;
259         int i;
260         int fd;
261
262         /*
263          * Figure out the system memory image size.  If an image file was
264          * specified and -m was not specified, use the image file's size.
265          */
266
267         if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
268                 Maxmem_bytes = (vm_paddr_t)st.st_size;
269         if ((imageFile == NULL || stat(imageFile, &st) < 0) && 
270             Maxmem_bytes == 0) {
271                 err(1, "Cannot create new memory file %s unless "
272                        "system memory size is specified with -m",
273                        imageFile);
274                 /* NOT REACHED */
275         }
276
277         /*
278          * Maxmem must be known at this time
279          */
280         if (Maxmem_bytes < 32 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
281                 err(1, "Bad maxmem specification: 32MB minimum, "
282                        "multiples of %dMB only",
283                        SEG_SIZE / 1024 / 1024);
284                 /* NOT REACHED */
285         }
286
287         /*
288          * Generate an image file name if necessary, then open/create the
289          * file exclusively locked.  Do not allow multiple virtual kernels
290          * to use the same image file.
291          */
292         if (imageFile == NULL) {
293                 for (i = 0; i < 1000000; ++i) {
294                         asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
295                         fd = open(imageFile, 
296                                   O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
297                         if (fd < 0 && errno == EWOULDBLOCK) {
298                                 free(imageFile);
299                                 continue;
300                         }
301                         break;
302                 }
303         } else {
304                 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
305         }
306         printf("Using memory file: %s\n", imageFile);
307         if (fd < 0 || fstat(fd, &st) < 0) {
308                 err(1, "Unable to open/create %s", imageFile);
309                 /* NOT REACHED */
310         }
311
312         /*
313          * Truncate or extend the file as necessary.
314          */
315         if (st.st_size > Maxmem_bytes) {
316                 ftruncate(fd, Maxmem_bytes);
317         } else if (st.st_size < Maxmem_bytes) {
318                 char *zmem;
319                 off_t off = st.st_size & ~SEG_MASK;
320
321                 kprintf("%s: Reserving blocks for memory image\n", imageFile);
322                 zmem = malloc(SEG_SIZE);
323                 bzero(zmem, SEG_SIZE);
324                 lseek(fd, off, SEEK_SET);
325                 while (off < Maxmem_bytes) {
326                         if (write(fd, zmem, SEG_SIZE) != SEG_SIZE) {
327                                 err(1, "Unable to reserve blocks for memory image");
328                                 /* NOT REACHED */
329                         }
330                         off += SEG_SIZE;
331                 }
332                 if (fsync(fd) < 0)
333                         err(1, "Unable to reserve blocks for memory image");
334                 free(zmem);
335         }
336         MemImageFd = fd;
337         Maxmem = Maxmem_bytes >> PAGE_SHIFT;
338 }
339
340 /*
341  * Initialize kernel memory.  This reserves kernel virtual memory by using
342  * MAP_VPAGETABLE
343  */
344
345 static
346 void
347 init_kern_memory(void)
348 {
349         void *base;
350         void *try;
351         char *zero;
352         char dummy;
353         char *topofstack = &dummy;
354         vpte_t pte;
355         int i;
356
357         /*
358          * Memory map our kernel virtual memory space.  Note that the
359          * kernel image itself is not made part of this memory for the
360          * moment.
361          *
362          * The memory map must be segment-aligned so we can properly
363          * offset KernelPTD.
364          *
365          * If the system kernel has a different MAXDSIZ, it might not
366          * be possible to map kernel memory in its prefered location.
367          * Try a number of different locations.
368          */
369         try = (void *)0x40000000;
370         base = NULL;
371         while ((char *)try + KERNEL_KVA_SIZE < topofstack) {
372                 base = mmap(try, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
373                             MAP_FILE|MAP_SHARED|MAP_VPAGETABLE,
374                             MemImageFd, 0);
375                 if (base == try)
376                         break;
377                 if (base != MAP_FAILED)
378                         munmap(base, KERNEL_KVA_SIZE);
379                 try = (char *)try + 0x10000000;
380         }
381         if (base != try) {
382                 err(1, "Unable to mmap() kernel virtual memory!");
383                 /* NOT REACHED */
384         }
385         madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
386         KvaStart = (vm_offset_t)base;
387         KvaSize = KERNEL_KVA_SIZE;
388         KvaEnd = KvaStart + KvaSize;
389         printf("KVM mapped at %p-%p\n", (void *)KvaStart, (void *)KvaEnd);
390
391         /*
392          * Create a top-level page table self-mapping itself. 
393          *
394          * Initialize the page directory at physical page index 0 to point
395          * to an array of page table pages starting at physical page index 1
396          */
397         lseek(MemImageFd, 0L, 0);
398         for (i = 0; i < KERNEL_KVA_SIZE / SEG_SIZE; ++i) {
399                 pte = ((i + 1) * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
400                 write(MemImageFd, &pte, sizeof(pte));
401         }
402
403         /*
404          * Initialize the PTEs in the page table pages required to map the
405          * page table itself.  This includes mapping the page directory page
406          * at the base so we go one more loop then normal.
407          */
408         lseek(MemImageFd, PAGE_SIZE, 0);
409         for (i = 0; i <= KERNEL_KVA_SIZE / SEG_SIZE * sizeof(vpte_t); ++i) {
410                 pte = (i * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
411                 write(MemImageFd, &pte, sizeof(pte));
412         }
413
414         /*
415          * Initialize remaining PTEs to 0.  We may be reusing a memory image
416          * file.  This is approximately a megabyte.
417          */
418         i = (KERNEL_KVA_SIZE / PAGE_SIZE - i) * sizeof(pte);
419         zero = malloc(PAGE_SIZE);
420         bzero(zero, PAGE_SIZE);
421         while (i) {
422                 write(MemImageFd, zero, (i > PAGE_SIZE) ? PAGE_SIZE : i);
423                 i = i - ((i > PAGE_SIZE) ? PAGE_SIZE : i);
424         }
425         free(zero);
426
427         /*
428          * Enable the page table and calculate pointers to our self-map
429          * for easy kernel page table manipulation.
430          *
431          * KernelPTA must be offset so we can do direct VA translations
432          */
433         mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
434                  0 | VPTE_R | VPTE_W | VPTE_V);
435         KernelPTD = (vpte_t *)base;                       /* pg directory */
436         KernelPTA = (vpte_t *)((char *)base + PAGE_SIZE); /* pg table pages */
437         KernelPTA -= KvaStart >> PAGE_SHIFT;
438
439         /*
440          * phys_avail[] represents unallocated physical memory.  MI code
441          * will use phys_avail[] to create the vm_page array.
442          */
443         phys_avail[0] = PAGE_SIZE +
444                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
445         phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
446         phys_avail[1] = Maxmem_bytes;
447
448         /*
449          * (virtual_start, virtual_end) represent unallocated kernel virtual
450          * memory.  MI code will create kernel_map using these parameters.
451          */
452         virtual_start = KvaStart + PAGE_SIZE +
453                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
454         virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
455         virtual_end = KvaStart + KERNEL_KVA_SIZE;
456
457         /*
458          * kernel_vm_end could be set to virtual_end but we want some 
459          * indication of how much of the kernel_map we've used, so
460          * set it low and let pmap_growkernel increase it even though we
461          * don't need to create any new page table pages.
462          */
463         kernel_vm_end = virtual_start;
464
465         /*
466          * Allocate space for process 0's UAREA.
467          */
468         proc0paddr = (void *)virtual_start;
469         for (i = 0; i < UPAGES; ++i) {
470                 pmap_kenter_quick(virtual_start, phys_avail[0]);
471                 virtual_start += PAGE_SIZE;
472                 phys_avail[0] += PAGE_SIZE;
473         }
474
475         /*
476          * crashdumpmap
477          */
478         crashdumpmap = virtual_start;
479         virtual_start += MAXDUMPPGS * PAGE_SIZE;
480
481         /*
482          * msgbufp maps the system message buffer
483          */
484         assert((MSGBUF_SIZE & PAGE_MASK) == 0);
485         msgbufp = (void *)virtual_start;
486         for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
487                 pmap_kenter_quick(virtual_start, phys_avail[0]);
488                 virtual_start += PAGE_SIZE;
489                 phys_avail[0] += PAGE_SIZE;
490         }
491         msgbufinit(msgbufp, MSGBUF_SIZE);
492
493         /*
494          * used by kern_memio for /dev/mem access
495          */
496         ptvmmap = (caddr_t)virtual_start;
497         virtual_start += PAGE_SIZE;
498
499         /*
500          * Bootstrap the kernel_pmap
501          */
502         pmap_bootstrap();
503 }
504
505 /*
506  * Map the per-cpu globaldata for cpu #0.  Allocate the space using
507  * virtual_start and phys_avail[0]
508  */
509 static
510 void
511 init_globaldata(void)
512 {
513         int i;
514         vm_paddr_t pa;
515         vm_offset_t va;
516
517         /*
518          * Reserve enough KVA to cover possible cpus.  This is a considerable
519          * amount of KVA since the privatespace structure includes two 
520          * whole page table mappings.
521          */
522         virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
523         CPU_prvspace = (void *)virtual_start;
524         virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
525
526         /*
527          * Allocate enough physical memory to cover the mdglobaldata
528          * portion of the space and the idle stack and map the pages
529          * into KVA.  For cpu #0 only.
530          */
531         for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
532                 pa = phys_avail[0];
533                 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
534                 pmap_kenter_quick(va, pa);
535                 phys_avail[0] += PAGE_SIZE;
536         }
537         for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
538                 pa = phys_avail[0];
539                 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
540                 pmap_kenter_quick(va, pa);
541                 phys_avail[0] += PAGE_SIZE;
542         }
543
544         /*
545          * Setup the %gs for cpu #0.  The mycpu macro works after this
546          * point.
547          */
548         tls_set_fs(&CPU_prvspace[0], sizeof(struct privatespace));
549 }
550
551 /*
552  * Initialize very low level systems including thread0, proc0, etc.
553  */
554 static
555 void
556 init_vkernel(void)
557 {
558         struct mdglobaldata *gd;
559
560         gd = &CPU_prvspace[0].mdglobaldata;
561         bzero(gd, sizeof(*gd));
562
563         gd->mi.gd_curthread = &thread0;
564         thread0.td_gd = &gd->mi;
565         ncpus = 1;
566         ncpus2 = 1;     /* rounded down power of 2 */
567         ncpus_fit = 1;  /* rounded up power of 2 */
568         /* ncpus2_mask and ncpus_fit_mask are 0 */
569         init_param1();
570         gd->mi.gd_prvspace = &CPU_prvspace[0];
571         mi_gdinit(&gd->mi, 0);
572         cpu_gdinit(gd, 0);
573         mi_proc0init(&gd->mi, proc0paddr);
574         lwp0.lwp_md.md_regs = &proc0_tf;
575
576         /*init_locks();*/
577         cninit();
578         rand_initialize();
579 #if 0   /* #ifdef DDB */
580         kdb_init();
581         if (boothowto & RB_KDB)
582                 Debugger("Boot flags requested debugger");
583 #endif
584 #if 0
585         initializecpu();        /* Initialize CPU registers */
586 #endif
587         init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
588
589 #if 0
590         /*
591          * Map the message buffer
592          */
593         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
594                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
595         msgbufinit(msgbufp, MSGBUF_SIZE);
596 #endif
597 #if 0
598         thread0.td_pcb_cr3 ... MMU
599         lwp0.lwp_md.md_regs = &proc0_tf;
600 #endif
601 }
602
603 /*
604  * Filesystem image paths for the virtual kernel are optional.  
605  * If specified they each should point to a disk image, 
606  * the first of which will become the root disk.
607  *
608  * The virtual kernel caches data from our 'disk' just like a normal kernel,
609  * so we do not really want the real kernel to cache the data too.  Use
610  * O_DIRECT to remove the duplication.
611  */
612 static
613 void
614 init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type)
615 {
616         int i;  
617
618         if (diskFileNum == 0)
619                 return;
620
621         for(i=0; i < diskFileNum; i++){
622                 char *fname;
623                 fname = diskExp[i];
624
625                 if (fname == NULL) {
626                         warnx("Invalid argument to '-r'");
627                         continue;
628                 }
629
630                 if (DiskNum < VKDISK_MAX) {
631                         struct stat st; 
632                         struct vkdisk_info* info = NULL;
633                         int fd;
634                         size_t l = 0;
635
636                         if (type == VKD_DISK)
637                             fd = open(fname, O_RDWR|O_DIRECT|O_EXLOCK|O_NONBLOCK, 0644);
638                         else
639                             fd = open(fname, O_RDONLY|O_DIRECT, 0644);
640                         if (fd < 0 || fstat(fd, &st) < 0) {
641                                 if (errno == EAGAIN)
642                                         fprintf(stderr, "You may already have a vkernel using this disk image!\n");
643                                 err(1, "Unable to open/create %s", fname);
644                                 /* NOT REACHED */
645                         }
646                         /* get rid of O_NONBLOCK, keep O_DIRECT */
647                         if (type == VKD_DISK)
648                                 fcntl(fd, F_SETFL, O_DIRECT);
649
650                         info = &DiskInfo[DiskNum];
651                         l = strlen(fname);
652
653                         info->unit = i;
654                         info->fd = fd;
655                         info->type = type;
656                         memcpy(info->fname, fname, l);
657
658                         if (i == 0) {
659                                 if (type == VKD_CD)
660                                     rootdevnames[0] = "cd9660:vcd0a";
661                                 else if (type == VKD_DISK)
662                                     rootdevnames[0] = "ufs:vkd0s0a";
663                         }
664
665                         DiskNum++;
666                 } else {
667                         warnx("vkd%d (%s) > VKDISK_MAX", DiskNum, fname);
668                         continue;
669                 }
670         }
671 }
672
673 static
674 int
675 netif_set_tapflags(int tap_unit, int f, int s)
676 {
677         struct ifreq ifr;
678         int flags;
679
680         bzero(&ifr, sizeof(ifr));
681
682         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
683         if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
684                 warn("tap%d: ioctl(SIOCGIFFLAGS) failed", tap_unit);
685                 return -1;
686         }
687
688         /*
689          * Adjust if_flags
690          *
691          * If the flags are already set/cleared, then we return
692          * immediately to avoid extra syscalls
693          */
694         flags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
695         if (f < 0) {
696                 /* Turn off flags */
697                 f = -f;
698                 if ((flags & f) == 0)
699                         return 0;
700                 flags &= ~f;
701         } else {
702                 /* Turn on flags */
703                 if (flags & f)
704                         return 0;
705                 flags |= f;
706         }
707
708         /*
709          * Fix up ifreq.ifr_name, since it may be trashed
710          * in previous ioctl(SIOCGIFFLAGS)
711          */
712         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
713
714         ifr.ifr_flags = flags & 0xffff;
715         ifr.ifr_flagshigh = flags >> 16;
716         if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
717                 warn("tap%d: ioctl(SIOCSIFFLAGS) failed", tap_unit);
718                 return -1;
719         }
720         return 0;
721 }
722
723 static
724 int
725 netif_set_tapaddr(int tap_unit, in_addr_t addr, in_addr_t mask, int s)
726 {
727         struct ifaliasreq ifra;
728         struct sockaddr_in *in;
729
730         bzero(&ifra, sizeof(ifra));
731         snprintf(ifra.ifra_name, sizeof(ifra.ifra_name), "tap%d", tap_unit);
732
733         /* Setup address */
734         in = (struct sockaddr_in *)&ifra.ifra_addr;
735         in->sin_family = AF_INET;
736         in->sin_len = sizeof(*in);
737         in->sin_addr.s_addr = addr;
738
739         if (mask != 0) {
740                 /* Setup netmask */
741                 in = (struct sockaddr_in *)&ifra.ifra_mask;
742                 in->sin_len = sizeof(*in);
743                 in->sin_addr.s_addr = mask;
744         }
745
746         if (ioctl(s, SIOCAIFADDR, &ifra) < 0) {
747                 warn("tap%d: ioctl(SIOCAIFADDR) failed", tap_unit);
748                 return -1;
749         }
750         return 0;
751 }
752
753 static
754 int
755 netif_add_tap2brg(int tap_unit, const char *ifbridge, int s)
756 {
757         struct ifbreq ifbr;
758         struct ifdrv ifd;
759
760         bzero(&ifbr, sizeof(ifbr));
761         snprintf(ifbr.ifbr_ifsname, sizeof(ifbr.ifbr_ifsname),
762                  "tap%d", tap_unit);
763
764         bzero(&ifd, sizeof(ifd));
765         strlcpy(ifd.ifd_name, ifbridge, sizeof(ifd.ifd_name));
766         ifd.ifd_cmd = BRDGADD;
767         ifd.ifd_len = sizeof(ifbr);
768         ifd.ifd_data = &ifbr;
769
770         if (ioctl(s, SIOCSDRVSPEC, &ifd) < 0) {
771                 /*
772                  * 'errno == EEXIST' means that the tap(4) is already
773                  * a member of the bridge(4)
774                  */
775                 if (errno != EEXIST) {
776                         warn("ioctl(%s, SIOCSDRVSPEC) failed", ifbridge);
777                         return -1;
778                 }
779         }
780         return 0;
781 }
782
783 #define TAPDEV_OFLAGS   (O_RDWR | O_NONBLOCK)
784
785 /* XXX major()/minor() can't be used in vkernel */
786 #define TAPDEV_MAJOR(x) ((int)(((u_int)(x) >> 8) & 0xff))
787 #define TAPDEV_MINOR(x) ((int)((x) & 0xffff00ff))
788
789 #ifndef TAP_CDEV_MAJOR
790 #define TAP_CDEV_MAJOR  149
791 #endif
792
793 /*
794  * Locate the first unused tap(4) device file if auto mode is requested,
795  * or open the user supplied device file, and bring up the corresponding
796  * tap(4) interface.
797  *
798  * NOTE: Only tap(4) device file is supported currently
799  */
800 static
801 int
802 netif_open_tap(const char *netif, int *tap_unit, int s)
803 {
804         char tap_dev[MAXPATHLEN];
805         int tap_fd, failed;
806         struct stat st;
807
808         *tap_unit = -1;
809
810         if (strcmp(netif, "auto") == 0) {
811                 int i;
812
813                 /*
814                  * Find first unused tap(4) device file
815                  */
816                 for (i = 0; ; ++i) {
817                         snprintf(tap_dev, sizeof(tap_dev), "/dev/tap%d", i);
818                         tap_fd = open(tap_dev, TAPDEV_OFLAGS);
819                         if (tap_fd >= 0 || errno == ENOENT)
820                                 break;
821                 }
822                 if (tap_fd < 0) {
823                         warnx("Unable to find a free tap(4)");
824                         return -1;
825                 }
826         } else {
827                 /*
828                  * User supplied tap(4) device file
829                  */
830                 if (netif[0] == '/')    /* Absolute path */
831                         strlcpy(tap_dev, netif, sizeof(tap_dev));
832                 else
833                         snprintf(tap_dev, sizeof(tap_dev), "/dev/%s", netif);
834
835                 tap_fd = open(tap_dev, TAPDEV_OFLAGS);
836                 if (tap_fd < 0) {
837                         warn("Unable to open %s", tap_dev);
838                         return -1;
839                 }
840         }
841
842         /*
843          * Check whether the device file is a tap(4)
844          */
845         failed = 1;
846         if (fstat(tap_fd, &st) == 0 && S_ISCHR(st.st_mode) &&
847             TAPDEV_MAJOR(st.st_rdev) == TAP_CDEV_MAJOR) {
848                 *tap_unit = TAPDEV_MINOR(st.st_rdev);
849
850                 /*
851                  * Bring up the corresponding tap(4) interface
852                  */
853                 if (netif_set_tapflags(*tap_unit, IFF_UP, s) == 0)
854                         failed = 0;
855         } else {
856                 warnx("%s is not a tap(4) device", tap_dev);
857         }
858
859         if (failed) {
860                 close(tap_fd);
861                 tap_fd = -1;
862                 *tap_unit = -1;
863         }
864         return tap_fd;
865 }
866
867 #undef TAPDEV_MAJOR
868 #undef TAPDEV_MINOR
869 #undef TAPDEV_OFLAGS
870
871 /*
872  * Following syntax is supported,
873  * 1) x.x.x.x             tap(4)'s address is x.x.x.x
874  *
875  * 2) x.x.x.x/z           tap(4)'s address is x.x.x.x
876  *                        tap(4)'s netmask len is z
877  *
878  * 3) x.x.x.x:y.y.y.y     tap(4)'s address is x.x.x.x
879  *                        pseudo netif's address is y.y.y.y
880  *
881  * 4) x.x.x.x:y.y.y.y/z   tap(4)'s address is x.x.x.x
882  *                        pseudo netif's address is y.y.y.y
883  *                        tap(4) and pseudo netif's netmask len are z
884  *
885  * 5) bridgeX             tap(4) will be added to bridgeX
886  *
887  * 6) bridgeX:y.y.y.y     tap(4) will be added to bridgeX
888  *                        pseudo netif's address is y.y.y.y
889  *
890  * 7) bridgeX:y.y.y.y/z   tap(4) will be added to bridgeX
891  *                        pseudo netif's address is y.y.y.y
892  *                        pseudo netif's netmask len is z
893  */
894 static
895 int
896 netif_init_tap(int tap_unit, in_addr_t *addr, in_addr_t *mask, int s)
897 {
898         in_addr_t tap_addr, netmask, netif_addr;
899         int next_netif_addr;
900         char *tok, *masklen_str, *ifbridge;
901
902         *addr = 0;
903         *mask = 0;
904
905         tok = strtok(NULL, ":/");
906         if (tok == NULL) {
907                 /*
908                  * Nothing special, simply use tap(4) as backend
909                  */
910                 return 0;
911         }
912
913         if (inet_pton(AF_INET, tok, &tap_addr) > 0) {
914                 /*
915                  * tap(4)'s address is supplied
916                  */
917                 ifbridge = NULL;
918
919                 /*
920                  * If there is next token, then it may be pseudo
921                  * netif's address or netmask len for tap(4)
922                  */
923                 next_netif_addr = 0;
924         } else {
925                 /*
926                  * Not tap(4)'s address, assume it as a bridge(4)
927                  * iface name
928                  */
929                 tap_addr = 0;
930                 ifbridge = tok;
931
932                 /*
933                  * If there is next token, then it must be pseudo
934                  * netif's address
935                  */
936                 next_netif_addr = 1;
937         }
938
939         netmask = netif_addr = 0;
940
941         tok = strtok(NULL, ":/");
942         if (tok == NULL)
943                 goto back;
944
945         if (inet_pton(AF_INET, tok, &netif_addr) <= 0) {
946                 if (next_netif_addr) {
947                         warnx("Invalid pseudo netif address: %s", tok);
948                         return -1;
949                 }
950                 netif_addr = 0;
951
952                 /*
953                  * Current token is not address, then it must be netmask len
954                  */
955                 masklen_str = tok;
956         } else {
957                 /*
958                  * Current token is pseudo netif address, if there is next token
959                  * it must be netmask len
960                  */
961                 masklen_str = strtok(NULL, "/");
962         }
963
964         /* Calculate netmask */
965         if (masklen_str != NULL) {
966                 u_long masklen;
967
968                 masklen = strtoul(masklen_str, NULL, 10);
969                 if (masklen < 32 && masklen > 0) {
970                         netmask = htonl(~((1LL << (32 - masklen)) - 1)
971                                         & 0xffffffff);
972                 } else {
973                         warnx("Invalid netmask len: %lu", masklen);
974                         return -1;
975                 }
976         }
977
978         /* Make sure there is no more token left */
979         if (strtok(NULL, ":/") != NULL) {
980                 warnx("Invalid argument to '-I'");
981                 return -1;
982         }
983
984 back:
985         if (ifbridge == NULL) {
986                 /* Set tap(4) address/netmask */
987                 if (netif_set_tapaddr(tap_unit, tap_addr, netmask, s) < 0)
988                         return -1;
989         } else {
990                 /* Tie tap(4) to bridge(4) */
991                 if (netif_add_tap2brg(tap_unit, ifbridge, s) < 0)
992                         return -1;
993         }
994
995         *addr = netif_addr;
996         *mask = netmask;
997         return 0;
998 }
999
1000 /*
1001  * NetifInfo[] will be filled for pseudo netif initialization.
1002  * NetifNum will be bumped to reflect the number of valid entries
1003  * in NetifInfo[].
1004  */
1005 static
1006 void
1007 init_netif(char *netifExp[], int netifExpNum)
1008 {
1009         int i, s;
1010
1011         if (netifExpNum == 0)
1012                 return;
1013
1014         s = socket(AF_INET, SOCK_DGRAM, 0);     /* for ioctl(SIOC) */
1015         if (s < 0)
1016                 return;
1017
1018         for (i = 0; i < netifExpNum; ++i) {
1019                 struct vknetif_info *info;
1020                 in_addr_t netif_addr, netif_mask;
1021                 int tap_fd, tap_unit;
1022                 char *netif;
1023
1024                 netif = strtok(netifExp[i], ":");
1025                 if (netif == NULL) {
1026                         warnx("Invalid argument to '-I'");
1027                         continue;
1028                 }
1029
1030                 /*
1031                  * Open tap(4) device file and bring up the
1032                  * corresponding interface
1033                  */
1034                 tap_fd = netif_open_tap(netif, &tap_unit, s);
1035                 if (tap_fd < 0)
1036                         continue;
1037
1038                 /*
1039                  * Initialize tap(4) and get address/netmask
1040                  * for pseudo netif
1041                  *
1042                  * NB: Rest part of netifExp[i] is passed
1043                  *     to netif_init_tap() implicitly.
1044                  */
1045                 if (netif_init_tap(tap_unit, &netif_addr, &netif_mask, s) < 0) {
1046                         /*
1047                          * NB: Closing tap(4) device file will bring
1048                          *     down the corresponding interface
1049                          */
1050                         close(tap_fd);
1051                         continue;
1052                 }
1053
1054                 info = &NetifInfo[NetifNum];
1055                 info->tap_fd = tap_fd;
1056                 info->tap_unit = tap_unit;
1057                 info->netif_addr = netif_addr;
1058                 info->netif_mask = netif_mask;
1059
1060                 NetifNum++;
1061                 if (NetifNum >= VKNETIF_MAX)    /* XXX will this happen? */
1062                         break;
1063         }
1064         close(s);
1065 }
1066
1067 static
1068 void
1069 writepid( void )
1070 {
1071         pid_t self;
1072         FILE *fp;
1073
1074         if (pid_file != NULL) {
1075                 self = getpid();
1076                 fp = fopen(pid_file, "w");
1077
1078                 if (fp != NULL) {
1079                         fprintf(fp, "%ld\n", (long)self);
1080                         fclose(fp);
1081                 }
1082                 else {
1083                         perror("Warning: couldn't open pidfile");
1084                 }
1085         }
1086 }
1087
1088 static
1089 void
1090 cleanpid( void ) 
1091 {
1092         if (pid_file != NULL) {
1093                 if ( unlink(pid_file) != 0 )
1094                         perror("Warning: couldn't remove pidfile");
1095         }
1096 }
1097
1098 static
1099 void
1100 usage(const char *ctl, ...)
1101 {
1102         va_list va;
1103
1104         va_start(va, ctl);
1105         vfprintf(stderr, ctl, va);
1106         va_end(va);
1107         fprintf(stderr, "\n");
1108         exit(1);
1109 }
1110
1111 void
1112 cpu_reset(void)
1113 {
1114         kprintf("cpu reset, rebooting vkernel\n");
1115         closefrom(3);
1116         cleanpid();
1117         execv(save_av[0], save_av);
1118 }
1119
1120 void
1121 cpu_halt(void)
1122 {
1123         kprintf("cpu halt, exiting vkernel\n");
1124         cleanpid();
1125         exit(0);
1126 }