aboutsummaryrefslogtreecommitdiff
path: root/softmmu
diff options
context:
space:
mode:
authorPeter Maydell <peter.maydell@linaro.org>2020-10-12 22:48:45 +0100
committerPeter Maydell <peter.maydell@linaro.org>2020-10-12 22:48:45 +0100
commit724c1c8bb350d84c097ab2005aad15e125d06b6c (patch)
treeb55ff4dc3e8012e2624d2aa2d1211684bd425656 /softmmu
parenta0bdf866873467271eff9a92f179ab0f77d735cb (diff)
parenta0c9162c8250e121af438aee5ef93e64ec62dae1 (diff)
downloadqemu-724c1c8bb350d84c097ab2005aad15e125d06b6c.zip
qemu-724c1c8bb350d84c097ab2005aad15e125d06b6c.tar.gz
qemu-724c1c8bb350d84c097ab2005aad15e125d06b6c.tar.bz2
Merge remote-tracking branch 'remotes/bonzini-gitlab/tags/for-upstream' into staging
* qtest documentation improvements (Eduardo, myself) * libqtest event buffering (Maxim) * use RCU for list of children of a bus (Maxim) * move more files to softmmu/ (myself) * meson.build cleanups, qemu-storage-daemon fix (Philippe) # gpg: Signature made Mon 12 Oct 2020 16:55:19 BST # gpg: using RSA key F13338574B662389866C7682BFFBD25F78C7AE83 # gpg: issuer "pbonzini@redhat.com" # gpg: Good signature from "Paolo Bonzini <bonzini@gnu.org>" [full] # gpg: aka "Paolo Bonzini <pbonzini@redhat.com>" [full] # Primary key fingerprint: 46F5 9FBD 57D6 12E7 BFD4 E2F7 7E15 100C CD36 69B1 # Subkey fingerprint: F133 3857 4B66 2389 866C 7682 BFFB D25F 78C7 AE83 * remotes/bonzini-gitlab/tags/for-upstream: (38 commits) meson: identify more sections of meson.build scsi/scsi_bus: fix races in REPORT LUNS virtio-scsi: use scsi_device_get scsi/scsi_bus: Add scsi_device_get scsi/scsi-bus: scsi_device_find: don't return unrealized devices device-core: use atomic_set on .realized property scsi: switch to bus->check_address device-core: use RCU for list of children of a bus device_core: use drain_call_rcu in in qmp_device_add scsi/scsi_bus: switch search direction in scsi_device_find qdev: add "check if address free" callback for buses qemu-iotests, qtest: rewrite test 067 as a qtest qtest: check that drives are really appearing and disappearing qtest: switch users back to qtest_qmp_receive device-plug-test: use qtest_qmp to send the device_del command qtest: remove qtest_qmp_receive_success qtest: Reintroduce qtest_qmp_receive with QMP event buffering qtest: rename qtest_qmp_receive to qtest_qmp_receive_dict meson.build: Re-enable KVM support for MIPS build-sys: fix git version from -version ... Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
Diffstat (limited to 'softmmu')
-rw-r--r--softmmu/bootdevice.c429
-rw-r--r--softmmu/device_tree.c579
-rw-r--r--softmmu/dma-helpers.c331
-rw-r--r--softmmu/meson.build11
-rw-r--r--softmmu/physmem.c3711
-rw-r--r--softmmu/qdev-monitor.c1005
-rw-r--r--softmmu/qemu-seccomp.c331
-rw-r--r--softmmu/qtest.c71
-rw-r--r--softmmu/tpm.c265
9 files changed, 6725 insertions, 8 deletions
diff --git a/softmmu/bootdevice.c b/softmmu/bootdevice.c
new file mode 100644
index 0000000..add4e3d
--- /dev/null
+++ b/softmmu/bootdevice.c
@@ -0,0 +1,429 @@
+/*
+ * QEMU Boot Device Implement
+ *
+ * Copyright (c) 2014 HUAWEI TECHNOLOGIES CO., LTD.
+ *
+ * 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.
+ */
+
+#include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "sysemu/sysemu.h"
+#include "qapi/visitor.h"
+#include "qemu/error-report.h"
+#include "sysemu/reset.h"
+#include "hw/qdev-core.h"
+#include "hw/boards.h"
+
+typedef struct FWBootEntry FWBootEntry;
+
+struct FWBootEntry {
+ QTAILQ_ENTRY(FWBootEntry) link;
+ int32_t bootindex;
+ DeviceState *dev;
+ char *suffix;
+};
+
+static QTAILQ_HEAD(, FWBootEntry) fw_boot_order =
+ QTAILQ_HEAD_INITIALIZER(fw_boot_order);
+static QEMUBootSetHandler *boot_set_handler;
+static void *boot_set_opaque;
+
+void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
+{
+ boot_set_handler = func;
+ boot_set_opaque = opaque;
+}
+
+void qemu_boot_set(const char *boot_order, Error **errp)
+{
+ Error *local_err = NULL;
+
+ if (!boot_set_handler) {
+ error_setg(errp, "no function defined to set boot device list for"
+ " this architecture");
+ return;
+ }
+
+ validate_bootdevices(boot_order, &local_err);
+ if (local_err) {
+ error_propagate(errp, local_err);
+ return;
+ }
+
+ boot_set_handler(boot_set_opaque, boot_order, errp);
+}
+
+void validate_bootdevices(const char *devices, Error **errp)
+{
+ /* We just do some generic consistency checks */
+ const char *p;
+ int bitmap = 0;
+
+ for (p = devices; *p != '\0'; p++) {
+ /* Allowed boot devices are:
+ * a-b: floppy disk drives
+ * c-f: IDE disk drives
+ * g-m: machine implementation dependent drives
+ * n-p: network devices
+ * It's up to each machine implementation to check if the given boot
+ * devices match the actual hardware implementation and firmware
+ * features.
+ */
+ if (*p < 'a' || *p > 'p') {
+ error_setg(errp, "Invalid boot device '%c'", *p);
+ return;
+ }
+ if (bitmap & (1 << (*p - 'a'))) {
+ error_setg(errp, "Boot device '%c' was given twice", *p);
+ return;
+ }
+ bitmap |= 1 << (*p - 'a');
+ }
+}
+
+void restore_boot_order(void *opaque)
+{
+ char *normal_boot_order = opaque;
+ static int first = 1;
+
+ /* Restore boot order and remove ourselves after the first boot */
+ if (first) {
+ first = 0;
+ return;
+ }
+
+ if (boot_set_handler) {
+ qemu_boot_set(normal_boot_order, &error_abort);
+ }
+
+ qemu_unregister_reset(restore_boot_order, normal_boot_order);
+ g_free(normal_boot_order);
+}
+
+void check_boot_index(int32_t bootindex, Error **errp)
+{
+ FWBootEntry *i;
+
+ if (bootindex >= 0) {
+ QTAILQ_FOREACH(i, &fw_boot_order, link) {
+ if (i->bootindex == bootindex) {
+ error_setg(errp, "The bootindex %d has already been used",
+ bootindex);
+ return;
+ }
+ }
+ }
+}
+
+void del_boot_device_path(DeviceState *dev, const char *suffix)
+{
+ FWBootEntry *i;
+
+ if (dev == NULL) {
+ return;
+ }
+
+ QTAILQ_FOREACH(i, &fw_boot_order, link) {
+ if ((!suffix || !g_strcmp0(i->suffix, suffix)) &&
+ i->dev == dev) {
+ QTAILQ_REMOVE(&fw_boot_order, i, link);
+ g_free(i->suffix);
+ g_free(i);
+
+ break;
+ }
+ }
+}
+
+void add_boot_device_path(int32_t bootindex, DeviceState *dev,
+ const char *suffix)
+{
+ FWBootEntry *node, *i;
+
+ if (bootindex < 0) {
+ del_boot_device_path(dev, suffix);
+ return;
+ }
+
+ assert(dev != NULL || suffix != NULL);
+
+ del_boot_device_path(dev, suffix);
+
+ node = g_malloc0(sizeof(FWBootEntry));
+ node->bootindex = bootindex;
+ node->suffix = g_strdup(suffix);
+ node->dev = dev;
+
+ QTAILQ_FOREACH(i, &fw_boot_order, link) {
+ if (i->bootindex == bootindex) {
+ error_report("Two devices with same boot index %d", bootindex);
+ exit(1);
+ } else if (i->bootindex < bootindex) {
+ continue;
+ }
+ QTAILQ_INSERT_BEFORE(i, node, link);
+ return;
+ }
+ QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
+}
+
+DeviceState *get_boot_device(uint32_t position)
+{
+ uint32_t counter = 0;
+ FWBootEntry *i = NULL;
+ DeviceState *res = NULL;
+
+ if (!QTAILQ_EMPTY(&fw_boot_order)) {
+ QTAILQ_FOREACH(i, &fw_boot_order, link) {
+ if (counter == position) {
+ res = i->dev;
+ break;
+ }
+ counter++;
+ }
+ }
+ return res;
+}
+
+static char *get_boot_device_path(DeviceState *dev, bool ignore_suffixes,
+ const char *suffix)
+{
+ char *devpath = NULL, *s = NULL, *d, *bootpath;
+
+ if (dev) {
+ devpath = qdev_get_fw_dev_path(dev);
+ assert(devpath);
+ }
+
+ if (!ignore_suffixes) {
+ if (dev) {
+ d = qdev_get_own_fw_dev_path_from_handler(dev->parent_bus, dev);
+ if (d) {
+ assert(!suffix);
+ s = d;
+ } else {
+ s = g_strdup(suffix);
+ }
+ } else {
+ s = g_strdup(suffix);
+ }
+ }
+
+ bootpath = g_strdup_printf("%s%s",
+ devpath ? devpath : "",
+ s ? s : "");
+ g_free(devpath);
+ g_free(s);
+
+ return bootpath;
+}
+
+/*
+ * This function returns null terminated string that consist of new line
+ * separated device paths.
+ *
+ * memory pointed by "size" is assigned total length of the array in bytes
+ *
+ */
+char *get_boot_devices_list(size_t *size)
+{
+ FWBootEntry *i;
+ size_t total = 0;
+ char *list = NULL;
+ MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
+ bool ignore_suffixes = mc->ignore_boot_device_suffixes;
+
+ QTAILQ_FOREACH(i, &fw_boot_order, link) {
+ char *bootpath;
+ size_t len;
+
+ bootpath = get_boot_device_path(i->dev, ignore_suffixes, i->suffix);
+
+ if (total) {
+ list[total-1] = '\n';
+ }
+ len = strlen(bootpath) + 1;
+ list = g_realloc(list, total + len);
+ memcpy(&list[total], bootpath, len);
+ total += len;
+ g_free(bootpath);
+ }
+
+ *size = total;
+
+ if (boot_strict && *size > 0) {
+ list[total-1] = '\n';
+ list = g_realloc(list, total + 5);
+ memcpy(&list[total], "HALT", 5);
+ *size = total + 5;
+ }
+ return list;
+}
+
+typedef struct {
+ int32_t *bootindex;
+ const char *suffix;
+ DeviceState *dev;
+} BootIndexProperty;
+
+static void device_get_bootindex(Object *obj, Visitor *v, const char *name,
+ void *opaque, Error **errp)
+{
+ BootIndexProperty *prop = opaque;
+ visit_type_int32(v, name, prop->bootindex, errp);
+}
+
+static void device_set_bootindex(Object *obj, Visitor *v, const char *name,
+ void *opaque, Error **errp)
+{
+ BootIndexProperty *prop = opaque;
+ int32_t boot_index;
+ Error *local_err = NULL;
+
+ if (!visit_type_int32(v, name, &boot_index, errp)) {
+ return;
+ }
+ /* check whether bootindex is present in fw_boot_order list */
+ check_boot_index(boot_index, &local_err);
+ if (local_err) {
+ error_propagate(errp, local_err);
+ return;
+ }
+ /* change bootindex to a new one */
+ *prop->bootindex = boot_index;
+
+ add_boot_device_path(*prop->bootindex, prop->dev, prop->suffix);
+}
+
+static void property_release_bootindex(Object *obj, const char *name,
+ void *opaque)
+
+{
+ BootIndexProperty *prop = opaque;
+
+ del_boot_device_path(prop->dev, prop->suffix);
+ g_free(prop);
+}
+
+void device_add_bootindex_property(Object *obj, int32_t *bootindex,
+ const char *name, const char *suffix,
+ DeviceState *dev)
+{
+ BootIndexProperty *prop = g_malloc0(sizeof(*prop));
+
+ prop->bootindex = bootindex;
+ prop->suffix = suffix;
+ prop->dev = dev;
+
+ object_property_add(obj, name, "int32",
+ device_get_bootindex,
+ device_set_bootindex,
+ property_release_bootindex,
+ prop);
+
+ /* initialize devices' bootindex property to -1 */
+ object_property_set_int(obj, name, -1, NULL);
+}
+
+typedef struct FWLCHSEntry FWLCHSEntry;
+
+struct FWLCHSEntry {
+ QTAILQ_ENTRY(FWLCHSEntry) link;
+ DeviceState *dev;
+ char *suffix;
+ uint32_t lcyls;
+ uint32_t lheads;
+ uint32_t lsecs;
+};
+
+static QTAILQ_HEAD(, FWLCHSEntry) fw_lchs =
+ QTAILQ_HEAD_INITIALIZER(fw_lchs);
+
+void add_boot_device_lchs(DeviceState *dev, const char *suffix,
+ uint32_t lcyls, uint32_t lheads, uint32_t lsecs)
+{
+ FWLCHSEntry *node;
+
+ if (!lcyls && !lheads && !lsecs) {
+ return;
+ }
+
+ assert(dev != NULL || suffix != NULL);
+
+ node = g_malloc0(sizeof(FWLCHSEntry));
+ node->suffix = g_strdup(suffix);
+ node->dev = dev;
+ node->lcyls = lcyls;
+ node->lheads = lheads;
+ node->lsecs = lsecs;
+
+ QTAILQ_INSERT_TAIL(&fw_lchs, node, link);
+}
+
+void del_boot_device_lchs(DeviceState *dev, const char *suffix)
+{
+ FWLCHSEntry *i;
+
+ if (dev == NULL) {
+ return;
+ }
+
+ QTAILQ_FOREACH(i, &fw_lchs, link) {
+ if ((!suffix || !g_strcmp0(i->suffix, suffix)) &&
+ i->dev == dev) {
+ QTAILQ_REMOVE(&fw_lchs, i, link);
+ g_free(i->suffix);
+ g_free(i);
+
+ break;
+ }
+ }
+}
+
+char *get_boot_devices_lchs_list(size_t *size)
+{
+ FWLCHSEntry *i;
+ size_t total = 0;
+ char *list = NULL;
+
+ QTAILQ_FOREACH(i, &fw_lchs, link) {
+ char *bootpath;
+ char *chs_string;
+ size_t len;
+
+ bootpath = get_boot_device_path(i->dev, false, i->suffix);
+ chs_string = g_strdup_printf("%s %" PRIu32 " %" PRIu32 " %" PRIu32,
+ bootpath, i->lcyls, i->lheads, i->lsecs);
+
+ if (total) {
+ list[total - 1] = '\n';
+ }
+ len = strlen(chs_string) + 1;
+ list = g_realloc(list, total + len);
+ memcpy(&list[total], chs_string, len);
+ total += len;
+ g_free(chs_string);
+ g_free(bootpath);
+ }
+
+ *size = total;
+
+ return list;
+}
diff --git a/softmmu/device_tree.c b/softmmu/device_tree.c
new file mode 100644
index 0000000..b335dae
--- /dev/null
+++ b/softmmu/device_tree.c
@@ -0,0 +1,579 @@
+/*
+ * Functions to help device tree manipulation using libfdt.
+ * It also provides functions to read entries from device tree proc
+ * interface.
+ *
+ * Copyright 2008 IBM Corporation.
+ * Authors: Jerone Young <jyoung5@us.ibm.com>
+ * Hollis Blanchard <hollisb@us.ibm.com>
+ *
+ * This work is licensed under the GNU GPL license version 2 or later.
+ *
+ */
+
+#include "qemu/osdep.h"
+
+#ifdef CONFIG_LINUX
+#include <dirent.h>
+#endif
+
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/bswap.h"
+#include "sysemu/device_tree.h"
+#include "sysemu/sysemu.h"
+#include "hw/loader.h"
+#include "hw/boards.h"
+#include "qemu/config-file.h"
+
+#include <libfdt.h>
+
+#define FDT_MAX_SIZE 0x100000
+
+void *create_device_tree(int *sizep)
+{
+ void *fdt;
+ int ret;
+
+ *sizep = FDT_MAX_SIZE;
+ fdt = g_malloc0(FDT_MAX_SIZE);
+ ret = fdt_create(fdt, FDT_MAX_SIZE);
+ if (ret < 0) {
+ goto fail;
+ }
+ ret = fdt_finish_reservemap(fdt);
+ if (ret < 0) {
+ goto fail;
+ }
+ ret = fdt_begin_node(fdt, "");
+ if (ret < 0) {
+ goto fail;
+ }
+ ret = fdt_end_node(fdt);
+ if (ret < 0) {
+ goto fail;
+ }
+ ret = fdt_finish(fdt);
+ if (ret < 0) {
+ goto fail;
+ }
+ ret = fdt_open_into(fdt, fdt, *sizep);
+ if (ret) {
+ error_report("Unable to copy device tree in memory");
+ exit(1);
+ }
+
+ return fdt;
+fail:
+ error_report("%s Couldn't create dt: %s", __func__, fdt_strerror(ret));
+ exit(1);
+}
+
+void *load_device_tree(const char *filename_path, int *sizep)
+{
+ int dt_size;
+ int dt_file_load_size;
+ int ret;
+ void *fdt = NULL;
+
+ *sizep = 0;
+ dt_size = get_image_size(filename_path);
+ if (dt_size < 0) {
+ error_report("Unable to get size of device tree file '%s'",
+ filename_path);
+ goto fail;
+ }
+ if (dt_size > INT_MAX / 2 - 10000) {
+ error_report("Device tree file '%s' is too large", filename_path);
+ goto fail;
+ }
+
+ /* Expand to 2x size to give enough room for manipulation. */
+ dt_size += 10000;
+ dt_size *= 2;
+ /* First allocate space in qemu for device tree */
+ fdt = g_malloc0(dt_size);
+
+ dt_file_load_size = load_image_size(filename_path, fdt, dt_size);
+ if (dt_file_load_size < 0) {
+ error_report("Unable to open device tree file '%s'",
+ filename_path);
+ goto fail;
+ }
+
+ ret = fdt_open_into(fdt, fdt, dt_size);
+ if (ret) {
+ error_report("Unable to copy device tree in memory");
+ goto fail;
+ }
+
+ /* Check sanity of device tree */
+ if (fdt_check_header(fdt)) {
+ error_report("Device tree file loaded into memory is invalid: %s",
+ filename_path);
+ goto fail;
+ }
+ *sizep = dt_size;
+ return fdt;
+
+fail:
+ g_free(fdt);
+ return NULL;
+}
+
+#ifdef CONFIG_LINUX
+
+#define SYSFS_DT_BASEDIR "/proc/device-tree"
+
+/**
+ * read_fstree: this function is inspired from dtc read_fstree
+ * @fdt: preallocated fdt blob buffer, to be populated
+ * @dirname: directory to scan under SYSFS_DT_BASEDIR
+ * the search is recursive and the tree is searched down to the
+ * leaves (property files).
+ *
+ * the function asserts in case of error
+ */
+static void read_fstree(void *fdt, const char *dirname)
+{
+ DIR *d;
+ struct dirent *de;
+ struct stat st;
+ const char *root_dir = SYSFS_DT_BASEDIR;
+ const char *parent_node;
+
+ if (strstr(dirname, root_dir) != dirname) {
+ error_report("%s: %s must be searched within %s",
+ __func__, dirname, root_dir);
+ exit(1);
+ }
+ parent_node = &dirname[strlen(SYSFS_DT_BASEDIR)];
+
+ d = opendir(dirname);
+ if (!d) {
+ error_report("%s cannot open %s", __func__, dirname);
+ exit(1);
+ }
+
+ while ((de = readdir(d)) != NULL) {
+ char *tmpnam;
+
+ if (!g_strcmp0(de->d_name, ".")
+ || !g_strcmp0(de->d_name, "..")) {
+ continue;
+ }
+
+ tmpnam = g_strdup_printf("%s/%s", dirname, de->d_name);
+
+ if (lstat(tmpnam, &st) < 0) {
+ error_report("%s cannot lstat %s", __func__, tmpnam);
+ exit(1);
+ }
+
+ if (S_ISREG(st.st_mode)) {
+ gchar *val;
+ gsize len;
+
+ if (!g_file_get_contents(tmpnam, &val, &len, NULL)) {
+ error_report("%s not able to extract info from %s",
+ __func__, tmpnam);
+ exit(1);
+ }
+
+ if (strlen(parent_node) > 0) {
+ qemu_fdt_setprop(fdt, parent_node,
+ de->d_name, val, len);
+ } else {
+ qemu_fdt_setprop(fdt, "/", de->d_name, val, len);
+ }
+ g_free(val);
+ } else if (S_ISDIR(st.st_mode)) {
+ char *node_name;
+
+ node_name = g_strdup_printf("%s/%s",
+ parent_node, de->d_name);
+ qemu_fdt_add_subnode(fdt, node_name);
+ g_free(node_name);
+ read_fstree(fdt, tmpnam);
+ }
+
+ g_free(tmpnam);
+ }
+
+ closedir(d);
+}
+
+/* load_device_tree_from_sysfs: extract the dt blob from host sysfs */
+void *load_device_tree_from_sysfs(void)
+{
+ void *host_fdt;
+ int host_fdt_size;
+
+ host_fdt = create_device_tree(&host_fdt_size);
+ read_fstree(host_fdt, SYSFS_DT_BASEDIR);
+ if (fdt_check_header(host_fdt)) {
+ error_report("%s host device tree extracted into memory is invalid",
+ __func__);
+ exit(1);
+ }
+ return host_fdt;
+}
+
+#endif /* CONFIG_LINUX */
+
+static int findnode_nofail(void *fdt, const char *node_path)
+{
+ int offset;
+
+ offset = fdt_path_offset(fdt, node_path);
+ if (offset < 0) {
+ error_report("%s Couldn't find node %s: %s", __func__, node_path,
+ fdt_strerror(offset));
+ exit(1);
+ }
+
+ return offset;
+}
+
+char **qemu_fdt_node_unit_path(void *fdt, const char *name, Error **errp)
+{
+ char *prefix = g_strdup_printf("%s@", name);
+ unsigned int path_len = 16, n = 0;
+ GSList *path_list = NULL, *iter;
+ const char *iter_name;
+ int offset, len, ret;
+ char **path_array;
+
+ offset = fdt_next_node(fdt, -1, NULL);
+
+ while (offset >= 0) {
+ iter_name = fdt_get_name(fdt, offset, &len);
+ if (!iter_name) {
+ offset = len;
+ break;
+ }
+ if (!strcmp(iter_name, name) || g_str_has_prefix(iter_name, prefix)) {
+ char *path;
+
+ path = g_malloc(path_len);
+ while ((ret = fdt_get_path(fdt, offset, path, path_len))
+ == -FDT_ERR_NOSPACE) {
+ path_len += 16;
+ path = g_realloc(path, path_len);
+ }
+ path_list = g_slist_prepend(path_list, path);
+ n++;
+ }
+ offset = fdt_next_node(fdt, offset, NULL);
+ }
+ g_free(prefix);
+
+ if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
+ error_setg(errp, "%s: abort parsing dt for %s node units: %s",
+ __func__, name, fdt_strerror(offset));
+ for (iter = path_list; iter; iter = iter->next) {
+ g_free(iter->data);
+ }
+ g_slist_free(path_list);
+ return NULL;
+ }
+
+ path_array = g_new(char *, n + 1);
+ path_array[n--] = NULL;
+
+ for (iter = path_list; iter; iter = iter->next) {
+ path_array[n--] = iter->data;
+ }
+
+ g_slist_free(path_list);
+
+ return path_array;
+}
+
+char **qemu_fdt_node_path(void *fdt, const char *name, const char *compat,
+ Error **errp)
+{
+ int offset, len, ret;
+ const char *iter_name;
+ unsigned int path_len = 16, n = 0;
+ GSList *path_list = NULL, *iter;
+ char **path_array;
+
+ offset = fdt_node_offset_by_compatible(fdt, -1, compat);
+
+ while (offset >= 0) {
+ iter_name = fdt_get_name(fdt, offset, &len);
+ if (!iter_name) {
+ offset = len;
+ break;
+ }
+ if (!name || !strcmp(iter_name, name)) {
+ char *path;
+
+ path = g_malloc(path_len);
+ while ((ret = fdt_get_path(fdt, offset, path, path_len))
+ == -FDT_ERR_NOSPACE) {
+ path_len += 16;
+ path = g_realloc(path, path_len);
+ }
+ path_list = g_slist_prepend(path_list, path);
+ n++;
+ }
+ offset = fdt_node_offset_by_compatible(fdt, offset, compat);
+ }
+
+ if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
+ error_setg(errp, "%s: abort parsing dt for %s/%s: %s",
+ __func__, name, compat, fdt_strerror(offset));
+ for (iter = path_list; iter; iter = iter->next) {
+ g_free(iter->data);
+ }
+ g_slist_free(path_list);
+ return NULL;
+ }
+
+ path_array = g_new(char *, n + 1);
+ path_array[n--] = NULL;
+
+ for (iter = path_list; iter; iter = iter->next) {
+ path_array[n--] = iter->data;
+ }
+
+ g_slist_free(path_list);
+
+ return path_array;
+}
+
+int qemu_fdt_setprop(void *fdt, const char *node_path,
+ const char *property, const void *val, int size)
+{
+ int r;
+
+ r = fdt_setprop(fdt, findnode_nofail(fdt, node_path), property, val, size);
+ if (r < 0) {
+ error_report("%s: Couldn't set %s/%s: %s", __func__, node_path,
+ property, fdt_strerror(r));
+ exit(1);
+ }
+
+ return r;
+}
+
+int qemu_fdt_setprop_cell(void *fdt, const char *node_path,
+ const char *property, uint32_t val)
+{
+ int r;
+
+ r = fdt_setprop_cell(fdt, findnode_nofail(fdt, node_path), property, val);
+ if (r < 0) {
+ error_report("%s: Couldn't set %s/%s = %#08x: %s", __func__,
+ node_path, property, val, fdt_strerror(r));
+ exit(1);
+ }
+
+ return r;
+}
+
+int qemu_fdt_setprop_u64(void *fdt, const char *node_path,
+ const char *property, uint64_t val)
+{
+ val = cpu_to_be64(val);
+ return qemu_fdt_setprop(fdt, node_path, property, &val, sizeof(val));
+}
+
+int qemu_fdt_setprop_string(void *fdt, const char *node_path,
+ const char *property, const char *string)
+{
+ int r;
+
+ r = fdt_setprop_string(fdt, findnode_nofail(fdt, node_path), property, string);
+ if (r < 0) {
+ error_report("%s: Couldn't set %s/%s = %s: %s", __func__,
+ node_path, property, string, fdt_strerror(r));
+ exit(1);
+ }
+
+ return r;
+}
+
+const void *qemu_fdt_getprop(void *fdt, const char *node_path,
+ const char *property, int *lenp, Error **errp)
+{
+ int len;
+ const void *r;
+
+ if (!lenp) {
+ lenp = &len;
+ }
+ r = fdt_getprop(fdt, findnode_nofail(fdt, node_path), property, lenp);
+ if (!r) {
+ error_setg(errp, "%s: Couldn't get %s/%s: %s", __func__,
+ node_path, property, fdt_strerror(*lenp));
+ }
+ return r;
+}
+
+uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
+ const char *property, int *lenp, Error **errp)
+{
+ int len;
+ const uint32_t *p;
+
+ if (!lenp) {
+ lenp = &len;
+ }
+ p = qemu_fdt_getprop(fdt, node_path, property, lenp, errp);
+ if (!p) {
+ return 0;
+ } else if (*lenp != 4) {
+ error_setg(errp, "%s: %s/%s not 4 bytes long (not a cell?)",
+ __func__, node_path, property);
+ *lenp = -EINVAL;
+ return 0;
+ }
+ return be32_to_cpu(*p);
+}
+
+uint32_t qemu_fdt_get_phandle(void *fdt, const char *path)
+{
+ uint32_t r;
+
+ r = fdt_get_phandle(fdt, findnode_nofail(fdt, path));
+ if (r == 0) {
+ error_report("%s: Couldn't get phandle for %s: %s", __func__,
+ path, fdt_strerror(r));
+ exit(1);
+ }
+
+ return r;
+}
+
+int qemu_fdt_setprop_phandle(void *fdt, const char *node_path,
+ const char *property,
+ const char *target_node_path)
+{
+ uint32_t phandle = qemu_fdt_get_phandle(fdt, target_node_path);
+ return qemu_fdt_setprop_cell(fdt, node_path, property, phandle);
+}
+
+uint32_t qemu_fdt_alloc_phandle(void *fdt)
+{
+ static int phandle = 0x0;
+
+ /*
+ * We need to find out if the user gave us special instruction at
+ * which phandle id to start allocating phandles.
+ */
+ if (!phandle) {
+ phandle = machine_phandle_start(current_machine);
+ }
+
+ if (!phandle) {
+ /*
+ * None or invalid phandle given on the command line, so fall back to
+ * default starting point.
+ */
+ phandle = 0x8000;
+ }
+
+ return phandle++;
+}
+
+int qemu_fdt_nop_node(void *fdt, const char *node_path)
+{
+ int r;
+
+ r = fdt_nop_node(fdt, findnode_nofail(fdt, node_path));
+ if (r < 0) {
+ error_report("%s: Couldn't nop node %s: %s", __func__, node_path,
+ fdt_strerror(r));
+ exit(1);
+ }
+
+ return r;
+}
+
+int qemu_fdt_add_subnode(void *fdt, const char *name)
+{
+ char *dupname = g_strdup(name);
+ char *basename = strrchr(dupname, '/');
+ int retval;
+ int parent = 0;
+
+ if (!basename) {
+ g_free(dupname);
+ return -1;
+ }
+
+ basename[0] = '\0';
+ basename++;
+
+ if (dupname[0]) {
+ parent = findnode_nofail(fdt, dupname);
+ }
+
+ retval = fdt_add_subnode(fdt, parent, basename);
+ if (retval < 0) {
+ error_report("FDT: Failed to create subnode %s: %s", name,
+ fdt_strerror(retval));
+ exit(1);
+ }
+
+ g_free(dupname);
+ return retval;
+}
+
+void qemu_fdt_dumpdtb(void *fdt, int size)
+{
+ const char *dumpdtb = qemu_opt_get(qemu_get_machine_opts(), "dumpdtb");
+
+ if (dumpdtb) {
+ /* Dump the dtb to a file and quit */
+ if (g_file_set_contents(dumpdtb, fdt, size, NULL)) {
+ info_report("dtb dumped to %s. Exiting.", dumpdtb);
+ exit(0);
+ }
+ error_report("%s: Failed dumping dtb to %s", __func__, dumpdtb);
+ exit(1);
+ }
+}
+
+int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
+ const char *node_path,
+ const char *property,
+ int numvalues,
+ uint64_t *values)
+{
+ uint32_t *propcells;
+ uint64_t value;
+ int cellnum, vnum, ncells;
+ uint32_t hival;
+ int ret;
+
+ propcells = g_new0(uint32_t, numvalues * 2);
+
+ cellnum = 0;
+ for (vnum = 0; vnum < numvalues; vnum++) {
+ ncells = values[vnum * 2];
+ if (ncells != 1 && ncells != 2) {
+ ret = -1;
+ goto out;
+ }
+ value = values[vnum * 2 + 1];
+ hival = cpu_to_be32(value >> 32);
+ if (ncells > 1) {
+ propcells[cellnum++] = hival;
+ } else if (hival != 0) {
+ ret = -1;
+ goto out;
+ }
+ propcells[cellnum++] = cpu_to_be32(value);
+ }
+
+ ret = qemu_fdt_setprop(fdt, node_path, property, propcells,
+ cellnum * sizeof(uint32_t));
+out:
+ g_free(propcells);
+ return ret;
+}
diff --git a/softmmu/dma-helpers.c b/softmmu/dma-helpers.c
new file mode 100644
index 0000000..03c92e0
--- /dev/null
+++ b/softmmu/dma-helpers.c
@@ -0,0 +1,331 @@
+/*
+ * DMA helper functions
+ *
+ * Copyright (c) 2009 Red Hat
+ *
+ * This work is licensed under the terms of the GNU General Public License
+ * (GNU GPL), version 2 or later.
+ */
+
+#include "qemu/osdep.h"
+#include "sysemu/block-backend.h"
+#include "sysemu/dma.h"
+#include "trace/trace-root.h"
+#include "qemu/thread.h"
+#include "qemu/main-loop.h"
+#include "sysemu/cpu-timers.h"
+#include "qemu/range.h"
+
+/* #define DEBUG_IOMMU */
+
+int dma_memory_set(AddressSpace *as, dma_addr_t addr, uint8_t c, dma_addr_t len)
+{
+ dma_barrier(as, DMA_DIRECTION_FROM_DEVICE);
+
+#define FILLBUF_SIZE 512
+ uint8_t fillbuf[FILLBUF_SIZE];
+ int l;
+ bool error = false;
+
+ memset(fillbuf, c, FILLBUF_SIZE);
+ while (len > 0) {
+ l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
+ error |= address_space_write(as, addr, MEMTXATTRS_UNSPECIFIED,
+ fillbuf, l);
+ len -= l;
+ addr += l;
+ }
+
+ return error;
+}
+
+void qemu_sglist_init(QEMUSGList *qsg, DeviceState *dev, int alloc_hint,
+ AddressSpace *as)
+{
+ qsg->sg = g_malloc(alloc_hint * sizeof(ScatterGatherEntry));
+ qsg->nsg = 0;
+ qsg->nalloc = alloc_hint;
+ qsg->size = 0;
+ qsg->as = as;
+ qsg->dev = dev;
+ object_ref(OBJECT(dev));
+}
+
+void qemu_sglist_add(QEMUSGList *qsg, dma_addr_t base, dma_addr_t len)
+{
+ if (qsg->nsg == qsg->nalloc) {
+ qsg->nalloc = 2 * qsg->nalloc + 1;
+ qsg->sg = g_realloc(qsg->sg, qsg->nalloc * sizeof(ScatterGatherEntry));
+ }
+ qsg->sg[qsg->nsg].base = base;
+ qsg->sg[qsg->nsg].len = len;
+ qsg->size += len;
+ ++qsg->nsg;
+}
+
+void qemu_sglist_destroy(QEMUSGList *qsg)
+{
+ object_unref(OBJECT(qsg->dev));
+ g_free(qsg->sg);
+ memset(qsg, 0, sizeof(*qsg));
+}
+
+typedef struct {
+ BlockAIOCB common;
+ AioContext *ctx;
+ BlockAIOCB *acb;
+ QEMUSGList *sg;
+ uint32_t align;
+ uint64_t offset;
+ DMADirection dir;
+ int sg_cur_index;
+ dma_addr_t sg_cur_byte;
+ QEMUIOVector iov;
+ QEMUBH *bh;
+ DMAIOFunc *io_func;
+ void *io_func_opaque;
+} DMAAIOCB;
+
+static void dma_blk_cb(void *opaque, int ret);
+
+static void reschedule_dma(void *opaque)
+{
+ DMAAIOCB *dbs = (DMAAIOCB *)opaque;
+
+ assert(!dbs->acb && dbs->bh);
+ qemu_bh_delete(dbs->bh);
+ dbs->bh = NULL;
+ dma_blk_cb(dbs, 0);
+}
+
+static void dma_blk_unmap(DMAAIOCB *dbs)
+{
+ int i;
+
+ for (i = 0; i < dbs->iov.niov; ++i) {
+ dma_memory_unmap(dbs->sg->as, dbs->iov.iov[i].iov_base,
+ dbs->iov.iov[i].iov_len, dbs->dir,
+ dbs->iov.iov[i].iov_len);
+ }
+ qemu_iovec_reset(&dbs->iov);
+}
+
+static void dma_complete(DMAAIOCB *dbs, int ret)
+{
+ trace_dma_complete(dbs, ret, dbs->common.cb);
+
+ assert(!dbs->acb && !dbs->bh);
+ dma_blk_unmap(dbs);
+ if (dbs->common.cb) {
+ dbs->common.cb(dbs->common.opaque, ret);
+ }
+ qemu_iovec_destroy(&dbs->iov);
+ qemu_aio_unref(dbs);
+}
+
+static void dma_blk_cb(void *opaque, int ret)
+{
+ DMAAIOCB *dbs = (DMAAIOCB *)opaque;
+ dma_addr_t cur_addr, cur_len;
+ void *mem;
+
+ trace_dma_blk_cb(dbs, ret);
+
+ dbs->acb = NULL;
+ dbs->offset += dbs->iov.size;
+
+ if (dbs->sg_cur_index == dbs->sg->nsg || ret < 0) {
+ dma_complete(dbs, ret);
+ return;
+ }
+ dma_blk_unmap(dbs);
+
+ while (dbs->sg_cur_index < dbs->sg->nsg) {
+ cur_addr = dbs->sg->sg[dbs->sg_cur_index].base + dbs->sg_cur_byte;
+ cur_len = dbs->sg->sg[dbs->sg_cur_index].len - dbs->sg_cur_byte;
+ mem = dma_memory_map(dbs->sg->as, cur_addr, &cur_len, dbs->dir);
+ /*
+ * Make reads deterministic in icount mode. Windows sometimes issues
+ * disk read requests with overlapping SGs. It leads
+ * to non-determinism, because resulting buffer contents may be mixed
+ * from several sectors. This code splits all SGs into several
+ * groups. SGs in every group do not overlap.
+ */
+ if (mem && icount_enabled() && dbs->dir == DMA_DIRECTION_FROM_DEVICE) {
+ int i;
+ for (i = 0 ; i < dbs->iov.niov ; ++i) {
+ if (ranges_overlap((intptr_t)dbs->iov.iov[i].iov_base,
+ dbs->iov.iov[i].iov_len, (intptr_t)mem,
+ cur_len)) {
+ dma_memory_unmap(dbs->sg->as, mem, cur_len,
+ dbs->dir, cur_len);
+ mem = NULL;
+ break;
+ }
+ }
+ }
+ if (!mem)
+ break;
+ qemu_iovec_add(&dbs->iov, mem, cur_len);
+ dbs->sg_cur_byte += cur_len;
+ if (dbs->sg_cur_byte == dbs->sg->sg[dbs->sg_cur_index].len) {
+ dbs->sg_cur_byte = 0;
+ ++dbs->sg_cur_index;
+ }
+ }
+
+ if (dbs->iov.size == 0) {
+ trace_dma_map_wait(dbs);
+ dbs->bh = aio_bh_new(dbs->ctx, reschedule_dma, dbs);
+ cpu_register_map_client(dbs->bh);
+ return;
+ }
+
+ if (!QEMU_IS_ALIGNED(dbs->iov.size, dbs->align)) {
+ qemu_iovec_discard_back(&dbs->iov,
+ QEMU_ALIGN_DOWN(dbs->iov.size, dbs->align));
+ }
+
+ aio_context_acquire(dbs->ctx);
+ dbs->acb = dbs->io_func(dbs->offset, &dbs->iov,
+ dma_blk_cb, dbs, dbs->io_func_opaque);
+ aio_context_release(dbs->ctx);
+ assert(dbs->acb);
+}
+
+static void dma_aio_cancel(BlockAIOCB *acb)
+{
+ DMAAIOCB *dbs = container_of(acb, DMAAIOCB, common);
+
+ trace_dma_aio_cancel(dbs);
+
+ assert(!(dbs->acb && dbs->bh));
+ if (dbs->acb) {
+ /* This will invoke dma_blk_cb. */
+ blk_aio_cancel_async(dbs->acb);
+ return;
+ }
+
+ if (dbs->bh) {
+ cpu_unregister_map_client(dbs->bh);
+ qemu_bh_delete(dbs->bh);
+ dbs->bh = NULL;
+ }
+ if (dbs->common.cb) {
+ dbs->common.cb(dbs->common.opaque, -ECANCELED);
+ }
+}
+
+static AioContext *dma_get_aio_context(BlockAIOCB *acb)
+{
+ DMAAIOCB *dbs = container_of(acb, DMAAIOCB, common);
+
+ return dbs->ctx;
+}
+
+static const AIOCBInfo dma_aiocb_info = {
+ .aiocb_size = sizeof(DMAAIOCB),
+ .cancel_async = dma_aio_cancel,
+ .get_aio_context = dma_get_aio_context,
+};
+
+BlockAIOCB *dma_blk_io(AioContext *ctx,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ DMAIOFunc *io_func, void *io_func_opaque,
+ BlockCompletionFunc *cb,
+ void *opaque, DMADirection dir)
+{
+ DMAAIOCB *dbs = qemu_aio_get(&dma_aiocb_info, NULL, cb, opaque);
+
+ trace_dma_blk_io(dbs, io_func_opaque, offset, (dir == DMA_DIRECTION_TO_DEVICE));
+
+ dbs->acb = NULL;
+ dbs->sg = sg;
+ dbs->ctx = ctx;
+ dbs->offset = offset;
+ dbs->align = align;
+ dbs->sg_cur_index = 0;
+ dbs->sg_cur_byte = 0;
+ dbs->dir = dir;
+ dbs->io_func = io_func;
+ dbs->io_func_opaque = io_func_opaque;
+ dbs->bh = NULL;
+ qemu_iovec_init(&dbs->iov, sg->nsg);
+ dma_blk_cb(dbs, 0);
+ return &dbs->common;
+}
+
+
+static
+BlockAIOCB *dma_blk_read_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb, void *cb_opaque,
+ void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_preadv(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_read(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io(blk_get_aio_context(blk), sg, offset, align,
+ dma_blk_read_io_func, blk, cb, opaque,
+ DMA_DIRECTION_FROM_DEVICE);
+}
+
+static
+BlockAIOCB *dma_blk_write_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb, void *cb_opaque,
+ void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_pwritev(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_write(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io(blk_get_aio_context(blk), sg, offset, align,
+ dma_blk_write_io_func, blk, cb, opaque,
+ DMA_DIRECTION_TO_DEVICE);
+}
+
+
+static uint64_t dma_buf_rw(uint8_t *ptr, int32_t len, QEMUSGList *sg,
+ DMADirection dir)
+{
+ uint64_t resid;
+ int sg_cur_index;
+
+ resid = sg->size;
+ sg_cur_index = 0;
+ len = MIN(len, resid);
+ while (len > 0) {
+ ScatterGatherEntry entry = sg->sg[sg_cur_index++];
+ int32_t xfer = MIN(len, entry.len);
+ dma_memory_rw(sg->as, entry.base, ptr, xfer, dir);
+ ptr += xfer;
+ len -= xfer;
+ resid -= xfer;
+ }
+
+ return resid;
+}
+
+uint64_t dma_buf_read(uint8_t *ptr, int32_t len, QEMUSGList *sg)
+{
+ return dma_buf_rw(ptr, len, sg, DMA_DIRECTION_FROM_DEVICE);
+}
+
+uint64_t dma_buf_write(uint8_t *ptr, int32_t len, QEMUSGList *sg)
+{
+ return dma_buf_rw(ptr, len, sg, DMA_DIRECTION_TO_DEVICE);
+}
+
+void dma_acct_start(BlockBackend *blk, BlockAcctCookie *cookie,
+ QEMUSGList *sg, enum BlockAcctType type)
+{
+ block_acct_start(blk_get_stats(blk), cookie, sg->size, type);
+}
diff --git a/softmmu/meson.build b/softmmu/meson.build
index 36c96e7..8f7210b 100644
--- a/softmmu/meson.build
+++ b/softmmu/meson.build
@@ -3,6 +3,7 @@ specific_ss.add(when: 'CONFIG_SOFTMMU', if_true: [files(
'balloon.c',
'cpus.c',
'cpu-throttle.c',
+ 'physmem.c',
'ioport.c',
'memory.c',
'memory_mapping.c',
@@ -14,3 +15,13 @@ specific_ss.add(when: 'CONFIG_SOFTMMU', if_true: [files(
specific_ss.add(when: ['CONFIG_SOFTMMU', 'CONFIG_TCG'], if_true: [files(
'icount.c'
)])
+
+softmmu_ss.add(files(
+ 'bootdevice.c',
+ 'dma-helpers.c',
+ 'qdev-monitor.c',
+), sdl, libpmem, libdaxctl)
+
+softmmu_ss.add(when: 'CONFIG_TPM', if_true: files('tpm.c'))
+softmmu_ss.add(when: 'CONFIG_SECCOMP', if_true: [files('qemu-seccomp.c'), seccomp])
+softmmu_ss.add(when: fdt, if_true: files('device_tree.c'))
diff --git a/softmmu/physmem.c b/softmmu/physmem.c
new file mode 100644
index 0000000..e319fb2
--- /dev/null
+++ b/softmmu/physmem.c
@@ -0,0 +1,3711 @@
+/*
+ * RAM allocation and memory access
+ *
+ * Copyright (c) 2003 Fabrice Bellard
+ *
+ * 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 "qemu/osdep.h"
+#include "qemu-common.h"
+#include "qapi/error.h"
+
+#include "qemu/cutils.h"
+#include "cpu.h"
+#include "exec/exec-all.h"
+#include "exec/target_page.h"
+#include "tcg/tcg.h"
+#include "hw/qdev-core.h"
+#include "hw/qdev-properties.h"
+#include "hw/boards.h"
+#include "hw/xen/xen.h"
+#include "sysemu/kvm.h"
+#include "sysemu/sysemu.h"
+#include "sysemu/tcg.h"
+#include "sysemu/qtest.h"
+#include "qemu/timer.h"
+#include "qemu/config-file.h"
+#include "qemu/error-report.h"
+#include "qemu/qemu-print.h"
+#include "exec/memory.h"
+#include "exec/ioport.h"
+#include "sysemu/dma.h"
+#include "sysemu/hostmem.h"
+#include "sysemu/hw_accel.h"
+#include "exec/address-spaces.h"
+#include "sysemu/xen-mapcache.h"
+#include "trace/trace-root.h"
+
+#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
+#include <linux/falloc.h>
+#endif
+
+#include "qemu/rcu_queue.h"
+#include "qemu/main-loop.h"
+#include "translate-all.h"
+#include "sysemu/replay.h"
+
+#include "exec/memory-internal.h"
+#include "exec/ram_addr.h"
+#include "exec/log.h"
+
+#include "qemu/pmem.h"
+
+#include "migration/vmstate.h"
+
+#include "qemu/range.h"
+#ifndef _WIN32
+#include "qemu/mmap-alloc.h"
+#endif
+
+#include "monitor/monitor.h"
+
+#ifdef CONFIG_LIBDAXCTL
+#include <daxctl/libdaxctl.h>
+#endif
+
+//#define DEBUG_SUBPAGE
+
+/* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
+ * are protected by the ramlist lock.
+ */
+RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
+
+static MemoryRegion *system_memory;
+static MemoryRegion *system_io;
+
+AddressSpace address_space_io;
+AddressSpace address_space_memory;
+
+static MemoryRegion io_mem_unassigned;
+
+typedef struct PhysPageEntry PhysPageEntry;
+
+struct PhysPageEntry {
+ /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
+ uint32_t skip : 6;
+ /* index into phys_sections (!skip) or phys_map_nodes (skip) */
+ uint32_t ptr : 26;
+};
+
+#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
+
+/* Size of the L2 (and L3, etc) page tables. */
+#define ADDR_SPACE_BITS 64
+
+#define P_L2_BITS 9
+#define P_L2_SIZE (1 << P_L2_BITS)
+
+#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
+
+typedef PhysPageEntry Node[P_L2_SIZE];
+
+typedef struct PhysPageMap {
+ struct rcu_head rcu;
+
+ unsigned sections_nb;
+ unsigned sections_nb_alloc;
+ unsigned nodes_nb;
+ unsigned nodes_nb_alloc;
+ Node *nodes;
+ MemoryRegionSection *sections;
+} PhysPageMap;
+
+struct AddressSpaceDispatch {
+ MemoryRegionSection *mru_section;
+ /* This is a multi-level map on the physical address space.
+ * The bottom level has pointers to MemoryRegionSections.
+ */
+ PhysPageEntry phys_map;
+ PhysPageMap map;
+};
+
+#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
+typedef struct subpage_t {
+ MemoryRegion iomem;
+ FlatView *fv;
+ hwaddr base;
+ uint16_t sub_section[];
+} subpage_t;
+
+#define PHYS_SECTION_UNASSIGNED 0
+
+static void io_mem_init(void);
+static void memory_map_init(void);
+static void tcg_log_global_after_sync(MemoryListener *listener);
+static void tcg_commit(MemoryListener *listener);
+
+/**
+ * CPUAddressSpace: all the information a CPU needs about an AddressSpace
+ * @cpu: the CPU whose AddressSpace this is
+ * @as: the AddressSpace itself
+ * @memory_dispatch: its dispatch pointer (cached, RCU protected)
+ * @tcg_as_listener: listener for tracking changes to the AddressSpace
+ */
+struct CPUAddressSpace {
+ CPUState *cpu;
+ AddressSpace *as;
+ struct AddressSpaceDispatch *memory_dispatch;
+ MemoryListener tcg_as_listener;
+};
+
+struct DirtyBitmapSnapshot {
+ ram_addr_t start;
+ ram_addr_t end;
+ unsigned long dirty[];
+};
+
+static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
+{
+ static unsigned alloc_hint = 16;
+ if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
+ map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
+ map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
+ alloc_hint = map->nodes_nb_alloc;
+ }
+}
+
+static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
+{
+ unsigned i;
+ uint32_t ret;
+ PhysPageEntry e;
+ PhysPageEntry *p;
+
+ ret = map->nodes_nb++;
+ p = map->nodes[ret];
+ assert(ret != PHYS_MAP_NODE_NIL);
+ assert(ret != map->nodes_nb_alloc);
+
+ e.skip = leaf ? 0 : 1;
+ e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
+ for (i = 0; i < P_L2_SIZE; ++i) {
+ memcpy(&p[i], &e, sizeof(e));
+ }
+ return ret;
+}
+
+static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
+ hwaddr *index, uint64_t *nb, uint16_t leaf,
+ int level)
+{
+ PhysPageEntry *p;
+ hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
+
+ if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
+ lp->ptr = phys_map_node_alloc(map, level == 0);
+ }
+ p = map->nodes[lp->ptr];
+ lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
+
+ while (*nb && lp < &p[P_L2_SIZE]) {
+ if ((*index & (step - 1)) == 0 && *nb >= step) {
+ lp->skip = 0;
+ lp->ptr = leaf;
+ *index += step;
+ *nb -= step;
+ } else {
+ phys_page_set_level(map, lp, index, nb, leaf, level - 1);
+ }
+ ++lp;
+ }
+}
+
+static void phys_page_set(AddressSpaceDispatch *d,
+ hwaddr index, uint64_t nb,
+ uint16_t leaf)
+{
+ /* Wildly overreserve - it doesn't matter much. */
+ phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
+
+ phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
+}
+
+/* Compact a non leaf page entry. Simply detect that the entry has a single child,
+ * and update our entry so we can skip it and go directly to the destination.
+ */
+static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
+{
+ unsigned valid_ptr = P_L2_SIZE;
+ int valid = 0;
+ PhysPageEntry *p;
+ int i;
+
+ if (lp->ptr == PHYS_MAP_NODE_NIL) {
+ return;
+ }
+
+ p = nodes[lp->ptr];
+ for (i = 0; i < P_L2_SIZE; i++) {
+ if (p[i].ptr == PHYS_MAP_NODE_NIL) {
+ continue;
+ }
+
+ valid_ptr = i;
+ valid++;
+ if (p[i].skip) {
+ phys_page_compact(&p[i], nodes);
+ }
+ }
+
+ /* We can only compress if there's only one child. */
+ if (valid != 1) {
+ return;
+ }
+
+ assert(valid_ptr < P_L2_SIZE);
+
+ /* Don't compress if it won't fit in the # of bits we have. */
+ if (P_L2_LEVELS >= (1 << 6) &&
+ lp->skip + p[valid_ptr].skip >= (1 << 6)) {
+ return;
+ }
+
+ lp->ptr = p[valid_ptr].ptr;
+ if (!p[valid_ptr].skip) {
+ /* If our only child is a leaf, make this a leaf. */
+ /* By design, we should have made this node a leaf to begin with so we
+ * should never reach here.
+ * But since it's so simple to handle this, let's do it just in case we
+ * change this rule.
+ */
+ lp->skip = 0;
+ } else {
+ lp->skip += p[valid_ptr].skip;
+ }
+}
+
+void address_space_dispatch_compact(AddressSpaceDispatch *d)
+{
+ if (d->phys_map.skip) {
+ phys_page_compact(&d->phys_map, d->map.nodes);
+ }
+}
+
+static inline bool section_covers_addr(const MemoryRegionSection *section,
+ hwaddr addr)
+{
+ /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
+ * the section must cover the entire address space.
+ */
+ return int128_gethi(section->size) ||
+ range_covers_byte(section->offset_within_address_space,
+ int128_getlo(section->size), addr);
+}
+
+static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
+{
+ PhysPageEntry lp = d->phys_map, *p;
+ Node *nodes = d->map.nodes;
+ MemoryRegionSection *sections = d->map.sections;
+ hwaddr index = addr >> TARGET_PAGE_BITS;
+ int i;
+
+ for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
+ if (lp.ptr == PHYS_MAP_NODE_NIL) {
+ return &sections[PHYS_SECTION_UNASSIGNED];
+ }
+ p = nodes[lp.ptr];
+ lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
+ }
+
+ if (section_covers_addr(&sections[lp.ptr], addr)) {
+ return &sections[lp.ptr];
+ } else {
+ return &sections[PHYS_SECTION_UNASSIGNED];
+ }
+}
+
+/* Called from RCU critical section */
+static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
+ hwaddr addr,
+ bool resolve_subpage)
+{
+ MemoryRegionSection *section = qatomic_read(&d->mru_section);
+ subpage_t *subpage;
+
+ if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
+ !section_covers_addr(section, addr)) {
+ section = phys_page_find(d, addr);
+ qatomic_set(&d->mru_section, section);
+ }
+ if (resolve_subpage && section->mr->subpage) {
+ subpage = container_of(section->mr, subpage_t, iomem);
+ section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
+ }
+ return section;
+}
+
+/* Called from RCU critical section */
+static MemoryRegionSection *
+address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
+ hwaddr *plen, bool resolve_subpage)
+{
+ MemoryRegionSection *section;
+ MemoryRegion *mr;
+ Int128 diff;
+
+ section = address_space_lookup_region(d, addr, resolve_subpage);
+ /* Compute offset within MemoryRegionSection */
+ addr -= section->offset_within_address_space;
+
+ /* Compute offset within MemoryRegion */
+ *xlat = addr + section->offset_within_region;
+
+ mr = section->mr;
+
+ /* MMIO registers can be expected to perform full-width accesses based only
+ * on their address, without considering adjacent registers that could
+ * decode to completely different MemoryRegions. When such registers
+ * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
+ * regions overlap wildly. For this reason we cannot clamp the accesses
+ * here.
+ *
+ * If the length is small (as is the case for address_space_ldl/stl),
+ * everything works fine. If the incoming length is large, however,
+ * the caller really has to do the clamping through memory_access_size.
+ */
+ if (memory_region_is_ram(mr)) {
+ diff = int128_sub(section->size, int128_make64(addr));
+ *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
+ }
+ return section;
+}
+
+/**
+ * address_space_translate_iommu - translate an address through an IOMMU
+ * memory region and then through the target address space.
+ *
+ * @iommu_mr: the IOMMU memory region that we start the translation from
+ * @addr: the address to be translated through the MMU
+ * @xlat: the translated address offset within the destination memory region.
+ * It cannot be %NULL.
+ * @plen_out: valid read/write length of the translated address. It
+ * cannot be %NULL.
+ * @page_mask_out: page mask for the translated address. This
+ * should only be meaningful for IOMMU translated
+ * addresses, since there may be huge pages that this bit
+ * would tell. It can be %NULL if we don't care about it.
+ * @is_write: whether the translation operation is for write
+ * @is_mmio: whether this can be MMIO, set true if it can
+ * @target_as: the address space targeted by the IOMMU
+ * @attrs: transaction attributes
+ *
+ * This function is called from RCU critical section. It is the common
+ * part of flatview_do_translate and address_space_translate_cached.
+ */
+static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
+ hwaddr *xlat,
+ hwaddr *plen_out,
+ hwaddr *page_mask_out,
+ bool is_write,
+ bool is_mmio,
+ AddressSpace **target_as,
+ MemTxAttrs attrs)
+{
+ MemoryRegionSection *section;
+ hwaddr page_mask = (hwaddr)-1;
+
+ do {
+ hwaddr addr = *xlat;
+ IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+ int iommu_idx = 0;
+ IOMMUTLBEntry iotlb;
+
+ if (imrc->attrs_to_index) {
+ iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
+ }
+
+ iotlb = imrc->translate(iommu_mr, addr, is_write ?
+ IOMMU_WO : IOMMU_RO, iommu_idx);
+
+ if (!(iotlb.perm & (1 << is_write))) {
+ goto unassigned;
+ }
+
+ addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
+ | (addr & iotlb.addr_mask));
+ page_mask &= iotlb.addr_mask;
+ *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
+ *target_as = iotlb.target_as;
+
+ section = address_space_translate_internal(
+ address_space_to_dispatch(iotlb.target_as), addr, xlat,
+ plen_out, is_mmio);
+
+ iommu_mr = memory_region_get_iommu(section->mr);
+ } while (unlikely(iommu_mr));
+
+ if (page_mask_out) {
+ *page_mask_out = page_mask;
+ }
+ return *section;
+
+unassigned:
+ return (MemoryRegionSection) { .mr = &io_mem_unassigned };
+}
+
+/**
+ * flatview_do_translate - translate an address in FlatView
+ *
+ * @fv: the flat view that we want to translate on
+ * @addr: the address to be translated in above address space
+ * @xlat: the translated address offset within memory region. It
+ * cannot be @NULL.
+ * @plen_out: valid read/write length of the translated address. It
+ * can be @NULL when we don't care about it.
+ * @page_mask_out: page mask for the translated address. This
+ * should only be meaningful for IOMMU translated
+ * addresses, since there may be huge pages that this bit
+ * would tell. It can be @NULL if we don't care about it.
+ * @is_write: whether the translation operation is for write
+ * @is_mmio: whether this can be MMIO, set true if it can
+ * @target_as: the address space targeted by the IOMMU
+ * @attrs: memory transaction attributes
+ *
+ * This function is called from RCU critical section
+ */
+static MemoryRegionSection flatview_do_translate(FlatView *fv,
+ hwaddr addr,
+ hwaddr *xlat,
+ hwaddr *plen_out,
+ hwaddr *page_mask_out,
+ bool is_write,
+ bool is_mmio,
+ AddressSpace **target_as,
+ MemTxAttrs attrs)
+{
+ MemoryRegionSection *section;
+ IOMMUMemoryRegion *iommu_mr;
+ hwaddr plen = (hwaddr)(-1);
+
+ if (!plen_out) {
+ plen_out = &plen;
+ }
+
+ section = address_space_translate_internal(
+ flatview_to_dispatch(fv), addr, xlat,
+ plen_out, is_mmio);
+
+ iommu_mr = memory_region_get_iommu(section->mr);
+ if (unlikely(iommu_mr)) {
+ return address_space_translate_iommu(iommu_mr, xlat,
+ plen_out, page_mask_out,
+ is_write, is_mmio,
+ target_as, attrs);
+ }
+ if (page_mask_out) {
+ /* Not behind an IOMMU, use default page size. */
+ *page_mask_out = ~TARGET_PAGE_MASK;
+ }
+
+ return *section;
+}
+
+/* Called from RCU critical section */
+IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
+ bool is_write, MemTxAttrs attrs)
+{
+ MemoryRegionSection section;
+ hwaddr xlat, page_mask;
+
+ /*
+ * This can never be MMIO, and we don't really care about plen,
+ * but page mask.
+ */
+ section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
+ NULL, &page_mask, is_write, false, &as,
+ attrs);
+
+ /* Illegal translation */
+ if (section.mr == &io_mem_unassigned) {
+ goto iotlb_fail;
+ }
+
+ /* Convert memory region offset into address space offset */
+ xlat += section.offset_within_address_space -
+ section.offset_within_region;
+
+ return (IOMMUTLBEntry) {
+ .target_as = as,
+ .iova = addr & ~page_mask,
+ .translated_addr = xlat & ~page_mask,
+ .addr_mask = page_mask,
+ /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
+ .perm = IOMMU_RW,
+ };
+
+iotlb_fail:
+ return (IOMMUTLBEntry) {0};
+}
+
+/* Called from RCU critical section */
+MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
+ hwaddr *plen, bool is_write,
+ MemTxAttrs attrs)
+{
+ MemoryRegion *mr;
+ MemoryRegionSection section;
+ AddressSpace *as = NULL;
+
+ /* This can be MMIO, so setup MMIO bit. */
+ section = flatview_do_translate(fv, addr, xlat, plen, NULL,
+ is_write, true, &as, attrs);
+ mr = section.mr;
+
+ if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
+ hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
+ *plen = MIN(page, *plen);
+ }
+
+ return mr;
+}
+
+typedef struct TCGIOMMUNotifier {
+ IOMMUNotifier n;
+ MemoryRegion *mr;
+ CPUState *cpu;
+ int iommu_idx;
+ bool active;
+} TCGIOMMUNotifier;
+
+static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
+{
+ TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
+
+ if (!notifier->active) {
+ return;
+ }
+ tlb_flush(notifier->cpu);
+ notifier->active = false;
+ /* We leave the notifier struct on the list to avoid reallocating it later.
+ * Generally the number of IOMMUs a CPU deals with will be small.
+ * In any case we can't unregister the iommu notifier from a notify
+ * callback.
+ */
+}
+
+static void tcg_register_iommu_notifier(CPUState *cpu,
+ IOMMUMemoryRegion *iommu_mr,
+ int iommu_idx)
+{
+ /* Make sure this CPU has an IOMMU notifier registered for this
+ * IOMMU/IOMMU index combination, so that we can flush its TLB
+ * when the IOMMU tells us the mappings we've cached have changed.
+ */
+ MemoryRegion *mr = MEMORY_REGION(iommu_mr);
+ TCGIOMMUNotifier *notifier;
+ int i;
+
+ for (i = 0; i < cpu->iommu_notifiers->len; i++) {
+ notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
+ if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
+ break;
+ }
+ }
+ if (i == cpu->iommu_notifiers->len) {
+ /* Not found, add a new entry at the end of the array */
+ cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
+ notifier = g_new0(TCGIOMMUNotifier, 1);
+ g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
+
+ notifier->mr = mr;
+ notifier->iommu_idx = iommu_idx;
+ notifier->cpu = cpu;
+ /* Rather than trying to register interest in the specific part
+ * of the iommu's address space that we've accessed and then
+ * expand it later as subsequent accesses touch more of it, we
+ * just register interest in the whole thing, on the assumption
+ * that iommu reconfiguration will be rare.
+ */
+ iommu_notifier_init(&notifier->n,
+ tcg_iommu_unmap_notify,
+ IOMMU_NOTIFIER_UNMAP,
+ 0,
+ HWADDR_MAX,
+ iommu_idx);
+ memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
+ &error_fatal);
+ }
+
+ if (!notifier->active) {
+ notifier->active = true;
+ }
+}
+
+void tcg_iommu_free_notifier_list(CPUState *cpu)
+{
+ /* Destroy the CPU's notifier list */
+ int i;
+ TCGIOMMUNotifier *notifier;
+
+ for (i = 0; i < cpu->iommu_notifiers->len; i++) {
+ notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
+ memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
+ g_free(notifier);
+ }
+ g_array_free(cpu->iommu_notifiers, true);
+}
+
+void tcg_iommu_init_notifier_list(CPUState *cpu)
+{
+ cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
+}
+
+/* Called from RCU critical section */
+MemoryRegionSection *
+address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
+ hwaddr *xlat, hwaddr *plen,
+ MemTxAttrs attrs, int *prot)
+{
+ MemoryRegionSection *section;
+ IOMMUMemoryRegion *iommu_mr;
+ IOMMUMemoryRegionClass *imrc;
+ IOMMUTLBEntry iotlb;
+ int iommu_idx;
+ AddressSpaceDispatch *d =
+ qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
+
+ for (;;) {
+ section = address_space_translate_internal(d, addr, &addr, plen, false);
+
+ iommu_mr = memory_region_get_iommu(section->mr);
+ if (!iommu_mr) {
+ break;
+ }
+
+ imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+
+ iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
+ tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
+ /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
+ * doesn't short-cut its translation table walk.
+ */
+ iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
+ addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
+ | (addr & iotlb.addr_mask));
+ /* Update the caller's prot bits to remove permissions the IOMMU
+ * is giving us a failure response for. If we get down to no
+ * permissions left at all we can give up now.
+ */
+ if (!(iotlb.perm & IOMMU_RO)) {
+ *prot &= ~(PAGE_READ | PAGE_EXEC);
+ }
+ if (!(iotlb.perm & IOMMU_WO)) {
+ *prot &= ~PAGE_WRITE;
+ }
+
+ if (!*prot) {
+ goto translate_fail;
+ }
+
+ d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
+ }
+
+ assert(!memory_region_is_iommu(section->mr));
+ *xlat = addr;
+ return section;
+
+translate_fail:
+ return &d->map.sections[PHYS_SECTION_UNASSIGNED];
+}
+
+void cpu_address_space_init(CPUState *cpu, int asidx,
+ const char *prefix, MemoryRegion *mr)
+{
+ CPUAddressSpace *newas;
+ AddressSpace *as = g_new0(AddressSpace, 1);
+ char *as_name;
+
+ assert(mr);
+ as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
+ address_space_init(as, mr, as_name);
+ g_free(as_name);
+
+ /* Target code should have set num_ases before calling us */
+ assert(asidx < cpu->num_ases);
+
+ if (asidx == 0) {
+ /* address space 0 gets the convenience alias */
+ cpu->as = as;
+ }
+
+ /* KVM cannot currently support multiple address spaces. */
+ assert(asidx == 0 || !kvm_enabled());
+
+ if (!cpu->cpu_ases) {
+ cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
+ }
+
+ newas = &cpu->cpu_ases[asidx];
+ newas->cpu = cpu;
+ newas->as = as;
+ if (tcg_enabled()) {
+ newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
+ newas->tcg_as_listener.commit = tcg_commit;
+ memory_listener_register(&newas->tcg_as_listener, as);
+ }
+}
+
+AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
+{
+ /* Return the AddressSpace corresponding to the specified index */
+ return cpu->cpu_ases[asidx].as;
+}
+
+/* Add a watchpoint. */
+int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
+ int flags, CPUWatchpoint **watchpoint)
+{
+ CPUWatchpoint *wp;
+ vaddr in_page;
+
+ /* forbid ranges which are empty or run off the end of the address space */
+ if (len == 0 || (addr + len - 1) < addr) {
+ error_report("tried to set invalid watchpoint at %"
+ VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
+ return -EINVAL;
+ }
+ wp = g_malloc(sizeof(*wp));
+
+ wp->vaddr = addr;
+ wp->len = len;
+ wp->flags = flags;
+
+ /* keep all GDB-injected watchpoints in front */
+ if (flags & BP_GDB) {
+ QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
+ } else {
+ QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
+ }
+
+ in_page = -(addr | TARGET_PAGE_MASK);
+ if (len <= in_page) {
+ tlb_flush_page(cpu, addr);
+ } else {
+ tlb_flush(cpu);
+ }
+
+ if (watchpoint)
+ *watchpoint = wp;
+ return 0;
+}
+
+/* Remove a specific watchpoint. */
+int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
+ int flags)
+{
+ CPUWatchpoint *wp;
+
+ QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
+ if (addr == wp->vaddr && len == wp->len
+ && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
+ cpu_watchpoint_remove_by_ref(cpu, wp);
+ return 0;
+ }
+ }
+ return -ENOENT;
+}
+
+/* Remove a specific watchpoint by reference. */
+void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
+{
+ QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
+
+ tlb_flush_page(cpu, watchpoint->vaddr);
+
+ g_free(watchpoint);
+}
+
+/* Remove all matching watchpoints. */
+void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
+{
+ CPUWatchpoint *wp, *next;
+
+ QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
+ if (wp->flags & mask) {
+ cpu_watchpoint_remove_by_ref(cpu, wp);
+ }
+ }
+}
+
+/* Return true if this watchpoint address matches the specified
+ * access (ie the address range covered by the watchpoint overlaps
+ * partially or completely with the address range covered by the
+ * access).
+ */
+static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
+ vaddr addr, vaddr len)
+{
+ /* We know the lengths are non-zero, but a little caution is
+ * required to avoid errors in the case where the range ends
+ * exactly at the top of the address space and so addr + len
+ * wraps round to zero.
+ */
+ vaddr wpend = wp->vaddr + wp->len - 1;
+ vaddr addrend = addr + len - 1;
+
+ return !(addr > wpend || wp->vaddr > addrend);
+}
+
+/* Return flags for watchpoints that match addr + prot. */
+int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
+{
+ CPUWatchpoint *wp;
+ int ret = 0;
+
+ QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
+ if (watchpoint_address_matches(wp, addr, len)) {
+ ret |= wp->flags;
+ }
+ }
+ return ret;
+}
+
+/* Called from RCU critical section */
+static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
+{
+ RAMBlock *block;
+
+ block = qatomic_rcu_read(&ram_list.mru_block);
+ if (block && addr - block->offset < block->max_length) {
+ return block;
+ }
+ RAMBLOCK_FOREACH(block) {
+ if (addr - block->offset < block->max_length) {
+ goto found;
+ }
+ }
+
+ fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
+ abort();
+
+found:
+ /* It is safe to write mru_block outside the iothread lock. This
+ * is what happens:
+ *
+ * mru_block = xxx
+ * rcu_read_unlock()
+ * xxx removed from list
+ * rcu_read_lock()
+ * read mru_block
+ * mru_block = NULL;
+ * call_rcu(reclaim_ramblock, xxx);
+ * rcu_read_unlock()
+ *
+ * qatomic_rcu_set is not needed here. The block was already published
+ * when it was placed into the list. Here we're just making an extra
+ * copy of the pointer.
+ */
+ ram_list.mru_block = block;
+ return block;
+}
+
+static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
+{
+ CPUState *cpu;
+ ram_addr_t start1;
+ RAMBlock *block;
+ ram_addr_t end;
+
+ assert(tcg_enabled());
+ end = TARGET_PAGE_ALIGN(start + length);
+ start &= TARGET_PAGE_MASK;
+
+ RCU_READ_LOCK_GUARD();
+ block = qemu_get_ram_block(start);
+ assert(block == qemu_get_ram_block(end - 1));
+ start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
+ CPU_FOREACH(cpu) {
+ tlb_reset_dirty(cpu, start1, length);
+ }
+}
+
+/* Note: start and end must be within the same ram block. */
+bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
+ ram_addr_t length,
+ unsigned client)
+{
+ DirtyMemoryBlocks *blocks;
+ unsigned long end, page, start_page;
+ bool dirty = false;
+ RAMBlock *ramblock;
+ uint64_t mr_offset, mr_size;
+
+ if (length == 0) {
+ return false;
+ }
+
+ end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
+ start_page = start >> TARGET_PAGE_BITS;
+ page = start_page;
+
+ WITH_RCU_READ_LOCK_GUARD() {
+ blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
+ ramblock = qemu_get_ram_block(start);
+ /* Range sanity check on the ramblock */
+ assert(start >= ramblock->offset &&
+ start + length <= ramblock->offset + ramblock->used_length);
+
+ while (page < end) {
+ unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
+ unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
+ unsigned long num = MIN(end - page,
+ DIRTY_MEMORY_BLOCK_SIZE - offset);
+
+ dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
+ offset, num);
+ page += num;
+ }
+
+ mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
+ mr_size = (end - start_page) << TARGET_PAGE_BITS;
+ memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
+ }
+
+ if (dirty && tcg_enabled()) {
+ tlb_reset_dirty_range_all(start, length);
+ }
+
+ return dirty;
+}
+
+DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
+ (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
+{
+ DirtyMemoryBlocks *blocks;
+ ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
+ unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
+ ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
+ ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
+ DirtyBitmapSnapshot *snap;
+ unsigned long page, end, dest;
+
+ snap = g_malloc0(sizeof(*snap) +
+ ((last - first) >> (TARGET_PAGE_BITS + 3)));
+ snap->start = first;
+ snap->end = last;
+
+ page = first >> TARGET_PAGE_BITS;
+ end = last >> TARGET_PAGE_BITS;
+ dest = 0;
+
+ WITH_RCU_READ_LOCK_GUARD() {
+ blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
+
+ while (page < end) {
+ unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
+ unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
+ unsigned long num = MIN(end - page,
+ DIRTY_MEMORY_BLOCK_SIZE - offset);
+
+ assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
+ assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
+ offset >>= BITS_PER_LEVEL;
+
+ bitmap_copy_and_clear_atomic(snap->dirty + dest,
+ blocks->blocks[idx] + offset,
+ num);
+ page += num;
+ dest += num >> BITS_PER_LEVEL;
+ }
+ }
+
+ if (tcg_enabled()) {
+ tlb_reset_dirty_range_all(start, length);
+ }
+
+ memory_region_clear_dirty_bitmap(mr, offset, length);
+
+ return snap;
+}
+
+bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
+ ram_addr_t start,
+ ram_addr_t length)
+{
+ unsigned long page, end;
+
+ assert(start >= snap->start);
+ assert(start + length <= snap->end);
+
+ end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
+ page = (start - snap->start) >> TARGET_PAGE_BITS;
+
+ while (page < end) {
+ if (test_bit(page, snap->dirty)) {
+ return true;
+ }
+ page++;
+ }
+ return false;
+}
+
+/* Called from RCU critical section */
+hwaddr memory_region_section_get_iotlb(CPUState *cpu,
+ MemoryRegionSection *section)
+{
+ AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
+ return section - d->map.sections;
+}
+
+static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
+ uint16_t section);
+static subpage_t *subpage_init(FlatView *fv, hwaddr base);
+
+static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
+ qemu_anon_ram_alloc;
+
+/*
+ * Set a custom physical guest memory alloator.
+ * Accelerators with unusual needs may need this. Hopefully, we can
+ * get rid of it eventually.
+ */
+void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
+{
+ phys_mem_alloc = alloc;
+}
+
+static uint16_t phys_section_add(PhysPageMap *map,
+ MemoryRegionSection *section)
+{
+ /* The physical section number is ORed with a page-aligned
+ * pointer to produce the iotlb entries. Thus it should
+ * never overflow into the page-aligned value.
+ */
+ assert(map->sections_nb < TARGET_PAGE_SIZE);
+
+ if (map->sections_nb == map->sections_nb_alloc) {
+ map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
+ map->sections = g_renew(MemoryRegionSection, map->sections,
+ map->sections_nb_alloc);
+ }
+ map->sections[map->sections_nb] = *section;
+ memory_region_ref(section->mr);
+ return map->sections_nb++;
+}
+
+static void phys_section_destroy(MemoryRegion *mr)
+{
+ bool have_sub_page = mr->subpage;
+
+ memory_region_unref(mr);
+
+ if (have_sub_page) {
+ subpage_t *subpage = container_of(mr, subpage_t, iomem);
+ object_unref(OBJECT(&subpage->iomem));
+ g_free(subpage);
+ }
+}
+
+static void phys_sections_free(PhysPageMap *map)
+{
+ while (map->sections_nb > 0) {
+ MemoryRegionSection *section = &map->sections[--map->sections_nb];
+ phys_section_destroy(section->mr);
+ }
+ g_free(map->sections);
+ g_free(map->nodes);
+}
+
+static void register_subpage(FlatView *fv, MemoryRegionSection *section)
+{
+ AddressSpaceDispatch *d = flatview_to_dispatch(fv);
+ subpage_t *subpage;
+ hwaddr base = section->offset_within_address_space
+ & TARGET_PAGE_MASK;
+ MemoryRegionSection *existing = phys_page_find(d, base);
+ MemoryRegionSection subsection = {
+ .offset_within_address_space = base,
+ .size = int128_make64(TARGET_PAGE_SIZE),
+ };
+ hwaddr start, end;
+
+ assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
+
+ if (!(existing->mr->subpage)) {
+ subpage = subpage_init(fv, base);
+ subsection.fv = fv;
+ subsection.mr = &subpage->iomem;
+ phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
+ phys_section_add(&d->map, &subsection));
+ } else {
+ subpage = container_of(existing->mr, subpage_t, iomem);
+ }
+ start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
+ end = start + int128_get64(section->size) - 1;
+ subpage_register(subpage, start, end,
+ phys_section_add(&d->map, section));
+}
+
+
+static void register_multipage(FlatView *fv,
+ MemoryRegionSection *section)
+{
+ AddressSpaceDispatch *d = flatview_to_dispatch(fv);
+ hwaddr start_addr = section->offset_within_address_space;
+ uint16_t section_index = phys_section_add(&d->map, section);
+ uint64_t num_pages = int128_get64(int128_rshift(section->size,
+ TARGET_PAGE_BITS));
+
+ assert(num_pages);
+ phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
+}
+
+/*
+ * The range in *section* may look like this:
+ *
+ * |s|PPPPPPP|s|
+ *
+ * where s stands for subpage and P for page.
+ */
+void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
+{
+ MemoryRegionSection remain = *section;
+ Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
+
+ /* register first subpage */
+ if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
+ uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
+ - remain.offset_within_address_space;
+
+ MemoryRegionSection now = remain;
+ now.size = int128_min(int128_make64(left), now.size);
+ register_subpage(fv, &now);
+ if (int128_eq(remain.size, now.size)) {
+ return;
+ }
+ remain.size = int128_sub(remain.size, now.size);
+ remain.offset_within_address_space += int128_get64(now.size);
+ remain.offset_within_region += int128_get64(now.size);
+ }
+
+ /* register whole pages */
+ if (int128_ge(remain.size, page_size)) {
+ MemoryRegionSection now = remain;
+ now.size = int128_and(now.size, int128_neg(page_size));
+ register_multipage(fv, &now);
+ if (int128_eq(remain.size, now.size)) {
+ return;
+ }
+ remain.size = int128_sub(remain.size, now.size);
+ remain.offset_within_address_space += int128_get64(now.size);
+ remain.offset_within_region += int128_get64(now.size);
+ }
+
+ /* register last subpage */
+ register_subpage(fv, &remain);
+}
+
+void qemu_flush_coalesced_mmio_buffer(void)
+{
+ if (kvm_enabled())
+ kvm_flush_coalesced_mmio_buffer();
+}
+
+void qemu_mutex_lock_ramlist(void)
+{
+ qemu_mutex_lock(&ram_list.mutex);
+}
+
+void qemu_mutex_unlock_ramlist(void)
+{
+ qemu_mutex_unlock(&ram_list.mutex);
+}
+
+void ram_block_dump(Monitor *mon)
+{
+ RAMBlock *block;
+ char *psize;
+
+ RCU_READ_LOCK_GUARD();
+ monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
+ "Block Name", "PSize", "Offset", "Used", "Total");
+ RAMBLOCK_FOREACH(block) {
+ psize = size_to_str(block->page_size);
+ monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
+ " 0x%016" PRIx64 "\n", block->idstr, psize,
+ (uint64_t)block->offset,
+ (uint64_t)block->used_length,
+ (uint64_t)block->max_length);
+ g_free(psize);
+ }
+}
+
+#ifdef __linux__
+/*
+ * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
+ * may or may not name the same files / on the same filesystem now as
+ * when we actually open and map them. Iterate over the file
+ * descriptors instead, and use qemu_fd_getpagesize().
+ */
+static int find_min_backend_pagesize(Object *obj, void *opaque)
+{
+ long *hpsize_min = opaque;
+
+ if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
+ HostMemoryBackend *backend = MEMORY_BACKEND(obj);
+ long hpsize = host_memory_backend_pagesize(backend);
+
+ if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
+ *hpsize_min = hpsize;
+ }
+ }
+
+ return 0;
+}
+
+static int find_max_backend_pagesize(Object *obj, void *opaque)
+{
+ long *hpsize_max = opaque;
+
+ if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
+ HostMemoryBackend *backend = MEMORY_BACKEND(obj);
+ long hpsize = host_memory_backend_pagesize(backend);
+
+ if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
+ *hpsize_max = hpsize;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * TODO: We assume right now that all mapped host memory backends are
+ * used as RAM, however some might be used for different purposes.
+ */
+long qemu_minrampagesize(void)
+{
+ long hpsize = LONG_MAX;
+ Object *memdev_root = object_resolve_path("/objects", NULL);
+
+ object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
+ return hpsize;
+}
+
+long qemu_maxrampagesize(void)
+{
+ long pagesize = 0;
+ Object *memdev_root = object_resolve_path("/objects", NULL);
+
+ object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
+ return pagesize;
+}
+#else
+long qemu_minrampagesize(void)
+{
+ return qemu_real_host_page_size;
+}
+long qemu_maxrampagesize(void)
+{
+ return qemu_real_host_page_size;
+}
+#endif
+
+#ifdef CONFIG_POSIX
+static int64_t get_file_size(int fd)
+{
+ int64_t size;
+#if defined(__linux__)
+ struct stat st;
+
+ if (fstat(fd, &st) < 0) {
+ return -errno;
+ }
+
+ /* Special handling for devdax character devices */
+ if (S_ISCHR(st.st_mode)) {
+ g_autofree char *subsystem_path = NULL;
+ g_autofree char *subsystem = NULL;
+
+ subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
+ major(st.st_rdev), minor(st.st_rdev));
+ subsystem = g_file_read_link(subsystem_path, NULL);
+
+ if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
+ g_autofree char *size_path = NULL;
+ g_autofree char *size_str = NULL;
+
+ size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
+ major(st.st_rdev), minor(st.st_rdev));
+
+ if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
+ return g_ascii_strtoll(size_str, NULL, 0);
+ }
+ }
+ }
+#endif /* defined(__linux__) */
+
+ /* st.st_size may be zero for special files yet lseek(2) works */
+ size = lseek(fd, 0, SEEK_END);
+ if (size < 0) {
+ return -errno;
+ }
+ return size;
+}
+
+static int64_t get_file_align(int fd)
+{
+ int64_t align = -1;
+#if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
+ struct stat st;
+
+ if (fstat(fd, &st) < 0) {
+ return -errno;
+ }
+
+ /* Special handling for devdax character devices */
+ if (S_ISCHR(st.st_mode)) {
+ g_autofree char *path = NULL;
+ g_autofree char *rpath = NULL;
+ struct daxctl_ctx *ctx;
+ struct daxctl_region *region;
+ int rc = 0;
+
+ path = g_strdup_printf("/sys/dev/char/%d:%d",
+ major(st.st_rdev), minor(st.st_rdev));
+ rpath = realpath(path, NULL);
+
+ rc = daxctl_new(&ctx);
+ if (rc) {
+ return -1;
+ }
+
+ daxctl_region_foreach(ctx, region) {
+ if (strstr(rpath, daxctl_region_get_path(region))) {
+ align = daxctl_region_get_align(region);
+ break;
+ }
+ }
+ daxctl_unref(ctx);
+ }
+#endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
+
+ return align;
+}
+
+static int file_ram_open(const char *path,
+ const char *region_name,
+ bool *created,
+ Error **errp)
+{
+ char *filename;
+ char *sanitized_name;
+ char *c;
+ int fd = -1;
+
+ *created = false;
+ for (;;) {
+ fd = open(path, O_RDWR);
+ if (fd >= 0) {
+ /* @path names an existing file, use it */
+ break;
+ }
+ if (errno == ENOENT) {
+ /* @path names a file that doesn't exist, create it */
+ fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
+ if (fd >= 0) {
+ *created = true;
+ break;
+ }
+ } else if (errno == EISDIR) {
+ /* @path names a directory, create a file there */
+ /* Make name safe to use with mkstemp by replacing '/' with '_'. */
+ sanitized_name = g_strdup(region_name);
+ for (c = sanitized_name; *c != '\0'; c++) {
+ if (*c == '/') {
+ *c = '_';
+ }
+ }
+
+ filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
+ sanitized_name);
+ g_free(sanitized_name);
+
+ fd = mkstemp(filename);
+ if (fd >= 0) {
+ unlink(filename);
+ g_free(filename);
+ break;
+ }
+ g_free(filename);
+ }
+ if (errno != EEXIST && errno != EINTR) {
+ error_setg_errno(errp, errno,
+ "can't open backing store %s for guest RAM",
+ path);
+ return -1;
+ }
+ /*
+ * Try again on EINTR and EEXIST. The latter happens when
+ * something else creates the file between our two open().
+ */
+ }
+
+ return fd;
+}
+
+static void *file_ram_alloc(RAMBlock *block,
+ ram_addr_t memory,
+ int fd,
+ bool truncate,
+ Error **errp)
+{
+ void *area;
+
+ block->page_size = qemu_fd_getpagesize(fd);
+ if (block->mr->align % block->page_size) {
+ error_setg(errp, "alignment 0x%" PRIx64
+ " must be multiples of page size 0x%zx",
+ block->mr->align, block->page_size);
+ return NULL;
+ } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
+ error_setg(errp, "alignment 0x%" PRIx64
+ " must be a power of two", block->mr->align);
+ return NULL;
+ }
+ block->mr->align = MAX(block->page_size, block->mr->align);
+#if defined(__s390x__)
+ if (kvm_enabled()) {
+ block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
+ }
+#endif
+
+ if (memory < block->page_size) {
+ error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
+ "or larger than page size 0x%zx",
+ memory, block->page_size);
+ return NULL;
+ }
+
+ memory = ROUND_UP(memory, block->page_size);
+
+ /*
+ * ftruncate is not supported by hugetlbfs in older
+ * hosts, so don't bother bailing out on errors.
+ * If anything goes wrong with it under other filesystems,
+ * mmap will fail.
+ *
+ * Do not truncate the non-empty backend file to avoid corrupting
+ * the existing data in the file. Disabling shrinking is not
+ * enough. For example, the current vNVDIMM implementation stores
+ * the guest NVDIMM labels at the end of the backend file. If the
+ * backend file is later extended, QEMU will not be able to find
+ * those labels. Therefore, extending the non-empty backend file
+ * is disabled as well.
+ */
+ if (truncate && ftruncate(fd, memory)) {
+ perror("ftruncate");
+ }
+
+ area = qemu_ram_mmap(fd, memory, block->mr->align,
+ block->flags & RAM_SHARED, block->flags & RAM_PMEM);
+ if (area == MAP_FAILED) {
+ error_setg_errno(errp, errno,
+ "unable to map backing store for guest RAM");
+ return NULL;
+ }
+
+ block->fd = fd;
+ return area;
+}
+#endif
+
+/* Allocate space within the ram_addr_t space that governs the
+ * dirty bitmaps.
+ * Called with the ramlist lock held.
+ */
+static ram_addr_t find_ram_offset(ram_addr_t size)
+{
+ RAMBlock *block, *next_block;
+ ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
+
+ assert(size != 0); /* it would hand out same offset multiple times */
+
+ if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
+ return 0;
+ }
+
+ RAMBLOCK_FOREACH(block) {
+ ram_addr_t candidate, next = RAM_ADDR_MAX;
+
+ /* Align blocks to start on a 'long' in the bitmap
+ * which makes the bitmap sync'ing take the fast path.
+ */
+ candidate = block->offset + block->max_length;
+ candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
+
+ /* Search for the closest following block
+ * and find the gap.
+ */
+ RAMBLOCK_FOREACH(next_block) {
+ if (next_block->offset >= candidate) {
+ next = MIN(next, next_block->offset);
+ }
+ }
+
+ /* If it fits remember our place and remember the size
+ * of gap, but keep going so that we might find a smaller
+ * gap to fill so avoiding fragmentation.
+ */
+ if (next - candidate >= size && next - candidate < mingap) {
+ offset = candidate;
+ mingap = next - candidate;
+ }
+
+ trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
+ }
+
+ if (offset == RAM_ADDR_MAX) {
+ fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
+ (uint64_t)size);
+ abort();
+ }
+
+ trace_find_ram_offset(size, offset);
+
+ return offset;
+}
+
+static unsigned long last_ram_page(void)
+{
+ RAMBlock *block;
+ ram_addr_t last = 0;
+
+ RCU_READ_LOCK_GUARD();
+ RAMBLOCK_FOREACH(block) {
+ last = MAX(last, block->offset + block->max_length);
+ }
+ return last >> TARGET_PAGE_BITS;
+}
+
+static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
+{
+ int ret;
+
+ /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
+ if (!machine_dump_guest_core(current_machine)) {
+ ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
+ if (ret) {
+ perror("qemu_madvise");
+ fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
+ "but dump_guest_core=off specified\n");
+ }
+ }
+}
+
+const char *qemu_ram_get_idstr(RAMBlock *rb)
+{
+ return rb->idstr;
+}
+
+void *qemu_ram_get_host_addr(RAMBlock *rb)
+{
+ return rb->host;
+}
+
+ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
+{
+ return rb->offset;
+}
+
+ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
+{
+ return rb->used_length;
+}
+
+bool qemu_ram_is_shared(RAMBlock *rb)
+{
+ return rb->flags & RAM_SHARED;
+}
+
+/* Note: Only set at the start of postcopy */
+bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
+{
+ return rb->flags & RAM_UF_ZEROPAGE;
+}
+
+void qemu_ram_set_uf_zeroable(RAMBlock *rb)
+{
+ rb->flags |= RAM_UF_ZEROPAGE;
+}
+
+bool qemu_ram_is_migratable(RAMBlock *rb)
+{
+ return rb->flags & RAM_MIGRATABLE;
+}
+
+void qemu_ram_set_migratable(RAMBlock *rb)
+{
+ rb->flags |= RAM_MIGRATABLE;
+}
+
+void qemu_ram_unset_migratable(RAMBlock *rb)
+{
+ rb->flags &= ~RAM_MIGRATABLE;
+}
+
+/* Called with iothread lock held. */
+void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
+{
+ RAMBlock *block;
+
+ assert(new_block);
+ assert(!new_block->idstr[0]);
+
+ if (dev) {
+ char *id = qdev_get_dev_path(dev);
+ if (id) {
+ snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
+ g_free(id);
+ }
+ }
+ pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
+
+ RCU_READ_LOCK_GUARD();
+ RAMBLOCK_FOREACH(block) {
+ if (block != new_block &&
+ !strcmp(block->idstr, new_block->idstr)) {
+ fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
+ new_block->idstr);
+ abort();
+ }
+ }
+}
+
+/* Called with iothread lock held. */
+void qemu_ram_unset_idstr(RAMBlock *block)
+{
+ /* FIXME: arch_init.c assumes that this is not called throughout
+ * migration. Ignore the problem since hot-unplug during migration
+ * does not work anyway.
+ */
+ if (block) {
+ memset(block->idstr, 0, sizeof(block->idstr));
+ }
+}
+
+size_t qemu_ram_pagesize(RAMBlock *rb)
+{
+ return rb->page_size;
+}
+
+/* Returns the largest size of page in use */
+size_t qemu_ram_pagesize_largest(void)
+{
+ RAMBlock *block;
+ size_t largest = 0;
+
+ RAMBLOCK_FOREACH(block) {
+ largest = MAX(largest, qemu_ram_pagesize(block));
+ }
+
+ return largest;
+}
+
+static int memory_try_enable_merging(void *addr, size_t len)
+{
+ if (!machine_mem_merge(current_machine)) {
+ /* disabled by the user */
+ return 0;
+ }
+
+ return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
+}
+
+/* Only legal before guest might have detected the memory size: e.g. on
+ * incoming migration, or right after reset.
+ *
+ * As memory core doesn't know how is memory accessed, it is up to
+ * resize callback to update device state and/or add assertions to detect
+ * misuse, if necessary.
+ */
+int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
+{
+ const ram_addr_t unaligned_size = newsize;
+
+ assert(block);
+
+ newsize = HOST_PAGE_ALIGN(newsize);
+
+ if (block->used_length == newsize) {
+ /*
+ * We don't have to resize the ram block (which only knows aligned
+ * sizes), however, we have to notify if the unaligned size changed.
+ */
+ if (unaligned_size != memory_region_size(block->mr)) {
+ memory_region_set_size(block->mr, unaligned_size);
+ if (block->resized) {
+ block->resized(block->idstr, unaligned_size, block->host);
+ }
+ }
+ return 0;
+ }
+
+ if (!(block->flags & RAM_RESIZEABLE)) {
+ error_setg_errno(errp, EINVAL,
+ "Length mismatch: %s: 0x" RAM_ADDR_FMT
+ " in != 0x" RAM_ADDR_FMT, block->idstr,
+ newsize, block->used_length);
+ return -EINVAL;
+ }
+
+ if (block->max_length < newsize) {
+ error_setg_errno(errp, EINVAL,
+ "Length too large: %s: 0x" RAM_ADDR_FMT
+ " > 0x" RAM_ADDR_FMT, block->idstr,
+ newsize, block->max_length);
+ return -EINVAL;
+ }
+
+ cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
+ block->used_length = newsize;
+ cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
+ DIRTY_CLIENTS_ALL);
+ memory_region_set_size(block->mr, unaligned_size);
+ if (block->resized) {
+ block->resized(block->idstr, unaligned_size, block->host);
+ }
+ return 0;
+}
+
+/*
+ * Trigger sync on the given ram block for range [start, start + length]
+ * with the backing store if one is available.
+ * Otherwise no-op.
+ * @Note: this is supposed to be a synchronous op.
+ */
+void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
+{
+ /* The requested range should fit in within the block range */
+ g_assert((start + length) <= block->used_length);
+
+#ifdef CONFIG_LIBPMEM
+ /* The lack of support for pmem should not block the sync */
+ if (ramblock_is_pmem(block)) {
+ void *addr = ramblock_ptr(block, start);
+ pmem_persist(addr, length);
+ return;
+ }
+#endif
+ if (block->fd >= 0) {
+ /**
+ * Case there is no support for PMEM or the memory has not been
+ * specified as persistent (or is not one) - use the msync.
+ * Less optimal but still achieves the same goal
+ */
+ void *addr = ramblock_ptr(block, start);
+ if (qemu_msync(addr, length, block->fd)) {
+ warn_report("%s: failed to sync memory range: start: "
+ RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
+ __func__, start, length);
+ }
+ }
+}
+
+/* Called with ram_list.mutex held */
+static void dirty_memory_extend(ram_addr_t old_ram_size,
+ ram_addr_t new_ram_size)
+{
+ ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
+ DIRTY_MEMORY_BLOCK_SIZE);
+ ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
+ DIRTY_MEMORY_BLOCK_SIZE);
+ int i;
+
+ /* Only need to extend if block count increased */
+ if (new_num_blocks <= old_num_blocks) {
+ return;
+ }
+
+ for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
+ DirtyMemoryBlocks *old_blocks;
+ DirtyMemoryBlocks *new_blocks;
+ int j;
+
+ old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
+ new_blocks = g_malloc(sizeof(*new_blocks) +
+ sizeof(new_blocks->blocks[0]) * new_num_blocks);
+
+ if (old_num_blocks) {
+ memcpy(new_blocks->blocks, old_blocks->blocks,
+ old_num_blocks * sizeof(old_blocks->blocks[0]));
+ }
+
+ for (j = old_num_blocks; j < new_num_blocks; j++) {
+ new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
+ }
+
+ qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
+
+ if (old_blocks) {
+ g_free_rcu(old_blocks, rcu);
+ }
+ }
+}
+
+static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
+{
+ RAMBlock *block;
+ RAMBlock *last_block = NULL;
+ ram_addr_t old_ram_size, new_ram_size;
+ Error *err = NULL;
+
+ old_ram_size = last_ram_page();
+
+ qemu_mutex_lock_ramlist();
+ new_block->offset = find_ram_offset(new_block->max_length);
+
+ if (!new_block->host) {
+ if (xen_enabled()) {
+ xen_ram_alloc(new_block->offset, new_block->max_length,
+ new_block->mr, &err);
+ if (err) {
+ error_propagate(errp, err);
+ qemu_mutex_unlock_ramlist();
+ return;
+ }
+ } else {
+ new_block->host = phys_mem_alloc(new_block->max_length,
+ &new_block->mr->align, shared);
+ if (!new_block->host) {
+ error_setg_errno(errp, errno,
+ "cannot set up guest memory '%s'",
+ memory_region_name(new_block->mr));
+ qemu_mutex_unlock_ramlist();
+ return;
+ }
+ memory_try_enable_merging(new_block->host, new_block->max_length);
+ }
+ }
+
+ new_ram_size = MAX(old_ram_size,
+ (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
+ if (new_ram_size > old_ram_size) {
+ dirty_memory_extend(old_ram_size, new_ram_size);
+ }
+ /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
+ * QLIST (which has an RCU-friendly variant) does not have insertion at
+ * tail, so save the last element in last_block.
+ */
+ RAMBLOCK_FOREACH(block) {
+ last_block = block;
+ if (block->max_length < new_block->max_length) {
+ break;
+ }
+ }
+ if (block) {
+ QLIST_INSERT_BEFORE_RCU(block, new_block, next);
+ } else if (last_block) {
+ QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
+ } else { /* list is empty */
+ QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
+ }
+ ram_list.mru_block = NULL;
+
+ /* Write list before version */
+ smp_wmb();
+ ram_list.version++;
+ qemu_mutex_unlock_ramlist();
+
+ cpu_physical_memory_set_dirty_range(new_block->offset,
+ new_block->used_length,
+ DIRTY_CLIENTS_ALL);
+
+ if (new_block->host) {
+ qemu_ram_setup_dump(new_block->host, new_block->max_length);
+ qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
+ /*
+ * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
+ * Configure it unless the machine is a qtest server, in which case
+ * KVM is not used and it may be forked (eg for fuzzing purposes).
+ */
+ if (!qtest_enabled()) {
+ qemu_madvise(new_block->host, new_block->max_length,
+ QEMU_MADV_DONTFORK);
+ }
+ ram_block_notify_add(new_block->host, new_block->max_length);
+ }
+}
+
+#ifdef CONFIG_POSIX
+RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
+ uint32_t ram_flags, int fd,
+ Error **errp)
+{
+ RAMBlock *new_block;
+ Error *local_err = NULL;
+ int64_t file_size, file_align;
+
+ /* Just support these ram flags by now. */
+ assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
+
+ if (xen_enabled()) {
+ error_setg(errp, "-mem-path not supported with Xen");
+ return NULL;
+ }
+
+ if (kvm_enabled() && !kvm_has_sync_mmu()) {
+ error_setg(errp,
+ "host lacks kvm mmu notifiers, -mem-path unsupported");
+ return NULL;
+ }
+
+ if (phys_mem_alloc != qemu_anon_ram_alloc) {
+ /*
+ * file_ram_alloc() needs to allocate just like
+ * phys_mem_alloc, but we haven't bothered to provide
+ * a hook there.
+ */
+ error_setg(errp,
+ "-mem-path not supported with this accelerator");
+ return NULL;
+ }
+
+ size = HOST_PAGE_ALIGN(size);
+ file_size = get_file_size(fd);
+ if (file_size > 0 && file_size < size) {
+ error_setg(errp, "backing store size 0x%" PRIx64
+ " does not match 'size' option 0x" RAM_ADDR_FMT,
+ file_size, size);
+ return NULL;
+ }
+
+ file_align = get_file_align(fd);
+ if (file_align > 0 && mr && file_align > mr->align) {
+ error_setg(errp, "backing store align 0x%" PRIx64
+ " is larger than 'align' option 0x%" PRIx64,
+ file_align, mr->align);
+ return NULL;
+ }
+
+ new_block = g_malloc0(sizeof(*new_block));
+ new_block->mr = mr;
+ new_block->used_length = size;
+ new_block->max_length = size;
+ new_block->flags = ram_flags;
+ new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
+ if (!new_block->host) {
+ g_free(new_block);
+ return NULL;
+ }
+
+ ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
+ if (local_err) {
+ g_free(new_block);
+ error_propagate(errp, local_err);
+ return NULL;
+ }
+ return new_block;
+
+}
+
+
+RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
+ uint32_t ram_flags, const char *mem_path,
+ Error **errp)
+{
+ int fd;
+ bool created;
+ RAMBlock *block;
+
+ fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
+ if (fd < 0) {
+ return NULL;
+ }
+
+ block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, errp);
+ if (!block) {
+ if (created) {
+ unlink(mem_path);
+ }
+ close(fd);
+ return NULL;
+ }
+
+ return block;
+}
+#endif
+
+static
+RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
+ void (*resized)(const char*,
+ uint64_t length,
+ void *host),
+ void *host, bool resizeable, bool share,
+ MemoryRegion *mr, Error **errp)
+{
+ RAMBlock *new_block;
+ Error *local_err = NULL;
+
+ size = HOST_PAGE_ALIGN(size);
+ max_size = HOST_PAGE_ALIGN(max_size);
+ new_block = g_malloc0(sizeof(*new_block));
+ new_block->mr = mr;
+ new_block->resized = resized;
+ new_block->used_length = size;
+ new_block->max_length = max_size;
+ assert(max_size >= size);
+ new_block->fd = -1;
+ new_block->page_size = qemu_real_host_page_size;
+ new_block->host = host;
+ if (host) {
+ new_block->flags |= RAM_PREALLOC;
+ }
+ if (resizeable) {
+ new_block->flags |= RAM_RESIZEABLE;
+ }
+ ram_block_add(new_block, &local_err, share);
+ if (local_err) {
+ g_free(new_block);
+ error_propagate(errp, local_err);
+ return NULL;
+ }
+ return new_block;
+}
+
+RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
+ MemoryRegion *mr, Error **errp)
+{
+ return qemu_ram_alloc_internal(size, size, NULL, host, false,
+ false, mr, errp);
+}
+
+RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
+ MemoryRegion *mr, Error **errp)
+{
+ return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
+ share, mr, errp);
+}
+
+RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
+ void (*resized)(const char*,
+ uint64_t length,
+ void *host),
+ MemoryRegion *mr, Error **errp)
+{
+ return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
+ false, mr, errp);
+}
+
+static void reclaim_ramblock(RAMBlock *block)
+{
+ if (block->flags & RAM_PREALLOC) {
+ ;
+ } else if (xen_enabled()) {
+ xen_invalidate_map_cache_entry(block->host);
+#ifndef _WIN32
+ } else if (block->fd >= 0) {
+ qemu_ram_munmap(block->fd, block->host, block->max_length);
+ close(block->fd);
+#endif
+ } else {
+ qemu_anon_ram_free(block->host, block->max_length);
+ }
+ g_free(block);
+}
+
+void qemu_ram_free(RAMBlock *block)
+{
+ if (!block) {
+ return;
+ }
+
+ if (block->host) {
+ ram_block_notify_remove(block->host, block->max_length);
+ }
+
+ qemu_mutex_lock_ramlist();
+ QLIST_REMOVE_RCU(block, next);
+ ram_list.mru_block = NULL;
+ /* Write list before version */
+ smp_wmb();
+ ram_list.version++;
+ call_rcu(block, reclaim_ramblock, rcu);
+ qemu_mutex_unlock_ramlist();
+}
+
+#ifndef _WIN32
+void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
+{
+ RAMBlock *block;
+ ram_addr_t offset;
+ int flags;
+ void *area, *vaddr;
+
+ RAMBLOCK_FOREACH(block) {
+ offset = addr - block->offset;
+ if (offset < block->max_length) {
+ vaddr = ramblock_ptr(block, offset);
+ if (block->flags & RAM_PREALLOC) {
+ ;
+ } else if (xen_enabled()) {
+ abort();
+ } else {
+ flags = MAP_FIXED;
+ if (block->fd >= 0) {
+ flags |= (block->flags & RAM_SHARED ?
+ MAP_SHARED : MAP_PRIVATE);
+ area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
+ flags, block->fd, offset);
+ } else {
+ /*
+ * Remap needs to match alloc. Accelerators that
+ * set phys_mem_alloc never remap. If they did,
+ * we'd need a remap hook here.
+ */
+ assert(phys_mem_alloc == qemu_anon_ram_alloc);
+
+ flags |= MAP_PRIVATE | MAP_ANONYMOUS;
+ area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
+ flags, -1, 0);
+ }
+ if (area != vaddr) {
+ error_report("Could not remap addr: "
+ RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
+ length, addr);
+ exit(1);
+ }
+ memory_try_enable_merging(vaddr, length);
+ qemu_ram_setup_dump(vaddr, length);
+ }
+ }
+ }
+}
+#endif /* !_WIN32 */
+
+/* Return a host pointer to ram allocated with qemu_ram_alloc.
+ * This should not be used for general purpose DMA. Use address_space_map
+ * or address_space_rw instead. For local memory (e.g. video ram) that the
+ * device owns, use memory_region_get_ram_ptr.
+ *
+ * Called within RCU critical section.
+ */
+void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
+{
+ RAMBlock *block = ram_block;
+
+ if (block == NULL) {
+ block = qemu_get_ram_block(addr);
+ addr -= block->offset;
+ }
+
+ if (xen_enabled() && block->host == NULL) {
+ /* We need to check if the requested address is in the RAM
+ * because we don't want to map the entire memory in QEMU.
+ * In that case just map until the end of the page.
+ */
+ if (block->offset == 0) {
+ return xen_map_cache(addr, 0, 0, false);
+ }
+
+ block->host = xen_map_cache(block->offset, block->max_length, 1, false);
+ }
+ return ramblock_ptr(block, addr);
+}
+
+/* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
+ * but takes a size argument.
+ *
+ * Called within RCU critical section.
+ */
+static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
+ hwaddr *size, bool lock)
+{
+ RAMBlock *block = ram_block;
+ if (*size == 0) {
+ return NULL;
+ }
+
+ if (block == NULL) {
+ block = qemu_get_ram_block(addr);
+ addr -= block->offset;
+ }
+ *size = MIN(*size, block->max_length - addr);
+
+ if (xen_enabled() && block->host == NULL) {
+ /* We need to check if the requested address is in the RAM
+ * because we don't want to map the entire memory in QEMU.
+ * In that case just map the requested area.
+ */
+ if (block->offset == 0) {
+ return xen_map_cache(addr, *size, lock, lock);
+ }
+
+ block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
+ }
+
+ return ramblock_ptr(block, addr);
+}
+
+/* Return the offset of a hostpointer within a ramblock */
+ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
+{
+ ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
+ assert((uintptr_t)host >= (uintptr_t)rb->host);
+ assert(res < rb->max_length);
+
+ return res;
+}
+
+/*
+ * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
+ * in that RAMBlock.
+ *
+ * ptr: Host pointer to look up
+ * round_offset: If true round the result offset down to a page boundary
+ * *ram_addr: set to result ram_addr
+ * *offset: set to result offset within the RAMBlock
+ *
+ * Returns: RAMBlock (or NULL if not found)
+ *
+ * By the time this function returns, the returned pointer is not protected
+ * by RCU anymore. If the caller is not within an RCU critical section and
+ * does not hold the iothread lock, it must have other means of protecting the
+ * pointer, such as a reference to the region that includes the incoming
+ * ram_addr_t.
+ */
+RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
+ ram_addr_t *offset)
+{
+ RAMBlock *block;
+ uint8_t *host = ptr;
+
+ if (xen_enabled()) {
+ ram_addr_t ram_addr;
+ RCU_READ_LOCK_GUARD();
+ ram_addr = xen_ram_addr_from_mapcache(ptr);
+ block = qemu_get_ram_block(ram_addr);
+ if (block) {
+ *offset = ram_addr - block->offset;
+ }
+ return block;
+ }
+
+ RCU_READ_LOCK_GUARD();
+ block = qatomic_rcu_read(&ram_list.mru_block);
+ if (block && block->host && host - block->host < block->max_length) {
+ goto found;
+ }
+
+ RAMBLOCK_FOREACH(block) {
+ /* This case append when the block is not mapped. */
+ if (block->host == NULL) {
+ continue;
+ }
+ if (host - block->host < block->max_length) {
+ goto found;
+ }
+ }
+
+ return NULL;
+
+found:
+ *offset = (host - block->host);
+ if (round_offset) {
+ *offset &= TARGET_PAGE_MASK;
+ }
+ return block;
+}
+
+/*
+ * Finds the named RAMBlock
+ *
+ * name: The name of RAMBlock to find
+ *
+ * Returns: RAMBlock (or NULL if not found)
+ */
+RAMBlock *qemu_ram_block_by_name(const char *name)
+{
+ RAMBlock *block;
+
+ RAMBLOCK_FOREACH(block) {
+ if (!strcmp(name, block->idstr)) {
+ return block;
+ }
+ }
+
+ return NULL;
+}
+
+/* Some of the softmmu routines need to translate from a host pointer
+ (typically a TLB entry) back to a ram offset. */
+ram_addr_t qemu_ram_addr_from_host(void *ptr)
+{
+ RAMBlock *block;
+ ram_addr_t offset;
+
+ block = qemu_ram_block_from_host(ptr, false, &offset);
+ if (!block) {
+ return RAM_ADDR_INVALID;
+ }
+
+ return block->offset + offset;
+}
+
+/* Generate a debug exception if a watchpoint has been hit. */
+void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
+ MemTxAttrs attrs, int flags, uintptr_t ra)
+{
+ CPUClass *cc = CPU_GET_CLASS(cpu);
+ CPUWatchpoint *wp;
+
+ assert(tcg_enabled());
+ if (cpu->watchpoint_hit) {
+ /*
+ * We re-entered the check after replacing the TB.
+ * Now raise the debug interrupt so that it will
+ * trigger after the current instruction.
+ */
+ qemu_mutex_lock_iothread();
+ cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
+ qemu_mutex_unlock_iothread();
+ return;
+ }
+
+ addr = cc->adjust_watchpoint_address(cpu, addr, len);
+ QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
+ if (watchpoint_address_matches(wp, addr, len)
+ && (wp->flags & flags)) {
+ if (replay_running_debug()) {
+ /*
+ * Don't process the watchpoints when we are
+ * in a reverse debugging operation.
+ */
+ replay_breakpoint();
+ return;
+ }
+ if (flags == BP_MEM_READ) {
+ wp->flags |= BP_WATCHPOINT_HIT_READ;
+ } else {
+ wp->flags |= BP_WATCHPOINT_HIT_WRITE;
+ }
+ wp->hitaddr = MAX(addr, wp->vaddr);
+ wp->hitattrs = attrs;
+ if (!cpu->watchpoint_hit) {
+ if (wp->flags & BP_CPU &&
+ !cc->debug_check_watchpoint(cpu, wp)) {
+ wp->flags &= ~BP_WATCHPOINT_HIT;
+ continue;
+ }
+ cpu->watchpoint_hit = wp;
+
+ mmap_lock();
+ tb_check_watchpoint(cpu, ra);
+ if (wp->flags & BP_STOP_BEFORE_ACCESS) {
+ cpu->exception_index = EXCP_DEBUG;
+ mmap_unlock();
+ cpu_loop_exit_restore(cpu, ra);
+ } else {
+ /* Force execution of one insn next time. */
+ cpu->cflags_next_tb = 1 | curr_cflags();
+ mmap_unlock();
+ if (ra) {
+ cpu_restore_state(cpu, ra, true);
+ }
+ cpu_loop_exit_noexc(cpu);
+ }
+ }
+ } else {
+ wp->flags &= ~BP_WATCHPOINT_HIT;
+ }
+ }
+}
+
+static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
+ MemTxAttrs attrs, void *buf, hwaddr len);
+static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
+ const void *buf, hwaddr len);
+static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
+ bool is_write, MemTxAttrs attrs);
+
+static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
+ unsigned len, MemTxAttrs attrs)
+{
+ subpage_t *subpage = opaque;
+ uint8_t buf[8];
+ MemTxResult res;
+
+#if defined(DEBUG_SUBPAGE)
+ printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
+ subpage, len, addr);
+#endif
+ res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
+ if (res) {
+ return res;
+ }
+ *data = ldn_p(buf, len);
+ return MEMTX_OK;
+}
+
+static MemTxResult subpage_write(void *opaque, hwaddr addr,
+ uint64_t value, unsigned len, MemTxAttrs attrs)
+{
+ subpage_t *subpage = opaque;
+ uint8_t buf[8];
+
+#if defined(DEBUG_SUBPAGE)
+ printf("%s: subpage %p len %u addr " TARGET_FMT_plx
+ " value %"PRIx64"\n",
+ __func__, subpage, len, addr, value);
+#endif
+ stn_p(buf, len, value);
+ return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
+}
+
+static bool subpage_accepts(void *opaque, hwaddr addr,
+ unsigned len, bool is_write,
+ MemTxAttrs attrs)
+{
+ subpage_t *subpage = opaque;
+#if defined(DEBUG_SUBPAGE)
+ printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
+ __func__, subpage, is_write ? 'w' : 'r', len, addr);
+#endif
+
+ return flatview_access_valid(subpage->fv, addr + subpage->base,
+ len, is_write, attrs);
+}
+
+static const MemoryRegionOps subpage_ops = {
+ .read_with_attrs = subpage_read,
+ .write_with_attrs = subpage_write,
+ .impl.min_access_size = 1,
+ .impl.max_access_size = 8,
+ .valid.min_access_size = 1,
+ .valid.max_access_size = 8,
+ .valid.accepts = subpage_accepts,
+ .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
+ uint16_t section)
+{
+ int idx, eidx;
+
+ if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
+ return -1;
+ idx = SUBPAGE_IDX(start);
+ eidx = SUBPAGE_IDX(end);
+#if defined(DEBUG_SUBPAGE)
+ printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
+ __func__, mmio, start, end, idx, eidx, section);
+#endif
+ for (; idx <= eidx; idx++) {
+ mmio->sub_section[idx] = section;
+ }
+
+ return 0;
+}
+
+static subpage_t *subpage_init(FlatView *fv, hwaddr base)
+{
+ subpage_t *mmio;
+
+ /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
+ mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
+ mmio->fv = fv;
+ mmio->base = base;
+ memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
+ NULL, TARGET_PAGE_SIZE);
+ mmio->iomem.subpage = true;
+#if defined(DEBUG_SUBPAGE)
+ printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
+ mmio, base, TARGET_PAGE_SIZE);
+#endif
+
+ return mmio;
+}
+
+static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
+{
+ assert(fv);
+ MemoryRegionSection section = {
+ .fv = fv,
+ .mr = mr,
+ .offset_within_address_space = 0,
+ .offset_within_region = 0,
+ .size = int128_2_64(),
+ };
+
+ return phys_section_add(map, &section);
+}
+
+MemoryRegionSection *iotlb_to_section(CPUState *cpu,
+ hwaddr index, MemTxAttrs attrs)
+{
+ int asidx = cpu_asidx_from_attrs(cpu, attrs);
+ CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
+ AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
+ MemoryRegionSection *sections = d->map.sections;
+
+ return &sections[index & ~TARGET_PAGE_MASK];
+}
+
+static void io_mem_init(void)
+{
+ memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
+ NULL, UINT64_MAX);
+}
+
+AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
+{
+ AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
+ uint16_t n;
+
+ n = dummy_section(&d->map, fv, &io_mem_unassigned);
+ assert(n == PHYS_SECTION_UNASSIGNED);
+
+ d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
+
+ return d;
+}
+
+void address_space_dispatch_free(AddressSpaceDispatch *d)
+{
+ phys_sections_free(&d->map);
+ g_free(d);
+}
+
+static void do_nothing(CPUState *cpu, run_on_cpu_data d)
+{
+}
+
+static void tcg_log_global_after_sync(MemoryListener *listener)
+{
+ CPUAddressSpace *cpuas;
+
+ /* Wait for the CPU to end the current TB. This avoids the following
+ * incorrect race:
+ *
+ * vCPU migration
+ * ---------------------- -------------------------
+ * TLB check -> slow path
+ * notdirty_mem_write
+ * write to RAM
+ * mark dirty
+ * clear dirty flag
+ * TLB check -> fast path
+ * read memory
+ * write to RAM
+ *
+ * by pushing the migration thread's memory read after the vCPU thread has
+ * written the memory.
+ */
+ if (replay_mode == REPLAY_MODE_NONE) {
+ /*
+ * VGA can make calls to this function while updating the screen.
+ * In record/replay mode this causes a deadlock, because
+ * run_on_cpu waits for rr mutex. Therefore no races are possible
+ * in this case and no need for making run_on_cpu when
+ * record/replay is not enabled.
+ */
+ cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
+ run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
+ }
+}
+
+static void tcg_commit(MemoryListener *listener)
+{
+ CPUAddressSpace *cpuas;
+ AddressSpaceDispatch *d;
+
+ assert(tcg_enabled());
+ /* since each CPU stores ram addresses in its TLB cache, we must
+ reset the modified entries */
+ cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
+ cpu_reloading_memory_map();
+ /* The CPU and TLB are protected by the iothread lock.
+ * We reload the dispatch pointer now because cpu_reloading_memory_map()
+ * may have split the RCU critical section.
+ */
+ d = address_space_to_dispatch(cpuas->as);
+ qatomic_rcu_set(&cpuas->memory_dispatch, d);
+ tlb_flush(cpuas->cpu);
+}
+
+static void memory_map_init(void)
+{
+ system_memory = g_malloc(sizeof(*system_memory));
+
+ memory_region_init(system_memory, NULL, "system", UINT64_MAX);
+ address_space_init(&address_space_memory, system_memory, "memory");
+
+ system_io = g_malloc(sizeof(*system_io));
+ memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
+ 65536);
+ address_space_init(&address_space_io, system_io, "I/O");
+}
+
+MemoryRegion *get_system_memory(void)
+{
+ return system_memory;
+}
+
+MemoryRegion *get_system_io(void)
+{
+ return system_io;
+}
+
+static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
+ hwaddr length)
+{
+ uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
+ addr += memory_region_get_ram_addr(mr);
+
+ /* No early return if dirty_log_mask is or becomes 0, because
+ * cpu_physical_memory_set_dirty_range will still call
+ * xen_modified_memory.
+ */
+ if (dirty_log_mask) {
+ dirty_log_mask =
+ cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
+ }
+ if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
+ assert(tcg_enabled());
+ tb_invalidate_phys_range(addr, addr + length);
+ dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
+ }
+ cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
+}
+
+void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
+{
+ /*
+ * In principle this function would work on other memory region types too,
+ * but the ROM device use case is the only one where this operation is
+ * necessary. Other memory regions should use the
+ * address_space_read/write() APIs.
+ */
+ assert(memory_region_is_romd(mr));
+
+ invalidate_and_set_dirty(mr, addr, size);
+}
+
+static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
+{
+ unsigned access_size_max = mr->ops->valid.max_access_size;
+
+ /* Regions are assumed to support 1-4 byte accesses unless
+ otherwise specified. */
+ if (access_size_max == 0) {
+ access_size_max = 4;
+ }
+
+ /* Bound the maximum access by the alignment of the address. */
+ if (!mr->ops->impl.unaligned) {
+ unsigned align_size_max = addr & -addr;
+ if (align_size_max != 0 && align_size_max < access_size_max) {
+ access_size_max = align_size_max;
+ }
+ }
+
+ /* Don't attempt accesses larger than the maximum. */
+ if (l > access_size_max) {
+ l = access_size_max;
+ }
+ l = pow2floor(l);
+
+ return l;
+}
+
+static bool prepare_mmio_access(MemoryRegion *mr)
+{
+ bool unlocked = !qemu_mutex_iothread_locked();
+ bool release_lock = false;
+
+ if (unlocked) {
+ qemu_mutex_lock_iothread();
+ unlocked = false;
+ release_lock = true;
+ }
+ if (mr->flush_coalesced_mmio) {
+ if (unlocked) {
+ qemu_mutex_lock_iothread();
+ }
+ qemu_flush_coalesced_mmio_buffer();
+ if (unlocked) {
+ qemu_mutex_unlock_iothread();
+ }
+ }
+
+ return release_lock;
+}
+
+/* Called within RCU critical section. */
+static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
+ MemTxAttrs attrs,
+ const void *ptr,
+ hwaddr len, hwaddr addr1,
+ hwaddr l, MemoryRegion *mr)
+{
+ uint8_t *ram_ptr;
+ uint64_t val;
+ MemTxResult result = MEMTX_OK;
+ bool release_lock = false;
+ const uint8_t *buf = ptr;
+
+ for (;;) {
+ if (!memory_access_is_direct(mr, true)) {
+ release_lock |= prepare_mmio_access(mr);
+ l = memory_access_size(mr, l, addr1);
+ /* XXX: could force current_cpu to NULL to avoid
+ potential bugs */
+ val = ldn_he_p(buf, l);
+ result |= memory_region_dispatch_write(mr, addr1, val,
+ size_memop(l), attrs);
+ } else {
+ /* RAM case */
+ ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
+ memcpy(ram_ptr, buf, l);
+ invalidate_and_set_dirty(mr, addr1, l);
+ }
+
+ if (release_lock) {
+ qemu_mutex_unlock_iothread();
+ release_lock = false;
+ }
+
+ len -= l;
+ buf += l;
+ addr += l;
+
+ if (!len) {
+ break;
+ }
+
+ l = len;
+ mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
+ }
+
+ return result;
+}
+
+/* Called from RCU critical section. */
+static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
+ const void *buf, hwaddr len)
+{
+ hwaddr l;
+ hwaddr addr1;
+ MemoryRegion *mr;
+ MemTxResult result = MEMTX_OK;
+
+ l = len;
+ mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
+ result = flatview_write_continue(fv, addr, attrs, buf, len,
+ addr1, l, mr);
+
+ return result;
+}
+
+/* Called within RCU critical section. */
+MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
+ MemTxAttrs attrs, void *ptr,
+ hwaddr len, hwaddr addr1, hwaddr l,
+ MemoryRegion *mr)
+{
+ uint8_t *ram_ptr;
+ uint64_t val;
+ MemTxResult result = MEMTX_OK;
+ bool release_lock = false;
+ uint8_t *buf = ptr;
+
+ for (;;) {
+ if (!memory_access_is_direct(mr, false)) {
+ /* I/O case */
+ release_lock |= prepare_mmio_access(mr);
+ l = memory_access_size(mr, l, addr1);
+ result |= memory_region_dispatch_read(mr, addr1, &val,
+ size_memop(l), attrs);
+ stn_he_p(buf, l, val);
+ } else {
+ /* RAM case */
+ ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
+ memcpy(buf, ram_ptr, l);
+ }
+
+ if (release_lock) {
+ qemu_mutex_unlock_iothread();
+ release_lock = false;
+ }
+
+ len -= l;
+ buf += l;
+ addr += l;
+
+ if (!len) {
+ break;
+ }
+
+ l = len;
+ mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
+ }
+
+ return result;
+}
+
+/* Called from RCU critical section. */
+static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
+ MemTxAttrs attrs, void *buf, hwaddr len)
+{
+ hwaddr l;
+ hwaddr addr1;
+ MemoryRegion *mr;
+
+ l = len;
+ mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
+ return flatview_read_continue(fv, addr, attrs, buf, len,
+ addr1, l, mr);
+}
+
+MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
+ MemTxAttrs attrs, void *buf, hwaddr len)
+{
+ MemTxResult result = MEMTX_OK;
+ FlatView *fv;
+
+ if (len > 0) {
+ RCU_READ_LOCK_GUARD();
+ fv = address_space_to_flatview(as);
+ result = flatview_read(fv, addr, attrs, buf, len);
+ }
+
+ return result;
+}
+
+MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
+ MemTxAttrs attrs,
+ const void *buf, hwaddr len)
+{
+ MemTxResult result = MEMTX_OK;
+ FlatView *fv;
+
+ if (len > 0) {
+ RCU_READ_LOCK_GUARD();
+ fv = address_space_to_flatview(as);
+ result = flatview_write(fv, addr, attrs, buf, len);
+ }
+
+ return result;
+}
+
+MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
+ void *buf, hwaddr len, bool is_write)
+{
+ if (is_write) {
+ return address_space_write(as, addr, attrs, buf, len);
+ } else {
+ return address_space_read_full(as, addr, attrs, buf, len);
+ }
+}
+
+void cpu_physical_memory_rw(hwaddr addr, void *buf,
+ hwaddr len, bool is_write)
+{
+ address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
+ buf, len, is_write);
+}
+
+enum write_rom_type {
+ WRITE_DATA,
+ FLUSH_CACHE,
+};
+
+static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
+ hwaddr addr,
+ MemTxAttrs attrs,
+ const void *ptr,
+ hwaddr len,
+ enum write_rom_type type)
+{
+ hwaddr l;
+ uint8_t *ram_ptr;
+ hwaddr addr1;
+ MemoryRegion *mr;
+ const uint8_t *buf = ptr;
+
+ RCU_READ_LOCK_GUARD();
+ while (len > 0) {
+ l = len;
+ mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
+
+ if (!(memory_region_is_ram(mr) ||
+ memory_region_is_romd(mr))) {
+ l = memory_access_size(mr, l, addr1);
+ } else {
+ /* ROM/RAM case */
+ ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
+ switch (type) {
+ case WRITE_DATA:
+ memcpy(ram_ptr, buf, l);
+ invalidate_and_set_dirty(mr, addr1, l);
+ break;
+ case FLUSH_CACHE:
+ flush_icache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr + l);
+ break;
+ }
+ }
+ len -= l;
+ buf += l;
+ addr += l;
+ }
+ return MEMTX_OK;
+}
+
+/* used for ROM loading : can write in RAM and ROM */
+MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
+ MemTxAttrs attrs,
+ const void *buf, hwaddr len)
+{
+ return address_space_write_rom_internal(as, addr, attrs,
+ buf, len, WRITE_DATA);
+}
+
+void cpu_flush_icache_range(hwaddr start, hwaddr len)
+{
+ /*
+ * This function should do the same thing as an icache flush that was
+ * triggered from within the guest. For TCG we are always cache coherent,
+ * so there is no need to flush anything. For KVM / Xen we need to flush
+ * the host's instruction cache at least.
+ */
+ if (tcg_enabled()) {
+ return;
+ }
+
+ address_space_write_rom_internal(&address_space_memory,
+ start, MEMTXATTRS_UNSPECIFIED,
+ NULL, len, FLUSH_CACHE);
+}
+
+typedef struct {
+ MemoryRegion *mr;
+ void *buffer;
+ hwaddr addr;
+ hwaddr len;
+ bool in_use;
+} BounceBuffer;
+
+static BounceBuffer bounce;
+
+typedef struct MapClient {
+ QEMUBH *bh;
+ QLIST_ENTRY(MapClient) link;
+} MapClient;
+
+QemuMutex map_client_list_lock;
+static QLIST_HEAD(, MapClient) map_client_list
+ = QLIST_HEAD_INITIALIZER(map_client_list);
+
+static void cpu_unregister_map_client_do(MapClient *client)
+{
+ QLIST_REMOVE(client, link);
+ g_free(client);
+}
+
+static void cpu_notify_map_clients_locked(void)
+{
+ MapClient *client;
+
+ while (!QLIST_EMPTY(&map_client_list)) {
+ client = QLIST_FIRST(&map_client_list);
+ qemu_bh_schedule(client->bh);
+ cpu_unregister_map_client_do(client);
+ }
+}
+
+void cpu_register_map_client(QEMUBH *bh)
+{
+ MapClient *client = g_malloc(sizeof(*client));
+
+ qemu_mutex_lock(&map_client_list_lock);
+ client->bh = bh;
+ QLIST_INSERT_HEAD(&map_client_list, client, link);
+ if (!qatomic_read(&bounce.in_use)) {
+ cpu_notify_map_clients_locked();
+ }
+ qemu_mutex_unlock(&map_client_list_lock);
+}
+
+void cpu_exec_init_all(void)
+{
+ qemu_mutex_init(&ram_list.mutex);
+ /* The data structures we set up here depend on knowing the page size,
+ * so no more changes can be made after this point.
+ * In an ideal world, nothing we did before we had finished the
+ * machine setup would care about the target page size, and we could
+ * do this much later, rather than requiring board models to state
+ * up front what their requirements are.
+ */
+ finalize_target_page_bits();
+ io_mem_init();
+ memory_map_init();
+ qemu_mutex_init(&map_client_list_lock);
+}
+
+void cpu_unregister_map_client(QEMUBH *bh)
+{
+ MapClient *client;
+
+ qemu_mutex_lock(&map_client_list_lock);
+ QLIST_FOREACH(client, &map_client_list, link) {
+ if (client->bh == bh) {
+ cpu_unregister_map_client_do(client);
+ break;
+ }
+ }
+ qemu_mutex_unlock(&map_client_list_lock);
+}
+
+static void cpu_notify_map_clients(void)
+{
+ qemu_mutex_lock(&map_client_list_lock);
+ cpu_notify_map_clients_locked();
+ qemu_mutex_unlock(&map_client_list_lock);
+}
+
+static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
+ bool is_write, MemTxAttrs attrs)
+{
+ MemoryRegion *mr;
+ hwaddr l, xlat;
+
+ while (len > 0) {
+ l = len;
+ mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
+ if (!memory_access_is_direct(mr, is_write)) {
+ l = memory_access_size(mr, l, addr);
+ if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
+ return false;
+ }
+ }
+
+ len -= l;
+ addr += l;
+ }
+ return true;
+}
+
+bool address_space_access_valid(AddressSpace *as, hwaddr addr,
+ hwaddr len, bool is_write,
+ MemTxAttrs attrs)
+{
+ FlatView *fv;
+ bool result;
+
+ RCU_READ_LOCK_GUARD();
+ fv = address_space_to_flatview(as);
+ result = flatview_access_valid(fv, addr, len, is_write, attrs);
+ return result;
+}
+
+static hwaddr
+flatview_extend_translation(FlatView *fv, hwaddr addr,
+ hwaddr target_len,
+ MemoryRegion *mr, hwaddr base, hwaddr len,
+ bool is_write, MemTxAttrs attrs)
+{
+ hwaddr done = 0;
+ hwaddr xlat;
+ MemoryRegion *this_mr;
+
+ for (;;) {
+ target_len -= len;
+ addr += len;
+ done += len;
+ if (target_len == 0) {
+ return done;
+ }
+
+ len = target_len;
+ this_mr = flatview_translate(fv, addr, &xlat,
+ &len, is_write, attrs);
+ if (this_mr != mr || xlat != base + done) {
+ return done;
+ }
+ }
+}
+
+/* Map a physical memory region into a host virtual address.
+ * May map a subset of the requested range, given by and returned in *plen.
+ * May return NULL if resources needed to perform the mapping are exhausted.
+ * Use only for reads OR writes - not for read-modify-write operations.
+ * Use cpu_register_map_client() to know when retrying the map operation is
+ * likely to succeed.
+ */
+void *address_space_map(AddressSpace *as,
+ hwaddr addr,
+ hwaddr *plen,
+ bool is_write,
+ MemTxAttrs attrs)
+{
+ hwaddr len = *plen;
+ hwaddr l, xlat;
+ MemoryRegion *mr;
+ void *ptr;
+ FlatView *fv;
+
+ if (len == 0) {
+ return NULL;
+ }
+
+ l = len;
+ RCU_READ_LOCK_GUARD();
+ fv = address_space_to_flatview(as);
+ mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
+
+ if (!memory_access_is_direct(mr, is_write)) {
+ if (qatomic_xchg(&bounce.in_use, true)) {
+ *plen = 0;
+ return NULL;
+ }
+ /* Avoid unbounded allocations */
+ l = MIN(l, TARGET_PAGE_SIZE);
+ bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
+ bounce.addr = addr;
+ bounce.len = l;
+
+ memory_region_ref(mr);
+ bounce.mr = mr;
+ if (!is_write) {
+ flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
+ bounce.buffer, l);
+ }
+
+ *plen = l;
+ return bounce.buffer;
+ }
+
+
+ memory_region_ref(mr);
+ *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
+ l, is_write, attrs);
+ ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
+
+ return ptr;
+}
+
+/* Unmaps a memory region previously mapped by address_space_map().
+ * Will also mark the memory as dirty if is_write is true. access_len gives
+ * the amount of memory that was actually read or written by the caller.
+ */
+void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
+ bool is_write, hwaddr access_len)
+{
+ if (buffer != bounce.buffer) {
+ MemoryRegion *mr;
+ ram_addr_t addr1;
+
+ mr = memory_region_from_host(buffer, &addr1);
+ assert(mr != NULL);
+ if (is_write) {
+ invalidate_and_set_dirty(mr, addr1, access_len);
+ }
+ if (xen_enabled()) {
+ xen_invalidate_map_cache_entry(buffer);
+ }
+ memory_region_unref(mr);
+ return;
+ }
+ if (is_write) {
+ address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
+ bounce.buffer, access_len);
+ }
+ qemu_vfree(bounce.buffer);
+ bounce.buffer = NULL;
+ memory_region_unref(bounce.mr);
+ qatomic_mb_set(&bounce.in_use, false);
+ cpu_notify_map_clients();
+}
+
+void *cpu_physical_memory_map(hwaddr addr,
+ hwaddr *plen,
+ bool is_write)
+{
+ return address_space_map(&address_space_memory, addr, plen, is_write,
+ MEMTXATTRS_UNSPECIFIED);
+}
+
+void cpu_physical_memory_unmap(void *buffer, hwaddr len,
+ bool is_write, hwaddr access_len)
+{
+ return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
+}
+
+#define ARG1_DECL AddressSpace *as
+#define ARG1 as
+#define SUFFIX
+#define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
+#define RCU_READ_LOCK(...) rcu_read_lock()
+#define RCU_READ_UNLOCK(...) rcu_read_unlock()
+#include "memory_ldst.c.inc"
+
+int64_t address_space_cache_init(MemoryRegionCache *cache,
+ AddressSpace *as,
+ hwaddr addr,
+ hwaddr len,
+ bool is_write)
+{
+ AddressSpaceDispatch *d;
+ hwaddr l;
+ MemoryRegion *mr;
+
+ assert(len > 0);
+
+ l = len;
+ cache->fv = address_space_get_flatview(as);
+ d = flatview_to_dispatch(cache->fv);
+ cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
+
+ mr = cache->mrs.mr;
+ memory_region_ref(mr);
+ if (memory_access_is_direct(mr, is_write)) {
+ /* We don't care about the memory attributes here as we're only
+ * doing this if we found actual RAM, which behaves the same
+ * regardless of attributes; so UNSPECIFIED is fine.
+ */
+ l = flatview_extend_translation(cache->fv, addr, len, mr,
+ cache->xlat, l, is_write,
+ MEMTXATTRS_UNSPECIFIED);
+ cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
+ } else {
+ cache->ptr = NULL;
+ }
+
+ cache->len = l;
+ cache->is_write = is_write;
+ return l;
+}
+
+void address_space_cache_invalidate(MemoryRegionCache *cache,
+ hwaddr addr,
+ hwaddr access_len)
+{
+ assert(cache->is_write);
+ if (likely(cache->ptr)) {
+ invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
+ }
+}
+
+void address_space_cache_destroy(MemoryRegionCache *cache)
+{
+ if (!cache->mrs.mr) {
+ return;
+ }
+
+ if (xen_enabled()) {
+ xen_invalidate_map_cache_entry(cache->ptr);
+ }
+ memory_region_unref(cache->mrs.mr);
+ flatview_unref(cache->fv);
+ cache->mrs.mr = NULL;
+ cache->fv = NULL;
+}
+
+/* Called from RCU critical section. This function has the same
+ * semantics as address_space_translate, but it only works on a
+ * predefined range of a MemoryRegion that was mapped with
+ * address_space_cache_init.
+ */
+static inline MemoryRegion *address_space_translate_cached(
+ MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
+ hwaddr *plen, bool is_write, MemTxAttrs attrs)
+{
+ MemoryRegionSection section;
+ MemoryRegion *mr;
+ IOMMUMemoryRegion *iommu_mr;
+ AddressSpace *target_as;
+
+ assert(!cache->ptr);
+ *xlat = addr + cache->xlat;
+
+ mr = cache->mrs.mr;
+ iommu_mr = memory_region_get_iommu(mr);
+ if (!iommu_mr) {
+ /* MMIO region. */
+ return mr;
+ }
+
+ section = address_space_translate_iommu(iommu_mr, xlat, plen,
+ NULL, is_write, true,
+ &target_as, attrs);
+ return section.mr;
+}
+
+/* Called from RCU critical section. address_space_read_cached uses this
+ * out of line function when the target is an MMIO or IOMMU region.
+ */
+MemTxResult
+address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
+ void *buf, hwaddr len)
+{
+ hwaddr addr1, l;
+ MemoryRegion *mr;
+
+ l = len;
+ mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
+ MEMTXATTRS_UNSPECIFIED);
+ return flatview_read_continue(cache->fv,
+ addr, MEMTXATTRS_UNSPECIFIED, buf, len,
+ addr1, l, mr);
+}
+
+/* Called from RCU critical section. address_space_write_cached uses this
+ * out of line function when the target is an MMIO or IOMMU region.
+ */
+MemTxResult
+address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
+ const void *buf, hwaddr len)
+{
+ hwaddr addr1, l;
+ MemoryRegion *mr;
+
+ l = len;
+ mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
+ MEMTXATTRS_UNSPECIFIED);
+ return flatview_write_continue(cache->fv,
+ addr, MEMTXATTRS_UNSPECIFIED, buf, len,
+ addr1, l, mr);
+}
+
+#define ARG1_DECL MemoryRegionCache *cache
+#define ARG1 cache
+#define SUFFIX _cached_slow
+#define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
+#define RCU_READ_LOCK() ((void)0)
+#define RCU_READ_UNLOCK() ((void)0)
+#include "memory_ldst.c.inc"
+
+/* virtual memory access for debug (includes writing to ROM) */
+int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
+ void *ptr, target_ulong len, bool is_write)
+{
+ hwaddr phys_addr;
+ target_ulong l, page;
+ uint8_t *buf = ptr;
+
+ cpu_synchronize_state(cpu);
+ while (len > 0) {
+ int asidx;
+ MemTxAttrs attrs;
+ MemTxResult res;
+
+ page = addr & TARGET_PAGE_MASK;
+ phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
+ asidx = cpu_asidx_from_attrs(cpu, attrs);
+ /* if no physical page mapped, return an error */
+ if (phys_addr == -1)
+ return -1;
+ l = (page + TARGET_PAGE_SIZE) - addr;
+ if (l > len)
+ l = len;
+ phys_addr += (addr & ~TARGET_PAGE_MASK);
+ if (is_write) {
+ res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
+ attrs, buf, l);
+ } else {
+ res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
+ attrs, buf, l);
+ }
+ if (res != MEMTX_OK) {
+ return -1;
+ }
+ len -= l;
+ buf += l;
+ addr += l;
+ }
+ return 0;
+}
+
+/*
+ * Allows code that needs to deal with migration bitmaps etc to still be built
+ * target independent.
+ */
+size_t qemu_target_page_size(void)
+{
+ return TARGET_PAGE_SIZE;
+}
+
+int qemu_target_page_bits(void)
+{
+ return TARGET_PAGE_BITS;
+}
+
+int qemu_target_page_bits_min(void)
+{
+ return TARGET_PAGE_BITS_MIN;
+}
+
+bool cpu_physical_memory_is_io(hwaddr phys_addr)
+{
+ MemoryRegion*mr;
+ hwaddr l = 1;
+ bool res;
+
+ RCU_READ_LOCK_GUARD();
+ mr = address_space_translate(&address_space_memory,
+ phys_addr, &phys_addr, &l, false,
+ MEMTXATTRS_UNSPECIFIED);
+
+ res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
+ return res;
+}
+
+int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
+{
+ RAMBlock *block;
+ int ret = 0;
+
+ RCU_READ_LOCK_GUARD();
+ RAMBLOCK_FOREACH(block) {
+ ret = func(block, opaque);
+ if (ret) {
+ break;
+ }
+ }
+ return ret;
+}
+
+/*
+ * Unmap pages of memory from start to start+length such that
+ * they a) read as 0, b) Trigger whatever fault mechanism
+ * the OS provides for postcopy.
+ * The pages must be unmapped by the end of the function.
+ * Returns: 0 on success, none-0 on failure
+ *
+ */
+int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
+{
+ int ret = -1;
+
+ uint8_t *host_startaddr = rb->host + start;
+
+ if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
+ error_report("ram_block_discard_range: Unaligned start address: %p",
+ host_startaddr);
+ goto err;
+ }
+
+ if ((start + length) <= rb->used_length) {
+ bool need_madvise, need_fallocate;
+ if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
+ error_report("ram_block_discard_range: Unaligned length: %zx",
+ length);
+ goto err;
+ }
+
+ errno = ENOTSUP; /* If we are missing MADVISE etc */
+
+ /* The logic here is messy;
+ * madvise DONTNEED fails for hugepages
+ * fallocate works on hugepages and shmem
+ */
+ need_madvise = (rb->page_size == qemu_host_page_size);
+ need_fallocate = rb->fd != -1;
+ if (need_fallocate) {
+ /* For a file, this causes the area of the file to be zero'd
+ * if read, and for hugetlbfs also causes it to be unmapped
+ * so a userfault will trigger.
+ */
+#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
+ ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
+ start, length);
+ if (ret) {
+ ret = -errno;
+ error_report("ram_block_discard_range: Failed to fallocate "
+ "%s:%" PRIx64 " +%zx (%d)",
+ rb->idstr, start, length, ret);
+ goto err;
+ }
+#else
+ ret = -ENOSYS;
+ error_report("ram_block_discard_range: fallocate not available/file"
+ "%s:%" PRIx64 " +%zx (%d)",
+ rb->idstr, start, length, ret);
+ goto err;
+#endif
+ }
+ if (need_madvise) {
+ /* For normal RAM this causes it to be unmapped,
+ * for shared memory it causes the local mapping to disappear
+ * and to fall back on the file contents (which we just
+ * fallocate'd away).
+ */
+#if defined(CONFIG_MADVISE)
+ ret = madvise(host_startaddr, length, MADV_DONTNEED);
+ if (ret) {
+ ret = -errno;
+ error_report("ram_block_discard_range: Failed to discard range "
+ "%s:%" PRIx64 " +%zx (%d)",
+ rb->idstr, start, length, ret);
+ goto err;
+ }
+#else
+ ret = -ENOSYS;
+ error_report("ram_block_discard_range: MADVISE not available"
+ "%s:%" PRIx64 " +%zx (%d)",
+ rb->idstr, start, length, ret);
+ goto err;
+#endif
+ }
+ trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
+ need_madvise, need_fallocate, ret);
+ } else {
+ error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
+ "/%zx/" RAM_ADDR_FMT")",
+ rb->idstr, start, length, rb->used_length);
+ }
+
+err:
+ return ret;
+}
+
+bool ramblock_is_pmem(RAMBlock *rb)
+{
+ return rb->flags & RAM_PMEM;
+}
+
+static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
+{
+ if (start == end - 1) {
+ qemu_printf("\t%3d ", start);
+ } else {
+ qemu_printf("\t%3d..%-3d ", start, end - 1);
+ }
+ qemu_printf(" skip=%d ", skip);
+ if (ptr == PHYS_MAP_NODE_NIL) {
+ qemu_printf(" ptr=NIL");
+ } else if (!skip) {
+ qemu_printf(" ptr=#%d", ptr);
+ } else {
+ qemu_printf(" ptr=[%d]", ptr);
+ }
+ qemu_printf("\n");
+}
+
+#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
+ int128_sub((size), int128_one())) : 0)
+
+void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
+{
+ int i;
+
+ qemu_printf(" Dispatch\n");
+ qemu_printf(" Physical sections\n");
+
+ for (i = 0; i < d->map.sections_nb; ++i) {
+ MemoryRegionSection *s = d->map.sections + i;
+ const char *names[] = { " [unassigned]", " [not dirty]",
+ " [ROM]", " [watch]" };
+
+ qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
+ " %s%s%s%s%s",
+ i,
+ s->offset_within_address_space,
+ s->offset_within_address_space + MR_SIZE(s->mr->size),
+ s->mr->name ? s->mr->name : "(noname)",
+ i < ARRAY_SIZE(names) ? names[i] : "",
+ s->mr == root ? " [ROOT]" : "",
+ s == d->mru_section ? " [MRU]" : "",
+ s->mr->is_iommu ? " [iommu]" : "");
+
+ if (s->mr->alias) {
+ qemu_printf(" alias=%s", s->mr->alias->name ?
+ s->mr->alias->name : "noname");
+ }
+ qemu_printf("\n");
+ }
+
+ qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
+ P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
+ for (i = 0; i < d->map.nodes_nb; ++i) {
+ int j, jprev;
+ PhysPageEntry prev;
+ Node *n = d->map.nodes + i;
+
+ qemu_printf(" [%d]\n", i);
+
+ for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
+ PhysPageEntry *pe = *n + j;
+
+ if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
+ continue;
+ }
+
+ mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
+
+ jprev = j;
+ prev = *pe;
+ }
+
+ if (jprev != ARRAY_SIZE(*n)) {
+ mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
+ }
+ }
+}
+
+/*
+ * If positive, discarding RAM is disabled. If negative, discarding RAM is
+ * required to work and cannot be disabled.
+ */
+static int ram_block_discard_disabled;
+
+int ram_block_discard_disable(bool state)
+{
+ int old;
+
+ if (!state) {
+ qatomic_dec(&ram_block_discard_disabled);
+ return 0;
+ }
+
+ do {
+ old = qatomic_read(&ram_block_discard_disabled);
+ if (old < 0) {
+ return -EBUSY;
+ }
+ } while (qatomic_cmpxchg(&ram_block_discard_disabled,
+ old, old + 1) != old);
+ return 0;
+}
+
+int ram_block_discard_require(bool state)
+{
+ int old;
+
+ if (!state) {
+ qatomic_inc(&ram_block_discard_disabled);
+ return 0;
+ }
+
+ do {
+ old = qatomic_read(&ram_block_discard_disabled);
+ if (old > 0) {
+ return -EBUSY;
+ }
+ } while (qatomic_cmpxchg(&ram_block_discard_disabled,
+ old, old - 1) != old);
+ return 0;
+}
+
+bool ram_block_discard_is_disabled(void)
+{
+ return qatomic_read(&ram_block_discard_disabled) > 0;
+}
+
+bool ram_block_discard_is_required(void)
+{
+ return qatomic_read(&ram_block_discard_disabled) < 0;
+}
diff --git a/softmmu/qdev-monitor.c b/softmmu/qdev-monitor.c
new file mode 100644
index 0000000..bcfb90a
--- /dev/null
+++ b/softmmu/qdev-monitor.c
@@ -0,0 +1,1005 @@
+/*
+ * Dynamic device configuration and creation.
+ *
+ * Copyright (c) 2009 CodeSourcery
+ *
+ * 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 "qemu/osdep.h"
+#include "hw/sysbus.h"
+#include "monitor/hmp.h"
+#include "monitor/monitor.h"
+#include "monitor/qdev.h"
+#include "sysemu/arch_init.h"
+#include "qapi/error.h"
+#include "qapi/qapi-commands-qdev.h"
+#include "qapi/qmp/qdict.h"
+#include "qapi/qmp/qerror.h"
+#include "qemu/config-file.h"
+#include "qemu/error-report.h"
+#include "qemu/help_option.h"
+#include "qemu/option.h"
+#include "qemu/qemu-print.h"
+#include "qemu/option_int.h"
+#include "sysemu/block-backend.h"
+#include "sysemu/sysemu.h"
+#include "migration/misc.h"
+#include "migration/migration.h"
+#include "qemu/cutils.h"
+#include "hw/clock.h"
+
+/*
+ * Aliases were a bad idea from the start. Let's keep them
+ * from spreading further.
+ */
+typedef struct QDevAlias
+{
+ const char *typename;
+ const char *alias;
+ uint32_t arch_mask;
+} QDevAlias;
+
+/* Please keep this table sorted by typename. */
+static const QDevAlias qdev_alias_table[] = {
+ { "AC97", "ac97" }, /* -soundhw name */
+ { "e1000", "e1000-82540em" },
+ { "ES1370", "es1370" }, /* -soundhw name */
+ { "ich9-ahci", "ahci" },
+ { "lsi53c895a", "lsi" },
+ { "virtio-9p-ccw", "virtio-9p", QEMU_ARCH_S390X },
+ { "virtio-9p-pci", "virtio-9p", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-balloon-ccw", "virtio-balloon", QEMU_ARCH_S390X },
+ { "virtio-balloon-pci", "virtio-balloon",
+ QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-blk-ccw", "virtio-blk", QEMU_ARCH_S390X },
+ { "virtio-blk-pci", "virtio-blk", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-gpu-ccw", "virtio-gpu", QEMU_ARCH_S390X },
+ { "virtio-gpu-pci", "virtio-gpu", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-input-host-ccw", "virtio-input-host", QEMU_ARCH_S390X },
+ { "virtio-input-host-pci", "virtio-input-host",
+ QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-iommu-pci", "virtio-iommu", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-keyboard-ccw", "virtio-keyboard", QEMU_ARCH_S390X },
+ { "virtio-keyboard-pci", "virtio-keyboard",
+ QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-mouse-ccw", "virtio-mouse", QEMU_ARCH_S390X },
+ { "virtio-mouse-pci", "virtio-mouse", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-net-ccw", "virtio-net", QEMU_ARCH_S390X },
+ { "virtio-net-pci", "virtio-net", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-rng-ccw", "virtio-rng", QEMU_ARCH_S390X },
+ { "virtio-rng-pci", "virtio-rng", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-scsi-ccw", "virtio-scsi", QEMU_ARCH_S390X },
+ { "virtio-scsi-pci", "virtio-scsi", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-serial-ccw", "virtio-serial", QEMU_ARCH_S390X },
+ { "virtio-serial-pci", "virtio-serial", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { "virtio-tablet-ccw", "virtio-tablet", QEMU_ARCH_S390X },
+ { "virtio-tablet-pci", "virtio-tablet", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+ { }
+};
+
+static const char *qdev_class_get_alias(DeviceClass *dc)
+{
+ const char *typename = object_class_get_name(OBJECT_CLASS(dc));
+ int i;
+
+ for (i = 0; qdev_alias_table[i].typename; i++) {
+ if (qdev_alias_table[i].arch_mask &&
+ !(qdev_alias_table[i].arch_mask & arch_type)) {
+ continue;
+ }
+
+ if (strcmp(qdev_alias_table[i].typename, typename) == 0) {
+ return qdev_alias_table[i].alias;
+ }
+ }
+
+ return NULL;
+}
+
+static bool qdev_class_has_alias(DeviceClass *dc)
+{
+ return (qdev_class_get_alias(dc) != NULL);
+}
+
+static void qdev_print_devinfo(DeviceClass *dc)
+{
+ qemu_printf("name \"%s\"", object_class_get_name(OBJECT_CLASS(dc)));
+ if (dc->bus_type) {
+ qemu_printf(", bus %s", dc->bus_type);
+ }
+ if (qdev_class_has_alias(dc)) {
+ qemu_printf(", alias \"%s\"", qdev_class_get_alias(dc));
+ }
+ if (dc->desc) {
+ qemu_printf(", desc \"%s\"", dc->desc);
+ }
+ if (!dc->user_creatable) {
+ qemu_printf(", no-user");
+ }
+ qemu_printf("\n");
+}
+
+static void qdev_print_devinfos(bool show_no_user)
+{
+ static const char *cat_name[DEVICE_CATEGORY_MAX + 1] = {
+ [DEVICE_CATEGORY_BRIDGE] = "Controller/Bridge/Hub",
+ [DEVICE_CATEGORY_USB] = "USB",
+ [DEVICE_CATEGORY_STORAGE] = "Storage",
+ [DEVICE_CATEGORY_NETWORK] = "Network",
+ [DEVICE_CATEGORY_INPUT] = "Input",
+ [DEVICE_CATEGORY_DISPLAY] = "Display",
+ [DEVICE_CATEGORY_SOUND] = "Sound",
+ [DEVICE_CATEGORY_MISC] = "Misc",
+ [DEVICE_CATEGORY_CPU] = "CPU",
+ [DEVICE_CATEGORY_MAX] = "Uncategorized",
+ };
+ GSList *list, *elt;
+ int i;
+ bool cat_printed;
+
+ module_load_qom_all();
+ list = object_class_get_list_sorted(TYPE_DEVICE, false);
+
+ for (i = 0; i <= DEVICE_CATEGORY_MAX; i++) {
+ cat_printed = false;
+ for (elt = list; elt; elt = elt->next) {
+ DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
+ TYPE_DEVICE);
+ if ((i < DEVICE_CATEGORY_MAX
+ ? !test_bit(i, dc->categories)
+ : !bitmap_empty(dc->categories, DEVICE_CATEGORY_MAX))
+ || (!show_no_user
+ && !dc->user_creatable)) {
+ continue;
+ }
+ if (!cat_printed) {
+ qemu_printf("%s%s devices:\n", i ? "\n" : "", cat_name[i]);
+ cat_printed = true;
+ }
+ qdev_print_devinfo(dc);
+ }
+ }
+
+ g_slist_free(list);
+}
+
+static int set_property(void *opaque, const char *name, const char *value,
+ Error **errp)
+{
+ Object *obj = opaque;
+
+ if (strcmp(name, "driver") == 0)
+ return 0;
+ if (strcmp(name, "bus") == 0)
+ return 0;
+
+ if (!object_property_parse(obj, name, value, errp)) {
+ return -1;
+ }
+ return 0;
+}
+
+static const char *find_typename_by_alias(const char *alias)
+{
+ int i;
+
+ for (i = 0; qdev_alias_table[i].alias; i++) {
+ if (qdev_alias_table[i].arch_mask &&
+ !(qdev_alias_table[i].arch_mask & arch_type)) {
+ continue;
+ }
+
+ if (strcmp(qdev_alias_table[i].alias, alias) == 0) {
+ return qdev_alias_table[i].typename;
+ }
+ }
+
+ return NULL;
+}
+
+static DeviceClass *qdev_get_device_class(const char **driver, Error **errp)
+{
+ ObjectClass *oc;
+ DeviceClass *dc;
+ const char *original_name = *driver;
+
+ oc = module_object_class_by_name(*driver);
+ if (!oc) {
+ const char *typename = find_typename_by_alias(*driver);
+
+ if (typename) {
+ *driver = typename;
+ oc = module_object_class_by_name(*driver);
+ }
+ }
+
+ if (!object_class_dynamic_cast(oc, TYPE_DEVICE)) {
+ if (*driver != original_name) {
+ error_setg(errp, "'%s' (alias '%s') is not a valid device model"
+ " name", original_name, *driver);
+ } else {
+ error_setg(errp, "'%s' is not a valid device model name", *driver);
+ }
+ return NULL;
+ }
+
+ if (object_class_is_abstract(oc)) {
+ error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
+ "non-abstract device type");
+ return NULL;
+ }
+
+ dc = DEVICE_CLASS(oc);
+ if (!dc->user_creatable ||
+ (qdev_hotplug && !dc->hotpluggable)) {
+ error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
+ "pluggable device type");
+ return NULL;
+ }
+
+ return dc;
+}
+
+
+int qdev_device_help(QemuOpts *opts)
+{
+ Error *local_err = NULL;
+ const char *driver;
+ ObjectPropertyInfoList *prop_list;
+ ObjectPropertyInfoList *prop;
+ GPtrArray *array;
+ int i;
+
+ driver = qemu_opt_get(opts, "driver");
+ if (driver && is_help_option(driver)) {
+ qdev_print_devinfos(false);
+ return 1;
+ }
+
+ if (!driver || !qemu_opt_has_help_opt(opts)) {
+ return 0;
+ }
+
+ if (!object_class_by_name(driver)) {
+ const char *typename = find_typename_by_alias(driver);
+
+ if (typename) {
+ driver = typename;
+ }
+ }
+
+ prop_list = qmp_device_list_properties(driver, &local_err);
+ if (local_err) {
+ goto error;
+ }
+
+ if (prop_list) {
+ qemu_printf("%s options:\n", driver);
+ } else {
+ qemu_printf("There are no options for %s.\n", driver);
+ }
+ array = g_ptr_array_new();
+ for (prop = prop_list; prop; prop = prop->next) {
+ g_ptr_array_add(array,
+ object_property_help(prop->value->name,
+ prop->value->type,
+ prop->value->default_value,
+ prop->value->description));
+ }
+ g_ptr_array_sort(array, (GCompareFunc)qemu_pstrcmp0);
+ for (i = 0; i < array->len; i++) {
+ qemu_printf("%s\n", (char *)array->pdata[i]);
+ }
+ g_ptr_array_set_free_func(array, g_free);
+ g_ptr_array_free(array, true);
+ qapi_free_ObjectPropertyInfoList(prop_list);
+ return 1;
+
+error:
+ error_report_err(local_err);
+ return 1;
+}
+
+static Object *qdev_get_peripheral(void)
+{
+ static Object *dev;
+
+ if (dev == NULL) {
+ dev = container_get(qdev_get_machine(), "/peripheral");
+ }
+
+ return dev;
+}
+
+static Object *qdev_get_peripheral_anon(void)
+{
+ static Object *dev;
+
+ if (dev == NULL) {
+ dev = container_get(qdev_get_machine(), "/peripheral-anon");
+ }
+
+ return dev;
+}
+
+static void qbus_error_append_bus_list_hint(DeviceState *dev,
+ Error *const *errp)
+{
+ BusState *child;
+ const char *sep = " ";
+
+ error_append_hint(errp, "child buses at \"%s\":",
+ dev->id ? dev->id : object_get_typename(OBJECT(dev)));
+ QLIST_FOREACH(child, &dev->child_bus, sibling) {
+ error_append_hint(errp, "%s\"%s\"", sep, child->name);
+ sep = ", ";
+ }
+ error_append_hint(errp, "\n");
+}
+
+static void qbus_error_append_dev_list_hint(BusState *bus,
+ Error *const *errp)
+{
+ BusChild *kid;
+ const char *sep = " ";
+
+ error_append_hint(errp, "devices at \"%s\":", bus->name);
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ error_append_hint(errp, "%s\"%s\"", sep,
+ object_get_typename(OBJECT(dev)));
+ if (dev->id) {
+ error_append_hint(errp, "/\"%s\"", dev->id);
+ }
+ sep = ", ";
+ }
+ error_append_hint(errp, "\n");
+}
+
+static BusState *qbus_find_bus(DeviceState *dev, char *elem)
+{
+ BusState *child;
+
+ QLIST_FOREACH(child, &dev->child_bus, sibling) {
+ if (strcmp(child->name, elem) == 0) {
+ return child;
+ }
+ }
+ return NULL;
+}
+
+static DeviceState *qbus_find_dev(BusState *bus, char *elem)
+{
+ BusChild *kid;
+
+ /*
+ * try to match in order:
+ * (1) instance id, if present
+ * (2) driver name
+ * (3) driver alias, if present
+ */
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ if (dev->id && strcmp(dev->id, elem) == 0) {
+ return dev;
+ }
+ }
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ if (strcmp(object_get_typename(OBJECT(dev)), elem) == 0) {
+ return dev;
+ }
+ }
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ DeviceClass *dc = DEVICE_GET_CLASS(dev);
+
+ if (qdev_class_has_alias(dc) &&
+ strcmp(qdev_class_get_alias(dc), elem) == 0) {
+ return dev;
+ }
+ }
+ return NULL;
+}
+
+static inline bool qbus_is_full(BusState *bus)
+{
+ BusClass *bus_class = BUS_GET_CLASS(bus);
+ return bus_class->max_dev && bus->num_children >= bus_class->max_dev;
+}
+
+/*
+ * Search the tree rooted at @bus for a bus.
+ * If @name, search for a bus with that name. Note that bus names
+ * need not be unique. Yes, that's screwed up.
+ * Else search for a bus that is a subtype of @bus_typename.
+ * If more than one exists, prefer one that can take another device.
+ * Return the bus if found, else %NULL.
+ */
+static BusState *qbus_find_recursive(BusState *bus, const char *name,
+ const char *bus_typename)
+{
+ BusChild *kid;
+ BusState *pick, *child, *ret;
+ bool match;
+
+ assert(name || bus_typename);
+ if (name) {
+ match = !strcmp(bus->name, name);
+ } else {
+ match = !!object_dynamic_cast(OBJECT(bus), bus_typename);
+ }
+
+ if (match && !qbus_is_full(bus)) {
+ return bus; /* root matches and isn't full */
+ }
+
+ pick = match ? bus : NULL;
+
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ QLIST_FOREACH(child, &dev->child_bus, sibling) {
+ ret = qbus_find_recursive(child, name, bus_typename);
+ if (ret && !qbus_is_full(ret)) {
+ return ret; /* a descendant matches and isn't full */
+ }
+ if (ret && !pick) {
+ pick = ret;
+ }
+ }
+ }
+
+ /* root or a descendant matches, but is full */
+ return pick;
+}
+
+static BusState *qbus_find(const char *path, Error **errp)
+{
+ DeviceState *dev;
+ BusState *bus;
+ char elem[128];
+ int pos, len;
+
+ /* find start element */
+ if (path[0] == '/') {
+ bus = sysbus_get_default();
+ pos = 0;
+ } else {
+ if (sscanf(path, "%127[^/]%n", elem, &len) != 1) {
+ assert(!path[0]);
+ elem[0] = len = 0;
+ }
+ bus = qbus_find_recursive(sysbus_get_default(), elem, NULL);
+ if (!bus) {
+ error_setg(errp, "Bus '%s' not found", elem);
+ return NULL;
+ }
+ pos = len;
+ }
+
+ for (;;) {
+ assert(path[pos] == '/' || !path[pos]);
+ while (path[pos] == '/') {
+ pos++;
+ }
+ if (path[pos] == '\0') {
+ break;
+ }
+
+ /* find device */
+ if (sscanf(path+pos, "%127[^/]%n", elem, &len) != 1) {
+ g_assert_not_reached();
+ elem[0] = len = 0;
+ }
+ pos += len;
+ dev = qbus_find_dev(bus, elem);
+ if (!dev) {
+ error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
+ "Device '%s' not found", elem);
+ qbus_error_append_dev_list_hint(bus, errp);
+ return NULL;
+ }
+
+ assert(path[pos] == '/' || !path[pos]);
+ while (path[pos] == '/') {
+ pos++;
+ }
+ if (path[pos] == '\0') {
+ /* last specified element is a device. If it has exactly
+ * one child bus accept it nevertheless */
+ if (dev->num_child_bus == 1) {
+ bus = QLIST_FIRST(&dev->child_bus);
+ break;
+ }
+ if (dev->num_child_bus) {
+ error_setg(errp, "Device '%s' has multiple child buses",
+ elem);
+ qbus_error_append_bus_list_hint(dev, errp);
+ } else {
+ error_setg(errp, "Device '%s' has no child bus", elem);
+ }
+ return NULL;
+ }
+
+ /* find bus */
+ if (sscanf(path+pos, "%127[^/]%n", elem, &len) != 1) {
+ g_assert_not_reached();
+ elem[0] = len = 0;
+ }
+ pos += len;
+ bus = qbus_find_bus(dev, elem);
+ if (!bus) {
+ error_setg(errp, "Bus '%s' not found", elem);
+ qbus_error_append_bus_list_hint(dev, errp);
+ return NULL;
+ }
+ }
+
+ if (qbus_is_full(bus)) {
+ error_setg(errp, "Bus '%s' is full", path);
+ return NULL;
+ }
+ return bus;
+}
+
+void qdev_set_id(DeviceState *dev, const char *id)
+{
+ if (id) {
+ dev->id = id;
+ }
+
+ if (dev->id) {
+ object_property_add_child(qdev_get_peripheral(), dev->id,
+ OBJECT(dev));
+ } else {
+ static int anon_count;
+ gchar *name = g_strdup_printf("device[%d]", anon_count++);
+ object_property_add_child(qdev_get_peripheral_anon(), name,
+ OBJECT(dev));
+ g_free(name);
+ }
+}
+
+static int is_failover_device(void *opaque, const char *name, const char *value,
+ Error **errp)
+{
+ if (strcmp(name, "failover_pair_id") == 0) {
+ QemuOpts *opts = (QemuOpts *)opaque;
+
+ if (qdev_should_hide_device(opts)) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static bool should_hide_device(QemuOpts *opts)
+{
+ if (qemu_opt_foreach(opts, is_failover_device, opts, NULL) == 0) {
+ return false;
+ }
+ return true;
+}
+
+DeviceState *qdev_device_add(QemuOpts *opts, Error **errp)
+{
+ DeviceClass *dc;
+ const char *driver, *path;
+ DeviceState *dev = NULL;
+ BusState *bus = NULL;
+ bool hide;
+
+ driver = qemu_opt_get(opts, "driver");
+ if (!driver) {
+ error_setg(errp, QERR_MISSING_PARAMETER, "driver");
+ return NULL;
+ }
+
+ /* find driver */
+ dc = qdev_get_device_class(&driver, errp);
+ if (!dc) {
+ return NULL;
+ }
+
+ /* find bus */
+ path = qemu_opt_get(opts, "bus");
+ if (path != NULL) {
+ bus = qbus_find(path, errp);
+ if (!bus) {
+ return NULL;
+ }
+ if (!object_dynamic_cast(OBJECT(bus), dc->bus_type)) {
+ error_setg(errp, "Device '%s' can't go on %s bus",
+ driver, object_get_typename(OBJECT(bus)));
+ return NULL;
+ }
+ } else if (dc->bus_type != NULL) {
+ bus = qbus_find_recursive(sysbus_get_default(), NULL, dc->bus_type);
+ if (!bus || qbus_is_full(bus)) {
+ error_setg(errp, "No '%s' bus found for device '%s'",
+ dc->bus_type, driver);
+ return NULL;
+ }
+ }
+ hide = should_hide_device(opts);
+
+ if ((hide || qdev_hotplug) && bus && !qbus_is_hotpluggable(bus)) {
+ error_setg(errp, QERR_BUS_NO_HOTPLUG, bus->name);
+ return NULL;
+ }
+
+ if (hide) {
+ return NULL;
+ }
+
+ if (!migration_is_idle()) {
+ error_setg(errp, "device_add not allowed while migrating");
+ return NULL;
+ }
+
+ /* create device */
+ dev = qdev_new(driver);
+
+ /* Check whether the hotplug is allowed by the machine */
+ if (qdev_hotplug && !qdev_hotplug_allowed(dev, errp)) {
+ goto err_del_dev;
+ }
+
+ if (!bus && qdev_hotplug && !qdev_get_machine_hotplug_handler(dev)) {
+ /* No bus, no machine hotplug handler --> device is not hotpluggable */
+ error_setg(errp, "Device '%s' can not be hotplugged on this machine",
+ driver);
+ goto err_del_dev;
+ }
+
+ qdev_set_id(dev, qemu_opts_id(opts));
+
+ /* set properties */
+ if (qemu_opt_foreach(opts, set_property, dev, errp)) {
+ goto err_del_dev;
+ }
+
+ dev->opts = opts;
+ if (!qdev_realize(DEVICE(dev), bus, errp)) {
+ dev->opts = NULL;
+ goto err_del_dev;
+ }
+ return dev;
+
+err_del_dev:
+ if (dev) {
+ object_unparent(OBJECT(dev));
+ object_unref(OBJECT(dev));
+ }
+ return NULL;
+}
+
+
+#define qdev_printf(fmt, ...) monitor_printf(mon, "%*s" fmt, indent, "", ## __VA_ARGS__)
+static void qbus_print(Monitor *mon, BusState *bus, int indent);
+
+static void qdev_print_props(Monitor *mon, DeviceState *dev, Property *props,
+ int indent)
+{
+ if (!props)
+ return;
+ for (; props->name; props++) {
+ char *value;
+ char *legacy_name = g_strdup_printf("legacy-%s", props->name);
+
+ if (object_property_get_type(OBJECT(dev), legacy_name, NULL)) {
+ value = object_property_get_str(OBJECT(dev), legacy_name, NULL);
+ } else {
+ value = object_property_print(OBJECT(dev), props->name, true,
+ NULL);
+ }
+ g_free(legacy_name);
+
+ if (!value) {
+ continue;
+ }
+ qdev_printf("%s = %s\n", props->name,
+ *value ? value : "<null>");
+ g_free(value);
+ }
+}
+
+static void bus_print_dev(BusState *bus, Monitor *mon, DeviceState *dev, int indent)
+{
+ BusClass *bc = BUS_GET_CLASS(bus);
+
+ if (bc->print_dev) {
+ bc->print_dev(mon, dev, indent);
+ }
+}
+
+static void qdev_print(Monitor *mon, DeviceState *dev, int indent)
+{
+ ObjectClass *class;
+ BusState *child;
+ NamedGPIOList *ngl;
+ NamedClockList *ncl;
+
+ qdev_printf("dev: %s, id \"%s\"\n", object_get_typename(OBJECT(dev)),
+ dev->id ? dev->id : "");
+ indent += 2;
+ QLIST_FOREACH(ngl, &dev->gpios, node) {
+ if (ngl->num_in) {
+ qdev_printf("gpio-in \"%s\" %d\n", ngl->name ? ngl->name : "",
+ ngl->num_in);
+ }
+ if (ngl->num_out) {
+ qdev_printf("gpio-out \"%s\" %d\n", ngl->name ? ngl->name : "",
+ ngl->num_out);
+ }
+ }
+ QLIST_FOREACH(ncl, &dev->clocks, node) {
+ qdev_printf("clock-%s%s \"%s\" freq_hz=%e\n",
+ ncl->output ? "out" : "in",
+ ncl->alias ? " (alias)" : "",
+ ncl->name,
+ CLOCK_PERIOD_TO_HZ(1.0 * clock_get(ncl->clock)));
+ }
+ class = object_get_class(OBJECT(dev));
+ do {
+ qdev_print_props(mon, dev, DEVICE_CLASS(class)->props_, indent);
+ class = object_class_get_parent(class);
+ } while (class != object_class_by_name(TYPE_DEVICE));
+ bus_print_dev(dev->parent_bus, mon, dev, indent);
+ QLIST_FOREACH(child, &dev->child_bus, sibling) {
+ qbus_print(mon, child, indent);
+ }
+}
+
+static void qbus_print(Monitor *mon, BusState *bus, int indent)
+{
+ BusChild *kid;
+
+ qdev_printf("bus: %s\n", bus->name);
+ indent += 2;
+ qdev_printf("type %s\n", object_get_typename(OBJECT(bus)));
+ QTAILQ_FOREACH(kid, &bus->children, sibling) {
+ DeviceState *dev = kid->child;
+ qdev_print(mon, dev, indent);
+ }
+}
+#undef qdev_printf
+
+void hmp_info_qtree(Monitor *mon, const QDict *qdict)
+{
+ if (sysbus_get_default())
+ qbus_print(mon, sysbus_get_default(), 0);
+}
+
+void hmp_info_qdm(Monitor *mon, const QDict *qdict)
+{
+ qdev_print_devinfos(true);
+}
+
+void qmp_device_add(QDict *qdict, QObject **ret_data, Error **errp)
+{
+ QemuOpts *opts;
+ DeviceState *dev;
+
+ opts = qemu_opts_from_qdict(qemu_find_opts("device"), qdict, errp);
+ if (!opts) {
+ return;
+ }
+ if (!monitor_cur_is_qmp() && qdev_device_help(opts)) {
+ qemu_opts_del(opts);
+ return;
+ }
+ dev = qdev_device_add(opts, errp);
+
+ /*
+ * Drain all pending RCU callbacks. This is done because
+ * some bus related operations can delay a device removal
+ * (in this case this can happen if device is added and then
+ * removed due to a configuration error)
+ * to a RCU callback, but user might expect that this interface
+ * will finish its job completely once qmp command returns result
+ * to the user
+ */
+ drain_call_rcu();
+
+ if (!dev) {
+ qemu_opts_del(opts);
+ return;
+ }
+ object_unref(OBJECT(dev));
+}
+
+static DeviceState *find_device_state(const char *id, Error **errp)
+{
+ Object *obj;
+
+ if (id[0] == '/') {
+ obj = object_resolve_path(id, NULL);
+ } else {
+ char *root_path = object_get_canonical_path(qdev_get_peripheral());
+ char *path = g_strdup_printf("%s/%s", root_path, id);
+
+ g_free(root_path);
+ obj = object_resolve_path_type(path, TYPE_DEVICE, NULL);
+ g_free(path);
+ }
+
+ if (!obj) {
+ error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
+ "Device '%s' not found", id);
+ return NULL;
+ }
+
+ if (!object_dynamic_cast(obj, TYPE_DEVICE)) {
+ error_setg(errp, "%s is not a hotpluggable device", id);
+ return NULL;
+ }
+
+ return DEVICE(obj);
+}
+
+void qdev_unplug(DeviceState *dev, Error **errp)
+{
+ DeviceClass *dc = DEVICE_GET_CLASS(dev);
+ HotplugHandler *hotplug_ctrl;
+ HotplugHandlerClass *hdc;
+ Error *local_err = NULL;
+
+ if (dev->parent_bus && !qbus_is_hotpluggable(dev->parent_bus)) {
+ error_setg(errp, QERR_BUS_NO_HOTPLUG, dev->parent_bus->name);
+ return;
+ }
+
+ if (!dc->hotpluggable) {
+ error_setg(errp, QERR_DEVICE_NO_HOTPLUG,
+ object_get_typename(OBJECT(dev)));
+ return;
+ }
+
+ if (!migration_is_idle() && !dev->allow_unplug_during_migration) {
+ error_setg(errp, "device_del not allowed while migrating");
+ return;
+ }
+
+ qdev_hot_removed = true;
+
+ 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, &local_err);
+ } else {
+ hotplug_handler_unplug(hotplug_ctrl, dev, &local_err);
+ if (!local_err) {
+ object_unparent(OBJECT(dev));
+ }
+ }
+ error_propagate(errp, local_err);
+}
+
+void qmp_device_del(const char *id, Error **errp)
+{
+ DeviceState *dev = find_device_state(id, errp);
+ if (dev != NULL) {
+ if (dev->pending_deleted_event) {
+ error_setg(errp, "Device %s is already in the "
+ "process of unplug", id);
+ return;
+ }
+
+ qdev_unplug(dev, errp);
+ }
+}
+
+void hmp_device_add(Monitor *mon, const QDict *qdict)
+{
+ Error *err = NULL;
+
+ qmp_device_add((QDict *)qdict, NULL, &err);
+ hmp_handle_error(mon, err);
+}
+
+void hmp_device_del(Monitor *mon, const QDict *qdict)
+{
+ const char *id = qdict_get_str(qdict, "id");
+ Error *err = NULL;
+
+ qmp_device_del(id, &err);
+ hmp_handle_error(mon, err);
+}
+
+BlockBackend *blk_by_qdev_id(const char *id, Error **errp)
+{
+ DeviceState *dev;
+ BlockBackend *blk;
+
+ dev = find_device_state(id, errp);
+ if (dev == NULL) {
+ return NULL;
+ }
+
+ blk = blk_by_dev(dev);
+ if (!blk) {
+ error_setg(errp, "Device does not have a block device backend");
+ }
+ return blk;
+}
+
+void qdev_machine_init(void)
+{
+ qdev_get_peripheral_anon();
+ qdev_get_peripheral();
+}
+
+QemuOptsList qemu_device_opts = {
+ .name = "device",
+ .implied_opt_name = "driver",
+ .head = QTAILQ_HEAD_INITIALIZER(qemu_device_opts.head),
+ .desc = {
+ /*
+ * no elements => accept any
+ * sanity checking will happen later
+ * when setting device properties
+ */
+ { /* end of list */ }
+ },
+};
+
+QemuOptsList qemu_global_opts = {
+ .name = "global",
+ .head = QTAILQ_HEAD_INITIALIZER(qemu_global_opts.head),
+ .desc = {
+ {
+ .name = "driver",
+ .type = QEMU_OPT_STRING,
+ },{
+ .name = "property",
+ .type = QEMU_OPT_STRING,
+ },{
+ .name = "value",
+ .type = QEMU_OPT_STRING,
+ },
+ { /* end of list */ }
+ },
+};
+
+int qemu_global_option(const char *str)
+{
+ char driver[64], property[64];
+ QemuOpts *opts;
+ int rc, offset;
+
+ rc = sscanf(str, "%63[^.=].%63[^=]%n", driver, property, &offset);
+ if (rc == 2 && str[offset] == '=') {
+ opts = qemu_opts_create(&qemu_global_opts, NULL, 0, &error_abort);
+ qemu_opt_set(opts, "driver", driver, &error_abort);
+ qemu_opt_set(opts, "property", property, &error_abort);
+ qemu_opt_set(opts, "value", str + offset + 1, &error_abort);
+ return 0;
+ }
+
+ opts = qemu_opts_parse_noisily(&qemu_global_opts, str, false);
+ if (!opts) {
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/softmmu/qemu-seccomp.c b/softmmu/qemu-seccomp.c
new file mode 100644
index 0000000..8325ecb
--- /dev/null
+++ b/softmmu/qemu-seccomp.c
@@ -0,0 +1,331 @@
+/*
+ * QEMU seccomp mode 2 support with libseccomp
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ * Eduardo Otubo <eotubo@br.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2. See
+ * the COPYING file in the top-level directory.
+ *
+ * Contributions after 2012-01-13 are licensed under the terms of the
+ * GNU GPL, version 2 or (at your option) any later version.
+ */
+
+#include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "qemu/config-file.h"
+#include "qemu/option.h"
+#include "qemu/module.h"
+#include <sys/prctl.h>
+#include <seccomp.h>
+#include "sysemu/seccomp.h"
+#include <linux/seccomp.h>
+
+/* For some architectures (notably ARM) cacheflush is not supported until
+ * libseccomp 2.2.3, but configure enforces that we are using a more recent
+ * version on those hosts, so it is OK for this check to be less strict.
+ */
+#if SCMP_VER_MAJOR >= 3
+ #define HAVE_CACHEFLUSH
+#elif SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR >= 2
+ #define HAVE_CACHEFLUSH
+#endif
+
+struct QemuSeccompSyscall {
+ int32_t num;
+ uint8_t set;
+ uint8_t narg;
+ const struct scmp_arg_cmp *arg_cmp;
+};
+
+const struct scmp_arg_cmp sched_setscheduler_arg[] = {
+ /* was SCMP_A1(SCMP_CMP_NE, SCHED_IDLE), but expanded due to GCC 4.x bug */
+ { .arg = 1, .op = SCMP_CMP_NE, .datum_a = SCHED_IDLE }
+};
+
+static const struct QemuSeccompSyscall blacklist[] = {
+ /* default set of syscalls to blacklist */
+ { SCMP_SYS(reboot), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(swapon), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(swapoff), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(syslog), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(mount), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(umount), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(kexec_load), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(afs_syscall), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(break), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(ftime), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(getpmsg), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(gtty), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(lock), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(mpx), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(prof), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(profil), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(putpmsg), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(security), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(stty), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(tuxcall), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(ulimit), QEMU_SECCOMP_SET_DEFAULT },
+ { SCMP_SYS(vserver), QEMU_SECCOMP_SET_DEFAULT },
+ /* obsolete */
+ { SCMP_SYS(readdir), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(_sysctl), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(bdflush), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(create_module), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(get_kernel_syms), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(query_module), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(sgetmask), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(ssetmask), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(sysfs), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(uselib), QEMU_SECCOMP_SET_OBSOLETE },
+ { SCMP_SYS(ustat), QEMU_SECCOMP_SET_OBSOLETE },
+ /* privileged */
+ { SCMP_SYS(setuid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setgid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setpgid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setsid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setreuid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setregid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setresuid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setresgid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setfsuid), QEMU_SECCOMP_SET_PRIVILEGED },
+ { SCMP_SYS(setfsgid), QEMU_SECCOMP_SET_PRIVILEGED },
+ /* spawn */
+ { SCMP_SYS(fork), QEMU_SECCOMP_SET_SPAWN },
+ { SCMP_SYS(vfork), QEMU_SECCOMP_SET_SPAWN },
+ { SCMP_SYS(execve), QEMU_SECCOMP_SET_SPAWN },
+ /* resource control */
+ { SCMP_SYS(getpriority), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(setpriority), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_setparam), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_getparam), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_setscheduler), QEMU_SECCOMP_SET_RESOURCECTL,
+ ARRAY_SIZE(sched_setscheduler_arg), sched_setscheduler_arg },
+ { SCMP_SYS(sched_getscheduler), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_setaffinity), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_getaffinity), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_get_priority_max), QEMU_SECCOMP_SET_RESOURCECTL },
+ { SCMP_SYS(sched_get_priority_min), QEMU_SECCOMP_SET_RESOURCECTL },
+};
+
+static inline __attribute__((unused)) int
+qemu_seccomp(unsigned int operation, unsigned int flags, void *args)
+{
+#ifdef __NR_seccomp
+ return syscall(__NR_seccomp, operation, flags, args);
+#else
+ errno = ENOSYS;
+ return -1;
+#endif
+}
+
+static uint32_t qemu_seccomp_get_action(int set)
+{
+ switch (set) {
+ case QEMU_SECCOMP_SET_DEFAULT:
+ case QEMU_SECCOMP_SET_OBSOLETE:
+ case QEMU_SECCOMP_SET_PRIVILEGED:
+ case QEMU_SECCOMP_SET_SPAWN: {
+#if defined(SECCOMP_GET_ACTION_AVAIL) && defined(SCMP_ACT_KILL_PROCESS) && \
+ defined(SECCOMP_RET_KILL_PROCESS)
+ static int kill_process = -1;
+ if (kill_process == -1) {
+ uint32_t action = SECCOMP_RET_KILL_PROCESS;
+
+ if (qemu_seccomp(SECCOMP_GET_ACTION_AVAIL, 0, &action) == 0) {
+ kill_process = 1;
+ } else {
+ kill_process = 0;
+ }
+ }
+ if (kill_process == 1) {
+ return SCMP_ACT_KILL_PROCESS;
+ }
+#endif
+ return SCMP_ACT_TRAP;
+ }
+
+ case QEMU_SECCOMP_SET_RESOURCECTL:
+ return SCMP_ACT_ERRNO(EPERM);
+
+ default:
+ g_assert_not_reached();
+ }
+}
+
+
+static int seccomp_start(uint32_t seccomp_opts, Error **errp)
+{
+ int rc = -1;
+ unsigned int i = 0;
+ scmp_filter_ctx ctx;
+
+ ctx = seccomp_init(SCMP_ACT_ALLOW);
+ if (ctx == NULL) {
+ error_setg(errp, "failed to initialize seccomp context");
+ goto seccomp_return;
+ }
+
+ rc = seccomp_attr_set(ctx, SCMP_FLTATR_CTL_TSYNC, 1);
+ if (rc != 0) {
+ error_setg_errno(errp, -rc,
+ "failed to set seccomp thread synchronization");
+ goto seccomp_return;
+ }
+
+ for (i = 0; i < ARRAY_SIZE(blacklist); i++) {
+ uint32_t action;
+ if (!(seccomp_opts & blacklist[i].set)) {
+ continue;
+ }
+
+ action = qemu_seccomp_get_action(blacklist[i].set);
+ rc = seccomp_rule_add_array(ctx, action, blacklist[i].num,
+ blacklist[i].narg, blacklist[i].arg_cmp);
+ if (rc < 0) {
+ error_setg_errno(errp, -rc,
+ "failed to add seccomp blacklist rules");
+ goto seccomp_return;
+ }
+ }
+
+ rc = seccomp_load(ctx);
+ if (rc < 0) {
+ error_setg_errno(errp, -rc,
+ "failed to load seccomp syscall filter in kernel");
+ }
+
+ seccomp_return:
+ seccomp_release(ctx);
+ return rc < 0 ? -1 : 0;
+}
+
+#ifdef CONFIG_SECCOMP
+int parse_sandbox(void *opaque, QemuOpts *opts, Error **errp)
+{
+ if (qemu_opt_get_bool(opts, "enable", false)) {
+ uint32_t seccomp_opts = QEMU_SECCOMP_SET_DEFAULT
+ | QEMU_SECCOMP_SET_OBSOLETE;
+ const char *value = NULL;
+
+ value = qemu_opt_get(opts, "obsolete");
+ if (value) {
+ if (g_str_equal(value, "allow")) {
+ seccomp_opts &= ~QEMU_SECCOMP_SET_OBSOLETE;
+ } else if (g_str_equal(value, "deny")) {
+ /* this is the default option, this if is here
+ * to provide a little bit of consistency for
+ * the command line */
+ } else {
+ error_setg(errp, "invalid argument for obsolete");
+ return -1;
+ }
+ }
+
+ value = qemu_opt_get(opts, "elevateprivileges");
+ if (value) {
+ if (g_str_equal(value, "deny")) {
+ seccomp_opts |= QEMU_SECCOMP_SET_PRIVILEGED;
+ } else if (g_str_equal(value, "children")) {
+ seccomp_opts |= QEMU_SECCOMP_SET_PRIVILEGED;
+
+ /* calling prctl directly because we're
+ * not sure if host has CAP_SYS_ADMIN set*/
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1)) {
+ error_setg(errp, "failed to set no_new_privs aborting");
+ return -1;
+ }
+ } else if (g_str_equal(value, "allow")) {
+ /* default value */
+ } else {
+ error_setg(errp, "invalid argument for elevateprivileges");
+ return -1;
+ }
+ }
+
+ value = qemu_opt_get(opts, "spawn");
+ if (value) {
+ if (g_str_equal(value, "deny")) {
+ seccomp_opts |= QEMU_SECCOMP_SET_SPAWN;
+ } else if (g_str_equal(value, "allow")) {
+ /* default value */
+ } else {
+ error_setg(errp, "invalid argument for spawn");
+ return -1;
+ }
+ }
+
+ value = qemu_opt_get(opts, "resourcecontrol");
+ if (value) {
+ if (g_str_equal(value, "deny")) {
+ seccomp_opts |= QEMU_SECCOMP_SET_RESOURCECTL;
+ } else if (g_str_equal(value, "allow")) {
+ /* default value */
+ } else {
+ error_setg(errp, "invalid argument for resourcecontrol");
+ return -1;
+ }
+ }
+
+ if (seccomp_start(seccomp_opts, errp) < 0) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static QemuOptsList qemu_sandbox_opts = {
+ .name = "sandbox",
+ .implied_opt_name = "enable",
+ .head = QTAILQ_HEAD_INITIALIZER(qemu_sandbox_opts.head),
+ .desc = {
+ {
+ .name = "enable",
+ .type = QEMU_OPT_BOOL,
+ },
+ {
+ .name = "obsolete",
+ .type = QEMU_OPT_STRING,
+ },
+ {
+ .name = "elevateprivileges",
+ .type = QEMU_OPT_STRING,
+ },
+ {
+ .name = "spawn",
+ .type = QEMU_OPT_STRING,
+ },
+ {
+ .name = "resourcecontrol",
+ .type = QEMU_OPT_STRING,
+ },
+ { /* end of list */ }
+ },
+};
+
+static void seccomp_register(void)
+{
+ bool add = false;
+
+ /* FIXME: use seccomp_api_get() >= 2 check when released */
+
+#if defined(SECCOMP_FILTER_FLAG_TSYNC)
+ int check;
+
+ /* check host TSYNC capability, it returns errno == ENOSYS if unavailable */
+ check = qemu_seccomp(SECCOMP_SET_MODE_FILTER,
+ SECCOMP_FILTER_FLAG_TSYNC, NULL);
+ if (check < 0 && errno == EFAULT) {
+ add = true;
+ }
+#endif
+
+ if (add) {
+ qemu_add_opts(&qemu_sandbox_opts);
+ }
+}
+opts_init(seccomp_register);
+#endif
diff --git a/softmmu/qtest.c b/softmmu/qtest.c
index 0d43cf8..2c6e8dc 100644
--- a/softmmu/qtest.c
+++ b/softmmu/qtest.c
@@ -49,92 +49,139 @@ static void *qtest_server_send_opaque;
#define FMT_timeval "%ld.%06ld"
/**
- * QTest Protocol
+ * DOC: QTest Protocol
*
* Line based protocol, request/response based. Server can send async messages
* so clients should always handle many async messages before the response
* comes in.
*
* Valid requests
+ * ^^^^^^^^^^^^^^
*
* Clock management:
+ * """""""""""""""""
*
* The qtest client is completely in charge of the QEMU_CLOCK_VIRTUAL. qtest commands
* let you adjust the value of the clock (monotonically). All the commands
* return the current value of the clock in nanoseconds.
*
+ * .. code-block:: none
+ *
* > clock_step
* < OK VALUE
*
- * Advance the clock to the next deadline. Useful when waiting for
- * asynchronous events.
+ * Advance the clock to the next deadline. Useful when waiting for
+ * asynchronous events.
+ *
+ * .. code-block:: none
*
* > clock_step NS
* < OK VALUE
*
- * Advance the clock by NS nanoseconds.
+ * Advance the clock by NS nanoseconds.
+ *
+ * .. code-block:: none
*
* > clock_set NS
* < OK VALUE
*
- * Advance the clock to NS nanoseconds (do nothing if it's already past).
+ * Advance the clock to NS nanoseconds (do nothing if it's already past).
*
* PIO and memory access:
+ * """"""""""""""""""""""
+ *
+ * .. code-block:: none
*
* > outb ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > outw ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > outl ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > inb ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > inw ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > inl ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > writeb ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > writew ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > writel ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > writeq ADDR VALUE
* < OK
*
+ * .. code-block:: none
+ *
* > readb ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > readw ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > readl ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > readq ADDR
* < OK VALUE
*
+ * .. code-block:: none
+ *
* > read ADDR SIZE
* < OK DATA
*
+ * .. code-block:: none
+ *
* > write ADDR SIZE DATA
* < OK
*
+ * .. code-block:: none
+ *
* > b64read ADDR SIZE
* < OK B64_DATA
*
+ * .. code-block:: none
+ *
* > b64write ADDR SIZE B64_DATA
* < OK
*
+ * .. code-block:: none
+ *
* > memset ADDR SIZE VALUE
* < OK
*
@@ -149,16 +196,21 @@ static void *qtest_server_send_opaque;
* If the sizes do not match, the data will be truncated.
*
* IRQ management:
+ * """""""""""""""
+ *
+ * .. code-block:: none
*
* > irq_intercept_in QOM-PATH
* < OK
*
+ * .. code-block:: none
+ *
* > irq_intercept_out QOM-PATH
* < OK
*
* Attach to the gpio-in (resp. gpio-out) pins exported by the device at
* QOM-PATH. When the pin is triggered, one of the following async messages
- * will be printed to the qtest stream:
+ * will be printed to the qtest stream::
*
* IRQ raise NUM
* IRQ lower NUM
@@ -168,12 +220,15 @@ static void *qtest_server_send_opaque;
* NUM=0 even though it is remapped to GSI 2).
*
* Setting interrupt level:
+ * """"""""""""""""""""""""
+ *
+ * .. code-block:: none
*
* > set_irq_in QOM-PATH NAME NUM LEVEL
* < OK
*
- * where NAME is the name of the irq/gpio list, NUM is an IRQ number and
- * LEVEL is an signed integer IRQ level.
+ * where NAME is the name of the irq/gpio list, NUM is an IRQ number and
+ * LEVEL is an signed integer IRQ level.
*
* Forcibly set the given interrupt pin to the given level.
*
diff --git a/softmmu/tpm.c b/softmmu/tpm.c
new file mode 100644
index 0000000..cab2063
--- /dev/null
+++ b/softmmu/tpm.c
@@ -0,0 +1,265 @@
+/*
+ * TPM configuration
+ *
+ * Copyright (C) 2011-2013 IBM Corporation
+ *
+ * Authors:
+ * Stefan Berger <stefanb@us.ibm.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.
+ *
+ * Based on net.c
+ */
+
+#include "qemu/osdep.h"
+
+#include "qapi/error.h"
+#include "qapi/qapi-commands-tpm.h"
+#include "qapi/qmp/qerror.h"
+#include "sysemu/tpm_backend.h"
+#include "sysemu/tpm.h"
+#include "qemu/config-file.h"
+#include "qemu/error-report.h"
+
+static QLIST_HEAD(, TPMBackend) tpm_backends =
+ QLIST_HEAD_INITIALIZER(tpm_backends);
+
+static const TPMBackendClass *
+tpm_be_find_by_type(enum TpmType type)
+{
+ ObjectClass *oc;
+ char *typename = g_strdup_printf("tpm-%s", TpmType_str(type));
+
+ oc = object_class_by_name(typename);
+ g_free(typename);
+
+ if (!object_class_dynamic_cast(oc, TYPE_TPM_BACKEND)) {
+ return NULL;
+ }
+
+ return TPM_BACKEND_CLASS(oc);
+}
+
+/*
+ * Walk the list of available TPM backend drivers and display them on the
+ * screen.
+ */
+static void tpm_display_backend_drivers(void)
+{
+ bool got_one = false;
+ int i;
+
+ for (i = 0; i < TPM_TYPE__MAX; i++) {
+ const TPMBackendClass *bc = tpm_be_find_by_type(i);
+ if (!bc) {
+ continue;
+ }
+ if (!got_one) {
+ error_printf("Supported TPM types (choose only one):\n");
+ got_one = true;
+ }
+ error_printf("%12s %s\n", TpmType_str(i), bc->desc);
+ }
+ if (!got_one) {
+ error_printf("No TPM backend types are available\n");
+ }
+}
+
+/*
+ * Find the TPM with the given Id
+ */
+TPMBackend *qemu_find_tpm_be(const char *id)
+{
+ TPMBackend *drv;
+
+ if (id) {
+ QLIST_FOREACH(drv, &tpm_backends, list) {
+ if (!strcmp(drv->id, id)) {
+ return drv;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+static int tpm_init_tpmdev(void *dummy, QemuOpts *opts, Error **errp)
+{
+ /*
+ * Use of error_report() in a function with an Error ** parameter
+ * is suspicious. It is okay here. The parameter only exists to
+ * make the function usable with qemu_opts_foreach(). It is not
+ * actually used.
+ */
+ const char *value;
+ const char *id;
+ const TPMBackendClass *be;
+ TPMBackend *drv;
+ Error *local_err = NULL;
+ int i;
+
+ if (!QLIST_EMPTY(&tpm_backends)) {
+ error_report("Only one TPM is allowed.");
+ return 1;
+ }
+
+ id = qemu_opts_id(opts);
+ if (id == NULL) {
+ error_report(QERR_MISSING_PARAMETER, "id");
+ return 1;
+ }
+
+ value = qemu_opt_get(opts, "type");
+ if (!value) {
+ error_report(QERR_MISSING_PARAMETER, "type");
+ tpm_display_backend_drivers();
+ return 1;
+ }
+
+ i = qapi_enum_parse(&TpmType_lookup, value, -1, NULL);
+ be = i >= 0 ? tpm_be_find_by_type(i) : NULL;
+ if (be == NULL) {
+ error_report(QERR_INVALID_PARAMETER_VALUE,
+ "type", "a TPM backend type");
+ tpm_display_backend_drivers();
+ return 1;
+ }
+
+ /* validate backend specific opts */
+ if (!qemu_opts_validate(opts, be->opts, &local_err)) {
+ error_report_err(local_err);
+ return 1;
+ }
+
+ drv = be->create(opts);
+ if (!drv) {
+ return 1;
+ }
+
+ drv->id = g_strdup(id);
+ QLIST_INSERT_HEAD(&tpm_backends, drv, list);
+
+ return 0;
+}
+
+/*
+ * Walk the list of TPM backend drivers that are in use and call their
+ * destroy function to have them cleaned up.
+ */
+void tpm_cleanup(void)
+{
+ TPMBackend *drv, *next;
+
+ QLIST_FOREACH_SAFE(drv, &tpm_backends, list, next) {
+ QLIST_REMOVE(drv, list);
+ object_unref(OBJECT(drv));
+ }
+}
+
+/*
+ * Initialize the TPM. Process the tpmdev command line options describing the
+ * TPM backend.
+ */
+int tpm_init(void)
+{
+ if (qemu_opts_foreach(qemu_find_opts("tpmdev"),
+ tpm_init_tpmdev, NULL, NULL)) {
+ return -1;
+ }
+
+ return 0;
+}
+
+/*
+ * Parse the TPM configuration options.
+ * To display all available TPM backends the user may use '-tpmdev help'
+ */
+int tpm_config_parse(QemuOptsList *opts_list, const char *optarg)
+{
+ QemuOpts *opts;
+
+ if (!strcmp(optarg, "help")) {
+ tpm_display_backend_drivers();
+ return -1;
+ }
+ opts = qemu_opts_parse_noisily(opts_list, optarg, true);
+ if (!opts) {
+ return -1;
+ }
+ return 0;
+}
+
+/*
+ * Walk the list of active TPM backends and collect information about them.
+ */
+TPMInfoList *qmp_query_tpm(Error **errp)
+{
+ TPMBackend *drv;
+ TPMInfoList *info, *head = NULL, *cur_item = NULL;
+
+ QLIST_FOREACH(drv, &tpm_backends, list) {
+ if (!drv->tpmif) {
+ continue;
+ }
+
+ info = g_new0(TPMInfoList, 1);
+ info->value = tpm_backend_query_tpm(drv);
+
+ if (!cur_item) {
+ head = cur_item = info;
+ } else {
+ cur_item->next = info;
+ cur_item = info;
+ }
+ }
+
+ return head;
+}
+
+TpmTypeList *qmp_query_tpm_types(Error **errp)
+{
+ unsigned int i = 0;
+ TpmTypeList *head = NULL, *prev = NULL, *cur_item;
+
+ for (i = 0; i < TPM_TYPE__MAX; i++) {
+ if (!tpm_be_find_by_type(i)) {
+ continue;
+ }
+ cur_item = g_new0(TpmTypeList, 1);
+ cur_item->value = i;
+
+ if (prev) {
+ prev->next = cur_item;
+ }
+ if (!head) {
+ head = cur_item;
+ }
+ prev = cur_item;
+ }
+
+ return head;
+}
+TpmModelList *qmp_query_tpm_models(Error **errp)
+{
+ TpmModelList *head = NULL, *prev = NULL, *cur_item;
+ GSList *e, *l = object_class_get_list(TYPE_TPM_IF, false);
+
+ for (e = l; e; e = e->next) {
+ TPMIfClass *c = TPM_IF_CLASS(e->data);
+
+ cur_item = g_new0(TpmModelList, 1);
+ cur_item->value = c->model;
+
+ if (prev) {
+ prev->next = cur_item;
+ }
+ if (!head) {
+ head = cur_item;
+ }
+ prev = cur_item;
+ }
+ g_slist_free(l);
+
+ return head;
+}