f8fedfaff874de4926b6d09f3cd3b241b0ee186e
[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.27 2007/01/15 01:29:04 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 <unistd.h>
69 #include <fcntl.h>
70 #include <string.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <assert.h>
74
75 vm_paddr_t phys_avail[16];
76 vm_paddr_t Maxmem;
77 vm_paddr_t Maxmem_bytes;
78 int MemImageFd = -1;
79 int RootImageFd = -1;
80 struct vknetif_info NetifInfo[VKNETIF_MAX];
81 int NetifNum;
82 vm_offset_t KvaStart;
83 vm_offset_t KvaEnd;
84 vm_offset_t KvaSize;
85 vm_offset_t virtual_start;
86 vm_offset_t virtual_end;
87 vm_offset_t kernel_vm_end;
88 vm_offset_t crashdumpmap;
89 vm_offset_t clean_sva;
90 vm_offset_t clean_eva;
91 struct msgbuf *msgbufp;
92 caddr_t ptvmmap;
93 vpte_t  *KernelPTD;
94 vpte_t  *KernelPTA;     /* Warning: Offset for direct VA translation */
95 u_int cpu_feature;      /* XXX */
96 u_int tsc_present;      /* XXX */
97
98 struct privatespace *CPU_prvspace;
99
100 static struct trapframe proc0_tf;
101 static void *proc0paddr;
102
103 static void init_sys_memory(char *imageFile);
104 static void init_kern_memory(void);
105 static void init_globaldata(void);
106 static void init_vkernel(void);
107 static void init_rootdevice(char *imageFile);
108 static void init_netif(char *netifFile[], int netifFileNum);
109 static void usage(const char *ctl);
110
111 /*
112  * Kernel startup for virtual kernels - standard main() 
113  */
114 int
115 main(int ac, char **av)
116 {
117         char *memImageFile = NULL;
118         char *rootImageFile = NULL;
119         char *netifFile[VKNETIF_MAX];
120         char *suffix;
121         int netifFileNum = 0;
122         int c;
123         int i;
124         int n;
125
126         /*
127          * Process options
128          */
129         while ((c = getopt(ac, av, "svm:r:e:I:")) != -1) {
130                 switch(c) {
131                 case 'e':
132                         /*
133                          * name=value:name=value:name=value...
134                          */
135                         n = strlen(optarg);
136                         kern_envp = malloc(n + 2);
137                         for (i = 0; i < n; ++i) {
138                                 if (optarg[i] == ':')
139                                         kern_envp[i] = 0;
140                                 else
141                                         kern_envp[i] = optarg[i];
142                         }
143                         kern_envp[i++] = 0;
144                         kern_envp[i++] = 0;
145                         break;
146                 case 's':
147                         boothowto |= RB_SINGLE;
148                         break;
149                 case 'v':
150                         bootverbose = 1;
151                         break;
152                 case 'i':
153                         memImageFile = optarg;
154                         break;
155                 case 'I':
156                         if (netifFileNum < VKNETIF_MAX)
157                                 netifFile[netifFileNum++] = optarg;
158                         break;
159                 case 'r':
160                         rootImageFile = optarg;
161                         break;
162                 case 'm':
163                         Maxmem_bytes = strtoull(optarg, &suffix, 0);
164                         if (suffix) {
165                                 switch(*suffix) {
166                                 case 'g':
167                                 case 'G':
168                                         Maxmem_bytes <<= 30;
169                                         break;
170                                 case 'm':
171                                 case 'M':
172                                         Maxmem_bytes <<= 20;
173                                         break;
174                                 case 'k':
175                                 case 'K':
176                                         Maxmem_bytes <<= 10;
177                                         break;
178                                 default:
179                                         Maxmem_bytes = 0;
180                                         usage("Bad maxmem option");
181                                         /* NOT REACHED */
182                                         break;
183                                 }
184                         }
185                         break;
186                 }
187         }
188
189         cpu_disable_intr();
190         init_sys_memory(memImageFile);
191         init_kern_memory();
192         init_globaldata();
193         init_vkernel();
194         init_kqueue();
195         init_rootdevice(rootImageFile);
196         init_netif(netifFile, netifFileNum);
197         init_exceptions();
198         mi_startup();
199         /* NOT REACHED */
200         exit(1);
201 }
202
203 /*
204  * Initialize system memory.  This is the virtual kernel's 'RAM'.
205  */
206 static
207 void
208 init_sys_memory(char *imageFile)
209 {
210         struct stat st;
211         int i;
212         int fd;
213
214         /*
215          * Figure out the system memory image size.  If an image file was
216          * specified and -m was not specified, use the image file's size.
217          */
218
219         if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
220                 Maxmem_bytes = (vm_paddr_t)st.st_size;
221         if ((imageFile == NULL || stat(imageFile, &st) < 0) && 
222             Maxmem_bytes == 0) {
223                 err(1, "Cannot create new memory file %s unless "
224                        "system memory size is specified with -m",
225                        imageFile);
226                 /* NOT REACHED */
227         }
228
229         /*
230          * Maxmem must be known at this time
231          */
232         if (Maxmem_bytes < 32 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
233                 err(1, "Bad maxmem specification: 32MB minimum, "
234                        "multiples of %dMB only",
235                        SEG_SIZE / 1024 / 1024);
236                 /* NOT REACHED */
237         }
238
239         /*
240          * Generate an image file name if necessary, then open/create the
241          * file exclusively locked.  Do not allow multiple virtual kernels
242          * to use the same image file.
243          */
244         if (imageFile == NULL) {
245                 for (i = 0; i < 1000000; ++i) {
246                         asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
247                         fd = open(imageFile, 
248                                   O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
249                         if (fd < 0 && errno == EWOULDBLOCK) {
250                                 free(imageFile);
251                                 continue;
252                         }
253                         break;
254                 }
255         } else {
256                 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
257         }
258         printf("Using memory file: %s\n", imageFile);
259         if (fd < 0 || fstat(fd, &st) < 0) {
260                 err(1, "Unable to open/create %s: %s",
261                       imageFile, strerror(errno));
262                 /* NOT REACHED */
263         }
264
265         /*
266          * Truncate or extend the file as necessary.
267          */
268         if (st.st_size > Maxmem_bytes) {
269                 ftruncate(fd, Maxmem_bytes);
270         } else if (st.st_size < Maxmem_bytes) {
271                 char *zmem;
272                 off_t off = st.st_size & ~SEG_MASK;
273
274                 kprintf("%s: Reserving blocks for memory image\n", imageFile);
275                 zmem = malloc(SEG_SIZE);
276                 bzero(zmem, SEG_SIZE);
277                 lseek(fd, off, SEEK_SET);
278                 while (off < Maxmem_bytes) {
279                         if (write(fd, zmem, SEG_SIZE) != SEG_SIZE) {
280                                 err(1, "Unable to reserve blocks for memory image");
281                                 /* NOT REACHED */
282                         }
283                         off += SEG_SIZE;
284                 }
285                 if (fsync(fd) < 0)
286                         err(1, "Unable to reserve blocks for memory image");
287                 free(zmem);
288         }
289         MemImageFd = fd;
290         Maxmem = Maxmem_bytes >> PAGE_SHIFT;
291 }
292
293 /*
294  * Initialize kernel memory.  This reserves kernel virtual memory by using
295  * MAP_VPAGETABLE
296  */
297 static
298 void
299 init_kern_memory(void)
300 {
301         void *base;
302         char *zero;
303         vpte_t pte;
304         int i;
305
306         /*
307          * Memory map our kernel virtual memory space.  Note that the
308          * kernel image itself is not made part of this memory for the
309          * moment.
310          *
311          * The memory map must be segment-aligned so we can properly
312          * offset KernelPTD.
313          */
314         base = mmap((void *)0x40000000, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
315                     MAP_FILE|MAP_SHARED|MAP_VPAGETABLE, MemImageFd, 0);
316         if (base == MAP_FAILED) {
317                 err(1, "Unable to mmap() kernel virtual memory!");
318                 /* NOT REACHED */
319         }
320         madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
321         KvaStart = (vm_offset_t)base;
322         KvaSize = KERNEL_KVA_SIZE;
323         KvaEnd = KvaStart + KvaSize;
324
325         /*
326          * Create a top-level page table self-mapping itself. 
327          *
328          * Initialize the page directory at physical page index 0 to point
329          * to an array of page table pages starting at physical page index 1
330          */
331         lseek(MemImageFd, 0L, 0);
332         for (i = 0; i < KERNEL_KVA_SIZE / SEG_SIZE; ++i) {
333                 pte = ((i + 1) * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
334                 write(MemImageFd, &pte, sizeof(pte));
335         }
336
337         /*
338          * Initialize the PTEs in the page table pages required to map the
339          * page table itself.  This includes mapping the page directory page
340          * at the base so we go one more loop then normal.
341          */
342         lseek(MemImageFd, PAGE_SIZE, 0);
343         for (i = 0; i <= KERNEL_KVA_SIZE / SEG_SIZE * sizeof(vpte_t); ++i) {
344                 pte = (i * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
345                 write(MemImageFd, &pte, sizeof(pte));
346         }
347
348         /*
349          * Initialize remaining PTEs to 0.  We may be reusing a memory image
350          * file.  This is approximately a megabyte.
351          */
352         i = (KERNEL_KVA_SIZE / PAGE_SIZE - i) * sizeof(pte);
353         zero = malloc(PAGE_SIZE);
354         bzero(zero, PAGE_SIZE);
355         while (i) {
356                 write(MemImageFd, zero, (i > PAGE_SIZE) ? PAGE_SIZE : i);
357                 i = i - ((i > PAGE_SIZE) ? PAGE_SIZE : i);
358         }
359         free(zero);
360
361         /*
362          * Enable the page table and calculate pointers to our self-map
363          * for easy kernel page table manipulation.
364          *
365          * KernelPTA must be offset so we can do direct VA translations
366          */
367         mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
368                  0 | VPTE_R | VPTE_W | VPTE_V);
369         KernelPTD = (vpte_t *)base;                       /* pg directory */
370         KernelPTA = (vpte_t *)((char *)base + PAGE_SIZE); /* pg table pages */
371         KernelPTA -= KvaStart >> PAGE_SHIFT;
372
373         /*
374          * phys_avail[] represents unallocated physical memory.  MI code
375          * will use phys_avail[] to create the vm_page array.
376          */
377         phys_avail[0] = PAGE_SIZE +
378                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
379         phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
380         phys_avail[1] = Maxmem_bytes;
381
382         /*
383          * (virtual_start, virtual_end) represent unallocated kernel virtual
384          * memory.  MI code will create kernel_map using these parameters.
385          */
386         virtual_start = KvaStart + PAGE_SIZE +
387                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
388         virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
389         virtual_end = KvaStart + KERNEL_KVA_SIZE;
390
391         /*
392          * kernel_vm_end could be set to virtual_end but we want some 
393          * indication of how much of the kernel_map we've used, so
394          * set it low and let pmap_growkernel increase it even though we
395          * don't need to create any new page table pages.
396          */
397         kernel_vm_end = virtual_start;
398
399         /*
400          * Allocate space for process 0's UAREA.
401          */
402         proc0paddr = (void *)virtual_start;
403         for (i = 0; i < UPAGES; ++i) {
404                 pmap_kenter_quick(virtual_start, phys_avail[0]);
405                 virtual_start += PAGE_SIZE;
406                 phys_avail[0] += PAGE_SIZE;
407         }
408
409         /*
410          * crashdumpmap
411          */
412         crashdumpmap = virtual_start;
413         virtual_start += MAXDUMPPGS * PAGE_SIZE;
414
415         /*
416          * msgbufp maps the system message buffer
417          */
418         assert((MSGBUF_SIZE & PAGE_MASK) == 0);
419         msgbufp = (void *)virtual_start;
420         for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
421                 pmap_kenter_quick(virtual_start, phys_avail[0]);
422                 virtual_start += PAGE_SIZE;
423                 phys_avail[0] += PAGE_SIZE;
424         }
425         msgbufinit(msgbufp, MSGBUF_SIZE);
426
427         /*
428          * used by kern_memio for /dev/mem access
429          */
430         ptvmmap = (caddr_t)virtual_start;
431         virtual_start += PAGE_SIZE;
432
433         /*
434          * Bootstrap the kernel_pmap
435          */
436         pmap_bootstrap();
437 }
438
439 /*
440  * Map the per-cpu globaldata for cpu #0.  Allocate the space using
441  * virtual_start and phys_avail[0]
442  */
443 static
444 void
445 init_globaldata(void)
446 {
447         int i;
448         vm_paddr_t pa;
449         vm_offset_t va;
450
451         /*
452          * Reserve enough KVA to cover possible cpus.  This is a considerable
453          * amount of KVA since the privatespace structure includes two 
454          * whole page table mappings.
455          */
456         virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
457         CPU_prvspace = (void *)virtual_start;
458         virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
459
460         /*
461          * Allocate enough physical memory to cover the mdglobaldata
462          * portion of the space and the idle stack and map the pages
463          * into KVA.  For cpu #0 only.
464          */
465         for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
466                 pa = phys_avail[0];
467                 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
468                 pmap_kenter_quick(va, pa);
469                 phys_avail[0] += PAGE_SIZE;
470         }
471         for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
472                 pa = phys_avail[0];
473                 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
474                 pmap_kenter_quick(va, pa);
475                 phys_avail[0] += PAGE_SIZE;
476         }
477
478         /*
479          * Setup the %gs for cpu #0.  The mycpu macro works after this
480          * point.
481          */
482         tls_set_fs(&CPU_prvspace[0], sizeof(struct privatespace));
483 }
484
485 /*
486  * Initialize very low level systems including thread0, proc0, etc.
487  */
488 static
489 void
490 init_vkernel(void)
491 {
492         struct mdglobaldata *gd;
493
494         gd = &CPU_prvspace[0].mdglobaldata;
495         bzero(gd, sizeof(*gd));
496
497         gd->mi.gd_curthread = &thread0;
498         thread0.td_gd = &gd->mi;
499         ncpus = 1;
500         ncpus2 = 1;
501         init_param1();
502         gd->mi.gd_prvspace = &CPU_prvspace[0];
503         mi_gdinit(&gd->mi, 0);
504         cpu_gdinit(gd, 0);
505         mi_proc0init(&gd->mi, proc0paddr);
506         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
507
508         /*init_locks();*/
509         cninit();
510         rand_initialize();
511 #if 0   /* #ifdef DDB */
512         kdb_init();
513         if (boothowto & RB_KDB)
514                 Debugger("Boot flags requested debugger");
515 #endif
516 #if 0
517         initializecpu();        /* Initialize CPU registers */
518 #endif
519         init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
520
521 #if 0
522         /*
523          * Map the message buffer
524          */
525         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
526                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
527         msgbufinit(msgbufp, MSGBUF_SIZE);
528 #endif
529 #if 0
530         thread0.td_pcb_cr3 ... MMU
531         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
532 #endif
533 }
534
535 /*
536  * The root filesystem path for the virtual kernel is optional.  If specified
537  * it points to a filesystem image.
538  *
539  * The virtual kernel caches data from our 'disk' just like a normal kernel,
540  * so we do not really want the real kernel to cache the data too.  Use
541  * O_DIRECT to remove the duplication.
542  */
543 static
544 void
545 init_rootdevice(char *imageFile)
546 {
547         struct stat st;
548
549         if (imageFile) {
550                 RootImageFd = open(imageFile, O_RDWR|O_DIRECT, 0644);
551                 if (RootImageFd < 0 || fstat(RootImageFd, &st) < 0) {
552                         err(1, "Unable to open/create %s: %s",
553                             imageFile, strerror(errno));
554                         /* NOT REACHED */
555                 }
556                 rootdevnames[0] = "ufs:vkd0a";
557         }
558 }
559
560 static
561 int
562 netif_set_tapflags(int tap_unit, int f, int s)
563 {
564         struct ifreq ifr;
565         int flags;
566
567         bzero(&ifr, sizeof(ifr));
568
569         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
570         if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
571                 warn("tap%d: ioctl(SIOCGIFFLAGS) failed: %s",
572                      tap_unit, strerror(errno));
573                 return -1;
574         }
575
576         /*
577          * Adjust if_flags
578          *
579          * If the flags are already set/cleared, then we return
580          * immediately to avoid extra syscalls
581          */
582         flags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
583         if (f < 0) {
584                 /* Turn off flags */
585                 f = -f;
586                 if ((flags & f) == 0)
587                         return 0;
588                 flags &= ~f;
589         } else {
590                 /* Turn on flags */
591                 if (flags & f)
592                         return 0;
593                 flags |= f;
594         }
595
596         /*
597          * Fix up ifreq.ifr_name, since it may be trashed
598          * in previous ioctl(SIOCGIFFLAGS)
599          */
600         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
601
602         ifr.ifr_flags = flags & 0xffff;
603         ifr.ifr_flagshigh = flags >> 16;
604         if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
605                 warn("tap%d: ioctl(SIOCSIFFLAGS) failed: %s",
606                      tap_unit, strerror(errno));
607                 return -1;
608         }
609         return 0;
610 }
611
612 static
613 int
614 netif_set_tapaddr(int tap_unit, in_addr_t addr, in_addr_t mask, int s)
615 {
616         struct ifaliasreq ifra;
617         struct sockaddr_in *in;
618
619         bzero(&ifra, sizeof(ifra));
620         snprintf(ifra.ifra_name, sizeof(ifra.ifra_name), "tap%d", tap_unit);
621
622         /* Setup address */
623         in = (struct sockaddr_in *)&ifra.ifra_addr;
624         in->sin_family = AF_INET;
625         in->sin_len = sizeof(*in);
626         in->sin_addr.s_addr = addr;
627
628         if (mask != 0) {
629                 /* Setup netmask */
630                 in = (struct sockaddr_in *)&ifra.ifra_mask;
631                 in->sin_len = sizeof(*in);
632                 in->sin_addr.s_addr = mask;
633         }
634
635         if (ioctl(s, SIOCAIFADDR, &ifra) < 0) {
636                 warn("tap%d: ioctl(SIOCAIFADDR) failed: %s",
637                      tap_unit, strerror(errno));
638                 return -1;
639         }
640         return 0;
641 }
642
643 static
644 int
645 netif_add_tap2brg(int tap_unit, const char *ifbridge, int s)
646 {
647         struct ifbreq ifbr;
648         struct ifdrv ifd;
649
650         bzero(&ifbr, sizeof(ifbr));
651         snprintf(ifbr.ifbr_ifsname, sizeof(ifbr.ifbr_ifsname),
652                  "tap%d", tap_unit);
653
654         bzero(&ifd, sizeof(ifd));
655         strlcpy(ifd.ifd_name, ifbridge, sizeof(ifd.ifd_name));
656         ifd.ifd_cmd = BRDGADD;
657         ifd.ifd_len = sizeof(ifbr);
658         ifd.ifd_data = &ifbr;
659
660         if (ioctl(s, SIOCSDRVSPEC, &ifd) < 0) {
661                 /*
662                  * 'errno == EEXIST' means that the tap(4) is already
663                  * a member of the bridge(4)
664                  */
665                 if (errno != EEXIST) {
666                         warn("ioctl(%s, SIOCSDRVSPEC) failed: %s",
667                              ifbridge, strerror(errno));
668                         return -1;
669                 }
670         }
671         return 0;
672 }
673
674 #define TAPDEV_OFLAGS   (O_RDWR | O_NONBLOCK)
675
676 /* XXX major()/minor() can't be used in vkernel */
677 #define TAPDEV_MAJOR(x) ((int)(((u_int)(x) >> 8) & 0xff))
678 #define TAPDEV_MINOR(x) ((int)((x) & 0xffff00ff))
679
680 #ifndef TAP_CDEV_MAJOR
681 #define TAP_CDEV_MAJOR  149
682 #endif
683
684 /*
685  * Locate the first unused tap(4) device file if auto mode is requested,
686  * or open the user supplied device file, and bring up the corresponding
687  * tap(4) interface.
688  *
689  * NOTE: Only tap(4) device file is supported currently
690  */
691 static
692 int
693 netif_open_tap(const char *netif, int *tap_unit, int s)
694 {
695         char tap_dev[MAXPATHLEN];
696         int tap_fd, failed;
697         struct stat st;
698
699         *tap_unit = -1;
700
701         if (strcmp(netif, "auto") == 0) {
702                 int i;
703
704                 /*
705                  * Find first unused tap(4) device file
706                  */
707                 for (i = 0; ; ++i) {
708                         snprintf(tap_dev, sizeof(tap_dev), "/dev/tap%d", i);
709                         tap_fd = open(tap_dev, TAPDEV_OFLAGS);
710                         if (tap_fd >= 0 || errno == ENOENT)
711                                 break;
712                 }
713                 if (tap_fd < 0) {
714                         warnx("Unable to find a free tap(4)");
715                         return -1;
716                 }
717         } else {
718                 /*
719                  * User supplied tap(4) device file
720                  */
721                 if (netif[0] == '/')    /* Absolute path */
722                         strlcpy(tap_dev, netif, sizeof(tap_dev));
723                 else
724                         snprintf(tap_dev, sizeof(tap_dev), "/dev/%s", netif);
725
726                 tap_fd = open(tap_dev, TAPDEV_OFLAGS);
727                 if (tap_fd < 0) {
728                         warn("Unable to open %s: %s",
729                              tap_dev, strerror(errno));
730                         return -1;
731                 }
732         }
733
734         /*
735          * Check whether the device file is a tap(4)
736          */
737         failed = 1;
738         if (fstat(tap_fd, &st) == 0 && S_ISCHR(st.st_mode) &&
739             TAPDEV_MAJOR(st.st_rdev) == TAP_CDEV_MAJOR) {
740                 *tap_unit = TAPDEV_MINOR(st.st_rdev);
741
742                 /*
743                  * Bring up the corresponding tap(4) interface
744                  */
745                 if (netif_set_tapflags(*tap_unit, IFF_UP, s) == 0)
746                         failed = 0;
747         } else {
748                 warnx("%s is not a tap(4) device", tap_dev);
749         }
750
751         if (failed) {
752                 close(tap_fd);
753                 tap_fd = -1;
754                 *tap_unit = -1;
755         }
756         return tap_fd;
757 }
758
759 #undef TAPDEV_MAJOR
760 #undef TAPDEV_MINOR
761 #undef TAPDEV_OFLAGS
762
763 /*
764  * Following syntax is supported,
765  * 1) x.x.x.x             tap(4)'s address is x.x.x.x
766  *
767  * 2) x.x.x.x/z           tap(4)'s address is x.x.x.x
768  *                        tap(4)'s netmask len is z
769  *
770  * 3) x.x.x.x:y.y.y.y     tap(4)'s address is x.x.x.x
771  *                        pseudo netif's address is y.y.y.y
772  *
773  * 4) x.x.x.x:y.y.y.y/z   tap(4)'s address is x.x.x.x
774  *                        pseudo netif's address is y.y.y.y
775  *                        tap(4) and pseudo netif's netmask len are z
776  *
777  * 5) bridgeX             tap(4) will be added to bridgeX
778  *
779  * 6) bridgeX:y.y.y.y     tap(4) will be added to bridgeX
780  *                        pseudo netif's address is y.y.y.y
781  *
782  * 7) bridgeX:y.y.y.y/z   tap(4) will be added to bridgeX
783  *                        pseudo netif's address is y.y.y.y
784  *                        pseudo netif's netmask len is z
785  */
786 static
787 int
788 netif_init_tap(int tap_unit, in_addr_t *addr, in_addr_t *mask, int s)
789 {
790         in_addr_t tap_addr, netmask, netif_addr;
791         int next_netif_addr;
792         char *tok, *masklen_str, *ifbridge;
793
794         *addr = 0;
795         *mask = 0;
796
797         tok = strtok(NULL, ":/");
798         if (tok == NULL) {
799                 /*
800                  * Nothing special, simply use tap(4) as backend
801                  */
802                 return 0;
803         }
804
805         if (inet_pton(AF_INET, tok, &tap_addr) > 0) {
806                 /*
807                  * tap(4)'s address is supplied
808                  */
809                 ifbridge = NULL;
810
811                 /*
812                  * If there is next token, then it may be pseudo
813                  * netif's address or netmask len for tap(4)
814                  */
815                 next_netif_addr = 0;
816         } else {
817                 /*
818                  * Not tap(4)'s address, assume it as a bridge(4)
819                  * iface name
820                  */
821                 tap_addr = 0;
822                 ifbridge = tok;
823
824                 /*
825                  * If there is next token, then it must be pseudo
826                  * netif's address
827                  */
828                 next_netif_addr = 1;
829         }
830
831         netmask = netif_addr = 0;
832
833         tok = strtok(NULL, ":/");
834         if (tok == NULL)
835                 goto back;
836
837         if (inet_pton(AF_INET, tok, &netif_addr) <= 0) {
838                 if (next_netif_addr) {
839                         warnx("Invalid pseudo netif address: %s", tok);
840                         return -1;
841                 }
842                 netif_addr = 0;
843
844                 /*
845                  * Current token is not address, then it must be netmask len
846                  */
847                 masklen_str = tok;
848         } else {
849                 /*
850                  * Current token is pseudo netif address, if there is next token
851                  * it must be netmask len
852                  */
853                 masklen_str = strtok(NULL, "/");
854         }
855
856         /* Calculate netmask */
857         if (masklen_str != NULL) {
858                 u_long masklen;
859
860                 masklen = strtoul(masklen_str, NULL, 10);
861                 if (masklen < 32 && masklen > 0) {
862                         netmask = htonl(~((1LL << (32 - masklen)) - 1)
863                                         & 0xffffffff);
864                 } else {
865                         warnx("Invalid netmask len: %lu", masklen);
866                         return -1;
867                 }
868         }
869
870         /* Make sure there is no more token left */
871         if (strtok(NULL, ":/") != NULL) {
872                 warnx("Invalid argument to '-I'");
873                 return -1;
874         }
875
876 back:
877         if (ifbridge == NULL) {
878                 /* Set tap(4) address/netmask */
879                 if (netif_set_tapaddr(tap_unit, tap_addr, netmask, s) < 0)
880                         return -1;
881         } else {
882                 /* Tie tap(4) to bridge(4) */
883                 if (netif_add_tap2brg(tap_unit, ifbridge, s) < 0)
884                         return -1;
885         }
886
887         *addr = netif_addr;
888         *mask = netmask;
889         return 0;
890 }
891
892 /*
893  * NetifInfo[] will be filled for pseudo netif initialization.
894  * NetifNum will be bumped to reflect the number of valid entries
895  * in NetifInfo[].
896  */
897 static
898 void
899 init_netif(char *netifExp[], int netifExpNum)
900 {
901         int i, s;
902
903         if (netifExpNum == 0)
904                 return;
905
906         s = socket(AF_INET, SOCK_DGRAM, 0);     /* for ioctl(SIOC) */
907         if (s < 0)
908                 return;
909
910         for (i = 0; i < netifExpNum; ++i) {
911                 struct vknetif_info *info;
912                 in_addr_t netif_addr, netif_mask;
913                 int tap_fd, tap_unit;
914                 char *netif;
915
916                 netif = strtok(netifExp[i], ":");
917                 if (netif == NULL) {
918                         warnx("Invalide argument to '-I'");
919                         continue;
920                 }
921
922                 /*
923                  * Open tap(4) device file and bring up the
924                  * corresponding interface
925                  */
926                 tap_fd = netif_open_tap(netif, &tap_unit, s);
927                 if (tap_fd < 0)
928                         continue;
929
930                 /*
931                  * Initialize tap(4) and get address/netmask
932                  * for pseudo netif
933                  *
934                  * NB: Rest part of netifExp[i] is passed
935                  *     to netif_init_tap() implicitly.
936                  */
937                 if (netif_init_tap(tap_unit, &netif_addr, &netif_mask, s) < 0) {
938                         /*
939                          * NB: Closing tap(4) device file will bring
940                          *     down the corresponding interface
941                          */
942                         close(tap_fd);
943                         continue;
944                 }
945
946                 info = &NetifInfo[NetifNum];
947                 info->tap_fd = tap_fd;
948                 info->tap_unit = tap_unit;
949                 info->netif_addr = netif_addr;
950                 info->netif_mask = netif_mask;
951
952                 NetifNum++;
953                 if (NetifNum >= VKNETIF_MAX)    /* XXX will this happen? */
954                         break;
955         }
956         close(s);
957 }
958
959 static
960 void
961 usage(const char *ctl)
962 {
963         
964 }
965
966 void
967 cpu_reset(void)
968 {
969         kprintf("cpu reset\n");
970         exit(0);
971 }
972
973 void
974 cpu_halt(void)
975 {
976         kprintf("cpu halt\n");
977         for (;;)
978                 __asm__ __volatile("hlt");
979 }