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