Skip to contentSkip to conversation

Rewrite jevents program in python

PATCH Superseded Ian Rogers 3 participants 14 messages Jun 16, 2022 – Jun 17, 2022 perf events

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Ian Rogers

author reviewer
#0 lore raw

v5 cover Rewrite jevents program in python

New architectures bring new complexity, such as Intel's hybrid models. jevents provides an alternative to specifying events in the kernel and exposing them through sysfs, however, it is difficult to work with. For example, an error in the json input would yield an error message but no json file or location. It is also a challenge to update jsmn.c given its forked nature.

The changes here switch from jevents.c to a rewrite in python called jevents.py. This means there is a build time dependency on python, but such a dependency already exists for asciidoc (used to generate perf's man pages). If the build detects that python isn't present or is older than version 3.6 (released Dec. 2016) then an empty file is substituted for the generated one.

A challenge with this code is in avoiding regressions. For this reason the jevents.py produces identical output to jevents.c, validated with a test script and build target.

v5. Adds a 2>/dev/null as suggested by David Laight
<[email protected]>.
v4. Fixes the build for systems with python2 installed by adding a
patch that makes python3 the preferred python (Reported-by: John Garry <[email protected]>). It also fixes a bash-ism in the jevents-test.sh and fixes the handling of an empty string for a metric BriefDescription as one was added for sapphirerapids in the metric Execute.
v3. Updates the patches for merged changes (on
acme/tmp.perf/core). Re-runs all comparisons to make sure the generated pmu-events.c isn't altered at all by this change. Adds the jevents.c ExtSel fix in:
https://lore.kernel.org/lkml/[email protected]/
Bumps the python version from 3.5 to 3.6, as f-strings weren't introduced until 3.6.

v2. Fixes the build for architectures that don't have pmu-events json
(Suggested-by: John Garry <[email protected]>) and fixes the build for python not being present or too old (Suggested-by: Peter Zijlstra <[email protected]>/John Garry <[email protected]>).

Ian Rogers (4):
perf python: Prefer python3
perf jevents: Add python converter script
perf jevents: Switch build to use jevents.py
perf jevents: Remove jevents.c

 tools/perf/Makefile.config               |   27 +-
 tools/perf/Makefile.perf                 |   16 +-
 tools/perf/pmu-events/Build              |   15 +-
 tools/perf/pmu-events/empty-pmu-events.c |   21 +
 tools/perf/pmu-events/jevents.c          | 1342 ----------------------
 tools/perf/pmu-events/jevents.py         |  394 +++++++
 tools/perf/pmu-events/jsmn.h             |   68 --
 tools/perf/pmu-events/json.c             |  162 ---
 tools/perf/pmu-events/json.h             |   39 -
 9 files changed, 450 insertions(+), 1634 deletions(-)
 create mode 100644 tools/perf/pmu-events/empty-pmu-events.c
 delete mode 100644 tools/perf/pmu-events/jevents.c
 create mode 100755 tools/perf/pmu-events/jevents.py
 delete mode 100644 tools/perf/pmu-events/jsmn.h
 delete mode 100644 tools/perf/pmu-events/json.c
 delete mode 100644 tools/perf/pmu-events/json.h
Signature · 1 line
2.36.1.476.g0c4daa206d-goog
author reviewer
#1 lore raw

PATCH v5 1/4 perf python: Prefer python3

The PYTHON_AUTO code orders the preference for the PYTHON command to be python3, python and then python2. python3 makes a more logical preference as python2 is no longer supported:
https://www.python.org/doc/sunset-python-2/

Reorder the priority of the PYTHON command to be python2, python and then python3.

---
 tools/perf/Makefile.config | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/Makefile.config +4 -4
index 73e0762092fe..16c1a87444b8 100644
@@ -241,15 +241,15 @@ endif
 # Try different combinations to accommodate systems that only have
 # python[2][3]-config in weird combinations in the following order of
 # priority from lowest to highest:
-#   * python3-config
-#   * python-config
 #   * python2-config as per pep-0394.
+#   * python-config
+#   * python3-config
 #   * $(PYTHON)-config (If PYTHON is user supplied but PYTHON_CONFIG isn't)
 #
 PYTHON_AUTO := python-config
-PYTHON_AUTO := $(if $(call get-executable,python3-config),python3-config,$(PYTHON_AUTO))
-PYTHON_AUTO := $(if $(call get-executable,python-config),python-config,$(PYTHON_AUTO))
 PYTHON_AUTO := $(if $(call get-executable,python2-config),python2-config,$(PYTHON_AUTO))
+PYTHON_AUTO := $(if $(call get-executable,python-config),python-config,$(PYTHON_AUTO))
+PYTHON_AUTO := $(if $(call get-executable,python3-config),python3-config,$(PYTHON_AUTO))
 
 # If PYTHON is defined but PYTHON_CONFIG isn't, then take $(PYTHON)-config as if it was the user
 # supplied value for PYTHON_CONFIG. Because it's "user supplied", error out if it doesn't exist.
Signature · 1 line
2.36.1.476.g0c4daa206d-goog
author reviewer
#2 lore raw

PATCH v5 2/4 perf jevents: Add python converter script

In reply to Ian Rogers

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
 tools/perf/Makefile.perf              |   6 +
 tools/perf/pmu-events/jevents-test.sh |  33 +++
 tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
 3 files changed, 433 insertions(+)
 create mode 100755 tools/perf/pmu-events/jevents-test.sh
 create mode 100755 tools/perf/pmu-events/jevents.py
tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
 $(JEVENTS): $(JEVENTS_IN)
 	$(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY	:=  pmu-events/jevents.py
+JEVENTS_PY_TEST	:=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+	$(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
 $(PMU_EVENTS_IN): $(JEVENTS) FORCE
 	$(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +394 -0

394 lines not on this page · raw message

Signature · 1 line
2.36.1.476.g0c4daa206d-goog
#3 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.
My python version:
Python 2.7.18 (default, Mar 8 2021, 13:02:45)
[GCC 9.3.0] on linux2

GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>

    def file_name_to_table_name(parents: list[str], dirname: str) -> str:

TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 483 lines · Ian Rogers

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
  tools/perf/Makefile.perf              |   6 +
  tools/perf/pmu-events/jevents-test.sh |  33 +++
  tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
  3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
  $(JEVENTS): $(JEVENTS_IN)
  	$(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY	:=  pmu-events/jevents.py
+JEVENTS_PY_TEST	:=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+	$(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
  $(PMU_EVENTS_IN): $(JEVENTS) FORCE
  	$(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +394 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()
Signature · 1 line
Zhengjun Xing
author reviewer
#4 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Quoted 15 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.
My python version:

   Python 2.7.18 (default, Mar  8 2021, 13:02:45)
   [GCC 9.3.0] on linux2


   GEN     pmu-events/pmu-events.c

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>

Quoted 7 lines
     def file_name_to_table_name(parents: list[str], dirname: str) -> str:

TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
  tools/perf/Makefile.perf              |   6 +
  tools/perf/pmu-events/jevents-test.sh |  33 +++
  tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
  3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
  $(JEVENTS): $(JEVENTS_IN)
      $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
  $(PMU_EVENTS_IN): $(JEVENTS) FORCE
      $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

#5 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

    My python version:
    Python 2.7.18 (default, Mar  8 2021, 13:02:45)
    [GCC 9.3.0] on linux2


    GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
   tools/perf/Makefile.perf              |   6 +
   tools/perf/pmu-events/jevents-test.sh |  33 +++
   tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
   3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
   $(JEVENTS): $(JEVENTS_IN)
       $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
   $(PMU_EVENTS_IN): $(JEVENTS) FORCE
       $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

Signature · 1 line
Zhengjun Xing
author reviewer
#6 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Quoted 48 lines · Xing Zhengjun

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

    My python version:
    Python 2.7.18 (default, Mar  8 2021, 13:02:45)
    [GCC 9.3.0] on linux2


    GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
Quoted 4 lines

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

TL;DR "apt install python-dev-is-python3" :-)

The problem is what you lose by making the code work with python2:
f-strings, various library functions. You end up coding to a worse standard of Python and the code is considered non-pythonic. Python 3.6 was released in Dec. 2016 and so is over 5 years old now - ie I'm not pushing for the bleeding edge.

A problem we face in the regular perf Python build is that Python 2 doesn't support new APIs and Python3 has deprecated the old APIs [1]. I think the sensible thing is to follow Python 3's deprecation plan which will mean losing Python 2 support, ie we shouldn't look for python2-config in the build any more as python2 won't support the APIs our scripts are now using.

I think arguing that Python 2 was something not worth sunsetting was an argument to be made 2 years ago, but now we have to live with the consequences. I don't think there is any hardship except an install step. For the build changes in these patches if an old version of Python is detected then you just don't get jevents and there is a warning at build time.

Thanks,
Ian

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 494 lines
Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
   tools/perf/Makefile.perf              |   6 +
   tools/perf/pmu-events/jevents-test.sh |  33 +++
   tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
   3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
   $(JEVENTS): $(JEVENTS_IN)
       $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
   $(PMU_EVENTS_IN): $(JEVENTS) FORCE
       $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

--
Zhengjun Xing

#7 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Quoted 70 lines · Ian Rogers
Quoted 48 lines · Xing Zhengjun

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

     My python version:
     Python 2.7.18 (default, Mar  8 2021, 13:02:45)
     [GCC 9.3.0] on linux2


     GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
Quoted 4 lines

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

TL;DR "apt install python-dev-is-python3" :-)

The problem is what you lose by making the code work with python2:
f-strings, various library functions. You end up coding to a worse standard of Python and the code is considered non-pythonic. Python 3.6 was released in Dec. 2016 and so is over 5 years old now - ie I'm not pushing for the bleeding edge.

A problem we face in the regular perf Python build is that Python 2 doesn't support new APIs and Python3 has deprecated the old APIs [1]. I think the sensible thing is to follow Python 3's deprecation plan which will mean losing Python 2 support, ie we shouldn't look for python2-config in the build any more as python2 won't support the APIs our scripts are now using.

Quoted 6 lines

I think arguing that Python 2 was something not worth sunsetting was an argument to be made 2 years ago, but now we have to live with the consequences. I don't think there is any hardship except an install step. For the build changes in these patches if an old version of Python is detected then you just don't get jevents and there is a warning at build time.

After "sudo apt install python-dev-is-python3", now the python version :
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux

But the issue still happened.

$cd tools/perf
$make
GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>

    def file_name_to_table_name(parents: list[str], dirname: str) -> str:

TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

For the python version, I think python3 is ok.
But during the build, we need to add a warning and how to fix messages when detecting the system is using pthon2, just like it did before:

Auto-detecting system features:

...                         dwarf: [ on  ]
...            dwarf_getlocations: [ on  ]
...                         glibc: [ on  ]
...                        libbfd: [ on  ]
...                libbfd-buildid: [ on  ]
...                        libcap: [ on  ]
...                        libelf: [ on  ]
...                       libnuma: [ on  ]
...        numa_num_possible_cpus: [ on  ]
...                       libperl: [ on  ]
...                     libpython: [ on  ]
...                     libcrypto: [ on  ]
...                     libunwind: [ on  ]
...            libdw-dwarf-unwind: [ on  ]
...                          zlib: [ on  ]
...                          lzma: [ on  ]
...                     get_cpuid: [ on  ]
...                           bpf: [ on  ]
...                        libaio: [ on  ]
...                       libzstd: [ on  ]
...        disassembler-four-args: [ on  ]

... python-dev-is-python3: [ off ]

Quoted 501 lines

Thanks,
Ian

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 494 lines
Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
    tools/perf/Makefile.perf              |   6 +
    tools/perf/pmu-events/jevents-test.sh |  33 +++
    tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
    3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
    $(JEVENTS): $(JEVENTS_IN)
        $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
    $(PMU_EVENTS_IN): $(JEVENTS) FORCE
        $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

--
Zhengjun Xing

Signature · 1 line
Zhengjun Xing
author reviewer
#8 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Quoted 129 lines · Xing Zhengjun
Quoted 70 lines · Ian Rogers
Quoted 48 lines · Xing Zhengjun

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

     My python version:
     Python 2.7.18 (default, Mar  8 2021, 13:02:45)
     [GCC 9.3.0] on linux2


     GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
Quoted 4 lines

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

TL;DR "apt install python-dev-is-python3" :-)

The problem is what you lose by making the code work with python2:
f-strings, various library functions. You end up coding to a worse standard of Python and the code is considered non-pythonic. Python 3.6 was released in Dec. 2016 and so is over 5 years old now - ie I'm not pushing for the bleeding edge.

A problem we face in the regular perf Python build is that Python 2 doesn't support new APIs and Python3 has deprecated the old APIs [1]. I think the sensible thing is to follow Python 3's deprecation plan which will mean losing Python 2 support, ie we shouldn't look for python2-config in the build any more as python2 won't support the APIs our scripts are now using.

Quoted 6 lines

I think arguing that Python 2 was something not worth sunsetting was an argument to be made 2 years ago, but now we have to live with the consequences. I don't think there is any hardship except an install step. For the build changes in these patches if an old version of Python is detected then you just don't get jevents and there is a warning at build time.

After "sudo apt install python-dev-is-python3", now the python version :
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux

But the issue still happened.

$cd tools/perf
$make
GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>

     def file_name_to_table_name(parents: list[str], dirname: str) -> str:

TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

For the python version, I think python3 is ok.
But during the build, we need to add a warning and how to fix messages when detecting the system is using pthon2, just like it did before:

Auto-detecting system features:

...                         dwarf: [ on  ]
...            dwarf_getlocations: [ on  ]
...                         glibc: [ on  ]
...                        libbfd: [ on  ]
...                libbfd-buildid: [ on  ]
...                        libcap: [ on  ]
...                        libelf: [ on  ]
...                       libnuma: [ on  ]
...        numa_num_possible_cpus: [ on  ]
...                       libperl: [ on  ]
...                     libpython: [ on  ]
...                     libcrypto: [ on  ]
...                     libunwind: [ on  ]
...            libdw-dwarf-unwind: [ on  ]
...                          zlib: [ on  ]
...                          lzma: [ on  ]
...                     get_cpuid: [ on  ]
...                           bpf: [ on  ]
...                        libaio: [ on  ]
...                       libzstd: [ on  ]
...        disassembler-four-args: [ on  ]
Quoted 2 lines

... python-dev-is-python3: [ off ]

Agreed on cleaning up the python Makefile logic. I'd rather do it out of these patches. For the issue you see can you try adding the 1 liner:

```
diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py
index 658eb2696f9a..9f1a37515c0f 100755
--- a/tools/perf/pmu-events/jevents.py
+++ b/tools/perf/pmu-events/jevents.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
"""Convert directories of JSON events to C code."""
+from __future__ import annotations
import argparse
import csv
import json
```

Thanks,
Ian

Quoted 504 lines
Quoted 501 lines

Thanks,
Ian

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 494 lines
Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
    tools/perf/Makefile.perf              |   6 +
    tools/perf/pmu-events/jevents-test.sh |  33 +++
    tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
    3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
    $(JEVENTS): $(JEVENTS_IN)
        $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
    $(PMU_EVENTS_IN): $(JEVENTS) FORCE
        $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

--
Zhengjun Xing

--
Zhengjun Xing

#9 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Hi Ian,

Quoted 146 lines · Ian Rogers
Quoted 129 lines · Xing Zhengjun
Quoted 70 lines · Ian Rogers
Quoted 48 lines · Xing Zhengjun

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

      My python version:
      Python 2.7.18 (default, Mar  8 2021, 13:02:45)
      [GCC 9.3.0] on linux2


      GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
Quoted 4 lines

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

TL;DR "apt install python-dev-is-python3" :-)

The problem is what you lose by making the code work with python2:
f-strings, various library functions. You end up coding to a worse standard of Python and the code is considered non-pythonic. Python 3.6 was released in Dec. 2016 and so is over 5 years old now - ie I'm not pushing for the bleeding edge.

A problem we face in the regular perf Python build is that Python 2 doesn't support new APIs and Python3 has deprecated the old APIs [1]. I think the sensible thing is to follow Python 3's deprecation plan which will mean losing Python 2 support, ie we shouldn't look for python2-config in the build any more as python2 won't support the APIs our scripts are now using.

Quoted 6 lines

I think arguing that Python 2 was something not worth sunsetting was an argument to be made 2 years ago, but now we have to live with the consequences. I don't think there is any hardship except an install step. For the build changes in these patches if an old version of Python is detected then you just don't get jevents and there is a warning at build time.

After "sudo apt install python-dev-is-python3", now the python version :
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux

But the issue still happened.

$cd tools/perf
$make
GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

For the python version, I think python3 is ok.
But during the build, we need to add a warning and how to fix messages when detecting the system is using pthon2, just like it did before:

Auto-detecting system features:

...                         dwarf: [ on  ]
...            dwarf_getlocations: [ on  ]
...                         glibc: [ on  ]
...                        libbfd: [ on  ]
...                libbfd-buildid: [ on  ]
...                        libcap: [ on  ]
...                        libelf: [ on  ]
...                       libnuma: [ on  ]
...        numa_num_possible_cpus: [ on  ]
...                       libperl: [ on  ]
...                     libpython: [ on  ]
...                     libcrypto: [ on  ]
...                     libunwind: [ on  ]
...            libdw-dwarf-unwind: [ on  ]
...                          zlib: [ on  ]
...                          lzma: [ on  ]
...                     get_cpuid: [ on  ]
...                           bpf: [ on  ]
...                        libaio: [ on  ]
...                       libzstd: [ on  ]
...        disassembler-four-args: [ on  ]
Quoted 2 lines

... python-dev-is-python3: [ off ]

Agreed on cleaning up the python Makefile logic. I'd rather do it out of these patches. For the issue you see can you try adding the 1 liner:

```

tools/perf/pmu-events/jevents.py +0 -0
index 658eb2696f9a..9f1a37515c0f 100755
@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
Quoted 7 lines

"""Convert directories of JSON events to C code.""" +from __future__ import annotations
import argparse
import csv
import json
```

With the patch, the build still fails.

GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 395, in <module>

    main()
  File "pmu-events/jevents.py", line 387, in main
    ftw(arch_path, [], process_one_file)
  File "pmu-events/jevents.py", line 368, in ftw
    ftw(item.path, parents + [item.name], action)
  File "pmu-events/jevents.py", line 366, in ftw
    action(parents, item)
  File "pmu-events/jevents.py", line 298, in process_one_file
    print_events_table_entries(item, get_topic(item.name))
  File "pmu-events/jevents.py", line 270, in get_topic
    return topic.removesuffix('.json').replace('-', ' ')

AttributeError: 'str' object has no attribute 'removesuffix' make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[3]: *** Deleting file 'pmu-events/pmu-events.c' make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 507 lines

Thanks,
Ian

Quoted 504 lines
Quoted 501 lines

Thanks,
Ian

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 494 lines
Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
     tools/perf/Makefile.perf              |   6 +
     tools/perf/pmu-events/jevents-test.sh |  33 +++
     tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
     3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
     $(JEVENTS): $(JEVENTS_IN)
         $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
     $(PMU_EVENTS_IN): $(JEVENTS) FORCE
         $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

--
Zhengjun Xing

--
Zhengjun Xing

Signature · 1 line
Zhengjun Xing
author reviewer
#10 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

Quoted 175 lines · Xing Zhengjun

Hi Ian,

Quoted 146 lines · Ian Rogers
Quoted 129 lines · Xing Zhengjun
Quoted 70 lines · Ian Rogers
Quoted 48 lines · Xing Zhengjun

Hi Ian,

Quoted 25 lines · Ian Rogers
Quoted 11 lines · Xing Zhengjun

Hi Ian,

I applied this patch series based on the head of the perf/core
branch, but it failed when do make.

      My python version:
      Python 2.7.18 (default, Mar  8 2021, 13:02:45)
      [GCC 9.3.0] on linux2


      GEN     pmu-events/pmu-events.c
Quoted 11 lines

make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Quoted 7 lines

Hi Zhengjun,

Thanks for testing! You are running the test script and not the main build. Unlike the main build I didn't add a Python version test for the test script. As mentioned in the cover letter you need Python 3.6 as Python 2 was sunset in 2020.

In fact, I run the main build,

$ cd tools/perf
$ make
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal
Quoted 4 lines

The default python in Ubuntu 20.04.3 is Python2

I think a lot of developers also use the Ubuntu 20.04.3 LTS, it's better to support python2.

TL;DR "apt install python-dev-is-python3" :-)

The problem is what you lose by making the code work with python2:
f-strings, various library functions. You end up coding to a worse standard of Python and the code is considered non-pythonic. Python 3.6 was released in Dec. 2016 and so is over 5 years old now - ie I'm not pushing for the bleeding edge.

A problem we face in the regular perf Python build is that Python 2 doesn't support new APIs and Python3 has deprecated the old APIs [1]. I think the sensible thing is to follow Python 3's deprecation plan which will mean losing Python 2 support, ie we shouldn't look for python2-config in the build any more as python2 won't support the APIs our scripts are now using.

Quoted 6 lines

I think arguing that Python 2 was something not worth sunsetting was an argument to be made 2 years ago, but now we have to live with the consequences. I don't think there is any hardship except an install step. For the build changes in these patches if an old version of Python is detected then you just don't get jevents and there is a warning at build time.

After "sudo apt install python-dev-is-python3", now the python version :
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux

But the issue still happened.

$cd tools/perf
$make
GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 23, in <module>
def file_name_to_table_name(parents: list[str], dirname: str) -> str:
TypeError: 'type' object is not subscriptable
make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

For the python version, I think python3 is ok.
But during the build, we need to add a warning and how to fix messages when detecting the system is using pthon2, just like it did before:

Auto-detecting system features:

...                         dwarf: [ on  ]
...            dwarf_getlocations: [ on  ]
...                         glibc: [ on  ]
...                        libbfd: [ on  ]
...                libbfd-buildid: [ on  ]
...                        libcap: [ on  ]
...                        libelf: [ on  ]
...                       libnuma: [ on  ]
...        numa_num_possible_cpus: [ on  ]
...                       libperl: [ on  ]
...                     libpython: [ on  ]
...                     libcrypto: [ on  ]
...                     libunwind: [ on  ]
...            libdw-dwarf-unwind: [ on  ]
...                          zlib: [ on  ]
...                          lzma: [ on  ]
...                     get_cpuid: [ on  ]
...                           bpf: [ on  ]
...                        libaio: [ on  ]
...                       libzstd: [ on  ]
...        disassembler-four-args: [ on  ]
Quoted 2 lines

... python-dev-is-python3: [ off ]

Agreed on cleaning up the python Makefile logic. I'd rather do it out of these patches. For the issue you see can you try adding the 1 liner:

```

tools/perf/pmu-events/jevents.py +0 -0
index 658eb2696f9a..9f1a37515c0f 100755
@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
Quoted 7 lines

"""Convert directories of JSON events to C code.""" +from __future__ import annotations
import argparse
import csv
import json
```

With the patch, the build still fails.

GEN pmu-events/pmu-events.c
make[3]: Nothing to be done for 'install_headers'.
GEN python/perf.so
Traceback (most recent call last):
File "pmu-events/jevents.py", line 395, in <module>

     main()
   File "pmu-events/jevents.py", line 387, in main
     ftw(arch_path, [], process_one_file)
   File "pmu-events/jevents.py", line 368, in ftw
     ftw(item.path, parents + [item.name], action)
   File "pmu-events/jevents.py", line 366, in ftw
     action(parents, item)
   File "pmu-events/jevents.py", line 298, in process_one_file
     print_events_table_entries(item, get_topic(item.name))
   File "pmu-events/jevents.py", line 270, in get_topic
     return topic.removesuffix('.json').replace('-', ' ')
Quoted 7 lines

AttributeError: 'str' object has no attribute 'removesuffix' make[3]: *** [pmu-events/Build:20: pmu-events/pmu-events.c] Error 1 make[3]: *** Deleting file 'pmu-events/pmu-events.c' make[2]: *** [Makefile.perf:663: pmu-events/pmu-events-in.o] Error 2 make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile.perf:240: sub-make] Error 2
make: *** [Makefile:70: all] Error 2

Ugh Python compatibility, removesuffix is Python 3.9. I want to automate checking Python version compatibility preferably without installing old versions of Python to achieve this. I'll post a new version with this, if you want to check with this version then update your python or switch the removesuffix calls.

Thanks,
Ian

Quoted 510 lines
Quoted 507 lines

Thanks,
Ian

Quoted 504 lines
Quoted 501 lines

Thanks,
Ian

[1] https://lore.kernel.org/lkml/[email protected]/

Quoted 494 lines
Quoted 491 lines

Thanks,
Ian

Quoted 487 lines · Ian Rogers
Quoted 473 lines

jevents.c is large, has a dependency on an old forked version of jsmn, and is challenging to work upon. A lot of jevents.c's complexity comes from needing to write json and csv parsing from first principles. In contrast python has this functionality in standard libraries and is already a build pre-requisite for tools like asciidoc (that builds all of the perf man pages).

Introduce jevents.py that produces identical output to jevents.c. Add a test that runs both converter tools and validates there are no output differences. The test can be invoked with a phony build target like:

make -C tools/perf jevents-py-test

The python code deliberately tries to replicate the behavior of jevents.c so that the output matches and transitioning tools shouldn't introduce regressions. In some cases the code isn't as elegant as hoped, but fixing this can be done as follow up.

---
     tools/perf/Makefile.perf              |   6 +
     tools/perf/pmu-events/jevents-test.sh |  33 +++
     tools/perf/pmu-events/jevents.py      | 394 ++++++++++++++++++++++++++
     3 files changed, 433 insertions(+)

create mode 100755 tools/perf/pmu-events/jevents-test.sh create mode 100755 tools/perf/pmu-events/jevents.py

tools/perf/Makefile.perf +6 -0
index 8f738e11356d..1e29c8936f71 100644
@@ -669,6 +669,12 @@ $(JEVENTS_IN): FORCE
     $(JEVENTS): $(JEVENTS_IN)
         $(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
 
+JEVENTS_PY   :=  pmu-events/jevents.py
+JEVENTS_PY_TEST      :=  pmu-events/jevents-test.sh
+.PHONY: jevents-py-test
+jevents-py-test: $(JEVENTS)
+     $(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
+
     $(PMU_EVENTS_IN): $(JEVENTS) FORCE
         $(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
tools/perf/pmu-events/jevents-test.sh new file +33 -0
new file mode 100755
index 000000000000..9ae852292576
@@ -0,0 +1,33 @@
+#!/bin/sh
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+# Validate that the legacy jevents and jevents.py produce identical output.
+set -e
+
+JEVENTS="$1"
+JEVENTS_PY="$2"
+ARCH_PATH="$3"
+JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
+JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
+
+cleanup() {
+  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+  trap - exit term int
+}
+trap cleanup exit term int
+
+for path in "$ARCH_PATH"/*
+do
+  arch=$(basename $path)
+  if [ "$arch" = "test" ]
+  then
+    continue
+  fi
+  echo "Checking architecture: $arch"
+  echo "Generating using jevents.c"
+  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
+  echo "Generating using jevents.py"
+  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
+  echo "Diffing"
+  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
+done
+cleanup
tools/perf/pmu-events/jevents.py new file +384 -0
new file mode 100755
index 000000000000..658eb2696f9a
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
+"""Convert directories of JSON events to C code."""
+import argparse
+import csv
+import json
+import os
+import sys
+from typing import Callable
+
+# Global command line arguments.
+args = None
+# List of event tables generated from "/sys" directories.
+sys_event_tables = []
+# Map from an event name to an architecture standard
+# JsonEvent. Architecture standard events are in json files in the top
+# f'{args.starting_dir}/{args.arch}' directory.
+arch_std_events = dict()
+# Track whether an events table is currently being defined and needs closing.
+close_table = False
+
+
+def file_name_to_table_name(parents: list[str], dirname: str) -> str:
+  """Generate a C table name from directory names."""
+  tblname = 'pme'
+  for p in parents:
+    tblname += '_' + p
+  tblname += '_' + dirname
+  return tblname.replace('-', '_')
+
+
+class JsonEvent:
+  """Representation of an event loaded from a json file dictionary."""
+
+  def __init__(self, dict):
+    """Constructor passed the dictionary of parsed json values."""
+
+    def llx(x: int) -> str:
+      """Convert an int to a string similar to a printf modifier of %#llx."""
+      return '0' if x == 0 else hex(x)
+
+    def fixdesc(s: str) -> str:
+      """Fix formatting issue for the desc string."""
+      if s is None:
+        return None
+      return s.removesuffix('.  ').removesuffix('. ').removesuffix('.').replace(
+          '\n', '\\n').replace('\"', '\\"').replace('\r', '\\r')
+
+    def convert_aggr_mode(aggr_mode: str) -> str:
+      """Returns the aggr_mode_class enum value associated with the JSON string."""
+      if not aggr_mode:
+        return None
+      aggr_mode_to_enum = {
+          'PerChip': '1',
+          'PerCore': '2',
+      }
+      return aggr_mode_to_enum[aggr_mode]
+
+    def lookup_msr(num: str) -> str:
+      """Converts the msr number, or first in a list to the appropriate event field."""
+      if not num:
+        return None
+      msrmap = {
+          0x3F6: 'ldlat=',
+          0x1A6: 'offcore_rsp=',
+          0x1A7: 'offcore_rsp=',
+          0x3F7: 'frontend=',
+      }
+      return msrmap[int(num.split(',', 1)[0], 0)]
+
+    def real_event(name: str, event: str) -> str:
+      """Convert well known event names to an event string otherwise use the event argument."""
+      fixed = {
+          'inst_retired.any': 'event=0xc0,period=2000003',
+          'inst_retired.any_p': 'event=0xc0,period=2000003',
+          'cpu_clk_unhalted.ref': 'event=0x0,umask=0x03,period=2000003',
+          'cpu_clk_unhalted.thread': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.core': 'event=0x3c,period=2000003',
+          'cpu_clk_unhalted.thread_any': 'event=0x3c,any=1,period=2000003',
+      }
+      if not name:
+        return None
+      if name.lower() in fixed:
+        return fixed[name.lower()]
+      return event
+
+    def unit_to_pmu(unit: str) -> str:
+      """Convert a JSON Unit to Linux PMU name."""
+      if not unit:
+        return None
+      # Comment brought over from jevents.c:
+      # it's not realistic to keep adding these, we need something more scalable ...
+      table = {
+          'CBO': 'uncore_cbox',
+          'QPI LL': 'uncore_qpi',
+          'SBO': 'uncore_sbox',
+          'iMPH-U': 'uncore_arb',
+          'CPU-M-CF': 'cpum_cf',
+          'CPU-M-SF': 'cpum_sf',
+          'UPI LL': 'uncore_upi',
+          'hisi_sicl,cpa': 'hisi_sicl,cpa',
+          'hisi_sccl,ddrc': 'hisi_sccl,ddrc',
+          'hisi_sccl,hha': 'hisi_sccl,hha',
+          'hisi_sccl,l3c': 'hisi_sccl,l3c',
+          'imx8_ddr': 'imx8_ddr',
+          'L3PMC': 'amd_l3',
+          'DFPMC': 'amd_df',
+          'cpu_core': 'cpu_core',
+          'cpu_atom': 'cpu_atom',
+      }
+      return table[unit] if unit in table else f'uncore_{unit.lower()}'
+
+    eventcode = 0
+    if 'EventCode' in dict:
+      eventcode = int(dict['EventCode'].split(',', 1)[0], 0)
+    if 'ExtSel' in dict:
+      eventcode |= int(dict['ExtSel']) << 8
+    configcode = int(dict['ConfigCode'], 0) if 'ConfigCode' in dict else None
+    self.name = dict['EventName'].lower() if 'EventName' in dict else None
+    self.compat = dict.get('Compat')
+    self.desc = fixdesc(dict.get('BriefDescription'))
+    self.long_desc = fixdesc(dict.get('PublicDescription'))
+    precise = dict.get('PEBS')
+    msr = lookup_msr(dict.get('MSRIndex'))
+    msrval = dict.get('MSRValue')
+    extra_desc = ''
+    if 'Data_LA' in dict:
+      extra_desc += '  Supports address when precise'
+      if 'Errata' in dict:
+        extra_desc += '.'
+    if 'Errata' in dict:
+      extra_desc += '  Spec update: ' + dict['Errata']
+    self.pmu = unit_to_pmu(dict.get('Unit'))
+    filter = dict.get('Filter')
+    self.unit = dict.get('ScaleUnit')
+    self.perpkg = dict.get('PerPkg')
+    self.aggr_mode = convert_aggr_mode(dict.get('AggregationMode'))
+    self.deprecated = dict.get('Deprecated')
+    self.metric_name = dict.get('MetricName')
+    self.metric_group = dict.get('MetricGroup')
+    self.metric_constraint = dict.get('MetricConstraint')
+    self.metric_expr = dict.get('MetricExpr')
+    if self.metric_expr:
+      self.metric_expr = self.metric_expr.replace('\\', '\\\\')
+    arch_std = dict.get('ArchStdEvent')
+    if precise and self.desc and not '(Precise Event)' in self.desc:
+      extra_desc += ' (Must be precise)' if precise == '2' else (' (Precise '
+                                                                 'event)')
+    event = f'config={llx(configcode)}' if configcode is not None else f'event={llx(eventcode)}'
+    event_fields = [
+        ('AnyThread', 'any='),
+        ('PortMask', 'ch_mask='),
+        ('CounterMask', 'cmask='),
+        ('EdgeDetect', 'edge='),
+        ('FCMask', 'fc_mask='),
+        ('Invert', 'inv='),
+        ('SampleAfterValue', 'period='),
+        ('UMask', 'umask='),
+    ]
+    for key, value in event_fields:
+      if key in dict and dict[key] != '0':
+        event += ',' + value + dict[key]
+    if filter:
+      event += f',{filter}'
+    if msr:
+      event += f',{msr}{msrval}'
+    if self.desc and extra_desc:
+      self.desc += extra_desc
+    if self.long_desc and extra_desc:
+      self.long_desc += extra_desc
+    if self.pmu:
+      if self.desc and not self.desc.endswith('. '):
+        self.desc += '. '
+      self.desc = (self.desc if self.desc else '') + ('Unit: ' + self.pmu + ' ')
+    if arch_std and arch_std.lower() in arch_std_events:
+      event = arch_std_events[arch_std.lower()].event
+      # Copy from the architecture standard event to self for undefined fields.
+      for attr, value in arch_std_events[arch_std.lower()].__dict__.items():
+        if hasattr(self, attr) and not getattr(self, attr):
+          setattr(self, attr, value)
+
+    self.event = real_event(self.name, event)
+
+  def __repr__(self) -> str:
+    """String representation primarily for debugging."""
+    s = '{\n'
+    for attr, value in self.__dict__.items():
+      if value:
+        s += f'\t{attr} = {value},\n'
+    return s + '}'
+
+  def ToCString(self, topic_local: str) -> str:
+    """Representation of the event as a C struct initializer."""
+
+    def AttrString(attr: str, value: str) -> str:
+      return '\t.%s = \"%s\",\n' % (attr, value)
+
+    def StrIfPresent(self, attr: str) -> str:
+      if not getattr(self, attr):
+        return ''
+      return AttrString(attr, getattr(self, attr))
+
+    s = '{\n'
+    for attr in ['name', 'event']:
+      s += StrIfPresent(self, attr)
+    if self.desc is not None:
+      s += AttrString('desc', self.desc)
+    else:
+      s += AttrString('desc', '(null)')
+    s += StrIfPresent(self, 'compat')
+    s += f'\t.topic = "{topic_local}",\n'
+    for attr in [
+        'long_desc', 'pmu', 'unit', 'perpkg', 'aggr_mode', 'metric_expr',
+        'metric_name', 'metric_group', 'deprecated', 'metric_constraint'
+    ]:
+      s += StrIfPresent(self, attr)
+    s += '},\n'
+    return s
+
+
+def read_json_events(path: str) -> list[JsonEvent]:
+  """Read json events from the specified file."""
+  return json.load(open(path), object_hook=lambda d: JsonEvent(d))
+
+def preprocess_arch_std_files(archpath: str) -> None:
+  """Read in all architecture standard events."""
+  global arch_std_events
+  for item in os.scandir(archpath):
+    if item.is_file() and item.name.endswith('.json'):
+      for event in read_json_events(item.path):
+        if event.name:
+          arch_std_events[event.name.lower()] = event
+
+
+def print_events_table_prefix(tblname: str) -> None:
+  """Called when a new events table is started."""
+  global close_table
+  if close_table:
+    raise IOError('Printing table prefix but last table has no suffix')
+  args.output_file.write('static const struct pmu_event %s[] = {\n' % tblname)
+  close_table = True
+
+
+def print_events_table_entries(item: os.DirEntry, topic: str) -> None:
+  """Create contents of an events table."""
+  if not close_table:
+    raise IOError('Table entries missing prefix')
+  for event in read_json_events(item.path):
+    args.output_file.write(event.ToCString(topic))
+
+def print_events_table_suffix() -> None:
+  """Optionally close events table."""
+  global close_table
+  if close_table:
+    args.output_file.write("""{
+\t.name = 0,
+\t.event = 0,
+\t.desc = 0,
+},
+};
+""")
+  close_table = False
+
+def process_one_file(parents: list[str], item: os.DirEntry) -> None:
+  """Process a JSON file during the main walk."""
+  global sys_event_tables
+
+  def get_topic(topic: str) -> str:
+    return topic.removesuffix('.json').replace('-', ' ')
+
+  def is_leaf_dir(path: str) -> bool:
+    for item in os.scandir(path):
+      if item.is_dir():
+        return False
+    return True
+
+  # model directory, reset topic
+  if item.is_dir() and is_leaf_dir(item.path):
+    print_events_table_suffix()
+
+    tblname = file_name_to_table_name(parents, item.name)
+    if item.name == 'sys':
+      sys_event_tables.append(tblname)
+    print_events_table_prefix(tblname)
+    return
+
+  # base dir or too deep
+  level = len(parents)
+  if level == 0 or level > 4:
+    return
+
+  # Ignore other directories. If the file name does not have a .json
+  # extension, ignore it. It could be a readme.txt for instance.
+  if not item.is_file() or not item.name.endswith('.json'):
+    return
+
+  print_events_table_entries(item, get_topic(item.name))
+
+
+def print_mapping_table() -> None:
+  """Read the mapfile and generate the struct from cpuid string to event table."""
+  table = csv.reader(open(f'{args.starting_dir}/{args.arch}/mapfile.csv'))
+  args.output_file.write('const struct pmu_events_map pmu_events_map[] = {\n')
+  first = True
+  for row in table:
+    # Skip the first row or any row beginning with #.
+    if not first and len(row) > 0 and not row[0].startswith('#'):
+      tblname = file_name_to_table_name([], row[2].replace('/', '_'))
+      args.output_file.write("""{
+\t.cpuid = \"%s\",
+\t.version = \"%s\",
+\t.type = \"%s\",
+\t.table = %s
+},
+""" % (row[0].replace('\\', '\\\\'), row[1], row[3], tblname))
+    first = False
+
+  args.output_file.write("""{
+\t.cpuid = "testcpu",
+\t.version = "v1",
+\t.type = "core",
+\t.table = pme_test_soc_cpu,
+},
+{
+\t.cpuid = 0,
+\t.version = 0,
+\t.type = 0,
+\t.table = 0,
+},
+};
+""")
+
+
+def print_system_mapping_table() -> None:
+  """C struct mapping table array for tables from /sys directories."""
+  args.output_file.write(
+      '\nconst struct pmu_sys_events pmu_sys_event_tables[] = {\n')
+  for tblname in sys_event_tables:
+    args.output_file.write("""\t{
+\t\t.table = %s,
+\t\t.name = \"%s\",
+\t},
+""" % (tblname, tblname))
+  args.output_file.write("""\t{
+\t\t.table = 0
+\t},
+};
+""")
+
+
+def main() -> None:
+  global args
+
+  def dir_path(path: str) -> str:
+    """Validate path is a directory for argparse."""
+    if os.path.isdir(path):
+      return path
+    else:
+      raise argparse.ArgumentTypeError(f'\'{path}\' is not a valid directory')
+
+  def ftw(path: str, parents: list[str],
+          action: Callable[[list[str], os.DirEntry], None]) -> None:
+    """Replicate the directory/file walking behavior of C's file tree walk."""
+    for item in os.scandir(path):
+      action(parents, item)
+      if item.is_dir():
+        ftw(item.path, parents + [item.name], action)
+
+  ap = argparse.ArgumentParser()
+  ap.add_argument('arch', help='Architecture name like x86')
+  ap.add_argument(
+      'starting_dir',
+      type=dir_path,
+      help='Root of tree containing architecture directories containing json files'
+  )
+  ap.add_argument(
+      'output_file', type=argparse.FileType('w'), nargs='?', default=sys.stdout)
+  args = ap.parse_args()
+
+  args.output_file.write("#include \"pmu-events/pmu-events.h\"\n")
+  for path in [args.arch, 'test']:
+    arch_path = f'{args.starting_dir}/{path}'
+    if not os.path.isdir(arch_path):
+      raise IOError(f'Missing architecture directory in \'{arch_path}\'')

tools/perf/pmu-events/jevents.py line 394

Quoted 10 lines
tools/perf/pmu-events/jevents.py new file +10 -0
+    preprocess_arch_std_files(arch_path)
+    ftw(arch_path, [], process_one_file)
+    print_events_table_suffix()
+
+  print_mapping_table()
+  print_system_mapping_table()
+
+
+if __name__ == '__main__':
+  main()

--
Zhengjun Xing

--
Zhengjun Xing

--
Zhengjun Xing

--
Zhengjun Xing

#11 lore raw

Re: [PATCH v5 2/4] perf jevents: Add python converter script

In reply to Ian Rogers
Quoted 6 lines · Ian Rogers
Quoted 4 lines

... libzstd: [ on ]
... disassembler-four-args: [ on ]
... python-dev-is-python3: [ off ]

Agreed on cleaning up the python Makefile logic. I'd rather do it out of these patches.

IMHO I know it's painful to get right but we should have it shouted that python is not properly configured and jevents won't get compiled (properly) - the message "Python interpreter too old (older than 3.6) disabling jevent generation" is too quiet.

Thanks!

author reviewer
#12 lore raw

PATCH v5 3/4 perf jevents: Switch build to use jevents.py

In reply to Ian Rogers

Generate pmu-events.c using jevents.py rather than the binary built from jevents.c. Add a new config variable NO_JEVENTS that is set when there is no architecture json or an appropriate python interpreter isn't present. When NO_JEVENTS is defined the file pmu-events/empty-pmu-events.c is copied and used as the pmu-events.c file.

---
 tools/perf/Makefile.config               | 19 +++++++++++++++++++
 tools/perf/Makefile.perf                 |  1 +
 tools/perf/pmu-events/Build              | 11 +++++++++--
 tools/perf/pmu-events/empty-pmu-events.c | 21 +++++++++++++++++++++
 4 files changed, 50 insertions(+), 2 deletions(-)
 create mode 100644 tools/perf/pmu-events/empty-pmu-events.c
tools/perf/Makefile.config +19 -0
index 16c1a87444b8..153c18909ff5 100644
@@ -889,6 +889,25 @@ else
   endif
 endif
 
+ifneq ($(NO_JEVENTS),1)
+  ifeq ($(wildcard pmu-events/arch/$(SRCARCH)/mapfile.csv),)
+    NO_JEVENTS := 1
+  endif
+endif
+ifneq ($(NO_JEVENTS),1)
+  NO_JEVENTS := 0
+  ifndef PYTHON
+    $(warning No python interpreter disabling jevent generation)
+    NO_JEVENTS := 1
+  else
+    # jevents.py uses f-strings present in Python 3.6 released in Dec. 2016.
+    JEVENTS_PYTHON_GOOD := $(shell $(PYTHON) -c 'import sys;print("1" if(sys.version_info.major >= 3 and sys.version_info.minor >= 6) else "0")' 2> /dev/null)
+    ifneq ($(JEVENTS_PYTHON_GOOD), 1)
+      $(warning Python interpreter too old (older than 3.6) disabling jevent generation)
+      NO_JEVENTS := 1
+    endif
+  endif
+endif
 
 ifndef NO_LIBBFD
   ifeq ($(feature-libbfd), 1)
tools/perf/Makefile.perf +1 -0
index 1e29c8936f71..dc6b177ac1de 100644
@@ -655,6 +655,7 @@ JEVENTS       := $(OUTPUT)pmu-events/jevents
 JEVENTS_IN    := $(OUTPUT)pmu-events/jevents-in.o
 
 PMU_EVENTS_IN := $(OUTPUT)pmu-events/pmu-events-in.o
+export NO_JEVENTS
 
 export JEVENTS
 
tools/perf/pmu-events/Build +9 -2
index a055dee6a46a..5e459e1c7a85 100644
@@ -9,10 +9,17 @@ JSON		=  $(shell [ -d $(JDIR) ] &&				\
 JDIR_TEST	=  pmu-events/arch/test
 JSON_TEST	=  $(shell [ -d $(JDIR_TEST) ] &&			\
 			find $(JDIR_TEST) -name '*.json')
+JEVENTS_PY	=  pmu-events/jevents.py
 
 #
 # Locate/process JSON files in pmu-events/arch/
 # directory and create tables in pmu-events.c.
 #
-$(OUTPUT)pmu-events/pmu-events.c: $(JSON) $(JSON_TEST) $(JEVENTS)
-	$(Q)$(call echo-cmd,gen)$(JEVENTS) $(SRCARCH) pmu-events/arch $(OUTPUT)pmu-events/pmu-events.c $(V)
+
+ifeq ($(NO_JEVENTS),1)
+$(OUTPUT)pmu-events/pmu-events.c: pmu-events/empty-pmu-events.c
+	$(Q)cp $< $@
+else
+$(OUTPUT)pmu-events/pmu-events.c: $(JSON) $(JSON_TEST) $(JEVENTS_PY)
+	$(Q)$(call echo-cmd,gen)$(PYTHON) $(JEVENTS_PY) $(SRCARCH) pmu-events/arch $@
+endif
tools/perf/pmu-events/empty-pmu-events.c new file +21 -0
new file mode 100644
index 000000000000..08fee615e015
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An empty pmu-events.c file used when there is no architecture json files in
+ * arch or when the jevents.py script cannot be run.
+ */
+#include "pmu-events/pmu-events.h"
+
+const struct pmu_events_map pmu_events_map[] = {
+	{
+		.cpuid = 0,
+		.version = 0,
+		.type = 0,
+		.table = 0,
+	},
+};
+
+const struct pmu_sys_events pmu_sys_event_tables[] = {
+	{
+		.table = 0
+	},
+};
Signature · 1 line
2.36.1.476.g0c4daa206d-goog
author reviewer
#13 lore raw

PATCH v5 4/4 perf jevents: Remove jevents.c

In reply to Ian Rogers

Remove files and build rules.
Remove test for comparing with jevents.py as there is no longer a binary to compare with.

---
 tools/perf/Makefile.perf              |   21 +-
 tools/perf/pmu-events/Build           |    4 -
 tools/perf/pmu-events/jevents-test.sh |   33 -
 tools/perf/pmu-events/jevents.c       | 1342 -------------------------
 tools/perf/pmu-events/jsmn.h          |   68 --
 tools/perf/pmu-events/json.c          |  162 ---
 tools/perf/pmu-events/json.h          |   39 -
 7 files changed, 2 insertions(+), 1667 deletions(-)
 delete mode 100755 tools/perf/pmu-events/jevents-test.sh
 delete mode 100644 tools/perf/pmu-events/jevents.c
 delete mode 100644 tools/perf/pmu-events/jsmn.h
 delete mode 100644 tools/perf/pmu-events/json.c
 delete mode 100644 tools/perf/pmu-events/json.h
tools/perf/Makefile.perf +2 -19
index dc6b177ac1de..8f0b1fb39984 100644
@@ -651,32 +651,15 @@ strip: $(PROGRAMS) $(OUTPUT)perf
 
 PERF_IN := $(OUTPUT)perf-in.o
 
-JEVENTS       := $(OUTPUT)pmu-events/jevents
-JEVENTS_IN    := $(OUTPUT)pmu-events/jevents-in.o
-
 PMU_EVENTS_IN := $(OUTPUT)pmu-events/pmu-events-in.o
 export NO_JEVENTS
 
-export JEVENTS
-
 build := -f $(srctree)/tools/build/Makefile.build dir=. obj
 
 $(PERF_IN): prepare FORCE
 	$(Q)$(MAKE) $(build)=perf
 
-$(JEVENTS_IN): FORCE
-	$(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=jevents
-
-$(JEVENTS): $(JEVENTS_IN)
-	$(QUIET_LINK)$(HOSTCC) $(JEVENTS_IN) -o $@
-
-JEVENTS_PY	:=  pmu-events/jevents.py
-JEVENTS_PY_TEST	:=  pmu-events/jevents-test.sh
-.PHONY: jevents-py-test
-jevents-py-test: $(JEVENTS)
-	$(Q)$(call echo-cmd,gen)$(JEVENTS_PY_TEST) $(JEVENTS) $(JEVENTS_PY) pmu-events/arch
-
-$(PMU_EVENTS_IN): $(JEVENTS) FORCE
+$(PMU_EVENTS_IN): FORCE
 	$(Q)$(MAKE) -f $(srctree)/tools/build/Makefile.build dir=pmu-events obj=pmu-events
 
 $(OUTPUT)perf: $(PERFLIBS) $(PERF_IN) $(PMU_EVENTS_IN) $(LIBTRACEEVENT_DYNAMIC_LIST)
@@ -1096,7 +1079,7 @@ clean:: $(LIBTRACEEVENT)-clean $(LIBAPI)-clean $(LIBBPF)-clean $(LIBSUBCMD)-clea
 	$(call QUIET_CLEAN, core-objs)  $(RM) $(LIBPERF_A) $(OUTPUT)perf-archive $(OUTPUT)perf-iostat $(LANG_BINDINGS)
 	$(Q)find $(or $(OUTPUT),.) -name '*.o' -delete -o -name '\.*.cmd' -delete -o -name '\.*.d' -delete
 	$(Q)$(RM) $(OUTPUT).config-detected
-	$(call QUIET_CLEAN, core-progs) $(RM) $(ALL_PROGRAMS) perf perf-read-vdso32 perf-read-vdsox32 $(OUTPUT)pmu-events/jevents $(OUTPUT)$(LIBJVMTI).so
+	$(call QUIET_CLEAN, core-progs) $(RM) $(ALL_PROGRAMS) perf perf-read-vdso32 perf-read-vdsox32 $(OUTPUT)$(LIBJVMTI).so
 	$(call QUIET_CLEAN, core-gen)   $(RM)  *.spec *.pyc *.pyo */*.pyc */*.pyo $(OUTPUT)common-cmds.h TAGS tags cscope* $(OUTPUT)PERF-VERSION-FILE $(OUTPUT)FEATURE-DUMP $(OUTPUT)util/*-bison* $(OUTPUT)util/*-flex* \
 		$(OUTPUT)util/intel-pt-decoder/inat-tables.c \
 		$(OUTPUT)tests/llvm-src-{base,kbuild,prologue,relocation}.c \
tools/perf/pmu-events/Build +0 -4
index 5e459e1c7a85..82e07be354fb 100644
@@ -1,7 +1,3 @@
-hostprogs := jevents
-
-jevents-y	+= json.o jsmn.o jevents.o
-HOSTCFLAGS_jevents.o	= -I$(srctree)/tools/include
 pmu-events-y	+= pmu-events.o
 JDIR		=  pmu-events/arch/$(SRCARCH)
 JSON		=  $(shell [ -d $(JDIR) ] &&				\
tools/perf/pmu-events/jevents-test.sh deleted +0 -33
deleted file mode 100755
index 9ae852292576..000000000000
@@ -1,33 +0,0 @@
-#!/bin/sh
-# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
-# Validate that the legacy jevents and jevents.py produce identical output.
-set -e
-
-JEVENTS="$1"
-JEVENTS_PY="$2"
-ARCH_PATH="$3"
-JEVENTS_C_GENERATED=$(mktemp /tmp/jevents_c.XXXXX.c)
-JEVENTS_PY_GENERATED=$(mktemp /tmp/jevents_py.XXXXX.c)
-
-cleanup() {
-  rm "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
-  trap - exit term int
-}
-trap cleanup exit term int
-
-for path in "$ARCH_PATH"/*
-do
-  arch=$(basename $path)
-  if [ "$arch" = "test" ]
-  then
-    continue
-  fi
-  echo "Checking architecture: $arch"
-  echo "Generating using jevents.c"
-  "$JEVENTS" "$arch" "$ARCH_PATH" "$JEVENTS_C_GENERATED"
-  echo "Generating using jevents.py"
-  "$JEVENTS_PY" "$arch" "$ARCH_PATH" "$JEVENTS_PY_GENERATED"
-  echo "Diffing"
-  diff -u "$JEVENTS_C_GENERATED" "$JEVENTS_PY_GENERATED"
-done
-cleanup
tools/perf/pmu-events/jevents.c deleted +0 -1342

1,342 lines not on this page · raw message

tools/perf/pmu-events/jsmn.h deleted +0 -68

68 lines not on this page · raw message

tools/perf/pmu-events/json.c deleted +0 -162

162 lines not on this page · raw message

tools/perf/pmu-events/json.h deleted +0 -39
deleted file mode 100644
index fbcd5a0590ad..000000000000
@@ -1,39 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0 */
-#ifndef JSON_H
-#define JSON_H 1
-
-#include "jsmn.h"
-
-jsmntok_t *parse_json(const char *fn, char **map, size_t *size, int *len);
-void free_json(char *map, size_t size, jsmntok_t *tokens);
-int json_line(char *map, jsmntok_t *t);
-const char *json_name(jsmntok_t *t);
-int json_streq(char *map, jsmntok_t *t, const char *s);
-int json_len(jsmntok_t *t);
-
-extern int verbose;
-
-#include <stdbool.h>
-
-extern int eprintf(int level, int var, const char *fmt, ...);
-#define pr_fmt(fmt)	fmt
-
-#define pr_err(fmt, ...) \
-	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
-
-#define pr_info(fmt, ...) \
-	eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__)
-
-#define pr_debug(fmt, ...) \
-	eprintf(2, verbose, pr_fmt(fmt), ##__VA_ARGS__)
-
-#ifndef roundup
-#define roundup(x, y) (                                \
-{                                                      \
-        const typeof(y) __y = y;                       \
-        (((x) + (__y - 1)) / __y) * __y;               \
-}                                                      \
-)
-#endif
-
-#endif
Signature · 1 line
2.36.1.476.g0c4daa206d-goog