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