xref: /openbmc/qemu/target/ppc/kvm.c (revision fb6051e7)
1 /*
2  * PowerPC implementation of KVM hooks
3  *
4  * Copyright IBM Corp. 2007
5  * Copyright (C) 2011 Freescale Semiconductor, Inc.
6  *
7  * Authors:
8  *  Jerone Young <jyoung5@us.ibm.com>
9  *  Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com>
10  *  Hollis Blanchard <hollisb@us.ibm.com>
11  *
12  * This work is licensed under the terms of the GNU GPL, version 2 or later.
13  * See the COPYING file in the top-level directory.
14  *
15  */
16 
17 #include "qemu/osdep.h"
18 #include <dirent.h>
19 #include <sys/ioctl.h>
20 #include <sys/vfs.h>
21 
22 #include <linux/kvm.h>
23 
24 #include "qapi/error.h"
25 #include "qemu/error-report.h"
26 #include "cpu.h"
27 #include "cpu-models.h"
28 #include "qemu/timer.h"
29 #include "sysemu/hw_accel.h"
30 #include "kvm_ppc.h"
31 #include "sysemu/cpus.h"
32 #include "sysemu/device_tree.h"
33 #include "mmu-hash64.h"
34 
35 #include "hw/ppc/spapr.h"
36 #include "hw/ppc/spapr_cpu_core.h"
37 #include "hw/hw.h"
38 #include "hw/ppc/ppc.h"
39 #include "migration/qemu-file-types.h"
40 #include "sysemu/watchdog.h"
41 #include "trace.h"
42 #include "gdbstub/enums.h"
43 #include "exec/memattrs.h"
44 #include "exec/ram_addr.h"
45 #include "sysemu/hostmem.h"
46 #include "qemu/cutils.h"
47 #include "qemu/main-loop.h"
48 #include "qemu/mmap-alloc.h"
49 #include "elf.h"
50 #include "sysemu/kvm_int.h"
51 #include "sysemu/kvm.h"
52 #include "hw/core/accel-cpu.h"
53 
54 #include CONFIG_DEVICES
55 
56 #define PROC_DEVTREE_CPU      "/proc/device-tree/cpus/"
57 
58 #define DEBUG_RETURN_GUEST 0
59 #define DEBUG_RETURN_GDB   1
60 
61 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
62     KVM_CAP_LAST_INFO
63 };
64 
65 static int cap_interrupt_unset;
66 static int cap_segstate;
67 static int cap_booke_sregs;
68 static int cap_ppc_smt;
69 static int cap_ppc_smt_possible;
70 static int cap_spapr_tce;
71 static int cap_spapr_tce_64;
72 static int cap_spapr_multitce;
73 static int cap_spapr_vfio;
74 static int cap_hior;
75 static int cap_one_reg;
76 static int cap_epr;
77 static int cap_ppc_watchdog;
78 static int cap_htab_fd;
79 static int cap_fixup_hcalls;
80 static int cap_htm;             /* Hardware transactional memory support */
81 static int cap_mmu_radix;
82 static int cap_mmu_hash_v3;
83 static int cap_xive;
84 static int cap_resize_hpt;
85 static int cap_ppc_pvr_compat;
86 static int cap_ppc_safe_cache;
87 static int cap_ppc_safe_bounds_check;
88 static int cap_ppc_safe_indirect_branch;
89 static int cap_ppc_count_cache_flush_assist;
90 static int cap_ppc_nested_kvm_hv;
91 static int cap_large_decr;
92 static int cap_fwnmi;
93 static int cap_rpt_invalidate;
94 static int cap_ail_mode_3;
95 
96 #ifdef CONFIG_PSERIES
97 static int cap_papr;
98 #else
99 #define cap_papr (0)
100 #endif
101 
102 static uint32_t debug_inst_opcode;
103 
104 /*
105  * Check whether we are running with KVM-PR (instead of KVM-HV).  This
106  * should only be used for fallback tests - generally we should use
107  * explicit capabilities for the features we want, rather than
108  * assuming what is/isn't available depending on the KVM variant.
109  */
110 static bool kvmppc_is_pr(KVMState *ks)
111 {
112     /* Assume KVM-PR if the GET_PVINFO capability is available */
113     return kvm_vm_check_extension(ks, KVM_CAP_PPC_GET_PVINFO) != 0;
114 }
115 
116 static int kvm_ppc_register_host_cpu_type(void);
117 static void kvmppc_get_cpu_characteristics(KVMState *s);
118 static int kvmppc_get_dec_bits(void);
119 
120 int kvm_arch_get_default_type(MachineState *ms)
121 {
122     return 0;
123 }
124 
125 int kvm_arch_init(MachineState *ms, KVMState *s)
126 {
127     cap_interrupt_unset = kvm_check_extension(s, KVM_CAP_PPC_UNSET_IRQ);
128     cap_segstate = kvm_check_extension(s, KVM_CAP_PPC_SEGSTATE);
129     cap_booke_sregs = kvm_check_extension(s, KVM_CAP_PPC_BOOKE_SREGS);
130     cap_ppc_smt_possible = kvm_vm_check_extension(s, KVM_CAP_PPC_SMT_POSSIBLE);
131     cap_spapr_tce = kvm_check_extension(s, KVM_CAP_SPAPR_TCE);
132     cap_spapr_tce_64 = kvm_check_extension(s, KVM_CAP_SPAPR_TCE_64);
133     cap_spapr_multitce = kvm_check_extension(s, KVM_CAP_SPAPR_MULTITCE);
134     cap_spapr_vfio = kvm_vm_check_extension(s, KVM_CAP_SPAPR_TCE_VFIO);
135     cap_one_reg = kvm_check_extension(s, KVM_CAP_ONE_REG);
136     cap_hior = kvm_check_extension(s, KVM_CAP_PPC_HIOR);
137     cap_epr = kvm_check_extension(s, KVM_CAP_PPC_EPR);
138     cap_ppc_watchdog = kvm_check_extension(s, KVM_CAP_PPC_BOOKE_WATCHDOG);
139     /*
140      * Note: we don't set cap_papr here, because this capability is
141      * only activated after this by kvmppc_set_papr()
142      */
143     cap_htab_fd = kvm_vm_check_extension(s, KVM_CAP_PPC_HTAB_FD);
144     cap_fixup_hcalls = kvm_check_extension(s, KVM_CAP_PPC_FIXUP_HCALL);
145     cap_ppc_smt = kvm_vm_check_extension(s, KVM_CAP_PPC_SMT);
146     cap_htm = kvm_vm_check_extension(s, KVM_CAP_PPC_HTM);
147     cap_mmu_radix = kvm_vm_check_extension(s, KVM_CAP_PPC_MMU_RADIX);
148     cap_mmu_hash_v3 = kvm_vm_check_extension(s, KVM_CAP_PPC_MMU_HASH_V3);
149     cap_xive = kvm_vm_check_extension(s, KVM_CAP_PPC_IRQ_XIVE);
150     cap_resize_hpt = kvm_vm_check_extension(s, KVM_CAP_SPAPR_RESIZE_HPT);
151     kvmppc_get_cpu_characteristics(s);
152     cap_ppc_nested_kvm_hv = kvm_vm_check_extension(s, KVM_CAP_PPC_NESTED_HV);
153     cap_large_decr = kvmppc_get_dec_bits();
154     cap_fwnmi = kvm_vm_check_extension(s, KVM_CAP_PPC_FWNMI);
155     /*
156      * Note: setting it to false because there is not such capability
157      * in KVM at this moment.
158      *
159      * TODO: call kvm_vm_check_extension() with the right capability
160      * after the kernel starts implementing it.
161      */
162     cap_ppc_pvr_compat = false;
163 
164     if (!kvm_check_extension(s, KVM_CAP_PPC_IRQ_LEVEL)) {
165         error_report("KVM: Host kernel doesn't have level irq capability");
166         exit(1);
167     }
168 
169     cap_rpt_invalidate = kvm_vm_check_extension(s, KVM_CAP_PPC_RPT_INVALIDATE);
170     cap_ail_mode_3 = kvm_vm_check_extension(s, KVM_CAP_PPC_AIL_MODE_3);
171     kvm_ppc_register_host_cpu_type();
172 
173     return 0;
174 }
175 
176 int kvm_arch_irqchip_create(KVMState *s)
177 {
178     return 0;
179 }
180 
181 static int kvm_arch_sync_sregs(PowerPCCPU *cpu)
182 {
183     CPUPPCState *cenv = &cpu->env;
184     CPUState *cs = CPU(cpu);
185     struct kvm_sregs sregs;
186     int ret;
187 
188     if (cenv->excp_model == POWERPC_EXCP_BOOKE) {
189         /*
190          * What we're really trying to say is "if we're on BookE, we
191          * use the native PVR for now". This is the only sane way to
192          * check it though, so we potentially confuse users that they
193          * can run BookE guests on BookS. Let's hope nobody dares
194          * enough :)
195          */
196         return 0;
197     } else {
198         if (!cap_segstate) {
199             fprintf(stderr, "kvm error: missing PVR setting capability\n");
200             return -ENOSYS;
201         }
202     }
203 
204     ret = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);
205     if (ret) {
206         return ret;
207     }
208 
209     sregs.pvr = cenv->spr[SPR_PVR];
210     return kvm_vcpu_ioctl(cs, KVM_SET_SREGS, &sregs);
211 }
212 
213 /* Set up a shared TLB array with KVM */
214 static int kvm_booke206_tlb_init(PowerPCCPU *cpu)
215 {
216     CPUPPCState *env = &cpu->env;
217     CPUState *cs = CPU(cpu);
218     struct kvm_book3e_206_tlb_params params = {};
219     struct kvm_config_tlb cfg = {};
220     unsigned int entries = 0;
221     int ret, i;
222 
223     if (!kvm_enabled() ||
224         !kvm_check_extension(cs->kvm_state, KVM_CAP_SW_TLB)) {
225         return 0;
226     }
227 
228     assert(ARRAY_SIZE(params.tlb_sizes) == BOOKE206_MAX_TLBN);
229 
230     for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
231         params.tlb_sizes[i] = booke206_tlb_size(env, i);
232         params.tlb_ways[i] = booke206_tlb_ways(env, i);
233         entries += params.tlb_sizes[i];
234     }
235 
236     assert(entries == env->nb_tlb);
237     assert(sizeof(struct kvm_book3e_206_tlb_entry) == sizeof(ppcmas_tlb_t));
238 
239     env->tlb_dirty = true;
240 
241     cfg.array = (uintptr_t)env->tlb.tlbm;
242     cfg.array_len = sizeof(ppcmas_tlb_t) * entries;
243     cfg.params = (uintptr_t)&params;
244     cfg.mmu_type = KVM_MMU_FSL_BOOKE_NOHV;
245 
246     ret = kvm_vcpu_enable_cap(cs, KVM_CAP_SW_TLB, 0, (uintptr_t)&cfg);
247     if (ret < 0) {
248         fprintf(stderr, "%s: couldn't enable KVM_CAP_SW_TLB: %s\n",
249                 __func__, strerror(-ret));
250         return ret;
251     }
252 
253     env->kvm_sw_tlb = true;
254     return 0;
255 }
256 
257 
258 #if defined(TARGET_PPC64)
259 static void kvm_get_smmu_info(struct kvm_ppc_smmu_info *info, Error **errp)
260 {
261     int ret;
262 
263     assert(kvm_state != NULL);
264 
265     if (!kvm_check_extension(kvm_state, KVM_CAP_PPC_GET_SMMU_INFO)) {
266         error_setg(errp, "KVM doesn't expose the MMU features it supports");
267         error_append_hint(errp, "Consider switching to a newer KVM\n");
268         return;
269     }
270 
271     ret = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_SMMU_INFO, info);
272     if (ret == 0) {
273         return;
274     }
275 
276     error_setg_errno(errp, -ret,
277                      "KVM failed to provide the MMU features it supports");
278 }
279 
280 static struct ppc_radix_page_info *kvmppc_get_radix_page_info(void)
281 {
282     KVMState *s = KVM_STATE(current_accel());
283     struct ppc_radix_page_info *radix_page_info;
284     struct kvm_ppc_rmmu_info rmmu_info = { };
285     int i;
286 
287     if (!kvm_check_extension(s, KVM_CAP_PPC_MMU_RADIX)) {
288         return NULL;
289     }
290     if (kvm_vm_ioctl(s, KVM_PPC_GET_RMMU_INFO, &rmmu_info)) {
291         return NULL;
292     }
293     radix_page_info = g_malloc0(sizeof(*radix_page_info));
294     radix_page_info->count = 0;
295     for (i = 0; i < PPC_PAGE_SIZES_MAX_SZ; i++) {
296         if (rmmu_info.ap_encodings[i]) {
297             radix_page_info->entries[i] = rmmu_info.ap_encodings[i];
298             radix_page_info->count++;
299         }
300     }
301     return radix_page_info;
302 }
303 
304 target_ulong kvmppc_configure_v3_mmu(PowerPCCPU *cpu,
305                                      bool radix, bool gtse,
306                                      uint64_t proc_tbl)
307 {
308     CPUState *cs = CPU(cpu);
309     int ret;
310     uint64_t flags = 0;
311     struct kvm_ppc_mmuv3_cfg cfg = {
312         .process_table = proc_tbl,
313     };
314 
315     if (radix) {
316         flags |= KVM_PPC_MMUV3_RADIX;
317     }
318     if (gtse) {
319         flags |= KVM_PPC_MMUV3_GTSE;
320     }
321     cfg.flags = flags;
322     ret = kvm_vm_ioctl(cs->kvm_state, KVM_PPC_CONFIGURE_V3_MMU, &cfg);
323     switch (ret) {
324     case 0:
325         return H_SUCCESS;
326     case -EINVAL:
327         return H_PARAMETER;
328     case -ENODEV:
329         return H_NOT_AVAILABLE;
330     default:
331         return H_HARDWARE;
332     }
333 }
334 
335 bool kvmppc_hpt_needs_host_contiguous_pages(void)
336 {
337     static struct kvm_ppc_smmu_info smmu_info;
338 
339     if (!kvm_enabled()) {
340         return false;
341     }
342 
343     kvm_get_smmu_info(&smmu_info, &error_fatal);
344     return !!(smmu_info.flags & KVM_PPC_PAGE_SIZES_REAL);
345 }
346 
347 void kvm_check_mmu(PowerPCCPU *cpu, Error **errp)
348 {
349     struct kvm_ppc_smmu_info smmu_info;
350     int iq, ik, jq, jk;
351     Error *local_err = NULL;
352 
353     /* For now, we only have anything to check on hash64 MMUs */
354     if (!cpu->hash64_opts || !kvm_enabled()) {
355         return;
356     }
357 
358     kvm_get_smmu_info(&smmu_info, &local_err);
359     if (local_err) {
360         error_propagate(errp, local_err);
361         return;
362     }
363 
364     if (ppc_hash64_has(cpu, PPC_HASH64_1TSEG)
365         && !(smmu_info.flags & KVM_PPC_1T_SEGMENTS)) {
366         error_setg(errp,
367                    "KVM does not support 1TiB segments which guest expects");
368         return;
369     }
370 
371     if (smmu_info.slb_size < cpu->hash64_opts->slb_size) {
372         error_setg(errp, "KVM only supports %u SLB entries, but guest needs %u",
373                    smmu_info.slb_size, cpu->hash64_opts->slb_size);
374         return;
375     }
376 
377     /*
378      * Verify that every pagesize supported by the cpu model is
379      * supported by KVM with the same encodings
380      */
381     for (iq = 0; iq < ARRAY_SIZE(cpu->hash64_opts->sps); iq++) {
382         PPCHash64SegmentPageSizes *qsps = &cpu->hash64_opts->sps[iq];
383         struct kvm_ppc_one_seg_page_size *ksps;
384 
385         for (ik = 0; ik < ARRAY_SIZE(smmu_info.sps); ik++) {
386             if (qsps->page_shift == smmu_info.sps[ik].page_shift) {
387                 break;
388             }
389         }
390         if (ik >= ARRAY_SIZE(smmu_info.sps)) {
391             error_setg(errp, "KVM doesn't support for base page shift %u",
392                        qsps->page_shift);
393             return;
394         }
395 
396         ksps = &smmu_info.sps[ik];
397         if (ksps->slb_enc != qsps->slb_enc) {
398             error_setg(errp,
399 "KVM uses SLB encoding 0x%x for page shift %u, but guest expects 0x%x",
400                        ksps->slb_enc, ksps->page_shift, qsps->slb_enc);
401             return;
402         }
403 
404         for (jq = 0; jq < ARRAY_SIZE(qsps->enc); jq++) {
405             for (jk = 0; jk < ARRAY_SIZE(ksps->enc); jk++) {
406                 if (qsps->enc[jq].page_shift == ksps->enc[jk].page_shift) {
407                     break;
408                 }
409             }
410 
411             if (jk >= ARRAY_SIZE(ksps->enc)) {
412                 error_setg(errp, "KVM doesn't support page shift %u/%u",
413                            qsps->enc[jq].page_shift, qsps->page_shift);
414                 return;
415             }
416             if (qsps->enc[jq].pte_enc != ksps->enc[jk].pte_enc) {
417                 error_setg(errp,
418 "KVM uses PTE encoding 0x%x for page shift %u/%u, but guest expects 0x%x",
419                            ksps->enc[jk].pte_enc, qsps->enc[jq].page_shift,
420                            qsps->page_shift, qsps->enc[jq].pte_enc);
421                 return;
422             }
423         }
424     }
425 
426     if (ppc_hash64_has(cpu, PPC_HASH64_CI_LARGEPAGE)) {
427         /*
428          * Mostly what guest pagesizes we can use are related to the
429          * host pages used to map guest RAM, which is handled in the
430          * platform code. Cache-Inhibited largepages (64k) however are
431          * used for I/O, so if they're mapped to the host at all it
432          * will be a normal mapping, not a special hugepage one used
433          * for RAM.
434          */
435         if (qemu_real_host_page_size() < 0x10000) {
436             error_setg(errp,
437                        "KVM can't supply 64kiB CI pages, which guest expects");
438         }
439     }
440 }
441 #endif /* !defined (TARGET_PPC64) */
442 
443 unsigned long kvm_arch_vcpu_id(CPUState *cpu)
444 {
445     return POWERPC_CPU(cpu)->vcpu_id;
446 }
447 
448 /*
449  * e500 supports 2 h/w breakpoint and 2 watchpoint.  book3s supports
450  * only 1 watchpoint, so array size of 4 is sufficient for now.
451  */
452 #define MAX_HW_BKPTS 4
453 
454 static struct HWBreakpoint {
455     target_ulong addr;
456     int type;
457 } hw_debug_points[MAX_HW_BKPTS];
458 
459 static CPUWatchpoint hw_watchpoint;
460 
461 /* Default there is no breakpoint and watchpoint supported */
462 static int max_hw_breakpoint;
463 static int max_hw_watchpoint;
464 static int nb_hw_breakpoint;
465 static int nb_hw_watchpoint;
466 
467 static void kvmppc_hw_debug_points_init(CPUPPCState *cenv)
468 {
469     if (cenv->excp_model == POWERPC_EXCP_BOOKE) {
470         max_hw_breakpoint = 2;
471         max_hw_watchpoint = 2;
472     }
473 
474     if ((max_hw_breakpoint + max_hw_watchpoint) > MAX_HW_BKPTS) {
475         fprintf(stderr, "Error initializing h/w breakpoints\n");
476         return;
477     }
478 }
479 
480 int kvm_arch_init_vcpu(CPUState *cs)
481 {
482     PowerPCCPU *cpu = POWERPC_CPU(cs);
483     CPUPPCState *cenv = &cpu->env;
484     int ret;
485 
486     /* Synchronize sregs with kvm */
487     ret = kvm_arch_sync_sregs(cpu);
488     if (ret) {
489         if (ret == -EINVAL) {
490             error_report("Register sync failed... If you're using kvm-hv.ko,"
491                          " only \"-cpu host\" is possible");
492         }
493         return ret;
494     }
495 
496     switch (cenv->mmu_model) {
497     case POWERPC_MMU_BOOKE206:
498         /* This target supports access to KVM's guest TLB */
499         ret = kvm_booke206_tlb_init(cpu);
500         break;
501     case POWERPC_MMU_2_07:
502         if (!cap_htm && !kvmppc_is_pr(cs->kvm_state)) {
503             /*
504              * KVM-HV has transactional memory on POWER8 also without
505              * the KVM_CAP_PPC_HTM extension, so enable it here
506              * instead as long as it's available to userspace on the
507              * host.
508              */
509             if (qemu_getauxval(AT_HWCAP2) & PPC_FEATURE2_HAS_HTM) {
510                 cap_htm = true;
511             }
512         }
513         break;
514     default:
515         break;
516     }
517 
518     kvm_get_one_reg(cs, KVM_REG_PPC_DEBUG_INST, &debug_inst_opcode);
519     kvmppc_hw_debug_points_init(cenv);
520 
521     return ret;
522 }
523 
524 int kvm_arch_destroy_vcpu(CPUState *cs)
525 {
526     return 0;
527 }
528 
529 static void kvm_sw_tlb_put(PowerPCCPU *cpu)
530 {
531     CPUPPCState *env = &cpu->env;
532     CPUState *cs = CPU(cpu);
533     struct kvm_dirty_tlb dirty_tlb;
534     unsigned char *bitmap;
535     int ret;
536 
537     if (!env->kvm_sw_tlb) {
538         return;
539     }
540 
541     bitmap = g_malloc((env->nb_tlb + 7) / 8);
542     memset(bitmap, 0xFF, (env->nb_tlb + 7) / 8);
543 
544     dirty_tlb.bitmap = (uintptr_t)bitmap;
545     dirty_tlb.num_dirty = env->nb_tlb;
546 
547     ret = kvm_vcpu_ioctl(cs, KVM_DIRTY_TLB, &dirty_tlb);
548     if (ret) {
549         fprintf(stderr, "%s: KVM_DIRTY_TLB: %s\n",
550                 __func__, strerror(-ret));
551     }
552 
553     g_free(bitmap);
554 }
555 
556 static void kvm_get_one_spr(CPUState *cs, uint64_t id, int spr)
557 {
558     CPUPPCState *env = cpu_env(cs);
559     /* Init 'val' to avoid "uninitialised value" Valgrind warnings */
560     union {
561         uint32_t u32;
562         uint64_t u64;
563     } val = { };
564     struct kvm_one_reg reg = {
565         .id = id,
566         .addr = (uintptr_t) &val,
567     };
568     int ret;
569 
570     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
571     if (ret != 0) {
572         trace_kvm_failed_spr_get(spr, strerror(errno));
573     } else {
574         switch (id & KVM_REG_SIZE_MASK) {
575         case KVM_REG_SIZE_U32:
576             env->spr[spr] = val.u32;
577             break;
578 
579         case KVM_REG_SIZE_U64:
580             env->spr[spr] = val.u64;
581             break;
582 
583         default:
584             /* Don't handle this size yet */
585             abort();
586         }
587     }
588 }
589 
590 static void kvm_put_one_spr(CPUState *cs, uint64_t id, int spr)
591 {
592     CPUPPCState *env = cpu_env(cs);
593     union {
594         uint32_t u32;
595         uint64_t u64;
596     } val;
597     struct kvm_one_reg reg = {
598         .id = id,
599         .addr = (uintptr_t) &val,
600     };
601     int ret;
602 
603     switch (id & KVM_REG_SIZE_MASK) {
604     case KVM_REG_SIZE_U32:
605         val.u32 = env->spr[spr];
606         break;
607 
608     case KVM_REG_SIZE_U64:
609         val.u64 = env->spr[spr];
610         break;
611 
612     default:
613         /* Don't handle this size yet */
614         abort();
615     }
616 
617     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
618     if (ret != 0) {
619         trace_kvm_failed_spr_set(spr, strerror(errno));
620     }
621 }
622 
623 static int kvm_put_fp(CPUState *cs)
624 {
625     CPUPPCState *env = cpu_env(cs);
626     struct kvm_one_reg reg;
627     int i;
628     int ret;
629 
630     if (env->insns_flags & PPC_FLOAT) {
631         uint64_t fpscr = env->fpscr;
632         bool vsx = !!(env->insns_flags2 & PPC2_VSX);
633 
634         reg.id = KVM_REG_PPC_FPSCR;
635         reg.addr = (uintptr_t)&fpscr;
636         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
637         if (ret < 0) {
638             trace_kvm_failed_fpscr_set(strerror(errno));
639             return ret;
640         }
641 
642         for (i = 0; i < 32; i++) {
643             uint64_t vsr[2];
644             uint64_t *fpr = cpu_fpr_ptr(env, i);
645             uint64_t *vsrl = cpu_vsrl_ptr(env, i);
646 
647 #if HOST_BIG_ENDIAN
648             vsr[0] = float64_val(*fpr);
649             vsr[1] = *vsrl;
650 #else
651             vsr[0] = *vsrl;
652             vsr[1] = float64_val(*fpr);
653 #endif
654             reg.addr = (uintptr_t) &vsr;
655             reg.id = vsx ? KVM_REG_PPC_VSR(i) : KVM_REG_PPC_FPR(i);
656 
657             ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
658             if (ret < 0) {
659                 trace_kvm_failed_fp_set(vsx ? "VSR" : "FPR", i,
660                                         strerror(errno));
661                 return ret;
662             }
663         }
664     }
665 
666     if (env->insns_flags & PPC_ALTIVEC) {
667         reg.id = KVM_REG_PPC_VSCR;
668         reg.addr = (uintptr_t)&env->vscr;
669         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
670         if (ret < 0) {
671             trace_kvm_failed_vscr_set(strerror(errno));
672             return ret;
673         }
674 
675         for (i = 0; i < 32; i++) {
676             reg.id = KVM_REG_PPC_VR(i);
677             reg.addr = (uintptr_t)cpu_avr_ptr(env, i);
678             ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
679             if (ret < 0) {
680                 trace_kvm_failed_vr_set(i, strerror(errno));
681                 return ret;
682             }
683         }
684     }
685 
686     return 0;
687 }
688 
689 static int kvm_get_fp(CPUState *cs)
690 {
691     CPUPPCState *env = cpu_env(cs);
692     struct kvm_one_reg reg;
693     int i;
694     int ret;
695 
696     if (env->insns_flags & PPC_FLOAT) {
697         uint64_t fpscr;
698         bool vsx = !!(env->insns_flags2 & PPC2_VSX);
699 
700         reg.id = KVM_REG_PPC_FPSCR;
701         reg.addr = (uintptr_t)&fpscr;
702         ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
703         if (ret < 0) {
704             trace_kvm_failed_fpscr_get(strerror(errno));
705             return ret;
706         } else {
707             env->fpscr = fpscr;
708         }
709 
710         for (i = 0; i < 32; i++) {
711             uint64_t vsr[2];
712             uint64_t *fpr = cpu_fpr_ptr(env, i);
713             uint64_t *vsrl = cpu_vsrl_ptr(env, i);
714 
715             reg.addr = (uintptr_t) &vsr;
716             reg.id = vsx ? KVM_REG_PPC_VSR(i) : KVM_REG_PPC_FPR(i);
717 
718             ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
719             if (ret < 0) {
720                 trace_kvm_failed_fp_get(vsx ? "VSR" : "FPR", i,
721                                         strerror(errno));
722                 return ret;
723             } else {
724 #if HOST_BIG_ENDIAN
725                 *fpr = vsr[0];
726                 if (vsx) {
727                     *vsrl = vsr[1];
728                 }
729 #else
730                 *fpr = vsr[1];
731                 if (vsx) {
732                     *vsrl = vsr[0];
733                 }
734 #endif
735             }
736         }
737     }
738 
739     if (env->insns_flags & PPC_ALTIVEC) {
740         reg.id = KVM_REG_PPC_VSCR;
741         reg.addr = (uintptr_t)&env->vscr;
742         ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
743         if (ret < 0) {
744             trace_kvm_failed_vscr_get(strerror(errno));
745             return ret;
746         }
747 
748         for (i = 0; i < 32; i++) {
749             reg.id = KVM_REG_PPC_VR(i);
750             reg.addr = (uintptr_t)cpu_avr_ptr(env, i);
751             ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
752             if (ret < 0) {
753                 trace_kvm_failed_vr_get(i, strerror(errno));
754                 return ret;
755             }
756         }
757     }
758 
759     return 0;
760 }
761 
762 #if defined(TARGET_PPC64)
763 static int kvm_get_vpa(CPUState *cs)
764 {
765     PowerPCCPU *cpu = POWERPC_CPU(cs);
766     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
767     struct kvm_one_reg reg;
768     int ret;
769 
770     reg.id = KVM_REG_PPC_VPA_ADDR;
771     reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
772     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
773     if (ret < 0) {
774         trace_kvm_failed_vpa_addr_get(strerror(errno));
775         return ret;
776     }
777 
778     assert((uintptr_t)&spapr_cpu->slb_shadow_size
779            == ((uintptr_t)&spapr_cpu->slb_shadow_addr + 8));
780     reg.id = KVM_REG_PPC_VPA_SLB;
781     reg.addr = (uintptr_t)&spapr_cpu->slb_shadow_addr;
782     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
783     if (ret < 0) {
784         trace_kvm_failed_slb_get(strerror(errno));
785         return ret;
786     }
787 
788     assert((uintptr_t)&spapr_cpu->dtl_size
789            == ((uintptr_t)&spapr_cpu->dtl_addr + 8));
790     reg.id = KVM_REG_PPC_VPA_DTL;
791     reg.addr = (uintptr_t)&spapr_cpu->dtl_addr;
792     ret = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
793     if (ret < 0) {
794         trace_kvm_failed_dtl_get(strerror(errno));
795         return ret;
796     }
797 
798     return 0;
799 }
800 
801 static int kvm_put_vpa(CPUState *cs)
802 {
803     PowerPCCPU *cpu = POWERPC_CPU(cs);
804     SpaprCpuState *spapr_cpu = spapr_cpu_state(cpu);
805     struct kvm_one_reg reg;
806     int ret;
807 
808     /*
809      * SLB shadow or DTL can't be registered unless a master VPA is
810      * registered.  That means when restoring state, if a VPA *is*
811      * registered, we need to set that up first.  If not, we need to
812      * deregister the others before deregistering the master VPA
813      */
814     assert(spapr_cpu->vpa_addr
815            || !(spapr_cpu->slb_shadow_addr || spapr_cpu->dtl_addr));
816 
817     if (spapr_cpu->vpa_addr) {
818         reg.id = KVM_REG_PPC_VPA_ADDR;
819         reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
820         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
821         if (ret < 0) {
822             trace_kvm_failed_vpa_addr_set(strerror(errno));
823             return ret;
824         }
825     }
826 
827     assert((uintptr_t)&spapr_cpu->slb_shadow_size
828            == ((uintptr_t)&spapr_cpu->slb_shadow_addr + 8));
829     reg.id = KVM_REG_PPC_VPA_SLB;
830     reg.addr = (uintptr_t)&spapr_cpu->slb_shadow_addr;
831     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
832     if (ret < 0) {
833         trace_kvm_failed_slb_set(strerror(errno));
834         return ret;
835     }
836 
837     assert((uintptr_t)&spapr_cpu->dtl_size
838            == ((uintptr_t)&spapr_cpu->dtl_addr + 8));
839     reg.id = KVM_REG_PPC_VPA_DTL;
840     reg.addr = (uintptr_t)&spapr_cpu->dtl_addr;
841     ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
842     if (ret < 0) {
843         trace_kvm_failed_dtl_set(strerror(errno));
844         return ret;
845     }
846 
847     if (!spapr_cpu->vpa_addr) {
848         reg.id = KVM_REG_PPC_VPA_ADDR;
849         reg.addr = (uintptr_t)&spapr_cpu->vpa_addr;
850         ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
851         if (ret < 0) {
852             trace_kvm_failed_null_vpa_addr_set(strerror(errno));
853             return ret;
854         }
855     }
856 
857     return 0;
858 }
859 #endif /* TARGET_PPC64 */
860 
861 int kvmppc_put_books_sregs(PowerPCCPU *cpu)
862 {
863     CPUPPCState *env = &cpu->env;
864     struct kvm_sregs sregs = { };
865     int i;
866 
867     sregs.pvr = env->spr[SPR_PVR];
868 
869     if (cpu->vhyp) {
870         sregs.u.s.sdr1 = cpu->vhyp_class->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 bool kvmppc_cpu_realize(CPUState *cs, Error **errp)
2352 {
2353     int ret;
2354     const char *vcpu_str = (cs->parent_obj.hotplugged == true) ?
2355                            "hotplug" : "create";
2356     cs->cpu_index = cpu_get_free_index();
2357 
2358     POWERPC_CPU(cs)->vcpu_id = cs->cpu_index;
2359 
2360     /* create and park to fail gracefully in case vcpu hotplug fails */
2361     ret = kvm_create_and_park_vcpu(cs);
2362     if (ret) {
2363         /*
2364          * This causes QEMU to terminate if initial CPU creation
2365          * fails, and only CPU hotplug failure if the error happens
2366          * there.
2367          */
2368         error_setg(errp, "%s: vcpu %s failed with %d",
2369                          __func__, vcpu_str, ret);
2370         return false;
2371     }
2372     return true;
2373 }
2374 
2375 static void kvmppc_host_cpu_class_init(ObjectClass *oc, void *data)
2376 {
2377     PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);
2378     uint32_t dcache_size = kvmppc_read_int_cpu_dt("d-cache-size");
2379     uint32_t icache_size = kvmppc_read_int_cpu_dt("i-cache-size");
2380 
2381     /* Now fix up the class with information we can query from the host */
2382     pcc->pvr = mfpvr();
2383 
2384     alter_insns(&pcc->insns_flags, PPC_ALTIVEC,
2385                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_ALTIVEC);
2386     alter_insns(&pcc->insns_flags2, PPC2_VSX,
2387                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_VSX);
2388     alter_insns(&pcc->insns_flags2, PPC2_DFP,
2389                 qemu_getauxval(AT_HWCAP) & PPC_FEATURE_HAS_DFP);
2390 
2391     if (dcache_size != -1) {
2392         pcc->l1_dcache_size = dcache_size;
2393     }
2394 
2395     if (icache_size != -1) {
2396         pcc->l1_icache_size = icache_size;
2397     }
2398 
2399 #if defined(TARGET_PPC64)
2400     pcc->radix_page_info = kvmppc_get_radix_page_info();
2401 #endif /* defined(TARGET_PPC64) */
2402 }
2403 
2404 bool kvmppc_has_cap_epr(void)
2405 {
2406     return cap_epr;
2407 }
2408 
2409 bool kvmppc_has_cap_fixup_hcalls(void)
2410 {
2411     return cap_fixup_hcalls;
2412 }
2413 
2414 bool kvmppc_has_cap_htm(void)
2415 {
2416     return cap_htm;
2417 }
2418 
2419 bool kvmppc_has_cap_mmu_radix(void)
2420 {
2421     return cap_mmu_radix;
2422 }
2423 
2424 bool kvmppc_has_cap_mmu_hash_v3(void)
2425 {
2426     return cap_mmu_hash_v3;
2427 }
2428 
2429 static bool kvmppc_power8_host(void)
2430 {
2431     bool ret = false;
2432 #ifdef TARGET_PPC64
2433     {
2434         uint32_t base_pvr = CPU_POWERPC_POWER_SERVER_MASK & mfpvr();
2435         ret = (base_pvr == CPU_POWERPC_POWER8E_BASE) ||
2436               (base_pvr == CPU_POWERPC_POWER8NVL_BASE) ||
2437               (base_pvr == CPU_POWERPC_POWER8_BASE);
2438     }
2439 #endif /* TARGET_PPC64 */
2440     return ret;
2441 }
2442 
2443 static int parse_cap_ppc_safe_cache(struct kvm_ppc_cpu_char c)
2444 {
2445     bool l1d_thread_priv_req = !kvmppc_power8_host();
2446 
2447     if (~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_L1D_FLUSH_PR) {
2448         return 2;
2449     } else if ((!l1d_thread_priv_req ||
2450                 c.character & c.character_mask & H_CPU_CHAR_L1D_THREAD_PRIV) &&
2451                (c.character & c.character_mask
2452                 & (H_CPU_CHAR_L1D_FLUSH_ORI30 | H_CPU_CHAR_L1D_FLUSH_TRIG2))) {
2453         return 1;
2454     }
2455 
2456     return 0;
2457 }
2458 
2459 static int parse_cap_ppc_safe_bounds_check(struct kvm_ppc_cpu_char c)
2460 {
2461     if (~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_BNDS_CHK_SPEC_BAR) {
2462         return 2;
2463     } else if (c.character & c.character_mask & H_CPU_CHAR_SPEC_BAR_ORI31) {
2464         return 1;
2465     }
2466 
2467     return 0;
2468 }
2469 
2470 static int parse_cap_ppc_safe_indirect_branch(struct kvm_ppc_cpu_char c)
2471 {
2472     if ((~c.behaviour & c.behaviour_mask & H_CPU_BEHAV_FLUSH_COUNT_CACHE) &&
2473         (~c.character & c.character_mask & H_CPU_CHAR_CACHE_COUNT_DIS) &&
2474         (~c.character & c.character_mask & H_CPU_CHAR_BCCTRL_SERIALISED)) {
2475         return SPAPR_CAP_FIXED_NA;
2476     } else if (c.behaviour & c.behaviour_mask & H_CPU_BEHAV_FLUSH_COUNT_CACHE) {
2477         return SPAPR_CAP_WORKAROUND;
2478     } else if (c.character & c.character_mask & H_CPU_CHAR_CACHE_COUNT_DIS) {
2479         return  SPAPR_CAP_FIXED_CCD;
2480     } else if (c.character & c.character_mask & H_CPU_CHAR_BCCTRL_SERIALISED) {
2481         return SPAPR_CAP_FIXED_IBS;
2482     }
2483 
2484     return 0;
2485 }
2486 
2487 static int parse_cap_ppc_count_cache_flush_assist(struct kvm_ppc_cpu_char c)
2488 {
2489     if (c.character & c.character_mask & H_CPU_CHAR_BCCTR_FLUSH_ASSIST) {
2490         return 1;
2491     }
2492     return 0;
2493 }
2494 
2495 bool kvmppc_has_cap_xive(void)
2496 {
2497     return cap_xive;
2498 }
2499 
2500 static void kvmppc_get_cpu_characteristics(KVMState *s)
2501 {
2502     struct kvm_ppc_cpu_char c;
2503     int ret;
2504 
2505     /* Assume broken */
2506     cap_ppc_safe_cache = 0;
2507     cap_ppc_safe_bounds_check = 0;
2508     cap_ppc_safe_indirect_branch = 0;
2509 
2510     ret = kvm_vm_check_extension(s, KVM_CAP_PPC_GET_CPU_CHAR);
2511     if (!ret) {
2512         return;
2513     }
2514     ret = kvm_vm_ioctl(s, KVM_PPC_GET_CPU_CHAR, &c);
2515     if (ret < 0) {
2516         return;
2517     }
2518 
2519     cap_ppc_safe_cache = parse_cap_ppc_safe_cache(c);
2520     cap_ppc_safe_bounds_check = parse_cap_ppc_safe_bounds_check(c);
2521     cap_ppc_safe_indirect_branch = parse_cap_ppc_safe_indirect_branch(c);
2522     cap_ppc_count_cache_flush_assist =
2523         parse_cap_ppc_count_cache_flush_assist(c);
2524 }
2525 
2526 int kvmppc_get_cap_safe_cache(void)
2527 {
2528     return cap_ppc_safe_cache;
2529 }
2530 
2531 int kvmppc_get_cap_safe_bounds_check(void)
2532 {
2533     return cap_ppc_safe_bounds_check;
2534 }
2535 
2536 int kvmppc_get_cap_safe_indirect_branch(void)
2537 {
2538     return cap_ppc_safe_indirect_branch;
2539 }
2540 
2541 int kvmppc_get_cap_count_cache_flush_assist(void)
2542 {
2543     return cap_ppc_count_cache_flush_assist;
2544 }
2545 
2546 bool kvmppc_has_cap_nested_kvm_hv(void)
2547 {
2548     return !!cap_ppc_nested_kvm_hv;
2549 }
2550 
2551 int kvmppc_set_cap_nested_kvm_hv(int enable)
2552 {
2553     return kvm_vm_enable_cap(kvm_state, KVM_CAP_PPC_NESTED_HV, 0, enable);
2554 }
2555 
2556 bool kvmppc_has_cap_spapr_vfio(void)
2557 {
2558     return cap_spapr_vfio;
2559 }
2560 
2561 int kvmppc_get_cap_large_decr(void)
2562 {
2563     return cap_large_decr;
2564 }
2565 
2566 int kvmppc_enable_cap_large_decr(PowerPCCPU *cpu, int enable)
2567 {
2568     CPUState *cs = CPU(cpu);
2569     uint64_t lpcr = 0;
2570 
2571     kvm_get_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2572     /* Do we need to modify the LPCR? */
2573     if (!!(lpcr & LPCR_LD) != !!enable) {
2574         if (enable) {
2575             lpcr |= LPCR_LD;
2576         } else {
2577             lpcr &= ~LPCR_LD;
2578         }
2579         kvm_set_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2580         kvm_get_one_reg(cs, KVM_REG_PPC_LPCR_64, &lpcr);
2581 
2582         if (!!(lpcr & LPCR_LD) != !!enable) {
2583             return -1;
2584         }
2585     }
2586 
2587     return 0;
2588 }
2589 
2590 int kvmppc_has_cap_rpt_invalidate(void)
2591 {
2592     return cap_rpt_invalidate;
2593 }
2594 
2595 bool kvmppc_supports_ail_3(void)
2596 {
2597     return cap_ail_mode_3;
2598 }
2599 
2600 PowerPCCPUClass *kvm_ppc_get_host_cpu_class(void)
2601 {
2602     uint32_t host_pvr = mfpvr();
2603     PowerPCCPUClass *pvr_pcc;
2604 
2605     pvr_pcc = ppc_cpu_class_by_pvr(host_pvr);
2606     if (pvr_pcc == NULL) {
2607         pvr_pcc = ppc_cpu_class_by_pvr_mask(host_pvr);
2608     }
2609 
2610     return pvr_pcc;
2611 }
2612 
2613 static void pseries_machine_class_fixup(ObjectClass *oc, void *opaque)
2614 {
2615     MachineClass *mc = MACHINE_CLASS(oc);
2616 
2617     mc->default_cpu_type = TYPE_HOST_POWERPC_CPU;
2618 }
2619 
2620 static int kvm_ppc_register_host_cpu_type(void)
2621 {
2622     TypeInfo type_info = {
2623         .name = TYPE_HOST_POWERPC_CPU,
2624         .class_init = kvmppc_host_cpu_class_init,
2625     };
2626     PowerPCCPUClass *pvr_pcc;
2627     ObjectClass *oc;
2628     DeviceClass *dc;
2629     int i;
2630 
2631     pvr_pcc = kvm_ppc_get_host_cpu_class();
2632     if (pvr_pcc == NULL) {
2633         return -1;
2634     }
2635     type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc));
2636     type_register(&type_info);
2637     /* override TCG default cpu type with 'host' cpu model */
2638     object_class_foreach(pseries_machine_class_fixup, TYPE_SPAPR_MACHINE,
2639                          false, NULL);
2640 
2641     oc = object_class_by_name(type_info.name);
2642     g_assert(oc);
2643 
2644     /*
2645      * Update generic CPU family class alias (e.g. on a POWER8NVL host,
2646      * we want "POWER8" to be a "family" alias that points to the current
2647      * host CPU type, too)
2648      */
2649     dc = DEVICE_CLASS(ppc_cpu_get_family_class(pvr_pcc));
2650     for (i = 0; ppc_cpu_aliases[i].alias != NULL; i++) {
2651         if (strcasecmp(ppc_cpu_aliases[i].alias, dc->desc) == 0) {
2652             char *suffix;
2653 
2654             ppc_cpu_aliases[i].model = g_strdup(object_class_get_name(oc));
2655             suffix = strstr(ppc_cpu_aliases[i].model, POWERPC_CPU_TYPE_SUFFIX);
2656             if (suffix) {
2657                 *suffix = 0;
2658             }
2659             break;
2660         }
2661     }
2662 
2663     return 0;
2664 }
2665 
2666 int kvmppc_define_rtas_kernel_token(uint32_t token, const char *function)
2667 {
2668     struct kvm_rtas_token_args args = {
2669         .token = token,
2670     };
2671 
2672     if (!kvm_check_extension(kvm_state, KVM_CAP_PPC_RTAS)) {
2673         return -ENOENT;
2674     }
2675 
2676     strncpy(args.name, function, sizeof(args.name) - 1);
2677 
2678     return kvm_vm_ioctl(kvm_state, KVM_PPC_RTAS_DEFINE_TOKEN, &args);
2679 }
2680 
2681 int kvmppc_get_htab_fd(bool write, uint64_t index, Error **errp)
2682 {
2683     struct kvm_get_htab_fd s = {
2684         .flags = write ? KVM_GET_HTAB_WRITE : 0,
2685         .start_index = index,
2686     };
2687     int ret;
2688 
2689     if (!cap_htab_fd) {
2690         error_setg(errp, "KVM version doesn't support %s the HPT",
2691                    write ? "writing" : "reading");
2692         return -ENOTSUP;
2693     }
2694 
2695     ret = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_HTAB_FD, &s);
2696     if (ret < 0) {
2697         error_setg(errp, "Unable to open fd for %s HPT %s KVM: %s",
2698                    write ? "writing" : "reading", write ? "to" : "from",
2699                    strerror(errno));
2700         return -errno;
2701     }
2702 
2703     return ret;
2704 }
2705 
2706 int kvmppc_save_htab(QEMUFile *f, int fd, size_t bufsize, int64_t max_ns)
2707 {
2708     int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2709     g_autofree uint8_t *buf = g_malloc(bufsize);
2710     ssize_t rc;
2711 
2712     do {
2713         rc = read(fd, buf, bufsize);
2714         if (rc < 0) {
2715             fprintf(stderr, "Error reading data from KVM HTAB fd: %s\n",
2716                     strerror(errno));
2717             return rc;
2718         } else if (rc) {
2719             uint8_t *buffer = buf;
2720             ssize_t n = rc;
2721             while (n) {
2722                 struct kvm_get_htab_header *head =
2723                     (struct kvm_get_htab_header *) buffer;
2724                 size_t chunksize = sizeof(*head) +
2725                      HASH_PTE_SIZE_64 * head->n_valid;
2726 
2727                 qemu_put_be32(f, head->index);
2728                 qemu_put_be16(f, head->n_valid);
2729                 qemu_put_be16(f, head->n_invalid);
2730                 qemu_put_buffer(f, (void *)(head + 1),
2731                                 HASH_PTE_SIZE_64 * head->n_valid);
2732 
2733                 buffer += chunksize;
2734                 n -= chunksize;
2735             }
2736         }
2737     } while ((rc != 0)
2738              && ((max_ns < 0) ||
2739                  ((qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) < max_ns)));
2740 
2741     return (rc == 0) ? 1 : 0;
2742 }
2743 
2744 int kvmppc_load_htab_chunk(QEMUFile *f, int fd, uint32_t index,
2745                            uint16_t n_valid, uint16_t n_invalid, Error **errp)
2746 {
2747     struct kvm_get_htab_header *buf;
2748     size_t chunksize = sizeof(*buf) + n_valid * HASH_PTE_SIZE_64;
2749     ssize_t rc;
2750 
2751     buf = alloca(chunksize);
2752     buf->index = index;
2753     buf->n_valid = n_valid;
2754     buf->n_invalid = n_invalid;
2755 
2756     qemu_get_buffer(f, (void *)(buf + 1), HASH_PTE_SIZE_64 * n_valid);
2757 
2758     rc = write(fd, buf, chunksize);
2759     if (rc < 0) {
2760         error_setg_errno(errp, errno, "Error writing the KVM hash table");
2761         return -errno;
2762     }
2763     if (rc != chunksize) {
2764         /* We should never get a short write on a single chunk */
2765         error_setg(errp, "Short write while restoring the KVM hash table");
2766         return -ENOSPC;
2767     }
2768     return 0;
2769 }
2770 
2771 bool kvm_arch_stop_on_emulation_error(CPUState *cpu)
2772 {
2773     return true;
2774 }
2775 
2776 void kvm_arch_init_irq_routing(KVMState *s)
2777 {
2778 }
2779 
2780 void kvmppc_read_hptes(ppc_hash_pte64_t *hptes, hwaddr ptex, int n)
2781 {
2782     int fd, rc;
2783     int i;
2784 
2785     fd = kvmppc_get_htab_fd(false, ptex, &error_abort);
2786 
2787     i = 0;
2788     while (i < n) {
2789         struct kvm_get_htab_header *hdr;
2790         int m = n < HPTES_PER_GROUP ? n : HPTES_PER_GROUP;
2791         char buf[sizeof(*hdr) + HPTES_PER_GROUP * HASH_PTE_SIZE_64];
2792 
2793         rc = read(fd, buf, sizeof(*hdr) + m * HASH_PTE_SIZE_64);
2794         if (rc < 0) {
2795             hw_error("kvmppc_read_hptes: Unable to read HPTEs");
2796         }
2797 
2798         hdr = (struct kvm_get_htab_header *)buf;
2799         while ((i < n) && ((char *)hdr < (buf + rc))) {
2800             int invalid = hdr->n_invalid, valid = hdr->n_valid;
2801 
2802             if (hdr->index != (ptex + i)) {
2803                 hw_error("kvmppc_read_hptes: Unexpected HPTE index %"PRIu32
2804                          " != (%"HWADDR_PRIu" + %d", hdr->index, ptex, i);
2805             }
2806 
2807             if (n - i < valid) {
2808                 valid = n - i;
2809             }
2810             memcpy(hptes + i, hdr + 1, HASH_PTE_SIZE_64 * valid);
2811             i += valid;
2812 
2813             if ((n - i) < invalid) {
2814                 invalid = n - i;
2815             }
2816             memset(hptes + i, 0, invalid * HASH_PTE_SIZE_64);
2817             i += invalid;
2818 
2819             hdr = (struct kvm_get_htab_header *)
2820                 ((char *)(hdr + 1) + HASH_PTE_SIZE_64 * hdr->n_valid);
2821         }
2822     }
2823 
2824     close(fd);
2825 }
2826 
2827 void kvmppc_write_hpte(hwaddr ptex, uint64_t pte0, uint64_t pte1)
2828 {
2829     int fd, rc;
2830     struct {
2831         struct kvm_get_htab_header hdr;
2832         uint64_t pte0;
2833         uint64_t pte1;
2834     } buf;
2835 
2836     fd = kvmppc_get_htab_fd(true, 0 /* Ignored */, &error_abort);
2837 
2838     buf.hdr.n_valid = 1;
2839     buf.hdr.n_invalid = 0;
2840     buf.hdr.index = ptex;
2841     buf.pte0 = cpu_to_be64(pte0);
2842     buf.pte1 = cpu_to_be64(pte1);
2843 
2844     rc = write(fd, &buf, sizeof(buf));
2845     if (rc != sizeof(buf)) {
2846         hw_error("kvmppc_write_hpte: Unable to update KVM HPT");
2847     }
2848     close(fd);
2849 }
2850 
2851 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
2852                              uint64_t address, uint32_t data, PCIDevice *dev)
2853 {
2854     return 0;
2855 }
2856 
2857 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
2858                                 int vector, PCIDevice *dev)
2859 {
2860     return 0;
2861 }
2862 
2863 int kvm_arch_release_virq_post(int virq)
2864 {
2865     return 0;
2866 }
2867 
2868 int kvm_arch_msi_data_to_gsi(uint32_t data)
2869 {
2870     return data & 0xffff;
2871 }
2872 
2873 #if defined(CONFIG_PSERIES)
2874 int kvm_handle_nmi(PowerPCCPU *cpu, struct kvm_run *run)
2875 {
2876     uint16_t flags = run->flags & KVM_RUN_PPC_NMI_DISP_MASK;
2877 
2878     cpu_synchronize_state(CPU(cpu));
2879 
2880     spapr_mce_req_event(cpu, flags == KVM_RUN_PPC_NMI_DISP_FULLY_RECOV);
2881 
2882     return 0;
2883 }
2884 #endif
2885 
2886 int kvmppc_enable_hwrng(void)
2887 {
2888     if (!kvm_enabled() || !kvm_check_extension(kvm_state, KVM_CAP_PPC_HWRNG)) {
2889         return -1;
2890     }
2891 
2892     return kvmppc_enable_hcall(kvm_state, H_RANDOM);
2893 }
2894 
2895 void kvmppc_check_papr_resize_hpt(Error **errp)
2896 {
2897     if (!kvm_enabled()) {
2898         return; /* No KVM, we're good */
2899     }
2900 
2901     if (cap_resize_hpt) {
2902         return; /* Kernel has explicit support, we're good */
2903     }
2904 
2905     /* Otherwise fallback on looking for PR KVM */
2906     if (kvmppc_is_pr(kvm_state)) {
2907         return;
2908     }
2909 
2910     error_setg(errp,
2911                "Hash page table resizing not available with this KVM version");
2912 }
2913 
2914 int kvmppc_resize_hpt_prepare(PowerPCCPU *cpu, target_ulong flags, int shift)
2915 {
2916     CPUState *cs = CPU(cpu);
2917     struct kvm_ppc_resize_hpt rhpt = {
2918         .flags = flags,
2919         .shift = shift,
2920     };
2921 
2922     if (!cap_resize_hpt) {
2923         return -ENOSYS;
2924     }
2925 
2926     return kvm_vm_ioctl(cs->kvm_state, KVM_PPC_RESIZE_HPT_PREPARE, &rhpt);
2927 }
2928 
2929 int kvmppc_resize_hpt_commit(PowerPCCPU *cpu, target_ulong flags, int shift)
2930 {
2931     CPUState *cs = CPU(cpu);
2932     struct kvm_ppc_resize_hpt rhpt = {
2933         .flags = flags,
2934         .shift = shift,
2935     };
2936 
2937     if (!cap_resize_hpt) {
2938         return -ENOSYS;
2939     }
2940 
2941     return kvm_vm_ioctl(cs->kvm_state, KVM_PPC_RESIZE_HPT_COMMIT, &rhpt);
2942 }
2943 
2944 /*
2945  * This is a helper function to detect a post migration scenario
2946  * in which a guest, running as KVM-HV, freezes in cpu_post_load because
2947  * the guest kernel can't handle a PVR value other than the actual host
2948  * PVR in KVM_SET_SREGS, even if pvr_match() returns true.
2949  *
2950  * If we don't have cap_ppc_pvr_compat and we're not running in PR
2951  * (so, we're HV), return true. The workaround itself is done in
2952  * cpu_post_load.
2953  *
2954  * The order here is important: we'll only check for KVM PR as a
2955  * fallback if the guest kernel can't handle the situation itself.
2956  * We need to avoid as much as possible querying the running KVM type
2957  * in QEMU level.
2958  */
2959 bool kvmppc_pvr_workaround_required(PowerPCCPU *cpu)
2960 {
2961     CPUState *cs = CPU(cpu);
2962 
2963     if (!kvm_enabled()) {
2964         return false;
2965     }
2966 
2967     if (cap_ppc_pvr_compat) {
2968         return false;
2969     }
2970 
2971     return !kvmppc_is_pr(cs->kvm_state);
2972 }
2973 
2974 void kvmppc_set_reg_ppc_online(PowerPCCPU *cpu, unsigned int online)
2975 {
2976     CPUState *cs = CPU(cpu);
2977 
2978     if (kvm_enabled()) {
2979         kvm_set_one_reg(cs, KVM_REG_PPC_ONLINE, &online);
2980     }
2981 }
2982 
2983 void kvmppc_set_reg_tb_offset(PowerPCCPU *cpu, int64_t tb_offset)
2984 {
2985     CPUState *cs = CPU(cpu);
2986 
2987     if (kvm_enabled()) {
2988         kvm_set_one_reg(cs, KVM_REG_PPC_TB_OFFSET, &tb_offset);
2989     }
2990 }
2991 
2992 void kvm_arch_accel_class_init(ObjectClass *oc)
2993 {
2994 }
2995 
2996 static void kvm_cpu_accel_class_init(ObjectClass *oc, void *data)
2997 {
2998     AccelCPUClass *acc = ACCEL_CPU_CLASS(oc);
2999 
3000     acc->cpu_target_realize = kvmppc_cpu_realize;
3001 }
3002 
3003 static const TypeInfo kvm_cpu_accel_type_info = {
3004     .name = ACCEL_CPU_NAME("kvm"),
3005 
3006     .parent = TYPE_ACCEL_CPU,
3007     .class_init = kvm_cpu_accel_class_init,
3008     .abstract = true,
3009 };
3010 static void kvm_cpu_accel_register_types(void)
3011 {
3012     type_register_static(&kvm_cpu_accel_type_info);
3013 }
3014 type_init(kvm_cpu_accel_register_types);
3015