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