xref: /openbmc/qemu/target/riscv/kvm/kvm-cpu.c (revision 9c707525)
1 /*
2  * RISC-V implementation of KVM hooks
3  *
4  * Copyright (c) 2020 Huawei Technologies Co., Ltd
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2 or later, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "qemu/osdep.h"
20 #include <sys/ioctl.h>
21 #include <sys/prctl.h>
22 
23 #include <linux/kvm.h>
24 
25 #include "qemu/timer.h"
26 #include "qapi/error.h"
27 #include "qemu/error-report.h"
28 #include "qemu/main-loop.h"
29 #include "qapi/visitor.h"
30 #include "sysemu/sysemu.h"
31 #include "sysemu/kvm.h"
32 #include "sysemu/kvm_int.h"
33 #include "cpu.h"
34 #include "trace.h"
35 #include "hw/core/accel-cpu.h"
36 #include "hw/pci/pci.h"
37 #include "exec/memattrs.h"
38 #include "exec/address-spaces.h"
39 #include "hw/boards.h"
40 #include "hw/irq.h"
41 #include "hw/intc/riscv_imsic.h"
42 #include "qemu/log.h"
43 #include "hw/loader.h"
44 #include "kvm_riscv.h"
45 #include "sbi_ecall_interface.h"
46 #include "chardev/char-fe.h"
47 #include "migration/misc.h"
48 #include "sysemu/runstate.h"
49 #include "hw/riscv/numa.h"
50 
51 #define PR_RISCV_V_SET_CONTROL            69
52 #define PR_RISCV_V_VSTATE_CTRL_ON          2
53 
54 void riscv_kvm_aplic_request(void *opaque, int irq, int level)
55 {
56     kvm_set_irq(kvm_state, irq, !!level);
57 }
58 
59 static bool cap_has_mp_state;
60 
61 static uint64_t kvm_riscv_reg_id_ulong(CPURISCVState *env, uint64_t type,
62                                  uint64_t idx)
63 {
64     uint64_t id = KVM_REG_RISCV | type | idx;
65 
66     switch (riscv_cpu_mxl(env)) {
67     case MXL_RV32:
68         id |= KVM_REG_SIZE_U32;
69         break;
70     case MXL_RV64:
71         id |= KVM_REG_SIZE_U64;
72         break;
73     default:
74         g_assert_not_reached();
75     }
76     return id;
77 }
78 
79 static uint64_t kvm_riscv_reg_id_u32(uint64_t type, uint64_t idx)
80 {
81     return KVM_REG_RISCV | KVM_REG_SIZE_U32 | type | idx;
82 }
83 
84 static uint64_t kvm_riscv_reg_id_u64(uint64_t type, uint64_t idx)
85 {
86     return KVM_REG_RISCV | KVM_REG_SIZE_U64 | type | idx;
87 }
88 
89 static uint64_t kvm_encode_reg_size_id(uint64_t id, size_t size_b)
90 {
91     uint64_t size_ctz = __builtin_ctz(size_b);
92 
93     return id | (size_ctz << KVM_REG_SIZE_SHIFT);
94 }
95 
96 static uint64_t kvm_riscv_vector_reg_id(RISCVCPU *cpu,
97                                         uint64_t idx)
98 {
99     uint64_t id;
100     size_t size_b;
101 
102     g_assert(idx < 32);
103 
104     id = KVM_REG_RISCV | KVM_REG_RISCV_VECTOR | KVM_REG_RISCV_VECTOR_REG(idx);
105     size_b = cpu->cfg.vlenb;
106 
107     return kvm_encode_reg_size_id(id, size_b);
108 }
109 
110 #define RISCV_CORE_REG(env, name) \
111     kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CORE, \
112                            KVM_REG_RISCV_CORE_REG(name))
113 
114 #define RISCV_CSR_REG(env, name) \
115     kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CSR, \
116                            KVM_REG_RISCV_CSR_REG(name))
117 
118 #define RISCV_CONFIG_REG(env, name) \
119     kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CONFIG, \
120                            KVM_REG_RISCV_CONFIG_REG(name))
121 
122 #define RISCV_TIMER_REG(name)  kvm_riscv_reg_id_u64(KVM_REG_RISCV_TIMER, \
123                  KVM_REG_RISCV_TIMER_REG(name))
124 
125 #define RISCV_FP_F_REG(idx)  kvm_riscv_reg_id_u32(KVM_REG_RISCV_FP_F, idx)
126 
127 #define RISCV_FP_D_REG(idx)  kvm_riscv_reg_id_u64(KVM_REG_RISCV_FP_D, idx)
128 
129 #define RISCV_VECTOR_CSR_REG(env, name) \
130     kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_VECTOR, \
131                            KVM_REG_RISCV_VECTOR_CSR_REG(name))
132 
133 #define KVM_RISCV_GET_CSR(cs, env, csr, reg) \
134     do { \
135         int _ret = kvm_get_one_reg(cs, RISCV_CSR_REG(env, csr), &reg); \
136         if (_ret) { \
137             return _ret; \
138         } \
139     } while (0)
140 
141 #define KVM_RISCV_SET_CSR(cs, env, csr, reg) \
142     do { \
143         int _ret = kvm_set_one_reg(cs, RISCV_CSR_REG(env, csr), &reg); \
144         if (_ret) { \
145             return _ret; \
146         } \
147     } while (0)
148 
149 #define KVM_RISCV_GET_TIMER(cs, name, reg) \
150     do { \
151         int ret = kvm_get_one_reg(cs, RISCV_TIMER_REG(name), &reg); \
152         if (ret) { \
153             abort(); \
154         } \
155     } while (0)
156 
157 #define KVM_RISCV_SET_TIMER(cs, name, reg) \
158     do { \
159         int ret = kvm_set_one_reg(cs, RISCV_TIMER_REG(name), &reg); \
160         if (ret) { \
161             abort(); \
162         } \
163     } while (0)
164 
165 typedef struct KVMCPUConfig {
166     const char *name;
167     const char *description;
168     target_ulong offset;
169     uint64_t kvm_reg_id;
170     bool user_set;
171     bool supported;
172 } KVMCPUConfig;
173 
174 #define KVM_MISA_CFG(_bit, _reg_id) \
175     {.offset = _bit, .kvm_reg_id = _reg_id}
176 
177 /* KVM ISA extensions */
178 static KVMCPUConfig kvm_misa_ext_cfgs[] = {
179     KVM_MISA_CFG(RVA, KVM_RISCV_ISA_EXT_A),
180     KVM_MISA_CFG(RVC, KVM_RISCV_ISA_EXT_C),
181     KVM_MISA_CFG(RVD, KVM_RISCV_ISA_EXT_D),
182     KVM_MISA_CFG(RVF, KVM_RISCV_ISA_EXT_F),
183     KVM_MISA_CFG(RVH, KVM_RISCV_ISA_EXT_H),
184     KVM_MISA_CFG(RVI, KVM_RISCV_ISA_EXT_I),
185     KVM_MISA_CFG(RVM, KVM_RISCV_ISA_EXT_M),
186     KVM_MISA_CFG(RVV, KVM_RISCV_ISA_EXT_V),
187 };
188 
189 static void kvm_cpu_get_misa_ext_cfg(Object *obj, Visitor *v,
190                                      const char *name,
191                                      void *opaque, Error **errp)
192 {
193     KVMCPUConfig *misa_ext_cfg = opaque;
194     target_ulong misa_bit = misa_ext_cfg->offset;
195     RISCVCPU *cpu = RISCV_CPU(obj);
196     CPURISCVState *env = &cpu->env;
197     bool value = env->misa_ext_mask & misa_bit;
198 
199     visit_type_bool(v, name, &value, errp);
200 }
201 
202 static void kvm_cpu_set_misa_ext_cfg(Object *obj, Visitor *v,
203                                      const char *name,
204                                      void *opaque, Error **errp)
205 {
206     KVMCPUConfig *misa_ext_cfg = opaque;
207     target_ulong misa_bit = misa_ext_cfg->offset;
208     RISCVCPU *cpu = RISCV_CPU(obj);
209     CPURISCVState *env = &cpu->env;
210     bool value, host_bit;
211 
212     if (!visit_type_bool(v, name, &value, errp)) {
213         return;
214     }
215 
216     host_bit = env->misa_ext_mask & misa_bit;
217 
218     if (value == host_bit) {
219         return;
220     }
221 
222     if (!value) {
223         misa_ext_cfg->user_set = true;
224         return;
225     }
226 
227     /*
228      * Forbid users to enable extensions that aren't
229      * available in the hart.
230      */
231     error_setg(errp, "Enabling MISA bit '%s' is not allowed: it's not "
232                "enabled in the host", misa_ext_cfg->name);
233 }
234 
235 static void kvm_riscv_update_cpu_misa_ext(RISCVCPU *cpu, CPUState *cs)
236 {
237     CPURISCVState *env = &cpu->env;
238     uint64_t id, reg;
239     int i, ret;
240 
241     for (i = 0; i < ARRAY_SIZE(kvm_misa_ext_cfgs); i++) {
242         KVMCPUConfig *misa_cfg = &kvm_misa_ext_cfgs[i];
243         target_ulong misa_bit = misa_cfg->offset;
244 
245         if (!misa_cfg->user_set) {
246             continue;
247         }
248 
249         /* If we're here we're going to disable the MISA bit */
250         reg = 0;
251         id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_ISA_EXT,
252                                     misa_cfg->kvm_reg_id);
253         ret = kvm_set_one_reg(cs, id, &reg);
254         if (ret != 0) {
255             /*
256              * We're not checking for -EINVAL because if the bit is about
257              * to be disabled, it means that it was already enabled by
258              * KVM. We determined that by fetching the 'isa' register
259              * during init() time. Any error at this point is worth
260              * aborting.
261              */
262             error_report("Unable to set KVM reg %s, error %d",
263                          misa_cfg->name, ret);
264             exit(EXIT_FAILURE);
265         }
266         env->misa_ext &= ~misa_bit;
267     }
268 }
269 
270 #define KVM_EXT_CFG(_name, _prop, _reg_id) \
271     {.name = _name, .offset = CPU_CFG_OFFSET(_prop), \
272      .kvm_reg_id = _reg_id}
273 
274 static KVMCPUConfig kvm_multi_ext_cfgs[] = {
275     KVM_EXT_CFG("zicbom", ext_zicbom, KVM_RISCV_ISA_EXT_ZICBOM),
276     KVM_EXT_CFG("zicboz", ext_zicboz, KVM_RISCV_ISA_EXT_ZICBOZ),
277     KVM_EXT_CFG("zicntr", ext_zicntr, KVM_RISCV_ISA_EXT_ZICNTR),
278     KVM_EXT_CFG("zicond", ext_zicond, KVM_RISCV_ISA_EXT_ZICOND),
279     KVM_EXT_CFG("zicsr", ext_zicsr, KVM_RISCV_ISA_EXT_ZICSR),
280     KVM_EXT_CFG("zifencei", ext_zifencei, KVM_RISCV_ISA_EXT_ZIFENCEI),
281     KVM_EXT_CFG("zihintntl", ext_zihintntl, KVM_RISCV_ISA_EXT_ZIHINTNTL),
282     KVM_EXT_CFG("zihintpause", ext_zihintpause, KVM_RISCV_ISA_EXT_ZIHINTPAUSE),
283     KVM_EXT_CFG("zihpm", ext_zihpm, KVM_RISCV_ISA_EXT_ZIHPM),
284     KVM_EXT_CFG("zfa", ext_zfa, KVM_RISCV_ISA_EXT_ZFA),
285     KVM_EXT_CFG("zfh", ext_zfh, KVM_RISCV_ISA_EXT_ZFH),
286     KVM_EXT_CFG("zfhmin", ext_zfhmin, KVM_RISCV_ISA_EXT_ZFHMIN),
287     KVM_EXT_CFG("zba", ext_zba, KVM_RISCV_ISA_EXT_ZBA),
288     KVM_EXT_CFG("zbb", ext_zbb, KVM_RISCV_ISA_EXT_ZBB),
289     KVM_EXT_CFG("zbc", ext_zbc, KVM_RISCV_ISA_EXT_ZBC),
290     KVM_EXT_CFG("zbkb", ext_zbkb, KVM_RISCV_ISA_EXT_ZBKB),
291     KVM_EXT_CFG("zbkc", ext_zbkc, KVM_RISCV_ISA_EXT_ZBKC),
292     KVM_EXT_CFG("zbkx", ext_zbkx, KVM_RISCV_ISA_EXT_ZBKX),
293     KVM_EXT_CFG("zbs", ext_zbs, KVM_RISCV_ISA_EXT_ZBS),
294     KVM_EXT_CFG("zknd", ext_zknd, KVM_RISCV_ISA_EXT_ZKND),
295     KVM_EXT_CFG("zkne", ext_zkne, KVM_RISCV_ISA_EXT_ZKNE),
296     KVM_EXT_CFG("zknh", ext_zknh, KVM_RISCV_ISA_EXT_ZKNH),
297     KVM_EXT_CFG("zkr", ext_zkr, KVM_RISCV_ISA_EXT_ZKR),
298     KVM_EXT_CFG("zksed", ext_zksed, KVM_RISCV_ISA_EXT_ZKSED),
299     KVM_EXT_CFG("zksh", ext_zksh, KVM_RISCV_ISA_EXT_ZKSH),
300     KVM_EXT_CFG("zkt", ext_zkt, KVM_RISCV_ISA_EXT_ZKT),
301     KVM_EXT_CFG("zvbb", ext_zvbb, KVM_RISCV_ISA_EXT_ZVBB),
302     KVM_EXT_CFG("zvbc", ext_zvbc, KVM_RISCV_ISA_EXT_ZVBC),
303     KVM_EXT_CFG("zvfh", ext_zvfh, KVM_RISCV_ISA_EXT_ZVFH),
304     KVM_EXT_CFG("zvfhmin", ext_zvfhmin, KVM_RISCV_ISA_EXT_ZVFHMIN),
305     KVM_EXT_CFG("zvkb", ext_zvkb, KVM_RISCV_ISA_EXT_ZVKB),
306     KVM_EXT_CFG("zvkg", ext_zvkg, KVM_RISCV_ISA_EXT_ZVKG),
307     KVM_EXT_CFG("zvkned", ext_zvkned, KVM_RISCV_ISA_EXT_ZVKNED),
308     KVM_EXT_CFG("zvknha", ext_zvknha, KVM_RISCV_ISA_EXT_ZVKNHA),
309     KVM_EXT_CFG("zvknhb", ext_zvknhb, KVM_RISCV_ISA_EXT_ZVKNHB),
310     KVM_EXT_CFG("zvksed", ext_zvksed, KVM_RISCV_ISA_EXT_ZVKSED),
311     KVM_EXT_CFG("zvksh", ext_zvksh, KVM_RISCV_ISA_EXT_ZVKSH),
312     KVM_EXT_CFG("zvkt", ext_zvkt, KVM_RISCV_ISA_EXT_ZVKT),
313     KVM_EXT_CFG("smstateen", ext_smstateen, KVM_RISCV_ISA_EXT_SMSTATEEN),
314     KVM_EXT_CFG("ssaia", ext_ssaia, KVM_RISCV_ISA_EXT_SSAIA),
315     KVM_EXT_CFG("sstc", ext_sstc, KVM_RISCV_ISA_EXT_SSTC),
316     KVM_EXT_CFG("svinval", ext_svinval, KVM_RISCV_ISA_EXT_SVINVAL),
317     KVM_EXT_CFG("svnapot", ext_svnapot, KVM_RISCV_ISA_EXT_SVNAPOT),
318     KVM_EXT_CFG("svpbmt", ext_svpbmt, KVM_RISCV_ISA_EXT_SVPBMT),
319 };
320 
321 static void *kvmconfig_get_cfg_addr(RISCVCPU *cpu, KVMCPUConfig *kvmcfg)
322 {
323     return (void *)&cpu->cfg + kvmcfg->offset;
324 }
325 
326 static void kvm_cpu_cfg_set(RISCVCPU *cpu, KVMCPUConfig *multi_ext,
327                             uint32_t val)
328 {
329     bool *ext_enabled = kvmconfig_get_cfg_addr(cpu, multi_ext);
330 
331     *ext_enabled = val;
332 }
333 
334 static uint32_t kvm_cpu_cfg_get(RISCVCPU *cpu,
335                                 KVMCPUConfig *multi_ext)
336 {
337     bool *ext_enabled = kvmconfig_get_cfg_addr(cpu, multi_ext);
338 
339     return *ext_enabled;
340 }
341 
342 static void kvm_cpu_get_multi_ext_cfg(Object *obj, Visitor *v,
343                                       const char *name,
344                                       void *opaque, Error **errp)
345 {
346     KVMCPUConfig *multi_ext_cfg = opaque;
347     RISCVCPU *cpu = RISCV_CPU(obj);
348     bool value = kvm_cpu_cfg_get(cpu, multi_ext_cfg);
349 
350     visit_type_bool(v, name, &value, errp);
351 }
352 
353 static void kvm_cpu_set_multi_ext_cfg(Object *obj, Visitor *v,
354                                       const char *name,
355                                       void *opaque, Error **errp)
356 {
357     KVMCPUConfig *multi_ext_cfg = opaque;
358     RISCVCPU *cpu = RISCV_CPU(obj);
359     bool value, host_val;
360 
361     if (!visit_type_bool(v, name, &value, errp)) {
362         return;
363     }
364 
365     host_val = kvm_cpu_cfg_get(cpu, multi_ext_cfg);
366 
367     /*
368      * Ignore if the user is setting the same value
369      * as the host.
370      */
371     if (value == host_val) {
372         return;
373     }
374 
375     if (!multi_ext_cfg->supported) {
376         /*
377          * Error out if the user is trying to enable an
378          * extension that KVM doesn't support. Ignore
379          * option otherwise.
380          */
381         if (value) {
382             error_setg(errp, "KVM does not support disabling extension %s",
383                        multi_ext_cfg->name);
384         }
385 
386         return;
387     }
388 
389     multi_ext_cfg->user_set = true;
390     kvm_cpu_cfg_set(cpu, multi_ext_cfg, value);
391 }
392 
393 static KVMCPUConfig kvm_cbom_blocksize = {
394     .name = "cbom_blocksize",
395     .offset = CPU_CFG_OFFSET(cbom_blocksize),
396     .kvm_reg_id = KVM_REG_RISCV_CONFIG_REG(zicbom_block_size)
397 };
398 
399 static KVMCPUConfig kvm_cboz_blocksize = {
400     .name = "cboz_blocksize",
401     .offset = CPU_CFG_OFFSET(cboz_blocksize),
402     .kvm_reg_id = KVM_REG_RISCV_CONFIG_REG(zicboz_block_size)
403 };
404 
405 static KVMCPUConfig kvm_v_vlenb = {
406     .name = "vlenb",
407     .offset = CPU_CFG_OFFSET(vlenb),
408     .kvm_reg_id =  KVM_REG_RISCV | KVM_REG_SIZE_U64 | KVM_REG_RISCV_VECTOR |
409                    KVM_REG_RISCV_VECTOR_CSR_REG(vlenb)
410 };
411 
412 static void kvm_riscv_update_cpu_cfg_isa_ext(RISCVCPU *cpu, CPUState *cs)
413 {
414     CPURISCVState *env = &cpu->env;
415     uint64_t id, reg;
416     int i, ret;
417 
418     for (i = 0; i < ARRAY_SIZE(kvm_multi_ext_cfgs); i++) {
419         KVMCPUConfig *multi_ext_cfg = &kvm_multi_ext_cfgs[i];
420 
421         if (!multi_ext_cfg->user_set) {
422             continue;
423         }
424 
425         id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_ISA_EXT,
426                                     multi_ext_cfg->kvm_reg_id);
427         reg = kvm_cpu_cfg_get(cpu, multi_ext_cfg);
428         ret = kvm_set_one_reg(cs, id, &reg);
429         if (ret != 0) {
430             error_report("Unable to %s extension %s in KVM, error %d",
431                          reg ? "enable" : "disable",
432                          multi_ext_cfg->name, ret);
433             exit(EXIT_FAILURE);
434         }
435     }
436 }
437 
438 static void cpu_get_cfg_unavailable(Object *obj, Visitor *v,
439                                     const char *name,
440                                     void *opaque, Error **errp)
441 {
442     bool value = false;
443 
444     visit_type_bool(v, name, &value, errp);
445 }
446 
447 static void cpu_set_cfg_unavailable(Object *obj, Visitor *v,
448                                     const char *name,
449                                     void *opaque, Error **errp)
450 {
451     const char *propname = opaque;
452     bool value;
453 
454     if (!visit_type_bool(v, name, &value, errp)) {
455         return;
456     }
457 
458     if (value) {
459         error_setg(errp, "'%s' is not available with KVM",
460                    propname);
461     }
462 }
463 
464 static void riscv_cpu_add_kvm_unavail_prop(Object *obj, const char *prop_name)
465 {
466     /* Check if KVM created the property already */
467     if (object_property_find(obj, prop_name)) {
468         return;
469     }
470 
471     /*
472      * Set the default to disabled for every extension
473      * unknown to KVM and error out if the user attempts
474      * to enable any of them.
475      */
476     object_property_add(obj, prop_name, "bool",
477                         cpu_get_cfg_unavailable,
478                         cpu_set_cfg_unavailable,
479                         NULL, (void *)prop_name);
480 }
481 
482 static void riscv_cpu_add_kvm_unavail_prop_array(Object *obj,
483                                         const RISCVCPUMultiExtConfig *array)
484 {
485     const RISCVCPUMultiExtConfig *prop;
486 
487     g_assert(array);
488 
489     for (prop = array; prop && prop->name; prop++) {
490         riscv_cpu_add_kvm_unavail_prop(obj, prop->name);
491     }
492 }
493 
494 static void kvm_riscv_add_cpu_user_properties(Object *cpu_obj)
495 {
496     int i;
497 
498     riscv_add_satp_mode_properties(cpu_obj);
499 
500     for (i = 0; i < ARRAY_SIZE(kvm_misa_ext_cfgs); i++) {
501         KVMCPUConfig *misa_cfg = &kvm_misa_ext_cfgs[i];
502         int bit = misa_cfg->offset;
503 
504         misa_cfg->name = riscv_get_misa_ext_name(bit);
505         misa_cfg->description = riscv_get_misa_ext_description(bit);
506 
507         object_property_add(cpu_obj, misa_cfg->name, "bool",
508                             kvm_cpu_get_misa_ext_cfg,
509                             kvm_cpu_set_misa_ext_cfg,
510                             NULL, misa_cfg);
511         object_property_set_description(cpu_obj, misa_cfg->name,
512                                         misa_cfg->description);
513     }
514 
515     for (i = 0; misa_bits[i] != 0; i++) {
516         const char *ext_name = riscv_get_misa_ext_name(misa_bits[i]);
517         riscv_cpu_add_kvm_unavail_prop(cpu_obj, ext_name);
518     }
519 
520     for (i = 0; i < ARRAY_SIZE(kvm_multi_ext_cfgs); i++) {
521         KVMCPUConfig *multi_cfg = &kvm_multi_ext_cfgs[i];
522 
523         object_property_add(cpu_obj, multi_cfg->name, "bool",
524                             kvm_cpu_get_multi_ext_cfg,
525                             kvm_cpu_set_multi_ext_cfg,
526                             NULL, multi_cfg);
527     }
528 
529     riscv_cpu_add_kvm_unavail_prop_array(cpu_obj, riscv_cpu_extensions);
530     riscv_cpu_add_kvm_unavail_prop_array(cpu_obj, riscv_cpu_vendor_exts);
531     riscv_cpu_add_kvm_unavail_prop_array(cpu_obj, riscv_cpu_experimental_exts);
532 
533    /* We don't have the needed KVM support for profiles */
534     for (i = 0; riscv_profiles[i] != NULL; i++) {
535         riscv_cpu_add_kvm_unavail_prop(cpu_obj, riscv_profiles[i]->name);
536     }
537 }
538 
539 static int kvm_riscv_get_regs_core(CPUState *cs)
540 {
541     int ret = 0;
542     int i;
543     target_ulong reg;
544     CPURISCVState *env = &RISCV_CPU(cs)->env;
545 
546     ret = kvm_get_one_reg(cs, RISCV_CORE_REG(env, regs.pc), &reg);
547     if (ret) {
548         return ret;
549     }
550     env->pc = reg;
551 
552     for (i = 1; i < 32; i++) {
553         uint64_t id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CORE, i);
554         ret = kvm_get_one_reg(cs, id, &reg);
555         if (ret) {
556             return ret;
557         }
558         env->gpr[i] = reg;
559     }
560 
561     return ret;
562 }
563 
564 static int kvm_riscv_put_regs_core(CPUState *cs)
565 {
566     int ret = 0;
567     int i;
568     target_ulong reg;
569     CPURISCVState *env = &RISCV_CPU(cs)->env;
570 
571     reg = env->pc;
572     ret = kvm_set_one_reg(cs, RISCV_CORE_REG(env, regs.pc), &reg);
573     if (ret) {
574         return ret;
575     }
576 
577     for (i = 1; i < 32; i++) {
578         uint64_t id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CORE, i);
579         reg = env->gpr[i];
580         ret = kvm_set_one_reg(cs, id, &reg);
581         if (ret) {
582             return ret;
583         }
584     }
585 
586     return ret;
587 }
588 
589 static int kvm_riscv_get_regs_csr(CPUState *cs)
590 {
591     CPURISCVState *env = &RISCV_CPU(cs)->env;
592 
593     KVM_RISCV_GET_CSR(cs, env, sstatus, env->mstatus);
594     KVM_RISCV_GET_CSR(cs, env, sie, env->mie);
595     KVM_RISCV_GET_CSR(cs, env, stvec, env->stvec);
596     KVM_RISCV_GET_CSR(cs, env, sscratch, env->sscratch);
597     KVM_RISCV_GET_CSR(cs, env, sepc, env->sepc);
598     KVM_RISCV_GET_CSR(cs, env, scause, env->scause);
599     KVM_RISCV_GET_CSR(cs, env, stval, env->stval);
600     KVM_RISCV_GET_CSR(cs, env, sip, env->mip);
601     KVM_RISCV_GET_CSR(cs, env, satp, env->satp);
602 
603     return 0;
604 }
605 
606 static int kvm_riscv_put_regs_csr(CPUState *cs)
607 {
608     CPURISCVState *env = &RISCV_CPU(cs)->env;
609 
610     KVM_RISCV_SET_CSR(cs, env, sstatus, env->mstatus);
611     KVM_RISCV_SET_CSR(cs, env, sie, env->mie);
612     KVM_RISCV_SET_CSR(cs, env, stvec, env->stvec);
613     KVM_RISCV_SET_CSR(cs, env, sscratch, env->sscratch);
614     KVM_RISCV_SET_CSR(cs, env, sepc, env->sepc);
615     KVM_RISCV_SET_CSR(cs, env, scause, env->scause);
616     KVM_RISCV_SET_CSR(cs, env, stval, env->stval);
617     KVM_RISCV_SET_CSR(cs, env, sip, env->mip);
618     KVM_RISCV_SET_CSR(cs, env, satp, env->satp);
619 
620     return 0;
621 }
622 
623 static int kvm_riscv_get_regs_fp(CPUState *cs)
624 {
625     int ret = 0;
626     int i;
627     CPURISCVState *env = &RISCV_CPU(cs)->env;
628 
629     if (riscv_has_ext(env, RVD)) {
630         uint64_t reg;
631         for (i = 0; i < 32; i++) {
632             ret = kvm_get_one_reg(cs, RISCV_FP_D_REG(i), &reg);
633             if (ret) {
634                 return ret;
635             }
636             env->fpr[i] = reg;
637         }
638         return ret;
639     }
640 
641     if (riscv_has_ext(env, RVF)) {
642         uint32_t reg;
643         for (i = 0; i < 32; i++) {
644             ret = kvm_get_one_reg(cs, RISCV_FP_F_REG(i), &reg);
645             if (ret) {
646                 return ret;
647             }
648             env->fpr[i] = reg;
649         }
650         return ret;
651     }
652 
653     return ret;
654 }
655 
656 static int kvm_riscv_put_regs_fp(CPUState *cs)
657 {
658     int ret = 0;
659     int i;
660     CPURISCVState *env = &RISCV_CPU(cs)->env;
661 
662     if (riscv_has_ext(env, RVD)) {
663         uint64_t reg;
664         for (i = 0; i < 32; i++) {
665             reg = env->fpr[i];
666             ret = kvm_set_one_reg(cs, RISCV_FP_D_REG(i), &reg);
667             if (ret) {
668                 return ret;
669             }
670         }
671         return ret;
672     }
673 
674     if (riscv_has_ext(env, RVF)) {
675         uint32_t reg;
676         for (i = 0; i < 32; i++) {
677             reg = env->fpr[i];
678             ret = kvm_set_one_reg(cs, RISCV_FP_F_REG(i), &reg);
679             if (ret) {
680                 return ret;
681             }
682         }
683         return ret;
684     }
685 
686     return ret;
687 }
688 
689 static void kvm_riscv_get_regs_timer(CPUState *cs)
690 {
691     CPURISCVState *env = &RISCV_CPU(cs)->env;
692 
693     if (env->kvm_timer_dirty) {
694         return;
695     }
696 
697     KVM_RISCV_GET_TIMER(cs, time, env->kvm_timer_time);
698     KVM_RISCV_GET_TIMER(cs, compare, env->kvm_timer_compare);
699     KVM_RISCV_GET_TIMER(cs, state, env->kvm_timer_state);
700     KVM_RISCV_GET_TIMER(cs, frequency, env->kvm_timer_frequency);
701 
702     env->kvm_timer_dirty = true;
703 }
704 
705 static void kvm_riscv_put_regs_timer(CPUState *cs)
706 {
707     uint64_t reg;
708     CPURISCVState *env = &RISCV_CPU(cs)->env;
709 
710     if (!env->kvm_timer_dirty) {
711         return;
712     }
713 
714     KVM_RISCV_SET_TIMER(cs, time, env->kvm_timer_time);
715     KVM_RISCV_SET_TIMER(cs, compare, env->kvm_timer_compare);
716 
717     /*
718      * To set register of RISCV_TIMER_REG(state) will occur a error from KVM
719      * on env->kvm_timer_state == 0, It's better to adapt in KVM, but it
720      * doesn't matter that adaping in QEMU now.
721      * TODO If KVM changes, adapt here.
722      */
723     if (env->kvm_timer_state) {
724         KVM_RISCV_SET_TIMER(cs, state, env->kvm_timer_state);
725     }
726 
727     /*
728      * For now, migration will not work between Hosts with different timer
729      * frequency. Therefore, we should check whether they are the same here
730      * during the migration.
731      */
732     if (migration_is_running()) {
733         KVM_RISCV_GET_TIMER(cs, frequency, reg);
734         if (reg != env->kvm_timer_frequency) {
735             error_report("Dst Hosts timer frequency != Src Hosts");
736         }
737     }
738 
739     env->kvm_timer_dirty = false;
740 }
741 
742 static int kvm_riscv_get_regs_vector(CPUState *cs)
743 {
744     RISCVCPU *cpu = RISCV_CPU(cs);
745     CPURISCVState *env = &cpu->env;
746     target_ulong reg;
747     uint64_t vreg_id;
748     int vreg_idx, ret = 0;
749 
750     if (!riscv_has_ext(env, RVV)) {
751         return 0;
752     }
753 
754     ret = kvm_get_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vstart), &reg);
755     if (ret) {
756         return ret;
757     }
758     env->vstart = reg;
759 
760     ret = kvm_get_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vl), &reg);
761     if (ret) {
762         return ret;
763     }
764     env->vl = reg;
765 
766     ret = kvm_get_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vtype), &reg);
767     if (ret) {
768         return ret;
769     }
770     env->vtype = reg;
771 
772     if (kvm_v_vlenb.supported) {
773         ret = kvm_get_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vlenb), &reg);
774         if (ret) {
775             return ret;
776         }
777         cpu->cfg.vlenb = reg;
778 
779         for (int i = 0; i < 32; i++) {
780             /*
781              * vreg[] is statically allocated using RV_VLEN_MAX.
782              * Use it instead of vlenb to calculate vreg_idx for
783              * simplicity.
784              */
785             vreg_idx = i * RV_VLEN_MAX / 64;
786             vreg_id = kvm_riscv_vector_reg_id(cpu, i);
787 
788             ret = kvm_get_one_reg(cs, vreg_id, &env->vreg[vreg_idx]);
789             if (ret) {
790                 return ret;
791             }
792         }
793     }
794 
795     return 0;
796 }
797 
798 static int kvm_riscv_put_regs_vector(CPUState *cs)
799 {
800     RISCVCPU *cpu = RISCV_CPU(cs);
801     CPURISCVState *env = &cpu->env;
802     target_ulong reg;
803     uint64_t vreg_id;
804     int vreg_idx, ret = 0;
805 
806     if (!riscv_has_ext(env, RVV)) {
807         return 0;
808     }
809 
810     reg = env->vstart;
811     ret = kvm_set_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vstart), &reg);
812     if (ret) {
813         return ret;
814     }
815 
816     reg = env->vl;
817     ret = kvm_set_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vl), &reg);
818     if (ret) {
819         return ret;
820     }
821 
822     reg = env->vtype;
823     ret = kvm_set_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vtype), &reg);
824     if (ret) {
825         return ret;
826     }
827 
828     if (kvm_v_vlenb.supported) {
829         reg = cpu->cfg.vlenb;
830         ret = kvm_set_one_reg(cs, RISCV_VECTOR_CSR_REG(env, vlenb), &reg);
831 
832         for (int i = 0; i < 32; i++) {
833             /*
834              * vreg[] is statically allocated using RV_VLEN_MAX.
835              * Use it instead of vlenb to calculate vreg_idx for
836              * simplicity.
837              */
838             vreg_idx = i * RV_VLEN_MAX / 64;
839             vreg_id = kvm_riscv_vector_reg_id(cpu, i);
840 
841             ret = kvm_set_one_reg(cs, vreg_id, &env->vreg[vreg_idx]);
842             if (ret) {
843                 return ret;
844             }
845         }
846     }
847 
848     return ret;
849 }
850 
851 typedef struct KVMScratchCPU {
852     int kvmfd;
853     int vmfd;
854     int cpufd;
855 } KVMScratchCPU;
856 
857 /*
858  * Heavily inspired by kvm_arm_create_scratch_host_vcpu()
859  * from target/arm/kvm.c.
860  */
861 static bool kvm_riscv_create_scratch_vcpu(KVMScratchCPU *scratch)
862 {
863     int kvmfd = -1, vmfd = -1, cpufd = -1;
864 
865     kvmfd = qemu_open_old("/dev/kvm", O_RDWR);
866     if (kvmfd < 0) {
867         goto err;
868     }
869     do {
870         vmfd = ioctl(kvmfd, KVM_CREATE_VM, 0);
871     } while (vmfd == -1 && errno == EINTR);
872     if (vmfd < 0) {
873         goto err;
874     }
875     cpufd = ioctl(vmfd, KVM_CREATE_VCPU, 0);
876     if (cpufd < 0) {
877         goto err;
878     }
879 
880     scratch->kvmfd =  kvmfd;
881     scratch->vmfd = vmfd;
882     scratch->cpufd = cpufd;
883 
884     return true;
885 
886  err:
887     if (cpufd >= 0) {
888         close(cpufd);
889     }
890     if (vmfd >= 0) {
891         close(vmfd);
892     }
893     if (kvmfd >= 0) {
894         close(kvmfd);
895     }
896 
897     return false;
898 }
899 
900 static void kvm_riscv_destroy_scratch_vcpu(KVMScratchCPU *scratch)
901 {
902     close(scratch->cpufd);
903     close(scratch->vmfd);
904     close(scratch->kvmfd);
905 }
906 
907 static void kvm_riscv_init_machine_ids(RISCVCPU *cpu, KVMScratchCPU *kvmcpu)
908 {
909     CPURISCVState *env = &cpu->env;
910     struct kvm_one_reg reg;
911     int ret;
912 
913     reg.id = RISCV_CONFIG_REG(env, mvendorid);
914     reg.addr = (uint64_t)&cpu->cfg.mvendorid;
915     ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
916     if (ret != 0) {
917         error_report("Unable to retrieve mvendorid from host, error %d", ret);
918     }
919 
920     reg.id = RISCV_CONFIG_REG(env, marchid);
921     reg.addr = (uint64_t)&cpu->cfg.marchid;
922     ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
923     if (ret != 0) {
924         error_report("Unable to retrieve marchid from host, error %d", ret);
925     }
926 
927     reg.id = RISCV_CONFIG_REG(env, mimpid);
928     reg.addr = (uint64_t)&cpu->cfg.mimpid;
929     ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
930     if (ret != 0) {
931         error_report("Unable to retrieve mimpid from host, error %d", ret);
932     }
933 }
934 
935 static void kvm_riscv_init_misa_ext_mask(RISCVCPU *cpu,
936                                          KVMScratchCPU *kvmcpu)
937 {
938     CPURISCVState *env = &cpu->env;
939     struct kvm_one_reg reg;
940     int ret;
941 
942     reg.id = RISCV_CONFIG_REG(env, isa);
943     reg.addr = (uint64_t)&env->misa_ext_mask;
944     ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
945 
946     if (ret) {
947         error_report("Unable to fetch ISA register from KVM, "
948                      "error %d", ret);
949         kvm_riscv_destroy_scratch_vcpu(kvmcpu);
950         exit(EXIT_FAILURE);
951     }
952 
953     env->misa_ext = env->misa_ext_mask;
954 }
955 
956 static void kvm_riscv_read_cbomz_blksize(RISCVCPU *cpu, KVMScratchCPU *kvmcpu,
957                                          KVMCPUConfig *cbomz_cfg)
958 {
959     CPURISCVState *env = &cpu->env;
960     struct kvm_one_reg reg;
961     int ret;
962 
963     reg.id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CONFIG,
964                                     cbomz_cfg->kvm_reg_id);
965     reg.addr = (uint64_t)kvmconfig_get_cfg_addr(cpu, cbomz_cfg);
966     ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
967     if (ret != 0) {
968         error_report("Unable to read KVM reg %s, error %d",
969                      cbomz_cfg->name, ret);
970         exit(EXIT_FAILURE);
971     }
972 }
973 
974 static void kvm_riscv_read_multiext_legacy(RISCVCPU *cpu,
975                                            KVMScratchCPU *kvmcpu)
976 {
977     CPURISCVState *env = &cpu->env;
978     uint64_t val;
979     int i, ret;
980 
981     for (i = 0; i < ARRAY_SIZE(kvm_multi_ext_cfgs); i++) {
982         KVMCPUConfig *multi_ext_cfg = &kvm_multi_ext_cfgs[i];
983         struct kvm_one_reg reg;
984 
985         reg.id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_ISA_EXT,
986                                         multi_ext_cfg->kvm_reg_id);
987         reg.addr = (uint64_t)&val;
988         ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
989         if (ret != 0) {
990             if (errno == EINVAL) {
991                 /* Silently default to 'false' if KVM does not support it. */
992                 multi_ext_cfg->supported = false;
993                 val = false;
994             } else {
995                 error_report("Unable to read ISA_EXT KVM register %s: %s",
996                              multi_ext_cfg->name, strerror(errno));
997                 exit(EXIT_FAILURE);
998             }
999         } else {
1000             multi_ext_cfg->supported = true;
1001         }
1002 
1003         kvm_cpu_cfg_set(cpu, multi_ext_cfg, val);
1004     }
1005 
1006     if (cpu->cfg.ext_zicbom) {
1007         kvm_riscv_read_cbomz_blksize(cpu, kvmcpu, &kvm_cbom_blocksize);
1008     }
1009 
1010     if (cpu->cfg.ext_zicboz) {
1011         kvm_riscv_read_cbomz_blksize(cpu, kvmcpu, &kvm_cboz_blocksize);
1012     }
1013 }
1014 
1015 static int uint64_cmp(const void *a, const void *b)
1016 {
1017     uint64_t val1 = *(const uint64_t *)a;
1018     uint64_t val2 = *(const uint64_t *)b;
1019 
1020     if (val1 < val2) {
1021         return -1;
1022     }
1023 
1024     if (val1 > val2) {
1025         return 1;
1026     }
1027 
1028     return 0;
1029 }
1030 
1031 static void kvm_riscv_read_vlenb(RISCVCPU *cpu, KVMScratchCPU *kvmcpu,
1032                                  struct kvm_reg_list *reglist)
1033 {
1034     struct kvm_one_reg reg;
1035     struct kvm_reg_list *reg_search;
1036     uint64_t val;
1037     int ret;
1038 
1039     reg_search = bsearch(&kvm_v_vlenb.kvm_reg_id, reglist->reg, reglist->n,
1040                          sizeof(uint64_t), uint64_cmp);
1041 
1042     if (reg_search) {
1043         reg.id = kvm_v_vlenb.kvm_reg_id;
1044         reg.addr = (uint64_t)&val;
1045 
1046         ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
1047         if (ret != 0) {
1048             error_report("Unable to read vlenb register, error code: %s",
1049                          strerrorname_np(errno));
1050             exit(EXIT_FAILURE);
1051         }
1052 
1053         kvm_v_vlenb.supported = true;
1054         cpu->cfg.vlenb = val;
1055     }
1056 }
1057 
1058 static void kvm_riscv_init_multiext_cfg(RISCVCPU *cpu, KVMScratchCPU *kvmcpu)
1059 {
1060     KVMCPUConfig *multi_ext_cfg;
1061     struct kvm_one_reg reg;
1062     struct kvm_reg_list rl_struct;
1063     struct kvm_reg_list *reglist;
1064     uint64_t val, reg_id, *reg_search;
1065     int i, ret;
1066 
1067     rl_struct.n = 0;
1068     ret = ioctl(kvmcpu->cpufd, KVM_GET_REG_LIST, &rl_struct);
1069 
1070     /*
1071      * If KVM_GET_REG_LIST isn't supported we'll get errno 22
1072      * (EINVAL). Use read_legacy() in this case.
1073      */
1074     if (errno == EINVAL) {
1075         return kvm_riscv_read_multiext_legacy(cpu, kvmcpu);
1076     } else if (errno != E2BIG) {
1077         /*
1078          * E2BIG is an expected error message for the API since we
1079          * don't know the number of registers. The right amount will
1080          * be written in rl_struct.n.
1081          *
1082          * Error out if we get any other errno.
1083          */
1084         error_report("Error when accessing get-reg-list: %s",
1085                      strerror(errno));
1086         exit(EXIT_FAILURE);
1087     }
1088 
1089     reglist = g_malloc(sizeof(struct kvm_reg_list) +
1090                        rl_struct.n * sizeof(uint64_t));
1091     reglist->n = rl_struct.n;
1092     ret = ioctl(kvmcpu->cpufd, KVM_GET_REG_LIST, reglist);
1093     if (ret) {
1094         error_report("Error when reading KVM_GET_REG_LIST: %s",
1095                      strerror(errno));
1096         exit(EXIT_FAILURE);
1097     }
1098 
1099     /* sort reglist to use bsearch() */
1100     qsort(&reglist->reg, reglist->n, sizeof(uint64_t), uint64_cmp);
1101 
1102     for (i = 0; i < ARRAY_SIZE(kvm_multi_ext_cfgs); i++) {
1103         multi_ext_cfg = &kvm_multi_ext_cfgs[i];
1104         reg_id = kvm_riscv_reg_id_ulong(&cpu->env, KVM_REG_RISCV_ISA_EXT,
1105                                         multi_ext_cfg->kvm_reg_id);
1106         reg_search = bsearch(&reg_id, reglist->reg, reglist->n,
1107                              sizeof(uint64_t), uint64_cmp);
1108         if (!reg_search) {
1109             continue;
1110         }
1111 
1112         reg.id = reg_id;
1113         reg.addr = (uint64_t)&val;
1114         ret = ioctl(kvmcpu->cpufd, KVM_GET_ONE_REG, &reg);
1115         if (ret != 0) {
1116             error_report("Unable to read ISA_EXT KVM register %s: %s",
1117                          multi_ext_cfg->name, strerror(errno));
1118             exit(EXIT_FAILURE);
1119         }
1120 
1121         multi_ext_cfg->supported = true;
1122         kvm_cpu_cfg_set(cpu, multi_ext_cfg, val);
1123     }
1124 
1125     if (cpu->cfg.ext_zicbom) {
1126         kvm_riscv_read_cbomz_blksize(cpu, kvmcpu, &kvm_cbom_blocksize);
1127     }
1128 
1129     if (cpu->cfg.ext_zicboz) {
1130         kvm_riscv_read_cbomz_blksize(cpu, kvmcpu, &kvm_cboz_blocksize);
1131     }
1132 
1133     if (riscv_has_ext(&cpu->env, RVV)) {
1134         kvm_riscv_read_vlenb(cpu, kvmcpu, reglist);
1135     }
1136 }
1137 
1138 static void riscv_init_kvm_registers(Object *cpu_obj)
1139 {
1140     RISCVCPU *cpu = RISCV_CPU(cpu_obj);
1141     KVMScratchCPU kvmcpu;
1142 
1143     if (!kvm_riscv_create_scratch_vcpu(&kvmcpu)) {
1144         return;
1145     }
1146 
1147     kvm_riscv_init_machine_ids(cpu, &kvmcpu);
1148     kvm_riscv_init_misa_ext_mask(cpu, &kvmcpu);
1149     kvm_riscv_init_multiext_cfg(cpu, &kvmcpu);
1150 
1151     kvm_riscv_destroy_scratch_vcpu(&kvmcpu);
1152 }
1153 
1154 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
1155     KVM_CAP_LAST_INFO
1156 };
1157 
1158 int kvm_arch_get_registers(CPUState *cs)
1159 {
1160     int ret = 0;
1161 
1162     ret = kvm_riscv_get_regs_core(cs);
1163     if (ret) {
1164         return ret;
1165     }
1166 
1167     ret = kvm_riscv_get_regs_csr(cs);
1168     if (ret) {
1169         return ret;
1170     }
1171 
1172     ret = kvm_riscv_get_regs_fp(cs);
1173     if (ret) {
1174         return ret;
1175     }
1176 
1177     ret = kvm_riscv_get_regs_vector(cs);
1178     if (ret) {
1179         return ret;
1180     }
1181 
1182     return ret;
1183 }
1184 
1185 int kvm_riscv_sync_mpstate_to_kvm(RISCVCPU *cpu, int state)
1186 {
1187     if (cap_has_mp_state) {
1188         struct kvm_mp_state mp_state = {
1189             .mp_state = state
1190         };
1191 
1192         int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
1193         if (ret) {
1194             fprintf(stderr, "%s: failed to sync MP_STATE %d/%s\n",
1195                     __func__, ret, strerror(-ret));
1196             return -1;
1197         }
1198     }
1199 
1200     return 0;
1201 }
1202 
1203 int kvm_arch_put_registers(CPUState *cs, int level)
1204 {
1205     int ret = 0;
1206 
1207     ret = kvm_riscv_put_regs_core(cs);
1208     if (ret) {
1209         return ret;
1210     }
1211 
1212     ret = kvm_riscv_put_regs_csr(cs);
1213     if (ret) {
1214         return ret;
1215     }
1216 
1217     ret = kvm_riscv_put_regs_fp(cs);
1218     if (ret) {
1219         return ret;
1220     }
1221 
1222     ret = kvm_riscv_put_regs_vector(cs);
1223     if (ret) {
1224         return ret;
1225     }
1226 
1227     if (KVM_PUT_RESET_STATE == level) {
1228         RISCVCPU *cpu = RISCV_CPU(cs);
1229         if (cs->cpu_index == 0) {
1230             ret = kvm_riscv_sync_mpstate_to_kvm(cpu, KVM_MP_STATE_RUNNABLE);
1231         } else {
1232             ret = kvm_riscv_sync_mpstate_to_kvm(cpu, KVM_MP_STATE_STOPPED);
1233         }
1234         if (ret) {
1235             return ret;
1236         }
1237     }
1238 
1239     return ret;
1240 }
1241 
1242 int kvm_arch_release_virq_post(int virq)
1243 {
1244     return 0;
1245 }
1246 
1247 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
1248                              uint64_t address, uint32_t data, PCIDevice *dev)
1249 {
1250     return 0;
1251 }
1252 
1253 int kvm_arch_destroy_vcpu(CPUState *cs)
1254 {
1255     return 0;
1256 }
1257 
1258 unsigned long kvm_arch_vcpu_id(CPUState *cpu)
1259 {
1260     return cpu->cpu_index;
1261 }
1262 
1263 static void kvm_riscv_vm_state_change(void *opaque, bool running,
1264                                       RunState state)
1265 {
1266     CPUState *cs = opaque;
1267 
1268     if (running) {
1269         kvm_riscv_put_regs_timer(cs);
1270     } else {
1271         kvm_riscv_get_regs_timer(cs);
1272     }
1273 }
1274 
1275 void kvm_arch_init_irq_routing(KVMState *s)
1276 {
1277 }
1278 
1279 static int kvm_vcpu_set_machine_ids(RISCVCPU *cpu, CPUState *cs)
1280 {
1281     CPURISCVState *env = &cpu->env;
1282     target_ulong reg;
1283     uint64_t id;
1284     int ret;
1285 
1286     id = RISCV_CONFIG_REG(env, mvendorid);
1287     /*
1288      * cfg.mvendorid is an uint32 but a target_ulong will
1289      * be written. Assign it to a target_ulong var to avoid
1290      * writing pieces of other cpu->cfg fields in the reg.
1291      */
1292     reg = cpu->cfg.mvendorid;
1293     ret = kvm_set_one_reg(cs, id, &reg);
1294     if (ret != 0) {
1295         return ret;
1296     }
1297 
1298     id = RISCV_CONFIG_REG(env, marchid);
1299     ret = kvm_set_one_reg(cs, id, &cpu->cfg.marchid);
1300     if (ret != 0) {
1301         return ret;
1302     }
1303 
1304     id = RISCV_CONFIG_REG(env, mimpid);
1305     ret = kvm_set_one_reg(cs, id, &cpu->cfg.mimpid);
1306 
1307     return ret;
1308 }
1309 
1310 int kvm_arch_init_vcpu(CPUState *cs)
1311 {
1312     int ret = 0;
1313     RISCVCPU *cpu = RISCV_CPU(cs);
1314 
1315     qemu_add_vm_change_state_handler(kvm_riscv_vm_state_change, cs);
1316 
1317     if (!object_dynamic_cast(OBJECT(cpu), TYPE_RISCV_CPU_HOST)) {
1318         ret = kvm_vcpu_set_machine_ids(cpu, cs);
1319         if (ret != 0) {
1320             return ret;
1321         }
1322     }
1323 
1324     kvm_riscv_update_cpu_misa_ext(cpu, cs);
1325     kvm_riscv_update_cpu_cfg_isa_ext(cpu, cs);
1326 
1327     return ret;
1328 }
1329 
1330 int kvm_arch_msi_data_to_gsi(uint32_t data)
1331 {
1332     abort();
1333 }
1334 
1335 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
1336                                 int vector, PCIDevice *dev)
1337 {
1338     return 0;
1339 }
1340 
1341 int kvm_arch_get_default_type(MachineState *ms)
1342 {
1343     return 0;
1344 }
1345 
1346 int kvm_arch_init(MachineState *ms, KVMState *s)
1347 {
1348     cap_has_mp_state = kvm_check_extension(s, KVM_CAP_MP_STATE);
1349     return 0;
1350 }
1351 
1352 int kvm_arch_irqchip_create(KVMState *s)
1353 {
1354     if (kvm_kernel_irqchip_split()) {
1355         error_report("-machine kernel_irqchip=split is not supported on RISC-V.");
1356         exit(1);
1357     }
1358 
1359     /*
1360      * We can create the VAIA using the newer device control API.
1361      */
1362     return kvm_check_extension(s, KVM_CAP_DEVICE_CTRL);
1363 }
1364 
1365 int kvm_arch_process_async_events(CPUState *cs)
1366 {
1367     return 0;
1368 }
1369 
1370 void kvm_arch_pre_run(CPUState *cs, struct kvm_run *run)
1371 {
1372 }
1373 
1374 MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)
1375 {
1376     return MEMTXATTRS_UNSPECIFIED;
1377 }
1378 
1379 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
1380 {
1381     return true;
1382 }
1383 
1384 static int kvm_riscv_handle_sbi(CPUState *cs, struct kvm_run *run)
1385 {
1386     int ret = 0;
1387     unsigned char ch;
1388     switch (run->riscv_sbi.extension_id) {
1389     case SBI_EXT_0_1_CONSOLE_PUTCHAR:
1390         ch = run->riscv_sbi.args[0];
1391         qemu_chr_fe_write(serial_hd(0)->be, &ch, sizeof(ch));
1392         break;
1393     case SBI_EXT_0_1_CONSOLE_GETCHAR:
1394         ret = qemu_chr_fe_read_all(serial_hd(0)->be, &ch, sizeof(ch));
1395         if (ret == sizeof(ch)) {
1396             run->riscv_sbi.ret[0] = ch;
1397         } else {
1398             run->riscv_sbi.ret[0] = -1;
1399         }
1400         ret = 0;
1401         break;
1402     default:
1403         qemu_log_mask(LOG_UNIMP,
1404                       "%s: un-handled SBI EXIT, specific reasons is %lu\n",
1405                       __func__, run->riscv_sbi.extension_id);
1406         ret = -1;
1407         break;
1408     }
1409     return ret;
1410 }
1411 
1412 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
1413 {
1414     int ret = 0;
1415     switch (run->exit_reason) {
1416     case KVM_EXIT_RISCV_SBI:
1417         ret = kvm_riscv_handle_sbi(cs, run);
1418         break;
1419     default:
1420         qemu_log_mask(LOG_UNIMP, "%s: un-handled exit reason %d\n",
1421                       __func__, run->exit_reason);
1422         ret = -1;
1423         break;
1424     }
1425     return ret;
1426 }
1427 
1428 void kvm_riscv_reset_vcpu(RISCVCPU *cpu)
1429 {
1430     CPURISCVState *env = &cpu->env;
1431     int i;
1432 
1433     if (!kvm_enabled()) {
1434         return;
1435     }
1436     for (i = 0; i < 32; i++) {
1437         env->gpr[i] = 0;
1438     }
1439     env->pc = cpu->env.kernel_addr;
1440     env->gpr[10] = kvm_arch_vcpu_id(CPU(cpu)); /* a0 */
1441     env->gpr[11] = cpu->env.fdt_addr;          /* a1 */
1442     env->satp = 0;
1443     env->mie = 0;
1444     env->stvec = 0;
1445     env->sscratch = 0;
1446     env->sepc = 0;
1447     env->scause = 0;
1448     env->stval = 0;
1449     env->mip = 0;
1450 }
1451 
1452 void kvm_riscv_set_irq(RISCVCPU *cpu, int irq, int level)
1453 {
1454     int ret;
1455     unsigned virq = level ? KVM_INTERRUPT_SET : KVM_INTERRUPT_UNSET;
1456 
1457     if (irq != IRQ_S_EXT) {
1458         perror("kvm riscv set irq != IRQ_S_EXT\n");
1459         abort();
1460     }
1461 
1462     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_INTERRUPT, &virq);
1463     if (ret < 0) {
1464         perror("Set irq failed");
1465         abort();
1466     }
1467 }
1468 
1469 bool kvm_arch_cpu_check_are_resettable(void)
1470 {
1471     return true;
1472 }
1473 
1474 static int aia_mode;
1475 
1476 static const char *kvm_aia_mode_str(uint64_t mode)
1477 {
1478     switch (mode) {
1479     case KVM_DEV_RISCV_AIA_MODE_EMUL:
1480         return "emul";
1481     case KVM_DEV_RISCV_AIA_MODE_HWACCEL:
1482         return "hwaccel";
1483     case KVM_DEV_RISCV_AIA_MODE_AUTO:
1484     default:
1485         return "auto";
1486     };
1487 }
1488 
1489 static char *riscv_get_kvm_aia(Object *obj, Error **errp)
1490 {
1491     return g_strdup(kvm_aia_mode_str(aia_mode));
1492 }
1493 
1494 static void riscv_set_kvm_aia(Object *obj, const char *val, Error **errp)
1495 {
1496     if (!strcmp(val, "emul")) {
1497         aia_mode = KVM_DEV_RISCV_AIA_MODE_EMUL;
1498     } else if (!strcmp(val, "hwaccel")) {
1499         aia_mode = KVM_DEV_RISCV_AIA_MODE_HWACCEL;
1500     } else if (!strcmp(val, "auto")) {
1501         aia_mode = KVM_DEV_RISCV_AIA_MODE_AUTO;
1502     } else {
1503         error_setg(errp, "Invalid KVM AIA mode");
1504         error_append_hint(errp, "Valid values are emul, hwaccel, and auto.\n");
1505     }
1506 }
1507 
1508 void kvm_arch_accel_class_init(ObjectClass *oc)
1509 {
1510     object_class_property_add_str(oc, "riscv-aia", riscv_get_kvm_aia,
1511                                   riscv_set_kvm_aia);
1512     object_class_property_set_description(oc, "riscv-aia",
1513                                           "Set KVM AIA mode. Valid values are "
1514                                           "emul, hwaccel, and auto. Default "
1515                                           "is auto.");
1516     object_property_set_default_str(object_class_property_find(oc, "riscv-aia"),
1517                                     "auto");
1518 }
1519 
1520 void kvm_riscv_aia_create(MachineState *machine, uint64_t group_shift,
1521                           uint64_t aia_irq_num, uint64_t aia_msi_num,
1522                           uint64_t aplic_base, uint64_t imsic_base,
1523                           uint64_t guest_num)
1524 {
1525     int ret, i;
1526     int aia_fd = -1;
1527     uint64_t default_aia_mode;
1528     uint64_t socket_count = riscv_socket_count(machine);
1529     uint64_t max_hart_per_socket = 0;
1530     uint64_t socket, base_hart, hart_count, socket_imsic_base, imsic_addr;
1531     uint64_t socket_bits, hart_bits, guest_bits;
1532 
1533     aia_fd = kvm_create_device(kvm_state, KVM_DEV_TYPE_RISCV_AIA, false);
1534 
1535     if (aia_fd < 0) {
1536         error_report("Unable to create in-kernel irqchip");
1537         exit(1);
1538     }
1539 
1540     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1541                             KVM_DEV_RISCV_AIA_CONFIG_MODE,
1542                             &default_aia_mode, false, NULL);
1543     if (ret < 0) {
1544         error_report("KVM AIA: failed to get current KVM AIA mode");
1545         exit(1);
1546     }
1547     qemu_log("KVM AIA: default mode is %s\n",
1548              kvm_aia_mode_str(default_aia_mode));
1549 
1550     if (default_aia_mode != aia_mode) {
1551         ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1552                                 KVM_DEV_RISCV_AIA_CONFIG_MODE,
1553                                 &aia_mode, true, NULL);
1554         if (ret < 0)
1555             warn_report("KVM AIA: failed to set KVM AIA mode");
1556         else
1557             qemu_log("KVM AIA: set current mode to %s\n",
1558                      kvm_aia_mode_str(aia_mode));
1559     }
1560 
1561     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1562                             KVM_DEV_RISCV_AIA_CONFIG_SRCS,
1563                             &aia_irq_num, true, NULL);
1564     if (ret < 0) {
1565         error_report("KVM AIA: failed to set number of input irq lines");
1566         exit(1);
1567     }
1568 
1569     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1570                             KVM_DEV_RISCV_AIA_CONFIG_IDS,
1571                             &aia_msi_num, true, NULL);
1572     if (ret < 0) {
1573         error_report("KVM AIA: failed to set number of msi");
1574         exit(1);
1575     }
1576 
1577 
1578     if (socket_count > 1) {
1579         socket_bits = find_last_bit(&socket_count, BITS_PER_LONG) + 1;
1580         ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1581                                 KVM_DEV_RISCV_AIA_CONFIG_GROUP_BITS,
1582                                 &socket_bits, true, NULL);
1583         if (ret < 0) {
1584             error_report("KVM AIA: failed to set group_bits");
1585             exit(1);
1586         }
1587 
1588         ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1589                                 KVM_DEV_RISCV_AIA_CONFIG_GROUP_SHIFT,
1590                                 &group_shift, true, NULL);
1591         if (ret < 0) {
1592             error_report("KVM AIA: failed to set group_shift");
1593             exit(1);
1594         }
1595     }
1596 
1597     guest_bits = guest_num == 0 ? 0 :
1598                  find_last_bit(&guest_num, BITS_PER_LONG) + 1;
1599     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1600                             KVM_DEV_RISCV_AIA_CONFIG_GUEST_BITS,
1601                             &guest_bits, true, NULL);
1602     if (ret < 0) {
1603         error_report("KVM AIA: failed to set guest_bits");
1604         exit(1);
1605     }
1606 
1607     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_ADDR,
1608                             KVM_DEV_RISCV_AIA_ADDR_APLIC,
1609                             &aplic_base, true, NULL);
1610     if (ret < 0) {
1611         error_report("KVM AIA: failed to set the base address of APLIC");
1612         exit(1);
1613     }
1614 
1615     for (socket = 0; socket < socket_count; socket++) {
1616         socket_imsic_base = imsic_base + socket * (1U << group_shift);
1617         hart_count = riscv_socket_hart_count(machine, socket);
1618         base_hart = riscv_socket_first_hartid(machine, socket);
1619 
1620         if (max_hart_per_socket < hart_count) {
1621             max_hart_per_socket = hart_count;
1622         }
1623 
1624         for (i = 0; i < hart_count; i++) {
1625             imsic_addr = socket_imsic_base + i * IMSIC_HART_SIZE(guest_bits);
1626             ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_ADDR,
1627                                     KVM_DEV_RISCV_AIA_ADDR_IMSIC(i + base_hart),
1628                                     &imsic_addr, true, NULL);
1629             if (ret < 0) {
1630                 error_report("KVM AIA: failed to set the IMSIC address for hart %d", i);
1631                 exit(1);
1632             }
1633         }
1634     }
1635 
1636     hart_bits = find_last_bit(&max_hart_per_socket, BITS_PER_LONG) + 1;
1637     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CONFIG,
1638                             KVM_DEV_RISCV_AIA_CONFIG_HART_BITS,
1639                             &hart_bits, true, NULL);
1640     if (ret < 0) {
1641         error_report("KVM AIA: failed to set hart_bits");
1642         exit(1);
1643     }
1644 
1645     if (kvm_has_gsi_routing()) {
1646         for (uint64_t idx = 0; idx < aia_irq_num + 1; ++idx) {
1647             /* KVM AIA only has one APLIC instance */
1648             kvm_irqchip_add_irq_route(kvm_state, idx, 0, idx);
1649         }
1650         kvm_gsi_routing_allowed = true;
1651         kvm_irqchip_commit_routes(kvm_state);
1652     }
1653 
1654     ret = kvm_device_access(aia_fd, KVM_DEV_RISCV_AIA_GRP_CTRL,
1655                             KVM_DEV_RISCV_AIA_CTRL_INIT,
1656                             NULL, true, NULL);
1657     if (ret < 0) {
1658         error_report("KVM AIA: initialized fail");
1659         exit(1);
1660     }
1661 
1662     kvm_msi_via_irqfd_allowed = true;
1663 }
1664 
1665 static void kvm_cpu_instance_init(CPUState *cs)
1666 {
1667     Object *obj = OBJECT(RISCV_CPU(cs));
1668 
1669     riscv_init_kvm_registers(obj);
1670 
1671     kvm_riscv_add_cpu_user_properties(obj);
1672 }
1673 
1674 /*
1675  * We'll get here via the following path:
1676  *
1677  * riscv_cpu_realize()
1678  *   -> cpu_exec_realizefn()
1679  *      -> kvm_cpu_realize() (via accel_cpu_common_realize())
1680  */
1681 static bool kvm_cpu_realize(CPUState *cs, Error **errp)
1682 {
1683     RISCVCPU *cpu = RISCV_CPU(cs);
1684     int ret;
1685 
1686     if (riscv_has_ext(&cpu->env, RVV)) {
1687         ret = prctl(PR_RISCV_V_SET_CONTROL, PR_RISCV_V_VSTATE_CTRL_ON);
1688         if (ret) {
1689             error_setg(errp, "Error in prctl PR_RISCV_V_SET_CONTROL, code: %s",
1690                        strerrorname_np(errno));
1691             return false;
1692         }
1693     }
1694 
1695    return true;
1696 }
1697 
1698 void riscv_kvm_cpu_finalize_features(RISCVCPU *cpu, Error **errp)
1699 {
1700     CPURISCVState *env = &cpu->env;
1701     KVMScratchCPU kvmcpu;
1702     struct kvm_one_reg reg;
1703     uint64_t val;
1704     int ret;
1705 
1706     /* short-circuit without spinning the scratch CPU */
1707     if (!cpu->cfg.ext_zicbom && !cpu->cfg.ext_zicboz &&
1708         !riscv_has_ext(env, RVV)) {
1709         return;
1710     }
1711 
1712     if (!kvm_riscv_create_scratch_vcpu(&kvmcpu)) {
1713         error_setg(errp, "Unable to create scratch KVM cpu");
1714         return;
1715     }
1716 
1717     if (cpu->cfg.ext_zicbom &&
1718         riscv_cpu_option_set(kvm_cbom_blocksize.name)) {
1719 
1720         reg.id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CONFIG,
1721                                         kvm_cbom_blocksize.kvm_reg_id);
1722         reg.addr = (uint64_t)&val;
1723         ret = ioctl(kvmcpu.cpufd, KVM_GET_ONE_REG, &reg);
1724         if (ret != 0) {
1725             error_setg(errp, "Unable to read cbom_blocksize, error %d", errno);
1726             return;
1727         }
1728 
1729         if (cpu->cfg.cbom_blocksize != val) {
1730             error_setg(errp, "Unable to set cbom_blocksize to a different "
1731                        "value than the host (%lu)", val);
1732             return;
1733         }
1734     }
1735 
1736     if (cpu->cfg.ext_zicboz &&
1737         riscv_cpu_option_set(kvm_cboz_blocksize.name)) {
1738 
1739         reg.id = kvm_riscv_reg_id_ulong(env, KVM_REG_RISCV_CONFIG,
1740                                         kvm_cboz_blocksize.kvm_reg_id);
1741         reg.addr = (uint64_t)&val;
1742         ret = ioctl(kvmcpu.cpufd, KVM_GET_ONE_REG, &reg);
1743         if (ret != 0) {
1744             error_setg(errp, "Unable to read cboz_blocksize, error %d", errno);
1745             return;
1746         }
1747 
1748         if (cpu->cfg.cboz_blocksize != val) {
1749             error_setg(errp, "Unable to set cboz_blocksize to a different "
1750                        "value than the host (%lu)", val);
1751             return;
1752         }
1753     }
1754 
1755     /* Users are setting vlen, not vlenb */
1756     if (riscv_has_ext(env, RVV) && riscv_cpu_option_set("vlen")) {
1757         if (!kvm_v_vlenb.supported) {
1758             error_setg(errp, "Unable to set 'vlenb': register not supported");
1759             return;
1760         }
1761 
1762         reg.id = kvm_v_vlenb.kvm_reg_id;
1763         reg.addr = (uint64_t)&val;
1764         ret = ioctl(kvmcpu.cpufd, KVM_GET_ONE_REG, &reg);
1765         if (ret != 0) {
1766             error_setg(errp, "Unable to read vlenb register, error %d", errno);
1767             return;
1768         }
1769 
1770         if (cpu->cfg.vlenb != val) {
1771             error_setg(errp, "Unable to set 'vlen' to a different "
1772                        "value than the host (%lu)", val * 8);
1773             return;
1774         }
1775     }
1776 
1777     kvm_riscv_destroy_scratch_vcpu(&kvmcpu);
1778 }
1779 
1780 static void kvm_cpu_accel_class_init(ObjectClass *oc, void *data)
1781 {
1782     AccelCPUClass *acc = ACCEL_CPU_CLASS(oc);
1783 
1784     acc->cpu_instance_init = kvm_cpu_instance_init;
1785     acc->cpu_target_realize = kvm_cpu_realize;
1786 }
1787 
1788 static const TypeInfo kvm_cpu_accel_type_info = {
1789     .name = ACCEL_CPU_NAME("kvm"),
1790 
1791     .parent = TYPE_ACCEL_CPU,
1792     .class_init = kvm_cpu_accel_class_init,
1793     .abstract = true,
1794 };
1795 static void kvm_cpu_accel_register_types(void)
1796 {
1797     type_register_static(&kvm_cpu_accel_type_info);
1798 }
1799 type_init(kvm_cpu_accel_register_types);
1800 
1801 static void riscv_host_cpu_class_init(ObjectClass *c, void *data)
1802 {
1803     RISCVCPUClass *mcc = RISCV_CPU_CLASS(c);
1804 
1805 #if defined(TARGET_RISCV32)
1806     mcc->misa_mxl_max = MXL_RV32;
1807 #elif defined(TARGET_RISCV64)
1808     mcc->misa_mxl_max = MXL_RV64;
1809 #endif
1810 }
1811 
1812 static const TypeInfo riscv_kvm_cpu_type_infos[] = {
1813     {
1814         .name = TYPE_RISCV_CPU_HOST,
1815         .parent = TYPE_RISCV_CPU,
1816         .class_init = riscv_host_cpu_class_init,
1817     }
1818 };
1819 
1820 DEFINE_TYPES(riscv_kvm_cpu_type_infos)
1821