xref: /openbmc/qemu/target/ppc/kvm.c (revision 500eb6db)
1 /*
2  * PowerPC implementation of KVM hooks
3  *
4  * Copyright IBM Corp. 2007
5  * Copyright (C) 2011 Freescale Semiconductor, Inc.
6  *
7  * Authors:
8  *  Jerone Young <jyoung5@us.ibm.com>
9  *  Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com>
10  *  Hollis Blanchard <hollisb@us.ibm.com>
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2 or later.
13  * See the COPYING file in the top-level directory.
14  *
15  */
16 
17 #include "qemu/osdep.h"
18 #include <dirent.h>
19 #include <sys/ioctl.h>
20 #include <sys/vfs.h>
21 
22 #include <linux/kvm.h>
23 
24 #include "qemu-common.h"
25 #include "qapi/error.h"
26 #include "qemu/error-report.h"
27 #include "cpu.h"
28 #include "cpu-models.h"
29 #include "qemu/timer.h"
30 #include "sysemu/sysemu.h"
31 #include "sysemu/hw_accel.h"
32 #include "kvm_ppc.h"
33 #include "sysemu/cpus.h"
34 #include "sysemu/device_tree.h"
35 #include "mmu-hash64.h"
36 
37 #include "hw/sysbus.h"
38 #include "hw/ppc/spapr.h"
39 #include "hw/ppc/spapr_cpu_core.h"
40 #include "hw/ppc/ppc.h"
41 #include "sysemu/watchdog.h"
42 #include "trace.h"
43 #include "exec/gdbstub.h"
44 #include "exec/memattrs.h"
45 #include "exec/ram_addr.h"
46 #include "sysemu/hostmem.h"
47 #include "qemu/cutils.h"
48 #include "qemu/mmap-alloc.h"
49 #include "elf.h"
50 #include "sysemu/kvm_int.h"
51 
52 #define PROC_DEVTREE_CPU      "/proc/device-tree/cpus/"
53 
54 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
55     KVM_CAP_LAST_INFO
56 };
57 
58 static int cap_interrupt_unset;
59 static int cap_interrupt_level;
60 static int cap_segstate;
61 static int cap_booke_sregs;
62 static int cap_ppc_smt;
63 static int cap_ppc_smt_possible;
64 static int cap_spapr_tce;
65 static int cap_spapr_tce_64;
66 static int cap_spapr_multitce;
67 static int cap_spapr_vfio;
68 static int cap_hior;
69 static int cap_one_reg;
70 static int cap_epr;
71 static int cap_ppc_watchdog;
72 static int cap_papr;
73 static int cap_htab_fd;
74 static int cap_fixup_hcalls;
75 static int cap_htm;             /* Hardware transactional memory support */
76 static int cap_mmu_radix;
77 static int cap_mmu_hash_v3;
78 static int cap_xive;
79 static int cap_resize_hpt;
80 static int cap_ppc_pvr_compat;
81 static int cap_ppc_safe_cache;
82 static int cap_ppc_safe_bounds_check;
83 static int cap_ppc_safe_indirect_branch;
84 static int cap_ppc_count_cache_flush_assist;
85 static int cap_ppc_nested_kvm_hv;
86 static int cap_large_decr;
87 
88 static uint32_t debug_inst_opcode;
89 
90 /*
91  * XXX We have a race condition where we actually have a level triggered
92  *     interrupt, but the infrastructure can't expose that yet, so the guest
93  *     takes but ignores it, goes to sleep and never gets notified that there's
94  *     still an interrupt pending.
95  *
96  *     As a quick workaround, let's just wake up again 20 ms after we injected
97  *     an interrupt. That way we can assure that we're always reinjecting
98  *     interrupts in case the guest swallowed them.
99  */
100 static QEMUTimer *idle_timer;
101 
102 static void kvm_kick_cpu(void *opaque)
103 {
104     PowerPCCPU *cpu = opaque;
105 
106     qemu_cpu_kick(CPU(cpu));
107 }
108 
109 /*
110  * Check whether we are running with KVM-PR (instead of KVM-HV).  This
111  * should only be used for fallback tests - generally we should use
112  * explicit capabilities for the features we want, rather than
113  * assuming what is/isn't available depending on the KVM variant.
114  */
115 static bool kvmppc_is_pr(KVMState *ks)
116 {
117     /* Assume KVM-PR if the GET_PVINFO capability is available */
118     return kvm_vm_check_extension(ks, KVM_CAP_PPC_GET_PVINFO) != 0;
119 }
120 
121 static int kvm_ppc_register_host_cpu_type(MachineState *ms);
122 static void kvmppc_get_cpu_characteristics(KVMState *s);
123 static int kvmppc_get_dec_bits(void);
124 
125 int kvm_arch_init(MachineState *ms, KVMState *s)
126 {
127     cap_interrupt_unset = kvm_check_extension(s, KVM_CAP_PPC_UNSET_IRQ);
128     cap_interrupt_level = kvm_check_extension(s, KVM_CAP_PPC_IRQ_LEVEL);
129     cap_segstate = kvm_check_extension(s, KVM_CAP_PPC_SEGSTATE);
130     cap_booke_sregs = kvm_check_extension(s, KVM_CAP_PPC_BOOKE_SREGS);
131     cap_ppc_smt_possible = kvm_vm_check_extension(s, KVM_CAP_PPC_SMT_POSSIBLE);
132     cap_spapr_tce = kvm_check_extension(s, KVM_CAP_SPAPR_TCE);
133     cap_spapr_tce_64 = kvm_check_extension(s, KVM_CAP_SPAPR_TCE_64);
134     cap_spapr_multitce = kvm_check_extension(s, KVM_CAP_SPAPR_MULTITCE);
135     cap_spapr_vfio = kvm_vm_check_extension(s, KVM_CAP_SPAPR_TCE_VFIO);
136     cap_one_reg = kvm_check_extension(s, KVM_CAP_ONE_REG);
137     cap_hior = kvm_check_extension(s, KVM_CAP_PPC_HIOR);
138     cap_epr = kvm_check_extension(s, KVM_CAP_PPC_EPR);
139     cap_ppc_watchdog = kvm_check_extension(s, KVM_CAP_PPC_BOOKE_WATCHDOG);
140     /*
141      * Note: we don't set cap_papr here, because this capability is
142      * only activated after this by kvmppc_set_papr()
143      */
144     cap_htab_fd = kvm_vm_check_extension(s, KVM_CAP_PPC_HTAB_FD);
145     cap_fixup_hcalls = kvm_check_extension(s, KVM_CAP_PPC_FIXUP_HCALL);
146     cap_ppc_smt = kvm_vm_check_extension(s, KVM_CAP_PPC_SMT);
147     cap_htm = kvm_vm_check_extension(s, KVM_CAP_PPC_HTM);
148     cap_mmu_radix = kvm_vm_check_extension(s, KVM_CAP_PPC_MMU_RADIX);
149     cap_mmu_hash_v3 = kvm_vm_check_extension(s, KVM_CAP_PPC_MMU_HASH_V3);
150     cap_xive = kvm_vm_check_extension(s, KVM_CAP_PPC_IRQ_XIVE);
151     cap_resize_hpt = kvm_vm_check_extension(s, KVM_CAP_SPAPR_RESIZE_HPT);
152     kvmppc_get_cpu_characteristics(s);
153     cap_ppc_nested_kvm_hv = kvm_vm_check_extension(s, KVM_CAP_PPC_NESTED_HV);
154     cap_large_decr = kvmppc_get_dec_bits();
155     /*
156      * Note: setting it to false because there is not such capability
157      * in KVM at this moment.
158      *
159      * TODO: call kvm_vm_check_extension() with the right capability
160      * after the kernel starts implementing it.
161      */
162     cap_ppc_pvr_compat = false;
163 
164     if (!cap_interrupt_level) {
165         fprintf(stderr, "KVM: Couldn't find level irq capability. Expect the "
166                         "VM to stall at times!\n");
167     }
168 
169     kvm_ppc_register_host_cpu_type(ms);
170 
171     return 0;
172 }
173 
174 int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
175 {
176     return 0;
177 }
178 
179 static int kvm_arch_sync_sregs(PowerPCCPU *cpu)
180 {
181     CPUPPCState *cenv = &cpu->env;
182     CPUState *cs = CPU(cpu);
183     struct kvm_sregs sregs;
184     int ret;
185 
186     if (cenv->excp_model == POWERPC_EXCP_BOOKE) {
187         /*
188          * What we're really trying to say is "if we're on BookE, we
189          * use the native PVR for now". This is the only sane way to
190          * check it though, so we potentially confuse users that they
191          * can run BookE guests on BookS. Let's hope nobody dares
192          * enough :)
193          */
194         return 0;
195     } else {
196         if (!cap_segstate) {
197             fprintf(stderr, "kvm error: missing PVR setting capability\n");
198             return -ENOSYS;
199         }
200     }
201 
202     ret = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);
203     if (ret) {
204         return ret;
205     }
206 
207     sregs.pvr = cenv->spr[SPR_PVR];
208     return kvm_vcpu_ioctl(cs, KVM_SET_SREGS, &sregs);
209 }
210 
211 /* Set up a shared TLB array with KVM */
212 static int kvm_booke206_tlb_init(PowerPCCPU *cpu)
213 {
214     CPUPPCState *env = &cpu->env;
215     CPUState *cs = CPU(cpu);
216     struct kvm_book3e_206_tlb_params params = {};
217     struct kvm_config_tlb cfg = {};
218     unsigned int entries = 0;
219     int ret, i;
220 
221     if (!kvm_enabled() ||
222         !kvm_check_extension(cs->kvm_state, KVM_CAP_SW_TLB)) {
223         return 0;
224     }
225 
226     assert(ARRAY_SIZE(params.tlb_sizes) == BOOKE206_MAX_TLBN);
227 
228     for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
229         params.tlb_sizes[i] = booke206_tlb_size(env, i);
230         params.tlb_ways[i] = booke206_tlb_ways(env, i);
231         entries += params.tlb_sizes[i];
232     }
233 
234     assert(entries == env->nb_tlb);
235     assert(sizeof(struct kvm_book3e_206_tlb_entry) == sizeof(ppcmas_tlb_t));
236 
237     env->tlb_dirty = true;
238 
239     cfg.array = (uintptr_t)env->tlb.tlbm;
240     cfg.array_len = sizeof(ppcmas_tlb_t) * entries;
241     cfg.params = (uintptr_t)&params;
242     cfg.mmu_type = KVM_MMU_FSL_BOOKE_NOHV;
243 
244     ret = kvm_vcpu_enable_cap(cs, KVM_CAP_SW_TLB, 0, (uintptr_t)&cfg);
245     if (ret < 0) {
246         fprintf(stderr, "%s: couldn't enable KVM_CAP_SW_TLB: %s\n",
247                 __func__, strerror(-ret));
248         return ret;
249     }
250 
251     env->kvm_sw_tlb = true;
252     return 0;
253 }
254 
255 
256 #if defined(TARGET_PPC64)
257 static void kvm_get_smmu_info(struct kvm_ppc_smmu_info *info, Error **errp)
258 {
259     int ret;
260 
261     assert(kvm_state != NULL);
262 
263     if (!kvm_check_extension(kvm_state, KVM_CAP_PPC_GET_SMMU_INFO)) {
264         error_setg(errp, "KVM doesn't expose the MMU features it supports");
265         error_append_hint(errp, "Consider switching to a newer KVM\n");
266         return;
267     }
268 
269     ret = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_SMMU_INFO, info);
270     if (ret == 0) {
271         return;
272     }
273 
274     error_setg_errno(errp, -ret,
275                      "KVM failed to provide the MMU features it supports");
276 }
277 
278 struct ppc_radix_page_info *kvm_get_radix_page_info(void)
279 {
280     KVMState *s = KVM_STATE(current_machine->accelerator);
281     struct ppc_radix_page_info *radix_page_info;
282     struct kvm_ppc_rmmu_info rmmu_info;
283     int i;
284 
285     if (!kvm_check_extension(s, KVM_CAP_PPC_MMU_RADIX)) {
286         return NULL;
287     }
288     if (kvm_vm_ioctl(s, KVM_PPC_GET_RMMU_INFO, &rmmu_info)) {
289         return NULL;
290     }
291     radix_page_info = g_malloc0(sizeof(*radix_page_info));
292     radix_page_info->count = 0;
293     for (i = 0; i < PPC_PAGE_SIZES_MAX_SZ; i++) {
294         if (rmmu_info.ap_encodings[i]) {
295             radix_page_info->entries[i] = rmmu_info.ap_encodings[i];
296             radix_page_info->count++;
297         }
298     }
299     return radix_page_info;
300 }
301 
302 target_ulong kvmppc_configure_v3_mmu(PowerPCCPU *cpu,
303                                      bool radix, bool gtse,
304                                      uint64_t proc_tbl)
305 {
306     CPUState *cs = CPU(cpu);
307     int ret;
308     uint64_t flags = 0;
309     struct kvm_ppc_mmuv3_cfg cfg = {
310         .process_table = proc_tbl,
311     };
312 
313     if (radix) {
314         flags |= KVM_PPC_MMUV3_RADIX;
315     }
316     if (gtse) {
317         flags |= KVM_PPC_MMUV3_GTSE;
318     }
319     cfg.flags = flags;
320     ret = kvm_vm_ioctl(cs->kvm_state, KVM_PPC_CONFIGURE_V3_MMU, &cfg);
321     switch (ret) {
322     case 0:
323         return H_SUCCESS;
324     case -EINVAL:
325         return H_PARAMETER;
326     case -ENODEV:
327         return H_NOT_AVAILABLE;
328     default:
329         return H_HARDWARE;
330     }
331 }
332 
333 bool kvmppc_hpt_needs_host_contiguous_pages(void)
334 {
335     static struct kvm_ppc_smmu_info smmu_info;
336 
337     if (!kvm_enabled()) {
338         return false;
339     }
340 
341     kvm_get_smmu_info(&smmu_info, &error_fatal);
342     return !!(smmu_info.flags & KVM_PPC_PAGE_SIZES_REAL);
343 }
344 
345 void kvm_check_mmu(PowerPCCPU *cpu, Error **errp)
346 {
347     struct kvm_ppc_smmu_info smmu_info;
348     int iq, ik, jq, jk;
349     Error *local_err = NULL;
350 
351     /* For now, we only have anything to check on hash64 MMUs */
352     if (!cpu->hash64_opts || !kvm_enabled()) {
353         return;
354     }
355 
356     kvm_get_smmu_info(&smmu_info, &local_err);
357     if (local_err) {
358         error_propagate(errp, local_err);
359         return;
360     }
361 
362     if (ppc_hash64_has(cpu, PPC_HASH64_1TSEG)
363         && !(smmu_info.flags & KVM_PPC_1T_SEGMENTS)) {
364         error_setg(errp,
365                    "KVM does not support 1TiB segments which guest expects");
366         return;
367     }
368 
369     if (smmu_info.slb_size < cpu->hash64_opts->slb_size) {
370         error_setg(errp, "KVM only supports %u SLB entries, but guest needs %u",
371                    smmu_info.slb_size, cpu->hash64_opts->slb_size);
372         return;
373     }
374 
375     /*
376      * Verify that every pagesize supported by the cpu model is
377      * supported by KVM with the same encodings
378      */
379     for (iq = 0; iq < ARRAY_SIZE(cpu->hash64_opts->sps); iq++) {
380         PPCHash64SegmentPageSizes *qsps = &cpu->hash64_opts->sps[iq];
381         struct kvm_ppc_one_seg_page_size *ksps;
382 
383         for (ik = 0; ik < ARRAY_SIZE(smmu_info.sps); ik++) {
384             if (qsps->page_shift == smmu_info.sps[ik].page_shift) {
385                 break;
386             }
387         }
388         if (ik >= ARRAY_SIZE(smmu_info.sps)) {
389             error_setg(errp, "KVM doesn't support for base page shift %u",
390                        qsps->page_shift);
391             return;
392         }
393 
394         ksps = &smmu_info.sps[ik];
395         if (ksps->slb_enc != qsps->slb_enc) {
396             error_setg(errp,
397 "KVM uses SLB encoding 0x%x for page shift %u, but guest expects 0x%x",
398                        ksps->slb_enc, ksps->page_shift, qsps->slb_enc);
399             return;
400         }
401 
402         for (jq = 0; jq < ARRAY_SIZE(qsps->enc); jq++) {
403             for (jk = 0; jk < ARRAY_SIZE(ksps->enc); jk++) {
404                 if (qsps->enc[jq].page_shift == ksps->enc[jk].page_shift) {
405                     break;
406                 }
407             }
408 
409             if (jk >= ARRAY_SIZE(ksps->enc)) {
410                 error_setg(errp, "KVM doesn't support page shift %u/%u",
411                            qsps->enc[jq].page_shift, qsps->page_shift);
412                 return;
413             }
414             if (qsps->enc[jq].pte_enc != ksps->enc[jk].pte_enc) {
415                 error_setg(errp,
416 "KVM uses PTE encoding 0x%x for page shift %u/%u, but guest expects 0x%x",
417                            ksps->enc[jk].pte_enc, qsps->enc[jq].page_shift,
418                            qsps->page_shift, qsps->enc[jq].pte_enc);
419                 return;
420             }
421         }
422     }
423 
424     if (ppc_hash64_has(cpu, PPC_HASH64_CI_LARGEPAGE)) {
425         /*
426          * Mostly what guest pagesizes we can use are related to the
427          * host pages used to map guest RAM, which is handled in the
428          * platform code. Cache-Inhibited largepages (64k) however are
429          * used for I/O, so if they're mapped to the host at all it
430          * will be a normal mapping, not a special hugepage one used
431          * for RAM.
432          */
433         if (getpagesize() < 0x10000) {
434             error_setg(errp,
435                        "KVM can't supply 64kiB CI pages, which guest expects");
436         }
437     }
438 }
439 #endif /* !defined (TARGET_PPC64) */
440 
441 unsigned long kvm_arch_vcpu_id(CPUState *cpu)
442 {
443     return POWERPC_CPU(cpu)->vcpu_id;
444 }
445 
446 /*
447  * e500 supports 2 h/w breakpoint and 2 watchpoint.  book3s supports
448  * only 1 watchpoint, so array size of 4 is sufficient for now.
449  */
450 #define MAX_HW_BKPTS 4
451 
452 static struct HWBreakpoint {
453     target_ulong addr;
454     int type;
455 } hw_debug_points[MAX_HW_BKPTS];
456 
457 static CPUWatchpoint hw_watchpoint;
458 
459 /* Default there is no breakpoint and watchpoint supported */
460 static int max_hw_breakpoint;
461 static int max_hw_watchpoint;
462 static int nb_hw_breakpoint;
463 static int nb_hw_watchpoint;
464 
465 static void kvmppc_hw_debug_points_init(CPUPPCState *cenv)
466 {
467     if (cenv->excp_model == POWERPC_EXCP_BOOKE) {
468         max_hw_breakpoint = 2;
469         max_hw_watchpoint = 2;
470     }
471 
472     if ((max_hw_breakpoint + max_hw_watchpoint) > MAX_HW_BKPTS) {
473         fprintf(stderr, "Error initializing h/w breakpoints\n");
474         return;
475     }
476 }
477 
478 int kvm_arch_init_vcpu(CPUState *cs)
479 {
480     PowerPCCPU *cpu = POWERPC_CPU(cs);
481     CPUPPCState *cenv = &cpu->env;
482     int ret;
483 
484     /* Synchronize sregs with kvm */
485     ret = kvm_arch_sync_sregs(cpu);
486     if (ret) {
487         if (ret == -EINVAL) {
488             error_report("Register sync failed... If you're using kvm-hv.ko,"
489                          " only \"-cpu host\" is possible");
490         }
491         return ret;
492     }
493 
494     idle_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, kvm_kick_cpu, cpu);
495 
496     switch (cenv->mmu_model) {
497     case POWERPC_MMU_BOOKE206:
498         /* This target supports access to KVM's guest TLB */
499         ret = kvm_booke206_tlb_init(cpu);
500         break;
501     case POWERPC_MMU_2_07:
502         if (!cap_htm && !kvmppc_is_pr(cs->kvm_state)) {
503             /*
504              * KVM-HV has transactional memory on POWER8 also without
505              * the KVM_CAP_PPC_HTM extension, so enable it here
506              * instead as long as it's availble to userspace on the
507              * host.
508              */
509             if (qemu_getauxval(AT_HWCAP2) & PPC_FEATURE2_HAS_HTM) {
510                 cap_htm = true;
511             }
512         }
513         break;
514     default:
515         break;
516     }
517 
518     kvm_get_one_reg(cs, KVM_REG_PPC_DEBUG_INST, &debug_inst_opcode);
519     kvmppc_hw_debug_points_init(cenv);
520 
521     return ret;
522 }
523 
524 static void kvm_sw_tlb_put(PowerPCCPU *cpu)
525 {
526     CPUPPCState *env = &cpu->env;
527     CPUState *cs = CPU(cpu);
528     struct kvm_dirty_tlb dirty_tlb;
529     unsigned char *bitmap;
530     int ret;
531 
532     if (!env->kvm_sw_tlb) {
533         return;
534     }
535 
536     bitmap = g_malloc((env->nb_tlb + 7) / 8);
537     memset(bitmap, 0xFF, (env->nb_tlb + 7) / 8);
538 
539     dirty_tlb.bitmap = (uintptr_t)bitmap;
540     dirty_tlb.num_dirty = env->nb_tlb;
541 
542     ret = kvm_vcpu_ioctl(cs, KVM_DIRTY_TLB, &dirty_tlb);
543     if (ret) {
544         fprintf(stderr, "%s: KVM_DIRTY_TLB: %s\n",
545                 __func__, strerror(-ret));
546     }
547 
548     g_free(bitmap);
549 }
550 
551 static void kvm_get_one_spr(CPUState *cs, uint64_t id, int spr)
552 {
553     PowerPCCPU *cpu = POWERPC_CPU(cs);
554     CPUPPCState *env = &cpu->env;
555     union {
556         uint32_t u32;
557         uint64_t u64;
558     } val;
559     struct kvm_one_reg reg = {
560         .id = id,
561         .addr = (uintptr_t) &val,
562     };
563     int ret;
564 
565     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
566     if (ret != 0) {
567         trace_kvm_failed_spr_get(spr, strerror(errno));
568     } else {
569         switch (id & KVM_REG_SIZE_MASK) {
570         case KVM_REG_SIZE_U32:
571             env->spr[spr] = val.u32;
572             break;
573 
574         case KVM_REG_SIZE_U64:
575             env->spr[spr] = val.u64;
576             break;
577 
578         default:
579             /* Don't handle this size yet */
580             abort();
581         }
582     }
583 }
584 
585 static void kvm_put_one_spr(CPUState *cs, uint64_t id, int spr)
586 {
587     PowerPCCPU *cpu = POWERPC_CPU(cs);
588     CPUPPCState *env = &cpu->env;
589     union {
590         uint32_t u32;
591         uint64_t u64;
592     } val;
593     struct kvm_one_reg reg = {
594         .id = id,
595         .addr = (uintptr_t) &val,
596     };
597     int ret;
598 
599     switch (id & KVM_REG_SIZE_MASK) {
600     case KVM_REG_SIZE_U32:
601         val.u32 = env->spr[spr];
602         break;
603 
604     case KVM_REG_SIZE_U64:
605         val.u64 = env->spr[spr];
606         break;
607 
608     default:
609         /* Don't handle this size yet */
610         abort();
611     }
612 
613     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
614     if (ret != 0) {
615         trace_kvm_failed_spr_set(spr, strerror(errno));
616     }
617 }
618 
619 static int kvm_put_fp(CPUState *cs)
620 {
621     PowerPCCPU *cpu = POWERPC_CPU(cs);
622     CPUPPCState *env = &cpu->env;
623     struct kvm_one_reg reg;
624     int i;
625     int ret;
626 
627     if (env->insns_flags & PPC_FLOAT) {
628         uint64_t fpscr = env->fpscr;
629         bool vsx = !!(env->insns_flags2 & PPC2_VSX);
630 
631         reg.id = KVM_REG_PPC_FPSCR;
632         reg.addr = (uintptr_t)&fpscr;
633         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
634         if (ret < 0) {
635             trace_kvm_failed_fpscr_set(strerror(errno));
636             return ret;
637         }
638 
639         for (i = 0; i < 32; i++) {
640             uint64_t vsr[2];
641             uint64_t *fpr = cpu_fpr_ptr(&cpu->env, i);
642             uint64_t *vsrl = cpu_vsrl_ptr(&cpu->env, i);
643 
644 #ifdef HOST_WORDS_BIGENDIAN
645             vsr[0] = float64_val(*fpr);
646             vsr[1] = *vsrl;
647 #else
648             vsr[0] = *vsrl;
649             vsr[1] = float64_val(*fpr);
650 #endif
651             reg.addr = (uintptr_t) &vsr;
652             reg.id = vsx ? KVM_REG_PPC_VSR(i) : KVM_REG_PPC_FPR(i);
653 
654             ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
655             if (ret < 0) {
656                 trace_kvm_failed_fp_set(vsx ? "VSR" : "FPR", i,
657                                         strerror(errno));
658                 return ret;
659             }
660         }
661     }
662 
663     if (env->insns_flags & PPC_ALTIVEC) {
664         reg.id = KVM_REG_PPC_VSCR;
665         reg.addr = (uintptr_t)&env->vscr;
666         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
667         if (ret < 0) {
668             trace_kvm_failed_vscr_set(strerror(errno));
669             return ret;
670         }
671 
672         for (i = 0; i < 32; i++) {
673             reg.id = KVM_REG_PPC_VR(i);
674             reg.addr = (uintptr_t)cpu_avr_ptr(env, i);
675             ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
676             if (ret < 0) {
677                 trace_kvm_failed_vr_set(i, strerror(errno));
678                 return ret;
679             }
680         }
681     }
682 
683     return 0;
684 }
685 
686 static int kvm_get_fp(CPUState *cs)
687 {
688     PowerPCCPU *cpu = POWERPC_CPU(cs);
689     CPUPPCState *env = &cpu->env;
690     struct kvm_one_reg reg;
691     int i;
692     int ret;
693 
694     if (env->insns_flags & PPC_FLOAT) {
695         uint64_t fpscr;
696         bool vsx = !!(env->insns_flags2 & PPC2_VSX);
697 
698         reg.id = KVM_REG_PPC_FPSCR;
699         reg.addr = (uintptr_t)&fpscr;
700         ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
701         if (ret < 0) {
702             trace_kvm_failed_fpscr_get(strerror(errno));
703             return ret;
704         } else {
705             env->fpscr = fpscr;
706         }
707 
708         for (i = 0; i < 32; i++) {
709             uint64_t vsr[2];
710             uint64_t *fpr = cpu_fpr_ptr(&cpu->env, i);
711             uint64_t *vsrl = cpu_vsrl_ptr(&cpu->env, i);
712 
713             reg.addr = (uintptr_t) &vsr;
714             reg.id = vsx ? KVM_REG_PPC_VSR(i) : KVM_REG_PPC_FPR(i);
715 
716             ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
717             if (ret < 0) {
718                 trace_kvm_failed_fp_get(vsx ? "VSR" : "FPR", i,
719                                         strerror(errno));
720                 return ret;
721             } else {
722 #ifdef HOST_WORDS_BIGENDIAN
723                 *fpr = vsr[0];
724                 if (vsx) {
725                     *vsrl = vsr[1];
726                 }
727 #else
728                 *fpr = vsr[1];
729                 if (vsx) {
730                     *vsrl = vsr[0];
731                 }
732 #endif
733             }
734         }
735     }
736 
737     if (env->insns_flags & PPC_ALTIVEC) {
738         reg.id = KVM_REG_PPC_VSCR;
739         reg.addr = (uintptr_t)&env->vscr;
740         ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
741         if (ret < 0) {
742             trace_kvm_failed_vscr_get(strerror(errno));
743             return ret;
744         }
745 
746         for (i = 0; i < 32; i++) {
747             reg.id = KVM_REG_PPC_VR(i);
748             reg.addr = (uintptr_t)cpu_avr_ptr(env, i);
749             ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
750             if (ret < 0) {
751                 trace_kvm_failed_vr_get(i, strerror(errno));
752                 return ret;
753             }
754         }
755     }
756 
757     return 0;
758 }
759 
760 #if defined(TARGET_PPC64)
761 static int kvm_get_vpa(CPUState *cs)
762 {
763     PowerPCCPU *cpu = POWERPC_CPU(cs);
764     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
765     struct kvm_one_reg reg;
766     int ret;
767 
768     reg.id = KVM_REG_PPC_VPA_ADDR;
769     reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
770     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
771     if (ret < 0) {
772         trace_kvm_failed_vpa_addr_get(strerror(errno));
773         return ret;
774     }
775 
776     assert((uintptr_t)&spapr_cpu->slb_shadow_size
777            == ((uintptr_t)&spapr_cpu->slb_shadow_addr + 8));
778     reg.id = KVM_REG_PPC_VPA_SLB;
779     reg.addr = (uintptr_t)&spapr_cpu->slb_shadow_addr;
780     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
781     if (ret < 0) {
782         trace_kvm_failed_slb_get(strerror(errno));
783         return ret;
784     }
785 
786     assert((uintptr_t)&spapr_cpu->dtl_size
787            == ((uintptr_t)&spapr_cpu->dtl_addr + 8));
788     reg.id = KVM_REG_PPC_VPA_DTL;
789     reg.addr = (uintptr_t)&spapr_cpu->dtl_addr;
790     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
791     if (ret < 0) {
792         trace_kvm_failed_dtl_get(strerror(errno));
793         return ret;
794     }
795 
796     return 0;
797 }
798 
799 static int kvm_put_vpa(CPUState *cs)
800 {
801     PowerPCCPU *cpu = POWERPC_CPU(cs);
802     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
803     struct kvm_one_reg reg;
804     int ret;
805 
806     /*
807      * SLB shadow or DTL can't be registered unless a master VPA is
808      * registered.  That means when restoring state, if a VPA *is*
809      * registered, we need to set that up first.  If not, we need to
810      * deregister the others before deregistering the master VPA
811      */
812     assert(spapr_cpu->vpa_addr
813            || !(spapr_cpu->slb_shadow_addr || spapr_cpu->dtl_addr));
814 
815     if (spapr_cpu->vpa_addr) {
816         reg.id = KVM_REG_PPC_VPA_ADDR;
817         reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
818         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
819         if (ret < 0) {
820             trace_kvm_failed_vpa_addr_set(strerror(errno));
821             return ret;
822         }
823     }
824 
825     assert((uintptr_t)&spapr_cpu->slb_shadow_size
826            == ((uintptr_t)&spapr_cpu->slb_shadow_addr + 8));
827     reg.id = KVM_REG_PPC_VPA_SLB;
828     reg.addr = (uintptr_t)&spapr_cpu->slb_shadow_addr;
829     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
830     if (ret < 0) {
831         trace_kvm_failed_slb_set(strerror(errno));
832         return ret;
833     }
834 
835     assert((uintptr_t)&spapr_cpu->dtl_size
836            == ((uintptr_t)&spapr_cpu->dtl_addr + 8));
837     reg.id = KVM_REG_PPC_VPA_DTL;
838     reg.addr = (uintptr_t)&spapr_cpu->dtl_addr;
839     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
840     if (ret < 0) {
841         trace_kvm_failed_dtl_set(strerror(errno));
842         return ret;
843     }
844 
845     if (!spapr_cpu->vpa_addr) {
846         reg.id = KVM_REG_PPC_VPA_ADDR;
847         reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
848         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
849         if (ret < 0) {
850             trace_kvm_failed_null_vpa_addr_set(strerror(errno));
851             return ret;
852         }
853     }
854 
855     return 0;
856 }
857 #endif /* TARGET_PPC64 */
858 
859 int kvmppc_put_books_sregs(PowerPCCPU *cpu)
860 {
861     CPUPPCState *env = &cpu->env;
862     struct kvm_sregs sregs;
863     int i;
864 
865     sregs.pvr = env->spr[SPR_PVR];
866 
867     if (cpu->vhyp) {
868         PPCVirtualHypervisorClass *vhc =
869             PPC_VIRTUAL_HYPERVISOR_GET_CLASS(cpu->vhyp);
870         sregs.u.s.sdr1 = vhc->encode_hpt_for_kvm_pr(cpu->vhyp);
871     } else {
872         sregs.u.s.sdr1 = env->spr[SPR_SDR1];
873     }
874 
875     /* Sync SLB */
876 #ifdef TARGET_PPC64
877     for (i = 0; i < ARRAY_SIZE(env->slb); i++) {
878         sregs.u.s.ppc64.slb[i].slbe = env->slb[i].esid;
879         if (env->slb[i].esid & SLB_ESID_V) {
880             sregs.u.s.ppc64.slb[i].slbe |= i;
881         }
882         sregs.u.s.ppc64.slb[i].slbv = env->slb[i].vsid;
883     }
884 #endif
885 
886     /* Sync SRs */
887     for (i = 0; i < 16; i++) {
888         sregs.u.s.ppc32.sr[i] = env->sr[i];
889     }
890 
891     /* Sync BATs */
892     for (i = 0; i < 8; i++) {
893         /* Beware. We have to swap upper and lower bits here */
894         sregs.u.s.ppc32.dbat[i] = ((uint64_t)env->DBAT[0][i] << 32)
895             | env->DBAT[1][i];
896         sregs.u.s.ppc32.ibat[i] = ((uint64_t)env->IBAT[0][i] << 32)
897             | env->IBAT[1][i];
898     }
899 
900     return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
901 }
902 
903 int kvm_arch_put_registers(CPUState *cs, int level)
904 {
905     PowerPCCPU *cpu = POWERPC_CPU(cs);
906     CPUPPCState *env = &cpu->env;
907     struct kvm_regs regs;
908     int ret;
909     int i;
910 
911     ret = kvm_vcpu_ioctl(cs, KVM_GET_REGS, &regs);
912     if (ret < 0) {
913         return ret;
914     }
915 
916     regs.ctr = env->ctr;
917     regs.lr  = env->lr;
918     regs.xer = cpu_read_xer(env);
919     regs.msr = env->msr;
920     regs.pc = env->nip;
921 
922     regs.srr0 = env->spr[SPR_SRR0];
923     regs.srr1 = env->spr[SPR_SRR1];
924 
925     regs.sprg0 = env->spr[SPR_SPRG0];
926     regs.sprg1 = env->spr[SPR_SPRG1];
927     regs.sprg2 = env->spr[SPR_SPRG2];
928     regs.sprg3 = env->spr[SPR_SPRG3];
929     regs.sprg4 = env->spr[SPR_SPRG4];
930     regs.sprg5 = env->spr[SPR_SPRG5];
931     regs.sprg6 = env->spr[SPR_SPRG6];
932     regs.sprg7 = env->spr[SPR_SPRG7];
933 
934     regs.pid = env->spr[SPR_BOOKE_PID];
935 
936     for (i = 0; i < 32; i++) {
937         regs.gpr[i] = env->gpr[i];
938     }
939 
940     regs.cr = 0;
941     for (i = 0; i < 8; i++) {
942         regs.cr |= (env->crf[i] & 15) << (4 * (7 - i));
943     }
944 
945     ret = kvm_vcpu_ioctl(cs, KVM_SET_REGS, &regs);
946     if (ret < 0) {
947         return ret;
948     }
949 
950     kvm_put_fp(cs);
951 
952     if (env->tlb_dirty) {
953         kvm_sw_tlb_put(cpu);
954         env->tlb_dirty = false;
955     }
956 
957     if (cap_segstate && (level >= KVM_PUT_RESET_STATE)) {
958         ret = kvmppc_put_books_sregs(cpu);
959         if (ret < 0) {
960             return ret;
961         }
962     }
963 
964     if (cap_hior && (level >= KVM_PUT_RESET_STATE)) {
965         kvm_put_one_spr(cs, KVM_REG_PPC_HIOR, SPR_HIOR);
966     }
967 
968     if (cap_one_reg) {
969         int i;
970 
971         /*
972          * We deliberately ignore errors here, for kernels which have
973          * the ONE_REG calls, but don't support the specific
974          * registers, there's a reasonable chance things will still
975          * work, at least until we try to migrate.
976          */
977         for (i = 0; i < 1024; i++) {
978             uint64_t id = env->spr_cb[i].one_reg_id;
979 
980             if (id != 0) {
981                 kvm_put_one_spr(cs, id, i);
982             }
983         }
984 
985 #ifdef TARGET_PPC64
986         if (msr_ts) {
987             for (i = 0; i < ARRAY_SIZE(env->tm_gpr); i++) {
988                 kvm_set_one_reg(cs, KVM_REG_PPC_TM_GPR(i), &env->tm_gpr[i]);
989             }
990             for (i = 0; i < ARRAY_SIZE(env->tm_vsr); i++) {
991                 kvm_set_one_reg(cs, KVM_REG_PPC_TM_VSR(i), &env->tm_vsr[i]);
992             }
993             kvm_set_one_reg(cs, KVM_REG_PPC_TM_CR, &env->tm_cr);
994             kvm_set_one_reg(cs, KVM_REG_PPC_TM_LR, &env->tm_lr);
995             kvm_set_one_reg(cs, KVM_REG_PPC_TM_CTR, &env->tm_ctr);
996             kvm_set_one_reg(cs, KVM_REG_PPC_TM_FPSCR, &env->tm_fpscr);
997             kvm_set_one_reg(cs, KVM_REG_PPC_TM_AMR, &env->tm_amr);
998             kvm_set_one_reg(cs, KVM_REG_PPC_TM_PPR, &env->tm_ppr);
999             kvm_set_one_reg(cs, KVM_REG_PPC_TM_VRSAVE, &env->tm_vrsave);
1000             kvm_set_one_reg(cs, KVM_REG_PPC_TM_VSCR, &env->tm_vscr);
1001             kvm_set_one_reg(cs, KVM_REG_PPC_TM_DSCR, &env->tm_dscr);
1002             kvm_set_one_reg(cs, KVM_REG_PPC_TM_TAR, &env->tm_tar);
1003         }
1004 
1005         if (cap_papr) {
1006             if (kvm_put_vpa(cs) < 0) {
1007                 trace_kvm_failed_put_vpa();
1008             }
1009         }
1010 
1011         kvm_set_one_reg(cs, KVM_REG_PPC_TB_OFFSET, &env->tb_env->tb_offset);
1012 #endif /* TARGET_PPC64 */
1013     }
1014 
1015     return ret;
1016 }
1017 
1018 static void kvm_sync_excp(CPUPPCState *env, int vector, int ivor)
1019 {
1020      env->excp_vectors[vector] = env->spr[ivor] + env->spr[SPR_BOOKE_IVPR];
1021 }
1022 
1023 static int kvmppc_get_booke_sregs(PowerPCCPU *cpu)
1024 {
1025     CPUPPCState *env = &cpu->env;
1026     struct kvm_sregs sregs;
1027     int ret;
1028 
1029     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1030     if (ret < 0) {
1031         return ret;
1032     }
1033 
1034     if (sregs.u.e.features & KVM_SREGS_E_BASE) {
1035         env->spr[SPR_BOOKE_CSRR0] = sregs.u.e.csrr0;
1036         env->spr[SPR_BOOKE_CSRR1] = sregs.u.e.csrr1;
1037         env->spr[SPR_BOOKE_ESR] = sregs.u.e.esr;
1038         env->spr[SPR_BOOKE_DEAR] = sregs.u.e.dear;
1039         env->spr[SPR_BOOKE_MCSR] = sregs.u.e.mcsr;
1040         env->spr[SPR_BOOKE_TSR] = sregs.u.e.tsr;
1041         env->spr[SPR_BOOKE_TCR] = sregs.u.e.tcr;
1042         env->spr[SPR_DECR] = sregs.u.e.dec;
1043         env->spr[SPR_TBL] = sregs.u.e.tb & 0xffffffff;
1044         env->spr[SPR_TBU] = sregs.u.e.tb >> 32;
1045         env->spr[SPR_VRSAVE] = sregs.u.e.vrsave;
1046     }
1047 
1048     if (sregs.u.e.features & KVM_SREGS_E_ARCH206) {
1049         env->spr[SPR_BOOKE_PIR] = sregs.u.e.pir;
1050         env->spr[SPR_BOOKE_MCSRR0] = sregs.u.e.mcsrr0;
1051         env->spr[SPR_BOOKE_MCSRR1] = sregs.u.e.mcsrr1;
1052         env->spr[SPR_BOOKE_DECAR] = sregs.u.e.decar;
1053         env->spr[SPR_BOOKE_IVPR] = sregs.u.e.ivpr;
1054     }
1055 
1056     if (sregs.u.e.features & KVM_SREGS_E_64) {
1057         env->spr[SPR_BOOKE_EPCR] = sregs.u.e.epcr;
1058     }
1059 
1060     if (sregs.u.e.features & KVM_SREGS_E_SPRG8) {
1061         env->spr[SPR_BOOKE_SPRG8] = sregs.u.e.sprg8;
1062     }
1063 
1064     if (sregs.u.e.features & KVM_SREGS_E_IVOR) {
1065         env->spr[SPR_BOOKE_IVOR0] = sregs.u.e.ivor_low[0];
1066         kvm_sync_excp(env, POWERPC_EXCP_CRITICAL,  SPR_BOOKE_IVOR0);
1067         env->spr[SPR_BOOKE_IVOR1] = sregs.u.e.ivor_low[1];
1068         kvm_sync_excp(env, POWERPC_EXCP_MCHECK,  SPR_BOOKE_IVOR1);
1069         env->spr[SPR_BOOKE_IVOR2] = sregs.u.e.ivor_low[2];
1070         kvm_sync_excp(env, POWERPC_EXCP_DSI,  SPR_BOOKE_IVOR2);
1071         env->spr[SPR_BOOKE_IVOR3] = sregs.u.e.ivor_low[3];
1072         kvm_sync_excp(env, POWERPC_EXCP_ISI,  SPR_BOOKE_IVOR3);
1073         env->spr[SPR_BOOKE_IVOR4] = sregs.u.e.ivor_low[4];
1074         kvm_sync_excp(env, POWERPC_EXCP_EXTERNAL,  SPR_BOOKE_IVOR4);
1075         env->spr[SPR_BOOKE_IVOR5] = sregs.u.e.ivor_low[5];
1076         kvm_sync_excp(env, POWERPC_EXCP_ALIGN,  SPR_BOOKE_IVOR5);
1077         env->spr[SPR_BOOKE_IVOR6] = sregs.u.e.ivor_low[6];
1078         kvm_sync_excp(env, POWERPC_EXCP_PROGRAM,  SPR_BOOKE_IVOR6);
1079         env->spr[SPR_BOOKE_IVOR7] = sregs.u.e.ivor_low[7];
1080         kvm_sync_excp(env, POWERPC_EXCP_FPU,  SPR_BOOKE_IVOR7);
1081         env->spr[SPR_BOOKE_IVOR8] = sregs.u.e.ivor_low[8];
1082         kvm_sync_excp(env, POWERPC_EXCP_SYSCALL,  SPR_BOOKE_IVOR8);
1083         env->spr[SPR_BOOKE_IVOR9] = sregs.u.e.ivor_low[9];
1084         kvm_sync_excp(env, POWERPC_EXCP_APU,  SPR_BOOKE_IVOR9);
1085         env->spr[SPR_BOOKE_IVOR10] = sregs.u.e.ivor_low[10];
1086         kvm_sync_excp(env, POWERPC_EXCP_DECR,  SPR_BOOKE_IVOR10);
1087         env->spr[SPR_BOOKE_IVOR11] = sregs.u.e.ivor_low[11];
1088         kvm_sync_excp(env, POWERPC_EXCP_FIT,  SPR_BOOKE_IVOR11);
1089         env->spr[SPR_BOOKE_IVOR12] = sregs.u.e.ivor_low[12];
1090         kvm_sync_excp(env, POWERPC_EXCP_WDT,  SPR_BOOKE_IVOR12);
1091         env->spr[SPR_BOOKE_IVOR13] = sregs.u.e.ivor_low[13];
1092         kvm_sync_excp(env, POWERPC_EXCP_DTLB,  SPR_BOOKE_IVOR13);
1093         env->spr[SPR_BOOKE_IVOR14] = sregs.u.e.ivor_low[14];
1094         kvm_sync_excp(env, POWERPC_EXCP_ITLB,  SPR_BOOKE_IVOR14);
1095         env->spr[SPR_BOOKE_IVOR15] = sregs.u.e.ivor_low[15];
1096         kvm_sync_excp(env, POWERPC_EXCP_DEBUG,  SPR_BOOKE_IVOR15);
1097 
1098         if (sregs.u.e.features & KVM_SREGS_E_SPE) {
1099             env->spr[SPR_BOOKE_IVOR32] = sregs.u.e.ivor_high[0];
1100             kvm_sync_excp(env, POWERPC_EXCP_SPEU,  SPR_BOOKE_IVOR32);
1101             env->spr[SPR_BOOKE_IVOR33] = sregs.u.e.ivor_high[1];
1102             kvm_sync_excp(env, POWERPC_EXCP_EFPDI,  SPR_BOOKE_IVOR33);
1103             env->spr[SPR_BOOKE_IVOR34] = sregs.u.e.ivor_high[2];
1104             kvm_sync_excp(env, POWERPC_EXCP_EFPRI,  SPR_BOOKE_IVOR34);
1105         }
1106 
1107         if (sregs.u.e.features & KVM_SREGS_E_PM) {
1108             env->spr[SPR_BOOKE_IVOR35] = sregs.u.e.ivor_high[3];
1109             kvm_sync_excp(env, POWERPC_EXCP_EPERFM,  SPR_BOOKE_IVOR35);
1110         }
1111 
1112         if (sregs.u.e.features & KVM_SREGS_E_PC) {
1113             env->spr[SPR_BOOKE_IVOR36] = sregs.u.e.ivor_high[4];
1114             kvm_sync_excp(env, POWERPC_EXCP_DOORI,  SPR_BOOKE_IVOR36);
1115             env->spr[SPR_BOOKE_IVOR37] = sregs.u.e.ivor_high[5];
1116             kvm_sync_excp(env, POWERPC_EXCP_DOORCI, SPR_BOOKE_IVOR37);
1117         }
1118     }
1119 
1120     if (sregs.u.e.features & KVM_SREGS_E_ARCH206_MMU) {
1121         env->spr[SPR_BOOKE_MAS0] = sregs.u.e.mas0;
1122         env->spr[SPR_BOOKE_MAS1] = sregs.u.e.mas1;
1123         env->spr[SPR_BOOKE_MAS2] = sregs.u.e.mas2;
1124         env->spr[SPR_BOOKE_MAS3] = sregs.u.e.mas7_3 & 0xffffffff;
1125         env->spr[SPR_BOOKE_MAS4] = sregs.u.e.mas4;
1126         env->spr[SPR_BOOKE_MAS6] = sregs.u.e.mas6;
1127         env->spr[SPR_BOOKE_MAS7] = sregs.u.e.mas7_3 >> 32;
1128         env->spr[SPR_MMUCFG] = sregs.u.e.mmucfg;
1129         env->spr[SPR_BOOKE_TLB0CFG] = sregs.u.e.tlbcfg[0];
1130         env->spr[SPR_BOOKE_TLB1CFG] = sregs.u.e.tlbcfg[1];
1131     }
1132 
1133     if (sregs.u.e.features & KVM_SREGS_EXP) {
1134         env->spr[SPR_BOOKE_EPR] = sregs.u.e.epr;
1135     }
1136 
1137     if (sregs.u.e.features & KVM_SREGS_E_PD) {
1138         env->spr[SPR_BOOKE_EPLC] = sregs.u.e.eplc;
1139         env->spr[SPR_BOOKE_EPSC] = sregs.u.e.epsc;
1140     }
1141 
1142     if (sregs.u.e.impl_id == KVM_SREGS_E_IMPL_FSL) {
1143         env->spr[SPR_E500_SVR] = sregs.u.e.impl.fsl.svr;
1144         env->spr[SPR_Exxx_MCAR] = sregs.u.e.impl.fsl.mcar;
1145         env->spr[SPR_HID0] = sregs.u.e.impl.fsl.hid0;
1146 
1147         if (sregs.u.e.impl.fsl.features & KVM_SREGS_E_FSL_PIDn) {
1148             env->spr[SPR_BOOKE_PID1] = sregs.u.e.impl.fsl.pid1;
1149             env->spr[SPR_BOOKE_PID2] = sregs.u.e.impl.fsl.pid2;
1150         }
1151     }
1152 
1153     return 0;
1154 }
1155 
1156 static int kvmppc_get_books_sregs(PowerPCCPU *cpu)
1157 {
1158     CPUPPCState *env = &cpu->env;
1159     struct kvm_sregs sregs;
1160     int ret;
1161     int i;
1162 
1163     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1164     if (ret < 0) {
1165         return ret;
1166     }
1167 
1168     if (!cpu->vhyp) {
1169         ppc_store_sdr1(env, sregs.u.s.sdr1);
1170     }
1171 
1172     /* Sync SLB */
1173 #ifdef TARGET_PPC64
1174     /*
1175      * The packed SLB array we get from KVM_GET_SREGS only contains
1176      * information about valid entries. So we flush our internal copy
1177      * to get rid of stale ones, then put all valid SLB entries back
1178      * in.
1179      */
1180     memset(env->slb, 0, sizeof(env->slb));
1181     for (i = 0; i < ARRAY_SIZE(env->slb); i++) {
1182         target_ulong rb = sregs.u.s.ppc64.slb[i].slbe;
1183         target_ulong rs = sregs.u.s.ppc64.slb[i].slbv;
1184         /*
1185          * Only restore valid entries
1186          */
1187         if (rb & SLB_ESID_V) {
1188             ppc_store_slb(cpu, rb & 0xfff, rb & ~0xfffULL, rs);
1189         }
1190     }
1191 #endif
1192 
1193     /* Sync SRs */
1194     for (i = 0; i < 16; i++) {
1195         env->sr[i] = sregs.u.s.ppc32.sr[i];
1196     }
1197 
1198     /* Sync BATs */
1199     for (i = 0; i < 8; i++) {
1200         env->DBAT[0][i] = sregs.u.s.ppc32.dbat[i] & 0xffffffff;
1201         env->DBAT[1][i] = sregs.u.s.ppc32.dbat[i] >> 32;
1202         env->IBAT[0][i] = sregs.u.s.ppc32.ibat[i] & 0xffffffff;
1203         env->IBAT[1][i] = sregs.u.s.ppc32.ibat[i] >> 32;
1204     }
1205 
1206     return 0;
1207 }
1208 
1209 int kvm_arch_get_registers(CPUState *cs)
1210 {
1211     PowerPCCPU *cpu = POWERPC_CPU(cs);
1212     CPUPPCState *env = &cpu->env;
1213     struct kvm_regs regs;
1214     uint32_t cr;
1215     int i, ret;
1216 
1217     ret = kvm_vcpu_ioctl(cs, KVM_GET_REGS, &regs);
1218     if (ret < 0) {
1219         return ret;
1220     }
1221 
1222     cr = regs.cr;
1223     for (i = 7; i >= 0; i--) {
1224         env->crf[i] = cr & 15;
1225         cr >>= 4;
1226     }
1227 
1228     env->ctr = regs.ctr;
1229     env->lr = regs.lr;
1230     cpu_write_xer(env, regs.xer);
1231     env->msr = regs.msr;
1232     env->nip = regs.pc;
1233 
1234     env->spr[SPR_SRR0] = regs.srr0;
1235     env->spr[SPR_SRR1] = regs.srr1;
1236 
1237     env->spr[SPR_SPRG0] = regs.sprg0;
1238     env->spr[SPR_SPRG1] = regs.sprg1;
1239     env->spr[SPR_SPRG2] = regs.sprg2;
1240     env->spr[SPR_SPRG3] = regs.sprg3;
1241     env->spr[SPR_SPRG4] = regs.sprg4;
1242     env->spr[SPR_SPRG5] = regs.sprg5;
1243     env->spr[SPR_SPRG6] = regs.sprg6;
1244     env->spr[SPR_SPRG7] = regs.sprg7;
1245 
1246     env->spr[SPR_BOOKE_PID] = regs.pid;
1247 
1248     for (i = 0; i < 32; i++) {
1249         env->gpr[i] = regs.gpr[i];
1250     }
1251 
1252     kvm_get_fp(cs);
1253 
1254     if (cap_booke_sregs) {
1255         ret = kvmppc_get_booke_sregs(cpu);
1256         if (ret < 0) {
1257             return ret;
1258         }
1259     }
1260 
1261     if (cap_segstate) {
1262         ret = kvmppc_get_books_sregs(cpu);
1263         if (ret < 0) {
1264             return ret;
1265         }
1266     }
1267 
1268     if (cap_hior) {
1269         kvm_get_one_spr(cs, KVM_REG_PPC_HIOR, SPR_HIOR);
1270     }
1271 
1272     if (cap_one_reg) {
1273         int i;
1274 
1275         /*
1276          * We deliberately ignore errors here, for kernels which have
1277          * the ONE_REG calls, but don't support the specific
1278          * registers, there's a reasonable chance things will still
1279          * work, at least until we try to migrate.
1280          */
1281         for (i = 0; i < 1024; i++) {
1282             uint64_t id = env->spr_cb[i].one_reg_id;
1283 
1284             if (id != 0) {
1285                 kvm_get_one_spr(cs, id, i);
1286             }
1287         }
1288 
1289 #ifdef TARGET_PPC64
1290         if (msr_ts) {
1291             for (i = 0; i < ARRAY_SIZE(env->tm_gpr); i++) {
1292                 kvm_get_one_reg(cs, KVM_REG_PPC_TM_GPR(i), &env->tm_gpr[i]);
1293             }
1294             for (i = 0; i < ARRAY_SIZE(env->tm_vsr); i++) {
1295                 kvm_get_one_reg(cs, KVM_REG_PPC_TM_VSR(i), &env->tm_vsr[i]);
1296             }
1297             kvm_get_one_reg(cs, KVM_REG_PPC_TM_CR, &env->tm_cr);
1298             kvm_get_one_reg(cs, KVM_REG_PPC_TM_LR, &env->tm_lr);
1299             kvm_get_one_reg(cs, KVM_REG_PPC_TM_CTR, &env->tm_ctr);
1300             kvm_get_one_reg(cs, KVM_REG_PPC_TM_FPSCR, &env->tm_fpscr);
1301             kvm_get_one_reg(cs, KVM_REG_PPC_TM_AMR, &env->tm_amr);
1302             kvm_get_one_reg(cs, KVM_REG_PPC_TM_PPR, &env->tm_ppr);
1303             kvm_get_one_reg(cs, KVM_REG_PPC_TM_VRSAVE, &env->tm_vrsave);
1304             kvm_get_one_reg(cs, KVM_REG_PPC_TM_VSCR, &env->tm_vscr);
1305             kvm_get_one_reg(cs, KVM_REG_PPC_TM_DSCR, &env->tm_dscr);
1306             kvm_get_one_reg(cs, KVM_REG_PPC_TM_TAR, &env->tm_tar);
1307         }
1308 
1309         if (cap_papr) {
1310             if (kvm_get_vpa(cs) < 0) {
1311                 trace_kvm_failed_get_vpa();
1312             }
1313         }
1314 
1315         kvm_get_one_reg(cs, KVM_REG_PPC_TB_OFFSET, &env->tb_env->tb_offset);
1316 #endif
1317     }
1318 
1319     return 0;
1320 }
1321 
1322 int kvmppc_set_interrupt(PowerPCCPU *cpu, int irq, int level)
1323 {
1324     unsigned virq = level ? KVM_INTERRUPT_SET_LEVEL : KVM_INTERRUPT_UNSET;
1325 
1326     if (irq != PPC_INTERRUPT_EXT) {
1327         return 0;
1328     }
1329 
1330     if (!kvm_enabled() || !cap_interrupt_unset || !cap_interrupt_level) {
1331         return 0;
1332     }
1333 
1334     kvm_vcpu_ioctl(CPU(cpu), KVM_INTERRUPT, &virq);
1335 
1336     return 0;
1337 }
1338 
1339 #if defined(TARGET_PPC64)
1340 #define PPC_INPUT_INT PPC970_INPUT_INT
1341 #else
1342 #define PPC_INPUT_INT PPC6xx_INPUT_INT
1343 #endif
1344 
1345 void kvm_arch_pre_run(CPUState *cs, struct kvm_run *run)
1346 {
1347     PowerPCCPU *cpu = POWERPC_CPU(cs);
1348     CPUPPCState *env = &cpu->env;
1349     int r;
1350     unsigned irq;
1351 
1352     qemu_mutex_lock_iothread();
1353 
1354     /*
1355      * PowerPC QEMU tracks the various core input pins (interrupt,
1356      * critical interrupt, reset, etc) in PPC-specific
1357      * env->irq_input_state.
1358      */
1359     if (!cap_interrupt_level &&
1360         run->ready_for_interrupt_injection &&
1361         (cs->interrupt_request & CPU_INTERRUPT_HARD) &&
1362         (env->irq_input_state & (1 << PPC_INPUT_INT)))
1363     {
1364         /*
1365          * For now KVM disregards the 'irq' argument. However, in the
1366          * future KVM could cache it in-kernel to avoid a heavyweight
1367          * exit when reading the UIC.
1368          */
1369         irq = KVM_INTERRUPT_SET;
1370 
1371         trace_kvm_injected_interrupt(irq);
1372         r = kvm_vcpu_ioctl(cs, KVM_INTERRUPT, &irq);
1373         if (r < 0) {
1374             printf("cpu %d fail inject %x\n", cs->cpu_index, irq);
1375         }
1376 
1377         /* Always wake up soon in case the interrupt was level based */
1378         timer_mod(idle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1379                        (NANOSECONDS_PER_SECOND / 50));
1380     }
1381 
1382     /*
1383      * We don't know if there are more interrupts pending after
1384      * this. However, the guest will return to userspace in the course
1385      * of handling this one anyways, so we will get a chance to
1386      * deliver the rest.
1387      */
1388 
1389     qemu_mutex_unlock_iothread();
1390 }
1391 
1392 MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)
1393 {
1394     return MEMTXATTRS_UNSPECIFIED;
1395 }
1396 
1397 int kvm_arch_process_async_events(CPUState *cs)
1398 {
1399     return cs->halted;
1400 }
1401 
1402 static int kvmppc_handle_halt(PowerPCCPU *cpu)
1403 {
1404     CPUState *cs = CPU(cpu);
1405     CPUPPCState *env = &cpu->env;
1406 
1407     if (!(cs->interrupt_request & CPU_INTERRUPT_HARD) && (msr_ee)) {
1408         cs->halted = 1;
1409         cs->exception_index = EXCP_HLT;
1410     }
1411 
1412     return 0;
1413 }
1414 
1415 /* map dcr access to existing qemu dcr emulation */
1416 static int kvmppc_handle_dcr_read(CPUPPCState *env,
1417                                   uint32_t dcrn, uint32_t *data)
1418 {
1419     if (ppc_dcr_read(env->dcr_env, dcrn, data) < 0) {
1420         fprintf(stderr, "Read to unhandled DCR (0x%x)\n", dcrn);
1421     }
1422 
1423     return 0;
1424 }
1425 
1426 static int kvmppc_handle_dcr_write(CPUPPCState *env,
1427                                    uint32_t dcrn, uint32_t data)
1428 {
1429     if (ppc_dcr_write(env->dcr_env, dcrn, data) < 0) {
1430         fprintf(stderr, "Write to unhandled DCR (0x%x)\n", dcrn);
1431     }
1432 
1433     return 0;
1434 }
1435 
1436 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
1437 {
1438     /* Mixed endian case is not handled */
1439     uint32_t sc = debug_inst_opcode;
1440 
1441     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
1442                             sizeof(sc), 0) ||
1443         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&sc, sizeof(sc), 1)) {
1444         return -EINVAL;
1445     }
1446 
1447     return 0;
1448 }
1449 
1450 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
1451 {
1452     uint32_t sc;
1453 
1454     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&sc, sizeof(sc), 0) ||
1455         sc != debug_inst_opcode ||
1456         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
1457                             sizeof(sc), 1)) {
1458         return -EINVAL;
1459     }
1460 
1461     return 0;
1462 }
1463 
1464 static int find_hw_breakpoint(target_ulong addr, int type)
1465 {
1466     int n;
1467 
1468     assert((nb_hw_breakpoint + nb_hw_watchpoint)
1469            <= ARRAY_SIZE(hw_debug_points));
1470 
1471     for (n = 0; n < nb_hw_breakpoint + nb_hw_watchpoint; n++) {
1472         if (hw_debug_points[n].addr == addr &&
1473              hw_debug_points[n].type == type) {
1474             return n;
1475         }
1476     }
1477 
1478     return -1;
1479 }
1480 
1481 static int find_hw_watchpoint(target_ulong addr, int *flag)
1482 {
1483     int n;
1484 
1485     n = find_hw_breakpoint(addr, GDB_WATCHPOINT_ACCESS);
1486     if (n >= 0) {
1487         *flag = BP_MEM_ACCESS;
1488         return n;
1489     }
1490 
1491     n = find_hw_breakpoint(addr, GDB_WATCHPOINT_WRITE);
1492     if (n >= 0) {
1493         *flag = BP_MEM_WRITE;
1494         return n;
1495     }
1496 
1497     n = find_hw_breakpoint(addr, GDB_WATCHPOINT_READ);
1498     if (n >= 0) {
1499         *flag = BP_MEM_READ;
1500         return n;
1501     }
1502 
1503     return -1;
1504 }
1505 
1506 int kvm_arch_insert_hw_breakpoint(target_ulong addr,
1507                                   target_ulong len, int type)
1508 {
1509     if ((nb_hw_breakpoint + nb_hw_watchpoint) >= ARRAY_SIZE(hw_debug_points)) {
1510         return -ENOBUFS;
1511     }
1512 
1513     hw_debug_points[nb_hw_breakpoint + nb_hw_watchpoint].addr = addr;
1514     hw_debug_points[nb_hw_breakpoint + nb_hw_watchpoint].type = type;
1515 
1516     switch (type) {
1517     case GDB_BREAKPOINT_HW:
1518         if (nb_hw_breakpoint >= max_hw_breakpoint) {
1519             return -ENOBUFS;
1520         }
1521 
1522         if (find_hw_breakpoint(addr, type) >= 0) {
1523             return -EEXIST;
1524         }
1525 
1526         nb_hw_breakpoint++;
1527         break;
1528 
1529     case GDB_WATCHPOINT_WRITE:
1530     case GDB_WATCHPOINT_READ:
1531     case GDB_WATCHPOINT_ACCESS:
1532         if (nb_hw_watchpoint >= max_hw_watchpoint) {
1533             return -ENOBUFS;
1534         }
1535 
1536         if (find_hw_breakpoint(addr, type) >= 0) {
1537             return -EEXIST;
1538         }
1539 
1540         nb_hw_watchpoint++;
1541         break;
1542 
1543     default:
1544         return -ENOSYS;
1545     }
1546 
1547     return 0;
1548 }
1549 
1550 int kvm_arch_remove_hw_breakpoint(target_ulong addr,
1551                                   target_ulong len, int type)
1552 {
1553     int n;
1554 
1555     n = find_hw_breakpoint(addr, type);
1556     if (n < 0) {
1557         return -ENOENT;
1558     }
1559 
1560     switch (type) {
1561     case GDB_BREAKPOINT_HW:
1562         nb_hw_breakpoint--;
1563         break;
1564 
1565     case GDB_WATCHPOINT_WRITE:
1566     case GDB_WATCHPOINT_READ:
1567     case GDB_WATCHPOINT_ACCESS:
1568         nb_hw_watchpoint--;
1569         break;
1570 
1571     default:
1572         return -ENOSYS;
1573     }
1574     hw_debug_points[n] = hw_debug_points[nb_hw_breakpoint + nb_hw_watchpoint];
1575 
1576     return 0;
1577 }
1578 
1579 void kvm_arch_remove_all_hw_breakpoints(void)
1580 {
1581     nb_hw_breakpoint = nb_hw_watchpoint = 0;
1582 }
1583 
1584 void kvm_arch_update_guest_debug(CPUState *cs, struct kvm_guest_debug *dbg)
1585 {
1586     int n;
1587 
1588     /* Software Breakpoint updates */
1589     if (kvm_sw_breakpoints_active(cs)) {
1590         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
1591     }
1592 
1593     assert((nb_hw_breakpoint + nb_hw_watchpoint)
1594            <= ARRAY_SIZE(hw_debug_points));
1595     assert((nb_hw_breakpoint + nb_hw_watchpoint) <= ARRAY_SIZE(dbg->arch.bp));
1596 
1597     if (nb_hw_breakpoint + nb_hw_watchpoint > 0) {
1598         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
1599         memset(dbg->arch.bp, 0, sizeof(dbg->arch.bp));
1600         for (n = 0; n < nb_hw_breakpoint + nb_hw_watchpoint; n++) {
1601             switch (hw_debug_points[n].type) {
1602             case GDB_BREAKPOINT_HW:
1603                 dbg->arch.bp[n].type = KVMPPC_DEBUG_BREAKPOINT;
1604                 break;
1605             case GDB_WATCHPOINT_WRITE:
1606                 dbg->arch.bp[n].type = KVMPPC_DEBUG_WATCH_WRITE;
1607                 break;
1608             case GDB_WATCHPOINT_READ:
1609                 dbg->arch.bp[n].type = KVMPPC_DEBUG_WATCH_READ;
1610                 break;
1611             case GDB_WATCHPOINT_ACCESS:
1612                 dbg->arch.bp[n].type = KVMPPC_DEBUG_WATCH_WRITE |
1613                                         KVMPPC_DEBUG_WATCH_READ;
1614                 break;
1615             default:
1616                 cpu_abort(cs, "Unsupported breakpoint type\n");
1617             }
1618             dbg->arch.bp[n].addr = hw_debug_points[n].addr;
1619         }
1620     }
1621 }
1622 
1623 static int kvm_handle_hw_breakpoint(CPUState *cs,
1624                                     struct kvm_debug_exit_arch *arch_info)
1625 {
1626     int handle = 0;
1627     int n;
1628     int flag = 0;
1629 
1630     if (nb_hw_breakpoint + nb_hw_watchpoint > 0) {
1631         if (arch_info->status & KVMPPC_DEBUG_BREAKPOINT) {
1632             n = find_hw_breakpoint(arch_info->address, GDB_BREAKPOINT_HW);
1633             if (n >= 0) {
1634                 handle = 1;
1635             }
1636         } else if (arch_info->status & (KVMPPC_DEBUG_WATCH_READ |
1637                                         KVMPPC_DEBUG_WATCH_WRITE)) {
1638             n = find_hw_watchpoint(arch_info->address,  &flag);
1639             if (n >= 0) {
1640                 handle = 1;
1641                 cs->watchpoint_hit = &hw_watchpoint;
1642                 hw_watchpoint.vaddr = hw_debug_points[n].addr;
1643                 hw_watchpoint.flags = flag;
1644             }
1645         }
1646     }
1647     return handle;
1648 }
1649 
1650 static int kvm_handle_singlestep(void)
1651 {
1652     return 1;
1653 }
1654 
1655 static int kvm_handle_sw_breakpoint(void)
1656 {
1657     return 1;
1658 }
1659 
1660 static int kvm_handle_debug(PowerPCCPU *cpu, struct kvm_run *run)
1661 {
1662     CPUState *cs = CPU(cpu);
1663     CPUPPCState *env = &cpu->env;
1664     struct kvm_debug_exit_arch *arch_info = &run->debug.arch;
1665 
1666     if (cs->singlestep_enabled) {
1667         return kvm_handle_singlestep();
1668     }
1669 
1670     if (arch_info->status) {
1671         return kvm_handle_hw_breakpoint(cs, arch_info);
1672     }
1673 
1674     if (kvm_find_sw_breakpoint(cs, arch_info->address)) {
1675         return kvm_handle_sw_breakpoint();
1676     }
1677 
1678     /*
1679      * QEMU is not able to handle debug exception, so inject
1680      * program exception to guest;
1681      * Yes program exception NOT debug exception !!
1682      * When QEMU is using debug resources then debug exception must
1683      * be always set. To achieve this we set MSR_DE and also set
1684      * MSRP_DEP so guest cannot change MSR_DE.
1685      * When emulating debug resource for guest we want guest
1686      * to control MSR_DE (enable/disable debug interrupt on need).
1687      * Supporting both configurations are NOT possible.
1688      * So the result is that we cannot share debug resources
1689      * between QEMU and Guest on BOOKE architecture.
1690      * In the current design QEMU gets the priority over guest,
1691      * this means that if QEMU is using debug resources then guest
1692      * cannot use them;
1693      * For software breakpoint QEMU uses a privileged instruction;
1694      * So there cannot be any reason that we are here for guest
1695      * set debug exception, only possibility is guest executed a
1696      * privileged / illegal instruction and that's why we are
1697      * injecting a program interrupt.
1698      */
1699     cpu_synchronize_state(cs);
1700     /*
1701      * env->nip is PC, so increment this by 4 to use
1702      * ppc_cpu_do_interrupt(), which set srr0 = env->nip - 4.
1703      */
1704     env->nip += 4;
1705     cs->exception_index = POWERPC_EXCP_PROGRAM;
1706     env->error_code = POWERPC_EXCP_INVAL;
1707     ppc_cpu_do_interrupt(cs);
1708 
1709     return 0;
1710 }
1711 
1712 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
1713 {
1714     PowerPCCPU *cpu = POWERPC_CPU(cs);
1715     CPUPPCState *env = &cpu->env;
1716     int ret;
1717 
1718     qemu_mutex_lock_iothread();
1719 
1720     switch (run->exit_reason) {
1721     case KVM_EXIT_DCR:
1722         if (run->dcr.is_write) {
1723             trace_kvm_handle_dcr_write();
1724             ret = kvmppc_handle_dcr_write(env, run->dcr.dcrn, run->dcr.data);
1725         } else {
1726             trace_kvm_handle_dcr_read();
1727             ret = kvmppc_handle_dcr_read(env, run->dcr.dcrn, &run->dcr.data);
1728         }
1729         break;
1730     case KVM_EXIT_HLT:
1731         trace_kvm_handle_halt();
1732         ret = kvmppc_handle_halt(cpu);
1733         break;
1734 #if defined(TARGET_PPC64)
1735     case KVM_EXIT_PAPR_HCALL:
1736         trace_kvm_handle_papr_hcall();
1737         run->papr_hcall.ret = spapr_hypercall(cpu,
1738                                               run->papr_hcall.nr,
1739                                               run->papr_hcall.args);
1740         ret = 0;
1741         break;
1742 #endif
1743     case KVM_EXIT_EPR:
1744         trace_kvm_handle_epr();
1745         run->epr.epr = ldl_phys(cs->as, env->mpic_iack);
1746         ret = 0;
1747         break;
1748     case KVM_EXIT_WATCHDOG:
1749         trace_kvm_handle_watchdog_expiry();
1750         watchdog_perform_action();
1751         ret = 0;
1752         break;
1753 
1754     case KVM_EXIT_DEBUG:
1755         trace_kvm_handle_debug_exception();
1756         if (kvm_handle_debug(cpu, run)) {
1757             ret = EXCP_DEBUG;
1758             break;
1759         }
1760         /* re-enter, this exception was guest-internal */
1761         ret = 0;
1762         break;
1763 
1764     default:
1765         fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
1766         ret = -1;
1767         break;
1768     }
1769 
1770     qemu_mutex_unlock_iothread();
1771     return ret;
1772 }
1773 
1774 int kvmppc_or_tsr_bits(PowerPCCPU *cpu, uint32_t tsr_bits)
1775 {
1776     CPUState *cs = CPU(cpu);
1777     uint32_t bits = tsr_bits;
1778     struct kvm_one_reg reg = {
1779         .id = KVM_REG_PPC_OR_TSR,
1780         .addr = (uintptr_t) &bits,
1781     };
1782 
1783     return kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
1784 }
1785 
1786 int kvmppc_clear_tsr_bits(PowerPCCPU *cpu, uint32_t tsr_bits)
1787 {
1788 
1789     CPUState *cs = CPU(cpu);
1790     uint32_t bits = tsr_bits;
1791     struct kvm_one_reg reg = {
1792         .id = KVM_REG_PPC_CLEAR_TSR,
1793         .addr = (uintptr_t) &bits,
1794     };
1795 
1796     return kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
1797 }
1798 
1799 int kvmppc_set_tcr(PowerPCCPU *cpu)
1800 {
1801     CPUState *cs = CPU(cpu);
1802     CPUPPCState *env = &cpu->env;
1803     uint32_t tcr = env->spr[SPR_BOOKE_TCR];
1804 
1805     struct kvm_one_reg reg = {
1806         .id = KVM_REG_PPC_TCR,
1807         .addr = (uintptr_t) &tcr,
1808     };
1809 
1810     return kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
1811 }
1812 
1813 int kvmppc_booke_watchdog_enable(PowerPCCPU *cpu)
1814 {
1815     CPUState *cs = CPU(cpu);
1816     int ret;
1817 
1818     if (!kvm_enabled()) {
1819         return -1;
1820     }
1821 
1822     if (!cap_ppc_watchdog) {
1823         printf("warning: KVM does not support watchdog");
1824         return -1;
1825     }
1826 
1827     ret = kvm_vcpu_enable_cap(cs, KVM_CAP_PPC_BOOKE_WATCHDOG, 0);
1828     if (ret < 0) {
1829         fprintf(stderr, "%s: couldn't enable KVM_CAP_PPC_BOOKE_WATCHDOG: %s\n",
1830                 __func__, strerror(-ret));
1831         return ret;
1832     }
1833 
1834     return ret;
1835 }
1836 
1837 static int read_cpuinfo(const char *field, char *value, int len)
1838 {
1839     FILE *f;
1840     int ret = -1;
1841     int field_len = strlen(field);
1842     char line[512];
1843 
1844     f = fopen("/proc/cpuinfo", "r");
1845     if (!f) {
1846         return -1;
1847     }
1848 
1849     do {
1850         if (!fgets(line, sizeof(line), f)) {
1851             break;
1852         }
1853         if (!strncmp(line, field, field_len)) {
1854             pstrcpy(value, len, line);
1855             ret = 0;
1856             break;
1857         }
1858     } while (*line);
1859 
1860     fclose(f);
1861 
1862     return ret;
1863 }
1864 
1865 uint32_t kvmppc_get_tbfreq(void)
1866 {
1867     char line[512];
1868     char *ns;
1869     uint32_t retval = NANOSECONDS_PER_SECOND;
1870 
1871     if (read_cpuinfo("timebase", line, sizeof(line))) {
1872         return retval;
1873     }
1874 
1875     ns = strchr(line, ':');
1876     if (!ns) {
1877         return retval;
1878     }
1879 
1880     ns++;
1881 
1882     return atoi(ns);
1883 }
1884 
1885 bool kvmppc_get_host_serial(char **value)
1886 {
1887     return g_file_get_contents("/proc/device-tree/system-id", value, NULL,
1888                                NULL);
1889 }
1890 
1891 bool kvmppc_get_host_model(char **value)
1892 {
1893     return g_file_get_contents("/proc/device-tree/model", value, NULL, NULL);
1894 }
1895 
1896 /* Try to find a device tree node for a CPU with clock-frequency property */
1897 static int kvmppc_find_cpu_dt(char *buf, int buf_len)
1898 {
1899     struct dirent *dirp;
1900     DIR *dp;
1901 
1902     dp = opendir(PROC_DEVTREE_CPU);
1903     if (!dp) {
1904         printf("Can't open directory " PROC_DEVTREE_CPU "\n");
1905         return -1;
1906     }
1907 
1908     buf[0] = '\0';
1909     while ((dirp = readdir(dp)) != NULL) {
1910         FILE *f;
1911         snprintf(buf, buf_len, "%s%s/clock-frequency", PROC_DEVTREE_CPU,
1912                  dirp->d_name);
1913         f = fopen(buf, "r");
1914         if (f) {
1915             snprintf(buf, buf_len, "%s%s", PROC_DEVTREE_CPU, dirp->d_name);
1916             fclose(f);
1917             break;
1918         }
1919         buf[0] = '\0';
1920     }
1921     closedir(dp);
1922     if (buf[0] == '\0') {
1923         printf("Unknown host!\n");
1924         return -1;
1925     }
1926 
1927     return 0;
1928 }
1929 
1930 static uint64_t kvmppc_read_int_dt(const char *filename)
1931 {
1932     union {
1933         uint32_t v32;
1934         uint64_t v64;
1935     } u;
1936     FILE *f;
1937     int len;
1938 
1939     f = fopen(filename, "rb");
1940     if (!f) {
1941         return -1;
1942     }
1943 
1944     len = fread(&u, 1, sizeof(u), f);
1945     fclose(f);
1946     switch (len) {
1947     case 4:
1948         /* property is a 32-bit quantity */
1949         return be32_to_cpu(u.v32);
1950     case 8:
1951         return be64_to_cpu(u.v64);
1952     }
1953 
1954     return 0;
1955 }
1956 
1957 /*
1958  * Read a CPU node property from the host device tree that's a single
1959  * integer (32-bit or 64-bit).  Returns 0 if anything goes wrong
1960  * (can't find or open the property, or doesn't understand the format)
1961  */
1962 static uint64_t kvmppc_read_int_cpu_dt(const char *propname)
1963 {
1964     char buf[PATH_MAX], *tmp;
1965     uint64_t val;
1966 
1967     if (kvmppc_find_cpu_dt(buf, sizeof(buf))) {
1968         return -1;
1969     }
1970 
1971     tmp = g_strdup_printf("%s/%s", buf, propname);
1972     val = kvmppc_read_int_dt(tmp);
1973     g_free(tmp);
1974 
1975     return val;
1976 }
1977 
1978 uint64_t kvmppc_get_clockfreq(void)
1979 {
1980     return kvmppc_read_int_cpu_dt("clock-frequency");
1981 }
1982 
1983 static int kvmppc_get_dec_bits(void)
1984 {
1985     int nr_bits = kvmppc_read_int_cpu_dt("ibm,dec-bits");
1986 
1987     if (nr_bits > 0) {
1988         return nr_bits;
1989     }
1990     return 0;
1991 }
1992 
1993 static int kvmppc_get_pvinfo(CPUPPCState *env, struct kvm_ppc_pvinfo *pvinfo)
1994 {
1995     CPUState *cs = env_cpu(env);
1996 
1997     if (kvm_vm_check_extension(cs->kvm_state, KVM_CAP_PPC_GET_PVINFO) &&
1998         !kvm_vm_ioctl(cs->kvm_state, KVM_PPC_GET_PVINFO, pvinfo)) {
1999         return 0;
2000     }
2001 
2002     return 1;
2003 }
2004 
2005 int kvmppc_get_hasidle(CPUPPCState *env)
2006 {
2007     struct kvm_ppc_pvinfo pvinfo;
2008 
2009     if (!kvmppc_get_pvinfo(env, &pvinfo) &&
2010         (pvinfo.flags & KVM_PPC_PVINFO_FLAGS_EV_IDLE)) {
2011         return 1;
2012     }
2013 
2014     return 0;
2015 }
2016 
2017 int kvmppc_get_hypercall(CPUPPCState *env, uint8_t *buf, int buf_len)
2018 {
2019     uint32_t *hc = (uint32_t *)buf;
2020     struct kvm_ppc_pvinfo pvinfo;
2021 
2022     if (!kvmppc_get_pvinfo(env, &pvinfo)) {
2023         memcpy(buf, pvinfo.hcall, buf_len);
2024         return 0;
2025     }
2026 
2027     /*
2028      * Fallback to always fail hypercalls regardless of endianness:
2029      *
2030      *     tdi 0,r0,72 (becomes b .+8 in wrong endian, nop in good endian)
2031      *     li r3, -1
2032      *     b .+8       (becomes nop in wrong endian)
2033      *     bswap32(li r3, -1)
2034      */
2035 
2036     hc[0] = cpu_to_be32(0x08000048);
2037     hc[1] = cpu_to_be32(0x3860ffff);
2038     hc[2] = cpu_to_be32(0x48000008);
2039     hc[3] = cpu_to_be32(bswap32(0x3860ffff));
2040 
2041     return 1;
2042 }
2043 
2044 static inline int kvmppc_enable_hcall(KVMState *s, target_ulong hcall)
2045 {
2046     return kvm_vm_enable_cap(s, KVM_CAP_PPC_ENABLE_HCALL, 0, hcall, 1);
2047 }
2048 
2049 void kvmppc_enable_logical_ci_hcalls(void)
2050 {
2051     /*
2052      * FIXME: it would be nice if we could detect the cases where
2053      * we're using a device which requires the in kernel
2054      * implementation of these hcalls, but the kernel lacks them and
2055      * produce a warning.
2056      */
2057     kvmppc_enable_hcall(kvm_state, H_LOGICAL_CI_LOAD);
2058     kvmppc_enable_hcall(kvm_state, H_LOGICAL_CI_STORE);
2059 }
2060 
2061 void kvmppc_enable_set_mode_hcall(void)
2062 {
2063     kvmppc_enable_hcall(kvm_state, H_SET_MODE);
2064 }
2065 
2066 void kvmppc_enable_clear_ref_mod_hcalls(void)
2067 {
2068     kvmppc_enable_hcall(kvm_state, H_CLEAR_REF);
2069     kvmppc_enable_hcall(kvm_state, H_CLEAR_MOD);
2070 }
2071 
2072 void kvmppc_enable_h_page_init(void)
2073 {
2074     kvmppc_enable_hcall(kvm_state, H_PAGE_INIT);
2075 }
2076 
2077 void kvmppc_set_papr(PowerPCCPU *cpu)
2078 {
2079     CPUState *cs = CPU(cpu);
2080     int ret;
2081 
2082     if (!kvm_enabled()) {
2083         return;
2084     }
2085 
2086     ret = kvm_vcpu_enable_cap(cs, KVM_CAP_PPC_PAPR, 0);
2087     if (ret) {
2088         error_report("This vCPU type or KVM version does not support PAPR");
2089         exit(1);
2090     }
2091 
2092     /*
2093      * Update the capability flag so we sync the right information
2094      * with kvm
2095      */
2096     cap_papr = 1;
2097 }
2098 
2099 int kvmppc_set_compat(PowerPCCPU *cpu, uint32_t compat_pvr)
2100 {
2101     return kvm_set_one_reg(CPU(cpu), KVM_REG_PPC_ARCH_COMPAT, &compat_pvr);
2102 }
2103 
2104 void kvmppc_set_mpic_proxy(PowerPCCPU *cpu, int mpic_proxy)
2105 {
2106     CPUState *cs = CPU(cpu);
2107     int ret;
2108 
2109     ret = kvm_vcpu_enable_cap(cs, KVM_CAP_PPC_EPR, 0, mpic_proxy);
2110     if (ret && mpic_proxy) {
2111         error_report("This KVM version does not support EPR");
2112         exit(1);
2113     }
2114 }
2115 
2116 int kvmppc_smt_threads(void)
2117 {
2118     return cap_ppc_smt ? cap_ppc_smt : 1;
2119 }
2120 
2121 int kvmppc_set_smt_threads(int smt)
2122 {
2123     int ret;
2124 
2125     ret = kvm_vm_enable_cap(kvm_state, KVM_CAP_PPC_SMT, 0, smt, 0);
2126     if (!ret) {
2127         cap_ppc_smt = smt;
2128     }
2129     return ret;
2130 }
2131 
2132 void kvmppc_hint_smt_possible(Error **errp)
2133 {
2134     int i;
2135     GString *g;
2136     char *s;
2137 
2138     assert(kvm_enabled());
2139     if (cap_ppc_smt_possible) {
2140         g = g_string_new("Available VSMT modes:");
2141         for (i = 63; i >= 0; i--) {
2142             if ((1UL << i) & cap_ppc_smt_possible) {
2143                 g_string_append_printf(g, " %lu", (1UL << i));
2144             }
2145         }
2146         s = g_string_free(g, false);
2147         error_append_hint(errp, "%s.\n", s);
2148         g_free(s);
2149     } else {
2150         error_append_hint(errp,
2151                           "This KVM seems to be too old to support VSMT.\n");
2152     }
2153 }
2154 
2155 
2156 #ifdef TARGET_PPC64
2157 uint64_t kvmppc_rma_size(uint64_t current_size, unsigned int hash_shift)
2158 {
2159     struct kvm_ppc_smmu_info info;
2160     long rampagesize, best_page_shift;
2161     int i;
2162 
2163     /*
2164      * Find the largest hardware supported page size that's less than
2165      * or equal to the (logical) backing page size of guest RAM
2166      */
2167     kvm_get_smmu_info(&info, &error_fatal);
2168     rampagesize = qemu_minrampagesize();
2169     best_page_shift = 0;
2170 
2171     for (i = 0; i < KVM_PPC_PAGE_SIZES_MAX_SZ; i++) {
2172         struct kvm_ppc_one_seg_page_size *sps = &info.sps[i];
2173 
2174         if (!sps->page_shift) {
2175             continue;
2176         }
2177 
2178         if ((sps->page_shift > best_page_shift)
2179             && ((1UL << sps->page_shift) <= rampagesize)) {
2180             best_page_shift = sps->page_shift;
2181         }
2182     }
2183 
2184     return MIN(current_size,
2185                1ULL << (best_page_shift + hash_shift - 7));
2186 }
2187 #endif
2188 
2189 bool kvmppc_spapr_use_multitce(void)
2190 {
2191     return cap_spapr_multitce;
2192 }
2193 
2194 int kvmppc_spapr_enable_inkernel_multitce(void)
2195 {
2196     int ret;
2197 
2198     ret = kvm_vm_enable_cap(kvm_state, KVM_CAP_PPC_ENABLE_HCALL, 0,
2199                             H_PUT_TCE_INDIRECT, 1);
2200     if (!ret) {
2201         ret = kvm_vm_enable_cap(kvm_state, KVM_CAP_PPC_ENABLE_HCALL, 0,
2202                                 H_STUFF_TCE, 1);
2203     }
2204 
2205     return ret;
2206 }
2207 
2208 void *kvmppc_create_spapr_tce(uint32_t liobn, uint32_t page_shift,
2209                               uint64_t bus_offset, uint32_t nb_table,
2210                               int *pfd, bool need_vfio)
2211 {
2212     long len;
2213     int fd;
2214     void *table;
2215 
2216     /*
2217      * Must set fd to -1 so we don't try to munmap when called for
2218      * destroying the table, which the upper layers -will- do
2219      */
2220     *pfd = -1;
2221     if (!cap_spapr_tce || (need_vfio && !cap_spapr_vfio)) {
2222         return NULL;
2223     }
2224 
2225     if (cap_spapr_tce_64) {
2226         struct kvm_create_spapr_tce_64 args = {
2227             .liobn = liobn,
2228             .page_shift = page_shift,
2229             .offset = bus_offset >> page_shift,
2230             .size = nb_table,
2231             .flags = 0
2232         };
2233         fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_SPAPR_TCE_64, &args);
2234         if (fd < 0) {
2235             fprintf(stderr,
2236                     "KVM: Failed to create TCE64 table for liobn 0x%x\n",
2237                     liobn);
2238             return NULL;
2239         }
2240     } else if (cap_spapr_tce) {
2241         uint64_t window_size = (uint64_t) nb_table << page_shift;
2242         struct kvm_create_spapr_tce args = {
2243             .liobn = liobn,
2244             .window_size = window_size,
2245         };
2246         if ((window_size != args.window_size) || bus_offset) {
2247             return NULL;
2248         }
2249         fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_SPAPR_TCE, &args);
2250         if (fd < 0) {
2251             fprintf(stderr, "KVM: Failed to create TCE table for liobn 0x%x\n",
2252                     liobn);
2253             return NULL;
2254         }
2255     } else {
2256         return NULL;
2257     }
2258 
2259     len = nb_table * sizeof(uint64_t);
2260     /* FIXME: round this up to page size */
2261 
2262     table = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2263     if (table == MAP_FAILED) {
2264         fprintf(stderr, "KVM: Failed to map TCE table for liobn 0x%x\n",
2265                 liobn);
2266         close(fd);
2267         return NULL;
2268     }
2269 
2270     *pfd = fd;
2271     return table;
2272 }
2273 
2274 int kvmppc_remove_spapr_tce(void *table, int fd, uint32_t nb_table)
2275 {
2276     long len;
2277 
2278     if (fd < 0) {
2279         return -1;
2280     }
2281 
2282     len = nb_table * sizeof(uint64_t);
2283     if ((munmap(table, len) < 0) ||
2284         (close(fd) < 0)) {
2285         fprintf(stderr, "KVM: Unexpected error removing TCE table: %s",
2286                 strerror(errno));
2287         /* Leak the table */
2288     }
2289 
2290     return 0;
2291 }
2292 
2293 int kvmppc_reset_htab(int shift_hint)
2294 {
2295     uint32_t shift = shift_hint;
2296 
2297     if (!kvm_enabled()) {
2298         /* Full emulation, tell caller to allocate htab itself */
2299         return 0;
2300     }
2301     if (kvm_vm_check_extension(kvm_state, KVM_CAP_PPC_ALLOC_HTAB)) {
2302         int ret;
2303         ret = kvm_vm_ioctl(kvm_state, KVM_PPC_ALLOCATE_HTAB, &shift);
2304         if (ret == -ENOTTY) {
2305             /*
2306              * At least some versions of PR KVM advertise the
2307              * capability, but don't implement the ioctl().  Oops.
2308              * Return 0 so that we allocate the htab in qemu, as is
2309              * correct for PR.
2310              */
2311             return 0;
2312         } else if (ret < 0) {
2313             return ret;
2314         }
2315         return shift;
2316     }
2317 
2318     /*
2319      * We have a kernel that predates the htab reset calls.  For PR
2320      * KVM, we need to allocate the htab ourselves, for an HV KVM of
2321      * this era, it has allocated a 16MB fixed size hash table
2322      * already.
2323      */
2324     if (kvmppc_is_pr(kvm_state)) {
2325         /* PR - tell caller to allocate htab */
2326         return 0;
2327     } else {
2328         /* HV - assume 16MB kernel allocated htab */
2329         return 24;
2330     }
2331 }
2332 
2333 static inline uint32_t mfpvr(void)
2334 {
2335     uint32_t pvr;
2336 
2337     asm ("mfpvr %0"
2338          : "=r"(pvr));
2339     return pvr;
2340 }
2341 
2342 static void alter_insns(uint64_t *word, uint64_t flags, bool on)
2343 {
2344     if (on) {
2345         *word |= flags;
2346     } else {
2347         *word &= ~flags;
2348     }
2349 }
2350 
2351 static void kvmppc_host_cpu_class_init(ObjectClass *oc, void *data)
2352 {
2353     PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);
2354     uint32_t dcache_size = kvmppc_read_int_cpu_dt("d-cache-size");
2355     uint32_t icache_size = kvmppc_read_int_cpu_dt("i-cache-size");
2356 
2357     /* Now fix up the class with information we can query from the host */
2358     pcc->pvr = mfpvr();
2359 
2360     alter_insns(&pcc->insns_flags, PPC_ALTIVEC,
2361                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_ALTIVEC);
2362     alter_insns(&pcc->insns_flags2, PPC2_VSX,
2363                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_VSX);
2364     alter_insns(&pcc->insns_flags2, PPC2_DFP,
2365                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_DFP);
2366 
2367     if (dcache_size != -1) {
2368         pcc->l1_dcache_size = dcache_size;
2369     }
2370 
2371     if (icache_size != -1) {
2372         pcc->l1_icache_size = icache_size;
2373     }
2374 
2375 #if defined(TARGET_PPC64)
2376     pcc->radix_page_info = kvm_get_radix_page_info();
2377 
2378     if ((pcc->pvr & 0xffffff00) == CPU_POWERPC_POWER9_DD1) {
2379         /*
2380          * POWER9 DD1 has some bugs which make it not really ISA 3.00
2381          * compliant.  More importantly, advertising ISA 3.00
2382          * architected mode may prevent guests from activating
2383          * necessary DD1 workarounds.
2384          */
2385         pcc->pcr_supported &= ~(PCR_COMPAT_3_00 | PCR_COMPAT_2_07
2386                                 | PCR_COMPAT_2_06 | PCR_COMPAT_2_05);
2387     }
2388 #endif /* defined(TARGET_PPC64) */
2389 }
2390 
2391 bool kvmppc_has_cap_epr(void)
2392 {
2393     return cap_epr;
2394 }
2395 
2396 bool kvmppc_has_cap_fixup_hcalls(void)
2397 {
2398     return cap_fixup_hcalls;
2399 }
2400 
2401 bool kvmppc_has_cap_htm(void)
2402 {
2403     return cap_htm;
2404 }
2405 
2406 bool kvmppc_has_cap_mmu_radix(void)
2407 {
2408     return cap_mmu_radix;
2409 }
2410 
2411 bool kvmppc_has_cap_mmu_hash_v3(void)
2412 {
2413     return cap_mmu_hash_v3;
2414 }
2415 
2416 static bool kvmppc_power8_host(void)
2417 {
2418     bool ret = false;
2419 #ifdef TARGET_PPC64
2420     {
2421         uint32_t base_pvr = CPU_POWERPC_POWER_SERVER_MASK & mfpvr();
2422         ret = (base_pvr == CPU_POWERPC_POWER8E_BASE) ||
2423               (base_pvr == CPU_POWERPC_POWER8NVL_BASE) ||
2424               (base_pvr == CPU_POWERPC_POWER8_BASE);
2425     }
2426 #endif /* TARGET_PPC64 */
2427     return ret;
2428 }
2429 
2430 static int parse_cap_ppc_safe_cache(struct kvm_ppc_cpu_char c)
2431 {
2432     bool l1d_thread_priv_req = !kvmppc_power8_host();
2433 
2434     if (~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_L1D_FLUSH_PR) {
2435         return 2;
2436     } else if ((!l1d_thread_priv_req ||
2437                 c.character & c.character_mask & H_CPU_CHAR_L1D_THREAD_PRIV) &&
2438                (c.character & c.character_mask
2439                 & (H_CPU_CHAR_L1D_FLUSH_ORI30 | H_CPU_CHAR_L1D_FLUSH_TRIG2))) {
2440         return 1;
2441     }
2442 
2443     return 0;
2444 }
2445 
2446 static int parse_cap_ppc_safe_bounds_check(struct kvm_ppc_cpu_char c)
2447 {
2448     if (~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_BNDS_CHK_SPEC_BAR) {
2449         return 2;
2450     } else if (c.character & c.character_mask & H_CPU_CHAR_SPEC_BAR_ORI31) {
2451         return 1;
2452     }
2453 
2454     return 0;
2455 }
2456 
2457 static int parse_cap_ppc_safe_indirect_branch(struct kvm_ppc_cpu_char c)
2458 {
2459     if ((~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_FLUSH_COUNT_CACHE) &&
2460         (~c.character & c.character_mask & H_CPU_CHAR_CACHE_COUNT_DIS) &&
2461         (~c.character & c.character_mask & H_CPU_CHAR_BCCTRL_SERIALISED)) {
2462         return SPAPR_CAP_FIXED_NA;
2463     } else if (c.behaviour & c.behaviour_mask & H_CPU_BEHAV_FLUSH_COUNT_CACHE) {
2464         return SPAPR_CAP_WORKAROUND;
2465     } else if (c.character & c.character_mask & H_CPU_CHAR_CACHE_COUNT_DIS) {
2466         return  SPAPR_CAP_FIXED_CCD;
2467     } else if (c.character & c.character_mask & H_CPU_CHAR_BCCTRL_SERIALISED) {
2468         return SPAPR_CAP_FIXED_IBS;
2469     }
2470 
2471     return 0;
2472 }
2473 
2474 static int parse_cap_ppc_count_cache_flush_assist(struct kvm_ppc_cpu_char c)
2475 {
2476     if (c.character & c.character_mask & H_CPU_CHAR_BCCTR_FLUSH_ASSIST) {
2477         return 1;
2478     }
2479     return 0;
2480 }
2481 
2482 bool kvmppc_has_cap_xive(void)
2483 {
2484     return cap_xive;
2485 }
2486 
2487 static void kvmppc_get_cpu_characteristics(KVMState *s)
2488 {
2489     struct kvm_ppc_cpu_char c;
2490     int ret;
2491 
2492     /* Assume broken */
2493     cap_ppc_safe_cache = 0;
2494     cap_ppc_safe_bounds_check = 0;
2495     cap_ppc_safe_indirect_branch = 0;
2496 
2497     ret = kvm_vm_check_extension(s, KVM_CAP_PPC_GET_CPU_CHAR);
2498     if (!ret) {
2499         return;
2500     }
2501     ret = kvm_vm_ioctl(s, KVM_PPC_GET_CPU_CHAR, &c);
2502     if (ret < 0) {
2503         return;
2504     }
2505 
2506     cap_ppc_safe_cache = parse_cap_ppc_safe_cache(c);
2507     cap_ppc_safe_bounds_check = parse_cap_ppc_safe_bounds_check(c);
2508     cap_ppc_safe_indirect_branch = parse_cap_ppc_safe_indirect_branch(c);
2509     cap_ppc_count_cache_flush_assist =
2510         parse_cap_ppc_count_cache_flush_assist(c);
2511 }
2512 
2513 int kvmppc_get_cap_safe_cache(void)
2514 {
2515     return cap_ppc_safe_cache;
2516 }
2517 
2518 int kvmppc_get_cap_safe_bounds_check(void)
2519 {
2520     return cap_ppc_safe_bounds_check;
2521 }
2522 
2523 int kvmppc_get_cap_safe_indirect_branch(void)
2524 {
2525     return cap_ppc_safe_indirect_branch;
2526 }
2527 
2528 int kvmppc_get_cap_count_cache_flush_assist(void)
2529 {
2530     return cap_ppc_count_cache_flush_assist;
2531 }
2532 
2533 bool kvmppc_has_cap_nested_kvm_hv(void)
2534 {
2535     return !!cap_ppc_nested_kvm_hv;
2536 }
2537 
2538 int kvmppc_set_cap_nested_kvm_hv(int enable)
2539 {
2540     return kvm_vm_enable_cap(kvm_state, KVM_CAP_PPC_NESTED_HV, 0, enable);
2541 }
2542 
2543 bool kvmppc_has_cap_spapr_vfio(void)
2544 {
2545     return cap_spapr_vfio;
2546 }
2547 
2548 int kvmppc_get_cap_large_decr(void)
2549 {
2550     return cap_large_decr;
2551 }
2552 
2553 int kvmppc_enable_cap_large_decr(PowerPCCPU *cpu, int enable)
2554 {
2555     CPUState *cs = CPU(cpu);
2556     uint64_t lpcr;
2557 
2558     kvm_get_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2559     /* Do we need to modify the LPCR? */
2560     if (!!(lpcr & LPCR_LD) != !!enable) {
2561         if (enable) {
2562             lpcr |= LPCR_LD;
2563         } else {
2564             lpcr &= ~LPCR_LD;
2565         }
2566         kvm_set_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2567         kvm_get_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2568 
2569         if (!!(lpcr & LPCR_LD) != !!enable) {
2570             return -1;
2571         }
2572     }
2573 
2574     return 0;
2575 }
2576 
2577 PowerPCCPUClass *kvm_ppc_get_host_cpu_class(void)
2578 {
2579     uint32_t host_pvr = mfpvr();
2580     PowerPCCPUClass *pvr_pcc;
2581 
2582     pvr_pcc = ppc_cpu_class_by_pvr(host_pvr);
2583     if (pvr_pcc == NULL) {
2584         pvr_pcc = ppc_cpu_class_by_pvr_mask(host_pvr);
2585     }
2586 
2587     return pvr_pcc;
2588 }
2589 
2590 static int kvm_ppc_register_host_cpu_type(MachineState *ms)
2591 {
2592     TypeInfo type_info = {
2593         .name = TYPE_HOST_POWERPC_CPU,
2594         .class_init = kvmppc_host_cpu_class_init,
2595     };
2596     MachineClass *mc = MACHINE_GET_CLASS(ms);
2597     PowerPCCPUClass *pvr_pcc;
2598     ObjectClass *oc;
2599     DeviceClass *dc;
2600     int i;
2601 
2602     pvr_pcc = kvm_ppc_get_host_cpu_class();
2603     if (pvr_pcc == NULL) {
2604         return -1;
2605     }
2606     type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc));
2607     type_register(&type_info);
2608     if (object_dynamic_cast(OBJECT(ms), TYPE_SPAPR_MACHINE)) {
2609         /* override TCG default cpu type with 'host' cpu model */
2610         mc->default_cpu_type = TYPE_HOST_POWERPC_CPU;
2611     }
2612 
2613     oc = object_class_by_name(type_info.name);
2614     g_assert(oc);
2615 
2616     /*
2617      * Update generic CPU family class alias (e.g. on a POWER8NVL host,
2618      * we want "POWER8" to be a "family" alias that points to the current
2619      * host CPU type, too)
2620      */
2621     dc = DEVICE_CLASS(ppc_cpu_get_family_class(pvr_pcc));
2622     for (i = 0; ppc_cpu_aliases[i].alias != NULL; i++) {
2623         if (strcasecmp(ppc_cpu_aliases[i].alias, dc->desc) == 0) {
2624             char *suffix;
2625 
2626             ppc_cpu_aliases[i].model = g_strdup(object_class_get_name(oc));
2627             suffix = strstr(ppc_cpu_aliases[i].model, POWERPC_CPU_TYPE_SUFFIX);
2628             if (suffix) {
2629                 *suffix = 0;
2630             }
2631             break;
2632         }
2633     }
2634 
2635     return 0;
2636 }
2637 
2638 int kvmppc_define_rtas_kernel_token(uint32_t token, const char *function)
2639 {
2640     struct kvm_rtas_token_args args = {
2641         .token = token,
2642     };
2643 
2644     if (!kvm_check_extension(kvm_state, KVM_CAP_PPC_RTAS)) {
2645         return -ENOENT;
2646     }
2647 
2648     strncpy(args.name, function, sizeof(args.name));
2649 
2650     return kvm_vm_ioctl(kvm_state, KVM_PPC_RTAS_DEFINE_TOKEN, &args);
2651 }
2652 
2653 int kvmppc_get_htab_fd(bool write, uint64_t index, Error **errp)
2654 {
2655     struct kvm_get_htab_fd s = {
2656         .flags = write ? KVM_GET_HTAB_WRITE : 0,
2657         .start_index = index,
2658     };
2659     int ret;
2660 
2661     if (!cap_htab_fd) {
2662         error_setg(errp, "KVM version doesn't support %s the HPT",
2663                    write ? "writing" : "reading");
2664         return -ENOTSUP;
2665     }
2666 
2667     ret = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_HTAB_FD, &s);
2668     if (ret < 0) {
2669         error_setg(errp, "Unable to open fd for %s HPT %s KVM: %s",
2670                    write ? "writing" : "reading", write ? "to" : "from",
2671                    strerror(errno));
2672         return -errno;
2673     }
2674 
2675     return ret;
2676 }
2677 
2678 int kvmppc_save_htab(QEMUFile *f, int fd, size_t bufsize, int64_t max_ns)
2679 {
2680     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2681     uint8_t buf[bufsize];
2682     ssize_t rc;
2683 
2684     do {
2685         rc = read(fd, buf, bufsize);
2686         if (rc < 0) {
2687             fprintf(stderr, "Error reading data from KVM HTAB fd: %s\n",
2688                     strerror(errno));
2689             return rc;
2690         } else if (rc) {
2691             uint8_t *buffer = buf;
2692             ssize_t n = rc;
2693             while (n) {
2694                 struct kvm_get_htab_header *head =
2695                     (struct kvm_get_htab_header *) buffer;
2696                 size_t chunksize = sizeof(*head) +
2697                      HASH_PTE_SIZE_64 * head->n_valid;
2698 
2699                 qemu_put_be32(f, head->index);
2700                 qemu_put_be16(f, head->n_valid);
2701                 qemu_put_be16(f, head->n_invalid);
2702                 qemu_put_buffer(f, (void *)(head + 1),
2703                                 HASH_PTE_SIZE_64 * head->n_valid);
2704 
2705                 buffer += chunksize;
2706                 n -= chunksize;
2707             }
2708         }
2709     } while ((rc != 0)
2710              && ((max_ns < 0) ||
2711                  ((qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) < max_ns)));
2712 
2713     return (rc == 0) ? 1 : 0;
2714 }
2715 
2716 int kvmppc_load_htab_chunk(QEMUFile *f, int fd, uint32_t index,
2717                            uint16_t n_valid, uint16_t n_invalid)
2718 {
2719     struct kvm_get_htab_header *buf;
2720     size_t chunksize = sizeof(*buf) + n_valid * HASH_PTE_SIZE_64;
2721     ssize_t rc;
2722 
2723     buf = alloca(chunksize);
2724     buf->index = index;
2725     buf->n_valid = n_valid;
2726     buf->n_invalid = n_invalid;
2727 
2728     qemu_get_buffer(f, (void *)(buf + 1), HASH_PTE_SIZE_64 * n_valid);
2729 
2730     rc = write(fd, buf, chunksize);
2731     if (rc < 0) {
2732         fprintf(stderr, "Error writing KVM hash table: %s\n",
2733                 strerror(errno));
2734         return rc;
2735     }
2736     if (rc != chunksize) {
2737         /* We should never get a short write on a single chunk */
2738         fprintf(stderr, "Short write, restoring KVM hash table\n");
2739         return -1;
2740     }
2741     return 0;
2742 }
2743 
2744 bool kvm_arch_stop_on_emulation_error(CPUState *cpu)
2745 {
2746     return true;
2747 }
2748 
2749 void kvm_arch_init_irq_routing(KVMState *s)
2750 {
2751 }
2752 
2753 void kvmppc_read_hptes(ppc_hash_pte64_t *hptes, hwaddr ptex, int n)
2754 {
2755     int fd, rc;
2756     int i;
2757 
2758     fd = kvmppc_get_htab_fd(false, ptex, &error_abort);
2759 
2760     i = 0;
2761     while (i < n) {
2762         struct kvm_get_htab_header *hdr;
2763         int m = n < HPTES_PER_GROUP ? n : HPTES_PER_GROUP;
2764         char buf[sizeof(*hdr) + m * HASH_PTE_SIZE_64];
2765 
2766         rc = read(fd, buf, sizeof(buf));
2767         if (rc < 0) {
2768             hw_error("kvmppc_read_hptes: Unable to read HPTEs");
2769         }
2770 
2771         hdr = (struct kvm_get_htab_header *)buf;
2772         while ((i < n) && ((char *)hdr < (buf + rc))) {
2773             int invalid = hdr->n_invalid, valid = hdr->n_valid;
2774 
2775             if (hdr->index != (ptex + i)) {
2776                 hw_error("kvmppc_read_hptes: Unexpected HPTE index %"PRIu32
2777                          " != (%"HWADDR_PRIu" + %d", hdr->index, ptex, i);
2778             }
2779 
2780             if (n - i < valid) {
2781                 valid = n - i;
2782             }
2783             memcpy(hptes + i, hdr + 1, HASH_PTE_SIZE_64 * valid);
2784             i += valid;
2785 
2786             if ((n - i) < invalid) {
2787                 invalid = n - i;
2788             }
2789             memset(hptes + i, 0, invalid * HASH_PTE_SIZE_64);
2790             i += invalid;
2791 
2792             hdr = (struct kvm_get_htab_header *)
2793                 ((char *)(hdr + 1) + HASH_PTE_SIZE_64 * hdr->n_valid);
2794         }
2795     }
2796 
2797     close(fd);
2798 }
2799 
2800 void kvmppc_write_hpte(hwaddr ptex, uint64_t pte0, uint64_t pte1)
2801 {
2802     int fd, rc;
2803     struct {
2804         struct kvm_get_htab_header hdr;
2805         uint64_t pte0;
2806         uint64_t pte1;
2807     } buf;
2808 
2809     fd = kvmppc_get_htab_fd(true, 0 /* Ignored */, &error_abort);
2810 
2811     buf.hdr.n_valid = 1;
2812     buf.hdr.n_invalid = 0;
2813     buf.hdr.index = ptex;
2814     buf.pte0 = cpu_to_be64(pte0);
2815     buf.pte1 = cpu_to_be64(pte1);
2816 
2817     rc = write(fd, &buf, sizeof(buf));
2818     if (rc != sizeof(buf)) {
2819         hw_error("kvmppc_write_hpte: Unable to update KVM HPT");
2820     }
2821     close(fd);
2822 }
2823 
2824 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
2825                              uint64_t address, uint32_t data, PCIDevice *dev)
2826 {
2827     return 0;
2828 }
2829 
2830 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
2831                                 int vector, PCIDevice *dev)
2832 {
2833     return 0;
2834 }
2835 
2836 int kvm_arch_release_virq_post(int virq)
2837 {
2838     return 0;
2839 }
2840 
2841 int kvm_arch_msi_data_to_gsi(uint32_t data)
2842 {
2843     return data & 0xffff;
2844 }
2845 
2846 int kvmppc_enable_hwrng(void)
2847 {
2848     if (!kvm_enabled() || !kvm_check_extension(kvm_state, KVM_CAP_PPC_HWRNG)) {
2849         return -1;
2850     }
2851 
2852     return kvmppc_enable_hcall(kvm_state, H_RANDOM);
2853 }
2854 
2855 void kvmppc_check_papr_resize_hpt(Error **errp)
2856 {
2857     if (!kvm_enabled()) {
2858         return; /* No KVM, we're good */
2859     }
2860 
2861     if (cap_resize_hpt) {
2862         return; /* Kernel has explicit support, we're good */
2863     }
2864 
2865     /* Otherwise fallback on looking for PR KVM */
2866     if (kvmppc_is_pr(kvm_state)) {
2867         return;
2868     }
2869 
2870     error_setg(errp,
2871                "Hash page table resizing not available with this KVM version");
2872 }
2873 
2874 int kvmppc_resize_hpt_prepare(PowerPCCPU *cpu, target_ulong flags, int shift)
2875 {
2876     CPUState *cs = CPU(cpu);
2877     struct kvm_ppc_resize_hpt rhpt = {
2878         .flags = flags,
2879         .shift = shift,
2880     };
2881 
2882     if (!cap_resize_hpt) {
2883         return -ENOSYS;
2884     }
2885 
2886     return kvm_vm_ioctl(cs->kvm_state, KVM_PPC_RESIZE_HPT_PREPARE, &rhpt);
2887 }
2888 
2889 int kvmppc_resize_hpt_commit(PowerPCCPU *cpu, target_ulong flags, int shift)
2890 {
2891     CPUState *cs = CPU(cpu);
2892     struct kvm_ppc_resize_hpt rhpt = {
2893         .flags = flags,
2894         .shift = shift,
2895     };
2896 
2897     if (!cap_resize_hpt) {
2898         return -ENOSYS;
2899     }
2900 
2901     return kvm_vm_ioctl(cs->kvm_state, KVM_PPC_RESIZE_HPT_COMMIT, &rhpt);
2902 }
2903 
2904 /*
2905  * This is a helper function to detect a post migration scenario
2906  * in which a guest, running as KVM-HV, freezes in cpu_post_load because
2907  * the guest kernel can't handle a PVR value other than the actual host
2908  * PVR in KVM_SET_SREGS, even if pvr_match() returns true.
2909  *
2910  * If we don't have cap_ppc_pvr_compat and we're not running in PR
2911  * (so, we're HV), return true. The workaround itself is done in
2912  * cpu_post_load.
2913  *
2914  * The order here is important: we'll only check for KVM PR as a
2915  * fallback if the guest kernel can't handle the situation itself.
2916  * We need to avoid as much as possible querying the running KVM type
2917  * in QEMU level.
2918  */
2919 bool kvmppc_pvr_workaround_required(PowerPCCPU *cpu)
2920 {
2921     CPUState *cs = CPU(cpu);
2922 
2923     if (!kvm_enabled()) {
2924         return false;
2925     }
2926 
2927     if (cap_ppc_pvr_compat) {
2928         return false;
2929     }
2930 
2931     return !kvmppc_is_pr(cs->kvm_state);
2932 }
2933 
2934 void kvmppc_set_reg_ppc_online(PowerPCCPU *cpu, unsigned int online)
2935 {
2936     CPUState *cs = CPU(cpu);
2937 
2938     if (kvm_enabled()) {
2939         kvm_set_one_reg(cs, KVM_REG_PPC_ONLINE, &online);
2940     }
2941 }
2942