Skip to contentSkip to conversation

Plugin support

RFC In review Emilio G. Cota 6 participants 63 messages Dec 9, 2018 – May 20, 2019

Subsystems (2)
lore
Share & tools
lore
#1 lore raw

RFC v2 1/38 trace: expand mem_info:size_shift to 3 bits

In reply to Emilio G. Cota

This will allow us to trace 16B-long memory accesses.

While at it, add some defines for the mem_info bits and simplify trace_mem_get_info by making it a wrapper around trace_mem_build_info.

---
 trace-events | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
trace-events +1 -1
index 4fd2cb4b97..9d65d472d2 100644
@@ -151,7 +151,7 @@ vcpu guest_cpu_reset(void)
 # Access information can be parsed as:
 #
 # struct mem_info {
-#     uint8_t size_shift : 2; /* interpreted as "1 << size_shift" bytes */
+#     uint8_t size_shift : 3; /* interpreted as "1 << size_shift" bytes */
 #     bool    sign_extend: 1; /* sign-extended */
 #     uint8_t endianness : 1; /* 0: little, 1: big */
 #     bool    store      : 1; /* wheter it's a store operation */
Signature · 1 line
2.17.1
#3 lore raw

RFC v2 2/38 tcg/README: fix typo s/afterwise/afterwards/

In reply to Emilio G. Cota

Afterwise is "wise after the fact", as in "hindsight". Here we meant "afterwards" (as in "subsequently"). Fix it.

---
 tcg/README | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tcg/README +1 -1
index d22ee084b8..3fa8a7059f 100644
@@ -101,7 +101,7 @@ This can be overridden using the following function modifiers:
   canonical locations before calling the helper.
 - TCG_CALL_NO_WRITE_GLOBALS means that the helper does not modify any globals.
   They will only be saved to their canonical location before calling helpers,
-  but they won't be reloaded afterwise.
+  but they won't be reloaded afterwards.
 - TCG_CALL_NO_SIDE_EFFECTS means that the call to the function is removed if
   the return value is not used.
 
Signature · 1 line
2.17.1
#6 lore raw

RFC v2 4/38 translate-all: use cpu_in_exclusive_work_context() in tb_flush

In reply to Emilio G. Cota

tb_flush will be called by the plugin module from a safe work environment. Prepare for that.

---
 accel/tcg/translate-all.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
accel/tcg/translate-all.c +7 -2
index 038d82fdb5..62d5e13185 100644
@@ -1269,8 +1269,13 @@ void tb_flush(CPUState *cpu)
 {
     if (tcg_enabled()) {
         unsigned tb_flush_count = atomic_mb_read(&tb_ctx.tb_flush_count);
-        async_safe_run_on_cpu(cpu, do_tb_flush,
-                              RUN_ON_CPU_HOST_INT(tb_flush_count));
+
+        if (cpu_in_exclusive_work_context(cpu)) {
+            do_tb_flush(cpu, RUN_ON_CPU_HOST_INT(tb_flush_count));
+        } else {
+            async_safe_run_on_cpu(cpu, do_tb_flush,
+                                  RUN_ON_CPU_HOST_INT(tb_flush_count));
+        }
     }
 }
 
Signature · 1 line
2.17.1
#29 lore raw

RFC v2 11/38 tcg: add tcg_gen_st_ptr

In reply to Emilio G. Cota

Will gain a user soon.

---
 tcg/tcg-op.h | 5 +++++
 1 file changed, 5 insertions(+)
tcg/tcg-op.h +5 -0
index e2948b10a2..d3c79a6cb2 100644
@@ -1219,6 +1219,11 @@ static inline void tcg_gen_ld_ptr(TCGv_ptr r, TCGv_ptr a, intptr_t o)
     glue(tcg_gen_ld_,PTR)((NAT)r, a, o);
 }
 
+static inline void tcg_gen_st_ptr(TCGv_ptr r, TCGv_ptr a, intptr_t o)
+{
+    glue(tcg_gen_st_, PTR)((NAT)r, a, o);
+}
+
 static inline void tcg_gen_discard_ptr(TCGv_ptr a)
 {
     glue(tcg_gen_discard_,PTR)((NAT)a);
Signature · 1 line
2.17.1
#0 lore raw

v2 cover Plugin support

v1: https://lists.gnu.org/archive/html/qemu-devel/2018-10/msg05682.html

Changes since v1:

- Drop the 2-pass translation. Instead, empty instrumentation is injected during translation. If it turns out that this empty instrumentation is not needed, it is removed from the output. For this, add 2 TCG ops that mark the beginning and end of this empty instrumentation.

This is cleaner than 2-pass translation, although it ends up being quite a bit more code, since we have
to copy backend TCG ops, which is tedious. Performance-wise, it is at worst ~9% slower (~1.3% avg) than 2-pass for SPEC06int:

    https://imgur.com/a/bUNox3H

This is for an "empty" plugin (also added to tests/plugin/empty.c). That is, it subscribes to TB translation events and does nothing with them (i.e. no execution-time subscriptions).
This means the empty instrumentation has to be injected and then removed, which is the worst-case scenario since all the injection work is wasted.

- Add QTAILQ_REMOVE_SEVERAL, which helps speed up the removal of empty instrumentation.

- Drop the "TCG runtime helper" support. We do not need it for empty instrumentation; we just replace the function pointer in the copied "call" op directly.
+ To detect when an instruction uses helpers, just strncmp the helper's name against "plugin_".

- Drop tb->plugin_mask. Instead, read cpu->plugin_mask from translator_loop.

- Drop the xxhash patches, since I submitted those as a separate series.

- Move a lot of plugin-related code from translator.c to plugin-gen.c, leaving only a few function calls in translator.c.

- Add support for only subscribing to an instruction's reads or writes. This is implemented via a flag added to the memory registration functions of the public API.

- Disentangle callbacks into separate arrays. Instead of just having 3 arrays (tb, insn and mem callbacks), have 5 arrays (tb, insn, virt. mem, hostaddr mem) of 2 arrays each (udata_cb and inline). This takes a bit more space per TB, but note that this struct is allocated only once in each TCGContext. OTOH, it makes the code much simpler. The union in struct dyn_cb remains, since for instrumenting memory accesses from helpers we still coalesce all types of memory callbacks into a single array.

- Add get_page_addr_code_hostp to get the host address of code from common code. Use this to export the host address of instructions (qemu_plugin_insn_haddr() added to the public API).

- Define TCGMemOp MO_HADDR. If set, the TCG backend copies on a TLB hit the corresponding host address to env->hostaddr. This allows us to only do this copy when needed.

- Use helpers for reading and setting env->hostaddr, so that we minimize the use of #ifdef CONFIG_PLUGIN.

- Only define env->hostaddr if CONFIG_PLUGIN.

- Drop the trailing 'S' in CONFIG_PLUGINS: it is now CONFIG_PLUGIN.

- Drop a few optional features from the RFC:
+ lockstep execution
+ plugin-chan + guest hooks
+ virtual clock control

- Define translator_ld* helpers and use them, as suggested by Alex and rth. All target ISAs that use translator_loop have been converted, except s390x and mips.

- Do not bloat TCGContext if !CONFIG_PLUGIN.

- Define TCGContext.plugin_tb as a pointer, instead of the whole struct.

- Test on 32-bit and 64-bit hosts (i386, x86_64, ppc64, aarch64).

- Add cpu_in_exclusive_work_context() and use it in tb_flush(), as suggested by Alex.

- configure fixes, including MacOSX builds thanks to Roman's help.

- Remove macros in atomic_template.h, as suggested by Alex. Turns out they aren't needed, inlines are enough.

- Fixed a bug by which cpu->plugin_mem was not being cleared if the instruction that used helpers was the last one in a TB (e.g. an exception). Fix it by adding checks (1) when returning from longjmp, and (2) when finishing a TB from tcg, so that we're sure to leave cpu->plugin_mem in a good state. (I noticed the bug by uninstalling a plugin that had registered memory callbacks, which resulted in callbacks to the uninstalled [dlclose'd] plugin.)

- Make sure tcg_ctx->plugin_mem_cb is always NULL after finishing the translation of a TB. This fixes a bug on uninstall.

- Do not abort when qemu_plugin_uninstall is called more than once. This is actually quite common, so just silently return on subsequent calls to uninstall.

- Drop the "qemu"/QEMU from some overly long function/macro names. This applies to qemu-internal files, of course.

- Keep the plugin's argument array in memory until the plugin is uninstalled, so that plugins don't have to strdup their arguments.

- Drop nargs argument from tcg_op_insert_before/after; it's unused.

- Rename plugin-api.h to qemu-plugin.h, which is the same name it gets in the final destination (after `make install').

- Add insn_inline function to the API.

- Add some sample plugins to tests/plugin.

You can fetch this series from:
https://github.com/cota/qemu/tree/plugin-v2

Thanks,

Emilio

---
 .gitignore                                |    2 +
 Makefile                                  |    8 +-
 Makefile.target                           |   18 +
 accel/tcg/Makefile.objs                   |    1 +
 accel/tcg/atomic_template.h               |  117 +++-
 accel/tcg/cpu-exec.c                      |    2 +
 accel/tcg/cputlb.c                        |   23 +-
 accel/tcg/plugin-gen.c                    | 1085 +++++++++++++++++++++++++++++
 accel/tcg/plugin-helpers.h                |    6 +
 accel/tcg/softmmu_template.h              |   43 +-
 accel/tcg/translate-all.c                 |   15 +-
 accel/tcg/translator.c                    |   16 +
 bsd-user/syscall.c                        |   12 +
 configure                                 |   86 ++-
 cpus-common.c                             |    2 +
 cpus.c                                    |   10 +
 exec.c                                    |    2 +
 include/exec/cpu-defs.h                   |    9 +
 include/exec/cpu_ldst.h                   |    9 +
 include/exec/cpu_ldst_template.h          |   43 +-
 include/exec/cpu_ldst_useronly_template.h |   42 +-
 include/exec/exec-all.h                   |   13 +
 include/exec/helper-gen.h                 |    1 +
 include/exec/helper-proto.h               |    1 +
 include/exec/helper-tcg.h                 |    1 +
 include/exec/plugin-gen.h                 |   75 ++
 include/exec/translator.h                 |   28 +
 include/qemu/plugin.h                     |  253 +++++++
 include/qemu/qemu-plugin.h                |  241 +++++++
 include/qemu/queue.h                      |   10 +
 include/qom/cpu.h                         |   19 +
 linux-user/exit.c                         |    1 +
 linux-user/main.c                         |   18 +
 linux-user/syscall.c                      |    3 +
 plugin.c                                  | 1030 +++++++++++++++++++++++++++
 qemu-options.hx                           |   17 +
 qemu-plugins.symbols                      |   34 +
 qom/cpu.c                                 |    2 +
 target/alpha/translate.c                  |    2 +-
 target/arm/translate-a64.c                |    2 +
 target/arm/translate.c                    |    8 +-
 target/hppa/translate.c                   |    2 +-
 target/i386/translate.c                   |   10 +-
 target/m68k/translate.c                   |    2 +-
 target/openrisc/translate.c               |    2 +-
 target/ppc/translate.c                    |    8 +-
 target/riscv/translate.c                  |    2 +-
 target/sh4/translate.c                    |    2 +-
 target/sparc/translate.c                  |    2 +-
 target/xtensa/translate.c                 |    4 +-
 tcg/README                                |    2 +-
 tcg/i386/tcg-target.inc.c                 |    7 +
 tcg/optimize.c                            |    4 +-
 tcg/tcg-op.c                              |   44 +-
 tcg/tcg-op.h                              |   16 +
 tcg/tcg-opc.h                             |    3 +
 tcg/tcg.c                                 |   27 +-
 tcg/tcg.h                                 |   32 +-
 tests/plugin/Makefile                     |   28 +
 tests/plugin/bb.c                         |   66 ++
 tests/plugin/empty.c                      |   30 +
 tests/plugin/insn.c                       |   63 ++
 tests/plugin/mem.c                        |   93 +++
 trace-events                              |    2 +-
 vl.c                                      |   11 +
 65 files changed, 3653 insertions(+), 119 deletions(-)
#4 lore raw

RFC v2 3/38 cpu: introduce cpu_in_exclusive_work_context()

---
 include/qom/cpu.h | 13 +++++++++++++
 cpus-common.c     |  2 ++
 2 files changed, 15 insertions(+)
include/qom/cpu.h +13 -0
index 772cc960fe..fab18089db 100644
@@ -349,6 +349,7 @@ struct CPUState {
     bool thread_kicked;
     bool crash_occurred;
     bool exit_request;
+    bool in_exclusive_work_context;
     uint32_t cflags_next_tb;
     /* updates protected by BQL */
     uint32_t interrupt_request;
@@ -913,6 +914,18 @@ void async_run_on_cpu_no_bql(CPUState *cpu, run_on_cpu_func func,
  */
 void async_safe_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
 
+/**
+ * cpu_in_exclusive_work_context()
+ * @cpu: The vCPU to check
+ *
+ * Returns true if @cpu is an exclusive work context, which has
+ * previously been queued via async_safe_run_on_cpu().
+ */
+static inline bool cpu_in_exclusive_work_context(const CPUState *cpu)
+{
+    return cpu->in_exclusive_work_context;
+}
+
 /**
  * qemu_get_cpu:
  * @index: The CPUState@cpu_index value of the CPU to obtain.
cpus-common.c +2 -0
index 232cb12c46..d6ea42c80c 100644
@@ -370,7 +370,9 @@ static void process_queued_cpu_work_locked(CPUState *cpu)
                 qemu_mutex_unlock_iothread();
             }
             start_exclusive();
+            cpu->in_exclusive_work_context = true;
             wi->func(cpu, wi->data);
+            cpu->in_exclusive_work_context = false;
             end_exclusive();
             if (has_bql) {
                 qemu_mutex_lock_iothread();
Signature · 1 line
2.17.1
#8 lore raw

RFC v2 5/38 plugin: add user-facing API

In reply to Emilio G. Cota

Add the API first to ease review.

---
 include/qemu/qemu-plugin.h | 241 +++++++++++++++++++++++++++++++++++++
 1 file changed, 241 insertions(+)
 create mode 100644 include/qemu/qemu-plugin.h
include/qemu/qemu-plugin.h new file +241 -0
new file mode 100644
index 0000000000..6c67211900
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2017, Emilio G. Cota <[email protected]>
+ *
+ * License: GNU GPL, version 2 or later.
+ *   See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_PLUGIN_API_H
+#define QEMU_PLUGIN_API_H
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+/*
+ * For best performance, build the plugin with -fvisibility=hidden so that
+ * QEMU_PLUGIN_LOCAL is implicit. Then, just mark qemu_plugin_install with
+ * QEMU_PLUGIN_EXPORT. For more info, see
+ *   https://gcc.gnu.org/wiki/Visibility
+ */
+#if defined _WIN32 || defined __CYGWIN__
+  #ifdef BUILDING_DLL
+    #define QEMU_PLUGIN_EXPORT __declspec(dllexport)
+  #else
+    #define QEMU_PLUGIN_EXPORT __declspec(dllimport)
+  #endif
+  #define QEMU_PLUGIN_LOCAL
+#else
+  #if __GNUC__ >= 4
+    #define QEMU_PLUGIN_EXPORT __attribute__((visibility("default")))
+    #define QEMU_PLUGIN_LOCAL  __attribute__((visibility("hidden")))
+  #else
+    #define QEMU_PLUGIN_EXPORT
+    #define QEMU_PLUGIN_LOCAL
+  #endif
+#endif
+
+typedef uint64_t qemu_plugin_id_t;
+
+/**
+ * qemu_plugin_install - Install a plugin
+ * @id: this plugin's opaque ID
+ * @argc: number of arguments
+ * @argv: array of arguments (@argc elements)
+ *
+ * All plugins must export this symbol.
+ *
+ * Note: @argv is freed after this function returns.
+ */
+QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, int argc,
+                                           char **argv);
+
+typedef void (*qemu_plugin_uninstall_cb_t)(qemu_plugin_id_t id);
+
+/**
+ * qemu_plugin_uninstall - Uninstall a plugin
+ * @id: this plugin's opaque ID
+ * @cb: callback to be called once the plugin has been removed
+ *
+ * Do NOT assume that the plugin has been uninstalled once this
+ * function returns. Plugins are uninstalled asynchronously,
+ * and therefore the given plugin might still receive callbacks
+ * from prior subscriptions _until_ @cb is called.
+ */
+void qemu_plugin_uninstall(qemu_plugin_id_t id, qemu_plugin_uninstall_cb_t cb);
+
+typedef void (*qemu_plugin_simple_cb_t)(qemu_plugin_id_t id);
+
+typedef void (*qemu_plugin_udata_cb_t)(qemu_plugin_id_t id, void *userdata);
+
+typedef void (*qemu_plugin_vcpu_simple_cb_t)(qemu_plugin_id_t id,
+                                             unsigned int vcpu_index);
+
+typedef void (*qemu_plugin_vcpu_udata_cb_t)(unsigned int vcpu_index,
+                                            void *userdata);
+
+/**
+ * qemu_plugin_register_vcpu_init_cb - register a vCPU initialization callback
+ * @id: plugin ID
+ * @cb: callback function
+ *
+ * The @cb function is called every time a vCPU is initialized.
+ *
+ * See also: qemu_plugin_register_vcpu_exit_cb()
+ */
+void qemu_plugin_register_vcpu_init_cb(qemu_plugin_id_t id,
+                                       qemu_plugin_vcpu_simple_cb_t cb);
+
+/**
+ * qemu_plugin_register_vcpu_exit_cb - register a vCPU exit callback
+ * @id: plugin ID
+ * @cb: callback function
+ *
+ * The @cb function is called every time a vCPU exits.
+ *
+ * See also: qemu_plugin_register_vcpu_init_cb()
+ */
+void qemu_plugin_register_vcpu_exit_cb(qemu_plugin_id_t id,
+                                       qemu_plugin_vcpu_simple_cb_t cb);
+
+void qemu_plugin_register_vcpu_idle_cb(qemu_plugin_id_t id,
+                                       qemu_plugin_vcpu_simple_cb_t cb);
+
+void qemu_plugin_register_vcpu_resume_cb(qemu_plugin_id_t id,
+                                         qemu_plugin_vcpu_simple_cb_t cb);
+
+struct qemu_plugin_tb;
+struct qemu_plugin_insn;
+
+enum qemu_plugin_cb_flags {
+    QEMU_PLUGIN_CB_NO_REGS, /* callback does not access the CPU's regs */
+    QEMU_PLUGIN_CB_R_REGS,  /* callback reads the CPU's regs */
+    QEMU_PLUGIN_CB_RW_REGS, /* callback reads and writes the CPU's regs */
+};
+
+enum qemu_plugin_mem_rw {
+    QEMU_PLUGIN_MEM_R = 1,
+    QEMU_PLUGIN_MEM_W,
+    QEMU_PLUGIN_MEM_RW,
+};
+
+typedef void (*qemu_plugin_vcpu_tb_trans_cb_t)(qemu_plugin_id_t id,
+                                               unsigned int vcpu_index,
+                                               struct qemu_plugin_tb *tb);
+
+void qemu_plugin_register_vcpu_tb_trans_cb(qemu_plugin_id_t id,
+                                           qemu_plugin_vcpu_tb_trans_cb_t cb);
+
+/* can only call from tb_trans_cb callback */
+void qemu_plugin_register_vcpu_tb_exec_cb(struct qemu_plugin_tb *tb,
+                                          qemu_plugin_vcpu_udata_cb_t cb,
+                                          enum qemu_plugin_cb_flags flags,
+                                          void *userdata);
+
+enum qemu_plugin_op {
+    QEMU_PLUGIN_INLINE_ADD_U64,
+};
+
+void qemu_plugin_register_vcpu_tb_exec_inline(struct qemu_plugin_tb *tb,
+                                              enum qemu_plugin_op op,
+                                              void *ptr, uint64_t imm);
+
+void qemu_plugin_register_vcpu_insn_exec_cb(struct qemu_plugin_insn *insn,
+                                            qemu_plugin_vcpu_udata_cb_t cb,
+                                            enum qemu_plugin_cb_flags flags,
+                                            void *userdata);
+
+void qemu_plugin_register_vcpu_insn_exec_inline(struct qemu_plugin_insn *insn,
+                                                enum qemu_plugin_op op,
+                                                void *ptr, uint64_t imm);
+
+typedef uint32_t qemu_plugin_meminfo_t;
+
+unsigned qemu_plugin_mem_size_shift(qemu_plugin_meminfo_t info);
+bool qemu_plugin_mem_is_sign_extended(qemu_plugin_meminfo_t info);
+bool qemu_plugin_mem_is_big_endian(qemu_plugin_meminfo_t info);
+bool qemu_plugin_mem_is_store(qemu_plugin_meminfo_t info);
+
+typedef void
+(*qemu_plugin_vcpu_mem_cb_t)(unsigned int vcpu_index,
+                             qemu_plugin_meminfo_t info, uint64_t vaddr,
+                             void *userdata);
+
+typedef void
+(*qemu_plugin_vcpu_mem_haddr_cb_t)(unsigned int vcpu_index,
+                                   qemu_plugin_meminfo_t info, uint64_t vaddr,
+                                   void *haddr, void *userdata);
+
+void qemu_plugin_register_vcpu_mem_cb(struct qemu_plugin_insn *insn,
+                                      qemu_plugin_vcpu_mem_cb_t cb,
+                                      enum qemu_plugin_cb_flags flags,
+                                      enum qemu_plugin_mem_rw rw,
+                                      void *userdata);
+
+void qemu_plugin_register_vcpu_mem_haddr_cb(struct qemu_plugin_insn *insn,
+                                            qemu_plugin_vcpu_mem_haddr_cb_t cb,
+                                            enum qemu_plugin_cb_flags flags,
+                                            enum qemu_plugin_mem_rw rw,
+                                            void *userdata);
+
+void qemu_plugin_register_vcpu_mem_inline(struct qemu_plugin_insn *insn,
+                                          enum qemu_plugin_mem_rw rw,
+                                          enum qemu_plugin_op op, void *ptr,
+                                          uint64_t imm);
+
+uint64_t qemu_plugin_ram_addr_from_host(void *haddr);
+
+typedef void
+(*qemu_plugin_vcpu_syscall_cb_t)(qemu_plugin_id_t id, unsigned int vcpu_index,
+                                 int64_t num, uint64_t a1, uint64_t a2,
+                                 uint64_t a3, uint64_t a4, uint64_t a5,
+                                 uint64_t a6, uint64_t a7, uint64_t a8);
+
+void qemu_plugin_register_vcpu_syscall_cb(qemu_plugin_id_t id,
+                                          qemu_plugin_vcpu_syscall_cb_t cb);
+
+typedef void
+(*qemu_plugin_vcpu_syscall_ret_cb_t)(qemu_plugin_id_t id, unsigned int vcpu_idx,
+                                     int64_t num, int64_t ret);
+
+void
+qemu_plugin_register_vcpu_syscall_ret_cb(qemu_plugin_id_t id,
+                                         qemu_plugin_vcpu_syscall_ret_cb_t cb);
+
+size_t qemu_plugin_tb_n_insns(const struct qemu_plugin_tb *tb);
+
+uint64_t qemu_plugin_tb_vaddr(const struct qemu_plugin_tb *tb);
+
+struct qemu_plugin_insn *
+qemu_plugin_tb_get_insn(const struct qemu_plugin_tb *tb, size_t idx);
+
+const void *qemu_plugin_insn_data(const struct qemu_plugin_insn *insn);
+
+size_t qemu_plugin_insn_size(const struct qemu_plugin_insn *insn);
+
+uint64_t qemu_plugin_insn_vaddr(const struct qemu_plugin_insn *insn);
+void *qemu_plugin_insn_haddr(const struct qemu_plugin_insn *insn);
+
+/**
+ * qemu_plugin_vcpu_for_each - iterate over the existing vCPU
+ * @id: plugin ID
+ * @cb: callback function
+ *
+ * The @cb function is called once for each existing vCPU.
+ *
+ * See also: qemu_plugin_register_vcpu_init_cb()
+ */
+void qemu_plugin_vcpu_for_each(qemu_plugin_id_t id,
+                               qemu_plugin_vcpu_simple_cb_t cb);
+
+void qemu_plugin_register_flush_cb(qemu_plugin_id_t id,
+                                   qemu_plugin_simple_cb_t cb);
+
+void qemu_plugin_register_atexit_cb(qemu_plugin_id_t id,
+                                    qemu_plugin_udata_cb_t cb, void *userdata);
+
+/* returns -1 in user-mode */
+int qemu_plugin_n_vcpus(void);
+
+/* returns -1 in user-mode */
+int qemu_plugin_n_max_vcpus(void);
+
+#endif /* QEMU_PLUGIN_API_H */
Signature · 1 line
2.17.1
#21 lore raw

RFC v2 7/38 queue: add QTAILQ_REMOVE_SEVERAL

In reply to Emilio G. Cota

This is faster than removing elements one by one.

Will gain a user soon.

---
 include/qemu/queue.h | 10 ++++++++++
 1 file changed, 10 insertions(+)
include/qemu/queue.h +10 -0
index ac418efc43..0283c2dd7d 100644
@@ -419,6 +419,16 @@ struct {                                                                \
         (elm)->field.tqe_prev = NULL;                                   \
 } while (/*CONSTCOND*/0)
 
+/* remove @left, @right and all elements in between from @head */
+#define QTAILQ_REMOVE_SEVERAL(head, left, right, field) do {    \
+        if (((right)->field.tqe_next) != NULL)                  \
+            (right)->field.tqe_next->field.tqe_prev =           \
+                (left)->field.tqe_prev;                         \
+        else                                                    \
+            (head)->tqh_last = (left)->field.tqe_prev;          \
+        *(left)->field.tqe_prev = (right)->field.tqe_next;      \
+    } while (/*CONSTCOND*/0)
+
 #define QTAILQ_FOREACH(var, head, field)                                \
         for ((var) = ((head)->tqh_first);                               \
                 (var);                                                  \
Signature · 1 line
2.17.1
#31 lore raw

RFC v2 12/38 tcg: add MO_HADDR to TCGMemOp

In reply to Emilio G. Cota

We will use this from plugins to mark mem accesses so that we can later obtain their host address.

---
 tcg/tcg.h | 7 +++++++
 1 file changed, 7 insertions(+)
tcg/tcg.h +7 -0
index 6fd525023b..a376f83ab6 100644
@@ -359,6 +359,13 @@ typedef enum TCGMemOp {
     MO_ALIGN_32 = 5 << MO_ASHIFT,
     MO_ALIGN_64 = 6 << MO_ASHIFT,
 
+    /*
+     * SoftMMU-only: if set, the TCG backend puts the corresponding host address
+     * in CPUArchState.hostaddr.
+     */
+    MO_HSHIFT = MO_ASHIFT + 3,
+    MO_HADDR = 1 << MO_HSHIFT,
+
     /* Combinations of the above, for ease of use.  */
     MO_UB    = MO_8,
     MO_UW    = MO_16,
Signature · 1 line
2.17.1
#26 lore raw

RFC v2 9/38 cputlb: introduce get_page_addr_code_hostp

In reply to Emilio G. Cota

This will be used by plugins to get the host address of instructions.

---
 include/exec/exec-all.h | 13 +++++++++++++
 accel/tcg/cputlb.c      | 14 +++++++++++++-
 2 files changed, 26 insertions(+), 1 deletion(-)
include/exec/exec-all.h +13 -0
index 815e5b1e83..afcc01e0e3 100644
@@ -22,6 +22,7 @@
 
 #include "qemu-common.h"
 #include "exec/tb-context.h"
+#include "exec/cpu_ldst.h"
 #include "sysemu/cpus.h"
 
 /* allow to see translation results - the slowdown should be negligible, so we leave it */
@@ -487,12 +488,24 @@ static inline tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong
 {
     return addr;
 }
+
+static inline tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env1,
+                                                      target_ulong addr,
+                                                      void **hostp)
+{
+    if (hostp) {
+        *hostp = g2h(addr);
+    }
+    return addr;
+}
 #else
 static inline void mmap_lock(void) {}
 static inline void mmap_unlock(void) {}
 
 /* cputlb.c */
 tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr);
+tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env1, target_ulong addr,
+                                        void **hostp);
 
 void tlb_reset_dirty(CPUState *cpu, ram_addr_t start1, ram_addr_t length);
 void tlb_set_dirty(CPUState *cpu, target_ulong vaddr);
accel/tcg/cputlb.c +13 -1
index e3582f2f1d..5c61908084 100644
@@ -1069,7 +1069,8 @@ static bool victim_tlb_hit(CPUArchState *env, size_t mmu_idx, size_t index,
  * is actually a ram_addr_t (in system mode; the user mode emulation
  * version of this function returns a guest virtual address).
  */
-tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
+tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, target_ulong addr,
+                                        void **hostp)
 {
     uintptr_t mmu_idx = cpu_mmu_index(env, true);
     uintptr_t index = tlb_index(env, mmu_idx, addr);
@@ -1092,13 +1093,24 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
          *    than a target page, so we must redo the MMU check every insn
          *  - TLB_MMIO: region is not backed by RAM
          */
+        if (hostp) {
+            *hostp = NULL;
+        }
         return -1;
     }
 
     p = (void *)((uintptr_t)addr + entry->addend);
+    if (hostp) {
+        *hostp = p;
+    }
     return qemu_ram_addr_from_host_nofail(p);
 }
 
+tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
+{
+    return get_page_addr_code_hostp(env, addr, NULL);
+}
+
 /* Probe for whether the specified guest write access is permitted.
  * If it is not permitted then an exception will be taken in the same
  * way as if this were a real write access (and we will not return).
Signature · 1 line
2.17.1
#17 lore raw

RFC v2 6/38 plugin: add core code

In reply to Emilio G. Cota

Some design requirements/goals:

- Make sure we cannot deadlock, particularly under MTTCG. For this, we acquire a lock when called from plugin code, and keep RCU lists of callbacks so that we do not have to hold the lock when calling the callbacks. This is also for performance, since some callbacks (e.g. memory access callbacks) might be called very frequently.
* A consequence of this is that we keep our own list of CPUs, so that we do not have to worry about locking order wrt cpu_list_lock.
* Use a recursive lock, since we can get registration calls from callbacks.

- Support as many plugins as the user wants (e.g. -plugin foo -plugin bar), just like other tools (e.g. dynamorio) do.

- Support the uninstallation of a plugin at any time (e.g. from plugin callbacks).

- Avoid malicious plugins from abusing the API. This is done by:
* Adding a qemu_plugin_id_t that all calls need to use. This is a unique id per plugin.
* Hiding CPUState * under cpu_index. Plugin code can keep per-vcpu data by using said index (say to index an array).
* Only exporting the relevant qemu_plugin symbols to the plugins by passing --dynamic-file to the linker (when supported), instead of exporting all symbols with -rdynamic.

- Performance: registering/unregistering callbacks is "slow", since it takes a lock. But this is very infrequent; we want performance when calling (or not calling) callbacks, not when registering them. Using RCU is great for this. The only difficulty is when uninstalling a plugin, where some callbacks might still be called after the uninstall returns. An alternative would be to use r/w locks, but that would complicate code quite a bit for very little gain. In any case, I suspect most plugins will just run until QEMU exits.

Some design decisions:
- I considered registering callbacks per-vcpu, but really I don't see the use case for it (would complicate the API and 99% of plugins won't care, so I'd rather make that 1% slower by letting them discard unwanted callbacks).

- Last, 'plugin' vs. 'instrumentation' naming: I think instrumentation is a subset of the functionality that plugins can provide. IOW, in the future not all plugins might be considered instrumentation, even if currently my goal is to use them for that purpose.

---
 Makefile              |    7 +-
 Makefile.target       |    2 +
 include/qemu/plugin.h |  253 ++++++++++
 include/qom/cpu.h     |    6 +
 plugin.c              | 1030 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 1297 insertions(+), 1 deletion(-)
 create mode 100644 include/qemu/plugin.h
 create mode 100644 plugin.c
Makefile +6 -1
index f2947186a4..9cb3076d84 100644
@@ -862,8 +862,10 @@ ifneq (,$(findstring qemu-ga,$(TOOLS)))
 endif
 endif
 
+install-includedir:
+	$(INSTALL_DIR) "$(DESTDIR)$(includedir)"
 
-install: all $(if $(BUILD_DOCS),install-doc) install-datadir install-localstatedir
+install: all $(if $(BUILD_DOCS),install-doc) install-datadir install-localstatedir install-includedir
 ifneq ($(TOOLS),)
 	$(call install-prog,$(subst qemu-ga,qemu-ga$(EXESUF),$(TOOLS)),$(DESTDIR)$(bindir))
 endif
@@ -885,6 +887,9 @@ ifneq ($(BLOBS),)
 endif
 ifdef CONFIG_GTK
 	$(MAKE) -C po $@
+endif
+ifeq ($(CONFIG_PLUGIN),y)
+	$(INSTALL_DATA) $(SRC_PATH)/include/qemu/qemu-plugin.h "$(DESTDIR)$(includedir)/qemu-plugin.h"
 endif
 	$(INSTALL_DIR) "$(DESTDIR)$(qemu_datadir)/keymaps"
 	set -e; for x in $(KEYMAPS); do \
Makefile.target +2 -0
index 4d56298bbf..75637c285c 100644
@@ -107,6 +107,8 @@ obj-y += target/$(TARGET_BASE_ARCH)/
 obj-y += disas.o
 obj-$(call notempty,$(TARGET_XML_FILES)) += gdbstub-xml.o
 
+obj-$(CONFIG_PLUGINS) += plugin.o
+
 #########################################################
 # Linux user emulator target
 
include/qemu/plugin.h new file +253 -0

253 lines not on this page · raw message

include/qom/cpu.h +6 -0
index fab18089db..4002a911af 100644
@@ -30,6 +30,7 @@
 #include "qemu/rcu_queue.h"
 #include "qemu/queue.h"
 #include "qemu/thread.h"
+#include "qemu/plugin.h"
 
 typedef int (*WriteCoreDumpFunction)(const void *buf, size_t size,
                                      void *opaque);
@@ -326,6 +327,7 @@ struct qemu_work_item;
  * @trace_dstate_delayed: Delayed changes to trace_dstate (includes all changes
  *                        to @trace_dstate).
  * @trace_dstate: Dynamic tracing state of events for this vCPU (bitmask).
+ * @plugin_mask: Plugin event bitmap. Modified only via async work.
  * @ignore_memory_transaction_failures: Cached copy of the MachineState
  *    flag of the same name: allows the board to suppress calling of the
  *    CPU do_transaction_failed hook function.
@@ -412,6 +414,10 @@ struct CPUState {
     DECLARE_BITMAP(trace_dstate_delayed, CPU_TRACE_DSTATE_MAX_EVENTS);
     DECLARE_BITMAP(trace_dstate, CPU_TRACE_DSTATE_MAX_EVENTS);
 
+    DECLARE_BITMAP(plugin_mask, QEMU_PLUGIN_EV_MAX);
+
+    struct qemu_plugin_dyn_cb_arr *plugin_mem_cbs;
+
     /* TODO Move common fields from CPUArchState here. */
     int cpu_index;
     uint32_t can_do_io;
plugin.c new file +1030 -0

1,030 lines not on this page · raw message

Signature · 1 line
2.17.1
#32 lore raw

RFC v2 13/38 atomic_template: fix indentation in GEN_ATOMIC_HELPER

In reply to Emilio G. Cota
---
 accel/tcg/atomic_template.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/atomic_template.h +1 -1
index efde12fdb2..8d177fefef 100644
@@ -284,7 +284,7 @@ ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, target_ulong addr,
 
 #define GEN_ATOMIC_HELPER(X)                                        \
 ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
-                 ABI_TYPE val EXTRA_ARGS)                           \
+                        ABI_TYPE val EXTRA_ARGS)                    \
 {                                                                   \
     ATOMIC_MMU_DECLS;                                               \
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;                           \
Signature · 1 line
2.17.1
#37 lore raw

RFC v2 16/38 translate-all: notify plugin code of tb_flush

In reply to Emilio G. Cota

Plugins might allocate per-TB data that then they get passed each time a TB is executed (via the *userdata pointer).

Notify plugin code every time a code cache flush occurs, so that plugins can then reclaim the memory of the per-TB data.

---
 accel/tcg/translate-all.c | 6 ++++++
 1 file changed, 6 insertions(+)
accel/tcg/translate-all.c +6 -0
index 62d5e13185..aaa8193ceb 100644
@@ -1232,6 +1232,8 @@ static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
 /* flush all the translation blocks */
 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
 {
+    bool did_flush = false;
+
     mmap_lock();
     /* If it is already been done on request of another CPU,
      * just retry.
@@ -1239,6 +1241,7 @@ static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
     if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
         goto done;
     }
+    did_flush = true;
 
     if (DEBUG_TB_FLUSH_GATE) {
         size_t nb_tbs = tcg_nb_tbs();
@@ -1263,6 +1266,9 @@ static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
 
 done:
     mmap_unlock();
+    if (did_flush) {
+        qemu_plugin_flush_cb();
+    }
 }
 
 void tb_flush(CPUState *cpu)
Signature · 1 line
2.17.1
#44 lore raw

RFC v2 23/38 target/ppc: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/ppc/translate.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
target/ppc/translate.c +3 -5
index 2d31b5f7a1..7a7c8a9a88 100644
@@ -7555,11 +7555,9 @@ static void ppc_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs)
     LOG_DISAS("nip=" TARGET_FMT_lx " super=%d ir=%d\n",
               ctx->base.pc_next, ctx->mem_idx, (int)msr_ir);
 
-    if (unlikely(need_byteswap(ctx))) {
-        ctx->opcode = bswap32(cpu_ldl_code(env, ctx->base.pc_next));
-    } else {
-        ctx->opcode = cpu_ldl_code(env, ctx->base.pc_next);
-    }
+    ctx->opcode = translator_ldl_swap(env, ctx->base.pc_next,
+                                      need_byteswap(ctx));
+
     LOG_DISAS("translate opcode %08x (%02x %02x %02x %02x) (%s)\n",
               ctx->opcode, opc1(ctx->opcode), opc2(ctx->opcode),
               opc3(ctx->opcode), opc4(ctx->opcode),
Signature · 1 line
2.17.1
#24 lore raw

RFC v2 8/38 tcg: drop nargs from tcg_op_insert_{before, after}

In reply to Emilio G. Cota

It's unused.

---
 tcg/tcg.h      |  4 ++--
 tcg/optimize.c |  4 ++--
 tcg/tcg.c      | 10 ++++------
 3 files changed, 8 insertions(+), 10 deletions(-)
tcg/tcg.h +2 -2
index f4efbaa680..a745e926bb 100644
@@ -1073,8 +1073,8 @@ void tcg_gen_callN(void *func, TCGTemp *ret, int nargs, TCGTemp **args);
 
 TCGOp *tcg_emit_op(TCGOpcode opc);
 void tcg_op_remove(TCGContext *s, TCGOp *op);
-TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *op, TCGOpcode opc, int narg);
-TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *op, TCGOpcode opc, int narg);
+TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *op, TCGOpcode opc);
+TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *op, TCGOpcode opc);
 
 void tcg_optimize(TCGContext *s);
 
tcg/optimize.c +2 -2
index 5dbe11c3c8..a2247f6de3 100644
@@ -1249,7 +1249,7 @@ void tcg_optimize(TCGContext *s)
                 uint64_t a = ((uint64_t)ah << 32) | al;
                 uint64_t b = ((uint64_t)bh << 32) | bl;
                 TCGArg rl, rh;
-                TCGOp *op2 = tcg_op_insert_before(s, op, INDEX_op_movi_i32, 2);
+                TCGOp *op2 = tcg_op_insert_before(s, op, INDEX_op_movi_i32);
 
                 if (opc == INDEX_op_add2_i32) {
                     a += b;
@@ -1271,7 +1271,7 @@ void tcg_optimize(TCGContext *s)
                 uint32_t b = arg_info(op->args[3])->val;
                 uint64_t r = (uint64_t)a * b;
                 TCGArg rl, rh;
-                TCGOp *op2 = tcg_op_insert_before(s, op, INDEX_op_movi_i32, 2);
+                TCGOp *op2 = tcg_op_insert_before(s, op, INDEX_op_movi_i32);
 
                 rl = op->args[0];
                 rh = op->args[1];
tcg/tcg.c +4 -6
index e85133ef05..e87c662a18 100644
@@ -2203,16 +2203,14 @@ TCGOp *tcg_emit_op(TCGOpcode opc)
     return op;
 }
 
-TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *old_op,
-                            TCGOpcode opc, int nargs)
+TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *old_op, TCGOpcode opc)
 {
     TCGOp *new_op = tcg_op_alloc(opc);
     QTAILQ_INSERT_BEFORE(old_op, new_op, link);
     return new_op;
 }
 
-TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *old_op,
-                           TCGOpcode opc, int nargs)
+TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *old_op, TCGOpcode opc)
 {
     TCGOp *new_op = tcg_op_alloc(opc);
     QTAILQ_INSERT_AFTER(&s->ops, old_op, new_op, link);
@@ -2550,7 +2548,7 @@ static bool liveness_pass_2(TCGContext *s)
                     TCGOpcode lopc = (arg_ts->type == TCG_TYPE_I32
                                       ? INDEX_op_ld_i32
                                       : INDEX_op_ld_i64);
-                    TCGOp *lop = tcg_op_insert_before(s, op, lopc, 3);
+                    TCGOp *lop = tcg_op_insert_before(s, op, lopc);
 
                     lop->args[0] = temp_arg(dir_ts);
                     lop->args[1] = temp_arg(arg_ts->mem_base);
@@ -2619,7 +2617,7 @@ static bool liveness_pass_2(TCGContext *s)
                 TCGOpcode sopc = (arg_ts->type == TCG_TYPE_I32
                                   ? INDEX_op_st_i32
                                   : INDEX_op_st_i64);
-                TCGOp *sop = tcg_op_insert_after(s, op, sopc, 3);
+                TCGOp *sop = tcg_op_insert_after(s, op, sopc);
 
                 sop->args[0] = temp_arg(dir_ts);
                 sop->args[1] = temp_arg(arg_ts->mem_base);
Signature · 1 line
2.17.1
#33 lore raw

RFC v2 14/38 atomic_template: add inline trace/plugin helpers

In reply to Emilio G. Cota

In preparation for plugin support.

---
 accel/tcg/atomic_template.h | 110 ++++++++++++++++++++++++------------
 1 file changed, 75 insertions(+), 35 deletions(-)
accel/tcg/atomic_template.h +75 -35
index 8d177fefef..2f7d5ee02a 100644
@@ -59,25 +59,44 @@
 # define ABI_TYPE  uint32_t
 #endif
 
-#define ATOMIC_TRACE_RMW do {                                           \
-        uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
-                                                                        \
-        trace_guest_mem_before_exec(ENV_GET_CPU(env), addr, info);      \
-        trace_guest_mem_before_exec(ENV_GET_CPU(env), addr,             \
-                                    info | TRACE_MEM_ST);               \
-    } while (0)
-
-#define ATOMIC_TRACE_LD do {                                            \
-        uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
-                                                                        \
-        trace_guest_mem_before_exec(ENV_GET_CPU(env), addr, info);      \
-    } while (0)
-
-# define ATOMIC_TRACE_ST do {                                           \
-        uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, true); \
-                                                                        \
-        trace_guest_mem_before_exec(ENV_GET_CPU(env), addr, info);      \
-    } while (0)
+#ifndef ATOMIC_TEMPLATE_COMMON
+#define ATOMIC_TEMPLATE_COMMON
+static inline
+void atomic_trace_rmw_pre(CPUArchState *env, target_ulong addr, uint8_t info)
+{
+    CPUState *cpu = ENV_GET_CPU(env);
+
+    trace_guest_mem_before_exec(cpu, addr, info);
+    trace_guest_mem_before_exec(cpu, addr, info | TRACE_MEM_ST);
+}
+
+static inline void atomic_trace_rmw_post(CPUArchState *env, target_ulong addr,
+                                         void *haddr, uint8_t info)
+{
+}
+
+static inline
+void atomic_trace_ld_pre(CPUArchState *env, target_ulong addr, uint8_t info)
+{
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), addr, info);
+}
+
+static inline void atomic_trace_ld_post(CPUArchState *env, target_ulong addr,
+                                        void *haddr, uint8_t info)
+{
+}
+
+static inline
+void atomic_trace_st_pre(CPUArchState *env, target_ulong addr, uint8_t info)
+{
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), addr, info);
+}
+
+static inline void atomic_trace_st_post(CPUArchState *env, target_ulong addr,
+                                        void *haddr, uint8_t info)
+{
+}
+#endif /* ATOMIC_TEMPLATE_COMMON */
 
 /* Define host-endian atomic operations.  Note that END is used within
    the ATOMIC_NAME macro, and redefined below.  */
@@ -98,14 +117,16 @@ ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, target_ulong addr,
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
     DATA_TYPE ret;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_RMW;
+    atomic_trace_rmw_pre(env, addr, info);
 #if DATA_SIZE == 16
     ret = atomic16_cmpxchg(haddr, cmpv, newv);
 #else
     ret = atomic_cmpxchg__nocheck(haddr, cmpv, newv);
 #endif
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_rmw_post(env, addr, haddr, info);
     return ret;
 }
 
@@ -115,10 +136,12 @@ ABI_TYPE ATOMIC_NAME(ld)(CPUArchState *env, target_ulong addr EXTRA_ARGS)
 {
     ATOMIC_MMU_DECLS;
     DATA_TYPE val, *haddr = ATOMIC_MMU_LOOKUP;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_LD;
+    atomic_trace_ld_pre(env, addr, info);
     val = atomic16_read(haddr);
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_ld_post(env, addr, haddr, info);
     return val;
 }
 
@@ -127,10 +150,12 @@ void ATOMIC_NAME(st)(CPUArchState *env, target_ulong addr,
 {
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, true);
 
-    ATOMIC_TRACE_ST;
+    atomic_trace_st_pre(env, addr, info);
     atomic16_set(haddr, val);
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_st_post(env, addr, haddr, info);
 }
 #endif
 #else
@@ -140,10 +165,12 @@ ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, target_ulong addr,
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
     DATA_TYPE ret;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_RMW;
+    atomic_trace_rmw_pre(env, addr, info);
     ret = atomic_xchg__nocheck(haddr, val);
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_rmw_post(env, addr, haddr, info);
     return ret;
 }
 
@@ -154,10 +181,12 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
     ATOMIC_MMU_DECLS;                                               \
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;                           \
     DATA_TYPE ret;                                                  \
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
                                                                     \
-    ATOMIC_TRACE_RMW;                                               \
+    atomic_trace_rmw_pre(env, addr, info);                          \
     ret = atomic_##X(haddr, val);                                   \
     ATOMIC_MMU_CLEANUP;                                             \
+    atomic_trace_rmw_post(env, addr, haddr, info);                  \
     return ret;                                                     \
 }
 
@@ -186,8 +215,9 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
     ATOMIC_MMU_DECLS;                                               \
     XDATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;                          \
     XDATA_TYPE cmp, old, new, val = xval;                           \
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
                                                                     \
-    ATOMIC_TRACE_RMW;                                               \
+    atomic_trace_rmw_pre(env, addr, info);                          \
     smp_mb();                                                       \
     cmp = atomic_read__nocheck(haddr);                              \
     do {                                                            \
@@ -195,6 +225,7 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
         cmp = atomic_cmpxchg__nocheck(haddr, old, new);             \
     } while (cmp != old);                                           \
     ATOMIC_MMU_CLEANUP;                                             \
+    atomic_trace_rmw_post(env, addr, haddr, info);                  \
     return RET;                                                     \
 }
 
@@ -232,14 +263,16 @@ ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, target_ulong addr,
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
     DATA_TYPE ret;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_RMW;
+    atomic_trace_rmw_pre(env, addr, info);
 #if DATA_SIZE == 16
     ret = atomic16_cmpxchg(haddr, BSWAP(cmpv), BSWAP(newv));
 #else
     ret = atomic_cmpxchg__nocheck(haddr, BSWAP(cmpv), BSWAP(newv));
 #endif
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_rmw_post(env, addr, haddr, info);
     return BSWAP(ret);
 }
 
@@ -249,10 +282,12 @@ ABI_TYPE ATOMIC_NAME(ld)(CPUArchState *env, target_ulong addr EXTRA_ARGS)
 {
     ATOMIC_MMU_DECLS;
     DATA_TYPE val, *haddr = ATOMIC_MMU_LOOKUP;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_LD;
+    atomic_trace_ld_pre(env, addr, info);
     val = atomic16_read(haddr);
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_ld_post(env, addr, haddr, info);
     return BSWAP(val);
 }
 
@@ -261,11 +296,14 @@ void ATOMIC_NAME(st)(CPUArchState *env, target_ulong addr,
 {
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, true);
 
-    ATOMIC_TRACE_ST;
+    val = BSWAP(val);
+    atomic_trace_st_pre(env, addr, info);
     val = BSWAP(val);
     atomic16_set(haddr, val);
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_st_post(env, addr, haddr, info);
 }
 #endif
 #else
@@ -275,10 +313,12 @@ ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, target_ulong addr,
     ATOMIC_MMU_DECLS;
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;
     ABI_TYPE ret;
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false);
 
-    ATOMIC_TRACE_RMW;
+    atomic_trace_rmw_pre(env, addr, info);
     ret = atomic_xchg__nocheck(haddr, BSWAP(val));
     ATOMIC_MMU_CLEANUP;
+    atomic_trace_rmw_post(env, addr, haddr, info);
     return BSWAP(ret);
 }
 
@@ -289,10 +329,12 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
     ATOMIC_MMU_DECLS;                                               \
     DATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;                           \
     DATA_TYPE ret;                                                  \
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
                                                                     \
-    ATOMIC_TRACE_RMW;                                               \
+    atomic_trace_rmw_pre(env, addr, info);                          \
     ret = atomic_##X(haddr, BSWAP(val));                            \
     ATOMIC_MMU_CLEANUP;                                             \
+    atomic_trace_rmw_post(env, addr, haddr, info);                  \
     return BSWAP(ret);                                              \
 }
 
@@ -319,8 +361,9 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
     ATOMIC_MMU_DECLS;                                               \
     XDATA_TYPE *haddr = ATOMIC_MMU_LOOKUP;                          \
     XDATA_TYPE ldo, ldn, old, new, val = xval;                      \
+    uint8_t info = glue(trace_mem_build_info_no_se, MEND)(SHIFT, false); \
                                                                     \
-    ATOMIC_TRACE_RMW;                                               \
+    atomic_trace_rmw_pre(env, addr, info);                          \
     smp_mb();                                                       \
     ldn = atomic_read__nocheck(haddr);                              \
     do {                                                            \
@@ -328,6 +371,7 @@ ABI_TYPE ATOMIC_NAME(X)(CPUArchState *env, target_ulong addr,       \
         ldn = atomic_cmpxchg__nocheck(haddr, ldo, BSWAP(new));      \
     } while (ldo != ldn);                                           \
     ATOMIC_MMU_CLEANUP;                                             \
+    atomic_trace_rmw_post(env, addr, haddr, info);                  \
     return RET;                                                     \
 }
 
@@ -355,10 +399,6 @@ GEN_ATOMIC_HELPER_FN(add_fetch, ADD, DATA_TYPE, new)
 #undef MEND
 #endif /* DATA_SIZE > 1 */
 
-#undef ATOMIC_TRACE_ST
-#undef ATOMIC_TRACE_LD
-#undef ATOMIC_TRACE_RMW
-
 #undef BSWAP
 #undef ABI_TYPE
 #undef DATA_TYPE
Signature · 1 line
2.17.1
#38 lore raw

RFC v2 17/38 *-user: notify plugin of exit

In reply to Emilio G. Cota
---
 bsd-user/syscall.c | 3 +++
 linux-user/exit.c  | 1 +
 2 files changed, 4 insertions(+)
bsd-user/syscall.c +3 -0
index 66492aaf5d..b7818af450 100644
@@ -332,6 +332,7 @@ abi_long do_freebsd_syscall(void *cpu_env, int num, abi_long arg1,
         _mcleanup();
 #endif
         gdb_exit(cpu_env, arg1);
+        qemu_plugin_atexit_cb();
         /* XXX: should free thread stack and CPU env */
         _exit(arg1);
         ret = 0; /* avoid warning */
@@ -430,6 +431,7 @@ abi_long do_netbsd_syscall(void *cpu_env, int num, abi_long arg1,
         _mcleanup();
 #endif
         gdb_exit(cpu_env, arg1);
+        qemu_plugin_atexit_cb();
         /* XXX: should free thread stack and CPU env */
         _exit(arg1);
         ret = 0; /* avoid warning */
@@ -505,6 +507,7 @@ abi_long do_openbsd_syscall(void *cpu_env, int num, abi_long arg1,
         _mcleanup();
 #endif
         gdb_exit(cpu_env, arg1);
+        qemu_plugin_atexit_cb();
         /* XXX: should free thread stack and CPU env */
         _exit(arg1);
         ret = 0; /* avoid warning */
linux-user/exit.c +1 -0
index 14e94e28fa..768856483a 100644
@@ -32,4 +32,5 @@ void preexit_cleanup(CPUArchState *env, int code)
         __gcov_dump();
 #endif
         gdb_exit(env, code);
+        qemu_plugin_atexit_cb();
 }
Signature · 1 line
2.17.1
#39 lore raw

RFC v2 18/38 *-user: plugin syscalls

In reply to Emilio G. Cota
---
 bsd-user/syscall.c   | 9 +++++++++
 linux-user/syscall.c | 3 +++
 2 files changed, 12 insertions(+)
bsd-user/syscall.c +9 -0
index b7818af450..4993f81b2b 100644
@@ -323,6 +323,8 @@ abi_long do_freebsd_syscall(void *cpu_env, int num, abi_long arg1,
     gemu_log("freebsd syscall %d\n", num);
 #endif
     trace_guest_user_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
+    qemu_plugin_vcpu_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
+                             arg8);
     if(do_strace)
         print_freebsd_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
 
@@ -404,6 +406,7 @@ abi_long do_freebsd_syscall(void *cpu_env, int num, abi_long arg1,
     if (do_strace)
         print_freebsd_syscall_ret(num, ret);
     trace_guest_user_syscall_ret(cpu, num, ret);
+    qemu_plugin_vcpu_syscall_ret(cpu, num, ret);
     return ret;
  efault:
     ret = -TARGET_EFAULT;
@@ -422,6 +425,8 @@ abi_long do_netbsd_syscall(void *cpu_env, int num, abi_long arg1,
     gemu_log("netbsd syscall %d\n", num);
 #endif
     trace_guest_user_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, 0, 0);
+    qemu_plugin_vcpu_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, 0,
+                             0);
     if(do_strace)
         print_netbsd_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
 
@@ -480,6 +485,7 @@ abi_long do_netbsd_syscall(void *cpu_env, int num, abi_long arg1,
     if (do_strace)
         print_netbsd_syscall_ret(num, ret);
     trace_guest_user_syscall_ret(cpu, num, ret);
+    qemu_plugin_vcpu_syscall_ret(cpu, num, ret);
     return ret;
  efault:
     ret = -TARGET_EFAULT;
@@ -498,6 +504,8 @@ abi_long do_openbsd_syscall(void *cpu_env, int num, abi_long arg1,
     gemu_log("openbsd syscall %d\n", num);
 #endif
     trace_guest_user_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, 0, 0);
+    qemu_plugin_vcpu_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, 0,
+                             0);
     if(do_strace)
         print_openbsd_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
 
@@ -556,6 +564,7 @@ abi_long do_openbsd_syscall(void *cpu_env, int num, abi_long arg1,
     if (do_strace)
         print_openbsd_syscall_ret(num, ret);
     trace_guest_user_syscall_ret(cpu, num, ret);
+    qemu_plugin_vcpu_syscall_ret(cpu, num, ret);
     return ret;
  efault:
     ret = -TARGET_EFAULT;
linux-user/syscall.c +3 -0
index 15b03e17b9..9f6457768c 100644
@@ -11422,6 +11422,8 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
 
     trace_guest_user_syscall(cpu, num, arg1, arg2, arg3, arg4,
                              arg5, arg6, arg7, arg8);
+    qemu_plugin_vcpu_syscall(cpu, num, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
+                             arg8);
 
     if (unlikely(do_strace)) {
         print_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
@@ -11434,5 +11436,6 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
     }
 
     trace_guest_user_syscall_ret(cpu, num, ret);
+    qemu_plugin_vcpu_syscall_ret(cpu, num, ret);
     return ret;
 }
Signature · 1 line
2.17.1
#40 lore raw

RFC v2 19/38 cpu: hook plugin vcpu events

In reply to Emilio G. Cota
---
 cpus.c    | 10 ++++++++++
 exec.c    |  2 ++
 qom/cpu.c |  2 ++
 3 files changed, 14 insertions(+)
cpus.c +10 -0
index c9acef73e4..e3844c69c8 100644
@@ -43,6 +43,7 @@
 #include "exec/exec-all.h"
 
 #include "qemu/thread.h"
+#include "qemu/plugin.h"
 #include "sysemu/cpus.h"
 #include "sysemu/qtest.h"
 #include "qemu/main-loop.h"
@@ -1322,12 +1323,21 @@ static void qemu_tcg_rr_wait_io_event(CPUState *cpu)
 
 static void qemu_wait_io_event(CPUState *cpu)
 {
+    bool slept = false;
+
     g_assert(cpu_mutex_locked(cpu));
     g_assert(!qemu_mutex_iothread_locked());
 
     while (cpu_thread_is_idle(cpu)) {
+        if (!slept) {
+            slept = true;
+            qemu_plugin_vcpu_idle_cb(cpu);
+        }
         qemu_cond_wait(&cpu->halt_cond, &cpu->lock);
     }
+    if (slept) {
+        qemu_plugin_vcpu_resume_cb(cpu);
+    }
 
 #ifdef _WIN32
     /* Eat dummy APC queued by qemu_cpu_kick_thread.  */
exec.c +2 -0
index 04d505500b..bdafb0e71a 100644
@@ -967,6 +967,8 @@ void cpu_exec_realizefn(CPUState *cpu, Error **errp)
     }
     tlb_init(cpu);
 
+    qemu_plugin_vcpu_init_hook(cpu);
+
 #ifndef CONFIG_USER_ONLY
     if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
         vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
qom/cpu.c +2 -0
index b33d182c4c..6233a98a84 100644
@@ -32,6 +32,7 @@
 #include "hw/boards.h"
 #include "hw/qdev-properties.h"
 #include "trace-root.h"
+#include "qemu/plugin.h"
 
 CPUInterruptHandler cpu_interrupt_handler;
 
@@ -352,6 +353,7 @@ static void cpu_common_unrealizefn(DeviceState *dev, Error **errp)
     CPUState *cpu = CPU(dev);
     /* NOTE: latest generic point before the cpu is fully unrealized */
     trace_fini_vcpu(cpu);
+    qemu_plugin_vcpu_exit_hook(cpu);
     cpu_exec_unrealizefn(cpu);
 }
 
Signature · 1 line
2.17.1
#41 lore raw

RFC v2 20/38 plugin-gen: add plugin_insn_append

In reply to Emilio G. Cota

By adding it to plugin-gen's header file, we can export is as an inline, since tcg.h is included in the header (we need tcg_ctx).

---
 include/exec/plugin-gen.h | 27 ++++++++++++++++++---------
 accel/tcg/plugin-gen.c    | 10 +++++++++-
 2 files changed, 27 insertions(+), 10 deletions(-)
include/exec/plugin-gen.h +18 -9
index 449ea16034..b09c16b720 100644
@@ -15,15 +15,6 @@
 #include "qemu/plugin.h"
 #include "tcg/tcg.h"
 
-/* used by plugin_callback_start and plugin_callback_end TCG ops */
-enum plugin_gen_from {
-    PLUGIN_GEN_FROM_TB,
-    PLUGIN_GEN_FROM_INSN,
-    PLUGIN_GEN_FROM_MEM,
-    PLUGIN_GEN_AFTER_INSN,
-    PLUGIN_GEN_N_FROMS,
-};
-
 struct DisasContextBase;
 
 #ifdef CONFIG_PLUGIN
@@ -36,6 +27,21 @@ void plugin_gen_insn_end(void);
 void plugin_gen_disable_mem_helpers(void);
 void plugin_gen_empty_mem_callback(TCGv addr, uint8_t info);
 
+static inline void plugin_insn_append(const void *from, size_t size)
+{
+    struct qemu_plugin_insn *insn = tcg_ctx->plugin_insn;
+
+    if (insn == NULL) {
+        return;
+    }
+    if (unlikely(insn->size + size > insn->capacity)) {
+        insn->data = g_realloc(insn->data, insn->size + size);
+        insn->capacity = insn->size + size;
+    }
+    memcpy(insn->data + insn->size, from, size);
+    insn->size += size;
+}
+
 #else /* !CONFIG_PLUGIN */
 
 static inline
@@ -60,6 +66,9 @@ static inline void plugin_gen_disable_mem_helpers(void)
 static inline void plugin_gen_empty_mem_callback(TCGv addr, uint8_t info)
 { }
 
+static inline void plugin_insn_append(const void *from, size_t size)
+{ }
+
 #endif /* CONFIG_PLUGIN */
 
 #endif /* QEMU_PLUGIN_GEN_H */
accel/tcg/plugin-gen.c +9 -1
index 06ec23e9f5..e6dd79e4d8 100644
@@ -60,9 +60,17 @@
 /*
  * plugin_cb_start TCG op args[]:
  * 0: enum plugin_gen_from
- * 1: enum plugin_gen_cb (defined below)
+ * 1: enum plugin_gen_cb
  * 2: set to 1 if it's a mem callback and it's a write, 0 otherwise.
  */
+enum plugin_gen_from {
+    PLUGIN_GEN_FROM_TB,
+    PLUGIN_GEN_FROM_INSN,
+    PLUGIN_GEN_FROM_MEM,
+    PLUGIN_GEN_AFTER_INSN,
+    PLUGIN_GEN_N_FROMS,
+};
+
 enum plugin_gen_cb {
     PLUGIN_GEN_CB_UDATA,
     PLUGIN_GEN_CB_INLINE,
Signature · 1 line
2.17.1
#42 lore raw

RFC v2 21/38 translator: add translator_ld{ub, sw, uw, l, q}

In reply to Emilio G. Cota
---
 include/exec/translator.h | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
include/exec/translator.h +28 -0
index 71e7b2c347..39f6f514a7 100644
@@ -19,7 +19,10 @@
  */
 
 
+#include "qemu/bswap.h"
 #include "exec/exec-all.h"
+#include "exec/cpu_ldst.h"
+#include "exec/plugin-gen.h"
 #include "tcg/tcg.h"
 
 
@@ -141,4 +144,29 @@ void translator_loop(const TranslatorOps *ops, DisasContextBase *db,
 
 void translator_loop_temp_check(DisasContextBase *db);
 
+#define GEN_TRANSLATOR_LD(fullname, name, type, swap_fn)                \
+    static inline type                                                  \
+    fullname ## _swap(CPUArchState *env, abi_ptr pc, bool do_swap)      \
+    {                                                                   \
+        type ret = cpu_ ## name ## _code(env, pc);                      \
+                                                                        \
+        if (do_swap) {                                                  \
+            ret = swap_fn(ret);                                         \
+        }                                                               \
+        plugin_insn_append(&ret, sizeof(ret));                          \
+        return ret;                                                     \
+    }                                                                   \
+                                                                        \
+    static inline type fullname(CPUArchState *env, abi_ptr pc)          \
+    {                                                                   \
+        return fullname ## _swap(env, pc, false);                       \
+    }
+
+GEN_TRANSLATOR_LD(translator_ldub, ldub, uint8_t, /* no swap needed */)
+GEN_TRANSLATOR_LD(translator_ldsw, ldsw, int16_t, bswap16)
+GEN_TRANSLATOR_LD(translator_lduw, lduw, uint16_t, bswap16)
+GEN_TRANSLATOR_LD(translator_ldl, ldl, uint32_t, bswap32)
+GEN_TRANSLATOR_LD(translator_ldq, ldq, uint64_t, bswap64)
+#undef GEN_TRANSLATOR_LD
+
 #endif  /* EXEC__TRANSLATOR_H */
Signature · 1 line
2.17.1
#43 lore raw

RFC v2 22/38 target/arm: call qemu_plugin_insn_append

In reply to Emilio G. Cota

I considered using translator_ld* from arm_ldl_code et al. However, note that there's a helper that also calls arm_ldl_code, so we'd have to change that caller.

In thumb's case I'm also calling plugin_insn_append directly, since we can't assume that all instructions are 16 bits long.

---
 target/arm/translate-a64.c | 2 ++
 target/arm/translate.c     | 8 +++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)
target/arm/translate-a64.c +2 -0
index 88195ab949..db95161c16 100644
@@ -38,6 +38,7 @@
 #include "trace-tcg.h"
 #include "translate-a64.h"
 #include "qemu/atomic128.h"
+#include "qemu/plugin.h"
 
 static TCGv_i64 cpu_X[32];
 static TCGv_i64 cpu_pc;
@@ -13321,6 +13322,7 @@ static void disas_a64_insn(CPUARMState *env, DisasContext *s)
     uint32_t insn;
 
     insn = arm_ldl_code(env, s->pc, s->sctlr_b);
+    plugin_insn_append(&insn, sizeof(insn));
     s->insn = insn;
     s->pc += 4;
 
target/arm/translate.c +7 -1
index 7c4675ffd8..d5171f54f6 100644
@@ -13234,6 +13234,7 @@ static void arm_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)
     }
 
     insn = arm_ldl_code(env, dc->pc, dc->sctlr_b);
+    plugin_insn_append(&insn, sizeof(insn));
     dc->insn = insn;
     dc->pc += 4;
     disas_arm_insn(dc, insn);
@@ -13304,11 +13305,16 @@ static void thumb_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)
     insn = arm_lduw_code(env, dc->pc, dc->sctlr_b);
     is_16bit = thumb_insn_is_16bit(dc, insn);
     dc->pc += 2;
-    if (!is_16bit) {
+    if (is_16bit) {
+        uint16_t insn16 = insn;
+
+        plugin_insn_append(&insn16, sizeof(insn16));
+    } else {
         uint32_t insn2 = arm_lduw_code(env, dc->pc, dc->sctlr_b);
 
         insn = insn << 16 | insn2;
         dc->pc += 2;
+        plugin_insn_append(&insn, sizeof(insn));
     }
     dc->insn = insn;
 
Signature · 1 line
2.17.1
#45 lore raw

RFC v2 24/38 target/sh4: fetch code with translator_ld (WIP)

In reply to Emilio G. Cota

XXX: cleanly get the gUSA instructions

---
 target/sh4/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/sh4/translate.c +1 -1
index ab254b0e8d..1704ce8dae 100644
@@ -2331,7 +2331,7 @@ static void sh4_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs)
     }
 #endif
 
-    ctx->opcode = cpu_lduw_code(env, ctx->base.pc_next);
+    ctx->opcode = translator_lduw(env, ctx->base.pc_next);
     decode_opc(ctx);
     ctx->base.pc_next += 2;
 }
Signature · 1 line
2.17.1
#28 lore raw

RFC v2 10/38 plugin-gen: add module for TCG-related code

In reply to Emilio G. Cota

We first inject empty instrumentation from translator_loop. After translation, we go through the plugins to see what they want to register for, filling in the empty instrumentation. If if turns out that some instrumentation remains unused, we remove it.

This approach supports the following features:

- Inlining TCG code for simple operations. Note that we do not export TCG ops to plugins. Instead, we give them a C API to insert inlined ops. So far we only support adding an immediate to a u64, e.g. to count events.

- "Direct" callbacks. These are callbacks that do not go via a helper. Instead, the helper is defined at run-time, so that the plugin code is directly called from TCG. This makes direct callbacks as efficient as possible; they are therefore used for very frequent events, e.g. memory callbacks.

- Passing the host address to memory callbacks. Most of this is implemented in a later patch though.

- Instrumentation of memory accesses performed from helpers. See the corresponding comment, as well as a later patch.

---
 accel/tcg/plugin-helpers.h  |    6 +
 include/exec/helper-gen.h   |    1 +
 include/exec/helper-proto.h |    1 +
 include/exec/helper-tcg.h   |    1 +
 include/exec/plugin-gen.h   |   66 +++
 tcg/tcg-op.h                |   11 +
 tcg/tcg-opc.h               |    3 +
 tcg/tcg.h                   |   20 +
 accel/tcg/plugin-gen.c      | 1077 +++++++++++++++++++++++++++++++++++
 tcg/tcg.c                   |   17 +
 accel/tcg/Makefile.objs     |    1 +
 11 files changed, 1204 insertions(+)
 create mode 100644 accel/tcg/plugin-helpers.h
 create mode 100644 include/exec/plugin-gen.h
 create mode 100644 accel/tcg/plugin-gen.c
accel/tcg/plugin-helpers.h new file +6 -0
new file mode 100644
index 0000000000..5457a3a577
@@ -0,0 +1,6 @@
+#ifdef CONFIG_PLUGIN
+/* Note: no TCG flags because those are overwritten later */
+DEF_HELPER_2(plugin_vcpu_udata_cb, void, i32, ptr)
+DEF_HELPER_4(plugin_vcpu_mem_cb, void, i32, i32, i64, ptr)
+DEF_HELPER_5(plugin_vcpu_mem_haddr_cb, void, i32, i32, i64, ptr, ptr)
+#endif
include/exec/helper-gen.h +1 -0
index 22381a1708..236ff40524 100644
@@ -70,6 +70,7 @@ static inline void glue(gen_helper_, name)(dh_retvar_decl(ret)          \
 #include "trace/generated-helpers.h"
 #include "trace/generated-helpers-wrappers.h"
 #include "tcg-runtime.h"
+#include "plugin-helpers.h"
 
 #undef DEF_HELPER_FLAGS_0
 #undef DEF_HELPER_FLAGS_1
include/exec/helper-proto.h +1 -0
index 74943edb13..1c4ba9bc78 100644
@@ -33,6 +33,7 @@ dh_ctype(ret) HELPER(name) (dh_ctype(t1), dh_ctype(t2), dh_ctype(t3), \
 #include "helper.h"
 #include "trace/generated-helpers.h"
 #include "tcg-runtime.h"
+#include "plugin-helpers.h"
 
 #undef DEF_HELPER_FLAGS_0
 #undef DEF_HELPER_FLAGS_1
include/exec/helper-tcg.h +1 -0
index b3bdb0c399..3977b4c606 100644
@@ -48,6 +48,7 @@
 #include "helper.h"
 #include "trace/generated-helpers.h"
 #include "tcg-runtime.h"
+#include "plugin-helpers.h"
 
 #undef str
 #undef DEF_HELPER_FLAGS_0
include/exec/plugin-gen.h new file +66 -0

66 lines not on this page · raw message

tcg/tcg-op.h +11 -0
index 7513c1eb7c..e2948b10a2 100644
@@ -822,6 +822,17 @@ void tcg_gen_goto_tb(unsigned idx);
  */
 void tcg_gen_lookup_and_goto_ptr(void);
 
+static inline void tcg_gen_plugin_cb_start(unsigned from, unsigned type,
+                                           unsigned wr)
+{
+    tcg_gen_op3(INDEX_op_plugin_cb_start, from, type, wr);
+}
+
+static inline void tcg_gen_plugin_cb_end(void)
+{
+    tcg_emit_op(INDEX_op_plugin_cb_end);
+}
+
 #if TARGET_LONG_BITS == 32
 #define tcg_temp_new() tcg_temp_new_i32()
 #define tcg_global_reg_new tcg_global_reg_new_i32
tcg/tcg-opc.h +3 -0
index e3a43aabb6..d15d0b9874 100644
@@ -195,6 +195,9 @@ DEF(exit_tb, 0, 0, 1, TCG_OPF_BB_END)
 DEF(goto_tb, 0, 0, 1, TCG_OPF_BB_END)
 DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_END | IMPL(TCG_TARGET_HAS_goto_ptr))
 
+DEF(plugin_cb_start, 0, 0, 3, TCG_OPF_NOT_PRESENT)
+DEF(plugin_cb_end, 0, 0, 0, TCG_OPF_NOT_PRESENT)
+
 DEF(qemu_ld_i32, 1, TLADDR_ARGS, 1,
     TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS)
 DEF(qemu_st_i32, 0, TLADDR_ARGS + 1, 1,
tcg/tcg.h +20 -0
index a745e926bb..6fd525023b 100644
@@ -615,6 +615,9 @@ typedef struct TCGOp {
 
     /* Next and previous opcodes.  */
     QTAILQ_ENTRY(TCGOp) link;
+#ifdef CONFIG_PLUGIN
+    QSIMPLEQ_ENTRY(TCGOp) plugin_link;
+#endif
 
     /* Arguments for the opcode.  */
     TCGArg args[MAX_OPC_PARAM];
@@ -712,6 +715,23 @@ struct TCGContext {
 
     TCGLabel *exitreq_label;
 
+#ifdef CONFIG_PLUGIN
+    /*
+     * We keep one plugin_tb struct per TCGContext. Note that on every TB
+     * translation we clear but do not free its contents; this way we
+     * avoid a lot of malloc/free churn, since after a few TB's it's
+     * unlikely that we'll need to allocate either more instructions or more
+     * space for instructions (for variable-instruction-length ISAs).
+     */
+    struct qemu_plugin_tb *plugin_tb;
+
+    /* descriptor of the instruction being translated */
+    struct qemu_plugin_insn *plugin_insn;
+
+    /* list to quickly access the injected ops */
+    QSIMPLEQ_HEAD(, TCGOp) plugin_ops;
+#endif
+
     TCGTempSet free_temps[TCG_TYPE_COUNT * 2];
     TCGTemp temps[TCG_MAX_TEMPS]; /* globals first, temps after */
 
accel/tcg/plugin-gen.c new file +1077 -0

1,077 lines not on this page · raw message

tcg/tcg.c +17 -0
index e87c662a18..9d72f35133 100644
@@ -749,6 +749,12 @@ void tcg_register_thread(void)
     g_assert(n < max_cpus);
     atomic_set(&tcg_ctxs[n], s);
 
+#ifdef CONFIG_PLUGIN
+    if (n > 0) {
+        s->plugin_tb = g_new0(struct qemu_plugin_tb, 1);
+    }
+#endif
+
     tcg_ctx = s;
     qemu_mutex_lock(&region.lock);
     err = tcg_region_initial_alloc__locked(tcg_ctx);
@@ -945,6 +951,10 @@ void tcg_context_init(TCGContext *s)
         indirect_reg_alloc_order[i] = tcg_target_reg_alloc_order[i];
     }
 
+#ifdef CONFIG_PLUGIN
+    s->plugin_tb = g_new0(struct qemu_plugin_tb, 1);
+#endif
+
     tcg_ctx = s;
     /*
      * In user-mode we simply share the init context among threads, since we
@@ -1626,6 +1636,13 @@ void tcg_gen_callN(void *func, TCGTemp *ret, int nargs, TCGTemp **args)
     flags = info->flags;
     sizemask = info->sizemask;
 
+#ifdef CONFIG_PLUGIN
+    /* detect non-plugin helpers */
+    if (tcg_ctx->plugin_insn && unlikely(strncmp(info->name, "plugin_", 7))) {
+        tcg_ctx->plugin_insn->calls_helpers = true;
+    }
+#endif
+
 #if defined(__sparc__) && !defined(__arch64__) \
     && !defined(CONFIG_TCG_INTERPRETER)
     /* We have 64-bit values in one register, but need to pass as two
accel/tcg/Makefile.objs +1 -0
index d381a02f34..a92f2c454b 100644
@@ -6,3 +6,4 @@ obj-y += translator.o
 
 obj-$(CONFIG_USER_ONLY) += user-exec.o
 obj-$(call lnot,$(CONFIG_SOFTMMU)) += user-exec-stub.o
+obj-$(CONFIG_PLUGIN) += plugin-gen.o
Signature · 1 line
2.17.1
#34 lore raw

RFC v2 15/38 tcg: let plugins instrument memory accesses

In reply to Emilio G. Cota

XXX: store hostaddr from non-i386 TCG backends
XXX: what hostaddr to return for I/O accesses?
XXX: what hostaddr to return for cross-page accesses?

Here the trickiest feature is passing the host address to memory callbacks that request it. Perhaps it would be more appropriate to pass a "physical" address to plugins, but since in QEMU host addr ~= guest physical, I'm going with that for simplicity.

To keep the implementation simple we piggy-back on the TLB fast path, and thus can only provide the host address _after_ memory accesses have occurred. For the slow path, it's a bit tedious because there are many places to update, but it's fairly simple.

However, note that cross-page accesses are tricky, since the access might be to non-contiguous host addresses. So I'm punting on that and just passing NULL.

---
 accel/tcg/atomic_template.h               |  5 +++
 accel/tcg/softmmu_template.h              | 43 +++++++++++++++++-----
 include/exec/cpu-defs.h                   |  9 +++++
 include/exec/cpu_ldst.h                   |  9 +++++
 include/exec/cpu_ldst_template.h          | 43 ++++++++++++++--------
 include/exec/cpu_ldst_useronly_template.h | 42 +++++++++++++++-------
 tcg/tcg.h                                 |  1 +
 accel/tcg/cpu-exec.c                      |  2 ++
 accel/tcg/cputlb.c                        |  9 +++++
 tcg/i386/tcg-target.inc.c                 |  7 ++++
 tcg/tcg-op.c                              | 44 ++++++++++++++++++-----
 11 files changed, 169 insertions(+), 45 deletions(-)
accel/tcg/atomic_template.h +5 -0
index 2f7d5ee02a..5619c4b4b9 100644
@@ -18,6 +18,7 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "qemu/plugin.h"
 #include "trace/mem.h"
 
 #if DATA_SIZE == 16
@@ -73,6 +74,8 @@ void atomic_trace_rmw_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_rmw_post(CPUArchState *env, target_ulong addr,
                                          void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info | TRACE_MEM_ST);
 }
 
 static inline
@@ -84,6 +87,7 @@ void atomic_trace_ld_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_ld_post(CPUArchState *env, target_ulong addr,
                                         void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
 }
 
 static inline
@@ -95,6 +99,7 @@ void atomic_trace_st_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_st_post(CPUArchState *env, target_ulong addr,
                                         void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
 }
 #endif /* ATOMIC_TEMPLATE_COMMON */
 
accel/tcg/softmmu_template.h +34 -9

160 lines not on this page · raw message

include/exec/cpu-defs.h +9 -0
index 40cd5d4774..f46bc0917d 100644
@@ -178,6 +178,14 @@ typedef struct CPUTLBDesc {
     CPUIOTLBEntry iotlb[NB_MMU_MODES][CPU_TLB_SIZE];
 #endif /* TCG_TARGET_IMPLEMENTS_DYN_TLB */
 
+#ifdef CONFIG_PLUGIN
+# define CPU_PLUGIN_HOSTADDR                            \
+    /* stores the host address of a guest access */     \
+    void *hostaddr;
+#else
+# define CPU_PLUGIN_HOSTADDR
+#endif
+
 #define CPU_COMMON_TLB                                                  \
     /* The meaning of the MMU modes is defined in the target code. */   \
     /* tlb_lock serializes updates to tlb_table and tlb_v_table */      \
@@ -186,6 +194,7 @@ typedef struct CPUTLBDesc {
     CPUTLBEntry tlb_v_table[NB_MMU_MODES][CPU_VTLB_SIZE];               \
     CPU_IOTLB                                                           \
     CPUIOTLBEntry iotlb_v[NB_MMU_MODES][CPU_VTLB_SIZE];                 \
+    CPU_PLUGIN_HOSTADDR                                                 \
     size_t tlb_flush_count;                                             \
     target_ulong tlb_flush_addr;                                        \
     target_ulong tlb_flush_mask;                                        \
include/exec/cpu_ldst.h +9 -0
index 83b2907d86..32dd8dd603 100644
@@ -85,6 +85,15 @@ typedef target_ulong abi_ptr;
 #define TARGET_ABI_FMT_ptr TARGET_ABI_FMT_lx
 #endif
 
+static inline void *read_hostaddr(CPUArchState *env)
+{
+#if defined(CONFIG_SOFTMMU) && defined(CONFIG_PLUGIN)
+    return env->hostaddr;
+#else
+    return NULL;
+#endif
+}
+
 #if defined(CONFIG_USER_ONLY)
 
 extern __thread uintptr_t helper_retaddr;
include/exec/cpu_ldst_template.h +28 -15

97 lines not on this page · raw message

include/exec/cpu_ldst_useronly_template.h +30 -12

71 lines not on this page · raw message

tcg/tcg.h +1 -0
index a376f83ab6..8938dcf52e 100644
@@ -29,6 +29,7 @@
 #include "cpu.h"
 #include "exec/tb-context.h"
 #include "qemu/bitops.h"
+#include "qemu/plugin.h"
 #include "qemu/queue.h"
 #include "tcg-mo.h"
 #include "tcg-target.h"
accel/tcg/cpu-exec.c +2 -0
index d590f1f6c0..4c8265a908 100644
@@ -267,6 +267,7 @@ void cpu_exec_step_atomic(CPUState *cpu)
         tcg_debug_assert(!have_mmap_lock());
 #endif
         assert_no_pages_locked();
+        qemu_plugin_disable_mem_helpers(cpu);
     }
 
     if (in_exclusive_region) {
@@ -716,6 +717,7 @@ int cpu_exec(CPUState *cpu)
         if (qemu_mutex_iothread_locked()) {
             qemu_mutex_unlock_iothread();
         }
+        qemu_plugin_disable_mem_helpers(cpu);
     }
 
     /* if an exception is pending, we execute it here */
accel/tcg/cputlb.c +9 -0
index 5c61908084..3bdf98d2c3 100644
@@ -1208,6 +1208,15 @@ static void *atomic_mmu_lookup(CPUArchState *env, target_ulong addr,
     cpu_loop_exit_atomic(ENV_GET_CPU(env), retaddr);
 }
 
+static inline void set_hostaddr(CPUArchState *env, TCGMemOp mo, void *haddr)
+{
+#ifdef CONFIG_PLUGIN
+    if (mo & MO_HADDR) {
+        env->hostaddr = haddr;
+    }
+#endif
+}
+
 #ifdef TARGET_WORDS_BIGENDIAN
 # define TGT_BE(X)  (X)
 # define TGT_LE(X)  BSWAP(X)
tcg/i386/tcg-target.inc.c +7 -0
index 5cbb07deab..eb3725f2e3 100644
@@ -1685,6 +1685,13 @@ static inline void tcg_out_tlb_load(TCGContext *s, TCGReg addrlo, TCGReg addrhi,
     /* add addend(r0), r1 */
     tcg_out_modrm_offset(s, OPC_ADD_GvEv + hrexw, r1, r0,
                          offsetof(CPUTLBEntry, addend));
+
+#ifdef CONFIG_PLUGIN
+    if (opc & MO_HADDR) {
+        tcg_out_st(s, TCG_TYPE_PTR, r1, TCG_AREG0,
+                   offsetof(CPUArchState, hostaddr));
+    }
+#endif
 }
 
 /*
tcg/tcg-op.c +35 -9

108 lines not on this page · raw message

Signature · 1 line
2.17.1
#46 lore raw

RFC v2 25/38 target/i386: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/i386/translate.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
target/i386/translate.c +5 -5
index 83c1ebe491..6ea784da54 100644
@@ -1900,28 +1900,28 @@ static uint64_t advance_pc(CPUX86State *env, DisasContext *s, int num_bytes)
 
 static inline uint8_t x86_ldub_code(CPUX86State *env, DisasContext *s)
 {
-    return cpu_ldub_code(env, advance_pc(env, s, 1));
+    return translator_ldub(env, advance_pc(env, s, 1));
 }
 
 static inline int16_t x86_ldsw_code(CPUX86State *env, DisasContext *s)
 {
-    return cpu_ldsw_code(env, advance_pc(env, s, 2));
+    return translator_ldsw(env, advance_pc(env, s, 2));
 }
 
 static inline uint16_t x86_lduw_code(CPUX86State *env, DisasContext *s)
 {
-    return cpu_lduw_code(env, advance_pc(env, s, 2));
+    return translator_lduw(env, advance_pc(env, s, 2));
 }
 
 static inline uint32_t x86_ldl_code(CPUX86State *env, DisasContext *s)
 {
-    return cpu_ldl_code(env, advance_pc(env, s, 4));
+    return translator_ldl(env, advance_pc(env, s, 4));
 }
 
 #ifdef TARGET_X86_64
 static inline uint64_t x86_ldq_code(CPUX86State *env, DisasContext *s)
 {
-    return cpu_ldq_code(env, advance_pc(env, s, 8));
+    return translator_ldq(env, advance_pc(env, s, 8));
 }
 #endif
 
Signature · 1 line
2.17.1
#47 lore raw

RFC v2 26/38 target/hppa: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/hppa/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/hppa/translate.c +1 -1
index df9179e70f..806dbda51f 100644
@@ -4754,7 +4754,7 @@ static void hppa_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs)
     {
         /* Always fetch the insn, even if nullified, so that we check
            the page permissions for execute.  */
-        uint32_t insn = cpu_ldl_code(env, ctx->base.pc_next);
+        uint32_t insn = translator_ldl(env, ctx->base.pc_next);
 
         /* Set up the IA queue for the next insn.
            This will be overwritten by a branch.  */
Signature · 1 line
2.17.1
#48 lore raw

RFC v2 27/38 target/m68k: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/m68k/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/m68k/translate.c +1 -1
index d55e707cf6..71263f8b37 100644
@@ -373,7 +373,7 @@ static TCGv gen_ldst(DisasContext *s, int opsize, TCGv addr, TCGv val,
 static inline uint16_t read_im16(CPUM68KState *env, DisasContext *s)
 {
     uint16_t im;
-    im = cpu_lduw_code(env, s->pc);
+    im = translator_lduw(env, s->pc);
     s->pc += 2;
     return im;
 }
Signature · 1 line
2.17.1
#49 lore raw

RFC v2 28/38 target/alpha: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/alpha/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/alpha/translate.c +1 -1
index 25cd95931d..f8d194994a 100644
@@ -2987,7 +2987,7 @@ static void alpha_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)
 {
     DisasContext *ctx = container_of(dcbase, DisasContext, base);
     CPUAlphaState *env = cpu->env_ptr;
-    uint32_t insn = cpu_ldl_code(env, ctx->base.pc_next);
+    uint32_t insn = translator_ldl(env, ctx->base.pc_next);
 
     ctx->base.pc_next += 4;
     ctx->base.is_jmp = translate_one(ctx, insn);
Signature · 1 line
2.17.1
#50 lore raw

RFC v2 29/38 target/riscv: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/riscv/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/riscv/translate.c +1 -1
index 18d7b6d147..fa96f45a69 100644
@@ -1848,7 +1848,7 @@ static void riscv_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)
     DisasContext *ctx = container_of(dcbase, DisasContext, base);
     CPURISCVState *env = cpu->env_ptr;
 
-    ctx->opcode = cpu_ldl_code(env, ctx->base.pc_next);
+    ctx->opcode = translator_ldl(env, ctx->base.pc_next);
     decode_opc(env, ctx);
     ctx->base.pc_next = ctx->pc_succ_insn;
 
Signature · 1 line
2.17.1
#51 lore raw

RFC v2 30/38 target/sparc: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/sparc/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/sparc/translate.c +1 -1
index 74315cdf09..2c754b6163 100644
@@ -5900,7 +5900,7 @@ static void sparc_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs)
     CPUSPARCState *env = cs->env_ptr;
     unsigned int insn;
 
-    insn = cpu_ldl_code(env, dc->pc);
+    insn = translator_ldl(env, dc->pc);
     dc->base.pc_next += 4;
     disas_sparc_insn(dc, insn);
 
Signature · 1 line
2.17.1
#52 lore raw

RFC v2 31/38 target/xtensa: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/xtensa/translate.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
target/xtensa/translate.c +2 -2
index 46e1338448..c140742562 100644
@@ -882,7 +882,7 @@ static inline unsigned xtensa_op0_insn_len(DisasContext *dc, uint8_t op0)
 static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
 {
     xtensa_isa isa = dc->config->isa;
-    unsigned char b[MAX_INSN_LENGTH] = {cpu_ldub_code(env, dc->pc)};
+    unsigned char b[MAX_INSN_LENGTH] = {translator_ldub(env, dc->pc)};
     unsigned len = xtensa_op0_insn_len(dc, b[0]);
     xtensa_format fmt;
     int slot, slots;
@@ -914,7 +914,7 @@ static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
                       dc->pc);
     }
     for (i = 1; i < len; ++i) {
-        b[i] = cpu_ldub_code(env, dc->pc + i);
+        b[i] = translator_ldub(env, dc->pc + i);
     }
     xtensa_insnbuf_from_chars(isa, dc->insnbuf, b, len);
     fmt = xtensa_format_decode(isa, dc->insnbuf);
Signature · 1 line
2.17.1
#55 lore raw

RFC v2 32/38 target/openrisc: fetch code with translator_ld

In reply to Emilio G. Cota
---
 target/openrisc/translate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
target/openrisc/translate.c +1 -1
index a271cd3903..6b5efc0155 100644
@@ -1305,7 +1305,7 @@ static void openrisc_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs)
 {
     DisasContext *dc = container_of(dcbase, DisasContext, base);
     OpenRISCCPU *cpu = OPENRISC_CPU(cs);
-    uint32_t insn = cpu_ldl_code(&cpu->env, dc->base.pc_next);
+    uint32_t insn = translator_ldl(&cpu->env, dc->base.pc_next);
 
     if (!decode(dc, insn)) {
         gen_illegal_exception(dc);
Signature · 1 line
2.17.1
#56 lore raw

RFC v2 33/38 translator: inject instrumentation from plugins

In reply to Emilio G. Cota
---
 accel/tcg/translator.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
accel/tcg/translator.c +16 -0
index afd0a49ea6..68174a2986 100644
@@ -17,6 +17,7 @@
 #include "exec/gen-icount.h"
 #include "exec/log.h"
 #include "exec/translator.h"
+#include "exec/plugin-gen.h"
 
 /* Pairs with tcg_clear_temp_count.
    To be called by #TranslatorOps.{translate_insn,tb_stop} if
@@ -35,6 +36,7 @@ void translator_loop(const TranslatorOps *ops, DisasContextBase *db,
                      CPUState *cpu, TranslationBlock *tb)
 {
     int bp_insn = 0;
+    bool plugin_enabled;
 
     /* Initialize DisasContext */
     db->tb = tb;
@@ -67,11 +69,17 @@ void translator_loop(const TranslatorOps *ops, DisasContextBase *db,
     ops->tb_start(db, cpu);
     tcg_debug_assert(db->is_jmp == DISAS_NEXT);  /* no early exit */
 
+    plugin_enabled = plugin_gen_tb_start(cpu, tb);
+
     while (true) {
         db->num_insns++;
         ops->insn_start(db, cpu);
         tcg_debug_assert(db->is_jmp == DISAS_NEXT);  /* no early exit */
 
+        if (plugin_enabled) {
+            plugin_gen_insn_start(cpu, db);
+        }
+
         /* Pass breakpoint hits to target for further processing */
         if (!db->singlestep_enabled
             && unlikely(!QTAILQ_EMPTY(&cpu->breakpoints))) {
@@ -107,6 +115,10 @@ void translator_loop(const TranslatorOps *ops, DisasContextBase *db,
             ops->translate_insn(db, cpu);
         }
 
+        if (plugin_enabled) {
+            plugin_gen_insn_end();
+        }
+
         /* Stop translation if translate_insn so indicated.  */
         if (db->is_jmp != DISAS_NEXT) {
             break;
@@ -124,6 +136,10 @@ void translator_loop(const TranslatorOps *ops, DisasContextBase *db,
     ops->tb_stop(db, cpu);
     gen_tb_end(db->tb, db->num_insns - bp_insn);
 
+    if (plugin_enabled) {
+        plugin_gen_tb_end(cpu);
+    }
+
     /* The disas_log hook may use these values rather than recompute.  */
     db->tb->size = db->pc_next - db->pc_first;
     db->tb->icount = db->num_insns;
Signature · 1 line
2.17.1
#57 lore raw

RFC v2 34/38 plugin: add API symbols to qemu-plugins.symbols

In reply to Emilio G. Cota
---
 qemu-plugins.symbols | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
 create mode 100644 qemu-plugins.symbols
qemu-plugins.symbols new file +34 -0
new file mode 100644
index 0000000000..2a5b18862a
@@ -0,0 +1,34 @@
+{
+  qemu_plugin_uninstall;
+  qemu_plugin_register_vcpu_init_cb;
+  qemu_plugin_register_vcpu_exit_cb;
+  qemu_plugin_register_vcpu_idle_cb;
+  qemu_plugin_register_vcpu_resume_cb;
+  qemu_plugin_register_vcpu_insn_exec_cb;
+  qemu_plugin_register_vcpu_insn_exec_inline;
+  qemu_plugin_register_vcpu_mem_cb;
+  qemu_plugin_register_vcpu_mem_haddr_cb;
+  qemu_plugin_register_vcpu_mem_inline;
+  qemu_plugin_ram_addr_from_host;
+  qemu_plugin_register_vcpu_tb_trans_cb;
+  qemu_plugin_register_vcpu_tb_exec_cb;
+  qemu_plugin_register_vcpu_tb_exec_inline;
+  qemu_plugin_register_flush_cb;
+  qemu_plugin_register_vcpu_syscall_cb;
+  qemu_plugin_register_vcpu_syscall_ret_cb;
+  qemu_plugin_register_atexit_cb;
+  qemu_plugin_tb_n_insns;
+  qemu_plugin_tb_get_insn;
+  qemu_plugin_tb_vaddr;
+  qemu_plugin_insn_data;
+  qemu_plugin_insn_size;
+  qemu_plugin_insn_vaddr;
+  qemu_plugin_insn_haddr;
+  qemu_plugin_mem_size_shift;
+  qemu_plugin_mem_is_sign_extended;
+  qemu_plugin_mem_is_big_endian;
+  qemu_plugin_mem_is_store;
+  qemu_plugin_vcpu_for_each;
+  qemu_plugin_n_vcpus;
+  qemu_plugin_n_max_vcpus;
+};
Signature · 1 line
2.17.1
#58 lore raw

RFC v2 35/38 configure: add --enable-plugins

In reply to Emilio G. Cota

Add support for both ld (using --dynamic-list) and MacOSX's ld64 (-exported_symbols_list).

---
 configure       | 82 +++++++++++++++++++++++++++++++++++++++++++++++++
 Makefile        |  1 +
 Makefile.target | 18 ++++++++++-
 .gitignore      |  2 ++
 4 files changed, 102 insertions(+), 1 deletion(-)
configure +82 -0
index 1c473ce95b..91f9c08ae2 100755
@@ -30,6 +30,7 @@ TMPO="${TMPDIR1}/${TMPB}.o"
 TMPCXX="${TMPDIR1}/${TMPB}.cxx"
 TMPE="${TMPDIR1}/${TMPB}.exe"
 TMPMO="${TMPDIR1}/${TMPB}.mo"
+TMPTXT="${TMPDIR1}/${TMPB}.txt"
 
 rm -f config.log
 
@@ -474,6 +475,7 @@ libxml2=""
 docker="no"
 debug_mutex="no"
 libpmem=""
+plugins="no"
 
 # cross compilers defaults, can be overridden with --cross-cc-ARCH
 cross_cc_aarch64="aarch64-linux-gnu-gcc"
@@ -1444,6 +1446,10 @@ for opt do
   ;;
   --disable-libpmem) libpmem=no
   ;;
+  --enable-plugins) plugins="yes"
+  ;;
+  --disable-plugins) plugins="no"
+  ;;
   *)
       echo "ERROR: unknown option $opt"
       echo "Try '$0 --help' for more information"
@@ -1634,6 +1640,8 @@ Advanced options (experts only):
                            xen pv domain builder
   --enable-debug-stack-usage
                            track the maximum stack usage of stacks created by qemu_alloc_stack
+  --enable-plugins
+                           enable plugins via shared library loading
 
 Optional features, enabled with --enable-FEATURE and
 disabled with --disable-FEATURE, default is enabled if available:
@@ -5143,6 +5151,58 @@ if compile_prog "" "" ; then
   atomic64=yes
 fi
 
+#########################################
+# See if --dynamic-list is supported by the linker
+
+cat > $TMPTXT <<EOF
+{
+  foo;
+};
+EOF
+
+cat > $TMPC <<EOF
+#include <stdio.h>
+void foo(void);
+
+void foo(void)
+{
+  printf("foo\n");
+}
+
+int main(void)
+{
+  foo();
+  return 0;
+}
+EOF
+
+ld_dynamic_list="no"
+if compile_prog "" "-Wl,--dynamic-list=$TMPTXT" ; then
+  ld_dynamic_list="yes"
+fi
+
+#########################################
+# See if -exported_symbols_list is supported by the linker
+
+cat > $TMPTXT <<EOF
+  _foo
+EOF
+
+ld_exported_symbols_list="no"
+if compile_prog "" "-Wl,-exported_symbols_list,$TMPTXT" ; then
+  ld_exported_symbols_list="yes"
+fi
+
+if  test "$plugins" = "yes" &&
+    test "$ld_dynamic_list" = "no" &&
+    test "$ld_exported_symbols_list" = "no" ; then
+  error_exit \
+      "Plugin support requires specifying a set of symbols that " \
+      "are exported to plugins. Unfortunately your linker doesn't " \
+      "support the flag (--dynamic-list or -exported_symbols_list) used " \
+      "for this purpose."
+fi
+
 ########################################
 # See if 16-byte vector operations are supported.
 # Even without a vector unit the compiler may expand these.
@@ -6027,6 +6087,7 @@ echo "VxHS block device $vxhs"
 echo "capstone          $capstone"
 echo "docker            $docker"
 echo "libpmem support   $libpmem"
+echo "plugin support    $plugins"
 
 if test "$sdl_too_old" = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -6779,6 +6840,27 @@ if test "$libpmem" = "yes" ; then
   echo "CONFIG_LIBPMEM=y" >> $config_host_mak
 fi
 
+if test "$plugins" = "yes" ; then
+    echo "CONFIG_PLUGIN=y" >> $config_host_mak
+    LIBS="-ldl $LIBS"
+    # Copy the export object list to the build dir
+    if test "$ld_dynamic_list" = "yes" ; then
+	echo "CONFIG_HAS_LD_DYNAMIC_LIST=yes" >> $config_host_mak
+	ld_symbols=qemu-plugins-ld.symbols
+	cp "$source_path/qemu-plugins.symbols" $ld_symbols
+    elif test "$ld_exported_symbols_list" = "yes" ; then
+	echo "CONFIG_HAS_LD_EXPORTED_SYMBOLS_LIST=yes" >> $config_host_mak
+	ld64_symbols=qemu-plugins-ld64.symbols
+	echo "# Automatically generated by configure - do not modify" > $ld64_symbols
+	grep 'qemu_' "$source_path/qemu-plugins.symbols" | sed 's/;//g' | \
+	    sed -E 's/^[[:space:]]*(.*)/_\1/' >> $ld64_symbols
+    else
+	error_exit \
+	    "If \$plugins=yes, either \$ld_dynamic_list or " \
+	    "\$ld_exported_symbols_list should have been set to 'yes'."
+    fi
+fi
+
 if test "$tcg_interpreter" = "yes"; then
   QEMU_INCLUDES="-iquote \$(SRC_PATH)/tcg/tci $QEMU_INCLUDES"
 elif test "$ARCH" = "sparc64" ; then
Makefile +1 -0
index 9cb3076d84..6fd15b296f 100644
@@ -778,6 +778,7 @@ distclean: clean
 	rm -f qemu-doc.fn qemu-doc.fns qemu-doc.info qemu-doc.ky qemu-doc.kys
 	rm -f qemu-doc.log qemu-doc.pdf qemu-doc.pg qemu-doc.toc qemu-doc.tp
 	rm -f qemu-doc.vr qemu-doc.txt
+	rm -f qemu-plugins-ld.symbols qemu-plugins-ld64.symbols
 	rm -f config.log
 	rm -f linux-headers/asm
 	rm -f docs/version.texi
Makefile.target +17 -1
index 75637c285c..7dada1f368 100644
@@ -107,7 +107,23 @@ obj-y += target/$(TARGET_BASE_ARCH)/
 obj-y += disas.o
 obj-$(call notempty,$(TARGET_XML_FILES)) += gdbstub-xml.o
 
-obj-$(CONFIG_PLUGINS) += plugin.o
+ifdef CONFIG_PLUGIN
+obj-y += plugin.o
+# Abuse -libs suffix to only link with --dynamic-list/-exported_symbols_list
+# when the final binary includes the plugin object.
+#
+# Note that simply setting LDFLAGS is not enough: we build binaries that
+# never link plugin.o, and the linker might fail (at least ld64 does)
+# if the symbols in the list are not in the output binary.
+ ifdef CONFIG_HAS_LD_DYNAMIC_LIST
+ plugin.o-libs := -Wl,--dynamic-list=$(BUILD_DIR)/qemu-plugins-ld.symbols
+ else
+  ifdef CONFIG_HAS_LD_EXPORTED_SYMBOLS_LIST
+  plugin.o-libs := \
+	-Wl,-exported_symbols_list,$(BUILD_DIR)/qemu-plugins-ld64.symbols
+  endif
+ endif
+endif
 
 #########################################################
 # Linux user emulator target
.gitignore +2 -0
index 64efdfd929..29f6446508 100644
@@ -213,3 +213,5 @@ trace-dtrace-root.dtrace
 trace-ust-all.h
 trace-ust-all.c
 /target/arm/decode-sve.inc.c
+qemu-plugins-ld.symbols
+qemu-plugins-ld64.symbols
Signature · 1 line
2.17.1
#59 lore raw

RFC v2 36/38 vl: support -plugin option

In reply to Emilio G. Cota

From: Lluís Vilanova <[email protected]>

[ cota: s/instrument/plugin ]
---
 vl.c            | 11 +++++++++++
 qemu-options.hx | 17 +++++++++++++++++
 2 files changed, 28 insertions(+)
vl.c +11 -0
index 1fcacc5caa..a1d6b76315 100644
@@ -111,6 +111,7 @@ int main(int argc, char **argv)
 
 #include "trace-root.h"
 #include "trace/control.h"
+#include "qemu/plugin.h"
 #include "qemu/queue.h"
 #include "sysemu/arch_init.h"
 
@@ -2998,6 +2999,7 @@ int main(int argc, char **argv, char **envp)
     } BlockdevOptions_queue;
     QSIMPLEQ_HEAD(, BlockdevOptions_queue) bdo_queue
         = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
+    struct qemu_plugin_list plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
 
     module_call_init(MODULE_INIT_TRACE);
 
@@ -3026,6 +3028,7 @@ int main(int argc, char **argv, char **envp)
     qemu_add_opts(&qemu_global_opts);
     qemu_add_opts(&qemu_mon_opts);
     qemu_add_opts(&qemu_trace_opts);
+    qemu_plugin_add_opts();
     qemu_add_opts(&qemu_option_rom_opts);
     qemu_add_opts(&qemu_machine_opts);
     qemu_add_opts(&qemu_accel_opts);
@@ -3840,6 +3843,9 @@ int main(int argc, char **argv, char **envp)
                 g_free(trace_file);
                 trace_file = trace_opt_parse(optarg);
                 break;
+            case QEMU_OPTION_plugin:
+                qemu_plugin_opt_parse(optarg, &plugin_list);
+                break;
             case QEMU_OPTION_readconfig:
                 {
                     int ret = qemu_read_config_file(optarg);
@@ -4137,6 +4143,11 @@ int main(int argc, char **argv, char **envp)
                                machine_class->default_machine_opts, 0);
     }
 
+    /* process plugin before CPUs are created, but once -smp has been parsed */
+    if (qemu_plugin_load_list(&plugin_list)) {
+        exit(1);
+    }
+
     qemu_opts_foreach(qemu_find_opts("device"),
                       default_driver_check, NULL, NULL);
     qemu_opts_foreach(qemu_find_opts("global"),
qemu-options.hx +17 -0
index 08f8516a9a..f3549eb2ec 100644
@@ -3847,6 +3847,23 @@ HXCOMM HX does not support conditional compilation of text.
 @findex -trace
 @include qemu-option-trace.texi
 ETEXI
+DEF("plugin", HAS_ARG, QEMU_OPTION_plugin,
+    "-plugin [file=]<file>[,arg=<string>]\n"
+    "                load a plugin\n",
+    QEMU_ARCH_ALL)
+STEXI
+@item -plugin file=@var{file}[,arg=@var{string}]
+@findex -plugin
+
+Load a plugin.
+
+@table @option
+@item file=@var{file}
+Load the given plugin from a shared library file.
+@item arg=@var{string}
+Argument string passed to the plugin. (Can be given multiple times.)
+@end table
+ETEXI
 
 HXCOMM Internal use
 DEF("qtest", HAS_ARG, QEMU_OPTION_qtest, "", QEMU_ARCH_ALL)
Signature · 1 line
2.17.1
#60 lore raw

RFC v2 37/38 linux-user: support -plugin option

In reply to Emilio G. Cota

From: Lluís Vilanova <[email protected]>

[ cota: s/instrument/plugin ]
---
 linux-user/main.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
linux-user/main.c +18 -0
index 923cbb753a..482766f0f4 100644
@@ -28,6 +28,7 @@
 #include "qemu/config-file.h"
 #include "qemu/cutils.h"
 #include "qemu/help_option.h"
+#include "qemu/plugin.h"
 #include "cpu.h"
 #include "exec/exec-all.h"
 #include "tcg.h"
@@ -385,6 +386,15 @@ static void handle_arg_trace(const char *arg)
     trace_file = trace_opt_parse(arg);
 }
 
+static struct qemu_plugin_list plugins = QTAILQ_HEAD_INITIALIZER(plugins);
+
+#ifdef CONFIG_PLUGIN
+static void handle_arg_plugin(const char *arg)
+{
+    qemu_plugin_opt_parse(arg, &plugins);
+}
+#endif
+
 struct qemu_argument {
     const char *argv;
     const char *env;
@@ -436,6 +446,10 @@ static const struct qemu_argument arg_table[] = {
      "",           "Seed for pseudo-random number generator"},
     {"trace",      "QEMU_TRACE",       true,  handle_arg_trace,
      "",           "[[enable=]<pattern>][,events=<file>][,file=<file>]"},
+#ifdef CONFIG_PLUGIN
+    {"plugin",     "QEMU_PLUGIN",      true,  handle_arg_plugin,
+     "",           "[file=]<file>[,arg=<string>]"},
+#endif
     {"version",    "QEMU_VERSION",     false, handle_arg_version,
      "",           "display version information and exit"},
     {NULL, NULL, false, NULL, NULL, NULL}
@@ -627,6 +641,7 @@ int main(int argc, char **argv, char **envp)
     srand(time(NULL));
 
     qemu_add_opts(&qemu_trace_opts);
+    qemu_plugin_add_opts();
 
     optind = parse_args(argc, argv);
 
@@ -634,6 +649,9 @@ int main(int argc, char **argv, char **envp)
         exit(1);
     }
     trace_init_file(trace_file);
+    if (qemu_plugin_load_list(&plugins)) {
+        exit(1);
+    }
 
     /* Zero out regs */
     memset(regs, 0, sizeof(struct target_pt_regs));
Signature · 1 line
2.17.1
#61 lore raw

RFC v2 38/38 tests/plugin: add sample plugins

In reply to Emilio G. Cota

Pass arguments with -plugin=libfoo.so,arg=bar,arg=baz

---
 configure             |  4 +-
 tests/plugin/bb.c     | 66 ++++++++++++++++++++++++++++++
 tests/plugin/empty.c  | 30 ++++++++++++++
 tests/plugin/insn.c   | 63 +++++++++++++++++++++++++++++
 tests/plugin/mem.c    | 93 +++++++++++++++++++++++++++++++++++++++++++
 tests/plugin/Makefile | 28 +++++++++++++
 6 files changed, 282 insertions(+), 2 deletions(-)
 create mode 100644 tests/plugin/bb.c
 create mode 100644 tests/plugin/empty.c
 create mode 100644 tests/plugin/insn.c
 create mode 100644 tests/plugin/mem.c
 create mode 100644 tests/plugin/Makefile
configure +2 -2
index 91f9c08ae2..1440b5e688 100755
@@ -7450,14 +7450,14 @@ fi
 
 # build tree in object directory in case the source is not in the current directory
 DIRS="tests tests/tcg tests/tcg/cris tests/tcg/lm32 tests/libqos tests/qapi-schema tests/tcg/xtensa tests/qemu-iotests tests/vm"
-DIRS="$DIRS tests/fp"
+DIRS="$DIRS tests/fp tests/plugin"
 DIRS="$DIRS docs docs/interop fsdev scsi"
 DIRS="$DIRS pc-bios/optionrom pc-bios/spapr-rtas pc-bios/s390-ccw"
 DIRS="$DIRS roms/seabios roms/vgabios"
 FILES="Makefile tests/tcg/Makefile qdict-test-data.txt"
 FILES="$FILES tests/tcg/cris/Makefile tests/tcg/cris/.gdbinit"
 FILES="$FILES tests/tcg/lm32/Makefile tests/tcg/xtensa/Makefile po/Makefile"
-FILES="$FILES tests/fp/Makefile"
+FILES="$FILES tests/fp/Makefile tests/plugin/Makefile"
 FILES="$FILES pc-bios/optionrom/Makefile pc-bios/keymaps"
 FILES="$FILES pc-bios/spapr-rtas/Makefile"
 FILES="$FILES pc-bios/s390-ccw/Makefile"
tests/plugin/bb.c new file +66 -0

66 lines not on this page · raw message

tests/plugin/empty.c new file +30 -0
new file mode 100644
index 0000000000..b2e30bddb2
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2018, Emilio G. Cota <[email protected]>
+ *
+ * License: GNU GPL, version 2 or later.
+ *   See the COPYING file in the top-level directory.
+ */
+#include <inttypes.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#include <qemu-plugin.h>
+
+/*
+ * Empty TB translation callback.
+ * This allows us to measure the overhead of injecting and then
+ * removing empty instrumentation.
+ */
+static void vcpu_tb_trans(qemu_plugin_id_t id, unsigned int cpu_index,
+                          struct qemu_plugin_tb *tb)
+{ }
+
+QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, int argc,
+                                           char **argv)
+{
+    qemu_plugin_register_vcpu_tb_trans_cb(id, vcpu_tb_trans);
+    return 0;
+}
tests/plugin/insn.c new file +63 -0

63 lines not on this page · raw message

tests/plugin/mem.c new file +93 -0

93 lines not on this page · raw message

tests/plugin/Makefile new file +28 -0
new file mode 100644
index 0000000000..f9a3546ea3
@@ -0,0 +1,28 @@
+BUILD_DIR := $(CURDIR)/../..
+
+include $(BUILD_DIR)/config-host.mak
+include $(SRC_PATH)/rules.mak
+
+$(call set-vpath, $(SRC_PATH)/tests/plugin)
+
+NAMES :=
+NAMES += bb
+NAMES += empty
+NAMES += insn
+NAMES += mem
+
+SONAMES := $(addsuffix .so,$(addprefix lib,$(NAMES)))
+
+QEMU_CFLAGS += -fPIC
+QEMU_CFLAGS += -I$(SRC_PATH)/include/qemu
+
+all: $(SONAMES)
+
+lib%.so: %.o
+	$(CC) -shared -Wl,-soname,$@ -o $@ $^ $(LDLIBS)
+
+clean:
+	rm -f *.o *.so *.d
+	rm -Rf .libs
+
+.PHONY: all clean
Signature · 1 line
2.17.1
#18 lore raw

Re: [Qemu-devel] [RFC v2 06/38] plugin: add core code

In reply to Emilio G. Cota
Quoted 22 lines

From: Emilio G. Cota [mailto:[email protected]]

include/qemu/plugin.h new file +20 -0
+/*
+ * A dynamic callback has an insertion point that is determined at run-time.
+ * Usually the insertion point is somewhere in the code cache; think for
+ * instance of a callback to be called upon the execution of a particular TB.
+ */
+struct qemu_plugin_dyn_cb {
+    union qemu_plugin_cb_sig f;
+    void *userp;
+    unsigned tcg_flags;
+    enum plugin_dyn_cb_type type;
+    /* @rw applies to mem callbacks only (both regular and inline) */
+    enum qemu_plugin_mem_rw rw;
+    /* fields specific to each dyn_cb type go here */
+    union {
+        struct {
+            bool haddr;
+        } mem;
+        struct {
+            enum qemu_plugin_op op;
+            uint64_t imm;

include/qemu/plugin.h line 121

Quoted 10 lines
include/qemu/plugin.h new file +10 -0
+        } inline_insn;
+    };
+};
+
+struct qemu_plugin_dyn_cb_arr {
+    struct qemu_plugin_dyn_cb *data;
+    size_t n;
+    size_t capacity;
+};
+

Why not list or something dynamic? Is the indexing required?

Can you add the comments for the data structures and functions? It is very hard to seek through the whole patch to get the details about them.

Pavel Dovgalyuk

#19 lore raw

Re: [Qemu-devel] [RFC v2 06/38] plugin: add core code

Quoted 1 line · Pavel Dovgalyuk
Quoted 1 line

From: Emilio G. Cota [mailto:[email protected]]

(snip)

Quoted 8 lines

include/qemu/plugin.h line 121

Quoted 6 lines
include/qemu/plugin.h new file +6 -0
+struct qemu_plugin_dyn_cb_arr {
+    struct qemu_plugin_dyn_cb *data;
+    size_t n;
+    size_t capacity;
+};
+

Why not list or something dynamic?

Performance. Registering of dynamic callbacks can happen very frequently (e.g. several times per instruction translated), so we avoid malloc/free churn by keeping an array of callback requests that we reuse across translated TB's. The hierarchy is:

struct qemu_plugin_tb {
	insns[n_insns_in_the_tb] {
		dyn_cb_arr[various types];
	}
}

Each array has a "capacity" field so that we only ever expand the arrays. This ensures that the amortized cost of adding callbacks is negligible.

Quoted 1 line

Is the indexing required?

No, this is done just for performance.

Quoted 2 lines

Can you add the comments for the data structures and functions? It is very hard to seek through the whole patch to get the details about them.

I had some comments but then the code evolved quickly and the comments were outdated, which led to confusion. So I removed most of them.

To understand the code I recommend you to go through one of the examples and then follow the API calls, first through plugin.c and then to plugin-gen.c where the instrumentation is injected (based on the contents of the dyn_cb arrays).

Please ask further questions if anything is unclear.

Thanks,

Emilio

#25 lore raw

Re: [Qemu-devel] [RFC v2 08/38] tcg: drop nargs from tcg_op_insert_{before, after}

In reply to Emilio G. Cota
Quoted 8 lines · Emilio G. Cota

It's unused.

---
 tcg/tcg.h      |  4 ++--
 tcg/optimize.c |  4 ++--
 tcg/tcg.c      | 10 ++++------
 3 files changed, 8 insertions(+), 10 deletions(-)

Cherry-picked this into tcg-next.
The nargs argument is unused since 75e8b9b7aa0b95a761b9add7e2f09248b101a392.

r~

#9 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

In reply to Emilio G. Cota

Emilio,

First, thanks for putting this together - I think everyone doing this sort of thing will benefit if we're able to agree on one upstream plugin interface.

One thing I'd like to see is support for unregistering callbacks once they are registered. For instance, you can imagine that a plugin may have 'modality', where it may care about tracing very detailed information in one mode, but trace only limited information otherwise - perhaps only enough to figure out when it needs to switch back to the other mode.

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation, allowing the plugin to drop instrumentation if it was no longer interested. Of course, you could always add logic to a plugin to ignore unwanted callbacks, but it could be significantly more efficient to remove them entirely. In Pavel's patchset, this was essentially just a call to tb_flush(), though I think it would be a little more involved for yours.

-Aaron

#10 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

Quoted 2 lines · Aaron Lindsay

One thing I'd like to see is support for unregistering callbacks once they are registered.

By the way, I'm willing to work on this if we agree it sounds reasonable and fits in with the rest of your implementation.

-Aaron

#11 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

In reply to Aaron Lindsay
Quoted 13 lines · Aaron Lindsay

Emilio,

First, thanks for putting this together - I think everyone doing this sort of thing will benefit if we're able to agree on one upstream plugin interface.

One thing I'd like to see is support for unregistering callbacks once they are registered. For instance, you can imagine that a plugin may have 'modality', where it may care about tracing very detailed information in one mode, but trace only limited information otherwise - perhaps only enough to figure out when it needs to switch back to the other mode.

Quoted 8 lines

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation, allowing the plugin to drop instrumentation if it was no longer interested. Of course, you could always add logic to a plugin to ignore unwanted callbacks, but it could be significantly more efficient to remove them entirely. In Pavel's patchset, this was essentially just a call to tb_flush(), though I think it would be a little more involved for yours.

This is a good point.

"Regular" callbacks can be unregistered by just passing NULL as the callback (see plugin_unregister_cb__locked, which is called from do_plugin_register_cb). "Direct" callbacks, however (i.e. the ones that embed a callback directly in the translated code), would have to be unregistered by flushing the particular TB (or all TBs, which is probably better from an API viewpoint).

I think the following API call would do what you need:

  typedef int (*qemu_plugin_reset_cb_t)(qemu_plugin_id_t id);
  void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_reset_cb_t cb);

(or maybe qemu_plugin_reinstall?)

The idea is that a plugin can "reset" itself, so that (1) all its CBs are cleared and (2) the plugin can register new callbacks. This would all happen in an atomic context (no vCPU running), so that the plugin would miss no CPU events.

How does this sound?

Thanks,

Emilio

#12 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

Quoted 1 line · Emilio G. Cota

On Fri, Dec 14, 2018 at 15:57:32 +0000, Aaron Lindsay wrote:

(snip)

Quoted 2 lines
Quoted 2 lines

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation,

(snip)

Quoted 6 lines

I think the following API call would do what you need:

  typedef int (*qemu_plugin_reset_cb_t)(qemu_plugin_id_t id);
  void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_reset_cb_t cb);

(or maybe qemu_plugin_reinstall?)

An alternative is to track the TBs that a plugin has inserted instrumentation into, and only flush those. This would require us to do an additional hash table insert when adding a direct callback, but it allow us to avoid exporting tb_flush indirectly to plugins, which could be abused by malicious plugins to perform a DoS attack.

I'll look into this.

		E.
#15 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

In reply to Emilio G. Cota
Quoted 23 lines · Emilio G. Cota
Quoted 13 lines · Aaron Lindsay

Emilio,

First, thanks for putting this together - I think everyone doing this sort of thing will benefit if we're able to agree on one upstream plugin interface.

One thing I'd like to see is support for unregistering callbacks once they are registered. For instance, you can imagine that a plugin may have 'modality', where it may care about tracing very detailed information in one mode, but trace only limited information otherwise - perhaps only enough to figure out when it needs to switch back to the other mode.

Quoted 8 lines

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation, allowing the plugin to drop instrumentation if it was no longer interested. Of course, you could always add logic to a plugin to ignore unwanted callbacks, but it could be significantly more efficient to remove them entirely. In Pavel's patchset, this was essentially just a call to tb_flush(), though I think it would be a little more involved for yours.

Quoted 5 lines

This is a good point.

"Regular" callbacks can be unregistered by just passing NULL as the callback (see plugin_unregister_cb__locked, which is called from do_plugin_register_cb).

Ah, okay, thanks - I missed this detail when looking through your patches earlier.

Quoted 11 lines

"Direct" callbacks, however (i.e. the ones
that embed a callback directly in the translated code), would have to be unregistered by flushing the particular TB (or all TBs, which is probably better from an API viewpoint).

I think the following API call would do what you need:

  typedef int (*qemu_plugin_reset_cb_t)(qemu_plugin_id_t id);
  void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_reset_cb_t cb);

(or maybe qemu_plugin_reinstall?)

I think I prefer your initial suggestion of qemu_plugin_reset - to me it does a better job communicating that existing callbacks will be removed. But, then again, _reinstall makes it more clear that you are responsible for re-adding any callbacks you still want...

Quoted 4 lines

The idea is that a plugin can "reset" itself, so that (1) all its CBs are cleared and (2) the plugin can register new callbacks. This would all happen in an atomic context (no vCPU running), so that the plugin would miss no CPU events.

The implication being that there would not be the same possibility of other callbacks being called between when qemu_plugin_reset and the qemu_plugin_reset_cb_t callback are called as there is at plugin un-installation time?

Quoted 1 line

How does this sound?

I think what you describe is exactly what I'm interested in.

-Aaron

#16 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

Quoted 1 line · Aaron Lindsay

On Dec 14 12:08, Emilio G. Cota wrote:

(snip)

Quoted 9 lines
Quoted 4 lines

The idea is that a plugin can "reset" itself, so that (1) all its CBs are cleared and (2) the plugin can register new callbacks. This would all happen in an atomic context (no vCPU running), so that the plugin would miss no CPU events.

The implication being that there would not be the same possibility of other callbacks being called between when qemu_plugin_reset and the qemu_plugin_reset_cb_t callback are called as there is at plugin un-installation time?

The callback is needed for the same reason -- we can only guarantee that there will be no callbacks once the current RCU read critical section expires.

Quoted 3 lines
Quoted 1 line

How does this sound?

I think what you describe is exactly what I'm interested in.

Nice. I'll work on this for v3.

Thanks,

Emilio

#13 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

In reply to Emilio G. Cota
Quoted 11 lines · Emilio G. Cota
Quoted 1 line · Emilio G. Cota

On Fri, Dec 14, 2018 at 15:57:32 +0000, Aaron Lindsay wrote:

(snip)

Quoted 2 lines
Quoted 2 lines

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation,

(snip)

Quoted 5 lines

I think the following API call would do what you need:

  typedef int (*qemu_plugin_reset_cb_t)(qemu_plugin_id_t id);
  void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_reset_cb_t cb);
Quoted 8 lines
Quoted 1 line

(or maybe qemu_plugin_reinstall?)

An alternative is to track the TBs that a plugin has inserted instrumentation into, and only flush those. This would require us to do an additional hash table insert when adding a direct callback, but it allow us to avoid exporting tb_flush indirectly to plugins, which could be abused by malicious plugins to perform a DoS attack.

I don't think I have a preference. Though now I'm curious - when/why do you expect users might run plugins that could be malicious in this way?

-Aaron

#14 lore raw

Re: [Qemu-devel] [RFC v2 05/38] plugin: add user-facing API

Quoted 21 lines · Aaron Lindsay
Quoted 11 lines · Emilio G. Cota
Quoted 1 line · Emilio G. Cota

On Fri, Dec 14, 2018 at 15:57:32 +0000, Aaron Lindsay wrote:

(snip)

Quoted 2 lines
Quoted 2 lines

I added a function to the user-facing plugin API in my own version of Pavel's plugin patchset to clear all existing plugin instrumentation,

(snip)

Quoted 5 lines

I think the following API call would do what you need:

  typedef int (*qemu_plugin_reset_cb_t)(qemu_plugin_id_t id);
  void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_reset_cb_t cb);
Quoted 8 lines
Quoted 1 line

(or maybe qemu_plugin_reinstall?)

An alternative is to track the TBs that a plugin has inserted instrumentation into, and only flush those. This would require us to do an additional hash table insert when adding a direct callback, but it allow us to avoid exporting tb_flush indirectly to plugins, which could be abused by malicious plugins to perform a DoS attack.

Quoted 2 lines

I don't think I have a preference. Though now I'm curious - when/why do you expect users might run plugins that could be malicious in this way?

When this work started, others expressed concern about potentially malicious plugins, although I think they were thinking of preventing plugins from gaining access to data structures that could affect the guest, e.g. CPUState. That's why I'm using a hash table for the plugin context id, although that's probably overkill (do we care about malicious plugins messing with the subscriptions of other plugins? Not sure we should.)

Here I'm thinking more about giving plugin developers too much rope to hang themselves with, e.g. calling repeatedly plugin_reset() out of convenience, without realising the performance impact that it entails. That's why I'd like to explore the alternative.

Emilio

#35 lore raw

Re: [Qemu-devel] [RFC v2 15/38] tcg: let plugins instrument memory accesses

In reply to Emilio G. Cota
Quoted 3 lines · Emilio G. Cota

XXX: store hostaddr from non-i386 TCG backends
XXX: what hostaddr to return for I/O accesses?
XXX: what hostaddr to return for cross-page accesses?

Just a heads up this patch now clashes with changes that have been made to master.

Quoted 659 lines

Here the trickiest feature is passing the host address to memory callbacks that request it. Perhaps it would be more appropriate to pass a "physical" address to plugins, but since in QEMU host addr ~= guest physical, I'm going with that for simplicity.

To keep the implementation simple we piggy-back on the TLB fast path, and thus can only provide the host address _after_ memory accesses have occurred. For the slow path, it's a bit tedious because there are many places to update, but it's fairly simple.

However, note that cross-page accesses are tricky, since the access might be to non-contiguous host addresses. So I'm punting on that and just passing NULL.

---
 accel/tcg/atomic_template.h               |  5 +++
 accel/tcg/softmmu_template.h              | 43 +++++++++++++++++-----
 include/exec/cpu-defs.h                   |  9 +++++
 include/exec/cpu_ldst.h                   |  9 +++++
 include/exec/cpu_ldst_template.h          | 43 ++++++++++++++--------
 include/exec/cpu_ldst_useronly_template.h | 42 +++++++++++++++-------
 tcg/tcg.h                                 |  1 +
 accel/tcg/cpu-exec.c                      |  2 ++
 accel/tcg/cputlb.c                        |  9 +++++
 tcg/i386/tcg-target.inc.c                 |  7 ++++
 tcg/tcg-op.c                              | 44 ++++++++++++++++++-----
 11 files changed, 169 insertions(+), 45 deletions(-)
accel/tcg/atomic_template.h +5 -0
index 2f7d5ee02a..5619c4b4b9 100644
@@ -18,6 +18,7 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "qemu/plugin.h"
 #include "trace/mem.h"
 
 #if DATA_SIZE == 16
@@ -73,6 +74,8 @@ void atomic_trace_rmw_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_rmw_post(CPUArchState *env, target_ulong addr,
                                          void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info | TRACE_MEM_ST);
 }
 
 static inline
@@ -84,6 +87,7 @@ void atomic_trace_ld_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_ld_post(CPUArchState *env, target_ulong addr,
                                         void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
 }
 
 static inline
@@ -95,6 +99,7 @@ void atomic_trace_st_pre(CPUArchState *env, target_ulong addr, uint8_t info)
 static inline void atomic_trace_st_post(CPUArchState *env, target_ulong addr,
                                         void *haddr, uint8_t info)
 {
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), addr, haddr, info);
 }
 #endif /* ATOMIC_TEMPLATE_COMMON */
 
accel/tcg/softmmu_template.h +34 -9
index b0adea045e..79109e25a1 100644
@@ -45,7 +45,6 @@
 #error unsupported data size
 #endif
 
-
 /* For the benefit of TCG generated code, we want to avoid the complication
    of ABI-specific return type promotion and always return a value extended
    to the register size of the host.  This is tcg_target_long, except in the
@@ -99,10 +98,15 @@ static inline DATA_TYPE glue(io_read, SUFFIX)(CPUArchState *env,
                                               size_t mmu_idx, size_t index,
                                               target_ulong addr,
                                               uintptr_t retaddr,
+                                              TCGMemOp mo,
                                               bool recheck,
                                               MMUAccessType access_type)
 {
     CPUIOTLBEntry *iotlbentry = &env->iotlb[mmu_idx][index];
+
+    /* XXX Any sensible choice other than NULL? */
+    set_hostaddr(env, mo, NULL);
+
     return io_readx(env, iotlbentry, mmu_idx, addr, retaddr, recheck,
                     access_type, DATA_SIZE);
 }
@@ -115,7 +119,8 @@ WORD_TYPE helper_le_ld_name(CPUArchState *env, target_ulong addr,
     uintptr_t index = tlb_index(env, mmu_idx, addr);
     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
     target_ulong tlb_addr = entry->ADDR_READ;
-    unsigned a_bits = get_alignment_bits(get_memop(oi));
+    TCGMemOp mo = get_memop(oi);
+    unsigned a_bits = get_alignment_bits(mo);
     uintptr_t haddr;
     DATA_TYPE res;
 
@@ -141,7 +146,7 @@ WORD_TYPE helper_le_ld_name(CPUArchState *env, target_ulong addr,
 
         /* ??? Note that the io helpers always read data in the target
            byte ordering.  We should push the LE/BE request down into io.  */
-        res = glue(io_read, SUFFIX)(env, mmu_idx, index, addr, retaddr,
+        res = glue(io_read, SUFFIX)(env, mmu_idx, index, addr, retaddr, mo,
                                     tlb_addr & TLB_RECHECK,
                                     READ_ACCESS_TYPE);
         res = TGT_LE(res);
@@ -162,12 +167,19 @@ WORD_TYPE helper_le_ld_name(CPUArchState *env, target_ulong addr,
         res2 = helper_le_ld_name(env, addr2, oi, retaddr);
         shift = (addr & (DATA_SIZE - 1)) * 8;
 
+        /*
+         * XXX cross-page accesses would have to be split into separate accesses
+         * for the host address to make sense. For now, just return NULL.
+         */
+        set_hostaddr(env, mo, NULL);
+
         /* Little-endian combine.  */
         res = (res1 >> shift) | (res2 << ((DATA_SIZE * 8) - shift));
         return res;
     }
 
     haddr = addr + entry->addend;
+    set_hostaddr(env, mo, (void *)haddr);
 #if DATA_SIZE == 1
     res = glue(glue(ld, LSUFFIX), _p)((uint8_t *)haddr);
 #else
@@ -184,7 +196,8 @@ WORD_TYPE helper_be_ld_name(CPUArchState *env, target_ulong addr,
     uintptr_t index = tlb_index(env, mmu_idx, addr);
     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
     target_ulong tlb_addr = entry->ADDR_READ;
-    unsigned a_bits = get_alignment_bits(get_memop(oi));
+    TCGMemOp mo = get_memop(oi);
+    unsigned a_bits = get_alignment_bits(mo);
     uintptr_t haddr;
     DATA_TYPE res;
 
@@ -210,7 +223,7 @@ WORD_TYPE helper_be_ld_name(CPUArchState *env, target_ulong addr,
 
         /* ??? Note that the io helpers always read data in the target
            byte ordering.  We should push the LE/BE request down into io.  */
-        res = glue(io_read, SUFFIX)(env, mmu_idx, index, addr, retaddr,
+        res = glue(io_read, SUFFIX)(env, mmu_idx, index, addr, retaddr, mo,
                                     tlb_addr & TLB_RECHECK,
                                     READ_ACCESS_TYPE);
         res = TGT_BE(res);
@@ -231,12 +244,15 @@ WORD_TYPE helper_be_ld_name(CPUArchState *env, target_ulong addr,
         res2 = helper_be_ld_name(env, addr2, oi, retaddr);
         shift = (addr & (DATA_SIZE - 1)) * 8;
 
+        set_hostaddr(env, mo, NULL);
+
         /* Big-endian combine.  */
         res = (res1 << shift) | (res2 >> ((DATA_SIZE * 8) - shift));
         return res;
     }
 
     haddr = addr + entry->addend;
+    set_hostaddr(env, mo, (void *)haddr);
     res = glue(glue(ld, LSUFFIX), _be_p)((uint8_t *)haddr);
     return res;
 }
@@ -267,9 +283,12 @@ static inline void glue(io_write, SUFFIX)(CPUArchState *env,
                                           DATA_TYPE val,
                                           target_ulong addr,
                                           uintptr_t retaddr,
+                                          TCGMemOp mo,
                                           bool recheck)
 {
     CPUIOTLBEntry *iotlbentry = &env->iotlb[mmu_idx][index];
+
+    set_hostaddr(env, mo, NULL);
     return io_writex(env, iotlbentry, mmu_idx, val, addr, retaddr,
                      recheck, DATA_SIZE);
 }
@@ -281,7 +300,8 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     uintptr_t index = tlb_index(env, mmu_idx, addr);
     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
     target_ulong tlb_addr = tlb_addr_write(entry);
-    unsigned a_bits = get_alignment_bits(get_memop(oi));
+    TCGMemOp mo = get_memop(oi);
+    unsigned a_bits = get_alignment_bits(mo);
     uintptr_t haddr;
 
     if (addr & ((1 << a_bits) - 1)) {
@@ -308,7 +328,7 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
            byte ordering.  We should push the LE/BE request down into io.  */
         val = TGT_LE(val);
         glue(io_write, SUFFIX)(env, mmu_idx, index, val, addr,
-                               retaddr, tlb_addr & TLB_RECHECK);
+                               retaddr, mo, tlb_addr & TLB_RECHECK);
         return;
     }
 
@@ -340,10 +360,12 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
             glue(helper_ret_stb, MMUSUFFIX)(env, addr + i, val8,
                                             oi, retaddr);
         }
+        set_hostaddr(env, mo, NULL);
         return;
     }
 
     haddr = addr + entry->addend;
+    set_hostaddr(env, mo, (void *)haddr);
 #if DATA_SIZE == 1
     glue(glue(st, SUFFIX), _p)((uint8_t *)haddr, val);
 #else
@@ -359,7 +381,8 @@ void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
     uintptr_t index = tlb_index(env, mmu_idx, addr);
     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
     target_ulong tlb_addr = tlb_addr_write(entry);
-    unsigned a_bits = get_alignment_bits(get_memop(oi));
+    TCGMemOp mo = get_memop(oi);
+    unsigned a_bits = get_alignment_bits(mo);
     uintptr_t haddr;
 
     if (addr & ((1 << a_bits) - 1)) {
@@ -385,7 +408,7 @@ void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
         /* ??? Note that the io helpers always read data in the target
            byte ordering.  We should push the LE/BE request down into io.  */
         val = TGT_BE(val);
-        glue(io_write, SUFFIX)(env, mmu_idx, index, val, addr, retaddr,
+        glue(io_write, SUFFIX)(env, mmu_idx, index, val, addr, retaddr, mo,
                                tlb_addr & TLB_RECHECK);
         return;
     }
@@ -418,10 +441,12 @@ void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
             glue(helper_ret_stb, MMUSUFFIX)(env, addr + i, val8,
                                             oi, retaddr);
         }
+        set_hostaddr(env, mo, NULL);
         return;
     }
 
     haddr = addr + entry->addend;
+    set_hostaddr(env, mo, (void *)haddr);
     glue(glue(st, SUFFIX), _be_p)((uint8_t *)haddr, val);
 }
 #endif /* DATA_SIZE > 1 */
include/exec/cpu-defs.h +9 -0
index 40cd5d4774..f46bc0917d 100644
@@ -178,6 +178,14 @@ typedef struct CPUTLBDesc {
     CPUIOTLBEntry iotlb[NB_MMU_MODES][CPU_TLB_SIZE];
 #endif /* TCG_TARGET_IMPLEMENTS_DYN_TLB */
 
+#ifdef CONFIG_PLUGIN
+# define CPU_PLUGIN_HOSTADDR                            \
+    /* stores the host address of a guest access */     \
+    void *hostaddr;
+#else
+# define CPU_PLUGIN_HOSTADDR
+#endif
+
 #define CPU_COMMON_TLB                                                  \
     /* The meaning of the MMU modes is defined in the target code. */   \
     /* tlb_lock serializes updates to tlb_table and tlb_v_table */      \
@@ -186,6 +194,7 @@ typedef struct CPUTLBDesc {
     CPUTLBEntry tlb_v_table[NB_MMU_MODES][CPU_VTLB_SIZE];               \
     CPU_IOTLB                                                           \
     CPUIOTLBEntry iotlb_v[NB_MMU_MODES][CPU_VTLB_SIZE];                 \
+    CPU_PLUGIN_HOSTADDR                                                 \
     size_t tlb_flush_count;                                             \
     target_ulong tlb_flush_addr;                                        \
     target_ulong tlb_flush_mask;                                        \
include/exec/cpu_ldst.h +9 -0
index 83b2907d86..32dd8dd603 100644
@@ -85,6 +85,15 @@ typedef target_ulong abi_ptr;
 #define TARGET_ABI_FMT_ptr TARGET_ABI_FMT_lx
 #endif
 
+static inline void *read_hostaddr(CPUArchState *env)
+{
+#if defined(CONFIG_SOFTMMU) && defined(CONFIG_PLUGIN)
+    return env->hostaddr;
+#else
+    return NULL;
+#endif
+}
+
 #if defined(CONFIG_USER_ONLY)
 
 extern __thread uintptr_t helper_retaddr;
include/exec/cpu_ldst_template.h +28 -15
index 0f061d47ef..3493cb13bf 100644
@@ -28,6 +28,7 @@
 #include "trace-root.h"
 #endif
 
+#include "qemu/plugin.h"
 #include "trace/mem.h"
 
 #if DATA_SIZE == 8
@@ -86,11 +87,11 @@ glue(glue(glue(cpu_ld, USUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
     target_ulong addr;
     int mmu_idx;
     TCGMemOpIdx oi;
-
+    uintptr_t hostaddr;
 #if !defined(SOFTMMU_CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, false, MO_TE, false));
+    uint8_t meminfo = trace_mem_build_info(SHIFT, false, MO_TE, false);
+
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
 #endif
 
     addr = ptr;
@@ -101,10 +102,14 @@ glue(glue(glue(cpu_ld, USUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
         oi = make_memop_idx(SHIFT, mmu_idx);
         res = glue(glue(helper_ret_ld, URETSUFFIX), MMUSUFFIX)(env, addr,
                                                             oi, retaddr);
+        hostaddr = (uintptr_t)read_hostaddr(env);
     } else {
-        uintptr_t hostaddr = addr + entry->addend;
+        hostaddr = addr + entry->addend;
         res = glue(glue(ld, USUFFIX), _p)((uint8_t *)hostaddr);
     }
+#ifndef SOFTMMU_CODE_ACCESS
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, (void *)hostaddr, meminfo);
+#endif
     return res;
 }
 
@@ -125,11 +130,11 @@ glue(glue(glue(cpu_lds, SUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
     target_ulong addr;
     int mmu_idx;
     TCGMemOpIdx oi;
-
+    uintptr_t hostaddr;
 #if !defined(SOFTMMU_CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, true, MO_TE, false));
+    uint8_t meminfo = trace_mem_build_info(SHIFT, false, MO_TE, false);
+
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
 #endif
 
     addr = ptr;
@@ -140,10 +145,14 @@ glue(glue(glue(cpu_lds, SUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
         oi = make_memop_idx(SHIFT, mmu_idx);
         res = (DATA_STYPE)glue(glue(helper_ret_ld, SRETSUFFIX),
                                MMUSUFFIX)(env, addr, oi, retaddr);
+        hostaddr = (uintptr_t)read_hostaddr(env);
     } else {
-        uintptr_t hostaddr = addr + entry->addend;
+        hostaddr = addr + entry->addend;
         res = glue(glue(lds, SUFFIX), _p)((uint8_t *)hostaddr);
     }
+#ifndef SOFTMMU_CODE_ACCESS
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, (void *)hostaddr, meminfo);
+#endif
     return res;
 }
 
@@ -167,11 +176,11 @@ glue(glue(glue(cpu_st, SUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
     target_ulong addr;
     int mmu_idx;
     TCGMemOpIdx oi;
-
+    uintptr_t hostaddr;
 #if !defined(SOFTMMU_CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, false, MO_TE, true));
+    uint8_t meminfo = trace_mem_build_info(SHIFT, false, MO_TE, true);
+
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
 #endif
 
     addr = ptr;
@@ -182,10 +191,14 @@ glue(glue(glue(cpu_st, SUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
         oi = make_memop_idx(SHIFT, mmu_idx);
         glue(glue(helper_ret_st, SUFFIX), MMUSUFFIX)(env, addr, v, oi,
                                                      retaddr);
+        hostaddr = (uintptr_t)read_hostaddr(env);
     } else {
-        uintptr_t hostaddr = addr + entry->addend;
+        hostaddr = addr + entry->addend;
         glue(glue(st, SUFFIX), _p)((uint8_t *)hostaddr, v);
     }
+#ifndef SOFTMMU_CODE_ACCESS
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, (void *)hostaddr, meminfo);
+#endif
 }
 
 static inline void
include/exec/cpu_ldst_useronly_template.h +30 -12
index 0fd6019af0..e752e9c00e 100644
@@ -64,12 +64,19 @@
 static inline RES_TYPE
 glue(glue(cpu_ld, USUFFIX), MEMSUFFIX)(CPUArchState *env, abi_ptr ptr)
 {
+    RES_TYPE ret;
+#if !defined(CODE_ACCESS)
+    uint8_t meminfo = trace_mem_build_info(SHIFT, false, MO_TE, false);
+
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
+#endif
+
+    ret = glue(glue(ld, USUFFIX), _p)(g2h(ptr));
+
 #if !defined(CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, false, MO_TE, false));
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, NULL, meminfo);
 #endif
-    return glue(glue(ld, USUFFIX), _p)(g2h(ptr));
+    return ret;
 }
 
 static inline RES_TYPE
@@ -88,12 +95,19 @@ glue(glue(glue(cpu_ld, USUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
 static inline int
 glue(glue(cpu_lds, SUFFIX), MEMSUFFIX)(CPUArchState *env, abi_ptr ptr)
 {
+    int ret;
 #if !defined(CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, true, MO_TE, false));
+    uint8_t meminfo = trace_mem_build_info(SHIFT, true, MO_TE, false);
+
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
 #endif
-    return glue(glue(lds, SUFFIX), _p)(g2h(ptr));
+
+    ret = glue(glue(lds, SUFFIX), _p)(g2h(ptr));
+
+#if !defined(CODE_ACCESS)
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, NULL, meminfo);
+#endif
+    return ret;
 }
 
 static inline int
@@ -109,17 +123,21 @@ glue(glue(glue(cpu_lds, SUFFIX), MEMSUFFIX), _ra)(CPUArchState *env,
 }
 #endif
 
-#ifndef CODE_ACCESS
+#if !defined(CODE_ACCESS)
 static inline void
 glue(glue(cpu_st, SUFFIX), MEMSUFFIX)(CPUArchState *env, abi_ptr ptr,
                                       RES_TYPE v)
 {
 #if !defined(CODE_ACCESS)
-    trace_guest_mem_before_exec(
-        ENV_GET_CPU(env), ptr,
-        trace_mem_build_info(SHIFT, false, MO_TE, true));
+    uint8_t meminfo = trace_mem_build_info(SHIFT, false, MO_TE, true);
+    trace_guest_mem_before_exec(ENV_GET_CPU(env), ptr, meminfo);
 #endif
+
     glue(glue(st, SUFFIX), _p)(g2h(ptr), v);
+
+#if !defined(CODE_ACCESS)
+    qemu_plugin_vcpu_mem_cb(ENV_GET_CPU(env), ptr, NULL, meminfo);
+#endif
 }
 
 static inline void
tcg/tcg.h +1 -0
index a376f83ab6..8938dcf52e 100644
@@ -29,6 +29,7 @@
 #include "cpu.h"
 #include "exec/tb-context.h"
 #include "qemu/bitops.h"
+#include "qemu/plugin.h"
 #include "qemu/queue.h"
 #include "tcg-mo.h"
 #include "tcg-target.h"
accel/tcg/cpu-exec.c +2 -0
index d590f1f6c0..4c8265a908 100644
@@ -267,6 +267,7 @@ void cpu_exec_step_atomic(CPUState *cpu)
         tcg_debug_assert(!have_mmap_lock());
 #endif
         assert_no_pages_locked();
+        qemu_plugin_disable_mem_helpers(cpu);
     }
 
     if (in_exclusive_region) {
@@ -716,6 +717,7 @@ int cpu_exec(CPUState *cpu)
         if (qemu_mutex_iothread_locked()) {
             qemu_mutex_unlock_iothread();
         }
+        qemu_plugin_disable_mem_helpers(cpu);
     }
 
     /* if an exception is pending, we execute it here */
accel/tcg/cputlb.c +9 -0
index 5c61908084..3bdf98d2c3 100644
@@ -1208,6 +1208,15 @@ static void *atomic_mmu_lookup(CPUArchState *env, target_ulong addr,
     cpu_loop_exit_atomic(ENV_GET_CPU(env), retaddr);
 }
 
+static inline void set_hostaddr(CPUArchState *env, TCGMemOp mo, void *haddr)
+{
+#ifdef CONFIG_PLUGIN
+    if (mo & MO_HADDR) {
+        env->hostaddr = haddr;
+    }
+#endif
+}
+
 #ifdef TARGET_WORDS_BIGENDIAN
 # define TGT_BE(X)  (X)
 # define TGT_LE(X)  BSWAP(X)
tcg/i386/tcg-target.inc.c +7 -0
index 5cbb07deab..eb3725f2e3 100644
@@ -1685,6 +1685,13 @@ static inline void tcg_out_tlb_load(TCGContext *s, TCGReg addrlo, TCGReg addrhi,
     /* add addend(r0), r1 */
     tcg_out_modrm_offset(s, OPC_ADD_GvEv + hrexw, r1, r0,
                          offsetof(CPUTLBEntry, addend));
+
+#ifdef CONFIG_PLUGIN
+    if (opc & MO_HADDR) {
+        tcg_out_st(s, TCG_TYPE_PTR, r1, TCG_AREG0,
+                   offsetof(CPUArchState, hostaddr));
+    }
+#endif
 }
 
 /*
tcg/tcg-op.c +32 -7
index 7a8015c5a9..b30f0d4440 100644
@@ -31,6 +31,7 @@
 #include "tcg-mo.h"
 #include "trace-tcg.h"
 #include "trace/mem.h"
+#include "exec/plugin-gen.h"
 
 /* Reduce the number of ifdefs below.  This assumes that all uses of
    TCGV_HIGH and TCGV_LOW are properly protected by a conditional that
@@ -2595,6 +2596,7 @@ void tcg_gen_exit_tb(TranslationBlock *tb, unsigned idx)
         tcg_debug_assert(idx == TB_EXIT_REQUESTED);
     }
 
+    plugin_gen_disable_mem_helpers();
     tcg_gen_op1i(INDEX_op_exit_tb, val);
 }
 
@@ -2607,6 +2609,7 @@ void tcg_gen_goto_tb(unsigned idx)
     tcg_debug_assert((tcg_ctx->goto_tb_issue_mask & (1 << idx)) == 0);
     tcg_ctx->goto_tb_issue_mask |= 1 << idx;
 #endif
+    plugin_gen_disable_mem_helpers();
     /* When not chaining, we simply fall through to the "fallback" exit.  */
     if (!qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {
         tcg_gen_op1i(INDEX_op_goto_tb, idx);
@@ -2616,7 +2619,10 @@ void tcg_gen_goto_tb(unsigned idx)
 void tcg_gen_lookup_and_goto_ptr(void)
 {
     if (TCG_TARGET_HAS_goto_ptr && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {
-        TCGv_ptr ptr = tcg_temp_new_ptr();
+        TCGv_ptr ptr;
+
+        plugin_gen_disable_mem_helpers();
+        ptr = tcg_temp_new_ptr();
         gen_helper_lookup_tb_ptr(ptr, cpu_env);
         tcg_gen_op1i(INDEX_op_goto_ptr, tcgv_ptr_arg(ptr));
         tcg_temp_free_ptr(ptr);
@@ -2699,26 +2705,42 @@ static void tcg_gen_req_mo(TCGBar type)
     }
 }
 
+static inline void plugin_gen_mem_callbacks(TCGv vaddr, uint8_t info)
+{
+#ifdef CONFIG_PLUGIN
+    if (tcg_ctx->plugin_insn == NULL) {
+        return;
+    }
+    plugin_gen_empty_mem_callback(vaddr, info);
+#endif
+}
+
 void tcg_gen_qemu_ld_i32(TCGv_i32 val, TCGv addr, TCGArg idx, TCGMemOp memop)
 {
+    uint8_t info = trace_mem_get_info(memop, 0);
+
     tcg_gen_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
     memop = tcg_canonicalize_memop(memop, 0, 0);
-    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env,
-                               addr, trace_mem_get_info(memop, 0));
+    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env, addr, info);
     gen_ldst_i32(INDEX_op_qemu_ld_i32, val, addr, memop, idx);
+    plugin_gen_mem_callbacks(addr, info);
 }
 
 void tcg_gen_qemu_st_i32(TCGv_i32 val, TCGv addr, TCGArg idx, TCGMemOp memop)
 {
+    uint8_t info = trace_mem_get_info(memop, 1);
+
     tcg_gen_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
     memop = tcg_canonicalize_memop(memop, 0, 1);
-    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env,
-                               addr, trace_mem_get_info(memop, 1));
+    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env, addr, info);
     gen_ldst_i32(INDEX_op_qemu_st_i32, val, addr, memop, idx);
+    plugin_gen_mem_callbacks(addr, info);
 }
 
 void tcg_gen_qemu_ld_i64(TCGv_i64 val, TCGv addr, TCGArg idx, TCGMemOp memop)
 {
+    uint8_t info;
+
     tcg_gen_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
     if (TCG_TARGET_REG_BITS == 32 && (memop & MO_SIZE) < MO_64) {
         tcg_gen_qemu_ld_i32(TCGV_LOW(val), addr, idx, memop);
@@ -2731,13 +2753,16 @@ void tcg_gen_qemu_ld_i64(TCGv_i64 val, TCGv addr, TCGArg idx, TCGMemOp memop)
     }
 
     memop = tcg_canonicalize_memop(memop, 1, 0);
-    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env,
-                               addr, trace_mem_get_info(memop, 0));
+    info = trace_mem_get_info(memop, 0);
+    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env, addr, info);
     gen_ldst_i64(INDEX_op_qemu_ld_i64, val, addr, memop, idx);
+    plugin_gen_mem_callbacks(addr, info);
 }
 
 void tcg_gen_qemu_st_i64(TCGv_i64 val, TCGv addr, TCGArg idx, TCGMemOp memop)
 {
+    uint8_t info;
+
     tcg_gen_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
     if (TCG_TARGET_REG_BITS == 32 && (memop & MO_SIZE) < MO_64) {
         tcg_gen_qemu_st_i32(TCGV_LOW(val), addr, idx, memop);
@@ -2745,9 +2770,10 @@ void tcg_gen_qemu_st_i64(TCGv_i64 val, TCGv addr, TCGArg idx, TCGMemOp memop)
     }
 

tcg/tcg-op.c void tcg_gen_qemu_st_i64(TCGv_i64 val, TCGv addr, TCGArg idx, TCGMemOp memop) · line 2779

Quoted 10 lines
tcg/tcg-op.c +3 -2
     memop = tcg_canonicalize_memop(memop, 1, 1);
-    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env,
-                               addr, trace_mem_get_info(memop, 1));
+    info = trace_mem_get_info(memop, 1);
+    trace_guest_mem_before_tcg(tcg_ctx->cpu, cpu_env, addr, info);
     gen_ldst_i64(INDEX_op_qemu_st_i64, val, addr, memop, idx);
+    plugin_gen_mem_callbacks(addr, info);
 }
 
 static void tcg_gen_ext_i32(TCGv_i32 ret, TCGv_i32 val, TCGMemOp opc)

--
Alex Bennée

Reviewed-by on v2 1/38
#2 lore raw

Re: [Qemu-devel] [RFC v2 01/38] trace: expand mem_info:size_shift to 3 bits

In reply to Emilio G. Cota
Quoted 6 lines · Emilio G. Cota

This will allow us to trace 16B-long memory accesses.

While at it, add some defines for the mem_info bits and simplify trace_mem_get_info by making it a wrapper around trace_mem_build_info.

Quoted 9 lines
---
 trace-events | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
trace-events +0 -0
index 4fd2cb4b97..9d65d472d2 100644

trace-events vcpu guest_cpu_reset(void) · line 157

Quoted 8 lines
trace-events +1 -1
@@ -151,7 +151,7 @@ vcpu guest_cpu_reset(void)
 # Access information can be parsed as:
 #
 # struct mem_info {
-#     uint8_t size_shift : 2; /* interpreted as "1 << size_shift" bytes */
+#     uint8_t size_shift : 3; /* interpreted as "1 << size_shift" bytes */
 #     bool    sign_extend: 1; /* sign-extended */
 #     uint8_t endianness : 1; /* 0: little, 1: big */
 #     bool    store      : 1; /* wheter it's a store operation */

--
Alex Bennée

Reviewed-by on v2 3/38
#5 lore raw

Re: [Qemu-devel] [RFC v2 03/38] cpu: introduce cpu_in_exclusive_work_context()

In reply to Emilio G. Cota
Quoted 12 lines · Emilio G. Cota
---
 include/qom/cpu.h | 13 +++++++++++++
 cpus-common.c     |  2 ++
 2 files changed, 15 insertions(+)
include/qom/cpu.h +0 -0
index 772cc960fe..fab18089db 100644

include/qom/cpu.h struct CPUState { · line 352

Quoted 4 lines
include/qom/cpu.h +1 -0
@@ -349,6 +349,7 @@ struct CPUState {
     bool thread_kicked;
     bool crash_occurred;
     bool exit_request;
+    bool in_exclusive_work_context;

I'm not sure if I meant this or in_exclusive_context and push the flag into start/end_exclusive. But let's see how it shakes out:

Quoted 27 lines
include/qom/cpu.h +12 -0
     uint32_t cflags_next_tb;
     /* updates protected by BQL */
     uint32_t interrupt_request;
@@ -913,6 +914,18 @@ void async_run_on_cpu_no_bql(CPUState *cpu, run_on_cpu_func func,
  */
 void async_safe_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data);
 
+/**
+ * cpu_in_exclusive_work_context()
+ * @cpu: The vCPU to check
+ *
+ * Returns true if @cpu is an exclusive work context, which has
+ * previously been queued via async_safe_run_on_cpu().
+ */
+static inline bool cpu_in_exclusive_work_context(const CPUState *cpu)
+{
+    return cpu->in_exclusive_work_context;
+}
+
 /**
  * qemu_get_cpu:
  * @index: The CPUState@cpu_index value of the CPU to obtain.
cpus-common.c +0 -0
index 232cb12c46..d6ea42c80c 100644

cpus-common.c static void process_queued_cpu_work_locked(CPUState *cpu) · line 378

Quoted 9 lines
cpus-common.c +2 -0
@@ -370,7 +370,9 @@ static void process_queued_cpu_work_locked(CPUState *cpu)
                 qemu_mutex_unlock_iothread();
             }
             start_exclusive();
+            cpu->in_exclusive_work_context = true;
             wi->func(cpu, wi->data);
+            cpu->in_exclusive_work_context = false;
             end_exclusive();
             if (has_bql) {
                 qemu_mutex_lock_iothread();

--
Alex Bennée

Reviewed-by on v2 4/38
#7 lore raw

Re: [Qemu-devel] [RFC v2 04/38] translate-all: use cpu_in_exclusive_work_context() in tb_flush

In reply to Emilio G. Cota
Quoted 5 lines · Emilio G. Cota

tb_flush will be called by the plugin module from a safe work environment. Prepare for that.

Quoted 13 lines
---
 accel/tcg/translate-all.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
accel/tcg/translate-all.c +0 -1
index 038d82fdb5..62d5e13185 100644
@@ -1269,8 +1269,13 @@ void tb_flush(CPUState *cpu)
 {
     if (tcg_enabled()) {
         unsigned tb_flush_count = atomic_mb_read(&tb_ctx.tb_flush_count);
-        async_safe_run_on_cpu(cpu, do_tb_flush,

accel/tcg/translate-all.c void tb_flush(CPUState *cpu) · line 1280

Quoted 10 lines
accel/tcg/translate-all.c +7 -1
-                              RUN_ON_CPU_HOST_INT(tb_flush_count));
+
+        if (cpu_in_exclusive_work_context(cpu)) {
+            do_tb_flush(cpu, RUN_ON_CPU_HOST_INT(tb_flush_count));
+        } else {
+            async_safe_run_on_cpu(cpu, do_tb_flush,
+                                  RUN_ON_CPU_HOST_INT(tb_flush_count));
+        }
     }
 }

--
Alex Bennée

#27 lore raw

Re: [Qemu-devel] [RFC v2 09/38] cputlb: introduce get_page_addr_code_hostp

In reply to Emilio G. Cota
Quoted 34 lines · Emilio G. Cota

This will be used by plugins to get the host address of instructions.

---
 include/exec/exec-all.h | 13 +++++++++++++
 accel/tcg/cputlb.c      | 14 +++++++++++++-
 2 files changed, 26 insertions(+), 1 deletion(-)
include/exec/exec-all.h +10 -0
index 815e5b1e83..afcc01e0e3 100644
@@ -22,6 +22,7 @@
 
 #include "qemu-common.h"
 #include "exec/tb-context.h"
+#include "exec/cpu_ldst.h"
 #include "sysemu/cpus.h"
 
 /* allow to see translation results - the slowdown should be negligible, so we leave it */
@@ -487,12 +488,24 @@ static inline tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong
 {
     return addr;
 }
+
+static inline tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env1,
+                                                      target_ulong addr,
+                                                      void **hostp)
+{
+    if (hostp) {
+        *hostp = g2h(addr);
+    }
+    return addr;

include/exec/exec-all.h static inline tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong · line 509

Quoted 10 lines
include/exec/exec-all.h +3 -0
+}
 #else
 static inline void mmap_lock(void) {}
 static inline void mmap_unlock(void) {}
 
 /* cputlb.c */
 tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr);
+tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env1, target_ulong addr,
+                                        void **hostp);
 

It's probably about time these helpers got proper doc headers. So I take it the host address of an instruction is where in host memory the code is or where in host memory the translation for that instruction is?

Quoted 31 lines
include/exec/exec-all.h +0 -0
 void tlb_reset_dirty(CPUState *cpu, ram_addr_t start1, ram_addr_t length);
 void tlb_set_dirty(CPUState *cpu, target_ulong vaddr);
accel/tcg/cputlb.c +8 -1
index e3582f2f1d..5c61908084 100644
@@ -1069,7 +1069,8 @@ static bool victim_tlb_hit(CPUArchState *env, size_t mmu_idx, size_t index,
  * is actually a ram_addr_t (in system mode; the user mode emulation
  * version of this function returns a guest virtual address).
  */
-tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
+tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, target_ulong addr,
+                                        void **hostp)
 {
     uintptr_t mmu_idx = cpu_mmu_index(env, true);
     uintptr_t index = tlb_index(env, mmu_idx, addr);
@@ -1092,13 +1093,24 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
          *    than a target page, so we must redo the MMU check every insn
          *  - TLB_MMIO: region is not backed by RAM
          */
+        if (hostp) {
+            *hostp = NULL;
+        }
         return -1;
     }
 
     p = (void *)((uintptr_t)addr + entry->addend);
+    if (hostp) {
+        *hostp = p;
+    }
     return qemu_ram_addr_from_host_nofail(p);

accel/tcg/cputlb.c tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr) · line 1116

Quoted 10 lines
accel/tcg/cputlb.c +5 -0
 }
 
+tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr)
+{
+    return get_page_addr_code_hostp(env, addr, NULL);
+}
+
 /* Probe for whether the specified guest write access is permitted.
  * If it is not permitted then an exception will be taken in the same
  * way as if this were a real write access (and we will not return).

--
Alex Bennée

#20 lore raw

Re: [Qemu-devel] [RFC v2 06/38] plugin: add core code

In reply to Emilio G. Cota
Quoted 1 line · Emilio G. Cota

Some design requirements/goals:

Also this commit breaks bisect-ability:

15:56:23 [alex@zen:~/l/q/qemu.git] (0138e1a5…)|BISECTING 2 + head -n 3 config.log # QEMU configure log Thu Jan 24 15:19:36 GMT 2019
# Configured with: './configure' '--disable-tools' '--disable-docs' '--python=/usr/bin/python3' #
15:56:35 [alex@zen:~/l/q/qemu.git] (0138e1a5…)|BISECTING + make
CHK version_gen.h
CC qapi/qapi-visit-core.o
In file included from /home/alex/lsrc/qemu/qemu.git/include/qom/cpu.h:33:0,

                   from ./trace/control-internal.h:13,
                   from ./trace/control.h:270,
                   from qapi/trace.h:7,
                   from qapi/qapi-visit-core.c:21:
  /home/alex/lsrc/qemu/qemu.git/include/qemu/plugin.h:38:49: error: ‘qemu_plugin_list’ defined as wrong kind of tag
                                            struct qemu_plugin_list *head)
                                                   ^~~~~~~~~~~~~~~~
  /home/alex/lsrc/qemu/qemu.git/include/qemu/plugin.h:38:49: error: ‘struct qemu_plugin_list’ declared inside parameter list will not be visible outside of this definition or
  declaration [-Werror]
  /home/alex/lsrc/qemu/qemu.git/include/qemu/plugin.h:44:48: error: ‘qemu_plugin_list’ defined as wrong kind of tag
   static inline int qemu_plugin_load_list(struct qemu_plugin_list *head)
                                                  ^~~~~~~~~~~~~~~~

/home/alex/lsrc/qemu/qemu.git/include/qemu/plugin.h:44:48: error: ‘struct qemu_plugin_list’ declared inside parameter list will not be visible outside of this definition or declaration [-Werror]
cc1: all warnings being treated as errors
/home/alex/lsrc/qemu/qemu.git/rules.mak:69: recipe for target 'qapi/qapi-visit-core.o' failed
make: *** [qapi/qapi-visit-core.o] Error 1

--
Alex Bennée

#53 lore raw

Re: [Qemu-devel] [RFC v2 31/38] target/xtensa: fetch code with translator_ld

In reply to Emilio G. Cota
Quoted 19 lines · Emilio G. Cota
---
 target/xtensa/translate.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
target/xtensa/translate.c +1 -1
index 46e1338448..c140742562 100644
@@ -882,7 +882,7 @@ static inline unsigned xtensa_op0_insn_len(DisasContext *dc, uint8_t op0)
 static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
 {
     xtensa_isa isa = dc->config->isa;
-    unsigned char b[MAX_INSN_LENGTH] = {cpu_ldub_code(env, dc->pc)};
+    unsigned char b[MAX_INSN_LENGTH] = {translator_ldub(env, dc->pc)};
     unsigned len = xtensa_op0_insn_len(dc, b[0]);
     xtensa_format fmt;
     int slot, slots;

target/xtensa/translate.c static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc) · line 920

Quoted 8 lines
target/xtensa/translate.c +1 -1
@@ -914,7 +914,7 @@ static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
                       dc->pc);
     }
     for (i = 1; i < len; ++i) {
-        b[i] = cpu_ldub_code(env, dc->pc + i);
+        b[i] = translator_ldub(env, dc->pc + i);
     }
     xtensa_insnbuf_from_chars(isa, dc->insnbuf, b, len);
     fmt = xtensa_format_decode(isa, dc->insnbuf);

There is also:

  static inline unsigned xtensa_insn_len(CPUXtensaState *env, DisasContext *dc)
  {
      uint8_t b0 = cpu_ldub_code(env, dc->pc);
      return xtensa_op0_insn_len(dc, b0);
  }

Or is this usage a re-read of something we've already got?

--
Alex Bennée

#22 lore raw

Re: [Qemu-devel] [RFC v2 07/38] queue: add QTAILQ_REMOVE_SEVERAL

In reply to Emilio G. Cota
Quoted 15 lines · Emilio G. Cota

This is faster than removing elements one by one.

Will gain a user soon.

---
 include/qemu/queue.h | 10 ++++++++++
 1 file changed, 10 insertions(+)
include/qemu/queue.h +0 -0
index ac418efc43..0283c2dd7d 100644
@@ -419,6 +419,16 @@ struct {                                                                \
         (elm)->field.tqe_prev = NULL;                                   \

include/qemu/queue.h struct { \ · line 429

Quoted 10 lines
include/qemu/queue.h +8 -0
 } while (/*CONSTCOND*/0)
 
+/* remove @left, @right and all elements in between from @head */
+#define QTAILQ_REMOVE_SEVERAL(head, left, right, field) do {    \
+        if (((right)->field.tqe_next) != NULL)                  \
+            (right)->field.tqe_next->field.tqe_prev =           \
+                (left)->field.tqe_prev;                         \
+        else                                                    \
+            (head)->tqh_last = (left)->field.tqe_prev;          \
+        *(left)->field.tqe_prev = (right)->field.tqe_next;      \

This seems wrong, shouldn't it be:

  (left)->field.tqe_prev->field.tqe_next = (right)->field.tqe_next;

Although to be honest every time I read the QUEUE macros I end up with a headache...

include/qemu/queue.h struct { \ · line 434

Quoted 5 lines
include/qemu/queue.h +2 -0
+    } while (/*CONSTCOND*/0)
+
 #define QTAILQ_FOREACH(var, head, field)                                \
         for ((var) = ((head)->tqh_first);                               \
                 (var);                                                  \

--
Alex Bennée

#23 lore raw

Re: [Qemu-devel] [RFC v2 07/38] queue: add QTAILQ_REMOVE_SEVERAL

Quoted 12 lines · Alex Bennée

include/qemu/queue.h struct { \ · line 429

Quoted 8 lines · Emilio G. Cota
include/qemu/queue.h +8 -0
+/* remove @left, @right and all elements in between from @head */
+#define QTAILQ_REMOVE_SEVERAL(head, left, right, field) do {    \
+        if (((right)->field.tqe_next) != NULL)                  \
+            (right)->field.tqe_next->field.tqe_prev =           \
+                (left)->field.tqe_prev;                         \
+        else                                                    \
+            (head)->tqh_last = (left)->field.tqe_prev;          \
+        *(left)->field.tqe_prev = (right)->field.tqe_next;      \

This seems wrong, shouldn't it be:

Quoted 1 line
  (left)->field.tqe_prev->field.tqe_next = (right)->field.tqe_next;

That would make too much sense, wouldn't it!

Looking at QTAILQ_REMOVE is the easiest way to reason about this:

#define QTAILQ_REMOVE(head, elm, field) do {                            \
        if (((elm)->field.tqe_next) != NULL)                            \
                (elm)->field.tqe_next->field.tqe_prev =                 \
                    (elm)->field.tqe_prev;                              \
        else                                                            \
                (head)->tqh_last = (elm)->field.tqe_prev;               \
        *(elm)->field.tqe_prev = (elm)->field.tqe_next;                 \
        (elm)->field.tqe_prev = NULL;                                   \

} while (/*CONSTCOND*/0)

Imagine we're removing the only element in the list. Thus, *(elm)->field.tqe_prev will be setting (head)->tqh_first (to NULL). IOW, we can't assume that the previous "element" (whether true element or head) has a .tqe_next field (the head has .thq_first); note that tqe_prev is a **, not a *.

Quoted 1 line

Although to be honest every time I read the QUEUE macros I end up with a headache...

You're not alone.

BTW, this code had to change for v3 because of 7274f01bb8 ("qemu/queue.h:
reimplement QTAILQ without pointer-to-pointers", 2019-01-11)

I think you might like that implementation better, since it is a little closer to sanity, i.e. kernel-style lists :-)
It uses a more predictable structure (*prev,*next) that is shoehorned with a union to avoid changing the memory layout.

Thanks,

Emilio

#54 lore raw

Re: [Qemu-devel] [RFC v2 31/38] target/xtensa: fetch code with translator_ld

In reply to Alex Bennée
Quoted 31 lines · Alex Bennée
Quoted 19 lines · Emilio G. Cota
---
 target/xtensa/translate.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
target/xtensa/translate.c +1 -1
index 46e1338448..c140742562 100644
@@ -882,7 +882,7 @@ static inline unsigned xtensa_op0_insn_len(DisasContext *dc, uint8_t op0)
 static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
 {
     xtensa_isa isa = dc->config->isa;
-    unsigned char b[MAX_INSN_LENGTH] = {cpu_ldub_code(env, dc->pc)};
+    unsigned char b[MAX_INSN_LENGTH] = {translator_ldub(env, dc->pc)};
     unsigned len = xtensa_op0_insn_len(dc, b[0]);
     xtensa_format fmt;
     int slot, slots;

target/xtensa/translate.c static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc) · line 920

Quoted 8 lines
target/xtensa/translate.c +1 -1
@@ -914,7 +914,7 @@ static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc)
                       dc->pc);
     }
     for (i = 1; i < len; ++i) {
-        b[i] = cpu_ldub_code(env, dc->pc + i);
+        b[i] = translator_ldub(env, dc->pc + i);
     }
     xtensa_insnbuf_from_chars(isa, dc->insnbuf, b, len);
     fmt = xtensa_format_decode(isa, dc->insnbuf);

There is also:

Quoted 7 lines
  static inline unsigned xtensa_insn_len(CPUXtensaState *env, DisasContext *dc)
  {
      uint8_t b0 = cpu_ldub_code(env, dc->pc);
      return xtensa_op0_insn_len(dc, b0);
  }

Or is this usage a re-read of something we've already got?

FWIW xtensa_insn_len is used to look into the instruction that follows the one that has just been translated, but it may only touch the same page as the last translated instruction.

Signature · 2 lines
Thanks.
-- Max
#36 lore raw

Re: [Qemu-devel] [RFC v2 15/38] tcg: let plugins instrument memory accesses

In reply to Alex Bennée
Quoted 8 lines · Alex Bennée
Quoted 3 lines · Emilio G. Cota

XXX: store hostaddr from non-i386 TCG backends
XXX: what hostaddr to return for I/O accesses?
XXX: what hostaddr to return for cross-page accesses?

Just a heads up this patch now clashes with changes that have been made to master.

<snip>

Now the softmmu work is in I re-based the series and fixed up these clashes. You can find my tree at:

https://github.com/stsquad/qemu/tree/review/plugin-review-v3-rebase

I'm just paging in context and getting back to the review now.

--
Alex Bennée

#62 lore raw

RFC PATCH 1/1 tests/tcg: enable plugin testing

In reply to Emilio G. Cota

If CONFIG_PLUGINS is enabled then lets enable testing for all our TCG targets. This is a simple smoke test that ensure we don't crash or otherwise barf out by running each plugin against each test.

There is a minor knock on effect for additional runners which need specialised QEMU_OPTS which will also need to declare a plugin version of the runner. If this gets onerous we might need to add another helper.

Checking the results of the plugins is left for a later exercise.

---
 tests/Makefile.include                | 10 +++++++-
 tests/tcg/Makefile                    | 34 +++++++++++++++++++++++++++
 tests/tcg/arm/Makefile.softmmu-target |  1 +
 3 files changed, 44 insertions(+), 1 deletion(-)
tests/Makefile.include +9 -1
index 792f685ac11..91d254cdca5 100644
@@ -1037,6 +1037,14 @@ check-softfloat:
 		"SKIPPED for non-TCG builds")
 endif
 
+# Plugins
+ifeq ($(CONFIG_PLUGIN),y)
+plugins:
+	$(call quiet-command,\
+		$(MAKE) $(SUBDIR_MAKEFLAGS) -C tests/plugin V="$(V)", \
+		"BUILD", "plugins")
+endif
+
 # Per guest TCG tests
 
 BUILD_TCG_TARGET_RULES=$(patsubst %,build-tcg-tests-%, $(TARGET_DIRS))
@@ -1051,7 +1059,7 @@ $(foreach PROBE_TARGET,$(TARGET_DIRS), 				\
 		$(eval build-tcg-tests-$(PROBE_TARGET): $(DOCKER_PREREQ))))
 endif
 
-build-tcg-tests-%:
+build-tcg-tests-%: $(if $(CONFIG_PLUGIN),plugins)
 	$(call quiet-command,$(MAKE) $(SUBDIR_MAKEFLAGS) -C $* V="$(V)" \
 		SKIP_DOCKER_BUILD=1 TARGET_DIR="$*/" guest-tests, \
 		"BUILD", "TCG tests for $*")
tests/tcg/Makefile +34 -0
index 6fa63cc8d53..9474ab29003 100644
@@ -116,11 +116,37 @@ all: $(TESTS)
 #
 
 RUN_TESTS=$(patsubst %,run-%, $(TESTS))
+
+# If plugins exist also include those in the tests
+ifeq ($(CONFIG_PLUGIN),y)
+PLUGIN_DIR=../../tests/plugin
+VPATH+=$(PLUGIN_DIR)
+PLUGINS=$(notdir $(wildcard $(PLUGIN_DIR)/*.so))
+
+# We need to ensure expand the run-plugin-TEST-with-PLUGIN
+# pre-requistes manually here as we can't use stems to handle it. We
+# also add some special helpers the run-plugin- rules can use bellow.
+
+$(foreach p,$(PLUGINS), \
+	$(foreach t,$(TESTS),\
+		$(eval run-plugin-$(t)-with-$(p): $t $p) \
+		$(eval RUN_TESTS+=run-plugin-$(t)-with-$(p))))
+endif
+
+strip-plugin = $(wordlist 1, 1, $(subst -with-, ,$1))
+extract-plugin = $(wordlist 2, 2, $(subst -with-, ,$1))
+
 RUN_TESTS+=$(EXTRA_RUNS)
 
 ifdef CONFIG_USER_ONLY
 run-%: %
 	$(call run-test, $<, $(QEMU) $(QEMU_OPTS) $<, "$< on $(TARGET_NAME)")
+
+run-plugin-%:
+	$(call run-test, $@, $(QEMU) $(QEMU_OPTS) \
+		-plugin $(PLUGIN_DIR)/$(call extract-plugin,$@) \
+		 $(call strip-plugin,$<), \
+	"$< on $(TARGET_NAME)")
 else
 run-%: %
 	$(call run-test, $<, \
@@ -128,6 +154,14 @@ run-%: %
 		  -chardev file$(COMMA)path=$<.out$(COMMA)id=output \
 	   	  $(QEMU_OPTS) $<, \
 	  "$< on $(TARGET_NAME)")
+
+run-plugin-%:
+	$(call run-test, $@, \
+	  $(QEMU) -monitor none -display none \
+		  -chardev file$(COMMA)[email protected]$(COMMA)id=output \
+	   	  -plugin $(PLUGIN_DIR)/$(call extract-plugin,$@) \
+	   	  $(QEMU_OPTS) $(call strip-plugin,$<), \
+	  "$< on $(TARGET_NAME)")
 endif
 
 gdb-%: %
tests/tcg/arm/Makefile.softmmu-target +1 -0
index 49d48d8a1c3..cd628306b3e 100644
@@ -25,5 +25,6 @@ LDFLAGS+=-nostdlib -N -static
 test-armv6m-undef: EXTRA_CFLAGS+=-mcpu=cortex-m0
 
 run-test-armv6m-undef: QEMU_OPTS+=-semihosting -M microbit -kernel
+run-plugin-test-armv6m-undef-%: QEMU_OPTS+=-semihosting -M microbit -kernel
 
 endif
Signature · 1 line
2.20.1
Reviewed-by on v2 11/38
#30 lore raw

Re: [Qemu-devel] [RFC v2 11/38] tcg: add tcg_gen_st_ptr

In reply to Emilio G. Cota
Quoted 3 lines · Emilio G. Cota

Will gain a user soon.

Quoted 10 lines
---
 tcg/tcg-op.h | 5 +++++
 1 file changed, 5 insertions(+)
tcg/tcg-op.h +0 -0
index e2948b10a2..d3c79a6cb2 100644
@@ -1219,6 +1219,11 @@ static inline void tcg_gen_ld_ptr(TCGv_ptr r, TCGv_ptr a, intptr_t o)
     glue(tcg_gen_ld_,PTR)((NAT)r, a, o);

tcg/tcg-op.h static inline void tcg_gen_ld_ptr(TCGv_ptr r, TCGv_ptr a, intptr_t o) · line 1229

Quoted 10 lines
tcg/tcg-op.h +5 -0
 }
 
+static inline void tcg_gen_st_ptr(TCGv_ptr r, TCGv_ptr a, intptr_t o)
+{
+    glue(tcg_gen_st_, PTR)((NAT)r, a, o);
+}
+
 static inline void tcg_gen_discard_ptr(TCGv_ptr a)
 {
     glue(tcg_gen_discard_,PTR)((NAT)a);

--
Alex Bennée