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