Virtualization changes to handle X2APIC mode.
[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;
554         uint64_t *p64;
555         void *a = (void *)0xe0000;
556         struct acpi_table_rsdp *r;
557         struct acpi_table_fadt *f;
558         struct acpi_table_madt *m;
559         struct acpi_table_xsdt *x;
560         uint64_t virtiobase = 0x100000000ULL;
561         // lowmem is a bump allocated pointer to 2M at the "physbase" of memory
562         void *lowmem = (void *) 0x1000000;
563         //struct vmctl vmctl;
564         int amt;
565         int vmmflags = 0; // Disabled probably forever. VMM_VMCALL_PRINTF;
566         uint64_t entry = 0x1200000, kerneladdress = 0x1200000;
567         int nr_gpcs = 1;
568         int ret;
569         void * xp;
570         int kfd = -1;
571         static char cmd[512];
572         int i;
573         uint8_t csum;
574         void *coreboot_tables = (void *) 0x1165000;
575         void *a_page;
576
577         the_ball = uth_mutex_alloc();
578         uth_mutex_lock(the_ball);
579
580         fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
581                         PML1_PTE_REACH);
582
583
584         // mmap is not working for us at present.
585         if ((uint64_t)_kernel > GKERNBASE) {
586                 fprintf(stderr, "kernel array @%p is above , GKERNBASE@%p sucks\n", _kernel, GKERNBASE);
587                 exit(1);
588         }
589         memset(_kernel, 0, sizeof(_kernel));
590         memset(lowmem, 0xff, 2*1048576);
591         memset(low4k, 0xff, 4096);
592         // avoid at all costs, requires too much instruction emulation.
593         //low4k[0x40e] = 0;
594         //low4k[0x40f] = 0xe0;
595
596         //Place mmap(Gan)
597         a_page = mmap((void *)0xfee00000, PGSIZE, PROT_READ | PROT_WRITE,
598                               MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
599         fprintf(stderr, "a_page mmap pointer %p\n", a_page);
600
601         if (a_page == (void *) -1) {
602                 perror("Could not mmap APIC");
603                 exit(1);
604         }
605         if (((uint64_t)a_page & 0xfff) != 0) {
606                 perror("APIC page mapping is not page aligned");
607                 exit(1);
608         }
609
610         memset(a_page, 0, 4096);
611         ((uint32_t *)a_page)[0x30/4] = 0x01060015;
612         //((uint32_t *)a_page)[0x30/4] = 0xDEADBEEF;
613
614
615         argc--,argv++;
616         // switches ...
617         // Sorry, I don't much like the gnu opt parsing code.
618         while (1) {
619                 if (*argv[0] != '-')
620                         break;
621                 switch(argv[0][1]) {
622                 case 'd':
623                         debug++;
624                         break;
625                 case 'v':
626                         vmmflags |= VMM_VMCALL_PRINTF;
627                         break;
628                 case 'm':
629                         argc--,argv++;
630                         maxresume = strtoull(argv[0], 0, 0);
631                         break;
632                 case 'i':
633                         argc--,argv++;
634                         virtioirq = strtoull(argv[0], 0, 0);
635                         break;
636                 default:
637                         fprintf(stderr, "BMAFR\n");
638                         break;
639                 }
640                 argc--,argv++;
641         }
642         if (argc < 1) {
643                 fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)] [coreboot_tables [loadaddress [entrypoint]]]\n", argv[0]);
644                 exit(1);
645         }
646         if (argc > 1)
647                 coreboot_tables = (void *) strtoull(argv[1], 0, 0);
648         if (argc > 2)
649                 kerneladdress = strtoull(argv[2], 0, 0);
650         if (argc > 3)
651                 entry = strtoull(argv[3], 0, 0);
652         kfd = open(argv[0], O_RDONLY);
653         if (kfd < 0) {
654                 perror(argv[0]);
655                 exit(1);
656         }
657         // read in the kernel.
658         xp = (void *)kerneladdress;
659         for(;;) {
660                 amt = read(kfd, xp, 1048576);
661                 if (amt < 0) {
662                         perror("read");
663                         exit(1);
664                 }
665                 if (amt == 0) {
666                         break;
667                 }
668                 xp += amt;
669         }
670         fprintf(stderr, "Read in %d bytes\n", xp-kerneladdress);
671         close(kfd);
672
673         // The low 1m so we can fill in bullshit like ACPI. */
674         // And, sorry, due to the STUPID format of the RSDP for now we need the low 1M.
675         low1m = mmap((int*)4096, MiB-4096, PROT_READ | PROT_WRITE,
676                          MAP_ANONYMOUS, -1, 0);
677         if (low1m != (void *)4096) {
678                 perror("Unable to mmap low 1m");
679                 exit(1);
680         }
681         memset(low1m, 0xff, MiB-4096);
682         r = a;
683         fprintf(stderr, "install rsdp to %p\n", r);
684         *r = rsdp;
685         a += sizeof(*r);
686         memmove(&r->xsdt_physical_address, &a, sizeof(a));
687         gencsum(&r->checksum, r, ACPI_RSDP_CHECKSUM_LENGTH);
688         if ((csum = acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_CHECKSUM_LENGTH)) != 0) {
689                 fprintf(stderr, "RSDP has bad checksum; summed to %x\n", csum);
690                 exit(1);
691         }
692
693         /* Check extended checksum if table version >= 2 */
694         gencsum(&r->extended_checksum, r, ACPI_RSDP_XCHECKSUM_LENGTH);
695         if ((rsdp.revision >= 2) &&
696             (acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_XCHECKSUM_LENGTH) != 0)) {
697                 fprintf(stderr, "RSDP has bad checksum v2\n");
698                 exit(1);
699         }
700
701         /* just leave a bunch of space for the xsdt. */
702         /* we need to zero the area since it has pointers. */
703         x = a;
704         a += sizeof(*x) + 8*sizeof(void *);
705         memset(x, 0, a - (void *)x);
706         fprintf(stderr, "install xsdt to %p\n", x);
707         *x = xsdt;
708         x->table_offset_entry[0] = 0;
709         x->table_offset_entry[1] = 0;
710         x->header.length = a - (void *)x;
711
712         f = a;
713         fprintf(stderr, "install fadt to %p\n", f);
714         *f = fadt;
715         x->table_offset_entry[2] = (uint64_t) f;
716         a += sizeof(*f);
717         f->header.length = a - (void *)f;
718         gencsum(&f->header.checksum, f, f->header.length);
719         if (acpi_tb_checksum((uint8_t *)f, f->header.length) != 0) {
720                 fprintf(stderr, "ffadt has bad checksum v2\n");
721                 exit(1);
722         }
723
724         m = a;
725         *m = madt;
726         x->table_offset_entry[3] = (uint64_t) m;
727         a += sizeof(*m);
728         fprintf(stderr, "install madt to %p\n", m);
729         memmove(a, &Apic0, sizeof(Apic0));
730         a += sizeof(Apic0);
731         memmove(a, &Apic1, sizeof(Apic1));
732         a += sizeof(Apic1);
733         memmove(a, &X2Apic0, sizeof(X2Apic0));
734         a += sizeof(X2Apic0);
735         memmove(a, &isor, sizeof(isor));
736         a += sizeof(isor);
737         m->header.length = a - (void *)m;
738         gencsum(&m->header.checksum, m, m->header.length);
739         if (acpi_tb_checksum((uint8_t *) m, m->header.length) != 0) {
740                 fprintf(stderr, "madt has bad checksum v2\n");
741                 exit(1);
742         }
743         fprintf(stderr, "allchecksums ok\n");
744
745         gencsum(&x->header.checksum, x, x->header.length);
746         if ((csum = acpi_tb_checksum((uint8_t *) x, x->header.length)) != 0) {
747                 fprintf(stderr, "XSDT has bad checksum; summed to %x\n", csum);
748                 exit(1);
749         }
750
751         hexdump(stdout, r, a-(void *)r);
752
753         a = (void *)(((unsigned long)a + 0xfff) & ~0xfff);
754         gpci.posted_irq_desc = a;
755         memset(a, 0, 4096);
756         a += 4096;
757         gpci.vapic_addr = a;
758         //vmctl.vapic = (uint64_t) a_page;
759         memset(a, 0, 4096);
760         ((uint32_t *)a)[0x30/4] = 0x01060014;
761         p64 = a;
762         // set up apic values? do we need to?
763         // qemu does this.
764         //((uint8_t *)a)[4] = 1;
765         a += 4096;
766         gpci.apic_addr = (void*)0xfee00000;
767
768         /* Allocate memory for, and zero the bootparams
769          * page before writing to it, or Linux thinks
770          * we're talking crazy.
771          */
772         a += 4096;
773         bp = a;
774         memset(bp, 0, 4096);
775
776         /* Set the kernel command line parameters */
777         a += 4096;
778         cmdline = a;
779         a += 4096;
780         bp->hdr.cmd_line_ptr = (uintptr_t) cmdline;
781         sprintf(cmdline, "earlyprintk=vmcall,keep"
782                              " console=hvc0"
783                              " virtio_mmio.device=1M@0x100000000:32"
784                              " nosmp"
785                              " maxcpus=1"
786                              " acpi.debug_layer=0x2"
787                              " acpi.debug_level=0xffffffff"
788                              " apic=debug"
789                              " noexec=off"
790                              " nohlt"
791                              " init=/bin/sh"
792                              " lapic=notscdeadline"
793                              " lapictimerfreq=1000"
794                              " pit=none");
795
796
797         /* Put the e820 memory region information in the boot_params */
798         bp->e820_entries = 3;
799         int e820i = 0;
800
801         bp->e820_map[e820i].addr = 0;
802         bp->e820_map[e820i].size = 16 * 1048576;
803         bp->e820_map[e820i++].type = E820_RESERVED;
804
805         bp->e820_map[e820i].addr = 16 * 1048576;
806         bp->e820_map[e820i].size = 128 * 1048576;
807         bp->e820_map[e820i++].type = E820_RAM;
808
809         bp->e820_map[e820i].addr = 0xf0000000;
810         bp->e820_map[e820i].size = 0x10000000;
811         bp->e820_map[e820i++].type = E820_RESERVED;
812
813         if (ros_syscall(SYS_vmm_setup, nr_gpcs, &gpci, vmmflags, 0, 0, 0) !=
814             nr_gpcs) {
815                 perror("Guest pcore setup failed");
816                 exit(1);
817         }
818
819         fprintf(stderr, "Run with %d cores and vmmflags 0x%x\n", nr_gpcs, vmmflags);
820         mcp = 1;
821         if (mcp) {
822                 my_retvals = malloc(sizeof(void*) * nr_threads);
823                 if (!my_retvals)
824                         perror("Init threads/malloc");
825
826                 pthread_can_vcore_request(FALSE);       /* 2LS won't manage vcores */
827                 pthread_need_tls(FALSE);
828                 pthread_mcp_init();                                     /* gives us one vcore */
829                 vcore_request(nr_threads - 1);          /* ghetto incremental interface */
830                 for (int i = 0; i < nr_threads; i++) {
831                         xp = __procinfo.vcoremap;
832                         fprintf(stderr, "%p\n", __procinfo.vcoremap);
833                         fprintf(stderr, "Vcore %d mapped to pcore %d\n", i,
834                                 __procinfo.vcoremap[i].pcoreid);
835                 }
836         }
837
838         ret = syscall(33, 1);
839         if (ret < 0) {
840                 perror("vm setup");
841                 exit(1);
842         }
843         ret = posix_memalign((void **)&p512, 4096, 3*4096);
844         fprintf(stderr, "memalign is %p\n", p512);
845         if (ret) {
846                 perror("ptp alloc");
847                 exit(1);
848         }
849         p1 = &p512[512];
850         p2m = &p512[1024];
851         uint64_t kernbase = 0; //0xffffffff80000000;
852         uint64_t highkernbase = 0xffffffff80000000;
853         p512[PML4(kernbase)] = (unsigned long long)p1 | 7;
854         p1[PML3(kernbase)] = /*0x87; */(unsigned long long)p2m | 7;
855         p512[PML4(highkernbase)] = (unsigned long long)p1 | 7;
856         p1[PML3(highkernbase)] = /*0x87; */(unsigned long long)p2m | 7;
857 #define _2MiB (0x200000)
858
859         for (i = 0; i < 512; i++) {
860                 p2m[PML2(kernbase + i * _2MiB)] = 0x87 | i * _2MiB;
861         }
862
863         kernbase >>= (0+12);
864         kernbase <<= (0 + 12);
865         uint8_t *kernel = (void *)GKERNBASE;
866         //write_coreboot_table(coreboot_tables, ((void *)VIRTIOBASE) /*kernel*/, KERNSIZE + 1048576);
867         hexdump(stdout, coreboot_tables, 512);
868         fprintf(stderr, "kernbase for pml4 is 0x%llx and entry is %llx\n", kernbase, entry);
869         fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);
870         vmctl.interrupt = 0;
871         vmctl.command = REG_RSP_RIP_CR3;
872         vmctl.cr3 = (uint64_t) p512;
873         vmctl.regs.tf_rip = entry;
874         vmctl.regs.tf_rsp = (uint64_t) &stack[1024];
875         vmctl.regs.tf_rsi = (uint64_t) bp;
876         if (mcp) {
877                 /* set up virtio bits, which depend on threads being enabled. */
878                 register_virtio_mmio(&vqdev, virtio_mmio_base);
879         }
880         fprintf(stderr, "threads started\n");
881         fprintf(stderr, "Writing command :%s:\n", cmd);
882
883         if (debug)
884                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
885
886         run_vmthread(&vmctl);
887
888         if (debug)
889                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
890
891         if (0 && !timer_started && mcp) {
892                 /* Start up timer thread */
893                 if (pthread_create(&timerthread_struct, NULL, timer_thread, NULL)) {
894                         fprintf(stderr, "pth_create failed for timer thread.");
895                         perror("pth_create");
896                 } else {
897                         timer_started = 1;
898                 }
899         }
900
901         while (1) {
902
903                 int c;
904                 uint8_t byte;
905                 vmctl.command = REG_RIP;
906                 if (maxresume-- == 0) {
907                         debug = 1;
908                         resumeprompt = 1;
909                 }
910                 if (debug) {
911                         fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
912                         showstatus(stderr, &vmctl);
913                 }
914                 if (resumeprompt) {
915                         fprintf(stderr, "RESUME?\n");
916                         c = getchar();
917                         if (c == 'q')
918                                 break;
919                 }
920                 if (vmctl.shutdown == SHUTDOWN_EPT_VIOLATION) {
921                         uint64_t gpa, *regp, val;
922                         uint8_t regx;
923                         int store, size;
924                         int advance;
925                         if (decode(&vmctl, &gpa, &regx, &regp, &store, &size, &advance)) {
926                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
927                                 showstatus(stderr, &vmctl);
928                                 quit = 1;
929                                 break;
930                         }
931                         if (debug) fprintf(stderr, "%p %p %p %p %p %p\n", gpa, regx, regp, store, size, advance);
932                         if ((gpa & ~0xfffULL) == virtiobase) {
933                                 if (debug) fprintf(stderr, "DO SOME VIRTIO\n");
934                                 // Lucky for us the various virtio ops are well-defined.
935                                 virtio_mmio(&vmctl, gpa, regx, regp, store);
936                                 if (debug) fprintf(stderr, "store is %d:\n", store);
937                                 if (debug) fprintf(stderr, "REGP IS %16x:\n", *regp);
938                         } else if ((gpa & 0xfee00000) == 0xfee00000) {
939                                 // until we fix our include mess, just put the proto here.
940                                 //int apic(struct vmctl *v, uint64_t gpa, int destreg, uint64_t *regp, int store);
941                                 //apic(&vmctl, gpa, regx, regp, store);
942                         } else if ((gpa & 0xfec00000) == 0xfec00000) {
943                                 // until we fix our include mess, just put the proto here.
944                                 int do_ioapic(struct vmctl *v, uint64_t gpa, int destreg, uint64_t *regp, int store);
945                                 do_ioapic(&vmctl, gpa, regx, regp, store);
946                         } else if (gpa < 4096) {
947                                 uint64_t val = 0;
948                                 memmove(&val, &low4k[gpa], size);
949                                 hexdump(stdout, &low4k[gpa], size);
950                                 fprintf(stderr, "Low 1m, code %p read @ %p, size %d, val %p\n", vmctl.regs.tf_rip, gpa, size, val);
951                                 memmove(regp, &low4k[gpa], size);
952                                 hexdump(stdout, regp, size);
953                         } else {
954                                 fprintf(stderr, "EPT violation: can't handle %p\n", gpa);
955                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
956                                 fprintf(stderr, "Returning 0xffffffff\n");
957                                 showstatus(stderr, &vmctl);
958                                 // Just fill the whole register for now.
959                                 *regp = (uint64_t) -1;
960                         }
961                         vmctl.regs.tf_rip += advance;
962                         if (debug) fprintf(stderr, "Advance rip by %d bytes to %p\n", advance, vmctl.regs.tf_rip);
963                         vmctl.shutdown = 0;
964                         vmctl.gpa = 0;
965                         vmctl.command = REG_ALL;
966                 } else if (vmctl.shutdown == SHUTDOWN_UNHANDLED_EXIT_REASON) {
967                         switch(vmctl.ret_code){
968                         case  EXIT_REASON_VMCALL:
969                                 byte = vmctl.regs.tf_rdi;
970                                 printf("%c", byte);
971                                 if (byte == '\n') printf("%c", '%');
972                                 vmctl.regs.tf_rip += 3;
973                                 break;
974                         case EXIT_REASON_EXTERNAL_INTERRUPT:
975                                 //debug = 1;
976                                 if (debug) fprintf(stderr, "XINT 0x%x 0x%x\n", vmctl.intrinfo1, vmctl.intrinfo2);
977                                 if (debug) pir_dump();
978                                 vmctl.command = RESUME;
979                                 break;
980                         case EXIT_REASON_IO_INSTRUCTION:
981                                 fprintf(stderr, "IO @ %p\n", vmctl.regs.tf_rip);
982                                 io(&vmctl);
983                                 vmctl.shutdown = 0;
984                                 vmctl.gpa = 0;
985                                 vmctl.command = REG_ALL;
986                                 break;
987                         case EXIT_REASON_INTERRUPT_WINDOW:
988                                 if (consdata) {
989                                         if (debug) fprintf(stderr, "inject an interrupt\n");
990                                         virtio_mmio_set_vring_irq();
991                                         vmctl.interrupt = 0x80000000 | virtioirq;
992                                         vmctl.command = RESUME;
993                                         consdata = 0;
994                                 }
995                                 break;
996                         case EXIT_REASON_MSR_WRITE:
997                         case EXIT_REASON_MSR_READ:
998                                 fprintf(stderr, "Do an msr\n");
999                                 if (msrio(&vmctl, vmctl.ret_code)) {
1000                                         // uh-oh, msrio failed
1001                                         // well, hand back a GP fault which is what Intel does
1002                                         fprintf(stderr, "MSR FAILED: RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1003                                         showstatus(stderr, &vmctl);
1004
1005                                         // Use event injection through vmctl to send
1006                                         // a general protection fault
1007                                         // vmctl.interrupt gets written to the VM-Entry
1008                                         // Interruption-Information Field by vmx
1009                                         vmctl.interrupt = (1 << 31) // "Valid" bit
1010                                                         | (0 << 12) // Reserved by Intel
1011                                                         | (1 << 11) // Deliver-error-code bit (set if event pushes error code to stack)
1012                                                         | (3 << 8)  // Event type (3 is "hardware exception")
1013                                                         | 13;       // Interrupt/exception vector (13 is "general protection fault")
1014                                         run_vmthread(&vmctl);
1015                                 } else {
1016                                         vmctl.regs.tf_rip += 2;
1017                                         run_vmthread(&vmctl);
1018                                 }
1019                                 break;
1020                         case EXIT_REASON_MWAIT_INSTRUCTION:
1021                           fflush(stdout);
1022                                 if (debug)fprintf(stderr, "\n================== Guest MWAIT. =======================\n");
1023                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1024                                 while (!consdata)
1025                                         ;
1026                                 //debug = 1;
1027                                 if (debug)
1028                                         vapic_status_dump(stderr, gpci.vapic_addr);
1029                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1030                                 vmctl.regs.tf_rip += 3;
1031                                 run_vmthread(&vmctl);
1032                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1033                                 //showstatus(stderr, &vmctl);
1034                                 break;
1035                         case EXIT_REASON_HLT:
1036                                 fflush(stdout);
1037                                 if (debug)fprintf(stderr, "\n================== Guest halted. =======================\n");
1038                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1039                                 while (!consdata)
1040                                         ;
1041                                 //debug = 1;
1042                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1043                                 vmctl.regs.tf_rip += 1;
1044                                 run_vmthread(&vmctl);
1045                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1046                                 //showstatus(stderr, &vmctl);
1047                                 break;
1048                         case EXIT_REASON_APIC_ACCESS:
1049                                 if (1 || debug)fprintf(stderr, "APIC READ EXIT\n");
1050
1051                                 uint64_t gpa, *regp, val;
1052                                 uint8_t regx;
1053                                 int store, size;
1054                                 int advance;
1055                                 if (decode(&vmctl, &gpa, &regx, &regp, &store, &size, &advance)) {
1056                                         fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1057                                         showstatus(stderr, &vmctl);
1058                                         quit = 1;
1059                                         break;
1060                                 }
1061
1062                                 int apic(struct vmctl *v, uint64_t gpa, int destreg, uint64_t *regp, int store);
1063                                 apic(&vmctl, gpa, regx, regp, store);
1064                                 vmctl.regs.tf_rip += advance;
1065                                 if (debug) fprintf(stderr, "Advance rip by %d bytes to %p\n", advance, vmctl.regs.tf_rip);
1066                                 vmctl.shutdown = 0;
1067                                 vmctl.gpa = 0;
1068                                 vmctl.command = REG_ALL;
1069                                 break;
1070                         case EXIT_REASON_APIC_WRITE:
1071                                 if (1 || debug)fprintf(stderr, "APIC WRITE EXIT\n");
1072                                 break;
1073                         default:
1074                                 fprintf(stderr, "Don't know how to handle exit %d\n", vmctl.ret_code);
1075                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1076                                 showstatus(stderr, &vmctl);
1077                                 quit = 1;
1078                                 break;
1079                         }
1080                 }
1081                 if (debug) fprintf(stderr, "at bottom of switch, quit is %d\n", quit);
1082                 if (quit)
1083                         break;
1084                 if (consdata) {
1085                         if (debug) fprintf(stderr, "inject an interrupt\n");
1086                         if (debug) fprintf(stderr, "XINT 0x%x 0x%x\n", vmctl.intrinfo1, vmctl.intrinfo2);
1087                         vmctl.interrupt = 0x80000000 | virtioirq;
1088                         virtio_mmio_set_vring_irq();
1089                         consdata = 0;
1090                         //debug = 1;
1091                         vmctl.command = RESUME;
1092                 }
1093                 if (debug) fprintf(stderr, "NOW DO A RESUME\n");
1094                 run_vmthread(&vmctl);
1095         }
1096
1097         /* later.
1098         for (int i = 0; i < nr_threads-1; i++) {
1099                 int ret;
1100                 if (pthread_join(my_threads[i], &my_retvals[i]))
1101                         perror("pth_join failed");
1102                 fprintf(stderr, "%d %d\n", i, ret);
1103         }
1104  */
1105
1106         fflush(stdout);
1107         exit(0);
1108 }