xref: /openbmc/qemu/hw/i386/kvmvapic.c (revision 8e6fe6b8)
1 /*
2  * TPR optimization for 32-bit Windows guests (XP and Server 2003)
3  *
4  * Copyright (C) 2007-2008 Qumranet Technologies
5  * Copyright (C) 2012      Jan Kiszka, Siemens AG
6  *
7  * This work is licensed under the terms of the GNU GPL version 2, or
8  * (at your option) any later version. See the COPYING file in the
9  * top-level directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qemu/module.h"
14 #include "cpu.h"
15 #include "sysemu/sysemu.h"
16 #include "sysemu/cpus.h"
17 #include "sysemu/hw_accel.h"
18 #include "sysemu/kvm.h"
19 #include "hw/i386/apic_internal.h"
20 #include "hw/sysbus.h"
21 #include "tcg/tcg.h"
22 
23 #define VAPIC_IO_PORT           0x7e
24 
25 #define VAPIC_CPU_SHIFT         7
26 
27 #define ROM_BLOCK_SIZE          512
28 #define ROM_BLOCK_MASK          (~(ROM_BLOCK_SIZE - 1))
29 
30 typedef enum VAPICMode {
31     VAPIC_INACTIVE = 0,
32     VAPIC_ACTIVE   = 1,
33     VAPIC_STANDBY  = 2,
34 } VAPICMode;
35 
36 typedef struct VAPICHandlers {
37     uint32_t set_tpr;
38     uint32_t set_tpr_eax;
39     uint32_t get_tpr[8];
40     uint32_t get_tpr_stack;
41 } QEMU_PACKED VAPICHandlers;
42 
43 typedef struct GuestROMState {
44     char signature[8];
45     uint32_t vaddr;
46     uint32_t fixup_start;
47     uint32_t fixup_end;
48     uint32_t vapic_vaddr;
49     uint32_t vapic_size;
50     uint32_t vcpu_shift;
51     uint32_t real_tpr_addr;
52     VAPICHandlers up;
53     VAPICHandlers mp;
54 } QEMU_PACKED GuestROMState;
55 
56 typedef struct VAPICROMState {
57     SysBusDevice busdev;
58     MemoryRegion io;
59     MemoryRegion rom;
60     uint32_t state;
61     uint32_t rom_state_paddr;
62     uint32_t rom_state_vaddr;
63     uint32_t vapic_paddr;
64     uint32_t real_tpr_addr;
65     GuestROMState rom_state;
66     size_t rom_size;
67     bool rom_mapped_writable;
68     VMChangeStateEntry *vmsentry;
69 } VAPICROMState;
70 
71 #define TYPE_VAPIC "kvmvapic"
72 #define VAPIC(obj) OBJECT_CHECK(VAPICROMState, (obj), TYPE_VAPIC)
73 
74 #define TPR_INSTR_ABS_MODRM             0x1
75 #define TPR_INSTR_MATCH_MODRM_REG       0x2
76 
77 typedef struct TPRInstruction {
78     uint8_t opcode;
79     uint8_t modrm_reg;
80     unsigned int flags;
81     TPRAccess access;
82     size_t length;
83     off_t addr_offset;
84 } TPRInstruction;
85 
86 /* must be sorted by length, shortest first */
87 static const TPRInstruction tpr_instr[] = {
88     { /* mov abs to eax */
89         .opcode = 0xa1,
90         .access = TPR_ACCESS_READ,
91         .length = 5,
92         .addr_offset = 1,
93     },
94     { /* mov eax to abs */
95         .opcode = 0xa3,
96         .access = TPR_ACCESS_WRITE,
97         .length = 5,
98         .addr_offset = 1,
99     },
100     { /* mov r32 to r/m32 */
101         .opcode = 0x89,
102         .flags = TPR_INSTR_ABS_MODRM,
103         .access = TPR_ACCESS_WRITE,
104         .length = 6,
105         .addr_offset = 2,
106     },
107     { /* mov r/m32 to r32 */
108         .opcode = 0x8b,
109         .flags = TPR_INSTR_ABS_MODRM,
110         .access = TPR_ACCESS_READ,
111         .length = 6,
112         .addr_offset = 2,
113     },
114     { /* push r/m32 */
115         .opcode = 0xff,
116         .modrm_reg = 6,
117         .flags = TPR_INSTR_ABS_MODRM | TPR_INSTR_MATCH_MODRM_REG,
118         .access = TPR_ACCESS_READ,
119         .length = 6,
120         .addr_offset = 2,
121     },
122     { /* mov imm32, r/m32 (c7/0) */
123         .opcode = 0xc7,
124         .modrm_reg = 0,
125         .flags = TPR_INSTR_ABS_MODRM | TPR_INSTR_MATCH_MODRM_REG,
126         .access = TPR_ACCESS_WRITE,
127         .length = 10,
128         .addr_offset = 2,
129     },
130 };
131 
132 static void read_guest_rom_state(VAPICROMState *s)
133 {
134     cpu_physical_memory_read(s->rom_state_paddr, &s->rom_state,
135                              sizeof(GuestROMState));
136 }
137 
138 static void write_guest_rom_state(VAPICROMState *s)
139 {
140     cpu_physical_memory_write(s->rom_state_paddr, &s->rom_state,
141                               sizeof(GuestROMState));
142 }
143 
144 static void update_guest_rom_state(VAPICROMState *s)
145 {
146     read_guest_rom_state(s);
147 
148     s->rom_state.real_tpr_addr = cpu_to_le32(s->real_tpr_addr);
149     s->rom_state.vcpu_shift = cpu_to_le32(VAPIC_CPU_SHIFT);
150 
151     write_guest_rom_state(s);
152 }
153 
154 static int find_real_tpr_addr(VAPICROMState *s, CPUX86State *env)
155 {
156     CPUState *cs = env_cpu(env);
157     hwaddr paddr;
158     target_ulong addr;
159 
160     if (s->state == VAPIC_ACTIVE) {
161         return 0;
162     }
163     /*
164      * If there is no prior TPR access instruction we could analyze (which is
165      * the case after resume from hibernation), we need to scan the possible
166      * virtual address space for the APIC mapping.
167      */
168     for (addr = 0xfffff000; addr >= 0x80000000; addr -= TARGET_PAGE_SIZE) {
169         paddr = cpu_get_phys_page_debug(cs, addr);
170         if (paddr != APIC_DEFAULT_ADDRESS) {
171             continue;
172         }
173         s->real_tpr_addr = addr + 0x80;
174         update_guest_rom_state(s);
175         return 0;
176     }
177     return -1;
178 }
179 
180 static uint8_t modrm_reg(uint8_t modrm)
181 {
182     return (modrm >> 3) & 7;
183 }
184 
185 static bool is_abs_modrm(uint8_t modrm)
186 {
187     return (modrm & 0xc7) == 0x05;
188 }
189 
190 static bool opcode_matches(uint8_t *opcode, const TPRInstruction *instr)
191 {
192     return opcode[0] == instr->opcode &&
193         (!(instr->flags & TPR_INSTR_ABS_MODRM) || is_abs_modrm(opcode[1])) &&
194         (!(instr->flags & TPR_INSTR_MATCH_MODRM_REG) ||
195          modrm_reg(opcode[1]) == instr->modrm_reg);
196 }
197 
198 static int evaluate_tpr_instruction(VAPICROMState *s, X86CPU *cpu,
199                                     target_ulong *pip, TPRAccess access)
200 {
201     CPUState *cs = CPU(cpu);
202     const TPRInstruction *instr;
203     target_ulong ip = *pip;
204     uint8_t opcode[2];
205     uint32_t real_tpr_addr;
206     int i;
207 
208     if ((ip & 0xf0000000ULL) != 0x80000000ULL &&
209         (ip & 0xf0000000ULL) != 0xe0000000ULL) {
210         return -1;
211     }
212 
213     /*
214      * Early Windows 2003 SMP initialization contains a
215      *
216      *   mov imm32, r/m32
217      *
218      * instruction that is patched by TPR optimization. The problem is that
219      * RSP, used by the patched instruction, is zero, so the guest gets a
220      * double fault and dies.
221      */
222     if (cpu->env.regs[R_ESP] == 0) {
223         return -1;
224     }
225 
226     if (kvm_enabled() && !kvm_irqchip_in_kernel()) {
227         /*
228          * KVM without kernel-based TPR access reporting will pass an IP that
229          * points after the accessing instruction. So we need to look backward
230          * to find the reason.
231          */
232         for (i = 0; i < ARRAY_SIZE(tpr_instr); i++) {
233             instr = &tpr_instr[i];
234             if (instr->access != access) {
235                 continue;
236             }
237             if (cpu_memory_rw_debug(cs, ip - instr->length, opcode,
238                                     sizeof(opcode), 0) < 0) {
239                 return -1;
240             }
241             if (opcode_matches(opcode, instr)) {
242                 ip -= instr->length;
243                 goto instruction_ok;
244             }
245         }
246         return -1;
247     } else {
248         if (cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0) < 0) {
249             return -1;
250         }
251         for (i = 0; i < ARRAY_SIZE(tpr_instr); i++) {
252             instr = &tpr_instr[i];
253             if (opcode_matches(opcode, instr)) {
254                 goto instruction_ok;
255             }
256         }
257         return -1;
258     }
259 
260 instruction_ok:
261     /*
262      * Grab the virtual TPR address from the instruction
263      * and update the cached values.
264      */
265     if (cpu_memory_rw_debug(cs, ip + instr->addr_offset,
266                             (void *)&real_tpr_addr,
267                             sizeof(real_tpr_addr), 0) < 0) {
268         return -1;
269     }
270     real_tpr_addr = le32_to_cpu(real_tpr_addr);
271     if ((real_tpr_addr & 0xfff) != 0x80) {
272         return -1;
273     }
274     s->real_tpr_addr = real_tpr_addr;
275     update_guest_rom_state(s);
276 
277     *pip = ip;
278     return 0;
279 }
280 
281 static int update_rom_mapping(VAPICROMState *s, CPUX86State *env, target_ulong ip)
282 {
283     CPUState *cs = env_cpu(env);
284     hwaddr paddr;
285     uint32_t rom_state_vaddr;
286     uint32_t pos, patch, offset;
287 
288     /* nothing to do if already activated */
289     if (s->state == VAPIC_ACTIVE) {
290         return 0;
291     }
292 
293     /* bail out if ROM init code was not executed (missing ROM?) */
294     if (s->state == VAPIC_INACTIVE) {
295         return -1;
296     }
297 
298     /* find out virtual address of the ROM */
299     rom_state_vaddr = s->rom_state_paddr + (ip & 0xf0000000);
300     paddr = cpu_get_phys_page_debug(cs, rom_state_vaddr);
301     if (paddr == -1) {
302         return -1;
303     }
304     paddr += rom_state_vaddr & ~TARGET_PAGE_MASK;
305     if (paddr != s->rom_state_paddr) {
306         return -1;
307     }
308     read_guest_rom_state(s);
309     if (memcmp(s->rom_state.signature, "kvm aPiC", 8) != 0) {
310         return -1;
311     }
312     s->rom_state_vaddr = rom_state_vaddr;
313 
314     /* fixup addresses in ROM if needed */
315     if (rom_state_vaddr == le32_to_cpu(s->rom_state.vaddr)) {
316         return 0;
317     }
318     for (pos = le32_to_cpu(s->rom_state.fixup_start);
319          pos < le32_to_cpu(s->rom_state.fixup_end);
320          pos += 4) {
321         cpu_physical_memory_read(paddr + pos - s->rom_state.vaddr,
322                                  &offset, sizeof(offset));
323         offset = le32_to_cpu(offset);
324         cpu_physical_memory_read(paddr + offset, &patch, sizeof(patch));
325         patch = le32_to_cpu(patch);
326         patch += rom_state_vaddr - le32_to_cpu(s->rom_state.vaddr);
327         patch = cpu_to_le32(patch);
328         cpu_physical_memory_write(paddr + offset, &patch, sizeof(patch));
329     }
330     read_guest_rom_state(s);
331     s->vapic_paddr = paddr + le32_to_cpu(s->rom_state.vapic_vaddr) -
332         le32_to_cpu(s->rom_state.vaddr);
333 
334     return 0;
335 }
336 
337 /*
338  * Tries to read the unique processor number from the Kernel Processor Control
339  * Region (KPCR) of 32-bit Windows XP and Server 2003. Returns -1 if the KPCR
340  * cannot be accessed or is considered invalid. This also ensures that we are
341  * not patching the wrong guest.
342  */
343 static int get_kpcr_number(X86CPU *cpu)
344 {
345     CPUX86State *env = &cpu->env;
346     struct kpcr {
347         uint8_t  fill1[0x1c];
348         uint32_t self;
349         uint8_t  fill2[0x31];
350         uint8_t  number;
351     } QEMU_PACKED kpcr;
352 
353     if (cpu_memory_rw_debug(CPU(cpu), env->segs[R_FS].base,
354                             (void *)&kpcr, sizeof(kpcr), 0) < 0 ||
355         kpcr.self != env->segs[R_FS].base) {
356         return -1;
357     }
358     return kpcr.number;
359 }
360 
361 static int vapic_enable(VAPICROMState *s, X86CPU *cpu)
362 {
363     int cpu_number = get_kpcr_number(cpu);
364     hwaddr vapic_paddr;
365     static const uint8_t enabled = 1;
366 
367     if (cpu_number < 0) {
368         return -1;
369     }
370     vapic_paddr = s->vapic_paddr +
371         (((hwaddr)cpu_number) << VAPIC_CPU_SHIFT);
372     cpu_physical_memory_write(vapic_paddr + offsetof(VAPICState, enabled),
373                               &enabled, sizeof(enabled));
374     apic_enable_vapic(cpu->apic_state, vapic_paddr);
375 
376     s->state = VAPIC_ACTIVE;
377 
378     return 0;
379 }
380 
381 static void patch_byte(X86CPU *cpu, target_ulong addr, uint8_t byte)
382 {
383     cpu_memory_rw_debug(CPU(cpu), addr, &byte, 1, 1);
384 }
385 
386 static void patch_call(X86CPU *cpu, target_ulong ip, uint32_t target)
387 {
388     uint32_t offset;
389 
390     offset = cpu_to_le32(target - ip - 5);
391     patch_byte(cpu, ip, 0xe8); /* call near */
392     cpu_memory_rw_debug(CPU(cpu), ip + 1, (void *)&offset, sizeof(offset), 1);
393 }
394 
395 typedef struct PatchInfo {
396     VAPICHandlers *handler;
397     target_ulong ip;
398 } PatchInfo;
399 
400 static void do_patch_instruction(CPUState *cs, run_on_cpu_data data)
401 {
402     X86CPU *x86_cpu = X86_CPU(cs);
403     PatchInfo *info = (PatchInfo *) data.host_ptr;
404     VAPICHandlers *handlers = info->handler;
405     target_ulong ip = info->ip;
406     uint8_t opcode[2];
407     uint32_t imm32 = 0;
408 
409     cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0);
410 
411     switch (opcode[0]) {
412     case 0x89: /* mov r32 to r/m32 */
413         patch_byte(x86_cpu, ip, 0x50 + modrm_reg(opcode[1]));  /* push reg */
414         patch_call(x86_cpu, ip + 1, handlers->set_tpr);
415         break;
416     case 0x8b: /* mov r/m32 to r32 */
417         patch_byte(x86_cpu, ip, 0x90);
418         patch_call(x86_cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]);
419         break;
420     case 0xa1: /* mov abs to eax */
421         patch_call(x86_cpu, ip, handlers->get_tpr[0]);
422         break;
423     case 0xa3: /* mov eax to abs */
424         patch_call(x86_cpu, ip, handlers->set_tpr_eax);
425         break;
426     case 0xc7: /* mov imm32, r/m32 (c7/0) */
427         patch_byte(x86_cpu, ip, 0x68);  /* push imm32 */
428         cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0);
429         cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1);
430         patch_call(x86_cpu, ip + 5, handlers->set_tpr);
431         break;
432     case 0xff: /* push r/m32 */
433         patch_byte(x86_cpu, ip, 0x50); /* push eax */
434         patch_call(x86_cpu, ip + 1, handlers->get_tpr_stack);
435         break;
436     default:
437         abort();
438     }
439 
440     g_free(info);
441 }
442 
443 static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip)
444 {
445     CPUState *cs = CPU(cpu);
446     VAPICHandlers *handlers;
447     PatchInfo *info;
448 
449     if (smp_cpus == 1) {
450         handlers = &s->rom_state.up;
451     } else {
452         handlers = &s->rom_state.mp;
453     }
454 
455     info  = g_new(PatchInfo, 1);
456     info->handler = handlers;
457     info->ip = ip;
458 
459     async_safe_run_on_cpu(cs, do_patch_instruction, RUN_ON_CPU_HOST_PTR(info));
460 }
461 
462 void vapic_report_tpr_access(DeviceState *dev, CPUState *cs, target_ulong ip,
463                              TPRAccess access)
464 {
465     VAPICROMState *s = VAPIC(dev);
466     X86CPU *cpu = X86_CPU(cs);
467     CPUX86State *env = &cpu->env;
468 
469     cpu_synchronize_state(cs);
470 
471     if (evaluate_tpr_instruction(s, cpu, &ip, access) < 0) {
472         if (s->state == VAPIC_ACTIVE) {
473             vapic_enable(s, cpu);
474         }
475         return;
476     }
477     if (update_rom_mapping(s, env, ip) < 0) {
478         return;
479     }
480     if (vapic_enable(s, cpu) < 0) {
481         return;
482     }
483     patch_instruction(s, cpu, ip);
484 }
485 
486 typedef struct VAPICEnableTPRReporting {
487     DeviceState *apic;
488     bool enable;
489 } VAPICEnableTPRReporting;
490 
491 static void vapic_do_enable_tpr_reporting(CPUState *cpu, run_on_cpu_data data)
492 {
493     VAPICEnableTPRReporting *info = data.host_ptr;
494     apic_enable_tpr_access_reporting(info->apic, info->enable);
495 }
496 
497 static void vapic_enable_tpr_reporting(bool enable)
498 {
499     VAPICEnableTPRReporting info = {
500         .enable = enable,
501     };
502     CPUState *cs;
503     X86CPU *cpu;
504 
505     CPU_FOREACH(cs) {
506         cpu = X86_CPU(cs);
507         info.apic = cpu->apic_state;
508         run_on_cpu(cs, vapic_do_enable_tpr_reporting, RUN_ON_CPU_HOST_PTR(&info));
509     }
510 }
511 
512 static void vapic_reset(DeviceState *dev)
513 {
514     VAPICROMState *s = VAPIC(dev);
515 
516     s->state = VAPIC_INACTIVE;
517     s->rom_state_paddr = 0;
518     vapic_enable_tpr_reporting(false);
519 }
520 
521 /*
522  * Set the IRQ polling hypercalls to the supported variant:
523  *  - vmcall if using KVM in-kernel irqchip
524  *  - 32-bit VAPIC port write otherwise
525  */
526 static int patch_hypercalls(VAPICROMState *s)
527 {
528     hwaddr rom_paddr = s->rom_state_paddr & ROM_BLOCK_MASK;
529     static const uint8_t vmcall_pattern[] = { /* vmcall */
530         0xb8, 0x1, 0, 0, 0, 0xf, 0x1, 0xc1
531     };
532     static const uint8_t outl_pattern[] = { /* nop; outl %eax,0x7e */
533         0xb8, 0x1, 0, 0, 0, 0x90, 0xe7, 0x7e
534     };
535     uint8_t alternates[2];
536     const uint8_t *pattern;
537     const uint8_t *patch;
538     off_t pos;
539     uint8_t *rom;
540 
541     rom = g_malloc(s->rom_size);
542     cpu_physical_memory_read(rom_paddr, rom, s->rom_size);
543 
544     for (pos = 0; pos < s->rom_size - sizeof(vmcall_pattern); pos++) {
545         if (kvm_irqchip_in_kernel()) {
546             pattern = outl_pattern;
547             alternates[0] = outl_pattern[7];
548             alternates[1] = outl_pattern[7];
549             patch = &vmcall_pattern[5];
550         } else {
551             pattern = vmcall_pattern;
552             alternates[0] = vmcall_pattern[7];
553             alternates[1] = 0xd9; /* AMD's VMMCALL */
554             patch = &outl_pattern[5];
555         }
556         if (memcmp(rom + pos, pattern, 7) == 0 &&
557             (rom[pos + 7] == alternates[0] || rom[pos + 7] == alternates[1])) {
558             cpu_physical_memory_write(rom_paddr + pos + 5, patch, 3);
559             /*
560              * Don't flush the tb here. Under ordinary conditions, the patched
561              * calls are miles away from the current IP. Under malicious
562              * conditions, the guest could trick us to crash.
563              */
564         }
565     }
566 
567     g_free(rom);
568     return 0;
569 }
570 
571 /*
572  * For TCG mode or the time KVM honors read-only memory regions, we need to
573  * enable write access to the option ROM so that variables can be updated by
574  * the guest.
575  */
576 static int vapic_map_rom_writable(VAPICROMState *s)
577 {
578     hwaddr rom_paddr = s->rom_state_paddr & ROM_BLOCK_MASK;
579     MemoryRegionSection section;
580     MemoryRegion *as;
581     size_t rom_size;
582     uint8_t *ram;
583 
584     as = sysbus_address_space(&s->busdev);
585 
586     if (s->rom_mapped_writable) {
587         memory_region_del_subregion(as, &s->rom);
588         object_unparent(OBJECT(&s->rom));
589     }
590 
591     /* grab RAM memory region (region @rom_paddr may still be pc.rom) */
592     section = memory_region_find(as, 0, 1);
593 
594     /* read ROM size from RAM region */
595     if (rom_paddr + 2 >= memory_region_size(section.mr)) {
596         return -1;
597     }
598     ram = memory_region_get_ram_ptr(section.mr);
599     rom_size = ram[rom_paddr + 2] * ROM_BLOCK_SIZE;
600     if (rom_size == 0) {
601         return -1;
602     }
603     s->rom_size = rom_size;
604 
605     /* We need to round to avoid creating subpages
606      * from which we cannot run code. */
607     rom_size += rom_paddr & ~TARGET_PAGE_MASK;
608     rom_paddr &= TARGET_PAGE_MASK;
609     rom_size = TARGET_PAGE_ALIGN(rom_size);
610 
611     memory_region_init_alias(&s->rom, OBJECT(s), "kvmvapic-rom", section.mr,
612                              rom_paddr, rom_size);
613     memory_region_add_subregion_overlap(as, rom_paddr, &s->rom, 1000);
614     s->rom_mapped_writable = true;
615     memory_region_unref(section.mr);
616 
617     return 0;
618 }
619 
620 static int vapic_prepare(VAPICROMState *s)
621 {
622     if (vapic_map_rom_writable(s) < 0) {
623         return -1;
624     }
625 
626     if (patch_hypercalls(s) < 0) {
627         return -1;
628     }
629 
630     vapic_enable_tpr_reporting(true);
631 
632     return 0;
633 }
634 
635 static void vapic_write(void *opaque, hwaddr addr, uint64_t data,
636                         unsigned int size)
637 {
638     VAPICROMState *s = opaque;
639     X86CPU *cpu;
640     CPUX86State *env;
641     hwaddr rom_paddr;
642 
643     if (!current_cpu) {
644         return;
645     }
646 
647     cpu_synchronize_state(current_cpu);
648     cpu = X86_CPU(current_cpu);
649     env = &cpu->env;
650 
651     /*
652      * The VAPIC supports two PIO-based hypercalls, both via port 0x7E.
653      *  o 16-bit write access:
654      *    Reports the option ROM initialization to the hypervisor. Written
655      *    value is the offset of the state structure in the ROM.
656      *  o 8-bit write access:
657      *    Reactivates the VAPIC after a guest hibernation, i.e. after the
658      *    option ROM content has been re-initialized by a guest power cycle.
659      *  o 32-bit write access:
660      *    Poll for pending IRQs, considering the current VAPIC state.
661      */
662     switch (size) {
663     case 2:
664         if (s->state == VAPIC_INACTIVE) {
665             rom_paddr = (env->segs[R_CS].base + env->eip) & ROM_BLOCK_MASK;
666             s->rom_state_paddr = rom_paddr + data;
667 
668             s->state = VAPIC_STANDBY;
669         }
670         if (vapic_prepare(s) < 0) {
671             s->state = VAPIC_INACTIVE;
672             s->rom_state_paddr = 0;
673             break;
674         }
675         break;
676     case 1:
677         if (kvm_enabled()) {
678             /*
679              * Disable triggering instruction in ROM by writing a NOP.
680              *
681              * We cannot do this in TCG mode as the reported IP is not
682              * accurate.
683              */
684             pause_all_vcpus();
685             patch_byte(cpu, env->eip - 2, 0x66);
686             patch_byte(cpu, env->eip - 1, 0x90);
687             resume_all_vcpus();
688         }
689 
690         if (s->state == VAPIC_ACTIVE) {
691             break;
692         }
693         if (update_rom_mapping(s, env, env->eip) < 0) {
694             break;
695         }
696         if (find_real_tpr_addr(s, env) < 0) {
697             break;
698         }
699         vapic_enable(s, cpu);
700         break;
701     default:
702     case 4:
703         if (!kvm_irqchip_in_kernel()) {
704             apic_poll_irq(cpu->apic_state);
705         }
706         break;
707     }
708 }
709 
710 static uint64_t vapic_read(void *opaque, hwaddr addr, unsigned size)
711 {
712     return 0xffffffff;
713 }
714 
715 static const MemoryRegionOps vapic_ops = {
716     .write = vapic_write,
717     .read = vapic_read,
718     .endianness = DEVICE_NATIVE_ENDIAN,
719 };
720 
721 static void vapic_realize(DeviceState *dev, Error **errp)
722 {
723     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
724     VAPICROMState *s = VAPIC(dev);
725 
726     memory_region_init_io(&s->io, OBJECT(s), &vapic_ops, s, "kvmvapic", 2);
727     sysbus_add_io(sbd, VAPIC_IO_PORT, &s->io);
728     sysbus_init_ioports(sbd, VAPIC_IO_PORT, 2);
729 
730     option_rom[nb_option_roms].name = "kvmvapic.bin";
731     option_rom[nb_option_roms].bootindex = -1;
732     nb_option_roms++;
733 }
734 
735 static void do_vapic_enable(CPUState *cs, run_on_cpu_data data)
736 {
737     VAPICROMState *s = data.host_ptr;
738     X86CPU *cpu = X86_CPU(cs);
739 
740     static const uint8_t enabled = 1;
741     cpu_physical_memory_write(s->vapic_paddr + offsetof(VAPICState, enabled),
742                               &enabled, sizeof(enabled));
743     apic_enable_vapic(cpu->apic_state, s->vapic_paddr);
744     s->state = VAPIC_ACTIVE;
745 }
746 
747 static void kvmvapic_vm_state_change(void *opaque, int running,
748                                      RunState state)
749 {
750     VAPICROMState *s = opaque;
751     uint8_t *zero;
752 
753     if (!running) {
754         return;
755     }
756 
757     if (s->state == VAPIC_ACTIVE) {
758         if (smp_cpus == 1) {
759             run_on_cpu(first_cpu, do_vapic_enable, RUN_ON_CPU_HOST_PTR(s));
760         } else {
761             zero = g_malloc0(s->rom_state.vapic_size);
762             cpu_physical_memory_write(s->vapic_paddr, zero,
763                                       s->rom_state.vapic_size);
764             g_free(zero);
765         }
766     }
767 
768     qemu_del_vm_change_state_handler(s->vmsentry);
769     s->vmsentry = NULL;
770 }
771 
772 static int vapic_post_load(void *opaque, int version_id)
773 {
774     VAPICROMState *s = opaque;
775 
776     /*
777      * The old implementation of qemu-kvm did not provide the state
778      * VAPIC_STANDBY. Reconstruct it.
779      */
780     if (s->state == VAPIC_INACTIVE && s->rom_state_paddr != 0) {
781         s->state = VAPIC_STANDBY;
782     }
783 
784     if (s->state != VAPIC_INACTIVE) {
785         if (vapic_prepare(s) < 0) {
786             return -1;
787         }
788     }
789 
790     if (!s->vmsentry) {
791         s->vmsentry =
792             qemu_add_vm_change_state_handler(kvmvapic_vm_state_change, s);
793     }
794     return 0;
795 }
796 
797 static const VMStateDescription vmstate_handlers = {
798     .name = "kvmvapic-handlers",
799     .version_id = 1,
800     .minimum_version_id = 1,
801     .fields = (VMStateField[]) {
802         VMSTATE_UINT32(set_tpr, VAPICHandlers),
803         VMSTATE_UINT32(set_tpr_eax, VAPICHandlers),
804         VMSTATE_UINT32_ARRAY(get_tpr, VAPICHandlers, 8),
805         VMSTATE_UINT32(get_tpr_stack, VAPICHandlers),
806         VMSTATE_END_OF_LIST()
807     }
808 };
809 
810 static const VMStateDescription vmstate_guest_rom = {
811     .name = "kvmvapic-guest-rom",
812     .version_id = 1,
813     .minimum_version_id = 1,
814     .fields = (VMStateField[]) {
815         VMSTATE_UNUSED(8),     /* signature */
816         VMSTATE_UINT32(vaddr, GuestROMState),
817         VMSTATE_UINT32(fixup_start, GuestROMState),
818         VMSTATE_UINT32(fixup_end, GuestROMState),
819         VMSTATE_UINT32(vapic_vaddr, GuestROMState),
820         VMSTATE_UINT32(vapic_size, GuestROMState),
821         VMSTATE_UINT32(vcpu_shift, GuestROMState),
822         VMSTATE_UINT32(real_tpr_addr, GuestROMState),
823         VMSTATE_STRUCT(up, GuestROMState, 0, vmstate_handlers, VAPICHandlers),
824         VMSTATE_STRUCT(mp, GuestROMState, 0, vmstate_handlers, VAPICHandlers),
825         VMSTATE_END_OF_LIST()
826     }
827 };
828 
829 static const VMStateDescription vmstate_vapic = {
830     .name = "kvm-tpr-opt",      /* compatible with qemu-kvm VAPIC */
831     .version_id = 1,
832     .minimum_version_id = 1,
833     .post_load = vapic_post_load,
834     .fields = (VMStateField[]) {
835         VMSTATE_STRUCT(rom_state, VAPICROMState, 0, vmstate_guest_rom,
836                        GuestROMState),
837         VMSTATE_UINT32(state, VAPICROMState),
838         VMSTATE_UINT32(real_tpr_addr, VAPICROMState),
839         VMSTATE_UINT32(rom_state_vaddr, VAPICROMState),
840         VMSTATE_UINT32(vapic_paddr, VAPICROMState),
841         VMSTATE_UINT32(rom_state_paddr, VAPICROMState),
842         VMSTATE_END_OF_LIST()
843     }
844 };
845 
846 static void vapic_class_init(ObjectClass *klass, void *data)
847 {
848     DeviceClass *dc = DEVICE_CLASS(klass);
849 
850     dc->reset   = vapic_reset;
851     dc->vmsd    = &vmstate_vapic;
852     dc->realize = vapic_realize;
853 }
854 
855 static const TypeInfo vapic_type = {
856     .name          = TYPE_VAPIC,
857     .parent        = TYPE_SYS_BUS_DEVICE,
858     .instance_size = sizeof(VAPICROMState),
859     .class_init    = vapic_class_init,
860 };
861 
862 static void vapic_register(void)
863 {
864     type_register_static(&vapic_type);
865 }
866 
867 type_init(vapic_register);
868