User library changes to take a guest_thread instead of a vmctl.
[akaros.git] / tests / vmm / vmrunkernel.c
1 #include <stdio.h>
2 #include <pthread.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <parlib/arch/arch.h>
7 #include <parlib/ros_debug.h>
8 #include <unistd.h>
9 #include <errno.h>
10 #include <dirent.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ros/syscall.h>
14 #include <sys/mman.h>
15 #include <vmm/coreboot_tables.h>
16 #include <vmm/vmm.h>
17 #include <vmm/acpi/acpi.h>
18 #include <ros/arch/mmu.h>
19 #include <ros/vmm.h>
20 #include <parlib/uthread.h>
21 #include <vmm/linux_bootparam.h>
22 #include <vmm/virtio.h>
23 #include <vmm/virtio_mmio.h>
24 #include <vmm/virtio_ids.h>
25 #include <vmm/virtio_config.h>
26 #include <vmm/sched.h>
27
28 struct vmctl vmctl;
29 struct vmm_gpcore_init gpci;
30
31 /* Whoever holds the ball runs.  run_vm never actually grabs it - it is grabbed
32  * on its behalf. */
33 uth_mutex_t the_ball;
34 pthread_t vm_thread;
35
36 void (*old_thread_refl)(struct uthread *uth, struct user_context *ctx);
37
38 static void copy_vmtf_to_vmctl(struct vm_trapframe *vm_tf, struct vmctl *vmctl)
39 {
40         vmctl->cr3 = vm_tf->tf_cr3;
41         vmctl->gva = vm_tf->tf_guest_va;
42         vmctl->gpa = vm_tf->tf_guest_pa;
43         vmctl->exit_qual = vm_tf->tf_exit_qual;
44         if (vm_tf->tf_exit_reason == EXIT_REASON_EPT_VIOLATION)
45                 vmctl->shutdown = SHUTDOWN_EPT_VIOLATION;
46         else
47                 vmctl->shutdown = SHUTDOWN_UNHANDLED_EXIT_REASON;
48         vmctl->ret_code = vm_tf->tf_exit_reason;
49         vmctl->interrupt = vm_tf->tf_trap_inject;
50         vmctl->intrinfo1 = vm_tf->tf_intrinfo1;
51         vmctl->intrinfo2 = vm_tf->tf_intrinfo2;
52         /* Most of the HW TF.  Should be good enough for now */
53         vmctl->regs.tf_rax = vm_tf->tf_rax;
54         vmctl->regs.tf_rbx = vm_tf->tf_rbx;
55         vmctl->regs.tf_rcx = vm_tf->tf_rcx;
56         vmctl->regs.tf_rdx = vm_tf->tf_rdx;
57         vmctl->regs.tf_rbp = vm_tf->tf_rbp;
58         vmctl->regs.tf_rsi = vm_tf->tf_rsi;
59         vmctl->regs.tf_rdi = vm_tf->tf_rdi;
60         vmctl->regs.tf_r8  = vm_tf->tf_r8;
61         vmctl->regs.tf_r9  = vm_tf->tf_r9;
62         vmctl->regs.tf_r10 = vm_tf->tf_r10;
63         vmctl->regs.tf_r11 = vm_tf->tf_r11;
64         vmctl->regs.tf_r12 = vm_tf->tf_r12;
65         vmctl->regs.tf_r13 = vm_tf->tf_r13;
66         vmctl->regs.tf_r14 = vm_tf->tf_r14;
67         vmctl->regs.tf_r15 = vm_tf->tf_r15;
68         vmctl->regs.tf_rip = vm_tf->tf_rip;
69         vmctl->regs.tf_rflags = vm_tf->tf_rflags;
70         vmctl->regs.tf_rsp = vm_tf->tf_rsp;
71 }
72
73 static void copy_vmctl_to_vmtf(struct vmctl *vmctl, struct vm_trapframe *vm_tf)
74 {
75         vm_tf->tf_rax = vmctl->regs.tf_rax;
76         vm_tf->tf_rbx = vmctl->regs.tf_rbx;
77         vm_tf->tf_rcx = vmctl->regs.tf_rcx;
78         vm_tf->tf_rdx = vmctl->regs.tf_rdx;
79         vm_tf->tf_rbp = vmctl->regs.tf_rbp;
80         vm_tf->tf_rsi = vmctl->regs.tf_rsi;
81         vm_tf->tf_rdi = vmctl->regs.tf_rdi;
82         vm_tf->tf_r8  = vmctl->regs.tf_r8;
83         vm_tf->tf_r9  = vmctl->regs.tf_r9;
84         vm_tf->tf_r10 = vmctl->regs.tf_r10;
85         vm_tf->tf_r11 = vmctl->regs.tf_r11;
86         vm_tf->tf_r12 = vmctl->regs.tf_r12;
87         vm_tf->tf_r13 = vmctl->regs.tf_r13;
88         vm_tf->tf_r14 = vmctl->regs.tf_r14;
89         vm_tf->tf_r15 = vmctl->regs.tf_r15;
90         vm_tf->tf_rip = vmctl->regs.tf_rip;
91         vm_tf->tf_rflags = vmctl->regs.tf_rflags;
92         vm_tf->tf_rsp = vmctl->regs.tf_rsp;
93         vm_tf->tf_cr3 = vmctl->cr3;
94         vm_tf->tf_trap_inject = vmctl->interrupt;
95         /* Don't care about the rest of the fields.  The kernel only writes them */
96 }
97
98 /* callback, runs in vcore context.  this sets up our initial context.  once we
99  * become runnable again, we'll run the first bits of the vm ctx.  after that,
100  * our context will be stopped and started and will just run whatever the guest
101  * VM wants.  we'll never come back to this code or to run_vm(). */
102 static void __build_vm_ctx_cb(struct uthread *uth, void *arg)
103 {
104         struct pthread_tcb *pthread = (struct pthread_tcb*)uth;
105         struct vmctl *vmctl = (struct vmctl*)arg;
106         struct vm_trapframe *vm_tf;
107
108         __pthread_generic_yield(pthread);
109         pthread->state = PTH_BLK_YIELDING;
110
111         memset(&uth->u_ctx, 0, sizeof(struct user_context));
112         uth->u_ctx.type = ROS_VM_CTX;
113         vm_tf = &uth->u_ctx.tf.vm_tf;
114
115         vm_tf->tf_guest_pcoreid = 0;    /* assuming only 1 guest core */
116
117         copy_vmctl_to_vmtf(vmctl, vm_tf);
118
119         /* other HW/GP regs are 0, which should be fine.  the FP state is still
120          * whatever we were running before, though this is pretty much unnecessary.
121          * we mostly don't want crazy crap in the uth->as, and a non-current_uthread
122          * VM ctx is supposed to have something in their FP state (like HW ctxs). */
123         save_fp_state(&uth->as);
124         uth->flags |= UTHREAD_FPSAVED | UTHREAD_SAVED;
125
126         uthread_runnable(uth);
127 }
128
129 static void *run_vm(void *arg)
130 {
131         struct vmctl *vmctl = (struct vmctl*)arg;
132
133         assert(vmctl->command == REG_RSP_RIP_CR3);
134         /* We need to hack our context, so that next time we run, we're a VM ctx */
135         uthread_yield(FALSE, __build_vm_ctx_cb, arg);
136 }
137
138 static void vmm_thread_refl_fault(struct uthread *uth,
139                                   struct user_context *ctx)
140 {
141         struct pthread_tcb *pthread = (struct pthread_tcb*)uth;
142
143         /* Hack to call the original pth 2LS op */
144         if (!ctx->type == ROS_VM_CTX) {
145                 old_thread_refl(uth, ctx);
146                 return;
147         }
148         __pthread_generic_yield(pthread);
149         /* normally we'd handle the vmexit here.  to work within the existing
150          * framework, we just wake the controller thread.  It'll look at our ctx
151          * then make us runnable again */
152         pthread->state = PTH_BLK_MUTEX;
153         uth_mutex_unlock(the_ball);             /* wake the run_vmthread */
154 }
155
156
157
158 /* this will start the vm thread, and return when the thread has blocked,
159  * with the right info in vmctl. */
160 static void run_vmthread(struct vmctl *vmctl)
161 {
162         struct vm_trapframe *vm_tf;
163
164         if (!vm_thread) {
165                 /* first time through, we make the vm thread.  the_ball was already
166                  * grabbed right after it was alloc'd. */
167                 if (pthread_create(&vm_thread, NULL, run_vm, vmctl)) {
168                         perror("pth_create");
169                         exit(-1);
170                 }
171                 /* hack in our own handlers for some 2LS ops */
172                 old_thread_refl = sched_ops->thread_refl_fault;
173                 sched_ops->thread_refl_fault = vmm_thread_refl_fault;
174         } else {
175                 copy_vmctl_to_vmtf(vmctl, &vm_thread->uthread.u_ctx.tf.vm_tf);
176                 uth_mutex_lock(the_ball);       /* grab it for the vm_thread */
177                 uthread_runnable((struct uthread*)vm_thread);
178         }
179         uth_mutex_lock(the_ball);
180         /* We woke due to a vm exit.  Need to unlock for the next time we're run */
181         uth_mutex_unlock(the_ball);
182         /* the vm stopped.  we can do whatever we want before rerunning it.  since
183          * we're controlling the uth, we need to handle its vmexits.  we'll fill in
184          * the vmctl, since that's the current framework. */
185         copy_vmtf_to_vmctl(&vm_thread->uthread.u_ctx.tf.vm_tf, vmctl);
186 }
187
188 /* By 1999, you could just scan the hardware
189  * and work it out. But 2005, that was no longer possible. How sad.
190  * so we have to fake acpi to make it all work.
191  * This will be copied to memory at 0xe0000, so the kernel can find it.
192  */
193
194 /* assume they're all 256 bytes long just to make it easy.
195  * Just have pointers that point to aligned things.
196  */
197
198 struct acpi_table_rsdp rsdp = {
199         .signature = "RSD PTR ",
200         .oem_id = "AKAROS",
201         .revision = 2,
202         .length = 36,
203 };
204
205 struct acpi_table_xsdt xsdt = {
206         .header = {
207                 .signature= "XSDT",
208                 // This is so stupid. Incredibly stupid.
209                 .revision = 0,
210                 .oem_id = "AKAROS",
211                 .oem_table_id = "ALPHABET",
212                 .oem_revision = 0,
213                 .asl_compiler_id = "RON ",
214                 .asl_compiler_revision = 0,
215         },
216 };
217 struct acpi_table_fadt fadt = {
218         .header = {
219                 .signature= "FADT",
220                 // This is so stupid. Incredibly stupid.
221                 .revision = 0,
222                 .oem_id = "AKAROS",
223                 .oem_table_id = "ALPHABET",
224                 .oem_revision = 0,
225                 .asl_compiler_id = "RON ",
226                 .asl_compiler_revision = 0,
227         },
228 };
229
230 /* This has to be dropped into memory, then the other crap just follows it.
231  */
232 struct acpi_table_madt madt = {
233         .header = {
234                 .signature = "APIC",
235                 .revision = 0,
236                 .oem_id = "AKAROS",
237                 .oem_table_id = "ALPHABET",
238                 .oem_revision = 0,
239                 .asl_compiler_id = "RON ",
240                 .asl_compiler_revision = 0,
241         },
242
243         .address = 0xfee00000ULL,
244 };
245
246 struct acpi_madt_local_apic Apic0 = {.header = {.type = ACPI_MADT_TYPE_LOCAL_APIC, .length = sizeof(struct acpi_madt_local_apic)},
247                                      .processor_id = 0, .id = 0};
248 struct acpi_madt_io_apic Apic1 = {.header = {.type = ACPI_MADT_TYPE_IO_APIC, .length = sizeof(struct acpi_madt_io_apic)},
249                                   .id = 1, .address = 0xfec00000, .global_irq_base = 0};
250 struct acpi_madt_local_x2apic X2Apic0 = {
251         .header = {
252                 .type = ACPI_MADT_TYPE_LOCAL_X2APIC,
253                 .length = sizeof(struct acpi_madt_local_x2apic)
254         },
255         .local_apic_id = 0,
256         .uid = 0
257 };
258
259 struct acpi_madt_interrupt_override isor[] = {
260         /* I have no idea if it should be source irq 2, global 0, or global 2, source 0. Shit. */
261         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
262          .bus = 0, .source_irq = 2, .global_irq = 0, .inti_flags = 0},
263         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
264          .bus = 0, .source_irq = 1, .global_irq = 1, .inti_flags = 0},
265         //{.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
266          //.bus = 0, .source_irq = 2, .global_irq = 2, .inti_flags = 0},
267         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
268          .bus = 0, .source_irq = 3, .global_irq = 3, .inti_flags = 0},
269         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
270          .bus = 0, .source_irq = 4, .global_irq = 4, .inti_flags = 0},
271         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
272          .bus = 0, .source_irq = 5, .global_irq = 5, .inti_flags = 0},
273         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
274          .bus = 0, .source_irq = 6, .global_irq = 6, .inti_flags = 0},
275         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
276          .bus = 0, .source_irq = 7, .global_irq = 7, .inti_flags = 0},
277         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
278          .bus = 0, .source_irq = 8, .global_irq = 8, .inti_flags = 0},
279         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
280          .bus = 0, .source_irq = 9, .global_irq = 9, .inti_flags = 0},
281         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
282          .bus = 0, .source_irq = 10, .global_irq = 10, .inti_flags = 0},
283         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
284          .bus = 0, .source_irq = 11, .global_irq = 11, .inti_flags = 0},
285         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
286          .bus = 0, .source_irq = 12, .global_irq = 12, .inti_flags = 0},
287         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
288          .bus = 0, .source_irq = 13, .global_irq = 13, .inti_flags = 0},
289         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
290          .bus = 0, .source_irq = 14, .global_irq = 14, .inti_flags = 0},
291         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
292          .bus = 0, .source_irq = 15, .global_irq = 15, .inti_flags = 0},
293         // VMMCP routes irq 32 to gsi 17
294         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
295          .bus = 0, .source_irq = 32, .global_irq = 17, .inti_flags = 5},
296 };
297
298
299 /* this test will run the "kernel" in the negative address space. We hope. */
300 void *low1m;
301 uint8_t low4k[4096];
302 unsigned long long stack[1024];
303 volatile int shared = 0;
304 volatile int quit = 0;
305 int mcp = 1;
306 int virtioirq = 17;
307
308 /* total hack. If the vm runs away we want to get control again. */
309 unsigned int maxresume = (unsigned int) -1;
310
311 #define MiB 0x100000u
312 #define GiB (1u<<30)
313 #define GKERNBASE (16*MiB)
314 #define KERNSIZE (128*MiB+GKERNBASE)
315 uint8_t _kernel[KERNSIZE];
316
317 unsigned long long *p512, *p1, *p2m;
318
319 void **my_retvals;
320 int nr_threads = 4;
321 int debug = 0;
322 int resumeprompt = 0;
323 /* unlike Linux, this shared struct is for both host and guest. */
324 //      struct virtqueue *constoguest =
325 //              vring_new_virtqueue(0, 512, 8192, 0, inpages, NULL, NULL, "test");
326 uint64_t virtio_mmio_base = 0x100000000ULL;
327
328 void vapic_status_dump(FILE *f, void *vapic);
329 static void set_posted_interrupt(int vector);
330
331 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
332 #error "Get a gcc newer than 4.4.0"
333 #else
334 #define BITOP_ADDR(x) "+m" (*(volatile long *) (x))
335 #endif
336
337 #define LOCK_PREFIX "lock "
338 #define ADDR                            BITOP_ADDR(addr)
339 static inline int test_and_set_bit(int nr, volatile unsigned long *addr);
340
341 static int timer_started;
342 pthread_t timerthread_struct;
343
344 void *timer_thread(void *arg)
345 {
346         while (1) {
347                 set_posted_interrupt(0xef);
348                 ros_syscall(SYS_vmm_poke_guest, 0, 0, 0, 0, 0, 0);
349                 uthread_usleep(100000);
350         }
351         fprintf(stderr, "SENDING TIMER\n");
352 }
353
354 void *consout(void *arg)
355 {
356         char *line, *consline, *outline;
357         static struct scatterlist out[] = { {NULL, sizeof(outline)}, };
358         static struct scatterlist in[] = { {NULL, sizeof(line)}, };
359         static struct scatterlist iov[32];
360         struct virtio_threadarg *a = arg;
361         static unsigned int inlen, outlen, conslen;
362         struct virtqueue *v = a->arg->virtio;
363         fprintf(stderr, "talk thread ..\n");
364         uint16_t head, gaveit = 0, gotitback = 0;
365         uint32_t vv;
366         int i;
367         int num;
368
369         if (debug) {
370                 fprintf(stderr, "----------------------- TT a %p\n", a);
371                 fprintf(stderr, "talk thread ttargs %x v %x\n", a, v);
372         }
373
374         for(num = 0;;num++) {
375                 //int debug = 1;
376                 /* host: use any buffers we should have been sent. */
377                 head = wait_for_vq_desc(v, iov, &outlen, &inlen);
378                 if (debug)
379                         fprintf(stderr, "CCC: vq desc head %d, gaveit %d gotitback %d\n", head, gaveit, gotitback);
380                 for(i = 0; debug && i < outlen + inlen; i++)
381                         fprintf(stderr, "CCC: v[%d/%d] v %p len %d\n", i, outlen + inlen, iov[i].v, iov[i].length);
382                 /* host: if we got an output buffer, just output it. */
383                 for(i = 0; i < outlen; i++) {
384                         num++;
385                         int j;
386                         if (debug) {
387                                 fprintf(stderr, "CCC: IOV length is %d\n", iov[i].length);
388                         }
389                         for (j = 0; j < iov[i].length; j++)
390                                 printf("%c", ((char *)iov[i].v)[j]);
391                 }
392                 fflush(stdout);
393                 if (debug)
394                         fprintf(stderr, "CCC: outlen is %d; inlen is %d\n", outlen, inlen);
395                 /* host: fill in the writeable buffers. */
396                 /* why we're getting these I don't know. */
397                 for (i = outlen; i < outlen + inlen; i++) {
398                         if (debug) fprintf(stderr, "CCC: send back empty writeable");
399                         iov[i].length = 0;
400                 }
401                 if (debug) fprintf(stderr, "CCC: call add_used\n");
402                 /* host: now ack that we used them all. */
403                 add_used(v, head, outlen+inlen);
404                 if (debug) fprintf(stderr, "CCC: DONE call add_used\n");
405         }
406         fprintf(stderr, "All done\n");
407         return NULL;
408 }
409
410 // FIXME.
411 volatile int consdata = 0;
412
413 void *consin(void *arg)
414 {
415         struct virtio_threadarg *a = arg;
416         char *line, *outline;
417         static char consline[128];
418         static struct scatterlist iov[32];
419         static struct scatterlist out[] = { {NULL, sizeof(outline)}, };
420         static struct scatterlist in[] = { {NULL, sizeof(line)}, };
421
422         static unsigned int inlen, outlen, conslen;
423         struct virtqueue *v = a->arg->virtio;
424         fprintf(stderr, "consin thread ..\n");
425         uint16_t head, gaveit = 0, gotitback = 0;
426         uint32_t vv;
427         int i;
428         int num;
429         //char c[1];
430
431         if (debug) fprintf(stderr, "Spin on console being read, print num queues, halt\n");
432
433         for(num = 0;! quit;num++) {
434                 //int debug = 1;
435                 /* host: use any buffers we should have been sent. */
436                 head = wait_for_vq_desc(v, iov, &outlen, &inlen);
437                 if (debug)
438                         fprintf(stderr, "vq desc head %d, gaveit %d gotitback %d\n", head, gaveit, gotitback);
439                 for(i = 0; debug && i < outlen + inlen; i++)
440                         fprintf(stderr, "v[%d/%d] v %p len %d\n", i, outlen + inlen, iov[i].v, iov[i].length);
441                 if (debug)
442                         fprintf(stderr, "outlen is %d; inlen is %d\n", outlen, inlen);
443                 /* host: fill in the writeable buffers. */
444                 for (i = outlen; i < outlen + inlen; i++) {
445                         /* host: read a line. */
446                         memset(consline, 0, 128);
447                         if (read(0, consline, 1) < 0) {
448                                 exit(0);
449                         }
450                         if (debug) fprintf(stderr, "CONSIN: GOT A LINE:%s:\n", consline);
451                         if (debug) fprintf(stderr, "CONSIN: OUTLEN:%d:\n", outlen);
452                         if (strlen(consline) < 3 && consline[0] == 'q' ) {
453                                 quit = 1;
454                                 break;
455                         }
456
457                         memmove(iov[i].v, consline, strlen(consline)+ 1);
458                         iov[i].length = strlen(consline) + 1;
459                 }
460                 if (debug) fprintf(stderr, "call add_used\n");
461                 /* host: now ack that we used them all. */
462                 add_used(v, head, outlen+inlen);
463                 /* turn off consdata - the IRQ injection isn't right */
464                 //consdata = 1;
465                 if (debug) fprintf(stderr, "DONE call add_used\n");
466
467                 // Send spurious for testing (Gan)
468                 set_posted_interrupt(0xE5);
469                 virtio_mmio_set_vring_irq();
470
471                 ros_syscall(SYS_vmm_poke_guest, 0, 0, 0, 0, 0, 0);
472         }
473         fprintf(stderr, "All done\n");
474         return NULL;
475 }
476
477 static struct vqdev vqdev= {
478 name: "console",
479 dev: VIRTIO_ID_CONSOLE,
480 device_features: 0, /* Can't do it: linux console device does not support it. VIRTIO_F_VERSION_1*/
481 numvqs: 2,
482 vqs: {
483                 {name: "consin", maxqnum: 64, f: consin, arg: (void *)0},
484                 {name: "consout", maxqnum: 64, f: consout, arg: (void *)0},
485         }
486 };
487
488 void lowmem() {
489         __asm__ __volatile__ (".section .lowmem, \"aw\"\n\tlow: \n\t.=0x1000\n\t.align 0x100000\n\t.previous\n");
490 }
491
492 static uint8_t acpi_tb_checksum(uint8_t *buffer, uint32_t length)
493 {
494         uint8_t sum = 0;
495         uint8_t *end = buffer + length;
496         fprintf(stderr, "tbchecksum %p for %d", buffer, length);
497         while (buffer < end) {
498                 if (end - buffer < 2)
499                         fprintf(stderr, "%02x\n", sum);
500                 sum = (uint8_t)(sum + *(buffer++));
501         }
502         fprintf(stderr, " is %02x\n", sum);
503         return (sum);
504 }
505
506 static void gencsum(uint8_t *target, void *data, int len)
507 {
508         uint8_t csum;
509         // blast target to zero so it does not get counted
510         // (it might be in the struct we checksum) And, yes, it is, goodness.
511         fprintf(stderr, "gencsum %p target %p source %d bytes\n", target, data, len);
512         *target = 0;
513         csum  = acpi_tb_checksum((uint8_t *)data, len);
514         *target = ~csum + 1;
515         fprintf(stderr, "Cmoputed is %02x\n", *target);
516 }
517
518 static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
519 {
520         int oldbit;
521
522         asm volatile(LOCK_PREFIX "bts %2,%1\n\t"
523                      "sbb %0,%0" : "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
524
525         return oldbit;
526 }
527
528 static void pir_dump()
529 {
530         unsigned long *pir_ptr = gpci.posted_irq_desc;
531         int i;
532         fprintf(stderr, "-------Begin PIR dump-------\n");
533         for (i = 0; i < 8; i++){
534                 fprintf(stderr, "Byte %d: 0x%016x\n", i, pir_ptr[i]);
535         }
536         fprintf(stderr, "-------End PIR dump-------\n");
537 }
538
539 static void set_posted_interrupt(int vector)
540 {
541         test_and_set_bit(vector, gpci.posted_irq_desc);
542         /* LOCKed instruction provides the mb() */
543         test_and_set_bit(VMX_POSTED_OUTSTANDING_NOTIF, gpci.posted_irq_desc);
544 }
545
546 int main(int argc, char **argv)
547 {
548         struct boot_params *bp;
549         char *cmdline_default = "earlyprintk=vmcall,keep"
550                                     " console=hvc0"
551                                     " virtio_mmio.device=1M@0x100000000:32"
552                                     " nosmp"
553                                     " maxcpus=1"
554                                     " acpi.debug_layer=0x2"
555                                     " acpi.debug_level=0xffffffff"
556                                     " apic=debug"
557                                     " noexec=off"
558                                     " nohlt"
559                                     " init=/bin/launcher"
560                                     " lapic=notscdeadline"
561                                     " lapictimerfreq=1000"
562                                     " pit=none";
563         char *cmdline_extra = "\0";
564         char *cmdline;
565         uint64_t *p64;
566         void *a = (void *)0xe0000;
567         struct acpi_table_rsdp *r;
568         struct acpi_table_fadt *f;
569         struct acpi_table_madt *m;
570         struct acpi_table_xsdt *x;
571         uint64_t virtiobase = 0x100000000ULL;
572         // lowmem is a bump allocated pointer to 2M at the "physbase" of memory
573         void *lowmem = (void *) 0x1000000;
574         //struct vmctl vmctl;
575         int amt;
576         int vmmflags = 0; // Disabled probably forever. VMM_VMCALL_PRINTF;
577         uint64_t entry = 0x1200000, kerneladdress = 0x1200000;
578         int nr_gpcs = 1;
579         int ret;
580         void * xp;
581         int kfd = -1;
582         static char cmd[512];
583         int i;
584         uint8_t csum;
585         void *coreboot_tables = (void *) 0x1165000;
586         void *a_page;
587         struct vm_trapframe *vm_tf;
588
589         the_ball = uth_mutex_alloc();
590         uth_mutex_lock(the_ball);
591
592         fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
593                         PML1_PTE_REACH);
594
595
596         // mmap is not working for us at present.
597         if ((uint64_t)_kernel > GKERNBASE) {
598                 fprintf(stderr, "kernel array @%p is above , GKERNBASE@%p sucks\n", _kernel, GKERNBASE);
599                 exit(1);
600         }
601         memset(_kernel, 0, sizeof(_kernel));
602         memset(lowmem, 0xff, 2*1048576);
603         memset(low4k, 0xff, 4096);
604         // avoid at all costs, requires too much instruction emulation.
605         //low4k[0x40e] = 0;
606         //low4k[0x40f] = 0xe0;
607
608         //Place mmap(Gan)
609         a_page = mmap((void *)0xfee00000, PGSIZE, PROT_READ | PROT_WRITE,
610                               MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
611         fprintf(stderr, "a_page mmap pointer %p\n", a_page);
612
613         if (a_page == (void *) -1) {
614                 perror("Could not mmap APIC");
615                 exit(1);
616         }
617         if (((uint64_t)a_page & 0xfff) != 0) {
618                 perror("APIC page mapping is not page aligned");
619                 exit(1);
620         }
621
622         memset(a_page, 0, 4096);
623         ((uint32_t *)a_page)[0x30/4] = 0x01060015;
624         //((uint32_t *)a_page)[0x30/4] = 0xDEADBEEF;
625
626
627         argc--, argv++;
628         // switches ...
629         // Sorry, I don't much like the gnu opt parsing code.
630         while (1) {
631                 if (*argv[0] != '-')
632                         break;
633                 switch(argv[0][1]) {
634                 case 'd':
635                         debug++;
636                         break;
637                 case 'v':
638                         vmmflags |= VMM_VMCALL_PRINTF;
639                         break;
640                 case 'm':
641                         argc--, argv++;
642                         maxresume = strtoull(argv[0], 0, 0);
643                         break;
644                 case 'i':
645                         argc--, argv++;
646                         virtioirq = strtoull(argv[0], 0, 0);
647                         break;
648                 case 'c':
649                         argc--, argv++;
650                         cmdline_extra = argv[0];
651                 default:
652                         fprintf(stderr, "BMAFR\n");
653                         break;
654                 }
655                 argc--, argv++;
656         }
657         if (argc < 1) {
658                 fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)] [coreboot_tables [loadaddress [entrypoint]]]\n", argv[0]);
659                 exit(1);
660         }
661         if (argc > 1)
662                 coreboot_tables = (void *) strtoull(argv[1], 0, 0);
663         if (argc > 2)
664                 kerneladdress = strtoull(argv[2], 0, 0);
665         if (argc > 3)
666                 entry = strtoull(argv[3], 0, 0);
667         kfd = open(argv[0], O_RDONLY);
668         if (kfd < 0) {
669                 perror(argv[0]);
670                 exit(1);
671         }
672         // read in the kernel.
673         xp = (void *)kerneladdress;
674         for(;;) {
675                 amt = read(kfd, xp, 1048576);
676                 if (amt < 0) {
677                         perror("read");
678                         exit(1);
679                 }
680                 if (amt == 0) {
681                         break;
682                 }
683                 xp += amt;
684         }
685         fprintf(stderr, "Read in %d bytes\n", xp-kerneladdress);
686         close(kfd);
687
688         // The low 1m so we can fill in bullshit like ACPI. */
689         // And, sorry, due to the STUPID format of the RSDP for now we need the low 1M.
690         low1m = mmap((int*)4096, MiB-4096, PROT_READ | PROT_WRITE,
691                          MAP_ANONYMOUS, -1, 0);
692         if (low1m != (void *)4096) {
693                 perror("Unable to mmap low 1m");
694                 exit(1);
695         }
696         memset(low1m, 0xff, MiB-4096);
697         r = a;
698         fprintf(stderr, "install rsdp to %p\n", r);
699         *r = rsdp;
700         a += sizeof(*r);
701         memmove(&r->xsdt_physical_address, &a, sizeof(a));
702         gencsum(&r->checksum, r, ACPI_RSDP_CHECKSUM_LENGTH);
703         if ((csum = acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_CHECKSUM_LENGTH)) != 0) {
704                 fprintf(stderr, "RSDP has bad checksum; summed to %x\n", csum);
705                 exit(1);
706         }
707
708         /* Check extended checksum if table version >= 2 */
709         gencsum(&r->extended_checksum, r, ACPI_RSDP_XCHECKSUM_LENGTH);
710         if ((rsdp.revision >= 2) &&
711             (acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_XCHECKSUM_LENGTH) != 0)) {
712                 fprintf(stderr, "RSDP has bad checksum v2\n");
713                 exit(1);
714         }
715
716         /* just leave a bunch of space for the xsdt. */
717         /* we need to zero the area since it has pointers. */
718         x = a;
719         a += sizeof(*x) + 8*sizeof(void *);
720         memset(x, 0, a - (void *)x);
721         fprintf(stderr, "install xsdt to %p\n", x);
722         *x = xsdt;
723         x->table_offset_entry[0] = 0;
724         x->table_offset_entry[1] = 0;
725         x->header.length = a - (void *)x;
726
727         f = a;
728         fprintf(stderr, "install fadt to %p\n", f);
729         *f = fadt;
730         x->table_offset_entry[2] = (uint64_t) f;
731         a += sizeof(*f);
732         f->header.length = a - (void *)f;
733         gencsum(&f->header.checksum, f, f->header.length);
734         if (acpi_tb_checksum((uint8_t *)f, f->header.length) != 0) {
735                 fprintf(stderr, "ffadt has bad checksum v2\n");
736                 exit(1);
737         }
738
739         m = a;
740         *m = madt;
741         x->table_offset_entry[3] = (uint64_t) m;
742         a += sizeof(*m);
743         fprintf(stderr, "install madt to %p\n", m);
744         memmove(a, &Apic0, sizeof(Apic0));
745         a += sizeof(Apic0);
746         memmove(a, &Apic1, sizeof(Apic1));
747         a += sizeof(Apic1);
748         memmove(a, &X2Apic0, sizeof(X2Apic0));
749         a += sizeof(X2Apic0);
750         memmove(a, &isor, sizeof(isor));
751         a += sizeof(isor);
752         m->header.length = a - (void *)m;
753         gencsum(&m->header.checksum, m, m->header.length);
754         if (acpi_tb_checksum((uint8_t *) m, m->header.length) != 0) {
755                 fprintf(stderr, "madt has bad checksum v2\n");
756                 exit(1);
757         }
758         fprintf(stderr, "allchecksums ok\n");
759
760         gencsum(&x->header.checksum, x, x->header.length);
761         if ((csum = acpi_tb_checksum((uint8_t *) x, x->header.length)) != 0) {
762                 fprintf(stderr, "XSDT has bad checksum; summed to %x\n", csum);
763                 exit(1);
764         }
765
766         hexdump(stdout, r, a-(void *)r);
767
768         a = (void *)(((unsigned long)a + 0xfff) & ~0xfff);
769         gpci.posted_irq_desc = a;
770         memset(a, 0, 4096);
771         a += 4096;
772         gpci.vapic_addr = a;
773         //vmctl.vapic = (uint64_t) a_page;
774         memset(a, 0, 4096);
775         ((uint32_t *)a)[0x30/4] = 0x01060014;
776         p64 = a;
777         // set up apic values? do we need to?
778         // qemu does this.
779         //((uint8_t *)a)[4] = 1;
780         a += 4096;
781         gpci.apic_addr = (void*)0xfee00000;
782
783         /* Allocate memory for, and zero the bootparams
784          * page before writing to it, or Linux thinks
785          * we're talking crazy.
786          */
787         a += 4096;
788         bp = a;
789         memset(bp, 0, 4096);
790
791         /* Set the kernel command line parameters */
792         a += 4096;
793         cmdline = a;
794         a += 4096;
795         bp->hdr.cmd_line_ptr = (uintptr_t) cmdline;
796         sprintf(cmdline, "%s %s", cmdline_default, cmdline_extra);
797
798
799         /* Put the e820 memory region information in the boot_params */
800         bp->e820_entries = 3;
801         int e820i = 0;
802
803         bp->e820_map[e820i].addr = 0;
804         bp->e820_map[e820i].size = 16 * 1048576;
805         bp->e820_map[e820i++].type = E820_RESERVED;
806
807         bp->e820_map[e820i].addr = 16 * 1048576;
808         bp->e820_map[e820i].size = 128 * 1048576;
809         bp->e820_map[e820i++].type = E820_RAM;
810
811         bp->e820_map[e820i].addr = 0xf0000000;
812         bp->e820_map[e820i].size = 0x10000000;
813         bp->e820_map[e820i++].type = E820_RESERVED;
814
815         if (ros_syscall(SYS_vmm_setup, nr_gpcs, &gpci, vmmflags, 0, 0, 0) !=
816             nr_gpcs) {
817                 perror("Guest pcore setup failed");
818                 exit(1);
819         }
820
821         fprintf(stderr, "Run with %d cores and vmmflags 0x%x\n", nr_gpcs, vmmflags);
822         mcp = 1;
823         if (mcp) {
824                 my_retvals = malloc(sizeof(void*) * nr_threads);
825                 if (!my_retvals)
826                         perror("Init threads/malloc");
827
828                 pthread_can_vcore_request(FALSE);       /* 2LS won't manage vcores */
829                 pthread_need_tls(FALSE);
830                 pthread_mcp_init();                                     /* gives us one vcore */
831                 vcore_request(nr_threads - 1);          /* ghetto incremental interface */
832                 for (int i = 0; i < nr_threads; i++) {
833                         xp = __procinfo.vcoremap;
834                         fprintf(stderr, "%p\n", __procinfo.vcoremap);
835                         fprintf(stderr, "Vcore %d mapped to pcore %d\n", i,
836                                 __procinfo.vcoremap[i].pcoreid);
837                 }
838         }
839
840         ret = syscall(33, 1);
841         if (ret < 0) {
842                 perror("vm setup");
843                 exit(1);
844         }
845         ret = posix_memalign((void **)&p512, 4096, 3*4096);
846         fprintf(stderr, "memalign is %p\n", p512);
847         if (ret) {
848                 perror("ptp alloc");
849                 exit(1);
850         }
851         p1 = &p512[512];
852         p2m = &p512[1024];
853         uint64_t kernbase = 0; //0xffffffff80000000;
854         uint64_t highkernbase = 0xffffffff80000000;
855         p512[PML4(kernbase)] = (unsigned long long)p1 | 7;
856         p1[PML3(kernbase)] = /*0x87; */(unsigned long long)p2m | 7;
857         p512[PML4(highkernbase)] = (unsigned long long)p1 | 7;
858         p1[PML3(highkernbase)] = /*0x87; */(unsigned long long)p2m | 7;
859 #define _2MiB (0x200000)
860
861         for (i = 0; i < 512; i++) {
862                 p2m[PML2(kernbase + i * _2MiB)] = 0x87 | i * _2MiB;
863         }
864
865         kernbase >>= (0+12);
866         kernbase <<= (0 + 12);
867         uint8_t *kernel = (void *)GKERNBASE;
868         //write_coreboot_table(coreboot_tables, ((void *)VIRTIOBASE) /*kernel*/, KERNSIZE + 1048576);
869         hexdump(stdout, coreboot_tables, 512);
870         fprintf(stderr, "kernbase for pml4 is 0x%llx and entry is %llx\n", kernbase, entry);
871         fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);
872         vmctl.interrupt = 0;
873         vmctl.command = REG_RSP_RIP_CR3;
874         vmctl.cr3 = (uint64_t) p512;
875         vmctl.regs.tf_rip = entry;
876         vmctl.regs.tf_rsp = (uint64_t) &stack[1024];
877         vmctl.regs.tf_rsi = (uint64_t) bp;
878         if (mcp) {
879                 /* set up virtio bits, which depend on threads being enabled. */
880                 register_virtio_mmio(&vqdev, virtio_mmio_base);
881         }
882         fprintf(stderr, "threads started\n");
883         fprintf(stderr, "Writing command :%s:\n", cmd);
884
885         if (debug)
886                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
887
888         run_vmthread(&vmctl);
889
890         if (debug)
891                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
892
893         if (0 && !timer_started && mcp) {
894                 /* Start up timer thread */
895                 if (pthread_create(&timerthread_struct, NULL, timer_thread, NULL)) {
896                         fprintf(stderr, "pth_create failed for timer thread.");
897                         perror("pth_create");
898                 } else {
899                         timer_started = 1;
900                 }
901         }
902
903         vm_tf = &(vm_thread->uthread.u_ctx.tf.vm_tf);
904
905         while (1) {
906
907                 int c;
908                 uint8_t byte;
909                 //vmctl.command = REG_RIP;
910                 if (maxresume-- == 0) {
911                         debug = 1;
912                         resumeprompt = 1;
913                 }
914                 if (debug) {
915                         fprintf(stderr, "RIP %p, exit reason 0x%x\n", vm_tf->tf_rip,
916                                 vm_tf->tf_exit_reason);
917                         showstatus(stderr, (struct guest_thread*)&vm_thread);
918                 }
919                 if (resumeprompt) {
920                         fprintf(stderr, "RESUME?\n");
921                         c = getchar();
922                         if (c == 'q')
923                                 break;
924                 }
925                 if (vm_tf->tf_exit_reason == EXIT_REASON_EPT_VIOLATION) {
926                         uint64_t gpa, *regp, val;
927                         uint8_t regx;
928                         int store, size;
929                         int advance;
930                         if (decode((struct guest_thread *) vm_thread, &gpa, &regx, &regp,
931                                    &store, &size, &advance)) {
932                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
933                                         vm_tf->tf_exit_reason);
934                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
935                                 quit = 1;
936                                 break;
937                         }
938                         if (debug) fprintf(stderr, "%p %p %p %p %p %p\n", gpa, regx, regp, store, size, advance);
939                         if ((gpa & ~0xfffULL) == virtiobase) {
940                                 if (debug) fprintf(stderr, "DO SOME VIRTIO\n");
941                                 // Lucky for us the various virtio ops are well-defined.
942                                 virtio_mmio((struct guest_thread *)vm_thread, gpa, regx, regp,
943                                             store);
944                                 if (debug) fprintf(stderr, "store is %d:\n", store);
945                                 if (debug) fprintf(stderr, "REGP IS %16x:\n", *regp);
946                         } else if ((gpa & 0xfee00000) == 0xfee00000) {
947                                 // until we fix our include mess, just put the proto here.
948                                 //int apic(struct vmctl *v, uint64_t gpa, int destreg, uint64_t *regp, int store);
949                                 //apic(&vmctl, gpa, regx, regp, store);
950                         } else if ((gpa & 0xfec00000) == 0xfec00000) {
951                                 // until we fix our include mess, just put the proto here.
952                                 do_ioapic((struct guest_thread *)vm_thread, gpa, regx, regp,
953                                           store);
954                         } else if (gpa < 4096) {
955                                 uint64_t val = 0;
956                                 memmove(&val, &low4k[gpa], size);
957                                 hexdump(stdout, &low4k[gpa], size);
958                                 fprintf(stderr, "Low 1m, code %p read @ %p, size %d, val %p\n",
959                                         vm_tf->tf_rip, gpa, size, val);
960                                 memmove(regp, &low4k[gpa], size);
961                                 hexdump(stdout, regp, size);
962                         } else {
963                                 fprintf(stderr, "EPT violation: can't handle %p\n", gpa);
964                                 fprintf(stderr, "RIP %p, exit reason 0x%x\n", vm_tf->tf_rip,
965                                         vm_tf->tf_exit_reason);
966                                 fprintf(stderr, "Returning 0xffffffff\n");
967                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
968                                 // Just fill the whole register for now.
969                                 *regp = (uint64_t) -1;
970                         }
971                         vm_tf->tf_rip += advance;
972                         if (debug)
973                                 fprintf(stderr, "Advance rip by %d bytes to %p\n",
974                                         advance, vm_tf->tf_rip);
975                         //vmctl.shutdown = 0;
976                         //vmctl.gpa = 0;
977                         //vmctl.command = REG_ALL;
978                 } else {
979                         switch (vm_tf->tf_exit_reason) {
980                         case  EXIT_REASON_VMCALL:
981                                 byte = vm_tf->tf_rdi;
982                                 printf("%c", byte);
983                                 if (byte == '\n') printf("%c", '%');
984                                 vm_tf->tf_rip += 3;
985                                 break;
986                         case EXIT_REASON_EXTERNAL_INTERRUPT:
987                                 //debug = 1;
988                                 if (debug)
989                                         fprintf(stderr, "XINT 0x%x 0x%x\n",
990                                                 vm_tf->tf_intrinfo1, vm_tf->tf_intrinfo2);
991                                 if (debug) pir_dump();
992                                 //vmctl.command = RESUME;
993                                 break;
994                         case EXIT_REASON_IO_INSTRUCTION:
995                                 fprintf(stderr, "IO @ %p\n", vm_tf->tf_rip);
996                                 io((struct guest_thread *)vm_thread);
997                                 //vmctl.shutdown = 0;
998                                 //vmctl.gpa = 0;
999                                 //vmctl.command = REG_ALL;
1000                                 break;
1001                         case EXIT_REASON_INTERRUPT_WINDOW:
1002                                 if (consdata) {
1003                                         if (debug) fprintf(stderr, "inject an interrupt\n");
1004                                         virtio_mmio_set_vring_irq();
1005                                         vm_tf->tf_trap_inject = 0x80000000 | virtioirq;
1006                                         //vmctl.command = RESUME;
1007                                         consdata = 0;
1008                                 }
1009                                 break;
1010                         case EXIT_REASON_MSR_WRITE:
1011                         case EXIT_REASON_MSR_READ:
1012                                 fprintf(stderr, "Do an msr\n");
1013                                 if (msrio((struct guest_thread *)vm_thread,
1014                                           vm_tf->tf_exit_reason)) {
1015                                         // uh-oh, msrio failed
1016                                         // well, hand back a GP fault which is what Intel does
1017                                         fprintf(stderr, "MSR FAILED: RIP %p, shutdown 0x%x\n",
1018                                                 vm_tf->tf_rip, vm_tf->tf_exit_reason);
1019                                         showstatus(stderr, (struct guest_thread*)&vm_thread);
1020
1021                                         // Use event injection through vmctl to send
1022                                         // a general protection fault
1023                                         // vmctl.interrupt gets written to the VM-Entry
1024                                         // Interruption-Information Field by vmx
1025                                         vm_tf->tf_trap_inject = VM_TRAP_VALID
1026                                                               | VM_TRAP_ERROR_CODE
1027                                                               | VM_TRAP_HARDWARE
1028                                                               | 13; // GPF
1029                                 } else {
1030                                         vm_tf->tf_rip += 2;
1031                                 }
1032                                 break;
1033                         case EXIT_REASON_MWAIT_INSTRUCTION:
1034                           fflush(stdout);
1035                                 if (debug)fprintf(stderr, "\n================== Guest MWAIT. =======================\n");
1036                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1037                                 while (!consdata)
1038                                         ;
1039                                 //debug = 1;
1040                                 if (debug)
1041                                         vapic_status_dump(stderr, gpci.vapic_addr);
1042                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1043                                 vm_tf->tf_rip += 3;
1044                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1045                                 //showstatus(stderr, (struct guest_thread*)&vm_thread);
1046                                 break;
1047                         case EXIT_REASON_HLT:
1048                                 fflush(stdout);
1049                                 if (debug)fprintf(stderr, "\n================== Guest halted. =======================\n");
1050                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1051                                 while (!consdata)
1052                                         ;
1053                                 //debug = 1;
1054                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1055                                 vm_tf->tf_rip += 1;
1056                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1057                                 //showstatus(stderr, (struct guest_thread*)&vm_thread);
1058                                 break;
1059                         case EXIT_REASON_APIC_ACCESS:
1060                                 if (1 || debug)fprintf(stderr, "APIC READ EXIT\n");
1061
1062                                 uint64_t gpa, *regp, val;
1063                                 uint8_t regx;
1064                                 int store, size;
1065                                 int advance;
1066                                 if (decode((struct guest_thread *)vm_thread, &gpa, &regx,
1067                                            &regp, &store, &size, &advance)) {
1068                                         fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
1069                                                 vm_tf->tf_exit_reason);
1070                                         showstatus(stderr, (struct guest_thread*)&vm_thread);
1071                                         quit = 1;
1072                                         break;
1073                                 }
1074
1075                                 int apic(struct guest_thread *vm_thread, uint64_t gpa,
1076                                          int destreg, uint64_t *regp, int store);
1077                                 apic((struct guest_thread *)vm_thread, gpa, regx, regp, store);
1078                                 vm_tf->tf_rip += advance;
1079                                 if (debug)
1080                                         fprintf(stderr, "Advance rip by %d bytes to %p\n",
1081                                                 advance, vm_tf->tf_rip);
1082                                 //vmctl.shutdown = 0;
1083                                 //vmctl.gpa = 0;
1084                                 //vmctl.command = REG_ALL;
1085                                 break;
1086                         case EXIT_REASON_APIC_WRITE:
1087                                 if (1 || debug)fprintf(stderr, "APIC WRITE EXIT\n");
1088                                 break;
1089                         default:
1090                                 fprintf(stderr, "Don't know how to handle exit %d\n",
1091                                         vm_tf->tf_exit_reason);
1092                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
1093                                         vm_tf->tf_exit_reason);
1094                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
1095                                 quit = 1;
1096                                 break;
1097                         }
1098                 }
1099                 if (debug) fprintf(stderr, "at bottom of switch, quit is %d\n", quit);
1100                 if (quit)
1101                         break;
1102                 if (consdata) {
1103                         if (debug) fprintf(stderr, "inject an interrupt\n");
1104                         if (debug)
1105                                 fprintf(stderr, "XINT 0x%x 0x%x\n", vm_tf->tf_intrinfo1,
1106                                         vm_tf->tf_intrinfo2);
1107                         vm_tf->tf_trap_inject = 0x80000000 | virtioirq;
1108                         virtio_mmio_set_vring_irq();
1109                         consdata = 0;
1110                         //debug = 1;
1111                         //vmctl.command = RESUME;
1112                 }
1113                 if (debug) fprintf(stderr, "NOW DO A RESUME\n");
1114                 copy_vmtf_to_vmctl(vm_tf, &vmctl);
1115                 run_vmthread(&vmctl);
1116                 copy_vmctl_to_vmtf(&vmctl, vm_tf);
1117         }
1118
1119         /* later.
1120         for (int i = 0; i < nr_threads-1; i++) {
1121                 int ret;
1122                 if (pthread_join(my_threads[i], &my_retvals[i]))
1123                         perror("pth_join failed");
1124                 fprintf(stderr, "%d %d\n", i, ret);
1125         }
1126  */
1127
1128         fflush(stdout);
1129         exit(0);
1130 }