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