2 * Copyright (c) 2006 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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
35 #include <sys/types.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
41 #include <sys/random.h>
42 #include <sys/vkernel.h>
44 #include <sys/reboot.h>
46 #include <sys/msgbuf.h>
47 #include <sys/vmspace.h>
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <sys/sysctl.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_map.h>
54 #include <sys/mplock2.h>
56 #include <machine/cpu.h>
57 #include <machine/globaldata.h>
58 #include <machine/tls.h>
59 #include <machine/md_var.h>
60 #include <machine/vmparam.h>
61 #include <cpu/specialreg.h>
64 #include <net/if_arp.h>
65 #include <net/ethernet.h>
66 #include <net/bridge/if_bridgevar.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <net/if_var.h>
83 vm_paddr_t phys_avail[16];
85 vm_paddr_t Maxmem_bytes;
88 struct vkdisk_info DiskInfo[VKDISK_MAX];
90 struct vknetif_info NetifInfo[VKNETIF_MAX];
96 vm_offset_t virtual_start;
97 vm_offset_t virtual_end;
98 vm_offset_t virtual2_start;
99 vm_offset_t virtual2_end;
100 vm_offset_t kernel_vm_end;
101 vm_offset_t crashdumpmap;
102 vm_offset_t clean_sva;
103 vm_offset_t clean_eva;
104 struct msgbuf *msgbufp;
107 vpte_t *KernelPTA; /* Warning: Offset for direct VA translation */
108 void *dmap_min_address;
109 u_int cpu_feature; /* XXX */
111 int64_t tsc_frequency;
112 int optcpus; /* number of cpus - see mp_start() */
113 int lwp_cpu_lock; /* if/how to lock virtual CPUs to real CPUs */
114 int real_ncpus; /* number of real CPUs */
115 int next_cpu; /* next real CPU to lock a virtual CPU to */
116 int vkernel_b_arg; /* -b argument - no of logical CPU bits - only SMP */
117 int vkernel_B_arg; /* -B argument - no of core bits - only SMP */
119 struct privatespace *CPU_prvspace;
121 static struct trapframe proc0_tf;
122 static void *proc0paddr;
124 static void init_sys_memory(char *imageFile);
125 static void init_kern_memory(void);
126 static void init_globaldata(void);
127 static void init_vkernel(void);
128 static void init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type);
129 static void init_netif(char *netifExp[], int netifFileNum);
130 static void writepid(void);
131 static void cleanpid(void);
132 static int unix_connect(const char *path);
133 static void usage_err(const char *ctl, ...);
134 static void usage_help(_Bool);
135 static void init_locks(void);
138 static char **save_av;
141 * Kernel startup for virtual kernels - standard main()
144 main(int ac, char **av)
146 char *memImageFile = NULL;
147 char *netifFile[VKNETIF_MAX];
148 char *diskFile[VKDISK_MAX];
149 char *cdFile[VKDISK_MAX];
154 int netifFileNum = 0;
157 int bootOnDisk = -1; /* set below to vcd (0) or vkd (1) */
165 int real_vkernel_enable;
180 kernel_mem_readonly = 1;
184 lwp_cpu_lock = LCL_NONE;
186 real_vkernel_enable = 0;
187 vsize = sizeof(real_vkernel_enable);
188 sysctlbyname("vm.vkernel_enable", &real_vkernel_enable, &vsize, NULL,0);
190 if (real_vkernel_enable == 0) {
191 errx(1, "vm.vkernel_enable is 0, must be set "
192 "to 1 to execute a vkernel!");
196 vsize = sizeof(real_ncpus);
197 sysctlbyname("hw.ncpu", &real_ncpus, &vsize, NULL, 0);
202 while ((c = getopt(ac, av, "c:hsvl:m:n:r:e:i:p:I:Ub:B:")) != -1) {
206 * name=value:name=value:name=value...
209 * Allow values to be quoted but note that shells
210 * may remove the quotes, so using this feature
211 * to embed colons may require a backslash.
218 kern_envp = malloc(kenv_size);
219 if (kern_envp == NULL)
220 errx(1, "Couldn't allocate %zd bytes for kern_envp", kenv_size);
222 kenv_size2 = kenv_size + n + 1;
224 if ((tmp = realloc(kern_envp, kenv_size2)) == NULL)
225 errx(1, "Couldn't reallocate %zd bytes for kern_envp", kenv_size2);
227 kenv_size = kenv_size2;
230 for (i = 0, j = pos; i < n; ++i) {
231 if (optarg[i] == '"')
233 else if (optarg[i] == '\'')
235 else if (isq == 0 && optarg[i] == ':')
238 kern_envp[j++] = optarg[i];
245 boothowto |= RB_SINGLE;
251 memImageFile = optarg;
254 if (netifFileNum < VKNETIF_MAX)
255 netifFile[netifFileNum++] = strdup(optarg);
260 if (diskFileNum + cdFileNum < VKDISK_MAX)
261 diskFile[diskFileNum++] = strdup(optarg);
266 if (diskFileNum + cdFileNum < VKDISK_MAX)
267 cdFile[cdFileNum++] = strdup(optarg);
270 Maxmem_bytes = strtoull(optarg, &suffix, 0);
287 usage_err("Bad maxmem option");
295 if (strncmp("map", optarg, 3) == 0) {
296 lwp_cpu_lock = LCL_PER_CPU;
297 if (optarg[3] == ',') {
298 next_cpu = strtol(optarg+4, &endp, 0);
300 usage_err("Bad target CPU number at '%s'", endp);
304 if (next_cpu < 0 || next_cpu > real_ncpus - 1)
305 usage_err("Bad target CPU, valid range is 0-%d", real_ncpus - 1);
306 } else if (strncmp("any", optarg, 3) == 0) {
307 lwp_cpu_lock = LCL_NONE;
309 lwp_cpu_lock = LCL_SINGLE_CPU;
310 next_cpu = strtol(optarg, &endp, 0);
312 usage_err("Bad target CPU number at '%s'", endp);
313 if (next_cpu < 0 || next_cpu > real_ncpus - 1)
314 usage_err("Bad target CPU, valid range is 0-%d", real_ncpus - 1);
319 * This value is set up by mp_start(), don't just
322 tok = strtok(optarg, ":");
323 optcpus = strtol(tok, NULL, 0);
324 if (optcpus < 1 || optcpus > MAXCPU)
325 usage_err("Bad ncpus, valid range is 1-%d", MAXCPU);
327 /* :lbits argument */
328 tok = strtok(NULL, ":");
330 vkernel_b_arg = strtol(tok, NULL, 0);
332 /* :cbits argument */
333 tok = strtok(NULL, ":");
335 vkernel_B_arg = strtol(tok, NULL, 0);
344 kernel_mem_readonly = 0;
356 init_sys_memory(memImageFile);
368 vsize = sizeof(tsc_present);
369 sysctlbyname("hw.tsc_present", &tsc_present, &vsize, NULL, 0);
370 vsize = sizeof(tsc_frequency);
371 sysctlbyname("hw.tsc_frequency", &tsc_frequency, &vsize, NULL, 0);
373 cpu_feature |= CPUID_TSC;
378 vsize = sizeof(supports_sse);
380 sysctlbyname("hw.instruction_sse", &supports_sse, &vsize, NULL, 0);
381 init_fpu(supports_sse);
383 cpu_feature |= CPUID_SSE | CPUID_FXSR;
386 * We boot from the first installed disk.
388 if (bootOnDisk == 1) {
389 init_disk(diskFile, diskFileNum, VKD_DISK);
390 init_disk(cdFile, cdFileNum, VKD_CD);
392 init_disk(cdFile, cdFileNum, VKD_CD);
393 init_disk(diskFile, diskFileNum, VKD_DISK);
395 init_netif(netifFile, netifFileNum);
403 * Initialize system memory. This is the virtual kernel's 'RAM'.
407 init_sys_memory(char *imageFile)
414 * Figure out the system memory image size. If an image file was
415 * specified and -m was not specified, use the image file's size.
417 if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
418 Maxmem_bytes = (vm_paddr_t)st.st_size;
419 if ((imageFile == NULL || stat(imageFile, &st) < 0) &&
421 errx(1, "Cannot create new memory file %s unless "
422 "system memory size is specified with -m",
428 * Maxmem must be known at this time
430 if (Maxmem_bytes < 64 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
431 errx(1, "Bad maxmem specification: 64MB minimum, "
432 "multiples of %dMB only",
433 SEG_SIZE / 1024 / 1024);
438 * Generate an image file name if necessary, then open/create the
439 * file exclusively locked. Do not allow multiple virtual kernels
440 * to use the same image file.
442 * Don't iterate through a million files if we do not have write
443 * access to the directory, stop if our open() failed on a
444 * non-existant file. Otherwise opens can fail for any number
446 if (imageFile == NULL) {
447 for (i = 0; i < 1000000; ++i) {
448 asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
450 O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
451 if (fd < 0 && stat(imageFile, &st) == 0) {
458 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
460 fprintf(stderr, "Using memory file: %s\n", imageFile);
461 if (fd < 0 || fstat(fd, &st) < 0) {
462 err(1, "Unable to open/create %s", imageFile);
467 * Truncate or extend the file as necessary. Clean out the contents
468 * of the file, we want it to be full of holes so we don't waste
469 * time reading in data from an old file that we no longer care
473 ftruncate(fd, Maxmem_bytes);
476 Maxmem = Maxmem_bytes >> PAGE_SHIFT;
481 * Initialize kernel memory. This reserves kernel virtual memory by using
487 init_kern_memory(void)
492 char *topofstack = &dummy;
497 * Memory map our kernel virtual memory space. Note that the
498 * kernel image itself is not made part of this memory for the
501 * The memory map must be segment-aligned so we can properly
504 * If the system kernel has a different MAXDSIZ, it might not
505 * be possible to map kernel memory in its prefered location.
506 * Try a number of different locations.
508 try = (void *)(512UL << 30);
510 while ((char *)try + KERNEL_KVA_SIZE < topofstack) {
511 base = mmap(try, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
512 MAP_FILE|MAP_SHARED|MAP_VPAGETABLE,
513 MemImageFd, (off_t)try);
516 if (base != MAP_FAILED)
517 munmap(base, KERNEL_KVA_SIZE);
518 try = (char *)try + (512UL << 30);
521 err(1, "Unable to mmap() kernel virtual memory!");
524 madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
525 KvaStart = (vm_offset_t)base;
526 KvaSize = KERNEL_KVA_SIZE;
527 KvaEnd = KvaStart + KvaSize;
529 /* cannot use kprintf yet */
530 printf("KVM mapped at %p-%p\n", (void *)KvaStart, (void *)KvaEnd);
533 dmap_min_address = mmap(0, DMAP_SIZE, PROT_READ|PROT_WRITE,
534 MAP_NOCORE|MAP_NOSYNC|MAP_SHARED,
536 if (dmap_min_address == MAP_FAILED) {
537 err(1, "Unable to mmap() kernel DMAP region!");
542 * Bootstrap the kernel_pmap
545 pmap_bootstrap((vm_paddr_t *)&firstfree, (int64_t)base);
547 mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
548 0 | VPTE_R | VPTE_W | VPTE_V);
551 * phys_avail[] represents unallocated physical memory. MI code
552 * will use phys_avail[] to create the vm_page array.
554 phys_avail[0] = (vm_paddr_t)firstfree;
555 phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
556 phys_avail[1] = Maxmem_bytes;
560 * (virtual_start, virtual_end) represent unallocated kernel virtual
561 * memory. MI code will create kernel_map using these parameters.
563 virtual_start = KvaStart + (long)firstfree;
564 virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
565 virtual_end = KvaStart + KERNEL_KVA_SIZE;
569 * pmap_growkernel() will set the correct value.
574 * Allocate space for process 0's UAREA.
576 proc0paddr = (void *)virtual_start;
577 for (i = 0; i < UPAGES; ++i) {
578 pmap_kenter_quick(virtual_start, phys_avail[0]);
579 virtual_start += PAGE_SIZE;
580 phys_avail[0] += PAGE_SIZE;
586 crashdumpmap = virtual_start;
587 virtual_start += MAXDUMPPGS * PAGE_SIZE;
590 * msgbufp maps the system message buffer
592 assert((MSGBUF_SIZE & PAGE_MASK) == 0);
593 msgbufp = (void *)virtual_start;
594 for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
595 pmap_kenter_quick(virtual_start, phys_avail[0]);
596 virtual_start += PAGE_SIZE;
597 phys_avail[0] += PAGE_SIZE;
599 msgbufinit(msgbufp, MSGBUF_SIZE);
602 * used by kern_memio for /dev/mem access
604 ptvmmap = (caddr_t)virtual_start;
605 virtual_start += PAGE_SIZE;
609 * Map the per-cpu globaldata for cpu #0. Allocate the space using
610 * virtual_start and phys_avail[0]
614 init_globaldata(void)
621 * Reserve enough KVA to cover possible cpus. This is a considerable
622 * amount of KVA since the privatespace structure includes two
623 * whole page table mappings.
625 virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
626 CPU_prvspace = (void *)virtual_start;
627 virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
630 * Allocate enough physical memory to cover the mdglobaldata
631 * portion of the space and the idle stack and map the pages
632 * into KVA. For cpu #0 only.
634 for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
636 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
637 pmap_kenter_quick(va, pa);
638 phys_avail[0] += PAGE_SIZE;
640 for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
642 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
643 pmap_kenter_quick(va, pa);
644 phys_avail[0] += PAGE_SIZE;
648 * Setup the %gs for cpu #0. The mycpu macro works after this
649 * point. Note that %fs is used by pthreads.
651 tls_set_gs(&CPU_prvspace[0], sizeof(struct privatespace));
656 * Initialize pool tokens and other necessary locks
663 * Get the initial mplock with a count of 1 for the BSP.
664 * This uses a LOGICAL cpu ID, ie BSP == 0.
666 cpu_get_initial_mplock();
668 /* our token pool needs to work early */
669 lwkt_token_pool_init();
675 * Initialize very low level systems including thread0, proc0, etc.
681 struct mdglobaldata *gd;
683 gd = &CPU_prvspace[0].mdglobaldata;
684 bzero(gd, sizeof(*gd));
686 gd->mi.gd_curthread = &thread0;
687 thread0.td_gd = &gd->mi;
689 ncpus2 = 1; /* rounded down power of 2 */
690 ncpus_fit = 1; /* rounded up power of 2 */
691 /* ncpus2_mask and ncpus_fit_mask are 0 */
693 gd->mi.gd_prvspace = &CPU_prvspace[0];
694 mi_gdinit(&gd->mi, 0);
696 mi_proc0init(&gd->mi, proc0paddr);
697 lwp0.lwp_md.md_regs = &proc0_tf;
702 #if 0 /* #ifdef DDB */
704 if (boothowto & RB_KDB)
705 Debugger("Boot flags requested debugger");
709 initializecpu(); /* Initialize CPU registers */
711 init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
715 * Map the message buffer
717 for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
718 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
719 msgbufinit(msgbufp, MSGBUF_SIZE);
722 thread0.td_pcb_cr3 ... MMU
723 lwp0.lwp_md.md_regs = &proc0_tf;
728 * Filesystem image paths for the virtual kernel are optional.
729 * If specified they each should point to a disk image,
730 * the first of which will become the root disk.
732 * The virtual kernel caches data from our 'disk' just like a normal kernel,
733 * so we do not really want the real kernel to cache the data too. Use
734 * O_DIRECT to remove the duplication.
738 init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type)
743 if (diskFileNum == 0)
746 for(i=0; i < diskFileNum; i++){
751 warnx("Invalid argument to '-r'");
755 * Check for a serial number for the virtual disk
756 * passed from the command line.
761 if (DiskNum < VKDISK_MAX) {
763 struct vkdisk_info* info = NULL;
767 if (type == VKD_DISK)
768 fd = open(fname, O_RDWR|O_DIRECT, 0644);
770 fd = open(fname, O_RDONLY|O_DIRECT, 0644);
771 if (fd < 0 || fstat(fd, &st) < 0) {
772 err(1, "Unable to open/create %s", fname);
775 if (S_ISREG(st.st_mode)) {
776 if (flock(fd, LOCK_EX|LOCK_NB) < 0) {
777 errx(1, "Disk image %s is already "
783 info = &DiskInfo[DiskNum];
789 memcpy(info->fname, fname, l);
792 if ((info->serno = malloc(SERNOLEN)) != NULL)
793 strlcpy(info->serno, serno, SERNOLEN);
795 warnx("Couldn't allocate memory for the operation");
799 if (type == VKD_CD) {
800 rootdevnames[0] = "cd9660:vcd0a";
801 } else if (type == VKD_DISK) {
802 rootdevnames[0] = "ufs:vkd0s0a";
803 rootdevnames[1] = "ufs:vkd0s1a";
809 warnx("vkd%d (%s) > VKDISK_MAX", DiskNum, fname);
817 netif_set_tapflags(int tap_unit, int f, int s)
822 bzero(&ifr, sizeof(ifr));
824 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
825 if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
826 warn("tap%d: ioctl(SIOCGIFFLAGS) failed", tap_unit);
833 * If the flags are already set/cleared, then we return
834 * immediately to avoid extra syscalls
836 flags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
840 if ((flags & f) == 0)
851 * Fix up ifreq.ifr_name, since it may be trashed
852 * in previous ioctl(SIOCGIFFLAGS)
854 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
856 ifr.ifr_flags = flags & 0xffff;
857 ifr.ifr_flagshigh = flags >> 16;
858 if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
859 warn("tap%d: ioctl(SIOCSIFFLAGS) failed", tap_unit);
867 netif_set_tapaddr(int tap_unit, in_addr_t addr, in_addr_t mask, int s)
869 struct ifaliasreq ifra;
870 struct sockaddr_in *in;
872 bzero(&ifra, sizeof(ifra));
873 snprintf(ifra.ifra_name, sizeof(ifra.ifra_name), "tap%d", tap_unit);
876 in = (struct sockaddr_in *)&ifra.ifra_addr;
877 in->sin_family = AF_INET;
878 in->sin_len = sizeof(*in);
879 in->sin_addr.s_addr = addr;
883 in = (struct sockaddr_in *)&ifra.ifra_mask;
884 in->sin_len = sizeof(*in);
885 in->sin_addr.s_addr = mask;
888 if (ioctl(s, SIOCAIFADDR, &ifra) < 0) {
889 warn("tap%d: ioctl(SIOCAIFADDR) failed", tap_unit);
897 netif_add_tap2brg(int tap_unit, const char *ifbridge, int s)
902 bzero(&ifbr, sizeof(ifbr));
903 snprintf(ifbr.ifbr_ifsname, sizeof(ifbr.ifbr_ifsname),
906 bzero(&ifd, sizeof(ifd));
907 strlcpy(ifd.ifd_name, ifbridge, sizeof(ifd.ifd_name));
908 ifd.ifd_cmd = BRDGADD;
909 ifd.ifd_len = sizeof(ifbr);
910 ifd.ifd_data = &ifbr;
912 if (ioctl(s, SIOCSDRVSPEC, &ifd) < 0) {
914 * 'errno == EEXIST' means that the tap(4) is already
915 * a member of the bridge(4)
917 if (errno != EEXIST) {
918 warn("ioctl(%s, SIOCSDRVSPEC) failed", ifbridge);
925 #define TAPDEV_OFLAGS (O_RDWR | O_NONBLOCK)
928 * Locate the first unused tap(4) device file if auto mode is requested,
929 * or open the user supplied device file, and bring up the corresponding
932 * NOTE: Only tap(4) device file is supported currently
936 netif_open_tap(const char *netif, int *tap_unit, int s)
938 char tap_dev[MAXPATHLEN];
945 if (strcmp(netif, "auto") == 0) {
947 * Find first unused tap(4) device file
949 tap_fd = open("/dev/tap", TAPDEV_OFLAGS);
951 warnc(errno, "Unable to find a free tap(4)");
956 * User supplied tap(4) device file or unix socket.
958 if (netif[0] == '/') /* Absolute path */
959 strlcpy(tap_dev, netif, sizeof(tap_dev));
961 snprintf(tap_dev, sizeof(tap_dev), "/dev/%s", netif);
963 tap_fd = open(tap_dev, TAPDEV_OFLAGS);
966 * If we cannot open normally try to connect to it.
969 tap_fd = unix_connect(tap_dev);
972 warn("Unable to open %s", tap_dev);
978 * Check whether the device file is a tap(4)
980 if (fstat(tap_fd, &st) < 0) {
982 } else if (S_ISCHR(st.st_mode)) {
983 dname = fdevname(tap_fd);
985 dname = strstr(dname, "tap");
988 * Bring up the corresponding tap(4) interface
990 *tap_unit = strtol(dname + 3, NULL, 10);
991 printf("TAP UNIT %d\n", *tap_unit);
992 if (netif_set_tapflags(*tap_unit, IFF_UP, s) == 0)
999 } else if (S_ISSOCK(st.st_mode)) {
1001 * Special socket connection (typically to vknet). We
1002 * do not have to do anything.
1010 warnx("%s is not a tap(4) device or socket", tap_dev);
1019 unix_connect(const char *path)
1021 struct sockaddr_un sunx;
1024 int sndbuf = 262144;
1027 snprintf(sunx.sun_path, sizeof(sunx.sun_path), "%s", path);
1028 len = offsetof(struct sockaddr_un, sun_path[strlen(sunx.sun_path)]);
1029 ++len; /* include nul */
1030 sunx.sun_family = AF_UNIX;
1033 net_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
1036 if (connect(net_fd, (void *)&sunx, len) < 0) {
1040 setsockopt(net_fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
1041 if (fstat(net_fd, &st) == 0)
1042 printf("Network socket buffer: %d bytes\n", st.st_blksize);
1043 fcntl(net_fd, F_SETFL, O_NONBLOCK);
1049 #undef TAPDEV_OFLAGS
1052 * Following syntax is supported,
1053 * 1) x.x.x.x tap(4)'s address is x.x.x.x
1055 * 2) x.x.x.x/z tap(4)'s address is x.x.x.x
1056 * tap(4)'s netmask len is z
1058 * 3) x.x.x.x:y.y.y.y tap(4)'s address is x.x.x.x
1059 * pseudo netif's address is y.y.y.y
1061 * 4) x.x.x.x:y.y.y.y/z tap(4)'s address is x.x.x.x
1062 * pseudo netif's address is y.y.y.y
1063 * tap(4) and pseudo netif's netmask len are z
1065 * 5) bridgeX tap(4) will be added to bridgeX
1067 * 6) bridgeX:y.y.y.y tap(4) will be added to bridgeX
1068 * pseudo netif's address is y.y.y.y
1070 * 7) bridgeX:y.y.y.y/z tap(4) will be added to bridgeX
1071 * pseudo netif's address is y.y.y.y
1072 * pseudo netif's netmask len is z
1076 netif_init_tap(int tap_unit, in_addr_t *addr, in_addr_t *mask, int s)
1078 in_addr_t tap_addr, netmask, netif_addr;
1079 int next_netif_addr;
1080 char *tok, *masklen_str, *ifbridge;
1085 tok = strtok(NULL, ":/");
1088 * Nothing special, simply use tap(4) as backend
1093 if (inet_pton(AF_INET, tok, &tap_addr) > 0) {
1095 * tap(4)'s address is supplied
1100 * If there is next token, then it may be pseudo
1101 * netif's address or netmask len for tap(4)
1103 next_netif_addr = 0;
1106 * Not tap(4)'s address, assume it as a bridge(4)
1113 * If there is next token, then it must be pseudo
1116 next_netif_addr = 1;
1119 netmask = netif_addr = 0;
1121 tok = strtok(NULL, ":/");
1125 if (inet_pton(AF_INET, tok, &netif_addr) <= 0) {
1126 if (next_netif_addr) {
1127 warnx("Invalid pseudo netif address: %s", tok);
1133 * Current token is not address, then it must be netmask len
1138 * Current token is pseudo netif address, if there is next token
1139 * it must be netmask len
1141 masklen_str = strtok(NULL, "/");
1144 /* Calculate netmask */
1145 if (masklen_str != NULL) {
1148 masklen = strtoul(masklen_str, NULL, 10);
1149 if (masklen < 32 && masklen > 0) {
1150 netmask = htonl(~((1LL << (32 - masklen)) - 1)
1153 warnx("Invalid netmask len: %lu", masklen);
1158 /* Make sure there is no more token left */
1159 if (strtok(NULL, ":/") != NULL) {
1160 warnx("Invalid argument to '-I'");
1167 } else if (ifbridge == NULL) {
1168 /* Set tap(4) address/netmask */
1169 if (netif_set_tapaddr(tap_unit, tap_addr, netmask, s) < 0)
1172 /* Tie tap(4) to bridge(4) */
1173 if (netif_add_tap2brg(tap_unit, ifbridge, s) < 0)
1183 * NetifInfo[] will be filled for pseudo netif initialization.
1184 * NetifNum will be bumped to reflect the number of valid entries
1189 init_netif(char *netifExp[], int netifExpNum)
1194 if (netifExpNum == 0)
1197 s = socket(AF_INET, SOCK_DGRAM, 0); /* for ioctl(SIOC) */
1201 for (i = 0; i < netifExpNum; ++i) {
1202 struct vknetif_info *info;
1203 in_addr_t netif_addr, netif_mask;
1204 int tap_fd, tap_unit;
1207 /* Extract MAC address if there is one */
1211 netif = strtok(netifExp[i], ":");
1212 if (netif == NULL) {
1213 warnx("Invalid argument to '-I'");
1218 * Open tap(4) device file and bring up the
1219 * corresponding interface
1221 tap_fd = netif_open_tap(netif, &tap_unit, s);
1226 * Initialize tap(4) and get address/netmask
1229 * NB: Rest part of netifExp[i] is passed
1230 * to netif_init_tap() implicitly.
1232 if (netif_init_tap(tap_unit, &netif_addr, &netif_mask, s) < 0) {
1234 * NB: Closing tap(4) device file will bring
1235 * down the corresponding interface
1241 info = &NetifInfo[NetifNum];
1242 bzero(info, sizeof(*info));
1243 info->tap_fd = tap_fd;
1244 info->tap_unit = tap_unit;
1245 info->netif_addr = netif_addr;
1246 info->netif_mask = netif_mask;
1248 * If tmp isn't NULL it means a MAC could have been
1249 * specified so attempt to convert it.
1250 * Setting enaddr to NULL will tell vke_attach() we
1251 * need a pseudo-random MAC address.
1254 if ((info->enaddr = malloc(ETHER_ADDR_LEN)) == NULL)
1255 warnx("Couldn't allocate memory for the operation");
1257 if ((kether_aton(tmp, info->enaddr)) == NULL) {
1259 info->enaddr = NULL;
1265 if (NetifNum >= VKNETIF_MAX) /* XXX will this happen? */
1272 * Create the pid file and leave it open and locked while the vkernel is
1273 * running. This allows a script to use /usr/bin/lockf to probe whether
1274 * a vkernel is still running (so as not to accidently kill an unrelated
1275 * process from a stale pid file).
1284 if (pid_file != NULL) {
1285 snprintf(buf, sizeof(buf), "%ld\n", (long)getpid());
1286 fd = open(pid_file, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0666);
1288 if (errno == EWOULDBLOCK) {
1289 perror("Failed to lock pidfile, "
1290 "vkernel already running");
1292 perror("Failed to create pidfile");
1297 write(fd, buf, strlen(buf));
1298 /* leave the file open to maintain the lock */
1306 if (pid_file != NULL) {
1307 if (unlink(pid_file) < 0)
1308 perror("Warning: couldn't remove pidfile");
1314 usage_err(const char *ctl, ...)
1319 vfprintf(stderr, ctl, va);
1321 fprintf(stderr, "\n");
1327 usage_help(_Bool help)
1329 fprintf(stderr, "Usage: %s [-hsUv] [-c file] [-e name=value:name=value:...]\n"
1330 "\t[-i file] [-I interface[:address1[:address2][/netmask]]] [-l cpulock]\n"
1331 "\t[-m size] [-n numcpus[:lbits[:cbits]]]\n"
1332 "\t[-p file] [-r file]\n", save_av[0]);
1335 fprintf(stderr, "\nArguments:\n"
1336 "\t-c\tSpecify a readonly CD-ROM image file to be used by the kernel.\n"
1337 "\t-e\tSpecify an environment to be used by the kernel.\n"
1338 "\t-h\tThis list of options.\n"
1339 "\t-i\tSpecify a memory image file to be used by the virtual kernel.\n"
1340 "\t-I\tCreate a virtual network device.\n"
1341 "\t-l\tSpecify which, if any, real CPUs to lock virtual CPUs to.\n"
1342 "\t-m\tSpecify the amount of memory to be used by the kernel in bytes.\n"
1343 "\t-n\tSpecify the number of CPUs and the topology you wish to emulate:\n"
1344 "\t \t- numcpus - number of cpus\n"
1345 "\t \t- :lbits - specify the number of bits within APICID(=CPUID) needed for representing\n"
1346 "\t \t the logical ID. Controls the number of threads/core (0bits - 1 thread, 1bit - 2 threads).\n"
1347 "\t \t- :cbits - specify the number of bits within APICID(=CPUID) needed for representing\n"
1348 "\t \t the core ID. Controls the number of core/package (0bits - 1 core, 1bit - 2 cores).\n"
1349 "\t-p\tSpecify a file in which to store the process ID.\n"
1350 "\t-r\tSpecify a R/W disk image file to be used by the kernel.\n"
1351 "\t-s\tBoot into single-user mode.\n"
1352 "\t-U\tEnable writing to kernel memory and module loading.\n"
1353 "\t-v\tTurn on verbose booting.\n");
1361 kprintf("cpu reset, rebooting vkernel\n");
1364 execv(save_av[0], save_av);
1370 kprintf("cpu halt, exiting vkernel\n");
1378 switch(lwp_cpu_lock) {
1381 kprintf("Locking CPU%d to real cpu %d\n",
1383 usched_set(getpid(), USCHED_SET_CPU, &next_cpu, sizeof(next_cpu));
1385 if (next_cpu >= real_ncpus)
1388 case LCL_SINGLE_CPU:
1390 kprintf("Locking CPU%d to real cpu %d\n",
1392 usched_set(getpid(), USCHED_SET_CPU, &next_cpu, sizeof(next_cpu));
1395 /* do not map virtual cpus to real cpus */
1401 * Allocate and free memory for module loading. The loaded module
1402 * has to be placed somewhere near the current kernel binary load
1403 * point or the relocations will not work.
1405 * I'm not sure why this isn't working.
1408 vkernel_module_memory_alloc(vm_offset_t *basep, size_t bytes)
1410 kprintf("module loading for vkernel64's not currently supported\n");
1416 xtra = (PAGE_SIZE - (vm_offset_t)sbrk(0)) & PAGE_MASK;
1417 *basep = (vm_offset_t)sbrk(xtra + bytes) + xtra;
1418 bzero((void *)*basep, bytes);
1420 *basep = (vm_offset_t)mmap((void *)0x000000000, bytes,
1421 PROT_READ|PROT_WRITE|PROT_EXEC,
1422 MAP_ANON|MAP_SHARED, -1, 0);
1423 if ((void *)*basep == MAP_FAILED)
1426 kprintf("basep %p %p %zd\n",
1427 (void *)vkernel_module_memory_alloc, (void *)*basep, bytes);
1433 vkernel_module_memory_free(vm_offset_t base, size_t bytes)
1437 munmap((void *)base, bytes);