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