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