VMM: Remove the stack
[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 <vmm/acpi/vmm_simple_dsdt.h>
19 #include <ros/arch/mmu.h>
20 #include <ros/vmm.h>
21 #include <parlib/uthread.h>
22 #include <vmm/linux_bootparam.h>
23 #include <vmm/virtio.h>
24 #include <vmm/virtio_mmio.h>
25 #include <vmm/virtio_ids.h>
26 #include <vmm/virtio_config.h>
27 #include <vmm/sched.h>
28
29
30 struct virtual_machine local_vm, *vm = &local_vm;
31 struct vmm_gpcore_init gpci;
32
33 struct vmctl vmctl;
34
35 /* Whoever holds the ball runs.  run_vm never actually grabs it - it is grabbed
36  * on its behalf. */
37 uth_mutex_t the_ball;
38 pthread_t vm_thread;
39
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 = ACPI_SIG_RSDP,
204         .oem_id = "AKAROS",
205         .revision = 2,
206         .length = 36,
207 };
208
209 struct acpi_table_xsdt xsdt = {
210         .header = {
211                 .signature = ACPI_SIG_DSDT,
212                 .revision = 2,
213                 .oem_id = "AKAROS",
214                 .oem_table_id = "ALPHABET",
215                 .oem_revision = 0,
216                 .asl_compiler_id = "RON ",
217                 .asl_compiler_revision = 0,
218         },
219 };
220 struct acpi_table_fadt fadt = {
221         .header = {
222                 .signature = ACPI_SIG_FADT,
223                 .revision = 2,
224                 .oem_id = "AKAROS",
225                 .oem_table_id = "ALPHABET",
226                 .oem_revision = 0,
227                 .asl_compiler_id = "RON ",
228                 .asl_compiler_revision = 0,
229         },
230 };
231
232
233 /* This has to be dropped into memory, then the other crap just follows it.
234  */
235 struct acpi_table_madt madt = {
236         .header = {
237                 .signature = ACPI_SIG_MADT,
238                 .revision = 2,
239                 .oem_id = "AKAROS",
240                 .oem_table_id = "ALPHABET",
241                 .oem_revision = 0,
242                 .asl_compiler_id = "RON ",
243                 .asl_compiler_revision = 0,
244         },
245
246         .address = 0xfee00000ULL,
247 };
248
249 struct acpi_madt_local_apic Apic0 = {.header = {.type = ACPI_MADT_TYPE_LOCAL_APIC, .length = sizeof(struct acpi_madt_local_apic)},
250                                      .processor_id = 0, .id = 0};
251 struct acpi_madt_io_apic Apic1 = {.header = {.type = ACPI_MADT_TYPE_IO_APIC, .length = sizeof(struct acpi_madt_io_apic)},
252                                   .id = 1, .address = 0xfec00000, .global_irq_base = 0};
253 struct acpi_madt_local_x2apic X2Apic0 = {
254         .header = {
255                 .type = ACPI_MADT_TYPE_LOCAL_X2APIC,
256                 .length = sizeof(struct acpi_madt_local_x2apic)
257         },
258         .local_apic_id = 0,
259         .uid = 0
260 };
261
262 struct acpi_madt_interrupt_override isor[] = {
263         /* I have no idea if it should be source irq 2, global 0, or global 2, source 0. Shit. */
264         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
265          .bus = 0, .source_irq = 2, .global_irq = 0, .inti_flags = 0},
266         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
267          .bus = 0, .source_irq = 1, .global_irq = 1, .inti_flags = 0},
268         //{.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
269          //.bus = 0, .source_irq = 2, .global_irq = 2, .inti_flags = 0},
270         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
271          .bus = 0, .source_irq = 3, .global_irq = 3, .inti_flags = 0},
272         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
273          .bus = 0, .source_irq = 4, .global_irq = 4, .inti_flags = 0},
274         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
275          .bus = 0, .source_irq = 5, .global_irq = 5, .inti_flags = 0},
276         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
277          .bus = 0, .source_irq = 6, .global_irq = 6, .inti_flags = 0},
278         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
279          .bus = 0, .source_irq = 7, .global_irq = 7, .inti_flags = 0},
280         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
281          .bus = 0, .source_irq = 8, .global_irq = 8, .inti_flags = 0},
282         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
283          .bus = 0, .source_irq = 9, .global_irq = 9, .inti_flags = 0},
284         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
285          .bus = 0, .source_irq = 10, .global_irq = 10, .inti_flags = 0},
286         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
287          .bus = 0, .source_irq = 11, .global_irq = 11, .inti_flags = 0},
288         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
289          .bus = 0, .source_irq = 12, .global_irq = 12, .inti_flags = 0},
290         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
291          .bus = 0, .source_irq = 13, .global_irq = 13, .inti_flags = 0},
292         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
293          .bus = 0, .source_irq = 14, .global_irq = 14, .inti_flags = 0},
294         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
295          .bus = 0, .source_irq = 15, .global_irq = 15, .inti_flags = 0},
296         // VMMCP routes irq 32 to gsi 17
297         {.header = {.type = ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, .length = sizeof(struct acpi_madt_interrupt_override)},
298          .bus = 0, .source_irq = 32, .global_irq = 17, .inti_flags = 5},
299 };
300
301
302 /* this test will run the "kernel" in the negative address space. We hope. */
303 void *low1m;
304 volatile int shared = 0;
305 volatile int quit = 0;
306 int mcp = 1;
307
308 /* total hack. If the vm runs away we want to get control again. */
309 unsigned int maxresume = (unsigned int) -1;
310
311 #define MiB 0x100000u
312 #define GiB (1u<<30)
313 #define GKERNBASE (16*MiB)
314 #define KERNSIZE (128*MiB+GKERNBASE)
315 uint8_t _kernel[KERNSIZE];
316
317 unsigned long long *p512, *p1, *p2m;
318
319 void **my_retvals;
320 int nr_threads = 4;
321 int debug = 0;
322 int resumeprompt = 0;
323 /* unlike Linux, this shared struct is for both host and guest. */
324 //      struct virtqueue *constoguest =
325 //              vring_new_virtqueue(0, 512, 8192, 0, inpages, NULL, NULL, "test");
326
327 void vapic_status_dump(FILE *f, void *vapic);
328 static void set_posted_interrupt(int vector);
329
330 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
331 #error "Get a gcc newer than 4.4.0"
332 #else
333 #define BITOP_ADDR(x) "+m" (*(volatile long *) (x))
334 #endif
335
336 #define LOCK_PREFIX "lock "
337 #define ADDR                            BITOP_ADDR(addr)
338 static inline int test_and_set_bit(int nr, volatile unsigned long *addr);
339
340 pthread_t timerthread_struct;
341
342 void *timer_thread(void *arg)
343 {
344         uint8_t vector;
345         uint32_t initial_count;
346         while (1) {
347                 vector = ((uint32_t *)gpci.vapic_addr)[0x32] & 0xff;
348                 initial_count = ((uint32_t *)gpci.vapic_addr)[0x38];
349                 if (vector && initial_count) {
350                         set_posted_interrupt(vector);
351                         ros_syscall(SYS_vmm_poke_guest, 0, 0, 0, 0, 0, 0);
352                 }
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=1000000"
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         // lowmem is a bump allocated pointer to 2M at the "physbase" of memory
576         void *lowmem = (void *) 0x1000000;
577         //struct vmctl vmctl;
578         int amt;
579         int vmmflags = 0; // Disabled probably forever. VMM_VMCALL_PRINTF;
580         uint64_t entry = 0x1200000, kerneladdress = 0x1200000;
581         int nr_gpcs = 1;
582         int ret;
583         void * xp;
584         int kfd = -1;
585         static char cmd[512];
586         int i;
587         uint8_t csum;
588         void *coreboot_tables = (void *) 0x1165000;
589         void *a_page;
590         struct vm_trapframe *vm_tf;
591         uint64_t tsc_freq_khz;
592
593         the_ball = uth_mutex_alloc();
594         uth_mutex_lock(the_ball);
595
596         fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
597                         PML1_PTE_REACH);
598
599
600         // mmap is not working for us at present.
601         if ((uint64_t)_kernel > GKERNBASE) {
602                 fprintf(stderr, "kernel array @%p is above , GKERNBASE@%p sucks\n", _kernel, GKERNBASE);
603                 exit(1);
604         }
605         memset(_kernel, 0, sizeof(_kernel));
606         memset(lowmem, 0xff, 2*1048576);
607         vm->low4k = malloc(PGSIZE);
608         memset(vm->low4k, 0xff, PGSIZE);
609         // avoid at all costs, requires too much instruction emulation.
610         //low4k[0x40e] = 0;
611         //low4k[0x40f] = 0xe0;
612
613         //Place mmap(Gan)
614         a_page = mmap((void *)0xfee00000, PGSIZE, PROT_READ | PROT_WRITE,
615                               MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
616         fprintf(stderr, "a_page mmap pointer %p\n", a_page);
617
618         if (a_page == (void *) -1) {
619                 perror("Could not mmap APIC");
620                 exit(1);
621         }
622         if (((uint64_t)a_page & 0xfff) != 0) {
623                 perror("APIC page mapping is not page aligned");
624                 exit(1);
625         }
626
627         memset(a_page, 0, 4096);
628         ((uint32_t *)a_page)[0x30/4] = 0x01060015;
629         //((uint32_t *)a_page)[0x30/4] = 0xDEADBEEF;
630
631         vm->virtio_irq = 17; /* TODO: is this an option?  or a #define? */
632
633         argc--, argv++;
634         // switches ...
635         // Sorry, I don't much like the gnu opt parsing code.
636         while (1) {
637                 if (*argv[0] != '-')
638                         break;
639                 switch(argv[0][1]) {
640                 case 'd':
641                         debug++;
642                         break;
643                 case 'v':
644                         vmmflags |= VMM_VMCALL_PRINTF;
645                         break;
646                 case 'm':
647                         argc--, argv++;
648                         maxresume = strtoull(argv[0], 0, 0);
649                         break;
650                 case 'i':
651                         argc--, argv++;
652                         vm->virtio_irq = strtoull(argv[0], 0, 0);
653                         break;
654                 case 'c':
655                         argc--, argv++;
656                         cmdline_extra = argv[0];
657                 default:
658                         fprintf(stderr, "BMAFR\n");
659                         break;
660                 }
661                 argc--, argv++;
662         }
663         if (argc < 1) {
664                 fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)] [coreboot_tables [loadaddress [entrypoint]]]\n", argv[0]);
665                 exit(1);
666         }
667         if (argc > 1)
668                 coreboot_tables = (void *) strtoull(argv[1], 0, 0);
669         if (argc > 2)
670                 kerneladdress = strtoull(argv[2], 0, 0);
671         if (argc > 3)
672                 entry = strtoull(argv[3], 0, 0);
673         kfd = open(argv[0], O_RDONLY);
674         if (kfd < 0) {
675                 perror(argv[0]);
676                 exit(1);
677         }
678         // read in the kernel.
679         xp = (void *)kerneladdress;
680         for(;;) {
681                 amt = read(kfd, xp, 1048576);
682                 if (amt < 0) {
683                         perror("read");
684                         exit(1);
685                 }
686                 if (amt == 0) {
687                         break;
688                 }
689                 xp += amt;
690         }
691         fprintf(stderr, "Read in %d bytes\n", xp-kerneladdress);
692         close(kfd);
693
694         // The low 1m so we can fill in bullshit like ACPI. */
695         // And, sorry, due to the STUPID format of the RSDP for now we need the low 1M.
696         low1m = mmap((int*)4096, MiB-4096, PROT_READ | PROT_WRITE,
697                          MAP_ANONYMOUS, -1, 0);
698         if (low1m != (void *)4096) {
699                 perror("Unable to mmap low 1m");
700                 exit(1);
701         }
702         memset(low1m, 0xff, MiB-4096);
703         r = a;
704         fprintf(stderr, "install rsdp to %p\n", r);
705         *r = rsdp;
706         a += sizeof(*r);
707         r->xsdt_physical_address = (uint64_t)a;
708         gencsum(&r->checksum, r, ACPI_RSDP_CHECKSUM_LENGTH);
709         if ((csum = acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_CHECKSUM_LENGTH)) != 0) {
710                 fprintf(stderr, "RSDP has bad checksum; summed to %x\n", csum);
711                 exit(1);
712         }
713
714         /* Check extended checksum if table version >= 2 */
715         gencsum(&r->extended_checksum, r, ACPI_RSDP_XCHECKSUM_LENGTH);
716         if ((rsdp.revision >= 2) &&
717             (acpi_tb_checksum((uint8_t *) r, ACPI_RSDP_XCHECKSUM_LENGTH) != 0)) {
718                 fprintf(stderr, "RSDP has bad checksum v2\n");
719                 exit(1);
720         }
721
722         /* just leave a bunch of space for the xsdt. */
723         /* we need to zero the area since it has pointers. */
724         x = a;
725         a += sizeof(*x) + 8*sizeof(void *);
726         memset(x, 0, a - (void *)x);
727         fprintf(stderr, "install xsdt to %p\n", x);
728         *x = xsdt;
729         x->table_offset_entry[0] = 0;
730         x->table_offset_entry[1] = 0;
731         x->header.length = a - (void *)x;
732
733         f = a;
734         fprintf(stderr, "install fadt to %p\n", f);
735         *f = fadt;
736         x->table_offset_entry[0] = (uint64_t)f; // fadt MUST be first in xsdt!
737         a += sizeof(*f);
738         f->header.length = a - (void *)f;
739
740         f->Xdsdt = (uint64_t) a;
741         fprintf(stderr, "install dsdt to %p\n", a);
742         memcpy(a, &DSDT_DSDTTBL_Header, 36);
743         a += 36;
744
745         gencsum(&f->header.checksum, f, f->header.length);
746         if (acpi_tb_checksum((uint8_t *)f, f->header.length) != 0) {
747                 fprintf(stderr, "fadt has bad checksum v2\n");
748                 exit(1);
749         }
750
751         m = a;
752         *m = madt;
753         x->table_offset_entry[3] = (uint64_t) m;
754         a += sizeof(*m);
755         fprintf(stderr, "install madt to %p\n", m);
756         memmove(a, &Apic0, sizeof(Apic0));
757         a += sizeof(Apic0);
758         memmove(a, &Apic1, sizeof(Apic1));
759         a += sizeof(Apic1);
760         memmove(a, &X2Apic0, sizeof(X2Apic0));
761         a += sizeof(X2Apic0);
762         memmove(a, &isor, sizeof(isor));
763         a += sizeof(isor);
764         m->header.length = a - (void *)m;
765
766         gencsum(&m->header.checksum, m, m->header.length);
767         if (acpi_tb_checksum((uint8_t *) m, m->header.length) != 0) {
768                 fprintf(stderr, "madt has bad checksum v2\n");
769                 exit(1);
770         }
771
772         gencsum(&x->header.checksum, x, x->header.length);
773         if ((csum = acpi_tb_checksum((uint8_t *) x, x->header.length)) != 0) {
774                 fprintf(stderr, "XSDT has bad checksum; summed to %x\n", csum);
775                 exit(1);
776         }
777
778
779
780         fprintf(stderr, "allchecksums ok\n");
781
782         hexdump(stdout, r, a-(void *)r);
783
784         a = (void *)(((unsigned long)a + 0xfff) & ~0xfff);
785         gpci.posted_irq_desc = a;
786         memset(a, 0, 4096);
787         a += 4096;
788         gpci.vapic_addr = a;
789         //vmctl.vapic = (uint64_t) a_page;
790         memset(a, 0, 4096);
791         ((uint32_t *)a)[0x30/4] = 0x01060014;
792         p64 = a;
793         // set up apic values? do we need to?
794         // qemu does this.
795         //((uint8_t *)a)[4] = 1;
796         a += 4096;
797         gpci.apic_addr = (void*)0xfee00000;
798
799         /* Allocate memory for, and zero the bootparams
800          * page before writing to it, or Linux thinks
801          * we're talking crazy.
802          */
803         a += 4096;
804         bp = a;
805         memset(bp, 0, 4096);
806
807         /* Set the kernel command line parameters */
808         a += 4096;
809         cmdline = a;
810         a += 4096;
811         bp->hdr.cmd_line_ptr = (uintptr_t) cmdline;
812         tsc_freq_khz = get_tsc_freq()/1000;
813         sprintf(cmdline, "%s tscfreq=%lld %s", cmdline_default, tsc_freq_khz,
814                 cmdline_extra);
815
816
817         /* Put the e820 memory region information in the boot_params */
818         bp->e820_entries = 3;
819         int e820i = 0;
820
821         bp->e820_map[e820i].addr = 0;
822         bp->e820_map[e820i].size = 16 * 1048576;
823         bp->e820_map[e820i++].type = E820_RESERVED;
824
825         bp->e820_map[e820i].addr = 16 * 1048576;
826         bp->e820_map[e820i].size = 128 * 1048576;
827         bp->e820_map[e820i++].type = E820_RAM;
828
829         bp->e820_map[e820i].addr = 0xf0000000;
830         bp->e820_map[e820i].size = 0x10000000;
831         bp->e820_map[e820i++].type = E820_RESERVED;
832
833         if (ros_syscall(SYS_vmm_setup, nr_gpcs, &gpci, vmmflags, 0, 0, 0) !=
834             nr_gpcs) {
835                 perror("Guest pcore setup failed");
836                 exit(1);
837         }
838
839         fprintf(stderr, "Run with %d cores and vmmflags 0x%x\n", nr_gpcs, vmmflags);
840         mcp = 1;
841         if (mcp) {
842                 my_retvals = malloc(sizeof(void*) * nr_threads);
843                 if (!my_retvals)
844                         perror("Init threads/malloc");
845
846                 pthread_can_vcore_request(FALSE);       /* 2LS won't manage vcores */
847                 pthread_need_tls(FALSE);
848                 pthread_mcp_init();                                     /* gives us one vcore */
849                 vcore_request_total(nr_threads);
850                 for (int i = 0; i < nr_threads; i++) {
851                         xp = __procinfo.vcoremap;
852                         fprintf(stderr, "%p\n", __procinfo.vcoremap);
853                         fprintf(stderr, "Vcore %d mapped to pcore %d\n", i,
854                                 __procinfo.vcoremap[i].pcoreid);
855                 }
856         }
857
858         ret = syscall(33, 1);
859         if (ret < 0) {
860                 perror("vm setup");
861                 exit(1);
862         }
863         ret = posix_memalign((void **)&p512, 4096, 3*4096);
864         fprintf(stderr, "memalign is %p\n", p512);
865         if (ret) {
866                 perror("ptp alloc");
867                 exit(1);
868         }
869         p1 = &p512[512];
870         p2m = &p512[1024];
871         uint64_t kernbase = 0; //0xffffffff80000000;
872         uint64_t highkernbase = 0xffffffff80000000;
873         p512[PML4(kernbase)] = (unsigned long long)p1 | 7;
874         p1[PML3(kernbase)] = /*0x87; */(unsigned long long)p2m | 7;
875         p512[PML4(highkernbase)] = (unsigned long long)p1 | 7;
876         p1[PML3(highkernbase)] = /*0x87; */(unsigned long long)p2m | 7;
877 #define _2MiB (0x200000)
878
879         for (i = 0; i < 512; i++) {
880                 p2m[PML2(kernbase + i * _2MiB)] = 0x87 | i * _2MiB;
881         }
882
883         kernbase >>= (0+12);
884         kernbase <<= (0 + 12);
885         uint8_t *kernel = (void *)GKERNBASE;
886         //write_coreboot_table(coreboot_tables, ((void *)VIRTIOBASE) /*kernel*/, KERNSIZE + 1048576);
887         hexdump(stdout, coreboot_tables, 512);
888         fprintf(stderr, "kernbase for pml4 is 0x%llx and entry is %llx\n", kernbase, entry);
889         fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);
890
891
892         vm->virtio_mmio_base = 0x100000000;
893
894
895         vmctl.interrupt = 0;
896         vmctl.command = REG_RSP_RIP_CR3;
897         vmctl.cr3 = (uint64_t) p512;
898         vmctl.regs.tf_rip = entry;
899         vmctl.regs.tf_rsp = 0;
900         vmctl.regs.tf_rsi = (uint64_t) bp;
901         if (mcp) {
902                 /* set up virtio bits, which depend on threads being enabled. */
903                 register_virtio_mmio(&vqdev, vm->virtio_mmio_base);
904         }
905         fprintf(stderr, "threads started\n");
906         fprintf(stderr, "Writing command :%s:\n", cmd);
907
908         if (debug)
909                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
910
911         run_vmthread(&vmctl);
912
913         if (debug)
914                 vapic_status_dump(stderr, (void *)gpci.vapic_addr);
915
916         if (mcp) {
917                 /* Start up timer thread */
918                 if (pthread_create(&timerthread_struct, NULL, timer_thread, NULL)) {
919                         fprintf(stderr, "pth_create failed for timer thread.");
920                         perror("pth_create");
921                 }
922         }
923
924         vm_tf = &(vm_thread->uthread.u_ctx.tf.vm_tf);
925
926         while (1) {
927
928                 int c;
929                 uint8_t byte;
930                 //vmctl.command = REG_RIP;
931                 if (maxresume-- == 0) {
932                         debug = 1;
933                         resumeprompt = 1;
934                 }
935                 if (debug) {
936                         fprintf(stderr, "RIP %p, exit reason 0x%x\n", vm_tf->tf_rip,
937                                 vm_tf->tf_exit_reason);
938                         showstatus(stderr, (struct guest_thread*)&vm_thread);
939                 }
940                 if (resumeprompt) {
941                         fprintf(stderr, "RESUME?\n");
942                         c = getchar();
943                         if (c == 'q')
944                                 break;
945                 }
946                 if (vm_tf->tf_exit_reason == EXIT_REASON_EPT_VIOLATION) {
947                         uint64_t gpa, *regp, val;
948                         uint8_t regx;
949                         int store, size;
950                         int advance;
951                         if (decode((struct guest_thread *) vm_thread, &gpa, &regx, &regp,
952                                    &store, &size, &advance)) {
953                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
954                                         vm_tf->tf_exit_reason);
955                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
956                                 quit = 1;
957                                 break;
958                         }
959                         if (debug) fprintf(stderr, "%p %p %p %p %p %p\n", gpa, regx, regp, store, size, advance);
960                         if (PG_ADDR(gpa) == vm->virtio_mmio_base) {
961                                 if (debug) fprintf(stderr, "DO SOME VIRTIO\n");
962                                 // Lucky for us the various virtio ops are well-defined.
963                                 virtio_mmio((struct guest_thread *)vm_thread, gpa, regx, regp,
964                                             store);
965                                 if (debug) fprintf(stderr, "store is %d:\n", store);
966                                 if (debug) fprintf(stderr, "REGP IS %16x:\n", *regp);
967                         } else if (PG_ADDR(gpa) == 0xfee00000) {
968                                 // until we fix our include mess, just put the proto here.
969                                 //int apic(struct vmctl *v, uint64_t gpa, int destreg, uint64_t *regp, int store);
970                                 //apic(&vmctl, gpa, regx, regp, store);
971                         } else if (PG_ADDR(gpa) == 0xfec00000) {
972                                 // until we fix our include mess, just put the proto here.
973                                 do_ioapic((struct guest_thread *)vm_thread, gpa, regx, regp,
974                                           store);
975                         } else if (PG_ADDR(gpa) == 0) {
976                                 uint64_t val = 0;
977                                 memmove(&val, &vm->low4k[gpa], size);
978                                 hexdump(stdout, &vm->low4k[gpa], size);
979                                 fprintf(stderr, "Low 4k, code %p read @ %p, size %d, val %p\n",
980                                         vm_tf->tf_rip, gpa, size, val);
981                                 memmove(regp, &vm->low4k[gpa], size);
982                                 hexdump(stdout, regp, size);
983                         } else {
984                                 fprintf(stderr, "EPT violation: can't handle %p\n", gpa);
985                                 fprintf(stderr, "RIP %p, exit reason 0x%x\n", vm_tf->tf_rip,
986                                         vm_tf->tf_exit_reason);
987                                 fprintf(stderr, "Returning 0xffffffff\n");
988                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
989                                 // Just fill the whole register for now.
990                                 *regp = (uint64_t) -1;
991                         }
992                         vm_tf->tf_rip += advance;
993                         if (debug)
994                                 fprintf(stderr, "Advance rip by %d bytes to %p\n",
995                                         advance, vm_tf->tf_rip);
996                         //vmctl.shutdown = 0;
997                         //vmctl.gpa = 0;
998                         //vmctl.command = REG_ALL;
999                 } else {
1000                         switch (vm_tf->tf_exit_reason) {
1001                         case  EXIT_REASON_VMCALL:
1002                                 byte = vm_tf->tf_rdi;
1003                                 printf("%c", byte);
1004                                 if (byte == '\n') printf("%c", '%');
1005                                 vm_tf->tf_rip += 3;
1006                                 break;
1007                         case EXIT_REASON_EXTERNAL_INTERRUPT:
1008                                 //debug = 1;
1009                                 if (debug)
1010                                         fprintf(stderr, "XINT 0x%x 0x%x\n",
1011                                                 vm_tf->tf_intrinfo1, vm_tf->tf_intrinfo2);
1012                                 if (debug) pir_dump();
1013                                 //vmctl.command = RESUME;
1014                                 break;
1015                         case EXIT_REASON_IO_INSTRUCTION:
1016                                 fprintf(stderr, "IO @ %p\n", vm_tf->tf_rip);
1017                                 io((struct guest_thread *)vm_thread);
1018                                 //vmctl.shutdown = 0;
1019                                 //vmctl.gpa = 0;
1020                                 //vmctl.command = REG_ALL;
1021                                 break;
1022                         case EXIT_REASON_INTERRUPT_WINDOW:
1023                                 if (consdata) {
1024                                         if (debug) fprintf(stderr, "inject an interrupt\n");
1025                                         virtio_mmio_set_vring_irq();
1026                                         vm_tf->tf_trap_inject = 0x80000000 | vm->virtio_irq;
1027                                         //vmctl.command = RESUME;
1028                                         consdata = 0;
1029                                 }
1030                                 break;
1031                         case EXIT_REASON_MSR_WRITE:
1032                         case EXIT_REASON_MSR_READ:
1033                                 fprintf(stderr, "Do an msr\n");
1034                                 if (msrio((struct guest_thread *)vm_thread, &gpci,
1035                                           vm_tf->tf_exit_reason)) {
1036                                         // uh-oh, msrio failed
1037                                         // well, hand back a GP fault which is what Intel does
1038                                         fprintf(stderr, "MSR FAILED: RIP %p, shutdown 0x%x\n",
1039                                                 vm_tf->tf_rip, vm_tf->tf_exit_reason);
1040                                         showstatus(stderr, (struct guest_thread*)&vm_thread);
1041
1042                                         // Use event injection through vmctl to send
1043                                         // a general protection fault
1044                                         // vmctl.interrupt gets written to the VM-Entry
1045                                         // Interruption-Information Field by vmx
1046                                         vm_tf->tf_trap_inject = VM_TRAP_VALID
1047                                                               | VM_TRAP_ERROR_CODE
1048                                                               | VM_TRAP_HARDWARE
1049                                                               | 13; // GPF
1050                                 } else {
1051                                         vm_tf->tf_rip += 2;
1052                                 }
1053                                 break;
1054                         case EXIT_REASON_MWAIT_INSTRUCTION:
1055                           fflush(stdout);
1056                                 if (debug)fprintf(stderr, "\n================== Guest MWAIT. =======================\n");
1057                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1058                                 while (!consdata)
1059                                         ;
1060                                 //debug = 1;
1061                                 if (debug)
1062                                         vapic_status_dump(stderr, gpci.vapic_addr);
1063                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1064                                 vm_tf->tf_rip += 3;
1065                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1066                                 //showstatus(stderr, (struct guest_thread*)&vm_thread);
1067                                 break;
1068                         case EXIT_REASON_HLT:
1069                                 fflush(stdout);
1070                                 if (debug)fprintf(stderr, "\n================== Guest halted. =======================\n");
1071                                 if (debug)fprintf(stderr, "Wait for cons data\n");
1072                                 while (!consdata)
1073                                         ;
1074                                 //debug = 1;
1075                                 if (debug)fprintf(stderr, "Resume with consdata ...\n");
1076                                 vm_tf->tf_rip += 1;
1077                                 //fprintf(stderr, "RIP %p, shutdown 0x%x\n", vmctl.regs.tf_rip, vmctl.shutdown);
1078                                 //showstatus(stderr, (struct guest_thread*)&vm_thread);
1079                                 break;
1080                         case EXIT_REASON_APIC_ACCESS:
1081                                 if (1 || debug)fprintf(stderr, "APIC READ EXIT\n");
1082
1083                                 uint64_t gpa, *regp, val;
1084                                 uint8_t regx;
1085                                 int store, size;
1086                                 int advance;
1087                                 if (decode((struct guest_thread *)vm_thread, &gpa, &regx,
1088                                            &regp, &store, &size, &advance)) {
1089                                         fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
1090                                                 vm_tf->tf_exit_reason);
1091                                         showstatus(stderr, (struct guest_thread*)&vm_thread);
1092                                         quit = 1;
1093                                         break;
1094                                 }
1095
1096                                 int apic(struct guest_thread *vm_thread, uint64_t gpa,
1097                                          int destreg, uint64_t *regp, int store);
1098                                 apic((struct guest_thread *)vm_thread, gpa, regx, regp, store);
1099                                 vm_tf->tf_rip += advance;
1100                                 if (debug)
1101                                         fprintf(stderr, "Advance rip by %d bytes to %p\n",
1102                                                 advance, vm_tf->tf_rip);
1103                                 //vmctl.shutdown = 0;
1104                                 //vmctl.gpa = 0;
1105                                 //vmctl.command = REG_ALL;
1106                                 break;
1107                         case EXIT_REASON_APIC_WRITE:
1108                                 if (1 || debug)fprintf(stderr, "APIC WRITE EXIT\n");
1109                                 break;
1110                         default:
1111                                 fprintf(stderr, "Don't know how to handle exit %d\n",
1112                                         vm_tf->tf_exit_reason);
1113                                 fprintf(stderr, "RIP %p, shutdown 0x%x\n", vm_tf->tf_rip,
1114                                         vm_tf->tf_exit_reason);
1115                                 showstatus(stderr, (struct guest_thread*)&vm_thread);
1116                                 quit = 1;
1117                                 break;
1118                         }
1119                 }
1120                 if (debug) fprintf(stderr, "at bottom of switch, quit is %d\n", quit);
1121                 if (quit)
1122                         break;
1123                 if (consdata) {
1124                         if (debug) fprintf(stderr, "inject an interrupt\n");
1125                         if (debug)
1126                                 fprintf(stderr, "XINT 0x%x 0x%x\n", vm_tf->tf_intrinfo1,
1127                                         vm_tf->tf_intrinfo2);
1128                         vm_tf->tf_trap_inject = 0x80000000 | vm->virtio_irq;
1129                         virtio_mmio_set_vring_irq();
1130                         consdata = 0;
1131                         //debug = 1;
1132                         //vmctl.command = RESUME;
1133                 }
1134                 if (debug) fprintf(stderr, "NOW DO A RESUME\n");
1135                 copy_vmtf_to_vmctl(vm_tf, &vmctl);
1136                 run_vmthread(&vmctl);
1137                 copy_vmctl_to_vmtf(&vmctl, vm_tf);
1138         }
1139
1140         /* later.
1141         for (int i = 0; i < nr_threads-1; i++) {
1142                 int ret;
1143                 if (pthread_join(my_threads[i], &my_retvals[i]))
1144                         perror("pth_join failed");
1145                 fprintf(stderr, "%d %d\n", i, ret);
1146         }
1147  */
1148
1149         fflush(stdout);
1150         exit(0);
1151 }