diff options
author | SeokYeon Hwang <syeon.hwang@samsung.com> | 2014-12-10 14:48:31 +0900 |
---|---|---|
committer | SeokYeon Hwang <syeon.hwang@samsung.com> | 2014-12-10 14:53:58 +0900 |
commit | ec77d208f0cc6de712c9b0b1345726a7258e57a1 (patch) | |
tree | df8e4db1190ed8ebaedd408ca7a55e4165106b44 /hw | |
parent | 96d2ac1f7274a69ec439581b75152bf9a4efd3a2 (diff) | |
parent | d00e6cddc220de993573dfb5fd160ac72ccd49ab (diff) | |
download | qemu-ec77d208f0cc6de712c9b0b1345726a7258e57a1.tar.gz qemu-ec77d208f0cc6de712c9b0b1345726a7258e57a1.tar.bz2 qemu-ec77d208f0cc6de712c9b0b1345726a7258e57a1.zip |
Merge 'v2.2.0' into tizen_next_qemu_2.2
v2.2.0 release
Conflicts:
blockdev.c
configure
cpu-exec.c
exec.c
hw/Makefile.objs
hw/i386/pc_piix.c
qom/object.c
target-i386/translate.c
util/oslib-posix.c
util/oslib-win32.c
vl.c
xen-hvm.c
Signed-off-by: SeokYeon Hwang <syeon.hwang@samsung.com>
Change-Id: I0f708eddfb51b98b9a7453e6e92f20c90a8b5aaf
Diffstat (limited to 'hw')
510 files changed, 28191 insertions, 12198 deletions
diff --git a/hw/9pfs/virtio-9p-device.c b/hw/9pfs/virtio-9p-device.c index 05dd75999d..6edc495d60 100644 --- a/hw/9pfs/virtio-9p-device.c +++ b/hw/9pfs/virtio-9p-device.c @@ -19,6 +19,7 @@ #include "fsdev/qemu-fsdev.h" #include "virtio-9p-xattr.h" #include "virtio-9p-coth.h" +#include "hw/virtio/virtio-access.h" #ifdef CONFIG_MARU #include "tizen/src/util/maru_err_table.h" @@ -38,7 +39,7 @@ static void virtio_9p_get_config(VirtIODevice *vdev, uint8_t *config) len = strlen(s->tag); cfg = g_malloc0(sizeof(struct virtio_9p_config) + len); - stw_raw(&cfg->tag_len, len); + virtio_stw_p(vdev, &cfg->tag_len, len); /* We don't copy the terminating null to config space */ memcpy(cfg->tag, s->tag, len); memcpy(config, cfg, s->config_size); diff --git a/hw/9pfs/virtio-9p-local.c b/hw/9pfs/virtio-9p-local.c index 56b302c122..a183eee662 100644 --- a/hw/9pfs/virtio-9p-local.c +++ b/hw/9pfs/virtio-9p-local.c @@ -14,6 +14,7 @@ #include "hw/virtio/virtio.h" #include "virtio-9p.h" #include "virtio-9p-xattr.h" +#include "fsdev/qemu-fsdev.h" /* local_ops */ #include <arpa/inet.h> #include <pwd.h> #include <grp.h> @@ -134,17 +135,17 @@ static int local_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf) mode_t tmp_mode; dev_t tmp_dev; if (getxattr(buffer, "user.virtfs.uid", &tmp_uid, sizeof(uid_t)) > 0) { - stbuf->st_uid = tmp_uid; + stbuf->st_uid = le32_to_cpu(tmp_uid); } if (getxattr(buffer, "user.virtfs.gid", &tmp_gid, sizeof(gid_t)) > 0) { - stbuf->st_gid = tmp_gid; + stbuf->st_gid = le32_to_cpu(tmp_gid); } if (getxattr(buffer, "user.virtfs.mode", &tmp_mode, sizeof(mode_t)) > 0) { - stbuf->st_mode = tmp_mode; + stbuf->st_mode = le32_to_cpu(tmp_mode); } if (getxattr(buffer, "user.virtfs.rdev", &tmp_dev, sizeof(dev_t)) > 0) { - stbuf->st_rdev = tmp_dev; + stbuf->st_rdev = le64_to_cpu(tmp_dev); } } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { local_mapped_file_attr(fs_ctx, path, stbuf); @@ -254,29 +255,29 @@ static int local_set_xattr(const char *path, FsCred *credp) int err; if (credp->fc_uid != -1) { - err = setxattr(path, "user.virtfs.uid", &credp->fc_uid, sizeof(uid_t), - 0); + uint32_t tmp_uid = cpu_to_le32(credp->fc_uid); + err = setxattr(path, "user.virtfs.uid", &tmp_uid, sizeof(uid_t), 0); if (err) { return err; } } if (credp->fc_gid != -1) { - err = setxattr(path, "user.virtfs.gid", &credp->fc_gid, sizeof(gid_t), - 0); + uint32_t tmp_gid = cpu_to_le32(credp->fc_gid); + err = setxattr(path, "user.virtfs.gid", &tmp_gid, sizeof(gid_t), 0); if (err) { return err; } } if (credp->fc_mode != -1) { - err = setxattr(path, "user.virtfs.mode", &credp->fc_mode, - sizeof(mode_t), 0); + uint32_t tmp_mode = cpu_to_le32(credp->fc_mode); + err = setxattr(path, "user.virtfs.mode", &tmp_mode, sizeof(mode_t), 0); if (err) { return err; } } if (credp->fc_rdev != -1) { - err = setxattr(path, "user.virtfs.rdev", &credp->fc_rdev, - sizeof(dev_t), 0); + uint64_t tmp_rdev = cpu_to_le64(credp->fc_rdev); + err = setxattr(path, "user.virtfs.rdev", &tmp_rdev, sizeof(dev_t), 0); if (err) { return err; } @@ -396,12 +397,15 @@ static int local_readdir_r(FsContext *ctx, V9fsFidOpenState *fs, again: ret = readdir_r(fs->dir, entry, result); - if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + if (ctx->export_flags & V9FS_SM_MAPPED) { + entry->d_type = DT_UNKNOWN; + } else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { if (!ret && *result != NULL && !strcmp(entry->d_name, VIRTFS_META_DIR)) { /* skp the meta data directory */ goto again; } + entry->d_type = DT_UNKNOWN; } return ret; } @@ -629,21 +633,17 @@ static int local_fstat(FsContext *fs_ctx, int fid_type, mode_t tmp_mode; dev_t tmp_dev; - if (fgetxattr(fd, "user.virtfs.uid", - &tmp_uid, sizeof(uid_t)) > 0) { - stbuf->st_uid = tmp_uid; + if (fgetxattr(fd, "user.virtfs.uid", &tmp_uid, sizeof(uid_t)) > 0) { + stbuf->st_uid = le32_to_cpu(tmp_uid); } - if (fgetxattr(fd, "user.virtfs.gid", - &tmp_gid, sizeof(gid_t)) > 0) { - stbuf->st_gid = tmp_gid; + if (fgetxattr(fd, "user.virtfs.gid", &tmp_gid, sizeof(gid_t)) > 0) { + stbuf->st_gid = le32_to_cpu(tmp_gid); } - if (fgetxattr(fd, "user.virtfs.mode", - &tmp_mode, sizeof(mode_t)) > 0) { - stbuf->st_mode = tmp_mode; + if (fgetxattr(fd, "user.virtfs.mode", &tmp_mode, sizeof(mode_t)) > 0) { + stbuf->st_mode = le32_to_cpu(tmp_mode); } - if (fgetxattr(fd, "user.virtfs.rdev", - &tmp_dev, sizeof(dev_t)) > 0) { - stbuf->st_rdev = tmp_dev; + if (fgetxattr(fd, "user.virtfs.rdev", &tmp_dev, sizeof(dev_t)) > 0) { + stbuf->st_rdev = le64_to_cpu(tmp_dev); } } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { errno = EOPNOTSUPP; diff --git a/hw/9pfs/virtio-9p-maru.c b/hw/9pfs/virtio-9p-maru.c index 0811794527..6cd62bb8b2 100644 --- a/hw/9pfs/virtio-9p-maru.c +++ b/hw/9pfs/virtio-9p-maru.c @@ -1087,8 +1087,9 @@ static void v9fs_attach(void *opaque) */ if (!s->migration_blocker) { s->root_fid = fid; - error_set(&s->migration_blocker, QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION, - s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); + error_setg(&s->migration_blocker, + "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'", + s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); migrate_add_blocker(s->migration_blocker); } out: diff --git a/hw/9pfs/virtio-9p-proxy.c b/hw/9pfs/virtio-9p-proxy.c index b57966d9d8..59c7445dea 100644 --- a/hw/9pfs/virtio-9p-proxy.c +++ b/hw/9pfs/virtio-9p-proxy.c @@ -1104,14 +1104,15 @@ static int connect_namedsocket(const char *path) sockfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd < 0) { - fprintf(stderr, "socket %s\n", strerror(errno)); + fprintf(stderr, "failed to create socket: %s\n", strerror(errno)); return -1; } strcpy(helper.sun_path, path); helper.sun_family = AF_UNIX; size = strlen(helper.sun_path) + sizeof(helper.sun_family); if (connect(sockfd, (struct sockaddr *)&helper, size) < 0) { - fprintf(stderr, "socket error\n"); + fprintf(stderr, "failed to connect to %s: %s\n", path, strerror(errno)); + close(sockfd); return -1; } @@ -1154,10 +1155,12 @@ static int proxy_init(FsContext *ctx) sock_id = atoi(ctx->fs_root); if (sock_id < 0) { fprintf(stderr, "socket descriptor not initialized\n"); - g_free(proxy); - return -1; } } + if (sock_id < 0) { + g_free(proxy); + return -1; + } g_free(ctx->fs_root); ctx->fs_root = NULL; diff --git a/hw/9pfs/virtio-9p-synth.c b/hw/9pfs/virtio-9p-synth.c index 840e4ebb5a..71262bccd2 100644 --- a/hw/9pfs/virtio-9p-synth.c +++ b/hw/9pfs/virtio-9p-synth.c @@ -21,7 +21,7 @@ #include <sys/stat.h> /* Root node for synth file system */ -V9fsSynthNode v9fs_synth_root = { +static V9fsSynthNode v9fs_synth_root = { .name = "/", .actual_attr = { .mode = 0555 | S_IFDIR, diff --git a/hw/9pfs/virtio-9p.c b/hw/9pfs/virtio-9p.c index 83e4e93983..5861a5b826 100644 --- a/hw/9pfs/virtio-9p.c +++ b/hw/9pfs/virtio-9p.c @@ -299,9 +299,7 @@ static int v9fs_xattr_fid_clunk(V9fsPDU *pdu, V9fsFidState *fidp) free_out: v9fs_string_free(&fidp->fs.xattr.name); free_value: - if (fidp->fs.xattr.value) { - g_free(fidp->fs.xattr.value); - } + g_free(fidp->fs.xattr.value); return retval; } @@ -987,8 +985,9 @@ static void v9fs_attach(void *opaque) */ if (!s->migration_blocker) { s->root_fid = fid; - error_set(&s->migration_blocker, QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION, - s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); + error_setg(&s->migration_blocker, + "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'", + s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); migrate_add_blocker(s->migration_blocker); } out: diff --git a/hw/Makefile.objs b/hw/Makefile.objs index a6ac525e0e..a43a06a215 100644 --- a/hw/Makefile.objs +++ b/hw/Makefile.objs @@ -29,6 +29,7 @@ devices-dirs-$(CONFIG_SOFTMMU) += usb/ devices-dirs-$(CONFIG_VIRTIO) += virtio/ devices-dirs-$(CONFIG_SOFTMMU) += watchdog/ devices-dirs-$(CONFIG_SOFTMMU) += xen/ +devices-dirs-$(CONFIG_MEM_HOTPLUG) += mem/ devices-dirs-$(CONFIG_BUILD_VIGS) += yagl/ devices-dirs-$(CONFIG_BUILD_VIGS) += vigs/ devices-dirs-y += core/ diff --git a/hw/acpi/Makefile.objs b/hw/acpi/Makefile.objs index 397d32babd..acd2389431 100644 --- a/hw/acpi/Makefile.objs +++ b/hw/acpi/Makefile.objs @@ -1 +1,3 @@ common-obj-$(CONFIG_ACPI) += core.o piix4.o ich9.o pcihp.o cpu_hotplug.o +common-obj-$(CONFIG_ACPI) += memory_hotplug.o +common-obj-$(CONFIG_ACPI) += acpi_interface.o diff --git a/hw/acpi/acpi_interface.c b/hw/acpi/acpi_interface.c new file mode 100644 index 0000000000..c181bb2262 --- /dev/null +++ b/hw/acpi/acpi_interface.c @@ -0,0 +1,15 @@ +#include "hw/acpi/acpi_dev_interface.h" +#include "qemu/module.h" + +static void register_types(void) +{ + static const TypeInfo acpi_dev_if_info = { + .name = TYPE_ACPI_DEVICE_IF, + .parent = TYPE_INTERFACE, + .class_size = sizeof(AcpiDeviceIfClass), + }; + + type_register_static(&acpi_dev_if_info); +} + +type_init(register_types) diff --git a/hw/acpi/core.c b/hw/acpi/core.c index 79414b44c7..51913d6932 100644 --- a/hw/acpi/core.c +++ b/hw/acpi/core.c @@ -22,11 +22,11 @@ #include "hw/hw.h" #include "hw/i386/pc.h" #include "hw/acpi/acpi.h" -#include "monitor/monitor.h" #include "qemu/config-file.h" #include "qapi/opts-visitor.h" #include "qapi/dealloc-visitor.h" #include "qapi-visit.h" +#include "qapi-event.h" struct acpi_table_header { uint16_t _length; /* our length, not actual part of the hdr */ @@ -376,8 +376,11 @@ static void acpi_notify_wakeup(Notifier *notifier, void *data) /* ACPI PM1a EVT */ uint16_t acpi_pm1_evt_get_sts(ACPIREGS *ar) { - int64_t d = acpi_pm_tmr_get_clock(); - if (d >= ar->tmr.overflow_time) { + /* Compare ns-clock, not PM timer ticks, because + acpi_pm_tmr_update function uses ns for setting the timer. */ + int64_t d = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); + if (d >= muldiv64(ar->tmr.overflow_time, + get_ticks_per_sec(), PM_TIMER_FREQUENCY)) { ar->pm1.evt.sts |= ACPI_BITMASK_TIMER_STATUS; } return ar->pm1.evt.sts; @@ -550,7 +553,7 @@ static void acpi_pm1_cnt_write(ACPIREGS *ar, uint16_t val) break; default: if (sus_typ == ar->pm1.cnt.s4_val) { /* S4 request */ - monitor_protocol_event(QEVENT_SUSPEND_DISK, NULL); + qapi_event_send_suspend_disk(&error_abort); qemu_system_shutdown_request(); } break; diff --git a/hw/acpi/cpu_hotplug.c b/hw/acpi/cpu_hotplug.c index 2ad83a0ede..b8ebfadc30 100644 --- a/hw/acpi/cpu_hotplug.c +++ b/hw/acpi/cpu_hotplug.c @@ -36,28 +36,40 @@ static const MemoryRegionOps AcpiCpuHotplug_ops = { }, }; -void AcpiCpuHotplug_add(ACPIGPE *gpe, AcpiCpuHotplug *g, CPUState *cpu) +static void acpi_set_cpu_present_bit(AcpiCpuHotplug *g, CPUState *cpu, + Error **errp) { CPUClass *k = CPU_GET_CLASS(cpu); int64_t cpu_id; - *gpe->sts = *gpe->sts | ACPI_CPU_HOTPLUG_STATUS; - cpu_id = k->get_arch_id(CPU(cpu)); - g_assert((cpu_id / 8) < ACPI_GPE_PROC_LEN); + cpu_id = k->get_arch_id(cpu); + if ((cpu_id / 8) >= ACPI_GPE_PROC_LEN) { + error_setg(errp, "acpi: invalid cpu id: %" PRIi64, cpu_id); + return; + } + g->sts[cpu_id / 8] |= (1 << (cpu_id % 8)); } -void AcpiCpuHotplug_init(MemoryRegion *parent, Object *owner, - AcpiCpuHotplug *gpe_cpu, uint16_t base) +void acpi_cpu_plug_cb(ACPIREGS *ar, qemu_irq irq, + AcpiCpuHotplug *g, DeviceState *dev, Error **errp) +{ + acpi_set_cpu_present_bit(g, CPU(dev), errp); + if (*errp != NULL) { + return; + } + + ar->gpe.sts[0] |= ACPI_CPU_HOTPLUG_STATUS; + acpi_update_sci(ar, irq); +} + +void acpi_cpu_hotplug_init(MemoryRegion *parent, Object *owner, + AcpiCpuHotplug *gpe_cpu, uint16_t base) { CPUState *cpu; CPU_FOREACH(cpu) { - CPUClass *cc = CPU_GET_CLASS(cpu); - int64_t id = cc->get_arch_id(cpu); - - g_assert((id / 8) < ACPI_GPE_PROC_LEN); - gpe_cpu->sts[id / 8] |= (1 << (id % 8)); + acpi_set_cpu_present_bit(gpe_cpu, cpu, &error_abort); } memory_region_init_io(&gpe_cpu->io, owner, &AcpiCpuHotplug_ops, gpe_cpu, "acpi-cpu-hotplug", ACPI_GPE_PROC_LEN); diff --git a/hw/acpi/ich9.c b/hw/acpi/ich9.c index 8e4e97251b..5cbe653fd6 100644 --- a/hw/acpi/ich9.c +++ b/hw/acpi/ich9.c @@ -35,6 +35,7 @@ #include "exec/address-spaces.h" #include "hw/i386/ich9.h" +#include "hw/mem/pc-dimm.h" //#define DEBUG @@ -140,11 +141,27 @@ static int ich9_pm_post_load(void *opaque, int version_id) .offset = vmstate_offset_pointer(_state, _field, uint8_t), \ } +static bool vmstate_test_use_memhp(void *opaque) +{ + ICH9LPCPMRegs *s = opaque; + return s->acpi_memory_hotplug.is_enabled; +} + +static const VMStateDescription vmstate_memhp_state = { + .name = "ich9_pm/memhp", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .fields = (VMStateField[]) { + VMSTATE_MEMORY_HOTPLUG(acpi_memory_hotplug, ICH9LPCPMRegs), + VMSTATE_END_OF_LIST() + } +}; + const VMStateDescription vmstate_ich9_pm = { .name = "ich9_pm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = ich9_pm_post_load, .fields = (VMStateField[]) { VMSTATE_UINT16(acpi_regs.pm1.evt.sts, ICH9LPCPMRegs), @@ -157,6 +174,13 @@ const VMStateDescription vmstate_ich9_pm = { VMSTATE_UINT32(smi_en, ICH9LPCPMRegs), VMSTATE_UINT32(smi_sts, ICH9LPCPMRegs), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_memhp_state, + .needed = vmstate_test_use_memhp, + }, + VMSTATE_END_OF_LIST() } }; @@ -186,15 +210,6 @@ static void pm_powerdown_req(Notifier *n, void *opaque) acpi_pm1_evt_power_down(&pm->acpi_regs); } -static void ich9_cpu_added_req(Notifier *n, void *opaque) -{ - ICH9LPCPMRegs *pm = container_of(n, ICH9LPCPMRegs, cpu_added_notifier); - - assert(pm != NULL); - AcpiCpuHotplug_add(&pm->acpi_regs.gpe, &pm->gpe_cpu, CPU(opaque)); - acpi_update_sci(&pm->acpi_regs, pm->irq); -} - void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm, qemu_irq sci_irq) { @@ -209,11 +224,11 @@ void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm, acpi_gpe_init(&pm->acpi_regs, ICH9_PMIO_GPE0_LEN); memory_region_init_io(&pm->io_gpe, OBJECT(lpc_pci), &ich9_gpe_ops, pm, - "apci-gpe0", ICH9_PMIO_GPE0_LEN); + "acpi-gpe0", ICH9_PMIO_GPE0_LEN); memory_region_add_subregion(&pm->io, ICH9_PMIO_GPE0_STS, &pm->io_gpe); memory_region_init_io(&pm->io_smi, OBJECT(lpc_pci), &ich9_smi_ops, pm, - "apci-smi", 8); + "acpi-smi", 8); memory_region_add_subregion(&pm->io, ICH9_PMIO_SMI_EN, &pm->io_smi); pm->irq = sci_irq; @@ -221,10 +236,13 @@ void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm, pm->powerdown_notifier.notify = pm_powerdown_req; qemu_register_powerdown_notifier(&pm->powerdown_notifier); - AcpiCpuHotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci), - &pm->gpe_cpu, ICH9_CPU_HOTPLUG_IO_BASE); - pm->cpu_added_notifier.notify = ich9_cpu_added_req; - qemu_register_cpu_added_notifier(&pm->cpu_added_notifier); + acpi_cpu_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci), + &pm->gpe_cpu, ICH9_CPU_HOTPLUG_IO_BASE); + + if (pm->acpi_memory_hotplug.is_enabled) { + acpi_memory_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci), + &pm->acpi_memory_hotplug); + } } static void ich9_pm_get_gpe0_blk(Object *obj, Visitor *v, @@ -237,9 +255,25 @@ static void ich9_pm_get_gpe0_blk(Object *obj, Visitor *v, visit_type_uint32(v, &value, name, errp); } +static bool ich9_pm_get_memory_hotplug_support(Object *obj, Error **errp) +{ + ICH9LPCState *s = ICH9_LPC_DEVICE(obj); + + return s->pm.acpi_memory_hotplug.is_enabled; +} + +static void ich9_pm_set_memory_hotplug_support(Object *obj, bool value, + Error **errp) +{ + ICH9LPCState *s = ICH9_LPC_DEVICE(obj); + + s->pm.acpi_memory_hotplug.is_enabled = value; +} + void ich9_pm_add_properties(Object *obj, ICH9LPCPMRegs *pm, Error **errp) { static const uint32_t gpe0_len = ICH9_PMIO_GPE0_LEN; + pm->acpi_memory_hotplug.is_enabled = true; object_property_add_uint32_ptr(obj, ACPI_PM_PROP_PM_IO_BASE, &pm->pm_io_base, errp); @@ -248,4 +282,29 @@ void ich9_pm_add_properties(Object *obj, ICH9LPCPMRegs *pm, Error **errp) NULL, NULL, pm, NULL); object_property_add_uint32_ptr(obj, ACPI_PM_PROP_GPE0_BLK_LEN, &gpe0_len, errp); + object_property_add_bool(obj, "memory-hotplug-support", + ich9_pm_get_memory_hotplug_support, + ich9_pm_set_memory_hotplug_support, + NULL); +} + +void ich9_pm_device_plug_cb(ICH9LPCPMRegs *pm, DeviceState *dev, Error **errp) +{ + if (pm->acpi_memory_hotplug.is_enabled && + object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) { + acpi_memory_plug_cb(&pm->acpi_regs, pm->irq, &pm->acpi_memory_hotplug, + dev, errp); + } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) { + acpi_cpu_plug_cb(&pm->acpi_regs, pm->irq, &pm->gpe_cpu, dev, errp); + } else { + error_setg(errp, "acpi: device plug request for not supported device" + " type: %s", object_get_typename(OBJECT(dev))); + } +} + +void ich9_pm_ospm_status(AcpiDeviceIf *adev, ACPIOSTInfoList ***list) +{ + ICH9LPCState *s = ICH9_LPC_DEVICE(adev); + + acpi_memory_ospm_status(&s->pm.acpi_memory_hotplug, list); } diff --git a/hw/acpi/memory_hotplug.c b/hw/acpi/memory_hotplug.c new file mode 100644 index 0000000000..ed3924126f --- /dev/null +++ b/hw/acpi/memory_hotplug.c @@ -0,0 +1,223 @@ +#include "hw/acpi/memory_hotplug.h" +#include "hw/acpi/pc-hotplug.h" +#include "hw/mem/pc-dimm.h" +#include "hw/boards.h" +#include "trace.h" +#include "qapi-event.h" + +static ACPIOSTInfo *acpi_memory_device_status(int slot, MemStatus *mdev) +{ + ACPIOSTInfo *info = g_new0(ACPIOSTInfo, 1); + + info->slot_type = ACPI_SLOT_TYPE_DIMM; + info->slot = g_strdup_printf("%d", slot); + info->source = mdev->ost_event; + info->status = mdev->ost_status; + if (mdev->dimm) { + DeviceState *dev = DEVICE(mdev->dimm); + if (dev->id) { + info->device = g_strdup(dev->id); + info->has_device = true; + } + } + return info; +} + +void acpi_memory_ospm_status(MemHotplugState *mem_st, ACPIOSTInfoList ***list) +{ + int i; + + for (i = 0; i < mem_st->dev_count; i++) { + ACPIOSTInfoList *elem = g_new0(ACPIOSTInfoList, 1); + elem->value = acpi_memory_device_status(i, &mem_st->devs[i]); + elem->next = NULL; + **list = elem; + *list = &elem->next; + } +} + +static uint64_t acpi_memory_hotplug_read(void *opaque, hwaddr addr, + unsigned int size) +{ + uint32_t val = 0; + MemHotplugState *mem_st = opaque; + MemStatus *mdev; + Object *o; + + if (mem_st->selector >= mem_st->dev_count) { + trace_mhp_acpi_invalid_slot_selected(mem_st->selector); + return 0; + } + + mdev = &mem_st->devs[mem_st->selector]; + o = OBJECT(mdev->dimm); + switch (addr) { + case 0x0: /* Lo part of phys address where DIMM is mapped */ + val = o ? object_property_get_int(o, PC_DIMM_ADDR_PROP, NULL) : 0; + trace_mhp_acpi_read_addr_lo(mem_st->selector, val); + break; + case 0x4: /* Hi part of phys address where DIMM is mapped */ + val = o ? object_property_get_int(o, PC_DIMM_ADDR_PROP, NULL) >> 32 : 0; + trace_mhp_acpi_read_addr_hi(mem_st->selector, val); + break; + case 0x8: /* Lo part of DIMM size */ + val = o ? object_property_get_int(o, PC_DIMM_SIZE_PROP, NULL) : 0; + trace_mhp_acpi_read_size_lo(mem_st->selector, val); + break; + case 0xc: /* Hi part of DIMM size */ + val = o ? object_property_get_int(o, PC_DIMM_SIZE_PROP, NULL) >> 32 : 0; + trace_mhp_acpi_read_size_hi(mem_st->selector, val); + break; + case 0x10: /* node proximity for _PXM method */ + val = o ? object_property_get_int(o, PC_DIMM_NODE_PROP, NULL) : 0; + trace_mhp_acpi_read_pxm(mem_st->selector, val); + break; + case 0x14: /* pack and return is_* fields */ + val |= mdev->is_enabled ? 1 : 0; + val |= mdev->is_inserting ? 2 : 0; + trace_mhp_acpi_read_flags(mem_st->selector, val); + break; + default: + val = ~0; + break; + } + return val; +} + +static void acpi_memory_hotplug_write(void *opaque, hwaddr addr, uint64_t data, + unsigned int size) +{ + MemHotplugState *mem_st = opaque; + MemStatus *mdev; + ACPIOSTInfo *info; + + if (!mem_st->dev_count) { + return; + } + + if (addr) { + if (mem_st->selector >= mem_st->dev_count) { + trace_mhp_acpi_invalid_slot_selected(mem_st->selector); + return; + } + } + + switch (addr) { + case 0x0: /* DIMM slot selector */ + mem_st->selector = data; + trace_mhp_acpi_write_slot(mem_st->selector); + break; + case 0x4: /* _OST event */ + mdev = &mem_st->devs[mem_st->selector]; + if (data == 1) { + /* TODO: handle device insert OST event */ + } else if (data == 3) { + /* TODO: handle device remove OST event */ + } + mdev->ost_event = data; + trace_mhp_acpi_write_ost_ev(mem_st->selector, mdev->ost_event); + break; + case 0x8: /* _OST status */ + mdev = &mem_st->devs[mem_st->selector]; + mdev->ost_status = data; + trace_mhp_acpi_write_ost_status(mem_st->selector, mdev->ost_status); + /* TODO: implement memory removal on guest signal */ + + info = acpi_memory_device_status(mem_st->selector, mdev); + qapi_event_send_acpi_device_ost(info, &error_abort); + qapi_free_ACPIOSTInfo(info); + break; + case 0x14: + mdev = &mem_st->devs[mem_st->selector]; + if (data & 2) { /* clear insert event */ + mdev->is_inserting = false; + trace_mhp_acpi_clear_insert_evt(mem_st->selector); + } + break; + } + +} +static const MemoryRegionOps acpi_memory_hotplug_ops = { + .read = acpi_memory_hotplug_read, + .write = acpi_memory_hotplug_write, + .endianness = DEVICE_LITTLE_ENDIAN, + .valid = { + .min_access_size = 1, + .max_access_size = 4, + }, +}; + +void acpi_memory_hotplug_init(MemoryRegion *as, Object *owner, + MemHotplugState *state) +{ + MachineState *machine = MACHINE(qdev_get_machine()); + + state->dev_count = machine->ram_slots; + if (!state->dev_count) { + return; + } + + state->devs = g_malloc0(sizeof(*state->devs) * state->dev_count); + memory_region_init_io(&state->io, owner, &acpi_memory_hotplug_ops, state, + "acpi-mem-hotplug", ACPI_MEMORY_HOTPLUG_IO_LEN); + memory_region_add_subregion(as, ACPI_MEMORY_HOTPLUG_BASE, &state->io); +} + +void acpi_memory_plug_cb(ACPIREGS *ar, qemu_irq irq, MemHotplugState *mem_st, + DeviceState *dev, Error **errp) +{ + MemStatus *mdev; + Error *local_err = NULL; + int slot = object_property_get_int(OBJECT(dev), "slot", &local_err); + + if (local_err) { + error_propagate(errp, local_err); + return; + } + + if (slot >= mem_st->dev_count) { + char *dev_path = object_get_canonical_path(OBJECT(dev)); + error_setg(errp, "acpi_memory_plug_cb: " + "device [%s] returned invalid memory slot[%d]", + dev_path, slot); + g_free(dev_path); + return; + } + + mdev = &mem_st->devs[slot]; + mdev->dimm = dev; + mdev->is_enabled = true; + mdev->is_inserting = true; + + /* do ACPI magic */ + ar->gpe.sts[0] |= ACPI_MEMORY_HOTPLUG_STATUS; + acpi_update_sci(ar, irq); + return; +} + +static const VMStateDescription vmstate_memhp_sts = { + .name = "memory hotplug device state", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .fields = (VMStateField[]) { + VMSTATE_BOOL(is_enabled, MemStatus), + VMSTATE_BOOL(is_inserting, MemStatus), + VMSTATE_UINT32(ost_event, MemStatus), + VMSTATE_UINT32(ost_status, MemStatus), + VMSTATE_END_OF_LIST() + } +}; + +const VMStateDescription vmstate_memory_hotplug = { + .name = "memory hotplug state", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT32(selector, MemHotplugState), + VMSTATE_STRUCT_VARRAY_POINTER_UINT32(devs, MemHotplugState, dev_count, + vmstate_memhp_sts, MemStatus), + VMSTATE_END_OF_LIST() + } +}; diff --git a/hw/acpi/pcihp.c b/hw/acpi/pcihp.c index f80c48008c..34dedf1e8b 100644 --- a/hw/acpi/pcihp.c +++ b/hw/acpi/pcihp.c @@ -63,16 +63,18 @@ typedef struct AcpiPciHpFind { static int acpi_pcihp_get_bsel(PCIBus *bus) { - QObject *o = object_property_get_qobject(OBJECT(bus), - ACPI_PCIHP_PROP_BSEL, NULL); - int64_t bsel = -1; - if (o) { - bsel = qint_get_int(qobject_to_qint(o)); - } - if (bsel < 0) { + Error *local_err = NULL; + int64_t bsel = object_property_get_int(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, + &local_err); + + if (local_err || bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { + if (local_err) { + error_free(local_err); + } return -1; + } else { + return bsel; } - return bsel; } static void acpi_pcihp_test_hotplug_bus(PCIBus *bus, void *opaque) @@ -229,7 +231,7 @@ static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) uint32_t val = 0; int bsel = s->hotplug_select; - if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) { + if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { return 0; } @@ -322,8 +324,7 @@ const VMStateDescription vmstate_acpi_pcihp_pci_status = { .name = "acpi_pcihp_pci_status", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(up, AcpiPciHpPciStatus), VMSTATE_UINT32(down, AcpiPciHpPciStatus), VMSTATE_END_OF_LIST() diff --git a/hw/acpi/piix4.c b/hw/acpi/piix4.c index 9bfea6c5f6..9842caaf65 100644 --- a/hw/acpi/piix4.c +++ b/hw/acpi/piix4.c @@ -34,6 +34,10 @@ #include "hw/acpi/pcihp.h" #include "hw/acpi/cpu_hotplug.h" #include "hw/hotplug.h" +#include "hw/mem/pc-dimm.h" +#include "hw/acpi/memory_hotplug.h" +#include "hw/acpi/acpi_dev_interface.h" +#include "hw/xen/xen.h" #ifdef CONFIG_MARU #include "tizen/src/hw/maru_pm.h" @@ -85,7 +89,8 @@ typedef struct PIIX4PMState { uint8_t s4_val; AcpiCpuHotplug gpe_cpu; - Notifier cpu_added_notifier; + + MemHotplugState acpi_memory_hotplug; } PIIX4PMState; #define TYPE_PIIX4_PM "PIIX4_PM" @@ -182,8 +187,7 @@ static const VMStateDescription vmstate_gpe = { .name = "gpe", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_GPE_ARRAY(sts, ACPIGPE), VMSTATE_GPE_ARRAY(en, ACPIGPE), VMSTATE_END_OF_LIST() @@ -194,8 +198,7 @@ static const VMStateDescription vmstate_pci_status = { .name = "pci_status", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(up, struct AcpiPciHpPciStatus), VMSTATE_UINT32(down, struct AcpiPciHpPciStatus), VMSTATE_END_OF_LIST() @@ -251,6 +254,23 @@ static bool vmstate_test_no_use_acpi_pci_hotplug(void *opaque, int version_id) return !s->use_acpi_pci_hotplug; } +static bool vmstate_test_use_memhp(void *opaque) +{ + PIIX4PMState *s = opaque; + return s->acpi_memory_hotplug.is_enabled; +} + +static const VMStateDescription vmstate_memhp_state = { + .name = "piix4_pm/memhp", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .fields = (VMStateField[]) { + VMSTATE_MEMORY_HOTPLUG(acpi_memory_hotplug, PIIX4PMState), + VMSTATE_END_OF_LIST() + } +}; + /* qemu-kvm 1.2 uses version 3 but advertised as 2 * To support incoming qemu-kvm 1.2 migration, change version_id * and minimum_version_id to 2 below (which breaks migration from @@ -264,7 +284,7 @@ static const VMStateDescription vmstate_acpi = { .minimum_version_id_old = 1, .load_state_old = acpi_load_old, .post_load = vmstate_acpi_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PIIX4PMState), VMSTATE_UINT16(ar.pm1.evt.sts, PIIX4PMState), VMSTATE_UINT16(ar.pm1.evt.en, PIIX4PMState), @@ -282,6 +302,13 @@ static const VMStateDescription vmstate_acpi = { VMSTATE_PCI_HOTPLUG(acpi_pci_hotplug, PIIX4PMState, vmstate_test_use_acpi_pci_hotplug), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_memhp_state, + .needed = vmstate_test_use_memhp, + }, + VMSTATE_END_OF_LIST() } }; @@ -315,19 +342,37 @@ static void piix4_pm_powerdown_req(Notifier *n, void *opaque) acpi_pm1_evt_power_down(&s->ar); } -static void piix4_pci_device_plug_cb(HotplugHandler *hotplug_dev, - DeviceState *dev, Error **errp) +static void piix4_device_plug_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { PIIX4PMState *s = PIIX4_PM(hotplug_dev); - acpi_pcihp_device_plug_cb(&s->ar, s->irq, &s->acpi_pci_hotplug, dev, errp); + + if (s->acpi_memory_hotplug.is_enabled && + object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) { + acpi_memory_plug_cb(&s->ar, s->irq, &s->acpi_memory_hotplug, dev, errp); + } else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) { + acpi_pcihp_device_plug_cb(&s->ar, s->irq, &s->acpi_pci_hotplug, dev, + errp); + } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) { + acpi_cpu_plug_cb(&s->ar, s->irq, &s->gpe_cpu, dev, errp); + } else { + error_setg(errp, "acpi: device plug request for not supported device" + " type: %s", object_get_typename(OBJECT(dev))); + } } -static void piix4_pci_device_unplug_cb(HotplugHandler *hotplug_dev, - DeviceState *dev, Error **errp) +static void piix4_device_unplug_request_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { PIIX4PMState *s = PIIX4_PM(hotplug_dev); - acpi_pcihp_device_unplug_cb(&s->ar, s->irq, &s->acpi_pci_hotplug, dev, - errp); + + if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) { + acpi_pcihp_device_unplug_cb(&s->ar, s->irq, &s->acpi_pci_hotplug, dev, + errp); + } else { + error_setg(errp, "acpi: device unplug request for not supported device" + " type: %s", object_get_typename(OBJECT(dev))); + } } static void piix4_update_bus_hotplug(PCIBus *pci_bus, void *opaque) @@ -449,18 +494,25 @@ Object *piix4_pm_find(void) I2CBus *piix4_pm_init(PCIBus *bus, int devfn, uint32_t smb_io_base, qemu_irq sci_irq, qemu_irq smi_irq, - int kvm_enabled, FWCfgState *fw_cfg) + int kvm_enabled, FWCfgState *fw_cfg, + DeviceState **piix4_pm) { DeviceState *dev; PIIX4PMState *s; dev = DEVICE(pci_create(bus, devfn, TYPE_PIIX4_PM)); qdev_prop_set_uint32(dev, "smb_io_base", smb_io_base); + if (piix4_pm) { + *piix4_pm = dev; + } s = PIIX4_PM(dev); s->irq = sci_irq; s->smi_irq = smi_irq; s->kvm_enabled = kvm_enabled; + if (xen_enabled()) { + s->use_acpi_pci_hotplug = false; + } qdev_init_nofail(dev); @@ -505,15 +557,6 @@ static const MemoryRegionOps piix4_gpe_ops = { .endianness = DEVICE_LITTLE_ENDIAN, }; -static void piix4_cpu_added_req(Notifier *n, void *opaque) -{ - PIIX4PMState *s = container_of(n, PIIX4PMState, cpu_added_notifier); - - assert(s != NULL); - AcpiCpuHotplug_add(&s->ar.gpe, &s->gpe_cpu, CPU(opaque)); - acpi_update_sci(&s->ar, s->irq); -} - static void piix4_acpi_system_hot_add_init(MemoryRegion *parent, PCIBus *bus, PIIX4PMState *s) { @@ -524,10 +567,19 @@ static void piix4_acpi_system_hot_add_init(MemoryRegion *parent, acpi_pcihp_init(&s->acpi_pci_hotplug, bus, parent, s->use_acpi_pci_hotplug); - AcpiCpuHotplug_init(parent, OBJECT(s), &s->gpe_cpu, - PIIX4_CPU_HOTPLUG_IO_BASE); - s->cpu_added_notifier.notify = piix4_cpu_added_req; - qemu_register_cpu_added_notifier(&s->cpu_added_notifier); + acpi_cpu_hotplug_init(parent, OBJECT(s), &s->gpe_cpu, + PIIX4_CPU_HOTPLUG_IO_BASE); + + if (s->acpi_memory_hotplug.is_enabled) { + acpi_memory_hotplug_init(parent, OBJECT(s), &s->acpi_memory_hotplug); + } +} + +static void piix4_ospm_status(AcpiDeviceIf *adev, ACPIOSTInfoList ***list) +{ + PIIX4PMState *s = PIIX4_PM(adev); + + acpi_memory_ospm_status(&s->acpi_memory_hotplug, list); } static Property piix4_pm_properties[] = { @@ -537,6 +589,8 @@ static Property piix4_pm_properties[] = { DEFINE_PROP_UINT8(ACPI_PM_PROP_S4_VAL, PIIX4PMState, s4_val, 2), DEFINE_PROP_BOOL("acpi-pci-hotplug-with-bridge-support", PIIX4PMState, use_acpi_pci_hotplug, true), + DEFINE_PROP_BOOL("memory-hotplug-support", PIIX4PMState, + acpi_memory_hotplug.is_enabled, true), DEFINE_PROP_END_OF_LIST(), }; @@ -545,6 +599,7 @@ static void piix4_pm_class_init(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); + AcpiDeviceIfClass *adevc = ACPI_DEVICE_IF_CLASS(klass); k->init = piix4_pm_initfn; k->config_write = pm_write_config; @@ -561,8 +616,9 @@ static void piix4_pm_class_init(ObjectClass *klass, void *data) */ dc->cannot_instantiate_with_device_add_yet = true; dc->hotpluggable = false; - hc->plug = piix4_pci_device_plug_cb; - hc->unplug = piix4_pci_device_unplug_cb; + hc->plug = piix4_device_plug_cb; + hc->unplug_request = piix4_device_unplug_request_cb; + adevc->ospm_status = piix4_ospm_status; } static const TypeInfo piix4_pm_info = { @@ -572,6 +628,7 @@ static const TypeInfo piix4_pm_info = { .class_init = piix4_pm_class_init, .interfaces = (InterfaceInfo[]) { { TYPE_HOTPLUG_HANDLER }, + { TYPE_ACPI_DEVICE_IF }, { } } }; diff --git a/hw/alpha/dp264.c b/hw/alpha/dp264.c index 1351ba55bd..84a55e41a2 100644 --- a/hw/alpha/dp264.c +++ b/hw/alpha/dp264.c @@ -43,13 +43,13 @@ static int clipper_pci_map_irq(PCIDevice *d, int irq_num) return (slot + 1) * 4 + irq_num; } -static void clipper_init(QEMUMachineInitArgs *args) +static void clipper_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; AlphaCPU *cpus[4]; PCIBus *pci_bus; ISABus *isa_bus; @@ -97,7 +97,7 @@ static void clipper_init(QEMUMachineInitArgs *args) /* IDE disk setup. */ { DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS]; - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); pci_cmd646_ide_init(pci_bus, hd, 0); } diff --git a/hw/alpha/typhoon.c b/hw/alpha/typhoon.c index 67a1070281..53100061d2 100644 --- a/hw/alpha/typhoon.c +++ b/hw/alpha/typhoon.c @@ -660,7 +660,8 @@ static bool window_translate(TyphoonWindow *win, hwaddr addr, /* Handle PCI-to-system address translation. */ /* TODO: A translation failure here ought to set PCI error codes on the Pchip and generate a machine check interrupt. */ -static IOMMUTLBEntry typhoon_translate_iommu(MemoryRegion *iommu, hwaddr addr) +static IOMMUTLBEntry typhoon_translate_iommu(MemoryRegion *iommu, hwaddr addr, + bool is_write) { TyphoonPchip *pchip = container_of(iommu, TyphoonPchip, iommu); IOMMUTLBEntry ret; @@ -843,7 +844,8 @@ PCIBus *typhoon_init(ram_addr_t ram_size, ISABus **isa_bus, /* Main memory region, 0x00.0000.0000. Real hardware supports 32GB, but the address space hole reserved at this point is 8TB. */ - memory_region_init_ram(&s->ram_region, OBJECT(s), "ram", ram_size); + memory_region_init_ram(&s->ram_region, OBJECT(s), "ram", ram_size, + &error_abort); vmstate_register_ram_global(&s->ram_region); memory_region_add_subregion(addr_space, 0, &s->ram_region); diff --git a/hw/arm/armv7m.c b/hw/arm/armv7m.c index 397e8dfb37..ef24ca40fc 100644 --- a/hw/arm/armv7m.c +++ b/hw/arm/armv7m.c @@ -166,7 +166,7 @@ static void armv7m_reset(void *opaque) flash_size and sram_size are in kb. Returns the NVIC array. */ -qemu_irq *armv7m_init(MemoryRegion *address_space_mem, +qemu_irq *armv7m_init(MemoryRegion *system_memory, int flash_size, int sram_size, const char *kernel_filename, const char *cpu_model) { @@ -210,13 +210,14 @@ qemu_irq *armv7m_init(MemoryRegion *address_space_mem, #endif /* Flash programming is done via the SCU, so pretend it is ROM. */ - memory_region_init_ram(flash, NULL, "armv7m.flash", flash_size); + memory_region_init_ram(flash, NULL, "armv7m.flash", flash_size, + &error_abort); vmstate_register_ram_global(flash); memory_region_set_readonly(flash, true); - memory_region_add_subregion(address_space_mem, 0, flash); - memory_region_init_ram(sram, NULL, "armv7m.sram", sram_size); + memory_region_add_subregion(system_memory, 0, flash); + memory_region_init_ram(sram, NULL, "armv7m.sram", sram_size, &error_abort); vmstate_register_ram_global(sram); - memory_region_add_subregion(address_space_mem, 0x20000000, sram); + memory_region_add_subregion(system_memory, 0x20000000, sram); armv7m_bitband_init(); nvic = qdev_create(NULL, "armv7m_nvic"); @@ -255,9 +256,9 @@ qemu_irq *armv7m_init(MemoryRegion *address_space_mem, /* Hack to map an additional page of ram at the top of the address space. This stops qemu complaining about executing code outside RAM when returning from an exception. */ - memory_region_init_ram(hack, NULL, "armv7m.hack", 0x1000); + memory_region_init_ram(hack, NULL, "armv7m.hack", 0x1000, &error_abort); vmstate_register_ram_global(hack); - memory_region_add_subregion(address_space_mem, 0xfffff000, hack); + memory_region_add_subregion(system_memory, 0xfffff000, hack); qemu_register_reset(armv7m_reset, cpu); return pic; diff --git a/hw/arm/boot.c b/hw/arm/boot.c index 3d1f4a255b..0014c34ddd 100644 --- a/hw/arm/boot.c +++ b/hw/arm/boot.c @@ -312,7 +312,26 @@ static void set_kernel_args_old(const struct arm_boot_info *info) } } -static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo) +/** + * load_dtb() - load a device tree binary image into memory + * @addr: the address to load the image at + * @binfo: struct describing the boot environment + * @addr_limit: upper limit of the available memory area at @addr + * + * Load a device tree supplied by the machine or by the user with the + * '-dtb' command line option, and put it at offset @addr in target + * memory. + * + * If @addr_limit contains a meaningful value (i.e., it is strictly greater + * than @addr), the device tree is only loaded if its size does not exceed + * the limit. + * + * Returns: the size of the device tree image on success, + * 0 if the image size exceeds the limit, + * -1 on errors. + */ +static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo, + hwaddr addr_limit) { void *fdt = NULL; int size, rc; @@ -341,6 +360,15 @@ static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo) } } + if (addr_limit > addr && size > (addr_limit - addr)) { + /* Installing the device tree blob at addr would exceed addr_limit. + * Whether this constitutes failure is up to the caller to decide, + * so just return 0 as size, i.e., no error. + */ + g_free(fdt); + return 0; + } + acells = qemu_fdt_getprop_cell(fdt, "/", "#address-cells"); scells = qemu_fdt_getprop_cell(fdt, "/", "#size-cells"); if (acells == 0 || scells == 0) { @@ -396,11 +424,14 @@ static int load_dtb(hwaddr addr, const struct arm_boot_info *binfo) qemu_fdt_dumpdtb(fdt, size); - cpu_physical_memory_write(addr, fdt, size); + /* Put the DTB into the memory map as a ROM image: this will ensure + * the DTB is copied again upon reset, even if addr points into RAM. + */ + rom_add_blob_fixed("dtb", fdt, size, addr); g_free(fdt); - return 0; + return size; fail: g_free(fdt); @@ -417,8 +448,12 @@ static void do_cpu_reset(void *opaque) if (info) { if (!info->is_linux) { /* Jump to the entry point. */ - env->regs[15] = info->entry & 0xfffffffe; - env->thumb = info->entry & 1; + if (env->aarch64) { + env->pc = info->entry; + } else { + env->regs[15] = info->entry & 0xfffffffe; + env->thumb = info->entry & 1; + } } else { if (CPU(cpu) == first_cpu) { if (env->aarch64) { @@ -443,18 +478,37 @@ static void do_cpu_reset(void *opaque) void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info) { - CPUState *cs = CPU(cpu); + CPUState *cs; int kernel_size; int initrd_size; int is_linux = 0; - uint64_t elf_entry; + uint64_t elf_entry, elf_low_addr, elf_high_addr; int elf_machine; hwaddr entry, kernel_load_offset; int big_endian; static const ARMInsnFixup *primary_loader; + /* CPU objects (unlike devices) are not automatically reset on system + * reset, so we must always register a handler to do so. If we're + * actually loading a kernel, the handler is also responsible for + * arranging that we start it correctly. + */ + for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) { + qemu_register_reset(do_cpu_reset, ARM_CPU(cs)); + } + /* Load the kernel. */ if (!info->kernel_filename) { + + if (have_dtb(info)) { + /* If we have a device tree blob, but no kernel to supply it to, + * copy it to the base of RAM for a bootloader to pick up. + */ + if (load_dtb(info->loader_start, info, 0) < 0) { + exit(1); + } + } + /* If no kernel specified, do nothing; we will start from address 0 * (typically a boot ROM image) in the same way as hardware. */ @@ -504,11 +558,36 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info) /* Assume that raw images are linux kernels, and ELF images are not. */ kernel_size = load_elf(info->kernel_filename, NULL, NULL, &elf_entry, - NULL, NULL, big_endian, elf_machine, 1); + &elf_low_addr, &elf_high_addr, big_endian, + elf_machine, 1); + if (kernel_size > 0 && have_dtb(info)) { + /* If there is still some room left at the base of RAM, try and put + * the DTB there like we do for images loaded with -bios or -pflash. + */ + if (elf_low_addr > info->loader_start + || elf_high_addr < info->loader_start) { + /* Pass elf_low_addr as address limit to load_dtb if it may be + * pointing into RAM, otherwise pass '0' (no limit) + */ + if (elf_low_addr < info->loader_start) { + elf_low_addr = 0; + } + if (load_dtb(info->loader_start, info, elf_low_addr) < 0) { + exit(1); + } + } + } entry = elf_entry; if (kernel_size < 0) { kernel_size = load_uimage(info->kernel_filename, &entry, NULL, - &is_linux); + &is_linux, NULL, NULL); + } + /* On aarch64, it's the bootloader's job to uncompress the kernel. */ + if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64) && kernel_size < 0) { + entry = info->loader_start + kernel_load_offset; + kernel_size = load_image_gzipped(info->kernel_filename, entry, + info->ram_size - kernel_load_offset); + is_linux = 1; } if (kernel_size < 0) { entry = info->loader_start + kernel_load_offset; @@ -558,7 +637,7 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info) */ hwaddr dtb_start = QEMU_ALIGN_UP(info->initrd_start + initrd_size, 4096); - if (load_dtb(dtb_start, info)) { + if (load_dtb(dtb_start, info, 0) < 0) { exit(1); } fixupcontext[FIXUP_ARGPTR] = dtb_start; @@ -582,9 +661,7 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info) } info->is_linux = is_linux; - for (; cs; cs = CPU_NEXT(cs)) { - cpu = ARM_CPU(cs); - cpu->env.boot_info = info; - qemu_register_reset(do_cpu_reset, cpu); + for (cs = CPU(cpu); cs; cs = CPU_NEXT(cs)) { + ARM_CPU(cs)->env.boot_info = info; } } diff --git a/hw/arm/collie.c b/hw/arm/collie.c index 8878b0ed9a..6c9b82fc54 100644 --- a/hw/arm/collie.c +++ b/hw/arm/collie.c @@ -15,7 +15,7 @@ #include "strongarm.h" #include "hw/arm/arm.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" static struct arm_boot_info collie_binfo = { @@ -23,12 +23,12 @@ static struct arm_boot_info collie_binfo = { .ram_size = 0x20000000, }; -static void collie_init(QEMUMachineInitArgs *args) +static void collie_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; StrongARMState *s; DriveInfo *dinfo; MemoryRegion *sysmem = get_system_memory(); @@ -41,13 +41,13 @@ static void collie_init(QEMUMachineInitArgs *args) dinfo = drive_get(IF_PFLASH, 0, 0); pflash_cfi01_register(SA_CS0, NULL, "collie.fl1", 0x02000000, - dinfo ? dinfo->bdrv : NULL, (64 * 1024), - 512, 4, 0x00, 0x00, 0x00, 0x00, 0); + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0); dinfo = drive_get(IF_PFLASH, 0, 1); pflash_cfi01_register(SA_CS1, NULL, "collie.fl2", 0x02000000, - dinfo ? dinfo->bdrv : NULL, (64 * 1024), - 512, 4, 0x00, 0x00, 0x00, 0x00, 0); + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (64 * 1024), 512, 4, 0x00, 0x00, 0x00, 0x00, 0); sysbus_create_simple("scoop", 0x40800000, NULL); diff --git a/hw/arm/cubieboard.c b/hw/arm/cubieboard.c index d95a7f35eb..d1e53be923 100644 --- a/hw/arm/cubieboard.c +++ b/hw/arm/cubieboard.c @@ -30,7 +30,7 @@ typedef struct CubieBoardState { MemoryRegion sdram; } CubieBoardState; -static void cubieboard_init(QEMUMachineInitArgs *args) +static void cubieboard_init(MachineState *machine) { CubieBoardState *s = g_new(CubieBoardState, 1); Error *err = NULL; @@ -43,6 +43,19 @@ static void cubieboard_init(QEMUMachineInitArgs *args) exit(1); } + object_property_set_int(OBJECT(&s->a10->timer), 32768, "clk0-freq", &err); + if (err != NULL) { + error_report("Couldn't set clk0 frequency: %s", error_get_pretty(err)); + exit(1); + } + + object_property_set_int(OBJECT(&s->a10->timer), 24000000, "clk1-freq", + &err); + if (err != NULL) { + error_report("Couldn't set clk1 frequency: %s", error_get_pretty(err)); + exit(1); + } + object_property_set_bool(OBJECT(s->a10), true, "realized", &err); if (err != NULL) { error_report("Couldn't realize Allwinner A10: %s", @@ -50,14 +63,15 @@ static void cubieboard_init(QEMUMachineInitArgs *args) exit(1); } - memory_region_init_ram(&s->sdram, NULL, "cubieboard.ram", args->ram_size); + memory_region_init_ram(&s->sdram, NULL, "cubieboard.ram", + machine->ram_size, &error_abort); vmstate_register_ram_global(&s->sdram); memory_region_add_subregion(get_system_memory(), AW_A10_SDRAM_BASE, &s->sdram); - cubieboard_binfo.ram_size = args->ram_size; - cubieboard_binfo.kernel_filename = args->kernel_filename; - cubieboard_binfo.kernel_cmdline = args->kernel_cmdline; + cubieboard_binfo.ram_size = machine->ram_size; + cubieboard_binfo.kernel_filename = machine->kernel_filename; + cubieboard_binfo.kernel_cmdline = machine->kernel_cmdline; arm_load_kernel(&s->a10->cpu, &cubieboard_binfo); } diff --git a/hw/arm/digic_boards.c b/hw/arm/digic_boards.c index 32fc30a69d..2a4b8720a6 100644 --- a/hw/arm/digic_boards.c +++ b/hw/arm/digic_boards.c @@ -51,7 +51,7 @@ typedef struct DigicBoard { static void digic4_board_setup_ram(DigicBoardState *s, hwaddr ram_size) { - memory_region_init_ram(&s->ram, NULL, "ram", ram_size); + memory_region_init_ram(&s->ram, NULL, "ram", ram_size, &error_abort); memory_region_add_subregion(get_system_memory(), 0, &s->ram); vmstate_register_ram_global(&s->ram); } @@ -143,7 +143,7 @@ static DigicBoard digic4_board_canon_a1100 = { .rom1_def_filename = "canon-a1100-rom1.bin", }; -static void canon_a1100_init(QEMUMachineInitArgs *args) +static void canon_a1100_init(MachineState *machine) { digic4_board_init(&digic4_board_canon_a1100); } diff --git a/hw/arm/exynos4210.c b/hw/arm/exynos4210.c index 6426d168d2..582794c19f 100644 --- a/hw/arm/exynos4210.c +++ b/hw/arm/exynos4210.c @@ -248,7 +248,7 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem, /* Internal ROM */ memory_region_init_ram(&s->irom_mem, NULL, "exynos4210.irom", - EXYNOS4210_IROM_SIZE); + EXYNOS4210_IROM_SIZE, &error_abort); vmstate_register_ram_global(&s->irom_mem); memory_region_set_readonly(&s->irom_mem, true); memory_region_add_subregion(system_mem, EXYNOS4210_IROM_BASE_ADDR, @@ -264,7 +264,7 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem, /* Internal RAM */ memory_region_init_ram(&s->iram_mem, NULL, "exynos4210.iram", - EXYNOS4210_IRAM_SIZE); + EXYNOS4210_IRAM_SIZE, &error_abort); vmstate_register_ram_global(&s->iram_mem); memory_region_add_subregion(system_mem, EXYNOS4210_IRAM_BASE_ADDR, &s->iram_mem); @@ -273,13 +273,14 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem, mem_size = ram_size; if (mem_size > EXYNOS4210_DRAM_MAX_SIZE) { memory_region_init_ram(&s->dram1_mem, NULL, "exynos4210.dram1", - mem_size - EXYNOS4210_DRAM_MAX_SIZE); + mem_size - EXYNOS4210_DRAM_MAX_SIZE, &error_abort); vmstate_register_ram_global(&s->dram1_mem); memory_region_add_subregion(system_mem, EXYNOS4210_DRAM1_BASE_ADDR, &s->dram1_mem); mem_size = EXYNOS4210_DRAM_MAX_SIZE; } - memory_region_init_ram(&s->dram0_mem, NULL, "exynos4210.dram0", mem_size); + memory_region_init_ram(&s->dram0_mem, NULL, "exynos4210.dram0", mem_size, + &error_abort); vmstate_register_ram_global(&s->dram0_mem); memory_region_add_subregion(system_mem, EXYNOS4210_DRAM0_BASE_ADDR, &s->dram0_mem); diff --git a/hw/arm/exynos4_boards.c b/hw/arm/exynos4_boards.c index 26cedecee3..d644db1ef9 100644 --- a/hw/arm/exynos4_boards.c +++ b/hw/arm/exynos4_boards.c @@ -94,7 +94,7 @@ static void lan9215_init(uint32_t base, qemu_irq irq) } } -static Exynos4210State *exynos4_boards_init_common(QEMUMachineInitArgs *args, +static Exynos4210State *exynos4_boards_init_common(MachineState *machine, Exynos4BoardType board_type) { if (smp_cpus != EXYNOS4210_NCPUS && !qtest_enabled()) { @@ -108,9 +108,9 @@ static Exynos4210State *exynos4_boards_init_common(QEMUMachineInitArgs *args, exynos4_board_binfo.board_id = exynos4_board_id[board_type]; exynos4_board_binfo.smp_bootreg_addr = exynos4_board_smp_bootreg_addr[board_type]; - exynos4_board_binfo.kernel_filename = args->kernel_filename; - exynos4_board_binfo.initrd_filename = args->initrd_filename; - exynos4_board_binfo.kernel_cmdline = args->kernel_cmdline; + exynos4_board_binfo.kernel_filename = machine->kernel_filename; + exynos4_board_binfo.initrd_filename = machine->initrd_filename; + exynos4_board_binfo.kernel_cmdline = machine->kernel_cmdline; exynos4_board_binfo.gic_cpu_if_addr = EXYNOS4210_SMP_PRIVATE_BASE_ADDR + 0x100; @@ -120,24 +120,24 @@ static Exynos4210State *exynos4_boards_init_common(QEMUMachineInitArgs *args, " initrd_filename: %s\n", exynos4_board_ram_size[board_type] / 1048576, exynos4_board_ram_size[board_type], - args->kernel_filename, - args->kernel_cmdline, - args->initrd_filename); + machine->kernel_filename, + machine->kernel_cmdline, + machine->initrd_filename); return exynos4210_init(get_system_memory(), exynos4_board_ram_size[board_type]); } -static void nuri_init(QEMUMachineInitArgs *args) +static void nuri_init(MachineState *machine) { - exynos4_boards_init_common(args, EXYNOS4_BOARD_NURI); + exynos4_boards_init_common(machine, EXYNOS4_BOARD_NURI); arm_load_kernel(ARM_CPU(first_cpu), &exynos4_board_binfo); } -static void smdkc210_init(QEMUMachineInitArgs *args) +static void smdkc210_init(MachineState *machine) { - Exynos4210State *s = exynos4_boards_init_common(args, + Exynos4210State *s = exynos4_boards_init_common(machine, EXYNOS4_BOARD_SMDKC210); lan9215_init(SMDK_LAN9118_BASE_ADDR, diff --git a/hw/arm/gumstix.c b/hw/arm/gumstix.c index aeea17295b..8103278b15 100644 --- a/hw/arm/gumstix.c +++ b/hw/arm/gumstix.c @@ -40,13 +40,13 @@ #include "hw/block/flash.h" #include "hw/devices.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "sysemu/qtest.h" static const int sector_len = 128 * 1024; -static void connex_init(QEMUMachineInitArgs *args) +static void connex_init(MachineState *machine) { PXA2xxState *cpu; DriveInfo *dinfo; @@ -71,7 +71,7 @@ static void connex_init(QEMUMachineInitArgs *args) be = 0; #endif if (!pflash_cfi01_register(0x00000000, NULL, "connext.rom", connex_rom, - dinfo ? dinfo->bdrv : NULL, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, sector_len, connex_rom / sector_len, 2, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); @@ -83,9 +83,9 @@ static void connex_init(QEMUMachineInitArgs *args) qdev_get_gpio_in(cpu->gpio, 36)); } -static void verdex_init(QEMUMachineInitArgs *args) +static void verdex_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; PXA2xxState *cpu; DriveInfo *dinfo; int be; @@ -109,7 +109,7 @@ static void verdex_init(QEMUMachineInitArgs *args) be = 0; #endif if (!pflash_cfi01_register(0x00000000, NULL, "verdex.rom", verdex_rom, - dinfo ? dinfo->bdrv : NULL, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, sector_len, verdex_rom / sector_len, 2, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); diff --git a/hw/arm/highbank.c b/hw/arm/highbank.c index 46b9f1e0c0..30f744a1bd 100644 --- a/hw/arm/highbank.c +++ b/hw/arm/highbank.c @@ -24,7 +24,7 @@ #include "net/net.h" #include "sysemu/sysemu.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "qemu/error-report.h" @@ -134,7 +134,6 @@ static VMStateDescription vmstate_highbank_regs = { .name = "highbank-regs", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, HighbankRegsState, NUM_REGS), VMSTATE_END_OF_LIST(), @@ -200,13 +199,13 @@ enum cxmachines { * 32-bit host, set the reg value of memory to 0xf7ff00000 in the * device tree and pass -m 2047 to QEMU. */ -static void calxeda_init(QEMUMachineInitArgs *args, enum cxmachines machine) +static void calxeda_init(MachineState *machine, enum cxmachines machine_id) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; DeviceState *dev = NULL; SysBusDevice *busdev; qemu_irq pic[128]; @@ -218,7 +217,7 @@ static void calxeda_init(QEMUMachineInitArgs *args, enum cxmachines machine) char *sysboot_filename; if (!cpu_model) { - switch (machine) { + switch (machine_id) { case CALXEDA_HIGHBANK: cpu_model = "cortex-a9"; break; @@ -256,12 +255,13 @@ static void calxeda_init(QEMUMachineInitArgs *args, enum cxmachines machine) sysmem = get_system_memory(); dram = g_new(MemoryRegion, 1); - memory_region_init_ram(dram, NULL, "highbank.dram", ram_size); + memory_region_init_ram(dram, NULL, "highbank.dram", ram_size, &error_abort); /* SDRAM at address zero. */ memory_region_add_subregion(sysmem, 0, dram); sysram = g_new(MemoryRegion, 1); - memory_region_init_ram(sysram, NULL, "highbank.sysram", 0x8000); + memory_region_init_ram(sysram, NULL, "highbank.sysram", 0x8000, + &error_abort); memory_region_add_subregion(sysmem, 0xfff88000, sysram); if (bios_name != NULL) { sysboot_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); @@ -275,7 +275,7 @@ static void calxeda_init(QEMUMachineInitArgs *args, enum cxmachines machine) } } - switch (machine) { + switch (machine_id) { case CALXEDA_HIGHBANK: dev = qdev_create(NULL, "l2x0"); qdev_init_nofail(dev); @@ -360,14 +360,14 @@ static void calxeda_init(QEMUMachineInitArgs *args, enum cxmachines machine) arm_load_kernel(ARM_CPU(first_cpu), &highbank_binfo); } -static void highbank_init(QEMUMachineInitArgs *args) +static void highbank_init(MachineState *machine) { - calxeda_init(args, CALXEDA_HIGHBANK); + calxeda_init(machine, CALXEDA_HIGHBANK); } -static void midway_init(QEMUMachineInitArgs *args) +static void midway_init(MachineState *machine) { - calxeda_init(args, CALXEDA_MIDWAY); + calxeda_init(machine, CALXEDA_MIDWAY); } static QEMUMachine highbank_machine = { diff --git a/hw/arm/integratorcp.c b/hw/arm/integratorcp.c index 912af96ee6..266ec18fb3 100644 --- a/hw/arm/integratorcp.c +++ b/hw/arm/integratorcp.c @@ -264,7 +264,8 @@ static int integratorcm_init(SysBusDevice *dev) s->cm_init = 0x00000112; s->cm_refcnt_offset = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL), 24, 1000); - memory_region_init_ram(&s->flash, OBJECT(s), "integrator.flash", 0x100000); + memory_region_init_ram(&s->flash, OBJECT(s), "integrator.flash", 0x100000, + &error_abort); vmstate_register_ram_global(&s->flash); memory_region_init_io(&s->iomem, OBJECT(s), &integratorcm_ops, s, @@ -461,13 +462,13 @@ static struct arm_boot_info integrator_binfo = { .board_id = 0x113, }; -static void integratorcp_init(QEMUMachineInitArgs *args) +static void integratorcp_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; ARMCPU *cpu; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -485,7 +486,7 @@ static void integratorcp_init(QEMUMachineInitArgs *args) exit(1); } - memory_region_init_ram(ram, NULL, "integrator.ram", ram_size); + memory_region_init_ram(ram, NULL, "integrator.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); /* ??? On a real system the first 1Mb is mapped as SSRAM or boot flash. */ /* ??? RAM should repeat to fill physical memory space. */ diff --git a/hw/arm/kzm.c b/hw/arm/kzm.c index 99d33cb9d0..94ceab6c8e 100644 --- a/hw/arm/kzm.c +++ b/hw/arm/kzm.c @@ -70,13 +70,13 @@ static struct arm_boot_info kzm_binfo = { .board_id = 1722, }; -static void kzm_init(QEMUMachineInitArgs *args) +static void kzm_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; ARMCPU *cpu; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -97,14 +97,14 @@ static void kzm_init(QEMUMachineInitArgs *args) /* On a real system, the first 16k is a `secure boot rom' */ - memory_region_init_ram(ram, NULL, "kzm.ram", ram_size); + memory_region_init_ram(ram, NULL, "kzm.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, KZM_RAMADDRESS, ram); memory_region_init_alias(ram_alias, NULL, "ram.alias", ram, 0, ram_size); memory_region_add_subregion(address_space_mem, 0x88000000, ram_alias); - memory_region_init_ram(sram, NULL, "kzm.sram", 0x4000); + memory_region_init_ram(sram, NULL, "kzm.sram", 0x4000, &error_abort); memory_region_add_subregion(address_space_mem, 0x1FFFC000, sram); dev = sysbus_create_varargs("imx_avic", 0x68000000, diff --git a/hw/arm/mainstone.c b/hw/arm/mainstone.c index d8e075e26d..0da02a67ec 100644 --- a/hw/arm/mainstone.c +++ b/hw/arm/mainstone.c @@ -18,7 +18,7 @@ #include "hw/devices.h" #include "hw/boards.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/sysbus.h" #include "exec/address-spaces.h" #include "sysemu/qtest.h" @@ -105,7 +105,7 @@ static struct arm_boot_info mainstone_binfo = { }; static void mainstone_common_init(MemoryRegion *address_space_mem, - QEMUMachineInitArgs *args, + MachineState *machine, enum mainstone_model_e model, int arm_id) { uint32_t sector_len = 256 * 1024; @@ -116,14 +116,15 @@ static void mainstone_common_init(MemoryRegion *address_space_mem, int i; int be; MemoryRegion *rom = g_new(MemoryRegion, 1); - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; if (!cpu_model) cpu_model = "pxa270-c5"; /* Setup CPU & memory */ mpu = pxa270_init(address_space_mem, mainstone_binfo.ram_size, cpu_model); - memory_region_init_ram(rom, NULL, "mainstone.rom", MAINSTONE_ROM); + memory_region_init_ram(rom, NULL, "mainstone.rom", MAINSTONE_ROM, + &error_abort); vmstate_register_ram_global(rom); memory_region_set_readonly(rom, true); memory_region_add_subregion(address_space_mem, 0, rom); @@ -148,9 +149,9 @@ static void mainstone_common_init(MemoryRegion *address_space_mem, if (!pflash_cfi01_register(mainstone_flash_base[i], NULL, i ? "mainstone.flash1" : "mainstone.flash0", MAINSTONE_FLASH, - dinfo->bdrv, sector_len, - MAINSTONE_FLASH / sector_len, 4, 0, 0, 0, 0, - be)) { + blk_by_legacy_dinfo(dinfo), + sector_len, MAINSTONE_FLASH / sector_len, + 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); exit(1); } @@ -175,16 +176,16 @@ static void mainstone_common_init(MemoryRegion *address_space_mem, smc91c111_init(&nd_table[0], MST_ETH_PHYS, qdev_get_gpio_in(mst_irq, ETHERNET_IRQ)); - mainstone_binfo.kernel_filename = args->kernel_filename; - mainstone_binfo.kernel_cmdline = args->kernel_cmdline; - mainstone_binfo.initrd_filename = args->initrd_filename; + mainstone_binfo.kernel_filename = machine->kernel_filename; + mainstone_binfo.kernel_cmdline = machine->kernel_cmdline; + mainstone_binfo.initrd_filename = machine->initrd_filename; mainstone_binfo.board_id = arm_id; arm_load_kernel(mpu->cpu, &mainstone_binfo); } -static void mainstone_init(QEMUMachineInitArgs *args) +static void mainstone_init(MachineState *machine) { - mainstone_common_init(get_system_memory(), args, mainstone, 0x196); + mainstone_common_init(get_system_memory(), machine, mainstone, 0x196); } static QEMUMachine mainstone2_machine = { diff --git a/hw/arm/musicpal.c b/hw/arm/musicpal.c index de542010aa..3712de6cba 100644 --- a/hw/arm/musicpal.c +++ b/hw/arm/musicpal.c @@ -18,11 +18,10 @@ #include "hw/char/serial.h" #include "qemu/timer.h" #include "hw/ptimer.h" -#include "block/block.h" #include "hw/block/flash.h" #include "ui/console.h" #include "hw/i2c/i2c.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "ui/pixel_ops.h" @@ -405,7 +404,6 @@ static const VMStateDescription mv88w8618_eth_vmsd = { .name = "mv88w8618_eth", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(smir, mv88w8618_eth_state), VMSTATE_UINT32(icr, mv88w8618_eth_state), @@ -642,7 +640,6 @@ static const VMStateDescription musicpal_lcd_vmsd = { .name = "musicpal_lcd", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(brightness, musicpal_lcd_state), VMSTATE_UINT32(mode, musicpal_lcd_state), @@ -769,7 +766,6 @@ static const VMStateDescription mv88w8618_pic_vmsd = { .name = "mv88w8618_pic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(level, mv88w8618_pic_state), VMSTATE_UINT32(enabled, mv88w8618_pic_state), @@ -940,7 +936,6 @@ static const VMStateDescription mv88w8618_timer_vmsd = { .name = "timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_PTIMER(ptimer, mv88w8618_timer_state), VMSTATE_UINT32(limit, mv88w8618_timer_state), @@ -952,7 +947,6 @@ static const VMStateDescription mv88w8618_pit_vmsd = { .name = "mv88w8618_pit", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(timer, mv88w8618_pit_state, 4, 1, mv88w8618_timer_vmsd, mv88w8618_timer_state), @@ -1041,7 +1035,6 @@ static const VMStateDescription mv88w8618_flashcfg_vmsd = { .name = "mv88w8618_flashcfg", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(cfgr0, mv88w8618_flashcfg_state), VMSTATE_END_OF_LIST() @@ -1381,7 +1374,6 @@ static const VMStateDescription musicpal_gpio_vmsd = { .name = "musicpal_gpio", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(lcd_brightness, musicpal_gpio_state), VMSTATE_UINT32(out_state, musicpal_gpio_state), @@ -1548,7 +1540,6 @@ static const VMStateDescription musicpal_key_vmsd = { .name = "musicpal_key", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(kbd_extended, musicpal_key_state), VMSTATE_UINT32(pressed_keys, musicpal_key_state), @@ -1577,12 +1568,12 @@ static struct arm_boot_info musicpal_binfo = { .board_id = 0x20e, }; -static void musicpal_init(QEMUMachineInitArgs *args) +static void musicpal_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; ARMCPU *cpu; qemu_irq pic[32]; DeviceState *dev; @@ -1609,11 +1600,13 @@ static void musicpal_init(QEMUMachineInitArgs *args) } /* For now we use a fixed - the original - RAM size */ - memory_region_init_ram(ram, NULL, "musicpal.ram", MP_RAM_DEFAULT_SIZE); + memory_region_init_ram(ram, NULL, "musicpal.ram", MP_RAM_DEFAULT_SIZE, + &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0, ram); - memory_region_init_ram(sram, NULL, "musicpal.sram", MP_SRAM_SIZE); + memory_region_init_ram(sram, NULL, "musicpal.sram", MP_SRAM_SIZE, + &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(address_space_mem, MP_SRAM_BASE, sram); @@ -1638,7 +1631,9 @@ static void musicpal_init(QEMUMachineInitArgs *args) /* Register flash */ dinfo = drive_get(IF_PFLASH, 0, 0); if (dinfo) { - flash_size = bdrv_getlength(dinfo->bdrv); + BlockBackend *blk = blk_by_legacy_dinfo(dinfo); + + flash_size = blk_getlength(blk); if (flash_size != 8*1024*1024 && flash_size != 16*1024*1024 && flash_size != 32*1024*1024) { fprintf(stderr, "Invalid flash image size\n"); @@ -1653,16 +1648,14 @@ static void musicpal_init(QEMUMachineInitArgs *args) #ifdef TARGET_WORDS_BIGENDIAN pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL, "musicpal.flash", flash_size, - dinfo->bdrv, 0x10000, - (flash_size + 0xffff) >> 16, + blk, 0x10000, (flash_size + 0xffff) >> 16, MP_FLASH_SIZE_MAX / flash_size, 2, 0x00BF, 0x236D, 0x0000, 0x0000, 0x5555, 0x2AAA, 1); #else pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL, "musicpal.flash", flash_size, - dinfo->bdrv, 0x10000, - (flash_size + 0xffff) >> 16, + blk, 0x10000, (flash_size + 0xffff) >> 16, MP_FLASH_SIZE_MAX / flash_size, 2, 0x00BF, 0x236D, 0x0000, 0x0000, 0x5555, 0x2AAA, 0); diff --git a/hw/arm/nseries.c b/hw/arm/nseries.c index c28f895c7a..c7ebaa6abc 100644 --- a/hw/arm/nseries.c +++ b/hw/arm/nseries.c @@ -31,7 +31,7 @@ #include "hw/hw.h" #include "hw/bt.h" #include "hw/loader.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/sysbus.h" #include "exec/address-spaces.h" @@ -172,8 +172,9 @@ static void n8x0_nand_setup(struct n800_s *s) qdev_prop_set_uint16(s->nand, "version_id", 0); qdev_prop_set_int32(s->nand, "shift", 1); dinfo = drive_get(IF_MTD, 0, 0); - if (dinfo && dinfo->bdrv) { - qdev_prop_set_drive_nofail(s->nand, "drive", dinfo->bdrv); + if (dinfo) { + qdev_prop_set_drive_nofail(s->nand, "drive", + blk_by_legacy_dinfo(dinfo)); } qdev_init_nofail(s->nand); sysbus_connect_irq(SYS_BUS_DEVICE(s->nand), 0, @@ -239,8 +240,9 @@ static void n800_key_event(void *opaque, int keycode) int code = s->keymap[keycode & 0x7f]; if (code == -1) { - if ((keycode & 0x7f) == RETU_KEYCODE) + if ((keycode & 0x7f) == RETU_KEYCODE) { retu_key_event(s->retu, !(keycode & 0x80)); + } return; } @@ -280,11 +282,14 @@ static void n800_tsc_kbd_setup(struct n800_s *s) s->ts.opaque = s->ts.chip->opaque; s->ts.txrx = tsc210x_txrx; - for (i = 0; i < 0x80; i ++) + for (i = 0; i < 0x80; i++) { s->keymap[i] = -1; - for (i = 0; i < 0x10; i ++) - if (n800_keys[i] >= 0) + } + for (i = 0; i < 0x10; i++) { + if (n800_keys[i] >= 0) { s->keymap[n800_keys[i]] = i; + } + } qemu_add_kbd_event_handler(n800_key_event, s); @@ -308,8 +313,9 @@ static void n810_key_event(void *opaque, int keycode) int code = s->keymap[keycode & 0x7f]; if (code == -1) { - if ((keycode & 0x7f) == RETU_KEYCODE) + if ((keycode & 0x7f) == RETU_KEYCODE) { retu_key_event(s->retu, !(keycode & 0x80)); + } return; } @@ -388,11 +394,14 @@ static void n810_kbd_setup(struct n800_s *s) qemu_irq kbd_irq = qdev_get_gpio_in(s->mpu->gpio, N810_KEYBOARD_GPIO); int i; - for (i = 0; i < 0x80; i ++) + for (i = 0; i < 0x80; i++) { s->keymap[i] = -1; - for (i = 0; i < 0x80; i ++) - if (n810_keys[i] > 0) + } + for (i = 0; i < 0x80; i++) { + if (n810_keys[i] > 0) { s->keymap[n810_keys[i]] = i; + } + } qemu_add_kbd_event_handler(n810_key_event, s); @@ -449,17 +458,20 @@ static uint32_t mipid_txrx(void *opaque, uint32_t cmd, int len) struct mipid_s *s = (struct mipid_s *) opaque; uint8_t ret; - if (len > 9) + if (len > 9) { hw_error("%s: FIXME: bad SPI word width %i\n", __FUNCTION__, len); + } - if (s->p >= ARRAY_SIZE(s->resp)) + if (s->p >= ARRAY_SIZE(s->resp)) { ret = 0; - else - ret = s->resp[s->p ++]; - if (s->pm --> 0) + } else { + ret = s->resp[s->p++]; + } + if (s->pm-- > 0) { s->param[s->pm] = cmd; - else + } else { s->cmd = cmd; + } switch (s->cmd) { case 0x00: /* NOP */ @@ -560,15 +572,17 @@ static uint32_t mipid_txrx(void *opaque, uint32_t cmd, int len) goto bad_cmd; case 0x25: /* WRCNTR */ - if (s->pm < 0) + if (s->pm < 0) { s->pm = 1; + } goto bad_cmd; case 0x26: /* GAMSET */ - if (!s->pm) + if (!s->pm) { s->gamma = ffs(s->param[0] & 0xf) - 1; - else if (s->pm < 0) + } else if (s->pm < 0) { s->pm = 1; + } break; case 0x28: /* DISPOFF */ @@ -591,10 +605,11 @@ static uint32_t mipid_txrx(void *opaque, uint32_t cmd, int len) s->te = 0; break; case 0x35: /* TEON */ - if (!s->pm) + if (!s->pm) { s->te = 1; - else if (s->pm < 0) + } else if (s->pm < 0) { s->pm = 1; + } break; case 0x36: /* MADCTR */ @@ -613,8 +628,9 @@ static uint32_t mipid_txrx(void *opaque, uint32_t cmd, int len) case 0xb0: /* CLKINT / DISCTL */ case 0xb1: /* CLKEXT */ - if (s->pm < 0) + if (s->pm < 0) { s->pm = 2; + } break; case 0xb4: /* FRMSEL */ @@ -635,8 +651,9 @@ static uint32_t mipid_txrx(void *opaque, uint32_t cmd, int len) break; case 0xc2: /* IFMOD */ - if (s->pm < 0) + if (s->pm < 0) { s->pm = 2; + } break; case 0xc6: /* PWRCTL */ @@ -834,118 +851,119 @@ static void n800_setup_nolo_tags(void *sram_base) strcpy((void *) (p + 8), "F5"); - stl_raw(p + 10, 0x04f70000); + stl_p(p + 10, 0x04f70000); strcpy((void *) (p + 9), "RX-34"); /* RAM size in MB? */ - stl_raw(p + 12, 0x80); + stl_p(p + 12, 0x80); /* Pointer to the list of tags */ - stl_raw(p + 13, OMAP2_SRAM_BASE + 0x9000); + stl_p(p + 13, OMAP2_SRAM_BASE + 0x9000); /* The NOLO tags start here */ p = sram_base + 0x9000; #define ADD_TAG(tag, len) \ - stw_raw((uint16_t *) p + 0, tag); \ - stw_raw((uint16_t *) p + 1, len); p ++; \ - stl_raw(p ++, OMAP2_SRAM_BASE | (((void *) v - sram_base) & 0xffff)); + stw_p((uint16_t *) p + 0, tag); \ + stw_p((uint16_t *) p + 1, len); p++; \ + stl_p(p++, OMAP2_SRAM_BASE | (((void *) v - sram_base) & 0xffff)); /* OMAP STI console? Pin out settings? */ ADD_TAG(0x6e01, 414); - for (i = 0; i < ARRAY_SIZE(n800_pinout); i ++) - stl_raw(v ++, n800_pinout[i]); + for (i = 0; i < ARRAY_SIZE(n800_pinout); i++) { + stl_p(v++, n800_pinout[i]); + } /* Kernel memsize? */ ADD_TAG(0x6e05, 1); - stl_raw(v ++, 2); + stl_p(v++, 2); /* NOLO serial console */ ADD_TAG(0x6e02, 4); - stl_raw(v ++, XLDR_LL_UART); /* UART number (1 - 3) */ + stl_p(v++, XLDR_LL_UART); /* UART number (1 - 3) */ #if 0 /* CBUS settings (Retu/AVilma) */ ADD_TAG(0x6e03, 6); - stw_raw((uint16_t *) v + 0, 65); /* CBUS GPIO0 */ - stw_raw((uint16_t *) v + 1, 66); /* CBUS GPIO1 */ - stw_raw((uint16_t *) v + 2, 64); /* CBUS GPIO2 */ + stw_p((uint16_t *) v + 0, 65); /* CBUS GPIO0 */ + stw_p((uint16_t *) v + 1, 66); /* CBUS GPIO1 */ + stw_p((uint16_t *) v + 2, 64); /* CBUS GPIO2 */ v += 2; #endif /* Nokia ASIC BB5 (Retu/Tahvo) */ ADD_TAG(0x6e0a, 4); - stw_raw((uint16_t *) v + 0, 111); /* "Retu" interrupt GPIO */ - stw_raw((uint16_t *) v + 1, 108); /* "Tahvo" interrupt GPIO */ - v ++; + stw_p((uint16_t *) v + 0, 111); /* "Retu" interrupt GPIO */ + stw_p((uint16_t *) v + 1, 108); /* "Tahvo" interrupt GPIO */ + v++; /* LCD console? */ ADD_TAG(0x6e04, 4); - stw_raw((uint16_t *) v + 0, 30); /* ??? */ - stw_raw((uint16_t *) v + 1, 24); /* ??? */ - v ++; + stw_p((uint16_t *) v + 0, 30); /* ??? */ + stw_p((uint16_t *) v + 1, 24); /* ??? */ + v++; #if 0 /* LCD settings */ ADD_TAG(0x6e06, 2); - stw_raw((uint16_t *) (v ++), 15); /* ??? */ + stw_p((uint16_t *) (v++), 15); /* ??? */ #endif /* I^2C (Menelaus) */ ADD_TAG(0x6e07, 4); - stl_raw(v ++, 0x00720000); /* ??? */ + stl_p(v++, 0x00720000); /* ??? */ /* Unknown */ ADD_TAG(0x6e0b, 6); - stw_raw((uint16_t *) v + 0, 94); /* ??? */ - stw_raw((uint16_t *) v + 1, 23); /* ??? */ - stw_raw((uint16_t *) v + 2, 0); /* ??? */ + stw_p((uint16_t *) v + 0, 94); /* ??? */ + stw_p((uint16_t *) v + 1, 23); /* ??? */ + stw_p((uint16_t *) v + 2, 0); /* ??? */ v += 2; /* OMAP gpio switch info */ ADD_TAG(0x6e0c, 80); strcpy((void *) v, "bat_cover"); v += 3; - stw_raw((uint16_t *) v + 0, 110); /* GPIO num ??? */ - stw_raw((uint16_t *) v + 1, 1); /* GPIO num ??? */ + stw_p((uint16_t *) v + 0, 110); /* GPIO num ??? */ + stw_p((uint16_t *) v + 1, 1); /* GPIO num ??? */ v += 2; strcpy((void *) v, "cam_act"); v += 3; - stw_raw((uint16_t *) v + 0, 95); /* GPIO num ??? */ - stw_raw((uint16_t *) v + 1, 32); /* GPIO num ??? */ + stw_p((uint16_t *) v + 0, 95); /* GPIO num ??? */ + stw_p((uint16_t *) v + 1, 32); /* GPIO num ??? */ v += 2; strcpy((void *) v, "cam_turn"); v += 3; - stw_raw((uint16_t *) v + 0, 12); /* GPIO num ??? */ - stw_raw((uint16_t *) v + 1, 33); /* GPIO num ??? */ + stw_p((uint16_t *) v + 0, 12); /* GPIO num ??? */ + stw_p((uint16_t *) v + 1, 33); /* GPIO num ??? */ v += 2; strcpy((void *) v, "headphone"); v += 3; - stw_raw((uint16_t *) v + 0, 107); /* GPIO num ??? */ - stw_raw((uint16_t *) v + 1, 17); /* GPIO num ??? */ + stw_p((uint16_t *) v + 0, 107); /* GPIO num ??? */ + stw_p((uint16_t *) v + 1, 17); /* GPIO num ??? */ v += 2; /* Bluetooth */ ADD_TAG(0x6e0e, 12); - stl_raw(v ++, 0x5c623d01); /* ??? */ - stl_raw(v ++, 0x00000201); /* ??? */ - stl_raw(v ++, 0x00000000); /* ??? */ + stl_p(v++, 0x5c623d01); /* ??? */ + stl_p(v++, 0x00000201); /* ??? */ + stl_p(v++, 0x00000000); /* ??? */ /* CX3110x WLAN settings */ ADD_TAG(0x6e0f, 8); - stl_raw(v ++, 0x00610025); /* ??? */ - stl_raw(v ++, 0xffff0057); /* ??? */ + stl_p(v++, 0x00610025); /* ??? */ + stl_p(v++, 0xffff0057); /* ??? */ /* MMC host settings */ ADD_TAG(0x6e10, 12); - stl_raw(v ++, 0xffff000f); /* ??? */ - stl_raw(v ++, 0xffffffff); /* ??? */ - stl_raw(v ++, 0x00000060); /* ??? */ + stl_p(v++, 0xffff000f); /* ??? */ + stl_p(v++, 0xffffffff); /* ??? */ + stl_p(v++, 0x00000060); /* ??? */ /* OneNAND chip select */ ADD_TAG(0x6e11, 10); - stl_raw(v ++, 0x00000401); /* ??? */ - stl_raw(v ++, 0x0002003a); /* ??? */ - stl_raw(v ++, 0x00000002); /* ??? */ + stl_p(v++, 0x00000401); /* ??? */ + stl_p(v++, 0x0002003a); /* ??? */ + stl_p(v++, 0x00000002); /* ??? */ /* TEA5761 sensor settings */ ADD_TAG(0x6e12, 2); - stl_raw(v ++, 93); /* GPIO num ??? */ + stl_p(v++, 93); /* GPIO num ??? */ #if 0 /* Unknown tag */ @@ -956,8 +974,8 @@ static void n800_setup_nolo_tags(void *sram_base) #endif /* End of the list */ - stl_raw(p ++, 0x00000000); - stl_raw(p ++, 0x00000000); + stl_p(p++, 0x00000000); + stl_p(p++, 0x00000000); } /* This task is normally performed by the bootloader. If we're loading @@ -1032,8 +1050,9 @@ static void n8x0_boot_init(void *opaque) s->mpu->cpu->env.GE = 0x5; /* If the machine has a slided keyboard, open it */ - if (s->kbd) + if (s->kbd) { qemu_irq_raise(qdev_get_gpio_in(s->mpu->gpio, N810_SLIDE_GPIO)); + } } #define OMAP_TAG_NOKIA_BT 0x4e01 @@ -1119,112 +1138,112 @@ static int n8x0_atag_setup(void *p, int model) w = p; - stw_raw(w ++, OMAP_TAG_UART); /* u16 tag */ - stw_raw(w ++, 4); /* u16 len */ - stw_raw(w ++, (1 << 2) | (1 << 1) | (1 << 0)); /* uint enabled_uarts */ - w ++; + stw_p(w++, OMAP_TAG_UART); /* u16 tag */ + stw_p(w++, 4); /* u16 len */ + stw_p(w++, (1 << 2) | (1 << 1) | (1 << 0)); /* uint enabled_uarts */ + w++; #if 0 - stw_raw(w ++, OMAP_TAG_SERIAL_CONSOLE); /* u16 tag */ - stw_raw(w ++, 4); /* u16 len */ - stw_raw(w ++, XLDR_LL_UART + 1); /* u8 console_uart */ - stw_raw(w ++, 115200); /* u32 console_speed */ + stw_p(w++, OMAP_TAG_SERIAL_CONSOLE); /* u16 tag */ + stw_p(w++, 4); /* u16 len */ + stw_p(w++, XLDR_LL_UART + 1); /* u8 console_uart */ + stw_p(w++, 115200); /* u32 console_speed */ #endif - stw_raw(w ++, OMAP_TAG_LCD); /* u16 tag */ - stw_raw(w ++, 36); /* u16 len */ + stw_p(w++, OMAP_TAG_LCD); /* u16 tag */ + stw_p(w++, 36); /* u16 len */ strcpy((void *) w, "QEMU LCD panel"); /* char panel_name[16] */ w += 8; strcpy((void *) w, "blizzard"); /* char ctrl_name[16] */ w += 8; - stw_raw(w ++, N810_BLIZZARD_RESET_GPIO); /* TODO: n800 s16 nreset_gpio */ - stw_raw(w ++, 24); /* u8 data_lines */ + stw_p(w++, N810_BLIZZARD_RESET_GPIO); /* TODO: n800 s16 nreset_gpio */ + stw_p(w++, 24); /* u8 data_lines */ - stw_raw(w ++, OMAP_TAG_CBUS); /* u16 tag */ - stw_raw(w ++, 8); /* u16 len */ - stw_raw(w ++, N8X0_CBUS_CLK_GPIO); /* s16 clk_gpio */ - stw_raw(w ++, N8X0_CBUS_DAT_GPIO); /* s16 dat_gpio */ - stw_raw(w ++, N8X0_CBUS_SEL_GPIO); /* s16 sel_gpio */ - w ++; + stw_p(w++, OMAP_TAG_CBUS); /* u16 tag */ + stw_p(w++, 8); /* u16 len */ + stw_p(w++, N8X0_CBUS_CLK_GPIO); /* s16 clk_gpio */ + stw_p(w++, N8X0_CBUS_DAT_GPIO); /* s16 dat_gpio */ + stw_p(w++, N8X0_CBUS_SEL_GPIO); /* s16 sel_gpio */ + w++; - stw_raw(w ++, OMAP_TAG_EM_ASIC_BB5); /* u16 tag */ - stw_raw(w ++, 4); /* u16 len */ - stw_raw(w ++, N8X0_RETU_GPIO); /* s16 retu_irq_gpio */ - stw_raw(w ++, N8X0_TAHVO_GPIO); /* s16 tahvo_irq_gpio */ + stw_p(w++, OMAP_TAG_EM_ASIC_BB5); /* u16 tag */ + stw_p(w++, 4); /* u16 len */ + stw_p(w++, N8X0_RETU_GPIO); /* s16 retu_irq_gpio */ + stw_p(w++, N8X0_TAHVO_GPIO); /* s16 tahvo_irq_gpio */ gpiosw = (model == 810) ? n810_gpiosw_info : n800_gpiosw_info; - for (; gpiosw->name; gpiosw ++) { - stw_raw(w ++, OMAP_TAG_GPIO_SWITCH); /* u16 tag */ - stw_raw(w ++, 20); /* u16 len */ + for (; gpiosw->name; gpiosw++) { + stw_p(w++, OMAP_TAG_GPIO_SWITCH); /* u16 tag */ + stw_p(w++, 20); /* u16 len */ strcpy((void *) w, gpiosw->name); /* char name[12] */ w += 6; - stw_raw(w ++, gpiosw->line); /* u16 gpio */ - stw_raw(w ++, gpiosw->type); - stw_raw(w ++, 0); - stw_raw(w ++, 0); + stw_p(w++, gpiosw->line); /* u16 gpio */ + stw_p(w++, gpiosw->type); + stw_p(w++, 0); + stw_p(w++, 0); } - stw_raw(w ++, OMAP_TAG_NOKIA_BT); /* u16 tag */ - stw_raw(w ++, 12); /* u16 len */ + stw_p(w++, OMAP_TAG_NOKIA_BT); /* u16 tag */ + stw_p(w++, 12); /* u16 len */ b = (void *) w; - stb_raw(b ++, 0x01); /* u8 chip_type (CSR) */ - stb_raw(b ++, N8X0_BT_WKUP_GPIO); /* u8 bt_wakeup_gpio */ - stb_raw(b ++, N8X0_BT_HOST_WKUP_GPIO); /* u8 host_wakeup_gpio */ - stb_raw(b ++, N8X0_BT_RESET_GPIO); /* u8 reset_gpio */ - stb_raw(b ++, BT_UART + 1); /* u8 bt_uart */ + stb_p(b++, 0x01); /* u8 chip_type (CSR) */ + stb_p(b++, N8X0_BT_WKUP_GPIO); /* u8 bt_wakeup_gpio */ + stb_p(b++, N8X0_BT_HOST_WKUP_GPIO); /* u8 host_wakeup_gpio */ + stb_p(b++, N8X0_BT_RESET_GPIO); /* u8 reset_gpio */ + stb_p(b++, BT_UART + 1); /* u8 bt_uart */ memcpy(b, &n8x0_bd_addr, 6); /* u8 bd_addr[6] */ b += 6; - stb_raw(b ++, 0x02); /* u8 bt_sysclk (38.4) */ + stb_p(b++, 0x02); /* u8 bt_sysclk (38.4) */ w = (void *) b; - stw_raw(w ++, OMAP_TAG_WLAN_CX3110X); /* u16 tag */ - stw_raw(w ++, 8); /* u16 len */ - stw_raw(w ++, 0x25); /* u8 chip_type */ - stw_raw(w ++, N8X0_WLAN_PWR_GPIO); /* s16 power_gpio */ - stw_raw(w ++, N8X0_WLAN_IRQ_GPIO); /* s16 irq_gpio */ - stw_raw(w ++, -1); /* s16 spi_cs_gpio */ + stw_p(w++, OMAP_TAG_WLAN_CX3110X); /* u16 tag */ + stw_p(w++, 8); /* u16 len */ + stw_p(w++, 0x25); /* u8 chip_type */ + stw_p(w++, N8X0_WLAN_PWR_GPIO); /* s16 power_gpio */ + stw_p(w++, N8X0_WLAN_IRQ_GPIO); /* s16 irq_gpio */ + stw_p(w++, -1); /* s16 spi_cs_gpio */ - stw_raw(w ++, OMAP_TAG_MMC); /* u16 tag */ - stw_raw(w ++, 16); /* u16 len */ + stw_p(w++, OMAP_TAG_MMC); /* u16 tag */ + stw_p(w++, 16); /* u16 len */ if (model == 810) { - stw_raw(w ++, 0x23f); /* unsigned flags */ - stw_raw(w ++, -1); /* s16 power_pin */ - stw_raw(w ++, -1); /* s16 switch_pin */ - stw_raw(w ++, -1); /* s16 wp_pin */ - stw_raw(w ++, 0x240); /* unsigned flags */ - stw_raw(w ++, 0xc000); /* s16 power_pin */ - stw_raw(w ++, 0x0248); /* s16 switch_pin */ - stw_raw(w ++, 0xc000); /* s16 wp_pin */ + stw_p(w++, 0x23f); /* unsigned flags */ + stw_p(w++, -1); /* s16 power_pin */ + stw_p(w++, -1); /* s16 switch_pin */ + stw_p(w++, -1); /* s16 wp_pin */ + stw_p(w++, 0x240); /* unsigned flags */ + stw_p(w++, 0xc000); /* s16 power_pin */ + stw_p(w++, 0x0248); /* s16 switch_pin */ + stw_p(w++, 0xc000); /* s16 wp_pin */ } else { - stw_raw(w ++, 0xf); /* unsigned flags */ - stw_raw(w ++, -1); /* s16 power_pin */ - stw_raw(w ++, -1); /* s16 switch_pin */ - stw_raw(w ++, -1); /* s16 wp_pin */ - stw_raw(w ++, 0); /* unsigned flags */ - stw_raw(w ++, 0); /* s16 power_pin */ - stw_raw(w ++, 0); /* s16 switch_pin */ - stw_raw(w ++, 0); /* s16 wp_pin */ + stw_p(w++, 0xf); /* unsigned flags */ + stw_p(w++, -1); /* s16 power_pin */ + stw_p(w++, -1); /* s16 switch_pin */ + stw_p(w++, -1); /* s16 wp_pin */ + stw_p(w++, 0); /* unsigned flags */ + stw_p(w++, 0); /* s16 power_pin */ + stw_p(w++, 0); /* s16 switch_pin */ + stw_p(w++, 0); /* s16 wp_pin */ } - stw_raw(w ++, OMAP_TAG_TEA5761); /* u16 tag */ - stw_raw(w ++, 4); /* u16 len */ - stw_raw(w ++, N8X0_TEA5761_CS_GPIO); /* u16 enable_gpio */ - w ++; + stw_p(w++, OMAP_TAG_TEA5761); /* u16 tag */ + stw_p(w++, 4); /* u16 len */ + stw_p(w++, N8X0_TEA5761_CS_GPIO); /* u16 enable_gpio */ + w++; partition = (model == 810) ? n810_part_info : n800_part_info; - for (; partition->name; partition ++) { - stw_raw(w ++, OMAP_TAG_PARTITION); /* u16 tag */ - stw_raw(w ++, 28); /* u16 len */ + for (; partition->name; partition++) { + stw_p(w++, OMAP_TAG_PARTITION); /* u16 tag */ + stw_p(w++, 28); /* u16 len */ strcpy((void *) w, partition->name); /* char name[16] */ l = (void *) (w + 8); - stl_raw(l ++, partition->size); /* unsigned int size */ - stl_raw(l ++, partition->offset); /* unsigned int offset */ - stl_raw(l ++, partition->mask); /* unsigned int mask_flags */ + stl_p(l++, partition->size); /* unsigned int size */ + stl_p(l++, partition->offset); /* unsigned int offset */ + stl_p(l++, partition->mask); /* unsigned int mask_flags */ w = (void *) l; } - stw_raw(w ++, OMAP_TAG_BOOT_REASON); /* u16 tag */ - stw_raw(w ++, 12); /* u16 len */ + stw_p(w++, OMAP_TAG_BOOT_REASON); /* u16 tag */ + stw_p(w++, 12); /* u16 len */ #if 0 strcpy((void *) w, "por"); /* char reason_str[12] */ strcpy((void *) w, "charger"); /* char reason_str[12] */ @@ -1242,15 +1261,15 @@ static int n8x0_atag_setup(void *p, int model) w += 6; tag = (model == 810) ? "RX-44" : "RX-34"; - stw_raw(w ++, OMAP_TAG_VERSION_STR); /* u16 tag */ - stw_raw(w ++, 24); /* u16 len */ + stw_p(w++, OMAP_TAG_VERSION_STR); /* u16 tag */ + stw_p(w++, 24); /* u16 len */ strcpy((void *) w, "product"); /* char component[12] */ w += 6; strcpy((void *) w, tag); /* char version[12] */ w += 6; - stw_raw(w ++, OMAP_TAG_VERSION_STR); /* u16 tag */ - stw_raw(w ++, 24); /* u16 len */ + stw_p(w++, OMAP_TAG_VERSION_STR); /* u16 tag */ + stw_p(w++, 24); /* u16 len */ strcpy((void *) w, "hw-build"); /* char component[12] */ w += 6; strcpy((void *) w, "QEMU "); @@ -1258,8 +1277,8 @@ static int n8x0_atag_setup(void *p, int model) w += 6; tag = (model == 810) ? "1.1.10-qemu" : "1.1.6-qemu"; - stw_raw(w ++, OMAP_TAG_VERSION_STR); /* u16 tag */ - stw_raw(w ++, 24); /* u16 len */ + stw_p(w++, OMAP_TAG_VERSION_STR); /* u16 tag */ + stw_p(w++, 24); /* u16 len */ strcpy((void *) w, "nolo"); /* char component[12] */ w += 6; strcpy((void *) w, tag); /* char version[12] */ @@ -1278,14 +1297,14 @@ static int n810_atag_setup(const struct arm_boot_info *info, void *p) return n8x0_atag_setup(p, 810); } -static void n8x0_init(QEMUMachineInitArgs *args, +static void n8x0_init(MachineState *machine, struct arm_boot_info *binfo, int model) { MemoryRegion *sysmem = get_system_memory(); struct n800_s *s = (struct n800_s *) g_malloc0(sizeof(*s)); int sdram_size = binfo->ram_size; - s->mpu = omap2420_mpu_init(sysmem, sdram_size, args->cpu_model); + s->mpu = omap2420_mpu_init(sysmem, sdram_size, machine->cpu_model); /* Setup peripherals * @@ -1315,9 +1334,9 @@ static void n8x0_init(QEMUMachineInitArgs *args, n8x0_gpio_setup(s); n8x0_nand_setup(s); n8x0_i2c_setup(s); - if (model == 800) + if (model == 800) { n800_tsc_kbd_setup(s); - else if (model == 810) { + } else if (model == 810) { n810_tsc_setup(s); n810_kbd_setup(s); } @@ -1329,18 +1348,18 @@ static void n8x0_init(QEMUMachineInitArgs *args, n8x0_usb_setup(s); } - if (args->kernel_filename) { + if (machine->kernel_filename) { /* Or at the linux loader. */ - binfo->kernel_filename = args->kernel_filename; - binfo->kernel_cmdline = args->kernel_cmdline; - binfo->initrd_filename = args->initrd_filename; + binfo->kernel_filename = machine->kernel_filename; + binfo->kernel_cmdline = machine->kernel_cmdline; + binfo->initrd_filename = machine->initrd_filename; arm_load_kernel(s->mpu->cpu, binfo); qemu_register_reset(n8x0_boot_init, s); } if (option_rom[0].name && - (args->boot_order[0] == 'n' || !args->kernel_filename)) { + (machine->boot_order[0] == 'n' || !machine->kernel_filename)) { uint8_t nolo_tags[0x10000]; /* No, wait, better start at the ROM. */ s->mpu->cpu->env.regs[15] = OMAP2_Q2_BASE + 0x400000; @@ -1382,14 +1401,14 @@ static struct arm_boot_info n810_binfo = { .atag_board = n810_atag_setup, }; -static void n800_init(QEMUMachineInitArgs *args) +static void n800_init(MachineState *machine) { - return n8x0_init(args, &n800_binfo, 800); + return n8x0_init(machine, &n800_binfo, 800); } -static void n810_init(QEMUMachineInitArgs *args) +static void n810_init(MachineState *machine) { - return n8x0_init(args, &n810_binfo, 810); + return n8x0_init(machine, &n810_binfo, 810); } static QEMUMachine n800_machine = { diff --git a/hw/arm/omap1.c b/hw/arm/omap1.c index b433748c60..abb183c2d5 100644 --- a/hw/arm/omap1.c +++ b/hw/arm/omap1.c @@ -21,6 +21,7 @@ #include "hw/arm/omap.h" #include "sysemu/sysemu.h" #include "hw/arm/soc_dma.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "qemu/range.h" #include "hw/sysbus.h" @@ -172,7 +173,7 @@ static void omap_timer_clk_update(void *opaque, int line, int on) static void omap_timer_clk_setup(struct omap_mpu_timer_s *timer) { omap_clk_adduser(timer->clk, - qemu_allocate_irqs(omap_timer_clk_update, timer, 1)[0]); + qemu_allocate_irq(omap_timer_clk_update, timer, 0)); timer->rate = omap_clk_getrate(timer->clk); } @@ -2098,7 +2099,7 @@ static struct omap_mpuio_s *omap_mpuio_init(MemoryRegion *memory, "omap-mpuio", 0x800); memory_region_add_subregion(memory, base, &s->iomem); - omap_clk_adduser(clk, qemu_allocate_irqs(omap_mpuio_onoff, s, 1)[0]); + omap_clk_adduser(clk, qemu_allocate_irq(omap_mpuio_onoff, s, 0)); return s; } @@ -2401,7 +2402,7 @@ static struct omap_pwl_s *omap_pwl_init(MemoryRegion *system_memory, "omap-pwl", 0x800); memory_region_add_subregion(system_memory, base, &s->iomem); - omap_clk_adduser(clk, qemu_allocate_irqs(omap_pwl_clk_update, s, 1)[0]); + omap_clk_adduser(clk, qemu_allocate_irq(omap_pwl_clk_update, s, 0)); return s; } @@ -2709,8 +2710,8 @@ static void omap_rtc_write(void *opaque, hwaddr addr, s->ti += ti[1]; } else { /* A less accurate version */ - s->ti -= (s->current_tm.tm_year % 100) * 31536000; - s->ti += from_bcd(value) * 31536000; + s->ti -= (time_t)(s->current_tm.tm_year % 100) * 31536000; + s->ti += (time_t)from_bcd(value) * 31536000; } return; @@ -3485,8 +3486,8 @@ static void omap_mcbsp_i2s_start(void *opaque, int line, int level) void omap_mcbsp_i2s_attach(struct omap_mcbsp_s *s, I2SCodec *slave) { s->codec = slave; - slave->rx_swallow = qemu_allocate_irqs(omap_mcbsp_i2s_swallow, s, 1)[0]; - slave->tx_start = qemu_allocate_irqs(omap_mcbsp_i2s_start, s, 1)[0]; + slave->rx_swallow = qemu_allocate_irq(omap_mcbsp_i2s_swallow, s, 0); + slave->tx_start = qemu_allocate_irq(omap_mcbsp_i2s_start, s, 0); } /* LED Pulse Generators */ @@ -3634,7 +3635,7 @@ static struct omap_lpg_s *omap_lpg_init(MemoryRegion *system_memory, memory_region_init_io(&s->iomem, NULL, &omap_lpg_ops, s, "omap-lpg", 0x800); memory_region_add_subregion(system_memory, base, &s->iomem); - omap_clk_adduser(clk, qemu_allocate_irqs(omap_lpg_clk_update, s, 1)[0]); + omap_clk_adduser(clk, qemu_allocate_irq(omap_lpg_clk_update, s, 0)); return s; } @@ -3848,16 +3849,18 @@ struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory, s->sdram_size = sdram_size; s->sram_size = OMAP15XX_SRAM_SIZE; - s->wakeup = qemu_allocate_irqs(omap_mpu_wakeup, s, 1)[0]; + s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0); /* Clocks */ omap_clk_init(s); /* Memory-mapped stuff */ - memory_region_init_ram(&s->emiff_ram, NULL, "omap1.dram", s->sdram_size); + memory_region_init_ram(&s->emiff_ram, NULL, "omap1.dram", s->sdram_size, + &error_abort); vmstate_register_ram_global(&s->emiff_ram); memory_region_add_subregion(system_memory, OMAP_EMIFF_BASE, &s->emiff_ram); - memory_region_init_ram(&s->imif_ram, NULL, "omap1.sram", s->sram_size); + memory_region_init_ram(&s->imif_ram, NULL, "omap1.sram", s->sram_size, + &error_abort); vmstate_register_ram_global(&s->imif_ram); memory_region_add_subregion(system_memory, OMAP_IMIF_BASE, &s->imif_ram); @@ -3976,7 +3979,8 @@ struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory, fprintf(stderr, "qemu: missing SecureDigital device\n"); exit(1); } - s->mmc = omap_mmc_init(0xfffb7800, system_memory, dinfo->bdrv, + s->mmc = omap_mmc_init(0xfffb7800, system_memory, + blk_by_legacy_dinfo(dinfo), qdev_get_gpio_in(s->ih[1], OMAP_INT_OQN), &s->drq[OMAP_DMA_MMC_TX], omap_findclk(s, "mmc_ck")); diff --git a/hw/arm/omap2.c b/hw/arm/omap2.c index 36efde0d64..b083ebebc8 100644 --- a/hw/arm/omap2.c +++ b/hw/arm/omap2.c @@ -18,6 +18,7 @@ * with this program; if not, see <http://www.gnu.org/licenses/>. */ +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/hw.h" #include "hw/arm/arm.h" @@ -2260,16 +2261,18 @@ struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem, s->sdram_size = sdram_size; s->sram_size = OMAP242X_SRAM_SIZE; - s->wakeup = qemu_allocate_irqs(omap_mpu_wakeup, s, 1)[0]; + s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0); /* Clocks */ omap_clk_init(s); /* Memory-mapped stuff */ - memory_region_init_ram(&s->sdram, NULL, "omap2.dram", s->sdram_size); + memory_region_init_ram(&s->sdram, NULL, "omap2.dram", s->sdram_size, + &error_abort); vmstate_register_ram_global(&s->sdram); memory_region_add_subregion(sysmem, OMAP2_Q2_BASE, &s->sdram); - memory_region_init_ram(&s->sram, NULL, "omap2.sram", s->sram_size); + memory_region_init_ram(&s->sram, NULL, "omap2.sram", s->sram_size, + &error_abort); vmstate_register_ram_global(&s->sram); memory_region_add_subregion(sysmem, OMAP2_SRAM_BASE, &s->sram); @@ -2459,7 +2462,8 @@ struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem, fprintf(stderr, "qemu: missing SecureDigital device\n"); exit(1); } - s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), dinfo->bdrv, + s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), + blk_by_legacy_dinfo(dinfo), qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ), &s->drq[OMAP24XX_DMA_MMC1_TX], omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk")); diff --git a/hw/arm/omap_sx1.c b/hw/arm/omap_sx1.c index 3ba263ab4d..671e02c4ed 100644 --- a/hw/arm/omap_sx1.c +++ b/hw/arm/omap_sx1.c @@ -31,7 +31,7 @@ #include "hw/boards.h" #include "hw/arm/arm.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "sysemu/qtest.h" #include "exec/address-spaces.h" @@ -98,7 +98,7 @@ static struct arm_boot_info sx1_binfo = { .board_id = 0x265, }; -static void sx1_init(QEMUMachineInitArgs *args, const int version) +static void sx1_init(MachineState *machine, const int version) { struct omap_mpu_state_s *mpu; MemoryRegion *address_space = get_system_memory(); @@ -118,10 +118,12 @@ static void sx1_init(QEMUMachineInitArgs *args, const int version) flash_size = flash2_size; } - mpu = omap310_mpu_init(address_space, sx1_binfo.ram_size, args->cpu_model); + mpu = omap310_mpu_init(address_space, sx1_binfo.ram_size, + machine->cpu_model); /* External Flash (EMIFS) */ - memory_region_init_ram(flash, NULL, "omap_sx1.flash0-0", flash_size); + memory_region_init_ram(flash, NULL, "omap_sx1.flash0-0", flash_size, + &error_abort); vmstate_register_ram_global(flash); memory_region_set_readonly(flash, true); memory_region_add_subregion(address_space, OMAP_CS0_BASE, flash); @@ -152,8 +154,8 @@ static void sx1_init(QEMUMachineInitArgs *args, const int version) if ((dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) { if (!pflash_cfi01_register(OMAP_CS0_BASE, NULL, "omap_sx1.flash0-1", flash_size, - dinfo->bdrv, sector_size, - flash_size / sector_size, + blk_by_legacy_dinfo(dinfo), + sector_size, flash_size / sector_size, 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory %d.\n", fl_idx); @@ -163,7 +165,8 @@ static void sx1_init(QEMUMachineInitArgs *args, const int version) if ((version == 1) && (dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) { - memory_region_init_ram(flash_1, NULL, "omap_sx1.flash1-0", flash1_size); + memory_region_init_ram(flash_1, NULL, "omap_sx1.flash1-0", flash1_size, + &error_abort); vmstate_register_ram_global(flash_1); memory_region_set_readonly(flash_1, true); memory_region_add_subregion(address_space, OMAP_CS1_BASE, flash_1); @@ -175,8 +178,8 @@ static void sx1_init(QEMUMachineInitArgs *args, const int version) if (!pflash_cfi01_register(OMAP_CS1_BASE, NULL, "omap_sx1.flash1-1", flash1_size, - dinfo->bdrv, sector_size, - flash1_size / sector_size, + blk_by_legacy_dinfo(dinfo), + sector_size, flash1_size / sector_size, 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory %d.\n", fl_idx); @@ -189,29 +192,29 @@ static void sx1_init(QEMUMachineInitArgs *args, const int version) OMAP_CS1_BASE, &cs[1]); } - if (!args->kernel_filename && !fl_idx && !qtest_enabled()) { + if (!machine->kernel_filename && !fl_idx && !qtest_enabled()) { fprintf(stderr, "Kernel or Flash image must be specified\n"); exit(1); } /* Load the kernel. */ - sx1_binfo.kernel_filename = args->kernel_filename; - sx1_binfo.kernel_cmdline = args->kernel_cmdline; - sx1_binfo.initrd_filename = args->initrd_filename; + sx1_binfo.kernel_filename = machine->kernel_filename; + sx1_binfo.kernel_cmdline = machine->kernel_cmdline; + sx1_binfo.initrd_filename = machine->initrd_filename; arm_load_kernel(mpu->cpu, &sx1_binfo); /* TODO: fix next line */ //~ qemu_console_resize(ds, 640, 480); } -static void sx1_init_v1(QEMUMachineInitArgs *args) +static void sx1_init_v1(MachineState *machine) { - sx1_init(args, 1); + sx1_init(machine, 1); } -static void sx1_init_v2(QEMUMachineInitArgs *args) +static void sx1_init_v2(MachineState *machine) { - sx1_init(args, 2); + sx1_init(machine, 2); } static QEMUMachine sx1_machine_v2 = { diff --git a/hw/arm/palm.c b/hw/arm/palm.c index fac4f69807..7f1cfb8f6a 100644 --- a/hw/arm/palm.c +++ b/hw/arm/palm.c @@ -191,12 +191,12 @@ static struct arm_boot_info palmte_binfo = { .board_id = 0x331, }; -static void palmte_init(QEMUMachineInitArgs *args) +static void palmte_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; MemoryRegion *address_space_mem = get_system_memory(); struct omap_mpu_state_s *mpu; int flash_size = 0x00800000; @@ -212,7 +212,8 @@ static void palmte_init(QEMUMachineInitArgs *args) mpu = omap310_mpu_init(address_space_mem, sdram_size, cpu_model); /* External Flash (EMIFS) */ - memory_region_init_ram(flash, NULL, "palmte.flash", flash_size); + memory_region_init_ram(flash, NULL, "palmte.flash", flash_size, + &error_abort); vmstate_register_ram_global(flash); memory_region_set_readonly(flash, true); memory_region_add_subregion(address_space_mem, OMAP_CS0_BASE, flash); diff --git a/hw/arm/pxa2xx.c b/hw/arm/pxa2xx.c index 04291488e4..693dfec9f2 100644 --- a/hw/arm/pxa2xx.c +++ b/hw/arm/pxa2xx.c @@ -14,6 +14,7 @@ #include "hw/i2c/i2c.h" #include "hw/ssi.h" #include "sysemu/char.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" static struct { @@ -148,8 +149,7 @@ static const VMStateDescription vmstate_pxa2xx_pm = { .name = "pxa2xx_pm", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(pm_regs, PXA2xxState, 0x40), VMSTATE_END_OF_LIST() } @@ -215,8 +215,7 @@ static const VMStateDescription vmstate_pxa2xx_cm = { .name = "pxa2xx_cm", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(cm_regs, PXA2xxState, 4), VMSTATE_UINT32(clkcfg, PXA2xxState), VMSTATE_UINT32(pmnc, PXA2xxState), @@ -440,8 +439,7 @@ static const VMStateDescription vmstate_pxa2xx_mm = { .name = "pxa2xx_mm", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(mm_regs, PXA2xxState, 0x1a), VMSTATE_END_OF_LIST() } @@ -732,7 +730,7 @@ static void pxa2xx_ssp_save(QEMUFile *f, void *opaque) static int pxa2xx_ssp_load(QEMUFile *f, void *opaque, int version_id) { PXA2xxSSPState *s = (PXA2xxSSPState *) opaque; - int i; + int i, v; s->enable = qemu_get_be32(f); @@ -746,7 +744,11 @@ static int pxa2xx_ssp_load(QEMUFile *f, void *opaque, int version_id) qemu_get_8s(f, &s->ssrsa); qemu_get_8s(f, &s->ssacd); - s->rx_level = qemu_get_byte(f); + v = qemu_get_byte(f); + if (v < 0 || v > ARRAY_SIZE(s->rx_fifo)) { + return -EINVAL; + } + s->rx_level = v; s->rx_start = 0; for (i = 0; i < s->rx_level; i ++) s->rx_fifo[i] = qemu_get_byte(f); @@ -1168,7 +1170,6 @@ static const VMStateDescription vmstate_pxa2xx_rtc_regs = { .name = "pxa2xx_rtc", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = pxa2xx_rtc_pre_save, .post_load = pxa2xx_rtc_post_load, .fields = (VMStateField[]) { @@ -1432,8 +1433,7 @@ static const VMStateDescription vmstate_pxa2xx_i2c_slave = { .name = "pxa2xx_i2c_slave", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_I2C_SLAVE(parent_obj, PXA2xxI2CSlaveState), VMSTATE_END_OF_LIST() } @@ -1443,8 +1443,7 @@ static const VMStateDescription vmstate_pxa2xx_i2c = { .name = "pxa2xx_i2c", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(control, PXA2xxI2CState), VMSTATE_UINT16(status, PXA2xxI2CState), VMSTATE_UINT8(ibmr, PXA2xxI2CState), @@ -1701,8 +1700,7 @@ static const VMStateDescription vmstate_pxa2xx_i2s = { .name = "pxa2xx_i2s", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(control, PXA2xxI2SState, 2), VMSTATE_UINT32(status, PXA2xxI2SState), VMSTATE_UINT32(mask, PXA2xxI2SState), @@ -2055,13 +2053,15 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space, fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } - s->reset = qemu_allocate_irqs(pxa2xx_reset, s, 1)[0]; + s->reset = qemu_allocate_irq(pxa2xx_reset, s, 0); /* SDRAM & Internal Memory Storage */ - memory_region_init_ram(&s->sdram, NULL, "pxa270.sdram", sdram_size); + memory_region_init_ram(&s->sdram, NULL, "pxa270.sdram", sdram_size, + &error_abort); vmstate_register_ram_global(&s->sdram); memory_region_add_subregion(address_space, PXA2XX_SDRAM_BASE, &s->sdram); - memory_region_init_ram(&s->internal, NULL, "pxa270.internal", 0x40000); + memory_region_init_ram(&s->internal, NULL, "pxa270.internal", 0x40000, + &error_abort); vmstate_register_ram_global(&s->internal); memory_region_add_subregion(address_space, PXA2XX_INTERNAL_BASE, &s->internal); @@ -2086,7 +2086,8 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space, fprintf(stderr, "qemu: missing SecureDigital device\n"); exit(1); } - s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv, + s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, + blk_by_legacy_dinfo(dinfo), qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC), qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI), qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI)); @@ -2186,14 +2187,15 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size) fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } - s->reset = qemu_allocate_irqs(pxa2xx_reset, s, 1)[0]; + s->reset = qemu_allocate_irq(pxa2xx_reset, s, 0); /* SDRAM & Internal Memory Storage */ - memory_region_init_ram(&s->sdram, NULL, "pxa255.sdram", sdram_size); + memory_region_init_ram(&s->sdram, NULL, "pxa255.sdram", sdram_size, + &error_abort); vmstate_register_ram_global(&s->sdram); memory_region_add_subregion(address_space, PXA2XX_SDRAM_BASE, &s->sdram); memory_region_init_ram(&s->internal, NULL, "pxa255.internal", - PXA2XX_INTERNAL_SIZE); + PXA2XX_INTERNAL_SIZE, &error_abort); vmstate_register_ram_global(&s->internal); memory_region_add_subregion(address_space, PXA2XX_INTERNAL_BASE, &s->internal); @@ -2217,7 +2219,8 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size) fprintf(stderr, "qemu: missing SecureDigital device\n"); exit(1); } - s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, dinfo->bdrv, + s->mmc = pxa2xx_mmci_init(address_space, 0x41100000, + blk_by_legacy_dinfo(dinfo), qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC), qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI), qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI)); diff --git a/hw/arm/pxa2xx_gpio.c b/hw/arm/pxa2xx_gpio.c index 07274285ab..354ccf1ea1 100644 --- a/hw/arm/pxa2xx_gpio.c +++ b/hw/arm/pxa2xx_gpio.c @@ -36,7 +36,6 @@ struct PXA2xxGPIOInfo { uint32_t rising[PXA2XX_GPIO_BANKS]; uint32_t falling[PXA2XX_GPIO_BANKS]; uint32_t status[PXA2XX_GPIO_BANKS]; - uint32_t gpsr[PXA2XX_GPIO_BANKS]; uint32_t gafr[PXA2XX_GPIO_BANKS * 2]; uint32_t prev_level[PXA2XX_GPIO_BANKS]; @@ -162,14 +161,14 @@ static uint64_t pxa2xx_gpio_read(void *opaque, hwaddr offset, return s->dir[bank]; case GPSR: /* GPIO Pin-Output Set registers */ - printf("%s: Read from a write-only register " REG_FMT "\n", - __FUNCTION__, offset); - return s->gpsr[bank]; /* Return last written value. */ + qemu_log_mask(LOG_GUEST_ERROR, + "pxa2xx GPIO: read from write only register GPSR\n"); + return 0; case GPCR: /* GPIO Pin-Output Clear registers */ - printf("%s: Read from a write-only register " REG_FMT "\n", - __FUNCTION__, offset); - return 31337; /* Specified as unpredictable in the docs. */ + qemu_log_mask(LOG_GUEST_ERROR, + "pxa2xx GPIO: read from write only register GPCR\n"); + return 0; case GRER: /* GPIO Rising-Edge Detect Enable registers */ return s->rising[bank]; @@ -217,7 +216,6 @@ static void pxa2xx_gpio_write(void *opaque, hwaddr offset, case GPSR: /* GPIO Pin-Output Set registers */ s->olevel[bank] |= value; pxa2xx_gpio_handler_update(s); - s->gpsr[bank] = value; break; case GPCR: /* GPIO Pin-Output Clear registers */ @@ -313,9 +311,7 @@ static const VMStateDescription vmstate_pxa2xx_gpio_regs = { .name = "pxa2xx-gpio", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { - VMSTATE_INT32(lines, PXA2xxGPIOInfo), + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(ilevel, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), VMSTATE_UINT32_ARRAY(olevel, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), VMSTATE_UINT32_ARRAY(dir, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), @@ -323,6 +319,7 @@ static const VMStateDescription vmstate_pxa2xx_gpio_regs = { VMSTATE_UINT32_ARRAY(falling, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), VMSTATE_UINT32_ARRAY(status, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), VMSTATE_UINT32_ARRAY(gafr, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS * 2), + VMSTATE_UINT32_ARRAY(prev_level, PXA2xxGPIOInfo, PXA2XX_GPIO_BANKS), VMSTATE_END_OF_LIST(), }, }; @@ -341,6 +338,7 @@ static void pxa2xx_gpio_class_init(ObjectClass *klass, void *data) k->init = pxa2xx_gpio_initfn; dc->desc = "PXA2xx GPIO controller"; dc->props = pxa2xx_gpio_properties; + dc->vmsd = &vmstate_pxa2xx_gpio_regs; } static const TypeInfo pxa2xx_gpio_info = { diff --git a/hw/arm/pxa2xx_pic.c b/hw/arm/pxa2xx_pic.c index d37fb543e8..9cfc714874 100644 --- a/hw/arm/pxa2xx_pic.c +++ b/hw/arm/pxa2xx_pic.c @@ -296,7 +296,6 @@ static VMStateDescription vmstate_pxa2xx_pic_regs = { .name = "pxa2xx_pic", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = pxa2xx_pic_post_load, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(int_enabled, PXA2xxPICState, 2), diff --git a/hw/arm/realview.c b/hw/arm/realview.c index 7e04e507f9..af65aa4082 100644 --- a/hw/arm/realview.c +++ b/hw/arm/realview.c @@ -16,7 +16,7 @@ #include "sysemu/sysemu.h" #include "hw/boards.h" #include "hw/i2c/i2c.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "qemu/error-report.h" @@ -45,7 +45,7 @@ static const int realview_board_id[] = { 0x76d }; -static void realview_init(QEMUMachineInitArgs *args, +static void realview_init(MachineState *machine, enum realview_board_type board_type) { ARMCPU *cpu = NULL; @@ -71,7 +71,7 @@ static void realview_init(QEMUMachineInitArgs *args, uint32_t proc_id = 0; uint32_t sys_id; ram_addr_t low_ram_size; - ram_addr_t ram_size = args->ram_size; + ram_addr_t ram_size = machine->ram_size; hwaddr periphbase = 0; switch (board_type) { @@ -91,7 +91,7 @@ static void realview_init(QEMUMachineInitArgs *args, break; } - cpu_oc = cpu_class_by_name(TYPE_ARM_CPU, args->cpu_model); + cpu_oc = cpu_class_by_name(TYPE_ARM_CPU, machine->cpu_model); if (!cpu_oc) { fprintf(stderr, "Unable to find CPU definition\n"); exit(1); @@ -137,12 +137,14 @@ static void realview_init(QEMUMachineInitArgs *args, /* Core tile RAM. */ low_ram_size = ram_size - 0x20000000; ram_size = 0x20000000; - memory_region_init_ram(ram_lo, NULL, "realview.lowmem", low_ram_size); + memory_region_init_ram(ram_lo, NULL, "realview.lowmem", low_ram_size, + &error_abort); vmstate_register_ram_global(ram_lo); memory_region_add_subregion(sysmem, 0x20000000, ram_lo); } - memory_region_init_ram(ram_hi, NULL, "realview.highmem", ram_size); + memory_region_init_ram(ram_hi, NULL, "realview.highmem", ram_size, + &error_abort); vmstate_register_ram_global(ram_hi); low_ram_size = ram_size; if (low_ram_size > 0x10000000) @@ -337,50 +339,51 @@ static void realview_init(QEMUMachineInitArgs *args, startup code. I guess this works on real hardware because the BootROM happens to be in ROM/flash or in memory that isn't clobbered until after Linux boots the secondary CPUs. */ - memory_region_init_ram(ram_hack, NULL, "realview.hack", 0x1000); + memory_region_init_ram(ram_hack, NULL, "realview.hack", 0x1000, + &error_abort); vmstate_register_ram_global(ram_hack); memory_region_add_subregion(sysmem, SMP_BOOT_ADDR, ram_hack); realview_binfo.ram_size = ram_size; - realview_binfo.kernel_filename = args->kernel_filename; - realview_binfo.kernel_cmdline = args->kernel_cmdline; - realview_binfo.initrd_filename = args->initrd_filename; + realview_binfo.kernel_filename = machine->kernel_filename; + realview_binfo.kernel_cmdline = machine->kernel_cmdline; + realview_binfo.initrd_filename = machine->initrd_filename; realview_binfo.nb_cpus = smp_cpus; realview_binfo.board_id = realview_board_id[board_type]; realview_binfo.loader_start = (board_type == BOARD_PB_A8 ? 0x70000000 : 0); arm_load_kernel(ARM_CPU(first_cpu), &realview_binfo); } -static void realview_eb_init(QEMUMachineInitArgs *args) +static void realview_eb_init(MachineState *machine) { - if (!args->cpu_model) { - args->cpu_model = "arm926"; + if (!machine->cpu_model) { + machine->cpu_model = "arm926"; } - realview_init(args, BOARD_EB); + realview_init(machine, BOARD_EB); } -static void realview_eb_mpcore_init(QEMUMachineInitArgs *args) +static void realview_eb_mpcore_init(MachineState *machine) { - if (!args->cpu_model) { - args->cpu_model = "arm11mpcore"; + if (!machine->cpu_model) { + machine->cpu_model = "arm11mpcore"; } - realview_init(args, BOARD_EB_MPCORE); + realview_init(machine, BOARD_EB_MPCORE); } -static void realview_pb_a8_init(QEMUMachineInitArgs *args) +static void realview_pb_a8_init(MachineState *machine) { - if (!args->cpu_model) { - args->cpu_model = "cortex-a8"; + if (!machine->cpu_model) { + machine->cpu_model = "cortex-a8"; } - realview_init(args, BOARD_PB_A8); + realview_init(machine, BOARD_PB_A8); } -static void realview_pbx_a9_init(QEMUMachineInitArgs *args) +static void realview_pbx_a9_init(MachineState *machine) { - if (!args->cpu_model) { - args->cpu_model = "cortex-a9"; + if (!machine->cpu_model) { + machine->cpu_model = "cortex-a9"; } - realview_init(args, BOARD_PBX_A9); + realview_init(machine, BOARD_PBX_A9); } static QEMUMachine realview_eb_machine = { diff --git a/hw/arm/spitz.c b/hw/arm/spitz.c index 392ca84c81..a16831c2e5 100644 --- a/hw/arm/spitz.c +++ b/hw/arm/spitz.c @@ -22,10 +22,9 @@ #include "hw/devices.h" #include "hw/arm/sharpsl.h" #include "ui/console.h" -#include "block/block.h" #include "audio/audio.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/sysbus.h" #include "exec/address-spaces.h" @@ -170,7 +169,8 @@ static int sl_nand_init(SysBusDevice *dev) s->ctl = 0; nand = drive_get(IF_MTD, 0, 0); - s->nand = nand_init(nand ? nand->bdrv : NULL, s->manf_id, s->chip_id); + s->nand = nand_init(nand ? blk_by_legacy_dinfo(nand) : NULL, + s->manf_id, s->chip_id); memory_region_init_io(&s->iomem, OBJECT(s), &sl_ops, s, "sl", 0x40); sysbus_init_mmio(dev, &s->iomem); @@ -285,9 +285,9 @@ static void spitz_keyboard_keydown(SpitzKeyboardState *s, int keycode) spitz_keyboard_sense_update(s); } -#define MOD_SHIFT (1 << 7) -#define MOD_CTRL (1 << 8) -#define MOD_FN (1 << 9) +#define SPITZ_MOD_SHIFT (1 << 7) +#define SPITZ_MOD_CTRL (1 << 8) +#define SPITZ_MOD_FN (1 << 9) #define QUEUE_KEY(c) s->fifo[(s->fifopos + s->fifolen ++) & 0xf] = c @@ -324,21 +324,26 @@ static void spitz_keyboard_handler(void *opaque, int keycode) } code = s->pre_map[mapcode = ((s->modifiers & 3) ? - (keycode | MOD_SHIFT) : - (keycode & ~MOD_SHIFT))]; + (keycode | SPITZ_MOD_SHIFT) : + (keycode & ~SPITZ_MOD_SHIFT))]; if (code != mapcode) { #if 0 - if ((code & MOD_SHIFT) && !(s->modifiers & 1)) + if ((code & SPITZ_MOD_SHIFT) && !(s->modifiers & 1)) { QUEUE_KEY(0x2a | (keycode & 0x80)); - if ((code & MOD_CTRL ) && !(s->modifiers & 4)) + } + if ((code & SPITZ_MOD_CTRL) && !(s->modifiers & 4)) { QUEUE_KEY(0x1d | (keycode & 0x80)); - if ((code & MOD_FN ) && !(s->modifiers & 8)) + } + if ((code & SPITZ_MOD_FN) && !(s->modifiers & 8)) { QUEUE_KEY(0x38 | (keycode & 0x80)); - if ((code & MOD_FN ) && (s->modifiers & 1)) + } + if ((code & SPITZ_MOD_FN) && (s->modifiers & 1)) { QUEUE_KEY(0x2a | (~keycode & 0x80)); - if ((code & MOD_FN ) && (s->modifiers & 2)) + } + if ((code & SPITZ_MOD_FN) && (s->modifiers & 2)) { QUEUE_KEY(0x36 | (~keycode & 0x80)); + } #else if (keycode & 0x80) { if ((s->imodifiers & 1 ) && !(s->modifiers & 1)) @@ -353,24 +358,27 @@ static void spitz_keyboard_handler(void *opaque, int keycode) QUEUE_KEY(0x36); s->imodifiers = 0; } else { - if ((code & MOD_SHIFT) && !((s->modifiers | s->imodifiers) & 1)) { + if ((code & SPITZ_MOD_SHIFT) && + !((s->modifiers | s->imodifiers) & 1)) { QUEUE_KEY(0x2a); s->imodifiers |= 1; } - if ((code & MOD_CTRL ) && !((s->modifiers | s->imodifiers) & 4)) { + if ((code & SPITZ_MOD_CTRL) && + !((s->modifiers | s->imodifiers) & 4)) { QUEUE_KEY(0x1d); s->imodifiers |= 4; } - if ((code & MOD_FN ) && !((s->modifiers | s->imodifiers) & 8)) { + if ((code & SPITZ_MOD_FN) && + !((s->modifiers | s->imodifiers) & 8)) { QUEUE_KEY(0x38); s->imodifiers |= 8; } - if ((code & MOD_FN ) && (s->modifiers & 1) && + if ((code & SPITZ_MOD_FN) && (s->modifiers & 1) && !(s->imodifiers & 0x10)) { QUEUE_KEY(0x2a | 0x80); s->imodifiers |= 0x10; } - if ((code & MOD_FN ) && (s->modifiers & 2) && + if ((code & SPITZ_MOD_FN) && (s->modifiers & 2) && !(s->imodifiers & 0x20)) { QUEUE_KEY(0x36 | 0x80); s->imodifiers |= 0x20; @@ -402,38 +410,38 @@ static void spitz_keyboard_pre_map(SpitzKeyboardState *s) int i; for (i = 0; i < 0x100; i ++) s->pre_map[i] = i; - s->pre_map[0x02 | MOD_SHIFT ] = 0x02 | MOD_SHIFT; /* exclam */ - s->pre_map[0x28 | MOD_SHIFT ] = 0x03 | MOD_SHIFT; /* quotedbl */ - s->pre_map[0x04 | MOD_SHIFT ] = 0x04 | MOD_SHIFT; /* numbersign */ - s->pre_map[0x05 | MOD_SHIFT ] = 0x05 | MOD_SHIFT; /* dollar */ - s->pre_map[0x06 | MOD_SHIFT ] = 0x06 | MOD_SHIFT; /* percent */ - s->pre_map[0x08 | MOD_SHIFT ] = 0x07 | MOD_SHIFT; /* ampersand */ - s->pre_map[0x28 ] = 0x08 | MOD_SHIFT; /* apostrophe */ - s->pre_map[0x0a | MOD_SHIFT ] = 0x09 | MOD_SHIFT; /* parenleft */ - s->pre_map[0x0b | MOD_SHIFT ] = 0x0a | MOD_SHIFT; /* parenright */ - s->pre_map[0x29 | MOD_SHIFT ] = 0x0b | MOD_SHIFT; /* asciitilde */ - s->pre_map[0x03 | MOD_SHIFT ] = 0x0c | MOD_SHIFT; /* at */ - s->pre_map[0xd3 ] = 0x0e | MOD_FN; /* Delete */ - s->pre_map[0x3a ] = 0x0f | MOD_FN; /* Caps_Lock */ - s->pre_map[0x07 | MOD_SHIFT ] = 0x11 | MOD_FN; /* asciicircum */ - s->pre_map[0x0d ] = 0x12 | MOD_FN; /* equal */ - s->pre_map[0x0d | MOD_SHIFT ] = 0x13 | MOD_FN; /* plus */ - s->pre_map[0x1a ] = 0x14 | MOD_FN; /* bracketleft */ - s->pre_map[0x1b ] = 0x15 | MOD_FN; /* bracketright */ - s->pre_map[0x1a | MOD_SHIFT ] = 0x16 | MOD_FN; /* braceleft */ - s->pre_map[0x1b | MOD_SHIFT ] = 0x17 | MOD_FN; /* braceright */ - s->pre_map[0x27 ] = 0x22 | MOD_FN; /* semicolon */ - s->pre_map[0x27 | MOD_SHIFT ] = 0x23 | MOD_FN; /* colon */ - s->pre_map[0x09 | MOD_SHIFT ] = 0x24 | MOD_FN; /* asterisk */ - s->pre_map[0x2b ] = 0x25 | MOD_FN; /* backslash */ - s->pre_map[0x2b | MOD_SHIFT ] = 0x26 | MOD_FN; /* bar */ - s->pre_map[0x0c | MOD_SHIFT ] = 0x30 | MOD_FN; /* underscore */ - s->pre_map[0x33 | MOD_SHIFT ] = 0x33 | MOD_FN; /* less */ - s->pre_map[0x35 ] = 0x33 | MOD_SHIFT; /* slash */ - s->pre_map[0x34 | MOD_SHIFT ] = 0x34 | MOD_FN; /* greater */ - s->pre_map[0x35 | MOD_SHIFT ] = 0x34 | MOD_SHIFT; /* question */ - s->pre_map[0x49 ] = 0x48 | MOD_FN; /* Page_Up */ - s->pre_map[0x51 ] = 0x50 | MOD_FN; /* Page_Down */ + s->pre_map[0x02 | SPITZ_MOD_SHIFT] = 0x02 | SPITZ_MOD_SHIFT; /* exclam */ + s->pre_map[0x28 | SPITZ_MOD_SHIFT] = 0x03 | SPITZ_MOD_SHIFT; /* quotedbl */ + s->pre_map[0x04 | SPITZ_MOD_SHIFT] = 0x04 | SPITZ_MOD_SHIFT; /* # */ + s->pre_map[0x05 | SPITZ_MOD_SHIFT] = 0x05 | SPITZ_MOD_SHIFT; /* dollar */ + s->pre_map[0x06 | SPITZ_MOD_SHIFT] = 0x06 | SPITZ_MOD_SHIFT; /* percent */ + s->pre_map[0x08 | SPITZ_MOD_SHIFT] = 0x07 | SPITZ_MOD_SHIFT; /* ampersand */ + s->pre_map[0x28] = 0x08 | SPITZ_MOD_SHIFT; /* ' */ + s->pre_map[0x0a | SPITZ_MOD_SHIFT] = 0x09 | SPITZ_MOD_SHIFT; /* ( */ + s->pre_map[0x0b | SPITZ_MOD_SHIFT] = 0x0a | SPITZ_MOD_SHIFT; /* ) */ + s->pre_map[0x29 | SPITZ_MOD_SHIFT] = 0x0b | SPITZ_MOD_SHIFT; /* tilde */ + s->pre_map[0x03 | SPITZ_MOD_SHIFT] = 0x0c | SPITZ_MOD_SHIFT; /* at */ + s->pre_map[0xd3] = 0x0e | SPITZ_MOD_FN; /* Delete */ + s->pre_map[0x3a] = 0x0f | SPITZ_MOD_FN; /* Caps_Lock */ + s->pre_map[0x07 | SPITZ_MOD_SHIFT] = 0x11 | SPITZ_MOD_FN; /* ^ */ + s->pre_map[0x0d] = 0x12 | SPITZ_MOD_FN; /* equal */ + s->pre_map[0x0d | SPITZ_MOD_SHIFT] = 0x13 | SPITZ_MOD_FN; /* plus */ + s->pre_map[0x1a] = 0x14 | SPITZ_MOD_FN; /* [ */ + s->pre_map[0x1b] = 0x15 | SPITZ_MOD_FN; /* ] */ + s->pre_map[0x1a | SPITZ_MOD_SHIFT] = 0x16 | SPITZ_MOD_FN; /* { */ + s->pre_map[0x1b | SPITZ_MOD_SHIFT] = 0x17 | SPITZ_MOD_FN; /* } */ + s->pre_map[0x27] = 0x22 | SPITZ_MOD_FN; /* semicolon */ + s->pre_map[0x27 | SPITZ_MOD_SHIFT] = 0x23 | SPITZ_MOD_FN; /* colon */ + s->pre_map[0x09 | SPITZ_MOD_SHIFT] = 0x24 | SPITZ_MOD_FN; /* asterisk */ + s->pre_map[0x2b] = 0x25 | SPITZ_MOD_FN; /* backslash */ + s->pre_map[0x2b | SPITZ_MOD_SHIFT] = 0x26 | SPITZ_MOD_FN; /* bar */ + s->pre_map[0x0c | SPITZ_MOD_SHIFT] = 0x30 | SPITZ_MOD_FN; /* _ */ + s->pre_map[0x33 | SPITZ_MOD_SHIFT] = 0x33 | SPITZ_MOD_FN; /* less */ + s->pre_map[0x35] = 0x33 | SPITZ_MOD_SHIFT; /* slash */ + s->pre_map[0x34 | SPITZ_MOD_SHIFT] = 0x34 | SPITZ_MOD_FN; /* greater */ + s->pre_map[0x35 | SPITZ_MOD_SHIFT] = 0x34 | SPITZ_MOD_SHIFT; /* question */ + s->pre_map[0x49] = 0x48 | SPITZ_MOD_FN; /* Page_Up */ + s->pre_map[0x51] = 0x50 | SPITZ_MOD_FN; /* Page_Down */ s->modifiers = 0; s->imodifiers = 0; @@ -441,9 +449,9 @@ static void spitz_keyboard_pre_map(SpitzKeyboardState *s) s->fifolen = 0; } -#undef MOD_SHIFT -#undef MOD_CTRL -#undef MOD_FN +#undef SPITZ_MOD_SHIFT +#undef SPITZ_MOD_CTRL +#undef SPITZ_MOD_FN static int spitz_keyboard_post_load(void *opaque, int version_id) { @@ -744,7 +752,7 @@ static void spitz_i2c_setup(PXA2xxState *cpu) spitz_wm8750_addr(wm, 0, 0); qdev_connect_gpio_out(cpu->gpio, SPITZ_GPIO_WM, - qemu_allocate_irqs(spitz_wm8750_addr, wm, 1)[0]); + qemu_allocate_irq(spitz_wm8750_addr, wm, 0)); /* .. and to the sound interface. */ cpu->i2s->opaque = wm; cpu->i2s->codec_out = wm8750_dac_dat; @@ -850,7 +858,7 @@ static void spitz_gpio_setup(PXA2xxState *cpu, int slots) * wouldn't guarantee that a guest ever exits the loop. */ spitz_hsync = 0; - lcd_hsync = qemu_allocate_irqs(spitz_lcd_hsync_handler, cpu, 1)[0]; + lcd_hsync = qemu_allocate_irq(spitz_lcd_hsync_handler, cpu, 0); pxa2xx_gpio_read_notifier(cpu->gpio, lcd_hsync); pxa2xx_lcd_vsync_notifier(cpu->lcd, lcd_hsync); @@ -887,14 +895,14 @@ static struct arm_boot_info spitz_binfo = { .ram_size = 0x04000000, }; -static void spitz_common_init(QEMUMachineInitArgs *args, +static void spitz_common_init(MachineState *machine, enum spitz_model_e model, int arm_id) { PXA2xxState *mpu; DeviceState *scp0, *scp1 = NULL; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *rom = g_new(MemoryRegion, 1); - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; if (!cpu_model) cpu_model = (model == terrier) ? "pxa270-c5" : "pxa270-c0"; @@ -904,7 +912,7 @@ static void spitz_common_init(QEMUMachineInitArgs *args, sl_flash_register(mpu, (model == spitz) ? FLASH_128M : FLASH_1024M); - memory_region_init_ram(rom, NULL, "spitz.rom", SPITZ_ROM); + memory_region_init_ram(rom, NULL, "spitz.rom", SPITZ_ROM, &error_abort); vmstate_register_ram_global(rom); memory_region_set_readonly(rom, true); memory_region_add_subregion(address_space_mem, 0, rom); @@ -935,32 +943,32 @@ static void spitz_common_init(QEMUMachineInitArgs *args, /* A 4.0 GB microdrive is permanently sitting in CF slot 0. */ spitz_microdrive_attach(mpu, 0); - spitz_binfo.kernel_filename = args->kernel_filename; - spitz_binfo.kernel_cmdline = args->kernel_cmdline; - spitz_binfo.initrd_filename = args->initrd_filename; + spitz_binfo.kernel_filename = machine->kernel_filename; + spitz_binfo.kernel_cmdline = machine->kernel_cmdline; + spitz_binfo.initrd_filename = machine->initrd_filename; spitz_binfo.board_id = arm_id; arm_load_kernel(mpu->cpu, &spitz_binfo); sl_bootparam_write(SL_PXA_PARAM_BASE); } -static void spitz_init(QEMUMachineInitArgs *args) +static void spitz_init(MachineState *machine) { - spitz_common_init(args, spitz, 0x2c9); + spitz_common_init(machine, spitz, 0x2c9); } -static void borzoi_init(QEMUMachineInitArgs *args) +static void borzoi_init(MachineState *machine) { - spitz_common_init(args, borzoi, 0x33f); + spitz_common_init(machine, borzoi, 0x33f); } -static void akita_init(QEMUMachineInitArgs *args) +static void akita_init(MachineState *machine) { - spitz_common_init(args, akita, 0x2e8); + spitz_common_init(machine, akita, 0x2e8); } -static void terrier_init(QEMUMachineInitArgs *args) +static void terrier_init(MachineState *machine) { - spitz_common_init(args, terrier, 0x33f); + spitz_common_init(machine, terrier, 0x33f); } static QEMUMachine akitapda_machine = { @@ -1006,8 +1014,7 @@ static VMStateDescription vmstate_sl_nand_info = { .name = "sl-nand", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(ctl, SLNANDState), VMSTATE_STRUCT(ecc, SLNANDState, 0, vmstate_ecc_state, ECCState), VMSTATE_END_OF_LIST(), @@ -1041,9 +1048,8 @@ static VMStateDescription vmstate_spitz_kbd = { .name = "spitz-keyboard", .version_id = 1, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = spitz_keyboard_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(sense_state, SpitzKeyboardState), VMSTATE_UINT16(strobe_state, SpitzKeyboardState), VMSTATE_UNUSED_TEST(is_version_0, 5), @@ -1076,8 +1082,7 @@ static const VMStateDescription vmstate_corgi_ssp_regs = { .name = "corgi-ssp", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_SSI_SLAVE(ssidev, CorgiSSPState), VMSTATE_UINT32_ARRAY(enable, CorgiSSPState, 3), VMSTATE_END_OF_LIST(), @@ -1105,8 +1110,7 @@ static const VMStateDescription vmstate_spitz_lcdtg_regs = { .name = "spitz-lcdtg", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_SSI_SLAVE(ssidev, SpitzLCDTG), VMSTATE_UINT32(bl_intensity, SpitzLCDTG), VMSTATE_UINT32(bl_power, SpitzLCDTG), diff --git a/hw/arm/stellaris.c b/hw/arm/stellaris.c index d6cc77b458..64bd4b4c4b 100644 --- a/hw/arm/stellaris.c +++ b/hw/arm/stellaris.c @@ -185,12 +185,19 @@ static uint64_t gptm_read(void *opaque, hwaddr offset, case 0x44: /* TBPMR */ return s->match_prescale[1]; case 0x48: /* TAR */ - if (s->control == 1) + if (s->config == 1) { return s->rtc; + } + qemu_log_mask(LOG_UNIMP, + "GPTM: read of TAR but timer read not supported"); + return 0; case 0x4c: /* TBR */ - hw_error("TODO: Timer value read\n"); + qemu_log_mask(LOG_UNIMP, + "GPTM: read of TBR but timer read not supported"); + return 0; default: - hw_error("gptm_read: Bad offset 0x%x\n", (int)offset); + qemu_log_mask(LOG_GUEST_ERROR, + "GPTM: read at bad offset 0x%x\n", (int)offset); return 0; } } @@ -286,8 +293,7 @@ static const VMStateDescription vmstate_stellaris_gptm = { .name = "stellaris_gptm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(config, gptm_state), VMSTATE_UINT32_ARRAY(mode, gptm_state, 2), VMSTATE_UINT32(control, gptm_state), @@ -643,9 +649,8 @@ static const VMStateDescription vmstate_stellaris_sys = { .name = "stellaris_sys", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = stellaris_sys_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(pborctl, ssys_state), VMSTATE_UINT32(ldopctl, ssys_state), VMSTATE_UINT32(int_mask, ssys_state), @@ -851,8 +856,7 @@ static const VMStateDescription vmstate_stellaris_i2c = { .name = "stellaris_i2c", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(msa, stellaris_i2c_state), VMSTATE_UINT32(mcs, stellaris_i2c_state), VMSTATE_UINT32(mdr, stellaris_i2c_state), @@ -1121,8 +1125,7 @@ static const VMStateDescription vmstate_stellaris_adc = { .name = "stellaris_adc", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(actss, stellaris_adc_state), VMSTATE_UINT32(ris, stellaris_adc_state), VMSTATE_UINT32(im, stellaris_adc_state), @@ -1205,7 +1208,6 @@ static void stellaris_init(const char *kernel_filename, const char *cpu_model, 0x40024000, 0x40025000, 0x40026000}; static const int gpio_irq[7] = {0, 1, 2, 3, 4, 30, 31}; - MemoryRegion *address_space_mem = get_system_memory(); qemu_irq *pic; DeviceState *gpio_dev[7]; qemu_irq gpio_in[7][8]; @@ -1220,7 +1222,7 @@ static void stellaris_init(const char *kernel_filename, const char *cpu_model, flash_size = ((board->dc0 & 0xffff) + 1) << 1; sram_size = (board->dc0 >> 18) + 1; - pic = armv7m_init(address_space_mem, + pic = armv7m_init(get_system_memory(), flash_size, sram_size, kernel_filename, cpu_model); if (board->dc1 & (1 << 16)) { @@ -1287,9 +1289,10 @@ static void stellaris_init(const char *kernel_filename, const char *cpu_model, sddev = ssi_create_slave(bus, "ssi-sd"); ssddev = ssi_create_slave(bus, "ssd0323"); - gpio_out[GPIO_D][0] = qemu_irq_split(qdev_get_gpio_in(sddev, 0), - qdev_get_gpio_in(ssddev, 0)); - gpio_out[GPIO_C][7] = qdev_get_gpio_in(ssddev, 1); + gpio_out[GPIO_D][0] = qemu_irq_split( + qdev_get_gpio_in_named(sddev, SSI_GPIO_CS, 0), + qdev_get_gpio_in_named(ssddev, SSI_GPIO_CS, 0)); + gpio_out[GPIO_C][7] = qdev_get_gpio_in(ssddev, 0); /* Make sure the select pin is high. */ qemu_irq_raise(gpio_out[GPIO_D][0]); @@ -1330,17 +1333,17 @@ static void stellaris_init(const char *kernel_filename, const char *cpu_model, } /* FIXME: Figure out how to generate these from stellaris_boards. */ -static void lm3s811evb_init(QEMUMachineInitArgs *args) +static void lm3s811evb_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; stellaris_init(kernel_filename, cpu_model, &stellaris_boards[0]); } -static void lm3s6965evb_init(QEMUMachineInitArgs *args) +static void lm3s6965evb_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; stellaris_init(kernel_filename, cpu_model, &stellaris_boards[1]); } diff --git a/hw/arm/strongarm.c b/hw/arm/strongarm.c index 170d0ce267..32063459dd 100644 --- a/hw/arm/strongarm.c +++ b/hw/arm/strongarm.c @@ -199,7 +199,6 @@ static VMStateDescription vmstate_strongarm_pic_regs = { .name = "strongarm_pic", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = strongarm_pic_post_load, .fields = (VMStateField[]) { VMSTATE_UINT32(pending, StrongARMPICState), @@ -424,7 +423,6 @@ static const VMStateDescription vmstate_strongarm_rtc_regs = { .name = "strongarm-rtc", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = strongarm_rtc_pre_save, .post_load = strongarm_rtc_post_load, .fields = (VMStateField[]) { @@ -482,7 +480,6 @@ struct StrongARMGPIOInfo { uint32_t rising; uint32_t falling; uint32_t status; - uint32_t gpsr; uint32_t gafr; uint32_t prev_level; @@ -546,14 +543,14 @@ static uint64_t strongarm_gpio_read(void *opaque, hwaddr offset, return s->dir; case GPSR: /* GPIO Pin-Output Set registers */ - DPRINTF("%s: Read from a write-only register 0x" TARGET_FMT_plx "\n", - __func__, offset); - return s->gpsr; /* Return last written value. */ + qemu_log_mask(LOG_GUEST_ERROR, + "strongarm GPIO: read from write only register GPSR\n"); + return 0; case GPCR: /* GPIO Pin-Output Clear registers */ - DPRINTF("%s: Read from a write-only register 0x" TARGET_FMT_plx "\n", - __func__, offset); - return 31337; /* Specified as unpredictable in the docs. */ + qemu_log_mask(LOG_GUEST_ERROR, + "strongarm GPIO: read from write only register GPCR\n"); + return 0; case GRER: /* GPIO Rising-Edge Detect Enable registers */ return s->rising; @@ -592,7 +589,6 @@ static void strongarm_gpio_write(void *opaque, hwaddr offset, case GPSR: /* GPIO Pin-Output Set registers */ s->olevel |= value; strongarm_gpio_handler_update(s); - s->gpsr = value; break; case GPCR: /* GPIO Pin-Output Clear registers */ @@ -670,7 +666,6 @@ static const VMStateDescription vmstate_strongarm_gpio_regs = { .name = "strongarm-gpio", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_UINT32(ilevel, StrongARMGPIOInfo), VMSTATE_UINT32(olevel, StrongARMGPIOInfo), @@ -679,6 +674,7 @@ static const VMStateDescription vmstate_strongarm_gpio_regs = { VMSTATE_UINT32(falling, StrongARMGPIOInfo), VMSTATE_UINT32(status, StrongARMGPIOInfo), VMSTATE_UINT32(gafr, StrongARMGPIOInfo), + VMSTATE_UINT32(prev_level, StrongARMGPIOInfo), VMSTATE_END_OF_LIST(), }, }; @@ -690,6 +686,7 @@ static void strongarm_gpio_class_init(ObjectClass *klass, void *data) k->init = strongarm_gpio_initfn; dc->desc = "StrongARM GPIO controller"; + dc->vmsd = &vmstate_strongarm_gpio_regs; } static const TypeInfo strongarm_gpio_info = { @@ -842,7 +839,6 @@ static const VMStateDescription vmstate_strongarm_ppc_regs = { .name = "strongarm-ppc", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_UINT32(ilevel, StrongARMPPCInfo), VMSTATE_UINT32(olevel, StrongARMPPCInfo), @@ -850,6 +846,7 @@ static const VMStateDescription vmstate_strongarm_ppc_regs = { VMSTATE_UINT32(ppar, StrongARMPPCInfo), VMSTATE_UINT32(psdr, StrongARMPPCInfo), VMSTATE_UINT32(ppfr, StrongARMPPCInfo), + VMSTATE_UINT32(prev_level, StrongARMPPCInfo), VMSTATE_END_OF_LIST(), }, }; @@ -861,6 +858,7 @@ static void strongarm_ppc_class_init(ObjectClass *klass, void *data) k->init = strongarm_ppc_init; dc->desc = "StrongARM PPC controller"; + dc->vmsd = &vmstate_strongarm_ppc_regs; } static const TypeInfo strongarm_ppc_info = { @@ -1293,7 +1291,6 @@ static const VMStateDescription vmstate_strongarm_uart_regs = { .name = "strongarm-uart", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = strongarm_uart_post_load, .fields = (VMStateField[]) { VMSTATE_UINT8(utcr0, StrongARMUARTState), @@ -1553,7 +1550,6 @@ static const VMStateDescription vmstate_strongarm_ssp_regs = { .name = "strongarm-ssp", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = strongarm_ssp_post_load, .fields = (VMStateField[]) { VMSTATE_UINT16_ARRAY(sscr, StrongARMSSPState, 2), @@ -1608,7 +1604,8 @@ StrongARMState *sa1110_init(MemoryRegion *sysmem, exit(1); } - memory_region_init_ram(&s->sdram, NULL, "strongarm.sdram", sdram_size); + memory_region_init_ram(&s->sdram, NULL, "strongarm.sdram", sdram_size, + &error_abort); vmstate_register_ram_global(&s->sdram); memory_region_add_subregion(sysmem, SA_SDCS0, &s->sdram); diff --git a/hw/arm/tosa.c b/hw/arm/tosa.c index 2069f55432..73572ebe01 100644 --- a/hw/arm/tosa.c +++ b/hw/arm/tosa.c @@ -17,11 +17,10 @@ #include "hw/devices.h" #include "hw/arm/sharpsl.h" #include "hw/pcmcia.h" -#include "block/block.h" #include "hw/boards.h" #include "hw/i2c/i2c.h" #include "hw/ssi.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/sysbus.h" #include "exec/address-spaces.h" @@ -211,12 +210,12 @@ static struct arm_boot_info tosa_binfo = { .ram_size = 0x04000000, }; -static void tosa_init(QEMUMachineInitArgs *args) +static void tosa_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *rom = g_new(MemoryRegion, 1); PXA2xxState *mpu; @@ -228,7 +227,7 @@ static void tosa_init(QEMUMachineInitArgs *args) mpu = pxa255_init(address_space_mem, tosa_binfo.ram_size); - memory_region_init_ram(rom, NULL, "tosa.rom", TOSA_ROM); + memory_region_init_ram(rom, NULL, "tosa.rom", TOSA_ROM, &error_abort); vmstate_register_ram_global(rom); memory_region_set_readonly(rom, true); memory_region_add_subregion(address_space_mem, 0, rom); diff --git a/hw/arm/versatilepb.c b/hw/arm/versatilepb.c index e5493b428f..e6ef0a2e7e 100644 --- a/hw/arm/versatilepb.c +++ b/hw/arm/versatilepb.c @@ -15,7 +15,7 @@ #include "hw/pci/pci.h" #include "hw/i2c/i2c.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "hw/block/flash.h" @@ -173,7 +173,7 @@ static int vpb_sic_init(SysBusDevice *sbd) static struct arm_boot_info versatile_binfo; -static void versatile_init(QEMUMachineInitArgs *args, int board_id) +static void versatile_init(MachineState *machine, int board_id) { ARMCPU *cpu; MemoryRegion *sysmem = get_system_memory(); @@ -190,15 +190,16 @@ static void versatile_init(QEMUMachineInitArgs *args, int board_id) int done_smc = 0; DriveInfo *dinfo; - if (!args->cpu_model) { - args->cpu_model = "arm926"; + if (!machine->cpu_model) { + machine->cpu_model = "arm926"; } - cpu = cpu_arm_init(args->cpu_model); + cpu = cpu_arm_init(machine->cpu_model); if (!cpu) { fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } - memory_region_init_ram(ram, NULL, "versatile.ram", args->ram_size); + memory_region_init_ram(ram, NULL, "versatile.ram", machine->ram_size, + &error_abort); vmstate_register_ram_global(ram); /* ??? RAM should repeat to fill physical memory space. */ /* SDRAM at address zero. */ @@ -337,29 +338,30 @@ static void versatile_init(QEMUMachineInitArgs *args, int board_id) dinfo = drive_get(IF_PFLASH, 0, 0); if (!pflash_cfi01_register(VERSATILE_FLASH_ADDR, NULL, "versatile.flash", - VERSATILE_FLASH_SIZE, dinfo ? dinfo->bdrv : NULL, + VERSATILE_FLASH_SIZE, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, VERSATILE_FLASH_SECT_SIZE, VERSATILE_FLASH_SIZE / VERSATILE_FLASH_SECT_SIZE, 4, 0x0089, 0x0018, 0x0000, 0x0, 0)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); } - versatile_binfo.ram_size = args->ram_size; - versatile_binfo.kernel_filename = args->kernel_filename; - versatile_binfo.kernel_cmdline = args->kernel_cmdline; - versatile_binfo.initrd_filename = args->initrd_filename; + versatile_binfo.ram_size = machine->ram_size; + versatile_binfo.kernel_filename = machine->kernel_filename; + versatile_binfo.kernel_cmdline = machine->kernel_cmdline; + versatile_binfo.initrd_filename = machine->initrd_filename; versatile_binfo.board_id = board_id; arm_load_kernel(cpu, &versatile_binfo); } -static void vpb_init(QEMUMachineInitArgs *args) +static void vpb_init(MachineState *machine) { - versatile_init(args, 0x183); + versatile_init(machine, 0x183); } -static void vab_init(QEMUMachineInitArgs *args) +static void vab_init(MachineState *machine) { - versatile_init(args, 0x25e); + versatile_init(machine, 0x25e); } static QEMUMachine versatilepb_machine = { diff --git a/hw/arm/vexpress.c b/hw/arm/vexpress.c index 169eb061a3..7cbd13f182 100644 --- a/hw/arm/vexpress.c +++ b/hw/arm/vexpress.c @@ -28,8 +28,9 @@ #include "net/net.h" #include "sysemu/sysemu.h" #include "hw/boards.h" +#include "hw/loader.h" #include "exec/address-spaces.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/block/flash.h" #include "sysemu/device_tree.h" #include "qemu/error-report.h" @@ -83,6 +84,7 @@ enum { }; static hwaddr motherboard_legacy_map[] = { + [VE_NORFLASHALIAS] = 0, /* CS7: 0x10000000 .. 0x10020000 */ [VE_SYSREGS] = 0x10000000, [VE_SP810] = 0x10001000, @@ -113,7 +115,6 @@ static hwaddr motherboard_legacy_map[] = { [VE_VIDEORAM] = 0x4c000000, [VE_ETHERNET] = 0x4e000000, [VE_USB] = 0x4f000000, - [VE_NORFLASHALIAS] = -1, /* not present */ }; static hwaddr motherboard_aseries_map[] = { @@ -251,7 +252,8 @@ static void a9_daughterboard_init(const VEDBoardInfo *daughterboard, exit(1); } - memory_region_init_ram(ram, NULL, "vexpress.highmem", ram_size); + memory_region_init_ram(ram, NULL, "vexpress.highmem", ram_size, + &error_abort); vmstate_register_ram_global(ram); low_ram_size = ram_size; if (low_ram_size > 0x4000000) { @@ -345,7 +347,8 @@ static void a15_daughterboard_init(const VEDBoardInfo *daughterboard, } } - memory_region_init_ram(ram, NULL, "vexpress.highmem", ram_size); + memory_region_init_ram(ram, NULL, "vexpress.highmem", ram_size, + &error_abort); vmstate_register_ram_global(ram); /* RAM is from 0x80000000 upwards; there is no low-memory alias for it. */ memory_region_add_subregion(sysmem, 0x80000000, ram); @@ -363,7 +366,8 @@ static void a15_daughterboard_init(const VEDBoardInfo *daughterboard, /* 0x2b060000: SP805 watchdog: not modelled */ /* 0x2b0a0000: PL341 dynamic memory controller: not modelled */ /* 0x2e000000: system SRAM */ - memory_region_init_ram(sram, NULL, "vexpress.a15sram", 0x10000); + memory_region_init_ram(sram, NULL, "vexpress.a15sram", 0x10000, + &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(sysmem, 0x2e000000, sram); @@ -487,7 +491,8 @@ static pflash_t *ve_pflash_cfi01_register(hwaddr base, const char *name, { DeviceState *dev = qdev_create(NULL, "cfi.pflash01"); - if (di && qdev_prop_set_drive(dev, "drive", di->bdrv)) { + if (di && qdev_prop_set_drive(dev, "drive", + blk_by_legacy_dinfo(di))) { abort(); } @@ -509,7 +514,7 @@ static pflash_t *ve_pflash_cfi01_register(hwaddr base, const char *name, } static void vexpress_common_init(VEDBoardInfo *daughterboard, - QEMUMachineInitArgs *args) + MachineState *machine) { DeviceState *dev, *sysctl, *pl041; qemu_irq pic[64]; @@ -525,7 +530,28 @@ static void vexpress_common_init(VEDBoardInfo *daughterboard, const hwaddr *map = daughterboard->motherboard_map; int i; - daughterboard->init(daughterboard, args->ram_size, args->cpu_model, pic); + daughterboard->init(daughterboard, machine->ram_size, machine->cpu_model, + pic); + + /* + * If a bios file was provided, attempt to map it into memory + */ + if (bios_name) { + const char *fn; + + if (drive_get(IF_PFLASH, 0, 0)) { + error_report("The contents of the first flash device may be " + "specified with -bios or with -drive if=pflash... " + "but you cannot use both options at once"); + exit(1); + } + fn = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); + if (!fn || load_image_targphys(fn, map[VE_NORFLASH0], + VEXPRESS_FLASH_SIZE) < 0) { + error_report("Could not load ROM image '%s'", bios_name); + exit(1); + } + } /* Motherboard peripherals: the wiring is the same but the * addresses vary between the legacy and A-Series memory maps. @@ -612,12 +638,14 @@ static void vexpress_common_init(VEDBoardInfo *daughterboard, } sram_size = 0x2000000; - memory_region_init_ram(sram, NULL, "vexpress.sram", sram_size); + memory_region_init_ram(sram, NULL, "vexpress.sram", sram_size, + &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(sysmem, map[VE_SRAM], sram); vram_size = 0x800000; - memory_region_init_ram(vram, NULL, "vexpress.vram", vram_size); + memory_region_init_ram(vram, NULL, "vexpress.vram", vram_size, + &error_abort); vmstate_register_ram_global(vram); memory_region_add_subregion(sysmem, map[VE_VIDEORAM], vram); @@ -639,10 +667,10 @@ static void vexpress_common_init(VEDBoardInfo *daughterboard, pic[40 + i]); } - daughterboard->bootinfo.ram_size = args->ram_size; - daughterboard->bootinfo.kernel_filename = args->kernel_filename; - daughterboard->bootinfo.kernel_cmdline = args->kernel_cmdline; - daughterboard->bootinfo.initrd_filename = args->initrd_filename; + daughterboard->bootinfo.ram_size = machine->ram_size; + daughterboard->bootinfo.kernel_filename = machine->kernel_filename; + daughterboard->bootinfo.kernel_cmdline = machine->kernel_cmdline; + daughterboard->bootinfo.initrd_filename = machine->initrd_filename; daughterboard->bootinfo.nb_cpus = smp_cpus; daughterboard->bootinfo.board_id = VEXPRESS_BOARD_ID; daughterboard->bootinfo.loader_start = daughterboard->loader_start; @@ -653,14 +681,14 @@ static void vexpress_common_init(VEDBoardInfo *daughterboard, arm_load_kernel(ARM_CPU(first_cpu), &daughterboard->bootinfo); } -static void vexpress_a9_init(QEMUMachineInitArgs *args) +static void vexpress_a9_init(MachineState *machine) { - vexpress_common_init(&a9_daughterboard, args); + vexpress_common_init(&a9_daughterboard, machine); } -static void vexpress_a15_init(QEMUMachineInitArgs *args) +static void vexpress_a15_init(MachineState *machine) { - vexpress_common_init(&a15_daughterboard, args); + vexpress_common_init(&a15_daughterboard, machine); } static QEMUMachine vexpress_a9_machine = { diff --git a/hw/arm/virt.c b/hw/arm/virt.c index 2bbc9313d2..314e55b563 100644 --- a/hw/arm/virt.c +++ b/hw/arm/virt.c @@ -33,10 +33,12 @@ #include "hw/arm/primecell.h" #include "hw/devices.h" #include "net/net.h" +#include "sysemu/block-backend.h" #include "sysemu/device_tree.h" #include "sysemu/sysemu.h" #include "sysemu/kvm.h" #include "hw/boards.h" +#include "hw/loader.h" #include "exec/address-spaces.h" #include "qemu/bitops.h" #include "qemu/error-report.h" @@ -65,6 +67,7 @@ enum { VIRT_GIC_CPU, VIRT_UART, VIRT_MMIO, + VIRT_RTC, }; typedef struct MemMapEntry { @@ -75,8 +78,6 @@ typedef struct MemMapEntry { typedef struct VirtBoardInfo { struct arm_boot_info bootinfo; const char *cpu_model; - const char *qdevname; - const char *gic_compatible; const MemMapEntry *memmap; const int *irqmap; int smp_cpus; @@ -94,39 +95,43 @@ typedef struct VirtBoardInfo { * high memory region beyond 4GB). * This represents a compromise between how much RAM can be given to * a 32 bit VM and leaving space for expansion and in particular for PCI. + * Note that devices should generally be placed at multiples of 0x10000, + * to accommodate guests using 64K pages. */ static const MemMapEntry a15memmap[] = { /* Space up to 0x8000000 is reserved for a boot ROM */ - [VIRT_FLASH] = { 0, 0x8000000 }, - [VIRT_CPUPERIPHS] = { 0x8000000, 0x8000 }, + [VIRT_FLASH] = { 0, 0x08000000 }, + [VIRT_CPUPERIPHS] = { 0x08000000, 0x00020000 }, /* GIC distributor and CPU interfaces sit inside the CPU peripheral space */ - [VIRT_GIC_DIST] = { 0x8001000, 0x1000 }, - [VIRT_GIC_CPU] = { 0x8002000, 0x1000 }, - [VIRT_UART] = { 0x9000000, 0x1000 }, - [VIRT_MMIO] = { 0xa000000, 0x200 }, + [VIRT_GIC_DIST] = { 0x08000000, 0x00010000 }, + [VIRT_GIC_CPU] = { 0x08010000, 0x00010000 }, + [VIRT_UART] = { 0x09000000, 0x00001000 }, + [VIRT_RTC] = { 0x09010000, 0x00001000 }, + [VIRT_MMIO] = { 0x0a000000, 0x00000200 }, /* ...repeating for a total of NUM_VIRTIO_TRANSPORTS, each of that size */ /* 0x10000000 .. 0x40000000 reserved for PCI */ - [VIRT_MEM] = { 0x40000000, 30ULL * 1024 * 1024 * 1024 }, + [VIRT_MEM] = { 0x40000000, 30ULL * 1024 * 1024 * 1024 }, }; static const int a15irqmap[] = { [VIRT_UART] = 1, + [VIRT_RTC] = 2, [VIRT_MMIO] = 16, /* ...to 16 + NUM_VIRTIO_TRANSPORTS - 1 */ }; static VirtBoardInfo machines[] = { { .cpu_model = "cortex-a15", - .qdevname = "a15mpcore_priv", - .gic_compatible = "arm,cortex-a15-gic", + .memmap = a15memmap, + .irqmap = a15irqmap, + }, + { + .cpu_model = "cortex-a57", .memmap = a15memmap, .irqmap = a15irqmap, }, { .cpu_model = "host", - /* We use the A15 private peripheral model to get a V2 GIC */ - .qdevname = "a15mpcore_priv", - .gic_compatible = "arm,cortex-a15-gic", .memmap = a15memmap, .irqmap = a15irqmap, }, @@ -182,17 +187,52 @@ static void create_fdt(VirtBoardInfo *vbi) "clk24mhz"); qemu_fdt_setprop_cell(fdt, "/apb-pclk", "phandle", vbi->clock_phandle); - /* No PSCI for TCG yet */ - if (kvm_enabled()) { - qemu_fdt_add_subnode(fdt, "/psci"); +} + +static void fdt_add_psci_node(const VirtBoardInfo *vbi) +{ + uint32_t cpu_suspend_fn; + uint32_t cpu_off_fn; + uint32_t cpu_on_fn; + uint32_t migrate_fn; + void *fdt = vbi->fdt; + ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(0)); + + qemu_fdt_add_subnode(fdt, "/psci"); + if (armcpu->psci_version == 2) { + const char comp[] = "arm,psci-0.2\0arm,psci"; + qemu_fdt_setprop(fdt, "/psci", "compatible", comp, sizeof(comp)); + + cpu_off_fn = QEMU_PSCI_0_2_FN_CPU_OFF; + if (arm_feature(&armcpu->env, ARM_FEATURE_AARCH64)) { + cpu_suspend_fn = QEMU_PSCI_0_2_FN64_CPU_SUSPEND; + cpu_on_fn = QEMU_PSCI_0_2_FN64_CPU_ON; + migrate_fn = QEMU_PSCI_0_2_FN64_MIGRATE; + } else { + cpu_suspend_fn = QEMU_PSCI_0_2_FN_CPU_SUSPEND; + cpu_on_fn = QEMU_PSCI_0_2_FN_CPU_ON; + migrate_fn = QEMU_PSCI_0_2_FN_MIGRATE; + } + } else { qemu_fdt_setprop_string(fdt, "/psci", "compatible", "arm,psci"); - qemu_fdt_setprop_string(fdt, "/psci", "method", "hvc"); - qemu_fdt_setprop_cell(fdt, "/psci", "cpu_suspend", - PSCI_FN_CPU_SUSPEND); - qemu_fdt_setprop_cell(fdt, "/psci", "cpu_off", PSCI_FN_CPU_OFF); - qemu_fdt_setprop_cell(fdt, "/psci", "cpu_on", PSCI_FN_CPU_ON); - qemu_fdt_setprop_cell(fdt, "/psci", "migrate", PSCI_FN_MIGRATE); + + cpu_suspend_fn = QEMU_PSCI_0_1_FN_CPU_SUSPEND; + cpu_off_fn = QEMU_PSCI_0_1_FN_CPU_OFF; + cpu_on_fn = QEMU_PSCI_0_1_FN_CPU_ON; + migrate_fn = QEMU_PSCI_0_1_FN_MIGRATE; } + + /* We adopt the PSCI spec's nomenclature, and use 'conduit' to refer + * to the instruction that should be used to invoke PSCI functions. + * However, the device tree binding uses 'method' instead, so that is + * what we should use here. + */ + qemu_fdt_setprop_string(fdt, "/psci", "method", "hvc"); + + qemu_fdt_setprop_cell(fdt, "/psci", "cpu_suspend", cpu_suspend_fn); + qemu_fdt_setprop_cell(fdt, "/psci", "cpu_off", cpu_off_fn); + qemu_fdt_setprop_cell(fdt, "/psci", "cpu_on", cpu_on_fn); + qemu_fdt_setprop_cell(fdt, "/psci", "migrate", migrate_fn); } static void fdt_add_timer_nodes(const VirtBoardInfo *vbi) @@ -201,14 +241,23 @@ static void fdt_add_timer_nodes(const VirtBoardInfo *vbi) * but for the GIC implementation provided by both QEMU and KVM * they are edge-triggered. */ + ARMCPU *armcpu; uint32_t irqflags = GIC_FDT_IRQ_FLAGS_EDGE_LO_HI; irqflags = deposit32(irqflags, GIC_FDT_IRQ_PPI_CPU_START, GIC_FDT_IRQ_PPI_CPU_WIDTH, (1 << vbi->smp_cpus) - 1); qemu_fdt_add_subnode(vbi->fdt, "/timer"); - qemu_fdt_setprop_string(vbi->fdt, "/timer", - "compatible", "arm,armv7-timer"); + + armcpu = ARM_CPU(qemu_get_cpu(0)); + if (arm_feature(&armcpu->env, ARM_FEATURE_V8)) { + const char compat[] = "arm,armv8-timer\0arm,armv7-timer"; + qemu_fdt_setprop(vbi->fdt, "/timer", "compatible", + compat, sizeof(compat)); + } else { + qemu_fdt_setprop_string(vbi->fdt, "/timer", "compatible", + "arm,armv7-timer"); + } qemu_fdt_setprop_cells(vbi->fdt, "/timer", "interrupts", GIC_FDT_IRQ_TYPE_PPI, 13, irqflags, GIC_FDT_IRQ_TYPE_PPI, 14, irqflags, @@ -251,8 +300,9 @@ static void fdt_add_gic_node(const VirtBoardInfo *vbi) qemu_fdt_setprop_cell(vbi->fdt, "/", "interrupt-parent", gic_phandle); qemu_fdt_add_subnode(vbi->fdt, "/intc"); + /* 'cortex-a15-gic' means 'GIC v2' */ qemu_fdt_setprop_string(vbi->fdt, "/intc", "compatible", - vbi->gic_compatible); + "arm,cortex-a15-gic"); qemu_fdt_setprop_cell(vbi->fdt, "/intc", "#interrupt-cells", 3); qemu_fdt_setprop(vbi->fdt, "/intc", "interrupt-controller", NULL, 0); qemu_fdt_setprop_sized_cells(vbi->fdt, "/intc", "reg", @@ -263,6 +313,56 @@ static void fdt_add_gic_node(const VirtBoardInfo *vbi) qemu_fdt_setprop_cell(vbi->fdt, "/intc", "phandle", gic_phandle); } +static void create_gic(const VirtBoardInfo *vbi, qemu_irq *pic) +{ + /* We create a standalone GIC v2 */ + DeviceState *gicdev; + SysBusDevice *gicbusdev; + const char *gictype = "arm_gic"; + int i; + + if (kvm_irqchip_in_kernel()) { + gictype = "kvm-arm-gic"; + } + + gicdev = qdev_create(NULL, gictype); + qdev_prop_set_uint32(gicdev, "revision", 2); + qdev_prop_set_uint32(gicdev, "num-cpu", smp_cpus); + /* Note that the num-irq property counts both internal and external + * interrupts; there are always 32 of the former (mandated by GIC spec). + */ + qdev_prop_set_uint32(gicdev, "num-irq", NUM_IRQS + 32); + qdev_init_nofail(gicdev); + gicbusdev = SYS_BUS_DEVICE(gicdev); + sysbus_mmio_map(gicbusdev, 0, vbi->memmap[VIRT_GIC_DIST].base); + sysbus_mmio_map(gicbusdev, 1, vbi->memmap[VIRT_GIC_CPU].base); + + /* Wire the outputs from each CPU's generic timer to the + * appropriate GIC PPI inputs, and the GIC's IRQ output to + * the CPU's IRQ input. + */ + for (i = 0; i < smp_cpus; i++) { + DeviceState *cpudev = DEVICE(qemu_get_cpu(i)); + int ppibase = NUM_IRQS + i * 32; + /* physical timer; we wire it up to the non-secure timer's ID, + * since a real A15 always has TrustZone but QEMU doesn't. + */ + qdev_connect_gpio_out(cpudev, 0, + qdev_get_gpio_in(gicdev, ppibase + 30)); + /* virtual timer */ + qdev_connect_gpio_out(cpudev, 1, + qdev_get_gpio_in(gicdev, ppibase + 27)); + + sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ)); + } + + for (i = 0; i < NUM_IRQS; i++) { + pic[i] = qdev_get_gpio_in(gicdev, i); + } + + fdt_add_gic_node(vbi); +} + static void create_uart(const VirtBoardInfo *vbi, qemu_irq *pic) { char *nodename; @@ -283,11 +383,36 @@ static void create_uart(const VirtBoardInfo *vbi, qemu_irq *pic) 2, base, 2, size); qemu_fdt_setprop_cells(vbi->fdt, nodename, "interrupts", GIC_FDT_IRQ_TYPE_SPI, irq, - GIC_FDT_IRQ_FLAGS_EDGE_LO_HI); + GIC_FDT_IRQ_FLAGS_LEVEL_HI); qemu_fdt_setprop_cells(vbi->fdt, nodename, "clocks", vbi->clock_phandle, vbi->clock_phandle); qemu_fdt_setprop(vbi->fdt, nodename, "clock-names", clocknames, sizeof(clocknames)); + + qemu_fdt_setprop_string(vbi->fdt, "/chosen", "stdout-path", nodename); + g_free(nodename); +} + +static void create_rtc(const VirtBoardInfo *vbi, qemu_irq *pic) +{ + char *nodename; + hwaddr base = vbi->memmap[VIRT_RTC].base; + hwaddr size = vbi->memmap[VIRT_RTC].size; + int irq = vbi->irqmap[VIRT_RTC]; + const char compat[] = "arm,pl031\0arm,primecell"; + + sysbus_create_simple("pl031", base, pic[irq]); + + nodename = g_strdup_printf("/pl031@%" PRIx64, base); + qemu_fdt_add_subnode(vbi->fdt, nodename); + qemu_fdt_setprop(vbi->fdt, nodename, "compatible", compat, sizeof(compat)); + qemu_fdt_setprop_sized_cells(vbi->fdt, nodename, "reg", + 2, base, 2, size); + qemu_fdt_setprop_cells(vbi->fdt, nodename, "interrupts", + GIC_FDT_IRQ_TYPE_SPI, irq, + GIC_FDT_IRQ_FLAGS_LEVEL_HI); + qemu_fdt_setprop_cell(vbi->fdt, nodename, "clocks", vbi->clock_phandle); + qemu_fdt_setprop_string(vbi->fdt, nodename, "clock-names", "apb_pclk"); g_free(nodename); } @@ -326,6 +451,74 @@ static void create_virtio_devices(const VirtBoardInfo *vbi, qemu_irq *pic) } } +static void create_one_flash(const char *name, hwaddr flashbase, + hwaddr flashsize) +{ + /* Create and map a single flash device. We use the same + * parameters as the flash devices on the Versatile Express board. + */ + DriveInfo *dinfo = drive_get_next(IF_PFLASH); + DeviceState *dev = qdev_create(NULL, "cfi.pflash01"); + const uint64_t sectorlength = 256 * 1024; + + if (dinfo && qdev_prop_set_drive(dev, "drive", + blk_by_legacy_dinfo(dinfo))) { + abort(); + } + + qdev_prop_set_uint32(dev, "num-blocks", flashsize / sectorlength); + qdev_prop_set_uint64(dev, "sector-length", sectorlength); + qdev_prop_set_uint8(dev, "width", 4); + qdev_prop_set_uint8(dev, "device-width", 2); + qdev_prop_set_uint8(dev, "big-endian", 0); + qdev_prop_set_uint16(dev, "id0", 0x89); + qdev_prop_set_uint16(dev, "id1", 0x18); + qdev_prop_set_uint16(dev, "id2", 0x00); + qdev_prop_set_uint16(dev, "id3", 0x00); + qdev_prop_set_string(dev, "name", name); + qdev_init_nofail(dev); + + sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, flashbase); +} + +static void create_flash(const VirtBoardInfo *vbi) +{ + /* Create two flash devices to fill the VIRT_FLASH space in the memmap. + * Any file passed via -bios goes in the first of these. + */ + hwaddr flashsize = vbi->memmap[VIRT_FLASH].size / 2; + hwaddr flashbase = vbi->memmap[VIRT_FLASH].base; + char *nodename; + + if (bios_name) { + const char *fn; + + if (drive_get(IF_PFLASH, 0, 0)) { + error_report("The contents of the first flash device may be " + "specified with -bios or with -drive if=pflash... " + "but you cannot use both options at once"); + exit(1); + } + fn = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); + if (!fn || load_image_targphys(fn, flashbase, flashsize) < 0) { + error_report("Could not load ROM image '%s'", bios_name); + exit(1); + } + } + + create_one_flash("virt.flash0", flashbase, flashsize); + create_one_flash("virt.flash1", flashbase + flashsize, flashsize); + + nodename = g_strdup_printf("/flash@%" PRIx64, flashbase); + qemu_fdt_add_subnode(vbi->fdt, nodename); + qemu_fdt_setprop_string(vbi->fdt, nodename, "compatible", "cfi-flash"); + qemu_fdt_setprop_sized_cells(vbi->fdt, nodename, "reg", + 2, flashbase, 2, flashsize, + 2, flashbase + flashsize, 2, flashsize); + qemu_fdt_setprop_cell(vbi->fdt, nodename, "bank-width", 4); + g_free(nodename); +} + static void *machvirt_dtb(const struct arm_boot_info *binfo, int *fdt_size) { const VirtBoardInfo *board = (const VirtBoardInfo *)binfo; @@ -334,15 +527,13 @@ static void *machvirt_dtb(const struct arm_boot_info *binfo, int *fdt_size) return board->fdt; } -static void machvirt_init(QEMUMachineInitArgs *args) +static void machvirt_init(MachineState *machine) { qemu_irq pic[NUM_IRQS]; MemoryRegion *sysmem = get_system_memory(); int n; MemoryRegion *ram = g_new(MemoryRegion, 1); - DeviceState *dev; - SysBusDevice *busdev; - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; VirtBoardInfo *vbi; if (!cpu_model) { @@ -358,23 +549,12 @@ static void machvirt_init(QEMUMachineInitArgs *args) vbi->smp_cpus = smp_cpus; - /* - * Only supported method of starting secondary CPUs is PSCI and - * PSCI is not yet supported with TCG, so limit smp_cpus to 1 - * if we're not using KVM. - */ - if (!kvm_enabled() && smp_cpus > 1) { - error_report("mach-virt: must enable KVM to use multiple CPUs"); - exit(1); - } - - if (args->ram_size > vbi->memmap[VIRT_MEM].size) { + if (machine->ram_size > vbi->memmap[VIRT_MEM].size) { error_report("mach-virt: cannot model more than 30GB RAM"); exit(1); } create_fdt(vbi); - fdt_add_timer_nodes(vbi); for (n = 0; n < smp_cpus; n++) { ObjectClass *oc = cpu_class_by_name(TYPE_ARM_CPU, cpu_model); @@ -386,6 +566,9 @@ static void machvirt_init(QEMUMachineInitArgs *args) } cpuobj = object_new(object_class_get_name(oc)); + object_property_set_int(cpuobj, QEMU_PSCI_CONDUIT_HVC, "psci-conduit", + NULL); + /* Secondary CPUs start in PSCI powered-down state */ if (n > 0) { object_property_set_bool(cpuobj, true, "start-powered-off", NULL); @@ -398,44 +581,33 @@ static void machvirt_init(QEMUMachineInitArgs *args) object_property_set_bool(cpuobj, true, "realized", NULL); } + fdt_add_timer_nodes(vbi); fdt_add_cpu_nodes(vbi); + fdt_add_psci_node(vbi); - memory_region_init_ram(ram, NULL, "mach-virt.ram", args->ram_size); + memory_region_init_ram(ram, NULL, "mach-virt.ram", machine->ram_size, + &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(sysmem, vbi->memmap[VIRT_MEM].base, ram); - dev = qdev_create(NULL, vbi->qdevname); - qdev_prop_set_uint32(dev, "num-cpu", smp_cpus); - /* Note that the num-irq property counts both internal and external - * interrupts; there are always 32 of the former (mandated by GIC spec). - */ - qdev_prop_set_uint32(dev, "num-irq", NUM_IRQS + 32); - qdev_init_nofail(dev); - busdev = SYS_BUS_DEVICE(dev); - sysbus_mmio_map(busdev, 0, vbi->memmap[VIRT_CPUPERIPHS].base); - fdt_add_gic_node(vbi); - for (n = 0; n < smp_cpus; n++) { - DeviceState *cpudev = DEVICE(qemu_get_cpu(n)); + create_flash(vbi); - sysbus_connect_irq(busdev, n, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ)); - } - - for (n = 0; n < NUM_IRQS; n++) { - pic[n] = qdev_get_gpio_in(dev, n); - } + create_gic(vbi, pic); create_uart(vbi, pic); + create_rtc(vbi, pic); + /* Create mmio transports, so the user can create virtio backends * (which will be automatically plugged in to the transports). If * no backend is created the transport will just sit harmlessly idle. */ create_virtio_devices(vbi, pic); - vbi->bootinfo.ram_size = args->ram_size; - vbi->bootinfo.kernel_filename = args->kernel_filename; - vbi->bootinfo.kernel_cmdline = args->kernel_cmdline; - vbi->bootinfo.initrd_filename = args->initrd_filename; + vbi->bootinfo.ram_size = machine->ram_size; + vbi->bootinfo.kernel_filename = machine->kernel_filename; + vbi->bootinfo.kernel_cmdline = machine->kernel_cmdline; + vbi->bootinfo.initrd_filename = machine->initrd_filename; vbi->bootinfo.nb_cpus = smp_cpus; vbi->bootinfo.board_id = -1; vbi->bootinfo.loader_start = vbi->memmap[VIRT_MEM].base; @@ -447,7 +619,7 @@ static QEMUMachine machvirt_a15_machine = { .name = "virt", .desc = "ARM Virtual Machine", .init = machvirt_init, - .max_cpus = 4, + .max_cpus = 8, }; static void machvirt_machine_init(void) diff --git a/hw/arm/xilinx_zynq.c b/hw/arm/xilinx_zynq.c index 9ee21e726a..b59039297a 100644 --- a/hw/arm/xilinx_zynq.c +++ b/hw/arm/xilinx_zynq.c @@ -22,7 +22,7 @@ #include "sysemu/sysemu.h" #include "hw/boards.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/loader.h" #include "hw/ssi.h" #include "qemu/error-report.h" @@ -94,20 +94,20 @@ static inline void zynq_init_spi_flashes(uint32_t base_addr, qemu_irq irq, for (j = 0; j < num_ss; ++j) { flash_dev = ssi_create_slave(spi, "n25q128"); - cs_line = qdev_get_gpio_in(flash_dev, 0); + cs_line = qdev_get_gpio_in_named(flash_dev, SSI_GPIO_CS, 0); sysbus_connect_irq(busdev, i * num_ss + j + 1, cs_line); } } } -static void zynq_init(QEMUMachineInitArgs *args) +static void zynq_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; ObjectClass *cpu_oc; ARMCPU *cpu; MemoryRegion *address_space_mem = get_system_memory(); @@ -149,12 +149,14 @@ static void zynq_init(QEMUMachineInitArgs *args) } /* DDR remapped to address zero. */ - memory_region_init_ram(ext_ram, NULL, "zynq.ext_ram", ram_size); + memory_region_init_ram(ext_ram, NULL, "zynq.ext_ram", ram_size, + &error_abort); vmstate_register_ram_global(ext_ram); memory_region_add_subregion(address_space_mem, 0, ext_ram); /* 256K of on-chip memory */ - memory_region_init_ram(ocm_ram, NULL, "zynq.ocm_ram", 256 << 10); + memory_region_init_ram(ocm_ram, NULL, "zynq.ocm_ram", 256 << 10, + &error_abort); vmstate_register_ram_global(ocm_ram); memory_region_add_subregion(address_space_mem, 0xFFFC0000, ocm_ram); @@ -162,7 +164,8 @@ static void zynq_init(QEMUMachineInitArgs *args) /* AMD */ pflash_cfi02_register(0xe2000000, NULL, "zynq.pflash", FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, FLASH_SECTOR_SIZE, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + FLASH_SECTOR_SIZE, FLASH_SIZE/FLASH_SECTOR_SIZE, 1, 1, 0x0066, 0x0022, 0x0000, 0x0000, 0x0555, 0x2aa, 0); diff --git a/hw/arm/z2.c b/hw/arm/z2.c index 67c1be84ac..17355479a1 100644 --- a/hw/arm/z2.c +++ b/hw/arm/z2.c @@ -20,7 +20,7 @@ #include "hw/boards.h" #include "sysemu/sysemu.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "ui/console.h" #include "audio/audio.h" #include "exec/address-spaces.h" @@ -164,7 +164,6 @@ static VMStateDescription vmstate_zipit_lcd_state = { .name = "zipit-lcd", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .fields = (VMStateField[]) { VMSTATE_SSI_SLAVE(ssidev, ZipitLCD), VMSTATE_INT32(selected, ZipitLCD), @@ -275,7 +274,6 @@ static VMStateDescription vmstate_aer915_state = { .name = "aer915", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_INT32(len, AER915State), VMSTATE_BUFFER(buf, AER915State), @@ -302,12 +300,12 @@ static const TypeInfo aer915_info = { .class_init = aer915_class_init, }; -static void z2_init(QEMUMachineInitArgs *args) +static void z2_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; MemoryRegion *address_space_mem = get_system_memory(); uint32_t sector_len = 0x10000; PXA2xxState *mpu; @@ -338,9 +336,9 @@ static void z2_init(QEMUMachineInitArgs *args) if (!pflash_cfi01_register(Z2_FLASH_BASE, NULL, "z2.flash0", Z2_FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, sector_len, - Z2_FLASH_SIZE / sector_len, 4, 0, 0, 0, 0, - be)) { + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + sector_len, Z2_FLASH_SIZE / sector_len, + 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); exit(1); } @@ -365,7 +363,7 @@ static void z2_init(QEMUMachineInitArgs *args) wm8750_data_req_set(wm, mpu->i2s->data_req, mpu->i2s); qdev_connect_gpio_out(mpu->gpio, Z2_GPIO_LCD_CS, - qemu_allocate_irqs(z2_lcd_cs, z2_lcd, 1)[0]); + qemu_allocate_irq(z2_lcd_cs, z2_lcd, 0)); z2_binfo.kernel_filename = kernel_filename; z2_binfo.kernel_cmdline = kernel_cmdline; diff --git a/hw/audio/ac97.c b/hw/audio/ac97.c index 03f484628e..111ec0e848 100644 --- a/hw/audio/ac97.c +++ b/hw/audio/ac97.c @@ -1163,8 +1163,7 @@ static const VMStateDescription vmstate_ac97_bm_regs = { .name = "ac97_bm_regs", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32 (bdbar, AC97BusMasterRegs), VMSTATE_UINT8 (civ, AC97BusMasterRegs), VMSTATE_UINT8 (lvi, AC97BusMasterRegs), @@ -1211,9 +1210,8 @@ static const VMStateDescription vmstate_ac97 = { .name = "ac97", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = ac97_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE (dev, AC97LinkState), VMSTATE_UINT32 (glob_cnt, AC97LinkState), VMSTATE_UINT32 (glob_sta, AC97LinkState), @@ -1323,9 +1321,9 @@ static const MemoryRegionOps ac97_io_nabm_ops = { .endianness = DEVICE_LITTLE_ENDIAN, }; -static void ac97_on_reset (void *opaque) +static void ac97_on_reset (DeviceState *dev) { - AC97LinkState *s = opaque; + AC97LinkState *s = container_of(dev, AC97LinkState, dev.qdev); reset_bm_regs (s, &s->bm_regs[0]); reset_bm_regs (s, &s->bm_regs[1]); @@ -1384,20 +1382,11 @@ static int ac97_initfn (PCIDevice *dev) "ac97-nabm", 256); pci_register_bar (&s->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &s->io_nam); pci_register_bar (&s->dev, 1, PCI_BASE_ADDRESS_SPACE_IO, &s->io_nabm); - qemu_register_reset (ac97_on_reset, s); AUD_register_card ("ac97", &s->card); - ac97_on_reset (s); + ac97_on_reset (&s->dev.qdev); return 0; } -static void ac97_exitfn (PCIDevice *dev) -{ - AC97LinkState *s = DO_UPCAST (AC97LinkState, dev, dev); - - memory_region_destroy (&s->io_nam); - memory_region_destroy (&s->io_nabm); -} - static int ac97_init (PCIBus *bus) { pci_create_simple (bus, -1, "AC97"); @@ -1415,7 +1404,6 @@ static void ac97_class_init (ObjectClass *klass, void *data) PCIDeviceClass *k = PCI_DEVICE_CLASS (klass); k->init = ac97_initfn; - k->exit = ac97_exitfn; k->vendor_id = PCI_VENDOR_ID_INTEL; k->device_id = PCI_DEVICE_ID_INTEL_82801AA_5; k->revision = 0x01; @@ -1424,6 +1412,7 @@ static void ac97_class_init (ObjectClass *klass, void *data) dc->desc = "Intel 82801AA AC97 Audio"; dc->vmsd = &vmstate_ac97; dc->props = ac97_properties; + dc->reset = ac97_on_reset; } static const TypeInfo ac97_info = { diff --git a/hw/audio/adlib.c b/hw/audio/adlib.c index 28eed81280..656eb3773a 100644 --- a/hw/audio/adlib.c +++ b/hw/audio/adlib.c @@ -86,6 +86,7 @@ typedef struct { #ifndef HAS_YMF262 FM_OPL *opl; #endif + PortioList port_list; } AdlibState; static AdlibState *glob_adlib; @@ -274,9 +275,7 @@ static void Adlib_fini (AdlibState *s) } #endif - if (s->mixbuf) { - g_free (s->mixbuf); - } + g_free(s->mixbuf); s->active = 0; s->enabled = 0; @@ -293,7 +292,6 @@ static MemoryRegionPortio adlib_portio_list[] = { static void adlib_realizefn (DeviceState *dev, Error **errp) { AdlibState *s = ADLIB(dev); - PortioList *port_list = g_new(PortioList, 1); struct audsettings as; if (glob_adlib) { @@ -349,8 +347,8 @@ static void adlib_realizefn (DeviceState *dev, Error **errp) adlib_portio_list[0].offset = s->port; adlib_portio_list[1].offset = s->port + 8; - portio_list_init (port_list, OBJECT(s), adlib_portio_list, s, "adlib"); - portio_list_add (port_list, isa_address_space_io(&s->parent_obj), 0); + portio_list_init (&s->port_list, OBJECT(s), adlib_portio_list, s, "adlib"); + portio_list_add (&s->port_list, isa_address_space_io(&s->parent_obj), 0); } static Property adlib_properties[] = { diff --git a/hw/audio/cs4231.c b/hw/audio/cs4231.c index d19195afc1..6325a8cea7 100644 --- a/hw/audio/cs4231.c +++ b/hw/audio/cs4231.c @@ -137,8 +137,7 @@ static const VMStateDescription vmstate_cs4231 = { .name ="cs4231", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, CSState, CS_REGS), VMSTATE_UINT8_ARRAY(dregs, CSState, CS_DREGS), VMSTATE_END_OF_LIST() diff --git a/hw/audio/cs4231a.c b/hw/audio/cs4231a.c index a0ec17a836..f96f561c7f 100644 --- a/hw/audio/cs4231a.c +++ b/hw/audio/cs4231a.c @@ -621,10 +621,9 @@ static const VMStateDescription vmstate_cs4231a = { .name = "cs4231a", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_load = cs4231a_pre_load, .post_load = cs4231a_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY (regs, CSState, CS_REGS), VMSTATE_BUFFER (dregs, CSState), VMSTATE_INT32 (dma_running, CSState), diff --git a/hw/audio/es1370.c b/hw/audio/es1370.c index 1ec7acee02..e67d1ea165 100644 --- a/hw/audio/es1370.c +++ b/hw/audio/es1370.c @@ -953,8 +953,7 @@ static const VMStateDescription vmstate_es1370_channel = { .name = "es1370_channel", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32 (shift, struct chan), VMSTATE_UINT32 (leftover, struct chan), VMSTATE_UINT32 (scount, struct chan), @@ -997,9 +996,8 @@ static const VMStateDescription vmstate_es1370 = { .name = "es1370", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = es1370_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE (dev, ES1370State), VMSTATE_STRUCT_ARRAY (chan, ES1370State, NB_CHANNELS, 2, vmstate_es1370_channel, struct chan), @@ -1044,13 +1042,6 @@ static int es1370_initfn (PCIDevice *dev) return 0; } -static void es1370_exitfn (PCIDevice *dev) -{ - ES1370State *s = DO_UPCAST (ES1370State, dev, dev); - - memory_region_destroy (&s->io); -} - static int es1370_init (PCIBus *bus) { pci_create_simple (bus, -1, "ES1370"); @@ -1063,7 +1054,6 @@ static void es1370_class_init (ObjectClass *klass, void *data) PCIDeviceClass *k = PCI_DEVICE_CLASS (klass); k->init = es1370_initfn; - k->exit = es1370_exitfn; k->vendor_id = PCI_VENDOR_ID_ENSONIQ; k->device_id = PCI_DEVICE_ID_ENSONIQ_ES1370; k->class_id = PCI_CLASS_MULTIMEDIA_AUDIO; diff --git a/hw/audio/fmopl.c b/hw/audio/fmopl.c index 290a224edc..adcef2d3b9 100644 --- a/hw/audio/fmopl.c +++ b/hw/audio/fmopl.c @@ -30,7 +30,6 @@ * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ -#define INLINE static inline #define HAS_YM3812 1 #include <stdio.h> @@ -247,7 +246,7 @@ static INT32 feedback2; /* connect for SLOT 2 */ /* --------------------- subroutines --------------------- */ -INLINE int Limit( int val, int max, int min ) { +static inline int Limit( int val, int max, int min ) { if ( val > max ) val = max; else if ( val < min ) @@ -257,7 +256,7 @@ INLINE int Limit( int val, int max, int min ) { } /* status set and IRQ handling */ -INLINE void OPL_STATUS_SET(FM_OPL *OPL,int flag) +static inline void OPL_STATUS_SET(FM_OPL *OPL,int flag) { /* set status flag */ OPL->status |= flag; @@ -273,7 +272,7 @@ INLINE void OPL_STATUS_SET(FM_OPL *OPL,int flag) } /* status reset and IRQ handling */ -INLINE void OPL_STATUS_RESET(FM_OPL *OPL,int flag) +static inline void OPL_STATUS_RESET(FM_OPL *OPL,int flag) { /* reset status flag */ OPL->status &=~flag; @@ -289,7 +288,7 @@ INLINE void OPL_STATUS_RESET(FM_OPL *OPL,int flag) } /* IRQ mask set */ -INLINE void OPL_STATUSMASK_SET(FM_OPL *OPL,int flag) +static inline void OPL_STATUSMASK_SET(FM_OPL *OPL,int flag) { OPL->statusmask = flag; /* IRQ handling check */ @@ -298,7 +297,7 @@ INLINE void OPL_STATUSMASK_SET(FM_OPL *OPL,int flag) } /* ----- key on ----- */ -INLINE void OPL_KEYON(OPL_SLOT *SLOT) +static inline void OPL_KEYON(OPL_SLOT *SLOT) { /* sin wave restart */ SLOT->Cnt = 0; @@ -309,7 +308,7 @@ INLINE void OPL_KEYON(OPL_SLOT *SLOT) SLOT->eve = EG_AED; } /* ----- key off ----- */ -INLINE void OPL_KEYOFF(OPL_SLOT *SLOT) +static inline void OPL_KEYOFF(OPL_SLOT *SLOT) { if( SLOT->evm > ENV_MOD_RR) { @@ -325,7 +324,7 @@ INLINE void OPL_KEYOFF(OPL_SLOT *SLOT) /* ---------- calcrate Envelope Generator & Phase Generator ---------- */ /* return : envelope output */ -INLINE UINT32 OPL_CALC_SLOT( OPL_SLOT *SLOT ) +static inline UINT32 OPL_CALC_SLOT( OPL_SLOT *SLOT ) { /* calcrate envelope generator */ if( (SLOT->evc+=SLOT->evs) >= SLOT->eve ) @@ -371,7 +370,7 @@ static void set_algorithm( OPL_CH *CH) } /* ---------- frequency counter for operater update ---------- */ -INLINE void CALC_FCSLOT(OPL_CH *CH,OPL_SLOT *SLOT) +static inline void CALC_FCSLOT(OPL_CH *CH,OPL_SLOT *SLOT) { int ksr; @@ -391,7 +390,7 @@ INLINE void CALC_FCSLOT(OPL_CH *CH,OPL_SLOT *SLOT) } /* set multi,am,vib,EG-TYP,KSR,mul */ -INLINE void set_mul(FM_OPL *OPL,int slot,int v) +static inline void set_mul(FM_OPL *OPL,int slot,int v) { OPL_CH *CH = &OPL->P_CH[slot/2]; OPL_SLOT *SLOT = &CH->SLOT[slot&1]; @@ -405,7 +404,7 @@ INLINE void set_mul(FM_OPL *OPL,int slot,int v) } /* set ksl & tl */ -INLINE void set_ksl_tl(FM_OPL *OPL,int slot,int v) +static inline void set_ksl_tl(FM_OPL *OPL,int slot,int v) { OPL_CH *CH = &OPL->P_CH[slot/2]; OPL_SLOT *SLOT = &CH->SLOT[slot&1]; @@ -421,7 +420,7 @@ INLINE void set_ksl_tl(FM_OPL *OPL,int slot,int v) } /* set attack rate & decay rate */ -INLINE void set_ar_dr(FM_OPL *OPL,int slot,int v) +static inline void set_ar_dr(FM_OPL *OPL,int slot,int v) { OPL_CH *CH = &OPL->P_CH[slot/2]; OPL_SLOT *SLOT = &CH->SLOT[slot&1]; @@ -438,7 +437,7 @@ INLINE void set_ar_dr(FM_OPL *OPL,int slot,int v) } /* set sustain level & release rate */ -INLINE void set_sl_rr(FM_OPL *OPL,int slot,int v) +static inline void set_sl_rr(FM_OPL *OPL,int slot,int v) { OPL_CH *CH = &OPL->P_CH[slot/2]; OPL_SLOT *SLOT = &CH->SLOT[slot&1]; @@ -455,7 +454,7 @@ INLINE void set_sl_rr(FM_OPL *OPL,int slot,int v) /* operator output calcrator */ #define OP_OUT(slot,env,con) slot->wavetable[((slot->Cnt+con)/(0x1000000/SIN_ENT))&(SIN_ENT-1)][env] /* ---------- calcrate one of channel ---------- */ -INLINE void OPL_CALC_CH( OPL_CH *CH ) +static inline void OPL_CALC_CH( OPL_CH *CH ) { UINT32 env_out; OPL_SLOT *SLOT; @@ -500,7 +499,7 @@ INLINE void OPL_CALC_CH( OPL_CH *CH ) /* ---------- calcrate rhythm block ---------- */ #define WHITE_NOISE_db 6.0 -INLINE void OPL_CALC_RH( OPL_CH *CH ) +static inline void OPL_CALC_RH( OPL_CH *CH ) { UINT32 env_tam,env_sd,env_top,env_hh; int whitenoise = (rand()&1)*(WHITE_NOISE_db/EG_STEP); @@ -716,7 +715,7 @@ static void OPLCloseTable( void ) } /* CSM Key Control */ -INLINE void CSMKeyControll(OPL_CH *CH) +static inline void CSMKeyControll(OPL_CH *CH) { OPL_SLOT *slot1 = &CH->SLOT[SLOT1]; OPL_SLOT *slot2 = &CH->SLOT[SLOT2]; diff --git a/hw/audio/gus.c b/hw/audio/gus.c index e29a5715db..4a43ce7adf 100644 --- a/hw/audio/gus.c +++ b/hw/audio/gus.c @@ -212,7 +212,7 @@ static int GUS_read_DMA (void *opaque, int nchan, int dma_pos, int dma_len) pos += copied; } - if (0 == ((mode >> 4) & 1)) { + if (((mode >> 4) & 1) == 0) { DMA_release_DREQ (s->emu.gusdma); } return dma_len; @@ -222,8 +222,7 @@ static const VMStateDescription vmstate_gus = { .name = "gus", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32 (pos, GUSState), VMSTATE_INT32 (left, GUSState), VMSTATE_INT32 (shift, GUSState), diff --git a/hw/audio/hda-codec.c b/hw/audio/hda-codec.c index a67ca91ca7..3c03ff5668 100644 --- a/hw/audio/hda-codec.c +++ b/hw/audio/hda-codec.c @@ -261,6 +261,9 @@ static void hda_audio_set_amp(HDAAudioStream *st) left = left * 255 / QEMU_HDA_AMP_STEPS; right = right * 255 / QEMU_HDA_AMP_STEPS; + if (!st->state->mixer) { + return; + } if (st->output) { AUD_set_volume_out(st->voice.out, muted, left, right); } else { @@ -486,8 +489,9 @@ static int hda_audio_init(HDACodecDevice *hda, const struct desc_codec *desc) for (i = 0; i < a->desc->nnodes; i++) { node = a->desc->nodes + i; param = hda_codec_find_param(node, AC_PAR_AUDIO_WIDGET_CAP); - if (NULL == param) + if (param == NULL) { continue; + } type = (param->val & AC_WCAP_TYPE) >> AC_WCAP_TYPE_SHIFT; switch (type) { case AC_WID_AUD_OUT: @@ -580,7 +584,7 @@ static void hda_audio_reset(DeviceState *dev) static const VMStateDescription vmstate_hda_audio_stream = { .name = "hda-audio-stream", .version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(stream, HDAAudioStream), VMSTATE_UINT32(channel, HDAAudioStream), VMSTATE_UINT32(format, HDAAudioStream), @@ -598,7 +602,7 @@ static const VMStateDescription vmstate_hda_audio = { .name = "hda-audio", .version_id = 2, .post_load = hda_audio_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(st, HDAAudioState, 4, 0, vmstate_hda_audio_stream, HDAAudioStream), diff --git a/hw/audio/intel-hda.c b/hw/audio/intel-hda.c index 9e075c0137..2885231a6d 100644 --- a/hw/audio/intel-hda.c +++ b/hw/audio/intel-hda.c @@ -187,6 +187,7 @@ struct IntelHDAState { /* properties */ uint32_t debug; uint32_t msi; + bool old_msi_addr; }; #define TYPE_INTEL_HDA_GENERIC "intel-hda-generic" @@ -245,7 +246,7 @@ static void intel_hda_update_int_sts(IntelHDAState *d) /* update global status */ if (sts & d->int_ctl) { - sts |= (1 << 31); + sts |= (1U << 31); } d->int_sts = sts; @@ -257,7 +258,7 @@ static void intel_hda_update_irq(IntelHDAState *d) int level; intel_hda_update_int_sts(d); - if (d->int_sts & (1 << 31) && d->int_ctl & (1 << 31)) { + if (d->int_sts & (1U << 31) && d->int_ctl & (1U << 31)) { level = 1; } else { level = 0; @@ -1141,7 +1142,7 @@ static int intel_hda_init(PCIDevice *pci) "intel-hda", 0x4000); pci_register_bar(&d->pci, 0, 0, &d->mmio); if (d->msi) { - msi_init(&d->pci, 0x50, 1, true, false); + msi_init(&d->pci, d->old_msi_addr ? 0x50 : 0x60, 1, true, false); } hda_codec_bus_init(DEVICE(pci), &d->codecs, sizeof(d->codecs), @@ -1155,7 +1156,6 @@ static void intel_hda_exit(PCIDevice *pci) IntelHDAState *d = INTEL_HDA(pci); msi_uninit(&d->pci); - memory_region_destroy(&d->mmio); } static int intel_hda_post_load(void *opaque, int version) @@ -1176,7 +1176,7 @@ static int intel_hda_post_load(void *opaque, int version) static const VMStateDescription vmstate_intel_hda_stream = { .name = "intel-hda-stream", .version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(ctl, IntelHDAStream), VMSTATE_UINT32(lpib, IntelHDAStream), VMSTATE_UINT32(cbl, IntelHDAStream), @@ -1192,7 +1192,7 @@ static const VMStateDescription vmstate_intel_hda = { .name = "intel-hda", .version_id = 1, .post_load = intel_hda_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pci, IntelHDAState), /* registers */ @@ -1236,6 +1236,7 @@ static const VMStateDescription vmstate_intel_hda = { static Property intel_hda_properties[] = { DEFINE_PROP_UINT32("debug", IntelHDAState, debug, 0), DEFINE_PROP_UINT32("msi", IntelHDAState, msi, 1), + DEFINE_PROP_BOOL("old_msi_addr", IntelHDAState, old_msi_addr, false), DEFINE_PROP_END_OF_LIST(), }; diff --git a/hw/audio/lm4549.c b/hw/audio/lm4549.c index d75f7ec21f..380ef603bd 100644 --- a/hw/audio/lm4549.c +++ b/hw/audio/lm4549.c @@ -324,9 +324,8 @@ const VMStateDescription vmstate_lm4549_state = { .name = "lm4549_state", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .post_load = &lm4549_post_load, - .fields = (VMStateField[]) { + .post_load = lm4549_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT32(voice_is_active, lm4549_state), VMSTATE_UINT16_ARRAY(regfile, lm4549_state, 128), VMSTATE_UINT16_ARRAY(buffer, lm4549_state, LM4549_BUFFER_SIZE), diff --git a/hw/audio/marvell_88w8618.c b/hw/audio/marvell_88w8618.c index cdce238f55..86992677e3 100644 --- a/hw/audio/marvell_88w8618.c +++ b/hw/audio/marvell_88w8618.c @@ -259,7 +259,6 @@ static const VMStateDescription mv88w8618_audio_vmsd = { .name = "mv88w8618_audio", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(playback_mode, mv88w8618_audio_state), VMSTATE_UINT32(status, mv88w8618_audio_state), diff --git a/hw/audio/milkymist-ac97.c b/hw/audio/milkymist-ac97.c index 9c0f7a092d..28f55e8535 100644 --- a/hw/audio/milkymist-ac97.c +++ b/hw/audio/milkymist-ac97.c @@ -316,9 +316,8 @@ static const VMStateDescription vmstate_milkymist_ac97 = { .name = "milkymist-ac97", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = ac97_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistAC97State, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/audio/pl041.c b/hw/audio/pl041.c index ed82be54e8..19982f2477 100644 --- a/hw/audio/pl041.c +++ b/hw/audio/pl041.c @@ -561,8 +561,7 @@ static const VMStateDescription vmstate_pl041_regfile = { .name = "pl041_regfile", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { #define REGISTER(name, offset) VMSTATE_UINT32(name, pl041_regfile), #include "pl041.hx" #undef REGISTER @@ -574,8 +573,7 @@ static const VMStateDescription vmstate_pl041_fifo = { .name = "pl041_fifo", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(level, pl041_fifo), VMSTATE_UINT32_ARRAY(data, pl041_fifo, MAX_FIFO_DEPTH), VMSTATE_END_OF_LIST() @@ -586,8 +584,7 @@ static const VMStateDescription vmstate_pl041_channel = { .name = "pl041_channel", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(tx_fifo, pl041_channel, 0, vmstate_pl041_fifo, pl041_fifo), VMSTATE_UINT8(tx_enabled, pl041_channel), diff --git a/hw/audio/sb16.c b/hw/audio/sb16.c index bb24e00f2c..bda26d0123 100644 --- a/hw/audio/sb16.c +++ b/hw/audio/sb16.c @@ -928,7 +928,7 @@ static IO_WRITE_PROTO (dsp_write) /* if (s->highspeed) */ /* break; */ - if (0 == s->needed_bytes) { + if (s->needed_bytes == 0) { command (s, val); #if 0 if (0 == s->needed_bytes) { @@ -1212,7 +1212,7 @@ static int SB_read_DMA (void *opaque, int nchan, int dma_pos, int dma_len) #endif if (till <= copy) { - if (0 == s->dma_auto) { + if (s->dma_auto == 0) { copy = till; } } @@ -1224,7 +1224,7 @@ static int SB_read_DMA (void *opaque, int nchan, int dma_pos, int dma_len) if (s->left_till_irq <= 0) { s->mixer_regs[0x82] |= (nchan & 4) ? 2 : 1; qemu_irq_raise (s->pic); - if (0 == s->dma_auto) { + if (s->dma_auto == 0) { control (s, 0); speaker (s, 0); } @@ -1289,9 +1289,8 @@ static const VMStateDescription vmstate_sb16 = { .name = "sb16", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = sb16_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32 (irq, SB16State), VMSTATE_UINT32 (dma, SB16State), VMSTATE_UINT32 (hdma, SB16State), diff --git a/hw/audio/wm8750.c b/hw/audio/wm8750.c index c18f2457a1..b50b331402 100644 --- a/hw/audio/wm8750.c +++ b/hw/audio/wm8750.c @@ -583,10 +583,9 @@ static const VMStateDescription vmstate_wm8750 = { .name = CODEC, .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = wm8750_pre_save, .post_load = wm8750_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8_ARRAY(i2c_data, WM8750State, 2), VMSTATE_INT32(i2c_len, WM8750State), VMSTATE_INT32(enable, WM8750State), diff --git a/hw/block/Makefile.objs b/hw/block/Makefile.objs index bf46f03b7e..d4c3ab758d 100644 --- a/hw/block/Makefile.objs +++ b/hw/block/Makefile.objs @@ -12,4 +12,4 @@ common-obj-$(CONFIG_NVME_PCI) += nvme.o obj-$(CONFIG_SH4) += tc58128.o obj-$(CONFIG_VIRTIO) += virtio-blk.o -obj-$(CONFIG_VIRTIO_BLK_DATA_PLANE) += dataplane/ +obj-$(CONFIG_VIRTIO) += dataplane/ diff --git a/hw/block/block.c b/hw/block/block.c index 33dd3f33b6..a625773d44 100644 --- a/hw/block/block.c +++ b/hw/block/block.c @@ -8,6 +8,7 @@ */ #include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/block/block.h" #include "qemu/error-report.h" @@ -17,28 +18,33 @@ void blkconf_serial(BlockConf *conf, char **serial) if (!*serial) { /* try to fall back to value set with legacy -drive serial=... */ - dinfo = drive_get_by_blockdev(conf->bs); - *serial = g_strdup(dinfo->serial); + dinfo = blk_legacy_dinfo(conf->blk); + if (dinfo) { + *serial = g_strdup(dinfo->serial); + } } } -int blkconf_geometry(BlockConf *conf, int *ptrans, - unsigned cyls_max, unsigned heads_max, unsigned secs_max) +void blkconf_geometry(BlockConf *conf, int *ptrans, + unsigned cyls_max, unsigned heads_max, unsigned secs_max, + Error **errp) { DriveInfo *dinfo; if (!conf->cyls && !conf->heads && !conf->secs) { /* try to fall back to value set with legacy -drive cyls=... */ - dinfo = drive_get_by_blockdev(conf->bs); - conf->cyls = dinfo->cyls; - conf->heads = dinfo->heads; - conf->secs = dinfo->secs; - if (ptrans) { - *ptrans = dinfo->trans; + dinfo = blk_legacy_dinfo(conf->blk); + if (dinfo) { + conf->cyls = dinfo->cyls; + conf->heads = dinfo->heads; + conf->secs = dinfo->secs; + if (ptrans) { + *ptrans = dinfo->trans; + } } } if (!conf->cyls && !conf->heads && !conf->secs) { - hd_geometry_guess(conf->bs, + hd_geometry_guess(conf->blk, &conf->cyls, &conf->heads, &conf->secs, ptrans); } else if (ptrans && *ptrans == BIOS_ATA_TRANSLATION_AUTO) { @@ -46,17 +52,16 @@ int blkconf_geometry(BlockConf *conf, int *ptrans, } if (conf->cyls || conf->heads || conf->secs) { if (conf->cyls < 1 || conf->cyls > cyls_max) { - error_report("cyls must be between 1 and %u", cyls_max); - return -1; + error_setg(errp, "cyls must be between 1 and %u", cyls_max); + return; } if (conf->heads < 1 || conf->heads > heads_max) { - error_report("heads must be between 1 and %u", heads_max); - return -1; + error_setg(errp, "heads must be between 1 and %u", heads_max); + return; } if (conf->secs < 1 || conf->secs > secs_max) { - error_report("secs must be between 1 and %u", secs_max); - return -1; + error_setg(errp, "secs must be between 1 and %u", secs_max); + return; } } - return 0; } diff --git a/hw/block/dataplane/Makefile.objs b/hw/block/dataplane/Makefile.objs index 9da2eb82ba..e786f66421 100644 --- a/hw/block/dataplane/Makefile.objs +++ b/hw/block/dataplane/Makefile.objs @@ -1 +1 @@ -obj-y += ioq.o virtio-blk.o +obj-y += virtio-blk.o diff --git a/hw/block/dataplane/ioq.c b/hw/block/dataplane/ioq.c deleted file mode 100644 index f709f87ed6..0000000000 --- a/hw/block/dataplane/ioq.c +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Linux AIO request queue - * - * Copyright 2012 IBM, Corp. - * Copyright 2012 Red Hat, Inc. and/or its affiliates - * - * Authors: - * Stefan Hajnoczi <stefanha@redhat.com> - * - * This work is licensed under the terms of the GNU GPL, version 2 or later. - * See the COPYING file in the top-level directory. - * - */ - -#include "ioq.h" - -void ioq_init(IOQueue *ioq, int fd, unsigned int max_reqs) -{ - int rc; - - ioq->fd = fd; - ioq->max_reqs = max_reqs; - - memset(&ioq->io_ctx, 0, sizeof ioq->io_ctx); - rc = io_setup(max_reqs, &ioq->io_ctx); - if (rc != 0) { - fprintf(stderr, "ioq io_setup failed %d\n", rc); - exit(1); - } - - rc = event_notifier_init(&ioq->io_notifier, 0); - if (rc != 0) { - fprintf(stderr, "ioq io event notifier creation failed %d\n", rc); - exit(1); - } - - ioq->freelist = g_malloc0(sizeof ioq->freelist[0] * max_reqs); - ioq->freelist_idx = 0; - - ioq->queue = g_malloc0(sizeof ioq->queue[0] * max_reqs); - ioq->queue_idx = 0; -} - -void ioq_cleanup(IOQueue *ioq) -{ - g_free(ioq->freelist); - g_free(ioq->queue); - - event_notifier_cleanup(&ioq->io_notifier); - io_destroy(ioq->io_ctx); -} - -EventNotifier *ioq_get_notifier(IOQueue *ioq) -{ - return &ioq->io_notifier; -} - -struct iocb *ioq_get_iocb(IOQueue *ioq) -{ - /* Underflow cannot happen since ioq is sized for max_reqs */ - assert(ioq->freelist_idx != 0); - - struct iocb *iocb = ioq->freelist[--ioq->freelist_idx]; - ioq->queue[ioq->queue_idx++] = iocb; - return iocb; -} - -void ioq_put_iocb(IOQueue *ioq, struct iocb *iocb) -{ - /* Overflow cannot happen since ioq is sized for max_reqs */ - assert(ioq->freelist_idx != ioq->max_reqs); - - ioq->freelist[ioq->freelist_idx++] = iocb; -} - -struct iocb *ioq_rdwr(IOQueue *ioq, bool read, struct iovec *iov, - unsigned int count, long long offset) -{ - struct iocb *iocb = ioq_get_iocb(ioq); - - if (read) { - io_prep_preadv(iocb, ioq->fd, iov, count, offset); - } else { - io_prep_pwritev(iocb, ioq->fd, iov, count, offset); - } - io_set_eventfd(iocb, event_notifier_get_fd(&ioq->io_notifier)); - return iocb; -} - -int ioq_submit(IOQueue *ioq) -{ - int rc = io_submit(ioq->io_ctx, ioq->queue_idx, ioq->queue); - ioq->queue_idx = 0; /* reset */ - return rc; -} - -int ioq_run_completion(IOQueue *ioq, IOQueueCompletion *completion, - void *opaque) -{ - struct io_event events[ioq->max_reqs]; - int nevents, i; - - do { - nevents = io_getevents(ioq->io_ctx, 0, ioq->max_reqs, events, NULL); - } while (nevents < 0 && errno == EINTR); - if (nevents < 0) { - return nevents; - } - - for (i = 0; i < nevents; i++) { - ssize_t ret = ((uint64_t)events[i].res2 << 32) | events[i].res; - - completion(events[i].obj, ret, opaque); - ioq_put_iocb(ioq, events[i].obj); - } - return nevents; -} diff --git a/hw/block/dataplane/ioq.h b/hw/block/dataplane/ioq.h deleted file mode 100644 index b49b5de7f4..0000000000 --- a/hw/block/dataplane/ioq.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Linux AIO request queue - * - * Copyright 2012 IBM, Corp. - * Copyright 2012 Red Hat, Inc. and/or its affiliates - * - * Authors: - * Stefan Hajnoczi <stefanha@redhat.com> - * - * This work is licensed under the terms of the GNU GPL, version 2 or later. - * See the COPYING file in the top-level directory. - * - */ - -#ifndef IOQ_H -#define IOQ_H - -#include <libaio.h> -#include "qemu/event_notifier.h" - -typedef struct { - int fd; /* file descriptor */ - unsigned int max_reqs; /* max length of freelist and queue */ - - io_context_t io_ctx; /* Linux AIO context */ - EventNotifier io_notifier; /* Linux AIO eventfd */ - - /* Requests can complete in any order so a free list is necessary to manage - * available iocbs. - */ - struct iocb **freelist; /* free iocbs */ - unsigned int freelist_idx; - - /* Multiple requests are queued up before submitting them all in one go */ - struct iocb **queue; /* queued iocbs */ - unsigned int queue_idx; -} IOQueue; - -void ioq_init(IOQueue *ioq, int fd, unsigned int max_reqs); -void ioq_cleanup(IOQueue *ioq); -EventNotifier *ioq_get_notifier(IOQueue *ioq); -struct iocb *ioq_get_iocb(IOQueue *ioq); -void ioq_put_iocb(IOQueue *ioq, struct iocb *iocb); -struct iocb *ioq_rdwr(IOQueue *ioq, bool read, struct iovec *iov, - unsigned int count, long long offset); -int ioq_submit(IOQueue *ioq); - -static inline unsigned int ioq_num_queued(IOQueue *ioq) -{ - return ioq->queue_idx; -} - -typedef void IOQueueCompletion(struct iocb *iocb, ssize_t ret, void *opaque); -int ioq_run_completion(IOQueue *ioq, IOQueueCompletion *completion, - void *opaque); - -#endif /* IOQ_H */ diff --git a/hw/block/dataplane/virtio-blk.c b/hw/block/dataplane/virtio-blk.c index 70b8a5ab75..1222a37f4f 100644 --- a/hw/block/dataplane/virtio-blk.c +++ b/hw/block/dataplane/virtio-blk.c @@ -17,41 +17,25 @@ #include "qemu/thread.h" #include "qemu/error-report.h" #include "hw/virtio/dataplane/vring.h" -#include "ioq.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/virtio/virtio-blk.h" #include "virtio-blk.h" #include "block/aio.h" #include "hw/virtio/virtio-bus.h" #include "qom/object_interfaces.h" -enum { - SEG_MAX = 126, /* maximum number of I/O segments */ - VRING_MAX = SEG_MAX + 2, /* maximum number of vring descriptors */ - REQ_MAX = VRING_MAX, /* maximum number of requests in the vring, - * is VRING_MAX / 2 with traditional and - * VRING_MAX with indirect descriptors */ -}; - -typedef struct { - struct iocb iocb; /* Linux AIO control block */ - QEMUIOVector *inhdr; /* iovecs for virtio_blk_inhdr */ - VirtQueueElement *elem; /* saved data from the virtqueue */ - struct iovec *bounce_iov; /* used if guest buffers are unaligned */ - QEMUIOVector *read_qiov; /* for read completion /w bounce buffer */ -} VirtIOBlockRequest; - struct VirtIOBlockDataPlane { bool started; bool starting; bool stopping; + bool disabled; - VirtIOBlkConf *blk; - int fd; /* image file descriptor */ + VirtIOBlkConf *conf; VirtIODevice *vdev; Vring vring; /* virtqueue vring */ EventNotifier *guest_notifier; /* irq */ + QEMUBH *bh; /* bh for guest notification */ /* Note that these EventNotifiers are assigned by value. This is * fine as long as you do not call event_notifier_cleanup on them @@ -61,15 +45,12 @@ struct VirtIOBlockDataPlane { IOThread *iothread; IOThread internal_iothread_obj; AioContext *ctx; - EventNotifier io_notifier; /* Linux AIO completion */ EventNotifier host_notifier; /* doorbell */ - IOQueue ioqueue; /* Linux AIO queue (should really be per - IOThread) */ - VirtIOBlockRequest requests[REQ_MAX]; /* pool of requests, managed by the - queue */ - - unsigned int num_reqs; + /* Operation blocker on BDS */ + Error *blocker; + void (*saved_complete_request)(struct VirtIOBlockReq *req, + unsigned char status); }; /* Raise an interrupt to signal guest, if necessary */ @@ -82,220 +63,65 @@ static void notify_guest(VirtIOBlockDataPlane *s) event_notifier_set(s->guest_notifier); } -static void complete_request(struct iocb *iocb, ssize_t ret, void *opaque) +static void notify_guest_bh(void *opaque) { VirtIOBlockDataPlane *s = opaque; - VirtIOBlockRequest *req = container_of(iocb, VirtIOBlockRequest, iocb); - struct virtio_blk_inhdr hdr; - int len; - - if (likely(ret >= 0)) { - hdr.status = VIRTIO_BLK_S_OK; - len = ret; - } else { - hdr.status = VIRTIO_BLK_S_IOERR; - len = 0; - } - - trace_virtio_blk_data_plane_complete_request(s, req->elem->index, ret); - - if (req->read_qiov) { - assert(req->bounce_iov); - qemu_iovec_from_buf(req->read_qiov, 0, req->bounce_iov->iov_base, len); - qemu_iovec_destroy(req->read_qiov); - g_slice_free(QEMUIOVector, req->read_qiov); - } - if (req->bounce_iov) { - qemu_vfree(req->bounce_iov->iov_base); - g_slice_free(struct iovec, req->bounce_iov); - } - - qemu_iovec_from_buf(req->inhdr, 0, &hdr, sizeof(hdr)); - qemu_iovec_destroy(req->inhdr); - g_slice_free(QEMUIOVector, req->inhdr); - - /* According to the virtio specification len should be the number of bytes - * written to, but for virtio-blk it seems to be the number of bytes - * transferred plus the status bytes. - */ - vring_push(&s->vring, req->elem, len + sizeof(hdr)); - req->elem = NULL; - s->num_reqs--; -} - -static void complete_request_early(VirtIOBlockDataPlane *s, VirtQueueElement *elem, - QEMUIOVector *inhdr, unsigned char status) -{ - struct virtio_blk_inhdr hdr = { - .status = status, - }; - - qemu_iovec_from_buf(inhdr, 0, &hdr, sizeof(hdr)); - qemu_iovec_destroy(inhdr); - g_slice_free(QEMUIOVector, inhdr); - - vring_push(&s->vring, elem, sizeof(hdr)); notify_guest(s); } -/* Get disk serial number */ -static void do_get_id_cmd(VirtIOBlockDataPlane *s, - struct iovec *iov, unsigned int iov_cnt, - VirtQueueElement *elem, QEMUIOVector *inhdr) -{ - char id[VIRTIO_BLK_ID_BYTES]; - - /* Serial number not NUL-terminated when longer than buffer */ - strncpy(id, s->blk->serial ? s->blk->serial : "", sizeof(id)); - iov_from_buf(iov, iov_cnt, 0, id, sizeof(id)); - complete_request_early(s, elem, inhdr, VIRTIO_BLK_S_OK); -} - -static int do_rdwr_cmd(VirtIOBlockDataPlane *s, bool read, - struct iovec *iov, unsigned iov_cnt, - long long offset, VirtQueueElement *elem, - QEMUIOVector *inhdr) -{ - struct iocb *iocb; - QEMUIOVector qiov; - struct iovec *bounce_iov = NULL; - QEMUIOVector *read_qiov = NULL; - - qemu_iovec_init_external(&qiov, iov, iov_cnt); - if (!bdrv_qiov_is_aligned(s->blk->conf.bs, &qiov)) { - void *bounce_buffer = qemu_blockalign(s->blk->conf.bs, qiov.size); - - if (read) { - /* Need to copy back from bounce buffer on completion */ - read_qiov = g_slice_new(QEMUIOVector); - qemu_iovec_init(read_qiov, iov_cnt); - qemu_iovec_concat_iov(read_qiov, iov, iov_cnt, 0, qiov.size); - } else { - qemu_iovec_to_buf(&qiov, 0, bounce_buffer, qiov.size); - } - - /* Redirect I/O to aligned bounce buffer */ - bounce_iov = g_slice_new(struct iovec); - bounce_iov->iov_base = bounce_buffer; - bounce_iov->iov_len = qiov.size; - iov = bounce_iov; - iov_cnt = 1; - } - - iocb = ioq_rdwr(&s->ioqueue, read, iov, iov_cnt, offset); - - /* Fill in virtio block metadata needed for completion */ - VirtIOBlockRequest *req = container_of(iocb, VirtIOBlockRequest, iocb); - req->elem = elem; - req->inhdr = inhdr; - req->bounce_iov = bounce_iov; - req->read_qiov = read_qiov; - return 0; -} - -static int process_request(IOQueue *ioq, VirtQueueElement *elem) +static void complete_request_vring(VirtIOBlockReq *req, unsigned char status) { - VirtIOBlockDataPlane *s = container_of(ioq, VirtIOBlockDataPlane, ioqueue); - struct iovec *iov = elem->out_sg; - struct iovec *in_iov = elem->in_sg; - unsigned out_num = elem->out_num; - unsigned in_num = elem->in_num; - struct virtio_blk_outhdr outhdr; - QEMUIOVector *inhdr; - size_t in_size; - - /* Copy in outhdr */ - if (unlikely(iov_to_buf(iov, out_num, 0, &outhdr, - sizeof(outhdr)) != sizeof(outhdr))) { - error_report("virtio-blk request outhdr too short"); - return -EFAULT; - } - iov_discard_front(&iov, &out_num, sizeof(outhdr)); - - /* Grab inhdr for later */ - in_size = iov_size(in_iov, in_num); - if (in_size < sizeof(struct virtio_blk_inhdr)) { - error_report("virtio_blk request inhdr too short"); - return -EFAULT; - } - inhdr = g_slice_new(QEMUIOVector); - qemu_iovec_init(inhdr, 1); - qemu_iovec_concat_iov(inhdr, in_iov, in_num, - in_size - sizeof(struct virtio_blk_inhdr), - sizeof(struct virtio_blk_inhdr)); - iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr)); - - /* TODO Linux sets the barrier bit even when not advertised! */ - outhdr.type &= ~VIRTIO_BLK_T_BARRIER; - - switch (outhdr.type) { - case VIRTIO_BLK_T_IN: - do_rdwr_cmd(s, true, in_iov, in_num, outhdr.sector * 512, elem, inhdr); - return 0; - - case VIRTIO_BLK_T_OUT: - do_rdwr_cmd(s, false, iov, out_num, outhdr.sector * 512, elem, inhdr); - return 0; - - case VIRTIO_BLK_T_SCSI_CMD: - /* TODO support SCSI commands */ - complete_request_early(s, elem, inhdr, VIRTIO_BLK_S_UNSUPP); - return 0; - - case VIRTIO_BLK_T_FLUSH: - /* TODO fdsync not supported by Linux AIO, do it synchronously here! */ - if (qemu_fdatasync(s->fd) < 0) { - complete_request_early(s, elem, inhdr, VIRTIO_BLK_S_IOERR); - } else { - complete_request_early(s, elem, inhdr, VIRTIO_BLK_S_OK); - } - return 0; + VirtIOBlockDataPlane *s = req->dev->dataplane; + stb_p(&req->in->status, status); - case VIRTIO_BLK_T_GET_ID: - do_get_id_cmd(s, in_iov, in_num, elem, inhdr); - return 0; + vring_push(&req->dev->dataplane->vring, &req->elem, + req->qiov.size + sizeof(*req->in)); - default: - error_report("virtio-blk unsupported request type %#x", outhdr.type); - qemu_iovec_destroy(inhdr); - g_slice_free(QEMUIOVector, inhdr); - return -EFAULT; - } + /* Suppress notification to guest by BH and its scheduled + * flag because requests are completed as a batch after io + * plug & unplug is introduced, and the BH can still be + * executed in dataplane aio context even after it is + * stopped, so needn't worry about notification loss with BH. + */ + qemu_bh_schedule(s->bh); } static void handle_notify(EventNotifier *e) { VirtIOBlockDataPlane *s = container_of(e, VirtIOBlockDataPlane, host_notifier); - - VirtQueueElement *elem; - int ret; - unsigned int num_queued; + VirtIOBlock *vblk = VIRTIO_BLK(s->vdev); event_notifier_test_and_clear(&s->host_notifier); + blk_io_plug(s->conf->conf.blk); for (;;) { + MultiReqBuffer mrb = { + .num_writes = 0, + }; + int ret; + /* Disable guest->host notifies to avoid unnecessary vmexits */ vring_disable_notification(s->vdev, &s->vring); for (;;) { - ret = vring_pop(s->vdev, &s->vring, &elem); + VirtIOBlockReq *req = virtio_blk_alloc_request(vblk); + + ret = vring_pop(s->vdev, &s->vring, &req->elem); if (ret < 0) { - assert(elem == NULL); + virtio_blk_free_request(req); break; /* no more requests */ } - trace_virtio_blk_data_plane_process_request(s, elem->out_num, - elem->in_num, elem->index); + trace_virtio_blk_data_plane_process_request(s, req->elem.out_num, + req->elem.in_num, + req->elem.index); - if (process_request(&s->ioqueue, elem) < 0) { - vring_set_broken(&s->vring); - vring_free_element(elem); - ret = -EFAULT; - break; - } + virtio_blk_handle_request(req, &mrb); } + virtio_submit_multiwrite(s->conf->conf.blk, &mrb); + if (likely(ret == -EAGAIN)) { /* vring emptied */ /* Re-enable guest->host notifies and stop processing the vring. * But if the guest has snuck in more descriptors, keep processing. @@ -303,95 +129,54 @@ static void handle_notify(EventNotifier *e) if (vring_enable_notification(s->vdev, &s->vring)) { break; } - } else { /* ret == -ENOBUFS or fatal error, iovecs[] is depleted */ - /* Since there are no iovecs[] left, stop processing for now. Do - * not re-enable guest->host notifies since the I/O completion - * handler knows to check for more vring descriptors anyway. - */ + } else { /* fatal error */ break; } } - - num_queued = ioq_num_queued(&s->ioqueue); - if (num_queued > 0) { - s->num_reqs += num_queued; - - int rc = ioq_submit(&s->ioqueue); - if (unlikely(rc < 0)) { - fprintf(stderr, "ioq_submit failed %d\n", rc); - exit(1); - } - } -} - -static void handle_io(EventNotifier *e) -{ - VirtIOBlockDataPlane *s = container_of(e, VirtIOBlockDataPlane, - io_notifier); - - event_notifier_test_and_clear(&s->io_notifier); - if (ioq_run_completion(&s->ioqueue, complete_request, s) > 0) { - notify_guest(s); - } - - /* If there were more requests than iovecs, the vring will not be empty yet - * so check again. There should now be enough resources to process more - * requests. - */ - if (unlikely(vring_more_avail(&s->vring))) { - handle_notify(&s->host_notifier); - } + blk_io_unplug(s->conf->conf.blk); } /* Context: QEMU global mutex held */ -void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *blk, +void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *conf, VirtIOBlockDataPlane **dataplane, Error **errp) { VirtIOBlockDataPlane *s; - int fd; + Error *local_err = NULL; + BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev))); + VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); *dataplane = NULL; - if (!blk->data_plane) { + if (!conf->data_plane && !conf->iothread) { return; } - if (blk->scsi) { + /* Don't try if transport does not support notifiers. */ + if (!k->set_guest_notifiers || !k->set_host_notifier) { error_setg(errp, - "device is incompatible with x-data-plane, use scsi=off"); - return; - } - - if (blk->config_wce) { - error_setg(errp, "device is incompatible with x-data-plane, " - "use config-wce=off"); + "device is incompatible with x-data-plane " + "(transport does not support notifiers)"); return; } /* If dataplane is (re-)enabled while the guest is running there could be * block jobs that can conflict. */ - if (bdrv_in_use(blk->conf.bs)) { - error_setg(errp, - "cannot start dataplane thread while device is in use"); - return; - } - - fd = raw_get_aio_fd(blk->conf.bs); - if (fd < 0) { - error_setg(errp, "drive is incompatible with x-data-plane, " - "use format=raw,cache=none,aio=native"); + if (blk_op_is_blocked(conf->conf.blk, BLOCK_OP_TYPE_DATAPLANE, + &local_err)) { + error_setg(errp, "cannot start dataplane thread: %s", + error_get_pretty(local_err)); + error_free(local_err); return; } s = g_new0(VirtIOBlockDataPlane, 1); s->vdev = vdev; - s->fd = fd; - s->blk = blk; + s->conf = conf; - if (blk->iothread) { - s->iothread = blk->iothread; + if (conf->iothread) { + s->iothread = conf->iothread; object_ref(OBJECT(s->iothread)); } else { /* Create per-device IOThread if none specified. This is for @@ -405,9 +190,17 @@ void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *blk, s->iothread = &s->internal_iothread_obj; } s->ctx = iothread_get_aio_context(s->iothread); - - /* Prevent block operations that conflict with data plane thread */ - bdrv_set_in_use(blk->conf.bs, 1); + s->bh = aio_bh_new(s->ctx, notify_guest_bh, s); + + error_setg(&s->blocker, "block device is in use by data plane"); + blk_op_block_all(conf->conf.blk, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_RESIZE, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_DRIVE_DEL, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_BACKUP_SOURCE, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_COMMIT, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_MIRROR, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_STREAM, s->blocker); + blk_op_unblock(conf->conf.blk, BLOCK_OP_TYPE_REPLACE, s->blocker); *dataplane = s; } @@ -420,8 +213,10 @@ void virtio_blk_data_plane_destroy(VirtIOBlockDataPlane *s) } virtio_blk_data_plane_stop(s); - bdrv_set_in_use(s->blk->conf.bs, 0); + blk_op_unblock_all(s->conf->conf.blk, s->blocker); + error_free(s->blocker); object_unref(OBJECT(s->iothread)); + qemu_bh_delete(s->bh); g_free(s); } @@ -430,10 +225,11 @@ void virtio_blk_data_plane_start(VirtIOBlockDataPlane *s) { BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s->vdev))); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOBlock *vblk = VIRTIO_BLK(s->vdev); VirtQueue *vq; - int i; + int r; - if (s->started) { + if (s->started || s->disabled) { return; } @@ -445,44 +241,51 @@ void virtio_blk_data_plane_start(VirtIOBlockDataPlane *s) vq = virtio_get_queue(s->vdev, 0); if (!vring_setup(&s->vring, s->vdev, 0)) { - s->starting = false; - return; + goto fail_vring; } /* Set up guest notifier (irq) */ - if (k->set_guest_notifiers(qbus->parent, 1, true) != 0) { - fprintf(stderr, "virtio-blk failed to set guest notifier, " - "ensure -enable-kvm is set\n"); - exit(1); + r = k->set_guest_notifiers(qbus->parent, 1, true); + if (r != 0) { + fprintf(stderr, "virtio-blk failed to set guest notifier (%d), " + "ensure -enable-kvm is set\n", r); + goto fail_guest_notifiers; } s->guest_notifier = virtio_queue_get_guest_notifier(vq); /* Set up virtqueue notify */ - if (k->set_host_notifier(qbus->parent, 0, true) != 0) { - fprintf(stderr, "virtio-blk failed to set host notifier\n"); - exit(1); + r = k->set_host_notifier(qbus->parent, 0, true); + if (r != 0) { + fprintf(stderr, "virtio-blk failed to set host notifier (%d)\n", r); + goto fail_host_notifier; } s->host_notifier = *virtio_queue_get_host_notifier(vq); - /* Set up ioqueue */ - ioq_init(&s->ioqueue, s->fd, REQ_MAX); - for (i = 0; i < ARRAY_SIZE(s->requests); i++) { - ioq_put_iocb(&s->ioqueue, &s->requests[i].iocb); - } - s->io_notifier = *ioq_get_notifier(&s->ioqueue); + s->saved_complete_request = vblk->complete_request; + vblk->complete_request = complete_request_vring; s->starting = false; s->started = true; trace_virtio_blk_data_plane_start(s); + blk_set_aio_context(s->conf->conf.blk, s->ctx); + /* Kick right away to begin processing requests already in vring */ event_notifier_set(virtio_queue_get_host_notifier(vq)); /* Get this show started by hooking up our callbacks */ aio_context_acquire(s->ctx); aio_set_event_notifier(s->ctx, &s->host_notifier, handle_notify); - aio_set_event_notifier(s->ctx, &s->io_notifier, handle_io); aio_context_release(s->ctx); + return; + + fail_host_notifier: + k->set_guest_notifiers(qbus->parent, 1, false); + fail_guest_notifiers: + vring_teardown(&s->vring, s->vdev, 0); + s->disabled = true; + fail_vring: + s->starting = false; } /* Context: QEMU global mutex held */ @@ -490,10 +293,19 @@ void virtio_blk_data_plane_stop(VirtIOBlockDataPlane *s) { BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s->vdev))); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOBlock *vblk = VIRTIO_BLK(s->vdev); + + + /* Better luck next time. */ + if (s->disabled) { + s->disabled = false; + return; + } if (!s->started || s->stopping) { return; } s->stopping = true; + vblk->complete_request = s->saved_complete_request; trace_virtio_blk_data_plane_stop(s); aio_context_acquire(s->ctx); @@ -501,13 +313,8 @@ void virtio_blk_data_plane_stop(VirtIOBlockDataPlane *s) /* Stop notifications for new requests from guest */ aio_set_event_notifier(s->ctx, &s->host_notifier, NULL); - /* Complete pending requests */ - while (s->num_reqs > 0) { - aio_poll(s->ctx, true); - } - - /* Stop ioq callbacks (there are no pending requests left) */ - aio_set_event_notifier(s->ctx, &s->io_notifier, NULL); + /* Drain and switch bs back to the QEMU main loop */ + blk_set_aio_context(s->conf->conf.blk, qemu_get_aio_context()); aio_context_release(s->ctx); @@ -516,7 +323,6 @@ void virtio_blk_data_plane_stop(VirtIOBlockDataPlane *s) */ vring_teardown(&s->vring, s->vdev, 0); - ioq_cleanup(&s->ioqueue); k->set_host_notifier(qbus->parent, 0, false); /* Clean up guest notifier (irq) */ diff --git a/hw/block/dataplane/virtio-blk.h b/hw/block/dataplane/virtio-blk.h index 1750c9905b..c88d40e72c 100644 --- a/hw/block/dataplane/virtio-blk.h +++ b/hw/block/dataplane/virtio-blk.h @@ -19,7 +19,7 @@ typedef struct VirtIOBlockDataPlane VirtIOBlockDataPlane; -void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *blk, +void virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *conf, VirtIOBlockDataPlane **dataplane, Error **errp); void virtio_blk_data_plane_destroy(VirtIOBlockDataPlane *s); diff --git a/hw/block/ecc.c b/hw/block/ecc.c index 8c888cc12a..10bb233089 100644 --- a/hw/block/ecc.c +++ b/hw/block/ecc.c @@ -81,8 +81,7 @@ VMStateDescription vmstate_ecc_state = { .name = "ecc-state", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(cp, ECCState), VMSTATE_UINT16_ARRAY(lp, ECCState, 2), VMSTATE_UINT16(count, ECCState), diff --git a/hw/block/fdc.c b/hw/block/fdc.c index 16510077db..739a03ed58 100644 --- a/hw/block/fdc.c +++ b/hw/block/fdc.c @@ -33,6 +33,7 @@ #include "qemu/timer.h" #include "hw/isa/isa.h" #include "hw/sysbus.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "sysemu/sysemu.h" #include "qemu/log.h" @@ -113,7 +114,7 @@ static const FDFormat fd_formats[] = { { FDRIVE_DRV_NONE, -1, -1, 0, 0, }, }; -static void pick_geometry(BlockDriverState *bs, int *nb_heads, +static void pick_geometry(BlockBackend *blk, int *nb_heads, int *max_track, int *last_sect, FDriveType drive_in, FDriveType *drive, FDriveRate *rate) @@ -122,7 +123,7 @@ static void pick_geometry(BlockDriverState *bs, int *nb_heads, uint64_t nb_sectors, size; int i, first_match, match; - bdrv_get_geometry(bs, &nb_sectors); + blk_get_geometry(blk, &nb_sectors); match = -1; first_match = -1; for (i = 0; ; i++) { @@ -175,7 +176,7 @@ typedef enum FDiskFlags { typedef struct FDrive { FDCtrl *fdctrl; - BlockDriverState *bs; + BlockBackend *blk; /* Drive status */ FDriveType drive; uint8_t perpendicular; /* 2.88 MB access mode */ @@ -260,7 +261,7 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect, #endif drv->head = head; if (drv->track != track) { - if (drv->bs != NULL && bdrv_is_inserted(drv->bs)) { + if (drv->blk != NULL && blk_is_inserted(drv->blk)) { drv->media_changed = 0; } ret = 1; @@ -269,7 +270,7 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect, drv->sect = sect; } - if (drv->bs == NULL || !bdrv_is_inserted(drv->bs)) { + if (drv->blk == NULL || !blk_is_inserted(drv->blk)) { ret = 2; } @@ -291,11 +292,11 @@ static void fd_revalidate(FDrive *drv) FDriveRate rate; FLOPPY_DPRINTF("revalidate\n"); - if (drv->bs != NULL) { - ro = bdrv_is_read_only(drv->bs); - pick_geometry(drv->bs, &nb_heads, &max_track, + if (drv->blk != NULL) { + ro = blk_is_read_only(drv->blk); + pick_geometry(drv->blk, &nb_heads, &max_track, &last_sect, drv->drive, &drive, &rate); - if (!bdrv_is_inserted(drv->bs)) { + if (!blk_is_inserted(drv->blk)) { FLOPPY_DPRINTF("No disk in drive\n"); } else { FLOPPY_DPRINTF("Floppy disk (%d h %d t %d s) %s\n", nb_heads, @@ -665,15 +666,14 @@ static bool fdrive_media_changed_needed(void *opaque) { FDrive *drive = opaque; - return (drive->bs != NULL && drive->media_changed != 1); + return (drive->blk != NULL && drive->media_changed != 1); } static const VMStateDescription vmstate_fdrive_media_changed = { .name = "fdrive/media_changed", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(media_changed, FDrive), VMSTATE_END_OF_LIST() } @@ -690,19 +690,41 @@ static const VMStateDescription vmstate_fdrive_media_rate = { .name = "fdrive/media_rate", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(media_rate, FDrive), VMSTATE_END_OF_LIST() } }; +static bool fdrive_perpendicular_needed(void *opaque) +{ + FDrive *drive = opaque; + + return drive->perpendicular != 0; +} + +static const VMStateDescription vmstate_fdrive_perpendicular = { + .name = "fdrive/perpendicular", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT8(perpendicular, FDrive), + VMSTATE_END_OF_LIST() + } +}; + +static int fdrive_post_load(void *opaque, int version_id) +{ + fd_revalidate(opaque); + return 0; +} + static const VMStateDescription vmstate_fdrive = { .name = "fdrive", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .post_load = fdrive_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT8(head, FDrive), VMSTATE_UINT8(track, FDrive), VMSTATE_UINT8(sect, FDrive), @@ -716,6 +738,9 @@ static const VMStateDescription vmstate_fdrive = { .vmsd = &vmstate_fdrive_media_rate, .needed = &fdrive_media_rate_needed, } , { + .vmsd = &vmstate_fdrive_perpendicular, + .needed = &fdrive_perpendicular_needed, + } , { /* empty */ } } @@ -737,14 +762,47 @@ static int fdc_post_load(void *opaque, int version_id) return 0; } +static bool fdc_reset_sensei_needed(void *opaque) +{ + FDCtrl *s = opaque; + + return s->reset_sensei != 0; +} + +static const VMStateDescription vmstate_fdc_reset_sensei = { + .name = "fdc/reset_sensei", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(reset_sensei, FDCtrl), + VMSTATE_END_OF_LIST() + } +}; + +static bool fdc_result_timer_needed(void *opaque) +{ + FDCtrl *s = opaque; + + return timer_pending(s->result_timer); +} + +static const VMStateDescription vmstate_fdc_result_timer = { + .name = "fdc/result_timer", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_TIMER(result_timer, FDCtrl), + VMSTATE_END_OF_LIST() + } +}; + static const VMStateDescription vmstate_fdc = { .name = "fdc", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .pre_save = fdc_pre_save, .post_load = fdc_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { /* Controller State */ VMSTATE_UINT8(sra, FDCtrl), VMSTATE_UINT8(srb, FDCtrl), @@ -774,6 +832,17 @@ static const VMStateDescription vmstate_fdc = { VMSTATE_STRUCT_ARRAY(drives, FDCtrl, MAX_FD, 1, vmstate_fdrive, FDrive), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_fdc_reset_sensei, + .needed = fdc_reset_sensei_needed, + } , { + .vmsd = &vmstate_fdc_result_timer, + .needed = fdc_result_timer_needed, + } , { + /* empty */ + } } }; @@ -842,12 +911,15 @@ static void fdctrl_reset(FDCtrl *fdctrl, int do_irq) /* Initialise controller */ fdctrl->sra = 0; fdctrl->srb = 0xc0; - if (!fdctrl->drives[1].bs) + if (!fdctrl->drives[1].blk) { fdctrl->sra |= FD_SRA_nDRV2; + } fdctrl->cur_drv = 0; fdctrl->dor = FD_DOR_nRESET; fdctrl->dor |= (fdctrl->dma_chann != -1) ? FD_DOR_DMAEN : 0; fdctrl->msr = FD_MSR_RQM; + fdctrl->reset_sensei = 0; + timer_del(fdctrl->result_timer); /* FIFO state */ fdctrl->data_pos = 0; fdctrl->data_len = 0; @@ -1333,7 +1405,7 @@ static int fdctrl_transfer_handler (void *opaque, int nchan, status2 = FD_SR2_SNS; if (dma_len > fdctrl->data_len) dma_len = fdctrl->data_len; - if (cur_drv->bs == NULL) { + if (cur_drv->blk == NULL) { if (fdctrl->data_dir == FD_DIR_WRITE) fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00); else @@ -1354,8 +1426,8 @@ static int fdctrl_transfer_handler (void *opaque, int nchan, if (fdctrl->data_dir != FD_DIR_WRITE || len < FD_SECTOR_LEN || rel_pos != 0) { /* READ & SCAN commands and realign to a sector for WRITE */ - if (bdrv_read(cur_drv->bs, fd_sector(cur_drv), - fdctrl->fifo, 1) < 0) { + if (blk_read(cur_drv->blk, fd_sector(cur_drv), + fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("Floppy: error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ @@ -1382,8 +1454,8 @@ static int fdctrl_transfer_handler (void *opaque, int nchan, DMA_read_memory (nchan, fdctrl->fifo + rel_pos, fdctrl->data_pos, len); - if (bdrv_write(cur_drv->bs, fd_sector(cur_drv), - fdctrl->fifo, 1) < 0) { + if (blk_write(cur_drv->blk, fd_sector(cur_drv), + fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error writing sector %d\n", fd_sector(cur_drv)); fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00); @@ -1458,7 +1530,8 @@ static uint32_t fdctrl_read_data(FDCtrl *fdctrl) fd_sector(cur_drv)); return 0; } - if (bdrv_read(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { + if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) + < 0) { FLOPPY_DPRINTF("error getting sector %d\n", fd_sector(cur_drv)); /* Sure, image size is too small... */ @@ -1527,8 +1600,8 @@ static void fdctrl_format_sector(FDCtrl *fdctrl) break; } memset(fdctrl->fifo, 0, FD_SECTOR_LEN); - if (cur_drv->bs == NULL || - bdrv_write(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { + if (cur_drv->blk == NULL || + blk_write(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { FLOPPY_DPRINTF("error formatting sector %d\n", fd_sector(cur_drv)); fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00); } else { @@ -1918,7 +1991,8 @@ static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value) if (pos == FD_SECTOR_LEN - 1 || fdctrl->data_pos == fdctrl->data_len) { cur_drv = get_cur_drv(fdctrl); - if (bdrv_write(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) { + if (blk_write(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) + < 0) { FLOPPY_DPRINTF("error writing sector %d\n", fd_sector(cur_drv)); return; @@ -2006,12 +2080,12 @@ static void fdctrl_connect_drives(FDCtrl *fdctrl, Error **errp) drive = &fdctrl->drives[i]; drive->fdctrl = fdctrl; - if (drive->bs) { - if (bdrv_get_on_error(drive->bs, 0) != BLOCKDEV_ON_ERROR_ENOSPC) { + if (drive->blk) { + if (blk_get_on_error(drive->blk, 0) != BLOCKDEV_ON_ERROR_ENOSPC) { error_setg(errp, "fdc doesn't support drive option werror"); return; } - if (bdrv_get_on_error(drive->bs, 1) != BLOCKDEV_ON_ERROR_REPORT) { + if (blk_get_on_error(drive->blk, 1) != BLOCKDEV_ON_ERROR_REPORT) { error_setg(errp, "fdc doesn't support drive option rerror"); return; } @@ -2019,8 +2093,8 @@ static void fdctrl_connect_drives(FDCtrl *fdctrl, Error **errp) fd_init(drive); fdctrl_change_cb(drive, 0); - if (drive->bs) { - bdrv_set_dev_ops(drive->bs, &fdctrl_block_ops, drive); + if (drive->blk) { + blk_set_dev_ops(drive->blk, &fdctrl_block_ops, drive); } } } @@ -2037,10 +2111,10 @@ ISADevice *fdctrl_init_isa(ISABus *bus, DriveInfo **fds) dev = DEVICE(isadev); if (fds[0]) { - qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv); + qdev_prop_set_drive_nofail(dev, "driveA", blk_by_legacy_dinfo(fds[0])); } if (fds[1]) { - qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv); + qdev_prop_set_drive_nofail(dev, "driveB", blk_by_legacy_dinfo(fds[1])); } qdev_init_nofail(dev); @@ -2060,10 +2134,10 @@ void fdctrl_init_sysbus(qemu_irq irq, int dma_chann, fdctrl = &sys->state; fdctrl->dma_chann = dma_chann; /* FIXME */ if (fds[0]) { - qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv); + qdev_prop_set_drive_nofail(dev, "driveA", blk_by_legacy_dinfo(fds[0])); } if (fds[1]) { - qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv); + qdev_prop_set_drive_nofail(dev, "driveB", blk_by_legacy_dinfo(fds[1])); } qdev_init_nofail(dev); sbd = SYS_BUS_DEVICE(dev); @@ -2079,7 +2153,7 @@ void sun4m_fdctrl_init(qemu_irq irq, hwaddr io_base, dev = qdev_create(NULL, "SUNW,fdtwo"); if (fds[0]) { - qdev_prop_set_drive_nofail(dev, "drive", fds[0]->bdrv); + qdev_prop_set_drive_nofail(dev, "drive", blk_by_legacy_dinfo(fds[0])); } qdev_init_nofail(dev); sys = SYSBUS_FDC(dev); @@ -2146,9 +2220,6 @@ static void isabus_fdc_realize(DeviceState *dev, Error **errp) error_propagate(errp, err); return; } - - add_boot_device_path(isa->bootindexA, dev, "/floppy@0"); - add_boot_device_path(isa->bootindexB, dev, "/floppy@1"); } static void sysbus_fdc_initfn(Object *obj) @@ -2209,7 +2280,7 @@ static const VMStateDescription vmstate_isa_fdc ={ .name = "fdc", .version_id = 2, .minimum_version_id = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(state, FDCtrlISABus, 0, vmstate_fdc, FDCtrl), VMSTATE_END_OF_LIST() } @@ -2219,10 +2290,8 @@ static Property isa_fdc_properties[] = { DEFINE_PROP_UINT32("iobase", FDCtrlISABus, iobase, 0x3f0), DEFINE_PROP_UINT32("irq", FDCtrlISABus, irq, 6), DEFINE_PROP_UINT32("dma", FDCtrlISABus, dma, 2), - DEFINE_PROP_DRIVE("driveA", FDCtrlISABus, state.drives[0].bs), - DEFINE_PROP_DRIVE("driveB", FDCtrlISABus, state.drives[1].bs), - DEFINE_PROP_INT32("bootindexA", FDCtrlISABus, bootindexA, -1), - DEFINE_PROP_INT32("bootindexB", FDCtrlISABus, bootindexB, -1), + DEFINE_PROP_DRIVE("driveA", FDCtrlISABus, state.drives[0].blk), + DEFINE_PROP_DRIVE("driveB", FDCtrlISABus, state.drives[1].blk), DEFINE_PROP_BIT("check_media_rate", FDCtrlISABus, state.check_media_rate, 0, true), DEFINE_PROP_END_OF_LIST(), @@ -2240,26 +2309,39 @@ static void isabus_fdc_class_init(ObjectClass *klass, void *data) set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); } +static void isabus_fdc_instance_init(Object *obj) +{ + FDCtrlISABus *isa = ISA_FDC(obj); + + device_add_bootindex_property(obj, &isa->bootindexA, + "bootindexA", "/floppy@0", + DEVICE(obj), NULL); + device_add_bootindex_property(obj, &isa->bootindexB, + "bootindexB", "/floppy@1", + DEVICE(obj), NULL); +} + static const TypeInfo isa_fdc_info = { .name = TYPE_ISA_FDC, .parent = TYPE_ISA_DEVICE, .instance_size = sizeof(FDCtrlISABus), .class_init = isabus_fdc_class_init, + .instance_init = isabus_fdc_instance_init, }; static const VMStateDescription vmstate_sysbus_fdc ={ .name = "fdc", .version_id = 2, .minimum_version_id = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(state, FDCtrlSysBus, 0, vmstate_fdc, FDCtrl), VMSTATE_END_OF_LIST() } }; static Property sysbus_fdc_properties[] = { - DEFINE_PROP_DRIVE("driveA", FDCtrlSysBus, state.drives[0].bs), - DEFINE_PROP_DRIVE("driveB", FDCtrlSysBus, state.drives[1].bs), + DEFINE_PROP_DRIVE("driveA", FDCtrlSysBus, state.drives[0].blk), + DEFINE_PROP_DRIVE("driveB", FDCtrlSysBus, state.drives[1].blk), DEFINE_PROP_END_OF_LIST(), }; @@ -2279,7 +2361,7 @@ static const TypeInfo sysbus_fdc_info = { }; static Property sun4m_fdc_properties[] = { - DEFINE_PROP_DRIVE("drive", FDCtrlSysBus, state.drives[0].bs), + DEFINE_PROP_DRIVE("drive", FDCtrlSysBus, state.drives[0].blk), DEFINE_PROP_END_OF_LIST(), }; diff --git a/hw/block/hd-geometry.c b/hw/block/hd-geometry.c index 6feb4f8175..6fcf74df44 100644 --- a/hw/block/hd-geometry.c +++ b/hw/block/hd-geometry.c @@ -30,7 +30,7 @@ * THE SOFTWARE. */ -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/block/block.h" #include "trace.h" @@ -49,7 +49,7 @@ struct partition { /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */ -static int guess_disk_lchs(BlockDriverState *bs, +static int guess_disk_lchs(BlockBackend *blk, int *pcylinders, int *pheads, int *psectors) { uint8_t buf[BDRV_SECTOR_SIZE]; @@ -58,14 +58,14 @@ static int guess_disk_lchs(BlockDriverState *bs, uint32_t nr_sects; uint64_t nb_sectors; - bdrv_get_geometry(bs, &nb_sectors); + blk_get_geometry(blk, &nb_sectors); /** * The function will be invoked during startup not only in sync I/O mode, * but also in async I/O mode. So the I/O throttling function has to * be disabled temporarily here, not permanently. */ - if (bdrv_read_unthrottled(bs, 0, buf, 1) < 0) { + if (blk_read_unthrottled(blk, 0, buf, 1) < 0) { return -1; } /* test msdos magic */ @@ -90,20 +90,20 @@ static int guess_disk_lchs(BlockDriverState *bs, *pheads = heads; *psectors = sectors; *pcylinders = cylinders; - trace_hd_geometry_lchs_guess(bs, cylinders, heads, sectors); + trace_hd_geometry_lchs_guess(blk, cylinders, heads, sectors); return 0; } } return -1; } -static void guess_chs_for_size(BlockDriverState *bs, +static void guess_chs_for_size(BlockBackend *blk, uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs) { uint64_t nb_sectors; int cylinders; - bdrv_get_geometry(bs, &nb_sectors); + blk_get_geometry(blk, &nb_sectors); cylinders = nb_sectors / (16 * 63); if (cylinders > 16383) { @@ -116,21 +116,21 @@ static void guess_chs_for_size(BlockDriverState *bs, *psecs = 63; } -void hd_geometry_guess(BlockDriverState *bs, +void hd_geometry_guess(BlockBackend *blk, uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs, int *ptrans) { int cylinders, heads, secs, translation; - if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) { + if (guess_disk_lchs(blk, &cylinders, &heads, &secs) < 0) { /* no LCHS guess: use a standard physical disk geometry */ - guess_chs_for_size(bs, pcyls, pheads, psecs); + guess_chs_for_size(blk, pcyls, pheads, psecs); translation = hd_bios_chs_auto_trans(*pcyls, *pheads, *psecs); } else if (heads > 16) { /* LCHS guess with heads > 16 means that a BIOS LBA translation was active, so a standard physical disk geometry is OK */ - guess_chs_for_size(bs, pcyls, pheads, psecs); + guess_chs_for_size(blk, pcyls, pheads, psecs); translation = *pcyls * *pheads <= 131072 ? BIOS_ATA_TRANSLATION_LARGE : BIOS_ATA_TRANSLATION_LBA; @@ -146,7 +146,7 @@ void hd_geometry_guess(BlockDriverState *bs, if (ptrans) { *ptrans = translation; } - trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation); + trace_hd_geometry_guess(blk, *pcyls, *pheads, *psecs, translation); } int hd_bios_chs_auto_trans(uint32_t cyls, uint32_t heads, uint32_t secs) diff --git a/hw/block/m25p80.c b/hw/block/m25p80.c index e29a738d23..ff1106b6c9 100644 --- a/hw/block/m25p80.c +++ b/hw/block/m25p80.c @@ -22,6 +22,7 @@ */ #include "hw/hw.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/ssi.h" @@ -245,7 +246,7 @@ typedef struct Flash { uint32_t r; - BlockDriverState *bdrv; + BlockBackend *blk; uint8_t *storage; uint32_t size; @@ -279,7 +280,7 @@ typedef struct M25P80Class { #define M25P80_GET_CLASS(obj) \ OBJECT_GET_CLASS(M25P80Class, (obj), TYPE_M25P80) -static void bdrv_sync_complete(void *opaque, int ret) +static void blk_sync_complete(void *opaque, int ret) { /* do nothing. Masters do not directly interact with the backing store, * only the working copy so no mutexing required. @@ -288,18 +289,20 @@ static void bdrv_sync_complete(void *opaque, int ret) static void flash_sync_page(Flash *s, int page) { - if (s->bdrv) { - int bdrv_sector, nb_sectors; - QEMUIOVector iov; - - bdrv_sector = (page * s->pi->page_size) / BDRV_SECTOR_SIZE; - nb_sectors = DIV_ROUND_UP(s->pi->page_size, BDRV_SECTOR_SIZE); - qemu_iovec_init(&iov, 1); - qemu_iovec_add(&iov, s->storage + bdrv_sector * BDRV_SECTOR_SIZE, - nb_sectors * BDRV_SECTOR_SIZE); - bdrv_aio_writev(s->bdrv, bdrv_sector, &iov, nb_sectors, - bdrv_sync_complete, NULL); + int blk_sector, nb_sectors; + QEMUIOVector iov; + + if (!s->blk || blk_is_read_only(s->blk)) { + return; } + + blk_sector = (page * s->pi->page_size) / BDRV_SECTOR_SIZE; + nb_sectors = DIV_ROUND_UP(s->pi->page_size, BDRV_SECTOR_SIZE); + qemu_iovec_init(&iov, 1); + qemu_iovec_add(&iov, s->storage + blk_sector * BDRV_SECTOR_SIZE, + nb_sectors * BDRV_SECTOR_SIZE); + blk_aio_writev(s->blk, blk_sector, &iov, nb_sectors, blk_sync_complete, + NULL); } static inline void flash_sync_area(Flash *s, int64_t off, int64_t len) @@ -307,7 +310,7 @@ static inline void flash_sync_area(Flash *s, int64_t off, int64_t len) int64_t start, end, nb_sectors; QEMUIOVector iov; - if (!s->bdrv) { + if (!s->blk || blk_is_read_only(s->blk)) { return; } @@ -318,7 +321,7 @@ static inline void flash_sync_area(Flash *s, int64_t off, int64_t len) qemu_iovec_init(&iov, 1); qemu_iovec_add(&iov, s->storage + (start * BDRV_SECTOR_SIZE), nb_sectors * BDRV_SECTOR_SIZE); - bdrv_aio_writev(s->bdrv, start, &iov, nb_sectors, bdrv_sync_complete, NULL); + blk_aio_writev(s->blk, start, &iov, nb_sectors, blk_sync_complete, NULL); } static void flash_erase(Flash *s, int offset, FlashCMD cmd) @@ -618,21 +621,17 @@ static int m25p80_init(SSISlave *ss) s->size = s->pi->sector_size * s->pi->n_sectors; s->dirty_page = -1; - s->storage = qemu_blockalign(s->bdrv, s->size); + s->storage = blk_blockalign(s->blk, s->size); dinfo = drive_get_next(IF_MTD); - if (dinfo && dinfo->bdrv) { + if (dinfo) { DB_PRINT_L(0, "Binding to IF_MTD drive\n"); - s->bdrv = dinfo->bdrv; - if (bdrv_is_read_only(s->bdrv)) { - fprintf(stderr, "Can't use a read-only drive"); - return 1; - } + s->blk = blk_by_legacy_dinfo(dinfo); /* FIXME: Move to late init */ - if (bdrv_read(s->bdrv, 0, s->storage, DIV_ROUND_UP(s->size, - BDRV_SECTOR_SIZE))) { + if (blk_read(s->blk, 0, s->storage, + DIV_ROUND_UP(s->size, BDRV_SECTOR_SIZE))) { fprintf(stderr, "Failed to initialize SPI flash!\n"); return 1; } @@ -653,7 +652,6 @@ static const VMStateDescription vmstate_m25p80 = { .name = "xilinx_spi", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = m25p80_pre_save, .fields = (VMStateField[]) { VMSTATE_UINT8(state, Flash), diff --git a/hw/block/nand.c b/hw/block/nand.c index 6d7c804f01..1882a0cbeb 100644 --- a/hw/block/nand.c +++ b/hw/block/nand.c @@ -20,7 +20,7 @@ # include "hw/hw.h" # include "hw/block/flash.h" -# include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/qdev.h" #include "qemu/error-report.h" @@ -61,7 +61,7 @@ struct NANDFlashState { int size, pages; int page_shift, oob_shift, erase_shift, addr_shift; uint8_t *storage; - BlockDriverState *bdrv; + BlockBackend *blk; int mem_oob; uint8_t cle, ale, ce, wp, gnd; @@ -346,10 +346,9 @@ static const VMStateDescription vmstate_nand = { .name = "nand", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = nand_pre_save, .post_load = nand_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(cle, NANDFlashState), VMSTATE_UINT8(ale, NANDFlashState), VMSTATE_UINT8(ce, NANDFlashState), @@ -401,12 +400,12 @@ static void nand_realize(DeviceState *dev, Error **errp) pagesize = 1 << s->oob_shift; s->mem_oob = 1; - if (s->bdrv) { - if (bdrv_is_read_only(s->bdrv)) { + if (s->blk) { + if (blk_is_read_only(s->blk)) { error_setg(errp, "Can't use a read-only drive"); return; } - if (bdrv_getlength(s->bdrv) >= + if (blk_getlength(s->blk) >= (s->pages << s->page_shift) + (s->pages << s->oob_shift)) { pagesize = 0; s->mem_oob = 0; @@ -425,7 +424,7 @@ static void nand_realize(DeviceState *dev, Error **errp) static Property nand_properties[] = { DEFINE_PROP_UINT8("manufacturer_id", NANDFlashState, manf_id, 0), DEFINE_PROP_UINT8("chip_id", NANDFlashState, chip_id, 0), - DEFINE_PROP_DRIVE("drive", NANDFlashState, bdrv), + DEFINE_PROP_DRIVE("drive", NANDFlashState, blk), DEFINE_PROP_END_OF_LIST(), }; @@ -625,7 +624,7 @@ uint32_t nand_getbuswidth(DeviceState *dev) return s->buswidth << 3; } -DeviceState *nand_init(BlockDriverState *bdrv, int manf_id, int chip_id) +DeviceState *nand_init(BlockBackend *blk, int manf_id, int chip_id) { DeviceState *dev; @@ -635,8 +634,8 @@ DeviceState *nand_init(BlockDriverState *bdrv, int manf_id, int chip_id) dev = DEVICE(object_new(TYPE_NAND)); qdev_prop_set_uint8(dev, "manufacturer_id", manf_id); qdev_prop_set_uint8(dev, "chip_id", chip_id); - if (bdrv) { - qdev_prop_set_drive_nofail(dev, "drive", bdrv); + if (blk) { + qdev_prop_set_drive_nofail(dev, "drive", blk); } qdev_init_nofail(dev); @@ -655,14 +654,14 @@ static void glue(nand_blk_write_, PAGE_SIZE)(NANDFlashState *s) if (PAGE(s->addr) >= s->pages) return; - if (!s->bdrv) { + if (!s->blk) { mem_and(s->storage + PAGE_START(s->addr) + (s->addr & PAGE_MASK) + s->offset, s->io, s->iolen); } else if (s->mem_oob) { sector = SECTOR(s->addr); off = (s->addr & PAGE_MASK) + s->offset; soff = SECTOR_OFFSET(s->addr); - if (bdrv_read(s->bdrv, sector, iobuf, PAGE_SECTORS) < 0) { + if (blk_read(s->blk, sector, iobuf, PAGE_SECTORS) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, sector); return; } @@ -674,21 +673,21 @@ static void glue(nand_blk_write_, PAGE_SIZE)(NANDFlashState *s) MIN(OOB_SIZE, off + s->iolen - PAGE_SIZE)); } - if (bdrv_write(s->bdrv, sector, iobuf, PAGE_SECTORS) < 0) { + if (blk_write(s->blk, sector, iobuf, PAGE_SECTORS) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, sector); } } else { off = PAGE_START(s->addr) + (s->addr & PAGE_MASK) + s->offset; sector = off >> 9; soff = off & 0x1ff; - if (bdrv_read(s->bdrv, sector, iobuf, PAGE_SECTORS + 2) < 0) { + if (blk_read(s->blk, sector, iobuf, PAGE_SECTORS + 2) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, sector); return; } mem_and(iobuf + soff, s->io, s->iolen); - if (bdrv_write(s->bdrv, sector, iobuf, PAGE_SECTORS + 2) < 0) { + if (blk_write(s->blk, sector, iobuf, PAGE_SECTORS + 2) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, sector); } } @@ -706,7 +705,7 @@ static void glue(nand_blk_erase_, PAGE_SIZE)(NANDFlashState *s) return; } - if (!s->bdrv) { + if (!s->blk) { memset(s->storage + PAGE_START(addr), 0xff, (PAGE_SIZE + OOB_SIZE) << s->erase_shift); } else if (s->mem_oob) { @@ -715,17 +714,17 @@ static void glue(nand_blk_erase_, PAGE_SIZE)(NANDFlashState *s) i = SECTOR(addr); page = SECTOR(addr + (ADDR_SHIFT + s->erase_shift)); for (; i < page; i ++) - if (bdrv_write(s->bdrv, i, iobuf, 1) < 0) { + if (blk_write(s->blk, i, iobuf, 1) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, i); } } else { addr = PAGE_START(addr); page = addr >> 9; - if (bdrv_read(s->bdrv, page, iobuf, 1) < 0) { + if (blk_read(s->blk, page, iobuf, 1) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, page); } memset(iobuf + (addr & 0x1ff), 0xff, (~addr & 0x1ff) + 1); - if (bdrv_write(s->bdrv, page, iobuf, 1) < 0) { + if (blk_write(s->blk, page, iobuf, 1) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, page); } @@ -733,18 +732,18 @@ static void glue(nand_blk_erase_, PAGE_SIZE)(NANDFlashState *s) i = (addr & ~0x1ff) + 0x200; for (addr += ((PAGE_SIZE + OOB_SIZE) << s->erase_shift) - 0x200; i < addr; i += 0x200) { - if (bdrv_write(s->bdrv, i >> 9, iobuf, 1) < 0) { + if (blk_write(s->blk, i >> 9, iobuf, 1) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, i >> 9); } } page = i >> 9; - if (bdrv_read(s->bdrv, page, iobuf, 1) < 0) { + if (blk_read(s->blk, page, iobuf, 1) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, page); } memset(iobuf, 0xff, ((addr - 1) & 0x1ff) + 1); - if (bdrv_write(s->bdrv, page, iobuf, 1) < 0) { + if (blk_write(s->blk, page, iobuf, 1) < 0) { printf("%s: write error in sector %" PRIu64 "\n", __func__, page); } } @@ -757,9 +756,9 @@ static void glue(nand_blk_load_, PAGE_SIZE)(NANDFlashState *s, return; } - if (s->bdrv) { + if (s->blk) { if (s->mem_oob) { - if (bdrv_read(s->bdrv, SECTOR(addr), s->io, PAGE_SECTORS) < 0) { + if (blk_read(s->blk, SECTOR(addr), s->io, PAGE_SECTORS) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, SECTOR(addr)); } @@ -768,8 +767,8 @@ static void glue(nand_blk_load_, PAGE_SIZE)(NANDFlashState *s, OOB_SIZE); s->ioaddr = s->io + SECTOR_OFFSET(s->addr) + offset; } else { - if (bdrv_read(s->bdrv, PAGE_START(addr) >> 9, - s->io, (PAGE_SECTORS + 2)) < 0) { + if (blk_read(s->blk, PAGE_START(addr) >> 9, + s->io, (PAGE_SECTORS + 2)) < 0) { printf("%s: read error in sector %" PRIu64 "\n", __func__, PAGE_START(addr) >> 9); } diff --git a/hw/block/nvme.c b/hw/block/nvme.c index 5fd8f89822..13276589e4 100644 --- a/hw/block/nvme.c +++ b/hw/block/nvme.c @@ -24,6 +24,9 @@ #include <hw/hw.h> #include <hw/pci/msix.h> #include <hw/pci/pci.h> +#include "sysemu/sysemu.h" +#include "qapi/visitor.h" +#include "sysemu/block-backend.h" #include "nvme.h" @@ -197,7 +200,7 @@ static void nvme_rw_cb(void *opaque, int ret) NvmeCtrl *n = sq->ctrl; NvmeCQueue *cq = n->cq[sq->cqid]; - bdrv_acct_done(n->conf.bs, &req->acct); + block_acct_done(blk_get_stats(n->conf.blk), &req->acct); if (!ret) { req->status = NVME_SUCCESS; } else { @@ -231,11 +234,11 @@ static uint16_t nvme_rw(NvmeCtrl *n, NvmeNamespace *ns, NvmeCmd *cmd, } assert((nlb << data_shift) == req->qsg.size); - dma_acct_start(n->conf.bs, &req->acct, &req->qsg, is_write ? - BDRV_ACCT_WRITE : BDRV_ACCT_READ); + dma_acct_start(n->conf.blk, &req->acct, &req->qsg, + is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ); req->aiocb = is_write ? - dma_bdrv_write(n->conf.bs, &req->qsg, aio_slba, nvme_rw_cb, req) : - dma_bdrv_read(n->conf.bs, &req->qsg, aio_slba, nvme_rw_cb, req); + dma_blk_write(n->conf.blk, &req->qsg, aio_slba, nvme_rw_cb, req) : + dma_blk_read(n->conf.blk, &req->qsg, aio_slba, nvme_rw_cb, req); return NVME_NO_COMPLETE; } @@ -288,7 +291,7 @@ static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeCmd *cmd) while (!QTAILQ_EMPTY(&sq->out_req_list)) { req = QTAILQ_FIRST(&sq->out_req_list); assert(req->aiocb); - bdrv_aio_cancel(req->aiocb); + blk_aio_cancel(req->aiocb); } if (!nvme_check_cqid(n, sq->cqid)) { cq = n->cq[sq->cqid]; @@ -319,7 +322,7 @@ static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr, sq->size = size; sq->cqid = cqid; sq->head = sq->tail = 0; - sq->io_req = g_malloc(sq->size * sizeof(*sq->io_req)); + sq->io_req = g_new(NvmeRequest, sq->size); QTAILQ_INIT(&sq->req_list); QTAILQ_INIT(&sq->out_req_list); @@ -563,7 +566,7 @@ static void nvme_clear_ctrl(NvmeCtrl *n) } } - bdrv_flush(n->conf.bs); + blk_flush(n->conf.blk); n->bar.cc = 0; } @@ -580,8 +583,7 @@ static int nvme_start_ctrl(NvmeCtrl *n) NVME_CC_IOCQES(n->bar.cc) > NVME_CTRL_CQES_MAX(n->id_ctrl.cqes) || NVME_CC_IOSQES(n->bar.cc) < NVME_CTRL_SQES_MIN(n->id_ctrl.sqes) || NVME_CC_IOSQES(n->bar.cc) > NVME_CTRL_SQES_MAX(n->id_ctrl.sqes) || - !NVME_AQA_ASQS(n->bar.aqa) || NVME_AQA_ASQS(n->bar.aqa) > 4095 || - !NVME_AQA_ACQS(n->bar.aqa) || NVME_AQA_ACQS(n->bar.aqa) > 4095) { + !NVME_AQA_ASQS(n->bar.aqa) || !NVME_AQA_ACQS(n->bar.aqa)) { return -1; } @@ -748,11 +750,11 @@ static int nvme_init(PCIDevice *pci_dev) int64_t bs_size; uint8_t *pci_conf; - if (!(n->conf.bs)) { + if (!n->conf.blk) { return -1; } - bs_size = bdrv_getlength(n->conf.bs); + bs_size = blk_getlength(n->conf.blk); if (bs_size < 0) { return -1; } @@ -773,9 +775,9 @@ static int nvme_init(PCIDevice *pci_dev) n->reg_size = 1 << qemu_fls(0x1004 + 2 * (n->num_queues + 1) * 4); n->ns_size = bs_size / (uint64_t)n->num_namespaces; - n->namespaces = g_malloc0(sizeof(*n->namespaces)*n->num_namespaces); - n->sq = g_malloc0(sizeof(*n->sq)*n->num_queues); - n->cq = g_malloc0(sizeof(*n->cq)*n->num_queues); + n->namespaces = g_new0(NvmeNamespace, n->num_namespaces); + n->sq = g_new0(NvmeSQueue *, n->num_queues); + n->cq = g_new0(NvmeCQueue *, n->num_queues); memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme", n->reg_size); @@ -839,7 +841,6 @@ static void nvme_exit(PCIDevice *pci_dev) g_free(n->cq); g_free(n->sq); msix_uninit_exclusive_bar(pci_dev); - memory_region_destroy(&n->iomem); } static Property nvme_props[] = { @@ -872,11 +873,53 @@ static void nvme_class_init(ObjectClass *oc, void *data) dc->vmsd = &nvme_vmstate; } +static void nvme_get_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + NvmeCtrl *s = NVME(obj); + + visit_type_int32(v, &s->conf.bootindex, name, errp); +} + +static void nvme_set_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + NvmeCtrl *s = NVME(obj); + int32_t boot_index; + Error *local_err = NULL; + + visit_type_int32(v, &boot_index, name, &local_err); + if (local_err) { + goto out; + } + /* check whether bootindex is present in fw_boot_order list */ + check_boot_index(boot_index, &local_err); + if (local_err) { + goto out; + } + /* change bootindex to a new one */ + s->conf.bootindex = boot_index; + +out: + if (local_err) { + error_propagate(errp, local_err); + } +} + +static void nvme_instance_init(Object *obj) +{ + object_property_add(obj, "bootindex", "int32", + nvme_get_bootindex, + nvme_set_bootindex, NULL, NULL, NULL); + object_property_set_int(obj, -1, "bootindex", NULL); +} + static const TypeInfo nvme_info = { .name = "nvme", .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(NvmeCtrl), .class_init = nvme_class_init, + .instance_init = nvme_instance_init, }; static void nvme_register_types(void) diff --git a/hw/block/nvme.h b/hw/block/nvme.h index bd8fc3e4bb..993c51131c 100644 --- a/hw/block/nvme.h +++ b/hw/block/nvme.h @@ -636,7 +636,7 @@ typedef struct NvmeAsyncEvent { typedef struct NvmeRequest { struct NvmeSQueue *sq; - BlockDriverAIOCB *aiocb; + BlockAIOCB *aiocb; uint16_t status; NvmeCqe cqe; BlockAcctCookie acct; diff --git a/hw/block/onenand.c b/hw/block/onenand.c index aae9ee7536..348630d905 100644 --- a/hw/block/onenand.c +++ b/hw/block/onenand.c @@ -22,6 +22,7 @@ #include "hw/hw.h" #include "hw/block/flash.h" #include "hw/irq.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "exec/memory.h" #include "exec/address-spaces.h" @@ -49,8 +50,8 @@ typedef struct OneNANDState { hwaddr base; qemu_irq intr; qemu_irq rdy; - BlockDriverState *bdrv; - BlockDriverState *bdrv_cur; + BlockBackend *blk; + BlockBackend *blk_cur; uint8_t *image; uint8_t *otp; uint8_t *current; @@ -169,7 +170,6 @@ static const VMStateDescription vmstate_onenand = { .name = "onenand", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = onenand_pre_save, .post_load = onenand_post_load, .fields = (VMStateField[]) { @@ -214,7 +214,7 @@ static void onenand_reset(OneNANDState *s, int cold) s->wpstatus = 0x0002; s->cycle = 0; s->otpmode = 0; - s->bdrv_cur = s->bdrv; + s->blk_cur = s->blk; s->current = s->image; s->secs_cur = s->secs; @@ -222,7 +222,7 @@ static void onenand_reset(OneNANDState *s, int cold) /* Lock the whole flash */ memset(s->blockwp, ONEN_LOCK_LOCKED, s->blocks); - if (s->bdrv_cur && bdrv_read(s->bdrv_cur, 0, s->boot[0], 8) < 0) { + if (s->blk_cur && blk_read(s->blk_cur, 0, s->boot[0], 8) < 0) { hw_error("%s: Loading the BootRAM failed.\n", __func__); } } @@ -238,10 +238,11 @@ static void onenand_system_reset(DeviceState *dev) static inline int onenand_load_main(OneNANDState *s, int sec, int secn, void *dest) { - if (s->bdrv_cur) - return bdrv_read(s->bdrv_cur, sec, dest, secn) < 0; - else if (sec + secn > s->secs_cur) + if (s->blk_cur) { + return blk_read(s->blk_cur, sec, dest, secn) < 0; + } else if (sec + secn > s->secs_cur) { return 1; + } memcpy(dest, s->current + (sec << 9), secn << 9); @@ -257,9 +258,9 @@ static inline int onenand_prog_main(OneNANDState *s, int sec, int secn, uint32_t size = (uint32_t)secn * 512; const uint8_t *sp = (const uint8_t *)src; uint8_t *dp = 0; - if (s->bdrv_cur) { + if (s->blk_cur) { dp = g_malloc(size); - if (!dp || bdrv_read(s->bdrv_cur, sec, dp, secn) < 0) { + if (!dp || blk_read(s->blk_cur, sec, dp, secn) < 0) { result = 1; } } else { @@ -274,11 +275,11 @@ static inline int onenand_prog_main(OneNANDState *s, int sec, int secn, for (i = 0; i < size; i++) { dp[i] &= sp[i]; } - if (s->bdrv_cur) { - result = bdrv_write(s->bdrv_cur, sec, dp, secn) < 0; + if (s->blk_cur) { + result = blk_write(s->blk_cur, sec, dp, secn) < 0; } } - if (dp && s->bdrv_cur) { + if (dp && s->blk_cur) { g_free(dp); } } @@ -291,14 +292,16 @@ static inline int onenand_load_spare(OneNANDState *s, int sec, int secn, { uint8_t buf[512]; - if (s->bdrv_cur) { - if (bdrv_read(s->bdrv_cur, s->secs_cur + (sec >> 5), buf, 1) < 0) + if (s->blk_cur) { + if (blk_read(s->blk_cur, s->secs_cur + (sec >> 5), buf, 1) < 0) { return 1; + } memcpy(dest, buf + ((sec & 31) << 4), secn << 4); - } else if (sec + secn > s->secs_cur) + } else if (sec + secn > s->secs_cur) { return 1; - else + } else { memcpy(dest, s->current + (s->secs_cur << 9) + (sec << 4), secn << 4); + } return 0; } @@ -310,11 +313,10 @@ static inline int onenand_prog_spare(OneNANDState *s, int sec, int secn, if (secn > 0) { const uint8_t *sp = (const uint8_t *)src; uint8_t *dp = 0, *dpp = 0; - if (s->bdrv_cur) { + if (s->blk_cur) { dp = g_malloc(512); - if (!dp || bdrv_read(s->bdrv_cur, - s->secs_cur + (sec >> 5), - dp, 1) < 0) { + if (!dp + || blk_read(s->blk_cur, s->secs_cur + (sec >> 5), dp, 1) < 0) { result = 1; } else { dpp = dp + ((sec & 31) << 4); @@ -331,14 +333,12 @@ static inline int onenand_prog_spare(OneNANDState *s, int sec, int secn, for (i = 0; i < (secn << 4); i++) { dpp[i] &= sp[i]; } - if (s->bdrv_cur) { - result = bdrv_write(s->bdrv_cur, s->secs_cur + (sec >> 5), - dp, 1) < 0; + if (s->blk_cur) { + result = blk_write(s->blk_cur, s->secs_cur + (sec >> 5), + dp, 1) < 0; } } - if (dp) { - g_free(dp); - } + g_free(dp); } return result; } @@ -357,16 +357,16 @@ static inline int onenand_erase(OneNANDState *s, int sec, int num) } memset(blankbuf, 0xff, 512); for (; num > 0; num--, sec++) { - if (s->bdrv_cur) { + if (s->blk_cur) { int erasesec = s->secs_cur + (sec >> 5); - if (bdrv_write(s->bdrv_cur, sec, blankbuf, 1) < 0) { + if (blk_write(s->blk_cur, sec, blankbuf, 1) < 0) { goto fail; } - if (bdrv_read(s->bdrv_cur, erasesec, tmpbuf, 1) < 0) { + if (blk_read(s->blk_cur, erasesec, tmpbuf, 1) < 0) { goto fail; } memcpy(tmpbuf + ((sec & 31) << 4), blankbuf, 1 << 4); - if (bdrv_write(s->bdrv_cur, erasesec, tmpbuf, 1) < 0) { + if (blk_write(s->blk_cur, erasesec, tmpbuf, 1) < 0) { goto fail; } } else { @@ -579,7 +579,7 @@ static void onenand_command(OneNANDState *s) case 0x65: /* OTP Access */ s->intstatus |= ONEN_INT; - s->bdrv_cur = NULL; + s->blk_cur = NULL; s->current = s->otp; s->secs_cur = 1 << (BLOCK_SHIFT - 9); s->addr[ONEN_BUF_BLOCK] = 0; @@ -779,20 +779,20 @@ static int onenand_initfn(SysBusDevice *sbd) ? (1 << (6 + ((s->id.dev >> 4) & 7))) : 0; memory_region_init_io(&s->iomem, OBJECT(s), &onenand_ops, s, "onenand", 0x10000 << s->shift); - if (!s->bdrv) { + if (!s->blk) { s->image = memset(g_malloc(size + (size >> 5)), 0xff, size + (size >> 5)); } else { - if (bdrv_is_read_only(s->bdrv)) { + if (blk_is_read_only(s->blk)) { error_report("Can't use a read-only drive"); return -1; } - s->bdrv_cur = s->bdrv; + s->blk_cur = s->blk; } s->otp = memset(g_malloc((64 + 2) << PAGE_SHIFT), 0xff, (64 + 2) << PAGE_SHIFT); memory_region_init_ram(&s->ram, OBJECT(s), "onenand.ram", - 0xc000 << s->shift); + 0xc000 << s->shift, &error_abort); vmstate_register_ram_global(&s->ram); ram = memory_region_get_ram_ptr(&s->ram); s->boot[0] = ram + (0x0000 << s->shift); @@ -818,7 +818,7 @@ static Property onenand_properties[] = { DEFINE_PROP_UINT16("device_id", OneNANDState, id.dev, 0), DEFINE_PROP_UINT16("version_id", OneNANDState, id.ver, 0), DEFINE_PROP_INT32("shift", OneNANDState, shift, 0), - DEFINE_PROP_DRIVE("drive", OneNANDState, bdrv), + DEFINE_PROP_DRIVE("drive", OneNANDState, blk), DEFINE_PROP_END_OF_LIST(), }; diff --git a/hw/block/pflash_cfi01.c b/hw/block/pflash_cfi01.c index 0c95d53dca..89d380e59d 100644 --- a/hw/block/pflash_cfi01.c +++ b/hw/block/pflash_cfi01.c @@ -38,7 +38,7 @@ #include "hw/hw.h" #include "hw/block/flash.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "qemu/timer.h" #include "qemu/bitops.h" #include "exec/address-spaces.h" @@ -69,7 +69,7 @@ struct pflash_t { SysBusDevice parent_obj; /*< public >*/ - BlockDriverState *bs; + BlockBackend *blk; uint32_t nb_blocs; uint64_t sector_len; uint8_t bank_width; @@ -94,10 +94,13 @@ struct pflash_t { void *storage; }; +static int pflash_post_load(void *opaque, int version_id); + static const VMStateDescription vmstate_pflash = { .name = "pflash_cfi01", .version_id = 1, .minimum_version_id = 1, + .post_load = pflash_post_load, .fields = (VMStateField[]) { VMSTATE_UINT8(wcycle, pflash_t), VMSTATE_UINT8(cmd, pflash_t), @@ -209,11 +212,11 @@ static uint32_t pflash_devid_query(pflash_t *pfl, hwaddr offset) switch (boff & 0xFF) { case 0: resp = pfl->ident0; - DPRINTF("%s: Manufacturer Code %04x\n", __func__, ret); + DPRINTF("%s: Manufacturer Code %04x\n", __func__, resp); break; case 1: resp = pfl->ident1; - DPRINTF("%s: Device ID Code %04x\n", __func__, ret); + DPRINTF("%s: Device ID Code %04x\n", __func__, resp); break; default: DPRINTF("%s: Read Device Information offset=%x\n", __func__, @@ -392,13 +395,13 @@ static void pflash_update(pflash_t *pfl, int offset, int size) { int offset_end; - if (pfl->bs) { + if (pfl->blk) { offset_end = offset + size; /* round to sectors */ offset = offset >> 9; offset_end = (offset_end + 511) >> 9; - bdrv_write(pfl->bs, offset, pfl->storage + (offset << 9), - offset_end - offset); + blk_write(pfl->blk, offset, pfl->storage + (offset << 9), + offset_end - offset); } } @@ -748,9 +751,19 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp) pflash_t *pfl = CFI_PFLASH01(dev); uint64_t total_len; int ret; + uint64_t blocks_per_device, device_len; + int num_devices; + Error *local_err = NULL; total_len = pfl->sector_len * pfl->nb_blocs; + /* These are only used to expose the parameters of each device + * in the cfi_table[]. + */ + num_devices = pfl->device_width ? (pfl->bank_width / pfl->device_width) : 1; + blocks_per_device = pfl->nb_blocs / num_devices; + device_len = pfl->sector_len * blocks_per_device; + /* XXX: to be fixed */ #if 0 if (total_len != (8 * 1024 * 1024) && total_len != (16 * 1024 * 1024) && @@ -761,25 +774,29 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp) memory_region_init_rom_device( &pfl->mem, OBJECT(dev), pfl->be ? &pflash_cfi01_ops_be : &pflash_cfi01_ops_le, pfl, - pfl->name, total_len); + pfl->name, total_len, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; + } + vmstate_register_ram(&pfl->mem, DEVICE(pfl)); pfl->storage = memory_region_get_ram_ptr(&pfl->mem); sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem); - if (pfl->bs) { + if (pfl->blk) { /* read the initial flash content */ - ret = bdrv_read(pfl->bs, 0, pfl->storage, total_len >> 9); + ret = blk_read(pfl->blk, 0, pfl->storage, total_len >> 9); if (ret < 0) { vmstate_unregister_ram(&pfl->mem, DEVICE(pfl)); - memory_region_destroy(&pfl->mem); error_setg(errp, "failed to read the initial flash content"); return; } } - if (pfl->bs) { - pfl->ro = bdrv_is_read_only(pfl->bs); + if (pfl->blk) { + pfl->ro = blk_is_read_only(pfl->blk); } else { pfl->ro = 0; } @@ -838,7 +855,7 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp) /* Max timeout for chip erase */ pfl->cfi_table[0x26] = 0x00; /* Device size */ - pfl->cfi_table[0x27] = ctz32(total_len); // + 1; + pfl->cfi_table[0x27] = ctz32(device_len); /* + 1; */ /* Flash device interface (8 & 16 bits) */ pfl->cfi_table[0x28] = 0x02; pfl->cfi_table[0x29] = 0x00; @@ -854,8 +871,8 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp) /* Number of erase block regions (uniform) */ pfl->cfi_table[0x2C] = 0x01; /* Erase block region 1 */ - pfl->cfi_table[0x2D] = pfl->nb_blocs - 1; - pfl->cfi_table[0x2E] = (pfl->nb_blocs - 1) >> 8; + pfl->cfi_table[0x2D] = blocks_per_device - 1; + pfl->cfi_table[0x2E] = (blocks_per_device - 1) >> 8; pfl->cfi_table[0x2F] = pfl->sector_len >> 8; pfl->cfi_table[0x30] = pfl->sector_len >> 16; @@ -881,7 +898,12 @@ static void pflash_cfi01_realize(DeviceState *dev, Error **errp) } static Property pflash_cfi01_properties[] = { - DEFINE_PROP_DRIVE("drive", struct pflash_t, bs), + DEFINE_PROP_DRIVE("drive", struct pflash_t, blk), + /* num-blocks is the number of blocks actually visible to the guest, + * ie the total size of the device divided by the sector length. + * If we're emulating flash devices wired in parallel the actual + * number of blocks per indvidual device will differ. + */ DEFINE_PROP_UINT32("num-blocks", struct pflash_t, nb_blocs, 0), DEFINE_PROP_UINT64("sector-length", struct pflash_t, sector_len, 0), /* width here is the overall width of this QEMU device in bytes. @@ -940,14 +962,14 @@ type_init(pflash_cfi01_register_types) pflash_t *pflash_cfi01_register(hwaddr base, DeviceState *qdev, const char *name, hwaddr size, - BlockDriverState *bs, + BlockBackend *blk, uint32_t sector_len, int nb_blocs, int bank_width, uint16_t id0, uint16_t id1, uint16_t id2, uint16_t id3, int be) { DeviceState *dev = qdev_create(NULL, TYPE_CFI_PFLASH01); - if (bs && qdev_prop_set_drive(dev, "drive", bs)) { + if (blk && qdev_prop_set_drive(dev, "drive", blk)) { abort(); } qdev_prop_set_uint32(dev, "num-blocks", nb_blocs); @@ -969,3 +991,14 @@ MemoryRegion *pflash_cfi01_get_memory(pflash_t *fl) { return &fl->mem; } + +static int pflash_post_load(void *opaque, int version_id) +{ + pflash_t *pfl = opaque; + + if (!pfl->ro) { + DPRINTF("%s: updating bdrv for %s\n", __func__, pfl->name); + pflash_update(pfl, 0, pfl->sector_len * pfl->nb_blocs); + } + return 0; +} diff --git a/hw/block/pflash_cfi02.c b/hw/block/pflash_cfi02.c index 8d4b828edf..8513a17e9f 100644 --- a/hw/block/pflash_cfi02.c +++ b/hw/block/pflash_cfi02.c @@ -38,7 +38,7 @@ #include "hw/hw.h" #include "hw/block/flash.h" #include "qemu/timer.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "qemu/host-utils.h" #include "hw/sysbus.h" @@ -63,7 +63,7 @@ struct pflash_t { SysBusDevice parent_obj; /*< public >*/ - BlockDriverState *bs; + BlockBackend *blk; uint32_t sector_len; uint32_t nb_blocs; uint32_t chip_len; @@ -249,13 +249,13 @@ static void pflash_update(pflash_t *pfl, int offset, int size) { int offset_end; - if (pfl->bs) { + if (pfl->blk) { offset_end = offset + size; /* round to sectors */ offset = offset >> 9; offset_end = (offset_end + 511) >> 9; - bdrv_write(pfl->bs, offset, pfl->storage + (offset << 9), - offset_end - offset); + blk_write(pfl->blk, offset, pfl->storage + (offset << 9), + offset_end - offset); } } @@ -597,6 +597,7 @@ static void pflash_cfi02_realize(DeviceState *dev, Error **errp) pflash_t *pfl = CFI_PFLASH02(dev); uint32_t chip_len; int ret; + Error *local_err = NULL; chip_len = pfl->sector_len * pfl->nb_blocs; /* XXX: to be fixed */ @@ -608,16 +609,20 @@ static void pflash_cfi02_realize(DeviceState *dev, Error **errp) memory_region_init_rom_device(&pfl->orig_mem, OBJECT(pfl), pfl->be ? &pflash_cfi02_ops_be : &pflash_cfi02_ops_le, - pfl, pfl->name, chip_len); + pfl, pfl->name, chip_len, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; + } + vmstate_register_ram(&pfl->orig_mem, DEVICE(pfl)); pfl->storage = memory_region_get_ram_ptr(&pfl->orig_mem); pfl->chip_len = chip_len; - if (pfl->bs) { + if (pfl->blk) { /* read the initial flash content */ - ret = bdrv_read(pfl->bs, 0, pfl->storage, chip_len >> 9); + ret = blk_read(pfl->blk, 0, pfl->storage, chip_len >> 9); if (ret < 0) { vmstate_unregister_ram(&pfl->orig_mem, DEVICE(pfl)); - memory_region_destroy(&pfl->orig_mem); error_setg(errp, "failed to read the initial flash content"); return; } @@ -627,8 +632,8 @@ static void pflash_cfi02_realize(DeviceState *dev, Error **errp) pfl->rom_mode = 1; sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem); - if (pfl->bs) { - pfl->ro = bdrv_is_read_only(pfl->bs); + if (pfl->blk) { + pfl->ro = blk_is_read_only(pfl->blk); } else { pfl->ro = 0; } @@ -717,7 +722,7 @@ static void pflash_cfi02_realize(DeviceState *dev, Error **errp) } static Property pflash_cfi02_properties[] = { - DEFINE_PROP_DRIVE("drive", struct pflash_t, bs), + DEFINE_PROP_DRIVE("drive", struct pflash_t, blk), DEFINE_PROP_UINT32("num-blocks", struct pflash_t, nb_blocs, 0), DEFINE_PROP_UINT32("sector-length", struct pflash_t, sector_len, 0), DEFINE_PROP_UINT8("width", struct pflash_t, width, 0), @@ -758,7 +763,7 @@ type_init(pflash_cfi02_register_types) pflash_t *pflash_cfi02_register(hwaddr base, DeviceState *qdev, const char *name, hwaddr size, - BlockDriverState *bs, uint32_t sector_len, + BlockBackend *blk, uint32_t sector_len, int nb_blocs, int nb_mappings, int width, uint16_t id0, uint16_t id1, uint16_t id2, uint16_t id3, @@ -767,7 +772,7 @@ pflash_t *pflash_cfi02_register(hwaddr base, { DeviceState *dev = qdev_create(NULL, TYPE_CFI_PFLASH02); - if (bs && qdev_prop_set_drive(dev, "drive", bs)) { + if (blk && qdev_prop_set_drive(dev, "drive", blk)) { abort(); } qdev_prop_set_uint32(dev, "num-blocks", nb_blocs); diff --git a/hw/block/virtio-blk.c b/hw/block/virtio-blk.c index 8a568e5edb..b19b102b42 100644 --- a/hw/block/virtio-blk.c +++ b/hw/block/virtio-blk.c @@ -12,34 +12,40 @@ */ #include "qemu-common.h" +#include "qemu/iov.h" #include "qemu/error-report.h" #include "trace.h" #include "hw/block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/virtio/virtio-blk.h" -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE -# include "dataplane/virtio-blk.h" -# include "migration/migration.h" -#endif +#include "dataplane/virtio-blk.h" +#include "migration/migration.h" #include "block/scsi.h" #ifdef __linux__ # include <scsi/sg.h> #endif #include "hw/virtio/virtio-bus.h" +#include "hw/virtio/virtio-access.h" -typedef struct VirtIOBlockReq +VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s) { - VirtIOBlock *dev; - VirtQueueElement elem; - struct virtio_blk_inhdr *in; - struct virtio_blk_outhdr *out; - struct virtio_scsi_inhdr *scsi; - QEMUIOVector qiov; - struct VirtIOBlockReq *next; - BlockAcctCookie acct; -} VirtIOBlockReq; + VirtIOBlockReq *req = g_slice_new(VirtIOBlockReq); + req->dev = s; + req->qiov.size = 0; + req->next = NULL; + return req; +} -static void virtio_blk_req_complete(VirtIOBlockReq *req, int status) +void virtio_blk_free_request(VirtIOBlockReq *req) +{ + if (req) { + g_slice_free(VirtIOBlockReq, req); + } +} + +static void virtio_blk_complete_request(VirtIOBlockReq *req, + unsigned char status) { VirtIOBlock *s = req->dev; VirtIODevice *vdev = VIRTIO_DEVICE(s); @@ -51,23 +57,29 @@ static void virtio_blk_req_complete(VirtIOBlockReq *req, int status) virtio_notify(vdev, s->vq); } +static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status) +{ + req->dev->complete_request(req, status); +} + static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error, bool is_read) { - BlockErrorAction action = bdrv_get_error_action(req->dev->bs, is_read, error); + BlockErrorAction action = blk_get_error_action(req->dev->blk, + is_read, error); VirtIOBlock *s = req->dev; - if (action == BDRV_ACTION_STOP) { + if (action == BLOCK_ERROR_ACTION_STOP) { req->next = s->rq; s->rq = req; - } else if (action == BDRV_ACTION_REPORT) { + } else if (action == BLOCK_ERROR_ACTION_REPORT) { virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR); - bdrv_acct_done(s->bs, &req->acct); - g_free(req); + block_acct_done(blk_get_stats(s->blk), &req->acct); + virtio_blk_free_request(req); } - bdrv_error_action(s->bs, action, is_read, error); - return action != BDRV_ACTION_IGNORE; + blk_error_action(s->blk, action, is_read, error); + return action != BLOCK_ERROR_ACTION_IGNORE; } static void virtio_blk_rw_complete(void *opaque, int ret) @@ -77,14 +89,15 @@ static void virtio_blk_rw_complete(void *opaque, int ret) trace_virtio_blk_rw_complete(req, ret); if (ret) { - bool is_read = !(ldl_p(&req->out->type) & VIRTIO_BLK_T_OUT); + int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type); + bool is_read = !(p & VIRTIO_BLK_T_OUT); if (virtio_blk_handle_rw_error(req, -ret, is_read)) return; } virtio_blk_req_complete(req, VIRTIO_BLK_S_OK); - bdrv_acct_done(req->dev->bs, &req->acct); - g_free(req); + block_acct_done(blk_get_stats(req->dev->blk), &req->acct); + virtio_blk_free_request(req); } static void virtio_blk_flush_complete(void *opaque, int ret) @@ -98,40 +111,33 @@ static void virtio_blk_flush_complete(void *opaque, int ret) } virtio_blk_req_complete(req, VIRTIO_BLK_S_OK); - bdrv_acct_done(req->dev->bs, &req->acct); - g_free(req); -} - -static VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s) -{ - VirtIOBlockReq *req = g_malloc(sizeof(*req)); - req->dev = s; - req->qiov.size = 0; - req->next = NULL; - return req; + block_acct_done(blk_get_stats(req->dev->blk), &req->acct); + virtio_blk_free_request(req); } static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s) { VirtIOBlockReq *req = virtio_blk_alloc_request(s); - if (req != NULL) { - if (!virtqueue_pop(s->vq, &req->elem)) { - g_free(req); - return NULL; - } + if (!virtqueue_pop(s->vq, &req->elem)) { + virtio_blk_free_request(req); + return NULL; } return req; } -static void virtio_blk_handle_scsi(VirtIOBlockReq *req) +int virtio_blk_handle_scsi_req(VirtIOBlock *blk, + VirtQueueElement *elem) { + int status = VIRTIO_BLK_S_OK; + struct virtio_scsi_inhdr *scsi = NULL; + VirtIODevice *vdev = VIRTIO_DEVICE(blk); + #ifdef __linux__ - int ret; int i; + struct sg_io_hdr hdr; #endif - int status = VIRTIO_BLK_S_OK; /* * We require at least one output segment each for the virtio_blk_outhdr @@ -140,19 +146,18 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req) * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr * and the sense buffer pointer in the input segments. */ - if (req->elem.out_num < 2 || req->elem.in_num < 3) { - virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR); - g_free(req); - return; + if (elem->out_num < 2 || elem->in_num < 3) { + status = VIRTIO_BLK_S_IOERR; + goto fail; } /* * The scsi inhdr is placed in the second-to-last input segment, just * before the regular inhdr. */ - req->scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base; + scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base; - if (!req->dev->blk.scsi) { + if (!blk->conf.scsi) { status = VIRTIO_BLK_S_UNSUPP; goto fail; } @@ -160,43 +165,42 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req) /* * No support for bidirection commands yet. */ - if (req->elem.out_num > 2 && req->elem.in_num > 3) { + if (elem->out_num > 2 && elem->in_num > 3) { status = VIRTIO_BLK_S_UNSUPP; goto fail; } #ifdef __linux__ - struct sg_io_hdr hdr; memset(&hdr, 0, sizeof(struct sg_io_hdr)); hdr.interface_id = 'S'; - hdr.cmd_len = req->elem.out_sg[1].iov_len; - hdr.cmdp = req->elem.out_sg[1].iov_base; + hdr.cmd_len = elem->out_sg[1].iov_len; + hdr.cmdp = elem->out_sg[1].iov_base; hdr.dxfer_len = 0; - if (req->elem.out_num > 2) { + if (elem->out_num > 2) { /* * If there are more than the minimally required 2 output segments * there is write payload starting from the third iovec. */ hdr.dxfer_direction = SG_DXFER_TO_DEV; - hdr.iovec_count = req->elem.out_num - 2; + hdr.iovec_count = elem->out_num - 2; for (i = 0; i < hdr.iovec_count; i++) - hdr.dxfer_len += req->elem.out_sg[i + 2].iov_len; + hdr.dxfer_len += elem->out_sg[i + 2].iov_len; - hdr.dxferp = req->elem.out_sg + 2; + hdr.dxferp = elem->out_sg + 2; - } else if (req->elem.in_num > 3) { + } else if (elem->in_num > 3) { /* * If we have more than 3 input segments the guest wants to actually * read data. */ hdr.dxfer_direction = SG_DXFER_FROM_DEV; - hdr.iovec_count = req->elem.in_num - 3; + hdr.iovec_count = elem->in_num - 3; for (i = 0; i < hdr.iovec_count; i++) - hdr.dxfer_len += req->elem.in_sg[i].iov_len; + hdr.dxfer_len += elem->in_sg[i].iov_len; - hdr.dxferp = req->elem.in_sg; + hdr.dxferp = elem->in_sg; } else { /* * Some SCSI commands don't actually transfer any data. @@ -204,11 +208,11 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req) hdr.dxfer_direction = SG_DXFER_NONE; } - hdr.sbp = req->elem.in_sg[req->elem.in_num - 3].iov_base; - hdr.mx_sb_len = req->elem.in_sg[req->elem.in_num - 3].iov_len; + hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base; + hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len; - ret = bdrv_ioctl(req->dev->bs, SG_IO, &hdr); - if (ret) { + status = blk_ioctl(blk->blk, SG_IO, &hdr); + if (status) { status = VIRTIO_BLK_S_UNSUPP; goto fail; } @@ -224,33 +228,36 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req) hdr.status = CHECK_CONDITION; } - stl_p(&req->scsi->errors, - hdr.status | (hdr.msg_status << 8) | - (hdr.host_status << 16) | (hdr.driver_status << 24)); - stl_p(&req->scsi->residual, hdr.resid); - stl_p(&req->scsi->sense_len, hdr.sb_len_wr); - stl_p(&req->scsi->data_len, hdr.dxfer_len); + virtio_stl_p(vdev, &scsi->errors, + hdr.status | (hdr.msg_status << 8) | + (hdr.host_status << 16) | (hdr.driver_status << 24)); + virtio_stl_p(vdev, &scsi->residual, hdr.resid); + virtio_stl_p(vdev, &scsi->sense_len, hdr.sb_len_wr); + virtio_stl_p(vdev, &scsi->data_len, hdr.dxfer_len); - virtio_blk_req_complete(req, status); - g_free(req); - return; + return status; #else abort(); #endif fail: /* Just put anything nonzero so that the ioctl fails in the guest. */ - stl_p(&req->scsi->errors, 255); - virtio_blk_req_complete(req, status); - g_free(req); + if (scsi) { + virtio_stl_p(vdev, &scsi->errors, 255); + } + return status; } -typedef struct MultiReqBuffer { - BlockRequest blkreq[32]; - unsigned int num_writes; -} MultiReqBuffer; +static void virtio_blk_handle_scsi(VirtIOBlockReq *req) +{ + int status; + + status = virtio_blk_handle_scsi_req(req->dev, &req->elem); + virtio_blk_req_complete(req, status); + virtio_blk_free_request(req); +} -static void virtio_submit_multiwrite(BlockDriverState *bs, MultiReqBuffer *mrb) +void virtio_submit_multiwrite(BlockBackend *blk, MultiReqBuffer *mrb) { int i, ret; @@ -258,7 +265,7 @@ static void virtio_submit_multiwrite(BlockDriverState *bs, MultiReqBuffer *mrb) return; } - ret = bdrv_aio_multiwrite(bs, mrb->blkreq, mrb->num_writes); + ret = blk_aio_multiwrite(blk, mrb->blkreq, mrb->num_writes); if (ret != 0) { for (i = 0; i < mrb->num_writes; i++) { if (mrb->blkreq[i].error) { @@ -272,13 +279,33 @@ static void virtio_submit_multiwrite(BlockDriverState *bs, MultiReqBuffer *mrb) static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb) { - bdrv_acct_start(req->dev->bs, &req->acct, 0, BDRV_ACCT_FLUSH); + block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0, + BLOCK_ACCT_FLUSH); /* * Make sure all outstanding writes are posted to the backing device. */ - virtio_submit_multiwrite(req->dev->bs, mrb); - bdrv_aio_flush(req->dev->bs, virtio_blk_flush_complete, req); + virtio_submit_multiwrite(req->dev->blk, mrb); + blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req); +} + +static bool virtio_blk_sect_range_ok(VirtIOBlock *dev, + uint64_t sector, size_t size) +{ + uint64_t nb_sectors = size >> BDRV_SECTOR_BITS; + uint64_t total_sectors; + + if (sector & dev->sector_mask) { + return false; + } + if (size % dev->conf.conf.logical_block_size) { + return false; + } + blk_get_geometry(dev->blk, &total_sectors); + if (sector > total_sectors || nb_sectors > total_sectors - sector) { + return false; + } + return true; } static void virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb) @@ -286,23 +313,21 @@ static void virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb) BlockRequest *blkreq; uint64_t sector; - sector = ldq_p(&req->out->sector); - - bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_WRITE); + sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector); trace_virtio_blk_handle_write(req, sector, req->qiov.size / 512); - if (sector & req->dev->sector_mask) { - virtio_blk_rw_complete(req, -EIO); - return; - } - if (req->qiov.size % req->dev->conf->logical_block_size) { - virtio_blk_rw_complete(req, -EIO); + if (!virtio_blk_sect_range_ok(req->dev, sector, req->qiov.size)) { + virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR); + virtio_blk_free_request(req); return; } + block_acct_start(blk_get_stats(req->dev->blk), &req->acct, req->qiov.size, + BLOCK_ACCT_WRITE); + if (mrb->num_writes == 32) { - virtio_submit_multiwrite(req->dev->bs, mrb); + virtio_submit_multiwrite(req->dev->blk, mrb); } blkreq = &mrb->blkreq[mrb->num_writes]; @@ -320,45 +345,56 @@ static void virtio_blk_handle_read(VirtIOBlockReq *req) { uint64_t sector; - sector = ldq_p(&req->out->sector); - - bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_READ); + sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector); trace_virtio_blk_handle_read(req, sector, req->qiov.size / 512); - if (sector & req->dev->sector_mask) { - virtio_blk_rw_complete(req, -EIO); - return; - } - if (req->qiov.size % req->dev->conf->logical_block_size) { - virtio_blk_rw_complete(req, -EIO); + if (!virtio_blk_sect_range_ok(req->dev, sector, req->qiov.size)) { + virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR); + virtio_blk_free_request(req); return; } - bdrv_aio_readv(req->dev->bs, sector, &req->qiov, - req->qiov.size / BDRV_SECTOR_SIZE, - virtio_blk_rw_complete, req); + + block_acct_start(blk_get_stats(req->dev->blk), &req->acct, req->qiov.size, + BLOCK_ACCT_READ); + blk_aio_readv(req->dev->blk, sector, &req->qiov, + req->qiov.size / BDRV_SECTOR_SIZE, + virtio_blk_rw_complete, req); } -static void virtio_blk_handle_request(VirtIOBlockReq *req, - MultiReqBuffer *mrb) +void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb) { uint32_t type; + struct iovec *in_iov = req->elem.in_sg; + struct iovec *iov = req->elem.out_sg; + unsigned in_num = req->elem.in_num; + unsigned out_num = req->elem.out_num; if (req->elem.out_num < 1 || req->elem.in_num < 1) { error_report("virtio-blk missing headers"); exit(1); } - if (req->elem.out_sg[0].iov_len < sizeof(*req->out) || - req->elem.in_sg[req->elem.in_num - 1].iov_len < sizeof(*req->in)) { - error_report("virtio-blk header not in correct element"); + if (unlikely(iov_to_buf(iov, out_num, 0, &req->out, + sizeof(req->out)) != sizeof(req->out))) { + error_report("virtio-blk request outhdr too short"); + exit(1); + } + + iov_discard_front(&iov, &out_num, sizeof(req->out)); + + if (in_num < 1 || + in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) { + error_report("virtio-blk request inhdr too short"); exit(1); } - req->out = (void *)req->elem.out_sg[0].iov_base; - req->in = (void *)req->elem.in_sg[req->elem.in_num - 1].iov_base; + req->in = (void *)in_iov[in_num - 1].iov_base + + in_iov[in_num - 1].iov_len + - sizeof(struct virtio_blk_inhdr); + iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr)); - type = ldl_p(&req->out->type); + type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type); if (type & VIRTIO_BLK_T_FLUSH) { virtio_blk_handle_flush(req, mrb); @@ -371,23 +407,23 @@ static void virtio_blk_handle_request(VirtIOBlockReq *req, * NB: per existing s/n string convention the string is * terminated by '\0' only when shorter than buffer. */ - strncpy(req->elem.in_sg[0].iov_base, - s->blk.serial ? s->blk.serial : "", - MIN(req->elem.in_sg[0].iov_len, VIRTIO_BLK_ID_BYTES)); + const char *serial = s->conf.serial ? s->conf.serial : ""; + size_t size = MIN(strlen(serial) + 1, + MIN(iov_size(in_iov, in_num), + VIRTIO_BLK_ID_BYTES)); + iov_from_buf(in_iov, in_num, 0, serial, size); virtio_blk_req_complete(req, VIRTIO_BLK_S_OK); - g_free(req); + virtio_blk_free_request(req); } else if (type & VIRTIO_BLK_T_OUT) { - qemu_iovec_init_external(&req->qiov, &req->elem.out_sg[1], - req->elem.out_num - 1); + qemu_iovec_init_external(&req->qiov, iov, out_num); virtio_blk_handle_write(req, mrb); } else if (type == VIRTIO_BLK_T_IN || type == VIRTIO_BLK_T_BARRIER) { /* VIRTIO_BLK_T_IN is 0, so we can't just & it. */ - qemu_iovec_init_external(&req->qiov, &req->elem.in_sg[0], - req->elem.in_num - 1); + qemu_iovec_init_external(&req->qiov, in_iov, in_num); virtio_blk_handle_read(req); } else { virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP); - g_free(req); + virtio_blk_free_request(req); } } @@ -399,7 +435,6 @@ static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq) .num_writes = 0, }; -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start * dataplane here instead of waiting for .set_status(). */ @@ -407,13 +442,12 @@ static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq) virtio_blk_data_plane_start(s->dataplane); return; } -#endif while ((req = virtio_blk_get_request(s))) { virtio_blk_handle_request(req, &mrb); } - virtio_submit_multiwrite(s->bs, &mrb); + virtio_submit_multiwrite(s->blk, &mrb); /* * FIXME: Want to check for completions before returning to guest mode, @@ -436,11 +470,12 @@ static void virtio_blk_dma_restart_bh(void *opaque) s->rq = NULL; while (req) { + VirtIOBlockReq *next = req->next; virtio_blk_handle_request(req, &mrb); - req = req->next; + req = next; } - virtio_submit_multiwrite(s->bs, &mrb); + virtio_submit_multiwrite(s->blk, &mrb); } static void virtio_blk_dma_restart_cb(void *opaque, int running, @@ -453,7 +488,8 @@ static void virtio_blk_dma_restart_cb(void *opaque, int running, } if (!s->bh) { - s->bh = qemu_bh_new(virtio_blk_dma_restart_bh, s); + s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk), + virtio_blk_dma_restart_bh, s); qemu_bh_schedule(s->bh); } } @@ -462,18 +498,16 @@ static void virtio_blk_reset(VirtIODevice *vdev) { VirtIOBlock *s = VIRTIO_BLK(vdev); -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE if (s->dataplane) { virtio_blk_data_plane_stop(s->dataplane); } -#endif /* * This should cancel pending requests, but can't do nicely until there * are per-device request lists. */ - bdrv_drain_all(); - bdrv_set_enable_write_cache(s->bs, s->original_wce); + blk_drain_all(); + blk_set_enable_write_cache(s->blk, s->original_wce); } /* coalesce internal state, copy to pci i/o region 0 @@ -481,19 +515,20 @@ static void virtio_blk_reset(VirtIODevice *vdev) static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config) { VirtIOBlock *s = VIRTIO_BLK(vdev); + BlockConf *conf = &s->conf.conf; struct virtio_blk_config blkcfg; uint64_t capacity; - int blk_size = s->conf->logical_block_size; + int blk_size = conf->logical_block_size; - bdrv_get_geometry(s->bs, &capacity); + blk_get_geometry(s->blk, &capacity); memset(&blkcfg, 0, sizeof(blkcfg)); - stq_raw(&blkcfg.capacity, capacity); - stl_raw(&blkcfg.seg_max, 128 - 2); - stw_raw(&blkcfg.cylinders, s->conf->cyls); - stl_raw(&blkcfg.blk_size, blk_size); - stw_raw(&blkcfg.min_io_size, s->conf->min_io_size / blk_size); - stw_raw(&blkcfg.opt_io_size, s->conf->opt_io_size / blk_size); - blkcfg.heads = s->conf->heads; + virtio_stq_p(vdev, &blkcfg.capacity, capacity); + virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2); + virtio_stw_p(vdev, &blkcfg.cylinders, conf->cyls); + virtio_stl_p(vdev, &blkcfg.blk_size, blk_size); + virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size); + virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size); + blkcfg.heads = conf->heads; /* * We must ensure that the block device capacity is a multiple of * the logical block size. If that is not the case, let's use @@ -505,15 +540,15 @@ static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config) * divided by 512 - instead it is the amount of blk_size blocks * per track (cylinder). */ - if (bdrv_getlength(s->bs) / s->conf->heads / s->conf->secs % blk_size) { - blkcfg.sectors = s->conf->secs & ~s->sector_mask; + if (blk_getlength(s->blk) / conf->heads / conf->secs % blk_size) { + blkcfg.sectors = conf->secs & ~s->sector_mask; } else { - blkcfg.sectors = s->conf->secs; + blkcfg.sectors = conf->secs; } blkcfg.size_max = 0; - blkcfg.physical_block_exp = get_physical_block_exp(s->conf); + blkcfg.physical_block_exp = get_physical_block_exp(conf); blkcfg.alignment_offset = 0; - blkcfg.wce = bdrv_enable_write_cache(s->bs); + blkcfg.wce = blk_enable_write_cache(s->blk); memcpy(config, &blkcfg, sizeof(struct virtio_blk_config)); } @@ -523,7 +558,10 @@ static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config) struct virtio_blk_config blkcfg; memcpy(&blkcfg, config, sizeof(blkcfg)); - bdrv_set_enable_write_cache(s->bs, blkcfg.wce != 0); + + aio_context_acquire(blk_get_aio_context(s->blk)); + blk_set_enable_write_cache(s->blk, blkcfg.wce != 0); + aio_context_release(blk_get_aio_context(s->blk)); } static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features) @@ -536,14 +574,15 @@ static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features) features |= (1 << VIRTIO_BLK_F_BLK_SIZE); features |= (1 << VIRTIO_BLK_F_SCSI); - if (s->blk.config_wce) { + if (s->conf.config_wce) { features |= (1 << VIRTIO_BLK_F_CONFIG_WCE); } - if (bdrv_enable_write_cache(s->bs)) + if (blk_enable_write_cache(s->blk)) { features |= (1 << VIRTIO_BLK_F_WCE); - - if (bdrv_is_read_only(s->bs)) + } + if (blk_is_read_only(s->blk)) { features |= 1 << VIRTIO_BLK_F_RO; + } return features; } @@ -553,12 +592,10 @@ static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status) VirtIOBlock *s = VIRTIO_BLK(vdev); uint32_t features; -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) { virtio_blk_data_plane_stop(s->dataplane); } -#endif if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) { return; @@ -579,24 +616,32 @@ static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status) * Guest writes 1 to the WCE configuration field (writeback mode) * Guest sets DRIVER_OK bit in status field * - * s->bs would erroneously be placed in writethrough mode. + * s->blk would erroneously be placed in writethrough mode. */ if (!(features & (1 << VIRTIO_BLK_F_CONFIG_WCE))) { - bdrv_set_enable_write_cache(s->bs, !!(features & (1 << VIRTIO_BLK_F_WCE))); + aio_context_acquire(blk_get_aio_context(s->blk)); + blk_set_enable_write_cache(s->blk, + !!(features & (1 << VIRTIO_BLK_F_WCE))); + aio_context_release(blk_get_aio_context(s->blk)); } } static void virtio_blk_save(QEMUFile *f, void *opaque) { - VirtIOBlock *s = opaque; - VirtIODevice *vdev = VIRTIO_DEVICE(s); - VirtIOBlockReq *req = s->rq; + VirtIODevice *vdev = VIRTIO_DEVICE(opaque); virtio_save(vdev, f); +} +static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f) +{ + VirtIOBlock *s = VIRTIO_BLK(vdev); + VirtIOBlockReq *req = s->rq; + while (req) { qemu_put_sbyte(f, 1); - qemu_put_buffer(f, (unsigned char*)&req->elem, sizeof(req->elem)); + qemu_put_buffer(f, (unsigned char *)&req->elem, + sizeof(VirtQueueElement)); req = req->next; } qemu_put_sbyte(f, 0); @@ -606,19 +651,22 @@ static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id) { VirtIOBlock *s = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(s); - int ret; if (version_id != 2) return -EINVAL; - ret = virtio_load(vdev, f); - if (ret) { - return ret; - } + return virtio_load(vdev, f, version_id); +} + +static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f, + int version_id) +{ + VirtIOBlock *s = VIRTIO_BLK(vdev); while (qemu_get_sbyte(f)) { VirtIOBlockReq *req = virtio_blk_alloc_request(s); - qemu_get_buffer(f, (unsigned char*)&req->elem, sizeof(req->elem)); + qemu_get_buffer(f, (unsigned char *)&req->elem, + sizeof(VirtQueueElement)); req->next = s->rq; s->rq = req; @@ -642,13 +690,6 @@ static const BlockDevOps virtio_block_ops = { .resize_cb = virtio_blk_resize, }; -void virtio_blk_set_conf(DeviceState *dev, VirtIOBlkConf *blk) -{ - VirtIOBlock *s = VIRTIO_BLK(dev); - memcpy(&(s->blk), blk, sizeof(struct VirtIOBlkConf)); -} - -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE /* Disable dataplane thread during live migration since it does not * update the dirty memory bitmap yet. */ @@ -670,8 +711,8 @@ static void virtio_blk_migration_state_changed(Notifier *notifier, void *data) if (s->dataplane) { return; } - bdrv_drain_all(); /* complete in-flight non-dataplane requests */ - virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->blk, + blk_drain_all(); /* complete in-flight non-dataplane requests */ + virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf, &s->dataplane, &err); if (err != NULL) { error_report("%s", error_get_pretty(err)); @@ -679,45 +720,42 @@ static void virtio_blk_migration_state_changed(Notifier *notifier, void *data) } } } -#endif /* CONFIG_VIRTIO_BLK_DATA_PLANE */ static void virtio_blk_device_realize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOBlock *s = VIRTIO_BLK(dev); - VirtIOBlkConf *blk = &(s->blk); -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE + VirtIOBlkConf *conf = &s->conf; Error *err = NULL; -#endif static int virtio_blk_id; - if (!blk->conf.bs) { + if (!conf->conf.blk) { error_setg(errp, "drive property not set"); return; } - if (!bdrv_is_inserted(blk->conf.bs)) { + if (!blk_is_inserted(conf->conf.blk)) { error_setg(errp, "Device needs media, but drive is empty"); return; } - blkconf_serial(&blk->conf, &blk->serial); - s->original_wce = bdrv_enable_write_cache(blk->conf.bs); - if (blkconf_geometry(&blk->conf, NULL, 65535, 255, 255) < 0) { - error_setg(errp, "Error setting geometry"); + blkconf_serial(&conf->conf, &conf->serial); + s->original_wce = blk_enable_write_cache(conf->conf.blk); + blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err); + if (err) { + error_propagate(errp, err); return; } virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK, sizeof(struct virtio_blk_config)); - s->bs = blk->conf.bs; - s->conf = &blk->conf; + s->blk = conf->conf.blk; s->rq = NULL; - s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1; + s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1; s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output); -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE - virtio_blk_data_plane_create(vdev, blk, &s->dataplane, &err); + s->complete_request = virtio_blk_complete_request; + virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err); if (err != NULL) { error_propagate(errp, err); virtio_cleanup(vdev); @@ -725,17 +763,14 @@ static void virtio_blk_device_realize(DeviceState *dev, Error **errp) } s->migration_state_notifier.notify = virtio_blk_migration_state_changed; add_migration_state_change_notifier(&s->migration_state_notifier); -#endif s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s); register_savevm(dev, "virtio-blk", virtio_blk_id++, 2, virtio_blk_save, virtio_blk_load, s); - bdrv_set_dev_ops(s->bs, &virtio_block_ops, s); - bdrv_set_guest_block_size(s->bs, s->conf->logical_block_size); - - bdrv_iostatus_enable(s->bs); + blk_set_dev_ops(s->blk, &virtio_block_ops, s); + blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size); - add_boot_device_path(s->conf->bootindex, dev, "/disk@0,0"); + blk_iostatus_enable(s->blk); } static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp) @@ -743,19 +778,37 @@ static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp) VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOBlock *s = VIRTIO_BLK(dev); -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE remove_migration_state_change_notifier(&s->migration_state_notifier); virtio_blk_data_plane_destroy(s->dataplane); s->dataplane = NULL; -#endif qemu_del_vm_change_state_handler(s->change); unregister_savevm(dev, "virtio-blk", s); - blockdev_mark_auto_del(s->bs); + blockdev_mark_auto_del(s->blk); virtio_cleanup(vdev); } +static void virtio_blk_instance_init(Object *obj) +{ + VirtIOBlock *s = VIRTIO_BLK(obj); + + object_property_add_link(obj, "iothread", TYPE_IOTHREAD, + (Object **)&s->conf.iothread, + qdev_prop_allow_set_link_before_realize, + OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL); + device_add_bootindex_property(obj, &s->conf.conf.bootindex, + "bootindex", "/disk@0,0", + DEVICE(obj), NULL); +} + static Property virtio_blk_properties[] = { - DEFINE_VIRTIO_BLK_PROPERTIES(VirtIOBlock, blk), + DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf), + DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf), + DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial), + DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true), +#ifdef __linux__ + DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, true), +#endif + DEFINE_PROP_BIT("x-data-plane", VirtIOBlock, conf.data_plane, 0, false), DEFINE_PROP_END_OF_LIST(), }; @@ -773,12 +826,15 @@ static void virtio_blk_class_init(ObjectClass *klass, void *data) vdc->get_features = virtio_blk_get_features; vdc->set_status = virtio_blk_set_status; vdc->reset = virtio_blk_reset; + vdc->save = virtio_blk_save_device; + vdc->load = virtio_blk_load_device; } static const TypeInfo virtio_device_info = { .name = TYPE_VIRTIO_BLK, .parent = TYPE_VIRTIO_DEVICE, .instance_size = sizeof(VirtIOBlock), + .instance_init = virtio_blk_instance_init, .class_init = virtio_blk_class_init, }; diff --git a/hw/block/xen_blkif.h b/hw/block/xen_blkif.h index c0f4136228..711b692742 100644 --- a/hw/block/xen_blkif.h +++ b/hw/block/xen_blkif.h @@ -79,6 +79,12 @@ static inline void blkif_get_x86_32_req(blkif_request_t *dst, blkif_x86_32_reque dst->handle = src->handle; dst->id = src->id; dst->sector_number = src->sector_number; + if (src->operation == BLKIF_OP_DISCARD) { + struct blkif_request_discard *s = (void *)src; + struct blkif_request_discard *d = (void *)dst; + d->nr_sectors = s->nr_sectors; + return; + } if (n > src->nr_segments) n = src->nr_segments; for (i = 0; i < n; i++) @@ -94,6 +100,12 @@ static inline void blkif_get_x86_64_req(blkif_request_t *dst, blkif_x86_64_reque dst->handle = src->handle; dst->id = src->id; dst->sector_number = src->sector_number; + if (src->operation == BLKIF_OP_DISCARD) { + struct blkif_request_discard *s = (void *)src; + struct blkif_request_discard *d = (void *)dst; + d->nr_sectors = s->nr_sectors; + return; + } if (n > src->nr_segments) n = src->nr_segments; for (i = 0; i < n; i++) diff --git a/hw/block/xen_disk.c b/hw/block/xen_disk.c index bc061e6403..21842a01e7 100644 --- a/hw/block/xen_disk.c +++ b/hw/block/xen_disk.c @@ -39,6 +39,7 @@ #include "hw/xen/xen_backend.h" #include "xen_blkif.h" #include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" /* ------------------------------------------------------------- */ @@ -58,6 +59,13 @@ struct PersistentGrant { typedef struct PersistentGrant PersistentGrant; +struct PersistentRegion { + void *addr; + int num; +}; + +typedef struct PersistentRegion PersistentRegion; + struct ioreq { blkif_request_t req; int16_t status; @@ -114,14 +122,16 @@ struct XenBlkDev { int requests_finished; /* Persistent grants extension */ + gboolean feature_discard; gboolean feature_persistent; GTree *persistent_gnts; + GSList *persistent_regions; unsigned int persistent_gnt_count; unsigned int max_grants; /* qemu block driver */ DriveInfo *dinfo; - BlockDriverState *bs; + BlockBackend *blk; QEMUBH *bh; }; @@ -175,6 +185,23 @@ static void destroy_grant(gpointer pgnt) g_free(grant); } +static void remove_persistent_region(gpointer data, gpointer dev) +{ + PersistentRegion *region = data; + struct XenBlkDev *blkdev = dev; + XenGnttab gnt = blkdev->xendev.gnttabdev; + + if (xc_gnttab_munmap(gnt, region->addr, region->num) != 0) { + xen_be_printf(&blkdev->xendev, 0, + "xc_gnttab_munmap region %p failed: %s\n", + region->addr, strerror(errno)); + } + xen_be_printf(&blkdev->xendev, 3, + "unmapped grant region %p with %d pages\n", + region->addr, region->num); + g_free(region); +} + static struct ioreq *ioreq_start(struct XenBlkDev *blkdev) { struct ioreq *ioreq = NULL; @@ -253,6 +280,8 @@ static int ioreq_parse(struct ioreq *ioreq) case BLKIF_OP_WRITE: ioreq->prot = PROT_READ; /* from memory */ break; + case BLKIF_OP_DISCARD: + return 0; default: xen_be_printf(&blkdev->xendev, 0, "error: unknown operation (%d)\n", ioreq->req.operation); @@ -339,6 +368,7 @@ static int ioreq_map(struct ioreq *ioreq) void *page[BLKIF_MAX_SEGMENTS_PER_REQUEST]; int i, j, new_maps = 0; PersistentGrant *grant; + PersistentRegion *region; /* domids and refs variables will contain the information necessary * to map the grants that are needed to fulfill this request. * @@ -417,7 +447,22 @@ static int ioreq_map(struct ioreq *ioreq) } } } - if (ioreq->blkdev->feature_persistent) { + if (ioreq->blkdev->feature_persistent && new_maps != 0 && + (!batch_maps || (ioreq->blkdev->persistent_gnt_count + new_maps <= + ioreq->blkdev->max_grants))) { + /* + * If we are using persistent grants and batch mappings only + * add the new maps to the list of persistent grants if the whole + * area can be persistently mapped. + */ + if (batch_maps) { + region = g_malloc0(sizeof(*region)); + region->addr = ioreq->pages; + region->num = new_maps; + ioreq->blkdev->persistent_regions = g_slist_append( + ioreq->blkdev->persistent_regions, + region); + } while ((ioreq->blkdev->persistent_gnt_count < ioreq->blkdev->max_grants) && new_maps) { /* Go through the list of newly mapped grants and add as many @@ -443,6 +488,7 @@ static int ioreq_map(struct ioreq *ioreq) grant); ioreq->blkdev->persistent_gnt_count++; } + assert(!batch_maps || new_maps == 0); } for (i = 0; i < ioreq->v.niov; i++) { ioreq->v.iov[i].iov_base += (uintptr_t)page[i]; @@ -476,7 +522,7 @@ static void qemu_aio_complete(void *opaque, int ret) if (ioreq->postsync) { ioreq->postsync = 0; ioreq->aio_inflight++; - bdrv_aio_flush(ioreq->blkdev->bs, qemu_aio_complete, ioreq); + blk_aio_flush(ioreq->blkdev->blk, qemu_aio_complete, ioreq); return; } @@ -490,8 +536,9 @@ static void qemu_aio_complete(void *opaque, int ret) break; } case BLKIF_OP_READ: - bdrv_acct_done(ioreq->blkdev->bs, &ioreq->acct); + block_acct_done(blk_get_stats(ioreq->blkdev->blk), &ioreq->acct); break; + case BLKIF_OP_DISCARD: default: break; } @@ -508,17 +555,18 @@ static int ioreq_runio_qemu_aio(struct ioreq *ioreq) ioreq->aio_inflight++; if (ioreq->presync) { - bdrv_aio_flush(ioreq->blkdev->bs, qemu_aio_complete, ioreq); + blk_aio_flush(ioreq->blkdev->blk, qemu_aio_complete, ioreq); return 0; } switch (ioreq->req.operation) { case BLKIF_OP_READ: - bdrv_acct_start(blkdev->bs, &ioreq->acct, ioreq->v.size, BDRV_ACCT_READ); + block_acct_start(blk_get_stats(blkdev->blk), &ioreq->acct, + ioreq->v.size, BLOCK_ACCT_READ); ioreq->aio_inflight++; - bdrv_aio_readv(blkdev->bs, ioreq->start / BLOCK_SIZE, - &ioreq->v, ioreq->v.size / BLOCK_SIZE, - qemu_aio_complete, ioreq); + blk_aio_readv(blkdev->blk, ioreq->start / BLOCK_SIZE, + &ioreq->v, ioreq->v.size / BLOCK_SIZE, + qemu_aio_complete, ioreq); break; case BLKIF_OP_WRITE: case BLKIF_OP_FLUSH_DISKCACHE: @@ -526,12 +574,22 @@ static int ioreq_runio_qemu_aio(struct ioreq *ioreq) break; } - bdrv_acct_start(blkdev->bs, &ioreq->acct, ioreq->v.size, BDRV_ACCT_WRITE); + block_acct_start(blk_get_stats(blkdev->blk), &ioreq->acct, + ioreq->v.size, BLOCK_ACCT_WRITE); ioreq->aio_inflight++; - bdrv_aio_writev(blkdev->bs, ioreq->start / BLOCK_SIZE, - &ioreq->v, ioreq->v.size / BLOCK_SIZE, + blk_aio_writev(blkdev->blk, ioreq->start / BLOCK_SIZE, + &ioreq->v, ioreq->v.size / BLOCK_SIZE, + qemu_aio_complete, ioreq); + break; + case BLKIF_OP_DISCARD: + { + struct blkif_request_discard *discard_req = (void *)&ioreq->req; + ioreq->aio_inflight++; + blk_aio_discard(blkdev->blk, + discard_req->sector_number, discard_req->nr_sectors, qemu_aio_complete, ioreq); break; + } default: /* unknown operation (shouldn't happen -- parse catches this) */ goto err; @@ -576,6 +634,7 @@ static int blk_send_response_one(struct ioreq *ioreq) break; default: dst = NULL; + return 0; } memcpy(dst, &resp, sizeof(resp)); blkdev->rings.common.rsp_prod_pvt++; @@ -710,6 +769,21 @@ static void blk_alloc(struct XenDevice *xendev) } } +static void blk_parse_discard(struct XenBlkDev *blkdev) +{ + int enable; + + blkdev->feature_discard = true; + + if (xenstore_read_be_int(&blkdev->xendev, "discard-enable", &enable) == 0) { + blkdev->feature_discard = !!enable; + } + + if (blkdev->feature_discard) { + xenstore_write_be_int(&blkdev->xendev, "feature-discard", 1); + } +} + static int blk_init(struct XenDevice *xendev) { struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev); @@ -777,6 +851,8 @@ static int blk_init(struct XenDevice *xendev) xenstore_write_be_int(&blkdev->xendev, "feature-persistent", 1); xenstore_write_be_int(&blkdev->xendev, "info", info); + blk_parse_discard(blkdev); + g_free(directiosafe); return 0; @@ -812,50 +888,58 @@ static int blk_connect(struct XenDevice *xendev) qflags |= BDRV_O_RDWR; readonly = false; } + if (blkdev->feature_discard) { + qflags |= BDRV_O_UNMAP; + } /* init qemu block driver */ index = (blkdev->xendev.dev - 202 * 256) / 16; blkdev->dinfo = drive_get(IF_XEN, 0, index); if (!blkdev->dinfo) { + Error *local_err = NULL; + BlockBackend *blk; + BlockDriver *drv; + BlockDriverState *bs; + /* setup via xenbus -> create new block driver instance */ xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n"); - blkdev->bs = bdrv_new(blkdev->dev); - if (blkdev->bs) { - Error *local_err = NULL; - BlockDriver *drv = bdrv_find_whitelisted_format(blkdev->fileproto, - readonly); - if (bdrv_open(&blkdev->bs, blkdev->filename, NULL, NULL, qflags, - drv, &local_err) != 0) - { - xen_be_printf(&blkdev->xendev, 0, "error: %s\n", - error_get_pretty(local_err)); - error_free(local_err); - bdrv_unref(blkdev->bs); - blkdev->bs = NULL; - } + blk = blk_new_with_bs(blkdev->dev, NULL); + if (!blk) { + return -1; } - if (!blkdev->bs) { + blkdev->blk = blk; + + bs = blk_bs(blk); + drv = bdrv_find_whitelisted_format(blkdev->fileproto, readonly); + if (bdrv_open(&bs, blkdev->filename, NULL, NULL, qflags, + drv, &local_err) != 0) { + xen_be_printf(&blkdev->xendev, 0, "error: %s\n", + error_get_pretty(local_err)); + error_free(local_err); + blk_unref(blk); + blkdev->blk = NULL; return -1; } + assert(bs == blk_bs(blk)); } else { /* setup via qemu cmdline -> already setup for us */ xen_be_printf(&blkdev->xendev, 2, "get configured bdrv (cmdline setup)\n"); - blkdev->bs = blkdev->dinfo->bdrv; - if (bdrv_is_read_only(blkdev->bs) && !readonly) { + blkdev->blk = blk_by_legacy_dinfo(blkdev->dinfo); + if (blk_is_read_only(blkdev->blk) && !readonly) { xen_be_printf(&blkdev->xendev, 0, "Unexpected read-only drive"); - blkdev->bs = NULL; + blkdev->blk = NULL; return -1; } - /* blkdev->bs is not create by us, we get a reference - * so we can bdrv_unref() unconditionally */ - bdrv_ref(blkdev->bs); + /* blkdev->blk is not create by us, we get a reference + * so we can blk_unref() unconditionally */ + blk_ref(blkdev->blk); } - bdrv_attach_dev_nofail(blkdev->bs, blkdev); - blkdev->file_size = bdrv_getlength(blkdev->bs); + blk_attach_dev_nofail(blkdev->blk, blkdev); + blkdev->file_size = blk_getlength(blkdev->blk); if (blkdev->file_size < 0) { - xen_be_printf(&blkdev->xendev, 1, "bdrv_getlength: %d (%s) | drv %s\n", + xen_be_printf(&blkdev->xendev, 1, "blk_getlength: %d (%s) | drv %s\n", (int)blkdev->file_size, strerror(-blkdev->file_size), - bdrv_get_format_name(blkdev->bs) ?: "-"); + bdrv_get_format_name(blk_bs(blkdev->blk)) ?: "-"); blkdev->file_size = 0; } @@ -929,7 +1013,10 @@ static int blk_connect(struct XenDevice *xendev) blkdev->max_grants = max_requests * BLKIF_MAX_SEGMENTS_PER_REQUEST; blkdev->persistent_gnts = g_tree_new_full((GCompareDataFunc)int_cmp, NULL, NULL, + batch_maps ? + (GDestroyNotify)g_free : (GDestroyNotify)destroy_grant); + blkdev->persistent_regions = NULL; blkdev->persistent_gnt_count = 0; } @@ -946,10 +1033,10 @@ static void blk_disconnect(struct XenDevice *xendev) { struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev); - if (blkdev->bs) { - bdrv_detach_dev(blkdev->bs, blkdev); - bdrv_unref(blkdev->bs); - blkdev->bs = NULL; + if (blkdev->blk) { + blk_detach_dev(blkdev->blk, blkdev); + blk_unref(blkdev->blk); + blkdev->blk = NULL; } xen_be_unbind_evtchn(&blkdev->xendev); @@ -958,6 +1045,26 @@ static void blk_disconnect(struct XenDevice *xendev) blkdev->cnt_map--; blkdev->sring = NULL; } + + /* + * Unmap persistent grants before switching to the closed state + * so the frontend can free them. + * + * In the !batch_maps case g_tree_destroy will take care of unmapping + * the grant, but in the batch_maps case we need to iterate over every + * region in persistent_regions and unmap it. + */ + if (blkdev->feature_persistent) { + g_tree_destroy(blkdev->persistent_gnts); + assert(batch_maps || blkdev->persistent_gnt_count == 0); + if (batch_maps) { + blkdev->persistent_gnt_count = 0; + g_slist_foreach(blkdev->persistent_regions, + (GFunc)remove_persistent_region, blkdev); + g_slist_free(blkdev->persistent_regions); + } + blkdev->feature_persistent = false; + } } static int blk_free(struct XenDevice *xendev) @@ -965,15 +1072,10 @@ static int blk_free(struct XenDevice *xendev) struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev); struct ioreq *ioreq; - if (blkdev->bs || blkdev->sring) { + if (blkdev->blk || blkdev->sring) { blk_disconnect(xendev); } - /* Free persistent grants */ - if (blkdev->feature_persistent) { - g_tree_destroy(blkdev->persistent_gnts); - } - while (!QLIST_EMPTY(&blkdev->freelist)) { ioreq = QLIST_FIRST(&blkdev->freelist); QLIST_REMOVE(ioreq, list); diff --git a/hw/bt/l2cap.c b/hw/bt/l2cap.c index 2301d6f87f..591e047781 100644 --- a/hw/bt/l2cap.c +++ b/hw/bt/l2cap.c @@ -429,7 +429,7 @@ static struct l2cap_chan_s *l2cap_channel_open(struct l2cap_instance_s *l2cap, status = L2CAP_CS_NO_INFO; } else { g_free(ch); - + ch = NULL; result = L2CAP_CR_NO_MEM; status = L2CAP_CS_NO_INFO; } diff --git a/hw/char/cadence_uart.c b/hw/char/cadence_uart.c index 1012f1ad64..a5736cbc07 100644 --- a/hw/char/cadence_uart.c +++ b/hw/char/cadence_uart.c @@ -175,8 +175,10 @@ static void uart_send_breaks(UartState *s) { int break_enabled = 1; - qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK, - &break_enabled); + if (s->chr) { + qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK, + &break_enabled); + } } static void uart_parameters_setup(UartState *s) @@ -227,7 +229,9 @@ static void uart_parameters_setup(UartState *s) packet_size += ssp.data_bits + ssp.stop_bits; s->char_tx_time = (get_ticks_per_sec() / ssp.speed) * packet_size; - qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp); + if (s->chr) { + qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp); + } } static int uart_can_receive(void *opaque) @@ -295,6 +299,7 @@ static gboolean cadence_uart_xmit(GIOChannel *chan, GIOCondition cond, /* instant drain the fifo when there's no back-end */ if (!s->chr) { s->tx_count = 0; + return FALSE; } if (!s->tx_count) { @@ -306,7 +311,8 @@ static gboolean cadence_uart_xmit(GIOChannel *chan, GIOCondition cond, memmove(s->tx_fifo, s->tx_fifo + ret, s->tx_count); if (s->tx_count) { - int r = qemu_chr_fe_add_watch(s->chr, G_IO_OUT, cadence_uart_xmit, s); + int r = qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP, + cadence_uart_xmit, s); assert(r); } @@ -374,7 +380,9 @@ static void uart_read_rx_fifo(UartState *s, uint32_t *c) *c = s->rx_fifo[rx_rpos]; s->rx_count--; - qemu_chr_accept_input(s->chr); + if (s->chr) { + qemu_chr_accept_input(s->chr); + } } else { *c = 0; } @@ -504,7 +512,6 @@ static const VMStateDescription vmstate_cadence_uart = { .name = "cadence_uart", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = cadence_uart_post_load, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(r, UartState, R_MAX), diff --git a/hw/char/digic-uart.c b/hw/char/digic-uart.c index fd8e07713d..8abe944de6 100644 --- a/hw/char/digic-uart.c +++ b/hw/char/digic-uart.c @@ -162,7 +162,6 @@ static const VMStateDescription vmstate_digic_uart = { .name = "digic-uart", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(reg_rx, DigicUartState), VMSTATE_UINT32(reg_st, DigicUartState), diff --git a/hw/char/escc.c b/hw/char/escc.c index 6397f6f282..ba653efd68 100644 --- a/hw/char/escc.c +++ b/hw/char/escc.c @@ -27,6 +27,7 @@ #include "hw/char/escc.h" #include "sysemu/char.h" #include "ui/console.h" +#include "ui/input.h" #include "trace.h" /* @@ -94,6 +95,7 @@ typedef struct ChannelState { ChnID chn; // this channel, A (base+4) or B (base+0) ChnType type; uint8_t rx, tx; + QemuInputHandlerState *hs; } ChannelState; #define ESCC(obj) OBJECT_CHECK(ESCCState, (obj), TYPE_ESCC) @@ -658,8 +660,7 @@ static const VMStateDescription vmstate_escc_chn = { .name ="escc_chn", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(vmstate_dummy, ChannelState), VMSTATE_UINT32(reg, ChannelState), VMSTATE_UINT32(rxint, ChannelState), @@ -678,8 +679,7 @@ static const VMStateDescription vmstate_escc = { .name ="escc", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(chn, ESCCState, 2, 2, vmstate_escc_chn, ChannelState), VMSTATE_END_OF_LIST() @@ -714,71 +714,181 @@ MemoryRegion *escc_init(hwaddr base, qemu_irq irqA, qemu_irq irqB, return &d->mmio; } -static const uint8_t keycodes[128] = { - 127, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 89, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 42, 99, 88, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 47, 19, 121, 119, 5, 6, 8, 10, 12, - 14, 16, 17, 18, 7, 98, 23, 68, 69, 70, 71, 91, 92, 93, 125, 112, - 113, 114, 94, 50, 0, 0, 124, 9, 11, 0, 0, 0, 0, 0, 0, 0, - 90, 0, 46, 22, 13, 111, 52, 20, 96, 24, 28, 74, 27, 123, 44, 66, - 0, 45, 2, 4, 48, 0, 0, 21, 0, 0, 0, 0, 0, 120, 122, 67, +static const uint8_t qcode_to_keycode[Q_KEY_CODE_MAX] = { + [Q_KEY_CODE_SHIFT] = 99, + [Q_KEY_CODE_SHIFT_R] = 110, + [Q_KEY_CODE_ALT] = 19, + [Q_KEY_CODE_ALT_R] = 13, + [Q_KEY_CODE_ALTGR] = 13, + [Q_KEY_CODE_CTRL] = 76, + [Q_KEY_CODE_CTRL_R] = 76, + [Q_KEY_CODE_ESC] = 29, + [Q_KEY_CODE_1] = 30, + [Q_KEY_CODE_2] = 31, + [Q_KEY_CODE_3] = 32, + [Q_KEY_CODE_4] = 33, + [Q_KEY_CODE_5] = 34, + [Q_KEY_CODE_6] = 35, + [Q_KEY_CODE_7] = 36, + [Q_KEY_CODE_8] = 37, + [Q_KEY_CODE_9] = 38, + [Q_KEY_CODE_0] = 39, + [Q_KEY_CODE_MINUS] = 40, + [Q_KEY_CODE_EQUAL] = 41, + [Q_KEY_CODE_BACKSPACE] = 43, + [Q_KEY_CODE_TAB] = 53, + [Q_KEY_CODE_Q] = 54, + [Q_KEY_CODE_W] = 55, + [Q_KEY_CODE_E] = 56, + [Q_KEY_CODE_R] = 57, + [Q_KEY_CODE_T] = 58, + [Q_KEY_CODE_Y] = 59, + [Q_KEY_CODE_U] = 60, + [Q_KEY_CODE_I] = 61, + [Q_KEY_CODE_O] = 62, + [Q_KEY_CODE_P] = 63, + [Q_KEY_CODE_BRACKET_LEFT] = 64, + [Q_KEY_CODE_BRACKET_RIGHT] = 65, + [Q_KEY_CODE_RET] = 89, + [Q_KEY_CODE_A] = 77, + [Q_KEY_CODE_S] = 78, + [Q_KEY_CODE_D] = 79, + [Q_KEY_CODE_F] = 80, + [Q_KEY_CODE_G] = 81, + [Q_KEY_CODE_H] = 82, + [Q_KEY_CODE_J] = 83, + [Q_KEY_CODE_K] = 84, + [Q_KEY_CODE_L] = 85, + [Q_KEY_CODE_SEMICOLON] = 86, + [Q_KEY_CODE_APOSTROPHE] = 87, + [Q_KEY_CODE_GRAVE_ACCENT] = 42, + [Q_KEY_CODE_BACKSLASH] = 88, + [Q_KEY_CODE_Z] = 100, + [Q_KEY_CODE_X] = 101, + [Q_KEY_CODE_C] = 102, + [Q_KEY_CODE_V] = 103, + [Q_KEY_CODE_B] = 104, + [Q_KEY_CODE_N] = 105, + [Q_KEY_CODE_M] = 106, + [Q_KEY_CODE_COMMA] = 107, + [Q_KEY_CODE_DOT] = 108, + [Q_KEY_CODE_SLASH] = 109, + [Q_KEY_CODE_ASTERISK] = 47, + [Q_KEY_CODE_SPC] = 121, + [Q_KEY_CODE_CAPS_LOCK] = 119, + [Q_KEY_CODE_F1] = 5, + [Q_KEY_CODE_F2] = 6, + [Q_KEY_CODE_F3] = 8, + [Q_KEY_CODE_F4] = 10, + [Q_KEY_CODE_F5] = 12, + [Q_KEY_CODE_F6] = 14, + [Q_KEY_CODE_F7] = 16, + [Q_KEY_CODE_F8] = 17, + [Q_KEY_CODE_F9] = 18, + [Q_KEY_CODE_F10] = 7, + [Q_KEY_CODE_NUM_LOCK] = 98, + [Q_KEY_CODE_SCROLL_LOCK] = 23, + [Q_KEY_CODE_KP_DIVIDE] = 46, + [Q_KEY_CODE_KP_MULTIPLY] = 47, + [Q_KEY_CODE_KP_SUBTRACT] = 71, + [Q_KEY_CODE_KP_ADD] = 125, + [Q_KEY_CODE_KP_ENTER] = 90, + [Q_KEY_CODE_KP_DECIMAL] = 50, + [Q_KEY_CODE_KP_0] = 94, + [Q_KEY_CODE_KP_1] = 112, + [Q_KEY_CODE_KP_2] = 113, + [Q_KEY_CODE_KP_3] = 114, + [Q_KEY_CODE_KP_4] = 91, + [Q_KEY_CODE_KP_5] = 92, + [Q_KEY_CODE_KP_6] = 93, + [Q_KEY_CODE_KP_7] = 68, + [Q_KEY_CODE_KP_8] = 69, + [Q_KEY_CODE_KP_9] = 70, + [Q_KEY_CODE_LESS] = 124, + [Q_KEY_CODE_F11] = 9, + [Q_KEY_CODE_F12] = 11, + [Q_KEY_CODE_HOME] = 52, + [Q_KEY_CODE_PGUP] = 96, + [Q_KEY_CODE_PGDN] = 123, + [Q_KEY_CODE_END] = 74, + [Q_KEY_CODE_LEFT] = 24, + [Q_KEY_CODE_UP] = 20, + [Q_KEY_CODE_DOWN] = 27, + [Q_KEY_CODE_RIGHT] = 28, + [Q_KEY_CODE_INSERT] = 44, + [Q_KEY_CODE_DELETE] = 66, + [Q_KEY_CODE_STOP] = 1, + [Q_KEY_CODE_AGAIN] = 3, + [Q_KEY_CODE_PROPS] = 25, + [Q_KEY_CODE_UNDO] = 26, + [Q_KEY_CODE_FRONT] = 49, + [Q_KEY_CODE_COPY] = 51, + [Q_KEY_CODE_OPEN] = 72, + [Q_KEY_CODE_PASTE] = 73, + [Q_KEY_CODE_FIND] = 95, + [Q_KEY_CODE_CUT] = 97, + [Q_KEY_CODE_LF] = 111, + [Q_KEY_CODE_HELP] = 118, + [Q_KEY_CODE_META_L] = 120, + [Q_KEY_CODE_META_R] = 122, + [Q_KEY_CODE_COMPOSE] = 67, + [Q_KEY_CODE_PRINT] = 22, + [Q_KEY_CODE_SYSRQ] = 21, }; -static const uint8_t e0_keycodes[128] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 76, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 109, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 68, 69, 70, 0, 91, 0, 93, 0, 112, - 113, 114, 94, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 3, 25, 26, 49, 52, 72, 73, 97, 99, 111, 118, 120, 122, 67, 0, -}; - -static void sunkbd_event(void *opaque, int ch) +static void sunkbd_handle_event(DeviceState *dev, QemuConsole *src, + InputEvent *evt) { - ChannelState *s = opaque; - int release = ch & 0x80; - - trace_escc_sunkbd_event_in(ch); - switch (ch) { - case 58: // Caps lock press - s->caps_lock_mode ^= 1; - if (s->caps_lock_mode == 2) - return; // Drop second press - break; - case 69: // Num lock press - s->num_lock_mode ^= 1; - if (s->num_lock_mode == 2) - return; // Drop second press - break; - case 186: // Caps lock release - s->caps_lock_mode ^= 2; - if (s->caps_lock_mode == 3) - return; // Drop first release - break; - case 197: // Num lock release - s->num_lock_mode ^= 2; - if (s->num_lock_mode == 3) - return; // Drop first release - break; - case 0xe0: - s->e0_mode = 1; - return; - default: - break; + ChannelState *s = (ChannelState *)dev; + int qcode, keycode; + + assert(evt->kind == INPUT_EVENT_KIND_KEY); + qcode = qemu_input_key_value_to_qcode(evt->key->key); + trace_escc_sunkbd_event_in(qcode, QKeyCode_lookup[qcode], + evt->key->down); + + if (qcode == Q_KEY_CODE_CAPS_LOCK) { + if (evt->key->down) { + s->caps_lock_mode ^= 1; + if (s->caps_lock_mode == 2) { + return; /* Drop second press */ + } + } else { + s->caps_lock_mode ^= 2; + if (s->caps_lock_mode == 3) { + return; /* Drop first release */ + } + } } - if (s->e0_mode) { - s->e0_mode = 0; - ch = e0_keycodes[ch & 0x7f]; - } else { - ch = keycodes[ch & 0x7f]; + + if (qcode == Q_KEY_CODE_NUM_LOCK) { + if (evt->key->down) { + s->num_lock_mode ^= 1; + if (s->num_lock_mode == 2) { + return; /* Drop second press */ + } + } else { + s->num_lock_mode ^= 2; + if (s->num_lock_mode == 3) { + return; /* Drop first release */ + } + } + } + + keycode = qcode_to_keycode[qcode]; + if (!evt->key->down) { + keycode |= 0x80; } - trace_escc_sunkbd_event_out(ch); - put_queue(s, ch | release); + trace_escc_sunkbd_event_out(keycode); + put_queue(s, keycode); } +static QemuInputHandler sunkbd_handler = { + .name = "sun keyboard", + .mask = INPUT_EVENT_MASK_KEY, + .event = sunkbd_handle_event, +}; + static void handle_kbd_command(ChannelState *s, int val) { trace_escc_kbd_command(val); @@ -800,7 +910,7 @@ static void handle_kbd_command(ChannelState *s, int val) case 0xf: clear_queue(s); put_queue(s, 0xfe); - put_queue(s, 0); // XXX, layout? + put_queue(s, 0x21); /* en-us layout */ break; default: break; @@ -898,7 +1008,8 @@ static int escc_init1(SysBusDevice *dev) "QEMU Sun Mouse"); } if (s->chn[1].type == kbd) { - qemu_add_kbd_event_handler(sunkbd_event, &s->chn[1]); + s->chn[1].hs = qemu_input_handler_register((DeviceState *)(&s->chn[1]), + &sunkbd_handler); } return 0; diff --git a/hw/char/exynos4210_uart.c b/hw/char/exynos4210_uart.c index 19b59ccddb..7614e5860f 100644 --- a/hw/char/exynos4210_uart.c +++ b/hw/char/exynos4210_uart.c @@ -560,7 +560,6 @@ static const VMStateDescription vmstate_exynos4210_uart_fifo = { .name = "exynos4210.uart.fifo", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(sp, Exynos4210UartFIFO), VMSTATE_UINT32(rp, Exynos4210UartFIFO), @@ -573,7 +572,6 @@ static const VMStateDescription vmstate_exynos4210_uart = { .name = "exynos4210.uart", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT(rx, Exynos4210UartState, 1, vmstate_exynos4210_uart_fifo, Exynos4210UartFIFO), diff --git a/hw/char/imx_serial.c b/hw/char/imx_serial.c index 7f16835aeb..f3fbc776be 100644 --- a/hw/char/imx_serial.c +++ b/hw/char/imx_serial.c @@ -76,7 +76,6 @@ static const VMStateDescription vmstate_imx_serial = { .name = "imx-serial", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_INT32(readbuff, IMXSerialState), VMSTATE_UINT32(usr1, IMXSerialState), diff --git a/hw/char/ipoctal232.c b/hw/char/ipoctal232.c index f9c388ed0b..c8d5cdb361 100644 --- a/hw/char/ipoctal232.c +++ b/hw/char/ipoctal232.c @@ -124,8 +124,7 @@ static const VMStateDescription vmstate_scc2698_channel = { .name = "scc2698_channel", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BOOL(rx_enabled, SCC2698Channel), VMSTATE_UINT8_ARRAY(mr, SCC2698Channel, 2), VMSTATE_UINT8(mr_idx, SCC2698Channel), @@ -141,8 +140,7 @@ static const VMStateDescription vmstate_scc2698_block = { .name = "scc2698_block", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(imr, SCC2698Block), VMSTATE_UINT8(isr, SCC2698Block), VMSTATE_END_OF_LIST() @@ -153,8 +151,7 @@ static const VMStateDescription vmstate_ipoctal = { .name = "ipoctal232", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_IPACK_DEVICE(parent_obj, IPOctalState), VMSTATE_STRUCT_ARRAY(ch, IPOctalState, N_CHANNELS, 1, vmstate_scc2698_channel, SCC2698Channel), diff --git a/hw/char/lm32_juart.c b/hw/char/lm32_juart.c index 380cb5dbea..628a86fc06 100644 --- a/hw/char/lm32_juart.c +++ b/hw/char/lm32_juart.c @@ -129,8 +129,7 @@ static const VMStateDescription vmstate_lm32_juart = { .name = "lm32-juart", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(jtx, LM32JuartState), VMSTATE_UINT32(jrx, LM32JuartState), VMSTATE_END_OF_LIST() diff --git a/hw/char/lm32_uart.c b/hw/char/lm32_uart.c index 84c2549cb7..4f2096637d 100644 --- a/hw/char/lm32_uart.c +++ b/hw/char/lm32_uart.c @@ -270,8 +270,7 @@ static const VMStateDescription vmstate_lm32_uart = { .name = "lm32-uart", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, LM32UartState, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/char/milkymist-uart.c b/hw/char/milkymist-uart.c index da51f82eac..d05b825340 100644 --- a/hw/char/milkymist-uart.c +++ b/hw/char/milkymist-uart.c @@ -221,8 +221,7 @@ static const VMStateDescription vmstate_milkymist_uart = { .name = "milkymist-uart", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistUartState, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/char/parallel.c b/hw/char/parallel.c index 7ac90a512b..c2b553f0d1 100644 --- a/hw/char/parallel.c +++ b/hw/char/parallel.c @@ -477,6 +477,23 @@ static const MemoryRegionPortio isa_parallel_portio_sw_list[] = { PORTIO_END_OF_LIST(), }; + +static const VMStateDescription vmstate_parallel_isa = { + .name = "parallel_isa", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT8(state.dataw, ISAParallelState), + VMSTATE_UINT8(state.datar, ISAParallelState), + VMSTATE_UINT8(state.status, ISAParallelState), + VMSTATE_UINT8(state.control, ISAParallelState), + VMSTATE_INT32(state.irq_pending, ISAParallelState), + VMSTATE_INT32(state.epp_timeout, ISAParallelState), + VMSTATE_END_OF_LIST() + } +}; + + static void parallel_isa_realizefn(DeviceState *dev, Error **errp) { static int index; @@ -606,6 +623,7 @@ static void parallel_isa_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); dc->realize = parallel_isa_realizefn; + dc->vmsd = &vmstate_parallel_isa; dc->props = parallel_isa_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); } diff --git a/hw/char/pl011.c b/hw/char/pl011.c index 644aad7cf0..0a451150e5 100644 --- a/hw/char/pl011.c +++ b/hw/char/pl011.c @@ -251,8 +251,7 @@ static const VMStateDescription vmstate_pl011 = { .name = "pl011", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(readbuff, PL011State), VMSTATE_UINT32(flags, PL011State), VMSTATE_UINT32(lcr, PL011State), diff --git a/hw/char/sclpconsole-lm.c b/hw/char/sclpconsole-lm.c index a2dc1c63b0..a9f5e62f24 100644 --- a/hw/char/sclpconsole-lm.c +++ b/hw/char/sclpconsole-lm.c @@ -52,7 +52,8 @@ typedef struct SCLPConsoleLM { * event_pending is set when a newline character is encountered * * The maximum command line length is limited by the maximum - * space available in an SCCB + * space available in an SCCB. Line mode console input is sent + * truncated to the guest in case it doesn't fit into the SCCB. */ static int chr_can_read(void *opaque) @@ -61,10 +62,8 @@ static int chr_can_read(void *opaque) if (scon->event.event_pending) { return 0; - } else if (SIZE_CONSOLE_BUFFER - scon->length) { - return 1; } - return 0; + return 1; } static void chr_read(void *opaque, const uint8_t *buf, int size) @@ -78,6 +77,10 @@ static void chr_read(void *opaque, const uint8_t *buf, int size) sclp_service_interrupt(0); return; } + if (scon->length == SIZE_CONSOLE_BUFFER) { + /* Eat the character, but still process CR and LF. */ + return; + } scon->buf[scon->length] = *buf; scon->length += 1; if (scon->echo) { @@ -125,6 +128,7 @@ static int get_console_data(SCLPEvent *event, uint8_t *buf, size_t *size, cons->length = 0; /* data provided and no more data pending */ event->event_pending = false; + qemu_notify_event(); return 0; } @@ -291,8 +295,7 @@ static const VMStateDescription vmstate_sclplmconsole = { .name = "sclplmconsole", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BOOL(event.event_pending, SCLPConsoleLM), VMSTATE_UINT32(write_errors, SCLPConsoleLM), VMSTATE_UINT32(length, SCLPConsoleLM), diff --git a/hw/char/sclpconsole.c b/hw/char/sclpconsole.c index ce406730a5..79891dfc58 100644 --- a/hw/char/sclpconsole.c +++ b/hw/char/sclpconsole.c @@ -36,6 +36,7 @@ typedef struct SCLPConsole { uint32_t iov_bs; /* offset in buf for char layer read operation */ uint32_t iov_data_len; /* length of byte stream in buffer */ uint32_t iov_sclp_rest; /* length of byte stream not read via SCLP */ + bool notify; /* qemu_notify_event() req'd if true */ } SCLPConsole; /* character layer call-back functions */ @@ -44,8 +45,12 @@ typedef struct SCLPConsole { static int chr_can_read(void *opaque) { SCLPConsole *scon = opaque; + int avail = SIZE_BUFFER_VT220 - scon->iov_data_len; - return SIZE_BUFFER_VT220 - scon->iov_data_len; + if (avail == 0) { + scon->notify = true; + } + return avail; } /* Send data from a char device over to the guest */ @@ -113,6 +118,10 @@ static void get_console_data(SCLPEvent *event, uint8_t *buf, size_t *size, cons->iov_sclp += avail; /* more data pending */ } + if (cons->notify) { + cons->notify = false; + qemu_notify_event(); + } } static int read_event_data(SCLPEvent *event, EventBufferHeader *evt_buf_hdr, @@ -185,8 +194,7 @@ static const VMStateDescription vmstate_sclpconsole = { .name = "sclpconsole", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BOOL(event.event_pending, SCLPConsole), VMSTATE_UINT8_ARRAY(iov, SCLPConsole, SIZE_BUFFER_VT220), VMSTATE_UINT32(iov_sclp, SCLPConsole), @@ -230,6 +238,7 @@ static void console_reset(DeviceState *dev) scon->iov_bs = 0; scon->iov_data_len = 0; scon->iov_sclp_rest = 0; + scon->notify = false; } static int console_exit(SCLPEvent *event) diff --git a/hw/char/serial-pci.c b/hw/char/serial-pci.c index 991c99fa6e..f05c9b4d86 100644 --- a/hw/char/serial-pci.c +++ b/hw/char/serial-pci.c @@ -34,6 +34,7 @@ typedef struct PCISerialState { PCIDevice dev; SerialState state; + uint8_t prog_if; } PCISerialState; typedef struct PCIMultiSerialState { @@ -44,6 +45,7 @@ typedef struct PCIMultiSerialState { SerialState state[PCI_SERIAL_MAX_PORTS]; uint32_t level[PCI_SERIAL_MAX_PORTS]; qemu_irq *irqs; + uint8_t prog_if; } PCIMultiSerialState; static int serial_pci_init(PCIDevice *dev) @@ -60,6 +62,7 @@ static int serial_pci_init(PCIDevice *dev) return -1; } + pci->dev.config[PCI_CLASS_PROG] = pci->prog_if; pci->dev.config[PCI_INTERRUPT_PIN] = 0x01; s->irq = pci_allocate_irq(&pci->dev); @@ -101,6 +104,7 @@ static int multi_serial_pci_init(PCIDevice *dev) assert(pci->ports > 0); assert(pci->ports <= PCI_SERIAL_MAX_PORTS); + pci->dev.config[PCI_CLASS_PROG] = pci->prog_if; pci->dev.config[PCI_INTERRUPT_PIN] = 0x01; memory_region_init(&pci->iobar, OBJECT(pci), "multiserial", 8 * pci->ports); pci_register_bar(&pci->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->iobar); @@ -131,7 +135,6 @@ static void serial_pci_exit(PCIDevice *dev) SerialState *s = &pci->state; serial_exit_core(s); - memory_region_destroy(&s->io); qemu_free_irq(s->irq); } @@ -144,18 +147,17 @@ static void multi_serial_pci_exit(PCIDevice *dev) for (i = 0; i < pci->ports; i++) { s = pci->state + i; serial_exit_core(s); - memory_region_destroy(&s->io); + memory_region_del_subregion(&pci->iobar, &s->io); g_free(pci->name[i]); } - memory_region_destroy(&pci->iobar); - qemu_free_irqs(pci->irqs); + qemu_free_irqs(pci->irqs, pci->ports); } static const VMStateDescription vmstate_pci_serial = { .name = "pci-serial", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCISerialState), VMSTATE_STRUCT(state, PCISerialState, 0, vmstate_serial, SerialState), VMSTATE_END_OF_LIST() @@ -166,7 +168,7 @@ static const VMStateDescription vmstate_pci_multi_serial = { .name = "pci-serial-multi", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCIMultiSerialState), VMSTATE_STRUCT_ARRAY(state, PCIMultiSerialState, PCI_SERIAL_MAX_PORTS, 0, vmstate_serial, SerialState), @@ -177,12 +179,14 @@ static const VMStateDescription vmstate_pci_multi_serial = { static Property serial_pci_properties[] = { DEFINE_PROP_CHR("chardev", PCISerialState, state.chr), + DEFINE_PROP_UINT8("prog_if", PCISerialState, prog_if, 0x02), DEFINE_PROP_END_OF_LIST(), }; static Property multi_2x_serial_pci_properties[] = { DEFINE_PROP_CHR("chardev1", PCIMultiSerialState, state[0].chr), DEFINE_PROP_CHR("chardev2", PCIMultiSerialState, state[1].chr), + DEFINE_PROP_UINT8("prog_if", PCIMultiSerialState, prog_if, 0x02), DEFINE_PROP_END_OF_LIST(), }; @@ -191,6 +195,7 @@ static Property multi_4x_serial_pci_properties[] = { DEFINE_PROP_CHR("chardev2", PCIMultiSerialState, state[1].chr), DEFINE_PROP_CHR("chardev3", PCIMultiSerialState, state[2].chr), DEFINE_PROP_CHR("chardev4", PCIMultiSerialState, state[3].chr), + DEFINE_PROP_UINT8("prog_if", PCIMultiSerialState, prog_if, 0x02), DEFINE_PROP_END_OF_LIST(), }; diff --git a/hw/char/serial.c b/hw/char/serial.c index f4d167f916..ebcacdc872 100644 --- a/hw/char/serial.c +++ b/hw/char/serial.c @@ -223,37 +223,42 @@ static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque) { SerialState *s = opaque; - if (s->tsr_retry <= 0) { - if (s->fcr & UART_FCR_FE) { - if (fifo8_is_empty(&s->xmit_fifo)) { + do { + if (s->tsr_retry <= 0) { + if (s->fcr & UART_FCR_FE) { + if (fifo8_is_empty(&s->xmit_fifo)) { + return FALSE; + } + s->tsr = fifo8_pop(&s->xmit_fifo); + if (!s->xmit_fifo.num) { + s->lsr |= UART_LSR_THRE; + } + } else if ((s->lsr & UART_LSR_THRE)) { return FALSE; - } - s->tsr = fifo8_pop(&s->xmit_fifo); - if (!s->xmit_fifo.num) { + } else { + s->tsr = s->thr; s->lsr |= UART_LSR_THRE; + s->lsr &= ~UART_LSR_TEMT; } - } else if ((s->lsr & UART_LSR_THRE)) { - return FALSE; - } else { - s->tsr = s->thr; - s->lsr |= UART_LSR_THRE; - s->lsr &= ~UART_LSR_TEMT; } - } - if (s->mcr & UART_MCR_LOOP) { - /* in loopback mode, say that we just received a char */ - serial_receive1(s, &s->tsr, 1); - } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) { - if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY && - qemu_chr_fe_add_watch(s->chr, G_IO_OUT, serial_xmit, s) > 0) { - s->tsr_retry++; - return FALSE; + if (s->mcr & UART_MCR_LOOP) { + /* in loopback mode, say that we just received a char */ + serial_receive1(s, &s->tsr, 1); + } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) { + if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY && + qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP, + serial_xmit, s) > 0) { + s->tsr_retry++; + return FALSE; + } + s->tsr_retry = 0; + } else { + s->tsr_retry = 0; } - s->tsr_retry = 0; - } else { - s->tsr_retry = 0; - } + /* Transmit another byte if it is already available. It is only + possible when FIFO is enabled and not empty. */ + } while ((s->fcr & UART_FCR_FE) && !fifo8_is_empty(&s->xmit_fifo)); s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); @@ -267,6 +272,36 @@ static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque) } +/* Setter for FCR. + is_load flag means, that value is set while loading VM state + and interrupt should not be invoked */ +static void serial_write_fcr(SerialState *s, uint8_t val) +{ + /* Set fcr - val only has the bits that are supposed to "stick" */ + s->fcr = val; + + if (val & UART_FCR_FE) { + s->iir |= UART_IIR_FE; + /* Set recv_fifo trigger Level */ + switch (val & 0xC0) { + case UART_FCR_ITL_1: + s->recv_fifo_itl = 1; + break; + case UART_FCR_ITL_2: + s->recv_fifo_itl = 4; + break; + case UART_FCR_ITL_3: + s->recv_fifo_itl = 8; + break; + case UART_FCR_ITL_4: + s->recv_fifo_itl = 14; + break; + } + } else { + s->iir &= ~UART_IIR_FE; + } +} + static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { @@ -293,7 +328,9 @@ static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val, s->thr_ipending = 0; s->lsr &= ~UART_LSR_THRE; serial_update_irq(s); - serial_xmit(NULL, G_IO_OUT, s); + if (s->tsr_retry <= 0) { + serial_xmit(NULL, G_IO_OUT, s); + } } break; case 1: @@ -320,20 +357,16 @@ static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val, } break; case 2: - val = val & 0xFF; - - if (s->fcr == val) - break; - /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */ - if ((val ^ s->fcr) & UART_FCR_FE) + if ((val ^ s->fcr) & UART_FCR_FE) { val |= UART_FCR_XFR | UART_FCR_RFR; + } /* FIFO clear */ if (val & UART_FCR_RFR) { timer_del(s->fifo_timeout_timer); - s->timeout_ipending=0; + s->timeout_ipending = 0; fifo8_reset(&s->recv_fifo); } @@ -341,28 +374,7 @@ static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val, fifo8_reset(&s->xmit_fifo); } - if (val & UART_FCR_FE) { - s->iir |= UART_IIR_FE; - /* Set recv_fifo trigger Level */ - switch (val & 0xC0) { - case UART_FCR_ITL_1: - s->recv_fifo_itl = 1; - break; - case UART_FCR_ITL_2: - s->recv_fifo_itl = 4; - break; - case UART_FCR_ITL_3: - s->recv_fifo_itl = 8; - break; - case UART_FCR_ITL_4: - s->recv_fifo_itl = 14; - break; - } - } else - s->iir &= ~UART_IIR_FE; - - /* Set fcr - or at least the bits in it that are supposed to "stick" */ - s->fcr = val & 0xC9; + serial_write_fcr(s, val & 0xC9); serial_update_irq(s); break; case 3: @@ -583,6 +595,14 @@ static void serial_pre_save(void *opaque) s->fcr_vmstate = s->fcr; } +static int serial_pre_load(void *opaque) +{ + SerialState *s = opaque; + s->thr_ipending = -1; + s->poll_msl = -1; + return 0; +} + static int serial_post_load(void *opaque, int version_id) { SerialState *s = opaque; @@ -590,19 +610,141 @@ static int serial_post_load(void *opaque, int version_id) if (version_id < 3) { s->fcr_vmstate = 0; } + if (s->thr_ipending == -1) { + s->thr_ipending = ((s->iir & UART_IIR_ID) == UART_IIR_THRI); + } + s->last_break_enable = (s->lcr >> 6) & 1; /* Initialize fcr via setter to perform essential side-effects */ - serial_ioport_write(s, 0x02, s->fcr_vmstate, 1); + serial_write_fcr(s, s->fcr_vmstate); serial_update_parameters(s); return 0; } +static bool serial_thr_ipending_needed(void *opaque) +{ + SerialState *s = opaque; + bool expected_value = ((s->iir & UART_IIR_ID) == UART_IIR_THRI); + return s->thr_ipending != expected_value; +} + +const VMStateDescription vmstate_serial_thr_ipending = { + .name = "serial/thr_ipending", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(thr_ipending, SerialState), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_tsr_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return s->tsr_retry != 0; +} + +const VMStateDescription vmstate_serial_tsr = { + .name = "serial/tsr", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(tsr_retry, SerialState), + VMSTATE_UINT8(thr, SerialState), + VMSTATE_UINT8(tsr, SerialState), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_recv_fifo_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return !fifo8_is_empty(&s->recv_fifo); + +} + +const VMStateDescription vmstate_serial_recv_fifo = { + .name = "serial/recv_fifo", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_STRUCT(recv_fifo, SerialState, 1, vmstate_fifo8, Fifo8), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_xmit_fifo_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return !fifo8_is_empty(&s->xmit_fifo); +} + +const VMStateDescription vmstate_serial_xmit_fifo = { + .name = "serial/xmit_fifo", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_STRUCT(xmit_fifo, SerialState, 1, vmstate_fifo8, Fifo8), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_fifo_timeout_timer_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return timer_pending(s->fifo_timeout_timer); +} + +const VMStateDescription vmstate_serial_fifo_timeout_timer = { + .name = "serial/fifo_timeout_timer", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_TIMER(fifo_timeout_timer, SerialState), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_timeout_ipending_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return s->timeout_ipending != 0; +} + +const VMStateDescription vmstate_serial_timeout_ipending = { + .name = "serial/timeout_ipending", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(timeout_ipending, SerialState), + VMSTATE_END_OF_LIST() + } +}; + +static bool serial_poll_needed(void *opaque) +{ + SerialState *s = (SerialState *)opaque; + return s->poll_msl >= 0; +} + +const VMStateDescription vmstate_serial_poll = { + .name = "serial/poll", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(poll_msl, SerialState), + VMSTATE_TIMER(modem_status_poll, SerialState), + VMSTATE_END_OF_LIST() + } +}; + const VMStateDescription vmstate_serial = { .name = "serial", .version_id = 3, .minimum_version_id = 2, .pre_save = serial_pre_save, + .pre_load = serial_pre_load, .post_load = serial_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16_V(divider, SerialState, 2), VMSTATE_UINT8(rbr, SerialState), VMSTATE_UINT8(ier, SerialState), @@ -614,6 +756,32 @@ const VMStateDescription vmstate_serial = { VMSTATE_UINT8(scr, SerialState), VMSTATE_UINT8_V(fcr_vmstate, SerialState, 3), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_serial_thr_ipending, + .needed = &serial_thr_ipending_needed, + } , { + .vmsd = &vmstate_serial_tsr, + .needed = &serial_tsr_needed, + } , { + .vmsd = &vmstate_serial_recv_fifo, + .needed = &serial_recv_fifo_needed, + } , { + .vmsd = &vmstate_serial_xmit_fifo, + .needed = &serial_xmit_fifo_needed, + } , { + .vmsd = &vmstate_serial_fifo_timeout_timer, + .needed = &serial_fifo_timeout_timer_needed, + } , { + .vmsd = &vmstate_serial_timeout_ipending, + .needed = &serial_timeout_ipending_needed, + } , { + .vmsd = &vmstate_serial_poll, + .needed = &serial_poll_needed, + } , { + /* empty */ + } } }; @@ -635,6 +803,10 @@ static void serial_reset(void *opaque) s->char_transmit_time = (get_ticks_per_sec() / 9600) * 10; s->poll_msl = 0; + s->timeout_ipending = 0; + timer_del(s->fifo_timeout_timer); + timer_del(s->modem_status_poll); + fifo8_reset(&s->recv_fifo); fifo8_reset(&s->xmit_fifo); @@ -643,6 +815,9 @@ static void serial_reset(void *opaque) s->thr_ipending = 0; s->last_break_enable = 0; qemu_irq_lower(s->irq); + + serial_update_msl(s); + s->msr &= ~UART_MSR_ANY_DELTA; } void serial_realize_core(SerialState *s, Error **errp) @@ -661,6 +836,7 @@ void serial_realize_core(SerialState *s, Error **errp) serial_event, s); fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH); fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH); + serial_reset(s); } void serial_exit_core(SerialState *s) @@ -772,7 +948,5 @@ SerialState *serial_mm_init(MemoryRegion *address_space, memory_region_init_io(&s->io, NULL, &serial_mm_ops[end], s, "serial", 8 << it_shift); memory_region_add_subregion(address_space, base, &s->io); - - serial_update_msl(s); return s; } diff --git a/hw/char/spapr_vty.c b/hw/char/spapr_vty.c index f8a4981e27..0adf096ae0 100644 --- a/hw/char/spapr_vty.c +++ b/hw/char/spapr_vty.c @@ -148,8 +148,7 @@ static const VMStateDescription vmstate_spapr_vty = { .name = "spapr_vty", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_SPAPR_VIO(sdev, VIOsPAPRVTYDevice), VMSTATE_UINT32(in, VIOsPAPRVTYDevice), diff --git a/hw/char/virtio-console.c b/hw/char/virtio-console.c index 6c8be0fe26..752ed2c3c8 100644 --- a/hw/char/virtio-console.c +++ b/hw/char/virtio-console.c @@ -14,6 +14,7 @@ #include "qemu/error-report.h" #include "trace.h" #include "hw/virtio/virtio-serial.h" +#include "qapi-event.h" #define TYPE_VIRTIO_CONSOLE_SERIAL_PORT "virtserialport" #define VIRTIO_CONSOLE(obj) \ @@ -69,7 +70,8 @@ static ssize_t flush_buf(VirtIOSerialPort *port, if (!k->is_console) { virtio_serial_throttle_port(port, true); if (!vcon->watch) { - vcon->watch = qemu_chr_fe_add_watch(vcon->chr, G_IO_OUT, + vcon->watch = qemu_chr_fe_add_watch(vcon->chr, + G_IO_OUT|G_IO_HUP, chr_write_unblocked, vcon); } } @@ -81,11 +83,16 @@ static ssize_t flush_buf(VirtIOSerialPort *port, static void set_guest_connected(VirtIOSerialPort *port, int guest_connected) { VirtConsole *vcon = VIRTIO_CONSOLE(port); + DeviceState *dev = DEVICE(port); - if (!vcon->chr) { - return; + if (vcon->chr) { + qemu_chr_fe_set_open(vcon->chr, guest_connected); + } + + if (dev->id) { + qapi_event_send_vserport_change(dev->id, guest_connected, + &error_abort); } - qemu_chr_fe_set_open(vcon->chr, guest_connected); } /* Readiness of the guest to accept data on a port */ diff --git a/hw/char/virtio-serial-bus.c b/hw/char/virtio-serial-bus.c index 2b647b68d5..a7b1b68984 100644 --- a/hw/char/virtio-serial-bus.c +++ b/hw/char/virtio-serial-bus.c @@ -24,6 +24,11 @@ #include "hw/sysbus.h" #include "trace.h" #include "hw/virtio/virtio-serial.h" +#include "hw/virtio/virtio-access.h" + +struct VirtIOSerialDevices { + QLIST_HEAD(, VirtIOSerial) devices; +} vserdevices; static VirtIOSerialPort *find_port_by_id(VirtIOSerial *vser, uint32_t id) { @@ -51,6 +56,22 @@ static VirtIOSerialPort *find_port_by_vq(VirtIOSerial *vser, VirtQueue *vq) return NULL; } +static VirtIOSerialPort *find_port_by_name(char *name) +{ + VirtIOSerial *vser; + + QLIST_FOREACH(vser, &vserdevices.devices, next) { + VirtIOSerialPort *port; + + QTAILQ_FOREACH(port, &vser->ports, next) { + if (!strcmp(port->name, name)) { + return port; + } + } + } + return NULL; +} + static bool use_multiport(VirtIOSerial *vser) { VirtIODevice *vdev = VIRTIO_DEVICE(vser); @@ -183,11 +204,12 @@ static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len) static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id, uint16_t event, uint16_t value) { + VirtIODevice *vdev = VIRTIO_DEVICE(vser); struct virtio_console_control cpkt; - stl_p(&cpkt.id, port_id); - stw_p(&cpkt.event, event); - stw_p(&cpkt.value, value); + virtio_stl_p(vdev, &cpkt.id, port_id); + virtio_stw_p(vdev, &cpkt.event, event); + virtio_stw_p(vdev, &cpkt.value, value); trace_virtio_serial_send_control_event(port_id, event, value); return send_control_msg(vser, &cpkt, sizeof(cpkt)); @@ -278,6 +300,7 @@ void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle) /* Guest wants to notify us of some event */ static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len) { + VirtIODevice *vdev = VIRTIO_DEVICE(vser); struct VirtIOSerialPort *port; VirtIOSerialPortClass *vsc; struct virtio_console_control cpkt, *gcpkt; @@ -291,8 +314,8 @@ static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len) return; } - cpkt.event = lduw_p(&gcpkt->event); - cpkt.value = lduw_p(&gcpkt->value); + cpkt.event = virtio_lduw_p(vdev, &gcpkt->event); + cpkt.value = virtio_lduw_p(vdev, &gcpkt->value); trace_virtio_serial_handle_control_message(cpkt.event, cpkt.value); @@ -312,10 +335,10 @@ static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len) return; } - port = find_port_by_id(vser, ldl_p(&gcpkt->id)); + port = find_port_by_id(vser, virtio_ldl_p(vdev, &gcpkt->id)); if (!port) { error_report("virtio-serial-bus: Unexpected port id %u for device %s", - ldl_p(&gcpkt->id), vser->bus.qbus.name); + virtio_ldl_p(vdev, &gcpkt->id), vser->bus.qbus.name); return; } @@ -342,9 +365,9 @@ static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len) } if (port->name) { - stl_p(&cpkt.id, port->id); - stw_p(&cpkt.event, VIRTIO_CONSOLE_PORT_NAME); - stw_p(&cpkt.value, 1); + virtio_stl_p(vdev, &cpkt.id, port->id); + virtio_stw_p(vdev, &cpkt.event, VIRTIO_CONSOLE_PORT_NAME); + virtio_stw_p(vdev, &cpkt.value, 1); buffer_len = sizeof(cpkt) + strlen(port->name) + 1; buffer = g_malloc(buffer_len); @@ -465,13 +488,6 @@ static void get_config(VirtIODevice *vdev, uint8_t *config_data) memcpy(config_data, &vser->config, sizeof(struct virtio_console_config)); } -static void set_config(VirtIODevice *vdev, const uint8_t *config_data) -{ - struct virtio_console_config config; - - memcpy(&config, config_data, sizeof(config)); -} - static void guest_reset(VirtIOSerial *vser) { VirtIOSerialPort *port; @@ -517,18 +533,25 @@ static void vser_reset(VirtIODevice *vdev) vser = VIRTIO_SERIAL(vdev); guest_reset(vser); + + /* In case we have switched endianness */ + vser->config.max_nr_ports = + virtio_tswap32(vdev, vser->serial.max_virtserial_ports); } static void virtio_serial_save(QEMUFile *f, void *opaque) { - VirtIOSerial *s = VIRTIO_SERIAL(opaque); + /* The virtio device */ + virtio_save(VIRTIO_DEVICE(opaque), f); +} + +static void virtio_serial_save_device(VirtIODevice *vdev, QEMUFile *f) +{ + VirtIOSerial *s = VIRTIO_SERIAL(vdev); VirtIOSerialPort *port; uint32_t nr_active_ports; unsigned int i, max_nr_ports; - /* The virtio device */ - virtio_save(VIRTIO_DEVICE(s), f); - /* The config space */ qemu_put_be16s(f, &s->config.cols); qemu_put_be16s(f, &s->config.rows); @@ -536,7 +559,7 @@ static void virtio_serial_save(QEMUFile *f, void *opaque) qemu_put_be32s(f, &s->config.max_nr_ports); /* The ports map */ - max_nr_ports = tswap32(s->config.max_nr_ports); + max_nr_ports = virtio_tswap32(vdev, s->config.max_nr_ports); for (i = 0; i < (max_nr_ports + 31) / 32; i++) { qemu_put_be32s(f, &s->ports_map[i]); } @@ -666,36 +689,39 @@ static int fetch_active_ports_list(QEMUFile *f, int version_id, static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id) { - VirtIOSerial *s = VIRTIO_SERIAL(opaque); - uint32_t max_nr_ports, nr_active_ports, ports_map; - unsigned int i; - int ret; - if (version_id > 3) { return -EINVAL; } /* The virtio device */ - ret = virtio_load(VIRTIO_DEVICE(s), f); - if (ret) { - return ret; - } + return virtio_load(VIRTIO_DEVICE(opaque), f, version_id); +} + +static int virtio_serial_load_device(VirtIODevice *vdev, QEMUFile *f, + int version_id) +{ + VirtIOSerial *s = VIRTIO_SERIAL(vdev); + uint32_t max_nr_ports, nr_active_ports, ports_map; + unsigned int i; + int ret; + uint32_t tmp; if (version_id < 2) { return 0; } - /* The config space */ - qemu_get_be16s(f, &s->config.cols); - qemu_get_be16s(f, &s->config.rows); - - qemu_get_be32s(f, &max_nr_ports); - tswap32s(&max_nr_ports); - if (max_nr_ports > tswap32(s->config.max_nr_ports)) { - /* Source could have had more ports than us. Fail migration. */ - return -EINVAL; - } + /* Unused */ + qemu_get_be16s(f, (uint16_t *) &tmp); + qemu_get_be16s(f, (uint16_t *) &tmp); + qemu_get_be32s(f, &tmp); + /* Note: this is the only location where we use tswap32() instead of + * virtio_tswap32() because: + * - virtio_tswap32() only makes sense when the device is fully restored + * - the target endianness that was used to populate s->config is + * necessarly the default one + */ + max_nr_ports = tswap32(s->config.max_nr_ports); for (i = 0; i < (max_nr_ports + 31) / 32; i++) { qemu_get_be32s(f, &ports_map); @@ -758,9 +784,10 @@ static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent) /* This function is only used if a port id is not provided by the user */ static uint32_t find_free_port_id(VirtIOSerial *vser) { + VirtIODevice *vdev = VIRTIO_DEVICE(vser); unsigned int i, max_nr_ports; - max_nr_ports = tswap32(vser->config.max_nr_ports); + max_nr_ports = virtio_tswap32(vdev, vser->config.max_nr_ports); for (i = 0; i < (max_nr_ports + 31) / 32; i++) { uint32_t map, bit; @@ -790,10 +817,18 @@ static void add_port(VirtIOSerial *vser, uint32_t port_id) static void remove_port(VirtIOSerial *vser, uint32_t port_id) { VirtIOSerialPort *port; - unsigned int i; - i = port_id / 32; - vser->ports_map[i] &= ~(1U << (port_id % 32)); + /* + * Don't mark port 0 removed -- we explicitly reserve it for + * backward compat with older guests, ensure a virtconsole device + * unplug retains the reservation. + */ + if (port_id) { + unsigned int i; + + i = port_id / 32; + vser->ports_map[i] &= ~(1U << (port_id % 32)); + } port = find_port_by_id(vser, port_id); /* @@ -813,6 +848,7 @@ static void virtser_port_device_realize(DeviceState *dev, Error **errp) VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev); VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev)); + VirtIODevice *vdev = VIRTIO_DEVICE(bus->vser); int max_nr_ports; bool plugging_port0; Error *err = NULL; @@ -835,6 +871,12 @@ static void virtser_port_device_realize(DeviceState *dev, Error **errp) return; } + if (port->name != NULL && find_port_by_name(port->name)) { + error_setg(errp, "virtio-serial-bus: A port already exists by name %s", + port->name); + return; + } + if (port->id == VIRTIO_CONSOLE_BAD_ID) { if (plugging_port0) { port->id = 0; @@ -848,7 +890,7 @@ static void virtser_port_device_realize(DeviceState *dev, Error **errp) } } - max_nr_ports = tswap32(port->vser->config.max_nr_ports); + max_nr_ports = virtio_tswap32(vdev, port->vser->config.max_nr_ports); if (port->id >= max_nr_ports) { error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, " "max. allowed: %u", max_nr_ports - 1); @@ -862,6 +904,12 @@ static void virtser_port_device_realize(DeviceState *dev, Error **errp) } port->elem.out_num = 0; +} + +static void virtser_port_device_plug(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev); QTAILQ_INSERT_TAIL(&port->vser->ports, port, next); port->ivq = port->vser->ivqs[port->id]; @@ -870,7 +918,7 @@ static void virtser_port_device_realize(DeviceState *dev, Error **errp) add_port(port->vser, port->id); /* Send an update to the guest about this new port added */ - virtio_notify_config(VIRTIO_DEVICE(port->vser)); + virtio_notify_config(VIRTIO_DEVICE(hotplug_dev)); } static void virtser_port_device_unrealize(DeviceState *dev, Error **errp) @@ -893,7 +941,6 @@ static void virtio_serial_device_realize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOSerial *vser = VIRTIO_SERIAL(dev); - BusState *bus; uint32_t i, max_supported_ports; if (!vser->serial.max_virtserial_ports) { @@ -915,8 +962,7 @@ static void virtio_serial_device_realize(DeviceState *dev, Error **errp) /* Spawn a new virtio-serial bus on which the ports will ride as devices */ qbus_create_inplace(&vser->bus, sizeof(vser->bus), TYPE_VIRTIO_SERIAL_BUS, dev, vdev->bus_name); - bus = BUS(&vser->bus); - bus->allow_hotplug = 1; + qbus_set_hotplug_handler(BUS(&vser->bus), DEVICE(vser), errp); vser->bus.vser = vser; QTAILQ_INIT(&vser->ports); @@ -949,7 +995,8 @@ static void virtio_serial_device_realize(DeviceState *dev, Error **errp) vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output); } - vser->config.max_nr_ports = tswap32(vser->serial.max_virtserial_ports); + vser->config.max_nr_ports = + virtio_tswap32(vdev, vser->serial.max_virtserial_ports); vser->ports_map = g_malloc0(((vser->serial.max_virtserial_ports + 31) / 32) * sizeof(vser->ports_map[0])); /* @@ -966,6 +1013,8 @@ static void virtio_serial_device_realize(DeviceState *dev, Error **errp) */ register_savevm(dev, "virtio-console", -1, 3, virtio_serial_save, virtio_serial_load, vser); + + QLIST_INSERT_HEAD(&vserdevices.devices, vser, next); } static void virtio_serial_port_class_init(ObjectClass *klass, void *data) @@ -976,7 +1025,6 @@ static void virtio_serial_port_class_init(ObjectClass *klass, void *data) k->bus_type = TYPE_VIRTIO_SERIAL_BUS; k->realize = virtser_port_device_realize; k->unrealize = virtser_port_device_unrealize; - k->unplug = qdev_simple_unplug_cb; k->props = virtser_props; } @@ -994,6 +1042,8 @@ static void virtio_serial_device_unrealize(DeviceState *dev, Error **errp) VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOSerial *vser = VIRTIO_SERIAL(dev); + QLIST_REMOVE(vser, next); + unregister_savevm(dev, "virtio-console", vser); g_free(vser->ivqs); @@ -1017,6 +1067,9 @@ static void virtio_serial_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); + + QLIST_INIT(&vserdevices.devices); dc->props = virtio_serial_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); @@ -1024,9 +1077,12 @@ static void virtio_serial_class_init(ObjectClass *klass, void *data) vdc->unrealize = virtio_serial_device_unrealize; vdc->get_features = get_features; vdc->get_config = get_config; - vdc->set_config = set_config; vdc->set_status = set_status; vdc->reset = vser_reset; + vdc->save = virtio_serial_save_device; + vdc->load = virtio_serial_load_device; + hc->plug = virtser_port_device_plug; + hc->unplug = qdev_simple_device_unplug_cb; } static const TypeInfo virtio_device_info = { @@ -1034,6 +1090,10 @@ static const TypeInfo virtio_device_info = { .parent = TYPE_VIRTIO_DEVICE, .instance_size = sizeof(VirtIOSerial), .class_init = virtio_serial_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static void virtio_serial_register_types(void) diff --git a/hw/char/xilinx_uartlite.c b/hw/char/xilinx_uartlite.c index b0d1d04af7..f7c3cae2fa 100644 --- a/hw/char/xilinx_uartlite.c +++ b/hw/char/xilinx_uartlite.c @@ -87,6 +87,11 @@ static void uart_update_status(XilinxUARTLite *s) s->regs[R_STATUS] = r; } +static void xilinx_uartlite_reset(DeviceState *dev) +{ + uart_update_status(XILINX_UARTLITE(dev)); +} + static uint64_t uart_read(void *opaque, hwaddr addr, unsigned int size) { @@ -196,34 +201,39 @@ static void uart_event(void *opaque, int event) } -static int xilinx_uartlite_init(SysBusDevice *dev) +static void xilinx_uartlite_realize(DeviceState *dev, Error **errp) { XilinxUARTLite *s = XILINX_UARTLITE(dev); - sysbus_init_irq(dev, &s->irq); - - uart_update_status(s); - memory_region_init_io(&s->mmio, OBJECT(s), &uart_ops, s, - "xlnx.xps-uartlite", R_MAX * 4); - sysbus_init_mmio(dev, &s->mmio); - s->chr = qemu_char_get_next_serial(); if (s->chr) qemu_chr_add_handlers(s->chr, uart_can_rx, uart_rx, uart_event, s); - return 0; +} + +static void xilinx_uartlite_init(Object *obj) +{ + XilinxUARTLite *s = XILINX_UARTLITE(obj); + + sysbus_init_irq(SYS_BUS_DEVICE(obj), &s->irq); + + memory_region_init_io(&s->mmio, obj, &uart_ops, s, + "xlnx.xps-uartlite", R_MAX * 4); + sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->mmio); } static void xilinx_uartlite_class_init(ObjectClass *klass, void *data) { - SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass); + DeviceClass *dc = DEVICE_CLASS(klass); - sdc->init = xilinx_uartlite_init; + dc->reset = xilinx_uartlite_reset; + dc->realize = xilinx_uartlite_realize; } static const TypeInfo xilinx_uartlite_info = { .name = TYPE_XILINX_UARTLITE, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(XilinxUARTLite), + .instance_init = xilinx_uartlite_init, .class_init = xilinx_uartlite_class_init, }; diff --git a/hw/core/Makefile.objs b/hw/core/Makefile.objs index 5377d052e9..9dce1bc53c 100644 --- a/hw/core/Makefile.objs +++ b/hw/core/Makefile.objs @@ -4,6 +4,7 @@ common-obj-y += fw-path-provider.o # irq.o needed for qdev GPIO handling: common-obj-y += irq.o common-obj-y += hotplug.o +common-obj-y += nmi.o common-obj-$(CONFIG_EMPTY_SLOT) += empty_slot.o common-obj-$(CONFIG_XILINX_AXI) += stream.o @@ -13,3 +14,4 @@ common-obj-$(CONFIG_SOFTMMU) += machine.o common-obj-$(CONFIG_SOFTMMU) += null-machine.o common-obj-$(CONFIG_SOFTMMU) += loader.o common-obj-$(CONFIG_SOFTMMU) += qdev-properties-system.o +common-obj-$(CONFIG_SOFTMMU) += platform-bus.o diff --git a/hw/core/hotplug.c b/hw/core/hotplug.c index 5573d9d2d9..4e01074557 100644 --- a/hw/core/hotplug.c +++ b/hw/core/hotplug.c @@ -23,6 +23,17 @@ void hotplug_handler_plug(HotplugHandler *plug_handler, } } +void hotplug_handler_unplug_request(HotplugHandler *plug_handler, + DeviceState *plugged_dev, + Error **errp) +{ + HotplugHandlerClass *hdc = HOTPLUG_HANDLER_GET_CLASS(plug_handler); + + if (hdc->unplug_request) { + hdc->unplug_request(plug_handler, plugged_dev, errp); + } +} + void hotplug_handler_unplug(HotplugHandler *plug_handler, DeviceState *plugged_dev, Error **errp) diff --git a/hw/core/irq.c b/hw/core/irq.c index 03c8cb31ea..8a62a36d5e 100644 --- a/hw/core/irq.c +++ b/hw/core/irq.c @@ -23,8 +23,13 @@ */ #include "qemu-common.h" #include "hw/irq.h" +#include "qom/object.h" + +#define IRQ(obj) OBJECT_CHECK(struct IRQState, (obj), TYPE_IRQ) struct IRQState { + Object parent_obj; + qemu_irq_handler handler; void *opaque; int n; @@ -42,23 +47,14 @@ qemu_irq *qemu_extend_irqs(qemu_irq *old, int n_old, qemu_irq_handler handler, void *opaque, int n) { qemu_irq *s; - struct IRQState *p; int i; if (!old) { n_old = 0; } s = old ? g_renew(qemu_irq, old, n + n_old) : g_new(qemu_irq, n); - p = old ? g_renew(struct IRQState, s[0], n + n_old) : - g_new(struct IRQState, n); - for (i = 0; i < n + n_old; i++) { - if (i >= n_old) { - p->handler = handler; - p->opaque = opaque; - p->n = i; - } - s[i] = p; - p++; + for (i = n_old; i < n + n_old; i++) { + s[i] = qemu_allocate_irq(handler, opaque, i); } return s; } @@ -72,7 +68,7 @@ qemu_irq qemu_allocate_irq(qemu_irq_handler handler, void *opaque, int n) { struct IRQState *irq; - irq = g_new(struct IRQState, 1); + irq = IRQ(object_new(TYPE_IRQ)); irq->handler = handler; irq->opaque = opaque; irq->n = n; @@ -80,15 +76,18 @@ qemu_irq qemu_allocate_irq(qemu_irq_handler handler, void *opaque, int n) return irq; } -void qemu_free_irqs(qemu_irq *s) +void qemu_free_irqs(qemu_irq *s, int n) { - g_free(s[0]); + int i; + for (i = 0; i < n; i++) { + qemu_free_irq(s[i]); + } g_free(s); } void qemu_free_irq(qemu_irq irq) { - g_free(irq); + object_unref(OBJECT(irq)); } static void qemu_notirq(void *opaque, int line, int level) @@ -102,7 +101,7 @@ qemu_irq qemu_irq_invert(qemu_irq irq) { /* The default state for IRQs is low, so raise the output now. */ qemu_irq_raise(irq); - return qemu_allocate_irqs(qemu_notirq, irq, 1)[0]; + return qemu_allocate_irq(qemu_notirq, irq, 0); } static void qemu_splitirq(void *opaque, int line, int level) @@ -117,7 +116,7 @@ qemu_irq qemu_irq_split(qemu_irq irq1, qemu_irq irq2) qemu_irq *s = g_malloc0(2 * sizeof(qemu_irq)); s[0] = irq1; s[1] = irq2; - return qemu_allocate_irqs(qemu_splitirq, s, 1)[0]; + return qemu_allocate_irq(qemu_splitirq, s, 0); } static void proxy_irq_handler(void *opaque, int n, int level) @@ -141,12 +140,19 @@ void qemu_irq_intercept_in(qemu_irq *gpio_in, qemu_irq_handler handler, int n) for (i = 0; i < n; i++) { *old_irqs[i] = *gpio_in[i]; gpio_in[i]->handler = handler; - gpio_in[i]->opaque = old_irqs; + gpio_in[i]->opaque = &old_irqs[i]; } } -void qemu_irq_intercept_out(qemu_irq **gpio_out, qemu_irq_handler handler, int n) +static const TypeInfo irq_type_info = { + .name = TYPE_IRQ, + .parent = TYPE_OBJECT, + .instance_size = sizeof(struct IRQState), +}; + +static void irq_register_types(void) { - qemu_irq *old_irqs = *gpio_out; - *gpio_out = qemu_allocate_irqs(handler, old_irqs, n); + type_register_static(&irq_type_info); } + +type_init(irq_register_types) diff --git a/hw/core/loader.c b/hw/core/loader.c index 2bf6b8ff85..7527fd3036 100644 --- a/hw/core/loader.c +++ b/hw/core/loader.c @@ -80,6 +80,13 @@ int load_image(const char *filename, uint8_t *addr) if (fd < 0) return -1; size = lseek(fd, 0, SEEK_END); + if (size == -1) { + fprintf(stderr, "file %-20s: get size error: %s\n", + filename, strerror(errno)); + close(fd); + return -1; + } + lseek(fd, 0, SEEK_SET); if (read(fd, addr, size) != size) { close(fd); @@ -89,6 +96,27 @@ int load_image(const char *filename, uint8_t *addr) return size; } +/* return the size or -1 if error */ +ssize_t load_image_size(const char *filename, void *addr, size_t size) +{ + int fd; + ssize_t actsize; + + fd = open(filename, O_RDONLY | O_BINARY); + if (fd < 0) { + return -1; + } + + actsize = read(fd, addr, size); + if (actsize < 0) { + close(fd); + return -1; + } + close(fd); + + return actsize; +} + /* read()-like version */ ssize_t read_targphys(const char *name, int fd, hwaddr dst_addr, size_t nbytes) @@ -456,7 +484,9 @@ static ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src, /* Load a U-Boot image. */ static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr, - int *is_linux, uint8_t image_type) + int *is_linux, uint8_t image_type, + uint64_t (*translate_fn)(void *, uint64_t), + void *translate_opaque) { int fd; int size; @@ -490,6 +520,9 @@ static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr, switch (hdr->ih_type) { case IH_TYPE_KERNEL: address = hdr->ih_load; + if (translate_fn) { + address = translate_fn(translate_opaque, address); + } if (loadaddr) { *loadaddr = hdr->ih_load; } @@ -566,15 +599,67 @@ out: } int load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr, - int *is_linux) + int *is_linux, + uint64_t (*translate_fn)(void *, uint64_t), + void *translate_opaque) { - return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL); + return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL, + translate_fn, translate_opaque); } /* Load a ramdisk. */ int load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz) { - return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK); + return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK, + NULL, NULL); +} + +/* This simply prevents g_malloc in the function below from allocating + * a huge amount of memory, by placing a limit on the maximum + * uncompressed image size that load_image_gzipped will read. + */ +#define LOAD_IMAGE_MAX_GUNZIP_BYTES (256 << 20) + +/* Load a gzip-compressed kernel. */ +int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz) +{ + uint8_t *compressed_data = NULL; + uint8_t *data = NULL; + gsize len; + ssize_t bytes; + int ret = -1; + + if (!g_file_get_contents(filename, (char **) &compressed_data, &len, + NULL)) { + goto out; + } + + /* Is it a gzip-compressed file? */ + if (len < 2 || + compressed_data[0] != 0x1f || + compressed_data[1] != 0x8b) { + goto out; + } + + if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) { + max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES; + } + + data = g_malloc(max_sz); + bytes = gunzip(data, max_sz, compressed_data, len); + if (bytes < 0) { + fprintf(stderr, "%s: unable to decompress gzipped kernel file\n", + filename); + goto out; + } + + rom_add_blob_fixed(filename, data, bytes, addr); + ret = bytes; + + out: + g_free(compressed_data); + g_free(data); + return ret; } /* @@ -632,7 +717,7 @@ static void *rom_set_mr(Rom *rom, Object *owner, const char *name) void *data; rom->mr = g_malloc(sizeof(*rom->mr)); - memory_region_init_ram(rom->mr, owner, name, rom->datasize); + memory_region_init_ram(rom->mr, owner, name, rom->datasize, &error_abort); memory_region_set_readonly(rom->mr, true); vmstate_register_ram_global(rom->mr); @@ -670,6 +755,12 @@ int rom_add_file(const char *file, const char *fw_dir, } rom->addr = addr; rom->romsize = lseek(fd, 0, SEEK_END); + if (rom->romsize == -1) { + fprintf(stderr, "rom: file %-20s: get size error: %s\n", + rom->name, strerror(errno)); + goto err; + } + rom->datasize = rom->romsize; rom->data = g_malloc0(rom->datasize); lseek(fd, 0, SEEK_SET); @@ -720,12 +811,12 @@ err: return -1; } -void *rom_add_blob(const char *name, const void *blob, size_t len, +ram_addr_t rom_add_blob(const char *name, const void *blob, size_t len, hwaddr addr, const char *fw_file_name, FWCfgReadCallback fw_callback, void *callback_opaque) { Rom *rom; - void *data = NULL; + ram_addr_t ret = RAM_ADDR_MAX; rom = g_malloc0(sizeof(*rom)); rom->name = g_strdup(name); @@ -737,11 +828,13 @@ void *rom_add_blob(const char *name, const void *blob, size_t len, rom_insert(rom); if (fw_file_name && fw_cfg) { char devpath[100]; + void *data; snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name); if (rom_file_has_mr) { data = rom_set_mr(rom, OBJECT(fw_cfg), devpath); + ret = memory_region_get_ram_addr(rom->mr); } else { data = rom->data; } @@ -750,7 +843,7 @@ void *rom_add_blob(const char *name, const void *blob, size_t len, fw_callback, callback_opaque, data, rom->romsize); } - return data; + return ret; } /* This function is specific for elf program because we don't need to allocate @@ -955,7 +1048,7 @@ void do_info_roms(Monitor *mon, const QDict *qdict) if (rom->mr) { monitor_printf(mon, "%s" " size=0x%06zx name=\"%s\"\n", - rom->mr->name, + memory_region_name(rom->mr), rom->romsize, rom->name); } else if (!rom->fw_file) { diff --git a/hw/core/machine.c b/hw/core/machine.c index d3ffef7e07..19d3e3a707 100644 --- a/hw/core/machine.c +++ b/hw/core/machine.c @@ -11,6 +11,347 @@ */ #include "hw/boards.h" +#include "qapi/visitor.h" +#include "hw/sysbus.h" +#include "sysemu/sysemu.h" +#include "qemu/error-report.h" + +static char *machine_get_accel(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->accel); +} + +static void machine_set_accel(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->accel); + ms->accel = g_strdup(value); +} + +static bool machine_get_kernel_irqchip(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return ms->kernel_irqchip; +} + +static void machine_set_kernel_irqchip(Object *obj, bool value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + ms->kernel_irqchip = value; +} + +static void machine_get_kvm_shadow_mem(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + MachineState *ms = MACHINE(obj); + int64_t value = ms->kvm_shadow_mem; + + visit_type_int(v, &value, name, errp); +} + +static void machine_set_kvm_shadow_mem(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + MachineState *ms = MACHINE(obj); + Error *error = NULL; + int64_t value; + + visit_type_int(v, &value, name, &error); + if (error) { + error_propagate(errp, error); + return; + } + + ms->kvm_shadow_mem = value; +} + +static char *machine_get_kernel(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->kernel_filename); +} + +static void machine_set_kernel(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->kernel_filename); + ms->kernel_filename = g_strdup(value); +} + +static char *machine_get_initrd(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->initrd_filename); +} + +static void machine_set_initrd(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->initrd_filename); + ms->initrd_filename = g_strdup(value); +} + +static char *machine_get_append(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->kernel_cmdline); +} + +static void machine_set_append(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->kernel_cmdline); + ms->kernel_cmdline = g_strdup(value); +} + +static char *machine_get_dtb(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->dtb); +} + +static void machine_set_dtb(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->dtb); + ms->dtb = g_strdup(value); +} + +static char *machine_get_dumpdtb(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->dumpdtb); +} + +static void machine_set_dumpdtb(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->dumpdtb); + ms->dumpdtb = g_strdup(value); +} + +static void machine_get_phandle_start(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + MachineState *ms = MACHINE(obj); + int64_t value = ms->phandle_start; + + visit_type_int(v, &value, name, errp); +} + +static void machine_set_phandle_start(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + MachineState *ms = MACHINE(obj); + Error *error = NULL; + int64_t value; + + visit_type_int(v, &value, name, &error); + if (error) { + error_propagate(errp, error); + return; + } + + ms->phandle_start = value; +} + +static char *machine_get_dt_compatible(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->dt_compatible); +} + +static void machine_set_dt_compatible(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->dt_compatible); + ms->dt_compatible = g_strdup(value); +} + +static bool machine_get_dump_guest_core(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return ms->dump_guest_core; +} + +static void machine_set_dump_guest_core(Object *obj, bool value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + ms->dump_guest_core = value; +} + +static bool machine_get_mem_merge(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return ms->mem_merge; +} + +static void machine_set_mem_merge(Object *obj, bool value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + ms->mem_merge = value; +} + +static bool machine_get_usb(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return ms->usb; +} + +static void machine_set_usb(Object *obj, bool value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + ms->usb = value; +} + +static char *machine_get_firmware(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return g_strdup(ms->firmware); +} + +static void machine_set_firmware(Object *obj, const char *value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->firmware); + ms->firmware = g_strdup(value); +} + +static bool machine_get_iommu(Object *obj, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + return ms->iommu; +} + +static void machine_set_iommu(Object *obj, bool value, Error **errp) +{ + MachineState *ms = MACHINE(obj); + + ms->iommu = value; +} + +static int error_on_sysbus_device(SysBusDevice *sbdev, void *opaque) +{ + error_report("Option '-device %s' cannot be handled by this machine", + object_class_get_name(object_get_class(OBJECT(sbdev)))); + exit(1); +} + +static void machine_init_notify(Notifier *notifier, void *data) +{ + Object *machine = qdev_get_machine(); + ObjectClass *oc = object_get_class(machine); + MachineClass *mc = MACHINE_CLASS(oc); + + if (mc->has_dynamic_sysbus) { + /* Our machine can handle dynamic sysbus devices, we're all good */ + return; + } + + /* + * Loop through all dynamically created devices and check whether there + * are sysbus devices among them. If there are, error out. + */ + foreach_dynamic_sysbus_device(error_on_sysbus_device, NULL); +} + +static void machine_initfn(Object *obj) +{ + MachineState *ms = MACHINE(obj); + + object_property_add_str(obj, "accel", + machine_get_accel, machine_set_accel, NULL); + object_property_add_bool(obj, "kernel-irqchip", + machine_get_kernel_irqchip, + machine_set_kernel_irqchip, + NULL); + object_property_add(obj, "kvm-shadow-mem", "int", + machine_get_kvm_shadow_mem, + machine_set_kvm_shadow_mem, + NULL, NULL, NULL); + object_property_add_str(obj, "kernel", + machine_get_kernel, machine_set_kernel, NULL); + object_property_add_str(obj, "initrd", + machine_get_initrd, machine_set_initrd, NULL); + object_property_add_str(obj, "append", + machine_get_append, machine_set_append, NULL); + object_property_add_str(obj, "dtb", + machine_get_dtb, machine_set_dtb, NULL); + object_property_add_str(obj, "dumpdtb", + machine_get_dumpdtb, machine_set_dumpdtb, NULL); + object_property_add(obj, "phandle-start", "int", + machine_get_phandle_start, + machine_set_phandle_start, + NULL, NULL, NULL); + object_property_add_str(obj, "dt-compatible", + machine_get_dt_compatible, + machine_set_dt_compatible, + NULL); + object_property_add_bool(obj, "dump-guest-core", + machine_get_dump_guest_core, + machine_set_dump_guest_core, + NULL); + object_property_add_bool(obj, "mem-merge", + machine_get_mem_merge, + machine_set_mem_merge, NULL); + object_property_add_bool(obj, "usb", + machine_get_usb, + machine_set_usb, NULL); + object_property_add_str(obj, "firmware", + machine_get_firmware, + machine_set_firmware, NULL); + object_property_add_bool(obj, "iommu", + machine_get_iommu, + machine_set_iommu, NULL); + + /* Register notifier when init is done for sysbus sanity checks */ + ms->sysbus_notifier.notify = machine_init_notify; + qemu_add_machine_init_done_notifier(&ms->sysbus_notifier); +} + +static void machine_finalize(Object *obj) +{ + MachineState *ms = MACHINE(obj); + + g_free(ms->accel); + g_free(ms->kernel_filename); + g_free(ms->initrd_filename); + g_free(ms->kernel_cmdline); + g_free(ms->dtb); + g_free(ms->dumpdtb); + g_free(ms->dt_compatible); + g_free(ms->firmware); +} static const TypeInfo machine_info = { .name = TYPE_MACHINE, @@ -18,6 +359,8 @@ static const TypeInfo machine_info = { .abstract = true, .class_size = sizeof(MachineClass), .instance_size = sizeof(MachineState), + .instance_init = machine_initfn, + .instance_finalize = machine_finalize, }; static void machine_register_types(void) diff --git a/hw/core/nmi.c b/hw/core/nmi.c new file mode 100644 index 0000000000..3dff020659 --- /dev/null +++ b/hw/core/nmi.c @@ -0,0 +1,84 @@ +/* + * NMI monitor handler class and helpers. + * + * Copyright IBM Corp., 2014 + * + * Author: Alexey Kardashevskiy <aik@ozlabs.ru> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, + * or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "hw/nmi.h" +#include "qapi/qmp/qerror.h" + +struct do_nmi_s { + int cpu_index; + Error *errp; + bool handled; +}; + +static void nmi_children(Object *o, struct do_nmi_s *ns); + +static int do_nmi(Object *o, void *opaque) +{ + struct do_nmi_s *ns = opaque; + NMIState *n = (NMIState *) object_dynamic_cast(o, TYPE_NMI); + + if (n) { + NMIClass *nc = NMI_GET_CLASS(n); + + ns->handled = true; + nc->nmi_monitor_handler(n, ns->cpu_index, &ns->errp); + if (ns->errp) { + return -1; + } + } + nmi_children(o, ns); + + return 0; +} + +static void nmi_children(Object *o, struct do_nmi_s *ns) +{ + object_child_foreach(o, do_nmi, ns); +} + +void nmi_monitor_handle(int cpu_index, Error **errp) +{ + struct do_nmi_s ns = { + .cpu_index = cpu_index, + .errp = NULL, + .handled = false + }; + + nmi_children(object_get_root(), &ns); + if (ns.handled) { + error_propagate(errp, ns.errp); + } else { + error_set(errp, QERR_UNSUPPORTED); + } +} + +static const TypeInfo nmi_info = { + .name = TYPE_NMI, + .parent = TYPE_INTERFACE, + .class_size = sizeof(NMIClass), +}; + +static void nmi_register_types(void) +{ + type_register_static(&nmi_info); +} + +type_init(nmi_register_types) diff --git a/hw/core/null-machine.c b/hw/core/null-machine.c index d813c089e7..1ec7c3bbe0 100644 --- a/hw/core/null-machine.c +++ b/hw/core/null-machine.c @@ -15,7 +15,7 @@ #include "hw/hw.h" #include "hw/boards.h" -static void machine_none_init(QEMUMachineInitArgs *args) +static void machine_none_init(MachineState *machine) { } diff --git a/hw/core/platform-bus.c b/hw/core/platform-bus.c new file mode 100644 index 0000000000..0f052b3338 --- /dev/null +++ b/hw/core/platform-bus.c @@ -0,0 +1,253 @@ +/* + * Platform Bus device to support dynamic Sysbus devices + * + * Copyright (C) 2014 Freescale Semiconductor, Inc. All rights reserved. + * + * Author: Alexander Graf, <agraf@suse.de> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "hw/platform-bus.h" +#include "monitor/monitor.h" +#include "exec/address-spaces.h" +#include "sysemu/sysemu.h" + + +/* + * Returns the PlatformBus IRQ number for a SysBusDevice irq number or -1 if + * the IRQ is not mapped on this Platform bus. + */ +int platform_bus_get_irqn(PlatformBusDevice *pbus, SysBusDevice *sbdev, + int n) +{ + qemu_irq sbirq = sysbus_get_connected_irq(sbdev, n); + int i; + + for (i = 0; i < pbus->num_irqs; i++) { + if (pbus->irqs[i] == sbirq) { + return i; + } + } + + /* IRQ not mapped on platform bus */ + return -1; +} + +/* + * Returns the PlatformBus MMIO region offset for Region n of a SysBusDevice or + * -1 if the region is not mapped on this Platform bus. + */ +hwaddr platform_bus_get_mmio_addr(PlatformBusDevice *pbus, SysBusDevice *sbdev, + int n) +{ + MemoryRegion *pbus_mr = &pbus->mmio; + MemoryRegion *sbdev_mr = sysbus_mmio_get_region(sbdev, n); + Object *pbus_mr_obj = OBJECT(pbus_mr); + Object *parent_mr; + + if (!memory_region_is_mapped(sbdev_mr)) { + /* Region is not mapped? */ + return -1; + } + + parent_mr = object_property_get_link(OBJECT(sbdev_mr), "container", NULL); + + assert(parent_mr); + if (parent_mr != pbus_mr_obj) { + /* MMIO region is not mapped on platform bus */ + return -1; + } + + return object_property_get_int(OBJECT(sbdev_mr), "addr", NULL); +} + +static int platform_bus_count_irqs(SysBusDevice *sbdev, void *opaque) +{ + PlatformBusDevice *pbus = opaque; + qemu_irq sbirq; + int n, i; + + for (n = 0; ; n++) { + if (!sysbus_has_irq(sbdev, n)) { + break; + } + + sbirq = sysbus_get_connected_irq(sbdev, n); + for (i = 0; i < pbus->num_irqs; i++) { + if (pbus->irqs[i] == sbirq) { + bitmap_set(pbus->used_irqs, i, 1); + break; + } + } + } + + return 0; +} + +/* + * Loop through all sysbus devices and look for unassigned IRQ lines as well as + * unassociated MMIO regions. Connect them to the platform bus if available. + */ +static void plaform_bus_refresh_irqs(PlatformBusDevice *pbus) +{ + bitmap_zero(pbus->used_irqs, pbus->num_irqs); + foreach_dynamic_sysbus_device(platform_bus_count_irqs, pbus); + pbus->done_gathering = true; +} + +static int platform_bus_map_irq(PlatformBusDevice *pbus, SysBusDevice *sbdev, + int n) +{ + int max_irqs = pbus->num_irqs; + int irqn; + + if (sysbus_is_irq_connected(sbdev, n)) { + /* IRQ is already mapped, nothing to do */ + return 0; + } + + irqn = find_first_zero_bit(pbus->used_irqs, max_irqs); + if (irqn >= max_irqs) { + hw_error("Platform Bus: Can not fit IRQ line"); + return -1; + } + + set_bit(irqn, pbus->used_irqs); + sysbus_connect_irq(sbdev, n, pbus->irqs[irqn]); + + return 0; +} + +static int platform_bus_map_mmio(PlatformBusDevice *pbus, SysBusDevice *sbdev, + int n) +{ + MemoryRegion *sbdev_mr = sysbus_mmio_get_region(sbdev, n); + uint64_t size = memory_region_size(sbdev_mr); + uint64_t alignment = (1ULL << (63 - clz64(size + size - 1))); + uint64_t off; + bool found_region = false; + + if (memory_region_is_mapped(sbdev_mr)) { + /* Region is already mapped, nothing to do */ + return 0; + } + + /* + * Look for empty space in the MMIO space that is naturally aligned with + * the target device's memory region + */ + for (off = 0; off < pbus->mmio_size; off += alignment) { + if (!memory_region_find(&pbus->mmio, off, size).mr) { + found_region = true; + break; + } + } + + if (!found_region) { + hw_error("Platform Bus: Can not fit MMIO region of size %"PRIx64, size); + } + + /* Map the device's region into our Platform Bus MMIO space */ + memory_region_add_subregion(&pbus->mmio, off, sbdev_mr); + + return 0; +} + +/* + * For each sysbus device, look for unassigned IRQ lines as well as + * unassociated MMIO regions. Connect them to the platform bus if available. + */ +static int link_sysbus_device(SysBusDevice *sbdev, void *opaque) +{ + PlatformBusDevice *pbus = opaque; + int i; + + for (i = 0; sysbus_has_irq(sbdev, i); i++) { + platform_bus_map_irq(pbus, sbdev, i); + } + + for (i = 0; sysbus_has_mmio(sbdev, i); i++) { + platform_bus_map_mmio(pbus, sbdev, i); + } + + return 0; +} + +static void platform_bus_init_notify(Notifier *notifier, void *data) +{ + PlatformBusDevice *pb = container_of(notifier, PlatformBusDevice, notifier); + + /* + * Generate a bitmap of used IRQ lines, as the user might have specified + * them on the command line. + */ + plaform_bus_refresh_irqs(pb); + + foreach_dynamic_sysbus_device(link_sysbus_device, pb); +} + +static void platform_bus_realize(DeviceState *dev, Error **errp) +{ + PlatformBusDevice *pbus; + SysBusDevice *d; + int i; + + d = SYS_BUS_DEVICE(dev); + pbus = PLATFORM_BUS_DEVICE(dev); + + memory_region_init(&pbus->mmio, NULL, "platform bus", pbus->mmio_size); + sysbus_init_mmio(d, &pbus->mmio); + + pbus->used_irqs = bitmap_new(pbus->num_irqs); + pbus->irqs = g_new0(qemu_irq, pbus->num_irqs); + for (i = 0; i < pbus->num_irqs; i++) { + sysbus_init_irq(d, &pbus->irqs[i]); + } + + /* + * Register notifier that allows us to gather dangling devices once the + * machine is completely assembled + */ + pbus->notifier.notify = platform_bus_init_notify; + qemu_add_machine_init_done_notifier(&pbus->notifier); +} + +static Property platform_bus_properties[] = { + DEFINE_PROP_UINT32("num_irqs", PlatformBusDevice, num_irqs, 0), + DEFINE_PROP_UINT32("mmio_size", PlatformBusDevice, mmio_size, 0), + DEFINE_PROP_END_OF_LIST() +}; + +static void platform_bus_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + + dc->realize = platform_bus_realize; + dc->props = platform_bus_properties; +} + +static const TypeInfo platform_bus_info = { + .name = TYPE_PLATFORM_BUS_DEVICE, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(PlatformBusDevice), + .class_init = platform_bus_class_init, +}; + +static void platform_bus_register_types(void) +{ + type_register_static(&platform_bus_info); +} + +type_init(platform_bus_register_types) diff --git a/hw/core/ptimer.c b/hw/core/ptimer.c index 3036bde1f3..466e543b3d 100644 --- a/hw/core/ptimer.c +++ b/hw/core/ptimer.c @@ -206,8 +206,7 @@ const VMStateDescription vmstate_ptimer = { .name = "ptimer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(enabled, ptimer_state), VMSTATE_UINT64(limit, ptimer_state), VMSTATE_UINT64(delta, ptimer_state), diff --git a/hw/core/qdev-properties-system.c b/hw/core/qdev-properties-system.c index de835612f0..65901ef10e 100644 --- a/hw/core/qdev-properties-system.c +++ b/hw/core/qdev-properties-system.c @@ -13,6 +13,7 @@ #include "net/net.h" #include "hw/qdev.h" #include "qapi/qmp/qerror.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/block/block.h" #include "net/hub.h" @@ -68,16 +69,16 @@ static void set_pointer(Object *obj, Visitor *v, Property *prop, static int parse_drive(DeviceState *dev, const char *str, void **ptr) { - BlockDriverState *bs; + BlockBackend *blk; - bs = bdrv_find(str); - if (bs == NULL) { + blk = blk_by_name(str); + if (!blk) { return -ENOENT; } - if (bdrv_attach_dev(bs, dev) < 0) { + if (blk_attach_dev(blk, dev) < 0) { return -EEXIST; } - *ptr = bs; + *ptr = blk; return 0; } @@ -85,17 +86,17 @@ static void release_drive(Object *obj, const char *name, void *opaque) { DeviceState *dev = DEVICE(obj); Property *prop = opaque; - BlockDriverState **ptr = qdev_get_prop_ptr(dev, prop); + BlockBackend **ptr = qdev_get_prop_ptr(dev, prop); if (*ptr) { - bdrv_detach_dev(*ptr, dev); + blk_detach_dev(*ptr, dev); blockdev_auto_del(*ptr); } } static char *print_drive(void *ptr) { - return g_strdup(bdrv_get_device_name(ptr)); + return g_strdup(blk_name(ptr)); } static void get_drive(Object *obj, Visitor *v, void *opaque, @@ -112,7 +113,7 @@ static void set_drive(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_drive = { .name = "str", - .legacy_name = "drive", + .description = "ID of a drive to use as a backend", .get = get_drive, .set = set_drive, .release = release_drive, @@ -169,7 +170,7 @@ static void set_chr(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_chr = { .name = "str", - .legacy_name = "chr", + .description = "ID of a chardev to use as a backend", .get = get_chr, .set = set_chr, .release = release_chr, @@ -180,7 +181,6 @@ PropertyInfo qdev_prop_chr = { static int parse_netdev(DeviceState *dev, const char *str, void **ptr) { NICPeers *peers_ptr = (NICPeers *)ptr; - NICConf *conf = container_of(peers_ptr, NICConf, peers); NetClientState **ncs = peers_ptr->ncs; NetClientState *peers[MAX_QUEUE_NUM]; int queues, i = 0; @@ -219,7 +219,7 @@ static int parse_netdev(DeviceState *dev, const char *str, void **ptr) ncs[i]->queue_index = i; } - conf->queues = queues; + peers_ptr->queues = queues; return 0; @@ -249,7 +249,7 @@ static void set_netdev(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_netdev = { .name = "str", - .legacy_name = "netdev", + .description = "ID of a netdev to use as a backend", .get = get_netdev, .set = set_netdev, }; @@ -329,29 +329,28 @@ static void set_vlan(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_vlan = { .name = "int32", - .legacy_name = "vlan", + .description = "Integer VLAN id to connect to", .print = print_vlan, .get = get_vlan, .set = set_vlan, }; int qdev_prop_set_drive(DeviceState *dev, const char *name, - BlockDriverState *value) + BlockBackend *value) { - Error *errp = NULL; - const char *bdrv_name = value ? bdrv_get_device_name(value) : ""; - object_property_set_str(OBJECT(dev), bdrv_name, - name, &errp); - if (errp) { - qerror_report_err(errp); - error_free(errp); + Error *err = NULL; + object_property_set_str(OBJECT(dev), + value ? blk_name(value) : "", name, &err); + if (err) { + qerror_report_err(err); + error_free(err); return -1; } return 0; } void qdev_prop_set_drive_nofail(DeviceState *dev, const char *name, - BlockDriverState *value) + BlockBackend *value) { if (qdev_prop_set_drive(dev, name, value) < 0) { exit(1); @@ -386,56 +385,6 @@ void qdev_set_nic_properties(DeviceState *dev, NICInfo *nd) nd->instantiated = 1; } -/* --- iothread --- */ - -static char *print_iothread(void *ptr) -{ - return iothread_get_id(ptr); -} - -static int parse_iothread(DeviceState *dev, const char *str, void **ptr) -{ - IOThread *iothread; - - iothread = iothread_find(str); - if (!iothread) { - return -ENOENT; - } - object_ref(OBJECT(iothread)); - *ptr = iothread; - return 0; -} - -static void get_iothread(Object *obj, struct Visitor *v, void *opaque, - const char *name, Error **errp) -{ - get_pointer(obj, v, opaque, print_iothread, name, errp); -} - -static void set_iothread(Object *obj, struct Visitor *v, void *opaque, - const char *name, Error **errp) -{ - set_pointer(obj, v, opaque, parse_iothread, name, errp); -} - -static void release_iothread(Object *obj, const char *name, void *opaque) -{ - DeviceState *dev = DEVICE(obj); - Property *prop = opaque; - IOThread **ptr = qdev_get_prop_ptr(dev, prop); - - if (*ptr) { - object_unref(OBJECT(*ptr)); - } -} - -PropertyInfo qdev_prop_iothread = { - .name = "iothread", - .get = get_iothread, - .set = set_iothread, - .release = release_iothread, -}; - static int qdev_add_one_global(QemuOpts *opts, void *opaque) { GlobalProperty *g; @@ -444,6 +393,7 @@ static int qdev_add_one_global(QemuOpts *opts, void *opaque) g->driver = qemu_opt_get(opts, "driver"); g->property = qemu_opt_get(opts, "property"); g->value = qemu_opt_get(opts, "value"); + g->user_provided = true; qdev_prop_register_global(g); return 0; } diff --git a/hw/core/qdev-properties.c b/hw/core/qdev-properties.c index c67acf58b5..2e47f70eb4 100644 --- a/hw/core/qdev-properties.c +++ b/hw/core/qdev-properties.c @@ -1,7 +1,7 @@ #include "net/net.h" #include "hw/qdev.h" #include "qapi/qmp/qerror.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/block/block.h" #include "net/hub.h" #include "qapi/visitor.h" @@ -120,7 +120,7 @@ static void prop_set_bit(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_bit = { .name = "bool", - .legacy_name = "on/off", + .description = "on/off", .get = prop_get_bit, .set = prop_set_bit, }; @@ -455,7 +455,7 @@ inval: PropertyInfo qdev_prop_macaddr = { .name = "str", - .legacy_name = "macaddr", + .description = "Ethernet 6-byte MAC Address, example: 52:54:00:12:34:56", .get = get_mac, .set = set_mac, }; @@ -477,7 +477,8 @@ QEMU_BUILD_BUG_ON(sizeof(BiosAtaTranslation) != sizeof(int)); PropertyInfo qdev_prop_bios_chs_trans = { .name = "BiosAtaTranslation", - .legacy_name = "bios-chs-trans", + .description = "Logical CHS translation algorithm, " + "auto/none/lba/large/rechs", .enum_table = BiosAtaTranslation_lookup, .get = get_enum, .set = set_enum, @@ -551,7 +552,7 @@ static int print_pci_devfn(DeviceState *dev, Property *prop, char *dest, PropertyInfo qdev_prop_pci_devfn = { .name = "int32", - .legacy_name = "pci-devfn", + .description = "Slot and optional function number, example: 06.0 or 06", .print = print_pci_devfn, .get = get_int32, .set = set_pci_devfn, @@ -587,8 +588,9 @@ static void set_blocksize(Object *obj, Visitor *v, void *opaque, /* We rely on power-of-2 blocksizes for bitmasks */ if ((value & (value - 1)) != 0) { - error_set(errp, QERR_PROPERTY_VALUE_NOT_POWER_OF_2, - dev->id?:"", name, (int64_t)value); + error_setg(errp, + "Property %s.%s doesn't take value '%" PRId64 "', it's not a power of 2", + dev->id ?: "", name, (int64_t)value); return; } @@ -597,7 +599,7 @@ static void set_blocksize(Object *obj, Visitor *v, void *opaque, PropertyInfo qdev_prop_blocksize = { .name = "uint16", - .legacy_name = "blocksize", + .description = "A power of two between 512 and 32768", .get = get_uint16, .set = set_blocksize, }; @@ -705,7 +707,8 @@ inval: PropertyInfo qdev_prop_pci_host_devaddr = { .name = "str", - .legacy_name = "pci-host-devaddr", + .description = "Address (bus/device/function) of " + "the host device, example: 04:10.0", .get = get_pci_host_devaddr, .set = set_pci_host_devaddr, }; @@ -750,6 +753,7 @@ static void set_prop_arraylen(Object *obj, Visitor *v, void *opaque, Property *prop = opaque; uint32_t *alenptr = qdev_get_prop_ptr(dev, prop); void **arrayptr = (void *)dev + prop->arrayoffset; + Error *local_err = NULL; void *eltptr; const char *arrayname; int i; @@ -763,8 +767,9 @@ static void set_prop_arraylen(Object *obj, Visitor *v, void *opaque, name); return; } - visit_type_uint32(v, alenptr, name, errp); - if (error_is_set(errp)) { + visit_type_uint32(v, alenptr, name, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } if (!*alenptr) { @@ -801,8 +806,9 @@ static void set_prop_arraylen(Object *obj, Visitor *v, void *opaque, arrayprop->prop.info->get, arrayprop->prop.info->set, array_element_release, - arrayprop, errp); - if (error_is_set(errp)) { + arrayprop, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } } @@ -853,7 +859,7 @@ void error_set_from_qdev_prop_error(Error **errp, int ret, DeviceState *dev, { switch (ret) { case -EEXIST: - error_set(errp, QERR_PROPERTY_VALUE_IN_USE, + error_setg(errp, "Property '%s.%s' can't take value '%s', it's in use", object_get_typename(OBJECT(dev)), prop->name, value); break; default: @@ -862,7 +868,7 @@ void error_set_from_qdev_prop_error(Error **errp, int ret, DeviceState *dev, object_get_typename(OBJECT(dev)), prop->name, value); break; case -ENOENT: - error_set(errp, QERR_PROPERTY_VALUE_NOT_FOUND, + error_setg(errp, "Property '%s.%s' can't find value '%s'", object_get_typename(OBJECT(dev)), prop->name, value); break; case 0: @@ -951,6 +957,39 @@ void qdev_prop_register_global_list(GlobalProperty *props) } } +int qdev_prop_check_globals(void) +{ + GlobalProperty *prop; + int ret = 0; + + QTAILQ_FOREACH(prop, &global_props, next) { + ObjectClass *oc; + DeviceClass *dc; + if (prop->used) { + continue; + } + if (!prop->user_provided) { + continue; + } + oc = object_class_by_name(prop->driver); + oc = object_class_dynamic_cast(oc, TYPE_DEVICE); + if (!oc) { + error_report("Warning: global %s.%s has invalid class name", + prop->driver, prop->property); + ret = 1; + continue; + } + dc = DEVICE_CLASS(oc); + if (!dc->hotpluggable && !prop->used) { + error_report("Warning: global %s.%s=%s not used", + prop->driver, prop->property, prop->value); + ret = 1; + continue; + } + } + return ret; +} + void qdev_prop_set_globals_for_type(DeviceState *dev, const char *typename, Error **errp) { @@ -962,6 +1001,7 @@ void qdev_prop_set_globals_for_type(DeviceState *dev, const char *typename, if (strcmp(typename, prop->driver) != 0) { continue; } + prop->used = true; object_property_parse(OBJECT(dev), prop->value, prop->property, &err); if (err != NULL) { error_propagate(errp, err); diff --git a/hw/core/qdev.c b/hw/core/qdev.c index 60f9df1ed9..35fd00d26c 100644 --- a/hw/core/qdev.c +++ b/hw/core/qdev.c @@ -32,8 +32,9 @@ #include "qapi/qmp/qerror.h" #include "qapi/visitor.h" #include "qapi/qmp/qjson.h" -#include "monitor/monitor.h" #include "hw/hotplug.h" +#include "hw/boards.h" +#include "qapi-event.h" int qdev_hotplug = 0; static bool qdev_hot_added = false; @@ -84,10 +85,6 @@ static void bus_add_child(BusState *bus, DeviceState *child) char name[32]; BusChild *kid = g_malloc0(sizeof(*kid)); - if (qdev_hotplug) { - assert(bus->allow_hotplug); - } - kid->index = bus->max_index++; kid->child = child; object_ref(OBJECT(kid->child)); @@ -111,6 +108,24 @@ void qdev_set_parent_bus(DeviceState *dev, BusState *bus) bus_add_child(bus, dev); } +static void qbus_set_hotplug_handler_internal(BusState *bus, Object *handler, + Error **errp) +{ + + object_property_set_link(OBJECT(bus), OBJECT(handler), + QDEV_HOTPLUG_HANDLER_PROPERTY, errp); +} + +void qbus_set_hotplug_handler(BusState *bus, DeviceState *handler, Error **errp) +{ + qbus_set_hotplug_handler_internal(bus, OBJECT(handler), errp); +} + +void qbus_set_bus_hotplug_handler(BusState *bus, Error **errp) +{ + qbus_set_hotplug_handler_internal(bus, OBJECT(bus), errp); +} + /* Create a new device. This only initializes the device state structure and allows properties to be set. qdev_init should be called to initialize the actual device emulation. */ @@ -174,14 +189,14 @@ int qdev_init(DeviceState *dev) return 0; } -static void device_realize(DeviceState *dev, Error **err) +static void device_realize(DeviceState *dev, Error **errp) { DeviceClass *dc = DEVICE_GET_CLASS(dev); if (dc->init) { int rc = dc->init(dev); if (rc < 0) { - error_setg(err, "Device initialization failed."); + error_setg(errp, "Device initialization failed."); return; } } @@ -208,11 +223,30 @@ void qdev_set_legacy_instance_id(DeviceState *dev, int alias_id, dev->alias_required_for_version = required_for_version; } +static HotplugHandler *qdev_get_hotplug_handler(DeviceState *dev) +{ + HotplugHandler *hotplug_ctrl = NULL; + + if (dev->parent_bus && dev->parent_bus->hotplug_handler) { + hotplug_ctrl = dev->parent_bus->hotplug_handler; + } else if (object_dynamic_cast(qdev_get_machine(), TYPE_MACHINE)) { + MachineState *machine = MACHINE(qdev_get_machine()); + MachineClass *mc = MACHINE_GET_CLASS(machine); + + if (mc->get_hotplug_handler) { + hotplug_ctrl = mc->get_hotplug_handler(machine, dev); + } + } + return hotplug_ctrl; +} + void qdev_unplug(DeviceState *dev, Error **errp) { DeviceClass *dc = DEVICE_GET_CLASS(dev); + HotplugHandler *hotplug_ctrl; + HotplugHandlerClass *hdc; - if (dev->parent_bus && !dev->parent_bus->allow_hotplug) { + if (dev->parent_bus && !qbus_is_hotpluggable(dev->parent_bus)) { error_set(errp, QERR_BUS_NO_HOTPLUG, dev->parent_bus->name); return; } @@ -225,13 +259,18 @@ void qdev_unplug(DeviceState *dev, Error **errp) qdev_hot_removed = true; - if (dev->parent_bus && dev->parent_bus->hotplug_handler) { - hotplug_handler_unplug(dev->parent_bus->hotplug_handler, dev, errp); + hotplug_ctrl = qdev_get_hotplug_handler(dev); + /* hotpluggable device MUST have HotplugHandler, if it doesn't + * then something is very wrong with it */ + g_assert(hotplug_ctrl); + + /* If device supports async unplug just request it to be done, + * otherwise just remove it synchronously */ + hdc = HOTPLUG_HANDLER_GET_CLASS(hotplug_ctrl); + if (hdc->unplug_request) { + hotplug_handler_unplug_request(hotplug_ctrl, dev, errp); } else { - assert(dc->unplug != NULL); - if (dc->unplug(dev) < 0) { /* legacy handler */ - error_set(errp, QERR_UNDEFINED_ERROR); - } + hotplug_handler_unplug(hotplug_ctrl, dev, errp); } } @@ -268,14 +307,13 @@ void qbus_reset_all_fn(void *opaque) } /* can be used as ->unplug() callback for the simple cases */ -int qdev_simple_unplug_cb(DeviceState *dev) +void qdev_simple_device_unplug_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { /* just zap it */ object_unparent(OBJECT(dev)); - return 0; } - /* Like qdev_init(), but terminate program via error_report() instead of returning an error value. This is okay during machine creation. Don't use for hotplug, because there callers need to recover from @@ -312,30 +350,174 @@ BusState *qdev_get_parent_bus(DeviceState *dev) return dev->parent_bus; } +static NamedGPIOList *qdev_get_named_gpio_list(DeviceState *dev, + const char *name) +{ + NamedGPIOList *ngl; + + QLIST_FOREACH(ngl, &dev->gpios, node) { + /* NULL is a valid and matchable name, otherwise do a normal + * strcmp match. + */ + if ((!ngl->name && !name) || + (name && ngl->name && strcmp(name, ngl->name) == 0)) { + return ngl; + } + } + + ngl = g_malloc0(sizeof(*ngl)); + ngl->name = g_strdup(name); + QLIST_INSERT_HEAD(&dev->gpios, ngl, node); + return ngl; +} + +void qdev_init_gpio_in_named(DeviceState *dev, qemu_irq_handler handler, + const char *name, int n) +{ + int i; + NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name); + char *propname = g_strdup_printf("%s[*]", name ? name : "unnamed-gpio-in"); + + assert(gpio_list->num_out == 0 || !name); + gpio_list->in = qemu_extend_irqs(gpio_list->in, gpio_list->num_in, handler, + dev, n); + + for (i = gpio_list->num_in; i < gpio_list->num_in + n; i++) { + object_property_add_child(OBJECT(dev), propname, + OBJECT(gpio_list->in[i]), &error_abort); + } + g_free(propname); + + gpio_list->num_in += n; +} + void qdev_init_gpio_in(DeviceState *dev, qemu_irq_handler handler, int n) { - dev->gpio_in = qemu_extend_irqs(dev->gpio_in, dev->num_gpio_in, handler, - dev, n); - dev->num_gpio_in += n; + qdev_init_gpio_in_named(dev, handler, NULL, n); +} + +void qdev_init_gpio_out_named(DeviceState *dev, qemu_irq *pins, + const char *name, int n) +{ + int i; + NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name); + char *propname = g_strdup_printf("%s[*]", name ? name : "unnamed-gpio-out"); + + assert(gpio_list->num_in == 0 || !name); + gpio_list->num_out += n; + + for (i = 0; i < n; ++i) { + memset(&pins[i], 0, sizeof(*pins)); + object_property_add_link(OBJECT(dev), propname, TYPE_IRQ, + (Object **)&pins[i], + object_property_allow_set_link, + OBJ_PROP_LINK_UNREF_ON_RELEASE, + &error_abort); + } + g_free(propname); } void qdev_init_gpio_out(DeviceState *dev, qemu_irq *pins, int n) { - assert(dev->num_gpio_out == 0); - dev->num_gpio_out = n; - dev->gpio_out = pins; + qdev_init_gpio_out_named(dev, pins, NULL, n); +} + +qemu_irq qdev_get_gpio_in_named(DeviceState *dev, const char *name, int n) +{ + NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name); + + assert(n >= 0 && n < gpio_list->num_in); + return gpio_list->in[n]; } qemu_irq qdev_get_gpio_in(DeviceState *dev, int n) { - assert(n >= 0 && n < dev->num_gpio_in); - return dev->gpio_in[n]; + return qdev_get_gpio_in_named(dev, NULL, n); +} + +void qdev_connect_gpio_out_named(DeviceState *dev, const char *name, int n, + qemu_irq pin) +{ + char *propname = g_strdup_printf("%s[%d]", + name ? name : "unnamed-gpio-out", n); + if (pin) { + /* We need a name for object_property_set_link to work. If the + * object has a parent, object_property_add_child will come back + * with an error without doing anything. If it has none, it will + * never fail. So we can just call it with a NULL Error pointer. + */ + object_property_add_child(qdev_get_machine(), "non-qdev-gpio[*]", + OBJECT(pin), NULL); + } + object_property_set_link(OBJECT(dev), OBJECT(pin), propname, &error_abort); + g_free(propname); +} + +qemu_irq qdev_get_gpio_out_connector(DeviceState *dev, const char *name, int n) +{ + char *propname = g_strdup_printf("%s[%d]", + name ? name : "unnamed-gpio-out", n); + + qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname, + NULL); + + return ret; +} + +/* disconnect a GPIO ouput, returning the disconnected input (if any) */ + +static qemu_irq qdev_disconnect_gpio_out_named(DeviceState *dev, + const char *name, int n) +{ + char *propname = g_strdup_printf("%s[%d]", + name ? name : "unnamed-gpio-out", n); + + qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname, + NULL); + if (ret) { + object_property_set_link(OBJECT(dev), NULL, propname, NULL); + } + g_free(propname); + return ret; +} + +qemu_irq qdev_intercept_gpio_out(DeviceState *dev, qemu_irq icpt, + const char *name, int n) +{ + qemu_irq disconnected = qdev_disconnect_gpio_out_named(dev, name, n); + qdev_connect_gpio_out_named(dev, name, n, icpt); + return disconnected; } void qdev_connect_gpio_out(DeviceState * dev, int n, qemu_irq pin) { - assert(n >= 0 && n < dev->num_gpio_out); - dev->gpio_out[n] = pin; + qdev_connect_gpio_out_named(dev, NULL, n, pin); +} + +void qdev_pass_gpios(DeviceState *dev, DeviceState *container, + const char *name) +{ + int i; + NamedGPIOList *ngl = qdev_get_named_gpio_list(dev, name); + + for (i = 0; i < ngl->num_in; i++) { + const char *nm = ngl->name ? ngl->name : "unnamed-gpio-in"; + char *propname = g_strdup_printf("%s[%d]", nm, i); + + object_property_add_alias(OBJECT(container), propname, + OBJECT(dev), propname, + &error_abort); + } + for (i = 0; i < ngl->num_out; i++) { + const char *nm = ngl->name ? ngl->name : "unnamed-gpio-out"; + char *propname = g_strdup_printf("%s[%d]", nm, i); + + object_property_add_alias(OBJECT(container), propname, + OBJECT(dev), propname, + &error_abort); + } + QLIST_REMOVE(ngl, node); + QLIST_INSERT_HEAD(&container->gpios, ngl, node); } BusState *qdev_get_child_bus(DeviceState *dev, const char *name) @@ -504,43 +686,46 @@ static void bus_unparent(Object *obj) } } -static bool bus_get_realized(Object *obj, Error **err) +static bool bus_get_realized(Object *obj, Error **errp) { BusState *bus = BUS(obj); return bus->realized; } -static void bus_set_realized(Object *obj, bool value, Error **err) +static void bus_set_realized(Object *obj, bool value, Error **errp) { BusState *bus = BUS(obj); BusClass *bc = BUS_GET_CLASS(bus); + BusChild *kid; Error *local_err = NULL; if (value && !bus->realized) { if (bc->realize) { bc->realize(bus, &local_err); + } + /* TODO: recursive realization */ + } else if (!value && bus->realized) { + QTAILQ_FOREACH(kid, &bus->children, sibling) { + DeviceState *dev = kid->child; + object_property_set_bool(OBJECT(dev), false, "realized", + &local_err); if (local_err != NULL) { - goto error; + break; } - } - } else if (!value && bus->realized) { - if (bc->unrealize) { + if (bc->unrealize && local_err == NULL) { bc->unrealize(bus, &local_err); - - if (local_err != NULL) { - goto error; - } } } - bus->realized = value; - return; + if (local_err != NULL) { + error_propagate(errp, local_err); + return; + } -error: - error_propagate(err, local_err); + bus->realized = value; } void qbus_create_inplace(void *bus, size_t size, const char *typename, @@ -660,8 +845,8 @@ static void qdev_get_legacy_property(Object *obj, Visitor *v, void *opaque, * Legacy properties are string versions of other OOM properties. The format * of the string depends on the property type. */ -void qdev_property_add_legacy(DeviceState *dev, Property *prop, - Error **errp) +static void qdev_property_add_legacy(DeviceState *dev, Property *prop, + Error **errp) { gchar *name; @@ -710,6 +895,11 @@ void qdev_property_add_static(DeviceState *dev, Property *prop, error_propagate(errp, local_err); return; } + + object_property_set_description(obj, prop->name, + prop->info->description, + &error_abort); + if (prop->qtype == QTYPE_NONE) { return; } @@ -724,32 +914,75 @@ void qdev_property_add_static(DeviceState *dev, Property *prop, } } -static bool device_get_realized(Object *obj, Error **err) +/* @qdev_alias_all_properties - Add alias properties to the source object for + * all qdev properties on the target DeviceState. + */ +void qdev_alias_all_properties(DeviceState *target, Object *source) +{ + ObjectClass *class; + Property *prop; + + class = object_get_class(OBJECT(target)); + do { + DeviceClass *dc = DEVICE_CLASS(class); + + for (prop = dc->props; prop && prop->name; prop++) { + object_property_add_alias(source, prop->name, + OBJECT(target), prop->name, + &error_abort); + } + class = object_class_get_parent(class); + } while (class != object_class_by_name(TYPE_DEVICE)); +} + +static int qdev_add_hotpluggable_device(Object *obj, void *opaque) +{ + GSList **list = opaque; + DeviceState *dev = DEVICE(obj); + + if (dev->realized && object_property_get_bool(obj, "hotpluggable", NULL)) { + *list = g_slist_append(*list, dev); + } + + return 0; +} + +GSList *qdev_build_hotpluggable_device_list(Object *peripheral) +{ + GSList *list = NULL; + + object_child_foreach(peripheral, qdev_add_hotpluggable_device, &list); + + return list; +} + +static bool device_get_realized(Object *obj, Error **errp) { DeviceState *dev = DEVICE(obj); return dev->realized; } -static void device_set_realized(Object *obj, bool value, Error **err) +static void device_set_realized(Object *obj, bool value, Error **errp) { DeviceState *dev = DEVICE(obj); DeviceClass *dc = DEVICE_GET_CLASS(dev); + HotplugHandler *hotplug_ctrl; BusState *bus; Error *local_err = NULL; if (dev->hotplugged && !dc->hotpluggable) { - error_set(err, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj)); + error_set(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj)); return; } if (value && !dev->realized) { - if (!obj->parent && local_err == NULL) { + if (!obj->parent) { static int unattached_count; gchar *name = g_strdup_printf("device[%d]", unattached_count++); object_property_add_child(container_get(qdev_get_machine(), "/unattached"), - name, obj, &local_err); + name, obj, &error_abort); g_free(name); } @@ -757,60 +990,101 @@ static void device_set_realized(Object *obj, bool value, Error **err) dc->realize(dev, &local_err); } - if (dev->parent_bus && dev->parent_bus->hotplug_handler && - local_err == NULL) { - hotplug_handler_plug(dev->parent_bus->hotplug_handler, - dev, &local_err); + if (local_err != NULL) { + goto fail; } - if (qdev_get_vmsd(dev) && local_err == NULL) { + hotplug_ctrl = qdev_get_hotplug_handler(dev); + if (hotplug_ctrl) { + hotplug_handler_plug(hotplug_ctrl, dev, &local_err); + } + + if (local_err != NULL) { + goto post_realize_fail; + } + + if (qdev_get_vmsd(dev)) { vmstate_register_with_alias_id(dev, -1, qdev_get_vmsd(dev), dev, dev->instance_id_alias, dev->alias_required_for_version); } - if (local_err == NULL) { - QLIST_FOREACH(bus, &dev->child_bus, sibling) { - object_property_set_bool(OBJECT(bus), true, "realized", + + QLIST_FOREACH(bus, &dev->child_bus, sibling) { + object_property_set_bool(OBJECT(bus), true, "realized", &local_err); - if (local_err != NULL) { - break; - } + if (local_err != NULL) { + goto child_realize_fail; } } - if (dev->hotplugged && local_err == NULL) { + if (dev->hotplugged) { device_reset(dev); } + dev->pending_deleted_event = false; } else if (!value && dev->realized) { + Error **local_errp = NULL; QLIST_FOREACH(bus, &dev->child_bus, sibling) { + local_errp = local_err ? NULL : &local_err; object_property_set_bool(OBJECT(bus), false, "realized", - &local_err); - if (local_err != NULL) { - break; - } + local_errp); } - if (qdev_get_vmsd(dev) && local_err == NULL) { + if (qdev_get_vmsd(dev)) { vmstate_unregister(dev, qdev_get_vmsd(dev), dev); } - if (dc->unrealize && local_err == NULL) { - dc->unrealize(dev, &local_err); + if (dc->unrealize) { + local_errp = local_err ? NULL : &local_err; + dc->unrealize(dev, local_errp); } + dev->pending_deleted_event = true; } if (local_err != NULL) { - error_propagate(err, local_err); - return; + goto fail; } dev->realized = value; + return; + +child_realize_fail: + QLIST_FOREACH(bus, &dev->child_bus, sibling) { + object_property_set_bool(OBJECT(bus), false, "realized", + NULL); + } + + if (qdev_get_vmsd(dev)) { + vmstate_unregister(dev, qdev_get_vmsd(dev), dev); + } + +post_realize_fail: + if (dc->unrealize) { + dc->unrealize(dev, NULL); + } + +fail: + error_propagate(errp, local_err); + return; } -static bool device_get_hotpluggable(Object *obj, Error **err) +static bool device_get_hotpluggable(Object *obj, Error **errp) { DeviceClass *dc = DEVICE_GET_CLASS(obj); DeviceState *dev = DEVICE(obj); return dc->hotpluggable && (dev->parent_bus == NULL || - dev->parent_bus->allow_hotplug); + qbus_is_hotpluggable(dev->parent_bus)); +} + +static bool device_get_hotplugged(Object *obj, Error **err) +{ + DeviceState *dev = DEVICE(obj); + + return dev->hotplugged; +} + +static void device_set_hotplugged(Object *obj, bool value, Error **err) +{ + DeviceState *dev = DEVICE(obj); + + dev->hotplugged = value; } static void device_initfn(Object *obj) @@ -831,6 +1105,9 @@ static void device_initfn(Object *obj) device_get_realized, device_set_realized, NULL); object_property_add_bool(obj, "hotpluggable", device_get_hotpluggable, NULL, NULL); + object_property_add_bool(obj, "hotplugged", + device_get_hotplugged, device_set_hotplugged, + &error_abort); class = object_get_class(OBJECT(dev)); do { @@ -844,20 +1121,39 @@ static void device_initfn(Object *obj) object_property_add_link(OBJECT(dev), "parent_bus", TYPE_BUS, (Object **)&dev->parent_bus, NULL, 0, &error_abort); + QLIST_INIT(&dev->gpios); } static void device_post_init(Object *obj) { - qdev_prop_set_globals(DEVICE(obj), &error_abort); + Error *err = NULL; + qdev_prop_set_globals(DEVICE(obj), &err); + if (err) { + qerror_report_err(err); + error_free(err); + exit(EXIT_FAILURE); + } } /* Unlink device from bus and free the structure. */ static void device_finalize(Object *obj) { + NamedGPIOList *ngl, *next; + DeviceState *dev = DEVICE(obj); if (dev->opts) { qemu_opts_del(dev->opts); } + + QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) { + QLIST_REMOVE(ngl, node); + qemu_free_irqs(ngl->in, ngl->num_in); + g_free(ngl->name); + g_free(ngl); + /* ngl->out irqs are owned by the other end and should not be freed + * here + */ + } } static void device_class_base_init(ObjectClass *class, void *data) @@ -874,8 +1170,6 @@ static void device_unparent(Object *obj) { DeviceState *dev = DEVICE(obj); BusState *bus; - QObject *event_data; - bool have_realized = dev->realized; if (dev->realized) { object_property_set_bool(obj, false, "realized", NULL); @@ -891,17 +1185,10 @@ static void device_unparent(Object *obj) } /* Only send event if the device had been completely realized */ - if (have_realized) { + if (dev->pending_deleted_event) { gchar *path = object_get_canonical_path(OBJECT(dev)); - if (dev->id) { - event_data = qobject_from_jsonf("{ 'device': %s, 'path': %s }", - dev->id, path); - } else { - event_data = qobject_from_jsonf("{ 'path': %s }", path); - } - monitor_protocol_event(QEVENT_DEVICE_DELETED, event_data); - qobject_decref(event_data); + qapi_event_send_device_deleted(!!dev->id, dev->id, path, &error_abort); g_free(path); } } diff --git a/hw/core/sysbus.c b/hw/core/sysbus.c index f4e760d6eb..84af59379d 100644 --- a/hw/core/sysbus.c +++ b/hw/core/sysbus.c @@ -24,6 +24,51 @@ static void sysbus_dev_print(Monitor *mon, DeviceState *dev, int indent); static char *sysbus_get_fw_dev_path(DeviceState *dev); +typedef struct SysBusFind { + void *opaque; + FindSysbusDeviceFunc *func; +} SysBusFind; + +/* Run func() for every sysbus device, traverse the tree for everything else */ +static int find_sysbus_device(Object *obj, void *opaque) +{ + SysBusFind *find = opaque; + Object *dev; + SysBusDevice *sbdev; + + dev = object_dynamic_cast(obj, TYPE_SYS_BUS_DEVICE); + sbdev = (SysBusDevice *)dev; + + if (!sbdev) { + /* Container, traverse it for children */ + return object_child_foreach(obj, find_sysbus_device, opaque); + } + + find->func(sbdev, find->opaque); + + return 0; +} + +/* + * Loop through all dynamically created sysbus devices and call + * func() for each instance. + */ +void foreach_dynamic_sysbus_device(FindSysbusDeviceFunc *func, void *opaque) +{ + Object *container; + SysBusFind find = { + .func = func, + .opaque = opaque, + }; + + /* Loop through all sysbus devices that were spawened outside the machine */ + container = container_get(qdev_get_machine(), "/peripheral"); + find_sysbus_device(container, &find); + container = container_get(qdev_get_machine(), "/peripheral-anon"); + find_sysbus_device(container, &find); +} + + static void system_bus_class_init(ObjectClass *klass, void *data) { BusClass *k = BUS_CLASS(klass); @@ -39,13 +84,36 @@ static const TypeInfo system_bus_info = { .class_init = system_bus_class_init, }; +/* Check whether an IRQ source exists */ +bool sysbus_has_irq(SysBusDevice *dev, int n) +{ + char *prop = g_strdup_printf("%s[%d]", SYSBUS_DEVICE_GPIO_IRQ, n); + ObjectProperty *r; + + r = object_property_find(OBJECT(dev), prop, NULL); + return (r != NULL); +} + +bool sysbus_is_irq_connected(SysBusDevice *dev, int n) +{ + return !!sysbus_get_connected_irq(dev, n); +} + +qemu_irq sysbus_get_connected_irq(SysBusDevice *dev, int n) +{ + DeviceState *d = DEVICE(dev); + return qdev_get_gpio_out_connector(d, SYSBUS_DEVICE_GPIO_IRQ, n); +} + void sysbus_connect_irq(SysBusDevice *dev, int n, qemu_irq irq) { - assert(n >= 0 && n < dev->num_irq); - dev->irqs[n] = NULL; - if (dev->irqp[n]) { - *dev->irqp[n] = irq; - } + qdev_connect_gpio_out_named(DEVICE(dev), SYSBUS_DEVICE_GPIO_IRQ, n, irq); +} + +/* Check whether an MMIO region exists */ +bool sysbus_has_mmio(SysBusDevice *dev, unsigned int n) +{ + return (n < dev->num_mmio); } static void sysbus_mmio_map_common(SysBusDevice *dev, int n, hwaddr addr, @@ -89,22 +157,13 @@ void sysbus_mmio_map_overlap(SysBusDevice *dev, int n, hwaddr addr, /* Request an IRQ source. The actual IRQ object may be populated later. */ void sysbus_init_irq(SysBusDevice *dev, qemu_irq *p) { - int n; - - assert(dev->num_irq < QDEV_MAX_IRQ); - n = dev->num_irq++; - dev->irqp[n] = p; + qdev_init_gpio_out_named(DEVICE(dev), p, SYSBUS_DEVICE_GPIO_IRQ, 1); } /* Pass IRQs from a target device. */ void sysbus_pass_irq(SysBusDevice *dev, SysBusDevice *target) { - int i; - assert(dev->num_irq == 0); - dev->num_irq = target->num_irq; - for (i = 0; i < dev->num_irq; i++) { - dev->irqp[i] = target->irqp[i]; - } + qdev_pass_gpios(DEVICE(target), DEVICE(dev), SYSBUS_DEVICE_GPIO_IRQ); } void sysbus_init_mmio(SysBusDevice *dev, MemoryRegion *memory) @@ -210,7 +269,6 @@ static void sysbus_dev_print(Monitor *mon, DeviceState *dev, int indent) hwaddr size; int i; - monitor_printf(mon, "%*sirq %d\n", indent, "", s->num_irq); for (i = 0; i < s->num_mmio; i++) { size = memory_region_size(s->mmio[i].memory); monitor_printf(mon, "%*smmio " TARGET_FMT_plx "/" TARGET_FMT_plx "\n", @@ -242,11 +300,6 @@ void sysbus_add_io(SysBusDevice *dev, hwaddr addr, memory_region_add_subregion(get_system_io(), addr, mem); } -void sysbus_del_io(SysBusDevice *dev, MemoryRegion *mem) -{ - memory_region_del_subregion(get_system_io(), mem); -} - MemoryRegion *sysbus_address_space(SysBusDevice *dev) { return get_system_memory(); @@ -257,13 +310,6 @@ static void sysbus_device_class_init(ObjectClass *klass, void *data) DeviceClass *k = DEVICE_CLASS(klass); k->init = sysbus_device_init; k->bus_type = TYPE_SYSTEM_BUS; - /* - * device_add plugs devices into suitable bus. For "real" buses, - * that actually connects the device. For sysbus, the connections - * need to be made separately, and device_add can't do that. The - * device would be left unconnected, and could not possibly work. - */ - k->cannot_instantiate_with_device_add_yet = true; } static const TypeInfo sysbus_device_type_info = { diff --git a/hw/cpu/icc_bus.c b/hw/cpu/icc_bus.c index 7f44c59b25..6646ea2b34 100644 --- a/hw/cpu/icc_bus.c +++ b/hw/cpu/icc_bus.c @@ -24,18 +24,10 @@ /* icc-bridge implementation */ -static void icc_bus_init(Object *obj) -{ - BusState *b = BUS(obj); - - b->allow_hotplug = true; -} - static const TypeInfo icc_bus_info = { .name = TYPE_ICC_BUS, .parent = TYPE_BUS, .instance_size = sizeof(ICCBus), - .instance_init = icc_bus_init, }; @@ -81,11 +73,11 @@ typedef struct ICCBridgeState { MemoryRegion apic_container; } ICCBridgeState; -#define ICC_BRIGDE(obj) OBJECT_CHECK(ICCBridgeState, (obj), TYPE_ICC_BRIDGE) +#define ICC_BRIDGE(obj) OBJECT_CHECK(ICCBridgeState, (obj), TYPE_ICC_BRIDGE) static void icc_bridge_init(Object *obj) { - ICCBridgeState *s = ICC_BRIGDE(obj); + ICCBridgeState *s = ICC_BRIDGE(obj); SysBusDevice *sb = SYS_BUS_DEVICE(obj); qbus_create_inplace(&s->icc_bus, sizeof(s->icc_bus), TYPE_ICC_BUS, diff --git a/hw/cris/axis_dev88.c b/hw/cris/axis_dev88.c index 645e45ccdf..047919686d 100644 --- a/hw/cris/axis_dev88.c +++ b/hw/cris/axis_dev88.c @@ -30,7 +30,7 @@ #include "hw/loader.h" #include "elf.h" #include "boot.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "sysemu/qtest.h" @@ -243,12 +243,12 @@ static const MemoryRegionOps gpio_ops = { static struct cris_load_info li; static -void axisdev88_init(QEMUMachineInitArgs *args) +void axisdev88_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; CRISCPU *cpu; CPUCRISState *env; DeviceState *dev; @@ -270,19 +270,21 @@ void axisdev88_init(QEMUMachineInitArgs *args) env = &cpu->env; /* allocate RAM */ - memory_region_init_ram(phys_ram, NULL, "axisdev88.ram", ram_size); + memory_region_init_ram(phys_ram, NULL, "axisdev88.ram", ram_size, + &error_abort); vmstate_register_ram_global(phys_ram); memory_region_add_subregion(address_space_mem, 0x40000000, phys_ram); /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the internal memory. */ - memory_region_init_ram(phys_intmem, NULL, "axisdev88.chipram", INTMEM_SIZE); + memory_region_init_ram(phys_intmem, NULL, "axisdev88.chipram", INTMEM_SIZE, + &error_abort); vmstate_register_ram_global(phys_intmem); memory_region_add_subregion(address_space_mem, 0x38000000, phys_intmem); /* Attach a NAND flash to CS1. */ nand = drive_get(IF_MTD, 0, 0); - nand_state.nand = nand_init(nand ? nand->bdrv : NULL, + nand_state.nand = nand_init(nand ? blk_by_legacy_dinfo(nand) : NULL, NAND_MFR_STMICRO, 0x39); memory_region_init_io(&nand_state.iomem, NULL, &nand_ops, &nand_state, "nand", 0x05000000); diff --git a/hw/display/ads7846.c b/hw/display/ads7846.c index 85252a2329..3f35369bb4 100644 --- a/hw/display/ads7846.c +++ b/hw/display/ads7846.c @@ -121,9 +121,8 @@ static const VMStateDescription vmstate_ads7846 = { .name = "ads7846", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = ads7856_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_SSI_SLAVE(ssidev, ADS7846State), VMSTATE_INT32_ARRAY(input, ADS7846State, 8), VMSTATE_INT32(noise, ADS7846State), diff --git a/hw/display/blizzard.c b/hw/display/blizzard.c index 55c0ddf00b..92b1fac563 100644 --- a/hw/display/blizzard.c +++ b/hw/display/blizzard.c @@ -134,14 +134,6 @@ static const int blizzard_iformat_bpp[0x10] = { 0, 0, 0, 0, 0, 0, }; -static inline void blizzard_rgb2yuv(int r, int g, int b, - int *y, int *u, int *v) -{ - *y = 0x10 + ((0x838 * r + 0x1022 * g + 0x322 * b) >> 13); - *u = 0x80 + ((0xe0e * b - 0x04c1 * r - 0x94e * g) >> 13); - *v = 0x80 + ((0xe0e * r - 0x0bc7 * g - 0x247 * b) >> 13); -} - static void blizzard_window(BlizzardState *s) { DisplaySurface *surface = qemu_console_surface(s->con); diff --git a/hw/display/cg3.c b/hw/display/cg3.c index a042b9ecbe..1e6ff2b546 100644 --- a/hw/display/cg3.c +++ b/hw/display/cg3.c @@ -177,7 +177,7 @@ static uint64_t cg3_reg_read(void *opaque, hwaddr addr, unsigned size) /* monitor ID 6, board type = 1 (color) */ val = s->regs[1] | CG3_SR_1152_900_76_B | CG3_SR_ID_COLOR; break; - case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE: + case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE - 1: val = s->regs[addr - 0x10]; break; default: @@ -247,7 +247,7 @@ static void cg3_reg_write(void *opaque, hwaddr addr, uint64_t val, qemu_irq_lower(s->irq); } break; - case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE: + case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE - 1: s->regs[addr - 0x10] = val; break; default: @@ -274,6 +274,21 @@ static const GraphicHwOps cg3_ops = { .gfx_update = cg3_update_display, }; +static void cg3_initfn(Object *obj) +{ + SysBusDevice *sbd = SYS_BUS_DEVICE(obj); + CG3State *s = CG3(obj); + + memory_region_init_ram(&s->rom, NULL, "cg3.prom", FCODE_MAX_ROM_SIZE, + &error_abort); + memory_region_set_readonly(&s->rom, true); + sysbus_init_mmio(sbd, &s->rom); + + memory_region_init_io(&s->reg, NULL, &cg3_reg_ops, s, "cg3.reg", + CG3_REG_SIZE); + sysbus_init_mmio(sbd, &s->reg); +} + static void cg3_realizefn(DeviceState *dev, Error **errp) { SysBusDevice *sbd = SYS_BUS_DEVICE(dev); @@ -282,11 +297,7 @@ static void cg3_realizefn(DeviceState *dev, Error **errp) char *fcode_filename; /* FCode ROM */ - memory_region_init_ram(&s->rom, NULL, "cg3.prom", FCODE_MAX_ROM_SIZE); vmstate_register_ram_global(&s->rom); - memory_region_set_readonly(&s->rom, true); - sysbus_init_mmio(sbd, &s->rom); - fcode_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, CG3_ROM_FILE); if (fcode_filename) { ret = load_image_targphys(fcode_filename, s->prom_addr, @@ -296,11 +307,8 @@ static void cg3_realizefn(DeviceState *dev, Error **errp) } } - memory_region_init_io(&s->reg, NULL, &cg3_reg_ops, s, "cg3.reg", - CG3_REG_SIZE); - sysbus_init_mmio(sbd, &s->reg); - - memory_region_init_ram(&s->vram_mem, NULL, "cg3.vram", s->vram_size); + memory_region_init_ram(&s->vram_mem, NULL, "cg3.vram", s->vram_size, + &error_abort); vmstate_register_ram_global(&s->vram_mem); sysbus_init_mmio(sbd, &s->vram_mem); @@ -324,7 +332,7 @@ static const VMStateDescription vmstate_cg3 = { .version_id = 1, .minimum_version_id = 1, .post_load = vmstate_cg3_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT16(height, CG3State), VMSTATE_UINT16(width, CG3State), VMSTATE_UINT16(depth, CG3State), @@ -374,6 +382,7 @@ static const TypeInfo cg3_info = { .name = TYPE_CG3, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(CG3State), + .instance_init = cg3_initfn, .class_init = cg3_class_init, }; diff --git a/hw/display/cirrus_vga.c b/hw/display/cirrus_vga.c index 0d3127da21..27252646bc 100644 --- a/hw/display/cirrus_vga.c +++ b/hw/display/cirrus_vga.c @@ -29,6 +29,7 @@ #include "hw/hw.h" #include "hw/pci/pci.h" #include "ui/console.h" +#include "ui/pixel_ops.h" #include "vga_int.h" #include "hw/loader.h" @@ -172,20 +173,6 @@ #define CIRRUS_PNPMMIO_SIZE 0x1000 -#define BLTUNSAFE(s) \ - ( \ - ( /* check dst is within bounds */ \ - (s)->cirrus_blt_height * ABS((s)->cirrus_blt_dstpitch) \ - + ((s)->cirrus_blt_dstaddr & (s)->cirrus_addr_mask) > \ - (s)->vga.vram_size \ - ) || \ - ( /* check src is within bounds */ \ - (s)->cirrus_blt_height * ABS((s)->cirrus_blt_srcpitch) \ - + ((s)->cirrus_blt_srcaddr & (s)->cirrus_addr_mask) > \ - (s)->vga.vram_size \ - ) \ - ) - struct CirrusVGAState; typedef void (*cirrus_bitblt_rop_t) (struct CirrusVGAState *s, uint8_t * dst, const uint8_t * src, @@ -278,6 +265,50 @@ static void cirrus_update_memory_access(CirrusVGAState *s); * ***************************************/ +static bool blit_region_is_unsafe(struct CirrusVGAState *s, + int32_t pitch, int32_t addr) +{ + if (pitch < 0) { + int64_t min = addr + + ((int64_t)s->cirrus_blt_height-1) * pitch; + int32_t max = addr + + s->cirrus_blt_width; + if (min < 0 || max >= s->vga.vram_size) { + return true; + } + } else { + int64_t max = addr + + ((int64_t)s->cirrus_blt_height-1) * pitch + + s->cirrus_blt_width; + if (max >= s->vga.vram_size) { + return true; + } + } + return false; +} + +static bool blit_is_unsafe(struct CirrusVGAState *s) +{ + /* should be the case, see cirrus_bitblt_start */ + assert(s->cirrus_blt_width > 0); + assert(s->cirrus_blt_height > 0); + + if (s->cirrus_blt_width > CIRRUS_BLTBUFSIZE) { + return true; + } + + if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch, + s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) { + return true; + } + if (blit_region_is_unsafe(s, s->cirrus_blt_srcpitch, + s->cirrus_blt_srcaddr & s->cirrus_addr_mask)) { + return true; + } + + return false; +} + static void cirrus_bitblt_rop_nop(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, @@ -635,7 +666,7 @@ static int cirrus_bitblt_common_patterncopy(CirrusVGAState * s, dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); - if (BLTUNSAFE(s)) + if (blit_is_unsafe(s)) return 0; (*s->cirrus_rop) (s, dst, src, @@ -653,8 +684,9 @@ static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop) { cirrus_fill_t rop_func; - if (BLTUNSAFE(s)) + if (blit_is_unsafe(s)) { return 0; + } rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1]; rop_func(s, s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask), s->cirrus_blt_dstpitch, @@ -751,7 +783,7 @@ static void cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h) static int cirrus_bitblt_videotovideo_copy(CirrusVGAState * s) { - if (BLTUNSAFE(s)) + if (blit_is_unsafe(s)) return 0; cirrus_do_copy(s, s->cirrus_blt_dstaddr - s->vga.start_addr, @@ -2059,7 +2091,7 @@ static void cirrus_vga_mem_write(void *opaque, } } else { #ifdef DEBUG_CIRRUS - printf("cirrus: mem_writeb " TARGET_FMT_plx " value %02x\n", addr, + printf("cirrus: mem_writeb " TARGET_FMT_plx " value 0x%02" PRIu64 "\n", addr, mem_value); #endif } @@ -2170,20 +2202,44 @@ static void cirrus_cursor_invalidate(VGACommonState *s1) } } -#define DEPTH 8 -#include "cirrus_vga_template.h" - -#define DEPTH 16 -#include "cirrus_vga_template.h" - -#define DEPTH 32 -#include "cirrus_vga_template.h" +static void vga_draw_cursor_line(uint8_t *d1, + const uint8_t *src1, + int poffset, int w, + unsigned int color0, + unsigned int color1, + unsigned int color_xor) +{ + const uint8_t *plane0, *plane1; + int x, b0, b1; + uint8_t *d; + + d = d1; + plane0 = src1; + plane1 = src1 + poffset; + for (x = 0; x < w; x++) { + b0 = (plane0[x >> 3] >> (7 - (x & 7))) & 1; + b1 = (plane1[x >> 3] >> (7 - (x & 7))) & 1; + switch (b0 | (b1 << 1)) { + case 0: + break; + case 1: + ((uint32_t *)d)[0] ^= color_xor; + break; + case 2: + ((uint32_t *)d)[0] = color0; + break; + case 3: + ((uint32_t *)d)[0] = color1; + break; + } + d += 4; + } +} static void cirrus_cursor_draw_line(VGACommonState *s1, uint8_t *d1, int scr_y) { CirrusVGAState *s = container_of(s1, CirrusVGAState, vga); - DisplaySurface *surface = qemu_console_surface(s->vga.con); - int w, h, bpp, x1, x2, poffset; + int w, h, x1, x2, poffset; unsigned int color0, color1; const uint8_t *palette, *src; uint32_t content; @@ -2212,6 +2268,8 @@ static void cirrus_cursor_draw_line(VGACommonState *s1, uint8_t *d1, int scr_y) } else { src += (s->vga.sr[0x13] & 0x3f) * 256; src += (scr_y - s->hw_cursor_y) * 4; + + poffset = 128; content = ((uint32_t *)src)[0] | ((uint32_t *)(src + 128))[0]; @@ -2229,30 +2287,14 @@ static void cirrus_cursor_draw_line(VGACommonState *s1, uint8_t *d1, int scr_y) x2 = s->vga.last_scr_width; w = x2 - x1; palette = s->cirrus_hidden_palette; - color0 = s->vga.rgb_to_pixel(c6_to_8(palette[0x0 * 3]), - c6_to_8(palette[0x0 * 3 + 1]), - c6_to_8(palette[0x0 * 3 + 2])); - color1 = s->vga.rgb_to_pixel(c6_to_8(palette[0xf * 3]), - c6_to_8(palette[0xf * 3 + 1]), - c6_to_8(palette[0xf * 3 + 2])); - bpp = surface_bytes_per_pixel(surface); - d1 += x1 * bpp; - switch (surface_bits_per_pixel(surface)) { - default: - break; - case 8: - vga_draw_cursor_line_8(d1, src, poffset, w, color0, color1, 0xff); - break; - case 15: - vga_draw_cursor_line_16(d1, src, poffset, w, color0, color1, 0x7fff); - break; - case 16: - vga_draw_cursor_line_16(d1, src, poffset, w, color0, color1, 0xffff); - break; - case 32: - vga_draw_cursor_line_32(d1, src, poffset, w, color0, color1, 0xffffff); - break; - } + color0 = rgb_to_pixel32(c6_to_8(palette[0x0 * 3]), + c6_to_8(palette[0x0 * 3 + 1]), + c6_to_8(palette[0x0 * 3 + 2])); + color1 = rgb_to_pixel32(c6_to_8(palette[0xf * 3]), + c6_to_8(palette[0xf * 3 + 1]), + c6_to_8(palette[0xf * 3 + 2])); + d1 += x1 * 4; + vga_draw_cursor_line(d1, src, poffset, w, color0, color1, 0xffffff); } /*************************************** @@ -2594,7 +2636,7 @@ static void cirrus_vga_ioport_write(void *opaque, hwaddr addr, uint64_t val, break; case 0x3c5: #ifdef DEBUG_VGA_REG - printf("vga: write SR%x = 0x%02x\n", s->sr_index, val); + printf("vga: write SR%x = 0x%02" PRIu64 "\n", s->sr_index, val); #endif cirrus_vga_write_sr(c, val); break; @@ -2619,7 +2661,7 @@ static void cirrus_vga_ioport_write(void *opaque, hwaddr addr, uint64_t val, break; case 0x3cf: #ifdef DEBUG_VGA_REG - printf("vga: write GR%x = 0x%02x\n", s->gr_index, val); + printf("vga: write GR%x = 0x%02" PRIu64 "\n", s->gr_index, val); #endif cirrus_vga_write_gr(c, s->gr_index, val); break; @@ -2630,7 +2672,7 @@ static void cirrus_vga_ioport_write(void *opaque, hwaddr addr, uint64_t val, case 0x3b5: case 0x3d5: #ifdef DEBUG_VGA_REG - printf("vga: write CR%x = 0x%02x\n", s->cr_index, val); + printf("vga: write CR%x = 0x%02"PRIu64"\n", s->cr_index, val); #endif cirrus_vga_write_cr(c, val); break; @@ -2702,9 +2744,8 @@ static const VMStateDescription vmstate_cirrus_vga = { .name = "cirrus_vga", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = cirrus_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(vga.latch, CirrusVGAState), VMSTATE_UINT8(vga.sr_index, CirrusVGAState), VMSTATE_BUFFER(vga.sr, CirrusVGAState), @@ -2742,8 +2783,7 @@ static const VMStateDescription vmstate_pci_cirrus_vga = { .name = "cirrus_vga", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCICirrusVGAState), VMSTATE_STRUCT(cirrus_vga, PCICirrusVGAState, 0, vmstate_cirrus_vga, CirrusVGAState), @@ -2913,7 +2953,15 @@ static void isa_cirrus_vga_realizefn(DeviceState *dev, Error **errp) ISACirrusVGAState *d = ISA_CIRRUS_VGA(dev); VGACommonState *s = &d->cirrus_vga.vga; - vga_common_init(s, OBJECT(dev)); + /* follow real hardware, cirrus card emulated has 4 MB video memory. + Also accept 8 MB/16 MB for backward compatibility. */ + if (s->vram_size_mb != 4 && s->vram_size_mb != 8 && + s->vram_size_mb != 16) { + error_setg(errp, "Invalid cirrus_vga ram size '%u'", + s->vram_size_mb); + return; + } + vga_common_init(s, OBJECT(dev), true); cirrus_init_common(&d->cirrus_vga, OBJECT(dev), CIRRUS_ID_CLGD5430, 0, isa_address_space(isadev), isa_address_space_io(isadev)); @@ -2959,8 +3007,16 @@ static int pci_cirrus_vga_initfn(PCIDevice *dev) PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev); int16_t device_id = pc->device_id; + /* follow real hardware, cirrus card emulated has 4 MB video memory. + Also accept 8 MB/16 MB for backward compatibility. */ + if (s->vga.vram_size_mb != 4 && s->vga.vram_size_mb != 8 && + s->vga.vram_size_mb != 16) { + error_report("Invalid cirrus_vga ram size '%u'", + s->vga.vram_size_mb); + return -1; + } /* setup VGA */ - vga_common_init(&s->vga, OBJECT(dev)); + vga_common_init(&s->vga, OBJECT(dev), true); cirrus_init_common(s, OBJECT(dev), device_id, 1, pci_address_space(dev), pci_address_space_io(dev)); s->vga.con = graphic_console_init(DEVICE(dev), 0, s->vga.hw_ops, &s->vga); diff --git a/hw/display/cirrus_vga_rop.h b/hw/display/cirrus_vga_rop.h index 9c7bb09286..0925a009fe 100644 --- a/hw/display/cirrus_vga_rop.h +++ b/hw/display/cirrus_vga_rop.h @@ -52,8 +52,7 @@ glue(cirrus_bitblt_rop_fwd_, ROP_NAME)(CirrusVGAState *s, dstpitch -= bltwidth; srcpitch -= bltwidth; - if (dstpitch < 0 || srcpitch < 0) { - /* is 0 valid? srcpitch == 0 could be useful */ + if (bltheight > 1 && (dstpitch < 0 || srcpitch < 0)) { return; } diff --git a/hw/display/cirrus_vga_template.h b/hw/display/cirrus_vga_template.h deleted file mode 100644 index 3b28280588..0000000000 --- a/hw/display/cirrus_vga_template.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * QEMU Cirrus VGA Emulator templates - * - * Copyright (c) 2003 Fabrice Bellard - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#if DEPTH == 8 -#define BPP 1 -#elif DEPTH == 15 || DEPTH == 16 -#define BPP 2 -#elif DEPTH == 32 -#define BPP 4 -#else -#error unsupported depth -#endif - -static void glue(vga_draw_cursor_line_, DEPTH)(uint8_t *d1, - const uint8_t *src1, - int poffset, int w, - unsigned int color0, - unsigned int color1, - unsigned int color_xor) -{ - const uint8_t *plane0, *plane1; - int x, b0, b1; - uint8_t *d; - - d = d1; - plane0 = src1; - plane1 = src1 + poffset; - for (x = 0; x < w; x++) { - b0 = (plane0[x >> 3] >> (7 - (x & 7))) & 1; - b1 = (plane1[x >> 3] >> (7 - (x & 7))) & 1; -#if DEPTH == 8 - switch (b0 | (b1 << 1)) { - case 0: - break; - case 1: - d[0] ^= color_xor; - break; - case 2: - d[0] = color0; - break; - case 3: - d[0] = color1; - break; - } -#elif DEPTH == 16 - switch (b0 | (b1 << 1)) { - case 0: - break; - case 1: - ((uint16_t *)d)[0] ^= color_xor; - break; - case 2: - ((uint16_t *)d)[0] = color0; - break; - case 3: - ((uint16_t *)d)[0] = color1; - break; - } -#elif DEPTH == 32 - switch (b0 | (b1 << 1)) { - case 0: - break; - case 1: - ((uint32_t *)d)[0] ^= color_xor; - break; - case 2: - ((uint32_t *)d)[0] = color0; - break; - case 3: - ((uint32_t *)d)[0] = color1; - break; - } -#else -#error unsupported depth -#endif - d += BPP; - } -} - -#undef DEPTH -#undef BPP diff --git a/hw/display/exynos4210_fimd.c b/hw/display/exynos4210_fimd.c index 9750330c25..45c62afac1 100644 --- a/hw/display/exynos4210_fimd.c +++ b/hw/display/exynos4210_fimd.c @@ -1845,7 +1845,7 @@ static const VMStateDescription exynos4210_fimd_window_vmstate = { .name = "exynos4210.fimd_window", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(wincon, Exynos4210fimdWindow), VMSTATE_UINT32_ARRAY(buf_start, Exynos4210fimdWindow, 3), VMSTATE_UINT32_ARRAY(buf_end, Exynos4210fimdWindow, 3), @@ -1875,7 +1875,7 @@ static const VMStateDescription exynos4210_fimd_vmstate = { .version_id = 1, .minimum_version_id = 1, .post_load = exynos4210_fimd_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(vidcon, Exynos4210fimdState, 4), VMSTATE_UINT32_ARRAY(vidtcon, Exynos4210fimdState, 4), VMSTATE_UINT32(shadowcon, Exynos4210fimdState), diff --git a/hw/display/g364fb.c b/hw/display/g364fb.c index 5c6a2d3605..46f7b41211 100644 --- a/hw/display/g364fb.c +++ b/hw/display/g364fb.c @@ -459,7 +459,6 @@ static const VMStateDescription vmstate_g364fb = { .name = "g364fb", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = g364fb_post_load, .fields = (VMStateField[]) { VMSTATE_VBUFFER_UINT32(vram, G364State, 1, NULL, 0, vram_size), diff --git a/hw/display/jazz_led.c b/hw/display/jazz_led.c index f9e7d7c981..12b1707cb2 100644 --- a/hw/display/jazz_led.c +++ b/hw/display/jazz_led.c @@ -173,6 +173,7 @@ static void jazz_led_update_display(void *opaque) case 16: color_segment = rgb_to_pixel16(0xaa, 0xaa, 0xaa); color_led = rgb_to_pixel16(0x00, 0xff, 0x00); + break; case 24: color_segment = rgb_to_pixel24(0xaa, 0xaa, 0xaa); color_led = rgb_to_pixel24(0x00, 0xff, 0x00); @@ -250,7 +251,6 @@ static const VMStateDescription vmstate_jazz_led = { .name = "jazz-led", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = jazz_led_post_load, .fields = (VMStateField[]) { VMSTATE_UINT8(segments, LedState), diff --git a/hw/display/milkymist-tmu2.c b/hw/display/milkymist-tmu2.c index b2a5fba0ff..3e1d0b9c20 100644 --- a/hw/display/milkymist-tmu2.c +++ b/hw/display/milkymist-tmu2.c @@ -463,8 +463,7 @@ static const VMStateDescription vmstate_milkymist_tmu2 = { .name = "milkymist-tmu2", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistTMU2State, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/display/milkymist-vgafb.c b/hw/display/milkymist-vgafb.c index 603537aabb..9b35e76ff1 100644 --- a/hw/display/milkymist-vgafb.c +++ b/hw/display/milkymist-vgafb.c @@ -305,9 +305,8 @@ static const VMStateDescription vmstate_milkymist_vgafb = { .name = "milkymist-vgafb", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = vgafb_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistVgafbState, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/display/omap_lcd_template.h b/hw/display/omap_lcd_template.h index 2fb96f83ae..e5dd447167 100644 --- a/hw/display/omap_lcd_template.h +++ b/hw/display/omap_lcd_template.h @@ -50,7 +50,7 @@ static void glue(draw_line2_, DEPTH)(void *opaque, uint8_t v, r, g, b; do { - v = ldub_raw((void *) s); + v = ldub_p((void *) s); r = (pal[v & 3] >> 4) & 0xf0; g = pal[v & 3] & 0xf0; b = (pal[v & 3] << 4) & 0xf0; @@ -89,7 +89,7 @@ static void glue(draw_line4_, DEPTH)(void *opaque, uint8_t v, r, g, b; do { - v = ldub_raw((void *) s); + v = ldub_p((void *) s); r = (pal[v & 0xf] >> 4) & 0xf0; g = pal[v & 0xf] & 0xf0; b = (pal[v & 0xf] << 4) & 0xf0; @@ -116,7 +116,7 @@ static void glue(draw_line8_, DEPTH)(void *opaque, uint8_t v, r, g, b; do { - v = ldub_raw((void *) s); + v = ldub_p((void *) s); r = (pal[v] >> 4) & 0xf0; g = pal[v] & 0xf0; b = (pal[v] << 4) & 0xf0; @@ -136,7 +136,7 @@ static void glue(draw_line12_, DEPTH)(void *opaque, uint8_t r, g, b; do { - v = lduw_raw((void *) s); + v = lduw_p((void *) s); r = (v >> 4) & 0xf0; g = v & 0xf0; b = (v << 4) & 0xf0; @@ -159,7 +159,7 @@ static void glue(draw_line16_, DEPTH)(void *opaque, uint8_t r, g, b; do { - v = lduw_raw((void *) s); + v = lduw_p((void *) s); r = (v >> 8) & 0xf8; g = (v >> 3) & 0xfc; b = (v << 3) & 0xf8; diff --git a/hw/display/pxa2xx_lcd.c b/hw/display/pxa2xx_lcd.c index 09cdf17ab9..ac3c018822 100644 --- a/hw/display/pxa2xx_lcd.c +++ b/hw/display/pxa2xx_lcd.c @@ -279,14 +279,6 @@ static inline void pxa2xx_dma_ber_set(PXA2xxLCDState *s, int ch) s->liidr = s->dma_ch[ch].id; } -/* Set Read Status interrupt high and poke associated registers */ -static inline void pxa2xx_dma_rdst_set(PXA2xxLCDState *s) -{ - s->status[0] |= LCSR0_RDST; - if (s->irqlevel && !(s->control[0] & LCCR0_RDSTM)) - s->status[0] |= LCSR0_SINT; -} - /* Load new Frame Descriptors from DMA */ static void pxa2xx_descriptor_load(PXA2xxLCDState *s) { @@ -620,24 +612,24 @@ static void pxa2xx_palette_parse(PXA2xxLCDState *s, int ch, int bpp) src += 2; break; case 1: /* 16 bpp plus transparency */ - alpha = *(uint16_t *) src & (1 << 24); + alpha = *(uint32_t *) src & (1 << 24); if (s->control[0] & LCCR0_CMS) - r = g = b = *(uint16_t *) src & 0xff; + r = g = b = *(uint32_t *) src & 0xff; else { - r = (*(uint16_t *) src & 0xf800) >> 8; - g = (*(uint16_t *) src & 0x07e0) >> 3; - b = (*(uint16_t *) src & 0x001f) << 3; + r = (*(uint32_t *) src & 0xf80000) >> 16; + g = (*(uint32_t *) src & 0x00fc00) >> 8; + b = (*(uint32_t *) src & 0x0000f8); } - src += 2; + src += 4; break; case 2: /* 18 bpp plus transparency */ alpha = *(uint32_t *) src & (1 << 24); if (s->control[0] & LCCR0_CMS) r = g = b = *(uint32_t *) src & 0xff; else { - r = (*(uint32_t *) src & 0xf80000) >> 16; + r = (*(uint32_t *) src & 0xfc0000) >> 16; g = (*(uint32_t *) src & 0x00fc00) >> 8; - b = (*(uint32_t *) src & 0x0000f8); + b = (*(uint32_t *) src & 0x0000fc); } src += 4; break; @@ -932,8 +924,7 @@ static const VMStateDescription vmstate_dma_channel = { .name = "dma_channel", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(branch, struct DMAChannel), VMSTATE_UINT8(up, struct DMAChannel), VMSTATE_BUFFER(pbuffer, struct DMAChannel), @@ -959,9 +950,8 @@ static const VMStateDescription vmstate_pxa2xx_lcdc = { .name = "pxa2xx_lcdc", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = pxa2xx_lcdc_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(irqlevel, PXA2xxLCDState), VMSTATE_INT32(transp, PXA2xxLCDState), VMSTATE_UINT32_ARRAY(control, PXA2xxLCDState, 6), diff --git a/hw/display/qxl-render.c b/hw/display/qxl-render.c index 84f1367716..e812ddd6e7 100644 --- a/hw/display/qxl-render.c +++ b/hw/display/qxl-render.c @@ -116,13 +116,14 @@ static void qxl_render_update_area_unlocked(PCIQXLDevice *qxl) qxl->guest_primary.bytes_pp, qxl->guest_primary.bits_pp); if (qxl->guest_primary.qxl_stride > 0) { + pixman_format_code_t format = + qemu_default_pixman_format(qxl->guest_primary.bits_pp, true); surface = qemu_create_displaysurface_from (qxl->guest_primary.surface.width, qxl->guest_primary.surface.height, - qxl->guest_primary.bits_pp, + format, qxl->guest_primary.abs_stride, - qxl->guest_primary.data, - false); + qxl->guest_primary.data); } else { surface = qemu_create_displaysurface (qxl->guest_primary.surface.width, @@ -138,6 +139,14 @@ static void qxl_render_update_area_unlocked(PCIQXLDevice *qxl) if (qemu_spice_rect_is_empty(qxl->dirty+i)) { break; } + if (qxl->dirty[i].left < 0 || + qxl->dirty[i].top < 0 || + qxl->dirty[i].left > qxl->dirty[i].right || + qxl->dirty[i].top > qxl->dirty[i].bottom || + qxl->dirty[i].right > qxl->guest_primary.surface.width || + qxl->dirty[i].bottom > qxl->guest_primary.surface.height) { + continue; + } qxl_blit(qxl, qxl->dirty+i); dpy_gfx_update(vga->con, qxl->dirty[i].left, qxl->dirty[i].top, diff --git a/hw/display/qxl.c b/hw/display/qxl.c index 47bbf1f1fe..b540dd656c 100644 --- a/hw/display/qxl.c +++ b/hw/display/qxl.c @@ -132,6 +132,8 @@ static void qxl_reset_memslots(PCIQXLDevice *d); static void qxl_reset_surfaces(PCIQXLDevice *d); static void qxl_ring_set_dirty(PCIQXLDevice *qxl); +static void qxl_hw_update(void *opaque); + void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...) { trace_qxl_set_guest_bug(qxl->id); @@ -710,7 +712,11 @@ static void interface_release_resource(QXLInstance *sin, if (ext.group_id == MEMSLOT_GROUP_HOST) { /* host group -> vga mode update request */ - qemu_spice_destroy_update(&qxl->ssd, (void *)(intptr_t)ext.info->id); + QXLCommandExt *cmdext = (void *)(intptr_t)(ext.info->id); + SimpleSpiceUpdate *update; + g_assert(cmdext->cmd.type == QXL_CMD_DRAW); + update = container_of(cmdext, SimpleSpiceUpdate, ext); + qemu_spice_destroy_update(&qxl->ssd, update); return; } @@ -1072,6 +1078,10 @@ static const QXLInterface qxl_interface = { .client_monitors_config = interface_client_monitors_config, }; +static const GraphicHwOps qxl_ops = { + .gfx_update = qxl_hw_update, +}; + static void qxl_enter_vga_mode(PCIQXLDevice *d) { if (d->mode == QXL_MODE_VGA) { @@ -1081,6 +1091,7 @@ static void qxl_enter_vga_mode(PCIQXLDevice *d) #if SPICE_SERVER_VERSION >= 0x000c03 /* release 0.12.3 */ spice_qxl_driver_unload(&d->ssd.qxl); #endif + graphic_console_set_hwops(d->ssd.dcl.con, d->vga.hw_ops, &d->vga); qemu_spice_create_host_primary(&d->ssd); d->mode = QXL_MODE_VGA; vga_dirty_log_start(&d->vga); @@ -1093,6 +1104,7 @@ static void qxl_exit_vga_mode(PCIQXLDevice *d) return; } trace_qxl_exit_vga_mode(d->id); + graphic_console_set_hwops(d->ssd.dcl.con, &qxl_ops, d); vga_dirty_log_stop(&d->vga); qxl_destroy_primary(d, QXL_SYNC); } @@ -1579,6 +1591,11 @@ async_common: qxl_set_guest_bug(d, "QXL_IO_UPDATE_AREA: invalid area (%ux%u)x(%ux%u)\n", update.left, update.top, update.right, update.bottom); + if (update.left == update.right || update.top == update.bottom) { + /* old drivers may provide empty area, keep going */ + qxl_clear_guest_bug(d); + goto cancel_async; + } break; } if (async == QXL_ASYNC) { @@ -1752,41 +1769,8 @@ static void qxl_send_events(PCIQXLDevice *d, uint32_t events) static void qxl_hw_update(void *opaque) { PCIQXLDevice *qxl = opaque; - VGACommonState *vga = &qxl->vga; - - switch (qxl->mode) { - case QXL_MODE_VGA: - vga->hw_ops->gfx_update(vga); - break; - case QXL_MODE_COMPAT: - case QXL_MODE_NATIVE: - qxl_render_update(qxl); - break; - default: - break; - } -} - -static void qxl_hw_invalidate(void *opaque) -{ - PCIQXLDevice *qxl = opaque; - VGACommonState *vga = &qxl->vga; - if (qxl->mode == QXL_MODE_VGA) { - vga->hw_ops->invalidate(vga); - return; - } -} - -static void qxl_hw_text_update(void *opaque, console_ch_t *chardata) -{ - PCIQXLDevice *qxl = opaque; - VGACommonState *vga = &qxl->vga; - - if (qxl->mode == QXL_MODE_VGA) { - vga->hw_ops->text_update(vga, chardata); - return; - } + qxl_render_update(qxl); } static void qxl_dirty_surfaces(PCIQXLDevice *qxl) @@ -1975,14 +1959,14 @@ static int qxl_init_common(PCIQXLDevice *qxl) qxl->rom_size = qxl_rom_size(); memory_region_init_ram(&qxl->rom_bar, OBJECT(qxl), "qxl.vrom", - qxl->rom_size); + qxl->rom_size, &error_abort); vmstate_register_ram(&qxl->rom_bar, &qxl->pci.qdev); init_qxl_rom(qxl); init_qxl_ram(qxl); qxl->guest_surfaces.cmds = g_new0(QXLPHYSICAL, qxl->ssd.num_surfaces); memory_region_init_ram(&qxl->vram_bar, OBJECT(qxl), "qxl.vram", - qxl->vram_size); + qxl->vram_size, &error_abort); vmstate_register_ram(&qxl->vram_bar, &qxl->pci.qdev); memory_region_init_alias(&qxl->vram32_bar, OBJECT(qxl), "qxl.vram32", &qxl->vram_bar, 0, qxl->vram32_size); @@ -2045,29 +2029,23 @@ static int qxl_init_common(PCIQXLDevice *qxl) return 0; } -static const GraphicHwOps qxl_ops = { - .invalidate = qxl_hw_invalidate, - .gfx_update = qxl_hw_update, - .text_update = qxl_hw_text_update, -}; - static int qxl_init_primary(PCIDevice *dev) { PCIQXLDevice *qxl = DO_UPCAST(PCIQXLDevice, pci, dev); VGACommonState *vga = &qxl->vga; - PortioList *qxl_vga_port_list = g_new(PortioList, 1); int rc; qxl->id = 0; qxl_init_ramsize(qxl); + vga->vbe_size = qxl->vgamem_size; vga->vram_size_mb = qxl->vga.vram_size >> 20; - vga_common_init(vga, OBJECT(dev)); + vga_common_init(vga, OBJECT(dev), true); vga_init(vga, OBJECT(dev), pci_address_space(dev), pci_address_space_io(dev), false); - portio_list_init(qxl_vga_port_list, OBJECT(dev), qxl_vga_portio_list, + portio_list_init(&qxl->vga_port_list, OBJECT(dev), qxl_vga_portio_list, vga, "vga"); - portio_list_set_flush_coalesced(qxl_vga_port_list); - portio_list_add(qxl_vga_port_list, pci_address_space_io(dev), 0x3b0); + portio_list_set_flush_coalesced(&qxl->vga_port_list); + portio_list_add(&qxl->vga_port_list, pci_address_space_io(dev), 0x3b0); vga->con = graphic_console_init(DEVICE(dev), 0, &qxl_ops, qxl); qemu_spice_display_init_common(&qxl->ssd); @@ -2091,7 +2069,7 @@ static int qxl_init_secondary(PCIDevice *dev) qxl->id = device_id++; qxl_init_ramsize(qxl); memory_region_init_ram(&qxl->vga.vram, OBJECT(dev), "qxl.vgavram", - qxl->vga.vram_size); + qxl->vga.vram_size, &error_abort); vmstate_register_ram(&qxl->vga.vram, &qxl->pci.qdev); qxl->vga.vram_ptr = memory_region_get_ram_ptr(&qxl->vga.vram); qxl->vga.con = graphic_console_init(DEVICE(dev), 0, &qxl_ops, qxl); diff --git a/hw/display/qxl.h b/hw/display/qxl.h index c5de3d7075..412e346b68 100644 --- a/hw/display/qxl.h +++ b/hw/display/qxl.h @@ -32,6 +32,7 @@ enum qxl_mode { typedef struct PCIQXLDevice { PCIDevice pci; + PortioList vga_port_list; SimpleSpiceDisplay ssd; int id; uint32_t debug; diff --git a/hw/display/sm501.c b/hw/display/sm501.c index eedf2d48e0..c72154b6f1 100644 --- a/hw/display/sm501.c +++ b/hw/display/sm501.c @@ -1410,7 +1410,7 @@ void sm501_init(MemoryRegion *address_space_mem, uint32_t base, /* allocate local memory */ memory_region_init_ram(&s->local_mem_region, NULL, "sm501.local", - local_mem_bytes); + local_mem_bytes, &error_abort); vmstate_register_ram_global(&s->local_mem_region); s->local_mem = memory_region_get_ram_ptr(&s->local_mem_region); memory_region_add_subregion(address_space_mem, base, &s->local_mem_region); diff --git a/hw/display/sm501_template.h b/hw/display/sm501_template.h index d4cea9e150..f33e499be4 100644 --- a/hw/display/sm501_template.h +++ b/hw/display/sm501_template.h @@ -47,7 +47,7 @@ static void glue(draw_line8_, PIXEL_NAME)( { uint8_t v, r, g, b; do { - v = ldub_raw(s); + v = ldub_p(s); r = (pal[v] >> 16) & 0xff; g = (pal[v] >> 8) & 0xff; b = (pal[v] >> 0) & 0xff; @@ -64,7 +64,7 @@ static void glue(draw_line16_, PIXEL_NAME)( uint8_t r, g, b; do { - rgb565 = lduw_raw(s); + rgb565 = lduw_p(s); r = ((rgb565 >> 11) & 0x1f) << 3; g = ((rgb565 >> 5) & 0x3f) << 2; b = ((rgb565 >> 0) & 0x1f) << 3; @@ -80,7 +80,7 @@ static void glue(draw_line32_, PIXEL_NAME)( uint8_t r, g, b; do { - ldub_raw(s); + ldub_p(s); #if defined(TARGET_WORDS_BIGENDIAN) r = s[1]; g = s[2]; diff --git a/hw/display/ssd0303.c b/hw/display/ssd0303.c index c2eea04934..f6804fb51b 100644 --- a/hw/display/ssd0303.c +++ b/hw/display/ssd0303.c @@ -272,8 +272,7 @@ static const VMStateDescription vmstate_ssd0303 = { .name = "ssd0303_oled", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(row, ssd0303_state), VMSTATE_INT32(col, ssd0303_state), VMSTATE_INT32(start_line, ssd0303_state), diff --git a/hw/display/ssd0323.c b/hw/display/ssd0323.c index 971152edbd..97270077e2 100644 --- a/hw/display/ssd0323.c +++ b/hw/display/ssd0323.c @@ -312,18 +312,42 @@ static int ssd0323_load(QEMUFile *f, void *opaque, int version_id) return -EINVAL; s->cmd_len = qemu_get_be32(f); + if (s->cmd_len < 0 || s->cmd_len > ARRAY_SIZE(s->cmd_data)) { + return -EINVAL; + } s->cmd = qemu_get_be32(f); for (i = 0; i < 8; i++) s->cmd_data[i] = qemu_get_be32(f); s->row = qemu_get_be32(f); + if (s->row < 0 || s->row >= 80) { + return -EINVAL; + } s->row_start = qemu_get_be32(f); + if (s->row_start < 0 || s->row_start >= 80) { + return -EINVAL; + } s->row_end = qemu_get_be32(f); + if (s->row_end < 0 || s->row_end >= 80) { + return -EINVAL; + } s->col = qemu_get_be32(f); + if (s->col < 0 || s->col >= 64) { + return -EINVAL; + } s->col_start = qemu_get_be32(f); + if (s->col_start < 0 || s->col_start >= 64) { + return -EINVAL; + } s->col_end = qemu_get_be32(f); + if (s->col_end < 0 || s->col_end >= 64) { + return -EINVAL; + } s->redraw = qemu_get_be32(f); s->remap = qemu_get_be32(f); s->mode = qemu_get_be32(f); + if (s->mode != SSD0323_CMD && s->mode != SSD0323_DATA) { + return -EINVAL; + } qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer)); ss->cs = qemu_get_be32(f); diff --git a/hw/display/tc6393xb.c b/hw/display/tc6393xb.c index f4011d2db0..4306adc959 100644 --- a/hw/display/tc6393xb.c +++ b/hw/display/tc6393xb.c @@ -15,6 +15,7 @@ #include "hw/block/flash.h" #include "ui/console.h" #include "ui/pixel_ops.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #define IRQ_TC6393_NAND 0 @@ -576,12 +577,14 @@ TC6393xbState *tc6393xb_init(MemoryRegion *sysmem, uint32_t base, qemu_irq irq) s->sub_irqs = qemu_allocate_irqs(tc6393xb_sub_irq, s, TC6393XB_NR_IRQS); nand = drive_get(IF_MTD, 0, 0); - s->flash = nand_init(nand ? nand->bdrv : NULL, NAND_MFR_TOSHIBA, 0x76); + s->flash = nand_init(nand ? blk_by_legacy_dinfo(nand) : NULL, + NAND_MFR_TOSHIBA, 0x76); memory_region_init_io(&s->iomem, NULL, &tc6393xb_ops, s, "tc6393xb", 0x10000); memory_region_add_subregion(sysmem, base, &s->iomem); - memory_region_init_ram(&s->vram, NULL, "tc6393xb.vram", 0x100000); + memory_region_init_ram(&s->vram, NULL, "tc6393xb.vram", 0x100000, + &error_abort); vmstate_register_ram_global(&s->vram); s->vram_ptr = memory_region_get_ram_ptr(&s->vram); memory_region_add_subregion(sysmem, base + 0x100000, &s->vram); diff --git a/hw/display/tcx.c b/hw/display/tcx.c index 2b37ffac4c..a9f9f66d15 100644 --- a/hw/display/tcx.c +++ b/hw/display/tcx.c @@ -33,10 +33,20 @@ #define MAXX 1024 #define MAXY 768 -#define TCX_DAC_NREGS 16 -#define TCX_THC_NREGS_8 0x081c -#define TCX_THC_NREGS_24 0x1000 +#define TCX_DAC_NREGS 16 +#define TCX_THC_NREGS 0x1000 +#define TCX_DHC_NREGS 0x4000 #define TCX_TEC_NREGS 0x1000 +#define TCX_ALT_NREGS 0x8000 +#define TCX_STIP_NREGS 0x800000 +#define TCX_BLIT_NREGS 0x800000 +#define TCX_RSTIP_NREGS 0x800000 +#define TCX_RBLIT_NREGS 0x800000 + +#define TCX_THC_MISC 0x818 +#define TCX_THC_CURSXY 0x8fc +#define TCX_THC_CURSMASK 0x900 +#define TCX_THC_CURSBITS 0x980 #define TYPE_TCX "SUNW,tcx" #define TCX(obj) OBJECT_CHECK(TCXState, (obj), TYPE_TCX) @@ -45,6 +55,7 @@ typedef struct TCXState { SysBusDevice parent_obj; QemuConsole *con; + qemu_irq irq; uint8_t *vram; uint32_t *vram24, *cplane; hwaddr prom_addr; @@ -52,17 +63,30 @@ typedef struct TCXState { MemoryRegion vram_mem; MemoryRegion vram_8bit; MemoryRegion vram_24bit; + MemoryRegion stip; + MemoryRegion blit; MemoryRegion vram_cplane; - MemoryRegion dac; + MemoryRegion rstip; + MemoryRegion rblit; MemoryRegion tec; + MemoryRegion dac; + MemoryRegion thc; + MemoryRegion dhc; + MemoryRegion alt; MemoryRegion thc24; - MemoryRegion thc8; + ram_addr_t vram24_offset, cplane_offset; + uint32_t tmpblit; uint32_t vram_size; - uint32_t palette[256]; - uint8_t r[256], g[256], b[256]; + uint32_t palette[260]; + uint8_t r[260], g[260], b[260]; uint16_t width, height, depth; uint8_t dac_index, dac_state; + uint32_t thcmisc; + uint32_t cursmask[32]; + uint32_t cursbits[32]; + uint16_t cursx; + uint16_t cursy; } TCXState; static void tcx_set_dirty(TCXState *s) @@ -70,10 +94,36 @@ static void tcx_set_dirty(TCXState *s) memory_region_set_dirty(&s->vram_mem, 0, MAXX * MAXY); } -static void tcx24_set_dirty(TCXState *s) +static inline int tcx24_check_dirty(TCXState *s, ram_addr_t page, + ram_addr_t page24, ram_addr_t cpage) +{ + int ret; + + ret = memory_region_get_dirty(&s->vram_mem, page, TARGET_PAGE_SIZE, + DIRTY_MEMORY_VGA); + ret |= memory_region_get_dirty(&s->vram_mem, page24, TARGET_PAGE_SIZE * 4, + DIRTY_MEMORY_VGA); + ret |= memory_region_get_dirty(&s->vram_mem, cpage, TARGET_PAGE_SIZE * 4, + DIRTY_MEMORY_VGA); + return ret; +} + +static inline void tcx24_reset_dirty(TCXState *ts, ram_addr_t page_min, + ram_addr_t page_max, ram_addr_t page24, + ram_addr_t cpage) { - memory_region_set_dirty(&s->vram_mem, s->vram24_offset, MAXX * MAXY * 4); - memory_region_set_dirty(&s->vram_mem, s->cplane_offset, MAXX * MAXY * 4); + memory_region_reset_dirty(&ts->vram_mem, + page_min, + (page_max - page_min) + TARGET_PAGE_SIZE, + DIRTY_MEMORY_VGA); + memory_region_reset_dirty(&ts->vram_mem, + page24 + page_min * 4, + (page_max - page_min) * 4 + TARGET_PAGE_SIZE, + DIRTY_MEMORY_VGA); + memory_region_reset_dirty(&ts->vram_mem, + cpage + page_min * 4, + (page_max - page_min) * 4 + TARGET_PAGE_SIZE, + DIRTY_MEMORY_VGA); } static void update_palette_entries(TCXState *s, int start, int end) @@ -102,11 +152,7 @@ static void update_palette_entries(TCXState *s, int start, int end) break; } } - if (s->depth == 24) { - tcx24_set_dirty(s); - } else { - tcx_set_dirty(s); - } + tcx_set_dirty(s); } static void tcx_draw_line32(TCXState *s1, uint8_t *d, @@ -116,7 +162,7 @@ static void tcx_draw_line32(TCXState *s1, uint8_t *d, uint8_t val; uint32_t *p = (uint32_t *)d; - for(x = 0; x < width; x++) { + for (x = 0; x < width; x++) { val = *s++; *p++ = s1->palette[val]; } @@ -129,7 +175,7 @@ static void tcx_draw_line16(TCXState *s1, uint8_t *d, uint8_t val; uint16_t *p = (uint16_t *)d; - for(x = 0; x < width; x++) { + for (x = 0; x < width; x++) { val = *s++; *p++ = s1->palette[val]; } @@ -147,6 +193,83 @@ static void tcx_draw_line8(TCXState *s1, uint8_t *d, } } +static void tcx_draw_cursor32(TCXState *s1, uint8_t *d, + int y, int width) +{ + int x, len; + uint32_t mask, bits; + uint32_t *p = (uint32_t *)d; + + y = y - s1->cursy; + mask = s1->cursmask[y]; + bits = s1->cursbits[y]; + len = MIN(width - s1->cursx, 32); + p = &p[s1->cursx]; + for (x = 0; x < len; x++) { + if (mask & 0x80000000) { + if (bits & 0x80000000) { + *p = s1->palette[259]; + } else { + *p = s1->palette[258]; + } + } + p++; + mask <<= 1; + bits <<= 1; + } +} + +static void tcx_draw_cursor16(TCXState *s1, uint8_t *d, + int y, int width) +{ + int x, len; + uint32_t mask, bits; + uint16_t *p = (uint16_t *)d; + + y = y - s1->cursy; + mask = s1->cursmask[y]; + bits = s1->cursbits[y]; + len = MIN(width - s1->cursx, 32); + p = &p[s1->cursx]; + for (x = 0; x < len; x++) { + if (mask & 0x80000000) { + if (bits & 0x80000000) { + *p = s1->palette[259]; + } else { + *p = s1->palette[258]; + } + } + p++; + mask <<= 1; + bits <<= 1; + } +} + +static void tcx_draw_cursor8(TCXState *s1, uint8_t *d, + int y, int width) +{ + int x, len; + uint32_t mask, bits; + + y = y - s1->cursy; + mask = s1->cursmask[y]; + bits = s1->cursbits[y]; + len = MIN(width - s1->cursx, 32); + d = &d[s1->cursx]; + for (x = 0; x < len; x++) { + if (mask & 0x80000000) { + if (bits & 0x80000000) { + *d = s1->palette[259]; + } else { + *d = s1->palette[258]; + } + } + d++; + mask <<= 1; + bits <<= 1; + } +} + /* XXX Could be much more optimal: * detect if line/page/whole screen is in 24 bit mode @@ -162,11 +285,10 @@ static inline void tcx24_draw_line32(TCXState *s1, uint8_t *d, uint8_t val, *p8; uint32_t *p = (uint32_t *)d; uint32_t dval; - bgr = is_surface_bgr(surface); for(x = 0; x < width; x++, s++, s24++) { - if ((be32_to_cpu(*cplane++) & 0xff000000) == 0x03000000) { - // 24-bit direct, BGR order + if (be32_to_cpu(*cplane) & 0x03000000) { + /* 24-bit direct, BGR order */ p8 = (uint8_t *)s24; p8++; b = *p8++; @@ -177,47 +299,18 @@ static inline void tcx24_draw_line32(TCXState *s1, uint8_t *d, else dval = rgb_to_pixel32(r, g, b); } else { + /* 8-bit pseudocolor */ val = *s; dval = s1->palette[val]; } *p++ = dval; + cplane++; } } -static inline int check_dirty(TCXState *s, ram_addr_t page, ram_addr_t page24, - ram_addr_t cpage) -{ - int ret; - - ret = memory_region_get_dirty(&s->vram_mem, page, TARGET_PAGE_SIZE, - DIRTY_MEMORY_VGA); - ret |= memory_region_get_dirty(&s->vram_mem, page24, TARGET_PAGE_SIZE * 4, - DIRTY_MEMORY_VGA); - ret |= memory_region_get_dirty(&s->vram_mem, cpage, TARGET_PAGE_SIZE * 4, - DIRTY_MEMORY_VGA); - return ret; -} - -static inline void reset_dirty(TCXState *ts, ram_addr_t page_min, - ram_addr_t page_max, ram_addr_t page24, - ram_addr_t cpage) -{ - memory_region_reset_dirty(&ts->vram_mem, - page_min, - (page_max - page_min) + TARGET_PAGE_SIZE, - DIRTY_MEMORY_VGA); - memory_region_reset_dirty(&ts->vram_mem, - page24 + page_min * 4, - (page_max - page_min) * 4 + TARGET_PAGE_SIZE, - DIRTY_MEMORY_VGA); - memory_region_reset_dirty(&ts->vram_mem, - cpage + page_min * 4, - (page_max - page_min) * 4 + TARGET_PAGE_SIZE, - DIRTY_MEMORY_VGA); -} - /* Fixed line length 1024 allows us to do nice tricks not possible on VGA... */ + static void tcx_update_display(void *opaque) { TCXState *ts = opaque; @@ -226,6 +319,7 @@ static void tcx_update_display(void *opaque) int y, y_start, dd, ds; uint8_t *d, *s; void (*f)(TCXState *s1, uint8_t *dst, const uint8_t *src, int width); + void (*fc)(TCXState *s1, uint8_t *dst, int y, int width); if (surface_bits_per_pixel(surface) == 0) { return; @@ -243,20 +337,23 @@ static void tcx_update_display(void *opaque) switch (surface_bits_per_pixel(surface)) { case 32: f = tcx_draw_line32; + fc = tcx_draw_cursor32; break; case 15: case 16: f = tcx_draw_line16; + fc = tcx_draw_cursor16; break; default: case 8: f = tcx_draw_line8; + fc = tcx_draw_cursor8; break; case 0: return; } - for(y = 0; y < ts->height; y += 4, page += TARGET_PAGE_SIZE) { + for (y = 0; y < ts->height; page += TARGET_PAGE_SIZE) { if (memory_region_get_dirty(&ts->vram_mem, page, TARGET_PAGE_SIZE, DIRTY_MEMORY_VGA)) { if (y_start < 0) @@ -265,18 +362,38 @@ static void tcx_update_display(void *opaque) page_min = page; if (page > page_max) page_max = page; + f(ts, d, s, ts->width); + if (y >= ts->cursy && y < ts->cursy + 32 && ts->cursx < ts->width) { + fc(ts, d, y, ts->width); + } d += dd; s += ds; + y++; + f(ts, d, s, ts->width); + if (y >= ts->cursy && y < ts->cursy + 32 && ts->cursx < ts->width) { + fc(ts, d, y, ts->width); + } d += dd; s += ds; + y++; + f(ts, d, s, ts->width); + if (y >= ts->cursy && y < ts->cursy + 32 && ts->cursx < ts->width) { + fc(ts, d, y, ts->width); + } d += dd; s += ds; + y++; + f(ts, d, s, ts->width); + if (y >= ts->cursy && y < ts->cursy + 32 && ts->cursx < ts->width) { + fc(ts, d, y, ts->width); + } d += dd; s += ds; + y++; } else { if (y_start >= 0) { /* flush to display */ @@ -286,6 +403,7 @@ static void tcx_update_display(void *opaque) } d += dd * 4; s += ds * 4; + y += 4; } } if (y_start >= 0) { @@ -328,9 +446,9 @@ static void tcx24_update_display(void *opaque) dd = surface_stride(surface); ds = 1024; - for(y = 0; y < ts->height; y += 4, page += TARGET_PAGE_SIZE, + for (y = 0; y < ts->height; page += TARGET_PAGE_SIZE, page24 += TARGET_PAGE_SIZE, cpage += TARGET_PAGE_SIZE) { - if (check_dirty(ts, page, page24, cpage)) { + if (tcx24_check_dirty(ts, page, page24, cpage)) { if (y_start < 0) y_start = y; if (page < page_min) @@ -338,25 +456,41 @@ static void tcx24_update_display(void *opaque) if (page > page_max) page_max = page; tcx24_draw_line32(ts, d, s, ts->width, cptr, s24); + if (y >= ts->cursy && y < ts->cursy+32 && ts->cursx < ts->width) { + tcx_draw_cursor32(ts, d, y, ts->width); + } d += dd; s += ds; cptr += ds; s24 += ds; + y++; tcx24_draw_line32(ts, d, s, ts->width, cptr, s24); + if (y >= ts->cursy && y < ts->cursy+32 && ts->cursx < ts->width) { + tcx_draw_cursor32(ts, d, y, ts->width); + } d += dd; s += ds; cptr += ds; s24 += ds; + y++; tcx24_draw_line32(ts, d, s, ts->width, cptr, s24); + if (y >= ts->cursy && y < ts->cursy+32 && ts->cursx < ts->width) { + tcx_draw_cursor32(ts, d, y, ts->width); + } d += dd; s += ds; cptr += ds; s24 += ds; + y++; tcx24_draw_line32(ts, d, s, ts->width, cptr, s24); + if (y >= ts->cursy && y < ts->cursy+32 && ts->cursx < ts->width) { + tcx_draw_cursor32(ts, d, y, ts->width); + } d += dd; s += ds; cptr += ds; s24 += ds; + y++; } else { if (y_start >= 0) { /* flush to display */ @@ -368,6 +502,7 @@ static void tcx24_update_display(void *opaque) s += ds * 4; cptr += ds * 4; s24 += ds * 4; + y += 4; } } if (y_start >= 0) { @@ -377,7 +512,7 @@ static void tcx24_update_display(void *opaque) } /* reset modified pages */ if (page_max >= page_min) { - reset_dirty(ts, page_min, page_max, page24, cpage); + tcx24_reset_dirty(ts, page_min, page_max, page24, cpage); } } @@ -394,7 +529,6 @@ static void tcx24_invalidate_display(void *opaque) TCXState *s = opaque; tcx_set_dirty(s); - tcx24_set_dirty(s); qemu_console_resize(s->con, s->width, s->height); } @@ -403,12 +537,7 @@ static int vmstate_tcx_post_load(void *opaque, int version_id) TCXState *s = opaque; update_palette_entries(s, 0, 256); - if (s->depth == 24) { - tcx24_set_dirty(s); - } else { - tcx_set_dirty(s); - } - + tcx_set_dirty(s); return 0; } @@ -416,9 +545,8 @@ static const VMStateDescription vmstate_tcx = { .name ="tcx", .version_id = 4, .minimum_version_id = 4, - .minimum_version_id_old = 4, .post_load = vmstate_tcx_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(height, TCXState), VMSTATE_UINT16(width, TCXState), VMSTATE_UINT16(depth, TCXState), @@ -436,56 +564,87 @@ static void tcx_reset(DeviceState *d) TCXState *s = TCX(d); /* Initialize palette */ - memset(s->r, 0, 256); - memset(s->g, 0, 256); - memset(s->b, 0, 256); + memset(s->r, 0, 260); + memset(s->g, 0, 260); + memset(s->b, 0, 260); s->r[255] = s->g[255] = s->b[255] = 255; - update_palette_entries(s, 0, 256); + s->r[256] = s->g[256] = s->b[256] = 255; + s->r[258] = s->g[258] = s->b[258] = 255; + update_palette_entries(s, 0, 260); memset(s->vram, 0, MAXX*MAXY); memory_region_reset_dirty(&s->vram_mem, 0, MAXX * MAXY * (1 + 4 + 4), DIRTY_MEMORY_VGA); s->dac_index = 0; s->dac_state = 0; + s->cursx = 0xf000; /* Put cursor off screen */ + s->cursy = 0xf000; } static uint64_t tcx_dac_readl(void *opaque, hwaddr addr, unsigned size) { - return 0; + TCXState *s = opaque; + uint32_t val = 0; + + switch (s->dac_state) { + case 0: + val = s->r[s->dac_index] << 24; + s->dac_state++; + break; + case 1: + val = s->g[s->dac_index] << 24; + s->dac_state++; + break; + case 2: + val = s->b[s->dac_index] << 24; + s->dac_index = (s->dac_index + 1) & 0xff; /* Index autoincrement */ + default: + s->dac_state = 0; + break; + } + + return val; } static void tcx_dac_writel(void *opaque, hwaddr addr, uint64_t val, unsigned size) { TCXState *s = opaque; + unsigned index; switch (addr) { - case 0: + case 0: /* Address */ s->dac_index = val >> 24; s->dac_state = 0; break; - case 4: + case 4: /* Pixel colours */ + case 12: /* Overlay (cursor) colours */ + if (addr & 8) { + index = (s->dac_index & 3) + 256; + } else { + index = s->dac_index; + } switch (s->dac_state) { case 0: - s->r[s->dac_index] = val >> 24; - update_palette_entries(s, s->dac_index, s->dac_index + 1); + s->r[index] = val >> 24; + update_palette_entries(s, index, index + 1); s->dac_state++; break; case 1: - s->g[s->dac_index] = val >> 24; - update_palette_entries(s, s->dac_index, s->dac_index + 1); + s->g[index] = val >> 24; + update_palette_entries(s, index, index + 1); s->dac_state++; break; case 2: - s->b[s->dac_index] = val >> 24; - update_palette_entries(s, s->dac_index, s->dac_index + 1); - s->dac_index = (s->dac_index + 1) & 255; // Index autoincrement + s->b[index] = val >> 24; + update_palette_entries(s, index, index + 1); + s->dac_index = (s->dac_index + 1) & 0xff; /* Index autoincrement */ default: s->dac_state = 0; break; } break; - default: + default: /* Control registers */ break; } } @@ -500,20 +659,266 @@ static const MemoryRegionOps tcx_dac_ops = { }, }; -static uint64_t dummy_readl(void *opaque, hwaddr addr, +static uint64_t tcx_stip_readl(void *opaque, hwaddr addr, + unsigned size) +{ + return 0; +} + +static void tcx_stip_writel(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + TCXState *s = opaque; + int i; + uint32_t col; + + if (!(addr & 4)) { + s->tmpblit = val; + } else { + addr = (addr >> 3) & 0xfffff; + col = cpu_to_be32(s->tmpblit); + if (s->depth == 24) { + for (i = 0; i < 32; i++) { + if (val & 0x80000000) { + s->vram[addr + i] = s->tmpblit; + s->vram24[addr + i] = col; + } + val <<= 1; + } + } else { + for (i = 0; i < 32; i++) { + if (val & 0x80000000) { + s->vram[addr + i] = s->tmpblit; + } + val <<= 1; + } + } + memory_region_set_dirty(&s->vram_mem, addr, 32); + } +} + +static void tcx_rstip_writel(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + TCXState *s = opaque; + int i; + uint32_t col; + + if (!(addr & 4)) { + s->tmpblit = val; + } else { + addr = (addr >> 3) & 0xfffff; + col = cpu_to_be32(s->tmpblit); + if (s->depth == 24) { + for (i = 0; i < 32; i++) { + if (val & 0x80000000) { + s->vram[addr + i] = s->tmpblit; + s->vram24[addr + i] = col; + s->cplane[addr + i] = col; + } + val <<= 1; + } + } else { + for (i = 0; i < 32; i++) { + if (val & 0x80000000) { + s->vram[addr + i] = s->tmpblit; + } + val <<= 1; + } + } + memory_region_set_dirty(&s->vram_mem, addr, 32); + } +} + +static const MemoryRegionOps tcx_stip_ops = { + .read = tcx_stip_readl, + .write = tcx_stip_writel, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static const MemoryRegionOps tcx_rstip_ops = { + .read = tcx_stip_readl, + .write = tcx_rstip_writel, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static uint64_t tcx_blit_readl(void *opaque, hwaddr addr, + unsigned size) +{ + return 0; +} + +static void tcx_blit_writel(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + TCXState *s = opaque; + uint32_t adsr, len; + int i; + + if (!(addr & 4)) { + s->tmpblit = val; + } else { + addr = (addr >> 3) & 0xfffff; + adsr = val & 0xffffff; + len = ((val >> 24) & 0x1f) + 1; + if (adsr == 0xffffff) { + memset(&s->vram[addr], s->tmpblit, len); + if (s->depth == 24) { + val = s->tmpblit & 0xffffff; + val = cpu_to_be32(val); + for (i = 0; i < len; i++) { + s->vram24[addr + i] = val; + } + } + } else { + memcpy(&s->vram[addr], &s->vram[adsr], len); + if (s->depth == 24) { + memcpy(&s->vram24[addr], &s->vram24[adsr], len * 4); + } + } + memory_region_set_dirty(&s->vram_mem, addr, len); + } +} + +static void tcx_rblit_writel(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + TCXState *s = opaque; + uint32_t adsr, len; + int i; + + if (!(addr & 4)) { + s->tmpblit = val; + } else { + addr = (addr >> 3) & 0xfffff; + adsr = val & 0xffffff; + len = ((val >> 24) & 0x1f) + 1; + if (adsr == 0xffffff) { + memset(&s->vram[addr], s->tmpblit, len); + if (s->depth == 24) { + val = s->tmpblit & 0xffffff; + val = cpu_to_be32(val); + for (i = 0; i < len; i++) { + s->vram24[addr + i] = val; + s->cplane[addr + i] = val; + } + } + } else { + memcpy(&s->vram[addr], &s->vram[adsr], len); + if (s->depth == 24) { + memcpy(&s->vram24[addr], &s->vram24[adsr], len * 4); + memcpy(&s->cplane[addr], &s->cplane[adsr], len * 4); + } + } + memory_region_set_dirty(&s->vram_mem, addr, len); + } +} + +static const MemoryRegionOps tcx_blit_ops = { + .read = tcx_blit_readl, + .write = tcx_blit_writel, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static const MemoryRegionOps tcx_rblit_ops = { + .read = tcx_blit_readl, + .write = tcx_rblit_writel, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static void tcx_invalidate_cursor_position(TCXState *s) +{ + int ymin, ymax, start, end; + + /* invalidate only near the cursor */ + ymin = s->cursy; + if (ymin >= s->height) { + return; + } + ymax = MIN(s->height, ymin + 32); + start = ymin * 1024; + end = ymax * 1024; + + memory_region_set_dirty(&s->vram_mem, start, end-start); +} + +static uint64_t tcx_thc_readl(void *opaque, hwaddr addr, + unsigned size) +{ + TCXState *s = opaque; + uint64_t val; + + if (addr == TCX_THC_MISC) { + val = s->thcmisc | 0x02000000; + } else { + val = 0; + } + return val; +} + +static void tcx_thc_writel(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + TCXState *s = opaque; + + if (addr == TCX_THC_CURSXY) { + tcx_invalidate_cursor_position(s); + s->cursx = val >> 16; + s->cursy = val; + tcx_invalidate_cursor_position(s); + } else if (addr >= TCX_THC_CURSMASK && addr < TCX_THC_CURSMASK + 128) { + s->cursmask[(addr - TCX_THC_CURSMASK) >> 2] = val; + tcx_invalidate_cursor_position(s); + } else if (addr >= TCX_THC_CURSBITS && addr < TCX_THC_CURSBITS + 128) { + s->cursbits[(addr - TCX_THC_CURSBITS) >> 2] = val; + tcx_invalidate_cursor_position(s); + } else if (addr == TCX_THC_MISC) { + s->thcmisc = val; + } + +} + +static const MemoryRegionOps tcx_thc_ops = { + .read = tcx_thc_readl, + .write = tcx_thc_writel, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static uint64_t tcx_dummy_readl(void *opaque, hwaddr addr, unsigned size) { return 0; } -static void dummy_writel(void *opaque, hwaddr addr, +static void tcx_dummy_writel(void *opaque, hwaddr addr, uint64_t val, unsigned size) { + return; } -static const MemoryRegionOps dummy_ops = { - .read = dummy_readl, - .write = dummy_writel, +static const MemoryRegionOps tcx_dummy_ops = { + .read = tcx_dummy_readl, + .write = tcx_dummy_writel, .endianness = DEVICE_NATIVE_ENDIAN, .valid = { .min_access_size = 4, @@ -531,8 +936,67 @@ static const GraphicHwOps tcx24_ops = { .gfx_update = tcx24_update_display, }; -static int tcx_init1(SysBusDevice *dev) +static void tcx_initfn(Object *obj) +{ + SysBusDevice *sbd = SYS_BUS_DEVICE(obj); + TCXState *s = TCX(obj); + + memory_region_init_ram(&s->rom, NULL, "tcx.prom", FCODE_MAX_ROM_SIZE, + &error_abort); + memory_region_set_readonly(&s->rom, true); + sysbus_init_mmio(sbd, &s->rom); + + /* 2/STIP : Stippler */ + memory_region_init_io(&s->stip, OBJECT(s), &tcx_stip_ops, s, "tcx.stip", + TCX_STIP_NREGS); + sysbus_init_mmio(sbd, &s->stip); + + /* 3/BLIT : Blitter */ + memory_region_init_io(&s->blit, OBJECT(s), &tcx_blit_ops, s, "tcx.blit", + TCX_BLIT_NREGS); + sysbus_init_mmio(sbd, &s->blit); + + /* 5/RSTIP : Raw Stippler */ + memory_region_init_io(&s->rstip, OBJECT(s), &tcx_rstip_ops, s, "tcx.rstip", + TCX_RSTIP_NREGS); + sysbus_init_mmio(sbd, &s->rstip); + + /* 6/RBLIT : Raw Blitter */ + memory_region_init_io(&s->rblit, OBJECT(s), &tcx_rblit_ops, s, "tcx.rblit", + TCX_RBLIT_NREGS); + sysbus_init_mmio(sbd, &s->rblit); + + /* 7/TEC : ??? */ + memory_region_init_io(&s->tec, OBJECT(s), &tcx_dummy_ops, s, + "tcx.tec", TCX_TEC_NREGS); + sysbus_init_mmio(sbd, &s->tec); + + /* 8/CMAP : DAC */ + memory_region_init_io(&s->dac, OBJECT(s), &tcx_dac_ops, s, + "tcx.dac", TCX_DAC_NREGS); + sysbus_init_mmio(sbd, &s->dac); + + /* 9/THC : Cursor */ + memory_region_init_io(&s->thc, OBJECT(s), &tcx_thc_ops, s, "tcx.thc", + TCX_THC_NREGS); + sysbus_init_mmio(sbd, &s->thc); + + /* 11/DHC : ??? */ + memory_region_init_io(&s->dhc, OBJECT(s), &tcx_dummy_ops, s, "tcx.dhc", + TCX_DHC_NREGS); + sysbus_init_mmio(sbd, &s->dhc); + + /* 12/ALT : ??? */ + memory_region_init_io(&s->alt, OBJECT(s), &tcx_dummy_ops, s, "tcx.alt", + TCX_ALT_NREGS); + sysbus_init_mmio(sbd, &s->alt); + + return; +} + +static void tcx_realizefn(DeviceState *dev, Error **errp) { + SysBusDevice *sbd = SYS_BUS_DEVICE(dev); TCXState *s = TCX(dev); ram_addr_t vram_offset = 0; int size, ret; @@ -540,80 +1004,65 @@ static int tcx_init1(SysBusDevice *dev) char *fcode_filename; memory_region_init_ram(&s->vram_mem, OBJECT(s), "tcx.vram", - s->vram_size * (1 + 4 + 4)); + s->vram_size * (1 + 4 + 4), &error_abort); vmstate_register_ram_global(&s->vram_mem); vram_base = memory_region_get_ram_ptr(&s->vram_mem); - /* FCode ROM */ - memory_region_init_ram(&s->rom, NULL, "tcx.prom", FCODE_MAX_ROM_SIZE); + /* 10/ROM : FCode ROM */ vmstate_register_ram_global(&s->rom); - memory_region_set_readonly(&s->rom, true); - sysbus_init_mmio(dev, &s->rom); - fcode_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, TCX_ROM_FILE); if (fcode_filename) { ret = load_image_targphys(fcode_filename, s->prom_addr, FCODE_MAX_ROM_SIZE); if (ret < 0 || ret > FCODE_MAX_ROM_SIZE) { - fprintf(stderr, "tcx: could not load prom '%s'\n", TCX_ROM_FILE); - return -1; + error_report("tcx: could not load prom '%s'", TCX_ROM_FILE); } } - /* 8-bit plane */ + /* 0/DFB8 : 8-bit plane */ s->vram = vram_base; size = s->vram_size; memory_region_init_alias(&s->vram_8bit, OBJECT(s), "tcx.vram.8bit", &s->vram_mem, vram_offset, size); - sysbus_init_mmio(dev, &s->vram_8bit); + sysbus_init_mmio(sbd, &s->vram_8bit); vram_offset += size; vram_base += size; - /* DAC */ - memory_region_init_io(&s->dac, OBJECT(s), &tcx_dac_ops, s, - "tcx.dac", TCX_DAC_NREGS); - sysbus_init_mmio(dev, &s->dac); + /* 1/DFB24 : 24bit plane */ + size = s->vram_size * 4; + s->vram24 = (uint32_t *)vram_base; + s->vram24_offset = vram_offset; + memory_region_init_alias(&s->vram_24bit, OBJECT(s), "tcx.vram.24bit", + &s->vram_mem, vram_offset, size); + sysbus_init_mmio(sbd, &s->vram_24bit); + vram_offset += size; + vram_base += size; - /* TEC (dummy) */ - memory_region_init_io(&s->tec, OBJECT(s), &dummy_ops, s, - "tcx.tec", TCX_TEC_NREGS); - sysbus_init_mmio(dev, &s->tec); - /* THC: NetBSD writes here even with 8-bit display: dummy */ - memory_region_init_io(&s->thc24, OBJECT(s), &dummy_ops, s, "tcx.thc24", - TCX_THC_NREGS_24); - sysbus_init_mmio(dev, &s->thc24); - - if (s->depth == 24) { - /* 24-bit plane */ - size = s->vram_size * 4; - s->vram24 = (uint32_t *)vram_base; - s->vram24_offset = vram_offset; - memory_region_init_alias(&s->vram_24bit, OBJECT(s), "tcx.vram.24bit", - &s->vram_mem, vram_offset, size); - sysbus_init_mmio(dev, &s->vram_24bit); - vram_offset += size; - vram_base += size; - - /* Control plane */ - size = s->vram_size * 4; - s->cplane = (uint32_t *)vram_base; - s->cplane_offset = vram_offset; - memory_region_init_alias(&s->vram_cplane, OBJECT(s), "tcx.vram.cplane", - &s->vram_mem, vram_offset, size); - sysbus_init_mmio(dev, &s->vram_cplane); + /* 4/RDFB32 : Raw Framebuffer */ + size = s->vram_size * 4; + s->cplane = (uint32_t *)vram_base; + s->cplane_offset = vram_offset; + memory_region_init_alias(&s->vram_cplane, OBJECT(s), "tcx.vram.cplane", + &s->vram_mem, vram_offset, size); + sysbus_init_mmio(sbd, &s->vram_cplane); - s->con = graphic_console_init(DEVICE(dev), 0, &tcx24_ops, s); - } else { - /* THC 8 bit (dummy) */ - memory_region_init_io(&s->thc8, OBJECT(s), &dummy_ops, s, "tcx.thc8", - TCX_THC_NREGS_8); - sysbus_init_mmio(dev, &s->thc8); + /* 9/THC24bits : NetBSD writes here even with 8-bit display: dummy */ + if (s->depth == 8) { + memory_region_init_io(&s->thc24, OBJECT(s), &tcx_dummy_ops, s, + "tcx.thc24", TCX_THC_NREGS); + sysbus_init_mmio(sbd, &s->thc24); + } + sysbus_init_irq(sbd, &s->irq); + + if (s->depth == 8) { s->con = graphic_console_init(DEVICE(dev), 0, &tcx_ops, s); + } else { + s->con = graphic_console_init(DEVICE(dev), 0, &tcx24_ops, s); } + s->thcmisc = 0; qemu_console_resize(s->con, s->width, s->height); - return 0; } static Property tcx_properties[] = { @@ -628,9 +1077,8 @@ static Property tcx_properties[] = { static void tcx_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); - k->init = tcx_init1; + dc->realize = tcx_realizefn; dc->reset = tcx_reset; dc->vmsd = &vmstate_tcx; dc->props = tcx_properties; @@ -640,6 +1088,7 @@ static const TypeInfo tcx_info = { .name = TYPE_TCX, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(TCXState), + .instance_init = tcx_initfn, .class_init = tcx_class_init, }; diff --git a/hw/display/vga_template.h b/hw/display/vga-helpers.h index 6cfae567b4..94f6de2046 100644 --- a/hw/display/vga_template.h +++ b/hw/display/vga-helpers.h @@ -22,41 +22,9 @@ * THE SOFTWARE. */ -#if DEPTH == 8 -#define BPP 1 -#define PIXEL_TYPE uint8_t -#elif DEPTH == 15 || DEPTH == 16 -#define BPP 2 -#define PIXEL_TYPE uint16_t -#elif DEPTH == 32 -#define BPP 4 -#define PIXEL_TYPE uint32_t -#else -#error unsupport depth -#endif - -#ifdef BGR_FORMAT -#define PIXEL_NAME glue(DEPTH, bgr) -#else -#define PIXEL_NAME DEPTH -#endif /* BGR_FORMAT */ - -#if DEPTH != 15 && !defined(BGR_FORMAT) - -static inline void glue(vga_draw_glyph_line_, DEPTH)(uint8_t *d, - uint32_t font_data, - uint32_t xorcol, - uint32_t bgcol) +static inline void vga_draw_glyph_line(uint8_t *d, uint32_t font_data, + uint32_t xorcol, uint32_t bgcol) { -#if BPP == 1 - ((uint32_t *)d)[0] = (dmask16[(font_data >> 4)] & xorcol) ^ bgcol; - ((uint32_t *)d)[1] = (dmask16[(font_data >> 0) & 0xf] & xorcol) ^ bgcol; -#elif BPP == 2 - ((uint32_t *)d)[0] = (dmask4[(font_data >> 6)] & xorcol) ^ bgcol; - ((uint32_t *)d)[1] = (dmask4[(font_data >> 4) & 3] & xorcol) ^ bgcol; - ((uint32_t *)d)[2] = (dmask4[(font_data >> 2) & 3] & xorcol) ^ bgcol; - ((uint32_t *)d)[3] = (dmask4[(font_data >> 0) & 3] & xorcol) ^ bgcol; -#else ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol; ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol; @@ -65,25 +33,24 @@ static inline void glue(vga_draw_glyph_line_, DEPTH)(uint8_t *d, ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol; -#endif } -static void glue(vga_draw_glyph8_, DEPTH)(uint8_t *d, int linesize, - const uint8_t *font_ptr, int h, - uint32_t fgcol, uint32_t bgcol) +static void vga_draw_glyph8(uint8_t *d, int linesize, + const uint8_t *font_ptr, int h, + uint32_t fgcol, uint32_t bgcol) { uint32_t font_data, xorcol; xorcol = bgcol ^ fgcol; do { font_data = font_ptr[0]; - glue(vga_draw_glyph_line_, DEPTH)(d, font_data, xorcol, bgcol); + vga_draw_glyph_line(d, font_data, xorcol, bgcol); font_ptr += 4; d += linesize; } while (--h); } -static void glue(vga_draw_glyph16_, DEPTH)(uint8_t *d, int linesize, +static void vga_draw_glyph16(uint8_t *d, int linesize, const uint8_t *font_ptr, int h, uint32_t fgcol, uint32_t bgcol) { @@ -92,48 +59,24 @@ static void glue(vga_draw_glyph16_, DEPTH)(uint8_t *d, int linesize, xorcol = bgcol ^ fgcol; do { font_data = font_ptr[0]; - glue(vga_draw_glyph_line_, DEPTH)(d, - expand4to8[font_data >> 4], - xorcol, bgcol); - glue(vga_draw_glyph_line_, DEPTH)(d + 8 * BPP, - expand4to8[font_data & 0x0f], - xorcol, bgcol); + vga_draw_glyph_line(d, expand4to8[font_data >> 4], + xorcol, bgcol); + vga_draw_glyph_line(d + 32, expand4to8[font_data & 0x0f], + xorcol, bgcol); font_ptr += 4; d += linesize; } while (--h); } -static void glue(vga_draw_glyph9_, DEPTH)(uint8_t *d, int linesize, - const uint8_t *font_ptr, int h, - uint32_t fgcol, uint32_t bgcol, int dup9) +static void vga_draw_glyph9(uint8_t *d, int linesize, + const uint8_t *font_ptr, int h, + uint32_t fgcol, uint32_t bgcol, int dup9) { uint32_t font_data, xorcol, v; xorcol = bgcol ^ fgcol; do { font_data = font_ptr[0]; -#if BPP == 1 - stl_p((uint32_t *)d, (dmask16[(font_data >> 4)] & xorcol) ^ bgcol); - v = (dmask16[(font_data >> 0) & 0xf] & xorcol) ^ bgcol; - stl_p(((uint32_t *)d)+1, v); - if (dup9) - ((uint8_t *)d)[8] = v >> (24 * (1 - BIG)); - else - ((uint8_t *)d)[8] = bgcol; - -#elif BPP == 2 - stl_p(((uint32_t *)d)+0, (dmask4[(font_data >> 6)] & xorcol) ^ bgcol); - stl_p(((uint32_t *)d)+1, - (dmask4[(font_data >> 4) & 3] & xorcol) ^ bgcol); - stl_p(((uint32_t *)d)+2, - (dmask4[(font_data >> 2) & 3] & xorcol) ^ bgcol); - v = (dmask4[(font_data >> 0) & 3] & xorcol) ^ bgcol; - stl_p(((uint32_t *)d)+3, v); - if (dup9) - ((uint16_t *)d)[8] = v >> (16 * (1 - BIG)); - else - ((uint16_t *)d)[8] = bgcol; -#else ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol; ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol; @@ -147,7 +90,6 @@ static void glue(vga_draw_glyph9_, DEPTH)(uint8_t *d, int linesize, ((uint32_t *)d)[8] = v; else ((uint32_t *)d)[8] = bgcol; -#endif font_ptr += 4; d += linesize; } while (--h); @@ -156,8 +98,8 @@ static void glue(vga_draw_glyph9_, DEPTH)(uint8_t *d, int linesize, /* * 4 color mode */ -static void glue(vga_draw_line2_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line2(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t plane_mask, *palette, data, v; int x; @@ -170,36 +112,30 @@ static void glue(vga_draw_line2_, DEPTH)(VGACommonState *s1, uint8_t *d, data &= plane_mask; v = expand2[GET_PLANE(data, 0)]; v |= expand2[GET_PLANE(data, 2)] << 2; - ((PIXEL_TYPE *)d)[0] = palette[v >> 12]; - ((PIXEL_TYPE *)d)[1] = palette[(v >> 8) & 0xf]; - ((PIXEL_TYPE *)d)[2] = palette[(v >> 4) & 0xf]; - ((PIXEL_TYPE *)d)[3] = palette[(v >> 0) & 0xf]; + ((uint32_t *)d)[0] = palette[v >> 12]; + ((uint32_t *)d)[1] = palette[(v >> 8) & 0xf]; + ((uint32_t *)d)[2] = palette[(v >> 4) & 0xf]; + ((uint32_t *)d)[3] = palette[(v >> 0) & 0xf]; v = expand2[GET_PLANE(data, 1)]; v |= expand2[GET_PLANE(data, 3)] << 2; - ((PIXEL_TYPE *)d)[4] = palette[v >> 12]; - ((PIXEL_TYPE *)d)[5] = palette[(v >> 8) & 0xf]; - ((PIXEL_TYPE *)d)[6] = palette[(v >> 4) & 0xf]; - ((PIXEL_TYPE *)d)[7] = palette[(v >> 0) & 0xf]; - d += BPP * 8; + ((uint32_t *)d)[4] = palette[v >> 12]; + ((uint32_t *)d)[5] = palette[(v >> 8) & 0xf]; + ((uint32_t *)d)[6] = palette[(v >> 4) & 0xf]; + ((uint32_t *)d)[7] = palette[(v >> 0) & 0xf]; + d += 32; s += 4; } } -#if BPP == 1 -#define PUT_PIXEL2(d, n, v) ((uint16_t *)d)[(n)] = (v) -#elif BPP == 2 -#define PUT_PIXEL2(d, n, v) ((uint32_t *)d)[(n)] = (v) -#else #define PUT_PIXEL2(d, n, v) \ ((uint32_t *)d)[2*(n)] = ((uint32_t *)d)[2*(n)+1] = (v) -#endif /* * 4 color mode, dup2 horizontal */ -static void glue(vga_draw_line2d2_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line2d2(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t plane_mask, *palette, data, v; int x; @@ -223,7 +159,7 @@ static void glue(vga_draw_line2d2_, DEPTH)(VGACommonState *s1, uint8_t *d, PUT_PIXEL2(d, 5, palette[(v >> 8) & 0xf]); PUT_PIXEL2(d, 6, palette[(v >> 4) & 0xf]); PUT_PIXEL2(d, 7, palette[(v >> 0) & 0xf]); - d += BPP * 16; + d += 64; s += 4; } } @@ -231,8 +167,8 @@ static void glue(vga_draw_line2d2_, DEPTH)(VGACommonState *s1, uint8_t *d, /* * 16 color mode */ -static void glue(vga_draw_line4_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line4(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t plane_mask, data, v, *palette; int x; @@ -247,15 +183,15 @@ static void glue(vga_draw_line4_, DEPTH)(VGACommonState *s1, uint8_t *d, v |= expand4[GET_PLANE(data, 1)] << 1; v |= expand4[GET_PLANE(data, 2)] << 2; v |= expand4[GET_PLANE(data, 3)] << 3; - ((PIXEL_TYPE *)d)[0] = palette[v >> 28]; - ((PIXEL_TYPE *)d)[1] = palette[(v >> 24) & 0xf]; - ((PIXEL_TYPE *)d)[2] = palette[(v >> 20) & 0xf]; - ((PIXEL_TYPE *)d)[3] = palette[(v >> 16) & 0xf]; - ((PIXEL_TYPE *)d)[4] = palette[(v >> 12) & 0xf]; - ((PIXEL_TYPE *)d)[5] = palette[(v >> 8) & 0xf]; - ((PIXEL_TYPE *)d)[6] = palette[(v >> 4) & 0xf]; - ((PIXEL_TYPE *)d)[7] = palette[(v >> 0) & 0xf]; - d += BPP * 8; + ((uint32_t *)d)[0] = palette[v >> 28]; + ((uint32_t *)d)[1] = palette[(v >> 24) & 0xf]; + ((uint32_t *)d)[2] = palette[(v >> 20) & 0xf]; + ((uint32_t *)d)[3] = palette[(v >> 16) & 0xf]; + ((uint32_t *)d)[4] = palette[(v >> 12) & 0xf]; + ((uint32_t *)d)[5] = palette[(v >> 8) & 0xf]; + ((uint32_t *)d)[6] = palette[(v >> 4) & 0xf]; + ((uint32_t *)d)[7] = palette[(v >> 0) & 0xf]; + d += 32; s += 4; } } @@ -263,8 +199,8 @@ static void glue(vga_draw_line4_, DEPTH)(VGACommonState *s1, uint8_t *d, /* * 16 color mode, dup2 horizontal */ -static void glue(vga_draw_line4d2_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line4d2(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t plane_mask, data, v, *palette; int x; @@ -287,7 +223,7 @@ static void glue(vga_draw_line4d2_, DEPTH)(VGACommonState *s1, uint8_t *d, PUT_PIXEL2(d, 5, palette[(v >> 8) & 0xf]); PUT_PIXEL2(d, 6, palette[(v >> 4) & 0xf]); PUT_PIXEL2(d, 7, palette[(v >> 0) & 0xf]); - d += BPP * 16; + d += 64; s += 4; } } @@ -297,8 +233,8 @@ static void glue(vga_draw_line4d2_, DEPTH)(VGACommonState *s1, uint8_t *d, * * XXX: add plane_mask support (never used in standard VGA modes) */ -static void glue(vga_draw_line8d2_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line8d2(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t *palette; int x; @@ -310,7 +246,7 @@ static void glue(vga_draw_line8d2_, DEPTH)(VGACommonState *s1, uint8_t *d, PUT_PIXEL2(d, 1, palette[s[1]]); PUT_PIXEL2(d, 2, palette[s[2]]); PUT_PIXEL2(d, 3, palette[s[3]]); - d += BPP * 8; + d += 32; s += 4; } } @@ -320,8 +256,8 @@ static void glue(vga_draw_line8d2_, DEPTH)(VGACommonState *s1, uint8_t *d, * * XXX: add plane_mask support (never used in standard VGA modes) */ -static void glue(vga_draw_line8_, DEPTH)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line8(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { uint32_t *palette; int x; @@ -329,107 +265,141 @@ static void glue(vga_draw_line8_, DEPTH)(VGACommonState *s1, uint8_t *d, palette = s1->last_palette; width >>= 3; for(x = 0; x < width; x++) { - ((PIXEL_TYPE *)d)[0] = palette[s[0]]; - ((PIXEL_TYPE *)d)[1] = palette[s[1]]; - ((PIXEL_TYPE *)d)[2] = palette[s[2]]; - ((PIXEL_TYPE *)d)[3] = palette[s[3]]; - ((PIXEL_TYPE *)d)[4] = palette[s[4]]; - ((PIXEL_TYPE *)d)[5] = palette[s[5]]; - ((PIXEL_TYPE *)d)[6] = palette[s[6]]; - ((PIXEL_TYPE *)d)[7] = palette[s[7]]; - d += BPP * 8; + ((uint32_t *)d)[0] = palette[s[0]]; + ((uint32_t *)d)[1] = palette[s[1]]; + ((uint32_t *)d)[2] = palette[s[2]]; + ((uint32_t *)d)[3] = palette[s[3]]; + ((uint32_t *)d)[4] = palette[s[4]]; + ((uint32_t *)d)[5] = palette[s[5]]; + ((uint32_t *)d)[6] = palette[s[6]]; + ((uint32_t *)d)[7] = palette[s[7]]; + d += 32; s += 8; } } -#endif /* DEPTH != 15 */ - - -/* XXX: optimize */ - /* * 15 bit color */ -static void glue(vga_draw_line15_, PIXEL_NAME)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line15_le(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { -#if DEPTH == 15 && defined(HOST_WORDS_BIGENDIAN) == defined(TARGET_WORDS_BIGENDIAN) - memcpy(d, s, width * 2); -#else int w; uint32_t v, r, g, b; w = width; do { - v = lduw_raw((void *)s); + v = lduw_le_p((void *)s); r = (v >> 7) & 0xf8; g = (v >> 2) & 0xf8; b = (v << 3) & 0xf8; - ((PIXEL_TYPE *)d)[0] = glue(rgb_to_pixel, PIXEL_NAME)(r, g, b); + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); s += 2; - d += BPP; + d += 4; + } while (--w != 0); +} + +static void vga_draw_line15_be(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) +{ + int w; + uint32_t v, r, g, b; + + w = width; + do { + v = lduw_be_p((void *)s); + r = (v >> 7) & 0xf8; + g = (v >> 2) & 0xf8; + b = (v << 3) & 0xf8; + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); + s += 2; + d += 4; } while (--w != 0); -#endif } /* * 16 bit color */ -static void glue(vga_draw_line16_, PIXEL_NAME)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line16_le(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { -#if DEPTH == 16 && defined(HOST_WORDS_BIGENDIAN) == defined(TARGET_WORDS_BIGENDIAN) - memcpy(d, s, width * 2); -#else int w; uint32_t v, r, g, b; w = width; do { - v = lduw_raw((void *)s); + v = lduw_le_p((void *)s); r = (v >> 8) & 0xf8; g = (v >> 3) & 0xfc; b = (v << 3) & 0xf8; - ((PIXEL_TYPE *)d)[0] = glue(rgb_to_pixel, PIXEL_NAME)(r, g, b); + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); s += 2; - d += BPP; + d += 4; + } while (--w != 0); +} + +static void vga_draw_line16_be(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) +{ + int w; + uint32_t v, r, g, b; + + w = width; + do { + v = lduw_be_p((void *)s); + r = (v >> 8) & 0xf8; + g = (v >> 3) & 0xfc; + b = (v << 3) & 0xf8; + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); + s += 2; + d += 4; } while (--w != 0); -#endif } /* * 24 bit color */ -static void glue(vga_draw_line24_, PIXEL_NAME)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line24_le(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { int w; uint32_t r, g, b; w = width; do { -#if defined(TARGET_WORDS_BIGENDIAN) - r = s[0]; - g = s[1]; - b = s[2]; -#else b = s[0]; g = s[1]; r = s[2]; -#endif - ((PIXEL_TYPE *)d)[0] = glue(rgb_to_pixel, PIXEL_NAME)(r, g, b); + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); s += 3; - d += BPP; + d += 4; + } while (--w != 0); +} + +static void vga_draw_line24_be(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) +{ + int w; + uint32_t r, g, b; + + w = width; + do { + r = s[0]; + g = s[1]; + b = s[2]; + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); + s += 3; + d += 4; } while (--w != 0); } /* * 32 bit color */ -static void glue(vga_draw_line32_, PIXEL_NAME)(VGACommonState *s1, uint8_t *d, - const uint8_t *s, int width) +static void vga_draw_line32_le(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) { -#if DEPTH == 32 && defined(HOST_WORDS_BIGENDIAN) == defined(TARGET_WORDS_BIGENDIAN) && !defined(BGR_FORMAT) +#ifndef HOST_WORDS_BIGENDIAN memcpy(d, s, width * 4); #else int w; @@ -437,25 +407,33 @@ static void glue(vga_draw_line32_, PIXEL_NAME)(VGACommonState *s1, uint8_t *d, w = width; do { -#if defined(TARGET_WORDS_BIGENDIAN) - r = s[1]; - g = s[2]; - b = s[3]; -#else b = s[0]; g = s[1]; r = s[2]; -#endif - ((PIXEL_TYPE *)d)[0] = glue(rgb_to_pixel, PIXEL_NAME)(r, g, b); + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); s += 4; - d += BPP; + d += 4; } while (--w != 0); #endif } -#undef PUT_PIXEL2 -#undef DEPTH -#undef BPP -#undef PIXEL_TYPE -#undef PIXEL_NAME -#undef BGR_FORMAT +static void vga_draw_line32_be(VGACommonState *s1, uint8_t *d, + const uint8_t *s, int width) +{ +#ifdef HOST_WORDS_BIGENDIAN + memcpy(d, s, width * 4); +#else + int w; + uint32_t r, g, b; + + w = width; + do { + r = s[1]; + g = s[2]; + b = s[3]; + ((uint32_t *)d)[0] = rgb_to_pixel32(r, g, b); + s += 4; + d += 4; + } while (--w != 0); +#endif +} diff --git a/hw/display/vga-isa-mm.c b/hw/display/vga-isa-mm.c index afc46b8c9d..4efc222789 100644 --- a/hw/display/vga-isa-mm.c +++ b/hw/display/vga-isa-mm.c @@ -132,7 +132,7 @@ int isa_vga_mm_init(hwaddr vram_base, s = g_malloc0(sizeof(*s)); s->vga.vram_size_mb = VGA_RAM_SIZE >> 20; - vga_common_init(&s->vga, NULL); + vga_common_init(&s->vga, NULL, true); vga_mm_init(s, vram_base, ctrl_base, it_shift, address_space); s->vga.con = graphic_console_init(NULL, 0, s->vga.hw_ops, s); diff --git a/hw/display/vga-isa.c b/hw/display/vga-isa.c index 1d9ea6b51d..2b480bd44d 100644 --- a/hw/display/vga-isa.c +++ b/hw/display/vga-isa.c @@ -56,7 +56,7 @@ static void vga_isa_realizefn(DeviceState *dev, Error **errp) MemoryRegion *vga_io_memory; const MemoryRegionPortio *vga_ports, *vbe_ports; - vga_common_init(s, OBJECT(dev)); + vga_common_init(s, OBJECT(dev), true); s->legacy_address_space = isa_address_space(isadev); vga_io_memory = vga_init_io(s, OBJECT(dev), &vga_ports, &vbe_ports); isa_register_portio_list(isadev, 0x3b0, vga_ports, s, "vga"); diff --git a/hw/display/vga-pci.c b/hw/display/vga-pci.c index 574ea0e7f9..db922f1843 100644 --- a/hw/display/vga-pci.c +++ b/hw/display/vga-pci.c @@ -35,10 +35,18 @@ #define PCI_VGA_IOPORT_SIZE (0x3e0 - 0x3c0) #define PCI_VGA_BOCHS_OFFSET 0x500 #define PCI_VGA_BOCHS_SIZE (0x0b * 2) +#define PCI_VGA_QEXT_OFFSET 0x600 +#define PCI_VGA_QEXT_SIZE (2 * 4) #define PCI_VGA_MMIO_SIZE 0x1000 +#define PCI_VGA_QEXT_REG_SIZE (0 * 4) +#define PCI_VGA_QEXT_REG_BYTEORDER (1 * 4) +#define PCI_VGA_QEXT_LITTLE_ENDIAN 0x1e1e1e1e +#define PCI_VGA_QEXT_BIG_ENDIAN 0xbebebebe + enum vga_pci_flags { PCI_VGA_FLAG_ENABLE_MMIO = 1, + PCI_VGA_FLAG_ENABLE_QEXT = 2, }; typedef struct PCIVGAState { @@ -48,14 +56,14 @@ typedef struct PCIVGAState { MemoryRegion mmio; MemoryRegion ioport; MemoryRegion bochs; + MemoryRegion qext; } PCIVGAState; static const VMStateDescription vmstate_vga_pci = { .name = "vga", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCIVGAState), VMSTATE_STRUCT(vga, PCIVGAState, 0, vmstate_vga_common, VGACommonState), VMSTATE_END_OF_LIST() @@ -141,13 +149,53 @@ static const MemoryRegionOps pci_vga_bochs_ops = { .endianness = DEVICE_LITTLE_ENDIAN, }; +static uint64_t pci_vga_qext_read(void *ptr, hwaddr addr, unsigned size) +{ + PCIVGAState *d = ptr; + + switch (addr) { + case PCI_VGA_QEXT_REG_SIZE: + return PCI_VGA_QEXT_SIZE; + case PCI_VGA_QEXT_REG_BYTEORDER: + return d->vga.big_endian_fb ? + PCI_VGA_QEXT_BIG_ENDIAN : PCI_VGA_QEXT_LITTLE_ENDIAN; + default: + return 0; + } +} + +static void pci_vga_qext_write(void *ptr, hwaddr addr, + uint64_t val, unsigned size) +{ + PCIVGAState *d = ptr; + + switch (addr) { + case PCI_VGA_QEXT_REG_BYTEORDER: + if (val == PCI_VGA_QEXT_BIG_ENDIAN) { + d->vga.big_endian_fb = true; + } + if (val == PCI_VGA_QEXT_LITTLE_ENDIAN) { + d->vga.big_endian_fb = false; + } + break; + } +} + +static const MemoryRegionOps pci_vga_qext_ops = { + .read = pci_vga_qext_read, + .write = pci_vga_qext_write, + .valid.min_access_size = 4, + .valid.max_access_size = 4, + .endianness = DEVICE_LITTLE_ENDIAN, +}; + static int pci_std_vga_initfn(PCIDevice *dev) { PCIVGAState *d = DO_UPCAST(PCIVGAState, dev, dev); VGACommonState *s = &d->vga; /* vga + console init */ - vga_common_init(s, OBJECT(dev)); + vga_common_init(s, OBJECT(dev), true); vga_init(s, OBJECT(dev), pci_address_space(dev), pci_address_space_io(dev), true); @@ -168,6 +216,15 @@ static int pci_std_vga_initfn(PCIDevice *dev) &d->ioport); memory_region_add_subregion(&d->mmio, PCI_VGA_BOCHS_OFFSET, &d->bochs); + + if (d->flags & (1 << PCI_VGA_FLAG_ENABLE_QEXT)) { + memory_region_init_io(&d->qext, NULL, &pci_vga_qext_ops, d, + "qemu extended regs", PCI_VGA_QEXT_SIZE); + memory_region_add_subregion(&d->mmio, PCI_VGA_QEXT_OFFSET, + &d->qext); + pci_set_byte(&d->dev.config[PCI_REVISION_ID], 2); + } + pci_register_bar(&d->dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY, &d->mmio); } @@ -179,9 +236,60 @@ static int pci_std_vga_initfn(PCIDevice *dev) return 0; } +static int pci_secondary_vga_initfn(PCIDevice *dev) +{ + PCIVGAState *d = DO_UPCAST(PCIVGAState, dev, dev); + VGACommonState *s = &d->vga; + + /* vga + console init */ + vga_common_init(s, OBJECT(dev), false); + s->con = graphic_console_init(DEVICE(dev), 0, s->hw_ops, s); + + /* mmio bar */ + memory_region_init(&d->mmio, OBJECT(dev), "vga.mmio", 4096); + memory_region_init_io(&d->ioport, OBJECT(dev), &pci_vga_ioport_ops, d, + "vga ioports remapped", PCI_VGA_IOPORT_SIZE); + memory_region_init_io(&d->bochs, OBJECT(dev), &pci_vga_bochs_ops, d, + "bochs dispi interface", PCI_VGA_BOCHS_SIZE); + + memory_region_add_subregion(&d->mmio, PCI_VGA_IOPORT_OFFSET, + &d->ioport); + memory_region_add_subregion(&d->mmio, PCI_VGA_BOCHS_OFFSET, + &d->bochs); + + if (d->flags & (1 << PCI_VGA_FLAG_ENABLE_QEXT)) { + memory_region_init_io(&d->qext, NULL, &pci_vga_qext_ops, d, + "qemu extended regs", PCI_VGA_QEXT_SIZE); + memory_region_add_subregion(&d->mmio, PCI_VGA_QEXT_OFFSET, + &d->qext); + pci_set_byte(&d->dev.config[PCI_REVISION_ID], 2); + } + + pci_register_bar(&d->dev, 0, PCI_BASE_ADDRESS_MEM_PREFETCH, &s->vram); + pci_register_bar(&d->dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY, &d->mmio); + + return 0; +} + +static void pci_secondary_vga_reset(DeviceState *dev) +{ + PCIVGAState *d = DO_UPCAST(PCIVGAState, dev.qdev, dev); + + vga_common_reset(&d->vga); +} + static Property vga_pci_properties[] = { DEFINE_PROP_UINT32("vgamem_mb", PCIVGAState, vga.vram_size_mb, 16), DEFINE_PROP_BIT("mmio", PCIVGAState, flags, PCI_VGA_FLAG_ENABLE_MMIO, true), + DEFINE_PROP_BIT("qemu-extended-regs", + PCIVGAState, flags, PCI_VGA_FLAG_ENABLE_QEXT, true), + DEFINE_PROP_END_OF_LIST(), +}; + +static Property secondary_pci_properties[] = { + DEFINE_PROP_UINT32("vgamem_mb", PCIVGAState, vga.vram_size_mb, 16), + DEFINE_PROP_BIT("qemu-extended-regs", + PCIVGAState, flags, PCI_VGA_FLAG_ENABLE_QEXT, true), DEFINE_PROP_END_OF_LIST(), }; @@ -201,6 +309,20 @@ static void vga_class_init(ObjectClass *klass, void *data) set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories); } +static void secondary_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + + k->init = pci_secondary_vga_initfn; + k->vendor_id = PCI_VENDOR_ID_QEMU; + k->device_id = PCI_DEVICE_ID_QEMU_VGA; + k->class_id = PCI_CLASS_DISPLAY_OTHER; + dc->vmsd = &vmstate_vga_pci; + dc->props = secondary_pci_properties; + dc->reset = pci_secondary_vga_reset; +} + static const TypeInfo vga_info = { .name = "VGA", .parent = TYPE_PCI_DEVICE, @@ -208,9 +330,17 @@ static const TypeInfo vga_info = { .class_init = vga_class_init, }; +static const TypeInfo secondary_info = { + .name = "secondary-vga", + .parent = TYPE_PCI_DEVICE, + .instance_size = sizeof(PCIVGAState), + .class_init = secondary_class_init, +}; + static void vga_register_types(void) { type_register_static(&vga_info); + type_register_static(&secondary_info); } type_init(vga_register_types) diff --git a/hw/display/vga.c b/hw/display/vga.c index 063319d34d..52eaf05659 100644 --- a/hw/display/vga.c +++ b/hw/display/vga.c @@ -136,43 +136,24 @@ static const uint32_t mask16[16] = { #define PAT(x) cbswap_32(x) #endif -static const uint32_t dmask16[16] = { - PAT(0x00000000), - PAT(0x000000ff), - PAT(0x0000ff00), - PAT(0x0000ffff), - PAT(0x00ff0000), - PAT(0x00ff00ff), - PAT(0x00ffff00), - PAT(0x00ffffff), - PAT(0xff000000), - PAT(0xff0000ff), - PAT(0xff00ff00), - PAT(0xff00ffff), - PAT(0xffff0000), - PAT(0xffff00ff), - PAT(0xffffff00), - PAT(0xffffffff), -}; - -static const uint32_t dmask4[4] = { - PAT(0x00000000), - PAT(0x0000ffff), - PAT(0xffff0000), - PAT(0xffffffff), -}; - static uint32_t expand4[256]; static uint16_t expand2[256]; static uint8_t expand4to8[16]; static void vga_update_memory_access(VGACommonState *s) { - MemoryRegion *region, *old_region = s->chain4_alias; hwaddr base, offset, size; - s->chain4_alias = NULL; + if (s->legacy_address_space == NULL) { + return; + } + if (s->has_chain4_alias) { + memory_region_del_subregion(s->legacy_address_space, &s->chain4_alias); + object_unparent(OBJECT(&s->chain4_alias)); + s->has_chain4_alias = false; + s->plane_updated = 0xf; + } if ((s->sr[VGA_SEQ_PLANE_WRITE] & VGA_SR02_ALL_PLANES) == VGA_SR02_ALL_PLANES && s->sr[VGA_SEQ_MEMORY_MODE] & VGA_SR04_CHN_4M) { offset = 0; @@ -197,18 +178,11 @@ static void vga_update_memory_access(VGACommonState *s) break; } base += isa_mem_base; - region = g_malloc(sizeof(*region)); - memory_region_init_alias(region, memory_region_owner(&s->vram), + memory_region_init_alias(&s->chain4_alias, memory_region_owner(&s->vram), "vga.chain4", &s->vram, offset, size); memory_region_add_subregion_overlap(s->legacy_address_space, base, - region, 2); - s->chain4_alias = region; - } - if (old_region) { - memory_region_del_subregion(s->legacy_address_space, old_region); - memory_region_destroy(old_region); - g_free(old_region); - s->plane_updated = 0xf; + &s->chain4_alias, 2); + s->has_chain4_alias = true; } } @@ -576,6 +550,93 @@ void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val) } } +/* + * Sanity check vbe register writes. + * + * As we don't have a way to signal errors to the guest in the bochs + * dispi interface we'll go adjust the registers to the closest valid + * value. + */ +static void vbe_fixup_regs(VGACommonState *s) +{ + uint16_t *r = s->vbe_regs; + uint32_t bits, linelength, maxy, offset; + + if (!(r[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) { + /* vbe is turned off -- nothing to do */ + return; + } + + /* check depth */ + switch (r[VBE_DISPI_INDEX_BPP]) { + case 4: + case 8: + case 16: + case 24: + case 32: + bits = r[VBE_DISPI_INDEX_BPP]; + break; + case 15: + bits = 16; + break; + default: + bits = r[VBE_DISPI_INDEX_BPP] = 8; + break; + } + + /* check width */ + r[VBE_DISPI_INDEX_XRES] &= ~7u; + if (r[VBE_DISPI_INDEX_XRES] == 0) { + r[VBE_DISPI_INDEX_XRES] = 8; + } + if (r[VBE_DISPI_INDEX_XRES] > VBE_DISPI_MAX_XRES) { + r[VBE_DISPI_INDEX_XRES] = VBE_DISPI_MAX_XRES; + } + r[VBE_DISPI_INDEX_VIRT_WIDTH] &= ~7u; + if (r[VBE_DISPI_INDEX_VIRT_WIDTH] > VBE_DISPI_MAX_XRES) { + r[VBE_DISPI_INDEX_VIRT_WIDTH] = VBE_DISPI_MAX_XRES; + } + if (r[VBE_DISPI_INDEX_VIRT_WIDTH] < r[VBE_DISPI_INDEX_XRES]) { + r[VBE_DISPI_INDEX_VIRT_WIDTH] = r[VBE_DISPI_INDEX_XRES]; + } + + /* check height */ + linelength = r[VBE_DISPI_INDEX_VIRT_WIDTH] * bits / 8; + maxy = s->vbe_size / linelength; + if (r[VBE_DISPI_INDEX_YRES] == 0) { + r[VBE_DISPI_INDEX_YRES] = 1; + } + if (r[VBE_DISPI_INDEX_YRES] > VBE_DISPI_MAX_YRES) { + r[VBE_DISPI_INDEX_YRES] = VBE_DISPI_MAX_YRES; + } + if (r[VBE_DISPI_INDEX_YRES] > maxy) { + r[VBE_DISPI_INDEX_YRES] = maxy; + } + + /* check offset */ + if (r[VBE_DISPI_INDEX_X_OFFSET] > VBE_DISPI_MAX_XRES) { + r[VBE_DISPI_INDEX_X_OFFSET] = VBE_DISPI_MAX_XRES; + } + if (r[VBE_DISPI_INDEX_Y_OFFSET] > VBE_DISPI_MAX_YRES) { + r[VBE_DISPI_INDEX_Y_OFFSET] = VBE_DISPI_MAX_YRES; + } + offset = r[VBE_DISPI_INDEX_X_OFFSET] * bits / 8; + offset += r[VBE_DISPI_INDEX_Y_OFFSET] * linelength; + if (offset + r[VBE_DISPI_INDEX_YRES] * linelength > s->vbe_size) { + r[VBE_DISPI_INDEX_Y_OFFSET] = 0; + offset = r[VBE_DISPI_INDEX_X_OFFSET] * bits / 8; + if (offset + r[VBE_DISPI_INDEX_YRES] * linelength > s->vbe_size) { + r[VBE_DISPI_INDEX_X_OFFSET] = 0; + offset = 0; + } + } + + /* update vga state */ + r[VBE_DISPI_INDEX_VIRT_HEIGHT] = maxy; + s->vbe_line_offset = linelength; + s->vbe_start_addr = offset / 4; +} + static uint32_t vbe_ioport_read_index(void *opaque, uint32_t addr) { VGACommonState *s = opaque; @@ -610,7 +671,7 @@ uint32_t vbe_ioport_read_data(void *opaque, uint32_t addr) val = s->vbe_regs[s->vbe_index]; } } else if (s->vbe_index == VBE_DISPI_INDEX_VIDEO_MEMORY_64K) { - val = s->vram_size / (64 * 1024); + val = s->vbe_size / (64 * 1024); } else { val = 0; } @@ -645,22 +706,13 @@ void vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val) } break; case VBE_DISPI_INDEX_XRES: - if ((val <= VBE_DISPI_MAX_XRES) && ((val & 7) == 0)) { - s->vbe_regs[s->vbe_index] = val; - } - break; case VBE_DISPI_INDEX_YRES: - if (val <= VBE_DISPI_MAX_YRES) { - s->vbe_regs[s->vbe_index] = val; - } - break; case VBE_DISPI_INDEX_BPP: - if (val == 0) - val = 8; - if (val == 4 || val == 8 || val == 15 || - val == 16 || val == 24 || val == 32) { - s->vbe_regs[s->vbe_index] = val; - } + case VBE_DISPI_INDEX_VIRT_WIDTH: + case VBE_DISPI_INDEX_X_OFFSET: + case VBE_DISPI_INDEX_Y_OFFSET: + s->vbe_regs[s->vbe_index] = val; + vbe_fixup_regs(s); break; case VBE_DISPI_INDEX_BANK: if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) { @@ -677,28 +729,19 @@ void vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val) !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) { int h, shift_control; - s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = - s->vbe_regs[VBE_DISPI_INDEX_XRES]; - s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] = - s->vbe_regs[VBE_DISPI_INDEX_YRES]; + s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = 0; s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0; s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0; + s->vbe_regs[VBE_DISPI_INDEX_ENABLE] |= VBE_DISPI_ENABLED; + vbe_fixup_regs(s); - if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) - s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 1; - else - s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] * - ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); - s->vbe_start_addr = 0; - - /* clear the screen (should be done in BIOS) */ + /* clear the screen */ if (!(val & VBE_DISPI_NOCLEARMEM)) { memset(s->vram_ptr, 0, s->vbe_regs[VBE_DISPI_INDEX_YRES] * s->vbe_line_offset); } - /* we initialize the VGA graphic mode (should be done - in BIOS) */ + /* we initialize the VGA graphic mode */ /* graphic mode + memory map 1 */ s->gr[VGA_GFX_MISC] = (s->gr[VGA_GFX_MISC] & ~0x0c) | 0x04 | VGA_GR06_GRAPHICS_MODE; @@ -731,47 +774,12 @@ void vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val) (shift_control << 5); s->cr[VGA_CRTC_MAX_SCAN] &= ~0x9f; /* no double scan */ } else { - /* XXX: the bios should do that */ s->bank_offset = 0; } s->dac_8bit = (val & VBE_DISPI_8BIT_DAC) > 0; s->vbe_regs[s->vbe_index] = val; vga_update_memory_access(s); break; - case VBE_DISPI_INDEX_VIRT_WIDTH: - { - int w, h, line_offset; - - if (val < s->vbe_regs[VBE_DISPI_INDEX_XRES]) - return; - w = val; - if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) - line_offset = w >> 1; - else - line_offset = w * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); - h = s->vram_size / line_offset; - /* XXX: support weird bochs semantics ? */ - if (h < s->vbe_regs[VBE_DISPI_INDEX_YRES]) - return; - s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = w; - s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] = h; - s->vbe_line_offset = line_offset; - } - break; - case VBE_DISPI_INDEX_X_OFFSET: - case VBE_DISPI_INDEX_Y_OFFSET: - { - int x; - s->vbe_regs[s->vbe_index] = val; - s->vbe_start_addr = s->vbe_line_offset * s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET]; - x = s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET]; - if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) - s->vbe_start_addr += x >> 1; - else - s->vbe_start_addr += x * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); - s->vbe_start_addr >>= 2; - } - break; default: break; } @@ -970,95 +978,10 @@ void vga_mem_writeb(VGACommonState *s, hwaddr addr, uint32_t val) } } -typedef void vga_draw_glyph8_func(uint8_t *d, int linesize, - const uint8_t *font_ptr, int h, - uint32_t fgcol, uint32_t bgcol); -typedef void vga_draw_glyph9_func(uint8_t *d, int linesize, - const uint8_t *font_ptr, int h, - uint32_t fgcol, uint32_t bgcol, int dup9); typedef void vga_draw_line_func(VGACommonState *s1, uint8_t *d, const uint8_t *s, int width); -#define DEPTH 8 -#include "vga_template.h" - -#define DEPTH 15 -#include "vga_template.h" - -#define BGR_FORMAT -#define DEPTH 15 -#include "vga_template.h" - -#define DEPTH 16 -#include "vga_template.h" - -#define BGR_FORMAT -#define DEPTH 16 -#include "vga_template.h" - -#define DEPTH 32 -#include "vga_template.h" - -#define BGR_FORMAT -#define DEPTH 32 -#include "vga_template.h" - -static unsigned int rgb_to_pixel8_dup(unsigned int r, unsigned int g, unsigned b) -{ - unsigned int col; - col = rgb_to_pixel8(r, g, b); - col |= col << 8; - col |= col << 16; - return col; -} - -static unsigned int rgb_to_pixel15_dup(unsigned int r, unsigned int g, unsigned b) -{ - unsigned int col; - col = rgb_to_pixel15(r, g, b); - col |= col << 16; - return col; -} - -static unsigned int rgb_to_pixel15bgr_dup(unsigned int r, unsigned int g, - unsigned int b) -{ - unsigned int col; - col = rgb_to_pixel15bgr(r, g, b); - col |= col << 16; - return col; -} - -static unsigned int rgb_to_pixel16_dup(unsigned int r, unsigned int g, unsigned b) -{ - unsigned int col; - col = rgb_to_pixel16(r, g, b); - col |= col << 16; - return col; -} - -static unsigned int rgb_to_pixel16bgr_dup(unsigned int r, unsigned int g, - unsigned int b) -{ - unsigned int col; - col = rgb_to_pixel16bgr(r, g, b); - col |= col << 16; - return col; -} - -static unsigned int rgb_to_pixel32_dup(unsigned int r, unsigned int g, unsigned b) -{ - unsigned int col; - col = rgb_to_pixel32(r, g, b); - return col; -} - -static unsigned int rgb_to_pixel32bgr_dup(unsigned int r, unsigned int g, unsigned b) -{ - unsigned int col; - col = rgb_to_pixel32bgr(r, g, b); - return col; -} +#include "vga-helpers.h" /* return true if the palette was modified */ static int update_palette16(VGACommonState *s) @@ -1076,9 +999,9 @@ static int update_palette16(VGACommonState *s) v = ((s->ar[VGA_ATC_COLOR_PAGE] & 0xc) << 4) | (v & 0x3f); } v = v * 3; - col = s->rgb_to_pixel(c6_to_8(s->palette[v]), - c6_to_8(s->palette[v + 1]), - c6_to_8(s->palette[v + 2])); + col = rgb_to_pixel32(c6_to_8(s->palette[v]), + c6_to_8(s->palette[v + 1]), + c6_to_8(s->palette[v + 2])); if (col != palette[i]) { full_update = 1; palette[i] = col; @@ -1098,13 +1021,13 @@ static int update_palette256(VGACommonState *s) v = 0; for(i = 0; i < 256; i++) { if (s->dac_8bit) { - col = s->rgb_to_pixel(s->palette[v], - s->palette[v + 1], - s->palette[v + 2]); + col = rgb_to_pixel32(s->palette[v], + s->palette[v + 1], + s->palette[v + 2]); } else { - col = s->rgb_to_pixel(c6_to_8(s->palette[v]), - c6_to_8(s->palette[v + 1]), - c6_to_8(s->palette[v + 2])); + col = rgb_to_pixel32(c6_to_8(s->palette[v]), + c6_to_8(s->palette[v + 1]), + c6_to_8(s->palette[v + 2])); } if (col != palette[i]) { full_update = 1; @@ -1166,56 +1089,6 @@ static int update_basic_params(VGACommonState *s) return full_update; } -#define NB_DEPTHS 7 - -static inline int get_depth_index(DisplaySurface *s) -{ - switch (surface_bits_per_pixel(s)) { - default: - case 8: - return 0; - case 15: - return 1; - case 16: - return 2; - case 32: - if (is_surface_bgr(s)) { - return 4; - } else { - return 3; - } - } -} - -static vga_draw_glyph8_func * const vga_draw_glyph8_table[NB_DEPTHS] = { - vga_draw_glyph8_8, - vga_draw_glyph8_16, - vga_draw_glyph8_16, - vga_draw_glyph8_32, - vga_draw_glyph8_32, - vga_draw_glyph8_16, - vga_draw_glyph8_16, -}; - -static vga_draw_glyph8_func * const vga_draw_glyph16_table[NB_DEPTHS] = { - vga_draw_glyph16_8, - vga_draw_glyph16_16, - vga_draw_glyph16_16, - vga_draw_glyph16_32, - vga_draw_glyph16_32, - vga_draw_glyph16_16, - vga_draw_glyph16_16, -}; - -static vga_draw_glyph9_func * const vga_draw_glyph9_table[NB_DEPTHS] = { - vga_draw_glyph9_8, - vga_draw_glyph9_16, - vga_draw_glyph9_16, - vga_draw_glyph9_32, - vga_draw_glyph9_32, - vga_draw_glyph9_16, - vga_draw_glyph9_16, -}; static const uint8_t cursor_glyph[32 * 4] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, @@ -1267,18 +1140,6 @@ static void vga_get_text_resolution(VGACommonState *s, int *pwidth, int *pheight *pcheight = cheight; } -typedef unsigned int rgb_to_pixel_dup_func(unsigned int r, unsigned int g, unsigned b); - -static rgb_to_pixel_dup_func * const rgb_to_pixel_dup_table[NB_DEPTHS] = { - rgb_to_pixel8_dup, - rgb_to_pixel15_dup, - rgb_to_pixel16_dup, - rgb_to_pixel32_dup, - rgb_to_pixel32bgr_dup, - rgb_to_pixel15bgr_dup, - rgb_to_pixel16bgr_dup, -}; - /* * Text mode update * Missing: @@ -1295,11 +1156,9 @@ static void vga_draw_text(VGACommonState *s, int full_update) uint32_t offset, fgcol, bgcol, v, cursor_offset; uint8_t *d1, *d, *src, *dest, *cursor_ptr; const uint8_t *font_ptr, *font_base[2]; - int dup9, line_offset, depth_index; + int dup9, line_offset; uint32_t *palette; uint32_t *ch_attr_ptr; - vga_draw_glyph8_func *vga_draw_glyph8; - vga_draw_glyph9_func *vga_draw_glyph9; int64_t now = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL); /* compute font data address (in plane 2) */ @@ -1317,7 +1176,7 @@ static void vga_draw_text(VGACommonState *s, int full_update) s->font_offsets[1] = offset; full_update = 1; } - if (s->plane_updated & (1 << 2) || s->chain4_alias) { + if (s->plane_updated & (1 << 2) || s->has_chain4_alias) { /* if the plane 2 was modified since the last display, it indicates the font may have been modified */ s->plane_updated = 0; @@ -1351,8 +1210,6 @@ static void vga_draw_text(VGACommonState *s, int full_update) s->last_cw = cw; full_update = 1; } - s->rgb_to_pixel = - rgb_to_pixel_dup_table[get_depth_index(surface)]; full_update |= update_palette16(s); palette = s->last_palette; x_incr = cw * surface_bytes_per_pixel(surface); @@ -1386,13 +1243,6 @@ static void vga_draw_text(VGACommonState *s, int full_update) s->cursor_visible_phase = !s->cursor_visible_phase; } - depth_index = get_depth_index(surface); - if (cw == 16) - vga_draw_glyph8 = vga_draw_glyph16_table[depth_index]; - else - vga_draw_glyph8 = vga_draw_glyph8_table[depth_index]; - vga_draw_glyph9 = vga_draw_glyph9_table[depth_index]; - dest = surface_data(surface); linesize = surface_stride(surface); ch_attr_ptr = s->last_ch_attr; @@ -1422,7 +1272,10 @@ static void vga_draw_text(VGACommonState *s, int full_update) font_ptr += 32 * 4 * ch; bgcol = palette[cattr >> 4]; fgcol = palette[cattr & 0x0f]; - if (cw != 9) { + if (cw == 16) { + vga_draw_glyph16(d1, linesize, + font_ptr, cheight, fgcol, bgcol); + } else if (cw != 9) { vga_draw_glyph8(d1, linesize, font_ptr, cheight, fgcol, bgcol); } else { @@ -1447,7 +1300,10 @@ static void vga_draw_text(VGACommonState *s, int full_update) if (line_last >= line_start && line_start < cheight) { h = line_last - line_start + 1; d = d1 + linesize * line_start; - if (cw != 9) { + if (cw == 16) { + vga_draw_glyph16(d, linesize, + cursor_glyph, h, fgcol, bgcol); + } else if (cw != 9) { vga_draw_glyph8(d, linesize, cursor_glyph, h, fgcol, bgcol); } else { @@ -1482,93 +1338,32 @@ enum { VGA_DRAW_LINE4D2, VGA_DRAW_LINE8D2, VGA_DRAW_LINE8, - VGA_DRAW_LINE15, - VGA_DRAW_LINE16, - VGA_DRAW_LINE24, - VGA_DRAW_LINE32, + VGA_DRAW_LINE15_LE, + VGA_DRAW_LINE16_LE, + VGA_DRAW_LINE24_LE, + VGA_DRAW_LINE32_LE, + VGA_DRAW_LINE15_BE, + VGA_DRAW_LINE16_BE, + VGA_DRAW_LINE24_BE, + VGA_DRAW_LINE32_BE, VGA_DRAW_LINE_NB, }; -static vga_draw_line_func * const vga_draw_line_table[NB_DEPTHS * VGA_DRAW_LINE_NB] = { - vga_draw_line2_8, - vga_draw_line2_16, - vga_draw_line2_16, - vga_draw_line2_32, - vga_draw_line2_32, - vga_draw_line2_16, - vga_draw_line2_16, - - vga_draw_line2d2_8, - vga_draw_line2d2_16, - vga_draw_line2d2_16, - vga_draw_line2d2_32, - vga_draw_line2d2_32, - vga_draw_line2d2_16, - vga_draw_line2d2_16, - - vga_draw_line4_8, - vga_draw_line4_16, - vga_draw_line4_16, - vga_draw_line4_32, - vga_draw_line4_32, - vga_draw_line4_16, - vga_draw_line4_16, - - vga_draw_line4d2_8, - vga_draw_line4d2_16, - vga_draw_line4d2_16, - vga_draw_line4d2_32, - vga_draw_line4d2_32, - vga_draw_line4d2_16, - vga_draw_line4d2_16, - - vga_draw_line8d2_8, - vga_draw_line8d2_16, - vga_draw_line8d2_16, - vga_draw_line8d2_32, - vga_draw_line8d2_32, - vga_draw_line8d2_16, - vga_draw_line8d2_16, - - vga_draw_line8_8, - vga_draw_line8_16, - vga_draw_line8_16, - vga_draw_line8_32, - vga_draw_line8_32, - vga_draw_line8_16, - vga_draw_line8_16, - - vga_draw_line15_8, - vga_draw_line15_15, - vga_draw_line15_16, - vga_draw_line15_32, - vga_draw_line15_32bgr, - vga_draw_line15_15bgr, - vga_draw_line15_16bgr, - - vga_draw_line16_8, - vga_draw_line16_15, - vga_draw_line16_16, - vga_draw_line16_32, - vga_draw_line16_32bgr, - vga_draw_line16_15bgr, - vga_draw_line16_16bgr, - - vga_draw_line24_8, - vga_draw_line24_15, - vga_draw_line24_16, - vga_draw_line24_32, - vga_draw_line24_32bgr, - vga_draw_line24_15bgr, - vga_draw_line24_16bgr, - - vga_draw_line32_8, - vga_draw_line32_15, - vga_draw_line32_16, - vga_draw_line32_32, - vga_draw_line32_32bgr, - vga_draw_line32_15bgr, - vga_draw_line32_16bgr, +static vga_draw_line_func * const vga_draw_line_table[VGA_DRAW_LINE_NB] = { + vga_draw_line2, + vga_draw_line2d2, + vga_draw_line4, + vga_draw_line4d2, + vga_draw_line8d2, + vga_draw_line8, + vga_draw_line15_le, + vga_draw_line16_le, + vga_draw_line24_le, + vga_draw_line32_le, + vga_draw_line15_be, + vga_draw_line16_be, + vga_draw_line24_be, + vga_draw_line32_be, }; static int vga_get_bpp(VGACommonState *s) @@ -1640,11 +1435,11 @@ static void vga_draw_graphic(VGACommonState *s, int full_update) int disp_width, multi_scan, multi_run; uint8_t *d; uint32_t v, addr1, addr; - vga_draw_line_func *vga_draw_line; -#if defined(HOST_WORDS_BIGENDIAN) == defined(TARGET_WORDS_BIGENDIAN) - static const bool byteswap = false; + vga_draw_line_func *vga_draw_line = NULL; +#ifdef HOST_WORDS_BIGENDIAN + bool byteswap = !s->big_endian_fb; #else - static const bool byteswap = true; + bool byteswap = s->big_endian_fb; #endif full_update |= update_basic_params(s); @@ -1687,11 +1482,14 @@ static void vga_draw_graphic(VGACommonState *s, int full_update) if (s->line_offset != s->last_line_offset || disp_width != s->last_width || height != s->last_height || - s->last_depth != depth) { + s->last_depth != depth || + s->last_byteswap != byteswap) { if (depth == 32 || (depth == 16 && !byteswap)) { + pixman_format_code_t format = + qemu_default_pixman_format(depth, !byteswap); surface = qemu_create_displaysurface_from(disp_width, - height, depth, s->line_offset, - s->vram_ptr + (s->start_addr * 4), byteswap); + height, format, s->line_offset, + s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } else { qemu_console_resize(s->con, disp_width, height); @@ -1703,19 +1501,19 @@ static void vga_draw_graphic(VGACommonState *s, int full_update) s->last_height = height; s->last_line_offset = s->line_offset; s->last_depth = depth; + s->last_byteswap = byteswap; full_update = 1; } else if (is_buffer_shared(surface) && (full_update || surface_data(surface) != s->vram_ptr + (s->start_addr * 4))) { + pixman_format_code_t format = + qemu_default_pixman_format(depth, !byteswap); surface = qemu_create_displaysurface_from(disp_width, - height, depth, s->line_offset, - s->vram_ptr + (s->start_addr * 4), byteswap); + height, format, s->line_offset, + s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } - s->rgb_to_pixel = - rgb_to_pixel_dup_table[get_depth_index(surface)]; - if (shift_control == 0) { full_update |= update_palette16(s); if (s->sr[VGA_SEQ_CLOCK_MODE] & 8) { @@ -1746,25 +1544,24 @@ static void vga_draw_graphic(VGACommonState *s, int full_update) bits = 8; break; case 15: - v = VGA_DRAW_LINE15; + v = s->big_endian_fb ? VGA_DRAW_LINE15_BE : VGA_DRAW_LINE15_LE; bits = 16; break; case 16: - v = VGA_DRAW_LINE16; + v = s->big_endian_fb ? VGA_DRAW_LINE16_BE : VGA_DRAW_LINE16_LE; bits = 16; break; case 24: - v = VGA_DRAW_LINE24; + v = s->big_endian_fb ? VGA_DRAW_LINE24_BE : VGA_DRAW_LINE24_LE; bits = 24; break; case 32: - v = VGA_DRAW_LINE32; + v = s->big_endian_fb ? VGA_DRAW_LINE32_BE : VGA_DRAW_LINE32_LE; bits = 32; break; } } - vga_draw_line = vga_draw_line_table[v * NB_DEPTHS + - get_depth_index(surface)]; + vga_draw_line = vga_draw_line_table[v]; if (!is_buffer_shared(surface) && s->cursor_invalidate) { s->cursor_invalidate(s); @@ -1854,7 +1651,7 @@ static void vga_draw_graphic(VGACommonState *s, int full_update) static void vga_draw_blank(VGACommonState *s, int full_update) { DisplaySurface *surface = qemu_console_surface(s->con); - int i, w, val; + int i, w; uint8_t *d; if (!full_update) @@ -1862,17 +1659,10 @@ static void vga_draw_blank(VGACommonState *s, int full_update) if (s->last_scr_width <= 0 || s->last_scr_height <= 0) return; - s->rgb_to_pixel = - rgb_to_pixel_dup_table[get_depth_index(surface)]; - if (surface_bits_per_pixel(surface) == 8) { - val = s->rgb_to_pixel(0, 0, 0); - } else { - val = 0; - } w = s->last_scr_width * surface_bytes_per_pixel(surface); d = surface_data(surface); for(i = 0; i < s->last_scr_height; i++) { - memset(d, val, w); + memset(d, 0, w); d += surface_stride(surface); } dpy_gfx_update(s->con, 0, 0, @@ -1975,6 +1765,7 @@ void vga_common_reset(VGACommonState *s) s->cursor_start = 0; s->cursor_end = 0; s->cursor_offset = 0; + s->big_endian_fb = s->default_endian_fb; memset(s->invalidated_y_table, '\0', sizeof(s->invalidated_y_table)); memset(s->last_palette, '\0', sizeof(s->last_palette)); memset(s->last_ch_attr, '\0', sizeof(s->last_ch_attr)); @@ -2206,13 +1997,34 @@ static int vga_common_post_load(void *opaque, int version_id) return 0; } +static bool vga_endian_state_needed(void *opaque) +{ + VGACommonState *s = opaque; + + /* + * Only send the endian state if it's different from the + * default one, thus ensuring backward compatibility for + * migration of the common case + */ + return s->default_endian_fb != s->big_endian_fb; +} + +const VMStateDescription vmstate_vga_endian = { + .name = "vga.endian", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_BOOL(big_endian_fb, VGACommonState), + VMSTATE_END_OF_LIST() + } +}; + const VMStateDescription vmstate_vga_common = { .name = "vga", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = vga_common_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(latch, VGACommonState), VMSTATE_UINT8(sr_index, VGACommonState), VMSTATE_PARTIAL_BUFFER(sr, VGACommonState, 8), @@ -2243,6 +2055,14 @@ const VMStateDescription vmstate_vga_common = { VMSTATE_UINT32(vbe_line_offset, VGACommonState), VMSTATE_UINT32(vbe_bank_mask, VGACommonState), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection []) { + { + .vmsd = &vmstate_vga_endian, + .needed = vga_endian_state_needed, + }, { + /* empty */ + } } }; @@ -2252,7 +2072,7 @@ static const GraphicHwOps vga_ops = { .text_update = vga_update_text, }; -void vga_common_init(VGACommonState *s, Object *obj) +void vga_common_init(VGACommonState *s, Object *obj, bool global_vmstate) { int i, j, v, b; @@ -2286,10 +2106,14 @@ void vga_common_init(VGACommonState *s, Object *obj) s->vram_size <<= 1; } s->vram_size_mb = s->vram_size >> 20; + if (!s->vbe_size) { + s->vbe_size = s->vram_size; + } s->is_vbe_vmstate = 1; - memory_region_init_ram(&s->vram, obj, "vga.vram", s->vram_size); - vmstate_register_ram_global(&s->vram); + memory_region_init_ram(&s->vram, obj, "vga.vram", s->vram_size, + &error_abort); + vmstate_register_ram(&s->vram, global_vmstate ? NULL : DEVICE(obj)); xen_register_framebuffer(&s->vram); s->vram_ptr = memory_region_get_ram_ptr(&s->vram); s->get_bpp = vga_get_bpp; @@ -2307,6 +2131,17 @@ void vga_common_init(VGACommonState *s, Object *obj) s->update_retrace_info = vga_precise_update_retrace_info; break; } + + /* + * Set default fb endian based on target, could probably be turned + * into a device attribute set by the machine/platform to remove + * all target endian dependencies from this file. + */ +#ifdef TARGET_WORDS_BIGENDIAN + s->default_endian_fb = true; +#else + s->default_endian_fb = false; +#endif vga_dirty_log_start(s); } @@ -2351,8 +2186,6 @@ void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space, { MemoryRegion *vga_io_memory; const MemoryRegionPortio *vga_ports, *vbe_ports; - PortioList *vga_port_list = g_new(PortioList, 1); - PortioList *vbe_port_list = g_new(PortioList, 1); qemu_register_reset(vga_reset, s); @@ -2367,13 +2200,13 @@ void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space, 1); memory_region_set_coalescing(vga_io_memory); if (init_vga_ports) { - portio_list_init(vga_port_list, obj, vga_ports, s, "vga"); - portio_list_set_flush_coalesced(vga_port_list); - portio_list_add(vga_port_list, address_space_io, 0x3b0); + portio_list_init(&s->vga_port_list, obj, vga_ports, s, "vga"); + portio_list_set_flush_coalesced(&s->vga_port_list); + portio_list_add(&s->vga_port_list, address_space_io, 0x3b0); } if (vbe_ports) { - portio_list_init(vbe_port_list, obj, vbe_ports, s, "vbe"); - portio_list_add(vbe_port_list, address_space_io, 0x1ce); + portio_list_init(&s->vbe_port_list, obj, vbe_ports, s, "vbe"); + portio_list_add(&s->vbe_port_list, address_space_io, 0x1ce); } } diff --git a/hw/display/vga_int.h b/hw/display/vga_int.h index e6418906a7..ed69e064a8 100644 --- a/hw/display/vga_int.h +++ b/hw/display/vga_int.h @@ -93,8 +93,10 @@ typedef struct VGACommonState { MemoryRegion vram_vbe; uint32_t vram_size; uint32_t vram_size_mb; /* property */ + uint32_t vbe_size; uint32_t latch; - MemoryRegion *chain4_alias; + bool has_chain4_alias; + MemoryRegion chain4_alias; uint8_t sr_index; uint8_t sr[256]; uint8_t gr_index; @@ -124,6 +126,8 @@ typedef struct VGACommonState { void (*get_resolution)(struct VGACommonState *s, int *pwidth, int *pheight); + PortioList vga_port_list; + PortioList vbe_port_list; /* bochs vbe state */ uint16_t vbe_index; uint16_t vbe_regs[VBE_DISPI_INDEX_NB]; @@ -146,15 +150,16 @@ typedef struct VGACommonState { uint32_t last_width, last_height; /* in chars or pixels */ uint32_t last_scr_width, last_scr_height; /* in pixels */ uint32_t last_depth; /* in bits */ + bool last_byteswap; uint8_t cursor_start, cursor_end; bool cursor_visible_phase; int64_t cursor_blink_time; uint32_t cursor_offset; - unsigned int (*rgb_to_pixel)(unsigned int r, - unsigned int g, unsigned b); const GraphicHwOps *hw_ops; bool full_update_text; bool full_update_gfx; + bool big_endian_fb; + bool default_endian_fb; /* hardware mouse cursor support */ uint32_t invalidated_y_table[VGA_MAX_HEIGHT / 32]; void (*cursor_invalidate)(struct VGACommonState *s); @@ -177,7 +182,7 @@ static inline int c6_to_8(int v) return (v << 2) | (b << 1) | b; } -void vga_common_init(VGACommonState *s, Object *obj); +void vga_common_init(VGACommonState *s, Object *obj, bool global_vmstate); void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space, MemoryRegion *address_space_io, bool init_vga_ports); MemoryRegion *vga_init_io(VGACommonState *s, Object *obj, diff --git a/hw/display/vmware_vga.c b/hw/display/vmware_vga.c index 6ae3348deb..1751f19793 100644 --- a/hw/display/vmware_vga.c +++ b/hw/display/vmware_vga.c @@ -292,47 +292,74 @@ enum { SVGA_CURSOR_ON_RESTORE_TO_FB = 3, }; -static inline void vmsvga_update_rect(struct vmsvga_state_s *s, - int x, int y, int w, int h) +static inline bool vmsvga_verify_rect(DisplaySurface *surface, + const char *name, + int x, int y, int w, int h) { - DisplaySurface *surface = qemu_console_surface(s->vga.con); - int line; - int bypl; - int width; - int start; - uint8_t *src; - uint8_t *dst; - if (x < 0) { - fprintf(stderr, "%s: update x was < 0 (%d)\n", __func__, x); - w += x; - x = 0; + fprintf(stderr, "%s: x was < 0 (%d)\n", name, x); + return false; + } + if (x > SVGA_MAX_WIDTH) { + fprintf(stderr, "%s: x was > %d (%d)\n", name, SVGA_MAX_WIDTH, x); + return false; } if (w < 0) { - fprintf(stderr, "%s: update w was < 0 (%d)\n", __func__, w); - w = 0; + fprintf(stderr, "%s: w was < 0 (%d)\n", name, w); + return false; + } + if (w > SVGA_MAX_WIDTH) { + fprintf(stderr, "%s: w was > %d (%d)\n", name, SVGA_MAX_WIDTH, w); + return false; } if (x + w > surface_width(surface)) { - fprintf(stderr, "%s: update width too large x: %d, w: %d\n", - __func__, x, w); - x = MIN(x, surface_width(surface)); - w = surface_width(surface) - x; + fprintf(stderr, "%s: width was > %d (x: %d, w: %d)\n", + name, surface_width(surface), x, w); + return false; } if (y < 0) { - fprintf(stderr, "%s: update y was < 0 (%d)\n", __func__, y); - h += y; - y = 0; + fprintf(stderr, "%s: y was < 0 (%d)\n", name, y); + return false; + } + if (y > SVGA_MAX_HEIGHT) { + fprintf(stderr, "%s: y was > %d (%d)\n", name, SVGA_MAX_HEIGHT, y); + return false; } if (h < 0) { - fprintf(stderr, "%s: update h was < 0 (%d)\n", __func__, h); - h = 0; + fprintf(stderr, "%s: h was < 0 (%d)\n", name, h); + return false; + } + if (h > SVGA_MAX_HEIGHT) { + fprintf(stderr, "%s: h was > %d (%d)\n", name, SVGA_MAX_HEIGHT, h); + return false; } if (y + h > surface_height(surface)) { - fprintf(stderr, "%s: update height too large y: %d, h: %d\n", - __func__, y, h); - y = MIN(y, surface_height(surface)); - h = surface_height(surface) - y; + fprintf(stderr, "%s: update height > %d (y: %d, h: %d)\n", + name, surface_height(surface), y, h); + return false; + } + + return true; +} + +static inline void vmsvga_update_rect(struct vmsvga_state_s *s, + int x, int y, int w, int h) +{ + DisplaySurface *surface = qemu_console_surface(s->vga.con); + int line; + int bypl; + int width; + int start; + uint8_t *src; + uint8_t *dst; + + if (!vmsvga_verify_rect(surface, __func__, x, y, w, h)) { + /* go for a fullscreen update as fallback */ + x = 0; + y = 0; + w = surface_width(surface); + h = surface_height(surface); } bypl = surface_stride(surface); @@ -377,7 +404,7 @@ static inline void vmsvga_update_rect_flush(struct vmsvga_state_s *s) } #ifdef HW_RECT_ACCEL -static inline void vmsvga_copy_rect(struct vmsvga_state_s *s, +static inline int vmsvga_copy_rect(struct vmsvga_state_s *s, int x0, int y0, int x1, int y1, int w, int h) { DisplaySurface *surface = qemu_console_surface(s->vga.con); @@ -388,6 +415,13 @@ static inline void vmsvga_copy_rect(struct vmsvga_state_s *s, int line = h; uint8_t *ptr[2]; + if (!vmsvga_verify_rect(surface, "vmsvga_copy_rect/src", x0, y0, w, h)) { + return -1; + } + if (!vmsvga_verify_rect(surface, "vmsvga_copy_rect/dst", x1, y1, w, h)) { + return -1; + } + if (y1 > y0) { ptr[0] = vram + bypp * x0 + bypl * (y0 + h - 1); ptr[1] = vram + bypp * x1 + bypl * (y1 + h - 1); @@ -403,11 +437,12 @@ static inline void vmsvga_copy_rect(struct vmsvga_state_s *s, } vmsvga_update_rect_delayed(s, x1, y1, w, h); + return 0; } #endif #ifdef HW_FILL_ACCEL -static inline void vmsvga_fill_rect(struct vmsvga_state_s *s, +static inline int vmsvga_fill_rect(struct vmsvga_state_s *s, uint32_t c, int x, int y, int w, int h) { DisplaySurface *surface = qemu_console_surface(s->vga.con); @@ -420,6 +455,10 @@ static inline void vmsvga_fill_rect(struct vmsvga_state_s *s, uint8_t *src; uint8_t col[4]; + if (!vmsvga_verify_rect(surface, __func__, x, y, w, h)) { + return -1; + } + col[0] = c; col[1] = c >> 8; col[2] = c >> 16; @@ -444,6 +483,7 @@ static inline void vmsvga_fill_rect(struct vmsvga_state_s *s, } vmsvga_update_rect_delayed(s, x, y, w, h); + return 0; } #endif @@ -576,12 +616,12 @@ static void vmsvga_fifo_run(struct vmsvga_state_s *s) width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_FILL_ACCEL - vmsvga_fill_rect(s, colour, x, y, width, height); - break; -#else + if (vmsvga_fill_rect(s, colour, x, y, width, height) == 0) { + break; + } +#endif args = 0; goto badcmd; -#endif case SVGA_CMD_RECT_COPY: len -= 7; @@ -596,12 +636,12 @@ static void vmsvga_fifo_run(struct vmsvga_state_s *s) width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_RECT_ACCEL - vmsvga_copy_rect(s, x, y, dx, dy, width, height); - break; -#else + if (vmsvga_copy_rect(s, x, y, dx, dy, width, height) == 0) { + break; + } +#endif args = 0; goto badcmd; -#endif case SVGA_CMD_DEFINE_CURSOR: len -= 8; @@ -863,7 +903,7 @@ static uint32_t vmsvga_value_read(void *opaque, uint32_t address) break; case SVGA_REG_CURSOR_Y: - ret = s->cursor.x; + ret = s->cursor.y; break; case SVGA_REG_CURSOR_ON: @@ -1052,10 +1092,12 @@ static inline void vmsvga_check_size(struct vmsvga_state_s *s) s->new_height != surface_height(surface) || s->new_depth != surface_bits_per_pixel(surface)) { int stride = (s->new_depth * s->new_width) / 8; + pixman_format_code_t format = + qemu_default_pixman_format(s->new_depth, true); trace_vmware_setmode(s->new_width, s->new_height, s->new_depth); surface = qemu_create_displaysurface_from(s->new_width, s->new_height, - s->new_depth, stride, - s->vga.vram_ptr, false); + format, stride, + s->vga.vram_ptr); dpy_gfx_replace_surface(s->vga.con, surface); s->invalidated = 1; } @@ -1152,9 +1194,8 @@ static const VMStateDescription vmstate_vmware_vga_internal = { .name = "vmware_vga_internal", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = vmsvga_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32_EQUAL(new_depth, struct vmsvga_state_s), VMSTATE_INT32(enable, struct vmsvga_state_s), VMSTATE_INT32(config, struct vmsvga_state_s), @@ -1179,8 +1220,7 @@ static const VMStateDescription vmstate_vmware_vga = { .name = "vmware_vga", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, struct pci_vmsvga_state_s), VMSTATE_STRUCT(chip, struct pci_vmsvga_state_s, 0, vmstate_vmware_vga_internal, struct vmsvga_state_s), @@ -1203,11 +1243,12 @@ static void vmsvga_init(DeviceState *dev, struct vmsvga_state_s *s, s->vga.con = graphic_console_init(dev, 0, &vmsvga_ops, s); s->fifo_size = SVGA_FIFO_SIZE; - memory_region_init_ram(&s->fifo_ram, NULL, "vmsvga.fifo", s->fifo_size); + memory_region_init_ram(&s->fifo_ram, NULL, "vmsvga.fifo", s->fifo_size, + &error_abort); vmstate_register_ram_global(&s->fifo_ram); s->fifo_ptr = memory_region_get_ram_ptr(&s->fifo_ram); - vga_common_init(&s->vga, OBJECT(dev)); + vga_common_init(&s->vga, OBJECT(dev), true); vga_init(&s->vga, OBJECT(dev), address_space, io, true); vmstate_register(NULL, 0, &vmstate_vga_common, &s->vga); s->new_depth = 32; diff --git a/hw/display/xenfb.c b/hw/display/xenfb.c index 032eb7a9a5..8a61e959a6 100644 --- a/hw/display/xenfb.c +++ b/hw/display/xenfb.c @@ -93,10 +93,12 @@ struct XenFB { static int common_bind(struct common *c) { - int mfn; + uint64_t mfn; - if (xenstore_read_fe_int(&c->xendev, "page-ref", &mfn) == -1) + if (xenstore_read_fe_uint64(&c->xendev, "page-ref", &mfn) == -1) return -1; + assert(mfn == (xen_pfn_t)mfn); + if (xenstore_read_fe_int(&c->xendev, "event-channel", &c->xendev.remote_port) == -1) return -1; @@ -107,7 +109,7 @@ static int common_bind(struct common *c) return -1; xen_be_bind_evtchn(&c->xendev); - xen_be_printf(&c->xendev, 1, "ring mfn %d, remote-port %d, local-port %d\n", + xen_be_printf(&c->xendev, 1, "ring mfn %"PRIx64", remote-port %d, local-port %d\n", mfn, c->xendev.remote_port, c->xendev.local_port); return 0; @@ -409,7 +411,7 @@ static void input_event(struct XenDevice *xendev) /* -------------------------------------------------------------------- */ -static void xenfb_copy_mfns(int mode, int count, unsigned long *dst, void *src) +static void xenfb_copy_mfns(int mode, int count, xen_pfn_t *dst, void *src) { uint32_t *src32 = src; uint64_t *src64 = src; @@ -424,8 +426,8 @@ static int xenfb_map_fb(struct XenFB *xenfb) struct xenfb_page *page = xenfb->c.page; char *protocol = xenfb->c.xendev.protocol; int n_fbdirs; - unsigned long *pgmfns = NULL; - unsigned long *fbmfns = NULL; + xen_pfn_t *pgmfns = NULL; + xen_pfn_t *fbmfns = NULL; void *map, *pd; int mode, ret = -1; @@ -483,8 +485,8 @@ static int xenfb_map_fb(struct XenFB *xenfb) n_fbdirs = xenfb->fbpages * mode / 8; n_fbdirs = (n_fbdirs + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE; - pgmfns = g_malloc0(sizeof(unsigned long) * n_fbdirs); - fbmfns = g_malloc0(sizeof(unsigned long) * xenfb->fbpages); + pgmfns = g_malloc0(sizeof(xen_pfn_t) * n_fbdirs); + fbmfns = g_malloc0(sizeof(xen_pfn_t) * xenfb->fbpages); xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd); map = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom, @@ -711,15 +713,17 @@ static void xenfb_update(void *opaque) /* resize if needed */ if (xenfb->do_resize) { + pixman_format_code_t format; + xenfb->do_resize = 0; switch (xenfb->depth) { case 16: case 32: /* console.c supported depth -> buffer can be used directly */ + format = qemu_default_pixman_format(xenfb->depth, true); surface = qemu_create_displaysurface_from - (xenfb->width, xenfb->height, xenfb->depth, - xenfb->row_stride, xenfb->pixels + xenfb->offset, - false); + (xenfb->width, xenfb->height, format, + xenfb->row_stride, xenfb->pixels + xenfb->offset); break; default: /* we must convert stuff */ diff --git a/hw/dma/i82374.c b/hw/dma/i82374.c index dc7a767ee2..b8ad2e64ec 100644 --- a/hw/dma/i82374.c +++ b/hw/dma/i82374.c @@ -39,6 +39,7 @@ do { fprintf(stderr, "i82374 ERROR: " fmt , ## __VA_ARGS__); } while (0) typedef struct I82374State { uint8_t commands[8]; qemu_irq out; + PortioList port_list; } I82374State; static const VMStateDescription vmstate_i82374 = { @@ -137,10 +138,10 @@ static void i82374_isa_realize(DeviceState *dev, Error **errp) { ISAi82374State *isa = I82374(dev); I82374State *s = &isa->state; - PortioList *port_list = g_new(PortioList, 1); - portio_list_init(port_list, OBJECT(isa), i82374_portio_list, s, "i82374"); - portio_list_add(port_list, isa_address_space_io(&isa->parent_obj), + portio_list_init(&s->port_list, OBJECT(isa), i82374_portio_list, s, + "i82374"); + portio_list_add(&s->port_list, isa_address_space_io(&isa->parent_obj), isa->iobase); i82374_realize(s, errp); diff --git a/hw/dma/i8257.c b/hw/dma/i8257.c index 44903723d3..a414029bea 100644 --- a/hw/dma/i8257.c +++ b/hw/dma/i8257.c @@ -24,6 +24,7 @@ #include "hw/hw.h" #include "hw/isa/isa.h" #include "qemu/main-loop.h" +#include "trace.h" /* #define DEBUG_DMA */ @@ -473,8 +474,7 @@ static void dma_reset(void *opaque) static int dma_phony_handler (void *opaque, int nchan, int dma_pos, int dma_len) { - dolog ("unregistered DMA channel used nchan=%d dma_pos=%d dma_len=%d\n", - nchan, dma_pos, dma_len); + trace_i8257_unregistered_dma(nchan, dma_pos, dma_len); return dma_pos; } @@ -551,8 +551,7 @@ static const VMStateDescription vmstate_dma_regs = { .name = "dma_regs", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32_ARRAY(now, struct dma_regs, 2), VMSTATE_UINT16_ARRAY(base, struct dma_regs, 2), VMSTATE_UINT8(mode, struct dma_regs), @@ -575,9 +574,8 @@ static const VMStateDescription vmstate_dma = { .name = "dma", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = dma_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(command, struct dma_cont), VMSTATE_UINT8(mask, struct dma_cont), VMSTATE_UINT8(flip_flop, struct dma_cont), diff --git a/hw/dma/omap_dma.c b/hw/dma/omap_dma.c index 0e8cccd27f..756a87acb8 100644 --- a/hw/dma/omap_dma.c +++ b/hw/dma/omap_dma.c @@ -973,7 +973,7 @@ static int omap_dma_ch_reg_write(struct omap_dma_s *s, case 0x22: /* DMA_COLOR_U */ ch->color &= 0xffff; - ch->color |= value << 16; + ch->color |= (uint32_t)value << 16; break; case 0x24: /* DMA_CCR2 */ @@ -1043,7 +1043,7 @@ static int omap_dma_3_2_lcd_write(struct omap_dma_lcd_channel_s *s, int offset, case 0xbca: /* TOP_B1_U */ s->src_f1_top &= 0x0000ffff; - s->src_f1_top |= value << 16; + s->src_f1_top |= (uint32_t)value << 16; break; case 0xbcc: /* BOT_B1_L */ @@ -1265,7 +1265,7 @@ static int omap_dma_3_1_lcd_write(struct omap_dma_lcd_channel_s *s, int offset, case 0x304: /* SYS_DMA_LCD_TOP_F1_U */ s->src_f1_top &= 0x0000ffff; - s->src_f1_top |= value << 16; + s->src_f1_top |= (uint32_t)value << 16; break; case 0x306: /* SYS_DMA_LCD_BOT_F1_L */ @@ -1275,7 +1275,7 @@ static int omap_dma_3_1_lcd_write(struct omap_dma_lcd_channel_s *s, int offset, case 0x308: /* SYS_DMA_LCD_BOT_F1_U */ s->src_f1_bottom &= 0x0000ffff; - s->src_f1_bottom |= value << 16; + s->src_f1_bottom |= (uint32_t)value << 16; break; case 0x30a: /* SYS_DMA_LCD_TOP_F2_L */ @@ -1285,7 +1285,7 @@ static int omap_dma_3_1_lcd_write(struct omap_dma_lcd_channel_s *s, int offset, case 0x30c: /* SYS_DMA_LCD_TOP_F2_U */ s->src_f2_top &= 0x0000ffff; - s->src_f2_top |= value << 16; + s->src_f2_top |= (uint32_t)value << 16; break; case 0x30e: /* SYS_DMA_LCD_BOT_F2_L */ @@ -1295,7 +1295,7 @@ static int omap_dma_3_1_lcd_write(struct omap_dma_lcd_channel_s *s, int offset, case 0x310: /* SYS_DMA_LCD_BOT_F2_U */ s->src_f2_bottom &= 0x0000ffff; - s->src_f2_bottom |= value << 16; + s->src_f2_bottom |= (uint32_t)value << 16; break; default: @@ -1660,7 +1660,7 @@ struct soc_dma_s *omap_dma_init(hwaddr base, qemu_irq *irqs, } omap_dma_setcaps(s); - omap_clk_adduser(s->clk, qemu_allocate_irqs(omap_dma_clk_update, s, 1)[0]); + omap_clk_adduser(s->clk, qemu_allocate_irq(omap_dma_clk_update, s, 0)); omap_dma_reset(s->dma); omap_dma_clk_update(s, 0, 1); @@ -2082,7 +2082,7 @@ struct soc_dma_s *omap_dma4_init(hwaddr base, qemu_irq *irqs, s->intr_update = omap_dma_interrupts_4_update; omap_dma_setcaps(s); - omap_clk_adduser(s->clk, qemu_allocate_irqs(omap_dma_clk_update, s, 1)[0]); + omap_clk_adduser(s->clk, qemu_allocate_irq(omap_dma_clk_update, s, 0)); omap_dma_reset(s->dma); omap_dma_clk_update(s, 0, !!s->dma->freq); diff --git a/hw/dma/pl330.c b/hw/dma/pl330.c index 608a58c47d..6b6eaaeb47 100644 --- a/hw/dma/pl330.c +++ b/hw/dma/pl330.c @@ -138,7 +138,6 @@ static const VMStateDescription vmstate_pl330_chan = { .name = "pl330_chan", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(src, PL330Chan), VMSTATE_UINT32(dst, PL330Chan), @@ -170,7 +169,6 @@ static const VMStateDescription vmstate_pl330_fifo = { .name = "pl330_chan", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_VBUFFER_UINT32(buf, PL330Fifo, 1, NULL, 0, buf_size), VMSTATE_VBUFFER_UINT32(tag, PL330Fifo, 1, NULL, 0, buf_size), @@ -195,7 +193,6 @@ static const VMStateDescription vmstate_pl330_queue_entry = { .name = "pl330_queue_entry", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(addr, PL330QueueEntry), VMSTATE_UINT32(len, PL330QueueEntry), @@ -218,7 +215,6 @@ static const VMStateDescription vmstate_pl330_queue = { .name = "pl330_queue", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT_VARRAY_UINT32(queue, PL330Queue, queue_size, 1, vmstate_pl330_queue_entry, PL330QueueEntry), @@ -279,7 +275,6 @@ static const VMStateDescription vmstate_pl330 = { .name = "pl330", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT(manager, PL330State, 0, vmstate_pl330_chan, PL330Chan), VMSTATE_STRUCT_VARRAY_UINT32(chan, PL330State, num_chnls, 0, diff --git a/hw/dma/pxa2xx_dma.c b/hw/dma/pxa2xx_dma.c index c013abb313..d4501fb4cb 100644 --- a/hw/dma/pxa2xx_dma.c +++ b/hw/dma/pxa2xx_dma.c @@ -514,7 +514,6 @@ static VMStateDescription vmstate_pxa2xx_dma_chan = { .name = "pxa2xx_dma_chan", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(descr, PXA2xxDMAChannel), VMSTATE_UINT32(src, PXA2xxDMAChannel), @@ -530,7 +529,6 @@ static VMStateDescription vmstate_pxa2xx_dma = { .name = "pxa2xx_dma", .version_id = 1, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_UNUSED_TEST(is_version_0, 4), VMSTATE_UINT32(stopintr, PXA2xxDMAState), diff --git a/hw/dma/sparc32_dma.c b/hw/dma/sparc32_dma.c index eac338f1bc..e6a453ce5c 100644 --- a/hw/dma/sparc32_dma.c +++ b/hw/dma/sparc32_dma.c @@ -263,8 +263,7 @@ static const VMStateDescription vmstate_dma = { .name ="sparc32_dma", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(dmaregs, DMAState, DMA_REGS), VMSTATE_END_OF_LIST() } diff --git a/hw/dma/sun4m_iommu.c b/hw/dma/sun4m_iommu.c index 899d454353..ec7c2efcd9 100644 --- a/hw/dma/sun4m_iommu.c +++ b/hw/dma/sun4m_iommu.c @@ -327,8 +327,7 @@ static const VMStateDescription vmstate_iommu = { .name ="iommu", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, IOMMUState, IOMMU_NREGS), VMSTATE_UINT64(iostart, IOMMUState), VMSTATE_END_OF_LIST() diff --git a/hw/dma/xilinx_axidma.c b/hw/dma/xilinx_axidma.c index 14b887bfa8..d06002dde8 100644 --- a/hw/dma/xilinx_axidma.c +++ b/hw/dma/xilinx_axidma.c @@ -157,11 +157,6 @@ static inline int stream_running(struct Stream *s) return s->regs[R_DMACR] & DMACR_RUNSTOP; } -static inline int stream_halted(struct Stream *s) -{ - return s->regs[R_DMASR] & DMASR_HALTED; -} - static inline int stream_idle(struct Stream *s) { return !!(s->regs[R_DMASR] & DMASR_IDLE); @@ -534,40 +529,42 @@ static void xilinx_axidma_realize(DeviceState *dev, Error **errp) XilinxAXIDMAStreamSlave *ds = XILINX_AXI_DMA_DATA_STREAM(&s->rx_data_dev); XilinxAXIDMAStreamSlave *cs = XILINX_AXI_DMA_CONTROL_STREAM( &s->rx_control_dev); - Error *local_errp = NULL; + Error *local_err = NULL; object_property_add_link(OBJECT(ds), "dma", TYPE_XILINX_AXI_DMA, (Object **)&ds->dma, object_property_allow_set_link, OBJ_PROP_LINK_UNREF_ON_RELEASE, - &local_errp); + &local_err); object_property_add_link(OBJECT(cs), "dma", TYPE_XILINX_AXI_DMA, (Object **)&cs->dma, object_property_allow_set_link, OBJ_PROP_LINK_UNREF_ON_RELEASE, - &local_errp); - if (local_errp) { + &local_err); + if (local_err) { goto xilinx_axidma_realize_fail; } - object_property_set_link(OBJECT(ds), OBJECT(s), "dma", &local_errp); - object_property_set_link(OBJECT(cs), OBJECT(s), "dma", &local_errp); - if (local_errp) { + object_property_set_link(OBJECT(ds), OBJECT(s), "dma", &local_err); + object_property_set_link(OBJECT(cs), OBJECT(s), "dma", &local_err); + if (local_err) { goto xilinx_axidma_realize_fail; } int i; for (i = 0; i < 2; i++) { - s->streams[i].nr = i; - s->streams[i].bh = qemu_bh_new(timer_hit, &s->streams[i]); - s->streams[i].ptimer = ptimer_init(s->streams[i].bh); - ptimer_set_freq(s->streams[i].ptimer, s->freqhz); + struct Stream *st = &s->streams[i]; + + st->nr = i; + st->bh = qemu_bh_new(timer_hit, st); + st->ptimer = ptimer_init(st->bh); + ptimer_set_freq(st->ptimer, s->freqhz); } return; xilinx_axidma_realize_fail: if (!*errp) { - *errp = local_errp; + *errp = local_err; } } diff --git a/hw/gpio/Makefile.objs b/hw/gpio/Makefile.objs index 2c8b51f09a..1abcf17988 100644 --- a/hw/gpio/Makefile.objs +++ b/hw/gpio/Makefile.objs @@ -2,5 +2,6 @@ common-obj-$(CONFIG_MAX7310) += max7310.o common-obj-$(CONFIG_PL061) += pl061.o common-obj-$(CONFIG_PUV3) += puv3_gpio.o common-obj-$(CONFIG_ZAURUS) += zaurus.o +common-obj-$(CONFIG_E500) += mpc8xxx.o obj-$(CONFIG_OMAP) += omap_gpio.o diff --git a/hw/gpio/max7310.c b/hw/gpio/max7310.c index cfcd89ca2b..7fbf313ce8 100644 --- a/hw/gpio/max7310.c +++ b/hw/gpio/max7310.c @@ -152,8 +152,7 @@ static const VMStateDescription vmstate_max7310 = { .name = "max7310", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(i2c_command_byte, MAX7310State), VMSTATE_INT32(len, MAX7310State), VMSTATE_UINT8(level, MAX7310State), diff --git a/hw/gpio/mpc8xxx.c b/hw/gpio/mpc8xxx.c new file mode 100644 index 0000000000..1aeaaaaf03 --- /dev/null +++ b/hw/gpio/mpc8xxx.c @@ -0,0 +1,217 @@ +/* + * GPIO Controller for a lot of Freescale SoCs + * + * Copyright (C) 2014 Freescale Semiconductor, Inc. All rights reserved. + * + * Author: Alexander Graf, <agraf@suse.de> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "hw/sysbus.h" + +#define TYPE_MPC8XXX_GPIO "mpc8xxx_gpio" +#define MPC8XXX_GPIO(obj) OBJECT_CHECK(MPC8XXXGPIOState, (obj), TYPE_MPC8XXX_GPIO) + +typedef struct MPC8XXXGPIOState { + SysBusDevice parent_obj; + + MemoryRegion iomem; + qemu_irq irq; + qemu_irq out[32]; + + uint32_t dir; + uint32_t odr; + uint32_t dat; + uint32_t ier; + uint32_t imr; + uint32_t icr; +} MPC8XXXGPIOState; + +static const VMStateDescription vmstate_mpc8xxx_gpio = { + .name = "mpc8xxx_gpio", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT32(dir, MPC8XXXGPIOState), + VMSTATE_UINT32(odr, MPC8XXXGPIOState), + VMSTATE_UINT32(dat, MPC8XXXGPIOState), + VMSTATE_UINT32(ier, MPC8XXXGPIOState), + VMSTATE_UINT32(imr, MPC8XXXGPIOState), + VMSTATE_UINT32(icr, MPC8XXXGPIOState), + VMSTATE_END_OF_LIST() + } +}; + +static void mpc8xxx_gpio_update(MPC8XXXGPIOState *s) +{ + qemu_set_irq(s->irq, !!(s->ier & s->imr)); +} + +static uint64_t mpc8xxx_gpio_read(void *opaque, hwaddr offset, + unsigned size) +{ + MPC8XXXGPIOState *s = (MPC8XXXGPIOState *)opaque; + + if (size != 4) { + /* All registers are 32bit */ + return 0; + } + + switch (offset) { + case 0x0: /* Direction */ + return s->dir; + case 0x4: /* Open Drain */ + return s->odr; + case 0x8: /* Data */ + return s->dat; + case 0xC: /* Interrupt Event */ + return s->ier; + case 0x10: /* Interrupt Mask */ + return s->imr; + case 0x14: /* Interrupt Control */ + return s->icr; + default: + return 0; + } +} + +static void mpc8xxx_write_data(MPC8XXXGPIOState *s, uint32_t new_data) +{ + uint32_t old_data = s->dat; + uint32_t diff = old_data ^ new_data; + int i; + + for (i = 0; i < 32; i++) { + uint32_t mask = 0x80000000 >> i; + if (!(diff & mask)) { + continue; + } + + if (s->dir & mask) { + /* Output */ + qemu_set_irq(s->out[i], (new_data & mask) != 0); + } + } + + s->dat = new_data; +} + +static void mpc8xxx_gpio_write(void *opaque, hwaddr offset, + uint64_t value, unsigned size) +{ + MPC8XXXGPIOState *s = (MPC8XXXGPIOState *)opaque; + + if (size != 4) { + /* All registers are 32bit */ + return; + } + + switch (offset) { + case 0x0: /* Direction */ + s->dir = value; + break; + case 0x4: /* Open Drain */ + s->odr = value; + break; + case 0x8: /* Data */ + mpc8xxx_write_data(s, value); + break; + case 0xC: /* Interrupt Event */ + s->ier &= ~value; + break; + case 0x10: /* Interrupt Mask */ + s->imr = value; + break; + case 0x14: /* Interrupt Control */ + s->icr = value; + break; + } + + mpc8xxx_gpio_update(s); +} + +static void mpc8xxx_gpio_reset(MPC8XXXGPIOState *s) +{ + s->dir = 0; + s->odr = 0; + s->dat = 0; + s->ier = 0; + s->imr = 0; + s->icr = 0; +} + +static void mpc8xxx_gpio_set_irq(void * opaque, int irq, int level) +{ + MPC8XXXGPIOState *s = (MPC8XXXGPIOState *)opaque; + uint32_t mask; + + mask = 0x80000000 >> irq; + if ((s->dir & mask) == 0) { + uint32_t old_value = s->dat & mask; + + s->dat &= ~mask; + if (level) + s->dat |= mask; + + if (!(s->icr & irq) || (old_value && !level)) { + s->ier |= mask; + } + + mpc8xxx_gpio_update(s); + } +} + +static const MemoryRegionOps mpc8xxx_gpio_ops = { + .read = mpc8xxx_gpio_read, + .write = mpc8xxx_gpio_write, + .endianness = DEVICE_BIG_ENDIAN, +}; + +static int mpc8xxx_gpio_initfn(SysBusDevice *sbd) +{ + DeviceState *dev = DEVICE(sbd); + MPC8XXXGPIOState *s = MPC8XXX_GPIO(dev); + + memory_region_init_io(&s->iomem, OBJECT(s), &mpc8xxx_gpio_ops, s, "mpc8xxx_gpio", 0x1000); + sysbus_init_mmio(sbd, &s->iomem); + sysbus_init_irq(sbd, &s->irq); + qdev_init_gpio_in(dev, mpc8xxx_gpio_set_irq, 32); + qdev_init_gpio_out(dev, s->out, 32); + mpc8xxx_gpio_reset(s); + return 0; +} + +static void mpc8xxx_gpio_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); + + k->init = mpc8xxx_gpio_initfn; + dc->vmsd = &vmstate_mpc8xxx_gpio; +} + +static const TypeInfo mpc8xxx_gpio_info = { + .name = TYPE_MPC8XXX_GPIO, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(MPC8XXXGPIOState), + .class_init = mpc8xxx_gpio_class_init, +}; + +static void mpc8xxx_gpio_register_types(void) +{ + type_register_static(&mpc8xxx_gpio_info); +} + +type_init(mpc8xxx_gpio_register_types) diff --git a/hw/gpio/pl061.c b/hw/gpio/pl061.c index dd4ea293e2..bd03e99975 100644 --- a/hw/gpio/pl061.c +++ b/hw/gpio/pl061.c @@ -37,7 +37,8 @@ typedef struct PL061State { MemoryRegion iomem; uint32_t locked; uint32_t data; - uint32_t old_data; + uint32_t old_out_data; + uint32_t old_in_data; uint32_t dir; uint32_t isense; uint32_t ibe; @@ -63,12 +64,13 @@ typedef struct PL061State { static const VMStateDescription vmstate_pl061 = { .name = "pl061", - .version_id = 2, - .minimum_version_id = 1, + .version_id = 3, + .minimum_version_id = 3, .fields = (VMStateField[]) { VMSTATE_UINT32(locked, PL061State), VMSTATE_UINT32(data, PL061State), - VMSTATE_UINT32(old_data, PL061State), + VMSTATE_UINT32(old_out_data, PL061State), + VMSTATE_UINT32(old_in_data, PL061State), VMSTATE_UINT32(dir, PL061State), VMSTATE_UINT32(isense, PL061State), VMSTATE_UINT32(ibe, PL061State), @@ -98,23 +100,52 @@ static void pl061_update(PL061State *s) uint8_t out; int i; + DPRINTF("dir = %d, data = %d\n", s->dir, s->data); + /* Outputs float high. */ /* FIXME: This is board dependent. */ out = (s->data & s->dir) | ~s->dir; - changed = s->old_data ^ out; - if (!changed) - return; + changed = s->old_out_data ^ out; + if (changed) { + s->old_out_data = out; + for (i = 0; i < 8; i++) { + mask = 1 << i; + if (changed & mask) { + DPRINTF("Set output %d = %d\n", i, (out & mask) != 0); + qemu_set_irq(s->out[i], (out & mask) != 0); + } + } + } - s->old_data = out; - for (i = 0; i < 8; i++) { - mask = 1 << i; - if (changed & mask) { - DPRINTF("Set output %d = %d\n", i, (out & mask) != 0); - qemu_set_irq(s->out[i], (out & mask) != 0); + /* Inputs */ + changed = (s->old_in_data ^ s->data) & ~s->dir; + if (changed) { + s->old_in_data = s->data; + for (i = 0; i < 8; i++) { + mask = 1 << i; + if (changed & mask) { + DPRINTF("Changed input %d = %d\n", i, (s->data & mask) != 0); + + if (!(s->isense & mask)) { + /* Edge interrupt */ + if (s->ibe & mask) { + /* Any edge triggers the interrupt */ + s->istate |= mask; + } else { + /* Edge is selected by IEV */ + s->istate |= ~(s->data ^ s->iev) & mask; + } + } + } } } - /* FIXME: Implement input interrupts. */ + /* Level interrupt */ + s->istate |= ~(s->data ^ s->iev) & s->isense; + + DPRINTF("istate = %02X\n", s->istate); + + qemu_set_irq(s->irq, (s->istate & s->im) != 0); } static uint64_t pl061_read(void *opaque, hwaddr offset, diff --git a/hw/gpio/zaurus.c b/hw/gpio/zaurus.c index dc79a8baa6..94083424f8 100644 --- a/hw/gpio/zaurus.c +++ b/hw/gpio/zaurus.c @@ -203,18 +203,27 @@ static bool is_version_0 (void *opaque, int version_id) return version_id == 0; } +static bool vmstate_scoop_validate(void *opaque, int version_id) +{ + ScoopInfo *s = opaque; + + return !(s->prev_level & 0xffff0000) && + !(s->gpio_level & 0xffff0000) && + !(s->gpio_dir & 0xffff0000); +} + static const VMStateDescription vmstate_scoop_regs = { .name = "scoop", .version_id = 1, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = scoop_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(status, ScoopInfo), VMSTATE_UINT16(power, ScoopInfo), VMSTATE_UINT32(gpio_level, ScoopInfo), VMSTATE_UINT32(gpio_dir, ScoopInfo), VMSTATE_UINT32(prev_level, ScoopInfo), + VMSTATE_VALIDATE("irq levels are 16 bit", vmstate_scoop_validate), VMSTATE_UINT16(mcr, ScoopInfo), VMSTATE_UINT16(cdr, ScoopInfo), VMSTATE_UINT16(ccr, ScoopInfo), diff --git a/hw/i2c/core.c b/hw/i2c/core.c index efd8b4fafb..5a64026347 100644 --- a/hw/i2c/core.c +++ b/hw/i2c/core.c @@ -52,10 +52,9 @@ static const VMStateDescription vmstate_i2c_bus = { .name = "i2c_bus", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = i2c_bus_pre_save, .post_load = i2c_bus_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(saved_address, I2CBus), VMSTATE_END_OF_LIST() } @@ -194,9 +193,8 @@ const VMStateDescription vmstate_i2c_slave = { .name = "I2CSlave", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = i2c_slave_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(address, I2CSlave), VMSTATE_END_OF_LIST() } diff --git a/hw/i2c/pm_smbus.c b/hw/i2c/pm_smbus.c index 9f50067735..ce1713d267 100644 --- a/hw/i2c/pm_smbus.c +++ b/hw/i2c/pm_smbus.c @@ -60,59 +60,78 @@ static void smb_transaction(PMSMBus *s) uint8_t cmd = s->smb_cmd; uint8_t addr = s->smb_addr >> 1; I2CBus *bus = s->smbus; + int ret; SMBUS_DPRINTF("SMBus trans addr=0x%02x prot=0x%02x\n", addr, prot); /* Transaction isn't exec if STS_DEV_ERR bit set */ if ((s->smb_stat & STS_DEV_ERR) != 0) { - goto error; - } + goto error; + } switch(prot) { case 0x0: - smbus_quick_command(bus, addr, read); - s->smb_stat |= STS_BYTE_DONE | STS_INTR; - break; + ret = smbus_quick_command(bus, addr, read); + goto done; case 0x1: if (read) { - s->smb_data0 = smbus_receive_byte(bus, addr); + ret = smbus_receive_byte(bus, addr); + goto data8; } else { - smbus_send_byte(bus, addr, cmd); + ret = smbus_send_byte(bus, addr, cmd); + goto done; } - s->smb_stat |= STS_BYTE_DONE | STS_INTR; - break; case 0x2: if (read) { - s->smb_data0 = smbus_read_byte(bus, addr, cmd); + ret = smbus_read_byte(bus, addr, cmd); + goto data8; } else { - smbus_write_byte(bus, addr, cmd, s->smb_data0); + ret = smbus_write_byte(bus, addr, cmd, s->smb_data0); + goto done; } - s->smb_stat |= STS_BYTE_DONE | STS_INTR; break; case 0x3: if (read) { - uint16_t val; - val = smbus_read_word(bus, addr, cmd); - s->smb_data0 = val; - s->smb_data1 = val >> 8; + ret = smbus_read_word(bus, addr, cmd); + goto data16; } else { - smbus_write_word(bus, addr, cmd, (s->smb_data1 << 8) | s->smb_data0); + ret = smbus_write_word(bus, addr, cmd, (s->smb_data1 << 8) | s->smb_data0); + goto done; } - s->smb_stat |= STS_BYTE_DONE | STS_INTR; break; case 0x5: if (read) { - s->smb_data0 = smbus_read_block(bus, addr, cmd, s->smb_data); + ret = smbus_read_block(bus, addr, cmd, s->smb_data); + goto data8; } else { - smbus_write_block(bus, addr, cmd, s->smb_data, s->smb_data0); + ret = smbus_write_block(bus, addr, cmd, s->smb_data, s->smb_data0); + goto done; } - s->smb_stat |= STS_BYTE_DONE | STS_INTR; break; default: goto error; } + abort(); + +data16: + if (ret < 0) { + goto error; + } + s->smb_data1 = ret >> 8; +data8: + if (ret < 0) { + goto error; + } + s->smb_data0 = ret; +done: + if (ret < 0) { + goto error; + } + s->smb_stat |= STS_BYTE_DONE | STS_INTR; return; - error: +error: s->smb_stat |= STS_DEV_ERR; + return; + } static void smb_ioport_writeb(void *opaque, hwaddr addr, uint64_t val, @@ -120,7 +139,8 @@ static void smb_ioport_writeb(void *opaque, hwaddr addr, uint64_t val, { PMSMBus *s = opaque; - SMBUS_DPRINTF("SMB writeb port=0x%04x val=0x%02x\n", addr, val); + SMBUS_DPRINTF("SMB writeb port=0x%04" HWADDR_PRIx + " val=0x%02" PRIx64 "\n", addr, val); switch(addr) { case SMBHSTSTS: s->smb_stat = (~(val & 0xff)) & s->smb_stat; @@ -187,7 +207,7 @@ static uint64_t smb_ioport_readb(void *opaque, hwaddr addr, unsigned width) val = 0; break; } - SMBUS_DPRINTF("SMB readb port=0x%04x val=0x%02x\n", addr, val); + SMBUS_DPRINTF("SMB readb port=0x%04" HWADDR_PRIx " val=0x%02x\n", addr, val); return val; } diff --git a/hw/i2c/smbus.c b/hw/i2c/smbus.c index 3febf3c258..6e27ae8bd2 100644 --- a/hw/i2c/smbus.c +++ b/hw/i2c/smbus.c @@ -208,34 +208,44 @@ static int smbus_device_init(I2CSlave *i2c) } /* Master device commands. */ -void smbus_quick_command(I2CBus *bus, uint8_t addr, int read) +int smbus_quick_command(I2CBus *bus, uint8_t addr, int read) { - i2c_start_transfer(bus, addr, read); + if (i2c_start_transfer(bus, addr, read)) { + return -1; + } i2c_end_transfer(bus); + return 0; } -uint8_t smbus_receive_byte(I2CBus *bus, uint8_t addr) +int smbus_receive_byte(I2CBus *bus, uint8_t addr) { uint8_t data; - i2c_start_transfer(bus, addr, 1); + if (i2c_start_transfer(bus, addr, 1)) { + return -1; + } data = i2c_recv(bus); i2c_nack(bus); i2c_end_transfer(bus); return data; } -void smbus_send_byte(I2CBus *bus, uint8_t addr, uint8_t data) +int smbus_send_byte(I2CBus *bus, uint8_t addr, uint8_t data) { - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, data); i2c_end_transfer(bus); + return 0; } -uint8_t smbus_read_byte(I2CBus *bus, uint8_t addr, uint8_t command) +int smbus_read_byte(I2CBus *bus, uint8_t addr, uint8_t command) { uint8_t data; - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_start_transfer(bus, addr, 1); data = i2c_recv(bus); @@ -244,18 +254,23 @@ uint8_t smbus_read_byte(I2CBus *bus, uint8_t addr, uint8_t command) return data; } -void smbus_write_byte(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t data) +int smbus_write_byte(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t data) { - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_send(bus, data); i2c_end_transfer(bus); + return 0; } -uint16_t smbus_read_word(I2CBus *bus, uint8_t addr, uint8_t command) +int smbus_read_word(I2CBus *bus, uint8_t addr, uint8_t command) { uint16_t data; - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_start_transfer(bus, addr, 1); data = i2c_recv(bus); @@ -265,13 +280,16 @@ uint16_t smbus_read_word(I2CBus *bus, uint8_t addr, uint8_t command) return data; } -void smbus_write_word(I2CBus *bus, uint8_t addr, uint8_t command, uint16_t data) +int smbus_write_word(I2CBus *bus, uint8_t addr, uint8_t command, uint16_t data) { - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_send(bus, data & 0xff); i2c_send(bus, data >> 8); i2c_end_transfer(bus); + return 0; } int smbus_read_block(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t *data) @@ -279,33 +297,41 @@ int smbus_read_block(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t *data) int len; int i; - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_start_transfer(bus, addr, 1); len = i2c_recv(bus); - if (len > 32) + if (len > 32) { len = 0; - for (i = 0; i < len; i++) + } + for (i = 0; i < len; i++) { data[i] = i2c_recv(bus); + } i2c_nack(bus); i2c_end_transfer(bus); return len; } -void smbus_write_block(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t *data, - int len) +int smbus_write_block(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t *data, + int len) { int i; if (len > 32) len = 32; - i2c_start_transfer(bus, addr, 0); + if (i2c_start_transfer(bus, addr, 0)) { + return -1; + } i2c_send(bus, command); i2c_send(bus, len); - for (i = 0; i < len; i++) + for (i = 0; i < len; i++) { i2c_send(bus, data[i]); + } i2c_end_transfer(bus); + return 0; } static void smbus_device_class_init(ObjectClass *klass, void *data) diff --git a/hw/i2c/smbus_eeprom.c b/hw/i2c/smbus_eeprom.c index 86f35c11de..72c09cba6b 100644 --- a/hw/i2c/smbus_eeprom.c +++ b/hw/i2c/smbus_eeprom.c @@ -71,7 +71,7 @@ static void eeprom_write_data(SMBusDevice *dev, uint8_t cmd, uint8_t *buf, int l printf("eeprom_write_byte: addr=0x%02x cmd=0x%02x val=0x%02x\n", dev->i2c.address, cmd, buf[0]); #endif - /* An page write operation is not a valid SMBus command. + /* A page write operation is not a valid SMBus command. It is a block write without a length byte. Fortunately we get the full block anyway. */ /* TODO: Should this set the current location? */ diff --git a/hw/i2c/smbus_ich9.c b/hw/i2c/smbus_ich9.c index 295b62ed29..0803dc4d18 100644 --- a/hw/i2c/smbus_ich9.c +++ b/hw/i2c/smbus_ich9.c @@ -48,7 +48,6 @@ static const VMStateDescription vmstate_ich9_smbus = { .name = "ich9_smb", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, struct ICH9SMBState), VMSTATE_END_OF_LIST() diff --git a/hw/i386/Makefile.objs b/hw/i386/Makefile.objs index 3df1612651..9d419addb4 100644 --- a/hw/i386/Makefile.objs +++ b/hw/i386/Makefile.objs @@ -2,14 +2,17 @@ obj-$(CONFIG_KVM) += kvm/ obj-y += multiboot.o smbios.o obj-y += pc.o pc_piix.o pc_q35.o obj-y += pc_sysfw.o -obj-$(CONFIG_XEN) += xen_domainbuild.o xen_machine_pv.o +obj-y += intel_iommu.o +obj-$(CONFIG_XEN) += ../xenpv/ xen/ obj-y += kvmvapic.o obj-y += acpi-build.o obj-y += bios-linker-loader.o hw/i386/acpi-build.o: hw/i386/acpi-build.c hw/i386/acpi-dsdt.hex \ hw/i386/ssdt-proc.hex hw/i386/ssdt-pcihp.hex hw/i386/ssdt-misc.hex \ - hw/i386/acpi-dsdt.hex hw/i386/q35-acpi-dsdt.hex + hw/i386/acpi-dsdt.hex hw/i386/q35-acpi-dsdt.hex \ + hw/i386/q35-acpi-dsdt.hex hw/i386/ssdt-mem.hex \ + hw/i386/ssdt-tpm.hex iasl-option=$(shell if test -z "`$(1) $(2) 2>&1 > /dev/null`" \ ; then echo "$(2)"; else echo "$(3)"; fi ;) @@ -17,7 +20,7 @@ iasl-option=$(shell if test -z "`$(1) $(2) 2>&1 > /dev/null`" \ ifdef IASL #IASL Present. Generate hex files from .dsl hw/i386/%.hex: $(SRC_PATH)/hw/i386/%.dsl $(SRC_PATH)/scripts/acpi_extract_preprocess.py $(SRC_PATH)/scripts/acpi_extract.py - $(call quiet-command, cpp -P $(QEMU_DGFLAGS) $(QEMU_INCLUDES) $< -o $*.dsl.i.orig, " CPP $(TARGET_DIR)$*.dsl.i.orig") + $(call quiet-command, $(CPP) -x c -P $(QEMU_DGFLAGS) $(QEMU_INCLUDES) $< -o $*.dsl.i.orig, " CPP $(TARGET_DIR)$*.dsl.i.orig") $(call quiet-command, $(PYTHON) $(SRC_PATH)/scripts/acpi_extract_preprocess.py $*.dsl.i.orig > $*.dsl.i, " ACPI_PREPROCESS $(TARGET_DIR)$*.dsl.i") $(call quiet-command, $(IASL) $(call iasl-option,$(IASL),-Pn,) -vs -l -tc -p $* $*.dsl.i $(if $(V), , > /dev/null) 2>&1 ," IASL $(TARGET_DIR)$*.dsl.i") $(call quiet-command, $(PYTHON) $(SRC_PATH)/scripts/acpi_extract.py $*.lst > $*.off, " ACPI_EXTRACT $(TARGET_DIR)$*.off") diff --git a/hw/i386/acpi-build.c b/hw/i386/acpi-build.c index c98df88cd2..b37a397820 100644 --- a/hw/i386/acpi-build.c +++ b/hw/i386/acpi-build.c @@ -25,7 +25,9 @@ #include <glib.h> #include "qemu-common.h" #include "qemu/bitmap.h" +#include "qemu/osdep.h" #include "qemu/range.h" +#include "qemu/error-report.h" #include "hw/pci/pci.h" #include "qom/cpu.h" #include "hw/i386/pc.h" @@ -37,6 +39,9 @@ #include "bios-linker-loader.h" #include "hw/loader.h" #include "hw/isa/isa.h" +#include "hw/acpi/memory_hotplug.h" +#include "sysemu/tpm.h" +#include "hw/acpi/tpm.h" /* Supported chipsets: */ #include "hw/acpi/piix4.h" @@ -44,12 +49,24 @@ #include "hw/i386/ich9.h" #include "hw/pci/pci_bus.h" #include "hw/pci-host/q35.h" +#include "hw/i386/intel_iommu.h" #include "hw/i386/q35-acpi-dsdt.hex" #include "hw/i386/acpi-dsdt.hex" #include "qapi/qmp/qint.h" #include "qom/qom-qobject.h" +#include "exec/ram_addr.h" + +/* These are used to size the ACPI tables for -M pc-i440fx-1.7 and + * -M pc-i440fx-2.0. Even if the actual amount of AML generated grows + * a little bit, there should be plenty of free space since the DSDT + * shrunk by ~1.5k between QEMU 2.0 and QEMU 2.1. + */ +#define ACPI_BUILD_LEGACY_CPU_AML_SIZE 97 +#define ACPI_BUILD_ALIGN_SIZE 0x1000 + +#define ACPI_BUILD_TABLE_SIZE 0x20000 typedef struct AcpiCpuInfo { DECLARE_BITMAP(found_cpus, ACPI_CPU_HOTPLUG_ID_LIMIT); @@ -63,6 +80,7 @@ typedef struct AcpiMcfgInfo { typedef struct AcpiPmInfo { bool s3_disabled; bool s4_disabled; + bool pcihp_bridge_en; uint8_t s4_val; uint16_t sci_int; uint8_t acpi_enable_cmd; @@ -74,6 +92,7 @@ typedef struct AcpiPmInfo { typedef struct AcpiMiscInfo { bool has_hpet; + bool has_tpm; DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX); const unsigned char *dsdt_code; unsigned dsdt_size; @@ -84,6 +103,7 @@ typedef struct AcpiBuildPciBusHotplugState { GArray *device_table; GArray *notify_table; struct AcpiBuildPciBusHotplugState *parent; + bool pcihp_bridge_en; } AcpiBuildPciBusHotplugState; static void acpi_get_dsdt(AcpiMiscInfo *info) @@ -156,18 +176,21 @@ static void acpi_get_pm_info(AcpiPmInfo *pm) } else { pm->s3_disabled = false; } + qobject_decref(o); o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL); if (o) { pm->s4_disabled = qint_get_int(qobject_to_qint(o)); } else { pm->s4_disabled = false; } + qobject_decref(o); o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL); if (o) { pm->s4_val = qint_get_int(qobject_to_qint(o)); } else { pm->s4_val = false; } + qobject_decref(o); /* Fill in mandatory properties */ pm->sci_int = object_property_get_int(obj, ACPI_PM_PROP_SCI_INT, NULL); @@ -184,11 +207,15 @@ static void acpi_get_pm_info(AcpiPmInfo *pm) NULL); pm->gpe0_blk_len = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK_LEN, NULL); + pm->pcihp_bridge_en = + object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support", + NULL); } static void acpi_get_misc_info(AcpiMiscInfo *info) { info->has_hpet = hpet_find(); + info->has_tpm = tpm_find(); info->pvpanic_port = pvpanic_port(); } @@ -223,6 +250,7 @@ static void acpi_get_pci_info(PcPciInfo *info) #define ACPI_BUILD_TABLE_FILE "etc/acpi/tables" #define ACPI_BUILD_RSDP_FILE "etc/acpi/rsdp" +#define ACPI_BUILD_TPMLOG_FILE "etc/tpm/log" static void build_header(GArray *linker, GArray *table_data, @@ -525,6 +553,12 @@ static void fadt_setup(AcpiFadtDescriptorRev1 *fadt, AcpiPmInfo *pm) (1 << ACPI_FADT_F_SLP_BUTTON) | (1 << ACPI_FADT_F_RTC_S4)); fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_USE_PLATFORM_CLOCK); + /* APIC destination mode ("Flat Logical") has an upper limit of 8 CPUs + * For more than 8 CPUs, "Clustered Logical" mode has to be used + */ + if (max_cpus > 8) { + fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_FORCE_APIC_CLUSTER_MODEL); + } } @@ -664,11 +698,20 @@ static inline char acpi_get_hex(uint32_t val) #define ACPI_PCIQXL_SIZEOF (*ssdt_pciqxl_end - *ssdt_pciqxl_start) #define ACPI_PCIQXL_AML (ssdp_pcihp_aml + *ssdt_pciqxl_start) +#include "hw/i386/ssdt-mem.hex" + +/* 0x5B 0x82 DeviceOp PkgLength NameString DimmID */ +#define ACPI_MEM_OFFSET_HEX (*ssdt_mem_name - *ssdt_mem_start + 2) +#define ACPI_MEM_OFFSET_ID (*ssdt_mem_id - *ssdt_mem_start + 7) +#define ACPI_MEM_SIZEOF (*ssdt_mem_end - *ssdt_mem_start) +#define ACPI_MEM_AML (ssdm_mem_aml + *ssdt_mem_start) + #define ACPI_SSDT_SIGNATURE 0x54445353 /* SSDT */ #define ACPI_SSDT_HEADER_LENGTH 36 #include "hw/i386/ssdt-misc.hex" #include "hw/i386/ssdt-pcihp.hex" +#include "hw/i386/ssdt-tpm.hex" static void build_append_notify_method(GArray *device, const char *name, @@ -733,7 +776,7 @@ static void *acpi_set_bsel(PCIBus *bus, void *opaque) unsigned *bsel_alloc = opaque; unsigned *bus_bsel; - if (bus->qbus.allow_hotplug) { + if (qbus_is_hotpluggable(BUS(bus))) { bus_bsel = g_malloc(sizeof *bus_bsel); *bus_bsel = (*bsel_alloc)++; @@ -756,11 +799,13 @@ static void acpi_set_pci_info(void) } static void build_pci_bus_state_init(AcpiBuildPciBusHotplugState *state, - AcpiBuildPciBusHotplugState *parent) + AcpiBuildPciBusHotplugState *parent, + bool pcihp_bridge_en) { state->parent = parent; state->device_table = build_alloc_array(); state->notify_table = build_alloc_array(); + state->pcihp_bridge_en = pcihp_bridge_en; } static void build_pci_bus_state_cleanup(AcpiBuildPciBusHotplugState *state) @@ -774,7 +819,7 @@ static void *build_pci_bus_begin(PCIBus *bus, void *parent_state) AcpiBuildPciBusHotplugState *parent = parent_state; AcpiBuildPciBusHotplugState *child = g_malloc(sizeof *child); - build_pci_bus_state_init(child, parent); + build_pci_bus_state_init(child, parent, parent->pcihp_bridge_en); return child; } @@ -795,6 +840,14 @@ static void build_pci_bus_end(PCIBus *bus, void *bus_state) GArray *method; bool bus_hotplug_support = false; + /* + * Skip bridge subtree creation if bridge hotplug is disabled + * to make acpi tables compatible with legacy machine types. + */ + if (!child->pcihp_bridge_en && bus->parent_dev) { + return; + } + if (bus->parent_dev) { op = 0x82; /* DeviceOp */ build_append_nameseg(bus_table, "S%.02X_", @@ -832,6 +885,7 @@ static void build_pci_bus_end(PCIBus *bus, void *bus_state) PCIDeviceClass *pc; PCIDevice *pdev = bus->devices[i]; int slot = PCI_SLOT(i); + bool bridge_in_acpi; if (!pdev) { continue; @@ -841,7 +895,13 @@ static void build_pci_bus_end(PCIBus *bus, void *bus_state) pc = PCI_DEVICE_GET_CLASS(pdev); dc = DEVICE_GET_CLASS(pdev); - if (pc->class_id == PCI_CLASS_BRIDGE_ISA || pc->is_bridge) { + /* When hotplug for bridges is enabled, bridges are + * described in ACPI separately (see build_pci_bus_end). + * In this case they aren't themselves hot-pluggable. + */ + bridge_in_acpi = pc->is_bridge && child->pcihp_bridge_en; + + if (pc->class_id == PCI_CLASS_BRIDGE_ISA || bridge_in_acpi) { set_bit(slot, slot_device_system); } @@ -853,7 +913,7 @@ static void build_pci_bus_end(PCIBus *bus, void *bus_state) } } - if (!dc->hotpluggable || pc->is_bridge) { + if (!dc->hotpluggable || bridge_in_acpi) { clear_bit(slot, slot_hotplug_enable); } } @@ -973,6 +1033,7 @@ static void build_pci_bus_end(PCIBus *bus, void *bus_state) } } + qobject_decref(bsel); build_free_array(bus_table); build_pci_bus_state_cleanup(child); g_free(child); @@ -999,6 +1060,8 @@ build_ssdt(GArray *table_data, GArray *linker, AcpiCpuInfo *cpu, AcpiPmInfo *pm, AcpiMiscInfo *misc, PcPciInfo *pci, PcGuestInfo *guest_info) { + MachineState *machine = MACHINE(qdev_get_machine()); + uint32_t nr_mem = machine->ram_slots; unsigned acpi_cpus = guest_info->apic_id_limit; int ssdt_start = table_data->len; uint8_t *ssdt_ptr; @@ -1027,6 +1090,9 @@ build_ssdt(GArray *table_data, GArray *linker, ACPI_BUILD_SET_LE(ssdt_ptr, sizeof(ssdp_misc_aml), ssdt_isa_pest[0], 16, misc->pvpanic_port); + ACPI_BUILD_SET_LE(ssdt_ptr, sizeof(ssdp_misc_aml), + ssdt_mctrl_nr_slots[0], 32, nr_mem); + { GArray *sb_scope = build_alloc_array(); uint8_t op = 0x10; /* ScopeOp */ @@ -1080,6 +1146,27 @@ build_ssdt(GArray *table_data, GArray *linker, build_free_array(package); } + if (nr_mem) { + assert(nr_mem <= ACPI_MAX_RAM_SLOTS); + /* build memory devices */ + for (i = 0; i < nr_mem; i++) { + char id[3]; + uint8_t *mem = acpi_data_push(sb_scope, ACPI_MEM_SIZEOF); + + snprintf(id, sizeof(id), "%02X", i); + memcpy(mem, ACPI_MEM_AML, ACPI_MEM_SIZEOF); + memcpy(mem + ACPI_MEM_OFFSET_HEX, id, 2); + memcpy(mem + ACPI_MEM_OFFSET_ID, id, 2); + } + + /* build Method(MEMORY_SLOT_NOTIFY_METHOD, 2) { + * If (LEqual(Arg0, 0x00)) {Notify(MP00, Arg1)} ... + */ + build_append_notify_method(sb_scope, + stringify(MEMORY_SLOT_NOTIFY_METHOD), + "MP%0.02X", nr_mem); + } + { AcpiBuildPciBusHotplugState hotplug_state; Object *pci_host; @@ -1091,7 +1178,7 @@ build_ssdt(GArray *table_data, GArray *linker, bus = PCI_HOST_BRIDGE(pci_host)->bus; } - build_pci_bus_state_init(&hotplug_state, NULL); + build_pci_bus_state_init(&hotplug_state, NULL, pm->pcihp_bridge_en); if (bus) { /* Scan all PCI buses. Generate tables to support hotplug. */ @@ -1129,21 +1216,61 @@ build_hpet(GArray *table_data, GArray *linker) } static void -acpi_build_srat_memory(AcpiSratMemoryAffinity *numamem, - uint64_t base, uint64_t len, int node, int enabled) +build_tpm_tcpa(GArray *table_data, GArray *linker, GArray *tcpalog) +{ + Acpi20Tcpa *tcpa = acpi_data_push(table_data, sizeof *tcpa); + uint64_t log_area_start_address = acpi_data_len(tcpalog); + + tcpa->platform_class = cpu_to_le16(TPM_TCPA_ACPI_CLASS_CLIENT); + tcpa->log_area_minimum_length = cpu_to_le32(TPM_LOG_AREA_MINIMUM_SIZE); + tcpa->log_area_start_address = cpu_to_le64(log_area_start_address); + + bios_linker_loader_alloc(linker, ACPI_BUILD_TPMLOG_FILE, 1, + false /* high memory */); + + /* log area start address to be filled by Guest linker */ + bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE, + ACPI_BUILD_TPMLOG_FILE, + table_data, &tcpa->log_area_start_address, + sizeof(tcpa->log_area_start_address)); + + build_header(linker, table_data, + (void *)tcpa, "TCPA", sizeof(*tcpa), 2); + + acpi_data_push(tcpalog, TPM_LOG_AREA_MINIMUM_SIZE); +} + +static void +build_tpm_ssdt(GArray *table_data, GArray *linker) +{ + void *tpm_ptr; + + tpm_ptr = acpi_data_push(table_data, sizeof(ssdt_tpm_aml)); + memcpy(tpm_ptr, ssdt_tpm_aml, sizeof(ssdt_tpm_aml)); +} + +typedef enum { + MEM_AFFINITY_NOFLAGS = 0, + MEM_AFFINITY_ENABLED = (1 << 0), + MEM_AFFINITY_HOTPLUGGABLE = (1 << 1), + MEM_AFFINITY_NON_VOLATILE = (1 << 2), +} MemoryAffinityFlags; + +static void +acpi_build_srat_memory(AcpiSratMemoryAffinity *numamem, uint64_t base, + uint64_t len, int node, MemoryAffinityFlags flags) { numamem->type = ACPI_SRAT_MEMORY; numamem->length = sizeof(*numamem); memset(numamem->proximity, 0, 4); numamem->proximity[0] = node; - numamem->flags = cpu_to_le32(!!enabled); + numamem->flags = cpu_to_le32(flags); numamem->base_addr = cpu_to_le64(base); numamem->range_length = cpu_to_le64(len); } static void -build_srat(GArray *table_data, GArray *linker, - AcpiCpuInfo *cpu, PcGuestInfo *guest_info) +build_srat(GArray *table_data, GArray *linker, PcGuestInfo *guest_info) { AcpiSystemResourceAffinityTable *srat; AcpiSratProcessorAffinity *core; @@ -1153,6 +1280,10 @@ build_srat(GArray *table_data, GArray *linker, uint64_t curnode; int srat_start, numa_start, slots; uint64_t mem_len, mem_base, next_base; + PCMachineState *pcms = PC_MACHINE(qdev_get_machine()); + ram_addr_t hotplugabble_address_space_size = + object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE, + NULL); srat_start = table_data->len; @@ -1169,11 +1300,7 @@ build_srat(GArray *table_data, GArray *linker, core->proximity_lo = curnode; memset(core->proximity_hi, 0, 3); core->local_sapic_eid = 0; - if (test_bit(i, cpu->found_cpus)) { - core->flags = cpu_to_le32(1); - } else { - core->flags = cpu_to_le32(0); - } + core->flags = cpu_to_le32(1); } @@ -1184,7 +1311,7 @@ build_srat(GArray *table_data, GArray *linker, numa_start = table_data->len; numamem = acpi_data_push(table_data, sizeof *numamem); - acpi_build_srat_memory(numamem, 0, 640*1024, 0, 1); + acpi_build_srat_memory(numamem, 0, 640*1024, 0, MEM_AFFINITY_ENABLED); next_base = 1024 * 1024; for (i = 1; i < guest_info->numa_nodes + 1; ++i) { mem_base = next_base; @@ -1200,19 +1327,34 @@ build_srat(GArray *table_data, GArray *linker, mem_len -= next_base - guest_info->ram_size_below_4g; if (mem_len > 0) { numamem = acpi_data_push(table_data, sizeof *numamem); - acpi_build_srat_memory(numamem, mem_base, mem_len, i-1, 1); + acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1, + MEM_AFFINITY_ENABLED); } mem_base = 1ULL << 32; mem_len = next_base - guest_info->ram_size_below_4g; next_base += (1ULL << 32) - guest_info->ram_size_below_4g; } numamem = acpi_data_push(table_data, sizeof *numamem); - acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1, 1); + acpi_build_srat_memory(numamem, mem_base, mem_len, i - 1, + MEM_AFFINITY_ENABLED); } slots = (table_data->len - numa_start) / sizeof *numamem; for (; slots < guest_info->numa_nodes + 2; slots++) { numamem = acpi_data_push(table_data, sizeof *numamem); - acpi_build_srat_memory(numamem, 0, 0, 0, 0); + acpi_build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS); + } + + /* + * Entry is required for Windows to enable memory hotplug in OS. + * Memory devices may override proximity set by this entry, + * providing _PXM method if necessary. + */ + if (hotplugabble_address_space_size) { + numamem = acpi_data_push(table_data, sizeof *numamem); + acpi_build_srat_memory(numamem, pcms->hotplug_memory_base, + hotplugabble_address_space_size, 0, + MEM_AFFINITY_HOTPLUGGABLE | + MEM_AFFINITY_ENABLED); } build_header(linker, table_data, @@ -1251,6 +1393,30 @@ build_mcfg_q35(GArray *table_data, GArray *linker, AcpiMcfgInfo *info) } static void +build_dmar_q35(GArray *table_data, GArray *linker) +{ + int dmar_start = table_data->len; + + AcpiTableDmar *dmar; + AcpiDmarHardwareUnit *drhd; + + dmar = acpi_data_push(table_data, sizeof(*dmar)); + dmar->host_address_width = VTD_HOST_ADDRESS_WIDTH - 1; + dmar->flags = 0; /* No intr_remap for now */ + + /* DMAR Remapping Hardware Unit Definition structure */ + drhd = acpi_data_push(table_data, sizeof(*drhd)); + drhd->type = cpu_to_le16(ACPI_DMAR_TYPE_HARDWARE_UNIT); + drhd->length = cpu_to_le16(sizeof(*drhd)); /* No device scope now */ + drhd->flags = ACPI_DMAR_INCLUDE_PCI_ALL; + drhd->pci_segment = cpu_to_le16(0); + drhd->address = cpu_to_le64(Q35_HOST_BRIDGE_IOMMU_ADDR); + + build_header(linker, table_data, (void *)(table_data->data + dmar_start), + "DMAR", table_data->len - dmar_start, 1); +} + +static void build_dsdt(GArray *table_data, GArray *linker, AcpiMiscInfo *misc) { AcpiTableHeader *dsdt; @@ -1294,7 +1460,7 @@ build_rsdp(GArray *rsdp_table, GArray *linker, unsigned rsdt) { AcpiRsdpDescriptor *rsdp = acpi_data_push(rsdp_table, sizeof *rsdp); - bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, 1, + bios_linker_loader_alloc(linker, ACPI_BUILD_RSDP_FILE, 16, true /* fseg memory */); memcpy(&rsdp->signature, "RSD PTR ", 8); @@ -1317,6 +1483,7 @@ typedef struct AcpiBuildTables { GArray *table_data; GArray *rsdp; + GArray *tcpalog; GArray *linker; } AcpiBuildTables; @@ -1324,23 +1491,23 @@ static inline void acpi_build_tables_init(AcpiBuildTables *tables) { tables->rsdp = g_array_new(false, true /* clear */, 1); tables->table_data = g_array_new(false, true /* clear */, 1); + tables->tcpalog = g_array_new(false, true /* clear */, 1); tables->linker = bios_linker_loader_init(); } static inline void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre) { void *linker_data = bios_linker_loader_cleanup(tables->linker); - if (mfre) { - g_free(linker_data); - } + g_free(linker_data); g_array_free(tables->rsdp, mfre); - g_array_free(tables->table_data, mfre); + g_array_free(tables->table_data, true); + g_array_free(tables->tcpalog, mfre); } typedef struct AcpiBuildState { /* Copy of table in RAM (for patching). */ - uint8_t *table_ram; + ram_addr_t table_ram; uint32_t table_size; /* Is table patched? */ uint8_t patched; @@ -1362,24 +1529,37 @@ static bool acpi_get_mcfg(AcpiMcfgInfo *mcfg) return false; } mcfg->mcfg_base = qint_get_int(qobject_to_qint(o)); + qobject_decref(o); o = object_property_get_qobject(pci_host, PCIE_HOST_MCFG_SIZE, NULL); assert(o); mcfg->mcfg_size = qint_get_int(qobject_to_qint(o)); + qobject_decref(o); return true; } +static bool acpi_has_iommu(void) +{ + bool ambiguous; + Object *intel_iommu; + + intel_iommu = object_resolve_path_type("", TYPE_INTEL_IOMMU_DEVICE, + &ambiguous); + return intel_iommu && !ambiguous; +} + static void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables) { GArray *table_offsets; - unsigned facs, dsdt, rsdt; + unsigned facs, ssdt, dsdt, rsdt; AcpiCpuInfo cpu; AcpiPmInfo pm; AcpiMiscInfo misc; AcpiMcfgInfo mcfg; PcPciInfo pci; uint8_t *u; + size_t aml_len = 0; acpi_get_cpu_info(&cpu); acpi_get_pm_info(&pm); @@ -1407,28 +1587,47 @@ void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables) dsdt = tables->table_data->len; build_dsdt(tables->table_data, tables->linker, &misc); + /* Count the size of the DSDT and SSDT, we will need it for legacy + * sizing of ACPI tables. + */ + aml_len += tables->table_data->len - dsdt; + /* ACPI tables pointed to by RSDT */ acpi_add_table(table_offsets, tables->table_data); build_fadt(tables->table_data, tables->linker, &pm, facs, dsdt); - acpi_add_table(table_offsets, tables->table_data); + ssdt = tables->table_data->len; + acpi_add_table(table_offsets, tables->table_data); build_ssdt(tables->table_data, tables->linker, &cpu, &pm, &misc, &pci, guest_info); - acpi_add_table(table_offsets, tables->table_data); + aml_len += tables->table_data->len - ssdt; - build_madt(tables->table_data, tables->linker, &cpu, guest_info); acpi_add_table(table_offsets, tables->table_data); + build_madt(tables->table_data, tables->linker, &cpu, guest_info); + if (misc.has_hpet) { + acpi_add_table(table_offsets, tables->table_data); build_hpet(tables->table_data, tables->linker); } + if (misc.has_tpm) { + acpi_add_table(table_offsets, tables->table_data); + build_tpm_tcpa(tables->table_data, tables->linker, tables->tcpalog); + + acpi_add_table(table_offsets, tables->table_data); + build_tpm_ssdt(tables->table_data, tables->linker); + } if (guest_info->numa_nodes) { acpi_add_table(table_offsets, tables->table_data); - build_srat(tables->table_data, tables->linker, &cpu, guest_info); + build_srat(tables->table_data, tables->linker, guest_info); } if (acpi_get_mcfg(&mcfg)) { acpi_add_table(table_offsets, tables->table_data); build_mcfg_q35(tables->table_data, tables->linker, &mcfg); } + if (acpi_has_iommu()) { + acpi_add_table(table_offsets, tables->table_data); + build_dmar_q35(tables->table_data, tables->linker); + } /* Add tables supplied by user (if any) */ for (u = acpi_table_first(); u; u = acpi_table_next(u)) { @@ -1445,14 +1644,53 @@ void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables) /* RSDP is in FSEG memory, so allocate it separately */ build_rsdp(tables->rsdp, tables->linker, rsdt); - /* We'll expose it all to Guest so align size to reduce + /* We'll expose it all to Guest so we want to reduce * chance of size changes. * RSDP is small so it's easy to keep it immutable, no need to * bother with alignment. + * + * We used to align the tables to 4k, but of course this would + * too simple to be enough. 4k turned out to be too small an + * alignment very soon, and in fact it is almost impossible to + * keep the table size stable for all (max_cpus, max_memory_slots) + * combinations. So the table size is always 64k for pc-i440fx-2.1 + * and we give an error if the table grows beyond that limit. + * + * We still have the problem of migrating from "-M pc-i440fx-2.0". For + * that, we exploit the fact that QEMU 2.1 generates _smaller_ tables + * than 2.0 and we can always pad the smaller tables with zeros. We can + * then use the exact size of the 2.0 tables. + * + * All this is for PIIX4, since QEMU 2.0 didn't support Q35 migration. */ - acpi_align_size(tables->table_data, 0x1000); + if (guest_info->legacy_acpi_table_size) { + /* Subtracting aml_len gives the size of fixed tables. Then add the + * size of the PIIX4 DSDT/SSDT in QEMU 2.0. + */ + int legacy_aml_len = + guest_info->legacy_acpi_table_size + + ACPI_BUILD_LEGACY_CPU_AML_SIZE * max_cpus; + int legacy_table_size = + ROUND_UP(tables->table_data->len - aml_len + legacy_aml_len, + ACPI_BUILD_ALIGN_SIZE); + if (tables->table_data->len > legacy_table_size) { + /* Should happen only with PCI bridges and -M pc-i440fx-2.0. */ + error_report("Warning: migration may not work."); + } + g_array_set_size(tables->table_data, legacy_table_size); + } else { + /* Make sure we have a buffer in case we need to resize the tables. */ + if (tables->table_data->len > ACPI_BUILD_TABLE_SIZE / 2) { + /* As of QEMU 2.1, this fires with 160 VCPUs and 255 memory slots. */ + error_report("Warning: ACPI tables are larger than 64k."); + error_report("Warning: migration may not work."); + error_report("Warning: please remove CPUs, NUMA nodes, " + "memory slots or PCI bridges."); + } + acpi_align_size(tables->table_data, ACPI_BUILD_TABLE_SIZE); + } - acpi_align_size(tables->linker, 0x1000); + acpi_align_size(tables->linker, ACPI_BUILD_ALIGN_SIZE); /* Cleanup memory that's no longer used. */ g_array_free(table_offsets, true); @@ -1474,9 +1712,12 @@ static void acpi_build_update(void *build_opaque, uint32_t offset) acpi_build(build_state->guest_info, &tables); assert(acpi_data_len(tables.table_data) == build_state->table_size); - memcpy(build_state->table_ram, tables.table_data->data, + memcpy(qemu_get_ram_ptr(build_state->table_ram), tables.table_data->data, build_state->table_size); + cpu_physical_memory_set_dirty_range_nocode(build_state->table_ram, + build_state->table_size); + acpi_build_tables_cleanup(&tables, true); } @@ -1486,7 +1727,7 @@ static void acpi_build_reset(void *build_opaque) build_state->patched = 0; } -static void *acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob, +static ram_addr_t acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob, const char *name) { return rom_add_blob(name, blob->data, acpi_data_len(blob), -1, name, @@ -1497,8 +1738,7 @@ static const VMStateDescription vmstate_acpi_build = { .name = "acpi_build", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(patched, AcpiBuildState), VMSTATE_END_OF_LIST() }, @@ -1536,10 +1776,14 @@ void acpi_setup(PcGuestInfo *guest_info) /* Now expose it all to Guest */ build_state->table_ram = acpi_add_rom_blob(build_state, tables.table_data, ACPI_BUILD_TABLE_FILE); + assert(build_state->table_ram != RAM_ADDR_MAX); build_state->table_size = acpi_data_len(tables.table_data); acpi_add_rom_blob(NULL, tables.linker, "etc/table-loader"); + fw_cfg_add_file(guest_info->fw_cfg, ACPI_BUILD_TPMLOG_FILE, + tables.tcpalog->data, acpi_data_len(tables.tcpalog)); + /* * RSDP is small so it's easy to keep it immutable, no need to * bother with ROM blobs. diff --git a/hw/i386/acpi-defs.h b/hw/i386/acpi-defs.h index e93babb026..c4468f84e8 100644 --- a/hw/i386/acpi-defs.h +++ b/hw/i386/acpi-defs.h @@ -314,4 +314,55 @@ struct AcpiTableMcfg { } QEMU_PACKED; typedef struct AcpiTableMcfg AcpiTableMcfg; +/* + * TCPA Description Table + */ +struct Acpi20Tcpa { + ACPI_TABLE_HEADER_DEF /* ACPI common table header */ + uint16_t platform_class; + uint32_t log_area_minimum_length; + uint64_t log_area_start_address; +} QEMU_PACKED; +typedef struct Acpi20Tcpa Acpi20Tcpa; + +/* DMAR - DMA Remapping table r2.2 */ +struct AcpiTableDmar { + ACPI_TABLE_HEADER_DEF + uint8_t host_address_width; /* Maximum DMA physical addressability */ + uint8_t flags; + uint8_t reserved[10]; +} QEMU_PACKED; +typedef struct AcpiTableDmar AcpiTableDmar; + +/* Masks for Flags field above */ +#define ACPI_DMAR_INTR_REMAP 1 +#define ACPI_DMAR_X2APIC_OPT_OUT (1 << 1) + +/* Values for sub-structure type for DMAR */ +enum { + ACPI_DMAR_TYPE_HARDWARE_UNIT = 0, /* DRHD */ + ACPI_DMAR_TYPE_RESERVED_MEMORY = 1, /* RMRR */ + ACPI_DMAR_TYPE_ATSR = 2, /* ATSR */ + ACPI_DMAR_TYPE_HARDWARE_AFFINITY = 3, /* RHSR */ + ACPI_DMAR_TYPE_ANDD = 4, /* ANDD */ + ACPI_DMAR_TYPE_RESERVED = 5 /* Reserved for furture use */ +}; + +/* + * Sub-structures for DMAR + */ +/* Type 0: Hardware Unit Definition */ +struct AcpiDmarHardwareUnit { + uint16_t type; + uint16_t length; + uint8_t flags; + uint8_t reserved; + uint16_t pci_segment; /* The PCI Segment associated with this unit */ + uint64_t address; /* Base address of remapping hardware register-set */ +} QEMU_PACKED; +typedef struct AcpiDmarHardwareUnit AcpiDmarHardwareUnit; + +/* Masks for Flags field above */ +#define ACPI_DMAR_INCLUDE_PCI_ALL 1 + #endif diff --git a/hw/i386/acpi-dsdt-mem-hotplug.dsl b/hw/i386/acpi-dsdt-mem-hotplug.dsl new file mode 100644 index 0000000000..2a36c4799e --- /dev/null +++ b/hw/i386/acpi-dsdt-mem-hotplug.dsl @@ -0,0 +1,176 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, see <http://www.gnu.org/licenses/>. + */ + + External(MEMORY_SLOT_NOTIFY_METHOD, MethodObj) + + Scope(\_SB.PCI0) { + Device(MEMORY_HOTPLUG_DEVICE) { + Name(_HID, "PNP0A06") + Name(_UID, "Memory hotplug resources") + External(MEMORY_SLOTS_NUMBER, IntObj) + + /* Memory hotplug IO registers */ + OperationRegion(MEMORY_HOTPLUG_IO_REGION, SystemIO, + ACPI_MEMORY_HOTPLUG_BASE, + ACPI_MEMORY_HOTPLUG_IO_LEN) + + Name(_CRS, ResourceTemplate() { + IO(Decode16, ACPI_MEMORY_HOTPLUG_BASE, ACPI_MEMORY_HOTPLUG_BASE, + 0, ACPI_MEMORY_HOTPLUG_IO_LEN, IO) + }) + + Method(_STA, 0) { + If (LEqual(MEMORY_SLOTS_NUMBER, Zero)) { + Return(0x0) + } + /* present, functioning, decoding, not shown in UI */ + Return(0xB) + } + + Field(MEMORY_HOTPLUG_IO_REGION, DWordAcc, NoLock, Preserve) { + MEMORY_SLOT_ADDR_LOW, 32, // read only + MEMORY_SLOT_ADDR_HIGH, 32, // read only + MEMORY_SLOT_SIZE_LOW, 32, // read only + MEMORY_SLOT_SIZE_HIGH, 32, // read only + MEMORY_SLOT_PROXIMITY, 32, // read only + } + Field(MEMORY_HOTPLUG_IO_REGION, ByteAcc, NoLock, Preserve) { + Offset(20), + MEMORY_SLOT_ENABLED, 1, // 1 if enabled, read only + MEMORY_SLOT_INSERT_EVENT, 1, // (read) 1 if has a insert event. (write) 1 to clear event + } + + Mutex (MEMORY_SLOT_LOCK, 0) + Field (MEMORY_HOTPLUG_IO_REGION, DWordAcc, NoLock, Preserve) { + MEMORY_SLOT_SLECTOR, 32, // DIMM selector, write only + MEMORY_SLOT_OST_EVENT, 32, // _OST event code, write only + MEMORY_SLOT_OST_STATUS, 32, // _OST status code, write only + } + + Method(MEMORY_SLOT_SCAN_METHOD, 0) { + If (LEqual(MEMORY_SLOTS_NUMBER, Zero)) { + Return(Zero) + } + + Store(Zero, Local0) // Mem devs iterrator + Acquire(MEMORY_SLOT_LOCK, 0xFFFF) + while (LLess(Local0, MEMORY_SLOTS_NUMBER)) { + Store(Local0, MEMORY_SLOT_SLECTOR) // select Local0 DIMM + If (LEqual(MEMORY_SLOT_INSERT_EVENT, One)) { // Memory device needs check + MEMORY_SLOT_NOTIFY_METHOD(Local0, 1) + Store(1, MEMORY_SLOT_INSERT_EVENT) + } + // TODO: handle memory eject request + Add(Local0, One, Local0) // goto next DIMM + } + Release(MEMORY_SLOT_LOCK) + Return(One) + } + + Method(MEMORY_SLOT_STATUS_METHOD, 1) { + Store(Zero, Local0) + + Acquire(MEMORY_SLOT_LOCK, 0xFFFF) + Store(ToInteger(Arg0), MEMORY_SLOT_SLECTOR) // select DIMM + + If (LEqual(MEMORY_SLOT_ENABLED, One)) { + Store(0xF, Local0) + } + + Release(MEMORY_SLOT_LOCK) + Return(Local0) + } + + Method(MEMORY_SLOT_CRS_METHOD, 1, Serialized) { + Acquire(MEMORY_SLOT_LOCK, 0xFFFF) + Store(ToInteger(Arg0), MEMORY_SLOT_SLECTOR) // select DIMM + + Name(MR64, ResourceTemplate() { + QWordMemory(ResourceProducer, PosDecode, MinFixed, MaxFixed, + Cacheable, ReadWrite, + 0x0000000000000000, // Address Space Granularity + 0x0000000000000000, // Address Range Minimum + 0xFFFFFFFFFFFFFFFE, // Address Range Maximum + 0x0000000000000000, // Address Translation Offset + 0xFFFFFFFFFFFFFFFF, // Address Length + ,, MW64, AddressRangeMemory, TypeStatic) + }) + + CreateDWordField(MR64, 14, MINL) + CreateDWordField(MR64, 18, MINH) + CreateDWordField(MR64, 38, LENL) + CreateDWordField(MR64, 42, LENH) + CreateDWordField(MR64, 22, MAXL) + CreateDWordField(MR64, 26, MAXH) + + Store(MEMORY_SLOT_ADDR_HIGH, MINH) + Store(MEMORY_SLOT_ADDR_LOW, MINL) + Store(MEMORY_SLOT_SIZE_HIGH, LENH) + Store(MEMORY_SLOT_SIZE_LOW, LENL) + + // 64-bit math: MAX = MIN + LEN - 1 + Add(MINL, LENL, MAXL) + Add(MINH, LENH, MAXH) + If (LLess(MAXL, MINL)) { + Add(MAXH, One, MAXH) + } + If (LLess(MAXL, One)) { + Subtract(MAXH, One, MAXH) + } + Subtract(MAXL, One, MAXL) + + If (LEqual(MAXH, Zero)){ + Name(MR32, ResourceTemplate() { + DWordMemory(ResourceProducer, PosDecode, MinFixed, MaxFixed, + Cacheable, ReadWrite, + 0x00000000, // Address Space Granularity + 0x00000000, // Address Range Minimum + 0xFFFFFFFE, // Address Range Maximum + 0x00000000, // Address Translation Offset + 0xFFFFFFFF, // Address Length + ,, MW32, AddressRangeMemory, TypeStatic) + }) + CreateDWordField(MR32, MW32._MIN, MIN) + CreateDWordField(MR32, MW32._MAX, MAX) + CreateDWordField(MR32, MW32._LEN, LEN) + Store(MINL, MIN) + Store(MAXL, MAX) + Store(LENL, LEN) + + Release(MEMORY_SLOT_LOCK) + Return(MR32) + } + + Release(MEMORY_SLOT_LOCK) + Return(MR64) + } + + Method(MEMORY_SLOT_PROXIMITY_METHOD, 1) { + Acquire(MEMORY_SLOT_LOCK, 0xFFFF) + Store(ToInteger(Arg0), MEMORY_SLOT_SLECTOR) // select DIMM + Store(MEMORY_SLOT_PROXIMITY, Local0) + Release(MEMORY_SLOT_LOCK) + Return(Local0) + } + + Method(MEMORY_SLOT_OST_METHOD, 4) { + Acquire(MEMORY_SLOT_LOCK, 0xFFFF) + Store(ToInteger(Arg0), MEMORY_SLOT_SLECTOR) // select DIMM + Store(Arg1, MEMORY_SLOT_OST_EVENT) + Store(Arg2, MEMORY_SLOT_OST_STATUS) + Release(MEMORY_SLOT_LOCK) + } + } // Device() + } // Scope() diff --git a/hw/i386/acpi-dsdt.dsl b/hw/i386/acpi-dsdt.dsl index 0a1e252d21..a611e07ec8 100644 --- a/hw/i386/acpi-dsdt.dsl +++ b/hw/i386/acpi-dsdt.dsl @@ -181,57 +181,45 @@ DefinitionBlock ( Scope(\_SB) { Scope(PCI0) { - Name(_PRT, Package() { - /* PCI IRQ routing table, example from ACPI 2.0a specification, - section 6.2.8.1 */ - /* Note: we provide the same info as the PCI routing - table of the Bochs BIOS */ - -#define prt_slot(nr, lnk0, lnk1, lnk2, lnk3) \ - Package() { nr##ffff, 0, lnk0, 0 }, \ - Package() { nr##ffff, 1, lnk1, 0 }, \ - Package() { nr##ffff, 2, lnk2, 0 }, \ - Package() { nr##ffff, 3, lnk3, 0 } - -#define prt_slot0(nr) prt_slot(nr, LNKD, LNKA, LNKB, LNKC) -#define prt_slot1(nr) prt_slot(nr, LNKA, LNKB, LNKC, LNKD) -#define prt_slot2(nr) prt_slot(nr, LNKB, LNKC, LNKD, LNKA) -#define prt_slot3(nr) prt_slot(nr, LNKC, LNKD, LNKA, LNKB) - - prt_slot0(0x0000), - /* Device 1 is power mgmt device, and can only use irq 9 */ - prt_slot(0x0001, LNKS, LNKB, LNKC, LNKD), - prt_slot2(0x0002), - prt_slot3(0x0003), - prt_slot0(0x0004), - prt_slot1(0x0005), - prt_slot2(0x0006), - prt_slot3(0x0007), - prt_slot0(0x0008), - prt_slot1(0x0009), - prt_slot2(0x000a), - prt_slot3(0x000b), - prt_slot0(0x000c), - prt_slot1(0x000d), - prt_slot2(0x000e), - prt_slot3(0x000f), - prt_slot0(0x0010), - prt_slot1(0x0011), - prt_slot2(0x0012), - prt_slot3(0x0013), - prt_slot0(0x0014), - prt_slot1(0x0015), - prt_slot2(0x0016), - prt_slot3(0x0017), - prt_slot0(0x0018), - prt_slot1(0x0019), - prt_slot2(0x001a), - prt_slot3(0x001b), - prt_slot0(0x001c), - prt_slot1(0x001d), - prt_slot2(0x001e), - prt_slot3(0x001f), - }) + Method (_PRT, 0) { + Store(Package(128) {}, Local0) + Store(Zero, Local1) + While(LLess(Local1, 128)) { + // slot = pin >> 2 + Store(ShiftRight(Local1, 2), Local2) + + // lnk = (slot + pin) & 3 + Store(And(Add(Local1, Local2), 3), Local3) + If (LEqual(Local3, 0)) { + Store(Package(4) { Zero, Zero, LNKD, Zero }, Local4) + } + If (LEqual(Local3, 1)) { + // device 1 is the power-management device, needs SCI + If (LEqual(Local1, 4)) { + Store(Package(4) { Zero, Zero, LNKS, Zero }, Local4) + } Else { + Store(Package(4) { Zero, Zero, LNKA, Zero }, Local4) + } + } + If (LEqual(Local3, 2)) { + Store(Package(4) { Zero, Zero, LNKB, Zero }, Local4) + } + If (LEqual(Local3, 3)) { + Store(Package(4) { Zero, Zero, LNKC, Zero }, Local4) + } + + // Complete the interrupt routing entry: + // Package(4) { 0x[slot]FFFF, [pin], [link], 0) } + + Store(Or(ShiftLeft(Local2, 16), 0xFFFF), Index(Local4, 0)) + Store(And(Local1, 3), Index(Local4, 1)) + Store(Local4, Index(Local0, Local1)) + + Increment(Local1) + } + + Return(Local0) + } } Field(PCI0.ISA.P40C, ByteAcc, NoLock, Preserve) { @@ -306,15 +294,15 @@ DefinitionBlock ( } } -#include "hw/acpi/cpu_hotplug_defs.h" +#include "hw/acpi/pc-hotplug.h" #define CPU_STATUS_BASE PIIX4_CPU_HOTPLUG_IO_BASE #include "acpi-dsdt-cpu-hotplug.dsl" +#include "acpi-dsdt-mem-hotplug.dsl" /**************************************************************** * General purpose events ****************************************************************/ - Scope(\_GPE) { Name(_HID, "ACPI0006") @@ -330,7 +318,9 @@ DefinitionBlock ( // CPU hotplug event \_SB.PRSC() } - Method(_L03) { + Method(_E03) { + // Memory hotplug event + \_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_SCAN_METHOD() } Method(_L04) { } diff --git a/hw/i386/acpi-dsdt.hex.generated b/hw/i386/acpi-dsdt.hex.generated index e61572a5dd..875570e5b1 100644 --- a/hw/i386/acpi-dsdt.hex.generated +++ b/hw/i386/acpi-dsdt.hex.generated @@ -3,12 +3,12 @@ static unsigned char AcpiDsdtAmlCode[] = { 0x53, 0x44, 0x54, -0x80, -0x11, +0x8, +0xe, 0x0, 0x0, 0x1, -0x60, +0xfc, 0x42, 0x58, 0x50, @@ -31,9 +31,9 @@ static unsigned char AcpiDsdtAmlCode[] = { 0x4e, 0x54, 0x4c, -0x15, -0x11, -0x13, +0x28, +0x8, +0x14, 0x20, 0x10, 0x49, @@ -1439,1419 +1439,68 @@ static unsigned char AcpiDsdtAmlCode[] = { 0xa4, 0x0, 0x10, -0x4a, -0xa0, +0x4e, +0x36, 0x5f, 0x53, 0x42, 0x5f, 0x10, -0x47, -0x74, +0x4b, +0xa, 0x50, 0x43, 0x49, 0x30, -0x8, +0x14, +0x44, +0xa, 0x5f, 0x50, 0x52, 0x54, -0x12, -0x4b, -0x73, -0x80, -0x12, -0xb, -0x4, -0xb, -0xff, -0xff, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xb, -0x4, -0xb, -0xff, -0xff, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xc, -0x4, -0xb, -0xff, -0xff, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xc, -0x4, -0xb, -0xff, -0xff, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x53, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x2, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x2, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x2, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x2, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x3, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x3, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x3, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x3, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x4, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x4, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x4, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x4, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x5, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x5, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x5, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x5, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x6, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x6, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x6, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x6, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x7, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x7, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x7, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x7, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x8, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x8, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, 0x0, +0x70, 0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x8, -0x0, -0xa, 0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x8, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x9, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x9, +0x80, +0x60, +0x70, 0x0, -0x1, -0x4c, -0x4e, -0x4b, +0x61, +0xa2, 0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x9, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, 0x9, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xa, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xa, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xa, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xa, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xb, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xb, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xb, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xb, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xc, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xc, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xc, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xc, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xd, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xd, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xd, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xd, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xe, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xe, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xe, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xe, -0x0, +0x95, +0x61, 0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xf, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0xf, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xf, -0x0, +0x80, +0x70, +0x7a, +0x61, 0xa, 0x2, -0x4c, -0x4e, -0x4b, -0x41, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0xf, +0x62, +0x70, +0x7b, +0x72, +0x61, +0x62, 0x0, 0xa, 0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x10, 0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x10, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x10, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, +0x63, +0xa0, 0x10, +0x93, +0x63, 0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x11, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x11, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x11, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x11, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x12, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x12, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x12, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x12, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x13, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x13, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x13, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x13, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x14, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x14, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x14, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x14, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x15, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x15, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x15, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x15, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x16, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x16, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x16, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x16, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x17, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x17, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x17, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x17, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, +0x70, 0x12, -0xd, +0x9, 0x4, -0xc, -0xff, -0xff, -0x18, 0x0, 0x0, 0x4c, @@ -2859,456 +1508,115 @@ static unsigned char AcpiDsdtAmlCode[] = { 0x4b, 0x44, 0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x18, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x18, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x18, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x19, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x19, -0x0, +0x64, +0xa0, +0x24, +0x93, +0x63, 0x1, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x19, -0x0, +0xa0, +0x11, +0x93, +0x61, 0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xe, 0x4, -0xc, -0xff, -0xff, -0x19, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, +0x70, 0x12, -0xd, +0x9, 0x4, -0xc, -0xff, -0xff, -0x1a, 0x0, 0x0, 0x4c, 0x4e, 0x4b, -0x42, +0x53, 0x0, -0x12, +0x64, +0xa1, 0xd, -0x4, -0xc, -0xff, -0xff, -0x1a, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, -0x0, +0x70, 0x12, -0xe, +0x9, 0x4, -0xc, -0xff, -0xff, -0x1a, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1a, 0x0, -0xa, -0x3, 0x4c, 0x4e, 0x4b, 0x41, 0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1b, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1b, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1b, -0x0, +0x64, +0xa0, +0x11, +0x93, +0x63, 0xa, 0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1b, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1c, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x44, -0x0, +0x70, 0x12, -0xd, +0x9, 0x4, -0xc, -0xff, -0xff, -0x1c, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x41, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1c, 0x0, -0xa, -0x2, 0x4c, 0x4e, 0x4b, 0x42, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1c, -0x0, +0x64, +0xa0, +0x11, +0x93, +0x63, 0xa, 0x3, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1d, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x41, -0x0, +0x70, 0x12, -0xd, +0x9, 0x4, -0xc, -0xff, -0xff, -0x1d, 0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x42, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1d, -0x0, -0xa, -0x2, 0x4c, 0x4e, 0x4b, 0x43, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1d, -0x0, +0x64, +0x70, +0x7d, +0x79, +0x62, 0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1e, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x42, +0x10, 0x0, -0x12, -0xd, -0x4, -0xc, +0xb, 0xff, 0xff, -0x1e, -0x0, -0x1, -0x4c, -0x4e, -0x4b, -0x43, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1e, +0x88, +0x64, 0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x44, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1e, 0x0, +0x70, +0x7b, +0x61, 0xa, 0x3, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1f, -0x0, -0x0, -0x4c, -0x4e, -0x4b, -0x43, -0x0, -0x12, -0xd, -0x4, -0xc, -0xff, -0xff, -0x1f, 0x0, +0x88, +0x64, 0x1, -0x4c, -0x4e, -0x4b, -0x44, 0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1f, -0x0, -0xa, -0x2, -0x4c, -0x4e, -0x4b, -0x41, -0x0, -0x12, -0xe, -0x4, -0xc, -0xff, -0xff, -0x1f, -0x0, -0xa, -0x3, -0x4c, -0x4e, -0x4b, -0x42, +0x70, +0x64, +0x88, +0x60, +0x61, 0x0, +0x75, +0x61, +0xa4, +0x60, 0x5b, 0x81, 0x24, @@ -4285,8 +2593,793 @@ static unsigned char AcpiDsdtAmlCode[] = { 0xa, 0xb, 0x10, +0x40, +0x31, +0x2e, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x5b, +0x82, +0x43, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x8, +0x5f, +0x48, +0x49, +0x44, +0xd, +0x50, +0x4e, +0x50, +0x30, +0x41, +0x30, +0x36, +0x0, +0x8, +0x5f, +0x55, +0x49, +0x44, +0xd, +0x4d, +0x65, +0x6d, +0x6f, +0x72, +0x79, +0x20, +0x68, +0x6f, +0x74, +0x70, +0x6c, +0x75, +0x67, +0x20, +0x72, +0x65, +0x73, +0x6f, +0x75, +0x72, +0x63, +0x65, +0x73, +0x0, +0x5b, +0x80, +0x48, +0x50, +0x4d, +0x52, +0x1, +0xb, +0x0, +0xa, +0xa, +0x18, +0x8, +0x5f, +0x43, +0x52, +0x53, +0x11, +0xd, +0xa, +0xa, +0x47, +0x1, +0x0, +0xa, +0x0, +0xa, +0x0, +0x18, +0x79, +0x0, +0x14, +0x13, +0x5f, +0x53, +0x54, +0x41, +0x0, +0xa0, +0x9, +0x93, +0x4d, +0x44, +0x4e, +0x52, +0x0, +0xa4, +0x0, +0xa4, +0xa, +0xb, +0x5b, +0x81, +0x1f, +0x48, +0x50, +0x4d, +0x52, +0x3, +0x4d, +0x52, +0x42, +0x4c, +0x20, +0x4d, +0x52, 0x42, +0x48, +0x20, +0x4d, +0x52, +0x4c, +0x4c, +0x20, +0x4d, +0x52, +0x4c, +0x48, +0x20, +0x4d, +0x50, +0x58, +0x5f, +0x20, +0x5b, +0x81, +0x13, +0x48, +0x50, +0x4d, +0x52, +0x1, +0x0, +0x40, +0xa, +0x4d, +0x45, +0x53, +0x5f, +0x1, +0x4d, +0x49, +0x4e, +0x53, +0x1, +0x5b, +0x1, +0x4d, +0x4c, +0x43, +0x4b, +0x0, +0x5b, +0x81, +0x15, +0x48, +0x50, +0x4d, +0x52, +0x3, +0x4d, +0x53, +0x45, +0x4c, +0x20, +0x4d, +0x4f, +0x45, +0x56, +0x20, +0x4d, +0x4f, +0x53, +0x43, +0x20, +0x14, +0x4a, +0x4, +0x4d, +0x53, +0x43, +0x4e, +0x0, +0xa0, +0x9, +0x93, +0x4d, +0x44, +0x4e, +0x52, +0x0, +0xa4, +0x0, +0x70, +0x0, +0x60, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0xa2, +0x25, +0x95, +0x60, +0x4d, +0x44, +0x4e, +0x52, +0x70, +0x60, +0x4d, +0x53, +0x45, +0x4c, +0xa0, +0x13, +0x93, +0x4d, +0x49, +0x4e, +0x53, +0x1, +0x4d, +0x54, +0x46, +0x59, +0x60, +0x1, +0x70, +0x1, +0x4d, +0x49, +0x4e, +0x53, +0x72, +0x60, +0x1, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x1, +0x14, +0x2d, +0x4d, +0x52, +0x53, +0x54, +0x1, +0x70, +0x0, +0x60, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0xa0, +0xb, +0x93, +0x4d, +0x45, +0x53, +0x5f, +0x1, +0x70, +0xa, +0xf, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x60, +0x14, +0x41, +0x18, +0x4d, +0x43, +0x52, +0x53, +0x9, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x8, +0x4d, +0x52, +0x36, +0x34, +0x11, +0x33, +0xa, +0x30, +0x8a, +0x2b, +0x0, +0x0, 0xc, +0x3, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xfe, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0x79, +0x0, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0xe, +0x4d, +0x49, +0x4e, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x12, +0x4d, +0x49, +0x4e, +0x48, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x26, +0x4c, +0x45, +0x4e, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x2a, +0x4c, +0x45, +0x4e, +0x48, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x16, +0x4d, +0x41, +0x58, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x1a, +0x4d, +0x41, +0x58, +0x48, +0x70, +0x4d, +0x52, +0x42, +0x48, +0x4d, +0x49, +0x4e, +0x48, +0x70, +0x4d, +0x52, +0x42, +0x4c, +0x4d, +0x49, +0x4e, +0x4c, +0x70, +0x4d, +0x52, +0x4c, +0x48, +0x4c, +0x45, +0x4e, +0x48, +0x70, +0x4d, +0x52, +0x4c, +0x4c, +0x4c, +0x45, +0x4e, +0x4c, +0x72, +0x4d, +0x49, +0x4e, +0x4c, +0x4c, +0x45, +0x4e, +0x4c, +0x4d, +0x41, +0x58, +0x4c, +0x72, +0x4d, +0x49, +0x4e, +0x48, +0x4c, +0x45, +0x4e, +0x48, +0x4d, +0x41, +0x58, +0x48, +0xa0, +0x14, +0x95, +0x4d, +0x41, +0x58, +0x4c, +0x4d, +0x49, +0x4e, +0x4c, +0x72, +0x4d, +0x41, +0x58, +0x48, +0x1, +0x4d, +0x41, +0x58, +0x48, +0xa0, +0x11, +0x95, +0x4d, +0x41, +0x58, +0x4c, +0x1, +0x74, +0x4d, +0x41, +0x58, +0x48, +0x1, +0x4d, +0x41, +0x58, +0x48, +0x74, +0x4d, +0x41, +0x58, +0x4c, +0x1, +0x4d, +0x41, +0x58, +0x4c, +0xa0, +0x44, +0x7, +0x93, +0x4d, +0x41, +0x58, +0x48, +0x0, +0x8, +0x4d, +0x52, +0x33, +0x32, +0x11, +0x1f, +0xa, +0x1c, +0x87, +0x17, +0x0, +0x0, +0xc, +0x3, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xfe, +0xff, +0xff, +0xff, +0x0, +0x0, +0x0, +0x0, +0xff, +0xff, +0xff, +0xff, +0x79, +0x0, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0xa, +0x4d, +0x49, +0x4e, +0x5f, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0xe, +0x4d, +0x41, +0x58, +0x5f, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0x16, +0x4c, +0x45, +0x4e, +0x5f, +0x70, +0x4d, +0x49, +0x4e, +0x4c, +0x4d, +0x49, +0x4e, +0x5f, +0x70, +0x4d, +0x41, +0x58, +0x4c, +0x4d, +0x41, +0x58, +0x5f, +0x70, +0x4c, +0x45, +0x4e, +0x4c, +0x4c, +0x45, +0x4e, +0x5f, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x4d, +0x52, +0x33, +0x32, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x4d, +0x52, +0x36, +0x34, +0x14, +0x24, +0x4d, +0x50, +0x58, +0x4d, +0x1, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x70, +0x4d, +0x50, +0x58, +0x5f, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x60, +0x14, +0x28, +0x4d, +0x4f, +0x53, +0x54, +0x4, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x70, +0x69, +0x4d, +0x4f, +0x45, +0x56, +0x70, +0x6a, +0x4d, +0x4f, +0x53, +0x43, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0x10, +0x45, +0xd, 0x5f, 0x47, 0x50, @@ -4389,12 +3482,31 @@ static unsigned char AcpiDsdtAmlCode[] = { 0x53, 0x43, 0x14, -0x6, +0x19, 0x5f, -0x4c, +0x45, 0x30, 0x33, 0x0, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x53, +0x43, +0x4e, 0x14, 0x6, 0x5f, diff --git a/hw/i386/intel_iommu.c b/hw/i386/intel_iommu.c new file mode 100644 index 0000000000..0a4282adf3 --- /dev/null +++ b/hw/i386/intel_iommu.c @@ -0,0 +1,1963 @@ +/* + * QEMU emulation of an Intel IOMMU (VT-d) + * (DMA Remapping device) + * + * Copyright (C) 2013 Knut Omang, Oracle <knut.omang@oracle.com> + * Copyright (C) 2014 Le Tan, <tamlokveer@gmail.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "hw/sysbus.h" +#include "exec/address-spaces.h" +#include "intel_iommu_internal.h" + +/*#define DEBUG_INTEL_IOMMU*/ +#ifdef DEBUG_INTEL_IOMMU +enum { + DEBUG_GENERAL, DEBUG_CSR, DEBUG_INV, DEBUG_MMU, DEBUG_FLOG, + DEBUG_CACHE, +}; +#define VTD_DBGBIT(x) (1 << DEBUG_##x) +static int vtd_dbgflags = VTD_DBGBIT(GENERAL) | VTD_DBGBIT(CSR); + +#define VTD_DPRINTF(what, fmt, ...) do { \ + if (vtd_dbgflags & VTD_DBGBIT(what)) { \ + fprintf(stderr, "(vtd)%s: " fmt "\n", __func__, \ + ## __VA_ARGS__); } \ + } while (0) +#else +#define VTD_DPRINTF(what, fmt, ...) do {} while (0) +#endif + +static void vtd_define_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val, + uint64_t wmask, uint64_t w1cmask) +{ + stq_le_p(&s->csr[addr], val); + stq_le_p(&s->wmask[addr], wmask); + stq_le_p(&s->w1cmask[addr], w1cmask); +} + +static void vtd_define_quad_wo(IntelIOMMUState *s, hwaddr addr, uint64_t mask) +{ + stq_le_p(&s->womask[addr], mask); +} + +static void vtd_define_long(IntelIOMMUState *s, hwaddr addr, uint32_t val, + uint32_t wmask, uint32_t w1cmask) +{ + stl_le_p(&s->csr[addr], val); + stl_le_p(&s->wmask[addr], wmask); + stl_le_p(&s->w1cmask[addr], w1cmask); +} + +static void vtd_define_long_wo(IntelIOMMUState *s, hwaddr addr, uint32_t mask) +{ + stl_le_p(&s->womask[addr], mask); +} + +/* "External" get/set operations */ +static void vtd_set_quad(IntelIOMMUState *s, hwaddr addr, uint64_t val) +{ + uint64_t oldval = ldq_le_p(&s->csr[addr]); + uint64_t wmask = ldq_le_p(&s->wmask[addr]); + uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]); + stq_le_p(&s->csr[addr], + ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val)); +} + +static void vtd_set_long(IntelIOMMUState *s, hwaddr addr, uint32_t val) +{ + uint32_t oldval = ldl_le_p(&s->csr[addr]); + uint32_t wmask = ldl_le_p(&s->wmask[addr]); + uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]); + stl_le_p(&s->csr[addr], + ((oldval & ~wmask) | (val & wmask)) & ~(w1cmask & val)); +} + +static uint64_t vtd_get_quad(IntelIOMMUState *s, hwaddr addr) +{ + uint64_t val = ldq_le_p(&s->csr[addr]); + uint64_t womask = ldq_le_p(&s->womask[addr]); + return val & ~womask; +} + +static uint32_t vtd_get_long(IntelIOMMUState *s, hwaddr addr) +{ + uint32_t val = ldl_le_p(&s->csr[addr]); + uint32_t womask = ldl_le_p(&s->womask[addr]); + return val & ~womask; +} + +/* "Internal" get/set operations */ +static uint64_t vtd_get_quad_raw(IntelIOMMUState *s, hwaddr addr) +{ + return ldq_le_p(&s->csr[addr]); +} + +static uint32_t vtd_get_long_raw(IntelIOMMUState *s, hwaddr addr) +{ + return ldl_le_p(&s->csr[addr]); +} + +static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val) +{ + stq_le_p(&s->csr[addr], val); +} + +static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr, + uint32_t clear, uint32_t mask) +{ + uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask; + stl_le_p(&s->csr[addr], new_val); + return new_val; +} + +static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr, + uint64_t clear, uint64_t mask) +{ + uint64_t new_val = (ldq_le_p(&s->csr[addr]) & ~clear) | mask; + stq_le_p(&s->csr[addr], new_val); + return new_val; +} + +/* GHashTable functions */ +static gboolean vtd_uint64_equal(gconstpointer v1, gconstpointer v2) +{ + return *((const uint64_t *)v1) == *((const uint64_t *)v2); +} + +static guint vtd_uint64_hash(gconstpointer v) +{ + return (guint)*(const uint64_t *)v; +} + +static gboolean vtd_hash_remove_by_domain(gpointer key, gpointer value, + gpointer user_data) +{ + VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value; + uint16_t domain_id = *(uint16_t *)user_data; + return entry->domain_id == domain_id; +} + +static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value, + gpointer user_data) +{ + VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value; + VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data; + uint64_t gfn = info->gfn & info->mask; + return (entry->domain_id == info->domain_id) && + ((entry->gfn & info->mask) == gfn); +} + +/* Reset all the gen of VTDAddressSpace to zero and set the gen of + * IntelIOMMUState to 1. + */ +static void vtd_reset_context_cache(IntelIOMMUState *s) +{ + VTDAddressSpace **pvtd_as; + VTDAddressSpace *vtd_as; + uint32_t bus_it; + uint32_t devfn_it; + + VTD_DPRINTF(CACHE, "global context_cache_gen=1"); + for (bus_it = 0; bus_it < VTD_PCI_BUS_MAX; ++bus_it) { + pvtd_as = s->address_spaces[bus_it]; + if (!pvtd_as) { + continue; + } + for (devfn_it = 0; devfn_it < VTD_PCI_DEVFN_MAX; ++devfn_it) { + vtd_as = pvtd_as[devfn_it]; + if (!vtd_as) { + continue; + } + vtd_as->context_cache_entry.context_cache_gen = 0; + } + } + s->context_cache_gen = 1; +} + +static void vtd_reset_iotlb(IntelIOMMUState *s) +{ + assert(s->iotlb); + g_hash_table_remove_all(s->iotlb); +} + +static VTDIOTLBEntry *vtd_lookup_iotlb(IntelIOMMUState *s, uint16_t source_id, + hwaddr addr) +{ + uint64_t key; + + key = (addr >> VTD_PAGE_SHIFT_4K) | + ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT); + return g_hash_table_lookup(s->iotlb, &key); + +} + +static void vtd_update_iotlb(IntelIOMMUState *s, uint16_t source_id, + uint16_t domain_id, hwaddr addr, uint64_t slpte, + bool read_flags, bool write_flags) +{ + VTDIOTLBEntry *entry = g_malloc(sizeof(*entry)); + uint64_t *key = g_malloc(sizeof(*key)); + uint64_t gfn = addr >> VTD_PAGE_SHIFT_4K; + + VTD_DPRINTF(CACHE, "update iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64 + " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr, slpte, + domain_id); + if (g_hash_table_size(s->iotlb) >= VTD_IOTLB_MAX_SIZE) { + VTD_DPRINTF(CACHE, "iotlb exceeds size limit, forced to reset"); + vtd_reset_iotlb(s); + } + + entry->gfn = gfn; + entry->domain_id = domain_id; + entry->slpte = slpte; + entry->read_flags = read_flags; + entry->write_flags = write_flags; + *key = gfn | ((uint64_t)(source_id) << VTD_IOTLB_SID_SHIFT); + g_hash_table_replace(s->iotlb, key, entry); +} + +/* Given the reg addr of both the message data and address, generate an + * interrupt via MSI. + */ +static void vtd_generate_interrupt(IntelIOMMUState *s, hwaddr mesg_addr_reg, + hwaddr mesg_data_reg) +{ + hwaddr addr; + uint32_t data; + + assert(mesg_data_reg < DMAR_REG_SIZE); + assert(mesg_addr_reg < DMAR_REG_SIZE); + + addr = vtd_get_long_raw(s, mesg_addr_reg); + data = vtd_get_long_raw(s, mesg_data_reg); + + VTD_DPRINTF(FLOG, "msi: addr 0x%"PRIx64 " data 0x%"PRIx32, addr, data); + stl_le_phys(&address_space_memory, addr, data); +} + +/* Generate a fault event to software via MSI if conditions are met. + * Notice that the value of FSTS_REG being passed to it should be the one + * before any update. + */ +static void vtd_generate_fault_event(IntelIOMMUState *s, uint32_t pre_fsts) +{ + if (pre_fsts & VTD_FSTS_PPF || pre_fsts & VTD_FSTS_PFO || + pre_fsts & VTD_FSTS_IQE) { + VTD_DPRINTF(FLOG, "there are previous interrupt conditions " + "to be serviced by software, fault event is not generated " + "(FSTS_REG 0x%"PRIx32 ")", pre_fsts); + return; + } + vtd_set_clear_mask_long(s, DMAR_FECTL_REG, 0, VTD_FECTL_IP); + if (vtd_get_long_raw(s, DMAR_FECTL_REG) & VTD_FECTL_IM) { + VTD_DPRINTF(FLOG, "Interrupt Mask set, fault event is not generated"); + } else { + vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG); + vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0); + } +} + +/* Check if the Fault (F) field of the Fault Recording Register referenced by + * @index is Set. + */ +static bool vtd_is_frcd_set(IntelIOMMUState *s, uint16_t index) +{ + /* Each reg is 128-bit */ + hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4); + addr += 8; /* Access the high 64-bit half */ + + assert(index < DMAR_FRCD_REG_NR); + + return vtd_get_quad_raw(s, addr) & VTD_FRCD_F; +} + +/* Update the PPF field of Fault Status Register. + * Should be called whenever change the F field of any fault recording + * registers. + */ +static void vtd_update_fsts_ppf(IntelIOMMUState *s) +{ + uint32_t i; + uint32_t ppf_mask = 0; + + for (i = 0; i < DMAR_FRCD_REG_NR; i++) { + if (vtd_is_frcd_set(s, i)) { + ppf_mask = VTD_FSTS_PPF; + break; + } + } + vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_PPF, ppf_mask); + VTD_DPRINTF(FLOG, "set PPF of FSTS_REG to %d", ppf_mask ? 1 : 0); +} + +static void vtd_set_frcd_and_update_ppf(IntelIOMMUState *s, uint16_t index) +{ + /* Each reg is 128-bit */ + hwaddr addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4); + addr += 8; /* Access the high 64-bit half */ + + assert(index < DMAR_FRCD_REG_NR); + + vtd_set_clear_mask_quad(s, addr, 0, VTD_FRCD_F); + vtd_update_fsts_ppf(s); +} + +/* Must not update F field now, should be done later */ +static void vtd_record_frcd(IntelIOMMUState *s, uint16_t index, + uint16_t source_id, hwaddr addr, + VTDFaultReason fault, bool is_write) +{ + uint64_t hi = 0, lo; + hwaddr frcd_reg_addr = DMAR_FRCD_REG_OFFSET + (((uint64_t)index) << 4); + + assert(index < DMAR_FRCD_REG_NR); + + lo = VTD_FRCD_FI(addr); + hi = VTD_FRCD_SID(source_id) | VTD_FRCD_FR(fault); + if (!is_write) { + hi |= VTD_FRCD_T; + } + vtd_set_quad_raw(s, frcd_reg_addr, lo); + vtd_set_quad_raw(s, frcd_reg_addr + 8, hi); + VTD_DPRINTF(FLOG, "record to FRCD_REG #%"PRIu16 ": hi 0x%"PRIx64 + ", lo 0x%"PRIx64, index, hi, lo); +} + +/* Try to collapse multiple pending faults from the same requester */ +static bool vtd_try_collapse_fault(IntelIOMMUState *s, uint16_t source_id) +{ + uint32_t i; + uint64_t frcd_reg; + hwaddr addr = DMAR_FRCD_REG_OFFSET + 8; /* The high 64-bit half */ + + for (i = 0; i < DMAR_FRCD_REG_NR; i++) { + frcd_reg = vtd_get_quad_raw(s, addr); + VTD_DPRINTF(FLOG, "frcd_reg #%d 0x%"PRIx64, i, frcd_reg); + if ((frcd_reg & VTD_FRCD_F) && + ((frcd_reg & VTD_FRCD_SID_MASK) == source_id)) { + return true; + } + addr += 16; /* 128-bit for each */ + } + return false; +} + +/* Log and report an DMAR (address translation) fault to software */ +static void vtd_report_dmar_fault(IntelIOMMUState *s, uint16_t source_id, + hwaddr addr, VTDFaultReason fault, + bool is_write) +{ + uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG); + + assert(fault < VTD_FR_MAX); + + if (fault == VTD_FR_RESERVED_ERR) { + /* This is not a normal fault reason case. Drop it. */ + return; + } + VTD_DPRINTF(FLOG, "sid 0x%"PRIx16 ", fault %d, addr 0x%"PRIx64 + ", is_write %d", source_id, fault, addr, is_write); + if (fsts_reg & VTD_FSTS_PFO) { + VTD_DPRINTF(FLOG, "new fault is not recorded due to " + "Primary Fault Overflow"); + return; + } + if (vtd_try_collapse_fault(s, source_id)) { + VTD_DPRINTF(FLOG, "new fault is not recorded due to " + "compression of faults"); + return; + } + if (vtd_is_frcd_set(s, s->next_frcd_reg)) { + VTD_DPRINTF(FLOG, "Primary Fault Overflow and " + "new fault is not recorded, set PFO field"); + vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_PFO); + return; + } + + vtd_record_frcd(s, s->next_frcd_reg, source_id, addr, fault, is_write); + + if (fsts_reg & VTD_FSTS_PPF) { + VTD_DPRINTF(FLOG, "there are pending faults already, " + "fault event is not generated"); + vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); + s->next_frcd_reg++; + if (s->next_frcd_reg == DMAR_FRCD_REG_NR) { + s->next_frcd_reg = 0; + } + } else { + vtd_set_clear_mask_long(s, DMAR_FSTS_REG, VTD_FSTS_FRI_MASK, + VTD_FSTS_FRI(s->next_frcd_reg)); + vtd_set_frcd_and_update_ppf(s, s->next_frcd_reg); /* Will set PPF */ + s->next_frcd_reg++; + if (s->next_frcd_reg == DMAR_FRCD_REG_NR) { + s->next_frcd_reg = 0; + } + /* This case actually cause the PPF to be Set. + * So generate fault event (interrupt). + */ + vtd_generate_fault_event(s, fsts_reg); + } +} + +/* Handle Invalidation Queue Errors of queued invalidation interface error + * conditions. + */ +static void vtd_handle_inv_queue_error(IntelIOMMUState *s) +{ + uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG); + + vtd_set_clear_mask_long(s, DMAR_FSTS_REG, 0, VTD_FSTS_IQE); + vtd_generate_fault_event(s, fsts_reg); +} + +/* Set the IWC field and try to generate an invalidation completion interrupt */ +static void vtd_generate_completion_event(IntelIOMMUState *s) +{ + VTD_DPRINTF(INV, "completes an invalidation wait command with " + "Interrupt Flag"); + if (vtd_get_long_raw(s, DMAR_ICS_REG) & VTD_ICS_IWC) { + VTD_DPRINTF(INV, "there is a previous interrupt condition to be " + "serviced by software, " + "new invalidation event is not generated"); + return; + } + vtd_set_clear_mask_long(s, DMAR_ICS_REG, 0, VTD_ICS_IWC); + vtd_set_clear_mask_long(s, DMAR_IECTL_REG, 0, VTD_IECTL_IP); + if (vtd_get_long_raw(s, DMAR_IECTL_REG) & VTD_IECTL_IM) { + VTD_DPRINTF(INV, "IM filed in IECTL_REG is set, new invalidation " + "event is not generated"); + return; + } else { + /* Generate the interrupt event */ + vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG); + vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0); + } +} + +static inline bool vtd_root_entry_present(VTDRootEntry *root) +{ + return root->val & VTD_ROOT_ENTRY_P; +} + +static int vtd_get_root_entry(IntelIOMMUState *s, uint8_t index, + VTDRootEntry *re) +{ + dma_addr_t addr; + + addr = s->root + index * sizeof(*re); + if (dma_memory_read(&address_space_memory, addr, re, sizeof(*re))) { + VTD_DPRINTF(GENERAL, "error: fail to access root-entry at 0x%"PRIx64 + " + %"PRIu8, s->root, index); + re->val = 0; + return -VTD_FR_ROOT_TABLE_INV; + } + re->val = le64_to_cpu(re->val); + return 0; +} + +static inline bool vtd_context_entry_present(VTDContextEntry *context) +{ + return context->lo & VTD_CONTEXT_ENTRY_P; +} + +static int vtd_get_context_entry_from_root(VTDRootEntry *root, uint8_t index, + VTDContextEntry *ce) +{ + dma_addr_t addr; + + if (!vtd_root_entry_present(root)) { + VTD_DPRINTF(GENERAL, "error: root-entry is not present"); + return -VTD_FR_ROOT_ENTRY_P; + } + addr = (root->val & VTD_ROOT_ENTRY_CTP) + index * sizeof(*ce); + if (dma_memory_read(&address_space_memory, addr, ce, sizeof(*ce))) { + VTD_DPRINTF(GENERAL, "error: fail to access context-entry at 0x%"PRIx64 + " + %"PRIu8, + (uint64_t)(root->val & VTD_ROOT_ENTRY_CTP), index); + return -VTD_FR_CONTEXT_TABLE_INV; + } + ce->lo = le64_to_cpu(ce->lo); + ce->hi = le64_to_cpu(ce->hi); + return 0; +} + +static inline dma_addr_t vtd_get_slpt_base_from_context(VTDContextEntry *ce) +{ + return ce->lo & VTD_CONTEXT_ENTRY_SLPTPTR; +} + +/* The shift of an addr for a certain level of paging structure */ +static inline uint32_t vtd_slpt_level_shift(uint32_t level) +{ + return VTD_PAGE_SHIFT_4K + (level - 1) * VTD_SL_LEVEL_BITS; +} + +static inline uint64_t vtd_get_slpte_addr(uint64_t slpte) +{ + return slpte & VTD_SL_PT_BASE_ADDR_MASK; +} + +/* Whether the pte indicates the address of the page frame */ +static inline bool vtd_is_last_slpte(uint64_t slpte, uint32_t level) +{ + return level == VTD_SL_PT_LEVEL || (slpte & VTD_SL_PT_PAGE_SIZE_MASK); +} + +/* Get the content of a spte located in @base_addr[@index] */ +static uint64_t vtd_get_slpte(dma_addr_t base_addr, uint32_t index) +{ + uint64_t slpte; + + assert(index < VTD_SL_PT_ENTRY_NR); + + if (dma_memory_read(&address_space_memory, + base_addr + index * sizeof(slpte), &slpte, + sizeof(slpte))) { + slpte = (uint64_t)-1; + return slpte; + } + slpte = le64_to_cpu(slpte); + return slpte; +} + +/* Given a gpa and the level of paging structure, return the offset of current + * level. + */ +static inline uint32_t vtd_gpa_level_offset(uint64_t gpa, uint32_t level) +{ + return (gpa >> vtd_slpt_level_shift(level)) & + ((1ULL << VTD_SL_LEVEL_BITS) - 1); +} + +/* Check Capability Register to see if the @level of page-table is supported */ +static inline bool vtd_is_level_supported(IntelIOMMUState *s, uint32_t level) +{ + return VTD_CAP_SAGAW_MASK & s->cap & + (1ULL << (level - 2 + VTD_CAP_SAGAW_SHIFT)); +} + +/* Get the page-table level that hardware should use for the second-level + * page-table walk from the Address Width field of context-entry. + */ +static inline uint32_t vtd_get_level_from_context_entry(VTDContextEntry *ce) +{ + return 2 + (ce->hi & VTD_CONTEXT_ENTRY_AW); +} + +static inline uint32_t vtd_get_agaw_from_context_entry(VTDContextEntry *ce) +{ + return 30 + (ce->hi & VTD_CONTEXT_ENTRY_AW) * 9; +} + +static const uint64_t vtd_paging_entry_rsvd_field[] = { + [0] = ~0ULL, + /* For not large page */ + [1] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [2] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [3] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [4] = 0x880ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + /* For large page */ + [5] = 0x800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [6] = 0x1ff800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [7] = 0x3ffff800ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), + [8] = 0x880ULL | ~(VTD_HAW_MASK | VTD_SL_IGN_COM), +}; + +static bool vtd_slpte_nonzero_rsvd(uint64_t slpte, uint32_t level) +{ + if (slpte & VTD_SL_PT_PAGE_SIZE_MASK) { + /* Maybe large page */ + return slpte & vtd_paging_entry_rsvd_field[level + 4]; + } else { + return slpte & vtd_paging_entry_rsvd_field[level]; + } +} + +/* Given the @gpa, get relevant @slptep. @slpte_level will be the last level + * of the translation, can be used for deciding the size of large page. + */ +static int vtd_gpa_to_slpte(VTDContextEntry *ce, uint64_t gpa, bool is_write, + uint64_t *slptep, uint32_t *slpte_level, + bool *reads, bool *writes) +{ + dma_addr_t addr = vtd_get_slpt_base_from_context(ce); + uint32_t level = vtd_get_level_from_context_entry(ce); + uint32_t offset; + uint64_t slpte; + uint32_t ce_agaw = vtd_get_agaw_from_context_entry(ce); + uint64_t access_right_check; + + /* Check if @gpa is above 2^X-1, where X is the minimum of MGAW in CAP_REG + * and AW in context-entry. + */ + if (gpa & ~((1ULL << MIN(ce_agaw, VTD_MGAW)) - 1)) { + VTD_DPRINTF(GENERAL, "error: gpa 0x%"PRIx64 " exceeds limits", gpa); + return -VTD_FR_ADDR_BEYOND_MGAW; + } + + /* FIXME: what is the Atomics request here? */ + access_right_check = is_write ? VTD_SL_W : VTD_SL_R; + + while (true) { + offset = vtd_gpa_level_offset(gpa, level); + slpte = vtd_get_slpte(addr, offset); + + if (slpte == (uint64_t)-1) { + VTD_DPRINTF(GENERAL, "error: fail to access second-level paging " + "entry at level %"PRIu32 " for gpa 0x%"PRIx64, + level, gpa); + if (level == vtd_get_level_from_context_entry(ce)) { + /* Invalid programming of context-entry */ + return -VTD_FR_CONTEXT_ENTRY_INV; + } else { + return -VTD_FR_PAGING_ENTRY_INV; + } + } + *reads = (*reads) && (slpte & VTD_SL_R); + *writes = (*writes) && (slpte & VTD_SL_W); + if (!(slpte & access_right_check)) { + VTD_DPRINTF(GENERAL, "error: lack of %s permission for " + "gpa 0x%"PRIx64 " slpte 0x%"PRIx64, + (is_write ? "write" : "read"), gpa, slpte); + return is_write ? -VTD_FR_WRITE : -VTD_FR_READ; + } + if (vtd_slpte_nonzero_rsvd(slpte, level)) { + VTD_DPRINTF(GENERAL, "error: non-zero reserved field in second " + "level paging entry level %"PRIu32 " slpte 0x%"PRIx64, + level, slpte); + return -VTD_FR_PAGING_ENTRY_RSVD; + } + + if (vtd_is_last_slpte(slpte, level)) { + *slptep = slpte; + *slpte_level = level; + return 0; + } + addr = vtd_get_slpte_addr(slpte); + level--; + } +} + +/* Map a device to its corresponding domain (context-entry) */ +static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num, + uint8_t devfn, VTDContextEntry *ce) +{ + VTDRootEntry re; + int ret_fr; + + ret_fr = vtd_get_root_entry(s, bus_num, &re); + if (ret_fr) { + return ret_fr; + } + + if (!vtd_root_entry_present(&re)) { + VTD_DPRINTF(GENERAL, "error: root-entry #%"PRIu8 " is not present", + bus_num); + return -VTD_FR_ROOT_ENTRY_P; + } else if (re.rsvd || (re.val & VTD_ROOT_ENTRY_RSVD)) { + VTD_DPRINTF(GENERAL, "error: non-zero reserved field in root-entry " + "hi 0x%"PRIx64 " lo 0x%"PRIx64, re.rsvd, re.val); + return -VTD_FR_ROOT_ENTRY_RSVD; + } + + ret_fr = vtd_get_context_entry_from_root(&re, devfn, ce); + if (ret_fr) { + return ret_fr; + } + + if (!vtd_context_entry_present(ce)) { + VTD_DPRINTF(GENERAL, + "error: context-entry #%"PRIu8 "(bus #%"PRIu8 ") " + "is not present", devfn, bus_num); + return -VTD_FR_CONTEXT_ENTRY_P; + } else if ((ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI) || + (ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO)) { + VTD_DPRINTF(GENERAL, + "error: non-zero reserved field in context-entry " + "hi 0x%"PRIx64 " lo 0x%"PRIx64, ce->hi, ce->lo); + return -VTD_FR_CONTEXT_ENTRY_RSVD; + } + /* Check if the programming of context-entry is valid */ + if (!vtd_is_level_supported(s, vtd_get_level_from_context_entry(ce))) { + VTD_DPRINTF(GENERAL, "error: unsupported Address Width value in " + "context-entry hi 0x%"PRIx64 " lo 0x%"PRIx64, + ce->hi, ce->lo); + return -VTD_FR_CONTEXT_ENTRY_INV; + } else if (ce->lo & VTD_CONTEXT_ENTRY_TT) { + VTD_DPRINTF(GENERAL, "error: unsupported Translation Type in " + "context-entry hi 0x%"PRIx64 " lo 0x%"PRIx64, + ce->hi, ce->lo); + return -VTD_FR_CONTEXT_ENTRY_INV; + } + return 0; +} + +static inline uint16_t vtd_make_source_id(uint8_t bus_num, uint8_t devfn) +{ + return ((bus_num & 0xffUL) << 8) | (devfn & 0xffUL); +} + +static const bool vtd_qualified_faults[] = { + [VTD_FR_RESERVED] = false, + [VTD_FR_ROOT_ENTRY_P] = false, + [VTD_FR_CONTEXT_ENTRY_P] = true, + [VTD_FR_CONTEXT_ENTRY_INV] = true, + [VTD_FR_ADDR_BEYOND_MGAW] = true, + [VTD_FR_WRITE] = true, + [VTD_FR_READ] = true, + [VTD_FR_PAGING_ENTRY_INV] = true, + [VTD_FR_ROOT_TABLE_INV] = false, + [VTD_FR_CONTEXT_TABLE_INV] = false, + [VTD_FR_ROOT_ENTRY_RSVD] = false, + [VTD_FR_PAGING_ENTRY_RSVD] = true, + [VTD_FR_CONTEXT_ENTRY_TT] = true, + [VTD_FR_RESERVED_ERR] = false, + [VTD_FR_MAX] = false, +}; + +/* To see if a fault condition is "qualified", which is reported to software + * only if the FPD field in the context-entry used to process the faulting + * request is 0. + */ +static inline bool vtd_is_qualified_fault(VTDFaultReason fault) +{ + return vtd_qualified_faults[fault]; +} + +static inline bool vtd_is_interrupt_addr(hwaddr addr) +{ + return VTD_INTERRUPT_ADDR_FIRST <= addr && addr <= VTD_INTERRUPT_ADDR_LAST; +} + +/* Map dev to context-entry then do a paging-structures walk to do a iommu + * translation. + * @bus_num: The bus number + * @devfn: The devfn, which is the combined of device and function number + * @is_write: The access is a write operation + * @entry: IOMMUTLBEntry that contain the addr to be translated and result + */ +static void vtd_do_iommu_translate(VTDAddressSpace *vtd_as, uint8_t bus_num, + uint8_t devfn, hwaddr addr, bool is_write, + IOMMUTLBEntry *entry) +{ + IntelIOMMUState *s = vtd_as->iommu_state; + VTDContextEntry ce; + VTDContextCacheEntry *cc_entry = &vtd_as->context_cache_entry; + uint64_t slpte; + uint32_t level; + uint16_t source_id = vtd_make_source_id(bus_num, devfn); + int ret_fr; + bool is_fpd_set = false; + bool reads = true; + bool writes = true; + VTDIOTLBEntry *iotlb_entry; + + /* Check if the request is in interrupt address range */ + if (vtd_is_interrupt_addr(addr)) { + if (is_write) { + /* FIXME: since we don't know the length of the access here, we + * treat Non-DWORD length write requests without PASID as + * interrupt requests, too. Withoud interrupt remapping support, + * we just use 1:1 mapping. + */ + VTD_DPRINTF(MMU, "write request to interrupt address " + "gpa 0x%"PRIx64, addr); + entry->iova = addr & VTD_PAGE_MASK_4K; + entry->translated_addr = addr & VTD_PAGE_MASK_4K; + entry->addr_mask = ~VTD_PAGE_MASK_4K; + entry->perm = IOMMU_WO; + return; + } else { + VTD_DPRINTF(GENERAL, "error: read request from interrupt address " + "gpa 0x%"PRIx64, addr); + vtd_report_dmar_fault(s, source_id, addr, VTD_FR_READ, is_write); + return; + } + } + /* Try to fetch slpte form IOTLB */ + iotlb_entry = vtd_lookup_iotlb(s, source_id, addr); + if (iotlb_entry) { + VTD_DPRINTF(CACHE, "hit iotlb sid 0x%"PRIx16 " gpa 0x%"PRIx64 + " slpte 0x%"PRIx64 " did 0x%"PRIx16, source_id, addr, + iotlb_entry->slpte, iotlb_entry->domain_id); + slpte = iotlb_entry->slpte; + reads = iotlb_entry->read_flags; + writes = iotlb_entry->write_flags; + goto out; + } + /* Try to fetch context-entry from cache first */ + if (cc_entry->context_cache_gen == s->context_cache_gen) { + VTD_DPRINTF(CACHE, "hit context-cache bus %d devfn %d " + "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 ")", + bus_num, devfn, cc_entry->context_entry.hi, + cc_entry->context_entry.lo, cc_entry->context_cache_gen); + ce = cc_entry->context_entry; + is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD; + } else { + ret_fr = vtd_dev_to_context_entry(s, bus_num, devfn, &ce); + is_fpd_set = ce.lo & VTD_CONTEXT_ENTRY_FPD; + if (ret_fr) { + ret_fr = -ret_fr; + if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) { + VTD_DPRINTF(FLOG, "fault processing is disabled for DMA " + "requests through this context-entry " + "(with FPD Set)"); + } else { + vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write); + } + return; + } + /* Update context-cache */ + VTD_DPRINTF(CACHE, "update context-cache bus %d devfn %d " + "(hi %"PRIx64 " lo %"PRIx64 " gen %"PRIu32 "->%"PRIu32 ")", + bus_num, devfn, ce.hi, ce.lo, + cc_entry->context_cache_gen, s->context_cache_gen); + cc_entry->context_entry = ce; + cc_entry->context_cache_gen = s->context_cache_gen; + } + + ret_fr = vtd_gpa_to_slpte(&ce, addr, is_write, &slpte, &level, + &reads, &writes); + if (ret_fr) { + ret_fr = -ret_fr; + if (is_fpd_set && vtd_is_qualified_fault(ret_fr)) { + VTD_DPRINTF(FLOG, "fault processing is disabled for DMA requests " + "through this context-entry (with FPD Set)"); + } else { + vtd_report_dmar_fault(s, source_id, addr, ret_fr, is_write); + } + return; + } + + vtd_update_iotlb(s, source_id, VTD_CONTEXT_ENTRY_DID(ce.hi), addr, slpte, + reads, writes); +out: + entry->iova = addr & VTD_PAGE_MASK_4K; + entry->translated_addr = vtd_get_slpte_addr(slpte) & VTD_PAGE_MASK_4K; + entry->addr_mask = ~VTD_PAGE_MASK_4K; + entry->perm = (writes ? 2 : 0) + (reads ? 1 : 0); +} + +static void vtd_root_table_setup(IntelIOMMUState *s) +{ + s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG); + s->root_extended = s->root & VTD_RTADDR_RTT; + s->root &= VTD_RTADDR_ADDR_MASK; + + VTD_DPRINTF(CSR, "root_table addr 0x%"PRIx64 " %s", s->root, + (s->root_extended ? "(extended)" : "")); +} + +static void vtd_context_global_invalidate(IntelIOMMUState *s) +{ + s->context_cache_gen++; + if (s->context_cache_gen == VTD_CONTEXT_CACHE_GEN_MAX) { + vtd_reset_context_cache(s); + } +} + +/* Do a context-cache device-selective invalidation. + * @func_mask: FM field after shifting + */ +static void vtd_context_device_invalidate(IntelIOMMUState *s, + uint16_t source_id, + uint16_t func_mask) +{ + uint16_t mask; + VTDAddressSpace **pvtd_as; + VTDAddressSpace *vtd_as; + uint16_t devfn; + uint16_t devfn_it; + + switch (func_mask & 3) { + case 0: + mask = 0; /* No bits in the SID field masked */ + break; + case 1: + mask = 4; /* Mask bit 2 in the SID field */ + break; + case 2: + mask = 6; /* Mask bit 2:1 in the SID field */ + break; + case 3: + mask = 7; /* Mask bit 2:0 in the SID field */ + break; + } + VTD_DPRINTF(INV, "device-selective invalidation source 0x%"PRIx16 + " mask %"PRIu16, source_id, mask); + pvtd_as = s->address_spaces[VTD_SID_TO_BUS(source_id)]; + if (pvtd_as) { + devfn = VTD_SID_TO_DEVFN(source_id); + for (devfn_it = 0; devfn_it < VTD_PCI_DEVFN_MAX; ++devfn_it) { + vtd_as = pvtd_as[devfn_it]; + if (vtd_as && ((devfn_it & mask) == (devfn & mask))) { + VTD_DPRINTF(INV, "invalidate context-cahce of devfn 0x%"PRIx16, + devfn_it); + vtd_as->context_cache_entry.context_cache_gen = 0; + } + } + } +} + +/* Context-cache invalidation + * Returns the Context Actual Invalidation Granularity. + * @val: the content of the CCMD_REG + */ +static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val) +{ + uint64_t caig; + uint64_t type = val & VTD_CCMD_CIRG_MASK; + + switch (type) { + case VTD_CCMD_DOMAIN_INVL: + VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16, + (uint16_t)VTD_CCMD_DID(val)); + /* Fall through */ + case VTD_CCMD_GLOBAL_INVL: + VTD_DPRINTF(INV, "global invalidation"); + caig = VTD_CCMD_GLOBAL_INVL_A; + vtd_context_global_invalidate(s); + break; + + case VTD_CCMD_DEVICE_INVL: + caig = VTD_CCMD_DEVICE_INVL_A; + vtd_context_device_invalidate(s, VTD_CCMD_SID(val), VTD_CCMD_FM(val)); + break; + + default: + VTD_DPRINTF(GENERAL, "error: invalid granularity"); + caig = 0; + } + return caig; +} + +static void vtd_iotlb_global_invalidate(IntelIOMMUState *s) +{ + vtd_reset_iotlb(s); +} + +static void vtd_iotlb_domain_invalidate(IntelIOMMUState *s, uint16_t domain_id) +{ + g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_domain, + &domain_id); +} + +static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id, + hwaddr addr, uint8_t am) +{ + VTDIOTLBPageInvInfo info; + + assert(am <= VTD_MAMV); + info.domain_id = domain_id; + info.gfn = addr >> VTD_PAGE_SHIFT_4K; + info.mask = ~((1 << am) - 1); + g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info); +} + +/* Flush IOTLB + * Returns the IOTLB Actual Invalidation Granularity. + * @val: the content of the IOTLB_REG + */ +static uint64_t vtd_iotlb_flush(IntelIOMMUState *s, uint64_t val) +{ + uint64_t iaig; + uint64_t type = val & VTD_TLB_FLUSH_GRANU_MASK; + uint16_t domain_id; + hwaddr addr; + uint8_t am; + + switch (type) { + case VTD_TLB_GLOBAL_FLUSH: + VTD_DPRINTF(INV, "global invalidation"); + iaig = VTD_TLB_GLOBAL_FLUSH_A; + vtd_iotlb_global_invalidate(s); + break; + + case VTD_TLB_DSI_FLUSH: + domain_id = VTD_TLB_DID(val); + VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16, + domain_id); + iaig = VTD_TLB_DSI_FLUSH_A; + vtd_iotlb_domain_invalidate(s, domain_id); + break; + + case VTD_TLB_PSI_FLUSH: + domain_id = VTD_TLB_DID(val); + addr = vtd_get_quad_raw(s, DMAR_IVA_REG); + am = VTD_IVA_AM(addr); + addr = VTD_IVA_ADDR(addr); + VTD_DPRINTF(INV, "page-selective invalidation domain 0x%"PRIx16 + " addr 0x%"PRIx64 " mask %"PRIu8, domain_id, addr, am); + if (am > VTD_MAMV) { + VTD_DPRINTF(GENERAL, "error: supported max address mask value is " + "%"PRIu8, (uint8_t)VTD_MAMV); + iaig = 0; + break; + } + iaig = VTD_TLB_PSI_FLUSH_A; + vtd_iotlb_page_invalidate(s, domain_id, addr, am); + break; + + default: + VTD_DPRINTF(GENERAL, "error: invalid granularity"); + iaig = 0; + } + return iaig; +} + +static inline bool vtd_queued_inv_enable_check(IntelIOMMUState *s) +{ + return s->iq_tail == 0; +} + +static inline bool vtd_queued_inv_disable_check(IntelIOMMUState *s) +{ + return s->qi_enabled && (s->iq_tail == s->iq_head) && + (s->iq_last_desc_type == VTD_INV_DESC_WAIT); +} + +static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en) +{ + uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG); + + VTD_DPRINTF(INV, "Queued Invalidation Enable %s", (en ? "on" : "off")); + if (en) { + if (vtd_queued_inv_enable_check(s)) { + s->iq = iqa_val & VTD_IQA_IQA_MASK; + /* 2^(x+8) entries */ + s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8); + s->qi_enabled = true; + VTD_DPRINTF(INV, "DMAR_IQA_REG 0x%"PRIx64, iqa_val); + VTD_DPRINTF(INV, "Invalidation Queue addr 0x%"PRIx64 " size %d", + s->iq, s->iq_size); + /* Ok - report back to driver */ + vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES); + } else { + VTD_DPRINTF(GENERAL, "error: can't enable Queued Invalidation: " + "tail %"PRIu16, s->iq_tail); + } + } else { + if (vtd_queued_inv_disable_check(s)) { + /* disable Queued Invalidation */ + vtd_set_quad_raw(s, DMAR_IQH_REG, 0); + s->iq_head = 0; + s->qi_enabled = false; + /* Ok - report back to driver */ + vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0); + } else { + VTD_DPRINTF(GENERAL, "error: can't disable Queued Invalidation: " + "head %"PRIu16 ", tail %"PRIu16 + ", last_descriptor %"PRIu8, + s->iq_head, s->iq_tail, s->iq_last_desc_type); + } + } +} + +/* Set Root Table Pointer */ +static void vtd_handle_gcmd_srtp(IntelIOMMUState *s) +{ + VTD_DPRINTF(CSR, "set Root Table Pointer"); + + vtd_root_table_setup(s); + /* Ok - report back to driver */ + vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_RTPS); +} + +/* Handle Translation Enable/Disable */ +static void vtd_handle_gcmd_te(IntelIOMMUState *s, bool en) +{ + VTD_DPRINTF(CSR, "Translation Enable %s", (en ? "on" : "off")); + + if (en) { + s->dmar_enabled = true; + /* Ok - report back to driver */ + vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_TES); + } else { + s->dmar_enabled = false; + + /* Clear the index of Fault Recording Register */ + s->next_frcd_reg = 0; + /* Ok - report back to driver */ + vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_TES, 0); + } +} + +/* Handle write to Global Command Register */ +static void vtd_handle_gcmd_write(IntelIOMMUState *s) +{ + uint32_t status = vtd_get_long_raw(s, DMAR_GSTS_REG); + uint32_t val = vtd_get_long_raw(s, DMAR_GCMD_REG); + uint32_t changed = status ^ val; + + VTD_DPRINTF(CSR, "value 0x%"PRIx32 " status 0x%"PRIx32, val, status); + if (changed & VTD_GCMD_TE) { + /* Translation enable/disable */ + vtd_handle_gcmd_te(s, val & VTD_GCMD_TE); + } + if (val & VTD_GCMD_SRTP) { + /* Set/update the root-table pointer */ + vtd_handle_gcmd_srtp(s); + } + if (changed & VTD_GCMD_QIE) { + /* Queued Invalidation Enable */ + vtd_handle_gcmd_qie(s, val & VTD_GCMD_QIE); + } +} + +/* Handle write to Context Command Register */ +static void vtd_handle_ccmd_write(IntelIOMMUState *s) +{ + uint64_t ret; + uint64_t val = vtd_get_quad_raw(s, DMAR_CCMD_REG); + + /* Context-cache invalidation request */ + if (val & VTD_CCMD_ICC) { + if (s->qi_enabled) { + VTD_DPRINTF(GENERAL, "error: Queued Invalidation enabled, " + "should not use register-based invalidation"); + return; + } + ret = vtd_context_cache_invalidate(s, val); + /* Invalidation completed. Change something to show */ + vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_ICC, 0ULL); + ret = vtd_set_clear_mask_quad(s, DMAR_CCMD_REG, VTD_CCMD_CAIG_MASK, + ret); + VTD_DPRINTF(INV, "CCMD_REG write-back val: 0x%"PRIx64, ret); + } +} + +/* Handle write to IOTLB Invalidation Register */ +static void vtd_handle_iotlb_write(IntelIOMMUState *s) +{ + uint64_t ret; + uint64_t val = vtd_get_quad_raw(s, DMAR_IOTLB_REG); + + /* IOTLB invalidation request */ + if (val & VTD_TLB_IVT) { + if (s->qi_enabled) { + VTD_DPRINTF(GENERAL, "error: Queued Invalidation enabled, " + "should not use register-based invalidation"); + return; + } + ret = vtd_iotlb_flush(s, val); + /* Invalidation completed. Change something to show */ + vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, VTD_TLB_IVT, 0ULL); + ret = vtd_set_clear_mask_quad(s, DMAR_IOTLB_REG, + VTD_TLB_FLUSH_GRANU_MASK_A, ret); + VTD_DPRINTF(INV, "IOTLB_REG write-back val: 0x%"PRIx64, ret); + } +} + +/* Fetch an Invalidation Descriptor from the Invalidation Queue */ +static bool vtd_get_inv_desc(dma_addr_t base_addr, uint32_t offset, + VTDInvDesc *inv_desc) +{ + dma_addr_t addr = base_addr + offset * sizeof(*inv_desc); + if (dma_memory_read(&address_space_memory, addr, inv_desc, + sizeof(*inv_desc))) { + VTD_DPRINTF(GENERAL, "error: fail to fetch Invalidation Descriptor " + "base_addr 0x%"PRIx64 " offset %"PRIu32, base_addr, offset); + inv_desc->lo = 0; + inv_desc->hi = 0; + + return false; + } + inv_desc->lo = le64_to_cpu(inv_desc->lo); + inv_desc->hi = le64_to_cpu(inv_desc->hi); + return true; +} + +static bool vtd_process_wait_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc) +{ + if ((inv_desc->hi & VTD_INV_DESC_WAIT_RSVD_HI) || + (inv_desc->lo & VTD_INV_DESC_WAIT_RSVD_LO)) { + VTD_DPRINTF(GENERAL, "error: non-zero reserved field in Invalidation " + "Wait Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64, + inv_desc->hi, inv_desc->lo); + return false; + } + if (inv_desc->lo & VTD_INV_DESC_WAIT_SW) { + /* Status Write */ + uint32_t status_data = (uint32_t)(inv_desc->lo >> + VTD_INV_DESC_WAIT_DATA_SHIFT); + + assert(!(inv_desc->lo & VTD_INV_DESC_WAIT_IF)); + + /* FIXME: need to be masked with HAW? */ + dma_addr_t status_addr = inv_desc->hi; + VTD_DPRINTF(INV, "status data 0x%x, status addr 0x%"PRIx64, + status_data, status_addr); + status_data = cpu_to_le32(status_data); + if (dma_memory_write(&address_space_memory, status_addr, &status_data, + sizeof(status_data))) { + VTD_DPRINTF(GENERAL, "error: fail to perform a coherent write"); + return false; + } + } else if (inv_desc->lo & VTD_INV_DESC_WAIT_IF) { + /* Interrupt flag */ + VTD_DPRINTF(INV, "Invalidation Wait Descriptor interrupt completion"); + vtd_generate_completion_event(s); + } else { + VTD_DPRINTF(GENERAL, "error: invalid Invalidation Wait Descriptor: " + "hi 0x%"PRIx64 " lo 0x%"PRIx64, inv_desc->hi, inv_desc->lo); + return false; + } + return true; +} + +static bool vtd_process_context_cache_desc(IntelIOMMUState *s, + VTDInvDesc *inv_desc) +{ + if ((inv_desc->lo & VTD_INV_DESC_CC_RSVD) || inv_desc->hi) { + VTD_DPRINTF(GENERAL, "error: non-zero reserved field in Context-cache " + "Invalidate Descriptor"); + return false; + } + switch (inv_desc->lo & VTD_INV_DESC_CC_G) { + case VTD_INV_DESC_CC_DOMAIN: + VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16, + (uint16_t)VTD_INV_DESC_CC_DID(inv_desc->lo)); + /* Fall through */ + case VTD_INV_DESC_CC_GLOBAL: + VTD_DPRINTF(INV, "global invalidation"); + vtd_context_global_invalidate(s); + break; + + case VTD_INV_DESC_CC_DEVICE: + vtd_context_device_invalidate(s, VTD_INV_DESC_CC_SID(inv_desc->lo), + VTD_INV_DESC_CC_FM(inv_desc->lo)); + break; + + default: + VTD_DPRINTF(GENERAL, "error: invalid granularity in Context-cache " + "Invalidate Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64, + inv_desc->hi, inv_desc->lo); + return false; + } + return true; +} + +static bool vtd_process_iotlb_desc(IntelIOMMUState *s, VTDInvDesc *inv_desc) +{ + uint16_t domain_id; + uint8_t am; + hwaddr addr; + + if ((inv_desc->lo & VTD_INV_DESC_IOTLB_RSVD_LO) || + (inv_desc->hi & VTD_INV_DESC_IOTLB_RSVD_HI)) { + VTD_DPRINTF(GENERAL, "error: non-zero reserved field in IOTLB " + "Invalidate Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64, + inv_desc->hi, inv_desc->lo); + return false; + } + + switch (inv_desc->lo & VTD_INV_DESC_IOTLB_G) { + case VTD_INV_DESC_IOTLB_GLOBAL: + VTD_DPRINTF(INV, "global invalidation"); + vtd_iotlb_global_invalidate(s); + break; + + case VTD_INV_DESC_IOTLB_DOMAIN: + domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo); + VTD_DPRINTF(INV, "domain-selective invalidation domain 0x%"PRIx16, + domain_id); + vtd_iotlb_domain_invalidate(s, domain_id); + break; + + case VTD_INV_DESC_IOTLB_PAGE: + domain_id = VTD_INV_DESC_IOTLB_DID(inv_desc->lo); + addr = VTD_INV_DESC_IOTLB_ADDR(inv_desc->hi); + am = VTD_INV_DESC_IOTLB_AM(inv_desc->hi); + VTD_DPRINTF(INV, "page-selective invalidation domain 0x%"PRIx16 + " addr 0x%"PRIx64 " mask %"PRIu8, domain_id, addr, am); + if (am > VTD_MAMV) { + VTD_DPRINTF(GENERAL, "error: supported max address mask value is " + "%"PRIu8, (uint8_t)VTD_MAMV); + return false; + } + vtd_iotlb_page_invalidate(s, domain_id, addr, am); + break; + + default: + VTD_DPRINTF(GENERAL, "error: invalid granularity in IOTLB Invalidate " + "Descriptor hi 0x%"PRIx64 " lo 0x%"PRIx64, + inv_desc->hi, inv_desc->lo); + return false; + } + return true; +} + +static bool vtd_process_inv_desc(IntelIOMMUState *s) +{ + VTDInvDesc inv_desc; + uint8_t desc_type; + + VTD_DPRINTF(INV, "iq head %"PRIu16, s->iq_head); + if (!vtd_get_inv_desc(s->iq, s->iq_head, &inv_desc)) { + s->iq_last_desc_type = VTD_INV_DESC_NONE; + return false; + } + desc_type = inv_desc.lo & VTD_INV_DESC_TYPE; + /* FIXME: should update at first or at last? */ + s->iq_last_desc_type = desc_type; + + switch (desc_type) { + case VTD_INV_DESC_CC: + VTD_DPRINTF(INV, "Context-cache Invalidate Descriptor hi 0x%"PRIx64 + " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo); + if (!vtd_process_context_cache_desc(s, &inv_desc)) { + return false; + } + break; + + case VTD_INV_DESC_IOTLB: + VTD_DPRINTF(INV, "IOTLB Invalidate Descriptor hi 0x%"PRIx64 + " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo); + if (!vtd_process_iotlb_desc(s, &inv_desc)) { + return false; + } + break; + + case VTD_INV_DESC_WAIT: + VTD_DPRINTF(INV, "Invalidation Wait Descriptor hi 0x%"PRIx64 + " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo); + if (!vtd_process_wait_desc(s, &inv_desc)) { + return false; + } + break; + + default: + VTD_DPRINTF(GENERAL, "error: unkonw Invalidation Descriptor type " + "hi 0x%"PRIx64 " lo 0x%"PRIx64 " type %"PRIu8, + inv_desc.hi, inv_desc.lo, desc_type); + return false; + } + s->iq_head++; + if (s->iq_head == s->iq_size) { + s->iq_head = 0; + } + return true; +} + +/* Try to fetch and process more Invalidation Descriptors */ +static void vtd_fetch_inv_desc(IntelIOMMUState *s) +{ + VTD_DPRINTF(INV, "fetch Invalidation Descriptors"); + if (s->iq_tail >= s->iq_size) { + /* Detects an invalid Tail pointer */ + VTD_DPRINTF(GENERAL, "error: iq_tail is %"PRIu16 + " while iq_size is %"PRIu16, s->iq_tail, s->iq_size); + vtd_handle_inv_queue_error(s); + return; + } + while (s->iq_head != s->iq_tail) { + if (!vtd_process_inv_desc(s)) { + /* Invalidation Queue Errors */ + vtd_handle_inv_queue_error(s); + break; + } + /* Must update the IQH_REG in time */ + vtd_set_quad_raw(s, DMAR_IQH_REG, + (((uint64_t)(s->iq_head)) << VTD_IQH_QH_SHIFT) & + VTD_IQH_QH_MASK); + } +} + +/* Handle write to Invalidation Queue Tail Register */ +static void vtd_handle_iqt_write(IntelIOMMUState *s) +{ + uint64_t val = vtd_get_quad_raw(s, DMAR_IQT_REG); + + s->iq_tail = VTD_IQT_QT(val); + VTD_DPRINTF(INV, "set iq tail %"PRIu16, s->iq_tail); + if (s->qi_enabled && !(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) { + /* Process Invalidation Queue here */ + vtd_fetch_inv_desc(s); + } +} + +static void vtd_handle_fsts_write(IntelIOMMUState *s) +{ + uint32_t fsts_reg = vtd_get_long_raw(s, DMAR_FSTS_REG); + uint32_t fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG); + uint32_t status_fields = VTD_FSTS_PFO | VTD_FSTS_PPF | VTD_FSTS_IQE; + + if ((fectl_reg & VTD_FECTL_IP) && !(fsts_reg & status_fields)) { + vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0); + VTD_DPRINTF(FLOG, "all pending interrupt conditions serviced, clear " + "IP field of FECTL_REG"); + } + /* FIXME: when IQE is Clear, should we try to fetch some Invalidation + * Descriptors if there are any when Queued Invalidation is enabled? + */ +} + +static void vtd_handle_fectl_write(IntelIOMMUState *s) +{ + uint32_t fectl_reg; + /* FIXME: when software clears the IM field, check the IP field. But do we + * need to compare the old value and the new value to conclude that + * software clears the IM field? Or just check if the IM field is zero? + */ + fectl_reg = vtd_get_long_raw(s, DMAR_FECTL_REG); + if ((fectl_reg & VTD_FECTL_IP) && !(fectl_reg & VTD_FECTL_IM)) { + vtd_generate_interrupt(s, DMAR_FEADDR_REG, DMAR_FEDATA_REG); + vtd_set_clear_mask_long(s, DMAR_FECTL_REG, VTD_FECTL_IP, 0); + VTD_DPRINTF(FLOG, "IM field is cleared, generate " + "fault event interrupt"); + } +} + +static void vtd_handle_ics_write(IntelIOMMUState *s) +{ + uint32_t ics_reg = vtd_get_long_raw(s, DMAR_ICS_REG); + uint32_t iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG); + + if ((iectl_reg & VTD_IECTL_IP) && !(ics_reg & VTD_ICS_IWC)) { + vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0); + VTD_DPRINTF(INV, "pending completion interrupt condition serviced, " + "clear IP field of IECTL_REG"); + } +} + +static void vtd_handle_iectl_write(IntelIOMMUState *s) +{ + uint32_t iectl_reg; + /* FIXME: when software clears the IM field, check the IP field. But do we + * need to compare the old value and the new value to conclude that + * software clears the IM field? Or just check if the IM field is zero? + */ + iectl_reg = vtd_get_long_raw(s, DMAR_IECTL_REG); + if ((iectl_reg & VTD_IECTL_IP) && !(iectl_reg & VTD_IECTL_IM)) { + vtd_generate_interrupt(s, DMAR_IEADDR_REG, DMAR_IEDATA_REG); + vtd_set_clear_mask_long(s, DMAR_IECTL_REG, VTD_IECTL_IP, 0); + VTD_DPRINTF(INV, "IM field is cleared, generate " + "invalidation event interrupt"); + } +} + +static uint64_t vtd_mem_read(void *opaque, hwaddr addr, unsigned size) +{ + IntelIOMMUState *s = opaque; + uint64_t val; + + if (addr + size > DMAR_REG_SIZE) { + VTD_DPRINTF(GENERAL, "error: addr outside region: max 0x%"PRIx64 + ", got 0x%"PRIx64 " %d", + (uint64_t)DMAR_REG_SIZE, addr, size); + return (uint64_t)-1; + } + + switch (addr) { + /* Root Table Address Register, 64-bit */ + case DMAR_RTADDR_REG: + if (size == 4) { + val = s->root & ((1ULL << 32) - 1); + } else { + val = s->root; + } + break; + + case DMAR_RTADDR_REG_HI: + assert(size == 4); + val = s->root >> 32; + break; + + /* Invalidation Queue Address Register, 64-bit */ + case DMAR_IQA_REG: + val = s->iq | (vtd_get_quad(s, DMAR_IQA_REG) & VTD_IQA_QS); + if (size == 4) { + val = val & ((1ULL << 32) - 1); + } + break; + + case DMAR_IQA_REG_HI: + assert(size == 4); + val = s->iq >> 32; + break; + + default: + if (size == 4) { + val = vtd_get_long(s, addr); + } else { + val = vtd_get_quad(s, addr); + } + } + VTD_DPRINTF(CSR, "addr 0x%"PRIx64 " size %d val 0x%"PRIx64, + addr, size, val); + return val; +} + +static void vtd_mem_write(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + IntelIOMMUState *s = opaque; + + if (addr + size > DMAR_REG_SIZE) { + VTD_DPRINTF(GENERAL, "error: addr outside region: max 0x%"PRIx64 + ", got 0x%"PRIx64 " %d", + (uint64_t)DMAR_REG_SIZE, addr, size); + return; + } + + switch (addr) { + /* Global Command Register, 32-bit */ + case DMAR_GCMD_REG: + VTD_DPRINTF(CSR, "DMAR_GCMD_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + vtd_set_long(s, addr, val); + vtd_handle_gcmd_write(s); + break; + + /* Context Command Register, 64-bit */ + case DMAR_CCMD_REG: + VTD_DPRINTF(CSR, "DMAR_CCMD_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + vtd_handle_ccmd_write(s); + } + break; + + case DMAR_CCMD_REG_HI: + VTD_DPRINTF(CSR, "DMAR_CCMD_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_ccmd_write(s); + break; + + /* IOTLB Invalidation Register, 64-bit */ + case DMAR_IOTLB_REG: + VTD_DPRINTF(INV, "DMAR_IOTLB_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + vtd_handle_iotlb_write(s); + } + break; + + case DMAR_IOTLB_REG_HI: + VTD_DPRINTF(INV, "DMAR_IOTLB_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_iotlb_write(s); + break; + + /* Invalidate Address Register, 64-bit */ + case DMAR_IVA_REG: + VTD_DPRINTF(INV, "DMAR_IVA_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + break; + + case DMAR_IVA_REG_HI: + VTD_DPRINTF(INV, "DMAR_IVA_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Fault Status Register, 32-bit */ + case DMAR_FSTS_REG: + VTD_DPRINTF(FLOG, "DMAR_FSTS_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_fsts_write(s); + break; + + /* Fault Event Control Register, 32-bit */ + case DMAR_FECTL_REG: + VTD_DPRINTF(FLOG, "DMAR_FECTL_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_fectl_write(s); + break; + + /* Fault Event Data Register, 32-bit */ + case DMAR_FEDATA_REG: + VTD_DPRINTF(FLOG, "DMAR_FEDATA_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Fault Event Address Register, 32-bit */ + case DMAR_FEADDR_REG: + VTD_DPRINTF(FLOG, "DMAR_FEADDR_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Fault Event Upper Address Register, 32-bit */ + case DMAR_FEUADDR_REG: + VTD_DPRINTF(FLOG, "DMAR_FEUADDR_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Protected Memory Enable Register, 32-bit */ + case DMAR_PMEN_REG: + VTD_DPRINTF(CSR, "DMAR_PMEN_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Root Table Address Register, 64-bit */ + case DMAR_RTADDR_REG: + VTD_DPRINTF(CSR, "DMAR_RTADDR_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + break; + + case DMAR_RTADDR_REG_HI: + VTD_DPRINTF(CSR, "DMAR_RTADDR_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Invalidation Queue Tail Register, 64-bit */ + case DMAR_IQT_REG: + VTD_DPRINTF(INV, "DMAR_IQT_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + vtd_handle_iqt_write(s); + break; + + case DMAR_IQT_REG_HI: + VTD_DPRINTF(INV, "DMAR_IQT_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + /* 19:63 of IQT_REG is RsvdZ, do nothing here */ + break; + + /* Invalidation Queue Address Register, 64-bit */ + case DMAR_IQA_REG: + VTD_DPRINTF(INV, "DMAR_IQA_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + break; + + case DMAR_IQA_REG_HI: + VTD_DPRINTF(INV, "DMAR_IQA_REG_HI write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Invalidation Completion Status Register, 32-bit */ + case DMAR_ICS_REG: + VTD_DPRINTF(INV, "DMAR_ICS_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_ics_write(s); + break; + + /* Invalidation Event Control Register, 32-bit */ + case DMAR_IECTL_REG: + VTD_DPRINTF(INV, "DMAR_IECTL_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + vtd_handle_iectl_write(s); + break; + + /* Invalidation Event Data Register, 32-bit */ + case DMAR_IEDATA_REG: + VTD_DPRINTF(INV, "DMAR_IEDATA_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Invalidation Event Address Register, 32-bit */ + case DMAR_IEADDR_REG: + VTD_DPRINTF(INV, "DMAR_IEADDR_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Invalidation Event Upper Address Register, 32-bit */ + case DMAR_IEUADDR_REG: + VTD_DPRINTF(INV, "DMAR_IEUADDR_REG write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + /* Fault Recording Registers, 128-bit */ + case DMAR_FRCD_REG_0_0: + VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_0 write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + break; + + case DMAR_FRCD_REG_0_1: + VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_1 write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + break; + + case DMAR_FRCD_REG_0_2: + VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_2 write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + /* May clear bit 127 (Fault), update PPF */ + vtd_update_fsts_ppf(s); + } + break; + + case DMAR_FRCD_REG_0_3: + VTD_DPRINTF(FLOG, "DMAR_FRCD_REG_0_3 write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + assert(size == 4); + vtd_set_long(s, addr, val); + /* May clear bit 127 (Fault), update PPF */ + vtd_update_fsts_ppf(s); + break; + + default: + VTD_DPRINTF(GENERAL, "error: unhandled reg write addr 0x%"PRIx64 + ", size %d, val 0x%"PRIx64, addr, size, val); + if (size == 4) { + vtd_set_long(s, addr, val); + } else { + vtd_set_quad(s, addr, val); + } + } +} + +static IOMMUTLBEntry vtd_iommu_translate(MemoryRegion *iommu, hwaddr addr, + bool is_write) +{ + VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu); + IntelIOMMUState *s = vtd_as->iommu_state; + IOMMUTLBEntry ret = { + .target_as = &address_space_memory, + .iova = addr, + .translated_addr = 0, + .addr_mask = ~(hwaddr)0, + .perm = IOMMU_NONE, + }; + + if (!s->dmar_enabled) { + /* DMAR disabled, passthrough, use 4k-page*/ + ret.iova = addr & VTD_PAGE_MASK_4K; + ret.translated_addr = addr & VTD_PAGE_MASK_4K; + ret.addr_mask = ~VTD_PAGE_MASK_4K; + ret.perm = IOMMU_RW; + return ret; + } + + vtd_do_iommu_translate(vtd_as, vtd_as->bus_num, vtd_as->devfn, addr, + is_write, &ret); + VTD_DPRINTF(MMU, + "bus %"PRIu8 " slot %"PRIu8 " func %"PRIu8 " devfn %"PRIu8 + " gpa 0x%"PRIx64 " hpa 0x%"PRIx64, vtd_as->bus_num, + VTD_PCI_SLOT(vtd_as->devfn), VTD_PCI_FUNC(vtd_as->devfn), + vtd_as->devfn, addr, ret.translated_addr); + return ret; +} + +static const VMStateDescription vtd_vmstate = { + .name = "iommu-intel", + .unmigratable = 1, +}; + +static const MemoryRegionOps vtd_mem_ops = { + .read = vtd_mem_read, + .write = vtd_mem_write, + .endianness = DEVICE_LITTLE_ENDIAN, + .impl = { + .min_access_size = 4, + .max_access_size = 8, + }, + .valid = { + .min_access_size = 4, + .max_access_size = 8, + }, +}; + +static Property vtd_properties[] = { + DEFINE_PROP_UINT32("version", IntelIOMMUState, version, 0), + DEFINE_PROP_END_OF_LIST(), +}; + +/* Do the initialization. It will also be called when reset, so pay + * attention when adding new initialization stuff. + */ +static void vtd_init(IntelIOMMUState *s) +{ + memset(s->csr, 0, DMAR_REG_SIZE); + memset(s->wmask, 0, DMAR_REG_SIZE); + memset(s->w1cmask, 0, DMAR_REG_SIZE); + memset(s->womask, 0, DMAR_REG_SIZE); + + s->iommu_ops.translate = vtd_iommu_translate; + s->root = 0; + s->root_extended = false; + s->dmar_enabled = false; + s->iq_head = 0; + s->iq_tail = 0; + s->iq = 0; + s->iq_size = 0; + s->qi_enabled = false; + s->iq_last_desc_type = VTD_INV_DESC_NONE; + s->next_frcd_reg = 0; + s->cap = VTD_CAP_FRO | VTD_CAP_NFR | VTD_CAP_ND | VTD_CAP_MGAW | + VTD_CAP_SAGAW | VTD_CAP_MAMV | VTD_CAP_PSI; + s->ecap = VTD_ECAP_QI | VTD_ECAP_IRO; + + vtd_reset_context_cache(s); + vtd_reset_iotlb(s); + + /* Define registers with default values and bit semantics */ + vtd_define_long(s, DMAR_VER_REG, 0x10UL, 0, 0); + vtd_define_quad(s, DMAR_CAP_REG, s->cap, 0, 0); + vtd_define_quad(s, DMAR_ECAP_REG, s->ecap, 0, 0); + vtd_define_long(s, DMAR_GCMD_REG, 0, 0xff800000UL, 0); + vtd_define_long_wo(s, DMAR_GCMD_REG, 0xff800000UL); + vtd_define_long(s, DMAR_GSTS_REG, 0, 0, 0); + vtd_define_quad(s, DMAR_RTADDR_REG, 0, 0xfffffffffffff000ULL, 0); + vtd_define_quad(s, DMAR_CCMD_REG, 0, 0xe0000003ffffffffULL, 0); + vtd_define_quad_wo(s, DMAR_CCMD_REG, 0x3ffff0000ULL); + + /* Advanced Fault Logging not supported */ + vtd_define_long(s, DMAR_FSTS_REG, 0, 0, 0x11UL); + vtd_define_long(s, DMAR_FECTL_REG, 0x80000000UL, 0x80000000UL, 0); + vtd_define_long(s, DMAR_FEDATA_REG, 0, 0x0000ffffUL, 0); + vtd_define_long(s, DMAR_FEADDR_REG, 0, 0xfffffffcUL, 0); + + /* Treated as RsvdZ when EIM in ECAP_REG is not supported + * vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0xffffffffUL, 0); + */ + vtd_define_long(s, DMAR_FEUADDR_REG, 0, 0, 0); + + /* Treated as RO for implementations that PLMR and PHMR fields reported + * as Clear in the CAP_REG. + * vtd_define_long(s, DMAR_PMEN_REG, 0, 0x80000000UL, 0); + */ + vtd_define_long(s, DMAR_PMEN_REG, 0, 0, 0); + + vtd_define_quad(s, DMAR_IQH_REG, 0, 0, 0); + vtd_define_quad(s, DMAR_IQT_REG, 0, 0x7fff0ULL, 0); + vtd_define_quad(s, DMAR_IQA_REG, 0, 0xfffffffffffff007ULL, 0); + vtd_define_long(s, DMAR_ICS_REG, 0, 0, 0x1UL); + vtd_define_long(s, DMAR_IECTL_REG, 0x80000000UL, 0x80000000UL, 0); + vtd_define_long(s, DMAR_IEDATA_REG, 0, 0xffffffffUL, 0); + vtd_define_long(s, DMAR_IEADDR_REG, 0, 0xfffffffcUL, 0); + /* Treadted as RsvdZ when EIM in ECAP_REG is not supported */ + vtd_define_long(s, DMAR_IEUADDR_REG, 0, 0, 0); + + /* IOTLB registers */ + vtd_define_quad(s, DMAR_IOTLB_REG, 0, 0Xb003ffff00000000ULL, 0); + vtd_define_quad(s, DMAR_IVA_REG, 0, 0xfffffffffffff07fULL, 0); + vtd_define_quad_wo(s, DMAR_IVA_REG, 0xfffffffffffff07fULL); + + /* Fault Recording Registers, 128-bit */ + vtd_define_quad(s, DMAR_FRCD_REG_0_0, 0, 0, 0); + vtd_define_quad(s, DMAR_FRCD_REG_0_2, 0, 0, 0x8000000000000000ULL); +} + +/* Should not reset address_spaces when reset because devices will still use + * the address space they got at first (won't ask the bus again). + */ +static void vtd_reset(DeviceState *dev) +{ + IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev); + + VTD_DPRINTF(GENERAL, ""); + vtd_init(s); +} + +static void vtd_realize(DeviceState *dev, Error **errp) +{ + IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev); + + VTD_DPRINTF(GENERAL, ""); + memset(s->address_spaces, 0, sizeof(s->address_spaces)); + memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s, + "intel_iommu", DMAR_REG_SIZE); + sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->csrmem); + /* No corresponding destroy */ + s->iotlb = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal, + g_free, g_free); + vtd_init(s); +} + +static void vtd_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + + dc->reset = vtd_reset; + dc->realize = vtd_realize; + dc->vmsd = &vtd_vmstate; + dc->props = vtd_properties; +} + +static const TypeInfo vtd_info = { + .name = TYPE_INTEL_IOMMU_DEVICE, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(IntelIOMMUState), + .class_init = vtd_class_init, +}; + +static void vtd_register_types(void) +{ + VTD_DPRINTF(GENERAL, ""); + type_register_static(&vtd_info); +} + +type_init(vtd_register_types) diff --git a/hw/i386/intel_iommu_internal.h b/hw/i386/intel_iommu_internal.h new file mode 100644 index 0000000000..ba288ab1d9 --- /dev/null +++ b/hw/i386/intel_iommu_internal.h @@ -0,0 +1,389 @@ +/* + * QEMU emulation of an Intel IOMMU (VT-d) + * (DMA Remapping device) + * + * Copyright (C) 2013 Knut Omang, Oracle <knut.omang@oracle.com> + * Copyright (C) 2014 Le Tan, <tamlokveer@gmail.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, see <http://www.gnu.org/licenses/>. + * + * Lots of defines copied from kernel/include/linux/intel-iommu.h: + * Copyright (C) 2006-2008 Intel Corporation + * Author: Ashok Raj <ashok.raj@intel.com> + * Author: Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com> + * + */ + +#ifndef HW_I386_INTEL_IOMMU_INTERNAL_H +#define HW_I386_INTEL_IOMMU_INTERNAL_H +#include "hw/i386/intel_iommu.h" + +/* + * Intel IOMMU register specification + */ +#define DMAR_VER_REG 0x0 /* Arch version supported by this IOMMU */ +#define DMAR_CAP_REG 0x8 /* Hardware supported capabilities */ +#define DMAR_CAP_REG_HI 0xc /* High 32-bit of DMAR_CAP_REG */ +#define DMAR_ECAP_REG 0x10 /* Extended capabilities supported */ +#define DMAR_ECAP_REG_HI 0X14 +#define DMAR_GCMD_REG 0x18 /* Global command */ +#define DMAR_GSTS_REG 0x1c /* Global status */ +#define DMAR_RTADDR_REG 0x20 /* Root entry table */ +#define DMAR_RTADDR_REG_HI 0X24 +#define DMAR_CCMD_REG 0x28 /* Context command */ +#define DMAR_CCMD_REG_HI 0x2c +#define DMAR_FSTS_REG 0x34 /* Fault status */ +#define DMAR_FECTL_REG 0x38 /* Fault control */ +#define DMAR_FEDATA_REG 0x3c /* Fault event interrupt data */ +#define DMAR_FEADDR_REG 0x40 /* Fault event interrupt addr */ +#define DMAR_FEUADDR_REG 0x44 /* Upper address */ +#define DMAR_AFLOG_REG 0x58 /* Advanced fault control */ +#define DMAR_AFLOG_REG_HI 0X5c +#define DMAR_PMEN_REG 0x64 /* Enable protected memory region */ +#define DMAR_PLMBASE_REG 0x68 /* PMRR low addr */ +#define DMAR_PLMLIMIT_REG 0x6c /* PMRR low limit */ +#define DMAR_PHMBASE_REG 0x70 /* PMRR high base addr */ +#define DMAR_PHMBASE_REG_HI 0X74 +#define DMAR_PHMLIMIT_REG 0x78 /* PMRR high limit */ +#define DMAR_PHMLIMIT_REG_HI 0x7c +#define DMAR_IQH_REG 0x80 /* Invalidation queue head */ +#define DMAR_IQH_REG_HI 0X84 +#define DMAR_IQT_REG 0x88 /* Invalidation queue tail */ +#define DMAR_IQT_REG_HI 0X8c +#define DMAR_IQA_REG 0x90 /* Invalidation queue addr */ +#define DMAR_IQA_REG_HI 0x94 +#define DMAR_ICS_REG 0x9c /* Invalidation complete status */ +#define DMAR_IRTA_REG 0xb8 /* Interrupt remapping table addr */ +#define DMAR_IRTA_REG_HI 0xbc +#define DMAR_IECTL_REG 0xa0 /* Invalidation event control */ +#define DMAR_IEDATA_REG 0xa4 /* Invalidation event data */ +#define DMAR_IEADDR_REG 0xa8 /* Invalidation event address */ +#define DMAR_IEUADDR_REG 0xac /* Invalidation event address */ +#define DMAR_PQH_REG 0xc0 /* Page request queue head */ +#define DMAR_PQH_REG_HI 0xc4 +#define DMAR_PQT_REG 0xc8 /* Page request queue tail*/ +#define DMAR_PQT_REG_HI 0xcc +#define DMAR_PQA_REG 0xd0 /* Page request queue address */ +#define DMAR_PQA_REG_HI 0xd4 +#define DMAR_PRS_REG 0xdc /* Page request status */ +#define DMAR_PECTL_REG 0xe0 /* Page request event control */ +#define DMAR_PEDATA_REG 0xe4 /* Page request event data */ +#define DMAR_PEADDR_REG 0xe8 /* Page request event address */ +#define DMAR_PEUADDR_REG 0xec /* Page event upper address */ +#define DMAR_MTRRCAP_REG 0x100 /* MTRR capability */ +#define DMAR_MTRRCAP_REG_HI 0x104 +#define DMAR_MTRRDEF_REG 0x108 /* MTRR default type */ +#define DMAR_MTRRDEF_REG_HI 0x10c + +/* IOTLB registers */ +#define DMAR_IOTLB_REG_OFFSET 0xf0 /* Offset to the IOTLB registers */ +#define DMAR_IVA_REG DMAR_IOTLB_REG_OFFSET /* Invalidate address */ +#define DMAR_IVA_REG_HI (DMAR_IVA_REG + 4) +/* IOTLB invalidate register */ +#define DMAR_IOTLB_REG (DMAR_IOTLB_REG_OFFSET + 0x8) +#define DMAR_IOTLB_REG_HI (DMAR_IOTLB_REG + 4) + +/* FRCD */ +#define DMAR_FRCD_REG_OFFSET 0x220 /* Offset to the fault recording regs */ +/* NOTICE: If you change the DMAR_FRCD_REG_NR, please remember to change the + * DMAR_REG_SIZE in include/hw/i386/intel_iommu.h. + * #define DMAR_REG_SIZE (DMAR_FRCD_REG_OFFSET + 16 * DMAR_FRCD_REG_NR) + */ +#define DMAR_FRCD_REG_NR 1ULL /* Num of fault recording regs */ + +#define DMAR_FRCD_REG_0_0 0x220 /* The 0th fault recording regs */ +#define DMAR_FRCD_REG_0_1 0x224 +#define DMAR_FRCD_REG_0_2 0x228 +#define DMAR_FRCD_REG_0_3 0x22c + +/* Interrupt Address Range */ +#define VTD_INTERRUPT_ADDR_FIRST 0xfee00000ULL +#define VTD_INTERRUPT_ADDR_LAST 0xfeefffffULL + +/* The shift of source_id in the key of IOTLB hash table */ +#define VTD_IOTLB_SID_SHIFT 36 +#define VTD_IOTLB_MAX_SIZE 1024 /* Max size of the hash table */ + +/* IOTLB_REG */ +#define VTD_TLB_GLOBAL_FLUSH (1ULL << 60) /* Global invalidation */ +#define VTD_TLB_DSI_FLUSH (2ULL << 60) /* Domain-selective */ +#define VTD_TLB_PSI_FLUSH (3ULL << 60) /* Page-selective */ +#define VTD_TLB_FLUSH_GRANU_MASK (3ULL << 60) +#define VTD_TLB_GLOBAL_FLUSH_A (1ULL << 57) +#define VTD_TLB_DSI_FLUSH_A (2ULL << 57) +#define VTD_TLB_PSI_FLUSH_A (3ULL << 57) +#define VTD_TLB_FLUSH_GRANU_MASK_A (3ULL << 57) +#define VTD_TLB_IVT (1ULL << 63) +#define VTD_TLB_DID(val) (((val) >> 32) & VTD_DOMAIN_ID_MASK) + +/* IVA_REG */ +#define VTD_IVA_ADDR(val) ((val) & ~0xfffULL & ((1ULL << VTD_MGAW) - 1)) +#define VTD_IVA_AM(val) ((val) & 0x3fULL) + +/* GCMD_REG */ +#define VTD_GCMD_TE (1UL << 31) +#define VTD_GCMD_SRTP (1UL << 30) +#define VTD_GCMD_SFL (1UL << 29) +#define VTD_GCMD_EAFL (1UL << 28) +#define VTD_GCMD_WBF (1UL << 27) +#define VTD_GCMD_QIE (1UL << 26) +#define VTD_GCMD_IRE (1UL << 25) +#define VTD_GCMD_SIRTP (1UL << 24) +#define VTD_GCMD_CFI (1UL << 23) + +/* GSTS_REG */ +#define VTD_GSTS_TES (1UL << 31) +#define VTD_GSTS_RTPS (1UL << 30) +#define VTD_GSTS_FLS (1UL << 29) +#define VTD_GSTS_AFLS (1UL << 28) +#define VTD_GSTS_WBFS (1UL << 27) +#define VTD_GSTS_QIES (1UL << 26) +#define VTD_GSTS_IRES (1UL << 25) +#define VTD_GSTS_IRTPS (1UL << 24) +#define VTD_GSTS_CFIS (1UL << 23) + +/* CCMD_REG */ +#define VTD_CCMD_ICC (1ULL << 63) +#define VTD_CCMD_GLOBAL_INVL (1ULL << 61) +#define VTD_CCMD_DOMAIN_INVL (2ULL << 61) +#define VTD_CCMD_DEVICE_INVL (3ULL << 61) +#define VTD_CCMD_CIRG_MASK (3ULL << 61) +#define VTD_CCMD_GLOBAL_INVL_A (1ULL << 59) +#define VTD_CCMD_DOMAIN_INVL_A (2ULL << 59) +#define VTD_CCMD_DEVICE_INVL_A (3ULL << 59) +#define VTD_CCMD_CAIG_MASK (3ULL << 59) +#define VTD_CCMD_DID(val) ((val) & VTD_DOMAIN_ID_MASK) +#define VTD_CCMD_SID(val) (((val) >> 16) & 0xffffULL) +#define VTD_CCMD_FM(val) (((val) >> 32) & 3ULL) + +/* RTADDR_REG */ +#define VTD_RTADDR_RTT (1ULL << 11) +#define VTD_RTADDR_ADDR_MASK (VTD_HAW_MASK ^ 0xfffULL) + +/* ECAP_REG */ +/* (offset >> 4) << 8 */ +#define VTD_ECAP_IRO (DMAR_IOTLB_REG_OFFSET << 4) +#define VTD_ECAP_QI (1ULL << 1) + +/* CAP_REG */ +/* (offset >> 4) << 24 */ +#define VTD_CAP_FRO (DMAR_FRCD_REG_OFFSET << 20) +#define VTD_CAP_NFR ((DMAR_FRCD_REG_NR - 1) << 40) +#define VTD_DOMAIN_ID_SHIFT 16 /* 16-bit domain id for 64K domains */ +#define VTD_DOMAIN_ID_MASK ((1UL << VTD_DOMAIN_ID_SHIFT) - 1) +#define VTD_CAP_ND (((VTD_DOMAIN_ID_SHIFT - 4) / 2) & 7ULL) +#define VTD_MGAW 39 /* Maximum Guest Address Width */ +#define VTD_CAP_MGAW (((VTD_MGAW - 1) & 0x3fULL) << 16) +#define VTD_MAMV 9ULL +#define VTD_CAP_MAMV (VTD_MAMV << 48) +#define VTD_CAP_PSI (1ULL << 39) + +/* Supported Adjusted Guest Address Widths */ +#define VTD_CAP_SAGAW_SHIFT 8 +#define VTD_CAP_SAGAW_MASK (0x1fULL << VTD_CAP_SAGAW_SHIFT) + /* 39-bit AGAW, 3-level page-table */ +#define VTD_CAP_SAGAW_39bit (0x2ULL << VTD_CAP_SAGAW_SHIFT) + /* 48-bit AGAW, 4-level page-table */ +#define VTD_CAP_SAGAW_48bit (0x4ULL << VTD_CAP_SAGAW_SHIFT) +#define VTD_CAP_SAGAW VTD_CAP_SAGAW_39bit + +/* IQT_REG */ +#define VTD_IQT_QT(val) (((val) >> 4) & 0x7fffULL) + +/* IQA_REG */ +#define VTD_IQA_IQA_MASK (VTD_HAW_MASK ^ 0xfffULL) +#define VTD_IQA_QS 0x7ULL + +/* IQH_REG */ +#define VTD_IQH_QH_SHIFT 4 +#define VTD_IQH_QH_MASK 0x7fff0ULL + +/* ICS_REG */ +#define VTD_ICS_IWC 1UL + +/* IECTL_REG */ +#define VTD_IECTL_IM (1UL << 31) +#define VTD_IECTL_IP (1UL << 30) + +/* FSTS_REG */ +#define VTD_FSTS_FRI_MASK 0xff00UL +#define VTD_FSTS_FRI(val) ((((uint32_t)(val)) << 8) & VTD_FSTS_FRI_MASK) +#define VTD_FSTS_IQE (1UL << 4) +#define VTD_FSTS_PPF (1UL << 1) +#define VTD_FSTS_PFO 1UL + +/* FECTL_REG */ +#define VTD_FECTL_IM (1UL << 31) +#define VTD_FECTL_IP (1UL << 30) + +/* Fault Recording Register */ +/* For the high 64-bit of 128-bit */ +#define VTD_FRCD_F (1ULL << 63) +#define VTD_FRCD_T (1ULL << 62) +#define VTD_FRCD_FR(val) (((val) & 0xffULL) << 32) +#define VTD_FRCD_SID_MASK 0xffffULL +#define VTD_FRCD_SID(val) ((val) & VTD_FRCD_SID_MASK) +/* For the low 64-bit of 128-bit */ +#define VTD_FRCD_FI(val) ((val) & (((1ULL << VTD_MGAW) - 1) ^ 0xfffULL)) + +/* DMA Remapping Fault Conditions */ +typedef enum VTDFaultReason { + VTD_FR_RESERVED = 0, /* Reserved for Advanced Fault logging */ + VTD_FR_ROOT_ENTRY_P = 1, /* The Present(P) field of root-entry is 0 */ + VTD_FR_CONTEXT_ENTRY_P, /* The Present(P) field of context-entry is 0 */ + VTD_FR_CONTEXT_ENTRY_INV, /* Invalid programming of a context-entry */ + VTD_FR_ADDR_BEYOND_MGAW, /* Input-address above (2^x-1) */ + VTD_FR_WRITE, /* No write permission */ + VTD_FR_READ, /* No read permission */ + /* Fail to access a second-level paging entry (not SL_PML4E) */ + VTD_FR_PAGING_ENTRY_INV, + VTD_FR_ROOT_TABLE_INV, /* Fail to access a root-entry */ + VTD_FR_CONTEXT_TABLE_INV, /* Fail to access a context-entry */ + /* Non-zero reserved field in a present root-entry */ + VTD_FR_ROOT_ENTRY_RSVD, + /* Non-zero reserved field in a present context-entry */ + VTD_FR_CONTEXT_ENTRY_RSVD, + /* Non-zero reserved field in a second-level paging entry with at lease one + * Read(R) and Write(W) or Execute(E) field is Set. + */ + VTD_FR_PAGING_ENTRY_RSVD, + /* Translation request or translated request explicitly blocked dut to the + * programming of the Translation Type (T) field in the present + * context-entry. + */ + VTD_FR_CONTEXT_ENTRY_TT, + /* This is not a normal fault reason. We use this to indicate some faults + * that are not referenced by the VT-d specification. + * Fault event with such reason should not be recorded. + */ + VTD_FR_RESERVED_ERR, + VTD_FR_MAX, /* Guard */ +} VTDFaultReason; + +#define VTD_CONTEXT_CACHE_GEN_MAX 0xffffffffUL + +/* Queued Invalidation Descriptor */ +struct VTDInvDesc { + uint64_t lo; + uint64_t hi; +}; +typedef struct VTDInvDesc VTDInvDesc; + +/* Masks for struct VTDInvDesc */ +#define VTD_INV_DESC_TYPE 0xf +#define VTD_INV_DESC_CC 0x1 /* Context-cache Invalidate Desc */ +#define VTD_INV_DESC_IOTLB 0x2 +#define VTD_INV_DESC_WAIT 0x5 /* Invalidation Wait Descriptor */ +#define VTD_INV_DESC_NONE 0 /* Not an Invalidate Descriptor */ + +/* Masks for Invalidation Wait Descriptor*/ +#define VTD_INV_DESC_WAIT_SW (1ULL << 5) +#define VTD_INV_DESC_WAIT_IF (1ULL << 4) +#define VTD_INV_DESC_WAIT_FN (1ULL << 6) +#define VTD_INV_DESC_WAIT_DATA_SHIFT 32 +#define VTD_INV_DESC_WAIT_RSVD_LO 0Xffffff80ULL +#define VTD_INV_DESC_WAIT_RSVD_HI 3ULL + +/* Masks for Context-cache Invalidation Descriptor */ +#define VTD_INV_DESC_CC_G (3ULL << 4) +#define VTD_INV_DESC_CC_GLOBAL (1ULL << 4) +#define VTD_INV_DESC_CC_DOMAIN (2ULL << 4) +#define VTD_INV_DESC_CC_DEVICE (3ULL << 4) +#define VTD_INV_DESC_CC_DID(val) (((val) >> 16) & VTD_DOMAIN_ID_MASK) +#define VTD_INV_DESC_CC_SID(val) (((val) >> 32) & 0xffffUL) +#define VTD_INV_DESC_CC_FM(val) (((val) >> 48) & 3UL) +#define VTD_INV_DESC_CC_RSVD 0xfffc00000000ffc0ULL + +/* Masks for IOTLB Invalidate Descriptor */ +#define VTD_INV_DESC_IOTLB_G (3ULL << 4) +#define VTD_INV_DESC_IOTLB_GLOBAL (1ULL << 4) +#define VTD_INV_DESC_IOTLB_DOMAIN (2ULL << 4) +#define VTD_INV_DESC_IOTLB_PAGE (3ULL << 4) +#define VTD_INV_DESC_IOTLB_DID(val) (((val) >> 16) & VTD_DOMAIN_ID_MASK) +#define VTD_INV_DESC_IOTLB_ADDR(val) ((val) & ~0xfffULL & \ + ((1ULL << VTD_MGAW) - 1)) +#define VTD_INV_DESC_IOTLB_AM(val) ((val) & 0x3fULL) +#define VTD_INV_DESC_IOTLB_RSVD_LO 0xffffffff0000ff00ULL +#define VTD_INV_DESC_IOTLB_RSVD_HI 0xf80ULL + +/* Information about page-selective IOTLB invalidate */ +struct VTDIOTLBPageInvInfo { + uint16_t domain_id; + uint64_t gfn; + uint8_t mask; +}; +typedef struct VTDIOTLBPageInvInfo VTDIOTLBPageInvInfo; + +/* Pagesize of VTD paging structures, including root and context tables */ +#define VTD_PAGE_SHIFT 12 +#define VTD_PAGE_SIZE (1ULL << VTD_PAGE_SHIFT) + +#define VTD_PAGE_SHIFT_4K 12 +#define VTD_PAGE_MASK_4K (~((1ULL << VTD_PAGE_SHIFT_4K) - 1)) +#define VTD_PAGE_SHIFT_2M 21 +#define VTD_PAGE_MASK_2M (~((1ULL << VTD_PAGE_SHIFT_2M) - 1)) +#define VTD_PAGE_SHIFT_1G 30 +#define VTD_PAGE_MASK_1G (~((1ULL << VTD_PAGE_SHIFT_1G) - 1)) + +struct VTDRootEntry { + uint64_t val; + uint64_t rsvd; +}; +typedef struct VTDRootEntry VTDRootEntry; + +/* Masks for struct VTDRootEntry */ +#define VTD_ROOT_ENTRY_P 1ULL +#define VTD_ROOT_ENTRY_CTP (~0xfffULL) + +#define VTD_ROOT_ENTRY_NR (VTD_PAGE_SIZE / sizeof(VTDRootEntry)) +#define VTD_ROOT_ENTRY_RSVD (0xffeULL | ~VTD_HAW_MASK) + +/* Masks for struct VTDContextEntry */ +/* lo */ +#define VTD_CONTEXT_ENTRY_P (1ULL << 0) +#define VTD_CONTEXT_ENTRY_FPD (1ULL << 1) /* Fault Processing Disable */ +#define VTD_CONTEXT_ENTRY_TT (3ULL << 2) /* Translation Type */ +#define VTD_CONTEXT_TT_MULTI_LEVEL 0 +#define VTD_CONTEXT_TT_DEV_IOTLB 1 +#define VTD_CONTEXT_TT_PASS_THROUGH 2 +/* Second Level Page Translation Pointer*/ +#define VTD_CONTEXT_ENTRY_SLPTPTR (~0xfffULL) +#define VTD_CONTEXT_ENTRY_RSVD_LO (0xff0ULL | ~VTD_HAW_MASK) +/* hi */ +#define VTD_CONTEXT_ENTRY_AW 7ULL /* Adjusted guest-address-width */ +#define VTD_CONTEXT_ENTRY_DID(val) (((val) >> 8) & VTD_DOMAIN_ID_MASK) +#define VTD_CONTEXT_ENTRY_RSVD_HI 0xffffffffff000080ULL + +#define VTD_CONTEXT_ENTRY_NR (VTD_PAGE_SIZE / sizeof(VTDContextEntry)) + +/* Paging Structure common */ +#define VTD_SL_PT_PAGE_SIZE_MASK (1ULL << 7) +/* Bits to decide the offset for each level */ +#define VTD_SL_LEVEL_BITS 9 + +/* Second Level Paging Structure */ +#define VTD_SL_PML4_LEVEL 4 +#define VTD_SL_PDP_LEVEL 3 +#define VTD_SL_PD_LEVEL 2 +#define VTD_SL_PT_LEVEL 1 +#define VTD_SL_PT_ENTRY_NR 512 + +/* Masks for Second Level Paging Entry */ +#define VTD_SL_RW_MASK 3ULL +#define VTD_SL_R 1ULL +#define VTD_SL_W (1ULL << 1) +#define VTD_SL_PT_BASE_ADDR_MASK (~(VTD_PAGE_SIZE - 1) & VTD_HAW_MASK) +#define VTD_SL_IGN_COM 0xbff0000000000000ULL + +#endif diff --git a/hw/i386/kvm/apic.c b/hw/i386/kvm/apic.c index e873b509a5..271e97f86f 100644 --- a/hw/i386/kvm/apic.c +++ b/hw/i386/kvm/apic.c @@ -175,6 +175,9 @@ static void kvm_apic_realize(DeviceState *dev, Error **errp) { APICCommonState *s = APIC_COMMON(dev); + /* Not used by KVM, which uses the CPU mp_state instead. */ + s->wait_for_sipi = 0; + memory_region_init_io(&s->io_memory, NULL, &kvm_apic_io_ops, s, "kvm-apic-msi", APIC_SPACE_SIZE); diff --git a/hw/i386/kvm/clock.c b/hw/i386/kvm/clock.c index 892aa025f4..58be2bda27 100644 --- a/hw/i386/kvm/clock.c +++ b/hw/i386/kvm/clock.c @@ -14,8 +14,10 @@ */ #include "qemu-common.h" +#include "qemu/host-utils.h" #include "sysemu/sysemu.h" #include "sysemu/kvm.h" +#include "sysemu/cpus.h" #include "hw/sysbus.h" #include "hw/kvm/clock.h" @@ -34,6 +36,48 @@ typedef struct KVMClockState { bool clock_valid; } KVMClockState; +struct pvclock_vcpu_time_info { + uint32_t version; + uint32_t pad0; + uint64_t tsc_timestamp; + uint64_t system_time; + uint32_t tsc_to_system_mul; + int8_t tsc_shift; + uint8_t flags; + uint8_t pad[2]; +} __attribute__((__packed__)); /* 32 bytes */ + +static uint64_t kvmclock_current_nsec(KVMClockState *s) +{ + CPUState *cpu = first_cpu; + CPUX86State *env = cpu->env_ptr; + hwaddr kvmclock_struct_pa = env->system_time_msr & ~1ULL; + uint64_t migration_tsc = env->tsc; + struct pvclock_vcpu_time_info time; + uint64_t delta; + uint64_t nsec_lo; + uint64_t nsec_hi; + uint64_t nsec; + + if (!(env->system_time_msr & 1ULL)) { + /* KVM clock not active */ + return 0; + } + + cpu_physical_memory_read(kvmclock_struct_pa, &time, sizeof(time)); + + assert(time.tsc_timestamp <= migration_tsc); + delta = migration_tsc - time.tsc_timestamp; + if (time.tsc_shift < 0) { + delta >>= -time.tsc_shift; + } else { + delta <<= time.tsc_shift; + } + + mulu64(&nsec_lo, &nsec_hi, delta, time.tsc_to_system_mul); + nsec = (nsec_lo >> 32) | (nsec_hi << 32); + return nsec + time.system_time; +} static void kvmclock_vm_state_change(void *opaque, int running, RunState state) @@ -45,9 +89,15 @@ static void kvmclock_vm_state_change(void *opaque, int running, if (running) { struct kvm_clock_data data; + uint64_t time_at_migration = kvmclock_current_nsec(s); s->clock_valid = false; + /* We can't rely on the migrated clock value, just discard it */ + if (time_at_migration) { + s->clock = time_at_migration; + } + data.clock = s->clock; data.flags = 0; ret = kvm_vm_ioctl(kvm_state, KVM_SET_CLOCK, &data); @@ -75,6 +125,23 @@ static void kvmclock_vm_state_change(void *opaque, int running, if (s->clock_valid) { return; } + + cpu_synchronize_all_states(); + /* In theory, the cpu_synchronize_all_states() call above wouldn't + * affect the rest of the code, as the VCPU state inside CPUState + * is supposed to always match the VCPU state on the kernel side. + * + * In practice, calling cpu_synchronize_state() too soon will load the + * kernel-side APIC state into X86CPU.apic_state too early, APIC state + * won't be reloaded later because CPUState.vcpu_dirty==true, and + * outdated APIC state may be migrated to another host. + * + * The real fix would be to make sure outdated APIC state is read + * from the kernel again when necessary. While this is not fixed, we + * need the cpu_clean_all_dirty() call below. + */ + cpu_clean_all_dirty(); + ret = kvm_vm_ioctl(kvm_state, KVM_GET_CLOCK, &data); if (ret < 0) { fprintf(stderr, "KVM_GET_CLOCK failed: %s\n", strerror(ret)); @@ -102,7 +169,6 @@ static const VMStateDescription kvmclock_vmsd = { .name = "kvmclock", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT64(clock, KVMClockState), VMSTATE_END_OF_LIST() diff --git a/hw/i386/kvm/i8254.c b/hw/i386/kvm/i8254.c index 59373aaade..472af811cd 100644 --- a/hw/i386/kvm/i8254.c +++ b/hw/i386/kvm/i8254.c @@ -239,6 +239,7 @@ static void kvm_pit_vm_state_change(void *opaque, int running, if (running) { kvm_pit_update_clock_offset(s); + kvm_pit_put(PIT_COMMON(s)); s->vm_stopped = false; } else { kvm_pit_update_clock_offset(s); @@ -314,8 +315,6 @@ static void kvm_pit_class_init(ObjectClass *klass, void *data) dc->realize = kvm_pit_realizefn; k->set_channel_gate = kvm_pit_set_gate; k->get_channel_info = kvm_pit_get_channel_info; - k->pre_save = kvm_pit_get; - k->post_load = kvm_pit_put; dc->reset = kvm_pit_reset; dc->props = kvm_pit_properties; } diff --git a/hw/i386/kvm/pci-assign.c b/hw/i386/kvm/pci-assign.c index a825871d8a..bb206da05f 100644 --- a/hw/i386/kvm/pci-assign.c +++ b/hw/i386/kvm/pci-assign.c @@ -394,9 +394,10 @@ static uint8_t pci_find_cap_offset(PCIDevice *d, uint8_t cap, uint8_t start) return 0; } -static int assigned_dev_register_regions(PCIRegion *io_regions, - unsigned long regions_num, - AssignedDevice *pci_dev) +static void assigned_dev_register_regions(PCIRegion *io_regions, + unsigned long regions_num, + AssignedDevice *pci_dev, + Error **errp) { uint32_t i; PCIRegion *cur_region = io_regions; @@ -425,9 +426,9 @@ static int assigned_dev_register_regions(PCIRegion *io_regions, if (pci_dev->v_addrs[i].u.r_virtbase == MAP_FAILED) { pci_dev->v_addrs[i].u.r_virtbase = NULL; - error_report("%s: Error: Couldn't mmap 0x%" PRIx64 "!", - __func__, cur_region->base_addr); - return -1; + error_setg_errno(errp, errno, "Couldn't mmap 0x%" PRIx64 "!", + cur_region->base_addr); + return; } pci_dev->v_addrs[i].r_size = cur_region->size; @@ -496,10 +497,10 @@ static int assigned_dev_register_regions(PCIRegion *io_regions, } /* success */ - return 0; } -static int get_real_id(const char *devpath, const char *idname, uint16_t *val) +static void get_real_id(const char *devpath, const char *idname, uint16_t *val, + Error **errp) { FILE *f; char name[128]; @@ -508,39 +509,39 @@ static int get_real_id(const char *devpath, const char *idname, uint16_t *val) snprintf(name, sizeof(name), "%s%s", devpath, idname); f = fopen(name, "r"); if (f == NULL) { - error_report("%s: %s: %m", __func__, name); - return -1; + error_setg_file_open(errp, errno, name); + return; } if (fscanf(f, "%li\n", &id) == 1) { *val = id; } else { - fclose(f); - return -1; + error_setg(errp, "Failed to parse contents of '%s'", name); } fclose(f); - - return 0; } -static int get_real_vendor_id(const char *devpath, uint16_t *val) +static void get_real_vendor_id(const char *devpath, uint16_t *val, + Error **errp) { - return get_real_id(devpath, "vendor", val); + get_real_id(devpath, "vendor", val, errp); } -static int get_real_device_id(const char *devpath, uint16_t *val) +static void get_real_device_id(const char *devpath, uint16_t *val, + Error **errp) { - return get_real_id(devpath, "device", val); + get_real_id(devpath, "device", val, errp); } -static int get_real_device(AssignedDevice *pci_dev) +static void get_real_device(AssignedDevice *pci_dev, Error **errp) { char dir[128], name[128]; - int fd, r = 0, v; + int fd, r = 0; FILE *f; uint64_t start, end, size, flags; uint16_t id; PCIRegion *rp; PCIDevRegions *dev = &pci_dev->real_device; + Error *local_err = NULL; dev->region_number = 0; @@ -551,16 +552,19 @@ static int get_real_device(AssignedDevice *pci_dev) snprintf(name, sizeof(name), "%sconfig", dir); if (pci_dev->configfd_name && *pci_dev->configfd_name) { - dev->config_fd = monitor_handle_fd_param(cur_mon, pci_dev->configfd_name); - if (dev->config_fd < 0) { - return 1; + dev->config_fd = monitor_handle_fd_param2(cur_mon, + pci_dev->configfd_name, + &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } } else { dev->config_fd = open(name, O_RDWR); if (dev->config_fd == -1) { - error_report("%s: %s: %m", __func__, name); - return 1; + error_setg_file_open(errp, errno, name); + return; } } again: @@ -570,7 +574,10 @@ again: if (errno == EINTR || errno == EAGAIN) { goto again; } - error_report("%s: read failed, errno = %d", __func__, errno); + error_setg_errno(errp, errno, "read(\"%s\")", + (pci_dev->configfd_name && *pci_dev->configfd_name) ? + pci_dev->configfd_name : name); + return; } /* Restore or clear multifunction, this is always controlled by qemu */ @@ -590,8 +597,8 @@ again: f = fopen(name, "r"); if (f == NULL) { - error_report("%s: %s: %m", __func__, name); - return 1; + error_setg_file_open(errp, errno, name); + return; } for (r = 0; r < PCI_ROM_SLOT; r++) { @@ -634,17 +641,19 @@ again: fclose(f); /* read and fill vendor ID */ - v = get_real_vendor_id(dir, &id); - if (v) { - return 1; + get_real_vendor_id(dir, &id, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } pci_dev->dev.config[0] = id & 0xff; pci_dev->dev.config[1] = (id & 0xff00) >> 8; /* read and fill device ID */ - v = get_real_device_id(dir, &id); - if (v) { - return 1; + get_real_device_id(dir, &id, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } pci_dev->dev.config[2] = id & 0xff; pci_dev->dev.config[3] = (id & 0xff00) >> 8; @@ -653,7 +662,6 @@ again: PCI_COMMAND_MASTER | PCI_COMMAND_INTX_DISABLE); dev->region_number = r; - return 0; } static void free_msi_virqs(AssignedDevice *dev) @@ -689,8 +697,6 @@ static void free_assigned_device(AssignedDevice *dev) if (region->u.r_baseport) { memory_region_del_subregion(®ion->container, ®ion->real_iomem); - memory_region_destroy(®ion->real_iomem); - memory_region_destroy(®ion->container); } } else if (pci_region->type & IORESOURCE_MEM) { if (region->u.r_virtbase) { @@ -704,9 +710,6 @@ static void free_assigned_device(AssignedDevice *dev) memory_region_del_subregion(®ion->container, &dev->mmio); } - - memory_region_destroy(®ion->real_iomem); - memory_region_destroy(®ion->container); if (munmap(region->u.r_virtbase, (pci_region->size + 0xFFF) & 0xFFFFF000)) { error_report("Failed to unmap assigned device region: %s", @@ -726,11 +729,17 @@ static void free_assigned_device(AssignedDevice *dev) free_msi_virqs(dev); } -static void assign_failed_examine(AssignedDevice *dev) +/* This function tries to determine the cause of the PCI assignment failure. It + * always returns the cause as a dynamically allocated, human readable string. + * If the function fails to determine the cause for any internal reason, then + * the returned string will state that fact. + */ +static char *assign_failed_examine(const AssignedDevice *dev) { char name[PATH_MAX], dir[PATH_MAX], driver[PATH_MAX] = {}, *ns; uint16_t vendor_id, device_id; int r; + Error *local_err = NULL; snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/", dev->host.domain, dev->host.bus, dev->host.slot, @@ -751,13 +760,17 @@ static void assign_failed_examine(AssignedDevice *dev) ns++; - if (get_real_vendor_id(dir, &vendor_id) || - get_real_device_id(dir, &device_id)) { + if ((get_real_vendor_id(dir, &vendor_id, &local_err), local_err) || + (get_real_device_id(dir, &device_id, &local_err), local_err)) { + /* We're already analyzing an assignment error, so we suppress this + * one just like the others above. + */ + error_free(local_err); goto fail; } - error_printf("*** The driver '%s' is occupying your device " - "%04x:%02x:%02x.%x.\n" + return g_strdup_printf( + "*** The driver '%s' is occupying your device %04x:%02x:%02x.%x.\n" "***\n" "*** You can try the following commands to free it:\n" "***\n" @@ -773,13 +786,11 @@ static void assign_failed_examine(AssignedDevice *dev) ns, dev->host.domain, dev->host.bus, dev->host.slot, dev->host.function, vendor_id, device_id); - return; - fail: - error_report("Couldn't find out why."); + return g_strdup("Couldn't find out why."); } -static int assign_device(AssignedDevice *dev) +static void assign_device(AssignedDevice *dev, Error **errp) { uint32_t flags = KVM_DEV_ASSIGN_ENABLE_IOMMU; int r; @@ -787,15 +798,15 @@ static int assign_device(AssignedDevice *dev) /* Only pass non-zero PCI segment to capable module */ if (!kvm_check_extension(kvm_state, KVM_CAP_PCI_SEGMENT) && dev->host.domain) { - error_report("Can't assign device inside non-zero PCI segment " - "as this KVM module doesn't support it."); - return -ENODEV; + error_setg(errp, "Can't assign device inside non-zero PCI segment " + "as this KVM module doesn't support it."); + return; } if (!kvm_check_extension(kvm_state, KVM_CAP_IOMMU)) { - error_report("No IOMMU found. Unable to assign device \"%s\"", - dev->dev.qdev.id); - return -ENODEV; + error_setg(errp, "No IOMMU found. Unable to assign device \"%s\"", + dev->dev.qdev.id); + return; } if (dev->features & ASSIGNED_DEVICE_SHARE_INTX_MASK && @@ -805,36 +816,39 @@ static int assign_device(AssignedDevice *dev) r = kvm_device_pci_assign(kvm_state, &dev->host, flags, &dev->dev_id); if (r < 0) { - error_report("Failed to assign device \"%s\" : %s", - dev->dev.qdev.id, strerror(-r)); - switch (r) { - case -EBUSY: - assign_failed_examine(dev); + case -EBUSY: { + char *cause; + + cause = assign_failed_examine(dev); + error_setg_errno(errp, -r, "Failed to assign device \"%s\"\n%s", + dev->dev.qdev.id, cause); + g_free(cause); break; + } default: + error_setg_errno(errp, -r, "Failed to assign device \"%s\"", + dev->dev.qdev.id); break; } } - return r; } -static bool check_irqchip_in_kernel(void) +static void verify_irqchip_in_kernel(Error **errp) { if (kvm_irqchip_in_kernel()) { - return true; + return; } - error_report("pci-assign: error: requires KVM with in-kernel irqchip " - "enabled"); - return false; + error_setg(errp, "pci-assign requires KVM with in-kernel irqchip enabled"); } -static int assign_intx(AssignedDevice *dev) +static int assign_intx(AssignedDevice *dev, Error **errp) { AssignedIRQType new_type; PCIINTxRoute intx_route; bool intx_host_msi; int r; + Error *local_err = NULL; /* Interrupt PIN 0 means don't use INTx */ if (assigned_dev_pci_read_byte(&dev->dev, PCI_INTERRUPT_PIN) == 0) { @@ -842,7 +856,9 @@ static int assign_intx(AssignedDevice *dev) return 0; } - if (!check_irqchip_in_kernel()) { + verify_irqchip_in_kernel(&local_err); + if (local_err) { + error_propagate(errp, local_err); return -ENOTSUP; } @@ -905,10 +921,11 @@ retry: dev->features |= ASSIGNED_DEVICE_PREFER_MSI_MASK; goto retry; } - error_report("Failed to assign irq for \"%s\": %s", - dev->dev.qdev.id, strerror(-r)); - error_report("Perhaps you are assigning a device " - "that shares an IRQ with another device?"); + error_setg_errno(errp, -r, + "Failed to assign irq for \"%s\"\n" + "Perhaps you are assigning a device " + "that shares an IRQ with another device?", + dev->dev.qdev.id); return r; } @@ -934,8 +951,11 @@ static void assigned_dev_update_irq_routing(PCIDevice *dev) Error *err = NULL; int r; - r = assign_intx(assigned_dev); + r = assign_intx(assigned_dev, &err); if (r < 0) { + error_report("%s", error_get_pretty(err)); + error_free(err); + err = NULL; qdev_unplug(&dev->qdev, &err); assert(!err); } @@ -986,7 +1006,13 @@ static void assigned_dev_update_msi(PCIDevice *pci_dev) assigned_dev->intx_route.irq = -1; assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSI; } else { - assign_intx(assigned_dev); + Error *local_err = NULL; + + assign_intx(assigned_dev, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); + } } } @@ -1128,7 +1154,13 @@ static void assigned_dev_update_msix(PCIDevice *pci_dev) assigned_dev->intx_route.irq = -1; assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSIX; } else { - assign_intx(assigned_dev); + Error *local_err = NULL; + + assign_intx(assigned_dev, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); + } } } @@ -1214,11 +1246,12 @@ static void assigned_dev_setup_cap_read(AssignedDevice *dev, uint32_t offset, assigned_dev_emulate_config_read(dev, offset + PCI_CAP_LIST_NEXT, 1); } -static int assigned_device_pci_cap_init(PCIDevice *pci_dev) +static int assigned_device_pci_cap_init(PCIDevice *pci_dev, Error **errp) { AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev); PCIRegion *pci_region = dev->real_device.regions; int ret, pos; + Error *local_err = NULL; /* Clear initial capabilities pointer and status copied from hw */ pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0); @@ -1230,13 +1263,17 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) * MSI capability is the 1st capability in capability config */ pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0); if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) { - if (!check_irqchip_in_kernel()) { + verify_irqchip_in_kernel(&local_err); + if (local_err) { + error_propagate(errp, local_err); return -ENOTSUP; } dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI; /* Only 32-bit/no-mask currently supported */ - ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_MSI, pos, 10, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } pci_dev->msi_cap = pos; @@ -1258,20 +1295,26 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) if (pos != 0 && kvm_device_msix_supported(kvm_state)) { int bar_nr; uint32_t msix_table_entry; + uint16_t msix_max; - if (!check_irqchip_in_kernel()) { + verify_irqchip_in_kernel(&local_err); + if (local_err) { + error_propagate(errp, local_err); return -ENOTSUP; } dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX; - ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_MSIX, pos, 12, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } pci_dev->msix_cap = pos; - pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS, - pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) & - PCI_MSIX_FLAGS_QSIZE); + msix_max = (pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) & + PCI_MSIX_FLAGS_QSIZE) + 1; + msix_max = MIN(msix_max, KVM_MAX_MSIX_PER_DEV); + pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS, msix_max - 1); /* Only enable and function mask bits are writable */ pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS, @@ -1281,9 +1324,7 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK; msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK; dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry; - dev->msix_max = pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS); - dev->msix_max &= PCI_MSIX_FLAGS_QSIZE; - dev->msix_max += 1; + dev->msix_max = msix_max; } /* Minimal PM support, nothing writable, device appears to NAK changes */ @@ -1291,8 +1332,10 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) if (pos) { uint16_t pmc; - ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } @@ -1330,8 +1373,8 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) */ size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos); if (size < 0x34) { - error_report("%s: Invalid size PCIe cap-id 0x%x", - __func__, PCI_CAP_ID_EXP); + error_setg(errp, "Invalid size PCIe cap-id 0x%x", + PCI_CAP_ID_EXP); return -EINVAL; } else if (size != 0x3c) { error_report("WARNING, %s: PCIe cap-id 0x%x has " @@ -1352,13 +1395,15 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) } if (size == 0) { - error_report("%s: Unsupported PCI express capability version %d", - __func__, version); + error_setg(errp, "Unsupported PCI express capability version %d", + version); return -EINVAL; } - ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP, pos, size); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_EXP, pos, size, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } @@ -1368,8 +1413,8 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) type = (type & PCI_EXP_FLAGS_TYPE) >> 4; if (type != PCI_EXP_TYPE_ENDPOINT && type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) { - error_report("Device assignment only supports endpoint assignment," - " device type %d", type); + error_setg(errp, "Device assignment only supports endpoint " + "assignment, device type %d", type); return -EINVAL; } @@ -1431,8 +1476,10 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) uint32_t status; /* Only expose the minimum, 8 byte capability */ - ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_PCIX, pos, 8, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } @@ -1457,8 +1504,10 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0); if (pos) { /* Direct R/W passthrough */ - ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_VPD, pos, 8, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } @@ -1473,8 +1522,10 @@ static int assigned_device_pci_cap_init(PCIDevice *pci_dev) pos += PCI_CAP_LIST_NEXT) { uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS); /* Direct R/W passthrough */ - ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR, pos, len); + ret = pci_add_capability2(pci_dev, PCI_CAP_ID_VNDR, pos, len, + &local_err); if (ret < 0) { + error_propagate(errp, local_err); return ret; } @@ -1602,20 +1653,20 @@ static void assigned_dev_msix_reset(AssignedDevice *dev) } } -static int assigned_dev_register_msix_mmio(AssignedDevice *dev) +static void assigned_dev_register_msix_mmio(AssignedDevice *dev, Error **errp) { dev->msix_table = mmap(NULL, MSIX_PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, 0, 0); if (dev->msix_table == MAP_FAILED) { - error_report("fail allocate msix_table! %s", strerror(errno)); - return -EFAULT; + error_setg_errno(errp, errno, "failed to allocate msix_table"); + dev->msix_table = NULL; + return; } assigned_dev_msix_reset(dev); memory_region_init_io(&dev->mmio, OBJECT(dev), &assigned_dev_msix_mmio_ops, dev, "assigned-dev-msix", MSIX_PAGE_SIZE); - return 0; } static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev) @@ -1624,8 +1675,6 @@ static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev) return; } - memory_region_destroy(&dev->mmio); - if (munmap(dev->msix_table, MSIX_PAGE_SIZE) == -1) { error_report("error unmapping msix_table! %s", strerror(errno)); } @@ -1698,16 +1747,17 @@ static int assigned_initfn(struct PCIDevice *pci_dev) AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev); uint8_t e_intx; int r; + Error *local_err = NULL; if (!kvm_enabled()) { - error_report("pci-assign: error: requires KVM support"); - return -1; + error_setg(&local_err, "pci-assign requires KVM support"); + goto exit_with_error; } if (!dev->host.domain && !dev->host.bus && !dev->host.slot && !dev->host.function) { - error_report("pci-assign: error: no host device specified"); - return -1; + error_setg(&local_err, "no host device specified"); + goto exit_with_error; } /* @@ -1730,27 +1780,28 @@ static int assigned_initfn(struct PCIDevice *pci_dev) memcpy(dev->emulate_config_write, dev->emulate_config_read, sizeof(dev->emulate_config_read)); - if (get_real_device(dev)) { - error_report("pci-assign: Error: Couldn't get real device (%s)!", - dev->dev.qdev.id); + get_real_device(dev, &local_err); + if (local_err) { goto out; } - if (assigned_device_pci_cap_init(pci_dev) < 0) { + if (assigned_device_pci_cap_init(pci_dev, &local_err) < 0) { goto out; } /* intercept MSI-X entry page in the MMIO */ if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) { - if (assigned_dev_register_msix_mmio(dev)) { + assigned_dev_register_msix_mmio(dev, &local_err); + if (local_err) { goto out; } } /* handle real device's MMIO/PIO BARs */ - if (assigned_dev_register_regions(dev->real_device.regions, - dev->real_device.region_number, - dev)) { + assigned_dev_register_regions(dev->real_device.regions, + dev->real_device.region_number, dev, + &local_err); + if (local_err) { goto out; } @@ -1761,27 +1812,31 @@ static int assigned_initfn(struct PCIDevice *pci_dev) dev->intx_route.irq = -1; /* assign device to guest */ - r = assign_device(dev); - if (r < 0) { + assign_device(dev, &local_err); + if (local_err) { goto out; } /* assign legacy INTx to the device */ - r = assign_intx(dev); + r = assign_intx(dev, &local_err); if (r < 0) { goto assigned_out; } assigned_dev_load_option_rom(dev); - add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL); - return 0; assigned_out: deassign_device(dev); + out: free_assigned_device(dev); + +exit_with_error: + assert(local_err); + qerror_report_err(local_err); + error_free(local_err); return -1; } @@ -1793,13 +1848,22 @@ static void assigned_exitfn(struct PCIDevice *pci_dev) free_assigned_device(dev); } +static void assigned_dev_instance_init(Object *obj) +{ + PCIDevice *pci_dev = PCI_DEVICE(obj); + AssignedDevice *d = DO_UPCAST(AssignedDevice, dev, PCI_DEVICE(obj)); + + device_add_bootindex_property(obj, &d->bootindex, + "bootindex", NULL, + &pci_dev->qdev, NULL); +} + static Property assigned_dev_properties[] = { DEFINE_PROP_PCI_HOST_DEVADDR("host", AssignedDevice, host), DEFINE_PROP_BIT("prefer_msi", AssignedDevice, features, ASSIGNED_DEVICE_PREFER_MSI_BIT, false), DEFINE_PROP_BIT("share_intx", AssignedDevice, features, ASSIGNED_DEVICE_SHARE_INTX_BIT, true), - DEFINE_PROP_INT32("bootindex", AssignedDevice, bootindex, -1), DEFINE_PROP_STRING("configfd", AssignedDevice, configfd_name), DEFINE_PROP_END_OF_LIST(), }; @@ -1825,6 +1889,7 @@ static const TypeInfo assign_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(AssignedDevice), .class_init = assign_class_init, + .instance_init = assigned_dev_instance_init, }; static void assign_register_types(void) @@ -1879,7 +1944,8 @@ static void assigned_dev_load_option_rom(AssignedDevice *dev) snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(dev))); - memory_region_init_ram(&dev->dev.rom, OBJECT(dev), name, st.st_size); + memory_region_init_ram(&dev->dev.rom, OBJECT(dev), name, st.st_size, + &error_abort); vmstate_register_ram(&dev->dev.rom, &dev->dev.qdev); ptr = memory_region_get_ram_ptr(&dev->dev.rom); memset(ptr, 0xff, st.st_size); @@ -1889,7 +1955,6 @@ static void assigned_dev_load_option_rom(AssignedDevice *dev) error_printf("Device option ROM contents are probably invalid " "(check dmesg).\nSkip option ROM probe with rombar=0, " "or load from file with romfile=\n"); - memory_region_destroy(&dev->dev.rom); goto close_rom; } diff --git a/hw/i386/kvmvapic.c b/hw/i386/kvmvapic.c index a1c3d1cb85..c6d34b2546 100644 --- a/hw/i386/kvmvapic.c +++ b/hw/i386/kvmvapic.c @@ -59,6 +59,7 @@ typedef struct VAPICROMState { GuestROMState rom_state; size_t rom_size; bool rom_mapped_writable; + VMChangeStateEntry *vmsentry; } VAPICROMState; #define TYPE_VAPIC "kvmvapic" @@ -124,14 +125,14 @@ static const TPRInstruction tpr_instr[] = { static void read_guest_rom_state(VAPICROMState *s) { - cpu_physical_memory_rw(s->rom_state_paddr, (void *)&s->rom_state, - sizeof(GuestROMState), 0); + cpu_physical_memory_read(s->rom_state_paddr, &s->rom_state, + sizeof(GuestROMState)); } static void write_guest_rom_state(VAPICROMState *s) { - cpu_physical_memory_rw(s->rom_state_paddr, (void *)&s->rom_state, - sizeof(GuestROMState), 1); + cpu_physical_memory_write(s->rom_state_paddr, &s->rom_state, + sizeof(GuestROMState)); } static void update_guest_rom_state(VAPICROMState *s) @@ -311,16 +312,14 @@ static int update_rom_mapping(VAPICROMState *s, CPUX86State *env, target_ulong i for (pos = le32_to_cpu(s->rom_state.fixup_start); pos < le32_to_cpu(s->rom_state.fixup_end); pos += 4) { - cpu_physical_memory_rw(paddr + pos - s->rom_state.vaddr, - (void *)&offset, sizeof(offset), 0); + cpu_physical_memory_read(paddr + pos - s->rom_state.vaddr, + &offset, sizeof(offset)); offset = le32_to_cpu(offset); - cpu_physical_memory_rw(paddr + offset, (void *)&patch, - sizeof(patch), 0); + cpu_physical_memory_read(paddr + offset, &patch, sizeof(patch)); patch = le32_to_cpu(patch); patch += rom_state_vaddr - le32_to_cpu(s->rom_state.vaddr); patch = cpu_to_le32(patch); - cpu_physical_memory_rw(paddr + offset, (void *)&patch, - sizeof(patch), 1); + cpu_physical_memory_write(paddr + offset, &patch, sizeof(patch)); } read_guest_rom_state(s); s->vapic_paddr = paddr + le32_to_cpu(s->rom_state.vapic_vaddr) - @@ -364,8 +363,8 @@ static int vapic_enable(VAPICROMState *s, X86CPU *cpu) } vapic_paddr = s->vapic_paddr + (((hwaddr)cpu_number) << VAPIC_CPU_SHIFT); - cpu_physical_memory_rw(vapic_paddr + offsetof(VAPICState, enabled), - (void *)&enabled, sizeof(enabled), 1); + cpu_physical_memory_write(vapic_paddr + offsetof(VAPICState, enabled), + &enabled, sizeof(enabled)); apic_enable_vapic(cpu->apic_state, vapic_paddr); s->state = VAPIC_ACTIVE; @@ -406,7 +405,6 @@ static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) } if (!kvm_enabled()) { - cpu_restore_state(cs, cs->mem_io_pc); cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base, ¤t_flags); } @@ -535,7 +533,7 @@ static int patch_hypercalls(VAPICROMState *s) uint8_t *rom; rom = g_malloc(s->rom_size); - cpu_physical_memory_rw(rom_paddr, rom, s->rom_size, 0); + cpu_physical_memory_read(rom_paddr, rom, s->rom_size); for (pos = 0; pos < s->rom_size - sizeof(vmcall_pattern); pos++) { if (kvm_irqchip_in_kernel()) { @@ -551,8 +549,7 @@ static int patch_hypercalls(VAPICROMState *s) } if (memcmp(rom + pos, pattern, 7) == 0 && (rom[pos + 7] == alternates[0] || rom[pos + 7] == alternates[1])) { - cpu_physical_memory_rw(rom_paddr + pos + 5, (uint8_t *)patch, - 3, 1); + cpu_physical_memory_write(rom_paddr + pos + 5, patch, 3); /* * Don't flush the tb here. Under ordinary conditions, the patched * calls are miles away from the current IP. Under malicious @@ -587,7 +584,7 @@ static int vapic_map_rom_writable(VAPICROMState *s) if (s->rom_mapped_writable) { memory_region_del_subregion(as, &s->rom); - memory_region_destroy(&s->rom); + object_unparent(OBJECT(&s->rom)); } /* grab RAM memory region (region @rom_paddr may still be pc.rom) */ @@ -734,14 +731,41 @@ static void do_vapic_enable(void *data) VAPICROMState *s = data; X86CPU *cpu = X86_CPU(first_cpu); - vapic_enable(s, cpu); + static const uint8_t enabled = 1; + cpu_physical_memory_write(s->vapic_paddr + offsetof(VAPICState, enabled), + &enabled, sizeof(enabled)); + apic_enable_vapic(cpu->apic_state, s->vapic_paddr); + s->state = VAPIC_ACTIVE; } -static int vapic_post_load(void *opaque, int version_id) +static void kvmvapic_vm_state_change(void *opaque, int running, + RunState state) { VAPICROMState *s = opaque; uint8_t *zero; + if (!running) { + return; + } + + if (s->state == VAPIC_ACTIVE) { + if (smp_cpus == 1) { + run_on_cpu(first_cpu, do_vapic_enable, s); + } else { + zero = g_malloc0(s->rom_state.vapic_size); + cpu_physical_memory_write(s->vapic_paddr, zero, + s->rom_state.vapic_size); + g_free(zero); + } + } + + qemu_del_vm_change_state_handler(s->vmsentry); +} + +static int vapic_post_load(void *opaque, int version_id) +{ + VAPICROMState *s = opaque; + /* * The old implementation of qemu-kvm did not provide the state * VAPIC_STANDBY. Reconstruct it. @@ -755,17 +779,11 @@ static int vapic_post_load(void *opaque, int version_id) return -1; } } - if (s->state == VAPIC_ACTIVE) { - if (smp_cpus == 1) { - run_on_cpu(first_cpu, do_vapic_enable, s); - } else { - zero = g_malloc0(s->rom_state.vapic_size); - cpu_physical_memory_rw(s->vapic_paddr, zero, - s->rom_state.vapic_size, 1); - g_free(zero); - } - } + if (!s->vmsentry) { + s->vmsentry = + qemu_add_vm_change_state_handler(kvmvapic_vm_state_change, s); + } return 0; } @@ -773,7 +791,6 @@ static const VMStateDescription vmstate_handlers = { .name = "kvmvapic-handlers", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(set_tpr, VAPICHandlers), VMSTATE_UINT32(set_tpr_eax, VAPICHandlers), @@ -787,7 +804,6 @@ static const VMStateDescription vmstate_guest_rom = { .name = "kvmvapic-guest-rom", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UNUSED(8), /* signature */ VMSTATE_UINT32(vaddr, GuestROMState), @@ -807,7 +823,6 @@ static const VMStateDescription vmstate_vapic = { .name = "kvm-tpr-opt", /* compatible with qemu-kvm VAPIC */ .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = vapic_post_load, .fields = (VMStateField[]) { VMSTATE_STRUCT(rom_state, VAPICROMState, 0, vmstate_guest_rom, diff --git a/hw/i386/pc.c b/hw/i386/pc.c index d6628d7f60..6e83a17d30 100644 --- a/hw/i386/pc.c +++ b/hw/i386/pc.c @@ -44,7 +44,7 @@ #include "sysemu/kvm.h" #include "kvm_i386.h" #include "hw/xen/xen.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/block/block.h" #include "ui/qemu-spice.h" #include "exec/memory.h" @@ -58,6 +58,10 @@ #include "hw/boards.h" #include "hw/pci/pci_host.h" #include "acpi-build.h" +#include "hw/mem/pc-dimm.h" +#include "trace.h" +#include "qapi/visitor.h" +#include "qapi-visit.h" #ifdef CONFIG_MARU #include "tizen/src/util/maru_err_table.h" @@ -72,8 +76,15 @@ #define DPRINTF(fmt, ...) #endif -/* Leave a chunk of memory at the top of RAM for the BIOS ACPI tables. */ -#define ACPI_DATA_SIZE 0x10000 +/* Leave a chunk of memory at the top of RAM for the BIOS ACPI tables + * (128K) and other BIOS datastructures (less than 4K reported to be used at + * the moment, 32K should be enough for a while). */ +static unsigned acpi_data_size = 0x20000 + 0x8000; +void pc_set_legacy_acpi_data_size(void) +{ + acpi_data_size = 0x10000; +} + #define BIOS_CFG_IOPORT 0x510 #define FW_CFG_ACPI_TABLES (FW_CFG_ARCH_LOCAL + 0) #define FW_CFG_SMBIOS_ENTRIES (FW_CFG_ARCH_LOCAL + 1) @@ -348,30 +359,15 @@ static void pc_cmos_init_late(void *opaque) qemu_unregister_reset(pc_cmos_init_late, opaque); } -typedef struct RTCCPUHotplugArg { - Notifier cpu_added_notifier; - ISADevice *rtc_state; -} RTCCPUHotplugArg; - -static void rtc_notify_cpu_added(Notifier *notifier, void *data) -{ - RTCCPUHotplugArg *arg = container_of(notifier, RTCCPUHotplugArg, - cpu_added_notifier); - ISADevice *s = arg->rtc_state; - - /* increment the number of CPUs */ - rtc_set_memory(s, 0x5f, rtc_get_memory(s, 0x5f) + 1); -} - void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size, - const char *boot_device, + const char *boot_device, MachineState *machine, ISADevice *floppy, BusState *idebus0, BusState *idebus1, ISADevice *s) { int val, nb, i; FDriveType fd_type[2] = { FDRIVE_DRV_NONE, FDRIVE_DRV_NONE }; static pc_cmos_init_late_arg arg; - static RTCCPUHotplugArg cpu_hotplug_cb; + PCMachineState *pc_machine = PC_MACHINE(machine); /* various important CMOS locations needed by PC/Bochs bios */ @@ -410,10 +406,14 @@ void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size, /* set the number of CPU */ rtc_set_memory(s, 0x5f, smp_cpus - 1); - /* init CPU hotplug notifier */ - cpu_hotplug_cb.rtc_state = s; - cpu_hotplug_cb.cpu_added_notifier.notify = rtc_notify_cpu_added; - qemu_register_cpu_added_notifier(&cpu_hotplug_cb.cpu_added_notifier); + + object_property_add_link(OBJECT(machine), "rtc_state", + TYPE_ISA_DEVICE, + (Object **)&pc_machine->rtc, + object_property_allow_set_link, + OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort); + object_property_set_link(OBJECT(machine), OBJECT(s), + "rtc_state", &error_abort); if (set_boot_dev(s, boot_device)) { exit(1); @@ -474,11 +474,12 @@ static void port92_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { Port92State *s = opaque; + int oldval = s->outport; - DPRINTF("port92: write 0x%02x\n", val); + DPRINTF("port92: write 0x%02" PRIx64 "\n", val); s->outport = val; qemu_set_irq(*s->a20_out, (val >> 1) & 1); - if (val & 1) { + if ((val & 1) && !(oldval & 1)) { qemu_system_reset_request(); } } @@ -505,8 +506,7 @@ static const VMStateDescription vmstate_port92_isa = { .name = "port92", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(outport, Port92State), VMSTATE_END_OF_LIST() } @@ -615,6 +615,21 @@ int e820_add_entry(uint64_t address, uint64_t length, uint32_t type) return e820_entries; } +int e820_get_num_entries(void) +{ + return e820_entries; +} + +bool e820_get_entry(int idx, uint32_t type, uint64_t *address, uint64_t *length) +{ + if (idx < e820_entries && e820_table[idx].type == cpu_to_le32(type)) { + *address = le64_to_cpu(e820_table[idx].address); + *length = le64_to_cpu(e820_table[idx].length); + return true; + } + return false; +} + /* Calculates the limit to CPU APIC ID values * * This function returns the limit for the APIC ID value, so that all @@ -630,8 +645,8 @@ static unsigned int pc_apic_id_limit(unsigned int max_cpus) static FWCfgState *bochs_bios_init(void) { FWCfgState *fw_cfg; - uint8_t *smbios_table; - size_t smbios_len; + uint8_t *smbios_tables, *smbios_anchor; + size_t smbios_tables_len, smbios_anchor_len; uint64_t *numa_fw_cfg; int i, j; unsigned int apic_id_limit = pc_apic_id_limit(max_cpus); @@ -658,10 +673,21 @@ static FWCfgState *bochs_bios_init(void) acpi_tables, acpi_tables_len); fw_cfg_add_i32(fw_cfg, FW_CFG_IRQ0_OVERRIDE, kvm_allows_irq0_override()); - smbios_table = smbios_get_table(&smbios_len); - if (smbios_table) + smbios_tables = smbios_get_table_legacy(&smbios_tables_len); + if (smbios_tables) { fw_cfg_add_bytes(fw_cfg, FW_CFG_SMBIOS_ENTRIES, - smbios_table, smbios_len); + smbios_tables, smbios_tables_len); + } + + smbios_get_tables(&smbios_tables, &smbios_tables_len, + &smbios_anchor, &smbios_anchor_len); + if (smbios_anchor) { + fw_cfg_add_file(fw_cfg, "etc/smbios/smbios-tables", + smbios_tables, smbios_tables_len); + fw_cfg_add_file(fw_cfg, "etc/smbios/smbios-anchor", + smbios_anchor, smbios_anchor_len); + } + fw_cfg_add_bytes(fw_cfg, FW_CFG_E820_TABLE, &e820_reserve, sizeof(e820_reserve)); fw_cfg_add_file(fw_cfg, "etc/e820", e820_table, @@ -678,14 +704,14 @@ static FWCfgState *bochs_bios_init(void) unsigned int apic_id = x86_cpu_apic_id_from_index(i); assert(apic_id < apic_id_limit); for (j = 0; j < nb_numa_nodes; j++) { - if (test_bit(i, node_cpumask[j])) { + if (test_bit(i, numa_info[j].node_cpu)) { numa_fw_cfg[apic_id + 1] = cpu_to_le64(j); break; } } } for (i = 0; i < nb_numa_nodes; i++) { - numa_fw_cfg[apic_id_limit + 1 + i] = cpu_to_le64(node_mem[i]); + numa_fw_cfg[apic_id_limit + 1 + i] = cpu_to_le64(numa_info[i].node_mem); } fw_cfg_add_bytes(fw_cfg, FW_CFG_NUMA, numa_fw_cfg, (1 + apic_id_limit + nb_numa_nodes) * @@ -792,8 +818,9 @@ static void load_linux(FWCfgState *fw_cfg, initrd_max = 0x37ffffff; } - if (initrd_max >= max_ram_size-ACPI_DATA_SIZE) - initrd_max = max_ram_size-ACPI_DATA_SIZE-1; + if (initrd_max >= max_ram_size - acpi_data_size) { + initrd_max = max_ram_size - acpi_data_size - 1; + } fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_ADDR, cmdline_addr); fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, strlen(kernel_cmdline)+1); @@ -1034,6 +1061,9 @@ void pc_cpus_init(const char *cpu_model, DeviceState *icc_bridge) sysbus_mmio_map_overlap(SYS_BUS_DEVICE(icc_bridge), 0, APIC_DEFAULT_ADDRESS, 0x1000); } + + /* tell smbios about cpuid version and features */ + smbios_set_cpuid(cpu->env.cpuid_version, cpu->env.features[FEAT_1_EDX]); } /* pci-info ROM file. Little endian format */ @@ -1044,35 +1074,6 @@ typedef struct PcRomPciInfo { uint64_t w64_max; } PcRomPciInfo; -static void pc_fw_cfg_guest_info(PcGuestInfo *guest_info) -{ - PcRomPciInfo *info; - Object *pci_info; - bool ambiguous = false; - - if (!guest_info->has_pci_info || !guest_info->fw_cfg) { - return; - } - pci_info = object_resolve_path_type("", TYPE_PCI_HOST_BRIDGE, &ambiguous); - g_assert(!ambiguous); - if (!pci_info) { - return; - } - - info = g_malloc(sizeof *info); - info->w32_min = cpu_to_le64(object_property_get_int(pci_info, - PCI_HOST_PROP_PCI_HOLE_START, NULL)); - info->w32_max = cpu_to_le64(object_property_get_int(pci_info, - PCI_HOST_PROP_PCI_HOLE_END, NULL)); - info->w64_min = cpu_to_le64(object_property_get_int(pci_info, - PCI_HOST_PROP_PCI_HOLE64_START, NULL)); - info->w64_max = cpu_to_le64(object_property_get_int(pci_info, - PCI_HOST_PROP_PCI_HOLE64_END, NULL)); - /* Pass PCI hole info to guest via a side channel. - * Required so guest PCI enumeration does the right thing. */ - fw_cfg_add_file(guest_info->fw_cfg, "etc/pci-info", info, sizeof *info); -} - typedef struct PcGuestInfoState { PcGuestInfo info; Notifier machine_done; @@ -1084,7 +1085,6 @@ void pc_guest_info_machine_done(Notifier *notifier, void *data) PcGuestInfoState *guest_info_state = container_of(notifier, PcGuestInfoState, machine_done); - pc_fw_cfg_guest_info(&guest_info_state->info); acpi_setup(&guest_info_state->info); } @@ -1100,8 +1100,12 @@ PcGuestInfo *pc_guest_info_init(ram_addr_t below_4g_mem_size, guest_info->apic_id_limit = pc_apic_id_limit(max_cpus); guest_info->apic_xrupt_override = kvm_allows_irq0_override(); guest_info->numa_nodes = nb_numa_nodes; - guest_info->node_mem = g_memdup(node_mem, guest_info->numa_nodes * + guest_info->node_mem = g_malloc0(guest_info->numa_nodes * sizeof *guest_info->node_mem); + for (i = 0; i < nb_numa_nodes; i++) { + guest_info->node_mem[i] = numa_info[i].node_mem; + } + guest_info->node_cpu = g_malloc0(guest_info->apic_id_limit * sizeof *guest_info->node_cpu); @@ -1109,7 +1113,7 @@ PcGuestInfo *pc_guest_info_init(ram_addr_t below_4g_mem_size, unsigned int apic_id = x86_cpu_apic_id_from_index(i); assert(apic_id < guest_info->apic_id_limit); for (j = 0; j < nb_numa_nodes; j++) { - if (test_bit(i, node_cpumask[j])) { + if (test_bit(i, numa_info[j].node_cpu)) { guest_info->node_cpu[apic_id] = j; break; } @@ -1164,11 +1168,34 @@ void pc_acpi_init(const char *default_dsdt) } } -FWCfgState *pc_memory_init(MemoryRegion *system_memory, - const char *kernel_filename, +FWCfgState *xen_load_linux(const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, ram_addr_t below_4g_mem_size, + PcGuestInfo *guest_info) +{ + int i; + FWCfgState *fw_cfg; + + assert(kernel_filename != NULL); + + fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0); + rom_set_fw(fw_cfg); + + load_linux(fw_cfg, kernel_filename, initrd_filename, + kernel_cmdline, below_4g_mem_size); + for (i = 0; i < nb_option_roms; i++) { + assert(!strcmp(option_rom[i].name, "linuxboot.bin") || + !strcmp(option_rom[i].name, "multiboot.bin")); + rom_add_option(option_rom[i].name, option_rom[i].bootindex); + } + guest_info->fw_cfg = fw_cfg; + return fw_cfg; +} + +FWCfgState *pc_memory_init(MachineState *machine, + MemoryRegion *system_memory, + ram_addr_t below_4g_mem_size, ram_addr_t above_4g_mem_size, MemoryRegion *rom_memory, MemoryRegion **ram_memory, @@ -1178,17 +1205,19 @@ FWCfgState *pc_memory_init(MemoryRegion *system_memory, MemoryRegion *ram, *option_rom_mr; MemoryRegion *ram_below_4g, *ram_above_4g; FWCfgState *fw_cfg; + PCMachineState *pcms = PC_MACHINE(machine); - linux_boot = (kernel_filename != NULL); + assert(machine->ram_size == below_4g_mem_size + above_4g_mem_size); + + linux_boot = (machine->kernel_filename != NULL); /* Allocate RAM. We allocate it as a single memory region and use * aliases to address portions of it, mostly for backwards compatibility * with older qemus that used qemu_ram_alloc(). */ ram = g_malloc(sizeof(*ram)); - memory_region_init_ram(ram, NULL, "pc.ram", - below_4g_mem_size + above_4g_mem_size); - vmstate_register_ram_global(ram); + memory_region_allocate_system_memory(ram, NULL, "pc.ram", + machine->ram_size); *ram_memory = ram; ram_below_4g = g_malloc(sizeof(*ram_below_4g)); memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram, @@ -1204,12 +1233,55 @@ FWCfgState *pc_memory_init(MemoryRegion *system_memory, e820_add_entry(0x100000000ULL, above_4g_mem_size, E820_RAM); } + if (!guest_info->has_reserved_memory && + (machine->ram_slots || + (machine->maxram_size > machine->ram_size))) { + MachineClass *mc = MACHINE_GET_CLASS(machine); + + error_report("\"-memory 'slots|maxmem'\" is not supported by: %s", + mc->name); + exit(EXIT_FAILURE); + } + + /* initialize hotplug memory address space */ + if (guest_info->has_reserved_memory && + (machine->ram_size < machine->maxram_size)) { + ram_addr_t hotplug_mem_size = + machine->maxram_size - machine->ram_size; + + if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) { + error_report("unsupported amount of memory slots: %"PRIu64, + machine->ram_slots); + exit(EXIT_FAILURE); + } + + pcms->hotplug_memory_base = + ROUND_UP(0x100000000ULL + above_4g_mem_size, 1ULL << 30); + + if (pcms->enforce_aligned_dimm) { + /* size hotplug region assuming 1G page max alignment per slot */ + hotplug_mem_size += (1ULL << 30) * machine->ram_slots; + } + + if ((pcms->hotplug_memory_base + hotplug_mem_size) < + hotplug_mem_size) { + error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT, + machine->maxram_size); + exit(EXIT_FAILURE); + } + + memory_region_init(&pcms->hotplug_memory, OBJECT(pcms), + "hotplug-memory", hotplug_mem_size); + memory_region_add_subregion(system_memory, pcms->hotplug_memory_base, + &pcms->hotplug_memory); + } /* Initialize PC system firmware */ pc_system_firmware_init(rom_memory, guest_info->isapc_ram_fw); option_rom_mr = g_malloc(sizeof(*option_rom_mr)); - memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE); + memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE, + &error_abort); vmstate_register_ram_global(option_rom_mr); memory_region_add_subregion_overlap(rom_memory, PC_ROM_MIN_VGA, @@ -1219,8 +1291,15 @@ FWCfgState *pc_memory_init(MemoryRegion *system_memory, fw_cfg = bochs_bios_init(); rom_set_fw(fw_cfg); + if (guest_info->has_reserved_memory && pcms->hotplug_memory_base) { + uint64_t *val = g_malloc(sizeof(*val)); + *val = cpu_to_le64(ROUND_UP(pcms->hotplug_memory_base, 0x1ULL << 30)); + fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val)); + } + if (linux_boot) { - load_linux(fw_cfg, kernel_filename, initrd_filename, kernel_cmdline, below_4g_mem_size); + load_linux(fw_cfg, machine->kernel_filename, machine->initrd_filename, + machine->kernel_cmdline, below_4g_mem_size); } for (i = 0; i < nb_option_roms; i++) { @@ -1436,3 +1515,351 @@ void ioapic_init_gsi(GSIState *gsi_state, const char *parent_name) gsi_state->ioapic_irq[i] = qdev_get_gpio_in(dev, i); } } + +static void pc_generic_machine_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + QEMUMachine *qm = data; + + mc->family = qm->family; + mc->name = qm->name; + mc->alias = qm->alias; + mc->desc = qm->desc; + mc->init = qm->init; + mc->reset = qm->reset; + mc->hot_add_cpu = qm->hot_add_cpu; + mc->kvm_type = qm->kvm_type; + mc->block_default_type = qm->block_default_type; + mc->units_per_default_bus = qm->units_per_default_bus; + mc->max_cpus = qm->max_cpus; + mc->no_serial = qm->no_serial; + mc->no_parallel = qm->no_parallel; + mc->use_virtcon = qm->use_virtcon; + mc->use_sclp = qm->use_sclp; + mc->no_floppy = qm->no_floppy; + mc->no_cdrom = qm->no_cdrom; + mc->no_sdcard = qm->no_sdcard; + mc->is_default = qm->is_default; + mc->default_machine_opts = qm->default_machine_opts; + mc->default_boot_order = qm->default_boot_order; + mc->default_display = qm->default_display; + mc->compat_props = qm->compat_props; + mc->hw_version = qm->hw_version; +} + +void qemu_register_pc_machine(QEMUMachine *m) +{ + char *name = g_strconcat(m->name, TYPE_MACHINE_SUFFIX, NULL); + TypeInfo ti = { + .name = name, + .parent = TYPE_PC_MACHINE, + .class_init = pc_generic_machine_class_init, + .class_data = (void *)m, + }; + + type_register(&ti); + g_free(name); +} + +static int pc_dimm_count(Object *obj, void *opaque) +{ + int *count = opaque; + + if (object_dynamic_cast(obj, TYPE_PC_DIMM)) { + (*count)++; + } + + object_child_foreach(obj, pc_dimm_count, opaque); + return 0; +} + +static int pc_existing_dimms_capacity(Object *obj, void *opaque) +{ + Error *local_err = NULL; + uint64_t *size = opaque; + + if (object_dynamic_cast(obj, TYPE_PC_DIMM)) { + (*size) += object_property_get_int(obj, PC_DIMM_SIZE_PROP, &local_err); + + if (local_err) { + qerror_report_err(local_err); + error_free(local_err); + return 1; + } + } + + object_child_foreach(obj, pc_dimm_count, opaque); + return 0; +} + +static void pc_dimm_plug(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + int slot; + HotplugHandlerClass *hhc; + Error *local_err = NULL; + PCMachineState *pcms = PC_MACHINE(hotplug_dev); + MachineState *machine = MACHINE(hotplug_dev); + PCDIMMDevice *dimm = PC_DIMM(dev); + PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm); + MemoryRegion *mr = ddc->get_memory_region(dimm); + uint64_t existing_dimms_capacity = 0; + uint64_t align = TARGET_PAGE_SIZE; + uint64_t addr; + + addr = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP, &local_err); + if (local_err) { + goto out; + } + + if (memory_region_get_alignment(mr) && pcms->enforce_aligned_dimm) { + align = memory_region_get_alignment(mr); + } + + addr = pc_dimm_get_free_addr(pcms->hotplug_memory_base, + memory_region_size(&pcms->hotplug_memory), + !addr ? NULL : &addr, align, + memory_region_size(mr), &local_err); + if (local_err) { + goto out; + } + + if (pc_existing_dimms_capacity(OBJECT(machine), &existing_dimms_capacity)) { + error_setg(&local_err, "failed to get total size of existing DIMMs"); + goto out; + } + + if (existing_dimms_capacity + memory_region_size(mr) > + machine->maxram_size - machine->ram_size) { + error_setg(&local_err, "not enough space, currently 0x%" PRIx64 + " in use of total 0x" RAM_ADDR_FMT, + existing_dimms_capacity, machine->maxram_size); + goto out; + } + + object_property_set_int(OBJECT(dev), addr, PC_DIMM_ADDR_PROP, &local_err); + if (local_err) { + goto out; + } + trace_mhp_pc_dimm_assigned_address(addr); + + slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP, &local_err); + if (local_err) { + goto out; + } + + slot = pc_dimm_get_free_slot(slot == PC_DIMM_UNASSIGNED_SLOT ? NULL : &slot, + machine->ram_slots, &local_err); + if (local_err) { + goto out; + } + object_property_set_int(OBJECT(dev), slot, PC_DIMM_SLOT_PROP, &local_err); + if (local_err) { + goto out; + } + trace_mhp_pc_dimm_assigned_slot(slot); + + if (!pcms->acpi_dev) { + error_setg(&local_err, + "memory hotplug is not enabled: missing acpi device"); + goto out; + } + + if (kvm_enabled() && !kvm_has_free_slot(machine)) { + error_setg(&local_err, "hypervisor has no free memory slots left"); + goto out; + } + + memory_region_add_subregion(&pcms->hotplug_memory, + addr - pcms->hotplug_memory_base, mr); + vmstate_register_ram(mr, dev); + + hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev); + hhc->plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err); +out: + error_propagate(errp, local_err); +} + +static void pc_cpu_plug(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + HotplugHandlerClass *hhc; + Error *local_err = NULL; + PCMachineState *pcms = PC_MACHINE(hotplug_dev); + + if (!dev->hotplugged) { + goto out; + } + + if (!pcms->acpi_dev) { + error_setg(&local_err, + "cpu hotplug is not enabled: missing acpi device"); + goto out; + } + + hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev); + hhc->plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err); + if (local_err) { + goto out; + } + + /* increment the number of CPUs */ + rtc_set_memory(pcms->rtc, 0x5f, rtc_get_memory(pcms->rtc, 0x5f) + 1); +out: + error_propagate(errp, local_err); +} + +static void pc_machine_device_plug_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) { + pc_dimm_plug(hotplug_dev, dev, errp); + } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU)) { + pc_cpu_plug(hotplug_dev, dev, errp); + } +} + +static HotplugHandler *pc_get_hotpug_handler(MachineState *machine, + DeviceState *dev) +{ + PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(machine); + + if (object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM) || + object_dynamic_cast(OBJECT(dev), TYPE_CPU)) { + return HOTPLUG_HANDLER(machine); + } + + return pcmc->get_hotplug_handler ? + pcmc->get_hotplug_handler(machine, dev) : NULL; +} + +static void +pc_machine_get_hotplug_memory_region_size(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + int64_t value = memory_region_size(&pcms->hotplug_memory); + + visit_type_int(v, &value, name, errp); +} + +static void pc_machine_get_max_ram_below_4g(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + uint64_t value = pcms->max_ram_below_4g; + + visit_type_size(v, &value, name, errp); +} + +static void pc_machine_set_max_ram_below_4g(Object *obj, Visitor *v, + void *opaque, const char *name, + Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + Error *error = NULL; + uint64_t value; + + visit_type_size(v, &value, name, &error); + if (error) { + error_propagate(errp, error); + return; + } + if (value > (1ULL << 32)) { + error_set(&error, ERROR_CLASS_GENERIC_ERROR, + "Machine option 'max-ram-below-4g=%"PRIu64 + "' expects size less than or equal to 4G", value); + error_propagate(errp, error); + return; + } + + if (value < (1ULL << 20)) { + error_report("Warning: small max_ram_below_4g(%"PRIu64 + ") less than 1M. BIOS may not work..", + value); + } + + pcms->max_ram_below_4g = value; +} + +static void pc_machine_get_vmport(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + OnOffAuto vmport = pcms->vmport; + + visit_type_OnOffAuto(v, &vmport, name, errp); +} + +static void pc_machine_set_vmport(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + + visit_type_OnOffAuto(v, &pcms->vmport, name, errp); +} + +static bool pc_machine_get_aligned_dimm(Object *obj, Error **errp) +{ + PCMachineState *pcms = PC_MACHINE(obj); + + return pcms->enforce_aligned_dimm; +} + +static void pc_machine_initfn(Object *obj) +{ + PCMachineState *pcms = PC_MACHINE(obj); + + object_property_add(obj, PC_MACHINE_MEMHP_REGION_SIZE, "int", + pc_machine_get_hotplug_memory_region_size, + NULL, NULL, NULL, NULL); + pcms->max_ram_below_4g = 1ULL << 32; /* 4G */ + object_property_add(obj, PC_MACHINE_MAX_RAM_BELOW_4G, "size", + pc_machine_get_max_ram_below_4g, + pc_machine_set_max_ram_below_4g, + NULL, NULL, NULL); + + pcms->vmport = ON_OFF_AUTO_AUTO; + object_property_add(obj, PC_MACHINE_VMPORT, "OnOffAuto", + pc_machine_get_vmport, + pc_machine_set_vmport, + NULL, NULL, NULL); + + pcms->enforce_aligned_dimm = true; + object_property_add_bool(obj, PC_MACHINE_ENFORCE_ALIGNED_DIMM, + pc_machine_get_aligned_dimm, + NULL, NULL); +} + +static void pc_machine_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + PCMachineClass *pcmc = PC_MACHINE_CLASS(oc); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc); + + pcmc->get_hotplug_handler = mc->get_hotplug_handler; + mc->get_hotplug_handler = pc_get_hotpug_handler; + hc->plug = pc_machine_device_plug_cb; +} + +static const TypeInfo pc_machine_info = { + .name = TYPE_PC_MACHINE, + .parent = TYPE_MACHINE, + .abstract = true, + .instance_size = sizeof(PCMachineState), + .instance_init = pc_machine_initfn, + .class_size = sizeof(PCMachineClass), + .class_init = pc_machine_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + }, +}; + +static void pc_machine_register_types(void) +{ + type_register_static(&pc_machine_info); +} + +type_init(pc_machine_register_types) diff --git a/hw/i386/pc_piix.c b/hw/i386/pc_piix.c index 89636909e9..d6d09e146e 100644 --- a/hw/i386/pc_piix.c +++ b/hw/i386/pc_piix.c @@ -41,13 +41,14 @@ #include "hw/sysbus.h" #include "hw/cpu/icc_bus.h" #include "sysemu/arch_init.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/i2c/smbus.h" #include "hw/xen/xen.h" #include "exec/memory.h" #include "exec/address-spaces.h" #include "hw/acpi/acpi.h" #include "cpu.h" +#include "qemu/error-report.h" #ifdef CONFIG_XEN # include <xen/hvm/hvm_info_table.h> #endif @@ -58,20 +59,24 @@ static const int ide_iobase[MAX_IDE_BUS] = { 0x1f0, 0x170 }; static const int ide_iobase2[MAX_IDE_BUS] = { 0x3f6, 0x376 }; static const int ide_irq[MAX_IDE_BUS] = { 14, 15 }; -static bool has_pci_info; static bool has_acpi_build = true; -static bool smbios_type1_defaults = true; +static int legacy_acpi_table_size; +static bool smbios_defaults = true; +static bool smbios_legacy_mode; +static bool smbios_uuid_encoded = true; /* Make sure that guest addresses aligned at 1Gbyte boundaries get mapped to * host addresses aligned at 1Gbyte boundaries. This way we can use 1GByte * pages in the host. */ static bool gigabyte_align = true; +static bool has_reserved_memory = true; /* PC hardware initialisation */ -static void pc_init1(QEMUMachineInitArgs *args, +static void pc_init1(MachineState *machine, int pci_enabled, int kvmclock_enabled) { + PCMachineState *pc_machine = PC_MACHINE(machine); MemoryRegion *system_memory = get_system_memory(); MemoryRegion *system_io = get_system_io(); int i; @@ -95,8 +100,44 @@ static void pc_init1(QEMUMachineInitArgs *args, DeviceState *icc_bridge; FWCfgState *fw_cfg = NULL; PcGuestInfo *guest_info; + ram_addr_t lowmem; - if (xen_enabled() && xen_hvm_init(&ram_memory) != 0) { + /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory). + * If it doesn't, we need to split it in chunks below and above 4G. + * In any case, try to make sure that guest addresses aligned at + * 1G boundaries get mapped to host addresses aligned at 1G boundaries. + * For old machine types, use whatever split we used historically to avoid + * breaking migration. + */ + if (machine->ram_size >= 0xe0000000) { + lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000; + } else { + lowmem = 0xe0000000; + } + + /* Handle the machine opt max-ram-below-4g. It is basically doing + * min(qemu limit, user limit). + */ + if (lowmem > pc_machine->max_ram_below_4g) { + lowmem = pc_machine->max_ram_below_4g; + if (machine->ram_size - lowmem > lowmem && + lowmem & ((1ULL << 30) - 1)) { + error_report("Warning: Large machine and max_ram_below_4g(%"PRIu64 + ") not a multiple of 1G; possible bad performance.", + pc_machine->max_ram_below_4g); + } + } + + if (machine->ram_size >= lowmem) { + above_4g_mem_size = machine->ram_size - lowmem; + below_4g_mem_size = lowmem; + } else { + above_4g_mem_size = 0; + below_4g_mem_size = machine->ram_size; + } + + if (xen_enabled() && xen_hvm_init(&below_4g_mem_size, &above_4g_mem_size, + &ram_memory) != 0) { fprintf(stderr, "xen hardware virtual machine initialisation failed\n"); exit(1); } @@ -105,28 +146,12 @@ static void pc_init1(QEMUMachineInitArgs *args, object_property_add_child(qdev_get_machine(), "icc-bridge", OBJECT(icc_bridge), NULL); - pc_cpus_init(args->cpu_model, icc_bridge); + pc_cpus_init(machine->cpu_model, icc_bridge); if (kvm_enabled() && kvmclock_enabled) { kvmclock_create(); } - /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory). - * If it doesn't, we need to split it in chunks below and above 4G. - * In any case, try to make sure that guest addresses aligned at - * 1G boundaries get mapped to host addresses aligned at 1G boundaries. - * For old machine types, use whatever split we used historically to avoid - * breaking migration. - */ - if (args->ram_size >= 0xe0000000) { - ram_addr_t lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000; - above_4g_mem_size = args->ram_size - lowmem; - below_4g_mem_size = lowmem; - } else { - above_4g_mem_size = 0; - below_4g_mem_size = args->ram_size; - } - if (pci_enabled) { pci_memory = g_new(MemoryRegion, 1); memory_region_init(pci_memory, NULL, "pci", UINT64_MAX); @@ -139,23 +164,30 @@ static void pc_init1(QEMUMachineInitArgs *args, guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size); guest_info->has_acpi_build = has_acpi_build; + guest_info->legacy_acpi_table_size = legacy_acpi_table_size; - guest_info->has_pci_info = has_pci_info; guest_info->isapc_ram_fw = !pci_enabled; + guest_info->has_reserved_memory = has_reserved_memory; - if (smbios_type1_defaults) { + if (smbios_defaults) { + MachineClass *mc = MACHINE_GET_CLASS(machine); /* These values are guest ABI, do not change */ - smbios_set_type1_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)", - args->machine->name); + smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)", + mc->name, smbios_legacy_mode, smbios_uuid_encoded); } /* allocate ram and load rom/bios */ if (!xen_enabled()) { - fw_cfg = pc_memory_init(system_memory, - args->kernel_filename, args->kernel_cmdline, - args->initrd_filename, - below_4g_mem_size, above_4g_mem_size, - rom_memory, &ram_memory, guest_info); + fw_cfg = pc_memory_init(machine, system_memory, + below_4g_mem_size, above_4g_mem_size, + rom_memory, &ram_memory, guest_info); + } else if (machine->kernel_filename != NULL) { + /* For xen HVM direct kernel boot, load linux here */ + fw_cfg = xen_load_linux(machine->kernel_filename, + machine->kernel_cmdline, + machine->initrd_filename, + below_4g_mem_size, + guest_info); } gsi_state = g_malloc0(sizeof(*gsi_state)); @@ -169,7 +201,7 @@ static void pc_init1(QEMUMachineInitArgs *args, if (pci_enabled) { pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi, - system_memory, system_io, args->ram_size, + system_memory, system_io, machine->ram_size, below_4g_mem_size, above_4g_mem_size, pci_memory, ram_memory); @@ -202,13 +234,18 @@ static void pc_init1(QEMUMachineInitArgs *args, pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL); + assert(pc_machine->vmport != ON_OFF_AUTO_MAX); + if (pc_machine->vmport == ON_OFF_AUTO_AUTO) { + pc_machine->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON; + } + /* init basic PC hardware */ - pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, xen_enabled(), - 0x4); + pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, + (pc_machine->vmport != ON_OFF_AUTO_ON), 0x4); pc_nic_init(isa_bus, pci_bus); - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); if (pci_enabled) { PCIDevice *dev; if (xen_enabled()) { @@ -234,22 +271,31 @@ static void pc_init1(QEMUMachineInitArgs *args, } } - pc_cmos_init(below_4g_mem_size, above_4g_mem_size, args->boot_order, - floppy, idebus[0], idebus[1], rtc_state); + pc_cmos_init(below_4g_mem_size, above_4g_mem_size, machine->boot_order, + machine, floppy, idebus[0], idebus[1], rtc_state); if (pci_enabled && usb_enabled(false)) { pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci"); } if (pci_enabled && acpi_enabled) { + DeviceState *piix4_pm; I2CBus *smbus; smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1); /* TODO: Populate SPD eeprom data. */ smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100, gsi[9], *smi_irq, - kvm_enabled(), fw_cfg); + kvm_enabled(), fw_cfg, &piix4_pm); smbus_eeprom_init(smbus, 8, NULL, 0); + + object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP, + TYPE_HOTPLUG_HANDLER, + (Object **)&pc_machine->acpi_dev, + object_property_allow_set_link, + OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort); + object_property_set_link(OBJECT(machine), OBJECT(piix4_pm), + PC_MACHINE_ACPI_DEVICE_PROP, &error_abort); } if (pci_enabled) { @@ -257,128 +303,176 @@ static void pc_init1(QEMUMachineInitArgs *args, } } -static void pc_init_pci(QEMUMachineInitArgs *args) +static void pc_init_pci(MachineState *machine) { - pc_init1(args, 1, 1); + pc_init1(machine, 1, 1); } #ifdef CONFIG_MARU -void maru_pc_init_pci(QEMUMachineInitArgs *args); +void maru_pc_init_pci(MachineState *machine); -void maru_pc_init_pci(QEMUMachineInitArgs *args) +void maru_pc_init_pci(MachineState *machine) { - pc_init_pci(args); + pc_init_pci(machine); } #endif -static void pc_compat_1_7(QEMUMachineInitArgs *args) +static void pc_compat_2_1(MachineState *machine) +{ + PCMachineState *pcms = PC_MACHINE(machine); + smbios_uuid_encoded = false; + x86_cpu_compat_set_features("coreduo", FEAT_1_ECX, CPUID_EXT_VMX, 0); + x86_cpu_compat_set_features("core2duo", FEAT_1_ECX, CPUID_EXT_VMX, 0); + x86_cpu_compat_kvm_no_autodisable(FEAT_8000_0001_ECX, CPUID_EXT3_SVM); + pcms->enforce_aligned_dimm = false; +} + +static void pc_compat_2_0(MachineState *machine) +{ + pc_compat_2_1(machine); + /* This value depends on the actual DSDT and SSDT compiled into + * the source QEMU; unfortunately it depends on the binary and + * not on the machine type, so we cannot make pc-i440fx-1.7 work on + * both QEMU 1.7 and QEMU 2.0. + * + * Large variations cause migration to fail for more than one + * consecutive value of the "-smp" maxcpus option. + * + * For small variations of the kind caused by different iasl versions, + * the 4k rounding usually leaves slack. However, there could be still + * one or two values that break. For QEMU 1.7 and QEMU 2.0 the + * slack is only ~10 bytes before one "-smp maxcpus" value breaks! + * + * 6652 is valid for QEMU 2.0, the right value for pc-i440fx-1.7 on + * QEMU 1.7 it is 6414. For RHEL/CentOS 7.0 it is 6418. + */ + legacy_acpi_table_size = 6652; + smbios_legacy_mode = true; + has_reserved_memory = false; + pc_set_legacy_acpi_data_size(); +} + +static void pc_compat_1_7(MachineState *machine) { - smbios_type1_defaults = false; + pc_compat_2_0(machine); + smbios_defaults = false; gigabyte_align = false; option_rom_has_mr = true; - x86_cpu_compat_disable_kvm_features(FEAT_1_ECX, CPUID_EXT_X2APIC); + legacy_acpi_table_size = 6414; + x86_cpu_compat_kvm_no_autoenable(FEAT_1_ECX, CPUID_EXT_X2APIC); } -static void pc_compat_1_6(QEMUMachineInitArgs *args) +static void pc_compat_1_6(MachineState *machine) { - pc_compat_1_7(args); - has_pci_info = false; + pc_compat_1_7(machine); rom_file_has_mr = false; has_acpi_build = false; } -static void pc_compat_1_5(QEMUMachineInitArgs *args) +static void pc_compat_1_5(MachineState *machine) { - pc_compat_1_6(args); + pc_compat_1_6(machine); } -static void pc_compat_1_4(QEMUMachineInitArgs *args) +static void pc_compat_1_4(MachineState *machine) { - pc_compat_1_5(args); + pc_compat_1_5(machine); x86_cpu_compat_set_features("n270", FEAT_1_ECX, 0, CPUID_EXT_MOVBE); x86_cpu_compat_set_features("Westmere", FEAT_1_ECX, 0, CPUID_EXT_PCLMULQDQ); } -static void pc_compat_1_3(QEMUMachineInitArgs *args) +static void pc_compat_1_3(MachineState *machine) { - pc_compat_1_4(args); + pc_compat_1_4(machine); enable_compat_apic_id_mode(); } /* PC compat function for pc-0.14 to pc-1.2 */ -static void pc_compat_1_2(QEMUMachineInitArgs *args) +static void pc_compat_1_2(MachineState *machine) +{ + pc_compat_1_3(machine); + x86_cpu_compat_kvm_no_autoenable(FEAT_KVM, KVM_FEATURE_PV_EOI); +} + +static void pc_init_pci_2_1(MachineState *machine) { - pc_compat_1_3(args); - x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI); + pc_compat_2_1(machine); + pc_init_pci(machine); } -static void pc_init_pci_1_7(QEMUMachineInitArgs *args) +static void pc_init_pci_2_0(MachineState *machine) { - pc_compat_1_7(args); - pc_init_pci(args); + pc_compat_2_0(machine); + pc_init_pci(machine); } -static void pc_init_pci_1_6(QEMUMachineInitArgs *args) +static void pc_init_pci_1_7(MachineState *machine) { - pc_compat_1_6(args); - pc_init_pci(args); + pc_compat_1_7(machine); + pc_init_pci(machine); } -static void pc_init_pci_1_5(QEMUMachineInitArgs *args) +static void pc_init_pci_1_6(MachineState *machine) { - pc_compat_1_5(args); - pc_init_pci(args); + pc_compat_1_6(machine); + pc_init_pci(machine); } -static void pc_init_pci_1_4(QEMUMachineInitArgs *args) +static void pc_init_pci_1_5(MachineState *machine) { - pc_compat_1_4(args); - pc_init_pci(args); + pc_compat_1_5(machine); + pc_init_pci(machine); } -static void pc_init_pci_1_3(QEMUMachineInitArgs *args) +static void pc_init_pci_1_4(MachineState *machine) { - pc_compat_1_3(args); - pc_init_pci(args); + pc_compat_1_4(machine); + pc_init_pci(machine); +} + +static void pc_init_pci_1_3(MachineState *machine) +{ + pc_compat_1_3(machine); + pc_init_pci(machine); } /* PC machine init function for pc-0.14 to pc-1.2 */ -static void pc_init_pci_1_2(QEMUMachineInitArgs *args) +static void pc_init_pci_1_2(MachineState *machine) { - pc_compat_1_2(args); - pc_init_pci(args); + pc_compat_1_2(machine); + pc_init_pci(machine); } -/* PC init function for pc-0.10 to pc-0.13, and reused by xenfv */ -static void pc_init_pci_no_kvmclock(QEMUMachineInitArgs *args) +/* PC init function for pc-0.10 to pc-0.13 */ +static void pc_init_pci_no_kvmclock(MachineState *machine) { - has_pci_info = false; - has_acpi_build = false; - smbios_type1_defaults = false; - x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI); - enable_compat_apic_id_mode(); - pc_init1(args, 1, 0); + pc_compat_1_2(machine); + pc_init1(machine, 1, 0); } -static void pc_init_isa(QEMUMachineInitArgs *args) +static void pc_init_isa(MachineState *machine) { - has_pci_info = false; has_acpi_build = false; - smbios_type1_defaults = false; - if (!args->cpu_model) { - args->cpu_model = "486"; + smbios_defaults = false; + gigabyte_align = false; + smbios_legacy_mode = true; + has_reserved_memory = false; + option_rom_has_mr = true; + rom_file_has_mr = false; + if (!machine->cpu_model) { + machine->cpu_model = "486"; } - x86_cpu_compat_disable_kvm_features(FEAT_KVM, KVM_FEATURE_PV_EOI); + x86_cpu_compat_kvm_no_autoenable(FEAT_KVM, KVM_FEATURE_PV_EOI); enable_compat_apic_id_mode(); - pc_init1(args, 0, 1); + pc_init1(machine, 0, 1); } #ifdef CONFIG_XEN -static void pc_xen_hvm_init(QEMUMachineInitArgs *args) +static void pc_xen_hvm_init(MachineState *machine) { PCIBus *bus; - pc_init_pci(args); + pc_init_pci(machine); bus = pci_find_primary_bus(); if (bus != NULL) { @@ -389,19 +483,47 @@ static void pc_xen_hvm_init(QEMUMachineInitArgs *args) #define PC_I440FX_MACHINE_OPTIONS \ PC_DEFAULT_MACHINE_OPTIONS, \ + .family = "pc_piix", \ .desc = "Standard PC (i440FX + PIIX, 1996)", \ .hot_add_cpu = pc_hot_add_cpu -#define PC_I440FX_2_0_MACHINE_OPTIONS \ +#define PC_I440FX_2_2_MACHINE_OPTIONS \ + PC_I440FX_MACHINE_OPTIONS, \ + .default_machine_opts = "firmware=bios-256k.bin", \ + .default_display = "std" + +static QEMUMachine pc_i440fx_machine_v2_2 = { + PC_I440FX_2_2_MACHINE_OPTIONS, + .name = "pc-i440fx-2.2", + .alias = "pc", + .init = pc_init_pci, + .is_default = 1, +}; + +#define PC_I440FX_2_1_MACHINE_OPTIONS \ PC_I440FX_MACHINE_OPTIONS, \ .default_machine_opts = "firmware=bios-256k.bin" +static QEMUMachine pc_i440fx_machine_v2_1 = { + PC_I440FX_2_1_MACHINE_OPTIONS, + .name = "pc-i440fx-2.1", + .init = pc_init_pci_2_1, + .compat_props = (GlobalProperty[]) { + HW_COMPAT_2_1, + { /* end of list */ } + }, +}; + +#define PC_I440FX_2_0_MACHINE_OPTIONS PC_I440FX_2_1_MACHINE_OPTIONS + static QEMUMachine pc_i440fx_machine_v2_0 = { PC_I440FX_2_0_MACHINE_OPTIONS, .name = "pc-i440fx-2.0", - .alias = "pc", - .init = pc_init_pci, - .is_default = 1, + .init = pc_init_pci_2_0, + .compat_props = (GlobalProperty[]) { + PC_COMPAT_2_0, + { /* end of list */ } + }, }; #define PC_I440FX_1_7_MACHINE_OPTIONS PC_I440FX_MACHINE_OPTIONS @@ -575,7 +697,7 @@ static QEMUMachine pc_machine_v1_1 = { .property = "class",\ .value = stringify(PCI_CLASS_MEMORY_RAM),\ },{\ - .driver = "apic",\ + .driver = "apic-common",\ .property = "vapic",\ .value = "off",\ },{\ @@ -810,40 +932,31 @@ static QEMUMachine xenfv_machine = { .max_cpus = HVM_MAX_VCPUS, .default_machine_opts = "accel=xen", .hot_add_cpu = pc_hot_add_cpu, - .compat_props = (GlobalProperty[]) { - /* xenfv has no fwcfg and so does not load acpi from QEMU. - * as such new acpi features don't work. - */ - { - .driver = "PIIX4_PM", - .property = "acpi-pci-hotplug-with-bridge-support", - .value = "off", - }, - { /* end of list */ } - }, }; #endif static void pc_machine_init(void) { - qemu_register_machine(&pc_i440fx_machine_v2_0); - qemu_register_machine(&pc_i440fx_machine_v1_7); - qemu_register_machine(&pc_i440fx_machine_v1_6); - qemu_register_machine(&pc_i440fx_machine_v1_5); - qemu_register_machine(&pc_i440fx_machine_v1_4); - qemu_register_machine(&pc_machine_v1_3); - qemu_register_machine(&pc_machine_v1_2); - qemu_register_machine(&pc_machine_v1_1); - qemu_register_machine(&pc_machine_v1_0); - qemu_register_machine(&pc_machine_v0_15); - qemu_register_machine(&pc_machine_v0_14); - qemu_register_machine(&pc_machine_v0_13); - qemu_register_machine(&pc_machine_v0_12); - qemu_register_machine(&pc_machine_v0_11); - qemu_register_machine(&pc_machine_v0_10); - qemu_register_machine(&isapc_machine); + qemu_register_pc_machine(&pc_i440fx_machine_v2_2); + qemu_register_pc_machine(&pc_i440fx_machine_v2_1); + qemu_register_pc_machine(&pc_i440fx_machine_v2_0); + qemu_register_pc_machine(&pc_i440fx_machine_v1_7); + qemu_register_pc_machine(&pc_i440fx_machine_v1_6); + qemu_register_pc_machine(&pc_i440fx_machine_v1_5); + qemu_register_pc_machine(&pc_i440fx_machine_v1_4); + qemu_register_pc_machine(&pc_machine_v1_3); + qemu_register_pc_machine(&pc_machine_v1_2); + qemu_register_pc_machine(&pc_machine_v1_1); + qemu_register_pc_machine(&pc_machine_v1_0); + qemu_register_pc_machine(&pc_machine_v0_15); + qemu_register_pc_machine(&pc_machine_v0_14); + qemu_register_pc_machine(&pc_machine_v0_13); + qemu_register_pc_machine(&pc_machine_v0_12); + qemu_register_pc_machine(&pc_machine_v0_11); + qemu_register_pc_machine(&pc_machine_v0_10); + qemu_register_pc_machine(&isapc_machine); #ifdef CONFIG_XEN - qemu_register_machine(&xenfv_machine); + qemu_register_pc_machine(&xenfv_machine); #endif } diff --git a/hw/i386/pc_q35.c b/hw/i386/pc_q35.c index c844dc2a9f..0262b5ef19 100644 --- a/hw/i386/pc_q35.c +++ b/hw/i386/pc_q35.c @@ -44,22 +44,26 @@ #include "hw/ide/ahci.h" #include "hw/usb.h" #include "hw/cpu/icc_bus.h" +#include "qemu/error-report.h" /* ICH9 AHCI has 6 ports */ #define MAX_SATA_PORTS 6 -static bool has_pci_info; static bool has_acpi_build = true; -static bool smbios_type1_defaults = true; +static bool smbios_defaults = true; +static bool smbios_legacy_mode; +static bool smbios_uuid_encoded = true; /* Make sure that guest addresses aligned at 1Gbyte boundaries get mapped to * host addresses aligned at 1Gbyte boundaries. This way we can use 1GByte * pages in the host. */ static bool gigabyte_align = true; +static bool has_reserved_memory = true; /* PC hardware initialisation */ -static void pc_q35_init(QEMUMachineInitArgs *args) +static void pc_q35_init(MachineState *machine) { + PCMachineState *pc_machine = PC_MACHINE(machine); ram_addr_t below_4g_mem_size, above_4g_mem_size; Q35PCIHost *q35_host; PCIHostState *phb; @@ -82,20 +86,8 @@ static void pc_q35_init(QEMUMachineInitArgs *args) PCIDevice *ahci; DeviceState *icc_bridge; PcGuestInfo *guest_info; - - if (xen_enabled() && xen_hvm_init(&ram_memory) != 0) { - fprintf(stderr, "xen hardware virtual machine initialisation failed\n"); - exit(1); - } - - icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE); - object_property_add_child(qdev_get_machine(), "icc-bridge", - OBJECT(icc_bridge), NULL); - - pc_cpus_init(args->cpu_model, icc_bridge); - pc_acpi_init("q35-acpi-dsdt.aml"); - - kvmclock_create(); + ram_addr_t lowmem; + DriveInfo *hd[MAX_SATA_PORTS]; /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory * and 256 Mbytes for PCI Express Enhanced Configuration Access Mapping @@ -106,15 +98,48 @@ static void pc_q35_init(QEMUMachineInitArgs *args) * For old machine types, use whatever split we used historically to avoid * breaking migration. */ - if (args->ram_size >= 0xb0000000) { - ram_addr_t lowmem = gigabyte_align ? 0x80000000 : 0xb0000000; - above_4g_mem_size = args->ram_size - lowmem; + if (machine->ram_size >= 0xb0000000) { + lowmem = gigabyte_align ? 0x80000000 : 0xb0000000; + } else { + lowmem = 0xb0000000; + } + + /* Handle the machine opt max-ram-below-4g. It is basically doing + * min(qemu limit, user limit). + */ + if (lowmem > pc_machine->max_ram_below_4g) { + lowmem = pc_machine->max_ram_below_4g; + if (machine->ram_size - lowmem > lowmem && + lowmem & ((1ULL << 30) - 1)) { + error_report("Warning: Large machine and max_ram_below_4g(%"PRIu64 + ") not a multiple of 1G; possible bad performance.", + pc_machine->max_ram_below_4g); + } + } + + if (machine->ram_size >= lowmem) { + above_4g_mem_size = machine->ram_size - lowmem; below_4g_mem_size = lowmem; } else { above_4g_mem_size = 0; - below_4g_mem_size = args->ram_size; + below_4g_mem_size = machine->ram_size; + } + + if (xen_enabled() && xen_hvm_init(&below_4g_mem_size, &above_4g_mem_size, + &ram_memory) != 0) { + fprintf(stderr, "xen hardware virtual machine initialisation failed\n"); + exit(1); } + icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE); + object_property_add_child(qdev_get_machine(), "icc-bridge", + OBJECT(icc_bridge), NULL); + + pc_cpus_init(machine->cpu_model, icc_bridge); + pc_acpi_init("q35-acpi-dsdt.aml"); + + kvmclock_create(); + /* pci enabled */ if (pci_enabled) { pci_memory = g_new(MemoryRegion, 1); @@ -126,21 +151,25 @@ static void pc_q35_init(QEMUMachineInitArgs *args) } guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size); - guest_info->has_pci_info = has_pci_info; guest_info->isapc_ram_fw = false; guest_info->has_acpi_build = has_acpi_build; + guest_info->has_reserved_memory = has_reserved_memory; + + /* Migration was not supported in 2.0 for Q35, so do not bother + * with this hack (see hw/i386/acpi-build.c). + */ + guest_info->legacy_acpi_table_size = 0; - if (smbios_type1_defaults) { + if (smbios_defaults) { + MachineClass *mc = MACHINE_GET_CLASS(machine); /* These values are guest ABI, do not change */ - smbios_set_type1_defaults("QEMU", "Standard PC (Q35 + ICH9, 2009)", - args->machine->name); + smbios_set_defaults("QEMU", "Standard PC (Q35 + ICH9, 2009)", + mc->name, smbios_legacy_mode, smbios_uuid_encoded); } /* allocate ram and load rom/bios */ if (!xen_enabled()) { - pc_memory_init(get_system_memory(), - args->kernel_filename, args->kernel_cmdline, - args->initrd_filename, + pc_memory_init(machine, get_system_memory(), below_4g_mem_size, above_4g_mem_size, rom_memory, &ram_memory, guest_info); } @@ -174,6 +203,15 @@ static void pc_q35_init(QEMUMachineInitArgs *args) lpc = pci_create_simple_multifunction(host_bus, PCI_DEVFN(ICH9_LPC_DEV, ICH9_LPC_FUNC), true, TYPE_ICH9_LPC_DEVICE); + + object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP, + TYPE_HOTPLUG_HANDLER, + (Object **)&pc_machine->acpi_dev, + object_property_allow_set_link, + OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort); + object_property_set_link(OBJECT(machine), OBJECT(lpc), + PC_MACHINE_ACPI_DEVICE_PROP, &error_abort); + ich9_lpc = ICH9_LPC_DEVICE(lpc); ich9_lpc->pic = gsi; ich9_lpc->ioapic = gsi_state->ioapic_irq; @@ -198,14 +236,20 @@ static void pc_q35_init(QEMUMachineInitArgs *args) gsi_state->i8259_irq[i] = i8259[i]; } if (pci_enabled) { - ioapic_init_gsi(gsi_state, NULL); + ioapic_init_gsi(gsi_state, "q35"); } qdev_init_nofail(icc_bridge); pc_register_ferr_irq(gsi[13]); + assert(pc_machine->vmport != ON_OFF_AUTO_MAX); + if (pc_machine->vmport == ON_OFF_AUTO_AUTO) { + pc_machine->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON; + } + /* init basic PC hardware */ - pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, false, 0xff0104); + pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, + (pc_machine->vmport != ON_OFF_AUTO_ON), 0xff0104); /* connect pm stuff to lpc */ ich9_lpc_pm_init(lpc); @@ -217,6 +261,9 @@ static void pc_q35_init(QEMUMachineInitArgs *args) true, "ich9-ahci"); idebus[0] = qdev_get_child_bus(&ahci->qdev, "ide.0"); idebus[1] = qdev_get_child_bus(&ahci->qdev, "ide.1"); + g_assert(MAX_SATA_PORTS == ICH_AHCI(ahci)->ahci.ports); + ide_drive_get(hd, ICH_AHCI(ahci)->ahci.ports); + ahci_ide_create_devs(ahci, hd); if (usb_enabled(false)) { /* Should we create 6 UHCI according to ich9 spec? */ @@ -229,8 +276,8 @@ static void pc_q35_init(QEMUMachineInitArgs *args) 0xb100), 8, NULL, 0); - pc_cmos_init(below_4g_mem_size, above_4g_mem_size, args->boot_order, - floppy, idebus[0], idebus[1], rtc_state); + pc_cmos_init(below_4g_mem_size, above_4g_mem_size, machine->boot_order, + machine, floppy, idebus[0], idebus[1], rtc_state); /* the rest devices to which pci devfn is automatically assigned */ pc_vga_init(isa_bus, host_bus); @@ -240,72 +287,132 @@ static void pc_q35_init(QEMUMachineInitArgs *args) } } -static void pc_compat_1_7(QEMUMachineInitArgs *args) +static void pc_compat_2_1(MachineState *machine) { - smbios_type1_defaults = false; + PCMachineState *pcms = PC_MACHINE(machine); + + pcms->enforce_aligned_dimm = false; + smbios_uuid_encoded = false; + x86_cpu_compat_set_features("coreduo", FEAT_1_ECX, CPUID_EXT_VMX, 0); + x86_cpu_compat_set_features("core2duo", FEAT_1_ECX, CPUID_EXT_VMX, 0); + x86_cpu_compat_kvm_no_autodisable(FEAT_8000_0001_ECX, CPUID_EXT3_SVM); +} + +static void pc_compat_2_0(MachineState *machine) +{ + pc_compat_2_1(machine); + smbios_legacy_mode = true; + has_reserved_memory = false; + pc_set_legacy_acpi_data_size(); +} + +static void pc_compat_1_7(MachineState *machine) +{ + pc_compat_2_0(machine); + smbios_defaults = false; gigabyte_align = false; option_rom_has_mr = true; - x86_cpu_compat_disable_kvm_features(FEAT_1_ECX, CPUID_EXT_X2APIC); + x86_cpu_compat_kvm_no_autoenable(FEAT_1_ECX, CPUID_EXT_X2APIC); } -static void pc_compat_1_6(QEMUMachineInitArgs *args) +static void pc_compat_1_6(MachineState *machine) { - pc_compat_1_7(args); - has_pci_info = false; + pc_compat_1_7(machine); rom_file_has_mr = false; has_acpi_build = false; } -static void pc_compat_1_5(QEMUMachineInitArgs *args) +static void pc_compat_1_5(MachineState *machine) { - pc_compat_1_6(args); + pc_compat_1_6(machine); } -static void pc_compat_1_4(QEMUMachineInitArgs *args) +static void pc_compat_1_4(MachineState *machine) { - pc_compat_1_5(args); + pc_compat_1_5(machine); x86_cpu_compat_set_features("n270", FEAT_1_ECX, 0, CPUID_EXT_MOVBE); x86_cpu_compat_set_features("Westmere", FEAT_1_ECX, 0, CPUID_EXT_PCLMULQDQ); } -static void pc_q35_init_1_7(QEMUMachineInitArgs *args) +static void pc_q35_init_2_1(MachineState *machine) +{ + pc_compat_2_1(machine); + pc_q35_init(machine); +} + +static void pc_q35_init_2_0(MachineState *machine) { - pc_compat_1_7(args); - pc_q35_init(args); + pc_compat_2_0(machine); + pc_q35_init(machine); } -static void pc_q35_init_1_6(QEMUMachineInitArgs *args) +static void pc_q35_init_1_7(MachineState *machine) { - pc_compat_1_6(args); - pc_q35_init(args); + pc_compat_1_7(machine); + pc_q35_init(machine); } -static void pc_q35_init_1_5(QEMUMachineInitArgs *args) +static void pc_q35_init_1_6(MachineState *machine) { - pc_compat_1_5(args); - pc_q35_init(args); + pc_compat_1_6(machine); + pc_q35_init(machine); } -static void pc_q35_init_1_4(QEMUMachineInitArgs *args) +static void pc_q35_init_1_5(MachineState *machine) { - pc_compat_1_4(args); - pc_q35_init(args); + pc_compat_1_5(machine); + pc_q35_init(machine); +} + +static void pc_q35_init_1_4(MachineState *machine) +{ + pc_compat_1_4(machine); + pc_q35_init(machine); } #define PC_Q35_MACHINE_OPTIONS \ PC_DEFAULT_MACHINE_OPTIONS, \ + .family = "pc_q35", \ .desc = "Standard PC (Q35 + ICH9, 2009)", \ - .hot_add_cpu = pc_hot_add_cpu + .hot_add_cpu = pc_hot_add_cpu, \ + .units_per_default_bus = 1 -#define PC_Q35_2_0_MACHINE_OPTIONS \ +#define PC_Q35_2_2_MACHINE_OPTIONS \ + PC_Q35_MACHINE_OPTIONS, \ + .default_machine_opts = "firmware=bios-256k.bin", \ + .default_display = "std" + +static QEMUMachine pc_q35_machine_v2_2 = { + PC_Q35_2_2_MACHINE_OPTIONS, + .name = "pc-q35-2.2", + .alias = "q35", + .init = pc_q35_init, +}; + +#define PC_Q35_2_1_MACHINE_OPTIONS \ PC_Q35_MACHINE_OPTIONS, \ .default_machine_opts = "firmware=bios-256k.bin" +static QEMUMachine pc_q35_machine_v2_1 = { + PC_Q35_2_1_MACHINE_OPTIONS, + .name = "pc-q35-2.1", + .init = pc_q35_init_2_1, + .compat_props = (GlobalProperty[]) { + HW_COMPAT_2_1, + { /* end of list */ } + }, +}; + +#define PC_Q35_2_0_MACHINE_OPTIONS PC_Q35_2_1_MACHINE_OPTIONS + static QEMUMachine pc_q35_machine_v2_0 = { PC_Q35_2_0_MACHINE_OPTIONS, .name = "pc-q35-2.0", - .alias = "q35", - .init = pc_q35_init, + .init = pc_q35_init_2_0, + .compat_props = (GlobalProperty[]) { + PC_COMPAT_2_0, + { /* end of list */ } + }, }; #define PC_Q35_1_7_MACHINE_OPTIONS PC_Q35_MACHINE_OPTIONS @@ -315,7 +422,7 @@ static QEMUMachine pc_q35_machine_v1_7 = { .name = "pc-q35-1.7", .init = pc_q35_init_1_7, .compat_props = (GlobalProperty[]) { - PC_Q35_COMPAT_1_7, + PC_COMPAT_1_7, { /* end of list */ } }, }; @@ -327,7 +434,7 @@ static QEMUMachine pc_q35_machine_v1_6 = { .name = "pc-q35-1.6", .init = pc_q35_init_1_6, .compat_props = (GlobalProperty[]) { - PC_Q35_COMPAT_1_6, + PC_COMPAT_1_6, { /* end of list */ } }, }; @@ -337,7 +444,7 @@ static QEMUMachine pc_q35_machine_v1_5 = { .name = "pc-q35-1.5", .init = pc_q35_init_1_5, .compat_props = (GlobalProperty[]) { - PC_Q35_COMPAT_1_5, + PC_COMPAT_1_5, { /* end of list */ } }, }; @@ -358,11 +465,13 @@ static QEMUMachine pc_q35_machine_v1_4 = { static void pc_q35_machine_init(void) { - qemu_register_machine(&pc_q35_machine_v2_0); - qemu_register_machine(&pc_q35_machine_v1_7); - qemu_register_machine(&pc_q35_machine_v1_6); - qemu_register_machine(&pc_q35_machine_v1_5); - qemu_register_machine(&pc_q35_machine_v1_4); + qemu_register_pc_machine(&pc_q35_machine_v2_2); + qemu_register_pc_machine(&pc_q35_machine_v2_1); + qemu_register_pc_machine(&pc_q35_machine_v2_0); + qemu_register_pc_machine(&pc_q35_machine_v1_7); + qemu_register_pc_machine(&pc_q35_machine_v1_6); + qemu_register_pc_machine(&pc_q35_machine_v1_5); + qemu_register_pc_machine(&pc_q35_machine_v1_4); } machine_init(pc_q35_machine_init); diff --git a/hw/i386/pc_sysfw.c b/hw/i386/pc_sysfw.c index 61e54ddc10..8cc2e7a0ea 100644 --- a/hw/i386/pc_sysfw.c +++ b/hw/i386/pc_sysfw.c @@ -23,7 +23,7 @@ * THE SOFTWARE. */ -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "qemu/error-report.h" #include "hw/sysbus.h" #include "hw/hw.h" @@ -59,7 +59,8 @@ static void pc_isa_bios_init(MemoryRegion *rom_memory, /* map the last 128KB of the BIOS in ISA space */ isa_bios_size = MIN(flash_size, 128 * 1024); isa_bios = g_malloc(sizeof(*isa_bios)); - memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size); + memory_region_init_ram(isa_bios, NULL, "isa-bios", isa_bios_size, + &error_abort); vmstate_register_ram_global(isa_bios); memory_region_add_subregion_overlap(rom_memory, 0x100000 - isa_bios_size, @@ -106,7 +107,7 @@ static void pc_system_flash_init(MemoryRegion *rom_memory) { int unit; DriveInfo *pflash_drv; - BlockDriverState *bdrv; + BlockBackend *blk; int64_t size; char *fatal_errmsg = NULL; hwaddr phys_addr = 0x100000000ULL; @@ -122,8 +123,8 @@ static void pc_system_flash_init(MemoryRegion *rom_memory) (unit < FLASH_MAP_UNIT_MAX && (pflash_drv = drive_get(IF_PFLASH, 0, unit)) != NULL); ++unit) { - bdrv = pflash_drv->bdrv; - size = bdrv_getlength(bdrv); + blk = blk_by_legacy_dinfo(pflash_drv); + size = blk_getlength(blk); if (size < 0) { fatal_errmsg = g_strdup_printf("failed to get backing file size"); } else if (size == 0) { @@ -159,7 +160,7 @@ static void pc_system_flash_init(MemoryRegion *rom_memory) /* pflash_cfi01_register() creates a deep copy of the name */ snprintf(name, sizeof name, "system.flash%d", unit); system_flash = pflash_cfi01_register(phys_addr, NULL /* qdev */, name, - size, bdrv, sector_size, + size, blk, sector_size, size >> sector_bits, 1 /* width */, 0x0000 /* id0 */, @@ -196,7 +197,7 @@ static void old_pc_system_rom_init(MemoryRegion *rom_memory, bool isapc_ram_fw) goto bios_error; } bios = g_malloc(sizeof(*bios)); - memory_region_init_ram(bios, NULL, "pc.bios", bios_size); + memory_region_init_ram(bios, NULL, "pc.bios", bios_size, &error_abort); vmstate_register_ram_global(bios); if (!isapc_ram_fw) { memory_region_set_readonly(bios, true); diff --git a/hw/i386/q35-acpi-dsdt.dsl b/hw/i386/q35-acpi-dsdt.dsl index f4d2a2daee..e1cee5d89a 100644 --- a/hw/i386/q35-acpi-dsdt.dsl +++ b/hw/i386/q35-acpi-dsdt.dsl @@ -402,15 +402,15 @@ DefinitionBlock ( define_gsi_link(GSIH, 0, 0x17) } -#include "hw/acpi/cpu_hotplug_defs.h" +#include "hw/acpi/pc-hotplug.h" #define CPU_STATUS_BASE ICH9_CPU_HOTPLUG_IO_BASE #include "acpi-dsdt-cpu-hotplug.dsl" +#include "acpi-dsdt-mem-hotplug.dsl" /**************************************************************** * General purpose events ****************************************************************/ - Scope(\_GPE) { Name(_HID, "ACPI0006") @@ -422,7 +422,9 @@ DefinitionBlock ( // CPU hotplug event \_SB.PRSC() } - Method(_L03) { + Method(_E03) { + // Memory hotplug event + \_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_SCAN_METHOD() } Method(_L04) { } diff --git a/hw/i386/q35-acpi-dsdt.hex.generated b/hw/i386/q35-acpi-dsdt.hex.generated index 6b788c9be0..4807bdf484 100644 --- a/hw/i386/q35-acpi-dsdt.hex.generated +++ b/hw/i386/q35-acpi-dsdt.hex.generated @@ -3,12 +3,12 @@ static unsigned char Q35AcpiDsdtAmlCode[] = { 0x53, 0x44, 0x54, -0xd2, -0x1c, +0xf6, +0x1f, 0x0, 0x0, 0x1, -0x13, +0x91, 0x42, 0x58, 0x50, @@ -31,9 +31,9 @@ static unsigned char Q35AcpiDsdtAmlCode[] = { 0x4e, 0x54, 0x4c, -0x15, -0x11, -0x13, +0x28, +0x8, +0x14, 0x20, 0x10, 0x49, @@ -7234,8 +7234,793 @@ static unsigned char Q35AcpiDsdtAmlCode[] = { 0xa, 0xb, 0x10, +0x40, +0x31, +0x2e, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x5b, +0x82, +0x43, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x8, +0x5f, +0x48, +0x49, +0x44, +0xd, +0x50, +0x4e, +0x50, +0x30, +0x41, +0x30, +0x36, +0x0, +0x8, +0x5f, +0x55, +0x49, +0x44, +0xd, +0x4d, +0x65, +0x6d, +0x6f, +0x72, +0x79, +0x20, +0x68, +0x6f, +0x74, +0x70, +0x6c, +0x75, +0x67, +0x20, +0x72, +0x65, +0x73, +0x6f, +0x75, +0x72, +0x63, +0x65, +0x73, +0x0, +0x5b, +0x80, +0x48, +0x50, +0x4d, +0x52, +0x1, +0xb, +0x0, +0xa, +0xa, +0x18, +0x8, +0x5f, +0x43, +0x52, +0x53, +0x11, +0xd, +0xa, +0xa, +0x47, +0x1, +0x0, +0xa, +0x0, +0xa, +0x0, +0x18, +0x79, +0x0, +0x14, +0x13, +0x5f, +0x53, +0x54, +0x41, +0x0, +0xa0, +0x9, +0x93, +0x4d, +0x44, +0x4e, +0x52, +0x0, +0xa4, +0x0, +0xa4, +0xa, +0xb, +0x5b, +0x81, +0x1f, +0x48, +0x50, +0x4d, +0x52, +0x3, +0x4d, +0x52, +0x42, +0x4c, +0x20, +0x4d, +0x52, +0x42, +0x48, +0x20, +0x4d, +0x52, +0x4c, +0x4c, +0x20, +0x4d, +0x52, +0x4c, +0x48, +0x20, +0x4d, +0x50, +0x58, +0x5f, +0x20, +0x5b, +0x81, +0x13, +0x48, +0x50, +0x4d, +0x52, +0x1, +0x0, +0x40, +0xa, +0x4d, +0x45, +0x53, +0x5f, +0x1, +0x4d, +0x49, +0x4e, +0x53, +0x1, +0x5b, +0x1, +0x4d, +0x4c, +0x43, +0x4b, +0x0, +0x5b, +0x81, +0x15, +0x48, +0x50, +0x4d, +0x52, +0x3, +0x4d, +0x53, +0x45, +0x4c, +0x20, +0x4d, +0x4f, +0x45, +0x56, +0x20, +0x4d, 0x4f, +0x53, +0x43, +0x20, +0x14, +0x4a, +0x4, +0x4d, +0x53, +0x43, +0x4e, +0x0, +0xa0, +0x9, +0x93, +0x4d, +0x44, +0x4e, +0x52, +0x0, +0xa4, +0x0, +0x70, +0x0, +0x60, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0xa2, +0x25, +0x95, +0x60, +0x4d, +0x44, +0x4e, +0x52, +0x70, +0x60, +0x4d, +0x53, +0x45, +0x4c, +0xa0, +0x13, +0x93, +0x4d, +0x49, +0x4e, +0x53, +0x1, +0x4d, +0x54, +0x46, +0x59, +0x60, +0x1, +0x70, +0x1, +0x4d, +0x49, +0x4e, +0x53, +0x72, +0x60, +0x1, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x1, +0x14, +0x2d, +0x4d, +0x52, +0x53, +0x54, +0x1, +0x70, +0x0, +0x60, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0xa0, +0xb, +0x93, +0x4d, +0x45, +0x53, +0x5f, +0x1, +0x70, +0xa, +0xf, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x60, +0x14, +0x41, +0x18, +0x4d, +0x43, +0x52, +0x53, +0x9, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x8, +0x4d, +0x52, +0x36, +0x34, +0x11, +0x33, +0xa, +0x30, +0x8a, +0x2b, +0x0, +0x0, +0xc, +0x3, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xfe, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0xff, +0x79, +0x0, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0xe, +0x4d, +0x49, +0x4e, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x12, +0x4d, +0x49, +0x4e, +0x48, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x26, +0x4c, +0x45, +0x4e, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x2a, +0x4c, +0x45, +0x4e, +0x48, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x16, +0x4d, +0x41, +0x58, +0x4c, +0x8a, +0x4d, +0x52, +0x36, +0x34, +0xa, +0x1a, +0x4d, +0x41, +0x58, +0x48, +0x70, +0x4d, +0x52, +0x42, +0x48, +0x4d, +0x49, +0x4e, +0x48, +0x70, +0x4d, +0x52, +0x42, +0x4c, +0x4d, +0x49, +0x4e, +0x4c, +0x70, +0x4d, +0x52, +0x4c, +0x48, +0x4c, +0x45, +0x4e, +0x48, +0x70, +0x4d, +0x52, +0x4c, +0x4c, +0x4c, +0x45, +0x4e, +0x4c, +0x72, +0x4d, +0x49, +0x4e, +0x4c, +0x4c, +0x45, +0x4e, +0x4c, +0x4d, +0x41, +0x58, +0x4c, +0x72, +0x4d, +0x49, +0x4e, +0x48, +0x4c, +0x45, +0x4e, +0x48, +0x4d, +0x41, +0x58, +0x48, +0xa0, +0x14, +0x95, +0x4d, +0x41, +0x58, +0x4c, +0x4d, +0x49, +0x4e, +0x4c, +0x72, +0x4d, +0x41, +0x58, +0x48, +0x1, +0x4d, +0x41, +0x58, +0x48, +0xa0, +0x11, +0x95, +0x4d, +0x41, +0x58, +0x4c, +0x1, +0x74, +0x4d, +0x41, +0x58, +0x48, +0x1, +0x4d, +0x41, +0x58, +0x48, +0x74, +0x4d, +0x41, +0x58, +0x4c, +0x1, +0x4d, +0x41, +0x58, +0x4c, +0xa0, +0x44, +0x7, +0x93, +0x4d, +0x41, +0x58, +0x48, +0x0, 0x8, +0x4d, +0x52, +0x33, +0x32, +0x11, +0x1f, +0xa, +0x1c, +0x87, +0x17, +0x0, +0x0, +0xc, +0x3, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0x0, +0xfe, +0xff, +0xff, +0xff, +0x0, +0x0, +0x0, +0x0, +0xff, +0xff, +0xff, +0xff, +0x79, +0x0, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0xa, +0x4d, +0x49, +0x4e, +0x5f, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0xe, +0x4d, +0x41, +0x58, +0x5f, +0x8a, +0x4d, +0x52, +0x33, +0x32, +0xa, +0x16, +0x4c, +0x45, +0x4e, +0x5f, +0x70, +0x4d, +0x49, +0x4e, +0x4c, +0x4d, +0x49, +0x4e, +0x5f, +0x70, +0x4d, +0x41, +0x58, +0x4c, +0x4d, +0x41, +0x58, +0x5f, +0x70, +0x4c, +0x45, +0x4e, +0x4c, +0x4c, +0x45, +0x4e, +0x5f, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x4d, +0x52, +0x33, +0x32, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x4d, +0x52, +0x36, +0x34, +0x14, +0x24, +0x4d, +0x50, +0x58, +0x4d, +0x1, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x70, +0x4d, +0x50, +0x58, +0x5f, +0x60, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0xa4, +0x60, +0x14, +0x28, +0x4d, +0x4f, +0x53, +0x54, +0x4, +0x5b, +0x23, +0x4d, +0x4c, +0x43, +0x4b, +0xff, +0xff, +0x70, +0x99, +0x68, +0x0, +0x4d, +0x53, +0x45, +0x4c, +0x70, +0x69, +0x4d, +0x4f, +0x45, +0x56, +0x70, +0x6a, +0x4d, +0x4f, +0x53, +0x43, +0x5b, +0x27, +0x4d, +0x4c, +0x43, +0x4b, +0x10, +0x42, +0xa, 0x5f, 0x47, 0x50, @@ -7287,12 +8072,31 @@ static unsigned char Q35AcpiDsdtAmlCode[] = { 0x53, 0x43, 0x14, -0x6, +0x19, 0x5f, -0x4c, +0x45, 0x30, 0x33, 0x0, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x53, +0x43, +0x4e, 0x14, 0x6, 0x5f, diff --git a/hw/i386/smbios.c b/hw/i386/smbios.c index e8f41ad435..024e59445b 100644 --- a/hw/i386/smbios.c +++ b/hw/i386/smbios.c @@ -18,12 +18,13 @@ #include "qemu/config-file.h" #include "qemu/error-report.h" #include "sysemu/sysemu.h" +#include "sysemu/cpus.h" +#include "hw/i386/pc.h" #include "hw/i386/smbios.h" #include "hw/loader.h" -/* - * Structures shared with the BIOS - */ + +/* legacy structures and constants for <= 2.0 machines */ struct smbios_header { uint16_t length; uint8_t type; @@ -46,18 +47,28 @@ struct smbios_table { static uint8_t *smbios_entries; static size_t smbios_entries_len; +static bool smbios_legacy = true; +static bool smbios_uuid_encoded = true; +/* end: legacy structures & constants for <= 2.0 machines */ + + +static uint8_t *smbios_tables; +static size_t smbios_tables_len; +static unsigned smbios_table_max; +static unsigned smbios_table_cnt; +static struct smbios_entry_point ep; + static int smbios_type4_count = 0; static bool smbios_immutable; +static bool smbios_have_defaults; +static uint32_t smbios_cpuid_version, smbios_cpuid_features, smbios_smp_sockets; -static struct { - bool seen; - int headertype; - Location loc; -} first_opt[2]; +static DECLARE_BITMAP(have_binfile_bitmap, SMBIOS_MAX_TYPE+1); +static DECLARE_BITMAP(have_fields_bitmap, SMBIOS_MAX_TYPE+1); static struct { const char *vendor, *version, *date; - bool have_major_minor; + bool have_major_minor, uefi; uint8_t major, minor; } type0; @@ -66,6 +77,22 @@ static struct { /* uuid is in qemu_uuid[] */ } type1; +static struct { + const char *manufacturer, *product, *version, *serial, *asset, *location; +} type2; + +static struct { + const char *manufacturer, *version, *serial, *asset, *sku; +} type3; + +static struct { + const char *sock_pfx, *manufacturer, *version, *serial, *asset, *part; +} type4; + +static struct { + const char *loc_pfx, *bank, *manufacturer, *serial, *asset, *part; +} type17; + static QemuOptsList qemu_smbios_opts = { .name = "smbios", .head = QTAILQ_HEAD_INITIALIZER(qemu_smbios_opts.head), @@ -108,6 +135,10 @@ static const QemuOptDesc qemu_smbios_type0_opts[] = { .name = "release", .type = QEMU_OPT_STRING, .help = "revision number", + },{ + .name = "uefi", + .type = QEMU_OPT_BOOL, + .help = "uefi support", }, { /* end of list */ } }; @@ -149,6 +180,134 @@ static const QemuOptDesc qemu_smbios_type1_opts[] = { { /* end of list */ } }; +static const QemuOptDesc qemu_smbios_type2_opts[] = { + { + .name = "type", + .type = QEMU_OPT_NUMBER, + .help = "SMBIOS element type", + },{ + .name = "manufacturer", + .type = QEMU_OPT_STRING, + .help = "manufacturer name", + },{ + .name = "product", + .type = QEMU_OPT_STRING, + .help = "product name", + },{ + .name = "version", + .type = QEMU_OPT_STRING, + .help = "version number", + },{ + .name = "serial", + .type = QEMU_OPT_STRING, + .help = "serial number", + },{ + .name = "asset", + .type = QEMU_OPT_STRING, + .help = "asset tag number", + },{ + .name = "location", + .type = QEMU_OPT_STRING, + .help = "location in chassis", + }, + { /* end of list */ } +}; + +static const QemuOptDesc qemu_smbios_type3_opts[] = { + { + .name = "type", + .type = QEMU_OPT_NUMBER, + .help = "SMBIOS element type", + },{ + .name = "manufacturer", + .type = QEMU_OPT_STRING, + .help = "manufacturer name", + },{ + .name = "version", + .type = QEMU_OPT_STRING, + .help = "version number", + },{ + .name = "serial", + .type = QEMU_OPT_STRING, + .help = "serial number", + },{ + .name = "asset", + .type = QEMU_OPT_STRING, + .help = "asset tag number", + },{ + .name = "sku", + .type = QEMU_OPT_STRING, + .help = "SKU number", + }, + { /* end of list */ } +}; + +static const QemuOptDesc qemu_smbios_type4_opts[] = { + { + .name = "type", + .type = QEMU_OPT_NUMBER, + .help = "SMBIOS element type", + },{ + .name = "sock_pfx", + .type = QEMU_OPT_STRING, + .help = "socket designation string prefix", + },{ + .name = "manufacturer", + .type = QEMU_OPT_STRING, + .help = "manufacturer name", + },{ + .name = "version", + .type = QEMU_OPT_STRING, + .help = "version number", + },{ + .name = "serial", + .type = QEMU_OPT_STRING, + .help = "serial number", + },{ + .name = "asset", + .type = QEMU_OPT_STRING, + .help = "asset tag number", + },{ + .name = "part", + .type = QEMU_OPT_STRING, + .help = "part number", + }, + { /* end of list */ } +}; + +static const QemuOptDesc qemu_smbios_type17_opts[] = { + { + .name = "type", + .type = QEMU_OPT_NUMBER, + .help = "SMBIOS element type", + },{ + .name = "loc_pfx", + .type = QEMU_OPT_STRING, + .help = "device locator string prefix", + },{ + .name = "bank", + .type = QEMU_OPT_STRING, + .help = "bank locator string", + },{ + .name = "manufacturer", + .type = QEMU_OPT_STRING, + .help = "manufacturer name", + },{ + .name = "serial", + .type = QEMU_OPT_STRING, + .help = "serial number", + },{ + .name = "asset", + .type = QEMU_OPT_STRING, + .help = "asset tag number", + },{ + .name = "part", + .type = QEMU_OPT_STRING, + .help = "part number", + }, + { /* end of list */ } +}; + static void smbios_register_config(void) { qemu_add_opts(&qemu_smbios_opts); @@ -158,35 +317,17 @@ machine_init(smbios_register_config); static void smbios_validate_table(void) { - if (smbios_type4_count && smbios_type4_count != smp_cpus) { - error_report("Number of SMBIOS Type 4 tables must match cpu count"); + uint32_t expect_t4_count = smbios_legacy ? smp_cpus : smbios_smp_sockets; + + if (smbios_type4_count && smbios_type4_count != expect_t4_count) { + error_report("Expected %d SMBIOS Type 4 tables, got %d instead", + expect_t4_count, smbios_type4_count); exit(1); } } -/* - * To avoid unresolvable overlaps in data, don't allow both - * tables and fields for the same smbios type. - */ -static void smbios_check_collision(int type, int entry) -{ - if (type < ARRAY_SIZE(first_opt)) { - if (first_opt[type].seen) { - if (first_opt[type].headertype != entry) { - error_report("Can't mix file= and type= for same type"); - loc_push_restore(&first_opt[type].loc); - error_report("This is the conflicting setting"); - loc_pop(&first_opt[type].loc); - exit(1); - } - } else { - first_opt[type].seen = true; - first_opt[type].headertype = entry; - loc_save(&first_opt[type].loc); - } - } -} +/* legacy setup functions for <= 2.0 machines */ static void smbios_add_field(int type, int offset, const void *data, size_t len) { struct smbios_field *field; @@ -251,27 +392,23 @@ static void smbios_build_type_1_fields(void) smbios_maybe_add_str(1, offsetof(struct smbios_type_1, family_str), type1.family); if (qemu_uuid_set) { + /* We don't encode the UUID in the "wire format" here because this + * function is for legacy mode and needs to keep the guest ABI, and + * because we don't know what's the SMBIOS version advertised by the + * BIOS. + */ smbios_add_field(1, offsetof(struct smbios_type_1, uuid), qemu_uuid, 16); } } -void smbios_set_type1_defaults(const char *manufacturer, - const char *product, const char *version) +uint8_t *smbios_get_table_legacy(size_t *length) { - if (!type1.manufacturer) { - type1.manufacturer = manufacturer; - } - if (!type1.product) { - type1.product = product; + if (!smbios_legacy) { + *length = 0; + return NULL; } - if (!type1.version) { - type1.version = version; - } -} -uint8_t *smbios_get_table(size_t *length) -{ if (!smbios_immutable) { smbios_build_type_0_fields(); smbios_build_type_1_fields(); @@ -281,6 +418,469 @@ uint8_t *smbios_get_table(size_t *length) *length = smbios_entries_len; return smbios_entries; } +/* end: legacy setup functions for <= 2.0 machines */ + + +static bool smbios_skip_table(uint8_t type, bool required_table) +{ + if (test_bit(type, have_binfile_bitmap)) { + return true; /* user provided their own binary blob(s) */ + } + if (test_bit(type, have_fields_bitmap)) { + return false; /* user provided fields via command line */ + } + if (smbios_have_defaults && required_table) { + return false; /* we're building tables, and this one's required */ + } + return true; +} + +#define SMBIOS_BUILD_TABLE_PRE(tbl_type, tbl_handle, tbl_required) \ + struct smbios_type_##tbl_type *t; \ + size_t t_off; /* table offset into smbios_tables */ \ + int str_index = 0; \ + do { \ + /* should we skip building this table ? */ \ + if (smbios_skip_table(tbl_type, tbl_required)) { \ + return; \ + } \ + \ + /* use offset of table t within smbios_tables */ \ + /* (pointer must be updated after each realloc) */ \ + t_off = smbios_tables_len; \ + smbios_tables_len += sizeof(*t); \ + smbios_tables = g_realloc(smbios_tables, smbios_tables_len); \ + t = (struct smbios_type_##tbl_type *)(smbios_tables + t_off); \ + \ + t->header.type = tbl_type; \ + t->header.length = sizeof(*t); \ + t->header.handle = cpu_to_le16(tbl_handle); \ + } while (0) + +#define SMBIOS_TABLE_SET_STR(tbl_type, field, value) \ + do { \ + int len = (value != NULL) ? strlen(value) + 1 : 0; \ + if (len > 1) { \ + smbios_tables = g_realloc(smbios_tables, \ + smbios_tables_len + len); \ + memcpy(smbios_tables + smbios_tables_len, value, len); \ + smbios_tables_len += len; \ + /* update pointer post-realloc */ \ + t = (struct smbios_type_##tbl_type *)(smbios_tables + t_off); \ + t->field = ++str_index; \ + } else { \ + t->field = 0; \ + } \ + } while (0) + +#define SMBIOS_BUILD_TABLE_POST \ + do { \ + size_t term_cnt, t_size; \ + \ + /* add '\0' terminator (add two if no strings defined) */ \ + term_cnt = (str_index == 0) ? 2 : 1; \ + smbios_tables = g_realloc(smbios_tables, \ + smbios_tables_len + term_cnt); \ + memset(smbios_tables + smbios_tables_len, 0, term_cnt); \ + smbios_tables_len += term_cnt; \ + \ + /* update smbios max. element size */ \ + t_size = smbios_tables_len - t_off; \ + if (t_size > smbios_table_max) { \ + smbios_table_max = t_size; \ + } \ + \ + /* update smbios element count */ \ + smbios_table_cnt++; \ + } while (0) + +static void smbios_build_type_0_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(0, 0x000, false); /* optional, leave up to BIOS */ + + SMBIOS_TABLE_SET_STR(0, vendor_str, type0.vendor); + SMBIOS_TABLE_SET_STR(0, bios_version_str, type0.version); + + t->bios_starting_address_segment = cpu_to_le16(0xE800); /* from SeaBIOS */ + + SMBIOS_TABLE_SET_STR(0, bios_release_date_str, type0.date); + + t->bios_rom_size = 0; /* hardcoded in SeaBIOS with FIXME comment */ + + t->bios_characteristics = cpu_to_le64(0x08); /* Not supported */ + t->bios_characteristics_extension_bytes[0] = 0; + t->bios_characteristics_extension_bytes[1] = 0x14; /* TCD/SVVP | VM */ + if (type0.uefi) { + t->bios_characteristics_extension_bytes[1] |= 0x08; /* |= UEFI */ + } + + if (type0.have_major_minor) { + t->system_bios_major_release = type0.major; + t->system_bios_minor_release = type0.minor; + } else { + t->system_bios_major_release = 0; + t->system_bios_minor_release = 0; + } + + /* hardcoded in SeaBIOS */ + t->embedded_controller_major_release = 0xFF; + t->embedded_controller_minor_release = 0xFF; + + SMBIOS_BUILD_TABLE_POST; +} + +/* Encode UUID from the big endian encoding described on RFC4122 to the wire + * format specified by SMBIOS version 2.6. + */ +static void smbios_encode_uuid(struct smbios_uuid *uuid, const uint8_t *buf) +{ + memcpy(uuid, buf, 16); + if (smbios_uuid_encoded) { + uuid->time_low = bswap32(uuid->time_low); + uuid->time_mid = bswap16(uuid->time_mid); + uuid->time_hi_and_version = bswap16(uuid->time_hi_and_version); + } +} + +static void smbios_build_type_1_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(1, 0x100, true); /* required */ + + SMBIOS_TABLE_SET_STR(1, manufacturer_str, type1.manufacturer); + SMBIOS_TABLE_SET_STR(1, product_name_str, type1.product); + SMBIOS_TABLE_SET_STR(1, version_str, type1.version); + SMBIOS_TABLE_SET_STR(1, serial_number_str, type1.serial); + if (qemu_uuid_set) { + smbios_encode_uuid(&t->uuid, qemu_uuid); + } else { + memset(&t->uuid, 0, 16); + } + t->wake_up_type = 0x06; /* power switch */ + SMBIOS_TABLE_SET_STR(1, sku_number_str, type1.sku); + SMBIOS_TABLE_SET_STR(1, family_str, type1.family); + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_2_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(2, 0x200, false); /* optional */ + + SMBIOS_TABLE_SET_STR(2, manufacturer_str, type2.manufacturer); + SMBIOS_TABLE_SET_STR(2, product_str, type2.product); + SMBIOS_TABLE_SET_STR(2, version_str, type2.version); + SMBIOS_TABLE_SET_STR(2, serial_number_str, type2.serial); + SMBIOS_TABLE_SET_STR(2, asset_tag_number_str, type2.asset); + t->feature_flags = 0x01; /* Motherboard */ + SMBIOS_TABLE_SET_STR(2, location_str, type2.location); + t->chassis_handle = cpu_to_le16(0x300); /* Type 3 (System enclosure) */ + t->board_type = 0x0A; /* Motherboard */ + t->contained_element_count = 0; + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_3_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(3, 0x300, true); /* required */ + + SMBIOS_TABLE_SET_STR(3, manufacturer_str, type3.manufacturer); + t->type = 0x01; /* Other */ + SMBIOS_TABLE_SET_STR(3, version_str, type3.version); + SMBIOS_TABLE_SET_STR(3, serial_number_str, type3.serial); + SMBIOS_TABLE_SET_STR(3, asset_tag_number_str, type3.asset); + t->boot_up_state = 0x03; /* Safe */ + t->power_supply_state = 0x03; /* Safe */ + t->thermal_state = 0x03; /* Safe */ + t->security_status = 0x02; /* Unknown */ + t->oem_defined = cpu_to_le32(0); + t->height = 0; + t->number_of_power_cords = 0; + t->contained_element_count = 0; + SMBIOS_TABLE_SET_STR(3, sku_number_str, type3.sku); + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_4_table(unsigned instance) +{ + char sock_str[128]; + + SMBIOS_BUILD_TABLE_PRE(4, 0x400 + instance, true); /* required */ + + snprintf(sock_str, sizeof(sock_str), "%s%2x", type4.sock_pfx, instance); + SMBIOS_TABLE_SET_STR(4, socket_designation_str, sock_str); + t->processor_type = 0x03; /* CPU */ + t->processor_family = 0x01; /* Other */ + SMBIOS_TABLE_SET_STR(4, processor_manufacturer_str, type4.manufacturer); + t->processor_id[0] = cpu_to_le32(smbios_cpuid_version); + t->processor_id[1] = cpu_to_le32(smbios_cpuid_features); + SMBIOS_TABLE_SET_STR(4, processor_version_str, type4.version); + t->voltage = 0; + t->external_clock = cpu_to_le16(0); /* Unknown */ + t->max_speed = cpu_to_le16(0); /* Unknown */ + t->current_speed = cpu_to_le16(0); /* Unknown */ + t->status = 0x41; /* Socket populated, CPU enabled */ + t->processor_upgrade = 0x01; /* Other */ + t->l1_cache_handle = cpu_to_le16(0xFFFF); /* N/A */ + t->l2_cache_handle = cpu_to_le16(0xFFFF); /* N/A */ + t->l3_cache_handle = cpu_to_le16(0xFFFF); /* N/A */ + SMBIOS_TABLE_SET_STR(4, serial_number_str, type4.serial); + SMBIOS_TABLE_SET_STR(4, asset_tag_number_str, type4.asset); + SMBIOS_TABLE_SET_STR(4, part_number_str, type4.part); + t->core_count = t->core_enabled = smp_cores; + t->thread_count = smp_threads; + t->processor_characteristics = cpu_to_le16(0x02); /* Unknown */ + t->processor_family2 = cpu_to_le16(0x01); /* Other */ + + SMBIOS_BUILD_TABLE_POST; + smbios_type4_count++; +} + +#define ONE_KB ((ram_addr_t)1 << 10) +#define ONE_MB ((ram_addr_t)1 << 20) +#define ONE_GB ((ram_addr_t)1 << 30) + +#define MAX_T16_STD_SZ 0x80000000 /* 2T in Kilobytes */ + +static void smbios_build_type_16_table(unsigned dimm_cnt) +{ + uint64_t size_kb; + + SMBIOS_BUILD_TABLE_PRE(16, 0x1000, true); /* required */ + + t->location = 0x01; /* Other */ + t->use = 0x03; /* System memory */ + t->error_correction = 0x06; /* Multi-bit ECC (for Microsoft, per SeaBIOS) */ + size_kb = QEMU_ALIGN_UP(ram_size, ONE_KB) / ONE_KB; + if (size_kb < MAX_T16_STD_SZ) { + t->maximum_capacity = cpu_to_le32(size_kb); + t->extended_maximum_capacity = cpu_to_le64(0); + } else { + t->maximum_capacity = cpu_to_le32(MAX_T16_STD_SZ); + t->extended_maximum_capacity = cpu_to_le64(ram_size); + } + t->memory_error_information_handle = cpu_to_le16(0xFFFE); /* Not provided */ + t->number_of_memory_devices = cpu_to_le16(dimm_cnt); + + SMBIOS_BUILD_TABLE_POST; +} + +#define MAX_T17_STD_SZ 0x7FFF /* (32G - 1M), in Megabytes */ +#define MAX_T17_EXT_SZ 0x80000000 /* 2P, in Megabytes */ + +static void smbios_build_type_17_table(unsigned instance, uint64_t size) +{ + char loc_str[128]; + uint64_t size_mb; + + SMBIOS_BUILD_TABLE_PRE(17, 0x1100 + instance, true); /* required */ + + t->physical_memory_array_handle = cpu_to_le16(0x1000); /* Type 16 above */ + t->memory_error_information_handle = cpu_to_le16(0xFFFE); /* Not provided */ + t->total_width = cpu_to_le16(0xFFFF); /* Unknown */ + t->data_width = cpu_to_le16(0xFFFF); /* Unknown */ + size_mb = QEMU_ALIGN_UP(size, ONE_MB) / ONE_MB; + if (size_mb < MAX_T17_STD_SZ) { + t->size = cpu_to_le16(size_mb); + t->extended_size = cpu_to_le32(0); + } else { + assert(size_mb < MAX_T17_EXT_SZ); + t->size = cpu_to_le16(MAX_T17_STD_SZ); + t->extended_size = cpu_to_le32(size_mb); + } + t->form_factor = 0x09; /* DIMM */ + t->device_set = 0; /* Not in a set */ + snprintf(loc_str, sizeof(loc_str), "%s %d", type17.loc_pfx, instance); + SMBIOS_TABLE_SET_STR(17, device_locator_str, loc_str); + SMBIOS_TABLE_SET_STR(17, bank_locator_str, type17.bank); + t->memory_type = 0x07; /* RAM */ + t->type_detail = cpu_to_le16(0x02); /* Other */ + t->speed = cpu_to_le16(0); /* Unknown */ + SMBIOS_TABLE_SET_STR(17, manufacturer_str, type17.manufacturer); + SMBIOS_TABLE_SET_STR(17, serial_number_str, type17.serial); + SMBIOS_TABLE_SET_STR(17, asset_tag_number_str, type17.asset); + SMBIOS_TABLE_SET_STR(17, part_number_str, type17.part); + t->attributes = 0; /* Unknown */ + t->configured_clock_speed = cpu_to_le16(0); /* Unknown */ + t->minimum_voltage = cpu_to_le16(0); /* Unknown */ + t->maximum_voltage = cpu_to_le16(0); /* Unknown */ + t->configured_voltage = cpu_to_le16(0); /* Unknown */ + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_19_table(unsigned instance, + uint64_t start, uint64_t size) +{ + uint64_t end, start_kb, end_kb; + + SMBIOS_BUILD_TABLE_PRE(19, 0x1300 + instance, true); /* required */ + + end = start + size - 1; + assert(end > start); + start_kb = start / ONE_KB; + end_kb = end / ONE_KB; + if (start_kb < UINT32_MAX && end_kb < UINT32_MAX) { + t->starting_address = cpu_to_le32(start_kb); + t->ending_address = cpu_to_le32(end_kb); + t->extended_starting_address = + t->extended_ending_address = cpu_to_le64(0); + } else { + t->starting_address = t->ending_address = cpu_to_le32(UINT32_MAX); + t->extended_starting_address = cpu_to_le64(start); + t->extended_ending_address = cpu_to_le64(end); + } + t->memory_array_handle = cpu_to_le16(0x1000); /* Type 16 above */ + t->partition_width = 1; /* One device per row */ + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_32_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(32, 0x2000, true); /* required */ + + memset(t->reserved, 0, 6); + t->boot_status = 0; /* No errors detected */ + + SMBIOS_BUILD_TABLE_POST; +} + +static void smbios_build_type_127_table(void) +{ + SMBIOS_BUILD_TABLE_PRE(127, 0x7F00, true); /* required */ + SMBIOS_BUILD_TABLE_POST; +} + +void smbios_set_cpuid(uint32_t version, uint32_t features) +{ + smbios_cpuid_version = version; + smbios_cpuid_features = features; +} + +#define SMBIOS_SET_DEFAULT(field, value) \ + if (!field) { \ + field = value; \ + } + +void smbios_set_defaults(const char *manufacturer, const char *product, + const char *version, bool legacy_mode, + bool uuid_encoded) +{ + smbios_have_defaults = true; + smbios_legacy = legacy_mode; + smbios_uuid_encoded = uuid_encoded; + + /* drop unwanted version of command-line file blob(s) */ + if (smbios_legacy) { + g_free(smbios_tables); + /* in legacy mode, also complain if fields were given for types > 1 */ + if (find_next_bit(have_fields_bitmap, + SMBIOS_MAX_TYPE+1, 2) < SMBIOS_MAX_TYPE+1) { + error_report("can't process fields for smbios " + "types > 1 on machine versions < 2.1!"); + exit(1); + } + } else { + g_free(smbios_entries); + } + + SMBIOS_SET_DEFAULT(type1.manufacturer, manufacturer); + SMBIOS_SET_DEFAULT(type1.product, product); + SMBIOS_SET_DEFAULT(type1.version, version); + SMBIOS_SET_DEFAULT(type2.manufacturer, manufacturer); + SMBIOS_SET_DEFAULT(type2.product, product); + SMBIOS_SET_DEFAULT(type2.version, version); + SMBIOS_SET_DEFAULT(type3.manufacturer, manufacturer); + SMBIOS_SET_DEFAULT(type3.version, version); + SMBIOS_SET_DEFAULT(type4.sock_pfx, "CPU"); + SMBIOS_SET_DEFAULT(type4.manufacturer, manufacturer); + SMBIOS_SET_DEFAULT(type4.version, version); + SMBIOS_SET_DEFAULT(type17.loc_pfx, "DIMM"); + SMBIOS_SET_DEFAULT(type17.manufacturer, manufacturer); +} + +static void smbios_entry_point_setup(void) +{ + memcpy(ep.anchor_string, "_SM_", 4); + memcpy(ep.intermediate_anchor_string, "_DMI_", 5); + ep.length = sizeof(struct smbios_entry_point); + ep.entry_point_revision = 0; /* formatted_area reserved, per spec v2.1+ */ + memset(ep.formatted_area, 0, 5); + + /* compliant with smbios spec v2.8 */ + ep.smbios_major_version = 2; + ep.smbios_minor_version = 8; + ep.smbios_bcd_revision = 0x28; + + /* set during table construction, but BIOS may override: */ + ep.structure_table_length = cpu_to_le16(smbios_tables_len); + ep.max_structure_size = cpu_to_le16(smbios_table_max); + ep.number_of_structures = cpu_to_le16(smbios_table_cnt); + + /* BIOS must recalculate: */ + ep.checksum = 0; + ep.intermediate_checksum = 0; + ep.structure_table_address = cpu_to_le32(0); +} + +void smbios_get_tables(uint8_t **tables, size_t *tables_len, + uint8_t **anchor, size_t *anchor_len) +{ + unsigned i, dimm_cnt, instance; + + if (smbios_legacy) { + *tables = *anchor = NULL; + *tables_len = *anchor_len = 0; + return; + } + + if (!smbios_immutable) { + smbios_build_type_0_table(); + smbios_build_type_1_table(); + smbios_build_type_2_table(); + smbios_build_type_3_table(); + + smbios_smp_sockets = DIV_ROUND_UP(smp_cpus, smp_cores * smp_threads); + assert(smbios_smp_sockets >= 1); + + for (i = 0; i < smbios_smp_sockets; i++) { + smbios_build_type_4_table(i); + } + +#define MAX_DIMM_SZ (16ll * ONE_GB) +#define GET_DIMM_SZ ((i < dimm_cnt - 1) ? MAX_DIMM_SZ : ram_size % MAX_DIMM_SZ) + + dimm_cnt = QEMU_ALIGN_UP(ram_size, MAX_DIMM_SZ) / MAX_DIMM_SZ; + + smbios_build_type_16_table(dimm_cnt); + + for (i = 0; i < dimm_cnt; i++) { + smbios_build_type_17_table(i, GET_DIMM_SZ); + } + + for (i = 0, instance = 0; i < e820_get_num_entries(); i++) { + uint64_t address, length; + if (e820_get_entry(i, E820_RAM, &address, &length)) { + smbios_build_type_19_table(instance++, address, length); + } + } + + smbios_build_type_32_table(); + smbios_build_type_127_table(); + + smbios_validate_table(); + smbios_entry_point_setup(); + smbios_immutable = true; + } + + /* return tables blob and entry point (anchor), and their sizes */ + *tables = smbios_tables; + *tables_len = smbios_tables_len; + *anchor = (uint8_t *)&ep; + *anchor_len = sizeof(struct smbios_entry_point); +} static void save_opt(const char **dest, QemuOpts *opts, const char *name) { @@ -297,11 +897,12 @@ void smbios_entry_add(QemuOpts *opts) const char *val; assert(!smbios_immutable); + val = qemu_opt_get(opts, "file"); if (val) { struct smbios_structure_header *header; - struct smbios_table *table; int size; + struct smbios_table *table; /* legacy mode only */ qemu_opts_validate(opts, qemu_smbios_file_opts, &local_err); if (local_err) { @@ -315,31 +916,60 @@ void smbios_entry_add(QemuOpts *opts) exit(1); } - if (!smbios_entries) { - smbios_entries_len = sizeof(uint16_t); - smbios_entries = g_malloc0(smbios_entries_len); - } - - smbios_entries = g_realloc(smbios_entries, smbios_entries_len + - sizeof(*table) + size); - table = (struct smbios_table *)(smbios_entries + smbios_entries_len); - table->header.type = SMBIOS_TABLE_ENTRY; - table->header.length = cpu_to_le16(sizeof(*table) + size); + /* + * NOTE: standard double '\0' terminator expected, per smbios spec. + * (except in legacy mode, where the second '\0' is implicit and + * will be inserted by the BIOS). + */ + smbios_tables = g_realloc(smbios_tables, smbios_tables_len + size); + header = (struct smbios_structure_header *)(smbios_tables + + smbios_tables_len); - if (load_image(val, table->data) != size) { + if (load_image(val, (uint8_t *)header) != size) { error_report("Failed to load SMBIOS file %s", val); exit(1); } - header = (struct smbios_structure_header *)(table->data); - smbios_check_collision(header->type, SMBIOS_TABLE_ENTRY); + if (test_bit(header->type, have_fields_bitmap)) { + error_report("can't load type %d struct, fields already specified!", + header->type); + exit(1); + } + set_bit(header->type, have_binfile_bitmap); + if (header->type == 4) { smbios_type4_count++; } + smbios_tables_len += size; + if (size > smbios_table_max) { + smbios_table_max = size; + } + smbios_table_cnt++; + + /* add a copy of the newly loaded blob to legacy smbios_entries */ + /* NOTE: This code runs before smbios_set_defaults(), so we don't + * yet know which mode (legacy vs. aggregate-table) will be + * required. We therefore add the binary blob to both legacy + * (smbios_entries) and aggregate (smbios_tables) tables, and + * delete the one we don't need from smbios_set_defaults(), + * once we know which machine version has been requested. + */ + if (!smbios_entries) { + smbios_entries_len = sizeof(uint16_t); + smbios_entries = g_malloc0(smbios_entries_len); + } + smbios_entries = g_realloc(smbios_entries, smbios_entries_len + + size + sizeof(*table)); + table = (struct smbios_table *)(smbios_entries + smbios_entries_len); + table->header.type = SMBIOS_TABLE_ENTRY; + table->header.length = cpu_to_le16(sizeof(*table) + size); + memcpy(table->data, header, size); smbios_entries_len += sizeof(*table) + size; (*(uint16_t *)smbios_entries) = cpu_to_le16(le16_to_cpu(*(uint16_t *)smbios_entries) + 1); + /* end: add a copy of the newly loaded blob to legacy smbios_entries */ + return; } @@ -347,7 +977,16 @@ void smbios_entry_add(QemuOpts *opts) if (val) { unsigned long type = strtoul(val, NULL, 0); - smbios_check_collision(type, SMBIOS_FIELD_ENTRY); + if (type > SMBIOS_MAX_TYPE) { + error_report("out of range!"); + exit(1); + } + + if (test_bit(type, have_binfile_bitmap)) { + error_report("can't add fields, binary file already loaded!"); + exit(1); + } + set_bit(type, have_fields_bitmap); switch (type) { case 0: @@ -359,6 +998,7 @@ void smbios_entry_add(QemuOpts *opts) save_opt(&type0.vendor, opts, "vendor"); save_opt(&type0.version, opts, "version"); save_opt(&type0.date, opts, "date"); + type0.uefi = qemu_opt_get_bool(opts, "uefi", false); val = qemu_opt_get(opts, "release"); if (val) { @@ -391,6 +1031,57 @@ void smbios_entry_add(QemuOpts *opts) qemu_uuid_set = true; } return; + case 2: + qemu_opts_validate(opts, qemu_smbios_type2_opts, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + exit(1); + } + save_opt(&type2.manufacturer, opts, "manufacturer"); + save_opt(&type2.product, opts, "product"); + save_opt(&type2.version, opts, "version"); + save_opt(&type2.serial, opts, "serial"); + save_opt(&type2.asset, opts, "asset"); + save_opt(&type2.location, opts, "location"); + return; + case 3: + qemu_opts_validate(opts, qemu_smbios_type3_opts, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + exit(1); + } + save_opt(&type3.manufacturer, opts, "manufacturer"); + save_opt(&type3.version, opts, "version"); + save_opt(&type3.serial, opts, "serial"); + save_opt(&type3.asset, opts, "asset"); + save_opt(&type3.sku, opts, "sku"); + return; + case 4: + qemu_opts_validate(opts, qemu_smbios_type4_opts, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + exit(1); + } + save_opt(&type4.sock_pfx, opts, "sock_pfx"); + save_opt(&type4.manufacturer, opts, "manufacturer"); + save_opt(&type4.version, opts, "version"); + save_opt(&type4.serial, opts, "serial"); + save_opt(&type4.asset, opts, "asset"); + save_opt(&type4.part, opts, "part"); + return; + case 17: + qemu_opts_validate(opts, qemu_smbios_type17_opts, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + exit(1); + } + save_opt(&type17.loc_pfx, opts, "loc_pfx"); + save_opt(&type17.bank, opts, "bank"); + save_opt(&type17.manufacturer, opts, "manufacturer"); + save_opt(&type17.serial, opts, "serial"); + save_opt(&type17.asset, opts, "asset"); + save_opt(&type17.part, opts, "part"); + return; default: error_report("Don't know how to build fields for SMBIOS type %ld", type); diff --git a/hw/i386/ssdt-mem.dsl b/hw/i386/ssdt-mem.dsl new file mode 100644 index 0000000000..22ff5ddfc3 --- /dev/null +++ b/hw/i386/ssdt-mem.dsl @@ -0,0 +1,77 @@ +/* + * Memory hotplug ACPI DSDT static objects definitions + * + * Copyright ProfitBricks GmbH 2012 + * Copyright (C) 2013-2014 Red Hat Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see <http://www.gnu.org/licenses/> + */ + +/* This file is the basis for the ssdt_mem[] variable in src/acpi.c. + * It defines the contents of the memory device object. At + * runtime, a dynamically generated SSDT will contain one copy of this + * AML snippet for every possible memory device in the system. The + * objects will be placed in the \_SB_ namespace. + * + * In addition to the aml code generated from this file, the + * src/acpi.c file creates a MTFY method with an entry for each memdevice: + * Method(MTFY, 2) { + * If (LEqual(Arg0, 0x00)) { Notify(MP00, Arg1) } + * If (LEqual(Arg0, 0x01)) { Notify(MP01, Arg1) } + * ... + * } + */ +#include "hw/acpi/pc-hotplug.h" + +ACPI_EXTRACT_ALL_CODE ssdm_mem_aml + +DefinitionBlock ("ssdt-mem.aml", "SSDT", 0x02, "BXPC", "CSSDT", 0x1) +{ + + External(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_CRS_METHOD, MethodObj) + External(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_STATUS_METHOD, MethodObj) + External(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_OST_METHOD, MethodObj) + External(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_PROXIMITY_METHOD, MethodObj) + + Scope(\_SB) { +/* v------------------ DO NOT EDIT ------------------v */ + ACPI_EXTRACT_DEVICE_START ssdt_mem_start + ACPI_EXTRACT_DEVICE_END ssdt_mem_end + ACPI_EXTRACT_DEVICE_STRING ssdt_mem_name + Device(MPAA) { + ACPI_EXTRACT_NAME_STRING ssdt_mem_id + Name(_UID, "0xAA") +/* ^------------------ DO NOT EDIT ------------------^ + * Don't change the above without also updating the C code. + */ + Name(_HID, EISAID("PNP0C80")) + + Method(_CRS, 0) { + Return(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_CRS_METHOD(_UID)) + } + + Method(_STA, 0) { + Return(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_STATUS_METHOD(_UID)) + } + + Method(_PXM, 0) { + Return(\_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_PROXIMITY_METHOD(_UID)) + } + + Method(_OST, 3) { + \_SB.PCI0.MEMORY_HOTPLUG_DEVICE.MEMORY_SLOT_OST_METHOD(_UID, Arg0, Arg1, Arg2) + } + } + } +} diff --git a/hw/i386/ssdt-mem.hex.generated b/hw/i386/ssdt-mem.hex.generated new file mode 100644 index 0000000000..b3bfbbda09 --- /dev/null +++ b/hw/i386/ssdt-mem.hex.generated @@ -0,0 +1,213 @@ +static unsigned char ssdt_mem_id[] = { +0x35 +}; +static unsigned char ssdm_mem_aml[] = { +0x53, +0x53, +0x44, +0x54, +0xc7, +0x0, +0x0, +0x0, +0x2, +0x66, +0x42, +0x58, +0x50, +0x43, +0x0, +0x0, +0x43, +0x53, +0x53, +0x44, +0x54, +0x0, +0x0, +0x0, +0x1, +0x0, +0x0, +0x0, +0x49, +0x4e, +0x54, +0x4c, +0x28, +0x8, +0x14, +0x20, +0x10, +0x42, +0xa, +0x5c, +0x5f, +0x53, +0x42, +0x5f, +0x5b, +0x82, +0x49, +0x9, +0x4d, +0x50, +0x41, +0x41, +0x8, +0x5f, +0x55, +0x49, +0x44, +0xd, +0x30, +0x78, +0x41, +0x41, +0x0, +0x8, +0x5f, +0x48, +0x49, +0x44, +0xc, +0x41, +0xd0, +0xc, +0x80, +0x14, +0x1e, +0x5f, +0x43, +0x52, +0x53, +0x0, +0xa4, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x43, +0x52, +0x53, +0x5f, +0x55, +0x49, +0x44, +0x14, +0x1e, +0x5f, +0x53, +0x54, +0x41, +0x0, +0xa4, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x52, +0x53, +0x54, +0x5f, +0x55, +0x49, +0x44, +0x14, +0x1e, +0x5f, +0x50, +0x58, +0x4d, +0x0, +0xa4, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x50, +0x58, +0x4d, +0x5f, +0x55, +0x49, +0x44, +0x14, +0x20, +0x5f, +0x4f, +0x53, +0x54, +0x3, +0x5c, +0x2f, +0x4, +0x5f, +0x53, +0x42, +0x5f, +0x50, +0x43, +0x49, +0x30, +0x4d, +0x48, +0x50, +0x44, +0x4d, +0x4f, +0x53, +0x54, +0x5f, +0x55, +0x49, +0x44, +0x68, +0x69, +0x6a +}; +static unsigned char ssdt_mem_start[] = { +0x2c +}; +static unsigned char ssdt_mem_end[] = { +0xc7 +}; +static unsigned char ssdt_mem_name[] = { +0x30 +}; diff --git a/hw/i386/ssdt-misc.dsl b/hw/i386/ssdt-misc.dsl index a4484b8176..1e3baaed3d 100644 --- a/hw/i386/ssdt-misc.dsl +++ b/hw/i386/ssdt-misc.dsl @@ -12,6 +12,7 @@ * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. */ +#include "hw/acpi/pc-hotplug.h" ACPI_EXTRACT_ALL_CODE ssdp_misc_aml @@ -35,6 +36,8 @@ DefinitionBlock ("ssdt-misc.aml", "SSDT", 0x01, "BXPC", "BXSSDTSUSP", 0x1) Name(P1E, Buffer() { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }) ACPI_EXTRACT_NAME_BUFFER8 acpi_pci64_length Name(P1L, Buffer() { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }) + ACPI_EXTRACT_NAME_DWORD_CONST ssdt_mctrl_nr_slots + Name(MEMORY_SLOTS_NUMBER, 0x12345678) } diff --git a/hw/i386/ssdt-misc.hex.generated b/hw/i386/ssdt-misc.hex.generated index 55e3bd2aa6..cbcf61dcce 100644 --- a/hw/i386/ssdt-misc.hex.generated +++ b/hw/i386/ssdt-misc.hex.generated @@ -2,10 +2,13 @@ static unsigned char acpi_pci64_length[] = { 0x6f }; static unsigned char acpi_s4_pkg[] = { -0x8f +0x99 +}; +static unsigned char ssdt_mctrl_nr_slots[] = { +0x7d }; static unsigned char acpi_s3_name[] = { -0x7c +0x86 }; static unsigned char acpi_pci32_start[] = { 0x2f @@ -18,12 +21,12 @@ static unsigned char ssdp_misc_aml[] = { 0x53, 0x44, 0x54, -0x62, +0x6c, 0x1, 0x0, 0x0, 0x1, -0x76, +0x3, 0x42, 0x58, 0x50, @@ -46,12 +49,12 @@ static unsigned char ssdp_misc_aml[] = { 0x4e, 0x54, 0x4c, -0x23, +0x28, 0x8, -0x13, +0x14, 0x20, 0x10, -0x42, +0x4c, 0x5, 0x5c, 0x0, @@ -133,6 +136,16 @@ static unsigned char ssdp_misc_aml[] = { 0x0, 0x0, 0x0, +0x8, +0x4d, +0x44, +0x4e, +0x52, +0xc, +0x78, +0x56, +0x34, +0x12, 0x10, 0x29, 0x5c, @@ -370,10 +383,10 @@ static unsigned char ssdp_misc_aml[] = { 0x58 }; static unsigned char ssdt_isa_pest[] = { -0xd0 +0xda }; static unsigned char acpi_s4_name[] = { -0x88 +0x92 }; static unsigned char acpi_pci64_start[] = { 0x4d diff --git a/hw/i386/ssdt-pcihp.hex.generated b/hw/i386/ssdt-pcihp.hex.generated index b599b4663c..72ffa84800 100644 --- a/hw/i386/ssdt-pcihp.hex.generated +++ b/hw/i386/ssdt-pcihp.hex.generated @@ -32,7 +32,7 @@ static unsigned char ssdp_pcihp_aml[] = { 0x0, 0x0, 0x1, -0x6b, +0x70, 0x42, 0x58, 0x50, @@ -55,8 +55,8 @@ static unsigned char ssdp_pcihp_aml[] = { 0x4e, 0x54, 0x4c, -0x23, -0x8, +0x15, +0x11, 0x13, 0x20, 0x10, diff --git a/hw/i386/ssdt-proc.hex.generated b/hw/i386/ssdt-proc.hex.generated index 97e28d4820..4df0734c79 100644 --- a/hw/i386/ssdt-proc.hex.generated +++ b/hw/i386/ssdt-proc.hex.generated @@ -11,7 +11,7 @@ static unsigned char ssdp_proc_aml[] = { 0x0, 0x0, 0x1, -0x78, +0x7d, 0x42, 0x58, 0x50, @@ -34,8 +34,8 @@ static unsigned char ssdp_proc_aml[] = { 0x4e, 0x54, 0x4c, -0x23, -0x8, +0x15, +0x11, 0x13, 0x20, 0x5b, diff --git a/hw/i386/ssdt-tpm.dsl b/hw/i386/ssdt-tpm.dsl new file mode 100644 index 0000000000..75d96910bf --- /dev/null +++ b/hw/i386/ssdt-tpm.dsl @@ -0,0 +1,43 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License along + * with this program; if not, see <http://www.gnu.org/licenses/>. + */ +#include "hw/acpi/tpm.h" + +ACPI_EXTRACT_ALL_CODE ssdt_tpm_aml + +DefinitionBlock ( + "ssdt-tpm.aml", // Output Filename + "SSDT", // Signature + 0x01, // SSDT Compliance Revision + "BXPC", // OEMID + "BXSSDT", // TABLE ID + 0x1 // OEM Revision + ) +{ + Scope(\_SB) { + /* TPM with emulated TPM TIS interface */ + Device (TPM) { + Name (_HID, EisaID ("PNP0C31")) + Name (_CRS, ResourceTemplate () + { + Memory32Fixed (ReadWrite, TPM_TIS_ADDR_BASE, TPM_TIS_ADDR_SIZE) + // older Linux tpm_tis drivers do not work with IRQ + //IRQNoFlags () {TPM_TIS_IRQ} + }) + Method (_STA, 0, NotSerialized) { + Return (0x0F) + } + } + } +} diff --git a/hw/i386/ssdt-tpm.hex.generated b/hw/i386/ssdt-tpm.hex.generated new file mode 100644 index 0000000000..4a916a8398 --- /dev/null +++ b/hw/i386/ssdt-tpm.hex.generated @@ -0,0 +1,95 @@ +static unsigned char ssdt_tpm_aml[] = { +0x53, +0x53, +0x44, +0x54, +0x5d, +0x0, +0x0, +0x0, +0x1, +0xf, +0x42, +0x58, +0x50, +0x43, +0x0, +0x0, +0x42, +0x58, +0x53, +0x53, +0x44, +0x54, +0x0, +0x0, +0x1, +0x0, +0x0, +0x0, +0x49, +0x4e, +0x54, +0x4c, +0x15, +0x11, +0x13, +0x20, +0x10, +0x38, +0x5c, +0x5f, +0x53, +0x42, +0x5f, +0x5b, +0x82, +0x30, +0x54, +0x50, +0x4d, +0x5f, +0x8, +0x5f, +0x48, +0x49, +0x44, +0xc, +0x41, +0xd0, +0xc, +0x31, +0x8, +0x5f, +0x43, +0x52, +0x53, +0x11, +0x11, +0xa, +0xe, +0x86, +0x9, +0x0, +0x1, +0x0, +0x0, +0xd4, +0xfe, +0x0, +0x50, +0x0, +0x0, +0x79, +0x0, +0x14, +0x9, +0x5f, +0x53, +0x54, +0x41, +0x0, +0xa4, +0xa, +0xf +}; diff --git a/hw/i386/xen/Makefile.objs b/hw/i386/xen/Makefile.objs new file mode 100644 index 0000000000..801a68d326 --- /dev/null +++ b/hw/i386/xen/Makefile.objs @@ -0,0 +1 @@ +obj-y += xen_platform.o xen_apic.o xen_pvdevice.o diff --git a/hw/xen/xen_apic.c b/hw/i386/xen/xen_apic.c index 63bb7f77c6..f5acd6a096 100644 --- a/hw/xen/xen_apic.c +++ b/hw/i386/xen/xen_apic.c @@ -40,6 +40,7 @@ static void xen_apic_realize(DeviceState *dev, Error **errp) { APICCommonState *s = APIC_COMMON(dev); + s->vapic_control = 0; memory_region_init_io(&s->io_memory, OBJECT(s), &xen_apic_io_ops, s, "xen-apic-msi", APIC_SPACE_SIZE); diff --git a/hw/xen/xen_platform.c b/hw/i386/xen/xen_platform.c index 1d9d0e9f25..28b324a6f4 100644 --- a/hw/xen/xen_platform.c +++ b/hw/i386/xen/xen_platform.c @@ -34,6 +34,7 @@ #include "hw/xen/xen_backend.h" #include "trace.h" #include "exec/address-spaces.h" +#include "sysemu/block-backend.h" #include <xenguest.h> @@ -132,8 +133,8 @@ static void platform_fixed_ioport_writew(void *opaque, uint32_t addr, uint32_t v devices, and bit 2 the non-primary-master IDE devices. */ if (val & UNPLUG_ALL_IDE_DISKS) { DPRINTF("unplug disks\n"); - bdrv_drain_all(); - bdrv_flush_all(); + blk_drain_all(); + blk_flush_all(); pci_unplug_disks(pci_dev->bus); } if (val & UNPLUG_ALL_NICS) { @@ -375,9 +376,8 @@ static const VMStateDescription vmstate_xen_platform = { .name = "platform", .version_id = 4, .minimum_version_id = 4, - .minimum_version_id_old = 4, .post_load = xen_platform_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PCIXenPlatformState), VMSTATE_UINT8(flags, PCIXenPlatformState), VMSTATE_END_OF_LIST() diff --git a/hw/xen/xen_pvdevice.c b/hw/i386/xen/xen_pvdevice.c index c2189473ba..c2189473ba 100644 --- a/hw/xen/xen_pvdevice.c +++ b/hw/i386/xen/xen_pvdevice.c diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c index bfe633f3a5..94f28e6bac 100644 --- a/hw/ide/ahci.c +++ b/hw/ide/ahci.c @@ -28,6 +28,7 @@ #include <hw/sysbus.h> #include "monitor/monitor.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include "internal.h" #include <hw/ide/pci.h> @@ -48,6 +49,9 @@ static int handle_cmd(AHCIState *s,int port,int slot); static void ahci_reset_port(AHCIState *s, int port); static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis); static void ahci_init_d2h(AHCIDevice *ad); +static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write); +static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes); + static uint32_t ahci_port_read(AHCIState *s, int port, int offset) { @@ -78,14 +82,13 @@ static uint32_t ahci_port_read(AHCIState *s, int port, int offset) val = pr->cmd; break; case PORT_TFDATA: - val = ((uint16_t)s->dev[port].port.ifs[0].error << 8) | - s->dev[port].port.ifs[0].status; + val = pr->tfdata; break; case PORT_SIG: val = pr->sig; break; case PORT_SCR_STAT: - if (s->dev[port].port.ifs[0].bs) { + if (s->dev[port].port.ifs[0].blk) { val = SATA_SCR_SSTATUS_DET_DEV_PRESENT_PHY_UP | SATA_SCR_SSTATUS_SPD_GEN1 | SATA_SCR_SSTATUS_IPM_ACTIVE; } else { @@ -175,17 +178,18 @@ static void ahci_trigger_irq(AHCIState *s, AHCIDevice *d, ahci_check_irq(s); } -static void map_page(uint8_t **ptr, uint64_t addr, uint32_t wanted) +static void map_page(AddressSpace *as, uint8_t **ptr, uint64_t addr, + uint32_t wanted) { hwaddr len = wanted; if (*ptr) { - cpu_physical_memory_unmap(*ptr, len, 1, len); + dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len); } - *ptr = cpu_physical_memory_map(addr, &len, 1); + *ptr = dma_memory_map(as, addr, &len, DMA_DIRECTION_FROM_DEVICE); if (len < wanted) { - cpu_physical_memory_unmap(*ptr, len, 1, len); + dma_memory_unmap(as, *ptr, len, DMA_DIRECTION_FROM_DEVICE, len); *ptr = NULL; } } @@ -198,24 +202,24 @@ static void ahci_port_write(AHCIState *s, int port, int offset, uint32_t val) switch (offset) { case PORT_LST_ADDR: pr->lst_addr = val; - map_page(&s->dev[port].lst, + map_page(s->as, &s->dev[port].lst, ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024); s->dev[port].cur_cmd = NULL; break; case PORT_LST_ADDR_HI: pr->lst_addr_hi = val; - map_page(&s->dev[port].lst, + map_page(s->as, &s->dev[port].lst, ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024); s->dev[port].cur_cmd = NULL; break; case PORT_FIS_ADDR: pr->fis_addr = val; - map_page(&s->dev[port].res_fis, + map_page(s->as, &s->dev[port].res_fis, ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256); break; case PORT_FIS_ADDR_HI: pr->fis_addr_hi = val; - map_page(&s->dev[port].res_fis, + map_page(s->as, &s->dev[port].res_fis, ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256); break; case PORT_IRQ_STAT: @@ -250,14 +254,13 @@ static void ahci_port_write(AHCIState *s, int port, int offset, uint32_t val) check_cmd(s, port); break; case PORT_TFDATA: - s->dev[port].port.ifs[0].error = (val >> 8) & 0xff; - s->dev[port].port.ifs[0].status = val & 0xff; + /* Read Only. */ break; case PORT_SIG: - pr->sig = val; + /* Read Only */ break; case PORT_SCR_STAT: - pr->scr_stat = val; + /* Read Only */ break; case PORT_SCR_CTL: if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) && @@ -438,9 +441,9 @@ static void check_cmd(AHCIState *s, int port) if ((pr->cmd & PORT_CMD_START) && pr->cmd_issue) { for (slot = 0; (slot < 32) && pr->cmd_issue; slot++) { - if ((pr->cmd_issue & (1 << slot)) && + if ((pr->cmd_issue & (1U << slot)) && !handle_cmd(s, port, slot)) { - pr->cmd_issue &= ~(1 << slot); + pr->cmd_issue &= ~(1U << slot); } } } @@ -496,11 +499,13 @@ static void ahci_reset_port(AHCIState *s, int port) pr->scr_stat = 0; pr->scr_err = 0; pr->scr_act = 0; + pr->tfdata = 0x7F; + pr->sig = 0xFFFFFFFF; d->busy_slot = -1; d->init_d2h_sent = false; ide_state = &s->dev[port].port.ifs[0]; - if (!ide_state->bs) { + if (!ide_state->blk) { return; } @@ -512,11 +517,11 @@ static void ahci_reset_port(AHCIState *s, int port) } if (ncq_tfs->aiocb) { - bdrv_aio_cancel(ncq_tfs->aiocb); + blk_aio_cancel(ncq_tfs->aiocb); ncq_tfs->aiocb = NULL; } - /* Maybe we just finished the request thanks to bdrv_aio_cancel() */ + /* Maybe we just finished the request thanks to blk_aio_cancel() */ if (!ncq_tfs->used) { continue; } @@ -526,17 +531,17 @@ static void ahci_reset_port(AHCIState *s, int port) } s->dev[port].port_state = STATE_RUN; - if (!ide_state->bs) { - s->dev[port].port_regs.sig = 0; + if (!ide_state->blk) { + pr->sig = 0; ide_state->status = SEEK_STAT | WRERR_STAT; } else if (ide_state->drive_kind == IDE_CD) { - s->dev[port].port_regs.sig = SATA_SIGNATURE_CDROM; + pr->sig = SATA_SIGNATURE_CDROM; ide_state->lcyl = 0x14; ide_state->hcyl = 0xeb; DPRINTF(port, "set lcyl = %d\n", ide_state->lcyl); ide_state->status = SEEK_STAT | WRERR_STAT | READY_STAT; } else { - s->dev[port].port_regs.sig = SATA_SIGNATURE_DISK; + pr->sig = SATA_SIGNATURE_DISK; ide_state->status = SEEK_STAT | WRERR_STAT; } @@ -562,28 +567,104 @@ static void debug_print_fis(uint8_t *fis, int cmd_len) static void ahci_write_fis_sdb(AHCIState *s, int port, uint32_t finished) { - AHCIPortRegs *pr = &s->dev[port].port_regs; + AHCIDevice *ad = &s->dev[port]; + AHCIPortRegs *pr = &ad->port_regs; IDEState *ide_state; - uint8_t *sdb_fis; + SDBFIS *sdb_fis; if (!s->dev[port].res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) { return; } - sdb_fis = &s->dev[port].res_fis[RES_FIS_SDBFIS]; - ide_state = &s->dev[port].port.ifs[0]; - - /* clear memory */ - *(uint32_t*)sdb_fis = 0; + sdb_fis = (SDBFIS *)&ad->res_fis[RES_FIS_SDBFIS]; + ide_state = &ad->port.ifs[0]; - /* write values */ - sdb_fis[0] = ide_state->error; - sdb_fis[2] = ide_state->status & 0x77; + sdb_fis->type = 0xA1; + /* Interrupt pending & Notification bit */ + sdb_fis->flags = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0); + sdb_fis->status = ide_state->status & 0x77; + sdb_fis->error = ide_state->error; + /* update SAct field in SDB_FIS */ s->dev[port].finished |= finished; - *(uint32_t*)(sdb_fis + 4) = cpu_to_le32(s->dev[port].finished); + sdb_fis->payload = cpu_to_le32(ad->finished); + + /* Update shadow registers (except BSY 0x80 and DRQ 0x08) */ + pr->tfdata = (ad->port.ifs[0].error << 8) | + (ad->port.ifs[0].status & 0x77) | + (pr->tfdata & 0x88); - ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_STAT_SDBS); + ahci_trigger_irq(s, ad, PORT_IRQ_SDB_FIS); +} + +static void ahci_write_fis_pio(AHCIDevice *ad, uint16_t len) +{ + AHCIPortRegs *pr = &ad->port_regs; + uint8_t *pio_fis, *cmd_fis; + uint64_t tbl_addr; + dma_addr_t cmd_len = 0x80; + IDEState *s = &ad->port.ifs[0]; + + if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) { + return; + } + + /* map cmd_fis */ + tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr); + cmd_fis = dma_memory_map(ad->hba->as, tbl_addr, &cmd_len, + DMA_DIRECTION_TO_DEVICE); + + if (cmd_fis == NULL) { + DPRINTF(ad->port_no, "dma_memory_map failed in ahci_write_fis_pio"); + ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR); + return; + } + + if (cmd_len != 0x80) { + DPRINTF(ad->port_no, + "dma_memory_map mapped too few bytes in ahci_write_fis_pio"); + dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len, + DMA_DIRECTION_TO_DEVICE, cmd_len); + ahci_trigger_irq(ad->hba, ad, PORT_IRQ_HBUS_ERR); + return; + } + + pio_fis = &ad->res_fis[RES_FIS_PSFIS]; + + pio_fis[0] = 0x5f; + pio_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0); + pio_fis[2] = s->status; + pio_fis[3] = s->error; + + pio_fis[4] = s->sector; + pio_fis[5] = s->lcyl; + pio_fis[6] = s->hcyl; + pio_fis[7] = s->select; + pio_fis[8] = s->hob_sector; + pio_fis[9] = s->hob_lcyl; + pio_fis[10] = s->hob_hcyl; + pio_fis[11] = 0; + pio_fis[12] = cmd_fis[12]; + pio_fis[13] = cmd_fis[13]; + pio_fis[14] = 0; + pio_fis[15] = s->status; + pio_fis[16] = len & 255; + pio_fis[17] = len >> 8; + pio_fis[18] = 0; + pio_fis[19] = 0; + + /* Update shadow registers: */ + pr->tfdata = (ad->port.ifs[0].error << 8) | + ad->port.ifs[0].status; + + if (pio_fis[2] & ERR_STAT) { + ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR); + } + + ahci_trigger_irq(ad->hba, ad, PORT_IRQ_PIOS_FIS); + + dma_memory_unmap(ad->hba->as, cmd_fis, cmd_len, + DMA_DIRECTION_TO_DEVICE, cmd_len); } static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis) @@ -593,6 +674,7 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis) int i; dma_addr_t cmd_len = 0x80; int cmd_mapped = 0; + IDEState *s = &ad->port.ifs[0]; if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) { return; @@ -610,25 +692,29 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis) d2h_fis[0] = 0x34; d2h_fis[1] = (ad->hba->control_regs.irqstatus ? (1 << 6) : 0); - d2h_fis[2] = ad->port.ifs[0].status; - d2h_fis[3] = ad->port.ifs[0].error; - - d2h_fis[4] = cmd_fis[4]; - d2h_fis[5] = cmd_fis[5]; - d2h_fis[6] = cmd_fis[6]; - d2h_fis[7] = cmd_fis[7]; - d2h_fis[8] = cmd_fis[8]; - d2h_fis[9] = cmd_fis[9]; - d2h_fis[10] = cmd_fis[10]; - d2h_fis[11] = cmd_fis[11]; + d2h_fis[2] = s->status; + d2h_fis[3] = s->error; + + d2h_fis[4] = s->sector; + d2h_fis[5] = s->lcyl; + d2h_fis[6] = s->hcyl; + d2h_fis[7] = s->select; + d2h_fis[8] = s->hob_sector; + d2h_fis[9] = s->hob_lcyl; + d2h_fis[10] = s->hob_hcyl; + d2h_fis[11] = 0; d2h_fis[12] = cmd_fis[12]; d2h_fis[13] = cmd_fis[13]; for (i = 14; i < 20; i++) { d2h_fis[i] = 0; } + /* Update shadow registers: */ + pr->tfdata = (ad->port.ifs[0].error << 8) | + ad->port.ifs[0].status; + if (d2h_fis[2] & ERR_STAT) { - ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_TFES); + ahci_trigger_irq(ad->hba, ad, PORT_IRQ_TF_ERR); } ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS); @@ -639,7 +725,13 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis) } } -static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) +static int prdt_tbl_entry_size(const AHCI_SG *tbl) +{ + return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1; +} + +static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, + int32_t offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); @@ -650,13 +742,21 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) uint8_t *prdt; int i; int r = 0; - int sum = 0; + uint64_t sum = 0; int off_idx = -1; - int off_pos = -1; + int64_t off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); + /* + * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support + * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a + * 512 byte sector size. We limit the PRDT in this implementation to + * a reasonably large 2GiB, which can accommodate the maximum transfer + * request for sector sizes up to 32K. + */ + if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; @@ -681,7 +781,7 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ - tbl_entry_size = (le32_to_cpu(tbl[i].flags_size) + 1); + tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; @@ -691,7 +791,7 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " - "off_idx: %d, off_pos: %d\n", + "off_idx: %d, off_pos: %"PRId64"\n", __func__, off_idx, off_pos); r = -1; goto out; @@ -700,12 +800,19 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) qemu_sglist_init(sglist, qbus->parent, (sglist_alloc_hint - off_idx), ad->hba->as); qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr + off_pos), - le32_to_cpu(tbl[off_idx].flags_size) + 1 - off_pos); + prdt_tbl_entry_size(&tbl[off_idx]) - off_pos); for (i = off_idx + 1; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), - le32_to_cpu(tbl[i].flags_size) + 1); + prdt_tbl_entry_size(&tbl[i])); + if (sglist->size > INT32_MAX) { + error_report("AHCI Physical Region Descriptor Table describes " + "more than 2 GiB.\n"); + qemu_sglist_destroy(sglist); + r = -1; + goto out; + } } } @@ -720,6 +827,9 @@ static void ncq_cb(void *opaque, int ret) NCQTransferState *ncq_tfs = (NCQTransferState *)opaque; IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; + if (ret == -ECANCELED) { + return; + } /* Clear bit for this tag in SActive */ ncq_tfs->drive->port_regs.scr_act &= ~(1 << ncq_tfs->tag); @@ -738,11 +848,27 @@ static void ncq_cb(void *opaque, int ret) DPRINTF(ncq_tfs->drive->port_no, "NCQ transfer tag %d finished\n", ncq_tfs->tag); - bdrv_acct_done(ncq_tfs->drive->port.ifs[0].bs, &ncq_tfs->acct); + block_acct_done(blk_get_stats(ncq_tfs->drive->port.ifs[0].blk), + &ncq_tfs->acct); qemu_sglist_destroy(&ncq_tfs->sglist); ncq_tfs->used = 0; } +static int is_ncq(uint8_t ata_cmd) +{ + /* Based on SATA 3.2 section 13.6.3.2 */ + switch (ata_cmd) { + case READ_FPDMA_QUEUED: + case WRITE_FPDMA_QUEUED: + case NCQ_NON_DATA: + case RECEIVE_FPDMA_QUEUED: + case SEND_FPDMA_QUEUED: + return 1; + default: + return 0; + } +} + static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis, int slot) { @@ -788,11 +914,11 @@ static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis, DPRINTF(port, "tag %d aio read %"PRId64"\n", ncq_tfs->tag, ncq_tfs->lba); - dma_acct_start(ncq_tfs->drive->port.ifs[0].bs, &ncq_tfs->acct, - &ncq_tfs->sglist, BDRV_ACCT_READ); - ncq_tfs->aiocb = dma_bdrv_read(ncq_tfs->drive->port.ifs[0].bs, - &ncq_tfs->sglist, ncq_tfs->lba, - ncq_cb, ncq_tfs); + dma_acct_start(ncq_tfs->drive->port.ifs[0].blk, &ncq_tfs->acct, + &ncq_tfs->sglist, BLOCK_ACCT_READ); + ncq_tfs->aiocb = dma_blk_read(ncq_tfs->drive->port.ifs[0].blk, + &ncq_tfs->sglist, ncq_tfs->lba, + ncq_cb, ncq_tfs); break; case WRITE_FPDMA_QUEUED: DPRINTF(port, "NCQ writing %d sectors to LBA %"PRId64", tag %d\n", @@ -801,23 +927,113 @@ static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis, DPRINTF(port, "tag %d aio write %"PRId64"\n", ncq_tfs->tag, ncq_tfs->lba); - dma_acct_start(ncq_tfs->drive->port.ifs[0].bs, &ncq_tfs->acct, - &ncq_tfs->sglist, BDRV_ACCT_WRITE); - ncq_tfs->aiocb = dma_bdrv_write(ncq_tfs->drive->port.ifs[0].bs, - &ncq_tfs->sglist, ncq_tfs->lba, - ncq_cb, ncq_tfs); + dma_acct_start(ncq_tfs->drive->port.ifs[0].blk, &ncq_tfs->acct, + &ncq_tfs->sglist, BLOCK_ACCT_WRITE); + ncq_tfs->aiocb = dma_blk_write(ncq_tfs->drive->port.ifs[0].blk, + &ncq_tfs->sglist, ncq_tfs->lba, + ncq_cb, ncq_tfs); break; default: - DPRINTF(port, "error: tried to process non-NCQ command as NCQ\n"); + if (is_ncq(cmd_fis[2])) { + DPRINTF(port, + "error: unsupported NCQ command (0x%02x) received\n", + cmd_fis[2]); + } else { + DPRINTF(port, + "error: tried to process non-NCQ command as NCQ\n"); + } qemu_sglist_destroy(&ncq_tfs->sglist); + } +} + +static void handle_reg_h2d_fis(AHCIState *s, int port, + int slot, uint8_t *cmd_fis) +{ + IDEState *ide_state = &s->dev[port].port.ifs[0]; + AHCICmdHdr *cmd = s->dev[port].cur_cmd; + uint32_t opts = le32_to_cpu(cmd->opts); + + if (cmd_fis[1] & 0x0F) { + DPRINTF(port, "Port Multiplier not supported." + " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n", + cmd_fis[0], cmd_fis[1], cmd_fis[2]); + return; + } + + if (cmd_fis[1] & 0x70) { + DPRINTF(port, "Reserved flags set in H2D Register FIS." + " cmd_fis[0]=%02x cmd_fis[1]=%02x cmd_fis[2]=%02x\n", + cmd_fis[0], cmd_fis[1], cmd_fis[2]); + return; + } + + if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) { + switch (s->dev[port].port_state) { + case STATE_RUN: + if (cmd_fis[15] & ATA_SRST) { + s->dev[port].port_state = STATE_RESET; + } break; + case STATE_RESET: + if (!(cmd_fis[15] & ATA_SRST)) { + ahci_reset_port(s, port); + } + break; + } + return; + } + + /* Check for NCQ command */ + if (is_ncq(cmd_fis[2])) { + process_ncq_command(s, port, cmd_fis, slot); + return; } + + /* Decompose the FIS: + * AHCI does not interpret FIS packets, it only forwards them. + * SATA 1.0 describes how to decode LBA28 and CHS FIS packets. + * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets. + * + * ATA4 describes sector number for LBA28/CHS commands. + * ATA6 describes sector number for LBA48 commands. + * ATA8 deprecates CHS fully, describing only LBA28/48. + * + * We dutifully convert the FIS into IDE registers, and allow the + * core layer to interpret them as needed. */ + ide_state->feature = cmd_fis[3]; + ide_state->sector = cmd_fis[4]; /* LBA 7:0 */ + ide_state->lcyl = cmd_fis[5]; /* LBA 15:8 */ + ide_state->hcyl = cmd_fis[6]; /* LBA 23:16 */ + ide_state->select = cmd_fis[7]; /* LBA 27:24 (LBA28) */ + ide_state->hob_sector = cmd_fis[8]; /* LBA 31:24 */ + ide_state->hob_lcyl = cmd_fis[9]; /* LBA 39:32 */ + ide_state->hob_hcyl = cmd_fis[10]; /* LBA 47:40 */ + ide_state->hob_feature = cmd_fis[11]; + ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]); + /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */ + /* 15: Only valid when UPDATE_COMMAND not set. */ + + /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command + * table to ide_state->io_buffer */ + if (opts & AHCI_CMD_ATAPI) { + memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10); + debug_print_fis(ide_state->io_buffer, 0x10); + s->dev[port].done_atapi_packet = false; + /* XXX send PIO setup FIS */ + } + + ide_state->error = 0; + + /* Reset transferred byte counter */ + cmd->status = 0; + + /* We're ready to process the command in FIS byte 2. */ + ide_exec_cmd(&s->dev[port].port, cmd_fis[2]); } static int handle_cmd(AHCIState *s, int port, int slot) { IDEState *ide_state; - uint32_t opts; uint64_t tbl_addr; AHCICmdHdr *cmd; uint8_t *cmd_fis; @@ -829,147 +1045,48 @@ static int handle_cmd(AHCIState *s, int port, int slot) return -1; } - cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot]; - if (!s->dev[port].lst) { DPRINTF(port, "error: lst not given but cmd handled"); return -1; } - + cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot]; /* remember current slot handle for later */ s->dev[port].cur_cmd = cmd; - opts = le32_to_cpu(cmd->opts); - tbl_addr = le64_to_cpu(cmd->tbl_addr); + /* The device we are working for */ + ide_state = &s->dev[port].port.ifs[0]; + if (!ide_state->blk) { + DPRINTF(port, "error: guest accessed unused port"); + return -1; + } + tbl_addr = le64_to_cpu(cmd->tbl_addr); cmd_len = 0x80; cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len, DMA_DIRECTION_FROM_DEVICE); - if (!cmd_fis) { DPRINTF(port, "error: guest passed us an invalid cmd fis\n"); return -1; - } - - /* The device we are working for */ - ide_state = &s->dev[port].port.ifs[0]; - - if (!ide_state->bs) { - DPRINTF(port, "error: guest accessed unused port"); + } else if (cmd_len != 0x80) { + ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR); + DPRINTF(port, "error: dma_memory_map failed: " + "(len(%02"PRIx64") != 0x80)\n", + cmd_len); goto out; } - - debug_print_fis(cmd_fis, 0x90); - //debug_print_fis(cmd_fis, (opts & AHCI_CMD_HDR_CMD_FIS_LEN) * 4); + debug_print_fis(cmd_fis, 0x80); switch (cmd_fis[0]) { case SATA_FIS_TYPE_REGISTER_H2D: + handle_reg_h2d_fis(s, port, slot, cmd_fis); break; default: DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x " "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1], cmd_fis[2]); - goto out; - break; - } - - switch (cmd_fis[1]) { - case SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER: - break; - case 0: - break; - default: - DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x " - "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1], - cmd_fis[2]); - goto out; break; } - switch (s->dev[port].port_state) { - case STATE_RUN: - if (cmd_fis[15] & ATA_SRST) { - s->dev[port].port_state = STATE_RESET; - } - break; - case STATE_RESET: - if (!(cmd_fis[15] & ATA_SRST)) { - ahci_reset_port(s, port); - } - break; - } - - if (cmd_fis[1] == SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER) { - - /* Check for NCQ command */ - if ((cmd_fis[2] == READ_FPDMA_QUEUED) || - (cmd_fis[2] == WRITE_FPDMA_QUEUED)) { - process_ncq_command(s, port, cmd_fis, slot); - goto out; - } - - /* Decompose the FIS */ - ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]); - ide_state->feature = cmd_fis[3]; - if (!ide_state->nsector) { - ide_state->nsector = 256; - } - - if (ide_state->drive_kind != IDE_CD) { - /* - * We set the sector depending on the sector defined in the FIS. - * Unfortunately, the spec isn't exactly obvious on this one. - * - * Apparently LBA48 commands set fis bytes 10,9,8,6,5,4 to the - * 48 bit sector number. ATA_CMD_READ_DMA_EXT is an example for - * such a command. - * - * Non-LBA48 commands however use 7[lower 4 bits],6,5,4 to define a - * 28-bit sector number. ATA_CMD_READ_DMA is an example for such - * a command. - * - * Since the spec doesn't explicitly state what each field should - * do, I simply assume non-used fields as reserved and OR everything - * together, independent of the command. - */ - ide_set_sector(ide_state, ((uint64_t)cmd_fis[10] << 40) - | ((uint64_t)cmd_fis[9] << 32) - /* This is used for LBA48 commands */ - | ((uint64_t)cmd_fis[8] << 24) - /* This is used for non-LBA48 commands */ - | ((uint64_t)(cmd_fis[7] & 0xf) << 24) - | ((uint64_t)cmd_fis[6] << 16) - | ((uint64_t)cmd_fis[5] << 8) - | cmd_fis[4]); - } - - /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command - * table to ide_state->io_buffer - */ - if (opts & AHCI_CMD_ATAPI) { - memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10); - ide_state->lcyl = 0x14; - ide_state->hcyl = 0xeb; - debug_print_fis(ide_state->io_buffer, 0x10); - ide_state->feature = IDE_FEATURE_DMA; - s->dev[port].done_atapi_packet = false; - /* XXX send PIO setup FIS */ - } - - ide_state->error = 0; - - /* Reset transferred byte counter */ - cmd->status = 0; - - /* We're ready to process the command in FIS byte 2. */ - ide_exec_cmd(&s->dev[port].port, cmd_fis[2]); - - if ((s->dev[port].port.ifs[0].status & (READY_STAT|DRQ_STAT|BUSY_STAT)) == - READY_STAT) { - ahci_write_fis_d2h(&s->dev[port], cmd_fis); - } - } - out: dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE, cmd_len); @@ -985,7 +1102,7 @@ out: } /* DMA dev <-> ram */ -static int ahci_start_transfer(IDEDMA *dma) +static void ahci_start_transfer(IDEDMA *dma) { AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); IDEState *s = &ad->port.ifs[0]; @@ -999,10 +1116,11 @@ static int ahci_start_transfer(IDEDMA *dma) if (is_atapi && !ad->done_atapi_packet) { /* already prepopulated iobuffer */ ad->done_atapi_packet = true; + size = 0; goto out; } - if (!ahci_populate_sglist(ad, &s->sg, 0)) { + if (ahci_dma_prepare_buf(dma, is_write)) { has_sglist = 1; } @@ -1018,29 +1136,23 @@ static int ahci_start_transfer(IDEDMA *dma) } } - /* update number of transferred bytes */ - ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + size); - out: /* declare that we processed everything */ s->data_ptr = s->data_end; - if (has_sglist) { - qemu_sglist_destroy(&s->sg); - } + /* Update number of transferred bytes, destroy sglist */ + ahci_commit_buf(dma, size); s->end_transfer_func(s); if (!(s->status & DRQ_STAT)) { - /* done with DMA */ - ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_DSS); + /* done with PIO send/receive */ + ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status)); } - - return 0; } static void ahci_start_dma(IDEDMA *dma, IDEState *s, - BlockDriverCompletionFunc *dma_cb) + BlockCompletionFunc *dma_cb) { #ifdef DEBUG_AHCI AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); @@ -1050,16 +1162,42 @@ static void ahci_start_dma(IDEDMA *dma, IDEState *s, dma_cb(s, 0); } -static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write) +/** + * Called in DMA R/W chains to read the PRDT, utilizing ahci_populate_sglist. + * Not currently invoked by PIO R/W chains, + * which invoke ahci_populate_sglist via ahci_start_transfer. + */ +static int32_t ahci_dma_prepare_buf(IDEDMA *dma, int is_write) { AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); IDEState *s = &ad->port.ifs[0]; - ahci_populate_sglist(ad, &s->sg, 0); + if (ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset) == -1) { + DPRINTF(ad->port_no, "ahci_dma_prepare_buf failed.\n"); + return -1; + } s->io_buffer_size = s->sg.size; DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size); - return s->io_buffer_size != 0; + return s->io_buffer_size; +} + +/** + * Destroys the scatter-gather list, + * and updates the command header with a bytes-read value. + * called explicitly via ahci_dma_rw_buf (ATAPI DMA), + * and ahci_start_transfer (PIO R/W), + * and called via callback from ide_dma_cb for DMA R/W paths. + */ +static void ahci_commit_buf(IDEDMA *dma, uint32_t tx_bytes) +{ + AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); + IDEState *s = &ad->port.ifs[0]; + + tx_bytes += le32_to_cpu(ad->cur_cmd->status); + ad->cur_cmd->status = cpu_to_le32(tx_bytes); + + qemu_sglist_destroy(&s->sg); } static int ahci_dma_rw_buf(IDEDMA *dma, int is_write) @@ -1079,11 +1217,9 @@ static int ahci_dma_rw_buf(IDEDMA *dma, int is_write) dma_buf_write(p, l, &s->sg); } - /* free sglist that was created in ahci_populate_sglist() */ - qemu_sglist_destroy(&s->sg); + /* free sglist, update byte count */ + ahci_commit_buf(dma, l); - /* update number of transferred bytes */ - ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + l); s->io_buffer_index += l; s->io_buffer_offset += l; @@ -1098,28 +1234,11 @@ static int ahci_dma_set_unit(IDEDMA *dma, int unit) return 0; } -static int ahci_dma_add_status(IDEDMA *dma, int status) -{ - AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); - DPRINTF(ad->port_no, "set status: %x\n", status); - - if (status & BM_STATUS_INT) { - ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_DSS); - } - - return 0; -} - -static int ahci_dma_set_inactive(IDEDMA *dma) -{ - return 0; -} - -static int ahci_async_cmd_done(IDEDMA *dma) +static void ahci_cmd_done(IDEDMA *dma) { AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); - DPRINTF(ad->port_no, "async cmd done\n"); + DPRINTF(ad->port_no, "cmd done\n"); /* update d2h status */ ahci_write_fis_d2h(ad, NULL); @@ -1129,8 +1248,6 @@ static int ahci_async_cmd_done(IDEDMA *dma) ad->check_bh = qemu_bh_new(ahci_check_cmd_bh, ad); qemu_bh_schedule(ad->check_bh); } - - return 0; } static void ahci_irq_set(void *opaque, int n, int level) @@ -1141,22 +1258,15 @@ static void ahci_dma_restart_cb(void *opaque, int running, RunState state) { } -static int ahci_dma_reset(IDEDMA *dma) -{ - return 0; -} - static const IDEDMAOps ahci_dma_ops = { .start_dma = ahci_start_dma, .start_transfer = ahci_start_transfer, .prepare_buf = ahci_dma_prepare_buf, + .commit_buf = ahci_commit_buf, .rw_buf = ahci_dma_rw_buf, .set_unit = ahci_dma_set_unit, - .add_status = ahci_dma_add_status, - .set_inactive = ahci_dma_set_inactive, - .async_cmd_done = ahci_async_cmd_done, + .cmd_done = ahci_cmd_done, .restart_cb = ahci_dma_restart_cb, - .reset = ahci_dma_reset, }; void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports) @@ -1166,7 +1276,7 @@ void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports) s->as = as; s->ports = ports; - s->dev = g_malloc0(sizeof(AHCIDevice) * ports); + s->dev = g_new0(AHCIDevice, ports); ahci_reg_init(s); /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */ memory_region_init_io(&s->mem, OBJECT(qdev), &ahci_mem_ops, s, @@ -1191,8 +1301,6 @@ void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports) void ahci_uninit(AHCIState *s) { - memory_region_destroy(&s->mem); - memory_region_destroy(&s->idp); g_free(s->dev); } @@ -1225,7 +1333,7 @@ void ahci_reset(AHCIState *s) static const VMStateDescription vmstate_ahci_device = { .name = "ahci port", .version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_IDE_BUS(port, AHCIDevice), VMSTATE_UINT32(port_state, AHCIDevice), VMSTATE_UINT32(finished, AHCIDevice), @@ -1260,9 +1368,9 @@ static int ahci_state_post_load(void *opaque, int version_id) ad = &s->dev[i]; AHCIPortRegs *pr = &ad->port_regs; - map_page(&ad->lst, + map_page(s->as, &ad->lst, ((uint64_t)pr->lst_addr_hi << 32) | pr->lst_addr, 1024); - map_page(&ad->res_fis, + map_page(s->as, &ad->res_fis, ((uint64_t)pr->fis_addr_hi << 32) | pr->fis_addr, 256); /* * All pending i/o should be flushed out on a migrate. However, @@ -1284,7 +1392,7 @@ const VMStateDescription vmstate_ahci = { .name = "ahci", .version_id = 1, .post_load = ahci_state_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_VARRAY_POINTER_INT32(dev, AHCIState, ports, vmstate_ahci_device, AHCIDevice), VMSTATE_UINT32(control_regs.cap, AHCIState), @@ -1293,7 +1401,7 @@ const VMStateDescription vmstate_ahci = { VMSTATE_UINT32(control_regs.impl, AHCIState), VMSTATE_UINT32(control_regs.version, AHCIState), VMSTATE_UINT32(idp_index, AHCIState), - VMSTATE_INT32(ports, AHCIState), + VMSTATE_INT32_EQUAL(ports, AHCIState), VMSTATE_END_OF_LIST() }, }; @@ -1313,7 +1421,7 @@ typedef struct SysbusAHCIState { static const VMStateDescription vmstate_sysbus_ahci = { .name = "sysbus-ahci", .unmigratable = 1, /* Still buggy under I/O load */ - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_AHCI(ahci, SysbusAHCIState), VMSTATE_END_OF_LIST() }, @@ -1366,3 +1474,18 @@ static void sysbus_ahci_register_types(void) } type_init(sysbus_ahci_register_types) + +void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd) +{ + AHCIPCIState *d = ICH_AHCI(dev); + AHCIState *ahci = &d->ahci; + int i; + + for (i = 0; i < ahci->ports; i++) { + if (hd[i] == NULL) { + continue; + } + ide_create_drive(&ahci->dev[i].port, 0, hd[i]); + } + +} diff --git a/hw/ide/ahci.h b/hw/ide/ahci.h index 9a4064f892..e0d2eb8f15 100644 --- a/hw/ide/ahci.h +++ b/hw/ide/ahci.h @@ -132,27 +132,6 @@ #define PORT_CMD_ICC_PARTIAL (0x2 << 28) /* Put i/f in partial state */ #define PORT_CMD_ICC_SLUMBER (0x6 << 28) /* Put i/f in slumber state */ -#define PORT_IRQ_STAT_DHRS (1 << 0) /* Device to Host Register FIS */ -#define PORT_IRQ_STAT_PSS (1 << 1) /* PIO Setup FIS */ -#define PORT_IRQ_STAT_DSS (1 << 2) /* DMA Setup FIS */ -#define PORT_IRQ_STAT_SDBS (1 << 3) /* Set Device Bits */ -#define PORT_IRQ_STAT_UFS (1 << 4) /* Unknown FIS */ -#define PORT_IRQ_STAT_DPS (1 << 5) /* Descriptor Processed */ -#define PORT_IRQ_STAT_PCS (1 << 6) /* Port Connect Change Status */ -#define PORT_IRQ_STAT_DMPS (1 << 7) /* Device Mechanical Presence - Status */ -#define PORT_IRQ_STAT_PRCS (1 << 22) /* File Ready Status */ -#define PORT_IRQ_STAT_IPMS (1 << 23) /* Incorrect Port Multiplier - Status */ -#define PORT_IRQ_STAT_OFS (1 << 24) /* Overflow Status */ -#define PORT_IRQ_STAT_INFS (1 << 26) /* Interface Non-Fatal Error - Status */ -#define PORT_IRQ_STAT_IFS (1 << 27) /* Interface Fatal Error */ -#define PORT_IRQ_STAT_HBDS (1 << 28) /* Host Bus Data Error Status */ -#define PORT_IRQ_STAT_HBFS (1 << 29) /* Host Bus Fatal Error Status */ -#define PORT_IRQ_STAT_TFES (1 << 30) /* Task File Error Status */ -#define PORT_IRQ_STAT_CPDS (1U << 31) /* Code Port Detect Status */ - /* ap->flags bits */ #define AHCI_FLAG_NO_NCQ (1 << 24) #define AHCI_FLAG_IGN_IRQ_IF_ERR (1 << 25) /* ignore IRQ_IF_ERR */ @@ -201,10 +180,15 @@ #define AHCI_COMMAND_TABLE_ACMD 0x40 +#define AHCI_PRDT_SIZE_MASK 0x3fffff + #define IDE_FEATURE_DMA 1 #define READ_FPDMA_QUEUED 0x60 #define WRITE_FPDMA_QUEUED 0x61 +#define NCQ_NON_DATA 0x63 +#define RECEIVE_FPDMA_QUEUED 0x65 +#define SEND_FPDMA_QUEUED 0x64 #define RES_FIS_DSFIS 0x00 #define RES_FIS_PSFIS 0x20 @@ -260,7 +244,7 @@ typedef struct AHCIDevice AHCIDevice; typedef struct NCQTransferState { AHCIDevice *drive; - BlockDriverAIOCB *aiocb; + BlockAIOCB *aiocb; QEMUSGList sglist; BlockAcctCookie acct; uint16_t sector_count; @@ -346,9 +330,19 @@ typedef struct NCQFrame { uint8_t reserved10; } QEMU_PACKED NCQFrame; +typedef struct SDBFIS { + uint8_t type; + uint8_t flags; + uint8_t status; + uint8_t error; + uint32_t payload; +} QEMU_PACKED SDBFIS; + void ahci_init(AHCIState *s, DeviceState *qdev, AddressSpace *as, int ports); void ahci_uninit(AHCIState *s); void ahci_reset(AHCIState *s); +void ahci_ide_create_devs(PCIDevice *dev, DriveInfo **hd); + #endif /* HW_IDE_AHCI_H */ diff --git a/hw/ide/atapi.c b/hw/ide/atapi.c index f7d2009c00..c63b7e556e 100644 --- a/hw/ide/atapi.c +++ b/hw/ide/atapi.c @@ -25,6 +25,7 @@ #include "hw/ide/internal.h" #include "hw/scsi/scsi.h" +#include "sysemu/block-backend.h" static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret); @@ -110,14 +111,16 @@ static int cd_read_sector(IDEState *s, int lba, uint8_t *buf, int sector_size) switch(sector_size) { case 2048: - bdrv_acct_start(s->bs, &s->acct, 4 * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); - ret = bdrv_read(s->bs, (int64_t)lba << 2, buf, 4); - bdrv_acct_done(s->bs, &s->acct); + block_acct_start(blk_get_stats(s->blk), &s->acct, + 4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); + ret = blk_read(s->blk, (int64_t)lba << 2, buf, 4); + block_acct_done(blk_get_stats(s->blk), &s->acct); break; case 2352: - bdrv_acct_start(s->bs, &s->acct, 4 * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); - ret = bdrv_read(s->bs, (int64_t)lba << 2, buf + 16, 4); - bdrv_acct_done(s->bs, &s->acct); + block_acct_start(blk_get_stats(s->blk), &s->acct, + 4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); + ret = blk_read(s->blk, (int64_t)lba << 2, buf + 16, 4); + block_acct_done(blk_get_stats(s->blk), &s->acct); if (ret < 0) return ret; cd_data_to_raw(buf, lba); @@ -134,6 +137,7 @@ void ide_atapi_cmd_ok(IDEState *s) s->error = 0; s->status = READY_STAT | SEEK_STAT; s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + ide_transfer_stop(s); ide_set_irq(s->bus); } @@ -147,6 +151,7 @@ void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc) s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; s->sense_key = sense_key; s->asc = asc; + ide_transfer_stop(s); ide_set_irq(s->bus); } @@ -174,9 +179,7 @@ void ide_atapi_cmd_reply_end(IDEState *s) #endif if (s->packet_transfer_size <= 0) { /* end of transfer */ - ide_transfer_stop(s); - s->status = READY_STAT | SEEK_STAT; - s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD; + ide_atapi_cmd_ok(s); ide_set_irq(s->bus); #ifdef DEBUG_IDE_ATAPI printf("status=0x%x\n", s->status); @@ -186,7 +189,6 @@ void ide_atapi_cmd_reply_end(IDEState *s) if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) { ret = cd_read_sector(s, s->lba, s->io_buffer, s->cd_sector_size); if (ret < 0) { - ide_transfer_stop(s); ide_atapi_io_error(s, ret); return; } @@ -253,10 +255,10 @@ static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size) s->io_buffer_index = 0; if (s->atapi_dma) { - bdrv_acct_start(s->bs, &s->acct, size, BDRV_ACCT_READ); + block_acct_start(blk_get_stats(s->blk), &s->acct, size, + BLOCK_ACCT_READ); s->status = READY_STAT | SEEK_STAT | DRQ_STAT; - s->bus->dma->ops->start_dma(s->bus->dma, s, - ide_atapi_cmd_read_dma_cb); + ide_start_dma(s, ide_atapi_cmd_read_dma_cb); } else { s->status = READY_STAT | SEEK_STAT; ide_atapi_cmd_reply_end(s); @@ -349,15 +351,14 @@ static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret) s->bus->dma->iov.iov_len = n * 4 * 512; qemu_iovec_init_external(&s->bus->dma->qiov, &s->bus->dma->iov, 1); - s->bus->dma->aiocb = bdrv_aio_readv(s->bs, (int64_t)s->lba << 2, + s->bus->dma->aiocb = blk_aio_readv(s->blk, (int64_t)s->lba << 2, &s->bus->dma->qiov, n * 4, ide_atapi_cmd_read_dma_cb, s); return; eot: - bdrv_acct_done(s->bs, &s->acct); - s->bus->dma->ops->add_status(s->bus->dma, BM_STATUS_INT); - ide_set_inactive(s); + block_acct_done(blk_get_stats(s->blk), &s->acct); + ide_set_inactive(s, false); } /* start a CD-CDROM read command with DMA */ @@ -371,12 +372,12 @@ static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors, s->io_buffer_size = 0; s->cd_sector_size = sector_size; - bdrv_acct_start(s->bs, &s->acct, s->packet_transfer_size, BDRV_ACCT_READ); + block_acct_start(blk_get_stats(s->blk), &s->acct, s->packet_transfer_size, + BLOCK_ACCT_READ); /* XXX: check if BUSY_STAT should be set */ s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT; - s->bus->dma->ops->start_dma(s->bus->dma, s, - ide_atapi_cmd_read_dma_cb); + ide_start_dma(s, ide_atapi_cmd_read_dma_cb); } static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors, @@ -504,7 +505,7 @@ static unsigned int event_status_media(IDEState *s, media_status = 0; if (s->tray_open) { media_status = MS_TRAY_OPEN; - } else if (bdrv_is_inserted(s->bs)) { + } else if (blk_is_inserted(s->blk)) { media_status = MS_MEDIA_PRESENT; } @@ -800,7 +801,7 @@ static void cmd_test_unit_ready(IDEState *s, uint8_t *buf) static void cmd_prevent_allow_medium_removal(IDEState *s, uint8_t* buf) { s->tray_locked = buf[4] & 1; - bdrv_lock_medium(s->bs, buf[4] & 1); + blk_lock_medium(s->blk, buf[4] & 1); ide_atapi_cmd_ok(s); } @@ -884,14 +885,14 @@ static void cmd_start_stop_unit(IDEState *s, uint8_t* buf) if (loej) { if (!start && !s->tray_open && s->tray_locked) { - sense = bdrv_is_inserted(s->bs) + sense = blk_is_inserted(s->blk) ? NOT_READY : ILLEGAL_REQUEST; ide_atapi_cmd_error(s, sense, ASC_MEDIA_REMOVAL_PREVENTED); return; } if (s->tray_open != !start) { - bdrv_eject(s->bs, !start); + blk_eject(s->blk, !start); s->tray_open = !start; } } @@ -1125,7 +1126,7 @@ void ide_atapi_cmd(IDEState *s) * states rely on this behavior. */ if (!(atapi_cmd_table[s->io_buffer[0]].flags & ALLOW_UA) && - !s->tray_open && bdrv_is_inserted(s->bs) && s->cdrom_changed) { + !s->tray_open && blk_is_inserted(s->blk) && s->cdrom_changed) { if (s->cdrom_changed == 1) { ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT); @@ -1140,7 +1141,7 @@ void ide_atapi_cmd(IDEState *s) /* Report a Not Ready condition if appropriate for the command */ if ((atapi_cmd_table[s->io_buffer[0]].flags & CHECK_READY) && - (!media_present(s) || !bdrv_is_inserted(s->bs))) + (!media_present(s) || !blk_is_inserted(s->blk))) { ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT); return; diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c index a8e35fe38f..c8b0322155 100644 --- a/hw/ide/cmd646.c +++ b/hw/ide/cmd646.c @@ -26,13 +26,20 @@ #include <hw/i386/pc.h> #include <hw/pci/pci.h> #include <hw/isa/isa.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "sysemu/dma.h" #include <hw/ide/pci.h> /* CMD646 specific */ +#define CFR 0x50 +#define CFR_INTR_CH0 0x04 +#define CNTRL 0x51 +#define CNTRL_EN_CH0 0x04 +#define CNTRL_EN_CH1 0x08 +#define ARTTIM23 0x57 +#define ARTTIM23_INTR_CH1 0x10 #define MRDMODE 0x71 #define MRDMODE_INTR_CH0 0x04 #define MRDMODE_INTR_CH1 0x08 @@ -41,7 +48,7 @@ #define UDIDETCR0 0x73 #define UDIDETCR1 0x7B -static void cmd646_update_irq(PCIIDEState *d); +static void cmd646_update_irq(PCIDevice *pd); static uint64_t cmd646_cmd_read(void *opaque, hwaddr addr, unsigned size) @@ -123,6 +130,38 @@ static void setup_cmd646_bar(PCIIDEState *d, int bus_num) "cmd646-data", 8); } +static void cmd646_update_dma_interrupts(PCIDevice *pd) +{ + /* Sync DMA interrupt status from UDMA interrupt status */ + if (pd->config[MRDMODE] & MRDMODE_INTR_CH0) { + pd->config[CFR] |= CFR_INTR_CH0; + } else { + pd->config[CFR] &= ~CFR_INTR_CH0; + } + + if (pd->config[MRDMODE] & MRDMODE_INTR_CH1) { + pd->config[ARTTIM23] |= ARTTIM23_INTR_CH1; + } else { + pd->config[ARTTIM23] &= ~ARTTIM23_INTR_CH1; + } +} + +static void cmd646_update_udma_interrupts(PCIDevice *pd) +{ + /* Sync UDMA interrupt status from DMA interrupt status */ + if (pd->config[CFR] & CFR_INTR_CH0) { + pd->config[MRDMODE] |= MRDMODE_INTR_CH0; + } else { + pd->config[MRDMODE] &= ~MRDMODE_INTR_CH0; + } + + if (pd->config[ARTTIM23] & ARTTIM23_INTR_CH1) { + pd->config[MRDMODE] |= MRDMODE_INTR_CH1; + } else { + pd->config[MRDMODE] &= ~MRDMODE_INTR_CH1; + } +} + static uint64_t bmdma_read(void *opaque, hwaddr addr, unsigned size) { @@ -181,7 +220,8 @@ static void bmdma_write(void *opaque, hwaddr addr, case 1: pci_dev->config[MRDMODE] = (pci_dev->config[MRDMODE] & ~0x30) | (val & 0x30); - cmd646_update_irq(bm->pci_dev); + cmd646_update_dma_interrupts(pci_dev); + cmd646_update_irq(pci_dev); break; case 2: bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06); @@ -219,11 +259,8 @@ static void bmdma_setup_bar(PCIIDEState *d) } } -/* XXX: call it also when the MRDMODE is changed from the PCI config - registers */ -static void cmd646_update_irq(PCIIDEState *d) +static void cmd646_update_irq(PCIDevice *pd) { - PCIDevice *pd = PCI_DEVICE(d); int pci_level; pci_level = ((pd->config[MRDMODE] & MRDMODE_INTR_CH0) && @@ -246,7 +283,8 @@ static void cmd646_set_irq(void *opaque, int channel, int level) } else { pd->config[MRDMODE] &= ~irq_mask; } - cmd646_update_irq(d); + cmd646_update_dma_interrupts(pd); + cmd646_update_irq(pd); } static void cmd646_reset(void *opaque) @@ -259,6 +297,34 @@ static void cmd646_reset(void *opaque) } } +static uint32_t cmd646_pci_config_read(PCIDevice *d, + uint32_t address, int len) +{ + return pci_default_read_config(d, address, len); +} + +static void cmd646_pci_config_write(PCIDevice *d, uint32_t addr, uint32_t val, + int l) +{ + uint32_t i; + + pci_default_write_config(d, addr, val, l); + + for (i = addr; i < addr + l; i++) { + switch (i) { + case CFR: + case ARTTIM23: + cmd646_update_udma_interrupts(d); + break; + case MRDMODE: + cmd646_update_dma_interrupts(d); + break; + } + } + + cmd646_update_irq(d); +} + /* CMD646 PCI IDE controller */ static int pci_cmd646_ide_initfn(PCIDevice *dev) { @@ -269,12 +335,20 @@ static int pci_cmd646_ide_initfn(PCIDevice *dev) pci_conf[PCI_CLASS_PROG] = 0x8f; - pci_conf[0x51] = 0x04; // enable IDE0 + pci_conf[CNTRL] = CNTRL_EN_CH0; // enable IDE0 if (d->secondary) { /* XXX: if not enabled, really disable the seconday IDE controller */ - pci_conf[0x51] |= 0x08; /* enable IDE1 */ + pci_conf[CNTRL] |= CNTRL_EN_CH1; /* enable IDE1 */ } + /* Set write-to-clear interrupt bits */ + dev->wmask[CFR] = 0x0; + dev->w1cmask[CFR] = CFR_INTR_CH0; + dev->wmask[ARTTIM23] = 0x0; + dev->w1cmask[ARTTIM23] = ARTTIM23_INTR_CH1; + dev->wmask[MRDMODE] = 0x0; + dev->w1cmask[MRDMODE] = MRDMODE_INTR_CH0 | MRDMODE_INTR_CH1; + setup_cmd646_bar(d, 0); setup_cmd646_bar(d, 1); pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &d->cmd646_bar[0].data); @@ -310,13 +384,8 @@ static void pci_cmd646_ide_exitfn(PCIDevice *dev) for (i = 0; i < 2; ++i) { memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].extra_io); - memory_region_destroy(&d->bmdma[i].extra_io); memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].addr_ioport); - memory_region_destroy(&d->bmdma[i].addr_ioport); - memory_region_destroy(&d->cmd646_bar[i].cmd); - memory_region_destroy(&d->cmd646_bar[i].data); } - memory_region_destroy(&d->bmdma_bar); } void pci_cmd646_ide_init(PCIBus *bus, DriveInfo **hd_table, @@ -347,6 +416,8 @@ static void cmd646_ide_class_init(ObjectClass *klass, void *data) k->device_id = PCI_DEVICE_ID_CMD_646; k->revision = 0x07; k->class_id = PCI_CLASS_STORAGE_IDE; + k->config_read = cmd646_pci_config_read; + k->config_write = cmd646_pci_config_write; dc->props = cmd646_ide_properties; } diff --git a/hw/ide/core.c b/hw/ide/core.c index c943a4d764..d4af5e2eb1 100644 --- a/hw/ide/core.c +++ b/hw/ide/core.c @@ -31,7 +31,7 @@ #include "sysemu/sysemu.h" #include "sysemu/dma.h" #include "hw/block/block.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include <hw/ide/internal.h> @@ -75,19 +75,29 @@ static void put_le16(uint16_t *p, unsigned int v) *p = cpu_to_le16(v); } +static void ide_identify_size(IDEState *s) +{ + uint16_t *p = (uint16_t *)s->identify_data; + put_le16(p + 60, s->nb_sectors); + put_le16(p + 61, s->nb_sectors >> 16); + put_le16(p + 100, s->nb_sectors); + put_le16(p + 101, s->nb_sectors >> 16); + put_le16(p + 102, s->nb_sectors >> 32); + put_le16(p + 103, s->nb_sectors >> 48); +} + static void ide_identify(IDEState *s) { uint16_t *p; unsigned int oldsize; IDEDevice *dev = s->unit ? s->bus->slave : s->bus->master; + p = (uint16_t *)s->identify_data; if (s->identify_set) { - memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data)); - return; + goto fill_buffer; } + memset(p, 0, sizeof(s->identify_data)); - memset(s->io_buffer, 0, 512); - p = (uint16_t *)s->io_buffer; put_le16(p + 0, 0x0040); put_le16(p + 1, s->cylinders); put_le16(p + 3, s->heads); @@ -116,8 +126,8 @@ static void ide_identify(IDEState *s) put_le16(p + 58, oldsize >> 16); if (s->mult_sectors) put_le16(p + 59, 0x100 | s->mult_sectors); - put_le16(p + 60, s->nb_sectors); - put_le16(p + 61, s->nb_sectors >> 16); + /* *(p + 60) := nb_sectors -- see ide_identify_size */ + /* *(p + 61) := nb_sectors >> 16 -- see ide_identify_size */ put_le16(p + 62, 0x07); /* single word dma0-2 supported */ put_le16(p + 63, 0x07); /* mdma0-2 supported */ put_le16(p + 64, 0x03); /* pio3-4 supported */ @@ -148,10 +158,11 @@ static void ide_identify(IDEState *s) put_le16(p + 84, (1 << 14) | 0); } /* 14 = NOP supported, 5=WCACHE enabled, 0=SMART feature set enabled */ - if (bdrv_enable_write_cache(s->bs)) - put_le16(p + 85, (1 << 14) | (1 << 5) | 1); - else - put_le16(p + 85, (1 << 14) | 1); + if (blk_enable_write_cache(s->blk)) { + put_le16(p + 85, (1 << 14) | (1 << 5) | 1); + } else { + put_le16(p + 85, (1 << 14) | 1); + } /* 13=flush_cache_ext,12=flush_cache,10=lba48 */ put_le16(p + 86, (1 << 13) | (1 <<12) | (1 << 10)); /* 14=set to 1, 8=has WWN, 1=SMART self test, 0=SMART error logging */ @@ -162,10 +173,10 @@ static void ide_identify(IDEState *s) } put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */ put_le16(p + 93, 1 | (1 << 14) | 0x2000); - put_le16(p + 100, s->nb_sectors); - put_le16(p + 101, s->nb_sectors >> 16); - put_le16(p + 102, s->nb_sectors >> 32); - put_le16(p + 103, s->nb_sectors >> 48); + /* *(p + 100) := nb_sectors -- see ide_identify_size */ + /* *(p + 101) := nb_sectors >> 16 -- see ide_identify_size */ + /* *(p + 102) := nb_sectors >> 32 -- see ide_identify_size */ + /* *(p + 103) := nb_sectors >> 48 -- see ide_identify_size */ if (dev && dev->conf.physical_block_size) put_le16(p + 106, 0x6000 | get_physical_block_exp(&dev->conf)); @@ -180,21 +191,23 @@ static void ide_identify(IDEState *s) put_le16(p + 169, 1); /* TRIM support */ } - memcpy(s->identify_data, p, sizeof(s->identify_data)); + ide_identify_size(s); s->identify_set = 1; + +fill_buffer: + memcpy(s->io_buffer, p, sizeof(s->identify_data)); } static void ide_atapi_identify(IDEState *s) { uint16_t *p; + p = (uint16_t *)s->identify_data; if (s->identify_set) { - memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data)); - return; + goto fill_buffer; } + memset(p, 0, sizeof(s->identify_data)); - memset(s->io_buffer, 0, 512); - p = (uint16_t *)s->io_buffer; /* Removable CDROM, 50us response, 12 byte packets */ put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0)); padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */ @@ -230,11 +243,36 @@ static void ide_atapi_identify(IDEState *s) } put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */ + if (s->wwn) { + put_le16(p + 84, (1 << 8)); /* supports WWN for words 108-111 */ + put_le16(p + 87, (1 << 8)); /* WWN enabled */ + } + #ifdef USE_DMA_CDROM put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */ #endif - memcpy(s->identify_data, p, sizeof(s->identify_data)); + + if (s->wwn) { + /* LE 16-bit words 111-108 contain 64-bit World Wide Name */ + put_le16(p + 108, s->wwn >> 48); + put_le16(p + 109, s->wwn >> 32); + put_le16(p + 110, s->wwn >> 16); + put_le16(p + 111, s->wwn); + } + s->identify_set = 1; + +fill_buffer: + memcpy(s->io_buffer, p, sizeof(s->identify_data)); +} + +static void ide_cfata_identify_size(IDEState *s) +{ + uint16_t *p = (uint16_t *)s->identify_data; + put_le16(p + 7, s->nb_sectors >> 16); /* Sectors per card */ + put_le16(p + 8, s->nb_sectors); /* Sectors per card */ + put_le16(p + 60, s->nb_sectors); /* Total LBA sectors */ + put_le16(p + 61, s->nb_sectors >> 16); /* Total LBA sectors */ } static void ide_cfata_identify(IDEState *s) @@ -242,10 +280,10 @@ static void ide_cfata_identify(IDEState *s) uint16_t *p; uint32_t cur_sec; - p = (uint16_t *) s->identify_data; - if (s->identify_set) + p = (uint16_t *)s->identify_data; + if (s->identify_set) { goto fill_buffer; - + } memset(p, 0, sizeof(s->identify_data)); cur_sec = s->cylinders * s->heads * s->sectors; @@ -254,8 +292,8 @@ static void ide_cfata_identify(IDEState *s) put_le16(p + 1, s->cylinders); /* Default cylinders */ put_le16(p + 3, s->heads); /* Default heads */ put_le16(p + 6, s->sectors); /* Default sectors per track */ - put_le16(p + 7, s->nb_sectors >> 16); /* Sectors per card */ - put_le16(p + 8, s->nb_sectors); /* Sectors per card */ + /* *(p + 7) := nb_sectors >> 16 -- see ide_cfata_identify_size */ + /* *(p + 8) := nb_sectors -- see ide_cfata_identify_size */ padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */ put_le16(p + 22, 0x0004); /* ECC bytes */ padstr((char *) (p + 23), s->version, 8); /* Firmware Revision */ @@ -276,8 +314,8 @@ static void ide_cfata_identify(IDEState *s) put_le16(p + 58, cur_sec >> 16); /* Current capacity */ if (s->mult_sectors) /* Multiple sector setting */ put_le16(p + 59, 0x100 | s->mult_sectors); - put_le16(p + 60, s->nb_sectors); /* Total LBA sectors */ - put_le16(p + 61, s->nb_sectors >> 16); /* Total LBA sectors */ + /* *(p + 60) := nb_sectors -- see ide_cfata_identify_size */ + /* *(p + 61) := nb_sectors >> 16 -- see ide_cfata_identify_size */ put_le16(p + 63, 0x0203); /* Multiword DMA capability */ put_le16(p + 64, 0x0001); /* Flow Control PIO support */ put_le16(p + 65, 0x0096); /* Min. Multiword DMA cycle */ @@ -297,6 +335,7 @@ static void ide_cfata_identify(IDEState *s) put_le16(p + 160, 0x8100); /* Power requirement */ put_le16(p + 161, 0x8001); /* CF command set */ + ide_cfata_identify_size(s); s->identify_set = 1; fill_buffer: @@ -312,7 +351,7 @@ static void ide_set_signature(IDEState *s) if (s->drive_kind == IDE_CD) { s->lcyl = 0x14; s->hcyl = 0xeb; - } else if (s->bs) { + } else if (s->blk) { s->lcyl = 0; s->hcyl = 0; } else { @@ -322,35 +361,34 @@ static void ide_set_signature(IDEState *s) } typedef struct TrimAIOCB { - BlockDriverAIOCB common; + BlockAIOCB common; + BlockBackend *blk; QEMUBH *bh; int ret; QEMUIOVector *qiov; - BlockDriverAIOCB *aiocb; + BlockAIOCB *aiocb; int i, j; } TrimAIOCB; -static void trim_aio_cancel(BlockDriverAIOCB *acb) +static void trim_aio_cancel(BlockAIOCB *acb) { TrimAIOCB *iocb = container_of(acb, TrimAIOCB, common); - /* Exit the loop in case bdrv_aio_cancel calls ide_issue_trim_cb again. */ + /* Exit the loop so ide_issue_trim_cb will not continue */ iocb->j = iocb->qiov->niov - 1; iocb->i = (iocb->qiov->iov[iocb->j].iov_len / 8) - 1; - /* Tell ide_issue_trim_cb not to trigger the completion, too. */ - qemu_bh_delete(iocb->bh); - iocb->bh = NULL; + iocb->ret = -ECANCELED; if (iocb->aiocb) { - bdrv_aio_cancel(iocb->aiocb); + blk_aio_cancel_async(iocb->aiocb); + iocb->aiocb = NULL; } - qemu_aio_release(iocb); } static const AIOCBInfo trim_aiocb_info = { .aiocb_size = sizeof(TrimAIOCB), - .cancel = trim_aio_cancel, + .cancel_async = trim_aio_cancel, }; static void ide_trim_bh_cb(void *opaque) @@ -361,7 +399,7 @@ static void ide_trim_bh_cb(void *opaque) qemu_bh_delete(iocb->bh); iocb->bh = NULL; - qemu_aio_release(iocb); + qemu_aio_unref(iocb); } static void ide_issue_trim_cb(void *opaque, int ret) @@ -384,8 +422,8 @@ static void ide_issue_trim_cb(void *opaque, int ret) } /* Got an entry! Submit and exit. */ - iocb->aiocb = bdrv_aio_discard(iocb->common.bs, sector, count, - ide_issue_trim_cb, opaque); + iocb->aiocb = blk_aio_discard(iocb->blk, sector, count, + ide_issue_trim_cb, opaque); return; } @@ -402,13 +440,14 @@ static void ide_issue_trim_cb(void *opaque, int ret) } } -BlockDriverAIOCB *ide_issue_trim(BlockDriverState *bs, +BlockAIOCB *ide_issue_trim(BlockBackend *blk, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, - BlockDriverCompletionFunc *cb, void *opaque) + BlockCompletionFunc *cb, void *opaque) { TrimAIOCB *iocb; - iocb = qemu_aio_get(&trim_aiocb_info, bs, cb, opaque); + iocb = blk_aio_get(&trim_aiocb_info, blk, cb, opaque); + iocb->blk = blk; iocb->bh = qemu_bh_new(ide_trim_bh_cb, iocb); iocb->ret = 0; iocb->qiov = qiov; @@ -420,6 +459,7 @@ BlockDriverAIOCB *ide_issue_trim(BlockDriverState *bs, static inline void ide_abort_command(IDEState *s) { + ide_transfer_stop(s); s->status = READY_STAT | ERR_STAT; s->error = ABRT_ERR; } @@ -434,7 +474,16 @@ void ide_transfer_start(IDEState *s, uint8_t *buf, int size, if (!(s->status & ERR_STAT)) { s->status |= DRQ_STAT; } - s->bus->dma->ops->start_transfer(s->bus->dma); + if (s->bus->dma->ops->start_transfer) { + s->bus->dma->ops->start_transfer(s->bus->dma); + } +} + +static void ide_cmd_done(IDEState *s) +{ + if (s->bus->dma->ops->cmd_done) { + s->bus->dma->ops->cmd_done(s->bus->dma); + } } void ide_transfer_stop(IDEState *s) @@ -443,6 +492,7 @@ void ide_transfer_stop(IDEState *s) s->data_ptr = s->io_buffer; s->data_end = s->io_buffer; s->status &= ~DRQ_STAT; + ide_cmd_done(s); } int64_t ide_get_sector(IDEState *s) @@ -499,6 +549,18 @@ static void ide_rw_error(IDEState *s) { ide_set_irq(s->bus); } +static bool ide_sect_range_ok(IDEState *s, + uint64_t sector, uint64_t nb_sectors) +{ + uint64_t total_sectors; + + blk_get_geometry(s->blk, &total_sectors); + if (sector > total_sectors || nb_sectors > total_sectors - sector) { + return false; + } + return true; +} + static void ide_sector_read_cb(void *opaque, int ret) { IDEState *s = opaque; @@ -507,10 +569,13 @@ static void ide_sector_read_cb(void *opaque, int ret) s->pio_aiocb = NULL; s->status &= ~BUSY_STAT; - bdrv_acct_done(s->bs, &s->acct); + if (ret == -ECANCELED) { + return; + } + block_acct_done(blk_get_stats(s->blk), &s->acct); if (ret != 0) { - if (ide_handle_rw_error(s, -ret, BM_STATUS_PIO_RETRY | - BM_STATUS_RETRY_READ)) { + if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO | + IDE_RETRY_READ)) { return; } } @@ -527,6 +592,7 @@ static void ide_sector_read_cb(void *opaque, int ret) ide_set_sector(s, ide_get_sector(s) + n); s->nsector -= n; + s->io_buffer_offset += 512 * n; } void ide_sector_read(IDEState *s) @@ -554,61 +620,63 @@ void ide_sector_read(IDEState *s) printf("sector=%" PRId64 "\n", sector_num); #endif + if (!ide_sect_range_ok(s, sector_num, n)) { + ide_rw_error(s); + return; + } + s->iov.iov_base = s->io_buffer; s->iov.iov_len = n * BDRV_SECTOR_SIZE; qemu_iovec_init_external(&s->qiov, &s->iov, 1); - bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); - s->pio_aiocb = bdrv_aio_readv(s->bs, sector_num, &s->qiov, n, - ide_sector_read_cb, s); + block_acct_start(blk_get_stats(s->blk), &s->acct, + n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); + s->pio_aiocb = blk_aio_readv(s->blk, sector_num, &s->qiov, n, + ide_sector_read_cb, s); } -static void dma_buf_commit(IDEState *s) +static void dma_buf_commit(IDEState *s, uint32_t tx_bytes) { - qemu_sglist_destroy(&s->sg); -} - -static void ide_async_cmd_done(IDEState *s) -{ - if (s->bus->dma->ops->async_cmd_done) { - s->bus->dma->ops->async_cmd_done(s->bus->dma); + if (s->bus->dma->ops->commit_buf) { + s->bus->dma->ops->commit_buf(s->bus->dma, tx_bytes); } + qemu_sglist_destroy(&s->sg); } -void ide_set_inactive(IDEState *s) +void ide_set_inactive(IDEState *s, bool more) { s->bus->dma->aiocb = NULL; - s->bus->dma->ops->set_inactive(s->bus->dma); - ide_async_cmd_done(s); + if (s->bus->dma->ops->set_inactive) { + s->bus->dma->ops->set_inactive(s->bus->dma, more); + } + ide_cmd_done(s); } void ide_dma_error(IDEState *s) { - ide_transfer_stop(s); - s->error = ABRT_ERR; - s->status = READY_STAT | ERR_STAT; - ide_set_inactive(s); + dma_buf_commit(s, 0); + ide_abort_command(s); + ide_set_inactive(s, false); ide_set_irq(s->bus); } static int ide_handle_rw_error(IDEState *s, int error, int op) { - bool is_read = (op & BM_STATUS_RETRY_READ) != 0; - BlockErrorAction action = bdrv_get_error_action(s->bs, is_read, error); + bool is_read = (op & IDE_RETRY_READ) != 0; + BlockErrorAction action = blk_get_error_action(s->blk, is_read, error); - if (action == BDRV_ACTION_STOP) { + if (action == BLOCK_ERROR_ACTION_STOP) { s->bus->dma->ops->set_unit(s->bus->dma, s->unit); s->bus->error_status = op; - } else if (action == BDRV_ACTION_REPORT) { - if (op & BM_STATUS_DMA_RETRY) { - dma_buf_commit(s); + } else if (action == BLOCK_ERROR_ACTION_REPORT) { + if (op & IDE_RETRY_DMA) { ide_dma_error(s); } else { ide_rw_error(s); } } - bdrv_error_action(s->bs, action, is_read, error); - return action != BDRV_ACTION_IGNORE; + blk_error_action(s->blk, action, is_read, error); + return action != BLOCK_ERROR_ACTION_IGNORE; } void ide_dma_cb(void *opaque, int ret) @@ -618,13 +686,16 @@ void ide_dma_cb(void *opaque, int ret) int64_t sector_num; bool stay_active = false; + if (ret == -ECANCELED) { + return; + } if (ret < 0) { - int op = BM_STATUS_DMA_RETRY; + int op = IDE_RETRY_DMA; if (s->dma_cmd == IDE_DMA_READ) - op |= BM_STATUS_RETRY_READ; + op |= IDE_RETRY_READ; else if (s->dma_cmd == IDE_DMA_TRIM) - op |= BM_STATUS_RETRY_TRIM; + op |= IDE_RETRY_TRIM; if (ide_handle_rw_error(s, -ret, op)) { return; @@ -642,7 +713,8 @@ void ide_dma_cb(void *opaque, int ret) sector_num = ide_get_sector(s); if (n > 0) { - dma_buf_commit(s); + assert(s->io_buffer_size == s->sg.size); + dma_buf_commit(s, s->io_buffer_size); sector_num += n; ide_set_sector(s, sector_num); s->nsector -= n; @@ -659,10 +731,11 @@ void ide_dma_cb(void *opaque, int ret) n = s->nsector; s->io_buffer_index = 0; s->io_buffer_size = n * 512; - if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) { + if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) < 512) { /* The PRDs were too short. Reset the Active bit, but don't raise an * interrupt. */ s->status = READY_STAT | SEEK_STAT; + dma_buf_commit(s, 0); goto eot; } @@ -671,31 +744,34 @@ void ide_dma_cb(void *opaque, int ret) sector_num, n, s->dma_cmd); #endif + if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) && + !ide_sect_range_ok(s, sector_num, n)) { + ide_dma_error(s); + return; + } + switch (s->dma_cmd) { case IDE_DMA_READ: - s->bus->dma->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num, - ide_dma_cb, s); + s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, sector_num, + ide_dma_cb, s); break; case IDE_DMA_WRITE: - s->bus->dma->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num, - ide_dma_cb, s); + s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, sector_num, + ide_dma_cb, s); break; case IDE_DMA_TRIM: - s->bus->dma->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num, - ide_issue_trim, ide_dma_cb, s, - DMA_DIRECTION_TO_DEVICE); + s->bus->dma->aiocb = dma_blk_io(s->blk, &s->sg, sector_num, + ide_issue_trim, ide_dma_cb, s, + DMA_DIRECTION_TO_DEVICE); break; } return; eot: if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) { - bdrv_acct_done(s->bs, &s->acct); - } - ide_set_inactive(s); - if (stay_active) { - s->bus->dma->ops->add_status(s->bus->dma, BM_STATUS_DMAING); + block_acct_done(blk_get_stats(s->blk), &s->acct); } + ide_set_inactive(s, stay_active); } static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd) @@ -707,18 +783,25 @@ static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd) switch (dma_cmd) { case IDE_DMA_READ: - bdrv_acct_start(s->bs, &s->acct, s->nsector * BDRV_SECTOR_SIZE, - BDRV_ACCT_READ); + block_acct_start(blk_get_stats(s->blk), &s->acct, + s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); break; case IDE_DMA_WRITE: - bdrv_acct_start(s->bs, &s->acct, s->nsector * BDRV_SECTOR_SIZE, - BDRV_ACCT_WRITE); + block_acct_start(blk_get_stats(s->blk), &s->acct, + s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE); break; default: break; } - s->bus->dma->ops->start_dma(s->bus->dma, s, ide_dma_cb); + ide_start_dma(s, ide_dma_cb); +} + +void ide_start_dma(IDEState *s, BlockCompletionFunc *cb) +{ + if (s->bus->dma->ops->start_dma) { + s->bus->dma->ops->start_dma(s->bus->dma, s, cb); + } } static void ide_sector_write_timer_cb(void *opaque) @@ -732,13 +815,16 @@ static void ide_sector_write_cb(void *opaque, int ret) IDEState *s = opaque; int n; - bdrv_acct_done(s->bs, &s->acct); + if (ret == -ECANCELED) { + return; + } + block_acct_done(blk_get_stats(s->blk), &s->acct); s->pio_aiocb = NULL; s->status &= ~BUSY_STAT; if (ret != 0) { - if (ide_handle_rw_error(s, -ret, BM_STATUS_PIO_RETRY)) { + if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO)) { return; } } @@ -748,6 +834,8 @@ static void ide_sector_write_cb(void *opaque, int ret) n = s->req_nb_sectors; } s->nsector -= n; + s->io_buffer_offset += 512 * n; + if (s->nsector == 0) { /* no more sectors to write */ ide_transfer_stop(s); @@ -790,42 +878,55 @@ void ide_sector_write(IDEState *s) n = s->req_nb_sectors; } + if (!ide_sect_range_ok(s, sector_num, n)) { + ide_rw_error(s); + return; + } + s->iov.iov_base = s->io_buffer; s->iov.iov_len = n * BDRV_SECTOR_SIZE; qemu_iovec_init_external(&s->qiov, &s->iov, 1); - bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); - s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n, - ide_sector_write_cb, s); + block_acct_start(blk_get_stats(s->blk), &s->acct, + n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); + s->pio_aiocb = blk_aio_writev(s->blk, sector_num, &s->qiov, n, + ide_sector_write_cb, s); } static void ide_flush_cb(void *opaque, int ret) { IDEState *s = opaque; + s->pio_aiocb = NULL; + + if (ret == -ECANCELED) { + return; + } if (ret < 0) { /* XXX: What sector number to set here? */ - if (ide_handle_rw_error(s, -ret, BM_STATUS_RETRY_FLUSH)) { + if (ide_handle_rw_error(s, -ret, IDE_RETRY_FLUSH)) { return; } } - bdrv_acct_done(s->bs, &s->acct); + if (s->blk) { + block_acct_done(blk_get_stats(s->blk), &s->acct); + } s->status = READY_STAT | SEEK_STAT; - ide_async_cmd_done(s); + ide_cmd_done(s); ide_set_irq(s->bus); } void ide_flush_cache(IDEState *s) { - if (s->bs == NULL) { + if (s->blk == NULL) { ide_flush_cb(s, 0); return; } s->status |= BUSY_STAT; - bdrv_acct_start(s->bs, &s->acct, 0, BDRV_ACCT_FLUSH); - bdrv_aio_flush(s->bs, ide_flush_cb, s); + block_acct_start(blk_get_stats(s->blk), &s->acct, 0, BLOCK_ACCT_FLUSH); + s->pio_aiocb = blk_aio_flush(s->blk, ide_flush_cb, s); } static void ide_cfata_metadata_inquiry(IDEState *s) @@ -888,7 +989,7 @@ static void ide_cd_change_cb(void *opaque, bool load) uint64_t nb_sectors; s->tray_open = !load; - bdrv_get_geometry(s->bs, &nb_sectors); + blk_get_geometry(s->blk, &nb_sectors); s->nb_sectors = nb_sectors; /* @@ -1022,7 +1123,7 @@ static bool cmd_data_set_management(IDEState *s, uint8_t cmd) { switch (s->feature) { case DSM_TRIM: - if (s->bs) { + if (s->blk) { ide_sector_start_dma(s, IDE_DMA_TRIM); return false; } @@ -1035,7 +1136,7 @@ static bool cmd_data_set_management(IDEState *s, uint8_t cmd) static bool cmd_identify(IDEState *s, uint8_t cmd) { - if (s->bs && s->drive_kind != IDE_CD) { + if (s->blk && s->drive_kind != IDE_CD) { if (s->drive_kind != IDE_CFATA) { ide_identify(s); } else { @@ -1085,7 +1186,7 @@ static bool cmd_read_multiple(IDEState *s, uint8_t cmd) { bool lba48 = (cmd == WIN_MULTREAD_EXT); - if (!s->bs || !s->mult_sectors) { + if (!s->blk || !s->mult_sectors) { ide_abort_command(s); return true; } @@ -1101,7 +1202,7 @@ static bool cmd_write_multiple(IDEState *s, uint8_t cmd) bool lba48 = (cmd == WIN_MULTWRITE_EXT); int n; - if (!s->bs || !s->mult_sectors) { + if (!s->blk || !s->mult_sectors) { ide_abort_command(s); return true; } @@ -1129,7 +1230,7 @@ static bool cmd_read_pio(IDEState *s, uint8_t cmd) return true; } - if (!s->bs) { + if (!s->blk) { ide_abort_command(s); return true; } @@ -1145,7 +1246,7 @@ static bool cmd_write_pio(IDEState *s, uint8_t cmd) { bool lba48 = (cmd == WIN_WRITE_EXT); - if (!s->bs) { + if (!s->blk) { ide_abort_command(s); return true; } @@ -1165,7 +1266,7 @@ static bool cmd_read_dma(IDEState *s, uint8_t cmd) { bool lba48 = (cmd == WIN_READDMA_EXT); - if (!s->bs) { + if (!s->blk) { ide_abort_command(s); return true; } @@ -1180,7 +1281,7 @@ static bool cmd_write_dma(IDEState *s, uint8_t cmd) { bool lba48 = (cmd == WIN_WRITEDMA_EXT); - if (!s->bs) { + if (!s->blk) { ide_abort_command(s); return true; } @@ -1231,7 +1332,7 @@ static bool cmd_set_features(IDEState *s, uint8_t cmd) { uint16_t *identify_data; - if (!s->bs) { + if (!s->blk) { ide_abort_command(s); return true; } @@ -1239,12 +1340,12 @@ static bool cmd_set_features(IDEState *s, uint8_t cmd) /* XXX: valid for CDROM ? */ switch (s->feature) { case 0x02: /* write cache enable */ - bdrv_set_enable_write_cache(s->bs, true); + blk_set_enable_write_cache(s->blk, true); identify_data = (uint16_t *)s->identify_data; put_le16(identify_data + 85, (1 << 14) | (1 << 5) | 1); return true; case 0x82: /* write cache disable */ - bdrv_set_enable_write_cache(s->bs, false); + blk_set_enable_write_cache(s->blk, false); identify_data = (uint16_t *)s->identify_data; put_le16(identify_data + 85, (1 << 14) | 1); ide_flush_cache(s); @@ -1711,8 +1812,9 @@ void ide_exec_cmd(IDEBus *bus, uint32_t val) #endif s = idebus_active_if(bus); /* ignore commands to non existent slave */ - if (s != bus->ifs && !s->bs) + if (s != bus->ifs && !s->blk) { return; + } /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */ if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET) @@ -1726,6 +1828,7 @@ void ide_exec_cmd(IDEBus *bus, uint32_t val) s->status = READY_STAT | BUSY_STAT; s->error = 0; + s->io_buffer_offset = 0; complete = ide_cmd_table[val].handler(s, val); if (complete) { @@ -1736,6 +1839,7 @@ void ide_exec_cmd(IDEBus *bus, uint32_t val) s->status |= SEEK_STAT; } + ide_cmd_done(s); ide_set_irq(s->bus); } } @@ -1756,59 +1860,66 @@ uint32_t ide_ioport_read(void *opaque, uint32_t addr1) ret = 0xff; break; case 1: - if ((!bus->ifs[0].bs && !bus->ifs[1].bs) || - (s != bus->ifs && !s->bs)) + if ((!bus->ifs[0].blk && !bus->ifs[1].blk) || + (s != bus->ifs && !s->blk)) { ret = 0; - else if (!hob) + } else if (!hob) { ret = s->error; - else + } else { ret = s->hob_feature; + } break; case 2: - if (!bus->ifs[0].bs && !bus->ifs[1].bs) + if (!bus->ifs[0].blk && !bus->ifs[1].blk) { ret = 0; - else if (!hob) + } else if (!hob) { ret = s->nsector & 0xff; - else + } else { ret = s->hob_nsector; + } break; case 3: - if (!bus->ifs[0].bs && !bus->ifs[1].bs) + if (!bus->ifs[0].blk && !bus->ifs[1].blk) { ret = 0; - else if (!hob) + } else if (!hob) { ret = s->sector; - else + } else { ret = s->hob_sector; + } break; case 4: - if (!bus->ifs[0].bs && !bus->ifs[1].bs) + if (!bus->ifs[0].blk && !bus->ifs[1].blk) { ret = 0; - else if (!hob) + } else if (!hob) { ret = s->lcyl; - else + } else { ret = s->hob_lcyl; + } break; case 5: - if (!bus->ifs[0].bs && !bus->ifs[1].bs) + if (!bus->ifs[0].blk && !bus->ifs[1].blk) { ret = 0; - else if (!hob) + } else if (!hob) { ret = s->hcyl; - else + } else { ret = s->hob_hcyl; + } break; case 6: - if (!bus->ifs[0].bs && !bus->ifs[1].bs) + if (!bus->ifs[0].blk && !bus->ifs[1].blk) { ret = 0; - else + } else { ret = s->select; + } break; default: case 7: - if ((!bus->ifs[0].bs && !bus->ifs[1].bs) || - (s != bus->ifs && !s->bs)) + if ((!bus->ifs[0].blk && !bus->ifs[1].blk) || + (s != bus->ifs && !s->blk)) { ret = 0; - else + } else { ret = s->status; + } qemu_irq_lower(bus->irq); break; } @@ -1824,11 +1935,12 @@ uint32_t ide_status_read(void *opaque, uint32_t addr) IDEState *s = idebus_active_if(bus); int ret; - if ((!bus->ifs[0].bs && !bus->ifs[1].bs) || - (s != bus->ifs && !s->bs)) + if ((!bus->ifs[0].blk && !bus->ifs[1].blk) || + (s != bus->ifs && !s->blk)) { ret = 0; - else + } else { ret = s->status; + } #ifdef DEBUG_IDE printf("ide: read status addr=0x%x val=%02x\n", addr, ret); #endif @@ -1989,7 +2101,7 @@ static void ide_reset(IDEState *s) #endif if (s->pio_aiocb) { - bdrv_aio_cancel(s->pio_aiocb); + blk_aio_cancel(s->pio_aiocb); s->pio_aiocb = NULL; } @@ -2053,12 +2165,14 @@ void ide_bus_reset(IDEBus *bus) #ifdef DEBUG_AIO printf("aio_cancel\n"); #endif - bdrv_aio_cancel(bus->dma->aiocb); + blk_aio_cancel(bus->dma->aiocb); bus->dma->aiocb = NULL; } /* reset dma provider too */ - bus->dma->ops->reset(bus->dma); + if (bus->dma->ops->reset) { + bus->dma->ops->reset(bus->dma); + } } static bool ide_cd_is_tray_open(void *opaque) @@ -2071,6 +2185,28 @@ static bool ide_cd_is_medium_locked(void *opaque) return ((IDEState *)opaque)->tray_locked; } +static void ide_resize_cb(void *opaque) +{ + IDEState *s = opaque; + uint64_t nb_sectors; + + if (!s->identify_set) { + return; + } + + blk_get_geometry(s->blk, &nb_sectors); + s->nb_sectors = nb_sectors; + + /* Update the identify data buffer. */ + if (s->drive_kind == IDE_CFATA) { + ide_cfata_identify_size(s); + } else { + /* IDE_CD uses a different set of callbacks entirely. */ + assert(s->drive_kind != IDE_CD); + ide_identify_size(s); + } +} + static const BlockDevOps ide_cd_block_ops = { .change_media_cb = ide_cd_change_cb, .eject_request_cb = ide_cd_eject_request_cb, @@ -2078,7 +2214,11 @@ static const BlockDevOps ide_cd_block_ops = { .is_medium_locked = ide_cd_is_medium_locked, }; -int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind, +static const BlockDevOps ide_hd_block_ops = { + .resize_cb = ide_resize_cb, +}; + +int ide_init_drive(IDEState *s, BlockBackend *blk, IDEDriveKind kind, const char *version, const char *serial, const char *model, uint64_t wwn, uint32_t cylinders, uint32_t heads, uint32_t secs, @@ -2086,10 +2226,10 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind, { uint64_t nb_sectors; - s->bs = bs; + s->blk = blk; s->drive_kind = kind; - bdrv_get_geometry(bs, &nb_sectors); + blk_get_geometry(blk, &nb_sectors); s->cylinders = cylinders; s->heads = heads; s->sectors = secs; @@ -2103,17 +2243,18 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind, s->smart_errors = 0; s->smart_selftest_count = 0; if (kind == IDE_CD) { - bdrv_set_dev_ops(bs, &ide_cd_block_ops, s); - bdrv_set_guest_block_size(bs, 2048); + blk_set_dev_ops(blk, &ide_cd_block_ops, s); + blk_set_guest_block_size(blk, 2048); } else { - if (!bdrv_is_inserted(s->bs)) { + if (!blk_is_inserted(s->blk)) { error_report("Device needs media, but drive is empty"); return -1; } - if (bdrv_is_read_only(bs)) { + if (blk_is_read_only(blk)) { error_report("Can't use a read-only drive"); return -1; } + blk_set_dev_ops(blk, &ide_hd_block_ops, s); } if (serial) { pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), serial); @@ -2144,7 +2285,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind, } ide_reset(s); - bdrv_iostatus_enable(bs); + blk_iostatus_enable(blk); return 0; } @@ -2161,24 +2302,19 @@ static void ide_init1(IDEBus *bus, int unit) s->io_buffer = qemu_memalign(2048, s->io_buffer_total_len); memset(s->io_buffer, 0, s->io_buffer_total_len); - s->smart_selftest_data = qemu_blockalign(s->bs, 512); + s->smart_selftest_data = blk_blockalign(s->blk, 512); memset(s->smart_selftest_data, 0, 512); s->sector_write_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ide_sector_write_timer_cb, s); } -static void ide_nop_start(IDEDMA *dma, IDEState *s, - BlockDriverCompletionFunc *cb) -{ -} - -static int ide_nop(IDEDMA *dma) +static int ide_nop_int(IDEDMA *dma, int x) { return 0; } -static int ide_nop_int(IDEDMA *dma, int x) +static int32_t ide_nop_int32(IDEDMA *dma, int x) { return 0; } @@ -2188,15 +2324,10 @@ static void ide_nop_restart(void *opaque, int x, RunState y) } static const IDEDMAOps ide_dma_nop_ops = { - .start_dma = ide_nop_start, - .start_transfer = ide_nop, - .prepare_buf = ide_nop_int, + .prepare_buf = ide_nop_int32, .rw_buf = ide_nop_int, .set_unit = ide_nop_int, - .add_status = ide_nop_int, - .set_inactive = ide_nop, .restart_cb = ide_nop_restart, - .reset = ide_nop, }; static IDEDMA ide_dma_nop = { @@ -2270,8 +2401,8 @@ static int ide_drive_post_load(void *opaque, int version_id) { IDEState *s = opaque; - if (s->identify_set) { - bdrv_set_enable_write_cache(s->bs, !!(s->identify_data[85] & (1 << 5))); + if (s->blk && s->identify_set) { + blk_set_enable_write_cache(s->blk, !!(s->identify_data[85] & (1 << 5))); } return 0; } @@ -2313,7 +2444,7 @@ static bool ide_drive_pio_state_needed(void *opaque) IDEState *s = opaque; return ((s->status & DRQ_STAT) != 0) - || (s->bus->error_status & BM_STATUS_PIO_RETRY); + || (s->bus->error_status & IDE_RETRY_PIO); } static bool ide_tray_state_needed(void *opaque) @@ -2342,8 +2473,7 @@ static const VMStateDescription vmstate_ide_atapi_gesn_state = { .name ="ide_drive/atapi/gesn_state", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_BOOL(events.new_media, IDEState), VMSTATE_BOOL(events.eject_request, IDEState), VMSTATE_END_OF_LIST() @@ -2354,7 +2484,6 @@ static const VMStateDescription vmstate_ide_tray_state = { .name = "ide_drive/tray_state", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_BOOL(tray_open, IDEState), VMSTATE_BOOL(tray_locked, IDEState), @@ -2366,10 +2495,9 @@ static const VMStateDescription vmstate_ide_drive_pio_state = { .name = "ide_drive/pio_state", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = ide_drive_pio_pre_save, .post_load = ide_drive_pio_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(req_nb_sectors, IDEState), VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1, vmstate_info_uint8, uint8_t), @@ -2386,9 +2514,8 @@ const VMStateDescription vmstate_ide_drive = { .name = "ide_drive", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = ide_drive_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(mult_sectors, IDEState), VMSTATE_INT32(identify_set, IDEState), VMSTATE_BUFFER_TEST(identify_data, IDEState, is_identify_set), @@ -2431,8 +2558,7 @@ static const VMStateDescription vmstate_ide_error_status = { .name ="ide_bus/error", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(error_status, IDEBus), VMSTATE_END_OF_LIST() } @@ -2442,8 +2568,7 @@ const VMStateDescription vmstate_ide_bus = { .name = "ide_bus", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(cmd, IDEBus), VMSTATE_UINT8(unit, IDEBus), VMSTATE_END_OF_LIST() @@ -2458,16 +2583,28 @@ const VMStateDescription vmstate_ide_bus = { } }; -void ide_drive_get(DriveInfo **hd, int max_bus) +void ide_drive_get(DriveInfo **hd, int n) { int i; + int highest_bus = drive_get_max_bus(IF_IDE) + 1; + int max_devs = drive_get_max_devs(IF_IDE); + int n_buses = max_devs ? (n / max_devs) : n; + + /* + * Note: The number of actual buses available is not known. + * We compute this based on the size of the DriveInfo* array, n. + * If it is less than max_devs * <num_real_buses>, + * We will stop looking for drives prematurely instead of overfilling + * the array. + */ - if (drive_get_max_bus(IF_IDE) >= max_bus) { - fprintf(stderr, "qemu: too many IDE bus: %d\n", max_bus); + if (highest_bus > n_buses) { + error_report("Too many IDE buses defined (%d > %d)", + highest_bus, n_buses); exit(1); } - for(i = 0; i < max_bus * MAX_IDE_DEVS; i++) { - hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS); + for (i = 0; i < n; i++) { + hd[i] = drive_get_by_index(IF_IDE, i); } } diff --git a/hw/ide/ich.c b/hw/ide/ich.c index 1c7c05810d..fb1d095503 100644 --- a/hw/ide/ich.c +++ b/hw/ide/ich.c @@ -65,12 +65,13 @@ #include <hw/i386/pc.h> #include <hw/pci/pci.h> #include <hw/isa/isa.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include <hw/ide/pci.h> #include <hw/ide/ahci.h> +#define ICH9_MSI_CAP_OFFSET 0x80 #define ICH9_SATA_CAP_OFFSET 0xA8 #define ICH9_IDP_BAR 4 @@ -83,7 +84,7 @@ static const VMStateDescription vmstate_ich9_ahci = { .name = "ich9_ahci", .unmigratable = 1, /* Still buggy under I/O load */ .version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, AHCIPCIState), VMSTATE_AHCI(ahci, AHCIPCIState), VMSTATE_END_OF_LIST() @@ -115,7 +116,6 @@ static int pci_ich9_ahci_init(PCIDevice *dev) /* XXX Software should program this register */ dev->config[0x90] = 1 << 6; /* Address Map Register - AHCI mode */ - msi_init(dev, 0x50, 1, true, false); d->ahci.irq = pci_allocate_irq(dev); pci_register_bar(dev, ICH9_IDP_BAR, PCI_BASE_ADDRESS_SPACE_IO, @@ -135,6 +135,11 @@ static int pci_ich9_ahci_init(PCIDevice *dev) (ICH9_IDP_BAR + 0x4) | (ICH9_IDP_INDEX_LOG2 << 4)); d->ahci.idp_offset = ICH9_IDP_INDEX; + /* Although the AHCI 1.3 specification states that the first capability + * should be PMCAP, the Intel ICH9 data sheet specifies that the ICH9 + * AHCI device puts the MSI capability first, pointing to 0x80. */ + msi_init(dev, ICH9_MSI_CAP_OFFSET, 1, true, false); + return 0; } diff --git a/hw/ide/internal.h b/hw/ide/internal.h index 0567a522f5..8a3eca40d2 100644 --- a/hw/ide/internal.h +++ b/hw/ide/internal.h @@ -319,9 +319,12 @@ typedef enum { IDE_HD, IDE_CD, IDE_CFATA } IDEDriveKind; typedef void EndTransferFunc(IDEState *); -typedef void DMAStartFunc(IDEDMA *, IDEState *, BlockDriverCompletionFunc *); -typedef int DMAFunc(IDEDMA *); +typedef void DMAStartFunc(IDEDMA *, IDEState *, BlockCompletionFunc *); +typedef void DMAVoidFunc(IDEDMA *); typedef int DMAIntFunc(IDEDMA *, int); +typedef int32_t DMAInt32Func(IDEDMA *, int); +typedef void DMAu32Func(IDEDMA *, uint32_t); +typedef void DMAStopFunc(IDEDMA *, bool); typedef void DMARestartFunc(void *, int, RunState); struct unreported_events { @@ -372,7 +375,7 @@ struct IDEState { /* set for lba48 access */ uint8_t lba48; - BlockDriverState *bs; + BlockBackend *blk; char version[9]; /* ATAPI specific */ struct unreported_events events; @@ -383,17 +386,17 @@ struct IDEState { uint8_t cdrom_changed; int packet_transfer_size; int elementary_transfer_size; - int io_buffer_index; + int32_t io_buffer_index; int lba; int cd_sector_size; int atapi_dma; /* true if dma is requested for the packet cmd */ BlockAcctCookie acct; - BlockDriverAIOCB *pio_aiocb; + BlockAIOCB *pio_aiocb; struct iovec iov; QEMUIOVector qiov; /* ATA DMA state */ - int io_buffer_offset; - int io_buffer_size; + int32_t io_buffer_offset; + int32_t io_buffer_size; QEMUSGList sg; /* PIO transfer handling */ int req_nb_sectors; /* number of sectors per interrupt */ @@ -403,8 +406,8 @@ struct IDEState { uint8_t *io_buffer; /* PIO save/restore */ int32_t io_buffer_total_len; - int cur_io_buffer_offset; - int cur_io_buffer_len; + int32_t cur_io_buffer_offset; + int32_t cur_io_buffer_len; uint8_t end_transfer_fn_idx; QEMUTimer *sector_write_timer; /* only used for win2k install hack */ uint32_t irq_count; /* counts IRQs when using win2k install hack */ @@ -427,22 +430,22 @@ struct IDEState { struct IDEDMAOps { DMAStartFunc *start_dma; - DMAFunc *start_transfer; - DMAIntFunc *prepare_buf; + DMAVoidFunc *start_transfer; + DMAInt32Func *prepare_buf; + DMAu32Func *commit_buf; DMAIntFunc *rw_buf; DMAIntFunc *set_unit; - DMAIntFunc *add_status; - DMAFunc *set_inactive; - DMAFunc *async_cmd_done; + DMAStopFunc *set_inactive; + DMAVoidFunc *cmd_done; DMARestartFunc *restart_cb; - DMAFunc *reset; + DMAVoidFunc *reset; }; struct IDEDMA { const struct IDEDMAOps *ops; struct iovec iov; QEMUIOVector qiov; - BlockDriverAIOCB *aiocb; + BlockAIOCB *aiocb; }; struct IDEBus { @@ -484,23 +487,12 @@ struct IDEDevice { uint64_t wwn; }; -#define BM_STATUS_DMAING 0x01 -#define BM_STATUS_ERROR 0x02 -#define BM_STATUS_INT 0x04 - -/* FIXME These are not status register bits */ -#define BM_STATUS_DMA_RETRY 0x08 -#define BM_STATUS_PIO_RETRY 0x10 -#define BM_STATUS_RETRY_READ 0x20 -#define BM_STATUS_RETRY_FLUSH 0x40 -#define BM_STATUS_RETRY_TRIM 0x80 - -#define BM_MIGRATION_COMPAT_STATUS_BITS \ - (BM_STATUS_DMA_RETRY | BM_STATUS_PIO_RETRY | \ - BM_STATUS_RETRY_READ | BM_STATUS_RETRY_FLUSH) - -#define BM_CMD_START 0x01 -#define BM_CMD_READ 0x08 +/* These are used for the error_status field of IDEBus */ +#define IDE_RETRY_DMA 0x08 +#define IDE_RETRY_PIO 0x10 +#define IDE_RETRY_READ 0x20 +#define IDE_RETRY_FLUSH 0x40 +#define IDE_RETRY_TRIM 0x80 static inline IDEState *idebus_active_if(IDEBus *bus) { @@ -532,6 +524,7 @@ void ide_bus_reset(IDEBus *bus); int64_t ide_get_sector(IDEState *s); void ide_set_sector(IDEState *s, int64_t sector_num); +void ide_start_dma(IDEState *s, BlockCompletionFunc *cb); void ide_dma_error(IDEState *s); void ide_atapi_cmd_ok(IDEState *s); @@ -547,7 +540,7 @@ uint32_t ide_data_readw(void *opaque, uint32_t addr); void ide_data_writel(void *opaque, uint32_t addr, uint32_t val); uint32_t ide_data_readl(void *opaque, uint32_t addr); -int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind, +int ide_init_drive(IDEState *s, BlockBackend *blk, IDEDriveKind kind, const char *version, const char *serial, const char *model, uint64_t wwn, uint32_t cylinders, uint32_t heads, uint32_t secs, @@ -564,10 +557,10 @@ void ide_flush_cache(IDEState *s); void ide_transfer_start(IDEState *s, uint8_t *buf, int size, EndTransferFunc *end_transfer_func); void ide_transfer_stop(IDEState *s); -void ide_set_inactive(IDEState *s); -BlockDriverAIOCB *ide_issue_trim(BlockDriverState *bs, +void ide_set_inactive(IDEState *s, bool more); +BlockAIOCB *ide_issue_trim(BlockBackend *blk, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, - BlockDriverCompletionFunc *cb, void *opaque); + BlockCompletionFunc *cb, void *opaque); /* hw/ide/atapi.c */ void ide_atapi_cmd(IDEState *s); diff --git a/hw/ide/isa.c b/hw/ide/isa.c index d2cabc142f..b084162ddc 100644 --- a/hw/ide/isa.c +++ b/hw/ide/isa.c @@ -25,7 +25,7 @@ #include <hw/hw.h> #include <hw/i386/pc.h> #include <hw/isa/isa.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include <hw/ide/internal.h> @@ -57,8 +57,7 @@ static const VMStateDescription vmstate_ide_isa = { .name = "isa-ide", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_IDE_BUS(bus, ISAIDEState), VMSTATE_IDE_DRIVES(bus.ifs, ISAIDEState), VMSTATE_END_OF_LIST() diff --git a/hw/ide/macio.c b/hw/ide/macio.c index da94580aac..f6074f2024 100644 --- a/hw/ide/macio.c +++ b/hw/ide/macio.c @@ -25,7 +25,7 @@ #include "hw/hw.h" #include "hw/ppc/mac.h" #include "hw/ppc/mac_dbdma.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include <hw/ide/internal.h> @@ -134,7 +134,7 @@ static void pmac_ide_atapi_transfer_cb(void *opaque, int ret) MACIO_DPRINTF("precopying unaligned %d bytes to %#" HWADDR_PRIx "\n", unaligned, io->addr + io->len - unaligned); - bdrv_read(s->bs, sector_num + nsector, io->remainder, 1); + blk_read(s->blk, sector_num + nsector, io->remainder, 1); cpu_physical_memory_write(io->addr + io->len - unaligned, io->remainder, unaligned); @@ -164,14 +164,14 @@ static void pmac_ide_atapi_transfer_cb(void *opaque, int ret) (s->lba << 2) + (s->io_buffer_index >> 9), s->packet_transfer_size, s->dma_cmd); - m->aiocb = dma_bdrv_read(s->bs, &s->sg, - (int64_t)(s->lba << 2) + (s->io_buffer_index >> 9), - pmac_ide_atapi_transfer_cb, io); + m->aiocb = dma_blk_read(s->blk, &s->sg, + (int64_t)(s->lba << 2) + (s->io_buffer_index >> 9), + pmac_ide_atapi_transfer_cb, io); return; done: MACIO_DPRINTF("done DMA\n"); - bdrv_acct_done(s->bs, &s->acct); + block_acct_done(blk_get_stats(s->blk), &s->acct); io->dma_end(opaque); } @@ -193,6 +193,11 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) goto done; } + if (--io->requests) { + /* More requests still in flight */ + return; + } + if (!m->dma_active) { MACIO_DPRINTF("waiting for data (%#x - %#x - %x)\n", s->nsector, io->len, s->status); @@ -212,6 +217,13 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) s->nsector -= n; } + if (io->finish_remain_read) { + /* Finish a stale read from the last iteration */ + io->finish_remain_read = false; + cpu_physical_memory_write(io->finish_addr, io->remainder, + io->finish_len); + } + MACIO_DPRINTF("remainder: %d io->len: %d nsector: %d " "sector_num: %" PRId64 "\n", io->remainder_len, io->len, s->nsector, sector_num); @@ -229,7 +241,6 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) break; case IDE_DMA_WRITE: cpu_physical_memory_read(io->addr, p, remainder_len); - bdrv_write(s->bs, sector_num - 1, io->remainder, 1); break; case IDE_DMA_TRIM: break; @@ -237,6 +248,15 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) io->addr += remainder_len; io->len -= remainder_len; io->remainder_len -= remainder_len; + + if (s->dma_cmd == IDE_DMA_WRITE && !io->remainder_len) { + io->requests++; + qemu_iovec_reset(&io->iov); + qemu_iovec_add(&io->iov, io->remainder, 0x200); + + m->aiocb = blk_aio_writev(s->blk, sector_num - 1, &io->iov, 1, + pmac_ide_transfer_cb, io); + } } if (s->nsector == 0 && !io->remainder_len) { @@ -267,20 +287,25 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) switch (s->dma_cmd) { case IDE_DMA_READ: - bdrv_read(s->bs, sector_num + nsector, io->remainder, 1); - cpu_physical_memory_write(io->addr + io->len - unaligned, - io->remainder, unaligned); + io->requests++; + io->finish_addr = io->addr + io->len - unaligned; + io->finish_len = unaligned; + io->finish_remain_read = true; + qemu_iovec_reset(&io->iov); + qemu_iovec_add(&io->iov, io->remainder, 0x200); + + m->aiocb = blk_aio_readv(s->blk, sector_num + nsector, &io->iov, 1, + pmac_ide_transfer_cb, io); break; case IDE_DMA_WRITE: /* cache the contents in our io struct */ cpu_physical_memory_read(io->addr + io->len - unaligned, - io->remainder, unaligned); + io->remainder + io->remainder_len, + unaligned); break; case IDE_DMA_TRIM: break; } - - io->len -= unaligned; } MACIO_DPRINTF("io->len = %#x\n", io->len); @@ -292,10 +317,12 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) io->remainder_len = (0x200 - unaligned) & 0x1ff; MACIO_DPRINTF("set remainder to: %d\n", io->remainder_len); - /* We would read no data from the block layer, thus not get a callback. - Just fake completion manually. */ + /* Only subsector reads happening */ if (!io->len) { - pmac_ide_transfer_cb(opaque, 0); + if (!io->requests) { + io->requests++; + pmac_ide_transfer_cb(opaque, ret); + } return; } @@ -306,24 +333,26 @@ static void pmac_ide_transfer_cb(void *opaque, int ret) switch (s->dma_cmd) { case IDE_DMA_READ: - m->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num, - pmac_ide_transfer_cb, io); + m->aiocb = dma_blk_read(s->blk, &s->sg, sector_num, + pmac_ide_transfer_cb, io); break; case IDE_DMA_WRITE: - m->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num, - pmac_ide_transfer_cb, io); + m->aiocb = dma_blk_write(s->blk, &s->sg, sector_num, + pmac_ide_transfer_cb, io); break; case IDE_DMA_TRIM: - m->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num, - ide_issue_trim, pmac_ide_transfer_cb, io, - DMA_DIRECTION_TO_DEVICE); + m->aiocb = dma_blk_io(s->blk, &s->sg, sector_num, + ide_issue_trim, pmac_ide_transfer_cb, io, + DMA_DIRECTION_TO_DEVICE); break; } + + io->requests++; return; done: if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) { - bdrv_acct_done(s->bs, &s->acct); + block_acct_done(blk_get_stats(s->blk), &s->acct); } io->dma_end(io); } @@ -337,22 +366,47 @@ static void pmac_ide_transfer(DBDMA_io *io) s->io_buffer_size = 0; if (s->drive_kind == IDE_CD) { - bdrv_acct_start(s->bs, &s->acct, io->len, BDRV_ACCT_READ); + + /* Handle non-block ATAPI DMA transfers */ + if (s->lba == -1) { + s->io_buffer_size = MIN(io->len, s->packet_transfer_size); + block_acct_start(blk_get_stats(s->blk), &s->acct, s->io_buffer_size, + BLOCK_ACCT_READ); + MACIO_DPRINTF("non-block ATAPI DMA transfer size: %d\n", + s->io_buffer_size); + + /* Copy ATAPI buffer directly to RAM and finish */ + cpu_physical_memory_write(io->addr, s->io_buffer, + s->io_buffer_size); + ide_atapi_cmd_ok(s); + m->dma_active = false; + + MACIO_DPRINTF("end of non-block ATAPI DMA transfer\n"); + block_acct_done(blk_get_stats(s->blk), &s->acct); + io->dma_end(io); + return; + } + + block_acct_start(blk_get_stats(s->blk), &s->acct, io->len, + BLOCK_ACCT_READ); pmac_ide_atapi_transfer_cb(io, 0); return; } switch (s->dma_cmd) { case IDE_DMA_READ: - bdrv_acct_start(s->bs, &s->acct, io->len, BDRV_ACCT_READ); + block_acct_start(blk_get_stats(s->blk), &s->acct, io->len, + BLOCK_ACCT_READ); break; case IDE_DMA_WRITE: - bdrv_acct_start(s->bs, &s->acct, io->len, BDRV_ACCT_WRITE); + block_acct_start(blk_get_stats(s->blk), &s->acct, io->len, + BLOCK_ACCT_WRITE); break; default: break; } + io->requests++; pmac_ide_transfer_cb(io, 0); } @@ -361,7 +415,7 @@ static void pmac_ide_flush(DBDMA_io *io) MACIOIDEState *m = io->opaque; if (m->aiocb) { - bdrv_drain_all(); + blk_drain_all(); } } @@ -480,8 +534,7 @@ static const VMStateDescription vmstate_pmac = { .name = "ide", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_IDE_BUS(bus, MACIOIDEState), VMSTATE_IDE_DRIVES(bus.ifs, MACIOIDEState), VMSTATE_END_OF_LIST() @@ -495,12 +548,12 @@ static void macio_ide_reset(DeviceState *dev) ide_bus_reset(&d->bus); } -static int ide_nop(IDEDMA *dma) +static int ide_nop_int(IDEDMA *dma, int x) { return 0; } -static int ide_nop_int(IDEDMA *dma, int x) +static int32_t ide_nop_int32(IDEDMA *dma, int x) { return 0; } @@ -510,7 +563,7 @@ static void ide_nop_restart(void *opaque, int x, RunState y) } static void ide_dbdma_start(IDEDMA *dma, IDEState *s, - BlockDriverCompletionFunc *cb) + BlockCompletionFunc *cb) { MACIOIDEState *m = container_of(dma, MACIOIDEState, dma); @@ -521,14 +574,10 @@ static void ide_dbdma_start(IDEDMA *dma, IDEState *s, static const IDEDMAOps dbdma_ops = { .start_dma = ide_dbdma_start, - .start_transfer = ide_nop, - .prepare_buf = ide_nop_int, + .prepare_buf = ide_nop_int32, .rw_buf = ide_nop_int, .set_unit = ide_nop_int, - .add_status = ide_nop_int, - .set_inactive = ide_nop, .restart_cb = ide_nop_restart, - .reset = ide_nop, }; static void macio_ide_realizefn(DeviceState *dev, Error **errp) diff --git a/hw/ide/microdrive.c b/hw/ide/microdrive.c index 21d6495817..6639dd4886 100644 --- a/hw/ide/microdrive.c +++ b/hw/ide/microdrive.c @@ -25,7 +25,7 @@ #include <hw/hw.h> #include <hw/i386/pc.h> #include <hw/pcmcia.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include <hw/ide/internal.h> @@ -247,7 +247,7 @@ static uint16_t md_common_read(PCMCIACardState *card, uint32_t at) return ide_ioport_read(&s->bus, 0x1); case 0xe: /* Alternate Status */ ifs = idebus_active_if(&s->bus); - if (ifs->bs) { + if (ifs->blk) { return ifs->status; } else { return 0; @@ -332,8 +332,7 @@ static const VMStateDescription vmstate_microdrive = { .name = "microdrive", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(opt, MicroDriveState), VMSTATE_UINT8(stat, MicroDriveState), VMSTATE_UINT8(pins, MicroDriveState), @@ -544,7 +543,6 @@ static int dscm1xxxx_attach(PCMCIACardState *card) device_reset(DEVICE(md)); md_interrupt_update(md); - card->slot->card_string = "DSCM-1xxxx Hitachi Microdrive"; return 0; } @@ -568,7 +566,7 @@ PCMCIACardState *dscm1xxxx_init(DriveInfo *dinfo) } md->bus.ifs[0].drive_kind = IDE_CFATA; md->bus.ifs[0].mdata_size = METADATA_SIZE; - md->bus.ifs[0].mdata_storage = (uint8_t *) g_malloc0(METADATA_SIZE); + md->bus.ifs[0].mdata_storage = g_malloc0(METADATA_SIZE); return PCMCIA_CARD(md); } @@ -594,7 +592,7 @@ static void microdrive_realize(DeviceState *dev, Error **errp) { MicroDriveState *md = MICRODRIVE(dev); - ide_init2(&md->bus, qemu_allocate_irqs(md_set_irq, md, 1)[0]); + ide_init2(&md->bus, qemu_allocate_irq(md_set_irq, md, 0)); } static void microdrive_init(Object *obj) diff --git a/hw/ide/mmio.c b/hw/ide/mmio.c index 9f66a52599..b6ce62ac5a 100644 --- a/hw/ide/mmio.c +++ b/hw/ide/mmio.c @@ -24,7 +24,7 @@ */ #include "hw/hw.h" #include "hw/sysbus.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" #include <hw/ide/internal.h> @@ -82,7 +82,7 @@ static void mmio_ide_write(void *opaque, hwaddr addr, static const MemoryRegionOps mmio_ide_ops = { .read = mmio_ide_read, .write = mmio_ide_write, - .endianness = DEVICE_NATIVE_ENDIAN, + .endianness = DEVICE_LITTLE_ENDIAN, }; static uint64_t mmio_ide_status_read(void *opaque, hwaddr addr, @@ -102,15 +102,14 @@ static void mmio_ide_cmd_write(void *opaque, hwaddr addr, static const MemoryRegionOps mmio_ide_cs_ops = { .read = mmio_ide_status_read, .write = mmio_ide_cmd_write, - .endianness = DEVICE_NATIVE_ENDIAN, + .endianness = DEVICE_LITTLE_ENDIAN, }; static const VMStateDescription vmstate_ide_mmio = { .name = "mmio-ide", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_IDE_BUS(bus, MMIOState), VMSTATE_IDE_DRIVES(bus.ifs, MMIOState), VMSTATE_END_OF_LIST() diff --git a/hw/ide/pci.c b/hw/ide/pci.c index d8b1157c2e..bee5ad39fe 100644 --- a/hw/ide/pci.c +++ b/hw/ide/pci.c @@ -26,15 +26,19 @@ #include <hw/i386/pc.h> #include <hw/pci/pci.h> #include <hw/isa/isa.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/dma.h" - +#include "qemu/error-report.h" #include <hw/ide/pci.h> #define BMDMA_PAGE_SIZE 4096 +#define BM_MIGRATION_COMPAT_STATUS_BITS \ + (IDE_RETRY_DMA | IDE_RETRY_PIO | \ + IDE_RETRY_READ | IDE_RETRY_FLUSH) + static void bmdma_start_dma(IDEDMA *dma, IDEState *s, - BlockDriverCompletionFunc *dma_cb) + BlockCompletionFunc *dma_cb) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); @@ -51,8 +55,11 @@ static void bmdma_start_dma(IDEDMA *dma, IDEState *s, } } -/* return 0 if buffer completed */ -static int bmdma_prepare_buf(IDEDMA *dma, int is_write) +/** + * Return the number of bytes successfully prepared. + * -1 on error. + */ +static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); @@ -70,8 +77,9 @@ static int bmdma_prepare_buf(IDEDMA *dma, int is_write) if (bm->cur_prd_len == 0) { /* end of table (with a fail safe of one page) */ if (bm->cur_prd_last || - (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) - return s->io_buffer_size != 0; + (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) { + return s->io_buffer_size; + } pci_dma_read(pci_dev, bm->cur_addr, &prd, 8); bm->cur_addr += 8; prd.addr = le32_to_cpu(prd.addr); @@ -86,12 +94,23 @@ static int bmdma_prepare_buf(IDEDMA *dma, int is_write) l = bm->cur_prd_len; if (l > 0) { qemu_sglist_add(&s->sg, bm->cur_prd_addr, l); + + /* Note: We limit the max transfer to be 2GiB. + * This should accommodate the largest ATA transaction + * for LBA48 (65,536 sectors) and 32K sector sizes. */ + if (s->sg.size > INT32_MAX) { + error_report("IDE: sglist describes more than 2GiB.\n"); + break; + } bm->cur_prd_addr += l; bm->cur_prd_len -= l; s->io_buffer_size += l; } } - return 1; + + qemu_sglist_destroy(&s->sg); + s->io_buffer_size = 0; + return -1; } /* return 0 if buffer completed */ @@ -152,23 +171,17 @@ static int bmdma_set_unit(IDEDMA *dma, int unit) return 0; } -static int bmdma_add_status(IDEDMA *dma, int status) -{ - BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); - bm->status |= status; - - return 0; -} - -static int bmdma_set_inactive(IDEDMA *dma) +static void bmdma_set_inactive(IDEDMA *dma, bool more) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); - bm->status &= ~BM_STATUS_DMAING; bm->dma_cb = NULL; bm->unit = -1; - - return 0; + if (more) { + bm->status |= BM_STATUS_DMAING; + } else { + bm->status &= ~BM_STATUS_DMAING; + } } static void bmdma_restart_dma(BMDMAState *bm, enum ide_dma_cmd dma_cmd) @@ -200,7 +213,7 @@ static void bmdma_restart_bh(void *opaque) return; } - is_read = (bus->error_status & BM_STATUS_RETRY_READ) != 0; + is_read = (bus->error_status & IDE_RETRY_READ) != 0; /* The error status must be cleared before resubmitting the request: The * request may fail again, and this case can only be distinguished if the @@ -208,19 +221,19 @@ static void bmdma_restart_bh(void *opaque) error_status = bus->error_status; bus->error_status = 0; - if (error_status & BM_STATUS_DMA_RETRY) { - if (error_status & BM_STATUS_RETRY_TRIM) { + if (error_status & IDE_RETRY_DMA) { + if (error_status & IDE_RETRY_TRIM) { bmdma_restart_dma(bm, IDE_DMA_TRIM); } else { bmdma_restart_dma(bm, is_read ? IDE_DMA_READ : IDE_DMA_WRITE); } - } else if (error_status & BM_STATUS_PIO_RETRY) { + } else if (error_status & IDE_RETRY_PIO) { if (is_read) { ide_sector_read(bmdma_active_if(bm)); } else { ide_sector_write(bmdma_active_if(bm)); } - } else if (error_status & BM_STATUS_RETRY_FLUSH) { + } else if (error_status & IDE_RETRY_FLUSH) { ide_flush_cache(bmdma_active_if(bm)); } } @@ -243,11 +256,11 @@ static void bmdma_cancel(BMDMAState *bm) { if (bm->status & BM_STATUS_DMAING) { /* cancel DMA request */ - bmdma_set_inactive(&bm->dma); + bmdma_set_inactive(&bm->dma, false); } } -static int bmdma_reset(IDEDMA *dma) +static void bmdma_reset(IDEDMA *dma) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); @@ -264,13 +277,6 @@ static int bmdma_reset(IDEDMA *dma) bm->cur_prd_len = 0; bm->sector_num = 0; bm->nsector = 0; - - return 0; -} - -static int bmdma_start_transfer(IDEDMA *dma) -{ - return 0; } static void bmdma_irq(void *opaque, int n, int level) @@ -311,7 +317,7 @@ void bmdma_cmd_writeb(BMDMAState *bm, uint32_t val) * aio operation with preadv/pwritev. */ if (bm->bus->dma->aiocb) { - bdrv_drain_all(); + blk_drain_all(); assert(bm->bus->dma->aiocb == NULL); } bm->status &= ~BM_STATUS_DMAING; @@ -411,8 +417,7 @@ static const VMStateDescription vmstate_bmdma_current = { .name = "ide bmdma_current", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(cur_addr, BMDMAState), VMSTATE_UINT32(cur_prd_last, BMDMAState), VMSTATE_UINT32(cur_prd_addr, BMDMAState), @@ -425,8 +430,7 @@ static const VMStateDescription vmstate_bmdma_status = { .name ="ide bmdma/status", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(status, BMDMAState), VMSTATE_END_OF_LIST() } @@ -436,9 +440,8 @@ static const VMStateDescription vmstate_bmdma = { .name = "ide bmdma", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = ide_bmdma_pre_save, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(cmd, BMDMAState), VMSTATE_UINT8(migration_compat_status, BMDMAState), VMSTATE_UINT32(addr, BMDMAState), @@ -479,9 +482,8 @@ const VMStateDescription vmstate_ide_pci = { .name = "ide", .version_id = 3, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = ide_pci_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PCIIDEState), VMSTATE_STRUCT_ARRAY(bmdma, PCIIDEState, 2, 0, vmstate_bmdma, BMDMAState), @@ -508,11 +510,9 @@ void pci_ide_create_devs(PCIDevice *dev, DriveInfo **hd_table) static const struct IDEDMAOps bmdma_ops = { .start_dma = bmdma_start_dma, - .start_transfer = bmdma_start_transfer, .prepare_buf = bmdma_prepare_buf, .rw_buf = bmdma_rw_buf, .set_unit = bmdma_set_unit, - .add_status = bmdma_add_status, .set_inactive = bmdma_set_inactive, .restart_cb = bmdma_restart_cb, .reset = bmdma_reset, diff --git a/hw/ide/pci.h b/hw/ide/pci.h index 2428275c8d..2e9314ad87 100644 --- a/hw/ide/pci.h +++ b/hw/ide/pci.h @@ -3,6 +3,13 @@ #include <hw/ide/internal.h> +#define BM_STATUS_DMAING 0x01 +#define BM_STATUS_ERROR 0x02 +#define BM_STATUS_INT 0x04 + +#define BM_CMD_START 0x01 +#define BM_CMD_READ 0x08 + typedef struct BMDMAState { IDEDMA dma; uint8_t cmd; @@ -16,7 +23,7 @@ typedef struct BMDMAState { uint32_t cur_prd_addr; uint32_t cur_prd_len; uint8_t unit; - BlockDriverCompletionFunc *dma_cb; + BlockCompletionFunc *dma_cb; int64_t sector_num; uint32_t nsector; MemoryRegion addr_ioport; diff --git a/hw/ide/piix.c b/hw/ide/piix.c index 40757eb001..b0172fbf59 100644 --- a/hw/ide/piix.c +++ b/hw/ide/piix.c @@ -27,7 +27,7 @@ #include <hw/i386/pc.h> #include <hw/pci/pci.h> #include <hw/isa/isa.h> -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "sysemu/dma.h" @@ -171,20 +171,20 @@ int pci_piix3_xen_ide_unplug(DeviceState *dev) { PCIIDEState *pci_ide; DriveInfo *di; - int i = 0; + int i; pci_ide = PCI_IDE(dev); - for (; i < 3; i++) { + for (i = 0; i < 4; i++) { di = drive_get_by_index(IF_IDE, i); if (di != NULL && !di->media_cd) { - DeviceState *ds = bdrv_get_attached_dev(di->bdrv); + BlockBackend *blk = blk_by_legacy_dinfo(di); + DeviceState *ds = blk_get_attached_dev(blk); if (ds) { - bdrv_detach_dev(di->bdrv, ds); + blk_detach_dev(blk, ds); } - bdrv_close(di->bdrv); - pci_ide->bus[di->bus].ifs[di->unit].bs = NULL; - drive_put_ref(di); + pci_ide->bus[di->bus].ifs[di->unit].blk = NULL; + blk_unref(blk); } } qdev_reset_all(DEVICE(dev)); @@ -207,11 +207,8 @@ static void pci_piix_ide_exitfn(PCIDevice *dev) for (i = 0; i < 2; ++i) { memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].extra_io); - memory_region_destroy(&d->bmdma[i].extra_io); memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].addr_ioport); - memory_region_destroy(&d->bmdma[i].addr_ioport); } - memory_region_destroy(&d->bmdma_bar); } /* hd_table must contain 4 block drivers */ diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c index 6e475e6970..b4f096e12e 100644 --- a/hw/ide/qdev.c +++ b/hw/ide/qdev.c @@ -20,9 +20,11 @@ #include "sysemu/dma.h" #include "qemu/error-report.h" #include <hw/ide/internal.h> +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/block/block.h" #include "sysemu/sysemu.h" +#include "qapi/visitor.h" /* --------------------------------- */ @@ -59,7 +61,7 @@ static char *idebus_get_fw_dev_path(DeviceState *dev) { char path[30]; - snprintf(path, sizeof(path), "%s@%d", qdev_fw_name(dev), + snprintf(path, sizeof(path), "%s@%x", qdev_fw_name(dev), ((IDEBus*)dev->parent_bus)->bus_id); return g_strdup(path); @@ -71,7 +73,7 @@ static int ide_qdev_init(DeviceState *qdev) IDEDeviceClass *dc = IDE_DEVICE_GET_CLASS(dev); IDEBus *bus = DO_UPCAST(IDEBus, qbus, qdev->parent_bus); - if (!dev->conf.bs) { + if (!dev->conf.blk) { error_report("No drive specified"); goto err; } @@ -116,7 +118,7 @@ IDEDevice *ide_create_drive(IDEBus *bus, int unit, DriveInfo *drive) dev = qdev_create(&bus->qbus, drive->media_cd ? "ide-cd" : "ide-hd"); qdev_prop_set_uint32(dev, "unit", unit); - qdev_prop_set_drive_nofail(dev, "drive", drive->bdrv); + qdev_prop_set_drive_nofail(dev, "drive", blk_by_legacy_dinfo(drive)); qdev_init_nofail(dev); return DO_UPCAST(IDEDevice, qdev, dev); } @@ -126,7 +128,7 @@ int ide_get_geometry(BusState *bus, int unit, { IDEState *s = &DO_UPCAST(IDEBus, qbus, bus)->ifs[unit]; - if (s->drive_kind != IDE_HD || !s->bs) { + if (s->drive_kind != IDE_HD || !s->blk) { return -1; } @@ -151,6 +153,7 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind) { IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus); IDEState *s = bus->ifs + dev->unit; + Error *err = NULL; if (dev->conf.discard_granularity == -1) { dev->conf.discard_granularity = 512; @@ -161,12 +164,16 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind) } blkconf_serial(&dev->conf, &dev->serial); - if (kind != IDE_CD - && blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255) < 0) { - return -1; + if (kind != IDE_CD) { + blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255, &err); + if (err) { + error_report("%s", error_get_pretty(err)); + error_free(err); + return -1; + } } - if (ide_init_drive(s, dev->conf.bs, kind, + if (ide_init_drive(s, dev->conf.blk, kind, dev->version, dev->serial, dev->model, dev->wwn, dev->conf.cyls, dev->conf.heads, dev->conf.secs, dev->chs_trans) < 0) { @@ -186,6 +193,51 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind) return 0; } +static void ide_dev_get_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + IDEDevice *d = IDE_DEVICE(obj); + + visit_type_int32(v, &d->conf.bootindex, name, errp); +} + +static void ide_dev_set_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + IDEDevice *d = IDE_DEVICE(obj); + int32_t boot_index; + Error *local_err = NULL; + + visit_type_int32(v, &boot_index, name, &local_err); + if (local_err) { + goto out; + } + /* check whether bootindex is present in fw_boot_order list */ + check_boot_index(boot_index, &local_err); + if (local_err) { + goto out; + } + /* change bootindex to a new one */ + d->conf.bootindex = boot_index; + + if (d->unit != -1) { + add_boot_device_path(d->conf.bootindex, &d->qdev, + d->unit ? "/disk@1" : "/disk@0"); + } +out: + if (local_err) { + error_propagate(errp, local_err); + } +} + +static void ide_dev_instance_init(Object *obj) +{ + object_property_add(obj, "bootindex", "int32", + ide_dev_get_bootindex, + ide_dev_set_bootindex, NULL, NULL, NULL); + object_property_set_int(obj, -1, "bootindex", NULL); +} + static int ide_hd_initfn(IDEDevice *dev) { return ide_dev_initfn(dev, IDE_HD); @@ -198,9 +250,9 @@ static int ide_cd_initfn(IDEDevice *dev) static int ide_drive_initfn(IDEDevice *dev) { - DriveInfo *dinfo = drive_get_by_blockdev(dev->conf.bs); + DriveInfo *dinfo = blk_legacy_dinfo(dev->conf.blk); - return ide_dev_initfn(dev, dinfo->media_cd ? IDE_CD : IDE_HD); + return ide_dev_initfn(dev, dinfo && dinfo->media_cd ? IDE_CD : IDE_HD); } #define DEFINE_IDE_DEV_PROPERTIES() \ @@ -295,6 +347,7 @@ static const TypeInfo ide_device_type_info = { .abstract = true, .class_size = sizeof(IDEDeviceClass), .class_init = ide_device_class_init, + .instance_init = ide_dev_instance_init, }; static void ide_register_types(void) diff --git a/hw/ide/via.c b/hw/ide/via.c index 198123b026..4d8089de75 100644 --- a/hw/ide/via.c +++ b/hw/ide/via.c @@ -27,7 +27,7 @@ #include <hw/i386/pc.h> #include <hw/pci/pci.h> #include <hw/isa/isa.h> -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "sysemu/dma.h" @@ -198,11 +198,8 @@ static void vt82c686b_ide_exitfn(PCIDevice *dev) for (i = 0; i < 2; ++i) { memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].extra_io); - memory_region_destroy(&d->bmdma[i].extra_io); memory_region_del_subregion(&d->bmdma_bar, &d->bmdma[i].addr_ioport); - memory_region_destroy(&d->bmdma[i].addr_ioport); } - memory_region_destroy(&d->bmdma_bar); } void vt82c686b_ide_init(PCIBus *bus, DriveInfo **hd_table, int devfn) diff --git a/hw/input/adb.c b/hw/input/adb.c index a75d3fd7b9..34c8058fc2 100644 --- a/hw/input/adb.c +++ b/hw/input/adb.c @@ -303,8 +303,7 @@ static const VMStateDescription vmstate_adb_kbd = { .name = "adb_kbd", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BUFFER(data, KBDState), VMSTATE_INT32(rptr, KBDState), VMSTATE_INT32(wptr, KBDState), @@ -518,8 +517,7 @@ static const VMStateDescription vmstate_adb_mouse = { .name = "adb_mouse", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(buttons_state, MouseState), VMSTATE_INT32(last_buttons_state, MouseState), VMSTATE_INT32(dx, MouseState), diff --git a/hw/input/hid.c b/hw/input/hid.c index bb0fa6a619..148c003bb2 100644 --- a/hw/input/hid.c +++ b/hw/input/hid.c @@ -105,70 +105,135 @@ void hid_set_next_idle(HIDState *hs) } } -static void hid_pointer_event_clear(HIDPointerEvent *e, int buttons) +static void hid_pointer_event(DeviceState *dev, QemuConsole *src, + InputEvent *evt) { - e->xdx = e->ydy = e->dz = 0; - e->buttons_state = buttons; -} + static const int bmap[INPUT_BUTTON_MAX] = { + [INPUT_BUTTON_LEFT] = 0x01, + [INPUT_BUTTON_RIGHT] = 0x02, + [INPUT_BUTTON_MIDDLE] = 0x04, + }; + HIDState *hs = (HIDState *)dev; + HIDPointerEvent *e; -static void hid_pointer_event_combine(HIDPointerEvent *e, int xyrel, - int x1, int y1, int z1) { - if (xyrel) { - e->xdx += x1; - e->ydy += y1; - } else { - e->xdx = x1; - e->ydy = y1; - /* Windows drivers do not like the 0/0 position and ignore such - * events. */ - if (!(x1 | y1)) { - e->xdx = 1; + assert(hs->n < QUEUE_LENGTH); + e = &hs->ptr.queue[(hs->head + hs->n) & QUEUE_MASK]; + + switch (evt->kind) { + case INPUT_EVENT_KIND_REL: + if (evt->rel->axis == INPUT_AXIS_X) { + e->xdx += evt->rel->value; + } else if (evt->rel->axis == INPUT_AXIS_Y) { + e->ydy += evt->rel->value; + } + break; + + case INPUT_EVENT_KIND_ABS: + if (evt->rel->axis == INPUT_AXIS_X) { + e->xdx = evt->rel->value; + } else if (evt->rel->axis == INPUT_AXIS_Y) { + e->ydy = evt->rel->value; } + break; + + case INPUT_EVENT_KIND_BTN: + if (evt->btn->down) { + e->buttons_state |= bmap[evt->btn->button]; + if (evt->btn->button == INPUT_BUTTON_WHEEL_UP) { + e->dz--; + } else if (evt->btn->button == INPUT_BUTTON_WHEEL_DOWN) { + e->dz++; + } + } else { + e->buttons_state &= ~bmap[evt->btn->button]; + } + break; + + default: + /* keep gcc happy */ + break; } - e->dz += z1; + } -static void hid_pointer_event(void *opaque, - int x1, int y1, int z1, int buttons_state) +static void hid_pointer_sync(DeviceState *dev) { - HIDState *hs = opaque; - unsigned use_slot = (hs->head + hs->n - 1) & QUEUE_MASK; - unsigned previous_slot = (use_slot - 1) & QUEUE_MASK; - - /* We combine events where feasible to keep the queue small. We shouldn't - * combine anything with the first event of a particular button state, as - * that would change the location of the button state change. When the - * queue is empty, a second event is needed because we don't know if - * the first event changed the button state. */ - if (hs->n == QUEUE_LENGTH) { - /* Queue full. Discard old button state, combine motion normally. */ - hs->ptr.queue[use_slot].buttons_state = buttons_state; - } else if (hs->n < 2 || - hs->ptr.queue[use_slot].buttons_state != buttons_state || - hs->ptr.queue[previous_slot].buttons_state != - hs->ptr.queue[use_slot].buttons_state) { - /* Cannot or should not combine, so add an empty item to the queue. */ - QUEUE_INCR(use_slot); + HIDState *hs = (HIDState *)dev; + HIDPointerEvent *prev, *curr, *next; + bool event_compression = false; + + if (hs->n == QUEUE_LENGTH-1) { + /* + * Queue full. We are losing information, but we at least + * keep track of most recent button state. + */ + return; + } + + prev = &hs->ptr.queue[(hs->head + hs->n - 1) & QUEUE_MASK]; + curr = &hs->ptr.queue[(hs->head + hs->n) & QUEUE_MASK]; + next = &hs->ptr.queue[(hs->head + hs->n + 1) & QUEUE_MASK]; + + if (hs->n > 0) { + /* + * No button state change between previous and current event + * (and previous wasn't seen by the guest yet), so there is + * motion information only and we can combine the two event + * into one. + */ + if (curr->buttons_state == prev->buttons_state) { + event_compression = true; + } + } + + if (event_compression) { + /* add current motion to previous, clear current */ + if (hs->kind == HID_MOUSE) { + prev->xdx += curr->xdx; + curr->xdx = 0; + prev->ydy += curr->ydy; + curr->ydy = 0; + } else { + prev->xdx = curr->xdx; + prev->ydy = curr->ydy; + } + prev->dz += curr->dz; + curr->dz = 0; + } else { + /* prepate next (clear rel, copy abs + btns) */ + if (hs->kind == HID_MOUSE) { + next->xdx = 0; + next->ydy = 0; + } else { + next->xdx = curr->xdx; + next->ydy = curr->ydy; + } + next->dz = 0; + next->buttons_state = curr->buttons_state; + /* make current guest visible, notify guest */ hs->n++; - hid_pointer_event_clear(&hs->ptr.queue[use_slot], buttons_state); + hs->event(hs); } - hid_pointer_event_combine(&hs->ptr.queue[use_slot], - hs->kind == HID_MOUSE, - x1, y1, z1); - hs->event(hs); } -static void hid_keyboard_event(void *opaque, int keycode) +static void hid_keyboard_event(DeviceState *dev, QemuConsole *src, + InputEvent *evt) { - HIDState *hs = opaque; + HIDState *hs = (HIDState *)dev; + int scancodes[3], i, count; int slot; - if (hs->n == QUEUE_LENGTH) { + count = qemu_input_key_value_to_scancode(evt->key->key, + evt->key->down, + scancodes); + if (hs->n + count > QUEUE_LENGTH) { fprintf(stderr, "usb-kbd: warning: key event queue full\n"); return; } - slot = (hs->head + hs->n) & QUEUE_MASK; hs->n++; - hs->kbd.keycodes[slot] = keycode; + for (i = 0; i < count; i++) { + slot = (hs->head + hs->n) & QUEUE_MASK; hs->n++; + hs->kbd.keycodes[slot] = scancodes[i]; + } hs->event(hs); } @@ -247,14 +312,14 @@ static inline int int_clamp(int val, int vmin, int vmax) void hid_pointer_activate(HIDState *hs) { if (!hs->ptr.mouse_grabbed) { - qemu_activate_mouse_event_handler(hs->ptr.eh_entry); + qemu_input_handler_activate(hs->s); hs->ptr.mouse_grabbed = 1; } } int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len) { - int dx, dy, dz, b, l; + int dx, dy, dz, l; int index; HIDPointerEvent *e; @@ -279,17 +344,6 @@ int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len) dz = int_clamp(e->dz, -127, 127); e->dz -= dz; - b = 0; - if (e->buttons_state & MOUSE_EVENT_LBUTTON) { - b |= 0x01; - } - if (e->buttons_state & MOUSE_EVENT_RBUTTON) { - b |= 0x02; - } - if (e->buttons_state & MOUSE_EVENT_MBUTTON) { - b |= 0x04; - } - if (hs->n && !e->dz && (hs->kind == HID_TABLET || (!e->xdx && !e->ydy))) { @@ -304,7 +358,7 @@ int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len) switch (hs->kind) { case HID_MOUSE: if (len > l) { - buf[l++] = b; + buf[l++] = e->buttons_state; } if (len > l) { buf[l++] = dx; @@ -319,7 +373,7 @@ int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len) case HID_TABLET: if (len > l) { - buf[l++] = b; + buf[l++] = e->buttons_state; } if (len > l) { buf[l++] = dx & 0xff; @@ -413,31 +467,45 @@ void hid_reset(HIDState *hs) void hid_free(HIDState *hs) { - switch (hs->kind) { - case HID_KEYBOARD: - qemu_remove_kbd_event_handler(hs->kbd.eh_entry); - break; - case HID_MOUSE: - case HID_TABLET: - qemu_remove_mouse_event_handler(hs->ptr.eh_entry); - break; - } + qemu_input_handler_unregister(hs->s); hid_del_idle_timer(hs); } +static QemuInputHandler hid_keyboard_handler = { + .name = "QEMU HID Keyboard", + .mask = INPUT_EVENT_MASK_KEY, + .event = hid_keyboard_event, +}; + +static QemuInputHandler hid_mouse_handler = { + .name = "QEMU HID Mouse", + .mask = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_REL, + .event = hid_pointer_event, + .sync = hid_pointer_sync, +}; + +static QemuInputHandler hid_tablet_handler = { + .name = "QEMU HID Tablet", + .mask = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_ABS, + .event = hid_pointer_event, + .sync = hid_pointer_sync, +}; + void hid_init(HIDState *hs, int kind, HIDEventFunc event) { hs->kind = kind; hs->event = event; if (hs->kind == HID_KEYBOARD) { - hs->kbd.eh_entry = qemu_add_kbd_event_handler(hid_keyboard_event, hs); + hs->s = qemu_input_handler_register((DeviceState *)hs, + &hid_keyboard_handler); + qemu_input_handler_activate(hs->s); } else if (hs->kind == HID_MOUSE) { - hs->ptr.eh_entry = qemu_add_mouse_event_handler(hid_pointer_event, hs, - 0, "QEMU HID Mouse"); + hs->s = qemu_input_handler_register((DeviceState *)hs, + &hid_mouse_handler); } else if (hs->kind == HID_TABLET) { - hs->ptr.eh_entry = qemu_add_mouse_event_handler(hid_pointer_event, hs, - 1, "QEMU HID Tablet"); + hs->s = qemu_input_handler_register((DeviceState *)hs, + &hid_tablet_handler); } } diff --git a/hw/input/lm832x.c b/hw/input/lm832x.c index 4ae1cd9c80..9eb68e87cb 100644 --- a/hw/input/lm832x.c +++ b/hw/input/lm832x.c @@ -432,9 +432,8 @@ static const VMStateDescription vmstate_lm_kbd = { .name = "LM8323", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = lm_kbd_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_I2C_SLAVE(parent_obj, LM823KbdState), VMSTATE_UINT8(i2c_dir, LM823KbdState), VMSTATE_UINT8(i2c_cycle, LM823KbdState), diff --git a/hw/input/milkymist-softusb.c b/hw/input/milkymist-softusb.c index ecde33cb95..5a427f0b33 100644 --- a/hw/input/milkymist-softusb.c +++ b/hw/input/milkymist-softusb.c @@ -156,31 +156,6 @@ static inline void softusb_write_dmem(MilkymistSoftUsbState *s, memcpy(s->dmem_ptr + offset, buf, len); } -static inline void softusb_read_pmem(MilkymistSoftUsbState *s, - uint32_t offset, uint8_t *buf, uint32_t len) -{ - if (offset + len >= s->pmem_size) { - error_report("milkymist_softusb: read pmem out of bounds " - "at offset 0x%x, len %d", offset, len); - memset(buf, 0, len); - return; - } - - memcpy(buf, s->pmem_ptr + offset, len); -} - -static inline void softusb_write_pmem(MilkymistSoftUsbState *s, - uint32_t offset, uint8_t *buf, uint32_t len) -{ - if (offset + len >= s->pmem_size) { - error_report("milkymist_softusb: write pmem out of bounds " - "at offset 0x%x, len %d", offset, len); - return; - } - - memcpy(s->pmem_ptr + offset, buf, len); -} - static void softusb_mouse_changed(MilkymistSoftUsbState *s) { uint8_t m; @@ -275,12 +250,12 @@ static int milkymist_softusb_init(SysBusDevice *dev) /* register pmem and dmem */ memory_region_init_ram(&s->pmem, OBJECT(s), "milkymist-softusb.pmem", - s->pmem_size); + s->pmem_size, &error_abort); vmstate_register_ram_global(&s->pmem); s->pmem_ptr = memory_region_get_ram_ptr(&s->pmem); sysbus_init_mmio(dev, &s->pmem); memory_region_init_ram(&s->dmem, OBJECT(s), "milkymist-softusb.dmem", - s->dmem_size); + s->dmem_size, &error_abort); vmstate_register_ram_global(&s->dmem); s->dmem_ptr = memory_region_get_ram_ptr(&s->dmem); sysbus_init_mmio(dev, &s->dmem); @@ -295,8 +270,7 @@ static const VMStateDescription vmstate_milkymist_softusb = { .name = "milkymist-softusb", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistSoftUsbState, R_MAX), VMSTATE_HID_KEYBOARD_DEVICE(hid_kbd, MilkymistSoftUsbState), VMSTATE_HID_POINTER_DEVICE(hid_mouse, MilkymistSoftUsbState), diff --git a/hw/input/pckbd.c b/hw/input/pckbd.c index 29af3d741f..2b0cd3dbb8 100644 --- a/hw/input/pckbd.c +++ b/hw/input/pckbd.c @@ -131,6 +131,7 @@ typedef struct KBDState { uint8_t status; uint8_t mode; uint8_t outport; + bool outport_present; /* Bitmask of devices with data available. */ uint8_t pending; void *kbd; @@ -229,7 +230,7 @@ static void kbd_write_command(void *opaque, hwaddr addr, { KBDState *s = opaque; - DPRINTF("kbd: write cmd=0x%02x\n", val); + DPRINTF("kbd: write cmd=0x%02" PRIx64 "\n", val); /* Bits 3-0 of the output port P2 of the keyboard controller may be pulsed * low for approximately 6 micro seconds. Bits 3-0 of the KBD_CCMD_PULSE @@ -330,7 +331,7 @@ static void kbd_write_data(void *opaque, hwaddr addr, { KBDState *s = opaque; - DPRINTF("kbd: write data=0x%02x\n", val); + DPRINTF("kbd: write data=0x%02" PRIx64 "\n", val); switch(s->write_cmd) { case 0: @@ -367,19 +368,68 @@ static void kbd_reset(void *opaque) s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT; s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED; s->outport = KBD_OUT_RESET | KBD_OUT_A20; + s->outport_present = false; +} + +static uint8_t kbd_outport_default(KBDState *s) +{ + return KBD_OUT_RESET | KBD_OUT_A20 + | (s->status & KBD_STAT_OBF ? KBD_OUT_OBF : 0) + | (s->status & KBD_STAT_MOUSE_OBF ? KBD_OUT_MOUSE_OBF : 0); +} + +static int kbd_outport_post_load(void *opaque, int version_id) +{ + KBDState *s = opaque; + s->outport_present = true; + return 0; +} + +static const VMStateDescription vmstate_kbd_outport = { + .name = "pckbd_outport", + .version_id = 1, + .minimum_version_id = 1, + .post_load = kbd_outport_post_load, + .fields = (VMStateField[]) { + VMSTATE_UINT8(outport, KBDState), + VMSTATE_END_OF_LIST() + } +}; + +static bool kbd_outport_needed(void *opaque) +{ + KBDState *s = opaque; + return s->outport != kbd_outport_default(s); +} + +static int kbd_post_load(void *opaque, int version_id) +{ + KBDState *s = opaque; + if (!s->outport_present) { + s->outport = kbd_outport_default(s); + } + s->outport_present = false; + return 0; } static const VMStateDescription vmstate_kbd = { .name = "pckbd", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .post_load = kbd_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT8(write_cmd, KBDState), VMSTATE_UINT8(status, KBDState), VMSTATE_UINT8(mode, KBDState), VMSTATE_UINT8(pending, KBDState), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_kbd_outport, + .needed = kbd_outport_needed, + }, + VMSTATE_END_OF_LIST() } }; @@ -462,8 +512,7 @@ static const VMStateDescription vmstate_kbd_isa = { .name = "pckbd", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(kbd, ISAKBDState, 0, vmstate_kbd, KBDState), VMSTATE_END_OF_LIST() } diff --git a/hw/input/ps2.c b/hw/input/ps2.c index 8d1731cf79..dff3c82055 100644 --- a/hw/input/ps2.c +++ b/hw/input/ps2.c @@ -24,6 +24,7 @@ #include "hw/hw.h" #include "hw/input/ps2.h" #include "ui/console.h" +#include "ui/input.h" #include "sysemu/sysemu.h" #ifdef CONFIG_MARU @@ -76,10 +77,12 @@ static QemuMutex mutex; #define MOUSE_STATUS_ENABLED 0x20 #define MOUSE_STATUS_SCALE21 0x10 -#define PS2_QUEUE_SIZE 256 +#define PS2_QUEUE_SIZE 16 /* Buffer size required by PS/2 protocol */ typedef struct { - uint8_t data[PS2_QUEUE_SIZE]; + /* Keep the data array 256 bytes long, which compatibility + with older qemu versions. */ + uint8_t data[256]; int rptr, wptr, count; } PS2Queue; @@ -142,7 +145,7 @@ void ps2_queue(void *opaque, int b) PS2State *s = (PS2State *)opaque; PS2Queue *q = &s->queue; - if (q->count >= PS2_QUEUE_SIZE) + if (q->count >= PS2_QUEUE_SIZE - 1) return; q->data[q->wptr] = b; if (++q->wptr == PS2_QUEUE_SIZE) @@ -175,6 +178,21 @@ static void ps2_put_keycode(void *opaque, int keycode) ps2_queue(&s->common, keycode); } +static void ps2_keyboard_event(DeviceState *dev, QemuConsole *src, + InputEvent *evt) +{ + PS2KbdState *s = (PS2KbdState *)dev; + int scancodes[3], i, count; + + qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER); + count = qemu_input_key_value_to_scancode(evt->key->key, + evt->key->down, + scancodes); + for (i = 0; i < count; i++) { + ps2_put_keycode(s, scancodes[i]); + } +} + uint32_t ps2_read_data(void *opaque) { PS2State *s = (PS2State *)opaque; @@ -357,31 +375,57 @@ static void ps2_mouse_send_packet(PS2MouseState *s) s->mouse_dz -= dz1; } -static void ps2_mouse_event(void *opaque, - int dx, int dy, int dz, int buttons_state) +static void ps2_mouse_event(DeviceState *dev, QemuConsole *src, + InputEvent *evt) { - PS2MouseState *s = opaque; + static const int bmap[INPUT_BUTTON_MAX] = { + [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON, + [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON, + [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON, + }; + PS2MouseState *s = (PS2MouseState *)dev; /* check if deltas are recorded when disabled */ if (!(s->mouse_status & MOUSE_STATUS_ENABLED)) return; - s->mouse_dx += dx; - s->mouse_dy -= dy; - s->mouse_dz += dz; - /* XXX: SDL sometimes generates nul events: we delete them */ - if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 && - s->mouse_buttons == buttons_state) - return; - s->mouse_buttons = buttons_state; + switch (evt->kind) { + case INPUT_EVENT_KIND_REL: + if (evt->rel->axis == INPUT_AXIS_X) { + s->mouse_dx += evt->rel->value; + } else if (evt->rel->axis == INPUT_AXIS_Y) { + s->mouse_dy -= evt->rel->value; + } + break; - if (buttons_state) { - qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER); + case INPUT_EVENT_KIND_BTN: + if (evt->btn->down) { + s->mouse_buttons |= bmap[evt->btn->button]; + if (evt->btn->button == INPUT_BUTTON_WHEEL_UP) { + s->mouse_dz--; + } else if (evt->btn->button == INPUT_BUTTON_WHEEL_DOWN) { + s->mouse_dz++; + } + } else { + s->mouse_buttons &= ~bmap[evt->btn->button]; + } + break; + + default: + /* keep gcc happy */ + break; } +} - if (!(s->mouse_status & MOUSE_STATUS_REMOTE) && - (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) { - for(;;) { +static void ps2_mouse_sync(DeviceState *dev) +{ + PS2MouseState *s = (PS2MouseState *)dev; + + if (s->mouse_buttons) { + qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER); + } + if (!(s->mouse_status & MOUSE_STATUS_REMOTE)) { + while (s->common.queue.count < PS2_QUEUE_SIZE - 4) { /* if not remote, send event. Multiple events are sent if too big deltas */ #ifdef CONFIG_MARU @@ -400,7 +444,9 @@ static void ps2_mouse_event(void *opaque, void ps2_mouse_fake_event(void *opaque) { - ps2_mouse_event(opaque, 1, 0, 0, 0); + PS2MouseState *s = opaque; + s->mouse_dx++; + ps2_mouse_sync(opaque); } void ps2_write_mouse(void *opaque, int val) @@ -540,6 +586,34 @@ static void ps2_common_reset(PS2State *s) s->update_irq(s->update_arg, 0); } +static void ps2_common_post_load(PS2State *s) +{ + PS2Queue *q = &s->queue; + int size; + int i; + int tmp_data[PS2_QUEUE_SIZE]; + + /* set the useful data buffer queue size, < PS2_QUEUE_SIZE */ + size = q->count > PS2_QUEUE_SIZE ? 0 : q->count; + + /* move the queue elements to the start of data array */ + if (size > 0) { + for (i = 0; i < size; i++) { + /* move the queue elements to the temporary buffer */ + tmp_data[i] = q->data[q->rptr]; + if (++q->rptr == 256) { + q->rptr = 0; + } + } + memcpy(q->data, tmp_data, size); + } + /* reset rptr/wptr/count */ + q->rptr = 0; + q->wptr = size; + q->count = size; + s->update_irq(s->update_arg, q->count != 0); +} + static void ps2_kbd_reset(void *opaque) { PS2KbdState *s = (PS2KbdState *) opaque; @@ -571,8 +645,7 @@ static const VMStateDescription vmstate_ps2_common = { .name = "PS2 Common State", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(write_cmd, PS2State), VMSTATE_INT32(queue.rptr, PS2State), VMSTATE_INT32(queue.wptr, PS2State), @@ -601,9 +674,8 @@ static const VMStateDescription vmstate_ps2_keyboard_ledstate = { .name = "ps2kbd/ledstate", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = ps2_kbd_ledstate_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(ledstate, PS2KbdState), VMSTATE_END_OF_LIST() } @@ -612,19 +684,31 @@ static const VMStateDescription vmstate_ps2_keyboard_ledstate = { static int ps2_kbd_post_load(void* opaque, int version_id) { PS2KbdState *s = (PS2KbdState*)opaque; + PS2State *ps2 = &s->common; if (version_id == 2) s->scancode_set=2; + + ps2_common_post_load(ps2); + return 0; } +static void ps2_kbd_pre_save(void *opaque) +{ + PS2KbdState *s = (PS2KbdState *)opaque; + PS2State *ps2 = &s->common; + + ps2_common_post_load(ps2); +} + static const VMStateDescription vmstate_ps2_keyboard = { .name = "ps2kbd", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = ps2_kbd_post_load, - .fields = (VMStateField []) { + .pre_save = ps2_kbd_pre_save, + .fields = (VMStateField[]) { VMSTATE_STRUCT(common, PS2KbdState, 0, vmstate_ps2_common, PS2State), VMSTATE_INT32(scan_enabled, PS2KbdState), VMSTATE_INT32(translate, PS2KbdState), @@ -641,12 +725,31 @@ static const VMStateDescription vmstate_ps2_keyboard = { } }; +static int ps2_mouse_post_load(void *opaque, int version_id) +{ + PS2MouseState *s = (PS2MouseState *)opaque; + PS2State *ps2 = &s->common; + + ps2_common_post_load(ps2); + + return 0; +} + +static void ps2_mouse_pre_save(void *opaque) +{ + PS2MouseState *s = (PS2MouseState *)opaque; + PS2State *ps2 = &s->common; + + ps2_common_post_load(ps2); +} + static const VMStateDescription vmstate_ps2_mouse = { .name = "ps2mouse", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .post_load = ps2_mouse_post_load, + .pre_save = ps2_mouse_pre_save, + .fields = (VMStateField[]) { VMSTATE_STRUCT(common, PS2MouseState, 0, vmstate_ps2_common, PS2State), VMSTATE_UINT8(mouse_status, PS2MouseState), VMSTATE_UINT8(mouse_resolution, PS2MouseState), @@ -662,6 +765,12 @@ static const VMStateDescription vmstate_ps2_mouse = { } }; +static QemuInputHandler ps2_keyboard_handler = { + .name = "QEMU PS/2 Keyboard", + .mask = INPUT_EVENT_MASK_KEY, + .event = ps2_keyboard_event, +}; + void *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg) { PS2KbdState *s = (PS2KbdState *)g_malloc0(sizeof(PS2KbdState)); @@ -670,11 +779,19 @@ void *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg) s->common.update_arg = update_arg; s->scancode_set = 2; vmstate_register(NULL, 0, &vmstate_ps2_keyboard, s); - qemu_add_kbd_event_handler(ps2_put_keycode, s); + qemu_input_handler_register((DeviceState *)s, + &ps2_keyboard_handler); qemu_register_reset(ps2_kbd_reset, s); return s; } +static QemuInputHandler ps2_mouse_handler = { + .name = "QEMU PS/2 Mouse", + .mask = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_REL, + .event = ps2_mouse_event, + .sync = ps2_mouse_sync, +}; + void *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg) { PS2MouseState *s = (PS2MouseState *)g_malloc0(sizeof(PS2MouseState)); @@ -682,7 +799,8 @@ void *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg) s->common.update_irq = update_irq; s->common.update_arg = update_arg; vmstate_register(NULL, 0, &vmstate_ps2_mouse, s); - qemu_add_mouse_event_handler(ps2_mouse_event, s, 0, "QEMU PS/2 Mouse"); + qemu_input_handler_register((DeviceState *)s, + &ps2_mouse_handler); qemu_register_reset(ps2_mouse_reset, s); #ifdef CONFIG_MARU /* to guarantee safe serialization of input event by Munkyu Im */ diff --git a/hw/input/pxa2xx_keypad.c b/hw/input/pxa2xx_keypad.c index b90b0ba102..85011145e6 100644 --- a/hw/input/pxa2xx_keypad.c +++ b/hw/input/pxa2xx_keypad.c @@ -291,8 +291,7 @@ static const VMStateDescription vmstate_pxa2xx_keypad = { .name = "pxa2xx_keypad", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(kpc, PXA2xxKeyPadState), VMSTATE_UINT32(kpdk, PXA2xxKeyPadState), VMSTATE_UINT32(kprec, PXA2xxKeyPadState), diff --git a/hw/input/stellaris_input.c b/hw/input/stellaris_input.c index 4e407922a0..0609e80868 100644 --- a/hw/input/stellaris_input.c +++ b/hw/input/stellaris_input.c @@ -51,8 +51,7 @@ static const VMStateDescription vmstate_stellaris_button = { .name = "stellaris_button", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(pressed, gamepad_button), VMSTATE_END_OF_LIST() } @@ -62,8 +61,7 @@ static const VMStateDescription vmstate_stellaris_gamepad = { .name = "stellaris_gamepad", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(extension, gamepad_state), VMSTATE_STRUCT_VARRAY_INT32(buttons, gamepad_state, num_buttons, 0, vmstate_stellaris_button, gamepad_button), diff --git a/hw/input/tsc210x.c b/hw/input/tsc210x.c index 485c9e5753..fae3385636 100644 --- a/hw/input/tsc210x.c +++ b/hw/input/tsc210x.c @@ -215,36 +215,6 @@ typedef struct { int fsref; } TSC210xRateInfo; -/* { rate, dsor, fsref } */ -static const TSC210xRateInfo tsc2101_rates[] = { - /* Fsref / 6.0 */ - { 7350, 7, 1 }, - { 8000, 7, 0 }, - /* Fsref / 5.5 */ - { 8018, 6, 1 }, - { 8727, 6, 0 }, - /* Fsref / 5.0 */ - { 8820, 5, 1 }, - { 9600, 5, 0 }, - /* Fsref / 4.0 */ - { 11025, 4, 1 }, - { 12000, 4, 0 }, - /* Fsref / 3.0 */ - { 14700, 3, 1 }, - { 16000, 3, 0 }, - /* Fsref / 2.0 */ - { 22050, 2, 1 }, - { 24000, 2, 0 }, - /* Fsref / 1.5 */ - { 29400, 1, 1 }, - { 32000, 1, 0 }, - /* Fsref */ - { 44100, 0, 1 }, - { 48000, 0, 0 }, - - { 0, 0, 0 }, -}; - /* { rate, dsor, fsref } */ static const TSC210xRateInfo tsc2102_rates[] = { /* Fsref / 6.0 */ @@ -1070,9 +1040,21 @@ static int tsc210x_load(QEMUFile *f, void *opaque, int version_id) s->enabled = qemu_get_byte(f); s->host_mode = qemu_get_byte(f); s->function = qemu_get_byte(f); + if (s->function < 0 || s->function >= ARRAY_SIZE(mode_regs)) { + return -EINVAL; + } s->nextfunction = qemu_get_byte(f); + if (s->nextfunction < 0 || s->nextfunction >= ARRAY_SIZE(mode_regs)) { + return -EINVAL; + } s->precision = qemu_get_byte(f); + if (s->precision < 0 || s->precision >= ARRAY_SIZE(resolution)) { + return -EINVAL; + } s->nextprecision = qemu_get_byte(f); + if (s->nextprecision < 0 || s->nextprecision >= ARRAY_SIZE(resolution)) { + return -EINVAL; + } s->filter = qemu_get_byte(f); s->pin_func = qemu_get_byte(f); s->ref = qemu_get_byte(f); diff --git a/hw/input/vmmouse.c b/hw/input/vmmouse.c index 6a5053352a..d7b1c76f58 100644 --- a/hw/input/vmmouse.c +++ b/hw/input/vmmouse.c @@ -240,9 +240,8 @@ static const VMStateDescription vmstate_vmmouse = { .name = "vmmouse", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = vmmouse_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32_EQUAL(queue_size, VMMouseState), VMSTATE_UINT32_ARRAY(queue, VMMouseState, VMMOUSE_QUEUE_SIZE), VMSTATE_UINT16(nb_queue, VMMouseState), diff --git a/hw/intc/Makefile.objs b/hw/intc/Makefile.objs index c8a2318d56..843864a3ef 100644 --- a/hw/intc/Makefile.objs +++ b/hw/intc/Makefile.objs @@ -26,3 +26,4 @@ obj-$(CONFIG_XICS) += xics.o obj-$(CONFIG_XICS_KVM) += xics_kvm.o obj-$(CONFIG_ALLWINNER_A10_PIC) += allwinner-a10-pic.o obj-$(CONFIG_S390_FLIC) += s390_flic.o +obj-$(CONFIG_S390_FLIC_KVM) += s390_flic_kvm.o diff --git a/hw/intc/allwinner-a10-pic.c b/hw/intc/allwinner-a10-pic.c index 407d563514..de820b9723 100644 --- a/hw/intc/allwinner-a10-pic.c +++ b/hw/intc/allwinner-a10-pic.c @@ -23,11 +23,20 @@ static void aw_a10_pic_update(AwA10PICState *s) { uint8_t i; - int irq = 0, fiq = 0; + int irq = 0, fiq = 0, pending; + + s->vector = 0; for (i = 0; i < AW_A10_PIC_REG_NUM; i++) { irq |= s->irq_pending[i] & ~s->mask[i]; fiq |= s->select[i] & s->irq_pending[i] & ~s->mask[i]; + + if (!s->vector) { + pending = ffs(s->irq_pending[i] & ~s->mask[i]); + if (pending) { + s->vector = (i * 32 + pending - 1) * 4; + } + } } qemu_set_irq(s->parent_irq, !!irq); @@ -40,6 +49,8 @@ static void aw_a10_pic_set_irq(void *opaque, int irq, int level) if (level) { set_bit(irq % 32, (void *)&s->irq_pending[irq / 32]); + } else { + clear_bit(irq % 32, (void *)&s->irq_pending[irq / 32]); } aw_a10_pic_update(s); } @@ -84,11 +95,9 @@ static void aw_a10_pic_write(void *opaque, hwaddr offset, uint64_t value, uint8_t index = (offset & 0xc) / 4; switch (offset) { - case AW_A10_PIC_VECTOR: - s->vector = value & ~0x3; - break; case AW_A10_PIC_BASE_ADDR: s->base_addr = value & ~0x3; + break; case AW_A10_PIC_PROTECT: s->protect = value; break; @@ -96,7 +105,11 @@ static void aw_a10_pic_write(void *opaque, hwaddr offset, uint64_t value, s->nmi = value; break; case AW_A10_PIC_IRQ_PENDING ... AW_A10_PIC_IRQ_PENDING + 8: - s->irq_pending[index] &= ~value; + /* + * The register is read-only; nevertheless, Linux (including + * the version originally shipped by Allwinner) pretends to + * write to the register. Just ignore it. + */ break; case AW_A10_PIC_FIQ_PENDING ... AW_A10_PIC_FIQ_PENDING + 8: s->fiq_pending[index] &= ~value; @@ -129,7 +142,6 @@ static const VMStateDescription vmstate_aw_a10_pic = { .name = "a10.pic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(vector, AwA10PICState), VMSTATE_UINT32(base_addr, AwA10PICState), diff --git a/hw/intc/apic.c b/hw/intc/apic.c index b8c061bdaa..0f97b47925 100644 --- a/hw/intc/apic.c +++ b/hw/intc/apic.c @@ -98,8 +98,8 @@ static void apic_sync_vapic(APICCommonState *s, int sync_type) return; } if (sync_type & SYNC_FROM_VAPIC) { - cpu_physical_memory_rw(s->vapic_paddr, (void *)&vapic_state, - sizeof(vapic_state), 0); + cpu_physical_memory_read(s->vapic_paddr, &vapic_state, + sizeof(vapic_state)); s->tpr = vapic_state.tpr; } if (sync_type & (SYNC_TO_VAPIC | SYNC_ISR_IRR_TO_VAPIC)) { @@ -188,7 +188,7 @@ void apic_deliver_pic_intr(DeviceState *dev, int level) apic_reset_bit(s->irr, lvt & 0xff); /* fall through */ case APIC_DM_EXTINT: - cpu_reset_interrupt(CPU(s->cpu), CPU_INTERRUPT_HARD); + apic_update_irq(s); break; } } @@ -349,6 +349,11 @@ static int apic_get_arb_pri(APICCommonState *s) static int apic_irq_pending(APICCommonState *s) { int irrv, ppr; + + if (!(s->spurious_vec & APIC_SV_ENABLE)) { + return 0; + } + irrv = get_highest_priority_int(s->irr); if (irrv < 0) { return 0; @@ -366,14 +371,13 @@ static void apic_update_irq(APICCommonState *s) { CPUState *cpu; - if (!(s->spurious_vec & APIC_SV_ENABLE)) { - return; - } cpu = CPU(s->cpu); if (!qemu_cpu_is_self(cpu)) { cpu_interrupt(cpu, CPU_INTERRUPT_POLL); } else if (apic_irq_pending(s) > 0) { cpu_interrupt(cpu, CPU_INTERRUPT_HARD); + } else if (!apic_accept_pic_intr(&s->busdev.qdev) || !pic_get_output(isa_pic)) { + cpu_reset_interrupt(cpu, CPU_INTERRUPT_HARD); } } @@ -567,7 +571,10 @@ int apic_get_interrupt(DeviceState *dev) apic_sync_vapic(s, SYNC_FROM_VAPIC); intno = apic_irq_pending(s); - if (intno == 0) { + /* if there is an interrupt from the 8259, let the caller handle + * that first since ExtINT interrupts ignore the priority. + */ + if (intno == 0 || apic_check_pic(s)) { apic_sync_vapic(s, SYNC_TO_VAPIC); return -1; } else if (intno < 0) { @@ -578,9 +585,6 @@ int apic_get_interrupt(DeviceState *dev) apic_set_bit(s->isr, intno); apic_sync_vapic(s, SYNC_TO_VAPIC); - /* re-inject if there is still a pending PIC interrupt */ - apic_check_pic(s); - apic_update_irq(s); return intno; @@ -675,7 +679,7 @@ static uint32_t apic_mem_readl(void *opaque, hwaddr addr) val = s->id << 24; break; case 0x03: /* version */ - val = 0x11 | ((APIC_LVT_NB - 1) << 16); /* version 0x11 */ + val = s->version | ((APIC_LVT_NB - 1) << 16); break; case 0x08: apic_sync_vapic(s, SYNC_FROM_VAPIC); @@ -698,7 +702,7 @@ static uint32_t apic_mem_readl(void *opaque, hwaddr addr) val = s->log_dest << 24; break; case 0x0e: - val = s->dest_mode << 28; + val = (s->dest_mode << 28) | 0xfffffff; break; case 0x0f: val = s->spurious_vec; diff --git a/hw/intc/apic_common.c b/hw/intc/apic_common.c index 517cd9a53c..824ea93913 100644 --- a/hw/intc/apic_common.c +++ b/hw/intc/apic_common.c @@ -200,7 +200,7 @@ void apic_init_reset(DeviceState *dev) s->initial_count = 0; s->initial_count_load_time = 0; s->next_time = 0; - s->wait_for_sipi = 1; + s->wait_for_sipi = !cpu_is_bsp(s->cpu); if (s->timer) { timer_del(s->timer); @@ -326,6 +326,19 @@ static void apic_common_realize(DeviceState *dev, Error **errp) } +static int apic_pre_load(void *opaque) +{ + APICCommonState *s = APIC_COMMON(opaque); + + /* The default is !cpu_is_bsp(s->cpu), but the common value is 0 + * so that's what apic_common_sipi_needed checks for. Reset to + * the value that is assumed when the apic_sipi subsection is + * absent. + */ + s->wait_for_sipi = 0; + return 0; +} + static void apic_dispatch_pre_save(void *opaque) { APICCommonState *s = APIC_COMMON(opaque); @@ -347,12 +360,30 @@ static int apic_dispatch_post_load(void *opaque, int version_id) return 0; } +static bool apic_common_sipi_needed(void *opaque) +{ + APICCommonState *s = APIC_COMMON(opaque); + return s->wait_for_sipi != 0; +} + +static const VMStateDescription vmstate_apic_common_sipi = { + .name = "apic_sipi", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT32(sipi_vector, APICCommonState), + VMSTATE_INT32(wait_for_sipi, APICCommonState), + VMSTATE_END_OF_LIST() + } +}; + static const VMStateDescription vmstate_apic_common = { .name = "apic", .version_id = 3, .minimum_version_id = 3, .minimum_version_id_old = 1, .load_state_old = apic_load_old, + .pre_load = apic_pre_load, .pre_save = apic_dispatch_pre_save, .post_load = apic_dispatch_post_load, .fields = (VMStateField[]) { @@ -377,11 +408,19 @@ static const VMStateDescription vmstate_apic_common = { VMSTATE_INT64(timer_expiry, APICCommonState), /* open-coded timer state */ VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_apic_common_sipi, + .needed = apic_common_sipi_needed, + }, + VMSTATE_END_OF_LIST() } }; static Property apic_properties_common[] = { DEFINE_PROP_UINT8("id", APICCommonState, id, -1), + DEFINE_PROP_UINT8("version", APICCommonState, version, 0x14), DEFINE_PROP_BIT("vapic", APICCommonState, vapic_control, VAPIC_ENABLE_BIT, true), DEFINE_PROP_END_OF_LIST(), diff --git a/hw/intc/arm_gic.c b/hw/intc/arm_gic.c index 955b8d4945..270ce05b58 100644 --- a/hw/intc/arm_gic.c +++ b/hw/intc/arm_gic.c @@ -66,7 +66,8 @@ void gic_update(GICState *s) best_prio = 0x100; best_irq = 1023; for (irq = 0; irq < s->num_irq; irq++) { - if (GIC_TEST_ENABLED(irq, cm) && gic_test_pending(s, irq, cm)) { + if (GIC_TEST_ENABLED(irq, cm) && gic_test_pending(s, irq, cm) && + (irq < GIC_INTERNAL || GIC_TARGET(irq) & cm)) { if (GIC_GET_PRIORITY(irq, cpu) < best_prio) { best_prio = GIC_GET_PRIORITY(irq, cpu); best_irq = irq; @@ -372,7 +373,7 @@ static uint32_t gic_dist_readb(void *opaque, hwaddr offset) } } else if (offset < 0xf00) { /* Interrupt Configuration. */ - irq = (offset - 0xc00) * 2 + GIC_BASE_IRQ; + irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ; if (irq >= s->num_irq) goto bad_reg; res = 0; @@ -558,13 +559,15 @@ static void gic_dist_writeb(void *opaque, hwaddr offset, irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ; if (irq >= s->num_irq) goto bad_reg; - if (irq < GIC_INTERNAL) + if (irq < GIC_NR_SGIS) value |= 0xaa; for (i = 0; i < 4; i++) { - if (value & (1 << (i * 2))) { - GIC_SET_MODEL(irq + i); - } else { - GIC_CLEAR_MODEL(irq + i); + if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) { + if (value & (1 << (i * 2))) { + GIC_SET_MODEL(irq + i); + } else { + GIC_CLEAR_MODEL(irq + i); + } } if (value & (2 << (i * 2))) { GIC_SET_EDGE_TRIGGER(irq + i); @@ -766,7 +769,7 @@ static const MemoryRegionOps gic_cpu_ops = { .endianness = DEVICE_NATIVE_ENDIAN, }; -void gic_init_irqs_and_distributor(GICState *s, int num_irq) +void gic_init_irqs_and_distributor(GICState *s) { SysBusDevice *sbd = SYS_BUS_DEVICE(s); int i; @@ -797,13 +800,15 @@ static void arm_gic_realize(DeviceState *dev, Error **errp) GICState *s = ARM_GIC(dev); SysBusDevice *sbd = SYS_BUS_DEVICE(dev); ARMGICClass *agc = ARM_GIC_GET_CLASS(s); + Error *local_err = NULL; - agc->parent_realize(dev, errp); - if (error_is_set(errp)) { + agc->parent_realize(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } - gic_init_irqs_and_distributor(s, s->num_irq); + gic_init_irqs_and_distributor(s); /* Memory regions for the CPU interfaces (NVIC doesn't have these): * a region for "CPU interface for this core", then a region for diff --git a/hw/intc/arm_gic_common.c b/hw/intc/arm_gic_common.c index 6d884eca3b..18b01ba0c7 100644 --- a/hw/intc/arm_gic_common.c +++ b/hw/intc/arm_gic_common.c @@ -128,7 +128,7 @@ static void arm_gic_common_reset(DeviceState *dev) s->running_priority[i] = 0x100; s->cpu_enabled[i] = false; } - for (i = 0; i < 16; i++) { + for (i = 0; i < GIC_NR_SGIS; i++) { GIC_SET_ENABLED(i, ALL_CPU_MASK); GIC_SET_EDGE_TRIGGER(i); } diff --git a/hw/intc/arm_gic_kvm.c b/hw/intc/arm_gic_kvm.c index 719d2277ec..5038885afd 100644 --- a/hw/intc/arm_gic_kvm.c +++ b/hw/intc/arm_gic_kvm.c @@ -517,10 +517,12 @@ static void kvm_arm_gic_realize(DeviceState *dev, Error **errp) GICState *s = KVM_ARM_GIC(dev); SysBusDevice *sbd = SYS_BUS_DEVICE(dev); KVMARMGICClass *kgc = KVM_ARM_GIC_GET_CLASS(s); + Error *local_err = NULL; int ret; - kgc->parent_realize(dev, errp); - if (error_is_set(errp)) { + kgc->parent_realize(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } diff --git a/hw/intc/armv7m_nvic.c b/hw/intc/armv7m_nvic.c index 6066fa6838..d0543d4b9d 100644 --- a/hw/intc/armv7m_nvic.c +++ b/hw/intc/armv7m_nvic.c @@ -173,7 +173,7 @@ static uint32_t nvic_readl(nvic_state *s, uint32_t offset) return 10000; case 0xd00: /* CPUID Base. */ cpu = ARM_CPU(current_cpu); - return cpu->env.cp15.c0_cpuid; + return cpu->midr; case 0xd04: /* Interrupt Control State. */ /* VECTACTIVE */ val = s->gic.running_irq[0]; @@ -211,7 +211,7 @@ static uint32_t nvic_readl(nvic_state *s, uint32_t offset) cpu = ARM_CPU(current_cpu); return cpu->env.v7m.vecbase; case 0xd0c: /* Application Interrupt/Reset Control. */ - return 0xfa05000; + return 0xfa050000; case 0xd10: /* System Control. */ /* TODO: Implement SLEEPONEXIT. */ return 0; @@ -346,6 +346,9 @@ static void nvic_writel(nvic_state *s, uint32_t offset, uint32_t value) if (value & 5) { qemu_log_mask(LOG_UNIMP, "AIRCR system reset unimplemented\n"); } + if (value & 0x700) { + qemu_log_mask(LOG_UNIMP, "PRIGROUP unimplemented\n"); + } } break; case 0xd10: /* System Control. */ @@ -443,8 +446,7 @@ static const VMStateDescription vmstate_nvic = { .name = "armv7m_nvic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(systick.control, nvic_state), VMSTATE_UINT32(systick.reload, nvic_state), VMSTATE_INT64(systick.tick, nvic_state), @@ -474,17 +476,19 @@ static void armv7m_nvic_realize(DeviceState *dev, Error **errp) { nvic_state *s = NVIC(dev); NVICClass *nc = NVIC_GET_CLASS(s); + Error *local_err = NULL; /* The NVIC always has only one CPU */ s->gic.num_cpu = 1; /* Tell the common code we're an NVIC */ s->gic.revision = 0xffffffff; s->num_irq = s->gic.num_irq; - nc->parent_realize(dev, errp); - if (error_is_set(errp)) { + nc->parent_realize(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } - gic_init_irqs_and_distributor(&s->gic, s->num_irq); + gic_init_irqs_and_distributor(&s->gic); /* The NVIC and system controller register area looks like this: * 0..0xff : system control registers, including systick * 0x100..0xcff : GIC-like registers diff --git a/hw/intc/exynos4210_combiner.c b/hw/intc/exynos4210_combiner.c index 3287479456..a6b7028906 100644 --- a/hw/intc/exynos4210_combiner.c +++ b/hw/intc/exynos4210_combiner.c @@ -77,7 +77,6 @@ static const VMStateDescription vmstate_exynos4210_combiner_group_state = { .name = "exynos4210.combiner.groupstate", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT8(src_mask, CombinerGroupState), VMSTATE_UINT8(src_pending, CombinerGroupState), @@ -89,7 +88,6 @@ static const VMStateDescription vmstate_exynos4210_combiner = { .name = "exynos4210.combiner", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(group, Exynos4210CombinerState, IIC_NGRP, 0, vmstate_exynos4210_combiner_group_state, CombinerGroupState), diff --git a/hw/intc/exynos4210_gic.c b/hw/intc/exynos4210_gic.c index 5b913f786e..0590d5dfb8 100644 --- a/hw/intc/exynos4210_gic.c +++ b/hw/intc/exynos4210_gic.c @@ -394,7 +394,6 @@ static const VMStateDescription vmstate_exynos4210_irq_gate = { .name = "exynos4210.irq_gate", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .fields = (VMStateField[]) { VMSTATE_VBUFFER_UINT32(level, Exynos4210IRQGateState, 1, NULL, 0, n_in), VMSTATE_END_OF_LIST() diff --git a/hw/intc/gic_internal.h b/hw/intc/gic_internal.h index 48a58d7890..e87ef36d0c 100644 --- a/hw/intc/gic_internal.h +++ b/hw/intc/gic_internal.h @@ -59,7 +59,7 @@ void gic_set_pending_private(GICState *s, int cpu, int irq); uint32_t gic_acknowledge_irq(GICState *s, int cpu); void gic_complete_irq(GICState *s, int cpu, int irq); void gic_update(GICState *s); -void gic_init_irqs_and_distributor(GICState *s, int num_irq); +void gic_init_irqs_and_distributor(GICState *s); void gic_set_priority(GICState *s, int cpu, int irq, uint8_t val); static inline bool gic_test_pending(GICState *s, int irq, int cm) diff --git a/hw/intc/heathrow_pic.c b/hw/intc/heathrow_pic.c index 9818f2430c..9ff3119edc 100644 --- a/hw/intc/heathrow_pic.c +++ b/hw/intc/heathrow_pic.c @@ -159,8 +159,7 @@ static const VMStateDescription vmstate_heathrow_pic_one = { .name = "heathrow_pic_one", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(events, HeathrowPIC), VMSTATE_UINT32(mask, HeathrowPIC), VMSTATE_UINT32(levels, HeathrowPIC), @@ -173,8 +172,7 @@ static const VMStateDescription vmstate_heathrow_pic = { .name = "heathrow_pic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(pics, HeathrowPICS, 2, 1, vmstate_heathrow_pic_one, HeathrowPIC), VMSTATE_END_OF_LIST() diff --git a/hw/intc/i8259.c b/hw/intc/i8259.c index c6f248b145..c51901bfb6 100644 --- a/hw/intc/i8259.c +++ b/hw/intc/i8259.c @@ -265,7 +265,8 @@ static void pic_ioport_write(void *opaque, hwaddr addr64, s->init4 = val & 1; s->single_mode = val & 2; if (val & 0x08) { - hw_error("level sensitive irq not supported"); + qemu_log_mask(LOG_UNIMP, + "i8259: level sensitive irq not supported\n"); } } else if (val & 0x08) { if (val & 0x04) { @@ -369,7 +370,7 @@ static uint64_t pic_ioport_read(void *opaque, hwaddr addr, ret = s->imr; } } - DPRINTF("read: addr=0x%02x val=0x%02x\n", addr, ret); + DPRINTF("read: addr=0x%02" HWADDR_PRIx " val=0x%02x\n", addr, ret); return ret; } @@ -412,7 +413,7 @@ static const MemoryRegionOps pic_elcr_ioport_ops = { }, }; -static void pic_realize(DeviceState *dev, Error **err) +static void pic_realize(DeviceState *dev, Error **errp) { PICCommonState *s = PIC_COMMON(dev); PICClass *pc = PIC_GET_CLASS(dev); @@ -425,7 +426,7 @@ static void pic_realize(DeviceState *dev, Error **err) qdev_init_gpio_out(dev, s->int_out, ARRAY_SIZE(s->int_out)); qdev_init_gpio_in(dev, pic_set_irq, 8); - pc->parent_realize(dev, err); + pc->parent_realize(dev, errp); } void pic_info(Monitor *mon, const QDict *qdict) @@ -471,7 +472,7 @@ qemu_irq *i8259_init(ISABus *bus, qemu_irq parent_irq) ISADevice *isadev; int i; - irq_set = g_malloc(ISA_NUM_IRQS * sizeof(qemu_irq)); + irq_set = g_new0(qemu_irq, ISA_NUM_IRQS); isadev = i8259_init_chip(TYPE_I8259, bus, true); dev = DEVICE(isadev); diff --git a/hw/intc/i8259_common.c b/hw/intc/i8259_common.c index 61381c463d..fbf26e5576 100644 --- a/hw/intc/i8259_common.c +++ b/hw/intc/i8259_common.c @@ -98,7 +98,6 @@ static const VMStateDescription vmstate_pic_common = { .name = "i8259", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = pic_dispatch_pre_save, .post_load = pic_dispatch_post_load, .fields = (VMStateField[]) { diff --git a/hw/intc/imx_avic.c b/hw/intc/imx_avic.c index fb00e910f6..e48f66c8fa 100644 --- a/hw/intc/imx_avic.c +++ b/hw/intc/imx_avic.c @@ -77,7 +77,6 @@ static const VMStateDescription vmstate_imx_avic = { .name = "imx-avic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT64(pending, IMXAVICState), VMSTATE_UINT64(enabled, IMXAVICState), @@ -98,15 +97,6 @@ static inline int imx_avic_prio(IMXAVICState *s, int irq) return 0xf & (s->prio[word] >> part); } -static inline void imx_avic_set_prio(IMXAVICState *s, int irq, int prio) -{ - uint32_t word = irq / PRIO_PER_WORD; - uint32_t part = 4 * (irq % PRIO_PER_WORD); - uint32_t mask = ~(0xf << part); - s->prio[word] &= mask; - s->prio[word] |= prio << part; -} - /* Update interrupts. */ static void imx_avic_update(IMXAVICState *s) { diff --git a/hw/intc/ioapic_common.c b/hw/intc/ioapic_common.c index 4d3d309b62..8b7d11806c 100644 --- a/hw/intc/ioapic_common.c +++ b/hw/intc/ioapic_common.c @@ -86,7 +86,6 @@ static const VMStateDescription vmstate_ioapic_common = { .name = "ioapic", .version_id = 3, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = ioapic_dispatch_pre_save, .post_load = ioapic_dispatch_post_load, .fields = (VMStateField[]) { diff --git a/hw/intc/lm32_pic.c b/hw/intc/lm32_pic.c index 32d009f678..72fc9ef674 100644 --- a/hw/intc/lm32_pic.c +++ b/hw/intc/lm32_pic.c @@ -169,8 +169,7 @@ static const VMStateDescription vmstate_lm32_pic = { .name = "lm32-pic", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(im, LM32PicState), VMSTATE_UINT32(ip, LM32PicState), VMSTATE_UINT32(irq_state, LM32PicState), diff --git a/hw/intc/openpic.c b/hw/intc/openpic.c index be76fbd78f..7d1f3b9497 100644 --- a/hw/intc/openpic.c +++ b/hw/intc/openpic.c @@ -41,6 +41,7 @@ #include "hw/sysbus.h" #include "hw/pci/msi.h" #include "qemu/bitops.h" +#include "qapi/qmp/qerror.h" //#define DEBUG_OPENPIC @@ -191,6 +192,7 @@ static uint32_t openpic_cpu_read_internal(void *opaque, hwaddr addr, int idx); static void openpic_cpu_write_internal(void *opaque, hwaddr addr, uint32_t val, int idx); +static void openpic_reset(DeviceState *d); typedef enum IRQType { IRQ_TYPE_NORMAL = 0, @@ -310,11 +312,6 @@ static inline void IRQ_resetbit(IRQQueue *q, int n_IRQ) clear_bit(n_IRQ, q->queue); } -static inline int IRQ_testbit(IRQQueue *q, int n_IRQ) -{ - return test_bit(n_IRQ, q->queue); -} - static void IRQ_check(OpenPICState *opp, IRQQueue *q) { int irq = -1; @@ -533,55 +530,6 @@ static void openpic_set_irq(void *opaque, int n_IRQ, int level) } } -static void openpic_reset(DeviceState *d) -{ - OpenPICState *opp = OPENPIC(d); - int i; - - opp->gcr = GCR_RESET; - /* Initialise controller registers */ - opp->frr = ((opp->nb_irqs - 1) << FRR_NIRQ_SHIFT) | - ((opp->nb_cpus - 1) << FRR_NCPU_SHIFT) | - (opp->vid << FRR_VID_SHIFT); - - opp->pir = 0; - opp->spve = -1 & opp->vector_mask; - opp->tfrr = opp->tfrr_reset; - /* Initialise IRQ sources */ - for (i = 0; i < opp->max_irq; i++) { - opp->src[i].ivpr = opp->ivpr_reset; - opp->src[i].idr = opp->idr_reset; - - switch (opp->src[i].type) { - case IRQ_TYPE_NORMAL: - opp->src[i].level = !!(opp->ivpr_reset & IVPR_SENSE_MASK); - break; - - case IRQ_TYPE_FSLINT: - opp->src[i].ivpr |= IVPR_POLARITY_MASK; - break; - - case IRQ_TYPE_FSLSPECIAL: - break; - } - } - /* Initialise IRQ destinations */ - for (i = 0; i < MAX_CPU; i++) { - opp->dst[i].ctpr = 15; - memset(&opp->dst[i].raised, 0, sizeof(IRQQueue)); - opp->dst[i].raised.next = -1; - memset(&opp->dst[i].servicing, 0, sizeof(IRQQueue)); - opp->dst[i].servicing.next = -1; - } - /* Initialise timers */ - for (i = 0; i < OPENPIC_MAX_TMR; i++) { - opp->timers[i].tccr = 0; - opp->timers[i].tbcr = TBCR_CI; - } - /* Go out of RESET state */ - opp->gcr = 0; -} - static inline uint32_t read_IRQreg_idr(OpenPICState *opp, int n_IRQ) { return opp->src[n_IRQ].idr; @@ -1416,7 +1364,7 @@ static void openpic_load_IRQ_queue(QEMUFile* f, IRQQueue *q) static int openpic_load(QEMUFile* f, void *opaque, int version_id) { OpenPICState *opp = (OpenPICState *)opaque; - unsigned int i; + unsigned int i, nb_cpus; if (version_id != 1) { return -EINVAL; @@ -1428,7 +1376,11 @@ static int openpic_load(QEMUFile* f, void *opaque, int version_id) qemu_get_be32s(f, &opp->spve); qemu_get_be32s(f, &opp->tfrr); - qemu_get_be32s(f, &opp->nb_cpus); + qemu_get_be32s(f, &nb_cpus); + if (opp->nb_cpus != nb_cpus) { + return -EINVAL; + } + assert(nb_cpus > 0 && nb_cpus <= MAX_CPU); for (i = 0; i < opp->nb_cpus; i++) { qemu_get_sbe32s(f, &opp->dst[i].ctpr); @@ -1461,6 +1413,55 @@ static int openpic_load(QEMUFile* f, void *opaque, int version_id) return 0; } +static void openpic_reset(DeviceState *d) +{ + OpenPICState *opp = OPENPIC(d); + int i; + + opp->gcr = GCR_RESET; + /* Initialise controller registers */ + opp->frr = ((opp->nb_irqs - 1) << FRR_NIRQ_SHIFT) | + ((opp->nb_cpus - 1) << FRR_NCPU_SHIFT) | + (opp->vid << FRR_VID_SHIFT); + + opp->pir = 0; + opp->spve = -1 & opp->vector_mask; + opp->tfrr = opp->tfrr_reset; + /* Initialise IRQ sources */ + for (i = 0; i < opp->max_irq; i++) { + opp->src[i].ivpr = opp->ivpr_reset; + switch (opp->src[i].type) { + case IRQ_TYPE_NORMAL: + opp->src[i].level = !!(opp->ivpr_reset & IVPR_SENSE_MASK); + break; + + case IRQ_TYPE_FSLINT: + opp->src[i].ivpr |= IVPR_POLARITY_MASK; + break; + + case IRQ_TYPE_FSLSPECIAL: + break; + } + + write_IRQreg_idr(opp, i, opp->idr_reset); + } + /* Initialise IRQ destinations */ + for (i = 0; i < MAX_CPU; i++) { + opp->dst[i].ctpr = 15; + memset(&opp->dst[i].raised, 0, sizeof(IRQQueue)); + opp->dst[i].raised.next = -1; + memset(&opp->dst[i].servicing, 0, sizeof(IRQQueue)); + opp->dst[i].servicing.next = -1; + } + /* Initialise timers */ + for (i = 0; i < OPENPIC_MAX_TMR; i++) { + opp->timers[i].tccr = 0; + opp->timers[i].tbcr = TBCR_CI; + } + /* Go out of RESET state */ + opp->gcr = 0; +} + typedef struct MemReg { const char *name; MemoryRegionOps const *ops; @@ -1567,6 +1568,13 @@ static void openpic_realize(DeviceState *dev, Error **errp) {NULL} }; + if (opp->nb_cpus > MAX_CPU) { + error_set(errp, QERR_PROPERTY_VALUE_OUT_OF_RANGE, + TYPE_OPENPIC, "nb_cpus", (uint64_t)opp->nb_cpus, + (uint64_t)0, (uint64_t)MAX_CPU); + return; + } + switch (opp->model) { case OPENPIC_MODEL_FSL_MPIC_20: default: @@ -1619,7 +1627,7 @@ static void openpic_realize(DeviceState *dev, Error **errp) } for (i = 0; i < opp->nb_cpus; i++) { - opp->dst[i].irqs = g_new(qemu_irq, OPENPIC_OUTPUT_NB); + opp->dst[i].irqs = g_new0(qemu_irq, OPENPIC_OUTPUT_NB); for (j = 0; j < OPENPIC_OUTPUT_NB; j++) { sysbus_init_irq(d, &opp->dst[i].irqs[j]); } diff --git a/hw/intc/openpic_kvm.c b/hw/intc/openpic_kvm.c index 6635407b8b..3e2cd189ff 100644 --- a/hw/intc/openpic_kvm.c +++ b/hw/intc/openpic_kvm.c @@ -31,6 +31,8 @@ #include "sysemu/kvm.h" #include "qemu/log.h" +#define GCR_RESET 0x80000000 + #define KVM_OPENPIC(obj) \ OBJECT_CHECK(KVMOpenPICState, (obj), TYPE_KVM_OPENPIC) @@ -43,6 +45,7 @@ typedef struct KVMOpenPICState { MemoryListener mem_listener; uint32_t fd; uint32_t model; + hwaddr mapped; } KVMOpenPICState; static void kvm_openpic_set_irq(void *opaque, int n_IRQ, int level) @@ -50,11 +53,6 @@ static void kvm_openpic_set_irq(void *opaque, int n_IRQ, int level) kvm_set_irq(kvm_state, n_IRQ, level); } -static void kvm_openpic_reset(DeviceState *d) -{ - qemu_log_mask(LOG_UNIMP, "%s: unimplemented\n", __func__); -} - static void kvm_openpic_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { @@ -74,6 +72,14 @@ static void kvm_openpic_write(void *opaque, hwaddr addr, uint64_t val, } } +static void kvm_openpic_reset(DeviceState *d) +{ + KVMOpenPICState *opp = KVM_OPENPIC(d); + + /* Trigger the GCR.RESET bit to reset the PIC */ + kvm_openpic_write(opp, 0x1020, GCR_RESET, sizeof(uint32_t)); +} + static uint64_t kvm_openpic_read(void *opaque, hwaddr addr, unsigned size) { KVMOpenPICState *opp = opaque; @@ -123,7 +129,16 @@ static void kvm_openpic_region_add(MemoryListener *listener, return; } + if (opp->mapped) { + /* + * We can only map the MPIC once. Since we are already mapped, + * the best we can do is ignore new maps. + */ + return; + } + reg_base = section->offset_within_address_space; + opp->mapped = reg_base; attr.group = KVM_DEV_MPIC_GRP_MISC; attr.attr = KVM_DEV_MPIC_BASE_ADDR; @@ -150,6 +165,15 @@ static void kvm_openpic_region_del(MemoryListener *listener, return; } + if (section->offset_within_address_space != opp->mapped) { + /* + * We can only map the MPIC once. This mapping was a secondary + * one that we couldn't fulfill. Ignore it. + */ + return; + } + opp->mapped = 0; + attr.group = KVM_DEV_MPIC_GRP_MISC; attr.attr = KVM_DEV_MPIC_BASE_ADDR; attr.addr = (uint64_t)(unsigned long)®_base; @@ -234,13 +258,9 @@ static void kvm_openpic_realize(DeviceState *dev, Error **errp) int kvm_openpic_connect_vcpu(DeviceState *d, CPUState *cs) { KVMOpenPICState *opp = KVM_OPENPIC(d); - struct kvm_enable_cap encap = {}; - - encap.cap = KVM_CAP_IRQ_MPIC; - encap.args[0] = opp->fd; - encap.args[1] = kvm_arch_vcpu_id(cs); - return kvm_vcpu_ioctl(cs, KVM_ENABLE_CAP, &encap); + return kvm_vcpu_enable_cap(cs, KVM_CAP_IRQ_MPIC, 0, opp->fd, + kvm_arch_vcpu_id(cs)); } static Property kvm_openpic_properties[] = { diff --git a/hw/intc/s390_flic.c b/hw/intc/s390_flic.c index b2ef3e3f8e..03c5e89f4e 100644 --- a/hw/intc/s390_flic.c +++ b/hw/intc/s390_flic.c @@ -1,322 +1,103 @@ /* - * QEMU S390x KVM floating interrupt controller (flic) + * QEMU S390x floating interrupt controller (flic) * * Copyright 2014 IBM Corp. * Author(s): Jens Freimann <jfrei@linux.vnet.ibm.com> + * Cornelia Huck <cornelia.huck@de.ibm.com> * * This work is licensed under the terms of the GNU GPL, version 2 or (at * your option) any later version. See the COPYING file in the top-level * directory. */ -#include <sys/ioctl.h> #include "qemu/error-report.h" #include "hw/sysbus.h" -#include "sysemu/kvm.h" #include "migration/qemu-file.h" #include "hw/s390x/s390_flic.h" #include "trace.h" -#define FLIC_SAVE_INITIAL_SIZE getpagesize() -#define FLIC_FAILED (-1UL) -#define FLIC_SAVEVM_VERSION 1 - -void s390_flic_init(void) -{ - DeviceState *dev; - int r; - - if (kvm_enabled()) { - dev = qdev_create(NULL, "s390-flic"); - object_property_add_child(qdev_get_machine(), "s390-flic", - OBJECT(dev), NULL); - r = qdev_init(dev); - if (r) { - error_report("flic: couldn't create qdev"); - } - } -} - -/** - * flic_get_all_irqs - store all pending irqs in buffer - * @buf: pointer to buffer which is passed to kernel - * @len: length of buffer - * @flic: pointer to flic device state - * - * Returns: -ENOMEM if buffer is too small, - * -EINVAL if attr.group is invalid, - * -EFAULT if copying to userspace failed, - * on success return number of stored interrupts - */ -static int flic_get_all_irqs(KVMS390FLICState *flic, - void *buf, int len) +S390FLICState *s390_get_flic(void) { - struct kvm_device_attr attr = { - .group = KVM_DEV_FLIC_GET_ALL_IRQS, - .addr = (uint64_t) buf, - .attr = len, - }; - int rc; - - rc = ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr); - - return rc == -1 ? -errno : rc; -} + S390FLICState *fs; -static void flic_enable_pfault(KVMS390FLICState *flic) -{ - struct kvm_device_attr attr = { - .group = KVM_DEV_FLIC_APF_ENABLE, - }; - int rc; - - rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); - - if (rc) { - fprintf(stderr, "flic: couldn't enable pfault\n"); + fs = S390_FLIC_COMMON(object_resolve_path(TYPE_KVM_S390_FLIC, NULL)); + if (!fs) { + fs = S390_FLIC_COMMON(object_resolve_path(TYPE_QEMU_S390_FLIC, NULL)); } + return fs; } -static void flic_disable_wait_pfault(KVMS390FLICState *flic) -{ - struct kvm_device_attr attr = { - .group = KVM_DEV_FLIC_APF_DISABLE_WAIT, - }; - int rc; - - rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); - - if (rc) { - fprintf(stderr, "flic: couldn't disable pfault\n"); - } -} - -/** flic_enqueue_irqs - returns 0 on success - * @buf: pointer to buffer which is passed to kernel - * @len: length of buffer - * @flic: pointer to flic device state - * - * Returns: -EINVAL if attr.group is unknown - */ -static int flic_enqueue_irqs(void *buf, uint64_t len, - KVMS390FLICState *flic) -{ - int rc; - struct kvm_device_attr attr = { - .group = KVM_DEV_FLIC_ENQUEUE, - .addr = (uint64_t) buf, - .attr = len, - }; - - rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); - - return rc ? -errno : 0; -} - -/** - * __get_all_irqs - store all pending irqs in buffer - * @flic: pointer to flic device state - * @buf: pointer to pointer to a buffer - * @len: length of buffer - * - * Returns: return value of flic_get_all_irqs - * Note: Retry and increase buffer size until flic_get_all_irqs - * either returns a value >= 0 or a negative error code. - * -ENOMEM is an exception, which means the buffer is too small - * and we should try again. Other negative error codes can be - * -EFAULT and -EINVAL which we ignore at this point - */ -static int __get_all_irqs(KVMS390FLICState *flic, - void **buf, int len) +void s390_flic_init(void) { + DeviceState *dev; int r; - do { - /* returns -ENOMEM if buffer is too small and number - * of queued interrupts on success */ - r = flic_get_all_irqs(flic, *buf, len); - if (r >= 0) { - break; - } - len *= 2; - *buf = g_try_realloc(*buf, len); - if (!buf) { - return -ENOMEM; - } - } while (r == -ENOMEM && len <= KVM_S390_FLIC_MAX_BUFFER); - - return r; -} - -/** - * kvm_flic_save - Save pending floating interrupts - * @f: QEMUFile containing migration state - * @opaque: pointer to flic device state - * - * Note: Pass buf and len to kernel. Start with one page and - * increase until buffer is sufficient or maxium size is - * reached - */ -static void kvm_flic_save(QEMUFile *f, void *opaque) -{ - KVMS390FLICState *flic = opaque; - int len = FLIC_SAVE_INITIAL_SIZE; - void *buf; - int count; - - flic_disable_wait_pfault((struct KVMS390FLICState *) opaque); - - buf = g_try_malloc0(len); - if (!buf) { - /* Storing FLIC_FAILED into the count field here will cause the - * target system to fail when attempting to load irqs from the - * migration state */ - error_report("flic: couldn't allocate memory"); - qemu_put_be64(f, FLIC_FAILED); - return; + dev = s390_flic_kvm_create(); + if (!dev) { + dev = qdev_create(NULL, TYPE_QEMU_S390_FLIC); + object_property_add_child(qdev_get_machine(), TYPE_QEMU_S390_FLIC, + OBJECT(dev), NULL); } - - count = __get_all_irqs(flic, &buf, len); - if (count < 0) { - error_report("flic: couldn't retrieve irqs from kernel, rc %d", - count); - /* Storing FLIC_FAILED into the count field here will cause the - * target system to fail when attempting to load irqs from the - * migration state */ - qemu_put_be64(f, FLIC_FAILED); - } else { - qemu_put_be64(f, count); - qemu_put_buffer(f, (uint8_t *) buf, - count * sizeof(struct kvm_s390_irq)); + r = qdev_init(dev); + if (r) { + error_report("flic: couldn't create qdev"); } - g_free(buf); } -/** - * kvm_flic_load - Load pending floating interrupts - * @f: QEMUFile containing migration state - * @opaque: pointer to flic device state - * @version_id: version id for migration - * - * Returns: value of flic_enqueue_irqs, -EINVAL on error - * Note: Do nothing when no interrupts where stored - * in QEMUFile - */ -static int kvm_flic_load(QEMUFile *f, void *opaque, int version_id) +static int qemu_s390_register_io_adapter(S390FLICState *fs, uint32_t id, + uint8_t isc, bool swap, + bool is_maskable) { - uint64_t len = 0; - uint64_t count = 0; - void *buf = NULL; - int r = 0; - - if (version_id != FLIC_SAVEVM_VERSION) { - r = -EINVAL; - goto out; - } - - flic_enable_pfault((struct KVMS390FLICState *) opaque); - - count = qemu_get_be64(f); - len = count * sizeof(struct kvm_s390_irq); - if (count == FLIC_FAILED) { - r = -EINVAL; - goto out; - } - if (count == 0) { - r = 0; - goto out; - } - buf = g_try_malloc0(len); - if (!buf) { - r = -ENOMEM; - goto out; - } - - if (qemu_get_buffer(f, (uint8_t *) buf, len) != len) { - r = -EINVAL; - goto out_free; - } - r = flic_enqueue_irqs(buf, len, (struct KVMS390FLICState *) opaque); - -out_free: - g_free(buf); -out: - return r; + /* nothing to do */ + return 0; } -static void kvm_s390_flic_realize(DeviceState *dev, Error **errp) +static int qemu_s390_io_adapter_map(S390FLICState *fs, uint32_t id, + uint64_t map_addr, bool do_map) { - KVMS390FLICState *flic_state = KVM_S390_FLIC(dev); - struct kvm_create_device cd = {0}; - int ret; - - flic_state->fd = -1; - if (!kvm_check_extension(kvm_state, KVM_CAP_DEVICE_CTRL)) { - trace_flic_no_device_api(errno); - return; - } - - cd.type = KVM_DEV_TYPE_FLIC; - ret = kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd); - if (ret < 0) { - trace_flic_create_device(errno); - return; - } - flic_state->fd = cd.fd; - - /* Register savevm handler for floating interrupts */ - register_savevm(NULL, "s390-flic", 0, 1, kvm_flic_save, - kvm_flic_load, (void *) flic_state); + /* nothing to do */ + return 0; } -static void kvm_s390_flic_unrealize(DeviceState *dev, Error **errp) +static int qemu_s390_add_adapter_routes(S390FLICState *fs, + AdapterRoutes *routes) { - KVMS390FLICState *flic_state = KVM_S390_FLIC(dev); - - unregister_savevm(DEVICE(flic_state), "s390-flic", flic_state); + return -ENOSYS; } -static void kvm_s390_flic_reset(DeviceState *dev) +static void qemu_s390_release_adapter_routes(S390FLICState *fs, + AdapterRoutes *routes) { - KVMS390FLICState *flic = KVM_S390_FLIC(dev); - struct kvm_device_attr attr = { - .group = KVM_DEV_FLIC_CLEAR_IRQS, - }; - int rc = 0; - - if (flic->fd == -1) { - return; - } - - flic_disable_wait_pfault(flic); - - rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); - if (rc) { - trace_flic_reset_failed(errno); - } - - flic_enable_pfault(flic); } -static void kvm_s390_flic_class_init(ObjectClass *oc, void *data) +static void qemu_s390_flic_class_init(ObjectClass *oc, void *data) { - DeviceClass *dc = DEVICE_CLASS(oc); + S390FLICStateClass *fsc = S390_FLIC_COMMON_CLASS(oc); - dc->realize = kvm_s390_flic_realize; - dc->unrealize = kvm_s390_flic_unrealize; - dc->reset = kvm_s390_flic_reset; + fsc->register_io_adapter = qemu_s390_register_io_adapter; + fsc->io_adapter_map = qemu_s390_io_adapter_map; + fsc->add_adapter_routes = qemu_s390_add_adapter_routes; + fsc->release_adapter_routes = qemu_s390_release_adapter_routes; } -static const TypeInfo kvm_s390_flic_info = { - .name = TYPE_KVM_S390_FLIC, +static const TypeInfo qemu_s390_flic_info = { + .name = TYPE_QEMU_S390_FLIC, + .parent = TYPE_S390_FLIC_COMMON, + .instance_size = sizeof(QEMUS390FLICState), + .class_init = qemu_s390_flic_class_init, +}; + +static const TypeInfo s390_flic_common_info = { + .name = TYPE_S390_FLIC_COMMON, .parent = TYPE_SYS_BUS_DEVICE, - .instance_size = sizeof(KVMS390FLICState), - .class_init = kvm_s390_flic_class_init, + .instance_size = sizeof(S390FLICState), + .class_size = sizeof(S390FLICStateClass), }; -static void kvm_s390_flic_register_types(void) +static void qemu_s390_flic_register_types(void) { - type_register_static(&kvm_s390_flic_info); + type_register_static(&s390_flic_common_info); + type_register_static(&qemu_s390_flic_info); } -type_init(kvm_s390_flic_register_types) +type_init(qemu_s390_flic_register_types) diff --git a/hw/intc/s390_flic_kvm.c b/hw/intc/s390_flic_kvm.c new file mode 100644 index 0000000000..b471e7a41e --- /dev/null +++ b/hw/intc/s390_flic_kvm.c @@ -0,0 +1,432 @@ +/* + * QEMU S390x KVM floating interrupt controller (flic) + * + * Copyright 2014 IBM Corp. + * Author(s): Jens Freimann <jfrei@linux.vnet.ibm.com> + * Cornelia Huck <cornelia.huck@de.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2 or (at + * your option) any later version. See the COPYING file in the top-level + * directory. + */ + +#include <sys/ioctl.h> +#include "qemu/error-report.h" +#include "hw/sysbus.h" +#include "sysemu/kvm.h" +#include "migration/qemu-file.h" +#include "hw/s390x/s390_flic.h" +#include "hw/s390x/adapter.h" +#include "trace.h" + +#define FLIC_SAVE_INITIAL_SIZE getpagesize() +#define FLIC_FAILED (-1UL) +#define FLIC_SAVEVM_VERSION 1 + +typedef struct KVMS390FLICState { + S390FLICState parent_obj; + + uint32_t fd; +} KVMS390FLICState; + +DeviceState *s390_flic_kvm_create(void) +{ + DeviceState *dev = NULL; + + if (kvm_enabled()) { + dev = qdev_create(NULL, TYPE_KVM_S390_FLIC); + object_property_add_child(qdev_get_machine(), TYPE_KVM_S390_FLIC, + OBJECT(dev), NULL); + } + return dev; +} + +/** + * flic_get_all_irqs - store all pending irqs in buffer + * @buf: pointer to buffer which is passed to kernel + * @len: length of buffer + * @flic: pointer to flic device state + * + * Returns: -ENOMEM if buffer is too small, + * -EINVAL if attr.group is invalid, + * -EFAULT if copying to userspace failed, + * on success return number of stored interrupts + */ +static int flic_get_all_irqs(KVMS390FLICState *flic, + void *buf, int len) +{ + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_GET_ALL_IRQS, + .addr = (uint64_t) buf, + .attr = len, + }; + int rc; + + rc = ioctl(flic->fd, KVM_GET_DEVICE_ATTR, &attr); + + return rc == -1 ? -errno : rc; +} + +static void flic_enable_pfault(KVMS390FLICState *flic) +{ + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_APF_ENABLE, + }; + int rc; + + rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + + if (rc) { + fprintf(stderr, "flic: couldn't enable pfault\n"); + } +} + +static void flic_disable_wait_pfault(KVMS390FLICState *flic) +{ + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_APF_DISABLE_WAIT, + }; + int rc; + + rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + + if (rc) { + fprintf(stderr, "flic: couldn't disable pfault\n"); + } +} + +/** flic_enqueue_irqs - returns 0 on success + * @buf: pointer to buffer which is passed to kernel + * @len: length of buffer + * @flic: pointer to flic device state + * + * Returns: -EINVAL if attr.group is unknown + */ +static int flic_enqueue_irqs(void *buf, uint64_t len, + KVMS390FLICState *flic) +{ + int rc; + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_ENQUEUE, + .addr = (uint64_t) buf, + .attr = len, + }; + + rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + + return rc ? -errno : 0; +} + +int kvm_s390_inject_flic(struct kvm_s390_irq *irq) +{ + static KVMS390FLICState *flic; + + if (unlikely(!flic)) { + flic = KVM_S390_FLIC(s390_get_flic()); + } + return flic_enqueue_irqs(irq, sizeof(*irq), flic); +} + +/** + * __get_all_irqs - store all pending irqs in buffer + * @flic: pointer to flic device state + * @buf: pointer to pointer to a buffer + * @len: length of buffer + * + * Returns: return value of flic_get_all_irqs + * Note: Retry and increase buffer size until flic_get_all_irqs + * either returns a value >= 0 or a negative error code. + * -ENOMEM is an exception, which means the buffer is too small + * and we should try again. Other negative error codes can be + * -EFAULT and -EINVAL which we ignore at this point + */ +static int __get_all_irqs(KVMS390FLICState *flic, + void **buf, int len) +{ + int r; + + do { + /* returns -ENOMEM if buffer is too small and number + * of queued interrupts on success */ + r = flic_get_all_irqs(flic, *buf, len); + if (r >= 0) { + break; + } + len *= 2; + *buf = g_try_realloc(*buf, len); + if (!buf) { + return -ENOMEM; + } + } while (r == -ENOMEM && len <= KVM_S390_FLIC_MAX_BUFFER); + + return r; +} + +static int kvm_s390_register_io_adapter(S390FLICState *fs, uint32_t id, + uint8_t isc, bool swap, + bool is_maskable) +{ + struct kvm_s390_io_adapter adapter = { + .id = id, + .isc = isc, + .maskable = is_maskable, + .swap = swap, + }; + KVMS390FLICState *flic = KVM_S390_FLIC(fs); + int r, ret; + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_ADAPTER_REGISTER, + .addr = (uint64_t)&adapter, + }; + + if (!kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING)) { + /* nothing to do */ + return 0; + } + + r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + + ret = r ? -errno : 0; + return ret; +} + +static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id, + uint64_t map_addr, bool do_map) +{ + struct kvm_s390_io_adapter_req req = { + .id = id, + .type = do_map ? KVM_S390_IO_ADAPTER_MAP : KVM_S390_IO_ADAPTER_UNMAP, + .addr = map_addr, + }; + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_ADAPTER_MODIFY, + .addr = (uint64_t)&req, + }; + KVMS390FLICState *flic = KVM_S390_FLIC(fs); + int r; + + if (!kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING)) { + /* nothing to do */ + return 0; + } + + r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + return r ? -errno : 0; +} + +static int kvm_s390_add_adapter_routes(S390FLICState *fs, + AdapterRoutes *routes) +{ + int ret, i; + uint64_t ind_offset = routes->adapter.ind_offset; + + for (i = 0; i < routes->num_routes; i++) { + ret = kvm_irqchip_add_adapter_route(kvm_state, &routes->adapter); + if (ret < 0) { + goto out_undo; + } + routes->gsi[i] = ret; + routes->adapter.ind_offset++; + } + /* Restore passed-in structure to original state. */ + routes->adapter.ind_offset = ind_offset; + return 0; +out_undo: + while (--i >= 0) { + kvm_irqchip_release_virq(kvm_state, routes->gsi[i]); + routes->gsi[i] = -1; + } + routes->adapter.ind_offset = ind_offset; + return ret; +} + +static void kvm_s390_release_adapter_routes(S390FLICState *fs, + AdapterRoutes *routes) +{ + int i; + + for (i = 0; i < routes->num_routes; i++) { + if (routes->gsi[i] >= 0) { + kvm_irqchip_release_virq(kvm_state, routes->gsi[i]); + routes->gsi[i] = -1; + } + } +} + +/** + * kvm_flic_save - Save pending floating interrupts + * @f: QEMUFile containing migration state + * @opaque: pointer to flic device state + * + * Note: Pass buf and len to kernel. Start with one page and + * increase until buffer is sufficient or maxium size is + * reached + */ +static void kvm_flic_save(QEMUFile *f, void *opaque) +{ + KVMS390FLICState *flic = opaque; + int len = FLIC_SAVE_INITIAL_SIZE; + void *buf; + int count; + + flic_disable_wait_pfault((struct KVMS390FLICState *) opaque); + + buf = g_try_malloc0(len); + if (!buf) { + /* Storing FLIC_FAILED into the count field here will cause the + * target system to fail when attempting to load irqs from the + * migration state */ + error_report("flic: couldn't allocate memory"); + qemu_put_be64(f, FLIC_FAILED); + return; + } + + count = __get_all_irqs(flic, &buf, len); + if (count < 0) { + error_report("flic: couldn't retrieve irqs from kernel, rc %d", + count); + /* Storing FLIC_FAILED into the count field here will cause the + * target system to fail when attempting to load irqs from the + * migration state */ + qemu_put_be64(f, FLIC_FAILED); + } else { + qemu_put_be64(f, count); + qemu_put_buffer(f, (uint8_t *) buf, + count * sizeof(struct kvm_s390_irq)); + } + g_free(buf); +} + +/** + * kvm_flic_load - Load pending floating interrupts + * @f: QEMUFile containing migration state + * @opaque: pointer to flic device state + * @version_id: version id for migration + * + * Returns: value of flic_enqueue_irqs, -EINVAL on error + * Note: Do nothing when no interrupts where stored + * in QEMUFile + */ +static int kvm_flic_load(QEMUFile *f, void *opaque, int version_id) +{ + uint64_t len = 0; + uint64_t count = 0; + void *buf = NULL; + int r = 0; + + if (version_id != FLIC_SAVEVM_VERSION) { + r = -EINVAL; + goto out; + } + + flic_enable_pfault((struct KVMS390FLICState *) opaque); + + count = qemu_get_be64(f); + len = count * sizeof(struct kvm_s390_irq); + if (count == FLIC_FAILED) { + r = -EINVAL; + goto out; + } + if (count == 0) { + r = 0; + goto out; + } + buf = g_try_malloc0(len); + if (!buf) { + r = -ENOMEM; + goto out; + } + + if (qemu_get_buffer(f, (uint8_t *) buf, len) != len) { + r = -EINVAL; + goto out_free; + } + r = flic_enqueue_irqs(buf, len, (struct KVMS390FLICState *) opaque); + +out_free: + g_free(buf); +out: + return r; +} + +static void kvm_s390_flic_realize(DeviceState *dev, Error **errp) +{ + KVMS390FLICState *flic_state = KVM_S390_FLIC(dev); + struct kvm_create_device cd = {0}; + int ret; + + flic_state->fd = -1; + if (!kvm_check_extension(kvm_state, KVM_CAP_DEVICE_CTRL)) { + trace_flic_no_device_api(errno); + return; + } + + cd.type = KVM_DEV_TYPE_FLIC; + ret = kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd); + if (ret < 0) { + trace_flic_create_device(errno); + return; + } + flic_state->fd = cd.fd; + + /* Register savevm handler for floating interrupts */ + register_savevm(NULL, "s390-flic", 0, 1, kvm_flic_save, + kvm_flic_load, (void *) flic_state); +} + +static void kvm_s390_flic_unrealize(DeviceState *dev, Error **errp) +{ + KVMS390FLICState *flic_state = KVM_S390_FLIC(dev); + + unregister_savevm(DEVICE(flic_state), "s390-flic", flic_state); +} + +static void kvm_s390_flic_reset(DeviceState *dev) +{ + KVMS390FLICState *flic = KVM_S390_FLIC(dev); + struct kvm_device_attr attr = { + .group = KVM_DEV_FLIC_CLEAR_IRQS, + }; + int rc = 0; + + if (flic->fd == -1) { + return; + } + + flic_disable_wait_pfault(flic); + + rc = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); + if (rc) { + trace_flic_reset_failed(errno); + } + + flic_enable_pfault(flic); +} + +static void kvm_s390_flic_class_init(ObjectClass *oc, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(oc); + S390FLICStateClass *fsc = S390_FLIC_COMMON_CLASS(oc); + + dc->realize = kvm_s390_flic_realize; + dc->unrealize = kvm_s390_flic_unrealize; + dc->reset = kvm_s390_flic_reset; + fsc->register_io_adapter = kvm_s390_register_io_adapter; + fsc->io_adapter_map = kvm_s390_io_adapter_map; + fsc->add_adapter_routes = kvm_s390_add_adapter_routes; + fsc->release_adapter_routes = kvm_s390_release_adapter_routes; +} + +static const TypeInfo kvm_s390_flic_info = { + .name = TYPE_KVM_S390_FLIC, + .parent = TYPE_S390_FLIC_COMMON, + .instance_size = sizeof(KVMS390FLICState), + .class_init = kvm_s390_flic_class_init, +}; + +static void kvm_s390_flic_register_types(void) +{ + type_register_static(&kvm_s390_flic_info); +} + +type_init(kvm_s390_flic_register_types) diff --git a/hw/intc/slavio_intctl.c b/hw/intc/slavio_intctl.c index b10fb66b8d..f22aba0313 100644 --- a/hw/intc/slavio_intctl.c +++ b/hw/intc/slavio_intctl.c @@ -381,8 +381,7 @@ static const VMStateDescription vmstate_intctl_cpu = { .name ="slavio_intctl_cpu", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(intreg_pending, SLAVIO_CPUINTCTLState), VMSTATE_END_OF_LIST() } @@ -392,9 +391,8 @@ static const VMStateDescription vmstate_intctl = { .name ="slavio_intctl", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = vmstate_intctl_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(slaves, SLAVIO_INTCTLState, MAX_CPUS, 1, vmstate_intctl_cpu, SLAVIO_CPUINTCTLState), VMSTATE_UINT32(intregm_pending, SLAVIO_INTCTLState), diff --git a/hw/intc/xics.c b/hw/intc/xics.c index 64aabe753d..0fd2a84c7b 100644 --- a/hw/intc/xics.c +++ b/hw/intc/xics.c @@ -330,10 +330,9 @@ static const VMStateDescription vmstate_icp_server = { .name = "icp/server", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = icp_dispatch_pre_save, .post_load = icp_dispatch_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { /* Sanity check */ VMSTATE_UINT32(xirr, ICPState), VMSTATE_UINT8(pending_priority, ICPState), @@ -438,7 +437,7 @@ static void ics_set_irq(void *opaque, int srcno, int val) { ICSState *ics = (ICSState *)opaque; - if (ics->islsi[srcno]) { + if (ics->irqs[srcno].flags & XICS_FLAGS_IRQ_LSI) { set_irq_lsi(ics, srcno, val); } else { set_irq_msi(ics, srcno, val); @@ -475,7 +474,7 @@ static void ics_write_xive(ICSState *ics, int nr, int server, trace_xics_ics_write_xive(nr, srcno, server, priority); - if (ics->islsi[srcno]) { + if (ics->irqs[srcno].flags & XICS_FLAGS_IRQ_LSI) { write_xive_lsi(ics, srcno); } else { write_xive_msi(ics, srcno); @@ -497,7 +496,7 @@ static void ics_resend(ICSState *ics) for (i = 0; i < ics->nr_irqs; i++) { /* FIXME: filter by server#? */ - if (ics->islsi[i]) { + if (ics->irqs[i].flags & XICS_FLAGS_IRQ_LSI) { resend_lsi(ics, i); } else { resend_msi(ics, i); @@ -512,7 +511,7 @@ static void ics_eoi(ICSState *ics, int nr) trace_xics_ics_eoi(nr); - if (ics->islsi[srcno]) { + if (ics->irqs[srcno].flags & XICS_FLAGS_IRQ_LSI) { irq->status &= ~XICS_STATUS_SENT; } } @@ -521,11 +520,18 @@ static void ics_reset(DeviceState *dev) { ICSState *ics = ICS(dev); int i; + uint8_t flags[ics->nr_irqs]; + + for (i = 0; i < ics->nr_irqs; i++) { + flags[i] = ics->irqs[i].flags; + } memset(ics->irqs, 0, sizeof(ICSIRQState) * ics->nr_irqs); + for (i = 0; i < ics->nr_irqs; i++) { ics->irqs[i].priority = 0xff; ics->irqs[i].saved_priority = 0xff; + ics->irqs[i].flags = flags[i]; } } @@ -564,14 +570,14 @@ static int ics_dispatch_post_load(void *opaque, int version_id) static const VMStateDescription vmstate_ics_irq = { .name = "ics/irq", - .version_id = 1, + .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(server, ICSIRQState), VMSTATE_UINT8(priority, ICSIRQState), VMSTATE_UINT8(saved_priority, ICSIRQState), VMSTATE_UINT8(status, ICSIRQState), + VMSTATE_UINT8(flags, ICSIRQState), VMSTATE_END_OF_LIST() }, }; @@ -580,10 +586,9 @@ static const VMStateDescription vmstate_ics = { .name = "ics", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = ics_dispatch_pre_save, .post_load = ics_dispatch_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { /* Sanity check */ VMSTATE_UINT32_EQUAL(nr_irqs, ICSState), @@ -609,7 +614,6 @@ static void ics_realize(DeviceState *dev, Error **errp) return; } ics->irqs = g_malloc0(ics->nr_irqs * sizeof(ICSIRQState)); - ics->islsi = g_malloc0(ics->nr_irqs * sizeof(bool)); ics->qirqs = qemu_allocate_irqs(ics_set_irq, ics, ics->nr_irqs); } @@ -636,21 +640,166 @@ static const TypeInfo ics_info = { /* * Exported functions */ +static int xics_find_source(XICSState *icp, int irq) +{ + int sources = 1; + int src; + + /* FIXME: implement multiple sources */ + for (src = 0; src < sources; ++src) { + ICSState *ics = &icp->ics[src]; + if (ics_valid_irq(ics, irq)) { + return src; + } + } + + return -1; +} qemu_irq xics_get_qirq(XICSState *icp, int irq) { - if (!ics_valid_irq(icp->ics, irq)) { - return NULL; + int src = xics_find_source(icp, irq); + + if (src >= 0) { + ICSState *ics = &icp->ics[src]; + return ics->qirqs[irq - ics->offset]; } - return icp->ics->qirqs[irq - icp->ics->offset]; + return NULL; +} + +static void ics_set_irq_type(ICSState *ics, int srcno, bool lsi) +{ + assert(!(ics->irqs[srcno].flags & XICS_FLAGS_IRQ_MASK)); + + ics->irqs[srcno].flags |= + lsi ? XICS_FLAGS_IRQ_LSI : XICS_FLAGS_IRQ_MSI; } void xics_set_irq_type(XICSState *icp, int irq, bool lsi) { - assert(ics_valid_irq(icp->ics, irq)); + int src = xics_find_source(icp, irq); + ICSState *ics; - icp->ics->islsi[irq - icp->ics->offset] = lsi; + assert(src >= 0); + + ics = &icp->ics[src]; + ics_set_irq_type(ics, irq - ics->offset, lsi); +} + +#define ICS_IRQ_FREE(ics, srcno) \ + (!((ics)->irqs[(srcno)].flags & (XICS_FLAGS_IRQ_MASK))) + +static int ics_find_free_block(ICSState *ics, int num, int alignnum) +{ + int first, i; + + for (first = 0; first < ics->nr_irqs; first += alignnum) { + if (num > (ics->nr_irqs - first)) { + return -1; + } + for (i = first; i < first + num; ++i) { + if (!ICS_IRQ_FREE(ics, i)) { + break; + } + } + if (i == (first + num)) { + return first; + } + } + + return -1; +} + +int xics_alloc(XICSState *icp, int src, int irq_hint, bool lsi) +{ + ICSState *ics = &icp->ics[src]; + int irq; + + if (irq_hint) { + assert(src == xics_find_source(icp, irq_hint)); + if (!ICS_IRQ_FREE(ics, irq_hint - ics->offset)) { + trace_xics_alloc_failed_hint(src, irq_hint); + return -1; + } + irq = irq_hint; + } else { + irq = ics_find_free_block(ics, 1, 1); + if (irq < 0) { + trace_xics_alloc_failed_no_left(src); + return -1; + } + irq += ics->offset; + } + + ics_set_irq_type(ics, irq - ics->offset, lsi); + trace_xics_alloc(src, irq); + + return irq; +} + +/* + * Allocate block of consequtive IRQs, returns a number of the first. + * If align==true, aligns the first IRQ number to num. + */ +int xics_alloc_block(XICSState *icp, int src, int num, bool lsi, bool align) +{ + int i, first = -1; + ICSState *ics = &icp->ics[src]; + + assert(src == 0); + /* + * MSIMesage::data is used for storing VIRQ so + * it has to be aligned to num to support multiple + * MSI vectors. MSI-X is not affected by this. + * The hint is used for the first IRQ, the rest should + * be allocated continuously. + */ + if (align) { + assert((num == 1) || (num == 2) || (num == 4) || + (num == 8) || (num == 16) || (num == 32)); + first = ics_find_free_block(ics, num, num); + } else { + first = ics_find_free_block(ics, num, 1); + } + + if (first >= 0) { + for (i = first; i < first + num; ++i) { + ics_set_irq_type(ics, i, lsi); + } + } + first += ics->offset; + + trace_xics_alloc_block(src, first, num, lsi, align); + + return first; +} + +static void ics_free(ICSState *ics, int srcno, int num) +{ + int i; + + for (i = srcno; i < srcno + num; ++i) { + if (ICS_IRQ_FREE(ics, i)) { + trace_xics_ics_free_warn(ics - ics->icp->ics, i + ics->offset); + } + memset(&ics->irqs[i], 0, sizeof(ICSIRQState)); + } +} + +void xics_free(XICSState *icp, int irq, int num) +{ + int src = xics_find_source(icp, irq); + + if (src >= 0) { + ICSState *ics = &icp->ics[src]; + + /* FIXME: implement multiple sources */ + assert(src == 0); + + trace_xics_ics_free(ics - icp->ics, irq, num); + ics_free(ics, irq - ics->offset, num); + } } /* @@ -869,10 +1018,10 @@ static void xics_realize(DeviceState *dev, Error **errp) } /* Registration of global state belongs into realize */ - spapr_rtas_register("ibm,set-xive", rtas_set_xive); - spapr_rtas_register("ibm,get-xive", rtas_get_xive); - spapr_rtas_register("ibm,int-off", rtas_int_off); - spapr_rtas_register("ibm,int-on", rtas_int_on); + spapr_rtas_register(RTAS_IBM_SET_XIVE, "ibm,set-xive", rtas_set_xive); + spapr_rtas_register(RTAS_IBM_GET_XIVE, "ibm,get-xive", rtas_get_xive); + spapr_rtas_register(RTAS_IBM_INT_OFF, "ibm,int-off", rtas_int_off); + spapr_rtas_register(RTAS_IBM_INT_ON, "ibm,int-on", rtas_int_on); spapr_register_hypercall(H_CPPR, h_cppr); spapr_register_hypercall(H_IPI, h_ipi); diff --git a/hw/intc/xics_kvm.c b/hw/intc/xics_kvm.c index c93dae053d..20b19e9d4f 100644 --- a/hw/intc/xics_kvm.c +++ b/hw/intc/xics_kvm.c @@ -38,10 +38,6 @@ typedef struct KVMXICSState { XICSState parent_obj; - uint32_t set_xive_token; - uint32_t get_xive_token; - uint32_t int_off_token; - uint32_t int_on_token; int kernel_xics_fd; } KVMXICSState; @@ -224,7 +220,7 @@ static int ics_set_kvm_state(ICSState *ics, int version_id) state |= KVM_XICS_MASKED; } - if (ics->islsi[i]) { + if (ics->irqs[i].flags & XICS_FLAGS_IRQ_LSI) { state |= KVM_XICS_LEVEL_SENSITIVE; if (irq->status & XICS_STATUS_ASSERTED) { state |= KVM_XICS_PENDING; @@ -253,7 +249,7 @@ static void ics_kvm_set_irq(void *opaque, int srcno, int val) int rc; args.irq = srcno + ics->offset; - if (!ics->islsi[srcno]) { + if (ics->irqs[srcno].flags & XICS_FLAGS_IRQ_MSI) { if (!val) { return; } @@ -271,11 +267,18 @@ static void ics_kvm_reset(DeviceState *dev) { ICSState *ics = ICS(dev); int i; + uint8_t flags[ics->nr_irqs]; + + for (i = 0; i < ics->nr_irqs; i++) { + flags[i] = ics->irqs[i].flags; + } memset(ics->irqs, 0, sizeof(ICSIRQState) * ics->nr_irqs); + for (i = 0; i < ics->nr_irqs; i++) { ics->irqs[i].priority = 0xff; ics->irqs[i].saved_priority = 0xff; + ics->irqs[i].flags = flags[i]; } ics_set_kvm_state(ics, 1); @@ -290,7 +293,6 @@ static void ics_kvm_realize(DeviceState *dev, Error **errp) return; } ics->irqs = g_malloc0(ics->nr_irqs * sizeof(ICSIRQState)); - ics->islsi = g_malloc0(ics->nr_irqs * sizeof(bool)); ics->qirqs = qemu_allocate_irqs(ics_kvm_set_irq, ics, ics->nr_irqs); } @@ -331,15 +333,11 @@ static void xics_kvm_cpu_setup(XICSState *icp, PowerPCCPU *cpu) if (icpkvm->kernel_xics_fd != -1) { int ret; - struct kvm_enable_cap xics_enable_cap = { - .cap = KVM_CAP_IRQ_XICS, - .flags = 0, - .args = {icpkvm->kernel_xics_fd, kvm_arch_vcpu_id(cs), 0, 0}, - }; ss->cs = cs; - ret = kvm_vcpu_ioctl(ss->cs, KVM_ENABLE_CAP, &xics_enable_cap); + ret = kvm_vcpu_enable_cap(cs, KVM_CAP_IRQ_XICS, 0, + icpkvm->kernel_xics_fd, kvm_arch_vcpu_id(cs)); if (ret < 0) { error_report("Unable to connect CPU%ld to kernel XICS: %s", kvm_arch_vcpu_id(cs), strerror(errno)); @@ -396,32 +394,30 @@ static void xics_kvm_realize(DeviceState *dev, Error **errp) goto fail; } - icpkvm->set_xive_token = spapr_rtas_register("ibm,set-xive", rtas_dummy); - icpkvm->get_xive_token = spapr_rtas_register("ibm,get-xive", rtas_dummy); - icpkvm->int_off_token = spapr_rtas_register("ibm,int-off", rtas_dummy); - icpkvm->int_on_token = spapr_rtas_register("ibm,int-on", rtas_dummy); + spapr_rtas_register(RTAS_IBM_SET_XIVE, "ibm,set-xive", rtas_dummy); + spapr_rtas_register(RTAS_IBM_GET_XIVE, "ibm,get-xive", rtas_dummy); + spapr_rtas_register(RTAS_IBM_INT_OFF, "ibm,int-off", rtas_dummy); + spapr_rtas_register(RTAS_IBM_INT_ON, "ibm,int-on", rtas_dummy); - rc = kvmppc_define_rtas_kernel_token(icpkvm->set_xive_token, - "ibm,set-xive"); + rc = kvmppc_define_rtas_kernel_token(RTAS_IBM_SET_XIVE, "ibm,set-xive"); if (rc < 0) { error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,set-xive"); goto fail; } - rc = kvmppc_define_rtas_kernel_token(icpkvm->get_xive_token, - "ibm,get-xive"); + rc = kvmppc_define_rtas_kernel_token(RTAS_IBM_GET_XIVE, "ibm,get-xive"); if (rc < 0) { error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,get-xive"); goto fail; } - rc = kvmppc_define_rtas_kernel_token(icpkvm->int_on_token, "ibm,int-on"); + rc = kvmppc_define_rtas_kernel_token(RTAS_IBM_INT_ON, "ibm,int-on"); if (rc < 0) { error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,int-on"); goto fail; } - rc = kvmppc_define_rtas_kernel_token(icpkvm->int_off_token, "ibm,int-off"); + rc = kvmppc_define_rtas_kernel_token(RTAS_IBM_INT_OFF, "ibm,int-off"); if (rc < 0) { error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,int-off"); goto fail; diff --git a/hw/intc/xilinx_intc.c b/hw/intc/xilinx_intc.c index 1b228ff4e0..12804ab729 100644 --- a/hw/intc/xilinx_intc.c +++ b/hw/intc/xilinx_intc.c @@ -121,6 +121,9 @@ pic_write(void *opaque, hwaddr addr, case R_CIE: p->regs[R_IER] &= ~value; /* Atomic clear ie. */ break; + case R_MER: + p->regs[R_MER] = value & 0x3; + break; case R_ISR: if ((p->regs[R_MER] & 2)) { break; @@ -158,18 +161,16 @@ static void irq_handler(void *opaque, int irq, int level) update_irq(p); } -static int xilinx_intc_init(SysBusDevice *sbd) +static void xilinx_intc_init(Object *obj) { - DeviceState *dev = DEVICE(sbd); - struct xlx_pic *p = XILINX_INTC(dev); + struct xlx_pic *p = XILINX_INTC(obj); - qdev_init_gpio_in(dev, irq_handler, 32); - sysbus_init_irq(sbd, &p->parent_irq); + qdev_init_gpio_in(DEVICE(obj), irq_handler, 32); + sysbus_init_irq(SYS_BUS_DEVICE(obj), &p->parent_irq); - memory_region_init_io(&p->mmio, OBJECT(p), &pic_ops, p, "xlnx.xps-intc", + memory_region_init_io(&p->mmio, obj, &pic_ops, p, "xlnx.xps-intc", R_MAX * 4); - sysbus_init_mmio(sbd, &p->mmio); - return 0; + sysbus_init_mmio(SYS_BUS_DEVICE(obj), &p->mmio); } static Property xilinx_intc_properties[] = { @@ -180,9 +181,7 @@ static Property xilinx_intc_properties[] = { static void xilinx_intc_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); - k->init = xilinx_intc_init; dc->props = xilinx_intc_properties; } @@ -190,6 +189,7 @@ static const TypeInfo xilinx_intc_info = { .name = TYPE_XILINX_INTC, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(struct xlx_pic), + .instance_init = xilinx_intc_init, .class_init = xilinx_intc_class_init, }; diff --git a/hw/ipack/ipack.c b/hw/ipack/ipack.c index ed63d2ac61..59bfe2869e 100644 --- a/hw/ipack/ipack.c +++ b/hw/ipack/ipack.c @@ -66,7 +66,7 @@ static void ipack_device_unrealize(DeviceState *dev, Error **errp) return; } - qemu_free_irqs(idev->irq); + qemu_free_irqs(idev->irq, 2); } static Property ipack_device_props[] = { @@ -89,8 +89,7 @@ const VMStateDescription vmstate_ipack_device = { .name = "ipack_device", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(slot, IPackDevice), VMSTATE_END_OF_LIST() } diff --git a/hw/ipack/tpci200.c b/hw/ipack/tpci200.c index e1b69b4552..b7031a0b13 100644 --- a/hw/ipack/tpci200.c +++ b/hw/ipack/tpci200.c @@ -613,24 +613,11 @@ static int tpci200_initfn(PCIDevice *pci_dev) return 0; } -static void tpci200_exitfn(PCIDevice *pci_dev) -{ - TPCI200State *s = TPCI200(pci_dev); - - memory_region_destroy(&s->mmio); - memory_region_destroy(&s->io); - memory_region_destroy(&s->las0); - memory_region_destroy(&s->las1); - memory_region_destroy(&s->las2); - memory_region_destroy(&s->las3); -} - static const VMStateDescription vmstate_tpci200 = { .name = "tpci200", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, TPCI200State), VMSTATE_BOOL_ARRAY(big_endian, TPCI200State, 3), VMSTATE_UINT8_ARRAY(ctrl, TPCI200State, N_MODULES), @@ -646,7 +633,6 @@ static void tpci200_class_init(ObjectClass *klass, void *data) PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->init = tpci200_initfn; - k->exit = tpci200_exitfn; k->vendor_id = PCI_VENDOR_ID_TEWS; k->device_id = PCI_DEVICE_ID_TEWS_TPCI200; k->class_id = PCI_CLASS_BRIDGE_OTHER; diff --git a/hw/isa/apm.c b/hw/isa/apm.c index f97e7a0c24..26ab170215 100644 --- a/hw/isa/apm.c +++ b/hw/isa/apm.c @@ -41,7 +41,8 @@ static void apm_ioport_writeb(void *opaque, hwaddr addr, uint64_t val, { APMState *apm = opaque; addr &= 1; - APM_DPRINTF("apm_ioport_writeb addr=0x%x val=0x%02x\n", addr, val); + APM_DPRINTF("apm_ioport_writeb addr=0x%" HWADDR_PRIx + " val=0x%02" PRIx64 "\n", addr, val); if (addr == 0) { apm->apmc = val; @@ -64,7 +65,7 @@ static uint64_t apm_ioport_readb(void *opaque, hwaddr addr, unsigned size) } else { val = apm->apms; } - APM_DPRINTF("apm_ioport_readb addr=0x%x val=0x%02x\n", addr, val); + APM_DPRINTF("apm_ioport_readb addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, val); return val; } @@ -72,7 +73,6 @@ const VMStateDescription vmstate_apm = { .name = "APM State", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT8(apmc, APMState), VMSTATE_UINT8(apms, APMState), diff --git a/hw/isa/isa-bus.c b/hw/isa/isa-bus.c index 55d01008d3..cc85e538b1 100644 --- a/hw/isa/isa-bus.c +++ b/hw/isa/isa-bus.c @@ -50,7 +50,7 @@ ISABus *isa_bus_new(DeviceState *dev, MemoryRegion *address_space_io) fprintf(stderr, "Can't create a second ISA bus\n"); return NULL; } - if (NULL == dev) { + if (!dev) { dev = qdev_create(NULL, "isabus-bridge"); qdev_init_nofail(dev); } @@ -108,15 +108,20 @@ void isa_register_portio_list(ISADevice *dev, uint16_t start, const MemoryRegionPortio *pio_start, void *opaque, const char *name) { - PortioList *piolist = g_new(PortioList, 1); + PortioList piolist; /* START is how we should treat DEV, regardless of the actual contents of the portio array. This is how the old code actually handled e.g. the FDC device. */ isa_init_ioport(dev, start); - portio_list_init(piolist, OBJECT(dev), pio_start, opaque, name); - portio_list_add(piolist, isabus->address_space_io, start); + /* FIXME: the device should store created PortioList in its state. Note + that DEV can be NULL here and that single device can register several + portio lists. Current implementation is leaking memory allocated + in portio_list_init. The leak is not critical because it happens only + at initialization time. */ + portio_list_init(&piolist, OBJECT(dev), pio_start, opaque, name); + portio_list_add(&piolist, isabus->address_space_io, start); } static void isa_device_init(Object *obj) diff --git a/hw/isa/lpc_ich9.c b/hw/isa/lpc_ich9.c index 51ce12dad6..530b074551 100644 --- a/hw/isa/lpc_ich9.c +++ b/hw/isa/lpc_ich9.c @@ -7,7 +7,7 @@ * VA Linux Systems Japan K.K. * Copyright (C) 2012 Jason Baron <jbaron@redhat.com> * - * This is based on piix_pci.c, but heavily modified. + * This is based on piix.c, but heavily modified. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -563,7 +563,14 @@ static void ich9_lpc_add_properties(ICH9LPCState *lpc) ich9_pm_add_properties(OBJECT(lpc), &lpc->pm, NULL); } -static int ich9_lpc_initfn(PCIDevice *d) +static void ich9_lpc_initfn(Object *obj) +{ + ICH9LPCState *lpc = ICH9_LPC_DEVICE(obj); + + ich9_lpc_add_properties(lpc); +} + +static int ich9_lpc_init(PCIDevice *d) { ICH9LPCState *lpc = ICH9_LPC_DEVICE(d); ISABus *isa_bus; @@ -589,10 +596,22 @@ static int ich9_lpc_initfn(PCIDevice *d) memory_region_add_subregion_overlap(pci_address_space_io(d), ICH9_RST_CNT_IOPORT, &lpc->rst_cnt_mem, 1); + return 0; +} - ich9_lpc_add_properties(lpc); +static void ich9_device_plug_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + ICH9LPCState *lpc = ICH9_LPC_DEVICE(hotplug_dev); - return 0; + ich9_pm_device_plug_cb(&lpc->pm, dev, errp); +} + +static void ich9_device_unplug_request_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) +{ + error_setg(errp, "acpi: device unplug request for not supported device" + " type: %s", object_get_typename(OBJECT(dev))); } static bool ich9_rst_cnt_needed(void *opaque) @@ -616,7 +635,6 @@ static const VMStateDescription vmstate_ich9_lpc = { .name = "ICH9LPC", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = ich9_lpc_post_load, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(d, ICH9LPCState), @@ -639,10 +657,12 @@ static void ich9_lpc_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); + AcpiDeviceIfClass *adevc = ACPI_DEVICE_IF_CLASS(klass); set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); dc->reset = ich9_lpc_reset; - k->init = ich9_lpc_initfn; + k->init = ich9_lpc_init; dc->vmsd = &vmstate_ich9_lpc; k->config_write = ich9_lpc_config_write; dc->desc = "ICH9 LPC bridge"; @@ -655,13 +675,22 @@ static void ich9_lpc_class_init(ObjectClass *klass, void *data) * pc_q35_init() */ dc->cannot_instantiate_with_device_add_yet = true; + hc->plug = ich9_device_plug_cb; + hc->unplug_request = ich9_device_unplug_request_cb; + adevc->ospm_status = ich9_pm_ospm_status; } static const TypeInfo ich9_lpc_info = { .name = TYPE_ICH9_LPC_DEVICE, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(struct ICH9LPCState), + .instance_init = ich9_lpc_initfn, .class_init = ich9_lpc_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { TYPE_ACPI_DEVICE_IF }, + { } + } }; static void ich9_lpc_register(void) diff --git a/hw/isa/pc87312.c b/hw/isa/pc87312.c index b352b491ac..40a11060a5 100644 --- a/hw/isa/pc87312.c +++ b/hw/isa/pc87312.c @@ -25,6 +25,7 @@ #include "hw/isa/pc87312.h" #include "qemu/error-report.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "sysemu/sysemu.h" #include "sysemu/char.h" @@ -86,11 +87,6 @@ static inline uint32_t get_parallel_irq(PC87312State *s) } } -static inline bool is_parallel_epp(PC87312State *s) -{ - return s->regs[REG_PTR] & PTR_EPP_MODE; -} - /* UARTs */ @@ -325,11 +321,13 @@ static void pc87312_realize(DeviceState *dev, Error **errp) qdev_prop_set_uint32(d, "irq", 6); drive = drive_get(IF_FLOPPY, 0, 0); if (drive != NULL) { - qdev_prop_set_drive_nofail(d, "driveA", drive->bdrv); + qdev_prop_set_drive_nofail(d, "driveA", + blk_by_legacy_dinfo(drive)); } drive = drive_get(IF_FLOPPY, 0, 1); if (drive != NULL) { - qdev_prop_set_drive_nofail(d, "driveB", drive->bdrv); + qdev_prop_set_drive_nofail(d, "driveB", + blk_by_legacy_dinfo(drive)); } qdev_init_nofail(d); s->fdc.dev = isa; diff --git a/hw/isa/piix4.c b/hw/isa/piix4.c index 492cd22fcf..1aa17d7cf6 100644 --- a/hw/isa/piix4.c +++ b/hw/isa/piix4.c @@ -76,8 +76,7 @@ static const VMStateDescription vmstate_piix4 = { .name = "PIIX4", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PIIX4State), VMSTATE_END_OF_LIST() } diff --git a/hw/isa/vt82c686.c b/hw/isa/vt82c686.c index 1a93afda4f..e0c235c3c2 100644 --- a/hw/isa/vt82c686.c +++ b/hw/isa/vt82c686.c @@ -230,9 +230,8 @@ static const VMStateDescription vmstate_acpi = { .name = "vt82c686b_pm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = vmstate_acpi_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, VT686PMState), VMSTATE_UINT16(ar.pm1.evt.sts, VT686PMState), VMSTATE_UINT16(ar.pm1.evt.en, VT686PMState), @@ -418,8 +417,7 @@ static const VMStateDescription vmstate_via = { .name = "vt82c686b", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, VT82C686BState), VMSTATE_END_OF_LIST() } diff --git a/hw/lm32/lm32_boards.c b/hw/lm32/lm32_boards.c index 5e22e9b4d7..af0abdbed9 100644 --- a/hw/lm32/lm32_boards.c +++ b/hw/lm32/lm32_boards.c @@ -23,7 +23,7 @@ #include "hw/devices.h" #include "hw/boards.h" #include "hw/loader.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "elf.h" #include "lm32_hwsetup.h" #include "lm32.h" @@ -69,10 +69,10 @@ static void main_cpu_reset(void *opaque) env->deba = reset_info->flash_base; } -static void lm32_evr_init(QEMUMachineInitArgs *args) +static void lm32_evr_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; LM32CPU *cpu; CPULM32State *env; DriveInfo *dinfo; @@ -111,16 +111,17 @@ static void lm32_evr_init(QEMUMachineInitArgs *args) reset_info->flash_base = flash_base; - memory_region_init_ram(phys_ram, NULL, "lm32_evr.sdram", ram_size); + memory_region_init_ram(phys_ram, NULL, "lm32_evr.sdram", ram_size, + &error_abort); vmstate_register_ram_global(phys_ram); memory_region_add_subregion(address_space_mem, ram_base, phys_ram); dinfo = drive_get(IF_PFLASH, 0, 0); /* Spansion S29NS128P */ pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size, - dinfo ? dinfo->bdrv : NULL, flash_sector_size, - flash_size / flash_sector_size, 1, 2, - 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1); + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + flash_sector_size, flash_size / flash_sector_size, + 1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1); /* create irq lines */ cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1); @@ -162,12 +163,12 @@ static void lm32_evr_init(QEMUMachineInitArgs *args) qemu_register_reset(main_cpu_reset, reset_info); } -static void lm32_uclinux_init(QEMUMachineInitArgs *args) +static void lm32_uclinux_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; LM32CPU *cpu; CPULM32State *env; DriveInfo *dinfo; @@ -213,16 +214,17 @@ static void lm32_uclinux_init(QEMUMachineInitArgs *args) reset_info->flash_base = flash_base; - memory_region_init_ram(phys_ram, NULL, "lm32_uclinux.sdram", ram_size); + memory_region_init_ram(phys_ram, NULL, "lm32_uclinux.sdram", ram_size, + &error_abort); vmstate_register_ram_global(phys_ram); memory_region_add_subregion(address_space_mem, ram_base, phys_ram); dinfo = drive_get(IF_PFLASH, 0, 0); /* Spansion S29NS128P */ pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size, - dinfo ? dinfo->bdrv : NULL, flash_sector_size, - flash_size / flash_sector_size, 1, 2, - 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1); + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + flash_sector_size, flash_size / flash_sector_size, + 1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1); /* create irq lines */ cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1); diff --git a/hw/lm32/milkymist.c b/hw/lm32/milkymist.c index baf234ce04..256c1029ce 100644 --- a/hw/lm32/milkymist.c +++ b/hw/lm32/milkymist.c @@ -26,7 +26,7 @@ #include "hw/boards.h" #include "hw/loader.h" #include "elf.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "milkymist-hw.h" #include "lm32.h" #include "exec/address-spaces.h" @@ -74,12 +74,12 @@ static void main_cpu_reset(void *opaque) } static void -milkymist_init(QEMUMachineInitArgs *args) +milkymist_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; LM32CPU *cpu; CPULM32State *env; int kernel_size; @@ -118,16 +118,17 @@ milkymist_init(QEMUMachineInitArgs *args) cpu_lm32_set_phys_msb_ignore(env, 1); - memory_region_init_ram(phys_sdram, NULL, "milkymist.sdram", sdram_size); + memory_region_init_ram(phys_sdram, NULL, "milkymist.sdram", sdram_size, + &error_abort); vmstate_register_ram_global(phys_sdram); memory_region_add_subregion(address_space_mem, sdram_base, phys_sdram); dinfo = drive_get(IF_PFLASH, 0, 0); /* Numonyx JS28F256J3F105 */ pflash_cfi01_register(flash_base, NULL, "milkymist.flash", flash_size, - dinfo ? dinfo->bdrv : NULL, flash_sector_size, - flash_size / flash_sector_size, 2, - 0x00, 0x89, 0x00, 0x1d, 1); + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + flash_sector_size, flash_size / flash_sector_size, + 2, 0x00, 0x89, 0x00, 0x1d, 1); /* create irq lines */ cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1); diff --git a/hw/m68k/an5206.c b/hw/m68k/an5206.c index 24f2068559..f1f13504c0 100644 --- a/hw/m68k/an5206.c +++ b/hw/m68k/an5206.c @@ -20,11 +20,11 @@ /* Board init. */ -static void an5206_init(QEMUMachineInitArgs *args) +static void an5206_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; M68kCPU *cpu; CPUM68KState *env; int kernel_size; @@ -50,12 +50,12 @@ static void an5206_init(QEMUMachineInitArgs *args) env->rambar0 = AN5206_RAMBAR_ADDR | 1; /* DRAM at address zero */ - memory_region_init_ram(ram, NULL, "an5206.ram", ram_size); + memory_region_init_ram(ram, NULL, "an5206.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0, ram); /* Internal SRAM. */ - memory_region_init_ram(sram, NULL, "an5206.sram", 512); + memory_region_init_ram(sram, NULL, "an5206.sram", 512, &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(address_space_mem, AN5206_RAMBAR_ADDR, sram); @@ -74,7 +74,8 @@ static void an5206_init(QEMUMachineInitArgs *args) NULL, NULL, 1, ELF_MACHINE, 0); entry = elf_entry; if (kernel_size < 0) { - kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); + kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL, + NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR, diff --git a/hw/m68k/dummy_m68k.c b/hw/m68k/dummy_m68k.c index 86e2e6e065..facd561efa 100644 --- a/hw/m68k/dummy_m68k.c +++ b/hw/m68k/dummy_m68k.c @@ -16,11 +16,11 @@ /* Board init. */ -static void dummy_m68k_init(QEMUMachineInitArgs *args) +static void dummy_m68k_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; CPUM68KState *env; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -40,7 +40,7 @@ static void dummy_m68k_init(QEMUMachineInitArgs *args) env->vbr = 0; /* RAM at address zero */ - memory_region_init_ram(ram, NULL, "dummy_m68k.ram", ram_size); + memory_region_init_ram(ram, NULL, "dummy_m68k.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0, ram); @@ -50,7 +50,8 @@ static void dummy_m68k_init(QEMUMachineInitArgs *args) NULL, NULL, 1, ELF_MACHINE, 0); entry = elf_entry; if (kernel_size < 0) { - kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); + kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL, + NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, diff --git a/hw/m68k/mcf5208.c b/hw/m68k/mcf5208.c index 6e30c0b393..a01a4458e6 100644 --- a/hw/m68k/mcf5208.c +++ b/hw/m68k/mcf5208.c @@ -188,11 +188,11 @@ static void mcf5208_sys_init(MemoryRegion *address_space, qemu_irq *pic) } } -static void mcf5208evb_init(QEMUMachineInitArgs *args) +static void mcf5208evb_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; M68kCPU *cpu; CPUM68KState *env; int kernel_size; @@ -218,12 +218,12 @@ static void mcf5208evb_init(QEMUMachineInitArgs *args) /* TODO: Configure BARs. */ /* DRAM at 0x40000000 */ - memory_region_init_ram(ram, NULL, "mcf5208.ram", ram_size); + memory_region_init_ram(ram, NULL, "mcf5208.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0x40000000, ram); /* Internal SRAM. */ - memory_region_init_ram(sram, NULL, "mcf5208.sram", 16384); + memory_region_init_ram(sram, NULL, "mcf5208.sram", 16384, &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(address_space_mem, 0x80000000, sram); @@ -279,7 +279,8 @@ static void mcf5208evb_init(QEMUMachineInitArgs *args) NULL, NULL, 1, ELF_MACHINE, 0); entry = elf_entry; if (kernel_size < 0) { - kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); + kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL, + NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, 0x40000000, diff --git a/hw/mem/Makefile.objs b/hw/mem/Makefile.objs new file mode 100644 index 0000000000..b000fb42bf --- /dev/null +++ b/hw/mem/Makefile.objs @@ -0,0 +1 @@ +common-obj-$(CONFIG_MEM_HOTPLUG) += pc-dimm.o diff --git a/hw/mem/pc-dimm.c b/hw/mem/pc-dimm.c new file mode 100644 index 0000000000..d431834030 --- /dev/null +++ b/hw/mem/pc-dimm.c @@ -0,0 +1,308 @@ +/* + * Dimm device for Memory Hotplug + * + * Copyright ProfitBricks GmbH 2012 + * Copyright (C) 2014 Red Hat Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see <http://www.gnu.org/licenses/> + */ + +#include "hw/mem/pc-dimm.h" +#include "qemu/config-file.h" +#include "qapi/visitor.h" +#include "qemu/range.h" + +int qmp_pc_dimm_device_list(Object *obj, void *opaque) +{ + MemoryDeviceInfoList ***prev = opaque; + + if (object_dynamic_cast(obj, TYPE_PC_DIMM)) { + DeviceState *dev = DEVICE(obj); + + if (dev->realized) { + MemoryDeviceInfoList *elem = g_new0(MemoryDeviceInfoList, 1); + MemoryDeviceInfo *info = g_new0(MemoryDeviceInfo, 1); + PCDIMMDeviceInfo *di = g_new0(PCDIMMDeviceInfo, 1); + DeviceClass *dc = DEVICE_GET_CLASS(obj); + PCDIMMDevice *dimm = PC_DIMM(obj); + + if (dev->id) { + di->has_id = true; + di->id = g_strdup(dev->id); + } + di->hotplugged = dev->hotplugged; + di->hotpluggable = dc->hotpluggable; + di->addr = dimm->addr; + di->slot = dimm->slot; + di->node = dimm->node; + di->size = object_property_get_int(OBJECT(dimm), PC_DIMM_SIZE_PROP, + NULL); + di->memdev = object_get_canonical_path(OBJECT(dimm->hostmem)); + + info->dimm = di; + elem->value = info; + elem->next = NULL; + **prev = elem; + *prev = &elem->next; + } + } + + object_child_foreach(obj, qmp_pc_dimm_device_list, opaque); + return 0; +} + +static int pc_dimm_slot2bitmap(Object *obj, void *opaque) +{ + unsigned long *bitmap = opaque; + + if (object_dynamic_cast(obj, TYPE_PC_DIMM)) { + DeviceState *dev = DEVICE(obj); + if (dev->realized) { /* count only realized DIMMs */ + PCDIMMDevice *d = PC_DIMM(obj); + set_bit(d->slot, bitmap); + } + } + + object_child_foreach(obj, pc_dimm_slot2bitmap, opaque); + return 0; +} + +int pc_dimm_get_free_slot(const int *hint, int max_slots, Error **errp) +{ + unsigned long *bitmap = bitmap_new(max_slots); + int slot = 0; + + object_child_foreach(qdev_get_machine(), pc_dimm_slot2bitmap, bitmap); + + /* check if requested slot is not occupied */ + if (hint) { + if (*hint >= max_slots) { + error_setg(errp, "invalid slot# %d, should be less than %d", + *hint, max_slots); + } else if (!test_bit(*hint, bitmap)) { + slot = *hint; + } else { + error_setg(errp, "slot %d is busy", *hint); + } + goto out; + } + + /* search for free slot */ + slot = find_first_zero_bit(bitmap, max_slots); + if (slot == max_slots) { + error_setg(errp, "no free slots available"); + } +out: + g_free(bitmap); + return slot; +} + +static gint pc_dimm_addr_sort(gconstpointer a, gconstpointer b) +{ + PCDIMMDevice *x = PC_DIMM(a); + PCDIMMDevice *y = PC_DIMM(b); + Int128 diff = int128_sub(int128_make64(x->addr), int128_make64(y->addr)); + + if (int128_lt(diff, int128_zero())) { + return -1; + } else if (int128_gt(diff, int128_zero())) { + return 1; + } + return 0; +} + +static int pc_dimm_built_list(Object *obj, void *opaque) +{ + GSList **list = opaque; + + if (object_dynamic_cast(obj, TYPE_PC_DIMM)) { + DeviceState *dev = DEVICE(obj); + if (dev->realized) { /* only realized DIMMs matter */ + *list = g_slist_insert_sorted(*list, dev, pc_dimm_addr_sort); + } + } + + object_child_foreach(obj, pc_dimm_built_list, opaque); + return 0; +} + +uint64_t pc_dimm_get_free_addr(uint64_t address_space_start, + uint64_t address_space_size, + uint64_t *hint, uint64_t align, uint64_t size, + Error **errp) +{ + GSList *list = NULL, *item; + uint64_t new_addr, ret = 0; + uint64_t address_space_end = address_space_start + address_space_size; + + g_assert(QEMU_ALIGN_UP(address_space_start, align) == address_space_start); + g_assert(QEMU_ALIGN_UP(address_space_size, align) == address_space_size); + + if (!address_space_size) { + error_setg(errp, "memory hotplug is not enabled, " + "please add maxmem option"); + goto out; + } + + if (hint && QEMU_ALIGN_UP(*hint, align) != *hint) { + error_setg(errp, "address must be aligned to 0x%" PRIx64 " bytes", + align); + goto out; + } + + if (QEMU_ALIGN_UP(size, align) != size) { + error_setg(errp, "backend memory size must be multiple of 0x%" + PRIx64, align); + goto out; + } + + assert(address_space_end > address_space_start); + object_child_foreach(qdev_get_machine(), pc_dimm_built_list, &list); + + if (hint) { + new_addr = *hint; + } else { + new_addr = address_space_start; + } + + /* find address range that will fit new DIMM */ + for (item = list; item; item = g_slist_next(item)) { + PCDIMMDevice *dimm = item->data; + uint64_t dimm_size = object_property_get_int(OBJECT(dimm), + PC_DIMM_SIZE_PROP, + errp); + if (errp && *errp) { + goto out; + } + + if (ranges_overlap(dimm->addr, dimm_size, new_addr, size)) { + if (hint) { + DeviceState *d = DEVICE(dimm); + error_setg(errp, "address range conflicts with '%s'", d->id); + goto out; + } + new_addr = QEMU_ALIGN_UP(dimm->addr + dimm_size, align); + } + } + ret = new_addr; + + if (new_addr < address_space_start) { + error_setg(errp, "can't add memory [0x%" PRIx64 ":0x%" PRIx64 + "] at 0x%" PRIx64, new_addr, size, address_space_start); + } else if ((new_addr + size) > address_space_end) { + error_setg(errp, "can't add memory [0x%" PRIx64 ":0x%" PRIx64 + "] beyond 0x%" PRIx64, new_addr, size, address_space_end); + } + +out: + g_slist_free(list); + return ret; +} + +static Property pc_dimm_properties[] = { + DEFINE_PROP_UINT64(PC_DIMM_ADDR_PROP, PCDIMMDevice, addr, 0), + DEFINE_PROP_UINT32(PC_DIMM_NODE_PROP, PCDIMMDevice, node, 0), + DEFINE_PROP_INT32(PC_DIMM_SLOT_PROP, PCDIMMDevice, slot, + PC_DIMM_UNASSIGNED_SLOT), + DEFINE_PROP_END_OF_LIST(), +}; + +static void pc_dimm_get_size(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + int64_t value; + MemoryRegion *mr; + PCDIMMDevice *dimm = PC_DIMM(obj); + + mr = host_memory_backend_get_memory(dimm->hostmem, errp); + value = memory_region_size(mr); + + visit_type_int(v, &value, name, errp); +} + +static void pc_dimm_check_memdev_is_busy(Object *obj, const char *name, + Object *val, Error **errp) +{ + MemoryRegion *mr; + + mr = host_memory_backend_get_memory(MEMORY_BACKEND(val), errp); + if (memory_region_is_mapped(mr)) { + char *path = object_get_canonical_path_component(val); + error_setg(errp, "can't use already busy memdev: %s", path); + g_free(path); + } else { + qdev_prop_allow_set_link_before_realize(obj, name, val, errp); + } +} + +static void pc_dimm_init(Object *obj) +{ + PCDIMMDevice *dimm = PC_DIMM(obj); + + object_property_add(obj, PC_DIMM_SIZE_PROP, "int", pc_dimm_get_size, + NULL, NULL, NULL, &error_abort); + object_property_add_link(obj, PC_DIMM_MEMDEV_PROP, TYPE_MEMORY_BACKEND, + (Object **)&dimm->hostmem, + pc_dimm_check_memdev_is_busy, + OBJ_PROP_LINK_UNREF_ON_RELEASE, + &error_abort); +} + +static void pc_dimm_realize(DeviceState *dev, Error **errp) +{ + PCDIMMDevice *dimm = PC_DIMM(dev); + + if (!dimm->hostmem) { + error_setg(errp, "'" PC_DIMM_MEMDEV_PROP "' property is not set"); + return; + } + if ((nb_numa_nodes > 0) && (dimm->node >= nb_numa_nodes)) { + error_setg(errp, "'DIMM property " PC_DIMM_NODE_PROP " has value %" + PRIu32 "' which exceeds the number of numa nodes: %d", + dimm->node, nb_numa_nodes); + return; + } +} + +static MemoryRegion *pc_dimm_get_memory_region(PCDIMMDevice *dimm) +{ + return host_memory_backend_get_memory(dimm->hostmem, &error_abort); +} + +static void pc_dimm_class_init(ObjectClass *oc, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(oc); + PCDIMMDeviceClass *ddc = PC_DIMM_CLASS(oc); + + dc->realize = pc_dimm_realize; + dc->props = pc_dimm_properties; + + ddc->get_memory_region = pc_dimm_get_memory_region; +} + +static TypeInfo pc_dimm_info = { + .name = TYPE_PC_DIMM, + .parent = TYPE_DEVICE, + .instance_size = sizeof(PCDIMMDevice), + .instance_init = pc_dimm_init, + .class_init = pc_dimm_class_init, + .class_size = sizeof(PCDIMMDeviceClass), +}; + +static void pc_dimm_register_types(void) +{ + type_register_static(&pc_dimm_info); +} + +type_init(pc_dimm_register_types) diff --git a/hw/microblaze/boot.c b/hw/microblaze/boot.c index 48d9e7afa4..a2843cdf99 100644 --- a/hw/microblaze/boot.c +++ b/hw/microblaze/boot.c @@ -148,13 +148,14 @@ void microblaze_load_kernel(MicroBlazeCPU *cpu, hwaddr ddr_base, big_endian, ELF_MACHINE, 0); } /* Always boot into physical ram. */ - boot_info.bootstrap_pc = ddr_base + (entry & 0x0fffffff); + boot_info.bootstrap_pc = (uint32_t)entry; /* If it wasn't an ELF image, try an u-boot image. */ if (kernel_size < 0) { hwaddr uentry, loadaddr; - kernel_size = load_uimage(kernel_filename, &uentry, &loadaddr, 0); + kernel_size = load_uimage(kernel_filename, &uentry, &loadaddr, 0, + NULL, NULL); boot_info.bootstrap_pc = uentry; high = (loadaddr + kernel_size + 3) & ~3; } @@ -174,9 +175,15 @@ void microblaze_load_kernel(MicroBlazeCPU *cpu, hwaddr ddr_base, high = ROUND_UP(high + kernel_size, 4); boot_info.initrd_start = high; initrd_offset = boot_info.initrd_start - ddr_base; - initrd_size = load_image_targphys(initrd_filename, - boot_info.initrd_start, - ram_size - initrd_offset); + + initrd_size = load_ramdisk(initrd_filename, + boot_info.initrd_start, + ram_size - initrd_offset); + if (initrd_size < 0) { + initrd_size = load_image_targphys(initrd_filename, + boot_info.initrd_start, + ram_size - initrd_offset); + } if (initrd_size < 0) { error_report("qemu: could not load initrd '%s'\n", initrd_filename); diff --git a/hw/microblaze/petalogix_ml605_mmu.c b/hw/microblaze/petalogix_ml605_mmu.c index 40a9f5ccdb..48c264b9d7 100644 --- a/hw/microblaze/petalogix_ml605_mmu.c +++ b/hw/microblaze/petalogix_ml605_mmu.c @@ -32,7 +32,7 @@ #include "sysemu/sysemu.h" #include "hw/devices.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/char/serial.h" #include "exec/address-spaces.h" #include "hw/ssi.h" @@ -79,9 +79,9 @@ static void machine_cpu_reset(MicroBlazeCPU *cpu) } static void -petalogix_ml605_init(QEMUMachineInitArgs *args) +petalogix_ml605_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; + ram_addr_t ram_size = machine->ram_size; MemoryRegion *address_space_mem = get_system_memory(); DeviceState *dev, *dma, *eth0; Object *ds, *cs; @@ -89,7 +89,6 @@ petalogix_ml605_init(QEMUMachineInitArgs *args) SysBusDevice *busdev; DriveInfo *dinfo; int i; - hwaddr ddr_base = MEMORY_BASEADDR; MemoryRegion *phys_lmb_bram = g_new(MemoryRegion, 1); MemoryRegion *phys_ram = g_new(MemoryRegion, 1); qemu_irq irq[32]; @@ -100,21 +99,22 @@ petalogix_ml605_init(QEMUMachineInitArgs *args) /* Attach emulated BRAM through the LMB. */ memory_region_init_ram(phys_lmb_bram, NULL, "petalogix_ml605.lmb_bram", - LMB_BRAM_SIZE); + LMB_BRAM_SIZE, &error_abort); vmstate_register_ram_global(phys_lmb_bram); memory_region_add_subregion(address_space_mem, 0x00000000, phys_lmb_bram); - memory_region_init_ram(phys_ram, NULL, "petalogix_ml605.ram", ram_size); + memory_region_init_ram(phys_ram, NULL, "petalogix_ml605.ram", ram_size, + &error_abort); vmstate_register_ram_global(phys_ram); - memory_region_add_subregion(address_space_mem, ddr_base, phys_ram); + memory_region_add_subregion(address_space_mem, MEMORY_BASEADDR, phys_ram); dinfo = drive_get(IF_PFLASH, 0, 0); /* 5th parameter 2 means bank-width * 10th paremeter 0 means little-endian */ pflash_cfi01_register(FLASH_BASEADDR, NULL, "petalogix_ml605.flash", FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, (64 * 1024), - FLASH_SIZE >> 16, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (64 * 1024), FLASH_SIZE >> 16, 2, 0x89, 0x18, 0x0000, 0x0, 0); @@ -196,13 +196,13 @@ petalogix_ml605_init(QEMUMachineInitArgs *args) qemu_irq cs_line; dev = ssi_create_slave(spi, "n25q128"); - cs_line = qdev_get_gpio_in(dev, 0); + cs_line = qdev_get_gpio_in_named(dev, SSI_GPIO_CS, 0); sysbus_connect_irq(busdev, i+1, cs_line); } } - microblaze_load_kernel(cpu, ddr_base, ram_size, - args->initrd_filename, + microblaze_load_kernel(cpu, MEMORY_BASEADDR, ram_size, + machine->initrd_filename, BINARY_DEVICE_TREE_FILE, machine_cpu_reset); diff --git a/hw/microblaze/petalogix_s3adsp1800_mmu.c b/hw/microblaze/petalogix_s3adsp1800_mmu.c index 6c45e206ec..84f6e74653 100644 --- a/hw/microblaze/petalogix_s3adsp1800_mmu.c +++ b/hw/microblaze/petalogix_s3adsp1800_mmu.c @@ -30,7 +30,7 @@ #include "sysemu/sysemu.h" #include "hw/devices.h" #include "hw/boards.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "boot.h" @@ -59,10 +59,10 @@ static void machine_cpu_reset(MicroBlazeCPU *cpu) } static void -petalogix_s3adsp1800_init(QEMUMachineInitArgs *args) +petalogix_s3adsp1800_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; DeviceState *dev; MicroBlazeCPU *cpu; DriveInfo *dinfo; @@ -81,19 +81,21 @@ petalogix_s3adsp1800_init(QEMUMachineInitArgs *args) /* Attach emulated BRAM through the LMB. */ memory_region_init_ram(phys_lmb_bram, NULL, - "petalogix_s3adsp1800.lmb_bram", LMB_BRAM_SIZE); + "petalogix_s3adsp1800.lmb_bram", LMB_BRAM_SIZE, + &error_abort); vmstate_register_ram_global(phys_lmb_bram); memory_region_add_subregion(sysmem, 0x00000000, phys_lmb_bram); - memory_region_init_ram(phys_ram, NULL, "petalogix_s3adsp1800.ram", ram_size); + memory_region_init_ram(phys_ram, NULL, "petalogix_s3adsp1800.ram", + ram_size, &error_abort); vmstate_register_ram_global(phys_ram); memory_region_add_subregion(sysmem, ddr_base, phys_ram); dinfo = drive_get(IF_PFLASH, 0, 0); pflash_cfi01_register(FLASH_BASEADDR, NULL, "petalogix_s3adsp1800.flash", FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, (64 * 1024), - FLASH_SIZE >> 16, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (64 * 1024), FLASH_SIZE >> 16, 1, 0x89, 0x18, 0x0000, 0x0, 1); dev = qdev_create(NULL, "xlnx.xps-intc"); @@ -128,7 +130,7 @@ petalogix_s3adsp1800_init(QEMUMachineInitArgs *args) sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq[ETHLITE_IRQ]); microblaze_load_kernel(cpu, ddr_base, ram_size, - args->initrd_filename, + machine->initrd_filename, BINARY_DEVICE_TREE_FILE, machine_cpu_reset); } diff --git a/hw/mips/addr.c b/hw/mips/addr.c index 99488f1d2a..ff3b952600 100644 --- a/hw/mips/addr.c +++ b/hw/mips/addr.c @@ -25,10 +25,15 @@ uint64_t cpu_mips_kseg0_to_phys(void *opaque, uint64_t addr) { - return addr & 0x7fffffffll; + return addr & 0x1fffffffll; } uint64_t cpu_mips_phys_to_kseg0(void *opaque, uint64_t addr) { return addr | ~0x7fffffffll; } + +uint64_t cpu_mips_kvm_um_phys_to_kseg0(void *opaque, uint64_t addr) +{ + return addr | 0x40000000ll; +} diff --git a/hw/mips/cputimer.c b/hw/mips/cputimer.c index c8b4b000cd..577c9aeab8 100644 --- a/hw/mips/cputimer.c +++ b/hw/mips/cputimer.c @@ -23,6 +23,7 @@ #include "hw/hw.h" #include "hw/mips/cpudevs.h" #include "qemu/timer.h" +#include "sysemu/kvm.h" #define TIMER_FREQ 100 * 1000 * 1000 @@ -85,7 +86,12 @@ uint32_t cpu_mips_get_count (CPUMIPSState *env) void cpu_mips_store_count (CPUMIPSState *env, uint32_t count) { - if (env->CP0_Cause & (1 << CP0Ca_DC)) + /* + * This gets called from cpu_state_reset(), potentially before timer init. + * So env->timer may be NULL, which is also the case with KVM enabled so + * treat timer as disabled in that case. + */ + if (env->CP0_Cause & (1 << CP0Ca_DC) || !env->timer) env->CP0_Count = count; else { /* Store new count register */ @@ -141,7 +147,11 @@ static void mips_timer_cb (void *opaque) void cpu_mips_clock_init (CPUMIPSState *env) { - env->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, &mips_timer_cb, env); - env->CP0_Compare = 0; - cpu_mips_store_count(env, 1); + /* + * If we're in KVM mode, don't create the periodic timer, that is handled in + * kernel. + */ + if (!kvm_enabled()) { + env->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, &mips_timer_cb, env); + } } diff --git a/hw/mips/gt64xxx_pci.c b/hw/mips/gt64xxx_pci.c index 6398514c99..1f2fe5fab9 100644 --- a/hw/mips/gt64xxx_pci.c +++ b/hw/mips/gt64xxx_pci.c @@ -297,7 +297,7 @@ static void gt64120_pci_mapping(GT64120State *s) if (s->PCI0IO_length) { memory_region_del_subregion(get_system_memory(), &s->PCI0IO_mem); - memory_region_destroy(&s->PCI0IO_mem); + object_unparent(OBJECT(&s->PCI0IO_mem)); } /* Map new IO address */ s->PCI0IO_start = s->regs[GT_PCI0IOLD] << 21; @@ -312,6 +312,27 @@ static void gt64120_pci_mapping(GT64120State *s) } } +static int gt64120_post_load(void *opaque, int version_id) +{ + GT64120State *s = opaque; + + gt64120_isd_mapping(s); + gt64120_pci_mapping(s); + + return 0; +} + +static const VMStateDescription vmstate_gt64120 = { + .name = "gt64120", + .version_id = 1, + .minimum_version_id = 1, + .post_load = gt64120_post_load, + .fields = (VMStateField[]) { + VMSTATE_UINT32_ARRAY(regs, GT64120State, GT_REGS), + VMSTATE_END_OF_LIST() + } +}; + static void gt64120_writel (void *opaque, hwaddr addr, uint64_t val, unsigned size) { @@ -1174,9 +1195,11 @@ static const TypeInfo gt64120_pci_info = { static void gt64120_class_init(ObjectClass *klass, void *data) { + DeviceClass *dc = DEVICE_CLASS(klass); SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass); sdc->init = gt64120_init; + dc->vmsd = &vmstate_gt64120; } static const TypeInfo gt64120_info = { diff --git a/hw/mips/mips_fulong2e.c b/hw/mips/mips_fulong2e.c index e1551aabe2..6a9ebfa911 100644 --- a/hw/mips/mips_fulong2e.c +++ b/hw/mips/mips_fulong2e.c @@ -25,7 +25,7 @@ #include "net/net.h" #include "hw/boards.h" #include "hw/i2c/smbus.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/block/flash.h" #include "hw/mips/mips.h" #include "hw/mips/cpudevs.h" @@ -178,24 +178,24 @@ static void write_bootloader (CPUMIPSState *env, uint8_t *base, int64_t kernel_a /* Small bootloader */ p = (uint32_t *) base; - stl_raw(p++, 0x0bf00010); /* j 0x1fc00040 */ - stl_raw(p++, 0x00000000); /* nop */ + stl_p(p++, 0x0bf00010); /* j 0x1fc00040 */ + stl_p(p++, 0x00000000); /* nop */ /* Second part of the bootloader */ p = (uint32_t *) (base + 0x040); - stl_raw(p++, 0x3c040000); /* lui a0, 0 */ - stl_raw(p++, 0x34840002); /* ori a0, a0, 2 */ - stl_raw(p++, 0x3c050000 | ((ENVP_ADDR >> 16) & 0xffff)); /* lui a1, high(ENVP_ADDR) */ - stl_raw(p++, 0x34a50000 | (ENVP_ADDR & 0xffff)); /* ori a1, a0, low(ENVP_ADDR) */ - stl_raw(p++, 0x3c060000 | (((ENVP_ADDR + 8) >> 16) & 0xffff)); /* lui a2, high(ENVP_ADDR + 8) */ - stl_raw(p++, 0x34c60000 | ((ENVP_ADDR + 8) & 0xffff)); /* ori a2, a2, low(ENVP_ADDR + 8) */ - stl_raw(p++, 0x3c070000 | (loaderparams.ram_size >> 16)); /* lui a3, high(env->ram_size) */ - stl_raw(p++, 0x34e70000 | (loaderparams.ram_size & 0xffff)); /* ori a3, a3, low(env->ram_size) */ - stl_raw(p++, 0x3c1f0000 | ((kernel_addr >> 16) & 0xffff)); /* lui ra, high(kernel_addr) */; - stl_raw(p++, 0x37ff0000 | (kernel_addr & 0xffff)); /* ori ra, ra, low(kernel_addr) */ - stl_raw(p++, 0x03e00008); /* jr ra */ - stl_raw(p++, 0x00000000); /* nop */ + stl_p(p++, 0x3c040000); /* lui a0, 0 */ + stl_p(p++, 0x34840002); /* ori a0, a0, 2 */ + stl_p(p++, 0x3c050000 | ((ENVP_ADDR >> 16) & 0xffff)); /* lui a1, high(ENVP_ADDR) */ + stl_p(p++, 0x34a50000 | (ENVP_ADDR & 0xffff)); /* ori a1, a0, low(ENVP_ADDR) */ + stl_p(p++, 0x3c060000 | (((ENVP_ADDR + 8) >> 16) & 0xffff)); /* lui a2, high(ENVP_ADDR + 8) */ + stl_p(p++, 0x34c60000 | ((ENVP_ADDR + 8) & 0xffff)); /* ori a2, a2, low(ENVP_ADDR + 8) */ + stl_p(p++, 0x3c070000 | (loaderparams.ram_size >> 16)); /* lui a3, high(env->ram_size) */ + stl_p(p++, 0x34e70000 | (loaderparams.ram_size & 0xffff)); /* ori a3, a3, low(env->ram_size) */ + stl_p(p++, 0x3c1f0000 | ((kernel_addr >> 16) & 0xffff)); /* lui ra, high(kernel_addr) */; + stl_p(p++, 0x37ff0000 | (kernel_addr & 0xffff)); /* ori ra, ra, low(kernel_addr) */ + stl_p(p++, 0x03e00008); /* jr ra */ + stl_p(p++, 0x00000000); /* nop */ } @@ -211,7 +211,7 @@ static void main_cpu_reset(void *opaque) } } -uint8_t eeprom_spd[0x80] = { +static const uint8_t eeprom_spd[0x80] = { 0x80,0x08,0x07,0x0d,0x09,0x02,0x40,0x00,0x04,0x70, 0x70,0x00,0x82,0x10,0x00,0x01,0x0e,0x04,0x0c,0x01, 0x02,0x20,0x80,0x75,0x70,0x00,0x00,0x50,0x3c,0x50, @@ -259,13 +259,13 @@ static void cpu_request_exit(void *opaque, int irq, int level) } } -static void mips_fulong2e_init(QEMUMachineInitArgs *args) +static void mips_fulong2e_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; char *filename; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -302,9 +302,10 @@ static void mips_fulong2e_init(QEMUMachineInitArgs *args) bios_size = 1024 * 1024; /* allocate RAM */ - memory_region_init_ram(ram, NULL, "fulong2e.ram", ram_size); + memory_region_init_ram(ram, NULL, "fulong2e.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); - memory_region_init_ram(bios, NULL, "fulong2e.bios", bios_size); + memory_region_init_ram(bios, NULL, "fulong2e.bios", bios_size, + &error_abort); vmstate_register_ram_global(bios); memory_region_set_readonly(bios, true); @@ -349,7 +350,7 @@ static void mips_fulong2e_init(QEMUMachineInitArgs *args) pci_bus = bonito_init((qemu_irq *)&(env->irq[2])); /* South bridge */ - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); isa_bus = vt82c686b_init(pci_bus, PCI_DEVFN(FULONG2E_VIA_SLOT, 0)); if (!isa_bus) { diff --git a/hw/mips/mips_int.c b/hw/mips/mips_int.c index 7dbd24d3d6..d740046ba1 100644 --- a/hw/mips/mips_int.c +++ b/hw/mips/mips_int.c @@ -23,6 +23,8 @@ #include "hw/hw.h" #include "hw/mips/cpudevs.h" #include "cpu.h" +#include "sysemu/kvm.h" +#include "kvm_mips.h" static void cpu_mips_irq_request(void *opaque, int irq, int level) { @@ -35,8 +37,17 @@ static void cpu_mips_irq_request(void *opaque, int irq, int level) if (level) { env->CP0_Cause |= 1 << (irq + CP0Ca_IP); + + if (kvm_enabled() && irq == 2) { + kvm_mips_set_interrupt(cpu, irq, level); + } + } else { env->CP0_Cause &= ~(1 << (irq + CP0Ca_IP)); + + if (kvm_enabled() && irq == 2) { + kvm_mips_set_interrupt(cpu, irq, level); + } } if (env->CP0_Cause & CP0Ca_IP_mask) { diff --git a/hw/mips/mips_jazz.c b/hw/mips/mips_jazz.c index 5f6dd9f588..3f33093fd9 100644 --- a/hw/mips/mips_jazz.c +++ b/hw/mips/mips_jazz.c @@ -39,7 +39,7 @@ #include "hw/timer/mc146818rtc.h" #include "hw/timer/i8254.h" #include "hw/audio/pcspk.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "hw/sysbus.h" #include "exec/address-spaces.h" #include "sysemu/qtest.h" @@ -179,11 +179,12 @@ static void mips_jazz_init(MemoryRegion *address_space, cc->do_unassigned_access = mips_jazz_do_unassigned_access; /* allocate RAM */ - memory_region_init_ram(ram, NULL, "mips_jazz.ram", ram_size); + memory_region_init_ram(ram, NULL, "mips_jazz.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space, 0, ram); - memory_region_init_ram(bios, NULL, "mips_jazz.bios", MAGNUM_BIOS_SIZE); + memory_region_init_ram(bios, NULL, "mips_jazz.bios", MAGNUM_BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); memory_region_set_readonly(bios, true); memory_region_init_alias(bios2, NULL, "mips_jazz.bios", bios, @@ -244,7 +245,8 @@ static void mips_jazz_init(MemoryRegion *address_space, { /* Simple ROM, so user doesn't have to provide one */ MemoryRegion *rom_mr = g_new(MemoryRegion, 1); - memory_region_init_ram(rom_mr, NULL, "g364fb.rom", 0x80000); + memory_region_init_ram(rom_mr, NULL, "g364fb.rom", 0x80000, + &error_abort); vmstate_register_ram_global(rom_mr); memory_region_set_readonly(rom_mr, true); uint8_t *rom = memory_region_get_ram_ptr(rom_mr); @@ -329,19 +331,19 @@ static void mips_jazz_init(MemoryRegion *address_space, } static -void mips_magnum_init(QEMUMachineInitArgs *args) +void mips_magnum_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; mips_jazz_init(get_system_memory(), get_system_io(), ram_size, cpu_model, JAZZ_MAGNUM); } static -void mips_pica61_init(QEMUMachineInitArgs *args) +void mips_pica61_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; mips_jazz_init(get_system_memory(), get_system_io(), ram_size, cpu_model, JAZZ_PICA61); } diff --git a/hw/mips/mips_malta.c b/hw/mips/mips_malta.c index ac5ec44db0..5845158a74 100644 --- a/hw/mips/mips_malta.c +++ b/hw/mips/mips_malta.c @@ -29,7 +29,7 @@ #include "net/net.h" #include "hw/boards.h" #include "hw/i2c/smbus.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/block/flash.h" #include "hw/mips/mips.h" #include "hw/mips/cpudevs.h" @@ -44,6 +44,7 @@ #include "elf.h" #include "hw/timer/mc146818rtc.h" #include "hw/timer/i8254.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "exec/address-spaces.h" #include "hw/sysbus.h" /* SysBusDevice */ @@ -51,6 +52,7 @@ #include "sysemu/qtest.h" #include "qemu/error-report.h" #include "hw/empty_slot.h" +#include "sysemu/kvm.h" //#define DEBUG_BOARD_INIT @@ -603,142 +605,144 @@ static void network_init(PCIBus *pci_bus) */ static void write_bootloader (CPUMIPSState *env, uint8_t *base, - int64_t kernel_entry) + int64_t run_addr, int64_t kernel_entry) { uint32_t *p; /* Small bootloader */ p = (uint32_t *)base; - stl_raw(p++, 0x0bf00160); /* j 0x1fc00580 */ - stl_raw(p++, 0x00000000); /* nop */ + + stl_p(p++, 0x08000000 | /* j 0x1fc00580 */ + ((run_addr + 0x580) & 0x0fffffff) >> 2); + stl_p(p++, 0x00000000); /* nop */ /* YAMON service vector */ - stl_raw(base + 0x500, 0xbfc00580); /* start: */ - stl_raw(base + 0x504, 0xbfc0083c); /* print_count: */ - stl_raw(base + 0x520, 0xbfc00580); /* start: */ - stl_raw(base + 0x52c, 0xbfc00800); /* flush_cache: */ - stl_raw(base + 0x534, 0xbfc00808); /* print: */ - stl_raw(base + 0x538, 0xbfc00800); /* reg_cpu_isr: */ - stl_raw(base + 0x53c, 0xbfc00800); /* unred_cpu_isr: */ - stl_raw(base + 0x540, 0xbfc00800); /* reg_ic_isr: */ - stl_raw(base + 0x544, 0xbfc00800); /* unred_ic_isr: */ - stl_raw(base + 0x548, 0xbfc00800); /* reg_esr: */ - stl_raw(base + 0x54c, 0xbfc00800); /* unreg_esr: */ - stl_raw(base + 0x550, 0xbfc00800); /* getchar: */ - stl_raw(base + 0x554, 0xbfc00800); /* syscon_read: */ + stl_p(base + 0x500, run_addr + 0x0580); /* start: */ + stl_p(base + 0x504, run_addr + 0x083c); /* print_count: */ + stl_p(base + 0x520, run_addr + 0x0580); /* start: */ + stl_p(base + 0x52c, run_addr + 0x0800); /* flush_cache: */ + stl_p(base + 0x534, run_addr + 0x0808); /* print: */ + stl_p(base + 0x538, run_addr + 0x0800); /* reg_cpu_isr: */ + stl_p(base + 0x53c, run_addr + 0x0800); /* unred_cpu_isr: */ + stl_p(base + 0x540, run_addr + 0x0800); /* reg_ic_isr: */ + stl_p(base + 0x544, run_addr + 0x0800); /* unred_ic_isr: */ + stl_p(base + 0x548, run_addr + 0x0800); /* reg_esr: */ + stl_p(base + 0x54c, run_addr + 0x0800); /* unreg_esr: */ + stl_p(base + 0x550, run_addr + 0x0800); /* getchar: */ + stl_p(base + 0x554, run_addr + 0x0800); /* syscon_read: */ /* Second part of the bootloader */ p = (uint32_t *) (base + 0x580); - stl_raw(p++, 0x24040002); /* addiu a0, zero, 2 */ - stl_raw(p++, 0x3c1d0000 | (((ENVP_ADDR - 64) >> 16) & 0xffff)); /* lui sp, high(ENVP_ADDR) */ - stl_raw(p++, 0x37bd0000 | ((ENVP_ADDR - 64) & 0xffff)); /* ori sp, sp, low(ENVP_ADDR) */ - stl_raw(p++, 0x3c050000 | ((ENVP_ADDR >> 16) & 0xffff)); /* lui a1, high(ENVP_ADDR) */ - stl_raw(p++, 0x34a50000 | (ENVP_ADDR & 0xffff)); /* ori a1, a1, low(ENVP_ADDR) */ - stl_raw(p++, 0x3c060000 | (((ENVP_ADDR + 8) >> 16) & 0xffff)); /* lui a2, high(ENVP_ADDR + 8) */ - stl_raw(p++, 0x34c60000 | ((ENVP_ADDR + 8) & 0xffff)); /* ori a2, a2, low(ENVP_ADDR + 8) */ - stl_raw(p++, 0x3c070000 | (loaderparams.ram_size >> 16)); /* lui a3, high(ram_size) */ - stl_raw(p++, 0x34e70000 | (loaderparams.ram_size & 0xffff)); /* ori a3, a3, low(ram_size) */ + stl_p(p++, 0x24040002); /* addiu a0, zero, 2 */ + stl_p(p++, 0x3c1d0000 | (((ENVP_ADDR - 64) >> 16) & 0xffff)); /* lui sp, high(ENVP_ADDR) */ + stl_p(p++, 0x37bd0000 | ((ENVP_ADDR - 64) & 0xffff)); /* ori sp, sp, low(ENVP_ADDR) */ + stl_p(p++, 0x3c050000 | ((ENVP_ADDR >> 16) & 0xffff)); /* lui a1, high(ENVP_ADDR) */ + stl_p(p++, 0x34a50000 | (ENVP_ADDR & 0xffff)); /* ori a1, a1, low(ENVP_ADDR) */ + stl_p(p++, 0x3c060000 | (((ENVP_ADDR + 8) >> 16) & 0xffff)); /* lui a2, high(ENVP_ADDR + 8) */ + stl_p(p++, 0x34c60000 | ((ENVP_ADDR + 8) & 0xffff)); /* ori a2, a2, low(ENVP_ADDR + 8) */ + stl_p(p++, 0x3c070000 | (loaderparams.ram_size >> 16)); /* lui a3, high(ram_size) */ + stl_p(p++, 0x34e70000 | (loaderparams.ram_size & 0xffff)); /* ori a3, a3, low(ram_size) */ /* Load BAR registers as done by YAMON */ - stl_raw(p++, 0x3c09b400); /* lui t1, 0xb400 */ + stl_p(p++, 0x3c09b400); /* lui t1, 0xb400 */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c08df00); /* lui t0, 0xdf00 */ + stl_p(p++, 0x3c08df00); /* lui t0, 0xdf00 */ #else - stl_raw(p++, 0x340800df); /* ori t0, r0, 0x00df */ + stl_p(p++, 0x340800df); /* ori t0, r0, 0x00df */ #endif - stl_raw(p++, 0xad280068); /* sw t0, 0x0068(t1) */ + stl_p(p++, 0xad280068); /* sw t0, 0x0068(t1) */ - stl_raw(p++, 0x3c09bbe0); /* lui t1, 0xbbe0 */ + stl_p(p++, 0x3c09bbe0); /* lui t1, 0xbbe0 */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c08c000); /* lui t0, 0xc000 */ + stl_p(p++, 0x3c08c000); /* lui t0, 0xc000 */ #else - stl_raw(p++, 0x340800c0); /* ori t0, r0, 0x00c0 */ + stl_p(p++, 0x340800c0); /* ori t0, r0, 0x00c0 */ #endif - stl_raw(p++, 0xad280048); /* sw t0, 0x0048(t1) */ + stl_p(p++, 0xad280048); /* sw t0, 0x0048(t1) */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c084000); /* lui t0, 0x4000 */ + stl_p(p++, 0x3c084000); /* lui t0, 0x4000 */ #else - stl_raw(p++, 0x34080040); /* ori t0, r0, 0x0040 */ + stl_p(p++, 0x34080040); /* ori t0, r0, 0x0040 */ #endif - stl_raw(p++, 0xad280050); /* sw t0, 0x0050(t1) */ + stl_p(p++, 0xad280050); /* sw t0, 0x0050(t1) */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c088000); /* lui t0, 0x8000 */ + stl_p(p++, 0x3c088000); /* lui t0, 0x8000 */ #else - stl_raw(p++, 0x34080080); /* ori t0, r0, 0x0080 */ + stl_p(p++, 0x34080080); /* ori t0, r0, 0x0080 */ #endif - stl_raw(p++, 0xad280058); /* sw t0, 0x0058(t1) */ + stl_p(p++, 0xad280058); /* sw t0, 0x0058(t1) */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c083f00); /* lui t0, 0x3f00 */ + stl_p(p++, 0x3c083f00); /* lui t0, 0x3f00 */ #else - stl_raw(p++, 0x3408003f); /* ori t0, r0, 0x003f */ + stl_p(p++, 0x3408003f); /* ori t0, r0, 0x003f */ #endif - stl_raw(p++, 0xad280060); /* sw t0, 0x0060(t1) */ + stl_p(p++, 0xad280060); /* sw t0, 0x0060(t1) */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c08c100); /* lui t0, 0xc100 */ + stl_p(p++, 0x3c08c100); /* lui t0, 0xc100 */ #else - stl_raw(p++, 0x340800c1); /* ori t0, r0, 0x00c1 */ + stl_p(p++, 0x340800c1); /* ori t0, r0, 0x00c1 */ #endif - stl_raw(p++, 0xad280080); /* sw t0, 0x0080(t1) */ + stl_p(p++, 0xad280080); /* sw t0, 0x0080(t1) */ #ifdef TARGET_WORDS_BIGENDIAN - stl_raw(p++, 0x3c085e00); /* lui t0, 0x5e00 */ + stl_p(p++, 0x3c085e00); /* lui t0, 0x5e00 */ #else - stl_raw(p++, 0x3408005e); /* ori t0, r0, 0x005e */ + stl_p(p++, 0x3408005e); /* ori t0, r0, 0x005e */ #endif - stl_raw(p++, 0xad280088); /* sw t0, 0x0088(t1) */ + stl_p(p++, 0xad280088); /* sw t0, 0x0088(t1) */ /* Jump to kernel code */ - stl_raw(p++, 0x3c1f0000 | ((kernel_entry >> 16) & 0xffff)); /* lui ra, high(kernel_entry) */ - stl_raw(p++, 0x37ff0000 | (kernel_entry & 0xffff)); /* ori ra, ra, low(kernel_entry) */ - stl_raw(p++, 0x03e00008); /* jr ra */ - stl_raw(p++, 0x00000000); /* nop */ + stl_p(p++, 0x3c1f0000 | ((kernel_entry >> 16) & 0xffff)); /* lui ra, high(kernel_entry) */ + stl_p(p++, 0x37ff0000 | (kernel_entry & 0xffff)); /* ori ra, ra, low(kernel_entry) */ + stl_p(p++, 0x03e00009); /* jalr ra */ + stl_p(p++, 0x00000000); /* nop */ /* YAMON subroutines */ p = (uint32_t *) (base + 0x800); - stl_raw(p++, 0x03e00008); /* jr ra */ - stl_raw(p++, 0x24020000); /* li v0,0 */ - /* 808 YAMON print */ - stl_raw(p++, 0x03e06821); /* move t5,ra */ - stl_raw(p++, 0x00805821); /* move t3,a0 */ - stl_raw(p++, 0x00a05021); /* move t2,a1 */ - stl_raw(p++, 0x91440000); /* lbu a0,0(t2) */ - stl_raw(p++, 0x254a0001); /* addiu t2,t2,1 */ - stl_raw(p++, 0x10800005); /* beqz a0,834 */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x0ff0021c); /* jal 870 */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x08000205); /* j 814 */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x01a00008); /* jr t5 */ - stl_raw(p++, 0x01602021); /* move a0,t3 */ + stl_p(p++, 0x03e00009); /* jalr ra */ + stl_p(p++, 0x24020000); /* li v0,0 */ + /* 808 YAMON print */ + stl_p(p++, 0x03e06821); /* move t5,ra */ + stl_p(p++, 0x00805821); /* move t3,a0 */ + stl_p(p++, 0x00a05021); /* move t2,a1 */ + stl_p(p++, 0x91440000); /* lbu a0,0(t2) */ + stl_p(p++, 0x254a0001); /* addiu t2,t2,1 */ + stl_p(p++, 0x10800005); /* beqz a0,834 */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x0ff0021c); /* jal 870 */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x08000205); /* j 814 */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x01a00009); /* jalr t5 */ + stl_p(p++, 0x01602021); /* move a0,t3 */ /* 0x83c YAMON print_count */ - stl_raw(p++, 0x03e06821); /* move t5,ra */ - stl_raw(p++, 0x00805821); /* move t3,a0 */ - stl_raw(p++, 0x00a05021); /* move t2,a1 */ - stl_raw(p++, 0x00c06021); /* move t4,a2 */ - stl_raw(p++, 0x91440000); /* lbu a0,0(t2) */ - stl_raw(p++, 0x0ff0021c); /* jal 870 */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x254a0001); /* addiu t2,t2,1 */ - stl_raw(p++, 0x258cffff); /* addiu t4,t4,-1 */ - stl_raw(p++, 0x1580fffa); /* bnez t4,84c */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x01a00008); /* jr t5 */ - stl_raw(p++, 0x01602021); /* move a0,t3 */ + stl_p(p++, 0x03e06821); /* move t5,ra */ + stl_p(p++, 0x00805821); /* move t3,a0 */ + stl_p(p++, 0x00a05021); /* move t2,a1 */ + stl_p(p++, 0x00c06021); /* move t4,a2 */ + stl_p(p++, 0x91440000); /* lbu a0,0(t2) */ + stl_p(p++, 0x0ff0021c); /* jal 870 */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x254a0001); /* addiu t2,t2,1 */ + stl_p(p++, 0x258cffff); /* addiu t4,t4,-1 */ + stl_p(p++, 0x1580fffa); /* bnez t4,84c */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x01a00009); /* jalr t5 */ + stl_p(p++, 0x01602021); /* move a0,t3 */ /* 0x870 */ - stl_raw(p++, 0x3c08b800); /* lui t0,0xb400 */ - stl_raw(p++, 0x350803f8); /* ori t0,t0,0x3f8 */ - stl_raw(p++, 0x91090005); /* lbu t1,5(t0) */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x31290040); /* andi t1,t1,0x40 */ - stl_raw(p++, 0x1120fffc); /* beqz t1,878 <outch+0x8> */ - stl_raw(p++, 0x00000000); /* nop */ - stl_raw(p++, 0x03e00008); /* jr ra */ - stl_raw(p++, 0xa1040000); /* sb a0,0(t0) */ + stl_p(p++, 0x3c08b800); /* lui t0,0xb400 */ + stl_p(p++, 0x350803f8); /* ori t0,t0,0x3f8 */ + stl_p(p++, 0x91090005); /* lbu t1,5(t0) */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x31290040); /* andi t1,t1,0x40 */ + stl_p(p++, 0x1120fffc); /* beqz t1,878 <outch+0x8> */ + stl_p(p++, 0x00000000); /* nop */ + stl_p(p++, 0x03e00009); /* jalr ra */ + stl_p(p++, 0xa1040000); /* sb a0,0(t0) */ } @@ -774,6 +778,7 @@ static int64_t load_kernel (void) uint32_t *prom_buf; long prom_size; int prom_index = 0; + uint64_t (*xlate_to_kseg0) (void *opaque, uint64_t addr); #ifdef TARGET_WORDS_BIGENDIAN big_endian = 1; @@ -789,6 +794,25 @@ static int64_t load_kernel (void) exit(1); } + /* Sanity check where the kernel has been linked */ + if (kvm_enabled()) { + if (kernel_entry & 0x80000000ll) { + error_report("KVM guest kernels must be linked in useg. " + "Did you forget to enable CONFIG_KVM_GUEST?"); + exit(1); + } + + xlate_to_kseg0 = cpu_mips_kvm_um_phys_to_kseg0; + } else { + if (!(kernel_entry & 0x80000000ll)) { + error_report("KVM guest kernels aren't supported with TCG. " + "Did you unintentionally enable CONFIG_KVM_GUEST?"); + exit(1); + } + + xlate_to_kseg0 = cpu_mips_phys_to_kseg0; + } + /* load initrd */ initrd_size = 0; initrd_offset = 0; @@ -820,7 +844,7 @@ static int64_t load_kernel (void) prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_filename); if (initrd_size > 0) { prom_set(prom_buf, prom_index++, "rd_start=0x%" PRIx64 " rd_size=%li %s", - cpu_mips_phys_to_kseg0(NULL, initrd_offset), initrd_size, + xlate_to_kseg0(NULL, initrd_offset), initrd_size, loaderparams.kernel_cmdline); } else { prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_cmdline); @@ -829,6 +853,7 @@ static int64_t load_kernel (void) prom_set(prom_buf, prom_index++, "memsize"); prom_set(prom_buf, prom_index++, "%i", MIN(loaderparams.ram_size, 256 << 20)); + prom_set(prom_buf, prom_index++, "modetty0"); prom_set(prom_buf, prom_index++, "38400n8r"); prom_set(prom_buf, prom_index++, NULL); @@ -863,6 +888,11 @@ static void main_cpu_reset(void *opaque) } malta_mips_config(cpu); + + if (kvm_enabled()) { + /* Start running from the bootloader we wrote to end of RAM */ + env->active_tc.PC = 0x40000000 + loaderparams.ram_size; + } } static void cpu_request_exit(void *opaque, int irq, int level) @@ -875,13 +905,14 @@ static void cpu_request_exit(void *opaque, int irq, int level) } static -void mips_malta_init(QEMUMachineInitArgs *args) +void mips_malta_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + ram_addr_t ram_low_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; char *filename; pflash_t *fl; MemoryRegion *system_memory = get_system_memory(); @@ -892,7 +923,7 @@ void mips_malta_init(QEMUMachineInitArgs *args) target_long bios_size = FLASH_SIZE; const size_t smbus_eeprom_size = 8 * 256; uint8_t *smbus_eeprom_buf = g_malloc0(smbus_eeprom_size); - int64_t kernel_entry; + int64_t kernel_entry, bootloader_run_addr; PCIBus *pci_bus; ISABus *isa_bus; MIPSCPU *cpu; @@ -962,7 +993,8 @@ void mips_malta_init(QEMUMachineInitArgs *args) } /* register RAM at high address where it is undisturbed by IO */ - memory_region_init_ram(ram_high, NULL, "mips_malta.ram", ram_size); + memory_region_init_ram(ram_high, NULL, "mips_malta.ram", ram_size, + &error_abort); vmstate_register_ram_global(ram_high); memory_region_add_subregion(system_memory, 0x80000000, ram_high); @@ -1001,24 +1033,48 @@ void mips_malta_init(QEMUMachineInitArgs *args) printf("Register parallel flash %d size " TARGET_FMT_lx " at " "addr %08llx '%s' %x\n", fl_idx, bios_size, FLASH_ADDRESS, - bdrv_get_device_name(dinfo->bdrv), fl_sectors); + blk_name(dinfo->bdrv), fl_sectors); } #endif fl = pflash_cfi01_register(FLASH_ADDRESS, NULL, "mips_malta.bios", - BIOS_SIZE, dinfo ? dinfo->bdrv : NULL, + BIOS_SIZE, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, 65536, fl_sectors, 4, 0x0000, 0x0000, 0x0000, 0x0000, be); bios = pflash_cfi01_get_memory(fl); fl_idx++; if (kernel_filename) { + ram_low_size = MIN(ram_size, 256 << 20); + /* For KVM we reserve 1MB of RAM for running bootloader */ + if (kvm_enabled()) { + ram_low_size -= 0x100000; + bootloader_run_addr = 0x40000000 + ram_low_size; + } else { + bootloader_run_addr = 0xbfc00000; + } + /* Write a small bootloader to the flash location. */ - loaderparams.ram_size = MIN(ram_size, 256 << 20); + loaderparams.ram_size = ram_low_size; loaderparams.kernel_filename = kernel_filename; loaderparams.kernel_cmdline = kernel_cmdline; loaderparams.initrd_filename = initrd_filename; kernel_entry = load_kernel(); - write_bootloader(env, memory_region_get_ram_ptr(bios), kernel_entry); + + write_bootloader(env, memory_region_get_ram_ptr(bios), + bootloader_run_addr, kernel_entry); + if (kvm_enabled()) { + /* Write the bootloader code @ the end of RAM, 1MB reserved */ + write_bootloader(env, memory_region_get_ram_ptr(ram_low_preio) + + ram_low_size, + bootloader_run_addr, kernel_entry); + } } else { + /* The flash region isn't executable from a KVM guest */ + if (kvm_enabled()) { + error_report("KVM enabled but no -kernel argument was specified. " + "Booting from flash is not supported with KVM."); + exit(1); + } /* Load firmware from flash. */ if (!dinfo) { /* Load a BIOS image. */ @@ -1063,7 +1119,8 @@ void mips_malta_init(QEMUMachineInitArgs *args) * handled by an overlapping region as the resulting ROM code subpage * regions are not executable. */ - memory_region_init_ram(bios_copy, NULL, "bios.1fc", BIOS_SIZE); + memory_region_init_ram(bios_copy, NULL, "bios.1fc", BIOS_SIZE, + &error_abort); if (!rom_copy(memory_region_get_ram_ptr(bios_copy), FLASH_ADDRESS, BIOS_SIZE)) { memcpy(memory_region_get_ram_ptr(bios_copy), @@ -1092,7 +1149,7 @@ void mips_malta_init(QEMUMachineInitArgs *args) pci_bus = gt64120_register(isa_irq); /* Southbridge */ - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); piix4_devfn = piix4_init(pci_bus, &isa_bus, 80); @@ -1104,7 +1161,7 @@ void mips_malta_init(QEMUMachineInitArgs *args) pci_piix4_ide_init(pci_bus, hd, piix4_devfn + 1); pci_create_simple(pci_bus, piix4_devfn + 2, "piix4-usb-uhci"); smbus = piix4_pm_init(pci_bus, piix4_devfn + 3, 0x1100, - isa_get_irq(NULL, 9), NULL, 0, NULL); + isa_get_irq(NULL, 9), NULL, 0, NULL, NULL); smbus_eeprom_init(smbus, 8, smbus_eeprom_buf, smbus_eeprom_size); g_free(smbus_eeprom_buf); pit = pit_init(isa_bus, 0x40, 0, NULL); diff --git a/hw/mips/mips_mipssim.c b/hw/mips/mips_mipssim.c index 239aa6ac8c..5d44c3f73d 100644 --- a/hw/mips/mips_mipssim.c +++ b/hw/mips/mips_mipssim.c @@ -133,13 +133,13 @@ static void mipsnet_init(int base, qemu_irq irq, NICInfo *nd) } static void -mips_mipssim_init(QEMUMachineInitArgs *args) +mips_mipssim_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; char *filename; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *isa = g_new(MemoryRegion, 1); @@ -171,9 +171,11 @@ mips_mipssim_init(QEMUMachineInitArgs *args) qemu_register_reset(main_cpu_reset, reset_info); /* Allocate RAM. */ - memory_region_init_ram(ram, NULL, "mips_mipssim.ram", ram_size); + memory_region_init_ram(ram, NULL, "mips_mipssim.ram", ram_size, + &error_abort); vmstate_register_ram_global(ram); - memory_region_init_ram(bios, NULL, "mips_mipssim.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "mips_mipssim.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); memory_region_set_readonly(bios, true); @@ -195,7 +197,7 @@ mips_mipssim_init(QEMUMachineInitArgs *args) !kernel_filename && !qtest_enabled()) { /* Bail out if we have neither a kernel image nor boot vector code. */ error_report("Could not load MIPS bios '%s', and no " - "-kernel argument was specified", filename); + "-kernel argument was specified", bios_name); exit(1); } else { /* We have a boot vector start address. */ diff --git a/hw/mips/mips_r4k.c b/hw/mips/mips_r4k.c index e94b543e80..a7fe0ceadf 100644 --- a/hw/mips/mips_r4k.c +++ b/hw/mips/mips_r4k.c @@ -24,7 +24,7 @@ #include "elf.h" #include "hw/timer/mc146818rtc.h" #include "hw/timer/i8254.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "sysemu/qtest.h" @@ -153,13 +153,13 @@ static void main_cpu_reset(void *opaque) static const int sector_len = 32 * 1024; static -void mips_r4k_init(QEMUMachineInitArgs *args) +void mips_r4k_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; char *filename; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -204,7 +204,7 @@ void mips_r4k_init(QEMUMachineInitArgs *args) ((unsigned int)ram_size / (1 << 20))); exit(1); } - memory_region_init_ram(ram, NULL, "mips_r4k.ram", ram_size); + memory_region_init_ram(ram, NULL, "mips_r4k.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0, ram); @@ -231,7 +231,8 @@ void mips_r4k_init(QEMUMachineInitArgs *args) #endif if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) { bios = g_new(MemoryRegion, 1); - memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); memory_region_set_readonly(bios, true); memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios); @@ -240,8 +241,8 @@ void mips_r4k_init(QEMUMachineInitArgs *args) } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) { uint32_t mips_rom = 0x00400000; if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom, - dinfo->bdrv, sector_len, - mips_rom / sector_len, + blk_by_legacy_dinfo(dinfo), + sector_len, mips_rom / sector_len, 4, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); } @@ -293,7 +294,7 @@ void mips_r4k_init(QEMUMachineInitArgs *args) if (nd_table[0].used) isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]); - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); for(i = 0; i < MAX_IDE_BUS; i++) isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i], hd[MAX_IDE_DEVS * i], diff --git a/hw/misc/Makefile.objs b/hw/misc/Makefile.objs index f6743659f7..979e532fdf 100644 --- a/hw/misc/Makefile.objs +++ b/hw/misc/Makefile.objs @@ -29,7 +29,6 @@ obj-$(CONFIG_NSERIES) += cbus.o obj-$(CONFIG_ECCMEMCTL) += eccmemctl.o obj-$(CONFIG_EXYNOS4) += exynos4210_pmu.o obj-$(CONFIG_IMX) += imx_ccm.o -obj-$(CONFIG_LM32) += lm32_sys.o obj-$(CONFIG_MILKYMIST) += milkymist-hpdmc.o obj-$(CONFIG_MILKYMIST) += milkymist-pfpu.o obj-$(CONFIG_MAINSTONE) += mst_fpga.o diff --git a/hw/misc/cbus.c b/hw/misc/cbus.c index 29b467b61f..495d5078fe 100644 --- a/hw/misc/cbus.c +++ b/hw/misc/cbus.c @@ -135,9 +135,9 @@ CBus *cbus_init(qemu_irq dat) CBusPriv *s = (CBusPriv *) g_malloc0(sizeof(*s)); s->dat_out = dat; - s->cbus.clk = qemu_allocate_irqs(cbus_clk, s, 1)[0]; - s->cbus.dat = qemu_allocate_irqs(cbus_dat, s, 1)[0]; - s->cbus.sel = qemu_allocate_irqs(cbus_sel, s, 1)[0]; + s->cbus.clk = qemu_allocate_irq(cbus_clk, s, 0); + s->cbus.dat = qemu_allocate_irq(cbus_dat, s, 0); + s->cbus.sel = qemu_allocate_irq(cbus_sel, s, 0); s->sel = 1; s->clk = 0; diff --git a/hw/misc/eccmemctl.c b/hw/misc/eccmemctl.c index 549431cb13..8bad6f682b 100644 --- a/hw/misc/eccmemctl.c +++ b/hw/misc/eccmemctl.c @@ -266,8 +266,7 @@ static const VMStateDescription vmstate_ecc = { .name ="ECC", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, ECCState, ECC_NREGS), VMSTATE_BUFFER(diag, ECCState), VMSTATE_UINT32(version, ECCState), diff --git a/hw/misc/exynos4210_pmu.c b/hw/misc/exynos4210_pmu.c index 5ec14d1c86..2b118c7255 100644 --- a/hw/misc/exynos4210_pmu.c +++ b/hw/misc/exynos4210_pmu.c @@ -471,7 +471,7 @@ static const VMStateDescription exynos4210_pmu_vmstate = { .name = "exynos4210.pmu", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(reg, Exynos4210PmuState, PMU_NUM_OF_REGISTERS), VMSTATE_END_OF_LIST() } diff --git a/hw/misc/imx_ccm.c b/hw/misc/imx_ccm.c index 63e33a41da..0920288634 100644 --- a/hw/misc/imx_ccm.c +++ b/hw/misc/imx_ccm.c @@ -57,7 +57,6 @@ static const VMStateDescription vmstate_imx_ccm = { .name = "imx-ccm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(ccmr, IMXCCMState), VMSTATE_UINT32(pdr0, IMXCCMState), @@ -68,6 +67,7 @@ static const VMStateDescription vmstate_imx_ccm = { VMSTATE_UINT32(pmcr0, IMXCCMState), VMSTATE_UINT32(pmcr1, IMXCCMState), VMSTATE_UINT32(pll_refclk_freq, IMXCCMState), + VMSTATE_END_OF_LIST() }, .post_load = imx_ccm_post_load, }; diff --git a/hw/misc/ivshmem.c b/hw/misc/ivshmem.c index 8d144baa1e..5d272c84e9 100644 --- a/hw/misc/ivshmem.c +++ b/hw/misc/ivshmem.c @@ -24,10 +24,12 @@ #include "migration/migration.h" #include "qapi/qmp/qerror.h" #include "qemu/event_notifier.h" +#include "qemu/fifo8.h" #include "sysemu/char.h" #include <sys/mman.h> #include <sys/types.h> +#include <limits.h> #define PCI_VENDOR_ID_IVSHMEM PCI_VENDOR_ID_REDHAT_QUMRANET #define PCI_DEVICE_ID_IVSHMEM 0x1110 @@ -73,6 +75,7 @@ typedef struct IVShmemState { CharDriverState **eventfd_chr; CharDriverState *server_chr; + Fifo8 incoming_fifo; MemoryRegion ivshmem_mmio; /* We might need to register the BAR before we actually have the memory. @@ -130,7 +133,7 @@ static void ivshmem_update_irq(IVShmemState *s, int val) /* don't print ISR resets */ if (isr) { IVSHMEM_DPRINTF("Set IRQ to %d (%04x %04x)\n", - isr ? 1 : 0, s->intrstatus, s->intrmask); + isr ? 1 : 0, s->intrstatus, s->intrmask); } pci_set_irq(d, (isr != 0)); @@ -297,8 +300,8 @@ static CharDriverState* create_eventfd_chr_device(void * opaque, EventNotifier * chr = qemu_chr_open_eventfd(eventfd); if (chr == NULL) { - fprintf(stderr, "creating eventfd for eventfd %d failed\n", eventfd); - exit(-1); + error_report("creating eventfd for eventfd %d failed", eventfd); + exit(1); } qemu_chr_fe_claim_no_fail(chr); @@ -324,13 +327,16 @@ static int check_shm_size(IVShmemState *s, int fd) { struct stat buf; - fstat(fd, &buf); + if (fstat(fd, &buf) < 0) { + error_report("exiting: fstat on fd %d failed: %s", + fd, strerror(errno)); + return -1; + } if (s->ivshmem_size > buf.st_size) { - fprintf(stderr, - "IVSHMEM ERROR: Requested memory size greater" - " than shared object size (%" PRIu64 " > %" PRIu64")\n", - s->ivshmem_size, (uint64_t)buf.st_size); + error_report("Requested memory size greater" + " than shared object size (%" PRIu64 " > %" PRIu64")", + s->ivshmem_size, (uint64_t)buf.st_size); return -1; } else { return 0; @@ -383,6 +389,9 @@ static void close_guest_eventfds(IVShmemState *s, int posn) if (!ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) { return; } + if (posn < 0 || posn >= s->nb_peers) { + return; + } guest_curr_max = s->peers[posn].nb_eventfds; @@ -401,14 +410,24 @@ static void close_guest_eventfds(IVShmemState *s, int posn) /* this function increase the dynamic storage need to store data about other * guests */ -static void increase_dynamic_storage(IVShmemState *s, int new_min_size) { +static int increase_dynamic_storage(IVShmemState *s, int new_min_size) +{ int j, old_nb_alloc; + /* check for integer overflow */ + if (new_min_size >= INT_MAX / sizeof(Peer) - 1 || new_min_size <= 0) { + return -1; + } + old_nb_alloc = s->nb_peers; - while (new_min_size >= s->nb_peers) - s->nb_peers = s->nb_peers * 2; + if (new_min_size >= s->nb_peers) { + /* +1 because #new_min_size is used as last array index */ + s->nb_peers = new_min_size + 1; + } else { + return 0; + } IVSHMEM_DPRINTF("bumping storage to %d guests\n", s->nb_peers); s->peers = g_realloc(s->peers, s->nb_peers * sizeof(Peer)); @@ -418,23 +437,57 @@ static void increase_dynamic_storage(IVShmemState *s, int new_min_size) { s->peers[j].eventfds = NULL; s->peers[j].nb_eventfds = 0; } + + return 0; } -static void ivshmem_read(void *opaque, const uint8_t * buf, int flags) +static void ivshmem_read(void *opaque, const uint8_t *buf, int size) { IVShmemState *s = opaque; int incoming_fd, tmp_fd; int guest_max_eventfd; long incoming_posn; - memcpy(&incoming_posn, buf, sizeof(long)); + if (fifo8_is_empty(&s->incoming_fifo) && size == sizeof(incoming_posn)) { + memcpy(&incoming_posn, buf, size); + } else { + const uint8_t *p; + uint32_t num; + + IVSHMEM_DPRINTF("short read of %d bytes\n", size); + num = MAX(size, sizeof(long) - fifo8_num_used(&s->incoming_fifo)); + fifo8_push_all(&s->incoming_fifo, buf, num); + if (fifo8_num_used(&s->incoming_fifo) < sizeof(incoming_posn)) { + return; + } + size -= num; + buf += num; + p = fifo8_pop_buf(&s->incoming_fifo, sizeof(incoming_posn), &num); + g_assert(num == sizeof(incoming_posn)); + memcpy(&incoming_posn, p, sizeof(incoming_posn)); + if (size > 0) { + fifo8_push_all(&s->incoming_fifo, buf, size); + } + } + + if (incoming_posn < -1) { + IVSHMEM_DPRINTF("invalid incoming_posn %ld\n", incoming_posn); + return; + } + /* pick off s->server_chr->msgfd and store it, posn should accompany msg */ tmp_fd = qemu_chr_fe_get_msgfd(s->server_chr); IVSHMEM_DPRINTF("posn is %ld, fd is %d\n", incoming_posn, tmp_fd); /* make sure we have enough space for this guest */ if (incoming_posn >= s->nb_peers) { - increase_dynamic_storage(s, incoming_posn); + if (increase_dynamic_storage(s, incoming_posn) < 0) { + error_report("increase_dynamic_storage() failed"); + if (tmp_fd != -1) { + close(tmp_fd); + } + return; + } } if (tmp_fd == -1) { @@ -456,8 +509,8 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags) incoming_fd = dup(tmp_fd); if (incoming_fd == -1) { - fprintf(stderr, "could not allocate file descriptor %s\n", - strerror(errno)); + error_report("could not allocate file descriptor %s", strerror(errno)); + close(tmp_fd); return; } @@ -469,7 +522,7 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags) s->max_peer = 0; if (check_shm_size(s, incoming_fd) == -1) { - exit(-1); + exit(1); } /* mmap the region and map into the BAR2 */ @@ -479,8 +532,8 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags) "ivshmem.bar2", s->ivshmem_size, map_ptr); vmstate_register_ram(&s->ivshmem, DEVICE(s)); - IVSHMEM_DPRINTF("guest h/w addr = %" PRIu64 ", size = %" PRIu64 "\n", - s->ivshmem_offset, s->ivshmem_size); + IVSHMEM_DPRINTF("guest h/w addr = %p, size = %" PRIu64 "\n", + map_ptr, s->ivshmem_size); memory_region_add_subregion(&s->bar, 0, &s->ivshmem); @@ -501,7 +554,7 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags) /* this is an eventfd for a particular guest VM */ IVSHMEM_DPRINTF("eventfds[%ld][%d] = %d\n", incoming_posn, - guest_max_eventfd, incoming_fd); + guest_max_eventfd, incoming_fd); event_notifier_init_fd(&s->peers[incoming_posn].eventfds[guest_max_eventfd], incoming_fd); @@ -563,13 +616,13 @@ static uint64_t ivshmem_get_size(IVShmemState * s) { value <<= 30; break; default: - fprintf(stderr, "qemu: invalid ram size: %s\n", s->sizearg); + error_report("invalid ram size: %s", s->sizearg); exit(1); } /* BARs must be a power of 2 */ if (!is_power_of_two(value)) { - fprintf(stderr, "ivshmem: size must be power of 2\n"); + error_report("size must be power of 2"); exit(1); } @@ -621,7 +674,7 @@ static int ivshmem_load(QEMUFile* f, void *opaque, int version_id) } if (proxy->role_val == IVSHMEM_PEER) { - fprintf(stderr, "ivshmem: 'peer' devices are not migratable\n"); + error_report("'peer' devices are not migratable"); return -EINVAL; } @@ -659,13 +712,15 @@ static int pci_ivshmem_init(PCIDevice *dev) s->ivshmem_size = ivshmem_get_size(s); } + fifo8_create(&s->incoming_fifo, sizeof(long)); + register_savevm(DEVICE(dev), "ivshmem", 0, 0, ivshmem_save, ivshmem_load, dev); /* IRQFD requires MSI */ if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) && !ivshmem_has_feature(s, IVSHMEM_MSI)) { - fprintf(stderr, "ivshmem: ioeventfd/irqfd requires MSI\n"); + error_report("ioeventfd/irqfd requires MSI"); exit(1); } @@ -676,7 +731,7 @@ static int pci_ivshmem_init(PCIDevice *dev) } else if (strncmp(s->role, "master", 7) == 0) { s->role_val = IVSHMEM_MASTER; } else { - fprintf(stderr, "ivshmem: 'role' must be 'peer' or 'master'\n"); + error_report("'role' must be 'peer' or 'master'"); exit(1); } } else { @@ -684,8 +739,8 @@ static int pci_ivshmem_init(PCIDevice *dev) } if (s->role_val == IVSHMEM_PEER) { - error_set(&s->migration_blocker, QERR_DEVICE_FEATURE_BLOCKS_MIGRATION, - "peer mode", "ivshmem"); + error_setg(&s->migration_blocker, + "Migration is disabled when using feature 'peer mode' in device 'ivshmem'"); migrate_add_blocker(s->migration_blocker); } @@ -716,12 +771,12 @@ static int pci_ivshmem_init(PCIDevice *dev) * to the ivshmem server to receive the memory region */ if (s->shmobj != NULL) { - fprintf(stderr, "WARNING: do not specify both 'chardev' " - "and 'shm' with ivshmem\n"); + error_report("WARNING: do not specify both 'chardev' " + "and 'shm' with ivshmem"); } IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n", - s->server_chr->filename); + s->server_chr->filename); if (ivshmem_has_feature(s, IVSHMEM_MSI)) { ivshmem_setup_msi(s); @@ -745,7 +800,7 @@ static int pci_ivshmem_init(PCIDevice *dev) int fd; if (s->shmobj == NULL) { - fprintf(stderr, "Must specify 'chardev' or 'shm' to ivshmem\n"); + error_report("Must specify 'chardev' or 'shm' to ivshmem"); exit(1); } @@ -757,18 +812,18 @@ static int pci_ivshmem_init(PCIDevice *dev) S_IRWXU|S_IRWXG|S_IRWXO)) > 0) { /* truncate file to length PCI device's memory */ if (ftruncate(fd, s->ivshmem_size) != 0) { - fprintf(stderr, "ivshmem: could not truncate shared file\n"); + error_report("could not truncate shared file"); } } else if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO)) < 0) { - fprintf(stderr, "ivshmem: could not open shared file\n"); - exit(-1); + error_report("could not open shared file"); + exit(1); } if (check_shm_size(s, fd) == -1) { - exit(-1); + exit(1); } create_shared_memory_BAR(s, fd); @@ -789,12 +844,10 @@ static void pci_ivshmem_uninit(PCIDevice *dev) error_free(s->migration_blocker); } - memory_region_destroy(&s->ivshmem_mmio); memory_region_del_subregion(&s->bar, &s->ivshmem); vmstate_unregister_ram(&s->ivshmem, DEVICE(dev)); - memory_region_destroy(&s->ivshmem); - memory_region_destroy(&s->bar); unregister_savevm(DEVICE(dev), "ivshmem", s); + fifo8_destroy(&s->incoming_fifo); } static Property ivshmem_properties[] = { diff --git a/hw/misc/lm32_sys.c b/hw/misc/lm32_sys.c deleted file mode 100644 index e394f2e63b..0000000000 --- a/hw/misc/lm32_sys.c +++ /dev/null @@ -1,180 +0,0 @@ -/* - * QEMU model of the LatticeMico32 system control block. - * - * Copyright (c) 2010 Michael Walle <michael@walle.cc> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, see <http://www.gnu.org/licenses/>. - */ - -/* - * This model is mainly intended for testing purposes and doesn't fit to any - * real hardware. On the one hand it provides a control register (R_CTRL) on - * the other hand it supports the lm32 tests. - * - * A write to the control register causes a system shutdown. - * Tests first write the pointer to a test name to the test name register - * (R_TESTNAME) and then write a zero to the pass/fail register (R_PASSFAIL) if - * the test is passed or any non-zero value to it if the test is failed. - */ - -#include "hw/hw.h" -#include "hw/sysbus.h" -#include "trace.h" -#include "qemu/log.h" -#include "qemu/error-report.h" -#include "sysemu/sysemu.h" - -enum { - R_CTRL = 0, - R_PASSFAIL, - R_TESTNAME, - R_MAX -}; - -#define MAX_TESTNAME_LEN 32 - -#define TYPE_LM32_SYS "lm32-sys" -#define LM32_SYS(obj) OBJECT_CHECK(LM32SysState, (obj), TYPE_LM32_SYS) - -struct LM32SysState { - SysBusDevice parent_obj; - - MemoryRegion iomem; - uint32_t base; - uint32_t regs[R_MAX]; - uint8_t testname[MAX_TESTNAME_LEN]; -}; -typedef struct LM32SysState LM32SysState; - -static void copy_testname(LM32SysState *s) -{ - cpu_physical_memory_read(s->regs[R_TESTNAME], s->testname, - MAX_TESTNAME_LEN); - s->testname[MAX_TESTNAME_LEN - 1] = '\0'; -} - -static void sys_write(void *opaque, hwaddr addr, - uint64_t value, unsigned size) -{ - LM32SysState *s = opaque; - char *testname; - - trace_lm32_sys_memory_write(addr, value); - - addr >>= 2; - switch (addr) { - case R_CTRL: - qemu_system_shutdown_request(); - break; - case R_PASSFAIL: - s->regs[addr] = value; - testname = (char *)s->testname; - fprintf(stderr, "TC %-*s %s\n", MAX_TESTNAME_LEN, - testname, (value) ? "FAILED" : "OK"); - if (value) { - cpu_dump_state(qemu_get_cpu(0), stderr, fprintf, 0); - } - break; - case R_TESTNAME: - s->regs[addr] = value; - copy_testname(s); - break; - - default: - error_report("lm32_sys: write access to unknown register 0x" - TARGET_FMT_plx, addr << 2); - break; - } -} - -static bool sys_ops_accepts(void *opaque, hwaddr addr, - unsigned size, bool is_write) -{ - return is_write && size == 4; -} - -static const MemoryRegionOps sys_ops = { - .write = sys_write, - .valid.accepts = sys_ops_accepts, - .endianness = DEVICE_NATIVE_ENDIAN, -}; - -static void sys_reset(DeviceState *d) -{ - LM32SysState *s = LM32_SYS(d); - int i; - - for (i = 0; i < R_MAX; i++) { - s->regs[i] = 0; - } - memset(s->testname, 0, MAX_TESTNAME_LEN); -} - -static int lm32_sys_init(SysBusDevice *dev) -{ - LM32SysState *s = LM32_SYS(dev); - - memory_region_init_io(&s->iomem, OBJECT(dev), &sys_ops , s, - "sys", R_MAX * 4); - sysbus_init_mmio(dev, &s->iomem); - - /* Note: This device is not created in the board initialization, - * instead it has to be added with the -device parameter. Therefore, - * the device maps itself. */ - sysbus_mmio_map(dev, 0, s->base); - - return 0; -} - -static const VMStateDescription vmstate_lm32_sys = { - .name = "lm32-sys", - .version_id = 1, - .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { - VMSTATE_UINT32_ARRAY(regs, LM32SysState, R_MAX), - VMSTATE_BUFFER(testname, LM32SysState), - VMSTATE_END_OF_LIST() - } -}; - -static Property lm32_sys_properties[] = { - DEFINE_PROP_UINT32("base", LM32SysState, base, 0xffff0000), - DEFINE_PROP_END_OF_LIST(), -}; - -static void lm32_sys_class_init(ObjectClass *klass, void *data) -{ - DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); - - k->init = lm32_sys_init; - dc->reset = sys_reset; - dc->vmsd = &vmstate_lm32_sys; - dc->props = lm32_sys_properties; -} - -static const TypeInfo lm32_sys_info = { - .name = TYPE_LM32_SYS, - .parent = TYPE_SYS_BUS_DEVICE, - .instance_size = sizeof(LM32SysState), - .class_init = lm32_sys_class_init, -}; - -static void lm32_sys_register_types(void) -{ - type_register_static(&lm32_sys_info); -} - -type_init(lm32_sys_register_types) diff --git a/hw/misc/macio/cuda.c b/hw/misc/macio/cuda.c index bc71aa7ccd..b4273aa171 100644 --- a/hw/misc/macio/cuda.c +++ b/hw/misc/macio/cuda.c @@ -123,13 +123,22 @@ static void cuda_update_irq(CUDAState *s) } } +static uint64_t get_tb(uint64_t freq) +{ + return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL), + freq, get_ticks_per_sec()); +} + static unsigned int get_counter(CUDATimer *s) { int64_t d; unsigned int counter; + uint64_t tb_diff; + + /* Reverse of the tb calculation algorithm that Mac OS X uses on bootup. */ + tb_diff = get_tb(s->frequency) - s->load_time; + d = (tb_diff * 0xBF401675E5DULL) / (s->frequency << 24); - d = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - s->load_time, - CUDA_TIMER_FREQ, get_ticks_per_sec()); if (s->index == 0) { /* the timer goes down from latch to -1 (period of latch + 2) */ if (d <= (s->counter_value + 1)) { @@ -147,7 +156,7 @@ static unsigned int get_counter(CUDATimer *s) static void set_counter(CUDAState *s, CUDATimer *ti, unsigned int val) { CUDA_DPRINTF("T%d.counter=%d\n", 1 + (ti->timer == NULL), val); - ti->load_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); + ti->load_time = get_tb(s->frequency); ti->counter_value = val; cuda_timer_update(s, ti, ti->load_time); } @@ -617,8 +626,7 @@ static const VMStateDescription vmstate_cuda_timer = { .name = "cuda_timer", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT16(latch, CUDATimer), VMSTATE_UINT16(counter_value, CUDATimer), VMSTATE_INT64(load_time, CUDATimer), @@ -632,8 +640,7 @@ static const VMStateDescription vmstate_cuda = { .name = "cuda", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(a, CUDAState), VMSTATE_UINT8(b, CUDAState), VMSTATE_UINT8(dira, CUDAState), @@ -690,6 +697,8 @@ static void cuda_realizefn(DeviceState *dev, Error **errp) struct tm tm; s->timers[0].timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, cuda_timer1, s); + s->timers[0].frequency = s->frequency; + s->timers[1].frequency = s->frequency; qemu_get_timedate(&tm, 0); s->tick_offset = (uint32_t)mktimegm(&tm) + RTC_OFFSET; @@ -715,6 +724,11 @@ static void cuda_initfn(Object *obj) DEVICE(obj), "adb.0"); } +static Property cuda_properties[] = { + DEFINE_PROP_UINT64("frequency", CUDAState, frequency, 0), + DEFINE_PROP_END_OF_LIST() +}; + static void cuda_class_init(ObjectClass *oc, void *data) { DeviceClass *dc = DEVICE_CLASS(oc); @@ -722,6 +736,7 @@ static void cuda_class_init(ObjectClass *oc, void *data) dc->realize = cuda_realizefn; dc->reset = cuda_reset; dc->vmsd = &vmstate_cuda; + dc->props = cuda_properties; } static const TypeInfo cuda_type_info = { diff --git a/hw/misc/macio/mac_dbdma.c b/hw/misc/macio/mac_dbdma.c index f47a736182..b25e8511b2 100644 --- a/hw/misc/macio/mac_dbdma.c +++ b/hw/misc/macio/mac_dbdma.c @@ -719,8 +719,7 @@ static const VMStateDescription vmstate_dbdma_channel = { .name = "dbdma_channel", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, struct DBDMA_channel, DBDMA_REGS), VMSTATE_END_OF_LIST() } @@ -730,8 +729,7 @@ static const VMStateDescription vmstate_dbdma = { .name = "dbdma", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(channels, DBDMAState, DBDMA_CHANNELS, 1, vmstate_dbdma_channel, DBDMA_channel), VMSTATE_END_OF_LIST() @@ -750,9 +748,15 @@ static void dbdma_reset(void *opaque) void* DBDMA_init (MemoryRegion **dbdma_mem) { DBDMAState *s; + int i; s = g_malloc0(sizeof(DBDMAState)); + for (i = 0; i < DBDMA_CHANNELS; i++) { + DBDMA_io *io = &s->channels[i].io; + qemu_iovec_init(&io->iov, 1); + } + memory_region_init_io(&s->mem, NULL, &dbdma_ops, s, "dbdma", 0x1000); *dbdma_mem = &s->mem; vmstate_register(NULL, -1, &vmstate_dbdma, s); diff --git a/hw/misc/macio/macio.c b/hw/misc/macio/macio.c index 7f99aa0d5c..e0f1e88f54 100644 --- a/hw/misc/macio/macio.c +++ b/hw/misc/macio/macio.c @@ -42,6 +42,7 @@ typedef struct MacIOState void *dbdma; MemoryRegion *pic_mem; MemoryRegion *escc_mem; + uint64_t frequency; } MacIOState; #define OLDWORLD_MACIO(obj) \ @@ -243,13 +244,18 @@ static void timer_write(void *opaque, hwaddr addr, uint64_t value, static uint64_t timer_read(void *opaque, hwaddr addr, unsigned size) { uint32_t value = 0; + uint64_t systime = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); + uint64_t kltime; + + kltime = muldiv64(systime, 4194300, get_ticks_per_sec() * 4); + kltime = muldiv64(kltime, 18432000, 1048575); switch (addr) { case 0x38: - value = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); + value = kltime; break; case 0x3c: - value = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) >> 32; + value = kltime >> 32; break; } @@ -259,7 +265,7 @@ static uint64_t timer_read(void *opaque, hwaddr addr, unsigned size) static const MemoryRegionOps timer_ops = { .read = timer_read, .write = timer_write, - .endianness = DEVICE_NATIVE_ENDIAN, + .endianness = DEVICE_LITTLE_ENDIAN, }; static int macio_newworld_initfn(PCIDevice *d) @@ -346,12 +352,19 @@ static void macio_newworld_class_init(ObjectClass *oc, void *data) pdc->device_id = PCI_DEVICE_ID_APPLE_UNI_N_KEYL; } +static Property macio_properties[] = { + DEFINE_PROP_UINT64("frequency", MacIOState, frequency, 0), + DEFINE_PROP_END_OF_LIST() +}; + static void macio_class_init(ObjectClass *klass, void *data) { PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + DeviceClass *dc = DEVICE_CLASS(klass); k->vendor_id = PCI_VENDOR_ID_APPLE; k->class_id = PCI_CLASS_OTHERS << 8; + dc->props = macio_properties; } static const TypeInfo macio_oldworld_type_info = { @@ -398,6 +411,8 @@ void macio_init(PCIDevice *d, macio_state->escc_mem = escc_mem; /* Note: this code is strongly inspirated from the corresponding code in PearPC */ + qdev_prop_set_uint64(DEVICE(&macio_state->cuda), "frequency", + macio_state->frequency); qdev_init_nofail(DEVICE(d)); } diff --git a/hw/misc/max111x.c b/hw/misc/max111x.c index bba87c2ec5..bef3651d6e 100644 --- a/hw/misc/max111x.c +++ b/hw/misc/max111x.c @@ -110,8 +110,7 @@ static const VMStateDescription vmstate_max111x = { .name = "max111x", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_SSI_SLAVE(parent_obj, MAX111xState), VMSTATE_UINT8(tb1, MAX111xState), VMSTATE_UINT8(rb2, MAX111xState), diff --git a/hw/misc/milkymist-hpdmc.c b/hw/misc/milkymist-hpdmc.c index aef135e572..f5f4c1b343 100644 --- a/hw/misc/milkymist-hpdmc.c +++ b/hw/misc/milkymist-hpdmc.c @@ -143,8 +143,7 @@ static const VMStateDescription vmstate_milkymist_hpdmc = { .name = "milkymist-hpdmc", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistHpdmcState, R_MAX), VMSTATE_END_OF_LIST() } diff --git a/hw/misc/milkymist-pfpu.c b/hw/misc/milkymist-pfpu.c index b3b2143d51..609f33f9cd 100644 --- a/hw/misc/milkymist-pfpu.c +++ b/hw/misc/milkymist-pfpu.c @@ -513,8 +513,7 @@ static const VMStateDescription vmstate_milkymist_pfpu = { .name = "milkymist-pfpu", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistPFPUState, R_MAX), VMSTATE_UINT32_ARRAY(gp_regs, MilkymistPFPUState, 128), VMSTATE_UINT32_ARRAY(microcode, MilkymistPFPUState, MICROCODE_WORDS), diff --git a/hw/misc/mst_fpga.c b/hw/misc/mst_fpga.c index c96810fec1..d5090799f8 100644 --- a/hw/misc/mst_fpga.c +++ b/hw/misc/mst_fpga.c @@ -219,12 +219,11 @@ static int mst_fpga_init(SysBusDevice *sbd) } static VMStateDescription vmstate_mst_fpga_regs = { - .name = "mainstone_fpga", - .version_id = 0, - .minimum_version_id = 0, - .minimum_version_id_old = 0, - .post_load = mst_fpga_post_load, - .fields = (VMStateField []) { + .name = "mainstone_fpga", + .version_id = 0, + .minimum_version_id = 0, + .post_load = mst_fpga_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT32(prev_level, mst_irq_state), VMSTATE_UINT32(leddat1, mst_irq_state), VMSTATE_UINT32(leddat2, mst_irq_state), diff --git a/hw/misc/omap_gpmc.c b/hw/misc/omap_gpmc.c index 2047274123..a0de52f9bf 100644 --- a/hw/misc/omap_gpmc.c +++ b/hw/misc/omap_gpmc.c @@ -242,6 +242,10 @@ static void fill_prefetch_fifo(struct omap_gpmc_s *s) if (bytes > s->prefetch.count) { bytes = s->prefetch.count; } + if (is16bit) { + bytes &= ~1; + } + s->prefetch.count -= bytes; s->prefetch.fifopointer += bytes; fptr = 64 - s->prefetch.fifopointer; @@ -432,7 +436,7 @@ static void omap_gpmc_cs_unmap(struct omap_gpmc_s *s, int cs) } memory_region_del_subregion(get_system_memory(), &f->container); memory_region_del_subregion(&f->container, omap_gpmc_cs_memregion(s, cs)); - memory_region_destroy(&f->container); + object_unparent(OBJECT(&f->container)); } void omap_gpmc_reset(struct omap_gpmc_s *s) @@ -462,8 +466,6 @@ void omap_gpmc_reset(struct omap_gpmc_s *s) s->cs_file[i].config[3] = 0x10031003; s->cs_file[i].config[4] = 0x10f1111; s->cs_file[i].config[5] = 0; - s->cs_file[i].config[6] = 0xf00 | (i ? 0 : 1 << 6); - s->cs_file[i].config[6] = 0xf00; /* In theory we could probe attached devices for some CFG1 * bits here, but we just retain them across resets as they diff --git a/hw/misc/pci-testdev.c b/hw/misc/pci-testdev.c index ca53b3f500..c78a63e3a7 100644 --- a/hw/misc/pci-testdev.c +++ b/hw/misc/pci-testdev.c @@ -293,8 +293,6 @@ pci_testdev_uninit(PCIDevice *dev) g_free(d->tests[i].hdr); } g_free(d->tests); - memory_region_destroy(&d->mmio); - memory_region_destroy(&d->portio); } static void qdev_pci_testdev_reset(DeviceState *dev) diff --git a/hw/misc/pvpanic.c b/hw/misc/pvpanic.c index 5377feed69..994f8af8e6 100644 --- a/hw/misc/pvpanic.c +++ b/hw/misc/pvpanic.c @@ -14,12 +14,12 @@ #include "qapi/qmp/qobject.h" #include "qapi/qmp/qjson.h" -#include "monitor/monitor.h" #include "sysemu/sysemu.h" #include "qemu/log.h" #include "hw/nvram/fw_cfg.h" #include "hw/i386/pc.h" +#include "qapi-event.h" /* The bit of supported pv event */ #define PVPANIC_F_PANICKED 0 @@ -31,15 +31,6 @@ #define ISA_PVPANIC_DEVICE(obj) \ OBJECT_CHECK(PVPanicState, (obj), TYPE_ISA_PVPANIC_DEVICE) -static void panicked_mon_event(const char *action) -{ - QObject *data; - - data = qobject_from_jsonf("{ 'action': %s }", action); - monitor_protocol_event(QEVENT_GUEST_PANICKED, data); - qobject_decref(data); -} - static void handle_event(int event) { static bool logged; @@ -50,7 +41,7 @@ static void handle_event(int event) } if (event & PVPANIC_PANICKED) { - panicked_mon_event("pause"); + qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE, &error_abort); vm_stop(RUN_STATE_GUEST_PANICKED); return; } diff --git a/hw/misc/slavio_misc.c b/hw/misc/slavio_misc.c index 767544eca1..50985958a4 100644 --- a/hw/misc/slavio_misc.c +++ b/hw/misc/slavio_misc.c @@ -400,8 +400,7 @@ static const VMStateDescription vmstate_misc = { .name ="slavio_misc", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32(dummy, MiscState), VMSTATE_UINT8(config, MiscState), VMSTATE_UINT8(aux1, MiscState), diff --git a/hw/misc/tmp105.c b/hw/misc/tmp105.c index 63aa3d6277..f3fe8b81fd 100644 --- a/hw/misc/tmp105.c +++ b/hw/misc/tmp105.c @@ -68,10 +68,12 @@ static void tmp105_set_temperature(Object *obj, Visitor *v, void *opaque, const char *name, Error **errp) { TMP105State *s = TMP105(obj); + Error *local_err = NULL; int64_t temp; - visit_type_int(v, &temp, name, errp); - if (error_is_set(errp)) { + visit_type_int(v, &temp, name, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } if (temp >= 128000 || temp < -128000) { @@ -197,9 +199,8 @@ static const VMStateDescription vmstate_tmp105 = { .name = "TMP105", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = tmp105_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(len, TMP105State), VMSTATE_UINT8_ARRAY(buf, TMP105State, 2), VMSTATE_UINT8(pointer, TMP105State), diff --git a/hw/misc/vfio.c b/hw/misc/vfio.c index 9cf5b84045..fd318a122d 100644 --- a/hw/misc/vfio.c +++ b/hw/misc/vfio.c @@ -39,6 +39,7 @@ #include "qemu/range.h" #include "sysemu/kvm.h" #include "sysemu/sysemu.h" +#include "hw/misc/vfio.h" /* #define DEBUG_VFIO */ #ifdef DEBUG_VFIO @@ -119,10 +120,19 @@ typedef struct VFIOINTx { } VFIOINTx; typedef struct VFIOMSIVector { - EventNotifier interrupt; /* eventfd triggered on interrupt */ + /* + * Two interrupt paths are configured per vector. The first, is only used + * for interrupts injected via QEMU. This is typically the non-accel path, + * but may also be used when we want QEMU to handle masking and pending + * bits. The KVM path bypasses QEMU and is therefore higher performance, + * but requires masking at the device. virq is used to track the MSI route + * through KVM, thus kvm_interrupt is only available when virq is set to a + * valid (>= 0) value. + */ + EventNotifier interrupt; + EventNotifier kvm_interrupt; struct VFIODevice *vdev; /* back pointer to device */ - MSIMessage msg; /* cache the MSI message so we know when it changes */ - int virq; /* KVM irqchip route for QEMU bypass */ + int virq; bool use; } VFIOMSIVector; @@ -133,6 +143,15 @@ enum { VFIO_INT_MSIX = 3, }; +typedef struct VFIOAddressSpace { + AddressSpace *as; + QLIST_HEAD(, VFIOContainer) containers; + QLIST_ENTRY(VFIOAddressSpace) list; +} VFIOAddressSpace; + +static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces = + QLIST_HEAD_INITIALIZER(vfio_address_spaces); + struct VFIOGroup; typedef struct VFIOType1 { @@ -142,6 +161,7 @@ typedef struct VFIOType1 { } VFIOType1; typedef struct VFIOContainer { + VFIOAddressSpace *space; int fd; /* /dev/vfio/vfio, empowered by the attached groups */ struct { /* enable abstraction to support various iommu backends */ @@ -150,10 +170,18 @@ typedef struct VFIOContainer { }; void (*release)(struct VFIOContainer *); } iommu_data; + QLIST_HEAD(, VFIOGuestIOMMU) giommu_list; QLIST_HEAD(, VFIOGroup) group_list; QLIST_ENTRY(VFIOContainer) next; } VFIOContainer; +typedef struct VFIOGuestIOMMU { + VFIOContainer *container; + MemoryRegion *iommu; + Notifier n; + QLIST_ENTRY(VFIOGuestIOMMU) giommu_next; +} VFIOGuestIOMMU; + /* Cache of MSI-X setup plus extra mmap and memory region for split BAR map */ typedef struct VFIOMSIXInfo { uint8_t table_bar; @@ -234,9 +262,6 @@ static const VFIORomBlacklistEntry romblacklist[] = { #define MSIX_CAP_LENGTH 12 -static QLIST_HEAD(, VFIOContainer) - container_list = QLIST_HEAD_INITIALIZER(container_list); - static QLIST_HEAD(, VFIOGroup) group_list = QLIST_HEAD_INITIALIZER(group_list); @@ -626,9 +651,9 @@ static void vfio_msi_interrupt(void *opaque) MSIMessage msg; if (vdev->interrupt == VFIO_INT_MSIX) { - msg = msi_get_message(&vdev->pdev, nr); - } else if (vdev->interrupt == VFIO_INT_MSI) { msg = msix_get_message(&vdev->pdev, nr); + } else if (vdev->interrupt == VFIO_INT_MSI) { + msg = msi_get_message(&vdev->pdev, nr); } else { abort(); } @@ -664,12 +689,24 @@ static int vfio_enable_vectors(VFIODevice *vdev, bool msix) fds = (int32_t *)&irq_set->data; for (i = 0; i < vdev->nr_vectors; i++) { - if (!vdev->msi_vectors[i].use) { - fds[i] = -1; - continue; + int fd = -1; + + /* + * MSI vs MSI-X - The guest has direct access to MSI mask and pending + * bits, therefore we always use the KVM signaling path when setup. + * MSI-X mask and pending bits are emulated, so we want to use the + * KVM signaling path only when configured and unmasked. + */ + if (vdev->msi_vectors[i].use) { + if (vdev->msi_vectors[i].virq < 0 || + (msix && msix_is_masked(&vdev->pdev, i))) { + fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt); + } else { + fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt); + } } - fds[i] = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt); + fds[i] = fd; } ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set); @@ -679,6 +716,50 @@ static int vfio_enable_vectors(VFIODevice *vdev, bool msix) return ret; } +static void vfio_add_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage *msg, + bool msix) +{ + int virq; + + if ((msix && !VFIO_ALLOW_KVM_MSIX) || + (!msix && !VFIO_ALLOW_KVM_MSI) || !msg) { + return; + } + + if (event_notifier_init(&vector->kvm_interrupt, 0)) { + return; + } + + virq = kvm_irqchip_add_msi_route(kvm_state, *msg); + if (virq < 0) { + event_notifier_cleanup(&vector->kvm_interrupt); + return; + } + + if (kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->kvm_interrupt, + NULL, virq) < 0) { + kvm_irqchip_release_virq(kvm_state, virq); + event_notifier_cleanup(&vector->kvm_interrupt); + return; + } + + vector->virq = virq; +} + +static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector) +{ + kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->kvm_interrupt, + vector->virq); + kvm_irqchip_release_virq(kvm_state, vector->virq); + vector->virq = -1; + event_notifier_cleanup(&vector->kvm_interrupt); +} + +static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg) +{ + kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg); +} + static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr, MSIMessage *msg, IOHandler *handler) { @@ -691,30 +772,32 @@ static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr, vdev->host.function, nr); vector = &vdev->msi_vectors[nr]; - vector->vdev = vdev; - vector->use = true; - - msix_vector_use(pdev, nr); - if (event_notifier_init(&vector->interrupt, 0)) { - error_report("vfio: Error: event_notifier_init failed"); + if (!vector->use) { + vector->vdev = vdev; + vector->virq = -1; + if (event_notifier_init(&vector->interrupt, 0)) { + error_report("vfio: Error: event_notifier_init failed"); + } + vector->use = true; + msix_vector_use(pdev, nr); } + qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), + handler, NULL, vector); + /* * Attempt to enable route through KVM irqchip, * default to userspace handling if unavailable. */ - vector->virq = msg && VFIO_ALLOW_KVM_MSIX ? - kvm_irqchip_add_msi_route(kvm_state, *msg) : -1; - if (vector->virq < 0 || - kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt, - NULL, vector->virq) < 0) { - if (vector->virq >= 0) { - kvm_irqchip_release_virq(kvm_state, vector->virq); - vector->virq = -1; + if (vector->virq >= 0) { + if (!msg) { + vfio_remove_kvm_msi_virq(vector); + } else { + vfio_update_kvm_msi_virq(vector, *msg); } - qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), - handler, NULL, vector); + } else { + vfio_add_kvm_msi_virq(vector, msg, true); } /* @@ -745,7 +828,11 @@ static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr, irq_set->count = 1; pfd = (int32_t *)&irq_set->data; - *pfd = event_notifier_get_fd(&vector->interrupt); + if (vector->virq >= 0) { + *pfd = event_notifier_get_fd(&vector->kvm_interrupt); + } else { + *pfd = event_notifier_get_fd(&vector->interrupt); + } ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set); g_free(irq_set); @@ -767,50 +854,41 @@ static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr) { VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev); VFIOMSIVector *vector = &vdev->msi_vectors[nr]; - int argsz; - struct vfio_irq_set *irq_set; - int32_t *pfd; DPRINTF("%s(%04x:%02x:%02x.%x) vector %d released\n", __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, vdev->host.function, nr); /* - * XXX What's the right thing to do here? This turns off the interrupt - * completely, but do we really just want to switch the interrupt to - * bouncing through userspace and let msix.c drop it? Not sure. + * There are still old guests that mask and unmask vectors on every + * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of + * the KVM setup in place, simply switch VFIO to use the non-bypass + * eventfd. We'll then fire the interrupt through QEMU and the MSI-X + * core will mask the interrupt and set pending bits, allowing it to + * be re-asserted on unmask. Nothing to do if already using QEMU mode. */ - msix_vector_unuse(pdev, nr); - - argsz = sizeof(*irq_set) + sizeof(*pfd); + if (vector->virq >= 0) { + int argsz; + struct vfio_irq_set *irq_set; + int32_t *pfd; - irq_set = g_malloc0(argsz); - irq_set->argsz = argsz; - irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | - VFIO_IRQ_SET_ACTION_TRIGGER; - irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX; - irq_set->start = nr; - irq_set->count = 1; - pfd = (int32_t *)&irq_set->data; + argsz = sizeof(*irq_set) + sizeof(*pfd); - *pfd = -1; + irq_set = g_malloc0(argsz); + irq_set->argsz = argsz; + irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | + VFIO_IRQ_SET_ACTION_TRIGGER; + irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX; + irq_set->start = nr; + irq_set->count = 1; + pfd = (int32_t *)&irq_set->data; - ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set); + *pfd = event_notifier_get_fd(&vector->interrupt); - g_free(irq_set); + ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set); - if (vector->virq < 0) { - qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), - NULL, NULL, NULL); - } else { - kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt, - vector->virq); - kvm_irqchip_release_virq(kvm_state, vector->virq); - vector->virq = -1; + g_free(irq_set); } - - event_notifier_cleanup(&vector->interrupt); - vector->use = false; } static void vfio_enable_msix(VFIODevice *vdev) @@ -858,30 +936,29 @@ retry: for (i = 0; i < vdev->nr_vectors; i++) { VFIOMSIVector *vector = &vdev->msi_vectors[i]; + MSIMessage msg = msi_get_message(&vdev->pdev, i); vector->vdev = vdev; + vector->virq = -1; vector->use = true; if (event_notifier_init(&vector->interrupt, 0)) { error_report("vfio: Error: event_notifier_init failed"); } - vector->msg = msi_get_message(&vdev->pdev, i); + qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), + vfio_msi_interrupt, NULL, vector); /* * Attempt to enable route through KVM irqchip, * default to userspace handling if unavailable. */ - vector->virq = VFIO_ALLOW_KVM_MSI ? - kvm_irqchip_add_msi_route(kvm_state, vector->msg) : -1; - if (vector->virq < 0 || - kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt, - NULL, vector->virq) < 0) { - qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), - vfio_msi_interrupt, NULL, vector); - } + vfio_add_kvm_msi_virq(vector, &msg, false); } + /* Set interrupt type prior to possible interrupts */ + vdev->interrupt = VFIO_INT_MSI; + ret = vfio_enable_vectors(vdev, false); if (ret) { if (ret < 0) { @@ -894,14 +971,10 @@ retry: for (i = 0; i < vdev->nr_vectors; i++) { VFIOMSIVector *vector = &vdev->msi_vectors[i]; if (vector->virq >= 0) { - kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt, - vector->virq); - kvm_irqchip_release_virq(kvm_state, vector->virq); - vector->virq = -1; - } else { - qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), - NULL, NULL, NULL); + vfio_remove_kvm_msi_virq(vector); } + qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), + NULL, NULL, NULL); event_notifier_cleanup(&vector->interrupt); } @@ -913,11 +986,17 @@ retry: } vdev->nr_vectors = 0; + /* + * Failing to setup MSI doesn't really fall within any specification. + * Let's try leaving interrupts disabled and hope the guest figures + * out to fall back to INTx for this device. + */ + error_report("vfio: Error: Failed to enable MSI"); + vdev->interrupt = VFIO_INT_NONE; + return; } - vdev->interrupt = VFIO_INT_MSI; - DPRINTF("%s(%04x:%02x:%02x.%x) Enabled %d MSI vectors\n", __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, vdev->host.function, vdev->nr_vectors); @@ -925,6 +1004,20 @@ retry: static void vfio_disable_msi_common(VFIODevice *vdev) { + int i; + + for (i = 0; i < vdev->nr_vectors; i++) { + VFIOMSIVector *vector = &vdev->msi_vectors[i]; + if (vdev->msi_vectors[i].use) { + if (vector->virq >= 0) { + vfio_remove_kvm_msi_virq(vector); + } + qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), + NULL, NULL, NULL); + event_notifier_cleanup(&vector->interrupt); + } + } + g_free(vdev->msi_vectors); vdev->msi_vectors = NULL; vdev->nr_vectors = 0; @@ -946,6 +1039,7 @@ static void vfio_disable_msix(VFIODevice *vdev) for (i = 0; i < vdev->nr_vectors; i++) { if (vdev->msi_vectors[i].use) { vfio_msix_vector_release(&vdev->pdev, i); + msix_vector_unuse(&vdev->pdev, i); } } @@ -961,30 +1055,7 @@ static void vfio_disable_msix(VFIODevice *vdev) static void vfio_disable_msi(VFIODevice *vdev) { - int i; - vfio_disable_irqindex(vdev, VFIO_PCI_MSI_IRQ_INDEX); - - for (i = 0; i < vdev->nr_vectors; i++) { - VFIOMSIVector *vector = &vdev->msi_vectors[i]; - - if (!vector->use) { - continue; - } - - if (vector->virq >= 0) { - kvm_irqchip_remove_irqfd_notifier(kvm_state, - &vector->interrupt, vector->virq); - kvm_irqchip_release_virq(kvm_state, vector->virq); - vector->virq = -1; - } else { - qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), - NULL, NULL, NULL); - } - - event_notifier_cleanup(&vector->interrupt); - } - vfio_disable_msi_common(vdev); DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain, @@ -1004,17 +1075,7 @@ static void vfio_update_msi(VFIODevice *vdev) } msg = msi_get_message(&vdev->pdev, i); - - if (msg.address != vector->msg.address || - msg.data != vector->msg.data) { - - DPRINTF("%s(%04x:%02x:%02x.%x) MSI vector %d changed\n", - __func__, vdev->host.domain, vdev->host.bus, - vdev->host.slot, vdev->host.function, i); - - kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg); - vector->msg = msg; - } + vfio_update_kvm_msi_virq(vector, msg); } } @@ -1189,7 +1250,13 @@ static void vfio_pci_load_rom(VFIODevice *vdev) static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size) { VFIODevice *vdev = opaque; - uint64_t val = ((uint64_t)1 << (size * 8)) - 1; + union { + uint8_t byte; + uint16_t word; + uint32_t dword; + uint64_t qword; + } val; + uint64_t data = 0; /* Load the ROM lazily when the guest tries to read it */ if (unlikely(!vdev->rom && !vdev->rom_read_failed)) { @@ -1199,11 +1266,26 @@ static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size) memcpy(&val, vdev->rom + addr, (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0); + switch (size) { + case 1: + data = val.byte; + break; + case 2: + data = le16_to_cpu(val.word); + break; + case 4: + data = le32_to_cpu(val.dword); + break; + default: + hw_error("vfio: unsupported read size, %d bytes\n", size); + break; + } + DPRINTF("%s(%04x:%02x:%02x.%x, 0x%"HWADDR_PRIx", 0x%x) = 0x%"PRIx64"\n", __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, - vdev->host.function, addr, size, val); + vdev->host.function, addr, size, data); - return val; + return data; } static void vfio_rom_write(void *opaque, hwaddr addr, @@ -1668,6 +1750,149 @@ static void vfio_probe_ati_bar4_window_quirk(VFIODevice *vdev, int nr) vdev->host.function); } +#define PCI_VENDOR_ID_REALTEK 0x10ec + +/* + * RTL8168 devices have a backdoor that can access the MSI-X table. At BAR2 + * offset 0x70 there is a dword data register, offset 0x74 is a dword address + * register. According to the Linux r8169 driver, the MSI-X table is addressed + * when the "type" portion of the address register is set to 0x1. This appears + * to be bits 16:30. Bit 31 is both a write indicator and some sort of + * "address latched" indicator. Bits 12:15 are a mask field, which we can + * ignore because the MSI-X table should always be accessed as a dword (full + * mask). Bits 0:11 is offset within the type. + * + * Example trace: + * + * Read from MSI-X table offset 0 + * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x1f000, 4) // store read addr + * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x8001f000 // latch + * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x70, 4) = 0xfee00398 // read data + * + * Write 0xfee00000 to MSI-X table offset 0 + * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x70, 0xfee00000, 4) // write data + * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x8001f000, 4) // do write + * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x1f000 // complete + */ + +static uint64_t vfio_rtl8168_window_quirk_read(void *opaque, + hwaddr addr, unsigned size) +{ + VFIOQuirk *quirk = opaque; + VFIODevice *vdev = quirk->vdev; + + switch (addr) { + case 4: /* address */ + if (quirk->data.flags) { + DPRINTF("%s fake read(%04x:%02x:%02x.%d)\n", + memory_region_name(&quirk->mem), vdev->host.domain, + vdev->host.bus, vdev->host.slot, vdev->host.function); + + return quirk->data.address_match ^ 0x10000000U; + } + break; + case 0: /* data */ + if (quirk->data.flags) { + uint64_t val; + + DPRINTF("%s MSI-X table read(%04x:%02x:%02x.%d)\n", + memory_region_name(&quirk->mem), vdev->host.domain, + vdev->host.bus, vdev->host.slot, vdev->host.function); + + if (!(vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX)) { + return 0; + } + + io_mem_read(&vdev->pdev.msix_table_mmio, + (hwaddr)(quirk->data.address_match & 0xfff), + &val, size); + return val; + } + } + + DPRINTF("%s direct read(%04x:%02x:%02x.%d)\n", + memory_region_name(&quirk->mem), vdev->host.domain, + vdev->host.bus, vdev->host.slot, vdev->host.function); + + return vfio_bar_read(&vdev->bars[quirk->data.bar], addr + 0x70, size); +} + +static void vfio_rtl8168_window_quirk_write(void *opaque, hwaddr addr, + uint64_t data, unsigned size) +{ + VFIOQuirk *quirk = opaque; + VFIODevice *vdev = quirk->vdev; + + switch (addr) { + case 4: /* address */ + if ((data & 0x7fff0000) == 0x10000) { + if (data & 0x10000000U && + vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX) { + + DPRINTF("%s MSI-X table write(%04x:%02x:%02x.%d)\n", + memory_region_name(&quirk->mem), vdev->host.domain, + vdev->host.bus, vdev->host.slot, vdev->host.function); + + io_mem_write(&vdev->pdev.msix_table_mmio, + (hwaddr)(quirk->data.address_match & 0xfff), + data, size); + } + + quirk->data.flags = 1; + quirk->data.address_match = data; + + return; + } + quirk->data.flags = 0; + break; + case 0: /* data */ + quirk->data.address_mask = data; + break; + } + + DPRINTF("%s direct write(%04x:%02x:%02x.%d)\n", + memory_region_name(&quirk->mem), vdev->host.domain, + vdev->host.bus, vdev->host.slot, vdev->host.function); + + vfio_bar_write(&vdev->bars[quirk->data.bar], addr + 0x70, data, size); +} + +static const MemoryRegionOps vfio_rtl8168_window_quirk = { + .read = vfio_rtl8168_window_quirk_read, + .write = vfio_rtl8168_window_quirk_write, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + .unaligned = false, + }, + .endianness = DEVICE_LITTLE_ENDIAN, +}; + +static void vfio_probe_rtl8168_bar2_window_quirk(VFIODevice *vdev, int nr) +{ + PCIDevice *pdev = &vdev->pdev; + VFIOQuirk *quirk; + + if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_REALTEK || + pci_get_word(pdev->config + PCI_DEVICE_ID) != 0x8168 || nr != 2) { + return; + } + + quirk = g_malloc0(sizeof(*quirk)); + quirk->vdev = vdev; + quirk->data.bar = nr; + + memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_rtl8168_window_quirk, + quirk, "vfio-rtl8168-window-quirk", 8); + memory_region_add_subregion_overlap(&vdev->bars[nr].mem, + 0x70, &quirk->mem, 1); + + QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next); + + DPRINTF("Enabled RTL8168 BAR2 window quirk for device %04x:%02x:%02x.%x\n", + vdev->host.domain, vdev->host.bus, vdev->host.slot, + vdev->host.function); +} /* * Trap the BAR2 MMIO window to config space as well. */ @@ -1969,9 +2194,13 @@ static void vfio_probe_nvidia_bar0_88000_quirk(VFIODevice *vdev, int nr) { PCIDevice *pdev = &vdev->pdev; VFIOQuirk *quirk; + uint16_t vendor, class; - if (!vdev->has_vga || nr != 0 || - pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) { + vendor = pci_get_word(pdev->config + PCI_VENDOR_ID); + class = pci_get_word(pdev->config + PCI_CLASS_DEVICE); + + if (nr != 0 || vendor != PCI_VENDOR_ID_NVIDIA || + class != PCI_CLASS_DISPLAY_VGA) { return; } @@ -2057,7 +2286,7 @@ static void vfio_vga_quirk_teardown(VFIODevice *vdev) while (!QLIST_EMPTY(&vdev->vga.region[i].quirks)) { VFIOQuirk *quirk = QLIST_FIRST(&vdev->vga.region[i].quirks); memory_region_del_subregion(&vdev->vga.region[i].mem, &quirk->mem); - memory_region_destroy(&quirk->mem); + object_unparent(OBJECT(&quirk->mem)); QLIST_REMOVE(quirk, next); g_free(quirk); } @@ -2071,6 +2300,7 @@ static void vfio_bar_quirk_setup(VFIODevice *vdev, int nr) vfio_probe_nvidia_bar5_window_quirk(vdev, nr); vfio_probe_nvidia_bar0_88000_quirk(vdev, nr); vfio_probe_nvidia_bar0_1800_quirk(vdev, nr); + vfio_probe_rtl8168_bar2_window_quirk(vdev, nr); } static void vfio_bar_quirk_teardown(VFIODevice *vdev, int nr) @@ -2080,7 +2310,7 @@ static void vfio_bar_quirk_teardown(VFIODevice *vdev, int nr) while (!QLIST_EMPTY(&bar->quirks)) { VFIOQuirk *quirk = QLIST_FIRST(&bar->quirks); memory_region_del_subregion(&bar->mem, &quirk->mem); - memory_region_destroy(&quirk->mem); + object_unparent(OBJECT(&quirk->mem)); QLIST_REMOVE(quirk, next); g_free(quirk); } @@ -2232,7 +2462,8 @@ static int vfio_dma_map(VFIOContainer *container, hwaddr iova, static bool vfio_listener_skipped_section(MemoryRegionSection *section) { - return !memory_region_is_ram(section->mr) || + return (!memory_region_is_ram(section->mr) && + !memory_region_is_iommu(section->mr)) || /* * Sizing an enabled 64-bit BAR can cause spurious mappings to * addresses in the upper part of the 64-bit address space. These @@ -2242,17 +2473,75 @@ static bool vfio_listener_skipped_section(MemoryRegionSection *section) section->offset_within_address_space & (1ULL << 63); } +static void vfio_iommu_map_notify(Notifier *n, void *data) +{ + VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n); + VFIOContainer *container = giommu->container; + IOMMUTLBEntry *iotlb = data; + MemoryRegion *mr; + hwaddr xlat; + hwaddr len = iotlb->addr_mask + 1; + void *vaddr; + int ret; + + DPRINTF("iommu map @ %"HWADDR_PRIx" - %"HWADDR_PRIx"\n", + iotlb->iova, iotlb->iova + iotlb->addr_mask); + + /* + * The IOMMU TLB entry we have just covers translation through + * this IOMMU to its immediate target. We need to translate + * it the rest of the way through to memory. + */ + mr = address_space_translate(&address_space_memory, + iotlb->translated_addr, + &xlat, &len, iotlb->perm & IOMMU_WO); + if (!memory_region_is_ram(mr)) { + DPRINTF("iommu map to non memory area %"HWADDR_PRIx"\n", + xlat); + return; + } + /* + * Translation truncates length to the IOMMU page size, + * check that it did not truncate too much. + */ + if (len & iotlb->addr_mask) { + DPRINTF("iommu has granularity incompatible with target AS\n"); + return; + } + + if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) { + vaddr = memory_region_get_ram_ptr(mr) + xlat; + + ret = vfio_dma_map(container, iotlb->iova, + iotlb->addr_mask + 1, vaddr, + !(iotlb->perm & IOMMU_WO) || mr->readonly); + if (ret) { + error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", " + "0x%"HWADDR_PRIx", %p) = %d (%m)", + container, iotlb->iova, + iotlb->addr_mask + 1, vaddr, ret); + } + } else { + ret = vfio_dma_unmap(container, iotlb->iova, iotlb->addr_mask + 1); + if (ret) { + error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", " + "0x%"HWADDR_PRIx") = %d (%m)", + container, iotlb->iova, + iotlb->addr_mask + 1, ret); + } + } +} + static void vfio_listener_region_add(MemoryListener *listener, MemoryRegionSection *section) { VFIOContainer *container = container_of(listener, VFIOContainer, iommu_data.type1.listener); hwaddr iova, end; + Int128 llend; void *vaddr; int ret; - assert(!memory_region_is_iommu(section->mr)); - if (vfio_listener_skipped_section(section)) { DPRINTF("SKIPPING region_add %"HWADDR_PRIx" - %"PRIx64"\n", section->offset_within_address_space, @@ -2268,21 +2557,65 @@ static void vfio_listener_region_add(MemoryListener *listener, } iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); - end = (section->offset_within_address_space + int128_get64(section->size)) & - TARGET_PAGE_MASK; + llend = int128_make64(section->offset_within_address_space); + llend = int128_add(llend, section->size); + llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK)); + + if (int128_ge(int128_make64(iova), llend)) { + return; + } + + memory_region_ref(section->mr); + + if (memory_region_is_iommu(section->mr)) { + VFIOGuestIOMMU *giommu; + + DPRINTF("region_add [iommu] %"HWADDR_PRIx" - %"HWADDR_PRIx"\n", + iova, int128_get64(int128_sub(llend, int128_one()))); + /* + * FIXME: We should do some checking to see if the + * capabilities of the host VFIO IOMMU are adequate to model + * the guest IOMMU + * + * FIXME: For VFIO iommu types which have KVM acceleration to + * avoid bouncing all map/unmaps through qemu this way, this + * would be the right place to wire that up (tell the KVM + * device emulation the VFIO iommu handles to use). + */ + /* + * This assumes that the guest IOMMU is empty of + * mappings at this point. + * + * One way of doing this is: + * 1. Avoid sharing IOMMUs between emulated devices or different + * IOMMU groups. + * 2. Implement VFIO_IOMMU_ENABLE in the host kernel to fail if + * there are some mappings in IOMMU. + * + * VFIO on SPAPR does that. Other IOMMU models may do that different, + * they must make sure there are no existing mappings or + * loop through existing mappings to map them into VFIO. + */ + giommu = g_malloc0(sizeof(*giommu)); + giommu->iommu = section->mr; + giommu->container = container; + giommu->n.notify = vfio_iommu_map_notify; + QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next); + memory_region_register_iommu_notifier(giommu->iommu, &giommu->n); - if (iova >= end) { return; } + /* Here we assume that memory_region_is_ram(section->mr)==true */ + + end = int128_get64(llend); vaddr = memory_region_get_ram_ptr(section->mr) + section->offset_within_region + (iova - section->offset_within_address_space); - DPRINTF("region_add %"HWADDR_PRIx" - %"HWADDR_PRIx" [%p]\n", + DPRINTF("region_add [ram] %"HWADDR_PRIx" - %"HWADDR_PRIx" [%p]\n", iova, end - 1, vaddr); - memory_region_ref(section->mr); ret = vfio_dma_map(container, iova, end - iova, vaddr, section->readonly); if (ret) { error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", " @@ -2326,6 +2659,27 @@ static void vfio_listener_region_del(MemoryListener *listener, return; } + if (memory_region_is_iommu(section->mr)) { + VFIOGuestIOMMU *giommu; + + QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) { + if (giommu->iommu == section->mr) { + memory_region_unregister_iommu_notifier(&giommu->n); + QLIST_REMOVE(giommu, giommu_next); + g_free(giommu); + break; + } + } + + /* + * FIXME: We assume the one big unmap below is adequate to + * remove any individual page mappings in the IOMMU which + * might have been copied into VFIO. This works for a page table + * based IOMMU where a big unmap flattens a large range of IO-PTEs. + * That may not be true for all IOMMU types. + */ + } + iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); end = (section->offset_within_address_space + int128_get64(section->size)) & TARGET_PAGE_MASK; @@ -2523,15 +2877,11 @@ static void vfio_unmap_bar(VFIODevice *vdev, int nr) memory_region_del_subregion(&bar->mem, &bar->mmap_mem); munmap(bar->mmap, memory_region_size(&bar->mmap_mem)); - memory_region_destroy(&bar->mmap_mem); if (vdev->msix && vdev->msix->table_bar == nr) { memory_region_del_subregion(&bar->mem, &vdev->msix->mmap_mem); munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem)); - memory_region_destroy(&vdev->msix->mmap_mem); } - - memory_region_destroy(&bar->mem); } static int vfio_mmap_bar(VFIODevice *vdev, VFIOBAR *bar, @@ -2561,6 +2911,7 @@ static int vfio_mmap_bar(VFIODevice *vdev, VFIOBAR *bar, } memory_region_init_ram_ptr(submem, OBJECT(vdev), name, size, *map); + memory_region_set_skip_dump(submem); } else { empty_region: /* Create a zero sized sub-region to make cleanup easy. */ @@ -2684,9 +3035,6 @@ static void vfio_unmap_bars(VFIODevice *vdev) if (vdev->has_vga) { vfio_vga_quirk_teardown(vdev); pci_unregister_vga(&vdev->pdev); - memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem); - memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem); - memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem); } } @@ -3274,16 +3622,43 @@ static void vfio_kvm_device_del_group(VFIOGroup *group) #endif } -static int vfio_connect_container(VFIOGroup *group) +static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as) +{ + VFIOAddressSpace *space; + + QLIST_FOREACH(space, &vfio_address_spaces, list) { + if (space->as == as) { + return space; + } + } + + /* No suitable VFIOAddressSpace, create a new one */ + space = g_malloc0(sizeof(*space)); + space->as = as; + QLIST_INIT(&space->containers); + + QLIST_INSERT_HEAD(&vfio_address_spaces, space, list); + + return space; +} + +static void vfio_put_address_space(VFIOAddressSpace *space) +{ + if (QLIST_EMPTY(&space->containers)) { + QLIST_REMOVE(space, list); + g_free(space); + } +} + +static int vfio_connect_container(VFIOGroup *group, AddressSpace *as) { VFIOContainer *container; int ret, fd; + VFIOAddressSpace *space; - if (group->container) { - return 0; - } + space = vfio_get_address_space(as); - QLIST_FOREACH(container, &container_list, next) { + QLIST_FOREACH(container, &space->containers, next) { if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) { group->container = container; QLIST_INSERT_HEAD(&container->group_list, group, container_next); @@ -3294,35 +3669,35 @@ static int vfio_connect_container(VFIOGroup *group) fd = qemu_open("/dev/vfio/vfio", O_RDWR); if (fd < 0) { error_report("vfio: failed to open /dev/vfio/vfio: %m"); - return -errno; + ret = -errno; + goto put_space_exit; } ret = ioctl(fd, VFIO_GET_API_VERSION); if (ret != VFIO_API_VERSION) { error_report("vfio: supported vfio version: %d, " "reported version: %d", VFIO_API_VERSION, ret); - close(fd); - return -EINVAL; + ret = -EINVAL; + goto close_fd_exit; } container = g_malloc0(sizeof(*container)); + container->space = space; container->fd = fd; if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) { ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd); if (ret) { error_report("vfio: failed to set group container: %m"); - g_free(container); - close(fd); - return -errno; + ret = -errno; + goto free_container_exit; } ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU); if (ret) { error_report("vfio: failed to set iommu for container: %m"); - g_free(container); - close(fd); - return -errno; + ret = -errno; + goto free_container_exit; } container->iommu_data.type1.listener = vfio_memory_listener; @@ -3333,29 +3708,72 @@ static int vfio_connect_container(VFIOGroup *group) if (container->iommu_data.type1.error) { ret = container->iommu_data.type1.error; - vfio_listener_release(container); - g_free(container); - close(fd); error_report("vfio: memory listener initialization failed for container"); - return ret; + goto listener_release_exit; } container->iommu_data.type1.initialized = true; + } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) { + ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd); + if (ret) { + error_report("vfio: failed to set group container: %m"); + ret = -errno; + goto free_container_exit; + } + + ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_SPAPR_TCE_IOMMU); + if (ret) { + error_report("vfio: failed to set iommu for container: %m"); + ret = -errno; + goto free_container_exit; + } + + /* + * The host kernel code implementing VFIO_IOMMU_DISABLE is called + * when container fd is closed so we do not call it explicitly + * in this file. + */ + ret = ioctl(fd, VFIO_IOMMU_ENABLE); + if (ret) { + error_report("vfio: failed to enable container: %m"); + ret = -errno; + goto free_container_exit; + } + + container->iommu_data.type1.listener = vfio_memory_listener; + container->iommu_data.release = vfio_listener_release; + + memory_listener_register(&container->iommu_data.type1.listener, + container->space->as); + } else { error_report("vfio: No available IOMMU models"); - g_free(container); - close(fd); - return -EINVAL; + ret = -EINVAL; + goto free_container_exit; } QLIST_INIT(&container->group_list); - QLIST_INSERT_HEAD(&container_list, container, next); + QLIST_INSERT_HEAD(&space->containers, container, next); group->container = container; QLIST_INSERT_HEAD(&container->group_list, group, container_next); return 0; + +listener_release_exit: + vfio_listener_release(container); + +free_container_exit: + g_free(container); + +close_fd_exit: + close(fd); + +put_space_exit: + vfio_put_address_space(space); + + return ret; } static void vfio_disconnect_container(VFIOGroup *group) @@ -3371,6 +3789,8 @@ static void vfio_disconnect_container(VFIOGroup *group) group->container = NULL; if (QLIST_EMPTY(&container->group_list)) { + VFIOAddressSpace *space = container->space; + if (container->iommu_data.release) { container->iommu_data.release(container); } @@ -3378,10 +3798,12 @@ static void vfio_disconnect_container(VFIOGroup *group) DPRINTF("vfio_disconnect_container: close container->fd\n"); close(container->fd); g_free(container); + + vfio_put_address_space(space); } } -static VFIOGroup *vfio_get_group(int groupid) +static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as) { VFIOGroup *group; char path[32]; @@ -3389,7 +3811,14 @@ static VFIOGroup *vfio_get_group(int groupid) QLIST_FOREACH(group, &group_list, next) { if (group->groupid == groupid) { - return group; + /* Found it. Now is it already in the right context? */ + if (group->container->space->as == as) { + return group; + } else { + error_report("vfio: group %d used in multiple address spaces", + group->groupid); + return NULL; + } } } @@ -3399,34 +3828,27 @@ static VFIOGroup *vfio_get_group(int groupid) group->fd = qemu_open(path, O_RDWR); if (group->fd < 0) { error_report("vfio: error opening %s: %m", path); - g_free(group); - return NULL; + goto free_group_exit; } if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) { error_report("vfio: error getting group status: %m"); - close(group->fd); - g_free(group); - return NULL; + goto close_fd_exit; } if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) { error_report("vfio: error, group %d is not viable, please ensure " "all devices within the iommu_group are bound to their " "vfio bus driver.", groupid); - close(group->fd); - g_free(group); - return NULL; + goto close_fd_exit; } group->groupid = groupid; QLIST_INIT(&group->device_list); - if (vfio_connect_container(group)) { + if (vfio_connect_container(group, as)) { error_report("vfio: failed to setup container for group %d", groupid); - close(group->fd); - g_free(group); - return NULL; + goto close_fd_exit; } if (QLIST_EMPTY(&group_list)) { @@ -3438,6 +3860,14 @@ static VFIOGroup *vfio_get_group(int groupid) vfio_kvm_device_add_group(group); return group; + +close_fd_exit: + close(group->fd); + +free_group_exit: + g_free(group); + + return NULL; } static void vfio_put_group(VFIOGroup *group) @@ -3646,7 +4076,7 @@ static void vfio_err_notifier_handler(void *opaque) __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, vdev->host.function); - vm_stop(RUN_STATE_IO_ERROR); + vm_stop(RUN_STATE_INTERNAL_ERROR); } /* @@ -3768,7 +4198,7 @@ static int vfio_initfn(PCIDevice *pdev) DPRINTF("%s(%04x:%02x:%02x.%x) group %d\n", __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot, vdev->host.function, groupid); - group = vfio_get_group(groupid); + group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev)); if (!group) { error_report("vfio: failed to get group %d", groupid); return -ENOENT; @@ -3867,7 +4297,6 @@ static int vfio_initfn(PCIDevice *pdev) } } - add_boot_device_path(vdev->bootindex, &pdev->qdev, NULL); vfio_register_err_notifier(vdev); return 0; @@ -3936,13 +4365,22 @@ post_reset: vfio_pci_post_reset(vdev); } +static void vfio_instance_init(Object *obj) +{ + PCIDevice *pci_dev = PCI_DEVICE(obj); + VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, PCI_DEVICE(obj)); + + device_add_bootindex_property(obj, &vdev->bootindex, + "bootindex", NULL, + &pci_dev->qdev, NULL); +} + static Property vfio_pci_dev_properties[] = { DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host), DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIODevice, intx.mmap_timeout, 1100), DEFINE_PROP_BIT("x-vga", VFIODevice, features, VFIO_FEATURE_ENABLE_VGA_BIT, false), - DEFINE_PROP_INT32("bootindex", VFIODevice, bootindex, -1), /* * TODO - support passed fds... is this necessary? * DEFINE_PROP_STRING("vfiofd", VFIODevice, vfiofd_name), @@ -3978,6 +4416,7 @@ static const TypeInfo vfio_pci_dev_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(VFIODevice), .class_init = vfio_pci_dev_class_init, + .instance_init = vfio_instance_init, }; static void register_vfio_pci_dev_type(void) @@ -3986,3 +4425,47 @@ static void register_vfio_pci_dev_type(void) } type_init(register_vfio_pci_dev_type) + +static int vfio_container_do_ioctl(AddressSpace *as, int32_t groupid, + int req, void *param) +{ + VFIOGroup *group; + VFIOContainer *container; + int ret = -1; + + group = vfio_get_group(groupid, as); + if (!group) { + error_report("vfio: group %d not registered", groupid); + return ret; + } + + container = group->container; + if (group->container) { + ret = ioctl(container->fd, req, param); + if (ret < 0) { + error_report("vfio: failed to ioctl container: ret=%d, %s", + ret, strerror(errno)); + } + } + + vfio_put_group(group); + + return ret; +} + +int vfio_container_ioctl(AddressSpace *as, int32_t groupid, + int req, void *param) +{ + /* We allow only certain ioctls to the container */ + switch (req) { + case VFIO_CHECK_EXTENSION: + case VFIO_IOMMU_SPAPR_TCE_GET_INFO: + break; + default: + /* Return an error on unknown requests */ + error_report("vfio: unsupported ioctl %X", req); + return -1; + } + + return vfio_container_do_ioctl(as, groupid, req, param); +} diff --git a/hw/misc/zynq_slcr.c b/hw/misc/zynq_slcr.c index d1cc23303a..964f2532ff 100644 --- a/hw/misc/zynq_slcr.c +++ b/hw/misc/zynq_slcr.c @@ -19,102 +19,155 @@ #include "hw/sysbus.h" #include "sysemu/sysemu.h" -#ifdef ZYNQ_ARM_SLCR_ERR_DEBUG +#ifndef ZYNQ_SLCR_ERR_DEBUG +#define ZYNQ_SLCR_ERR_DEBUG 0 +#endif + #define DB_PRINT(...) do { \ - fprintf(stderr, ": %s: ", __func__); \ - fprintf(stderr, ## __VA_ARGS__); \ + if (ZYNQ_SLCR_ERR_DEBUG) { \ + fprintf(stderr, ": %s: ", __func__); \ + fprintf(stderr, ## __VA_ARGS__); \ + } \ } while (0); -#else - #define DB_PRINT(...) -#endif #define XILINX_LOCK_KEY 0x767b #define XILINX_UNLOCK_KEY 0xdf0d #define R_PSS_RST_CTRL_SOFT_RST 0x1 -typedef enum { - ARM_PLL_CTRL, - DDR_PLL_CTRL, - IO_PLL_CTRL, - PLL_STATUS, - ARM_PPL_CFG, - DDR_PLL_CFG, - IO_PLL_CFG, - PLL_BG_CTRL, - PLL_MAX -} PLLValues; - -typedef enum { - ARM_CLK_CTRL, - DDR_CLK_CTRL, - DCI_CLK_CTRL, - APER_CLK_CTRL, - USB0_CLK_CTRL, - USB1_CLK_CTRL, - GEM0_RCLK_CTRL, - GEM1_RCLK_CTRL, - GEM0_CLK_CTRL, - GEM1_CLK_CTRL, - SMC_CLK_CTRL, - LQSPI_CLK_CTRL, - SDIO_CLK_CTRL, - UART_CLK_CTRL, - SPI_CLK_CTRL, - CAN_CLK_CTRL, - CAN_MIOCLK_CTRL, - DBG_CLK_CTRL, - PCAP_CLK_CTRL, - TOPSW_CLK_CTRL, - CLK_MAX -} ClkValues; - -typedef enum { - CLK_CTRL, - THR_CTRL, - THR_CNT, - THR_STA, - FPGA_MAX -} FPGAValues; - -typedef enum { - SYNC_CTRL, - SYNC_STATUS, - BANDGAP_TRIP, - CC_TEST, - PLL_PREDIVISOR, - CLK_621_TRUE, - PICTURE_DBG, - PICTURE_DBG_UCNT, - PICTURE_DBG_LCNT, - MISC_MAX -} MiscValues; - -typedef enum { - PSS, - DDDR, - DMAC = 3, - USB, - GEM, - SDIO, - SPI, - CAN, - I2C, - UART, - GPIO, - LQSPI, - SMC, - OCM, - DEVCI, - FPGA, - A9_CPU, - RS_AWDT, - RST_REASON, - RST_REASON_CLR, - REBOOT_STATUS, - BOOT_MODE, - RESET_MAX -} ResetValues; +enum { + SCL = 0x000 / 4, + LOCK, + UNLOCK, + LOCKSTA, + + ARM_PLL_CTRL = 0x100 / 4, + DDR_PLL_CTRL, + IO_PLL_CTRL, + PLL_STATUS, + ARM_PLL_CFG, + DDR_PLL_CFG, + IO_PLL_CFG, + + ARM_CLK_CTRL = 0x120 / 4, + DDR_CLK_CTRL, + DCI_CLK_CTRL, + APER_CLK_CTRL, + USB0_CLK_CTRL, + USB1_CLK_CTRL, + GEM0_RCLK_CTRL, + GEM1_RCLK_CTRL, + GEM0_CLK_CTRL, + GEM1_CLK_CTRL, + SMC_CLK_CTRL, + LQSPI_CLK_CTRL, + SDIO_CLK_CTRL, + UART_CLK_CTRL, + SPI_CLK_CTRL, + CAN_CLK_CTRL, + CAN_MIOCLK_CTRL, + DBG_CLK_CTRL, + PCAP_CLK_CTRL, + TOPSW_CLK_CTRL, + +#define FPGA_CTRL_REGS(n, start) \ + FPGA ## n ## _CLK_CTRL = (start) / 4, \ + FPGA ## n ## _THR_CTRL, \ + FPGA ## n ## _THR_CNT, \ + FPGA ## n ## _THR_STA, + FPGA_CTRL_REGS(0, 0x170) + FPGA_CTRL_REGS(1, 0x180) + FPGA_CTRL_REGS(2, 0x190) + FPGA_CTRL_REGS(3, 0x1a0) + + BANDGAP_TRIP = 0x1b8 / 4, + PLL_PREDIVISOR = 0x1c0 / 4, + CLK_621_TRUE, + + PSS_RST_CTRL = 0x200 / 4, + DDR_RST_CTRL, + TOPSW_RESET_CTRL, + DMAC_RST_CTRL, + USB_RST_CTRL, + GEM_RST_CTRL, + SDIO_RST_CTRL, + SPI_RST_CTRL, + CAN_RST_CTRL, + I2C_RST_CTRL, + UART_RST_CTRL, + GPIO_RST_CTRL, + LQSPI_RST_CTRL, + SMC_RST_CTRL, + OCM_RST_CTRL, + FPGA_RST_CTRL = 0x240 / 4, + A9_CPU_RST_CTRL, + + RS_AWDT_CTRL = 0x24c / 4, + RST_REASON, + + REBOOT_STATUS = 0x258 / 4, + BOOT_MODE, + + APU_CTRL = 0x300 / 4, + WDT_CLK_SEL, + + TZ_DMA_NS = 0x440 / 4, + TZ_DMA_IRQ_NS, + TZ_DMA_PERIPH_NS, + + PSS_IDCODE = 0x530 / 4, + + DDR_URGENT = 0x600 / 4, + DDR_CAL_START = 0x60c / 4, + DDR_REF_START = 0x614 / 4, + DDR_CMD_STA, + DDR_URGENT_SEL, + DDR_DFI_STATUS, + + MIO = 0x700 / 4, +#define MIO_LENGTH 54 + + MIO_LOOPBACK = 0x804 / 4, + MIO_MST_TRI0, + MIO_MST_TRI1, + + SD0_WP_CD_SEL = 0x830 / 4, + SD1_WP_CD_SEL, + + LVL_SHFTR_EN = 0x900 / 4, + OCM_CFG = 0x910 / 4, + + CPU_RAM = 0xa00 / 4, + + IOU = 0xa30 / 4, + + DMAC_RAM = 0xa50 / 4, + + AFI0 = 0xa60 / 4, + AFI1 = AFI0 + 3, + AFI2 = AFI1 + 3, + AFI3 = AFI2 + 3, +#define AFI_LENGTH 3 + + OCM = 0xa90 / 4, + + DEVCI_RAM = 0xaa0 / 4, + + CSG_RAM = 0xab0 / 4, + + GPIOB_CTRL = 0xb00 / 4, + GPIOB_CFG_CMOS18, + GPIOB_CFG_CMOS25, + GPIOB_CFG_CMOS33, + GPIOB_CFG_HSTL = 0xb14 / 4, + GPIOB_DRVR_BIAS_CTRL, + + DDRIOB = 0xb40 / 4, +#define DDRIOB_LENGTH 14 +}; + +#define ZYNQ_SLCR_MMIO_SIZE 0x1000 +#define ZYNQ_SLCR_NUM_REGS (ZYNQ_SLCR_MMIO_SIZE / 4) #define TYPE_ZYNQ_SLCR "xilinx,zynq_slcr" #define ZYNQ_SLCR(obj) OBJECT_CHECK(ZynqSLCRState, (obj), TYPE_ZYNQ_SLCR) @@ -124,42 +177,7 @@ typedef struct ZynqSLCRState { MemoryRegion iomem; - union { - struct { - uint16_t scl; - uint16_t lockval; - uint32_t pll[PLL_MAX]; /* 0x100 - 0x11C */ - uint32_t clk[CLK_MAX]; /* 0x120 - 0x16C */ - uint32_t fpga[4][FPGA_MAX]; /* 0x170 - 0x1AC */ - uint32_t misc[MISC_MAX]; /* 0x1B0 - 0x1D8 */ - uint32_t reset[RESET_MAX]; /* 0x200 - 0x25C */ - uint32_t apu_ctrl; /* 0x300 */ - uint32_t wdt_clk_sel; /* 0x304 */ - uint32_t tz_ocm[3]; /* 0x400 - 0x408 */ - uint32_t tz_ddr; /* 0x430 */ - uint32_t tz_dma[3]; /* 0x440 - 0x448 */ - uint32_t tz_misc[3]; /* 0x450 - 0x458 */ - uint32_t tz_fpga[2]; /* 0x484 - 0x488 */ - uint32_t dbg_ctrl; /* 0x500 */ - uint32_t pss_idcode; /* 0x530 */ - uint32_t ddr[8]; /* 0x600 - 0x620 - 0x604-missing */ - uint32_t mio[54]; /* 0x700 - 0x7D4 */ - uint32_t mio_func[4]; /* 0x800 - 0x810 */ - uint32_t sd[2]; /* 0x830 - 0x834 */ - uint32_t lvl_shftr_en; /* 0x900 */ - uint32_t ocm_cfg; /* 0x910 */ - uint32_t cpu_ram[8]; /* 0xA00 - 0xA1C */ - uint32_t iou[7]; /* 0xA30 - 0xA48 */ - uint32_t dmac_ram; /* 0xA50 */ - uint32_t afi[4][3]; /* 0xA60 - 0xA8C */ - uint32_t ocm[3]; /* 0xA90 - 0xA98 */ - uint32_t devci_ram; /* 0xAA0 */ - uint32_t csg_ram; /* 0xAB0 */ - uint32_t gpiob[12]; /* 0xB00 - 0xB2C */ - uint32_t ddriob[14]; /* 0xB40 - 0xB74 */ - }; - uint8_t data[0x1000]; - }; + uint32_t regs[ZYNQ_SLCR_NUM_REGS]; } ZynqSLCRState; static void zynq_slcr_reset(DeviceState *d) @@ -169,177 +187,169 @@ static void zynq_slcr_reset(DeviceState *d) DB_PRINT("RESET\n"); - s->lockval = 1; + s->regs[LOCKSTA] = 1; /* 0x100 - 0x11C */ - s->pll[ARM_PLL_CTRL] = 0x0001A008; - s->pll[DDR_PLL_CTRL] = 0x0001A008; - s->pll[IO_PLL_CTRL] = 0x0001A008; - s->pll[PLL_STATUS] = 0x0000003F; - s->pll[ARM_PPL_CFG] = 0x00014000; - s->pll[DDR_PLL_CFG] = 0x00014000; - s->pll[IO_PLL_CFG] = 0x00014000; + s->regs[ARM_PLL_CTRL] = 0x0001A008; + s->regs[DDR_PLL_CTRL] = 0x0001A008; + s->regs[IO_PLL_CTRL] = 0x0001A008; + s->regs[PLL_STATUS] = 0x0000003F; + s->regs[ARM_PLL_CFG] = 0x00014000; + s->regs[DDR_PLL_CFG] = 0x00014000; + s->regs[IO_PLL_CFG] = 0x00014000; /* 0x120 - 0x16C */ - s->clk[ARM_CLK_CTRL] = 0x1F000400; - s->clk[DDR_CLK_CTRL] = 0x18400003; - s->clk[DCI_CLK_CTRL] = 0x01E03201; - s->clk[APER_CLK_CTRL] = 0x01FFCCCD; - s->clk[USB0_CLK_CTRL] = s->clk[USB1_CLK_CTRL] = 0x00101941; - s->clk[GEM0_RCLK_CTRL] = s->clk[GEM1_RCLK_CTRL] = 0x00000001; - s->clk[GEM0_CLK_CTRL] = s->clk[GEM1_CLK_CTRL] = 0x00003C01; - s->clk[SMC_CLK_CTRL] = 0x00003C01; - s->clk[LQSPI_CLK_CTRL] = 0x00002821; - s->clk[SDIO_CLK_CTRL] = 0x00001E03; - s->clk[UART_CLK_CTRL] = 0x00003F03; - s->clk[SPI_CLK_CTRL] = 0x00003F03; - s->clk[CAN_CLK_CTRL] = 0x00501903; - s->clk[DBG_CLK_CTRL] = 0x00000F03; - s->clk[PCAP_CLK_CTRL] = 0x00000F01; + s->regs[ARM_CLK_CTRL] = 0x1F000400; + s->regs[DDR_CLK_CTRL] = 0x18400003; + s->regs[DCI_CLK_CTRL] = 0x01E03201; + s->regs[APER_CLK_CTRL] = 0x01FFCCCD; + s->regs[USB0_CLK_CTRL] = s->regs[USB1_CLK_CTRL] = 0x00101941; + s->regs[GEM0_RCLK_CTRL] = s->regs[GEM1_RCLK_CTRL] = 0x00000001; + s->regs[GEM0_CLK_CTRL] = s->regs[GEM1_CLK_CTRL] = 0x00003C01; + s->regs[SMC_CLK_CTRL] = 0x00003C01; + s->regs[LQSPI_CLK_CTRL] = 0x00002821; + s->regs[SDIO_CLK_CTRL] = 0x00001E03; + s->regs[UART_CLK_CTRL] = 0x00003F03; + s->regs[SPI_CLK_CTRL] = 0x00003F03; + s->regs[CAN_CLK_CTRL] = 0x00501903; + s->regs[DBG_CLK_CTRL] = 0x00000F03; + s->regs[PCAP_CLK_CTRL] = 0x00000F01; /* 0x170 - 0x1AC */ - s->fpga[0][CLK_CTRL] = s->fpga[1][CLK_CTRL] = s->fpga[2][CLK_CTRL] = - s->fpga[3][CLK_CTRL] = 0x00101800; - s->fpga[0][THR_STA] = s->fpga[1][THR_STA] = s->fpga[2][THR_STA] = - s->fpga[3][THR_STA] = 0x00010000; + s->regs[FPGA0_CLK_CTRL] = s->regs[FPGA1_CLK_CTRL] = s->regs[FPGA2_CLK_CTRL] + = s->regs[FPGA3_CLK_CTRL] = 0x00101800; + s->regs[FPGA0_THR_STA] = s->regs[FPGA1_THR_STA] = s->regs[FPGA2_THR_STA] + = s->regs[FPGA3_THR_STA] = 0x00010000; /* 0x1B0 - 0x1D8 */ - s->misc[BANDGAP_TRIP] = 0x0000001F; - s->misc[PLL_PREDIVISOR] = 0x00000001; - s->misc[CLK_621_TRUE] = 0x00000001; + s->regs[BANDGAP_TRIP] = 0x0000001F; + s->regs[PLL_PREDIVISOR] = 0x00000001; + s->regs[CLK_621_TRUE] = 0x00000001; /* 0x200 - 0x25C */ - s->reset[FPGA] = 0x01F33F0F; - s->reset[RST_REASON] = 0x00000040; + s->regs[FPGA_RST_CTRL] = 0x01F33F0F; + s->regs[RST_REASON] = 0x00000040; + + s->regs[BOOT_MODE] = 0x00000001; /* 0x700 - 0x7D4 */ for (i = 0; i < 54; i++) { - s->mio[i] = 0x00001601; + s->regs[MIO + i] = 0x00001601; } for (i = 2; i <= 8; i++) { - s->mio[i] = 0x00000601; + s->regs[MIO + i] = 0x00000601; } - /* MIO_MST_TRI0, MIO_MST_TRI1 */ - s->mio_func[2] = s->mio_func[3] = 0xFFFFFFFF; + s->regs[MIO_MST_TRI0] = s->regs[MIO_MST_TRI1] = 0xFFFFFFFF; - s->cpu_ram[0] = s->cpu_ram[1] = s->cpu_ram[3] = - s->cpu_ram[4] = s->cpu_ram[7] = 0x00010101; - s->cpu_ram[2] = s->cpu_ram[5] = 0x01010101; - s->cpu_ram[6] = 0x00000001; + s->regs[CPU_RAM + 0] = s->regs[CPU_RAM + 1] = s->regs[CPU_RAM + 3] + = s->regs[CPU_RAM + 4] = s->regs[CPU_RAM + 7] + = 0x00010101; + s->regs[CPU_RAM + 2] = s->regs[CPU_RAM + 5] = 0x01010101; + s->regs[CPU_RAM + 6] = 0x00000001; - s->iou[0] = s->iou[1] = s->iou[2] = s->iou[3] = 0x09090909; - s->iou[4] = s->iou[5] = 0x00090909; - s->iou[6] = 0x00000909; + s->regs[IOU + 0] = s->regs[IOU + 1] = s->regs[IOU + 2] = s->regs[IOU + 3] + = 0x09090909; + s->regs[IOU + 4] = s->regs[IOU + 5] = 0x00090909; + s->regs[IOU + 6] = 0x00000909; - s->dmac_ram = 0x00000009; + s->regs[DMAC_RAM] = 0x00000009; - s->afi[0][0] = s->afi[0][1] = 0x09090909; - s->afi[1][0] = s->afi[1][1] = 0x09090909; - s->afi[2][0] = s->afi[2][1] = 0x09090909; - s->afi[3][0] = s->afi[3][1] = 0x09090909; - s->afi[0][2] = s->afi[1][2] = s->afi[2][2] = s->afi[3][2] = 0x00000909; + s->regs[AFI0 + 0] = s->regs[AFI0 + 1] = 0x09090909; + s->regs[AFI1 + 0] = s->regs[AFI1 + 1] = 0x09090909; + s->regs[AFI2 + 0] = s->regs[AFI2 + 1] = 0x09090909; + s->regs[AFI3 + 0] = s->regs[AFI3 + 1] = 0x09090909; + s->regs[AFI0 + 2] = s->regs[AFI1 + 2] = s->regs[AFI2 + 2] + = s->regs[AFI3 + 2] = 0x00000909; - s->ocm[0] = 0x01010101; - s->ocm[1] = s->ocm[2] = 0x09090909; + s->regs[OCM + 0] = 0x01010101; + s->regs[OCM + 1] = s->regs[OCM + 2] = 0x09090909; - s->devci_ram = 0x00000909; - s->csg_ram = 0x00000001; + s->regs[DEVCI_RAM] = 0x00000909; + s->regs[CSG_RAM] = 0x00000001; - s->ddriob[0] = s->ddriob[1] = s->ddriob[2] = s->ddriob[3] = 0x00000e00; - s->ddriob[4] = s->ddriob[5] = s->ddriob[6] = 0x00000e00; - s->ddriob[12] = 0x00000021; + s->regs[DDRIOB + 0] = s->regs[DDRIOB + 1] = s->regs[DDRIOB + 2] + = s->regs[DDRIOB + 3] = 0x00000e00; + s->regs[DDRIOB + 4] = s->regs[DDRIOB + 5] = s->regs[DDRIOB + 6] + = 0x00000e00; + s->regs[DDRIOB + 12] = 0x00000021; } -static inline uint32_t zynq_slcr_read_imp(void *opaque, - hwaddr offset) -{ - ZynqSLCRState *s = (ZynqSLCRState *)opaque; +static bool zynq_slcr_check_offset(hwaddr offset, bool rnw) +{ switch (offset) { - case 0x0: /* SCL */ - return s->scl; - case 0x4: /* LOCK */ - case 0x8: /* UNLOCK */ - DB_PRINT("Reading SCLR_LOCK/UNLOCK is not enabled\n"); - return 0; - case 0x0C: /* LOCKSTA */ - return s->lockval; - case 0x100 ... 0x11C: - return s->pll[(offset - 0x100) / 4]; - case 0x120 ... 0x16C: - return s->clk[(offset - 0x120) / 4]; - case 0x170 ... 0x1AC: - return s->fpga[0][(offset - 0x170) / 4]; - case 0x1B0 ... 0x1D8: - return s->misc[(offset - 0x1B0) / 4]; - case 0x200 ... 0x258: - return s->reset[(offset - 0x200) / 4]; - case 0x25c: - return 1; - case 0x300: - return s->apu_ctrl; - case 0x304: - return s->wdt_clk_sel; - case 0x400 ... 0x408: - return s->tz_ocm[(offset - 0x400) / 4]; - case 0x430: - return s->tz_ddr; - case 0x440 ... 0x448: - return s->tz_dma[(offset - 0x440) / 4]; - case 0x450 ... 0x458: - return s->tz_misc[(offset - 0x450) / 4]; - case 0x484 ... 0x488: - return s->tz_fpga[(offset - 0x484) / 4]; - case 0x500: - return s->dbg_ctrl; - case 0x530: - return s->pss_idcode; - case 0x600 ... 0x620: - if (offset == 0x604) { - goto bad_reg; - } - return s->ddr[(offset - 0x600) / 4]; - case 0x700 ... 0x7D4: - return s->mio[(offset - 0x700) / 4]; - case 0x800 ... 0x810: - return s->mio_func[(offset - 0x800) / 4]; - case 0x830 ... 0x834: - return s->sd[(offset - 0x830) / 4]; - case 0x900: - return s->lvl_shftr_en; - case 0x910: - return s->ocm_cfg; - case 0xA00 ... 0xA1C: - return s->cpu_ram[(offset - 0xA00) / 4]; - case 0xA30 ... 0xA48: - return s->iou[(offset - 0xA30) / 4]; - case 0xA50: - return s->dmac_ram; - case 0xA60 ... 0xA8C: - return s->afi[0][(offset - 0xA60) / 4]; - case 0xA90 ... 0xA98: - return s->ocm[(offset - 0xA90) / 4]; - case 0xAA0: - return s->devci_ram; - case 0xAB0: - return s->csg_ram; - case 0xB00 ... 0xB2C: - return s->gpiob[(offset - 0xB00) / 4]; - case 0xB40 ... 0xB74: - return s->ddriob[(offset - 0xB40) / 4]; + case LOCK: + case UNLOCK: + case DDR_CAL_START: + case DDR_REF_START: + return !rnw; /* Write only */ + case LOCKSTA: + case FPGA0_THR_STA: + case FPGA1_THR_STA: + case FPGA2_THR_STA: + case FPGA3_THR_STA: + case BOOT_MODE: + case PSS_IDCODE: + case DDR_CMD_STA: + case DDR_DFI_STATUS: + case PLL_STATUS: + return rnw;/* read only */ + case SCL: + case ARM_PLL_CTRL ... IO_PLL_CTRL: + case ARM_PLL_CFG ... IO_PLL_CFG: + case ARM_CLK_CTRL ... TOPSW_CLK_CTRL: + case FPGA0_CLK_CTRL ... FPGA0_THR_CNT: + case FPGA1_CLK_CTRL ... FPGA1_THR_CNT: + case FPGA2_CLK_CTRL ... FPGA2_THR_CNT: + case FPGA3_CLK_CTRL ... FPGA3_THR_CNT: + case BANDGAP_TRIP: + case PLL_PREDIVISOR: + case CLK_621_TRUE: + case PSS_RST_CTRL ... A9_CPU_RST_CTRL: + case RS_AWDT_CTRL: + case RST_REASON: + case REBOOT_STATUS: + case APU_CTRL: + case WDT_CLK_SEL: + case TZ_DMA_NS ... TZ_DMA_PERIPH_NS: + case DDR_URGENT: + case DDR_URGENT_SEL: + case MIO ... MIO + MIO_LENGTH - 1: + case MIO_LOOPBACK ... MIO_MST_TRI1: + case SD0_WP_CD_SEL: + case SD1_WP_CD_SEL: + case LVL_SHFTR_EN: + case OCM_CFG: + case CPU_RAM: + case IOU: + case DMAC_RAM: + case AFI0 ... AFI3 + AFI_LENGTH - 1: + case OCM: + case DEVCI_RAM: + case CSG_RAM: + case GPIOB_CTRL ... GPIOB_CFG_CMOS33: + case GPIOB_CFG_HSTL: + case GPIOB_DRVR_BIAS_CTRL: + case DDRIOB ... DDRIOB + DDRIOB_LENGTH - 1: + return true; default: - bad_reg: - DB_PRINT("Bad register offset 0x%x\n", (int)offset); - return 0; + return false; } } static uint64_t zynq_slcr_read(void *opaque, hwaddr offset, unsigned size) { - uint32_t ret = zynq_slcr_read_imp(opaque, offset); + ZynqSLCRState *s = opaque; + offset /= 4; + uint32_t ret = s->regs[offset]; + + if (!zynq_slcr_check_offset(offset, true)) { + qemu_log_mask(LOG_GUEST_ERROR, "zynq_slcr: Invalid read access to " + " addr %" HWADDR_PRIx "\n", offset * 4); + } - DB_PRINT("addr: %08x data: %08x\n", (unsigned)offset, (unsigned)ret); + DB_PRINT("addr: %08" HWADDR_PRIx " data: %08" PRIx32 "\n", offset * 4, ret); return ret; } @@ -347,148 +357,55 @@ static void zynq_slcr_write(void *opaque, hwaddr offset, uint64_t val, unsigned size) { ZynqSLCRState *s = (ZynqSLCRState *)opaque; + offset /= 4; - DB_PRINT("offset: %08x data: %08x\n", (unsigned)offset, (unsigned)val); + DB_PRINT("addr: %08" HWADDR_PRIx " data: %08" PRIx64 "\n", offset * 4, val); + + if (!zynq_slcr_check_offset(offset, false)) { + qemu_log_mask(LOG_GUEST_ERROR, "zynq_slcr: Invalid write access to " + "addr %" HWADDR_PRIx "\n", offset * 4); + return; + } switch (offset) { - case 0x00: /* SCL */ - s->scl = val & 0x1; - return; - case 0x4: /* SLCR_LOCK */ + case SCL: + s->regs[SCL] = val & 0x1; + return; + case LOCK: if ((val & 0xFFFF) == XILINX_LOCK_KEY) { DB_PRINT("XILINX LOCK 0xF8000000 + 0x%x <= 0x%x\n", (int)offset, (unsigned)val & 0xFFFF); - s->lockval = 1; + s->regs[LOCKSTA] = 1; } else { DB_PRINT("WRONG XILINX LOCK KEY 0xF8000000 + 0x%x <= 0x%x\n", (int)offset, (unsigned)val & 0xFFFF); } return; - case 0x8: /* SLCR_UNLOCK */ + case UNLOCK: if ((val & 0xFFFF) == XILINX_UNLOCK_KEY) { DB_PRINT("XILINX UNLOCK 0xF8000000 + 0x%x <= 0x%x\n", (int)offset, (unsigned)val & 0xFFFF); - s->lockval = 0; + s->regs[LOCKSTA] = 0; } else { DB_PRINT("WRONG XILINX UNLOCK KEY 0xF8000000 + 0x%x <= 0x%x\n", (int)offset, (unsigned)val & 0xFFFF); } return; - case 0xc: /* LOCKSTA */ - DB_PRINT("Writing SCLR_LOCKSTA is not enabled\n"); - return; } - if (!s->lockval) { - switch (offset) { - case 0x100 ... 0x11C: - if (offset == 0x10C) { - goto bad_reg; - } - s->pll[(offset - 0x100) / 4] = val; - break; - case 0x120 ... 0x16C: - s->clk[(offset - 0x120) / 4] = val; - break; - case 0x170 ... 0x1AC: - s->fpga[0][(offset - 0x170) / 4] = val; - break; - case 0x1B0 ... 0x1D8: - s->misc[(offset - 0x1B0) / 4] = val; - break; - case 0x200 ... 0x25C: - if (offset == 0x250) { - goto bad_reg; - } - s->reset[(offset - 0x200) / 4] = val; - if (offset == 0x200 && (val & R_PSS_RST_CTRL_SOFT_RST)) { - qemu_system_reset_request(); - } - break; - case 0x300: - s->apu_ctrl = val; - break; - case 0x304: - s->wdt_clk_sel = val; - break; - case 0x400 ... 0x408: - s->tz_ocm[(offset - 0x400) / 4] = val; - break; - case 0x430: - s->tz_ddr = val; - break; - case 0x440 ... 0x448: - s->tz_dma[(offset - 0x440) / 4] = val; - break; - case 0x450 ... 0x458: - s->tz_misc[(offset - 0x450) / 4] = val; - break; - case 0x484 ... 0x488: - s->tz_fpga[(offset - 0x484) / 4] = val; - break; - case 0x500: - s->dbg_ctrl = val; - break; - case 0x530: - s->pss_idcode = val; - break; - case 0x600 ... 0x620: - if (offset == 0x604) { - goto bad_reg; - } - s->ddr[(offset - 0x600) / 4] = val; - break; - case 0x700 ... 0x7D4: - s->mio[(offset - 0x700) / 4] = val; - break; - case 0x800 ... 0x810: - s->mio_func[(offset - 0x800) / 4] = val; - break; - case 0x830 ... 0x834: - s->sd[(offset - 0x830) / 4] = val; - break; - case 0x900: - s->lvl_shftr_en = val; - break; - case 0x910: - break; - case 0xA00 ... 0xA1C: - s->cpu_ram[(offset - 0xA00) / 4] = val; - break; - case 0xA30 ... 0xA48: - s->iou[(offset - 0xA30) / 4] = val; - break; - case 0xA50: - s->dmac_ram = val; - break; - case 0xA60 ... 0xA8C: - s->afi[0][(offset - 0xA60) / 4] = val; - break; - case 0xA90: - s->ocm[0] = val; - break; - case 0xAA0: - s->devci_ram = val; - break; - case 0xAB0: - s->csg_ram = val; - break; - case 0xB00 ... 0xB2C: - if (offset == 0xB20 || offset == 0xB2C) { - goto bad_reg; - } - s->gpiob[(offset - 0xB00) / 4] = val; - break; - case 0xB40 ... 0xB74: - s->ddriob[(offset - 0xB40) / 4] = val; - break; - default: - bad_reg: - DB_PRINT("Bad register write %x <= %08x\n", (int)offset, - (unsigned)val); - } + if (!s->regs[LOCKSTA]) { + s->regs[offset / 4] = val; } else { DB_PRINT("SCLR registers are locked. Unlock them first\n"); + return; + } + + switch (offset) { + case PSS_RST_CTRL: + if (val & R_PSS_RST_CTRL_SOFT_RST) { + qemu_system_reset_request(); + } + break; } } @@ -498,23 +415,21 @@ static const MemoryRegionOps slcr_ops = { .endianness = DEVICE_NATIVE_ENDIAN, }; -static int zynq_slcr_init(SysBusDevice *dev) +static void zynq_slcr_init(Object *obj) { - ZynqSLCRState *s = ZYNQ_SLCR(dev); - - memory_region_init_io(&s->iomem, OBJECT(s), &slcr_ops, s, "slcr", 0x1000); - sysbus_init_mmio(dev, &s->iomem); + ZynqSLCRState *s = ZYNQ_SLCR(obj); - return 0; + memory_region_init_io(&s->iomem, obj, &slcr_ops, s, "slcr", + ZYNQ_SLCR_MMIO_SIZE); + sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->iomem); } static const VMStateDescription vmstate_zynq_slcr = { .name = "zynq_slcr", - .version_id = 1, - .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { - VMSTATE_UINT8_ARRAY(data, ZynqSLCRState, 0x1000), + .version_id = 2, + .minimum_version_id = 2, + .fields = (VMStateField[]) { + VMSTATE_UINT32_ARRAY(regs, ZynqSLCRState, ZYNQ_SLCR_NUM_REGS), VMSTATE_END_OF_LIST() } }; @@ -522,9 +437,7 @@ static const VMStateDescription vmstate_zynq_slcr = { static void zynq_slcr_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass); - sdc->init = zynq_slcr_init; dc->vmsd = &vmstate_zynq_slcr; dc->reset = zynq_slcr_reset; } @@ -534,6 +447,7 @@ static const TypeInfo zynq_slcr_info = { .name = TYPE_ZYNQ_SLCR, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(ZynqSLCRState), + .instance_init = zynq_slcr_init, }; static void zynq_slcr_register_types(void) diff --git a/hw/moxie/moxiesim.c b/hw/moxie/moxiesim.c index a87ca6ddcc..80bcc5b4f6 100644 --- a/hw/moxie/moxiesim.c +++ b/hw/moxie/moxiesim.c @@ -94,27 +94,14 @@ static void main_cpu_reset(void *opaque) cpu_reset(CPU(cpu)); } -static inline DeviceState * -moxie_intc_create(hwaddr base, qemu_irq irq, int kind_of_intr) -{ - DeviceState *dev; - - dev = qdev_create(NULL, "moxie,intc"); - qdev_prop_set_uint32(dev, "kind-of-intr", kind_of_intr); - qdev_init_nofail(dev); - sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base); - sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq); - return dev; -} - -static void moxiesim_init(QEMUMachineInitArgs *args) +static void moxiesim_init(MachineState *machine) { MoxieCPU *cpu = NULL; - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; CPUMoxieState *env; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); @@ -136,11 +123,11 @@ static void moxiesim_init(QEMUMachineInitArgs *args) qemu_register_reset(main_cpu_reset, cpu); /* Allocate RAM. */ - memory_region_init_ram(ram, NULL, "moxiesim.ram", ram_size); + memory_region_init_ram(ram, NULL, "moxiesim.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, ram_base, ram); - memory_region_init_ram(rom, NULL, "moxie.rom", 128*0x1000); + memory_region_init_ram(rom, NULL, "moxie.rom", 128*0x1000, &error_abort); vmstate_register_ram_global(rom); memory_region_add_subregion(get_system_memory(), 0x1000, rom); diff --git a/hw/net/allwinner_emac.c b/hw/net/allwinner_emac.c index 469f2f0ede..d780ba0fcb 100644 --- a/hw/net/allwinner_emac.c +++ b/hw/net/allwinner_emac.c @@ -27,11 +27,11 @@ static uint8_t padding[60]; static void mii_set_link(RTL8201CPState *mii, bool link_ok) { if (link_ok) { - mii->bmsr |= MII_BMSR_LINK_ST; + mii->bmsr |= MII_BMSR_LINK_ST | MII_BMSR_AN_COMP; mii->anlpar |= MII_ANAR_TXFD | MII_ANAR_10FD | MII_ANAR_10 | MII_ANAR_CSMACD; } else { - mii->bmsr &= ~MII_BMSR_LINK_ST; + mii->bmsr &= ~(MII_BMSR_LINK_ST | MII_BMSR_AN_COMP); mii->anlpar = MII_ANAR_TX; } } @@ -391,9 +391,11 @@ static void aw_emac_write(void *opaque, hwaddr offset, uint64_t value, break; case EMAC_INT_CTL_REG: s->int_ctl = value; + aw_emac_update_irq(s); break; case EMAC_INT_STA_REG: s->int_sta &= ~value; + aw_emac_update_irq(s); break; case EMAC_MAC_MADR_REG: s->phy_target = value; diff --git a/hw/net/cadence_gem.c b/hw/net/cadence_gem.c index 92dc2f21fa..de26609c9d 100644 --- a/hw/net/cadence_gem.c +++ b/hw/net/cadence_gem.c @@ -1,5 +1,5 @@ /* - * QEMU Xilinx GEM emulation + * QEMU Cadence GEM emulation * * Copyright (c) 2011 Xilinx, Inc. * @@ -50,7 +50,7 @@ #define GEM_IER (0x00000028/4) /* Interrupt Enable reg */ #define GEM_IDR (0x0000002C/4) /* Interrupt Disable reg */ #define GEM_IMR (0x00000030/4) /* Interrupt Mask reg */ -#define GEM_PHYMNTNC (0x00000034/4) /* Phy Maintaince reg */ +#define GEM_PHYMNTNC (0x00000034/4) /* Phy Maintenance reg */ #define GEM_RXPAUSE (0x00000038/4) /* RX Pause Time reg */ #define GEM_TXPAUSE (0x0000003C/4) /* TX Pause Time reg */ #define GEM_TXPARTIALSF (0x00000040/4) /* TX Partial Store and Forward */ @@ -150,7 +150,7 @@ #define GEM_NWCTRL_LOCALLOOP 0x00000002 /* Local Loopback */ #define GEM_NWCFG_STRIP_FCS 0x00020000 /* Strip FCS field */ -#define GEM_NWCFG_LERR_DISC 0x00010000 /* Discard RX frames with lenth err */ +#define GEM_NWCFG_LERR_DISC 0x00010000 /* Discard RX frames with len err */ #define GEM_NWCFG_BUFF_OFST_M 0x0000C000 /* Receive buffer offset mask */ #define GEM_NWCFG_BUFF_OFST_S 14 /* Receive buffer offset shift */ #define GEM_NWCFG_UCAST_HASH 0x00000080 /* accept unicast if hash match */ @@ -388,7 +388,7 @@ typedef struct GemState { } GemState; /* The broadcast MAC address: 0xFFFFFFFFFFFF */ -const uint8_t broadcast_addr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; +static const uint8_t broadcast_addr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; /* * gem_init_register_masks: @@ -397,7 +397,7 @@ const uint8_t broadcast_addr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; */ static void gem_init_register_masks(GemState *s) { - /* Mask of register bits which are read only*/ + /* Mask of register bits which are read only */ memset(&s->regs_ro[0], 0, sizeof(s->regs_ro)); s->regs_ro[GEM_NWCTRL] = 0xFFF80000; s->regs_ro[GEM_NWSTATUS] = 0xFFFFFFFF; @@ -717,22 +717,16 @@ static ssize_t gem_receive(NetClientState *nc, const uint8_t *buf, size_t size) rxbuf_ptr = (void *)buf; } else { unsigned crc_val; - int crc_offset; /* The application wants the FCS field, which QEMU does not provide. - * We must try and caclculate one. + * We must try and calculate one. */ memcpy(rxbuf, buf, size); memset(rxbuf + size, 0, sizeof(rxbuf) - size); rxbuf_ptr = rxbuf; crc_val = cpu_to_le32(crc32(0, rxbuf, MAX(size, 60))); - if (size < 60) { - crc_offset = 60; - } else { - crc_offset = size; - } - memcpy(rxbuf + crc_offset, &crc_val, sizeof(crc_val)); + memcpy(rxbuf + size, &crc_val, sizeof(crc_val)); bytes_to_copy += 4; size += 4; @@ -877,7 +871,7 @@ static void gem_transmit(GemState *s) DB_PRINT("\n"); - /* The packet we will hand off to qemu. + /* The packet we will hand off to QEMU. * Packets scattered across multiple descriptors are gathered to this * one contiguous buffer first. */ @@ -886,8 +880,10 @@ static void gem_transmit(GemState *s) /* read current descriptor */ packet_desc_addr = s->tx_desc_addr; + + DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr); cpu_physical_memory_read(packet_desc_addr, - (uint8_t *)&desc[0], sizeof(desc)); + (uint8_t *)desc, sizeof(desc)); /* Handle all descriptors owned by hardware */ while (tx_desc_get_used(desc) == 0) { @@ -917,15 +913,17 @@ static void gem_transmit(GemState *s) /* Last descriptor for this packet; hand the whole thing off */ if (tx_desc_get_last(desc)) { + unsigned desc_first[2]; + /* Modify the 1st descriptor of this packet to be owned by * the processor. */ - cpu_physical_memory_read(s->tx_desc_addr, - (uint8_t *)&desc[0], sizeof(desc)); - tx_desc_set_used(desc); - cpu_physical_memory_write(s->tx_desc_addr, - (uint8_t *)&desc[0], sizeof(desc)); - /* Advance the hardare current descriptor past this packet */ + cpu_physical_memory_read(s->tx_desc_addr, (uint8_t *)desc_first, + sizeof(desc_first)); + tx_desc_set_used(desc_first); + cpu_physical_memory_write(s->tx_desc_addr, (uint8_t *)desc_first, + sizeof(desc_first)); + /* Advance the hardware current descriptor past this packet */ if (tx_desc_get_wrap(desc)) { s->tx_desc_addr = s->regs[GEM_TXQBASE]; } else { @@ -966,8 +964,9 @@ static void gem_transmit(GemState *s) } else { packet_desc_addr += 8; } + DB_PRINT("read descriptor 0x%" HWADDR_PRIx "\n", packet_desc_addr); cpu_physical_memory_read(packet_desc_addr, - (uint8_t *)&desc[0], sizeof(desc)); + (uint8_t *)desc, sizeof(desc)); } if (tx_desc_get_used(desc)) { @@ -1093,7 +1092,7 @@ static uint64_t gem_read(void *opaque, hwaddr offset, unsigned size) uint32_t phy_addr, reg_num; phy_addr = (retval & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT; - if (phy_addr == BOARD_PHY_ADDRESS) { + if (phy_addr == BOARD_PHY_ADDRESS || phy_addr == 0) { reg_num = (retval & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT; retval &= 0xFFFF0000; retval |= gem_phy_read(s, reg_num); @@ -1193,7 +1192,7 @@ static void gem_write(void *opaque, hwaddr offset, uint64_t val, uint32_t phy_addr, reg_num; phy_addr = (val & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT; - if (phy_addr == BOARD_PHY_ADDRESS) { + if (phy_addr == BOARD_PHY_ADDRESS || phy_addr == 0) { reg_num = (val & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT; gem_phy_write(s, reg_num, val); } @@ -1257,8 +1256,7 @@ static const VMStateDescription vmstate_cadence_gem = { .name = "cadence_gem", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, GemState, GEM_MAXREG), VMSTATE_UINT16_ARRAY(phy_regs, GemState, 32), VMSTATE_UINT8(phy_loop, GemState), diff --git a/hw/net/dp8393x.c b/hw/net/dp8393x.c index 789d385743..7eab7ad0cc 100644 --- a/hw/net/dp8393x.c +++ b/hw/net/dp8393x.c @@ -863,9 +863,6 @@ static void nic_cleanup(NetClientState *nc) { dp8393xState *s = qemu_get_nic_opaque(nc); - memory_region_del_subregion(s->address_space, &s->mmio); - memory_region_destroy(&s->mmio); - timer_del(s->watchdog); timer_free(s->watchdog); diff --git a/hw/net/e1000.c b/hw/net/e1000.c index 8387443ee3..e33a4da9fa 100644 --- a/hw/net/e1000.c +++ b/hw/net/e1000.c @@ -69,23 +69,11 @@ static int debugflags = DBGBIT(TXERR) | DBGBIT(GENERAL); /* * HW models: - * E1000_DEV_ID_82540EM works with Windows and Linux - * E1000_DEV_ID_82573L OK with windoze and Linux 2.6.22, - * appears to perform better than 82540EM, but breaks with Linux 2.6.18 + * E1000_DEV_ID_82540EM works with Windows, Linux, and OS X <= 10.8 * E1000_DEV_ID_82544GC_COPPER appears to work; not well tested + * E1000_DEV_ID_82545EM_COPPER works with Linux and OS X >= 10.6 * Others never tested */ -enum { E1000_DEVID = E1000_DEV_ID_82540EM }; - -/* - * May need to specify additional MAC-to-PHY entries -- - * Intel's Windows driver refuses to initialize unless they match - */ -enum { - PHY_ID2_INIT = E1000_DEVID == E1000_DEV_ID_82573L ? 0xcc2 : - E1000_DEVID == E1000_DEV_ID_82544GC_COPPER ? 0xc30 : - /* default to E1000_DEV_ID_82540EM */ 0xc20 -}; typedef struct E1000State_st { /*< private >*/ @@ -151,10 +139,20 @@ typedef struct E1000State_st { uint32_t compat_flags; } E1000State; -#define TYPE_E1000 "e1000" +typedef struct E1000BaseClass { + PCIDeviceClass parent_class; + uint16_t phy_id2; +} E1000BaseClass; + +#define TYPE_E1000_BASE "e1000-base" #define E1000(obj) \ - OBJECT_CHECK(E1000State, (obj), TYPE_E1000) + OBJECT_CHECK(E1000State, (obj), TYPE_E1000_BASE) + +#define E1000_DEVICE_CLASS(klass) \ + OBJECT_CLASS_CHECK(E1000BaseClass, (klass), TYPE_E1000_BASE) +#define E1000_DEVICE_GET_CLASS(obj) \ + OBJECT_GET_CLASS(E1000BaseClass, (obj), TYPE_E1000_BASE) #define defreg(x) x = (E1000_##x>>2) enum { @@ -177,6 +175,8 @@ e1000_link_down(E1000State *s) { s->mac_reg[STATUS] &= ~E1000_STATUS_LU; s->phy_reg[PHY_STATUS] &= ~MII_SR_LINK_STATUS; + s->phy_reg[PHY_STATUS] &= ~MII_SR_AUTONEG_COMPLETE; + s->phy_reg[PHY_LP_ABILITY] &= ~MII_LPAR_LPACK; } static void @@ -186,34 +186,32 @@ e1000_link_up(E1000State *s) s->phy_reg[PHY_STATUS] |= MII_SR_LINK_STATUS; } +static bool +have_autoneg(E1000State *s) +{ + return (s->compat_flags & E1000_FLAG_AUTONEG) && + (s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN); +} + static void set_phy_ctrl(E1000State *s, int index, uint16_t val) { + /* bits 0-5 reserved; MII_CR_[RESTART_AUTO_NEG,RESET] are self clearing */ + s->phy_reg[PHY_CTRL] = val & ~(0x3f | + MII_CR_RESET | + MII_CR_RESTART_AUTO_NEG); + /* * QEMU 1.3 does not support link auto-negotiation emulation, so if we * migrate during auto negotiation, after migration the link will be * down. */ - if (!(s->compat_flags & E1000_FLAG_AUTONEG)) { - return; - } - if ((val & MII_CR_AUTO_NEG_EN) && (val & MII_CR_RESTART_AUTO_NEG)) { + if (have_autoneg(s) && (val & MII_CR_RESTART_AUTO_NEG)) { e1000_link_down(s); - s->phy_reg[PHY_STATUS] &= ~MII_SR_AUTONEG_COMPLETE; DBGOUT(PHY, "Start link auto negotiation\n"); - timer_mod(s->autoneg_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); - } -} - -static void -e1000_autoneg_timer(void *opaque) -{ - E1000State *s = opaque; - if (!qemu_get_queue(s->nic)->link_down) { - e1000_link_up(s); + timer_mod(s->autoneg_timer, + qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); } - s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; - DBGOUT(PHY, "Auto negotiation is completed\n"); } static void (*phyreg_writeops[])(E1000State *, int, uint16_t) = { @@ -229,17 +227,36 @@ static const char phy_regcap[0x20] = { [PHY_CTRL] = PHY_RW, [PHY_1000T_CTRL] = PHY_RW, [PHY_LP_ABILITY] = PHY_R, [PHY_1000T_STATUS] = PHY_R, [PHY_AUTONEG_ADV] = PHY_RW, [M88E1000_RX_ERR_CNTR] = PHY_R, - [PHY_ID2] = PHY_R, [M88E1000_PHY_SPEC_STATUS] = PHY_R + [PHY_ID2] = PHY_R, [M88E1000_PHY_SPEC_STATUS] = PHY_R, + [PHY_AUTONEG_EXP] = PHY_R, }; +/* PHY_ID2 documented in 8254x_GBe_SDM.pdf, pp. 250 */ static const uint16_t phy_reg_init[] = { - [PHY_CTRL] = 0x1140, - [PHY_STATUS] = 0x794d, /* link initially up with not completed autoneg */ - [PHY_ID1] = 0x141, [PHY_ID2] = PHY_ID2_INIT, - [PHY_1000T_CTRL] = 0x0e00, [M88E1000_PHY_SPEC_CTRL] = 0x360, - [M88E1000_EXT_PHY_SPEC_CTRL] = 0x0d60, [PHY_AUTONEG_ADV] = 0xde1, - [PHY_LP_ABILITY] = 0x1e0, [PHY_1000T_STATUS] = 0x3c00, + [PHY_CTRL] = MII_CR_SPEED_SELECT_MSB | + MII_CR_FULL_DUPLEX | + MII_CR_AUTO_NEG_EN, + + [PHY_STATUS] = MII_SR_EXTENDED_CAPS | + MII_SR_LINK_STATUS | /* link initially up */ + MII_SR_AUTONEG_CAPS | + /* MII_SR_AUTONEG_COMPLETE: initially NOT completed */ + MII_SR_PREAMBLE_SUPPRESS | + MII_SR_EXTENDED_STATUS | + MII_SR_10T_HD_CAPS | + MII_SR_10T_FD_CAPS | + MII_SR_100X_HD_CAPS | + MII_SR_100X_FD_CAPS, + + [PHY_ID1] = 0x141, + /* [PHY_ID2] configured per DevId, from e1000_reset() */ + [PHY_AUTONEG_ADV] = 0xde1, + [PHY_LP_ABILITY] = 0x1e0, + [PHY_1000T_CTRL] = 0x0e00, + [PHY_1000T_STATUS] = 0x3c00, + [M88E1000_PHY_SPEC_CTRL] = 0x360, [M88E1000_PHY_SPEC_STATUS] = 0xac00, + [M88E1000_EXT_PHY_SPEC_CTRL] = 0x0d60, }; static const uint32_t mac_reg_init[] = { @@ -272,10 +289,6 @@ set_interrupt_cause(E1000State *s, int index, uint32_t val) uint32_t pending_ints; uint32_t mit_delay; - if (val && (E1000_DEVID >= E1000_DEV_ID_82547EI_MOBILE)) { - /* Only for 8257x */ - val |= E1000_ICR_INT_ASSERTED; - } s->mac_reg[ICR] = val; /* @@ -349,6 +362,19 @@ set_ics(E1000State *s, int index, uint32_t val) set_interrupt_cause(s, 0, val | s->mac_reg[ICR]); } +static void +e1000_autoneg_timer(void *opaque) +{ + E1000State *s = opaque; + if (!qemu_get_queue(s->nic)->link_down) { + e1000_link_up(s); + s->phy_reg[PHY_LP_ABILITY] |= MII_LPAR_LPACK; + s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; + DBGOUT(PHY, "Auto negotiation is completed\n"); + set_ics(s, 0, E1000_ICS_LSC); /* signal link status change to guest */ + } +} + static int rxbufsize(uint32_t v) { @@ -375,6 +401,7 @@ rxbufsize(uint32_t v) static void e1000_reset(void *opaque) { E1000State *d = opaque; + E1000BaseClass *edc = E1000_DEVICE_GET_CLASS(d); uint8_t *macaddr = d->conf.macaddr.a; int i; @@ -385,6 +412,7 @@ static void e1000_reset(void *opaque) d->mit_ide = 0; memset(d->phy_reg, 0, sizeof d->phy_reg); memmove(d->phy_reg, phy_reg_init, sizeof phy_reg_init); + d->phy_reg[PHY_ID2] = edc->phy_id2; memset(d->mac_reg, 0, sizeof d->mac_reg); memmove(d->mac_reg, mac_reg_init, sizeof mac_reg_init); d->rxbuf_min_shift = 1; @@ -445,8 +473,9 @@ set_mdic(E1000State *s, int index, uint32_t val) } else { if (addr < NPHYWRITEOPS && phyreg_writeops[addr]) { phyreg_writeops[addr](s, index, data); + } else { + s->phy_reg[addr] = data; } - s->phy_reg[addr] = data; } } s->mac_reg[MDIC] = val | E1000_MDIC_READY; @@ -856,7 +885,14 @@ e1000_set_link_status(NetClientState *nc) if (nc->link_down) { e1000_link_down(s); } else { - e1000_link_up(s); + if (have_autoneg(s) && + !(s->phy_reg[PHY_STATUS] & MII_SR_AUTONEG_COMPLETE)) { + /* emulate auto-negotiation if supported */ + timer_mod(s->autoneg_timer, + qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); + } else { + e1000_link_up(s); + } } if (s->mac_reg[STATUS] != old_status) @@ -1282,19 +1318,13 @@ static void e1000_pre_save(void *opaque) e1000_mit_timer(s); } - if (!(s->compat_flags & E1000_FLAG_AUTONEG)) { - return; - } - /* - * If link is down and auto-negotiation is ongoing, complete - * auto-negotiation immediately. This allows is to look at - * MII_SR_AUTONEG_COMPLETE to infer link status on load. + * If link is down and auto-negotiation is supported and ongoing, + * complete auto-negotiation immediately. This allows us to look + * at MII_SR_AUTONEG_COMPLETE to infer link status on load. */ - if (nc->link_down && - s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN && - s->phy_reg[PHY_CTRL] & MII_CR_RESTART_AUTO_NEG) { - s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; + if (nc->link_down && have_autoneg(s)) { + s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE; } } @@ -1316,15 +1346,11 @@ static int e1000_post_load(void *opaque, int version_id) * Alternatively, restart link negotiation if it was in progress. */ nc->link_down = (s->mac_reg[STATUS] & E1000_STATUS_LU) == 0; - if (!(s->compat_flags & E1000_FLAG_AUTONEG)) { - return 0; - } - - if (s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN && - s->phy_reg[PHY_CTRL] & MII_CR_RESTART_AUTO_NEG && + if (have_autoneg(s) && !(s->phy_reg[PHY_STATUS] & MII_SR_AUTONEG_COMPLETE)) { nc->link_down = false; - timer_mod(s->autoneg_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); + timer_mod(s->autoneg_timer, + qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500); } return 0; @@ -1341,8 +1367,7 @@ static const VMStateDescription vmstate_e1000_mit_state = { .name = "e1000/mit_state", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(mac_reg[RDTR], E1000State), VMSTATE_UINT32(mac_reg[RADV], E1000State), VMSTATE_UINT32(mac_reg[TADV], E1000State), @@ -1356,10 +1381,9 @@ static const VMStateDescription vmstate_e1000 = { .name = "e1000", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = e1000_pre_save, .post_load = e1000_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, E1000State), VMSTATE_UNUSED_TEST(is_version_1, 4), /* was instance id */ VMSTATE_UNUSED(4), /* Was mmio_base. */ @@ -1440,9 +1464,13 @@ static const VMStateDescription vmstate_e1000 = { } }; +/* + * EEPROM contents documented in Tables 5-2 and 5-3, pp. 98-102. + * Note: A valid DevId will be inserted during pci_e1000_init(). + */ static const uint16_t e1000_eeprom_template[64] = { 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0x0000, 0x0000, 0x0000, - 0x3000, 0x1000, 0x6403, E1000_DEVID, 0x8086, E1000_DEVID, 0x8086, 0x3040, + 0x3000, 0x1000, 0x6403, 0 /*DevId*/, 0x8086, 0 /*DevId*/, 0x8086, 0x3040, 0x0008, 0x2000, 0x7e14, 0x0048, 0x1000, 0x00d8, 0x0000, 0x2700, 0x6cc9, 0x3150, 0x0722, 0x040b, 0x0984, 0x0000, 0xc000, 0x0706, 0x1008, 0x0000, 0x0f04, 0x7fff, 0x4d01, 0xffff, 0xffff, 0xffff, @@ -1488,8 +1516,6 @@ pci_e1000_uninit(PCIDevice *dev) timer_free(d->autoneg_timer); timer_del(d->mit_timer); timer_free(d->mit_timer); - memory_region_destroy(&d->mmio); - memory_region_destroy(&d->io); qemu_del_nic(d->nic); } @@ -1507,6 +1533,7 @@ static int pci_e1000_init(PCIDevice *pci_dev) { DeviceState *dev = DEVICE(pci_dev); E1000State *d = E1000(pci_dev); + PCIDeviceClass *pdc = PCI_DEVICE_GET_CLASS(pci_dev); uint8_t *pci_conf; uint16_t checksum = 0; int i; @@ -1531,6 +1558,7 @@ static int pci_e1000_init(PCIDevice *pci_dev) macaddr = d->conf.macaddr.a; for (i = 0; i < 3; i++) d->eeprom_data[i] = (macaddr[2*i+1]<<8) | macaddr[2*i]; + d->eeprom_data[11] = d->eeprom_data[13] = pdc->device_id; for (i = 0; i < EEPROM_CHECKSUM_REG; i++) checksum += d->eeprom_data[i]; checksum = (uint16_t) EEPROM_SUM - checksum; @@ -1541,8 +1569,6 @@ static int pci_e1000_init(PCIDevice *pci_dev) qemu_format_nic_info_str(qemu_get_queue(d->nic), macaddr); - add_boot_device_path(d->conf.bootindex, dev, "/ethernet-phy@0"); - d->autoneg_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, e1000_autoneg_timer, d); d->mit_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, e1000_mit_timer, d); @@ -1564,17 +1590,27 @@ static Property e1000_properties[] = { DEFINE_PROP_END_OF_LIST(), }; +typedef struct E1000Info { + const char *name; + uint16_t device_id; + uint8_t revision; + uint16_t phy_id2; +} E1000Info; + static void e1000_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + E1000BaseClass *e = E1000_DEVICE_CLASS(klass); + const E1000Info *info = data; k->init = pci_e1000_init; k->exit = pci_e1000_uninit; k->romfile = "efi-e1000.rom"; k->vendor_id = PCI_VENDOR_ID_INTEL; - k->device_id = E1000_DEVID; - k->revision = 0x03; + k->device_id = info->device_id; + k->revision = info->revision; + e->phy_id2 = info->phy_id2; k->class_id = PCI_CLASS_NETWORK_ETHERNET; set_bit(DEVICE_CATEGORY_NETWORK, dc->categories); dc->desc = "Intel Gigabit Ethernet"; @@ -1583,16 +1619,67 @@ static void e1000_class_init(ObjectClass *klass, void *data) dc->props = e1000_properties; } -static const TypeInfo e1000_info = { - .name = TYPE_E1000, +static void e1000_instance_init(Object *obj) +{ + E1000State *n = E1000(obj); + device_add_bootindex_property(obj, &n->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(n), NULL); +} + +static const TypeInfo e1000_base_info = { + .name = TYPE_E1000_BASE, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(E1000State), - .class_init = e1000_class_init, + .instance_init = e1000_instance_init, + .class_size = sizeof(E1000BaseClass), + .abstract = true, +}; + +static const E1000Info e1000_devices[] = { + { + .name = "e1000-82540em", + .device_id = E1000_DEV_ID_82540EM, + .revision = 0x03, + .phy_id2 = E1000_PHY_ID2_8254xx_DEFAULT, + }, + { + .name = "e1000-82544gc", + .device_id = E1000_DEV_ID_82544GC_COPPER, + .revision = 0x03, + .phy_id2 = E1000_PHY_ID2_82544x, + }, + { + .name = "e1000-82545em", + .device_id = E1000_DEV_ID_82545EM_COPPER, + .revision = 0x03, + .phy_id2 = E1000_PHY_ID2_8254xx_DEFAULT, + }, +}; + +static const TypeInfo e1000_default_info = { + .name = "e1000", + .parent = "e1000-82540em", }; static void e1000_register_types(void) { - type_register_static(&e1000_info); + int i; + + type_register_static(&e1000_base_info); + for (i = 0; i < ARRAY_SIZE(e1000_devices); i++) { + const E1000Info *info = &e1000_devices[i]; + TypeInfo type_info = {}; + + type_info.name = info->name; + type_info.parent = TYPE_E1000_BASE; + type_info.class_data = (void *)info; + type_info.class_init = e1000_class_init; + type_info.instance_init = e1000_instance_init; + + type_register(&type_info); + } + type_register_static(&e1000_default_info); } type_init(e1000_register_types) diff --git a/hw/net/e1000_regs.h b/hw/net/e1000_regs.h index c9cb79e64d..60b96aaf13 100644 --- a/hw/net/e1000_regs.h +++ b/hw/net/e1000_regs.h @@ -99,6 +99,12 @@ #define E1000_DEV_ID_ICH8_IFE_G 0x10C5 #define E1000_DEV_ID_ICH8_IGP_M 0x104D +/* Device Specific Register Defaults */ +#define E1000_PHY_ID2_82541x 0x380 +#define E1000_PHY_ID2_82544x 0xC30 +#define E1000_PHY_ID2_8254xx_DEFAULT 0xC20 /* 82540x, 82545x, and 82546x */ +#define E1000_PHY_ID2_82573x 0xCC0 + /* Register Set. (82543, 82544) * * Registers are defined to be 32 bits and should be accessed as 32 bit values. @@ -378,6 +384,9 @@ #define MII_SR_100X_FD_CAPS 0x4000 /* 100X Full Duplex Capable */ #define MII_SR_100T4_CAPS 0x8000 /* 100T4 Capable */ +/* PHY Link Partner Ability Register */ +#define MII_LPAR_LPACK 0x4000 /* Acked by link partner */ + /* Interrupt Cause Read */ #define E1000_ICR_TXDW 0x00000001 /* Transmit desc written back */ #define E1000_ICR_TXQE 0x00000002 /* Transmit Queue empty */ diff --git a/hw/net/eepro100.c b/hw/net/eepro100.c index 9c70cce2a8..4877bfd4d3 100644 --- a/hw/net/eepro100.c +++ b/hw/net/eepro100.c @@ -1784,8 +1784,7 @@ static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size) static const VMStateDescription vmstate_eepro100 = { .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, EEPRO100State), VMSTATE_UNUSED(32), VMSTATE_BUFFER(mult, EEPRO100State), @@ -1844,9 +1843,6 @@ static void pci_nic_uninit(PCIDevice *pci_dev) { EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev); - memory_region_destroy(&s->mmio_bar); - memory_region_destroy(&s->io_bar); - memory_region_destroy(&s->flash_bar); vmstate_unregister(&pci_dev->qdev, s->vmstate, s); eeprom93xx_free(&pci_dev->qdev, s->eeprom); qemu_del_nic(s->nic); @@ -1905,11 +1901,17 @@ static int e100_nic_init(PCIDevice *pci_dev) s->vmstate->name = qemu_get_queue(s->nic)->model; vmstate_register(&pci_dev->qdev, -1, s->vmstate, s); - add_boot_device_path(s->conf.bootindex, &pci_dev->qdev, "/ethernet-phy@0"); - return 0; } +static void eepro100_instance_init(Object *obj) +{ + EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, PCI_DEVICE(obj)); + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(s), NULL); +} + static E100PCIDeviceInfo e100_devices[] = { { .name = "i82550", @@ -2108,7 +2110,8 @@ static void eepro100_register_types(void) type_info.parent = TYPE_PCI_DEVICE; type_info.class_init = eepro100_class_init; type_info.instance_size = sizeof(EEPRO100State); - + type_info.instance_init = eepro100_instance_init; + type_register(&type_info); } } diff --git a/hw/net/fsl_etsec/rings.c b/hw/net/fsl_etsec/rings.c index e36cfbe76d..d4a494f6a3 100644 --- a/hw/net/fsl_etsec/rings.c +++ b/hw/net/fsl_etsec/rings.c @@ -159,7 +159,7 @@ static void ievent_set(eTSEC *etsec, if ((flags & IEVENT_RXB && etsec->regs[IMASK].value & IMASK_RXBEN) || (flags & IEVENT_RXF && etsec->regs[IMASK].value & IMASK_RXFEN)) { - qemu_irq_pulse(etsec->rx_irq); + qemu_irq_raise(etsec->rx_irq); RING_DEBUG("%s Raise Rx IRQ\n", __func__); } } diff --git a/hw/net/lance.c b/hw/net/lance.c index fe18564e1e..a1c49f1b97 100644 --- a/hw/net/lance.c +++ b/hw/net/lance.c @@ -42,6 +42,7 @@ #include "hw/sparc/sun4m.h" #include "pcnet.h" #include "trace.h" +#include "sysemu/sysemu.h" #define TYPE_LANCE "lance" #define SYSBUS_PCNET(obj) \ @@ -110,8 +111,7 @@ static const VMStateDescription vmstate_lance = { .name = "pcnet", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(state, SysBusPCNetState, 0, vmstate_pcnet, PCNetState), VMSTATE_END_OF_LIST() } @@ -144,6 +144,16 @@ static void lance_reset(DeviceState *dev) pcnet_h_reset(&d->state); } +static void lance_instance_init(Object *obj) +{ + SysBusPCNetState *d = SYSBUS_PCNET(obj); + PCNetState *s = &d->state; + + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(obj), NULL); +} + static Property lance_properties[] = { DEFINE_PROP_PTR("dma", SysBusPCNetState, state.dma_opaque), DEFINE_NIC_PROPERTIES(SysBusPCNetState, state.conf), @@ -170,6 +180,7 @@ static const TypeInfo lance_info = { .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(SysBusPCNetState), .class_init = lance_class_init, + .instance_init = lance_instance_init, }; static void lance_register_types(void) diff --git a/hw/net/mcf_fec.c b/hw/net/mcf_fec.c index 4bff3de34f..22cd7cf870 100644 --- a/hw/net/mcf_fec.c +++ b/hw/net/mcf_fec.c @@ -443,9 +443,6 @@ static void mcf_fec_cleanup(NetClientState *nc) { mcf_fec_state *s = qemu_get_nic_opaque(nc); - memory_region_del_subregion(s->sysmem, &s->iomem); - memory_region_destroy(&s->iomem); - g_free(s); } diff --git a/hw/net/milkymist-minimac2.c b/hw/net/milkymist-minimac2.c index 1e9237984d..c6326728eb 100644 --- a/hw/net/milkymist-minimac2.c +++ b/hw/net/milkymist-minimac2.c @@ -472,7 +472,7 @@ static int milkymist_minimac2_init(SysBusDevice *sbd) /* register buffers memory */ memory_region_init_ram(&s->buffers, OBJECT(dev), "milkymist-minimac2.buffers", - buffers_size); + buffers_size, &error_abort); vmstate_register_ram_global(&s->buffers); s->rx0_buf = memory_region_get_ram_ptr(&s->buffers); s->rx1_buf = s->rx0_buf + MINIMAC2_BUFFER_SIZE; @@ -492,8 +492,7 @@ static const VMStateDescription vmstate_milkymist_minimac2_mdio = { .name = "milkymist-minimac2-mdio", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(last_clk, MilkymistMinimac2MdioState), VMSTATE_INT32(count, MilkymistMinimac2MdioState), VMSTATE_UINT32(data, MilkymistMinimac2MdioState), @@ -509,8 +508,7 @@ static const VMStateDescription vmstate_milkymist_minimac2 = { .name = "milkymist-minimac2", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistMinimac2State, R_MAX), VMSTATE_UINT16_ARRAY(phy_regs, MilkymistMinimac2State, R_PHY_MAX), VMSTATE_STRUCT(mdio, MilkymistMinimac2State, 0, diff --git a/hw/net/mipsnet.c b/hw/net/mipsnet.c index e421b867e7..b26c369178 100644 --- a/hw/net/mipsnet.c +++ b/hw/net/mipsnet.c @@ -198,8 +198,7 @@ static const VMStateDescription vmstate_mipsnet = { .name = "mipsnet", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(busy, MIPSnetState), VMSTATE_UINT32(rx_count, MIPSnetState), VMSTATE_UINT32(rx_read, MIPSnetState), diff --git a/hw/net/ne2000-isa.c b/hw/net/ne2000-isa.c index 0a14f6d1cd..82e2ba17c1 100644 --- a/hw/net/ne2000-isa.c +++ b/hw/net/ne2000-isa.c @@ -28,6 +28,7 @@ #include "net/net.h" #include "ne2000.h" #include "exec/address-spaces.h" +#include "qapi/visitor.h" #define TYPE_ISA_NE2000 "ne2k_isa" #define ISA_NE2000(obj) OBJECT_CHECK(ISANE2000State, (obj), TYPE_ISA_NE2000) @@ -59,8 +60,7 @@ static const VMStateDescription vmstate_isa_ne2000 = { .name = "ne2000", .version_id = 2, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(ne2000, ISANE2000State, 0, vmstate_ne2000, NE2000State), VMSTATE_END_OF_LIST() } @@ -102,11 +102,54 @@ static void isa_ne2000_class_initfn(ObjectClass *klass, void *data) set_bit(DEVICE_CATEGORY_NETWORK, dc->categories); } +static void isa_ne2000_get_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + ISANE2000State *isa = ISA_NE2000(obj); + NE2000State *s = &isa->ne2000; + + visit_type_int32(v, &s->c.bootindex, name, errp); +} + +static void isa_ne2000_set_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + ISANE2000State *isa = ISA_NE2000(obj); + NE2000State *s = &isa->ne2000; + int32_t boot_index; + Error *local_err = NULL; + + visit_type_int32(v, &boot_index, name, &local_err); + if (local_err) { + goto out; + } + /* check whether bootindex is present in fw_boot_order list */ + check_boot_index(boot_index, &local_err); + if (local_err) { + goto out; + } + /* change bootindex to a new one */ + s->c.bootindex = boot_index; + +out: + if (local_err) { + error_propagate(errp, local_err); + } +} + +static void isa_ne2000_instance_init(Object *obj) +{ + object_property_add(obj, "bootindex", "int32", + isa_ne2000_get_bootindex, + isa_ne2000_set_bootindex, NULL, NULL, NULL); + object_property_set_int(obj, -1, "bootindex", NULL); +} static const TypeInfo ne2000_isa_info = { .name = TYPE_ISA_NE2000, .parent = TYPE_ISA_DEVICE, .instance_size = sizeof(ISANE2000State), .class_init = isa_ne2000_class_initfn, + .instance_init = isa_ne2000_instance_init, }; static void ne2000_isa_register_types(void) diff --git a/hw/net/ne2000.c b/hw/net/ne2000.c index 4c32e9ec25..3ab2d03696 100644 --- a/hw/net/ne2000.c +++ b/hw/net/ne2000.c @@ -615,9 +615,8 @@ const VMStateDescription vmstate_ne2000 = { .name = "ne2000", .version_id = 2, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = ne2000_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8_V(rxcr, NE2000State, 2), VMSTATE_UINT8(cmd, NE2000State), VMSTATE_UINT32(start, NE2000State), @@ -645,8 +644,7 @@ static const VMStateDescription vmstate_pci_ne2000 = { .name = "ne2000", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCINE2000State), VMSTATE_STRUCT(ne2000, PCINE2000State, 0, vmstate_ne2000, NE2000State), VMSTATE_END_OF_LIST() @@ -740,8 +738,6 @@ static int pci_ne2000_init(PCIDevice *pci_dev) object_get_typename(OBJECT(pci_dev)), pci_dev->qdev.id, s); qemu_format_nic_info_str(qemu_get_queue(s->nic), s->c.macaddr.a); - add_boot_device_path(s->c.bootindex, &pci_dev->qdev, "/ethernet-phy@0"); - return 0; } @@ -750,11 +746,21 @@ static void pci_ne2000_exit(PCIDevice *pci_dev) PCINE2000State *d = DO_UPCAST(PCINE2000State, dev, pci_dev); NE2000State *s = &d->ne2000; - memory_region_destroy(&s->io); qemu_del_nic(s->nic); qemu_free_irq(s->irq); } +static void ne2000_instance_init(Object *obj) +{ + PCIDevice *pci_dev = PCI_DEVICE(obj); + PCINE2000State *d = DO_UPCAST(PCINE2000State, dev, pci_dev); + NE2000State *s = &d->ne2000; + + device_add_bootindex_property(obj, &s->c.bootindex, + "bootindex", "/ethernet-phy@0", + &pci_dev->qdev, NULL); +} + static Property ne2000_properties[] = { DEFINE_NIC_PROPERTIES(PCINE2000State, ne2000.c), DEFINE_PROP_END_OF_LIST(), @@ -781,6 +787,7 @@ static const TypeInfo ne2000_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(PCINE2000State), .class_init = ne2000_class_init, + .instance_init = ne2000_instance_init, }; static void ne2000_register_types(void) diff --git a/hw/net/pcnet-pci.c b/hw/net/pcnet-pci.c index 6a5d8064bb..fb5f5d6237 100644 --- a/hw/net/pcnet-pci.c +++ b/hw/net/pcnet-pci.c @@ -32,6 +32,7 @@ #include "hw/loader.h" #include "qemu/timer.h" #include "sysemu/dma.h" +#include "sysemu/sysemu.h" #include "pcnet.h" @@ -241,8 +242,7 @@ static const VMStateDescription vmstate_pci_pcnet = { .name = "pcnet", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PCIPCNetState), VMSTATE_STRUCT(state, PCIPCNetState, 0, vmstate_pcnet, PCNetState), VMSTATE_END_OF_LIST() @@ -283,8 +283,6 @@ static void pci_pcnet_uninit(PCIDevice *dev) PCIPCNetState *d = PCI_PCNET(dev); qemu_free_irq(d->state.irq); - memory_region_destroy(&d->state.mmio); - memory_region_destroy(&d->io_bar); timer_del(d->state.poll_timer); timer_free(d->state.poll_timer); qemu_del_nic(d->state.nic); @@ -347,6 +345,16 @@ static void pci_reset(DeviceState *dev) pcnet_h_reset(&d->state); } +static void pcnet_instance_init(Object *obj) +{ + PCIPCNetState *d = PCI_PCNET(obj); + PCNetState *s = &d->state; + + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(obj), NULL); +} + static Property pcnet_properties[] = { DEFINE_NIC_PROPERTIES(PCIPCNetState, state.conf), DEFINE_PROP_END_OF_LIST(), @@ -375,6 +383,7 @@ static const TypeInfo pcnet_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(PCIPCNetState), .class_init = pcnet_class_init, + .instance_init = pcnet_instance_init, }; static void pci_pcnet_register_types(void) diff --git a/hw/net/pcnet.c b/hw/net/pcnet.c index 7cb47b3f1f..f409b9293d 100644 --- a/hw/net/pcnet.c +++ b/hw/net/pcnet.c @@ -718,7 +718,6 @@ static void pcnet_s_reset(PCNetState *s) s->csr[94] = 0x0000; s->csr[100] = 0x0200; s->csr[103] = 0x0105; - s->csr[103] = 0x0105; s->csr[112] = 0x0000; s->csr[114] = 0x0000; s->csr[122] = 0x0000; @@ -1213,7 +1212,7 @@ static void pcnet_transmit(PCNetState *s) hwaddr xmit_cxda = 0; int count = CSR_XMTRL(s)-1; int add_crc = 0; - + int bcnt; s->xmit_pos = -1; if (!CSR_TXON(s)) { @@ -1248,35 +1247,40 @@ static void pcnet_transmit(PCNetState *s) s->xmit_pos = -1; goto txdone; } + + if (s->xmit_pos < 0) { + goto txdone; + } + + bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT); + s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr), + s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s)); + s->xmit_pos += bcnt; + if (!GET_FIELD(tmd.status, TMDS, ENP)) { - int bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT); - s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr), - s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s)); - s->xmit_pos += bcnt; - } else if (s->xmit_pos >= 0) { - int bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT); - s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr), - s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s)); - s->xmit_pos += bcnt; + goto txdone; + } + #ifdef PCNET_DEBUG - printf("pcnet_transmit size=%d\n", s->xmit_pos); + printf("pcnet_transmit size=%d\n", s->xmit_pos); #endif - if (CSR_LOOP(s)) { - if (BCR_SWSTYLE(s) == 1) - add_crc = !GET_FIELD(tmd.status, TMDS, NOFCS); - s->looptest = add_crc ? PCNET_LOOPTEST_CRC : PCNET_LOOPTEST_NOCRC; - pcnet_receive(qemu_get_queue(s->nic), s->buffer, s->xmit_pos); - s->looptest = 0; - } else - if (s->nic) - qemu_send_packet(qemu_get_queue(s->nic), s->buffer, - s->xmit_pos); - - s->csr[0] &= ~0x0008; /* clear TDMD */ - s->csr[4] |= 0x0004; /* set TXSTRT */ - s->xmit_pos = -1; + if (CSR_LOOP(s)) { + if (BCR_SWSTYLE(s) == 1) + add_crc = !GET_FIELD(tmd.status, TMDS, NOFCS); + s->looptest = add_crc ? PCNET_LOOPTEST_CRC : PCNET_LOOPTEST_NOCRC; + pcnet_receive(qemu_get_queue(s->nic), s->buffer, s->xmit_pos); + s->looptest = 0; + } else { + if (s->nic) { + qemu_send_packet(qemu_get_queue(s->nic), s->buffer, + s->xmit_pos); + } } + s->csr[0] &= ~0x0008; /* clear TDMD */ + s->csr[4] |= 0x0004; /* set TXSTRT */ + s->xmit_pos = -1; + txdone: SET_FIELD(&tmd.status, TMDS, OWN, 0); TMDSTORE(&tmd, PHYSADDR(s,CSR_CXDA(s))); @@ -1701,8 +1705,7 @@ const VMStateDescription vmstate_pcnet = { .name = "pcnet", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(rap, PCNetState), VMSTATE_INT32(isr, PCNetState), VMSTATE_INT32(lnkst, PCNetState), @@ -1737,8 +1740,6 @@ int pcnet_common_init(DeviceState *dev, PCNetState *s, NetClientInfo *info) s->nic = qemu_new_nic(info, &s->conf, object_get_typename(OBJECT(dev)), dev->id, s); qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a); - add_boot_device_path(s->conf.bootindex, dev, "/ethernet-phy@0"); - /* Initialize the PROM */ /* diff --git a/hw/net/pcnet.h b/hw/net/pcnet.h index 9dee6f3e2c..f8e8a6f6ba 100644 --- a/hw/net/pcnet.h +++ b/hw/net/pcnet.h @@ -66,5 +66,4 @@ void pcnet_set_link_status(NetClientState *nc); void pcnet_common_cleanup(PCNetState *d); int pcnet_common_init(DeviceState *dev, PCNetState *s, NetClientInfo *info); extern const VMStateDescription vmstate_pcnet; - #endif diff --git a/hw/net/rtl8139.c b/hw/net/rtl8139.c index 5329f44a9d..5f0197c9df 100644 --- a/hw/net/rtl8139.c +++ b/hw/net/rtl8139.c @@ -1358,8 +1358,7 @@ static const VMStateDescription vmstate_tally_counters = { .name = "tally_counters", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT64(TxOk, RTL8139TallyCounters), VMSTATE_UINT64(RxOk, RTL8139TallyCounters), VMSTATE_UINT64(TxERR, RTL8139TallyCounters), @@ -1776,6 +1775,7 @@ static void rtl8139_transfer_frame(RTL8139State *s, uint8_t *buf, int size, int do_interrupt, const uint8_t *dot1q_buf) { struct iovec *iov = NULL; + struct iovec vlan_iov[3]; if (!size) { @@ -1790,6 +1790,9 @@ static void rtl8139_transfer_frame(RTL8139State *s, uint8_t *buf, int size, { .iov_base = buf + ETHER_ADDR_LEN * 2, .iov_len = size - ETHER_ADDR_LEN * 2 }, }; + + memcpy(vlan_iov, iov, sizeof(vlan_iov)); + iov = vlan_iov; } if (TxLoopBack == (s->TxConfig & TxLoopBack)) @@ -3271,8 +3274,7 @@ static const VMStateDescription vmstate_rtl8139_hotplug_ready ={ .name = "rtl8139/hotplug_ready", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_END_OF_LIST() } }; @@ -3293,10 +3295,9 @@ static const VMStateDescription vmstate_rtl8139 = { .name = "rtl8139", .version_id = 4, .minimum_version_id = 3, - .minimum_version_id_old = 3, .post_load = rtl8139_post_load, .pre_save = rtl8139_pre_save, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, RTL8139State), VMSTATE_PARTIAL_BUFFER(phys, RTL8139State, 6), VMSTATE_BUFFER(mult, RTL8139State), @@ -3465,8 +3466,6 @@ static void pci_rtl8139_uninit(PCIDevice *dev) { RTL8139State *s = RTL8139(dev); - memory_region_destroy(&s->bar_io); - memory_region_destroy(&s->bar_mem); if (s->cplus_txbuffer) { g_free(s->cplus_txbuffer); s->cplus_txbuffer = NULL; @@ -3543,11 +3542,18 @@ static int pci_rtl8139_init(PCIDevice *dev) s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, rtl8139_timer, s); rtl8139_set_next_tctr_time(s, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)); - add_boot_device_path(s->conf.bootindex, d, "/ethernet-phy@0"); - return 0; } +static void rtl8139_instance_init(Object *obj) +{ + RTL8139State *s = RTL8139(obj); + + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(obj), NULL); +} + static Property rtl8139_properties[] = { DEFINE_NIC_PROPERTIES(RTL8139State, conf), DEFINE_PROP_END_OF_LIST(), @@ -3576,6 +3582,7 @@ static const TypeInfo rtl8139_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(RTL8139State), .class_init = rtl8139_class_init, + .instance_init = rtl8139_instance_init, }; static void rtl8139_register_types(void) diff --git a/hw/net/smc91c111.c b/hw/net/smc91c111.c index a8e29b3b42..d1dca8f4e2 100644 --- a/hw/net/smc91c111.c +++ b/hw/net/smc91c111.c @@ -54,7 +54,7 @@ static const VMStateDescription vmstate_smc91c111 = { .name = "smc91c111", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(tcr, smc91c111_state), VMSTATE_UINT16(rcr, smc91c111_state), VMSTATE_UINT16(cr, smc91c111_state), diff --git a/hw/net/spapr_llan.c b/hw/net/spapr_llan.c index c433337b67..2c8b038227 100644 --- a/hw/net/spapr_llan.c +++ b/hw/net/spapr_llan.c @@ -72,7 +72,14 @@ typedef uint64_t vlan_bd_t; #define VLAN_RXQ_BD_OFF 0 #define VLAN_FILTER_BD_OFF 8 #define VLAN_RX_BDS_OFF 16 -#define VLAN_MAX_BUFS ((SPAPR_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF) / 8) +/* + * The final 8 bytes of the buffer list is a counter of frames dropped + * because there was not a buffer in the buffer list capable of holding + * the frame. We must avoid it, or the operating system will report garbage + * for this statistic. + */ +#define VLAN_RX_BDS_LEN (SPAPR_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF - 8) +#define VLAN_MAX_BUFS (VLAN_RX_BDS_LEN / 8) #define TYPE_VIO_SPAPR_VLAN_DEVICE "spapr-vlan" #define VIO_SPAPR_VLAN_DEVICE(obj) \ @@ -119,7 +126,7 @@ static ssize_t spapr_vlan_receive(NetClientState *nc, const uint8_t *buf, do { buf_ptr += 8; - if (buf_ptr >= SPAPR_TCE_PAGE_SIZE) { + if (buf_ptr >= (VLAN_RX_BDS_LEN + VLAN_RX_BDS_OFF)) { buf_ptr = VLAN_RX_BDS_OFF; } @@ -214,11 +221,18 @@ static int spapr_vlan_init(VIOsPAPRDevice *sdev) object_get_typename(OBJECT(sdev)), sdev->qdev.id, dev); qemu_format_nic_info_str(qemu_get_queue(dev->nic), dev->nicconf.macaddr.a); - add_boot_device_path(dev->nicconf.bootindex, DEVICE(dev), ""); - return 0; } +static void spapr_vlan_instance_init(Object *obj) +{ + VIOsPAPRVLANDevice *dev = VIO_SPAPR_VLAN_DEVICE(obj); + + device_add_bootindex_property(obj, &dev->nicconf.bootindex, + "bootindex", "", + DEVICE(dev), NULL); +} + void spapr_vlan_create(VIOsPAPRBus *bus, NICInfo *nd) { DeviceState *dev; @@ -397,7 +411,7 @@ static target_ulong h_add_logical_lan_buffer(PowerPCCPU *cpu, do { dev->add_buf_ptr += 8; - if (dev->add_buf_ptr >= SPAPR_TCE_PAGE_SIZE) { + if (dev->add_buf_ptr >= (VLAN_RX_BDS_LEN + VLAN_RX_BDS_OFF)) { dev->add_buf_ptr = VLAN_RX_BDS_OFF; } @@ -509,8 +523,7 @@ static const VMStateDescription vmstate_spapr_llan = { .name = "spapr_llan", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_SPAPR_VIO(sdev, VIOsPAPRVLANDevice), /* LLAN state */ VMSTATE_BOOL(isopen, VIOsPAPRVLANDevice), @@ -547,6 +560,7 @@ static const TypeInfo spapr_vlan_info = { .parent = TYPE_VIO_SPAPR_DEVICE, .instance_size = sizeof(VIOsPAPRVLANDevice), .class_init = spapr_vlan_class_init, + .instance_init = spapr_vlan_instance_init, }; static void spapr_vlan_register_types(void) diff --git a/hw/net/stellaris_enet.c b/hw/net/stellaris_enet.c index d04e6a46f8..c07e5137c2 100644 --- a/hw/net/stellaris_enet.c +++ b/hw/net/stellaris_enet.c @@ -47,6 +47,11 @@ do { fprintf(stderr, "stellaris_enet: error: " fmt , ## __VA_ARGS__);} while (0) OBJECT_CHECK(stellaris_enet_state, (obj), TYPE_STELLARIS_ENET) typedef struct { + uint8_t data[2048]; + uint32_t len; +} StellarisEnetRxFrame; + +typedef struct { SysBusDevice parent_obj; uint32_t ris; @@ -59,29 +64,159 @@ typedef struct { uint32_t mtxd; uint32_t mrxd; uint32_t np; - int tx_frame_len; - int tx_fifo_len; + uint32_t tx_fifo_len; uint8_t tx_fifo[2048]; /* Real hardware has a 2k fifo, which works out to be at most 31 packets. We implement a full 31 packet fifo. */ - struct { - uint8_t data[2048]; - int len; - } rx[31]; - uint8_t *rx_fifo; - int rx_fifo_len; - int next_packet; + StellarisEnetRxFrame rx[31]; + uint32_t rx_fifo_offset; + uint32_t next_packet; NICState *nic; NICConf conf; qemu_irq irq; MemoryRegion mmio; } stellaris_enet_state; +static const VMStateDescription vmstate_rx_frame = { + .name = "stellaris_enet/rx_frame", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT8_ARRAY(data, StellarisEnetRxFrame, 2048), + VMSTATE_UINT32(len, StellarisEnetRxFrame), + VMSTATE_END_OF_LIST() + } +}; + +static int stellaris_enet_post_load(void *opaque, int version_id) +{ + stellaris_enet_state *s = opaque; + int i; + + /* Sanitize inbound state. Note that next_packet is an index but + * np is a size; hence their valid upper bounds differ. + */ + if (s->next_packet >= ARRAY_SIZE(s->rx)) { + return -1; + } + + if (s->np > ARRAY_SIZE(s->rx)) { + return -1; + } + + for (i = 0; i < ARRAY_SIZE(s->rx); i++) { + if (s->rx[i].len > ARRAY_SIZE(s->rx[i].data)) { + return -1; + } + } + + if (s->rx_fifo_offset > ARRAY_SIZE(s->rx[0].data) - 4) { + return -1; + } + + if (s->tx_fifo_len > ARRAY_SIZE(s->tx_fifo)) { + return -1; + } + + return 0; +} + +static const VMStateDescription vmstate_stellaris_enet = { + .name = "stellaris_enet", + .version_id = 2, + .minimum_version_id = 2, + .post_load = stellaris_enet_post_load, + .fields = (VMStateField[]) { + VMSTATE_UINT32(ris, stellaris_enet_state), + VMSTATE_UINT32(im, stellaris_enet_state), + VMSTATE_UINT32(rctl, stellaris_enet_state), + VMSTATE_UINT32(tctl, stellaris_enet_state), + VMSTATE_UINT32(thr, stellaris_enet_state), + VMSTATE_UINT32(mctl, stellaris_enet_state), + VMSTATE_UINT32(mdv, stellaris_enet_state), + VMSTATE_UINT32(mtxd, stellaris_enet_state), + VMSTATE_UINT32(mrxd, stellaris_enet_state), + VMSTATE_UINT32(np, stellaris_enet_state), + VMSTATE_UINT32(tx_fifo_len, stellaris_enet_state), + VMSTATE_UINT8_ARRAY(tx_fifo, stellaris_enet_state, 2048), + VMSTATE_STRUCT_ARRAY(rx, stellaris_enet_state, 31, 1, + vmstate_rx_frame, StellarisEnetRxFrame), + VMSTATE_UINT32(rx_fifo_offset, stellaris_enet_state), + VMSTATE_UINT32(next_packet, stellaris_enet_state), + VMSTATE_END_OF_LIST() + } +}; + static void stellaris_enet_update(stellaris_enet_state *s) { qemu_set_irq(s->irq, (s->ris & s->im) != 0); } +/* Return the data length of the packet currently being assembled + * in the TX fifo. + */ +static inline int stellaris_txpacket_datalen(stellaris_enet_state *s) +{ + return s->tx_fifo[0] | (s->tx_fifo[1] << 8); +} + +/* Return true if the packet currently in the TX FIFO is complete, +* ie the FIFO holds enough bytes for the data length, ethernet header, +* payload and optionally CRC. +*/ +static inline bool stellaris_txpacket_complete(stellaris_enet_state *s) +{ + int framelen = stellaris_txpacket_datalen(s); + framelen += 16; + if (!(s->tctl & SE_TCTL_CRC)) { + framelen += 4; + } + /* Cover the corner case of a 2032 byte payload with auto-CRC disabled: + * this requires more bytes than will fit in the FIFO. It's not totally + * clear how the h/w handles this, but if using threshold-based TX + * it will definitely try to transmit something. + */ + framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo)); + return s->tx_fifo_len >= framelen; +} + +/* Return true if the TX FIFO threshold is enabled and the FIFO + * has filled enough to reach it. + */ +static inline bool stellaris_tx_thr_reached(stellaris_enet_state *s) +{ + return (s->thr < 0x3f && + (s->tx_fifo_len >= 4 * (s->thr * 8 + 1))); +} + +/* Send the packet currently in the TX FIFO */ +static void stellaris_enet_send(stellaris_enet_state *s) +{ + int framelen = stellaris_txpacket_datalen(s); + + /* Ethernet header is in the FIFO but not in the datacount. + * We don't implement explicit CRC, so just ignore any + * CRC value in the FIFO. + */ + framelen += 14; + if ((s->tctl & SE_TCTL_PADEN) && framelen < 60) { + memset(&s->tx_fifo[framelen + 2], 0, 60 - framelen); + framelen = 60; + } + /* This MIN will have no effect unless the FIFO data is corrupt + * (eg bad data from an incoming migration); otherwise the check + * on the datalen at the start of writing the data into the FIFO + * will have caught this. Silently write a corrupt half-packet, + * which is what the hardware does in FIFO underrun situations. + */ + framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo) - 2); + qemu_send_packet(qemu_get_queue(s->nic), s->tx_fifo + 2, framelen); + s->tx_fifo_len = 0; + s->ris |= SE_INT_TXEMP; + stellaris_enet_update(s); + DPRINTF("Done TX\n"); +} + /* TODO: Implement MAC address filtering. */ static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { @@ -97,7 +232,7 @@ static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, si return -1; } - DPRINTF("Received packet len=%d\n", size); + DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; @@ -152,21 +287,21 @@ static uint64_t stellaris_enet_read(void *opaque, hwaddr offset, case 0x0c: /* TCTL */ return s->tctl; case 0x10: /* DATA */ - if (s->rx_fifo_len == 0) { - if (s->np == 0) { - BADF("RX underflow\n"); - return 0; - } - s->rx_fifo_len = s->rx[s->next_packet].len; - s->rx_fifo = s->rx[s->next_packet].data; - DPRINTF("RX FIFO start packet len=%d\n", s->rx_fifo_len); + { + uint8_t *rx_fifo; + + if (s->np == 0) { + BADF("RX underflow\n"); + return 0; } - val = s->rx_fifo[0] | (s->rx_fifo[1] << 8) | (s->rx_fifo[2] << 16) - | (s->rx_fifo[3] << 24); - s->rx_fifo += 4; - s->rx_fifo_len -= 4; - if (s->rx_fifo_len <= 0) { - s->rx_fifo_len = 0; + + rx_fifo = s->rx[s->next_packet].data + s->rx_fifo_offset; + + val = rx_fifo[0] | (rx_fifo[1] << 8) | (rx_fifo[2] << 16) + | (rx_fifo[3] << 24); + s->rx_fifo_offset += 4; + if (s->rx_fifo_offset >= s->rx[s->next_packet].len) { + s->rx_fifo_offset = 0; s->next_packet++; if (s->next_packet >= 31) s->next_packet = 0; @@ -174,6 +309,7 @@ static uint64_t stellaris_enet_read(void *opaque, hwaddr offset, DPRINTF("RX done np=%d\n", s->np); } return val; + } case 0x14: /* IA0 */ return s->conf.macaddr.a[0] | (s->conf.macaddr.a[1] << 8) | (s->conf.macaddr.a[2] << 16) @@ -212,22 +348,23 @@ static void stellaris_enet_write(void *opaque, hwaddr offset, switch (offset) { case 0x00: /* IACK */ s->ris &= ~value; - DPRINTF("IRQ ack %02x/%02x\n", value, s->ris); + DPRINTF("IRQ ack %02" PRIx64 "/%02x\n", value, s->ris); stellaris_enet_update(s); /* Clearing TXER also resets the TX fifo. */ - if (value & SE_INT_TXER) - s->tx_frame_len = -1; + if (value & SE_INT_TXER) { + s->tx_fifo_len = 0; + } break; case 0x04: /* IM */ - DPRINTF("IRQ mask %02x/%02x\n", value, s->ris); + DPRINTF("IRQ mask %02" PRIx64 "/%02x\n", value, s->ris); s->im = value; stellaris_enet_update(s); break; case 0x08: /* RCTL */ s->rctl = value; if (value & SE_RCTL_RSTFIFO) { - s->rx_fifo_len = 0; s->np = 0; + s->rx_fifo_offset = 0; stellaris_enet_update(s); } break; @@ -235,43 +372,26 @@ static void stellaris_enet_write(void *opaque, hwaddr offset, s->tctl = value; break; case 0x10: /* DATA */ - if (s->tx_frame_len == -1) { - s->tx_frame_len = value & 0xffff; - if (s->tx_frame_len > 2032) { - DPRINTF("TX frame too long (%d)\n", s->tx_frame_len); - s->tx_frame_len = 0; + if (s->tx_fifo_len == 0) { + /* The first word is special, it contains the data length */ + int framelen = value & 0xffff; + if (framelen > 2032) { + DPRINTF("TX frame too long (%d)\n", framelen); s->ris |= SE_INT_TXER; stellaris_enet_update(s); - } else { - DPRINTF("Start TX frame len=%d\n", s->tx_frame_len); - /* The value written does not include the ethernet header. */ - s->tx_frame_len += 14; - if ((s->tctl & SE_TCTL_CRC) == 0) - s->tx_frame_len += 4; - s->tx_fifo_len = 0; - s->tx_fifo[s->tx_fifo_len++] = value >> 16; - s->tx_fifo[s->tx_fifo_len++] = value >> 24; + break; } - } else { + } + + if (s->tx_fifo_len + 4 <= ARRAY_SIZE(s->tx_fifo)) { s->tx_fifo[s->tx_fifo_len++] = value; s->tx_fifo[s->tx_fifo_len++] = value >> 8; s->tx_fifo[s->tx_fifo_len++] = value >> 16; s->tx_fifo[s->tx_fifo_len++] = value >> 24; - if (s->tx_fifo_len >= s->tx_frame_len) { - /* We don't implement explicit CRC, so just chop it off. */ - if ((s->tctl & SE_TCTL_CRC) == 0) - s->tx_frame_len -= 4; - if ((s->tctl & SE_TCTL_PADEN) && s->tx_frame_len < 60) { - memset(&s->tx_fifo[s->tx_frame_len], 0, 60 - s->tx_frame_len); - s->tx_fifo_len = 60; - } - qemu_send_packet(qemu_get_queue(s->nic), s->tx_fifo, - s->tx_frame_len); - s->tx_frame_len = -1; - s->ris |= SE_INT_TXEMP; - stellaris_enet_update(s); - DPRINTF("Done TX\n"); - } + } + + if (stellaris_tx_thr_reached(s) && stellaris_txpacket_complete(s)) { + stellaris_enet_send(s); } break; case 0x14: /* IA0 */ @@ -299,9 +419,13 @@ static void stellaris_enet_write(void *opaque, hwaddr offset, case 0x2c: /* MTXD */ s->mtxd = value & 0xff; break; + case 0x38: /* TR */ + if (value & 1) { + stellaris_enet_send(s); + } + break; case 0x30: /* MRXD */ case 0x34: /* NP */ - case 0x38: /* TR */ /* Ignored. */ case 0x3c: /* Undocuented: Timestamp? */ /* Ignored. */ @@ -324,68 +448,7 @@ static void stellaris_enet_reset(stellaris_enet_state *s) s->im = SE_INT_PHY | SE_INT_MD | SE_INT_RXER | SE_INT_FOV | SE_INT_TXEMP | SE_INT_TXER | SE_INT_RX; s->thr = 0x3f; - s->tx_frame_len = -1; -} - -static void stellaris_enet_save(QEMUFile *f, void *opaque) -{ - stellaris_enet_state *s = (stellaris_enet_state *)opaque; - int i; - - qemu_put_be32(f, s->ris); - qemu_put_be32(f, s->im); - qemu_put_be32(f, s->rctl); - qemu_put_be32(f, s->tctl); - qemu_put_be32(f, s->thr); - qemu_put_be32(f, s->mctl); - qemu_put_be32(f, s->mdv); - qemu_put_be32(f, s->mtxd); - qemu_put_be32(f, s->mrxd); - qemu_put_be32(f, s->np); - qemu_put_be32(f, s->tx_frame_len); - qemu_put_be32(f, s->tx_fifo_len); - qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo)); - for (i = 0; i < 31; i++) { - qemu_put_be32(f, s->rx[i].len); - qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data)); - - } - qemu_put_be32(f, s->next_packet); - qemu_put_be32(f, s->rx_fifo - s->rx[s->next_packet].data); - qemu_put_be32(f, s->rx_fifo_len); -} - -static int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id) -{ - stellaris_enet_state *s = (stellaris_enet_state *)opaque; - int i; - - if (version_id != 1) - return -EINVAL; - - s->ris = qemu_get_be32(f); - s->im = qemu_get_be32(f); - s->rctl = qemu_get_be32(f); - s->tctl = qemu_get_be32(f); - s->thr = qemu_get_be32(f); - s->mctl = qemu_get_be32(f); - s->mdv = qemu_get_be32(f); - s->mtxd = qemu_get_be32(f); - s->mrxd = qemu_get_be32(f); - s->np = qemu_get_be32(f); - s->tx_frame_len = qemu_get_be32(f); - s->tx_fifo_len = qemu_get_be32(f); - qemu_get_buffer(f, s->tx_fifo, sizeof(s->tx_fifo)); - for (i = 0; i < 31; i++) { - s->rx[i].len = qemu_get_be32(f); - qemu_get_buffer(f, s->rx[i].data, sizeof(s->rx[i].data)); - - } - s->next_packet = qemu_get_be32(f); - s->rx_fifo = s->rx[s->next_packet].data + qemu_get_be32(f); - s->rx_fifo_len = qemu_get_be32(f); - - return 0; + s->tx_fifo_len = 0; } static void stellaris_enet_cleanup(NetClientState *nc) @@ -419,20 +482,9 @@ static int stellaris_enet_init(SysBusDevice *sbd) qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a); stellaris_enet_reset(s); - register_savevm(dev, "stellaris_enet", -1, 1, - stellaris_enet_save, stellaris_enet_load, s); return 0; } -static void stellaris_enet_unrealize(DeviceState *dev, Error **errp) -{ - stellaris_enet_state *s = STELLARIS_ENET(dev); - - unregister_savevm(DEVICE(s), "stellaris_enet", s); - - memory_region_destroy(&s->mmio); -} - static Property stellaris_enet_properties[] = { DEFINE_NIC_PROPERTIES(stellaris_enet_state, conf), DEFINE_PROP_END_OF_LIST(), @@ -444,8 +496,8 @@ static void stellaris_enet_class_init(ObjectClass *klass, void *data) SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); k->init = stellaris_enet_init; - dc->unrealize = stellaris_enet_unrealize; dc->props = stellaris_enet_properties; + dc->vmsd = &vmstate_stellaris_enet; } static const TypeInfo stellaris_enet_info = { diff --git a/hw/net/vhost_net.c b/hw/net/vhost_net.c index a1de2f43a0..4e3a061622 100644 --- a/hw/net/vhost_net.c +++ b/hw/net/vhost_net.c @@ -15,6 +15,7 @@ #include "net/net.h" #include "net/tap.h" +#include "net/vhost-user.h" #include "hw/virtio/virtio-net.h" #include "net/vhost_net.h" @@ -27,8 +28,6 @@ #include <sys/socket.h> #include <linux/kvm.h> #include <fcntl.h> -#include <sys/ioctl.h> -#include <linux/virtio_ring.h> #include <netpacket/packet.h> #include <net/ethernet.h> #include <net/if.h> @@ -36,6 +35,7 @@ #include <stdio.h> +#include "hw/virtio/virtio_ring.h" #include "hw/virtio/vhost.h" #include "hw/virtio/virtio-bus.h" @@ -46,39 +46,77 @@ struct vhost_net { NetClientState *nc; }; -unsigned vhost_net_get_features(struct vhost_net *net, unsigned features) +/* Features supported by host kernel. */ +static const int kernel_feature_bits[] = { + VIRTIO_F_NOTIFY_ON_EMPTY, + VIRTIO_RING_F_INDIRECT_DESC, + VIRTIO_RING_F_EVENT_IDX, + VIRTIO_NET_F_MRG_RXBUF, + VHOST_INVALID_FEATURE_BIT +}; + +/* Features supported by others. */ +const int user_feature_bits[] = { + VIRTIO_F_NOTIFY_ON_EMPTY, + VIRTIO_RING_F_INDIRECT_DESC, + VIRTIO_RING_F_EVENT_IDX, + + VIRTIO_F_ANY_LAYOUT, + VIRTIO_NET_F_CSUM, + VIRTIO_NET_F_GUEST_CSUM, + VIRTIO_NET_F_GSO, + VIRTIO_NET_F_GUEST_TSO4, + VIRTIO_NET_F_GUEST_TSO6, + VIRTIO_NET_F_GUEST_ECN, + VIRTIO_NET_F_GUEST_UFO, + VIRTIO_NET_F_HOST_TSO4, + VIRTIO_NET_F_HOST_TSO6, + VIRTIO_NET_F_HOST_ECN, + VIRTIO_NET_F_HOST_UFO, + VIRTIO_NET_F_MRG_RXBUF, + VIRTIO_NET_F_STATUS, + VIRTIO_NET_F_CTRL_VQ, + VIRTIO_NET_F_CTRL_RX, + VIRTIO_NET_F_CTRL_VLAN, + VIRTIO_NET_F_CTRL_RX_EXTRA, + VIRTIO_NET_F_CTRL_MAC_ADDR, + VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, + + VIRTIO_NET_F_MQ, + + VHOST_INVALID_FEATURE_BIT +}; + +static const int *vhost_net_get_feature_bits(struct vhost_net *net) { - /* Clear features not supported by host kernel. */ - if (!(net->dev.features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY))) { - features &= ~(1 << VIRTIO_F_NOTIFY_ON_EMPTY); - } - if (!(net->dev.features & (1 << VIRTIO_RING_F_INDIRECT_DESC))) { - features &= ~(1 << VIRTIO_RING_F_INDIRECT_DESC); - } - if (!(net->dev.features & (1 << VIRTIO_RING_F_EVENT_IDX))) { - features &= ~(1 << VIRTIO_RING_F_EVENT_IDX); - } - if (!(net->dev.features & (1 << VIRTIO_NET_F_MRG_RXBUF))) { - features &= ~(1 << VIRTIO_NET_F_MRG_RXBUF); + const int *feature_bits = 0; + + switch (net->nc->info->type) { + case NET_CLIENT_OPTIONS_KIND_TAP: + feature_bits = kernel_feature_bits; + break; + case NET_CLIENT_OPTIONS_KIND_VHOST_USER: + feature_bits = user_feature_bits; + break; + default: + error_report("Feature bits not defined for this type: %d", + net->nc->info->type); + break; } - return features; + + return feature_bits; +} + +unsigned vhost_net_get_features(struct vhost_net *net, unsigned features) +{ + return vhost_get_features(&net->dev, vhost_net_get_feature_bits(net), + features); } void vhost_net_ack_features(struct vhost_net *net, unsigned features) { net->dev.acked_features = net->dev.backend_features; - if (features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) { - net->dev.acked_features |= (1 << VIRTIO_F_NOTIFY_ON_EMPTY); - } - if (features & (1 << VIRTIO_RING_F_INDIRECT_DESC)) { - net->dev.acked_features |= (1 << VIRTIO_RING_F_INDIRECT_DESC); - } - if (features & (1 << VIRTIO_RING_F_EVENT_IDX)) { - net->dev.acked_features |= (1 << VIRTIO_RING_F_EVENT_IDX); - } - if (features & (1 << VIRTIO_NET_F_MRG_RXBUF)) { - net->dev.acked_features |= (1 << VIRTIO_NET_F_MRG_RXBUF); - } + vhost_ack_features(&net->dev, vhost_net_get_feature_bits(net), features); } static int vhost_net_get_fd(NetClientState *backend) @@ -92,42 +130,52 @@ static int vhost_net_get_fd(NetClientState *backend) } } -struct vhost_net *vhost_net_init(NetClientState *backend, int devfd, - bool force) +struct vhost_net *vhost_net_init(VhostNetOptions *options) { int r; + bool backend_kernel = options->backend_type == VHOST_BACKEND_TYPE_KERNEL; struct vhost_net *net = g_malloc(sizeof *net); - if (!backend) { - fprintf(stderr, "vhost-net requires backend to be setup\n"); + + if (!options->net_backend) { + fprintf(stderr, "vhost-net requires net backend to be setup\n"); goto fail; } - r = vhost_net_get_fd(backend); - if (r < 0) { - goto fail; + + if (backend_kernel) { + r = vhost_net_get_fd(options->net_backend); + if (r < 0) { + goto fail; + } + net->dev.backend_features = qemu_has_vnet_hdr(options->net_backend) + ? 0 : (1 << VHOST_NET_F_VIRTIO_NET_HDR); + net->backend = r; + } else { + net->dev.backend_features = 0; + net->backend = -1; } - net->nc = backend; - net->dev.backend_features = qemu_has_vnet_hdr(backend) ? 0 : - (1 << VHOST_NET_F_VIRTIO_NET_HDR); - net->backend = r; + net->nc = options->net_backend; net->dev.nvqs = 2; net->dev.vqs = net->vqs; - r = vhost_dev_init(&net->dev, devfd, "/dev/vhost-net", force); + r = vhost_dev_init(&net->dev, options->opaque, + options->backend_type, options->force); if (r < 0) { goto fail; } - if (!qemu_has_vnet_hdr_len(backend, + if (backend_kernel) { + if (!qemu_has_vnet_hdr_len(options->net_backend, sizeof(struct virtio_net_hdr_mrg_rxbuf))) { - net->dev.features &= ~(1 << VIRTIO_NET_F_MRG_RXBUF); - } - if (~net->dev.features & net->dev.backend_features) { - fprintf(stderr, "vhost lacks feature mask %" PRIu64 " for backend\n", - (uint64_t)(~net->dev.features & net->dev.backend_features)); - vhost_dev_cleanup(&net->dev); - goto fail; + net->dev.features &= ~(1 << VIRTIO_NET_F_MRG_RXBUF); + } + if (~net->dev.features & net->dev.backend_features) { + fprintf(stderr, "vhost lacks feature mask %" PRIu64 + " for backend\n", + (uint64_t)(~net->dev.features & net->dev.backend_features)); + vhost_dev_cleanup(&net->dev); + goto fail; + } } - /* Set sane init value. Override when guest acks. */ vhost_net_ack_features(net, 0); return net; @@ -141,20 +189,19 @@ bool vhost_net_query(VHostNetState *net, VirtIODevice *dev) return vhost_dev_query(&net->dev, dev); } +static void vhost_net_set_vq_index(struct vhost_net *net, int vq_index) +{ + net->dev.vq_index = vq_index; +} + static int vhost_net_start_one(struct vhost_net *net, - VirtIODevice *dev, - int vq_index) + VirtIODevice *dev) { struct vhost_vring_file file = { }; int r; - if (net->dev.started) { - return 0; - } - net->dev.nvqs = 2; net->dev.vqs = net->vqs; - net->dev.vq_index = vq_index; r = vhost_dev_enable_notifiers(&net->dev, dev); if (r < 0) { @@ -166,24 +213,37 @@ static int vhost_net_start_one(struct vhost_net *net, goto fail_start; } - net->nc->info->poll(net->nc, false); - qemu_set_fd_handler(net->backend, NULL, NULL, NULL); - file.fd = net->backend; - for (file.index = 0; file.index < net->dev.nvqs; ++file.index) { - r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file); - if (r < 0) { - r = -errno; - goto fail; + if (net->nc->info->poll) { + net->nc->info->poll(net->nc, false); + } + + if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) { + qemu_set_fd_handler(net->backend, NULL, NULL, NULL); + file.fd = net->backend; + for (file.index = 0; file.index < net->dev.nvqs; ++file.index) { + const VhostOps *vhost_ops = net->dev.vhost_ops; + r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND, + &file); + if (r < 0) { + r = -errno; + goto fail; + } } } return 0; fail: file.fd = -1; - while (file.index-- > 0) { - int r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file); - assert(r >= 0); + if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) { + while (file.index-- > 0) { + const VhostOps *vhost_ops = net->dev.vhost_ops; + int r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND, + &file); + assert(r >= 0); + } + } + if (net->nc->info->poll) { + net->nc->info->poll(net->nc, true); } - net->nc->info->poll(net->nc, true); vhost_dev_stop(&net->dev, dev); fail_start: vhost_dev_disable_notifiers(&net->dev, dev); @@ -196,26 +256,47 @@ static void vhost_net_stop_one(struct vhost_net *net, { struct vhost_vring_file file = { .fd = -1 }; - if (!net->dev.started) { - return; + if (net->nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP) { + for (file.index = 0; file.index < net->dev.nvqs; ++file.index) { + const VhostOps *vhost_ops = net->dev.vhost_ops; + int r = vhost_ops->vhost_call(&net->dev, VHOST_NET_SET_BACKEND, + &file); + assert(r >= 0); + } } - - for (file.index = 0; file.index < net->dev.nvqs; ++file.index) { - int r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file); - assert(r >= 0); + if (net->nc->info->poll) { + net->nc->info->poll(net->nc, true); } - net->nc->info->poll(net->nc, true); vhost_dev_stop(&net->dev, dev); vhost_dev_disable_notifiers(&net->dev, dev); } +static bool vhost_net_device_endian_ok(VirtIODevice *vdev) +{ +#ifdef TARGET_IS_BIENDIAN +#ifdef HOST_WORDS_BIGENDIAN + return virtio_is_big_endian(vdev); +#else + return !virtio_is_big_endian(vdev); +#endif +#else + return true; +#endif +} + int vhost_net_start(VirtIODevice *dev, NetClientState *ncs, int total_queues) { BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(dev))); VirtioBusState *vbus = VIRTIO_BUS(qbus); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus); - int r, i = 0; + int r, e, i; + + if (!vhost_net_device_endian_ok(dev)) { + error_report("vhost-net does not support cross-endian"); + r = -ENOSYS; + goto err; + } if (!k->set_guest_notifiers) { error_report("binding does not support guest notifiers"); @@ -224,11 +305,7 @@ int vhost_net_start(VirtIODevice *dev, NetClientState *ncs, } for (i = 0; i < total_queues; i++) { - r = vhost_net_start_one(tap_get_vhost_net(ncs[i].peer), dev, i * 2); - - if (r < 0) { - goto err; - } + vhost_net_set_vq_index(get_vhost_net(ncs[i].peer), i * 2); } r = k->set_guest_notifiers(qbus->parent, total_queues * 2, true); @@ -237,12 +314,26 @@ int vhost_net_start(VirtIODevice *dev, NetClientState *ncs, goto err; } + for (i = 0; i < total_queues; i++) { + r = vhost_net_start_one(get_vhost_net(ncs[i].peer), dev); + + if (r < 0) { + goto err_start; + } + } + return 0; -err: +err_start: while (--i >= 0) { - vhost_net_stop_one(tap_get_vhost_net(ncs[i].peer), dev); + vhost_net_stop_one(get_vhost_net(ncs[i].peer), dev); } + e = k->set_guest_notifiers(qbus->parent, total_queues * 2, false); + if (e < 0) { + fprintf(stderr, "vhost guest notifier cleanup failed: %d\n", e); + fflush(stderr); + } +err: return r; } @@ -254,16 +345,16 @@ void vhost_net_stop(VirtIODevice *dev, NetClientState *ncs, VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus); int i, r; + for (i = 0; i < total_queues; i++) { + vhost_net_stop_one(get_vhost_net(ncs[i].peer), dev); + } + r = k->set_guest_notifiers(qbus->parent, total_queues * 2, false); if (r < 0) { fprintf(stderr, "vhost guest notifier cleanup failed: %d\n", r); fflush(stderr); } assert(r >= 0); - - for (i = 0; i < total_queues; i++) { - vhost_net_stop_one(tap_get_vhost_net(ncs[i].peer), dev); - } } void vhost_net_cleanup(struct vhost_net *net) @@ -282,9 +373,30 @@ void vhost_net_virtqueue_mask(VHostNetState *net, VirtIODevice *dev, { vhost_virtqueue_mask(&net->dev, dev, idx, mask); } + +VHostNetState *get_vhost_net(NetClientState *nc) +{ + VHostNetState *vhost_net = 0; + + if (!nc) { + return 0; + } + + switch (nc->info->type) { + case NET_CLIENT_OPTIONS_KIND_TAP: + vhost_net = tap_get_vhost_net(nc); + break; + case NET_CLIENT_OPTIONS_KIND_VHOST_USER: + vhost_net = vhost_user_get_vhost_net(nc); + break; + default: + break; + } + + return vhost_net; +} #else -struct vhost_net *vhost_net_init(NetClientState *backend, int devfd, - bool force) +struct vhost_net *vhost_net_init(VhostNetOptions *options) { error_report("vhost-net support is not compiled in"); return NULL; @@ -328,4 +440,9 @@ void vhost_net_virtqueue_mask(VHostNetState *net, VirtIODevice *dev, int idx, bool mask) { } + +VHostNetState *get_vhost_net(NetClientState *nc) +{ + return 0; +} #endif diff --git a/hw/net/virtio-net.c b/hw/net/virtio-net.c index 33bd233a2d..e574bd4322 100644 --- a/hw/net/virtio-net.c +++ b/hw/net/virtio-net.c @@ -22,7 +22,8 @@ #include "net/vhost_net.h" #include "hw/virtio/virtio-bus.h" #include "qapi/qmp/qjson.h" -#include "monitor/monitor.h" +#include "qapi-event.h" +#include "hw/virtio/virtio-access.h" #define VIRTIO_NET_VM_VERSION 11 @@ -72,8 +73,8 @@ static void virtio_net_get_config(VirtIODevice *vdev, uint8_t *config) VirtIONet *n = VIRTIO_NET(vdev); struct virtio_net_config netcfg; - stw_p(&netcfg.status, n->status); - stw_p(&netcfg.max_virtqueue_pairs, n->max_queues); + virtio_stw_p(vdev, &netcfg.status, n->status); + virtio_stw_p(vdev, &netcfg.max_virtqueue_pairs, n->max_queues); memcpy(netcfg.mac, n->mac, ETH_ALEN); memcpy(config, &netcfg, n->config_size); } @@ -99,20 +100,23 @@ static bool virtio_net_started(VirtIONet *n, uint8_t status) (n->status & VIRTIO_NET_S_LINK_UP) && vdev->vm_running; } +static void virtio_net_announce_timer(void *opaque) +{ + VirtIONet *n = opaque; + VirtIODevice *vdev = VIRTIO_DEVICE(n); + + n->announce_counter--; + n->status |= VIRTIO_NET_S_ANNOUNCE; + virtio_notify_config(vdev); +} + static void virtio_net_vhost_status(VirtIONet *n, uint8_t status) { VirtIODevice *vdev = VIRTIO_DEVICE(n); NetClientState *nc = qemu_get_queue(n->nic); int queues = n->multiqueue ? n->max_queues : 1; - if (!nc->peer) { - return; - } - if (nc->peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) { - return; - } - - if (!tap_get_vhost_net(nc->peer)) { + if (!get_vhost_net(nc->peer)) { return; } @@ -121,10 +125,23 @@ static void virtio_net_vhost_status(VirtIONet *n, uint8_t status) return; } if (!n->vhost_started) { - int r; - if (!vhost_net_query(tap_get_vhost_net(nc->peer), vdev)) { + int r, i; + + if (!vhost_net_query(get_vhost_net(nc->peer), vdev)) { return; } + + /* Any packets outstanding? Purge them to avoid touching rings + * when vhost is running. + */ + for (i = 0; i < queues; i++) { + NetClientState *qnc = qemu_get_subqueue(n->nic, i); + + /* Purge both directions: TX and RX. */ + qemu_net_queue_purge(qnc->peer->incoming_queue, qnc); + qemu_net_queue_purge(qnc->incoming_queue, qnc->peer); + } + n->vhost_started = 1; r = vhost_net_start(vdev, n->nic->ncs, queues); if (r < 0) { @@ -196,19 +213,12 @@ static void virtio_net_set_link_status(NetClientState *nc) static void rxfilter_notify(NetClientState *nc) { - QObject *event_data; VirtIONet *n = qemu_get_nic_opaque(nc); if (nc->rxfilter_notify_enabled) { gchar *path = object_get_canonical_path(OBJECT(n->qdev)); - if (n->netclient_name) { - event_data = qobject_from_jsonf("{ 'name': %s, 'path': %s }", - n->netclient_name, path); - } else { - event_data = qobject_from_jsonf("{ 'path': %s }", path); - } - monitor_protocol_event(QEVENT_NIC_RX_FILTER_CHANGED, event_data); - qobject_decref(event_data); + qapi_event_send_nic_rx_filter_changed(!!n->netclient_name, + n->netclient_name, path, &error_abort); g_free(path); /* disable event notification to avoid events flooding */ @@ -322,6 +332,9 @@ static void virtio_net_reset(VirtIODevice *vdev) n->nobcast = 0; /* multiqueue is disabled by default */ n->curr_queues = 1; + timer_del(n->announce_timer); + n->announce_counter = 0; + n->status &= ~VIRTIO_NET_S_ANNOUNCE; /* Flush any MAC and VLAN filter table state */ n->mac_table.in_use = 0; @@ -452,13 +465,10 @@ static uint32_t virtio_net_get_features(VirtIODevice *vdev, uint32_t features) features &= ~(0x1 << VIRTIO_NET_F_HOST_UFO); } - if (!nc->peer || nc->peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) { + if (!get_vhost_net(nc->peer)) { return features; } - if (!tap_get_vhost_net(nc->peer)) { - return features; - } - return vhost_net_get_features(tap_get_vhost_net(nc->peer), features); + return vhost_net_get_features(get_vhost_net(nc->peer), features); } static uint32_t virtio_net_bad_features(VirtIODevice *vdev) @@ -522,13 +532,10 @@ static void virtio_net_set_features(VirtIODevice *vdev, uint32_t features) for (i = 0; i < n->max_queues; i++) { NetClientState *nc = qemu_get_subqueue(n->nic, i); - if (!nc->peer || nc->peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) { + if (!get_vhost_net(nc->peer)) { continue; } - if (!tap_get_vhost_net(nc->peer)) { - continue; - } - vhost_net_ack_features(tap_get_vhost_net(nc->peer), features); + vhost_net_ack_features(get_vhost_net(nc->peer), features); } if ((1 << VIRTIO_NET_F_CTRL_VLAN) & features) { @@ -611,6 +618,7 @@ static int virtio_net_handle_offloads(VirtIONet *n, uint8_t cmd, static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd, struct iovec *iov, unsigned int iov_cnt) { + VirtIODevice *vdev = VIRTIO_DEVICE(n); struct virtio_net_ctrl_mac mac_data; size_t s; NetClientState *nc = qemu_get_queue(n->nic); @@ -639,7 +647,7 @@ static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd, s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries, sizeof(mac_data.entries)); - mac_data.entries = ldl_p(&mac_data.entries); + mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries); if (s != sizeof(mac_data.entries)) { goto error; } @@ -666,7 +674,7 @@ static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd, s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries, sizeof(mac_data.entries)); - mac_data.entries = ldl_p(&mac_data.entries); + mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries); if (s != sizeof(mac_data.entries)) { goto error; } @@ -706,12 +714,13 @@ error: static int virtio_net_handle_vlan_table(VirtIONet *n, uint8_t cmd, struct iovec *iov, unsigned int iov_cnt) { + VirtIODevice *vdev = VIRTIO_DEVICE(n); uint16_t vid; size_t s; NetClientState *nc = qemu_get_queue(n->nic); s = iov_to_buf(iov, iov_cnt, 0, &vid, sizeof(vid)); - vid = lduw_p(&vid); + vid = virtio_lduw_p(vdev, &vid); if (s != sizeof(vid)) { return VIRTIO_NET_ERR; } @@ -731,6 +740,23 @@ static int virtio_net_handle_vlan_table(VirtIONet *n, uint8_t cmd, return VIRTIO_NET_OK; } +static int virtio_net_handle_announce(VirtIONet *n, uint8_t cmd, + struct iovec *iov, unsigned int iov_cnt) +{ + if (cmd == VIRTIO_NET_CTRL_ANNOUNCE_ACK && + n->status & VIRTIO_NET_S_ANNOUNCE) { + n->status &= ~VIRTIO_NET_S_ANNOUNCE; + if (n->announce_counter) { + timer_mod(n->announce_timer, + qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + + self_announce_delay(n->announce_counter)); + } + return VIRTIO_NET_OK; + } else { + return VIRTIO_NET_ERR; + } +} + static int virtio_net_handle_mq(VirtIONet *n, uint8_t cmd, struct iovec *iov, unsigned int iov_cnt) { @@ -748,7 +774,7 @@ static int virtio_net_handle_mq(VirtIONet *n, uint8_t cmd, return VIRTIO_NET_ERR; } - queues = lduw_p(&mq.virtqueue_pairs); + queues = virtio_lduw_p(vdev, &mq.virtqueue_pairs); if (queues < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN || queues > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX || @@ -772,7 +798,7 @@ static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) virtio_net_ctrl_ack status = VIRTIO_NET_ERR; VirtQueueElement elem; size_t s; - struct iovec *iov; + struct iovec *iov, *iov2; unsigned int iov_cnt; while (virtqueue_pop(vq, &elem)) { @@ -782,8 +808,8 @@ static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) exit(1); } - iov = elem.out_sg; iov_cnt = elem.out_num; + iov2 = iov = g_memdup(elem.out_sg, sizeof(struct iovec) * elem.out_num); s = iov_to_buf(iov, iov_cnt, 0, &ctrl, sizeof(ctrl)); iov_discard_front(&iov, &iov_cnt, sizeof(ctrl)); if (s != sizeof(ctrl)) { @@ -794,6 +820,8 @@ static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) status = virtio_net_handle_mac(n, ctrl.cmd, iov, iov_cnt); } else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) { status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, iov_cnt); + } else if (ctrl.class == VIRTIO_NET_CTRL_ANNOUNCE) { + status = virtio_net_handle_announce(n, ctrl.cmd, iov, iov_cnt); } else if (ctrl.class == VIRTIO_NET_CTRL_MQ) { status = virtio_net_handle_mq(n, ctrl.cmd, iov, iov_cnt); } else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) { @@ -805,6 +833,7 @@ static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) virtqueue_push(vq, &elem, sizeof(status)); virtio_notify(vdev, vq); + g_free(iov2); } } @@ -863,6 +892,14 @@ static int virtio_net_has_buffers(VirtIONetQueue *q, int bufsize) return 1; } +static void virtio_net_hdr_swap(VirtIODevice *vdev, struct virtio_net_hdr *hdr) +{ + virtio_tswap16s(vdev, &hdr->hdr_len); + virtio_tswap16s(vdev, &hdr->gso_size); + virtio_tswap16s(vdev, &hdr->csum_start); + virtio_tswap16s(vdev, &hdr->csum_offset); +} + /* dhclient uses AF_PACKET but doesn't pass auxdata to the kernel so * it never finds out that the packets don't have valid checksums. This * causes dhclient to get upset. Fedora's carried a patch for ages to @@ -898,6 +935,7 @@ static void receive_header(VirtIONet *n, const struct iovec *iov, int iov_cnt, void *wbuf = (void *)buf; work_around_broken_dhclient(wbuf, wbuf + n->host_hdr_len, size - n->host_hdr_len); + virtio_net_hdr_swap(VIRTIO_DEVICE(n), wbuf); iov_from_buf(iov, iov_cnt, 0, buf, sizeof(struct virtio_net_hdr)); } else { struct virtio_net_hdr hdr = { @@ -1047,7 +1085,7 @@ static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf, size_t } if (mhdr_cnt) { - stw_p(&mhdr.num_buffers, i); + virtio_stw_p(vdev, &mhdr.num_buffers, i); iov_from_buf(mhdr_sg, mhdr_cnt, 0, &mhdr.num_buffers, sizeof mhdr.num_buffers); @@ -1088,8 +1126,6 @@ static int32_t virtio_net_flush_tx(VirtIONetQueue *q) return num_packets; } - assert(vdev->vm_running); - if (q->async_tx.elem.out_num) { virtio_queue_set_notification(q->tx_vq, 0); return num_packets; @@ -1106,6 +1142,14 @@ static int32_t virtio_net_flush_tx(VirtIONetQueue *q) exit(1); } + if (n->has_vnet_hdr) { + if (out_sg[0].iov_len < n->guest_hdr_len) { + error_report("virtio-net header incorrect"); + exit(1); + } + virtio_net_hdr_swap(vdev, (void *) out_sg[0].iov_base); + } + /* * If host wants to see the guest header as is, we can * pass it on unchanged. Otherwise, copy just the parts @@ -1192,7 +1236,12 @@ static void virtio_net_tx_timer(void *opaque) VirtIONetQueue *q = opaque; VirtIONet *n = q->n; VirtIODevice *vdev = VIRTIO_DEVICE(n); - assert(vdev->vm_running); + /* This happens when device was stopped but BH wasn't. */ + if (!vdev->vm_running) { + /* Make sure tx waiting is set, so we'll run when restarted. */ + assert(q->tx_waiting); + return; + } q->tx_waiting = 0; @@ -1212,7 +1261,12 @@ static void virtio_net_tx_bh(void *opaque) VirtIODevice *vdev = VIRTIO_DEVICE(n); int32_t ret; - assert(vdev->vm_running); + /* This happens when device was stopped but BH wasn't. */ + if (!vdev->vm_running) { + /* Make sure tx waiting is set, so we'll run when restarted. */ + assert(q->tx_waiting); + return; + } q->tx_waiting = 0; @@ -1285,7 +1339,6 @@ static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue) static void virtio_net_save(QEMUFile *f, void *opaque) { - int i; VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); @@ -1293,6 +1346,12 @@ static void virtio_net_save(QEMUFile *f, void *opaque) * it might keep writing to memory. */ assert(!n->vhost_started); virtio_save(vdev, f); +} + +static void virtio_net_save_device(VirtIODevice *vdev, QEMUFile *f) +{ + VirtIONet *n = VIRTIO_NET(vdev); + int i; qemu_put_buffer(f, n->mac, ETH_ALEN); qemu_put_be32(f, n->vqs[0].tx_waiting); @@ -1328,15 +1387,18 @@ static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); - int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; - ret = virtio_load(vdev, f); - if (ret) { - return ret; - } + return virtio_load(vdev, f, version_id); +} + +static int virtio_net_load_device(VirtIODevice *vdev, QEMUFile *f, + int version_id) +{ + VirtIONet *n = VIRTIO_NET(vdev); + int i, link_down; qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); @@ -1362,10 +1424,17 @@ static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); - } else if (n->mac_table.in_use) { - uint8_t *buf = g_malloc0(n->mac_table.in_use); - qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); - g_free(buf); + } else { + int64_t i; + + /* Overflow detected - can happen if source has a larger MAC table. + * We simply set overflow flag so there's no need to maintain the + * table of addresses, discard them all. + * Note: 64 bit math to avoid integer overflow. + */ + for (i = 0; i < (int64_t)n->mac_table.in_use * ETH_ALEN; ++i) { + qemu_get_byte(f); + } n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } @@ -1407,6 +1476,11 @@ static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) } n->curr_queues = qemu_get_be16(f); + if (n->curr_queues > n->max_queues) { + error_report("virtio-net: curr_queues %x > max_queues %x", + n->curr_queues, n->max_queues); + return -1; + } for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } @@ -1439,6 +1513,12 @@ static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) qemu_get_subqueue(n->nic, i)->link_down = link_down; } + if (vdev->guest_features & (0x1 << VIRTIO_NET_F_GUEST_ANNOUNCE) && + vdev->guest_features & (0x1 << VIRTIO_NET_F_CTRL_VQ)) { + n->announce_counter = SELF_ANNOUNCE_ROUNDS; + timer_mod(n->announce_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL)); + } + return 0; } @@ -1464,7 +1544,7 @@ static bool virtio_net_guest_notifier_pending(VirtIODevice *vdev, int idx) VirtIONet *n = VIRTIO_NET(vdev); NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx)); assert(n->vhost_started); - return vhost_net_virtqueue_pending(tap_get_vhost_net(nc->peer), idx); + return vhost_net_virtqueue_pending(get_vhost_net(nc->peer), idx); } static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx, @@ -1473,7 +1553,7 @@ static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx, VirtIONet *n = VIRTIO_NET(vdev); NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx)); assert(n->vhost_started); - vhost_net_virtqueue_mask(tap_get_vhost_net(nc->peer), + vhost_net_virtqueue_mask(get_vhost_net(nc->peer), vdev, idx, mask); } @@ -1497,18 +1577,9 @@ void virtio_net_set_netclient_name(VirtIONet *n, const char *name, */ assert(type != NULL); - if (n->netclient_name) { - g_free(n->netclient_name); - n->netclient_name = NULL; - } - if (n->netclient_type) { - g_free(n->netclient_type); - n->netclient_type = NULL; - } - - if (name != NULL) { - n->netclient_name = g_strdup(name); - } + g_free(n->netclient_name); + g_free(n->netclient_type); + n->netclient_name = g_strdup(name); n->netclient_type = g_strdup(type); } @@ -1521,7 +1592,7 @@ static void virtio_net_device_realize(DeviceState *dev, Error **errp) virtio_init(vdev, "virtio-net", VIRTIO_ID_NET, n->config_size); - n->max_queues = MAX(n->nic_conf.queues, 1); + n->max_queues = MAX(n->nic_conf.peers.queues, 1); n->vqs = g_malloc0(sizeof(VirtIONetQueue) * n->max_queues); n->vqs[0].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx); n->curr_queues = 1; @@ -1550,6 +1621,8 @@ static void virtio_net_device_realize(DeviceState *dev, Error **errp) qemu_macaddr_default_if_unset(&n->nic_conf.macaddr); memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac)); n->status = VIRTIO_NET_S_LINK_UP; + n->announce_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, + virtio_net_announce_timer, n); if (n->netclient_type) { /* @@ -1589,8 +1662,6 @@ static void virtio_net_device_realize(DeviceState *dev, Error **errp) n->qdev = dev; register_savevm(dev, "virtio-net", -1, VIRTIO_NET_VM_VERSION, virtio_net_save, virtio_net_load, n); - - add_boot_device_path(n->nic_conf.bootindex, dev, "/ethernet-phy@0"); } static void virtio_net_device_unrealize(DeviceState *dev, Error **errp) @@ -1604,14 +1675,10 @@ static void virtio_net_device_unrealize(DeviceState *dev, Error **errp) unregister_savevm(dev, "virtio-net", n); - if (n->netclient_name) { - g_free(n->netclient_name); - n->netclient_name = NULL; - } - if (n->netclient_type) { - g_free(n->netclient_type); - n->netclient_type = NULL; - } + g_free(n->netclient_name); + n->netclient_name = NULL; + g_free(n->netclient_type); + n->netclient_type = NULL; g_free(n->mac_table.macs); g_free(n->vlans); @@ -1630,6 +1697,8 @@ static void virtio_net_device_unrealize(DeviceState *dev, Error **errp) } } + timer_del(n->announce_timer); + timer_free(n->announce_timer); g_free(n->vqs); qemu_del_nic(n->nic); virtio_cleanup(vdev); @@ -1644,6 +1713,9 @@ static void virtio_net_instance_init(Object *obj) * Can be overriden with virtio_net_set_config_size. */ n->config_size = sizeof(struct virtio_net_config); + device_add_bootindex_property(obj, &n->nic_conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(n), NULL); } static Property virtio_net_properties[] = { @@ -1673,6 +1745,8 @@ static void virtio_net_class_init(ObjectClass *klass, void *data) vdc->set_status = virtio_net_set_status; vdc->guest_notifier_mask = virtio_net_guest_notifier_mask; vdc->guest_notifier_pending = virtio_net_guest_notifier_pending; + vdc->load = virtio_net_load_device; + vdc->save = virtio_net_save_device; } static const TypeInfo virtio_net_info = { diff --git a/hw/net/vmxnet3.c b/hw/net/vmxnet3.c index ddcee4bd21..8eea58989b 100644 --- a/hw/net/vmxnet3.c +++ b/hw/net/vmxnet3.c @@ -34,6 +34,7 @@ #define PCI_DEVICE_ID_VMWARE_VMXNET3_REVISION 0x1 #define VMXNET3_MSIX_BAR_SIZE 0x2000 +#define MIN_BUF_SIZE 60 #define VMXNET3_BAR0_IDX (0) #define VMXNET3_BAR1_IDX (1) @@ -1009,7 +1010,7 @@ vmxnet3_indicate_packet(VMXNET3State *s) vmxnet3_dump_rx_descr(&rxd); - if (0 != ready_rxcd_pa) { + if (ready_rxcd_pa != 0) { cpu_physical_memory_write(ready_rxcd_pa, &rxcd, sizeof(rxcd)); } @@ -1020,7 +1021,7 @@ vmxnet3_indicate_packet(VMXNET3State *s) rxcd.gen = new_rxcd_gen; rxcd.rqID = RXQ_IDX + rx_ridx * s->rxq_num; - if (0 == bytes_left) { + if (bytes_left == 0) { vmxnet3_rx_update_descr(s->rx_pkt, &rxcd); } @@ -1038,16 +1039,16 @@ vmxnet3_indicate_packet(VMXNET3State *s) num_frags++; } - if (0 != ready_rxcd_pa) { + if (ready_rxcd_pa != 0) { rxcd.eop = 1; - rxcd.err = (0 != bytes_left); + rxcd.err = (bytes_left != 0); cpu_physical_memory_write(ready_rxcd_pa, &rxcd, sizeof(rxcd)); /* Flush RX descriptor changes */ smp_wmb(); } - if (0 != new_rxcd_pa) { + if (new_rxcd_pa != 0) { vmxnet3_revert_rxc_descr(s, RXQ_IDX); } @@ -1190,8 +1191,8 @@ static void vmxnet3_update_mcast_filters(VMXNET3State *s) s->mcast_list_len = list_bytes / sizeof(s->mcast_list[0]); s->mcast_list = g_realloc(s->mcast_list, list_bytes); - if (NULL == s->mcast_list) { - if (0 == s->mcast_list_len) { + if (!s->mcast_list) { + if (s->mcast_list_len == 0) { VMW_CFPRN("Current multicast list is empty"); } else { VMW_ERPRN("Failed to allocate multicast list of %d elements", @@ -1667,7 +1668,7 @@ vmxnet3_io_bar1_write(void *opaque, * memory address. We save it to temp variable and set the * shared address only after we get the high part */ - if (0 == val) { + if (val == 0) { s->device_active = false; } s->temp_shared_guest_driver_memory = val; @@ -1871,12 +1872,21 @@ vmxnet3_receive(NetClientState *nc, const uint8_t *buf, size_t size) { VMXNET3State *s = qemu_get_nic_opaque(nc); size_t bytes_indicated; + uint8_t min_buf[MIN_BUF_SIZE]; if (!vmxnet3_can_receive(nc)) { VMW_PKPRN("Cannot receive now"); return -1; } + /* Pad to minimum Ethernet frame length */ + if (size < sizeof(min_buf)) { + memcpy(min_buf, buf, size); + memset(&min_buf[size], 0, sizeof(min_buf) - size); + buf = min_buf; + size = sizeof(min_buf); + } + if (s->peer_has_vhdr) { vmxnet_rx_pkt_set_vhdr(s->rx_pkt, (struct virtio_net_hdr *)buf); buf += sizeof(struct virtio_net_hdr); @@ -2050,7 +2060,7 @@ vmxnet3_cleanup_msix(VMXNET3State *s) PCIDevice *d = PCI_DEVICE(s); if (s->msix_used) { - msix_vector_unuse(d, VMXNET3_MAX_INTRS); + vmxnet3_unuse_msix_vectors(s, VMXNET3_MAX_INTRS); msix_uninit(d, &s->msix_bar, &s->msix_bar); } } @@ -2162,11 +2172,16 @@ static int vmxnet3_pci_init(PCIDevice *pci_dev) register_savevm(dev, "vmxnet3-msix", -1, 1, vmxnet3_msix_save, vmxnet3_msix_load, s); - add_boot_device_path(s->conf.bootindex, dev, "/ethernet-phy@0"); - return 0; } +static void vmxnet3_instance_init(Object *obj) +{ + VMXNET3State *s = VMXNET3(obj); + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + DEVICE(obj), NULL); +} static void vmxnet3_pci_uninit(PCIDevice *pci_dev) { @@ -2182,10 +2197,6 @@ static void vmxnet3_pci_uninit(PCIDevice *pci_dev) vmxnet3_cleanup_msix(s); vmxnet3_cleanup_msi(s); - - memory_region_destroy(&s->bar0); - memory_region_destroy(&s->bar1); - memory_region_destroy(&s->msix_bar); } static void vmxnet3_qdev_reset(DeviceState *dev) @@ -2223,7 +2234,6 @@ static const VMStateDescription vmxstate_vmxnet3_mcast_list = { .name = "vmxnet3/mcast_list", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_load = vmxnet3_mcast_list_pre_load, .fields = (VMStateField[]) { VMSTATE_VBUFFER_UINT32(mcast_list, VMXNET3State, 0, NULL, 0, @@ -2305,7 +2315,7 @@ static void vmxnet3_put_txq_descr(QEMUFile *f, void *pv, size_t size) vmxnet3_put_tx_stats_to_file(f, &r->txq_stats); } -const VMStateInfo txq_descr_info = { +static const VMStateInfo txq_descr_info = { .name = "txq_descr", .get = vmxnet3_get_txq_descr, .put = vmxnet3_put_txq_descr @@ -2397,7 +2407,7 @@ static int vmxnet3_post_load(void *opaque, int version_id) return 0; } -const VMStateInfo rxq_descr_info = { +static const VMStateInfo rxq_descr_info = { .name = "rxq_descr", .get = vmxnet3_get_rxq_descr, .put = vmxnet3_put_rxq_descr @@ -2423,7 +2433,7 @@ static void vmxnet3_put_int_state(QEMUFile *f, void *pv, size_t size) qemu_put_byte(f, r->is_asserted); } -const VMStateInfo int_state_info = { +static const VMStateInfo int_state_info = { .name = "int_state", .get = vmxnet3_get_int_state, .put = vmxnet3_put_int_state @@ -2433,10 +2443,9 @@ static const VMStateDescription vmstate_vmxnet3 = { .name = "vmxnet3", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = vmxnet3_pre_save, .post_load = vmxnet3_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, VMXNET3State), VMSTATE_BOOL(rx_packets_compound, VMXNET3State), VMSTATE_BOOL(rx_vlan_stripping, VMXNET3State), @@ -2520,6 +2529,7 @@ static const TypeInfo vmxnet3_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(VMXNET3State), .class_init = vmxnet3_class_init, + .instance_init = vmxnet3_instance_init, }; static void vmxnet3_register_types(void) diff --git a/hw/net/xgmac.c b/hw/net/xgmac.c index 9384fa0c5c..aeffcb58b7 100644 --- a/hw/net/xgmac.c +++ b/hw/net/xgmac.c @@ -152,11 +152,11 @@ typedef struct XgmacState { uint32_t regs[R_MAX]; } XgmacState; -const VMStateDescription vmstate_rxtx_stats = { +static const VMStateDescription vmstate_rxtx_stats = { .name = "xgmac_stats", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT64(rx_bytes, RxTxStats), VMSTATE_UINT64(tx_bytes, RxTxStats), VMSTATE_UINT64(rx, RxTxStats), diff --git a/hw/net/xilinx_axienet.c b/hw/net/xilinx_axienet.c index 839d97ca86..cd952d2514 100644 --- a/hw/net/xilinx_axienet.c +++ b/hw/net/xilinx_axienet.c @@ -98,7 +98,7 @@ static unsigned int tdk_read(struct PHY *phy, unsigned int req) r |= 1; break; case 17: - /* Marvel PHY on many xilinx boards. */ + /* Marvell PHY on many xilinx boards. */ r = 0x8000; /* 1000Mb */ break; case 18: @@ -142,6 +142,9 @@ tdk_write(struct PHY *phy, unsigned int req, unsigned int data) phy->regs[regnum] = data; break; } + + /* Unconditionally clear regs[BMCR][BMCR_RESET] */ + phy->regs[0] &= ~0x8000; } static void @@ -942,24 +945,24 @@ static void xilinx_enet_realize(DeviceState *dev, Error **errp) XilinxAXIEnetStreamSlave *ds = XILINX_AXI_ENET_DATA_STREAM(&s->rx_data_dev); XilinxAXIEnetStreamSlave *cs = XILINX_AXI_ENET_CONTROL_STREAM( &s->rx_control_dev); - Error *local_errp = NULL; + Error *local_err = NULL; object_property_add_link(OBJECT(ds), "enet", "xlnx.axi-ethernet", (Object **) &ds->enet, object_property_allow_set_link, OBJ_PROP_LINK_UNREF_ON_RELEASE, - &local_errp); + &local_err); object_property_add_link(OBJECT(cs), "enet", "xlnx.axi-ethernet", (Object **) &cs->enet, object_property_allow_set_link, OBJ_PROP_LINK_UNREF_ON_RELEASE, - &local_errp); - if (local_errp) { + &local_err); + if (local_err) { goto xilinx_enet_realize_fail; } - object_property_set_link(OBJECT(ds), OBJECT(s), "enet", &local_errp); - object_property_set_link(OBJECT(cs), OBJECT(s), "enet", &local_errp); - if (local_errp) { + object_property_set_link(OBJECT(ds), OBJECT(s), "enet", &local_err); + object_property_set_link(OBJECT(cs), OBJECT(s), "enet", &local_err); + if (local_err) { goto xilinx_enet_realize_fail; } @@ -978,7 +981,7 @@ static void xilinx_enet_realize(DeviceState *dev, Error **errp) xilinx_enet_realize_fail: if (!*errp) { - *errp = local_errp; + *errp = local_err; } } diff --git a/hw/net/xilinx_ethlite.c b/hw/net/xilinx_ethlite.c index 3a2a6c21c9..1b177b3dae 100644 --- a/hw/net/xilinx_ethlite.c +++ b/hw/net/xilinx_ethlite.c @@ -196,14 +196,22 @@ static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size) memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size); s->regs[rxbase + R_RX_CTRL0] |= CTRL_S; - if (s->regs[rxbase + R_RX_CTRL0] & CTRL_I) + if (s->regs[R_RX_CTRL0] & CTRL_I) { eth_pulse_irq(s); + } /* If c_rx_pingpong was set flip buffers. */ s->rxbuf ^= s->c_rx_pingpong; return size; } +static void xilinx_ethlite_reset(DeviceState *dev) +{ + struct xlx_ethlite *s = XILINX_ETHLITE(dev); + + s->rxbuf = 0; +} + static void eth_cleanup(NetClientState *nc) { struct xlx_ethlite *s = qemu_get_nic_opaque(nc); @@ -219,23 +227,25 @@ static NetClientInfo net_xilinx_ethlite_info = { .cleanup = eth_cleanup, }; -static int xilinx_ethlite_init(SysBusDevice *sbd) +static void xilinx_ethlite_realize(DeviceState *dev, Error **errp) { - DeviceState *dev = DEVICE(sbd); struct xlx_ethlite *s = XILINX_ETHLITE(dev); - sysbus_init_irq(sbd, &s->irq); - s->rxbuf = 0; - - memory_region_init_io(&s->mmio, OBJECT(s), ð_ops, s, - "xlnx.xps-ethernetlite", R_MAX * 4); - sysbus_init_mmio(sbd, &s->mmio); - qemu_macaddr_default_if_unset(&s->conf.macaddr); s->nic = qemu_new_nic(&net_xilinx_ethlite_info, &s->conf, object_get_typename(OBJECT(dev)), dev->id, s); qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a); - return 0; +} + +static void xilinx_ethlite_init(Object *obj) +{ + struct xlx_ethlite *s = XILINX_ETHLITE(obj); + + sysbus_init_irq(SYS_BUS_DEVICE(obj), &s->irq); + + memory_region_init_io(&s->mmio, obj, ð_ops, s, + "xlnx.xps-ethernetlite", R_MAX * 4); + sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->mmio); } static Property xilinx_ethlite_properties[] = { @@ -248,9 +258,9 @@ static Property xilinx_ethlite_properties[] = { static void xilinx_ethlite_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); - k->init = xilinx_ethlite_init; + dc->realize = xilinx_ethlite_realize; + dc->reset = xilinx_ethlite_reset; dc->props = xilinx_ethlite_properties; } @@ -258,6 +268,7 @@ static const TypeInfo xilinx_ethlite_info = { .name = TYPE_XILINX_ETHLITE, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(struct xlx_ethlite), + .instance_init = xilinx_ethlite_init, .class_init = xilinx_ethlite_class_init, }; diff --git a/hw/nvram/ds1225y.c b/hw/nvram/ds1225y.c index f9a700b01c..332598b257 100644 --- a/hw/nvram/ds1225y.c +++ b/hw/nvram/ds1225y.c @@ -95,7 +95,6 @@ static const VMStateDescription vmstate_nvram = { .name = "nvram", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .post_load = nvram_post_load, .fields = (VMStateField[]) { VMSTATE_VARRAY_UINT32(contents, NvRamState, chip_size, 0, diff --git a/hw/nvram/eeprom93xx.c b/hw/nvram/eeprom93xx.c index a98f924b81..0af4d6707f 100644 --- a/hw/nvram/eeprom93xx.c +++ b/hw/nvram/eeprom93xx.c @@ -125,8 +125,7 @@ static const VMStateDescription vmstate_eeprom = { .name = "eeprom", .version_id = EEPROM_VERSION, .minimum_version_id = OLD_EEPROM_VERSION, - .minimum_version_id_old = OLD_EEPROM_VERSION, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(tick, eeprom_t), VMSTATE_UINT8(address, eeprom_t), VMSTATE_UINT8(command, eeprom_t), diff --git a/hw/nvram/fw_cfg.c b/hw/nvram/fw_cfg.c index 282341ac1b..a7122ee56b 100644 --- a/hw/nvram/fw_cfg.c +++ b/hw/nvram/fw_cfg.c @@ -377,8 +377,7 @@ static const VMStateDescription vmstate_fw_cfg = { .name = "fw_cfg", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(cur_entry, FWCfgState), VMSTATE_UINT16_HACK(cur_offset, FWCfgState, is_version_1), VMSTATE_UINT32_V(cur_offset, FWCfgState, 2), @@ -403,6 +402,26 @@ static void fw_cfg_add_bytes_read_callback(FWCfgState *s, uint16_t key, s->entries[arch][key].callback_opaque = callback_opaque; } +static void *fw_cfg_modify_bytes_read(FWCfgState *s, uint16_t key, + void *data, size_t len) +{ + void *ptr; + int arch = !!(key & FW_CFG_ARCH_LOCAL); + + key &= FW_CFG_ENTRY_MASK; + + assert(key < FW_CFG_MAX_ENTRY && len < UINT32_MAX); + + /* return the old data to the function caller, avoid memory leak */ + ptr = s->entries[arch][key].data; + s->entries[arch][key].data = data; + s->entries[arch][key].len = len; + s->entries[arch][key].callback_opaque = NULL; + s->entries[arch][key].callback = NULL; + + return ptr; +} + void fw_cfg_add_bytes(FWCfgState *s, uint16_t key, void *data, size_t len) { fw_cfg_add_bytes_read_callback(s, key, NULL, NULL, data, len); @@ -500,13 +519,45 @@ void fw_cfg_add_file(FWCfgState *s, const char *filename, fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len); } -static void fw_cfg_machine_ready(struct Notifier *n, void *data) +void *fw_cfg_modify_file(FWCfgState *s, const char *filename, + void *data, size_t len) +{ + int i, index; + void *ptr = NULL; + + assert(s->files); + + index = be32_to_cpu(s->files->count); + assert(index < FW_CFG_FILE_SLOTS); + + for (i = 0; i < index; i++) { + if (strcmp(filename, s->files->f[i].name) == 0) { + ptr = fw_cfg_modify_bytes_read(s, FW_CFG_FILE_FIRST + i, + data, len); + s->files->f[i].size = cpu_to_be32(len); + return ptr; + } + } + /* add new one */ + fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len); + return NULL; +} + +static void fw_cfg_machine_reset(void *opaque) { + void *ptr; size_t len; - FWCfgState *s = container_of(n, FWCfgState, machine_ready); + FWCfgState *s = opaque; char *bootindex = get_boot_devices_list(&len, false); - fw_cfg_add_file(s, "bootorder", (uint8_t*)bootindex, len); + ptr = fw_cfg_modify_file(s, "bootorder", (uint8_t *)bootindex, len); + g_free(ptr); +} + +static void fw_cfg_machine_ready(struct Notifier *n, void *data) +{ + FWCfgState *s = container_of(n, FWCfgState, machine_ready); + qemu_register_reset(fw_cfg_machine_reset, s); } FWCfgState *fw_cfg_init(uint32_t ctl_port, uint32_t data_port, diff --git a/hw/nvram/mac_nvram.c b/hw/nvram/mac_nvram.c index 2eb008179a..d35f8a3121 100644 --- a/hw/nvram/mac_nvram.c +++ b/hw/nvram/mac_nvram.c @@ -26,6 +26,7 @@ #include "hw/nvram/openbios_firmware_abi.h" #include "sysemu/sysemu.h" #include "hw/ppc/mac.h" +#include <zlib.h> /* debug NVR */ //#define DEBUG_NVR @@ -39,29 +40,6 @@ #define DEF_SYSTEM_SIZE 0xc10 -/* Direct access to NVRAM */ -uint8_t macio_nvram_read(MacIONVRAMState *s, uint32_t addr) -{ - uint32_t ret; - - if (addr < s->size) { - ret = s->data[addr]; - } else { - ret = -1; - } - NVR_DPRINTF("read addr %04" PRIx32 " val %" PRIx8 "\n", addr, ret); - - return ret; -} - -void macio_nvram_write(MacIONVRAMState *s, uint32_t addr, uint8_t val) -{ - NVR_DPRINTF("write addr %04" PRIx32 " val %" PRIx8 "\n", addr, val); - if (addr < s->size) { - s->data[addr] = val; - } -} - /* macio style NVRAM device */ static void macio_nvram_writeb(void *opaque, hwaddr addr, uint64_t value, unsigned size) @@ -89,6 +67,10 @@ static uint64_t macio_nvram_readb(void *opaque, hwaddr addr, static const MemoryRegionOps macio_nvram_ops = { .read = macio_nvram_readb, .write = macio_nvram_writeb, + .valid.min_access_size = 1, + .valid.max_access_size = 4, + .impl.min_access_size = 1, + .impl.max_access_size = 1, .endianness = DEVICE_BIG_ENDIAN, }; @@ -96,8 +78,7 @@ static const VMStateDescription vmstate_macio_nvram = { .name = "macio_nvram", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_VBUFFER_UINT32(data, MacIONVRAMState, 0, NULL, 0, size), VMSTATE_END_OF_LIST() } @@ -157,15 +138,16 @@ static void macio_nvram_register_types(void) } /* Set up a system OpenBIOS NVRAM partition */ -void pmac_format_nvram_partition (MacIONVRAMState *nvr, int len) +static void pmac_format_nvram_partition_of(MacIONVRAMState *nvr, int off, + int len) { unsigned int i; - uint32_t start = 0, end; + uint32_t start = off, end; struct OpenBIOS_nvpart_v1 *part_header; // OpenBIOS nvram variables // Variable partition - part_header = (struct OpenBIOS_nvpart_v1 *)nvr->data; + part_header = (struct OpenBIOS_nvpart_v1 *)&nvr->data[start]; part_header->signature = OPENBIOS_PART_SYSTEM; pstrcpy(part_header->name, sizeof(part_header->name), "system"); @@ -193,4 +175,39 @@ void pmac_format_nvram_partition (MacIONVRAMState *nvr, int len) OpenBIOS_finish_partition(part_header, end - start); } +#define OSX_NVRAM_SIGNATURE (0x5A) + +/* Set up a Mac OS X NVRAM partition */ +static void pmac_format_nvram_partition_osx(MacIONVRAMState *nvr, int off, + int len) +{ + uint32_t start = off; + struct OpenBIOS_nvpart_v1 *part_header; + unsigned char *data = &nvr->data[start]; + + /* empty partition */ + part_header = (struct OpenBIOS_nvpart_v1 *)data; + part_header->signature = OSX_NVRAM_SIGNATURE; + pstrcpy(part_header->name, sizeof(part_header->name), "wwwwwwwwwwww"); + + OpenBIOS_finish_partition(part_header, len); + + /* Generation */ + stl_be_p(&data[20], 2); + + /* Adler32 checksum */ + stl_be_p(&data[16], adler32(0, &data[20], len - 20)); +} + +/* Set up NVRAM with OF and OSX partitions */ +void pmac_format_nvram_partition(MacIONVRAMState *nvr, int len) +{ + /* + * Mac OS X expects side "B" of the flash at the second half of NVRAM, + * so we use half of the chip for OF and the other half for a free OSX + * partition. + */ + pmac_format_nvram_partition_of(nvr, 0, len / 2); + pmac_format_nvram_partition_osx(nvr, len / 2, len / 2); +} type_init(macio_nvram_register_types) diff --git a/hw/nvram/spapr_nvram.c b/hw/nvram/spapr_nvram.c index 635713e766..35dc6d5684 100644 --- a/hw/nvram/spapr_nvram.c +++ b/hw/nvram/spapr_nvram.c @@ -24,6 +24,7 @@ #include <libfdt.h> +#include "sysemu/block-backend.h" #include "sysemu/device_tree.h" #include "hw/sysbus.h" #include "hw/ppc/spapr.h" @@ -33,7 +34,7 @@ typedef struct sPAPRNVRAM { VIOsPAPRDevice sdev; uint32_t size; uint8_t *buf; - BlockDriverState *drive; + BlockBackend *blk; } sPAPRNVRAM; #define TYPE_VIO_SPAPR_NVRAM "spapr-nvram" @@ -42,7 +43,7 @@ typedef struct sPAPRNVRAM { #define MIN_NVRAM_SIZE 8192 #define DEFAULT_NVRAM_SIZE 65536 -#define MAX_NVRAM_SIZE (UINT16_MAX * 16) +#define MAX_NVRAM_SIZE 1048576 static void rtas_nvram_fetch(PowerPCCPU *cpu, sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, @@ -51,7 +52,6 @@ static void rtas_nvram_fetch(PowerPCCPU *cpu, sPAPREnvironment *spapr, { sPAPRNVRAM *nvram = spapr->nvram; hwaddr offset, buffer, len; - int alen; void *membuf; if ((nargs != 3) || (nret != 2)) { @@ -76,19 +76,14 @@ static void rtas_nvram_fetch(PowerPCCPU *cpu, sPAPREnvironment *spapr, return; } - membuf = cpu_physical_memory_map(buffer, &len, 1); - if (nvram->drive) { - alen = bdrv_pread(nvram->drive, offset, membuf, len); - } else { - assert(nvram->buf); + assert(nvram->buf); - memcpy(membuf, nvram->buf + offset, len); - alen = len; - } + membuf = cpu_physical_memory_map(buffer, &len, 1); + memcpy(membuf, nvram->buf + offset, len); cpu_physical_memory_unmap(membuf, len, 1, len); - rtas_st(rets, 0, (alen < len) ? RTAS_OUT_HW_ERROR : RTAS_OUT_SUCCESS); - rtas_st(rets, 1, (alen < 0) ? 0 : alen); + rtas_st(rets, 0, RTAS_OUT_SUCCESS); + rtas_st(rets, 1, len); } static void rtas_nvram_store(PowerPCCPU *cpu, sPAPREnvironment *spapr, @@ -122,14 +117,15 @@ static void rtas_nvram_store(PowerPCCPU *cpu, sPAPREnvironment *spapr, } membuf = cpu_physical_memory_map(buffer, &len, 0); - if (nvram->drive) { - alen = bdrv_pwrite(nvram->drive, offset, membuf, len); - } else { - assert(nvram->buf); - memcpy(nvram->buf + offset, membuf, len); - alen = len; + alen = len; + if (nvram->blk) { + alen = blk_pwrite(nvram->blk, offset, membuf, len); } + + assert(nvram->buf); + memcpy(nvram->buf + offset, membuf, len); + cpu_physical_memory_unmap(membuf, len, 0, len); rtas_st(rets, 0, (alen < len) ? RTAS_OUT_HW_ERROR : RTAS_OUT_SUCCESS); @@ -140,21 +136,30 @@ static int spapr_nvram_init(VIOsPAPRDevice *dev) { sPAPRNVRAM *nvram = VIO_SPAPR_NVRAM(dev); - if (nvram->drive) { - nvram->size = bdrv_getlength(nvram->drive); + if (nvram->blk) { + nvram->size = blk_getlength(nvram->blk); } else { nvram->size = DEFAULT_NVRAM_SIZE; - nvram->buf = g_malloc0(nvram->size); } + nvram->buf = g_malloc0(nvram->size); + if ((nvram->size < MIN_NVRAM_SIZE) || (nvram->size > MAX_NVRAM_SIZE)) { fprintf(stderr, "spapr-nvram must be between %d and %d bytes in size\n", MIN_NVRAM_SIZE, MAX_NVRAM_SIZE); return -1; } - spapr_rtas_register("nvram-fetch", rtas_nvram_fetch); - spapr_rtas_register("nvram-store", rtas_nvram_store); + if (nvram->blk) { + int alen = blk_pread(nvram->blk, 0, nvram->buf, nvram->size); + + if (alen != nvram->size) { + return -1; + } + } + + spapr_rtas_register(RTAS_NVRAM_FETCH, "nvram-fetch", rtas_nvram_fetch); + spapr_rtas_register(RTAS_NVRAM_STORE, "nvram-store", rtas_nvram_store); return 0; } @@ -166,9 +171,51 @@ static int spapr_nvram_devnode(VIOsPAPRDevice *dev, void *fdt, int node_off) return fdt_setprop_cell(fdt, node_off, "#bytes", nvram->size); } +static int spapr_nvram_pre_load(void *opaque) +{ + sPAPRNVRAM *nvram = VIO_SPAPR_NVRAM(opaque); + + g_free(nvram->buf); + nvram->buf = NULL; + nvram->size = 0; + + return 0; +} + +static int spapr_nvram_post_load(void *opaque, int version_id) +{ + sPAPRNVRAM *nvram = VIO_SPAPR_NVRAM(opaque); + + if (nvram->blk) { + int alen = blk_pwrite(nvram->blk, 0, nvram->buf, nvram->size); + + if (alen < 0) { + return alen; + } + if (alen != nvram->size) { + return -1; + } + } + + return 0; +} + +static const VMStateDescription vmstate_spapr_nvram = { + .name = "spapr_nvram", + .version_id = 1, + .minimum_version_id = 1, + .pre_load = spapr_nvram_pre_load, + .post_load = spapr_nvram_post_load, + .fields = (VMStateField[]) { + VMSTATE_UINT32(size, sPAPRNVRAM), + VMSTATE_VBUFFER_ALLOC_UINT32(buf, sPAPRNVRAM, 1, NULL, 0, size), + VMSTATE_END_OF_LIST() + }, +}; + static Property spapr_nvram_properties[] = { DEFINE_SPAPR_PROPERTIES(sPAPRNVRAM, sdev), - DEFINE_PROP_DRIVE("drive", sPAPRNVRAM, drive), + DEFINE_PROP_DRIVE("drive", sPAPRNVRAM, blk), DEFINE_PROP_END_OF_LIST(), }; @@ -184,6 +231,7 @@ static void spapr_nvram_class_init(ObjectClass *klass, void *data) k->dt_compatible = "qemu,spapr-nvram"; set_bit(DEVICE_CATEGORY_MISC, dc->categories); dc->props = spapr_nvram_properties; + dc->vmsd = &vmstate_spapr_nvram; } static const TypeInfo spapr_nvram_type_info = { diff --git a/hw/openrisc/openrisc_sim.c b/hw/openrisc/openrisc_sim.c index 8e1af8bf2e..1da0657ddf 100644 --- a/hw/openrisc/openrisc_sim.c +++ b/hw/openrisc/openrisc_sim.c @@ -72,7 +72,7 @@ static void cpu_openrisc_load_kernel(ram_addr_t ram_size, entry = elf_entry; if (kernel_size < 0) { kernel_size = load_uimage(kernel_filename, - &entry, NULL, NULL); + &entry, NULL, NULL, NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, @@ -90,11 +90,11 @@ static void cpu_openrisc_load_kernel(ram_addr_t ram_size, } } -static void openrisc_sim_init(QEMUMachineInitArgs *args) +static void openrisc_sim_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; OpenRISCCPU *cpu = NULL; MemoryRegion *ram; int n; @@ -114,7 +114,7 @@ static void openrisc_sim_init(QEMUMachineInitArgs *args) } ram = g_malloc(sizeof(*ram)); - memory_region_init_ram(ram, NULL, "openrisc.ram", ram_size); + memory_region_init_ram(ram, NULL, "openrisc.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(get_system_memory(), 0, ram); diff --git a/hw/pci-bridge/ioh3420.c b/hw/pci-bridge/ioh3420.c index 0f7f2092a7..cce2fdd8e7 100644 --- a/hw/pci-bridge/ioh3420.c +++ b/hw/pci-bridge/ioh3420.c @@ -85,6 +85,7 @@ static void ioh3420_reset(DeviceState *qdev) pcie_cap_root_reset(d); pcie_cap_deverr_reset(d); pcie_cap_slot_reset(d); + pcie_cap_arifwd_reset(d); pcie_aer_root_reset(d); pci_bridge_reset(qdev); pci_bridge_disable_base_limit(d); @@ -118,6 +119,8 @@ static int ioh3420_initfn(PCIDevice *d) if (rc < 0) { goto err_msi; } + + pcie_cap_arifwd_init(d); pcie_cap_deverr_init(d); pcie_cap_slot_init(d, s->slot); pcie_chassis_create(s->chassis); @@ -156,35 +159,16 @@ static void ioh3420_exitfn(PCIDevice *d) pci_bridge_exitfn(d); } -PCIESlot *ioh3420_init(PCIBus *bus, int devfn, bool multifunction, - const char *bus_name, pci_map_irq_fn map_irq, - uint8_t port, uint8_t chassis, uint16_t slot) -{ - PCIDevice *d; - PCIBridge *br; - DeviceState *qdev; - - d = pci_create_multifunction(bus, devfn, multifunction, "ioh3420"); - if (!d) { - return NULL; - } - br = PCI_BRIDGE(d); - - qdev = DEVICE(d); - pci_bridge_map_irq(br, bus_name, map_irq); - qdev_prop_set_uint8(qdev, "port", port); - qdev_prop_set_uint8(qdev, "chassis", chassis); - qdev_prop_set_uint16(qdev, "slot", slot); - qdev_init_nofail(qdev); - - return PCIE_SLOT(d); -} +static Property ioh3420_props[] = { + DEFINE_PROP_BIT(COMPAT_PROP_PCP, PCIDevice, cap_present, + QEMU_PCIE_SLTCAP_PCP_BITNR, true), + DEFINE_PROP_END_OF_LIST() +}; static const VMStateDescription vmstate_ioh3420 = { .name = "ioh-3240-express-root-port", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = pcie_cap_slot_post_load, .fields = (VMStateField[]) { VMSTATE_PCIE_DEVICE(parent_obj.parent_obj.parent_obj, PCIESlot), @@ -211,6 +195,7 @@ static void ioh3420_class_init(ObjectClass *klass, void *data) dc->desc = "Intel IOH device id 3420 PCIE Root Port"; dc->reset = ioh3420_reset; dc->vmsd = &vmstate_ioh3420; + dc->props = ioh3420_props; } static const TypeInfo ioh3420_info = { diff --git a/hw/pci-bridge/ioh3420.h b/hw/pci-bridge/ioh3420.h index 7776e5b02d..ea423cb991 100644 --- a/hw/pci-bridge/ioh3420.h +++ b/hw/pci-bridge/ioh3420.h @@ -3,8 +3,4 @@ #include "hw/pci/pcie_port.h" -PCIESlot *ioh3420_init(PCIBus *bus, int devfn, bool multifunction, - const char *bus_name, pci_map_irq_fn map_irq, - uint8_t port, uint8_t chassis, uint16_t slot); - #endif /* QEMU_IOH3420_H */ diff --git a/hw/pci-bridge/pci_bridge_dev.c b/hw/pci-bridge/pci_bridge_dev.c index e68145c52f..252ea5eb53 100644 --- a/hw/pci-bridge/pci_bridge_dev.c +++ b/hw/pci-bridge/pci_bridge_dev.c @@ -81,7 +81,6 @@ msi_error: slotid_error: shpc_cleanup(dev, &bridge_dev->bar); shpc_error: - memory_region_destroy(&bridge_dev->bar); pci_bridge_exitfn(dev); bridge_error: return err; @@ -95,7 +94,6 @@ static void pci_bridge_dev_exitfn(PCIDevice *dev) } slotid_cap_cleanup(dev); shpc_cleanup(dev, &bridge_dev->bar); - memory_region_destroy(&bridge_dev->bar); pci_bridge_exitfn(dev); } @@ -152,7 +150,7 @@ static void pci_bridge_dev_class_init(ObjectClass *klass, void *data) dc->vmsd = &pci_bridge_dev_vmstate; set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); hc->plug = shpc_device_hotplug_cb; - hc->unplug = shpc_device_hot_unplug_cb; + hc->unplug_request = shpc_device_hot_unplug_request_cb; } static const TypeInfo pci_bridge_dev_info = { diff --git a/hw/pci-bridge/xio3130_downstream.c b/hw/pci-bridge/xio3130_downstream.c index 94f97819cf..b3a6479262 100644 --- a/hw/pci-bridge/xio3130_downstream.c +++ b/hw/pci-bridge/xio3130_downstream.c @@ -50,7 +50,7 @@ static void xio3130_downstream_reset(DeviceState *qdev) pcie_cap_deverr_reset(d); pcie_cap_slot_reset(d); - pcie_cap_ari_reset(d); + pcie_cap_arifwd_reset(d); pci_bridge_reset(qdev); } @@ -91,7 +91,7 @@ static int xio3130_downstream_initfn(PCIDevice *d) if (rc < 0) { goto err_pcie_cap; } - pcie_cap_ari_init(d); + pcie_cap_arifwd_init(d); rc = pcie_aer_init(d, XIO3130_AER_OFFSET); if (rc < 0) { goto err; @@ -147,11 +147,16 @@ PCIESlot *xio3130_downstream_init(PCIBus *bus, int devfn, bool multifunction, return PCIE_SLOT(d); } +static Property xio3130_downstream_props[] = { + DEFINE_PROP_BIT(COMPAT_PROP_PCP, PCIDevice, cap_present, + QEMU_PCIE_SLTCAP_PCP_BITNR, true), + DEFINE_PROP_END_OF_LIST() +}; + static const VMStateDescription vmstate_xio3130_downstream = { .name = "xio3130-express-downstream-port", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = pcie_cap_slot_post_load, .fields = (VMStateField[]) { VMSTATE_PCIE_DEVICE(parent_obj.parent_obj.parent_obj, PCIESlot), @@ -178,6 +183,7 @@ static void xio3130_downstream_class_init(ObjectClass *klass, void *data) dc->desc = "TI X3130 Downstream Port of PCI Express Switch"; dc->reset = xio3130_downstream_reset; dc->vmsd = &vmstate_xio3130_downstream; + dc->props = xio3130_downstream_props; } static const TypeInfo xio3130_downstream_info = { diff --git a/hw/pci-bridge/xio3130_upstream.c b/hw/pci-bridge/xio3130_upstream.c index 59f97f6ff1..eada5828af 100644 --- a/hw/pci-bridge/xio3130_upstream.c +++ b/hw/pci-bridge/xio3130_upstream.c @@ -131,7 +131,6 @@ static const VMStateDescription vmstate_xio3130_upstream = { .name = "xio3130-express-upstream-port", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_PCIE_DEVICE(parent_obj.parent_obj, PCIEPort), VMSTATE_STRUCT(parent_obj.parent_obj.exp.aer_log, PCIEPort, 0, diff --git a/hw/pci-host/apb.c b/hw/pci-host/apb.c index 252caefda7..f573875baf 100644 --- a/hw/pci-host/apb.c +++ b/hw/pci-host/apb.c @@ -46,6 +46,16 @@ do { printf("APB: " fmt , ## __VA_ARGS__); } while (0) #define APB_DPRINTF(fmt, ...) #endif +/* debug IOMMU */ +//#define DEBUG_IOMMU + +#ifdef DEBUG_IOMMU +#define IOMMU_DPRINTF(fmt, ...) \ +do { printf("IOMMU: " fmt , ## __VA_ARGS__); } while (0) +#else +#define IOMMU_DPRINTF(fmt, ...) +#endif + /* * Chipset docs: * PBM: "UltraSPARC IIi User's Manual", @@ -70,6 +80,52 @@ do { printf("APB: " fmt , ## __VA_ARGS__); } while (0) #define MAX_IVEC 0x40 #define NO_IRQ_REQUEST (MAX_IVEC + 1) +#define IOMMU_PAGE_SIZE_8K (1ULL << 13) +#define IOMMU_PAGE_MASK_8K (~(IOMMU_PAGE_SIZE_8K - 1)) +#define IOMMU_PAGE_SIZE_64K (1ULL << 16) +#define IOMMU_PAGE_MASK_64K (~(IOMMU_PAGE_SIZE_64K - 1)) + +#define IOMMU_NREGS 3 + +#define IOMMU_CTRL 0x0 +#define IOMMU_CTRL_TBW_SIZE (1ULL << 2) +#define IOMMU_CTRL_MMU_EN (1ULL) + +#define IOMMU_CTRL_TSB_SHIFT 16 + +#define IOMMU_BASE 0x8 +#define IOMMU_FLUSH 0x10 + +#define IOMMU_TTE_DATA_V (1ULL << 63) +#define IOMMU_TTE_DATA_SIZE (1ULL << 61) +#define IOMMU_TTE_DATA_W (1ULL << 1) + +#define IOMMU_TTE_PHYS_MASK_8K 0x1ffffffe000ULL +#define IOMMU_TTE_PHYS_MASK_64K 0x1ffffff8000ULL + +#define IOMMU_TSB_8K_OFFSET_MASK_8M 0x00000000007fe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_16M 0x0000000000ffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_32M 0x0000000001ffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_64M 0x0000000003ffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_128M 0x0000000007ffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_256M 0x000000000fffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_512M 0x000000001fffe000ULL +#define IOMMU_TSB_8K_OFFSET_MASK_1G 0x000000003fffe000ULL + +#define IOMMU_TSB_64K_OFFSET_MASK_64M 0x0000000003ff0000ULL +#define IOMMU_TSB_64K_OFFSET_MASK_128M 0x0000000007ff0000ULL +#define IOMMU_TSB_64K_OFFSET_MASK_256M 0x000000000fff0000ULL +#define IOMMU_TSB_64K_OFFSET_MASK_512M 0x000000001fff0000ULL +#define IOMMU_TSB_64K_OFFSET_MASK_1G 0x000000003fff0000ULL +#define IOMMU_TSB_64K_OFFSET_MASK_2G 0x000000007fff0000ULL + +typedef struct IOMMUState { + AddressSpace iommu_as; + MemoryRegion iommu; + + uint64_t regs[IOMMU_NREGS]; +} IOMMUState; + #define TYPE_APB "pbm" #define APB_DEVICE(obj) \ @@ -83,9 +139,10 @@ typedef struct APBState { MemoryRegion pci_mmio; MemoryRegion pci_ioport; uint64_t pci_irq_in; - uint32_t iommu[4]; + IOMMUState iommu; uint32_t pci_control[16]; uint32_t pci_irq_map[8]; + uint32_t pci_err_irq_map[4]; uint32_t obio_irq_map[32]; qemu_irq *pbm_irqs; qemu_irq *ivec_irqs; @@ -141,10 +198,225 @@ static inline void pbm_clear_request(APBState *s, unsigned int irq_num) s->irq_request = NO_IRQ_REQUEST; } +static AddressSpace *pbm_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn) +{ + IOMMUState *is = opaque; + + return &is->iommu_as; +} + +static IOMMUTLBEntry pbm_translate_iommu(MemoryRegion *iommu, hwaddr addr, + bool is_write) +{ + IOMMUState *is = container_of(iommu, IOMMUState, iommu); + hwaddr baseaddr, offset; + uint64_t tte; + uint32_t tsbsize; + IOMMUTLBEntry ret = { + .target_as = &address_space_memory, + .iova = 0, + .translated_addr = 0, + .addr_mask = ~(hwaddr)0, + .perm = IOMMU_NONE, + }; + + if (!(is->regs[IOMMU_CTRL >> 3] & IOMMU_CTRL_MMU_EN)) { + /* IOMMU disabled, passthrough using standard 8K page */ + ret.iova = addr & IOMMU_PAGE_MASK_8K; + ret.translated_addr = addr; + ret.addr_mask = IOMMU_PAGE_MASK_8K; + ret.perm = IOMMU_RW; + + return ret; + } + + baseaddr = is->regs[IOMMU_BASE >> 3]; + tsbsize = (is->regs[IOMMU_CTRL >> 3] >> IOMMU_CTRL_TSB_SHIFT) & 0x7; + + if (is->regs[IOMMU_CTRL >> 3] & IOMMU_CTRL_TBW_SIZE) { + /* 64K */ + switch (tsbsize) { + case 0: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_64M) >> 13; + break; + case 1: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_128M) >> 13; + break; + case 2: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_256M) >> 13; + break; + case 3: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_512M) >> 13; + break; + case 4: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_1G) >> 13; + break; + case 5: + offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_2G) >> 13; + break; + default: + /* Not implemented, error */ + return ret; + } + } else { + /* 8K */ + switch (tsbsize) { + case 0: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_8M) >> 10; + break; + case 1: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_16M) >> 10; + break; + case 2: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_32M) >> 10; + break; + case 3: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_64M) >> 10; + break; + case 4: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_128M) >> 10; + break; + case 5: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_256M) >> 10; + break; + case 6: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_512M) >> 10; + break; + case 7: + offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_1G) >> 10; + break; + } + } + + tte = ldq_be_phys(&address_space_memory, baseaddr + offset); + + if (!(tte & IOMMU_TTE_DATA_V)) { + /* Invalid mapping */ + return ret; + } + + if (tte & IOMMU_TTE_DATA_W) { + /* Writeable */ + ret.perm = IOMMU_RW; + } else { + ret.perm = IOMMU_RO; + } + + /* Extract phys */ + if (tte & IOMMU_TTE_DATA_SIZE) { + /* 64K */ + ret.iova = addr & IOMMU_PAGE_MASK_64K; + ret.translated_addr = tte & IOMMU_TTE_PHYS_MASK_64K; + ret.addr_mask = (IOMMU_PAGE_SIZE_64K - 1); + } else { + /* 8K */ + ret.iova = addr & IOMMU_PAGE_MASK_8K; + ret.translated_addr = tte & IOMMU_TTE_PHYS_MASK_8K; + ret.addr_mask = (IOMMU_PAGE_SIZE_8K - 1); + } + + return ret; +} + +static MemoryRegionIOMMUOps pbm_iommu_ops = { + .translate = pbm_translate_iommu, +}; + +static void iommu_config_write(void *opaque, hwaddr addr, + uint64_t val, unsigned size) +{ + IOMMUState *is = opaque; + + IOMMU_DPRINTF("IOMMU config write: 0x%" HWADDR_PRIx " val: %" PRIx64 + " size: %d\n", addr, val, size); + + switch (addr) { + case IOMMU_CTRL: + if (size == 4) { + is->regs[IOMMU_CTRL >> 3] &= 0xffffffffULL; + is->regs[IOMMU_CTRL >> 3] |= val << 32; + } else { + is->regs[IOMMU_CTRL >> 3] = val; + } + break; + case IOMMU_CTRL + 0x4: + is->regs[IOMMU_CTRL >> 3] &= 0xffffffff00000000ULL; + is->regs[IOMMU_CTRL >> 3] |= val & 0xffffffffULL; + break; + case IOMMU_BASE: + if (size == 4) { + is->regs[IOMMU_BASE >> 3] &= 0xffffffffULL; + is->regs[IOMMU_BASE >> 3] |= val << 32; + } else { + is->regs[IOMMU_BASE >> 3] = val; + } + break; + case IOMMU_BASE + 0x4: + is->regs[IOMMU_BASE >> 3] &= 0xffffffff00000000ULL; + is->regs[IOMMU_BASE >> 3] |= val & 0xffffffffULL; + break; + case IOMMU_FLUSH: + case IOMMU_FLUSH + 0x4: + break; + default: + qemu_log_mask(LOG_UNIMP, + "apb iommu: Unimplemented register write " + "reg 0x%" HWADDR_PRIx " size 0x%x value 0x%" PRIx64 "\n", + addr, size, val); + break; + } +} + +static uint64_t iommu_config_read(void *opaque, hwaddr addr, unsigned size) +{ + IOMMUState *is = opaque; + uint64_t val; + + switch (addr) { + case IOMMU_CTRL: + if (size == 4) { + val = is->regs[IOMMU_CTRL >> 3] >> 32; + } else { + val = is->regs[IOMMU_CTRL >> 3]; + } + break; + case IOMMU_CTRL + 0x4: + val = is->regs[IOMMU_CTRL >> 3] & 0xffffffffULL; + break; + case IOMMU_BASE: + if (size == 4) { + val = is->regs[IOMMU_BASE >> 3] >> 32; + } else { + val = is->regs[IOMMU_BASE >> 3]; + } + break; + case IOMMU_BASE + 0x4: + val = is->regs[IOMMU_BASE >> 3] & 0xffffffffULL; + break; + case IOMMU_FLUSH: + case IOMMU_FLUSH + 0x4: + val = 0; + break; + default: + qemu_log_mask(LOG_UNIMP, + "apb iommu: Unimplemented register read " + "reg 0x%" HWADDR_PRIx " size 0x%x\n", + addr, size); + val = 0; + break; + } + + IOMMU_DPRINTF("IOMMU config read: 0x%" HWADDR_PRIx " val: %" PRIx64 + " size: %d\n", addr, val, size); + + return val; +} + static void apb_config_writel (void *opaque, hwaddr addr, uint64_t val, unsigned size) { APBState *s = opaque; + IOMMUState *is = &s->iommu; APB_DPRINTF("%s: addr " TARGET_FMT_plx " val %" PRIx64 "\n", __func__, addr, val); @@ -152,10 +424,8 @@ static void apb_config_writel (void *opaque, hwaddr addr, case 0x30 ... 0x4f: /* DMA error registers */ /* XXX: not implemented yet */ break; - case 0x200 ... 0x20b: /* IOMMU */ - s->iommu[(addr & 0xf) >> 2] = val; - break; - case 0x20c ... 0x3ff: /* IOMMU flush */ + case 0x200 ... 0x217: /* IOMMU */ + iommu_config_write(is, (addr & 0x1f), val, size); break; case 0xc00 ... 0xc3f: /* PCI interrupt control */ if (addr & 4) { @@ -168,7 +438,7 @@ static void apb_config_writel (void *opaque, hwaddr addr, pbm_check_irqs(s); } break; - case 0x1000 ... 0x1080: /* OBIO interrupt control */ + case 0x1000 ... 0x107f: /* OBIO interrupt control */ if (addr & 4) { unsigned int ino = ((addr & 0xff) >> 3); s->obio_irq_map[ino] &= PBM_PCI_IMR_MASK; @@ -228,6 +498,7 @@ static uint64_t apb_config_readl (void *opaque, hwaddr addr, unsigned size) { APBState *s = opaque; + IOMMUState *is = &s->iommu; uint32_t val; switch (addr & 0xffff) { @@ -235,11 +506,8 @@ static uint64_t apb_config_readl (void *opaque, val = 0; /* XXX: not implemented yet */ break; - case 0x200 ... 0x20b: /* IOMMU */ - val = s->iommu[(addr & 0xf) >> 2]; - break; - case 0x20c ... 0x3ff: /* IOMMU flush */ - val = 0; + case 0x200 ... 0x217: /* IOMMU */ + val = iommu_config_read(is, (addr & 0x1f), size); break; case 0xc00 ... 0xc3f: /* PCI interrupt control */ if (addr & 4) { @@ -248,13 +516,20 @@ static uint64_t apb_config_readl (void *opaque, val = 0; } break; - case 0x1000 ... 0x1080: /* OBIO interrupt control */ + case 0x1000 ... 0x107f: /* OBIO interrupt control */ if (addr & 4) { val = s->obio_irq_map[(addr & 0xff) >> 3]; } else { val = 0; } break; + case 0x1080 ... 0x108f: /* PCI bus error */ + if (addr & 4) { + val = s->pci_err_irq_map[(addr & 0xf) >> 3]; + } else { + val = 0; + } + break; case 0x2000 ... 0x202f: /* PCI control */ val = s->pci_control[(addr & 0x3f) >> 2]; break; @@ -390,6 +665,7 @@ PCIBus *pci_apb_init(hwaddr special_base, SysBusDevice *s; PCIHostState *phb; APBState *d; + IOMMUState *is; PCIDevice *pci_dev; PCIBridge *br; @@ -420,6 +696,15 @@ PCIBus *pci_apb_init(hwaddr special_base, pci_create_simple(phb->bus, 0, "pbm-pci"); + /* APB IOMMU */ + is = &d->iommu; + memset(is, 0, sizeof(IOMMUState)); + + memory_region_init_iommu(&is->iommu, OBJECT(dev), &pbm_iommu_ops, + "iommu-apb", UINT64_MAX); + address_space_init(&is->iommu_as, &is->iommu, "pbm-as"); + pci_setup_iommu(phb->bus, pbm_pci_dma_iommu, is); + /* APB secondary busses */ pci_dev = pci_create_multifunction(phb->bus, PCI_DEVFN(1, 0), true, "pbm-bridge"); @@ -476,6 +761,9 @@ static int pci_pbm_init_device(SysBusDevice *dev) for (i = 0; i < 8; i++) { s->pci_irq_map[i] = (0x1f << 6) | (i << 2); } + for (i = 0; i < 2; i++) { + s->pci_err_irq_map[i] = (0x1f << 6) | 0x30; + } for (i = 0; i < 32; i++) { s->obio_irq_map[i] = ((0x1f << 6) | 0x20) + i; } diff --git a/hw/pci-host/bonito.c b/hw/pci-host/bonito.c index 902441f10b..56292adb03 100644 --- a/hw/pci-host/bonito.c +++ b/hw/pci-host/bonito.c @@ -687,8 +687,7 @@ static const VMStateDescription vmstate_bonito = { .name = "Bonito", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PCIBonitoState), VMSTATE_END_OF_LIST() } diff --git a/hw/pci-host/pam.c b/hw/pci-host/pam.c index e1e95aabcd..8272de3f28 100644 --- a/hw/pci-host/pam.c +++ b/hw/pci-host/pam.c @@ -1,12 +1,12 @@ /* - * QEMU i440FX/PIIX3 PCI Bridge Emulation + * QEMU Smram/pam logic implementation * * Copyright (c) 2006 Fabrice Bellard * Copyright (c) 2011 Isaku Yamahata <yamahata at valinux co jp> * VA Linux Systems Japan K.K. * Copyright (c) 2012 Jason Baron <jbaron@redhat.com> * - * Split out from piix_pci.c + * Split out from piix.c * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/hw/pci-host/piix.c b/hw/pci-host/piix.c index ffdc853a62..1530038cb0 100644 --- a/hw/pci-host/piix.c +++ b/hw/pci-host/piix.c @@ -203,7 +203,7 @@ static const VMStateDescription vmstate_i440fx = { .minimum_version_id_old = 1, .load_state_old = i440fx_load_old, .post_load = i440fx_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PCII440FXState), VMSTATE_UINT8(smm_enabled, PCII440FXState), VMSTATE_END_OF_LIST() @@ -409,7 +409,7 @@ static void piix3_set_irq_pic(PIIX3State *piix3, int pic_irq) (pic_irq * PIIX_NUM_PIRQS)))); } -static void piix3_set_irq_level(PIIX3State *piix3, int pirq, int level) +static void piix3_set_irq_level_internal(PIIX3State *piix3, int pirq, int level) { int pic_irq; uint64_t mask; @@ -422,6 +422,18 @@ static void piix3_set_irq_level(PIIX3State *piix3, int pirq, int level) mask = 1ULL << ((pic_irq * PIIX_NUM_PIRQS) + pirq); piix3->pic_levels &= ~mask; piix3->pic_levels |= mask * !!level; +} + +static void piix3_set_irq_level(PIIX3State *piix3, int pirq, int level) +{ + int pic_irq; + + pic_irq = piix3->dev.config[PIIX_PIRQC + pirq]; + if (pic_irq >= PIIX_NUM_PIC_IRQS) { + return; + } + + piix3_set_irq_level_internal(piix3, pirq, level); piix3_set_irq_pic(piix3, pic_irq); } @@ -527,7 +539,21 @@ static void piix3_reset(void *opaque) static int piix3_post_load(void *opaque, int version_id) { PIIX3State *piix3 = opaque; - piix3_update_irq_levels(piix3); + int pirq; + + /* Because the i8259 has not been deserialized yet, qemu_irq_raise + * might bring the system to a different state than the saved one; + * for example, the interrupt could be masked but the i8259 would + * not know that yet and would trigger an interrupt in the CPU. + * + * Here, we update irq levels without raising the interrupt. + * Interrupt state will be deserialized separately through the i8259. + */ + piix3->pic_levels = 0; + for (pirq = 0; pirq < PIIX_NUM_PIRQS; pirq++) { + piix3_set_irq_level_internal(piix3, pirq, + pci_bus_get_irq_level(piix3->dev.bus, pirq)); + } return 0; } @@ -553,7 +579,7 @@ static const VMStateDescription vmstate_piix3_rcr = { .name = "PIIX3/rcr", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(rcr, PIIX3State), VMSTATE_END_OF_LIST() } @@ -563,10 +589,9 @@ static const VMStateDescription vmstate_piix3 = { .name = "PIIX3", .version_id = 3, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = piix3_post_load, .pre_save = piix3_pre_save, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, PIIX3State), VMSTATE_INT32_ARRAY_V(pci_irq_levels_vmstate, PIIX3State, PIIX_NUM_PIRQS, 3), diff --git a/hw/pci-host/ppce500.c b/hw/pci-host/ppce500.c index c80b7cb2f5..1b4c0f0023 100644 --- a/hw/pci-host/ppce500.c +++ b/hw/pci-host/ppce500.c @@ -87,8 +87,10 @@ struct PPCE500PCIState { struct pci_outbound pob[PPCE500_PCI_NR_POBS]; struct pci_inbound pib[PPCE500_PCI_NR_PIBS]; uint32_t gasket_time; - qemu_irq irq[4]; + qemu_irq irq[PCI_NUM_PINS]; + uint32_t irq_num[PCI_NUM_PINS]; uint32_t first_slot; + uint32_t first_pin_irq; /* mmio maps */ MemoryRegion container; MemoryRegion iomem; @@ -252,34 +254,46 @@ static const MemoryRegionOps e500_pci_reg_ops = { .endianness = DEVICE_BIG_ENDIAN, }; -static int mpc85xx_pci_map_irq(PCIDevice *pci_dev, int irq_num) +static int mpc85xx_pci_map_irq(PCIDevice *pci_dev, int pin) { int devno = pci_dev->devfn >> 3; int ret; - ret = ppce500_pci_map_irq_slot(devno, irq_num); + ret = ppce500_pci_map_irq_slot(devno, pin); pci_debug("%s: devfn %x irq %d -> %d devno:%x\n", __func__, - pci_dev->devfn, irq_num, ret, devno); + pci_dev->devfn, pin, ret, devno); return ret; } -static void mpc85xx_pci_set_irq(void *opaque, int irq_num, int level) +static void mpc85xx_pci_set_irq(void *opaque, int pin, int level) { - qemu_irq *pic = opaque; + PPCE500PCIState *s = opaque; + qemu_irq *pic = s->irq; - pci_debug("%s: PCI irq %d, level:%d\n", __func__, irq_num, level); + pci_debug("%s: PCI irq %d, level:%d\n", __func__, pin , level); - qemu_set_irq(pic[irq_num], level); + qemu_set_irq(pic[pin], level); +} + +static PCIINTxRoute e500_route_intx_pin_to_irq(void *opaque, int pin) +{ + PCIINTxRoute route; + PPCE500PCIState *s = opaque; + + route.mode = PCI_INTX_ENABLED; + route.irq = s->irq_num[pin]; + + pci_debug("%s: PCI irq-pin = %d, irq_num= %d\n", __func__, pin, route.irq); + return route; } static const VMStateDescription vmstate_pci_outbound = { .name = "pci_outbound", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(potar, struct pci_outbound), VMSTATE_UINT32(potear, struct pci_outbound), VMSTATE_UINT32(powbar, struct pci_outbound), @@ -292,8 +306,7 @@ static const VMStateDescription vmstate_pci_inbound = { .name = "pci_inbound", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(pitar, struct pci_inbound), VMSTATE_UINT32(piwbar, struct pci_inbound), VMSTATE_UINT32(piwbear, struct pci_inbound), @@ -306,12 +319,11 @@ static const VMStateDescription vmstate_ppce500_pci = { .name = "ppce500_pci", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(pob, PPCE500PCIState, PPCE500_PCI_NR_POBS, 1, vmstate_pci_outbound, struct pci_outbound), VMSTATE_STRUCT_ARRAY(pib, PPCE500PCIState, PPCE500_PCI_NR_PIBS, 1, - vmstate_pci_outbound, struct pci_inbound), + vmstate_pci_inbound, struct pci_inbound), VMSTATE_UINT32(gasket_time, PPCE500PCIState), VMSTATE_END_OF_LIST() } @@ -352,10 +364,14 @@ static int e500_pcihost_initfn(SysBusDevice *dev) sysbus_init_irq(dev, &s->irq[i]); } + for (i = 0; i < PCI_NUM_PINS; i++) { + s->irq_num[i] = s->first_pin_irq + i; + } + memory_region_init(&s->pio, OBJECT(s), "pci-pio", PCIE500_PCI_IOLEN); b = pci_register_bus(DEVICE(dev), NULL, mpc85xx_pci_set_irq, - mpc85xx_pci_map_irq, s->irq, address_space_mem, + mpc85xx_pci_map_irq, s, address_space_mem, &s->pio, PCI_DEVFN(s->first_slot, 0), 4, TYPE_PCI_BUS); h->bus = b; @@ -373,6 +389,7 @@ static int e500_pcihost_initfn(SysBusDevice *dev) memory_region_add_subregion(&s->container, PCIE500_REG_BASE, &s->iomem); sysbus_init_mmio(dev, &s->container); sysbus_init_mmio(dev, &s->pio); + pci_bus_set_route_irq_fn(b, e500_route_intx_pin_to_irq); return 0; } @@ -403,6 +420,7 @@ static const TypeInfo e500_host_bridge_info = { static Property pcihost_properties[] = { DEFINE_PROP_UINT32("first_slot", PPCE500PCIState, first_slot, 0x11), + DEFINE_PROP_UINT32("first_pin_irq", PPCE500PCIState, first_pin_irq, 0x1), DEFINE_PROP_END_OF_LIST(), }; diff --git a/hw/pci-host/prep.c b/hw/pci-host/prep.c index 40145408ef..1de3681db9 100644 --- a/hw/pci-host/prep.c +++ b/hw/pci-host/prep.c @@ -256,9 +256,7 @@ static void raven_pcihost_initfn(Object *obj) memory_region_init(&s->pci_io, obj, "pci-io", 0x3f800000); memory_region_init_io(&s->pci_io_non_contiguous, obj, &raven_io_ops, s, "pci-io-non-contiguous", 0x00800000); - /* Open Hack'Ware hack: real size should be only 0x3f000000 bytes */ - memory_region_init(&s->pci_memory, obj, "pci-memory", - 0x3f000000 + 0xc0000000ULL); + memory_region_init(&s->pci_memory, obj, "pci-memory", 0x3f000000); address_space_init(&s->pci_io_as, &s->pci_io, "raven-io"); /* CPU address space */ @@ -301,7 +299,8 @@ static int raven_init(PCIDevice *d) d->config[0x0D] = 0x10; // latency_timer d->config[0x34] = 0x00; // capabilities_pointer - memory_region_init_ram(&s->bios, OBJECT(s), "bios", BIOS_SIZE); + memory_region_init_ram(&s->bios, OBJECT(s), "bios", BIOS_SIZE, + &error_abort); memory_region_set_readonly(&s->bios, true); memory_region_add_subregion(get_system_memory(), (uint32_t)(-BIOS_SIZE), &s->bios); diff --git a/hw/pci-host/q35.c b/hw/pci-host/q35.c index 8b8cc4e294..b20bad8373 100644 --- a/hw/pci-host/q35.c +++ b/hw/pci-host/q35.c @@ -7,7 +7,7 @@ * VA Linux Systems Japan K.K. * Copyright (C) 2012 Jason Baron <jbaron@redhat.com> * - * This is based on piix_pci.c, but heavily modified. + * This is based on piix.c, but heavily modified. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -47,10 +47,6 @@ static void q35_host_realize(DeviceState *dev, Error **errp) sysbus_add_io(sbd, MCH_HOST_BRIDGE_CONFIG_DATA, &pci->data_mem); sysbus_init_ioports(sbd, MCH_HOST_BRIDGE_CONFIG_DATA, 4); - if (pcie_host_init(PCIE_HOST_BRIDGE(s)) < 0) { - error_setg(errp, "failed to initialize pcie host"); - return; - } pci->bus = pci_bus_new(DEVICE(s), "pcie.0", s->mch.pci_address_space, s->mch.address_space_io, 0, TYPE_PCIE_BUS); @@ -330,9 +326,8 @@ static const VMStateDescription vmstate_mch = { .name = "mch", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = mch_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, MCHPCIState), VMSTATE_UINT8(smm_enabled, MCHPCIState), VMSTATE_END_OF_LIST() @@ -352,6 +347,49 @@ static void mch_reset(DeviceState *qdev) mch_update(mch); } +static AddressSpace *q35_host_dma_iommu(PCIBus *bus, void *opaque, int devfn) +{ + IntelIOMMUState *s = opaque; + VTDAddressSpace **pvtd_as; + int bus_num = pci_bus_num(bus); + + assert(0 <= bus_num && bus_num <= VTD_PCI_BUS_MAX); + assert(0 <= devfn && devfn <= VTD_PCI_DEVFN_MAX); + + pvtd_as = s->address_spaces[bus_num]; + if (!pvtd_as) { + /* No corresponding free() */ + pvtd_as = g_malloc0(sizeof(VTDAddressSpace *) * VTD_PCI_DEVFN_MAX); + s->address_spaces[bus_num] = pvtd_as; + } + if (!pvtd_as[devfn]) { + pvtd_as[devfn] = g_malloc0(sizeof(VTDAddressSpace)); + + pvtd_as[devfn]->bus_num = (uint8_t)bus_num; + pvtd_as[devfn]->devfn = (uint8_t)devfn; + pvtd_as[devfn]->iommu_state = s; + pvtd_as[devfn]->context_cache_entry.context_cache_gen = 0; + memory_region_init_iommu(&pvtd_as[devfn]->iommu, OBJECT(s), + &s->iommu_ops, "intel_iommu", UINT64_MAX); + address_space_init(&pvtd_as[devfn]->as, + &pvtd_as[devfn]->iommu, "intel_iommu"); + } + return &pvtd_as[devfn]->as; +} + +static void mch_init_dmar(MCHPCIState *mch) +{ + PCIBus *pci_bus = PCI_BUS(qdev_get_parent_bus(DEVICE(mch))); + + mch->iommu = INTEL_IOMMU_DEVICE(qdev_create(NULL, TYPE_INTEL_IOMMU_DEVICE)); + object_property_add_child(OBJECT(mch), "intel-iommu", + OBJECT(mch->iommu), NULL); + qdev_init_nofail(DEVICE(mch->iommu)); + sysbus_mmio_map(SYS_BUS_DEVICE(mch->iommu), 0, Q35_HOST_BRIDGE_IOMMU_ADDR); + + pci_setup_iommu(pci_bus, q35_host_dma_iommu, mch->iommu); +} + static int mch_init(PCIDevice *d) { int i; @@ -368,12 +406,17 @@ static int mch_init(PCIDevice *d) memory_region_add_subregion_overlap(mch->system_memory, 0xa0000, &mch->smram_region, 1); memory_region_set_enabled(&mch->smram_region, false); - init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, mch->pci_address_space, - &mch->pam_regions[0], PAM_BIOS_BASE, PAM_BIOS_SIZE); + init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, + mch->pci_address_space, &mch->pam_regions[0], + PAM_BIOS_BASE, PAM_BIOS_SIZE); for (i = 0; i < 12; ++i) { - init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, mch->pci_address_space, - &mch->pam_regions[i+1], PAM_EXPAN_BASE + i * PAM_EXPAN_SIZE, - PAM_EXPAN_SIZE); + init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, + mch->pci_address_space, &mch->pam_regions[i+1], + PAM_EXPAN_BASE + i * PAM_EXPAN_SIZE, PAM_EXPAN_SIZE); + } + /* Intel IOMMU (VT-d) */ + if (qemu_opt_get_bool(qemu_get_machine_opts(), "iommu", false)) { + mch_init_dmar(mch); } return 0; } diff --git a/hw/pci-host/uninorth.c b/hw/pci-host/uninorth.c index e72fe2a70b..21f805f314 100644 --- a/hw/pci-host/uninorth.c +++ b/hw/pci-host/uninorth.c @@ -230,7 +230,7 @@ PCIBus *pci_pmac_init(qemu_irq *pic, d = UNI_NORTH_PCI_HOST_BRIDGE(dev); memory_region_init(&d->pci_mmio, OBJECT(d), "pci-mmio", 0x100000000ULL); memory_region_init_alias(&d->pci_hole, OBJECT(d), "pci-hole", &d->pci_mmio, - 0x80000000ULL, 0x70000000ULL); + 0x80000000ULL, 0x10000000ULL); memory_region_add_subregion(address_space_mem, 0x80000000ULL, &d->pci_hole); diff --git a/hw/pci/msi.c b/hw/pci/msi.c index a4a3040d4d..52d23130d9 100644 --- a/hw/pci/msi.c +++ b/hw/pci/msi.c @@ -291,7 +291,7 @@ void msi_notify(PCIDevice *dev, unsigned int vector) "notify vector 0x%x" " address: 0x%"PRIx64" data: 0x%"PRIx32"\n", vector, msg.address, msg.data); - stl_le_phys(&address_space_memory, msg.address, msg.data); + stl_le_phys(&dev->bus_master_as, msg.address, msg.data); } /* Normally called by pci_default_write_config(). */ diff --git a/hw/pci/msix.c b/hw/pci/msix.c index 5c49bfc304..24de2605fb 100644 --- a/hw/pci/msix.c +++ b/hw/pci/msix.c @@ -319,7 +319,6 @@ int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries, bar_nr, MSIX_EXCLUSIVE_BAR_PBA_OFFSET, MSIX_EXCLUSIVE_CAP_OFFSET); if (ret) { - memory_region_destroy(&dev->msix_exclusive_bar); return ret; } @@ -359,11 +358,9 @@ void msix_uninit(PCIDevice *dev, MemoryRegion *table_bar, MemoryRegion *pba_bar) msix_free_irq_entries(dev); dev->msix_entries_nr = 0; memory_region_del_subregion(pba_bar, &dev->msix_pba_mmio); - memory_region_destroy(&dev->msix_pba_mmio); g_free(dev->msix_pba); dev->msix_pba = NULL; memory_region_del_subregion(table_bar, &dev->msix_table_mmio); - memory_region_destroy(&dev->msix_table_mmio); g_free(dev->msix_table); dev->msix_table = NULL; g_free(dev->msix_entry_used); @@ -375,7 +372,6 @@ void msix_uninit_exclusive_bar(PCIDevice *dev) { if (msix_present(dev)) { msix_uninit(dev, &dev->msix_exclusive_bar, &dev->msix_exclusive_bar); - memory_region_destroy(&dev->msix_exclusive_bar); } } @@ -439,7 +435,7 @@ void msix_notify(PCIDevice *dev, unsigned vector) msg = msix_get_message(dev, vector); - stl_le_phys(&address_space_memory, msg.address, msg.data); + stl_le_phys(&dev->bus_master_as, msg.address, msg.data); } void msix_reset(PCIDevice *dev) diff --git a/hw/pci/pci-hotplug-old.c b/hw/pci/pci-hotplug-old.c index cf2caebfb1..0c09c72ac5 100644 --- a/hw/pci/pci-hotplug-old.c +++ b/hw/pci/pci-hotplug-old.c @@ -33,7 +33,7 @@ #include "hw/scsi/scsi.h" #include "hw/virtio/virtio-blk.h" #include "qemu/config-file.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "qapi/error.h" static int pci_read_devaddr(Monitor *mon, const char *addr, @@ -77,7 +77,7 @@ static PCIDevice *qemu_pci_hot_add_nic(Monitor *mon, monitor_printf(mon, "Invalid PCI device address %s\n", devaddr); return NULL; } - if (!((BusState*)bus)->allow_hotplug) { + if (!qbus_is_hotpluggable(BUS(bus))) { monitor_printf(mon, "PCI bus doesn't support hotplug\n"); return NULL; } @@ -107,6 +107,7 @@ static int scsi_hot_add(Monitor *mon, DeviceState *adapter, { SCSIBus *scsibus; SCSIDevice *scsidev; + Error *local_err = NULL; scsibus = (SCSIBus *) object_dynamic_cast(OBJECT(QLIST_FIRST(&adapter->child_bus)), @@ -126,9 +127,13 @@ static int scsi_hot_add(Monitor *mon, DeviceState *adapter, */ dinfo->unit = qemu_opt_get_number(dinfo->opts, "unit", -1); dinfo->bus = scsibus->busnr; - scsidev = scsi_bus_legacy_add_drive(scsibus, dinfo->bdrv, dinfo->unit, - false, -1, NULL, NULL); + scsidev = scsi_bus_legacy_add_drive(scsibus, + blk_by_legacy_dinfo(dinfo), + dinfo->unit, false, -1, NULL, + &local_err); if (!scsidev) { + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); return -1; } dinfo->unit = scsidev->id; @@ -224,7 +229,7 @@ static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon, monitor_printf(mon, "Invalid PCI device address %s\n", devaddr); return NULL; } - if (!((BusState*)bus)->allow_hotplug) { + if (!qbus_is_hotpluggable(BUS(bus))) { monitor_printf(mon, "PCI bus doesn't support hotplug\n"); return NULL; } @@ -247,7 +252,8 @@ static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon, return NULL; } dev = pci_create(bus, devfn, "virtio-blk-pci"); - if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) { + if (qdev_prop_set_drive(&dev->qdev, "drive", + blk_by_legacy_dinfo(dinfo)) < 0) { object_unparent(OBJECT(dev)); dev = NULL; break; diff --git a/hw/pci/pci.c b/hw/pci/pci.c index cdc8ee23d9..2c0afd3e82 100644 --- a/hw/pci/pci.c +++ b/hw/pci/pci.c @@ -64,8 +64,7 @@ static const VMStateDescription vmstate_pcibus = { .name = "PCIBUS", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32_EQUAL(nirq, PCIBus), VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, @@ -473,9 +472,8 @@ const VMStateDescription vmstate_pci_device = { .name = "PCIDevice", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { - VMSTATE_INT32_LE(version_id, PCIDevice), + .fields = (VMStateField[]) { + VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice), VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0, vmstate_info_pci_config, PCI_CONFIG_SPACE_SIZE), @@ -490,9 +488,8 @@ const VMStateDescription vmstate_pcie_device = { .name = "PCIEDevice", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { - VMSTATE_INT32_LE(version_id, PCIDevice), + .fields = (VMStateField[]) { + VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice), VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0, vmstate_info_pci_config, PCIE_CONFIG_SPACE_SIZE), @@ -605,13 +602,13 @@ PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root, const char *devaddr) int dom, bus; unsigned slot; - assert(!root->parent_dev); - if (!root) { fprintf(stderr, "No primary PCI bus\n"); return NULL; } + assert(!root->parent_dev); + if (!devaddr) { *devfnp = -1; return pci_find_bus_nr(root, 0); @@ -802,7 +799,6 @@ static void do_pci_unregister_device(PCIDevice *pci_dev) pci_config_free(pci_dev); address_space_destroy(&pci_dev->bus_master_as); - memory_region_destroy(&pci_dev->bus_master_enable_region); } /* -1 for devfn means auto assign */ @@ -830,6 +826,7 @@ static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus, } pci_dev->bus = bus; + pci_dev->devfn = devfn; dma_as = pci_device_iommu_address_space(pci_dev); memory_region_init_alias(&pci_dev->bus_master_enable_region, @@ -839,7 +836,6 @@ static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus, address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region, name); - pci_dev->devfn = devfn; pstrcpy(pci_dev->name, sizeof(pci_dev->name), name); pci_dev->irq_state = 0; pci_config_alloc(pci_dev); @@ -1150,9 +1146,10 @@ uint32_t pci_default_read_config(PCIDevice *d, return le32_to_cpu(val); } -void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l) +void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l) { int i, was_irq_disabled = pci_irq_disabled(d); + uint32_t val = val_in; for (i = 0; i < l; val >>= 8, ++i) { uint8_t wmask = d->wmask[addr + i]; @@ -1174,8 +1171,8 @@ void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l) & PCI_COMMAND_MASTER); } - msi_write_config(d, addr, val, l); - msix_write_config(d, addr, val, l); + msi_write_config(d, addr, val_in, l); + msix_write_config(d, addr, val_in, l); } /***********************************************************/ @@ -1779,7 +1776,12 @@ static int pci_qdev_init(DeviceState *qdev) pci_dev->romfile = g_strdup(pc->romfile); is_default_rom = true; } - pci_add_option_rom(pci_dev, is_default_rom); + + rc = pci_add_option_rom(pci_dev, is_default_rom); + if (rc != 0) { + pci_unregister_device(DEVICE(pci_dev)); + return rc; + } return 0; } @@ -1940,6 +1942,15 @@ static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom) * for 0.11 compatibility. */ int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE); + + /* + * Hot-plugged devices can't use the option ROM + * if the rom bar is disabled. + */ + if (DEVICE(pdev)->hotplugged) { + return -1; + } + if (class == 0x0300) { rom_add_vga(pdev->romfile); } else { @@ -1977,7 +1988,7 @@ static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom) snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev))); } pdev->has_rom = true; - memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size); + memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_abort); vmstate_register_ram(&pdev->rom, &pdev->qdev); ptr = memory_region_get_ram_ptr(&pdev->rom); load_image(path, ptr); @@ -1999,7 +2010,6 @@ static void pci_del_option_rom(PCIDevice *pdev) return; vmstate_unregister_ram(&pdev->rom, &pdev->qdev); - memory_region_destroy(&pdev->rom); pdev->has_rom = false; } @@ -2013,12 +2023,32 @@ static void pci_del_option_rom(PCIDevice *pdev) int pci_add_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t offset, uint8_t size) { + int ret; + Error *local_err = NULL; + + ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err); + if (local_err) { + assert(ret < 0); + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); + } else { + /* success implies a positive offset in config space */ + assert(ret > 0); + } + return ret; +} + +int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id, + uint8_t offset, uint8_t size, + Error **errp) +{ uint8_t *config; int i, overlapping_cap; if (!offset) { offset = pci_find_space(pdev, size); if (!offset) { + error_setg(errp, "out of PCI config space"); return -ENOSPC; } } else { @@ -2029,12 +2059,12 @@ int pci_add_capability(PCIDevice *pdev, uint8_t cap_id, for (i = offset; i < offset + size; i++) { overlapping_cap = pci_find_capability_at_offset(pdev, i); if (overlapping_cap) { - fprintf(stderr, "ERROR: %s:%02x:%02x.%x " - "Attempt to add PCI capability %x at offset " - "%x overlaps existing capability %x at offset %x\n", - pci_root_bus_path(pdev), pci_bus_num(pdev->bus), - PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn), - cap_id, offset, overlapping_cap, i); + error_setg(errp, "%s:%02x:%02x.%x " + "Attempt to add PCI capability %x at offset " + "%x overlaps existing capability %x at offset %x", + pci_root_bus_path(pdev), pci_bus_num(pdev->bus), + PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn), + cap_id, offset, overlapping_cap, i); return -EINVAL; } } diff --git a/hw/pci/pci_bridge.c b/hw/pci/pci_bridge.c index 4becdc14b8..40c97b155c 100644 --- a/hw/pci/pci_bridge.c +++ b/hw/pci/pci_bridge.c @@ -219,12 +219,12 @@ static void pci_bridge_region_del(PCIBridge *br, PCIBridgeWindows *w) static void pci_bridge_region_cleanup(PCIBridge *br, PCIBridgeWindows *w) { - memory_region_destroy(&w->alias_io); - memory_region_destroy(&w->alias_mem); - memory_region_destroy(&w->alias_pref_mem); - memory_region_destroy(&w->alias_vga[QEMU_PCI_VGA_IO_LO]); - memory_region_destroy(&w->alias_vga[QEMU_PCI_VGA_IO_HI]); - memory_region_destroy(&w->alias_vga[QEMU_PCI_VGA_MEM]); + object_unparent(OBJECT(&w->alias_io)); + object_unparent(OBJECT(&w->alias_mem)); + object_unparent(OBJECT(&w->alias_pref_mem)); + object_unparent(OBJECT(&w->alias_vga[QEMU_PCI_VGA_IO_LO])); + object_unparent(OBJECT(&w->alias_vga[QEMU_PCI_VGA_IO_HI])); + object_unparent(OBJECT(&w->alias_vga[QEMU_PCI_VGA_MEM])); g_free(w); } @@ -389,8 +389,6 @@ void pci_bridge_exitfn(PCIDevice *pci_dev) QLIST_REMOVE(&s->sec_bus, sibling); pci_bridge_region_del(s, s->windows); pci_bridge_region_cleanup(s, s->windows); - memory_region_destroy(&s->address_space_mem); - memory_region_destroy(&s->address_space_io); /* object_unparent() is called automatically during device deletion */ } diff --git a/hw/pci/pcie.c b/hw/pci/pcie.c index 02cde6f96c..1abbbb192e 100644 --- a/hw/pci/pcie.c +++ b/hw/pci/pcie.c @@ -145,7 +145,7 @@ void pcie_cap_deverr_init(PCIDevice *dev) PCI_EXP_DEVCTL_FERE | PCI_EXP_DEVCTL_URRE); pci_long_test_and_set_mask(dev->w1cmask + pos + PCI_EXP_DEVSTA, PCI_EXP_DEVSTA_CED | PCI_EXP_DEVSTA_NFED | - PCI_EXP_DEVSTA_URD | PCI_EXP_DEVSTA_URD); + PCI_EXP_DEVSTA_FED | PCI_EXP_DEVSTA_URD); } void pcie_cap_deverr_reset(PCIDevice *dev) @@ -224,12 +224,12 @@ static void pcie_cap_slot_hotplug_common(PCIDevice *hotplug_dev, *exp_cap = hotplug_dev->config + hotplug_dev->exp.exp_cap; uint16_t sltsta = pci_get_word(*exp_cap + PCI_EXP_SLTSTA); - PCIE_DEV_PRINTF(PCI_DEVICE(dev), "hotplug state: %d\n", state); + PCIE_DEV_PRINTF(PCI_DEVICE(dev), "hotplug state: 0x%x\n", sltsta); if (sltsta & PCI_EXP_SLTSTA_EIS) { /* the slot is electromechanically locked. * This error is propagated up to qdev and then to HMP/QMP. */ - error_setg_errno(errp, -EBUSY, "slot is electromechanically locked"); + error_setg_errno(errp, EBUSY, "slot is electromechanically locked"); } } @@ -258,20 +258,18 @@ void pcie_cap_slot_hotplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev, pci_word_test_and_set_mask(exp_cap + PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_PDS); - pcie_cap_slot_event(PCI_DEVICE(hotplug_dev), PCI_EXP_HP_EV_PDC); + pcie_cap_slot_event(PCI_DEVICE(hotplug_dev), + PCI_EXP_HP_EV_PDC | PCI_EXP_HP_EV_ABP); } -void pcie_cap_slot_hot_unplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev, - Error **errp) +void pcie_cap_slot_hot_unplug_request_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { uint8_t *exp_cap; pcie_cap_slot_hotplug_common(PCI_DEVICE(hotplug_dev), dev, &exp_cap, errp); - object_unparent(OBJECT(dev)); - pci_word_test_and_clear_mask(exp_cap + PCI_EXP_SLTSTA, - PCI_EXP_SLTSTA_PDS); - pcie_cap_slot_event(PCI_DEVICE(hotplug_dev), PCI_EXP_HP_EV_PDC); + pcie_cap_slot_push_attention_button(PCI_DEVICE(hotplug_dev)); } /* pci express slot for pci express root/downstream port @@ -294,6 +292,15 @@ void pcie_cap_slot_init(PCIDevice *dev, uint16_t slot) PCI_EXP_SLTCAP_AIP | PCI_EXP_SLTCAP_ABP); + if (dev->cap_present & QEMU_PCIE_SLTCAP_PCP) { + pci_long_test_and_set_mask(dev->config + pos + PCI_EXP_SLTCAP, + PCI_EXP_SLTCAP_PCP); + pci_word_test_and_clear_mask(dev->config + pos + PCI_EXP_SLTCTL, + PCI_EXP_SLTCTL_PCC); + pci_word_test_and_set_mask(dev->wmask + pos + PCI_EXP_SLTCTL, + PCI_EXP_SLTCTL_PCC); + } + pci_word_test_and_clear_mask(dev->config + pos + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PIC | PCI_EXP_SLTCTL_AIC); @@ -327,6 +334,10 @@ void pcie_cap_slot_init(PCIDevice *dev, uint16_t slot) void pcie_cap_slot_reset(PCIDevice *dev) { uint8_t *exp_cap = dev->config + dev->exp.exp_cap; + uint8_t port_type = pcie_cap_get_type(dev); + + assert(port_type == PCI_EXP_TYPE_DOWNSTREAM || + port_type == PCI_EXP_TYPE_ROOT_PORT); PCIE_DEV_PRINTF(dev, "reset\n"); @@ -339,9 +350,25 @@ void pcie_cap_slot_reset(PCIDevice *dev) PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE); pci_word_test_and_set_mask(exp_cap + PCI_EXP_SLTCTL, - PCI_EXP_SLTCTL_PIC_OFF | PCI_EXP_SLTCTL_AIC_OFF); + if (dev->cap_present & QEMU_PCIE_SLTCAP_PCP) { + /* Downstream ports enforce device number 0. */ + bool populated = pci_bridge_get_sec_bus(PCI_BRIDGE(dev))->devices[0]; + uint16_t pic; + + if (populated) { + pci_word_test_and_clear_mask(exp_cap + PCI_EXP_SLTCTL, + PCI_EXP_SLTCTL_PCC); + } else { + pci_word_test_and_set_mask(exp_cap + PCI_EXP_SLTCTL, + PCI_EXP_SLTCTL_PCC); + } + + pic = populated ? PCI_EXP_SLTCTL_PIC_ON : PCI_EXP_SLTCTL_PIC_OFF; + pci_word_test_and_set_mask(exp_cap + PCI_EXP_SLTCTL, pic); + } + pci_word_test_and_clear_mask(exp_cap + PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_EIS |/* on reset, the lock is released */ @@ -352,6 +379,11 @@ void pcie_cap_slot_reset(PCIDevice *dev) hotplug_event_update_event_status(dev); } +static void pcie_unplug_device(PCIBus *bus, PCIDevice *dev, void *opaque) +{ + object_unparent(OBJECT(dev)); +} + void pcie_cap_slot_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int len) { @@ -376,6 +408,22 @@ void pcie_cap_slot_write_config(PCIDevice *dev, sltsta); } + /* + * If the slot is polulated, power indicator is off and power + * controller is off, it is safe to detach the devices. + */ + if ((sltsta & PCI_EXP_SLTSTA_PDS) && (val & PCI_EXP_SLTCTL_PCC) && + ((val & PCI_EXP_SLTCTL_PIC_OFF) == PCI_EXP_SLTCTL_PIC_OFF)) { + PCIBus *sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(dev)); + pci_for_each_device(sec_bus, pci_bus_num(sec_bus), + pcie_unplug_device, NULL); + + pci_word_test_and_clear_mask(exp_cap + PCI_EXP_SLTSTA, + PCI_EXP_SLTSTA_PDS); + pci_word_test_and_set_mask(exp_cap + PCI_EXP_SLTSTA, + PCI_EXP_SLTSTA_PDC); + } + hotplug_event_notify(dev); /* @@ -449,9 +497,10 @@ void pcie_cap_flr_write_config(PCIDevice *dev, } } -/* Alternative Routing-ID Interpretation (ARI) */ -/* ari forwarding support for down stream port */ -void pcie_cap_ari_init(PCIDevice *dev) +/* Alternative Routing-ID Interpretation (ARI) + * forwarding support for root and downstream ports + */ +void pcie_cap_arifwd_init(PCIDevice *dev) { uint32_t pos = dev->exp.exp_cap; pci_long_test_and_set_mask(dev->config + pos + PCI_EXP_DEVCAP2, @@ -460,13 +509,13 @@ void pcie_cap_ari_init(PCIDevice *dev) PCI_EXP_DEVCTL2_ARI); } -void pcie_cap_ari_reset(PCIDevice *dev) +void pcie_cap_arifwd_reset(PCIDevice *dev) { uint8_t *devctl2 = dev->config + dev->exp.exp_cap + PCI_EXP_DEVCTL2; pci_long_test_and_clear_mask(devctl2, PCI_EXP_DEVCTL2_ARI); } -bool pcie_cap_is_ari_enabled(const PCIDevice *dev) +bool pcie_cap_is_arifwd_enabled(const PCIDevice *dev) { if (!pci_is_express(dev)) { return false; @@ -480,7 +529,7 @@ bool pcie_cap_is_ari_enabled(const PCIDevice *dev) } /************************************************************************** - * pci express extended capability allocation functions + * pci express extended capability list management functions * uint16_t ext_cap_id (16 bit) * uint8_t cap_ver (4 bit) * uint16_t cap_offset (12 bit) @@ -582,5 +631,5 @@ void pcie_ari_init(PCIDevice *dev, uint16_t offset, uint16_t nextfn) { pcie_add_capability(dev, PCI_EXT_CAP_ID_ARI, PCI_ARI_VER, offset, PCI_ARI_SIZEOF); - pci_set_long(dev->config + offset + PCI_ARI_CAP, PCI_ARI_CAP_NFN(nextfn)); + pci_set_long(dev->config + offset + PCI_ARI_CAP, (nextfn & 0xff) << 8); } diff --git a/hw/pci/pcie_aer.c b/hw/pci/pcie_aer.c index 991502e517..1f4be1677c 100644 --- a/hw/pci/pcie_aer.c +++ b/hw/pci/pcie_aer.c @@ -784,8 +784,7 @@ static const VMStateDescription vmstate_pcie_aer_err = { .name = "PCIE_AER_ERROR", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(status, PCIEAERErr), VMSTATE_UINT16(source_id, PCIEAERErr), VMSTATE_UINT16(flags, PCIEAERErr), @@ -795,14 +794,21 @@ static const VMStateDescription vmstate_pcie_aer_err = { } }; +static bool pcie_aer_state_log_num_valid(void *opaque, int version_id) +{ + PCIEAERLog *s = opaque; + + return s->log_num <= s->log_max; +} + const VMStateDescription vmstate_pcie_aer_log = { .name = "PCIE_AER_ERROR_LOG", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT16(log_num, PCIEAERLog), - VMSTATE_UINT16(log_max, PCIEAERLog), + VMSTATE_UINT16_EQUAL(log_max, PCIEAERLog), + VMSTATE_VALIDATE("log_num <= log_max", pcie_aer_state_log_num_valid), VMSTATE_STRUCT_VARRAY_POINTER_UINT16(log, PCIEAERLog, log_num, vmstate_pcie_aer_err, PCIEAERErr), VMSTATE_END_OF_LIST() diff --git a/hw/pci/pcie_host.c b/hw/pci/pcie_host.c index c6e1b573e1..3db038fc7f 100644 --- a/hw/pci/pcie_host.c +++ b/hw/pci/pcie_host.c @@ -83,18 +83,17 @@ static const MemoryRegionOps pcie_mmcfg_ops = { .endianness = DEVICE_NATIVE_ENDIAN, }; -int pcie_host_init(PCIExpressHost *e) +static void pcie_host_init(Object *obj) { - e->base_addr = PCIE_BASE_ADDR_UNMAPPED; + PCIExpressHost *e = PCIE_HOST_BRIDGE(obj); - return 0; + e->base_addr = PCIE_BASE_ADDR_UNMAPPED; } void pcie_host_mmcfg_unmap(PCIExpressHost *e) { if (e->base_addr != PCIE_BASE_ADDR_UNMAPPED) { memory_region_del_subregion(get_system_memory(), &e->mmio); - memory_region_destroy(&e->mmio); e->base_addr = PCIE_BASE_ADDR_UNMAPPED; } } @@ -128,6 +127,7 @@ static const TypeInfo pcie_host_type_info = { .parent = TYPE_PCI_HOST_BRIDGE, .abstract = true, .instance_size = sizeof(PCIExpressHost), + .instance_init = pcie_host_init, }; static void pcie_host_register_types(void) diff --git a/hw/pci/pcie_port.c b/hw/pci/pcie_port.c index fa24877955..40ca8d5d17 100644 --- a/hw/pci/pcie_port.c +++ b/hw/pci/pcie_port.c @@ -154,7 +154,7 @@ static void pcie_slot_class_init(ObjectClass *oc, void *data) dc->props = pcie_slot_props; hc->plug = pcie_cap_slot_hotplug_cb; - hc->unplug = pcie_cap_slot_hot_unplug_cb; + hc->unplug_request = pcie_cap_slot_hot_unplug_request_cb; } static const TypeInfo pcie_slot_type_info = { diff --git a/hw/pci/shpc.c b/hw/pci/shpc.c index 180faa7adb..27c496e8c3 100644 --- a/hw/pci/shpc.c +++ b/hw/pci/shpc.c @@ -549,8 +549,8 @@ void shpc_device_hotplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev, shpc_interrupt_update(pci_hotplug_dev); } -void shpc_device_hot_unplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev, - Error **errp) +void shpc_device_hot_unplug_request_cb(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { Error *local_err = NULL; PCIDevice *pci_hotplug_dev = PCI_DEVICE(hotplug_dev); @@ -559,8 +559,9 @@ void shpc_device_hot_unplug_cb(HotplugHandler *hotplug_dev, DeviceState *dev, uint8_t led; int slot; - shpc_device_hotplug_common(PCI_DEVICE(dev), &slot, shpc, errp); + shpc_device_hotplug_common(PCI_DEVICE(dev), &slot, shpc, &local_err); if (local_err) { + error_propagate(errp, local_err); return; } @@ -662,12 +663,12 @@ void shpc_cleanup(PCIDevice *d, MemoryRegion *bar) SHPCDevice *shpc = d->shpc; d->cap_present &= ~QEMU_PCI_CAP_SHPC; memory_region_del_subregion(bar, &shpc->mmio); + object_unparent(OBJECT(&shpc->mmio)); /* TODO: cleanup config space changes? */ g_free(shpc->config); g_free(shpc->cmask); g_free(shpc->wmask); g_free(shpc->w1cmask); - memory_region_destroy(&shpc->mmio); g_free(shpc); } diff --git a/hw/pcmcia/pxa2xx.c b/hw/pcmcia/pxa2xx.c index 96f377453d..a7e187743d 100644 --- a/hw/pcmcia/pxa2xx.c +++ b/hw/pcmcia/pxa2xx.c @@ -149,24 +149,11 @@ PXA2xxPCMCIAState *pxa2xx_pcmcia_init(MemoryRegion *sysmem, sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base); s = PXA2XX_PCMCIA(dev); - if (base == 0x30000000) { - s->slot.slot_string = "PXA PC Card Socket 1"; - } else { - s->slot.slot_string = "PXA PC Card Socket 0"; - } - qdev_init_nofail(dev); return s; } -static void pxa2xx_pcmcia_realize(DeviceState *dev, Error **errp) -{ - PXA2xxPCMCIAState *s = PXA2XX_PCMCIA(dev); - - pcmcia_socket_register(&s->slot); -} - static void pxa2xx_pcmcia_initfn(Object *obj) { SysBusDevice *sbd = SYS_BUS_DEVICE(obj); @@ -195,7 +182,7 @@ static void pxa2xx_pcmcia_initfn(Object *obj) memory_region_add_subregion(&s->container_mem, 0x0c000000, &s->common_iomem); - s->slot.irq = qemu_allocate_irqs(pxa2xx_pcmcia_set_irq, s, 1)[0]; + s->slot.irq = qemu_allocate_irq(pxa2xx_pcmcia_set_irq, s, 0); object_property_add_link(obj, "card", TYPE_PCMCIA_CARD, (Object **)&s->card, @@ -262,19 +249,11 @@ void pxa2xx_pcmcia_set_irq_cb(void *opaque, qemu_irq irq, qemu_irq cd_irq) s->cd_irq = cd_irq; } -static void pxa2xx_pcmcia_class_init(ObjectClass *oc, void *data) -{ - DeviceClass *dc = DEVICE_CLASS(oc); - - dc->realize = pxa2xx_pcmcia_realize; -} - static const TypeInfo pxa2xx_pcmcia_type_info = { .name = TYPE_PXA2XX_PCMCIA, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(PXA2xxPCMCIAState), .instance_init = pxa2xx_pcmcia_initfn, - .class_init = pxa2xx_pcmcia_class_init, }; static void pxa2xx_pcmcia_register_types(void) diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs index ea747f0a20..19d99200ae 100644 --- a/hw/ppc/Makefile.objs +++ b/hw/ppc/Makefile.objs @@ -4,6 +4,9 @@ obj-y += ppc.o ppc_booke.o obj-$(CONFIG_PSERIES) += spapr.o spapr_vio.o spapr_events.o obj-$(CONFIG_PSERIES) += spapr_hcall.o spapr_iommu.o spapr_rtas.o obj-$(CONFIG_PSERIES) += spapr_pci.o +ifeq ($(CONFIG_PCI)$(CONFIG_PSERIES)$(CONFIG_LINUX), yyy) +obj-y += spapr_pci_vfio.o +endif # PowerPC 4xx boards obj-y += ppc405_boards.o ppc4xx_devs.o ppc405_uc.o ppc440_bamboo.o obj-y += ppc4xx_pci.o @@ -17,4 +20,4 @@ obj-$(CONFIG_MAC) += mac_newworld.o obj-$(CONFIG_E500) += e500.o mpc8544ds.o e500plat.o obj-$(CONFIG_E500) += mpc8544_guts.o ppce500_spin.o # PowerPC 440 Xilinx ML507 reference board. -obj-y += virtex_ml507.o +obj-$(CONFIG_XILINX) += virtex_ml507.o diff --git a/hw/ppc/e500.c b/hw/ppc/e500.c index f984b3e9a9..2832fc0da4 100644 --- a/hw/ppc/e500.c +++ b/hw/ppc/e500.c @@ -36,10 +36,12 @@ #include "exec/address-spaces.h" #include "qemu/host-utils.h" #include "hw/pci-host/ppce500.h" +#include "qemu/error-report.h" +#include "hw/platform-bus.h" +#include "hw/net/fsl_etsec/etsec.h" #define EPAPR_MAGIC (0x45504150) #define BINARY_DEVICE_TREE_FILE "mpc8544ds.dtb" -#define UIMAGE_LOAD_BASE 0 #define DTC_LOAD_PAD 0x1800000 #define DTC_PAD_MASK 0xFFFFF #define DTB_MAX_SIZE (8 * 1024 * 1024) @@ -62,6 +64,8 @@ #define MPC8544_PCI_IO 0xE1000000ULL #define MPC8544_UTIL_OFFSET 0xe0000ULL #define MPC8544_SPIN_BASE 0xEF000000ULL +#define MPC8XXX_GPIO_OFFSET 0x000FF000ULL +#define MPC8XXX_GPIO_IRQ 43 struct boot_info { @@ -123,16 +127,154 @@ static void dt_serial_create(void *fdt, unsigned long long offset, } } -static int ppce500_load_device_tree(QEMUMachineInitArgs *args, +static void create_dt_mpc8xxx_gpio(void *fdt, const char *soc, const char *mpic) +{ + hwaddr mmio0 = MPC8XXX_GPIO_OFFSET; + int irq0 = MPC8XXX_GPIO_IRQ; + gchar *node = g_strdup_printf("%s/gpio@%"PRIx64, soc, mmio0); + gchar *poweroff = g_strdup_printf("%s/power-off", soc); + int gpio_ph; + + qemu_fdt_add_subnode(fdt, node); + qemu_fdt_setprop_string(fdt, node, "compatible", "fsl,qoriq-gpio"); + qemu_fdt_setprop_cells(fdt, node, "reg", mmio0, 0x1000); + qemu_fdt_setprop_cells(fdt, node, "interrupts", irq0, 0x2); + qemu_fdt_setprop_phandle(fdt, node, "interrupt-parent", mpic); + qemu_fdt_setprop_cells(fdt, node, "#gpio-cells", 2); + qemu_fdt_setprop(fdt, node, "gpio-controller", NULL, 0); + gpio_ph = qemu_fdt_alloc_phandle(fdt); + qemu_fdt_setprop_cell(fdt, node, "phandle", gpio_ph); + qemu_fdt_setprop_cell(fdt, node, "linux,phandle", gpio_ph); + + /* Power Off Pin */ + qemu_fdt_add_subnode(fdt, poweroff); + qemu_fdt_setprop_string(fdt, poweroff, "compatible", "gpio-poweroff"); + qemu_fdt_setprop_cells(fdt, poweroff, "gpios", gpio_ph, 0, 0); + + g_free(node); + g_free(poweroff); +} + +typedef struct PlatformDevtreeData { + void *fdt; + const char *mpic; + int irq_start; + const char *node; + PlatformBusDevice *pbus; +} PlatformDevtreeData; + +static int create_devtree_etsec(SysBusDevice *sbdev, PlatformDevtreeData *data) +{ + eTSEC *etsec = ETSEC_COMMON(sbdev); + PlatformBusDevice *pbus = data->pbus; + hwaddr mmio0 = platform_bus_get_mmio_addr(pbus, sbdev, 0); + int irq0 = platform_bus_get_irqn(pbus, sbdev, 0); + int irq1 = platform_bus_get_irqn(pbus, sbdev, 1); + int irq2 = platform_bus_get_irqn(pbus, sbdev, 2); + gchar *node = g_strdup_printf("/platform/ethernet@%"PRIx64, mmio0); + gchar *group = g_strdup_printf("%s/queue-group", node); + void *fdt = data->fdt; + + assert((int64_t)mmio0 >= 0); + assert(irq0 >= 0); + assert(irq1 >= 0); + assert(irq2 >= 0); + + qemu_fdt_add_subnode(fdt, node); + qemu_fdt_setprop_string(fdt, node, "device_type", "network"); + qemu_fdt_setprop_string(fdt, node, "compatible", "fsl,etsec2"); + qemu_fdt_setprop_string(fdt, node, "model", "eTSEC"); + qemu_fdt_setprop(fdt, node, "local-mac-address", etsec->conf.macaddr.a, 6); + qemu_fdt_setprop_cells(fdt, node, "fixed-link", 0, 1, 1000, 0, 0); + + qemu_fdt_add_subnode(fdt, group); + qemu_fdt_setprop_cells(fdt, group, "reg", mmio0, 0x1000); + qemu_fdt_setprop_cells(fdt, group, "interrupts", + data->irq_start + irq0, 0x2, + data->irq_start + irq1, 0x2, + data->irq_start + irq2, 0x2); + + g_free(node); + g_free(group); + + return 0; +} + +static int sysbus_device_create_devtree(SysBusDevice *sbdev, void *opaque) +{ + PlatformDevtreeData *data = opaque; + bool matched = false; + + if (object_dynamic_cast(OBJECT(sbdev), TYPE_ETSEC_COMMON)) { + create_devtree_etsec(sbdev, data); + matched = true; + } + + if (!matched) { + error_report("Device %s is not supported by this machine yet.", + qdev_fw_name(DEVICE(sbdev))); + exit(1); + } + + return 0; +} + +static void platform_bus_create_devtree(PPCE500Params *params, void *fdt, + const char *mpic) +{ + gchar *node = g_strdup_printf("/platform@%"PRIx64, params->platform_bus_base); + const char platcomp[] = "qemu,platform\0simple-bus"; + uint64_t addr = params->platform_bus_base; + uint64_t size = params->platform_bus_size; + int irq_start = params->platform_bus_first_irq; + PlatformBusDevice *pbus; + DeviceState *dev; + + /* Create a /platform node that we can put all devices into */ + + qemu_fdt_add_subnode(fdt, node); + qemu_fdt_setprop(fdt, node, "compatible", platcomp, sizeof(platcomp)); + + /* Our platform bus region is less than 32bit big, so 1 cell is enough for + address and size */ + qemu_fdt_setprop_cells(fdt, node, "#size-cells", 1); + qemu_fdt_setprop_cells(fdt, node, "#address-cells", 1); + qemu_fdt_setprop_cells(fdt, node, "ranges", 0, addr >> 32, addr, size); + + qemu_fdt_setprop_phandle(fdt, node, "interrupt-parent", mpic); + + dev = qdev_find_recursive(sysbus_get_default(), TYPE_PLATFORM_BUS_DEVICE); + pbus = PLATFORM_BUS_DEVICE(dev); + + /* We can only create dt nodes for dynamic devices when they're ready */ + if (pbus->done_gathering) { + PlatformDevtreeData data = { + .fdt = fdt, + .mpic = mpic, + .irq_start = irq_start, + .node = node, + .pbus = pbus, + }; + + /* Loop through all dynamic sysbus devices and create nodes for them */ + foreach_dynamic_sysbus_device(sysbus_device_create_devtree, &data); + } + + g_free(node); +} + +static int ppce500_load_device_tree(MachineState *machine, PPCE500Params *params, hwaddr addr, hwaddr initrd_base, hwaddr initrd_size, + hwaddr kernel_base, + hwaddr kernel_size, bool dry_run) { CPUPPCState *env = first_cpu->env_ptr; int ret = -1; - uint64_t mem_reg_property[] = { 0, cpu_to_be64(args->ram_size) }; + uint64_t mem_reg_property[] = { 0, cpu_to_be64(machine->ram_size) }; int fdt_size; void *fdt; uint8_t hypercall[16]; @@ -204,10 +346,17 @@ static int ppce500_load_device_tree(QEMUMachineInitArgs *args, if (ret < 0) { fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n"); } + + } + + if (kernel_base != -1ULL) { + qemu_fdt_setprop_cells(fdt, "/chosen", "qemu,boot-kernel", + kernel_base >> 32, kernel_base, + kernel_size >> 32, kernel_size); } ret = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs", - args->kernel_cmdline); + machine->kernel_cmdline); if (ret < 0) fprintf(stderr, "couldn't set /chosen/bootargs\n"); @@ -308,10 +457,15 @@ static int ppce500_load_device_tree(QEMUMachineInitArgs *args, * device it finds in the dt as serial output device. And we generate * devices in reverse order to the dt. */ - dt_serial_create(fdt, MPC8544_SERIAL1_REGS_OFFSET, - soc, mpic, "serial1", 1, false); - dt_serial_create(fdt, MPC8544_SERIAL0_REGS_OFFSET, - soc, mpic, "serial0", 0, true); + if (serial_hds[1]) { + dt_serial_create(fdt, MPC8544_SERIAL1_REGS_OFFSET, + soc, mpic, "serial1", 1, false); + } + + if (serial_hds[0]) { + dt_serial_create(fdt, MPC8544_SERIAL0_REGS_OFFSET, + soc, mpic, "serial0", 0, true); + } snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc, MPC8544_UTIL_OFFSET); @@ -366,6 +520,14 @@ static int ppce500_load_device_tree(QEMUMachineInitArgs *args, qemu_fdt_setprop_cell(fdt, pci, "#address-cells", 3); qemu_fdt_setprop_string(fdt, "/aliases", "pci0", pci); + if (params->has_mpc8xxx_gpio) { + create_dt_mpc8xxx_gpio(fdt, soc, mpic); + } + + if (params->has_platform_bus) { + platform_bus_create_devtree(params, fdt, mpic); + } + params->fixup_devtree(params, fdt); if (toplevel_compat) { @@ -387,38 +549,55 @@ out: } typedef struct DeviceTreeParams { - QEMUMachineInitArgs args; + MachineState *machine; PPCE500Params params; hwaddr addr; hwaddr initrd_base; hwaddr initrd_size; + hwaddr kernel_base; + hwaddr kernel_size; + Notifier notifier; } DeviceTreeParams; static void ppce500_reset_device_tree(void *opaque) { DeviceTreeParams *p = opaque; - ppce500_load_device_tree(&p->args, &p->params, p->addr, p->initrd_base, - p->initrd_size, false); + ppce500_load_device_tree(p->machine, &p->params, p->addr, p->initrd_base, + p->initrd_size, p->kernel_base, p->kernel_size, + false); } -static int ppce500_prep_device_tree(QEMUMachineInitArgs *args, +static void ppce500_init_notify(Notifier *notifier, void *data) +{ + DeviceTreeParams *p = container_of(notifier, DeviceTreeParams, notifier); + ppce500_reset_device_tree(p); +} + +static int ppce500_prep_device_tree(MachineState *machine, PPCE500Params *params, hwaddr addr, hwaddr initrd_base, - hwaddr initrd_size) + hwaddr initrd_size, + hwaddr kernel_base, + hwaddr kernel_size) { DeviceTreeParams *p = g_new(DeviceTreeParams, 1); - p->args = *args; + p->machine = machine; p->params = *params; p->addr = addr; p->initrd_base = initrd_base; p->initrd_size = initrd_size; + p->kernel_base = kernel_base; + p->kernel_size = kernel_size; qemu_register_reset(ppce500_reset_device_tree, p); + p->notifier.notify = ppce500_init_notify; + qemu_add_machine_init_done_notifier(&p->notifier); /* Issue the device tree loader once, so that we get the size of the blob */ - return ppce500_load_device_tree(args, params, addr, initrd_base, - initrd_size, true); + return ppce500_load_device_tree(machine, params, addr, initrd_base, + initrd_size, kernel_base, kernel_size, + true); } /* Create -kernel TLB entries for BookE. */ @@ -562,7 +741,7 @@ static qemu_irq *ppce500_init_mpic(PPCE500Params *params, MemoryRegion *ccsr, SysBusDevice *s; int i; - mpic = g_new(qemu_irq, 256); + mpic = g_new0(qemu_irq, 256); if (kvm_enabled()) { QemuOpts *machine_opts = qemu_get_machine_opts(); @@ -597,23 +776,35 @@ static qemu_irq *ppce500_init_mpic(PPCE500Params *params, MemoryRegion *ccsr, return mpic; } -void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) +static void ppce500_power_off(void *opaque, int line, int on) +{ + if (on) { + qemu_system_shutdown_request(); + } +} + +void ppce500_init(MachineState *machine, PPCE500Params *params) { MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); PCIBus *pci_bus; CPUPPCState *env = NULL; - uint64_t elf_entry; - uint64_t elf_lowaddr; - hwaddr entry=0; - hwaddr loadaddr=UIMAGE_LOAD_BASE; - target_long kernel_size=0; - target_ulong dt_base = 0; - target_ulong initrd_base = 0; - target_long initrd_size = 0; - target_ulong cur_base = 0; + uint64_t loadaddr; + hwaddr kernel_base = -1LL; + int kernel_size = 0; + hwaddr dt_base = 0; + hwaddr initrd_base = 0; + int initrd_size = 0; + hwaddr cur_base = 0; + char *filename; + hwaddr bios_entry = 0; + target_long bios_size; + struct boot_info *boot_info; + int dt_size; int i; - unsigned int pci_irq_nrs[4] = {1, 2, 3, 4}; + /* irq num for pin INTA, INTB, INTC and INTD is 1, 2, 3 and + * 4 respectively */ + unsigned int pci_irq_nrs[PCI_NUM_PINS] = {1, 2, 3, 4}; qemu_irq **irqs, *mpic; DeviceState *dev; CPUPPCState *firstenv = NULL; @@ -622,8 +813,8 @@ void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) PPCE500CCSRState *ccsr; /* Setup CPUs */ - if (args->cpu_model == NULL) { - args->cpu_model = "e500v2_v30"; + if (machine->cpu_model == NULL) { + machine->cpu_model = "e500v2_v30"; } irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *)); @@ -633,7 +824,7 @@ void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) CPUState *cs; qemu_irq *input; - cpu = cpu_ppc_init(args->cpu_model); + cpu = cpu_ppc_init(machine->cpu_model); if (cpu == NULL) { fprintf(stderr, "Unable to initialize CPU!\n"); exit(1); @@ -672,11 +863,10 @@ void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) /* Fixup Memory size on a alignment boundary */ ram_size &= ~(RAM_SIZES_ALIGN - 1); - args->ram_size = ram_size; + machine->ram_size = ram_size; /* Register Memory */ - memory_region_init_ram(ram, NULL, "mpc8544ds.ram", ram_size); - vmstate_register_ram_global(ram); + memory_region_allocate_system_memory(ram, NULL, "mpc8544ds.ram", ram_size); memory_region_add_subregion(address_space_mem, 0, ram); dev = qdev_create(NULL, "e500-ccsr"); @@ -713,12 +903,13 @@ void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) /* PCI */ dev = qdev_create(NULL, "e500-pcihost"); qdev_prop_set_uint32(dev, "first_slot", params->pci_first_slot); + qdev_prop_set_uint32(dev, "first_pin_irq", pci_irq_nrs[0]); qdev_init_nofail(dev); s = SYS_BUS_DEVICE(dev); - sysbus_connect_irq(s, 0, mpic[pci_irq_nrs[0]]); - sysbus_connect_irq(s, 1, mpic[pci_irq_nrs[1]]); - sysbus_connect_irq(s, 2, mpic[pci_irq_nrs[2]]); - sysbus_connect_irq(s, 3, mpic[pci_irq_nrs[3]]); + for (i = 0; i < PCI_NUM_PINS; i++) { + sysbus_connect_irq(s, i, mpic[pci_irq_nrs[i]]); + } + memory_region_add_subregion(ccsr_addr_space, MPC8544_PCI_REGS_OFFSET, sysbus_mmio_get_region(s, 0)); @@ -738,64 +929,130 @@ void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params) /* Register spinning region */ sysbus_create_simple("e500-spin", MPC8544_SPIN_BASE, NULL); - /* Load kernel. */ - if (args->kernel_filename) { - kernel_size = load_uimage(args->kernel_filename, &entry, - &loadaddr, NULL); - if (kernel_size < 0) { - kernel_size = load_elf(args->kernel_filename, NULL, NULL, - &elf_entry, &elf_lowaddr, NULL, 1, - ELF_MACHINE, 0); - entry = elf_entry; - loadaddr = elf_lowaddr; + if (cur_base < (32 * 1024 * 1024)) { + /* u-boot occupies memory up to 32MB, so load blobs above */ + cur_base = (32 * 1024 * 1024); + } + + if (params->has_mpc8xxx_gpio) { + qemu_irq poweroff_irq; + + dev = qdev_create(NULL, "mpc8xxx_gpio"); + s = SYS_BUS_DEVICE(dev); + qdev_init_nofail(dev); + sysbus_connect_irq(s, 0, mpic[MPC8XXX_GPIO_IRQ]); + memory_region_add_subregion(ccsr_addr_space, MPC8XXX_GPIO_OFFSET, + sysbus_mmio_get_region(s, 0)); + + /* Power Off GPIO at Pin 0 */ + poweroff_irq = qemu_allocate_irq(ppce500_power_off, NULL, 0); + qdev_connect_gpio_out(dev, 0, poweroff_irq); + } + + /* Platform Bus Device */ + if (params->has_platform_bus) { + dev = qdev_create(NULL, TYPE_PLATFORM_BUS_DEVICE); + dev->id = TYPE_PLATFORM_BUS_DEVICE; + qdev_prop_set_uint32(dev, "num_irqs", params->platform_bus_num_irqs); + qdev_prop_set_uint32(dev, "mmio_size", params->platform_bus_size); + qdev_init_nofail(dev); + s = SYS_BUS_DEVICE(dev); + + for (i = 0; i < params->platform_bus_num_irqs; i++) { + int irqn = params->platform_bus_first_irq + i; + sysbus_connect_irq(s, i, mpic[irqn]); } - /* XXX try again as binary */ + + memory_region_add_subregion(address_space_mem, + params->platform_bus_base, + sysbus_mmio_get_region(s, 0)); + } + + /* Load kernel. */ + if (machine->kernel_filename) { + kernel_base = cur_base; + kernel_size = load_image_targphys(machine->kernel_filename, + cur_base, + ram_size - cur_base); if (kernel_size < 0) { fprintf(stderr, "qemu: could not load kernel '%s'\n", - args->kernel_filename); + machine->kernel_filename); exit(1); } - cur_base = loadaddr + kernel_size; - - /* Reserve space for dtb */ - dt_base = (cur_base + DTC_LOAD_PAD) & ~DTC_PAD_MASK; - cur_base += DTB_MAX_SIZE; + cur_base += kernel_size; } /* Load initrd. */ - if (args->initrd_filename) { + if (machine->initrd_filename) { initrd_base = (cur_base + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK; - initrd_size = load_image_targphys(args->initrd_filename, initrd_base, + initrd_size = load_image_targphys(machine->initrd_filename, initrd_base, ram_size - initrd_base); if (initrd_size < 0) { fprintf(stderr, "qemu: could not load initial ram disk '%s'\n", - args->initrd_filename); + machine->initrd_filename); exit(1); } cur_base = initrd_base + initrd_size; } - /* If we're loading a kernel directly, we must load the device tree too. */ - if (args->kernel_filename) { - struct boot_info *boot_info; - int dt_size; - - dt_size = ppce500_prep_device_tree(args, params, dt_base, - initrd_base, initrd_size); - if (dt_size < 0) { - fprintf(stderr, "couldn't load device tree\n"); + /* + * Smart firmware defaults ahead! + * + * We follow the following table to select which payload we execute. + * + * -kernel | -bios | payload + * ---------+-------+--------- + * N | Y | u-boot + * N | N | u-boot + * Y | Y | u-boot + * Y | N | kernel + * + * This ensures backwards compatibility with how we used to expose + * -kernel to users but allows them to run through u-boot as well. + */ + if (bios_name == NULL) { + if (machine->kernel_filename) { + bios_name = machine->kernel_filename; + } else { + bios_name = "u-boot.e500"; + } + } + filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); + + bios_size = load_elf(filename, NULL, NULL, &bios_entry, &loadaddr, NULL, + 1, ELF_MACHINE, 0); + if (bios_size < 0) { + /* + * Hrm. No ELF image? Try a uImage, maybe someone is giving us an + * ePAPR compliant kernel + */ + kernel_size = load_uimage(filename, &bios_entry, &loadaddr, NULL, + NULL, NULL); + if (kernel_size < 0) { + fprintf(stderr, "qemu: could not load firmware '%s'\n", filename); exit(1); } - assert(dt_size < DTB_MAX_SIZE); + } - boot_info = env->load_info; - boot_info->entry = entry; - boot_info->dt_base = dt_base; - boot_info->dt_size = dt_size; + /* Reserve space for dtb */ + dt_base = (loadaddr + bios_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK; + + dt_size = ppce500_prep_device_tree(machine, params, dt_base, + initrd_base, initrd_size, + kernel_base, kernel_size); + if (dt_size < 0) { + fprintf(stderr, "couldn't load device tree\n"); + exit(1); } + assert(dt_size < DTB_MAX_SIZE); + + boot_info = env->load_info; + boot_info->entry = bios_entry; + boot_info->dt_base = dt_base; + boot_info->dt_size = dt_size; if (kvm_enabled()) { kvmppc_init(); diff --git a/hw/ppc/e500.h b/hw/ppc/e500.h index 52726a2ec0..9f61ab2b1c 100644 --- a/hw/ppc/e500.h +++ b/hw/ppc/e500.h @@ -11,8 +11,14 @@ typedef struct PPCE500Params { void (*fixup_devtree)(struct PPCE500Params *params, void *fdt); int mpic_version; + bool has_mpc8xxx_gpio; + bool has_platform_bus; + hwaddr platform_bus_base; + hwaddr platform_bus_size; + int platform_bus_first_irq; + int platform_bus_num_irqs; } PPCE500Params; -void ppce500_init(QEMUMachineInitArgs *args, PPCE500Params *params); +void ppce500_init(MachineState *machine, PPCE500Params *params); #endif diff --git a/hw/ppc/e500plat.c b/hw/ppc/e500plat.c index 7d5357e83b..d50ae000ee 100644 --- a/hw/ppc/e500plat.c +++ b/hw/ppc/e500plat.c @@ -28,13 +28,19 @@ static void e500plat_fixup_devtree(PPCE500Params *params, void *fdt) sizeof(compatible)); } -static void e500plat_init(QEMUMachineInitArgs *args) +static void e500plat_init(MachineState *machine) { PPCE500Params params = { .pci_first_slot = 0x1, .pci_nr_slots = PCI_SLOT_MAX - 1, .fixup_devtree = e500plat_fixup_devtree, .mpic_version = OPENPIC_MODEL_FSL_MPIC_42, + .has_mpc8xxx_gpio = true, + .has_platform_bus = true, + .platform_bus_base = 0xf00000000ULL, + .platform_bus_size = (128ULL * 1024 * 1024), + .platform_bus_first_irq = 5, + .platform_bus_num_irqs = 10, }; /* Older KVM versions don't support EPR which breaks guests when we announce @@ -43,7 +49,7 @@ static void e500plat_init(QEMUMachineInitArgs *args) params.mpic_version = OPENPIC_MODEL_FSL_MPIC_20; } - ppce500_init(args, ¶ms); + ppce500_init(machine, ¶ms); } static QEMUMachine e500plat_machine = { @@ -51,6 +57,7 @@ static QEMUMachine e500plat_machine = { .desc = "generic paravirt e500 platform", .init = e500plat_init, .max_cpus = 32, + .has_dynamic_sysbus = true, }; static void e500plat_machine_init(void) diff --git a/hw/ppc/mac.h b/hw/ppc/mac.h index c1faf9ce27..8bdba30c1e 100644 --- a/hw/ppc/mac.h +++ b/hw/ppc/mac.h @@ -57,6 +57,7 @@ typedef struct CUDATimer { uint16_t counter_value; int64_t load_time; int64_t next_irq_time; + uint64_t frequency; QEMUTimer *timer; } CUDATimer; @@ -97,6 +98,7 @@ typedef struct CUDAState { CUDATimer timers[2]; uint32_t tick_offset; + uint64_t frequency; uint8_t last_b; uint8_t last_acr; @@ -129,7 +131,7 @@ typedef struct MACIOIDEState { MemoryRegion mem; IDEBus bus; - BlockDriverAIOCB *aiocb; + BlockAIOCB *aiocb; IDEDMA dma; void *dbdma; bool dma_active; @@ -178,6 +180,4 @@ typedef struct MacIONVRAMState { } MacIONVRAMState; void pmac_format_nvram_partition (MacIONVRAMState *nvr, int len); -uint8_t macio_nvram_read(MacIONVRAMState *s, uint32_t addr); -void macio_nvram_write(MacIONVRAMState *s, uint32_t addr, uint8_t val); #endif /* !defined(__PPC_MAC_H__) */ diff --git a/hw/ppc/mac_newworld.c b/hw/ppc/mac_newworld.c index 5e79575165..89aee716d4 100644 --- a/hw/ppc/mac_newworld.c +++ b/hw/ppc/mac_newworld.c @@ -65,13 +65,15 @@ #include "sysemu/kvm.h" #include "kvm_ppc.h" #include "hw/usb.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "hw/sysbus.h" #define MAX_IDE_BUS 2 #define CFG_ADDR 0xf0000510 #define TBFREQ (100UL * 1000UL * 1000UL) +#define CLOCKFREQ (266UL * 1000UL * 1000UL) +#define BUSFREQ (100UL * 1000UL * 1000UL) /* debug UniNorth */ //#define DEBUG_UNIN @@ -140,14 +142,14 @@ static void ppc_core99_reset(void *opaque) } /* PowerPC Mac99 hardware initialisation */ -static void ppc_core99_init(QEMUMachineInitArgs *args) +static void ppc_core99_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; - const char *boot_device = args->boot_order; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; + const char *boot_device = machine->boot_order; PowerPCCPU *cpu = NULL; CPUPPCState *env = NULL; char *filename; @@ -174,6 +176,8 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) SysBusDevice *s; DeviceState *dev; int *token = g_new(int, 1); + hwaddr nvram_addr = 0xFFF04000; + uint64_t tbfreq; linux_boot = (kernel_filename != NULL); @@ -198,13 +202,14 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) } /* allocate RAM */ - memory_region_init_ram(ram, NULL, "ppc_core99.ram", ram_size); - vmstate_register_ram_global(ram); + memory_region_allocate_system_memory(ram, NULL, "ppc_core99.ram", ram_size); memory_region_add_subregion(get_system_memory(), 0, ram); /* allocate and load BIOS */ - memory_region_init_ram(bios, NULL, "ppc_core99.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "ppc_core99.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); + if (bios_name == NULL) bios_name = PROM_FILENAME; filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); @@ -344,7 +349,7 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) } } - pic = g_new(qemu_irq, 64); + pic = g_new0(qemu_irq, 64); dev = qdev_create(NULL, TYPE_OPENPIC); qdev_prop_set_uint32(dev, "model", OPENPIC_MODEL_RAVEN); @@ -370,19 +375,20 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) pci_bus = pci_pmac_init(pic, get_system_memory(), get_system_io()); machine_arch = ARCH_MAC99; } - /* init basic PC hardware */ - pci_vga_init(pci_bus); + /* Timebase Frequency */ + if (kvm_enabled()) { + tbfreq = kvmppc_get_tbfreq(); + } else { + tbfreq = TBFREQ; + } + + /* init basic PC hardware */ escc_mem = escc_init(0, pic[0x25], pic[0x24], serial_hds[0], serial_hds[1], ESCC_CLOCK, 4); memory_region_init_alias(escc_bar, NULL, "escc-bar", escc_mem, 0, memory_region_size(escc_mem)); - for(i = 0; i < nb_nics; i++) - pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL); - - ide_drive_get(hd, MAX_IDE_BUS); - macio = pci_create(pci_bus, -1, TYPE_NEWWORLD_MACIO); dev = DEVICE(macio); qdev_connect_gpio_out(dev, 0, pic[0x19]); /* CUDA */ @@ -390,9 +396,12 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE DMA */ qdev_connect_gpio_out(dev, 3, pic[0x0e]); /* IDE */ qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE DMA */ + qdev_prop_set_uint64(dev, "frequency", tbfreq); macio_init(macio, pic_mem, escc_bar); /* We only emulate 2 out of 3 IDE controllers for now */ + ide_drive_get(hd, ARRAY_SIZE(hd)); + macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio), "ide[0]")); macio_ide_init_drives(macio_ide, hd); @@ -418,15 +427,29 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) } } - if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8) + pci_vga_init(pci_bus); + + if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8) { graphic_depth = 15; + } + + for (i = 0; i < nb_nics; i++) { + pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL); + } /* The NewWorld NVRAM is not located in the MacIO device */ +#ifdef CONFIG_KVM + if (kvm_enabled() && getpagesize() > 4096) { + /* We can't combine read-write and read-only in a single page, so + move the NVRAM out of ROM again for KVM */ + nvram_addr = 0xFFE00000; + } +#endif dev = qdev_create(NULL, TYPE_MACIO_NVRAM); qdev_prop_set_uint32(dev, "size", 0x2000); qdev_prop_set_uint32(dev, "it_shift", 1); qdev_init_nofail(dev); - sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xFFF04000); + sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, nvram_addr); nvr = MACIO_NVRAM(dev); pmac_format_nvram_partition(nvr, 0x2000); /* No PCI init: the BIOS will do it */ @@ -457,27 +480,34 @@ static void ppc_core99_init(QEMUMachineInitArgs *args) #ifdef CONFIG_KVM uint8_t *hypercall; - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq()); hypercall = g_malloc(16); kvmppc_get_hypercall(env, hypercall, 16); fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16); fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid()); #endif - } else { - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, TBFREQ); } + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, tbfreq); /* Mac OS X requires a "known good" clock-frequency value; pass it one. */ - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, 266000000); + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, CLOCKFREQ); + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_BUSFREQ, BUSFREQ); + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_NVRAM_ADDR, nvram_addr); qemu_register_boot_set(fw_cfg_boot_set, fw_cfg); } +static int core99_kvm_type(const char *arg) +{ + /* Always force PR KVM */ + return 2; +} + static QEMUMachine core99_machine = { .name = "mac99", .desc = "Mac99 based PowerMAC", .init = ppc_core99_init, .max_cpus = MAX_CPUS, .default_boot_order = "cd", + .kvm_type = core99_kvm_type, }; static void core99_machine_init(void) diff --git a/hw/ppc/mac_oldworld.c b/hw/ppc/mac_oldworld.c index 2f27754c6c..32c21a4286 100644 --- a/hw/ppc/mac_oldworld.c +++ b/hw/ppc/mac_oldworld.c @@ -40,12 +40,14 @@ #include "elf.h" #include "sysemu/kvm.h" #include "kvm_ppc.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #define MAX_IDE_BUS 2 #define CFG_ADDR 0xf0000510 #define TBFREQ 16600000UL +#define CLOCKFREQ 266000000UL +#define BUSFREQ 66000000UL static int fw_cfg_boot_set(void *opaque, const char *boot_device) { @@ -71,14 +73,14 @@ static void ppc_heathrow_reset(void *opaque) cpu_reset(CPU(cpu)); } -static void ppc_heathrow_init(QEMUMachineInitArgs *args) +static void ppc_heathrow_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; - const char *boot_device = args->boot_order; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; + const char *boot_device = machine->boot_order; MemoryRegion *sysmem = get_system_memory(); PowerPCCPU *cpu = NULL; CPUPPCState *env = NULL; @@ -101,6 +103,7 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) uint16_t ppc_boot_device; DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS]; void *fw_cfg; + uint64_t tbfreq; linux_boot = (kernel_filename != NULL); @@ -128,13 +131,15 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) exit(1); } - memory_region_init_ram(ram, NULL, "ppc_heathrow.ram", ram_size); - vmstate_register_ram_global(ram); + memory_region_allocate_system_memory(ram, NULL, "ppc_heathrow.ram", + ram_size); memory_region_add_subregion(sysmem, 0, ram); /* allocate and load BIOS */ - memory_region_init_ram(bios, NULL, "ppc_heathrow.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "ppc_heathrow.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); + if (bios_name == NULL) bios_name = PROM_FILENAME; filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); @@ -247,6 +252,13 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) } } + /* Timebase Frequency */ + if (kvm_enabled()) { + tbfreq = kvmppc_get_tbfreq(); + } else { + tbfreq = TBFREQ; + } + /* init basic PC hardware */ if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) { hw_error("Only 6xx bus is supported on heathrow machine\n"); @@ -266,7 +278,7 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL); - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); macio = pci_create(pci_bus, -1, TYPE_OLDWORLD_MACIO); dev = DEVICE(macio); @@ -275,6 +287,7 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE-0 DMA */ qdev_connect_gpio_out(dev, 3, pic[0x0E]); /* IDE-1 */ qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE-1 DMA */ + qdev_prop_set_uint64(dev, "frequency", tbfreq); macio_init(macio, pic_mem, escc_bar); macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio), @@ -327,21 +340,26 @@ static void ppc_heathrow_init(QEMUMachineInitArgs *args) #ifdef CONFIG_KVM uint8_t *hypercall; - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq()); hypercall = g_malloc(16); kvmppc_get_hypercall(env, hypercall, 16); fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16); fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid()); #endif - } else { - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, TBFREQ); } + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, tbfreq); /* Mac OS X requires a "known good" clock-frequency value; pass it one. */ - fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, 266000000); + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, CLOCKFREQ); + fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_BUSFREQ, BUSFREQ); qemu_register_boot_set(fw_cfg_boot_set, fw_cfg); } +static int heathrow_kvm_type(const char *arg) +{ + /* Always force PR KVM */ + return 2; +} + static QEMUMachine heathrow_machine = { .name = "g3beige", .desc = "Heathrow based PowerMAC", @@ -351,6 +369,7 @@ static QEMUMachine heathrow_machine = { .is_default = 1, #endif .default_boot_order = "cd", /* TOFIX "cad" when Mac floppy is implemented */ + .kvm_type = heathrow_kvm_type, }; static void heathrow_machine_init(void) diff --git a/hw/ppc/mpc8544ds.c b/hw/ppc/mpc8544ds.c index 292c70953b..b99f74af75 100644 --- a/hw/ppc/mpc8544ds.c +++ b/hw/ppc/mpc8544ds.c @@ -26,7 +26,7 @@ static void mpc8544ds_fixup_devtree(PPCE500Params *params, void *fdt) sizeof(compatible)); } -static void mpc8544ds_init(QEMUMachineInitArgs *args) +static void mpc8544ds_init(MachineState *machine) { PPCE500Params params = { .pci_first_slot = 0x11, @@ -35,7 +35,7 @@ static void mpc8544ds_init(QEMUMachineInitArgs *args) .mpic_version = OPENPIC_MODEL_FSL_MPIC_20, }; - ppce500_init(args, ¶ms); + ppce500_init(machine, ¶ms); } diff --git a/hw/ppc/ppc.c b/hw/ppc/ppc.c index 71df471746..bec82cd7a9 100644 --- a/hw/ppc/ppc.c +++ b/hw/ppc/ppc.c @@ -29,9 +29,11 @@ #include "sysemu/cpus.h" #include "hw/timer/m48t59.h" #include "qemu/log.h" +#include "qemu/error-report.h" #include "hw/loader.h" #include "sysemu/kvm.h" #include "kvm_ppc.h" +#include "trace.h" //#define PPC_DEBUG_IRQ //#define PPC_DEBUG_TB @@ -49,6 +51,8 @@ # define LOG_TB(...) do { } while (0) #endif +#define NSEC_PER_SEC 1000000000LL + static void cpu_ppc_tb_stop (CPUPPCState *env); static void cpu_ppc_tb_start (CPUPPCState *env); @@ -829,6 +833,81 @@ static void cpu_ppc_set_tb_clk (void *opaque, uint32_t freq) cpu_ppc_store_purr(cpu, 0x0000000000000000ULL); } +static void timebase_pre_save(void *opaque) +{ + PPCTimebase *tb = opaque; + uint64_t ticks = cpu_get_real_ticks(); + PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu); + + if (!first_ppc_cpu->env.tb_env) { + error_report("No timebase object"); + return; + } + + tb->time_of_the_day_ns = get_clock_realtime(); + /* + * tb_offset is only expected to be changed by migration so + * there is no need to update it from KVM here + */ + tb->guest_timebase = ticks + first_ppc_cpu->env.tb_env->tb_offset; +} + +static int timebase_post_load(void *opaque, int version_id) +{ + PPCTimebase *tb_remote = opaque; + CPUState *cpu; + PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu); + int64_t tb_off_adj, tb_off, ns_diff; + int64_t migration_duration_ns, migration_duration_tb, guest_tb, host_ns; + unsigned long freq; + + if (!first_ppc_cpu->env.tb_env) { + error_report("No timebase object"); + return -1; + } + + freq = first_ppc_cpu->env.tb_env->tb_freq; + /* + * Calculate timebase on the destination side of migration. + * The destination timebase must be not less than the source timebase. + * We try to adjust timebase by downtime if host clocks are not + * too much out of sync (1 second for now). + */ + host_ns = get_clock_realtime(); + ns_diff = MAX(0, host_ns - tb_remote->time_of_the_day_ns); + migration_duration_ns = MIN(NSEC_PER_SEC, ns_diff); + migration_duration_tb = muldiv64(migration_duration_ns, freq, NSEC_PER_SEC); + guest_tb = tb_remote->guest_timebase + MIN(0, migration_duration_tb); + + tb_off_adj = guest_tb - cpu_get_real_ticks(); + + tb_off = first_ppc_cpu->env.tb_env->tb_offset; + trace_ppc_tb_adjust(tb_off, tb_off_adj, tb_off_adj - tb_off, + (tb_off_adj - tb_off) / freq); + + /* Set new offset to all CPUs */ + CPU_FOREACH(cpu) { + PowerPCCPU *pcpu = POWERPC_CPU(cpu); + pcpu->env.tb_env->tb_offset = tb_off_adj; + } + + return 0; +} + +const VMStateDescription vmstate_ppc_timebase = { + .name = "timebase", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .pre_save = timebase_pre_save, + .post_load = timebase_post_load, + .fields = (VMStateField []) { + VMSTATE_UINT64(guest_timebase, PPCTimebase), + VMSTATE_INT64(time_of_the_day_ns, PPCTimebase), + VMSTATE_END_OF_LIST() + }, +}; + /* Set up (once) timebase frequency (in Hz) */ clk_setup_cb cpu_ppc_tb_init (CPUPPCState *env, uint32_t freq) { diff --git a/hw/ppc/ppc405_boards.c b/hw/ppc/ppc405_boards.c index f1a8f6734a..1dcea7730e 100644 --- a/hw/ppc/ppc405_boards.c +++ b/hw/ppc/ppc405_boards.c @@ -28,11 +28,12 @@ #include "hw/block/flash.h" #include "sysemu/sysemu.h" #include "sysemu/qtest.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/boards.h" #include "qemu/log.h" #include "qemu/error-report.h" #include "hw/loader.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "exec/address-spaces.h" @@ -172,12 +173,12 @@ static void ref405ep_fpga_init(MemoryRegion *sysmem, uint32_t base) qemu_register_reset(&ref405ep_fpga_reset, fpga); } -static void ref405ep_init(QEMUMachineInitArgs *args) +static void ref405ep_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; char *filename; ppc4xx_bd_info_t bd; CPUPPCState *env; @@ -199,8 +200,8 @@ static void ref405ep_init(QEMUMachineInitArgs *args) MemoryRegion *sysmem = get_system_memory(); /* XXX: fix this */ - memory_region_init_ram(&ram_memories[0], NULL, "ef405ep.ram", 0x08000000); - vmstate_register_ram_global(&ram_memories[0]); + memory_region_allocate_system_memory(&ram_memories[0], NULL, "ef405ep.ram", + 0x08000000); ram_bases[0] = 0; ram_sizes[0] = 0x08000000; memory_region_init(&ram_memories[1], NULL, "ef405ep.ram1", 0); @@ -214,7 +215,7 @@ static void ref405ep_init(QEMUMachineInitArgs *args) 33333333, &pic, kernel_filename == NULL ? 0 : 1); /* allocate SRAM */ sram_size = 512 * 1024; - memory_region_init_ram(sram, NULL, "ef405ep.sram", sram_size); + memory_region_init_ram(sram, NULL, "ef405ep.sram", sram_size, &error_abort); vmstate_register_ram_global(sram); memory_region_add_subregion(sysmem, 0xFFF00000, sram); /* allocate and load BIOS */ @@ -225,17 +226,19 @@ static void ref405ep_init(QEMUMachineInitArgs *args) #ifdef USE_FLASH_BIOS dinfo = drive_get(IF_PFLASH, 0, fl_idx); if (dinfo) { - bios_size = bdrv_getlength(dinfo->bdrv); + BlockBackend *blk = blk_by_legacy_dinfo(dinfo); + + bios_size = blk_getlength(blk); fl_sectors = (bios_size + 65535) >> 16; #ifdef DEBUG_BOARD_INIT printf("Register parallel flash %d size %lx" " at addr %lx '%s' %d\n", fl_idx, bios_size, -bios_size, - bdrv_get_device_name(dinfo->bdrv), fl_sectors); + blk_name(blk), fl_sectors); #endif pflash_cfi02_register((uint32_t)(-bios_size), NULL, "ef405ep.bios", bios_size, - dinfo->bdrv, 65536, fl_sectors, 1, + blk, 65536, fl_sectors, 1, 2, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA, 1); fl_idx++; @@ -246,8 +249,10 @@ static void ref405ep_init(QEMUMachineInitArgs *args) printf("Load BIOS from file\n"); #endif bios = g_new(MemoryRegion, 1); - memory_region_init_ram(bios, NULL, "ef405ep.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "ef405ep.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); + if (bios_name == NULL) bios_name = BIOS_FILENAME; filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); @@ -499,16 +504,17 @@ static void taihu_cpld_init(MemoryRegion *sysmem, uint32_t base) qemu_register_reset(&taihu_cpld_reset, cpld); } -static void taihu_405ep_init(QEMUMachineInitArgs *args) +static void taihu_405ep_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *kernel_filename = args->kernel_filename; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *kernel_filename = machine->kernel_filename; + const char *initrd_filename = machine->initrd_filename; char *filename; qemu_irq *pic; MemoryRegion *sysmem = get_system_memory(); MemoryRegion *bios; MemoryRegion *ram_memories = g_malloc(2 * sizeof(*ram_memories)); + MemoryRegion *ram = g_malloc0(sizeof(*ram)); hwaddr ram_bases[2], ram_sizes[2]; long bios_size; target_ulong kernel_base, initrd_base; @@ -518,17 +524,20 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) DriveInfo *dinfo; /* RAM is soldered to the board so the size cannot be changed */ - memory_region_init_ram(&ram_memories[0], NULL, - "taihu_405ep.ram-0", 0x04000000); - vmstate_register_ram_global(&ram_memories[0]); + ram_size = 0x08000000; + memory_region_allocate_system_memory(ram, NULL, "taihu_405ep.ram", + ram_size); + ram_bases[0] = 0; ram_sizes[0] = 0x04000000; - memory_region_init_ram(&ram_memories[1], NULL, - "taihu_405ep.ram-1", 0x04000000); - vmstate_register_ram_global(&ram_memories[1]); + memory_region_init_alias(&ram_memories[0], NULL, + "taihu_405ep.ram-0", ram, ram_bases[0], + ram_sizes[0]); ram_bases[1] = 0x04000000; ram_sizes[1] = 0x04000000; - ram_size = 0x08000000; + memory_region_init_alias(&ram_memories[1], NULL, + "taihu_405ep.ram-1", ram, ram_bases[1], + ram_sizes[1]); #ifdef DEBUG_BOARD_INIT printf("%s: register cpu\n", __func__); #endif @@ -542,7 +551,9 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) #if defined(USE_FLASH_BIOS) dinfo = drive_get(IF_PFLASH, 0, fl_idx); if (dinfo) { - bios_size = bdrv_getlength(dinfo->bdrv); + BlockBackend *blk = blk_by_legacy_dinfo(dinfo); + + bios_size = blk_getlength(blk); /* XXX: should check that size is 2MB */ // bios_size = 2 * 1024 * 1024; fl_sectors = (bios_size + 65535) >> 16; @@ -550,11 +561,11 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) printf("Register parallel flash %d size %lx" " at addr %lx '%s' %d\n", fl_idx, bios_size, -bios_size, - bdrv_get_device_name(dinfo->bdrv), fl_sectors); + blk_name(blk), fl_sectors); #endif pflash_cfi02_register((uint32_t)(-bios_size), NULL, "taihu_405ep.bios", bios_size, - dinfo->bdrv, 65536, fl_sectors, 1, + blk, 65536, fl_sectors, 1, 4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA, 1); fl_idx++; @@ -567,7 +578,8 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) if (bios_name == NULL) bios_name = BIOS_FILENAME; bios = g_new(MemoryRegion, 1); - memory_region_init_ram(bios, NULL, "taihu_405ep.bios", BIOS_SIZE); + memory_region_init_ram(bios, NULL, "taihu_405ep.bios", BIOS_SIZE, + &error_abort); vmstate_register_ram_global(bios); filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name); if (filename) { @@ -588,7 +600,9 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) /* Register Linux flash */ dinfo = drive_get(IF_PFLASH, 0, fl_idx); if (dinfo) { - bios_size = bdrv_getlength(dinfo->bdrv); + BlockBackend *blk = blk_by_legacy_dinfo(dinfo); + + bios_size = blk_getlength(blk); /* XXX: should check that size is 32MB */ bios_size = 32 * 1024 * 1024; fl_sectors = (bios_size + 65535) >> 16; @@ -596,10 +610,10 @@ static void taihu_405ep_init(QEMUMachineInitArgs *args) printf("Register parallel flash %d size %lx" " at addr " TARGET_FMT_lx " '%s'\n", fl_idx, bios_size, (target_ulong)0xfc000000, - bdrv_get_device_name(dinfo->bdrv)); + blk_name(blk)); #endif pflash_cfi02_register(0xfc000000, NULL, "taihu_405ep.flash", bios_size, - dinfo->bdrv, 65536, fl_sectors, 1, + blk, 65536, fl_sectors, 1, 4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA, 1); fl_idx++; diff --git a/hw/ppc/ppc405_uc.c b/hw/ppc/ppc405_uc.c index 54ba59e73a..c77434ae05 100644 --- a/hw/ppc/ppc405_uc.c +++ b/hw/ppc/ppc405_uc.c @@ -23,6 +23,7 @@ */ #include "hw/hw.h" #include "hw/ppc/ppc.h" +#include "hw/boards.h" #include "ppc405.h" #include "hw/char/serial.h" #include "qemu/timer.h" @@ -973,7 +974,8 @@ static void ppc405_ocm_init(CPUPPCState *env) ocm = g_malloc0(sizeof(ppc405_ocm_t)); /* XXX: Size is 4096 or 0x04000000 */ - memory_region_init_ram(&ocm->isarc_ram, NULL, "ppc405.ocm", 4096); + memory_region_init_ram(&ocm->isarc_ram, NULL, "ppc405.ocm", 4096, + &error_abort); vmstate_register_ram_global(&ocm->isarc_ram); memory_region_init_alias(&ocm->dsarc_ram, NULL, "ppc405.dsarc", &ocm->isarc_ram, 0, 4096); diff --git a/hw/ppc/ppc440_bamboo.c b/hw/ppc/ppc440_bamboo.c index 2ddc2ed4b9..778970aa9b 100644 --- a/hw/ppc/ppc440_bamboo.c +++ b/hw/ppc/ppc440_bamboo.c @@ -156,13 +156,13 @@ static void main_cpu_reset(void *opaque) mmubooke_create_initial_mapping(env, 0, 0); } -static void bamboo_init(QEMUMachineInitArgs *args) +static void bamboo_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; unsigned int pci_irq_nrs[4] = { 28, 27, 26, 25 }; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *isa = g_new(MemoryRegion, 1); @@ -253,7 +253,8 @@ static void bamboo_init(QEMUMachineInitArgs *args) /* Load kernel. */ if (kernel_filename) { - success = load_uimage(kernel_filename, &entry, &loadaddr, NULL); + success = load_uimage(kernel_filename, &entry, &loadaddr, NULL, + NULL, NULL); if (success < 0) { success = load_elf(kernel_filename, NULL, NULL, &elf_entry, &elf_lowaddr, NULL, 1, ELF_MACHINE, 0); diff --git a/hw/ppc/ppc4xx_devs.c b/hw/ppc/ppc4xx_devs.c index 8a43111a51..2f38ff7d26 100644 --- a/hw/ppc/ppc4xx_devs.c +++ b/hw/ppc/ppc4xx_devs.c @@ -24,6 +24,7 @@ #include "hw/hw.h" #include "hw/ppc/ppc.h" #include "hw/ppc/ppc4xx.h" +#include "hw/boards.h" #include "qemu/log.h" #include "exec/address-spaces.h" @@ -421,7 +422,7 @@ static void sdram_set_bcr(ppc4xx_sdram_t *sdram, &sdram->containers[n]); memory_region_del_subregion(&sdram->containers[n], &sdram->ram_memories[n]); - memory_region_destroy(&sdram->containers[n]); + object_unparent(OBJECT(&sdram->containers[n])); } *bcrp = bcr & 0xFFDEE001; if (enabled && (bcr & 0x00000001)) { @@ -682,28 +683,20 @@ ram_addr_t ppc4xx_sdram_adjust(ram_addr_t ram_size, int nr_banks, hwaddr ram_sizes[], const unsigned int sdram_bank_sizes[]) { + MemoryRegion *ram = g_malloc0(sizeof(*ram)); ram_addr_t size_left = ram_size; ram_addr_t base = 0; + unsigned int bank_size; int i; int j; for (i = 0; i < nr_banks; i++) { for (j = 0; sdram_bank_sizes[j] != 0; j++) { - unsigned int bank_size = sdram_bank_sizes[j]; - + bank_size = sdram_bank_sizes[j]; if (bank_size <= size_left) { - char name[32]; - snprintf(name, sizeof(name), "ppc4xx.sdram%d", i); - memory_region_init_ram(&ram_memories[i], NULL, name, bank_size); - vmstate_register_ram_global(&ram_memories[i]); - ram_bases[i] = base; - ram_sizes[i] = bank_size; - base += bank_size; size_left -= bank_size; - break; } } - if (!size_left) { /* No need to use the remaining banks. */ break; @@ -711,9 +704,31 @@ ram_addr_t ppc4xx_sdram_adjust(ram_addr_t ram_size, int nr_banks, } ram_size -= size_left; - if (size_left) + if (size_left) { printf("Truncating memory to %d MiB to fit SDRAM controller limits.\n", (int)(ram_size >> 20)); + } + + memory_region_allocate_system_memory(ram, NULL, "ppc4xx.sdram", ram_size); + + size_left = ram_size; + for (i = 0; i < nr_banks && size_left; i++) { + for (j = 0; sdram_bank_sizes[j] != 0; j++) { + bank_size = sdram_bank_sizes[j]; + + if (bank_size <= size_left) { + char name[32]; + snprintf(name, sizeof(name), "ppc4xx.sdram%d", i); + memory_region_init_alias(&ram_memories[i], NULL, name, ram, + base, bank_size); + ram_bases[i] = base; + ram_sizes[i] = bank_size; + base += bank_size; + size_left -= bank_size; + break; + } + } + } return ram_size; } diff --git a/hw/ppc/ppc4xx_pci.c b/hw/ppc/ppc4xx_pci.c index 4cb78518a3..0bb3cdb46e 100644 --- a/hw/ppc/ppc4xx_pci.c +++ b/hw/ppc/ppc4xx_pci.c @@ -92,30 +92,6 @@ typedef struct PPC4xxPCIState PPC4xxPCIState; #define PCI_ALL_SIZE (PCI_REG_BASE + PCI_REG_SIZE) -static uint64_t pci4xx_cfgaddr_read(void *opaque, hwaddr addr, - unsigned size) -{ - PPC4xxPCIState *ppc4xx_pci = opaque; - PCIHostState *phb = PCI_HOST_BRIDGE(ppc4xx_pci); - - return phb->config_reg; -} - -static void pci4xx_cfgaddr_write(void *opaque, hwaddr addr, - uint64_t value, unsigned size) -{ - PPC4xxPCIState *ppc4xx_pci = opaque; - PCIHostState *phb = PCI_HOST_BRIDGE(ppc4xx_pci); - - phb->config_reg = value & ~0x3; -} - -static const MemoryRegionOps pci4xx_cfgaddr_ops = { - .read = pci4xx_cfgaddr_read, - .write = pci4xx_cfgaddr_write, - .endianness = DEVICE_LITTLE_ENDIAN, -}; - static void ppc4xx_pci_reg_write4(void *opaque, hwaddr offset, uint64_t value, unsigned size) { @@ -294,8 +270,7 @@ static const VMStateDescription vmstate_pci_master_map = { .name = "pci_master_map", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(la, struct PCIMasterMap), VMSTATE_UINT32(ma, struct PCIMasterMap), VMSTATE_UINT32(pcila, struct PCIMasterMap), @@ -308,8 +283,7 @@ static const VMStateDescription vmstate_pci_target_map = { .name = "pci_target_map", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(ms, struct PCITargetMap), VMSTATE_UINT32(la, struct PCITargetMap), VMSTATE_END_OF_LIST() @@ -320,8 +294,7 @@ static const VMStateDescription vmstate_ppc4xx_pci = { .name = "ppc4xx_pci", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(pmm, PPC4xxPCIState, PPC4xx_PCI_NR_PMMS, 1, vmstate_pci_master_map, struct PCIMasterMap), diff --git a/hw/ppc/prep.c b/hw/ppc/prep.c index e2436512f7..dd8433d0c9 100644 --- a/hw/ppc/prep.c +++ b/hw/ppc/prep.c @@ -38,7 +38,7 @@ #include "hw/loader.h" #include "hw/timer/mc146818rtc.h" #include "hw/isa/pc87312.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "sysemu/arch_init.h" #include "sysemu/qtest.h" #include "exec/address-spaces.h" @@ -346,9 +346,6 @@ static void ppc_prep_reset(void *opaque) PowerPCCPU *cpu = opaque; cpu_reset(CPU(cpu)); - - /* Reset address */ - cpu->env.nip = 0xfffffffc; } static const MemoryRegionPortio prep_portio_list[] = { @@ -361,27 +358,27 @@ static const MemoryRegionPortio prep_portio_list[] = { PORTIO_END_OF_LIST(), }; +static PortioList prep_port_list; + /* PowerPC PREP hardware initialisation */ -static void ppc_prep_init(QEMUMachineInitArgs *args) +static void ppc_prep_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; - const char *boot_device = args->boot_order; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; + const char *boot_device = machine->boot_order; MemoryRegion *sysmem = get_system_memory(); PowerPCCPU *cpu = NULL; CPUPPCState *env = NULL; nvram_t nvram; M48t59State *m48t59; - PortioList *port_list = g_new(PortioList, 1); #if 0 MemoryRegion *xcsr = g_new(MemoryRegion, 1); #endif int linux_boot, i, nb_nics1; MemoryRegion *ram = g_new(MemoryRegion, 1); - MemoryRegion *vga = g_new(MemoryRegion, 1); uint32_t kernel_base, initrd_base; long kernel_size, initrd_size; DeviceState *dev; @@ -420,8 +417,7 @@ static void ppc_prep_init(QEMUMachineInitArgs *args) } /* allocate RAM */ - memory_region_init_ram(ram, NULL, "ppc_prep.ram", ram_size); - vmstate_register_ram_global(ram); + memory_region_allocate_system_memory(ram, NULL, "ppc_prep.ram", ram_size); memory_region_add_subregion(sysmem, 0, ram); if (linux_boot) { @@ -507,14 +503,6 @@ static void ppc_prep_init(QEMUMachineInitArgs *args) /* init basic PC hardware */ pci_vga_init(pci_bus); - /* Open Hack'Ware hack: PCI BAR#0 is programmed to 0xf0000000. - * While bios will access framebuffer at 0xf0000000, real physical - * address is 0xf0000000 + 0xc0000000 (PCI memory base). - * Alias the wrong memory accesses to the right place. - */ - memory_region_init_alias(vga, NULL, "vga-alias", pci_address_space(pci), - 0xf0000000, 0x1000000); - memory_region_add_subregion_overlap(sysmem, 0xf0000000, vga, 10); nb_nics1 = nb_nics; if (nb_nics1 > NE2000_NB_MAX) @@ -531,7 +519,7 @@ static void ppc_prep_init(QEMUMachineInitArgs *args) } } - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); for(i = 0; i < MAX_IDE_BUS; i++) { isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i], hd[2 * i], @@ -542,8 +530,8 @@ static void ppc_prep_init(QEMUMachineInitArgs *args) cpu = POWERPC_CPU(first_cpu); sysctrl->reset_irq = cpu->env.irq_inputs[PPC6xx_INPUT_HRESET]; - portio_list_init(port_list, NULL, prep_portio_list, sysctrl, "prep"); - portio_list_add(port_list, isa_address_space_io(isa), 0x0); + portio_list_init(&prep_port_list, NULL, prep_portio_list, sysctrl, "prep"); + portio_list_add(&prep_port_list, isa_address_space_io(isa), 0x0); /* PowerPC control and status register group */ #if 0 diff --git a/hw/ppc/spapr.c b/hw/ppc/spapr.c index a11e1217b9..30de25de5c 100644 --- a/hw/ppc/spapr.c +++ b/hw/ppc/spapr.c @@ -29,11 +29,12 @@ #include "hw/fw-path-provider.h" #include "elf.h" #include "net/net.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "sysemu/cpus.h" #include "sysemu/kvm.h" #include "kvm_ppc.h" #include "mmu-hash64.h" +#include "qom/cpu.h" #include "hw/boards.h" #include "hw/ppc/ppc.h" @@ -53,6 +54,10 @@ #include "hw/usb.h" #include "qemu/config-file.h" #include "qemu/error-report.h" +#include "trace.h" +#include "hw/nmi.h" + +#include "hw/compat.h" #include <libfdt.h> @@ -68,6 +73,7 @@ */ #define FDT_MAX_SIZE 0x40000 #define RTAS_MAX_SIZE 0x10000 +#define RTAS_MAX_ADDR 0x80000000 /* RTAS must stay below that */ #define FW_MAX_SIZE 0x400000 #define FW_FILE_NAME "slof.bin" #define FW_OVERHEAD 0x2800000 @@ -77,83 +83,30 @@ #define TIMEBASE_FREQ 512000000ULL -#define MAX_CPUS 256 -#define XICS_IRQS 1024 +#define MAX_CPUS 255 #define PHANDLE_XICP 0x00001111 #define HTAB_SIZE(spapr) (1ULL << ((spapr)->htab_shift)) -#define TYPE_SPAPR_MACHINE "spapr-machine" - -sPAPREnvironment *spapr; - -int spapr_allocate_irq(int hint, bool lsi) -{ - int irq; - - if (hint) { - irq = hint; - if (hint >= spapr->next_irq) { - spapr->next_irq = hint + 1; - } - /* FIXME: we should probably check for collisions somehow */ - } else { - irq = spapr->next_irq++; - } +typedef struct sPAPRMachineState sPAPRMachineState; - /* Configure irq type */ - if (!xics_get_qirq(spapr->icp, irq)) { - return 0; - } - - xics_set_irq_type(spapr->icp, irq, lsi); - - return irq; -} +#define TYPE_SPAPR_MACHINE "spapr-machine" +#define SPAPR_MACHINE(obj) \ + OBJECT_CHECK(sPAPRMachineState, (obj), TYPE_SPAPR_MACHINE) -/* - * Allocate block of consequtive IRQs, returns a number of the first. - * If msi==true, aligns the first IRQ number to num. +/** + * sPAPRMachineState: */ -int spapr_allocate_irq_block(int num, bool lsi, bool msi) -{ - int first = -1; - int i, hint = 0; - - /* - * MSIMesage::data is used for storing VIRQ so - * it has to be aligned to num to support multiple - * MSI vectors. MSI-X is not affected by this. - * The hint is used for the first IRQ, the rest should - * be allocated continuously. - */ - if (msi) { - assert((num == 1) || (num == 2) || (num == 4) || - (num == 8) || (num == 16) || (num == 32)); - hint = (spapr->next_irq + num - 1) & ~(num - 1); - } - - for (i = 0; i < num; ++i) { - int irq; +struct sPAPRMachineState { + /*< private >*/ + MachineState parent_obj; - irq = spapr_allocate_irq(hint, lsi); - if (!irq) { - return -1; - } - - if (0 == i) { - first = irq; - hint = 0; - } - - /* If the above doesn't create a consecutive block then that's - * an internal bug */ - assert(irq == (first + i)); - } + /*< public >*/ + char *kvm_type; +}; - return first; -} +sPAPREnvironment *spapr; static XICSState *try_create_xics(const char *type, int nr_servers, int nr_irqs) @@ -202,34 +155,78 @@ static XICSState *xics_system_init(int nr_servers, int nr_irqs) return icp; } +static int spapr_fixup_cpu_smt_dt(void *fdt, int offset, PowerPCCPU *cpu, + int smt_threads) +{ + int i, ret = 0; + uint32_t servers_prop[smt_threads]; + uint32_t gservers_prop[smt_threads * 2]; + int index = ppc_get_vcpu_dt_id(cpu); + + if (cpu->cpu_version) { + ret = fdt_setprop_cell(fdt, offset, "cpu-version", cpu->cpu_version); + if (ret < 0) { + return ret; + } + } + + /* Build interrupt servers and gservers properties */ + for (i = 0; i < smt_threads; i++) { + servers_prop[i] = cpu_to_be32(index + i); + /* Hack, direct the group queues back to cpu 0 */ + gservers_prop[i*2] = cpu_to_be32(index + i); + gservers_prop[i*2 + 1] = 0; + } + ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-server#s", + servers_prop, sizeof(servers_prop)); + if (ret < 0) { + return ret; + } + ret = fdt_setprop(fdt, offset, "ibm,ppc-interrupt-gserver#s", + gservers_prop, sizeof(gservers_prop)); + + return ret; +} + static int spapr_fixup_cpu_dt(void *fdt, sPAPREnvironment *spapr) { - int ret = 0, offset; - CPUState *cpu; + int ret = 0, offset, cpus_offset; + CPUState *cs; char cpu_model[32]; int smt = kvmppc_smt_threads(); uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)}; - CPU_FOREACH(cpu) { - DeviceClass *dc = DEVICE_GET_CLASS(cpu); - int index = ppc_get_vcpu_dt_id(POWERPC_CPU(cpu)); + CPU_FOREACH(cs) { + PowerPCCPU *cpu = POWERPC_CPU(cs); + DeviceClass *dc = DEVICE_GET_CLASS(cs); + int index = ppc_get_vcpu_dt_id(cpu); uint32_t associativity[] = {cpu_to_be32(0x5), cpu_to_be32(0x0), cpu_to_be32(0x0), cpu_to_be32(0x0), - cpu_to_be32(cpu->numa_node), + cpu_to_be32(cs->numa_node), cpu_to_be32(index)}; if ((index % smt) != 0) { continue; } - snprintf(cpu_model, 32, "/cpus/%s@%x", dc->fw_name, - index); + snprintf(cpu_model, 32, "%s@%x", dc->fw_name, index); - offset = fdt_path_offset(fdt, cpu_model); + cpus_offset = fdt_path_offset(fdt, "/cpus"); + if (cpus_offset < 0) { + cpus_offset = fdt_add_subnode(fdt, fdt_path_offset(fdt, "/"), + "cpus"); + if (cpus_offset < 0) { + return cpus_offset; + } + } + offset = fdt_subnode_offset(fdt, cpus_offset, cpu_model); if (offset < 0) { - return offset; + offset = fdt_add_subnode(fdt, cpus_offset, cpu_model); + if (offset < 0) { + return offset; + } } if (nb_numa_nodes > 1) { @@ -245,6 +242,12 @@ static int spapr_fixup_cpu_dt(void *fdt, sPAPREnvironment *spapr) if (ret < 0) { return ret; } + + ret = spapr_fixup_cpu_smt_dt(fdt, offset, cpu, + ppc_get_compat_smt_threads(cpu)); + if (ret < 0) { + return ret; + } } return ret; } @@ -283,6 +286,19 @@ static size_t create_page_sizes_prop(CPUPPCState *env, uint32_t *prop, return (p - prop) * sizeof(uint32_t); } +static hwaddr spapr_node0_size(void) +{ + if (nb_numa_nodes) { + int i; + for (i = 0; i < nb_numa_nodes; ++i) { + if (numa_info[i].node_mem) { + return MIN(pow2floor(numa_info[i].node_mem), ram_size); + } + } + } + return ram_size; +} + #define _FDT(exp) \ do { \ int ret = (exp); \ @@ -293,6 +309,10 @@ static size_t create_page_sizes_prop(CPUPPCState *env, uint32_t *prop, } \ } while (0) +static void add_str(GString *s, const gchar *s1) +{ + g_string_append_len(s, s1, strlen(s1) + 1); +} static void *spapr_create_fdt_skel(hwaddr initrd_base, hwaddr initrd_size, @@ -306,13 +326,27 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, CPUState *cs; uint32_t start_prop = cpu_to_be32(initrd_base); uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size); - char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt" - "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk\0hcall-set-mode"; - char qemu_hypertas_prop[] = "hcall-memop1"; + GString *hypertas = g_string_sized_new(256); + GString *qemu_hypertas = g_string_sized_new(256); uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)}; uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)}; - int i, smt = kvmppc_smt_threads(); + int smt = kvmppc_smt_threads(); unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80}; + QemuOpts *opts = qemu_opts_find(qemu_find_opts("smp-opts"), NULL); + unsigned sockets = opts ? qemu_opt_get_number(opts, "sockets", 0) : 0; + uint32_t cpus_per_socket = sockets ? (smp_cpus / sockets) : 1; + char *buf; + + add_str(hypertas, "hcall-pft"); + add_str(hypertas, "hcall-term"); + add_str(hypertas, "hcall-dabr"); + add_str(hypertas, "hcall-interrupt"); + add_str(hypertas, "hcall-tce"); + add_str(hypertas, "hcall-vio"); + add_str(hypertas, "hcall-splpar"); + add_str(hypertas, "hcall-bulk"); + add_str(hypertas, "hcall-set-mode"); + add_str(qemu_hypertas, "hcall-memop1"); fdt = g_malloc0(FDT_MAX_SIZE); _FDT((fdt_create(fdt, FDT_MAX_SIZE))); @@ -331,6 +365,29 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)"))); _FDT((fdt_property_string(fdt, "compatible", "qemu,pseries"))); + /* + * Add info to guest to indentify which host is it being run on + * and what is the uuid of the guest + */ + if (kvmppc_get_host_model(&buf)) { + _FDT((fdt_property_string(fdt, "host-model", buf))); + g_free(buf); + } + if (kvmppc_get_host_serial(&buf)) { + _FDT((fdt_property_string(fdt, "host-serial", buf))); + g_free(buf); + } + + buf = g_strdup_printf(UUID_FMT, qemu_uuid[0], qemu_uuid[1], + qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], + qemu_uuid[5], qemu_uuid[6], qemu_uuid[7], + qemu_uuid[8], qemu_uuid[9], qemu_uuid[10], + qemu_uuid[11], qemu_uuid[12], qemu_uuid[13], + qemu_uuid[14], qemu_uuid[15]); + + _FDT((fdt_property_string(fdt, "vm,uuid", buf))); + g_free(buf); + _FDT((fdt_property_cell(fdt, "#address-cells", 0x2))); _FDT((fdt_property_cell(fdt, "#size-cells", 0x2))); @@ -357,6 +414,9 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, if (boot_device) { _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device))); } + if (boot_menu) { + _FDT((fdt_property_cell(fdt, "qemu,boot-menu", boot_menu))); + } _FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width))); _FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height))); _FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth))); @@ -375,8 +435,6 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, DeviceClass *dc = DEVICE_GET_CLASS(cs); PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs); int index = ppc_get_vcpu_dt_id(cpu); - uint32_t servers_prop[smp_threads]; - uint32_t gservers_prop[smp_threads * 2]; char *nodename; uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40), 0xffffffff, 0xffffffff}; @@ -425,18 +483,6 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, _FDT((fdt_property_string(fdt, "status", "okay"))); _FDT((fdt_property(fdt, "64-bit", NULL, 0))); - /* Build interrupt servers and gservers properties */ - for (i = 0; i < smp_threads; i++) { - servers_prop[i] = cpu_to_be32(index + i); - /* Hack, direct the group queues back to cpu 0 */ - gservers_prop[i*2] = cpu_to_be32(index + i); - gservers_prop[i*2 + 1] = 0; - } - _FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s", - servers_prop, sizeof(servers_prop)))); - _FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s", - gservers_prop, sizeof(gservers_prop)))); - if (env->spr_cb[SPR_PURR].oea_read) { _FDT((fdt_property(fdt, "ibm,purr", NULL, 0))); } @@ -470,6 +516,9 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, page_sizes_prop, page_sizes_prop_size))); } + _FDT((fdt_property_cell(fdt, "ibm,chip-id", + cs->cpu_index / cpus_per_socket))); + _FDT((fdt_end_node(fdt))); } @@ -478,16 +527,30 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, /* RTAS */ _FDT((fdt_begin_node(fdt, "rtas"))); - _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop, - sizeof(hypertas_prop)))); - _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas_prop, - sizeof(qemu_hypertas_prop)))); + if (!kvm_enabled() || kvmppc_spapr_use_multitce()) { + add_str(hypertas, "hcall-multi-tce"); + } + _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas->str, + hypertas->len))); + g_string_free(hypertas, TRUE); + _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas->str, + qemu_hypertas->len))); + g_string_free(qemu_hypertas, TRUE); _FDT((fdt_property(fdt, "ibm,associativity-reference-points", refpoints, sizeof(refpoints)))); _FDT((fdt_property_cell(fdt, "rtas-error-log-max", RTAS_ERROR_LOG_MAX))); + /* + * According to PAPR, rtas ibm,os-term does not guarantee a return + * back to the guest cpu. + * + * While an additional ibm,extended-os-term property indicates that + * rtas call return will always occur. Set this property. + */ + _FDT((fdt_property(fdt, "ibm,extended-os-term", NULL, 0))); + _FDT((fdt_end_node(fdt))); /* interrupt controller */ @@ -521,78 +584,137 @@ static void *spapr_create_fdt_skel(hwaddr initrd_base, /* event-sources */ spapr_events_fdt_skel(fdt, epow_irq); + /* /hypervisor node */ + if (kvm_enabled()) { + uint8_t hypercall[16]; + + /* indicate KVM hypercall interface */ + _FDT((fdt_begin_node(fdt, "hypervisor"))); + _FDT((fdt_property_string(fdt, "compatible", "linux,kvm"))); + if (kvmppc_has_cap_fixup_hcalls()) { + /* + * Older KVM versions with older guest kernels were broken with the + * magic page, don't allow the guest to map it. + */ + kvmppc_get_hypercall(first_cpu->env_ptr, hypercall, + sizeof(hypercall)); + _FDT((fdt_property(fdt, "hcall-instructions", hypercall, + sizeof(hypercall)))); + } + _FDT((fdt_end_node(fdt))); + } + _FDT((fdt_end_node(fdt))); /* close root node */ _FDT((fdt_finish(fdt))); return fdt; } -static int spapr_populate_memory(sPAPREnvironment *spapr, void *fdt) +int spapr_h_cas_compose_response(target_ulong addr, target_ulong size) +{ + void *fdt, *fdt_skel; + sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 }; + + size -= sizeof(hdr); + + /* Create sceleton */ + fdt_skel = g_malloc0(size); + _FDT((fdt_create(fdt_skel, size))); + _FDT((fdt_begin_node(fdt_skel, ""))); + _FDT((fdt_end_node(fdt_skel))); + _FDT((fdt_finish(fdt_skel))); + fdt = g_malloc0(size); + _FDT((fdt_open_into(fdt_skel, fdt, size))); + g_free(fdt_skel); + + /* Fix skeleton up */ + _FDT((spapr_fixup_cpu_dt(fdt, spapr))); + + /* Pack resulting tree */ + _FDT((fdt_pack(fdt))); + + if (fdt_totalsize(fdt) + sizeof(hdr) > size) { + trace_spapr_cas_failed(size); + return -1; + } + + cpu_physical_memory_write(addr, &hdr, sizeof(hdr)); + cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt)); + trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr)); + g_free(fdt); + + return 0; +} + +static void spapr_populate_memory_node(void *fdt, int nodeid, hwaddr start, + hwaddr size) { - uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0), - cpu_to_be32(0x0), cpu_to_be32(0x0), - cpu_to_be32(0x0)}; + uint32_t associativity[] = { + cpu_to_be32(0x4), /* length */ + cpu_to_be32(0x0), cpu_to_be32(0x0), + cpu_to_be32(0x0), cpu_to_be32(nodeid) + }; char mem_name[32]; - hwaddr node0_size, mem_start, node_size; uint64_t mem_reg_property[2]; - int i, off; + int off; - /* memory node(s) */ - if (nb_numa_nodes > 1 && node_mem[0] < ram_size) { - node0_size = node_mem[0]; - } else { - node0_size = ram_size; - } + mem_reg_property[0] = cpu_to_be64(start); + mem_reg_property[1] = cpu_to_be64(size); - /* RMA */ - mem_reg_property[0] = 0; - mem_reg_property[1] = cpu_to_be64(spapr->rma_size); - off = fdt_add_subnode(fdt, 0, "memory@0"); + sprintf(mem_name, "memory@" TARGET_FMT_lx, start); + off = fdt_add_subnode(fdt, 0, mem_name); _FDT(off); _FDT((fdt_setprop_string(fdt, off, "device_type", "memory"))); _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property, sizeof(mem_reg_property)))); _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity, sizeof(associativity)))); +} - /* RAM: Node 0 */ - if (node0_size > spapr->rma_size) { - mem_reg_property[0] = cpu_to_be64(spapr->rma_size); - mem_reg_property[1] = cpu_to_be64(node0_size - spapr->rma_size); - - sprintf(mem_name, "memory@" TARGET_FMT_lx, spapr->rma_size); - off = fdt_add_subnode(fdt, 0, mem_name); - _FDT(off); - _FDT((fdt_setprop_string(fdt, off, "device_type", "memory"))); - _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property, - sizeof(mem_reg_property)))); - _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity, - sizeof(associativity)))); - } - - /* RAM: Node 1 and beyond */ - mem_start = node0_size; - for (i = 1; i < nb_numa_nodes; i++) { - mem_reg_property[0] = cpu_to_be64(mem_start); +static int spapr_populate_memory(sPAPREnvironment *spapr, void *fdt) +{ + hwaddr mem_start, node_size; + int i, nb_nodes = nb_numa_nodes; + NodeInfo *nodes = numa_info; + NodeInfo ramnode; + + /* No NUMA nodes, assume there is just one node with whole RAM */ + if (!nb_numa_nodes) { + nb_nodes = 1; + ramnode.node_mem = ram_size; + nodes = &ramnode; + } + + for (i = 0, mem_start = 0; i < nb_nodes; ++i) { + if (!nodes[i].node_mem) { + continue; + } if (mem_start >= ram_size) { node_size = 0; } else { - node_size = node_mem[i]; + node_size = nodes[i].node_mem; if (node_size > ram_size - mem_start) { node_size = ram_size - mem_start; } } - mem_reg_property[1] = cpu_to_be64(node_size); - associativity[3] = associativity[4] = cpu_to_be32(i); - sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start); - off = fdt_add_subnode(fdt, 0, mem_name); - _FDT(off); - _FDT((fdt_setprop_string(fdt, off, "device_type", "memory"))); - _FDT((fdt_setprop(fdt, off, "reg", mem_reg_property, - sizeof(mem_reg_property)))); - _FDT((fdt_setprop(fdt, off, "ibm,associativity", associativity, - sizeof(associativity)))); - mem_start += node_size; + if (!mem_start) { + /* ppc_spapr_init() checks for rma_size <= node0_size already */ + spapr_populate_memory_node(fdt, i, 0, spapr->rma_size); + mem_start += spapr->rma_size; + node_size -= spapr->rma_size; + } + for ( ; node_size; ) { + hwaddr sizetmp = pow2floor(node_size); + + /* mem_start != 0 here */ + if (ctzl(mem_start) < ctzl(sizetmp)) { + sizetmp = 1ULL << ctzl(mem_start); + } + + spapr_populate_memory_node(fdt, i, mem_start, sizetmp); + node_size -= sizetmp; + mem_start += sizetmp; + } } return 0; @@ -676,6 +798,7 @@ static void spapr_finalize_fdt(sPAPREnvironment *spapr, cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt)); + g_free(bootlist); g_free(fdt); } @@ -722,24 +845,58 @@ static void spapr_reset_htab(sPAPREnvironment *spapr) /* Update the RMA size if necessary */ if (spapr->vrma_adjust) { - hwaddr node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size; - spapr->rma_size = kvmppc_rma_size(node0_size, spapr->htab_shift); + spapr->rma_size = kvmppc_rma_size(spapr_node0_size(), + spapr->htab_shift); } } +static int find_unknown_sysbus_device(SysBusDevice *sbdev, void *opaque) +{ + bool matched = false; + + if (object_dynamic_cast(OBJECT(sbdev), TYPE_SPAPR_PCI_HOST_BRIDGE)) { + matched = true; + } + + if (!matched) { + error_report("Device %s is not supported by this machine yet.", + qdev_fw_name(DEVICE(sbdev))); + exit(1); + } + + return 0; +} + static void ppc_spapr_reset(void) { PowerPCCPU *first_ppc_cpu; + uint32_t rtas_limit; + + /* Check for unknown sysbus devices */ + foreach_dynamic_sysbus_device(find_unknown_sysbus_device, NULL); /* Reset the hash table & recalc the RMA */ spapr_reset_htab(spapr); qemu_devices_reset(); + /* + * We place the device tree and RTAS just below either the top of the RMA, + * or just below 2GB, whichever is lowere, so that it can be + * processed with 32-bit real mode code if necessary + */ + rtas_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR); + spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE; + spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE; + /* Load the fdt */ spapr_finalize_fdt(spapr, spapr->fdt_addr, spapr->rtas_addr, spapr->rtas_size); + /* Copy RTAS over */ + cpu_physical_memory_write(spapr->rtas_addr, spapr->rtas_blob, + spapr->rtas_size); + /* Set up the entry state */ first_ppc_cpu = POWERPC_CPU(first_cpu); first_ppc_cpu->env.gpr[3] = spapr->fdt_addr; @@ -790,7 +947,7 @@ static void spapr_create_nvram(sPAPREnvironment *spapr) DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0); if (dinfo) { - qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv); + qdev_prop_set_drive_nofail(dev, "drive", blk_by_legacy_dinfo(dinfo)); } qdev_init_nofail(dev); @@ -817,15 +974,14 @@ static int spapr_vga_init(PCIBus *pci_bus) static const VMStateDescription vmstate_spapr = { .name = "spapr", - .version_id = 1, + .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { - VMSTATE_UINT32(next_irq, sPAPREnvironment), + .fields = (VMStateField[]) { + VMSTATE_UNUSED(4), /* used to be @next_irq */ /* RTC offset */ VMSTATE_UINT64(rtc_offset, sPAPREnvironment), - + VMSTATE_PPC_TIMEBASE_V(tb, sPAPREnvironment, 2), VMSTATE_END_OF_LIST() }, }; @@ -1140,25 +1296,27 @@ static SaveVMHandlers savevm_htab_handlers = { }; /* pSeries LPAR / sPAPR hardware init */ -static void ppc_spapr_init(QEMUMachineInitArgs *args) +static void ppc_spapr_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; - const char *boot_device = args->boot_order; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; + const char *boot_device = machine->boot_order; PowerPCCPU *cpu; CPUPPCState *env; PCIHostState *phb; int i; MemoryRegion *sysmem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); + MemoryRegion *rma_region; + void *rma = NULL; hwaddr rma_alloc_size; - hwaddr node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size; + hwaddr node0_size = spapr_node0_size(); uint32_t initrd_base = 0; long kernel_size = 0, initrd_size = 0; - long load_limit, rtas_limit, fw_size; + long load_limit, fw_size; bool kernel_le = false; char *filename; @@ -1170,7 +1328,7 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) cpu_ppc_hypercall = emulate_spapr_hypercall; /* Allocate RMA if necessary */ - rma_alloc_size = kvmppc_alloc_rma("ppc_spapr.rma", sysmem); + rma_alloc_size = kvmppc_alloc_rma(&rma); if (rma_alloc_size == -1) { hw_error("qemu: Unable to create RMA\n"); @@ -1203,13 +1361,8 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) exit(1); } - /* We place the device tree and RTAS just below either the top of the RMA, - * or just below 2GB, whichever is lowere, so that it can be - * processed with 32-bit real mode code if necessary */ - rtas_limit = MIN(spapr->rma_size, 0x80000000); - spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE; - spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE; - load_limit = spapr->fdt_addr - FW_OVERHEAD; + /* Setup a load limit for the ramdisk leaving room for SLOF and FDT */ + load_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR) - FW_OVERHEAD; /* We aim for a hash table of size 1/128 the size of RAM. The * normal rule of thumb is 1/64 the size of RAM, but that's much @@ -1225,7 +1378,6 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) /* Set up Interrupt Controller before we create the VCPUs */ spapr->icp = xics_system_init(smp_cpus * kvmppc_smt_threads() / smp_threads, XICS_IRQS); - spapr->next_irq = XICS_IRQ_BASE; /* init CPUs */ if (cpu_model == NULL) { @@ -1252,6 +1404,12 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) kvmppc_set_papr(cpu); } + if (cpu->max_compat) { + if (ppc_set_compat(cpu, cpu->max_compat) < 0) { + exit(1); + } + } + xics_cpu_setup(spapr->icp, cpu); qemu_register_reset(spapr_cpu_reset, cpu); @@ -1259,24 +1417,27 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) /* allocate RAM */ spapr->ram_limit = ram_size; - if (spapr->ram_limit > rma_alloc_size) { - ram_addr_t nonrma_base = rma_alloc_size; - ram_addr_t nonrma_size = spapr->ram_limit - rma_alloc_size; + memory_region_allocate_system_memory(ram, NULL, "ppc_spapr.ram", + spapr->ram_limit); + memory_region_add_subregion(sysmem, 0, ram); - memory_region_init_ram(ram, NULL, "ppc_spapr.ram", nonrma_size); - vmstate_register_ram_global(ram); - memory_region_add_subregion(sysmem, nonrma_base, ram); + if (rma_alloc_size && rma) { + rma_region = g_new(MemoryRegion, 1); + memory_region_init_ram_ptr(rma_region, NULL, "ppc_spapr.rma", + rma_alloc_size, rma); + vmstate_register_ram_global(rma_region); + memory_region_add_subregion(sysmem, 0, rma_region); } filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin"); - spapr->rtas_size = load_image_targphys(filename, spapr->rtas_addr, - rtas_limit - spapr->rtas_addr); - if (spapr->rtas_size < 0) { + spapr->rtas_size = get_image_size(filename); + spapr->rtas_blob = g_malloc(spapr->rtas_size); + if (load_image_size(filename, spapr->rtas_blob, spapr->rtas_size) < 0) { hw_error("qemu: could not load LPAR rtas '%s'\n", filename); exit(1); } if (spapr->rtas_size > RTAS_MAX_SIZE) { - hw_error("RTAS too big ! 0x%lx bytes (max is 0x%x)\n", + hw_error("RTAS too big ! 0x%zx bytes (max is 0x%x)\n", spapr->rtas_size, RTAS_MAX_SIZE); exit(1); } @@ -1298,7 +1459,6 @@ static void ppc_spapr_init(QEMUMachineInitArgs *args) spapr_create_nvram(spapr); /* Set up PCI */ - spapr_pci_msi_init(spapr, SPAPR_PCI_MSI_WINDOW); spapr_pci_rtas_init(); phb = spapr_create_phb(spapr, 0); @@ -1419,19 +1579,6 @@ static int spapr_kvm_type(const char *vm_type) exit(1); } -static QEMUMachine spapr_machine = { - .name = "pseries", - .desc = "pSeries Logical Partition (PAPR compliant)", - .is_default = 1, - .init = ppc_spapr_init, - .reset = ppc_spapr_reset, - .block_default_type = IF_SCSI, - .max_cpus = MAX_CPUS, - .no_parallel = 1, - .default_boot_order = NULL, - .kvm_type = spapr_kvm_type, -}; - /* * Implementation of an interface to adjust firmware patch * for the bootindex property handling. @@ -1489,29 +1636,117 @@ static char *spapr_get_fw_dev_path(FWPathProvider *p, BusState *bus, return NULL; } +static char *spapr_get_kvm_type(Object *obj, Error **errp) +{ + sPAPRMachineState *sm = SPAPR_MACHINE(obj); + + return g_strdup(sm->kvm_type); +} + +static void spapr_set_kvm_type(Object *obj, const char *value, Error **errp) +{ + sPAPRMachineState *sm = SPAPR_MACHINE(obj); + + g_free(sm->kvm_type); + sm->kvm_type = g_strdup(value); +} + +static void spapr_machine_initfn(Object *obj) +{ + object_property_add_str(obj, "kvm-type", + spapr_get_kvm_type, spapr_set_kvm_type, NULL); +} + +static void ppc_cpu_do_nmi_on_cpu(void *arg) +{ + CPUState *cs = arg; + + cpu_synchronize_state(cs); + ppc_cpu_do_system_reset(cs); +} + +static void spapr_nmi(NMIState *n, int cpu_index, Error **errp) +{ + CPUState *cs; + + CPU_FOREACH(cs) { + async_run_on_cpu(cs, ppc_cpu_do_nmi_on_cpu, cs); + } +} + static void spapr_machine_class_init(ObjectClass *oc, void *data) { MachineClass *mc = MACHINE_CLASS(oc); FWPathProviderClass *fwc = FW_PATH_PROVIDER_CLASS(oc); + NMIClass *nc = NMI_CLASS(oc); + + mc->init = ppc_spapr_init; + mc->reset = ppc_spapr_reset; + mc->block_default_type = IF_SCSI; + mc->max_cpus = MAX_CPUS; + mc->no_parallel = 1; + mc->default_boot_order = NULL; + mc->kvm_type = spapr_kvm_type; + mc->has_dynamic_sysbus = true; - mc->qemu_machine = data; fwc->get_dev_path = spapr_get_fw_dev_path; + nc->nmi_monitor_handler = spapr_nmi; } static const TypeInfo spapr_machine_info = { .name = TYPE_SPAPR_MACHINE, .parent = TYPE_MACHINE, + .abstract = true, + .instance_size = sizeof(sPAPRMachineState), + .instance_init = spapr_machine_initfn, .class_init = spapr_machine_class_init, - .class_data = &spapr_machine, .interfaces = (InterfaceInfo[]) { { TYPE_FW_PATH_PROVIDER }, + { TYPE_NMI }, { } }, }; +static void spapr_machine_2_1_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + static GlobalProperty compat_props[] = { + HW_COMPAT_2_1, + { /* end of list */ } + }; + + mc->name = "pseries-2.1"; + mc->desc = "pSeries Logical Partition (PAPR compliant) v2.1"; + mc->compat_props = compat_props; +} + +static const TypeInfo spapr_machine_2_1_info = { + .name = TYPE_SPAPR_MACHINE "2.1", + .parent = TYPE_SPAPR_MACHINE, + .class_init = spapr_machine_2_1_class_init, +}; + +static void spapr_machine_2_2_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + + mc->name = "pseries-2.2"; + mc->desc = "pSeries Logical Partition (PAPR compliant) v2.2"; + mc->alias = "pseries"; + mc->is_default = 1; +} + +static const TypeInfo spapr_machine_2_2_info = { + .name = TYPE_SPAPR_MACHINE "2.2", + .parent = TYPE_SPAPR_MACHINE, + .class_init = spapr_machine_2_2_class_init, +}; + static void spapr_machine_register_types(void) { type_register_static(&spapr_machine_info); + type_register_static(&spapr_machine_2_1_info); + type_register_static(&spapr_machine_2_2_info); } type_init(spapr_machine_register_types) diff --git a/hw/ppc/spapr_events.c b/hw/ppc/spapr_events.c index 16fa49e886..1b6157dec4 100644 --- a/hw/ppc/spapr_events.c +++ b/hw/ppc/spapr_events.c @@ -314,8 +314,9 @@ static void check_exception(PowerPCCPU *cpu, sPAPREnvironment *spapr, void spapr_events_init(sPAPREnvironment *spapr) { - spapr->epow_irq = spapr_allocate_msi(0); + spapr->epow_irq = xics_alloc(spapr->icp, 0, 0, false); spapr->epow_notifier.notify = spapr_powerdown_req; qemu_register_powerdown_notifier(&spapr->epow_notifier); - spapr_rtas_register("check-exception", check_exception); + spapr_rtas_register(RTAS_CHECK_EXCEPTION, "check-exception", + check_exception); } diff --git a/hw/ppc/spapr_hcall.c b/hw/ppc/spapr_hcall.c index 0bae0535e8..86514472fe 100644 --- a/hw/ppc/spapr_hcall.c +++ b/hw/ppc/spapr_hcall.c @@ -3,6 +3,9 @@ #include "helper_regs.h" #include "hw/ppc/spapr.h" #include "mmu-hash64.h" +#include "cpu-models.h" +#include "trace.h" +#include "kvm_ppc.h" struct SPRSyncState { CPUState *cs; @@ -709,47 +712,218 @@ static target_ulong h_logical_dcbf(PowerPCCPU *cpu, sPAPREnvironment *spapr, return H_SUCCESS; } +static target_ulong h_set_mode_resource_le(PowerPCCPU *cpu, + target_ulong mflags, + target_ulong value1, + target_ulong value2) +{ + CPUState *cs; + + if (value1) { + return H_P3; + } + if (value2) { + return H_P4; + } + + switch (mflags) { + case H_SET_MODE_ENDIAN_BIG: + CPU_FOREACH(cs) { + set_spr(cs, SPR_LPCR, 0, LPCR_ILE); + } + return H_SUCCESS; + + case H_SET_MODE_ENDIAN_LITTLE: + CPU_FOREACH(cs) { + set_spr(cs, SPR_LPCR, LPCR_ILE, LPCR_ILE); + } + return H_SUCCESS; + } + + return H_UNSUPPORTED_FLAG; +} + +static target_ulong h_set_mode_resource_addr_trans_mode(PowerPCCPU *cpu, + target_ulong mflags, + target_ulong value1, + target_ulong value2) +{ + CPUState *cs; + PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu); + target_ulong prefix; + + if (!(pcc->insns_flags2 & PPC2_ISA207S)) { + return H_P2; + } + if (value1) { + return H_P3; + } + if (value2) { + return H_P4; + } + + switch (mflags) { + case H_SET_MODE_ADDR_TRANS_NONE: + prefix = 0; + break; + case H_SET_MODE_ADDR_TRANS_0001_8000: + prefix = 0x18000; + break; + case H_SET_MODE_ADDR_TRANS_C000_0000_0000_4000: + prefix = 0xC000000000004000ULL; + break; + default: + return H_UNSUPPORTED_FLAG; + } + + CPU_FOREACH(cs) { + CPUPPCState *env = &POWERPC_CPU(cpu)->env; + + set_spr(cs, SPR_LPCR, mflags << LPCR_AIL_SHIFT, LPCR_AIL); + env->excp_prefix = prefix; + } + + return H_SUCCESS; +} + static target_ulong h_set_mode(PowerPCCPU *cpu, sPAPREnvironment *spapr, target_ulong opcode, target_ulong *args) { - CPUState *cs; - target_ulong mflags = args[0]; target_ulong resource = args[1]; - target_ulong value1 = args[2]; - target_ulong value2 = args[3]; target_ulong ret = H_P2; - if (resource == H_SET_MODE_RESOURCE_LE) { - if (value1) { - ret = H_P3; - goto out; - } - if (value2) { - ret = H_P4; - goto out; - } - switch (mflags) { - case H_SET_MODE_ENDIAN_BIG: - CPU_FOREACH(cs) { - set_spr(cs, SPR_LPCR, 0, LPCR_ILE); - } - ret = H_SUCCESS; - break; + switch (resource) { + case H_SET_MODE_RESOURCE_LE: + ret = h_set_mode_resource_le(cpu, args[0], args[2], args[3]); + break; + case H_SET_MODE_RESOURCE_ADDR_TRANS_MODE: + ret = h_set_mode_resource_addr_trans_mode(cpu, args[0], + args[2], args[3]); + break; + } + + return ret; +} + +typedef struct { + PowerPCCPU *cpu; + uint32_t cpu_version; + int ret; +} SetCompatState; - case H_SET_MODE_ENDIAN_LITTLE: - CPU_FOREACH(cs) { - set_spr(cs, SPR_LPCR, LPCR_ILE, LPCR_ILE); +static void do_set_compat(void *arg) +{ + SetCompatState *s = arg; + + cpu_synchronize_state(CPU(s->cpu)); + s->ret = ppc_set_compat(s->cpu, s->cpu_version); +} + +#define get_compat_level(cpuver) ( \ + ((cpuver) == CPU_POWERPC_LOGICAL_2_05) ? 2050 : \ + ((cpuver) == CPU_POWERPC_LOGICAL_2_06) ? 2060 : \ + ((cpuver) == CPU_POWERPC_LOGICAL_2_06_PLUS) ? 2061 : \ + ((cpuver) == CPU_POWERPC_LOGICAL_2_07) ? 2070 : 0) + +static target_ulong h_client_architecture_support(PowerPCCPU *cpu_, + sPAPREnvironment *spapr, + target_ulong opcode, + target_ulong *args) +{ + target_ulong list = args[0]; + PowerPCCPUClass *pcc_ = POWERPC_CPU_GET_CLASS(cpu_); + CPUState *cs; + bool cpu_match = false; + unsigned old_cpu_version = cpu_->cpu_version; + unsigned compat_lvl = 0, cpu_version = 0; + unsigned max_lvl = get_compat_level(cpu_->max_compat); + int counter; + + /* Parse PVR list */ + for (counter = 0; counter < 512; ++counter) { + uint32_t pvr, pvr_mask; + + pvr_mask = rtas_ld(list, 0); + list += 4; + pvr = rtas_ld(list, 0); + list += 4; + + trace_spapr_cas_pvr_try(pvr); + if (!max_lvl && + ((cpu_->env.spr[SPR_PVR] & pvr_mask) == (pvr & pvr_mask))) { + cpu_match = true; + cpu_version = 0; + } else if (pvr == cpu_->cpu_version) { + cpu_match = true; + cpu_version = cpu_->cpu_version; + } else if (!cpu_match) { + /* If it is a logical PVR, try to determine the highest level */ + unsigned lvl = get_compat_level(pvr); + if (lvl) { + bool is205 = (pcc_->pcr_mask & PCR_COMPAT_2_05) && + (lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_05)); + bool is206 = (pcc_->pcr_mask & PCR_COMPAT_2_06) && + ((lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_06)) || + (lvl == get_compat_level(CPU_POWERPC_LOGICAL_2_06_PLUS))); + + if (is205 || is206) { + if (!max_lvl) { + /* User did not set the level, choose the highest */ + if (compat_lvl <= lvl) { + compat_lvl = lvl; + cpu_version = pvr; + } + } else if (max_lvl >= lvl) { + /* User chose the level, don't set higher than this */ + compat_lvl = lvl; + cpu_version = pvr; + } + } } - ret = H_SUCCESS; + } + /* Terminator record */ + if (~pvr_mask & pvr) { break; + } + } - default: - ret = H_UNSUPPORTED_FLAG; + /* For the future use: here @list points to the first capability */ + + /* Parsing finished */ + trace_spapr_cas_pvr(cpu_->cpu_version, cpu_match, + cpu_version, pcc_->pcr_mask); + + /* Update CPUs */ + if (old_cpu_version != cpu_version) { + CPU_FOREACH(cs) { + SetCompatState s = { + .cpu = POWERPC_CPU(cs), + .cpu_version = cpu_version, + .ret = 0 + }; + + run_on_cpu(cs, do_set_compat, &s); + + if (s.ret < 0) { + fprintf(stderr, "Unable to set compatibility mode\n"); + return H_HARDWARE; + } } } -out: - return ret; + if (!cpu_version) { + return H_SUCCESS; + } + + if (!list) { + return H_SUCCESS; + } + + if (spapr_h_cas_compose_response(args[1], args[2])) { + qemu_system_reset_request(); + } + + return H_SUCCESS; } static spapr_hcall_fn papr_hypercall_table[(MAX_HCALL_OPCODE / 4) + 1]; @@ -831,6 +1005,9 @@ static void hypercall_register_types(void) spapr_register_hypercall(KVMPPC_H_RTAS, h_rtas); spapr_register_hypercall(H_SET_MODE, h_set_mode); + + /* ibm,client-architecture-support support */ + spapr_register_hypercall(KVMPPC_H_CAS, h_client_architecture_support); } type_init(hypercall_register_types) diff --git a/hw/ppc/spapr_iommu.c b/hw/ppc/spapr_iommu.c index d9fe946818..6c91d8edd8 100644 --- a/hw/ppc/spapr_iommu.c +++ b/hw/ppc/spapr_iommu.c @@ -35,7 +35,10 @@ enum sPAPRTCEAccess { SPAPR_TCE_RW = 3, }; -QLIST_HEAD(spapr_tce_tables, sPAPRTCETable) spapr_tce_tables; +#define IOMMU_PAGE_SIZE(shift) (1ULL << (shift)) +#define IOMMU_PAGE_MASK(shift) (~(IOMMU_PAGE_SIZE(shift) - 1)) + +static QLIST_HEAD(spapr_tce_tables, sPAPRTCETable) spapr_tce_tables; static sPAPRTCETable *spapr_tce_find_by_liobn(uint32_t liobn) { @@ -56,7 +59,8 @@ static sPAPRTCETable *spapr_tce_find_by_liobn(uint32_t liobn) return NULL; } -static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr) +static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr, + bool is_write) { sPAPRTCETable *tcet = container_of(iommu, sPAPRTCETable, iommu); uint64_t tce; @@ -70,13 +74,15 @@ static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr) if (tcet->bypass) { ret.perm = IOMMU_RW; - } else if (addr < tcet->window_size) { + } else if ((addr >> tcet->page_shift) < tcet->nb_table) { /* Check if we are in bound */ - tce = tcet->table[addr >> SPAPR_TCE_PAGE_SHIFT]; - ret.iova = addr & ~SPAPR_TCE_PAGE_MASK; - ret.translated_addr = tce & ~SPAPR_TCE_PAGE_MASK; - ret.addr_mask = SPAPR_TCE_PAGE_MASK; - ret.perm = tce; + hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + + tce = tcet->table[addr >> tcet->page_shift]; + ret.iova = addr & page_mask; + ret.translated_addr = tce & page_mask; + ret.addr_mask = ~page_mask; + ret.perm = tce & IOMMU_RW; } trace_spapr_iommu_xlate(tcet->liobn, addr, ret.iova, ret.perm, ret.addr_mask); @@ -84,25 +90,14 @@ static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr) return ret; } -static int spapr_tce_table_pre_load(void *opaque) -{ - sPAPRTCETable *tcet = SPAPR_TCE_TABLE(opaque); - - tcet->nb_table = tcet->window_size >> SPAPR_TCE_PAGE_SHIFT; - - return 0; -} - static const VMStateDescription vmstate_spapr_tce_table = { .name = "spapr_iommu", - .version_id = 1, - .minimum_version_id = 1, - .minimum_version_id_old = 1, - .pre_load = spapr_tce_table_pre_load, + .version_id = 2, + .minimum_version_id = 2, .fields = (VMStateField []) { /* Sanity check */ VMSTATE_UINT32_EQUAL(liobn, sPAPRTCETable), - VMSTATE_UINT32_EQUAL(window_size, sPAPRTCETable), + VMSTATE_UINT32_EQUAL(nb_table, sPAPRTCETable), /* IOMMU state */ VMSTATE_BOOL(bypass, sPAPRTCETable), @@ -122,28 +117,35 @@ static int spapr_tce_table_realize(DeviceState *dev) if (kvm_enabled()) { tcet->table = kvmppc_create_spapr_tce(tcet->liobn, - tcet->window_size, - &tcet->fd); + tcet->nb_table << + tcet->page_shift, + &tcet->fd, + tcet->vfio_accel); } if (!tcet->table) { - size_t table_size = (tcet->window_size >> SPAPR_TCE_PAGE_SHIFT) - * sizeof(uint64_t); + size_t table_size = tcet->nb_table * sizeof(uint64_t); tcet->table = g_malloc0(table_size); } - tcet->nb_table = tcet->window_size >> SPAPR_TCE_PAGE_SHIFT; trace_spapr_iommu_new_table(tcet->liobn, tcet, tcet->table, tcet->fd); memory_region_init_iommu(&tcet->iommu, OBJECT(dev), &spapr_iommu_ops, - "iommu-spapr", UINT64_MAX); + "iommu-spapr", ram_size); QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list); + vmstate_register(DEVICE(tcet), tcet->liobn, &vmstate_spapr_tce_table, + tcet); + return 0; } -sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn, size_t window_size) +sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn, + uint64_t bus_offset, + uint32_t page_shift, + uint32_t nb_table, + bool vfio_accel) { sPAPRTCETable *tcet; @@ -153,17 +155,20 @@ sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn, size_t wi return NULL; } - if (!window_size) { + if (!nb_table) { return NULL; } tcet = SPAPR_TCE_TABLE(object_new(TYPE_SPAPR_TCE_TABLE)); tcet->liobn = liobn; - tcet->window_size = window_size; + tcet->bus_offset = bus_offset; + tcet->page_shift = page_shift; + tcet->nb_table = nb_table; + tcet->vfio_accel = vfio_accel; object_property_add_child(OBJECT(owner), "tce-table", OBJECT(tcet), NULL); - qdev_init_nofail(DEVICE(tcet)); + object_property_set_bool(OBJECT(tcet), true, "realized", NULL); return tcet; } @@ -176,7 +181,7 @@ static void spapr_tce_table_finalize(Object *obj) if (!kvm_enabled() || (kvmppc_remove_spapr_tce(tcet->table, tcet->fd, - tcet->window_size) != 0)) { + tcet->nb_table) != 0)) { g_free(tcet->table); } } @@ -194,8 +199,7 @@ void spapr_tce_set_bypass(sPAPRTCETable *tcet, bool bypass) static void spapr_tce_reset(DeviceState *dev) { sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev); - size_t table_size = (tcet->window_size >> SPAPR_TCE_PAGE_SHIFT) - * sizeof(uint64_t); + size_t table_size = tcet->nb_table * sizeof(uint64_t); tcet->bypass = false; memset(tcet->table, 0, table_size); @@ -205,25 +209,110 @@ static target_ulong put_tce_emu(sPAPRTCETable *tcet, target_ulong ioba, target_ulong tce) { IOMMUTLBEntry entry; + hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + unsigned long index = (ioba - tcet->bus_offset) >> tcet->page_shift; - if (ioba >= tcet->window_size) { + if (index >= tcet->nb_table) { hcall_dprintf("spapr_vio_put_tce on out-of-bounds IOBA 0x" TARGET_FMT_lx "\n", ioba); return H_PARAMETER; } - tcet->table[ioba >> SPAPR_TCE_PAGE_SHIFT] = tce; + tcet->table[index] = tce; entry.target_as = &address_space_memory, - entry.iova = ioba & ~SPAPR_TCE_PAGE_MASK; - entry.translated_addr = tce & ~SPAPR_TCE_PAGE_MASK; - entry.addr_mask = SPAPR_TCE_PAGE_MASK; - entry.perm = tce; + entry.iova = ioba & page_mask; + entry.translated_addr = tce & page_mask; + entry.addr_mask = ~page_mask; + entry.perm = tce & IOMMU_RW; memory_region_notify_iommu(&tcet->iommu, entry); return H_SUCCESS; } +static target_ulong h_put_tce_indirect(PowerPCCPU *cpu, + sPAPREnvironment *spapr, + target_ulong opcode, target_ulong *args) +{ + int i; + target_ulong liobn = args[0]; + target_ulong ioba = args[1]; + target_ulong ioba1 = ioba; + target_ulong tce_list = args[2]; + target_ulong npages = args[3]; + target_ulong ret = H_PARAMETER; + sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn); + CPUState *cs = CPU(cpu); + hwaddr page_mask, page_size; + + if (!tcet) { + return H_PARAMETER; + } + + if ((npages > 512) || (tce_list & SPAPR_TCE_PAGE_MASK)) { + return H_PARAMETER; + } + + page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + page_size = IOMMU_PAGE_SIZE(tcet->page_shift); + ioba &= page_mask; + + for (i = 0; i < npages; ++i, ioba += page_size) { + target_ulong off = (tce_list & ~SPAPR_TCE_RW) + + i * sizeof(target_ulong); + target_ulong tce = ldq_phys(cs->as, off); + + ret = put_tce_emu(tcet, ioba, tce); + if (ret) { + break; + } + } + + /* Trace last successful or the first problematic entry */ + i = i ? (i - 1) : 0; + trace_spapr_iommu_indirect(liobn, ioba1, tce_list, i, + ldq_phys(cs->as, + tce_list + i * sizeof(target_ulong)), + ret); + + return ret; +} + +static target_ulong h_stuff_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr, + target_ulong opcode, target_ulong *args) +{ + int i; + target_ulong liobn = args[0]; + target_ulong ioba = args[1]; + target_ulong tce_value = args[2]; + target_ulong npages = args[3]; + target_ulong ret = H_PARAMETER; + sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn); + hwaddr page_mask, page_size; + + if (!tcet) { + return H_PARAMETER; + } + + if (npages > tcet->nb_table) { + return H_PARAMETER; + } + + page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + page_size = IOMMU_PAGE_SIZE(tcet->page_shift); + ioba &= page_mask; + + for (i = 0; i < npages; ++i, ioba += page_size) { + ret = put_tce_emu(tcet, ioba, tce_value); + if (ret) { + break; + } + } + trace_spapr_iommu_stuff(liobn, ioba, tce_value, npages, ret); + + return ret; +} + static target_ulong h_put_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr, target_ulong opcode, target_ulong *args) { @@ -233,9 +322,11 @@ static target_ulong h_put_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr, target_ulong ret = H_PARAMETER; sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn); - ioba &= ~(SPAPR_TCE_PAGE_SIZE - 1); - if (tcet) { + hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + + ioba &= page_mask; + ret = put_tce_emu(tcet, ioba, tce); } trace_spapr_iommu_put(liobn, ioba, tce, ret); @@ -246,13 +337,15 @@ static target_ulong h_put_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr, static target_ulong get_tce_emu(sPAPRTCETable *tcet, target_ulong ioba, target_ulong *tce) { - if (ioba >= tcet->window_size) { + unsigned long index = (ioba - tcet->bus_offset) >> tcet->page_shift; + + if (index >= tcet->nb_table) { hcall_dprintf("spapr_iommu_get_tce on out-of-bounds IOBA 0x" TARGET_FMT_lx "\n", ioba); return H_PARAMETER; } - *tce = tcet->table[ioba >> SPAPR_TCE_PAGE_SHIFT]; + *tce = tcet->table[index]; return H_SUCCESS; } @@ -266,9 +359,11 @@ static target_ulong h_get_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr, target_ulong ret = H_PARAMETER; sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn); - ioba &= ~(SPAPR_TCE_PAGE_SIZE - 1); - if (tcet) { + hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift); + + ioba &= page_mask; + ret = get_tce_emu(tcet, ioba, &tce); if (!ret) { args[0] = tce; @@ -317,13 +412,12 @@ int spapr_tcet_dma_dt(void *fdt, int node_off, const char *propname, } return spapr_dma_dt(fdt, node_off, propname, - tcet->liobn, 0, tcet->window_size); + tcet->liobn, 0, tcet->nb_table << tcet->page_shift); } static void spapr_tce_table_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - dc->vmsd = &vmstate_spapr_tce_table; dc->init = spapr_tce_table_realize; dc->reset = spapr_tce_reset; @@ -332,6 +426,8 @@ static void spapr_tce_table_class_init(ObjectClass *klass, void *data) /* hcall-tce */ spapr_register_hypercall(H_PUT_TCE, h_put_tce); spapr_register_hypercall(H_GET_TCE, h_get_tce); + spapr_register_hypercall(H_PUT_TCE_INDIRECT, h_put_tce_indirect); + spapr_register_hypercall(H_STUFF_TCE, h_stuff_tce); } static TypeInfo spapr_tce_table_info = { diff --git a/hw/ppc/spapr_pci.c b/hw/ppc/spapr_pci.c index cbef095935..21b95b342c 100644 --- a/hw/ppc/spapr_pci.c +++ b/hw/ppc/spapr_pci.c @@ -220,36 +220,12 @@ static void rtas_write_pci_config(PowerPCCPU *cpu, sPAPREnvironment *spapr, } /* - * Find an entry with config_addr or returns the empty one if not found AND - * alloc_new is set. - * At the moment the msi_table entries are never released so there is - * no point to look till the end of the list if we need to find the free entry. - */ -static int spapr_msicfg_find(sPAPRPHBState *phb, uint32_t config_addr, - bool alloc_new) -{ - int i; - - for (i = 0; i < SPAPR_MSIX_MAX_DEVS; ++i) { - if (!phb->msi_table[i].nvec) { - break; - } - if (phb->msi_table[i].config_addr == config_addr) { - return i; - } - } - if ((i < SPAPR_MSIX_MAX_DEVS) && alloc_new) { - trace_spapr_pci_msi("Allocating new MSI config", i, config_addr); - return i; - } - - return -1; -} - -/* * Set MSI/MSIX message data. * This is required for msi_notify()/msix_notify() which * will write at the addresses via spapr_msi_write(). + * + * If hwaddr == 0, all entries will have .data == first_irq i.e. + * table will be reset. */ static void spapr_msi_setmsg(PCIDevice *pdev, hwaddr addr, bool msix, unsigned first_irq, unsigned req_num) @@ -263,9 +239,12 @@ static void spapr_msi_setmsg(PCIDevice *pdev, hwaddr addr, bool msix, return; } - for (i = 0; i < req_num; ++i, ++msg.data) { + for (i = 0; i < req_num; ++i) { msix_set_message(pdev, i, msg); trace_spapr_pci_msi_setup(pdev->name, i, msg.address); + if (addr) { + ++msg.data; + } } } @@ -280,9 +259,11 @@ static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPREnvironment *spapr, unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */ unsigned int seq_num = rtas_ld(args, 5); unsigned int ret_intr_type; - int ndev, irq; + unsigned int irq, max_irqs = 0, num = 0; sPAPRPHBState *phb = NULL; PCIDevice *pdev = NULL; + spapr_pci_msi *msi; + int *config_addr_key; switch (func) { case RTAS_CHANGE_MSI_FN: @@ -310,13 +291,23 @@ static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPREnvironment *spapr, /* Releasing MSIs */ if (!req_num) { - ndev = spapr_msicfg_find(phb, config_addr, false); - if (ndev < 0) { - trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr); + msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr); + if (!msi) { + trace_spapr_pci_msi("Releasing wrong config", config_addr); rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } - trace_spapr_pci_msi("Released MSIs", ndev, config_addr); + + xics_free(spapr->icp, msi->first_irq, msi->num); + if (msi_present(pdev)) { + spapr_msi_setmsg(pdev, 0, false, 0, num); + } + if (msix_present(pdev)) { + spapr_msi_setmsg(pdev, 0, true, 0, num); + } + g_hash_table_remove(phb->msi, &config_addr); + + trace_spapr_pci_msi("Released MSIs", config_addr); rtas_st(rets, 0, RTAS_OUT_SUCCESS); rtas_st(rets, 1, 0); return; @@ -324,47 +315,54 @@ static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPREnvironment *spapr, /* Enabling MSI */ - /* Find a device number in the map to add or reuse the existing one */ - ndev = spapr_msicfg_find(phb, config_addr, true); - if (ndev >= SPAPR_MSIX_MAX_DEVS || ndev < 0) { - error_report("No free entry for a new MSI device"); - rtas_st(rets, 0, RTAS_OUT_HW_ERROR); + /* Check if the device supports as many IRQs as requested */ + if (ret_intr_type == RTAS_TYPE_MSI) { + max_irqs = msi_nr_vectors_allocated(pdev); + } else if (ret_intr_type == RTAS_TYPE_MSIX) { + max_irqs = pdev->msix_entries_nr; + } + if (!max_irqs) { + error_report("Requested interrupt type %d is not enabled for device %x", + ret_intr_type, config_addr); + rtas_st(rets, 0, -1); /* Hardware error */ return; } - trace_spapr_pci_msi("Configuring MSI", ndev, config_addr); + /* Correct the number if the guest asked for too many */ + if (req_num > max_irqs) { + trace_spapr_pci_msi_retry(config_addr, req_num, max_irqs); + req_num = max_irqs; + irq = 0; /* to avoid misleading trace */ + goto out; + } - /* Check if there is an old config and MSI number has not changed */ - if (phb->msi_table[ndev].nvec && (req_num != phb->msi_table[ndev].nvec)) { - /* Unexpected behaviour */ - error_report("Cannot reuse MSI config for device#%d", ndev); + /* Allocate MSIs */ + irq = xics_alloc_block(spapr->icp, 0, req_num, false, + ret_intr_type == RTAS_TYPE_MSI); + if (!irq) { + error_report("Cannot allocate MSIs for device %x", config_addr); rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } - /* There is no cached config, allocate MSIs */ - if (!phb->msi_table[ndev].nvec) { - irq = spapr_allocate_irq_block(req_num, false, - ret_intr_type == RTAS_TYPE_MSI); - if (irq < 0) { - error_report("Cannot allocate MSIs for device#%d", ndev); - rtas_st(rets, 0, RTAS_OUT_HW_ERROR); - return; - } - phb->msi_table[ndev].irq = irq; - phb->msi_table[ndev].nvec = req_num; - phb->msi_table[ndev].config_addr = config_addr; - } - /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */ - spapr_msi_setmsg(pdev, spapr->msi_win_addr, ret_intr_type == RTAS_TYPE_MSIX, - phb->msi_table[ndev].irq, req_num); - + spapr_msi_setmsg(pdev, SPAPR_PCI_MSI_WINDOW, ret_intr_type == RTAS_TYPE_MSIX, + irq, req_num); + + /* Add MSI device to cache */ + msi = g_new(spapr_pci_msi, 1); + msi->first_irq = irq; + msi->num = req_num; + config_addr_key = g_new(int, 1); + *config_addr_key = config_addr; + g_hash_table_insert(phb->msi, config_addr_key, msi); + +out: rtas_st(rets, 0, RTAS_OUT_SUCCESS); rtas_st(rets, 1, req_num); rtas_st(rets, 2, ++seq_num); rtas_st(rets, 3, ret_intr_type); - trace_spapr_pci_rtas_ibm_change_msi(func, req_num); + trace_spapr_pci_rtas_ibm_change_msi(config_addr, func, req_num, irq); } static void rtas_ibm_query_interrupt_source_number(PowerPCCPU *cpu, @@ -378,25 +376,28 @@ static void rtas_ibm_query_interrupt_source_number(PowerPCCPU *cpu, uint32_t config_addr = rtas_ld(args, 0); uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2); unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3); - int ndev; sPAPRPHBState *phb = NULL; + PCIDevice *pdev = NULL; + spapr_pci_msi *msi; - /* Fins sPAPRPHBState */ + /* Find sPAPRPHBState */ phb = find_phb(spapr, buid); - if (!phb) { + if (phb) { + pdev = find_dev(spapr, buid, config_addr); + } + if (!phb || !pdev) { rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR); return; } /* Find device descriptor and start IRQ */ - ndev = spapr_msicfg_find(phb, config_addr, false); - if (ndev < 0) { - trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr); + msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr); + if (!msi || !msi->first_irq || !msi->num || (ioa_intr_num >= msi->num)) { + trace_spapr_pci_msi("Failed to return vector", config_addr); rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } - - intr_src_num = phb->msi_table[ndev].irq + ioa_intr_num; + intr_src_num = msi->first_irq + ioa_intr_num; trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num, intr_src_num); @@ -468,34 +469,6 @@ static const MemoryRegionOps spapr_msi_ops = { .endianness = DEVICE_LITTLE_ENDIAN }; -void spapr_pci_msi_init(sPAPREnvironment *spapr, hwaddr addr) -{ - uint64_t window_size = 4096; - - /* - * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors, - * we need to allocate some memory to catch those writes coming - * from msi_notify()/msix_notify(). - * As MSIMessage:addr is going to be the same and MSIMessage:data - * is going to be a VIRQ number, 4 bytes of the MSI MR will only - * be used. - * - * For KVM we want to ensure that this memory is a full page so that - * our memory slot is of page size granularity. - */ -#ifdef CONFIG_KVM - if (kvm_enabled()) { - window_size = getpagesize(); - } -#endif - - spapr->msi_win_addr = addr; - memory_region_init_io(&spapr->msiwindow, NULL, &spapr_msi_ops, spapr, - "msi", window_size); - memory_region_add_subregion(get_system_memory(), spapr->msi_win_addr, - &spapr->msiwindow); -} - /* * PHB PCI device */ @@ -511,9 +484,11 @@ static void spapr_phb_realize(DeviceState *dev, Error **errp) SysBusDevice *s = SYS_BUS_DEVICE(dev); sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s); PCIHostState *phb = PCI_HOST_BRIDGE(s); + sPAPRPHBClass *info = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(s); char *namebuf; int i; PCIBus *bus; + uint64_t msi_window_size = 4096; if (sphb->index != -1) { hwaddr windows_base; @@ -575,23 +550,14 @@ static void spapr_phb_realize(DeviceState *dev, Error **errp) memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr, &sphb->memwindow); - /* On ppc, we only have MMIO no specific IO space from the CPU - * perspective. In theory we ought to be able to embed the PCI IO - * memory region direction in the system memory space. However, - * if any of the IO BAR subregions use the old_portio mechanism, - * that won't be processed properly unless accessed from the - * system io address space. This hack to bounce things via - * system_io works around the problem until all the users of - * old_portion are updated */ + /* Initialize IO regions */ sprintf(namebuf, "%s.io", sphb->dtbusname); memory_region_init(&sphb->iospace, OBJECT(sphb), namebuf, SPAPR_PCI_IO_WIN_SIZE); - /* FIXME: fix to support multiple PHBs */ - memory_region_add_subregion(get_system_io(), 0, &sphb->iospace); sprintf(namebuf, "%s.io-alias", sphb->dtbusname); memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf, - get_system_io(), 0, SPAPR_PCI_IO_WIN_SIZE); + &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE); memory_region_add_subregion(get_system_memory(), sphb->io_win_addr, &sphb->iowindow); @@ -601,18 +567,42 @@ static void spapr_phb_realize(DeviceState *dev, Error **errp) PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS); phb->bus = bus; - sphb->dma_window_start = 0; - sphb->dma_window_size = 0x40000000; - sphb->tcet = spapr_tce_new_table(dev, sphb->dma_liobn, - sphb->dma_window_size); - if (!sphb->tcet) { - error_setg(errp, "Unable to create TCE table for %s", - sphb->dtbusname); - return; - } - address_space_init(&sphb->iommu_as, spapr_tce_get_iommu(sphb->tcet), + /* + * Initialize PHB address space. + * By default there will be at least one subregion for default + * 32bit DMA window. + * Later the guest might want to create another DMA window + * which will become another memory subregion. + */ + sprintf(namebuf, "%s.iommu-root", sphb->dtbusname); + + memory_region_init(&sphb->iommu_root, OBJECT(sphb), + namebuf, UINT64_MAX); + address_space_init(&sphb->iommu_as, &sphb->iommu_root, sphb->dtbusname); + /* + * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors, + * we need to allocate some memory to catch those writes coming + * from msi_notify()/msix_notify(). + * As MSIMessage:addr is going to be the same and MSIMessage:data + * is going to be a VIRQ number, 4 bytes of the MSI MR will only + * be used. + * + * For KVM we want to ensure that this memory is a full page so that + * our memory slot is of page size granularity. + */ +#ifdef CONFIG_KVM + if (kvm_enabled()) { + msi_window_size = getpagesize(); + } +#endif + + memory_region_init_io(&sphb->msiwindow, NULL, &spapr_msi_ops, spapr, + "msi", msi_window_size); + memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW, + &sphb->msiwindow); + pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb); pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq); @@ -623,7 +613,7 @@ static void spapr_phb_realize(DeviceState *dev, Error **errp) for (i = 0; i < PCI_NUM_PINS; i++) { uint32_t irq; - irq = spapr_allocate_lsi(0); + irq = xics_alloc_block(spapr->icp, 0, 1, true, false); if (!irq) { error_setg(errp, "spapr_allocate_lsi failed"); return; @@ -631,15 +621,51 @@ static void spapr_phb_realize(DeviceState *dev, Error **errp) sphb->lsi_table[i].irq = irq; } + + if (!info->finish_realize) { + error_setg(errp, "finish_realize not defined"); + return; + } + + info->finish_realize(sphb, errp); + + sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free); } -static void spapr_phb_reset(DeviceState *qdev) +static void spapr_phb_finish_realize(sPAPRPHBState *sphb, Error **errp) { - SysBusDevice *s = SYS_BUS_DEVICE(qdev); - sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s); + sPAPRTCETable *tcet; + + tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn, + 0, + SPAPR_TCE_PAGE_SHIFT, + 0x40000000 >> SPAPR_TCE_PAGE_SHIFT, false); + if (!tcet) { + error_setg(errp, "Unable to create TCE table for %s", + sphb->dtbusname); + return ; + } + + /* Register default 32bit DMA window */ + memory_region_add_subregion(&sphb->iommu_root, 0, + spapr_tce_get_iommu(tcet)); +} + +static int spapr_phb_children_reset(Object *child, void *opaque) +{ + DeviceState *dev = (DeviceState *) object_dynamic_cast(child, TYPE_DEVICE); + if (dev) { + device_reset(dev); + } + + return 0; +} + +static void spapr_phb_reset(DeviceState *qdev) +{ /* Reset the IOMMU state */ - device_reset(DEVICE(sphb->tcet)); + object_child_foreach(OBJECT(qdev), spapr_phb_children_reset, NULL); } static Property spapr_phb_properties[] = { @@ -659,8 +685,7 @@ static const VMStateDescription vmstate_spapr_pci_lsi = { .name = "spapr_pci/lsi", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT32_EQUAL(irq, struct spapr_pci_lsi), VMSTATE_END_OF_LIST() @@ -668,25 +693,76 @@ static const VMStateDescription vmstate_spapr_pci_lsi = { }; static const VMStateDescription vmstate_spapr_pci_msi = { - .name = "spapr_pci/lsi", + .name = "spapr_pci/msi", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { - VMSTATE_UINT32(config_addr, struct spapr_pci_msi), - VMSTATE_UINT32(irq, struct spapr_pci_msi), - VMSTATE_UINT32(nvec, struct spapr_pci_msi), - + .fields = (VMStateField []) { + VMSTATE_UINT32(key, spapr_pci_msi_mig), + VMSTATE_UINT32(value.first_irq, spapr_pci_msi_mig), + VMSTATE_UINT32(value.num, spapr_pci_msi_mig), VMSTATE_END_OF_LIST() }, }; +static void spapr_pci_fill_msi_devs(gpointer key, gpointer value, + gpointer opaque) +{ + sPAPRPHBState *sphb = opaque; + + sphb->msi_devs[sphb->msi_devs_num].key = *(uint32_t *)key; + sphb->msi_devs[sphb->msi_devs_num].value = *(spapr_pci_msi *)value; + sphb->msi_devs_num++; +} + +static void spapr_pci_pre_save(void *opaque) +{ + sPAPRPHBState *sphb = opaque; + int msi_devs_num; + + if (sphb->msi_devs) { + g_free(sphb->msi_devs); + sphb->msi_devs = NULL; + } + sphb->msi_devs_num = 0; + msi_devs_num = g_hash_table_size(sphb->msi); + if (!msi_devs_num) { + return; + } + sphb->msi_devs = g_malloc(msi_devs_num * sizeof(spapr_pci_msi_mig)); + + g_hash_table_foreach(sphb->msi, spapr_pci_fill_msi_devs, sphb); + assert(sphb->msi_devs_num == msi_devs_num); +} + +static int spapr_pci_post_load(void *opaque, int version_id) +{ + sPAPRPHBState *sphb = opaque; + gpointer key, value; + int i; + + for (i = 0; i < sphb->msi_devs_num; ++i) { + key = g_memdup(&sphb->msi_devs[i].key, + sizeof(sphb->msi_devs[i].key)); + value = g_memdup(&sphb->msi_devs[i].value, + sizeof(sphb->msi_devs[i].value)); + g_hash_table_insert(sphb->msi, key, value); + } + if (sphb->msi_devs) { + g_free(sphb->msi_devs); + sphb->msi_devs = NULL; + } + sphb->msi_devs_num = 0; + + return 0; +} + static const VMStateDescription vmstate_spapr_pci = { .name = "spapr_pci", - .version_id = 1, - .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .version_id = 2, + .minimum_version_id = 2, + .pre_save = spapr_pci_pre_save, + .post_load = spapr_pci_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT64_EQUAL(buid, sPAPRPHBState), VMSTATE_UINT32_EQUAL(dma_liobn, sPAPRPHBState), VMSTATE_UINT64_EQUAL(mem_win_addr, sPAPRPHBState), @@ -695,9 +771,9 @@ static const VMStateDescription vmstate_spapr_pci = { VMSTATE_UINT64_EQUAL(io_win_size, sPAPRPHBState), VMSTATE_STRUCT_ARRAY(lsi_table, sPAPRPHBState, PCI_NUM_PINS, 0, vmstate_spapr_pci_lsi, struct spapr_pci_lsi), - VMSTATE_STRUCT_ARRAY(msi_table, sPAPRPHBState, SPAPR_MSIX_MAX_DEVS, 0, - vmstate_spapr_pci_msi, struct spapr_pci_msi), - + VMSTATE_INT32(msi_devs_num, sPAPRPHBState), + VMSTATE_STRUCT_VARRAY_ALLOC(msi_devs, sPAPRPHBState, msi_devs_num, 0, + vmstate_spapr_pci_msi, spapr_pci_msi_mig), VMSTATE_END_OF_LIST() }, }; @@ -714,6 +790,7 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data) { PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); + sPAPRPHBClass *spc = SPAPR_PCI_HOST_BRIDGE_CLASS(klass); hc->root_bus_path = spapr_phb_root_bus_path; dc->realize = spapr_phb_realize; @@ -722,6 +799,7 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data) dc->vmsd = &vmstate_spapr_pci; set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); dc->cannot_instantiate_with_device_add_yet = false; + spc->finish_realize = spapr_phb_finish_realize; } static const TypeInfo spapr_phb_info = { @@ -729,6 +807,7 @@ static const TypeInfo spapr_phb_info = { .parent = TYPE_PCI_HOST_BRIDGE, .instance_size = sizeof(sPAPRPHBState), .class_init = spapr_phb_class_init, + .class_size = sizeof(sPAPRPHBClass), }; PCIHostState *spapr_create_phb(sPAPREnvironment *spapr, int index) @@ -753,6 +832,29 @@ PCIHostState *spapr_create_phb(sPAPREnvironment *spapr, int index) #define b_fff(x) b_x((x), 8, 3) /* function number */ #define b_rrrrrrrr(x) b_x((x), 0, 8) /* register number */ +typedef struct sPAPRTCEDT { + void *fdt; + int node_off; +} sPAPRTCEDT; + +static int spapr_phb_children_dt(Object *child, void *opaque) +{ + sPAPRTCEDT *p = opaque; + sPAPRTCETable *tcet; + + tcet = (sPAPRTCETable *) object_dynamic_cast(child, TYPE_SPAPR_TCE_TABLE); + if (!tcet) { + return 0; + } + + spapr_dma_dt(p->fdt, p->node_off, "ibm,dma-window", + tcet->liobn, tcet->bus_offset, + tcet->nb_table << tcet->page_shift); + /* Stop after the first window */ + + return 1; +} + int spapr_populate_pci_dt(sPAPRPHBState *phb, uint32_t xics_phandle, void *fdt) @@ -808,6 +910,7 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb, _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof(ranges))); _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg))); _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1)); + _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS)); /* Build the interrupt-map, this must matches what is done * in pci_spapr_map_irq @@ -832,23 +935,28 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb, _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map, sizeof(interrupt_map))); - spapr_dma_dt(fdt, bus_off, "ibm,dma-window", - phb->dma_liobn, phb->dma_window_start, - phb->dma_window_size); + object_child_foreach(OBJECT(phb), spapr_phb_children_dt, + &((sPAPRTCEDT){ .fdt = fdt, .node_off = bus_off })); return 0; } void spapr_pci_rtas_init(void) { - spapr_rtas_register("read-pci-config", rtas_read_pci_config); - spapr_rtas_register("write-pci-config", rtas_write_pci_config); - spapr_rtas_register("ibm,read-pci-config", rtas_ibm_read_pci_config); - spapr_rtas_register("ibm,write-pci-config", rtas_ibm_write_pci_config); + spapr_rtas_register(RTAS_READ_PCI_CONFIG, "read-pci-config", + rtas_read_pci_config); + spapr_rtas_register(RTAS_WRITE_PCI_CONFIG, "write-pci-config", + rtas_write_pci_config); + spapr_rtas_register(RTAS_IBM_READ_PCI_CONFIG, "ibm,read-pci-config", + rtas_ibm_read_pci_config); + spapr_rtas_register(RTAS_IBM_WRITE_PCI_CONFIG, "ibm,write-pci-config", + rtas_ibm_write_pci_config); if (msi_supported) { - spapr_rtas_register("ibm,query-interrupt-source-number", + spapr_rtas_register(RTAS_IBM_QUERY_INTERRUPT_SOURCE_NUMBER, + "ibm,query-interrupt-source-number", rtas_ibm_query_interrupt_source_number); - spapr_rtas_register("ibm,change-msi", rtas_ibm_change_msi); + spapr_rtas_register(RTAS_IBM_CHANGE_MSI, "ibm,change-msi", + rtas_ibm_change_msi); } } diff --git a/hw/ppc/spapr_pci_vfio.c b/hw/ppc/spapr_pci_vfio.c new file mode 100644 index 0000000000..d3bddf2887 --- /dev/null +++ b/hw/ppc/spapr_pci_vfio.c @@ -0,0 +1,102 @@ +/* + * QEMU sPAPR PCI host for VFIO + * + * Copyright (c) 2011-2014 Alexey Kardashevskiy, IBM Corporation. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, + * or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "hw/ppc/spapr.h" +#include "hw/pci-host/spapr.h" +#include "linux/vfio.h" +#include "hw/misc/vfio.h" + +static Property spapr_phb_vfio_properties[] = { + DEFINE_PROP_INT32("iommu", sPAPRPHBVFIOState, iommugroupid, -1), + DEFINE_PROP_END_OF_LIST(), +}; + +static void spapr_phb_vfio_finish_realize(sPAPRPHBState *sphb, Error **errp) +{ + sPAPRPHBVFIOState *svphb = SPAPR_PCI_VFIO_HOST_BRIDGE(sphb); + struct vfio_iommu_spapr_tce_info info = { .argsz = sizeof(info) }; + int ret; + sPAPRTCETable *tcet; + uint32_t liobn = svphb->phb.dma_liobn; + + if (svphb->iommugroupid == -1) { + error_setg(errp, "Wrong IOMMU group ID %d", svphb->iommugroupid); + return; + } + + ret = vfio_container_ioctl(&svphb->phb.iommu_as, svphb->iommugroupid, + VFIO_CHECK_EXTENSION, + (void *) VFIO_SPAPR_TCE_IOMMU); + if (ret != 1) { + error_setg_errno(errp, -ret, + "spapr-vfio: SPAPR extension is not supported"); + return; + } + + ret = vfio_container_ioctl(&svphb->phb.iommu_as, svphb->iommugroupid, + VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info); + if (ret) { + error_setg_errno(errp, -ret, + "spapr-vfio: get info from container failed"); + return; + } + + tcet = spapr_tce_new_table(DEVICE(sphb), liobn, info.dma32_window_start, + SPAPR_TCE_PAGE_SHIFT, + info.dma32_window_size >> SPAPR_TCE_PAGE_SHIFT, + true); + if (!tcet) { + error_setg(errp, "spapr-vfio: failed to create VFIO TCE table"); + return; + } + + /* Register default 32bit DMA window */ + memory_region_add_subregion(&sphb->iommu_root, tcet->bus_offset, + spapr_tce_get_iommu(tcet)); +} + +static void spapr_phb_vfio_reset(DeviceState *qdev) +{ + /* Do nothing */ +} + +static void spapr_phb_vfio_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + sPAPRPHBClass *spc = SPAPR_PCI_HOST_BRIDGE_CLASS(klass); + + dc->props = spapr_phb_vfio_properties; + dc->reset = spapr_phb_vfio_reset; + spc->finish_realize = spapr_phb_vfio_finish_realize; +} + +static const TypeInfo spapr_phb_vfio_info = { + .name = TYPE_SPAPR_PCI_VFIO_HOST_BRIDGE, + .parent = TYPE_SPAPR_PCI_HOST_BRIDGE, + .instance_size = sizeof(sPAPRPHBVFIOState), + .class_init = spapr_phb_vfio_class_init, + .class_size = sizeof(sPAPRPHBClass), +}; + +static void spapr_pci_vfio_register_types(void) +{ + type_register_static(&spapr_phb_vfio_info); +} + +type_init(spapr_pci_vfio_register_types) diff --git a/hw/ppc/spapr_rtas.c b/hw/ppc/spapr_rtas.c index 73860d0486..2ec2a8e4d1 100644 --- a/hw/ppc/spapr_rtas.c +++ b/hw/ppc/spapr_rtas.c @@ -32,12 +32,10 @@ #include "hw/ppc/spapr.h" #include "hw/ppc/spapr_vio.h" +#include "qapi-event.h" #include <libfdt.h> -#define TOKEN_BASE 0x2000 -#define TOKEN_MAX 0x100 - static void rtas_display_character(PowerPCCPU *cpu, sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, @@ -93,7 +91,7 @@ static void rtas_set_time_of_day(PowerPCCPU *cpu, sPAPREnvironment *spapr, tm.tm_sec = rtas_ld(args, 5); /* Just generate a monitor event for the change */ - rtc_change_mon_event(&tm); + qapi_event_send_rtc_change(qemu_timedate_diff(&tm), &error_abort); spapr->rtc_offset = qemu_timedate_diff(&tm); rtas_st(rets, 0, RTAS_OUT_SUCCESS); @@ -224,8 +222,6 @@ static void rtas_stop_self(PowerPCCPU *cpu, sPAPREnvironment *spapr, env->msr = 0; } -#define DIAGNOSTICS_RUN_MODE 42 - static void rtas_ibm_get_system_parameter(PowerPCCPU *cpu, sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, @@ -235,16 +231,28 @@ static void rtas_ibm_get_system_parameter(PowerPCCPU *cpu, target_ulong parameter = rtas_ld(args, 0); target_ulong buffer = rtas_ld(args, 1); target_ulong length = rtas_ld(args, 2); - target_ulong ret = RTAS_OUT_NOT_SUPPORTED; + target_ulong ret = RTAS_OUT_SUCCESS; switch (parameter) { - case DIAGNOSTICS_RUN_MODE: - if (length == 1) { - rtas_st(buffer, 0, 0); - ret = RTAS_OUT_SUCCESS; - } + case RTAS_SYSPARM_SPLPAR_CHARACTERISTICS: { + char *param_val = g_strdup_printf("MaxEntCap=%d,MaxPlatProcs=%d", + max_cpus, smp_cpus); + rtas_st_buffer(buffer, length, (uint8_t *)param_val, strlen(param_val)); + g_free(param_val); break; } + case RTAS_SYSPARM_DIAGNOSTICS_RUN_MODE: { + uint8_t param_val = DIAGNOSTICS_RUN_MODE_DISABLED; + + rtas_st_buffer(buffer, length, ¶m_val, sizeof(param_val)); + break; + } + case RTAS_SYSPARM_UUID: + rtas_st_buffer(buffer, length, qemu_uuid, (qemu_uuid_set ? 16 : 0)); + break; + default: + ret = RTAS_OUT_NOT_SUPPORTED; + } rtas_st(rets, 0, ret); } @@ -259,7 +267,9 @@ static void rtas_ibm_set_system_parameter(PowerPCCPU *cpu, target_ulong ret = RTAS_OUT_NOT_SUPPORTED; switch (parameter) { - case DIAGNOSTICS_RUN_MODE: + case RTAS_SYSPARM_SPLPAR_CHARACTERISTICS: + case RTAS_SYSPARM_DIAGNOSTICS_RUN_MODE: + case RTAS_SYSPARM_UUID: ret = RTAS_OUT_NOT_AUTHORIZED; break; } @@ -267,20 +277,30 @@ static void rtas_ibm_set_system_parameter(PowerPCCPU *cpu, rtas_st(rets, 0, ret); } +static void rtas_ibm_os_term(PowerPCCPU *cpu, + sPAPREnvironment *spapr, + uint32_t token, uint32_t nargs, + target_ulong args, + uint32_t nret, target_ulong rets) +{ + target_ulong ret = 0; + + qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE, &error_abort); + + rtas_st(rets, 0, ret); +} + static struct rtas_call { const char *name; spapr_rtas_fn fn; -} rtas_table[TOKEN_MAX]; - -struct rtas_call *rtas_next = rtas_table; +} rtas_table[RTAS_TOKEN_MAX - RTAS_TOKEN_BASE]; target_ulong spapr_rtas_call(PowerPCCPU *cpu, sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, uint32_t nret, target_ulong rets) { - if ((token >= TOKEN_BASE) - && ((token - TOKEN_BASE) < TOKEN_MAX)) { - struct rtas_call *call = rtas_table + (token - TOKEN_BASE); + if ((token >= RTAS_TOKEN_BASE) && (token < RTAS_TOKEN_MAX)) { + struct rtas_call *call = rtas_table + (token - RTAS_TOKEN_BASE); if (call->fn) { call->fn(cpu, spapr, token, nargs, args, nret, rets); @@ -302,23 +322,22 @@ target_ulong spapr_rtas_call(PowerPCCPU *cpu, sPAPREnvironment *spapr, return H_PARAMETER; } -int spapr_rtas_register(const char *name, spapr_rtas_fn fn) +void spapr_rtas_register(int token, const char *name, spapr_rtas_fn fn) { - int i; - - for (i = 0; i < (rtas_next - rtas_table); i++) { - if (strcmp(name, rtas_table[i].name) == 0) { - fprintf(stderr, "RTAS call \"%s\" registered twice\n", name); - exit(1); - } + if (!((token >= RTAS_TOKEN_BASE) && (token < RTAS_TOKEN_MAX))) { + fprintf(stderr, "RTAS invalid token 0x%x\n", token); + exit(1); } - assert(rtas_next < (rtas_table + TOKEN_MAX)); - - rtas_next->name = name; - rtas_next->fn = fn; + token -= RTAS_TOKEN_BASE; + if (rtas_table[token].name) { + fprintf(stderr, "RTAS call \"%s\" is registered already as 0x%x\n", + rtas_table[token].name, token); + exit(1); + } - return (rtas_next++ - rtas_table) + TOKEN_BASE; + rtas_table[token].name = name; + rtas_table[token].fn = fn; } int spapr_rtas_device_tree_setup(void *fdt, hwaddr rtas_addr, @@ -358,7 +377,7 @@ int spapr_rtas_device_tree_setup(void *fdt, hwaddr rtas_addr, return ret; } - for (i = 0; i < TOKEN_MAX; i++) { + for (i = 0; i < RTAS_TOKEN_MAX - RTAS_TOKEN_BASE; i++) { struct rtas_call *call = &rtas_table[i]; if (!call->name) { @@ -366,7 +385,7 @@ int spapr_rtas_device_tree_setup(void *fdt, hwaddr rtas_addr, } ret = qemu_fdt_setprop_cell(fdt, "/rtas", call->name, - i + TOKEN_BASE); + i + RTAS_TOKEN_BASE); if (ret < 0) { fprintf(stderr, "Couldn't add rtas token for %s: %s\n", call->name, fdt_strerror(ret)); @@ -379,19 +398,27 @@ int spapr_rtas_device_tree_setup(void *fdt, hwaddr rtas_addr, static void core_rtas_register_types(void) { - spapr_rtas_register("display-character", rtas_display_character); - spapr_rtas_register("get-time-of-day", rtas_get_time_of_day); - spapr_rtas_register("set-time-of-day", rtas_set_time_of_day); - spapr_rtas_register("power-off", rtas_power_off); - spapr_rtas_register("system-reboot", rtas_system_reboot); - spapr_rtas_register("query-cpu-stopped-state", + spapr_rtas_register(RTAS_DISPLAY_CHARACTER, "display-character", + rtas_display_character); + spapr_rtas_register(RTAS_GET_TIME_OF_DAY, "get-time-of-day", + rtas_get_time_of_day); + spapr_rtas_register(RTAS_SET_TIME_OF_DAY, "set-time-of-day", + rtas_set_time_of_day); + spapr_rtas_register(RTAS_POWER_OFF, "power-off", rtas_power_off); + spapr_rtas_register(RTAS_SYSTEM_REBOOT, "system-reboot", + rtas_system_reboot); + spapr_rtas_register(RTAS_QUERY_CPU_STOPPED_STATE, "query-cpu-stopped-state", rtas_query_cpu_stopped_state); - spapr_rtas_register("start-cpu", rtas_start_cpu); - spapr_rtas_register("stop-self", rtas_stop_self); - spapr_rtas_register("ibm,get-system-parameter", + spapr_rtas_register(RTAS_START_CPU, "start-cpu", rtas_start_cpu); + spapr_rtas_register(RTAS_STOP_SELF, "stop-self", rtas_stop_self); + spapr_rtas_register(RTAS_IBM_GET_SYSTEM_PARAMETER, + "ibm,get-system-parameter", rtas_ibm_get_system_parameter); - spapr_rtas_register("ibm,set-system-parameter", + spapr_rtas_register(RTAS_IBM_SET_SYSTEM_PARAMETER, + "ibm,set-system-parameter", rtas_ibm_set_system_parameter); + spapr_rtas_register(RTAS_IBM_OS_TERM, "ibm,os-term", + rtas_ibm_os_term); } type_init(core_rtas_register_types) diff --git a/hw/ppc/spapr_vio.c b/hw/ppc/spapr_vio.c index 2ae06a3356..dc9e46a7b1 100644 --- a/hw/ppc/spapr_vio.c +++ b/hw/ppc/spapr_vio.c @@ -449,14 +449,18 @@ static int spapr_vio_busdev_init(DeviceState *qdev) dev->qdev.id = id; } - dev->irq = spapr_allocate_msi(dev->irq); + dev->irq = xics_alloc(spapr->icp, 0, dev->irq, false); if (!dev->irq) { return -1; } if (pc->rtce_window_size) { uint32_t liobn = SPAPR_VIO_BASE_LIOBN | dev->reg; - dev->tcet = spapr_tce_new_table(qdev, liobn, pc->rtce_window_size); + dev->tcet = spapr_tce_new_table(qdev, liobn, + 0, + SPAPR_TCE_PAGE_SHIFT, + pc->rtce_window_size >> + SPAPR_TCE_PAGE_SHIFT, false); address_space_init(&dev->as, spapr_tce_get_iommu(dev->tcet), qdev->id); } @@ -513,8 +517,9 @@ VIOsPAPRBus *spapr_vio_bus_init(void) spapr_register_hypercall(H_ENABLE_CRQ, h_enable_crq); /* RTAS calls */ - spapr_rtas_register("ibm,set-tce-bypass", rtas_set_tce_bypass); - spapr_rtas_register("quiesce", rtas_quiesce); + spapr_rtas_register(RTAS_IBM_SET_TCE_BYPASS, "ibm,set-tce-bypass", + rtas_set_tce_bypass); + spapr_rtas_register(RTAS_QUIESCE, "quiesce", rtas_quiesce); return bus; } @@ -547,8 +552,7 @@ const VMStateDescription vmstate_spapr_vio = { .name = "spapr_vio", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { /* Sanity check */ VMSTATE_UINT32_EQUAL(reg, VIOsPAPRDevice), VMSTATE_UINT32_EQUAL(irq, VIOsPAPRDevice), diff --git a/hw/ppc/virtex_ml507.c b/hw/ppc/virtex_ml507.c index 3e3569d4b8..6ebd5bee8b 100644 --- a/hw/ppc/virtex_ml507.c +++ b/hw/ppc/virtex_ml507.c @@ -39,7 +39,7 @@ #include "hw/ppc/ppc4xx.h" #include "ppc405.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "qapi/qmp/qerror.h" #define EPAPR_MAGIC (0x45504150) @@ -194,12 +194,12 @@ static int xilinx_load_device_tree(hwaddr addr, return fdt_size; } -static void virtex_init(QEMUMachineInitArgs *args) +static void virtex_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; hwaddr initrd_base = 0; int initrd_size = 0; MemoryRegion *address_space_mem = get_system_memory(); @@ -222,14 +222,13 @@ static void virtex_init(QEMUMachineInitArgs *args) env = &cpu->env; qemu_register_reset(main_cpu_reset, cpu); - memory_region_init_ram(phys_ram, NULL, "ram", ram_size); - vmstate_register_ram_global(phys_ram); + memory_region_allocate_system_memory(phys_ram, NULL, "ram", ram_size); memory_region_add_subregion(address_space_mem, ram_base, phys_ram); dinfo = drive_get(IF_PFLASH, 0, 0); pflash_cfi01_register(PFLASH_BASEADDR, NULL, "virtex.flash", FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, (64 * 1024), - FLASH_SIZE >> 16, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (64 * 1024), FLASH_SIZE >> 16, 1, 0x89, 0x18, 0x0000, 0x0, 1); cpu_irq = (qemu_irq *) &env->irq_inputs[PPC40x_INPUT_INT]; @@ -275,14 +274,14 @@ static void virtex_init(QEMUMachineInitArgs *args) boot_info.ima_size = kernel_size; /* Load initrd. */ - if (args->initrd_filename) { + if (machine->initrd_filename) { initrd_base = high = ROUND_UP(high, 4); - initrd_size = load_image_targphys(args->initrd_filename, + initrd_size = load_image_targphys(machine->initrd_filename, high, ram_size - high); if (initrd_size < 0) { error_report("couldn't load ram disk '%s'", - args->initrd_filename); + machine->initrd_filename); exit(1); } high = ROUND_UP(high + initrd_size, 4); diff --git a/hw/s390x/css.c b/hw/s390x/css.c index 7074d2b3d5..b67c039a70 100644 --- a/hw/s390x/css.c +++ b/hw/s390x/css.c @@ -16,6 +16,7 @@ #include "ioinst.h" #include "css.h" #include "trace.h" +#include "hw/s390x/s390_flic.h" typedef struct CrwContainer { CRW crw; @@ -39,6 +40,13 @@ typedef struct CssImage { ChpInfo chpids[MAX_CHPID + 1]; } CssImage; +typedef struct IoAdapter { + uint32_t id; + uint8_t type; + uint8_t isc; + QTAILQ_ENTRY(IoAdapter) sibling; +} IoAdapter; + typedef struct ChannelSubSys { QTAILQ_HEAD(, CrwContainer) pending_crws; bool do_crw_mchk; @@ -49,6 +57,7 @@ typedef struct ChannelSubSys { uint64_t chnmon_area; CssImage *css[MAX_CSSID + 1]; uint8_t default_cssid; + QTAILQ_HEAD(, IoAdapter) io_adapters; } ChannelSubSys; static ChannelSubSys *channel_subsys; @@ -69,6 +78,46 @@ int css_create_css_image(uint8_t cssid, bool default_image) return 0; } +int css_register_io_adapter(uint8_t type, uint8_t isc, bool swap, + bool maskable, uint32_t *id) +{ + IoAdapter *adapter; + bool found = false; + int ret; + S390FLICState *fs = s390_get_flic(); + S390FLICStateClass *fsc = S390_FLIC_COMMON_GET_CLASS(fs); + + *id = 0; + QTAILQ_FOREACH(adapter, &channel_subsys->io_adapters, sibling) { + if ((adapter->type == type) && (adapter->isc == isc)) { + *id = adapter->id; + found = true; + ret = 0; + break; + } + if (adapter->id >= *id) { + *id = adapter->id + 1; + } + } + if (found) { + goto out; + } + adapter = g_new0(IoAdapter, 1); + ret = fsc->register_io_adapter(fs, *id, isc, swap, maskable); + if (ret == 0) { + adapter->id = *id; + adapter->isc = isc; + adapter->type = type; + QTAILQ_INSERT_TAIL(&channel_subsys->io_adapters, adapter, sibling); + } else { + g_free(adapter); + fprintf(stderr, "Unexpected error %d when registering adapter %d\n", + ret, *id); + } +out: + return ret; +} + uint16_t css_build_subchannel_id(SubchDev *sch) { if (channel_subsys->max_cssid > 0) { @@ -79,13 +128,11 @@ uint16_t css_build_subchannel_id(SubchDev *sch) static void css_inject_io_interrupt(SubchDev *sch) { - S390CPU *cpu = s390_cpu_addr2state(0); uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11; trace_css_io_interrupt(sch->cssid, sch->ssid, sch->schid, sch->curr_status.pmcw.intparm, isc, ""); - s390_io_interrupt(cpu, - css_build_subchannel_id(sch), + s390_io_interrupt(css_build_subchannel_id(sch), sch->schid, sch->curr_status.pmcw.intparm, isc << 27); @@ -98,7 +145,6 @@ void css_conditional_io_interrupt(SubchDev *sch) * with alert status. */ if (!(sch->curr_status.scsw.ctrl & SCSW_STCTL_STATUS_PEND)) { - S390CPU *cpu = s390_cpu_addr2state(0); uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11; trace_css_io_interrupt(sch->cssid, sch->ssid, sch->schid, @@ -108,8 +154,7 @@ void css_conditional_io_interrupt(SubchDev *sch) sch->curr_status.scsw.ctrl |= SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; /* Inject an I/O interrupt. */ - s390_io_interrupt(cpu, - css_build_subchannel_id(sch), + s390_io_interrupt(css_build_subchannel_id(sch), sch->schid, sch->curr_status.pmcw.intparm, isc << 27); @@ -118,11 +163,10 @@ void css_conditional_io_interrupt(SubchDev *sch) void css_adapter_interrupt(uint8_t isc) { - S390CPU *cpu = s390_cpu_addr2state(0); uint32_t io_int_word = (isc << 27) | IO_INT_WORD_AI; trace_css_adapter_interrupt(isc); - s390_io_interrupt(cpu, 0, 0, 0, io_int_word); + s390_io_interrupt(0, 0, 0, io_int_word); } static void sch_handle_clear_func(SubchDev *sch) @@ -140,7 +184,6 @@ static void sch_handle_clear_func(SubchDev *sch) s->flags &= ~SCSW_FLAGS_MASK_PNO; /* We always 'attempt to issue the clear signal', and we always succeed. */ - sch->orb = NULL; sch->channel_prog = 0x0; sch->last_cmd_valid = false; s->ctrl &= ~SCSW_ACTL_CLEAR_PEND; @@ -157,13 +200,13 @@ static void sch_handle_halt_func(SubchDev *sch) PMCW *p = &sch->curr_status.pmcw; SCSW *s = &sch->curr_status.scsw; + hwaddr curr_ccw = sch->channel_prog; int path; /* Path management: In our simple css, we always choose the only path. */ path = 0x80; /* We always 'attempt to issue the halt signal', and we always succeed. */ - sch->orb = NULL; sch->channel_prog = 0x0; sch->last_cmd_valid = false; s->ctrl &= ~SCSW_ACTL_HALT_PEND; @@ -174,6 +217,10 @@ static void sch_handle_halt_func(SubchDev *sch) (s->ctrl & SCSW_ACTL_SUSP))) { s->dstat = SCSW_DSTAT_DEVICE_END; } + if ((s->ctrl & (SCSW_ACTL_SUBCH_ACTIVE | SCSW_ACTL_DEVICE_ACTIVE)) || + (s->ctrl & SCSW_ACTL_SUSP)) { + s->cpa = curr_ccw + 8; + } s->cstat = 0; p->lpum = path; @@ -196,17 +243,25 @@ static void copy_sense_id_to_guest(SenseId *dest, SenseId *src) } } -static CCW1 copy_ccw_from_guest(hwaddr addr) +static CCW1 copy_ccw_from_guest(hwaddr addr, bool fmt1) { - CCW1 tmp; + CCW0 tmp0; + CCW1 tmp1; CCW1 ret; - cpu_physical_memory_read(addr, &tmp, sizeof(tmp)); - ret.cmd_code = tmp.cmd_code; - ret.flags = tmp.flags; - ret.count = be16_to_cpu(tmp.count); - ret.cda = be32_to_cpu(tmp.cda); - + if (fmt1) { + cpu_physical_memory_read(addr, &tmp1, sizeof(tmp1)); + ret.cmd_code = tmp1.cmd_code; + ret.flags = tmp1.flags; + ret.count = be16_to_cpu(tmp1.count); + ret.cda = be32_to_cpu(tmp1.cda); + } else { + cpu_physical_memory_read(addr, &tmp0, sizeof(tmp0)); + ret.cmd_code = tmp0.cmd_code; + ret.flags = tmp0.flags; + ret.count = be16_to_cpu(tmp0.count); + ret.cda = be16_to_cpu(tmp0.cda1) | (tmp0.cda0 << 16); + } return ret; } @@ -221,7 +276,8 @@ static int css_interpret_ccw(SubchDev *sch, hwaddr ccw_addr) return -EIO; } - ccw = copy_ccw_from_guest(ccw_addr); + /* Translate everything to format-1 ccws - the information is the same. */ + ccw = copy_ccw_from_guest(ccw_addr, sch->ccw_fmt_1); /* Check for invalid command codes. */ if ((ccw.cmd_code & 0x0f) == 0) { @@ -238,6 +294,13 @@ static int css_interpret_ccw(SubchDev *sch, hwaddr ccw_addr) check_len = !((ccw.flags & CCW_FLAG_SLI) && !(ccw.flags & CCW_FLAG_DC)); + if (!ccw.cda) { + if (sch->ccw_no_data_cnt == 255) { + return -EINVAL; + } + sch->ccw_no_data_cnt++; + } + /* Look at the command. */ switch (ccw.cmd_code) { case CCW_CMD_NOOP: @@ -317,12 +380,11 @@ static int css_interpret_ccw(SubchDev *sch, hwaddr ccw_addr) return ret; } -static void sch_handle_start_func(SubchDev *sch) +static void sch_handle_start_func(SubchDev *sch, ORB *orb) { PMCW *p = &sch->curr_status.pmcw; SCSW *s = &sch->curr_status.scsw; - ORB *orb = sch->orb; int path; int ret; @@ -331,6 +393,7 @@ static void sch_handle_start_func(SubchDev *sch) if (!(s->ctrl & SCSW_ACTL_SUSP)) { /* Look at the orb and try to execute the channel program. */ + assert(orb != NULL); /* resume does not pass an orb */ p->intparm = orb->intparm; if (!(orb->lpm & path)) { /* Generate a deferred cc 3 condition. */ @@ -339,6 +402,8 @@ static void sch_handle_start_func(SubchDev *sch) s->ctrl |= (SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND); return; } + sch->ccw_fmt_1 = !!(orb->ctrl0 & ORB_CTRL0_MASK_FMT); + sch->ccw_no_data_cnt = 0; } else { s->ctrl &= ~(SCSW_ACTL_SUSP | SCSW_ACTL_RESUME_PEND); } @@ -356,6 +421,7 @@ static void sch_handle_start_func(SubchDev *sch) s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_STATUS_PEND; s->dstat = SCSW_DSTAT_CHANNEL_END | SCSW_DSTAT_DEVICE_END; + s->cpa = sch->channel_prog + 8; break; case -ENOSYS: /* unsupported command, generate unit check (command reject) */ @@ -366,6 +432,7 @@ static void sch_handle_start_func(SubchDev *sch) s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; + s->cpa = sch->channel_prog + 8; break; case -EFAULT: /* memory problem, generate channel data check */ @@ -374,6 +441,7 @@ static void sch_handle_start_func(SubchDev *sch) s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; + s->cpa = sch->channel_prog + 8; break; case -EBUSY: /* subchannel busy, generate deferred cc 1 */ @@ -394,6 +462,7 @@ static void sch_handle_start_func(SubchDev *sch) s->ctrl &= ~SCSW_CTRL_MASK_STCTL; s->ctrl |= SCSW_STCTL_PRIMARY | SCSW_STCTL_SECONDARY | SCSW_STCTL_ALERT | SCSW_STCTL_STATUS_PEND; + s->cpa = sch->channel_prog + 8; break; } } while (ret == -EAGAIN); @@ -406,7 +475,7 @@ static void sch_handle_start_func(SubchDev *sch) * read/writes) asynchronous later on if we start supporting more than * our current very simple devices. */ -static void do_subchannel_work(SubchDev *sch) +static void do_subchannel_work(SubchDev *sch, ORB *orb) { SCSW *s = &sch->curr_status.scsw; @@ -416,7 +485,7 @@ static void do_subchannel_work(SubchDev *sch) } else if (s->ctrl & SCSW_FCTL_HALT_FUNC) { sch_handle_halt_func(sch); } else if (s->ctrl & SCSW_FCTL_START_FUNC) { - sch_handle_start_func(sch); + sch_handle_start_func(sch, orb); } else { /* Cannot happen. */ return; @@ -594,7 +663,6 @@ int css_do_xsch(SubchDev *sch) SCSW_ACTL_SUSP); sch->channel_prog = 0x0; sch->last_cmd_valid = false; - sch->orb = NULL; s->dstat = 0; s->cstat = 0; ret = 0; @@ -618,7 +686,7 @@ int css_do_csch(SubchDev *sch) s->ctrl &= ~(SCSW_CTRL_MASK_FCTL | SCSW_CTRL_MASK_ACTL); s->ctrl |= SCSW_FCTL_CLEAR_FUNC | SCSW_FCTL_CLEAR_FUNC; - do_subchannel_work(sch); + do_subchannel_work(sch, NULL); ret = 0; out: @@ -659,7 +727,7 @@ int css_do_hsch(SubchDev *sch) } s->ctrl |= SCSW_ACTL_HALT_PEND; - do_subchannel_work(sch); + do_subchannel_work(sch, NULL); ret = 0; out: @@ -721,22 +789,23 @@ int css_do_ssch(SubchDev *sch, ORB *orb) if (channel_subsys->chnmon_active) { css_update_chnmon(sch); } - sch->orb = orb; sch->channel_prog = orb->cpa; /* Trigger the start function. */ s->ctrl |= (SCSW_FCTL_START_FUNC | SCSW_ACTL_START_PEND); s->flags &= ~SCSW_FLAGS_MASK_PNO; - do_subchannel_work(sch); + do_subchannel_work(sch, orb); ret = 0; out: return ret; } -static void copy_irb_to_guest(IRB *dest, const IRB *src) +static void copy_irb_to_guest(IRB *dest, const IRB *src, PMCW *pmcw) { int i; + uint16_t stctl = src->scsw.ctrl & SCSW_CTRL_MASK_STCTL; + uint16_t actl = src->scsw.ctrl & SCSW_CTRL_MASK_ACTL; copy_scsw_to_guest(&dest->scsw, &src->scsw); @@ -746,8 +815,22 @@ static void copy_irb_to_guest(IRB *dest, const IRB *src) for (i = 0; i < ARRAY_SIZE(dest->ecw); i++) { dest->ecw[i] = cpu_to_be32(src->ecw[i]); } - for (i = 0; i < ARRAY_SIZE(dest->emw); i++) { - dest->emw[i] = cpu_to_be32(src->emw[i]); + /* extended measurements enabled? */ + if ((src->scsw.flags & SCSW_FLAGS_MASK_ESWF) || + !(pmcw->flags & PMCW_FLAGS_MASK_TF) || + !(pmcw->chars & PMCW_CHARS_MASK_XMWME)) { + return; + } + /* extended measurements pending? */ + if (!(stctl & SCSW_STCTL_STATUS_PEND)) { + return; + } + if ((stctl & SCSW_STCTL_PRIMARY) || + (stctl == SCSW_STCTL_SECONDARY) || + ((stctl & SCSW_STCTL_INTERMEDIATE) && (actl & SCSW_ACTL_SUSP))) { + for (i = 0; i < ARRAY_SIZE(dest->emw); i++) { + dest->emw[i] = cpu_to_be32(src->emw[i]); + } } } @@ -793,7 +876,7 @@ int css_do_tsch(SubchDev *sch, IRB *target_irb) } } /* Store the irb to the guest. */ - copy_irb_to_guest(target_irb, &irb); + copy_irb_to_guest(target_irb, &irb, p); /* Clear conditions on subchannel, if applicable. */ if (stctl & SCSW_STCTL_STATUS_PEND) { @@ -957,7 +1040,7 @@ int css_do_rsch(SubchDev *sch) } s->ctrl |= SCSW_ACTL_RESUME_PEND; - do_subchannel_work(sch); + do_subchannel_work(sch, NULL); ret = 0; out: @@ -1170,11 +1253,9 @@ void css_queue_crw(uint8_t rsc, uint8_t erc, int chain, uint16_t rsid) QTAILQ_INSERT_TAIL(&channel_subsys->pending_crws, crw_cont, sibling); if (channel_subsys->do_crw_mchk) { - S390CPU *cpu = s390_cpu_addr2state(0); - channel_subsys->do_crw_mchk = false; /* Inject crw pending machine check. */ - s390_crw_mchk(cpu); + s390_crw_mchk(); } } @@ -1232,6 +1313,121 @@ int css_enable_mss(void) return 0; } +void subch_device_save(SubchDev *s, QEMUFile *f) +{ + int i; + + qemu_put_byte(f, s->cssid); + qemu_put_byte(f, s->ssid); + qemu_put_be16(f, s->schid); + qemu_put_be16(f, s->devno); + qemu_put_byte(f, s->thinint_active); + /* SCHIB */ + /* PMCW */ + qemu_put_be32(f, s->curr_status.pmcw.intparm); + qemu_put_be16(f, s->curr_status.pmcw.flags); + qemu_put_be16(f, s->curr_status.pmcw.devno); + qemu_put_byte(f, s->curr_status.pmcw.lpm); + qemu_put_byte(f, s->curr_status.pmcw.pnom); + qemu_put_byte(f, s->curr_status.pmcw.lpum); + qemu_put_byte(f, s->curr_status.pmcw.pim); + qemu_put_be16(f, s->curr_status.pmcw.mbi); + qemu_put_byte(f, s->curr_status.pmcw.pom); + qemu_put_byte(f, s->curr_status.pmcw.pam); + qemu_put_buffer(f, s->curr_status.pmcw.chpid, 8); + qemu_put_be32(f, s->curr_status.pmcw.chars); + /* SCSW */ + qemu_put_be16(f, s->curr_status.scsw.flags); + qemu_put_be16(f, s->curr_status.scsw.ctrl); + qemu_put_be32(f, s->curr_status.scsw.cpa); + qemu_put_byte(f, s->curr_status.scsw.dstat); + qemu_put_byte(f, s->curr_status.scsw.cstat); + qemu_put_be16(f, s->curr_status.scsw.count); + qemu_put_be64(f, s->curr_status.mba); + qemu_put_buffer(f, s->curr_status.mda, 4); + /* end SCHIB */ + qemu_put_buffer(f, s->sense_data, 32); + qemu_put_be64(f, s->channel_prog); + /* last cmd */ + qemu_put_byte(f, s->last_cmd.cmd_code); + qemu_put_byte(f, s->last_cmd.flags); + qemu_put_be16(f, s->last_cmd.count); + qemu_put_be32(f, s->last_cmd.cda); + qemu_put_byte(f, s->last_cmd_valid); + qemu_put_byte(f, s->id.reserved); + qemu_put_be16(f, s->id.cu_type); + qemu_put_byte(f, s->id.cu_model); + qemu_put_be16(f, s->id.dev_type); + qemu_put_byte(f, s->id.dev_model); + qemu_put_byte(f, s->id.unused); + for (i = 0; i < ARRAY_SIZE(s->id.ciw); i++) { + qemu_put_byte(f, s->id.ciw[i].type); + qemu_put_byte(f, s->id.ciw[i].command); + qemu_put_be16(f, s->id.ciw[i].count); + } + qemu_put_byte(f, s->ccw_fmt_1); + qemu_put_byte(f, s->ccw_no_data_cnt); + return; +} + +int subch_device_load(SubchDev *s, QEMUFile *f) +{ + int i; + + s->cssid = qemu_get_byte(f); + s->ssid = qemu_get_byte(f); + s->schid = qemu_get_be16(f); + s->devno = qemu_get_be16(f); + s->thinint_active = qemu_get_byte(f); + /* SCHIB */ + /* PMCW */ + s->curr_status.pmcw.intparm = qemu_get_be32(f); + s->curr_status.pmcw.flags = qemu_get_be16(f); + s->curr_status.pmcw.devno = qemu_get_be16(f); + s->curr_status.pmcw.lpm = qemu_get_byte(f); + s->curr_status.pmcw.pnom = qemu_get_byte(f); + s->curr_status.pmcw.lpum = qemu_get_byte(f); + s->curr_status.pmcw.pim = qemu_get_byte(f); + s->curr_status.pmcw.mbi = qemu_get_be16(f); + s->curr_status.pmcw.pom = qemu_get_byte(f); + s->curr_status.pmcw.pam = qemu_get_byte(f); + qemu_get_buffer(f, s->curr_status.pmcw.chpid, 8); + s->curr_status.pmcw.chars = qemu_get_be32(f); + /* SCSW */ + s->curr_status.scsw.flags = qemu_get_be16(f); + s->curr_status.scsw.ctrl = qemu_get_be16(f); + s->curr_status.scsw.cpa = qemu_get_be32(f); + s->curr_status.scsw.dstat = qemu_get_byte(f); + s->curr_status.scsw.cstat = qemu_get_byte(f); + s->curr_status.scsw.count = qemu_get_be16(f); + s->curr_status.mba = qemu_get_be64(f); + qemu_get_buffer(f, s->curr_status.mda, 4); + /* end SCHIB */ + qemu_get_buffer(f, s->sense_data, 32); + s->channel_prog = qemu_get_be64(f); + /* last cmd */ + s->last_cmd.cmd_code = qemu_get_byte(f); + s->last_cmd.flags = qemu_get_byte(f); + s->last_cmd.count = qemu_get_be16(f); + s->last_cmd.cda = qemu_get_be32(f); + s->last_cmd_valid = qemu_get_byte(f); + s->id.reserved = qemu_get_byte(f); + s->id.cu_type = qemu_get_be16(f); + s->id.cu_model = qemu_get_byte(f); + s->id.dev_type = qemu_get_be16(f); + s->id.dev_model = qemu_get_byte(f); + s->id.unused = qemu_get_byte(f); + for (i = 0; i < ARRAY_SIZE(s->id.ciw); i++) { + s->id.ciw[i].type = qemu_get_byte(f); + s->id.ciw[i].command = qemu_get_byte(f); + s->id.ciw[i].count = qemu_get_be16(f); + } + s->ccw_fmt_1 = qemu_get_byte(f); + s->ccw_no_data_cnt = qemu_get_byte(f); + return 0; +} + + static void css_init(void) { channel_subsys = g_malloc0(sizeof(*channel_subsys)); @@ -1239,6 +1435,7 @@ static void css_init(void) channel_subsys->do_crw_mchk = true; channel_subsys->crws_lost = false; channel_subsys->chnmon_active = false; + QTAILQ_INIT(&channel_subsys->io_adapters); } machine_init(css_init); @@ -1267,7 +1464,6 @@ void css_reset_sch(SubchDev *sch) sch->channel_prog = 0x0; sch->last_cmd_valid = false; - sch->orb = NULL; sch->thinint_active = false; } diff --git a/hw/s390x/css.h b/hw/s390x/css.h index e9b440540d..33104ac58e 100644 --- a/hw/s390x/css.h +++ b/hw/s390x/css.h @@ -76,8 +76,9 @@ struct SubchDev { hwaddr channel_prog; CCW1 last_cmd; bool last_cmd_valid; - ORB *orb; + bool ccw_fmt_1; bool thinint_active; + uint8_t ccw_no_data_cnt; /* transport-provided data: */ int (*ccw_cb) (SubchDev *, CCW1); SenseId id; @@ -86,6 +87,8 @@ struct SubchDev { typedef SubchDev *(*css_subch_cb_func)(uint8_t m, uint8_t cssid, uint8_t ssid, uint16_t schid); +void subch_device_save(SubchDev *s, QEMUFile *f); +int subch_device_load(SubchDev *s, QEMUFile *f); int css_create_css_image(uint8_t cssid, bool default_image); bool css_devno_used(uint8_t cssid, uint8_t ssid, uint16_t devno); void css_subch_assign(uint8_t cssid, uint8_t ssid, uint16_t schid, @@ -99,4 +102,8 @@ void css_generate_sch_crws(uint8_t cssid, uint8_t ssid, uint16_t schid, int hotplugged, int add); void css_generate_chp_crws(uint8_t cssid, uint8_t chpid); void css_adapter_interrupt(uint8_t isc); + +#define CSS_IO_ADAPTER_VIRTIO 1 +int css_register_io_adapter(uint8_t type, uint8_t isc, bool swap, + bool maskable, uint32_t *id); #endif diff --git a/hw/s390x/event-facility.c b/hw/s390x/event-facility.c index 0777a93916..78da718362 100644 --- a/hw/s390x/event-facility.c +++ b/hw/s390x/event-facility.c @@ -32,7 +32,7 @@ struct SCLPEventFacility { unsigned int receive_mask; }; -SCLPEvent cpu_hotplug; +static SCLPEvent cpu_hotplug; /* return true if any child has event pending set */ static bool event_pending(SCLPEventFacility *ef) @@ -319,8 +319,7 @@ static const VMStateDescription vmstate_event_facility = { .name = "vmstate-event-facility", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(receive_mask, SCLPEventFacility), VMSTATE_END_OF_LIST() } @@ -334,7 +333,6 @@ static int init_event_facility(SCLPEventFacility *event_facility) /* Spawn a new bus for SCLP events */ qbus_create_inplace(&event_facility->sbus, sizeof(event_facility->sbus), TYPE_SCLP_EVENTS_BUS, sdev, NULL); - event_facility->sbus.qbus.allow_hotplug = 0; quiesce = qdev_create(&event_facility->sbus.qbus, "sclpquiesce"); if (!quiesce) { @@ -409,7 +407,6 @@ static void event_class_init(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); dc->bus_type = TYPE_SCLP_EVENTS_BUS; - dc->unplug = qdev_simple_unplug_cb; dc->realize = event_realize; dc->unrealize = event_unrealize; } diff --git a/hw/s390x/ipl.c b/hw/s390x/ipl.c index 4fa9cffded..3b77c9a227 100644 --- a/hw/s390x/ipl.c +++ b/hw/s390x/ipl.c @@ -176,7 +176,7 @@ static void s390_ipl_reset(DeviceState *dev) } } - s390_add_running_cpu(cpu); + s390_cpu_set_state(CPU_STATE_OPERATING, cpu); } static void s390_ipl_class_init(ObjectClass *klass, void *data) diff --git a/hw/s390x/s390-virtio-bus.c b/hw/s390x/s390-virtio-bus.c index 9c71afa031..39dc2011b9 100644 --- a/hw/s390x/s390-virtio-bus.c +++ b/hw/s390x/s390-virtio-bus.c @@ -18,7 +18,7 @@ */ #include "hw/hw.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "hw/boards.h" #include "monitor/monitor.h" @@ -45,8 +45,6 @@ do { } while (0) #endif -#define VIRTIO_EXT_CODE 0x2603 - static void virtio_s390_bus_new(VirtioBusState *bus, size_t bus_size, VirtIOS390Device *dev); @@ -104,7 +102,7 @@ VirtIOS390Bus *s390_virtio_bus_init(ram_addr_t *ram_size) bus->next_ring = bus->dev_page + TARGET_PAGE_SIZE; /* Enable hotplugging */ - _bus->allow_hotplug = 1; + qbus_set_hotplug_handler(_bus, dev, &error_abort); /* Allocate RAM for VirtIO device pages (descriptors, queues, rings) */ *ram_size += S390_DEVICE_PAGES * TARGET_PAGE_SIZE; @@ -113,15 +111,6 @@ VirtIOS390Bus *s390_virtio_bus_init(ram_addr_t *ram_size) return bus; } -static void s390_virtio_irq(S390CPU *cpu, int config_change, uint64_t token) -{ - if (kvm_enabled()) { - kvm_s390_virtio_irq(cpu, config_change, token); - } else { - cpu_inject_ext(cpu, VIRTIO_EXT_CODE, config_change, token); - } -} - static int s390_virtio_device_init(VirtIOS390Device *dev, VirtIODevice *vdev) { VirtIOS390Bus *bus; @@ -144,8 +133,7 @@ static int s390_virtio_device_init(VirtIOS390Device *dev, VirtIODevice *vdev) s390_virtio_device_sync(dev); s390_virtio_reset_idx(dev); if (dev->qdev.hotplugged) { - S390CPU *cpu = s390_cpu_addr2state(0); - s390_virtio_irq(cpu, VIRTIO_PARAM_DEV_ADD, dev->dev_offs); + s390_virtio_irq(VIRTIO_PARAM_DEV_ADD, dev->dev_offs); } return 0; @@ -171,15 +159,17 @@ static int s390_virtio_net_init(VirtIOS390Device *s390_dev) static void s390_virtio_net_instance_init(Object *obj) { VirtIONetS390 *dev = VIRTIO_NET_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_NET); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_NET); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static int s390_virtio_blk_init(VirtIOS390Device *s390_dev) { VirtIOBlkS390 *dev = VIRTIO_BLK_S390(s390_dev); DeviceState *vdev = DEVICE(&dev->vdev); - virtio_blk_set_conf(vdev, &(dev->blk)); qdev_set_parent_bus(vdev, BUS(&s390_dev->bus)); if (qdev_init(vdev) < 0) { return -1; @@ -190,8 +180,13 @@ static int s390_virtio_blk_init(VirtIOS390Device *s390_dev) static void s390_virtio_blk_instance_init(Object *obj) { VirtIOBlkS390 *dev = VIRTIO_BLK_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_BLK); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_BLK); + object_property_add_alias(obj, "iothread", OBJECT(&dev->vdev),"iothread", + &error_abort); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static int s390_virtio_serial_init(VirtIOS390Device *s390_dev) @@ -231,8 +226,9 @@ static int s390_virtio_serial_init(VirtIOS390Device *s390_dev) static void s390_virtio_serial_instance_init(Object *obj) { VirtIOSerialS390 *dev = VIRTIO_SERIAL_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SERIAL); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SERIAL); } static int s390_virtio_scsi_init(VirtIOS390Device *s390_dev) @@ -263,8 +259,9 @@ static int s390_virtio_scsi_init(VirtIOS390Device *s390_dev) static void s390_virtio_scsi_instance_init(Object *obj) { VirtIOSCSIS390 *dev = VIRTIO_SCSI_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SCSI); } #ifdef CONFIG_VHOST_SCSI @@ -284,8 +281,9 @@ static int s390_vhost_scsi_init(VirtIOS390Device *s390_dev) static void s390_vhost_scsi_instance_init(Object *obj) { VHostSCSIS390 *dev = VHOST_SCSI_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VHOST_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VHOST_SCSI); } #endif @@ -310,12 +308,11 @@ static int s390_virtio_rng_init(VirtIOS390Device *s390_dev) static void s390_virtio_rng_instance_init(Object *obj) { VirtIORNGS390 *dev = VIRTIO_RNG_S390(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_RNG); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); - object_property_add_link(obj, "rng", TYPE_RNG_BACKEND, - (Object **)&dev->vdev.conf.rng, - qdev_prop_allow_set_link_before_realize, - OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_RNG); + object_property_add_alias(obj, "rng", OBJECT(&dev->vdev), + "rng", &error_abort); } static uint64_t s390_virtio_device_vq_token(VirtIOS390Device *dev, int vq) @@ -489,9 +486,8 @@ static void virtio_s390_notify(DeviceState *d, uint16_t vector) { VirtIOS390Device *dev = to_virtio_s390_device_fast(d); uint64_t token = s390_virtio_device_vq_token(dev, vector); - S390CPU *cpu = s390_cpu_addr2state(0); - s390_virtio_irq(cpu, 0, token); + s390_virtio_irq(0, token); } static unsigned virtio_s390_get_features(DeviceState *d) @@ -503,9 +499,8 @@ static unsigned virtio_s390_get_features(DeviceState *d) /**************** S390 Virtio Bus Device Descriptions *******************/ static Property s390_virtio_net_properties[] = { - DEFINE_NIC_PROPERTIES(VirtIONetS390, vdev.nic_conf), + DEFINE_VIRTIO_COMMON_FEATURES(VirtIOS390Device, host_features), DEFINE_VIRTIO_NET_FEATURES(VirtIOS390Device, host_features), - DEFINE_VIRTIO_NET_PROPERTIES(VirtIONetS390, vdev.net_conf), DEFINE_PROP_END_OF_LIST(), }; @@ -526,18 +521,11 @@ static const TypeInfo s390_virtio_net = { .class_init = s390_virtio_net_class_init, }; -static Property s390_virtio_blk_properties[] = { - DEFINE_VIRTIO_BLK_PROPERTIES(VirtIOBlkS390, blk), - DEFINE_PROP_END_OF_LIST(), -}; - static void s390_virtio_blk_class_init(ObjectClass *klass, void *data) { - DeviceClass *dc = DEVICE_CLASS(klass); VirtIOS390DeviceClass *k = VIRTIO_S390_DEVICE_CLASS(klass); k->init = s390_virtio_blk_init; - dc->props = s390_virtio_blk_properties; } static const TypeInfo s390_virtio_blk = { @@ -549,7 +537,6 @@ static const TypeInfo s390_virtio_blk = { }; static Property s390_virtio_serial_properties[] = { - DEFINE_VIRTIO_SERIAL_PROPERTIES(VirtIOSerialS390, vdev.serial), DEFINE_PROP_END_OF_LIST(), }; @@ -572,7 +559,6 @@ static const TypeInfo s390_virtio_serial = { static Property s390_virtio_rng_properties[] = { DEFINE_VIRTIO_COMMON_FEATURES(VirtIOS390Device, host_features), - DEFINE_VIRTIO_RNG_PROPERTIES(VirtIORNGS390, vdev.conf), DEFINE_PROP_END_OF_LIST(), }; @@ -616,7 +602,6 @@ static void virtio_s390_device_class_init(ObjectClass *klass, void *data) dc->init = s390_virtio_busdev_init; dc->bus_type = TYPE_S390_VIRTIO_BUS; - dc->unplug = qdev_simple_unplug_cb; dc->reset = s390_virtio_busdev_reset; } @@ -630,7 +615,7 @@ static const TypeInfo virtio_s390_device_info = { }; static Property s390_virtio_scsi_properties[] = { - DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOSCSIS390, vdev.parent_obj.conf), + DEFINE_VIRTIO_COMMON_FEATURES(VirtIOS390Device, host_features), DEFINE_VIRTIO_SCSI_FEATURES(VirtIOS390Device, host_features), DEFINE_PROP_END_OF_LIST(), }; @@ -655,7 +640,6 @@ static const TypeInfo s390_virtio_scsi = { #ifdef CONFIG_VHOST_SCSI static Property s390_vhost_scsi_properties[] = { DEFINE_VIRTIO_COMMON_FEATURES(VirtIOS390Device, host_features), - DEFINE_VHOST_SCSI_PROPERTIES(VHostSCSIS390, vdev.parent_obj.conf), DEFINE_PROP_END_OF_LIST(), }; @@ -698,6 +682,10 @@ static const TypeInfo s390_virtio_bridge_info = { .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(SysBusDevice), .class_init = s390_virtio_bridge_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; /* virtio-s390-bus */ @@ -706,13 +694,10 @@ static void virtio_s390_bus_new(VirtioBusState *bus, size_t bus_size, VirtIOS390Device *dev) { DeviceState *qdev = DEVICE(dev); - BusState *qbus; char virtio_bus_name[] = "virtio-bus"; qbus_create_inplace(bus, bus_size, TYPE_VIRTIO_S390_BUS, qdev, virtio_bus_name); - qbus = BUS(bus); - qbus->allow_hotplug = 1; } static void virtio_s390_bus_class_init(ObjectClass *klass, void *data) diff --git a/hw/s390x/s390-virtio-bus.h b/hw/s390x/s390-virtio-bus.h index ac81bd89ee..ffd0df708b 100644 --- a/hw/s390x/s390-virtio-bus.h +++ b/hw/s390x/s390-virtio-bus.h @@ -124,7 +124,6 @@ void s390_virtio_reset_idx(VirtIOS390Device *dev); typedef struct VirtIOBlkS390 { VirtIOS390Device parent_obj; VirtIOBlock vdev; - VirtIOBlkConf blk; } VirtIOBlkS390; /* virtio-scsi-s390 */ diff --git a/hw/s390x/s390-virtio-ccw.c b/hw/s390x/s390-virtio-ccw.c index 0d4f6ae2f3..bc4dc2ae8a 100644 --- a/hw/s390x/s390-virtio-ccw.c +++ b/hw/s390x/s390-virtio-ccw.c @@ -17,6 +17,9 @@ #include "ioinst.h" #include "css.h" #include "virtio-ccw.h" +#include "qemu/config-file.h" + +#define TYPE_S390_CCW_MACHINE "s390-ccw-machine" void io_subsystem_reset(void) { @@ -79,22 +82,40 @@ static void virtio_ccw_register_hcalls(void) virtio_ccw_hcall_early_printk); } -static void ccw_init(QEMUMachineInitArgs *args) +static void ccw_init(MachineState *machine) { - ram_addr_t my_ram_size = args->ram_size; + ram_addr_t my_ram_size = machine->ram_size; MemoryRegion *sysmem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); - int shift = 0; + sclpMemoryHotplugDev *mhd = init_sclp_memory_hotplug_dev(); uint8_t *storage_keys; int ret; VirtualCssBus *css_bus; - - /* s390x ram size detection needs a 16bit multiplier + an increment. So - guests > 64GB can be specified in 2MB steps etc. */ - while ((my_ram_size >> (20 + shift)) > 65535) { - shift++; + QemuOpts *opts = qemu_opts_find(qemu_find_opts("memory"), NULL); + ram_addr_t pad_size = 0; + ram_addr_t maxmem = qemu_opt_get_size(opts, "maxmem", my_ram_size); + ram_addr_t standby_mem_size = maxmem - my_ram_size; + + /* The storage increment size is a multiple of 1M and is a power of 2. + * The number of storage increments must be MAX_STORAGE_INCREMENTS or fewer. + * The variable 'mhd->increment_size' is an exponent of 2 that can be + * used to calculate the size (in bytes) of an increment. */ + mhd->increment_size = 20; + while ((my_ram_size >> mhd->increment_size) > MAX_STORAGE_INCREMENTS) { + mhd->increment_size++; + } + while ((standby_mem_size >> mhd->increment_size) > MAX_STORAGE_INCREMENTS) { + mhd->increment_size++; } - my_ram_size = my_ram_size >> (20 + shift) << (20 + shift); + + /* The core and standby memory areas need to be aligned with + * the increment size. In effect, this can cause the + * user-specified memory size to be rounded down to align + * with the nearest increment boundary. */ + standby_mem_size = standby_mem_size >> mhd->increment_size + << mhd->increment_size; + my_ram_size = my_ram_size >> mhd->increment_size + << mhd->increment_size; /* let's propagate the changed ram size into the global variable. */ ram_size = my_ram_size; @@ -102,23 +123,34 @@ static void ccw_init(QEMUMachineInitArgs *args) /* get a BUS */ css_bus = virtual_css_bus_init(); s390_sclp_init(); - s390_init_ipl_dev(args->kernel_filename, args->kernel_cmdline, - args->initrd_filename, "s390-ccw.img"); + s390_init_ipl_dev(machine->kernel_filename, machine->kernel_cmdline, + machine->initrd_filename, "s390-ccw.img"); s390_flic_init(); /* register hypercalls */ virtio_ccw_register_hcalls(); - /* allocate RAM */ - memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size); + /* allocate RAM for core */ + memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(sysmem, 0, ram); + /* If the size of ram is not on a MEM_SECTION_SIZE boundary, + calculate the pad size necessary to force this boundary. */ + if (standby_mem_size) { + if (my_ram_size % MEM_SECTION_SIZE) { + pad_size = MEM_SECTION_SIZE - my_ram_size % MEM_SECTION_SIZE; + } + my_ram_size += standby_mem_size + pad_size; + mhd->pad_size = pad_size; + mhd->standby_mem_size = standby_mem_size; + } + /* allocate storage keys */ storage_keys = g_malloc0(my_ram_size / TARGET_PAGE_SIZE); /* init CPUs */ - s390_init_cpus(args->cpu_model, storage_keys); + s390_init_cpus(machine->cpu_model, storage_keys); if (kvm_enabled()) { kvm_s390_enable_css_support(s390_cpu_addr2state(0)); @@ -134,24 +166,39 @@ static void ccw_init(QEMUMachineInitArgs *args) s390_create_virtio_net(BUS(css_bus), "virtio-net-ccw"); } -static QEMUMachine ccw_machine = { - .name = "s390-ccw-virtio", - .alias = "s390-ccw", - .desc = "VirtIO-ccw based S390 machine", - .init = ccw_init, - .block_default_type = IF_VIRTIO, - .no_cdrom = 1, - .no_floppy = 1, - .no_serial = 1, - .no_parallel = 1, - .no_sdcard = 1, - .use_sclp = 1, - .max_cpus = 255, +static void ccw_machine_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + NMIClass *nc = NMI_CLASS(oc); + + mc->name = "s390-ccw-virtio"; + mc->alias = "s390-ccw"; + mc->desc = "VirtIO-ccw based S390 machine"; + mc->init = ccw_init; + mc->block_default_type = IF_VIRTIO; + mc->no_cdrom = 1; + mc->no_floppy = 1; + mc->no_serial = 1; + mc->no_parallel = 1; + mc->no_sdcard = 1; + mc->use_sclp = 1, + mc->max_cpus = 255; + nc->nmi_monitor_handler = s390_nmi; +} + +static const TypeInfo ccw_machine_info = { + .name = TYPE_S390_CCW_MACHINE, + .parent = TYPE_MACHINE, + .class_init = ccw_machine_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_NMI }, + { } + }, }; -static void ccw_machine_init(void) +static void ccw_machine_register_types(void) { - qemu_register_machine(&ccw_machine); + type_register_static(&ccw_machine_info); } -machine_init(ccw_machine_init) +type_init(ccw_machine_register_types) diff --git a/hw/s390x/s390-virtio.c b/hw/s390x/s390-virtio.c index aef200310c..c215cd80e3 100644 --- a/hw/s390x/s390-virtio.c +++ b/hw/s390x/s390-virtio.c @@ -22,7 +22,7 @@ */ #include "hw/hw.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "sysemu/sysemu.h" #include "net/net.h" @@ -51,6 +51,7 @@ #define MAX_BLK_DEVS 10 #define ZIPL_FILENAME "s390-zipl.rom" +#define TYPE_S390_MACHINE "s390-machine" static VirtIOS390Bus *s390_bus; static S390CPU **ipi_states; @@ -124,38 +125,6 @@ static void s390_virtio_register_hcalls(void) s390_virtio_hcall_set_status); } -/* - * The number of running CPUs. On s390 a shutdown is the state of all CPUs - * being either stopped or disabled (for interrupts) waiting. We have to - * track this number to call the shutdown sequence accordingly. This - * number is modified either on startup or while holding the big qemu lock. - */ -static unsigned s390_running_cpus; - -void s390_add_running_cpu(S390CPU *cpu) -{ - CPUState *cs = CPU(cpu); - - if (cs->halted) { - s390_running_cpus++; - cs->halted = 0; - cs->exception_index = -1; - } -} - -unsigned s390_del_running_cpu(S390CPU *cpu) -{ - CPUState *cs = CPU(cpu); - - if (cs->halted == 0) { - assert(s390_running_cpus >= 1); - s390_running_cpus--; - cs->halted = 1; - cs->exception_index = EXCP_HLT; - } - return s390_running_cpus; -} - void s390_init_ipl_dev(const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, @@ -224,23 +193,26 @@ void s390_create_virtio_net(BusState *bus, const char *name) } /* PC hardware initialisation */ -static void s390_init(QEMUMachineInitArgs *args) +static void s390_init(MachineState *machine) { - ram_addr_t my_ram_size = args->ram_size; + ram_addr_t my_ram_size = machine->ram_size; MemoryRegion *sysmem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); - int shift = 0; + int increment_size = 20; uint8_t *storage_keys; void *virtio_region; hwaddr virtio_region_len; hwaddr virtio_region_start; - /* s390x ram size detection needs a 16bit multiplier + an increment. So - guests > 64GB can be specified in 2MB steps etc. */ - while ((my_ram_size >> (20 + shift)) > 65535) { - shift++; + /* + * The storage increment size is a multiple of 1M and is a power of 2. + * The number of storage increments must be MAX_STORAGE_INCREMENTS or + * fewer. + */ + while ((my_ram_size >> increment_size) > MAX_STORAGE_INCREMENTS) { + increment_size++; } - my_ram_size = my_ram_size >> (20 + shift) << (20 + shift); + my_ram_size = my_ram_size >> increment_size << increment_size; /* let's propagate the changed ram size into the global variable. */ ram_size = my_ram_size; @@ -248,15 +220,15 @@ static void s390_init(QEMUMachineInitArgs *args) /* get a BUS */ s390_bus = s390_virtio_bus_init(&my_ram_size); s390_sclp_init(); - s390_init_ipl_dev(args->kernel_filename, args->kernel_cmdline, - args->initrd_filename, ZIPL_FILENAME); + s390_init_ipl_dev(machine->kernel_filename, machine->kernel_cmdline, + machine->initrd_filename, ZIPL_FILENAME); s390_flic_init(); /* register hypercalls */ s390_virtio_register_hcalls(); /* allocate RAM */ - memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size); + memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(sysmem, 0, ram); @@ -273,31 +245,55 @@ static void s390_init(QEMUMachineInitArgs *args) storage_keys = g_malloc0(my_ram_size / TARGET_PAGE_SIZE); /* init CPUs */ - s390_init_cpus(args->cpu_model, storage_keys); + s390_init_cpus(machine->cpu_model, storage_keys); /* Create VirtIO network adapters */ s390_create_virtio_net((BusState *)s390_bus, "virtio-net-s390"); } -static QEMUMachine s390_machine = { - .name = "s390-virtio", - .alias = "s390", - .desc = "VirtIO based S390 machine", - .init = s390_init, - .block_default_type = IF_VIRTIO, - .no_cdrom = 1, - .no_floppy = 1, - .no_serial = 1, - .no_parallel = 1, - .no_sdcard = 1, - .use_virtcon = 1, - .max_cpus = 255, - .is_default = 1, +void s390_nmi(NMIState *n, int cpu_index, Error **errp) +{ + CPUState *cs = qemu_get_cpu(cpu_index); + + if (s390_cpu_restart(S390_CPU(cs))) { + error_set(errp, QERR_UNSUPPORTED); + } +} + +static void s390_machine_class_init(ObjectClass *oc, void *data) +{ + MachineClass *mc = MACHINE_CLASS(oc); + NMIClass *nc = NMI_CLASS(oc); + + mc->name = "s390-virtio"; + mc->alias = "s390"; + mc->desc = "VirtIO based S390 machine"; + mc->init = s390_init; + mc->block_default_type = IF_VIRTIO; + mc->max_cpus = 255; + mc->no_serial = 1; + mc->no_parallel = 1; + mc->use_virtcon = 1; + mc->no_floppy = 1; + mc->no_cdrom = 1; + mc->no_sdcard = 1; + mc->is_default = 1; + nc->nmi_monitor_handler = s390_nmi; +} + +static const TypeInfo s390_machine_info = { + .name = TYPE_S390_MACHINE, + .parent = TYPE_MACHINE, + .class_init = s390_machine_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_NMI }, + { } + }, }; -static void s390_machine_init(void) +static void s390_machine_register_types(void) { - qemu_register_machine(&s390_machine); + type_register_static(&s390_machine_info); } -machine_init(s390_machine_init); +type_init(s390_machine_register_types) diff --git a/hw/s390x/s390-virtio.h b/hw/s390x/s390-virtio.h index 5c405e7755..33847aefcf 100644 --- a/hw/s390x/s390-virtio.h +++ b/hw/s390x/s390-virtio.h @@ -12,6 +12,8 @@ #ifndef HW_S390_VIRTIO_H #define HW_S390_VIRTIO_H 1 +#include "hw/nmi.h" + #define KVM_S390_VIRTIO_NOTIFY 0 #define KVM_S390_VIRTIO_RESET 1 #define KVM_S390_VIRTIO_SET_STATUS 2 @@ -26,4 +28,5 @@ void s390_init_ipl_dev(const char *kernel_filename, const char *initrd_filename, const char *firmware); void s390_create_virtio_net(BusState *bus, const char *name); +void s390_nmi(NMIState *n, int cpu_index, Error **errp); #endif diff --git a/hw/s390x/sclp.c b/hw/s390x/sclp.c index d8ddf35e58..a759da7f34 100644 --- a/hw/s390x/sclp.c +++ b/hw/s390x/sclp.c @@ -16,7 +16,8 @@ #include "sysemu/kvm.h" #include "exec/memory.h" #include "sysemu/sysemu.h" - +#include "exec/address-spaces.h" +#include "qemu/config-file.h" #include "hw/s390x/sclp.h" #include "hw/s390x/event-facility.h" @@ -33,10 +34,19 @@ static inline SCLPEventFacility *get_event_facility(void) static void read_SCP_info(SCCB *sccb) { ReadInfo *read_info = (ReadInfo *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); CPUState *cpu; - int shift = 0; int cpu_count = 0; int i = 0; + int increment_size = 20; + int rnsize, rnmax; + QemuOpts *opts = qemu_opts_find(qemu_find_opts("memory"), NULL); + int slots = qemu_opt_get_number(opts, "slots", 0); + int max_avail_slots = s390_get_memslot_count(kvm_state); + + if (slots > max_avail_slots) { + slots = max_avail_slots; + } CPU_FOREACH(cpu) { cpu_count++; @@ -54,14 +64,235 @@ static void read_SCP_info(SCCB *sccb) read_info->facilities = cpu_to_be64(SCLP_HAS_CPU_INFO); - while ((ram_size >> (20 + shift)) > 65535) { - shift++; + /* + * The storage increment size is a multiple of 1M and is a power of 2. + * The number of storage increments must be MAX_STORAGE_INCREMENTS or fewer. + */ + while ((ram_size >> increment_size) > MAX_STORAGE_INCREMENTS) { + increment_size++; + } + rnmax = ram_size >> increment_size; + + /* Memory Hotplug is only supported for the ccw machine type */ + if (mhd) { + while ((mhd->standby_mem_size >> increment_size) > + MAX_STORAGE_INCREMENTS) { + increment_size++; + } + assert(increment_size == mhd->increment_size); + + mhd->standby_subregion_size = MEM_SECTION_SIZE; + /* Deduct the memory slot already used for core */ + if (slots > 0) { + while ((mhd->standby_subregion_size * (slots - 1) + < mhd->standby_mem_size)) { + mhd->standby_subregion_size = mhd->standby_subregion_size << 1; + } + } + /* + * Initialize mapping of guest standby memory sections indicating which + * are and are not online. Assume all standby memory begins offline. + */ + if (mhd->standby_state_map == 0) { + if (mhd->standby_mem_size % mhd->standby_subregion_size) { + mhd->standby_state_map = g_malloc0((mhd->standby_mem_size / + mhd->standby_subregion_size + 1) * + (mhd->standby_subregion_size / + MEM_SECTION_SIZE)); + } else { + mhd->standby_state_map = g_malloc0(mhd->standby_mem_size / + MEM_SECTION_SIZE); + } + } + mhd->padded_ram_size = ram_size + mhd->pad_size; + mhd->rzm = 1 << mhd->increment_size; + rnmax = ((ram_size + mhd->standby_mem_size + mhd->pad_size) + >> mhd->increment_size); + + read_info->facilities |= cpu_to_be64(SCLP_FC_ASSIGN_ATTACH_READ_STOR); + } + + rnsize = 1 << (increment_size - 20); + if (rnsize <= 128) { + read_info->rnsize = rnsize; + } else { + read_info->rnsize = 0; + read_info->rnsize2 = cpu_to_be32(rnsize); + } + + if (rnmax < 0x10000) { + read_info->rnmax = cpu_to_be16(rnmax); + } else { + read_info->rnmax = cpu_to_be16(0); + read_info->rnmax2 = cpu_to_be64(rnmax); } - read_info->rnmax = cpu_to_be16(ram_size >> (20 + shift)); - read_info->rnsize = 1 << shift; + sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_READ_COMPLETION); } +static void read_storage_element0_info(SCCB *sccb) +{ + int i, assigned; + int subincrement_id = SCLP_STARTING_SUBINCREMENT_ID; + ReadStorageElementInfo *storage_info = (ReadStorageElementInfo *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); + + assert(mhd); + + if ((ram_size >> mhd->increment_size) >= 0x10000) { + sccb->h.response_code = cpu_to_be16(SCLP_RC_SCCB_BOUNDARY_VIOLATION); + return; + } + + /* Return information regarding core memory */ + storage_info->max_id = cpu_to_be16(mhd->standby_mem_size ? 1 : 0); + assigned = ram_size >> mhd->increment_size; + storage_info->assigned = cpu_to_be16(assigned); + + for (i = 0; i < assigned; i++) { + storage_info->entries[i] = cpu_to_be32(subincrement_id); + subincrement_id += SCLP_INCREMENT_UNIT; + } + sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_READ_COMPLETION); +} + +static void read_storage_element1_info(SCCB *sccb) +{ + ReadStorageElementInfo *storage_info = (ReadStorageElementInfo *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); + + assert(mhd); + + if ((mhd->standby_mem_size >> mhd->increment_size) >= 0x10000) { + sccb->h.response_code = cpu_to_be16(SCLP_RC_SCCB_BOUNDARY_VIOLATION); + return; + } + + /* Return information regarding standby memory */ + storage_info->max_id = cpu_to_be16(mhd->standby_mem_size ? 1 : 0); + storage_info->assigned = cpu_to_be16(mhd->standby_mem_size >> + mhd->increment_size); + storage_info->standby = cpu_to_be16(mhd->standby_mem_size >> + mhd->increment_size); + sccb->h.response_code = cpu_to_be16(SCLP_RC_STANDBY_READ_COMPLETION); +} + +static void attach_storage_element(SCCB *sccb, uint16_t element) +{ + int i, assigned, subincrement_id; + AttachStorageElement *attach_info = (AttachStorageElement *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); + + assert(mhd); + + if (element != 1) { + sccb->h.response_code = cpu_to_be16(SCLP_RC_INVALID_SCLP_COMMAND); + return; + } + + assigned = mhd->standby_mem_size >> mhd->increment_size; + attach_info->assigned = cpu_to_be16(assigned); + subincrement_id = ((ram_size >> mhd->increment_size) << 16) + + SCLP_STARTING_SUBINCREMENT_ID; + for (i = 0; i < assigned; i++) { + attach_info->entries[i] = cpu_to_be32(subincrement_id); + subincrement_id += SCLP_INCREMENT_UNIT; + } + sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION); +} + +static void assign_storage(SCCB *sccb) +{ + MemoryRegion *mr = NULL; + uint64_t this_subregion_size; + AssignStorage *assign_info = (AssignStorage *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); + assert(mhd); + ram_addr_t assign_addr = (assign_info->rn - 1) * mhd->rzm; + MemoryRegion *sysmem = get_system_memory(); + + if ((assign_addr % MEM_SECTION_SIZE == 0) && + (assign_addr >= mhd->padded_ram_size)) { + /* Re-use existing memory region if found */ + mr = memory_region_find(sysmem, assign_addr, 1).mr; + if (!mr) { + + MemoryRegion *standby_ram = g_new(MemoryRegion, 1); + + /* offset to align to standby_subregion_size for allocation */ + ram_addr_t offset = assign_addr - + (assign_addr - mhd->padded_ram_size) + % mhd->standby_subregion_size; + + /* strlen("standby.ram") + 4 (Max of KVM_MEMORY_SLOTS) + NULL */ + char id[16]; + snprintf(id, 16, "standby.ram%d", + (int)((offset - mhd->padded_ram_size) / + mhd->standby_subregion_size) + 1); + + /* Allocate a subregion of the calculated standby_subregion_size */ + if (offset + mhd->standby_subregion_size > + mhd->padded_ram_size + mhd->standby_mem_size) { + this_subregion_size = mhd->padded_ram_size + + mhd->standby_mem_size - offset; + } else { + this_subregion_size = mhd->standby_subregion_size; + } + + memory_region_init_ram(standby_ram, NULL, id, this_subregion_size, &error_abort); + vmstate_register_ram_global(standby_ram); + memory_region_add_subregion(sysmem, offset, standby_ram); + } + /* The specified subregion is no longer in standby */ + mhd->standby_state_map[(assign_addr - mhd->padded_ram_size) + / MEM_SECTION_SIZE] = 1; + } + sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION); +} + +static void unassign_storage(SCCB *sccb) +{ + MemoryRegion *mr = NULL; + AssignStorage *assign_info = (AssignStorage *) sccb; + sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev(); + assert(mhd); + ram_addr_t unassign_addr = (assign_info->rn - 1) * mhd->rzm; + MemoryRegion *sysmem = get_system_memory(); + + /* if the addr is a multiple of 256 MB */ + if ((unassign_addr % MEM_SECTION_SIZE == 0) && + (unassign_addr >= mhd->padded_ram_size)) { + mhd->standby_state_map[(unassign_addr - + mhd->padded_ram_size) / MEM_SECTION_SIZE] = 0; + + /* find the specified memory region and destroy it */ + mr = memory_region_find(sysmem, unassign_addr, 1).mr; + if (mr) { + int i; + int is_removable = 1; + ram_addr_t map_offset = (unassign_addr - mhd->padded_ram_size - + (unassign_addr - mhd->padded_ram_size) + % mhd->standby_subregion_size); + /* Mark all affected subregions as 'standby' once again */ + for (i = 0; + i < (mhd->standby_subregion_size / MEM_SECTION_SIZE); + i++) { + + if (mhd->standby_state_map[i + map_offset / MEM_SECTION_SIZE]) { + is_removable = 0; + break; + } + } + if (is_removable) { + memory_region_del_subregion(sysmem, mr); + object_unparent(OBJECT(mr)); + g_free(mr); + } + } + } + sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION); +} + /* Provide information about the CPU */ static void sclp_read_cpu_info(SCCB *sccb) { @@ -103,6 +334,22 @@ static void sclp_execute(SCCB *sccb, uint32_t code) case SCLP_CMDW_READ_CPU_INFO: sclp_read_cpu_info(sccb); break; + case SCLP_READ_STORAGE_ELEMENT_INFO: + if (code & 0xff00) { + read_storage_element1_info(sccb); + } else { + read_storage_element0_info(sccb); + } + break; + case SCLP_ATTACH_STORAGE_ELEMENT: + attach_storage_element(sccb, (code & 0xff00) >> 8); + break; + case SCLP_ASSIGN_STORAGE: + assign_storage(sccb); + break; + case SCLP_UNASSIGN_STORAGE: + unassign_storage(sccb); + break; default: efc->command_handler(ef, sccb, code); break; @@ -183,3 +430,33 @@ void s390_sclp_init(void) OBJECT(dev), NULL); qdev_init_nofail(dev); } + +sclpMemoryHotplugDev *init_sclp_memory_hotplug_dev(void) +{ + DeviceState *dev; + dev = qdev_create(NULL, TYPE_SCLP_MEMORY_HOTPLUG_DEV); + object_property_add_child(qdev_get_machine(), + TYPE_SCLP_MEMORY_HOTPLUG_DEV, + OBJECT(dev), NULL); + qdev_init_nofail(dev); + return SCLP_MEMORY_HOTPLUG_DEV(object_resolve_path( + TYPE_SCLP_MEMORY_HOTPLUG_DEV, NULL)); +} + +sclpMemoryHotplugDev *get_sclp_memory_hotplug_dev(void) +{ + return SCLP_MEMORY_HOTPLUG_DEV(object_resolve_path( + TYPE_SCLP_MEMORY_HOTPLUG_DEV, NULL)); +} + +static TypeInfo sclp_memory_hotplug_dev_info = { + .name = TYPE_SCLP_MEMORY_HOTPLUG_DEV, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(sclpMemoryHotplugDev), +}; + +static void register_types(void) +{ + type_register_static(&sclp_memory_hotplug_dev_info); +} +type_init(register_types); diff --git a/hw/s390x/sclpquiesce.c b/hw/s390x/sclpquiesce.c index a3c4bd6272..1a399bd1f0 100644 --- a/hw/s390x/sclpquiesce.c +++ b/hw/s390x/sclpquiesce.c @@ -69,8 +69,7 @@ static const VMStateDescription vmstate_sclpquiesce = { .name = "sclpquiesce", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BOOL(event_pending, SCLPEvent), VMSTATE_END_OF_LIST() } diff --git a/hw/s390x/virtio-ccw.c b/hw/s390x/virtio-ccw.c index 2bf0af8f0a..ea236c9b01 100644 --- a/hw/s390x/virtio-ccw.c +++ b/hw/s390x/virtio-ccw.c @@ -10,7 +10,7 @@ */ #include "hw/hw.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "sysemu/sysemu.h" #include "net/net.h" @@ -21,12 +21,77 @@ #include "hw/sysbus.h" #include "qemu/bitops.h" #include "hw/virtio/virtio-bus.h" +#include "hw/s390x/adapter.h" +#include "hw/s390x/s390_flic.h" #include "ioinst.h" #include "css.h" #include "virtio-ccw.h" #include "trace.h" +static QTAILQ_HEAD(, IndAddr) indicator_addresses = + QTAILQ_HEAD_INITIALIZER(indicator_addresses); + +static IndAddr *get_indicator(hwaddr ind_addr, int len) +{ + IndAddr *indicator; + + QTAILQ_FOREACH(indicator, &indicator_addresses, sibling) { + if (indicator->addr == ind_addr) { + indicator->refcnt++; + return indicator; + } + } + indicator = g_new0(IndAddr, 1); + indicator->addr = ind_addr; + indicator->len = len; + indicator->refcnt = 1; + QTAILQ_INSERT_TAIL(&indicator_addresses, indicator, sibling); + return indicator; +} + +static int s390_io_adapter_map(AdapterInfo *adapter, uint64_t map_addr, + bool do_map) +{ + S390FLICState *fs = s390_get_flic(); + S390FLICStateClass *fsc = S390_FLIC_COMMON_GET_CLASS(fs); + + return fsc->io_adapter_map(fs, adapter->adapter_id, map_addr, do_map); +} + +static void release_indicator(AdapterInfo *adapter, IndAddr *indicator) +{ + assert(indicator->refcnt > 0); + indicator->refcnt--; + if (indicator->refcnt > 0) { + return; + } + QTAILQ_REMOVE(&indicator_addresses, indicator, sibling); + if (indicator->map) { + s390_io_adapter_map(adapter, indicator->map, false); + } + g_free(indicator); +} + +static int map_indicator(AdapterInfo *adapter, IndAddr *indicator) +{ + int ret; + + if (indicator->map) { + return 0; /* already mapped is not an error */ + } + indicator->map = indicator->addr; + ret = s390_io_adapter_map(adapter, indicator->map, true); + if ((ret != 0) && (ret != -ENOSYS)) { + goto out_err; + } + return 0; + +out_err: + indicator->map = 0; + return ret; +} + static void virtio_ccw_bus_new(VirtioBusState *bus, size_t bus_size, VirtioCcwDevice *dev); @@ -165,7 +230,7 @@ VirtualCssBus *virtual_css_bus_init(void) cbus = VIRTUAL_CSS_BUS(bus); /* Enable hotplugging */ - bus->allow_hotplug = 1; + qbus_set_hotplug_handler(bus, dev, &error_abort); return cbus; } @@ -445,7 +510,7 @@ static int virtio_ccw_cb(SubchDev *sch, CCW1 ccw) ret = -EFAULT; } else { indicators = ldq_phys(&address_space_memory, ccw.cda); - dev->indicators = indicators; + dev->indicators = get_indicator(indicators, sizeof(uint64_t)); sch->curr_status.scsw.count = ccw.count - sizeof(indicators); ret = 0; } @@ -465,7 +530,7 @@ static int virtio_ccw_cb(SubchDev *sch, CCW1 ccw) ret = -EFAULT; } else { indicators = ldq_phys(&address_space_memory, ccw.cda); - dev->indicators2 = indicators; + dev->indicators2 = get_indicator(indicators, sizeof(uint64_t)); sch->curr_status.scsw.count = ccw.count - sizeof(indicators); ret = 0; } @@ -517,13 +582,20 @@ static int virtio_ccw_cb(SubchDev *sch, CCW1 ccw) ret = -EFAULT; } else { len = hw_len; - dev->summary_indicator = thinint->summary_indicator; - dev->indicators = thinint->device_indicator; + dev->summary_indicator = + get_indicator(thinint->summary_indicator, sizeof(uint8_t)); + dev->indicators = get_indicator(thinint->device_indicator, + thinint->ind_bit / 8 + 1); dev->thinint_isc = thinint->isc; - dev->ind_bit = thinint->ind_bit; + dev->routes.adapter.ind_offset = thinint->ind_bit; + dev->routes.adapter.summary_offset = 7; cpu_physical_memory_unmap(thinint, hw_len, 0, hw_len); - sch->thinint_active = ((dev->indicators != 0) && - (dev->summary_indicator != 0)); + ret = css_register_io_adapter(CSS_IO_ADAPTER_VIRTIO, + dev->thinint_isc, true, false, + &dev->routes.adapter.adapter_id); + assert(ret == 0); + sch->thinint_active = ((dev->indicators != NULL) && + (dev->summary_indicator != NULL)); sch->curr_status.scsw.count = ccw.count - len; ret = 0; } @@ -554,12 +626,11 @@ static int virtio_ccw_device_init(VirtioCcwDevice *dev, VirtIODevice *vdev) sch->driver_data = dev; dev->sch = sch; - dev->indicators = 0; + dev->indicators = NULL; /* Initialize subchannel structure. */ sch->channel_prog = 0x0; sch->last_cmd_valid = false; - sch->orb = NULL; sch->thinint_active = false; /* * Use a device number if provided. Otherwise, fall back to subchannel @@ -694,7 +765,10 @@ static int virtio_ccw_exit(VirtioCcwDevice *dev) css_subch_assign(sch->cssid, sch->ssid, sch->schid, sch->devno, NULL); g_free(sch); } - dev->indicators = 0; + if (dev->indicators) { + release_indicator(&dev->routes.adapter, dev->indicators); + dev->indicators = NULL; + } return 0; } @@ -718,15 +792,17 @@ static int virtio_ccw_net_init(VirtioCcwDevice *ccw_dev) static void virtio_ccw_net_instance_init(Object *obj) { VirtIONetCcw *dev = VIRTIO_NET_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_NET); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_NET); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static int virtio_ccw_blk_init(VirtioCcwDevice *ccw_dev) { VirtIOBlkCcw *dev = VIRTIO_BLK_CCW(ccw_dev); DeviceState *vdev = DEVICE(&dev->vdev); - virtio_blk_set_conf(vdev, &(dev->blk)); qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus)); if (qdev_init(vdev) < 0) { return -1; @@ -738,8 +814,13 @@ static int virtio_ccw_blk_init(VirtioCcwDevice *ccw_dev) static void virtio_ccw_blk_instance_init(Object *obj) { VirtIOBlkCcw *dev = VIRTIO_BLK_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_BLK); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_BLK); + object_property_add_alias(obj, "iothread", OBJECT(&dev->vdev),"iothread", + &error_abort); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static int virtio_ccw_serial_init(VirtioCcwDevice *ccw_dev) @@ -771,8 +852,9 @@ static int virtio_ccw_serial_init(VirtioCcwDevice *ccw_dev) static void virtio_ccw_serial_instance_init(Object *obj) { VirtioSerialCcw *dev = VIRTIO_SERIAL_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SERIAL); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SERIAL); } static int virtio_ccw_balloon_init(VirtioCcwDevice *ccw_dev) @@ -819,7 +901,7 @@ static void virtio_ccw_balloon_instance_init(Object *obj) VirtIOBalloonCcw *dev = VIRTIO_BALLOON_CCW(obj); object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_BALLOON); object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); - + object_unref(OBJECT(&dev->vdev)); object_property_add(obj, "guest-stats", "guest statistics", balloon_ccw_stats_get_all, NULL, NULL, dev, NULL); @@ -857,8 +939,11 @@ static int virtio_ccw_scsi_init(VirtioCcwDevice *ccw_dev) static void virtio_ccw_scsi_instance_init(Object *obj) { VirtIOSCSICcw *dev = VIRTIO_SCSI_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SCSI); + object_property_add_alias(obj, "iothread", OBJECT(&dev->vdev), "iothread", + &error_abort); } #ifdef CONFIG_VHOST_SCSI @@ -878,8 +963,9 @@ static int vhost_ccw_scsi_init(VirtioCcwDevice *ccw_dev) static void vhost_ccw_scsi_instance_init(Object *obj) { VHostSCSICcw *dev = VHOST_SCSI_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VHOST_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VHOST_SCSI); } #endif @@ -951,17 +1037,19 @@ static void virtio_ccw_notify(DeviceState *d, uint16_t vector) * ind_bit indicates the start of the indicators in a big * endian notation. */ - virtio_set_ind_atomic(sch, dev->indicators + - (dev->ind_bit + vector) / 8, - 0x80 >> ((dev->ind_bit + vector) % 8)); - if (!virtio_set_ind_atomic(sch, dev->summary_indicator, + uint64_t ind_bit = dev->routes.adapter.ind_offset; + + virtio_set_ind_atomic(sch, dev->indicators->addr + + (ind_bit + vector) / 8, + 0x80 >> ((ind_bit + vector) % 8)); + if (!virtio_set_ind_atomic(sch, dev->summary_indicator->addr, 0x01)) { css_adapter_interrupt(dev->thinint_isc); } } else { - indicators = ldq_phys(&address_space_memory, dev->indicators); + indicators = ldq_phys(&address_space_memory, dev->indicators->addr); indicators |= 1ULL << vector; - stq_phys(&address_space_memory, dev->indicators, indicators); + stq_phys(&address_space_memory, dev->indicators->addr, indicators); css_conditional_io_interrupt(sch); } } else { @@ -969,9 +1057,9 @@ static void virtio_ccw_notify(DeviceState *d, uint16_t vector) return; } vector = 0; - indicators = ldq_phys(&address_space_memory, dev->indicators2); + indicators = ldq_phys(&address_space_memory, dev->indicators2->addr); indicators |= 1ULL << vector; - stq_phys(&address_space_memory, dev->indicators2, indicators); + stq_phys(&address_space_memory, dev->indicators2->addr, indicators); css_conditional_io_interrupt(sch); } } @@ -992,9 +1080,18 @@ static void virtio_ccw_reset(DeviceState *d) virtio_ccw_stop_ioeventfd(dev); virtio_reset(vdev); css_reset_sch(dev->sch); - dev->indicators = 0; - dev->indicators2 = 0; - dev->summary_indicator = 0; + if (dev->indicators) { + release_indicator(&dev->routes.adapter, dev->indicators); + dev->indicators = NULL; + } + if (dev->indicators2) { + release_indicator(&dev->routes.adapter, dev->indicators2); + dev->indicators2 = NULL; + } + if (dev->summary_indicator) { + release_indicator(&dev->routes.adapter, dev->summary_indicator); + dev->summary_indicator = NULL; + } } static void virtio_ccw_vmstate_change(DeviceState *d, bool running) @@ -1028,6 +1125,79 @@ static int virtio_ccw_set_host_notifier(DeviceState *d, int n, bool assign) return virtio_ccw_set_guest2host_notifier(dev, n, assign, false); } +static int virtio_ccw_get_mappings(VirtioCcwDevice *dev) +{ + int r; + + if (!dev->sch->thinint_active) { + return -EINVAL; + } + + r = map_indicator(&dev->routes.adapter, dev->summary_indicator); + if (r) { + return r; + } + r = map_indicator(&dev->routes.adapter, dev->indicators); + if (r) { + return r; + } + dev->routes.adapter.summary_addr = dev->summary_indicator->map; + dev->routes.adapter.ind_addr = dev->indicators->map; + + return 0; +} + +static int virtio_ccw_setup_irqroutes(VirtioCcwDevice *dev, int nvqs) +{ + int i; + VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + int ret; + S390FLICState *fs = s390_get_flic(); + S390FLICStateClass *fsc = S390_FLIC_COMMON_GET_CLASS(fs); + + ret = virtio_ccw_get_mappings(dev); + if (ret) { + return ret; + } + for (i = 0; i < nvqs; i++) { + if (!virtio_queue_get_num(vdev, i)) { + break; + } + } + dev->routes.num_routes = i; + return fsc->add_adapter_routes(fs, &dev->routes); +} + +static void virtio_ccw_release_irqroutes(VirtioCcwDevice *dev, int nvqs) +{ + S390FLICState *fs = s390_get_flic(); + S390FLICStateClass *fsc = S390_FLIC_COMMON_GET_CLASS(fs); + + fsc->release_adapter_routes(fs, &dev->routes); +} + +static int virtio_ccw_add_irqfd(VirtioCcwDevice *dev, int n) +{ + VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + VirtQueue *vq = virtio_get_queue(vdev, n); + EventNotifier *notifier = virtio_queue_get_guest_notifier(vq); + + return kvm_irqchip_add_irqfd_notifier(kvm_state, notifier, NULL, + dev->routes.gsi[n]); +} + +static void virtio_ccw_remove_irqfd(VirtioCcwDevice *dev, int n) +{ + VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + VirtQueue *vq = virtio_get_queue(vdev, n); + EventNotifier *notifier = virtio_queue_get_guest_notifier(vq); + int ret; + + ret = kvm_irqchip_remove_irqfd_notifier(kvm_state, notifier, + dev->routes.gsi[n]); + assert(ret == 0); +} + static int virtio_ccw_set_guest_notifier(VirtioCcwDevice *dev, int n, bool assign, bool with_irqfd) { @@ -1043,11 +1213,17 @@ static int virtio_ccw_set_guest_notifier(VirtioCcwDevice *dev, int n, return r; } virtio_queue_set_guest_notifier_fd_handler(vq, true, with_irqfd); - /* We do not support irqfd for classic I/O interrupts, because the - * classic interrupts are intermixed with the subchannel status, that - * is queried with test subchannel. We want to use vhost, though. - * Lets make sure to have vhost running and wire up the irq fd to - * land in qemu (and only the irq fd) in this code. + if (with_irqfd) { + r = virtio_ccw_add_irqfd(dev, n); + if (r) { + virtio_queue_set_guest_notifier_fd_handler(vq, false, + with_irqfd); + return r; + } + } + /* + * We do not support individual masking for channel devices, so we + * need to manually trigger any guest masking callbacks here. */ if (k->guest_notifier_mask) { k->guest_notifier_mask(vdev, n, false); @@ -1061,6 +1237,9 @@ static int virtio_ccw_set_guest_notifier(VirtioCcwDevice *dev, int n, if (k->guest_notifier_mask) { k->guest_notifier_mask(vdev, n, true); } + if (with_irqfd) { + virtio_ccw_remove_irqfd(dev, n); + } virtio_queue_set_guest_notifier_fd_handler(vq, false, with_irqfd); event_notifier_cleanup(notifier); } @@ -1072,34 +1251,138 @@ static int virtio_ccw_set_guest_notifiers(DeviceState *d, int nvqs, { VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + bool with_irqfd = dev->sch->thinint_active && kvm_irqfds_enabled(); int r, n; + if (with_irqfd && assigned) { + /* irq routes need to be set up before assigning irqfds */ + r = virtio_ccw_setup_irqroutes(dev, nvqs); + if (r < 0) { + goto irqroute_error; + } + } for (n = 0; n < nvqs; n++) { if (!virtio_queue_get_num(vdev, n)) { break; } - /* false -> true, as soon as irqfd works */ - r = virtio_ccw_set_guest_notifier(dev, n, assigned, false); + r = virtio_ccw_set_guest_notifier(dev, n, assigned, with_irqfd); if (r < 0) { goto assign_error; } } + if (with_irqfd && !assigned) { + /* release irq routes after irqfds have been released */ + virtio_ccw_release_irqroutes(dev, nvqs); + } return 0; assign_error: while (--n >= 0) { virtio_ccw_set_guest_notifier(dev, n, !assigned, false); } +irqroute_error: + if (with_irqfd && assigned) { + virtio_ccw_release_irqroutes(dev, nvqs); + } return r; } +static void virtio_ccw_save_queue(DeviceState *d, int n, QEMUFile *f) +{ + VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); + VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + + qemu_put_be16(f, virtio_queue_vector(vdev, n)); +} + +static int virtio_ccw_load_queue(DeviceState *d, int n, QEMUFile *f) +{ + VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); + VirtIODevice *vdev = virtio_bus_get_device(&dev->bus); + uint16_t vector; + + qemu_get_be16s(f, &vector); + virtio_queue_set_vector(vdev, n , vector); + + return 0; +} + +static void virtio_ccw_save_config(DeviceState *d, QEMUFile *f) +{ + VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); + SubchDev *s = dev->sch; + + subch_device_save(s, f); + if (dev->indicators != NULL) { + qemu_put_be32(f, dev->indicators->len); + qemu_put_be64(f, dev->indicators->addr); + } else { + qemu_put_be32(f, 0); + qemu_put_be64(f, 0UL); + } + if (dev->indicators2 != NULL) { + qemu_put_be32(f, dev->indicators2->len); + qemu_put_be64(f, dev->indicators2->addr); + } else { + qemu_put_be32(f, 0); + qemu_put_be64(f, 0UL); + } + if (dev->summary_indicator != NULL) { + qemu_put_be32(f, dev->summary_indicator->len); + qemu_put_be64(f, dev->summary_indicator->addr); + } else { + qemu_put_be32(f, 0); + qemu_put_be64(f, 0UL); + } + qemu_put_be64(f, dev->routes.adapter.ind_offset); + qemu_put_byte(f, dev->thinint_isc); +} + +static int virtio_ccw_load_config(DeviceState *d, QEMUFile *f) +{ + VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d); + SubchDev *s = dev->sch; + int len; + + s->driver_data = dev; + subch_device_load(s, f); + len = qemu_get_be32(f); + if (len != 0) { + dev->indicators = get_indicator(qemu_get_be64(f), len); + } else { + qemu_get_be64(f); + dev->indicators = NULL; + } + len = qemu_get_be32(f); + if (len != 0) { + dev->indicators2 = get_indicator(qemu_get_be64(f), len); + } else { + qemu_get_be64(f); + dev->indicators2 = NULL; + } + len = qemu_get_be32(f); + if (len != 0) { + dev->summary_indicator = get_indicator(qemu_get_be64(f), len); + } else { + qemu_get_be64(f); + dev->summary_indicator = NULL; + } + dev->routes.adapter.ind_offset = qemu_get_be64(f); + dev->thinint_isc = qemu_get_byte(f); + if (s->thinint_active) { + return css_register_io_adapter(CSS_IO_ADAPTER_VIRTIO, + dev->thinint_isc, true, false, + &dev->routes.adapter.adapter_id); + } + + return 0; +} + /**************** Virtio-ccw Bus Device Descriptions *******************/ static Property virtio_ccw_net_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), DEFINE_VIRTIO_NET_FEATURES(VirtioCcwDevice, host_features[0]), - DEFINE_VIRTIO_NET_PROPERTIES(VirtIONetCcw, vdev.net_conf), - DEFINE_NIC_PROPERTIES(VirtIONetCcw, vdev.nic_conf), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_END_OF_LIST(), @@ -1126,13 +1409,8 @@ static const TypeInfo virtio_ccw_net = { static Property virtio_ccw_blk_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VIRTIO_BLK_FEATURES(VirtioCcwDevice, host_features[0]), - DEFINE_VIRTIO_BLK_PROPERTIES(VirtIOBlkCcw, blk), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE - DEFINE_PROP_BIT("x-data-plane", VirtIOBlkCcw, blk.data_plane, 0, false), -#endif DEFINE_PROP_END_OF_LIST(), }; @@ -1157,8 +1435,6 @@ static const TypeInfo virtio_ccw_blk = { static Property virtio_ccw_serial_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VIRTIO_SERIAL_PROPERTIES(VirtioSerialCcw, vdev.serial), - DEFINE_VIRTIO_COMMON_FEATURES(VirtioCcwDevice, host_features[0]), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_END_OF_LIST(), @@ -1185,7 +1461,6 @@ static const TypeInfo virtio_ccw_serial = { static Property virtio_ccw_balloon_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VIRTIO_COMMON_FEATURES(VirtioCcwDevice, host_features[0]), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_END_OF_LIST(), @@ -1212,7 +1487,6 @@ static const TypeInfo virtio_ccw_balloon = { static Property virtio_ccw_scsi_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOSCSICcw, vdev.parent_obj.conf), DEFINE_VIRTIO_SCSI_FEATURES(VirtioCcwDevice, host_features[0]), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), @@ -1241,8 +1515,6 @@ static const TypeInfo virtio_ccw_scsi = { #ifdef CONFIG_VHOST_SCSI static Property vhost_ccw_scsi_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VHOST_SCSI_PROPERTIES(VirtIOSCSICcw, vdev.parent_obj.conf), - DEFINE_VIRTIO_COMMON_FEATURES(VirtioCcwDevice, host_features[0]), DEFINE_PROP_END_OF_LIST(), }; @@ -1260,7 +1532,7 @@ static void vhost_ccw_scsi_class_init(ObjectClass *klass, void *data) static const TypeInfo vhost_ccw_scsi = { .name = TYPE_VHOST_SCSI_CCW, .parent = TYPE_VIRTIO_CCW_DEVICE, - .instance_size = sizeof(VirtIOSCSICcw), + .instance_size = sizeof(VHostSCSICcw), .instance_init = vhost_ccw_scsi_instance_init, .class_init = vhost_ccw_scsi_class_init, }; @@ -1269,18 +1541,15 @@ static const TypeInfo vhost_ccw_scsi = { static void virtio_ccw_rng_instance_init(Object *obj) { VirtIORNGCcw *dev = VIRTIO_RNG_CCW(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_RNG); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); - object_property_add_link(obj, "rng", TYPE_RNG_BACKEND, - (Object **)&dev->vdev.conf.rng, - qdev_prop_allow_set_link_before_realize, - OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_RNG); + object_property_add_alias(obj, "rng", OBJECT(&dev->vdev), + "rng", &error_abort); } static Property virtio_ccw_rng_properties[] = { DEFINE_PROP_STRING("devno", VirtioCcwDevice, bus_id), - DEFINE_VIRTIO_COMMON_FEATURES(VirtioCcwDevice, host_features[0]), - DEFINE_VIRTIO_RNG_PROPERTIES(VirtIORNGCcw, vdev.conf), DEFINE_PROP_BIT("ioeventfd", VirtioCcwDevice, flags, VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_END_OF_LIST(), @@ -1323,7 +1592,8 @@ static int virtio_ccw_busdev_exit(DeviceState *dev) return _info->exit(_dev); } -static int virtio_ccw_busdev_unplug(DeviceState *dev) +static void virtio_ccw_busdev_unplug(HotplugHandler *hotplug_dev, + DeviceState *dev, Error **errp) { VirtioCcwDevice *_dev = (VirtioCcwDevice *)dev; SubchDev *sch = _dev->sch; @@ -1342,18 +1612,21 @@ static int virtio_ccw_busdev_unplug(DeviceState *dev) css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid, 1, 0); object_unparent(OBJECT(dev)); - return 0; } +static Property virtio_ccw_properties[] = { + DEFINE_VIRTIO_COMMON_FEATURES(VirtioCcwDevice, host_features[0]), + DEFINE_PROP_END_OF_LIST(), +}; + static void virtio_ccw_device_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); + dc->props = virtio_ccw_properties; dc->init = virtio_ccw_busdev_init; dc->exit = virtio_ccw_busdev_exit; - dc->unplug = virtio_ccw_busdev_unplug; dc->bus_type = TYPE_VIRTUAL_CSS_BUS; - } static const TypeInfo virtio_ccw_device_info = { @@ -1377,8 +1650,10 @@ static int virtual_css_bridge_init(SysBusDevice *dev) static void virtual_css_bridge_class_init(ObjectClass *klass, void *data) { SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); k->init = virtual_css_bridge_init; + hc->unplug = virtio_ccw_busdev_unplug; } static const TypeInfo virtual_css_bridge_info = { @@ -1386,6 +1661,10 @@ static const TypeInfo virtual_css_bridge_info = { .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(SysBusDevice), .class_init = virtual_css_bridge_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; /* virtio-ccw-bus */ @@ -1394,13 +1673,10 @@ static void virtio_ccw_bus_new(VirtioBusState *bus, size_t bus_size, VirtioCcwDevice *dev) { DeviceState *qdev = DEVICE(dev); - BusState *qbus; char virtio_bus_name[] = "virtio-bus"; qbus_create_inplace(bus, bus_size, TYPE_VIRTIO_CCW_BUS, qdev, virtio_bus_name); - qbus = BUS(bus); - qbus->allow_hotplug = 1; } static void virtio_ccw_bus_class_init(ObjectClass *klass, void *data) @@ -1415,6 +1691,10 @@ static void virtio_ccw_bus_class_init(ObjectClass *klass, void *data) k->query_guest_notifiers = virtio_ccw_query_guest_notifiers; k->set_host_notifier = virtio_ccw_set_host_notifier; k->set_guest_notifiers = virtio_ccw_set_guest_notifiers; + k->save_queue = virtio_ccw_save_queue; + k->load_queue = virtio_ccw_load_queue; + k->save_config = virtio_ccw_save_config; + k->load_config = virtio_ccw_load_config; } static const TypeInfo virtio_ccw_bus_info = { diff --git a/hw/s390x/virtio-ccw.h b/hw/s390x/virtio-ccw.h index 4393e44814..5a1f16ee5d 100644 --- a/hw/s390x/virtio-ccw.h +++ b/hw/s390x/virtio-ccw.h @@ -22,6 +22,7 @@ #include <hw/virtio/virtio-balloon.h> #include <hw/virtio/virtio-rng.h> #include <hw/virtio/virtio-bus.h> +#include <hw/s390x/s390_flic.h> #define VIRTUAL_CSSID 0xfe @@ -75,6 +76,14 @@ typedef struct VirtIOCCWDeviceClass { #define VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT 1 #define VIRTIO_CCW_FLAG_USE_IOEVENTFD (1 << VIRTIO_CCW_FLAG_USE_IOEVENTFD_BIT) +typedef struct IndAddr { + hwaddr addr; + uint64_t map; + unsigned long refcnt; + int len; + QTAILQ_ENTRY(IndAddr) sibling; +} IndAddr; + struct VirtioCcwDevice { DeviceState parent_obj; SubchDev *sch; @@ -85,10 +94,11 @@ struct VirtioCcwDevice { bool ioeventfd_disabled; uint32_t flags; uint8_t thinint_isc; + AdapterRoutes routes; /* Guest provided values: */ - hwaddr indicators; - hwaddr indicators2; - hwaddr summary_indicator; + IndAddr *indicators; + IndAddr *indicators2; + IndAddr *summary_indicator; uint64_t ind_bit; }; @@ -134,7 +144,6 @@ typedef struct VHostSCSICcw { typedef struct VirtIOBlkCcw { VirtioCcwDevice parent_obj; VirtIOBlock vdev; - VirtIOBlkConf blk; } VirtIOBlkCcw; /* virtio-balloon-ccw */ diff --git a/hw/scsi/Makefile.objs b/hw/scsi/Makefile.objs index 121ddc5cf4..40c79d34c9 100644 --- a/hw/scsi/Makefile.objs +++ b/hw/scsi/Makefile.objs @@ -8,6 +8,6 @@ common-obj-$(CONFIG_ESP_PCI) += esp-pci.o obj-$(CONFIG_PSERIES) += spapr_vscsi.o ifeq ($(CONFIG_VIRTIO),y) -obj-y += virtio-scsi.o +obj-y += virtio-scsi.o virtio-scsi-dataplane.o obj-$(CONFIG_VHOST_SCSI) += vhost-scsi.o endif diff --git a/hw/scsi/esp-pci.c b/hw/scsi/esp-pci.c index 48c8b82350..00b7297354 100644 --- a/hw/scsi/esp-pci.c +++ b/hw/scsi/esp-pci.c @@ -268,6 +268,9 @@ static void esp_pci_dma_memory_rw(PCIESPState *pci, uint8_t *buf, int len, /* update status registers */ pci->dma_regs[DMA_WBC] -= len; pci->dma_regs[DMA_WAC] += len; + if (pci->dma_regs[DMA_WBC] == 0) { + pci->dma_regs[DMA_STAT] |= DMA_STAT_DONE; + } } static void esp_pci_dma_memory_read(void *opaque, uint8_t *buf, int len) @@ -310,7 +313,6 @@ static const VMStateDescription vmstate_esp_pci_scsi = { .name = "pciespscsi", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PCIESPState), VMSTATE_BUFFER_UNSAFE(dma_regs, PCIESPState, 0, 8 * sizeof(uint32_t)), @@ -379,7 +381,6 @@ static void esp_pci_scsi_uninit(PCIDevice *d) PCIESPState *pci = PCI_ESP(d); qemu_free_irq(pci->esp.irq); - memory_region_destroy(&pci->io); } static void esp_pci_class_init(ObjectClass *klass, void *data) diff --git a/hw/scsi/esp.c b/hw/scsi/esp.c index 2d150bfe48..272d13d633 100644 --- a/hw/scsi/esp.c +++ b/hw/scsi/esp.c @@ -364,7 +364,7 @@ void esp_hard_reset(ESPState *s) { memset(s->rregs, 0, ESP_REGS); memset(s->wregs, 0, ESP_REGS); - s->rregs[ESP_TCHI] = s->chip_id; + s->tchi_written = 0; s->ti_size = 0; s->ti_rptr = 0; s->ti_wptr = 0; @@ -422,6 +422,11 @@ uint64_t esp_reg_read(ESPState *s, uint32_t saddr) esp_lower_irq(s); return old_val; + case ESP_TCHI: + /* Return the unique id if the value has never been written */ + if (!s->tchi_written) { + return s->chip_id; + } default: break; } @@ -432,9 +437,11 @@ void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val) { trace_esp_mem_writeb(saddr, s->wregs[saddr], val); switch (saddr) { + case ESP_TCHI: + s->tchi_written = true; + /* fall through */ case ESP_TCLO: case ESP_TCMID: - case ESP_TCHI: s->rregs[ESP_RSTAT] &= ~STAT_TC; break; case ESP_FIFO: @@ -560,8 +567,7 @@ const VMStateDescription vmstate_esp = { .name ="esp", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_BUFFER(rregs, ESPState), VMSTATE_BUFFER(wregs, ESPState), VMSTATE_INT32(ti_size, ESPState), @@ -706,7 +712,6 @@ static const VMStateDescription vmstate_sysbus_esp_scsi = { .name = "sysbusespscsi", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .fields = (VMStateField[]) { VMSTATE_STRUCT(esp, SysBusESPState, 0, vmstate_esp, ESPState), VMSTATE_END_OF_LIST() diff --git a/hw/scsi/lsi53c895a.c b/hw/scsi/lsi53c895a.c index cb30414849..d9b4c7ea3c 100644 --- a/hw/scsi/lsi53c895a.c +++ b/hw/scsi/lsi53c895a.c @@ -19,6 +19,7 @@ #include "hw/pci/pci.h" #include "hw/scsi/scsi.h" #include "sysemu/dma.h" +#include "qemu/error-report.h" //#define DEBUG_LSI //#define DEBUG_LSI_REG @@ -1994,9 +1995,8 @@ static const VMStateDescription vmstate_lsi_scsi = { .name = "lsiscsi", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = lsi_pre_save, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, LSIState), VMSTATE_INT32(carry, LSIState), @@ -2073,15 +2073,6 @@ static const VMStateDescription vmstate_lsi_scsi = { } }; -static void lsi_scsi_uninit(PCIDevice *d) -{ - LSIState *s = LSI53C895A(d); - - memory_region_destroy(&s->mmio_io); - memory_region_destroy(&s->ram_io); - memory_region_destroy(&s->io_io); -} - static const struct SCSIBusInfo lsi_scsi_info = { .tcq = true, .max_target = LSI_MAX_DEVS, @@ -2135,7 +2126,6 @@ static void lsi_class_init(ObjectClass *klass, void *data) PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->init = lsi_scsi_init; - k->exit = lsi_scsi_uninit; k->vendor_id = PCI_VENDOR_ID_LSI_LOGIC; k->device_id = PCI_DEVICE_ID_LSI_53C895A; k->class_id = PCI_CLASS_STORAGE_SCSI; diff --git a/hw/scsi/megasas.c b/hw/scsi/megasas.c index e6e1ffd1bb..604252a198 100644 --- a/hw/scsi/megasas.c +++ b/hw/scsi/megasas.c @@ -21,6 +21,8 @@ #include "hw/hw.h" #include "hw/pci/pci.h" #include "sysemu/dma.h" +#include "sysemu/block-backend.h" +#include "hw/pci/msi.h" #include "hw/pci/msix.h" #include "qemu/iov.h" #include "hw/scsi/scsi.h" @@ -29,9 +31,11 @@ #include "mfi.h" -#define MEGASAS_VERSION "1.70" +#define MEGASAS_VERSION_GEN1 "1.70" +#define MEGASAS_VERSION_GEN2 "1.80" #define MEGASAS_MAX_FRAMES 2048 /* Firmware limit at 65535 */ #define MEGASAS_DEFAULT_FRAMES 1000 /* Windows requires this */ +#define MEGASAS_GEN2_DEFAULT_FRAMES 1008 /* Windows requires this */ #define MEGASAS_MAX_SGE 128 /* Firmware limit */ #define MEGASAS_DEFAULT_SGE 80 #define MEGASAS_MAX_SECTORS 0xFFFF /* No real limit */ @@ -43,9 +47,11 @@ #define MEGASAS_FLAG_USE_JBOD 0 #define MEGASAS_MASK_USE_JBOD (1 << MEGASAS_FLAG_USE_JBOD) -#define MEGASAS_FLAG_USE_MSIX 1 +#define MEGASAS_FLAG_USE_MSI 1 +#define MEGASAS_MASK_USE_MSI (1 << MEGASAS_FLAG_USE_MSI) +#define MEGASAS_FLAG_USE_MSIX 2 #define MEGASAS_MASK_USE_MSIX (1 << MEGASAS_FLAG_USE_MSIX) -#define MEGASAS_FLAG_USE_QUEUE64 2 +#define MEGASAS_FLAG_USE_QUEUE64 3 #define MEGASAS_MASK_USE_QUEUE64 (1 << MEGASAS_FLAG_USE_QUEUE64) static const char *mfi_frame_desc[] = { @@ -87,6 +93,8 @@ typedef struct MegasasState { int intr_mask; int doorbell; int busy; + int diag; + int adp_reset; MegasasCmd *event_cmd; int event_locale; @@ -107,14 +115,30 @@ typedef struct MegasasState { uint64_t producer_pa; MegasasCmd frames[MEGASAS_MAX_FRAMES]; - + DECLARE_BITMAP(frame_map, MEGASAS_MAX_FRAMES); SCSIBus bus; } MegasasState; -#define TYPE_MEGASAS "megasas" +typedef struct MegasasBaseClass { + PCIDeviceClass parent_class; + const char *product_name; + const char *product_version; + int mmio_bar; + int ioport_bar; + int osts; +} MegasasBaseClass; + +#define TYPE_MEGASAS_BASE "megasas-base" +#define TYPE_MEGASAS_GEN1 "megasas" +#define TYPE_MEGASAS_GEN2 "megasas-gen2" #define MEGASAS(obj) \ - OBJECT_CHECK(MegasasState, (obj), TYPE_MEGASAS) + OBJECT_CHECK(MegasasState, (obj), TYPE_MEGASAS_BASE) + +#define MEGASAS_DEVICE_CLASS(oc) \ + OBJECT_CLASS_CHECK(MegasasBaseClass, (oc), TYPE_MEGASAS_BASE) +#define MEGASAS_DEVICE_GET_CLASS(oc) \ + OBJECT_GET_CLASS(MegasasBaseClass, (oc), TYPE_MEGASAS_BASE) #define MEGASAS_INTR_DISABLED_MASK 0xFFFFFFFF @@ -132,6 +156,11 @@ static bool megasas_use_queue64(MegasasState *s) return s->flags & MEGASAS_MASK_USE_QUEUE64; } +static bool megasas_use_msi(MegasasState *s) +{ + return s->flags & MEGASAS_MASK_USE_MSI; +} + static bool megasas_use_msix(MegasasState *s) { return s->flags & MEGASAS_MASK_USE_MSIX; @@ -286,6 +315,7 @@ static void megasas_unmap_sgl(MegasasCmd *cmd) static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr, uint8_t sense_len) { + PCIDevice *pcid = PCI_DEVICE(cmd->state); uint32_t pa_hi = 0, pa_lo; hwaddr pa; @@ -298,7 +328,7 @@ static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr, pa_hi = le32_to_cpu(cmd->frame->pass.sense_addr_hi); } pa = ((uint64_t) pa_hi << 32) | pa_lo; - cpu_physical_memory_write(pa, sense_ptr, sense_len); + pci_dma_write(pcid, pa, sense_ptr, sense_len); cmd->frame->header.sense_len = sense_len; } return sense_len; @@ -433,71 +463,71 @@ static MegasasCmd *megasas_lookup_frame(MegasasState *s, return cmd; } -static MegasasCmd *megasas_next_frame(MegasasState *s, - hwaddr frame) +static void megasas_unmap_frame(MegasasState *s, MegasasCmd *cmd) { - MegasasCmd *cmd = NULL; - int num = 0, index; + PCIDevice *p = PCI_DEVICE(s); - cmd = megasas_lookup_frame(s, frame); - if (cmd) { - trace_megasas_qf_found(cmd->index, cmd->pa); - return cmd; - } - index = s->reply_queue_head; - num = 0; - while (num < s->fw_cmds) { - if (!s->frames[index].pa) { - cmd = &s->frames[index]; - break; - } - index = megasas_next_index(s, index, s->fw_cmds); - num++; - } - if (!cmd) { - trace_megasas_qf_failed(frame); - } - trace_megasas_qf_new(index, cmd); - return cmd; + pci_dma_unmap(p, cmd->frame, cmd->pa_size, 0, 0); + cmd->frame = NULL; + cmd->pa = 0; + clear_bit(cmd->index, s->frame_map); } +/* + * This absolutely needs to be locked if + * qemu ever goes multithreaded. + */ static MegasasCmd *megasas_enqueue_frame(MegasasState *s, hwaddr frame, uint64_t context, int count) { + PCIDevice *pcid = PCI_DEVICE(s); MegasasCmd *cmd = NULL; int frame_size = MFI_FRAME_SIZE * 16; hwaddr frame_size_p = frame_size; + unsigned long index; - cmd = megasas_next_frame(s, frame); - /* All frames busy */ - if (!cmd) { + index = 0; + while (index < s->fw_cmds) { + index = find_next_zero_bit(s->frame_map, s->fw_cmds, index); + if (!s->frames[index].pa) + break; + /* Busy frame found */ + trace_megasas_qf_mapped(index); + } + if (index >= s->fw_cmds) { + /* All frames busy */ + trace_megasas_qf_busy(frame); return NULL; } - if (!cmd->pa) { - cmd->pa = frame; - /* Map all possible frames */ - cmd->frame = cpu_physical_memory_map(frame, &frame_size_p, 0); - if (frame_size_p != frame_size) { - trace_megasas_qf_map_failed(cmd->index, (unsigned long)frame); - if (cmd->frame) { - cpu_physical_memory_unmap(cmd->frame, frame_size_p, 0, 0); - cmd->frame = NULL; - cmd->pa = 0; - } - s->event_count++; - return NULL; - } - cmd->pa_size = frame_size_p; - cmd->context = context; - if (!megasas_use_queue64(s)) { - cmd->context &= (uint64_t)0xFFFFFFFF; + cmd = &s->frames[index]; + set_bit(index, s->frame_map); + trace_megasas_qf_new(index, frame); + + cmd->pa = frame; + /* Map all possible frames */ + cmd->frame = pci_dma_map(pcid, frame, &frame_size_p, 0); + if (frame_size_p != frame_size) { + trace_megasas_qf_map_failed(cmd->index, (unsigned long)frame); + if (cmd->frame) { + megasas_unmap_frame(s, cmd); } + s->event_count++; + return NULL; + } + cmd->pa_size = frame_size_p; + cmd->context = context; + if (!megasas_use_queue64(s)) { + cmd->context &= (uint64_t)0xFFFFFFFF; } cmd->count = count; s->busy++; + if (s->consumer_pa) { + s->reply_queue_tail = ldl_le_phys(&address_space_memory, + s->consumer_pa); + } trace_megasas_qf_enqueue(cmd->index, cmd->count, cmd->context, - s->reply_queue_head, s->busy); + s->reply_queue_head, s->reply_queue_tail, s->busy); return cmd; } @@ -509,36 +539,47 @@ static void megasas_complete_frame(MegasasState *s, uint64_t context) /* Decrement busy count */ s->busy--; - if (s->reply_queue_pa) { /* * Put command on the reply queue. * Context is opaque, but emulation is running in * little endian. So convert it. */ - tail = s->reply_queue_head; if (megasas_use_queue64(s)) { - queue_offset = tail * sizeof(uint64_t); + queue_offset = s->reply_queue_head * sizeof(uint64_t); stq_le_phys(&address_space_memory, s->reply_queue_pa + queue_offset, context); } else { - queue_offset = tail * sizeof(uint32_t); + queue_offset = s->reply_queue_head * sizeof(uint32_t); stl_le_phys(&address_space_memory, s->reply_queue_pa + queue_offset, context); } - s->reply_queue_head = megasas_next_index(s, tail, s->fw_cmds); - trace_megasas_qf_complete(context, tail, queue_offset, - s->busy, s->doorbell); + s->reply_queue_tail = ldl_le_phys(&address_space_memory, + s->consumer_pa); + trace_megasas_qf_complete(context, s->reply_queue_head, + s->reply_queue_tail, s->busy); } if (megasas_intr_enabled(s)) { + /* Update reply queue pointer */ + s->reply_queue_tail = ldl_le_phys(&address_space_memory, + s->consumer_pa); + tail = s->reply_queue_head; + s->reply_queue_head = megasas_next_index(s, tail, s->fw_cmds); + trace_megasas_qf_update(s->reply_queue_head, s->reply_queue_tail, + s->busy); + stl_le_phys(&address_space_memory, + s->producer_pa, s->reply_queue_head); /* Notify HBA */ - s->doorbell++; - if (s->doorbell == 1) { - if (msix_enabled(pci_dev)) { - trace_megasas_msix_raise(0); - msix_notify(pci_dev, 0); - } else { + if (msix_enabled(pci_dev)) { + trace_megasas_msix_raise(0); + msix_notify(pci_dev, 0); + } else if (msi_enabled(pci_dev)) { + trace_megasas_msi_raise(0); + msi_notify(pci_dev, 0); + } else { + s->doorbell++; + if (s->doorbell == 1) { trace_megasas_irq_raise(); pci_irq_assert(pci_dev); } @@ -556,11 +597,10 @@ static void megasas_reset_frames(MegasasState *s) for (i = 0; i < s->fw_cmds; i++) { cmd = &s->frames[i]; if (cmd->pa) { - cpu_physical_memory_unmap(cmd->frame, cmd->pa_size, 0, 0); - cmd->frame = NULL; - cmd->pa = 0; + megasas_unmap_frame(s, cmd); } } + bitmap_zero(s->frame_map, MEGASAS_MAX_FRAMES); } static void megasas_abort_command(MegasasCmd *cmd) @@ -573,18 +613,22 @@ static void megasas_abort_command(MegasasCmd *cmd) static int megasas_init_firmware(MegasasState *s, MegasasCmd *cmd) { + PCIDevice *pcid = PCI_DEVICE(s); uint32_t pa_hi, pa_lo; - hwaddr iq_pa, initq_size; - struct mfi_init_qinfo *initq; + hwaddr iq_pa, initq_size = sizeof(struct mfi_init_qinfo); + struct mfi_init_qinfo *initq = NULL; uint32_t flags; int ret = MFI_STAT_OK; + if (s->reply_queue_pa) { + trace_megasas_initq_mapped(s->reply_queue_pa); + goto out; + } pa_lo = le32_to_cpu(cmd->frame->init.qinfo_new_addr_lo); pa_hi = le32_to_cpu(cmd->frame->init.qinfo_new_addr_hi); iq_pa = (((uint64_t) pa_hi << 32) | pa_lo); trace_megasas_init_firmware((uint64_t)iq_pa); - initq_size = sizeof(*initq); - initq = cpu_physical_memory_map(iq_pa, &initq_size, 0); + initq = pci_dma_map(pcid, iq_pa, &initq_size, 0); if (!initq || initq_size != sizeof(*initq)) { trace_megasas_initq_map_failed(cmd->index); s->event_count++; @@ -620,7 +664,7 @@ static int megasas_init_firmware(MegasasState *s, MegasasCmd *cmd) s->fw_state = MFI_FWSTATE_OPERATIONAL; out: if (initq) { - cpu_physical_memory_unmap(initq, initq_size, 0, 0); + pci_dma_unmap(pcid, initq, initq_size, 0, 0); } return ret; } @@ -670,11 +714,12 @@ static void megasas_finish_dcmd(MegasasCmd *cmd, uint32_t iov_size) static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); + PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); + MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; - int num_ld_disks = 0; - uint16_t sdev_id; + int num_pd_disks = 0; memset(&info, 0x0, cmd->iov_size); if (cmd->iov_size < dcmd_size) { @@ -683,10 +728,10 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) return MFI_STAT_INVALID_PARAMETER; } - info.pci.vendor = cpu_to_le16(PCI_VENDOR_ID_LSI_LOGIC); - info.pci.device = cpu_to_le16(PCI_DEVICE_ID_LSI_SAS1078); - info.pci.subvendor = cpu_to_le16(PCI_VENDOR_ID_LSI_LOGIC); - info.pci.subdevice = cpu_to_le16(0x1013); + info.pci.vendor = cpu_to_le16(pci_class->vendor_id); + info.pci.device = cpu_to_le16(pci_class->device_id); + info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); + info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports @@ -703,22 +748,24 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); + uint16_t pd_id; - if (num_ld_disks < 8) { - sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF); - info.device.port_addr[num_ld_disks] = - cpu_to_le64(megasas_get_sata_addr(sdev_id)); + if (num_pd_disks < 8) { + pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); + info.device.port_addr[num_pd_disks] = + cpu_to_le64(megasas_get_sata_addr(pd_id)); } - num_ld_disks++; + num_pd_disks++; } - memcpy(info.product_name, "MegaRAID SAS 8708EM2", 20); + memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", QEMU_VERSION); memcpy(info.image_component[0].name, "APP", 3); - memcpy(info.image_component[0].version, MEGASAS_VERSION "-QEMU", 9); - memcpy(info.image_component[0].build_date, __DATE__, 11); - memcpy(info.image_component[0].build_time, __TIME__, 8); + snprintf(info.image_component[0].version, 10, "%s-QEMU", + base_class->product_version); + memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); + memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; @@ -735,13 +782,14 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; - info.max_lds = s->fw_luns; + info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); - info.lds_present = cpu_to_le16(num_ld_disks); - info.pd_present = cpu_to_le16(num_ld_disks); - info.pd_disks_present = cpu_to_le16(num_ld_disks); + if (!megasas_is_jbod(s)) + info.lds_present = cpu_to_le16(num_pd_disks); + info.pd_present = cpu_to_le16(num_pd_disks); + info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); @@ -900,7 +948,6 @@ static int megasas_dcmd_pd_get_list(MegasasState *s, MegasasCmd *cmd) size_t dcmd_size = sizeof(info); BusChild *kid; uint32_t offset, dcmd_limit, num_pd_disks = 0, max_pd_disks; - uint16_t sdev_id; memset(&info, 0, dcmd_size); offset = 8; @@ -912,22 +959,25 @@ static int megasas_dcmd_pd_get_list(MegasasState *s, MegasasCmd *cmd) } max_pd_disks = (cmd->iov_size - offset) / sizeof(struct mfi_pd_address); - if (max_pd_disks > s->fw_luns) { - max_pd_disks = s->fw_luns; + if (max_pd_disks > MFI_MAX_SYS_PDS) { + max_pd_disks = MFI_MAX_SYS_PDS; } - QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); + uint16_t pd_id; + + if (num_pd_disks >= max_pd_disks) + break; - sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF); - info.addr[num_pd_disks].device_id = cpu_to_le16(sdev_id); + pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); + info.addr[num_pd_disks].device_id = cpu_to_le16(pd_id); info.addr[num_pd_disks].encl_device_id = 0xFFFF; info.addr[num_pd_disks].encl_index = 0; - info.addr[num_pd_disks].slot_number = (sdev->id & 0xFF); + info.addr[num_pd_disks].slot_number = sdev->id & 0xFF; info.addr[num_pd_disks].scsi_dev_type = sdev->type; info.addr[num_pd_disks].connect_port_bitmap = 0x1; info.addr[num_pd_disks].sas_addr[0] = - cpu_to_le64(megasas_get_sata_addr(sdev_id)); + cpu_to_le64(megasas_get_sata_addr(pd_id)); num_pd_disks++; offset += sizeof(struct mfi_pd_address); } @@ -961,9 +1011,8 @@ static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun, { struct mfi_pd_info *info = cmd->iov_buf; size_t dcmd_size = sizeof(struct mfi_pd_info); - BlockConf *conf = &sdev->conf; uint64_t pd_size; - uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (lun & 0xFF); + uint16_t pd_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF); uint8_t cmdbuf[6]; SCSIRequest *req; size_t len, resid; @@ -1019,10 +1068,10 @@ static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun, info->fw_state = cpu_to_le16(MFI_PD_STATE_OFFLINE); } - info->ref.v.device_id = cpu_to_le16(sdev_id); + info->ref.v.device_id = cpu_to_le16(pd_id); info->state.ddf.pd_type = cpu_to_le16(MFI_PD_DDF_TYPE_IN_VD| MFI_PD_DDF_TYPE_INTF_SAS); - bdrv_get_geometry(conf->bs, &pd_size); + blk_get_geometry(sdev->conf.blk, &pd_size); info->raw_size = cpu_to_le64(pd_size); info->non_coerced_size = cpu_to_le64(pd_size); info->coerced_size = cpu_to_le64(pd_size); @@ -1030,7 +1079,7 @@ static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun, info->slot_number = (sdev->id & 0xFF); info->path_info.count = 1; info->path_info.sas_addr[0] = - cpu_to_le64(megasas_get_sata_addr(sdev_id)); + cpu_to_le64(megasas_get_sata_addr(pd_id)); info->connected_port_bitmap = 0x1; info->device_speed = 1; info->link_speed = 1; @@ -1045,6 +1094,7 @@ static int megasas_dcmd_pd_get_info(MegasasState *s, MegasasCmd *cmd) { size_t dcmd_size = sizeof(struct mfi_pd_info); uint16_t pd_id; + uint8_t target_id, lun_id; SCSIDevice *sdev = NULL; int retval = MFI_STAT_DEVICE_NOT_FOUND; @@ -1054,7 +1104,9 @@ static int megasas_dcmd_pd_get_info(MegasasState *s, MegasasCmd *cmd) /* mbox0 has the ID */ pd_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]); - sdev = scsi_device_find(&s->bus, 0, pd_id, 0); + target_id = (pd_id >> 8) & 0xFF; + lun_id = pd_id & 0xFF; + sdev = scsi_device_find(&s->bus, 0, target_id, lun_id); trace_megasas_dcmd_pd_get_info(cmd->index, pd_id); if (sdev) { @@ -1069,31 +1121,33 @@ static int megasas_dcmd_ld_get_list(MegasasState *s, MegasasCmd *cmd) { struct mfi_ld_list info; size_t dcmd_size = sizeof(info), resid; - uint32_t num_ld_disks = 0, max_ld_disks = s->fw_luns; + uint32_t num_ld_disks = 0, max_ld_disks; uint64_t ld_size; BusChild *kid; memset(&info, 0, dcmd_size); - if (cmd->iov_size < dcmd_size) { + if (cmd->iov_size > dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } + max_ld_disks = (cmd->iov_size - 8) / 16; if (megasas_is_jbod(s)) { max_ld_disks = 0; } + if (max_ld_disks > MFI_MAX_LD) { + max_ld_disks = MFI_MAX_LD; + } QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); - BlockConf *conf = &sdev->conf; if (num_ld_disks >= max_ld_disks) { break; } /* Logical device size is in blocks */ - bdrv_get_geometry(conf->bs, &ld_size); + blk_get_geometry(sdev->conf.blk, &ld_size); info.ld_list[num_ld_disks].ld.v.target_id = sdev->id; - info.ld_list[num_ld_disks].ld.v.lun_id = sdev->lun; info.ld_list[num_ld_disks].state = MFI_LD_STATE_OPTIMAL; info.ld_list[num_ld_disks].size = cpu_to_le64(ld_size); num_ld_disks++; @@ -1106,6 +1160,55 @@ static int megasas_dcmd_ld_get_list(MegasasState *s, MegasasCmd *cmd) return MFI_STAT_OK; } +static int megasas_dcmd_ld_list_query(MegasasState *s, MegasasCmd *cmd) +{ + uint16_t flags; + struct mfi_ld_targetid_list info; + size_t dcmd_size = sizeof(info), resid; + uint32_t num_ld_disks = 0, max_ld_disks = s->fw_luns; + BusChild *kid; + + /* mbox0 contains flags */ + flags = le16_to_cpu(cmd->frame->dcmd.mbox[0]); + trace_megasas_dcmd_ld_list_query(cmd->index, flags); + if (flags != MR_LD_QUERY_TYPE_ALL && + flags != MR_LD_QUERY_TYPE_EXPOSED_TO_HOST) { + max_ld_disks = 0; + } + + memset(&info, 0, dcmd_size); + if (cmd->iov_size < 12) { + trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, + dcmd_size); + return MFI_STAT_INVALID_PARAMETER; + } + dcmd_size = sizeof(uint32_t) * 2 + 3; + max_ld_disks = cmd->iov_size - dcmd_size; + if (megasas_is_jbod(s)) { + max_ld_disks = 0; + } + if (max_ld_disks > MFI_MAX_LD) { + max_ld_disks = MFI_MAX_LD; + } + QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { + SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); + + if (num_ld_disks >= max_ld_disks) { + break; + } + info.targetid[num_ld_disks] = sdev->lun; + num_ld_disks++; + dcmd_size++; + } + info.ld_count = cpu_to_le32(num_ld_disks); + info.size = dcmd_size; + trace_megasas_dcmd_ld_get_list(cmd->index, num_ld_disks, max_ld_disks); + + resid = dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); + cmd->iov_size = dcmd_size - resid; + return MFI_STAT_OK; +} + static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun, MegasasCmd *cmd) { @@ -1114,8 +1217,7 @@ static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun, uint8_t cdb[6]; SCSIRequest *req; ssize_t len, resid; - BlockConf *conf = &sdev->conf; - uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (lun & 0xFF); + uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF); uint64_t ld_size; if (!cmd->iov_buf) { @@ -1147,7 +1249,7 @@ static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun, info->ld_config.params.num_drives = 1; info->ld_config.params.is_consistent = 1; /* Logical device size is in blocks */ - bdrv_get_geometry(conf->bs, &ld_size); + blk_get_geometry(sdev->conf.blk, &ld_size); info->size = cpu_to_le64(ld_size); memset(info->ld_config.span, 0, sizeof(info->ld_config.span)); info->ld_config.span[0].start_block = 0; @@ -1231,15 +1333,14 @@ static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd) QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); - BlockConf *conf = &sdev->conf; - uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF); + uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); struct mfi_array *array; struct mfi_ld_config *ld; uint64_t pd_size; int i; array = (struct mfi_array *)(data + array_offset); - bdrv_get_geometry(conf->bs, &pd_size); + blk_get_geometry(sdev->conf.blk, &pd_size); array->size = cpu_to_le64(pd_size); array->num_drives = 1; array->array_ref = cpu_to_le16(sdev_id); @@ -1258,7 +1359,7 @@ static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd) array_offset += sizeof(struct mfi_array); ld = (struct mfi_ld_config *)(data + ld_offset); memset(ld, 0, sizeof(struct mfi_ld_config)); - ld->properties.ld.v.target_id = (sdev->id & 0xFF); + ld->properties.ld.v.target_id = sdev->id; ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD | MR_LD_CACHE_READ_ADAPTIVE; ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD | @@ -1310,7 +1411,7 @@ static int megasas_dcmd_get_properties(MegasasState *s, MegasasCmd *cmd) static int megasas_cache_flush(MegasasState *s, MegasasCmd *cmd) { - bdrv_drain_all(); + blk_drain_all(); return MFI_STAT_OK; } @@ -1320,9 +1421,23 @@ static int megasas_ctrl_shutdown(MegasasState *s, MegasasCmd *cmd) return MFI_STAT_OK; } +/* Some implementations use CLUSTER RESET LD to simulate a device reset */ static int megasas_cluster_reset_ld(MegasasState *s, MegasasCmd *cmd) { - return MFI_STAT_INVALID_DCMD; + uint16_t target_id; + int i; + + /* mbox0 contains the device index */ + target_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]); + trace_megasas_dcmd_reset_ld(cmd->index, target_id); + for (i = 0; i < s->fw_cmds; i++) { + MegasasCmd *tmp_cmd = &s->frames[i]; + if (tmp_cmd->req && tmp_cmd->req->dev->id == target_id) { + SCSIDevice *d = tmp_cmd->req->dev; + qdev_reset_all(&d->qdev); + } + } + return MFI_STAT_OK; } static int megasas_dcmd_set_properties(MegasasState *s, MegasasCmd *cmd) @@ -1409,6 +1524,8 @@ static const struct dcmd_cmd_tbl_t { megasas_dcmd_dummy }, { MFI_DCMD_LD_GET_LIST, "LD_GET_LIST", megasas_dcmd_ld_get_list}, + { MFI_DCMD_LD_LIST_QUERY, "LD_LIST_QUERY", + megasas_dcmd_ld_list_query }, { MFI_DCMD_LD_GET_INFO, "LD_GET_INFO", megasas_dcmd_ld_get_info }, { MFI_DCMD_LD_GET_PROP, "LD_GET_PROP", @@ -1537,16 +1654,23 @@ static int megasas_handle_scsi(MegasasState *s, MegasasCmd *cmd, bool is_logical) { uint8_t *cdb; - int len; bool is_write; struct SCSIDevice *sdev = NULL; cdb = cmd->frame->pass.cdb; - if (cmd->frame->header.target_id < s->fw_luns) { - sdev = scsi_device_find(&s->bus, 0, cmd->frame->header.target_id, - cmd->frame->header.lun_id); + if (is_logical) { + if (cmd->frame->header.target_id >= MFI_MAX_LD || + cmd->frame->header.lun_id != 0) { + trace_megasas_scsi_target_not_present( + mfi_frame_desc[cmd->frame->header.frame_cmd], is_logical, + cmd->frame->header.target_id, cmd->frame->header.lun_id); + return MFI_STAT_DEVICE_NOT_FOUND; + } } + sdev = scsi_device_find(&s->bus, 0, cmd->frame->header.target_id, + cmd->frame->header.lun_id); + cmd->iov_size = le32_to_cpu(cmd->frame->header.data_len); trace_megasas_handle_scsi(mfi_frame_desc[cmd->frame->header.frame_cmd], is_logical, cmd->frame->header.target_id, @@ -1590,16 +1714,16 @@ static int megasas_handle_scsi(MegasasState *s, MegasasCmd *cmd, } is_write = (cmd->req->cmd.mode == SCSI_XFER_TO_DEV); - len = megasas_enqueue_req(cmd, is_write); - if (len > 0) { + if (cmd->iov_size) { if (is_write) { - trace_megasas_scsi_write_start(cmd->index, len); + trace_megasas_scsi_write_start(cmd->index, cmd->iov_size); } else { - trace_megasas_scsi_read_start(cmd->index, len); + trace_megasas_scsi_read_start(cmd->index, cmd->iov_size); } } else { trace_megasas_scsi_nodata(cmd->index); } + megasas_enqueue_req(cmd, is_write); return MFI_STAT_INVALID_STATUS; } @@ -1617,7 +1741,8 @@ static int megasas_handle_io(MegasasState *s, MegasasCmd *cmd) lba_start_hi = le32_to_cpu(cmd->frame->io.lba_hi); lba_start = ((uint64_t)lba_start_hi << 32) | lba_start_lo; - if (cmd->frame->header.target_id < s->fw_luns) { + if (cmd->frame->header.target_id < MFI_MAX_LD && + cmd->frame->header.lun_id == 0) { sdev = scsi_device_find(&s->bus, 0, cmd->frame->header.target_id, cmd->frame->header.lun_id); } @@ -1768,6 +1893,7 @@ static void megasas_command_complete(SCSIRequest *req, uint32_t status, cmd->req = NULL; } cmd->frame->header.cmd_status = cmd_status; + megasas_unmap_frame(cmd->state, cmd); megasas_complete_frame(cmd->state, cmd->context); } @@ -1871,6 +1997,7 @@ static void megasas_handle_frame(MegasasState *s, uint64_t frame_addr, } else { megasas_frame_set_cmd_status(frame_addr, frame_status); } + megasas_unmap_frame(s, cmd); megasas_complete_frame(s, cmd->context); } } @@ -1879,38 +2006,55 @@ static uint64_t megasas_mmio_read(void *opaque, hwaddr addr, unsigned size) { MegasasState *s = opaque; + PCIDevice *pci_dev = PCI_DEVICE(s); + MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); uint32_t retval = 0; switch (addr) { case MFI_IDB: retval = 0; + trace_megasas_mmio_readl("MFI_IDB", retval); break; case MFI_OMSG0: case MFI_OSP0: - retval = (megasas_use_msix(s) ? MFI_FWSTATE_MSIX_SUPPORTED : 0) | + retval = (msix_present(pci_dev) ? MFI_FWSTATE_MSIX_SUPPORTED : 0) | (s->fw_state & MFI_FWSTATE_MASK) | ((s->fw_sge & 0xff) << 16) | (s->fw_cmds & 0xFFFF); + trace_megasas_mmio_readl(addr == MFI_OMSG0 ? "MFI_OMSG0" : "MFI_OSP0", + retval); break; case MFI_OSTS: if (megasas_intr_enabled(s) && s->doorbell) { - retval = MFI_1078_RM | 1; + retval = base_class->osts; } + trace_megasas_mmio_readl("MFI_OSTS", retval); break; case MFI_OMSK: retval = s->intr_mask; + trace_megasas_mmio_readl("MFI_OMSK", retval); break; case MFI_ODCR0: - retval = s->doorbell; + retval = s->doorbell ? 1 : 0; + trace_megasas_mmio_readl("MFI_ODCR0", retval); + break; + case MFI_DIAG: + retval = s->diag; + trace_megasas_mmio_readl("MFI_DIAG", retval); + break; + case MFI_OSP1: + retval = 15; + trace_megasas_mmio_readl("MFI_OSP1", retval); break; default: trace_megasas_mmio_invalid_readl(addr); break; } - trace_megasas_mmio_readl(addr, retval); return retval; } +static int adp_reset_seq[] = {0x00, 0x04, 0x0b, 0x02, 0x07, 0x0d}; + static void megasas_mmio_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { @@ -1920,9 +2064,9 @@ static void megasas_mmio_write(void *opaque, hwaddr addr, uint32_t frame_count; int i; - trace_megasas_mmio_writel(addr, val); switch (addr) { case MFI_IDB: + trace_megasas_mmio_writel("MFI_IDB", val); if (val & MFI_FWINIT_ABORT) { /* Abort all pending cmds */ for (i = 0; i < s->fw_cmds; i++) { @@ -1936,40 +2080,58 @@ static void megasas_mmio_write(void *opaque, hwaddr addr, if (val & MFI_FWINIT_MFIMODE) { /* discard MFIs */ } + if (val & MFI_FWINIT_STOP_ADP) { + /* Terminal error, stop processing */ + s->fw_state = MFI_FWSTATE_FAULT; + } break; case MFI_OMSK: + trace_megasas_mmio_writel("MFI_OMSK", val); s->intr_mask = val; - if (!megasas_intr_enabled(s) && !msix_enabled(pci_dev)) { + if (!megasas_intr_enabled(s) && + !msi_enabled(pci_dev) && + !msix_enabled(pci_dev)) { trace_megasas_irq_lower(); pci_irq_deassert(pci_dev); } if (megasas_intr_enabled(s)) { - trace_megasas_intr_enabled(); + if (msix_enabled(pci_dev)) { + trace_megasas_msix_enabled(0); + } else if (msi_enabled(pci_dev)) { + trace_megasas_msi_enabled(0); + } else { + trace_megasas_intr_enabled(); + } } else { trace_megasas_intr_disabled(); + megasas_soft_reset(s); } break; case MFI_ODCR0: + trace_megasas_mmio_writel("MFI_ODCR0", val); s->doorbell = 0; - if (s->producer_pa && megasas_intr_enabled(s)) { - /* Update reply queue pointer */ - trace_megasas_qf_update(s->reply_queue_head, s->busy); - stl_le_phys(&address_space_memory, - s->producer_pa, s->reply_queue_head); - if (!msix_enabled(pci_dev)) { + if (megasas_intr_enabled(s)) { + if (!msix_enabled(pci_dev) && !msi_enabled(pci_dev)) { trace_megasas_irq_lower(); pci_irq_deassert(pci_dev); } } break; case MFI_IQPH: + trace_megasas_mmio_writel("MFI_IQPH", val); /* Received high 32 bits of a 64 bit MFI frame address */ s->frame_hi = val; break; case MFI_IQPL: + trace_megasas_mmio_writel("MFI_IQPL", val); /* Received low 32 bits of a 64 bit MFI frame address */ + /* Fallthrough */ case MFI_IQP: - /* Received 32 bit MFI frame address */ + if (addr == MFI_IQP) { + trace_megasas_mmio_writel("MFI_IQP", val); + /* Received 64 bit MFI frame address */ + s->frame_hi = 0; + } frame_addr = (val & ~0x1F); /* Add possible 64 bit offset */ frame_addr |= ((uint64_t)s->frame_hi << 32); @@ -1977,6 +2139,30 @@ static void megasas_mmio_write(void *opaque, hwaddr addr, frame_count = (val >> 1) & 0xF; megasas_handle_frame(s, frame_addr, frame_count); break; + case MFI_SEQ: + trace_megasas_mmio_writel("MFI_SEQ", val); + /* Magic sequence to start ADP reset */ + if (adp_reset_seq[s->adp_reset] == val) { + s->adp_reset++; + } else { + s->adp_reset = 0; + s->diag = 0; + } + if (s->adp_reset == 6) { + s->diag = MFI_DIAG_WRITE_ENABLE; + } + break; + case MFI_DIAG: + trace_megasas_mmio_writel("MFI_DIAG", val); + /* ADP reset */ + if ((s->diag & MFI_DIAG_WRITE_ENABLE) && + (val & MFI_DIAG_RESET_ADP)) { + s->diag |= MFI_DIAG_RESET_ADP; + megasas_soft_reset(s); + s->adp_reset = 0; + s->diag = 0; + } + break; default: trace_megasas_mmio_invalid_writel(addr, val); break; @@ -2035,11 +2221,26 @@ static void megasas_soft_reset(MegasasState *s) int i; MegasasCmd *cmd; - trace_megasas_reset(); + trace_megasas_reset(s->fw_state); for (i = 0; i < s->fw_cmds; i++) { cmd = &s->frames[i]; megasas_abort_command(cmd); } + if (s->fw_state == MFI_FWSTATE_READY) { + BusChild *kid; + + /* + * The EFI firmware doesn't handle UA, + * so we need to clear the Power On/Reset UA + * after the initial reset. + */ + QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { + SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child); + + sdev->unit_attention = SENSE_CODE(NO_SENSE); + scsi_device_unit_attention_reported(sdev); + } + } megasas_reset_frames(s); s->reply_queue_len = s->fw_cmds; s->reply_queue_pa = 0; @@ -2061,13 +2262,32 @@ static void megasas_scsi_reset(DeviceState *dev) megasas_soft_reset(s); } -static const VMStateDescription vmstate_megasas = { +static const VMStateDescription vmstate_megasas_gen1 = { .name = "megasas", .version_id = 0, .minimum_version_id = 0, + .fields = (VMStateField[]) { + VMSTATE_PCI_DEVICE(parent_obj, MegasasState), + VMSTATE_MSIX(parent_obj, MegasasState), + + VMSTATE_INT32(fw_state, MegasasState), + VMSTATE_INT32(intr_mask, MegasasState), + VMSTATE_INT32(doorbell, MegasasState), + VMSTATE_UINT64(reply_queue_pa, MegasasState), + VMSTATE_UINT64(consumer_pa, MegasasState), + VMSTATE_UINT64(producer_pa, MegasasState), + VMSTATE_END_OF_LIST() + } +}; + +static const VMStateDescription vmstate_megasas_gen2 = { + .name = "megasas-gen2", + .version_id = 0, + .minimum_version_id = 0, .minimum_version_id_old = 0, .fields = (VMStateField[]) { - VMSTATE_PCI_DEVICE(parent_obj, MegasasState), + VMSTATE_PCIE_DEVICE(parent_obj, MegasasState), + VMSTATE_MSIX(parent_obj, MegasasState), VMSTATE_INT32(fw_state, MegasasState), VMSTATE_INT32(intr_mask, MegasasState), @@ -2083,12 +2303,12 @@ static void megasas_scsi_uninit(PCIDevice *d) { MegasasState *s = MEGASAS(d); -#ifdef USE_MSIX - msix_uninit(d, &s->mmio_io); -#endif - memory_region_destroy(&s->mmio_io); - memory_region_destroy(&s->port_io); - memory_region_destroy(&s->queue_io); + if (megasas_use_msix(s)) { + msix_uninit(d, &s->mmio_io, &s->mmio_io); + } + if (megasas_use_msi(s)) { + msi_uninit(d); + } } static const struct SCSIBusInfo megasas_scsi_info = { @@ -2106,6 +2326,7 @@ static int megasas_scsi_init(PCIDevice *dev) { DeviceState *d = DEVICE(dev); MegasasState *s = MEGASAS(dev); + MegasasBaseClass *b = MEGASAS_DEVICE_GET_CLASS(s); uint8_t *pci_conf; int i, bar_type; Error *err = NULL; @@ -2124,25 +2345,30 @@ static int megasas_scsi_init(PCIDevice *dev) memory_region_init_io(&s->queue_io, OBJECT(s), &megasas_queue_ops, s, "megasas-queue", 0x40000); -#ifdef USE_MSIX - /* MSI-X support is currently broken */ + if (megasas_use_msi(s) && + msi_init(dev, 0x50, 1, true, false)) { + s->flags &= ~MEGASAS_MASK_USE_MSI; + } if (megasas_use_msix(s) && - msix_init(dev, 15, &s->mmio_io, 0, 0x2000)) { + msix_init(dev, 15, &s->mmio_io, b->mmio_bar, 0x2000, + &s->mmio_io, b->mmio_bar, 0x3800, 0x68)) { s->flags &= ~MEGASAS_MASK_USE_MSIX; } -#else - s->flags &= ~MEGASAS_MASK_USE_MSIX; -#endif + if (pci_is_express(dev)) { + pcie_endpoint_cap_init(dev, 0xa0); + } bar_type = PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64; - pci_register_bar(dev, 0, bar_type, &s->mmio_io); - pci_register_bar(dev, 2, PCI_BASE_ADDRESS_SPACE_IO, &s->port_io); + pci_register_bar(dev, b->ioport_bar, + PCI_BASE_ADDRESS_SPACE_IO, &s->port_io); + pci_register_bar(dev, b->mmio_bar, bar_type, &s->mmio_io); pci_register_bar(dev, 3, bar_type, &s->queue_io); if (megasas_use_msix(s)) { msix_vector_use(dev, 0); } + s->fw_state = MFI_FWSTATE_READY; if (!s->sas_addr) { s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) | IEEE_COMPANY_LOCALLY_ASSIGNED) << 36; @@ -2151,7 +2377,7 @@ static int megasas_scsi_init(PCIDevice *dev) s->sas_addr |= PCI_FUNC(dev->devfn); } if (!s->hba_serial) { - s->hba_serial = g_strdup(MEGASAS_HBA_SERIAL); + s->hba_serial = g_strdup(MEGASAS_HBA_SERIAL); } if (s->fw_sge >= MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE) { s->fw_sge = MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE; @@ -2164,10 +2390,13 @@ static int megasas_scsi_init(PCIDevice *dev) s->fw_cmds = MEGASAS_MAX_FRAMES; } trace_megasas_init(s->fw_sge, s->fw_cmds, - megasas_use_msix(s) ? "MSI-X" : "INTx", megasas_is_jbod(s) ? "jbod" : "raid"); - s->fw_luns = (MFI_MAX_LD > MAX_SCSI_DEVS) ? - MAX_SCSI_DEVS : MFI_MAX_LD; + + if (megasas_is_jbod(s)) { + s->fw_luns = MFI_MAX_SYS_PDS; + } else { + s->fw_luns = MFI_MAX_LD; + } s->producer_pa = 0; s->consumer_pa = 0; for (i = 0; i < s->fw_cmds; i++) { @@ -2189,51 +2418,142 @@ static int megasas_scsi_init(PCIDevice *dev) return 0; } -static Property megasas_properties[] = { +static void +megasas_write_config(PCIDevice *pci, uint32_t addr, uint32_t val, int len) +{ + pci_default_write_config(pci, addr, val, len); + msi_write_config(pci, addr, val, len); +} + +static Property megasas_properties_gen1[] = { DEFINE_PROP_UINT32("max_sge", MegasasState, fw_sge, MEGASAS_DEFAULT_SGE), DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds, MEGASAS_DEFAULT_FRAMES), DEFINE_PROP_STRING("hba_serial", MegasasState, hba_serial), DEFINE_PROP_UINT64("sas_address", MegasasState, sas_addr, 0), -#ifdef USE_MSIX + DEFINE_PROP_BIT("use_msi", MegasasState, flags, + MEGASAS_FLAG_USE_MSI, false), DEFINE_PROP_BIT("use_msix", MegasasState, flags, MEGASAS_FLAG_USE_MSIX, false), -#endif DEFINE_PROP_BIT("use_jbod", MegasasState, flags, MEGASAS_FLAG_USE_JBOD, false), DEFINE_PROP_END_OF_LIST(), }; +static Property megasas_properties_gen2[] = { + DEFINE_PROP_UINT32("max_sge", MegasasState, fw_sge, + MEGASAS_DEFAULT_SGE), + DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds, + MEGASAS_GEN2_DEFAULT_FRAMES), + DEFINE_PROP_STRING("hba_serial", MegasasState, hba_serial), + DEFINE_PROP_UINT64("sas_address", MegasasState, sas_addr, 0), + DEFINE_PROP_BIT("use_msi", MegasasState, flags, + MEGASAS_FLAG_USE_MSI, true), + DEFINE_PROP_BIT("use_msix", MegasasState, flags, + MEGASAS_FLAG_USE_MSIX, true), + DEFINE_PROP_BIT("use_jbod", MegasasState, flags, + MEGASAS_FLAG_USE_JBOD, false), + DEFINE_PROP_END_OF_LIST(), +}; + +typedef struct MegasasInfo { + const char *name; + const char *desc; + const char *product_name; + const char *product_version; + uint16_t device_id; + uint16_t subsystem_id; + int ioport_bar; + int mmio_bar; + bool is_express; + int osts; + const VMStateDescription *vmsd; + Property *props; +} MegasasInfo; + +static struct MegasasInfo megasas_devices[] = { + { + .name = TYPE_MEGASAS_GEN1, + .desc = "LSI MegaRAID SAS 1078", + .product_name = "LSI MegaRAID SAS 8708EM2", + .product_version = MEGASAS_VERSION_GEN1, + .device_id = PCI_DEVICE_ID_LSI_SAS1078, + .subsystem_id = 0x1013, + .ioport_bar = 2, + .mmio_bar = 0, + .osts = MFI_1078_RM | 1, + .is_express = false, + .vmsd = &vmstate_megasas_gen1, + .props = megasas_properties_gen1, + },{ + .name = TYPE_MEGASAS_GEN2, + .desc = "LSI MegaRAID SAS 2108", + .product_name = "LSI MegaRAID SAS 9260-8i", + .product_version = MEGASAS_VERSION_GEN2, + .device_id = PCI_DEVICE_ID_LSI_SAS0079, + .subsystem_id = 0x9261, + .ioport_bar = 0, + .mmio_bar = 1, + .osts = MFI_GEN2_RM, + .is_express = true, + .vmsd = &vmstate_megasas_gen2, + .props = megasas_properties_gen2, + } +}; + static void megasas_class_init(ObjectClass *oc, void *data) { DeviceClass *dc = DEVICE_CLASS(oc); PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc); + MegasasBaseClass *e = MEGASAS_DEVICE_CLASS(oc); + const MegasasInfo *info = data; pc->init = megasas_scsi_init; pc->exit = megasas_scsi_uninit; pc->vendor_id = PCI_VENDOR_ID_LSI_LOGIC; - pc->device_id = PCI_DEVICE_ID_LSI_SAS1078; + pc->device_id = info->device_id; pc->subsystem_vendor_id = PCI_VENDOR_ID_LSI_LOGIC; - pc->subsystem_id = 0x1013; + pc->subsystem_id = info->subsystem_id; pc->class_id = PCI_CLASS_STORAGE_RAID; - dc->props = megasas_properties; + pc->is_express = info->is_express; + e->mmio_bar = info->mmio_bar; + e->ioport_bar = info->ioport_bar; + e->osts = info->osts; + e->product_name = info->product_name; + e->product_version = info->product_version; + dc->props = info->props; dc->reset = megasas_scsi_reset; - dc->vmsd = &vmstate_megasas; + dc->vmsd = info->vmsd; set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); - dc->desc = "LSI MegaRAID SAS 1078"; + dc->desc = info->desc; + pc->config_write = megasas_write_config; } static const TypeInfo megasas_info = { - .name = TYPE_MEGASAS, + .name = TYPE_MEGASAS_BASE, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(MegasasState), - .class_init = megasas_class_init, + .class_size = sizeof(MegasasBaseClass), + .abstract = true, }; static void megasas_register_types(void) { + int i; + type_register_static(&megasas_info); + for (i = 0; i < ARRAY_SIZE(megasas_devices); i++) { + const MegasasInfo *info = &megasas_devices[i]; + TypeInfo type_info = {}; + + type_info.name = info->name; + type_info.parent = TYPE_MEGASAS_BASE; + type_info.class_data = (void *)info; + type_info.class_init = megasas_class_init; + + type_register(&type_info); + } } type_init(megasas_register_types) diff --git a/hw/scsi/mfi.h b/hw/scsi/mfi.h index cd8355badf..29d41775d4 100644 --- a/hw/scsi/mfi.h +++ b/hw/scsi/mfi.h @@ -60,6 +60,7 @@ #define MFI_ODR0 0x9c /* outbound doorbell register0 */ #define MFI_ODCR0 0xa0 /* outbound doorbell clear register0 */ #define MFI_OSP0 0xb0 /* outbound scratch pad0 */ +#define MFI_OSP1 0xb4 /* outbound scratch pad1 */ #define MFI_IQPL 0xc0 /* Inbound queue port (low bytes) */ #define MFI_IQPH 0xc4 /* Inbound queue port (high bytes) */ #define MFI_DIAG 0xf8 /* Host diag */ @@ -116,6 +117,12 @@ #define MFI_FWINIT_STOP_ADP 0x00000020 /* Move to operational, stop */ #define MFI_FWINIT_ADP_RESET 0x00000040 /* Reset ADP */ +/* + * Control bits for the DIAG register + */ +#define MFI_DIAG_WRITE_ENABLE 0x00000080 +#define MFI_DIAG_RESET_ADP 0x00000004 + /* MFI Commands */ typedef enum { MFI_CMD_INIT = 0x00, @@ -164,6 +171,7 @@ typedef enum { MFI_DCMD_PD_BLINK = 0x02070100, MFI_DCMD_PD_UNBLINK = 0x02070200, MFI_DCMD_LD_GET_LIST = 0x03010000, + MFI_DCMD_LD_LIST_QUERY = 0x03010100, MFI_DCMD_LD_GET_INFO = 0x03020000, MFI_DCMD_LD_GET_PROP = 0x03030000, MFI_DCMD_LD_SET_PROP = 0x03040000, @@ -411,6 +419,14 @@ typedef enum { MR_PD_QUERY_TYPE_EXPOSED_TO_HOST = 5, /*query for system drives */ } mfi_pd_query_type; +typedef enum { + MR_LD_QUERY_TYPE_ALL = 0, + MR_LD_QUERY_TYPE_EXPOSED_TO_HOST = 1, + MR_LD_QUERY_TYPE_USED_TGT_IDS = 2, + MR_LD_QUERY_TYPE_CLUSTER_ACCESS = 3, + MR_LD_QUERY_TYPE_CLUSTER_LOCALE = 4, +} mfi_ld_query_type; + /* * Other propertities and definitions */ @@ -1085,7 +1101,7 @@ struct mfi_pd_list { union mfi_ld_ref { struct { uint8_t target_id; - uint8_t lun_id; + uint8_t reserved; uint16_t seq; } v; uint32_t ref; @@ -1102,6 +1118,13 @@ struct mfi_ld_list { } ld_list[MFI_MAX_LD]; } QEMU_PACKED; +struct mfi_ld_targetid_list { + uint32_t size; + uint32_t ld_count; + uint8_t pad[3]; + uint8_t targetid[MFI_MAX_LD]; +} QEMU_PACKED; + enum mfi_ld_access { MFI_LD_ACCESS_RW = 0, MFI_LD_ACCSSS_RO = 2, diff --git a/hw/scsi/scsi-bus.c b/hw/scsi/scsi-bus.c index ae921a6a75..24f7b74ae8 100644 --- a/hw/scsi/scsi-bus.c +++ b/hw/scsi/scsi-bus.c @@ -3,13 +3,13 @@ #include "hw/scsi/scsi.h" #include "block/scsi.h" #include "hw/qdev.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "trace.h" #include "sysemu/dma.h" static char *scsibus_get_dev_path(DeviceState *dev); static char *scsibus_get_fw_dev_path(DeviceState *dev); -static int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf); static void scsi_req_dequeue(SCSIRequest *req); static uint8_t *scsi_target_alloc_buf(SCSIRequest *req, size_t len); static void scsi_target_free_buf(SCSIRequest *req); @@ -24,9 +24,11 @@ static Property scsi_props[] = { static void scsi_bus_class_init(ObjectClass *klass, void *data) { BusClass *k = BUS_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); k->get_dev_path = scsibus_get_dev_path; k->get_fw_dev_path = scsibus_get_fw_dev_path; + hc->unplug = qdev_simple_device_unplug_cb; } static const TypeInfo scsi_bus_info = { @@ -34,24 +36,33 @@ static const TypeInfo scsi_bus_info = { .parent = TYPE_BUS, .instance_size = sizeof(SCSIBus), .class_init = scsi_bus_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static int next_scsi_bus; -static int scsi_device_init(SCSIDevice *s) +static void scsi_device_realize(SCSIDevice *s, Error **errp) { SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s); - if (sc->init) { - return sc->init(s); + if (sc->realize) { + sc->realize(s, errp); } - return 0; } -static void scsi_device_destroy(SCSIDevice *s) +int scsi_bus_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, uint8_t *buf, + void *hba_private) { - SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s); - if (sc->destroy) { - sc->destroy(s); + SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus); + int rc; + + assert(cmd->len == 0); + rc = scsi_req_parse_cdb(dev, cmd, buf); + if (bus->info->parse_cdb) { + rc = bus->info->parse_cdb(dev, cmd, buf, hba_private); } + return rc; } static SCSIRequest *scsi_device_alloc_req(SCSIDevice *s, uint32_t tag, uint32_t lun, @@ -65,7 +76,7 @@ static SCSIRequest *scsi_device_alloc_req(SCSIDevice *s, uint32_t tag, uint32_t return NULL; } -static void scsi_device_unit_attention_reported(SCSIDevice *s) +void scsi_device_unit_attention_reported(SCSIDevice *s) { SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s); if (sc->unit_attention_reported) { @@ -80,7 +91,7 @@ void scsi_bus_new(SCSIBus *bus, size_t bus_size, DeviceState *host, qbus_create_inplace(bus, bus_size, TYPE_SCSI_BUS, host, bus_name); bus->busnr = next_scsi_bus++; bus->info = info; - bus->qbus.allow_hotplug = 1; + qbus_set_bus_hotplug_handler(BUS(bus), &error_abort); } static void scsi_dma_restart_bh(void *opaque) @@ -130,24 +141,24 @@ static void scsi_dma_restart_cb(void *opaque, int running, RunState state) } } -static int scsi_qdev_init(DeviceState *qdev) +static void scsi_qdev_realize(DeviceState *qdev, Error **errp) { SCSIDevice *dev = SCSI_DEVICE(qdev); SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus); SCSIDevice *d; - int rc = -1; + Error *local_err = NULL; if (dev->channel > bus->info->max_channel) { - error_report("bad scsi channel id: %d", dev->channel); - goto err; + error_setg(errp, "bad scsi channel id: %d", dev->channel); + return; } if (dev->id != -1 && dev->id > bus->info->max_target) { - error_report("bad scsi device id: %d", dev->id); - goto err; + error_setg(errp, "bad scsi device id: %d", dev->id); + return; } if (dev->lun != -1 && dev->lun > bus->info->max_lun) { - error_report("bad scsi device lun: %d", dev->lun); - goto err; + error_setg(errp, "bad scsi device lun: %d", dev->lun); + return; } if (dev->id == -1) { @@ -159,8 +170,8 @@ static int scsi_qdev_init(DeviceState *qdev) d = scsi_device_find(bus, dev->channel, ++id, dev->lun); } while (d && d->lun == dev->lun && id < bus->info->max_target); if (d && d->lun == dev->lun) { - error_report("no free target"); - goto err; + error_setg(errp, "no free target"); + return; } dev->id = id; } else if (dev->lun == -1) { @@ -169,46 +180,43 @@ static int scsi_qdev_init(DeviceState *qdev) d = scsi_device_find(bus, dev->channel, dev->id, ++lun); } while (d && d->lun == lun && lun < bus->info->max_lun); if (d && d->lun == lun) { - error_report("no free lun"); - goto err; + error_setg(errp, "no free lun"); + return; } dev->lun = lun; } else { d = scsi_device_find(bus, dev->channel, dev->id, dev->lun); assert(d); if (d->lun == dev->lun && dev != d) { - object_unparent(OBJECT(d)); + error_setg(errp, "lun already used by '%s'", d->qdev.id); + return; } } QTAILQ_INIT(&dev->requests); - rc = scsi_device_init(dev); - if (rc == 0) { - dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb, - dev); - } - - if (bus->info->hotplug) { - bus->info->hotplug(bus, dev); + scsi_device_realize(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } - -err: - return rc; + dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb, + dev); } -static int scsi_qdev_exit(DeviceState *qdev) +static void scsi_qdev_unrealize(DeviceState *qdev, Error **errp) { SCSIDevice *dev = SCSI_DEVICE(qdev); if (dev->vmsentry) { qemu_del_vm_change_state_handler(dev->vmsentry); } - scsi_device_destroy(dev); - return 0; + + scsi_device_purge_requests(dev, SENSE_CODE(NO_SENSE)); + blockdev_mark_auto_del(dev->conf.blk); } /* handle legacy '-drive if=scsi,...' cmd line args */ -SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv, +SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockBackend *blk, int unit, bool removable, int bootindex, const char *serial, Error **errp) { @@ -216,11 +224,12 @@ SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv, DeviceState *dev; Error *err = NULL; - driver = bdrv_is_sg(bdrv) ? "scsi-generic" : "scsi-disk"; + driver = blk_is_sg(blk) ? "scsi-generic" : "scsi-disk"; dev = qdev_create(&bus->qbus, driver); qdev_prop_set_uint32(dev, "scsi-id", unit); if (bootindex >= 0) { - qdev_prop_set_int32(dev, "bootindex", bootindex); + object_property_set_int(OBJECT(dev), bootindex, "bootindex", + &error_abort); } if (object_property_find(OBJECT(dev), "removable", NULL)) { qdev_prop_set_bit(dev, "removable", removable); @@ -228,7 +237,7 @@ SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv, if (serial && object_property_find(OBJECT(dev), "serial", NULL)) { qdev_prop_set_string(dev, "serial", serial); } - if (qdev_prop_set_drive(dev, "drive", bdrv) < 0) { + if (qdev_prop_set_drive(dev, "drive", blk) < 0) { error_setg(errp, "Setting drive property failed"); object_unparent(OBJECT(dev)); return NULL; @@ -256,9 +265,10 @@ void scsi_bus_legacy_handle_cmdline(SCSIBus *bus, Error **errp) continue; } qemu_opts_loc_restore(dinfo->opts); - scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false, -1, NULL, - &err); + scsi_bus_legacy_add_drive(bus, blk_by_legacy_dinfo(dinfo), + unit, false, -1, NULL, &err); if (err != NULL) { + error_report("%s", error_get_pretty(err)); error_propagate(errp, err); break; } @@ -539,8 +549,11 @@ SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d, SCSIRequest *req; SCSIBus *bus = scsi_bus_from_device(d); BusState *qbus = BUS(bus); + const int memset_off = offsetof(SCSIRequest, sense) + + sizeof(req->sense); - req = g_malloc0(reqops->size); + req = g_slice_alloc(reqops->size); + memset((uint8_t *)req + memset_off, 0, reqops->size - memset_off); req->refcount = 1; req->bus = bus; req->dev = d; @@ -548,10 +561,10 @@ SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d, req->lun = lun; req->hba_private = hba_private; req->status = -1; - req->sense_len = 0; req->ops = reqops; object_ref(OBJECT(d)); object_ref(OBJECT(qbus->parent)); + notifier_list_init(&req->cancel_notifiers); trace_scsi_req_alloc(req->dev->id, req->lun, req->tag); return req; } @@ -560,13 +573,44 @@ SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun, uint8_t *buf, void *hba_private) { SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus); + const SCSIReqOps *ops; + SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(d); SCSIRequest *req; - SCSICommand cmd; + SCSICommand cmd = { .len = 0 }; + int ret; + + if ((d->unit_attention.key == UNIT_ATTENTION || + bus->unit_attention.key == UNIT_ATTENTION) && + (buf[0] != INQUIRY && + buf[0] != REPORT_LUNS && + buf[0] != GET_CONFIGURATION && + buf[0] != GET_EVENT_STATUS_NOTIFICATION && + + /* + * If we already have a pending unit attention condition, + * report this one before triggering another one. + */ + !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) { + ops = &reqops_unit_attention; + } else if (lun != d->lun || + buf[0] == REPORT_LUNS || + (buf[0] == REQUEST_SENSE && d->sense_len)) { + ops = &reqops_target_command; + } else { + ops = NULL; + } + + if (ops != NULL || !sc->parse_cdb) { + ret = scsi_req_parse_cdb(d, &cmd, buf); + } else { + ret = sc->parse_cdb(d, &cmd, buf, hba_private); + } - if (scsi_req_parse(&cmd, d, buf) != 0) { + if (ret != 0) { trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]); req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private); } else { + assert(cmd.len != 0); trace_scsi_req_parsed(d->id, lun, tag, buf[0], cmd.mode, cmd.xfer); if (cmd.lba != -1) { @@ -576,25 +620,8 @@ SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun, if (cmd.xfer > INT32_MAX) { req = scsi_req_alloc(&reqops_invalid_field, d, tag, lun, hba_private); - } else if ((d->unit_attention.key == UNIT_ATTENTION || - bus->unit_attention.key == UNIT_ATTENTION) && - (buf[0] != INQUIRY && - buf[0] != REPORT_LUNS && - buf[0] != GET_CONFIGURATION && - buf[0] != GET_EVENT_STATUS_NOTIFICATION && - - /* - * If we already have a pending unit attention condition, - * report this one before triggering another one. - */ - !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) { - req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun, - hba_private); - } else if (lun != d->lun || - buf[0] == REPORT_LUNS || - (buf[0] == REQUEST_SENSE && d->sense_len)) { - req = scsi_req_alloc(&reqops_target_command, d, tag, lun, - hba_private); + } else if (ops) { + req = scsi_req_alloc(ops, d, tag, lun, hba_private); } else { req = scsi_device_alloc_req(d, tag, lun, buf, hba_private); } @@ -793,7 +820,7 @@ static int ata_passthrough_xfer_unit(SCSIDevice *dev, uint8_t *buf) return xfer_unit; } -static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf) +static int ata_passthrough_12_xfer(SCSIDevice *dev, uint8_t *buf) { int length = buf[2] & 0x3; int xfer; @@ -816,7 +843,7 @@ static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf) return xfer * unit; } -static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf) +static int ata_passthrough_16_xfer(SCSIDevice *dev, uint8_t *buf) { int extend = buf[1] & 0x1; int length = buf[2] & 0x3; @@ -842,16 +869,16 @@ static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf) return xfer * unit; } -uint32_t scsi_data_cdb_length(uint8_t *buf) +uint32_t scsi_data_cdb_xfer(uint8_t *buf) { if ((buf[0] >> 5) == 0 && buf[4] == 0) { return 256; } else { - return scsi_cdb_length(buf); + return scsi_cdb_xfer(buf); } } -uint32_t scsi_cdb_length(uint8_t *buf) +uint32_t scsi_cdb_xfer(uint8_t *buf) { switch (buf[0] >> 5) { case 0: @@ -872,9 +899,9 @@ uint32_t scsi_cdb_length(uint8_t *buf) } } -static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) +static int scsi_req_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) { - cmd->xfer = scsi_cdb_length(buf); + cmd->xfer = scsi_cdb_xfer(buf); switch (buf[0]) { case TEST_UNIT_READY: case REWIND: @@ -938,6 +965,7 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) if (cmd->xfer == 0) { cmd->xfer = 256; } + /* fall through */ case WRITE_10: case WRITE_VERIFY_10: case WRITE_12: @@ -952,6 +980,7 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) if (cmd->xfer == 0) { cmd->xfer = 256; } + /* fall through */ case READ_10: case RECOVER_BUFFERED_DATA: case READ_12: @@ -1003,17 +1032,17 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) /* BLANK command of MMC */ cmd->xfer = 0; } else { - cmd->xfer = ata_passthrough_12_xfer_size(dev, buf); + cmd->xfer = ata_passthrough_12_xfer(dev, buf); } break; case ATA_PASSTHROUGH_16: - cmd->xfer = ata_passthrough_16_xfer_size(dev, buf); + cmd->xfer = ata_passthrough_16_xfer(dev, buf); break; } return 0; } -static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) +static int scsi_req_stream_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) { switch (buf[0]) { /* stream commands */ @@ -1068,12 +1097,12 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu break; /* generic commands */ default: - return scsi_req_length(cmd, dev, buf); + return scsi_req_xfer(cmd, dev, buf); } return 0; } -static int scsi_req_medium_changer_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) +static int scsi_req_medium_changer_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) { switch (buf[0]) { /* medium changer commands */ @@ -1090,7 +1119,7 @@ static int scsi_req_medium_changer_length(SCSICommand *cmd, SCSIDevice *dev, uin /* generic commands */ default: - return scsi_req_length(cmd, dev, buf); + return scsi_req_xfer(cmd, dev, buf); } return 0; } @@ -1179,37 +1208,45 @@ static uint64_t scsi_cmd_lba(SCSICommand *cmd) return lba; } -int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf) -{ - int rc; +int scsi_cdb_length(uint8_t *buf) { + int cdb_len; switch (buf[0] >> 5) { case 0: - cmd->len = 6; + cdb_len = 6; break; case 1: case 2: - cmd->len = 10; + cdb_len = 10; break; case 4: - cmd->len = 16; + cdb_len = 16; break; case 5: - cmd->len = 12; + cdb_len = 12; break; default: - return -1; + cdb_len = -1; } + return cdb_len; +} + +int scsi_req_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, uint8_t *buf) +{ + int rc; + + cmd->lba = -1; + cmd->len = scsi_cdb_length(buf); switch (dev->type) { case TYPE_TAPE: - rc = scsi_req_stream_length(cmd, dev, buf); + rc = scsi_req_stream_xfer(cmd, dev, buf); break; case TYPE_MEDIUM_CHANGER: - rc = scsi_req_medium_changer_length(cmd, dev, buf); + rc = scsi_req_medium_changer_xfer(cmd, dev, buf); break; default: - rc = scsi_req_length(cmd, dev, buf); + rc = scsi_req_xfer(cmd, dev, buf); break; } @@ -1427,7 +1464,7 @@ int scsi_build_sense(uint8_t *in_buf, int in_len, } } -static const char *scsi_command_name(uint8_t cmd) +const char *scsi_command_name(uint8_t cmd) { static const char *names[] = { [ TEST_UNIT_READY ] = "TEST_UNIT_READY", @@ -1543,6 +1580,8 @@ static const char *scsi_command_name(uint8_t cmd) [ SET_READ_AHEAD ] = "SET_READ_AHEAD", [ ALLOW_OVERWRITE ] = "ALLOW_OVERWRITE", [ MECHANISM_STATUS ] = "MECHANISM_STATUS", + [ GET_EVENT_STATUS_NOTIFICATION ] = "GET_EVENT_STATUS_NOTIFICATION", + [ READ_DISC_INFORMATION ] = "READ_DISC_INFORMATION", }; if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL) @@ -1572,7 +1611,7 @@ void scsi_req_unref(SCSIRequest *req) } object_unref(OBJECT(req->dev)); object_unref(OBJECT(qbus->parent)); - g_free(req); + g_slice_free1(req->ops->size, req); } } @@ -1682,40 +1721,56 @@ void scsi_req_complete(SCSIRequest *req, int status) scsi_req_ref(req); scsi_req_dequeue(req); req->bus->info->complete(req, req->status, req->resid); + + /* Cancelled requests might end up being completed instead of cancelled */ + notifier_list_notify(&req->cancel_notifiers, req); scsi_req_unref(req); } -void scsi_req_cancel(SCSIRequest *req) +/* Called by the devices when the request is canceled. */ +void scsi_req_cancel_complete(SCSIRequest *req) +{ + assert(req->io_canceled); + if (req->bus->info->cancel) { + req->bus->info->cancel(req); + } + notifier_list_notify(&req->cancel_notifiers, req); + scsi_req_unref(req); +} + +/* Cancel @req asynchronously. @notifier is added to @req's cancellation + * notifier list, the bus will be notified the requests cancellation is + * completed. + * */ +void scsi_req_cancel_async(SCSIRequest *req, Notifier *notifier) { trace_scsi_req_cancel(req->dev->id, req->lun, req->tag); - if (!req->enqueued) { + if (notifier) { + notifier_list_add(&req->cancel_notifiers, notifier); + } + if (req->io_canceled) { return; } scsi_req_ref(req); scsi_req_dequeue(req); req->io_canceled = true; - if (req->ops->cancel_io) { - req->ops->cancel_io(req); + if (req->aiocb) { + blk_aio_cancel_async(req->aiocb); } - if (req->bus->info->cancel) { - req->bus->info->cancel(req); - } - scsi_req_unref(req); } -void scsi_req_abort(SCSIRequest *req, int status) +void scsi_req_cancel(SCSIRequest *req) { + trace_scsi_req_cancel(req->dev->id, req->lun, req->tag); if (!req->enqueued) { return; } scsi_req_ref(req); scsi_req_dequeue(req); req->io_canceled = true; - if (req->ops->cancel_io) { - req->ops->cancel_io(req); + if (req->aiocb) { + blk_aio_cancel(req->aiocb); } - scsi_req_complete(req, status); - scsi_req_unref(req); } static int scsi_ua_precedence(SCSISense sense) @@ -1887,17 +1942,6 @@ static int get_scsi_requests(QEMUFile *f, void *pv, size_t size) return 0; } -static int scsi_qdev_unplug(DeviceState *qdev) -{ - SCSIDevice *dev = SCSI_DEVICE(qdev); - SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus); - - if (bus->info->hot_unplug) { - bus->info->hot_unplug(bus, dev); - } - return qdev_simple_unplug_cb(qdev); -} - static const VMStateInfo vmstate_info_scsi_requests = { .name = "scsi-requests", .get = get_scsi_requests, @@ -1915,8 +1959,7 @@ static const VMStateDescription vmstate_scsi_sense_state = { .name = "SCSIDevice/sense", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8_SUB_ARRAY(sense, SCSIDevice, SCSI_SENSE_BUF_SIZE_OLD, SCSI_SENSE_BUF_SIZE - SCSI_SENSE_BUF_SIZE_OLD), @@ -1928,7 +1971,6 @@ const VMStateDescription vmstate_scsi_device = { .name = "SCSIDevice", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT8(unit_attention.key, SCSIDevice), VMSTATE_UINT8(unit_attention.asc, SCSIDevice), @@ -1961,11 +2003,20 @@ static void scsi_device_class_init(ObjectClass *klass, void *data) { DeviceClass *k = DEVICE_CLASS(klass); set_bit(DEVICE_CATEGORY_STORAGE, k->categories); - k->bus_type = TYPE_SCSI_BUS; - k->init = scsi_qdev_init; - k->unplug = scsi_qdev_unplug; - k->exit = scsi_qdev_exit; - k->props = scsi_props; + k->bus_type = TYPE_SCSI_BUS; + k->realize = scsi_qdev_realize; + k->unrealize = scsi_qdev_unrealize; + k->props = scsi_props; +} + +static void scsi_dev_instance_init(Object *obj) +{ + DeviceState *dev = DEVICE(obj); + SCSIDevice *s = DO_UPCAST(SCSIDevice, qdev, dev); + + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", NULL, + &s->qdev, NULL); } static const TypeInfo scsi_device_type_info = { @@ -1975,6 +2026,7 @@ static const TypeInfo scsi_device_type_info = { .abstract = true, .class_size = sizeof(SCSIDeviceClass), .class_init = scsi_device_class_init, + .instance_init = scsi_dev_instance_init, }; static void scsi_register_types(void) diff --git a/hw/scsi/scsi-disk.c b/hw/scsi/scsi-disk.c index 48a28ae199..2f75d7d51c 100644 --- a/hw/scsi/scsi-disk.c +++ b/hw/scsi/scsi-disk.c @@ -33,6 +33,7 @@ do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0) #include "hw/scsi/scsi.h" #include "block/scsi.h" #include "sysemu/sysemu.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/block/block.h" #include "sysemu/dma.h" @@ -105,30 +106,13 @@ static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense) scsi_req_complete(&r->req, CHECK_CONDITION); } -/* Cancel a pending data transfer. */ -static void scsi_cancel_io(SCSIRequest *req) -{ - SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); - - DPRINTF("Cancel tag=0x%x\n", req->tag); - if (r->req.aiocb) { - bdrv_aio_cancel(r->req.aiocb); - - /* This reference was left in by scsi_*_data. We take ownership of - * it the moment scsi_req_cancel is called, independent of whether - * bdrv_aio_cancel completes the request or not. */ - scsi_req_unref(&r->req); - } - r->req.aiocb = NULL; -} - static uint32_t scsi_init_iovec(SCSIDiskReq *r, size_t size) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); if (!r->iov.iov_base) { r->buflen = size; - r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen); + r->iov.iov_base = blk_blockalign(s->qdev.conf.blk, r->buflen); } r->iov.iov_len = MIN(r->sector_count * 512, r->buflen); qemu_iovec_init_external(&r->qiov, &r->iov, 1); @@ -183,8 +167,9 @@ static void scsi_aio_complete(void *opaque, int ret) assert(r->req.aiocb != NULL); r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -197,9 +182,7 @@ static void scsi_aio_complete(void *opaque, int ret) scsi_req_complete(&r->req, GOOD); done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } static bool scsi_is_cmd_fua(SCSICommand *cmd) @@ -233,21 +216,21 @@ static void scsi_write_do_fua(SCSIDiskReq *r) SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } if (scsi_is_cmd_fua(&r->req.cmd)) { - bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH); - r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0, + BLOCK_ACCT_FLUSH); + r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r); return; } scsi_req_complete(&r->req, GOOD); done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } static void scsi_dma_complete_noio(void *opaque, int ret) @@ -257,9 +240,10 @@ static void scsi_dma_complete_noio(void *opaque, int ret) if (r->req.aiocb != NULL) { r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); } if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -279,9 +263,7 @@ static void scsi_dma_complete_noio(void *opaque, int ret) } done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } static void scsi_dma_complete(void *opaque, int ret) @@ -300,8 +282,9 @@ static void scsi_read_complete(void * opaque, int ret) assert(r->req.aiocb != NULL); r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -319,9 +302,7 @@ static void scsi_read_complete(void * opaque, int ret) scsi_req_data(&r->req, r->qiov.size); done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } /* Actually issue a read to the block device. */ @@ -333,9 +314,10 @@ static void scsi_do_read(void *opaque, int ret) if (r->req.aiocb != NULL) { r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); } if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -349,21 +331,20 @@ static void scsi_do_read(void *opaque, int ret) scsi_req_ref(&r->req); if (r->req.sg) { - dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ); + dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_READ); r->req.resid -= r->req.sg->size; - r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector, - scsi_dma_complete, r); + r->req.aiocb = dma_blk_read(s->qdev.conf.blk, r->req.sg, r->sector, + scsi_dma_complete, r); } else { n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE); - bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); - r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n, - scsi_read_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, + n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ); + r->req.aiocb = blk_aio_readv(s->qdev.conf.blk, r->sector, &r->qiov, n, + scsi_read_complete, r); } done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } /* Read more data from scsi device into buffer. */ @@ -399,8 +380,9 @@ static void scsi_read_data(SCSIRequest *req) first = !r->started; r->started = true; if (first && scsi_is_cmd_fua(&r->req.cmd)) { - bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH); - r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_do_read, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0, + BLOCK_ACCT_FLUSH); + r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_do_read, r); } else { scsi_do_read(r, 0); } @@ -417,9 +399,10 @@ static int scsi_handle_rw_error(SCSIDiskReq *r, int error) { bool is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); - BlockErrorAction action = bdrv_get_error_action(s->qdev.conf.bs, is_read, error); + BlockErrorAction action = blk_get_error_action(s->qdev.conf.blk, + is_read, error); - if (action == BDRV_ACTION_REPORT) { + if (action == BLOCK_ERROR_ACTION_REPORT) { switch (error) { case ENOMEDIUM: scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); @@ -438,11 +421,11 @@ static int scsi_handle_rw_error(SCSIDiskReq *r, int error) break; } } - bdrv_error_action(s->qdev.conf.bs, action, is_read, error); - if (action == BDRV_ACTION_STOP) { + blk_error_action(s->qdev.conf.blk, action, is_read, error); + if (action == BLOCK_ERROR_ACTION_STOP) { scsi_req_retry(&r->req); } - return action != BDRV_ACTION_IGNORE; + return action != BLOCK_ERROR_ACTION_IGNORE; } static void scsi_write_complete(void * opaque, int ret) @@ -453,9 +436,10 @@ static void scsi_write_complete(void * opaque, int ret) if (r->req.aiocb != NULL) { r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); } if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -478,9 +462,7 @@ static void scsi_write_complete(void * opaque, int ret) } done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } static void scsi_write_data(SCSIRequest *req) @@ -522,15 +504,16 @@ static void scsi_write_data(SCSIRequest *req) } if (r->req.sg) { - dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_WRITE); + dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_WRITE); r->req.resid -= r->req.sg->size; - r->req.aiocb = dma_bdrv_write(s->qdev.conf.bs, r->req.sg, r->sector, - scsi_dma_complete, r); + r->req.aiocb = dma_blk_write(s->qdev.conf.blk, r->req.sg, r->sector, + scsi_dma_complete, r); } else { n = r->qiov.size / 512; - bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE); - r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, r->sector, &r->qiov, n, - scsi_write_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, + n * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE); + r->req.aiocb = blk_aio_writev(s->qdev.conf.blk, r->sector, &r->qiov, n, + scsi_write_complete, r); } } @@ -597,7 +580,7 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf) case 0x83: /* Device identification page, mandatory */ { - const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs); + const char *str = s->serial ?: blk_name(s->qdev.conf.blk); int max_len = s->serial ? 20 : 255 - 8; int id_len = strlen(str); @@ -758,10 +741,10 @@ static inline bool media_is_dvd(SCSIDiskState *s) if (s->qdev.type != TYPE_ROM) { return false; } - if (!bdrv_is_inserted(s->qdev.conf.bs)) { + if (!blk_is_inserted(s->qdev.conf.blk)) { return false; } - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); return nb_sectors > CD_MAX_SECTORS; } @@ -771,10 +754,10 @@ static inline bool media_is_cd(SCSIDiskState *s) if (s->qdev.type != TYPE_ROM) { return false; } - if (!bdrv_is_inserted(s->qdev.conf.bs)) { + if (!blk_is_inserted(s->qdev.conf.blk)) { return false; } - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); return nb_sectors <= CD_MAX_SECTORS; } @@ -835,7 +818,7 @@ static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r, } if (format != 0xff) { - if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) { + if (s->tray_open || !blk_is_inserted(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); return -1; } @@ -857,7 +840,7 @@ static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r, if (layer != 0) { goto fail; } - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); outbuf[4] = 1; /* DVD-ROM, part version 1 */ outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */ @@ -912,7 +895,7 @@ static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf) media_status = 0; if (s->tray_open) { media_status = MS_TRAY_OPEN; - } else if (bdrv_is_inserted(s->qdev.conf.bs)) { + } else if (blk_is_inserted(s->qdev.conf.blk)) { media_status = MS_MEDIA_PRESENT; } @@ -1110,7 +1093,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf, case MODE_PAGE_CACHING: length = 0x12; if (page_control == 1 || /* Changeable Values */ - bdrv_enable_write_cache(s->qdev.conf.bs)) { + blk_enable_write_cache(s->qdev.conf.blk)) { p[0] = 4; /* WCE */ } break; @@ -1191,7 +1174,7 @@ static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf) if (s->qdev.type == TYPE_DISK) { dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0; - if (bdrv_is_read_only(s->qdev.conf.bs)) { + if (blk_is_read_only(s->qdev.conf.blk)) { dev_specific_param |= 0x80; /* Readonly. */ } } else { @@ -1213,7 +1196,7 @@ static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf) p += 8; } - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); if (!dbd && nb_sectors) { if (r->req.cmd.buf[0] == MODE_SENSE) { outbuf[3] = 8; /* Block descriptor length */ @@ -1276,7 +1259,7 @@ static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf) msf = req->cmd.buf[1] & 2; format = req->cmd.buf[2] & 0xf; start_track = req->cmd.buf[6]; - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1); nb_sectors /= s->qdev.blocksize / 512; switch (format) { @@ -1316,14 +1299,14 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r) if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) { if (!start && !s->tray_open && s->tray_locked) { scsi_check_condition(r, - bdrv_is_inserted(s->qdev.conf.bs) + blk_is_inserted(s->qdev.conf.blk) ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED) : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED)); return -1; } if (s->tray_open != !start) { - bdrv_eject(s->qdev.conf.bs, !start); + blk_eject(s->qdev.conf.blk, !start); s->tray_open = !start; } } @@ -1390,7 +1373,7 @@ static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p) { switch (page) { case MODE_PAGE_CACHING: - bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0); + blk_set_enable_write_cache(s->qdev.conf.blk, (p[0] & 4) != 0); break; default: @@ -1493,11 +1476,12 @@ static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf) return; } } - if (!bdrv_enable_write_cache(s->qdev.conf.bs)) { + if (!blk_enable_write_cache(s->qdev.conf.blk)) { /* The request is used as the AIO opaque value, so add a ref. */ scsi_req_ref(&r->req); - bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH); - r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0, + BLOCK_ACCT_FLUSH); + r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r); return; } @@ -1548,6 +1532,7 @@ static void scsi_unmap_complete(void *opaque, int ret) r->req.aiocb = NULL; if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -1565,10 +1550,10 @@ static void scsi_unmap_complete(void *opaque, int ret) goto done; } - r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs, - sector_num * (s->qdev.blocksize / 512), - nb_sectors * (s->qdev.blocksize / 512), - scsi_unmap_complete, data); + r->req.aiocb = blk_aio_discard(s->qdev.conf.blk, + sector_num * (s->qdev.blocksize / 512), + nb_sectors * (s->qdev.blocksize / 512), + scsi_unmap_complete, data); data->count--; data->inbuf += 16; return; @@ -1577,9 +1562,7 @@ static void scsi_unmap_complete(void *opaque, int ret) scsi_req_complete(&r->req, GOOD); done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); g_free(data); } @@ -1608,7 +1591,7 @@ static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf) goto invalid_param_len; } - if (bdrv_is_read_only(s->qdev.conf.bs)) { + if (blk_is_read_only(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED)); return; } @@ -1647,8 +1630,9 @@ static void scsi_write_same_complete(void *opaque, int ret) assert(r->req.aiocb != NULL); r->req.aiocb = NULL; - bdrv_acct_done(s->qdev.conf.bs, &r->acct); + block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct); if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); goto done; } @@ -1662,19 +1646,18 @@ static void scsi_write_same_complete(void *opaque, int ret) data->sector += data->iov.iov_len / 512; data->iov.iov_len = MIN(data->nb_sectors * 512, data->iov.iov_len); if (data->iov.iov_len) { - bdrv_acct_start(s->qdev.conf.bs, &r->acct, data->iov.iov_len, BDRV_ACCT_WRITE); - r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, data->sector, - &data->qiov, data->iov.iov_len / 512, - scsi_write_same_complete, data); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, + data->iov.iov_len, BLOCK_ACCT_WRITE); + r->req.aiocb = blk_aio_writev(s->qdev.conf.blk, data->sector, + &data->qiov, data->iov.iov_len / 512, + scsi_write_same_complete, data); return; } scsi_req_complete(&r->req, GOOD); done: - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); qemu_vfree(data->iov.iov_base); g_free(data); } @@ -1683,7 +1666,7 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf) { SCSIRequest *req = &r->req; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); - uint32_t nb_sectors = scsi_data_cdb_length(r->req.cmd.buf); + uint32_t nb_sectors = scsi_data_cdb_xfer(r->req.cmd.buf); WriteSameCBData *data; uint8_t *buf; int i; @@ -1694,7 +1677,7 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf) return; } - if (bdrv_is_read_only(s->qdev.conf.bs)) { + if (blk_is_read_only(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED)); return; } @@ -1708,12 +1691,13 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf) /* The request is used as the AIO opaque value, so add a ref. */ scsi_req_ref(&r->req); - bdrv_acct_start(s->qdev.conf.bs, &r->acct, nb_sectors * s->qdev.blocksize, - BDRV_ACCT_WRITE); - r->req.aiocb = bdrv_aio_write_zeroes(s->qdev.conf.bs, - r->req.cmd.lba * (s->qdev.blocksize / 512), - nb_sectors * (s->qdev.blocksize / 512), - flags, scsi_aio_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, + nb_sectors * s->qdev.blocksize, + BLOCK_ACCT_WRITE); + r->req.aiocb = blk_aio_write_zeroes(s->qdev.conf.blk, + r->req.cmd.lba * (s->qdev.blocksize / 512), + nb_sectors * (s->qdev.blocksize / 512), + flags, scsi_aio_complete, r); return; } @@ -1722,7 +1706,8 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf) data->sector = r->req.cmd.lba * (s->qdev.blocksize / 512); data->nb_sectors = nb_sectors * (s->qdev.blocksize / 512); data->iov.iov_len = MIN(data->nb_sectors * 512, SCSI_WRITE_SAME_MAX); - data->iov.iov_base = buf = qemu_blockalign(s->qdev.conf.bs, data->iov.iov_len); + data->iov.iov_base = buf = blk_blockalign(s->qdev.conf.blk, + data->iov.iov_len); qemu_iovec_init_external(&data->qiov, &data->iov, 1); for (i = 0; i < data->iov.iov_len; i += s->qdev.blocksize) { @@ -1730,10 +1715,11 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf) } scsi_req_ref(&r->req); - bdrv_acct_start(s->qdev.conf.bs, &r->acct, data->iov.iov_len, BDRV_ACCT_WRITE); - r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, data->sector, - &data->qiov, data->iov.iov_len / 512, - scsi_write_same_complete, data); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, + data->iov.iov_len, BLOCK_ACCT_WRITE); + r->req.aiocb = blk_aio_writev(s->qdev.conf.blk, data->sector, + &data->qiov, data->iov.iov_len / 512, + scsi_write_same_complete, data); } static void scsi_disk_emulate_write_data(SCSIRequest *req) @@ -1802,7 +1788,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) break; default: - if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) { + if (s->tray_open || !blk_is_inserted(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); return 0; } @@ -1823,7 +1809,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) r->buflen = MAX(4096, req->cmd.xfer); if (!r->iov.iov_base) { - r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen); + r->iov.iov_base = blk_blockalign(s->qdev.conf.blk, r->buflen); } buflen = req->cmd.xfer; @@ -1831,7 +1817,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) memset(outbuf, 0, r->buflen); switch (req->cmd.buf[0]) { case TEST_UNIT_READY: - assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs)); + assert(!s->tray_open && blk_is_inserted(s->qdev.conf.blk)); break; case INQUIRY: buflen = scsi_disk_emulate_inquiry(req, outbuf); @@ -1879,12 +1865,12 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) break; case ALLOW_MEDIUM_REMOVAL: s->tray_locked = req->cmd.buf[4] & 1; - bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1); + blk_lock_medium(s->qdev.conf.blk, req->cmd.buf[4] & 1); break; case READ_CAPACITY_10: /* The normal LEN field for this command is zero. */ memset(outbuf, 0, 8); - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); if (!nb_sectors) { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); return 0; @@ -1953,7 +1939,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) { DPRINTF("SAI READ CAPACITY(16)\n"); memset(outbuf, 0, req->cmd.xfer); - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); if (!nb_sectors) { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); return 0; @@ -1994,8 +1980,9 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) case SYNCHRONIZE_CACHE: /* The request is used as the AIO opaque value, so add a ref. */ scsi_req_ref(&r->req); - bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH); - r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r); + block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0, + BLOCK_ACCT_FLUSH); + r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r); return 0; case SEEK_10: DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba); @@ -2015,7 +2002,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) case VERIFY_10: case VERIFY_12: case VERIFY_16: - DPRINTF("Verify (bytchk %lu)\n", (r->req.buf[1] >> 1) & 3); + DPRINTF("Verify (bytchk %d)\n", (req->cmd.buf[1] >> 1) & 3); if (req->cmd.buf[1] & 6) { goto illegal_request; } @@ -2027,7 +2014,8 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf) (long)r->req.cmd.xfer); break; default: - DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]); + DPRINTF("Unknown SCSI command (%2.2x=%s)\n", buf[0], + scsi_command_name(buf[0])); scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return 0; } @@ -2068,12 +2056,12 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf) command = buf[0]; - if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) { + if (s->tray_open || !blk_is_inserted(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); return 0; } - len = scsi_data_cdb_length(r->req.cmd.buf); + len = scsi_data_cdb_xfer(r->req.cmd.buf); switch (command) { case READ_6: case READ_10: @@ -2096,7 +2084,7 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf) case WRITE_VERIFY_10: case WRITE_VERIFY_12: case WRITE_VERIFY_16: - if (bdrv_is_read_only(s->qdev.conf.bs)) { + if (blk_is_read_only(s->qdev.conf.blk)) { scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED)); return 0; } @@ -2139,7 +2127,7 @@ static void scsi_disk_reset(DeviceState *dev) scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET)); - bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors); + blk_get_geometry(s->qdev.conf.blk, &nb_sectors); nb_sectors /= s->qdev.blocksize / 512; if (nb_sectors) { nb_sectors--; @@ -2150,14 +2138,6 @@ static void scsi_disk_reset(DeviceState *dev) s->tray_open = 0; } -static void scsi_destroy(SCSIDevice *dev) -{ - SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); - - scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE)); - blockdev_mark_auto_del(s->qdev.conf.bs); -} - static void scsi_disk_resize_cb(void *opaque) { SCSIDiskState *s = opaque; @@ -2233,25 +2213,29 @@ static void scsi_disk_unit_attention_reported(SCSIDevice *dev) } } -static int scsi_initfn(SCSIDevice *dev) +static void scsi_realize(SCSIDevice *dev, Error **errp) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); + Error *err = NULL; - if (!s->qdev.conf.bs) { - error_report("drive property not set"); - return -1; + if (!s->qdev.conf.blk) { + error_setg(errp, "drive property not set"); + return; } if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) && - !bdrv_is_inserted(s->qdev.conf.bs)) { - error_report("Device needs media, but drive is empty"); - return -1; + !blk_is_inserted(s->qdev.conf.blk)) { + error_setg(errp, "Device needs media, but drive is empty"); + return; } blkconf_serial(&s->qdev.conf, &s->serial); - if (dev->type == TYPE_DISK - && blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) { - return -1; + if (dev->type == TYPE_DISK) { + blkconf_geometry(&dev->conf, NULL, 65535, 255, 255, &err); + if (err) { + error_propagate(errp, err); + return; + } } if (s->qdev.conf.discard_granularity == -1) { @@ -2266,25 +2250,23 @@ static int scsi_initfn(SCSIDevice *dev) s->vendor = g_strdup("QEMU"); } - if (bdrv_is_sg(s->qdev.conf.bs)) { - error_report("unwanted /dev/sg*"); - return -1; + if (blk_is_sg(s->qdev.conf.blk)) { + error_setg(errp, "unwanted /dev/sg*"); + return; } if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && !(s->features & (1 << SCSI_DISK_F_NO_REMOVABLE_DEVOPS))) { - bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s); + blk_set_dev_ops(s->qdev.conf.blk, &scsi_disk_removable_block_ops, s); } else { - bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s); + blk_set_dev_ops(s->qdev.conf.blk, &scsi_disk_block_ops, s); } - bdrv_set_guest_block_size(s->qdev.conf.bs, s->qdev.blocksize); + blk_set_guest_block_size(s->qdev.conf.blk, s->qdev.blocksize); - bdrv_iostatus_enable(s->qdev.conf.bs); - add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL); - return 0; + blk_iostatus_enable(s->qdev.conf.blk); } -static int scsi_hd_initfn(SCSIDevice *dev) +static void scsi_hd_realize(SCSIDevice *dev, Error **errp) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); s->qdev.blocksize = s->qdev.conf.logical_block_size; @@ -2292,10 +2274,10 @@ static int scsi_hd_initfn(SCSIDevice *dev) if (!s->product) { s->product = g_strdup("QEMU HARDDISK"); } - return scsi_initfn(&s->qdev); + scsi_realize(&s->qdev, errp); } -static int scsi_cd_initfn(SCSIDevice *dev) +static void scsi_cd_realize(SCSIDevice *dev, Error **errp) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); s->qdev.blocksize = 2048; @@ -2304,22 +2286,26 @@ static int scsi_cd_initfn(SCSIDevice *dev) if (!s->product) { s->product = g_strdup("QEMU CD-ROM"); } - return scsi_initfn(&s->qdev); + scsi_realize(&s->qdev, errp); } -static int scsi_disk_initfn(SCSIDevice *dev) +static void scsi_disk_realize(SCSIDevice *dev, Error **errp) { DriveInfo *dinfo; + Error *local_err = NULL; - if (!dev->conf.bs) { - return scsi_initfn(dev); /* ... and die there */ + if (!dev->conf.blk) { + scsi_realize(dev, &local_err); + assert(local_err); + error_propagate(errp, local_err); + return; } - dinfo = drive_get_by_blockdev(dev->conf.bs); - if (dinfo->media_cd) { - return scsi_cd_initfn(dev); + dinfo = blk_legacy_dinfo(dev->conf.blk); + if (dinfo && dinfo->media_cd) { + scsi_cd_realize(dev, errp); } else { - return scsi_hd_initfn(dev); + scsi_hd_realize(dev, errp); } } @@ -2329,7 +2315,6 @@ static const SCSIReqOps scsi_disk_emulate_reqops = { .send_command = scsi_disk_emulate_command, .read_data = scsi_disk_emulate_read_data, .write_data = scsi_disk_emulate_write_data, - .cancel_io = scsi_cancel_io, .get_buf = scsi_get_buf, }; @@ -2339,7 +2324,6 @@ static const SCSIReqOps scsi_disk_dma_reqops = { .send_command = scsi_disk_dma_command, .read_data = scsi_read_data, .write_data = scsi_write_data, - .cancel_io = scsi_cancel_io, .get_buf = scsi_get_buf, .load_request = scsi_disk_load_request, .save_request = scsi_disk_save_request, @@ -2404,7 +2388,7 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]); { int i; - for (i = 1; i < req->cmd.len; i++) { + for (i = 1; i < scsi_cdb_length(buf); i++) { printf(" 0x%02x", buf[i]); } printf("\n"); @@ -2417,7 +2401,6 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, #ifdef __linux__ static int get_device_type(SCSIDiskState *s) { - BlockDriverState *bdrv = s->qdev.conf.bs; uint8_t cmd[16]; uint8_t buf[36]; uint8_t sensebuf[8]; @@ -2440,7 +2423,7 @@ static int get_device_type(SCSIDiskState *s) io_header.sbp = sensebuf; io_header.timeout = 6000; /* XXX */ - ret = bdrv_ioctl(bdrv, SG_IO, &io_header); + ret = blk_ioctl(s->qdev.conf.blk, SG_IO, &io_header); if (ret < 0 || io_header.driver_status || io_header.host_status) { return -1; } @@ -2451,29 +2434,35 @@ static int get_device_type(SCSIDiskState *s) return 0; } -static int scsi_block_initfn(SCSIDevice *dev) +static void scsi_block_realize(SCSIDevice *dev, Error **errp) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); int sg_version; int rc; - if (!s->qdev.conf.bs) { - error_report("scsi-block: drive property not set"); - return -1; + if (!s->qdev.conf.blk) { + error_setg(errp, "drive property not set"); + return; } /* check we are using a driver managing SG_IO (version 3 and after) */ - if (bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 || - sg_version < 30000) { - error_report("scsi-block: scsi generic interface too old"); - return -1; + rc = blk_ioctl(s->qdev.conf.blk, SG_GET_VERSION_NUM, &sg_version); + if (rc < 0) { + error_setg(errp, "cannot get SG_IO version number: %s. " + "Is this a SCSI device?", + strerror(-rc)); + return; + } + if (sg_version < 30000) { + error_setg(errp, "scsi generic interface too old"); + return; } /* get device type from INQUIRY data */ rc = get_device_type(s); if (rc < 0) { - error_report("scsi-block: INQUIRY failed"); - return -1; + error_setg(errp, "INQUIRY failed"); + return; } /* Make a guess for the block size, we'll fix it when the guest sends. @@ -2491,15 +2480,11 @@ static int scsi_block_initfn(SCSIDevice *dev) */ s->features |= (1 << SCSI_DISK_F_NO_REMOVABLE_DEVOPS); - return scsi_initfn(&s->qdev); + scsi_realize(&s->qdev, errp); } -static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag, - uint32_t lun, uint8_t *buf, - void *hba_private) +static bool scsi_block_is_passthrough(SCSIDiskState *s, uint8_t *buf) { - SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); - switch (buf[0]) { case READ_6: case READ_10: @@ -2516,11 +2501,11 @@ static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag, case WRITE_VERIFY_12: case WRITE_VERIFY_16: /* If we are not using O_DIRECT, we might read stale data from the - * host cache if writes were made using other commands than these - * ones (such as WRITE SAME or EXTENDED COPY, etc.). So, without - * O_DIRECT everything must go through SG_IO. + * host cache if writes were made using other commands than these + * ones (such as WRITE SAME or EXTENDED COPY, etc.). So, without + * O_DIRECT everything must go through SG_IO. */ - if (bdrv_get_flags(s->qdev.conf.bs) & BDRV_O_NOCACHE) { + if (!(blk_get_flags(s->qdev.conf.blk) & BDRV_O_NOCACHE)) { break; } @@ -2535,14 +2520,45 @@ static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag, * just make scsi-block operate the same as scsi-generic for them. */ if (s->qdev.type != TYPE_ROM) { - return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun, - hba_private); + return false; } + break; + + default: + break; } - return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun, - hba_private); + return true; } + + +static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag, + uint32_t lun, uint8_t *buf, + void *hba_private) +{ + SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); + + if (scsi_block_is_passthrough(s, buf)) { + return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun, + hba_private); + } else { + return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun, + hba_private); + } +} + +static int scsi_block_parse_cdb(SCSIDevice *d, SCSICommand *cmd, + uint8_t *buf, void *hba_private) +{ + SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); + + if (scsi_block_is_passthrough(s, buf)) { + return scsi_bus_parse_cdb(&s->qdev, cmd, buf, hba_private); + } else { + return scsi_req_parse_cdb(&s->qdev, cmd, buf); + } +} + #endif #define DEFINE_SCSI_DISK_PROPERTIES() \ @@ -2571,7 +2587,6 @@ static const VMStateDescription vmstate_scsi_disk_state = { .name = "scsi-disk", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_SCSI_DEVICE(qdev, SCSIDiskState), VMSTATE_BOOL(media_changed, SCSIDiskState), @@ -2588,8 +2603,7 @@ static void scsi_hd_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); - sc->init = scsi_hd_initfn; - sc->destroy = scsi_destroy; + sc->realize = scsi_hd_realize; sc->alloc_req = scsi_new_request; sc->unit_attention_reported = scsi_disk_unit_attention_reported; dc->fw_name = "disk"; @@ -2619,8 +2633,7 @@ static void scsi_cd_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); - sc->init = scsi_cd_initfn; - sc->destroy = scsi_destroy; + sc->realize = scsi_cd_realize; sc->alloc_req = scsi_new_request; sc->unit_attention_reported = scsi_disk_unit_attention_reported; dc->fw_name = "disk"; @@ -2639,8 +2652,7 @@ static const TypeInfo scsi_cd_info = { #ifdef __linux__ static Property scsi_block_properties[] = { - DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.bs), - DEFINE_PROP_INT32("bootindex", SCSIDiskState, qdev.conf.bootindex, -1), + DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.blk), DEFINE_PROP_END_OF_LIST(), }; @@ -2649,9 +2661,9 @@ static void scsi_block_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); - sc->init = scsi_block_initfn; - sc->destroy = scsi_destroy; + sc->realize = scsi_block_realize; sc->alloc_req = scsi_block_new_request; + sc->parse_cdb = scsi_block_parse_cdb; dc->fw_name = "disk"; dc->desc = "SCSI block device passthrough"; dc->reset = scsi_disk_reset; @@ -2686,8 +2698,7 @@ static void scsi_disk_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); - sc->init = scsi_disk_initfn; - sc->destroy = scsi_destroy; + sc->realize = scsi_disk_realize; sc->alloc_req = scsi_new_request; sc->unit_attention_reported = scsi_disk_unit_attention_reported; dc->fw_name = "disk"; diff --git a/hw/scsi/scsi-generic.c b/hw/scsi/scsi-generic.c index 8d92e0da15..6b9e4e1ef9 100644 --- a/hw/scsi/scsi-generic.c +++ b/hw/scsi/scsi-generic.c @@ -14,6 +14,7 @@ #include "qemu-common.h" #include "qemu/error-report.h" #include "hw/scsi/scsi.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #ifdef __linux__ @@ -93,6 +94,10 @@ static void scsi_command_complete(void *opaque, int ret) SCSIGenericReq *r = (SCSIGenericReq *)opaque; r->req.aiocb = NULL; + if (r->req.io_canceled) { + scsi_req_cancel_complete(&r->req); + goto done; + } if (r->io_header.driver_status & SG_ERR_DRIVER_SENSE) { r->req.sense_len = r->io_header.sb_len_wr; } @@ -133,31 +138,13 @@ static void scsi_command_complete(void *opaque, int ret) r, r->req.tag, status); scsi_req_complete(&r->req, status); - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } -} - -/* Cancel a pending data transfer. */ -static void scsi_cancel_io(SCSIRequest *req) -{ - SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req); - - DPRINTF("Cancel tag=0x%x\n", req->tag); - if (r->req.aiocb) { - bdrv_aio_cancel(r->req.aiocb); - - /* This reference was left in by scsi_*_data. We take ownership of - * it independent of whether bdrv_aio_cancel completes the request - * or not. */ - scsi_req_unref(&r->req); - } - r->req.aiocb = NULL; +done: + scsi_req_unref(&r->req); } -static int execute_command(BlockDriverState *bdrv, +static int execute_command(BlockBackend *blk, SCSIGenericReq *r, int direction, - BlockDriverCompletionFunc *complete) + BlockCompletionFunc *complete) { r->io_header.interface_id = 'S'; r->io_header.dxfer_direction = direction; @@ -171,7 +158,7 @@ static int execute_command(BlockDriverState *bdrv, r->io_header.usr_ptr = r; r->io_header.flags |= SG_FLAG_DIRECT_IO; - r->req.aiocb = bdrv_aio_ioctl(bdrv, SG_IO, &r->io_header, complete, r); + r->req.aiocb = blk_aio_ioctl(blk, SG_IO, &r->io_header, complete, r); if (r->req.aiocb == NULL) { return -EIO; } @@ -186,8 +173,7 @@ static void scsi_read_complete(void * opaque, int ret) int len; r->req.aiocb = NULL; - if (ret) { - DPRINTF("IO error ret %d\n", ret); + if (ret || r->req.io_canceled) { scsi_command_complete(r, ret); return; } @@ -208,12 +194,10 @@ static void scsi_read_complete(void * opaque, int ret) s->blocksize = ldl_be_p(&r->buf[8]); s->max_lba = ldq_be_p(&r->buf[0]); } - bdrv_set_guest_block_size(s->conf.bs, s->blocksize); + blk_set_guest_block_size(s->conf.blk, s->blocksize); scsi_req_data(&r->req, len); - if (!r->req.io_canceled) { - scsi_req_unref(&r->req); - } + scsi_req_unref(&r->req); } } @@ -233,7 +217,8 @@ static void scsi_read_data(SCSIRequest *req) return; } - ret = execute_command(s->conf.bs, r, SG_DXFER_FROM_DEV, scsi_read_complete); + ret = execute_command(s->conf.blk, r, SG_DXFER_FROM_DEV, + scsi_read_complete); if (ret < 0) { scsi_command_complete(r, ret); } @@ -246,8 +231,7 @@ static void scsi_write_complete(void * opaque, int ret) DPRINTF("scsi_write_complete() ret = %d\n", ret); r->req.aiocb = NULL; - if (ret) { - DPRINTF("IO error\n"); + if (ret || r->req.io_canceled) { scsi_command_complete(r, ret); return; } @@ -278,7 +262,7 @@ static void scsi_write_data(SCSIRequest *req) /* The request is used as the AIO opaque value, so add a ref. */ scsi_req_ref(&r->req); - ret = execute_command(s->conf.bs, r, SG_DXFER_TO_DEV, scsi_write_complete); + ret = execute_command(s->conf.blk, r, SG_DXFER_TO_DEV, scsi_write_complete); if (ret < 0) { scsi_command_complete(r, ret); } @@ -303,9 +287,6 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd) SCSIDevice *s = r->req.dev; int ret; - DPRINTF("Command: lun=%d tag=0x%x len %zd data=0x%02x", lun, tag, - r->req.cmd.xfer, cmd[0]); - #ifdef DEBUG_SCSI { int i; @@ -323,7 +304,8 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd) r->buf = NULL; /* The request is used as the AIO opaque value, so add a ref. */ scsi_req_ref(&r->req); - ret = execute_command(s->conf.bs, r, SG_DXFER_NONE, scsi_command_complete); + ret = execute_command(s->conf.blk, r, SG_DXFER_NONE, + scsi_command_complete); if (ret < 0) { scsi_command_complete(r, ret); return 0; @@ -348,7 +330,7 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd) } } -static int get_stream_blocksize(BlockDriverState *bdrv) +static int get_stream_blocksize(BlockBackend *blk) { uint8_t cmd[6]; uint8_t buf[12]; @@ -372,7 +354,7 @@ static int get_stream_blocksize(BlockDriverState *bdrv) io_header.sbp = sensebuf; io_header.timeout = 6000; /* XXX */ - ret = bdrv_ioctl(bdrv, SG_IO, &io_header); + ret = blk_ioctl(blk, SG_IO, &io_header); if (ret < 0 || io_header.driver_status || io_header.host_status) { return -1; } @@ -386,57 +368,52 @@ static void scsi_generic_reset(DeviceState *dev) scsi_device_purge_requests(s, SENSE_CODE(RESET)); } -static void scsi_destroy(SCSIDevice *s) -{ - scsi_device_purge_requests(s, SENSE_CODE(NO_SENSE)); - blockdev_mark_auto_del(s->conf.bs); -} - -static int scsi_generic_initfn(SCSIDevice *s) +static void scsi_generic_realize(SCSIDevice *s, Error **errp) { + int rc; int sg_version; struct sg_scsi_id scsiid; - if (!s->conf.bs) { - error_report("drive property not set"); - return -1; + if (!s->conf.blk) { + error_setg(errp, "drive property not set"); + return; } - if (bdrv_get_on_error(s->conf.bs, 0) != BLOCKDEV_ON_ERROR_ENOSPC) { - error_report("Device doesn't support drive option werror"); - return -1; + if (blk_get_on_error(s->conf.blk, 0) != BLOCKDEV_ON_ERROR_ENOSPC) { + error_setg(errp, "Device doesn't support drive option werror"); + return; } - if (bdrv_get_on_error(s->conf.bs, 1) != BLOCKDEV_ON_ERROR_REPORT) { - error_report("Device doesn't support drive option rerror"); - return -1; + if (blk_get_on_error(s->conf.blk, 1) != BLOCKDEV_ON_ERROR_REPORT) { + error_setg(errp, "Device doesn't support drive option rerror"); + return; } /* check we are using a driver managing SG_IO (version 3 and after */ - if (bdrv_ioctl(s->conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0) { - error_report("scsi generic interface not supported"); - return -1; + rc = blk_ioctl(s->conf.blk, SG_GET_VERSION_NUM, &sg_version); + if (rc < 0) { + error_setg(errp, "cannot get SG_IO version number: %s. " + "Is this a SCSI device?", + strerror(-rc)); + return; } if (sg_version < 30000) { - error_report("scsi generic interface too old"); - return -1; + error_setg(errp, "scsi generic interface too old"); + return; } /* get LUN of the /dev/sg? */ - if (bdrv_ioctl(s->conf.bs, SG_GET_SCSI_ID, &scsiid)) { - error_report("SG_GET_SCSI_ID ioctl failed"); - return -1; + if (blk_ioctl(s->conf.blk, SG_GET_SCSI_ID, &scsiid)) { + error_setg(errp, "SG_GET_SCSI_ID ioctl failed"); + return; } /* define device state */ s->type = scsiid.scsi_type; DPRINTF("device type %d\n", s->type); - if (s->type == TYPE_DISK || s->type == TYPE_ROM) { - add_boot_device_path(s->conf.bootindex, &s->qdev, NULL); - } switch (s->type) { case TYPE_TAPE: - s->blocksize = get_stream_blocksize(s->conf.bs); + s->blocksize = get_stream_blocksize(s->conf.blk); if (s->blocksize == -1) { s->blocksize = 0; } @@ -456,7 +433,6 @@ static int scsi_generic_initfn(SCSIDevice *s) } DPRINTF("block size %d\n", s->blocksize); - return 0; } const SCSIReqOps scsi_generic_req_ops = { @@ -465,7 +441,6 @@ const SCSIReqOps scsi_generic_req_ops = { .send_command = scsi_send_command, .read_data = scsi_read_data, .write_data = scsi_write_data, - .cancel_io = scsi_cancel_io, .get_buf = scsi_get_buf, .load_request = scsi_generic_load_request, .save_request = scsi_generic_save_request, @@ -481,19 +456,24 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, } static Property scsi_generic_properties[] = { - DEFINE_PROP_DRIVE("drive", SCSIDevice, conf.bs), - DEFINE_PROP_INT32("bootindex", SCSIDevice, conf.bootindex, -1), + DEFINE_PROP_DRIVE("drive", SCSIDevice, conf.blk), DEFINE_PROP_END_OF_LIST(), }; +static int scsi_generic_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, + uint8_t *buf, void *hba_private) +{ + return scsi_bus_parse_cdb(dev, cmd, buf, hba_private); +} + static void scsi_generic_class_initfn(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass); - sc->init = scsi_generic_initfn; - sc->destroy = scsi_destroy; + sc->realize = scsi_generic_realize; sc->alloc_req = scsi_new_request; + sc->parse_cdb = scsi_generic_parse_cdb; dc->fw_name = "disk"; dc->desc = "pass through generic scsi device (/dev/sg*)"; dc->reset = scsi_generic_reset; diff --git a/hw/scsi/spapr_vscsi.c b/hw/scsi/spapr_vscsi.c index d4ada4f335..20b20f0bae 100644 --- a/hw/scsi/spapr_vscsi.c +++ b/hw/scsi/spapr_vscsi.c @@ -77,8 +77,9 @@ typedef struct vscsi_req { SCSIRequest *sreq; uint32_t qtag; /* qemu tag != srp tag */ bool active; - uint32_t data_len; bool writing; + bool dma_error; + uint32_t data_len; uint32_t senselen; uint8_t sense[SCSI_SENSE_BUF_SIZE]; @@ -536,8 +537,8 @@ static void vscsi_transfer_data(SCSIRequest *sreq, uint32_t len) } if (rc < 0) { fprintf(stderr, "VSCSI: RDMA error rc=%d!\n", rc); - vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0); - scsi_req_abort(req->sreq, CHECK_CONDITION); + req->dma_error = true; + scsi_req_cancel(req->sreq); return; } @@ -591,6 +592,12 @@ static void vscsi_request_cancelled(SCSIRequest *sreq) { vscsi_req *req = sreq->hba_private; + if (req->dma_error) { + VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(sreq->bus->qbus.parent); + + vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0); + vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0); + } vscsi_put_req(req); } @@ -598,8 +605,7 @@ static const VMStateDescription vmstate_spapr_vscsi_req = { .name = "spapr_vscsi_req", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_BUFFER(crq.raw, vscsi_req), VMSTATE_BUFFER(iu.srp.reserved, vscsi_req), VMSTATE_UINT32(qtag, vscsi_req), @@ -800,8 +806,9 @@ static int vscsi_queue_cmd(VSCSIState *s, vscsi_req *req) req->sreq = scsi_req_new(sdev, req->qtag, lun, srp->cmd.cdb, req); n = scsi_req_enqueue(req->sreq); - DPRINTF("VSCSI: Queued command tag 0x%x CMD 0x%x LUN %d ret: %d\n", - req->qtag, srp->cmd.cdb[0], lun, n); + DPRINTF("VSCSI: Queued command tag 0x%x CMD 0x%x=%s LUN %d ret: %d\n", + req->qtag, srp->cmd.cdb[0], scsi_command_name(srp->cmd.cdb[0]), + lun, n); if (n) { /* Transfer direction must be set before preprocessing the @@ -1260,8 +1267,7 @@ static const VMStateDescription vmstate_spapr_vscsi = { .name = "spapr_vscsi", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_SPAPR_VIO(vdev, VSCSIState), /* VSCSI state */ /* ???? */ diff --git a/hw/scsi/vhost-scsi.c b/hw/scsi/vhost-scsi.c index 3983a5b464..dcb2bc5a6e 100644 --- a/hw/scsi/vhost-scsi.c +++ b/hw/scsi/vhost-scsi.c @@ -23,16 +23,27 @@ #include "hw/virtio/vhost.h" #include "hw/virtio/virtio-scsi.h" #include "hw/virtio/virtio-bus.h" +#include "hw/virtio/virtio-access.h" + +/* Features supported by host kernel. */ +static const int kernel_feature_bits[] = { + VIRTIO_F_NOTIFY_ON_EMPTY, + VIRTIO_RING_F_INDIRECT_DESC, + VIRTIO_RING_F_EVENT_IDX, + VIRTIO_SCSI_F_HOTPLUG, + VHOST_INVALID_FEATURE_BIT +}; static int vhost_scsi_set_endpoint(VHostSCSI *s) { VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + const VhostOps *vhost_ops = s->dev.vhost_ops; struct vhost_scsi_target backend; int ret; memset(&backend, 0, sizeof(backend)); pstrcpy(backend.vhost_wwpn, sizeof(backend.vhost_wwpn), vs->conf.wwpn); - ret = ioctl(s->dev.control, VHOST_SCSI_SET_ENDPOINT, &backend); + ret = vhost_ops->vhost_call(&s->dev, VHOST_SCSI_SET_ENDPOINT, &backend); if (ret < 0) { return -errno; } @@ -43,10 +54,11 @@ static void vhost_scsi_clear_endpoint(VHostSCSI *s) { VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); struct vhost_scsi_target backend; + const VhostOps *vhost_ops = s->dev.vhost_ops; memset(&backend, 0, sizeof(backend)); pstrcpy(backend.vhost_wwpn, sizeof(backend.vhost_wwpn), vs->conf.wwpn); - ioctl(s->dev.control, VHOST_SCSI_CLEAR_ENDPOINT, &backend); + vhost_ops->vhost_call(&s->dev, VHOST_SCSI_CLEAR_ENDPOINT, &backend); } static int vhost_scsi_start(VHostSCSI *s) @@ -55,13 +67,15 @@ static int vhost_scsi_start(VHostSCSI *s) VirtIODevice *vdev = VIRTIO_DEVICE(s); BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev))); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + const VhostOps *vhost_ops = s->dev.vhost_ops; if (!k->set_guest_notifiers) { error_report("binding does not support guest notifiers"); return -ENOSYS; } - ret = ioctl(s->dev.control, VHOST_SCSI_GET_ABI_VERSION, &abi_version); + ret = vhost_ops->vhost_call(&s->dev, + VHOST_SCSI_GET_ABI_VERSION, &abi_version); if (ret < 0) { return -errno; } @@ -141,21 +155,7 @@ static uint32_t vhost_scsi_get_features(VirtIODevice *vdev, { VHostSCSI *s = VHOST_SCSI(vdev); - /* Clear features not supported by host kernel. */ - if (!(s->dev.features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY))) { - features &= ~(1 << VIRTIO_F_NOTIFY_ON_EMPTY); - } - if (!(s->dev.features & (1 << VIRTIO_RING_F_INDIRECT_DESC))) { - features &= ~(1 << VIRTIO_RING_F_INDIRECT_DESC); - } - if (!(s->dev.features & (1 << VIRTIO_RING_F_EVENT_IDX))) { - features &= ~(1 << VIRTIO_RING_F_EVENT_IDX); - } - if (!(s->dev.features & (1 << VIRTIO_SCSI_F_HOTPLUG))) { - features &= ~(1 << VIRTIO_SCSI_F_HOTPLUG); - } - - return features; + return vhost_get_features(&s->dev, kernel_feature_bits, features); } static void vhost_scsi_set_config(VirtIODevice *vdev, @@ -164,8 +164,8 @@ static void vhost_scsi_set_config(VirtIODevice *vdev, VirtIOSCSIConfig *scsiconf = (VirtIOSCSIConfig *)config; VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(vdev); - if ((uint32_t) ldl_raw(&scsiconf->sense_size) != vs->sense_size || - (uint32_t) ldl_raw(&scsiconf->cdb_size) != vs->cdb_size) { + if ((uint32_t) virtio_ldl_p(vdev, &scsiconf->sense_size) != vs->sense_size || + (uint32_t) virtio_ldl_p(vdev, &scsiconf->cdb_size) != vs->cdb_size) { error_report("vhost-scsi does not support changing the sense data and CDB sizes"); exit(1); } @@ -196,6 +196,10 @@ static void vhost_scsi_set_status(VirtIODevice *vdev, uint8_t val) } } +static void vhost_dummy_handle_output(VirtIODevice *vdev, VirtQueue *vq) +{ +} + static void vhost_scsi_realize(DeviceState *dev, Error **errp) { VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(dev); @@ -215,25 +219,36 @@ static void vhost_scsi_realize(DeviceState *dev, Error **errp) error_setg(errp, "vhost-scsi: unable to parse vhostfd"); return; } + } else { + vhostfd = open("/dev/vhost-scsi", O_RDWR); + if (vhostfd < 0) { + error_setg(errp, "vhost-scsi: open vhost char device failed: %s", + strerror(errno)); + return; + } } - virtio_scsi_common_realize(dev, &err); + virtio_scsi_common_realize(dev, &err, vhost_dummy_handle_output, + vhost_dummy_handle_output, + vhost_dummy_handle_output); if (err != NULL) { error_propagate(errp, err); + close(vhostfd); return; } s->dev.nvqs = VHOST_SCSI_VQ_NUM_FIXED + vs->conf.num_queues; s->dev.vqs = g_new(struct vhost_virtqueue, s->dev.nvqs); s->dev.vq_index = 0; + s->dev.backend_features = 0; - ret = vhost_dev_init(&s->dev, vhostfd, "/dev/vhost-scsi", true); + ret = vhost_dev_init(&s->dev, (void *)(uintptr_t)vhostfd, + VHOST_BACKEND_TYPE_KERNEL, true); if (ret < 0) { error_setg(errp, "vhost-scsi: vhost initialization failed: %s", strerror(-ret)); return; } - s->dev.backend_features = 0; error_setg(&s->migration_blocker, "vhost-scsi does not support migration"); diff --git a/hw/scsi/virtio-scsi-dataplane.c b/hw/scsi/virtio-scsi-dataplane.c new file mode 100644 index 0000000000..03a1e8cfcf --- /dev/null +++ b/hw/scsi/virtio-scsi-dataplane.c @@ -0,0 +1,312 @@ +/* + * Virtio SCSI dataplane + * + * Copyright Red Hat, Inc. 2014 + * + * Authors: + * Fam Zheng <famz@redhat.com> + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#include "hw/virtio/virtio-scsi.h" +#include "qemu/error-report.h" +#include "sysemu/block-backend.h" +#include <hw/scsi/scsi.h> +#include <block/scsi.h> +#include <hw/virtio/virtio-bus.h> +#include "hw/virtio/virtio-access.h" +#include "stdio.h" + +/* Context: QEMU global mutex held */ +void virtio_scsi_set_iothread(VirtIOSCSI *s, IOThread *iothread) +{ + BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s))); + VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + + assert(!s->ctx); + s->ctx = iothread_get_aio_context(vs->conf.iothread); + + /* Don't try if transport does not support notifiers. */ + if (!k->set_guest_notifiers || !k->set_host_notifier) { + fprintf(stderr, "virtio-scsi: Failed to set iothread " + "(transport does not support notifiers)"); + exit(1); + } +} + +static VirtIOSCSIVring *virtio_scsi_vring_init(VirtIOSCSI *s, + VirtQueue *vq, + EventNotifierHandler *handler, + int n) +{ + BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s))); + VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOSCSIVring *r = g_slice_new(VirtIOSCSIVring); + int rc; + + /* Set up virtqueue notify */ + rc = k->set_host_notifier(qbus->parent, n, true); + if (rc != 0) { + fprintf(stderr, "virtio-scsi: Failed to set host notifier (%d)\n", + rc); + s->dataplane_fenced = true; + return NULL; + } + r->host_notifier = *virtio_queue_get_host_notifier(vq); + r->guest_notifier = *virtio_queue_get_guest_notifier(vq); + aio_set_event_notifier(s->ctx, &r->host_notifier, handler); + + r->parent = s; + + if (!vring_setup(&r->vring, VIRTIO_DEVICE(s), n)) { + fprintf(stderr, "virtio-scsi: VRing setup failed\n"); + goto fail_vring; + } + return r; + +fail_vring: + aio_set_event_notifier(s->ctx, &r->host_notifier, NULL); + k->set_host_notifier(qbus->parent, n, false); + g_slice_free(VirtIOSCSIVring, r); + return NULL; +} + +VirtIOSCSIReq *virtio_scsi_pop_req_vring(VirtIOSCSI *s, + VirtIOSCSIVring *vring) +{ + VirtIOSCSIReq *req = virtio_scsi_init_req(s, NULL); + int r; + + req->vring = vring; + r = vring_pop((VirtIODevice *)s, &vring->vring, &req->elem); + if (r < 0) { + virtio_scsi_free_req(req); + req = NULL; + } + return req; +} + +void virtio_scsi_vring_push_notify(VirtIOSCSIReq *req) +{ + VirtIODevice *vdev = VIRTIO_DEVICE(req->vring->parent); + + vring_push(&req->vring->vring, &req->elem, + req->qsgl.size + req->resp_iov.size); + + if (vring_should_notify(vdev, &req->vring->vring)) { + event_notifier_set(&req->vring->guest_notifier); + } +} + +static void virtio_scsi_iothread_handle_ctrl(EventNotifier *notifier) +{ + VirtIOSCSIVring *vring = container_of(notifier, + VirtIOSCSIVring, host_notifier); + VirtIOSCSI *s = VIRTIO_SCSI(vring->parent); + VirtIOSCSIReq *req; + + event_notifier_test_and_clear(notifier); + while ((req = virtio_scsi_pop_req_vring(s, vring))) { + virtio_scsi_handle_ctrl_req(s, req); + } +} + +static void virtio_scsi_iothread_handle_event(EventNotifier *notifier) +{ + VirtIOSCSIVring *vring = container_of(notifier, + VirtIOSCSIVring, host_notifier); + VirtIOSCSI *s = vring->parent; + VirtIODevice *vdev = VIRTIO_DEVICE(s); + + event_notifier_test_and_clear(notifier); + + if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) { + return; + } + + if (s->events_dropped) { + virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0); + } +} + +static void virtio_scsi_iothread_handle_cmd(EventNotifier *notifier) +{ + VirtIOSCSIVring *vring = container_of(notifier, + VirtIOSCSIVring, host_notifier); + VirtIOSCSI *s = (VirtIOSCSI *)vring->parent; + VirtIOSCSIReq *req, *next; + QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs); + + event_notifier_test_and_clear(notifier); + while ((req = virtio_scsi_pop_req_vring(s, vring))) { + if (virtio_scsi_handle_cmd_req_prepare(s, req)) { + QTAILQ_INSERT_TAIL(&reqs, req, next); + } + } + + QTAILQ_FOREACH_SAFE(req, &reqs, next, next) { + virtio_scsi_handle_cmd_req_submit(s, req); + } +} + +/* assumes s->ctx held */ +static void virtio_scsi_clear_aio(VirtIOSCSI *s) +{ + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + int i; + + if (s->ctrl_vring) { + aio_set_event_notifier(s->ctx, &s->ctrl_vring->host_notifier, NULL); + } + if (s->event_vring) { + aio_set_event_notifier(s->ctx, &s->event_vring->host_notifier, NULL); + } + if (s->cmd_vrings) { + for (i = 0; i < vs->conf.num_queues && s->cmd_vrings[i]; i++) { + aio_set_event_notifier(s->ctx, &s->cmd_vrings[i]->host_notifier, NULL); + } + } +} + +static void virtio_scsi_vring_teardown(VirtIOSCSI *s) +{ + VirtIODevice *vdev = VIRTIO_DEVICE(s); + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + int i; + + if (s->ctrl_vring) { + vring_teardown(&s->ctrl_vring->vring, vdev, 0); + } + if (s->event_vring) { + vring_teardown(&s->event_vring->vring, vdev, 1); + } + if (s->cmd_vrings) { + for (i = 0; i < vs->conf.num_queues && s->cmd_vrings[i]; i++) { + vring_teardown(&s->cmd_vrings[i]->vring, vdev, 2 + i); + } + free(s->cmd_vrings); + s->cmd_vrings = NULL; + } +} + +/* Context: QEMU global mutex held */ +void virtio_scsi_dataplane_start(VirtIOSCSI *s) +{ + int i; + int rc; + BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s))); + VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + + if (s->dataplane_started || + s->dataplane_starting || + s->dataplane_fenced || + s->ctx != iothread_get_aio_context(vs->conf.iothread)) { + return; + } + + s->dataplane_starting = true; + + assert(!s->blocker); + error_setg(&s->blocker, "block device is in use by data plane"); + /* Set up guest notifier (irq) */ + rc = k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, true); + if (rc != 0) { + fprintf(stderr, "virtio-scsi: Failed to set guest notifiers (%d), " + "ensure -enable-kvm is set\n", rc); + s->dataplane_fenced = true; + goto fail_guest_notifiers; + } + + aio_context_acquire(s->ctx); + s->ctrl_vring = virtio_scsi_vring_init(s, vs->ctrl_vq, + virtio_scsi_iothread_handle_ctrl, + 0); + if (!s->ctrl_vring) { + goto fail_vrings; + } + s->event_vring = virtio_scsi_vring_init(s, vs->event_vq, + virtio_scsi_iothread_handle_event, + 1); + if (!s->event_vring) { + goto fail_vrings; + } + s->cmd_vrings = g_new(VirtIOSCSIVring *, vs->conf.num_queues); + for (i = 0; i < vs->conf.num_queues; i++) { + s->cmd_vrings[i] = + virtio_scsi_vring_init(s, vs->cmd_vqs[i], + virtio_scsi_iothread_handle_cmd, + i + 2); + if (!s->cmd_vrings[i]) { + goto fail_vrings; + } + } + + s->dataplane_starting = false; + s->dataplane_started = true; + aio_context_release(s->ctx); + return; + +fail_vrings: + virtio_scsi_clear_aio(s); + aio_context_release(s->ctx); + virtio_scsi_vring_teardown(s); + for (i = 0; i < vs->conf.num_queues + 2; i++) { + k->set_host_notifier(qbus->parent, i, false); + } + k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, false); +fail_guest_notifiers: + s->dataplane_starting = false; +} + +/* Context: QEMU global mutex held */ +void virtio_scsi_dataplane_stop(VirtIOSCSI *s) +{ + BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s))); + VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + int i; + + /* Better luck next time. */ + if (s->dataplane_fenced) { + s->dataplane_fenced = false; + return; + } + if (!s->dataplane_started || s->dataplane_stopping) { + return; + } + error_free(s->blocker); + s->blocker = NULL; + s->dataplane_stopping = true; + assert(s->ctx == iothread_get_aio_context(vs->conf.iothread)); + + aio_context_acquire(s->ctx); + + aio_set_event_notifier(s->ctx, &s->ctrl_vring->host_notifier, NULL); + aio_set_event_notifier(s->ctx, &s->event_vring->host_notifier, NULL); + for (i = 0; i < vs->conf.num_queues; i++) { + aio_set_event_notifier(s->ctx, &s->cmd_vrings[i]->host_notifier, NULL); + } + + blk_drain_all(); /* ensure there are no in-flight requests */ + + aio_context_release(s->ctx); + + /* Sync vring state back to virtqueue so that non-dataplane request + * processing can continue when we disable the host notifier below. + */ + virtio_scsi_vring_teardown(s); + + for (i = 0; i < vs->conf.num_queues + 2; i++) { + k->set_host_notifier(qbus->parent, i, false); + } + + /* Clean up guest notifier (irq) */ + k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, false); + s->dataplane_stopping = false; + s->dataplane_started = false; +} diff --git a/hw/scsi/virtio-scsi.c b/hw/scsi/virtio-scsi.c index b0d7517cb1..ef485508b1 100644 --- a/hw/scsi/virtio-scsi.c +++ b/hw/scsi/virtio-scsi.c @@ -15,30 +15,13 @@ #include "hw/virtio/virtio-scsi.h" #include "qemu/error-report.h" +#include "qemu/iov.h" +#include "sysemu/block-backend.h" #include <hw/scsi/scsi.h> #include <block/scsi.h> #include <hw/virtio/virtio-bus.h> - -typedef struct VirtIOSCSIReq { - VirtIOSCSI *dev; - VirtQueue *vq; - VirtQueueElement elem; - QEMUSGList qsgl; - SCSIRequest *sreq; - union { - char *buf; - VirtIOSCSICmdReq *cmd; - VirtIOSCSICtrlTMFReq *tmf; - VirtIOSCSICtrlANReq *an; - } req; - union { - char *buf; - VirtIOSCSICmdResp *cmd; - VirtIOSCSICtrlTMFResp *tmf; - VirtIOSCSICtrlANResp *an; - VirtIOSCSIEvent *event; - } resp; -} VirtIOSCSIReq; +#include "hw/virtio/virtio-access.h" +#include "migration/migration.h" static inline int virtio_scsi_get_lun(uint8_t *lun) { @@ -56,19 +39,51 @@ static inline SCSIDevice *virtio_scsi_device_find(VirtIOSCSI *s, uint8_t *lun) return scsi_device_find(&s->bus, 0, lun[1], virtio_scsi_get_lun(lun)); } +VirtIOSCSIReq *virtio_scsi_init_req(VirtIOSCSI *s, VirtQueue *vq) +{ + VirtIOSCSIReq *req; + VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s; + const size_t zero_skip = offsetof(VirtIOSCSIReq, elem) + + sizeof(VirtQueueElement); + + req = g_slice_alloc(sizeof(*req) + vs->cdb_size); + req->vq = vq; + req->dev = s; + qemu_sglist_init(&req->qsgl, DEVICE(s), 8, &address_space_memory); + qemu_iovec_init(&req->resp_iov, 1); + memset((uint8_t *)req + zero_skip, 0, sizeof(*req) - zero_skip); + return req; +} + +void virtio_scsi_free_req(VirtIOSCSIReq *req) +{ + VirtIOSCSICommon *vs = (VirtIOSCSICommon *)req->dev; + + qemu_iovec_destroy(&req->resp_iov); + qemu_sglist_destroy(&req->qsgl); + g_slice_free1(sizeof(*req) + vs->cdb_size, req); +} + static void virtio_scsi_complete_req(VirtIOSCSIReq *req) { VirtIOSCSI *s = req->dev; VirtQueue *vq = req->vq; VirtIODevice *vdev = VIRTIO_DEVICE(s); - virtqueue_push(vq, &req->elem, req->qsgl.size + req->elem.in_sg[0].iov_len); - qemu_sglist_destroy(&req->qsgl); + + qemu_iovec_from_buf(&req->resp_iov, 0, &req->resp, req->resp_size); + if (req->vring) { + assert(req->vq == NULL); + virtio_scsi_vring_push_notify(req); + } else { + virtqueue_push(vq, &req->elem, req->qsgl.size + req->resp_iov.size); + virtio_notify(vdev, vq); + } + if (req->sreq) { req->sreq->hba_private = NULL; scsi_req_unref(req->sreq); } - g_free(req); - virtio_notify(vdev, vq); + virtio_scsi_free_req(req); } static void virtio_scsi_bad_req(void) @@ -77,50 +92,90 @@ static void virtio_scsi_bad_req(void) exit(1); } -static void qemu_sgl_init_external(VirtIOSCSIReq *req, struct iovec *sg, - hwaddr *addr, int num) +static size_t qemu_sgl_concat(VirtIOSCSIReq *req, struct iovec *iov, + hwaddr *addr, int num, size_t skip) { QEMUSGList *qsgl = &req->qsgl; - - qemu_sglist_init(qsgl, DEVICE(req->dev), num, &address_space_memory); - while (num--) { - qemu_sglist_add(qsgl, *(addr++), (sg++)->iov_len); + size_t copied = 0; + + while (num) { + if (skip >= iov->iov_len) { + skip -= iov->iov_len; + } else { + qemu_sglist_add(qsgl, *addr + skip, iov->iov_len - skip); + copied += iov->iov_len - skip; + skip = 0; + } + iov++; + addr++; + num--; } + + assert(skip == 0); + return copied; } -static void virtio_scsi_parse_req(VirtIOSCSI *s, VirtQueue *vq, - VirtIOSCSIReq *req) +static int virtio_scsi_parse_req(VirtIOSCSIReq *req, + unsigned req_size, unsigned resp_size) { - assert(req->elem.in_num); - req->vq = vq; - req->dev = s; - req->sreq = NULL; - if (req->elem.out_num) { - req->req.buf = req->elem.out_sg[0].iov_base; + VirtIODevice *vdev = (VirtIODevice *) req->dev; + size_t in_size, out_size; + + if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0, + &req->req, req_size) < req_size) { + return -EINVAL; } - req->resp.buf = req->elem.in_sg[0].iov_base; - if (req->elem.out_num > 1) { - qemu_sgl_init_external(req, &req->elem.out_sg[1], - &req->elem.out_addr[1], - req->elem.out_num - 1); - } else { - qemu_sgl_init_external(req, &req->elem.in_sg[1], - &req->elem.in_addr[1], - req->elem.in_num - 1); + if (qemu_iovec_concat_iov(&req->resp_iov, + req->elem.in_sg, req->elem.in_num, 0, + resp_size) < resp_size) { + return -EINVAL; } + + req->resp_size = resp_size; + + /* Old BIOSes left some padding by mistake after the req_size/resp_size. + * As a workaround, always consider the first buffer as the virtio-scsi + * request/response, making the payload start at the second element + * of the iovec. + * + * The actual length of the response header, stored in req->resp_size, + * does not change. + * + * TODO: always disable this workaround for virtio 1.0 devices. + */ + if ((vdev->guest_features & VIRTIO_F_ANY_LAYOUT) == 0) { + req_size = req->elem.out_sg[0].iov_len; + resp_size = req->elem.in_sg[0].iov_len; + } + + out_size = qemu_sgl_concat(req, req->elem.out_sg, + &req->elem.out_addr[0], req->elem.out_num, + req_size); + in_size = qemu_sgl_concat(req, req->elem.in_sg, + &req->elem.in_addr[0], req->elem.in_num, + resp_size); + + if (out_size && in_size) { + return -ENOTSUP; + } + + if (out_size) { + req->mode = SCSI_XFER_TO_DEV; + } else if (in_size) { + req->mode = SCSI_XFER_FROM_DEV; + } + + return 0; } static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq) { - VirtIOSCSIReq *req; - req = g_malloc(sizeof(*req)); + VirtIOSCSIReq *req = virtio_scsi_init_req(s, vq); if (!virtqueue_pop(vq, &req->elem)) { - g_free(req); + virtio_scsi_free_req(req); return NULL; } - - virtio_scsi_parse_req(s, vq, req); return req; } @@ -143,45 +198,83 @@ static void *virtio_scsi_load_request(QEMUFile *f, SCSIRequest *sreq) VirtIOSCSIReq *req; uint32_t n; - req = g_malloc(sizeof(*req)); qemu_get_be32s(f, &n); assert(n < vs->conf.num_queues); + req = virtio_scsi_init_req(s, vs->cmd_vqs[n]); qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem)); - virtio_scsi_parse_req(s, vs->cmd_vqs[n], req); + /* TODO: add a way for SCSIBusInfo's load_request to fail, + * and fail migration instead of asserting here. + * When we do, we might be able to re-enable NDEBUG below. + */ +#ifdef NDEBUG +#error building with NDEBUG is not supported +#endif + assert(req->elem.in_num <= ARRAY_SIZE(req->elem.in_sg)); + assert(req->elem.out_num <= ARRAY_SIZE(req->elem.out_sg)); + + if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size, + sizeof(VirtIOSCSICmdResp) + vs->sense_size) < 0) { + error_report("invalid SCSI request migration data"); + exit(1); + } scsi_req_ref(sreq); req->sreq = sreq; if (req->sreq->cmd.mode != SCSI_XFER_NONE) { - int req_mode = - (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV); - - assert(req->sreq->cmd.mode == req_mode); + assert(req->sreq->cmd.mode == req->mode); } return req; } -static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) +typedef struct { + Notifier notifier; + VirtIOSCSIReq *tmf_req; +} VirtIOSCSICancelNotifier; + +static void virtio_scsi_cancel_notify(Notifier *notifier, void *data) +{ + VirtIOSCSICancelNotifier *n = container_of(notifier, + VirtIOSCSICancelNotifier, + notifier); + + if (--n->tmf_req->remaining == 0) { + virtio_scsi_complete_req(n->tmf_req); + } + g_slice_free(VirtIOSCSICancelNotifier, n); +} + +/* Return 0 if the request is ready to be completed and return to guest; + * -EINPROGRESS if the request is submitted and will be completed later, in the + * case of async cancellation. */ +static int virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) { - SCSIDevice *d = virtio_scsi_device_find(s, req->req.tmf->lun); + SCSIDevice *d = virtio_scsi_device_find(s, req->req.tmf.lun); SCSIRequest *r, *next; BusChild *kid; int target; + int ret = 0; + if (s->dataplane_started && blk_get_aio_context(d->conf.blk) != s->ctx) { + aio_context_acquire(s->ctx); + blk_set_aio_context(d->conf.blk, s->ctx); + aio_context_release(s->ctx); + } /* Here VIRTIO_SCSI_S_OK means "FUNCTION COMPLETE". */ - req->resp.tmf->response = VIRTIO_SCSI_S_OK; + req->resp.tmf.response = VIRTIO_SCSI_S_OK; - switch (req->req.tmf->subtype) { + virtio_tswap32s(VIRTIO_DEVICE(s), &req->req.tmf.subtype); + switch (req->req.tmf.subtype) { case VIRTIO_SCSI_T_TMF_ABORT_TASK: case VIRTIO_SCSI_T_TMF_QUERY_TASK: if (!d) { goto fail; } - if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) { + if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) { goto incorrect_lun; } QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) { VirtIOSCSIReq *cmd_req = r->hba_private; - if (cmd_req && cmd_req->req.cmd->tag == req->req.tmf->tag) { + if (cmd_req && cmd_req->req.cmd.tag == req->req.tmf.tag) { break; } } @@ -191,13 +284,20 @@ static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) * check for it in the loop above. */ assert(r->hba_private); - if (req->req.tmf->subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) { + if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) { /* "If the specified command is present in the task set, then * return a service response set to FUNCTION SUCCEEDED". */ - req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED; + req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED; } else { - scsi_req_cancel(r); + VirtIOSCSICancelNotifier *notifier; + + req->remaining = 1; + notifier = g_slice_new(VirtIOSCSICancelNotifier); + notifier->tmf_req = req; + notifier->notifier.notify = virtio_scsi_cancel_notify; + scsi_req_cancel_async(r, ¬ifier->notifier); + ret = -EINPROGRESS; } } break; @@ -206,7 +306,7 @@ static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) if (!d) { goto fail; } - if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) { + if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) { goto incorrect_lun; } s->resetting++; @@ -220,26 +320,42 @@ static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) if (!d) { goto fail; } - if (d->lun != virtio_scsi_get_lun(req->req.tmf->lun)) { + if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) { goto incorrect_lun; } + + /* Add 1 to "remaining" until virtio_scsi_do_tmf returns. + * This way, if the bus starts calling back to the notifiers + * even before we finish the loop, virtio_scsi_cancel_notify + * will not complete the TMF too early. + */ + req->remaining = 1; QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) { if (r->hba_private) { - if (req->req.tmf->subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK_SET) { + if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK_SET) { /* "If there is any command present in the task set, then * return a service response set to FUNCTION SUCCEEDED". */ - req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED; + req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED; break; } else { - scsi_req_cancel(r); + VirtIOSCSICancelNotifier *notifier; + + req->remaining++; + notifier = g_slice_new(VirtIOSCSICancelNotifier); + notifier->notifier.notify = virtio_scsi_cancel_notify; + notifier->tmf_req = req; + scsi_req_cancel_async(r, ¬ifier->notifier); } } } + if (--req->remaining > 0) { + ret = -EINPROGRESS; + } break; case VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET: - target = req->req.tmf->lun[1]; + target = req->req.tmf.lun[1]; s->resetting++; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { d = DO_UPCAST(SCSIDevice, qdev, kid->child); @@ -252,77 +368,125 @@ static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req) case VIRTIO_SCSI_T_TMF_CLEAR_ACA: default: - req->resp.tmf->response = VIRTIO_SCSI_S_FUNCTION_REJECTED; + req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_REJECTED; break; } - return; + return ret; incorrect_lun: - req->resp.tmf->response = VIRTIO_SCSI_S_INCORRECT_LUN; - return; + req->resp.tmf.response = VIRTIO_SCSI_S_INCORRECT_LUN; + return ret; fail: - req->resp.tmf->response = VIRTIO_SCSI_S_BAD_TARGET; + req->resp.tmf.response = VIRTIO_SCSI_S_BAD_TARGET; + return ret; } -static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) +void virtio_scsi_handle_ctrl_req(VirtIOSCSI *s, VirtIOSCSIReq *req) { - VirtIOSCSI *s = (VirtIOSCSI *)vdev; - VirtIOSCSIReq *req; + VirtIODevice *vdev = (VirtIODevice *)s; + uint32_t type; + int r = 0; - while ((req = virtio_scsi_pop_req(s, vq))) { - int out_size, in_size; - if (req->elem.out_num < 1 || req->elem.in_num < 1) { + if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0, + &type, sizeof(type)) < sizeof(type)) { + virtio_scsi_bad_req(); + return; + } + + virtio_tswap32s(vdev, &type); + if (type == VIRTIO_SCSI_T_TMF) { + if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq), + sizeof(VirtIOSCSICtrlTMFResp)) < 0) { virtio_scsi_bad_req(); - continue; + } else { + r = virtio_scsi_do_tmf(s, req); } - out_size = req->elem.out_sg[0].iov_len; - in_size = req->elem.in_sg[0].iov_len; - if (req->req.tmf->type == VIRTIO_SCSI_T_TMF) { - if (out_size < sizeof(VirtIOSCSICtrlTMFReq) || - in_size < sizeof(VirtIOSCSICtrlTMFResp)) { - virtio_scsi_bad_req(); - } - virtio_scsi_do_tmf(s, req); - - } else if (req->req.tmf->type == VIRTIO_SCSI_T_AN_QUERY || - req->req.tmf->type == VIRTIO_SCSI_T_AN_SUBSCRIBE) { - if (out_size < sizeof(VirtIOSCSICtrlANReq) || - in_size < sizeof(VirtIOSCSICtrlANResp)) { - virtio_scsi_bad_req(); - } - req->resp.an->event_actual = 0; - req->resp.an->response = VIRTIO_SCSI_S_OK; + } else if (type == VIRTIO_SCSI_T_AN_QUERY || + type == VIRTIO_SCSI_T_AN_SUBSCRIBE) { + if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq), + sizeof(VirtIOSCSICtrlANResp)) < 0) { + virtio_scsi_bad_req(); + } else { + req->resp.an.event_actual = 0; + req->resp.an.response = VIRTIO_SCSI_S_OK; } + } + if (r == 0) { virtio_scsi_complete_req(req); + } else { + assert(r == -EINPROGRESS); } } +static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) +{ + VirtIOSCSI *s = (VirtIOSCSI *)vdev; + VirtIOSCSIReq *req; + + if (s->ctx && !s->dataplane_disabled) { + virtio_scsi_dataplane_start(s); + return; + } + while ((req = virtio_scsi_pop_req(s, vq))) { + virtio_scsi_handle_ctrl_req(s, req); + } +} + +static void virtio_scsi_complete_cmd_req(VirtIOSCSIReq *req) +{ + /* Sense data is not in req->resp and is copied separately + * in virtio_scsi_command_complete. + */ + req->resp_size = sizeof(VirtIOSCSICmdResp); + virtio_scsi_complete_req(req); +} + static void virtio_scsi_command_complete(SCSIRequest *r, uint32_t status, size_t resid) { VirtIOSCSIReq *req = r->hba_private; - VirtIOSCSI *s = req->dev; - VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); + uint8_t sense[SCSI_SENSE_BUF_SIZE]; uint32_t sense_len; + VirtIODevice *vdev = VIRTIO_DEVICE(req->dev); if (r->io_canceled) { return; } - req->resp.cmd->response = VIRTIO_SCSI_S_OK; - req->resp.cmd->status = status; - if (req->resp.cmd->status == GOOD) { - req->resp.cmd->resid = tswap32(resid); + req->resp.cmd.response = VIRTIO_SCSI_S_OK; + req->resp.cmd.status = status; + if (req->resp.cmd.status == GOOD) { + req->resp.cmd.resid = virtio_tswap32(vdev, resid); } else { - req->resp.cmd->resid = 0; - sense_len = scsi_req_get_sense(r, req->resp.cmd->sense, - vs->sense_size); - req->resp.cmd->sense_len = tswap32(sense_len); + req->resp.cmd.resid = 0; + sense_len = scsi_req_get_sense(r, sense, sizeof(sense)); + sense_len = MIN(sense_len, req->resp_iov.size - sizeof(req->resp.cmd)); + qemu_iovec_from_buf(&req->resp_iov, sizeof(req->resp.cmd), + sense, sense_len); + req->resp.cmd.sense_len = virtio_tswap32(vdev, sense_len); } - virtio_scsi_complete_req(req); + virtio_scsi_complete_cmd_req(req); +} + +static int virtio_scsi_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, + uint8_t *buf, void *hba_private) +{ + VirtIOSCSIReq *req = hba_private; + + if (cmd->len == 0) { + cmd->len = MIN(VIRTIO_SCSI_CDB_SIZE, SCSI_CMD_BUF_SIZE); + memcpy(cmd->buf, buf, cmd->len); + } + + /* Extract the direction and mode directly from the request, for + * host device passthrough. + */ + cmd->xfer = req->qsgl.size; + cmd->mode = req->mode; + return 0; } static QEMUSGList *virtio_scsi_get_sg_list(SCSIRequest *r) @@ -340,74 +504,93 @@ static void virtio_scsi_request_cancelled(SCSIRequest *r) return; } if (req->dev->resetting) { - req->resp.cmd->response = VIRTIO_SCSI_S_RESET; + req->resp.cmd.response = VIRTIO_SCSI_S_RESET; } else { - req->resp.cmd->response = VIRTIO_SCSI_S_ABORTED; + req->resp.cmd.response = VIRTIO_SCSI_S_ABORTED; } - virtio_scsi_complete_req(req); + virtio_scsi_complete_cmd_req(req); } static void virtio_scsi_fail_cmd_req(VirtIOSCSIReq *req) { - req->resp.cmd->response = VIRTIO_SCSI_S_FAILURE; - virtio_scsi_complete_req(req); + req->resp.cmd.response = VIRTIO_SCSI_S_FAILURE; + virtio_scsi_complete_cmd_req(req); } -static void virtio_scsi_handle_cmd(VirtIODevice *vdev, VirtQueue *vq) +bool virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req) { - /* use non-QOM casts in the data path */ - VirtIOSCSI *s = (VirtIOSCSI *)vdev; VirtIOSCSICommon *vs = &s->parent_obj; + SCSIDevice *d; + int rc; - VirtIOSCSIReq *req; - int n; - - while ((req = virtio_scsi_pop_req(s, vq))) { - SCSIDevice *d; - int out_size, in_size; - if (req->elem.out_num < 1 || req->elem.in_num < 1) { + rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size, + sizeof(VirtIOSCSICmdResp) + vs->sense_size); + if (rc < 0) { + if (rc == -ENOTSUP) { + virtio_scsi_fail_cmd_req(req); + } else { virtio_scsi_bad_req(); } + return false; + } - out_size = req->elem.out_sg[0].iov_len; - in_size = req->elem.in_sg[0].iov_len; - if (out_size < sizeof(VirtIOSCSICmdReq) + vs->cdb_size || - in_size < sizeof(VirtIOSCSICmdResp) + vs->sense_size) { - virtio_scsi_bad_req(); - } + d = virtio_scsi_device_find(s, req->req.cmd.lun); + if (!d) { + req->resp.cmd.response = VIRTIO_SCSI_S_BAD_TARGET; + virtio_scsi_complete_cmd_req(req); + return false; + } + if (s->dataplane_started && blk_get_aio_context(d->conf.blk) != s->ctx) { + aio_context_acquire(s->ctx); + blk_set_aio_context(d->conf.blk, s->ctx); + aio_context_release(s->ctx); + } + req->sreq = scsi_req_new(d, req->req.cmd.tag, + virtio_scsi_get_lun(req->req.cmd.lun), + req->req.cdb, req); + + if (req->sreq->cmd.mode != SCSI_XFER_NONE + && (req->sreq->cmd.mode != req->mode || + req->sreq->cmd.xfer > req->qsgl.size)) { + req->resp.cmd.response = VIRTIO_SCSI_S_OVERRUN; + virtio_scsi_complete_cmd_req(req); + return false; + } + scsi_req_ref(req->sreq); + blk_io_plug(d->conf.blk); + return true; +} - if (req->elem.out_num > 1 && req->elem.in_num > 1) { - virtio_scsi_fail_cmd_req(req); - continue; - } +void virtio_scsi_handle_cmd_req_submit(VirtIOSCSI *s, VirtIOSCSIReq *req) +{ + SCSIRequest *sreq = req->sreq; + if (scsi_req_enqueue(sreq)) { + scsi_req_continue(sreq); + } + blk_io_unplug(sreq->dev->conf.blk); + scsi_req_unref(sreq); +} - d = virtio_scsi_device_find(s, req->req.cmd->lun); - if (!d) { - req->resp.cmd->response = VIRTIO_SCSI_S_BAD_TARGET; - virtio_scsi_complete_req(req); - continue; - } - req->sreq = scsi_req_new(d, req->req.cmd->tag, - virtio_scsi_get_lun(req->req.cmd->lun), - req->req.cmd->cdb, req); - - if (req->sreq->cmd.mode != SCSI_XFER_NONE) { - int req_mode = - (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV); - - if (req->sreq->cmd.mode != req_mode || - req->sreq->cmd.xfer > req->qsgl.size) { - req->resp.cmd->response = VIRTIO_SCSI_S_OVERRUN; - virtio_scsi_complete_req(req); - continue; - } - } +static void virtio_scsi_handle_cmd(VirtIODevice *vdev, VirtQueue *vq) +{ + /* use non-QOM casts in the data path */ + VirtIOSCSI *s = (VirtIOSCSI *)vdev; + VirtIOSCSIReq *req, *next; + QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs); - n = scsi_req_enqueue(req->sreq); - if (n) { - scsi_req_continue(req->sreq); + if (s->ctx && !s->dataplane_disabled) { + virtio_scsi_dataplane_start(s); + return; + } + while ((req = virtio_scsi_pop_req(s, vq))) { + if (virtio_scsi_handle_cmd_req_prepare(s, req)) { + QTAILQ_INSERT_TAIL(&reqs, req, next); } } + + QTAILQ_FOREACH_SAFE(req, &reqs, next, next) { + virtio_scsi_handle_cmd_req_submit(s, req); + } } static void virtio_scsi_get_config(VirtIODevice *vdev, @@ -416,16 +599,16 @@ static void virtio_scsi_get_config(VirtIODevice *vdev, VirtIOSCSIConfig *scsiconf = (VirtIOSCSIConfig *)config; VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(vdev); - stl_raw(&scsiconf->num_queues, s->conf.num_queues); - stl_raw(&scsiconf->seg_max, 128 - 2); - stl_raw(&scsiconf->max_sectors, s->conf.max_sectors); - stl_raw(&scsiconf->cmd_per_lun, s->conf.cmd_per_lun); - stl_raw(&scsiconf->event_info_size, sizeof(VirtIOSCSIEvent)); - stl_raw(&scsiconf->sense_size, s->sense_size); - stl_raw(&scsiconf->cdb_size, s->cdb_size); - stw_raw(&scsiconf->max_channel, VIRTIO_SCSI_MAX_CHANNEL); - stw_raw(&scsiconf->max_target, VIRTIO_SCSI_MAX_TARGET); - stl_raw(&scsiconf->max_lun, VIRTIO_SCSI_MAX_LUN); + virtio_stl_p(vdev, &scsiconf->num_queues, s->conf.num_queues); + virtio_stl_p(vdev, &scsiconf->seg_max, 128 - 2); + virtio_stl_p(vdev, &scsiconf->max_sectors, s->conf.max_sectors); + virtio_stl_p(vdev, &scsiconf->cmd_per_lun, s->conf.cmd_per_lun); + virtio_stl_p(vdev, &scsiconf->event_info_size, sizeof(VirtIOSCSIEvent)); + virtio_stl_p(vdev, &scsiconf->sense_size, s->sense_size); + virtio_stl_p(vdev, &scsiconf->cdb_size, s->cdb_size); + virtio_stw_p(vdev, &scsiconf->max_channel, VIRTIO_SCSI_MAX_CHANNEL); + virtio_stw_p(vdev, &scsiconf->max_target, VIRTIO_SCSI_MAX_TARGET); + virtio_stl_p(vdev, &scsiconf->max_lun, VIRTIO_SCSI_MAX_LUN); } static void virtio_scsi_set_config(VirtIODevice *vdev, @@ -434,14 +617,14 @@ static void virtio_scsi_set_config(VirtIODevice *vdev, VirtIOSCSIConfig *scsiconf = (VirtIOSCSIConfig *)config; VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(vdev); - if ((uint32_t) ldl_raw(&scsiconf->sense_size) >= 65536 || - (uint32_t) ldl_raw(&scsiconf->cdb_size) >= 256) { + if ((uint32_t) virtio_ldl_p(vdev, &scsiconf->sense_size) >= 65536 || + (uint32_t) virtio_ldl_p(vdev, &scsiconf->cdb_size) >= 256) { error_report("bad data written to virtio-scsi configuration space"); exit(1); } - vs->sense_size = ldl_raw(&scsiconf->sense_size); - vs->cdb_size = ldl_raw(&scsiconf->cdb_size); + vs->sense_size = virtio_ldl_p(vdev, &scsiconf->sense_size); + vs->cdb_size = virtio_ldl_p(vdev, &scsiconf->cdb_size); } static uint32_t virtio_scsi_get_features(VirtIODevice *vdev, @@ -455,6 +638,9 @@ static void virtio_scsi_reset(VirtIODevice *vdev) VirtIOSCSI *s = VIRTIO_SCSI(vdev); VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(vdev); + if (s->ctx) { + virtio_scsi_dataplane_stop(s); + } s->resetting++; qbus_reset_all(&s->bus.qbus); s->resetting--; @@ -478,33 +664,38 @@ static int virtio_scsi_load(QEMUFile *f, void *opaque, int version_id) VirtIODevice *vdev = VIRTIO_DEVICE(opaque); int ret; - ret = virtio_load(vdev, f); + ret = virtio_load(vdev, f, version_id); if (ret) { return ret; } return 0; } -static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev, - uint32_t event, uint32_t reason) +void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev, + uint32_t event, uint32_t reason) { VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); - VirtIOSCSIReq *req = virtio_scsi_pop_req(s, vs->event_vq); + VirtIOSCSIReq *req; VirtIOSCSIEvent *evt; VirtIODevice *vdev = VIRTIO_DEVICE(s); - int in_size; if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) { return; } - if (!req) { - s->events_dropped = true; - return; + if (s->dataplane_started) { + assert(s->ctx); + aio_context_acquire(s->ctx); } - if (req->elem.out_num || req->elem.in_num != 1) { - virtio_scsi_bad_req(); + if (s->dataplane_started) { + req = virtio_scsi_pop_req_vring(s, s->event_vring); + } else { + req = virtio_scsi_pop_req(s, vs->event_vq); + } + if (!req) { + s->events_dropped = true; + goto out; } if (s->events_dropped) { @@ -512,15 +703,14 @@ static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev, s->events_dropped = false; } - in_size = req->elem.in_sg[0].iov_len; - if (in_size < sizeof(VirtIOSCSIEvent)) { + if (virtio_scsi_parse_req(req, 0, sizeof(VirtIOSCSIEvent))) { virtio_scsi_bad_req(); } - evt = req->resp.event; + evt = &req->resp.event; memset(evt, 0, sizeof(VirtIOSCSIEvent)); - evt->event = event; - evt->reason = reason; + evt->event = virtio_tswap32(vdev, event); + evt->reason = virtio_tswap32(vdev, reason); if (!dev) { assert(event == VIRTIO_SCSI_T_EVENTS_MISSED); } else { @@ -534,12 +724,20 @@ static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev, evt->lun[3] = dev->lun & 0xFF; } virtio_scsi_complete_req(req); +out: + if (s->dataplane_started) { + aio_context_release(s->ctx); + } } static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq) { VirtIOSCSI *s = VIRTIO_SCSI(vdev); + if (s->ctx && !s->dataplane_disabled) { + virtio_scsi_dataplane_start(s); + return; + } if (s->events_dropped) { virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0); } @@ -557,26 +755,44 @@ static void virtio_scsi_change(SCSIBus *bus, SCSIDevice *dev, SCSISense sense) } } -static void virtio_scsi_hotplug(SCSIBus *bus, SCSIDevice *dev) +static void virtio_scsi_hotplug(HotplugHandler *hotplug_dev, DeviceState *dev, + Error **errp) { - VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus); - VirtIODevice *vdev = VIRTIO_DEVICE(s); + VirtIODevice *vdev = VIRTIO_DEVICE(hotplug_dev); + VirtIOSCSI *s = VIRTIO_SCSI(vdev); + SCSIDevice *sd = SCSI_DEVICE(dev); + + if (s->ctx && !s->dataplane_disabled) { + if (blk_op_is_blocked(sd->conf.blk, BLOCK_OP_TYPE_DATAPLANE, errp)) { + return; + } + blk_op_block_all(sd->conf.blk, s->blocker); + } if ((vdev->guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) { - virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET, + virtio_scsi_push_event(s, sd, + VIRTIO_SCSI_T_TRANSPORT_RESET, VIRTIO_SCSI_EVT_RESET_RESCAN); } } -static void virtio_scsi_hot_unplug(SCSIBus *bus, SCSIDevice *dev) +static void virtio_scsi_hotunplug(HotplugHandler *hotplug_dev, DeviceState *dev, + Error **errp) { - VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus); - VirtIODevice *vdev = VIRTIO_DEVICE(s); + VirtIODevice *vdev = VIRTIO_DEVICE(hotplug_dev); + VirtIOSCSI *s = VIRTIO_SCSI(vdev); + SCSIDevice *sd = SCSI_DEVICE(dev); if ((vdev->guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) { - virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET, + virtio_scsi_push_event(s, sd, + VIRTIO_SCSI_T_TRANSPORT_RESET, VIRTIO_SCSI_EVT_RESET_REMOVED); } + + if (s->ctx) { + blk_op_unblock_all(sd->conf.blk, s->blocker); + } + qdev_simple_device_unplug_cb(hotplug_dev, dev, errp); } static struct SCSIBusInfo virtio_scsi_scsi_info = { @@ -588,14 +804,15 @@ static struct SCSIBusInfo virtio_scsi_scsi_info = { .complete = virtio_scsi_command_complete, .cancel = virtio_scsi_request_cancelled, .change = virtio_scsi_change, - .hotplug = virtio_scsi_hotplug, - .hot_unplug = virtio_scsi_hot_unplug, + .parse_cdb = virtio_scsi_parse_cdb, .get_sg_list = virtio_scsi_get_sg_list, .save_request = virtio_scsi_save_request, .load_request = virtio_scsi_load_request, }; -void virtio_scsi_common_realize(DeviceState *dev, Error **errp) +void virtio_scsi_common_realize(DeviceState *dev, Error **errp, + HandleOutput ctrl, HandleOutput evt, + HandleOutput cmd) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(dev); @@ -604,17 +821,54 @@ void virtio_scsi_common_realize(DeviceState *dev, Error **errp) virtio_init(vdev, "virtio-scsi", VIRTIO_ID_SCSI, sizeof(VirtIOSCSIConfig)); + if (s->conf.num_queues == 0 || + s->conf.num_queues > VIRTIO_PCI_QUEUE_MAX - 2) { + error_setg(errp, "Invalid number of queues (= %" PRIu32 "), " + "must be a positive integer less than %d.", + s->conf.num_queues, VIRTIO_PCI_QUEUE_MAX - 2); + virtio_cleanup(vdev); + return; + } s->cmd_vqs = g_malloc0(s->conf.num_queues * sizeof(VirtQueue *)); s->sense_size = VIRTIO_SCSI_SENSE_SIZE; s->cdb_size = VIRTIO_SCSI_CDB_SIZE; s->ctrl_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE, - virtio_scsi_handle_ctrl); + ctrl); s->event_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE, - virtio_scsi_handle_event); + evt); for (i = 0; i < s->conf.num_queues; i++) { s->cmd_vqs[i] = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE, - virtio_scsi_handle_cmd); + cmd); + } + + if (s->conf.iothread) { + virtio_scsi_set_iothread(VIRTIO_SCSI(s), s->conf.iothread); + } +} + +/* Disable dataplane thread during live migration since it does not + * update the dirty memory bitmap yet. + */ +static void virtio_scsi_migration_state_changed(Notifier *notifier, void *data) +{ + VirtIOSCSI *s = container_of(notifier, VirtIOSCSI, + migration_state_notifier); + MigrationState *mig = data; + + if (migration_in_setup(mig)) { + if (!s->dataplane_started) { + return; + } + virtio_scsi_dataplane_stop(s); + s->dataplane_disabled = true; + } else if (migration_has_finished(mig) || + migration_has_failed(mig)) { + if (s->dataplane_started) { + return; + } + blk_drain_all(); /* complete in-flight non-dataplane requests */ + s->dataplane_disabled = false; } } @@ -625,7 +879,9 @@ static void virtio_scsi_device_realize(DeviceState *dev, Error **errp) static int virtio_scsi_id; Error *err = NULL; - virtio_scsi_common_realize(dev, &err); + virtio_scsi_common_realize(dev, &err, virtio_scsi_handle_ctrl, + virtio_scsi_handle_event, + virtio_scsi_handle_cmd); if (err != NULL) { error_propagate(errp, err); return; @@ -633,6 +889,8 @@ static void virtio_scsi_device_realize(DeviceState *dev, Error **errp) scsi_bus_new(&s->bus, sizeof(s->bus), dev, &virtio_scsi_scsi_info, vdev->bus_name); + /* override default SCSI bus hotplug-handler, with virtio-scsi's one */ + qbus_set_hotplug_handler(BUS(&s->bus), dev, &error_abort); if (!dev->hotplugged) { scsi_bus_legacy_handle_cmdline(&s->bus, &err); @@ -644,6 +902,18 @@ static void virtio_scsi_device_realize(DeviceState *dev, Error **errp) register_savevm(dev, "virtio-scsi", virtio_scsi_id++, 1, virtio_scsi_save, virtio_scsi_load, s); + s->migration_state_notifier.notify = virtio_scsi_migration_state_changed; + add_migration_state_change_notifier(&s->migration_state_notifier); +} + +static void virtio_scsi_instance_init(Object *obj) +{ + VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(obj); + + object_property_add_link(obj, "iothread", TYPE_IOTHREAD, + (Object **)&vs->conf.iothread, + qdev_prop_allow_set_link_before_realize, + OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort); } void virtio_scsi_common_unrealize(DeviceState *dev, Error **errp) @@ -660,6 +930,7 @@ static void virtio_scsi_device_unrealize(DeviceState *dev, Error **errp) VirtIOSCSI *s = VIRTIO_SCSI(dev); unregister_savevm(dev, "virtio-scsi", s); + remove_migration_state_change_notifier(&s->migration_state_notifier); virtio_scsi_common_unrealize(dev, errp); } @@ -682,6 +953,7 @@ static void virtio_scsi_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); dc->props = virtio_scsi_properties; set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); @@ -690,6 +962,8 @@ static void virtio_scsi_class_init(ObjectClass *klass, void *data) vdc->set_config = virtio_scsi_set_config; vdc->get_features = virtio_scsi_get_features; vdc->reset = virtio_scsi_reset; + hc->plug = virtio_scsi_hotplug; + hc->unplug = virtio_scsi_hotunplug; } static const TypeInfo virtio_scsi_common_info = { @@ -704,7 +978,12 @@ static const TypeInfo virtio_scsi_info = { .name = TYPE_VIRTIO_SCSI, .parent = TYPE_VIRTIO_SCSI_COMMON, .instance_size = sizeof(VirtIOSCSI), + .instance_init = virtio_scsi_instance_init, .class_init = virtio_scsi_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static void virtio_register_types(void) diff --git a/hw/scsi/vmw_pvscsi.c b/hw/scsi/vmw_pvscsi.c index e35bff76a9..d3a92fbabf 100644 --- a/hw/scsi/vmw_pvscsi.c +++ b/hw/scsi/vmw_pvscsi.c @@ -524,17 +524,20 @@ pvscsi_send_msg(PVSCSIState *s, SCSIDevice *dev, uint32_t msg_type) } static void -pvscsi_hotplug(SCSIBus *bus, SCSIDevice *dev) +pvscsi_hotplug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp) { - PVSCSIState *s = container_of(bus, PVSCSIState, bus); - pvscsi_send_msg(s, dev, PVSCSI_MSG_DEV_ADDED); + PVSCSIState *s = PVSCSI(hotplug_dev); + + pvscsi_send_msg(s, SCSI_DEVICE(dev), PVSCSI_MSG_DEV_ADDED); } static void -pvscsi_hot_unplug(SCSIBus *bus, SCSIDevice *dev) +pvscsi_hot_unplug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp) { - PVSCSIState *s = container_of(bus, PVSCSIState, bus); - pvscsi_send_msg(s, dev, PVSCSI_MSG_DEV_REMOVED); + PVSCSIState *s = PVSCSI(hotplug_dev); + + pvscsi_send_msg(s, SCSI_DEVICE(dev), PVSCSI_MSG_DEV_REMOVED); + qdev_simple_device_unplug_cb(hotplug_dev, dev, errp); } static void @@ -1057,8 +1060,6 @@ static const struct SCSIBusInfo pvscsi_scsi_info = { .get_sg_list = pvscsi_get_sg_list, .complete = pvscsi_command_complete, .cancel = pvscsi_request_cancelled, - .hotplug = pvscsi_hotplug, - .hot_unplug = pvscsi_hot_unplug, }; static int @@ -1087,12 +1088,13 @@ pvscsi_init(PCIDevice *pci_dev) s->completion_worker = qemu_bh_new(pvscsi_process_completion_queue, s); if (!s->completion_worker) { pvscsi_cleanup_msi(s); - memory_region_destroy(&s->io_space); return -ENOMEM; } scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(pci_dev), &pvscsi_scsi_info, NULL); + /* override default SCSI bus hotplug-handler, with pvscsi's one */ + qbus_set_hotplug_handler(BUS(&s->bus), DEVICE(s), &error_abort); pvscsi_reset_state(s); return 0; @@ -1107,8 +1109,6 @@ pvscsi_uninit(PCIDevice *pci_dev) qemu_bh_delete(s->completion_worker); pvscsi_cleanup_msi(s); - - memory_region_destroy(&s->io_space); } static void @@ -1143,10 +1143,9 @@ static const VMStateDescription vmstate_pvscsi = { .name = "pvscsi", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = pvscsi_pre_save, .post_load = pvscsi_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(parent_obj, PVSCSIState), VMSTATE_UINT8(msi_used, PVSCSIState), VMSTATE_UINT32(resetting, PVSCSIState), @@ -1191,6 +1190,7 @@ static void pvscsi_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); k->init = pvscsi_init; k->exit = pvscsi_uninit; @@ -1203,6 +1203,8 @@ static void pvscsi_class_init(ObjectClass *klass, void *data) dc->props = pvscsi_properties; set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); k->config_write = pvscsi_write_config; + hc->unplug = pvscsi_hot_unplug; + hc->plug = pvscsi_hotplug; } static const TypeInfo pvscsi_info = { @@ -1210,6 +1212,10 @@ static const TypeInfo pvscsi_info = { .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(PVSCSIState), .class_init = pvscsi_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static void diff --git a/hw/sd/milkymist-memcard.c b/hw/sd/milkymist-memcard.c index d1168c9e04..9661eafac8 100644 --- a/hw/sd/milkymist-memcard.c +++ b/hw/sd/milkymist-memcard.c @@ -26,6 +26,7 @@ #include "sysemu/sysemu.h" #include "trace.h" #include "qemu/error-report.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/sd.h" @@ -252,14 +253,16 @@ static int milkymist_memcard_init(SysBusDevice *dev) { MilkymistMemcardState *s = MILKYMIST_MEMCARD(dev); DriveInfo *dinfo; + BlockBackend *blk; dinfo = drive_get_next(IF_SD); - s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false); + blk = dinfo ? blk_by_legacy_dinfo(dinfo) : NULL; + s->card = sd_init(blk, false); if (s->card == NULL) { return -1; } - s->enabled = dinfo ? bdrv_is_inserted(dinfo->bdrv) : 0; + s->enabled = blk && blk_is_inserted(blk); memory_region_init_io(&s->regs_region, OBJECT(s), &memcard_mmio_ops, s, "milkymist-memcard", R_MAX * 4); @@ -272,8 +275,7 @@ static const VMStateDescription vmstate_milkymist_memcard = { .name = "milkymist-memcard", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32(command_write_ptr, MilkymistMemcardState), VMSTATE_INT32(response_read_ptr, MilkymistMemcardState), VMSTATE_INT32(response_len, MilkymistMemcardState), diff --git a/hw/sd/omap_mmc.c b/hw/sd/omap_mmc.c index 937a47869a..86c477d720 100644 --- a/hw/sd/omap_mmc.c +++ b/hw/sd/omap_mmc.c @@ -574,7 +574,7 @@ static void omap_mmc_cover_cb(void *opaque, int line, int level) struct omap_mmc_s *omap_mmc_init(hwaddr base, MemoryRegion *sysmem, - BlockDriverState *bd, + BlockBackend *blk, qemu_irq irq, qemu_irq dma[], omap_clk clk) { struct omap_mmc_s *s = (struct omap_mmc_s *) @@ -592,7 +592,7 @@ struct omap_mmc_s *omap_mmc_init(hwaddr base, memory_region_add_subregion(sysmem, base, &s->iomem); /* Instantiate the storage */ - s->card = sd_init(bd, false); + s->card = sd_init(blk, false); if (s->card == NULL) { exit(1); } @@ -601,7 +601,7 @@ struct omap_mmc_s *omap_mmc_init(hwaddr base, } struct omap_mmc_s *omap2_mmc_init(struct omap_target_agent_s *ta, - BlockDriverState *bd, qemu_irq irq, qemu_irq dma[], + BlockBackend *blk, qemu_irq irq, qemu_irq dma[], omap_clk fclk, omap_clk iclk) { struct omap_mmc_s *s = (struct omap_mmc_s *) @@ -620,12 +620,12 @@ struct omap_mmc_s *omap2_mmc_init(struct omap_target_agent_s *ta, omap_l4_attach(ta, 0, &s->iomem); /* Instantiate the storage */ - s->card = sd_init(bd, false); + s->card = sd_init(blk, false); if (s->card == NULL) { exit(1); } - s->cdet = qemu_allocate_irqs(omap_mmc_cover_cb, s, 1)[0]; + s->cdet = qemu_allocate_irq(omap_mmc_cover_cb, s, 0); sd_set_cb(s->card, NULL, s->cdet); return s; diff --git a/hw/sd/pl181.c b/hw/sd/pl181.c index 462558b76d..e704b6e97a 100644 --- a/hw/sd/pl181.c +++ b/hw/sd/pl181.c @@ -7,6 +7,7 @@ * This code is licensed under the GPL. */ +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/sysbus.h" #include "hw/sd.h" @@ -490,7 +491,7 @@ static int pl181_init(SysBusDevice *sbd) sysbus_init_irq(sbd, &s->irq[1]); qdev_init_gpio_out(dev, s->cardstatus, 2); dinfo = drive_get_next(IF_SD); - s->card = sd_init(dinfo ? dinfo->bdrv : NULL, false); + s->card = sd_init(dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, false); if (s->card == NULL) { return -1; } diff --git a/hw/sd/pxa2xx_mmci.c b/hw/sd/pxa2xx_mmci.c index b9d8b1a3e1..ac3ab39bea 100644 --- a/hw/sd/pxa2xx_mmci.c +++ b/hw/sd/pxa2xx_mmci.c @@ -523,7 +523,7 @@ static int pxa2xx_mmci_load(QEMUFile *f, void *opaque, int version_id) PXA2xxMMCIState *pxa2xx_mmci_init(MemoryRegion *sysmem, hwaddr base, - BlockDriverState *bd, qemu_irq irq, + BlockBackend *blk, qemu_irq irq, qemu_irq rx_dma, qemu_irq tx_dma) { PXA2xxMMCIState *s; @@ -538,7 +538,7 @@ PXA2xxMMCIState *pxa2xx_mmci_init(MemoryRegion *sysmem, memory_region_add_subregion(sysmem, base, &s->iomem); /* Instantiate the actual storage */ - s->card = sd_init(bd, false); + s->card = sd_init(blk, false); if (s->card == NULL) { exit(1); } diff --git a/hw/sd/sd.c b/hw/sd/sd.c index 4502ad143d..f955265f74 100644 --- a/hw/sd/sd.c +++ b/hw/sd/sd.c @@ -30,7 +30,7 @@ */ #include "hw/hw.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "hw/sd.h" #include "qemu/bitmap.h" @@ -110,7 +110,7 @@ struct SDState { uint8_t data[512]; qemu_irq readonly_cb; qemu_irq inserted_cb; - BlockDriverState *bdrv; + BlockBackend *blk; uint8_t *buf; bool enable; @@ -151,17 +151,6 @@ static const sd_cmd_type_t sd_cmd_type[64] = { sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, }; -static const sd_cmd_type_t sd_acmd_type[64] = { - sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac, sd_none, - sd_none, sd_none, sd_none, sd_none, sd_none, sd_adtc, sd_none, sd_none, - sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_adtc, sd_ac, - sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, - sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, - sd_none, sd_bcr, sd_ac, sd_none, sd_none, sd_none, sd_none, sd_none, - sd_none, sd_none, sd_none, sd_adtc, sd_none, sd_none, sd_none, sd_none, - sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, -}; - static const int sd_cmd_class[64] = { 0, 0, 0, 0, 0, 9, 10, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, @@ -400,13 +389,13 @@ static inline uint64_t sd_addr_to_wpnum(uint64_t addr) return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT); } -static void sd_reset(SDState *sd, BlockDriverState *bdrv) +static void sd_reset(SDState *sd, BlockBackend *blk) { uint64_t size; uint64_t sect; - if (bdrv) { - bdrv_get_geometry(bdrv, §); + if (blk) { + blk_get_geometry(blk, §); } else { sect = 0; } @@ -423,11 +412,11 @@ static void sd_reset(SDState *sd, BlockDriverState *bdrv) sd_set_cardstatus(sd); sd_set_sdstatus(sd); - sd->bdrv = bdrv; + sd->blk = blk; if (sd->wp_groups) g_free(sd->wp_groups); - sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : false; + sd->wp_switch = blk ? blk_is_read_only(blk) : false; sd->wpgrps_size = sect; sd->wp_groups = bitmap_new(sd->wpgrps_size); memset(sd->function_group, 0, sizeof(sd->function_group)); @@ -443,9 +432,9 @@ static void sd_cardchange(void *opaque, bool load) { SDState *sd = opaque; - qemu_set_irq(sd->inserted_cb, bdrv_is_inserted(sd->bdrv)); - if (bdrv_is_inserted(sd->bdrv)) { - sd_reset(sd, sd->bdrv); + qemu_set_irq(sd->inserted_cb, blk_is_inserted(sd->blk)); + if (blk_is_inserted(sd->blk)) { + sd_reset(sd, sd->blk); qemu_set_irq(sd->readonly_cb, sd->wp_switch); } } @@ -490,23 +479,23 @@ static const VMStateDescription sd_vmstate = { whether card should be in SSI or MMC/SD mode. It is also up to the board to ensure that ssi transfers only occur when the chip select is asserted. */ -SDState *sd_init(BlockDriverState *bs, bool is_spi) +SDState *sd_init(BlockBackend *blk, bool is_spi) { SDState *sd; - if (bs && bdrv_is_read_only(bs)) { + if (blk && blk_is_read_only(blk)) { fprintf(stderr, "sd_init: Cannot use read-only drive\n"); return NULL; } sd = (SDState *) g_malloc0(sizeof(SDState)); - sd->buf = qemu_blockalign(bs, 512); + sd->buf = blk_blockalign(blk, 512); sd->spi = is_spi; sd->enable = true; - sd_reset(sd, bs); - if (sd->bdrv) { - bdrv_attach_dev_nofail(sd->bdrv, sd); - bdrv_set_dev_ops(sd->bdrv, &sd_block_ops, sd); + sd_reset(sd, blk); + if (sd->blk) { + blk_attach_dev_nofail(sd->blk, sd); + blk_set_dev_ops(sd->blk, &sd_block_ops, sd); } vmstate_register(NULL, -1, &sd_vmstate, sd); return sd; @@ -516,8 +505,8 @@ void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert) { sd->readonly_cb = readonly; sd->inserted_cb = insert; - qemu_set_irq(readonly, sd->bdrv ? bdrv_is_read_only(sd->bdrv) : 0); - qemu_set_irq(insert, sd->bdrv ? bdrv_is_inserted(sd->bdrv) : 0); + qemu_set_irq(readonly, sd->blk ? blk_is_read_only(sd->blk) : 0); + qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0); } static void sd_erase(SDState *sd) @@ -691,7 +680,7 @@ static sd_rsp_type_t sd_normal_command(SDState *sd, default: sd->state = sd_idle_state; - sd_reset(sd, sd->bdrv); + sd_reset(sd, sd->blk); return sd->spi ? sd_r1 : sd_r0; } break; @@ -1358,7 +1347,7 @@ int sd_do_command(SDState *sd, SDRequest *req, sd_rsp_type_t rtype; int rsplen; - if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable) { + if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) { return 0; } @@ -1467,7 +1456,7 @@ static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len) DPRINTF("sd_blk_read: addr = 0x%08llx, len = %d\n", (unsigned long long) addr, len); - if (!sd->bdrv || bdrv_read(sd->bdrv, addr >> 9, sd->buf, 1) < 0) { + if (!sd->blk || blk_read(sd->blk, addr >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_read: read error on host side\n"); return; } @@ -1475,7 +1464,7 @@ static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len) if (end > (addr & ~511) + 512) { memcpy(sd->data, sd->buf + (addr & 511), 512 - (addr & 511)); - if (bdrv_read(sd->bdrv, end >> 9, sd->buf, 1) < 0) { + if (blk_read(sd->blk, end >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_read: read error on host side\n"); return; } @@ -1489,29 +1478,29 @@ static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len) uint64_t end = addr + len; if ((addr & 511) || len < 512) - if (!sd->bdrv || bdrv_read(sd->bdrv, addr >> 9, sd->buf, 1) < 0) { + if (!sd->blk || blk_read(sd->blk, addr >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_write: read error on host side\n"); return; } if (end > (addr & ~511) + 512) { memcpy(sd->buf + (addr & 511), sd->data, 512 - (addr & 511)); - if (bdrv_write(sd->bdrv, addr >> 9, sd->buf, 1) < 0) { + if (blk_write(sd->blk, addr >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_write: write error on host side\n"); return; } - if (bdrv_read(sd->bdrv, end >> 9, sd->buf, 1) < 0) { + if (blk_read(sd->blk, end >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_write: read error on host side\n"); return; } memcpy(sd->buf, sd->data + 512 - (addr & 511), end & 511); - if (bdrv_write(sd->bdrv, end >> 9, sd->buf, 1) < 0) { + if (blk_write(sd->blk, end >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_write: write error on host side\n"); } } else { memcpy(sd->buf + (addr & 511), sd->data, len); - if (!sd->bdrv || bdrv_write(sd->bdrv, addr >> 9, sd->buf, 1) < 0) { + if (!sd->blk || blk_write(sd->blk, addr >> 9, sd->buf, 1) < 0) { fprintf(stderr, "sd_blk_write: write error on host side\n"); } } @@ -1526,7 +1515,7 @@ void sd_write_data(SDState *sd, uint8_t value) { int i; - if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable) + if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) return; if (sd->state != sd_receivingdata_state) { @@ -1652,7 +1641,7 @@ uint8_t sd_read_data(SDState *sd) uint8_t ret; int io_len; - if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable) + if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) return 0x00; if (sd->state != sd_sendingdata_state) { diff --git a/hw/sd/sdhci.c b/hw/sd/sdhci.c index 843e697bfe..b38005003c 100644 --- a/hw/sd/sdhci.c +++ b/hw/sd/sdhci.c @@ -23,6 +23,7 @@ */ #include "hw/hw.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "sysemu/dma.h" #include "qemu/timer.h" @@ -702,7 +703,8 @@ static void sdhci_do_adma(SDHCIState *s) length -= block_size - begin; } dma_memory_read(&address_space_memory, dscr.addr, - &s->fifo_buffer[begin], s->data_count); + &s->fifo_buffer[begin], + s->data_count - begin); dscr.addr += s->data_count - begin; if (s->data_count == block_size) { for (n = 0; n < block_size; n++) { @@ -1164,12 +1166,12 @@ static void sdhci_initfn(Object *obj) DriveInfo *di; di = drive_get_next(IF_SD); - s->card = sd_init(di ? di->bdrv : NULL, false); + s->card = sd_init(di ? blk_by_legacy_dinfo(di) : NULL, false); if (s->card == NULL) { exit(1); } - s->eject_cb = qemu_allocate_irqs(sdhci_insert_eject_cb, s, 1)[0]; - s->ro_cb = qemu_allocate_irqs(sdhci_card_readonly_cb, s, 1)[0]; + s->eject_cb = qemu_allocate_irq(sdhci_insert_eject_cb, s, 0); + s->ro_cb = qemu_allocate_irq(sdhci_card_readonly_cb, s, 0); sd_set_cb(s->card, s->ro_cb, s->eject_cb); s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s); @@ -1184,8 +1186,8 @@ static void sdhci_uninitfn(Object *obj) timer_free(s->insert_timer); timer_del(s->transfer_timer); timer_free(s->transfer_timer); - qemu_free_irqs(&s->eject_cb); - qemu_free_irqs(&s->ro_cb); + qemu_free_irq(s->eject_cb); + qemu_free_irq(s->ro_cb); if (s->fifo_buffer) { g_free(s->fifo_buffer); @@ -1197,7 +1199,7 @@ const VMStateDescription sdhci_vmstate = { .name = "sdhci", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(sdmasysad, SDHCIState), VMSTATE_UINT16(blksize, SDHCIState), VMSTATE_UINT16(blkcnt, SDHCIState), diff --git a/hw/sd/ssi-sd.c b/hw/sd/ssi-sd.c index 3273c8a31f..a71fbca714 100644 --- a/hw/sd/ssi-sd.c +++ b/hw/sd/ssi-sd.c @@ -10,6 +10,7 @@ * GNU GPL, version 2 or (at your option) any later version. */ +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" #include "hw/ssi.h" #include "hw/sd.h" @@ -230,8 +231,17 @@ static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id) for (i = 0; i < 5; i++) s->response[i] = qemu_get_be32(f); s->arglen = qemu_get_be32(f); + if (s->mode == SSI_SD_CMDARG && + (s->arglen < 0 || s->arglen >= ARRAY_SIZE(s->cmdarg))) { + return -EINVAL; + } s->response_pos = qemu_get_be32(f); s->stopping = qemu_get_be32(f); + if (s->mode == SSI_SD_RESPONSE && + (s->response_pos < 0 || s->response_pos >= ARRAY_SIZE(s->response) || + (!s->stopping && s->arglen > ARRAY_SIZE(s->response)))) { + return -EINVAL; + } ss->cs = qemu_get_be32(f); @@ -246,7 +256,7 @@ static int ssi_sd_init(SSISlave *d) s->mode = SSI_SD_CMD; dinfo = drive_get_next(IF_SD); - s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true); + s->sd = sd_init(dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, true); if (s->sd == NULL) { return -1; } diff --git a/hw/sh4/r2d.c b/hw/sh4/r2d.c index eaeb7ede4e..12f44d28f0 100644 --- a/hw/sh4/r2d.c +++ b/hw/sh4/r2d.c @@ -36,7 +36,7 @@ #include "hw/loader.h" #include "hw/usb.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #define FLASH_BASE 0x00000000 @@ -219,12 +219,12 @@ static struct QEMU_PACKED char kernel_cmdline[256]; } boot_params; -static void r2d_init(QEMUMachineInitArgs *args) +static void r2d_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; SuperHCPU *cpu; CPUSH4State *env; ResetData *reset_info; @@ -255,7 +255,7 @@ static void r2d_init(QEMUMachineInitArgs *args) qemu_register_reset(main_cpu_reset, reset_info); /* Allocate memory space */ - memory_region_init_ram(sdram, NULL, "r2d.sdram", SDRAM_SIZE); + memory_region_init_ram(sdram, NULL, "r2d.sdram", SDRAM_SIZE, &error_abort); vmstate_register_ram_global(sdram); memory_region_add_subregion(address_space_mem, SDRAM_BASE, sdram); /* Register peripherals */ @@ -290,8 +290,8 @@ static void r2d_init(QEMUMachineInitArgs *args) /* onboard flash memory */ dinfo = drive_get(IF_PFLASH, 0, 0); pflash_cfi02_register(0x0, NULL, "r2d.flash", FLASH_SIZE, - dinfo ? dinfo->bdrv : NULL, (16 * 1024), - FLASH_SIZE >> 16, + dinfo ? blk_by_legacy_dinfo(dinfo) : NULL, + (16 * 1024), FLASH_SIZE >> 16, 1, 4, 0x0000, 0x0000, 0x0000, 0x0000, 0x555, 0x2aa, 0); diff --git a/hw/sh4/sh7750.c b/hw/sh4/sh7750.c index 4a39357529..5dda5de34e 100644 --- a/hw/sh4/sh7750.c +++ b/hw/sh4/sh7750.c @@ -838,6 +838,5 @@ SH7750State *sh7750_init(SuperHCPU *cpu, MemoryRegion *sysmem) qemu_irq sh7750_irl(SH7750State *s) { sh_intc_toggle_source(sh_intc_source(&s->intc, IRL), 1, 0); /* enable */ - return qemu_allocate_irqs(sh_intc_set_irl, sh_intc_source(&s->intc, IRL), - 1)[0]; + return qemu_allocate_irq(sh_intc_set_irl, sh_intc_source(&s->intc, IRL), 0); } diff --git a/hw/sh4/shix.c b/hw/sh4/shix.c index 904a966700..f93f98e568 100644 --- a/hw/sh4/shix.c +++ b/hw/sh4/shix.c @@ -39,9 +39,9 @@ #define BIOS_FILENAME "shix_bios.bin" #define BIOS_ADDRESS 0xA0000000 -static void shix_init(QEMUMachineInitArgs *args) +static void shix_init(MachineState *machine) { - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; int ret; SuperHCPU *cpu; struct SH7750State *s; @@ -59,14 +59,16 @@ static void shix_init(QEMUMachineInitArgs *args) } /* Allocate memory space */ - memory_region_init_ram(rom, NULL, "shix.rom", 0x4000); + memory_region_init_ram(rom, NULL, "shix.rom", 0x4000, &error_abort); vmstate_register_ram_global(rom); memory_region_set_readonly(rom, true); memory_region_add_subregion(sysmem, 0x00000000, rom); - memory_region_init_ram(&sdram[0], NULL, "shix.sdram1", 0x01000000); + memory_region_init_ram(&sdram[0], NULL, "shix.sdram1", 0x01000000, + &error_abort); vmstate_register_ram_global(&sdram[0]); memory_region_add_subregion(sysmem, 0x08000000, &sdram[0]); - memory_region_init_ram(&sdram[1], NULL, "shix.sdram2", 0x01000000); + memory_region_init_ram(&sdram[1], NULL, "shix.sdram2", 0x01000000, + &error_abort); vmstate_register_ram_global(&sdram[1]); memory_region_add_subregion(sysmem, 0x0c000000, &sdram[1]); diff --git a/hw/sparc/leon3.c b/hw/sparc/leon3.c index c16e9e4c81..751392e137 100644 --- a/hw/sparc/leon3.c +++ b/hw/sparc/leon3.c @@ -101,11 +101,11 @@ static void leon3_set_pil_in(void *opaque, uint32_t pil_in) } } -static void leon3_generic_hw_init(QEMUMachineInitArgs *args) +static void leon3_generic_hw_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; SPARCCPU *cpu; CPUSPARCState *env; MemoryRegion *address_space_mem = get_system_memory(); @@ -151,13 +151,13 @@ static void leon3_generic_hw_init(QEMUMachineInitArgs *args) exit(1); } - memory_region_init_ram(ram, NULL, "leon3.ram", ram_size); + memory_region_init_ram(ram, NULL, "leon3.ram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0x40000000, ram); /* Allocate BIOS */ prom_size = 8 * 1024 * 1024; /* 8Mb */ - memory_region_init_ram(prom, NULL, "Leon3.bios", prom_size); + memory_region_init_ram(prom, NULL, "Leon3.bios", prom_size, &error_abort); vmstate_register_ram_global(prom); memory_region_set_readonly(prom, true); memory_region_add_subregion(address_space_mem, 0x00000000, prom); diff --git a/hw/sparc/sun4m.c b/hw/sparc/sun4m.c index 75adb68abc..8273199f11 100644 --- a/hw/sparc/sun4m.c +++ b/hw/sparc/sun4m.c @@ -40,7 +40,7 @@ #include "hw/empty_slot.h" #include "hw/loader.h" #include "elf.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "trace.h" /* @@ -527,7 +527,7 @@ static void apc_init(hwaddr power_base, qemu_irq cpu_halt) sysbus_connect_irq(s, 0, cpu_halt); } -static void tcx_init(hwaddr addr, int vram_size, int width, +static void tcx_init(hwaddr addr, qemu_irq irq, int vram_size, int width, int height, int depth) { DeviceState *dev; @@ -541,25 +541,43 @@ static void tcx_init(hwaddr addr, int vram_size, int width, qdev_prop_set_uint64(dev, "prom_addr", addr); qdev_init_nofail(dev); s = SYS_BUS_DEVICE(dev); - /* FCode ROM */ + + /* 10/ROM : FCode ROM */ sysbus_mmio_map(s, 0, addr); - /* 8-bit plane */ - sysbus_mmio_map(s, 1, addr + 0x00800000ULL); - /* DAC */ - sysbus_mmio_map(s, 2, addr + 0x00200000ULL); - /* TEC (dummy) */ - sysbus_mmio_map(s, 3, addr + 0x00700000ULL); - /* THC 24 bit: NetBSD writes here even with 8-bit display: dummy */ - sysbus_mmio_map(s, 4, addr + 0x00301000ULL); - if (depth == 24) { - /* 24-bit plane */ - sysbus_mmio_map(s, 5, addr + 0x02000000ULL); - /* Control plane */ - sysbus_mmio_map(s, 6, addr + 0x0a000000ULL); + /* 2/STIP : Stipple */ + sysbus_mmio_map(s, 1, addr + 0x04000000ULL); + /* 3/BLIT : Blitter */ + sysbus_mmio_map(s, 2, addr + 0x06000000ULL); + /* 5/RSTIP : Raw Stipple */ + sysbus_mmio_map(s, 3, addr + 0x0c000000ULL); + /* 6/RBLIT : Raw Blitter */ + sysbus_mmio_map(s, 4, addr + 0x0e000000ULL); + /* 7/TEC : Transform Engine */ + sysbus_mmio_map(s, 5, addr + 0x00700000ULL); + /* 8/CMAP : DAC */ + sysbus_mmio_map(s, 6, addr + 0x00200000ULL); + /* 9/THC : */ + if (depth == 8) { + sysbus_mmio_map(s, 7, addr + 0x00300000ULL); } else { - /* THC 8 bit (dummy) */ - sysbus_mmio_map(s, 5, addr + 0x00300000ULL); + sysbus_mmio_map(s, 7, addr + 0x00301000ULL); } + /* 11/DHC : */ + sysbus_mmio_map(s, 8, addr + 0x00240000ULL); + /* 12/ALT : */ + sysbus_mmio_map(s, 9, addr + 0x00280000ULL); + /* 0/DFB8 : 8-bit plane */ + sysbus_mmio_map(s, 10, addr + 0x00800000ULL); + /* 1/DFB24 : 24bit plane */ + sysbus_mmio_map(s, 11, addr + 0x02000000ULL); + /* 4/RDFB32: Raw framebuffer. Control plane */ + sysbus_mmio_map(s, 12, addr + 0x0a000000ULL); + /* 9/THC24bits : NetBSD writes here even with 8-bit display: dummy */ + if (depth == 8) { + sysbus_mmio_map(s, 13, addr + 0x00301000ULL); + } + + sysbus_connect_irq(s, 0, irq); } static void cg3_init(hwaddr addr, qemu_irq irq, int vram_size, int width, @@ -621,7 +639,7 @@ static int idreg_init1(SysBusDevice *dev) IDRegState *s = MACIO_ID_REGISTER(dev); memory_region_init_ram(&s->mem, OBJECT(s), - "sun4m.idreg", sizeof(idreg_data)); + "sun4m.idreg", sizeof(idreg_data), &error_abort); vmstate_register_ram_global(&s->mem); memory_region_set_readonly(&s->mem, true); sysbus_init_mmio(dev, &s->mem); @@ -668,7 +686,7 @@ static int afx_init1(SysBusDevice *dev) { AFXState *s = TCX_AFX(dev); - memory_region_init_ram(&s->mem, OBJECT(s), "sun4m.afx", 4); + memory_region_init_ram(&s->mem, OBJECT(s), "sun4m.afx", 4, &error_abort); vmstate_register_ram_global(&s->mem); sysbus_init_mmio(dev, &s->mem); return 0; @@ -742,7 +760,8 @@ static int prom_init1(SysBusDevice *dev) { PROMState *s = OPENPROM(dev); - memory_region_init_ram(&s->prom, OBJECT(s), "sun4m.prom", PROM_SIZE_MAX); + memory_region_init_ram(&s->prom, OBJECT(s), "sun4m.prom", PROM_SIZE_MAX, + &error_abort); vmstate_register_ram_global(&s->prom); memory_region_set_readonly(&s->prom, true); sysbus_init_mmio(dev, &s->prom); @@ -784,7 +803,8 @@ static int ram_init1(SysBusDevice *dev) { RamDevice *d = SUN4M_RAM(dev); - memory_region_init_ram(&d->ram, OBJECT(d), "sun4m.ram", d->size); + memory_region_init_ram(&d->ram, OBJECT(d), "sun4m.ram", d->size, + &error_abort); vmstate_register_ram_global(&d->ram); sysbus_init_mmio(dev, &d->ram); return 0; @@ -867,9 +887,9 @@ static void dummy_fdc_tc(void *opaque, int irq, int level) } static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, - QEMUMachineInitArgs *args) + MachineState *machine) { - const char *cpu_model = args->cpu_model; + const char *cpu_model = machine->cpu_model; unsigned int i; void *iommu, *espdma, *ledma, *nvram; qemu_irq *cpu_irqs[MAX_CPUS], slavio_irq[32], slavio_cpu_irq[MAX_CPUS], @@ -895,10 +915,10 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, /* set up devices */ - ram_init(0, args->ram_size, hwdef->max_mem); + ram_init(0, machine->ram_size, hwdef->max_mem); /* models without ECC don't trap when missing ram is accessed */ if (!hwdef->ecc_base) { - empty_slot_init(args->ram_size, hwdef->max_mem - args->ram_size); + empty_slot_init(machine->ram_size, hwdef->max_mem - machine->ram_size); } prom_init(hwdef->slavio_base, bios_name); @@ -974,8 +994,8 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, exit(1); } - tcx_init(hwdef->tcx_base, 0x00100000, graphic_width, graphic_height, - graphic_depth); + tcx_init(hwdef->tcx_base, slavio_irq[11], 0x00100000, + graphic_width, graphic_height, graphic_depth); } } @@ -1051,14 +1071,14 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, empty_slot_init(hwdef->bpp_base, 0x20); } - kernel_size = sun4m_load_kernel(args->kernel_filename, - args->initrd_filename, - args->ram_size); + kernel_size = sun4m_load_kernel(machine->kernel_filename, + machine->initrd_filename, + machine->ram_size); - nvram_init(nvram, (uint8_t *)&nd_table[0].macaddr, args->kernel_cmdline, - args->boot_order, args->ram_size, kernel_size, graphic_width, - graphic_height, graphic_depth, hwdef->nvram_machine_id, - "Sun4m"); + nvram_init(nvram, (uint8_t *)&nd_table[0].macaddr, machine->kernel_cmdline, + machine->boot_order, machine->ram_size, kernel_size, + graphic_width, graphic_height, graphic_depth, + hwdef->nvram_machine_id, "Sun4m"); if (hwdef->ecc_base) ecc_init(hwdef->ecc_base, slavio_irq[28], @@ -1074,20 +1094,20 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, fw_cfg_add_i16(fw_cfg, FW_CFG_SUN4M_HEIGHT, graphic_height); fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, KERNEL_LOAD_ADDR); fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size); - if (args->kernel_cmdline) { + if (machine->kernel_cmdline) { fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, CMDLINE_ADDR); pstrcpy_targphys("cmdline", CMDLINE_ADDR, TARGET_PAGE_SIZE, - args->kernel_cmdline); - fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, args->kernel_cmdline); + machine->kernel_cmdline); + fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, machine->kernel_cmdline); fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, - strlen(args->kernel_cmdline) + 1); + strlen(machine->kernel_cmdline) + 1); } else { fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0); fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, 0); } fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, INITRD_LOAD_ADDR); fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, 0); // not used - fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, args->boot_order[0]); + fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, machine->boot_order[0]); qemu_register_boot_set(fw_cfg_boot_set, fw_cfg); } @@ -1349,57 +1369,57 @@ static const struct sun4m_hwdef sun4m_hwdefs[] = { }; /* SPARCstation 5 hardware initialisation */ -static void ss5_init(QEMUMachineInitArgs *args) +static void ss5_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[0], args); + sun4m_hw_init(&sun4m_hwdefs[0], machine); } /* SPARCstation 10 hardware initialisation */ -static void ss10_init(QEMUMachineInitArgs *args) +static void ss10_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[1], args); + sun4m_hw_init(&sun4m_hwdefs[1], machine); } /* SPARCserver 600MP hardware initialisation */ -static void ss600mp_init(QEMUMachineInitArgs *args) +static void ss600mp_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[2], args); + sun4m_hw_init(&sun4m_hwdefs[2], machine); } /* SPARCstation 20 hardware initialisation */ -static void ss20_init(QEMUMachineInitArgs *args) +static void ss20_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[3], args); + sun4m_hw_init(&sun4m_hwdefs[3], machine); } /* SPARCstation Voyager hardware initialisation */ -static void vger_init(QEMUMachineInitArgs *args) +static void vger_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[4], args); + sun4m_hw_init(&sun4m_hwdefs[4], machine); } /* SPARCstation LX hardware initialisation */ -static void ss_lx_init(QEMUMachineInitArgs *args) +static void ss_lx_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[5], args); + sun4m_hw_init(&sun4m_hwdefs[5], machine); } /* SPARCstation 4 hardware initialisation */ -static void ss4_init(QEMUMachineInitArgs *args) +static void ss4_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[6], args); + sun4m_hw_init(&sun4m_hwdefs[6], machine); } /* SPARCClassic hardware initialisation */ -static void scls_init(QEMUMachineInitArgs *args) +static void scls_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[7], args); + sun4m_hw_init(&sun4m_hwdefs[7], machine); } /* SPARCbook hardware initialisation */ -static void sbook_init(QEMUMachineInitArgs *args) +static void sbook_init(MachineState *machine) { - sun4m_hw_init(&sun4m_hwdefs[8], args); + sun4m_hw_init(&sun4m_hwdefs[8], machine); } static QEMUMachine ss5_machine = { diff --git a/hw/sparc64/sun4u.c b/hw/sparc64/sun4u.c index 6f271d9cfc..f42112c1b2 100644 --- a/hw/sparc64/sun4u.c +++ b/hw/sparc64/sun4u.c @@ -38,7 +38,7 @@ #include "hw/ide.h" #include "hw/loader.h" #include "elf.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" //#define DEBUG_IRQ @@ -609,8 +609,8 @@ pci_ebus_init1(PCIDevice *pci_dev) 0, 0x1000000); pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar0); memory_region_init_alias(&s->bar1, OBJECT(s), "bar1", get_system_io(), - 0, 0x800000); - pci_register_bar(pci_dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar1); + 0, 0x1000); + pci_register_bar(pci_dev, 1, PCI_BASE_ADDRESS_SPACE_IO, &s->bar1); return 0; } @@ -686,7 +686,8 @@ static int prom_init1(SysBusDevice *dev) { PROMState *s = OPENPROM(dev); - memory_region_init_ram(&s->prom, OBJECT(s), "sun4u.prom", PROM_SIZE_MAX); + memory_region_init_ram(&s->prom, OBJECT(s), "sun4u.prom", PROM_SIZE_MAX, + &error_abort); vmstate_register_ram_global(&s->prom); memory_region_set_readonly(&s->prom, true); sysbus_init_mmio(dev, &s->prom); @@ -729,7 +730,8 @@ static int ram_init1(SysBusDevice *dev) { RamDevice *d = SUN4U_RAM(dev); - memory_region_init_ram(&d->ram, OBJECT(d), "sun4u.ram", d->size); + memory_region_init_ram(&d->ram, OBJECT(d), "sun4u.ram", d->size, + &error_abort); vmstate_register_ram_global(&d->ram); sysbus_init_mmio(dev, &d->ram); return 0; @@ -811,7 +813,7 @@ static SPARCCPU *cpu_devinit(const char *cpu_model, const struct hwdef *hwdef) } static void sun4uv_init(MemoryRegion *address_space_mem, - QEMUMachineInitArgs *args, + MachineState *machine, const struct hwdef *hwdef) { SPARCCPU *cpu; @@ -826,10 +828,10 @@ static void sun4uv_init(MemoryRegion *address_space_mem, FWCfgState *fw_cfg; /* init CPUs */ - cpu = cpu_devinit(args->cpu_model, hwdef); + cpu = cpu_devinit(machine->cpu_model, hwdef); /* set up devices */ - ram_init(0, args->ram_size); + ram_init(0, machine->ram_size); prom_init(hwdef->prom_addr, bios_name); @@ -862,7 +864,7 @@ static void sun4uv_init(MemoryRegion *address_space_mem, for(i = 0; i < nb_nics; i++) pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL); - ide_drive_get(hd, MAX_IDE_BUS); + ide_drive_get(hd, ARRAY_SIZE(hd)); pci_cmd646_ide_init(pci_bus, hd, 1); @@ -875,15 +877,15 @@ static void sun4uv_init(MemoryRegion *address_space_mem, initrd_size = 0; initrd_addr = 0; - kernel_size = sun4u_load_kernel(args->kernel_filename, - args->initrd_filename, + kernel_size = sun4u_load_kernel(machine->kernel_filename, + machine->initrd_filename, ram_size, &initrd_size, &initrd_addr, &kernel_addr, &kernel_entry); - sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", args->ram_size, - args->boot_order, + sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", machine->ram_size, + machine->boot_order, kernel_addr, kernel_size, - args->kernel_cmdline, + machine->kernel_cmdline, initrd_addr, initrd_size, /* XXX: need an option to load a NVRAM image */ 0, @@ -897,16 +899,16 @@ static void sun4uv_init(MemoryRegion *address_space_mem, fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id); fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_entry); fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size); - if (args->kernel_cmdline) { + if (machine->kernel_cmdline) { fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, - strlen(args->kernel_cmdline) + 1); - fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, args->kernel_cmdline); + strlen(machine->kernel_cmdline) + 1); + fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, machine->kernel_cmdline); } else { fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, 0); } fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr); fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size); - fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, args->boot_order[0]); + fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, machine->boot_order[0]); fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_WIDTH, graphic_width); fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_HEIGHT, graphic_height); @@ -946,21 +948,21 @@ static const struct hwdef hwdefs[] = { }; /* Sun4u hardware initialisation */ -static void sun4u_init(QEMUMachineInitArgs *args) +static void sun4u_init(MachineState *machine) { - sun4uv_init(get_system_memory(), args, &hwdefs[0]); + sun4uv_init(get_system_memory(), machine, &hwdefs[0]); } /* Sun4v hardware initialisation */ -static void sun4v_init(QEMUMachineInitArgs *args) +static void sun4v_init(MachineState *machine) { - sun4uv_init(get_system_memory(), args, &hwdefs[1]); + sun4uv_init(get_system_memory(), machine, &hwdefs[1]); } /* Niagara hardware initialisation */ -static void niagara_init(QEMUMachineInitArgs *args) +static void niagara_init(MachineState *machine) { - sun4uv_init(get_system_memory(), args, &hwdefs[2]); + sun4uv_init(get_system_memory(), machine, &hwdefs[2]); } static QEMUMachine sun4u_machine = { diff --git a/hw/ssi/pl022.c b/hw/ssi/pl022.c index fd479effb9..61d568f36e 100644 --- a/hw/ssi/pl022.c +++ b/hw/ssi/pl022.c @@ -240,12 +240,25 @@ static const MemoryRegionOps pl022_ops = { .endianness = DEVICE_NATIVE_ENDIAN, }; +static int pl022_post_load(void *opaque, int version_id) +{ + PL022State *s = opaque; + + if (s->tx_fifo_head < 0 || + s->tx_fifo_head >= ARRAY_SIZE(s->tx_fifo) || + s->rx_fifo_head < 0 || + s->rx_fifo_head >= ARRAY_SIZE(s->rx_fifo)) { + return -1; + } + return 0; +} + static const VMStateDescription vmstate_pl022 = { .name = "pl022_ssp", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .post_load = pl022_post_load, + .fields = (VMStateField[]) { VMSTATE_UINT32(cr0, PL022State), VMSTATE_UINT32(cr1, PL022State), VMSTATE_UINT32(bitmask, PL022State), diff --git a/hw/ssi/ssi.c b/hw/ssi/ssi.c index 017f0221fb..2aab79ba7f 100644 --- a/hw/ssi/ssi.c +++ b/hw/ssi/ssi.c @@ -60,7 +60,7 @@ static int ssi_slave_init(DeviceState *dev) if (ssc->transfer_raw == ssi_transfer_raw_default && ssc->cs_polarity != SSI_CS_NONE) { - qdev_init_gpio_in(dev, ssi_cs_default, 1); + qdev_init_gpio_in_named(dev, ssi_cs_default, SSI_GPIO_CS, 1); } return ssc->init(s); @@ -126,8 +126,7 @@ const VMStateDescription vmstate_ssi_slave = { .name = "SSISlave", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_BOOL(cs, SSISlave), VMSTATE_END_OF_LIST() } @@ -156,7 +155,7 @@ static int ssi_auto_connect_slave(Object *child, void *opaque) return 0; } - cs_line = qdev_get_gpio_in(DEVICE(dev), 0); + cs_line = qdev_get_gpio_in_named(DEVICE(dev), SSI_GPIO_CS, 0); qdev_set_parent_bus(DEVICE(dev), BUS(arg->bus)); **arg->cs_linep = cs_line; (*arg->cs_linep)++; diff --git a/hw/ssi/xilinx_spi.c b/hw/ssi/xilinx_spi.c index d44caae8ad..620573caca 100644 --- a/hw/ssi/xilinx_spi.c +++ b/hw/ssi/xilinx_spi.c @@ -329,7 +329,7 @@ static int xilinx_spi_init(SysBusDevice *sbd) s->spi = ssi_create_bus(dev, "spi"); sysbus_init_irq(sbd, &s->irq); - s->cs_lines = g_new(qemu_irq, s->num_cs); + s->cs_lines = g_new0(qemu_irq, s->num_cs); ssi_auto_connect_slaves(dev, s->cs_lines, s->spi); for (i = 0; i < s->num_cs; ++i) { sysbus_init_irq(sbd, &s->cs_lines[i]); @@ -351,7 +351,6 @@ static const VMStateDescription vmstate_xilinx_spi = { .name = "xilinx_spi", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_FIFO8(tx_fifo, XilinxSPI), VMSTATE_FIFO8(rx_fifo, XilinxSPI), diff --git a/hw/ssi/xilinx_spips.c b/hw/ssi/xilinx_spips.c index 8977243725..0910f5479a 100644 --- a/hw/ssi/xilinx_spips.c +++ b/hw/ssi/xilinx_spips.c @@ -704,7 +704,6 @@ static const VMStateDescription vmstate_xilinx_spips = { .name = "xilinx_spips", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .post_load = xilinx_spips_post_load, .fields = (VMStateField[]) { VMSTATE_FIFO8(tx_fifo, XilinxSPIPS), diff --git a/hw/timer/allwinner-a10-pit.c b/hw/timer/allwinner-a10-pit.c index b27fce8cd2..34124fe3d1 100644 --- a/hw/timer/allwinner-a10-pit.c +++ b/hw/timer/allwinner-a10-pit.c @@ -19,6 +19,15 @@ #include "sysemu/sysemu.h" #include "hw/timer/allwinner-a10-pit.h" +static void a10_pit_update_irq(AwA10PITState *s) +{ + int i; + + for (i = 0; i < AW_A10_PIT_TIMER_NR; i++) { + qemu_set_irq(s->irq[i], !!(s->irq_status & s->irq_enable & (1 << i))); + } +} + static uint64_t a10_pit_read(void *opaque, hwaddr offset, unsigned size) { AwA10PITState *s = AW_A10_PIT(opaque); @@ -65,6 +74,22 @@ static uint64_t a10_pit_read(void *opaque, hwaddr offset, unsigned size) return 0; } +static void a10_pit_set_freq(AwA10PITState *s, int index) +{ + uint32_t prescaler, source, source_freq; + + prescaler = 1 << extract32(s->control[index], 4, 3); + source = extract32(s->control[index], 2, 2); + source_freq = s->clk_freq[source]; + + if (source_freq) { + ptimer_set_freq(s->timer[index], source_freq / prescaler); + } else { + qemu_log_mask(LOG_GUEST_ERROR, "%s: Invalid clock source %u\n", + __func__, source); + } +} + static void a10_pit_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { @@ -74,9 +99,11 @@ static void a10_pit_write(void *opaque, hwaddr offset, uint64_t value, switch (offset) { case AW_A10_PIT_TIMER_IRQ_EN: s->irq_enable = value; + a10_pit_update_irq(s); break; case AW_A10_PIT_TIMER_IRQ_ST: s->irq_status &= ~value; + a10_pit_update_irq(s); break; case AW_A10_PIT_TIMER_BASE ... AW_A10_PIT_TIMER_BASE_END: index = offset & 0xf0; @@ -85,6 +112,7 @@ static void a10_pit_write(void *opaque, hwaddr offset, uint64_t value, switch (offset & 0x0f) { case AW_A10_PIT_TIMER_CONTROL: s->control[index] = value; + a10_pit_set_freq(s, index); if (s->control[index] & AW_A10_PIT_TIMER_RELOAD) { ptimer_set_count(s->timer[index], s->interval[index]); } @@ -150,11 +178,18 @@ static const MemoryRegionOps a10_pit_ops = { .endianness = DEVICE_NATIVE_ENDIAN, }; +static Property a10_pit_properties[] = { + DEFINE_PROP_UINT32("clk0-freq", AwA10PITState, clk_freq[0], 0), + DEFINE_PROP_UINT32("clk1-freq", AwA10PITState, clk_freq[1], 0), + DEFINE_PROP_UINT32("clk2-freq", AwA10PITState, clk_freq[2], 0), + DEFINE_PROP_UINT32("clk3-freq", AwA10PITState, clk_freq[3], 0), + DEFINE_PROP_END_OF_LIST(), +}; + static const VMStateDescription vmstate_a10_pit = { .name = "a10.pit", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(irq_enable, AwA10PITState), VMSTATE_UINT32(irq_status, AwA10PITState), @@ -178,11 +213,14 @@ static void a10_pit_reset(DeviceState *dev) s->irq_enable = 0; s->irq_status = 0; + a10_pit_update_irq(s); + for (i = 0; i < 6; i++) { s->control[i] = AW_A10_PIT_DEFAULT_CLOCK; s->interval[i] = 0; s->count[i] = 0; ptimer_stop(s->timer[i]); + a10_pit_set_freq(s, i); } s->watch_dog_mode = 0; s->watch_dog_control = 0; @@ -193,18 +231,17 @@ static void a10_pit_reset(DeviceState *dev) static void a10_pit_timer_cb(void *opaque) { - AwA10PITState *s = AW_A10_PIT(opaque); - uint8_t i; + AwA10TimerContext *tc = opaque; + AwA10PITState *s = tc->container; + uint8_t i = tc->index; - for (i = 0; i < AW_A10_PIT_TIMER_NR; i++) { - if (s->control[i] & AW_A10_PIT_TIMER_EN) { - s->irq_status |= 1 << i; - if (s->control[i] & AW_A10_PIT_TIMER_MODE) { - ptimer_stop(s->timer[i]); - s->control[i] &= ~AW_A10_PIT_TIMER_EN; - } - qemu_irq_pulse(s->irq[i]); + if (s->control[i] & AW_A10_PIT_TIMER_EN) { + s->irq_status |= 1 << i; + if (s->control[i] & AW_A10_PIT_TIMER_MODE) { + ptimer_stop(s->timer[i]); + s->control[i] &= ~AW_A10_PIT_TIMER_EN; } + a10_pit_update_irq(s); } } @@ -223,9 +260,12 @@ static void a10_pit_init(Object *obj) sysbus_init_mmio(sbd, &s->iomem); for (i = 0; i < AW_A10_PIT_TIMER_NR; i++) { - bh[i] = qemu_bh_new(a10_pit_timer_cb, s); + AwA10TimerContext *tc = &s->timer_context[i]; + + tc->container = s; + tc->index = i; + bh[i] = qemu_bh_new(a10_pit_timer_cb, tc); s->timer[i] = ptimer_init(bh[i]); - ptimer_set_freq(s->timer[i], 240000); } } @@ -234,6 +274,7 @@ static void a10_pit_class_init(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); dc->reset = a10_pit_reset; + dc->props = a10_pit_properties; dc->desc = "allwinner a10 timer"; dc->vmsd = &vmstate_a10_pit; } diff --git a/hw/timer/arm_timer.c b/hw/timer/arm_timer.c index fb0a45c889..145291016b 100644 --- a/hw/timer/arm_timer.c +++ b/hw/timer/arm_timer.c @@ -150,8 +150,7 @@ static const VMStateDescription vmstate_arm_timer = { .name = "arm_timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(control, arm_timer_state), VMSTATE_UINT32(limit, arm_timer_state), VMSTATE_INT32(int_level, arm_timer_state), @@ -271,8 +270,7 @@ static const VMStateDescription vmstate_sp804 = { .name = "sp804", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_INT32_ARRAY(level, SP804State, 2), VMSTATE_END_OF_LIST() } diff --git a/hw/timer/cadence_ttc.c b/hw/timer/cadence_ttc.c index a279bced78..d46db3c0e2 100644 --- a/hw/timer/cadence_ttc.c +++ b/hw/timer/cadence_ttc.c @@ -346,11 +346,13 @@ static void cadence_ttc_write(void *opaque, hwaddr offset, case 0x34: case 0x38: s->reg_match[0] = value & 0xffff; + break; case 0x3c: /* match register */ case 0x40: case 0x44: s->reg_match[1] = value & 0xffff; + break; case 0x48: /* match register */ case 0x4c: @@ -404,21 +406,19 @@ static void cadence_timer_init(uint32_t freq, CadenceTimerState *s) s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, cadence_timer_tick, s); } -static int cadence_ttc_init(SysBusDevice *dev) +static void cadence_ttc_init(Object *obj) { - CadenceTTCState *s = CADENCE_TTC(dev); + CadenceTTCState *s = CADENCE_TTC(obj); int i; for (i = 0; i < 3; ++i) { cadence_timer_init(133000000, &s->timer[i]); - sysbus_init_irq(dev, &s->timer[i].irq); + sysbus_init_irq(SYS_BUS_DEVICE(obj), &s->timer[i].irq); } - memory_region_init_io(&s->iomem, OBJECT(s), &cadence_ttc_ops, s, + memory_region_init_io(&s->iomem, obj, &cadence_ttc_ops, s, "timer", 0x1000); - sysbus_init_mmio(dev, &s->iomem); - - return 0; + sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->iomem); } static void cadence_timer_pre_save(void *opaque) @@ -441,7 +441,6 @@ static const VMStateDescription vmstate_cadence_timer = { .name = "cadence_timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = cadence_timer_pre_save, .post_load = cadence_timer_post_load, .fields = (VMStateField[]) { @@ -462,7 +461,6 @@ static const VMStateDescription vmstate_cadence_ttc = { .name = "cadence_TTC", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(timer, CadenceTTCState, 3, 0, vmstate_cadence_timer, @@ -474,9 +472,7 @@ static const VMStateDescription vmstate_cadence_ttc = { static void cadence_ttc_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass); - sdc->init = cadence_ttc_init; dc->vmsd = &vmstate_cadence_ttc; } @@ -484,6 +480,7 @@ static const TypeInfo cadence_ttc_info = { .name = TYPE_CADENCE_TTC, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(CadenceTTCState), + .instance_init = cadence_ttc_init, .class_init = cadence_ttc_class_init, }; diff --git a/hw/timer/digic-timer.c b/hw/timer/digic-timer.c index 1fde22c67f..7e28e7e5f5 100644 --- a/hw/timer/digic-timer.c +++ b/hw/timer/digic-timer.c @@ -36,7 +36,6 @@ static const VMStateDescription vmstate_digic_timer = { .name = "digic.timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_PTIMER(ptimer, DigicTimerState), VMSTATE_UINT32(control, DigicTimerState), diff --git a/hw/timer/ds1338.c b/hw/timer/ds1338.c index bb2f8ee8b3..ec6dbeeab0 100644 --- a/hw/timer/ds1338.c +++ b/hw/timer/ds1338.c @@ -40,7 +40,6 @@ static const VMStateDescription vmstate_ds1338 = { .name = "ds1338", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_I2C_SLAVE(parent_obj, DS1338State), VMSTATE_INT64(offset, DS1338State), diff --git a/hw/timer/exynos4210_mct.c b/hw/timer/exynos4210_mct.c index 86f4fcd3e8..015bbaf1bd 100644 --- a/hw/timer/exynos4210_mct.c +++ b/hw/timer/exynos4210_mct.c @@ -264,7 +264,6 @@ static const VMStateDescription vmstate_tick_timer = { .name = "exynos4210.mct.tick_timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(cnt_run, struct tick_timer), VMSTATE_UINT32(int_run, struct tick_timer), @@ -284,7 +283,6 @@ static const VMStateDescription vmstate_lregs = { .name = "exynos4210.mct.lregs", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(cnt, struct lregs, L_REG_CNT_AMOUNT), VMSTATE_UINT32(tcon, struct lregs), @@ -299,7 +297,6 @@ static const VMStateDescription vmstate_exynos4210_mct_lt = { .name = "exynos4210.mct.lt", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_INT32(id, Exynos4210MCTLT), VMSTATE_STRUCT(tick_timer, Exynos4210MCTLT, 0, @@ -317,7 +314,6 @@ static const VMStateDescription vmstate_gregs = { .name = "exynos4210.mct.lregs", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT64(cnt, struct gregs), VMSTATE_UINT32(cnt_wstat, struct gregs), @@ -336,7 +332,6 @@ static const VMStateDescription vmstate_exynos4210_mct_gt = { .name = "exynos4210.mct.lt", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT(reg, Exynos4210MCTGT, 0, vmstate_gregs, struct gregs), @@ -351,7 +346,6 @@ static const VMStateDescription vmstate_exynos4210_mct_state = { .name = "exynos4210.mct", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(reg_mct_cfg, Exynos4210MCTState), VMSTATE_STRUCT_ARRAY(l_timer, Exynos4210MCTState, 2, 0, @@ -824,14 +818,14 @@ static void exynos4210_ltick_recalc_count(struct tick_timer *s) */ if (s->last_tcnto) { - to_count = s->last_tcnto * s->last_icnto; + to_count = (uint64_t)s->last_tcnto * s->last_icnto; } else { to_count = s->last_icnto; } } else { /* distance is passed, recalculate with tcnto * icnto */ if (s->icntb) { - s->distance = s->tcntb * s->icntb; + s->distance = (uint64_t)s->tcntb * s->icntb; } else { s->distance = s->tcntb; } diff --git a/hw/timer/exynos4210_pwm.c b/hw/timer/exynos4210_pwm.c index 1aa8f4d07a..1c1a2b8ff6 100644 --- a/hw/timer/exynos4210_pwm.c +++ b/hw/timer/exynos4210_pwm.c @@ -120,7 +120,6 @@ static const VMStateDescription vmstate_exynos4210_pwm = { .name = "exynos4210.pwm.pwm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(id, Exynos4210PWM), VMSTATE_UINT32(freq, Exynos4210PWM), @@ -135,7 +134,6 @@ static const VMStateDescription vmstate_exynos4210_pwm_state = { .name = "exynos4210.pwm", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(reg_tcfg, Exynos4210PWMState, 2), VMSTATE_UINT32(reg_tcon, Exynos4210PWMState), diff --git a/hw/timer/exynos4210_rtc.c b/hw/timer/exynos4210_rtc.c index 026f81a2e3..bf2ee9f80e 100644 --- a/hw/timer/exynos4210_rtc.c +++ b/hw/timer/exynos4210_rtc.c @@ -118,7 +118,6 @@ static const VMStateDescription vmstate_exynos4210_rtc_state = { .name = "exynos4210.rtc", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(reg_intp, Exynos4210RTCState), VMSTATE_UINT32(reg_rtccon, Exynos4210RTCState), diff --git a/hw/timer/hpet.c b/hw/timer/hpet.c index e15d6bcac7..e160e8facc 100644 --- a/hw/timer/hpet.c +++ b/hw/timer/hpet.c @@ -239,6 +239,18 @@ static int hpet_pre_load(void *opaque) return 0; } +static bool hpet_validate_num_timers(void *opaque, int version_id) +{ + HPETState *s = opaque; + + if (s->num_timers < HPET_MIN_TIMERS) { + return false; + } else if (s->num_timers > HPET_MAX_TIMERS) { + return false; + } + return true; +} + static int hpet_post_load(void *opaque, int version_id) { HPETState *s = opaque; @@ -270,8 +282,7 @@ static const VMStateDescription vmstate_hpet_rtc_irq_level = { .name = "hpet/rtc_irq_level", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(rtc_irq_level, HPETState), VMSTATE_END_OF_LIST() } @@ -281,8 +292,7 @@ static const VMStateDescription vmstate_hpet_timer = { .name = "hpet_timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(tn, HPETTimer), VMSTATE_UINT64(config, HPETTimer), VMSTATE_UINT64(cmp, HPETTimer), @@ -298,15 +308,15 @@ static const VMStateDescription vmstate_hpet = { .name = "hpet", .version_id = 2, .minimum_version_id = 1, - .minimum_version_id_old = 1, .pre_save = hpet_pre_save, .pre_load = hpet_pre_load, .post_load = hpet_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT64(config, HPETState), VMSTATE_UINT64(isr, HPETState), VMSTATE_UINT64(hpet_counter, HPETState), VMSTATE_UINT8_V(num_timers, HPETState, 2), + VMSTATE_VALIDATE("num_timers in range", hpet_validate_num_timers), VMSTATE_STRUCT_VARRAY_UINT8(timer, HPETState, num_timers, 0, vmstate_hpet_timer, HPETTimer), VMSTATE_END_OF_LIST() diff --git a/hw/timer/i8254.c b/hw/timer/i8254.c index 28152d88ea..3450c98637 100644 --- a/hw/timer/i8254.c +++ b/hw/timer/i8254.c @@ -322,7 +322,7 @@ static void pit_post_load(PITCommonState *s) } } -static void pit_realizefn(DeviceState *dev, Error **err) +static void pit_realizefn(DeviceState *dev, Error **errp) { PITCommonState *pit = PIT_COMMON(dev); PITClass *pc = PIT_GET_CLASS(dev); @@ -338,7 +338,7 @@ static void pit_realizefn(DeviceState *dev, Error **err) qdev_init_gpio_in(dev, pit_irq_control, 1); - pc->parent_realize(dev, err); + pc->parent_realize(dev, errp); } static Property pit_properties[] = { diff --git a/hw/timer/i8254_common.c b/hw/timer/i8254_common.c index 9db5c9d129..07345f668c 100644 --- a/hw/timer/i8254_common.c +++ b/hw/timer/i8254_common.c @@ -180,7 +180,6 @@ static const VMStateDescription vmstate_pit_channel = { .name = "pit channel", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .fields = (VMStateField[]) { VMSTATE_INT32(count, PITChannelState), VMSTATE_UINT16(latched_count, PITChannelState), diff --git a/hw/timer/imx_epit.c b/hw/timer/imx_epit.c index 0dbe15c99b..ffefc22f43 100644 --- a/hw/timer/imx_epit.c +++ b/hw/timer/imx_epit.c @@ -83,7 +83,7 @@ static char const *imx_epit_reg_name(uint32_t reg) #define CR_CLKSRC_SHIFT (24) #define CR_CLKSRC_MASK (0x3 << CR_CLKSRC_SHIFT) -#define TIMER_MAX 0XFFFFFFFFUL +#define EPIT_TIMER_MAX 0XFFFFFFFFUL /* * Exact clock frequencies vary from board to board. @@ -155,7 +155,7 @@ static void imx_epit_reset(DeviceState *dev) */ s->cr &= (CR_EN|CR_ENMOD|CR_STOPEN|CR_DOZEN|CR_WAITEN|CR_DBGEN); s->sr = 0; - s->lr = TIMER_MAX; + s->lr = EPIT_TIMER_MAX; s->cmp = 0; s->cnt = 0; /* stop both timers */ @@ -163,9 +163,9 @@ static void imx_epit_reset(DeviceState *dev) ptimer_stop(s->timer_reload); /* compute new frequency */ imx_epit_set_freq(s); - /* init both timers to TIMER_MAX */ - ptimer_set_limit(s->timer_cmp, TIMER_MAX, 1); - ptimer_set_limit(s->timer_reload, TIMER_MAX, 1); + /* init both timers to EPIT_TIMER_MAX */ + ptimer_set_limit(s->timer_cmp, EPIT_TIMER_MAX, 1); + ptimer_set_limit(s->timer_reload, EPIT_TIMER_MAX, 1); if (s->freq && (s->cr & CR_EN)) { /* if the timer is still enabled, restart it */ ptimer_run(s->timer_reload, 0); @@ -227,7 +227,7 @@ static void imx_epit_reload_compare_timer(IMXEPITState *s) /* It'll fire in this round of the timer */ next = tmp - s->cmp; } else { /* catch it next time around */ - next = tmp - s->cmp + ((s->cr & CR_RLD) ? TIMER_MAX : s->lr); + next = tmp - s->cmp + ((s->cr & CR_RLD) ? EPIT_TIMER_MAX : s->lr); } ptimer_set_count(s->timer_cmp, next); } @@ -260,8 +260,8 @@ static void imx_epit_write(void *opaque, hwaddr offset, uint64_t value, ptimer_set_limit(s->timer_reload, s->lr, 1); ptimer_set_limit(s->timer_cmp, s->lr, 1); } else { - ptimer_set_limit(s->timer_reload, TIMER_MAX, 1); - ptimer_set_limit(s->timer_cmp, TIMER_MAX, 1); + ptimer_set_limit(s->timer_reload, EPIT_TIMER_MAX, 1); + ptimer_set_limit(s->timer_cmp, EPIT_TIMER_MAX, 1); } } @@ -353,8 +353,7 @@ static const VMStateDescription vmstate_imx_timer_epit = { .name = "imx.epit", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(cr, IMXEPITState), VMSTATE_UINT32(sr, IMXEPITState), VMSTATE_UINT32(lr, IMXEPITState), diff --git a/hw/timer/imx_gpt.c b/hw/timer/imx_gpt.c index f2d1975e70..3b3101084b 100644 --- a/hw/timer/imx_gpt.c +++ b/hw/timer/imx_gpt.c @@ -80,11 +80,11 @@ static char const *imx_gpt_reg_name(uint32_t reg) * GPT : General purpose timer * * This timer counts up continuously while it is enabled, resetting itself - * to 0 when it reaches TIMER_MAX (in freerun mode) or when it + * to 0 when it reaches GPT_TIMER_MAX (in freerun mode) or when it * reaches the value of one of the ocrX (in periodic mode). */ -#define TIMER_MAX 0XFFFFFFFFUL +#define GPT_TIMER_MAX 0XFFFFFFFFUL /* Control register. Not all of these bits have any effect (yet) */ #define GPT_CR_EN (1 << 0) /* GPT Enable */ @@ -146,8 +146,7 @@ static const VMStateDescription vmstate_imx_timer_gpt = { .name = "imx.gpt", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32(cr, IMXGPTState), VMSTATE_UINT32(pr, IMXGPTState), VMSTATE_UINT32(sr, IMXGPTState), @@ -219,7 +218,7 @@ static inline uint32_t imx_gpt_find_limit(uint32_t count, uint32_t reg, static void imx_gpt_compute_next_timeout(IMXGPTState *s, bool event) { - uint32_t timeout = TIMER_MAX; + uint32_t timeout = GPT_TIMER_MAX; uint32_t count = 0; long long limit; @@ -231,10 +230,10 @@ static void imx_gpt_compute_next_timeout(IMXGPTState *s, bool event) if (event) { /* This is a timer event */ - if ((s->cr & GPT_CR_FRR) && (s->next_timeout != TIMER_MAX)) { + if ((s->cr & GPT_CR_FRR) && (s->next_timeout != GPT_TIMER_MAX)) { /* * if we are in free running mode and we have not reached - * the TIMER_MAX limit, then update the count + * the GPT_TIMER_MAX limit, then update the count */ count = imx_gpt_update_count(s); } @@ -268,7 +267,7 @@ static void imx_gpt_compute_next_timeout(IMXGPTState *s, bool event) if ((s->ir & GPT_IR_OF3IE) && (timeout == s->ocr3)) { s->next_int |= GPT_SR_OF3; } - if ((s->ir & GPT_IR_ROVIE) && (timeout == TIMER_MAX)) { + if ((s->ir & GPT_IR_ROVIE) && (timeout == GPT_TIMER_MAX)) { s->next_int |= GPT_SR_ROV; } @@ -371,20 +370,20 @@ static void imx_gpt_reset(DeviceState *dev) s->pr = 0; s->ir = 0; s->cnt = 0; - s->ocr1 = TIMER_MAX; - s->ocr2 = TIMER_MAX; - s->ocr3 = TIMER_MAX; + s->ocr1 = GPT_TIMER_MAX; + s->ocr2 = GPT_TIMER_MAX; + s->ocr3 = GPT_TIMER_MAX; s->icr1 = 0; s->icr2 = 0; - s->next_timeout = TIMER_MAX; + s->next_timeout = GPT_TIMER_MAX; s->next_int = 0; /* compute new freq */ imx_gpt_set_freq(s); - /* reset the limit to TIMER_MAX */ - ptimer_set_limit(s->timer, TIMER_MAX, 1); + /* reset the limit to GPT_TIMER_MAX */ + ptimer_set_limit(s->timer, GPT_TIMER_MAX, 1); /* if the timer is still enabled, restart it */ if (s->freq && (s->cr & GPT_CR_EN)) { @@ -416,8 +415,8 @@ static void imx_gpt_write(void *opaque, hwaddr offset, uint64_t value, if ((oldreg ^ s->cr) & GPT_CR_EN) { if (s->cr & GPT_CR_EN) { if (s->cr & GPT_CR_ENMOD) { - s->next_timeout = TIMER_MAX; - ptimer_set_count(s->timer, TIMER_MAX); + s->next_timeout = GPT_TIMER_MAX; + ptimer_set_count(s->timer, GPT_TIMER_MAX); imx_gpt_compute_next_timeout(s, false); } ptimer_run(s->timer, 1); @@ -452,8 +451,8 @@ static void imx_gpt_write(void *opaque, hwaddr offset, uint64_t value, /* In non-freerun mode, reset count when this register is written */ if (!(s->cr & GPT_CR_FRR)) { - s->next_timeout = TIMER_MAX; - ptimer_set_limit(s->timer, TIMER_MAX, 1); + s->next_timeout = GPT_TIMER_MAX; + ptimer_set_limit(s->timer, GPT_TIMER_MAX, 1); } /* compute the new timeout */ diff --git a/hw/timer/lm32_timer.c b/hw/timer/lm32_timer.c index 8ed138cc0e..d2ab1e74b2 100644 --- a/hw/timer/lm32_timer.c +++ b/hw/timer/lm32_timer.c @@ -196,8 +196,7 @@ static const VMStateDescription vmstate_lm32_timer = { .name = "lm32-timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PTIMER(ptimer, LM32TimerState), VMSTATE_UINT32(freq_hz, LM32TimerState), VMSTATE_UINT32_ARRAY(regs, LM32TimerState, R_MAX), diff --git a/hw/timer/m48t59.c b/hw/timer/m48t59.c index 7cf868445f..31509d5c28 100644 --- a/hw/timer/m48t59.c +++ b/hw/timer/m48t59.c @@ -595,8 +595,7 @@ static const VMStateDescription vmstate_m48t59 = { .name = "m48t59", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT8(lock, M48t59State), VMSTATE_UINT16(addr, M48t59State), VMSTATE_VBUFFER_UINT32(buffer, M48t59State, 0, NULL, 0, size), diff --git a/hw/timer/mc146818rtc.c b/hw/timer/mc146818rtc.c index 8509309fa7..f18d1281ca 100644 --- a/hw/timer/mc146818rtc.c +++ b/hw/timer/mc146818rtc.c @@ -26,6 +26,8 @@ #include "sysemu/sysemu.h" #include "hw/timer/mc146818rtc.h" #include "qapi/visitor.h" +#include "qapi-event.h" +#include "qmp-commands.h" #ifdef TARGET_I386 #include "hw/i386/apic.h" @@ -84,6 +86,7 @@ typedef struct RTCState { Notifier clock_reset_notifier; LostTickPolicy lost_tick_policy; Notifier suspend_notifier; + QLIST_ENTRY(RTCState) link; } RTCState; static void rtc_set_time(RTCState *s); @@ -388,7 +391,7 @@ static void cmos_ioport_write(void *opaque, hwaddr addr, if ((addr & 1) == 0) { s->cmos_index = data & 0x7f; } else { - CMOS_DPRINTF("cmos: write index=0x%02x val=0x%02x\n", + CMOS_DPRINTF("cmos: write index=0x%02x val=0x%02" PRIx64 "\n", s->cmos_index, data); switch(s->cmos_index) { case RTC_SECONDS_ALARM: @@ -522,6 +525,20 @@ static void rtc_get_time(RTCState *s, struct tm *tm) rtc_from_bcd(s, s->cmos_data[RTC_CENTURY]) * 100 - 1900; } +static QLIST_HEAD(, RTCState) rtc_devices = + QLIST_HEAD_INITIALIZER(rtc_devices); + +#ifdef TARGET_I386 +void qmp_rtc_reset_reinjection(Error **errp) +{ + RTCState *s; + + QLIST_FOREACH(s, &rtc_devices, link) { + s->irq_coalesced = 0; + } +} +#endif + static void rtc_set_time(RTCState *s) { struct tm tm; @@ -530,7 +547,7 @@ static void rtc_set_time(RTCState *s) s->base_rtc = mktimegm(&tm); s->last_update = qemu_clock_get_ns(rtc_clock); - rtc_change_mon_event(&tm); + qapi_event_send_rtc_change(qemu_timedate_diff(&tm), &error_abort); } static void rtc_set_cmos(RTCState *s, const struct tm *tm) @@ -716,13 +733,28 @@ static int rtc_post_load(void *opaque, int version_id) return 0; } +static const VMStateDescription vmstate_rtc_irq_reinject_on_ack_count = { + .name = "irq_reinject_on_ack_count", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT16(irq_reinject_on_ack_count, RTCState), + VMSTATE_END_OF_LIST() + } +}; + +static bool rtc_irq_reinject_on_ack_count_needed(void *opaque) +{ + RTCState *s = (RTCState *)opaque; + return s->irq_reinject_on_ack_count != 0; +} + static const VMStateDescription vmstate_rtc = { .name = "mc146818rtc", .version_id = 3, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = rtc_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_BUFFER(cmos_data, RTCState), VMSTATE_UINT8(cmos_index, RTCState), VMSTATE_UNUSED(7*4), @@ -737,6 +769,14 @@ static const VMStateDescription vmstate_rtc = { VMSTATE_TIMER_V(update_timer, RTCState, 3), VMSTATE_UINT64_V(next_alarm_time, RTCState, 3), VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_rtc_irq_reinject_on_ack_count, + .needed = rtc_irq_reinject_on_ack_count_needed, + }, { + /* empty */ + } } }; @@ -776,6 +816,7 @@ static void rtc_reset(void *opaque) #ifdef TARGET_I386 if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) { s->irq_coalesced = 0; + s->irq_reinject_on_ack_count = 0; } #endif } @@ -793,19 +834,46 @@ static const MemoryRegionOps cmos_ops = { static void rtc_get_date(Object *obj, Visitor *v, void *opaque, const char *name, Error **errp) { + Error *err = NULL; RTCState *s = MC146818_RTC(obj); struct tm current_tm; rtc_update_time(s); rtc_get_time(s, ¤t_tm); - visit_start_struct(v, NULL, "struct tm", name, 0, errp); - visit_type_int32(v, ¤t_tm.tm_year, "tm_year", errp); - visit_type_int32(v, ¤t_tm.tm_mon, "tm_mon", errp); - visit_type_int32(v, ¤t_tm.tm_mday, "tm_mday", errp); - visit_type_int32(v, ¤t_tm.tm_hour, "tm_hour", errp); - visit_type_int32(v, ¤t_tm.tm_min, "tm_min", errp); - visit_type_int32(v, ¤t_tm.tm_sec, "tm_sec", errp); + visit_start_struct(v, NULL, "struct tm", name, 0, &err); + if (err) { + goto out; + } + visit_type_int32(v, ¤t_tm.tm_year, "tm_year", &err); + if (err) { + goto out_end; + } + visit_type_int32(v, ¤t_tm.tm_mon, "tm_mon", &err); + if (err) { + goto out_end; + } + visit_type_int32(v, ¤t_tm.tm_mday, "tm_mday", &err); + if (err) { + goto out_end; + } + visit_type_int32(v, ¤t_tm.tm_hour, "tm_hour", &err); + if (err) { + goto out_end; + } + visit_type_int32(v, ¤t_tm.tm_min, "tm_min", &err); + if (err) { + goto out_end; + } + visit_type_int32(v, ¤t_tm.tm_sec, "tm_sec", &err); + if (err) { + goto out_end; + } +out_end: + error_propagate(errp, err); + err = NULL; visit_end_struct(v, errp); +out: + error_propagate(errp, err); } static void rtc_realizefn(DeviceState *dev, Error **errp) @@ -852,7 +920,7 @@ static void rtc_realizefn(DeviceState *dev, Error **errp) check_update_timer(s); s->clock_reset_notifier.notify = rtc_notify_clock_reset; - qemu_clock_register_reset_notifier(QEMU_CLOCK_REALTIME, + qemu_clock_register_reset_notifier(rtc_clock, &s->clock_reset_notifier); s->suspend_notifier.notify = rtc_notify_suspend; @@ -866,6 +934,9 @@ static void rtc_realizefn(DeviceState *dev, Error **errp) object_property_add(OBJECT(s), "date", "struct tm", rtc_get_date, NULL, NULL, s, NULL); + + object_property_add_alias(qdev_get_machine(), "rtc-time", + OBJECT(s), "date", NULL); } ISADevice *rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq) @@ -884,6 +955,8 @@ ISADevice *rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq) } else { isa_init_irq(isadev, &s->irq, RTC_ISA_IRQ); } + QLIST_INSERT_HEAD(&rtc_devices, s, link); + return isadev; } @@ -905,11 +978,17 @@ static void rtc_class_initfn(ObjectClass *klass, void *data) dc->cannot_instantiate_with_device_add_yet = true; } +static void rtc_finalize(Object *obj) +{ + object_property_del(qdev_get_machine(), "rtc", NULL); +} + static const TypeInfo mc146818rtc_info = { .name = TYPE_MC146818_RTC, .parent = TYPE_ISA_DEVICE, .instance_size = sizeof(RTCState), .class_init = rtc_class_initfn, + .instance_finalize = rtc_finalize, }; static void mc146818rtc_register_types(void) diff --git a/hw/timer/milkymist-sysctl.c b/hw/timer/milkymist-sysctl.c index 94246e56f6..30535a4e3d 100644 --- a/hw/timer/milkymist-sysctl.c +++ b/hw/timer/milkymist-sysctl.c @@ -295,8 +295,7 @@ static const VMStateDescription vmstate_milkymist_sysctl = { .name = "milkymist-sysctl", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(regs, MilkymistSysctlState, R_MAX), VMSTATE_PTIMER(ptimer0, MilkymistSysctlState), VMSTATE_PTIMER(ptimer1, MilkymistSysctlState), diff --git a/hw/timer/omap_gptimer.c b/hw/timer/omap_gptimer.c index 016207f626..b7f3d49ca6 100644 --- a/hw/timer/omap_gptimer.c +++ b/hw/timer/omap_gptimer.c @@ -227,7 +227,7 @@ static void omap_gp_timer_clk_update(void *opaque, int line, int on) static void omap_gp_timer_clk_setup(struct omap_gp_timer_s *timer) { omap_clk_adduser(timer->clk, - qemu_allocate_irqs(omap_gp_timer_clk_update, timer, 1)[0]); + qemu_allocate_irq(omap_gp_timer_clk_update, timer, 0)); timer->rate = omap_clk_getrate(timer->clk); } @@ -476,7 +476,7 @@ struct omap_gp_timer_s *omap_gp_timer_init(struct omap_target_agent_s *ta, s->clk = fclk; s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_gp_timer_tick, s); s->match = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_gp_timer_match, s); - s->in = qemu_allocate_irqs(omap_gp_timer_input, s, 1)[0]; + s->in = qemu_allocate_irq(omap_gp_timer_input, s, 0); omap_gp_timer_reset(s); omap_gp_timer_clk_setup(s); diff --git a/hw/timer/pxa2xx_timer.c b/hw/timer/pxa2xx_timer.c index 0f546c4121..130e9dc345 100644 --- a/hw/timer/pxa2xx_timer.c +++ b/hw/timer/pxa2xx_timer.c @@ -476,7 +476,6 @@ static const VMStateDescription vmstate_pxa2xx_timer0_regs = { .name = "pxa2xx_timer0", .version_id = 2, .minimum_version_id = 2, - .minimum_version_id_old = 2, .fields = (VMStateField[]) { VMSTATE_UINT32(value, PXA2xxTimer0), VMSTATE_END_OF_LIST(), @@ -487,7 +486,6 @@ static const VMStateDescription vmstate_pxa2xx_timer4_regs = { .name = "pxa2xx_timer4", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .fields = (VMStateField[]) { VMSTATE_STRUCT(tm, PXA2xxTimer4, 1, vmstate_pxa2xx_timer0_regs, PXA2xxTimer0), @@ -509,7 +507,6 @@ static const VMStateDescription vmstate_pxa2xx_timer_regs = { .name = "pxa2xx_timer", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = pxa25x_timer_post_load, .fields = (VMStateField[]) { VMSTATE_INT32(clock, PXA2xxTimerInfo), diff --git a/hw/timer/slavio_timer.c b/hw/timer/slavio_timer.c index e4dcceaf23..45d97e6678 100644 --- a/hw/timer/slavio_timer.c +++ b/hw/timer/slavio_timer.c @@ -329,8 +329,7 @@ static const VMStateDescription vmstate_timer = { .name ="timer", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT64(limit, CPUTimerState), VMSTATE_UINT32(count, CPUTimerState), VMSTATE_UINT32(counthigh, CPUTimerState), @@ -345,8 +344,7 @@ static const VMStateDescription vmstate_slavio_timer = { .name ="slavio_timer", .version_id = 3, .minimum_version_id = 3, - .minimum_version_id_old = 3, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_STRUCT_ARRAY(cputimer, SLAVIO_TIMERState, MAX_CPUS + 1, 3, vmstate_timer, CPUTimerState), VMSTATE_END_OF_LIST() diff --git a/hw/timer/tusb6010.c b/hw/timer/tusb6010.c index bd2a89e020..459c748e1b 100644 --- a/hw/timer/tusb6010.c +++ b/hw/timer/tusb6010.c @@ -282,9 +282,6 @@ static void tusb_gpio_intr_update(TUSBState *s) /* TODO: How is this signalled? */ } -extern CPUReadMemoryFunc * const musb_read[]; -extern CPUWriteMemoryFunc * const musb_write[]; - static uint32_t tusb_async_readb(void *opaque, hwaddr addr) { TUSBState *s = (TUSBState *) opaque; diff --git a/hw/timer/twl92230.c b/hw/timer/twl92230.c index 85d59909da..7ded4ba2ad 100644 --- a/hw/timer/twl92230.c +++ b/hw/timer/twl92230.c @@ -772,8 +772,7 @@ static const VMStateDescription vmstate_menelaus_tm = { .name = "menelaus_tm", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16_HACK(tm_sec, struct tm), VMSTATE_UINT16_HACK(tm_min, struct tm), VMSTATE_UINT16_HACK(tm_hour, struct tm), @@ -811,10 +810,9 @@ static const VMStateDescription vmstate_menelaus = { .name = "menelaus", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, .pre_save = menelaus_pre_save, .post_load = menelaus_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_INT32(firstbyte, MenelausState), VMSTATE_UINT8(reg, MenelausState), VMSTATE_UINT8_ARRAY(vcore, MenelausState, 5), diff --git a/hw/timer/xilinx_timer.c b/hw/timer/xilinx_timer.c index 6113b975bf..cdb3355174 100644 --- a/hw/timer/xilinx_timer.c +++ b/hw/timer/xilinx_timer.c @@ -169,7 +169,7 @@ timer_write(void *opaque, hwaddr addr, if (value & TCSR_TINT) value &= ~TCSR_TINT; - xt->regs[addr] = value; + xt->regs[addr] = value & 0x7ff; if (value & TCSR_ENT) timer_enable(xt); break; @@ -204,14 +204,11 @@ static void timer_hit(void *opaque) timer_update_irq(t); } -static int xilinx_timer_init(SysBusDevice *dev) +static void xilinx_timer_realize(DeviceState *dev, Error **errp) { struct timerblock *t = XILINX_TIMER(dev); unsigned int i; - /* All timers share a single irq line. */ - sysbus_init_irq(dev, &t->irq); - /* Init all the ptimers. */ t->timers = g_malloc0(sizeof t->timers[0] * num_timers(t)); for (i = 0; i < num_timers(t); i++) { @@ -226,8 +223,15 @@ static int xilinx_timer_init(SysBusDevice *dev) memory_region_init_io(&t->mmio, OBJECT(t), &timer_ops, t, "xlnx.xps-timer", R_MAX * 4 * num_timers(t)); - sysbus_init_mmio(dev, &t->mmio); - return 0; + sysbus_init_mmio(SYS_BUS_DEVICE(dev), &t->mmio); +} + +static void xilinx_timer_init(Object *obj) +{ + struct timerblock *t = XILINX_TIMER(obj); + + /* All timers share a single irq line. */ + sysbus_init_irq(SYS_BUS_DEVICE(obj), &t->irq); } static Property xilinx_timer_properties[] = { @@ -240,9 +244,8 @@ static Property xilinx_timer_properties[] = { static void xilinx_timer_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); - SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); - k->init = xilinx_timer_init; + dc->realize = xilinx_timer_realize; dc->props = xilinx_timer_properties; } @@ -250,6 +253,7 @@ static const TypeInfo xilinx_timer_info = { .name = TYPE_XILINX_TIMER, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(struct timerblock), + .instance_init = xilinx_timer_init, .class_init = xilinx_timer_class_init, }; diff --git a/hw/tpm/tpm_tis.c b/hw/tpm/tpm_tis.c index 6f0a4d2814..c0e7cd738a 100644 --- a/hw/tpm/tpm_tis.c +++ b/hw/tpm/tpm_tis.c @@ -21,7 +21,7 @@ #include "sysemu/tpm_backend.h" #include "tpm_int.h" -#include "block/block.h" +#include "sysemu/block-backend.h" #include "exec/address-spaces.h" #include "hw/hw.h" #include "hw/i386/pc.h" @@ -896,14 +896,6 @@ static void tpm_tis_initfn(Object *obj) &s->mmio); } -static void tpm_tis_uninitfn(Object *obj) -{ - TPMState *s = TPM(obj); - - memory_region_del_subregion(get_system_memory(), &s->mmio); - memory_region_destroy(&s->mmio); -} - static void tpm_tis_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); @@ -919,7 +911,6 @@ static const TypeInfo tpm_tis_info = { .parent = TYPE_ISA_DEVICE, .instance_size = sizeof(TPMState), .instance_init = tpm_tis_initfn, - .instance_finalize = tpm_tis_uninitfn, .class_init = tpm_tis_class_init, }; diff --git a/hw/tpm/tpm_tis.h b/hw/tpm/tpm_tis.h index 916152ae3e..1a0db23367 100644 --- a/hw/tpm/tpm_tis.h +++ b/hw/tpm/tpm_tis.h @@ -18,23 +18,17 @@ #define TPM_TPM_TIS_H #include "hw/isa/isa.h" +#include "hw/acpi/tpm.h" #include "qemu-common.h" -#define TPM_TIS_ADDR_BASE 0xFED40000 - #define TPM_TIS_NUM_LOCALITIES 5 /* per spec */ #define TPM_TIS_LOCALITY_SHIFT 12 #define TPM_TIS_NO_LOCALITY 0xff #define TPM_TIS_IS_VALID_LOCTY(x) ((x) < TPM_TIS_NUM_LOCALITIES) -#define TPM_TIS_IRQ 5 - #define TPM_TIS_BUFFER_MAX 4096 -#define TYPE_TPM_TIS "tpm-tis" - - typedef enum { TPM_TIS_STATE_IDLE = 0, TPM_TIS_STATE_READY, diff --git a/hw/tricore/Makefile.objs b/hw/tricore/Makefile.objs new file mode 100644 index 0000000000..435e095cff --- /dev/null +++ b/hw/tricore/Makefile.objs @@ -0,0 +1 @@ +obj-y += tricore_testboard.o diff --git a/hw/tricore/tricore_testboard.c b/hw/tricore/tricore_testboard.c new file mode 100644 index 0000000000..a059a20a30 --- /dev/null +++ b/hw/tricore/tricore_testboard.c @@ -0,0 +1,124 @@ +/* + * TriCore Baseboard System emulation. + * + * Copyright (c) 2013-2014 Bastian Koppelmann C-Lab/University Paderborn + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see <http://www.gnu.org/licenses/>. + */ + + +#include "hw/hw.h" +#include "hw/devices.h" +#include "net/net.h" +#include "sysemu/sysemu.h" +#include "hw/boards.h" +#include "hw/loader.h" +#include "sysemu/block-backend.h" +#include "exec/address-spaces.h" +#include "hw/block/flash.h" +#include "elf.h" +#include "hw/tricore/tricore.h" +#include "qemu/error-report.h" + + +/* Board init. */ + +static struct tricore_boot_info tricoretb_binfo; + +static void tricore_load_kernel(CPUTriCoreState *env) +{ + uint64_t entry; + long kernel_size; + + kernel_size = load_elf(tricoretb_binfo.kernel_filename, NULL, + NULL, (uint64_t *)&entry, NULL, + NULL, 0, + ELF_MACHINE, 1); + if (kernel_size <= 0) { + error_report("qemu: no kernel file '%s'", + tricoretb_binfo.kernel_filename); + exit(1); + } + env->PC = entry; + +} + +static void tricore_testboard_init(MachineState *machine, int board_id) +{ + TriCoreCPU *cpu; + CPUTriCoreState *env; + + MemoryRegion *sysmem = get_system_memory(); + MemoryRegion *ext_cram = g_new(MemoryRegion, 1); + MemoryRegion *ext_dram = g_new(MemoryRegion, 1); + MemoryRegion *int_cram = g_new(MemoryRegion, 1); + MemoryRegion *int_dram = g_new(MemoryRegion, 1); + MemoryRegion *pcp_data = g_new(MemoryRegion, 1); + MemoryRegion *pcp_text = g_new(MemoryRegion, 1); + + if (!machine->cpu_model) { + machine->cpu_model = "tc1796"; + } + cpu = cpu_tricore_init(machine->cpu_model); + if (!cpu) { + error_report("Unable to find CPU definition"); + exit(1); + } + env = &cpu->env; + memory_region_init_ram(ext_cram, NULL, "powerlink_ext_c.ram", 2*1024*1024, &error_abort); + vmstate_register_ram_global(ext_cram); + memory_region_init_ram(ext_dram, NULL, "powerlink_ext_d.ram", 4*1024*1024, &error_abort); + vmstate_register_ram_global(ext_dram); + memory_region_init_ram(int_cram, NULL, "powerlink_int_c.ram", 48*1024, &error_abort); + vmstate_register_ram_global(int_cram); + memory_region_init_ram(int_dram, NULL, "powerlink_int_d.ram", 48*1024, &error_abort); + vmstate_register_ram_global(int_dram); + memory_region_init_ram(pcp_data, NULL, "powerlink_pcp_data.ram", 16*1024, &error_abort); + vmstate_register_ram_global(pcp_data); + memory_region_init_ram(pcp_text, NULL, "powerlink_pcp_text.ram", 32*1024, &error_abort); + vmstate_register_ram_global(pcp_text); + + memory_region_add_subregion(sysmem, 0x80000000, ext_cram); + memory_region_add_subregion(sysmem, 0xa1000000, ext_dram); + memory_region_add_subregion(sysmem, 0xd4000000, int_cram); + memory_region_add_subregion(sysmem, 0xd0000000, int_dram); + memory_region_add_subregion(sysmem, 0xf0050000, pcp_data); + memory_region_add_subregion(sysmem, 0xf0060000, pcp_text); + + tricoretb_binfo.ram_size = machine->ram_size; + tricoretb_binfo.kernel_filename = machine->kernel_filename; + + if (machine->kernel_filename) { + tricore_load_kernel(env); + } +} + +static void tricoreboard_init(MachineState *machine) +{ + tricore_testboard_init(machine, 0x183); +} + +static QEMUMachine ttb_machine = { + .name = "tricore_testboard", + .desc = "a minimal TriCore board", + .init = tricoreboard_init, + .is_default = 0, +}; + +static void tricore_testboard_machine_init(void) +{ + qemu_register_machine(&ttb_machine); +} + +machine_init(tricore_testboard_machine_init); diff --git a/hw/unicore32/puv3.c b/hw/unicore32/puv3.c index 42913b6a5a..c41499e38e 100644 --- a/hw/unicore32/puv3.c +++ b/hw/unicore32/puv3.c @@ -74,7 +74,8 @@ static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size) MemoryRegion *ram_memory = g_new(MemoryRegion, 1); /* SDRAM at address zero. */ - memory_region_init_ram(ram_memory, NULL, "puv3.ram", ram_size); + memory_region_init_ram(ram_memory, NULL, "puv3.ram", ram_size, + &error_abort); vmstate_register_ram_global(ram_memory); memory_region_add_subregion(get_system_memory(), 0, ram_memory); } @@ -101,12 +102,12 @@ static void puv3_load_kernel(const char *kernel_filename) graphic_console_init(NULL, 0, &no_ops, NULL); } -static void puv3_init(QEMUMachineInitArgs *args) +static void puv3_init(MachineState *machine) { - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *initrd_filename = args->initrd_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; + const char *initrd_filename = machine->initrd_filename; CPUUniCore32State *env; if (initrd_filename) { diff --git a/hw/usb/Makefile.objs b/hw/usb/Makefile.objs index 97b457541f..3fe4dff3bd 100644 --- a/hw/usb/Makefile.objs +++ b/hw/usb/Makefile.objs @@ -24,6 +24,11 @@ ifeq ($(CONFIG_USB_SMARTCARD),y) common-obj-y += dev-smartcard-reader.o common-obj-y += ccid-card-passthru.o common-obj-$(CONFIG_SMARTCARD_NSS) += ccid-card-emulated.o +ccid-card-emulated.o-cflags := -I$(SRC_PATH)/libcacard +endif + +ifeq ($(CONFIG_POSIX),y) +common-obj-$(CONFIG_USB_STORAGE_MTP) += dev-mtp.o endif # usb redirection diff --git a/hw/usb/bus.c b/hw/usb/bus.c index fe70429304..986b2d8da8 100644 --- a/hw/usb/bus.c +++ b/hw/usb/bus.c @@ -9,7 +9,7 @@ static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent); static char *usb_get_dev_path(DeviceState *dev); static char *usb_get_fw_dev_path(DeviceState *qdev); -static int usb_qdev_exit(DeviceState *qdev); +static void usb_qdev_unrealize(DeviceState *qdev, Error **errp); static Property usb_props[] = { DEFINE_PROP_STRING("port", USBDevice, port_path), @@ -24,10 +24,12 @@ static Property usb_props[] = { static void usb_bus_class_init(ObjectClass *klass, void *data) { BusClass *k = BUS_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); k->print_dev = usb_bus_dev_print; k->get_dev_path = usb_get_dev_path; k->get_fw_dev_path = usb_get_fw_dev_path; + hc->unplug = qdev_simple_device_unplug_cb; } static const TypeInfo usb_bus_info = { @@ -35,6 +37,10 @@ static const TypeInfo usb_bus_info = { .parent = TYPE_BUS, .instance_size = sizeof(USBBus), .class_init = usb_bus_class_init, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static int next_usb_bus = 0; @@ -49,8 +55,10 @@ static int usb_device_post_load(void *opaque, int version_id) } else { dev->attached = 1; } - if (dev->setup_index >= sizeof(dev->data_buf) || - dev->setup_len >= sizeof(dev->data_buf)) { + if (dev->setup_index < 0 || + dev->setup_len < 0 || + dev->setup_index > dev->setup_len || + dev->setup_len > sizeof(dev->data_buf)) { return -EINVAL; } return 0; @@ -61,7 +69,7 @@ const VMStateDescription vmstate_usb_device = { .version_id = 1, .minimum_version_id = 1, .post_load = usb_device_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT8(addr, USBDevice), VMSTATE_INT32(state, USBDevice), VMSTATE_INT32(remote_wakeup, USBDevice), @@ -77,14 +85,21 @@ void usb_bus_new(USBBus *bus, size_t bus_size, USBBusOps *ops, DeviceState *host) { qbus_create_inplace(bus, bus_size, TYPE_USB_BUS, host, NULL); + qbus_set_bus_hotplug_handler(BUS(bus), &error_abort); bus->ops = ops; bus->busnr = next_usb_bus++; - bus->qbus.allow_hotplug = 1; /* Yes, we can */ QTAILQ_INIT(&bus->free); QTAILQ_INIT(&bus->used); QTAILQ_INSERT_TAIL(&busses, bus, next); } +void usb_bus_release(USBBus *bus) +{ + assert(next_usb_bus > 0); + + QTAILQ_REMOVE(&busses, bus, next); +} + USBBus *usb_bus_find(int busnr) { USBBus *bus; @@ -98,13 +113,13 @@ USBBus *usb_bus_find(int busnr) return NULL; } -static int usb_device_init(USBDevice *dev) +static void usb_device_realize(USBDevice *dev, Error **errp) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); - if (klass->init) { - return klass->init(dev); + + if (klass->realize) { + klass->realize(dev, errp); } - return 0; } USBDevice *usb_device_find_device(USBDevice *dev, uint8_t addr) @@ -223,36 +238,41 @@ void usb_device_free_streams(USBDevice *dev, USBEndpoint **eps, int nr_eps) } } -static int usb_qdev_init(DeviceState *qdev) +static void usb_qdev_realize(DeviceState *qdev, Error **errp) { USBDevice *dev = USB_DEVICE(qdev); - int rc; + Error *local_err = NULL; pstrcpy(dev->product_desc, sizeof(dev->product_desc), usb_device_get_product_desc(dev)); dev->auto_attach = 1; QLIST_INIT(&dev->strings); usb_ep_init(dev); - rc = usb_claim_port(dev); - if (rc != 0) { - return rc; + + usb_claim_port(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } - rc = usb_device_init(dev); - if (rc != 0) { + + usb_device_realize(dev, &local_err); + if (local_err) { usb_release_port(dev); - return rc; + error_propagate(errp, local_err); + return; } + if (dev->auto_attach) { - rc = usb_device_attach(dev); - if (rc != 0) { - usb_qdev_exit(qdev); - return rc; + usb_device_attach(dev, &local_err); + if (local_err) { + usb_qdev_unrealize(qdev, NULL); + error_propagate(errp, local_err); + return; } } - return 0; } -static int usb_qdev_exit(DeviceState *qdev) +static void usb_qdev_unrealize(DeviceState *qdev, Error **errp) { USBDevice *dev = USB_DEVICE(qdev); @@ -263,7 +283,6 @@ static int usb_qdev_exit(DeviceState *qdev) if (dev->port) { usb_release_port(dev); } - return 0; } typedef struct LegacyUSBFactory @@ -383,7 +402,7 @@ void usb_unregister_port(USBBus *bus, USBPort *port) bus->nfree--; } -int usb_claim_port(USBDevice *dev) +void usb_claim_port(USBDevice *dev, Error **errp) { USBBus *bus = usb_bus_from_device(dev); USBPort *port; @@ -397,9 +416,9 @@ int usb_claim_port(USBDevice *dev) } } if (port == NULL) { - error_report("Error: usb port %s (bus %s) not found (in use?)", - dev->port_path, bus->qbus.name); - return -1; + error_setg(errp, "Error: usb port %s (bus %s) not found (in use?)", + dev->port_path, bus->qbus.name); + return; } } else { if (bus->nfree == 1 && strcmp(object_get_typename(OBJECT(dev)), "usb-hub") != 0) { @@ -407,9 +426,9 @@ int usb_claim_port(USBDevice *dev) usb_create_simple(bus, "usb-hub"); } if (bus->nfree == 0) { - error_report("Error: tried to attach usb device %s to a bus " - "with no free ports", dev->product_desc); - return -1; + error_setg(errp, "Error: tried to attach usb device %s to a bus " + "with no free ports", dev->product_desc); + return; } port = QTAILQ_FIRST(&bus->free); } @@ -423,7 +442,6 @@ int usb_claim_port(USBDevice *dev) QTAILQ_INSERT_TAIL(&bus->used, port, next); bus->nused++; - return 0; } void usb_release_port(USBDevice *dev) @@ -466,7 +484,7 @@ static void usb_mask_to_str(char *dest, size_t size, } } -int usb_device_attach(USBDevice *dev) +void usb_check_attach(USBDevice *dev, Error **errp) { USBBus *bus = usb_bus_from_device(dev); USBPort *port = dev->port; @@ -480,18 +498,28 @@ int usb_device_attach(USBDevice *dev) devspeed, portspeed); if (!(port->speedmask & dev->speedmask)) { - error_report("Warning: speed mismatch trying to attach" - " usb device \"%s\" (%s speed)" - " to bus \"%s\", port \"%s\" (%s speed)", - dev->product_desc, devspeed, - bus->qbus.name, port->path, portspeed); - return -1; + error_setg(errp, "Warning: speed mismatch trying to attach" + " usb device \"%s\" (%s speed)" + " to bus \"%s\", port \"%s\" (%s speed)", + dev->product_desc, devspeed, + bus->qbus.name, port->path, portspeed); + return; + } +} + +void usb_device_attach(USBDevice *dev, Error **errp) +{ + USBPort *port = dev->port; + Error *local_err = NULL; + + usb_check_attach(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } dev->attached++; usb_attach(port); - - return 0; } int usb_device_detach(USBDevice *dev) @@ -587,11 +615,11 @@ static char *usb_get_fw_dev_path(DeviceState *qdev) nr = strtol(in, &in, 10); if (in[0] == '.') { /* some hub between root port and device */ - pos += snprintf(fw_path + pos, fw_len - pos, "hub@%ld/", nr); + pos += snprintf(fw_path + pos, fw_len - pos, "hub@%lx/", nr); in++; } else { /* the device itself */ - pos += snprintf(fw_path + pos, fw_len - pos, "%s@%ld", + pos += snprintf(fw_path + pos, fw_len - pos, "%s@%lx", qdev_fw_name(qdev), nr); break; } @@ -679,9 +707,8 @@ static void usb_device_class_init(ObjectClass *klass, void *data) { DeviceClass *k = DEVICE_CLASS(klass); k->bus_type = TYPE_USB_BUS; - k->init = usb_qdev_init; - k->unplug = qdev_simple_unplug_cb; - k->exit = usb_qdev_exit; + k->realize = usb_qdev_realize; + k->unrealize = usb_qdev_unrealize; k->props = usb_props; } diff --git a/hw/usb/ccid-card-emulated.c b/hw/usb/ccid-card-emulated.c index 7213c8909c..aa1c37aabd 100644 --- a/hw/usb/ccid-card-emulated.c +++ b/hw/usb/ccid-card-emulated.c @@ -126,7 +126,7 @@ struct EmulatedState { QemuMutex vreader_mutex; /* and guest_apdu_list mutex */ QemuMutex handle_apdu_mutex; QemuCond handle_apdu_cond; - int pipe[2]; + EventNotifier notifier; int quit_apdu_thread; QemuThread apdu_thread_id; }; @@ -162,9 +162,7 @@ static void emulated_push_event(EmulatedState *card, EmulEvent *event) qemu_mutex_lock(&card->event_list_mutex); QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry); qemu_mutex_unlock(&card->event_list_mutex); - if (write(card->pipe[1], card, 1) != 1) { - DPRINTF(card, 1, "write to pipe failed\n"); - } + event_notifier_set(&card->notifier); } static void emulated_push_type(EmulatedState *card, uint32_t type) @@ -358,16 +356,12 @@ static void *event_thread(void *arg) return NULL; } -static void pipe_read(void *opaque) +static void card_event_handler(EventNotifier *notifier) { - EmulatedState *card = opaque; + EmulatedState *card = container_of(notifier, EmulatedState, notifier); EmulEvent *event, *next; - char dummy; - int len; - do { - len = read(card->pipe[0], &dummy, sizeof(dummy)); - } while (len == sizeof(dummy)); + event_notifier_test_and_clear(&card->notifier); qemu_mutex_lock(&card->event_list_mutex); QSIMPLEQ_FOREACH_SAFE(event, &card->event_list, entry, next) { DPRINTF(card, 2, "event %s\n", emul_event_to_string(event->p.gen.type)); @@ -404,16 +398,13 @@ static void pipe_read(void *opaque) qemu_mutex_unlock(&card->event_list_mutex); } -static int init_pipe_signaling(EmulatedState *card) +static int init_event_notifier(EmulatedState *card) { - if (pipe(card->pipe) < 0) { - DPRINTF(card, 2, "pipe creation failed\n"); + if (event_notifier_init(&card->notifier, false) < 0) { + DPRINTF(card, 2, "event notifier creation failed\n"); return -1; } - fcntl(card->pipe[0], F_SETFL, O_NONBLOCK); - fcntl(card->pipe[1], F_SETFL, O_NONBLOCK); - fcntl(card->pipe[0], F_SETOWN, getpid()); - qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card); + event_notifier_set_handler(&card->notifier, card_event_handler); return 0; } @@ -500,7 +491,7 @@ static int emulated_initfn(CCIDCardState *base) qemu_cond_init(&card->handle_apdu_cond); card->reader = NULL; card->quit_apdu_thread = 0; - if (init_pipe_signaling(card) < 0) { + if (init_event_notifier(card) < 0) { return -1; } diff --git a/hw/usb/core.c b/hw/usb/core.c index 67ba7d6018..cf34755bba 100644 --- a/hw/usb/core.c +++ b/hw/usb/core.c @@ -28,6 +28,26 @@ #include "qemu/iov.h" #include "trace.h" +void usb_pick_speed(USBPort *port) +{ + static const int speeds[] = { + USB_SPEED_SUPER, + USB_SPEED_HIGH, + USB_SPEED_FULL, + USB_SPEED_LOW, + }; + USBDevice *udev = port->dev; + int i; + + for (i = 0; i < ARRAY_SIZE(speeds); i++) { + if ((udev->speedmask & (1 << speeds[i])) && + (port->speedmask & (1 << speeds[i]))) { + udev->speed = speeds[i]; + return; + } + } +} + void usb_attach(USBPort *port) { USBDevice *dev = port->dev; @@ -35,6 +55,7 @@ void usb_attach(USBPort *port) assert(dev != NULL); assert(dev->attached); assert(dev->state == USB_STATE_NOTATTACHED); + usb_pick_speed(port); port->ops->attach(port); dev->state = USB_STATE_ATTACHED; usb_device_handle_attach(dev); diff --git a/hw/usb/desc-msos.c b/hw/usb/desc-msos.c index ed8d62cab8..334d1aea8d 100644 --- a/hw/usb/desc-msos.c +++ b/hw/usb/desc-msos.c @@ -44,7 +44,7 @@ typedef struct msos_compat_hdr { typedef struct msos_compat_func { uint8_t bFirstInterfaceNumber; uint8_t reserved_1; - uint8_t compatibleId[8]; + char compatibleId[8]; uint8_t subCompatibleId[8]; uint8_t reserved_2[6]; } QEMU_PACKED msos_compat_func; @@ -59,6 +59,10 @@ static int usb_desc_msos_compat(const USBDesc *desc, uint8_t *dest) func = (void *)(dest + length); func->bFirstInterfaceNumber = 0; func->reserved_1 = 0x01; + if (desc->msos->CompatibleID) { + snprintf(func->compatibleId, sizeof(func->compatibleId), + "%s", desc->msos->CompatibleID); + } length += sizeof(*func); count++; diff --git a/hw/usb/desc.c b/hw/usb/desc.c index ab48691363..b82c397ef9 100644 --- a/hw/usb/desc.c +++ b/hw/usb/desc.c @@ -518,18 +518,6 @@ void usb_desc_init(USBDevice *dev) void usb_desc_attach(USBDevice *dev) { - const USBDesc *desc = usb_device_get_usb_desc(dev); - - assert(desc != NULL); - if (desc->super && (dev->port->speedmask & USB_SPEED_MASK_SUPER)) { - dev->speed = USB_SPEED_SUPER; - } else if (desc->high && (dev->port->speedmask & USB_SPEED_MASK_HIGH)) { - dev->speed = USB_SPEED_HIGH; - } else if (desc->full && (dev->port->speedmask & USB_SPEED_MASK_FULL)) { - dev->speed = USB_SPEED_FULL; - } else { - return; - } usb_desc_setdefaults(dev); } diff --git a/hw/usb/desc.h b/hw/usb/desc.h index 2b4fcdae76..8e8db03a0c 100644 --- a/hw/usb/desc.h +++ b/hw/usb/desc.h @@ -184,6 +184,7 @@ struct USBDescOther { }; struct USBDescMSOS { + const char *CompatibleID; const wchar_t *Label; bool SelectiveSuspendEnabled; }; diff --git a/hw/usb/dev-audio.c b/hw/usb/dev-audio.c index bfebfe90f3..67deffebcf 100644 --- a/hw/usb/dev-audio.c +++ b/hw/usb/dev-audio.c @@ -371,7 +371,7 @@ static void output_callback(void *opaque, int avail) return; } data = streambuf_get(&s->out.buf); - if (NULL == data) { + if (!data) { return; } AUD_write(s->out.voice, data, USBAUDIO_PACKET_SIZE); @@ -628,7 +628,7 @@ static void usb_audio_handle_destroy(USBDevice *dev) streambuf_fini(&s->out.buf); } -static int usb_audio_initfn(USBDevice *dev) +static void usb_audio_realize(USBDevice *dev, Error **errp) { USBAudioState *s = DO_UPCAST(USBAudioState, dev, dev); @@ -651,7 +651,6 @@ static int usb_audio_initfn(USBDevice *dev) s, output_callback, &s->out.as); AUD_set_volume_out(s->out.voice, s->out.mute, s->out.vol[0], s->out.vol[1]); AUD_set_active_out(s->out.voice, 0); - return 0; } static const VMStateDescription vmstate_usb_audio = { @@ -676,7 +675,7 @@ static void usb_audio_class_init(ObjectClass *klass, void *data) set_bit(DEVICE_CATEGORY_SOUND, dc->categories); k->product_desc = "QEMU USB Audio Interface"; k->usb_desc = &desc_audio; - k->init = usb_audio_initfn; + k->realize = usb_audio_realize; k->handle_reset = usb_audio_handle_reset; k->handle_control = usb_audio_handle_control; k->handle_data = usb_audio_handle_data; diff --git a/hw/usb/dev-bluetooth.c b/hw/usb/dev-bluetooth.c index a9661d2801..390d475c16 100644 --- a/hw/usb/dev-bluetooth.c +++ b/hw/usb/dev-bluetooth.c @@ -19,6 +19,7 @@ */ #include "qemu-common.h" +#include "qemu/error-report.h" #include "hw/usb.h" #include "hw/usb/desc.h" #include "sysemu/bt.h" @@ -500,15 +501,21 @@ static void usb_bt_handle_destroy(USBDevice *dev) s->hci->acl_recv = NULL; } -static int usb_bt_initfn(USBDevice *dev) +static void usb_bt_realize(USBDevice *dev, Error **errp) { struct USBBtState *s = DO_UPCAST(struct USBBtState, dev, dev); usb_desc_create_serial(dev); usb_desc_init(dev); + s->dev.opaque = s; + if (!s->hci) { + s->hci = bt_new_hci(qemu_find_bt_vlan(0)); + } + s->hci->opaque = s; + s->hci->evt_recv = usb_bt_out_hci_packet_event; + s->hci->acl_recv = usb_bt_out_hci_packet_acl; + usb_bt_handle_reset(&s->dev); s->intr = usb_ep_get(dev, USB_TOKEN_IN, USB_EVT_EP); - - return 0; } static USBDevice *usb_bt_init(USBBus *bus, const char *cmdline) @@ -516,6 +523,7 @@ static USBDevice *usb_bt_init(USBBus *bus, const char *cmdline) USBDevice *dev; struct USBBtState *s; HCIInfo *hci; + const char *name = "usb-bt-dongle"; if (*cmdline) { hci = hci_init(cmdline); @@ -525,19 +533,17 @@ static USBDevice *usb_bt_init(USBBus *bus, const char *cmdline) if (!hci) return NULL; - dev = usb_create_simple(bus, "usb-bt-dongle"); + dev = usb_create(bus, name); if (!dev) { + error_report("Failed to create USB device '%s'", name); return NULL; } s = DO_UPCAST(struct USBBtState, dev, dev); - s->dev.opaque = s; - s->hci = hci; - s->hci->opaque = s; - s->hci->evt_recv = usb_bt_out_hci_packet_event; - s->hci->acl_recv = usb_bt_out_hci_packet_acl; - - usb_bt_handle_reset(&s->dev); + if (qdev_init(&dev->qdev) < 0) { + error_report("Failed to initialize USB device '%s'", name); + return NULL; + } return dev; } @@ -552,7 +558,7 @@ static void usb_bt_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_bt_initfn; + uc->realize = usb_bt_realize; uc->product_desc = "QEMU BT dongle"; uc->usb_desc = &desc_bluetooth; uc->handle_reset = usb_bt_handle_reset; diff --git a/hw/usb/dev-hid.c b/hw/usb/dev-hid.c index f36e617632..507c9663c5 100644 --- a/hw/usb/dev-hid.c +++ b/hw/usb/dev-hid.c @@ -47,6 +47,8 @@ typedef struct USBHIDState { USBEndpoint *intr; HIDState hid; uint32_t usb_version; + char *display; + uint32_t head; } USBHIDState; enum { @@ -102,6 +104,37 @@ static const USBDescIface desc_iface_mouse = { }, }; +static const USBDescIface desc_iface_mouse2 = { + .bInterfaceNumber = 0, + .bNumEndpoints = 1, + .bInterfaceClass = USB_CLASS_HID, + .bInterfaceSubClass = 0x01, /* boot */ + .bInterfaceProtocol = 0x02, + .ndesc = 1, + .descs = (USBDescOther[]) { + { + /* HID descriptor */ + .data = (uint8_t[]) { + 0x09, /* u8 bLength */ + USB_DT_HID, /* u8 bDescriptorType */ + 0x01, 0x00, /* u16 HID_class */ + 0x00, /* u8 country_code */ + 0x01, /* u8 num_descriptors */ + USB_DT_REPORT, /* u8 type: Report */ + 52, 0, /* u16 len */ + }, + }, + }, + .eps = (USBDescEndpoint[]) { + { + .bEndpointAddress = USB_DIR_IN | 0x01, + .bmAttributes = USB_ENDPOINT_XFER_INT, + .wMaxPacketSize = 4, + .bInterval = 7, /* 2 ^ (8-1) * 125 usecs = 8 ms */ + }, + }, +}; + static const USBDescIface desc_iface_tablet = { .bInterfaceNumber = 0, .bNumEndpoints = 1, @@ -193,6 +226,37 @@ static const USBDescIface desc_iface_keyboard = { }, }; +static const USBDescIface desc_iface_keyboard2 = { + .bInterfaceNumber = 0, + .bNumEndpoints = 1, + .bInterfaceClass = USB_CLASS_HID, + .bInterfaceSubClass = 0x01, /* boot */ + .bInterfaceProtocol = 0x01, /* keyboard */ + .ndesc = 1, + .descs = (USBDescOther[]) { + { + /* HID descriptor */ + .data = (uint8_t[]) { + 0x09, /* u8 bLength */ + USB_DT_HID, /* u8 bDescriptorType */ + 0x11, 0x01, /* u16 HID_class */ + 0x00, /* u8 country_code */ + 0x01, /* u8 num_descriptors */ + USB_DT_REPORT, /* u8 type: Report */ + 0x3f, 0, /* u16 len */ + }, + }, + }, + .eps = (USBDescEndpoint[]) { + { + .bEndpointAddress = USB_DIR_IN | 0x01, + .bmAttributes = USB_ENDPOINT_XFER_INT, + .wMaxPacketSize = 8, + .bInterval = 7, /* 2 ^ (8-1) * 125 usecs = 8 ms */ + }, + }, +}; + static const USBDescDevice desc_device_mouse = { .bcdUSB = 0x0100, .bMaxPacketSize0 = 8, @@ -210,6 +274,23 @@ static const USBDescDevice desc_device_mouse = { }, }; +static const USBDescDevice desc_device_mouse2 = { + .bcdUSB = 0x0200, + .bMaxPacketSize0 = 64, + .bNumConfigurations = 1, + .confs = (USBDescConfig[]) { + { + .bNumInterfaces = 1, + .bConfigurationValue = 1, + .iConfiguration = STR_CONFIG_MOUSE, + .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP, + .bMaxPower = 50, + .nif = 1, + .ifs = &desc_iface_mouse2, + }, + }, +}; + static const USBDescDevice desc_device_tablet = { .bcdUSB = 0x0100, .bMaxPacketSize0 = 8, @@ -261,6 +342,23 @@ static const USBDescDevice desc_device_keyboard = { }, }; +static const USBDescDevice desc_device_keyboard2 = { + .bcdUSB = 0x0200, + .bMaxPacketSize0 = 64, + .bNumConfigurations = 1, + .confs = (USBDescConfig[]) { + { + .bNumInterfaces = 1, + .bConfigurationValue = 1, + .iConfiguration = STR_CONFIG_KEYBOARD, + .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP, + .bMaxPower = 50, + .nif = 1, + .ifs = &desc_iface_keyboard2, + }, + }, +}; + static const USBDescMSOS desc_msos_suspend = { .SelectiveSuspendEnabled = true, }; @@ -279,6 +377,21 @@ static const USBDesc desc_mouse = { .msos = &desc_msos_suspend, }; +static const USBDesc desc_mouse2 = { + .id = { + .idVendor = 0x0627, + .idProduct = 0x0001, + .bcdDevice = 0, + .iManufacturer = STR_MANUFACTURER, + .iProduct = STR_PRODUCT_MOUSE, + .iSerialNumber = STR_SERIALNUMBER, + }, + .full = &desc_device_mouse, + .high = &desc_device_mouse2, + .str = desc_strings, + .msos = &desc_msos_suspend, +}; + static const USBDesc desc_tablet = { .id = { .idVendor = 0x0627, @@ -322,6 +435,21 @@ static const USBDesc desc_keyboard = { .msos = &desc_msos_suspend, }; +static const USBDesc desc_keyboard2 = { + .id = { + .idVendor = 0x0627, + .idProduct = 0x0001, + .bcdDevice = 0, + .iManufacturer = STR_MANUFACTURER, + .iProduct = STR_PRODUCT_KEYBOARD, + .iSerialNumber = STR_SERIALNUMBER, + }, + .full = &desc_device_keyboard, + .high = &desc_device_keyboard2, + .str = desc_strings, + .msos = &desc_msos_suspend, +}; + static const uint8_t qemu_mouse_hid_report_descriptor[] = { 0x05, 0x01, /* Usage Page (Generic Desktop) */ 0x09, 0x02, /* Usage (Mouse) */ @@ -564,9 +692,26 @@ static void usb_hid_handle_destroy(USBDevice *dev) hid_free(&us->hid); } -static int usb_hid_initfn(USBDevice *dev, int kind) +static void usb_hid_initfn(USBDevice *dev, int kind, + const USBDesc *usb1, const USBDesc *usb2, + Error **errp) { USBHIDState *us = DO_UPCAST(USBHIDState, dev, dev); + switch (us->usb_version) { + case 1: + dev->usb_desc = usb1; + break; + case 2: + dev->usb_desc = usb2; + break; + default: + dev->usb_desc = NULL; + } + if (!dev->usb_desc) { + error_setg(errp, "Invalid usb version %d for usb hid device", + us->usb_version); + return; + } if (dev->serial) { usb_desc_set_string(dev, STR_SERIALNUMBER, dev->serial); @@ -574,37 +719,25 @@ static int usb_hid_initfn(USBDevice *dev, int kind) usb_desc_init(dev); us->intr = usb_ep_get(dev, USB_TOKEN_IN, 1); hid_init(&us->hid, kind, usb_hid_changed); - return 0; + if (us->display && us->hid.s) { + qemu_input_handler_bind(us->hid.s, us->display, us->head, NULL); + } } -static int usb_tablet_initfn(USBDevice *dev) +static void usb_tablet_realize(USBDevice *dev, Error **errp) { - USBHIDState *us = DO_UPCAST(USBHIDState, dev, dev); - - switch (us->usb_version) { - case 1: - dev->usb_desc = &desc_tablet; - break; - case 2: - dev->usb_desc = &desc_tablet2; - break; - default: - error_report("Invalid usb version %d for usb-tabler (must be 1 or 2)", - us->usb_version); - return -1; - } - return usb_hid_initfn(dev, HID_TABLET); + usb_hid_initfn(dev, HID_TABLET, &desc_tablet, &desc_tablet2, errp); } -static int usb_mouse_initfn(USBDevice *dev) +static void usb_mouse_realize(USBDevice *dev, Error **errp) { - return usb_hid_initfn(dev, HID_MOUSE); + usb_hid_initfn(dev, HID_MOUSE, &desc_mouse, &desc_mouse2, errp); } -static int usb_keyboard_initfn(USBDevice *dev) +static void usb_keyboard_realize(USBDevice *dev, Error **errp) { - return usb_hid_initfn(dev, HID_KEYBOARD); + usb_hid_initfn(dev, HID_KEYBOARD, &desc_keyboard, &desc_keyboard2, errp); } static int usb_ptr_post_load(void *opaque, int version_id) @@ -622,7 +755,7 @@ static const VMStateDescription vmstate_usb_ptr = { .version_id = 1, .minimum_version_id = 1, .post_load = usb_ptr_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_USB_DEVICE(dev, USBHIDState), VMSTATE_HID_POINTER_DEVICE(hid, USBHIDState), VMSTATE_END_OF_LIST() @@ -633,7 +766,7 @@ static const VMStateDescription vmstate_usb_kbd = { .name = "usb-kbd", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_USB_DEVICE(dev, USBHIDState), VMSTATE_HID_KEYBOARD_DEVICE(hid, USBHIDState), VMSTATE_END_OF_LIST() @@ -653,6 +786,8 @@ static void usb_hid_class_initfn(ObjectClass *klass, void *data) static Property usb_tablet_properties[] = { DEFINE_PROP_UINT32("usb_version", USBHIDState, usb_version, 2), + DEFINE_PROP_STRING("display", USBHIDState, display), + DEFINE_PROP_UINT32("head", USBHIDState, head, 0), DEFINE_PROP_END_OF_LIST(), }; @@ -662,7 +797,7 @@ static void usb_tablet_class_initfn(ObjectClass *klass, void *data) USBDeviceClass *uc = USB_DEVICE_CLASS(klass); usb_hid_class_initfn(klass, data); - uc->init = usb_tablet_initfn; + uc->realize = usb_tablet_realize; uc->product_desc = "QEMU USB Tablet"; dc->vmsd = &vmstate_usb_ptr; dc->props = usb_tablet_properties; @@ -676,16 +811,21 @@ static const TypeInfo usb_tablet_info = { .class_init = usb_tablet_class_initfn, }; +static Property usb_mouse_properties[] = { + DEFINE_PROP_UINT32("usb_version", USBHIDState, usb_version, 2), + DEFINE_PROP_END_OF_LIST(), +}; + static void usb_mouse_class_initfn(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); usb_hid_class_initfn(klass, data); - uc->init = usb_mouse_initfn; + uc->realize = usb_mouse_realize; uc->product_desc = "QEMU USB Mouse"; - uc->usb_desc = &desc_mouse; dc->vmsd = &vmstate_usb_ptr; + dc->props = usb_mouse_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); } @@ -696,16 +836,22 @@ static const TypeInfo usb_mouse_info = { .class_init = usb_mouse_class_initfn, }; +static Property usb_keyboard_properties[] = { + DEFINE_PROP_UINT32("usb_version", USBHIDState, usb_version, 2), + DEFINE_PROP_STRING("display", USBHIDState, display), + DEFINE_PROP_END_OF_LIST(), +}; + static void usb_keyboard_class_initfn(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); usb_hid_class_initfn(klass, data); - uc->init = usb_keyboard_initfn; + uc->realize = usb_keyboard_realize; uc->product_desc = "QEMU USB Keyboard"; - uc->usb_desc = &desc_keyboard; dc->vmsd = &vmstate_usb_kbd; + dc->props = usb_keyboard_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); } diff --git a/hw/usb/dev-hub.c b/hw/usb/dev-hub.c index bc03531666..0482f58719 100644 --- a/hw/usb/dev-hub.c +++ b/hw/usb/dev-hub.c @@ -511,15 +511,15 @@ static USBPortOps usb_hub_port_ops = { .complete = usb_hub_complete, }; -static int usb_hub_initfn(USBDevice *dev) +static void usb_hub_realize(USBDevice *dev, Error **errp) { USBHubState *s = DO_UPCAST(USBHubState, dev, dev); USBHubPort *port; int i; if (dev->port->hubcount == 5) { - error_report("usb hub chain too deep"); - return -1; + error_setg(errp, "usb hub chain too deep"); + return; } usb_desc_create_serial(dev); @@ -533,14 +533,13 @@ static int usb_hub_initfn(USBDevice *dev) usb_port_location(&port->port, dev->port, i+1); } usb_hub_handle_reset(dev); - return 0; } static const VMStateDescription vmstate_usb_hub_port = { .name = "usb-hub-port", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(wPortStatus, USBHubPort), VMSTATE_UINT16(wPortChange, USBHubPort), VMSTATE_END_OF_LIST() @@ -551,7 +550,7 @@ static const VMStateDescription vmstate_usb_hub = { .name = "usb-hub", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_USB_DEVICE(dev, USBHubState), VMSTATE_STRUCT_ARRAY(ports, USBHubState, NUM_PORTS, 0, vmstate_usb_hub_port, USBHubPort), @@ -564,7 +563,7 @@ static void usb_hub_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_hub_initfn; + uc->realize = usb_hub_realize; uc->product_desc = "QEMU USB Hub"; uc->usb_desc = &desc_hub; uc->find_device = usb_hub_find_device; diff --git a/hw/usb/dev-mtp.c b/hw/usb/dev-mtp.c new file mode 100644 index 0000000000..108ece8190 --- /dev/null +++ b/hw/usb/dev-mtp.c @@ -0,0 +1,1127 @@ +/* + * Media Transfer Protocol implementation, backed by host filesystem. + * + * Copyright Red Hat, Inc 2014 + * + * Author: + * Gerd Hoffmann <kraxel@redhat.com> + * + * This code is licensed under the GPL v2 or later. + */ + +#include <wchar.h> +#include <dirent.h> +#include <unistd.h> + +#include <sys/stat.h> +#include <sys/statvfs.h> + +#include "qemu-common.h" +#include "qemu/iov.h" +#include "trace.h" +#include "hw/usb.h" +#include "hw/usb/desc.h" + +/* ----------------------------------------------------------------------- */ + +enum mtp_container_type { + TYPE_COMMAND = 1, + TYPE_DATA = 2, + TYPE_RESPONSE = 3, + TYPE_EVENT = 4, +}; + +enum mtp_code { + /* command codes */ + CMD_GET_DEVICE_INFO = 0x1001, + CMD_OPEN_SESSION = 0x1002, + CMD_CLOSE_SESSION = 0x1003, + CMD_GET_STORAGE_IDS = 0x1004, + CMD_GET_STORAGE_INFO = 0x1005, + CMD_GET_NUM_OBJECTS = 0x1006, + CMD_GET_OBJECT_HANDLES = 0x1007, + CMD_GET_OBJECT_INFO = 0x1008, + CMD_GET_OBJECT = 0x1009, + CMD_GET_PARTIAL_OBJECT = 0x101b, + + /* response codes */ + RES_OK = 0x2001, + RES_GENERAL_ERROR = 0x2002, + RES_SESSION_NOT_OPEN = 0x2003, + RES_INVALID_TRANSACTION_ID = 0x2004, + RES_OPERATION_NOT_SUPPORTED = 0x2005, + RES_PARAMETER_NOT_SUPPORTED = 0x2006, + RES_INCOMPLETE_TRANSFER = 0x2007, + RES_INVALID_STORAGE_ID = 0x2008, + RES_INVALID_OBJECT_HANDLE = 0x2009, + RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014, + RES_INVALID_PARENT_OBJECT = 0x201a, + RES_INVALID_PARAMETER = 0x201d, + RES_SESSION_ALREADY_OPEN = 0x201e, + + /* format codes */ + FMT_UNDEFINED_OBJECT = 0x3000, + FMT_ASSOCIATION = 0x3001, +}; + +typedef struct { + uint32_t length; + uint16_t type; + uint16_t code; + uint32_t trans; +} QEMU_PACKED mtp_container; + +/* ----------------------------------------------------------------------- */ + +typedef struct MTPState MTPState; +typedef struct MTPControl MTPControl; +typedef struct MTPData MTPData; +typedef struct MTPObject MTPObject; + +enum { + EP_DATA_IN = 1, + EP_DATA_OUT, + EP_EVENT, +}; + +struct MTPControl { + uint16_t code; + uint32_t trans; + int argc; + uint32_t argv[5]; +}; + +struct MTPData { + uint16_t code; + uint32_t trans; + uint32_t offset; + uint32_t length; + uint32_t alloc; + uint8_t *data; + bool first; + int fd; +}; + +struct MTPObject { + uint32_t handle; + uint16_t format; + char *name; + char *path; + struct stat stat; + MTPObject *parent; + MTPObject **children; + uint32_t nchildren; + bool have_children; + QTAILQ_ENTRY(MTPObject) next; +}; + +struct MTPState { + USBDevice dev; + char *root; + char *desc; + uint32_t flags; + + MTPData *data_in; + MTPData *data_out; + MTPControl *result; + uint32_t session; + uint32_t next_handle; + + QTAILQ_HEAD(, MTPObject) objects; +}; + +#define QEMU_STORAGE_ID 0x00010001 + +#define MTP_FLAG_WRITABLE 0 + +#define FLAG_SET(_mtp, _flag) ((_mtp)->flags & (1 << (_flag))) + +/* ----------------------------------------------------------------------- */ + +#define MTP_MANUFACTURER "QEMU" +#define MTP_PRODUCT "QEMU filesharing" + +enum { + STR_MANUFACTURER = 1, + STR_PRODUCT, + STR_SERIALNUMBER, + STR_MTP, + STR_CONFIG_FULL, + STR_CONFIG_HIGH, + STR_CONFIG_SUPER, +}; + +static const USBDescStrings desc_strings = { + [STR_MANUFACTURER] = MTP_MANUFACTURER, + [STR_PRODUCT] = MTP_PRODUCT, + [STR_SERIALNUMBER] = "34617", + [STR_MTP] = "MTP", + [STR_CONFIG_FULL] = "Full speed config (usb 1.1)", + [STR_CONFIG_HIGH] = "High speed config (usb 2.0)", + [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)", +}; + +static const USBDescIface desc_iface_full = { + .bInterfaceNumber = 0, + .bNumEndpoints = 3, + .bInterfaceClass = USB_CLASS_STILL_IMAGE, + .bInterfaceSubClass = 0x01, + .bInterfaceProtocol = 0x01, + .iInterface = STR_MTP, + .eps = (USBDescEndpoint[]) { + { + .bEndpointAddress = USB_DIR_IN | EP_DATA_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = 64, + },{ + .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = 64, + },{ + .bEndpointAddress = USB_DIR_IN | EP_EVENT, + .bmAttributes = USB_ENDPOINT_XFER_INT, + .wMaxPacketSize = 8, + .bInterval = 0x0a, + }, + } +}; + +static const USBDescDevice desc_device_full = { + .bcdUSB = 0x0200, + .bMaxPacketSize0 = 8, + .bNumConfigurations = 1, + .confs = (USBDescConfig[]) { + { + .bNumInterfaces = 1, + .bConfigurationValue = 1, + .iConfiguration = STR_CONFIG_FULL, + .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP, + .bMaxPower = 2, + .nif = 1, + .ifs = &desc_iface_full, + }, + }, +}; + +static const USBDescIface desc_iface_high = { + .bInterfaceNumber = 0, + .bNumEndpoints = 3, + .bInterfaceClass = USB_CLASS_STILL_IMAGE, + .bInterfaceSubClass = 0x01, + .bInterfaceProtocol = 0x01, + .iInterface = STR_MTP, + .eps = (USBDescEndpoint[]) { + { + .bEndpointAddress = USB_DIR_IN | EP_DATA_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = 512, + },{ + .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = 512, + },{ + .bEndpointAddress = USB_DIR_IN | EP_EVENT, + .bmAttributes = USB_ENDPOINT_XFER_INT, + .wMaxPacketSize = 8, + .bInterval = 0x0a, + }, + } +}; + +static const USBDescDevice desc_device_high = { + .bcdUSB = 0x0200, + .bMaxPacketSize0 = 64, + .bNumConfigurations = 1, + .confs = (USBDescConfig[]) { + { + .bNumInterfaces = 1, + .bConfigurationValue = 1, + .iConfiguration = STR_CONFIG_HIGH, + .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP, + .bMaxPower = 2, + .nif = 1, + .ifs = &desc_iface_high, + }, + }, +}; + +static const USBDescMSOS desc_msos = { + .CompatibleID = "MTP", + .SelectiveSuspendEnabled = true, +}; + +static const USBDesc desc = { + .id = { + .idVendor = 0x46f4, /* CRC16() of "QEMU" */ + .idProduct = 0x0004, + .bcdDevice = 0, + .iManufacturer = STR_MANUFACTURER, + .iProduct = STR_PRODUCT, + .iSerialNumber = STR_SERIALNUMBER, + }, + .full = &desc_device_full, + .high = &desc_device_high, + .str = desc_strings, + .msos = &desc_msos, +}; + +/* ----------------------------------------------------------------------- */ + +static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle, + MTPObject *parent, char *name) +{ + MTPObject *o = g_new0(MTPObject, 1); + + if (name[0] == '.') { + goto ignore; + } + + o->handle = handle; + o->parent = parent; + o->name = g_strdup(name); + if (parent == NULL) { + o->path = g_strdup(name); + } else { + o->path = g_strdup_printf("%s/%s", parent->path, name); + } + + if (lstat(o->path, &o->stat) != 0) { + goto ignore; + } + if (S_ISREG(o->stat.st_mode)) { + o->format = FMT_UNDEFINED_OBJECT; + } else if (S_ISDIR(o->stat.st_mode)) { + o->format = FMT_ASSOCIATION; + } else { + goto ignore; + } + + if (access(o->path, R_OK) != 0) { + goto ignore; + } + + trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path); + + QTAILQ_INSERT_TAIL(&s->objects, o, next); + return o; + +ignore: + g_free(o->name); + g_free(o->path); + g_free(o); + return NULL; +} + +static void usb_mtp_object_free(MTPState *s, MTPObject *o) +{ + int i; + + trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path); + + QTAILQ_REMOVE(&s->objects, o, next); + for (i = 0; i < o->nchildren; i++) { + usb_mtp_object_free(s, o->children[i]); + } + g_free(o->children); + g_free(o->name); + g_free(o->path); + g_free(o); +} + +static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle) +{ + MTPObject *o; + + QTAILQ_FOREACH(o, &s->objects, next) { + if (o->handle == handle) { + return o; + } + } + return NULL; +} + +static void usb_mtp_object_readdir(MTPState *s, MTPObject *o) +{ + struct dirent *entry; + DIR *dir; + + if (o->have_children) { + return; + } + o->have_children = true; + + dir = opendir(o->path); + if (!dir) { + return; + } + while ((entry = readdir(dir)) != NULL) { + if ((o->nchildren % 32) == 0) { + o->children = g_realloc(o->children, + (o->nchildren + 32) * sizeof(MTPObject *)); + } + o->children[o->nchildren] = + usb_mtp_object_alloc(s, s->next_handle++, o, entry->d_name); + if (o->children[o->nchildren] != NULL) { + o->nchildren++; + } + } + closedir(dir); +} + +/* ----------------------------------------------------------------------- */ + +static MTPData *usb_mtp_data_alloc(MTPControl *c) +{ + MTPData *data = g_new0(MTPData, 1); + + data->code = c->code; + data->trans = c->trans; + data->fd = -1; + data->first = true; + return data; +} + +static void usb_mtp_data_free(MTPData *data) +{ + if (data == NULL) { + return; + } + if (data->fd != -1) { + close(data->fd); + } + g_free(data->data); + g_free(data); +} + +static void usb_mtp_realloc(MTPData *data, uint32_t bytes) +{ + if (data->length + bytes <= data->alloc) { + return; + } + data->alloc = (data->length + bytes + 0xff) & ~0xff; + data->data = g_realloc(data->data, data->alloc); +} + +static void usb_mtp_add_u8(MTPData *data, uint8_t val) +{ + usb_mtp_realloc(data, 1); + data->data[data->length++] = val; +} + +static void usb_mtp_add_u16(MTPData *data, uint16_t val) +{ + usb_mtp_realloc(data, 2); + data->data[data->length++] = (val >> 0) & 0xff; + data->data[data->length++] = (val >> 8) & 0xff; +} + +static void usb_mtp_add_u32(MTPData *data, uint32_t val) +{ + usb_mtp_realloc(data, 4); + data->data[data->length++] = (val >> 0) & 0xff; + data->data[data->length++] = (val >> 8) & 0xff; + data->data[data->length++] = (val >> 16) & 0xff; + data->data[data->length++] = (val >> 24) & 0xff; +} + +static void usb_mtp_add_u64(MTPData *data, uint64_t val) +{ + usb_mtp_realloc(data, 8); + data->data[data->length++] = (val >> 0) & 0xff; + data->data[data->length++] = (val >> 8) & 0xff; + data->data[data->length++] = (val >> 16) & 0xff; + data->data[data->length++] = (val >> 24) & 0xff; + data->data[data->length++] = (val >> 32) & 0xff; + data->data[data->length++] = (val >> 40) & 0xff; + data->data[data->length++] = (val >> 48) & 0xff; + data->data[data->length++] = (val >> 56) & 0xff; +} + +static void usb_mtp_add_u16_array(MTPData *data, uint32_t len, + const uint16_t *vals) +{ + int i; + + usb_mtp_add_u32(data, len); + for (i = 0; i < len; i++) { + usb_mtp_add_u16(data, vals[i]); + } +} + +static void usb_mtp_add_u32_array(MTPData *data, uint32_t len, + const uint32_t *vals) +{ + int i; + + usb_mtp_add_u32(data, len); + for (i = 0; i < len; i++) { + usb_mtp_add_u32(data, vals[i]); + } +} + +static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str) +{ + uint32_t len = wcslen(str); + int i; + + if (len > 0) { + len++; /* include terminating L'\0' */ + } + + usb_mtp_add_u8(data, len); + for (i = 0; i < len; i++) { + usb_mtp_add_u16(data, str[i]); + } +} + +static void usb_mtp_add_str(MTPData *data, const char *str) +{ + uint32_t len = strlen(str)+1; + wchar_t wstr[len]; + size_t ret; + + ret = mbstowcs(wstr, str, len); + if (ret == -1) { + usb_mtp_add_wstr(data, L"Oops"); + } else { + usb_mtp_add_wstr(data, wstr); + } +} + +static void usb_mtp_add_time(MTPData *data, time_t time) +{ + char buf[16]; + struct tm tm; + + gmtime_r(&time, &tm); + strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm); + usb_mtp_add_str(data, buf); +} + +/* ----------------------------------------------------------------------- */ + +static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans, + int argc, uint32_t arg0, uint32_t arg1) +{ + MTPControl *c = g_new0(MTPControl, 1); + + c->code = code; + c->trans = trans; + c->argc = argc; + if (argc > 0) { + c->argv[0] = arg0; + } + if (argc > 1) { + c->argv[1] = arg1; + } + + assert(s->result == NULL); + s->result = c; +} + +/* ----------------------------------------------------------------------- */ + +static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c) +{ + static const uint16_t ops[] = { + CMD_GET_DEVICE_INFO, + CMD_OPEN_SESSION, + CMD_CLOSE_SESSION, + CMD_GET_STORAGE_IDS, + CMD_GET_STORAGE_INFO, + CMD_GET_NUM_OBJECTS, + CMD_GET_OBJECT_HANDLES, + CMD_GET_OBJECT_INFO, + CMD_GET_OBJECT, + CMD_GET_PARTIAL_OBJECT, + }; + static const uint16_t fmt[] = { + FMT_UNDEFINED_OBJECT, + FMT_ASSOCIATION, + }; + MTPData *d = usb_mtp_data_alloc(c); + + trace_usb_mtp_op_get_device_info(s->dev.addr); + + usb_mtp_add_u16(d, 100); + usb_mtp_add_u32(d, 0xffffffff); + usb_mtp_add_u16(d, 0x0101); + usb_mtp_add_wstr(d, L""); + usb_mtp_add_u16(d, 0x0000); + + usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops); + usb_mtp_add_u16_array(d, 0, NULL); + usb_mtp_add_u16_array(d, 0, NULL); + usb_mtp_add_u16_array(d, 0, NULL); + usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt); + + usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER); + usb_mtp_add_wstr(d, L"" MTP_PRODUCT); + usb_mtp_add_wstr(d, L"0.1"); + usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef"); + + return d; +} + +static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c) +{ + static const uint32_t ids[] = { + QEMU_STORAGE_ID, + }; + MTPData *d = usb_mtp_data_alloc(c); + + trace_usb_mtp_op_get_storage_ids(s->dev.addr); + + usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids); + + return d; +} + +static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c) +{ + MTPData *d = usb_mtp_data_alloc(c); + struct statvfs buf; + int rc; + + trace_usb_mtp_op_get_storage_info(s->dev.addr); + + if (FLAG_SET(s, MTP_FLAG_WRITABLE)) { + usb_mtp_add_u16(d, 0x0003); + usb_mtp_add_u16(d, 0x0002); + usb_mtp_add_u16(d, 0x0000); + } else { + usb_mtp_add_u16(d, 0x0001); + usb_mtp_add_u16(d, 0x0002); + usb_mtp_add_u16(d, 0x0001); + } + + rc = statvfs(s->root, &buf); + if (rc == 0) { + usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks); + usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks); + usb_mtp_add_u32(d, buf.f_ffree); + } else { + usb_mtp_add_u64(d, 0xffffffff); + usb_mtp_add_u64(d, 0xffffffff); + usb_mtp_add_u32(d, 0xffffffff); + } + + usb_mtp_add_str(d, s->desc); + usb_mtp_add_wstr(d, L"123456789abcdef"); + return d; +} + +static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c, + MTPObject *o) +{ + MTPData *d = usb_mtp_data_alloc(c); + uint32_t i, handles[o->nchildren]; + + trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path); + + for (i = 0; i < o->nchildren; i++) { + handles[i] = o->children[i]->handle; + } + usb_mtp_add_u32_array(d, o->nchildren, handles); + + return d; +} + +static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c, + MTPObject *o) +{ + MTPData *d = usb_mtp_data_alloc(c); + + trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path); + + usb_mtp_add_u32(d, QEMU_STORAGE_ID); + usb_mtp_add_u16(d, o->format); + usb_mtp_add_u16(d, 0); + usb_mtp_add_u32(d, o->stat.st_size); + + usb_mtp_add_u16(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + + if (o->parent) { + usb_mtp_add_u32(d, o->parent->handle); + } else { + usb_mtp_add_u32(d, 0); + } + if (o->format == FMT_ASSOCIATION) { + usb_mtp_add_u16(d, 0x0001); + usb_mtp_add_u32(d, 0x00000001); + usb_mtp_add_u32(d, 0); + } else { + usb_mtp_add_u16(d, 0); + usb_mtp_add_u32(d, 0); + usb_mtp_add_u32(d, 0); + } + + usb_mtp_add_str(d, o->name); + usb_mtp_add_time(d, o->stat.st_ctime); + usb_mtp_add_time(d, o->stat.st_mtime); + usb_mtp_add_wstr(d, L""); + + return d; +} + +static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c, + MTPObject *o) +{ + MTPData *d = usb_mtp_data_alloc(c); + + trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path); + + d->fd = open(o->path, O_RDONLY); + if (d->fd == -1) { + usb_mtp_data_free(d); + return NULL; + } + d->length = o->stat.st_size; + d->alloc = 512; + d->data = g_malloc(d->alloc); + return d; +} + +static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c, + MTPObject *o) +{ + MTPData *d = usb_mtp_data_alloc(c); + off_t offset; + + trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path, + c->argv[1], c->argv[2]); + + d->fd = open(o->path, O_RDONLY); + if (d->fd == -1) { + usb_mtp_data_free(d); + return NULL; + } + + offset = c->argv[1]; + if (offset > o->stat.st_size) { + offset = o->stat.st_size; + } + if (lseek(d->fd, offset, SEEK_SET) < 0) { + usb_mtp_data_free(d); + return NULL; + } + + d->length = c->argv[2]; + if (d->length > o->stat.st_size - offset) { + d->length = o->stat.st_size - offset; + } + + return d; +} + +static void usb_mtp_command(MTPState *s, MTPControl *c) +{ + MTPData *data_in = NULL; + MTPObject *o; + uint32_t nres = 0, res0 = 0; + + /* sanity checks */ + if (c->code >= CMD_CLOSE_SESSION && s->session == 0) { + usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN, + c->trans, 0, 0, 0); + return; + } + + /* process commands */ + switch (c->code) { + case CMD_GET_DEVICE_INFO: + data_in = usb_mtp_get_device_info(s, c); + break; + case CMD_OPEN_SESSION: + if (s->session) { + usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN, + c->trans, 1, s->session, 0); + return; + } + if (c->argv[0] == 0) { + usb_mtp_queue_result(s, RES_INVALID_PARAMETER, + c->trans, 0, 0, 0); + return; + } + trace_usb_mtp_op_open_session(s->dev.addr); + s->session = c->argv[0]; + usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root); + break; + case CMD_CLOSE_SESSION: + trace_usb_mtp_op_close_session(s->dev.addr); + s->session = 0; + s->next_handle = 0; + usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects)); + assert(QTAILQ_EMPTY(&s->objects)); + break; + case CMD_GET_STORAGE_IDS: + data_in = usb_mtp_get_storage_ids(s, c); + break; + case CMD_GET_STORAGE_INFO: + if (c->argv[0] != QEMU_STORAGE_ID && + c->argv[0] != 0xffffffff) { + usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID, + c->trans, 0, 0, 0); + return; + } + data_in = usb_mtp_get_storage_info(s, c); + break; + case CMD_GET_NUM_OBJECTS: + case CMD_GET_OBJECT_HANDLES: + if (c->argv[0] != QEMU_STORAGE_ID && + c->argv[0] != 0xffffffff) { + usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID, + c->trans, 0, 0, 0); + return; + } + if (c->argv[1] != 0x00000000) { + usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED, + c->trans, 0, 0, 0); + return; + } + if (c->argv[2] == 0x00000000 || + c->argv[2] == 0xffffffff) { + o = QTAILQ_FIRST(&s->objects); + } else { + o = usb_mtp_object_lookup(s, c->argv[2]); + } + if (o == NULL) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + if (o->format != FMT_ASSOCIATION) { + usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, + c->trans, 0, 0, 0); + return; + } + usb_mtp_object_readdir(s, o); + if (c->code == CMD_GET_NUM_OBJECTS) { + trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path); + nres = 1; + res0 = o->nchildren; + } else { + data_in = usb_mtp_get_object_handles(s, c, o); + } + break; + case CMD_GET_OBJECT_INFO: + o = usb_mtp_object_lookup(s, c->argv[0]); + if (o == NULL) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + data_in = usb_mtp_get_object_info(s, c, o); + break; + case CMD_GET_OBJECT: + o = usb_mtp_object_lookup(s, c->argv[0]); + if (o == NULL) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + if (o->format == FMT_ASSOCIATION) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + data_in = usb_mtp_get_object(s, c, o); + if (data_in == NULL) { + usb_mtp_queue_result(s, RES_GENERAL_ERROR, + c->trans, 0, 0, 0); + return; + } + break; + case CMD_GET_PARTIAL_OBJECT: + o = usb_mtp_object_lookup(s, c->argv[0]); + if (o == NULL) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + if (o->format == FMT_ASSOCIATION) { + usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, + c->trans, 0, 0, 0); + return; + } + data_in = usb_mtp_get_partial_object(s, c, o); + if (data_in == NULL) { + usb_mtp_queue_result(s, RES_GENERAL_ERROR, + c->trans, 0, 0, 0); + return; + } + nres = 1; + res0 = data_in->length; + break; + default: + trace_usb_mtp_op_unknown(s->dev.addr, c->code); + usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED, + c->trans, 0, 0, 0); + return; + } + + /* return results on success */ + if (data_in) { + assert(s->data_in == NULL); + s->data_in = data_in; + } + usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0); +} + +/* ----------------------------------------------------------------------- */ + +static void usb_mtp_handle_reset(USBDevice *dev) +{ + MTPState *s = DO_UPCAST(MTPState, dev, dev); + + trace_usb_mtp_reset(s->dev.addr); + + s->session = 0; + usb_mtp_data_free(s->data_in); + s->data_in = NULL; + usb_mtp_data_free(s->data_out); + s->data_out = NULL; + g_free(s->result); + s->result = NULL; +} + +static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p, + int request, int value, int index, + int length, uint8_t *data) +{ + int ret; + + ret = usb_desc_handle_control(dev, p, request, value, index, length, data); + if (ret >= 0) { + return; + } + + trace_usb_mtp_stall(dev->addr, "unknown control request"); + p->status = USB_RET_STALL; +} + +static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p) +{ + /* we don't use async packets, so this should never be called */ + fprintf(stderr, "%s\n", __func__); +} + +static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p) +{ + MTPState *s = DO_UPCAST(MTPState, dev, dev); + MTPControl cmd; + mtp_container container; + uint32_t params[5]; + int i, rc; + + switch (p->ep->nr) { + case EP_DATA_IN: + if (s->data_out != NULL) { + /* guest bug */ + trace_usb_mtp_stall(s->dev.addr, "awaiting data-out"); + p->status = USB_RET_STALL; + return; + } + if (p->iov.size < sizeof(container)) { + trace_usb_mtp_stall(s->dev.addr, "packet too small"); + p->status = USB_RET_STALL; + return; + } + if (s->data_in != NULL) { + MTPData *d = s->data_in; + int dlen = d->length - d->offset; + if (d->first) { + trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length); + container.length = cpu_to_le32(d->length + sizeof(container)); + container.type = cpu_to_le16(TYPE_DATA); + container.code = cpu_to_le16(d->code); + container.trans = cpu_to_le32(d->trans); + usb_packet_copy(p, &container, sizeof(container)); + d->first = false; + if (dlen > p->iov.size - sizeof(container)) { + dlen = p->iov.size - sizeof(container); + } + } else { + if (dlen > p->iov.size) { + dlen = p->iov.size; + } + } + if (d->fd == -1) { + usb_packet_copy(p, d->data + d->offset, dlen); + } else { + if (d->alloc < p->iov.size) { + d->alloc = p->iov.size; + d->data = g_realloc(d->data, d->alloc); + } + rc = read(d->fd, d->data, dlen); + if (rc != dlen) { + memset(d->data, 0, dlen); + s->result->code = RES_INCOMPLETE_TRANSFER; + } + usb_packet_copy(p, d->data, dlen); + } + d->offset += dlen; + if (d->offset == d->length) { + usb_mtp_data_free(s->data_in); + s->data_in = NULL; + } + } else if (s->result != NULL) { + MTPControl *r = s->result; + int length = sizeof(container) + r->argc * sizeof(uint32_t); + if (r->code == RES_OK) { + trace_usb_mtp_success(s->dev.addr, r->trans, + (r->argc > 0) ? r->argv[0] : 0, + (r->argc > 1) ? r->argv[1] : 0); + } else { + trace_usb_mtp_error(s->dev.addr, r->code, r->trans, + (r->argc > 0) ? r->argv[0] : 0, + (r->argc > 1) ? r->argv[1] : 0); + } + container.length = cpu_to_le32(length); + container.type = cpu_to_le16(TYPE_RESPONSE); + container.code = cpu_to_le16(r->code); + container.trans = cpu_to_le32(r->trans); + for (i = 0; i < r->argc; i++) { + params[i] = cpu_to_le32(r->argv[i]); + } + usb_packet_copy(p, &container, sizeof(container)); + usb_packet_copy(p, ¶ms, length - sizeof(container)); + g_free(s->result); + s->result = NULL; + } + break; + case EP_DATA_OUT: + if (p->iov.size < sizeof(container)) { + trace_usb_mtp_stall(s->dev.addr, "packet too small"); + p->status = USB_RET_STALL; + return; + } + usb_packet_copy(p, &container, sizeof(container)); + switch (le16_to_cpu(container.type)) { + case TYPE_COMMAND: + if (s->data_in || s->data_out || s->result) { + trace_usb_mtp_stall(s->dev.addr, "transaction inflight"); + p->status = USB_RET_STALL; + return; + } + cmd.code = le16_to_cpu(container.code); + cmd.argc = (le32_to_cpu(container.length) - sizeof(container)) + / sizeof(uint32_t); + cmd.trans = le32_to_cpu(container.trans); + if (cmd.argc > ARRAY_SIZE(cmd.argv)) { + cmd.argc = ARRAY_SIZE(cmd.argv); + } + if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) { + trace_usb_mtp_stall(s->dev.addr, "packet too small"); + p->status = USB_RET_STALL; + return; + } + usb_packet_copy(p, ¶ms, cmd.argc * sizeof(uint32_t)); + for (i = 0; i < cmd.argc; i++) { + cmd.argv[i] = le32_to_cpu(params[i]); + } + trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans, + (cmd.argc > 0) ? cmd.argv[0] : 0, + (cmd.argc > 1) ? cmd.argv[1] : 0, + (cmd.argc > 2) ? cmd.argv[2] : 0, + (cmd.argc > 3) ? cmd.argv[3] : 0, + (cmd.argc > 4) ? cmd.argv[4] : 0); + usb_mtp_command(s, &cmd); + break; + default: + /* not needed as long as the mtp device is read-only */ + p->status = USB_RET_STALL; + return; + } + break; + case EP_EVENT: + p->status = USB_RET_NAK; + return; + default: + trace_usb_mtp_stall(s->dev.addr, "invalid endpoint"); + p->status = USB_RET_STALL; + return; + } + + if (p->actual_length == 0) { + trace_usb_mtp_nak(s->dev.addr, p->ep->nr); + p->status = USB_RET_NAK; + return; + } else { + trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length, + p->iov.size); + return; + } +} + +static void usb_mtp_realize(USBDevice *dev, Error **errp) +{ + MTPState *s = DO_UPCAST(MTPState, dev, dev); + + usb_desc_create_serial(dev); + usb_desc_init(dev); + QTAILQ_INIT(&s->objects); + if (s->desc == NULL) { + s->desc = strrchr(s->root, '/'); + if (s->desc && s->desc[0]) { + s->desc = g_strdup(s->desc + 1); + } else { + s->desc = g_strdup("none"); + } + } +} + +static const VMStateDescription vmstate_usb_mtp = { + .name = "usb-mtp", + .unmigratable = 1, + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_USB_DEVICE(dev, MTPState), + VMSTATE_END_OF_LIST() + } +}; + +static Property mtp_properties[] = { + DEFINE_PROP_STRING("x-root", MTPState, root), + DEFINE_PROP_STRING("desc", MTPState, desc), + DEFINE_PROP_END_OF_LIST(), +}; + +static void usb_mtp_class_initfn(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + USBDeviceClass *uc = USB_DEVICE_CLASS(klass); + + uc->realize = usb_mtp_realize; + uc->product_desc = "QEMU USB MTP"; + uc->usb_desc = &desc; + uc->cancel_packet = usb_mtp_cancel_packet; + uc->handle_attach = usb_desc_attach; + uc->handle_reset = usb_mtp_handle_reset; + uc->handle_control = usb_mtp_handle_control; + uc->handle_data = usb_mtp_handle_data; + dc->fw_name = "mtp"; + dc->vmsd = &vmstate_usb_mtp; + dc->props = mtp_properties; +} + +static TypeInfo mtp_info = { + .name = "usb-mtp", + .parent = TYPE_USB_DEVICE, + .instance_size = sizeof(MTPState), + .class_init = usb_mtp_class_initfn, +}; + +static void usb_mtp_register_types(void) +{ + type_register_static(&mtp_info); +} + +type_init(usb_mtp_register_types) diff --git a/hw/usb/dev-network.c b/hw/usb/dev-network.c index 518d5366d1..5b95d5c382 100644 --- a/hw/usb/dev-network.c +++ b/hw/usb/dev-network.c @@ -27,7 +27,7 @@ #include "hw/usb.h" #include "hw/usb/desc.h" #include "net/net.h" -#include "qapi/qmp/qerror.h" +#include "qemu/error-report.h" #include "qemu/queue.h" #include "qemu/config-file.h" #include "sysemu/sysemu.h" @@ -1341,7 +1341,7 @@ static NetClientInfo net_usbnet_info = { .cleanup = usbnet_cleanup, }; -static int usb_net_initfn(USBDevice *dev) +static void usb_net_realize(USBDevice *dev, Error **errrp) { USBNetState *s = DO_UPCAST(USBNetState, dev, dev); @@ -1371,9 +1371,16 @@ static int usb_net_initfn(USBDevice *dev) s->conf.macaddr.a[4], s->conf.macaddr.a[5]); usb_desc_set_string(dev, STRING_ETHADDR, s->usbstring_mac); +} - add_boot_device_path(s->conf.bootindex, &dev->qdev, "/ethernet@0"); - return 0; +static void usb_net_instance_init(Object *obj) +{ + USBDevice *dev = USB_DEVICE(obj); + USBNetState *s = DO_UPCAST(USBNetState, dev, dev); + + device_add_bootindex_property(obj, &s->conf.bootindex, + "bootindex", "/ethernet-phy@0", + &dev->qdev, NULL); } static USBDevice *usb_net_init(USBBus *bus, const char *cmdline) @@ -1392,7 +1399,7 @@ static USBDevice *usb_net_init(USBBus *bus, const char *cmdline) idx = net_client_init(opts, 0, &local_err); if (local_err) { - qerror_report_err(local_err); + error_report("%s", error_get_pretty(local_err)); error_free(local_err); return NULL; } @@ -1421,7 +1428,7 @@ static void usb_net_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_net_initfn; + uc->realize = usb_net_realize; uc->product_desc = "QEMU USB Network Interface"; uc->usb_desc = &desc_net; uc->handle_reset = usb_net_handle_reset; @@ -1439,6 +1446,7 @@ static const TypeInfo net_info = { .parent = TYPE_USB_DEVICE, .instance_size = sizeof(USBNetState), .class_init = usb_net_class_initfn, + .instance_init = usb_net_instance_init, }; static void usb_net_register_types(void) diff --git a/hw/usb/dev-serial.c b/hw/usb/dev-serial.c index d3606142c9..1cee450259 100644 --- a/hw/usb/dev-serial.c +++ b/hw/usb/dev-serial.c @@ -9,7 +9,7 @@ */ #include "qemu-common.h" -#include "qemu/error-report.h" +#include "monitor/monitor.h" #include "hw/usb.h" #include "hw/usb/desc.h" #include "sysemu/char.h" @@ -460,7 +460,7 @@ static void usb_serial_event(void *opaque, int event) break; case CHR_EVENT_OPENED: if (!s->dev.attached) { - usb_device_attach(&s->dev); + usb_device_attach(&s->dev, &error_abort); } break; case CHR_EVENT_CLOSED: @@ -471,17 +471,24 @@ static void usb_serial_event(void *opaque, int event) } } -static int usb_serial_initfn(USBDevice *dev) +static void usb_serial_realize(USBDevice *dev, Error **errp) { USBSerialState *s = DO_UPCAST(USBSerialState, dev, dev); + Error *local_err = NULL; usb_desc_create_serial(dev); usb_desc_init(dev); dev->auto_attach = 0; if (!s->cs) { - error_report("Property chardev is required"); - return -1; + error_setg(errp, "Property chardev is required"); + return; + } + + usb_check_attach(dev, &local_err); + if (local_err) { + error_propagate(errp, local_err); + return; } qemu_chr_add_handlers(s->cs, usb_serial_can_read, usb_serial_read, @@ -489,9 +496,8 @@ static int usb_serial_initfn(USBDevice *dev) usb_serial_handle_reset(dev); if (s->cs->be_open && !dev->attached) { - usb_device_attach(dev); + usb_device_attach(dev, &error_abort); } - return 0; } static USBDevice *usb_serial_init(USBBus *bus, const char *filename) @@ -582,7 +588,7 @@ static void usb_serial_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_serial_initfn; + uc->realize = usb_serial_realize; uc->product_desc = "QEMU USB Serial"; uc->usb_desc = &desc_serial; uc->handle_reset = usb_serial_handle_reset; @@ -610,7 +616,7 @@ static void usb_braille_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_serial_initfn; + uc->realize = usb_serial_realize; uc->product_desc = "QEMU USB Braille"; uc->usb_desc = &desc_braille; uc->handle_reset = usb_serial_handle_reset; diff --git a/hw/usb/dev-smartcard-reader.c b/hw/usb/dev-smartcard-reader.c index 470e69ffc8..78ce681671 100644 --- a/hw/usb/dev-smartcard-reader.c +++ b/hw/usb/dev-smartcard-reader.c @@ -1304,7 +1304,7 @@ static int ccid_card_init(DeviceState *qdev) return ret; } -static int ccid_initfn(USBDevice *dev) +static void ccid_realize(USBDevice *dev, Error **errp) { USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev); @@ -1312,8 +1312,8 @@ static int ccid_initfn(USBDevice *dev) usb_desc_init(dev); qbus_create_inplace(&s->bus, sizeof(s->bus), TYPE_CCID_BUS, DEVICE(dev), NULL); + qbus_set_hotplug_handler(BUS(&s->bus), DEVICE(dev), &error_abort); s->intr = usb_ep_get(dev, USB_TOKEN_IN, CCID_INT_IN_EP); - s->bus.qbus.allow_hotplug = 1; s->card = NULL; s->migration_state = MIGRATION_NONE; s->migration_target_ip = 0; @@ -1332,7 +1332,6 @@ static int ccid_initfn(USBDevice *dev) ccid_reset_parameters(s); ccid_reset(s); s->debug = parse_debug_env("QEMU_CCID_DEBUG", D_VERBOSE, s->debug); - return 0; } static int ccid_post_load(void *opaque, int version_id) @@ -1440,8 +1439,9 @@ static void ccid_class_initfn(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); + HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); - uc->init = ccid_initfn; + uc->realize = ccid_realize; uc->product_desc = "QEMU USB CCID"; uc->usb_desc = &desc_ccid; uc->handle_reset = ccid_handle_reset; @@ -1452,6 +1452,7 @@ static void ccid_class_initfn(ObjectClass *klass, void *data) dc->vmsd = &ccid_vmstate; dc->props = ccid_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); + hc->unplug = qdev_simple_device_unplug_cb; } static const TypeInfo ccid_info = { @@ -1459,6 +1460,10 @@ static const TypeInfo ccid_info = { .parent = TYPE_USB_DEVICE, .instance_size = sizeof(USBCCIDState), .class_init = ccid_class_initfn, + .interfaces = (InterfaceInfo[]) { + { TYPE_HOTPLUG_HANDLER }, + { } + } }; static void ccid_card_class_init(ObjectClass *klass, void *data) diff --git a/hw/usb/dev-storage.c b/hw/usb/dev-storage.c index 2852669d57..4539733e42 100644 --- a/hw/usb/dev-storage.c +++ b/hw/usb/dev-storage.c @@ -16,7 +16,9 @@ #include "ui/console.h" #include "monitor/monitor.h" #include "sysemu/sysemu.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" +#include "qapi/visitor.h" //#define DEBUG_MSD @@ -59,6 +61,7 @@ typedef struct { /* usb-storage only */ BlockConf conf; uint32_t removable; + SCSIDevice *scsi_dev; } MSDState; struct usb_msd_cbw { @@ -409,19 +412,19 @@ static void usb_msd_handle_data(USBDevice *dev, USBPacket *p) switch (s->mode) { case USB_MSDM_CBW: if (p->iov.size != 31) { - fprintf(stderr, "usb-msd: Bad CBW size"); + error_report("usb-msd: Bad CBW size"); goto fail; } usb_packet_copy(p, &cbw, 31); if (le32_to_cpu(cbw.sig) != 0x43425355) { - fprintf(stderr, "usb-msd: Bad signature %08x\n", - le32_to_cpu(cbw.sig)); + error_report("usb-msd: Bad signature %08x", + le32_to_cpu(cbw.sig)); goto fail; } DPRINTF("Command on LUN %d\n", cbw.lun); scsi_dev = scsi_device_find(&s->bus, 0, 0, cbw.lun); if (scsi_dev == NULL) { - fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun); + error_report("usb-msd: Bad LUN %d", cbw.lun); goto fail; } tag = le32_to_cpu(cbw.tag); @@ -549,12 +552,17 @@ static void usb_msd_handle_data(USBDevice *dev, USBPacket *p) static void usb_msd_password_cb(void *opaque, int err) { MSDState *s = opaque; + Error *local_err = NULL; - if (!err) - err = usb_device_attach(&s->dev); + if (!err) { + usb_device_attach(&s->dev, &local_err); + } - if (err) + if (local_err) { + qerror_report_err(local_err); + error_free(local_err); qdev_unplug(&s->dev.qdev, NULL); + } } static void *usb_msd_load_request(QEMUFile *f, SCSIRequest *req) @@ -590,16 +598,16 @@ static const struct SCSIBusInfo usb_msd_scsi_info_bot = { .load_request = usb_msd_load_request, }; -static int usb_msd_initfn_storage(USBDevice *dev) +static void usb_msd_realize_storage(USBDevice *dev, Error **errp) { MSDState *s = DO_UPCAST(MSDState, dev, dev); - BlockDriverState *bs = s->conf.bs; + BlockBackend *blk = s->conf.blk; SCSIDevice *scsi_dev; Error *err = NULL; - if (!bs) { - error_report("drive property not set"); - return -1; + if (!blk) { + error_setg(errp, "drive property not set"); + return; } blkconf_serial(&s->conf, &dev->serial); @@ -613,35 +621,35 @@ static int usb_msd_initfn_storage(USBDevice *dev) * * The hack is probably a bad idea. */ - bdrv_detach_dev(bs, &s->dev.qdev); - s->conf.bs = NULL; + blk_detach_dev(blk, &s->dev.qdev); + s->conf.blk = NULL; usb_desc_create_serial(dev); usb_desc_init(dev); scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev), &usb_msd_scsi_info_storage, NULL); - scsi_dev = scsi_bus_legacy_add_drive(&s->bus, bs, 0, !!s->removable, + scsi_dev = scsi_bus_legacy_add_drive(&s->bus, blk, 0, !!s->removable, s->conf.bootindex, dev->serial, &err); if (!scsi_dev) { - return -1; + error_propagate(errp, err); + return; } - s->bus.qbus.allow_hotplug = 0; usb_msd_handle_reset(dev); + s->scsi_dev = scsi_dev; - if (bdrv_key_required(bs)) { + if (bdrv_key_required(blk_bs(blk))) { if (cur_mon) { - monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb, s); + monitor_read_bdrv_key_start(cur_mon, blk_bs(blk), + usb_msd_password_cb, s); s->dev.auto_attach = 0; } else { autostart = 0; } } - - return 0; } -static int usb_msd_initfn_bot(USBDevice *dev) +static void usb_msd_realize_bot(USBDevice *dev, Error **errp) { MSDState *s = DO_UPCAST(MSDState, dev, dev); @@ -649,10 +657,7 @@ static int usb_msd_initfn_bot(USBDevice *dev) usb_desc_init(dev); scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev), &usb_msd_scsi_info_bot, NULL); - s->bus.qbus.allow_hotplug = 0; usb_msd_handle_reset(dev); - - return 0; } static USBDevice *usb_msd_init(USBBus *bus, const char *filename) @@ -666,8 +671,10 @@ static USBDevice *usb_msd_init(USBBus *bus, const char *filename) char fmt[32]; /* parse -usbdevice disk: syntax into drive opts */ - snprintf(id, sizeof(id), "usb%d", nr++); - opts = qemu_opts_create(qemu_find_opts("drive"), id, 0, NULL); + do { + snprintf(id, sizeof(id), "usb%d", nr++); + opts = qemu_opts_create(qemu_find_opts("drive"), id, 1, NULL); + } while (!opts); p1 = strchr(filename, ':'); if (p1++) { @@ -678,20 +685,20 @@ static USBDevice *usb_msd_init(USBBus *bus, const char *filename) pstrcpy(fmt, len, p2); qemu_opt_set(opts, "format", fmt); } else if (*filename != ':') { - printf("unrecognized USB mass-storage option %s\n", filename); + error_report("unrecognized USB mass-storage option %s", filename); return NULL; } filename = p1; } if (!*filename) { - printf("block device specification needed\n"); + error_report("block device specification needed"); return NULL; } qemu_opt_set(opts, "file", filename); qemu_opt_set(opts, "if", "none"); /* create host drive */ - dinfo = drive_init(opts, 0); + dinfo = drive_new(opts, 0); if (!dinfo) { qemu_opts_del(opts); return NULL; @@ -702,7 +709,8 @@ static USBDevice *usb_msd_init(USBBus *bus, const char *filename) if (!dev) { return NULL; } - if (qdev_prop_set_drive(&dev->qdev, "drive", dinfo->bdrv) < 0) { + if (qdev_prop_set_drive(&dev->qdev, "drive", + blk_by_legacy_dinfo(dinfo)) < 0) { object_unparent(OBJECT(dev)); return NULL; } @@ -716,7 +724,7 @@ static const VMStateDescription vmstate_usb_msd = { .name = "usb-storage", .version_id = 1, .minimum_version_id = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_USB_DEVICE(dev, MSDState), VMSTATE_UINT32(mode, MSDState), VMSTATE_UINT32(scsi_len, MSDState), @@ -758,17 +766,67 @@ static void usb_msd_class_initfn_storage(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_msd_initfn_storage; + uc->realize = usb_msd_realize_storage; dc->props = msd_properties; usb_msd_class_initfn_common(klass); } +static void usb_msd_get_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + USBDevice *dev = USB_DEVICE(obj); + MSDState *s = DO_UPCAST(MSDState, dev, dev); + + visit_type_int32(v, &s->conf.bootindex, name, errp); +} + +static void usb_msd_set_bootindex(Object *obj, Visitor *v, void *opaque, + const char *name, Error **errp) +{ + USBDevice *dev = USB_DEVICE(obj); + MSDState *s = DO_UPCAST(MSDState, dev, dev); + int32_t boot_index; + Error *local_err = NULL; + + visit_type_int32(v, &boot_index, name, &local_err); + if (local_err) { + goto out; + } + /* check whether bootindex is present in fw_boot_order list */ + check_boot_index(boot_index, &local_err); + if (local_err) { + goto out; + } + /* change bootindex to a new one */ + s->conf.bootindex = boot_index; + + if (s->scsi_dev) { + object_property_set_int(OBJECT(s->scsi_dev), boot_index, "bootindex", + &error_abort); + } + +out: + if (local_err) { + error_propagate(errp, local_err); + } +} + +static void usb_msd_instance_init(Object *obj) +{ + object_property_add(obj, "bootindex", "int32", + usb_msd_get_bootindex, + usb_msd_set_bootindex, NULL, NULL, NULL); + object_property_set_int(obj, -1, "bootindex", NULL); +} + static void usb_msd_class_initfn_bot(ObjectClass *klass, void *data) { USBDeviceClass *uc = USB_DEVICE_CLASS(klass); + DeviceClass *dc = DEVICE_CLASS(klass); - uc->init = usb_msd_initfn_bot; + uc->realize = usb_msd_realize_bot; usb_msd_class_initfn_common(klass); + dc->hotpluggable = false; } static const TypeInfo msd_info = { @@ -776,6 +834,7 @@ static const TypeInfo msd_info = { .parent = TYPE_USB_DEVICE, .instance_size = sizeof(MSDState), .class_init = usb_msd_class_initfn_storage, + .instance_init = usb_msd_instance_init, }; static const TypeInfo bot_info = { diff --git a/hw/usb/dev-uas.c b/hw/usb/dev-uas.c index 9832385119..04fc515dbe 100644 --- a/hw/usb/dev-uas.c +++ b/hw/usb/dev-uas.c @@ -13,6 +13,7 @@ #include "qemu/option.h" #include "qemu/config-file.h" #include "trace.h" +#include "qemu/error-report.h" #include "hw/usb.h" #include "hw/usb/desc.h" @@ -648,7 +649,7 @@ static void usb_uas_handle_control(USBDevice *dev, USBPacket *p, if (ret >= 0) { return; } - fprintf(stderr, "%s: unhandled control request\n", __func__); + error_report("%s: unhandled control request", __func__); p->status = USB_RET_STALL; } @@ -814,8 +815,8 @@ static void usb_uas_handle_data(USBDevice *dev, USBPacket *p) usb_uas_task(uas, &iu); break; default: - fprintf(stderr, "%s: unknown command iu: id 0x%x\n", - __func__, iu.hdr.id); + error_report("%s: unknown command iu: id 0x%x", + __func__, iu.hdr.id); p->status = USB_RET_STALL; break; } @@ -861,7 +862,7 @@ static void usb_uas_handle_data(USBDevice *dev, USBPacket *p) p->status = USB_RET_ASYNC; break; } else { - fprintf(stderr, "%s: no inflight request\n", __func__); + error_report("%s: no inflight request", __func__); p->status = USB_RET_STALL; break; } @@ -879,7 +880,7 @@ static void usb_uas_handle_data(USBDevice *dev, USBPacket *p) usb_uas_start_next_transfer(uas); break; default: - fprintf(stderr, "%s: invalid endpoint %d\n", __func__, p->ep->nr); + error_report("%s: invalid endpoint %d", __func__, p->ep->nr); p->status = USB_RET_STALL; break; } @@ -892,7 +893,7 @@ static void usb_uas_handle_destroy(USBDevice *dev) qemu_bh_delete(uas->status_bh); } -static int usb_uas_init(USBDevice *dev) +static void usb_uas_realize(USBDevice *dev, Error **errp) { UASDevice *uas = DO_UPCAST(UASDevice, dev, dev); @@ -905,8 +906,6 @@ static int usb_uas_init(USBDevice *dev) scsi_bus_new(&uas->bus, sizeof(uas->bus), DEVICE(dev), &usb_uas_scsi_info, NULL); - - return 0; } static const VMStateDescription vmstate_usb_uas = { @@ -928,7 +927,7 @@ static void usb_uas_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_uas_init; + uc->realize = usb_uas_realize; uc->product_desc = desc_strings[STR_PRODUCT]; uc->usb_desc = &desc; uc->cancel_packet = usb_uas_cancel_io; diff --git a/hw/usb/dev-wacom.c b/hw/usb/dev-wacom.c index 1b73fd0aab..844eafadf7 100644 --- a/hw/usb/dev-wacom.c +++ b/hw/usb/dev-wacom.c @@ -335,14 +335,13 @@ static void usb_wacom_handle_destroy(USBDevice *dev) } } -static int usb_wacom_initfn(USBDevice *dev) +static void usb_wacom_realize(USBDevice *dev, Error **errp) { USBWacomState *s = DO_UPCAST(USBWacomState, dev, dev); usb_desc_create_serial(dev); usb_desc_init(dev); s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1); s->changed = 1; - return 0; } static const VMStateDescription vmstate_usb_wacom = { @@ -357,7 +356,7 @@ static void usb_wacom_class_init(ObjectClass *klass, void *data) uc->product_desc = "QEMU PenPartner Tablet"; uc->usb_desc = &desc_wacom; - uc->init = usb_wacom_initfn; + uc->realize = usb_wacom_realize; uc->handle_reset = usb_wacom_handle_reset; uc->handle_control = usb_wacom_handle_control; uc->handle_data = usb_wacom_handle_data; diff --git a/hw/usb/hcd-ehci-pci.c b/hw/usb/hcd-ehci-pci.c index 484a9bd059..490f2b6af9 100644 --- a/hw/usb/hcd-ehci-pci.c +++ b/hw/usb/hcd-ehci-pci.c @@ -23,6 +23,7 @@ typedef struct EHCIPCIInfo { uint16_t vendor_id; uint16_t device_id; uint8_t revision; + bool companion; } EHCIPCIInfo; static int usb_ehci_pci_initfn(PCIDevice *dev) @@ -71,6 +72,7 @@ static int usb_ehci_pci_initfn(PCIDevice *dev) static void usb_ehci_pci_init(Object *obj) { + DeviceClass *dc = OBJECT_GET_CLASS(DeviceClass, obj, TYPE_DEVICE); EHCIPCIState *i = PCI_EHCI(obj); EHCIState *s = &i->ehci; @@ -81,9 +83,26 @@ static void usb_ehci_pci_init(Object *obj) s->portscbase = 0x44; s->portnr = NB_PORTS; + if (!dc->hotpluggable) { + s->companion_enable = true; + } + usb_ehci_init(s, DEVICE(obj)); } +static void usb_ehci_pci_exit(PCIDevice *dev) +{ + EHCIPCIState *i = PCI_EHCI(dev); + EHCIState *s = &i->ehci; + + usb_ehci_unrealize(s, DEVICE(dev), NULL); + + if (s->irq) { + g_free(s->irq); + s->irq = NULL; + } +} + static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int l) { @@ -108,7 +127,7 @@ static const VMStateDescription vmstate_ehci_pci = { .name = "ehci", .version_id = 2, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState), VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() @@ -121,9 +140,9 @@ static void ehci_class_init(ObjectClass *klass, void *data) PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->init = usb_ehci_pci_initfn; + k->exit = usb_ehci_pci_exit; k->class_id = PCI_CLASS_SERIAL_USB; k->config_write = usb_ehci_pci_write_config; - dc->hotpluggable = false; dc->vmsd = &vmstate_ehci_pci; dc->props = ehci_pci_properties; } @@ -147,6 +166,9 @@ static void ehci_data_class_init(ObjectClass *klass, void *data) k->device_id = i->device_id; k->revision = i->revision; set_bit(DEVICE_CATEGORY_USB, dc->categories); + if (i->companion) { + dc->hotpluggable = false; + } } static struct EHCIPCIInfo ehci_pci_info[] = { @@ -160,11 +182,13 @@ static struct EHCIPCIInfo ehci_pci_info[] = { .vendor_id = PCI_VENDOR_ID_INTEL, .device_id = PCI_DEVICE_ID_INTEL_82801I_EHCI1, .revision = 0x03, + .companion = true, },{ .name = "ich9-usb-ehci2", /* 00:1a.7 */ .vendor_id = PCI_VENDOR_ID_INTEL, .device_id = PCI_DEVICE_ID_INTEL_82801I_EHCI2, .revision = 0x03, + .companion = true, } }; diff --git a/hw/usb/hcd-ehci-sysbus.c b/hw/usb/hcd-ehci-sysbus.c index fe6eea5908..19ed2c26aa 100644 --- a/hw/usb/hcd-ehci-sysbus.c +++ b/hw/usb/hcd-ehci-sysbus.c @@ -21,7 +21,7 @@ static const VMStateDescription vmstate_ehci_sysbus = { .name = "ehci-sysbus", .version_id = 2, .minimum_version_id = 1, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { VMSTATE_STRUCT(ehci, EHCISysBusState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() } diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c index 355bbd6bed..1cc0fc116d 100644 --- a/hw/usb/hcd-ehci.c +++ b/hw/usb/hcd-ehci.c @@ -27,87 +27,10 @@ * along with this program; if not, see <http://www.gnu.org/licenses/>. */ +#include "hw/usb/ehci-regs.h" #include "hw/usb/hcd-ehci.h" #include "trace.h" -/* Capability Registers Base Address - section 2.2 */ -#define CAPLENGTH 0x0000 /* 1-byte, 0x0001 reserved */ -#define HCIVERSION 0x0002 /* 2-bytes, i/f version # */ -#define HCSPARAMS 0x0004 /* 4-bytes, structural params */ -#define HCCPARAMS 0x0008 /* 4-bytes, capability params */ -#define EECP HCCPARAMS + 1 -#define HCSPPORTROUTE1 0x000c -#define HCSPPORTROUTE2 0x0010 - -#define USBCMD 0x0000 -#define USBCMD_RUNSTOP (1 << 0) // run / Stop -#define USBCMD_HCRESET (1 << 1) // HC Reset -#define USBCMD_FLS (3 << 2) // Frame List Size -#define USBCMD_FLS_SH 2 // Frame List Size Shift -#define USBCMD_PSE (1 << 4) // Periodic Schedule Enable -#define USBCMD_ASE (1 << 5) // Asynch Schedule Enable -#define USBCMD_IAAD (1 << 6) // Int Asynch Advance Doorbell -#define USBCMD_LHCR (1 << 7) // Light Host Controller Reset -#define USBCMD_ASPMC (3 << 8) // Async Sched Park Mode Count -#define USBCMD_ASPME (1 << 11) // Async Sched Park Mode Enable -#define USBCMD_ITC (0x7f << 16) // Int Threshold Control -#define USBCMD_ITC_SH 16 // Int Threshold Control Shift - -#define USBSTS 0x0004 -#define USBSTS_RO_MASK 0x0000003f -#define USBSTS_INT (1 << 0) // USB Interrupt -#define USBSTS_ERRINT (1 << 1) // Error Interrupt -#define USBSTS_PCD (1 << 2) // Port Change Detect -#define USBSTS_FLR (1 << 3) // Frame List Rollover -#define USBSTS_HSE (1 << 4) // Host System Error -#define USBSTS_IAA (1 << 5) // Interrupt on Async Advance -#define USBSTS_HALT (1 << 12) // HC Halted -#define USBSTS_REC (1 << 13) // Reclamation -#define USBSTS_PSS (1 << 14) // Periodic Schedule Status -#define USBSTS_ASS (1 << 15) // Asynchronous Schedule Status - -/* - * Interrupt enable bits correspond to the interrupt active bits in USBSTS - * so no need to redefine here. - */ -#define USBINTR 0x0008 -#define USBINTR_MASK 0x0000003f - -#define FRINDEX 0x000c -#define CTRLDSSEGMENT 0x0010 -#define PERIODICLISTBASE 0x0014 -#define ASYNCLISTADDR 0x0018 -#define ASYNCLISTADDR_MASK 0xffffffe0 - -#define CONFIGFLAG 0x0040 - -/* - * Bits that are reserved or are read-only are masked out of values - * written to us by software - */ -#define PORTSC_RO_MASK 0x007001c0 -#define PORTSC_RWC_MASK 0x0000002a -#define PORTSC_WKOC_E (1 << 22) // Wake on Over Current Enable -#define PORTSC_WKDS_E (1 << 21) // Wake on Disconnect Enable -#define PORTSC_WKCN_E (1 << 20) // Wake on Connect Enable -#define PORTSC_PTC (15 << 16) // Port Test Control -#define PORTSC_PTC_SH 16 // Port Test Control shift -#define PORTSC_PIC (3 << 14) // Port Indicator Control -#define PORTSC_PIC_SH 14 // Port Indicator Control Shift -#define PORTSC_POWNER (1 << 13) // Port Owner -#define PORTSC_PPOWER (1 << 12) // Port Power -#define PORTSC_LINESTAT (3 << 10) // Port Line Status -#define PORTSC_LINESTAT_SH 10 // Port Line Status Shift -#define PORTSC_PRESET (1 << 8) // Port Reset -#define PORTSC_SUSPEND (1 << 7) // Port Suspend -#define PORTSC_FPRES (1 << 6) // Force Port Resume -#define PORTSC_OCC (1 << 5) // Over Current Change -#define PORTSC_OCA (1 << 4) // Over Current Active -#define PORTSC_PEDC (1 << 3) // Port Enable/Disable Change -#define PORTSC_PED (1 << 2) // Port Enable/Disable -#define PORTSC_CSC (1 << 1) // Connect Status Change -#define PORTSC_CONNECT (1 << 0) // Current Connect Status - #define FRAME_TIMER_FREQ 1000 #define FRAME_TIMER_NS (1000000000 / FRAME_TIMER_FREQ) #define UFRAME_TIMER_NS (FRAME_TIMER_NS / 8) @@ -1673,7 +1596,7 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async) entry = ehci_get_fetch_addr(ehci, async); q = ehci_find_queue_by_qh(ehci, entry, async); - if (NULL == q) { + if (q == NULL) { q = ehci_alloc_queue(ehci, entry, async); } @@ -2424,10 +2347,13 @@ static USBPortOps ehci_port_ops = { .complete = ehci_async_complete_packet, }; -static USBBusOps ehci_bus_ops = { +static USBBusOps ehci_bus_ops_companion = { .register_companion = ehci_register_companion, .wakeup_endpoint = ehci_wakeup_endpoint, }; +static USBBusOps ehci_bus_ops_standalone = { + .wakeup_endpoint = ehci_wakeup_endpoint, +}; static void usb_ehci_pre_save(void *opaque) { @@ -2492,7 +2418,7 @@ const VMStateDescription vmstate_ehci = { .minimum_version_id = 1, .pre_save = usb_ehci_pre_save, .post_load = usb_ehci_post_load, - .fields = (VMStateField[]) { + .fields = (VMStateField[]) { /* mmio registers */ VMSTATE_UINT32(usbcmd, EHCIState), VMSTATE_UINT32(usbsts, EHCIState), @@ -2533,7 +2459,8 @@ void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp) return; } - usb_bus_new(&s->bus, sizeof(s->bus), &ehci_bus_ops, dev); + usb_bus_new(&s->bus, sizeof(s->bus), s->companion_enable ? + &ehci_bus_ops_companion : &ehci_bus_ops_standalone, dev); for (i = 0; i < s->portnr; i++) { usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops, USB_SPEED_MASK_HIGH); @@ -2545,7 +2472,34 @@ void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp) s->device = dev; qemu_register_reset(ehci_reset, s); - qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s); + s->vmstate = qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s); +} + +void usb_ehci_unrealize(EHCIState *s, DeviceState *dev, Error **errp) +{ + trace_usb_ehci_unrealize(); + + if (s->frame_timer) { + timer_del(s->frame_timer); + timer_free(s->frame_timer); + s->frame_timer = NULL; + } + if (s->async_bh) { + qemu_bh_delete(s->async_bh); + } + + ehci_queues_rip_all(s, 0); + ehci_queues_rip_all(s, 1); + + memory_region_del_subregion(&s->mem, &s->mem_caps); + memory_region_del_subregion(&s->mem, &s->mem_opreg); + memory_region_del_subregion(&s->mem, &s->mem_ports); + + usb_bus_release(&s->bus); + + if (s->vmstate) { + qemu_del_vm_change_state_handler(s->vmstate); + } } void usb_ehci_init(EHCIState *s, DeviceState *dev) diff --git a/hw/usb/hcd-ehci.h b/hw/usb/hcd-ehci.h index 1ad4b96cce..2bc259c9b4 100644 --- a/hw/usb/hcd-ehci.h +++ b/hw/usb/hcd-ehci.h @@ -262,6 +262,7 @@ struct EHCIState { MemoryRegion mem_opreg; MemoryRegion mem_ports; int companion_count; + bool companion_enable; uint16_t capsbase; uint16_t opregbase; uint16_t portscbase; @@ -316,12 +317,14 @@ struct EHCIState { uint32_t async_stepdown; uint32_t periodic_sched_active; bool int_req_by_async; + VMChangeStateEntry *vmstate; }; extern const VMStateDescription vmstate_ehci; void usb_ehci_init(EHCIState *s, DeviceState *dev); void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp); +void usb_ehci_unrealize(EHCIState *s, DeviceState *dev, Error **errp); #define TYPE_PCI_EHCI "pci-ehci-usb" #define PCI_EHCI(obj) OBJECT_CHECK(EHCIPCIState, (obj), TYPE_PCI_EHCI) diff --git a/hw/usb/hcd-musb.c b/hw/usb/hcd-musb.c index 66bc61ae1e..40809f610e 100644 --- a/hw/usb/hcd-musb.c +++ b/hw/usb/hcd-musb.c @@ -608,6 +608,7 @@ static void musb_packet(MUSBState *s, MUSBEndPoint *ep, USBDevice *dev; USBEndpoint *uep; int idx = epnum && dir; + int id; int ttype; /* ep->type[0,1] contains: @@ -625,8 +626,11 @@ static void musb_packet(MUSBState *s, MUSBEndPoint *ep, /* A wild guess on the FADDR semantics... */ dev = usb_find_device(&s->port, ep->faddr[idx]); uep = usb_ep_get(dev, pid, ep->type[idx] & 0xf); - usb_packet_setup(&ep->packey[dir].p, pid, uep, 0, - (dev->addr << 16) | (uep->nr << 8) | pid, false, true); + id = pid; + if (uep) { + id |= (dev->addr << 16) | (uep->nr << 8); + } + usb_packet_setup(&ep->packey[dir].p, pid, uep, 0, id, false, true); usb_packet_addbuf(&ep->packey[dir].p, ep->buf[idx], len); ep->packey[dir].ep = ep; ep->packey[dir].dir = dir; diff --git a/hw/usb/hcd-ohci.c b/hw/usb/hcd-ohci.c index 93f186f5e7..9a84eb6950 100644 --- a/hw/usb/hcd-ohci.c +++ b/hw/usb/hcd-ohci.c @@ -31,20 +31,11 @@ #include "hw/pci/pci.h" #include "hw/sysbus.h" #include "hw/qdev-dma.h" +#include "trace.h" -//#define DEBUG_OHCI -/* Dump packet contents. */ -//#define DEBUG_PACKET -//#define DEBUG_ISOCH /* This causes frames to occur 1000x slower */ //#define OHCI_TIME_WARP 1 -#ifdef DEBUG_OHCI -#define DPRINTF printf -#else -#define DPRINTF(...) -#endif - /* Number of Downstream Ports on the root hub. */ #define OHCI_MAX_PORTS 15 @@ -80,13 +71,13 @@ typedef struct { uint32_t bulk_head, bulk_cur; uint32_t per_cur; uint32_t done; - int done_count; + int32_t done_count; /* Frame counter partition */ - uint32_t fsmps:15; - uint32_t fit:1; - uint32_t fi:14; - uint32_t frt:1; + uint16_t fsmps; + uint8_t fit; + uint16_t fi; + uint8_t frt; uint16_t frame_number; uint16_t padding; uint32_t pstart; @@ -111,7 +102,7 @@ typedef struct { USBPacket usb_packet; uint8_t usb_buf[8192]; uint32_t async_td; - int async_complete; + bool async_complete; } OHCIState; @@ -350,7 +341,7 @@ static void ohci_attach(USBPort *port1) ohci_set_interrupt(s, OHCI_INTR_RD); } - DPRINTF("usb-ohci: Attached port %d\n", port1->index); + trace_usb_ohci_port_attach(port1->index); if (old_state != port->ctrl) { ohci_set_interrupt(s, OHCI_INTR_RHSC); @@ -375,7 +366,7 @@ static void ohci_detach(USBPort *port1) port->ctrl &= ~OHCI_PORT_PES; port->ctrl |= OHCI_PORT_PESC; } - DPRINTF("usb-ohci: Detached port %d\n", port1->index); + trace_usb_ohci_port_detach(port1->index); if (old_state != port->ctrl) { ohci_set_interrupt(s, OHCI_INTR_RHSC); @@ -388,14 +379,14 @@ static void ohci_wakeup(USBPort *port1) OHCIPort *port = &s->rhport[port1->index]; uint32_t intr = 0; if (port->ctrl & OHCI_PORT_PSS) { - DPRINTF("usb-ohci: port %d: wakeup\n", port1->index); + trace_usb_ohci_port_wakeup(port1->index); port->ctrl |= OHCI_PORT_PSSC; port->ctrl &= ~OHCI_PORT_PSS; intr = OHCI_INTR_RHSC; } /* Note that the controller can be suspended even if this port is not */ if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND) { - DPRINTF("usb-ohci: remote-wakeup: SUSPEND->RESUME\n"); + trace_usb_ohci_remote_wakeup(s->name); /* This is the one state transition the controller can do by itself */ s->ctl &= ~OHCI_CTL_HCFS; s->ctl |= OHCI_USB_RESUME; @@ -497,7 +488,7 @@ static void ohci_reset(void *opaque) ohci->async_td = 0; } ohci_stop_endpoints(ohci); - DPRINTF("usb-ohci: Reset %s\n", ohci->name); + trace_usb_ohci_reset(ohci->name); } /* Get an array of dwords from main memory */ @@ -619,8 +610,8 @@ static inline int ohci_put_td(OHCIState *ohci, static inline int ohci_put_iso_td(OHCIState *ohci, dma_addr_t addr, struct ohci_iso_td *td) { - return put_dwords(ohci, addr, (uint32_t *)td, 4 || - put_words(ohci, addr + 16, td->offset, 8)); + return put_dwords(ohci, addr, (uint32_t *)td, 4) || + put_words(ohci, addr + 16, td->offset, 8); } static inline int ohci_put_hcca(OHCIState *ohci, @@ -690,10 +681,9 @@ static void ohci_process_lists(OHCIState *ohci, int completion); static void ohci_async_complete_packet(USBPort *port, USBPacket *packet) { OHCIState *ohci = container_of(packet, OHCIState, usb_packet); -#ifdef DEBUG_PACKET - DPRINTF("Async packet complete\n"); -#endif - ohci->async_complete = 1; + + trace_usb_ohci_async_complete(); + ohci->async_complete = true; ohci_process_lists(ohci, 1); } @@ -704,9 +694,7 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, { int dir; size_t len = 0; -#ifdef DEBUG_ISOCH const char *str = NULL; -#endif int pid; int ret; int i; @@ -723,7 +711,7 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, addr = ed->head & OHCI_DPTR_MASK; if (ohci_read_iso_td(ohci, addr, &iso_td)) { - printf("usb-ohci: ISO_TD read error at %x\n", addr); + trace_usb_ohci_iso_td_read_failed(addr); ohci_die(ohci); return 0; } @@ -732,31 +720,25 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, frame_count = OHCI_BM(iso_td.flags, TD_FC); relative_frame_number = USUB(ohci->frame_number, starting_frame); -#ifdef DEBUG_ISOCH - printf("--- ISO_TD ED head 0x%.8x tailp 0x%.8x\n" - "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n" - "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n" - "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n" - "frame_number 0x%.8x starting_frame 0x%.8x\n" - "frame_count 0x%.8x relative %d\n" - "di 0x%.8x cc 0x%.8x\n", + trace_usb_ohci_iso_td_head( ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK, iso_td.flags, iso_td.bp, iso_td.next, iso_td.be, - iso_td.offset[0], iso_td.offset[1], iso_td.offset[2], iso_td.offset[3], - iso_td.offset[4], iso_td.offset[5], iso_td.offset[6], iso_td.offset[7], - ohci->frame_number, starting_frame, - frame_count, relative_frame_number, - OHCI_BM(iso_td.flags, TD_DI), OHCI_BM(iso_td.flags, TD_CC)); -#endif + ohci->frame_number, starting_frame, + frame_count, relative_frame_number); + trace_usb_ohci_iso_td_head_offset( + iso_td.offset[0], iso_td.offset[1], + iso_td.offset[2], iso_td.offset[3], + iso_td.offset[4], iso_td.offset[5], + iso_td.offset[6], iso_td.offset[7]); if (relative_frame_number < 0) { - DPRINTF("usb-ohci: ISO_TD R=%d < 0\n", relative_frame_number); + trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number); return 1; } else if (relative_frame_number > frame_count) { /* ISO TD expired - retire the TD to the Done Queue and continue with the next ISO TD of the same ED */ - DPRINTF("usb-ohci: ISO_TD R=%d > FC=%d\n", relative_frame_number, - frame_count); + trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number, + frame_count); OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN); ed->head &= ~OHCI_DPTR_MASK; ed->head |= (iso_td.next & OHCI_DPTR_MASK); @@ -775,30 +757,24 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, dir = OHCI_BM(ed->flags, ED_D); switch (dir) { case OHCI_TD_DIR_IN: -#ifdef DEBUG_ISOCH str = "in"; -#endif pid = USB_TOKEN_IN; break; case OHCI_TD_DIR_OUT: -#ifdef DEBUG_ISOCH str = "out"; -#endif pid = USB_TOKEN_OUT; break; case OHCI_TD_DIR_SETUP: -#ifdef DEBUG_ISOCH str = "setup"; -#endif pid = USB_TOKEN_SETUP; break; default: - printf("usb-ohci: Bad direction %d\n", dir); + trace_usb_ohci_iso_td_bad_direction(dir); return 1; } if (!iso_td.bp || !iso_td.be) { - printf("usb-ohci: ISO_TD bp 0x%.8x be 0x%.8x\n", iso_td.bp, iso_td.be); + trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be); return 1; } @@ -808,14 +784,12 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) || ((relative_frame_number < frame_count) && !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) { - printf("usb-ohci: ISO_TD cc != not accessed 0x%.8x 0x%.8x\n", - start_offset, next_offset); + trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset); return 1; } if ((relative_frame_number < frame_count) && (start_offset > next_offset)) { - printf("usb-ohci: ISO_TD start_offset=0x%.8x > next_offset=0x%.8x\n", - start_offset, next_offset); + trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset); return 1; } @@ -875,10 +849,8 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, ret = ohci->usb_packet.status; } -#ifdef DEBUG_ISOCH - printf("so 0x%.8x eo 0x%.8x\nsa 0x%.8x ea 0x%.8x\ndir %s len %zu ret %d\n", - start_offset, end_offset, start_addr, end_addr, str, len, ret); -#endif + trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr, + str, len, ret); /* Writeback */ if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) { @@ -898,13 +870,13 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0); } else { if (ret > (ssize_t) len) { - printf("usb-ohci: DataOverrun %d > %zu\n", ret, len); + trace_usb_ohci_iso_td_data_overrun(ret, len); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC, OHCI_CC_DATAOVERRUN); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, len); } else if (ret >= 0) { - printf("usb-ohci: DataUnderrun %d\n", ret); + trace_usb_ohci_iso_td_data_underrun(ret); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC, OHCI_CC_DATAUNDERRUN); } else { @@ -918,14 +890,14 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, break; case USB_RET_NAK: case USB_RET_STALL: - printf("usb-ohci: got NAK/STALL %d\n", ret); + trace_usb_ohci_iso_td_nak(ret); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC, OHCI_CC_STALL); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0); break; default: - printf("usb-ohci: Bad device response %d\n", ret); + trace_usb_ohci_iso_td_bad_response(ret); OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC, OHCI_CC_UNDEXPETEDPID); break; @@ -950,6 +922,43 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed, return 1; } +#ifdef trace_event_get_state +static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len) +{ + bool print16 = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_SHORT); + bool printall = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_FULL); + const int width = 16; + int i; + char tmp[3 * width + 1]; + char *p = tmp; + + if (!printall && !print16) { + return; + } + + for (i = 0; ; i++) { + if (i && (!(i % width) || (i == len))) { + if (!printall) { + trace_usb_ohci_td_pkt_short(msg, tmp); + break; + } + trace_usb_ohci_td_pkt_full(msg, tmp); + p = tmp; + *p = 0; + } + if (i == len) { + break; + } + + p += sprintf(p, " %.2x", buf[i]); + } +} +#else +static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len) +{ +} +#endif + /* Service a transport descriptor. Returns nonzero to terminate processing of this endpoint. */ @@ -957,9 +966,7 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) { int dir; size_t len = 0, pktlen = 0; -#ifdef DEBUG_PACKET const char *str = NULL; -#endif int pid; int ret; int i; @@ -974,13 +981,11 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) /* See if this TD has already been submitted to the device. */ completion = (addr == ohci->async_td); if (completion && !ohci->async_complete) { -#ifdef DEBUG_PACKET - DPRINTF("Skipping async TD\n"); -#endif + trace_usb_ohci_td_skip_async(); return 1; } if (ohci_read_td(ohci, addr, &td)) { - fprintf(stderr, "usb-ohci: TD read error at %x\n", addr); + trace_usb_ohci_td_read_error(addr); ohci_die(ohci); return 0; } @@ -998,25 +1003,19 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) switch (dir) { case OHCI_TD_DIR_IN: -#ifdef DEBUG_PACKET str = "in"; -#endif pid = USB_TOKEN_IN; break; case OHCI_TD_DIR_OUT: -#ifdef DEBUG_PACKET str = "out"; -#endif pid = USB_TOKEN_OUT; break; case OHCI_TD_DIR_SETUP: -#ifdef DEBUG_PACKET str = "setup"; -#endif pid = USB_TOKEN_SETUP; break; default: - fprintf(stderr, "usb-ohci: Bad direction\n"); + trace_usb_ohci_td_bad_direction(dir); return 1; } if (td.cbp && td.be) { @@ -1043,22 +1042,13 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) } flag_r = (td.flags & OHCI_TD_R) != 0; -#ifdef DEBUG_PACKET - DPRINTF(" TD @ 0x%.8x %" PRId64 " of %" PRId64 - " bytes %s r=%d cbp=0x%.8x be=0x%.8x\n", - addr, (int64_t)pktlen, (int64_t)len, str, flag_r, td.cbp, td.be); - - if (pktlen > 0 && dir != OHCI_TD_DIR_IN) { - DPRINTF(" data:"); - for (i = 0; i < pktlen; i++) { - printf(" %.2x", ohci->usb_buf[i]); - } - DPRINTF("\n"); - } -#endif + trace_usb_ohci_td_pkt_hdr(addr, (int64_t)pktlen, (int64_t)len, str, + flag_r, td.cbp, td.be); + ohci_td_pkt("OUT", ohci->usb_buf, pktlen); + if (completion) { ohci->async_td = 0; - ohci->async_complete = 0; + ohci->async_complete = false; } else { if (ohci->async_td) { /* ??? The hardware should allow one active packet per @@ -1066,9 +1056,7 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) This should be sufficient as long as devices respond in a timely manner. */ -#ifdef DEBUG_PACKET - DPRINTF("Too many pending packets\n"); -#endif + trace_usb_ohci_td_too_many_pending(); return 1; } dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA)); @@ -1077,9 +1065,8 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) OHCI_BM(td.flags, TD_DI) == 0); usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, pktlen); usb_handle_packet(dev, &ohci->usb_packet); -#ifdef DEBUG_PACKET - DPRINTF("status=%d\n", ohci->usb_packet.status); -#endif + trace_usb_ohci_td_packet_status(ohci->usb_packet.status); + if (ohci->usb_packet.status == USB_RET_ASYNC) { usb_device_flush_ep_queue(dev, ep); ohci->async_td = addr; @@ -1098,12 +1085,7 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) DMA_DIRECTION_FROM_DEVICE)) { ohci_die(ohci); } -#ifdef DEBUG_PACKET - DPRINTF(" data:"); - for (i = 0; i < ret; i++) - printf(" %.2x", ohci->usb_buf[i]); - DPRINTF("\n"); -#endif + ohci_td_pkt("IN", ohci->usb_buf, pktlen); } else { ret = pktlen; } @@ -1137,28 +1119,28 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed) ed->head |= OHCI_ED_C; } else { if (ret >= 0) { - DPRINTF("usb-ohci: Underrun\n"); + trace_usb_ohci_td_underrun(); OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN); } else { switch (ret) { case USB_RET_IOERROR: case USB_RET_NODEV: - DPRINTF("usb-ohci: got DEV ERROR\n"); + trace_usb_ohci_td_dev_error(); OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING); break; case USB_RET_NAK: - DPRINTF("usb-ohci: got NAK\n"); + trace_usb_ohci_td_nak(); return 1; case USB_RET_STALL: - DPRINTF("usb-ohci: got STALL\n"); + trace_usb_ohci_td_stall(); OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL); break; case USB_RET_BABBLE: - DPRINTF("usb-ohci: got BABBLE\n"); + trace_usb_ohci_td_babble(); OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN); break; default: - fprintf(stderr, "usb-ohci: Bad device response %d\n", ret); + trace_usb_ohci_td_bad_device_response(ret); OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID); OHCI_SET_BM(td.flags, TD_EC, 3); break; @@ -1198,7 +1180,7 @@ static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion) for (cur = head; cur; cur = next_ed) { if (ohci_read_ed(ohci, cur, &ed)) { - fprintf(stderr, "usb-ohci: ED read error at %x\n", cur); + trace_usb_ohci_ed_read_error(cur); ohci_die(ohci); return 0; } @@ -1219,16 +1201,15 @@ static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion) } while ((ed.head & OHCI_DPTR_MASK) != ed.tail) { -#ifdef DEBUG_PACKET - DPRINTF("ED @ 0x%.8x fa=%u en=%u d=%u s=%u k=%u f=%u mps=%u " - "h=%u c=%u\n head=0x%.8x tailp=0x%.8x next=0x%.8x\n", cur, + trace_usb_ohci_ed_pkt(cur, (ed.head & OHCI_ED_H) != 0, + (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK, + ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK); + trace_usb_ohci_ed_pkt_flags( OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN), OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0, (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0, - OHCI_BM(ed.flags, ED_MPS), (ed.head & OHCI_ED_H) != 0, - (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK, - ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK); -#endif + OHCI_BM(ed.flags, ED_MPS)); + active = 1; if ((ed.flags & OHCI_ED_F) == 0) { @@ -1263,8 +1244,7 @@ static void ohci_process_lists(OHCIState *ohci, int completion) { if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) { if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head) { - DPRINTF("usb-ohci: head %x, cur %x\n", - ohci->ctrl_head, ohci->ctrl_cur); + trace_usb_ohci_process_lists(ohci->ctrl_head, ohci->ctrl_cur); } if (!ohci_service_ed_list(ohci, ohci->ctrl_head, completion)) { ohci->ctrl_cur = 0; @@ -1287,7 +1267,7 @@ static void ohci_frame_boundary(void *opaque) struct ohci_hcca hcca; if (ohci_read_hcca(ohci, ohci->hcca, &hcca)) { - fprintf(stderr, "usb-ohci: HCCA read error at %x\n", ohci->hcca); + trace_usb_ohci_hcca_read_error(ohci->hcca); ohci_die(ohci); return; } @@ -1356,12 +1336,12 @@ static int ohci_bus_start(OHCIState *ohci) ohci); if (ohci->eof_timer == NULL) { - fprintf(stderr, "usb-ohci: %s: timer_new_ns failed\n", ohci->name); + trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } - DPRINTF("usb-ohci: %s: USB Operational\n", ohci->name); + trace_usb_ohci_start(ohci->name); ohci_sof(ohci); @@ -1371,8 +1351,11 @@ static int ohci_bus_start(OHCIState *ohci) /* Stop sending SOF tokens on the bus */ static void ohci_bus_stop(OHCIState *ohci) { - if (ohci->eof_timer) + trace_usb_ohci_stop(ohci->name); + if (ohci->eof_timer) { timer_del(ohci->eof_timer); + timer_free(ohci->eof_timer); + } ohci->eof_timer = NULL; } @@ -1414,8 +1397,7 @@ static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val) val &= OHCI_FMI_FI; if (val != ohci->fi) { - DPRINTF("usb-ohci: %s: FrameInterval = 0x%x (%u)\n", - ohci->name, ohci->fi, ohci->fi); + trace_usb_ohci_set_frame_interval(ohci->name, ohci->fi, ohci->fi); } ohci->fi = val; @@ -1447,20 +1429,19 @@ static void ohci_set_ctl(OHCIState *ohci, uint32_t val) if (old_state == new_state) return; + trace_usb_ohci_set_ctl(ohci->name, new_state); switch (new_state) { case OHCI_USB_OPERATIONAL: ohci_bus_start(ohci); break; case OHCI_USB_SUSPEND: ohci_bus_stop(ohci); - DPRINTF("usb-ohci: %s: USB Suspended\n", ohci->name); break; case OHCI_USB_RESUME: - DPRINTF("usb-ohci: %s: USB Resume\n", ohci->name); + trace_usb_ohci_resume(ohci->name); break; case OHCI_USB_RESET: ohci_reset(ohci); - DPRINTF("usb-ohci: %s: USB Reset\n", ohci->name); break; } } @@ -1505,7 +1486,7 @@ static void ohci_set_hub_status(OHCIState *ohci, uint32_t val) for (i = 0; i < ohci->num_ports; i++) ohci_port_power(ohci, i, 0); - DPRINTF("usb-ohci: powered down all ports\n"); + trace_usb_ohci_hub_power_down(); } if (val & OHCI_RHS_LPSC) { @@ -1513,7 +1494,7 @@ static void ohci_set_hub_status(OHCIState *ohci, uint32_t val) for (i = 0; i < ohci->num_ports; i++) ohci_port_power(ohci, i, 1); - DPRINTF("usb-ohci: powered up all ports\n"); + trace_usb_ohci_hub_power_up(); } if (val & OHCI_RHS_DRWE) @@ -1545,11 +1526,11 @@ static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val) ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES); if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS)) { - DPRINTF("usb-ohci: port %d: SUSPEND\n", portnum); + trace_usb_ohci_port_suspend(portnum); } if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) { - DPRINTF("usb-ohci: port %d: RESET\n", portnum); + trace_usb_ohci_port_reset(portnum); usb_device_reset(port->port.dev); port->ctrl &= ~OHCI_PORT_PRS; /* ??? Should this also set OHCI_PORT_PESC. */ @@ -1577,7 +1558,7 @@ static uint64_t ohci_mem_read(void *opaque, /* Only aligned reads are allowed on OHCI */ if (addr & 3) { - fprintf(stderr, "usb-ohci: Mis-aligned read\n"); + trace_usb_ohci_mem_read_unaligned(addr); return 0xffffffff; } else if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) { /* HcRhPortStatus */ @@ -1683,7 +1664,7 @@ static uint64_t ohci_mem_read(void *opaque, break; default: - fprintf(stderr, "ohci_read: Bad offset %x\n", (int)addr); + trace_usb_ohci_mem_read_bad_offset(addr); retval = 0xffffffff; } } @@ -1700,7 +1681,7 @@ static void ohci_mem_write(void *opaque, /* Only aligned reads are allowed on OHCI */ if (addr & 3) { - fprintf(stderr, "usb-ohci: Mis-aligned write\n"); + trace_usb_ohci_mem_write_unaligned(addr); return; } @@ -1814,7 +1795,7 @@ static void ohci_mem_write(void *opaque, break; default: - fprintf(stderr, "ohci_write: Bad offset %x\n", (int)addr); + trace_usb_ohci_mem_write_bad_offset(addr); break; } } @@ -1867,8 +1848,7 @@ static int usb_ohci_init(OHCIState *ohci, DeviceState *dev, usb_bit_time = 1; } #endif - DPRINTF("usb-ohci: usb_bit_time=%" PRId64 " usb_frame_time=%" PRId64 "\n", - usb_frame_time, usb_bit_time); + trace_usb_ohci_init_time(usb_frame_time, usb_bit_time); } ohci->num_ports = num_ports; @@ -1926,7 +1906,7 @@ static void ohci_die(OHCIState *ohci) { OHCIPCIState *dev = container_of(ohci, OHCIPCIState, state); - fprintf(stderr, "%s: DMA error\n", __func__); + trace_usb_ohci_die(); ohci_set_interrupt(ohci, OHCI_INTR_UE); ohci_bus_stop(ohci); @@ -1952,6 +1932,25 @@ static int usb_ohci_initfn_pci(PCIDevice *dev) return 0; } +static void usb_ohci_exit(PCIDevice *dev) +{ + OHCIPCIState *ohci = PCI_OHCI(dev); + OHCIState *s = &ohci->state; + + trace_usb_ohci_exit(s->name); + ohci_bus_stop(s); + + if (s->async_td) { + usb_cancel_packet(&s->usb_packet); + s->async_td = 0; + } + ohci_stop_endpoints(s); + + if (!ohci->masterbus) { + usb_bus_release(&s->bus); + } +} + #define TYPE_SYSBUS_OHCI "sysbus-ohci" #define SYSBUS_OHCI(obj) OBJECT_CHECK(OHCISysBusState, (obj), TYPE_SYSBUS_OHCI) @@ -1984,12 +1983,112 @@ static Property ohci_pci_properties[] = { DEFINE_PROP_END_OF_LIST(), }; +static const VMStateDescription vmstate_ohci_state_port = { + .name = "ohci-core/port", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT32(ctrl, OHCIPort), + VMSTATE_END_OF_LIST() + }, +}; + +static bool ohci_eof_timer_needed(void *opaque) +{ + OHCIState *ohci = opaque; + + return ohci->eof_timer != NULL; +} + +static int ohci_eof_timer_pre_load(void *opaque) +{ + OHCIState *ohci = opaque; + + ohci_bus_start(ohci); + + return 0; +} + +static const VMStateDescription vmstate_ohci_eof_timer = { + .name = "ohci-core/eof-timer", + .version_id = 1, + .minimum_version_id = 1, + .pre_load = ohci_eof_timer_pre_load, + .fields = (VMStateField[]) { + VMSTATE_TIMER(eof_timer, OHCIState), + VMSTATE_END_OF_LIST() + }, +}; + +static const VMStateDescription vmstate_ohci_state = { + .name = "ohci-core", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_INT64(sof_time, OHCIState), + VMSTATE_UINT32(ctl, OHCIState), + VMSTATE_UINT32(status, OHCIState), + VMSTATE_UINT32(intr_status, OHCIState), + VMSTATE_UINT32(intr, OHCIState), + VMSTATE_UINT32(hcca, OHCIState), + VMSTATE_UINT32(ctrl_head, OHCIState), + VMSTATE_UINT32(ctrl_cur, OHCIState), + VMSTATE_UINT32(bulk_head, OHCIState), + VMSTATE_UINT32(bulk_cur, OHCIState), + VMSTATE_UINT32(per_cur, OHCIState), + VMSTATE_UINT32(done, OHCIState), + VMSTATE_INT32(done_count, OHCIState), + VMSTATE_UINT16(fsmps, OHCIState), + VMSTATE_UINT8(fit, OHCIState), + VMSTATE_UINT16(fi, OHCIState), + VMSTATE_UINT8(frt, OHCIState), + VMSTATE_UINT16(frame_number, OHCIState), + VMSTATE_UINT16(padding, OHCIState), + VMSTATE_UINT32(pstart, OHCIState), + VMSTATE_UINT32(lst, OHCIState), + VMSTATE_UINT32(rhdesc_a, OHCIState), + VMSTATE_UINT32(rhdesc_b, OHCIState), + VMSTATE_UINT32(rhstatus, OHCIState), + VMSTATE_STRUCT_ARRAY(rhport, OHCIState, OHCI_MAX_PORTS, 0, + vmstate_ohci_state_port, OHCIPort), + VMSTATE_UINT32(hstatus, OHCIState), + VMSTATE_UINT32(hmask, OHCIState), + VMSTATE_UINT32(hreset, OHCIState), + VMSTATE_UINT32(htest, OHCIState), + VMSTATE_UINT32(old_ctl, OHCIState), + VMSTATE_UINT8_ARRAY(usb_buf, OHCIState, 8192), + VMSTATE_UINT32(async_td, OHCIState), + VMSTATE_BOOL(async_complete, OHCIState), + VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection []) { + { + .vmsd = &vmstate_ohci_eof_timer, + .needed = ohci_eof_timer_needed, + } , { + /* empty */ + } + } +}; + +static const VMStateDescription vmstate_ohci = { + .name = "ohci", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_PCI_DEVICE(parent_obj, OHCIPCIState), + VMSTATE_STRUCT(state, OHCIPCIState, 1, vmstate_ohci_state, OHCIState), + VMSTATE_END_OF_LIST() + } +}; + static void ohci_pci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->init = usb_ohci_initfn_pci; + k->exit = usb_ohci_exit; k->vendor_id = PCI_VENDOR_ID_APPLE; k->device_id = PCI_DEVICE_ID_APPLE_IPID_USB; k->class_id = PCI_CLASS_SERIAL_USB; @@ -1997,6 +2096,7 @@ static void ohci_pci_class_init(ObjectClass *klass, void *data) dc->desc = "Apple USB Controller"; dc->props = ohci_pci_properties; dc->hotpluggable = false; + dc->vmsd = &vmstate_ohci; } static const TypeInfo ohci_pci_info = { diff --git a/hw/usb/hcd-uhci.c b/hw/usb/hcd-uhci.c index 0820244905..4a4215d332 100644 --- a/hw/usb/hcd-uhci.c +++ b/hw/usb/hcd-uhci.c @@ -27,6 +27,7 @@ */ #include "hw/hw.h" #include "hw/usb.h" +#include "hw/usb/uhci-regs.h" #include "hw/pci/pci.h" #include "qemu/timer.h" #include "qemu/iov.h" @@ -34,44 +35,6 @@ #include "trace.h" #include "qemu/main-loop.h" -//#define DEBUG -//#define DEBUG_DUMP_DATA - -#define UHCI_CMD_FGR (1 << 4) -#define UHCI_CMD_EGSM (1 << 3) -#define UHCI_CMD_GRESET (1 << 2) -#define UHCI_CMD_HCRESET (1 << 1) -#define UHCI_CMD_RS (1 << 0) - -#define UHCI_STS_HCHALTED (1 << 5) -#define UHCI_STS_HCPERR (1 << 4) -#define UHCI_STS_HSERR (1 << 3) -#define UHCI_STS_RD (1 << 2) -#define UHCI_STS_USBERR (1 << 1) -#define UHCI_STS_USBINT (1 << 0) - -#define TD_CTRL_SPD (1 << 29) -#define TD_CTRL_ERROR_SHIFT 27 -#define TD_CTRL_IOS (1 << 25) -#define TD_CTRL_IOC (1 << 24) -#define TD_CTRL_ACTIVE (1 << 23) -#define TD_CTRL_STALL (1 << 22) -#define TD_CTRL_BABBLE (1 << 20) -#define TD_CTRL_NAK (1 << 19) -#define TD_CTRL_TIMEOUT (1 << 18) - -#define UHCI_PORT_SUSPEND (1 << 12) -#define UHCI_PORT_RESET (1 << 9) -#define UHCI_PORT_LSDA (1 << 8) -#define UHCI_PORT_RD (1 << 6) -#define UHCI_PORT_ENC (1 << 3) -#define UHCI_PORT_EN (1 << 2) -#define UHCI_PORT_CSC (1 << 1) -#define UHCI_PORT_CCS (1 << 0) - -#define UHCI_PORT_READ_ONLY (0x1bb) -#define UHCI_PORT_WRITE_CLEAR (UHCI_PORT_CSC | UHCI_PORT_ENC) - #define FRAME_TIMER_FREQ 1000 #define FRAME_MAX_LOOPS 256 @@ -422,8 +385,7 @@ static const VMStateDescription vmstate_uhci_port = { .name = "uhci port", .version_id = 1, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_UINT16(ctrl, UHCIPort), VMSTATE_END_OF_LIST() } @@ -444,9 +406,8 @@ static const VMStateDescription vmstate_uhci = { .name = "uhci", .version_id = 3, .minimum_version_id = 1, - .minimum_version_id_old = 1, .post_load = uhci_post_load, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, UHCIState), VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState), VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1, @@ -1296,16 +1257,37 @@ static void usb_uhci_exit(PCIDevice *dev) { UHCIState *s = DO_UPCAST(UHCIState, dev, dev); - memory_region_destroy(&s->io_bar); + trace_usb_uhci_exit(); + + if (s->frame_timer) { + timer_del(s->frame_timer); + timer_free(s->frame_timer); + s->frame_timer = NULL; + } + + if (s->bh) { + qemu_bh_delete(s->bh); + } + + uhci_async_cancel_all(s); + + if (!s->masterbus) { + usb_bus_release(&s->bus); + } } -static Property uhci_properties[] = { +static Property uhci_properties_companion[] = { DEFINE_PROP_STRING("masterbus", UHCIState, masterbus), DEFINE_PROP_UINT32("firstport", UHCIState, firstport, 0), DEFINE_PROP_UINT32("bandwidth", UHCIState, frame_bandwidth, 1280), DEFINE_PROP_UINT32("maxframes", UHCIState, maxframes, 128), DEFINE_PROP_END_OF_LIST(), }; +static Property uhci_properties_standalone[] = { + DEFINE_PROP_UINT32("bandwidth", UHCIState, frame_bandwidth, 1280), + DEFINE_PROP_UINT32("maxframes", UHCIState, maxframes, 128), + DEFINE_PROP_END_OF_LIST(), +}; static void uhci_class_init(ObjectClass *klass, void *data) { @@ -1320,9 +1302,14 @@ static void uhci_class_init(ObjectClass *klass, void *data) k->device_id = info->device_id; k->revision = info->revision; k->class_id = PCI_CLASS_SERIAL_USB; - dc->hotpluggable = false; dc->vmsd = &vmstate_uhci; - dc->props = uhci_properties; + if (!info->unplug) { + /* uhci controllers in companion setups can't be hotplugged */ + dc->hotpluggable = false; + dc->props = uhci_properties_companion; + } else { + dc->props = uhci_properties_standalone; + } set_bit(DEVICE_CATEGORY_USB, dc->categories); u->info = *info; } diff --git a/hw/usb/hcd-xhci.c b/hw/usb/hcd-xhci.c index ef3177aee9..9a942cfad4 100644 --- a/hw/usb/hcd-xhci.c +++ b/hw/usb/hcd-xhci.c @@ -459,6 +459,7 @@ struct XHCIState { uint32_t numintrs; uint32_t numslots; uint32_t flags; + uint32_t max_pstreams_mask; /* Operational Registers */ uint32_t usbcmd; @@ -498,6 +499,9 @@ typedef struct XHCIEvRingSeg { enum xhci_flags { XHCI_FLAG_USE_MSI = 1, XHCI_FLAG_USE_MSI_X, + XHCI_FLAG_SS_FIRST, + XHCI_FLAG_FORCE_PCIE_ENDCAP, + XHCI_FLAG_ENABLE_STREAMS, }; static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, @@ -621,6 +625,11 @@ static const char *ep_state_name(uint32_t state) ARRAY_SIZE(ep_state_names)); } +static bool xhci_get_flag(XHCIState *xhci, enum xhci_flags bit) +{ + return xhci->flags & (1 << bit); +} + static uint64_t xhci_mfindex_get(XHCIState *xhci) { int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); @@ -709,10 +718,18 @@ static XHCIPort *xhci_lookup_port(XHCIState *xhci, struct USBPort *uport) case USB_SPEED_LOW: case USB_SPEED_FULL: case USB_SPEED_HIGH: - index = uport->index; + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + index = uport->index + xhci->numports_3; + } else { + index = uport->index; + } break; case USB_SPEED_SUPER: - index = uport->index + xhci->numports_2; + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + index = uport->index; + } else { + index = uport->index + xhci->numports_2; + } break; default: return NULL; @@ -1137,7 +1154,7 @@ static void xhci_reset_streams(XHCIEPContext *epctx) static void xhci_alloc_streams(XHCIEPContext *epctx, dma_addr_t base) { assert(epctx->pstreams == NULL); - epctx->nr_pstreams = 2 << (epctx->max_pstreams + 1); + epctx->nr_pstreams = 2 << epctx->max_pstreams; epctx->pstreams = xhci_alloc_stream_contexts(epctx->nr_pstreams, base); } @@ -1166,7 +1183,7 @@ static int xhci_epmask_to_eps_with_streams(XHCIState *xhci, slot = &xhci->slots[slotid - 1]; for (i = 2, j = 0; i <= 31; i++) { - if (!(epmask & (1 << i))) { + if (!(epmask & (1u << i))) { continue; } @@ -1366,14 +1383,11 @@ static void xhci_init_epctx(XHCIEPContext *epctx, dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]); epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK; - DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type); epctx->pctx = pctx; epctx->max_psize = ctx[1]>>16; epctx->max_psize *= 1+((ctx[1]>>8)&0xff); - epctx->max_pstreams = (ctx[0] >> 10) & 0xf; + epctx->max_pstreams = (ctx[0] >> 10) & epctx->xhci->max_pstreams_mask; epctx->lsa = (ctx[0] >> 15) & 1; - DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n", - epid/2, epid%2, epctx->max_psize); if (epctx->max_pstreams) { xhci_alloc_streams(epctx, dequeue); } else { @@ -1404,6 +1418,9 @@ static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid, slot->eps[epid-1] = epctx; xhci_init_epctx(epctx, pctx, ctx); + DPRINTF("xhci: endpoint %d.%d type is %d, max transaction (burst) " + "size is %d\n", epid/2, epid%2, epctx->type, epctx->max_psize); + epctx->mfindex_last = 0; epctx->state = EP_RUNNING; @@ -1593,12 +1610,6 @@ static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid, "data might be lost\n"); } - uint8_t ep = epid>>1; - - if (epid & 1) { - ep |= 0x80; - } - if (!xhci->slots[slotid-1].uport || !xhci->slots[slotid-1].uport->dev || !xhci->slots[slotid-1].uport->dev->attached) { @@ -2251,6 +2262,9 @@ static USBPort *xhci_lookup_uport(XHCIState *xhci, uint32_t *slot_ctx) int i, pos, port; port = (slot_ctx[1]>>16) & 0xFF; + if (port < 1 || port > xhci->numports) { + return NULL; + } port = xhci->ports[port-1].uport->index+1; pos = snprintf(path, sizeof(path), "%d", port); for (i = 0; i < 5; i++) { @@ -2451,7 +2465,7 @@ static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid, res = xhci_alloc_device_streams(xhci, slotid, ictl_ctx[1]); if (res != CC_SUCCESS) { for (i = 2; i <= 31; i++) { - if (ictl_ctx[1] & (1 << i)) { + if (ictl_ctx[1] & (1u << i)) { xhci_disable_ep(xhci, slotid, i); } } @@ -2851,7 +2865,7 @@ static void xhci_port_update(XHCIPort *port, int is_detach) static void xhci_port_reset(XHCIPort *port, bool warm_reset) { - trace_usb_xhci_port_reset(port->portnr); + trace_usb_xhci_port_reset(port->portnr, warm_reset); if (!xhci_port_have_device(port)) { return; @@ -2947,9 +2961,9 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size) break; case 0x10: /* HCCPARAMS */ if (sizeof(dma_addr_t) == 4) { - ret = 0x00087000; + ret = 0x00080000 | (xhci->max_pstreams_mask << 12); } else { - ret = 0x00087001; + ret = 0x00080001 | (xhci->max_pstreams_mask << 12); } break; case 0x14: /* DBOFF */ @@ -2967,7 +2981,11 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size) ret = 0x20425355; /* "USB " */ break; case 0x28: /* Supported Protocol:08 */ - ret = 0x00000001 | (xhci->numports_2<<8); + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + ret = (xhci->numports_2<<8) | (xhci->numports_3+1); + } else { + ret = (xhci->numports_2<<8) | 1; + } break; case 0x2c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ @@ -2979,7 +2997,11 @@ static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size) ret = 0x20425355; /* "USB " */ break; case 0x38: /* Supported Protocol:08 */ - ret = 0x00000000 | (xhci->numports_2+1) | (xhci->numports_3<<8); + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + ret = (xhci->numports_3<<8) | 1; + } else { + ret = (xhci->numports_3<<8) | (xhci->numports_2+1); + } break; case 0x3c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ @@ -3435,7 +3457,7 @@ static void xhci_child_detach(USBPort *uport, USBDevice *child) USBBus *bus = usb_bus_from_device(child); XHCIState *xhci = container_of(bus, XHCIState, bus); - xhci_detach_slot(xhci, uport); + xhci_detach_slot(xhci, child->port); } static USBPortOps xhci_uport_ops = { @@ -3512,8 +3534,13 @@ static void usb_xhci_init(XHCIState *xhci) for (i = 0; i < usbports; i++) { speedmask = 0; if (i < xhci->numports_2) { - port = &xhci->ports[i]; - port->portnr = i + 1; + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + port = &xhci->ports[i + xhci->numports_3]; + port->portnr = i + 1 + xhci->numports_3; + } else { + port = &xhci->ports[i]; + port->portnr = i + 1; + } port->uport = &xhci->uports[i]; port->speedmask = USB_SPEED_MASK_LOW | @@ -3523,8 +3550,13 @@ static void usb_xhci_init(XHCIState *xhci) speedmask |= port->speedmask; } if (i < xhci->numports_3) { - port = &xhci->ports[i + xhci->numports_2]; - port->portnr = i + 1 + xhci->numports_2; + if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { + port = &xhci->ports[i]; + port->portnr = i + 1; + } else { + port = &xhci->ports[i + xhci->numports_2]; + port->portnr = i + 1 + xhci->numports_2; + } port->uport = &xhci->uports[i]; port->speedmask = USB_SPEED_MASK_SUPER; snprintf(port->name, sizeof(port->name), "usb3 port #%d", i+1); @@ -3563,6 +3595,11 @@ static int usb_xhci_initfn(struct PCIDevice *dev) if (xhci->numslots < 1) { xhci->numslots = 1; } + if (xhci_get_flag(xhci, XHCI_FLAG_ENABLE_STREAMS)) { + xhci->max_pstreams_mask = 7; /* == 256 primary streams */ + } else { + xhci->max_pstreams_mask = 0; + } xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci); @@ -3594,13 +3631,16 @@ static int usb_xhci_initfn(struct PCIDevice *dev) PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64, &xhci->mem); - ret = pcie_endpoint_cap_init(dev, 0xa0); - assert(ret >= 0); + if (pci_bus_is_express(dev->bus) || + xhci_get_flag(xhci, XHCI_FLAG_FORCE_PCIE_ENDCAP)) { + ret = pcie_endpoint_cap_init(dev, 0xa0); + assert(ret >= 0); + } - if (xhci->flags & (1 << XHCI_FLAG_USE_MSI)) { + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI)) { msi_init(dev, 0x70, xhci->numintrs, true, false); } - if (xhci->flags & (1 << XHCI_FLAG_USE_MSI_X)) { + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI_X)) { msix_init(dev, xhci->numintrs, &xhci->mem, 0, OFF_MSIX_TABLE, &xhci->mem, 0, OFF_MSIX_PBA, @@ -3610,6 +3650,43 @@ static int usb_xhci_initfn(struct PCIDevice *dev) return 0; } +static void usb_xhci_exit(PCIDevice *dev) +{ + int i; + XHCIState *xhci = XHCI(dev); + + trace_usb_xhci_exit(); + + for (i = 0; i < xhci->numslots; i++) { + xhci_disable_slot(xhci, i + 1); + } + + if (xhci->mfwrap_timer) { + timer_del(xhci->mfwrap_timer); + timer_free(xhci->mfwrap_timer); + xhci->mfwrap_timer = NULL; + } + + memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); + memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); + memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); + memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); + + for (i = 0; i < xhci->numports; i++) { + XHCIPort *port = &xhci->ports[i]; + memory_region_del_subregion(&xhci->mem, &port->mem); + } + + /* destroy msix memory region */ + if (dev->msix_table && dev->msix_pba + && dev->msix_entry_used) { + memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio); + memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio); + } + + usb_bus_release(&xhci->bus); +} + static int usb_xhci_post_load(void *opaque, int version_id) { XHCIState *xhci = opaque; @@ -3632,6 +3709,12 @@ static int usb_xhci_post_load(void *opaque, int version_id) xhci_mask64(ldq_le_pci_dma(pci_dev, dcbaap + 8 * slotid)); xhci_dma_read_u32s(xhci, slot->ctx, slot_ctx, sizeof(slot_ctx)); slot->uport = xhci_lookup_uport(xhci, slot_ctx); + if (!slot->uport) { + /* should not happen, but may trigger on guest bugs */ + slot->enabled = 0; + slot->addressed = 0; + continue; + } assert(slot->uport && slot->uport->dev); for (epid = 1; epid <= 31; epid++) { @@ -3703,6 +3786,7 @@ static const VMStateDescription vmstate_xhci_event = { VMSTATE_UINT32(flags, XHCIEvent), VMSTATE_UINT8(slotid, XHCIEvent), VMSTATE_UINT8(epid, XHCIEvent), + VMSTATE_END_OF_LIST() } }; @@ -3781,6 +3865,12 @@ static const VMStateDescription vmstate_xhci = { static Property xhci_properties[] = { DEFINE_PROP_BIT("msi", XHCIState, flags, XHCI_FLAG_USE_MSI, true), DEFINE_PROP_BIT("msix", XHCIState, flags, XHCI_FLAG_USE_MSI_X, true), + DEFINE_PROP_BIT("superspeed-ports-first", + XHCIState, flags, XHCI_FLAG_SS_FIRST, true), + DEFINE_PROP_BIT("force-pcie-endcap", XHCIState, flags, + XHCI_FLAG_FORCE_PCIE_ENDCAP, false), + DEFINE_PROP_BIT("streams", XHCIState, flags, + XHCI_FLAG_ENABLE_STREAMS, true), DEFINE_PROP_UINT32("intrs", XHCIState, numintrs, MAXINTRS), DEFINE_PROP_UINT32("slots", XHCIState, numslots, MAXSLOTS), DEFINE_PROP_UINT32("p2", XHCIState, numports_2, 4), @@ -3796,9 +3886,9 @@ static void xhci_class_init(ObjectClass *klass, void *data) dc->vmsd = &vmstate_xhci; dc->props = xhci_properties; dc->reset = xhci_reset; - dc->hotpluggable = false; set_bit(DEVICE_CATEGORY_USB, dc->categories); k->init = usb_xhci_initfn; + k->exit = usb_xhci_exit; k->vendor_id = PCI_VENDOR_ID_NEC; k->device_id = PCI_DEVICE_ID_NEC_UPD720200; k->class_id = PCI_CLASS_SERIAL_USB; diff --git a/hw/usb/host-libusb.c b/hw/usb/host-libusb.c index 57bed09a1e..a5f9dab0cd 100644 --- a/hw/usb/host-libusb.c +++ b/hw/usb/host-libusb.c @@ -111,6 +111,7 @@ struct USBHostRequest { unsigned char *buffer; unsigned char *cbuf; unsigned int clen; + bool usb3ep0quirk; QTAILQ_ENTRY(USBHostRequest) next; }; @@ -142,10 +143,20 @@ static void usb_host_attach_kernel(USBHostDevice *s); /* ------------------------------------------------------------------------ */ +#ifndef LIBUSB_LOG_LEVEL_WARNING /* older libusb didn't define these */ +#define LIBUSB_LOG_LEVEL_WARNING 2 +#endif + +/* ------------------------------------------------------------------------ */ + #define CONTROL_TIMEOUT 10000 /* 10 sec */ #define BULK_TIMEOUT 0 /* unlimited */ #define INTR_TIMEOUT 0 /* unlimited */ +#if LIBUSBX_API_VERSION >= 0x01000103 +# define HAVE_STREAMS 1 +#endif + static const char *speed_name[] = { [LIBUSB_SPEED_UNKNOWN] = "?", [LIBUSB_SPEED_LOW] = "1.5", @@ -270,7 +281,7 @@ static void usb_host_libusb_error(const char *func, int rc) } else { errname = "?"; } - fprintf(stderr, "%s: %d [%s]\n", func, rc, errname); + error_report("%s: %d [%s]", func, rc, errname); } /* ------------------------------------------------------------------------ */ @@ -346,6 +357,13 @@ static void usb_host_req_complete_ctrl(struct libusb_transfer *xfer) r->p->actual_length = xfer->actual_length; if (r->in && xfer->actual_length) { memcpy(r->cbuf, r->buffer + 8, xfer->actual_length); + + /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices + * to work redirected to a not superspeed capable hcd */ + if (r->usb3ep0quirk && xfer->actual_length >= 18 && + r->cbuf[7] == 9) { + r->cbuf[7] = 64; + } } trace_usb_host_req_complete(s->bus_num, s->addr, r->p, r->p->status, r->p->actual_length); @@ -672,11 +690,17 @@ static void usb_host_iso_data_out(USBHostDevice *s, USBPacket *p) /* ------------------------------------------------------------------------ */ -static bool usb_host_full_speed_compat(USBHostDevice *s) +static void usb_host_speed_compat(USBHostDevice *s) { + USBDevice *udev = USB_DEVICE(s); struct libusb_config_descriptor *conf; const struct libusb_interface_descriptor *intf; const struct libusb_endpoint_descriptor *endp; +#ifdef HAVE_STREAMS + struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp; +#endif + bool compat_high = true; + bool compat_full = true; uint8_t type; int rc, c, i, a, e; @@ -693,10 +717,27 @@ static bool usb_host_full_speed_compat(USBHostDevice *s) type = endp->bmAttributes & 0x3; switch (type) { case 0x01: /* ISO */ - return false; + compat_full = false; + compat_high = false; + break; + case 0x02: /* BULK */ +#ifdef HAVE_STREAMS + rc = libusb_get_ss_endpoint_companion_descriptor + (ctx, endp, &endp_ss_comp); + if (rc == LIBUSB_SUCCESS) { + libusb_free_ss_endpoint_companion_descriptor + (endp_ss_comp); + compat_full = false; + compat_high = false; + } +#endif + break; case 0x03: /* INTERRUPT */ if (endp->wMaxPacketSize > 64) { - return false; + compat_full = false; + } + if (endp->wMaxPacketSize > 1024) { + compat_high = false; } break; } @@ -705,7 +746,17 @@ static bool usb_host_full_speed_compat(USBHostDevice *s) } libusb_free_config_descriptor(conf); } - return true; + + udev->speedmask = (1 << udev->speed); + if (udev->speed == USB_SPEED_SUPER && compat_high) { + udev->speedmask |= USB_SPEED_MASK_HIGH; + } + if (udev->speed == USB_SPEED_SUPER && compat_full) { + udev->speedmask |= USB_SPEED_MASK_FULL; + } + if (udev->speed == USB_SPEED_HIGH && compat_full) { + udev->speedmask |= USB_SPEED_MASK_FULL; + } } static void usb_host_ep_update(USBHostDevice *s) @@ -720,6 +771,9 @@ static void usb_host_ep_update(USBHostDevice *s) struct libusb_config_descriptor *conf; const struct libusb_interface_descriptor *intf; const struct libusb_endpoint_descriptor *endp; +#ifdef HAVE_STREAMS + struct libusb_ss_endpoint_companion_descriptor *endp_ss_comp; +#endif uint8_t devep, type; int pid, ep; int rc, i, e; @@ -765,6 +819,15 @@ static void usb_host_ep_update(USBHostDevice *s) usb_ep_set_type(udev, pid, ep, type); usb_ep_set_ifnum(udev, pid, ep, i); usb_ep_set_halted(udev, pid, ep, 0); +#ifdef HAVE_STREAMS + if (type == LIBUSB_TRANSFER_TYPE_BULK && + libusb_get_ss_endpoint_companion_descriptor(ctx, endp, + &endp_ss_comp) == LIBUSB_SUCCESS) { + usb_ep_set_max_streams(udev, pid, ep, + endp_ss_comp->bmAttributes); + libusb_free_ss_endpoint_companion_descriptor(endp_ss_comp); + } +#endif } } @@ -777,6 +840,7 @@ static int usb_host_open(USBHostDevice *s, libusb_device *dev) int bus_num = libusb_get_bus_number(dev); int addr = libusb_get_device_address(dev); int rc; + Error *local_err = NULL; trace_usb_host_open_started(bus_num, addr); @@ -801,10 +865,7 @@ static int usb_host_open(USBHostDevice *s, libusb_device *dev) usb_host_ep_update(s); udev->speed = speed_map[libusb_get_device_speed(dev)]; - udev->speedmask = (1 << udev->speed); - if (udev->speed == USB_SPEED_HIGH && usb_host_full_speed_compat(s)) { - udev->speedmask |= USB_SPEED_MASK_FULL; - } + usb_host_speed_compat(s); if (s->ddesc.iProduct) { libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct, @@ -815,8 +876,10 @@ static int usb_host_open(USBHostDevice *s, libusb_device *dev) "host:%d.%d", bus_num, addr); } - rc = usb_device_attach(udev); - if (rc) { + usb_device_attach(udev, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); goto fail; } @@ -894,10 +957,23 @@ static void usb_host_exit_notifier(struct Notifier *n, void *data) } } -static int usb_host_initfn(USBDevice *udev) +static void usb_host_realize(USBDevice *udev, Error **errp) { USBHostDevice *s = USB_HOST_DEVICE(udev); + if (s->match.vendor_id > 0xffff) { + error_setg(errp, "vendorid out of range"); + return; + } + if (s->match.product_id > 0xffff) { + error_setg(errp, "productid out of range"); + return; + } + if (s->match.addr > 127) { + error_setg(errp, "hostaddr out of range"); + return; + } + loglevel = s->loglevel; udev->flags |= (1 << USB_DEV_FLAG_IS_HOST); udev->auto_attach = 0; @@ -908,9 +984,17 @@ static int usb_host_initfn(USBDevice *udev) qemu_add_exit_notifier(&s->exit); QTAILQ_INSERT_TAIL(&hostdevs, s, next); - add_boot_device_path(s->bootindex, &udev->qdev, NULL); usb_host_auto_check(NULL); - return 0; +} + +static void usb_host_instance_init(Object *obj) +{ + USBDevice *udev = USB_DEVICE(obj); + USBHostDevice *s = USB_HOST_DEVICE(udev); + + device_add_bootindex_property(obj, &s->bootindex, + "bootindex", NULL, + &udev->qdev, NULL); } static void usb_host_handle_destroy(USBDevice *udev) @@ -1150,6 +1234,14 @@ static void usb_host_handle_control(USBDevice *udev, USBPacket *p, memcpy(r->buffer + 8, r->cbuf, r->clen); } + /* Fix up USB-3 ep0 maxpacket size to allow superspeed connected devices + * to work redirected to a not superspeed capable hcd */ + if (udev->speed == USB_SPEED_SUPER && + !((udev->port->speedmask & USB_SPEED_MASK_SUPER)) && + request == 0x8006 && value == 0x100 && index == 0) { + r->usb3ep0quirk = true; + } + libusb_fill_control_transfer(r->xfer, s->dh, r->buffer, usb_host_req_complete_ctrl, r, CONTROL_TIMEOUT); @@ -1202,10 +1294,23 @@ static void usb_host_handle_data(USBDevice *udev, USBPacket *p) usb_packet_copy(p, r->buffer, size); } ep = p->ep->nr | (r->in ? USB_DIR_IN : 0); - libusb_fill_bulk_transfer(r->xfer, s->dh, ep, - r->buffer, size, - usb_host_req_complete_data, r, - BULK_TIMEOUT); + if (p->stream) { +#ifdef HAVE_STREAMS + libusb_fill_bulk_stream_transfer(r->xfer, s->dh, ep, p->stream, + r->buffer, size, + usb_host_req_complete_data, r, + BULK_TIMEOUT); +#else + usb_host_req_free(r); + p->status = USB_RET_STALL; + return; +#endif + } else { + libusb_fill_bulk_transfer(r->xfer, s->dh, ep, + r->buffer, size, + usb_host_req_complete_data, r, + BULK_TIMEOUT); + } break; case USB_ENDPOINT_XFER_INT: r = usb_host_req_alloc(s, p, p->pid == USB_TOKEN_IN, p->iov.size); @@ -1268,6 +1373,53 @@ static void usb_host_handle_reset(USBDevice *udev) } } +static int usb_host_alloc_streams(USBDevice *udev, USBEndpoint **eps, + int nr_eps, int streams) +{ +#ifdef HAVE_STREAMS + USBHostDevice *s = USB_HOST_DEVICE(udev); + unsigned char endpoints[30]; + int i, rc; + + for (i = 0; i < nr_eps; i++) { + endpoints[i] = eps[i]->nr; + if (eps[i]->pid == USB_TOKEN_IN) { + endpoints[i] |= 0x80; + } + } + rc = libusb_alloc_streams(s->dh, streams, endpoints, nr_eps); + if (rc < 0) { + usb_host_libusb_error("libusb_alloc_streams", rc); + } else if (rc != streams) { + error_report("libusb_alloc_streams: got less streams " + "then requested %d < %d", rc, streams); + } + + return (rc == streams) ? 0 : -1; +#else + error_report("libusb_alloc_streams: error not implemented"); + return -1; +#endif +} + +static void usb_host_free_streams(USBDevice *udev, USBEndpoint **eps, + int nr_eps) +{ +#ifdef HAVE_STREAMS + USBHostDevice *s = USB_HOST_DEVICE(udev); + unsigned char endpoints[30]; + int i; + + for (i = 0; i < nr_eps; i++) { + endpoints[i] = eps[i]->nr; + if (eps[i]->pid == USB_TOKEN_IN) { + endpoints[i] |= 0x80; + } + } + libusb_free_streams(s->dh, endpoints, nr_eps); +#endif +} + /* * This is *NOT* about restoring state. We have absolutely no idea * what state the host device is in at the moment and whenever it is @@ -1328,7 +1480,6 @@ static Property usb_host_dev_properties[] = { DEFINE_PROP_UINT32("productid", USBHostDevice, match.product_id, 0), DEFINE_PROP_UINT32("isobufs", USBHostDevice, iso_urb_count, 4), DEFINE_PROP_UINT32("isobsize", USBHostDevice, iso_urb_frames, 32), - DEFINE_PROP_INT32("bootindex", USBHostDevice, bootindex, -1), DEFINE_PROP_UINT32("loglevel", USBHostDevice, loglevel, LIBUSB_LOG_LEVEL_WARNING), DEFINE_PROP_BIT("pipeline", USBHostDevice, options, @@ -1341,7 +1492,7 @@ static void usb_host_class_initfn(ObjectClass *klass, void *data) DeviceClass *dc = DEVICE_CLASS(klass); USBDeviceClass *uc = USB_DEVICE_CLASS(klass); - uc->init = usb_host_initfn; + uc->realize = usb_host_realize; uc->product_desc = "USB Host Device"; uc->cancel_packet = usb_host_cancel_packet; uc->handle_data = usb_host_handle_data; @@ -1349,6 +1500,8 @@ static void usb_host_class_initfn(ObjectClass *klass, void *data) uc->handle_reset = usb_host_handle_reset; uc->handle_destroy = usb_host_handle_destroy; uc->flush_ep_queue = usb_host_flush_ep_queue; + uc->alloc_streams = usb_host_alloc_streams; + uc->free_streams = usb_host_free_streams; dc->vmsd = &vmstate_usb_host; dc->props = usb_host_dev_properties; set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); @@ -1359,6 +1512,7 @@ static TypeInfo usb_host_dev_info = { .parent = TYPE_USB_DEVICE, .instance_size = sizeof(USBHostDevice), .class_init = usb_host_class_initfn, + .instance_init = usb_host_instance_init, }; static void usb_host_register_types(void) @@ -1384,7 +1538,7 @@ static void usb_host_auto_check(void *unused) { struct USBHostDevice *s; struct USBAutoFilter *f; - libusb_device **devs; + libusb_device **devs = NULL; struct libusb_device_descriptor ddesc; int unconnected = 0; int i, n; @@ -1485,7 +1639,7 @@ static void usb_host_auto_check(void *unused) void usb_host_info(Monitor *mon, const QDict *qdict) { - libusb_device **devs; + libusb_device **devs = NULL; struct libusb_device_descriptor ddesc; char port[16]; int i, n; diff --git a/hw/usb/redirect.c b/hw/usb/redirect.c index 287a505b48..9fbd59e5ee 100644 --- a/hw/usb/redirect.c +++ b/hw/usb/redirect.c @@ -50,6 +50,10 @@ ((i) & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT, \ (i) & 0x0f)) +#ifndef USBREDIR_VERSION /* This is not defined in older usbredir versions */ +#define USBREDIR_VERSION 0 +#endif + typedef struct USBRedirDevice USBRedirDevice; /* Struct to hold buffered packets */ @@ -68,6 +72,7 @@ struct endp_data { uint8_t interval; uint8_t interface; /* bInterfaceNumber this ep belongs to */ uint16_t max_packet_size; /* In bytes, not wMaxPacketSize format !! */ + uint32_t max_streams; uint8_t iso_started; uint8_t iso_error; /* For reporting iso errors to the HC */ uint8_t interrupt_started; @@ -106,8 +111,9 @@ struct USBRedirDevice { int read_buf_size; /* Active chardev-watch-tag */ guint watch; - /* For async handling of close */ + /* For async handling of close / reject */ QEMUBH *chardev_close_bh; + QEMUBH *device_reject_bh; /* To delay the usb attach in case of quick chardev close + open */ QEMUTimer *attach_timer; int64_t next_attach_time; @@ -284,7 +290,7 @@ static int usbredir_write(void *priv, uint8_t *data, int count) r = qemu_chr_fe_write(dev->cs, data, count); if (r < count) { if (!dev->watch) { - dev->watch = qemu_chr_fe_add_watch(dev->cs, G_IO_OUT, + dev->watch = qemu_chr_fe_add_watch(dev->cs, G_IO_OUT|G_IO_HUP, usbredir_write_unblocked, dev); } if (r < 0) { @@ -780,11 +786,12 @@ static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p, dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0; } - DPRINTF("bulk-out ep %02X len %zd id %"PRIu64"\n", ep, size, p->id); + DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n", + ep, p->stream, size, p->id); bulk_packet.endpoint = ep; bulk_packet.length = size; - bulk_packet.stream_id = 0; + bulk_packet.stream_id = p->stream; bulk_packet.length_high = size >> 16; assert(bulk_packet.length_high == 0 || usbredirparser_peer_has_cap(dev->parser, @@ -1091,6 +1098,66 @@ static void usbredir_handle_control(USBDevice *udev, USBPacket *p, p->status = USB_RET_ASYNC; } +static int usbredir_alloc_streams(USBDevice *udev, USBEndpoint **eps, + int nr_eps, int streams) +{ + USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev); +#if USBREDIR_VERSION >= 0x000700 + struct usb_redir_alloc_bulk_streams_header alloc_streams; + int i; + + if (!usbredirparser_peer_has_cap(dev->parser, + usb_redir_cap_bulk_streams)) { + ERROR("peer does not support streams\n"); + goto reject; + } + + if (streams == 0) { + ERROR("request to allocate 0 streams\n"); + return -1; + } + + alloc_streams.no_streams = streams; + alloc_streams.endpoints = 0; + for (i = 0; i < nr_eps; i++) { + alloc_streams.endpoints |= 1 << USBEP2I(eps[i]); + } + usbredirparser_send_alloc_bulk_streams(dev->parser, 0, &alloc_streams); + usbredirparser_do_write(dev->parser); + + return 0; +#else + ERROR("usbredir_alloc_streams not implemented\n"); + goto reject; +#endif +reject: + ERROR("streams are not available, disconnecting\n"); + qemu_bh_schedule(dev->device_reject_bh); + return -1; +} + +static void usbredir_free_streams(USBDevice *udev, USBEndpoint **eps, + int nr_eps) +{ +#if USBREDIR_VERSION >= 0x000700 + USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev); + struct usb_redir_free_bulk_streams_header free_streams; + int i; + + if (!usbredirparser_peer_has_cap(dev->parser, + usb_redir_cap_bulk_streams)) { + return; + } + + free_streams.endpoints = 0; + for (i = 0; i < nr_eps; i++) { + free_streams.endpoints |= 1 << USBEP2I(eps[i]); + } + usbredirparser_send_free_bulk_streams(dev->parser, 0, &free_streams); + usbredirparser_do_write(dev->parser); +#endif +} + /* * Close events can be triggered by usbredirparser_do_write which gets called * from within the USBDevice data / control packet callbacks and doing a @@ -1102,6 +1169,7 @@ static void usbredir_chardev_close_bh(void *opaque) { USBRedirDevice *dev = opaque; + qemu_bh_cancel(dev->device_reject_bh); usbredir_device_disconnect(dev); if (dev->parser) { @@ -1153,6 +1221,9 @@ static void usbredir_create_parser(USBRedirDevice *dev) usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids); usbredirparser_caps_set_cap(caps, usb_redir_cap_32bits_bulk_length); usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_receiving); +#if USBREDIR_VERSION >= 0x000700 + usbredirparser_caps_set_cap(caps, usb_redir_cap_bulk_streams); +#endif if (runstate_check(RUN_STATE_INMIGRATE)) { flags |= usbredirparser_fl_no_hello; @@ -1171,9 +1242,21 @@ static void usbredir_reject_device(USBRedirDevice *dev) } } +/* + * We may need to reject the device when the hcd calls alloc_streams, doing + * an usb_detach from within a hcd call is not a good idea, hence this bh. + */ +static void usbredir_device_reject_bh(void *opaque) +{ + USBRedirDevice *dev = opaque; + + usbredir_reject_device(dev); +} + static void usbredir_do_attach(void *opaque) { USBRedirDevice *dev = opaque; + Error *local_err = NULL; /* In order to work properly with XHCI controllers we need these caps */ if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !( @@ -1188,7 +1271,10 @@ static void usbredir_do_attach(void *opaque) return; } - if (usb_device_attach(&dev->dev) != 0) { + usb_device_attach(&dev->dev, &local_err); + if (local_err) { + error_report("%s", error_get_pretty(local_err)); + error_free(local_err); WARNING("rejecting device due to speed mismatch\n"); usbredir_reject_device(dev); } @@ -1275,14 +1361,14 @@ static void usbredir_init_endpoints(USBRedirDevice *dev) } } -static int usbredir_initfn(USBDevice *udev) +static void usbredir_realize(USBDevice *udev, Error **errp) { USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev); int i; if (dev->cs == NULL) { - qerror_report(QERR_MISSING_PARAMETER, "chardev"); - return -1; + error_set(errp, QERR_MISSING_PARAMETER, "chardev"); + return; } if (dev->filter_str) { @@ -1290,13 +1376,14 @@ static int usbredir_initfn(USBDevice *udev) &dev->filter_rules, &dev->filter_rules_count); if (i) { - qerror_report(QERR_INVALID_PARAMETER_VALUE, "filter", - "a usb device filter string"); - return -1; + error_set(errp, QERR_INVALID_PARAMETER_VALUE, "filter", + "a usb device filter string"); + return; } } dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev); + dev->device_reject_bh = qemu_bh_new(usbredir_device_reject_bh, dev); dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev); packet_id_queue_init(&dev->cancelled, dev, "cancelled"); @@ -1314,8 +1401,6 @@ static int usbredir_initfn(USBDevice *udev) usbredir_chardev_read, usbredir_chardev_event, dev); qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev); - add_boot_device_path(dev->bootindex, &udev->qdev, NULL); - return 0; } static void usbredir_cleanup_device_queues(USBRedirDevice *dev) @@ -1337,6 +1422,7 @@ static void usbredir_handle_destroy(USBDevice *udev) dev->cs = NULL; /* Note must be done after qemu_chr_close, as that causes a close event */ qemu_bh_delete(dev->chardev_close_bh); + qemu_bh_delete(dev->device_reject_bh); timer_del(dev->attach_timer); timer_free(dev->attach_timer); @@ -1628,6 +1714,7 @@ static void usbredir_setup_usb_eps(USBRedirDevice *dev) usb_ep->type = dev->endpoint[i].type; usb_ep->ifnum = dev->endpoint[i].interface; usb_ep->max_packet_size = dev->endpoint[i].max_packet_size; + usb_ep->max_streams = dev->endpoint[i].max_streams; usbredir_set_pipeline(dev, usb_ep); } } @@ -1646,6 +1733,12 @@ static void usbredir_ep_info(void *priv, usb_redir_cap_ep_info_max_packet_size)) { dev->endpoint[i].max_packet_size = ep_info->max_packet_size[i]; } +#if USBREDIR_VERSION >= 0x000700 + if (usbredirparser_peer_has_cap(dev->parser, + usb_redir_cap_bulk_streams)) { + dev->endpoint[i].max_streams = ep_info->max_streams[i]; + } +#endif switch (dev->endpoint[i].type) { case usb_redir_type_invalid: break; @@ -1779,6 +1872,20 @@ static void usbredir_interrupt_receiving_status(void *priv, uint64_t id, static void usbredir_bulk_streams_status(void *priv, uint64_t id, struct usb_redir_bulk_streams_status_header *bulk_streams_status) { +#if USBREDIR_VERSION >= 0x000700 + USBRedirDevice *dev = priv; + + if (bulk_streams_status->status == usb_redir_success) { + DPRINTF("bulk streams status %d eps %08x\n", + bulk_streams_status->status, bulk_streams_status->endpoints); + } else { + ERROR("bulk streams %s failed status %d eps %08x\n", + (bulk_streams_status->no_streams == 0) ? "free" : "alloc", + bulk_streams_status->status, bulk_streams_status->endpoints); + ERROR("usb-redir-host does not provide streams, disconnecting\n"); + usbredir_reject_device(dev); + } +#endif } static void usbredir_bulk_receiving_status(void *priv, uint64_t id, @@ -1850,8 +1957,8 @@ static void usbredir_bulk_packet(void *priv, uint64_t id, int len = (bulk_packet->length_high << 16) | bulk_packet->length; USBPacket *p; - DPRINTF("bulk-in status %d ep %02X len %d id %"PRIu64"\n", - bulk_packet->status, ep, len, id); + DPRINTF("bulk-in status %d ep %02X stream %u len %d id %"PRIu64"\n", + bulk_packet->status, ep, bulk_packet->stream_id, len, id); p = usbredir_find_packet_by_id(dev, ep, id); if (p) { @@ -2165,6 +2272,23 @@ static bool usbredir_bulk_receiving_needed(void *priv) return endp->bulk_receiving_started; } +static const VMStateDescription usbredir_stream_vmstate = { + .name = "usb-redir-ep/stream-state", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT32(max_streams, struct endp_data), + VMSTATE_END_OF_LIST() + } +}; + +static bool usbredir_stream_needed(void *priv) +{ + struct endp_data *endp = priv; + + return endp->max_streams; +} + static const VMStateDescription usbredir_ep_vmstate = { .name = "usb-redir-ep", .version_id = 1, @@ -2197,6 +2321,9 @@ static const VMStateDescription usbredir_ep_vmstate = { .vmsd = &usbredir_bulk_receiving_vmstate, .needed = usbredir_bulk_receiving_needed, }, { + .vmsd = &usbredir_stream_vmstate, + .needed = usbredir_stream_needed, + }, { /* empty */ } } @@ -2343,7 +2470,6 @@ static Property usbredir_properties[] = { DEFINE_PROP_CHR("chardev", USBRedirDevice, cs), DEFINE_PROP_UINT8("debug", USBRedirDevice, debug, usbredirparser_warning), DEFINE_PROP_STRING("filter", USBRedirDevice, filter_str), - DEFINE_PROP_INT32("bootindex", USBRedirDevice, bootindex, -1), DEFINE_PROP_END_OF_LIST(), }; @@ -2352,7 +2478,7 @@ static void usbredir_class_initfn(ObjectClass *klass, void *data) USBDeviceClass *uc = USB_DEVICE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); - uc->init = usbredir_initfn; + uc->realize = usbredir_realize; uc->product_desc = "USB Redirection Device"; uc->handle_destroy = usbredir_handle_destroy; uc->cancel_packet = usbredir_cancel_packet; @@ -2361,16 +2487,29 @@ static void usbredir_class_initfn(ObjectClass *klass, void *data) uc->handle_control = usbredir_handle_control; uc->flush_ep_queue = usbredir_flush_ep_queue; uc->ep_stopped = usbredir_ep_stopped; + uc->alloc_streams = usbredir_alloc_streams; + uc->free_streams = usbredir_free_streams; dc->vmsd = &usbredir_vmstate; dc->props = usbredir_properties; set_bit(DEVICE_CATEGORY_MISC, dc->categories); } +static void usbredir_instance_init(Object *obj) +{ + USBDevice *udev = USB_DEVICE(obj); + USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev); + + device_add_bootindex_property(obj, &dev->bootindex, + "bootindex", NULL, + &udev->qdev, NULL); +} + static const TypeInfo usbredir_dev_info = { .name = "usb-redir", .parent = TYPE_USB_DEVICE, .instance_size = sizeof(USBRedirDevice), .class_init = usbredir_class_initfn, + .instance_init = usbredir_instance_init, }; static void usbredir_register_types(void) diff --git a/hw/vigs/vigs_device.c b/hw/vigs/vigs_device.c index c3185da198..562704bfdc 100644 --- a/hw/vigs/vigs_device.c +++ b/hw/vigs/vigs_device.c @@ -385,11 +385,11 @@ static int vigs_device_init(PCIDevice *dev) memory_region_init_ram(&s->vram_bar, OBJECT(s), TYPE_VIGS_DEVICE ".vram", - s->vram_size); + s->vram_size, &error_abort); memory_region_init_ram(&s->ram_bar, OBJECT(s), TYPE_VIGS_DEVICE ".ram", - s->ram_size); + s->ram_size, &error_abort); memory_region_init_io(&s->io_bar, OBJECT(s), &vigs_io_ops, @@ -459,10 +459,6 @@ fail: vigs_fenceman_destroy(s->fenceman); } - memory_region_destroy(&s->io_bar); - memory_region_destroy(&s->ram_bar); - memory_region_destroy(&s->vram_bar); - vigs_log_cleanup(); return -1; @@ -494,10 +490,6 @@ static void vigs_device_exit(PCIDevice *dev) vigs_fenceman_destroy(s->fenceman); - memory_region_destroy(&s->io_bar); - memory_region_destroy(&s->ram_bar); - memory_region_destroy(&s->vram_bar); - VIGS_LOG_INFO("VIGS deinitialized"); vigs_log_cleanup(); diff --git a/hw/virtio/Makefile.objs b/hw/virtio/Makefile.objs index 1ba53d9cc3..d21c397756 100644 --- a/hw/virtio/Makefile.objs +++ b/hw/virtio/Makefile.objs @@ -2,7 +2,7 @@ common-obj-y += virtio-rng.o common-obj-$(CONFIG_VIRTIO_PCI) += virtio-pci.o common-obj-y += virtio-bus.o common-obj-y += virtio-mmio.o -common-obj-$(CONFIG_VIRTIO_BLK_DATA_PLANE) += dataplane/ +common-obj-$(CONFIG_VIRTIO) += dataplane/ obj-y += virtio.o virtio-balloon.o -obj-$(CONFIG_LINUX) += vhost.o +obj-$(CONFIG_LINUX) += vhost.o vhost-backend.o vhost-user.o diff --git a/hw/virtio/dataplane/vring.c b/hw/virtio/dataplane/vring.c index 665a1ffcb3..61f6d83686 100644 --- a/hw/virtio/dataplane/vring.c +++ b/hw/virtio/dataplane/vring.c @@ -181,7 +181,8 @@ static int get_desc(Vring *vring, VirtQueueElement *elem, /* Stop for now if there are not enough iovecs available. */ if (*num >= VIRTQUEUE_MAX_SIZE) { - return -ENOBUFS; + error_report("Invalid SG num: %u", *num); + return -EFAULT; } /* TODO handle non-contiguous memory across region boundaries */ @@ -272,7 +273,7 @@ static int get_indirect(Vring *vring, VirtQueueElement *elem, return 0; } -void vring_free_element(VirtQueueElement *elem) +static void vring_unmap_element(VirtQueueElement *elem) { int i; @@ -287,8 +288,6 @@ void vring_free_element(VirtQueueElement *elem) for (i = 0; i < elem->in_num; i++) { vring_unmap(elem->in_sg[i].iov_base, true); } - - g_slice_free(VirtQueueElement, elem); } /* This looks in the virtqueue and for the first available buffer, and converts @@ -303,14 +302,16 @@ void vring_free_element(VirtQueueElement *elem) * Stolen from linux/drivers/vhost/vhost.c. */ int vring_pop(VirtIODevice *vdev, Vring *vring, - VirtQueueElement **p_elem) + VirtQueueElement *elem) { struct vring_desc desc; unsigned int i, head, found = 0, num = vring->vr.num; uint16_t avail_idx, last_avail_idx; - VirtQueueElement *elem = NULL; int ret; + /* Initialize elem so it can be safely unmapped */ + elem->in_num = elem->out_num = 0; + /* If there was a fatal error then refuse operation */ if (vring->broken) { ret = -EFAULT; @@ -342,10 +343,8 @@ int vring_pop(VirtIODevice *vdev, Vring *vring, * the index we've seen. */ head = vring->vr.avail->ring[last_avail_idx % num]; - elem = g_slice_new(VirtQueueElement); elem->index = head; - elem->in_num = elem->out_num = 0; - + /* If their number is silly, that's an error. */ if (unlikely(head >= num)) { error_report("Guest says index %u > %u is available", head, num); @@ -353,10 +352,6 @@ int vring_pop(VirtIODevice *vdev, Vring *vring, goto out; } - if (vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) { - vring_avail_event(&vring->vr) = vring->vr.avail->idx; - } - i = head; do { if (unlikely(i >= num)) { @@ -393,7 +388,10 @@ int vring_pop(VirtIODevice *vdev, Vring *vring, /* On success, increment avail index. */ vring->last_avail_idx++; - *p_elem = elem; + if (vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) { + vring_avail_event(&vring->vr) = vring->last_avail_idx; + } + return head; out: @@ -401,10 +399,7 @@ out: if (ret == -EFAULT) { vring->broken = true; } - if (elem) { - vring_free_element(elem); - } - *p_elem = NULL; + vring_unmap_element(elem); return ret; } @@ -418,7 +413,7 @@ void vring_push(Vring *vring, VirtQueueElement *elem, int len) unsigned int head = elem->index; uint16_t new; - vring_free_element(elem); + vring_unmap_element(elem); /* Don't touch vring if a fatal error occurred */ if (vring->broken) { diff --git a/hw/virtio/vhost-backend.c b/hw/virtio/vhost-backend.c new file mode 100644 index 0000000000..ff4f2001bb --- /dev/null +++ b/hw/virtio/vhost-backend.c @@ -0,0 +1,69 @@ +/* + * vhost-backend + * + * Copyright (c) 2013 Virtual Open Systems Sarl. + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#include "hw/virtio/vhost.h" +#include "hw/virtio/vhost-backend.h" +#include "qemu/error-report.h" + +#include <sys/ioctl.h> + +static int vhost_kernel_call(struct vhost_dev *dev, unsigned long int request, + void *arg) +{ + int fd = (uintptr_t) dev->opaque; + + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_KERNEL); + + return ioctl(fd, request, arg); +} + +static int vhost_kernel_init(struct vhost_dev *dev, void *opaque) +{ + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_KERNEL); + + dev->opaque = opaque; + + return 0; +} + +static int vhost_kernel_cleanup(struct vhost_dev *dev) +{ + int fd = (uintptr_t) dev->opaque; + + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_KERNEL); + + return close(fd); +} + +static const VhostOps kernel_ops = { + .backend_type = VHOST_BACKEND_TYPE_KERNEL, + .vhost_call = vhost_kernel_call, + .vhost_backend_init = vhost_kernel_init, + .vhost_backend_cleanup = vhost_kernel_cleanup +}; + +int vhost_set_backend_type(struct vhost_dev *dev, VhostBackendType backend_type) +{ + int r = 0; + + switch (backend_type) { + case VHOST_BACKEND_TYPE_KERNEL: + dev->vhost_ops = &kernel_ops; + break; + case VHOST_BACKEND_TYPE_USER: + dev->vhost_ops = &user_ops; + break; + default: + error_report("Unknown vhost backend type\n"); + r = -1; + } + + return r; +} diff --git a/hw/virtio/vhost-user.c b/hw/virtio/vhost-user.c new file mode 100644 index 0000000000..aefe0bbaaf --- /dev/null +++ b/hw/virtio/vhost-user.c @@ -0,0 +1,351 @@ +/* + * vhost-user + * + * Copyright (c) 2013 Virtual Open Systems Sarl. + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#include "hw/virtio/vhost.h" +#include "hw/virtio/vhost-backend.h" +#include "sysemu/char.h" +#include "sysemu/kvm.h" +#include "qemu/error-report.h" +#include "qemu/sockets.h" +#include "exec/ram_addr.h" + +#include <fcntl.h> +#include <unistd.h> +#include <sys/ioctl.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <linux/vhost.h> + +#define VHOST_MEMORY_MAX_NREGIONS 8 + +typedef enum VhostUserRequest { + VHOST_USER_NONE = 0, + VHOST_USER_GET_FEATURES = 1, + VHOST_USER_SET_FEATURES = 2, + VHOST_USER_SET_OWNER = 3, + VHOST_USER_RESET_OWNER = 4, + VHOST_USER_SET_MEM_TABLE = 5, + VHOST_USER_SET_LOG_BASE = 6, + VHOST_USER_SET_LOG_FD = 7, + VHOST_USER_SET_VRING_NUM = 8, + VHOST_USER_SET_VRING_ADDR = 9, + VHOST_USER_SET_VRING_BASE = 10, + VHOST_USER_GET_VRING_BASE = 11, + VHOST_USER_SET_VRING_KICK = 12, + VHOST_USER_SET_VRING_CALL = 13, + VHOST_USER_SET_VRING_ERR = 14, + VHOST_USER_MAX +} VhostUserRequest; + +typedef struct VhostUserMemoryRegion { + uint64_t guest_phys_addr; + uint64_t memory_size; + uint64_t userspace_addr; + uint64_t mmap_offset; +} VhostUserMemoryRegion; + +typedef struct VhostUserMemory { + uint32_t nregions; + uint32_t padding; + VhostUserMemoryRegion regions[VHOST_MEMORY_MAX_NREGIONS]; +} VhostUserMemory; + +typedef struct VhostUserMsg { + VhostUserRequest request; + +#define VHOST_USER_VERSION_MASK (0x3) +#define VHOST_USER_REPLY_MASK (0x1<<2) + uint32_t flags; + uint32_t size; /* the following payload size */ + union { +#define VHOST_USER_VRING_IDX_MASK (0xff) +#define VHOST_USER_VRING_NOFD_MASK (0x1<<8) + uint64_t u64; + struct vhost_vring_state state; + struct vhost_vring_addr addr; + VhostUserMemory memory; + }; +} QEMU_PACKED VhostUserMsg; + +static VhostUserMsg m __attribute__ ((unused)); +#define VHOST_USER_HDR_SIZE (sizeof(m.request) \ + + sizeof(m.flags) \ + + sizeof(m.size)) + +#define VHOST_USER_PAYLOAD_SIZE (sizeof(m) - VHOST_USER_HDR_SIZE) + +/* The version of the protocol we support */ +#define VHOST_USER_VERSION (0x1) + +static bool ioeventfd_enabled(void) +{ + return kvm_enabled() && kvm_eventfds_enabled(); +} + +static unsigned long int ioctl_to_vhost_user_request[VHOST_USER_MAX] = { + -1, /* VHOST_USER_NONE */ + VHOST_GET_FEATURES, /* VHOST_USER_GET_FEATURES */ + VHOST_SET_FEATURES, /* VHOST_USER_SET_FEATURES */ + VHOST_SET_OWNER, /* VHOST_USER_SET_OWNER */ + VHOST_RESET_OWNER, /* VHOST_USER_RESET_OWNER */ + VHOST_SET_MEM_TABLE, /* VHOST_USER_SET_MEM_TABLE */ + VHOST_SET_LOG_BASE, /* VHOST_USER_SET_LOG_BASE */ + VHOST_SET_LOG_FD, /* VHOST_USER_SET_LOG_FD */ + VHOST_SET_VRING_NUM, /* VHOST_USER_SET_VRING_NUM */ + VHOST_SET_VRING_ADDR, /* VHOST_USER_SET_VRING_ADDR */ + VHOST_SET_VRING_BASE, /* VHOST_USER_SET_VRING_BASE */ + VHOST_GET_VRING_BASE, /* VHOST_USER_GET_VRING_BASE */ + VHOST_SET_VRING_KICK, /* VHOST_USER_SET_VRING_KICK */ + VHOST_SET_VRING_CALL, /* VHOST_USER_SET_VRING_CALL */ + VHOST_SET_VRING_ERR /* VHOST_USER_SET_VRING_ERR */ +}; + +static VhostUserRequest vhost_user_request_translate(unsigned long int request) +{ + VhostUserRequest idx; + + for (idx = 0; idx < VHOST_USER_MAX; idx++) { + if (ioctl_to_vhost_user_request[idx] == request) { + break; + } + } + + return (idx == VHOST_USER_MAX) ? VHOST_USER_NONE : idx; +} + +static int vhost_user_read(struct vhost_dev *dev, VhostUserMsg *msg) +{ + CharDriverState *chr = dev->opaque; + uint8_t *p = (uint8_t *) msg; + int r, size = VHOST_USER_HDR_SIZE; + + r = qemu_chr_fe_read_all(chr, p, size); + if (r != size) { + error_report("Failed to read msg header. Read %d instead of %d.\n", r, + size); + goto fail; + } + + /* validate received flags */ + if (msg->flags != (VHOST_USER_REPLY_MASK | VHOST_USER_VERSION)) { + error_report("Failed to read msg header." + " Flags 0x%x instead of 0x%x.\n", msg->flags, + VHOST_USER_REPLY_MASK | VHOST_USER_VERSION); + goto fail; + } + + /* validate message size is sane */ + if (msg->size > VHOST_USER_PAYLOAD_SIZE) { + error_report("Failed to read msg header." + " Size %d exceeds the maximum %zu.\n", msg->size, + VHOST_USER_PAYLOAD_SIZE); + goto fail; + } + + if (msg->size) { + p += VHOST_USER_HDR_SIZE; + size = msg->size; + r = qemu_chr_fe_read_all(chr, p, size); + if (r != size) { + error_report("Failed to read msg payload." + " Read %d instead of %d.\n", r, msg->size); + goto fail; + } + } + + return 0; + +fail: + return -1; +} + +static int vhost_user_write(struct vhost_dev *dev, VhostUserMsg *msg, + int *fds, int fd_num) +{ + CharDriverState *chr = dev->opaque; + int size = VHOST_USER_HDR_SIZE + msg->size; + + if (fd_num) { + qemu_chr_fe_set_msgfds(chr, fds, fd_num); + } + + return qemu_chr_fe_write_all(chr, (const uint8_t *) msg, size) == size ? + 0 : -1; +} + +static int vhost_user_call(struct vhost_dev *dev, unsigned long int request, + void *arg) +{ + VhostUserMsg msg; + VhostUserRequest msg_request; + struct vhost_vring_file *file = 0; + int need_reply = 0; + int fds[VHOST_MEMORY_MAX_NREGIONS]; + int i, fd; + size_t fd_num = 0; + + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER); + + msg_request = vhost_user_request_translate(request); + msg.request = msg_request; + msg.flags = VHOST_USER_VERSION; + msg.size = 0; + + switch (request) { + case VHOST_GET_FEATURES: + need_reply = 1; + break; + + case VHOST_SET_FEATURES: + case VHOST_SET_LOG_BASE: + msg.u64 = *((__u64 *) arg); + msg.size = sizeof(m.u64); + break; + + case VHOST_SET_OWNER: + case VHOST_RESET_OWNER: + break; + + case VHOST_SET_MEM_TABLE: + for (i = 0; i < dev->mem->nregions; ++i) { + struct vhost_memory_region *reg = dev->mem->regions + i; + ram_addr_t ram_addr; + + assert((uintptr_t)reg->userspace_addr == reg->userspace_addr); + qemu_ram_addr_from_host((void *)(uintptr_t)reg->userspace_addr, &ram_addr); + fd = qemu_get_ram_fd(ram_addr); + if (fd > 0) { + msg.memory.regions[fd_num].userspace_addr = reg->userspace_addr; + msg.memory.regions[fd_num].memory_size = reg->memory_size; + msg.memory.regions[fd_num].guest_phys_addr = reg->guest_phys_addr; + msg.memory.regions[fd_num].mmap_offset = reg->userspace_addr - + (uintptr_t) qemu_get_ram_block_host_ptr(ram_addr); + assert(fd_num < VHOST_MEMORY_MAX_NREGIONS); + fds[fd_num++] = fd; + } + } + + msg.memory.nregions = fd_num; + + if (!fd_num) { + error_report("Failed initializing vhost-user memory map\n" + "consider using -object memory-backend-file share=on\n"); + return -1; + } + + msg.size = sizeof(m.memory.nregions); + msg.size += sizeof(m.memory.padding); + msg.size += fd_num * sizeof(VhostUserMemoryRegion); + + break; + + case VHOST_SET_LOG_FD: + fds[fd_num++] = *((int *) arg); + break; + + case VHOST_SET_VRING_NUM: + case VHOST_SET_VRING_BASE: + memcpy(&msg.state, arg, sizeof(struct vhost_vring_state)); + msg.size = sizeof(m.state); + break; + + case VHOST_GET_VRING_BASE: + memcpy(&msg.state, arg, sizeof(struct vhost_vring_state)); + msg.size = sizeof(m.state); + need_reply = 1; + break; + + case VHOST_SET_VRING_ADDR: + memcpy(&msg.addr, arg, sizeof(struct vhost_vring_addr)); + msg.size = sizeof(m.addr); + break; + + case VHOST_SET_VRING_KICK: + case VHOST_SET_VRING_CALL: + case VHOST_SET_VRING_ERR: + file = arg; + msg.u64 = file->index & VHOST_USER_VRING_IDX_MASK; + msg.size = sizeof(m.u64); + if (ioeventfd_enabled() && file->fd > 0) { + fds[fd_num++] = file->fd; + } else { + msg.u64 |= VHOST_USER_VRING_NOFD_MASK; + } + break; + default: + error_report("vhost-user trying to send unhandled ioctl\n"); + return -1; + break; + } + + if (vhost_user_write(dev, &msg, fds, fd_num) < 0) { + return 0; + } + + if (need_reply) { + if (vhost_user_read(dev, &msg) < 0) { + return 0; + } + + if (msg_request != msg.request) { + error_report("Received unexpected msg type." + " Expected %d received %d\n", msg_request, msg.request); + return -1; + } + + switch (msg_request) { + case VHOST_USER_GET_FEATURES: + if (msg.size != sizeof(m.u64)) { + error_report("Received bad msg size.\n"); + return -1; + } + *((__u64 *) arg) = msg.u64; + break; + case VHOST_USER_GET_VRING_BASE: + if (msg.size != sizeof(m.state)) { + error_report("Received bad msg size.\n"); + return -1; + } + memcpy(arg, &msg.state, sizeof(struct vhost_vring_state)); + break; + default: + error_report("Received unexpected msg type.\n"); + return -1; + break; + } + } + + return 0; +} + +static int vhost_user_init(struct vhost_dev *dev, void *opaque) +{ + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER); + + dev->opaque = opaque; + + return 0; +} + +static int vhost_user_cleanup(struct vhost_dev *dev) +{ + assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_USER); + + dev->opaque = 0; + + return 0; +} + +const VhostOps user_ops = { + .backend_type = VHOST_BACKEND_TYPE_USER, + .vhost_call = vhost_user_call, + .vhost_backend_init = vhost_user_init, + .vhost_backend_cleanup = vhost_user_cleanup + }; diff --git a/hw/virtio/vhost.c b/hw/virtio/vhost.c index 9e336ad81e..5a128613bb 100644 --- a/hw/virtio/vhost.c +++ b/hw/virtio/vhost.c @@ -13,7 +13,6 @@ * GNU GPL, version 2 or (at your option) any later version. */ -#include <sys/ioctl.h> #include "hw/virtio/vhost.h" #include "hw/hw.h" #include "qemu/atomic.h" @@ -21,6 +20,7 @@ #include <linux/vhost.h> #include "exec/address-spaces.h" #include "hw/virtio/virtio-bus.h" +#include "migration/migration.h" static void vhost_dev_sync_region(struct vhost_dev *dev, MemoryRegionSection *section, @@ -41,7 +41,6 @@ static void vhost_dev_sync_region(struct vhost_dev *dev, for (;from < to; ++from) { vhost_log_chunk_t log; - int bit; /* We first check with non-atomic: much cheaper, * and we expect non-dirty to be the common case. */ if (!*from) { @@ -51,12 +50,11 @@ static void vhost_dev_sync_region(struct vhost_dev *dev, /* Data must be read atomically. We don't really need barrier semantics * but it's easier to use atomic_* than roll our own. */ log = atomic_xchg(from, 0); - while ((bit = sizeof(log) > sizeof(int) ? - ffsll(log) : ffs(log))) { + while (log) { + int bit = ctzl(log); hwaddr page_addr; hwaddr section_offset; hwaddr mr_offset; - bit -= 1; page_addr = addr + bit * VHOST_LOG_PAGE; section_offset = page_addr - section->offset_within_address_space; mr_offset = section_offset + section->offset_within_region; @@ -291,15 +289,13 @@ static inline void vhost_dev_log_resize(struct vhost_dev* dev, uint64_t size) log = g_malloc0(size * sizeof *log); log_base = (uint64_t)(unsigned long)log; - r = ioctl(dev->control, VHOST_SET_LOG_BASE, &log_base); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_LOG_BASE, &log_base); assert(r >= 0); /* Sync only the range covered by the old log */ if (dev->log_size) { vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1); } - if (dev->log) { - g_free(dev->log); - } + g_free(dev->log); dev->log = log; dev->log_size = size; } @@ -309,7 +305,9 @@ static int vhost_verify_ring_mappings(struct vhost_dev *dev, uint64_t size) { int i; - for (i = 0; i < dev->nvqs; ++i) { + int r = 0; + + for (i = 0; !r && i < dev->nvqs; ++i) { struct vhost_virtqueue *vq = dev->vqs + i; hwaddr l; void *p; @@ -321,15 +319,15 @@ static int vhost_verify_ring_mappings(struct vhost_dev *dev, p = cpu_physical_memory_map(vq->ring_phys, &l, 1); if (!p || l != vq->ring_size) { fprintf(stderr, "Unable to map ring buffer for ring %d\n", i); - return -ENOMEM; + r = -ENOMEM; } if (p != vq->ring) { fprintf(stderr, "Ring buffer relocated for ring %d\n", i); - return -EBUSY; + r = -EBUSY; } cpu_physical_memory_unmap(p, l, 0, 0); } - return 0; + return r; } static struct vhost_memory_region *vhost_dev_find_reg(struct vhost_dev *dev, @@ -460,7 +458,7 @@ static void vhost_commit(MemoryListener *listener) } if (!dev->log_enabled) { - r = ioctl(dev->control, VHOST_SET_MEM_TABLE, dev->mem); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_MEM_TABLE, dev->mem); assert(r >= 0); dev->memory_changed = false; return; @@ -473,7 +471,7 @@ static void vhost_commit(MemoryListener *listener) if (dev->log_size < log_size) { vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER); } - r = ioctl(dev->control, VHOST_SET_MEM_TABLE, dev->mem); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_MEM_TABLE, dev->mem); assert(r >= 0); /* To log less, can only decrease log size after table update. */ if (dev->log_size > log_size + VHOST_LOG_BUFFER) { @@ -541,7 +539,7 @@ static int vhost_virtqueue_set_addr(struct vhost_dev *dev, .log_guest_addr = vq->used_phys, .flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0, }; - int r = ioctl(dev->control, VHOST_SET_VRING_ADDR, &addr); + int r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_ADDR, &addr); if (r < 0) { return -errno; } @@ -555,7 +553,7 @@ static int vhost_dev_set_features(struct vhost_dev *dev, bool enable_log) if (enable_log) { features |= 0x1 << VHOST_F_LOG_ALL; } - r = ioctl(dev->control, VHOST_SET_FEATURES, &features); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_FEATURES, &features); return r < 0 ? -errno : 0; } @@ -603,9 +601,7 @@ static int vhost_migration_log(MemoryListener *listener, int enable) if (r < 0) { return r; } - if (dev->log) { - g_free(dev->log); - } + g_free(dev->log); dev->log = NULL; dev->log_size = 0; } else { @@ -670,13 +666,13 @@ static int vhost_virtqueue_start(struct vhost_dev *dev, assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); vq->num = state.num = virtio_queue_get_num(vdev, idx); - r = ioctl(dev->control, VHOST_SET_VRING_NUM, &state); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_NUM, &state); if (r) { return -errno; } state.num = virtio_queue_get_last_avail_idx(vdev, idx); - r = ioctl(dev->control, VHOST_SET_VRING_BASE, &state); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_BASE, &state); if (r) { return -errno; } @@ -718,7 +714,7 @@ static int vhost_virtqueue_start(struct vhost_dev *dev, } file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq)); - r = ioctl(dev->control, VHOST_SET_VRING_KICK, &file); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_KICK, &file); if (r) { r = -errno; goto fail_kick; @@ -756,7 +752,7 @@ static void vhost_virtqueue_stop(struct vhost_dev *dev, }; int r; assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); - r = ioctl(dev->control, VHOST_GET_VRING_BASE, &state); + r = dev->vhost_ops->vhost_call(dev, VHOST_GET_VRING_BASE, &state); if (r < 0) { fprintf(stderr, "vhost VQ %d ring restore failed: %d\n", idx, r); fflush(stderr); @@ -798,7 +794,7 @@ static int vhost_virtqueue_init(struct vhost_dev *dev, } file.fd = event_notifier_get_fd(&vq->masked_notifier); - r = ioctl(dev->control, VHOST_SET_VRING_CALL, &file); + r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_CALL, &file); if (r) { r = -errno; goto fail_call; @@ -814,25 +810,28 @@ static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq) event_notifier_cleanup(&vq->masked_notifier); } -int vhost_dev_init(struct vhost_dev *hdev, int devfd, const char *devpath, - bool force) +int vhost_dev_init(struct vhost_dev *hdev, void *opaque, + VhostBackendType backend_type, bool force) { uint64_t features; int i, r; - if (devfd >= 0) { - hdev->control = devfd; - } else { - hdev->control = open(devpath, O_RDWR); - if (hdev->control < 0) { - return -errno; - } + + if (vhost_set_backend_type(hdev, backend_type) < 0) { + close((uintptr_t)opaque); + return -1; + } + + if (hdev->vhost_ops->vhost_backend_init(hdev, opaque) < 0) { + close((uintptr_t)opaque); + return -errno; } - r = ioctl(hdev->control, VHOST_SET_OWNER, NULL); + + r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_OWNER, NULL); if (r < 0) { goto fail; } - r = ioctl(hdev->control, VHOST_GET_FEATURES, &features); + r = hdev->vhost_ops->vhost_call(hdev, VHOST_GET_FEATURES, &features); if (r < 0) { goto fail; } @@ -860,6 +859,12 @@ int vhost_dev_init(struct vhost_dev *hdev, int devfd, const char *devpath, .eventfd_del = vhost_eventfd_del, .priority = 10 }; + hdev->migration_blocker = NULL; + if (!(hdev->features & (0x1 << VHOST_F_LOG_ALL))) { + error_setg(&hdev->migration_blocker, + "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature."); + migrate_add_blocker(hdev->migration_blocker); + } hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions)); hdev->n_mem_sections = 0; hdev->mem_sections = NULL; @@ -877,7 +882,7 @@ fail_vq: } fail: r = -errno; - close(hdev->control); + hdev->vhost_ops->vhost_backend_cleanup(hdev); return r; } @@ -888,9 +893,13 @@ void vhost_dev_cleanup(struct vhost_dev *hdev) vhost_virtqueue_cleanup(hdev->vqs + i); } memory_listener_unregister(&hdev->memory_listener); + if (hdev->migration_blocker) { + migrate_del_blocker(hdev->migration_blocker); + error_free(hdev->migration_blocker); + } g_free(hdev->mem); g_free(hdev->mem_sections); - close(hdev->control); + hdev->vhost_ops->vhost_backend_cleanup(hdev); } bool vhost_dev_query(struct vhost_dev *hdev, VirtIODevice *vdev) @@ -969,7 +978,6 @@ void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev) bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n) { struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index; - assert(hdev->started); assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs); return event_notifier_test_and_clear(&vq->masked_notifier); } @@ -981,7 +989,6 @@ void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n, struct VirtQueue *vvq = virtio_get_queue(vdev, n); int r, index = n - hdev->vq_index; - assert(hdev->started); assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs); struct vhost_vring_file file = { @@ -992,10 +999,37 @@ void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n, } else { file.fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vvq)); } - r = ioctl(hdev->control, VHOST_SET_VRING_CALL, &file); + r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_VRING_CALL, &file); assert(r >= 0); } +unsigned vhost_get_features(struct vhost_dev *hdev, const int *feature_bits, + unsigned features) +{ + const int *bit = feature_bits; + while (*bit != VHOST_INVALID_FEATURE_BIT) { + unsigned bit_mask = (1 << *bit); + if (!(hdev->features & bit_mask)) { + features &= ~bit_mask; + } + bit++; + } + return features; +} + +void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits, + unsigned features) +{ + const int *bit = feature_bits; + while (*bit != VHOST_INVALID_FEATURE_BIT) { + unsigned bit_mask = (1 << *bit); + if (features & bit_mask) { + hdev->acked_features |= bit_mask; + } + bit++; + } +} + /* Host notifiers must be enabled at this point. */ int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev) { @@ -1007,7 +1041,7 @@ int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev) if (r < 0) { goto fail_features; } - r = ioctl(hdev->control, VHOST_SET_MEM_TABLE, hdev->mem); + r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_MEM_TABLE, hdev->mem); if (r < 0) { r = -errno; goto fail_mem; @@ -1026,8 +1060,7 @@ int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev) hdev->log_size = vhost_get_log_size(hdev); hdev->log = hdev->log_size ? g_malloc0(hdev->log_size * sizeof *hdev->log) : NULL; - r = ioctl(hdev->control, VHOST_SET_LOG_BASE, - (uint64_t)(unsigned long)hdev->log); + r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_LOG_BASE, hdev->log); if (r < 0) { r = -errno; goto fail_log; diff --git a/hw/virtio/virtio-balloon.c b/hw/virtio/virtio-balloon.c index a470a0b3a6..7bfbb75ad3 100644 --- a/hw/virtio/virtio-balloon.c +++ b/hw/virtio/virtio-balloon.c @@ -24,12 +24,14 @@ #include "sysemu/kvm.h" #include "exec/address-spaces.h" #include "qapi/visitor.h" +#include "qapi-event.h" #if defined(__linux__) #include <sys/mman.h> #endif #include "hw/virtio/virtio-bus.h" +#include "hw/virtio/virtio-access.h" static void balloon_page(void *addr, int deflate) { @@ -85,7 +87,7 @@ static void balloon_stats_destroy_timer(VirtIOBalloon *s) } } -static void balloon_stats_change_timer(VirtIOBalloon *s, int secs) +static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs) { timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000); } @@ -108,25 +110,37 @@ static void balloon_stats_poll_cb(void *opaque) static void balloon_stats_get_all(Object *obj, struct Visitor *v, void *opaque, const char *name, Error **errp) { + Error *err = NULL; VirtIOBalloon *s = opaque; int i; - if (!s->stats_last_update) { - error_setg(errp, "guest hasn't updated any stats yet"); - return; + visit_start_struct(v, NULL, "guest-stats", name, 0, &err); + if (err) { + goto out; + } + visit_type_int(v, &s->stats_last_update, "last-update", &err); + if (err) { + goto out_end; } - visit_start_struct(v, NULL, "guest-stats", name, 0, errp); - visit_type_int(v, &s->stats_last_update, "last-update", errp); - - visit_start_struct(v, NULL, NULL, "stats", 0, errp); - for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) { + visit_start_struct(v, NULL, NULL, "stats", 0, &err); + if (err) { + goto out_end; + } + for (i = 0; !err && i < VIRTIO_BALLOON_S_NR; i++) { visit_type_int64(v, (int64_t *) &s->stats[i], balloon_stat_names[i], - errp); + &err); } - visit_end_struct(v, errp); - - visit_end_struct(v, errp); + error_propagate(errp, err); + err = NULL; + visit_end_struct(v, &err); + +out_end: + error_propagate(errp, err); + err = NULL; + visit_end_struct(v, &err); +out: + error_propagate(errp, err); } static void balloon_stats_get_poll_interval(Object *obj, struct Visitor *v, @@ -142,10 +156,12 @@ static void balloon_stats_set_poll_interval(Object *obj, struct Visitor *v, Error **errp) { VirtIOBalloon *s = opaque; + Error *local_err = NULL; int64_t value; - visit_type_int(v, &value, name, errp); - if (error_is_set(errp)) { + visit_type_int(v, &value, name, &local_err); + if (local_err) { + error_propagate(errp, local_err); return; } @@ -154,6 +170,11 @@ static void balloon_stats_set_poll_interval(Object *obj, struct Visitor *v, return; } + if (value > UINT32_MAX) { + error_setg(errp, "timer value is too big"); + return; + } + if (value == s->stats_poll_interval) { return; } @@ -191,8 +212,9 @@ static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq) while (iov_to_buf(elem.out_sg, elem.out_num, offset, &pfn, 4) == 4) { ram_addr_t pa; ram_addr_t addr; + int p = virtio_ldl_p(vdev, &pfn); - pa = (ram_addr_t)ldl_p(&pfn) << VIRTIO_BALLOON_PFN_SHIFT; + pa = (ram_addr_t) p << VIRTIO_BALLOON_PFN_SHIFT; offset += 4; /* FIXME: remove get_system_memory(), but how? */ @@ -233,8 +255,8 @@ static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq) while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat)) == sizeof(stat)) { - uint16_t tag = tswap16(stat.tag); - uint64_t val = tswap64(stat.val); + uint16_t tag = virtio_tswap16(vdev, stat.tag); + uint64_t val = virtio_tswap64(vdev, stat.val); offset += sizeof(stat); if (tag < VIRTIO_BALLOON_S_NR) @@ -275,8 +297,9 @@ static void virtio_balloon_set_config(VirtIODevice *vdev, memcpy(&config, config_data, sizeof(struct virtio_balloon_config)); dev->actual = le32_to_cpu(config.actual); if (dev->actual != oldactual) { - qemu_balloon_changed(ram_size - - ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT)); + qapi_event_send_balloon_change(ram_size - + ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT), + &error_abort); } } @@ -309,10 +332,12 @@ static void virtio_balloon_to_target(void *opaque, ram_addr_t target) static void virtio_balloon_save(QEMUFile *f, void *opaque) { - VirtIOBalloon *s = VIRTIO_BALLOON(opaque); - VirtIODevice *vdev = VIRTIO_DEVICE(s); + virtio_save(VIRTIO_DEVICE(opaque), f); +} - virtio_save(vdev, f); +static void virtio_balloon_save_device(VirtIODevice *vdev, QEMUFile *f) +{ + VirtIOBalloon *s = VIRTIO_BALLOON(vdev); qemu_put_be32(f, s->num_pages); qemu_put_be32(f, s->actual); @@ -320,17 +345,16 @@ static void virtio_balloon_save(QEMUFile *f, void *opaque) static int virtio_balloon_load(QEMUFile *f, void *opaque, int version_id) { - VirtIOBalloon *s = VIRTIO_BALLOON(opaque); - VirtIODevice *vdev = VIRTIO_DEVICE(s); - int ret; - if (version_id != 1) return -EINVAL; - ret = virtio_load(vdev, f); - if (ret) { - return ret; - } + return virtio_load(VIRTIO_DEVICE(opaque), f, version_id); +} + +static int virtio_balloon_load_device(VirtIODevice *vdev, QEMUFile *f, + int version_id) +{ + VirtIOBalloon *s = VIRTIO_BALLOON(vdev); s->num_pages = qemu_get_be32(f); s->actual = qemu_get_be32(f); @@ -359,6 +383,8 @@ static void virtio_balloon_device_realize(DeviceState *dev, Error **errp) s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output); s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats); + reset_stats(s); + register_savevm(dev, "virtio-balloon", -1, 1, virtio_balloon_save, virtio_balloon_load, s); @@ -398,6 +424,8 @@ static void virtio_balloon_class_init(ObjectClass *klass, void *data) vdc->get_config = virtio_balloon_get_config; vdc->set_config = virtio_balloon_set_config; vdc->get_features = virtio_balloon_get_features; + vdc->save = virtio_balloon_save_device; + vdc->load = virtio_balloon_load_device; } static const TypeInfo virtio_balloon_info = { diff --git a/hw/virtio/virtio-mmio.c b/hw/virtio/virtio-mmio.c index 8829eb0e26..2450c13747 100644 --- a/hw/virtio/virtio-mmio.c +++ b/hw/virtio/virtio-mmio.c @@ -89,9 +89,6 @@ typedef struct { VirtioBusState bus; } VirtIOMMIOProxy; -static void virtio_mmio_bus_new(VirtioBusState *bus, size_t bus_size, - VirtIOMMIOProxy *dev); - static uint64_t virtio_mmio_read(void *opaque, hwaddr offset, unsigned size) { VirtIOMMIOProxy *proxy = (VirtIOMMIOProxy *)opaque; @@ -362,17 +359,24 @@ static void virtio_mmio_realizefn(DeviceState *d, Error **errp) VirtIOMMIOProxy *proxy = VIRTIO_MMIO(d); SysBusDevice *sbd = SYS_BUS_DEVICE(d); - virtio_mmio_bus_new(&proxy->bus, sizeof(proxy->bus), proxy); + qbus_create_inplace(&proxy->bus, sizeof(proxy->bus), TYPE_VIRTIO_MMIO_BUS, + d, NULL); sysbus_init_irq(sbd, &proxy->irq); memory_region_init_io(&proxy->iomem, OBJECT(d), &virtio_mem_ops, proxy, TYPE_VIRTIO_MMIO, 0x200); sysbus_init_mmio(sbd, &proxy->iomem); } +static Property virtio_mmio_properties[] = { + DEFINE_VIRTIO_COMMON_FEATURES(VirtIOMMIOProxy, host_features), + DEFINE_PROP_END_OF_LIST(), +}; + static void virtio_mmio_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); + dc->props = virtio_mmio_properties; dc->realize = virtio_mmio_realizefn; dc->reset = virtio_mmio_reset; set_bit(DEVICE_CATEGORY_MISC, dc->categories); @@ -387,17 +391,6 @@ static const TypeInfo virtio_mmio_info = { /* virtio-mmio-bus. */ -static void virtio_mmio_bus_new(VirtioBusState *bus, size_t bus_size, - VirtIOMMIOProxy *dev) -{ - DeviceState *qdev = DEVICE(dev); - BusState *qbus; - - qbus_create_inplace(bus, bus_size, TYPE_VIRTIO_MMIO_BUS, qdev, NULL); - qbus = BUS(bus); - qbus->allow_hotplug = 0; -} - static void virtio_mmio_bus_class_init(ObjectClass *klass, void *data) { BusClass *bus_class = BUS_CLASS(klass); diff --git a/hw/virtio/virtio-pci.c b/hw/virtio/virtio-pci.c index ce97514b69..dde1d73b56 100644 --- a/hw/virtio/virtio-pci.c +++ b/hw/virtio/virtio-pci.c @@ -29,7 +29,7 @@ #include "hw/pci/msix.h" #include "hw/loader.h" #include "sysemu/kvm.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "virtio-pci.h" #include "qemu/range.h" #include "hw/virtio/virtio-bus.h" @@ -86,12 +86,6 @@ * 12 is historical, and due to x86 page size. */ #define VIRTIO_PCI_QUEUE_ADDR_SHIFT 12 -/* Flags track per-device state like workarounds for quirks in older guests. */ -#define VIRTIO_PCI_FLAG_BUS_MASTER_BUG (1 << 0) - -/* HACK for virtio to determine if it's running a big endian guest */ -bool virtio_is_big_endian(void); - static void virtio_pci_bus_new(VirtioBusState *bus, size_t bus_size, VirtIOPCIProxy *dev); @@ -317,12 +311,14 @@ static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val) msix_unuse_all_vectors(&proxy->pci_dev); } - /* Linux before 2.6.34 sets the device as OK without enabling - the PCI device bus master bit. In this case we need to disable - some safety checks. */ - if ((val & VIRTIO_CONFIG_S_DRIVER_OK) && - !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) { - proxy->flags |= VIRTIO_PCI_FLAG_BUS_MASTER_BUG; + /* Linux before 2.6.34 drives the device without enabling + the PCI device bus master bit. Enable it automatically + for the guest. This is a PCI spec violation but so is + initiating DMA with bus master bit clear. */ + if (val == (VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER)) { + pci_default_write_config(&proxy->pci_dev, PCI_COMMAND, + proxy->pci_dev.config[PCI_COMMAND] | + PCI_COMMAND_MASTER, 1); } break; case VIRTIO_MSI_CONFIG_VECTOR: @@ -409,13 +405,13 @@ static uint64_t virtio_pci_config_read(void *opaque, hwaddr addr, break; case 2: val = virtio_config_readw(vdev, addr); - if (virtio_is_big_endian()) { + if (virtio_is_big_endian(vdev)) { val = bswap16(val); } break; case 4: val = virtio_config_readl(vdev, addr); - if (virtio_is_big_endian()) { + if (virtio_is_big_endian(vdev)) { val = bswap32(val); } break; @@ -443,13 +439,13 @@ static void virtio_pci_config_write(void *opaque, hwaddr addr, virtio_config_writeb(vdev, addr, val); break; case 2: - if (virtio_is_big_endian()) { + if (virtio_is_big_endian(vdev)) { val = bswap16(val); } virtio_config_writew(vdev, addr, val); break; case 4: - if (virtio_is_big_endian()) { + if (virtio_is_big_endian(vdev)) { val = bswap32(val); } virtio_config_writel(vdev, addr, val); @@ -476,8 +472,7 @@ static void virtio_write_config(PCIDevice *pci_dev, uint32_t address, pci_default_write_config(pci_dev, address, val, len); if (range_covers_byte(address, len, PCI_COMMAND) && - !(pci_dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER) && - !(proxy->flags & VIRTIO_PCI_FLAG_BUS_MASTER_BUG)) { + !(pci_dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER)) { virtio_pci_stop_ioeventfd(proxy); virtio_set_status(vdev, vdev->status & ~VIRTIO_CONFIG_S_DRIVER_OK); } @@ -888,11 +883,15 @@ static void virtio_pci_vmstate_change(DeviceState *d, bool running) VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus); if (running) { - /* Try to find out if the guest has bus master disabled, but is - in ready state. Then we have a buggy guest OS. */ - if ((vdev->status & VIRTIO_CONFIG_S_DRIVER_OK) && + /* Old QEMU versions did not set bus master enable on status write. + * Detect DRIVER set and enable it. + */ + if ((proxy->flags & VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION) && + (vdev->status & VIRTIO_CONFIG_S_DRIVER) && !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) { - proxy->flags |= VIRTIO_PCI_FLAG_BUS_MASTER_BUG; + pci_default_write_config(&proxy->pci_dev, PCI_COMMAND, + proxy->pci_dev.config[PCI_COMMAND] | + PCI_COMMAND_MASTER, 1); } virtio_pci_start_ioeventfd(proxy); } else { @@ -917,8 +916,6 @@ static Property virtio_9p_pci_properties[] = { DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags, VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2), - DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VIRTIO_9P_PROPERTIES(V9fsPCIState, vdev.fsconf), DEFINE_PROP_END_OF_LIST(), }; @@ -940,8 +937,9 @@ static void virtio_9p_pci_class_init(ObjectClass *klass, void *data) static void virtio_9p_pci_instance_init(Object *obj) { V9fsPCIState *dev = VIRTIO_9P_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_9P); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_9P); } static const TypeInfo virtio_9p_pci_info = { @@ -976,6 +974,8 @@ static void virtio_pci_device_plugged(DeviceState *d) if (proxy->nvectors && msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors, 1)) { + error_report("unable to init msix vectors to %" PRIu32, + proxy->nvectors); proxy->nvectors = 0; } @@ -1004,11 +1004,9 @@ static void virtio_pci_device_plugged(DeviceState *d) static void virtio_pci_device_unplugged(DeviceState *d) { - PCIDevice *pci_dev = PCI_DEVICE(d); VirtIOPCIProxy *proxy = VIRTIO_PCI(d); virtio_pci_stop_ioeventfd(proxy); - msix_uninit_exclusive_bar(pci_dev); } static int virtio_pci_init(PCIDevice *pci_dev) @@ -1024,8 +1022,7 @@ static int virtio_pci_init(PCIDevice *pci_dev) static void virtio_pci_exit(PCIDevice *pci_dev) { - VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev); - memory_region_destroy(&proxy->bar); + msix_uninit_exclusive_bar(pci_dev); } static void virtio_pci_reset(DeviceState *qdev) @@ -1035,14 +1032,21 @@ static void virtio_pci_reset(DeviceState *qdev) virtio_pci_stop_ioeventfd(proxy); virtio_bus_reset(bus); msix_unuse_all_vectors(&proxy->pci_dev); - proxy->flags &= ~VIRTIO_PCI_FLAG_BUS_MASTER_BUG; } +static Property virtio_pci_properties[] = { + DEFINE_PROP_BIT("virtio-pci-bus-master-bug-migration", VirtIOPCIProxy, flags, + VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION_BIT, false), + DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), + DEFINE_PROP_END_OF_LIST(), +}; + static void virtio_pci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + dc->props = virtio_pci_properties; k->init = virtio_pci_init; k->exit = virtio_pci_exit; k->vendor_id = PCI_VENDOR_ID_REDHAT_QUMRANET; @@ -1067,11 +1071,6 @@ static Property virtio_blk_pci_properties[] = { DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags, VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2), -#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE - DEFINE_PROP_BIT("x-data-plane", VirtIOBlkPCI, blk.data_plane, 0, false), -#endif - DEFINE_VIRTIO_BLK_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VIRTIO_BLK_PROPERTIES(VirtIOBlkPCI, blk), DEFINE_PROP_END_OF_LIST(), }; @@ -1079,7 +1078,6 @@ static int virtio_blk_pci_init(VirtIOPCIProxy *vpci_dev) { VirtIOBlkPCI *dev = VIRTIO_BLK_PCI(vpci_dev); DeviceState *vdev = DEVICE(&dev->vdev); - virtio_blk_set_conf(vdev, &(dev->blk)); qdev_set_parent_bus(vdev, BUS(&vpci_dev->bus)); if (qdev_init(vdev) < 0) { return -1; @@ -1105,8 +1103,13 @@ static void virtio_blk_pci_class_init(ObjectClass *klass, void *data) static void virtio_blk_pci_instance_init(Object *obj) { VirtIOBlkPCI *dev = VIRTIO_BLK_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_BLK); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_BLK); + object_property_add_alias(obj, "iothread", OBJECT(&dev->vdev),"iothread", + &error_abort); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static const TypeInfo virtio_blk_pci_info = { @@ -1125,7 +1128,6 @@ static Property virtio_scsi_pci_properties[] = { DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, DEV_NVECTORS_UNSPECIFIED), DEFINE_VIRTIO_SCSI_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOSCSIPCI, vdev.parent_obj.conf), DEFINE_PROP_END_OF_LIST(), }; @@ -1175,8 +1177,11 @@ static void virtio_scsi_pci_class_init(ObjectClass *klass, void *data) static void virtio_scsi_pci_instance_init(Object *obj) { VirtIOSCSIPCI *dev = VIRTIO_SCSI_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SCSI); + object_property_add_alias(obj, "iothread", OBJECT(&dev->vdev), "iothread", + &error_abort); } static const TypeInfo virtio_scsi_pci_info = { @@ -1193,8 +1198,6 @@ static const TypeInfo virtio_scsi_pci_info = { static Property vhost_scsi_pci_properties[] = { DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, DEV_NVECTORS_UNSPECIFIED), - DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VHOST_SCSI_PROPERTIES(VHostSCSIPCI, vdev.parent_obj.conf), DEFINE_PROP_END_OF_LIST(), }; @@ -1232,8 +1235,9 @@ static void vhost_scsi_pci_class_init(ObjectClass *klass, void *data) static void vhost_scsi_pci_instance_init(Object *obj) { VHostSCSIPCI *dev = VHOST_SCSI_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VHOST_SCSI); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VHOST_SCSI); } static const TypeInfo vhost_scsi_pci_info = { @@ -1274,7 +1278,6 @@ static void balloon_pci_stats_set_poll_interval(Object *obj, struct Visitor *v, } static Property virtio_balloon_pci_properties[] = { - DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), DEFINE_PROP_UINT32("class", VirtIOPCIProxy, class_code, 0), DEFINE_PROP_END_OF_LIST(), }; @@ -1315,7 +1318,7 @@ static void virtio_balloon_pci_instance_init(Object *obj) VirtIOBalloonPCI *dev = VIRTIO_BALLOON_PCI(obj); object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_BALLOON); object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); - + object_unref(OBJECT(&dev->vdev)); object_property_add(obj, "guest-stats", "guest statistics", balloon_pci_stats_get_all, NULL, NULL, dev, NULL); @@ -1377,8 +1380,6 @@ static Property virtio_serial_pci_properties[] = { VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true), DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2), DEFINE_PROP_UINT32("class", VirtIOPCIProxy, class_code, 0), - DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VIRTIO_SERIAL_PROPERTIES(VirtIOSerialPCI, vdev.serial), DEFINE_PROP_END_OF_LIST(), }; @@ -1399,8 +1400,9 @@ static void virtio_serial_pci_class_init(ObjectClass *klass, void *data) static void virtio_serial_pci_instance_init(Object *obj) { VirtIOSerialPCI *dev = VIRTIO_SERIAL_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_SERIAL); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_SERIAL); } static const TypeInfo virtio_serial_pci_info = { @@ -1418,8 +1420,6 @@ static Property virtio_net_properties[] = { VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, false), DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 3), DEFINE_VIRTIO_NET_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_NIC_PROPERTIES(VirtIONetPCI, vdev.nic_conf), - DEFINE_VIRTIO_NET_PROPERTIES(VirtIONetPCI, vdev.net_conf), DEFINE_PROP_END_OF_LIST(), }; @@ -1458,8 +1458,11 @@ static void virtio_net_pci_class_init(ObjectClass *klass, void *data) static void virtio_net_pci_instance_init(Object *obj) { VirtIONetPCI *dev = VIRTIO_NET_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_NET); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); + + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_NET); + object_property_add_alias(obj, "bootindex", OBJECT(&dev->vdev), + "bootindex", &error_abort); } static const TypeInfo virtio_net_pci_info = { @@ -1473,8 +1476,6 @@ static const TypeInfo virtio_net_pci_info = { /* virtio-rng-pci */ static Property virtio_rng_pci_properties[] = { - DEFINE_VIRTIO_COMMON_FEATURES(VirtIOPCIProxy, host_features), - DEFINE_VIRTIO_RNG_PROPERTIES(VirtIORngPCI, vdev.conf), DEFINE_PROP_END_OF_LIST(), }; @@ -1514,13 +1515,11 @@ static void virtio_rng_pci_class_init(ObjectClass *klass, void *data) static void virtio_rng_initfn(Object *obj) { VirtIORngPCI *dev = VIRTIO_RNG_PCI(obj); - object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_RNG); - object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL); - object_property_add_link(obj, "rng", TYPE_RNG_BACKEND, - (Object **)&dev->vdev.conf.rng, - qdev_prop_allow_set_link_before_realize, - OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL); + virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev), + TYPE_VIRTIO_RNG); + object_property_add_alias(obj, "rng", OBJECT(&dev->vdev), "rng", + &error_abort); } static const TypeInfo virtio_rng_pci_info = { @@ -1537,13 +1536,10 @@ static void virtio_pci_bus_new(VirtioBusState *bus, size_t bus_size, VirtIOPCIProxy *dev) { DeviceState *qdev = DEVICE(dev); - BusState *qbus; char virtio_bus_name[] = "virtio-bus"; qbus_create_inplace(bus, bus_size, TYPE_VIRTIO_PCI_BUS, qdev, virtio_bus_name); - qbus = BUS(bus); - qbus->allow_hotplug = 1; } static void virtio_pci_bus_class_init(ObjectClass *klass, void *data) diff --git a/hw/virtio/virtio-pci.h b/hw/virtio/virtio-pci.h index dc332ae774..8873b6d138 100644 --- a/hw/virtio/virtio-pci.h +++ b/hw/virtio/virtio-pci.h @@ -53,6 +53,11 @@ typedef struct VirtioBusClass VirtioPCIBusClass; #define VIRTIO_PCI_BUS_CLASS(klass) \ OBJECT_CLASS_CHECK(VirtioPCIBusClass, klass, TYPE_VIRTIO_PCI_BUS) +/* Need to activate work-arounds for buggy guests at vmstate load. */ +#define VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION_BIT 0 +#define VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION \ + (1 << VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION_BIT) + /* Performance improves when virtqueue kick processing is decoupled from the * vcpu thread using ioeventfd for some devices. */ #define VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT 1 @@ -131,7 +136,6 @@ struct VHostSCSIPCI { struct VirtIOBlkPCI { VirtIOPCIProxy parent_obj; VirtIOBlock vdev; - VirtIOBlkConf blk; }; /* diff --git a/hw/virtio/virtio-rng.c b/hw/virtio/virtio-rng.c index b6ab3610cb..473c04410e 100644 --- a/hw/virtio/virtio-rng.c +++ b/hw/virtio/virtio-rng.c @@ -16,6 +16,7 @@ #include "hw/virtio/virtio-rng.h" #include "sysemu/rng.h" #include "qom/object_interfaces.h" +#include "trace.h" static bool is_guest_ready(VirtIORNG *vrng) { @@ -24,6 +25,7 @@ static bool is_guest_ready(VirtIORNG *vrng) && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) { return true; } + trace_virtio_rng_guest_not_ready(vrng); return false; } @@ -62,6 +64,7 @@ static void chr_read(void *opaque, const void *buf, size_t size) offset += len; virtqueue_push(vrng->vq, &elem, len); + trace_virtio_rng_pushed(vrng, len); } virtio_notify(vdev, vrng->vq); } @@ -81,6 +84,9 @@ static void virtio_rng_process(VirtIORNG *vrng) quota = MIN((uint64_t)vrng->quota_remaining, (uint64_t)UINT32_MAX); } size = get_request_size(vrng->vq, quota); + + trace_virtio_rng_request(vrng, size, quota); + size = MIN(vrng->quota_remaining, size); if (size) { rng_backend_request_entropy(vrng->rng, size, chr_read, vrng); @@ -108,12 +114,15 @@ static void virtio_rng_save(QEMUFile *f, void *opaque) static int virtio_rng_load(QEMUFile *f, void *opaque, int version_id) { VirtIORNG *vrng = opaque; - VirtIODevice *vdev = VIRTIO_DEVICE(vrng); + int ret; if (version_id != 1) { return -EINVAL; } - virtio_load(vdev, f); + ret = virtio_load(VIRTIO_DEVICE(vrng), f, version_id); + if (ret != 0) { + return ret; + } /* We may have an element ready but couldn't process it due to a quota * limit. Make sure to try again after live migration when the quota may @@ -141,8 +150,15 @@ static void virtio_rng_device_realize(DeviceState *dev, Error **errp) Error *local_err = NULL; if (!vrng->conf.period_ms > 0) { - error_set(errp, QERR_INVALID_PARAMETER_VALUE, "period", - "a positive number"); + error_setg(errp, "'period' parameter expects a positive integer"); + return; + } + + /* Workaround: Property parsing does not enforce unsigned integers, + * So this is a hack to reject such numbers. */ + if (vrng->conf.max_bytes > INT64_MAX) { + error_setg(errp, "'max-bytes' parameter must be non-negative, " + "and less than 2^63"); return; } @@ -170,17 +186,15 @@ static void virtio_rng_device_realize(DeviceState *dev, Error **errp) "rng", NULL); } - virtio_init(vdev, "virtio-rng", VIRTIO_ID_RNG, 0); - vrng->rng = vrng->conf.rng; if (vrng->rng == NULL) { - error_set(errp, QERR_INVALID_PARAMETER_VALUE, "rng", "a valid object"); + error_setg(errp, "'rng' parameter expects a valid object"); return; } - vrng->vq = virtio_add_queue(vdev, 8, handle_input); + virtio_init(vdev, "virtio-rng", VIRTIO_ID_RNG, 0); - assert(vrng->conf.max_bytes <= INT64_MAX); + vrng->vq = virtio_add_queue(vdev, 8, handle_input); vrng->quota_remaining = vrng->conf.max_bytes; vrng->rate_limit_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, diff --git a/hw/virtio/virtio.c b/hw/virtio/virtio.c index aeabf3a459..013979a6b8 100644 --- a/hw/virtio/virtio.c +++ b/hw/virtio/virtio.c @@ -19,6 +19,8 @@ #include "hw/virtio/virtio.h" #include "qemu/atomic.h" #include "hw/virtio/virtio-bus.h" +#include "migration/migration.h" +#include "hw/virtio/virtio-access.h" /* * The alignment to use between consumer and producer parts of vring. @@ -101,53 +103,56 @@ static void virtqueue_init(VirtQueue *vq) vq->vring.align); } -static inline uint64_t vring_desc_addr(hwaddr desc_pa, int i) +static inline uint64_t vring_desc_addr(VirtIODevice *vdev, hwaddr desc_pa, + int i) { hwaddr pa; pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, addr); - return ldq_phys(&address_space_memory, pa); + return virtio_ldq_phys(vdev, pa); } -static inline uint32_t vring_desc_len(hwaddr desc_pa, int i) +static inline uint32_t vring_desc_len(VirtIODevice *vdev, hwaddr desc_pa, int i) { hwaddr pa; pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, len); - return ldl_phys(&address_space_memory, pa); + return virtio_ldl_phys(vdev, pa); } -static inline uint16_t vring_desc_flags(hwaddr desc_pa, int i) +static inline uint16_t vring_desc_flags(VirtIODevice *vdev, hwaddr desc_pa, + int i) { hwaddr pa; pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, flags); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vdev, pa); } -static inline uint16_t vring_desc_next(hwaddr desc_pa, int i) +static inline uint16_t vring_desc_next(VirtIODevice *vdev, hwaddr desc_pa, + int i) { hwaddr pa; pa = desc_pa + sizeof(VRingDesc) * i + offsetof(VRingDesc, next); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vdev, pa); } static inline uint16_t vring_avail_flags(VirtQueue *vq) { hwaddr pa; pa = vq->vring.avail + offsetof(VRingAvail, flags); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vq->vdev, pa); } static inline uint16_t vring_avail_idx(VirtQueue *vq) { hwaddr pa; pa = vq->vring.avail + offsetof(VRingAvail, idx); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vq->vdev, pa); } static inline uint16_t vring_avail_ring(VirtQueue *vq, int i) { hwaddr pa; pa = vq->vring.avail + offsetof(VRingAvail, ring[i]); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vq->vdev, pa); } static inline uint16_t vring_used_event(VirtQueue *vq) @@ -159,44 +164,44 @@ static inline void vring_used_ring_id(VirtQueue *vq, int i, uint32_t val) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, ring[i].id); - stl_phys(&address_space_memory, pa, val); + virtio_stl_phys(vq->vdev, pa, val); } static inline void vring_used_ring_len(VirtQueue *vq, int i, uint32_t val) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, ring[i].len); - stl_phys(&address_space_memory, pa, val); + virtio_stl_phys(vq->vdev, pa, val); } static uint16_t vring_used_idx(VirtQueue *vq) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, idx); - return lduw_phys(&address_space_memory, pa); + return virtio_lduw_phys(vq->vdev, pa); } static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, idx); - stw_phys(&address_space_memory, pa, val); + virtio_stw_phys(vq->vdev, pa, val); } static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask) { + VirtIODevice *vdev = vq->vdev; hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, flags); - stw_phys(&address_space_memory, - pa, lduw_phys(&address_space_memory, pa) | mask); + virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) | mask); } static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask) { + VirtIODevice *vdev = vq->vdev; hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, flags); - stw_phys(&address_space_memory, - pa, lduw_phys(&address_space_memory, pa) & ~mask); + virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) & ~mask); } static inline void vring_avail_event(VirtQueue *vq, uint16_t val) @@ -206,7 +211,7 @@ static inline void vring_avail_event(VirtQueue *vq, uint16_t val) return; } pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]); - stw_phys(&address_space_memory, pa, val); + virtio_stw_phys(vq->vdev, pa, val); } void virtio_queue_set_notification(VirtQueue *vq, int enable) @@ -323,17 +328,18 @@ static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx) return head; } -static unsigned virtqueue_next_desc(hwaddr desc_pa, +static unsigned virtqueue_next_desc(VirtIODevice *vdev, hwaddr desc_pa, unsigned int i, unsigned int max) { unsigned int next; /* If this descriptor says it doesn't chain, we're done. */ - if (!(vring_desc_flags(desc_pa, i) & VRING_DESC_F_NEXT)) + if (!(vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_NEXT)) { return max; + } /* Check they're not leading us off end of descriptors. */ - next = vring_desc_next(desc_pa, i); + next = vring_desc_next(vdev, desc_pa, i); /* Make sure compiler knows to grab that: we don't want it changing! */ smp_wmb(); @@ -356,6 +362,7 @@ void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes, total_bufs = in_total = out_total = 0; while (virtqueue_num_heads(vq, idx)) { + VirtIODevice *vdev = vq->vdev; unsigned int max, num_bufs, indirect = 0; hwaddr desc_pa; int i; @@ -365,8 +372,8 @@ void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes, i = virtqueue_get_head(vq, idx++); desc_pa = vq->vring.desc; - if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) { - if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) { + if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_INDIRECT) { + if (vring_desc_len(vdev, desc_pa, i) % sizeof(VRingDesc)) { error_report("Invalid size for indirect buffer table"); exit(1); } @@ -379,8 +386,8 @@ void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes, /* loop over the indirect descriptor table */ indirect = 1; - max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc); - desc_pa = vring_desc_addr(desc_pa, i); + max = vring_desc_len(vdev, desc_pa, i) / sizeof(VRingDesc); + desc_pa = vring_desc_addr(vdev, desc_pa, i); num_bufs = i = 0; } @@ -391,15 +398,15 @@ void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes, exit(1); } - if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) { - in_total += vring_desc_len(desc_pa, i); + if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_WRITE) { + in_total += vring_desc_len(vdev, desc_pa, i); } else { - out_total += vring_desc_len(desc_pa, i); + out_total += vring_desc_len(vdev, desc_pa, i); } if (in_total >= max_in_bytes && out_total >= max_out_bytes) { goto done; } - } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max); + } while ((i = virtqueue_next_desc(vdev, desc_pa, i, max)) != max); if (!indirect) total_bufs = num_bufs; @@ -430,11 +437,17 @@ void virtqueue_map_sg(struct iovec *sg, hwaddr *addr, unsigned int i; hwaddr len; + if (num_sg > VIRTQUEUE_MAX_SIZE) { + error_report("virtio: map attempt out of bounds: %zd > %d", + num_sg, VIRTQUEUE_MAX_SIZE); + exit(1); + } + for (i = 0; i < num_sg; i++) { len = sg[i].iov_len; sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write); if (sg[i].iov_base == NULL || len != sg[i].iov_len) { - error_report("virtio: trying to map MMIO memory"); + error_report("virtio: error trying to map MMIO memory"); exit(1); } } @@ -444,6 +457,7 @@ int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem) { unsigned int i, head, max; hwaddr desc_pa = vq->vring.desc; + VirtIODevice *vdev = vq->vdev; if (!virtqueue_num_heads(vq, vq->last_avail_idx)) return 0; @@ -454,19 +468,19 @@ int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem) max = vq->vring.num; i = head = virtqueue_get_head(vq, vq->last_avail_idx++); - if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) { - vring_avail_event(vq, vring_avail_idx(vq)); + if (vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) { + vring_avail_event(vq, vq->last_avail_idx); } - if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) { - if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) { + if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_INDIRECT) { + if (vring_desc_len(vdev, desc_pa, i) % sizeof(VRingDesc)) { error_report("Invalid size for indirect buffer table"); exit(1); } /* loop over the indirect descriptor table */ - max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc); - desc_pa = vring_desc_addr(desc_pa, i); + max = vring_desc_len(vdev, desc_pa, i) / sizeof(VRingDesc); + desc_pa = vring_desc_addr(vdev, desc_pa, i); i = 0; } @@ -474,30 +488,30 @@ int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem) do { struct iovec *sg; - if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) { + if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_WRITE) { if (elem->in_num >= ARRAY_SIZE(elem->in_sg)) { error_report("Too many write descriptors in indirect table"); exit(1); } - elem->in_addr[elem->in_num] = vring_desc_addr(desc_pa, i); + elem->in_addr[elem->in_num] = vring_desc_addr(vdev, desc_pa, i); sg = &elem->in_sg[elem->in_num++]; } else { if (elem->out_num >= ARRAY_SIZE(elem->out_sg)) { error_report("Too many read descriptors in indirect table"); exit(1); } - elem->out_addr[elem->out_num] = vring_desc_addr(desc_pa, i); + elem->out_addr[elem->out_num] = vring_desc_addr(vdev, desc_pa, i); sg = &elem->out_sg[elem->out_num++]; } - sg->iov_len = vring_desc_len(desc_pa, i); + sg->iov_len = vring_desc_len(vdev, desc_pa, i); /* If we've got too many, that implies a descriptor loop. */ if ((elem->in_num + elem->out_num) > max) { error_report("Looped descriptor"); exit(1); } - } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max); + } while ((i = virtqueue_next_desc(vdev, desc_pa, i, max)) != max); /* Now map what we have collected */ virtqueue_map_sg(elem->in_sg, elem->in_addr, elem->in_num, 1); @@ -538,6 +552,27 @@ void virtio_set_status(VirtIODevice *vdev, uint8_t val) vdev->status = val; } +bool target_words_bigendian(void); +static enum virtio_device_endian virtio_default_endian(void) +{ + if (target_words_bigendian()) { + return VIRTIO_DEVICE_ENDIAN_BIG; + } else { + return VIRTIO_DEVICE_ENDIAN_LITTLE; + } +} + +static enum virtio_device_endian virtio_current_cpu_endian(void) +{ + CPUClass *cc = CPU_GET_CLASS(current_cpu); + + if (cc->virtio_is_big_endian(current_cpu)) { + return VIRTIO_DEVICE_ENDIAN_BIG; + } else { + return VIRTIO_DEVICE_ENDIAN_LITTLE; + } +} + void virtio_reset(void *opaque) { VirtIODevice *vdev = opaque; @@ -545,6 +580,13 @@ void virtio_reset(void *opaque) int i; virtio_set_status(vdev, 0); + if (current_cpu) { + /* Guest initiated reset */ + vdev->device_endian = virtio_current_cpu_endian(); + } else { + /* System reset */ + vdev->device_endian = virtio_default_endian(); + } if (k->reset) { k->reset(vdev); @@ -833,10 +875,46 @@ void virtio_notify_config(VirtIODevice *vdev) virtio_notify_vector(vdev, vdev->config_vector); } +static bool virtio_device_endian_needed(void *opaque) +{ + VirtIODevice *vdev = opaque; + + assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN); + return vdev->device_endian != virtio_default_endian(); +} + +static const VMStateDescription vmstate_virtio_device_endian = { + .name = "virtio/device_endian", + .version_id = 1, + .minimum_version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_UINT8(device_endian, VirtIODevice), + VMSTATE_END_OF_LIST() + } +}; + +static const VMStateDescription vmstate_virtio = { + .name = "virtio", + .version_id = 1, + .minimum_version_id = 1, + .minimum_version_id_old = 1, + .fields = (VMStateField[]) { + VMSTATE_END_OF_LIST() + }, + .subsections = (VMStateSubsection[]) { + { + .vmsd = &vmstate_virtio_device_endian, + .needed = &virtio_device_endian_needed + }, + { 0 } + } +}; + void virtio_save(VirtIODevice *vdev, QEMUFile *f) { BusState *qbus = qdev_get_parent_bus(DEVICE(vdev)); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev); int i; if (k->save_config) { @@ -871,6 +949,13 @@ void virtio_save(VirtIODevice *vdev, QEMUFile *f) k->save_queue(qbus->parent, i, f); } } + + if (vdc->save != NULL) { + vdc->save(vdev, f); + } + + /* Subsections */ + vmstate_save_state(f, &vmstate_virtio, vdev); } int virtio_set_features(VirtIODevice *vdev, uint32_t val) @@ -889,13 +974,22 @@ int virtio_set_features(VirtIODevice *vdev, uint32_t val) return bad ? -1 : 0; } -int virtio_load(VirtIODevice *vdev, QEMUFile *f) +int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id) { - int num, i, ret; + int i, ret; + int32_t config_len; + uint32_t num; uint32_t features; uint32_t supported_features; BusState *qbus = qdev_get_parent_bus(DEVICE(vdev)); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); + VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev); + + /* + * We poison the endianness to ensure it does not get used before + * subsections have been loaded. + */ + vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN; if (k->load_config) { ret = k->load_config(qbus->parent, f); @@ -906,6 +1000,9 @@ int virtio_load(VirtIODevice *vdev, QEMUFile *f) qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); + if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) { + return -1; + } qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { @@ -914,11 +1011,27 @@ int virtio_load(VirtIODevice *vdev, QEMUFile *f) features, supported_features); return -1; } - vdev->config_len = qemu_get_be32(f); - qemu_get_buffer(f, vdev->config, vdev->config_len); + config_len = qemu_get_be32(f); + + /* + * There are cases where the incoming config can be bigger or smaller + * than what we have; so load what we have space for, and skip + * any excess that's in the stream. + */ + qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len)); + + while (config_len > vdev->config_len) { + qemu_get_byte(f); + config_len--; + } num = qemu_get_be32(f); + if (num > VIRTIO_PCI_QUEUE_MAX) { + error_report("Invalid number of PCI queues: 0x%x", num); + return -1; + } + for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { @@ -930,18 +1043,7 @@ int virtio_load(VirtIODevice *vdev, QEMUFile *f) vdev->vq[i].notification = true; if (vdev->vq[i].pa) { - uint16_t nheads; virtqueue_init(&vdev->vq[i]); - nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; - /* Check it isn't doing very strange things with descriptor numbers. */ - if (nheads > vdev->vq[i].vring.num) { - error_report("VQ %d size 0x%x Guest index 0x%x " - "inconsistent with Host index 0x%x: delta 0x%x", - i, vdev->vq[i].vring.num, - vring_avail_idx(&vdev->vq[i]), - vdev->vq[i].last_avail_idx, nheads); - return -1; - } } else if (vdev->vq[i].last_avail_idx) { error_report("VQ %d address 0x0 " "inconsistent with Host index 0x%x", @@ -956,6 +1058,40 @@ int virtio_load(VirtIODevice *vdev, QEMUFile *f) } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); + + if (vdc->load != NULL) { + ret = vdc->load(vdev, f, version_id); + if (ret) { + return ret; + } + } + + /* Subsections */ + ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1); + if (ret) { + return ret; + } + + if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) { + vdev->device_endian = virtio_default_endian(); + } + + for (i = 0; i < num; i++) { + if (vdev->vq[i].pa) { + uint16_t nheads; + nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; + /* Check it isn't doing strange things with descriptor numbers. */ + if (nheads > vdev->vq[i].vring.num) { + error_report("VQ %d size 0x%x Guest index 0x%x " + "inconsistent with Host index 0x%x: delta 0x%x", + i, vdev->vq[i].vring.num, + vring_avail_idx(&vdev->vq[i]), + vdev->vq[i].last_avail_idx, nheads); + return -1; + } + } + } + return 0; } @@ -987,6 +1123,17 @@ static void virtio_vmstate_change(void *opaque, int running, RunState state) } } +void virtio_instance_init_common(Object *proxy_obj, void *data, + size_t vdev_size, const char *vdev_name) +{ + DeviceState *vdev = data; + + object_initialize(vdev, vdev_size, vdev_name); + object_property_add_child(proxy_obj, "virtio-backend", OBJECT(vdev), NULL); + object_unref(OBJECT(vdev)); + qdev_alias_all_properties(vdev, proxy_obj); +} + void virtio_init(VirtIODevice *vdev, const char *name, uint16_t device_id, size_t config_size) { @@ -1013,6 +1160,7 @@ void virtio_init(VirtIODevice *vdev, const char *name, } vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change, vdev); + vdev->device_endian = virtio_default_endian(); } hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n) @@ -1143,14 +1291,8 @@ EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq) void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name) { - if (vdev->bus_name) { - g_free(vdev->bus_name); - vdev->bus_name = NULL; - } - - if (bus_name) { - vdev->bus_name = g_strdup(bus_name); - } + g_free(vdev->bus_name); + vdev->bus_name = g_strdup(bus_name); } static void virtio_device_realize(DeviceState *dev, Error **errp) @@ -1185,10 +1327,8 @@ static void virtio_device_unrealize(DeviceState *dev, Error **errp) } } - if (vdev->bus_name) { - g_free(vdev->bus_name); - vdev->bus_name = NULL; - } + g_free(vdev->bus_name); + vdev->bus_name = NULL; } static void virtio_device_class_init(ObjectClass *klass, void *data) diff --git a/hw/watchdog/watchdog.c b/hw/watchdog/watchdog.c index f28161b2d6..c307f9b57e 100644 --- a/hw/watchdog/watchdog.c +++ b/hw/watchdog/watchdog.c @@ -24,9 +24,9 @@ #include "qemu/config-file.h" #include "qemu/queue.h" #include "qapi/qmp/types.h" -#include "monitor/monitor.h" #include "sysemu/sysemu.h" #include "sysemu/watchdog.h" +#include "qapi-event.h" /* Possible values for action parameter. */ #define WDT_RESET 1 /* Hard reset. */ @@ -101,47 +101,42 @@ int select_watchdog_action(const char *p) return 0; } -static void watchdog_mon_event(const char *action) -{ - QObject *data; - - data = qobject_from_jsonf("{ 'action': %s }", action); - monitor_protocol_event(QEVENT_WATCHDOG, data); - qobject_decref(data); -} - /* This actually performs the "action" once a watchdog has expired, * ie. reboot, shutdown, exit, etc. */ void watchdog_perform_action(void) { - switch(watchdog_action) { + switch (watchdog_action) { case WDT_RESET: /* same as 'system_reset' in monitor */ - watchdog_mon_event("reset"); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_RESET, &error_abort); qemu_system_reset_request(); break; case WDT_SHUTDOWN: /* same as 'system_powerdown' in monitor */ - watchdog_mon_event("shutdown"); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_SHUTDOWN, &error_abort); qemu_system_powerdown_request(); break; case WDT_POWEROFF: /* same as 'quit' command in monitor */ - watchdog_mon_event("poweroff"); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_POWEROFF, &error_abort); exit(0); case WDT_PAUSE: /* same as 'stop' command in monitor */ - watchdog_mon_event("pause"); - vm_stop(RUN_STATE_WATCHDOG); + /* In a timer callback, when vm_stop calls qemu_clock_enable + * you would get a deadlock. Bypass the problem. + */ + qemu_system_vmstop_request_prepare(); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_PAUSE, &error_abort); + qemu_system_vmstop_request(RUN_STATE_WATCHDOG); break; case WDT_DEBUG: - watchdog_mon_event("debug"); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_DEBUG, &error_abort); fprintf(stderr, "watchdog: timer fired\n"); break; case WDT_NONE: - watchdog_mon_event("none"); + qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_NONE, &error_abort); break; } } diff --git a/hw/watchdog/wdt_i6300esb.c b/hw/watchdog/wdt_i6300esb.c index 36d38878ee..687c8b1d4a 100644 --- a/hw/watchdog/wdt_i6300esb.c +++ b/hw/watchdog/wdt_i6300esb.c @@ -379,18 +379,18 @@ static const VMStateDescription vmstate_i6300esb = { * version_id to be set for every build. This eventually broke * migration. * - * To correct this without breaking old->new migration for older versions - * of QEMU, we've set version_id to a value high enough to exceed all past - * values of sizeof(I6300State) across various build environments, and have - * reset minimum_version_id_old/minimum_version_id to 1, since this VMSD - * has never changed and thus can accept all past versions. + * To correct this without breaking old->new migration for older + * versions of QEMU, we've set version_id to a value high enough + * to exceed all past values of sizeof(I6300State) across various + * build environments, and have reset minimum_version_id to 1, + * since this VMSD has never changed and thus can accept all past + * versions. * * For future changes we can treat these values as we normally would. */ .version_id = 10000, .minimum_version_id = 1, - .minimum_version_id_old = 1, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(dev, I6300State), VMSTATE_INT32(reboot_enabled, I6300State), VMSTATE_INT32(clock_scale, I6300State), @@ -425,13 +425,6 @@ static int i6300esb_init(PCIDevice *dev) return 0; } -static void i6300esb_exit(PCIDevice *dev) -{ - I6300State *d = DO_UPCAST(I6300State, dev, dev); - - memory_region_destroy(&d->io_mem); -} - static WatchdogTimerModel model = { .wdt_name = "i6300esb", .wdt_description = "Intel 6300ESB", @@ -445,7 +438,6 @@ static void i6300esb_class_init(ObjectClass *klass, void *data) k->config_read = i6300esb_config_read; k->config_write = i6300esb_config_write; k->init = i6300esb_init; - k->exit = i6300esb_exit; k->vendor_id = PCI_VENDOR_ID_INTEL; k->device_id = PCI_DEVICE_ID_INTEL_ESB_9; k->class_id = PCI_CLASS_SYSTEM_OTHER; diff --git a/hw/watchdog/wdt_ib700.c b/hw/watchdog/wdt_ib700.c index bc994a4c32..8cb9827e3b 100644 --- a/hw/watchdog/wdt_ib700.c +++ b/hw/watchdog/wdt_ib700.c @@ -42,6 +42,8 @@ typedef struct IB700state { ISADevice parent_obj; QEMUTimer *timer; + + PortioList port_list; } IB700State; /* This is the timer. We use a global here because the watchdog @@ -90,8 +92,7 @@ static const VMStateDescription vmstate_ib700 = { .name = "ib700_wdt", .version_id = 0, .minimum_version_id = 0, - .minimum_version_id_old = 0, - .fields = (VMStateField []) { + .fields = (VMStateField[]) { VMSTATE_TIMER(timer, IB700State), VMSTATE_END_OF_LIST() } @@ -106,14 +107,13 @@ static const MemoryRegionPortio wdt_portio_list[] = { static void wdt_ib700_realize(DeviceState *dev, Error **errp) { IB700State *s = IB700(dev); - PortioList *port_list = g_new(PortioList, 1); ib700_debug("watchdog init\n"); s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ib700_timer_expired, s); - portio_list_init(port_list, OBJECT(s), wdt_portio_list, s, "ib700"); - portio_list_add(port_list, isa_address_space_io(&s->parent_obj), 0); + portio_list_init(&s->port_list, OBJECT(s), wdt_portio_list, s, "ib700"); + portio_list_add(&s->port_list, isa_address_space_io(&s->parent_obj), 0); } static void wdt_ib700_reset(DeviceState *dev) diff --git a/hw/xen/Makefile.objs b/hw/xen/Makefile.objs index ce640c61a5..a0ca0aa3df 100644 --- a/hw/xen/Makefile.objs +++ b/hw/xen/Makefile.objs @@ -1,6 +1,5 @@ # xen backend driver support common-obj-$(CONFIG_XEN_BACKEND) += xen_backend.o xen_devconfig.o -obj-$(CONFIG_XEN_I386) += xen_platform.o xen_apic.o xen_pvdevice.o obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen-host-pci-device.o obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen_pt.o xen_pt_config_init.o xen_pt_msi.o diff --git a/hw/xen/xen_backend.c b/hw/xen/xen_backend.c index 197795ffe1..b2cb22b99d 100644 --- a/hw/xen/xen_backend.c +++ b/hw/xen/xen_backend.c @@ -45,7 +45,6 @@ /* public */ XenXC xen_xc = XC_HANDLER_INITIAL_VALUE; -XenGnttab xen_xcg = XC_HANDLER_INITIAL_VALUE; struct xs_handle *xenstore = NULL; const char *xen_protocol; @@ -112,6 +111,19 @@ int xenstore_read_int(const char *base, const char *node, int *ival) return rc; } +int xenstore_read_uint64(const char *base, const char *node, uint64_t *uval) +{ + char *val; + int rc = -1; + + val = xenstore_read_str(base, node); + if (val && 1 == sscanf(val, "%"SCNu64, uval)) { + rc = 0; + } + g_free(val); + return rc; +} + int xenstore_write_be_str(struct XenDevice *xendev, const char *node, const char *val) { return xenstore_write_str(xendev->be, node, val); @@ -147,6 +159,11 @@ int xenstore_read_fe_int(struct XenDevice *xendev, const char *node, int *ival) return xenstore_read_int(xendev->fe, node, ival); } +int xenstore_read_fe_uint64(struct XenDevice *xendev, const char *node, uint64_t *uval) +{ + return xenstore_read_uint64(xendev->fe, node, uval); +} + /* ------------------------------------------------------------- */ const char *xenbus_strstate(enum xenbus_state state) diff --git a/hw/xen/xen_devconfig.c b/hw/xen/xen_devconfig.c index fa998eff04..e138dbbec9 100644 --- a/hw/xen/xen_devconfig.c +++ b/hw/xen/xen_devconfig.c @@ -1,4 +1,5 @@ #include "hw/xen/xen_backend.h" +#include "sysemu/block-backend.h" #include "sysemu/blockdev.h" /* ------------------------------------------------------------- */ diff --git a/hw/xen/xen_pt.c b/hw/xen/xen_pt.c index be4220b415..c1bf357154 100644 --- a/hw/xen/xen_pt.c +++ b/hw/xen/xen_pt.c @@ -453,25 +453,6 @@ static int xen_pt_register_regions(XenPCIPassthroughState *s) return 0; } -static void xen_pt_unregister_regions(XenPCIPassthroughState *s) -{ - XenHostPCIDevice *d = &s->real_device; - int i; - - for (i = 0; i < PCI_NUM_REGIONS - 1; i++) { - XenHostPCIIORegion *r = &d->io_regions[i]; - - if (r->base_addr == 0 || r->size == 0) { - continue; - } - - memory_region_destroy(&s->bar[i]); - } - if (d->rom.base_addr && d->rom.size) { - memory_region_destroy(&s->rom); - } -} - /* region mapping */ static int xen_pt_bar_from_region(XenPCIPassthroughState *s, MemoryRegion *mr) @@ -810,7 +791,6 @@ static void xen_pt_unregister_device(PCIDevice *d) /* delete all emulated config registers */ xen_pt_config_delete(s); - xen_pt_unregister_regions(s); memory_listener_unregister(&s->memory_listener); memory_listener_unregister(&s->io_listener); diff --git a/hw/xen/xen_pt_config_init.c b/hw/xen/xen_pt_config_init.c index 8ccc2e4b9c..de9a20f437 100644 --- a/hw/xen/xen_pt_config_init.c +++ b/hw/xen/xen_pt_config_init.c @@ -1123,8 +1123,8 @@ static int xen_pt_msgctrl_reg_write(XenPCIPassthroughState *s, msi->mapped = true; } msi->flags |= PCI_MSI_FLAGS_ENABLE; - } else { - msi->flags &= ~PCI_MSI_FLAGS_ENABLE; + } else if (msi->mapped) { + xen_pt_msi_disable(s); } /* pass through MSI_ENABLE bit */ @@ -1397,6 +1397,8 @@ static int xen_pt_msixctrl_reg_write(XenPCIPassthroughState *s, if ((*val & PCI_MSIX_FLAGS_ENABLE) && !(*val & PCI_MSIX_FLAGS_MASKALL)) { xen_pt_msix_update(s); + } else if (!(*val & PCI_MSIX_FLAGS_ENABLE) && s->msix->enabled) { + xen_pt_msix_disable(s); } debug_msix_enabled_old = s->msix->enabled; diff --git a/hw/xen/xen_pt_msi.c b/hw/xen/xen_pt_msi.c index 6fbe0cc86b..9ed9321c9f 100644 --- a/hw/xen/xen_pt_msi.c +++ b/hw/xen/xen_pt_msi.c @@ -282,7 +282,8 @@ void xen_pt_msi_disable(XenPCIPassthroughState *s) msi->initialized); /* clear msi info */ - msi->flags = 0; + msi->flags &= ~PCI_MSI_FLAGS_ENABLE; + msi->initialized = false; msi->mapped = false; msi->pirq = XEN_PT_UNASSIGNED_PIRQ; } @@ -446,7 +447,8 @@ static void pci_msix_write(void *opaque, hwaddr addr, if (offset != PCI_MSIX_ENTRY_VECTOR_CTRL) { const volatile uint32_t *vec_ctrl; - if (get_entry_value(entry, offset) == val) { + if (get_entry_value(entry, offset) == val + && entry->pirq != XEN_PT_UNASSIGNED_PIRQ) { return; } @@ -591,7 +593,6 @@ int xen_pt_msix_init(XenPCIPassthroughState *s, uint32_t base) return 0; error_out: - memory_region_destroy(&msix->mmio); g_free(s->msix); s->msix = NULL; return rc; @@ -614,7 +615,6 @@ void xen_pt_msix_delete(XenPCIPassthroughState *s) } memory_region_del_subregion(&s->bar[msix->bar_index], &msix->mmio); - memory_region_destroy(&msix->mmio); g_free(s->msix); s->msix = NULL; diff --git a/hw/xenpv/Makefile.objs b/hw/xenpv/Makefile.objs new file mode 100644 index 0000000000..49f6e9e3c5 --- /dev/null +++ b/hw/xenpv/Makefile.objs @@ -0,0 +1,2 @@ +# Xen PV machine support +obj-$(CONFIG_XEN) += xen_domainbuild.o xen_machine_pv.o diff --git a/hw/i386/xen_domainbuild.c b/hw/xenpv/xen_domainbuild.c index c0ab7537df..c0ab7537df 100644 --- a/hw/i386/xen_domainbuild.c +++ b/hw/xenpv/xen_domainbuild.c diff --git a/hw/i386/xen_domainbuild.h b/hw/xenpv/xen_domainbuild.h index 29a91ea7b1..29a91ea7b1 100644 --- a/hw/i386/xen_domainbuild.h +++ b/hw/xenpv/xen_domainbuild.h diff --git a/hw/i386/xen_machine_pv.c b/hw/xenpv/xen_machine_pv.c index 9adb57fc14..2e545d2418 100644 --- a/hw/i386/xen_machine_pv.c +++ b/hw/xenpv/xen_machine_pv.c @@ -26,13 +26,13 @@ #include "hw/boards.h" #include "hw/xen/xen_backend.h" #include "xen_domainbuild.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" -static void xen_init_pv(QEMUMachineInitArgs *args) +static void xen_init_pv(MachineState *machine) { - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; - const char *initrd_filename = args->initrd_filename; + const char *kernel_filename = machine->kernel_filename; + const char *kernel_cmdline = machine->kernel_cmdline; + const char *initrd_filename = machine->initrd_filename; DriveInfo *dinfo; int i; diff --git a/hw/xtensa/Makefile.objs b/hw/xtensa/Makefile.objs index 6ead7820c4..cb77dc3793 100644 --- a/hw/xtensa/Makefile.objs +++ b/hw/xtensa/Makefile.objs @@ -1,3 +1,3 @@ obj-y += pic_cpu.o -obj-y += xtensa_sim.o -obj-y += xtensa_lx60.o +obj-y += sim.o +obj-y += xtfpga.o diff --git a/hw/xtensa/bootparam.h b/hw/xtensa/bootparam.h new file mode 100644 index 0000000000..955f4e86e3 --- /dev/null +++ b/hw/xtensa/bootparam.h @@ -0,0 +1,49 @@ +#ifndef HW_XTENSA_BOOTPARAM +#define HW_XTENSA_BOOTPARAM + +#define BP_TAG_COMMAND_LINE 0x1001 /* command line (0-terminated string)*/ +#define BP_TAG_INITRD 0x1002 /* ramdisk addr and size (bp_meminfo) */ +#define BP_TAG_MEMORY 0x1003 /* memory addr and size (bp_meminfo) */ +#define BP_TAG_SERIAL_BAUDRATE 0x1004 /* baud rate of current console. */ +#define BP_TAG_SERIAL_PORT 0x1005 /* serial device of current console */ +#define BP_TAG_FDT 0x1006 /* flat device tree addr */ + +#define BP_TAG_FIRST 0x7B0B /* first tag with a version number */ +#define BP_TAG_LAST 0x7E0B /* last tag */ + +typedef struct BpTag { + uint16_t tag; + uint16_t size; +} BpTag; + +typedef struct BpMemInfo { + uint32_t type; + uint32_t start; + uint32_t end; +} BpMemInfo; + +#define MEMORY_TYPE_CONVENTIONAL 0x1000 +#define MEMORY_TYPE_NONE 0x2000 + +static inline size_t get_tag_size(size_t data_size) +{ + return data_size + sizeof(BpTag) + 4; +} + +static inline ram_addr_t put_tag(ram_addr_t addr, uint16_t tag, + size_t size, const void *data) +{ + BpTag bp_tag = { + .tag = tswap16(tag), + .size = tswap16((size + 3) & ~3), + }; + + cpu_physical_memory_write(addr, &bp_tag, sizeof(bp_tag)); + addr += sizeof(bp_tag); + cpu_physical_memory_write(addr, data, size); + addr += (size + 3) & ~3; + + return addr; +} + +#endif diff --git a/hw/xtensa/pic_cpu.c b/hw/xtensa/pic_cpu.c index e2005bd981..18825d19f0 100644 --- a/hw/xtensa/pic_cpu.c +++ b/hw/xtensa/pic_cpu.c @@ -31,14 +31,14 @@ void xtensa_advance_ccount(CPUXtensaState *env, uint32_t d) { - uint32_t old_ccount = env->sregs[CCOUNT]; + uint32_t old_ccount = env->sregs[CCOUNT] + 1; env->sregs[CCOUNT] += d; if (xtensa_option_enabled(env->config, XTENSA_OPTION_TIMER_INTERRUPT)) { int i; for (i = 0; i < env->config->nccompare; ++i) { - if (env->sregs[CCOMPARE + i] - old_ccount <= d) { + if (env->sregs[CCOMPARE + i] - old_ccount < d) { xtensa_timer_irq(env, i, 1); } } diff --git a/hw/xtensa/xtensa_sim.c b/hw/xtensa/sim.c index 1192ce7134..37ea9ae9c2 100644 --- a/hw/xtensa/xtensa_sim.c +++ b/hw/xtensa/sim.c @@ -31,6 +31,7 @@ #include "elf.h" #include "exec/memory.h" #include "exec/address-spaces.h" +#include "qemu/error-report.h" static uint64_t translate_phys_addr(void *opaque, uint64_t addr) { @@ -46,14 +47,14 @@ static void sim_reset(void *opaque) cpu_reset(CPU(cpu)); } -static void xtensa_sim_init(QEMUMachineInitArgs *args) +static void xtensa_sim_init(MachineState *machine) { XtensaCPU *cpu = NULL; CPUXtensaState *env = NULL; MemoryRegion *ram, *rom; - ram_addr_t ram_size = args->ram_size; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; + ram_addr_t ram_size = machine->ram_size; + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = machine->kernel_filename; int n; if (!cpu_model) { @@ -63,8 +64,9 @@ static void xtensa_sim_init(QEMUMachineInitArgs *args) for (n = 0; n < smp_cpus; n++) { cpu = cpu_xtensa_init(cpu_model); if (cpu == NULL) { - fprintf(stderr, "Unable to find CPU definition\n"); - exit(1); + error_report("unable to find CPU definition '%s'\n", + cpu_model); + exit(EXIT_FAILURE); } env = &cpu->env; @@ -77,12 +79,12 @@ static void xtensa_sim_init(QEMUMachineInitArgs *args) } ram = g_malloc(sizeof(*ram)); - memory_region_init_ram(ram, NULL, "xtensa.sram", ram_size); + memory_region_init_ram(ram, NULL, "xtensa.sram", ram_size, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(get_system_memory(), 0, ram); rom = g_malloc(sizeof(*rom)); - memory_region_init_ram(rom, NULL, "xtensa.rom", 0x1000); + memory_region_init_ram(rom, NULL, "xtensa.rom", 0x1000, &error_abort); vmstate_register_ram_global(rom); memory_region_add_subregion(get_system_memory(), 0xfe000000, rom); diff --git a/hw/xtensa/xtensa_bootparam.h b/hw/xtensa/xtensa_bootparam.h deleted file mode 100644 index 38ef32bdb6..0000000000 --- a/hw/xtensa/xtensa_bootparam.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef HW_XTENSA_BOOTPARAM -#define HW_XTENSA_BOOTPARAM - -typedef struct BpTag { - uint16_t tag; - uint16_t size; -} BpTag; - -static inline ram_addr_t put_tag(ram_addr_t addr, uint16_t tag, - size_t size, const void *data) -{ - BpTag bp_tag = { - .tag = tswap16(tag), - .size = tswap16((size + 3) & ~3), - }; - - cpu_physical_memory_write(addr, &bp_tag, sizeof(bp_tag)); - addr += sizeof(bp_tag); - cpu_physical_memory_write(addr, data, size); - addr += (size + 3) & ~3; - - return addr; -} - -#endif diff --git a/hw/xtensa/xtensa_lx60.c b/hw/xtensa/xtfpga.c index 49c58d11a3..e5a6bba783 100644 --- a/hw/xtensa/xtensa_lx60.c +++ b/hw/xtensa/xtfpga.c @@ -35,13 +35,16 @@ #include "net/net.h" #include "hw/sysbus.h" #include "hw/block/flash.h" -#include "sysemu/blockdev.h" +#include "sysemu/block-backend.h" #include "sysemu/char.h" -#include "xtensa_bootparam.h" +#include "sysemu/device_tree.h" +#include "qemu/error-report.h" +#include "bootparam.h" typedef struct LxBoardDesc { hwaddr flash_base; size_t flash_size; + size_t flash_boot_base; size_t flash_sector_size; size_t sram_size; } LxBoardDesc; @@ -140,7 +143,7 @@ static void lx60_net_init(MemoryRegion *address_space, sysbus_mmio_get_region(s, 1)); ram = g_malloc(sizeof(*ram)); - memory_region_init_ram(ram, OBJECT(s), "open_eth.ram", 16384); + memory_region_init_ram(ram, OBJECT(s), "open_eth.ram", 16384, &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space, buffers, ram); } @@ -159,7 +162,7 @@ static void lx60_reset(void *opaque) cpu_reset(CPU(cpu)); } -static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) +static void lx_init(const LxBoardDesc *board, MachineState *machine) { #ifdef TARGET_WORDS_BIGENDIAN int be = 1; @@ -172,9 +175,12 @@ static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) MemoryRegion *ram, *rom, *system_io; DriveInfo *dinfo; pflash_t *flash = NULL; - const char *cpu_model = args->cpu_model; - const char *kernel_filename = args->kernel_filename; - const char *kernel_cmdline = args->kernel_cmdline; + QemuOpts *machine_opts = qemu_get_machine_opts(); + const char *cpu_model = machine->cpu_model; + const char *kernel_filename = qemu_opt_get(machine_opts, "kernel"); + const char *kernel_cmdline = qemu_opt_get(machine_opts, "append"); + const char *dtb_filename = qemu_opt_get(machine_opts, "dtb"); + const char *initrd_filename = qemu_opt_get(machine_opts, "initrd"); int n; if (!cpu_model) { @@ -184,8 +190,9 @@ static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) for (n = 0; n < smp_cpus; n++) { cpu = cpu_xtensa_init(cpu_model); if (cpu == NULL) { - fprintf(stderr, "Unable to find CPU definition\n"); - exit(1); + error_report("unable to find CPU definition '%s'\n", + cpu_model); + exit(EXIT_FAILURE); } env = &cpu->env; @@ -198,7 +205,8 @@ static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) } ram = g_malloc(sizeof(*ram)); - memory_region_init_ram(ram, NULL, "lx60.dram", args->ram_size); + memory_region_init_ram(ram, NULL, "lx60.dram", machine->ram_size, + &error_abort); vmstate_register_ram_global(ram); memory_region_add_subregion(system_memory, 0, ram); @@ -222,43 +230,124 @@ static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) if (dinfo) { flash = pflash_cfi01_register(board->flash_base, NULL, "lx60.io.flash", board->flash_size, - dinfo->bdrv, board->flash_sector_size, + blk_by_legacy_dinfo(dinfo), + board->flash_sector_size, board->flash_size / board->flash_sector_size, 4, 0x0000, 0x0000, 0x0000, 0x0000, be); if (flash == NULL) { - fprintf(stderr, "Unable to mount pflash\n"); - exit(1); + error_report("unable to mount pflash\n"); + exit(EXIT_FAILURE); } } /* Use presence of kernel file name as 'boot from SRAM' switch. */ if (kernel_filename) { + uint32_t entry_point = env->pc; + size_t bp_size = 3 * get_tag_size(0); /* first/last and memory tags */ + uint32_t tagptr = 0xfe000000 + board->sram_size; + uint32_t cur_tagptr; + BpMemInfo memory_location = { + .type = tswap32(MEMORY_TYPE_CONVENTIONAL), + .start = tswap32(0), + .end = tswap32(machine->ram_size), + }; + uint32_t lowmem_end = machine->ram_size < 0x08000000 ? + machine->ram_size : 0x08000000; + uint32_t cur_lowmem = QEMU_ALIGN_UP(lowmem_end / 2, 4096); + rom = g_malloc(sizeof(*rom)); - memory_region_init_ram(rom, NULL, "lx60.sram", board->sram_size); + memory_region_init_ram(rom, NULL, "lx60.sram", board->sram_size, + &error_abort); vmstate_register_ram_global(rom); memory_region_add_subregion(system_memory, 0xfe000000, rom); - /* Put kernel bootparameters to the end of that SRAM */ if (kernel_cmdline) { - size_t cmdline_size = strlen(kernel_cmdline) + 1; - size_t bp_size = sizeof(BpTag[4]) + cmdline_size; - uint32_t tagptr = (0xfe000000 + board->sram_size - bp_size) & ~0xff; + bp_size += get_tag_size(strlen(kernel_cmdline) + 1); + } + if (dtb_filename) { + bp_size += get_tag_size(sizeof(uint32_t)); + } + if (initrd_filename) { + bp_size += get_tag_size(sizeof(BpMemInfo)); + } - env->regs[2] = tagptr; + /* Put kernel bootparameters to the end of that SRAM */ + tagptr = (tagptr - bp_size) & ~0xff; + cur_tagptr = put_tag(tagptr, BP_TAG_FIRST, 0, NULL); + cur_tagptr = put_tag(cur_tagptr, BP_TAG_MEMORY, + sizeof(memory_location), &memory_location); + + if (kernel_cmdline) { + cur_tagptr = put_tag(cur_tagptr, BP_TAG_COMMAND_LINE, + strlen(kernel_cmdline) + 1, kernel_cmdline); + } + if (dtb_filename) { + int fdt_size; + void *fdt = load_device_tree(dtb_filename, &fdt_size); + uint32_t dtb_addr = tswap32(cur_lowmem); + + if (!fdt) { + error_report("could not load DTB '%s'\n", dtb_filename); + exit(EXIT_FAILURE); + } - tagptr = put_tag(tagptr, 0x7b0b, 0, NULL); - if (cmdline_size > 1) { - tagptr = put_tag(tagptr, 0x1001, - cmdline_size, kernel_cmdline); + cpu_physical_memory_write(cur_lowmem, fdt, fdt_size); + cur_tagptr = put_tag(cur_tagptr, BP_TAG_FDT, + sizeof(dtb_addr), &dtb_addr); + cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + fdt_size, 4096); + } + if (initrd_filename) { + BpMemInfo initrd_location = { 0 }; + int initrd_size = load_ramdisk(initrd_filename, cur_lowmem, + lowmem_end - cur_lowmem); + + if (initrd_size < 0) { + initrd_size = load_image_targphys(initrd_filename, + cur_lowmem, + lowmem_end - cur_lowmem); + } + if (initrd_size < 0) { + error_report("could not load initrd '%s'\n", initrd_filename); + exit(EXIT_FAILURE); } - tagptr = put_tag(tagptr, 0x7e0b, 0, NULL); + initrd_location.start = tswap32(cur_lowmem); + initrd_location.end = tswap32(cur_lowmem + initrd_size); + cur_tagptr = put_tag(cur_tagptr, BP_TAG_INITRD, + sizeof(initrd_location), &initrd_location); + cur_lowmem = QEMU_ALIGN_UP(cur_lowmem + initrd_size, 4096); } + cur_tagptr = put_tag(cur_tagptr, BP_TAG_LAST, 0, NULL); + env->regs[2] = tagptr; + uint64_t elf_entry; uint64_t elf_lowaddr; int success = load_elf(kernel_filename, translate_phys_addr, cpu, &elf_entry, &elf_lowaddr, NULL, be, ELF_MACHINE, 0); if (success > 0) { - env->pc = elf_entry; + entry_point = elf_entry; + } else { + hwaddr ep; + int is_linux; + success = load_uimage(kernel_filename, &ep, NULL, &is_linux, + translate_phys_addr, cpu); + if (success > 0 && is_linux) { + entry_point = ep; + } else { + error_report("could not load kernel '%s'\n", + kernel_filename); + exit(EXIT_FAILURE); + } + } + if (entry_point != env->pc) { + static const uint8_t jx_a0[] = { +#ifdef TARGET_WORDS_BIGENDIAN + 0x0a, 0, 0, +#else + 0xa0, 0, 0, +#endif + }; + env->regs[0] = entry_point; + cpu_physical_memory_write(env->pc, jx_a0, sizeof(jx_a0)); } } else { if (flash) { @@ -266,16 +355,16 @@ static void lx_init(const LxBoardDesc *board, QEMUMachineInitArgs *args) MemoryRegion *flash_io = g_malloc(sizeof(*flash_io)); memory_region_init_alias(flash_io, NULL, "lx60.flash", - flash_mr, 0, - board->flash_size < 0x02000000 ? - board->flash_size : 0x02000000); + flash_mr, board->flash_boot_base, + board->flash_size - board->flash_boot_base < 0x02000000 ? + board->flash_size - board->flash_boot_base : 0x02000000); memory_region_add_subregion(system_memory, 0xfe000000, flash_io); } } } -static void xtensa_lx60_init(QEMUMachineInitArgs *args) +static void xtensa_lx60_init(MachineState *machine) { static const LxBoardDesc lx60_board = { .flash_base = 0xf8000000, @@ -283,10 +372,10 @@ static void xtensa_lx60_init(QEMUMachineInitArgs *args) .flash_sector_size = 0x10000, .sram_size = 0x20000, }; - lx_init(&lx60_board, args); + lx_init(&lx60_board, machine); } -static void xtensa_lx200_init(QEMUMachineInitArgs *args) +static void xtensa_lx200_init(MachineState *machine) { static const LxBoardDesc lx200_board = { .flash_base = 0xf8000000, @@ -294,10 +383,10 @@ static void xtensa_lx200_init(QEMUMachineInitArgs *args) .flash_sector_size = 0x20000, .sram_size = 0x2000000, }; - lx_init(&lx200_board, args); + lx_init(&lx200_board, machine); } -static void xtensa_ml605_init(QEMUMachineInitArgs *args) +static void xtensa_ml605_init(MachineState *machine) { static const LxBoardDesc ml605_board = { .flash_base = 0xf8000000, @@ -305,18 +394,19 @@ static void xtensa_ml605_init(QEMUMachineInitArgs *args) .flash_sector_size = 0x20000, .sram_size = 0x2000000, }; - lx_init(&ml605_board, args); + lx_init(&ml605_board, machine); } -static void xtensa_kc705_init(QEMUMachineInitArgs *args) +static void xtensa_kc705_init(MachineState *machine) { static const LxBoardDesc kc705_board = { .flash_base = 0xf0000000, .flash_size = 0x08000000, + .flash_boot_base = 0x06000000, .flash_sector_size = 0x20000, .sram_size = 0x2000000, }; - lx_init(&kc705_board, args); + lx_init(&kc705_board, machine); } static QEMUMachine xtensa_lx60_machine = { diff --git a/hw/yagl/yagl_device.c b/hw/yagl/yagl_device.c index de24498883..60fbfc8c9f 100644 --- a/hw/yagl/yagl_device.c +++ b/hw/yagl/yagl_device.c @@ -386,8 +386,6 @@ static void yagl_device_exit(PCIDevice *dev) YAGL_LOG_FUNC_ENTER(yagl_device_exit, NULL); - memory_region_destroy(&s->iomem); - yagl_server_state_destroy(s->ss); yagl_handle_gen_cleanup(); |