Skip to contentSkip to conversation

contrib/plugins/bbv: Add region-of-interest selection

PATCH In review Akihiko Odaki 3 participants 18 messages Oct 7 – Oct 14

lore
Share & tools
lore
#0 lore raw

cover contrib/plugins/bbv: Add region-of-interest selection

Benchmarks can spend more time parsing input or initializing state than running the computation of interest. Generating basic block vectors for the whole execution can therefore give these setup phases too much weight in SimPoint analysis.

This series adds optional begin=A and end=A markers to control BBV generation using guest instruction virtual addresses. Omitting begin starts generation at program startup; omitting end leaves it enabled until program exit. The markers let users focus collection on a region of interest.

The first patch rejects non-positive intervals and values with trailing non-digit characters. The second adds the ROI options and documents their use.

---
Akihiko Odaki (2):
contrib/plugins/bbv.c: Reject invalid intervals contrib/plugins/bbv.c: Allow selecting ROI

 docs/about/emulation.rst |  8 +++++
 contrib/plugins/bbv.c    | 93 +++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 97 insertions(+), 4 deletions(-)

---
base-commit: f7ada39edacaa5c26b30e98b94017b0b2ccbcf94
change-id: 20261002-bbv-e2e3e2043829

Best regards,

Signature · 1 line
Akihiko Odaki <[email protected]>
#1 lore raw

PATCH 1/2 contrib/plugins/bbv.c: Reject invalid intervals

g_ascii_strtoull() accepts a leading minus sign, and returns the negation of the parsed number. It also accepts zero. Reject those non-positive values since their semantics is unclear.

Also reject interval values with trailing non-digit characters, such as interval=8a.

---
 contrib/plugins/bbv.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
contrib/plugins/bbv.c +11 -2
index 0e6ec673d972..e5caf5d9543b 100644
@@ -26,7 +26,7 @@ static GHashTable *bbs;
 static GRWLock bbs_lock;
 static char *filename;
 static struct qemu_plugin_scoreboard *vcpus;
-static uint64_t interval = 100000000;
+static int64_t interval = 100000000;
 
 static void plugin_exit(void *p)
 {
@@ -138,7 +138,16 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
         char *opt = argv[i];
         g_auto(GStrv) tokens = g_strsplit(opt, "=", 2);
         if (g_strcmp0(tokens[0], "interval") == 0) {
-            interval = g_ascii_strtoull(tokens[1], NULL, 10);
+            char *endptr;
+            interval = g_ascii_strtoll(tokens[1], &endptr, 10);
+            if (*endptr) {
+                fprintf(stderr, "malformed integer: %s\n", opt);
+                return -1;
+            }
+            if (interval <= 0) {
+                fprintf(stderr, "unexpected non-positive value: %s\n", opt);
+                return -1;
+            }
         } else if (g_strcmp0(tokens[0], "outfile") == 0) {
             filename = tokens[1];
             tokens[1] = NULL;
Signature · 1 line
2.55.0
Reviewed-by on v1 1/2
#2 lore raw

Re: [PATCH 1/2] contrib/plugins/bbv.c: Reject invalid intervals

Quoted 11 lines · Akihiko Odaki

g_ascii_strtoull() accepts a leading minus sign, and returns the negation of the parsed number. It also accepts zero. Reject those non-positive values since their semantics is unclear.

Also reject interval values with trailing non-digit characters, such as interval=8a.

---
  contrib/plugins/bbv.c | 13 +++++++++++--
  1 file changed, 11 insertions(+), 2 deletions(-)
Reviewed-by on v1 1/2
#3 lore raw

Re: [PATCH 1/2] contrib/plugins/bbv.c: Reject invalid intervals

In reply to Akihiko Odaki
Quoted 4 lines · Akihiko Odaki

g_ascii_strtoull() accepts a leading minus sign, and returns the negation of the parsed number. It also accepts zero. Reject those non-positive values since their semantics is unclear.

Quoted 8 lines

Also reject interval values with trailing non-digit characters, such as interval=8a.

---
 contrib/plugins/bbv.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
#4 lore raw

PATCH 2/2 contrib/plugins/bbv.c: Allow selecting ROI

In reply to Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit. For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
 docs/about/emulation.rst |  8 +++++
 contrib/plugins/bbv.c    | 80 ++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +8 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic block vectors for use with the
 
   * - Option
     - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if
+      not specified.
   * - interval=N
     - The interval to generate a basic block vector specified by the number of
       instructions (Default: N = 100000000)
contrib/plugins/bbv.c +78 -2

128 lines not on this page · raw message

Signature · 1 line
2.55.0
#5 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 20 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit. For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
 docs/about/emulation.rst |  8 +++++
 contrib/plugins/bbv.c    | 80 ++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644

docs/about/emulation.rst The bbv plugin allows you to generate basic block vectors for use with the · line 293

Quoted 10 lines
docs/about/emulation.rst +7 -0
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic block vectors for use with the
 
   * - Option
     - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Quoted 29 lines
docs/about/emulation.rst +1 -0
+      not specified.
   * - interval=N
     - The interval to generate a basic block vector specified by the number of
       instructions (Default: N = 100000000)
contrib/plugins/bbv.c +6 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
  * SPDX-License-Identifier: GPL-2.0-or-later
  */
 
+#include <stdbool.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <glib.h>
 
@@ -26,6 +28,10 @@ static GHashTable *bbs;
 static GRWLock bbs_lock;
 static char *filename;
 static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
 static int64_t interval = 100000000;
 
 static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void *userdata) · line 75

Quoted 4 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void *userdata)
     Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
 
     vcpu_filename = g_strdup_printf("%s.%u.bb", filename, vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

The original logic was to increment this count, until reaching interval, after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

Quoted 47 lines
contrib/plugins/bbv.c +29 -0
     vcpu->file = fopen(vcpu_filename, "w");
 }
 
@@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)
     fputc('\n', vcpu->file);
 }
 
+static void vcpu_begin_insn_exec(unsigned int vcpu_index, void *userdata)
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
 static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
 {
     uint64_t n_insns = qemu_plugin_tb_n_insns(tb);
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
     }
     g_rw_lock_writer_unlock(&bbs_lock);
 
+    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb, idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS, NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), INT64_MIN);
+        }
+    }
+
     qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu(
         tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns);
 

contrib/plugins/bbv.c static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata) · line 167

Quoted 6 lines
contrib/plugins/bbv.c +2 -1
@@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
 
     qemu_plugin_register_vcpu_tb_exec_cond_cb(
         tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL);
+        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
+}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader. It would be better to choose something like:
UINT64_MAX - 1024, and assert than no tb has more than 1024 insn.

From that and code above, it seems like we're trying to introduce a "run forever" logic as an arbitrary big interval when using begin/end features.

Maybe it would be more obvious to use:
- leave count initialization to 0
- if using begin/end, set an arbitrary large interval (which will never be "fullfilled" by normal execution), like UINT64_MAX - 1024.

Normal path is unmodified, and you can insert the begin/end logic accordingly.

Maybe I missed the clever way it's supposed to work, but at this time of the day, my brain can't see it :). Feel free to explain if I missed anything obvious.

Regards,
Pierrick

#6 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 22 lines · Pierrick Bouvier
Quoted 21 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit. For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
  docs/about/emulation.rst |  8 +++++
  contrib/plugins/bbv.c    | 80 ++++++++++++++++++++++++++++++++++++++++++++++--
  2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic block vectors for use with the
 
Quoted 11 lines

docs/about/emulation.rst The bbv plugin allows you to generate basic block vectors for use with the · line 293

Quoted 9 lines
docs/about/emulation.rst +7 -0
    * - Option
      - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 32 lines
Quoted 32 lines
docs/about/emulation.rst +1 -0
+      not specified.
    * - interval=N
      - The interval to generate a basic block vector specified by the number of
        instructions (Default: N = 100000000)
contrib/plugins/bbv.c +6 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
   * SPDX-License-Identifier: GPL-2.0-or-later
   */
 
+#include <stdbool.h>
+#include <stdint.h>
  #include <stdio.h>
  #include <glib.h>
 
@@ -26,6 +28,10 @@ static GHashTable *bbs;
  static GRWLock bbs_lock;
  static char *filename;
  static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
  static int64_t interval = 100000000;
 
  static void plugin_exit(void *p)
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void *userdata)
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
 
Quoted 8 lines

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void *userdata) · line 75

Quoted 2 lines
contrib/plugins/bbv.c +1 -0
      vcpu_filename = g_strdup_printf("%s.%u.bb", filename, vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

The original logic was to increment this count, until reaching interval, after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

    initial count:       -100
    after 130 insns:       30  -> emit a vector
    subtract interval:    -70  -> 70 insns until the next vector
Quoted 49 lines
Quoted 49 lines
contrib/plugins/bbv.c +29 -0
      vcpu->file = fopen(vcpu_filename, "w");
  }
 
@@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)
      fputc('\n', vcpu->file);
  }
 
+static void vcpu_begin_insn_exec(unsigned int vcpu_index, void *userdata)
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
  static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
  {
      uint64_t n_insns = qemu_plugin_tb_n_insns(tb);
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
      }
      g_rw_lock_writer_unlock(&bbs_lock);
 
+    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb, idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS, NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), INT64_MIN);
+        }
+    }
+
      qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu(
          tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns);
 
@@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
 
Quoted 8 lines

contrib/plugins/bbv.c static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata) · line 167

Quoted 5 lines
contrib/plugins/bbv.c +2 -1
      qemu_plugin_register_vcpu_tb_exec_cond_cb(
          tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL);
+        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
+}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Quoted 5 lines

It would be better to choose something like:
UINT64_MAX - 1024, and assert than no tb has more than 1024 insn.

From that and code above, it seems like we're trying to introduce a "run
forever" logic as an arbitrary big interval when using begin/end features.

Using UINT64_MAX - 1024 as the disabled counter value would wrap after 1025 instructions in total. Bounding the size of each TB would not prevent that.

Quoted 8 lines

Maybe it would be more obvious to use:
- leave count initialization to 0
- if using begin/end, set an arbitrary large interval (which will never be "fullfilled" by normal execution), like UINT64_MAX - 1024.

Normal path is unmodified, and you can insert the begin/end logic accordingly.

Using a large interval instead needs another consideration: the comparison threshold is embedded as an immediate in translated code. Changing the interval variable at begin/end would not update existing comparisons, and that variable is shared across vCPUs. Adjusting the per-vCPU counter lets the comparison stay fixed.

Quoted 4 lines

Maybe I missed the clever way it's supposed to work, but at this time of the day, my brain can't see it :). Feel free to explain if I missed anything obvious.

I agree this encoding deserves a comment; it is not obvious from the code alone.

Regards,
Akihiko Odaki

#7 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 150 lines · Akihiko Odaki
Quoted 30 lines · Pierrick Bouvier
Quoted 29 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit. For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
  docs/about/emulation.rst |  8 +++++ contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++++++++++
+++++++++--

  2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
      * - Option
      - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 36 lines
Quoted 28 lines

+      not specified.
    * - interval=N
      - The interval to generate a basic block vector specified by the number of
        instructions (Default: N = 100000000)

contrib/plugins/bbv.c +0 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
    * SPDX-License-Identifier: GPL-2.0-or-later
    */

  +#include <stdbool.h>
+#include <stdint.h>
  #include <stdio.h>
  #include <glib.h>
  @@ -26,6 +28,10 @@ static GHashTable *bbs;
  static GRWLock bbs_lock;
  static char *filename;
  static struct qemu_plugin_scoreboard *vcpus;

contrib/plugins/bbv.c +4 -0
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;

  static int64_t interval = 100000000;
    static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void · line 76

Quoted 5 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void
 *userdata)
       Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
         vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
 vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 3 lines

The original logic was to increment this count, until reaching interval, after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

    initial count:       -100
    after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 51 lines
Quoted 51 lines
contrib/plugins/bbv.c +0 -0
       vcpu->file = fopen(vcpu_filename, "w");
   }

  @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)
      fputc('\n', vcpu->file);
  }
  +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void *userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+

  static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata) {
      uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +9 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb
 *tb, void *userdata)
       }
       g_rw_lock_writer_unlock(&bbs_lock);
   +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
 idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
 NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),

INT64_MIN);
+        }
+    }
+
      qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

        qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS, -        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Thanks,
Pierrick

#8 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 166 lines · Pierrick Bouvier
Quoted 150 lines · Akihiko Odaki
Quoted 30 lines · Pierrick Bouvier
Quoted 29 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit. For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
   docs/about/emulation.rst |  8 +++++
   contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++++++++++
+++++++++--
   2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
      * - Option
      - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 36 lines
Quoted 28 lines

+      not specified.
    * - interval=N
      - The interval to generate a basic block vector specified by
the number of
        instructions (Default: N = 100000000)

contrib/plugins/bbv.c +5 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
    * SPDX-License-Identifier: GPL-2.0-or-later
    */
   +#include <stdbool.h>
+#include <stdint.h>
   #include <stdio.h>
   #include <glib.h>
   @@ -26,6 +28,10 @@ static GHashTable *bbs;
   static GRWLock bbs_lock;
   static char *filename;
   static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
   static int64_t interval = 100000000;
     static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void · line 76

Quoted 5 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void
 *userdata)
       Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
         vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
 vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 3 lines

The original logic was to increment this count, until reaching interval, after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

    initial count:       -100
    after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 51 lines
Quoted 51 lines
contrib/plugins/bbv.c +0 -0
       vcpu->file = fopen(vcpu_filename, "w");
   }

  @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
      fputc('\n', vcpu->file);
  }
  +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void
*userdata)

contrib/plugins/bbv.c +24 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
   static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
   {
       uint64_t n_insns = qemu_plugin_tb_n_insns(tb);
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb
 *tb, void *userdata)
       }
       g_rw_lock_writer_unlock(&bbs_lock);
   +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
 idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
 NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),

INT64_MIN);
+        }
+    }
+
      qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

        qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

Regards,
Akihiko Odaki

#9 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 176 lines · Akihiko Odaki
Quoted 170 lines · Pierrick Bouvier
Quoted 154 lines · Akihiko Odaki
Quoted 32 lines · Pierrick Bouvier
Quoted 31 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
   docs/about/emulation.rst |  8 +++++ contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++++++++++
+++++++++--

   2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
       * - Option
       - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 36 lines
Quoted 28 lines

+      not specified.
     * - interval=N
       - The interval to generate a basic block vector specified by the number of
         instructions (Default: N = 100000000)

contrib/plugins/bbv.c +0 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
     * SPDX-License-Identifier: GPL-2.0-or-later
     */

   +#include <stdbool.h>
+#include <stdint.h>
   #include <stdio.h>
   #include <glib.h>
   @@ -26,6 +28,10 @@ static GHashTable *bbs;
   static GRWLock bbs_lock;
   static char *filename;
   static struct qemu_plugin_scoreboard *vcpus;

contrib/plugins/bbv.c +4 -0
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;

   static int64_t interval = 100000000;
     static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void · line 76

Quoted 5 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void
 *userdata)
        Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
          vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
 vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 4 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

     initial count:       -100
     after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 52 lines
Quoted 52 lines
contrib/plugins/bbv.c +0 -0
        vcpu->file = fopen(vcpu_filename, "w");
    }

   @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)
       fputc('\n', vcpu->file);
   }
   +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void *userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+

   static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
   {
       uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +9 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb
 *tb, void *userdata)
        }
        g_rw_lock_writer_unlock(&bbs_lock);
    +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
 idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
 NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),

INT64_MIN);
+        }
+    }
+
       qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

         qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS, -        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 6 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

Quoted 2 lines

Regards,
Akihiko Odaki

Regards,
Pierrick

#10 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 202 lines · Pierrick Bouvier
Quoted 176 lines · Akihiko Odaki
Quoted 170 lines · Pierrick Bouvier
Quoted 154 lines · Akihiko Odaki
Quoted 32 lines · Pierrick Bouvier
Quoted 31 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
    docs/about/emulation.rst |  8 +++++
    contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++++++++++
+++++++++--
    2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
       * - Option
       - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 36 lines
Quoted 28 lines

+      not specified.
     * - interval=N
       - The interval to generate a basic block vector specified by
the number of
         instructions (Default: N = 100000000)

contrib/plugins/bbv.c +5 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
     * SPDX-License-Identifier: GPL-2.0-or-later
     */
    +#include <stdbool.h>
+#include <stdint.h>
    #include <stdio.h>
    #include <glib.h>
    @@ -26,6 +28,10 @@ static GHashTable *bbs;
    static GRWLock bbs_lock;
    static char *filename;
    static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
    static int64_t interval = 100000000;
      static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void · line 76

Quoted 5 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void
 *userdata)
        Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
          vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
 vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 4 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

     initial count:       -100
     after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 52 lines
Quoted 52 lines
contrib/plugins/bbv.c +0 -0
        vcpu->file = fopen(vcpu_filename, "w");
    }

   @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
       fputc('\n', vcpu->file);
   }
   +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void
*userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
    static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void

*userdata)
   {
       uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +9 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb
 *tb, void *userdata)
        }
        g_rw_lock_writer_unlock(&bbs_lock);
    +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
 idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
 NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),

INT64_MIN);
+        }
+    }
+
       qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

         qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 6 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Quoted 8 lines

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

The current design that resets the bb table is intentional. A "virtual" interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

I don't think we need to add a special handling to enforce a particular order of transitions. This patch performs the same action for the begin and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to tell that it resets the bb table, making the behavior clear regardless of transition order.

Regards,
Akihiko Odaki

#11 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 207 lines · Akihiko Odaki
Quoted 206 lines · Pierrick Bouvier
Quoted 176 lines · Akihiko Odaki
Quoted 170 lines · Pierrick Bouvier
Quoted 154 lines · Akihiko Odaki
Quoted 32 lines · Pierrick Bouvier
Quoted 31 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
     docs/about/emulation.rst |  8 +++++
     contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++++++++++
+++++++++--
     2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
       * - Option
       - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 36 lines
Quoted 28 lines

+      not specified.
     * - interval=N
       - The interval to generate a basic block vector specified by
the number of
         instructions (Default: N = 100000000)

contrib/plugins/bbv.c +5 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
      * SPDX-License-Identifier: GPL-2.0-or-later
      */
     +#include <stdbool.h>
+#include <stdint.h>
     #include <stdio.h>
     #include <glib.h>
     @@ -26,6 +28,10 @@ static GHashTable *bbs;
     static GRWLock bbs_lock;
     static char *filename;
     static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
     static int64_t interval = 100000000;
       static void plugin_exit(void *p)

contrib/plugins/bbv.c static void vcpu_init(unsigned int vcpu_index, void · line 76

Quoted 5 lines
contrib/plugins/bbv.c +1 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, void
 *userdata)
         Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
           vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
 vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 4 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

     initial count:       -100
     after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 52 lines
Quoted 52 lines
contrib/plugins/bbv.c +0 -0
         vcpu->file = fopen(vcpu_filename, "w");
     }

   @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
       fputc('\n', vcpu->file);
   }
   +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void
*userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
     static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void

*userdata)
   {
       uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +9 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct qemu_plugin_tb
 *tb, void *userdata)
         }
         g_rw_lock_writer_unlock(&bbs_lock);
     +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
 idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
 NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),

INT64_MIN);
+        }
+    }
+
       qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

         qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The begin callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 6 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Quoted 9 lines
Quoted 4 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

The current design that resets the bb table is intentional. A "virtual" interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 8 lines

I don't think we need to add a special handling to enforce a particular order of transitions. This patch performs the same action for the begin and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), 
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
   qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region, 
QEMU_PLUGIN_CB_NO_REGS, NULL);
}

static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
   Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
   vcpu_interval_exec(vcpu_index, NULL);
   vcpu->tracking_region = false;
}
```

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)

{
    Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
    if (!vcpu->tracking) {
      return;
    }
    ...

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

Quoted 2 lines

Regards,
Akihiko Odaki

Thanks,
Pierrick

#12 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 235 lines · Pierrick Bouvier
Quoted 213 lines · Akihiko Odaki
Quoted 212 lines · Pierrick Bouvier
Quoted 182 lines · Akihiko Odaki
Quoted 176 lines · Pierrick Bouvier
Quoted 160 lines · Akihiko Odaki
Quoted 34 lines · Pierrick Bouvier
Quoted 33 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound basic block vector generation to the ROI.

---
     docs/about/emulation.rst |  8 +++++ contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++
++++++++
+++++++++--

     2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
         * - Option
         - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block
vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 37 lines
Quoted 28 lines

+      not specified.
       * - interval=N
         - The interval to generate a basic block vector specified by the number of
           instructions (Default: N = 100000000)

contrib/plugins/bbv.c +0 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
       * SPDX-License-Identifier: GPL-2.0-or-later
       */

     +#include <stdbool.h>
+#include <stdint.h>
     #include <stdio.h>
     #include <glib.h>
     @@ -26,6 +28,10 @@ static GHashTable *bbs;
     static GRWLock bbs_lock;
     static char *filename;
     static struct qemu_plugin_scoreboard *vcpus;

contrib/plugins/bbv.c +4 -0
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;

     static int64_t interval = 100000000;
       static void plugin_exit(void *p)

contrib/plugins/bbv.c +0 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index, 
Quoted 6 lines

void
*userdata)
         Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); vcpu_filename = g_strdup_printf("%s.%u.bb", filename, vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 4 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting interval after emitting a vector still preserves the extra instructions. For example, with interval=100:

       initial count:       -100
       after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 55 lines
Quoted 55 lines

         vcpu->file = fopen(vcpu_filename, "w");
     }
     @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int vcpu_index, void *udata)
         fputc('\n', vcpu->file);
     }
     +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void *userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+

     static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
     {
         uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +0 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct 

qemu_plugin_tb
*tb, void *userdata)
         }
         g_rw_lock_writer_unlock(&bbs_lock);
     +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn); +
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) { +            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu( +                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), INT64_MIN);
+        }
+    }
+
         qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

           qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS, -        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

Quoted 9 lines

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with the signed comparison (int64_t)count >= 0. That is why this particular value is used.

Setting count to INT64_MIN suppresses output for the next 2^63 counted instructions, which is effectively disabled for this use. The beginEmulation callback clears the BB counters and sets count to -interval; end sets it back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 6 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Quoted 9 lines
Quoted 4 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

The current design that resets the bb table is intentional. A "virtual" interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 8 lines

I don't think we need to add a special handling to enforce a particular order of transitions. This patch performs the same action for the begin and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to tell that it resets the bb table, making the behavior clear regardless of transition order.

Quoted 6 lines

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
             qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                 insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), 
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
    qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region, 
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
    Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
    vcpu_interval_exec(vcpu_index, NULL);
    vcpu->tracking_region = false;
}
```

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition: it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

Quoted 11 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
    Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
      return;
    }
    ...

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Quoted 2 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

Regards,
Akihiko Odaki

#13 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 287 lines · Akihiko Odaki
Quoted 255 lines · Pierrick Bouvier
Quoted 227 lines · Akihiko Odaki
Quoted 226 lines · Pierrick Bouvier
Quoted 195 lines · Akihiko Odaki
Quoted 189 lines · Pierrick Bouvier
Quoted 175 lines · Akihiko Odaki
Quoted 35 lines · Pierrick Bouvier
Quoted 34 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound
basic block vector generation to the ROI.

---
      docs/about/emulation.rst |  8 +++++
      contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++
++++++++
+++++++++--
      2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
         * - Option
         - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block
vector
+      generation. Generation starts from the beginning of the execution if

Quoted 8 lines
Quoted 6 lines

+      not specified.
+  * - end=A
+    - The virtual address of the instruction that ends basic block vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 40 lines
Quoted 29 lines

+      not specified.
       * - interval=N
         - The interval to generate a basic block vector
specified by
the number of
           instructions (Default: N = 100000000)

contrib/plugins/bbv.c +5 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
       * SPDX-License-Identifier: GPL-2.0-or-later
       */
      +#include <stdbool.h>
+#include <stdint.h>
      #include <stdio.h>
      #include <glib.h>
      @@ -26,6 +28,10 @@ static GHashTable *bbs;
      static GRWLock bbs_lock;
      static char *filename;
      static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
      static int64_t interval = 100000000;
        static void plugin_exit(void *p)
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index,
Quoted 7 lines

void
*userdata)
         Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus,
vcpu_index);
           vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 5 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep
the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting
interval after emitting a vector still preserves the extra instructions.
For example, with interval=100:

       initial count:       -100
       after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 57 lines
Quoted 57 lines

         vcpu->file = fopen(vcpu_filename, "w");
     }
     @@ -102,6 +109,22 @@ static void
vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
         fputc('\n', vcpu->file);
     }
     +static void vcpu_begin_insn_exec(unsigned int vcpu_index,
void
*userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
      static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void

*userdata)
     {
         uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +0 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct

qemu_plugin_tb
*tb, void *userdata)
         }
         g_rw_lock_writer_unlock(&bbs_lock);
     +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn); +
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu( +                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), INT64_MIN);
+        }
+    }
+
         qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

           qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with
the signed comparison (int64_t)count >= 0. That is why this particular
value is used.

Quoted 7 lines

Setting count to INT64_MIN suppresses output for the next 2^63 counted
instructions, which is effectively disabled for this use. The beginEmulation callback clears the BB counters and sets count to -interval; end sets it
back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 7 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Quoted 9 lines
Quoted 4 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

The current design that resets the bb table is intentional. A "virtual" interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 8 lines

I don't think we need to add a special handling to enforce a particular order of transitions. This patch performs the same action for the begin and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Quoted 3 lines

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
              qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                  insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
     qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region,
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
     Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
     vcpu_interval_exec(vcpu_index, NULL);
     vcpu->tracking_region = false;
}
```
Quoted 5 lines

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition:
it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

I'm fine with it. I was unsure if you wanted to dump the partial data, aggregate it when reentering the section, or simply discard it. With a discard, it's even simpler, just need to set tracking_region to false.

Quoted 13 lines
Quoted 4 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

Quoted 8 lines

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
    Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
      return;
    }
    ...

Quoted 5 lines

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Right, thanks for catching it.

Quoted 15 lines
Quoted 5 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

Quoted 8 lines

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

If the argument is "C allows that with a defined behaviour", I don't think it makes a point for me. There is a lot of well defined and confusing code you can write.

Something like:
qemu_plugin_register_vcpu_tb_exec_cond_cb(

        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

with limit and counter being unsigned is not readable for me.

Quoted 4 lines

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

From there I'll let you decide between introducing the flag, or reimplement that with positive values (sticking to init count=0) only if you really prefer this approach.

Quoted 2 lines

Regards,
Akihiko Odaki

Regards,
Pierrick

#14 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 351 lines · Pierrick Bouvier
Quoted 289 lines · Akihiko Odaki
Quoted 257 lines · Pierrick Bouvier
Quoted 229 lines · Akihiko Odaki
Quoted 228 lines · Pierrick Bouvier
Quoted 196 lines · Akihiko Odaki
Quoted 190 lines · Pierrick Bouvier
Quoted 176 lines · Akihiko Odaki
Quoted 36 lines · Pierrick Bouvier
Quoted 35 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter; basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound
basic block vector generation to the ROI.

---
      docs/about/emulation.rst |  8 +++++ contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++++++
++++++++
+++++++++--

      2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
          * - Option
          - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block
vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.

Quoted 8 lines
Quoted 6 lines

+  * - end=A
+    - The virtual address of the instruction that ends basic block
vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 40 lines
Quoted 29 lines

+      not specified.
        * - interval=N
          - The interval to generate a basic block vector specified by
the number of
            instructions (Default: N = 100000000)

contrib/plugins/bbv.c +0 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
        * SPDX-License-Identifier: GPL-2.0-or-later
        */

      +#include <stdbool.h>
+#include <stdint.h>
      #include <stdio.h>
      #include <glib.h>
      @@ -26,6 +28,10 @@ static GHashTable *bbs; static GRWLock bbs_lock;
      static char *filename;
      static struct qemu_plugin_scoreboard *vcpus;

contrib/plugins/bbv.c +4 -0
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;

      static int64_t interval = 100000000;
        static void plugin_exit(void *p)

contrib/plugins/bbv.c +0 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index,
Quoted 7 lines

void
*userdata)
          Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
            vcpu_filename = g_strdup_printf("%s.%u.bb", filename, vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 5 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep
the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting
interval after emitting a vector still preserves the extra instructions.
For example, with interval=100:

        initial count:       -100
        after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 57 lines
Quoted 57 lines

          vcpu->file = fopen(vcpu_filename, "w");
      }
      @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
          fputc('\n', vcpu->file);
      }
      +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void
*userdata)

contrib/plugins/bbv.c +15 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index, 0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+

      static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
      {
          uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +0 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct

qemu_plugin_tb
*tb, void *userdata)
          }
          g_rw_lock_writer_unlock(&bbs_lock);
      +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn); +
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) {
+            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu( +                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(), INT64_MIN);
+        }
+    }
+
          qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns); @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

            qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS, -        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with
the signed comparison (int64_t)count >= 0. That is why this particular
value is used.

Quoted 7 lines

Setting count to INT64_MIN suppresses output for the next 2^63 counted
instructions, which is effectively disabled for this use. The beginEmulation callback clears the BB counters and sets count to -interval; end sets it
back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 4 lines

I would prefer if you could refactor this to keep a zero initialized count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite interval".

Quoted 7 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and the only need thing to do is to snapshot bbs hashtable to keep track of the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from
previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/ restore when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we want to report an error or handle reentrance correctly in this case.

Quoted 9 lines
Quoted 4 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

The current design that resets the bb table is intentional. A "virtual" interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 8 lines

I don't think we need to add a special handling to enforce a particular order of transitions. This patch performs the same action for the begin and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Quoted 3 lines

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
              qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                  insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
     qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region,
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
     Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
     vcpu_interval_exec(vcpu_index, NULL);
     vcpu->tracking_region = false;
}
```
Quoted 5 lines

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition:
it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

I'm fine with it. I was unsure if you wanted to dump the partial data, aggregate it when reentering the section, or simply discard it. With a discard, it's even simpler, just need to set tracking_region to false.

Quoted 13 lines
Quoted 4 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

Quoted 8 lines

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
        return;
      }
      ...

Quoted 5 lines

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Right, thanks for catching it.

Quoted 15 lines
Quoted 5 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

Quoted 8 lines

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

If the argument is "C allows that with a defined behaviour", I don't think it makes a point for me. There is a lot of well defined and confusing code you can write.

Something like:
 qemu_plugin_register_vcpu_tb_exec_cond_cb( QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
with limit and counter being unsigned is not readable for me.

Quoted 7 lines
Quoted 4 lines

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

From there I'll let you decide between introducing the flag, or
reimplement that with positive values (sticking to init count=0) only if you really prefer this approach.

I agree that "C allows this with defined behaviour" is insufficient on its own. Ideally, we could express the signed interpretation directly with int64_t without adding complexity. That would improve clarity, even though the existing arithmetic is already well-defined.

However, we need to consider the whole design. Both approaches require readers to understand more than the individual expressions.

The counter-only approach requires knowing that:

- count is actually treated as signed.
- Any non-negative is smaller than (uint64_t)INT64_MIN when compared as unsigned.

The flag approach requires considering:
- How the count and flag together determine when a vector is emitted.
- The required ordering of count and flag accesses.
- Whether the number of callback invocations will significantly increase.

The count-only approach requires fewer considerations, and the ones it does require needs no deduction. The first point is a common practice, as seen in the underlying implementation. The second point is simply a matter of the int64_t definition. In both cases, knowing the definition is sufficient, and both can be documented clearly in the comments.

In contrast, the flag approach requires real reasoning. Comments won't help here; explaining the ordering and interactions via comments would be as complicated as the code itself, thereby imposing a greater cognitive burden.

Furthermore, supporting a variable interval (as done in the count-only approach) is a pattern we should embrace, rather than working around it by introducing a separate flag.

We have also already discussed why retaining count=0 is not a drop-in alternative under the same counter-only instrumentation. The initial state must distinguish execution that starts inside the ROI from execution waiting for the begin marker.

Putting all together, I still believe utilizing the existing signed representation is cleaner than inventing an alternative approach ourselves.

Regards,
Akihiko Odaki

#15 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 425 lines · Akihiko Odaki
Quoted 380 lines · Pierrick Bouvier
Quoted 314 lines · Akihiko Odaki
Quoted 282 lines · Pierrick Bouvier
Quoted 255 lines · Akihiko Odaki
Quoted 247 lines · Pierrick Bouvier
Quoted 208 lines · Akihiko Odaki
Quoted 200 lines · Pierrick Bouvier
Quoted 185 lines · Akihiko Odaki
Quoted 39 lines · Pierrick Bouvier
Quoted 38 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and
exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter;
basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound
basic block vector generation to the ROI.

---
      docs/about/emulation.rst |  8 +++++ contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++
++++
++++++++
+++++++++--

      2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
          * - Option
          - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block
vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.

Quoted 8 lines
Quoted 6 lines

+  * - end=A
+    - The virtual address of the instruction that ends basic block
vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 41 lines
Quoted 29 lines

+      not specified.
        * - interval=N
          - The interval to generate a basic block vector specified by
the number of
            instructions (Default: N = 100000000)

contrib/plugins/bbv.c +0 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
        * SPDX-License-Identifier: GPL-2.0-or-later
        */

      +#include <stdbool.h>
+#include <stdint.h>
      #include <stdio.h>
      #include <glib.h>
      @@ -26,6 +28,10 @@ static GHashTable *bbs; static GRWLock bbs_lock;
      static char *filename;
      static struct qemu_plugin_scoreboard *vcpus;

contrib/plugins/bbv.c +4 -0
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;

      static int64_t interval = 100000000;
        static void plugin_exit(void *p)

contrib/plugins/bbv.c +0 -0
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index,
Quoted 8 lines

void
*userdata)
          Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
            vcpu_filename = g_strdup_printf("%s.%u.bb", filename,
vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 5 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep
the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting
interval after emitting a vector still preserves the extra instructions.
For example, with interval=100:

        initial count:       -100
        after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next vector

Quoted 61 lines
Quoted 61 lines

          vcpu->file = fopen(vcpu_filename, "w");
      }
      @@ -102,6 +109,22 @@ static void vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
          fputc('\n', vcpu->file);
      }
      +static void vcpu_begin_insn_exec(unsigned int vcpu_index, void
*userdata)

contrib/plugins/bbv.c +9 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index,

0);
+    }

contrib/plugins/bbv.c +5 -0
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+

      static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)
      {
          uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +0 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct

qemu_plugin_tb
*tb, void *userdata)
          }
          g_rw_lock_writer_unlock(&bbs_lock);
      +    for (size_t idx = 0; idx < n_insns; idx++) { +        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn); +
+        if (begin_present && insn_vaddr == begin) { +            qemu_plugin_register_vcpu_insn_exec_cb( +                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) { + qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu( +                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
+        }
+    }
+ qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(), n_insns);
      @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

            qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS, -        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with
the signed comparison (int64_t)count >= 0. That is why this particular
value is used.

Quoted 8 lines

Setting count to INT64_MIN suppresses output for the next 2^63 counted
instructions, which is effectively disabled for this use. The beginEmulation
callback clears the BB counters and sets count to -interval; end sets it
back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 6 lines

I would prefer if you could refactor this to keep a zero initialized
count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite
interval".

Quoted 8 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is
translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify
interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and
the only need thing to do is to snapshot bbs hashtable to keep track of
the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from
previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/ restore
when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we
want to report an error or handle reentrance correctly in this case.

Quoted 6 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think
the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

Quoted 5 lines

The current design that resets the bb table is intentional. A "virtual"
interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 11 lines

I don't think we need to add a special handling to enforce a particular
order of transitions. This patch performs the same action for the begin
and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to
tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Quoted 3 lines

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
              qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                  insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
     qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region,
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
     Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
     vcpu_interval_exec(vcpu_index, NULL);
     vcpu->tracking_region = false;
}
```
Quoted 5 lines

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition:
it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

I'm fine with it. I was unsure if you wanted to dump the partial data, aggregate it when reentering the section, or simply discard it. With a discard, it's even simpler, just need to set tracking_region to false.

Quoted 13 lines
Quoted 4 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

Quoted 8 lines

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
        return;
      }
      ...

Quoted 5 lines

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Right, thanks for catching it.

Quoted 15 lines
Quoted 5 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

Quoted 8 lines

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

If the argument is "C allows that with a defined behaviour", I don't think it makes a point for me. There is a lot of well defined and confusing code you can write.

Something like:
  qemu_plugin_register_vcpu_tb_exec_cond_cb( QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); with limit and counter being unsigned is not readable for me.

Quoted 8 lines
Quoted 4 lines

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

 From there I'll let you decide between introducing the flag, or reimplement that with positive values (sticking to init count=0) only if you really prefer this approach.

I agree that "C allows this with defined behaviour" is insufficient on its own. Ideally, we could express the signed interpretation directly with int64_t without adding complexity. That would improve clarity, even though the existing arithmetic is already well-defined.

However, we need to consider the whole design. Both approaches require readers to understand more than the individual expressions.

The counter-only approach requires knowing that:

- count is actually treated as signed.
- Any non-negative is smaller than (uint64_t)INT64_MIN when compared as unsigned.

The flag approach requires considering:
- How the count and flag together determine when a vector is emitted.
- The required ordering of count and flag accesses.
- Whether the number of callback invocations will significantly increase.

The count-only approach requires fewer considerations, and the ones it does require needs no deduction. The first point is a common practice, as seen in the underlying implementation. The second point is simply a matter of the int64_t definition. In both cases, knowing the definition is sufficient, and both can be documented clearly in the comments.

In contrast, the flag approach requires real reasoning. Comments won't help here; explaining the ordering and interactions via comments would be as complicated as the code itself, thereby imposing a greater cognitive burden.

Furthermore, supporting a variable interval (as done in the count-only approach) is a pattern we should embrace, rather than working around it by introducing a separate flag.

Quoted 8 lines

We have also already discussed why retaining count=0 is not a drop-in alternative under the same counter-only instrumentation. The initial state must distinguish execution that starts inside the ROI from execution waiting for the begin marker.

Putting all together, I still believe utilizing the existing signed representation is cleaner than inventing an alternative approach ourselves.

I respect your opinion, but I would prefer to not introduce such usage of the existing API in contrib/, since it might (wrongly) inspire other people reading this plugin code.

Quoted 2 lines

Regards,
Akihiko Odaki

Regards,
Pierrick

#16 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 431 lines · Pierrick Bouvier
Quoted 430 lines · Akihiko Odaki
Quoted 380 lines · Pierrick Bouvier
Quoted 314 lines · Akihiko Odaki
Quoted 282 lines · Pierrick Bouvier
Quoted 255 lines · Akihiko Odaki
Quoted 247 lines · Pierrick Bouvier
Quoted 208 lines · Akihiko Odaki
Quoted 200 lines · Pierrick Bouvier
Quoted 185 lines · Akihiko Odaki
Quoted 39 lines · Pierrick Bouvier
Quoted 38 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup and
exit.
For example, a benchmark may parse a large input and then run a computation kernel and the former may take longer than the latter;
basic block vectors generated for the whole execution will not properly
represent the latter.

Add options to specify the beginning and the end of the ROI to bound
basic block vector generation to the ROI.

---
       docs/about/emulation.rst |  8 +++++
       contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++
++++
++++++++
+++++++++--
       2 files changed, 86 insertions(+), 2 deletions(-)
docs/about/emulation.rst +0 -0
index c58149086cdd..0566171b517b 100644
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic

block vectors for use with the
          * - Option
          - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic block
vector
+      generation. Generation starts from the beginning of the execution if
+      not specified.

Quoted 8 lines
Quoted 6 lines

+  * - end=A
+    - The virtual address of the instruction that ends basic block
vector
+      generation. Generation continues until the endo of the execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 41 lines
Quoted 29 lines

+      not specified.
        * - interval=N
          - The interval to generate a basic block vector
specified by
the number of
            instructions (Default: N = 100000000)

contrib/plugins/bbv.c +5 -0
index e5caf5d9543b..a2a779f7639e 100644
@@ -5,6 +5,8 @@
        * SPDX-License-Identifier: GPL-2.0-or-later
        */
       +#include <stdbool.h>
+#include <stdint.h>
       #include <stdio.h>
       #include <glib.h>
       @@ -26,6 +28,10 @@ static GHashTable *bbs;
       static GRWLock bbs_lock;
       static char *filename;
       static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
       static int64_t interval = 100000000;
         static void plugin_exit(void *p)
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index,
Quoted 8 lines

void
*userdata)
          Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus,
vcpu_index);
            vcpu_filename = g_strdup_printf("%s.%u.bb",
filename,
vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 5 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep
the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting
interval after emitting a vector still preserves the extra instructions.
For example, with interval=100:

        initial count:       -100
        after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next
vector

Quoted 61 lines
Quoted 61 lines

          vcpu->file = fopen(vcpu_filename, "w");
      }
      @@ -102,6 +109,22 @@ static void
vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
          fputc('\n', vcpu->file);
      }
      +static void vcpu_begin_insn_exec(unsigned int vcpu_index,
void
*userdata)

contrib/plugins/bbv.c +9 -0
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index,

0);
+    }

contrib/plugins/bbv.c +5 -0
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
       static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void

*userdata)
      {
          uint64_t n_insns = qemu_plugin_tb_n_insns(tb);

contrib/plugins/bbv.c +0 -0
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct

qemu_plugin_tb
*tb, void *userdata)
          }
          g_rw_lock_writer_unlock(&bbs_lock);
      +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn); +
+        if (begin_present && insn_vaddr == begin) { +            qemu_plugin_register_vcpu_insn_exec_cb( +                insn, vcpu_begin_insn_exec, QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) { + qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu( +                insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
+        }
+    }
+
          qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu( tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(),
n_insns);
      @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

            qemu_plugin_register_vcpu_tb_exec_cond_cb( tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL); +        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL); +}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with
the signed comparison (int64_t)count >= 0. That is why this particular
value is used.

Quoted 8 lines

Setting count to INT64_MIN suppresses output for the next 2^63 counted
instructions, which is effectively disabled for this use. The beginEmulation
callback clears the BB counters and sets count to -interval; end sets it
back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 6 lines

I would prefer if you could refactor this to keep a zero initialized
count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite
interval".

Quoted 8 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is
translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify
interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and
the only need thing to do is to snapshot bbs hashtable to keep track of
the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from
previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/ restore
when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we
want to report an error or handle reentrance correctly in this case.

Quoted 6 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think
the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

Quoted 5 lines

The current design that resets the bb table is intentional. A "virtual"
interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 11 lines

I don't think we need to add a special handling to enforce a particular
order of transitions. This patch performs the same action for the begin
and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to
tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Quoted 3 lines

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
               qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                   insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
      qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region,
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
      vcpu_interval_exec(vcpu_index, NULL);
      vcpu->tracking_region = false;
}
```
Quoted 5 lines

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition:
it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

I'm fine with it. I was unsure if you wanted to dump the partial data, aggregate it when reentering the section, or simply discard it. With a discard, it's even simpler, just need to set tracking_region to false.

Quoted 13 lines
Quoted 4 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

Quoted 8 lines

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
        return;
      }
      ...

Quoted 5 lines

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Right, thanks for catching it.

Quoted 15 lines
Quoted 5 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

Quoted 8 lines

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

If the argument is "C allows that with a defined behaviour", I don't think it makes a point for me. There is a lot of well defined and confusing code you can write.

Something like:
  qemu_plugin_register_vcpu_tb_exec_cond_cb( QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
with limit and counter being unsigned is not readable for me.

Quoted 8 lines
Quoted 4 lines

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

 From there I'll let you decide between introducing the flag, or
reimplement that with positive values (sticking to init count=0) only if you really prefer this approach.

I agree that "C allows this with defined behaviour" is insufficient on its own. Ideally, we could express the signed interpretation directly with int64_t without adding complexity. That would improve clarity, even though the existing arithmetic is already well-defined.

However, we need to consider the whole design. Both approaches require readers to understand more than the individual expressions.

The counter-only approach requires knowing that:

- count is actually treated as signed.
- Any non-negative is smaller than (uint64_t)INT64_MIN when compared as unsigned.

The flag approach requires considering:
- How the count and flag together determine when a vector is emitted.
- The required ordering of count and flag accesses.
- Whether the number of callback invocations will significantly increase.

The count-only approach requires fewer considerations, and the ones it does require needs no deduction. The first point is a common practice, as seen in the underlying implementation. The second point is simply a matter of the int64_t definition. In both cases, knowing the definition is sufficient, and both can be documented clearly in the comments.

In contrast, the flag approach requires real reasoning. Comments won't help here; explaining the ordering and interactions via comments would be as complicated as the code itself, thereby imposing a greater cognitive burden.

Furthermore, supporting a variable interval (as done in the count-only approach) is a pattern we should embrace, rather than working around it by introducing a separate flag.

We have also already discussed why retaining count=0 is not a drop-in alternative under the same counter-only instrumentation. The initial state must distinguish execution that starts inside the ROI from execution waiting for the begin marker.

Quoted 7 lines
Quoted 3 lines

Putting all together, I still believe utilizing the existing signed representation is cleaner than inventing an alternative approach ourselves.

I respect your opinion, but I would prefer to not introduce such usage of the existing API in contrib/, since it might (wrongly) inspire other people reading this plugin code.

I agree that contrib plugins should set a good example. What pattern would you like them to demonstrate for a counting timer whose expiration can change at runtime, including effectively disabling the timer?

The counter-only design expresses this by updating the counter while keeping the instrumentation unchanged. I think that is a useful pattern to demonstrate, with its interpretation and assumptions documented.

I would like to understand which general pattern you would prefer to encourage, so we can compare the approaches on that basis.

Regards,
Akihiko Odaki

#17 lore raw

Re: [PATCH 2/2] contrib/plugins/bbv.c: Allow selecting ROI

Quoted 436 lines · Akihiko Odaki
Quoted 435 lines · Pierrick Bouvier
Quoted 433 lines · Akihiko Odaki
Quoted 380 lines · Pierrick Bouvier
Quoted 314 lines · Akihiko Odaki
Quoted 282 lines · Pierrick Bouvier
Quoted 255 lines · Akihiko Odaki
Quoted 247 lines · Pierrick Bouvier
Quoted 208 lines · Akihiko Odaki
Quoted 200 lines · Pierrick Bouvier
Quoted 185 lines · Akihiko Odaki
Quoted 39 lines · Pierrick Bouvier
Quoted 38 lines · Akihiko Odaki

A region of interest (ROI) often excludes the program startup
and
exit.
For example, a benchmark may parse a large input and then run a
computation kernel and the former may take longer than the
latter;
basic block vectors generated for the whole execution will not
properly
represent the latter.

Add options to specify the beginning and the end of the ROI to
bound
basic block vector generation to the ROI.

Signed-off-by: Akihiko Odaki <[email protected]>
---
      docs/about/emulation.rst |  8 +++++
      contrib/plugins/bbv.c    | 80 +++++++++++++++++++++++++
++++
++++++++
+++++++++--
      2 files changed, 86 insertions(+), 2 deletions(-)

diff --git a/docs/about/emulation.rst b/docs/about/emulation.rst
index c58149086cdd..0566171b517b 100644
--- a/docs/about/emulation.rst
+++ b/docs/about/emulation.rst
@@ -284,6 +284,14 @@ The bbv plugin allows you to generate basic
block vectors for use with the
          * - Option
          - Description
+  * - begin=A
+    - The virtual address of the instruction that starts basic
block
vector
+      generation. Generation starts from the beginning of the
execution if
+      not specified.

Quoted 8 lines
Quoted 6 lines

+  * - end=A
+    - The virtual address of the instruction that ends basic
block
vector
+      generation. Generation continues until the endo of the
execution if

small typo here: s/endo/end

Thanks for catching the typo.

Quoted 41 lines
Quoted 37 lines

+      not specified.
        * - interval=N
          - The interval to generate a basic block vector
specified by
the number of
            instructions (Default: N = 100000000)
diff --git a/contrib/plugins/bbv.c b/contrib/plugins/bbv.c
index e5caf5d9543b..a2a779f7639e 100644
--- a/contrib/plugins/bbv.c
+++ b/contrib/plugins/bbv.c
@@ -5,6 +5,8 @@
       * SPDX-License-Identifier: GPL-2.0-or-later
       */
      +#include <stdbool.h>
+#include <stdint.h>
      #include <stdio.h>
      #include <glib.h>
      @@ -26,6 +28,10 @@ static GHashTable *bbs;
      static GRWLock bbs_lock;
      static char *filename;
      static struct qemu_plugin_scoreboard *vcpus;
+static bool begin_present;
+static uint64_t begin;
+static bool end_present;
+static uint64_t end;
      static int64_t interval = 100000000;
        static void plugin_exit(void *p)
@@ -66,6 +72,7 @@ static void vcpu_init(unsigned int vcpu_index,
void
*userdata)
          Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus,
vcpu_index);
            vcpu_filename = g_strdup_printf("%s.%u.bb",
filename,
vcpu_index);
+    vcpu->count = begin_present ? INT64_MIN : -interval;

Not sure which semantic we are trying to achieve with -interval here.

Quoted 5 lines

The original logic was to increment this count, until reaching interval,
after what we would reset it by using vcpu_count -= interval, to keep
the extra insn that went in after the threshold.

The counter now starts at -interval and counts up to zero. Subtracting
interval after emitting a vector still preserves the extra instructions.
For example, with interval=100:

        initial count:       -100
        after 130 insns:       30  -> emit a vector subtract interval:    -70  -> 70 insns until the next
vector

Quoted 61 lines
Quoted 61 lines

          vcpu->file = fopen(vcpu_filename, "w");
      }
      @@ -102,6 +109,22 @@ static void
vcpu_interval_exec(unsigned int
vcpu_index, void *udata)
          fputc('\n', vcpu->file);
      }
      +static void vcpu_begin_insn_exec(unsigned int vcpu_index,
void
*userdata)
+{
+    GHashTableIter iter;
+    void *value;
+
+    g_rw_lock_reader_lock(&bbs_lock);
+    g_hash_table_iter_init(&iter, bbs);
+
+    while (g_hash_table_iter_next(&iter, NULL, &value)) {
+        qemu_plugin_u64_set(bb_count_u64(value), vcpu_index,
0);
+    }
+
+    g_rw_lock_reader_unlock(&bbs_lock);
+    qemu_plugin_u64_set(count_u64(), vcpu_index, -interval);
+}
+
      static void vcpu_tb_trans(struct qemu_plugin_tb *tb, void
*userdata)
      {
          uint64_t n_insns = qemu_plugin_tb_n_insns(tb);
@@ -119,6 +142,19 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb
*tb, void *userdata)
          }
          g_rw_lock_writer_unlock(&bbs_lock);
      +    for (size_t idx = 0; idx < n_insns; idx++) {
+        struct qemu_plugin_insn *insn =
qemu_plugin_tb_get_insn(tb,
idx);
+        uint64_t insn_vaddr = qemu_plugin_insn_vaddr(insn);
+
+        if (begin_present && insn_vaddr == begin) {
+            qemu_plugin_register_vcpu_insn_exec_cb(
+                insn, vcpu_begin_insn_exec,
QEMU_PLUGIN_CB_NO_REGS,
NULL);
+        } else if (end_present && insn_vaddr == end) {
+
qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64,
count_u64(),
INT64_MIN);
+        }
+    }
+
          qemu_plugin_register_vcpu_tb_exec_inline_per_vcpu(
              tb, QEMU_PLUGIN_INLINE_ADD_U64, count_u64(),
n_insns);
      @@ -127,7 +163,32 @@ static void vcpu_tb_trans(struct
qemu_plugin_tb *tb, void *userdata)

Quoted 8 lines
Quoted 5 lines

            qemu_plugin_register_vcpu_tb_exec_cond_cb(
              tb, vcpu_interval_exec, QEMU_PLUGIN_CB_NO_REGS,
-        QEMU_PLUGIN_COND_GE, count_u64(), interval, NULL);
+        QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
+}

is INT64_MIN used as an arbitrary large value when interpreted as unsigned immediate? If yes, that's confusing to the reader.

The unsigned comparison count < (uint64_t)INT64_MIN is equivalent with
the signed comparison (int64_t)count >= 0. That is why this particular
value is used.

Quoted 8 lines

Setting count to INT64_MIN suppresses output for the next 2^63 counted
instructions, which is effectively disabled for this use. The beginEmulation
callback clears the BB counters and sets count to -interval; end sets it
back to INT64_MIN. The requested interval stays unchanged.

Ok I see better.
Even though it works, it's pretty confusing to be honest. Inline operatons works with unsigned values, so with conversion and wrap around, it's safe, but really not intuitive.

Quoted 6 lines

I would prefer if you could refactor this to keep a zero initialized
count value, and add a specific instrumentation path for begin, end logic (COND_LT, UINT64_MAX - N) to keep the same behavior of "infinite
interval".

Quoted 8 lines

We cannot choose a separate instrumentation path based on whether execution is inside the ROI. Instrumentation is installed when a TB is
translated, but the same TB may execute both inside and outside the ROI.

I will preserve this logic and add code comments for clarification.

I took some time to read again how bbv works. Indeed, my idea to modify
interval was a non sense, and not what is expected.

The current instrumentation per tb is always done unconditionally, and
the only need thing to do is to snapshot bbs hashtable to keep track of
the correct data only when being inside the ROI. The rest of existing logic stays the same.

- On enter, set vcpu->count to 0 (fresh start) and restore bb table from
previous exit (empty table if there was no exit yet).
- On exit, duplicate the bb table to allow to restore it next time we enter in ROI.
Key idea is that we keep on adding things in bb table, but save/ restore
when leaving/entering ROI.

I think for robustness you should also add detection of those expected
transitions: Out of ROI -> Enter ROI -> Exit ROI -> Enter ROI -> ...

Nothing is currently done to detect if if we meet enter/exit address multiple times, without having the correct sequence. I don't know if we
want to report an error or handle reentrance correctly in this case.

Quoted 6 lines

Also, should count be reset on each entrance, or do we want to keep track of it also, and save/restore that on exit/enter? I tend to think
the idea is create a "virtual" interval than only is alive when being inside the ROI. In this case, we should keep track of this value also.

Quoted 5 lines

The current design that resets the bb table is intentional. A "virtual"
interval spanning multiple ROIs would be misleading because it mixes different sections of execution.

Ok.

Quoted 11 lines

I don't think we need to add a special handling to enforce a particular
order of transitions. This patch performs the same action for the begin
and end addresses and that makes the behavior predictable.

Perhaps we can extend the documentation to clarify the "begin" marker to
tell that it resets the bb table, making the behavior clear regardless of transition order.

I'm fine to keep a simple model, but I'll ask you to remove the logic involving negative numbers, it's just too confusing. Please remove:
vcpu->count = begin_present ? INT64_MIN : -interval;
and
QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);

Quoted 3 lines

Instead, let's add a new boolean "tracking_region" in struct Vcpu, that is set to true when entering ROI (or true by default if no begin parameter was given).

The flag may look simpler in isolation, but streamlining the interactions with the counter requires more careful thought. Please see below.

Quoted 15 lines

Then, modify instrumentation to replace:

```
else if (end_present && insn_vaddr == end) {
                qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
                    insn, QEMU_PLUGIN_INLINE_STORE_U64, count_u64(),
INT64_MIN);
```
with:
```
else if (end_present && insn_vaddr == end) {
       qemu_plugin_register_vcpu_insn_exec_cb(insn, vcpu_exit_region,
QEMU_PLUGIN_CB_NO_REGS, NULL);
}
Quoted 7 lines
static void vcpu_exit_region(unsigned int vcpu_index, void *userdata)
{
       Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index);
       vcpu_interval_exec(vcpu_index, NULL);
       vcpu->tracking_region = false;
}
```
Quoted 5 lines

vcpu_exit_region should only disable tracking. Calling vcpu_interval_exec directly bypasses its count >= interval precondition:
it subtracts interval even when count is smaller, wrapping the unsigned counter, and emits a partial vector or potentially an empty one.

I'm fine with it. I was unsure if you wanted to dump the partial data, aggregate it when reentering the section, or simply discard it. With a discard, it's even simpler, just need to set tracking_region to false.

Quoted 13 lines
Quoted 4 lines

In addition, let's rename s/vcpu_begin_insn_exec/vcpu_enter_region, to be consistent and explicit on what it's doing.

Quoted 8 lines

And finally, the last piece:
static void vcpu_interval_exec(unsigned int vcpu_index, void *udata) {
      Vcpu *vcpu = qemu_plugin_scoreboard_find(vcpus, vcpu_index); if (!vcpu->tracking) {
        return;
      }
      ...

Quoted 5 lines

The early return must come after vcpu->count -= interval. Otherwise, once count reaches interval outside the ROI, it remains above the threshold and invokes the callback on every subsequent TB, rather than once per interval.

Right, thanks for catching it.

Quoted 15 lines
Quoted 5 lines

The impact performance of calling vcpu_interval_exec + one if every N instructions is invisible, and at least, it's a piece of code we can read in 6 months, and understand in less than 2 min without any additional doc.

I agree the performance impact is negligible, but at least you need to consider about that to be sure. Adding another flag requires those additional considerations.

More broadly, I don't think it's ideal to introduce application-specific logic for this. Looking at the bigger picture, a counting timer with variable expiration is a common pattern that should ideally be supported generally.

Quoted 8 lines

An alternative option is to have signed integer variants of qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() and similar functions to support for that. However, I don't think those are necessary either. Taking at an even broader perspective, C allows avoiding such specialization by letting unsigned variables hold signed values in a well-defined manner; even the underlying implementation of the inline op uses signed and unsigned types interchangeably.

If the argument is "C allows that with a defined behaviour", I don't think it makes a point for me. There is a lot of well defined and confusing code you can write.

Something like:
  qemu_plugin_register_vcpu_tb_exec_cond_cb( QEMU_PLUGIN_COND_LT, count_u64(), INT64_MIN, NULL);
with limit and counter being unsigned is not readable for me.

Quoted 8 lines
Quoted 4 lines

Although it might not be immediately obvious that an unsigned variable is storing a signed value, adding a brief clarifying comment is still simpler than introducing another variable overall.

 From there I'll let you decide between introducing the flag, or
reimplement that with positive values (sticking to init count=0) only if you really prefer this approach.

I agree that "C allows this with defined behaviour" is insufficient on its own. Ideally, we could express the signed interpretation directly with int64_t without adding complexity. That would improve clarity, even though the existing arithmetic is already well-defined.

However, we need to consider the whole design. Both approaches require readers to understand more than the individual expressions.

The counter-only approach requires knowing that:

- count is actually treated as signed.
- Any non-negative is smaller than (uint64_t)INT64_MIN when compared as unsigned.

The flag approach requires considering:
- How the count and flag together determine when a vector is emitted.
- The required ordering of count and flag accesses.
- Whether the number of callback invocations will significantly increase.

The count-only approach requires fewer considerations, and the ones it does require needs no deduction. The first point is a common practice, as seen in the underlying implementation. The second point is simply a matter of the int64_t definition. In both cases, knowing the definition is sufficient, and both can be documented clearly in the comments.

In contrast, the flag approach requires real reasoning. Comments won't help here; explaining the ordering and interactions via comments would be as complicated as the code itself, thereby imposing a greater cognitive burden.

Furthermore, supporting a variable interval (as done in the count-only approach) is a pattern we should embrace, rather than working around it by introducing a separate flag.

We have also already discussed why retaining count=0 is not a drop-in alternative under the same counter-only instrumentation. The initial state must distinguish execution that starts inside the ROI from execution waiting for the begin marker.

Putting all together, I still believe utilizing the existing signed representation is cleaner than inventing an alternative approach ourselves.

Quoted 8 lines
Quoted 3 lines

I respect your opinion, but I would prefer to not introduce such usage of the existing API in contrib/, since it might (wrongly) inspire other people reading this plugin code.

I agree that contrib plugins should set a good example. What pattern would you like them to demonstrate for a counting timer whose expiration can change at runtime, including effectively disabling the timer?

You can still emulate this behavior by having a fixed limit, and set scoreboard value as you wish. This emulates a counting timer with variable expiration, by growing/shrinking your distance to the bound as you wish. You're well aware that's also exactly what the current patch is doing, except that it's using signed values converted to unsigned, and that's my only problem with it. If it was only unsigned values with an arbitrary limit (UINT64_MAX >> 1) for instance, I would be ok with it.

When we designed those inline operations, we considered various things, including if a semantic of "add only with unsigned values" was enough. So far, there was nothing that couldn't be expressed easily with that.

Quoted 7 lines

The counter-only design expresses this by updating the counter while keeping the instrumentation unchanged. I think that is a useful pattern to demonstrate, with its interpretation and assumptions documented.

I would like to understand which general pattern you would prefer to encourage, so we can compare the approaches on that basis.

For current use case, I don't see any new pattern. It's just an instrumentation that is always active, with a callback that does something or not based on a predicate (in_region in this case).

So I'll repeat one of my previous answer, you have the choice between:
- A simple bool tracking_region or in_region representing the predicate, with {enter,exit}_region callbacks. The code is self documenting and explicit.
- Choose an arbitrary strictly positive bound, keep vcpu->count init to 0, and implement the rest accordingly. I'll accept that too if the introduction of a bool is really something not acceptable for you.

I would finally say that if you're really focused on performance, and having done my homework on this part, I can tell you that conditional callbacks are not as "free" as what you might think, since they are still composed of multiple tcg_op, which translates to a lot of host instructions. They can even be slower than a callback that does not access registers. So, personally, I have no problem with a simple callback checking a if and returning early.

Quoted 2 lines

Regards,
Akihiko Odaki

Regards,
Pierrick