vmrunkernel: allow loading of an SMBIOS table
[akaros.git] / tests / vmm / vmrunkernel.c
index 6a86284..91bef23 100644 (file)
@@ -6,13 +6,14 @@
 #include <parlib/arch/arch.h>
 #include <parlib/ros_debug.h>
 #include <unistd.h>
 #include <parlib/arch/arch.h>
 #include <parlib/ros_debug.h>
 #include <unistd.h>
+#include <gelf.h>
 #include <errno.h>
 #include <errno.h>
+#include <libelf.h>
 #include <dirent.h>
 #include <stdlib.h>
 #include <string.h>
 #include <ros/syscall.h>
 #include <sys/mman.h>
 #include <dirent.h>
 #include <stdlib.h>
 #include <string.h>
 #include <ros/syscall.h>
 #include <sys/mman.h>
-#include <vmm/coreboot_tables.h>
 #include <vmm/vmm.h>
 #include <vmm/acpi/acpi.h>
 #include <vmm/acpi/vmm_simple_dsdt.h>
 #include <vmm/vmm.h>
 #include <vmm/acpi/acpi.h>
 #include <vmm/acpi/vmm_simple_dsdt.h>
 #include <ros/vmm.h>
 #include <parlib/uthread.h>
 #include <vmm/linux_bootparam.h>
 #include <ros/vmm.h>
 #include <parlib/uthread.h>
 #include <vmm/linux_bootparam.h>
+#include <getopt.h>
 
 #include <vmm/virtio.h>
 
 #include <vmm/virtio.h>
+#include <vmm/virtio_blk.h>
 #include <vmm/virtio_mmio.h>
 #include <vmm/virtio_ids.h>
 #include <vmm/virtio_config.h>
 #include <vmm/virtio_console.h>
 #include <vmm/virtio_mmio.h>
 #include <vmm/virtio_ids.h>
 #include <vmm/virtio_config.h>
 #include <vmm/virtio_console.h>
+#include <vmm/virtio_net.h>
 #include <vmm/virtio_lguest_console.h>
 
 #include <vmm/sched.h>
 #include <vmm/virtio_lguest_console.h>
 
 #include <vmm/sched.h>
@@ -92,12 +96,13 @@ struct acpi_table_madt madt = {
        },
 
        .address = 0xfee00000ULL,
        },
 
        .address = 0xfee00000ULL,
+       .flags = 0,
 };
 
 struct acpi_madt_local_apic Apic0 = {.header = {.type = ACPI_MADT_TYPE_LOCAL_APIC, .length = sizeof(struct acpi_madt_local_apic)},
 };
 
 struct acpi_madt_local_apic Apic0 = {.header = {.type = ACPI_MADT_TYPE_LOCAL_APIC, .length = sizeof(struct acpi_madt_local_apic)},
-                                    .processor_id = 0, .id = 0};
+                                     .processor_id = 0, .id = 0, .lapic_flags = 1};
 struct acpi_madt_io_apic Apic1 = {.header = {.type = ACPI_MADT_TYPE_IO_APIC, .length = sizeof(struct acpi_madt_io_apic)},
 struct acpi_madt_io_apic Apic1 = {.header = {.type = ACPI_MADT_TYPE_IO_APIC, .length = sizeof(struct acpi_madt_io_apic)},
-                                 .id = 1, .address = 0xfec00000, .global_irq_base = 0};
+                                  .id = 0, .address = 0xfec00000, .global_irq_base = 0};
 struct acpi_madt_local_x2apic X2Apic0 = {
        .header = {
                .type = ACPI_MADT_TYPE_LOCAL_X2APIC,
 struct acpi_madt_local_x2apic X2Apic0 = {
        .header = {
                .type = ACPI_MADT_TYPE_LOCAL_X2APIC,
@@ -108,42 +113,12 @@ struct acpi_madt_local_x2apic X2Apic0 = {
 };
 
 struct acpi_madt_interrupt_override isor[] = {
 };
 
 struct acpi_madt_interrupt_override isor[] = {
-       /* I have no idea if it should be source irq 2, global 0, or global 2, source 0. Shit. */
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 2, .global_irq = 0, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 1, .global_irq = 1, .inti_flags = 0},
-       //{.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        //.bus = 0, .source_irq = 2, .global_irq = 2, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 3, .global_irq = 3, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 4, .global_irq = 4, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 5, .global_irq = 5, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 6, .global_irq = 6, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 7, .global_irq = 7, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 8, .global_irq = 8, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 9, .global_irq = 9, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 10, .global_irq = 10, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 11, .global_irq = 11, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 12, .global_irq = 12, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 13, .global_irq = 13, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 14, .global_irq = 14, .inti_flags = 0},
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 15, .global_irq = 15, .inti_flags = 0},
-       // VMMCP routes irq 32 to gsi 17
-       {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
-        .bus = 0, .source_irq = 32, .global_irq = 17, .inti_flags = 5},
+       /* From the ACPI Specification Version 6.1:
+        * For example, if your machine has the ISA Programmable Interrupt Timer
+        * (PIT) connected to ISA IRQ 0, but in APIC mode, it is connected to I/O
+        * APIC interrupt input 2, then you would need an Interrupt Source Override
+        * where the source entry is ‘0’ and the Global System Interrupt is ‘2.’
+        */
 };
 
 
 };
 
 
@@ -155,12 +130,13 @@ volatile int quit = 0;
 /* total hack. If the vm runs away we want to get control again. */
 unsigned int maxresume = (unsigned int) -1;
 
 /* total hack. If the vm runs away we want to get control again. */
 unsigned int maxresume = (unsigned int) -1;
 
-#define MiB 0x100000u
-#define GiB (1u<<30)
-#define GKERNBASE (16*MiB)
-#define KERNSIZE (128*MiB+GKERNBASE)
-uint8_t _kernel[KERNSIZE];
-
+#define MiB 0x100000ull
+#define GiB (1ull << 30)
+#define MinMemory (16*MiB)
+void *kernel;
+unsigned long long memsize = GiB;
+uintptr_t memstart = MinMemory;
+uintptr_t stack;
 unsigned long long *p512, *p1, *p2m;
 
 void **my_retvals;
 unsigned long long *p512, *p1, *p2m;
 
 void **my_retvals;
@@ -172,7 +148,6 @@ int resumeprompt = 0;
 //             vring_new_virtqueue(0, 512, 8192, 0, inpages, NULL, NULL, "test");
 
 void vapic_status_dump(FILE *f, void *vapic);
 //             vring_new_virtqueue(0, 512, 8192, 0, inpages, NULL, NULL, "test");
 
 void vapic_status_dump(FILE *f, void *vapic);
-static void set_posted_interrupt(int vector);
 
 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
 #error "Get a gcc newer than 4.4.0"
 
 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
 #error "Get a gcc newer than 4.4.0"
@@ -183,6 +158,7 @@ static void set_posted_interrupt(int vector);
 #define LOCK_PREFIX "lock "
 #define ADDR                           BITOP_ADDR(addr)
 static inline int test_and_set_bit(int nr, volatile unsigned long *addr);
 #define LOCK_PREFIX "lock "
 #define ADDR                           BITOP_ADDR(addr)
 static inline int test_and_set_bit(int nr, volatile unsigned long *addr);
+static int default_nic = 1;
 
 pthread_t timerthread_struct;
 
 
 pthread_t timerthread_struct;
 
@@ -193,10 +169,8 @@ void timer_thread(void *arg)
        while (1) {
                vector = ((uint32_t *)gpci.vapic_addr)[0x32] & 0xff;
                initial_count = ((uint32_t *)gpci.vapic_addr)[0x38];
        while (1) {
                vector = ((uint32_t *)gpci.vapic_addr)[0x32] & 0xff;
                initial_count = ((uint32_t *)gpci.vapic_addr)[0x38];
-               if (vector && initial_count) {
-                       set_posted_interrupt(vector);
-                       ros_syscall(SYS_vmm_poke_guest, 0, 0, 0, 0, 0, 0);
-               }
+               if (vector && initial_count)
+                       vmm_interrupt_guest(vm, 0, vector);
                uthread_usleep(100000);
        }
        fprintf(stderr, "SENDING TIMER\n");
                uthread_usleep(100000);
        }
        fprintf(stderr, "SENDING TIMER\n");
@@ -206,14 +180,14 @@ void timer_thread(void *arg)
 // FIXME.
 volatile int consdata = 0;
 
 // FIXME.
 volatile int consdata = 0;
 
-static void virtio_poke_guest(void)
+/* TODO: pass a core id to poke_guest */
+static void virtio_poke_guest(uint8_t vec)
 {
 {
-       set_posted_interrupt(0xE5);
-       ros_syscall(SYS_vmm_poke_guest, 0, 0, 0, 0, 0, 0);
+       vmm_interrupt_guest(vm, 0, vec);
 }
 
 static struct virtio_mmio_dev cons_mmio_dev = {
 }
 
 static struct virtio_mmio_dev cons_mmio_dev = {
-       .poke_guest = virtio_poke_guest
+       .poke_guest = virtio_poke_guest,
 };
 
 static struct virtio_console_config cons_cfg;
 };
 
 static struct virtio_console_config cons_cfg;
@@ -222,30 +196,95 @@ static struct virtio_console_config cons_cfg_d;
 static struct virtio_vq_dev cons_vqdev = {
        .name = "console",
        .dev_id = VIRTIO_ID_CONSOLE,
 static struct virtio_vq_dev cons_vqdev = {
        .name = "console",
        .dev_id = VIRTIO_ID_CONSOLE,
-       .dev_feat = ((uint64_t)1 << VIRTIO_F_VERSION_1)
-                                         | (1 << VIRTIO_RING_F_INDIRECT_DESC)
-                         ,
+       .dev_feat =
+       (1ULL << VIRTIO_F_VERSION_1) | (1 << VIRTIO_RING_F_INDIRECT_DESC),
        .num_vqs = 2,
        .cfg = &cons_cfg,
        .cfg_d = &cons_cfg_d,
        .cfg_sz = sizeof(struct virtio_console_config),
        .transport_dev = &cons_mmio_dev,
        .vqs = {
        .num_vqs = 2,
        .cfg = &cons_cfg,
        .cfg_d = &cons_cfg_d,
        .cfg_sz = sizeof(struct virtio_console_config),
        .transport_dev = &cons_mmio_dev,
        .vqs = {
-                       {
-                               .name = "cons_receiveq",
-                               .qnum_max = 64,
-                               .srv_fn = cons_receiveq_fn,
-                               .vqdev = &cons_vqdev
-                       },
-                       {
-                               .name = "cons_transmitq",
-                               .qnum_max = 64,
-                               .srv_fn = cons_transmitq_fn,
-                               .vqdev = &cons_vqdev
-                       },
-               }
+               {
+                       .name = "cons_receiveq",
+                       .qnum_max = 64,
+                       .srv_fn = cons_receiveq_fn,
+                       .vqdev = &cons_vqdev
+               },
+               {
+                       .name = "cons_transmitq",
+                       .qnum_max = 64,
+                       .srv_fn = cons_transmitq_fn,
+                       .vqdev = &cons_vqdev
+               },
+       }
+};
+
+static struct virtio_mmio_dev net_mmio_dev = {
+       .poke_guest = virtio_poke_guest,
+};
+
+static struct virtio_net_config net_cfg = {
+       .max_virtqueue_pairs = 1
+};
+static struct virtio_net_config net_cfg_d = {
+       .max_virtqueue_pairs = 1
+};
+
+static struct virtio_vq_dev net_vqdev = {
+       .name = "network",
+       .dev_id = VIRTIO_ID_NET,
+       .dev_feat = (1ULL << VIRTIO_F_VERSION_1 | 1 << VIRTIO_NET_F_MAC),
+
+       .num_vqs = 2,
+       .cfg = &net_cfg,
+       .cfg_d = &net_cfg_d,
+       .cfg_sz = sizeof(struct virtio_net_config),
+       .transport_dev = &net_mmio_dev,
+       .vqs = {
+               {
+                       .name = "net_receiveq",
+                       .qnum_max = 64,
+                       .srv_fn = net_receiveq_fn,
+                       .vqdev = &net_vqdev
+               },
+               {
+                       .name = "net_transmitq",
+                       .qnum_max = 64,
+                       .srv_fn = net_transmitq_fn,
+                       .vqdev = &net_vqdev
+               },
+       }
 };
 
 };
 
+static struct virtio_mmio_dev blk_mmio_dev = {
+       .poke_guest = virtio_poke_guest,
+};
+
+static struct virtio_blk_config blk_cfg = {
+};
+
+static struct virtio_blk_config blk_cfg_d = {
+};
+
+static struct virtio_vq_dev blk_vqdev = {
+       .name = "block",
+       .dev_id = VIRTIO_ID_BLOCK,
+       .dev_feat = (1ULL << VIRTIO_F_VERSION_1),
+
+       .num_vqs = 1,
+       .cfg = &blk_cfg,
+       .cfg_d = &blk_cfg_d,
+       .cfg_sz = sizeof(struct virtio_blk_config),
+       .transport_dev = &blk_mmio_dev,
+       .vqs = {
+               {
+                       .name = "blk_request",
+                       .qnum_max = 64,
+                       .srv_fn = blk_request,
+                       .vqdev = &blk_vqdev
+               },
+       }
+};
 
 void lowmem() {
        __asm__ __volatile__ (".section .lowmem, \"aw\"\n\tlow: \n\t.=0x1000\n\t.align 0x100000\n\t.previous\n");
 
 void lowmem() {
        __asm__ __volatile__ (".section .lowmem, \"aw\"\n\tlow: \n\t.=0x1000\n\t.align 0x100000\n\t.previous\n");
@@ -282,93 +321,214 @@ static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
        int oldbit;
 
        asm volatile(LOCK_PREFIX "bts %2,%1\n\t"
        int oldbit;
 
        asm volatile(LOCK_PREFIX "bts %2,%1\n\t"
-                    "sbb %0,%0" : "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
+                    "sbb %0,%0" : "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
 
        return oldbit;
 }
 
 
        return oldbit;
 }
 
-static void pir_dump()
+/* load_kernel loads an ELF file as a kernel. */
+uintptr_t
+load_kernel(char *filename, uintptr_t *kernstart, uintptr_t *kernend)
+{
+       Elf64_Ehdr *ehdr;
+       Elf *elf;
+       size_t phnum = 0;
+       Elf64_Phdr *hdrs;
+       int fd;
+
+       elf_version(EV_CURRENT);
+       fd = open(filename, O_RDONLY);
+       if (fd < 0) {
+               fprintf(stderr, "Can't open %s: %r\n", filename);
+               return 0;
+       }
+
+       elf = elf_begin(fd, ELF_C_READ, NULL);
+       if (elf == NULL) {
+               fprintf(stderr, "%s: cannot read %s ELF file.\n", __func__, filename);
+               close(fd);
+               return 0;
+       }
+
+       ehdr = elf64_getehdr(elf);
+       if (ehdr == NULL) {
+               fprintf(stderr, "%s: cannot get exec header of %s.\n",
+                       __func__, filename);
+               goto fail;
+       }
+       fprintf(stderr, "%s ELF entry point is %p\n", filename,
+               (void *)ehdr->e_entry);
+
+       if (elf_getphdrnum(elf, &phnum) < 0) {
+               fprintf(stderr, "%s: cannot get program header num of %s.\n",
+                       __func__, filename);
+               goto fail;
+       }
+       fprintf(stderr, "%s has %p program headers\n", filename, phnum);
+
+       hdrs = elf64_getphdr(elf);
+       if (hdrs == NULL) {
+               fprintf(stderr, "%s: cannot get program headers of %s.\n",
+                       __func__, filename);
+               goto fail;
+       }
+
+       for (int i = 0; i < phnum; i++) {
+               size_t tot;
+               Elf64_Phdr *h = &hdrs[i];
+               uintptr_t pa;
+
+               fprintf(stderr,
+                       "%d: type 0x%lx flags 0x%lx  offset 0x%lx vaddr 0x%lx paddr 0x%lx size 0x%lx  memsz 0x%lx align 0x%lx\n",
+                       i,
+                       h->p_type,              /* Segment type */
+                       h->p_flags,             /* Segment flags */
+                       h->p_offset,            /* Segment file offset */
+                       h->p_vaddr,             /* Segment virtual address */
+                       h->p_paddr,             /* Segment physical address */
+                       h->p_filesz,            /* Segment size in file */
+                       h->p_memsz,             /* Segment size in memory */
+                       h->p_align              /* Segment alignment */);
+               if (h->p_type != PT_LOAD)
+                       continue;
+               if ((h->p_flags & (PF_R | PF_W | PF_X)) == 0)
+                       continue;
+
+               pa = h->p_paddr;
+               if (*kernstart > pa)
+                       *kernstart = pa;
+               if (*kernend < pa + h->p_memsz)
+                       *kernend = pa + h->p_memsz;
+               fprintf(stderr,
+                       "Read header %d @offset %p to %p (elf PA is %p) %d bytes:",
+                       i, h->p_offset, pa, h->p_paddr, h->p_filesz);
+               tot = 0;
+               while (tot < h->p_filesz) {
+                       int amt = pread(fd, (void *)(pa + tot), h->p_filesz - tot,
+                                       h->p_offset + tot);
+                       if (amt < 1)
+                               break;
+                       tot += amt;
+               }
+               fprintf(stderr, "read a total of %d bytes\n", tot);
+               if (tot < h->p_filesz) {
+                       fprintf(stderr, "%s: got %d bytes, wanted %d bytes\n",
+                               filename, tot, h->p_filesz);
+                       goto fail;
+               }
+       }
+
+       close(fd);
+       elf_end(elf);
+       return ehdr->e_entry;
+fail:
+       close(fd);
+       elf_end(elf);
+       return 0;
+}
+
+/* TODO: put this in a library somewhere */
+int cat(char *file, char *where)
 {
 {
-       unsigned long *pir_ptr = gpci.posted_irq_desc;
-       int i;
-       fprintf(stderr, "-------Begin PIR dump-------\n");
-       for (i = 0; i < 8; i++){
-               fprintf(stderr, "Byte %d: 0x%016x\n", i, pir_ptr[i]);
+       int fd;
+       int amt, tot = 0;
+
+       fd = open(file, O_RDONLY);
+       if (fd < 0)
+               return -1;
+
+       while (amt = read(fd, where, 4096)) {
+               if (amt < 0) {
+                       close(fd);
+                       return -1;
+               }
+               tot += amt;
+               where += amt;
        }
        }
-       fprintf(stderr, "-------End PIR dump-------\n");
+       close(fd);
+       return tot;
 }
 
 }
 
-static void set_posted_interrupt(int vector)
+int smbios(char *smbiostable, void *esegment)
 {
 {
-       test_and_set_bit(vector, gpci.posted_irq_desc);
-       /* LOCKed instruction provides the mb() */
-       test_and_set_bit(VMX_POSTED_OUTSTANDING_NOTIF, gpci.posted_irq_desc);
+       int amt;
+
+       amt = cat(smbiostable, esegment);
+       if (amt < 0) {
+               fprintf(stderr, "%s: %r\n", smbiostable);
+               exit(1);
+       }
+
+       return amt;
 }
 
 int main(int argc, char **argv)
 {
        struct boot_params *bp;
 }
 
 int main(int argc, char **argv)
 {
        struct boot_params *bp;
-       char *cmdline_default = "earlyprintk=vmcall,keep"
-                                   " console=hvc0"
-                                   " virtio_mmio.device=1M@0x100000000:32"
-                                   " nosmp"
-                                   " maxcpus=1"
-                                   " acpi.debug_layer=0x2"
-                                   " acpi.debug_level=0xffffffff"
-                                   " apic=debug"
-                                   " noexec=off"
-                                   " nohlt"
-                                   " init=/bin/launcher"
-                                   " lapic=notscdeadline"
-                                   " lapictimerfreq=1000000"
-                                   " pit=none";
+       char cmdline_default[512] = {0};
        char *cmdline_extra = "\0";
        char *cmdline;
        char *cmdline_extra = "\0";
        char *cmdline;
-       uint64_t *p64;
        void *a = (void *)0xe0000;
        struct acpi_table_rsdp *r;
        struct acpi_table_fadt *f;
        struct acpi_table_madt *m;
        struct acpi_table_xsdt *x;
        void *a = (void *)0xe0000;
        struct acpi_table_rsdp *r;
        struct acpi_table_fadt *f;
        struct acpi_table_madt *m;
        struct acpi_table_xsdt *x;
-       // lowmem is a bump allocated pointer to 2M at the "physbase" of memory
-       void *lowmem = (void *) 0x1000000;
-       int amt;
        int vmmflags = 0; // Disabled probably forever. VMM_VMCALL_PRINTF;
        int vmmflags = 0; // Disabled probably forever. VMM_VMCALL_PRINTF;
-       uint64_t entry = 0x1200000, kerneladdress = 0x1200000;
+       uint64_t entry = 0;
        int ret;
        int ret;
-       void * xp;
-       int kfd = -1;
-       static char cmd[512];
-       int i;
+       uintptr_t size;
        uint8_t csum;
        uint8_t csum;
-       void *coreboot_tables = (void *) 0x1165000;
        void *a_page;
        struct vm_trapframe *vm_tf;
        uint64_t tsc_freq_khz;
        void *a_page;
        struct vm_trapframe *vm_tf;
        uint64_t tsc_freq_khz;
+       char *cmdlinep;
+       int cmdlinesz, len, cmdline_fd;
+       char *disk_image_file = NULL;
+       int c;
+       struct stat stat_result;
+       int num_read;
+       int option_index;
+       uintptr_t kernstart = (uintptr_t)~1, kernend = 0;
+       char *smbiostable = NULL;
+
+       static struct option long_options[] = {
+               {"debug",         no_argument,       0, 'd'},
+               {"vmm_vmcall",    no_argument,       0, 'v'},
+               {"maxresume",     required_argument, 0, 'R'},
+               {"memsize",       required_argument, 0, 'm'},
+               {"memstart",      required_argument, 0, 'M'},
+               {"stack",         required_argument, 0, 'S'},
+               {"cmdline_extra", required_argument, 0, 'c'},
+               {"greedy",        no_argument,       0, 'g'},
+               {"scp",           no_argument,       0, 's'},
+               {"image_file",    required_argument, 0, 'f'},
+               {"cmdline",       required_argument, 0, 'k'},
+               {"nic",           required_argument, 0, 'n'},
+               {"smbiostable",   required_argument, 0, 't'},
+               {"help",          no_argument,       0, 'h'},
+               {0, 0, 0, 0}
+       };
 
        fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
 
        fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
-                       PML1_PTE_REACH);
+               PML1_PTE_REACH);
 
 
-
-       // mmap is not working for us at present.
-       if ((uint64_t)_kernel > GKERNBASE) {
-               fprintf(stderr, "kernel array @%p is above , GKERNBASE@%p sucks\n", _kernel, GKERNBASE);
+       if ((uintptr_t)__procinfo.program_end >= MinMemory) {
+               fprintf(stderr,
+                       "Panic: vmrunkernel binary extends into guest memory\n");
                exit(1);
        }
                exit(1);
        }
-       memset(_kernel, 0, sizeof(_kernel));
-       memset(lowmem, 0xff, 2*1048576);
+
        vm->low4k = malloc(PGSIZE);
        memset(vm->low4k, 0xff, PGSIZE);
        vm->low4k = malloc(PGSIZE);
        memset(vm->low4k, 0xff, PGSIZE);
-       // avoid at all costs, requires too much instruction emulation.
-       //low4k[0x40e] = 0;
-       //low4k[0x40f] = 0xe0;
+       vm->low4k[0x40e] = 0;
+       vm->low4k[0x40f] = 0;
 
        //Place mmap(Gan)
        a_page = mmap((void *)0xfee00000, PGSIZE, PROT_READ | PROT_WRITE,
 
        //Place mmap(Gan)
        a_page = mmap((void *)0xfee00000, PGSIZE, PROT_READ | PROT_WRITE,
-                             MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
+                     MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
        fprintf(stderr, "a_page mmap pointer %p\n", a_page);
 
        fprintf(stderr, "a_page mmap pointer %p\n", a_page);
 
-       if (a_page == (void *) -1) {
+       if (a_page != (void *)0xfee00000) {
                perror("Could not mmap APIC");
                exit(1);
        }
                perror("Could not mmap APIC");
                exit(1);
        }
@@ -377,17 +537,12 @@ int main(int argc, char **argv)
                exit(1);
        }
 
                exit(1);
        }
 
-       memset(a_page, 0, 4096);
        ((uint32_t *)a_page)[0x30/4] = 0x01060015;
        //((uint32_t *)a_page)[0x30/4] = 0xDEADBEEF;
 
        ((uint32_t *)a_page)[0x30/4] = 0x01060015;
        //((uint32_t *)a_page)[0x30/4] = 0xDEADBEEF;
 
-       argc--, argv++;
-       // switches ...
-       // Sorry, I don't much like the gnu opt parsing code.
-       while (1) {
-               if (*argv[0] != '-')
-                       break;
-               switch(argv[0][1]) {
+       while ((c = getopt_long(argc, argv, "dvm:M:S:c:gsf:k:n:t:hR:",
+                               long_options, &option_index)) != -1) {
+               switch (c) {
                case 'd':
                        debug++;
                        break;
                case 'd':
                        debug++;
                        break;
@@ -395,64 +550,113 @@ int main(int argc, char **argv)
                        vmmflags |= VMM_VMCALL_PRINTF;
                        break;
                case 'm':
                        vmmflags |= VMM_VMCALL_PRINTF;
                        break;
                case 'm':
-                       argc--, argv++;
-                       maxresume = strtoull(argv[0], 0, 0);
+                       memsize = strtoull(optarg, 0, 0);
+                       break;
+               case 'M':
+                       memstart = strtoull(optarg, 0, 0);
+                       break;
+               case 'S':
+                       stack = strtoull(optarg, 0, 0);
+                       break;
+               case 'R':
+                       maxresume = strtoull(optarg, 0, 0);
                        break;
                case 'c':
                        break;
                case 'c':
-                       argc--, argv++;
-                       cmdline_extra = argv[0];
+                       cmdline_extra = optarg;
                case 'g':       /* greedy */
                        parlib_never_yield = TRUE;
                        break;
                case 's':       /* scp */
                        parlib_wants_to_be_mcp = FALSE;
                        break;
                case 'g':       /* greedy */
                        parlib_never_yield = TRUE;
                        break;
                case 's':       /* scp */
                        parlib_wants_to_be_mcp = FALSE;
                        break;
-               default:
-                       fprintf(stderr, "BMAFR\n");
+               case 'f':       /* file to pass to blk_init */
+                       disk_image_file = optarg;
+                       break;
+               case 'k':       /* specify file to get cmdline args from */
+                       cmdline_fd = open(optarg, O_RDONLY);
+                       if (cmdline_fd < 0) {
+                               fprintf(stderr, "failed to open file: %s\n", optarg);
+                               exit(1);
+                       }
+                       if (stat(optarg, &stat_result) == -1) {
+                               fprintf(stderr, "stat of %s failed\n", optarg);
+                               exit(1);
+                       }
+                       len = stat_result.st_size;
+                       if (len > 512) {
+                               fprintf(stderr, "command line options exceed 512 bytes!");
+                               exit(1);
+                       }
+                       num_read = read(cmdline_fd, cmdline_default, len);
+                       if (num_read != len) {
+                               fprintf(stderr, "read failed len was : %d, num_read was: %d\n",
+                                       len, num_read);
+                               exit(1);
+                       }
+                       close(cmdline_fd);
+                       break;
+               case 't':
+                       smbiostable = optarg;
                        break;
                        break;
+               case 'n':
+                       default_nic = strtoull(optarg, 0, 0);
+                       break;
+               case 'h':
+               default:
+                       // Sadly, the getopt_long struct does
+                       // not have a pointer to help text.
+                       for (int i = 0;
+                            i < sizeof(long_options)/sizeof(long_options[0]) - 1;
+                            i++) {
+                               struct option *l = &long_options[i];
+
+                               fprintf(stderr, "%s or %c%s\n", l->name, l->val,
+                                       l->has_arg ? " <arg>" : "");
+                       }
+                       exit(0);
                }
                }
-               argc--, argv++;
        }
        }
+       if (strlen(cmdline_default) == 0) {
+               fprintf(stderr, "WARNING: No command line parameter file specified.\n");
+       }
+       argc -= optind;
+       argv += optind;
        if (argc < 1) {
        if (argc < 1) {
-               fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)] [coreboot_tables [loadaddress [entrypoint]]]\n", argv[0]);
+               fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)]\n", argv[0]);
                exit(1);
        }
                exit(1);
        }
-       if (argc > 1)
-               coreboot_tables = (void *) strtoull(argv[1], 0, 0);
-       if (argc > 2)
-               kerneladdress = strtoull(argv[2], 0, 0);
-       if (argc > 3)
-               entry = strtoull(argv[3], 0, 0);
-       kfd = open(argv[0], O_RDONLY);
-       if (kfd < 0) {
-               perror(argv[0]);
+
+       if ((uintptr_t)(memstart + memsize) >= (uintptr_t)BRK_START) {
+               fprintf(stderr,
+                       "memstart 0x%lx memsize 0x%lx -> 0x%lx is too large; overlaps BRK_START at %p\n",
+                       memstart, memsize, memstart + memsize, BRK_START);
                exit(1);
        }
                exit(1);
        }
-       // read in the kernel.
-       xp = (void *)kerneladdress;
-       for(;;) {
-               amt = read(kfd, xp, 1048576);
-               if (amt < 0) {
-                       perror("read");
-                       exit(1);
-               }
-               if (amt == 0) {
-                       break;
-               }
-               xp += amt;
+
+       kernel = mmap((void *)memstart, memsize,
+                     PROT_READ | PROT_WRITE | PROT_EXEC,
+                     MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
+       if (kernel != (void *)memstart) {
+               fprintf(stderr, "Could not mmap 0x%lx bytes at 0x%lx\n",
+                       memsize, memstart);
+               exit(1);
+       }
+
+       entry = load_kernel(argv[0], &kernstart, &kernend);
+       if (entry == 0) {
+               fprintf(stderr, "Unable to load kernel %s\n", argv[0]);
+               exit(1);
        }
        }
-       fprintf(stderr, "Read in %d bytes\n", xp-kerneladdress);
-       close(kfd);
+
 
        // The low 1m so we can fill in bullshit like ACPI. */
        // And, sorry, due to the STUPID format of the RSDP for now we need the low 1M.
        low1m = mmap((int*)4096, MiB-4096, PROT_READ | PROT_WRITE,
 
        // The low 1m so we can fill in bullshit like ACPI. */
        // And, sorry, due to the STUPID format of the RSDP for now we need the low 1M.
        low1m = mmap((int*)4096, MiB-4096, PROT_READ | PROT_WRITE,
-                        MAP_ANONYMOUS, -1, 0);
+                    MAP_ANONYMOUS, -1, 0);
        if (low1m != (void *)4096) {
                perror("Unable to mmap low 1m");
                exit(1);
        }
        if (low1m != (void *)4096) {
                perror("Unable to mmap low 1m");
                exit(1);
        }
-       memset(low1m, 0xff, MiB-4096);
        r = a;
        fprintf(stderr, "install rsdp to %p\n", r);
        *r = rsdp;
        r = a;
        fprintf(stderr, "install rsdp to %p\n", r);
        *r = rsdp;
@@ -528,8 +732,6 @@ int main(int argc, char **argv)
                exit(1);
        }
 
                exit(1);
        }
 
-
-
        fprintf(stderr, "allchecksums ok\n");
 
        hexdump(stdout, r, a-(void *)r);
        fprintf(stderr, "allchecksums ok\n");
 
        hexdump(stdout, r, a-(void *)r);
@@ -541,7 +743,6 @@ int main(int argc, char **argv)
        gpci.vapic_addr = a;
        memset(a, 0, 4096);
        ((uint32_t *)a)[0x30/4] = 0x01060014;
        gpci.vapic_addr = a;
        memset(a, 0, 4096);
        ((uint32_t *)a)[0x30/4] = 0x01060014;
-       p64 = a;
        // set up apic values? do we need to?
        // qemu does this.
        //((uint8_t *)a)[4] = 1;
        // set up apic values? do we need to?
        // qemu does this.
        //((uint8_t *)a)[4] = 1;
@@ -556,81 +757,145 @@ int main(int argc, char **argv)
        bp = a;
        memset(bp, 0, 4096);
 
        bp = a;
        memset(bp, 0, 4096);
 
-       /* Set the kernel command line parameters */
-       a += 4096;
-       cmdline = a;
-       a += 4096;
-       bp->hdr.cmd_line_ptr = (uintptr_t) cmdline;
-       tsc_freq_khz = get_tsc_freq()/1000;
-       sprintf(cmdline, "%s tscfreq=%lld %s", cmdline_default, tsc_freq_khz,
-               cmdline_extra);
-
-
        /* Put the e820 memory region information in the boot_params */
        /* Put the e820 memory region information in the boot_params */
-       bp->e820_entries = 3;
+       bp->e820_entries = 5;
        int e820i = 0;
 
        int e820i = 0;
 
+       /* Give it just a tiny bit of memory -- 60k -- at low memory. */
        bp->e820_map[e820i].addr = 0;
        bp->e820_map[e820i].addr = 0;
-       bp->e820_map[e820i].size = 16 * 1048576;
+       bp->e820_map[e820i].size = 4 * 1024;
+       bp->e820_map[e820i++].type = E820_RESERVED;
+
+       bp->e820_map[e820i].addr = 4 * 1024;
+       bp->e820_map[e820i].size = 64 * 1024 - 4 * 1024;
+       bp->e820_map[e820i++].type = E820_RAM;
+
+       bp->e820_map[e820i].addr = 64 * 1024;
+       bp->e820_map[e820i].size = memstart - 64 * 1024;
        bp->e820_map[e820i++].type = E820_RESERVED;
 
        bp->e820_map[e820i++].type = E820_RESERVED;
 
-       bp->e820_map[e820i].addr = 16 * 1048576;
-       bp->e820_map[e820i].size = 128 * 1048576;
+       bp->e820_map[e820i].addr = memstart;
+       bp->e820_map[e820i].size = memsize;
        bp->e820_map[e820i++].type = E820_RAM;
 
        bp->e820_map[e820i].addr = 0xf0000000;
        bp->e820_map[e820i].size = 0x10000000;
        bp->e820_map[e820i++].type = E820_RESERVED;
 
        bp->e820_map[e820i++].type = E820_RAM;
 
        bp->e820_map[e820i].addr = 0xf0000000;
        bp->e820_map[e820i].size = 0x10000000;
        bp->e820_map[e820i++].type = E820_RESERVED;
 
+       /* The MMIO address of the console device is really the address of an
+        * unbacked EPT page: accesses to this page will cause a page fault that
+        * traps to the host, which will examine the fault, see it was for the
+        * known MMIO address, and fulfill the MMIO read or write on the guest's
+        * behalf accordingly. We place the virtio space at 512 GB higher than the
+        * guest physical memory to avoid a full page table walk. */
+       uint64_t virtio_mmio_base_addr = ROUNDUP((bp->e820_map[e820i - 1].addr +
+                                                 bp->e820_map[e820i - 1].size),
+                                                512 * GiB);
+
+       cons_mmio_dev.addr =
+               virtio_mmio_base_addr + PGSIZE * VIRTIO_MMIO_CONSOLE_DEV;
+       cons_mmio_dev.vqdev = &cons_vqdev;
+       vm->virtio_mmio_devices[VIRTIO_MMIO_CONSOLE_DEV] = &cons_mmio_dev;
+
+       net_mmio_dev.addr =
+               virtio_mmio_base_addr + PGSIZE * VIRTIO_MMIO_NETWORK_DEV;
+       net_mmio_dev.vqdev = &net_vqdev;
+       vm->virtio_mmio_devices[VIRTIO_MMIO_NETWORK_DEV] = &net_mmio_dev;
+
+       if (disk_image_file != NULL) {
+               blk_mmio_dev.addr =
+                       virtio_mmio_base_addr + PGSIZE * VIRTIO_MMIO_BLOCK_DEV;
+               blk_mmio_dev.vqdev = &blk_vqdev;
+               vm->virtio_mmio_devices[VIRTIO_MMIO_BLOCK_DEV] = &blk_mmio_dev;
+               blk_init_fn(&blk_vqdev, disk_image_file);
+       }
+       net_init_fn(&net_vqdev, default_nic);
+
+       /* Set the kernel command line parameters */
+       a += 4096;
+       cmdline = a;
+       a += 4096;
+
+       if (smbiostable) {
+               fprintf(stderr, "Using SMBIOS table %s\n", smbiostable);
+               a += smbios(smbiostable, a);
+       }
+
+       bp->hdr.cmd_line_ptr = (uintptr_t) cmdline;
+
+       tsc_freq_khz = get_tsc_freq()/1000;
+       len = snprintf(cmdline, 4096, "%s tscfreq=%lld %s", cmdline_default,
+                      tsc_freq_khz, cmdline_extra);
+
+       cmdlinesz = 4096 - len;
+       cmdlinep = cmdline + len;
+
+       for (int i = 0; i < VIRTIO_MMIO_MAX_NUM_DEV; i++) {
+               if (vm->virtio_mmio_devices[i] == NULL)
+                       continue;
+
+               /* Append all the virtio mmio base addresses. */
+
+               /* Since the lower number irqs are no longer being used, the irqs
+                * can now be assigned starting from 0.
+                */
+               vm->virtio_mmio_devices[i]->irq = i;
+               len = snprintf(cmdlinep, cmdlinesz,
+                              " virtio_mmio.device=1K@0x%llx:%lld",
+                              vm->virtio_mmio_devices[i]->addr,
+                              vm->virtio_mmio_devices[i]->irq);
+               if (len >= cmdlinesz) {
+                       fprintf(stderr, "Too many arguments to the linux command line.");
+                       exit(1);
+               }
+               cmdlinesz -= len;
+               cmdlinep += len;
+       }
+
        vm->nr_gpcs = 1;
        vm->gpcis = &gpci;
        ret = vmm_init(vm, vmmflags);
        assert(!ret);
 
        vm->nr_gpcs = 1;
        vm->gpcis = &gpci;
        ret = vmm_init(vm, vmmflags);
        assert(!ret);
 
-
-       ret = posix_memalign((void **)&p512, 4096, 3*4096);
-       fprintf(stderr, "memalign is %p\n", p512);
+       /* Allocate 3 pages for page table pages: a page of 512 GiB
+        * PTEs with only one entry filled to point to a page of 1 GiB
+        * PTEs; a page of 1 GiB PTEs with only one entry filled to
+        * point to a page of 2 MiB PTEs; and a page of 2 MiB PTEs,
+        * only a subset of which will be filled. */
+       ret = posix_memalign((void **)&p512, PGSIZE, 3 * PGSIZE);
        if (ret) {
                perror("ptp alloc");
                exit(1);
        }
        if (ret) {
                perror("ptp alloc");
                exit(1);
        }
-       p1 = &p512[512];
-       p2m = &p512[1024];
-       uint64_t kernbase = 0; //0xffffffff80000000;
-       uint64_t highkernbase = 0xffffffff80000000;
-       p512[PML4(kernbase)] = (unsigned long long)p1 | 7;
-       p1[PML3(kernbase)] = /*0x87; */(unsigned long long)p2m | 7;
-       p512[PML4(highkernbase)] = (unsigned long long)p1 | 7;
-       p1[PML3(highkernbase)] = /*0x87; */(unsigned long long)p2m | 7;
-#define _2MiB (0x200000)
-
-       for (i = 0; i < 512; i++) {
-               p2m[PML2(kernbase + i * _2MiB)] = 0x87 | i * _2MiB;
-       }
-
-       kernbase >>= (0+12);
-       kernbase <<= (0 + 12);
-       uint8_t *kernel = (void *)GKERNBASE;
-       //write_coreboot_table(coreboot_tables, ((void *)VIRTIOBASE) /*kernel*/, KERNSIZE + 1048576);
-       hexdump(stdout, coreboot_tables, 512);
-       fprintf(stderr, "kernbase for pml4 is 0x%llx and entry is %llx\n", kernbase, entry);
-       fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);
 
 
-       /* The MMIO address of the console device is really the address of an
-        * unbacked EPT page: accesses to this page will cause a page fault that
-        * traps to the host, which will examine the fault, see it was for the
-        * known MMIO address, and fulfill the MMIO read or write on the guest's
-        * behalf accordingly. */
-       cons_mmio_dev.addr = 0x100000000;
-       cons_mmio_dev.vqdev = &cons_vqdev;
-       vm->virtio_mmio_devices[VIRTIO_MMIO_CONSOLE_DEV] = &cons_mmio_dev;
+       /* Set up a 1:1 ("identity") page mapping from guest virtual
+        * to guest physical using the (host virtual)
+        * `kerneladdress`. This mapping is used for only a short
+        * time, until the guest sets up its own page tables. Be aware
+        * that the values stored in the table are physical addresses.
+        * This is subtle and mistakes are easily disguised due to the
+        * identity mapping, so take care when manipulating these
+        * mappings. */
+       p1 = &p512[NPTENTRIES];
+       p2m = &p512[2 * NPTENTRIES];
+
+       size = kernend - kernstart;
+       fprintf(stderr, "Map %p for %zu bytes\n", kernstart, size);
+       p512[PML4(kernstart)] = (uint64_t)p1 | PTE_KERN_RW;
+       p1[PML3(kernstart)] = (uint64_t)p2m | PTE_KERN_RW;
+       for (uintptr_t i = 0; i < size; i += PML2_PTE_REACH) {
+               p2m[PML2(kernstart + i)] =
+                       (uint64_t)(kernstart + i) | PTE_KERN_RW | PTE_PS;
+       }
+
+       fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);
 
        vmm_run_task(vm, timer_thread, 0);
 
        vm_tf = gth_to_vmtf(vm->gths[0]);
        vm_tf->tf_cr3 = (uint64_t) p512;
        vm_tf->tf_rip = entry;
 
        vmm_run_task(vm, timer_thread, 0);
 
        vm_tf = gth_to_vmtf(vm->gths[0]);
        vm_tf->tf_cr3 = (uint64_t) p512;
        vm_tf->tf_rip = entry;
-       vm_tf->tf_rsp = 0;
+       vm_tf->tf_rsp = stack;
        vm_tf->tf_rsi = (uint64_t) bp;
        start_guest_thread(vm->gths[0]);
 
        vm_tf->tf_rsi = (uint64_t) bp;
        start_guest_thread(vm->gths[0]);