qemu/target/s390x/kvm/kvm.c
<<
>>
Prefs
   1/*
   2 * QEMU S390x KVM implementation
   3 *
   4 * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
   5 * Copyright IBM Corp. 2012
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License as published by
   9 * the Free Software Foundation; either version 2 of the License, or
  10 * (at your option) any later version.
  11 *
  12 * This program is distributed in the hope that it will be useful,
  13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15 * General Public License for more details.
  16 *
  17 * You should have received a copy of the GNU General Public License
  18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
  19 */
  20
  21#include "qemu/osdep.h"
  22#include <sys/ioctl.h>
  23
  24#include <linux/kvm.h>
  25#include <asm/ptrace.h>
  26
  27#include "qemu-common.h"
  28#include "cpu.h"
  29#include "s390x-internal.h"
  30#include "kvm_s390x.h"
  31#include "sysemu/kvm_int.h"
  32#include "qemu/cutils.h"
  33#include "qapi/error.h"
  34#include "qemu/error-report.h"
  35#include "qemu/timer.h"
  36#include "qemu/units.h"
  37#include "qemu/main-loop.h"
  38#include "qemu/mmap-alloc.h"
  39#include "qemu/log.h"
  40#include "sysemu/sysemu.h"
  41#include "sysemu/hw_accel.h"
  42#include "sysemu/runstate.h"
  43#include "sysemu/device_tree.h"
  44#include "exec/gdbstub.h"
  45#include "exec/ram_addr.h"
  46#include "trace.h"
  47#include "hw/s390x/s390-pci-inst.h"
  48#include "hw/s390x/s390-pci-bus.h"
  49#include "hw/s390x/ipl.h"
  50#include "hw/s390x/ebcdic.h"
  51#include "exec/memattrs.h"
  52#include "hw/s390x/s390-virtio-ccw.h"
  53#include "hw/s390x/s390-virtio-hcall.h"
  54#include "hw/s390x/pv.h"
  55
  56#ifndef DEBUG_KVM
  57#define DEBUG_KVM  0
  58#endif
  59
  60#define DPRINTF(fmt, ...) do {                \
  61    if (DEBUG_KVM) {                          \
  62        fprintf(stderr, fmt, ## __VA_ARGS__); \
  63    }                                         \
  64} while (0)
  65
  66#define kvm_vm_check_mem_attr(s, attr) \
  67    kvm_vm_check_attr(s, KVM_S390_VM_MEM_CTRL, attr)
  68
  69#define IPA0_DIAG                       0x8300
  70#define IPA0_SIGP                       0xae00
  71#define IPA0_B2                         0xb200
  72#define IPA0_B9                         0xb900
  73#define IPA0_EB                         0xeb00
  74#define IPA0_E3                         0xe300
  75
  76#define PRIV_B2_SCLP_CALL               0x20
  77#define PRIV_B2_CSCH                    0x30
  78#define PRIV_B2_HSCH                    0x31
  79#define PRIV_B2_MSCH                    0x32
  80#define PRIV_B2_SSCH                    0x33
  81#define PRIV_B2_STSCH                   0x34
  82#define PRIV_B2_TSCH                    0x35
  83#define PRIV_B2_TPI                     0x36
  84#define PRIV_B2_SAL                     0x37
  85#define PRIV_B2_RSCH                    0x38
  86#define PRIV_B2_STCRW                   0x39
  87#define PRIV_B2_STCPS                   0x3a
  88#define PRIV_B2_RCHP                    0x3b
  89#define PRIV_B2_SCHM                    0x3c
  90#define PRIV_B2_CHSC                    0x5f
  91#define PRIV_B2_SIGA                    0x74
  92#define PRIV_B2_XSCH                    0x76
  93
  94#define PRIV_EB_SQBS                    0x8a
  95#define PRIV_EB_PCISTB                  0xd0
  96#define PRIV_EB_SIC                     0xd1
  97
  98#define PRIV_B9_EQBS                    0x9c
  99#define PRIV_B9_CLP                     0xa0
 100#define PRIV_B9_PCISTG                  0xd0
 101#define PRIV_B9_PCILG                   0xd2
 102#define PRIV_B9_RPCIT                   0xd3
 103
 104#define PRIV_E3_MPCIFC                  0xd0
 105#define PRIV_E3_STPCIFC                 0xd4
 106
 107#define DIAG_TIMEREVENT                 0x288
 108#define DIAG_IPL                        0x308
 109#define DIAG_SET_CONTROL_PROGRAM_CODES  0x318
 110#define DIAG_KVM_HYPERCALL              0x500
 111#define DIAG_KVM_BREAKPOINT             0x501
 112
 113#define ICPT_INSTRUCTION                0x04
 114#define ICPT_PROGRAM                    0x08
 115#define ICPT_EXT_INT                    0x14
 116#define ICPT_WAITPSW                    0x1c
 117#define ICPT_SOFT_INTERCEPT             0x24
 118#define ICPT_CPU_STOP                   0x28
 119#define ICPT_OPEREXC                    0x2c
 120#define ICPT_IO                         0x40
 121#define ICPT_PV_INSTR                   0x68
 122#define ICPT_PV_INSTR_NOTIFICATION      0x6c
 123
 124#define NR_LOCAL_IRQS 32
 125/*
 126 * Needs to be big enough to contain max_cpus emergency signals
 127 * and in addition NR_LOCAL_IRQS interrupts
 128 */
 129#define VCPU_IRQ_BUF_SIZE(max_cpus) (sizeof(struct kvm_s390_irq) * \
 130                                     (max_cpus + NR_LOCAL_IRQS))
 131/*
 132 * KVM does only support memory slots up to KVM_MEM_MAX_NR_PAGES pages
 133 * as the dirty bitmap must be managed by bitops that take an int as
 134 * position indicator. This would end at an unaligned  address
 135 * (0x7fffff00000). As future variants might provide larger pages
 136 * and to make all addresses properly aligned, let us split at 4TB.
 137 */
 138#define KVM_SLOT_MAX_BYTES (4UL * TiB)
 139
 140static CPUWatchpoint hw_watchpoint;
 141/*
 142 * We don't use a list because this structure is also used to transmit the
 143 * hardware breakpoints to the kernel.
 144 */
 145static struct kvm_hw_breakpoint *hw_breakpoints;
 146static int nb_hw_breakpoints;
 147
 148const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
 149    KVM_CAP_LAST_INFO
 150};
 151
 152static int cap_sync_regs;
 153static int cap_async_pf;
 154static int cap_mem_op;
 155static int cap_s390_irq;
 156static int cap_ri;
 157static int cap_hpage_1m;
 158static int cap_vcpu_resets;
 159static int cap_protected;
 160
 161static int active_cmma;
 162
 163static int kvm_s390_query_mem_limit(uint64_t *memory_limit)
 164{
 165    struct kvm_device_attr attr = {
 166        .group = KVM_S390_VM_MEM_CTRL,
 167        .attr = KVM_S390_VM_MEM_LIMIT_SIZE,
 168        .addr = (uint64_t) memory_limit,
 169    };
 170
 171    return kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
 172}
 173
 174int kvm_s390_set_mem_limit(uint64_t new_limit, uint64_t *hw_limit)
 175{
 176    int rc;
 177
 178    struct kvm_device_attr attr = {
 179        .group = KVM_S390_VM_MEM_CTRL,
 180        .attr = KVM_S390_VM_MEM_LIMIT_SIZE,
 181        .addr = (uint64_t) &new_limit,
 182    };
 183
 184    if (!kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_LIMIT_SIZE)) {
 185        return 0;
 186    }
 187
 188    rc = kvm_s390_query_mem_limit(hw_limit);
 189    if (rc) {
 190        return rc;
 191    } else if (*hw_limit < new_limit) {
 192        return -E2BIG;
 193    }
 194
 195    return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 196}
 197
 198int kvm_s390_cmma_active(void)
 199{
 200    return active_cmma;
 201}
 202
 203static bool kvm_s390_cmma_available(void)
 204{
 205    static bool initialized, value;
 206
 207    if (!initialized) {
 208        initialized = true;
 209        value = kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_ENABLE_CMMA) &&
 210                kvm_vm_check_mem_attr(kvm_state, KVM_S390_VM_MEM_CLR_CMMA);
 211    }
 212    return value;
 213}
 214
 215void kvm_s390_cmma_reset(void)
 216{
 217    int rc;
 218    struct kvm_device_attr attr = {
 219        .group = KVM_S390_VM_MEM_CTRL,
 220        .attr = KVM_S390_VM_MEM_CLR_CMMA,
 221    };
 222
 223    if (!kvm_s390_cmma_active()) {
 224        return;
 225    }
 226
 227    rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 228    trace_kvm_clear_cmma(rc);
 229}
 230
 231static void kvm_s390_enable_cmma(void)
 232{
 233    int rc;
 234    struct kvm_device_attr attr = {
 235        .group = KVM_S390_VM_MEM_CTRL,
 236        .attr = KVM_S390_VM_MEM_ENABLE_CMMA,
 237    };
 238
 239    if (cap_hpage_1m) {
 240        warn_report("CMM will not be enabled because it is not "
 241                    "compatible with huge memory backings.");
 242        return;
 243    }
 244    rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 245    active_cmma = !rc;
 246    trace_kvm_enable_cmma(rc);
 247}
 248
 249static void kvm_s390_set_attr(uint64_t attr)
 250{
 251    struct kvm_device_attr attribute = {
 252        .group = KVM_S390_VM_CRYPTO,
 253        .attr  = attr,
 254    };
 255
 256    int ret = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attribute);
 257
 258    if (ret) {
 259        error_report("Failed to set crypto device attribute %lu: %s",
 260                     attr, strerror(-ret));
 261    }
 262}
 263
 264static void kvm_s390_init_aes_kw(void)
 265{
 266    uint64_t attr = KVM_S390_VM_CRYPTO_DISABLE_AES_KW;
 267
 268    if (object_property_get_bool(OBJECT(qdev_get_machine()), "aes-key-wrap",
 269                                 NULL)) {
 270            attr = KVM_S390_VM_CRYPTO_ENABLE_AES_KW;
 271    }
 272
 273    if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO, attr)) {
 274            kvm_s390_set_attr(attr);
 275    }
 276}
 277
 278static void kvm_s390_init_dea_kw(void)
 279{
 280    uint64_t attr = KVM_S390_VM_CRYPTO_DISABLE_DEA_KW;
 281
 282    if (object_property_get_bool(OBJECT(qdev_get_machine()), "dea-key-wrap",
 283                                 NULL)) {
 284            attr = KVM_S390_VM_CRYPTO_ENABLE_DEA_KW;
 285    }
 286
 287    if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO, attr)) {
 288            kvm_s390_set_attr(attr);
 289    }
 290}
 291
 292void kvm_s390_crypto_reset(void)
 293{
 294    if (s390_has_feat(S390_FEAT_MSA_EXT_3)) {
 295        kvm_s390_init_aes_kw();
 296        kvm_s390_init_dea_kw();
 297    }
 298}
 299
 300void kvm_s390_set_max_pagesize(uint64_t pagesize, Error **errp)
 301{
 302    if (pagesize == 4 * KiB) {
 303        return;
 304    }
 305
 306    if (!hpage_1m_allowed()) {
 307        error_setg(errp, "This QEMU machine does not support huge page "
 308                   "mappings");
 309        return;
 310    }
 311
 312    if (pagesize != 1 * MiB) {
 313        error_setg(errp, "Memory backing with 2G pages was specified, "
 314                   "but KVM does not support this memory backing");
 315        return;
 316    }
 317
 318    if (kvm_vm_enable_cap(kvm_state, KVM_CAP_S390_HPAGE_1M, 0)) {
 319        error_setg(errp, "Memory backing with 1M pages was specified, "
 320                   "but KVM does not support this memory backing");
 321        return;
 322    }
 323
 324    cap_hpage_1m = 1;
 325}
 326
 327int kvm_s390_get_hpage_1m(void)
 328{
 329    return cap_hpage_1m;
 330}
 331
 332static void ccw_machine_class_foreach(ObjectClass *oc, void *opaque)
 333{
 334    MachineClass *mc = MACHINE_CLASS(oc);
 335
 336    mc->default_cpu_type = S390_CPU_TYPE_NAME("host");
 337}
 338
 339int kvm_arch_init(MachineState *ms, KVMState *s)
 340{
 341    object_class_foreach(ccw_machine_class_foreach, TYPE_S390_CCW_MACHINE,
 342                         false, NULL);
 343
 344    if (!kvm_check_extension(kvm_state, KVM_CAP_DEVICE_CTRL)) {
 345        error_report("KVM is missing capability KVM_CAP_DEVICE_CTRL - "
 346                     "please use kernel 3.15 or newer");
 347        return -1;
 348    }
 349    if (!kvm_check_extension(s, KVM_CAP_S390_COW)) {
 350        error_report("KVM is missing capability KVM_CAP_S390_COW - "
 351                     "unsupported environment");
 352        return -1;
 353    }
 354
 355    cap_sync_regs = kvm_check_extension(s, KVM_CAP_SYNC_REGS);
 356    cap_async_pf = kvm_check_extension(s, KVM_CAP_ASYNC_PF);
 357    cap_mem_op = kvm_check_extension(s, KVM_CAP_S390_MEM_OP);
 358    cap_s390_irq = kvm_check_extension(s, KVM_CAP_S390_INJECT_IRQ);
 359    cap_vcpu_resets = kvm_check_extension(s, KVM_CAP_S390_VCPU_RESETS);
 360    cap_protected = kvm_check_extension(s, KVM_CAP_S390_PROTECTED);
 361
 362    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_SIGP, 0);
 363    kvm_vm_enable_cap(s, KVM_CAP_S390_VECTOR_REGISTERS, 0);
 364    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_STSI, 0);
 365    if (ri_allowed()) {
 366        if (kvm_vm_enable_cap(s, KVM_CAP_S390_RI, 0) == 0) {
 367            cap_ri = 1;
 368        }
 369    }
 370    if (cpu_model_allowed()) {
 371        kvm_vm_enable_cap(s, KVM_CAP_S390_GS, 0);
 372    }
 373
 374    /*
 375     * The migration interface for ais was introduced with kernel 4.13
 376     * but the capability itself had been active since 4.12. As migration
 377     * support is considered necessary, we only try to enable this for
 378     * newer machine types if KVM_CAP_S390_AIS_MIGRATION is available.
 379     */
 380    if (cpu_model_allowed() && kvm_kernel_irqchip_allowed() &&
 381        kvm_check_extension(s, KVM_CAP_S390_AIS_MIGRATION)) {
 382        kvm_vm_enable_cap(s, KVM_CAP_S390_AIS, 0);
 383    }
 384
 385    kvm_set_max_memslot_size(KVM_SLOT_MAX_BYTES);
 386    return 0;
 387}
 388
 389int kvm_arch_irqchip_create(KVMState *s)
 390{
 391    return 0;
 392}
 393
 394unsigned long kvm_arch_vcpu_id(CPUState *cpu)
 395{
 396    return cpu->cpu_index;
 397}
 398
 399int kvm_arch_init_vcpu(CPUState *cs)
 400{
 401    unsigned int max_cpus = MACHINE(qdev_get_machine())->smp.max_cpus;
 402    S390CPU *cpu = S390_CPU(cs);
 403    kvm_s390_set_cpu_state(cpu, cpu->env.cpu_state);
 404    cpu->irqstate = g_malloc0(VCPU_IRQ_BUF_SIZE(max_cpus));
 405    return 0;
 406}
 407
 408int kvm_arch_destroy_vcpu(CPUState *cs)
 409{
 410    S390CPU *cpu = S390_CPU(cs);
 411
 412    g_free(cpu->irqstate);
 413    cpu->irqstate = NULL;
 414
 415    return 0;
 416}
 417
 418static void kvm_s390_reset_vcpu(S390CPU *cpu, unsigned long type)
 419{
 420    CPUState *cs = CPU(cpu);
 421
 422    /*
 423     * The reset call is needed here to reset in-kernel vcpu data that
 424     * we can't access directly from QEMU (i.e. with older kernels
 425     * which don't support sync_regs/ONE_REG).  Before this ioctl
 426     * cpu_synchronize_state() is called in common kvm code
 427     * (kvm-all).
 428     */
 429    if (kvm_vcpu_ioctl(cs, type)) {
 430        error_report("CPU reset failed on CPU %i type %lx",
 431                     cs->cpu_index, type);
 432    }
 433}
 434
 435void kvm_s390_reset_vcpu_initial(S390CPU *cpu)
 436{
 437    kvm_s390_reset_vcpu(cpu, KVM_S390_INITIAL_RESET);
 438}
 439
 440void kvm_s390_reset_vcpu_clear(S390CPU *cpu)
 441{
 442    if (cap_vcpu_resets) {
 443        kvm_s390_reset_vcpu(cpu, KVM_S390_CLEAR_RESET);
 444    } else {
 445        kvm_s390_reset_vcpu(cpu, KVM_S390_INITIAL_RESET);
 446    }
 447}
 448
 449void kvm_s390_reset_vcpu_normal(S390CPU *cpu)
 450{
 451    if (cap_vcpu_resets) {
 452        kvm_s390_reset_vcpu(cpu, KVM_S390_NORMAL_RESET);
 453    }
 454}
 455
 456static int can_sync_regs(CPUState *cs, int regs)
 457{
 458    return cap_sync_regs && (cs->kvm_run->kvm_valid_regs & regs) == regs;
 459}
 460
 461int kvm_arch_put_registers(CPUState *cs, int level)
 462{
 463    S390CPU *cpu = S390_CPU(cs);
 464    CPUS390XState *env = &cpu->env;
 465    struct kvm_sregs sregs;
 466    struct kvm_regs regs;
 467    struct kvm_fpu fpu = {};
 468    int r;
 469    int i;
 470
 471    /* always save the PSW  and the GPRS*/
 472    cs->kvm_run->psw_addr = env->psw.addr;
 473    cs->kvm_run->psw_mask = env->psw.mask;
 474
 475    if (can_sync_regs(cs, KVM_SYNC_GPRS)) {
 476        for (i = 0; i < 16; i++) {
 477            cs->kvm_run->s.regs.gprs[i] = env->regs[i];
 478            cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_GPRS;
 479        }
 480    } else {
 481        for (i = 0; i < 16; i++) {
 482            regs.gprs[i] = env->regs[i];
 483        }
 484        r = kvm_vcpu_ioctl(cs, KVM_SET_REGS, &regs);
 485        if (r < 0) {
 486            return r;
 487        }
 488    }
 489
 490    if (can_sync_regs(cs, KVM_SYNC_VRS)) {
 491        for (i = 0; i < 32; i++) {
 492            cs->kvm_run->s.regs.vrs[i][0] = env->vregs[i][0];
 493            cs->kvm_run->s.regs.vrs[i][1] = env->vregs[i][1];
 494        }
 495        cs->kvm_run->s.regs.fpc = env->fpc;
 496        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_VRS;
 497    } else if (can_sync_regs(cs, KVM_SYNC_FPRS)) {
 498        for (i = 0; i < 16; i++) {
 499            cs->kvm_run->s.regs.fprs[i] = *get_freg(env, i);
 500        }
 501        cs->kvm_run->s.regs.fpc = env->fpc;
 502        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_FPRS;
 503    } else {
 504        /* Floating point */
 505        for (i = 0; i < 16; i++) {
 506            fpu.fprs[i] = *get_freg(env, i);
 507        }
 508        fpu.fpc = env->fpc;
 509
 510        r = kvm_vcpu_ioctl(cs, KVM_SET_FPU, &fpu);
 511        if (r < 0) {
 512            return r;
 513        }
 514    }
 515
 516    /* Do we need to save more than that? */
 517    if (level == KVM_PUT_RUNTIME_STATE) {
 518        return 0;
 519    }
 520
 521    if (can_sync_regs(cs, KVM_SYNC_ARCH0)) {
 522        cs->kvm_run->s.regs.cputm = env->cputm;
 523        cs->kvm_run->s.regs.ckc = env->ckc;
 524        cs->kvm_run->s.regs.todpr = env->todpr;
 525        cs->kvm_run->s.regs.gbea = env->gbea;
 526        cs->kvm_run->s.regs.pp = env->pp;
 527        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ARCH0;
 528    } else {
 529        /*
 530         * These ONE_REGS are not protected by a capability. As they are only
 531         * necessary for migration we just trace a possible error, but don't
 532         * return with an error return code.
 533         */
 534        kvm_set_one_reg(cs, KVM_REG_S390_CPU_TIMER, &env->cputm);
 535        kvm_set_one_reg(cs, KVM_REG_S390_CLOCK_COMP, &env->ckc);
 536        kvm_set_one_reg(cs, KVM_REG_S390_TODPR, &env->todpr);
 537        kvm_set_one_reg(cs, KVM_REG_S390_GBEA, &env->gbea);
 538        kvm_set_one_reg(cs, KVM_REG_S390_PP, &env->pp);
 539    }
 540
 541    if (can_sync_regs(cs, KVM_SYNC_RICCB)) {
 542        memcpy(cs->kvm_run->s.regs.riccb, env->riccb, 64);
 543        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_RICCB;
 544    }
 545
 546    /* pfault parameters */
 547    if (can_sync_regs(cs, KVM_SYNC_PFAULT)) {
 548        cs->kvm_run->s.regs.pft = env->pfault_token;
 549        cs->kvm_run->s.regs.pfs = env->pfault_select;
 550        cs->kvm_run->s.regs.pfc = env->pfault_compare;
 551        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_PFAULT;
 552    } else if (cap_async_pf) {
 553        r = kvm_set_one_reg(cs, KVM_REG_S390_PFTOKEN, &env->pfault_token);
 554        if (r < 0) {
 555            return r;
 556        }
 557        r = kvm_set_one_reg(cs, KVM_REG_S390_PFCOMPARE, &env->pfault_compare);
 558        if (r < 0) {
 559            return r;
 560        }
 561        r = kvm_set_one_reg(cs, KVM_REG_S390_PFSELECT, &env->pfault_select);
 562        if (r < 0) {
 563            return r;
 564        }
 565    }
 566
 567    /* access registers and control registers*/
 568    if (can_sync_regs(cs, KVM_SYNC_ACRS | KVM_SYNC_CRS)) {
 569        for (i = 0; i < 16; i++) {
 570            cs->kvm_run->s.regs.acrs[i] = env->aregs[i];
 571            cs->kvm_run->s.regs.crs[i] = env->cregs[i];
 572        }
 573        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ACRS;
 574        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_CRS;
 575    } else {
 576        for (i = 0; i < 16; i++) {
 577            sregs.acrs[i] = env->aregs[i];
 578            sregs.crs[i] = env->cregs[i];
 579        }
 580        r = kvm_vcpu_ioctl(cs, KVM_SET_SREGS, &sregs);
 581        if (r < 0) {
 582            return r;
 583        }
 584    }
 585
 586    if (can_sync_regs(cs, KVM_SYNC_GSCB)) {
 587        memcpy(cs->kvm_run->s.regs.gscb, env->gscb, 32);
 588        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_GSCB;
 589    }
 590
 591    if (can_sync_regs(cs, KVM_SYNC_BPBC)) {
 592        cs->kvm_run->s.regs.bpbc = env->bpbc;
 593        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_BPBC;
 594    }
 595
 596    if (can_sync_regs(cs, KVM_SYNC_ETOKEN)) {
 597        cs->kvm_run->s.regs.etoken = env->etoken;
 598        cs->kvm_run->s.regs.etoken_extension  = env->etoken_extension;
 599        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ETOKEN;
 600    }
 601
 602    if (can_sync_regs(cs, KVM_SYNC_DIAG318)) {
 603        cs->kvm_run->s.regs.diag318 = env->diag318_info;
 604        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_DIAG318;
 605    }
 606
 607    /* Finally the prefix */
 608    if (can_sync_regs(cs, KVM_SYNC_PREFIX)) {
 609        cs->kvm_run->s.regs.prefix = env->psa;
 610        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_PREFIX;
 611    } else {
 612        /* prefix is only supported via sync regs */
 613    }
 614    return 0;
 615}
 616
 617int kvm_arch_get_registers(CPUState *cs)
 618{
 619    S390CPU *cpu = S390_CPU(cs);
 620    CPUS390XState *env = &cpu->env;
 621    struct kvm_sregs sregs;
 622    struct kvm_regs regs;
 623    struct kvm_fpu fpu;
 624    int i, r;
 625
 626    /* get the PSW */
 627    env->psw.addr = cs->kvm_run->psw_addr;
 628    env->psw.mask = cs->kvm_run->psw_mask;
 629
 630    /* the GPRS */
 631    if (can_sync_regs(cs, KVM_SYNC_GPRS)) {
 632        for (i = 0; i < 16; i++) {
 633            env->regs[i] = cs->kvm_run->s.regs.gprs[i];
 634        }
 635    } else {
 636        r = kvm_vcpu_ioctl(cs, KVM_GET_REGS, &regs);
 637        if (r < 0) {
 638            return r;
 639        }
 640         for (i = 0; i < 16; i++) {
 641            env->regs[i] = regs.gprs[i];
 642        }
 643    }
 644
 645    /* The ACRS and CRS */
 646    if (can_sync_regs(cs, KVM_SYNC_ACRS | KVM_SYNC_CRS)) {
 647        for (i = 0; i < 16; i++) {
 648            env->aregs[i] = cs->kvm_run->s.regs.acrs[i];
 649            env->cregs[i] = cs->kvm_run->s.regs.crs[i];
 650        }
 651    } else {
 652        r = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);
 653        if (r < 0) {
 654            return r;
 655        }
 656         for (i = 0; i < 16; i++) {
 657            env->aregs[i] = sregs.acrs[i];
 658            env->cregs[i] = sregs.crs[i];
 659        }
 660    }
 661
 662    /* Floating point and vector registers */
 663    if (can_sync_regs(cs, KVM_SYNC_VRS)) {
 664        for (i = 0; i < 32; i++) {
 665            env->vregs[i][0] = cs->kvm_run->s.regs.vrs[i][0];
 666            env->vregs[i][1] = cs->kvm_run->s.regs.vrs[i][1];
 667        }
 668        env->fpc = cs->kvm_run->s.regs.fpc;
 669    } else if (can_sync_regs(cs, KVM_SYNC_FPRS)) {
 670        for (i = 0; i < 16; i++) {
 671            *get_freg(env, i) = cs->kvm_run->s.regs.fprs[i];
 672        }
 673        env->fpc = cs->kvm_run->s.regs.fpc;
 674    } else {
 675        r = kvm_vcpu_ioctl(cs, KVM_GET_FPU, &fpu);
 676        if (r < 0) {
 677            return r;
 678        }
 679        for (i = 0; i < 16; i++) {
 680            *get_freg(env, i) = fpu.fprs[i];
 681        }
 682        env->fpc = fpu.fpc;
 683    }
 684
 685    /* The prefix */
 686    if (can_sync_regs(cs, KVM_SYNC_PREFIX)) {
 687        env->psa = cs->kvm_run->s.regs.prefix;
 688    }
 689
 690    if (can_sync_regs(cs, KVM_SYNC_ARCH0)) {
 691        env->cputm = cs->kvm_run->s.regs.cputm;
 692        env->ckc = cs->kvm_run->s.regs.ckc;
 693        env->todpr = cs->kvm_run->s.regs.todpr;
 694        env->gbea = cs->kvm_run->s.regs.gbea;
 695        env->pp = cs->kvm_run->s.regs.pp;
 696    } else {
 697        /*
 698         * These ONE_REGS are not protected by a capability. As they are only
 699         * necessary for migration we just trace a possible error, but don't
 700         * return with an error return code.
 701         */
 702        kvm_get_one_reg(cs, KVM_REG_S390_CPU_TIMER, &env->cputm);
 703        kvm_get_one_reg(cs, KVM_REG_S390_CLOCK_COMP, &env->ckc);
 704        kvm_get_one_reg(cs, KVM_REG_S390_TODPR, &env->todpr);
 705        kvm_get_one_reg(cs, KVM_REG_S390_GBEA, &env->gbea);
 706        kvm_get_one_reg(cs, KVM_REG_S390_PP, &env->pp);
 707    }
 708
 709    if (can_sync_regs(cs, KVM_SYNC_RICCB)) {
 710        memcpy(env->riccb, cs->kvm_run->s.regs.riccb, 64);
 711    }
 712
 713    if (can_sync_regs(cs, KVM_SYNC_GSCB)) {
 714        memcpy(env->gscb, cs->kvm_run->s.regs.gscb, 32);
 715    }
 716
 717    if (can_sync_regs(cs, KVM_SYNC_BPBC)) {
 718        env->bpbc = cs->kvm_run->s.regs.bpbc;
 719    }
 720
 721    if (can_sync_regs(cs, KVM_SYNC_ETOKEN)) {
 722        env->etoken = cs->kvm_run->s.regs.etoken;
 723        env->etoken_extension = cs->kvm_run->s.regs.etoken_extension;
 724    }
 725
 726    /* pfault parameters */
 727    if (can_sync_regs(cs, KVM_SYNC_PFAULT)) {
 728        env->pfault_token = cs->kvm_run->s.regs.pft;
 729        env->pfault_select = cs->kvm_run->s.regs.pfs;
 730        env->pfault_compare = cs->kvm_run->s.regs.pfc;
 731    } else if (cap_async_pf) {
 732        r = kvm_get_one_reg(cs, KVM_REG_S390_PFTOKEN, &env->pfault_token);
 733        if (r < 0) {
 734            return r;
 735        }
 736        r = kvm_get_one_reg(cs, KVM_REG_S390_PFCOMPARE, &env->pfault_compare);
 737        if (r < 0) {
 738            return r;
 739        }
 740        r = kvm_get_one_reg(cs, KVM_REG_S390_PFSELECT, &env->pfault_select);
 741        if (r < 0) {
 742            return r;
 743        }
 744    }
 745
 746    if (can_sync_regs(cs, KVM_SYNC_DIAG318)) {
 747        env->diag318_info = cs->kvm_run->s.regs.diag318;
 748    }
 749
 750    return 0;
 751}
 752
 753int kvm_s390_get_clock(uint8_t *tod_high, uint64_t *tod_low)
 754{
 755    int r;
 756    struct kvm_device_attr attr = {
 757        .group = KVM_S390_VM_TOD,
 758        .attr = KVM_S390_VM_TOD_LOW,
 759        .addr = (uint64_t)tod_low,
 760    };
 761
 762    r = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
 763    if (r) {
 764        return r;
 765    }
 766
 767    attr.attr = KVM_S390_VM_TOD_HIGH;
 768    attr.addr = (uint64_t)tod_high;
 769    return kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
 770}
 771
 772int kvm_s390_get_clock_ext(uint8_t *tod_high, uint64_t *tod_low)
 773{
 774    int r;
 775    struct kvm_s390_vm_tod_clock gtod;
 776    struct kvm_device_attr attr = {
 777        .group = KVM_S390_VM_TOD,
 778        .attr = KVM_S390_VM_TOD_EXT,
 779        .addr = (uint64_t)&gtod,
 780    };
 781
 782    r = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
 783    *tod_high = gtod.epoch_idx;
 784    *tod_low  = gtod.tod;
 785
 786    return r;
 787}
 788
 789int kvm_s390_set_clock(uint8_t tod_high, uint64_t tod_low)
 790{
 791    int r;
 792    struct kvm_device_attr attr = {
 793        .group = KVM_S390_VM_TOD,
 794        .attr = KVM_S390_VM_TOD_LOW,
 795        .addr = (uint64_t)&tod_low,
 796    };
 797
 798    r = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 799    if (r) {
 800        return r;
 801    }
 802
 803    attr.attr = KVM_S390_VM_TOD_HIGH;
 804    attr.addr = (uint64_t)&tod_high;
 805    return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 806}
 807
 808int kvm_s390_set_clock_ext(uint8_t tod_high, uint64_t tod_low)
 809{
 810    struct kvm_s390_vm_tod_clock gtod = {
 811        .epoch_idx = tod_high,
 812        .tod  = tod_low,
 813    };
 814    struct kvm_device_attr attr = {
 815        .group = KVM_S390_VM_TOD,
 816        .attr = KVM_S390_VM_TOD_EXT,
 817        .addr = (uint64_t)&gtod,
 818    };
 819
 820    return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
 821}
 822
 823/**
 824 * kvm_s390_mem_op:
 825 * @addr:      the logical start address in guest memory
 826 * @ar:        the access register number
 827 * @hostbuf:   buffer in host memory. NULL = do only checks w/o copying
 828 * @len:       length that should be transferred
 829 * @is_write:  true = write, false = read
 830 * Returns:    0 on success, non-zero if an exception or error occurred
 831 *
 832 * Use KVM ioctl to read/write from/to guest memory. An access exception
 833 * is injected into the vCPU in case of translation errors.
 834 */
 835int kvm_s390_mem_op(S390CPU *cpu, vaddr addr, uint8_t ar, void *hostbuf,
 836                    int len, bool is_write)
 837{
 838    struct kvm_s390_mem_op mem_op = {
 839        .gaddr = addr,
 840        .flags = KVM_S390_MEMOP_F_INJECT_EXCEPTION,
 841        .size = len,
 842        .op = is_write ? KVM_S390_MEMOP_LOGICAL_WRITE
 843                       : KVM_S390_MEMOP_LOGICAL_READ,
 844        .buf = (uint64_t)hostbuf,
 845        .ar = ar,
 846    };
 847    int ret;
 848
 849    if (!cap_mem_op) {
 850        return -ENOSYS;
 851    }
 852    if (!hostbuf) {
 853        mem_op.flags |= KVM_S390_MEMOP_F_CHECK_ONLY;
 854    }
 855
 856    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_S390_MEM_OP, &mem_op);
 857    if (ret < 0) {
 858        warn_report("KVM_S390_MEM_OP failed: %s", strerror(-ret));
 859    }
 860    return ret;
 861}
 862
 863int kvm_s390_mem_op_pv(S390CPU *cpu, uint64_t offset, void *hostbuf,
 864                       int len, bool is_write)
 865{
 866    struct kvm_s390_mem_op mem_op = {
 867        .sida_offset = offset,
 868        .size = len,
 869        .op = is_write ? KVM_S390_MEMOP_SIDA_WRITE
 870                       : KVM_S390_MEMOP_SIDA_READ,
 871        .buf = (uint64_t)hostbuf,
 872    };
 873    int ret;
 874
 875    if (!cap_mem_op || !cap_protected) {
 876        return -ENOSYS;
 877    }
 878
 879    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_S390_MEM_OP, &mem_op);
 880    if (ret < 0) {
 881        error_report("KVM_S390_MEM_OP failed: %s", strerror(-ret));
 882        abort();
 883    }
 884    return ret;
 885}
 886
 887static uint8_t const *sw_bp_inst;
 888static uint8_t sw_bp_ilen;
 889
 890static void determine_sw_breakpoint_instr(void)
 891{
 892        /* DIAG 501 is used for sw breakpoints with old kernels */
 893        static const uint8_t diag_501[] = {0x83, 0x24, 0x05, 0x01};
 894        /* Instruction 0x0000 is used for sw breakpoints with recent kernels */
 895        static const uint8_t instr_0x0000[] = {0x00, 0x00};
 896
 897        if (sw_bp_inst) {
 898            return;
 899        }
 900        if (kvm_vm_enable_cap(kvm_state, KVM_CAP_S390_USER_INSTR0, 0)) {
 901            sw_bp_inst = diag_501;
 902            sw_bp_ilen = sizeof(diag_501);
 903            DPRINTF("KVM: will use 4-byte sw breakpoints.\n");
 904        } else {
 905            sw_bp_inst = instr_0x0000;
 906            sw_bp_ilen = sizeof(instr_0x0000);
 907            DPRINTF("KVM: will use 2-byte sw breakpoints.\n");
 908        }
 909}
 910
 911int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
 912{
 913    determine_sw_breakpoint_instr();
 914
 915    if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
 916                            sw_bp_ilen, 0) ||
 917        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)sw_bp_inst, sw_bp_ilen, 1)) {
 918        return -EINVAL;
 919    }
 920    return 0;
 921}
 922
 923int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
 924{
 925    uint8_t t[MAX_ILEN];
 926
 927    if (cpu_memory_rw_debug(cs, bp->pc, t, sw_bp_ilen, 0)) {
 928        return -EINVAL;
 929    } else if (memcmp(t, sw_bp_inst, sw_bp_ilen)) {
 930        return -EINVAL;
 931    } else if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,
 932                                   sw_bp_ilen, 1)) {
 933        return -EINVAL;
 934    }
 935
 936    return 0;
 937}
 938
 939static struct kvm_hw_breakpoint *find_hw_breakpoint(target_ulong addr,
 940                                                    int len, int type)
 941{
 942    int n;
 943
 944    for (n = 0; n < nb_hw_breakpoints; n++) {
 945        if (hw_breakpoints[n].addr == addr && hw_breakpoints[n].type == type &&
 946            (hw_breakpoints[n].len == len || len == -1)) {
 947            return &hw_breakpoints[n];
 948        }
 949    }
 950
 951    return NULL;
 952}
 953
 954static int insert_hw_breakpoint(target_ulong addr, int len, int type)
 955{
 956    int size;
 957
 958    if (find_hw_breakpoint(addr, len, type)) {
 959        return -EEXIST;
 960    }
 961
 962    size = (nb_hw_breakpoints + 1) * sizeof(struct kvm_hw_breakpoint);
 963
 964    if (!hw_breakpoints) {
 965        nb_hw_breakpoints = 0;
 966        hw_breakpoints = (struct kvm_hw_breakpoint *)g_try_malloc(size);
 967    } else {
 968        hw_breakpoints =
 969            (struct kvm_hw_breakpoint *)g_try_realloc(hw_breakpoints, size);
 970    }
 971
 972    if (!hw_breakpoints) {
 973        nb_hw_breakpoints = 0;
 974        return -ENOMEM;
 975    }
 976
 977    hw_breakpoints[nb_hw_breakpoints].addr = addr;
 978    hw_breakpoints[nb_hw_breakpoints].len = len;
 979    hw_breakpoints[nb_hw_breakpoints].type = type;
 980
 981    nb_hw_breakpoints++;
 982
 983    return 0;
 984}
 985
 986int kvm_arch_insert_hw_breakpoint(target_ulong addr,
 987                                  target_ulong len, int type)
 988{
 989    switch (type) {
 990    case GDB_BREAKPOINT_HW:
 991        type = KVM_HW_BP;
 992        break;
 993    case GDB_WATCHPOINT_WRITE:
 994        if (len < 1) {
 995            return -EINVAL;
 996        }
 997        type = KVM_HW_WP_WRITE;
 998        break;
 999    default:
1000        return -ENOSYS;
1001    }
1002    return insert_hw_breakpoint(addr, len, type);
1003}
1004
1005int kvm_arch_remove_hw_breakpoint(target_ulong addr,
1006                                  target_ulong len, int type)
1007{
1008    int size;
1009    struct kvm_hw_breakpoint *bp = find_hw_breakpoint(addr, len, type);
1010
1011    if (bp == NULL) {
1012        return -ENOENT;
1013    }
1014
1015    nb_hw_breakpoints--;
1016    if (nb_hw_breakpoints > 0) {
1017        /*
1018         * In order to trim the array, move the last element to the position to
1019         * be removed - if necessary.
1020         */
1021        if (bp != &hw_breakpoints[nb_hw_breakpoints]) {
1022            *bp = hw_breakpoints[nb_hw_breakpoints];
1023        }
1024        size = nb_hw_breakpoints * sizeof(struct kvm_hw_breakpoint);
1025        hw_breakpoints =
1026             (struct kvm_hw_breakpoint *)g_realloc(hw_breakpoints, size);
1027    } else {
1028        g_free(hw_breakpoints);
1029        hw_breakpoints = NULL;
1030    }
1031
1032    return 0;
1033}
1034
1035void kvm_arch_remove_all_hw_breakpoints(void)
1036{
1037    nb_hw_breakpoints = 0;
1038    g_free(hw_breakpoints);
1039    hw_breakpoints = NULL;
1040}
1041
1042void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
1043{
1044    int i;
1045
1046    if (nb_hw_breakpoints > 0) {
1047        dbg->arch.nr_hw_bp = nb_hw_breakpoints;
1048        dbg->arch.hw_bp = hw_breakpoints;
1049
1050        for (i = 0; i < nb_hw_breakpoints; ++i) {
1051            hw_breakpoints[i].phys_addr = s390_cpu_get_phys_addr_debug(cpu,
1052                                                       hw_breakpoints[i].addr);
1053        }
1054        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
1055    } else {
1056        dbg->arch.nr_hw_bp = 0;
1057        dbg->arch.hw_bp = NULL;
1058    }
1059}
1060
1061void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
1062{
1063}
1064
1065MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)
1066{
1067    return MEMTXATTRS_UNSPECIFIED;
1068}
1069
1070int kvm_arch_process_async_events(CPUState *cs)
1071{
1072    return cs->halted;
1073}
1074
1075static int s390_kvm_irq_to_interrupt(struct kvm_s390_irq *irq,
1076                                     struct kvm_s390_interrupt *interrupt)
1077{
1078    int r = 0;
1079
1080    interrupt->type = irq->type;
1081    switch (irq->type) {
1082    case KVM_S390_INT_VIRTIO:
1083        interrupt->parm = irq->u.ext.ext_params;
1084        /* fall through */
1085    case KVM_S390_INT_PFAULT_INIT:
1086    case KVM_S390_INT_PFAULT_DONE:
1087        interrupt->parm64 = irq->u.ext.ext_params2;
1088        break;
1089    case KVM_S390_PROGRAM_INT:
1090        interrupt->parm = irq->u.pgm.code;
1091        break;
1092    case KVM_S390_SIGP_SET_PREFIX:
1093        interrupt->parm = irq->u.prefix.address;
1094        break;
1095    case KVM_S390_INT_SERVICE:
1096        interrupt->parm = irq->u.ext.ext_params;
1097        break;
1098    case KVM_S390_MCHK:
1099        interrupt->parm = irq->u.mchk.cr14;
1100        interrupt->parm64 = irq->u.mchk.mcic;
1101        break;
1102    case KVM_S390_INT_EXTERNAL_CALL:
1103        interrupt->parm = irq->u.extcall.code;
1104        break;
1105    case KVM_S390_INT_EMERGENCY:
1106        interrupt->parm = irq->u.emerg.code;
1107        break;
1108    case KVM_S390_SIGP_STOP:
1109    case KVM_S390_RESTART:
1110        break; /* These types have no parameters */
1111    case KVM_S390_INT_IO_MIN...KVM_S390_INT_IO_MAX:
1112        interrupt->parm = irq->u.io.subchannel_id << 16;
1113        interrupt->parm |= irq->u.io.subchannel_nr;
1114        interrupt->parm64 = (uint64_t)irq->u.io.io_int_parm << 32;
1115        interrupt->parm64 |= irq->u.io.io_int_word;
1116        break;
1117    default:
1118        r = -EINVAL;
1119        break;
1120    }
1121    return r;
1122}
1123
1124static void inject_vcpu_irq_legacy(CPUState *cs, struct kvm_s390_irq *irq)
1125{
1126    struct kvm_s390_interrupt kvmint = {};
1127    int r;
1128
1129    r = s390_kvm_irq_to_interrupt(irq, &kvmint);
1130    if (r < 0) {
1131        fprintf(stderr, "%s called with bogus interrupt\n", __func__);
1132        exit(1);
1133    }
1134
1135    r = kvm_vcpu_ioctl(cs, KVM_S390_INTERRUPT, &kvmint);
1136    if (r < 0) {
1137        fprintf(stderr, "KVM failed to inject interrupt\n");
1138        exit(1);
1139    }
1140}
1141
1142void kvm_s390_vcpu_interrupt(S390CPU *cpu, struct kvm_s390_irq *irq)
1143{
1144    CPUState *cs = CPU(cpu);
1145    int r;
1146
1147    if (cap_s390_irq) {
1148        r = kvm_vcpu_ioctl(cs, KVM_S390_IRQ, irq);
1149        if (!r) {
1150            return;
1151        }
1152        error_report("KVM failed to inject interrupt %llx", irq->type);
1153        exit(1);
1154    }
1155
1156    inject_vcpu_irq_legacy(cs, irq);
1157}
1158
1159void kvm_s390_floating_interrupt_legacy(struct kvm_s390_irq *irq)
1160{
1161    struct kvm_s390_interrupt kvmint = {};
1162    int r;
1163
1164    r = s390_kvm_irq_to_interrupt(irq, &kvmint);
1165    if (r < 0) {
1166        fprintf(stderr, "%s called with bogus interrupt\n", __func__);
1167        exit(1);
1168    }
1169
1170    r = kvm_vm_ioctl(kvm_state, KVM_S390_INTERRUPT, &kvmint);
1171    if (r < 0) {
1172        fprintf(stderr, "KVM failed to inject interrupt\n");
1173        exit(1);
1174    }
1175}
1176
1177void kvm_s390_program_interrupt(S390CPU *cpu, uint16_t code)
1178{
1179    struct kvm_s390_irq irq = {
1180        .type = KVM_S390_PROGRAM_INT,
1181        .u.pgm.code = code,
1182    };
1183    qemu_log_mask(CPU_LOG_INT, "program interrupt at %#" PRIx64 "\n",
1184                  cpu->env.psw.addr);
1185    kvm_s390_vcpu_interrupt(cpu, &irq);
1186}
1187
1188void kvm_s390_access_exception(S390CPU *cpu, uint16_t code, uint64_t te_code)
1189{
1190    struct kvm_s390_irq irq = {
1191        .type = KVM_S390_PROGRAM_INT,
1192        .u.pgm.code = code,
1193        .u.pgm.trans_exc_code = te_code,
1194        .u.pgm.exc_access_id = te_code & 3,
1195    };
1196
1197    kvm_s390_vcpu_interrupt(cpu, &irq);
1198}
1199
1200static void kvm_sclp_service_call(S390CPU *cpu, struct kvm_run *run,
1201                                 uint16_t ipbh0)
1202{
1203    CPUS390XState *env = &cpu->env;
1204    uint64_t sccb;
1205    uint32_t code;
1206    int r;
1207
1208    sccb = env->regs[ipbh0 & 0xf];
1209    code = env->regs[(ipbh0 & 0xf0) >> 4];
1210
1211    switch (run->s390_sieic.icptcode) {
1212    case ICPT_PV_INSTR_NOTIFICATION:
1213        g_assert(s390_is_pv());
1214        /* The notification intercepts are currently handled by KVM */
1215        error_report("unexpected SCLP PV notification");
1216        exit(1);
1217        break;
1218    case ICPT_PV_INSTR:
1219        g_assert(s390_is_pv());
1220        sclp_service_call_protected(env, sccb, code);
1221        /* Setting the CC is done by the Ultravisor. */
1222        break;
1223    case ICPT_INSTRUCTION:
1224        g_assert(!s390_is_pv());
1225        r = sclp_service_call(env, sccb, code);
1226        if (r < 0) {
1227            kvm_s390_program_interrupt(cpu, -r);
1228            return;
1229        }
1230        setcc(cpu, r);
1231    }
1232}
1233
1234static int handle_b2(S390CPU *cpu, struct kvm_run *run, uint8_t ipa1)
1235{
1236    CPUS390XState *env = &cpu->env;
1237    int rc = 0;
1238    uint16_t ipbh0 = (run->s390_sieic.ipb & 0xffff0000) >> 16;
1239
1240    switch (ipa1) {
1241    case PRIV_B2_XSCH:
1242        ioinst_handle_xsch(cpu, env->regs[1], RA_IGNORED);
1243        break;
1244    case PRIV_B2_CSCH:
1245        ioinst_handle_csch(cpu, env->regs[1], RA_IGNORED);
1246        break;
1247    case PRIV_B2_HSCH:
1248        ioinst_handle_hsch(cpu, env->regs[1], RA_IGNORED);
1249        break;
1250    case PRIV_B2_MSCH:
1251        ioinst_handle_msch(cpu, env->regs[1], run->s390_sieic.ipb, RA_IGNORED);
1252        break;
1253    case PRIV_B2_SSCH:
1254        ioinst_handle_ssch(cpu, env->regs[1], run->s390_sieic.ipb, RA_IGNORED);
1255        break;
1256    case PRIV_B2_STCRW:
1257        ioinst_handle_stcrw(cpu, run->s390_sieic.ipb, RA_IGNORED);
1258        break;
1259    case PRIV_B2_STSCH:
1260        ioinst_handle_stsch(cpu, env->regs[1], run->s390_sieic.ipb, RA_IGNORED);
1261        break;
1262    case PRIV_B2_TSCH:
1263        /* We should only get tsch via KVM_EXIT_S390_TSCH. */
1264        fprintf(stderr, "Spurious tsch intercept\n");
1265        break;
1266    case PRIV_B2_CHSC:
1267        ioinst_handle_chsc(cpu, run->s390_sieic.ipb, RA_IGNORED);
1268        break;
1269    case PRIV_B2_TPI:
1270        /* This should have been handled by kvm already. */
1271        fprintf(stderr, "Spurious tpi intercept\n");
1272        break;
1273    case PRIV_B2_SCHM:
1274        ioinst_handle_schm(cpu, env->regs[1], env->regs[2],
1275                           run->s390_sieic.ipb, RA_IGNORED);
1276        break;
1277    case PRIV_B2_RSCH:
1278        ioinst_handle_rsch(cpu, env->regs[1], RA_IGNORED);
1279        break;
1280    case PRIV_B2_RCHP:
1281        ioinst_handle_rchp(cpu, env->regs[1], RA_IGNORED);
1282        break;
1283    case PRIV_B2_STCPS:
1284        /* We do not provide this instruction, it is suppressed. */
1285        break;
1286    case PRIV_B2_SAL:
1287        ioinst_handle_sal(cpu, env->regs[1], RA_IGNORED);
1288        break;
1289    case PRIV_B2_SIGA:
1290        /* Not provided, set CC = 3 for subchannel not operational */
1291        setcc(cpu, 3);
1292        break;
1293    case PRIV_B2_SCLP_CALL:
1294        kvm_sclp_service_call(cpu, run, ipbh0);
1295        break;
1296    default:
1297        rc = -1;
1298        DPRINTF("KVM: unhandled PRIV: 0xb2%x\n", ipa1);
1299        break;
1300    }
1301
1302    return rc;
1303}
1304
1305static uint64_t get_base_disp_rxy(S390CPU *cpu, struct kvm_run *run,
1306                                  uint8_t *ar)
1307{
1308    CPUS390XState *env = &cpu->env;
1309    uint32_t x2 = (run->s390_sieic.ipa & 0x000f);
1310    uint32_t base2 = run->s390_sieic.ipb >> 28;
1311    uint32_t disp2 = ((run->s390_sieic.ipb & 0x0fff0000) >> 16) +
1312                     ((run->s390_sieic.ipb & 0xff00) << 4);
1313
1314    if (disp2 & 0x80000) {
1315        disp2 += 0xfff00000;
1316    }
1317    if (ar) {
1318        *ar = base2;
1319    }
1320
1321    return (base2 ? env->regs[base2] : 0) +
1322           (x2 ? env->regs[x2] : 0) + (long)(int)disp2;
1323}
1324
1325static uint64_t get_base_disp_rsy(S390CPU *cpu, struct kvm_run *run,
1326                                  uint8_t *ar)
1327{
1328    CPUS390XState *env = &cpu->env;
1329    uint32_t base2 = run->s390_sieic.ipb >> 28;
1330    uint32_t disp2 = ((run->s390_sieic.ipb & 0x0fff0000) >> 16) +
1331                     ((run->s390_sieic.ipb & 0xff00) << 4);
1332
1333    if (disp2 & 0x80000) {
1334        disp2 += 0xfff00000;
1335    }
1336    if (ar) {
1337        *ar = base2;
1338    }
1339
1340    return (base2 ? env->regs[base2] : 0) + (long)(int)disp2;
1341}
1342
1343static int kvm_clp_service_call(S390CPU *cpu, struct kvm_run *run)
1344{
1345    uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1346
1347    if (s390_has_feat(S390_FEAT_ZPCI)) {
1348        return clp_service_call(cpu, r2, RA_IGNORED);
1349    } else {
1350        return -1;
1351    }
1352}
1353
1354static int kvm_pcilg_service_call(S390CPU *cpu, struct kvm_run *run)
1355{
1356    uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1357    uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1358
1359    if (s390_has_feat(S390_FEAT_ZPCI)) {
1360        return pcilg_service_call(cpu, r1, r2, RA_IGNORED);
1361    } else {
1362        return -1;
1363    }
1364}
1365
1366static int kvm_pcistg_service_call(S390CPU *cpu, struct kvm_run *run)
1367{
1368    uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1369    uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1370
1371    if (s390_has_feat(S390_FEAT_ZPCI)) {
1372        return pcistg_service_call(cpu, r1, r2, RA_IGNORED);
1373    } else {
1374        return -1;
1375    }
1376}
1377
1378static int kvm_stpcifc_service_call(S390CPU *cpu, struct kvm_run *run)
1379{
1380    uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1381    uint64_t fiba;
1382    uint8_t ar;
1383
1384    if (s390_has_feat(S390_FEAT_ZPCI)) {
1385        fiba = get_base_disp_rxy(cpu, run, &ar);
1386
1387        return stpcifc_service_call(cpu, r1, fiba, ar, RA_IGNORED);
1388    } else {
1389        return -1;
1390    }
1391}
1392
1393static int kvm_sic_service_call(S390CPU *cpu, struct kvm_run *run)
1394{
1395    CPUS390XState *env = &cpu->env;
1396    uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1397    uint8_t r3 = run->s390_sieic.ipa & 0x000f;
1398    uint8_t isc;
1399    uint16_t mode;
1400    int r;
1401
1402    mode = env->regs[r1] & 0xffff;
1403    isc = (env->regs[r3] >> 27) & 0x7;
1404    r = css_do_sic(env, isc, mode);
1405    if (r) {
1406        kvm_s390_program_interrupt(cpu, -r);
1407    }
1408
1409    return 0;
1410}
1411
1412static int kvm_rpcit_service_call(S390CPU *cpu, struct kvm_run *run)
1413{
1414    uint8_t r1 = (run->s390_sieic.ipb & 0x00f00000) >> 20;
1415    uint8_t r2 = (run->s390_sieic.ipb & 0x000f0000) >> 16;
1416
1417    if (s390_has_feat(S390_FEAT_ZPCI)) {
1418        return rpcit_service_call(cpu, r1, r2, RA_IGNORED);
1419    } else {
1420        return -1;
1421    }
1422}
1423
1424static int kvm_pcistb_service_call(S390CPU *cpu, struct kvm_run *run)
1425{
1426    uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1427    uint8_t r3 = run->s390_sieic.ipa & 0x000f;
1428    uint64_t gaddr;
1429    uint8_t ar;
1430
1431    if (s390_has_feat(S390_FEAT_ZPCI)) {
1432        gaddr = get_base_disp_rsy(cpu, run, &ar);
1433
1434        return pcistb_service_call(cpu, r1, r3, gaddr, ar, RA_IGNORED);
1435    } else {
1436        return -1;
1437    }
1438}
1439
1440static int kvm_mpcifc_service_call(S390CPU *cpu, struct kvm_run *run)
1441{
1442    uint8_t r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1443    uint64_t fiba;
1444    uint8_t ar;
1445
1446    if (s390_has_feat(S390_FEAT_ZPCI)) {
1447        fiba = get_base_disp_rxy(cpu, run, &ar);
1448
1449        return mpcifc_service_call(cpu, r1, fiba, ar, RA_IGNORED);
1450    } else {
1451        return -1;
1452    }
1453}
1454
1455static int handle_b9(S390CPU *cpu, struct kvm_run *run, uint8_t ipa1)
1456{
1457    int r = 0;
1458
1459    switch (ipa1) {
1460    case PRIV_B9_CLP:
1461        r = kvm_clp_service_call(cpu, run);
1462        break;
1463    case PRIV_B9_PCISTG:
1464        r = kvm_pcistg_service_call(cpu, run);
1465        break;
1466    case PRIV_B9_PCILG:
1467        r = kvm_pcilg_service_call(cpu, run);
1468        break;
1469    case PRIV_B9_RPCIT:
1470        r = kvm_rpcit_service_call(cpu, run);
1471        break;
1472    case PRIV_B9_EQBS:
1473        /* just inject exception */
1474        r = -1;
1475        break;
1476    default:
1477        r = -1;
1478        DPRINTF("KVM: unhandled PRIV: 0xb9%x\n", ipa1);
1479        break;
1480    }
1481
1482    return r;
1483}
1484
1485static int handle_eb(S390CPU *cpu, struct kvm_run *run, uint8_t ipbl)
1486{
1487    int r = 0;
1488
1489    switch (ipbl) {
1490    case PRIV_EB_PCISTB:
1491        r = kvm_pcistb_service_call(cpu, run);
1492        break;
1493    case PRIV_EB_SIC:
1494        r = kvm_sic_service_call(cpu, run);
1495        break;
1496    case PRIV_EB_SQBS:
1497        /* just inject exception */
1498        r = -1;
1499        break;
1500    default:
1501        r = -1;
1502        DPRINTF("KVM: unhandled PRIV: 0xeb%x\n", ipbl);
1503        break;
1504    }
1505
1506    return r;
1507}
1508
1509static int handle_e3(S390CPU *cpu, struct kvm_run *run, uint8_t ipbl)
1510{
1511    int r = 0;
1512
1513    switch (ipbl) {
1514    case PRIV_E3_MPCIFC:
1515        r = kvm_mpcifc_service_call(cpu, run);
1516        break;
1517    case PRIV_E3_STPCIFC:
1518        r = kvm_stpcifc_service_call(cpu, run);
1519        break;
1520    default:
1521        r = -1;
1522        DPRINTF("KVM: unhandled PRIV: 0xe3%x\n", ipbl);
1523        break;
1524    }
1525
1526    return r;
1527}
1528
1529static int handle_hypercall(S390CPU *cpu, struct kvm_run *run)
1530{
1531    CPUS390XState *env = &cpu->env;
1532    int ret;
1533
1534    ret = s390_virtio_hypercall(env);
1535    if (ret == -EINVAL) {
1536        kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1537        return 0;
1538    }
1539
1540    return ret;
1541}
1542
1543static void kvm_handle_diag_288(S390CPU *cpu, struct kvm_run *run)
1544{
1545    uint64_t r1, r3;
1546    int rc;
1547
1548    r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1549    r3 = run->s390_sieic.ipa & 0x000f;
1550    rc = handle_diag_288(&cpu->env, r1, r3);
1551    if (rc) {
1552        kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1553    }
1554}
1555
1556static void kvm_handle_diag_308(S390CPU *cpu, struct kvm_run *run)
1557{
1558    uint64_t r1, r3;
1559
1560    r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
1561    r3 = run->s390_sieic.ipa & 0x000f;
1562    handle_diag_308(&cpu->env, r1, r3, RA_IGNORED);
1563}
1564
1565static int handle_sw_breakpoint(S390CPU *cpu, struct kvm_run *run)
1566{
1567    CPUS390XState *env = &cpu->env;
1568    unsigned long pc;
1569
1570    pc = env->psw.addr - sw_bp_ilen;
1571    if (kvm_find_sw_breakpoint(CPU(cpu), pc)) {
1572        env->psw.addr = pc;
1573        return EXCP_DEBUG;
1574    }
1575
1576    return -ENOENT;
1577}
1578
1579void kvm_s390_set_diag318(CPUState *cs, uint64_t diag318_info)
1580{
1581    CPUS390XState *env = &S390_CPU(cs)->env;
1582
1583    /* Feat bit is set only if KVM supports sync for diag318 */
1584    if (s390_has_feat(S390_FEAT_DIAG_318)) {
1585        env->diag318_info = diag318_info;
1586        cs->kvm_run->s.regs.diag318 = diag318_info;
1587        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_DIAG318;
1588        /*
1589         * diag 318 info is zeroed during a clear reset and
1590         * diag 308 IPL subcodes.
1591         */
1592    }
1593}
1594
1595static void handle_diag_318(S390CPU *cpu, struct kvm_run *run)
1596{
1597    uint64_t reg = (run->s390_sieic.ipa & 0x00f0) >> 4;
1598    uint64_t diag318_info = run->s.regs.gprs[reg];
1599    CPUState *t;
1600
1601    /*
1602     * DIAG 318 can only be enabled with KVM support. As such, let's
1603     * ensure a guest cannot execute this instruction erroneously.
1604     */
1605    if (!s390_has_feat(S390_FEAT_DIAG_318)) {
1606        kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1607        return;
1608    }
1609
1610    CPU_FOREACH(t) {
1611        run_on_cpu(t, s390_do_cpu_set_diag318,
1612                   RUN_ON_CPU_HOST_ULONG(diag318_info));
1613    }
1614}
1615
1616#define DIAG_KVM_CODE_MASK 0x000000000000ffff
1617
1618static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
1619{
1620    int r = 0;
1621    uint16_t func_code;
1622
1623    /*
1624     * For any diagnose call we support, bits 48-63 of the resulting
1625     * address specify the function code; the remainder is ignored.
1626     */
1627    func_code = decode_basedisp_rs(&cpu->env, ipb, NULL) & DIAG_KVM_CODE_MASK;
1628    switch (func_code) {
1629    case DIAG_TIMEREVENT:
1630        kvm_handle_diag_288(cpu, run);
1631        break;
1632    case DIAG_IPL:
1633        kvm_handle_diag_308(cpu, run);
1634        break;
1635    case DIAG_SET_CONTROL_PROGRAM_CODES:
1636        handle_diag_318(cpu, run);
1637        break;
1638    case DIAG_KVM_HYPERCALL:
1639        r = handle_hypercall(cpu, run);
1640        break;
1641    case DIAG_KVM_BREAKPOINT:
1642        r = handle_sw_breakpoint(cpu, run);
1643        break;
1644    default:
1645        DPRINTF("KVM: unknown DIAG: 0x%x\n", func_code);
1646        kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
1647        break;
1648    }
1649
1650    return r;
1651}
1652
1653static int kvm_s390_handle_sigp(S390CPU *cpu, uint8_t ipa1, uint32_t ipb)
1654{
1655    CPUS390XState *env = &cpu->env;
1656    const uint8_t r1 = ipa1 >> 4;
1657    const uint8_t r3 = ipa1 & 0x0f;
1658    int ret;
1659    uint8_t order;
1660
1661    /* get order code */
1662    order = decode_basedisp_rs(env, ipb, NULL) & SIGP_ORDER_MASK;
1663
1664    ret = handle_sigp(env, order, r1, r3);
1665    setcc(cpu, ret);
1666    return 0;
1667}
1668
1669static int handle_instruction(S390CPU *cpu, struct kvm_run *run)
1670{
1671    unsigned int ipa0 = (run->s390_sieic.ipa & 0xff00);
1672    uint8_t ipa1 = run->s390_sieic.ipa & 0x00ff;
1673    int r = -1;
1674
1675    DPRINTF("handle_instruction 0x%x 0x%x\n",
1676            run->s390_sieic.ipa, run->s390_sieic.ipb);
1677    switch (ipa0) {
1678    case IPA0_B2:
1679        r = handle_b2(cpu, run, ipa1);
1680        break;
1681    case IPA0_B9:
1682        r = handle_b9(cpu, run, ipa1);
1683        break;
1684    case IPA0_EB:
1685        r = handle_eb(cpu, run, run->s390_sieic.ipb & 0xff);
1686        break;
1687    case IPA0_E3:
1688        r = handle_e3(cpu, run, run->s390_sieic.ipb & 0xff);
1689        break;
1690    case IPA0_DIAG:
1691        r = handle_diag(cpu, run, run->s390_sieic.ipb);
1692        break;
1693    case IPA0_SIGP:
1694        r = kvm_s390_handle_sigp(cpu, ipa1, run->s390_sieic.ipb);
1695        break;
1696    }
1697
1698    if (r < 0) {
1699        r = 0;
1700        kvm_s390_program_interrupt(cpu, PGM_OPERATION);
1701    }
1702
1703    return r;
1704}
1705
1706static void unmanageable_intercept(S390CPU *cpu, S390CrashReason reason,
1707                                   int pswoffset)
1708{
1709    CPUState *cs = CPU(cpu);
1710
1711    s390_cpu_halt(cpu);
1712    cpu->env.crash_reason = reason;
1713    qemu_system_guest_panicked(cpu_get_crash_info(cs));
1714}
1715
1716/* try to detect pgm check loops */
1717static int handle_oper_loop(S390CPU *cpu, struct kvm_run *run)
1718{
1719    CPUState *cs = CPU(cpu);
1720    PSW oldpsw, newpsw;
1721
1722    newpsw.mask = ldq_phys(cs->as, cpu->env.psa +
1723                           offsetof(LowCore, program_new_psw));
1724    newpsw.addr = ldq_phys(cs->as, cpu->env.psa +
1725                           offsetof(LowCore, program_new_psw) + 8);
1726    oldpsw.mask  = run->psw_mask;
1727    oldpsw.addr  = run->psw_addr;
1728    /*
1729     * Avoid endless loops of operation exceptions, if the pgm new
1730     * PSW will cause a new operation exception.
1731     * The heuristic checks if the pgm new psw is within 6 bytes before
1732     * the faulting psw address (with same DAT, AS settings) and the
1733     * new psw is not a wait psw and the fault was not triggered by
1734     * problem state. In that case go into crashed state.
1735     */
1736
1737    if (oldpsw.addr - newpsw.addr <= 6 &&
1738        !(newpsw.mask & PSW_MASK_WAIT) &&
1739        !(oldpsw.mask & PSW_MASK_PSTATE) &&
1740        (newpsw.mask & PSW_MASK_ASC) == (oldpsw.mask & PSW_MASK_ASC) &&
1741        (newpsw.mask & PSW_MASK_DAT) == (oldpsw.mask & PSW_MASK_DAT)) {
1742        unmanageable_intercept(cpu, S390_CRASH_REASON_OPINT_LOOP,
1743                               offsetof(LowCore, program_new_psw));
1744        return EXCP_HALTED;
1745    }
1746    return 0;
1747}
1748
1749static int handle_intercept(S390CPU *cpu)
1750{
1751    CPUState *cs = CPU(cpu);
1752    struct kvm_run *run = cs->kvm_run;
1753    int icpt_code = run->s390_sieic.icptcode;
1754    int r = 0;
1755
1756    DPRINTF("intercept: 0x%x (at 0x%lx)\n", icpt_code, (long)run->psw_addr);
1757    switch (icpt_code) {
1758        case ICPT_INSTRUCTION:
1759        case ICPT_PV_INSTR:
1760        case ICPT_PV_INSTR_NOTIFICATION:
1761            r = handle_instruction(cpu, run);
1762            break;
1763        case ICPT_PROGRAM:
1764            unmanageable_intercept(cpu, S390_CRASH_REASON_PGMINT_LOOP,
1765                                   offsetof(LowCore, program_new_psw));
1766            r = EXCP_HALTED;
1767            break;
1768        case ICPT_EXT_INT:
1769            unmanageable_intercept(cpu, S390_CRASH_REASON_EXTINT_LOOP,
1770                                   offsetof(LowCore, external_new_psw));
1771            r = EXCP_HALTED;
1772            break;
1773        case ICPT_WAITPSW:
1774            /* disabled wait, since enabled wait is handled in kernel */
1775            s390_handle_wait(cpu);
1776            r = EXCP_HALTED;
1777            break;
1778        case ICPT_CPU_STOP:
1779            do_stop_interrupt(&cpu->env);
1780            r = EXCP_HALTED;
1781            break;
1782        case ICPT_OPEREXC:
1783            /* check for break points */
1784            r = handle_sw_breakpoint(cpu, run);
1785            if (r == -ENOENT) {
1786                /* Then check for potential pgm check loops */
1787                r = handle_oper_loop(cpu, run);
1788                if (r == 0) {
1789                    kvm_s390_program_interrupt(cpu, PGM_OPERATION);
1790                }
1791            }
1792            break;
1793        case ICPT_SOFT_INTERCEPT:
1794            fprintf(stderr, "KVM unimplemented icpt SOFT\n");
1795            exit(1);
1796            break;
1797        case ICPT_IO:
1798            fprintf(stderr, "KVM unimplemented icpt IO\n");
1799            exit(1);
1800            break;
1801        default:
1802            fprintf(stderr, "Unknown intercept code: %d\n", icpt_code);
1803            exit(1);
1804            break;
1805    }
1806
1807    return r;
1808}
1809
1810static int handle_tsch(S390CPU *cpu)
1811{
1812    CPUState *cs = CPU(cpu);
1813    struct kvm_run *run = cs->kvm_run;
1814    int ret;
1815
1816    ret = ioinst_handle_tsch(cpu, cpu->env.regs[1], run->s390_tsch.ipb,
1817                             RA_IGNORED);
1818    if (ret < 0) {
1819        /*
1820         * Failure.
1821         * If an I/O interrupt had been dequeued, we have to reinject it.
1822         */
1823        if (run->s390_tsch.dequeued) {
1824            s390_io_interrupt(run->s390_tsch.subchannel_id,
1825                              run->s390_tsch.subchannel_nr,
1826                              run->s390_tsch.io_int_parm,
1827                              run->s390_tsch.io_int_word);
1828        }
1829        ret = 0;
1830    }
1831    return ret;
1832}
1833
1834static void insert_stsi_3_2_2(S390CPU *cpu, __u64 addr, uint8_t ar)
1835{
1836    const MachineState *ms = MACHINE(qdev_get_machine());
1837    uint16_t conf_cpus = 0, reserved_cpus = 0;
1838    SysIB_322 sysib;
1839    int del, i;
1840
1841    if (s390_is_pv()) {
1842        s390_cpu_pv_mem_read(cpu, 0, &sysib, sizeof(sysib));
1843    } else if (s390_cpu_virt_mem_read(cpu, addr, ar, &sysib, sizeof(sysib))) {
1844        return;
1845    }
1846    /* Shift the stack of Extended Names to prepare for our own data */
1847    memmove(&sysib.ext_names[1], &sysib.ext_names[0],
1848            sizeof(sysib.ext_names[0]) * (sysib.count - 1));
1849    /* First virt level, that doesn't provide Ext Names delimits stack. It is
1850     * assumed it's not capable of managing Extended Names for lower levels.
1851     */
1852    for (del = 1; del < sysib.count; del++) {
1853        if (!sysib.vm[del].ext_name_encoding || !sysib.ext_names[del][0]) {
1854            break;
1855        }
1856    }
1857    if (del < sysib.count) {
1858        memset(sysib.ext_names[del], 0,
1859               sizeof(sysib.ext_names[0]) * (sysib.count - del));
1860    }
1861
1862    /* count the cpus and split them into configured and reserved ones */
1863    for (i = 0; i < ms->possible_cpus->len; i++) {
1864        if (ms->possible_cpus->cpus[i].cpu) {
1865            conf_cpus++;
1866        } else {
1867            reserved_cpus++;
1868        }
1869    }
1870    sysib.vm[0].total_cpus = conf_cpus + reserved_cpus;
1871    sysib.vm[0].conf_cpus = conf_cpus;
1872    sysib.vm[0].reserved_cpus = reserved_cpus;
1873
1874    /* Insert short machine name in EBCDIC, padded with blanks */
1875    if (qemu_name) {
1876        memset(sysib.vm[0].name, 0x40, sizeof(sysib.vm[0].name));
1877        ebcdic_put(sysib.vm[0].name, qemu_name, MIN(sizeof(sysib.vm[0].name),
1878                                                    strlen(qemu_name)));
1879    }
1880    sysib.vm[0].ext_name_encoding = 2; /* 2 = UTF-8 */
1881    /* If hypervisor specifies zero Extended Name in STSI322 SYSIB, it's
1882     * considered by s390 as not capable of providing any Extended Name.
1883     * Therefore if no name was specified on qemu invocation, we go with the
1884     * same "KVMguest" default, which KVM has filled into short name field.
1885     */
1886    strpadcpy((char *)sysib.ext_names[0],
1887              sizeof(sysib.ext_names[0]),
1888              qemu_name ?: "KVMguest", '\0');
1889
1890    /* Insert UUID */
1891    memcpy(sysib.vm[0].uuid, &qemu_uuid, sizeof(sysib.vm[0].uuid));
1892
1893    if (s390_is_pv()) {
1894        s390_cpu_pv_mem_write(cpu, 0, &sysib, sizeof(sysib));
1895    } else {
1896        s390_cpu_virt_mem_write(cpu, addr, ar, &sysib, sizeof(sysib));
1897    }
1898}
1899
1900static int handle_stsi(S390CPU *cpu)
1901{
1902    CPUState *cs = CPU(cpu);
1903    struct kvm_run *run = cs->kvm_run;
1904
1905    switch (run->s390_stsi.fc) {
1906    case 3:
1907        if (run->s390_stsi.sel1 != 2 || run->s390_stsi.sel2 != 2) {
1908            return 0;
1909        }
1910        /* Only sysib 3.2.2 needs post-handling for now. */
1911        insert_stsi_3_2_2(cpu, run->s390_stsi.addr, run->s390_stsi.ar);
1912        return 0;
1913    default:
1914        return 0;
1915    }
1916}
1917
1918static int kvm_arch_handle_debug_exit(S390CPU *cpu)
1919{
1920    CPUState *cs = CPU(cpu);
1921    struct kvm_run *run = cs->kvm_run;
1922
1923    int ret = 0;
1924    struct kvm_debug_exit_arch *arch_info = &run->debug.arch;
1925
1926    switch (arch_info->type) {
1927    case KVM_HW_WP_WRITE:
1928        if (find_hw_breakpoint(arch_info->addr, -1, arch_info->type)) {
1929            cs->watchpoint_hit = &hw_watchpoint;
1930            hw_watchpoint.vaddr = arch_info->addr;
1931            hw_watchpoint.flags = BP_MEM_WRITE;
1932            ret = EXCP_DEBUG;
1933        }
1934        break;
1935    case KVM_HW_BP:
1936        if (find_hw_breakpoint(arch_info->addr, -1, arch_info->type)) {
1937            ret = EXCP_DEBUG;
1938        }
1939        break;
1940    case KVM_SINGLESTEP:
1941        if (cs->singlestep_enabled) {
1942            ret = EXCP_DEBUG;
1943        }
1944        break;
1945    default:
1946        ret = -ENOSYS;
1947    }
1948
1949    return ret;
1950}
1951
1952int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
1953{
1954    S390CPU *cpu = S390_CPU(cs);
1955    int ret = 0;
1956
1957    qemu_mutex_lock_iothread();
1958
1959    kvm_cpu_synchronize_state(cs);
1960
1961    switch (run->exit_reason) {
1962        case KVM_EXIT_S390_SIEIC:
1963            ret = handle_intercept(cpu);
1964            break;
1965        case KVM_EXIT_S390_RESET:
1966            s390_ipl_reset_request(cs, S390_RESET_REIPL);
1967            break;
1968        case KVM_EXIT_S390_TSCH:
1969            ret = handle_tsch(cpu);
1970            break;
1971        case KVM_EXIT_S390_STSI:
1972            ret = handle_stsi(cpu);
1973            break;
1974        case KVM_EXIT_DEBUG:
1975            ret = kvm_arch_handle_debug_exit(cpu);
1976            break;
1977        default:
1978            fprintf(stderr, "Unknown KVM exit: %d\n", run->exit_reason);
1979            break;
1980    }
1981    qemu_mutex_unlock_iothread();
1982
1983    if (ret == 0) {
1984        ret = EXCP_INTERRUPT;
1985    }
1986    return ret;
1987}
1988
1989bool kvm_arch_stop_on_emulation_error(CPUState *cpu)
1990{
1991    return true;
1992}
1993
1994void kvm_s390_enable_css_support(S390CPU *cpu)
1995{
1996    int r;
1997
1998    /* Activate host kernel channel subsystem support. */
1999    r = kvm_vcpu_enable_cap(CPU(cpu), KVM_CAP_S390_CSS_SUPPORT, 0);
2000    assert(r == 0);
2001}
2002
2003void kvm_arch_init_irq_routing(KVMState *s)
2004{
2005    /*
2006     * Note that while irqchip capabilities generally imply that cpustates
2007     * are handled in-kernel, it is not true for s390 (yet); therefore, we
2008     * have to override the common code kvm_halt_in_kernel_allowed setting.
2009     */
2010    if (kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2011        kvm_gsi_routing_allowed = true;
2012        kvm_halt_in_kernel_allowed = false;
2013    }
2014}
2015
2016int kvm_s390_assign_subch_ioeventfd(EventNotifier *notifier, uint32_t sch,
2017                                    int vq, bool assign)
2018{
2019    struct kvm_ioeventfd kick = {
2020        .flags = KVM_IOEVENTFD_FLAG_VIRTIO_CCW_NOTIFY |
2021        KVM_IOEVENTFD_FLAG_DATAMATCH,
2022        .fd = event_notifier_get_fd(notifier),
2023        .datamatch = vq,
2024        .addr = sch,
2025        .len = 8,
2026    };
2027    trace_kvm_assign_subch_ioeventfd(kick.fd, kick.addr, assign,
2028                                     kick.datamatch);
2029    if (!kvm_check_extension(kvm_state, KVM_CAP_IOEVENTFD)) {
2030        return -ENOSYS;
2031    }
2032    if (!assign) {
2033        kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
2034    }
2035    return kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
2036}
2037
2038int kvm_s390_get_ri(void)
2039{
2040    return cap_ri;
2041}
2042
2043int kvm_s390_set_cpu_state(S390CPU *cpu, uint8_t cpu_state)
2044{
2045    struct kvm_mp_state mp_state = {};
2046    int ret;
2047
2048    /* the kvm part might not have been initialized yet */
2049    if (CPU(cpu)->kvm_state == NULL) {
2050        return 0;
2051    }
2052
2053    switch (cpu_state) {
2054    case S390_CPU_STATE_STOPPED:
2055        mp_state.mp_state = KVM_MP_STATE_STOPPED;
2056        break;
2057    case S390_CPU_STATE_CHECK_STOP:
2058        mp_state.mp_state = KVM_MP_STATE_CHECK_STOP;
2059        break;
2060    case S390_CPU_STATE_OPERATING:
2061        mp_state.mp_state = KVM_MP_STATE_OPERATING;
2062        break;
2063    case S390_CPU_STATE_LOAD:
2064        mp_state.mp_state = KVM_MP_STATE_LOAD;
2065        break;
2066    default:
2067        error_report("Requested CPU state is not a valid S390 CPU state: %u",
2068                     cpu_state);
2069        exit(1);
2070    }
2071
2072    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2073    if (ret) {
2074        trace_kvm_failed_cpu_state_set(CPU(cpu)->cpu_index, cpu_state,
2075                                       strerror(-ret));
2076    }
2077
2078    return ret;
2079}
2080
2081void kvm_s390_vcpu_interrupt_pre_save(S390CPU *cpu)
2082{
2083    unsigned int max_cpus = MACHINE(qdev_get_machine())->smp.max_cpus;
2084    struct kvm_s390_irq_state irq_state = {
2085        .buf = (uint64_t) cpu->irqstate,
2086        .len = VCPU_IRQ_BUF_SIZE(max_cpus),
2087    };
2088    CPUState *cs = CPU(cpu);
2089    int32_t bytes;
2090
2091    if (!kvm_check_extension(kvm_state, KVM_CAP_S390_IRQ_STATE)) {
2092        return;
2093    }
2094
2095    bytes = kvm_vcpu_ioctl(cs, KVM_S390_GET_IRQ_STATE, &irq_state);
2096    if (bytes < 0) {
2097        cpu->irqstate_saved_size = 0;
2098        error_report("Migration of interrupt state failed");
2099        return;
2100    }
2101
2102    cpu->irqstate_saved_size = bytes;
2103}
2104
2105int kvm_s390_vcpu_interrupt_post_load(S390CPU *cpu)
2106{
2107    CPUState *cs = CPU(cpu);
2108    struct kvm_s390_irq_state irq_state = {
2109        .buf = (uint64_t) cpu->irqstate,
2110        .len = cpu->irqstate_saved_size,
2111    };
2112    int r;
2113
2114    if (cpu->irqstate_saved_size == 0) {
2115        return 0;
2116    }
2117
2118    if (!kvm_check_extension(kvm_state, KVM_CAP_S390_IRQ_STATE)) {
2119        return -ENOSYS;
2120    }
2121
2122    r = kvm_vcpu_ioctl(cs, KVM_S390_SET_IRQ_STATE, &irq_state);
2123    if (r) {
2124        error_report("Setting interrupt state failed %d", r);
2125    }
2126    return r;
2127}
2128
2129int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
2130                             uint64_t address, uint32_t data, PCIDevice *dev)
2131{
2132    S390PCIBusDevice *pbdev;
2133    uint32_t vec = data & ZPCI_MSI_VEC_MASK;
2134
2135    if (!dev) {
2136        DPRINTF("add_msi_route no pci device\n");
2137        return -ENODEV;
2138    }
2139
2140    pbdev = s390_pci_find_dev_by_target(s390_get_phb(), DEVICE(dev)->id);
2141    if (!pbdev) {
2142        DPRINTF("add_msi_route no zpci device\n");
2143        return -ENODEV;
2144    }
2145
2146    route->type = KVM_IRQ_ROUTING_S390_ADAPTER;
2147    route->flags = 0;
2148    route->u.adapter.summary_addr = pbdev->routes.adapter.summary_addr;
2149    route->u.adapter.ind_addr = pbdev->routes.adapter.ind_addr;
2150    route->u.adapter.summary_offset = pbdev->routes.adapter.summary_offset;
2151    route->u.adapter.ind_offset = pbdev->routes.adapter.ind_offset + vec;
2152    route->u.adapter.adapter_id = pbdev->routes.adapter.adapter_id;
2153    return 0;
2154}
2155
2156int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
2157                                int vector, PCIDevice *dev)
2158{
2159    return 0;
2160}
2161
2162int kvm_arch_release_virq_post(int virq)
2163{
2164    return 0;
2165}
2166
2167int kvm_arch_msi_data_to_gsi(uint32_t data)
2168{
2169    abort();
2170}
2171
2172static int query_cpu_subfunc(S390FeatBitmap features)
2173{
2174    struct kvm_s390_vm_cpu_subfunc prop = {};
2175    struct kvm_device_attr attr = {
2176        .group = KVM_S390_VM_CPU_MODEL,
2177        .attr = KVM_S390_VM_CPU_MACHINE_SUBFUNC,
2178        .addr = (uint64_t) &prop,
2179    };
2180    int rc;
2181
2182    rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2183    if (rc) {
2184        return  rc;
2185    }
2186
2187    /*
2188     * We're going to add all subfunctions now, if the corresponding feature
2189     * is available that unlocks the query functions.
2190     */
2191    s390_add_from_feat_block(features, S390_FEAT_TYPE_PLO, prop.plo);
2192    if (test_bit(S390_FEAT_TOD_CLOCK_STEERING, features)) {
2193        s390_add_from_feat_block(features, S390_FEAT_TYPE_PTFF, prop.ptff);
2194    }
2195    if (test_bit(S390_FEAT_MSA, features)) {
2196        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMAC, prop.kmac);
2197        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMC, prop.kmc);
2198        s390_add_from_feat_block(features, S390_FEAT_TYPE_KM, prop.km);
2199        s390_add_from_feat_block(features, S390_FEAT_TYPE_KIMD, prop.kimd);
2200        s390_add_from_feat_block(features, S390_FEAT_TYPE_KLMD, prop.klmd);
2201    }
2202    if (test_bit(S390_FEAT_MSA_EXT_3, features)) {
2203        s390_add_from_feat_block(features, S390_FEAT_TYPE_PCKMO, prop.pckmo);
2204    }
2205    if (test_bit(S390_FEAT_MSA_EXT_4, features)) {
2206        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMCTR, prop.kmctr);
2207        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMF, prop.kmf);
2208        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMO, prop.kmo);
2209        s390_add_from_feat_block(features, S390_FEAT_TYPE_PCC, prop.pcc);
2210    }
2211    if (test_bit(S390_FEAT_MSA_EXT_5, features)) {
2212        s390_add_from_feat_block(features, S390_FEAT_TYPE_PPNO, prop.ppno);
2213    }
2214    if (test_bit(S390_FEAT_MSA_EXT_8, features)) {
2215        s390_add_from_feat_block(features, S390_FEAT_TYPE_KMA, prop.kma);
2216    }
2217    if (test_bit(S390_FEAT_MSA_EXT_9, features)) {
2218        s390_add_from_feat_block(features, S390_FEAT_TYPE_KDSA, prop.kdsa);
2219    }
2220    if (test_bit(S390_FEAT_ESORT_BASE, features)) {
2221        s390_add_from_feat_block(features, S390_FEAT_TYPE_SORTL, prop.sortl);
2222    }
2223    if (test_bit(S390_FEAT_DEFLATE_BASE, features)) {
2224        s390_add_from_feat_block(features, S390_FEAT_TYPE_DFLTCC, prop.dfltcc);
2225    }
2226    return 0;
2227}
2228
2229static int configure_cpu_subfunc(const S390FeatBitmap features)
2230{
2231    struct kvm_s390_vm_cpu_subfunc prop = {};
2232    struct kvm_device_attr attr = {
2233        .group = KVM_S390_VM_CPU_MODEL,
2234        .attr = KVM_S390_VM_CPU_PROCESSOR_SUBFUNC,
2235        .addr = (uint64_t) &prop,
2236    };
2237
2238    if (!kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2239                           KVM_S390_VM_CPU_PROCESSOR_SUBFUNC)) {
2240        /* hardware support might be missing, IBC will handle most of this */
2241        return 0;
2242    }
2243
2244    s390_fill_feat_block(features, S390_FEAT_TYPE_PLO, prop.plo);
2245    if (test_bit(S390_FEAT_TOD_CLOCK_STEERING, features)) {
2246        s390_fill_feat_block(features, S390_FEAT_TYPE_PTFF, prop.ptff);
2247    }
2248    if (test_bit(S390_FEAT_MSA, features)) {
2249        s390_fill_feat_block(features, S390_FEAT_TYPE_KMAC, prop.kmac);
2250        s390_fill_feat_block(features, S390_FEAT_TYPE_KMC, prop.kmc);
2251        s390_fill_feat_block(features, S390_FEAT_TYPE_KM, prop.km);
2252        s390_fill_feat_block(features, S390_FEAT_TYPE_KIMD, prop.kimd);
2253        s390_fill_feat_block(features, S390_FEAT_TYPE_KLMD, prop.klmd);
2254    }
2255    if (test_bit(S390_FEAT_MSA_EXT_3, features)) {
2256        s390_fill_feat_block(features, S390_FEAT_TYPE_PCKMO, prop.pckmo);
2257    }
2258    if (test_bit(S390_FEAT_MSA_EXT_4, features)) {
2259        s390_fill_feat_block(features, S390_FEAT_TYPE_KMCTR, prop.kmctr);
2260        s390_fill_feat_block(features, S390_FEAT_TYPE_KMF, prop.kmf);
2261        s390_fill_feat_block(features, S390_FEAT_TYPE_KMO, prop.kmo);
2262        s390_fill_feat_block(features, S390_FEAT_TYPE_PCC, prop.pcc);
2263    }
2264    if (test_bit(S390_FEAT_MSA_EXT_5, features)) {
2265        s390_fill_feat_block(features, S390_FEAT_TYPE_PPNO, prop.ppno);
2266    }
2267    if (test_bit(S390_FEAT_MSA_EXT_8, features)) {
2268        s390_fill_feat_block(features, S390_FEAT_TYPE_KMA, prop.kma);
2269    }
2270    if (test_bit(S390_FEAT_MSA_EXT_9, features)) {
2271        s390_fill_feat_block(features, S390_FEAT_TYPE_KDSA, prop.kdsa);
2272    }
2273    if (test_bit(S390_FEAT_ESORT_BASE, features)) {
2274        s390_fill_feat_block(features, S390_FEAT_TYPE_SORTL, prop.sortl);
2275    }
2276    if (test_bit(S390_FEAT_DEFLATE_BASE, features)) {
2277        s390_fill_feat_block(features, S390_FEAT_TYPE_DFLTCC, prop.dfltcc);
2278    }
2279    return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2280}
2281
2282static int kvm_to_feat[][2] = {
2283    { KVM_S390_VM_CPU_FEAT_ESOP, S390_FEAT_ESOP },
2284    { KVM_S390_VM_CPU_FEAT_SIEF2, S390_FEAT_SIE_F2 },
2285    { KVM_S390_VM_CPU_FEAT_64BSCAO , S390_FEAT_SIE_64BSCAO },
2286    { KVM_S390_VM_CPU_FEAT_SIIF, S390_FEAT_SIE_SIIF },
2287    { KVM_S390_VM_CPU_FEAT_GPERE, S390_FEAT_SIE_GPERE },
2288    { KVM_S390_VM_CPU_FEAT_GSLS, S390_FEAT_SIE_GSLS },
2289    { KVM_S390_VM_CPU_FEAT_IB, S390_FEAT_SIE_IB },
2290    { KVM_S390_VM_CPU_FEAT_CEI, S390_FEAT_SIE_CEI },
2291    { KVM_S390_VM_CPU_FEAT_IBS, S390_FEAT_SIE_IBS },
2292    { KVM_S390_VM_CPU_FEAT_SKEY, S390_FEAT_SIE_SKEY },
2293    { KVM_S390_VM_CPU_FEAT_CMMA, S390_FEAT_SIE_CMMA },
2294    { KVM_S390_VM_CPU_FEAT_PFMFI, S390_FEAT_SIE_PFMFI},
2295    { KVM_S390_VM_CPU_FEAT_SIGPIF, S390_FEAT_SIE_SIGPIF},
2296    { KVM_S390_VM_CPU_FEAT_KSS, S390_FEAT_SIE_KSS},
2297};
2298
2299static int query_cpu_feat(S390FeatBitmap features)
2300{
2301    struct kvm_s390_vm_cpu_feat prop = {};
2302    struct kvm_device_attr attr = {
2303        .group = KVM_S390_VM_CPU_MODEL,
2304        .attr = KVM_S390_VM_CPU_MACHINE_FEAT,
2305        .addr = (uint64_t) &prop,
2306    };
2307    int rc;
2308    int i;
2309
2310    rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2311    if (rc) {
2312        return  rc;
2313    }
2314
2315    for (i = 0; i < ARRAY_SIZE(kvm_to_feat); i++) {
2316        if (test_be_bit(kvm_to_feat[i][0], (uint8_t *) prop.feat)) {
2317            set_bit(kvm_to_feat[i][1], features);
2318        }
2319    }
2320    return 0;
2321}
2322
2323static int configure_cpu_feat(const S390FeatBitmap features)
2324{
2325    struct kvm_s390_vm_cpu_feat prop = {};
2326    struct kvm_device_attr attr = {
2327        .group = KVM_S390_VM_CPU_MODEL,
2328        .attr = KVM_S390_VM_CPU_PROCESSOR_FEAT,
2329        .addr = (uint64_t) &prop,
2330    };
2331    int i;
2332
2333    for (i = 0; i < ARRAY_SIZE(kvm_to_feat); i++) {
2334        if (test_bit(kvm_to_feat[i][1], features)) {
2335            set_be_bit(kvm_to_feat[i][0], (uint8_t *) prop.feat);
2336        }
2337    }
2338    return kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2339}
2340
2341bool kvm_s390_cpu_models_supported(void)
2342{
2343    if (!cpu_model_allowed()) {
2344        /* compatibility machines interfere with the cpu model */
2345        return false;
2346    }
2347    return kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2348                             KVM_S390_VM_CPU_MACHINE) &&
2349           kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2350                             KVM_S390_VM_CPU_PROCESSOR) &&
2351           kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2352                             KVM_S390_VM_CPU_MACHINE_FEAT) &&
2353           kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2354                             KVM_S390_VM_CPU_PROCESSOR_FEAT) &&
2355           kvm_vm_check_attr(kvm_state, KVM_S390_VM_CPU_MODEL,
2356                             KVM_S390_VM_CPU_MACHINE_SUBFUNC);
2357}
2358
2359void kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
2360{
2361    struct kvm_s390_vm_cpu_machine prop = {};
2362    struct kvm_device_attr attr = {
2363        .group = KVM_S390_VM_CPU_MODEL,
2364        .attr = KVM_S390_VM_CPU_MACHINE,
2365        .addr = (uint64_t) &prop,
2366    };
2367    uint16_t unblocked_ibc = 0, cpu_type = 0;
2368    int rc;
2369
2370    memset(model, 0, sizeof(*model));
2371
2372    if (!kvm_s390_cpu_models_supported()) {
2373        error_setg(errp, "KVM doesn't support CPU models");
2374        return;
2375    }
2376
2377    /* query the basic cpu model properties */
2378    rc = kvm_vm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr);
2379    if (rc) {
2380        error_setg(errp, "KVM: Error querying host CPU model: %d", rc);
2381        return;
2382    }
2383
2384    cpu_type = cpuid_type(prop.cpuid);
2385    if (has_ibc(prop.ibc)) {
2386        model->lowest_ibc = lowest_ibc(prop.ibc);
2387        unblocked_ibc = unblocked_ibc(prop.ibc);
2388    }
2389    model->cpu_id = cpuid_id(prop.cpuid);
2390    model->cpu_id_format = cpuid_format(prop.cpuid);
2391    model->cpu_ver = 0xff;
2392
2393    /* get supported cpu features indicated via STFL(E) */
2394    s390_add_from_feat_block(model->features, S390_FEAT_TYPE_STFL,
2395                             (uint8_t *) prop.fac_mask);
2396    /* dat-enhancement facility 2 has no bit but was introduced with stfle */
2397    if (test_bit(S390_FEAT_STFLE, model->features)) {
2398        set_bit(S390_FEAT_DAT_ENH_2, model->features);
2399    }
2400    /* get supported cpu features indicated e.g. via SCLP */
2401    rc = query_cpu_feat(model->features);
2402    if (rc) {
2403        error_setg(errp, "KVM: Error querying CPU features: %d", rc);
2404        return;
2405    }
2406    /* get supported cpu subfunctions indicated via query / test bit */
2407    rc = query_cpu_subfunc(model->features);
2408    if (rc) {
2409        error_setg(errp, "KVM: Error querying CPU subfunctions: %d", rc);
2410        return;
2411    }
2412
2413    /* PTFF subfunctions might be indicated although kernel support missing */
2414    if (!test_bit(S390_FEAT_MULTIPLE_EPOCH, model->features)) {
2415        clear_bit(S390_FEAT_PTFF_QSIE, model->features);
2416        clear_bit(S390_FEAT_PTFF_QTOUE, model->features);
2417        clear_bit(S390_FEAT_PTFF_STOE, model->features);
2418        clear_bit(S390_FEAT_PTFF_STOUE, model->features);
2419    }
2420
2421    /* with cpu model support, CMM is only indicated if really available */
2422    if (kvm_s390_cmma_available()) {
2423        set_bit(S390_FEAT_CMM, model->features);
2424    } else {
2425        /* no cmm -> no cmm nt */
2426        clear_bit(S390_FEAT_CMM_NT, model->features);
2427    }
2428
2429    /* bpb needs kernel support for migration, VSIE and reset */
2430    if (!kvm_check_extension(kvm_state, KVM_CAP_S390_BPB)) {
2431        clear_bit(S390_FEAT_BPB, model->features);
2432    }
2433
2434    /*
2435     * If we have support for protected virtualization, indicate
2436     * the protected virtualization IPL unpack facility.
2437     */
2438    if (cap_protected) {
2439        set_bit(S390_FEAT_UNPACK, model->features);
2440    }
2441
2442    /* We emulate a zPCI bus and AEN, therefore we don't need HW support */
2443    set_bit(S390_FEAT_ZPCI, model->features);
2444    set_bit(S390_FEAT_ADAPTER_EVENT_NOTIFICATION, model->features);
2445
2446    if (s390_known_cpu_type(cpu_type)) {
2447        /* we want the exact model, even if some features are missing */
2448        model->def = s390_find_cpu_def(cpu_type, ibc_gen(unblocked_ibc),
2449                                       ibc_ec_ga(unblocked_ibc), NULL);
2450    } else {
2451        /* model unknown, e.g. too new - search using features */
2452        model->def = s390_find_cpu_def(0, ibc_gen(unblocked_ibc),
2453                                       ibc_ec_ga(unblocked_ibc),
2454                                       model->features);
2455    }
2456    if (!model->def) {
2457        error_setg(errp, "KVM: host CPU model could not be identified");
2458        return;
2459    }
2460    /* for now, we can only provide the AP feature with HW support */
2461    if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO,
2462        KVM_S390_VM_CRYPTO_ENABLE_APIE)) {
2463        set_bit(S390_FEAT_AP, model->features);
2464    }
2465
2466    /*
2467     * Extended-Length SCCB is handled entirely within QEMU.
2468     * For PV guests this is completely fenced by the Ultravisor, as Service
2469     * Call error checking and STFLE interpretation are handled via SIE.
2470     */
2471    set_bit(S390_FEAT_EXTENDED_LENGTH_SCCB, model->features);
2472
2473    if (kvm_check_extension(kvm_state, KVM_CAP_S390_DIAG318)) {
2474        set_bit(S390_FEAT_DIAG_318, model->features);
2475    }
2476
2477    /* strip of features that are not part of the maximum model */
2478    bitmap_and(model->features, model->features, model->def->full_feat,
2479               S390_FEAT_MAX);
2480}
2481
2482static void kvm_s390_configure_apie(bool interpret)
2483{
2484    uint64_t attr = interpret ? KVM_S390_VM_CRYPTO_ENABLE_APIE :
2485                                KVM_S390_VM_CRYPTO_DISABLE_APIE;
2486
2487    if (kvm_vm_check_attr(kvm_state, KVM_S390_VM_CRYPTO, attr)) {
2488        kvm_s390_set_attr(attr);
2489    }
2490}
2491
2492void kvm_s390_apply_cpu_model(const S390CPUModel *model, Error **errp)
2493{
2494    struct kvm_s390_vm_cpu_processor prop  = {
2495        .fac_list = { 0 },
2496    };
2497    struct kvm_device_attr attr = {
2498        .group = KVM_S390_VM_CPU_MODEL,
2499        .attr = KVM_S390_VM_CPU_PROCESSOR,
2500        .addr = (uint64_t) &prop,
2501    };
2502    int rc;
2503
2504    if (!model) {
2505        /* compatibility handling if cpu models are disabled */
2506        if (kvm_s390_cmma_available()) {
2507            kvm_s390_enable_cmma();
2508        }
2509        return;
2510    }
2511    if (!kvm_s390_cpu_models_supported()) {
2512        error_setg(errp, "KVM doesn't support CPU models");
2513        return;
2514    }
2515    prop.cpuid = s390_cpuid_from_cpu_model(model);
2516    prop.ibc = s390_ibc_from_cpu_model(model);
2517    /* configure cpu features indicated via STFL(e) */
2518    s390_fill_feat_block(model->features, S390_FEAT_TYPE_STFL,
2519                         (uint8_t *) prop.fac_list);
2520    rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);
2521    if (rc) {
2522        error_setg(errp, "KVM: Error configuring the CPU model: %d", rc);
2523        return;
2524    }
2525    /* configure cpu features indicated e.g. via SCLP */
2526    rc = configure_cpu_feat(model->features);
2527    if (rc) {
2528        error_setg(errp, "KVM: Error configuring CPU features: %d", rc);
2529        return;
2530    }
2531    /* configure cpu subfunctions indicated via query / test bit */
2532    rc = configure_cpu_subfunc(model->features);
2533    if (rc) {
2534        error_setg(errp, "KVM: Error configuring CPU subfunctions: %d", rc);
2535        return;
2536    }
2537    /* enable CMM via CMMA */
2538    if (test_bit(S390_FEAT_CMM, model->features)) {
2539        kvm_s390_enable_cmma();
2540    }
2541
2542    if (test_bit(S390_FEAT_AP, model->features)) {
2543        kvm_s390_configure_apie(true);
2544    }
2545}
2546
2547void kvm_s390_restart_interrupt(S390CPU *cpu)
2548{
2549    struct kvm_s390_irq irq = {
2550        .type = KVM_S390_RESTART,
2551    };
2552
2553    kvm_s390_vcpu_interrupt(cpu, &irq);
2554}
2555
2556void kvm_s390_stop_interrupt(S390CPU *cpu)
2557{
2558    struct kvm_s390_irq irq = {
2559        .type = KVM_S390_SIGP_STOP,
2560    };
2561
2562    kvm_s390_vcpu_interrupt(cpu, &irq);
2563}
2564
2565bool kvm_arch_cpu_check_are_resettable(void)
2566{
2567    return true;
2568}
2569