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