diff options
Diffstat (limited to '')
97 files changed, 4554 insertions, 979 deletions
diff --git a/tools/perf/tests/Build b/tools/perf/tests/Build index 803ca426f8e6..2064a640facb 100644 --- a/tools/perf/tests/Build +++ b/tools/perf/tests/Build @@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 perf-y += builtin-test.o +perf-y += builtin-test-list.o perf-y += parse-events.o perf-y += dso-data.o perf-y += attr.o @@ -65,6 +66,7 @@ perf-y += pe-file-parsing.o perf-y += expand-cgroup.o perf-y += perf-time-to-tsc.o perf-y += dlfilter-test.o +perf-y += sigtrap.o $(OUTPUT)tests/llvm-src-base.c: tests/bpf-script-example.c tests/Build $(call rule_mkdir) diff --git a/tools/perf/tests/attr.c b/tools/perf/tests/attr.c index 0f73e300f207..56fba08a3037 100644 --- a/tools/perf/tests/attr.c +++ b/tools/perf/tests/attr.c @@ -65,7 +65,7 @@ do { \ #define WRITE_ASS(field, fmt) __WRITE_ASS(field, fmt, attr->field) -static int store_event(struct perf_event_attr *attr, pid_t pid, int cpu, +static int store_event(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu, int fd, int group_fd, unsigned long flags) { FILE *file; @@ -93,7 +93,7 @@ static int store_event(struct perf_event_attr *attr, pid_t pid, int cpu, /* syscall arguments */ __WRITE_ASS(fd, "d", fd); __WRITE_ASS(group_fd, "d", group_fd); - __WRITE_ASS(cpu, "d", cpu); + __WRITE_ASS(cpu, "d", cpu.cpu); __WRITE_ASS(pid, "d", pid); __WRITE_ASS(flags, "lu", flags); @@ -144,7 +144,7 @@ static int store_event(struct perf_event_attr *attr, pid_t pid, int cpu, return 0; } -void test_attr__open(struct perf_event_attr *attr, pid_t pid, int cpu, +void test_attr__open(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu, int fd, int group_fd, unsigned long flags) { int errno_saved = errno; diff --git a/tools/perf/tests/attr/README b/tools/perf/tests/attr/README index a36f49fb4dbe..eb3f7d4bb324 100644 --- a/tools/perf/tests/attr/README +++ b/tools/perf/tests/attr/README @@ -45,8 +45,10 @@ Following tests are defined (with perf commands): perf record -d kill (test-record-data) perf record -F 100 kill (test-record-freq) perf record -g kill (test-record-graph-default) + perf record -g kill (test-record-graph-default-aarch64) perf record --call-graph dwarf kill (test-record-graph-dwarf) perf record --call-graph fp kill (test-record-graph-fp) + perf record --call-graph fp kill (test-record-graph-fp-aarch64) perf record --group -e cycles,instructions kill (test-record-group) perf record -e '{cycles,instructions}' kill (test-record-group1) perf record -e '{cycles/period=1/,instructions/period=2/}:S' kill (test-record-group2) @@ -56,6 +58,9 @@ Following tests are defined (with perf commands): perf record -c 100 -P kill (test-record-period) perf record -c 1 --pfm-events=cycles:period=2 (test-record-pfm-period) perf record -R kill (test-record-raw) + perf record -c 2 -e arm_spe_0// -- kill (test-record-spe-period) + perf record -e arm_spe_0/period=3/ -- kill (test-record-spe-period-term) + perf record -e arm_spe_0/pa_enable=1/ -- kill (test-record-spe-physical-address) perf stat -e cycles kill (test-stat-basic) perf stat kill (test-stat-default) perf stat -d kill (test-stat-detailed-1) diff --git a/tools/perf/tests/attr/base-record b/tools/perf/tests/attr/base-record index 8c10955eff93..3ef07a12aa14 100644 --- a/tools/perf/tests/attr/base-record +++ b/tools/perf/tests/attr/base-record @@ -9,7 +9,7 @@ size=128 config=0 sample_period=* sample_type=263 -read_format=0|4 +read_format=0|4|20 disabled=1 inherit=1 pinned=0 diff --git a/tools/perf/tests/attr/base-record-spe b/tools/perf/tests/attr/base-record-spe new file mode 100644 index 000000000000..08fa96b59240 --- /dev/null +++ b/tools/perf/tests/attr/base-record-spe @@ -0,0 +1,40 @@ +[event] +fd=* +group_fd=-1 +flags=* +cpu=* +type=* +size=* +config=* +sample_period=* +sample_type=* +read_format=* +disabled=* +inherit=* +pinned=* +exclusive=* +exclude_user=* +exclude_kernel=* +exclude_hv=* +exclude_idle=* +mmap=* +comm=* +freq=* +inherit_stat=* +enable_on_exec=* +task=* +watermark=* +precise_ip=* +mmap_data=* +sample_id_all=* +exclude_host=* +exclude_guest=* +exclude_callchain_kernel=* +exclude_callchain_user=* +wakeup_events=* +bp_type=* +config1=* +config2=* +branch_sample_type=* +sample_regs_user=* +sample_stack_user=* diff --git a/tools/perf/tests/attr/system-wide-dummy b/tools/perf/tests/attr/system-wide-dummy index 86a15dd359d9..8fec06eda5f9 100644 --- a/tools/perf/tests/attr/system-wide-dummy +++ b/tools/perf/tests/attr/system-wide-dummy @@ -11,7 +11,7 @@ size=128 config=9 sample_period=4000 sample_type=455 -read_format=4 +read_format=4|20 # Event will be enabled right away. disabled=0 inherit=1 diff --git a/tools/perf/tests/attr/test-record-graph-default b/tools/perf/tests/attr/test-record-graph-default index 5d8234d50845..f0a18b4ea4f5 100644 --- a/tools/perf/tests/attr/test-record-graph-default +++ b/tools/perf/tests/attr/test-record-graph-default @@ -2,6 +2,8 @@ command = record args = --no-bpf-event -g kill >/dev/null 2>&1 ret = 1 +# arm64 enables registers in the default mode (fp) +arch = !aarch64 [event:base-record] sample_type=295 diff --git a/tools/perf/tests/attr/test-record-graph-default-aarch64 b/tools/perf/tests/attr/test-record-graph-default-aarch64 new file mode 100644 index 000000000000..e98d62efb6f7 --- /dev/null +++ b/tools/perf/tests/attr/test-record-graph-default-aarch64 @@ -0,0 +1,9 @@ +[config] +command = record +args = --no-bpf-event -g kill >/dev/null 2>&1 +ret = 1 +arch = aarch64 + +[event:base-record] +sample_type=4391 +sample_regs_user=1073741824 diff --git a/tools/perf/tests/attr/test-record-graph-fp b/tools/perf/tests/attr/test-record-graph-fp index 5630521c0b0f..a6e60e839205 100644 --- a/tools/perf/tests/attr/test-record-graph-fp +++ b/tools/perf/tests/attr/test-record-graph-fp @@ -2,6 +2,8 @@ command = record args = --no-bpf-event --call-graph fp kill >/dev/null 2>&1 ret = 1 +# arm64 enables registers in fp mode +arch = !aarch64 [event:base-record] sample_type=295 diff --git a/tools/perf/tests/attr/test-record-graph-fp-aarch64 b/tools/perf/tests/attr/test-record-graph-fp-aarch64 new file mode 100644 index 000000000000..cbeea9971285 --- /dev/null +++ b/tools/perf/tests/attr/test-record-graph-fp-aarch64 @@ -0,0 +1,9 @@ +[config] +command = record +args = --no-bpf-event --call-graph fp kill >/dev/null 2>&1 +ret = 1 +arch = aarch64 + +[event:base-record] +sample_type=4391 +sample_regs_user=1073741824 diff --git a/tools/perf/tests/attr/test-record-group b/tools/perf/tests/attr/test-record-group index 14ee60fd3f41..6c1cff8aae8b 100644 --- a/tools/perf/tests/attr/test-record-group +++ b/tools/perf/tests/attr/test-record-group @@ -7,14 +7,14 @@ ret = 1 fd=1 group_fd=-1 sample_type=327 -read_format=4 +read_format=4|20 [event-2:base-record] fd=2 group_fd=1 config=1 sample_type=327 -read_format=4 +read_format=4|20 mmap=0 comm=0 task=0 diff --git a/tools/perf/tests/attr/test-record-group-sampling b/tools/perf/tests/attr/test-record-group-sampling index 300b9f7e6d69..97e7e64a38f0 100644 --- a/tools/perf/tests/attr/test-record-group-sampling +++ b/tools/perf/tests/attr/test-record-group-sampling @@ -7,7 +7,7 @@ ret = 1 fd=1 group_fd=-1 sample_type=343 -read_format=12 +read_format=12|28 inherit=0 [event-2:base-record] @@ -21,8 +21,8 @@ config=3 # default | PERF_SAMPLE_READ sample_type=343 -# PERF_FORMAT_ID | PERF_FORMAT_GROUP -read_format=12 +# PERF_FORMAT_ID | PERF_FORMAT_GROUP | PERF_FORMAT_LOST +read_format=12|28 task=0 mmap=0 comm=0 diff --git a/tools/perf/tests/attr/test-record-group1 b/tools/perf/tests/attr/test-record-group1 index 3ffe246e0228..eeb1db392bc9 100644 --- a/tools/perf/tests/attr/test-record-group1 +++ b/tools/perf/tests/attr/test-record-group1 @@ -7,7 +7,7 @@ ret = 1 fd=1 group_fd=-1 sample_type=327 -read_format=4 +read_format=4|20 [event-2:base-record] fd=2 @@ -15,7 +15,7 @@ group_fd=1 type=0 config=1 sample_type=327 -read_format=4 +read_format=4|20 mmap=0 comm=0 task=0 diff --git a/tools/perf/tests/attr/test-record-group2 b/tools/perf/tests/attr/test-record-group2 index 6b9f8d182ce1..cebdaa8e64e4 100644 --- a/tools/perf/tests/attr/test-record-group2 +++ b/tools/perf/tests/attr/test-record-group2 @@ -9,7 +9,7 @@ group_fd=-1 config=0|1 sample_period=1234000 sample_type=87 -read_format=12 +read_format=12|28 inherit=0 freq=0 @@ -19,7 +19,7 @@ group_fd=1 config=0|1 sample_period=6789000 sample_type=87 -read_format=12 +read_format=12|28 disabled=0 inherit=0 mmap=0 diff --git a/tools/perf/tests/attr/test-record-spe-period b/tools/perf/tests/attr/test-record-spe-period new file mode 100644 index 000000000000..75f8c9cd8e3f --- /dev/null +++ b/tools/perf/tests/attr/test-record-spe-period @@ -0,0 +1,12 @@ +[config] +command = record +args = --no-bpf-event -c 2 -e arm_spe_0// -- kill >/dev/null 2>&1 +ret = 1 +arch = aarch64 + +[event-10:base-record-spe] +sample_period=2 +freq=0 + +# dummy event +[event-1:base-record-spe] diff --git a/tools/perf/tests/attr/test-record-spe-period-term b/tools/perf/tests/attr/test-record-spe-period-term new file mode 100644 index 000000000000..8f60a4fec657 --- /dev/null +++ b/tools/perf/tests/attr/test-record-spe-period-term @@ -0,0 +1,12 @@ +[config] +command = record +args = --no-bpf-event -e arm_spe_0/period=3/ -- kill >/dev/null 2>&1 +ret = 1 +arch = aarch64 + +[event-10:base-record-spe] +sample_period=3 +freq=0 + +# dummy event +[event-1:base-record-spe] diff --git a/tools/perf/tests/attr/test-record-spe-physical-address b/tools/perf/tests/attr/test-record-spe-physical-address new file mode 100644 index 000000000000..7ebcf5012ce3 --- /dev/null +++ b/tools/perf/tests/attr/test-record-spe-physical-address @@ -0,0 +1,12 @@ +[config] +command = record +args = --no-bpf-event -e arm_spe_0/pa_enable=1/ -- kill >/dev/null 2>&1 +ret = 1 +arch = aarch64 + +[event-10:base-record-spe] +# 622727 is the decimal of IP|TID|TIME|CPU|IDENTIFIER|DATA_SRC|PHYS_ADDR +sample_type=622727 + +# dummy event +[event-1:base-record-spe]
\ No newline at end of file diff --git a/tools/perf/tests/bitmap.c b/tools/perf/tests/bitmap.c index 384856347236..4965dd666956 100644 --- a/tools/perf/tests/bitmap.c +++ b/tools/perf/tests/bitmap.c @@ -17,8 +17,8 @@ static unsigned long *get_bitmap(const char *str, int nbits) bm = bitmap_zalloc(nbits); if (map && bm) { - for (i = 0; i < map->nr; i++) - set_bit(map->map[i], bm); + for (i = 0; i < perf_cpu_map__nr(map); i++) + set_bit(perf_cpu_map__cpu(map, i).cpu, bm); } if (map) diff --git a/tools/perf/tests/bp_account.c b/tools/perf/tests/bp_account.c index d1ebb5561e5b..6f921db33cf9 100644 --- a/tools/perf/tests/bp_account.c +++ b/tools/perf/tests/bp_account.c @@ -151,11 +151,21 @@ static int detect_ioctl(void) static int detect_share(int wp_cnt, int bp_cnt) { struct perf_event_attr attr; - int i, fd[wp_cnt + bp_cnt], ret; + int i, *fd = NULL, ret = -1; + + if (wp_cnt + bp_cnt == 0) + return 0; + + fd = malloc(sizeof(int) * (wp_cnt + bp_cnt)); + if (!fd) + return -1; for (i = 0; i < wp_cnt; i++) { fd[i] = wp_event((void *)&the_var, &attr); - TEST_ASSERT_VAL("failed to create wp\n", fd[i] != -1); + if (fd[i] == -1) { + pr_err("failed to create wp\n"); + goto out; + } } for (; i < (bp_cnt + wp_cnt); i++) { @@ -166,9 +176,11 @@ static int detect_share(int wp_cnt, int bp_cnt) ret = i != (bp_cnt + wp_cnt); +out: while (i--) close(fd[i]); + free(fd); return ret; } diff --git a/tools/perf/tests/bpf-script-example.c b/tools/perf/tests/bpf-script-example.c index ab4b98b3165d..7981c69ed1b4 100644 --- a/tools/perf/tests/bpf-script-example.c +++ b/tools/perf/tests/bpf-script-example.c @@ -17,20 +17,31 @@ static void *(*bpf_map_lookup_elem)(void *map, void *key) = static void *(*bpf_map_update_elem)(void *map, void *key, void *value, int flags) = (void *) BPF_FUNC_map_update_elem; -struct bpf_map_def { - unsigned int type; - unsigned int key_size; - unsigned int value_size; - unsigned int max_entries; -}; +/* + * Following macros are taken from tools/lib/bpf/bpf_helpers.h, + * and are used to create BTF defined maps. It is easier to take + * 2 simple macros, than being able to include above header in + * runtime. + * + * __uint - defines integer attribute of BTF map definition, + * Such attributes are represented using a pointer to an array, + * in which dimensionality of array encodes specified integer + * value. + * + * __type - defines pointer variable with typeof(val) type for + * attributes like key or value, which will be defined by the + * size of the type. + */ +#define __uint(name, val) int (*name)[val] +#define __type(name, val) typeof(val) *name #define SEC(NAME) __attribute__((section(NAME), used)) -struct bpf_map_def SEC("maps") flip_table = { - .type = BPF_MAP_TYPE_ARRAY, - .key_size = sizeof(int), - .value_size = sizeof(int), - .max_entries = 1, -}; +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, int); + __type(value, int); +} flip_table SEC(".maps"); SEC("func=do_epoll_wait") int bpf_func__SyS_epoll_pwait(void *ctx) diff --git a/tools/perf/tests/bpf.c b/tools/perf/tests/bpf.c index 573490530194..17c023823713 100644 --- a/tools/perf/tests/bpf.c +++ b/tools/perf/tests/bpf.c @@ -222,11 +222,11 @@ static int __test__bpf(int idx) ret = test_llvm__fetch_bpf_obj(&obj_buf, &obj_buf_sz, bpf_testcase_table[idx].prog_id, - true, NULL); + false, NULL); if (ret != TEST_OK || !obj_buf || !obj_buf_sz) { pr_debug("Unable to get BPF object, %s\n", bpf_testcase_table[idx].msg_compile_fail); - if (idx == 0) + if ((idx == 0) || (ret == TEST_SKIP)) return TEST_SKIP; else return TEST_FAIL; @@ -281,8 +281,8 @@ out: static int check_env(void) { + LIBBPF_OPTS(bpf_prog_load_opts, opts); int err; - unsigned int kver_int; char license[] = "GPL"; struct bpf_insn insns[] = { @@ -290,19 +290,13 @@ static int check_env(void) BPF_EXIT_INSN(), }; - err = fetch_kernel_version(&kver_int, NULL, 0); + err = fetch_kernel_version(&opts.kern_version, NULL, 0); if (err) { pr_debug("Unable to get kernel version\n"); return err; } - -/* temporarily disable libbpf deprecation warnings */ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - err = bpf_load_program(BPF_PROG_TYPE_KPROBE, insns, - ARRAY_SIZE(insns), - license, kver_int, NULL, 0); -#pragma GCC diagnostic pop + err = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, license, insns, + ARRAY_SIZE(insns), &opts); if (err < 0) { pr_err("Missing basic BPF support, skip this test: %s\n", strerror(errno)); @@ -370,9 +364,11 @@ static int test__bpf_prologue_test(struct test_suite *test __maybe_unused, static struct test_case bpf_tests[] = { #ifdef HAVE_LIBBPF_SUPPORT TEST_CASE("Basic BPF filtering", basic_bpf_test), - TEST_CASE("BPF pinning", bpf_pinning), + TEST_CASE_REASON("BPF pinning", bpf_pinning, + "clang isn't installed or environment missing BPF support"), #ifdef HAVE_BPF_PROLOGUE - TEST_CASE("BPF prologue generation", bpf_prologue_test), + TEST_CASE_REASON("BPF prologue generation", bpf_prologue_test, + "clang isn't installed or environment missing BPF support"), #else TEST_CASE_REASON("BPF prologue generation", bpf_prologue_test, "not compiled in"), #endif diff --git a/tools/perf/tests/builtin-test-list.c b/tools/perf/tests/builtin-test-list.c new file mode 100644 index 000000000000..a65b9e547d82 --- /dev/null +++ b/tools/perf/tests/builtin-test-list.c @@ -0,0 +1,207 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <linux/ctype.h> +#include <linux/kernel.h> +#include <linux/string.h> +#include <linux/zalloc.h> +#include <string.h> +#include <stdlib.h> +#include <sys/types.h> +#include <unistd.h> +#include <subcmd/exec-cmd.h> +#include <subcmd/parse-options.h> +#include <sys/wait.h> +#include <sys/stat.h> +#include "builtin.h" +#include "builtin-test-list.h" +#include "color.h" +#include "debug.h" +#include "hist.h" +#include "intlist.h" +#include "string2.h" +#include "symbol.h" +#include "tests.h" +#include "util/rlimit.h" + + +/* + * As this is a singleton built once for the run of the process, there is + * no value in trying to free it and just let it stay around until process + * exits when it's cleaned up. + */ +static size_t files_num = 0; +static struct script_file *files = NULL; +static int files_max_width = 0; + +static const char *shell_tests__dir(char *path, size_t size) +{ + const char *devel_dirs[] = { "./tools/perf/tests", "./tests", }; + char *exec_path; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(devel_dirs); ++i) { + struct stat st; + + if (!lstat(devel_dirs[i], &st)) { + scnprintf(path, size, "%s/shell", devel_dirs[i]); + if (!lstat(devel_dirs[i], &st)) + return path; + } + } + + /* Then installed path. */ + exec_path = get_argv_exec_path(); + scnprintf(path, size, "%s/tests/shell", exec_path); + free(exec_path); + return path; +} + +static const char *shell_test__description(char *description, size_t size, + const char *path, const char *name) +{ + FILE *fp; + char filename[PATH_MAX]; + int ch; + + path__join(filename, sizeof(filename), path, name); + fp = fopen(filename, "r"); + if (!fp) + return NULL; + + /* Skip first line - should be #!/bin/sh Shebang */ + do { + ch = fgetc(fp); + } while (ch != EOF && ch != '\n'); + + description = fgets(description, size, fp); + fclose(fp); + + /* Assume first char on line is omment everything after that desc */ + return description ? strim(description + 1) : NULL; +} + +/* Is this full file path a shell script */ +static bool is_shell_script(const char *path) +{ + const char *ext; + + ext = strrchr(path, '.'); + if (!ext) + return false; + if (!strcmp(ext, ".sh")) { /* Has .sh extension */ + if (access(path, R_OK | X_OK) == 0) /* Is executable */ + return true; + } + return false; +} + +/* Is this file in this dir a shell script (for test purposes) */ +static bool is_test_script(const char *path, const char *name) +{ + char filename[PATH_MAX]; + + path__join(filename, sizeof(filename), path, name); + if (!is_shell_script(filename)) return false; + return true; +} + +/* Duplicate a string and fall over and die if we run out of memory */ +static char *strdup_check(const char *str) +{ + char *newstr; + + newstr = strdup(str); + if (!newstr) { + pr_err("Out of memory while duplicating test script string\n"); + abort(); + } + return newstr; +} + +static void append_script(const char *dir, const char *file, const char *desc) +{ + struct script_file *files_tmp; + size_t files_num_tmp; + int width; + + files_num_tmp = files_num + 1; + if (files_num_tmp >= SIZE_MAX) { + pr_err("Too many script files\n"); + abort(); + } + /* Realloc is good enough, though we could realloc by chunks, not that + * anyone will ever measure performance here */ + files_tmp = realloc(files, + (files_num_tmp + 1) * sizeof(struct script_file)); + if (files_tmp == NULL) { + pr_err("Out of memory while building test list\n"); + abort(); + } + /* Add file to end and NULL terminate the struct array */ + files = files_tmp; + files_num = files_num_tmp; + files[files_num - 1].dir = strdup_check(dir); + files[files_num - 1].file = strdup_check(file); + files[files_num - 1].desc = strdup_check(desc); + files[files_num].dir = NULL; + files[files_num].file = NULL; + files[files_num].desc = NULL; + + width = strlen(desc); /* Track max width of desc */ + if (width > files_max_width) + files_max_width = width; +} + +static void append_scripts_in_dir(const char *path) +{ + struct dirent **entlist; + struct dirent *ent; + int n_dirs, i; + char filename[PATH_MAX]; + + /* List files, sorted by alpha */ + n_dirs = scandir(path, &entlist, NULL, alphasort); + if (n_dirs == -1) + return; + for (i = 0; i < n_dirs && (ent = entlist[i]); i++) { + if (ent->d_name[0] == '.') + continue; /* Skip hidden files */ + if (is_test_script(path, ent->d_name)) { /* It's a test */ + char bf[256]; + const char *desc = shell_test__description + (bf, sizeof(bf), path, ent->d_name); + + if (desc) /* It has a desc line - valid script */ + append_script(path, ent->d_name, desc); + } else if (is_directory(path, ent)) { /* Scan the subdir */ + path__join(filename, sizeof(filename), + path, ent->d_name); + append_scripts_in_dir(filename); + } + } + for (i = 0; i < n_dirs; i++) /* Clean up */ + zfree(&entlist[i]); + free(entlist); +} + +const struct script_file *list_script_files(void) +{ + char path_dir[PATH_MAX]; + const char *path; + + if (files) + return files; /* Singleton - we already know our list */ + + path = shell_tests__dir(path_dir, sizeof(path_dir)); /* Walk dir */ + append_scripts_in_dir(path); + + return files; +} + +int list_script_max_width(void) +{ + list_script_files(); /* Ensure we have scanned all scripts */ + return files_max_width; +} diff --git a/tools/perf/tests/builtin-test-list.h b/tools/perf/tests/builtin-test-list.h new file mode 100644 index 000000000000..eb81f3aa6683 --- /dev/null +++ b/tools/perf/tests/builtin-test-list.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +struct script_file { + char *dir; + char *file; + char *desc; +}; + +/* List available script tests to run - singleton - never freed */ +const struct script_file *list_script_files(void); +/* Get maximum width of description string */ +int list_script_max_width(void); diff --git a/tools/perf/tests/builtin-test.c b/tools/perf/tests/builtin-test.c index 8cb5a1c3489e..7122eae1d98d 100644 --- a/tools/perf/tests/builtin-test.c +++ b/tools/perf/tests/builtin-test.c @@ -28,6 +28,8 @@ #include <subcmd/exec-cmd.h> #include <linux/zalloc.h> +#include "builtin-test-list.h" + static bool dont_fork; struct test_suite *__weak arch_tests[] = { @@ -107,6 +109,7 @@ static struct test_suite *generic_tests[] = { &suite__expand_cgroup_events, &suite__perf_time_to_tsc, &suite__dlfilter, + &suite__sigtrap, NULL, }; @@ -136,10 +139,10 @@ static bool has_subtests(const struct test_suite *t) static const char *skip_reason(const struct test_suite *t, int subtest) { - if (t->test_cases && subtest >= 0) - return t->test_cases[subtest].skip_reason; + if (!t->test_cases) + return NULL; - return NULL; + return t->test_cases[subtest >= 0 ? subtest : 0].skip_reason; } static const char *test_description(const struct test_suite *t, int subtest) @@ -273,86 +276,6 @@ static int test_and_print(struct test_suite *t, int subtest) return err; } -static const char *shell_test__description(char *description, size_t size, - const char *path, const char *name) -{ - FILE *fp; - char filename[PATH_MAX]; - - path__join(filename, sizeof(filename), path, name); - fp = fopen(filename, "r"); - if (!fp) - return NULL; - - /* Skip shebang */ - while (fgetc(fp) != '\n'); - - description = fgets(description, size, fp); - fclose(fp); - - return description ? strim(description + 1) : NULL; -} - -#define for_each_shell_test(entlist, nr, base, ent) \ - for (int __i = 0; __i < nr && (ent = entlist[__i]); __i++) \ - if (!is_directory(base, ent) && ent->d_name[0] != '.') - -static const char *shell_tests__dir(char *path, size_t size) -{ - const char *devel_dirs[] = { "./tools/perf/tests", "./tests", }; - char *exec_path; - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(devel_dirs); ++i) { - struct stat st; - if (!lstat(devel_dirs[i], &st)) { - scnprintf(path, size, "%s/shell", devel_dirs[i]); - if (!lstat(devel_dirs[i], &st)) - return path; - } - } - - /* Then installed path. */ - exec_path = get_argv_exec_path(); - scnprintf(path, size, "%s/tests/shell", exec_path); - free(exec_path); - return path; -} - -static int shell_tests__max_desc_width(void) -{ - struct dirent **entlist; - struct dirent *ent; - int n_dirs, e; - char path_dir[PATH_MAX]; - const char *path = shell_tests__dir(path_dir, sizeof(path_dir)); - int width = 0; - - if (path == NULL) - return -1; - - n_dirs = scandir(path, &entlist, NULL, alphasort); - if (n_dirs == -1) - return -1; - - for_each_shell_test(entlist, n_dirs, path, ent) { - char bf[256]; - const char *desc = shell_test__description(bf, sizeof(bf), path, ent->d_name); - - if (desc) { - int len = strlen(desc); - - if (width < len) - width = len; - } - } - - for (e = 0; e < n_dirs; e++) - zfree(&entlist[e]); - free(entlist); - return width; -} - struct shell_test { const char *dir; const char *file; @@ -379,33 +302,17 @@ static int shell_test__run(struct test_suite *test, int subdir __maybe_unused) static int run_shell_tests(int argc, const char *argv[], int i, int width, struct intlist *skiplist) { - struct dirent **entlist; - struct dirent *ent; - int n_dirs, e; - char path_dir[PATH_MAX]; - struct shell_test st = { - .dir = shell_tests__dir(path_dir, sizeof(path_dir)), - }; - - if (st.dir == NULL) - return -1; + struct shell_test st; + const struct script_file *files, *file; - n_dirs = scandir(st.dir, &entlist, NULL, alphasort); - if (n_dirs == -1) { - pr_err("failed to open shell test directory: %s\n", - st.dir); - return -1; - } - - for_each_shell_test(entlist, n_dirs, st.dir, ent) { + files = list_script_files(); + if (!files) + return 0; + for (file = files; file->dir; file++) { int curr = i++; - char desc[256]; struct test_case test_cases[] = { { - .desc = shell_test__description(desc, - sizeof(desc), - st.dir, - ent->d_name), + .desc = file->desc, .run_case = shell_test__run, }, { .name = NULL, } @@ -415,12 +322,14 @@ static int run_shell_tests(int argc, const char *argv[], int i, int width, .test_cases = test_cases, .priv = &st, }; + st.dir = file->dir; - if (!perf_test__matches(test_suite.desc, curr, argc, argv)) + if (test_suite.desc == NULL || + !perf_test__matches(test_suite.desc, curr, argc, argv)) continue; - st.file = ent->d_name; - pr_info("%2d: %-*s:", i, width, test_suite.desc); + st.file = file->file; + pr_info("%3d: %-*s:", i, width, test_suite.desc); if (intlist__find(skiplist, i)) { color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n"); @@ -429,10 +338,6 @@ static int run_shell_tests(int argc, const char *argv[], int i, int width, test_and_print(&test_suite, 0); } - - for (e = 0; e < n_dirs; e++) - zfree(&entlist[e]); - free(entlist); return 0; } @@ -441,7 +346,7 @@ static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist) struct test_suite *t; unsigned int j, k; int i = 0; - int width = shell_tests__max_desc_width(); + int width = list_script_max_width(); for_each_test(j, k, t) { int len = strlen(test_description(t, -1)); @@ -470,7 +375,7 @@ static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist) continue; } - pr_info("%2d: %-*s:", i, width, test_description(t, -1)); + pr_info("%3d: %-*s:", i, width, test_description(t, -1)); if (intlist__find(skiplist, i)) { color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n"); @@ -510,7 +415,7 @@ static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist) curr, argc, argv)) continue; - pr_info("%2d.%1d: %-*s:", i, subi + 1, subw, + pr_info("%3d.%1d: %-*s:", i, subi + 1, subw, test_description(t, subi)); test_and_print(t, subi); } @@ -522,36 +427,22 @@ static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist) static int perf_test__list_shell(int argc, const char **argv, int i) { - struct dirent **entlist; - struct dirent *ent; - int n_dirs, e; - char path_dir[PATH_MAX]; - const char *path = shell_tests__dir(path_dir, sizeof(path_dir)); + const struct script_file *files, *file; - if (path == NULL) - return -1; - - n_dirs = scandir(path, &entlist, NULL, alphasort); - if (n_dirs == -1) - return -1; - - for_each_shell_test(entlist, n_dirs, path, ent) { + files = list_script_files(); + if (!files) + return 0; + for (file = files; file->dir; file++) { int curr = i++; - char bf[256]; struct test_suite t = { - .desc = shell_test__description(bf, sizeof(bf), path, ent->d_name), + .desc = file->desc }; if (!perf_test__matches(t.desc, curr, argc, argv)) continue; - pr_info("%2d: %s\n", i, t.desc); - + pr_info("%3d: %s\n", i, t.desc); } - - for (e = 0; e < n_dirs; e++) - zfree(&entlist[e]); - free(entlist); return 0; } @@ -567,14 +458,14 @@ static int perf_test__list(int argc, const char **argv) if (!perf_test__matches(test_description(t, -1), curr, argc, argv)) continue; - pr_info("%2d: %s\n", i, test_description(t, -1)); + pr_info("%3d: %s\n", i, test_description(t, -1)); if (has_subtests(t)) { int subn = num_subtests(t); int subi; for (subi = 0; subi < subn; subi++) - pr_info("%2d:%1d: %s\n", i, subi + 1, + pr_info("%3d:%1d: %s\n", i, subi + 1, test_description(t, subi)); } } @@ -606,6 +497,9 @@ int cmd_test(int argc, const char **argv) if (ret < 0) return ret; + /* Unbuffered output */ + setvbuf(stdout, NULL, _IONBF, 0); + argc = parse_options_subcommand(argc, argv, test_options, test_subcommands, test_usage, 0); if (argc >= 1 && !strcmp(argv[0], "list")) return perf_test__list(argc - 1, argv + 1); diff --git a/tools/perf/tests/code-reading.c b/tools/perf/tests/code-reading.c index 5610767b407f..95feb6ef34a0 100644 --- a/tools/perf/tests/code-reading.c +++ b/tools/perf/tests/code-reading.c @@ -638,7 +638,7 @@ static int do_test_code_reading(bool try_kcore) str = do_determine_event(excl_kernel); pr_debug("Parsing event '%s'\n", str); - ret = parse_events(evlist, str, NULL); + ret = parse_event(evlist, str); if (ret < 0) { pr_debug("parse_events failed\n"); goto out_put; diff --git a/tools/perf/tests/cpumap.c b/tools/perf/tests/cpumap.c index 89a155092f85..7c873c6ae3eb 100644 --- a/tools/perf/tests/cpumap.c +++ b/tools/perf/tests/cpumap.c @@ -17,29 +17,31 @@ static int process_event_mask(struct perf_tool *tool __maybe_unused, struct machine *machine __maybe_unused) { struct perf_record_cpu_map *map_event = &event->cpu_map; - struct perf_record_record_cpu_map *mask; struct perf_record_cpu_map_data *data; struct perf_cpu_map *map; - int i; + unsigned int long_size; data = &map_event->data; TEST_ASSERT_VAL("wrong type", data->type == PERF_CPU_MAP__MASK); - mask = (struct perf_record_record_cpu_map *)data->data; + long_size = data->mask32_data.long_size; - TEST_ASSERT_VAL("wrong nr", mask->nr == 1); + TEST_ASSERT_VAL("wrong long_size", long_size == 4 || long_size == 8); - for (i = 0; i < 20; i++) { - TEST_ASSERT_VAL("wrong cpu", test_bit(i, mask->mask)); - } + TEST_ASSERT_VAL("wrong nr", data->mask32_data.nr == 1); + + TEST_ASSERT_VAL("wrong cpu", perf_record_cpu_map_data__test_bit(0, data)); + TEST_ASSERT_VAL("wrong cpu", !perf_record_cpu_map_data__test_bit(1, data)); + for (int i = 2; i <= 20; i++) + TEST_ASSERT_VAL("wrong cpu", perf_record_cpu_map_data__test_bit(i, data)); map = cpu_map__new_data(data); - TEST_ASSERT_VAL("wrong nr", map->nr == 20); + TEST_ASSERT_VAL("wrong nr", perf_cpu_map__nr(map) == 20); - for (i = 0; i < 20; i++) { - TEST_ASSERT_VAL("wrong cpu", map->map[i] == i); - } + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__cpu(map, 0).cpu == 0); + for (int i = 2; i <= 20; i++) + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__cpu(map, i - 1).cpu == i); perf_cpu_map__put(map); return 0; @@ -51,7 +53,6 @@ static int process_event_cpus(struct perf_tool *tool __maybe_unused, struct machine *machine __maybe_unused) { struct perf_record_cpu_map *map_event = &event->cpu_map; - struct cpu_map_entries *cpus; struct perf_record_cpu_map_data *data; struct perf_cpu_map *map; @@ -59,16 +60,40 @@ static int process_event_cpus(struct perf_tool *tool __maybe_unused, TEST_ASSERT_VAL("wrong type", data->type == PERF_CPU_MAP__CPUS); - cpus = (struct cpu_map_entries *)data->data; + TEST_ASSERT_VAL("wrong nr", data->cpus_data.nr == 2); + TEST_ASSERT_VAL("wrong cpu", data->cpus_data.cpu[0] == 1); + TEST_ASSERT_VAL("wrong cpu", data->cpus_data.cpu[1] == 256); + + map = cpu_map__new_data(data); + TEST_ASSERT_VAL("wrong nr", perf_cpu_map__nr(map) == 2); + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__cpu(map, 0).cpu == 1); + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__cpu(map, 1).cpu == 256); + TEST_ASSERT_VAL("wrong refcnt", refcount_read(&map->refcnt) == 1); + perf_cpu_map__put(map); + return 0; +} + +static int process_event_range_cpus(struct perf_tool *tool __maybe_unused, + union perf_event *event, + struct perf_sample *sample __maybe_unused, + struct machine *machine __maybe_unused) +{ + struct perf_record_cpu_map *map_event = &event->cpu_map; + struct perf_record_cpu_map_data *data; + struct perf_cpu_map *map; + + data = &map_event->data; + + TEST_ASSERT_VAL("wrong type", data->type == PERF_CPU_MAP__RANGE_CPUS); - TEST_ASSERT_VAL("wrong nr", cpus->nr == 2); - TEST_ASSERT_VAL("wrong cpu", cpus->cpu[0] == 1); - TEST_ASSERT_VAL("wrong cpu", cpus->cpu[1] == 256); + TEST_ASSERT_VAL("wrong any_cpu", data->range_cpu_data.any_cpu == 0); + TEST_ASSERT_VAL("wrong start_cpu", data->range_cpu_data.start_cpu == 1); + TEST_ASSERT_VAL("wrong end_cpu", data->range_cpu_data.end_cpu == 256); map = cpu_map__new_data(data); - TEST_ASSERT_VAL("wrong nr", map->nr == 2); - TEST_ASSERT_VAL("wrong cpu", map->map[0] == 1); - TEST_ASSERT_VAL("wrong cpu", map->map[1] == 256); + TEST_ASSERT_VAL("wrong nr", perf_cpu_map__nr(map) == 256); + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__cpu(map, 0).cpu == 1); + TEST_ASSERT_VAL("wrong cpu", perf_cpu_map__max(map).cpu == 256); TEST_ASSERT_VAL("wrong refcnt", refcount_read(&map->refcnt) == 1); perf_cpu_map__put(map); return 0; @@ -79,21 +104,29 @@ static int test__cpu_map_synthesize(struct test_suite *test __maybe_unused, int { struct perf_cpu_map *cpus; - /* This one is better stores in mask. */ - cpus = perf_cpu_map__new("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19"); + /* This one is better stored in a mask. */ + cpus = perf_cpu_map__new("0,2-20"); TEST_ASSERT_VAL("failed to synthesize map", !perf_event__synthesize_cpu_map(NULL, cpus, process_event_mask, NULL)); perf_cpu_map__put(cpus); - /* This one is better stores in cpu values. */ + /* This one is better stored in cpu values. */ cpus = perf_cpu_map__new("1,256"); TEST_ASSERT_VAL("failed to synthesize map", !perf_event__synthesize_cpu_map(NULL, cpus, process_event_cpus, NULL)); perf_cpu_map__put(cpus); + + /* This one is better stored as a range. */ + cpus = perf_cpu_map__new("1-256"); + + TEST_ASSERT_VAL("failed to synthesize map", + !perf_event__synthesize_cpu_map(NULL, cpus, process_event_range_cpus, NULL)); + + perf_cpu_map__put(cpus); return 0; } @@ -130,7 +163,7 @@ static int test__cpu_map_merge(struct test_suite *test __maybe_unused, int subte struct perf_cpu_map *c = perf_cpu_map__merge(a, b); char buf[100]; - TEST_ASSERT_VAL("failed to merge map: bad nr", c->nr == 5); + TEST_ASSERT_VAL("failed to merge map: bad nr", perf_cpu_map__nr(c) == 5); cpu_map__snprint(c, buf, sizeof(buf)); TEST_ASSERT_VAL("failed to merge map: bad result", !strcmp(buf, "1-2,4-5,7")); perf_cpu_map__put(b); diff --git a/tools/perf/tests/dwarf-unwind.c b/tools/perf/tests/dwarf-unwind.c index 2dab2d262060..afdca7f2959f 100644 --- a/tools/perf/tests/dwarf-unwind.c +++ b/tools/perf/tests/dwarf-unwind.c @@ -122,7 +122,7 @@ NO_TAIL_CALL_ATTRIBUTE noinline int test_dwarf_unwind__thread(struct thread *thr } err = unwind__get_entries(unwind_entry, &cnt, thread, - &sample, MAX_STACK); + &sample, MAX_STACK, false); if (err) pr_debug("unwind failed\n"); else if (cnt != MAX_STACK) { diff --git a/tools/perf/tests/event-times.c b/tools/perf/tests/event-times.c index 7606eb3df92f..e155f0e0e04d 100644 --- a/tools/perf/tests/event-times.c +++ b/tools/perf/tests/event-times.c @@ -174,7 +174,7 @@ static int test_times(int (attach)(struct evlist *), goto out_err; } - err = parse_events(evlist, "cpu-clock:u", NULL); + err = parse_event(evlist, "cpu-clock:u"); if (err) { pr_debug("failed to parse event cpu-clock:u\n"); goto out_err; diff --git a/tools/perf/tests/event_update.c b/tools/perf/tests/event_update.c index d01532d40acb..d093a9b878d1 100644 --- a/tools/perf/tests/event_update.c +++ b/tools/perf/tests/event_update.c @@ -21,7 +21,7 @@ static int process_event_unit(struct perf_tool *tool __maybe_unused, TEST_ASSERT_VAL("wrong id", ev->id == 123); TEST_ASSERT_VAL("wrong id", ev->type == PERF_EVENT_UPDATE__UNIT); - TEST_ASSERT_VAL("wrong unit", !strcmp(ev->data, "KRAVA")); + TEST_ASSERT_VAL("wrong unit", !strcmp(ev->unit, "KRAVA")); return 0; } @@ -31,13 +31,10 @@ static int process_event_scale(struct perf_tool *tool __maybe_unused, struct machine *machine __maybe_unused) { struct perf_record_event_update *ev = (struct perf_record_event_update *)event; - struct perf_record_event_update_scale *ev_data; - - ev_data = (struct perf_record_event_update_scale *)ev->data; TEST_ASSERT_VAL("wrong id", ev->id == 123); TEST_ASSERT_VAL("wrong id", ev->type == PERF_EVENT_UPDATE__SCALE); - TEST_ASSERT_VAL("wrong scale", ev_data->scale == 0.123); + TEST_ASSERT_VAL("wrong scale", ev->scale.scale == 0.123); return 0; } @@ -56,7 +53,7 @@ static int process_event_name(struct perf_tool *tool, TEST_ASSERT_VAL("wrong id", ev->id == 123); TEST_ASSERT_VAL("wrong id", ev->type == PERF_EVENT_UPDATE__NAME); - TEST_ASSERT_VAL("wrong name", !strcmp(ev->data, tmp->name)); + TEST_ASSERT_VAL("wrong name", !strcmp(ev->name, tmp->name)); return 0; } @@ -66,19 +63,16 @@ static int process_event_cpus(struct perf_tool *tool __maybe_unused, struct machine *machine __maybe_unused) { struct perf_record_event_update *ev = (struct perf_record_event_update *)event; - struct perf_record_event_update_cpus *ev_data; struct perf_cpu_map *map; - ev_data = (struct perf_record_event_update_cpus *) ev->data; - - map = cpu_map__new_data(&ev_data->cpus); + map = cpu_map__new_data(&ev->cpus.cpus); TEST_ASSERT_VAL("wrong id", ev->id == 123); TEST_ASSERT_VAL("wrong type", ev->type == PERF_EVENT_UPDATE__CPUS); - TEST_ASSERT_VAL("wrong cpus", map->nr == 3); - TEST_ASSERT_VAL("wrong cpus", map->map[0] == 1); - TEST_ASSERT_VAL("wrong cpus", map->map[1] == 2); - TEST_ASSERT_VAL("wrong cpus", map->map[2] == 3); + TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__nr(map) == 3); + TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 0).cpu == 1); + TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 1).cpu == 2); + TEST_ASSERT_VAL("wrong cpus", perf_cpu_map__cpu(map, 2).cpu == 3); perf_cpu_map__put(map); return 0; } diff --git a/tools/perf/tests/evsel-roundtrip-name.c b/tools/perf/tests/evsel-roundtrip-name.c index fdbf17642e45..e94fed901992 100644 --- a/tools/perf/tests/evsel-roundtrip-name.c +++ b/tools/perf/tests/evsel-roundtrip-name.c @@ -27,7 +27,7 @@ static int perf_evsel__roundtrip_cache_name_test(void) for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) { __evsel__hw_cache_type_op_res_name(type, op, i, name, sizeof(name)); - err = parse_events(evlist, name, NULL); + err = parse_event(evlist, name); if (err) ret = err; } @@ -64,7 +64,7 @@ static int perf_evsel__roundtrip_cache_name_test(void) return ret; } -static int __perf_evsel__name_array_test(const char *names[], int nr_names, +static int __perf_evsel__name_array_test(const char *const names[], int nr_names, int distance) { int i, err; @@ -75,7 +75,7 @@ static int __perf_evsel__name_array_test(const char *names[], int nr_names, return -ENOMEM; for (i = 0; i < nr_names; ++i) { - err = parse_events(evlist, names[i], NULL); + err = parse_event(evlist, names[i]); if (err) { pr_debug("failed to parse event '%s', err %d\n", names[i], err); diff --git a/tools/perf/tests/expand-cgroup.c b/tools/perf/tests/expand-cgroup.c index dfefe5b60eb2..51fb5f34c1dd 100644 --- a/tools/perf/tests/expand-cgroup.c +++ b/tools/perf/tests/expand-cgroup.c @@ -180,33 +180,14 @@ static int expand_metric_events(void) struct evlist *evlist; struct rblist metric_events; const char metric_str[] = "CPI"; - - struct pmu_event pme_test[] = { - { - .metric_expr = "instructions / cycles", - .metric_name = "IPC", - }, - { - .metric_expr = "1 / IPC", - .metric_name = "CPI", - }, - { - .metric_expr = NULL, - .metric_name = NULL, - }, - }; - const struct pmu_events_map ev_map = { - .cpuid = "test", - .version = "1", - .type = "core", - .table = pme_test, - }; + const struct pmu_events_table *pme_test; evlist = evlist__new(); TEST_ASSERT_VAL("failed to get evlist", evlist); rblist__init(&metric_events); - ret = metricgroup__parse_groups_test(evlist, &ev_map, metric_str, + pme_test = find_core_events_table("testarch", "testcpu"); + ret = metricgroup__parse_groups_test(evlist, pme_test, metric_str, false, false, &metric_events); if (ret < 0) { pr_debug("failed to parse '%s' metric\n", metric_str); diff --git a/tools/perf/tests/expr.c b/tools/perf/tests/expr.c index d54c5371c6a6..6512f5e22045 100644 --- a/tools/perf/tests/expr.c +++ b/tools/perf/tests/expr.c @@ -1,8 +1,11 @@ // SPDX-License-Identifier: GPL-2.0 +#include "util/cputopo.h" #include "util/debug.h" #include "util/expr.h" +#include "util/header.h" #include "util/smt.h" #include "tests.h" +#include <math.h> #include <stdlib.h> #include <string.h> #include <linux/zalloc.h> @@ -69,6 +72,11 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u double val, num_cpus, num_cores, num_dies, num_packages; int ret; struct expr_parse_ctx *ctx; + bool is_intel = false; + char buf[128]; + + if (!get_cpuid(buf, sizeof(buf))) + is_intel = strstr(buf, "Intel") != NULL; TEST_ASSERT_EQUAL("ids_union", test_ids_union(), 0); @@ -87,6 +95,10 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u ret |= test(ctx, "min(1,2) + 1", 2); ret |= test(ctx, "max(1,2) + 1", 3); ret |= test(ctx, "1+1 if 3*4 else 0", 2); + ret |= test(ctx, "100 if 1 else 200 if 1 else 300", 100); + ret |= test(ctx, "100 if 0 else 200 if 1 else 300", 200); + ret |= test(ctx, "100 if 1 else 200 if 0 else 300", 100); + ret |= test(ctx, "100 if 0 else 200 if 0 else 300", 300); ret |= test(ctx, "1.1 + 2.1", 3.2); ret |= test(ctx, ".1 + 2.", 2.1); ret |= test(ctx, "d_ratio(1, 2)", 0.5); @@ -97,6 +109,8 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u ret |= test(ctx, "2.2 > 2.2", 0); ret |= test(ctx, "2.2 < 1.1", 0); ret |= test(ctx, "1.1 > 2.2", 0); + ret |= test(ctx, "1.1e10 < 1.1e100", 1); + ret |= test(ctx, "1.1e2 > 1.1e-2", 1); if (ret) { expr__ctx_free(ctx); @@ -124,7 +138,7 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u (void **)&val_ptr)); expr__ctx_clear(ctx); - ctx->runtime = 3; + ctx->sctx.runtime = 3; TEST_ASSERT_VAL("find ids", expr__find_ids("EVENT1\\,param\\=?@ + EVENT2\\,param\\=?@", NULL, ctx) == 0); @@ -145,15 +159,33 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u (void **)&val_ptr)); /* Only EVENT1 or EVENT2 need be measured depending on the value of smt_on. */ - expr__ctx_clear(ctx); - TEST_ASSERT_VAL("find ids", - expr__find_ids("EVENT1 if #smt_on else EVENT2", - NULL, ctx) == 0); - TEST_ASSERT_VAL("find ids", hashmap__size(ctx->ids) == 1); - TEST_ASSERT_VAL("find ids", hashmap__find(ctx->ids, - smt_on() ? "EVENT1" : "EVENT2", - (void **)&val_ptr)); + { + struct cpu_topology *topology = cpu_topology__new(); + bool smton = smt_on(topology); + bool corewide = core_wide(/*system_wide=*/false, + /*user_requested_cpus=*/false, + topology); + + cpu_topology__delete(topology); + expr__ctx_clear(ctx); + TEST_ASSERT_VAL("find ids", + expr__find_ids("EVENT1 if #smt_on else EVENT2", + NULL, ctx) == 0); + TEST_ASSERT_VAL("find ids", hashmap__size(ctx->ids) == 1); + TEST_ASSERT_VAL("find ids", hashmap__find(ctx->ids, + smton ? "EVENT1" : "EVENT2", + (void **)&val_ptr)); + + expr__ctx_clear(ctx); + TEST_ASSERT_VAL("find ids", + expr__find_ids("EVENT1 if #core_wide else EVENT2", + NULL, ctx) == 0); + TEST_ASSERT_VAL("find ids", hashmap__size(ctx->ids) == 1); + TEST_ASSERT_VAL("find ids", hashmap__find(ctx->ids, + corewide ? "EVENT1" : "EVENT2", + (void **)&val_ptr)); + } /* The expression is a constant 1.0 without needing to evaluate EVENT1. */ expr__ctx_clear(ctx); TEST_ASSERT_VAL("find ids", @@ -173,6 +205,12 @@ static int test__expr(struct test_suite *t __maybe_unused, int subtest __maybe_u if (num_dies) // Some platforms do not have CPU die support, for example s390 TEST_ASSERT_VAL("#num_dies >= #num_packages", num_dies >= num_packages); + TEST_ASSERT_VAL("#system_tsc_freq", expr__parse(&val, ctx, "#system_tsc_freq") == 0); + if (is_intel) + TEST_ASSERT_VAL("#system_tsc_freq > 0", val > 0); + else + TEST_ASSERT_VAL("#system_tsc_freq == 0", fpclassify(val) == FP_ZERO); + /* * Source count returns the number of events aggregating in a leader * event including the leader. Check parsing yields an id. diff --git a/tools/perf/tests/hists_cumulate.c b/tools/perf/tests/hists_cumulate.c index 17f4fcd6bdce..b42d37ff2399 100644 --- a/tools/perf/tests/hists_cumulate.c +++ b/tools/perf/tests/hists_cumulate.c @@ -706,7 +706,7 @@ static int test__hists_cumulate(struct test_suite *test __maybe_unused, int subt TEST_ASSERT_VAL("No memory", evlist); - err = parse_events(evlist, "cpu-clock", NULL); + err = parse_event(evlist, "cpu-clock"); if (err) goto out; err = TEST_FAIL; diff --git a/tools/perf/tests/hists_filter.c b/tools/perf/tests/hists_filter.c index 08cbeb9e39ae..8e1ceeb9b7b6 100644 --- a/tools/perf/tests/hists_filter.c +++ b/tools/perf/tests/hists_filter.c @@ -111,10 +111,10 @@ static int test__hists_filter(struct test_suite *test __maybe_unused, int subtes TEST_ASSERT_VAL("No memory", evlist); - err = parse_events(evlist, "cpu-clock", NULL); + err = parse_event(evlist, "cpu-clock"); if (err) goto out; - err = parse_events(evlist, "task-clock", NULL); + err = parse_event(evlist, "task-clock"); if (err) goto out; err = TEST_FAIL; diff --git a/tools/perf/tests/hists_link.c b/tools/perf/tests/hists_link.c index c575e13a850d..14b2ff808b5e 100644 --- a/tools/perf/tests/hists_link.c +++ b/tools/perf/tests/hists_link.c @@ -276,10 +276,10 @@ static int test__hists_link(struct test_suite *test __maybe_unused, int subtest if (evlist == NULL) return -ENOMEM; - err = parse_events(evlist, "cpu-clock", NULL); + err = parse_event(evlist, "cpu-clock"); if (err) goto out; - err = parse_events(evlist, "task-clock", NULL); + err = parse_event(evlist, "task-clock"); if (err) goto out; diff --git a/tools/perf/tests/hists_output.c b/tools/perf/tests/hists_output.c index 0bde4a768c15..62b0093253e3 100644 --- a/tools/perf/tests/hists_output.c +++ b/tools/perf/tests/hists_output.c @@ -593,7 +593,7 @@ static int test__hists_output(struct test_suite *test __maybe_unused, int subtes TEST_ASSERT_VAL("No memory", evlist); - err = parse_events(evlist, "cpu-clock", NULL); + err = parse_event(evlist, "cpu-clock"); if (err) goto out; err = TEST_FAIL; diff --git a/tools/perf/tests/keep-tracking.c b/tools/perf/tests/keep-tracking.c index dd2067312452..8f4f9b632e1e 100644 --- a/tools/perf/tests/keep-tracking.c +++ b/tools/perf/tests/keep-tracking.c @@ -89,8 +89,8 @@ static int test__keep_tracking(struct test_suite *test __maybe_unused, int subte perf_evlist__set_maps(&evlist->core, cpus, threads); - CHECK__(parse_events(evlist, "dummy:u", NULL)); - CHECK__(parse_events(evlist, "cycles:u", NULL)); + CHECK__(parse_event(evlist, "dummy:u")); + CHECK__(parse_event(evlist, "cycles:u")); evlist__config(evlist, &opts, NULL); diff --git a/tools/perf/tests/llvm.c b/tools/perf/tests/llvm.c index 8ac0a3a457ef..0bc25a56cfef 100644 --- a/tools/perf/tests/llvm.c +++ b/tools/perf/tests/llvm.c @@ -13,7 +13,7 @@ static int test__bpf_parsing(void *obj_buf, size_t obj_buf_sz) { struct bpf_object *obj; - obj = bpf_object__open_buffer(obj_buf, obj_buf_sz, NULL); + obj = bpf_object__open_mem(obj_buf, obj_buf_sz, NULL); if (libbpf_get_error(obj)) return TEST_FAIL; bpf_object__close(obj); diff --git a/tools/perf/tests/maps.c b/tools/perf/tests/maps.c index e308a3296cef..a69988a89d26 100644 --- a/tools/perf/tests/maps.c +++ b/tools/perf/tests/maps.c @@ -35,7 +35,6 @@ static int check_maps(struct map_def *merged, unsigned int size, struct maps *ma static int test__maps__merge_in(struct test_suite *t __maybe_unused, int subtest __maybe_unused) { - struct maps maps; unsigned int i; struct map_def bpf_progs[] = { { "bpf_prog_1", 200, 300 }, @@ -63,8 +62,9 @@ static int test__maps__merge_in(struct test_suite *t __maybe_unused, int subtest }; struct map *map_kcore1, *map_kcore2, *map_kcore3; int ret; + struct maps *maps = maps__new(NULL); - maps__init(&maps, NULL); + TEST_ASSERT_VAL("failed to create maps", maps); for (i = 0; i < ARRAY_SIZE(bpf_progs); i++) { struct map *map; @@ -74,7 +74,7 @@ static int test__maps__merge_in(struct test_suite *t __maybe_unused, int subtest map->start = bpf_progs[i].start; map->end = bpf_progs[i].end; - maps__insert(&maps, map); + maps__insert(maps, map); map__put(map); } @@ -99,25 +99,25 @@ static int test__maps__merge_in(struct test_suite *t __maybe_unused, int subtest map_kcore3->start = 880; map_kcore3->end = 1100; - ret = maps__merge_in(&maps, map_kcore1); + ret = maps__merge_in(maps, map_kcore1); TEST_ASSERT_VAL("failed to merge map", !ret); - ret = check_maps(merged12, ARRAY_SIZE(merged12), &maps); + ret = check_maps(merged12, ARRAY_SIZE(merged12), maps); TEST_ASSERT_VAL("merge check failed", !ret); - ret = maps__merge_in(&maps, map_kcore2); + ret = maps__merge_in(maps, map_kcore2); TEST_ASSERT_VAL("failed to merge map", !ret); - ret = check_maps(merged12, ARRAY_SIZE(merged12), &maps); + ret = check_maps(merged12, ARRAY_SIZE(merged12), maps); TEST_ASSERT_VAL("merge check failed", !ret); - ret = maps__merge_in(&maps, map_kcore3); + ret = maps__merge_in(maps, map_kcore3); TEST_ASSERT_VAL("failed to merge map", !ret); - ret = check_maps(merged3, ARRAY_SIZE(merged3), &maps); + ret = check_maps(merged3, ARRAY_SIZE(merged3), maps); TEST_ASSERT_VAL("merge check failed", !ret); - maps__exit(&maps); + maps__delete(maps); return TEST_OK; } diff --git a/tools/perf/tests/mem2node.c b/tools/perf/tests/mem2node.c index b17b86391383..4c96829510c9 100644 --- a/tools/perf/tests/mem2node.c +++ b/tools/perf/tests/mem2node.c @@ -25,14 +25,15 @@ static unsigned long *get_bitmap(const char *str, int nbits) { struct perf_cpu_map *map = perf_cpu_map__new(str); unsigned long *bm = NULL; - int i; bm = bitmap_zalloc(nbits); if (map && bm) { - for (i = 0; i < map->nr; i++) { - set_bit(map->map[i], bm); - } + struct perf_cpu cpu; + int i; + + perf_cpu_map__for_each_cpu(cpu, i, map) + set_bit(cpu.cpu, bm); } if (map) diff --git a/tools/perf/tests/mmap-basic.c b/tools/perf/tests/mmap-basic.c index 90b2feda31ac..8322fc2295fa 100644 --- a/tools/perf/tests/mmap-basic.c +++ b/tools/perf/tests/mmap-basic.c @@ -1,8 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 #include <errno.h> #include <inttypes.h> -/* For the CLR_() macros */ -#include <pthread.h> #include <stdlib.h> #include <perf/cpumap.h> @@ -31,7 +29,7 @@ */ static int test__basic_mmap(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - int err = -1; + int err = TEST_FAIL; union perf_event *event; struct perf_thread_map *threads; struct perf_cpu_map *cpus; @@ -59,11 +57,12 @@ static int test__basic_mmap(struct test_suite *test __maybe_unused, int subtest } CPU_ZERO(&cpu_set); - CPU_SET(cpus->map[0], &cpu_set); + CPU_SET(perf_cpu_map__cpu(cpus, 0).cpu, &cpu_set); sched_setaffinity(0, sizeof(cpu_set), &cpu_set); if (sched_setaffinity(0, sizeof(cpu_set), &cpu_set) < 0) { pr_debug("sched_setaffinity() failed on CPU %d: %s ", - cpus->map[0], str_error_r(errno, sbuf, sizeof(sbuf))); + perf_cpu_map__cpu(cpus, 0).cpu, + str_error_r(errno, sbuf, sizeof(sbuf))); goto out_free_cpus; } @@ -82,6 +81,10 @@ static int test__basic_mmap(struct test_suite *test __maybe_unused, int subtest evsels[i] = evsel__newtp("syscalls", name); if (IS_ERR(evsels[i])) { pr_debug("evsel__new(%s)\n", name); + if (PTR_ERR(evsels[i]) == -EACCES) { + /* Permissions failure, flag the failure as a skip. */ + err = TEST_SKIP; + } goto out_delete_evlist; } @@ -109,8 +112,7 @@ static int test__basic_mmap(struct test_suite *test __maybe_unused, int subtest for (i = 0; i < nsyscalls; ++i) for (j = 0; j < expected_nr_events[i]; ++j) { - int foo = syscalls[i](); - ++foo; + syscalls[i](); } md = &evlist->mmap[0]; @@ -165,4 +167,139 @@ out_free_threads: return err; } -DEFINE_SUITE("Read samples using the mmap interface", basic_mmap); +static int test_stat_user_read(int event) +{ + struct perf_counts_values counts = { .val = 0 }; + struct perf_thread_map *threads; + struct perf_evsel *evsel; + struct perf_event_mmap_page *pc; + struct perf_event_attr attr = { + .type = PERF_TYPE_HARDWARE, + .config = event, +#ifdef __aarch64__ + .config1 = 0x2, /* Request user access */ +#endif + }; + int err, i, ret = TEST_FAIL; + bool opened = false, mapped = false; + + threads = perf_thread_map__new_dummy(); + TEST_ASSERT_VAL("failed to create threads", threads); + + perf_thread_map__set_pid(threads, 0, 0); + + evsel = perf_evsel__new(&attr); + TEST_ASSERT_VAL("failed to create evsel", evsel); + + err = perf_evsel__open(evsel, NULL, threads); + if (err) { + pr_err("failed to open evsel: %s\n", strerror(-err)); + ret = TEST_SKIP; + goto out; + } + opened = true; + + err = perf_evsel__mmap(evsel, 0); + if (err) { + pr_err("failed to mmap evsel: %s\n", strerror(-err)); + goto out; + } + mapped = true; + + pc = perf_evsel__mmap_base(evsel, 0, 0); + if (!pc) { + pr_err("failed to get mmapped address\n"); + goto out; + } + + if (!pc->cap_user_rdpmc || !pc->index) { + pr_err("userspace counter access not %s\n", + !pc->cap_user_rdpmc ? "supported" : "enabled"); + ret = TEST_SKIP; + goto out; + } + if (pc->pmc_width < 32) { + pr_err("userspace counter width not set (%d)\n", pc->pmc_width); + goto out; + } + + perf_evsel__read(evsel, 0, 0, &counts); + if (counts.val == 0) { + pr_err("failed to read value for evsel\n"); + goto out; + } + + for (i = 0; i < 5; i++) { + volatile int count = 0x10000 << i; + __u64 start, end, last = 0; + + pr_debug("\tloop = %u, ", count); + + perf_evsel__read(evsel, 0, 0, &counts); + start = counts.val; + + while (count--) ; + + perf_evsel__read(evsel, 0, 0, &counts); + end = counts.val; + + if ((end - start) < last) { + pr_err("invalid counter data: end=%llu start=%llu last= %llu\n", + end, start, last); + goto out; + } + last = end - start; + pr_debug("count = %llu\n", end - start); + } + ret = TEST_OK; + +out: + if (mapped) + perf_evsel__munmap(evsel); + if (opened) + perf_evsel__close(evsel); + perf_evsel__delete(evsel); + + perf_thread_map__put(threads); + return ret; +} + +static int test__mmap_user_read_instr(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + return test_stat_user_read(PERF_COUNT_HW_INSTRUCTIONS); +} + +static int test__mmap_user_read_cycles(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + return test_stat_user_read(PERF_COUNT_HW_CPU_CYCLES); +} + +static struct test_case tests__basic_mmap[] = { + TEST_CASE_REASON("Read samples using the mmap interface", + basic_mmap, + "permissions"), + TEST_CASE_REASON("User space counter reading of instructions", + mmap_user_read_instr, +#if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) + "permissions" +#else + "unsupported" +#endif + ), + TEST_CASE_REASON("User space counter reading of cycles", + mmap_user_read_cycles, +#if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) + "permissions" +#else + "unsupported" +#endif + ), + { .name = NULL, } +}; + +struct test_suite suite__basic_mmap = { + .desc = "mmap interface tests", + .test_cases = tests__basic_mmap, +}; diff --git a/tools/perf/tests/openat-syscall-all-cpus.c b/tools/perf/tests/openat-syscall-all-cpus.c index cd3dd463783f..f3275be83a33 100644 --- a/tools/perf/tests/openat-syscall-all-cpus.c +++ b/tools/perf/tests/openat-syscall-all-cpus.c @@ -2,7 +2,7 @@ #include <errno.h> #include <inttypes.h> /* For the CPU_* macros */ -#include <pthread.h> +#include <sched.h> #include <sys/types.h> #include <sys/stat.h> @@ -22,7 +22,8 @@ static int test__openat_syscall_event_on_all_cpus(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - int err = -1, fd, cpu; + int err = TEST_FAIL, fd, idx; + struct perf_cpu cpu; struct perf_cpu_map *cpus; struct evsel *evsel; unsigned int nr_openat_calls = 111, i; @@ -48,6 +49,7 @@ static int test__openat_syscall_event_on_all_cpus(struct test_suite *test __mayb if (IS_ERR(evsel)) { tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "syscalls", "sys_enter_openat"); pr_debug("%s\n", errbuf); + err = TEST_SKIP; goto out_cpu_map_delete; } @@ -55,26 +57,27 @@ static int test__openat_syscall_event_on_all_cpus(struct test_suite *test __mayb pr_debug("failed to open counter: %s, " "tweak /proc/sys/kernel/perf_event_paranoid?\n", str_error_r(errno, sbuf, sizeof(sbuf))); + err = TEST_SKIP; goto out_evsel_delete; } - for (cpu = 0; cpu < cpus->nr; ++cpu) { - unsigned int ncalls = nr_openat_calls + cpu; + perf_cpu_map__for_each_cpu(cpu, idx, cpus) { + unsigned int ncalls = nr_openat_calls + idx; /* * XXX eventually lift this restriction in a way that * keeps perf building on older glibc installations * without CPU_ALLOC. 1024 cpus in 2010 still seems * a reasonable upper limit tho :-) */ - if (cpus->map[cpu] >= CPU_SETSIZE) { - pr_debug("Ignoring CPU %d\n", cpus->map[cpu]); + if (cpu.cpu >= CPU_SETSIZE) { + pr_debug("Ignoring CPU %d\n", cpu.cpu); continue; } - CPU_SET(cpus->map[cpu], &cpu_set); + CPU_SET(cpu.cpu, &cpu_set); if (sched_setaffinity(0, sizeof(cpu_set), &cpu_set) < 0) { pr_debug("sched_setaffinity() failed on CPU %d: %s ", - cpus->map[cpu], + cpu.cpu, str_error_r(errno, sbuf, sizeof(sbuf))); goto out_close_fd; } @@ -82,38 +85,30 @@ static int test__openat_syscall_event_on_all_cpus(struct test_suite *test __mayb fd = openat(0, "/etc/passwd", O_RDONLY); close(fd); } - CPU_CLR(cpus->map[cpu], &cpu_set); + CPU_CLR(cpu.cpu, &cpu_set); } - /* - * Here we need to explicitly preallocate the counts, as if - * we use the auto allocation it will allocate just for 1 cpu, - * as we start by cpu 0. - */ - if (evsel__alloc_counts(evsel, cpus->nr, 1) < 0) { - pr_debug("evsel__alloc_counts(ncpus=%d)\n", cpus->nr); - goto out_close_fd; - } + evsel->core.cpus = perf_cpu_map__get(cpus); - err = 0; + err = TEST_OK; - for (cpu = 0; cpu < cpus->nr; ++cpu) { + perf_cpu_map__for_each_cpu(cpu, idx, cpus) { unsigned int expected; - if (cpus->map[cpu] >= CPU_SETSIZE) + if (cpu.cpu >= CPU_SETSIZE) continue; - if (evsel__read_on_cpu(evsel, cpu, 0) < 0) { + if (evsel__read_on_cpu(evsel, idx, 0) < 0) { pr_debug("evsel__read_on_cpu\n"); - err = -1; + err = TEST_FAIL; break; } - expected = nr_openat_calls + cpu; - if (perf_counts(evsel->counts, cpu, 0)->val != expected) { + expected = nr_openat_calls + idx; + if (perf_counts(evsel->counts, idx, 0)->val != expected) { pr_debug("evsel__read_on_cpu: expected to intercept %d calls on cpu %d, got %" PRIu64 "\n", - expected, cpus->map[cpu], perf_counts(evsel->counts, cpu, 0)->val); - err = -1; + expected, cpu.cpu, perf_counts(evsel->counts, idx, 0)->val); + err = TEST_FAIL; } } @@ -129,4 +124,15 @@ out_thread_map_delete: return err; } -DEFINE_SUITE("Detect openat syscall event on all cpus", openat_syscall_event_on_all_cpus); + +static struct test_case tests__openat_syscall_event_on_all_cpus[] = { + TEST_CASE_REASON("Detect openat syscall event on all cpus", + openat_syscall_event_on_all_cpus, + "permissions"), + { .name = NULL, } +}; + +struct test_suite suite__openat_syscall_event_on_all_cpus = { + .desc = "Detect openat syscall event on all cpus", + .test_cases = tests__openat_syscall_event_on_all_cpus, +}; diff --git a/tools/perf/tests/openat-syscall.c b/tools/perf/tests/openat-syscall.c index 7f4c13c4b14d..7e05b8b5cc95 100644 --- a/tools/perf/tests/openat-syscall.c +++ b/tools/perf/tests/openat-syscall.c @@ -16,7 +16,7 @@ static int test__openat_syscall_event(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - int err = -1, fd; + int err = TEST_FAIL, fd; struct evsel *evsel; unsigned int nr_openat_calls = 111, i; struct perf_thread_map *threads = thread_map__new(-1, getpid(), UINT_MAX); @@ -25,13 +25,14 @@ static int test__openat_syscall_event(struct test_suite *test __maybe_unused, if (threads == NULL) { pr_debug("thread_map__new\n"); - return -1; + return TEST_FAIL; } evsel = evsel__newtp("syscalls", "sys_enter_openat"); if (IS_ERR(evsel)) { tracing_path__strerror_open_tp(errno, errbuf, sizeof(errbuf), "syscalls", "sys_enter_openat"); pr_debug("%s\n", errbuf); + err = TEST_SKIP; goto out_thread_map_delete; } @@ -39,6 +40,7 @@ static int test__openat_syscall_event(struct test_suite *test __maybe_unused, pr_debug("failed to open counter: %s, " "tweak /proc/sys/kernel/perf_event_paranoid?\n", str_error_r(errno, sbuf, sizeof(sbuf))); + err = TEST_SKIP; goto out_evsel_delete; } @@ -58,7 +60,7 @@ static int test__openat_syscall_event(struct test_suite *test __maybe_unused, goto out_close_fd; } - err = 0; + err = TEST_OK; out_close_fd: perf_evsel__close_fd(&evsel->core); out_evsel_delete: @@ -68,4 +70,14 @@ out_thread_map_delete: return err; } -DEFINE_SUITE("Detect openat syscall event", openat_syscall_event); +static struct test_case tests__openat_syscall_event[] = { + TEST_CASE_REASON("Detect openat syscall event", + openat_syscall_event, + "permissions"), + { .name = NULL, } +}; + +struct test_suite suite__openat_syscall_event = { + .desc = "Detect openat syscall event", + .test_cases = tests__openat_syscall_event, +}; diff --git a/tools/perf/tests/parse-events.c b/tools/perf/tests/parse-events.c index a508f1dbcb2a..459afdb256a1 100644 --- a/tools/perf/tests/parse-events.c +++ b/tools/perf/tests/parse-events.c @@ -56,7 +56,7 @@ static int test__checkevent_tracepoint(struct evlist *evlist) TEST_ASSERT_VAL("wrong sample_type", PERF_TP_SAMPLE_TYPE == evsel->core.attr.sample_type); TEST_ASSERT_VAL("wrong sample_period", 1 == evsel->core.attr.sample_period); - return 0; + return TEST_OK; } static int test__checkevent_tracepoint_multi(struct evlist *evlist) @@ -74,7 +74,7 @@ static int test__checkevent_tracepoint_multi(struct evlist *evlist) TEST_ASSERT_VAL("wrong sample_period", 1 == evsel->core.attr.sample_period); } - return 0; + return TEST_OK; } static int test__checkevent_raw(struct evlist *evlist) @@ -84,7 +84,7 @@ static int test__checkevent_raw(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x1a == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_numeric(struct evlist *evlist) @@ -94,7 +94,7 @@ static int test__checkevent_numeric(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", 1 == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 1 == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_symbolic_name(struct evlist *evlist) @@ -105,7 +105,7 @@ static int test__checkevent_symbolic_name(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", PERF_TYPE_HARDWARE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", PERF_COUNT_HW_INSTRUCTIONS == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_symbolic_name_config(struct evlist *evlist) @@ -126,7 +126,7 @@ static int test__checkevent_symbolic_name_config(struct evlist *evlist) 0 == evsel->core.attr.config1); TEST_ASSERT_VAL("wrong config2", 1 == evsel->core.attr.config2); - return 0; + return TEST_OK; } static int test__checkevent_symbolic_alias(struct evlist *evlist) @@ -137,7 +137,7 @@ static int test__checkevent_symbolic_alias(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", PERF_TYPE_SOFTWARE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", PERF_COUNT_SW_PAGE_FAULTS == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_genhw(struct evlist *evlist) @@ -147,7 +147,7 @@ static int test__checkevent_genhw(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_HW_CACHE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", (1 << 16) == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint(struct evlist *evlist) @@ -161,7 +161,7 @@ static int test__checkevent_breakpoint(struct evlist *evlist) evsel->core.attr.bp_type); TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_4 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_x(struct evlist *evlist) @@ -174,7 +174,7 @@ static int test__checkevent_breakpoint_x(struct evlist *evlist) TEST_ASSERT_VAL("wrong bp_type", HW_BREAKPOINT_X == evsel->core.attr.bp_type); TEST_ASSERT_VAL("wrong bp_len", sizeof(long) == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_r(struct evlist *evlist) @@ -189,7 +189,7 @@ static int test__checkevent_breakpoint_r(struct evlist *evlist) HW_BREAKPOINT_R == evsel->core.attr.bp_type); TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_4 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_w(struct evlist *evlist) @@ -204,7 +204,7 @@ static int test__checkevent_breakpoint_w(struct evlist *evlist) HW_BREAKPOINT_W == evsel->core.attr.bp_type); TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_4 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_rw(struct evlist *evlist) @@ -219,7 +219,7 @@ static int test__checkevent_breakpoint_rw(struct evlist *evlist) (HW_BREAKPOINT_R|HW_BREAKPOINT_W) == evsel->core.attr.bp_type); TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_4 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_tracepoint_modifier(struct evlist *evlist) @@ -450,7 +450,7 @@ static int test__checkevent_pmu(struct evlist *evlist) */ TEST_ASSERT_VAL("wrong period", 0 == evsel->core.attr.sample_period); - return 0; + return TEST_OK; } static int test__checkevent_list(struct evlist *evlist) @@ -489,7 +489,7 @@ static int test__checkevent_list(struct evlist *evlist) TEST_ASSERT_VAL("wrong exclude_hv", !evsel->core.attr.exclude_hv); TEST_ASSERT_VAL("wrong precise_ip", evsel->core.attr.precise_ip); - return 0; + return TEST_OK; } static int test__checkevent_pmu_name(struct evlist *evlist) @@ -510,7 +510,7 @@ static int test__checkevent_pmu_name(struct evlist *evlist) TEST_ASSERT_VAL("wrong name", !strcmp(evsel__name(evsel), "cpu/config=2/u")); - return 0; + return TEST_OK; } static int test__checkevent_pmu_partial_time_callgraph(struct evlist *evlist) @@ -541,7 +541,7 @@ static int test__checkevent_pmu_partial_time_callgraph(struct evlist *evlist) TEST_ASSERT_VAL("wrong callgraph", !evsel__has_callchain(evsel)); TEST_ASSERT_VAL("wrong time", !(PERF_SAMPLE_TIME & evsel->core.attr.sample_type)); - return 0; + return TEST_OK; } static int test__checkevent_pmu_events(struct evlist *evlist) @@ -559,7 +559,7 @@ static int test__checkevent_pmu_events(struct evlist *evlist) TEST_ASSERT_VAL("wrong pinned", !evsel->core.attr.pinned); TEST_ASSERT_VAL("wrong exclusive", !evsel->core.attr.exclusive); - return 0; + return TEST_OK; } @@ -591,7 +591,7 @@ static int test__checkevent_pmu_events_mix(struct evlist *evlist) TEST_ASSERT_VAL("wrong pinned", !evsel->core.attr.pinned); TEST_ASSERT_VAL("wrong exclusive", !evsel->core.attr.pinned); - return 0; + return TEST_OK; } static int test__checkterms_simple(struct list_head *terms) @@ -662,7 +662,7 @@ static int test__checkterms_simple(struct list_head *terms) term->type_val == PARSE_EVENTS__TERM_TYPE_NUM); TEST_ASSERT_VAL("wrong val", term->val.num == 0xead); TEST_ASSERT_VAL("wrong config", !strcmp(term->config, "config")); - return 0; + return TEST_OK; } static int test__group1(struct evlist *evlist) @@ -704,7 +704,7 @@ static int test__group1(struct evlist *evlist) TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); TEST_ASSERT_VAL("wrong sample_read", !evsel->sample_read); - return 0; + return TEST_OK; } static int test__group2(struct evlist *evlist) @@ -759,7 +759,7 @@ static int test__group2(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__is_group_leader(evsel)); TEST_ASSERT_VAL("wrong sample_read", !evsel->sample_read); - return 0; + return TEST_OK; } static int test__group3(struct evlist *evlist __maybe_unused) @@ -851,7 +851,7 @@ static int test__group3(struct evlist *evlist __maybe_unused) TEST_ASSERT_VAL("wrong leader", evsel__is_group_leader(evsel)); TEST_ASSERT_VAL("wrong sample_read", !evsel->sample_read); - return 0; + return TEST_OK; } static int test__group4(struct evlist *evlist __maybe_unused) @@ -895,7 +895,7 @@ static int test__group4(struct evlist *evlist __maybe_unused) TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); TEST_ASSERT_VAL("wrong sample_read", !evsel->sample_read); - return 0; + return TEST_OK; } static int test__group5(struct evlist *evlist __maybe_unused) @@ -981,7 +981,7 @@ static int test__group5(struct evlist *evlist __maybe_unused) TEST_ASSERT_VAL("wrong precise_ip", !evsel->core.attr.precise_ip); TEST_ASSERT_VAL("wrong leader", evsel__is_group_leader(evsel)); - return 0; + return TEST_OK; } static int test__group_gh1(struct evlist *evlist) @@ -1021,7 +1021,7 @@ static int test__group_gh1(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); - return 0; + return TEST_OK; } static int test__group_gh2(struct evlist *evlist) @@ -1061,7 +1061,7 @@ static int test__group_gh2(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); - return 0; + return TEST_OK; } static int test__group_gh3(struct evlist *evlist) @@ -1101,7 +1101,7 @@ static int test__group_gh3(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); - return 0; + return TEST_OK; } static int test__group_gh4(struct evlist *evlist) @@ -1141,7 +1141,7 @@ static int test__group_gh4(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong group_idx", evsel__group_idx(evsel) == 1); - return 0; + return TEST_OK; } static int test__leader_sample1(struct evlist *evlist) @@ -1194,7 +1194,7 @@ static int test__leader_sample1(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong sample_read", evsel->sample_read); - return 0; + return TEST_OK; } static int test__leader_sample2(struct evlist *evlist __maybe_unused) @@ -1233,7 +1233,7 @@ static int test__leader_sample2(struct evlist *evlist __maybe_unused) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong sample_read", evsel->sample_read); - return 0; + return TEST_OK; } static int test__checkevent_pinned_modifier(struct evlist *evlist) @@ -1277,7 +1277,7 @@ static int test__pinned_group(struct evlist *evlist) PERF_COUNT_HW_BRANCH_MISSES == evsel->core.attr.config); TEST_ASSERT_VAL("wrong pinned", !evsel->core.attr.pinned); - return 0; + return TEST_OK; } static int test__checkevent_exclusive_modifier(struct evlist *evlist) @@ -1321,7 +1321,7 @@ static int test__exclusive_group(struct evlist *evlist) PERF_COUNT_HW_BRANCH_MISSES == evsel->core.attr.config); TEST_ASSERT_VAL("wrong exclusive", !evsel->core.attr.exclusive); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_len(struct evlist *evlist) { @@ -1335,7 +1335,7 @@ static int test__checkevent_breakpoint_len(struct evlist *evlist) TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_1 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int test__checkevent_breakpoint_len_w(struct evlist *evlist) @@ -1350,7 +1350,7 @@ static int test__checkevent_breakpoint_len_w(struct evlist *evlist) TEST_ASSERT_VAL("wrong bp_len", HW_BREAKPOINT_LEN_2 == evsel->core.attr.bp_len); - return 0; + return TEST_OK; } static int @@ -1374,7 +1374,7 @@ static int test__checkevent_precise_max_modifier(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", PERF_TYPE_SOFTWARE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", PERF_COUNT_SW_TASK_CLOCK == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__checkevent_config_symbol(struct evlist *evlist) @@ -1382,7 +1382,7 @@ static int test__checkevent_config_symbol(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong name setting", strcmp(evsel->name, "insn") == 0); - return 0; + return TEST_OK; } static int test__checkevent_config_raw(struct evlist *evlist) @@ -1390,7 +1390,7 @@ static int test__checkevent_config_raw(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong name setting", strcmp(evsel->name, "rawpmu") == 0); - return 0; + return TEST_OK; } static int test__checkevent_config_num(struct evlist *evlist) @@ -1398,7 +1398,7 @@ static int test__checkevent_config_num(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong name setting", strcmp(evsel->name, "numpmu") == 0); - return 0; + return TEST_OK; } static int test__checkevent_config_cache(struct evlist *evlist) @@ -1406,7 +1406,7 @@ static int test__checkevent_config_cache(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong name setting", strcmp(evsel->name, "cachepmu") == 0); - return 0; + return TEST_OK; } static bool test__intel_pt_valid(void) @@ -1419,7 +1419,7 @@ static int test__intel_pt(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong name setting", strcmp(evsel->name, "intel_pt//u") == 0); - return 0; + return TEST_OK; } static int test__checkevent_complex_name(struct evlist *evlist) @@ -1427,7 +1427,7 @@ static int test__checkevent_complex_name(struct evlist *evlist) struct evsel *evsel = evlist__first(evlist); TEST_ASSERT_VAL("wrong complex name parsing", strcmp(evsel->name, "COMPLEX_CYCLES_NAME:orig=cycles,desc=chip-clock-ticks") == 0); - return 0; + return TEST_OK; } static int test__checkevent_raw_pmu(struct evlist *evlist) @@ -1437,7 +1437,7 @@ static int test__checkevent_raw_pmu(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_SOFTWARE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x1a == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__sym_event_slash(struct evlist *evlist) @@ -1447,7 +1447,7 @@ static int test__sym_event_slash(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", evsel->core.attr.type == PERF_TYPE_HARDWARE); TEST_ASSERT_VAL("wrong config", evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES); TEST_ASSERT_VAL("wrong exclude_kernel", evsel->core.attr.exclude_kernel); - return 0; + return TEST_OK; } static int test__sym_event_dc(struct evlist *evlist) @@ -1457,7 +1457,7 @@ static int test__sym_event_dc(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", evsel->core.attr.type == PERF_TYPE_HARDWARE); TEST_ASSERT_VAL("wrong config", evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES); TEST_ASSERT_VAL("wrong exclude_user", evsel->core.attr.exclude_user); - return 0; + return TEST_OK; } static int count_tracepoints(void) @@ -1521,7 +1521,7 @@ static int test__hybrid_hw_event_with_pmu(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x3c == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__hybrid_hw_group_event(struct evlist *evlist) @@ -1538,7 +1538,7 @@ static int test__hybrid_hw_group_event(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0xc0 == evsel->core.attr.config); TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); - return 0; + return TEST_OK; } static int test__hybrid_sw_hw_group_event(struct evlist *evlist) @@ -1554,7 +1554,7 @@ static int test__hybrid_sw_hw_group_event(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x3c == evsel->core.attr.config); TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); - return 0; + return TEST_OK; } static int test__hybrid_hw_sw_group_event(struct evlist *evlist) @@ -1570,7 +1570,7 @@ static int test__hybrid_hw_sw_group_event(struct evlist *evlist) evsel = evsel__next(evsel); TEST_ASSERT_VAL("wrong type", PERF_TYPE_SOFTWARE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); - return 0; + return TEST_OK; } static int test__hybrid_group_modifier1(struct evlist *evlist) @@ -1591,7 +1591,7 @@ static int test__hybrid_group_modifier1(struct evlist *evlist) TEST_ASSERT_VAL("wrong leader", evsel__has_leader(evsel, leader)); TEST_ASSERT_VAL("wrong exclude_user", !evsel->core.attr.exclude_user); TEST_ASSERT_VAL("wrong exclude_kernel", evsel->core.attr.exclude_kernel); - return 0; + return TEST_OK; } static int test__hybrid_raw1(struct evlist *evlist) @@ -1602,7 +1602,7 @@ static int test__hybrid_raw1(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x1a == evsel->core.attr.config); - return 0; + return TEST_OK; } TEST_ASSERT_VAL("wrong number of entries", 2 == evlist->core.nr_entries); @@ -1612,7 +1612,7 @@ static int test__hybrid_raw1(struct evlist *evlist) /* The type of second event is randome value */ evsel = evsel__next(evsel); TEST_ASSERT_VAL("wrong config", 0x1a == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__hybrid_raw2(struct evlist *evlist) @@ -1622,7 +1622,7 @@ static int test__hybrid_raw2(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_RAW == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x1a == evsel->core.attr.config); - return 0; + return TEST_OK; } static int test__hybrid_cache_event(struct evlist *evlist) @@ -1632,434 +1632,435 @@ static int test__hybrid_cache_event(struct evlist *evlist) TEST_ASSERT_VAL("wrong number of entries", 1 == evlist->core.nr_entries); TEST_ASSERT_VAL("wrong type", PERF_TYPE_HW_CACHE == evsel->core.attr.type); TEST_ASSERT_VAL("wrong config", 0x2 == (evsel->core.attr.config & 0xffffffff)); - return 0; + return TEST_OK; } struct evlist_test { const char *name; - __u32 type; - const int id; bool (*valid)(void); int (*check)(struct evlist *evlist); }; -static struct evlist_test test__events[] = { +static const struct evlist_test test__events[] = { { .name = "syscalls:sys_enter_openat", .check = test__checkevent_tracepoint, - .id = 0, + /* 0 */ }, { .name = "syscalls:*", .check = test__checkevent_tracepoint_multi, - .id = 1, + /* 1 */ }, { .name = "r1a", .check = test__checkevent_raw, - .id = 2, + /* 2 */ }, { .name = "1:1", .check = test__checkevent_numeric, - .id = 3, + /* 3 */ }, { .name = "instructions", .check = test__checkevent_symbolic_name, - .id = 4, + /* 4 */ }, { .name = "cycles/period=100000,config2/", .check = test__checkevent_symbolic_name_config, - .id = 5, + /* 5 */ }, { .name = "faults", .check = test__checkevent_symbolic_alias, - .id = 6, + /* 6 */ }, { .name = "L1-dcache-load-miss", .check = test__checkevent_genhw, - .id = 7, + /* 7 */ }, { .name = "mem:0", .check = test__checkevent_breakpoint, - .id = 8, + /* 8 */ }, { .name = "mem:0:x", .check = test__checkevent_breakpoint_x, - .id = 9, + /* 9 */ }, { .name = "mem:0:r", .check = test__checkevent_breakpoint_r, - .id = 10, + /* 0 */ }, { .name = "mem:0:w", .check = test__checkevent_breakpoint_w, - .id = 11, + /* 1 */ }, { .name = "syscalls:sys_enter_openat:k", .check = test__checkevent_tracepoint_modifier, - .id = 12, + /* 2 */ }, { .name = "syscalls:*:u", .check = test__checkevent_tracepoint_multi_modifier, - .id = 13, + /* 3 */ }, { .name = "r1a:kp", .check = test__checkevent_raw_modifier, - .id = 14, + /* 4 */ }, { .name = "1:1:hp", .check = test__checkevent_numeric_modifier, - .id = 15, + /* 5 */ }, { .name = "instructions:h", .check = test__checkevent_symbolic_name_modifier, - .id = 16, + /* 6 */ }, { .name = "faults:u", .check = test__checkevent_symbolic_alias_modifier, - .id = 17, + /* 7 */ }, { .name = "L1-dcache-load-miss:kp", .check = test__checkevent_genhw_modifier, - .id = 18, + /* 8 */ }, { .name = "mem:0:u", .check = test__checkevent_breakpoint_modifier, - .id = 19, + /* 9 */ }, { .name = "mem:0:x:k", .check = test__checkevent_breakpoint_x_modifier, - .id = 20, + /* 0 */ }, { .name = "mem:0:r:hp", .check = test__checkevent_breakpoint_r_modifier, - .id = 21, + /* 1 */ }, { .name = "mem:0:w:up", .check = test__checkevent_breakpoint_w_modifier, - .id = 22, + /* 2 */ }, { .name = "r1,syscalls:sys_enter_openat:k,1:1:hp", .check = test__checkevent_list, - .id = 23, + /* 3 */ }, { .name = "instructions:G", .check = test__checkevent_exclude_host_modifier, - .id = 24, + /* 4 */ }, { .name = "instructions:H", .check = test__checkevent_exclude_guest_modifier, - .id = 25, + /* 5 */ }, { .name = "mem:0:rw", .check = test__checkevent_breakpoint_rw, - .id = 26, + /* 6 */ }, { .name = "mem:0:rw:kp", .check = test__checkevent_breakpoint_rw_modifier, - .id = 27, + /* 7 */ }, { .name = "{instructions:k,cycles:upp}", .check = test__group1, - .id = 28, + /* 8 */ }, { .name = "{faults:k,cache-references}:u,cycles:k", .check = test__group2, - .id = 29, + /* 9 */ }, { .name = "group1{syscalls:sys_enter_openat:H,cycles:kppp},group2{cycles,1:3}:G,instructions:u", .check = test__group3, - .id = 30, + /* 0 */ }, { .name = "{cycles:u,instructions:kp}:p", .check = test__group4, - .id = 31, + /* 1 */ }, { .name = "{cycles,instructions}:G,{cycles:G,instructions:G},cycles", .check = test__group5, - .id = 32, + /* 2 */ }, { .name = "*:*", .check = test__all_tracepoints, - .id = 33, + /* 3 */ }, { .name = "{cycles,cache-misses:G}:H", .check = test__group_gh1, - .id = 34, + /* 4 */ }, { .name = "{cycles,cache-misses:H}:G", .check = test__group_gh2, - .id = 35, + /* 5 */ }, { .name = "{cycles:G,cache-misses:H}:u", .check = test__group_gh3, - .id = 36, + /* 6 */ }, { .name = "{cycles:G,cache-misses:H}:uG", .check = test__group_gh4, - .id = 37, + /* 7 */ }, { .name = "{cycles,cache-misses,branch-misses}:S", .check = test__leader_sample1, - .id = 38, + /* 8 */ }, { .name = "{instructions,branch-misses}:Su", .check = test__leader_sample2, - .id = 39, + /* 9 */ }, { .name = "instructions:uDp", .check = test__checkevent_pinned_modifier, - .id = 40, + /* 0 */ }, { .name = "{cycles,cache-misses,branch-misses}:D", .check = test__pinned_group, - .id = 41, + /* 1 */ }, { .name = "mem:0/1", .check = test__checkevent_breakpoint_len, - .id = 42, + /* 2 */ }, { .name = "mem:0/2:w", .check = test__checkevent_breakpoint_len_w, - .id = 43, + /* 3 */ }, { .name = "mem:0/4:rw:u", .check = test__checkevent_breakpoint_len_rw_modifier, - .id = 44 + /* 4 */ }, #if defined(__s390x__) { .name = "kvm-s390:kvm_s390_create_vm", .check = test__checkevent_tracepoint, .valid = kvm_s390_create_vm_valid, - .id = 100, + /* 0 */ }, #endif { .name = "instructions:I", .check = test__checkevent_exclude_idle_modifier, - .id = 45, + /* 5 */ }, { .name = "instructions:kIG", .check = test__checkevent_exclude_idle_modifier_1, - .id = 46, + /* 6 */ }, { .name = "task-clock:P,cycles", .check = test__checkevent_precise_max_modifier, - .id = 47, + /* 7 */ }, { .name = "instructions/name=insn/", .check = test__checkevent_config_symbol, - .id = 48, + /* 8 */ }, { .name = "r1234/name=rawpmu/", .check = test__checkevent_config_raw, - .id = 49, + /* 9 */ }, { .name = "4:0x6530160/name=numpmu/", .check = test__checkevent_config_num, - .id = 50, + /* 0 */ }, { .name = "L1-dcache-misses/name=cachepmu/", .check = test__checkevent_config_cache, - .id = 51, + /* 1 */ }, { .name = "intel_pt//u", .valid = test__intel_pt_valid, .check = test__intel_pt, - .id = 52, + /* 2 */ }, { .name = "cycles/name='COMPLEX_CYCLES_NAME:orig=cycles,desc=chip-clock-ticks'/Duk", .check = test__checkevent_complex_name, - .id = 53 + /* 3 */ }, { .name = "cycles//u", .check = test__sym_event_slash, - .id = 54, + /* 4 */ }, { .name = "cycles:k", .check = test__sym_event_dc, - .id = 55, + /* 5 */ }, { .name = "instructions:uep", .check = test__checkevent_exclusive_modifier, - .id = 56, + /* 6 */ }, { .name = "{cycles,cache-misses,branch-misses}:e", .check = test__exclusive_group, - .id = 57, + /* 7 */ }, }; -static struct evlist_test test__events_pmu[] = { +static const struct evlist_test test__events_pmu[] = { { .name = "cpu/config=10,config1,config2=3,period=1000/u", .check = test__checkevent_pmu, - .id = 0, + /* 0 */ }, { .name = "cpu/config=1,name=krava/u,cpu/config=2/u", .check = test__checkevent_pmu_name, - .id = 1, + /* 1 */ }, { .name = "cpu/config=1,call-graph=fp,time,period=100000/,cpu/config=2,call-graph=no,time=0,period=2000/", .check = test__checkevent_pmu_partial_time_callgraph, - .id = 2, + /* 2 */ }, { .name = "cpu/name='COMPLEX_CYCLES_NAME:orig=cycles,desc=chip-clock-ticks',period=0x1,event=0x2/ukp", .check = test__checkevent_complex_name, - .id = 3, + /* 3 */ }, { .name = "software/r1a/", .check = test__checkevent_raw_pmu, - .id = 4, + /* 4 */ }, { .name = "software/r0x1a/", .check = test__checkevent_raw_pmu, - .id = 4, + /* 5 */ }, }; struct terms_test { const char *str; - __u32 type; int (*check)(struct list_head *terms); }; -static struct terms_test test__terms[] = { +static const struct terms_test test__terms[] = { [0] = { .str = "config=10,config1,config2=3,umask=1,read,r0xead", .check = test__checkterms_simple, }, }; -static struct evlist_test test__hybrid_events[] = { +static const struct evlist_test test__hybrid_events[] = { { .name = "cpu_core/cpu-cycles/", .check = test__hybrid_hw_event_with_pmu, - .id = 0, + /* 0 */ }, { .name = "{cpu_core/cpu-cycles/,cpu_core/instructions/}", .check = test__hybrid_hw_group_event, - .id = 1, + /* 1 */ }, { .name = "{cpu-clock,cpu_core/cpu-cycles/}", .check = test__hybrid_sw_hw_group_event, - .id = 2, + /* 2 */ }, { .name = "{cpu_core/cpu-cycles/,cpu-clock}", .check = test__hybrid_hw_sw_group_event, - .id = 3, + /* 3 */ }, { .name = "{cpu_core/cpu-cycles/k,cpu_core/instructions/u}", .check = test__hybrid_group_modifier1, - .id = 4, + /* 4 */ }, { .name = "r1a", .check = test__hybrid_raw1, - .id = 5, + /* 5 */ }, { .name = "cpu_core/r1a/", .check = test__hybrid_raw2, - .id = 6, + /* 6 */ }, { .name = "cpu_core/config=10,config1,config2=3,period=1000/u", .check = test__checkevent_pmu, - .id = 7, + /* 7 */ }, { .name = "cpu_core/LLC-loads/", .check = test__hybrid_cache_event, - .id = 8, + /* 8 */ }, }; -static int test_event(struct evlist_test *e) +static int test_event(const struct evlist_test *e) { struct parse_events_error err; struct evlist *evlist; int ret; if (e->valid && !e->valid()) { - pr_debug("... SKIP"); - return 0; + pr_debug("... SKIP\n"); + return TEST_OK; } evlist = evlist__new(); - if (evlist == NULL) - return -ENOMEM; - + if (evlist == NULL) { + pr_err("Failed allocation"); + return TEST_FAIL; + } parse_events_error__init(&err); ret = parse_events(evlist, e->name, &err); if (ret) { pr_debug("failed to parse event '%s', err %d, str '%s'\n", e->name, ret, err.str); parse_events_error__print(&err, e->name); + ret = TEST_FAIL; + if (strstr(err.str, "can't access trace events")) + ret = TEST_SKIP; } else { ret = e->check(evlist); } @@ -2069,25 +2070,65 @@ static int test_event(struct evlist_test *e) return ret; } -static int test_events(struct evlist_test *events, unsigned cnt) +static int test_event_fake_pmu(const char *str) { - int ret1, ret2 = 0; - unsigned i; + struct parse_events_error err; + struct evlist *evlist; + int ret; - for (i = 0; i < cnt; i++) { - struct evlist_test *e = &events[i]; + evlist = evlist__new(); + if (!evlist) + return -ENOMEM; - pr_debug("running test %d '%s'", e->id, e->name); - ret1 = test_event(e); - if (ret1) - ret2 = ret1; - pr_debug("\n"); + parse_events_error__init(&err); + perf_pmu__test_parse_init(); + ret = __parse_events(evlist, str, &err, &perf_pmu__fake); + if (ret) { + pr_debug("failed to parse event '%s', err %d, str '%s'\n", + str, ret, err.str); + parse_events_error__print(&err, str); } - return ret2; + parse_events_error__exit(&err); + evlist__delete(evlist); + + return ret; } -static int test_term(struct terms_test *t) +static int combine_test_results(int existing, int latest) +{ + if (existing == TEST_FAIL) + return TEST_FAIL; + if (existing == TEST_SKIP) + return latest == TEST_OK ? TEST_SKIP : latest; + return latest; +} + +static int test_events(const struct evlist_test *events, int cnt) +{ + int ret = TEST_OK; + + for (int i = 0; i < cnt; i++) { + const struct evlist_test *e = &events[i]; + int test_ret; + + pr_debug("running test %d '%s'\n", i, e->name); + test_ret = test_event(e); + if (test_ret != TEST_OK) { + pr_debug("Event test failure: test %d '%s'", i, e->name); + ret = combine_test_results(ret, test_ret); + } + } + + return ret; +} + +static int test__events2(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +{ + return test_events(test__events, ARRAY_SIZE(test__events)); +} + +static int test_term(const struct terms_test *t) { struct list_head terms; int ret; @@ -2114,13 +2155,12 @@ static int test_term(struct terms_test *t) return ret; } -static int test_terms(struct terms_test *terms, unsigned cnt) +static int test_terms(const struct terms_test *terms, int cnt) { int ret = 0; - unsigned i; - for (i = 0; i < cnt; i++) { - struct terms_test *t = &terms[i]; + for (int i = 0; i < cnt; i++) { + const struct terms_test *t = &terms[i]; pr_debug("running test %d '%s'\n", i, t->str); ret = test_term(t); @@ -2131,6 +2171,11 @@ static int test_terms(struct terms_test *terms, unsigned cnt) return ret; } +static int test__terms2(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +{ + return test_terms(test__terms, ARRAY_SIZE(test__terms)); +} + static int test_pmu(void) { struct stat st; @@ -2146,7 +2191,7 @@ static int test_pmu(void) return !ret; } -static int test_pmu_events(void) +static int test__pmu_events(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { struct stat st; char path[PATH_MAX]; @@ -2154,24 +2199,29 @@ static int test_pmu_events(void) DIR *dir; int ret; + if (!test_pmu()) + return TEST_SKIP; + snprintf(path, PATH_MAX, "%s/bus/event_source/devices/cpu/events/", sysfs__mountpoint()); ret = stat(path, &st); if (ret) { - pr_debug("omitting PMU cpu events tests\n"); - return 0; + pr_debug("omitting PMU cpu events tests: %s\n", path); + return TEST_OK; } dir = opendir(path); if (!dir) { - pr_debug("can't open pmu event dir"); - return -1; + pr_debug("can't open pmu event dir: %s\n", path); + return TEST_FAIL; } - while (!ret && (ent = readdir(dir))) { - struct evlist_test e = { .id = 0, }; + ret = TEST_OK; + while ((ent = readdir(dir))) { + struct evlist_test e = { .name = NULL, }; char name[2 * NAME_MAX + 1 + 12 + 3]; + int test_ret; /* Names containing . are special and cannot be used directly */ if (strchr(ent->d_name, '.')) @@ -2182,19 +2232,33 @@ static int test_pmu_events(void) e.name = name; e.check = test__checkevent_pmu_events; - ret = test_event(&e); - if (ret) - break; + test_ret = test_event(&e); + if (test_ret != TEST_OK) { + pr_debug("Test PMU event failed for '%s'", name); + ret = combine_test_results(ret, test_ret); + } snprintf(name, sizeof(name), "%s:u,cpu/event=%s/u", ent->d_name, ent->d_name); e.name = name; e.check = test__checkevent_pmu_events_mix; - ret = test_event(&e); + test_ret = test_event(&e); + if (test_ret != TEST_OK) { + pr_debug("Test PMU event failed for '%s'", name); + ret = combine_test_results(ret, test_ret); + } } closedir(dir); return ret; } +static int test__pmu_events2(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +{ + if (!test_pmu()) + return TEST_SKIP; + + return test_events(test__events_pmu, ARRAY_SIZE(test__events_pmu)); +} + static bool test_alias(char **event, char **alias) { char path[PATH_MAX]; @@ -2253,6 +2317,14 @@ static bool test_alias(char **event, char **alias) return false; } +static int test__hybrid(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +{ + if (!perf_pmu__has_hybrid()) + return TEST_SKIP; + + return test_events(test__hybrid_events, ARRAY_SIZE(test__hybrid_events)); +} + static int test__checkevent_pmu_events_alias(struct evlist *evlist) { struct evsel *evsel1 = evlist__first(evlist); @@ -2260,12 +2332,12 @@ static int test__checkevent_pmu_events_alias(struct evlist *evlist) TEST_ASSERT_VAL("wrong type", evsel1->core.attr.type == evsel2->core.attr.type); TEST_ASSERT_VAL("wrong config", evsel1->core.attr.config == evsel2->core.attr.config); - return 0; + return TEST_OK; } -static int test_pmu_events_alias(char *event, char *alias) +static int test__pmu_events_alias(char *event, char *alias) { - struct evlist_test e = { .id = 0, }; + struct evlist_test e = { .name = NULL, }; char name[2 * NAME_MAX + 20]; snprintf(name, sizeof(name), "%s/event=1/,%s/event=1/", @@ -2276,48 +2348,63 @@ static int test_pmu_events_alias(char *event, char *alias) return test_event(&e); } -static int test__parse_events(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +static int test__alias(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - int ret1, ret2 = 0; char *event, *alias; + int ret; -#define TEST_EVENTS(tests) \ -do { \ - ret1 = test_events(tests, ARRAY_SIZE(tests)); \ - if (!ret2) \ - ret2 = ret1; \ -} while (0) - - if (perf_pmu__has_hybrid()) { - TEST_EVENTS(test__hybrid_events); - return ret2; - } + if (!test_alias(&event, &alias)) + return TEST_SKIP; - TEST_EVENTS(test__events); + ret = test__pmu_events_alias(event, alias); - if (test_pmu()) - TEST_EVENTS(test__events_pmu); + free(event); + free(alias); + return ret; +} - if (test_pmu()) { - int ret = test_pmu_events(); - if (ret) - return ret; - } +static int test__pmu_events_alias2(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + static const char events[][30] = { + "event-hyphen", + "event-two-hyph", + }; + int ret = TEST_OK; - if (test_alias(&event, &alias)) { - int ret = test_pmu_events_alias(event, alias); + for (unsigned int i = 0; i < ARRAY_SIZE(events); i++) { + int test_ret = test_event_fake_pmu(&events[i][0]); - free(event); - free(alias); - if (ret) - return ret; + if (test_ret != TEST_OK) { + pr_debug("check_parse_fake %s failed\n", &events[i][0]); + ret = combine_test_results(ret, test_ret); + } } - ret1 = test_terms(test__terms, ARRAY_SIZE(test__terms)); - if (!ret2) - ret2 = ret1; - - return ret2; + return ret; } -DEFINE_SUITE("Parse event definition strings", parse_events); +static struct test_case tests__parse_events[] = { + TEST_CASE_REASON("Test event parsing", + events2, + "permissions"), + TEST_CASE_REASON("Test parsing of \"hybrid\" CPU events", + hybrid, + "not hybrid"), + TEST_CASE_REASON("Parsing of all PMU events from sysfs", + pmu_events, + "permissions"), + TEST_CASE_REASON("Parsing of given PMU events from sysfs", + pmu_events2, + "permissions"), + TEST_CASE_REASON("Parsing of aliased events from sysfs", alias, + "no aliases in sysfs"), + TEST_CASE("Parsing of aliased events", pmu_events_alias2), + TEST_CASE("Parsing of terms (event modifiers)", terms2), + { .name = NULL, } +}; + +struct test_suite suite__parse_events = { + .desc = "Parse event definition strings", + .test_cases = tests__parse_events, +}; diff --git a/tools/perf/tests/parse-metric.c b/tools/perf/tests/parse-metric.c index 07b6f4ec024f..68f5a2a03242 100644 --- a/tools/perf/tests/parse-metric.c +++ b/tools/perf/tests/parse-metric.c @@ -13,79 +13,6 @@ #include "stat.h" #include "pmu.h" -static struct pmu_event pme_test[] = { -{ - .metric_expr = "inst_retired.any / cpu_clk_unhalted.thread", - .metric_name = "IPC", - .metric_group = "group1", -}, -{ - .metric_expr = "idq_uops_not_delivered.core / (4 * (( ( cpu_clk_unhalted.thread / 2 ) * " - "( 1 + cpu_clk_unhalted.one_thread_active / cpu_clk_unhalted.ref_xclk ) )))", - .metric_name = "Frontend_Bound_SMT", -}, -{ - .metric_expr = "l1d\\-loads\\-misses / inst_retired.any", - .metric_name = "dcache_miss_cpi", -}, -{ - .metric_expr = "l1i\\-loads\\-misses / inst_retired.any", - .metric_name = "icache_miss_cycles", -}, -{ - .metric_expr = "(dcache_miss_cpi + icache_miss_cycles)", - .metric_name = "cache_miss_cycles", - .metric_group = "group1", -}, -{ - .metric_expr = "l2_rqsts.demand_data_rd_hit + l2_rqsts.pf_hit + l2_rqsts.rfo_hit", - .metric_name = "DCache_L2_All_Hits", -}, -{ - .metric_expr = "max(l2_rqsts.all_demand_data_rd - l2_rqsts.demand_data_rd_hit, 0) + " - "l2_rqsts.pf_miss + l2_rqsts.rfo_miss", - .metric_name = "DCache_L2_All_Miss", -}, -{ - .metric_expr = "dcache_l2_all_hits + dcache_l2_all_miss", - .metric_name = "DCache_L2_All", -}, -{ - .metric_expr = "d_ratio(dcache_l2_all_hits, dcache_l2_all)", - .metric_name = "DCache_L2_Hits", -}, -{ - .metric_expr = "d_ratio(dcache_l2_all_miss, dcache_l2_all)", - .metric_name = "DCache_L2_Misses", -}, -{ - .metric_expr = "ipc + m2", - .metric_name = "M1", -}, -{ - .metric_expr = "ipc + m1", - .metric_name = "M2", -}, -{ - .metric_expr = "1/m3", - .metric_name = "M3", -}, -{ - .metric_expr = "64 * l1d.replacement / 1000000000 / duration_time", - .metric_name = "L1D_Cache_Fill_BW", -}, -{ - .name = NULL, -} -}; - -static const struct pmu_events_map map = { - .cpuid = "test", - .version = "1", - .type = "core", - .table = pme_test, -}; - struct value { const char *event; u64 val; @@ -145,6 +72,7 @@ static int __compute_metric(const char *name, struct value *vals, struct rblist metric_events = { .nr_entries = 0, }; + const struct pmu_events_table *pme_test; struct perf_cpu_map *cpus; struct runtime_stat st; struct evlist *evlist; @@ -168,7 +96,8 @@ static int __compute_metric(const char *name, struct value *vals, runtime_stat__init(&st); /* Parse the metric into metric_events list. */ - err = metricgroup__parse_groups_test(evlist, &map, name, + pme_test = find_core_events_table("testarch", "testcpu"); + err = metricgroup__parse_groups_test(evlist, pme_test, name, false, false, &metric_events); if (err) diff --git a/tools/perf/tests/perf-record.c b/tools/perf/tests/perf-record.c index 6354465067b8..7aa946aa886d 100644 --- a/tools/perf/tests/perf-record.c +++ b/tools/perf/tests/perf-record.c @@ -2,8 +2,6 @@ #include <errno.h> #include <inttypes.h> #include <linux/string.h> -/* For the CLR_() macros */ -#include <pthread.h> #include <sched.h> #include <perf/mmap.h> @@ -330,7 +328,21 @@ found_exit: out_delete_evlist: evlist__delete(evlist); out: - return (err < 0 || errs > 0) ? -1 : 0; + if (err == -EACCES) + return TEST_SKIP; + if (err < 0 || errs != 0) + return TEST_FAIL; + return TEST_OK; } -DEFINE_SUITE("PERF_RECORD_* events & perf_sample fields", PERF_RECORD); +static struct test_case tests__PERF_RECORD[] = { + TEST_CASE_REASON("PERF_RECORD_* events & perf_sample fields", + PERF_RECORD, + "permissions"), + { .name = NULL, } +}; + +struct test_suite suite__PERF_RECORD = { + .desc = "PERF_RECORD_* events & perf_sample fields", + .test_cases = tests__PERF_RECORD, +}; diff --git a/tools/perf/tests/perf-time-to-tsc.c b/tools/perf/tests/perf-time-to-tsc.c index d12d0ad81801..c3aaa1ddff29 100644 --- a/tools/perf/tests/perf-time-to-tsc.c +++ b/tools/perf/tests/perf-time-to-tsc.c @@ -20,8 +20,6 @@ #include "tsc.h" #include "mmap.h" #include "tests.h" -#include "pmu.h" -#include "pmu-hybrid.h" /* * Except x86_64/i386 and Arm64, other archs don't support TSC in perf. Just @@ -47,13 +45,24 @@ } \ } +static int test__tsc_is_supported(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + if (!TSC_IS_SUPPORTED) { + pr_debug("Test not supported on this architecture\n"); + return TEST_SKIP; + } + + return TEST_OK; +} + /** * test__perf_time_to_tsc - test converting perf time to TSC. * * This function implements a test that checks that the conversion of perf time * to and from TSC is consistent with the order of events. If the test passes * %0 is returned, otherwise %-1 is returned. If TSC conversion is not - * supported then then the test passes but " (not supported)" is printed. + * supported then the test passes but " (not supported)" is printed. */ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { @@ -70,7 +79,7 @@ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int su struct perf_cpu_map *cpus = NULL; struct evlist *evlist = NULL; struct evsel *evsel = NULL; - int err = -1, ret, i; + int err = TEST_FAIL, ret, i; const char *comm1, *comm2; struct perf_tsc_conversion tc; struct perf_event_mmap_page *pc; @@ -79,10 +88,6 @@ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int su u64 test_time, comm1_time = 0, comm2_time = 0; struct mmap *md; - if (!TSC_IS_SUPPORTED) { - pr_debug("Test not supported on this architecture"); - return TEST_SKIP; - } threads = thread_map__new(-1, getpid(), UINT_MAX); CHECK_NOT_NULL__(threads); @@ -95,28 +100,25 @@ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int su perf_evlist__set_maps(&evlist->core, cpus, threads); - CHECK__(parse_events(evlist, "cycles:u", NULL)); + CHECK__(parse_event(evlist, "cycles:u")); evlist__config(evlist, &opts, NULL); - evsel = evlist__first(evlist); - - evsel->core.attr.comm = 1; - evsel->core.attr.disabled = 1; - evsel->core.attr.enable_on_exec = 0; - - /* - * For hybrid "cycles:u", it creates two events. - * Init the second evsel here. - */ - if (perf_pmu__has_hybrid() && perf_pmu__hybrid_mounted("cpu_atom")) { - evsel = evsel__next(evsel); + /* For hybrid "cycles:u", it creates two events */ + evlist__for_each_entry(evlist, evsel) { evsel->core.attr.comm = 1; evsel->core.attr.disabled = 1; evsel->core.attr.enable_on_exec = 0; } - CHECK__(evlist__open(evlist)); + ret = evlist__open(evlist); + if (ret < 0) { + if (ret == -ENOENT) + err = TEST_SKIP; + else + pr_debug("evlist__open() failed\n"); + goto out_err; + } CHECK__(evlist__mmap(evlist, UINT_MAX)); @@ -124,8 +126,8 @@ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int su ret = perf_read_tsc_conversion(pc, &tc); if (ret) { if (ret == -EOPNOTSUPP) { - fprintf(stderr, " (not supported)"); - return 0; + pr_debug("perf_read_tsc_conversion is not supported in current kernel\n"); + err = TEST_SKIP; } goto out_err; } @@ -156,10 +158,12 @@ static int test__perf_time_to_tsc(struct test_suite *test __maybe_unused, int su goto next_event; if (strcmp(event->comm.comm, comm1) == 0) { + CHECK_NOT_NULL__(evsel = evlist__event2evsel(evlist, event)); CHECK__(evsel__parse_sample(evsel, event, &sample)); comm1_time = sample.time; } if (strcmp(event->comm.comm, comm2) == 0) { + CHECK_NOT_NULL__(evsel = evlist__event2evsel(evlist, event)); CHECK__(evsel__parse_sample(evsel, event, &sample)); comm2_time = sample.time; } @@ -191,7 +195,7 @@ next_event: test_tsc >= comm2_tsc) goto out_err; - err = 0; + err = TEST_OK; out_err: evlist__delete(evlist); @@ -200,4 +204,15 @@ out_err: return err; } -DEFINE_SUITE("Convert perf time to TSC", perf_time_to_tsc); +static struct test_case time_to_tsc_tests[] = { + TEST_CASE_REASON("TSC support", tsc_is_supported, + "This architecture does not support"), + TEST_CASE_REASON("Perf time to TSC", perf_time_to_tsc, + "perf_read_tsc_conversion is not supported"), + { .name = NULL, } +}; + +struct test_suite suite__perf_time_to_tsc = { + .desc = "Convert perf time to TSC", + .test_cases = time_to_tsc_tests, +}; diff --git a/tools/perf/tests/pmu-events.c b/tools/perf/tests/pmu-events.c index df1c9a3cc05b..097e05c796ab 100644 --- a/tools/perf/tests/pmu-events.c +++ b/tools/perf/tests/pmu-events.c @@ -9,10 +9,12 @@ #include <linux/zalloc.h> #include "debug.h" #include "../pmu-events/pmu-events.h" +#include <perf/evlist.h> #include "util/evlist.h" #include "util/expr.h" #include "util/parse-events.h" #include "metricgroup.h" +#include "stat.h" struct perf_pmu_test_event { /* used for matching against events from generated pmu-events.c */ @@ -63,33 +65,33 @@ static const struct perf_pmu_test_event bp_l2_btb_correct = { static const struct perf_pmu_test_event segment_reg_loads_any = { .event = { .name = "segment_reg_loads.any", - .event = "umask=0x80,period=200000,event=0x6", + .event = "event=0x6,period=200000,umask=0x80", .desc = "Number of segment register loads", .topic = "other", }, - .alias_str = "umask=0x80,period=0x30d40,event=0x6", + .alias_str = "event=0x6,period=0x30d40,umask=0x80", .alias_long_desc = "Number of segment register loads", }; static const struct perf_pmu_test_event dispatch_blocked_any = { .event = { .name = "dispatch_blocked.any", - .event = "umask=0x20,period=200000,event=0x9", + .event = "event=0x9,period=200000,umask=0x20", .desc = "Memory cluster signals to block micro-op dispatch for any reason", .topic = "other", }, - .alias_str = "umask=0x20,period=0x30d40,event=0x9", + .alias_str = "event=0x9,period=0x30d40,umask=0x20", .alias_long_desc = "Memory cluster signals to block micro-op dispatch for any reason", }; static const struct perf_pmu_test_event eist_trans = { .event = { .name = "eist_trans", - .event = "umask=0x0,period=200000,event=0x3a", + .event = "event=0x3a,period=200000,umask=0x0", .desc = "Number of Enhanced Intel SpeedStep(R) Technology (EIST) transitions", .topic = "other", }, - .alias_str = "umask=0,period=0x30d40,event=0x3a", + .alias_str = "event=0x3a,period=0x30d40,umask=0", .alias_long_desc = "Number of Enhanced Intel SpeedStep(R) Technology (EIST) transitions", }; @@ -132,17 +134,45 @@ static const struct perf_pmu_test_event uncore_hisi_ddrc_flux_wcmd = { static const struct perf_pmu_test_event unc_cbo_xsnp_response_miss_eviction = { .event = { .name = "unc_cbo_xsnp_response.miss_eviction", - .event = "umask=0x81,event=0x22", - .desc = "Unit: uncore_cbox A cross-core snoop resulted from L3 Eviction which misses in some processor core", + .event = "event=0x22,umask=0x81", + .desc = "A cross-core snoop resulted from L3 Eviction which misses in some processor core. Unit: uncore_cbox ", .topic = "uncore", .long_desc = "A cross-core snoop resulted from L3 Eviction which misses in some processor core", .pmu = "uncore_cbox", }, - .alias_str = "umask=0x81,event=0x22", + .alias_str = "event=0x22,umask=0x81", .alias_long_desc = "A cross-core snoop resulted from L3 Eviction which misses in some processor core", .matching_pmu = "uncore_cbox_0", }; +static const struct perf_pmu_test_event uncore_hyphen = { + .event = { + .name = "event-hyphen", + .event = "event=0xe0,umask=0x00", + .desc = "UNC_CBO_HYPHEN. Unit: uncore_cbox ", + .topic = "uncore", + .long_desc = "UNC_CBO_HYPHEN", + .pmu = "uncore_cbox", + }, + .alias_str = "event=0xe0,umask=0", + .alias_long_desc = "UNC_CBO_HYPHEN", + .matching_pmu = "uncore_cbox_0", +}; + +static const struct perf_pmu_test_event uncore_two_hyph = { + .event = { + .name = "event-two-hyph", + .event = "event=0xc0,umask=0x00", + .desc = "UNC_CBO_TWO_HYPH. Unit: uncore_cbox ", + .topic = "uncore", + .long_desc = "UNC_CBO_TWO_HYPH", + .pmu = "uncore_cbox", + }, + .alias_str = "event=0xc0,umask=0", + .alias_long_desc = "UNC_CBO_TWO_HYPH", + .matching_pmu = "uncore_cbox_0", +}; + static const struct perf_pmu_test_event uncore_hisi_l3c_rd_hit_cpipe = { .event = { .name = "uncore_hisi_l3c.rd_hit_cpipe", @@ -188,6 +218,8 @@ static const struct perf_pmu_test_event uncore_imc_cache_hits = { static const struct perf_pmu_test_event *uncore_events[] = { &uncore_hisi_ddrc_flux_wcmd, &unc_cbo_xsnp_response_miss_eviction, + &uncore_hyphen, + &uncore_two_hyph, &uncore_hisi_l3c_rd_hit_cpipe, &uncore_imc_free_running_cache_miss, &uncore_imc_cache_hits, @@ -242,32 +274,6 @@ static bool is_same(const char *reference, const char *test) return !strcmp(reference, test); } -static const struct pmu_events_map *__test_pmu_get_events_map(void) -{ - const struct pmu_events_map *map; - - for (map = &pmu_events_map[0]; map->cpuid; map++) { - if (!strcmp(map->cpuid, "testcpu")) - return map; - } - - pr_err("could not find test events map\n"); - - return NULL; -} - -static const struct pmu_event *__test_pmu_get_sys_events_table(void) -{ - const struct pmu_sys_events *tables = &pmu_sys_event_tables[0]; - - for ( ; tables->name; tables++) { - if (!strcmp("pme_test_soc_sys", tables->name)) - return tables->table; - } - - return NULL; -} - static int compare_pmu_events(const struct pmu_event *e1, const struct pmu_event *e2) { if (!is_same(e1->name, e2->name)) { @@ -417,85 +423,104 @@ static int compare_alias_to_test_event(struct perf_pmu_alias *alias, return 0; } -/* Verify generated events from pmu-events.c are as expected */ -static int test__pmu_event_table(struct test_suite *test __maybe_unused, - int subtest __maybe_unused) +static int test__pmu_event_table_core_callback(const struct pmu_event *pe, + const struct pmu_events_table *table __maybe_unused, + void *data) { - const struct pmu_event *sys_event_tables = __test_pmu_get_sys_events_table(); - const struct pmu_events_map *map = __test_pmu_get_events_map(); - const struct pmu_event *table; - int map_events = 0, expected_events; + int *map_events = data; + struct perf_pmu_test_event const **test_event_table; + bool found = false; - /* ignore 3x sentinels */ - expected_events = ARRAY_SIZE(core_events) + - ARRAY_SIZE(uncore_events) + - ARRAY_SIZE(sys_events) - 3; + if (!pe->name) + return 0; - if (!map || !sys_event_tables) - return -1; + if (pe->pmu) + test_event_table = &uncore_events[0]; + else + test_event_table = &core_events[0]; - for (table = map->table; table->name; table++) { - struct perf_pmu_test_event const **test_event_table; - bool found = false; + for (; *test_event_table; test_event_table++) { + struct perf_pmu_test_event const *test_event = *test_event_table; + struct pmu_event const *event = &test_event->event; - if (table->pmu) - test_event_table = &uncore_events[0]; - else - test_event_table = &core_events[0]; + if (strcmp(pe->name, event->name)) + continue; + found = true; + (*map_events)++; - for (; *test_event_table; test_event_table++) { - struct perf_pmu_test_event const *test_event = *test_event_table; - struct pmu_event const *event = &test_event->event; + if (compare_pmu_events(pe, event)) + return -1; - if (strcmp(table->name, event->name)) - continue; - found = true; - map_events++; + pr_debug("testing event table %s: pass\n", pe->name); + } + if (!found) { + pr_err("testing event table: could not find event %s\n", pe->name); + return -1; + } + return 0; +} - if (compare_pmu_events(table, event)) - return -1; +static int test__pmu_event_table_sys_callback(const struct pmu_event *pe, + const struct pmu_events_table *table __maybe_unused, + void *data) +{ + int *map_events = data; + struct perf_pmu_test_event const **test_event_table; + bool found = false; - pr_debug("testing event table %s: pass\n", table->name); - } + test_event_table = &sys_events[0]; - if (!found) { - pr_err("testing event table: could not find event %s\n", - table->name); - return -1; - } - } + for (; *test_event_table; test_event_table++) { + struct perf_pmu_test_event const *test_event = *test_event_table; + struct pmu_event const *event = &test_event->event; - for (table = sys_event_tables; table->name; table++) { - struct perf_pmu_test_event const **test_event_table; - bool found = false; + if (strcmp(pe->name, event->name)) + continue; + found = true; + (*map_events)++; - test_event_table = &sys_events[0]; + if (compare_pmu_events(pe, event)) + return TEST_FAIL; - for (; *test_event_table; test_event_table++) { - struct perf_pmu_test_event const *test_event = *test_event_table; - struct pmu_event const *event = &test_event->event; + pr_debug("testing sys event table %s: pass\n", pe->name); + } + if (!found) { + pr_debug("testing sys event table: could not find event %s\n", pe->name); + return TEST_FAIL; + } + return TEST_OK; +} - if (strcmp(table->name, event->name)) - continue; - found = true; - map_events++; +/* Verify generated events from pmu-events.c are as expected */ +static int test__pmu_event_table(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + const struct pmu_events_table *sys_event_table = find_sys_events_table("pme_test_soc_sys"); + const struct pmu_events_table *table = find_core_events_table("testarch", "testcpu"); + int map_events = 0, expected_events, err; - if (compare_pmu_events(table, event)) - return -1; + /* ignore 3x sentinels */ + expected_events = ARRAY_SIZE(core_events) + + ARRAY_SIZE(uncore_events) + + ARRAY_SIZE(sys_events) - 3; - pr_debug("testing sys event table %s: pass\n", table->name); - } - if (!found) { - pr_debug("testing event table: could not find event %s\n", - table->name); - return -1; - } - } + if (!table || !sys_event_table) + return -1; + + err = pmu_events_table_for_each_event(table, test__pmu_event_table_core_callback, + &map_events); + if (err) + return err; + + err = pmu_events_table_for_each_event(sys_event_table, test__pmu_event_table_sys_callback, + &map_events); + if (err) + return err; if (map_events != expected_events) { pr_err("testing event table: found %d, but expected %d\n", map_events, expected_events); - return -1; + return TEST_FAIL; } return 0; @@ -519,10 +544,10 @@ static int __test_core_pmu_event_aliases(char *pmu_name, int *count) struct perf_pmu *pmu; LIST_HEAD(aliases); int res = 0; - const struct pmu_events_map *map = __test_pmu_get_events_map(); + const struct pmu_events_table *table = find_core_events_table("testarch", "testcpu"); struct perf_pmu_alias *a, *tmp; - if (!map) + if (!table) return -1; test_event_table = &core_events[0]; @@ -533,7 +558,7 @@ static int __test_core_pmu_event_aliases(char *pmu_name, int *count) pmu->name = pmu_name; - pmu_add_cpu_aliases_map(&aliases, pmu, map); + pmu_add_cpu_aliases_table(&aliases, pmu, table); for (; *test_event_table; test_event_table++) { struct perf_pmu_test_event const *test_event = *test_event_table; @@ -572,14 +597,14 @@ static int __test_uncore_pmu_event_aliases(struct perf_pmu_test_pmu *test_pmu) struct perf_pmu *pmu = &test_pmu->pmu; const char *pmu_name = pmu->name; struct perf_pmu_alias *a, *tmp, *alias; - const struct pmu_events_map *map; + const struct pmu_events_table *events_table; LIST_HEAD(aliases); int res = 0; - map = __test_pmu_get_events_map(); - if (!map) + events_table = find_core_events_table("testarch", "testcpu"); + if (!events_table) return -1; - pmu_add_cpu_aliases_map(&aliases, pmu, map); + pmu_add_cpu_aliases_table(&aliases, pmu, events_table); pmu_add_sys_aliases(&aliases, pmu); /* Count how many aliases we generated */ @@ -654,6 +679,8 @@ static struct perf_pmu_test_pmu test_pmus[] = { }, .aliases = { &unc_cbo_xsnp_response_miss_eviction, + &uncore_hyphen, + &uncore_two_hyph, }, }, { @@ -780,6 +807,15 @@ static int check_parse_id(const char *id, struct parse_events_error *error, for (cur = strchr(dup, '@') ; cur; cur = strchr(++cur, '@')) *cur = '/'; + if (fake_pmu) { + /* + * Every call to __parse_events will try to initialize the PMU + * state from sysfs and then clean it up at the end. Reset the + * PMU events to the test state so that we don't pick up + * erroneous prefixes and suffixes. + */ + perf_pmu__test_parse_init(); + } ret = __parse_events(evlist, dup, error, fake_pmu); free(dup); @@ -787,27 +823,6 @@ static int check_parse_id(const char *id, struct parse_events_error *error, return ret; } -static int check_parse_cpu(const char *id, bool same_cpu, const struct pmu_event *pe) -{ - struct parse_events_error error; - int ret; - - parse_events_error__init(&error); - ret = check_parse_id(id, &error, NULL); - if (ret && same_cpu) { - pr_warning("Parse event failed metric '%s' id '%s' expr '%s'\n", - pe->metric_name, id, pe->metric_expr); - pr_warning("Error string '%s' help '%s'\n", error.str, - error.help); - } else if (ret) { - pr_debug3("Parse event failed, but for an event that may not be supported by this CPU.\nid '%s' metric '%s' expr '%s'\n", - id, pe->metric_name, pe->metric_expr); - ret = 0; - } - parse_events_error__exit(&error); - return ret; -} - static int check_parse_fake(const char *id) { struct parse_events_error error; @@ -819,158 +834,116 @@ static int check_parse_fake(const char *id) return ret; } -static void expr_failure(const char *msg, - const struct pmu_events_map *map, - const struct pmu_event *pe) -{ - pr_debug("%s for map %s %s %s\n", - msg, map->cpuid, map->version, map->type); - pr_debug("On metric %s\n", pe->metric_name); - pr_debug("On expression %s\n", pe->metric_expr); -} - struct metric { struct list_head list; struct metric_ref metric_ref; }; -static int resolve_metric_simple(struct expr_parse_ctx *pctx, - struct list_head *compound_list, - const struct pmu_events_map *map, - const char *metric_name) +static int test__parsing_callback(const struct pmu_event *pe, const struct pmu_events_table *table, + void *data) { - struct hashmap_entry *cur, *cur_tmp; - struct metric *metric, *tmp; - size_t bkt; - bool all; - int rc; - - do { - all = true; - hashmap__for_each_entry_safe(pctx->ids, cur, cur_tmp, bkt) { - struct metric_ref *ref; - const struct pmu_event *pe; - - pe = metricgroup__find_metric(cur->key, map); - if (!pe) - continue; - - if (!strcmp(metric_name, (char *)cur->key)) { - pr_warning("Recursion detected for metric %s\n", metric_name); - rc = -1; - goto out_err; - } + int *failures = data; + int k; + struct evlist *evlist; + struct perf_cpu_map *cpus; + struct runtime_stat st; + struct evsel *evsel; + struct rblist metric_events = { + .nr_entries = 0, + }; + int err = 0; - all = false; + if (!pe->metric_expr) + return 0; - /* The metric key itself needs to go out.. */ - expr__del_id(pctx, cur->key); + pr_debug("Found metric '%s'\n", pe->metric_name); + (*failures)++; - metric = malloc(sizeof(*metric)); - if (!metric) { - rc = -ENOMEM; - goto out_err; - } + /* + * We need to prepare evlist for stat mode running on CPU 0 + * because that's where all the stats are going to be created. + */ + evlist = evlist__new(); + if (!evlist) + return -ENOMEM; - ref = &metric->metric_ref; - ref->metric_name = pe->metric_name; - ref->metric_expr = pe->metric_expr; - list_add_tail(&metric->list, compound_list); + cpus = perf_cpu_map__new("0"); + if (!cpus) { + evlist__delete(evlist); + return -ENOMEM; + } - rc = expr__find_ids(pe->metric_expr, NULL, pctx); - if (rc) - goto out_err; - break; /* The hashmap has been modified, so restart */ + perf_evlist__set_maps(&evlist->core, cpus, NULL); + runtime_stat__init(&st); + + err = metricgroup__parse_groups_test(evlist, table, pe->metric_name, + false, false, + &metric_events); + if (err) { + if (!strcmp(pe->metric_name, "M1") || !strcmp(pe->metric_name, "M2") || + !strcmp(pe->metric_name, "M3")) { + (*failures)--; + pr_debug("Expected broken metric %s skipping\n", pe->metric_name); + err = 0; } - } while (!all); - - return 0; + goto out_err; + } -out_err: - list_for_each_entry_safe(metric, tmp, compound_list, list) - free(metric); + err = evlist__alloc_stats(evlist, false); + if (err) + goto out_err; + /* + * Add all ids with a made up value. The value may trigger divide by + * zero when subtracted and so try to make them unique. + */ + k = 1; + perf_stat__reset_shadow_stats(); + evlist__for_each_entry(evlist, evsel) { + perf_stat__update_shadow_stats(evsel, k, 0, &st); + if (!strcmp(evsel->name, "duration_time")) + update_stats(&walltime_nsecs_stats, k); + k++; + } + evlist__for_each_entry(evlist, evsel) { + struct metric_event *me = metricgroup__lookup(&metric_events, evsel, false); - return rc; + if (me != NULL) { + struct metric_expr *mexp; + list_for_each_entry (mexp, &me->head, nd) { + if (strcmp(mexp->metric_name, pe->metric_name)) + continue; + pr_debug("Result %f\n", test_generic_metric(mexp, 0, &st)); + err = 0; + (*failures)--; + goto out_err; + } + } + } + pr_debug("Didn't find parsed metric %s", pe->metric_name); + err = 1; +out_err: + if (err) + pr_debug("Broken metric %s\n", pe->metric_name); + + /* ... cleanup. */ + metricgroup__rblist_exit(&metric_events); + runtime_stat__exit(&st); + evlist__free_stats(evlist); + perf_cpu_map__put(cpus); + evlist__delete(evlist); + return err; } static int test__parsing(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - const struct pmu_events_map *cpus_map = pmu_events_map__find(); - const struct pmu_events_map *map; - const struct pmu_event *pe; - int i, j, k; - int ret = 0; - struct expr_parse_ctx *ctx; - double result; + int failures = 0; - ctx = expr__ctx_new(); - if (!ctx) { - pr_debug("expr__ctx_new failed"); - return TEST_FAIL; - } - i = 0; - for (;;) { - map = &pmu_events_map[i++]; - if (!map->table) - break; - j = 0; - for (;;) { - struct metric *metric, *tmp; - struct hashmap_entry *cur; - LIST_HEAD(compound_list); - size_t bkt; - - pe = &map->table[j++]; - if (!pe->name && !pe->metric_group && !pe->metric_name) - break; - if (!pe->metric_expr) - continue; - expr__ctx_clear(ctx); - if (expr__find_ids(pe->metric_expr, NULL, ctx) < 0) { - expr_failure("Parse find ids failed", map, pe); - ret++; - continue; - } + pmu_for_each_core_event(test__parsing_callback, &failures); + pmu_for_each_sys_event(test__parsing_callback, &failures); - if (resolve_metric_simple(ctx, &compound_list, map, - pe->metric_name)) { - expr_failure("Could not resolve metrics", map, pe); - ret++; - goto exit; /* Don't tolerate errors due to severity */ - } - - /* - * Add all ids with a made up value. The value may - * trigger divide by zero when subtracted and so try to - * make them unique. - */ - k = 1; - hashmap__for_each_entry(ctx->ids, cur, bkt) - expr__add_id_val(ctx, strdup(cur->key), k++); - - hashmap__for_each_entry(ctx->ids, cur, bkt) { - if (check_parse_cpu(cur->key, map == cpus_map, - pe)) - ret++; - } - - list_for_each_entry_safe(metric, tmp, &compound_list, list) { - expr__add_ref(ctx, &metric->metric_ref); - free(metric); - } - - if (expr__parse(&result, ctx, pe->metric_expr)) { - expr_failure("Parse failed", map, pe); - ret++; - } - } - } - expr__ctx_free(ctx); - /* TODO: fail when not ok */ -exit: - return ret == 0 ? TEST_OK : TEST_SKIP; + return failures == 0 ? TEST_OK : TEST_FAIL; } struct test_metric { @@ -1022,16 +995,36 @@ static int metric_parse_fake(const char *str) } } - if (expr__parse(&result, ctx, str)) - pr_err("expr__parse failed\n"); - else - ret = 0; + ret = 0; + if (expr__parse(&result, ctx, str)) { + /* + * Parsing failed, make numbers go from large to small which can + * resolve divide by zero issues. + */ + i = 1024; + hashmap__for_each_entry(ctx->ids, cur, bkt) + expr__add_id_val(ctx, strdup(cur->key), i--); + if (expr__parse(&result, ctx, str)) { + pr_err("expr__parse failed\n"); + ret = -1; + } + } out: expr__ctx_free(ctx); return ret; } +static int test__parsing_fake_callback(const struct pmu_event *pe, + const struct pmu_events_table *table __maybe_unused, + void *data __maybe_unused) +{ + if (!pe->metric_expr) + return 0; + + return metric_parse_fake(pe->metric_expr); +} + /* * Parse all the metrics for current architecture, * or all defined cpus via the 'fake_pmu' @@ -1040,36 +1033,19 @@ out: static int test__parsing_fake(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - const struct pmu_events_map *map; - const struct pmu_event *pe; - unsigned int i, j; int err = 0; - for (i = 0; i < ARRAY_SIZE(metrics); i++) { + for (size_t i = 0; i < ARRAY_SIZE(metrics); i++) { err = metric_parse_fake(metrics[i].str); if (err) return err; } - i = 0; - for (;;) { - map = &pmu_events_map[i++]; - if (!map->table) - break; - j = 0; - for (;;) { - pe = &map->table[j++]; - if (!pe->name && !pe->metric_group && !pe->metric_name) - break; - if (!pe->metric_expr) - continue; - err = metric_parse_fake(pe->metric_expr); - if (err) - return err; - } - } + err = pmu_for_each_core_event(test__parsing_fake_callback, NULL); + if (err) + return err; - return 0; + return pmu_for_each_sys_event(test__parsing_fake_callback, NULL); } static struct test_case pmu_events_tests[] = { diff --git a/tools/perf/tests/sample-parsing.c b/tools/perf/tests/sample-parsing.c index 07f2411b0ad4..20930dd48ee0 100644 --- a/tools/perf/tests/sample-parsing.c +++ b/tools/perf/tests/sample-parsing.c @@ -86,10 +86,15 @@ static bool samples_same(const struct perf_sample *s1, COMP(read.time_running); /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */ if (read_format & PERF_FORMAT_GROUP) { - for (i = 0; i < s1->read.group.nr; i++) - MCOMP(read.group.values[i]); + for (i = 0; i < s1->read.group.nr; i++) { + /* FIXME: check values without LOST */ + if (read_format & PERF_FORMAT_LOST) + MCOMP(read.group.values[i]); + } } else { COMP(read.one.id); + if (read_format & PERF_FORMAT_LOST) + COMP(read.one.lost); } } @@ -263,7 +268,7 @@ static int do_test(u64 sample_type, u64 sample_regs, u64 read_format) .data = (void *)aux_data, }, }; - struct sample_read_value values[] = {{1, 5}, {9, 3}, {2, 7}, {6, 4},}; + struct sample_read_value values[] = {{1, 5, 0}, {9, 3, 0}, {2, 7, 0}, {6, 4, 1},}; struct perf_sample sample_out, sample_out_endian; size_t i, sz, bufsz; int err, ret = -1; @@ -286,6 +291,7 @@ static int do_test(u64 sample_type, u64 sample_regs, u64 read_format) } else { sample.read.one.value = 0x08789faeb786aa87ULL; sample.read.one.id = 99; + sample.read.one.lost = 1; } sz = perf_event__sample_event_size(&sample, sample_type, read_format); @@ -370,7 +376,7 @@ out_free: */ static int test__sample_parsing(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - const u64 rf[] = {4, 5, 6, 7, 12, 13, 14, 15}; + const u64 rf[] = {4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 28, 29, 30, 31}; u64 sample_type; u64 sample_regs; size_t i; diff --git a/tools/perf/tests/shell/coresight/Makefile b/tools/perf/tests/shell/coresight/Makefile new file mode 100644 index 000000000000..b070e779703e --- /dev/null +++ b/tools/perf/tests/shell/coresight/Makefile @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +include ../../../../../tools/scripts/Makefile.include +include ../../../../../tools/scripts/Makefile.arch +include ../../../../../tools/scripts/utilities.mak + +SUBDIRS = \ + asm_pure_loop \ + memcpy_thread \ + thread_loop \ + unroll_loop_thread + +all: $(SUBDIRS) +$(SUBDIRS): + @$(MAKE) -C $@ >/dev/null + +INSTALLDIRS = $(SUBDIRS:%=install-%) + +install-tests: $(INSTALLDIRS) +$(INSTALLDIRS): + @$(MAKE) -C $(@:install-%=%) install-tests >/dev/null + +CLEANDIRS = $(SUBDIRS:%=clean-%) + +clean: $(CLEANDIRS) +$(CLEANDIRS): + $(call QUIET_CLEAN, test-$(@:clean-%=%)) $(Q)$(MAKE) -C $(@:clean-%=%) clean >/dev/null + +.PHONY: all clean $(SUBDIRS) $(CLEANDIRS) $(INSTALLDIRS) diff --git a/tools/perf/tests/shell/coresight/Makefile.miniconfig b/tools/perf/tests/shell/coresight/Makefile.miniconfig new file mode 100644 index 000000000000..5f72a9cb43f3 --- /dev/null +++ b/tools/perf/tests/shell/coresight/Makefile.miniconfig @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +ifndef DESTDIR +prefix ?= $(HOME) +endif + +DESTDIR_SQ = $(subst ','\'',$(DESTDIR)) +INSTALL = install +INSTDIR_SUB = tests/shell/coresight + +include ../../../../../scripts/Makefile.include +include ../../../../../scripts/Makefile.arch +include ../../../../../scripts/utilities.mak diff --git a/tools/perf/tests/shell/coresight/asm_pure_loop.sh b/tools/perf/tests/shell/coresight/asm_pure_loop.sh new file mode 100755 index 000000000000..569e9d46162b --- /dev/null +++ b/tools/perf/tests/shell/coresight/asm_pure_loop.sh @@ -0,0 +1,18 @@ +#!/bin/sh -e +# CoreSight / ASM Pure Loop + +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +TEST="asm_pure_loop" +. $(dirname $0)/../lib/coresight.sh +ARGS="" +DATV="out" +DATA="$DATD/perf-$TEST-$DATV.data" + +perf record $PERFRECOPT -o "$DATA" "$BIN" $ARGS + +perf_dump_aux_verify "$DATA" 10 10 10 + +err=$? +exit $err diff --git a/tools/perf/tests/shell/coresight/asm_pure_loop/.gitignore b/tools/perf/tests/shell/coresight/asm_pure_loop/.gitignore new file mode 100644 index 000000000000..468673ac32e8 --- /dev/null +++ b/tools/perf/tests/shell/coresight/asm_pure_loop/.gitignore @@ -0,0 +1 @@ +asm_pure_loop diff --git a/tools/perf/tests/shell/coresight/asm_pure_loop/Makefile b/tools/perf/tests/shell/coresight/asm_pure_loop/Makefile new file mode 100644 index 000000000000..206849e92bc9 --- /dev/null +++ b/tools/perf/tests/shell/coresight/asm_pure_loop/Makefile @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +include ../Makefile.miniconfig + +# Binary to produce +BIN=asm_pure_loop +# Any linking/libraries needed for the binary - empty if none needed +LIB= + +all: $(BIN) + +$(BIN): $(BIN).S +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Build line - this is raw asm with no libc to have an always exact binary + $(Q)$(CC) $(BIN).S -nostdlib -static -o $(BIN) $(LIB) +endif +endif + +install-tests: all +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Install the test tool in the right place + $(call QUIET_INSTALL, tests) \ + $(INSTALL) -d -m 755 '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)'; \ + $(INSTALL) $(BIN) '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)/$(BIN)' +endif +endif + +clean: + $(Q)$(RM) -f $(BIN) + +.PHONY: all clean install-tests diff --git a/tools/perf/tests/shell/coresight/asm_pure_loop/asm_pure_loop.S b/tools/perf/tests/shell/coresight/asm_pure_loop/asm_pure_loop.S new file mode 100644 index 000000000000..75cf084a927d --- /dev/null +++ b/tools/perf/tests/shell/coresight/asm_pure_loop/asm_pure_loop.S @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Tamas Zsoldos <tamas.zsoldos@arm.com>, 2021 */ + +.globl _start +_start: + mov x0, 0x0000ffff + mov x1, xzr +loop: + nop + nop + cbnz x1, noskip + nop + nop + adrp x2, skip + add x2, x2, :lo12:skip + br x2 + nop + nop +noskip: + nop + nop +skip: + sub x0, x0, 1 + cbnz x0, loop + + mov x0, #0 + mov x8, #93 // __NR_exit syscall + svc #0 diff --git a/tools/perf/tests/shell/coresight/memcpy_thread/.gitignore b/tools/perf/tests/shell/coresight/memcpy_thread/.gitignore new file mode 100644 index 000000000000..f8217e56091e --- /dev/null +++ b/tools/perf/tests/shell/coresight/memcpy_thread/.gitignore @@ -0,0 +1 @@ +memcpy_thread diff --git a/tools/perf/tests/shell/coresight/memcpy_thread/Makefile b/tools/perf/tests/shell/coresight/memcpy_thread/Makefile new file mode 100644 index 000000000000..2db637eb2c26 --- /dev/null +++ b/tools/perf/tests/shell/coresight/memcpy_thread/Makefile @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +include ../Makefile.miniconfig + +# Binary to produce +BIN=memcpy_thread +# Any linking/libraries needed for the binary - empty if none needed +LIB=-pthread + +all: $(BIN) + +$(BIN): $(BIN).c +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Build line + $(Q)$(CC) $(BIN).c -o $(BIN) $(LIB) +endif +endif + +install-tests: all +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Install the test tool in the right place + $(call QUIET_INSTALL, tests) \ + $(INSTALL) -d -m 755 '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)'; \ + $(INSTALL) $(BIN) '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)/$(BIN)' +endif +endif + +clean: + $(Q)$(RM) -f $(BIN) + +.PHONY: all clean install-tests diff --git a/tools/perf/tests/shell/coresight/memcpy_thread/memcpy_thread.c b/tools/perf/tests/shell/coresight/memcpy_thread/memcpy_thread.c new file mode 100644 index 000000000000..a7e169d1bf64 --- /dev/null +++ b/tools/perf/tests/shell/coresight/memcpy_thread/memcpy_thread.c @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0 +// Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <pthread.h> + +struct args { + unsigned long loops; + unsigned long size; + pthread_t th; + void *ret; +}; + +static void *thrfn(void *arg) +{ + struct args *a = arg; + unsigned long i, len = a->loops; + unsigned char *src, *dst; + + src = malloc(a->size * 1024); + dst = malloc(a->size * 1024); + if ((!src) || (!dst)) { + printf("ERR: Can't allocate memory\n"); + exit(1); + } + for (i = 0; i < len; i++) + memcpy(dst, src, a->size * 1024); +} + +static pthread_t new_thr(void *(*fn) (void *arg), void *arg) +{ + pthread_t t; + pthread_attr_t attr; + + pthread_attr_init(&attr); + pthread_create(&t, &attr, fn, arg); + return t; +} + +int main(int argc, char **argv) +{ + unsigned long i, len, size, thr; + pthread_t threads[256]; + struct args args[256]; + long long v; + + if (argc < 4) { + printf("ERR: %s [copysize Kb] [numthreads] [numloops (hundreds)]\n", argv[0]); + exit(1); + } + + v = atoll(argv[1]); + if ((v < 1) || (v > (1024 * 1024))) { + printf("ERR: max memory 1GB (1048576 KB)\n"); + exit(1); + } + size = v; + thr = atol(argv[2]); + if ((thr < 1) || (thr > 256)) { + printf("ERR: threads 1-256\n"); + exit(1); + } + v = atoll(argv[3]); + if ((v < 1) || (v > 40000000000ll)) { + printf("ERR: loops 1-40000000000 (hundreds)\n"); + exit(1); + } + len = v * 100; + for (i = 0; i < thr; i++) { + args[i].loops = len; + args[i].size = size; + args[i].th = new_thr(thrfn, &(args[i])); + } + for (i = 0; i < thr; i++) + pthread_join(args[i].th, &(args[i].ret)); + return 0; +} diff --git a/tools/perf/tests/shell/coresight/memcpy_thread_16k_10.sh b/tools/perf/tests/shell/coresight/memcpy_thread_16k_10.sh new file mode 100755 index 000000000000..d21ba8545938 --- /dev/null +++ b/tools/perf/tests/shell/coresight/memcpy_thread_16k_10.sh @@ -0,0 +1,18 @@ +#!/bin/sh -e +# CoreSight / Memcpy 16k 10 Threads + +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +TEST="memcpy_thread" +. $(dirname $0)/../lib/coresight.sh +ARGS="16 10 1" +DATV="16k_10" +DATA="$DATD/perf-$TEST-$DATV.data" + +perf record $PERFRECOPT -o "$DATA" "$BIN" $ARGS + +perf_dump_aux_verify "$DATA" 10 10 10 + +err=$? +exit $err diff --git a/tools/perf/tests/shell/coresight/thread_loop/.gitignore b/tools/perf/tests/shell/coresight/thread_loop/.gitignore new file mode 100644 index 000000000000..6d4c33eaa9e8 --- /dev/null +++ b/tools/perf/tests/shell/coresight/thread_loop/.gitignore @@ -0,0 +1 @@ +thread_loop diff --git a/tools/perf/tests/shell/coresight/thread_loop/Makefile b/tools/perf/tests/shell/coresight/thread_loop/Makefile new file mode 100644 index 000000000000..ea846c038e7a --- /dev/null +++ b/tools/perf/tests/shell/coresight/thread_loop/Makefile @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +include ../Makefile.miniconfig + +# Binary to produce +BIN=thread_loop +# Any linking/libraries needed for the binary - empty if none needed +LIB=-pthread + +all: $(BIN) + +$(BIN): $(BIN).c +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Build line + $(Q)$(CC) $(BIN).c -o $(BIN) $(LIB) +endif +endif + +install-tests: all +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Install the test tool in the right place + $(call QUIET_INSTALL, tests) \ + $(INSTALL) -d -m 755 '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)'; \ + $(INSTALL) $(BIN) '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)/$(BIN)' +endif +endif + +clean: + $(Q)$(RM) -f $(BIN) + +.PHONY: all clean install-tests diff --git a/tools/perf/tests/shell/coresight/thread_loop/thread_loop.c b/tools/perf/tests/shell/coresight/thread_loop/thread_loop.c new file mode 100644 index 000000000000..c0158fac7d0b --- /dev/null +++ b/tools/perf/tests/shell/coresight/thread_loop/thread_loop.c @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-2.0 +// Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +// define this for gettid() +#define _GNU_SOURCE + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <pthread.h> +#include <sys/syscall.h> +#ifndef SYS_gettid +// gettid is 178 on arm64 +# define SYS_gettid 178 +#endif +#define gettid() syscall(SYS_gettid) + +struct args { + unsigned int loops; + pthread_t th; + void *ret; +}; + +static void *thrfn(void *arg) +{ + struct args *a = arg; + int i = 0, len = a->loops; + + if (getenv("SHOW_TID")) { + unsigned long long tid = gettid(); + + printf("%llu\n", tid); + } + asm volatile( + "loop:\n" + "add %[i], %[i], #1\n" + "cmp %[i], %[len]\n" + "blt loop\n" + : /* out */ + : /* in */ [i] "r" (i), [len] "r" (len) + : /* clobber */ + ); + return (void *)(long)i; +} + +static pthread_t new_thr(void *(*fn) (void *arg), void *arg) +{ + pthread_t t; + pthread_attr_t attr; + + pthread_attr_init(&attr); + pthread_create(&t, &attr, fn, arg); + return t; +} + +int main(int argc, char **argv) +{ + unsigned int i, len, thr; + pthread_t threads[256]; + struct args args[256]; + + if (argc < 3) { + printf("ERR: %s [numthreads] [numloops (millions)]\n", argv[0]); + exit(1); + } + + thr = atoi(argv[1]); + if ((thr < 1) || (thr > 256)) { + printf("ERR: threads 1-256\n"); + exit(1); + } + len = atoi(argv[2]); + if ((len < 1) || (len > 4000)) { + printf("ERR: max loops 4000 (millions)\n"); + exit(1); + } + len *= 1000000; + for (i = 0; i < thr; i++) { + args[i].loops = len; + args[i].th = new_thr(thrfn, &(args[i])); + } + for (i = 0; i < thr; i++) + pthread_join(args[i].th, &(args[i].ret)); + return 0; +} diff --git a/tools/perf/tests/shell/coresight/thread_loop_check_tid_10.sh b/tools/perf/tests/shell/coresight/thread_loop_check_tid_10.sh new file mode 100755 index 000000000000..7c13636fc778 --- /dev/null +++ b/tools/perf/tests/shell/coresight/thread_loop_check_tid_10.sh @@ -0,0 +1,19 @@ +#!/bin/sh -e +# CoreSight / Thread Loop 10 Threads - Check TID + +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +TEST="thread_loop" +. $(dirname $0)/../lib/coresight.sh +ARGS="10 1" +DATV="check-tid-10th" +DATA="$DATD/perf-$TEST-$DATV.data" +STDO="$DATD/perf-$TEST-$DATV.stdout" + +SHOW_TID=1 perf record -s $PERFRECOPT -o "$DATA" "$BIN" $ARGS > $STDO + +perf_dump_aux_tid_verify "$DATA" "$STDO" + +err=$? +exit $err diff --git a/tools/perf/tests/shell/coresight/thread_loop_check_tid_2.sh b/tools/perf/tests/shell/coresight/thread_loop_check_tid_2.sh new file mode 100755 index 000000000000..a067145af43c --- /dev/null +++ b/tools/perf/tests/shell/coresight/thread_loop_check_tid_2.sh @@ -0,0 +1,19 @@ +#!/bin/sh -e +# CoreSight / Thread Loop 2 Threads - Check TID + +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +TEST="thread_loop" +. $(dirname $0)/../lib/coresight.sh +ARGS="2 20" +DATV="check-tid-2th" +DATA="$DATD/perf-$TEST-$DATV.data" +STDO="$DATD/perf-$TEST-$DATV.stdout" + +SHOW_TID=1 perf record -s $PERFRECOPT -o "$DATA" "$BIN" $ARGS > $STDO + +perf_dump_aux_tid_verify "$DATA" "$STDO" + +err=$? +exit $err diff --git a/tools/perf/tests/shell/coresight/unroll_loop_thread/.gitignore b/tools/perf/tests/shell/coresight/unroll_loop_thread/.gitignore new file mode 100644 index 000000000000..2cb4e996dbf3 --- /dev/null +++ b/tools/perf/tests/shell/coresight/unroll_loop_thread/.gitignore @@ -0,0 +1 @@ +unroll_loop_thread diff --git a/tools/perf/tests/shell/coresight/unroll_loop_thread/Makefile b/tools/perf/tests/shell/coresight/unroll_loop_thread/Makefile new file mode 100644 index 000000000000..6264c4e3abd1 --- /dev/null +++ b/tools/perf/tests/shell/coresight/unroll_loop_thread/Makefile @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +include ../Makefile.miniconfig + +# Binary to produce +BIN=unroll_loop_thread +# Any linking/libraries needed for the binary - empty if none needed +LIB=-pthread + +all: $(BIN) + +$(BIN): $(BIN).c +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Build line + $(Q)$(CC) $(BIN).c -o $(BIN) $(LIB) +endif +endif + +install-tests: all +ifdef CORESIGHT +ifeq ($(ARCH),arm64) +# Install the test tool in the right place + $(call QUIET_INSTALL, tests) \ + $(INSTALL) -d -m 755 '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)'; \ + $(INSTALL) $(BIN) '$(DESTDIR_SQ)$(perfexec_instdir_SQ)/$(INSTDIR_SUB)/$(BIN)/$(BIN)' +endif +endif + +clean: + $(Q)$(RM) -f $(BIN) + +.PHONY: all clean install-tests diff --git a/tools/perf/tests/shell/coresight/unroll_loop_thread/unroll_loop_thread.c b/tools/perf/tests/shell/coresight/unroll_loop_thread/unroll_loop_thread.c new file mode 100644 index 000000000000..8f6d384208ed --- /dev/null +++ b/tools/perf/tests/shell/coresight/unroll_loop_thread/unroll_loop_thread.c @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-2.0 +// Carsten Haitzler <carsten.haitzler@arm.com>, 2021 +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <pthread.h> + +struct args { + pthread_t th; + unsigned int in; + void *ret; +}; + +static void *thrfn(void *arg) +{ + struct args *a = arg; + unsigned int i, in = a->in; + + for (i = 0; i < 10000; i++) { + asm volatile ( +// force an unroll of thia add instruction so we can test long runs of code +#define SNIP1 "add %[in], %[in], #1\n" +// 10 +#define SNIP2 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 SNIP1 +// 100 +#define SNIP3 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 SNIP2 +// 1000 +#define SNIP4 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 SNIP3 +// 10000 +#define SNIP5 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 SNIP4 +// 100000 + SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 SNIP5 + : /* out */ + : /* in */ [in] "r" (in) + : /* clobber */ + ); + } +} + +static pthread_t new_thr(void *(*fn) (void *arg), void *arg) +{ + pthread_t t; + pthread_attr_t attr; + + pthread_attr_init(&attr); + pthread_create(&t, &attr, fn, arg); + return t; +} + +int main(int argc, char **argv) +{ + unsigned int i, thr; + pthread_t threads[256]; + struct args args[256]; + + if (argc < 2) { + printf("ERR: %s [numthreads]\n", argv[0]); + exit(1); + } + + thr = atoi(argv[1]); + if ((thr > 256) || (thr < 1)) { + printf("ERR: threads 1-256\n"); + exit(1); + } + for (i = 0; i < thr; i++) { + args[i].in = rand(); + args[i].th = new_thr(thrfn, &(args[i])); + } + for (i = 0; i < thr; i++) + pthread_join(args[i].th, &(args[i].ret)); + return 0; +} diff --git a/tools/perf/tests/shell/coresight/unroll_loop_thread_10.sh b/tools/perf/tests/shell/coresight/unroll_loop_thread_10.sh new file mode 100755 index 000000000000..f48c85230b15 --- /dev/null +++ b/tools/perf/tests/shell/coresight/unroll_loop_thread_10.sh @@ -0,0 +1,18 @@ +#!/bin/sh -e +# CoreSight / Unroll Loop Thread 10 + +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +TEST="unroll_loop_thread" +. $(dirname $0)/../lib/coresight.sh +ARGS="10" +DATV="10" +DATA="$DATD/perf-$TEST-$DATV.data" + +perf record $PERFRECOPT -o "$DATA" "$BIN" $ARGS + +perf_dump_aux_verify "$DATA" 10 10 10 + +err=$? +exit $err diff --git a/tools/perf/tests/shell/lib/coresight.sh b/tools/perf/tests/shell/lib/coresight.sh new file mode 100644 index 000000000000..45a1477256b6 --- /dev/null +++ b/tools/perf/tests/shell/lib/coresight.sh @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: GPL-2.0 +# Carsten Haitzler <carsten.haitzler@arm.com>, 2021 + +# This is sourced from a driver script so no need for #!/bin... etc. at the +# top - the assumption below is that it runs as part of sourcing after the +# test sets up some basic env vars to say what it is. + +# This currently works with ETMv4 / ETF not any other packet types at thi +# point. This will need changes if that changes. + +# perf record options for the perf tests to use +PERFRECMEM="-m ,16M" +PERFRECOPT="$PERFRECMEM -e cs_etm//u" + +TOOLS=$(dirname $0) +DIR="$TOOLS/$TEST" +BIN="$DIR/$TEST" +# If the test tool/binary does not exist and is executable then skip the test +if ! test -x "$BIN"; then exit 2; fi +DATD="." +# If the data dir env is set then make the data dir use that instead of ./ +if test -n "$PERF_TEST_CORESIGHT_DATADIR"; then + DATD="$PERF_TEST_CORESIGHT_DATADIR"; +fi +# If the stat dir env is set then make the data dir use that instead of ./ +STATD="." +if test -n "$PERF_TEST_CORESIGHT_STATDIR"; then + STATD="$PERF_TEST_CORESIGHT_STATDIR"; +fi + +# Called if the test fails - error code 1 +err() { + echo "$1" + exit 1 +} + +# Check that some statistics from our perf +check_val_min() { + STATF="$4" + if test "$2" -lt "$3"; then + echo ", FAILED" >> "$STATF" + err "Sanity check number of $1 is too low ($2 < $3)" + fi +} + +perf_dump_aux_verify() { + # Some basic checking that the AUX chunk contains some sensible data + # to see that we are recording something and at least a minimum + # amount of it. We should almost always see Fn packets in just about + # anything but certainly we will see some trace info and async + # packets + DUMP="$DATD/perf-tmp-aux-dump.txt" + perf report --stdio --dump -i "$1" | \ + grep -o -e I_ATOM_F -e I_ASYNC -e I_TRACE_INFO > "$DUMP" + # Simply count how many of these packets we find to see that we are + # producing a reasonable amount of data - exact checks are not sane + # as this is a lossy process where we may lose some blocks and the + # compiler may produce different code depending on the compiler and + # optimization options, so this is rough just to see if we're + # either missing almost all the data or all of it + ATOM_FX_NUM=`grep I_ATOM_F "$DUMP" | wc -l` + ASYNC_NUM=`grep I_ASYNC "$DUMP" | wc -l` + TRACE_INFO_NUM=`grep I_TRACE_INFO "$DUMP" | wc -l` + rm -f "$DUMP" + + # Arguments provide minimums for a pass + CHECK_FX_MIN="$2" + CHECK_ASYNC_MIN="$3" + CHECK_TRACE_INFO_MIN="$4" + + # Write out statistics, so over time you can track results to see if + # there is a pattern - for example we have less "noisy" results that + # produce more consistent amounts of data each run, to see if over + # time any techinques to minimize data loss are having an effect or + # not + STATF="$STATD/stats-$TEST-$DATV.csv" + if ! test -f "$STATF"; then + echo "ATOM Fx Count, Minimum, ASYNC Count, Minimum, TRACE INFO Count, Minimum" > "$STATF" + fi + echo -n "$ATOM_FX_NUM, $CHECK_FX_MIN, $ASYNC_NUM, $CHECK_ASYNC_MIN, $TRACE_INFO_NUM, $CHECK_TRACE_INFO_MIN" >> "$STATF" + + # Actually check to see if we passed or failed. + check_val_min "ATOM_FX" "$ATOM_FX_NUM" "$CHECK_FX_MIN" "$STATF" + check_val_min "ASYNC" "$ASYNC_NUM" "$CHECK_ASYNC_MIN" "$STATF" + check_val_min "TRACE_INFO" "$TRACE_INFO_NUM" "$CHECK_TRACE_INFO_MIN" "$STATF" + echo ", Ok" >> "$STATF" +} + +perf_dump_aux_tid_verify() { + # Specifically crafted test will produce a list of Tread ID's to + # stdout that need to be checked to see that they have had trace + # info collected in AUX blocks in the perf data. This will go + # through all the TID's that are listed as CID=0xabcdef and see + # that all the Thread IDs the test tool reports are in the perf + # data AUX chunks + + # The TID test tools will print a TID per stdout line that are being + # tested + TIDS=`cat "$2"` + # Scan the perf report to find the TIDs that are actually CID in hex + # and build a list of the ones found + FOUND_TIDS=`perf report --stdio --dump -i "$1" | \ + grep -o "CID=0x[0-9a-z]\+" | sed 's/CID=//g' | \ + uniq | sort | uniq` + # No CID=xxx found - maybe your kernel is reporting these as + # VMID=xxx so look there + if test -z "$FOUND_TIDS"; then + FOUND_TIDS=`perf report --stdio --dump -i "$1" | \ + grep -o "VMID=0x[0-9a-z]\+" | sed 's/VMID=//g' | \ + uniq | sort | uniq` + fi + + # Iterate over the list of TIDs that the test says it has and find + # them in the TIDs found in the perf report + MISSING="" + for TID2 in $TIDS; do + FOUND="" + for TIDHEX in $FOUND_TIDS; do + TID=`printf "%i" $TIDHEX` + if test "$TID" -eq "$TID2"; then + FOUND="y" + break + fi + done + if test -z "$FOUND"; then + MISSING="$MISSING $TID" + fi + done + if test -n "$MISSING"; then + err "Thread IDs $MISSING not found in perf AUX data" + fi +} diff --git a/tools/perf/tests/shell/lib/perf_json_output_lint.py b/tools/perf/tests/shell/lib/perf_json_output_lint.py new file mode 100644 index 000000000000..d90f8d102eb9 --- /dev/null +++ b/tools/perf/tests/shell/lib/perf_json_output_lint.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +# Basic sanity check of perf JSON output as specified in the man page. + +import argparse +import sys +import json + +ap = argparse.ArgumentParser() +ap.add_argument('--no-args', action='store_true') +ap.add_argument('--interval', action='store_true') +ap.add_argument('--system-wide-no-aggr', action='store_true') +ap.add_argument('--system-wide', action='store_true') +ap.add_argument('--event', action='store_true') +ap.add_argument('--per-core', action='store_true') +ap.add_argument('--per-thread', action='store_true') +ap.add_argument('--per-die', action='store_true') +ap.add_argument('--per-node', action='store_true') +ap.add_argument('--per-socket', action='store_true') +args = ap.parse_args() + +Lines = sys.stdin.readlines() + +def isfloat(num): + try: + float(num) + return True + except ValueError: + return False + + +def isint(num): + try: + int(num) + return True + except ValueError: + return False + +def is_counter_value(num): + return isfloat(num) or num == '<not counted>' or num == '<not supported>' + +def check_json_output(expected_items): + if expected_items != -1: + for line in Lines: + if 'failed' not in line: + count = 0 + count = line.count(',') + if count != expected_items and count >= 1 and count <= 3 and 'metric-value' in line: + # Events that generate >1 metric may have isolated metric + # values and possibly other prefixes like interval, core and + # aggregate-number. + continue + if count != expected_items: + raise RuntimeError(f'wrong number of fields. counted {count} expected {expected_items}' + f' in \'{line}\'') + checks = { + 'aggregate-number': lambda x: isfloat(x), + 'core': lambda x: True, + 'counter-value': lambda x: is_counter_value(x), + 'cgroup': lambda x: True, + 'cpu': lambda x: isint(x), + 'die': lambda x: True, + 'event': lambda x: True, + 'event-runtime': lambda x: isfloat(x), + 'interval': lambda x: isfloat(x), + 'metric-unit': lambda x: True, + 'metric-value': lambda x: isfloat(x), + 'node': lambda x: True, + 'pcnt-running': lambda x: isfloat(x), + 'socket': lambda x: True, + 'thread': lambda x: True, + 'unit': lambda x: True, + } + input = '[\n' + ','.join(Lines) + '\n]' + for item in json.loads(input): + for key, value in item.items(): + if key not in checks: + raise RuntimeError(f'Unexpected key: key={key} value={value}') + if not checks[key](value): + raise RuntimeError(f'Check failed for: key={key} value={value}') + + +try: + if args.no_args or args.system_wide or args.event: + expected_items = 6 + elif args.interval or args.per_thread or args.system_wide_no_aggr: + expected_items = 7 + elif args.per_core or args.per_socket or args.per_node or args.per_die: + expected_items = 8 + else: + # If no option is specified, don't check the number of items. + expected_items = -1 + check_json_output(expected_items) +except: + print('Test failed for input:\n' + '\n'.join(Lines)) + raise diff --git a/tools/perf/tests/shell/lib/probe_vfs_getname.sh b/tools/perf/tests/shell/lib/probe_vfs_getname.sh index 5b17d916c555..b616d42bd19d 100644 --- a/tools/perf/tests/shell/lib/probe_vfs_getname.sh +++ b/tools/perf/tests/shell/lib/probe_vfs_getname.sh @@ -19,6 +19,6 @@ add_probe_vfs_getname() { } skip_if_no_debuginfo() { - add_probe_vfs_getname -v 2>&1 | egrep -q "^(Failed to find the path for the kernel|Debuginfo-analysis is not supported)" && return 2 + add_probe_vfs_getname -v 2>&1 | egrep -q "^(Failed to find the path for the kernel|Debuginfo-analysis is not supported)|(file has no debug information)" && return 2 return 1 } diff --git a/tools/perf/tests/shell/lib/waiting.sh b/tools/perf/tests/shell/lib/waiting.sh new file mode 100644 index 000000000000..e7a39134a68e --- /dev/null +++ b/tools/perf/tests/shell/lib/waiting.sh @@ -0,0 +1,77 @@ +# SPDX-License-Identifier: GPL-2.0 + +tenths=date\ +%s%1N + +# Wait for PID $1 to have $2 number of threads started +# Time out after $3 tenths of a second or 5 seconds if $3 is "" +wait_for_threads() +{ + tm_out=$3 ; [ -n "${tm_out}" ] || tm_out=50 + start_time=$($tenths) + while [ -e "/proc/$1/task" ] ; do + th_cnt=$(find "/proc/$1/task" -mindepth 1 -maxdepth 1 -printf x | wc -c) + if [ "${th_cnt}" -ge "$2" ] ; then + return 0 + fi + # Wait at most tm_out tenths of a second + if [ $(($($tenths) - start_time)) -ge $tm_out ] ; then + echo "PID $1 does not have $2 threads" + return 1 + fi + done + return 1 +} + +# Wait for perf record -vvv 2>$2 with PID $1 to start by looking at file $2 +# It depends on capturing perf record debug message "perf record has started" +# Time out after $3 tenths of a second or 5 seconds if $3 is "" +wait_for_perf_to_start() +{ + tm_out=$3 ; [ -n "${tm_out}" ] || tm_out=50 + echo "Waiting for \"perf record has started\" message" + start_time=$($tenths) + while [ -e "/proc/$1" ] ; do + if grep -q "perf record has started" "$2" ; then + echo OK + break + fi + # Wait at most tm_out tenths of a second + if [ $(($($tenths) - start_time)) -ge $tm_out ] ; then + echo "perf recording did not start" + return 1 + fi + done + return 0 +} + +# Wait for process PID %1 to exit +# Time out after $2 tenths of a second or 5 seconds if $2 is "" +wait_for_process_to_exit() +{ + tm_out=$2 ; [ -n "${tm_out}" ] || tm_out=50 + start_time=$($tenths) + while [ -e "/proc/$1" ] ; do + # Wait at most tm_out tenths of a second + if [ $(($($tenths) - start_time)) -ge $tm_out ] ; then + echo "PID $1 did not exit as expected" + return 1 + fi + done + return 0 +} + +# Check if PID $1 is still running after $2 tenths of a second +# or 0.3 seconds if $2 is "" +is_running() +{ + tm_out=$2 ; [ -n "${tm_out}" ] || tm_out=3 + start_time=$($tenths) + while [ -e "/proc/$1" ] ; do + # Check for at least tm_out tenths of a second + if [ $(($($tenths) - start_time)) -gt $tm_out ] ; then + return 0 + fi + done + echo "PID $1 exited prematurely" + return 1 +} diff --git a/tools/perf/tests/shell/lock_contention.sh b/tools/perf/tests/shell/lock_contention.sh new file mode 100755 index 000000000000..04bf604e3c6f --- /dev/null +++ b/tools/perf/tests/shell/lock_contention.sh @@ -0,0 +1,73 @@ +#!/bin/sh +# kernel lock contention analysis test +# SPDX-License-Identifier: GPL-2.0 + +set -e + +err=0 +perfdata=$(mktemp /tmp/__perf_test.perf.data.XXXXX) +result=$(mktemp /tmp/__perf_test.result.XXXXX) + +cleanup() { + rm -f ${perfdata} + rm -f ${result} + trap - exit term int +} + +trap_cleanup() { + cleanup + exit ${err} +} +trap trap_cleanup exit term int + +check() { + if [ `id -u` != 0 ]; then + echo "[Skip] No root permission" + err=2 + exit + fi + + if ! perf list | grep -q lock:contention_begin; then + echo "[Skip] No lock contention tracepoints" + err=2 + exit + fi +} + +test_record() +{ + echo "Testing perf lock record and perf lock contention" + perf lock record -o ${perfdata} -- perf bench sched messaging > /dev/null 2>&1 + # the output goes to the stderr and we expect only 1 output (-E 1) + perf lock contention -i ${perfdata} -E 1 -q 2> ${result} + if [ $(cat "${result}" | wc -l) != "1" ]; then + echo "[Fail] Recorded result count is not 1:" $(cat "${result}" | wc -l) + err=1 + exit + fi +} + +test_bpf() +{ + echo "Testing perf lock contention --use-bpf" + + if ! perf lock con -b true > /dev/null 2>&1 ; then + echo "[Skip] No BPF support" + exit + fi + + # the perf lock contention output goes to the stderr + perf lock con -a -b -E 1 -q -- perf bench sched messaging > /dev/null 2> ${result} + if [ $(cat "${result}" | wc -l) != "1" ]; then + echo "[Fail] BPF result count is not 1:" $(cat "${result}" | wc -l) + err=1 + exit + fi +} + +check + +test_record +test_bpf + +exit ${err} diff --git a/tools/perf/tests/shell/record.sh b/tools/perf/tests/shell/record.sh new file mode 100755 index 000000000000..301f95427159 --- /dev/null +++ b/tools/perf/tests/shell/record.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# perf record tests +# SPDX-License-Identifier: GPL-2.0 + +set -e + +err=0 +perfdata=$(mktemp /tmp/__perf_test.perf.data.XXXXX) + +cleanup() { + rm -f ${perfdata} + rm -f ${perfdata}.old + trap - exit term int +} + +trap_cleanup() { + cleanup + exit 1 +} +trap trap_cleanup exit term int + +test_per_thread() { + echo "Basic --per-thread mode test" + if ! perf record -e instructions:u -o ${perfdata} --quiet true 2> /dev/null + then + echo "Per-thread record [Skipped instructions:u not supported]" + if [ $err -ne 1 ] + then + err=2 + fi + return + fi + if ! perf record -e instructions:u --per-thread -o ${perfdata} true 2> /dev/null + then + echo "Per-thread record of instructions:u [Failed]" + err=1 + return + fi + if ! perf report -i ${perfdata} -q | egrep -q true + then + echo "Per-thread record [Failed missing output]" + err=1 + return + fi + echo "Basic --per-thread mode test [Success]" +} + +test_register_capture() { + echo "Register capture test" + if ! perf list | egrep -q 'br_inst_retired.near_call' + then + echo "Register capture test [Skipped missing instruction]" + if [ $err -ne 1 ] + then + err=2 + fi + return + fi + if ! perf record --intr-regs=\? 2>&1 | egrep -q 'available registers: AX BX CX DX SI DI BP SP IP FLAGS CS SS R8 R9 R10 R11 R12 R13 R14 R15' + then + echo "Register capture test [Skipped missing registers]" + return + fi + if ! perf record -o - --intr-regs=di,r8,dx,cx -e br_inst_retired.near_call:p \ + -c 1000 --per-thread true 2> /dev/null \ + | perf script -F ip,sym,iregs -i - 2> /dev/null \ + | egrep -q "DI:" + then + echo "Register capture test [Failed missing output]" + err=1 + return + fi + echo "Register capture test [Success]" +} + +test_per_thread +test_register_capture + +cleanup +exit $err diff --git a/tools/perf/tests/shell/record_offcpu.sh b/tools/perf/tests/shell/record_offcpu.sh new file mode 100755 index 000000000000..d2eba583a2ac --- /dev/null +++ b/tools/perf/tests/shell/record_offcpu.sh @@ -0,0 +1,103 @@ +#!/bin/sh +# perf record offcpu profiling tests +# SPDX-License-Identifier: GPL-2.0 + +set -e + +err=0 +perfdata=$(mktemp /tmp/__perf_test.perf.data.XXXXX) + +cleanup() { + rm -f ${perfdata} + rm -f ${perfdata}.old + trap - exit term int +} + +trap_cleanup() { + cleanup + exit 1 +} +trap trap_cleanup exit term int + +test_offcpu_priv() { + echo "Checking off-cpu privilege" + + if [ `id -u` != 0 ] + then + echo "off-cpu test [Skipped permission]" + err=2 + return + fi + if perf record --off-cpu -o /dev/null --quiet true 2>&1 | grep BUILD_BPF_SKEL + then + echo "off-cpu test [Skipped missing BPF support]" + err=2 + return + fi +} + +test_offcpu_basic() { + echo "Basic off-cpu test" + + if ! perf record --off-cpu -e dummy -o ${perfdata} sleep 1 2> /dev/null + then + echo "Basic off-cpu test [Failed record]" + err=1 + return + fi + if ! perf evlist -i ${perfdata} | grep -q "offcpu-time" + then + echo "Basic off-cpu test [Failed no event]" + err=1 + return + fi + if ! perf report -i ${perfdata} -q --percent-limit=90 | egrep -q sleep + then + echo "Basic off-cpu test [Failed missing output]" + err=1 + return + fi + echo "Basic off-cpu test [Success]" +} + +test_offcpu_child() { + echo "Child task off-cpu test" + + # perf bench sched messaging creates 400 processes + if ! perf record --off-cpu -e dummy -o ${perfdata} -- \ + perf bench sched messaging -g 10 > /dev/null 2&>1 + then + echo "Child task off-cpu test [Failed record]" + err=1 + return + fi + if ! perf evlist -i ${perfdata} | grep -q "offcpu-time" + then + echo "Child task off-cpu test [Failed no event]" + err=1 + return + fi + # each process waits for read and write, so it should be more than 800 events + if ! perf report -i ${perfdata} -s comm -q -n -t ';' --percent-limit=90 | \ + awk -F ";" '{ if (NF > 3 && int($3) < 800) exit 1; }' + then + echo "Child task off-cpu test [Failed invalid output]" + err=1 + return + fi + echo "Child task off-cpu test [Success]" +} + + +test_offcpu_priv + +if [ $err = 0 ]; then + test_offcpu_basic +fi + +if [ $err = 0 ]; then + test_offcpu_child +fi + +cleanup +exit $err diff --git a/tools/perf/tests/shell/stat+csv_output.sh b/tools/perf/tests/shell/stat+csv_output.sh new file mode 100755 index 000000000000..b7f050aa6210 --- /dev/null +++ b/tools/perf/tests/shell/stat+csv_output.sh @@ -0,0 +1,204 @@ +#!/bin/bash +# perf stat CSV output linter +# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +# Tests various perf stat CSV output commands for the +# correct number of fields and the CSV separator set to ','. + +set -e + +skip_test=0 + +function commachecker() +{ + local -i cnt=0 + local exp=0 + + case "$1" + in "--no-args") exp=6 + ;; "--system-wide") exp=6 + ;; "--event") exp=6 + ;; "--interval") exp=7 + ;; "--per-thread") exp=7 + ;; "--system-wide-no-aggr") exp=7 + [ $(uname -m) = "s390x" ] && exp='^[6-7]$' + ;; "--per-core") exp=8 + ;; "--per-socket") exp=8 + ;; "--per-node") exp=8 + ;; "--per-die") exp=8 + esac + + while read line + do + # Check for lines beginning with Failed + x=${line:0:6} + [ "$x" = "Failed" ] && continue + + # Count the number of commas + x=$(echo $line | tr -d -c ',') + cnt="${#x}" + # echo $line $cnt + [[ ! "$cnt" =~ $exp ]] && { + echo "wrong number of fields. expected $exp in $line" 1>&2 + exit 1; + } + done + return 0 +} + +# Return true if perf_event_paranoid is > $1 and not running as root. +function ParanoidAndNotRoot() +{ + [ $(id -u) != 0 ] && [ $(cat /proc/sys/kernel/perf_event_paranoid) -gt $1 ] +} + +check_no_args() +{ + echo -n "Checking CSV output: no args " + perf stat -x, true 2>&1 | commachecker --no-args + echo "[Success]" +} + +check_system_wide() +{ + echo -n "Checking CSV output: system wide " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, -a true 2>&1 | commachecker --system-wide + echo "[Success]" +} + +check_system_wide_no_aggr() +{ + echo -n "Checking CSV output: system wide " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + echo -n "Checking CSV output: system wide no aggregation " + perf stat -x, -A -a --no-merge true 2>&1 | commachecker --system-wide-no-aggr + echo "[Success]" +} + +check_interval() +{ + echo -n "Checking CSV output: interval " + perf stat -x, -I 1000 true 2>&1 | commachecker --interval + echo "[Success]" +} + + +check_event() +{ + echo -n "Checking CSV output: event " + perf stat -x, -e cpu-clock true 2>&1 | commachecker --event + echo "[Success]" +} + +check_per_core() +{ + echo -n "Checking CSV output: per core " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, --per-core -a true 2>&1 | commachecker --per-core + echo "[Success]" +} + +check_per_thread() +{ + echo -n "Checking CSV output: per thread " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, --per-thread -a true 2>&1 | commachecker --per-thread + echo "[Success]" +} + +check_per_die() +{ + echo -n "Checking CSV output: per die " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, --per-die -a true 2>&1 | commachecker --per-die + echo "[Success]" +} + +check_per_node() +{ + echo -n "Checking CSV output: per node " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, --per-node -a true 2>&1 | commachecker --per-node + echo "[Success]" +} + +check_per_socket() +{ + echo -n "Checking CSV output: per socket " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoid and not root" + return + fi + perf stat -x, --per-socket -a true 2>&1 | commachecker --per-socket + echo "[Success]" +} + +# The perf stat options for per-socket, per-core, per-die +# and -A ( no_aggr mode ) uses the info fetched from this +# directory: "/sys/devices/system/cpu/cpu*/topology". For +# example, socket value is fetched from "physical_package_id" +# file in topology directory. +# Reference: cpu__get_topology_int in util/cpumap.c +# If the platform doesn't expose topology information, values +# will be set to -1. For example, incase of pSeries platform +# of powerpc, value for "physical_package_id" is restricted +# and set to -1. Check here validates the socket-id read from +# topology file before proceeding further + +FILE_LOC="/sys/devices/system/cpu/cpu*/topology/" +FILE_NAME="physical_package_id" + +check_for_topology() +{ + if ! ParanoidAndNotRoot 0 + then + socket_file=`ls $FILE_LOC/$FILE_NAME | head -n 1` + [ -z $socket_file ] && return 0 + socket_id=`cat $socket_file` + [ $socket_id == -1 ] && skip_test=1 + return 0 + fi +} + +check_for_topology +check_no_args +check_system_wide +check_interval +check_event +check_per_thread +check_per_node +if [ $skip_test -ne 1 ] +then + check_system_wide_no_aggr + check_per_core + check_per_die + check_per_socket +else + echo "[Skip] Skipping tests for system_wide_no_aggr, per_core, per_die and per_socket since socket id exposed via topology is invalid" +fi +exit 0 diff --git a/tools/perf/tests/shell/stat+json_output.sh b/tools/perf/tests/shell/stat+json_output.sh new file mode 100755 index 000000000000..2c4212c641ed --- /dev/null +++ b/tools/perf/tests/shell/stat+json_output.sh @@ -0,0 +1,182 @@ +#!/bin/bash +# perf stat JSON output linter +# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +# Checks various perf stat JSON output commands for the +# correct number of fields. + +set -e + +skip_test=0 + +pythonchecker=$(dirname $0)/lib/perf_json_output_lint.py +if [ "x$PYTHON" == "x" ] +then + if which python3 > /dev/null + then + PYTHON=python3 + elif which python > /dev/null + then + PYTHON=python + else + echo Skipping test, python not detected please set environment variable PYTHON. + exit 2 + fi +fi + +# Return true if perf_event_paranoid is > $1 and not running as root. +function ParanoidAndNotRoot() +{ + [ $(id -u) != 0 ] && [ $(cat /proc/sys/kernel/perf_event_paranoid) -gt $1 ] +} + +check_no_args() +{ + echo -n "Checking json output: no args " + perf stat -j true 2>&1 | $PYTHON $pythonchecker --no-args + echo "[Success]" +} + +check_system_wide() +{ + echo -n "Checking json output: system wide " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j -a true 2>&1 | $PYTHON $pythonchecker --system-wide + echo "[Success]" +} + +check_system_wide_no_aggr() +{ + echo -n "Checking json output: system wide " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + echo -n "Checking json output: system wide no aggregation " + perf stat -j -A -a --no-merge true 2>&1 | $PYTHON $pythonchecker --system-wide-no-aggr + echo "[Success]" +} + +check_interval() +{ + echo -n "Checking json output: interval " + perf stat -j -I 1000 true 2>&1 | $PYTHON $pythonchecker --interval + echo "[Success]" +} + + +check_event() +{ + echo -n "Checking json output: event " + perf stat -j -e cpu-clock true 2>&1 | $PYTHON $pythonchecker --event + echo "[Success]" +} + +check_per_core() +{ + echo -n "Checking json output: per core " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j --per-core -a true 2>&1 | $PYTHON $pythonchecker --per-core + echo "[Success]" +} + +check_per_thread() +{ + echo -n "Checking json output: per thread " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j --per-thread -a true 2>&1 | $PYTHON $pythonchecker --per-thread + echo "[Success]" +} + +check_per_die() +{ + echo -n "Checking json output: per die " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j --per-die -a true 2>&1 | $PYTHON $pythonchecker --per-die + echo "[Success]" +} + +check_per_node() +{ + echo -n "Checking json output: per node " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j --per-node -a true 2>&1 | $PYTHON $pythonchecker --per-node + echo "[Success]" +} + +check_per_socket() +{ + echo -n "Checking json output: per socket " + if ParanoidAndNotRoot 0 + then + echo "[Skip] paranoia and not root" + return + fi + perf stat -j --per-socket -a true 2>&1 | $PYTHON $pythonchecker --per-socket + echo "[Success]" +} + +# The perf stat options for per-socket, per-core, per-die +# and -A ( no_aggr mode ) uses the info fetched from this +# directory: "/sys/devices/system/cpu/cpu*/topology". For +# example, socket value is fetched from "physical_package_id" +# file in topology directory. +# Reference: cpu__get_topology_int in util/cpumap.c +# If the platform doesn't expose topology information, values +# will be set to -1. For example, incase of pSeries platform +# of powerpc, value for "physical_package_id" is restricted +# and set to -1. Check here validates the socket-id read from +# topology file before proceeding further + +FILE_LOC="/sys/devices/system/cpu/cpu*/topology/" +FILE_NAME="physical_package_id" + +check_for_topology() +{ + if ! ParanoidAndNotRoot 0 + then + socket_file=`ls $FILE_LOC/$FILE_NAME | head -n 1` + [ -z $socket_file ] && return 0 + socket_id=`cat $socket_file` + [ $socket_id == -1 ] && skip_test=1 + return 0 + fi +} + +check_for_topology +check_no_args +check_system_wide +check_interval +check_event +check_per_thread +check_per_node +if [ $skip_test -ne 1 ] +then + check_system_wide_no_aggr + check_per_core + check_per_die + check_per_socket +else + echo "[Skip] Skipping tests for system_wide_no_aggr, per_core, per_die and per_socket since socket id exposed via topology is invalid" +fi +exit 0 diff --git a/tools/perf/tests/shell/stat.sh b/tools/perf/tests/shell/stat.sh new file mode 100755 index 000000000000..26a51b48aee4 --- /dev/null +++ b/tools/perf/tests/shell/stat.sh @@ -0,0 +1,99 @@ +#!/bin/sh +# perf stat tests +# SPDX-License-Identifier: GPL-2.0 + +set -e + +err=0 +test_default_stat() { + echo "Basic stat command test" + if ! perf stat true 2>&1 | egrep -q "Performance counter stats for 'true':" + then + echo "Basic stat command test [Failed]" + err=1 + return + fi + echo "Basic stat command test [Success]" +} + +test_stat_record_report() { + echo "stat record and report test" + if ! perf stat record -o - true | perf stat report -i - 2>&1 | \ + egrep -q "Performance counter stats for 'pipe':" + then + echo "stat record and report test [Failed]" + err=1 + return + fi + echo "stat record and report test [Success]" +} + +test_stat_repeat_weak_groups() { + echo "stat repeat weak groups test" + if ! perf stat -e '{cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles}' \ + true 2>&1 | grep -q 'seconds time elapsed' + then + echo "stat repeat weak groups test [Skipped event parsing failed]" + return + fi + if ! perf stat -r2 -e '{cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles,cycles}:W' \ + true > /dev/null 2>&1 + then + echo "stat repeat weak groups test [Failed]" + err=1 + return + fi + echo "stat repeat weak groups test [Success]" +} + +test_topdown_groups() { + # Topdown events must be grouped with the slots event first. Test that + # parse-events reorders this. + echo "Topdown event group test" + if ! perf stat -e '{slots,topdown-retiring}' true > /dev/null 2>&1 + then + echo "Topdown event group test [Skipped event parsing failed]" + return + fi + if perf stat -e '{slots,topdown-retiring}' true 2>&1 | egrep -q "<not supported>" + then + echo "Topdown event group test [Failed events not supported]" + err=1 + return + fi + if perf stat -e '{topdown-retiring,slots}' true 2>&1 | egrep -q "<not supported>" + then + echo "Topdown event group test [Failed slots not reordered first]" + err=1 + return + fi + echo "Topdown event group test [Success]" +} + +test_topdown_weak_groups() { + # Weak groups break if the perf_event_open of multiple grouped events + # fails. Breaking a topdown group causes the events to fail. Test a very large + # grouping to see that the topdown events aren't broken out. + echo "Topdown weak groups test" + ok_grouping="{slots,topdown-bad-spec,topdown-be-bound,topdown-fe-bound,topdown-retiring},branch-instructions,branch-misses,bus-cycles,cache-misses,cache-references,cpu-cycles,instructions,mem-loads,mem-stores,ref-cycles,cache-misses,cache-references" + if ! perf stat --no-merge -e "$ok_grouping" true > /dev/null 2>&1 + then + echo "Topdown weak groups test [Skipped event parsing failed]" + return + fi + group_needs_break="{slots,topdown-bad-spec,topdown-be-bound,topdown-fe-bound,topdown-retiring,branch-instructions,branch-misses,bus-cycles,cache-misses,cache-references,cpu-cycles,instructions,mem-loads,mem-stores,ref-cycles,cache-misses,cache-references}:W" + if perf stat --no-merge -e "$group_needs_break" true 2>&1 | egrep -q "<not supported>" + then + echo "Topdown weak groups test [Failed events not supported]" + err=1 + return + fi + echo "Topdown weak groups test [Success]" +} + +test_default_stat +test_stat_record_report +test_stat_repeat_weak_groups +test_topdown_groups +test_topdown_weak_groups +exit $err diff --git a/tools/perf/tests/shell/stat_all_metricgroups.sh b/tools/perf/tests/shell/stat_all_metricgroups.sh index de24d374ce24..cb35e488809a 100755 --- a/tools/perf/tests/shell/stat_all_metricgroups.sh +++ b/tools/perf/tests/shell/stat_all_metricgroups.sh @@ -6,7 +6,7 @@ set -e for m in $(perf list --raw-dump metricgroups); do echo "Testing $m" - perf stat -M "$m" true + perf stat -M "$m" -a true done exit 0 diff --git a/tools/perf/tests/shell/stat_all_metrics.sh b/tools/perf/tests/shell/stat_all_metrics.sh index 7f4ba3cad632..6e79349e42be 100755 --- a/tools/perf/tests/shell/stat_all_metrics.sh +++ b/tools/perf/tests/shell/stat_all_metrics.sh @@ -1,22 +1,43 @@ -#!/bin/sh +#!/bin/bash # perf all metrics test # SPDX-License-Identifier: GPL-2.0 -set -e - +err=0 for m in $(perf list --raw-dump metrics); do echo "Testing $m" result=$(perf stat -M "$m" true 2>&1) - if [[ ! "$result" =~ "$m" ]] && [[ ! "$result" =~ "<not supported>" ]]; then - # We failed to see the metric and the events are support. Possibly the - # workload was too small so retry with something longer. - result=$(perf stat -M "$m" perf bench internals synthesize 2>&1) - if [[ ! "$result" =~ "$m" ]]; then - echo "Metric '$m' not printed in:" - echo "$result" - exit 1 + if [[ "$result" =~ "${m:0:50}" ]] || [[ "$result" =~ "<not supported>" ]] + then + continue + fi + # Failed so try system wide. + result=$(perf stat -M "$m" -a true 2>&1) + if [[ "$result" =~ "${m:0:50}" ]] + then + continue + fi + # Failed again, possibly the workload was too small so retry with something + # longer. + result=$(perf stat -M "$m" perf bench internals synthesize 2>&1) + if [[ "$result" =~ "${m:0:50}" ]] + then + continue + fi + echo "Metric '$m' not printed in:" + echo "$result" + if [[ "$err" != "1" ]] + then + err=2 + if [[ "$result" =~ "FP_ARITH" || "$result" =~ "AMX" ]] + then + echo "Skip, not fail, for FP issues" + elif [[ "$result" =~ "PMM" ]] + then + echo "Skip, not fail, for Optane memory issues" + else + err=1 fi fi done -exit 0 +exit "$err" diff --git a/tools/perf/tests/shell/stat_all_pmu.sh b/tools/perf/tests/shell/stat_all_pmu.sh index b30dba455f36..9c9ef33e0b3c 100755 --- a/tools/perf/tests/shell/stat_all_pmu.sh +++ b/tools/perf/tests/shell/stat_all_pmu.sh @@ -5,6 +5,16 @@ set -e for p in $(perf list --raw-dump pmu); do + # In powerpc, skip the events for hv_24x7 and hv_gpci. + # These events needs input values to be filled in for + # core, chip, partition id based on system. + # Example: hv_24x7/CPM_ADJUNCT_INST,domain=?,core=?/ + # hv_gpci/event,partition_id=?/ + # Hence skip these events for ppc. + if echo "$p" |grep -Eq 'hv_24x7|hv_gpci' ; then + echo "Skipping: Event '$p' in powerpc" + continue + fi echo "Testing $p" result=$(perf stat -e "$p" true 2>&1) if ! echo "$result" | grep -q "$p" && ! echo "$result" | grep -q "<not supported>" ; then diff --git a/tools/perf/tests/shell/stat_bpf_counters_cgrp.sh b/tools/perf/tests/shell/stat_bpf_counters_cgrp.sh new file mode 100755 index 000000000000..d724855d097c --- /dev/null +++ b/tools/perf/tests/shell/stat_bpf_counters_cgrp.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# perf stat --bpf-counters --for-each-cgroup test +# SPDX-License-Identifier: GPL-2.0 + +set -e + +test_cgroups= +if [ "$1" = "-v" ]; then + verbose="1" +fi + +# skip if --bpf-counters --for-each-cgroup is not supported +check_bpf_counter() +{ + if ! perf stat -a --bpf-counters --for-each-cgroup / true > /dev/null 2>&1; then + if [ "${verbose}" = "1" ]; then + echo "Skipping: --bpf-counters --for-each-cgroup not supported" + perf --no-pager stat -a --bpf-counters --for-each-cgroup / true || true + fi + exit 2 + fi +} + +# find two cgroups to measure +find_cgroups() +{ + # try usual systemd slices first + if [ -d /sys/fs/cgroup/system.slice -a -d /sys/fs/cgroup/user.slice ]; then + test_cgroups="system.slice,user.slice" + return + fi + + # try root and self cgroups + local self_cgrp=$(grep perf_event /proc/self/cgroup | cut -d: -f3) + if [ -z ${self_cgrp} ]; then + # cgroup v2 doesn't specify perf_event + self_cgrp=$(grep ^0: /proc/self/cgroup | cut -d: -f3) + fi + + if [ -z ${self_cgrp} ]; then + test_cgroups="/" + else + test_cgroups="/,${self_cgrp}" + fi +} + +# As cgroup events are cpu-wide, we cannot simply compare the result. +# Just check if it runs without failure and has non-zero results. +check_system_wide_counted() +{ + local output + + output=$(perf stat -a --bpf-counters --for-each-cgroup ${test_cgroups} -e cpu-clock -x, sleep 1 2>&1) + if echo ${output} | grep -q -F "<not "; then + echo "Some system-wide events are not counted" + if [ "${verbose}" = "1" ]; then + echo ${output} + fi + exit 1 + fi +} + +check_cpu_list_counted() +{ + local output + + output=$(perf stat -C 1 --bpf-counters --for-each-cgroup ${test_cgroups} -e cpu-clock -x, taskset -c 1 sleep 1 2>&1) + if echo ${output} | grep -q -F "<not "; then + echo "Some CPU events are not counted" + if [ "${verbose}" = "1" ]; then + echo ${output} + fi + exit 1 + fi +} + +check_bpf_counter +find_cgroups + +check_system_wide_counted +check_cpu_list_counted + +exit 0 diff --git a/tools/perf/tests/shell/test_arm_callgraph_fp.sh b/tools/perf/tests/shell/test_arm_callgraph_fp.sh new file mode 100755 index 000000000000..ec108d45d3c6 --- /dev/null +++ b/tools/perf/tests/shell/test_arm_callgraph_fp.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# Check Arm64 callgraphs are complete in fp mode +# SPDX-License-Identifier: GPL-2.0 + +lscpu | grep -q "aarch64" || exit 2 + +if ! [ -x "$(command -v cc)" ]; then + echo "failed: no compiler, install gcc" + exit 2 +fi + +PERF_DATA=$(mktemp /tmp/__perf_test.perf.data.XXXXX) +TEST_PROGRAM_SOURCE=$(mktemp /tmp/test_program.XXXXX.c) +TEST_PROGRAM=$(mktemp /tmp/test_program.XXXXX) + +cleanup_files() +{ + rm -f $PERF_DATA + rm -f $TEST_PROGRAM_SOURCE + rm -f $TEST_PROGRAM +} + +trap cleanup_files exit term int + +cat << EOF > $TEST_PROGRAM_SOURCE +int a = 0; +void leaf(void) { + for (;;) + a += a; +} +void parent(void) { + leaf(); +} +int main(void) { + parent(); + return 0; +} +EOF + +echo " + Compiling test program ($TEST_PROGRAM)..." + +CFLAGS="-g -O0 -fno-inline -fno-omit-frame-pointer" +cc $CFLAGS $TEST_PROGRAM_SOURCE -o $TEST_PROGRAM || exit 1 + +# Add a 1 second delay to skip samples that are not in the leaf() function +perf record -o $PERF_DATA --call-graph fp -e cycles//u -D 1000 --user-callchains -- $TEST_PROGRAM 2> /dev/null & +PID=$! + +echo " + Recording (PID=$PID)..." +sleep 2 +echo " + Stopping perf-record..." + +kill $PID +wait $PID + +# expected perf-script output: +# +# program +# 728 leaf +# 753 parent +# 76c main +# ... + +perf script -i $PERF_DATA -F comm,ip,sym | head -n4 +perf script -i $PERF_DATA -F comm,ip,sym | head -n4 | \ + awk '{ if ($2 != "") sym[i++] = $2 } END { if (sym[0] != "leaf" || + sym[1] != "parent" || + sym[2] != "main") exit 1 }' diff --git a/tools/perf/tests/shell/test_arm_coresight.sh b/tools/perf/tests/shell/test_arm_coresight.sh index 6de53b7ef5ff..daad786cf48d 100755 --- a/tools/perf/tests/shell/test_arm_coresight.sh +++ b/tools/perf/tests/shell/test_arm_coresight.sh @@ -29,7 +29,6 @@ cleanup_files() rm -f ${file} rm -f "${perfdata}.old" trap - exit term int - kill -2 $$ exit $glb_err } @@ -71,7 +70,7 @@ perf_report_instruction_samples() { # 68.12% touch libc-2.27.so [.] _dl_addr # 5.80% touch libc-2.27.so [.] getenv # 4.35% touch ld-2.27.so [.] _dl_fixup - perf report --itrace=i1000i --stdio -i ${perfdata} 2>&1 | \ + perf report --itrace=i20i --stdio -i ${perfdata} 2>&1 | \ egrep " +[0-9]+\.[0-9]+% +$1" > /dev/null 2>&1 } diff --git a/tools/perf/tests/shell/test_arm_spe.sh b/tools/perf/tests/shell/test_arm_spe.sh index e59044edc406..0d47479adba8 100755 --- a/tools/perf/tests/shell/test_arm_spe.sh +++ b/tools/perf/tests/shell/test_arm_spe.sh @@ -23,17 +23,20 @@ glb_err=0 cleanup_files() { rm -f ${perfdata} + rm -f ${perfdata}.old exit $glb_err } trap cleanup_files exit term int arm_spe_report() { - if [ $2 != 0 ]; then + if [ $2 = 0 ]; then + echo "$1: PASS" + elif [ $2 = 2 ]; then + echo "$1: SKIPPED" + else echo "$1: FAIL" glb_err=$2 - else - echo "$1: PASS" fi } @@ -85,5 +88,26 @@ arm_spe_snapshot_test() { arm_spe_report "SPE snapshot testing" $err } +arm_spe_system_wide_test() { + echo "Recording trace with system-wide mode $perfdata" + + perf record -o - -e dummy -a -B true > /dev/null 2>&1 + if [ $? != 0 ]; then + arm_spe_report "SPE system-wide testing" 2 + return + fi + + perf record -o ${perfdata} -e arm_spe// -a --no-bpf-event \ + -- dd if=/dev/zero of=/dev/null count=100000 > /dev/null 2>&1 + + perf_script_samples dd && + perf_report_samples dd + + err=$? + arm_spe_report "SPE system-wide testing" $err +} + arm_spe_snapshot_test +arm_spe_system_wide_test + exit $glb_err diff --git a/tools/perf/tests/shell/test_arm_spe_fork.sh b/tools/perf/tests/shell/test_arm_spe_fork.sh new file mode 100755 index 000000000000..c920d3583d30 --- /dev/null +++ b/tools/perf/tests/shell/test_arm_spe_fork.sh @@ -0,0 +1,92 @@ +#!/bin/sh +# Check Arm SPE doesn't hang when there are forks + +# SPDX-License-Identifier: GPL-2.0 +# German Gomez <german.gomez@arm.com>, 2022 + +skip_if_no_arm_spe_event() { + perf list | egrep -q 'arm_spe_[0-9]+//' && return 0 + return 2 +} + +skip_if_no_arm_spe_event || exit 2 + +# skip if there's no compiler +if ! [ -x "$(command -v cc)" ]; then + echo "failed: no compiler, install gcc" + exit 2 +fi + +TEST_PROGRAM_SOURCE=$(mktemp /tmp/__perf_test.program.XXXXX.c) +TEST_PROGRAM=$(mktemp /tmp/__perf_test.program.XXXXX) +PERF_DATA=$(mktemp /tmp/__perf_test.perf.data.XXXXX) +PERF_RECORD_LOG=$(mktemp /tmp/__perf_test.log.XXXXX) + +cleanup_files() +{ + echo "Cleaning up files..." + rm -f ${PERF_RECORD_LOG} + rm -f ${PERF_DATA} + rm -f ${TEST_PROGRAM_SOURCE} + rm -f ${TEST_PROGRAM} +} + +trap cleanup_files exit term int + +# compile test program +cat << EOF > $TEST_PROGRAM_SOURCE +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/wait.h> + +int workload() { + while (1) + sqrt(rand()); + return 0; +} + +int main() { + switch (fork()) { + case 0: + return workload(); + case -1: + return 1; + default: + wait(NULL); + } + return 0; +} +EOF + +echo "Compiling test program..." +CFLAGS="-lm" +cc $TEST_PROGRAM_SOURCE $CFLAGS -o $TEST_PROGRAM || exit 1 + +echo "Recording workload..." +perf record -o ${PERF_DATA} -e arm_spe/period=65536/ -vvv -- $TEST_PROGRAM > ${PERF_RECORD_LOG} 2>&1 & +PERFPID=$! + +# Check if perf hangs by checking the perf-record logs. +sleep 1 +log0=$(wc -l $PERF_RECORD_LOG) +echo Log lines = $log0 +sleep 1 +log1=$(wc -l $PERF_RECORD_LOG) +echo Log lines after 1 second = $log1 + +kill $PERFPID +wait $PERFPID +# test program may leave an orphan process running the workload +killall $(basename $TEST_PROGRAM) + +if [ "$log0" = "$log1" ]; +then + echo "SPE hang test: FAIL" + exit 1 +else + echo "SPE hang test: PASS" +fi + +exit 0 diff --git a/tools/perf/tests/shell/test_brstack.sh b/tools/perf/tests/shell/test_brstack.sh new file mode 100755 index 000000000000..d7ff5c4b4da4 --- /dev/null +++ b/tools/perf/tests/shell/test_brstack.sh @@ -0,0 +1,118 @@ +#!/bin/sh +# Check branch stack sampling + +# SPDX-License-Identifier: GPL-2.0 +# German Gomez <german.gomez@arm.com>, 2022 + +# we need a C compiler to build the test programs +# so bail if none is found +if ! [ -x "$(command -v cc)" ]; then + echo "failed: no compiler, install gcc" + exit 2 +fi + +# skip the test if the hardware doesn't support branch stack sampling +# and if the architecture doesn't support filter types: any,save_type,u +if ! perf record -o- --no-buildid --branch-filter any,save_type,u -- true > /dev/null 2>&1 ; then + echo "skip: system doesn't support filter types: any,save_type,u" + exit 2 +fi + +TMPDIR=$(mktemp -d /tmp/__perf_test.program.XXXXX) + +cleanup() { + rm -rf $TMPDIR +} + +trap cleanup exit term int + +gen_test_program() { + # generate test program + cat << EOF > $1 +#define BENCH_RUNS 999999 +int cnt; +void bar(void) { +} /* return */ +void foo(void) { + bar(); /* call */ +} /* return */ +void bench(void) { + void (*foo_ind)(void) = foo; + if ((cnt++) % 3) /* branch (cond) */ + foo(); /* call */ + bar(); /* call */ + foo_ind(); /* call (ind) */ +} +int main(void) +{ + int cnt = 0; + while (1) { + if ((cnt++) > BENCH_RUNS) + break; + bench(); /* call */ + } /* branch (uncond) */ + return 0; +} +EOF +} + +test_user_branches() { + echo "Testing user branch stack sampling" + + gen_test_program "$TEMPDIR/program.c" + cc -fno-inline -g "$TEMPDIR/program.c" -o $TMPDIR/a.out + + perf record -o $TMPDIR/perf.data --branch-filter any,save_type,u -- $TMPDIR/a.out > /dev/null 2>&1 + perf script -i $TMPDIR/perf.data --fields brstacksym | xargs -n1 > $TMPDIR/perf.script + + # example of branch entries: + # foo+0x14/bar+0x40/P/-/-/0/CALL + + set -x + egrep -m1 "^bench\+[^ ]*/foo\+[^ ]*/IND_CALL$" $TMPDIR/perf.script + egrep -m1 "^foo\+[^ ]*/bar\+[^ ]*/CALL$" $TMPDIR/perf.script + egrep -m1 "^bench\+[^ ]*/foo\+[^ ]*/CALL$" $TMPDIR/perf.script + egrep -m1 "^bench\+[^ ]*/bar\+[^ ]*/CALL$" $TMPDIR/perf.script + egrep -m1 "^bar\+[^ ]*/foo\+[^ ]*/RET$" $TMPDIR/perf.script + egrep -m1 "^foo\+[^ ]*/bench\+[^ ]*/RET$" $TMPDIR/perf.script + egrep -m1 "^bench\+[^ ]*/bench\+[^ ]*/COND$" $TMPDIR/perf.script + egrep -m1 "^main\+[^ ]*/main\+[^ ]*/UNCOND$" $TMPDIR/perf.script + set +x + + # some branch types are still not being tested: + # IND COND_CALL COND_RET SYSCALL SYSRET IRQ SERROR NO_TX +} + +# first argument <arg0> is the argument passed to "--branch-stack <arg0>,save_type,u" +# second argument are the expected branch types for the given filter +test_filter() { + local filter=$1 + local expect=$2 + + echo "Testing branch stack filtering permutation ($filter,$expect)" + + gen_test_program "$TEMPDIR/program.c" + cc -fno-inline -g "$TEMPDIR/program.c" -o $TMPDIR/a.out + + perf record -o $TMPDIR/perf.data --branch-filter $filter,save_type,u -- $TMPDIR/a.out > /dev/null 2>&1 + perf script -i $TMPDIR/perf.data --fields brstack | xargs -n1 > $TMPDIR/perf.script + + # fail if we find any branch type that doesn't match any of the expected ones + # also consider UNKNOWN branch types (-) + if egrep -vm1 "^[^ ]*/($expect|-|( *))$" $TMPDIR/perf.script; then + return 1 + fi +} + +set -e + +test_user_branches + +test_filter "any_call" "CALL|IND_CALL|COND_CALL|SYSCALL|IRQ" +test_filter "call" "CALL|SYSCALL" +test_filter "cond" "COND" +test_filter "any_ret" "RET|COND_RET|SYSRET|ERET" + +test_filter "call,cond" "CALL|SYSCALL|COND" +test_filter "any_call,cond" "CALL|IND_CALL|COND_CALL|IRQ|SYSCALL|COND" +test_filter "cond,any_call,any_ret" "COND|CALL|IND_CALL|COND_CALL|SYSCALL|IRQ|RET|COND_RET|SYSRET|ERET" diff --git a/tools/perf/tests/shell/test_data_symbol.sh b/tools/perf/tests/shell/test_data_symbol.sh new file mode 100755 index 000000000000..cd6eb54d235d --- /dev/null +++ b/tools/perf/tests/shell/test_data_symbol.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# Test data symbol + +# SPDX-License-Identifier: GPL-2.0 +# Leo Yan <leo.yan@linaro.org>, 2022 + +skip_if_no_mem_event() { + perf mem record -e list 2>&1 | egrep -q 'available' && return 0 + return 2 +} + +skip_if_no_mem_event || exit 2 + +# skip if there's no compiler +if ! [ -x "$(command -v cc)" ]; then + echo "skip: no compiler, install gcc" + exit 2 +fi + +TEST_PROGRAM=$(mktemp /tmp/__perf_test.program.XXXXX) +PERF_DATA=$(mktemp /tmp/__perf_test.perf.data.XXXXX) + +check_result() { + # The memory report format is as below: + # 99.92% ... [.] buf1+0x38 + result=$(perf mem report -i ${PERF_DATA} -s symbol_daddr -q 2>&1 | + awk '/buf1/ { print $4 }') + + # Testing is failed if has no any sample for "buf1" + [ -z "$result" ] && return 1 + + while IFS= read -r line; do + # The "data1" and "data2" fields in structure "buf1" have + # offset "0x0" and "0x38", returns failure if detect any + # other offset value. + if [ "$line" != "buf1+0x0" ] && [ "$line" != "buf1+0x38" ]; then + return 1 + fi + done <<< "$result" + + return 0 +} + +cleanup_files() +{ + echo "Cleaning up files..." + rm -f ${PERF_DATA} + rm -f ${TEST_PROGRAM} +} + +trap cleanup_files exit term int + +# compile test program +echo "Compiling test program..." +cat << EOF | cc -o ${TEST_PROGRAM} -x c - +typedef struct _buf { + char data1; + char reserved[55]; + char data2; +} buf __attribute__((aligned(64))); + +static buf buf1; + +int main(void) { + for (;;) { + buf1.data1++; + buf1.data2 += buf1.data1; + } + return 0; +} +EOF + +echo "Recording workload..." + +# perf mem/c2c internally uses IBS PMU on AMD CPU which doesn't support +# user/kernel filtering and per-process monitoring, spin program on +# specific CPU and test in per-CPU mode. +is_amd=$(egrep -c 'vendor_id.*AuthenticAMD' /proc/cpuinfo) +if (($is_amd >= 1)); then + perf mem record -o ${PERF_DATA} -C 0 -- taskset -c 0 $TEST_PROGRAM & +else + perf mem record --all-user -o ${PERF_DATA} -- $TEST_PROGRAM & +fi + +PERFPID=$! + +sleep 1 + +kill $PERFPID +wait $PERFPID + +check_result +exit $? diff --git a/tools/perf/tests/shell/test_intel_pt.sh b/tools/perf/tests/shell/test_intel_pt.sh new file mode 100755 index 000000000000..f5ed7b1af419 --- /dev/null +++ b/tools/perf/tests/shell/test_intel_pt.sh @@ -0,0 +1,663 @@ +#!/bin/sh +# Miscellaneous Intel PT testing +# SPDX-License-Identifier: GPL-2.0 + +set -e + +# Skip if no Intel PT +perf list | grep -q 'intel_pt//' || exit 2 + +shelldir=$(dirname "$0") +. "${shelldir}"/lib/waiting.sh + +skip_cnt=0 +ok_cnt=0 +err_cnt=0 + +temp_dir=$(mktemp -d /tmp/perf-test-intel-pt-sh.XXXXXXXXXX) + +tmpfile="${temp_dir}/tmp-perf.data" +perfdatafile="${temp_dir}/test-perf.data" +outfile="${temp_dir}/test-out.txt" +errfile="${temp_dir}/test-err.txt" +workload="${temp_dir}/workload" +awkscript="${temp_dir}/awkscript" +jitdump_workload="${temp_dir}/jitdump_workload" +maxbrstack="${temp_dir}/maxbrstack.py" + +cleanup() +{ + trap - EXIT TERM INT + sane=$(echo "${temp_dir}" | cut -b 1-26) + if [ "${sane}" = "/tmp/perf-test-intel-pt-sh" ] ; then + echo "--- Cleaning up ---" + rm -f "${temp_dir}/"* + rmdir "${temp_dir}" + fi +} + +trap_cleanup() +{ + cleanup + exit 1 +} + +trap trap_cleanup EXIT TERM INT + +# perf record for testing without decoding +perf_record_no_decode() +{ + # Options to speed up recording: no post-processing, no build-id cache update, + # and no BPF events. + perf record -B -N --no-bpf-event "$@" +} + +# perf record for testing should not need BPF events +perf_record_no_bpf() +{ + # Options for no BPF events + perf record --no-bpf-event "$@" +} + +have_workload=false +cat << _end_of_file_ | /usr/bin/cc -o "${workload}" -xc - -pthread && have_workload=true +#include <time.h> +#include <pthread.h> + +void work(void) { + struct timespec tm = { + .tv_nsec = 1000000, + }; + int i; + + /* Run for about 30 seconds */ + for (i = 0; i < 30000; i++) + nanosleep(&tm, NULL); +} + +void *threadfunc(void *arg) { + work(); + return NULL; +} + +int main(void) { + pthread_t th; + + pthread_create(&th, NULL, threadfunc, NULL); + work(); + pthread_join(th, NULL); + return 0; +} +_end_of_file_ + +can_cpu_wide() +{ + echo "Checking for CPU-wide recording on CPU $1" + if ! perf_record_no_decode -o "${tmpfile}" -e dummy:u -C "$1" true >/dev/null 2>&1 ; then + echo "No so skipping" + return 2 + fi + echo OK + return 0 +} + +test_system_wide_side_band() +{ + echo "--- Test system-wide sideband ---" + + # Need CPU 0 and CPU 1 + can_cpu_wide 0 || return $? + can_cpu_wide 1 || return $? + + # Record on CPU 0 a task running on CPU 1 + perf_record_no_decode -o "${perfdatafile}" -e intel_pt//u -C 0 -- taskset --cpu-list 1 uname + + # Should get MMAP events from CPU 1 because they can be needed to decode + mmap_cnt=$(perf script -i "${perfdatafile}" --no-itrace --show-mmap-events -C 1 2>/dev/null | grep -c MMAP) + + if [ "${mmap_cnt}" -gt 0 ] ; then + echo OK + return 0 + fi + + echo "Failed to record MMAP events on CPU 1 when tracing CPU 0" + return 1 +} + +can_kernel() +{ + if [ -z "${can_kernel_trace}" ] ; then + can_kernel_trace=0 + perf_record_no_decode -o "${tmpfile}" -e dummy:k true >/dev/null 2>&1 && can_kernel_trace=1 + fi + if [ ${can_kernel_trace} -eq 0 ] ; then + echo "SKIP: no kernel tracing" + return 2 + fi + return 0 +} + +test_per_thread() +{ + k="$1" + desc="$2" + + echo "--- Test per-thread ${desc}recording ---" + + if ! $have_workload ; then + echo "No workload, so skipping" + return 2 + fi + + if [ "${k}" = "k" ] ; then + can_kernel || return 2 + fi + + cat <<- "_end_of_file_" > "${awkscript}" + BEGIN { + s = "[ ]*" + u = s"[0-9]+"s + d = s"[0-9-]+"s + x = s"[0-9a-fA-FxX]+"s + mmapping = "idx"u": mmapping fd"u + set_output = "idx"u": set output fd"u"->"u + perf_event_open = "sys_perf_event_open: pid"d"cpu"d"group_fd"d"flags"x"="u + } + + /perf record opening and mmapping events/ { + if (!done) + active = 1 + } + + /perf record done opening and mmapping events/ { + active = 0 + done = 1 + } + + $0 ~ perf_event_open && active { + match($0, perf_event_open) + $0 = substr($0, RSTART, RLENGTH) + pid = $3 + cpu = $5 + fd = $11 + print "pid " pid " cpu " cpu " fd " fd " : " $0 + fd_array[fd] = fd + pid_array[fd] = pid + cpu_array[fd] = cpu + } + + $0 ~ mmapping && active { + match($0, mmapping) + $0 = substr($0, RSTART, RLENGTH) + fd = $5 + print "fd " fd " : " $0 + if (fd in fd_array) { + mmap_array[fd] = 1 + } else { + print "Unknown fd " fd + exit 1 + } + } + + $0 ~ set_output && active { + match($0, set_output) + $0 = substr($0, RSTART, RLENGTH) + fd = $6 + fd_to = $8 + print "fd " fd " fd_to " fd_to " : " $0 + if (fd in fd_array) { + if (fd_to in fd_array) { + set_output_array[fd] = fd_to + } else { + print "Unknown fd " fd_to + exit 1 + } + } else { + print "Unknown fd " fd + exit 1 + } + } + + END { + print "Checking " length(fd_array) " fds" + for (fd in fd_array) { + if (fd in mmap_array) { + pid = pid_array[fd] + if (pid != -1) { + if (pid in pids) { + print "More than 1 mmap for PID " pid + exit 1 + } + pids[pid] = 1 + } + cpu = cpu_array[fd] + if (cpu != -1) { + if (cpu in cpus) { + print "More than 1 mmap for CPU " cpu + exit 1 + } + cpus[cpu] = 1 + } + } else if (!(fd in set_output_array)) { + print "No mmap for fd " fd + exit 1 + } + } + n = length(pids) + if (n != thread_cnt) { + print "Expected " thread_cnt " per-thread mmaps - found " n + exit 1 + } + } + _end_of_file_ + + $workload & + w1=$! + $workload & + w2=$! + echo "Workload PIDs are $w1 and $w2" + wait_for_threads ${w1} 2 + wait_for_threads ${w2} 2 + + perf_record_no_decode -o "${perfdatafile}" -e intel_pt//u"${k}" -vvv --per-thread -p "${w1},${w2}" 2>"${errfile}" >"${outfile}" & + ppid=$! + echo "perf PID is $ppid" + wait_for_perf_to_start ${ppid} "${errfile}" || return 1 + + kill ${w1} + wait_for_process_to_exit ${w1} || return 1 + is_running ${ppid} || return 1 + + kill ${w2} + wait_for_process_to_exit ${w2} || return 1 + wait_for_process_to_exit ${ppid} || return 1 + + awk -v thread_cnt=4 -f "${awkscript}" "${errfile}" || return 1 + + echo OK + return 0 +} + +test_jitdump() +{ + echo "--- Test tracing self-modifying code that uses jitdump ---" + + script_path=$(realpath "$0") + script_dir=$(dirname "$script_path") + jitdump_incl_dir="${script_dir}/../../util" + jitdump_h="${jitdump_incl_dir}/jitdump.h" + + if [ ! -e "${jitdump_h}" ] ; then + echo "SKIP: Include file jitdump.h not found" + return 2 + fi + + if [ -z "${have_jitdump_workload}" ] ; then + have_jitdump_workload=false + # Create a workload that uses self-modifying code and generates its own jitdump file + cat <<- "_end_of_file_" | /usr/bin/cc -o "${jitdump_workload}" -I "${jitdump_incl_dir}" -xc - -pthread && have_jitdump_workload=true + #define _GNU_SOURCE + #include <sys/mman.h> + #include <sys/types.h> + #include <stddef.h> + #include <stdio.h> + #include <stdint.h> + #include <unistd.h> + #include <string.h> + + #include "jitdump.h" + + #define CHK_BYTE 0x5a + + static inline uint64_t rdtsc(void) + { + unsigned int low, high; + + asm volatile("rdtsc" : "=a" (low), "=d" (high)); + + return low | ((uint64_t)high) << 32; + } + + static FILE *open_jitdump(void) + { + struct jitheader header = { + .magic = JITHEADER_MAGIC, + .version = JITHEADER_VERSION, + .total_size = sizeof(header), + .pid = getpid(), + .timestamp = rdtsc(), + .flags = JITDUMP_FLAGS_ARCH_TIMESTAMP, + }; + char filename[256]; + FILE *f; + void *m; + + snprintf(filename, sizeof(filename), "jit-%d.dump", getpid()); + f = fopen(filename, "w+"); + if (!f) + goto err; + /* Create an MMAP event for the jitdump file. That is how perf tool finds it. */ + m = mmap(0, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno(f), 0); + if (m == MAP_FAILED) + goto err_close; + munmap(m, 4096); + if (fwrite(&header,sizeof(header),1,f) != 1) + goto err_close; + return f; + + err_close: + fclose(f); + err: + return NULL; + } + + static int write_jitdump(FILE *f, void *addr, const uint8_t *dat, size_t sz, uint64_t *idx) + { + struct jr_code_load rec = { + .p.id = JIT_CODE_LOAD, + .p.total_size = sizeof(rec) + sz, + .p.timestamp = rdtsc(), + .pid = getpid(), + .tid = gettid(), + .vma = (unsigned long)addr, + .code_addr = (unsigned long)addr, + .code_size = sz, + .code_index = ++*idx, + }; + + if (fwrite(&rec,sizeof(rec),1,f) != 1 || + fwrite(dat, sz, 1, f) != 1) + return -1; + return 0; + } + + static void close_jitdump(FILE *f) + { + fclose(f); + } + + int main() + { + /* Get a memory page to store executable code */ + void *addr = mmap(0, 4096, PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); + /* Code to execute: mov CHK_BYTE, %eax ; ret */ + uint8_t dat[] = {0xb8, CHK_BYTE, 0x00, 0x00, 0x00, 0xc3}; + FILE *f = open_jitdump(); + uint64_t idx = 0; + int ret = 1; + + if (!f) + return 1; + /* Copy executable code to executable memory page */ + memcpy(addr, dat, sizeof(dat)); + /* Record it in the jitdump file */ + if (write_jitdump(f, addr, dat, sizeof(dat), &idx)) + goto out_close; + /* Call it */ + ret = ((int (*)(void))addr)() - CHK_BYTE; + out_close: + close_jitdump(f); + return ret; + } + _end_of_file_ + fi + + if ! $have_jitdump_workload ; then + echo "SKIP: No jitdump workload" + return 2 + fi + + # Change to temp_dir so jitdump collateral files go there + cd "${temp_dir}" + perf_record_no_bpf -o "${tmpfile}" -e intel_pt//u "${jitdump_workload}" + perf inject -i "${tmpfile}" -o "${perfdatafile}" --jit + decode_br_cnt=$(perf script -i "${perfdatafile}" --itrace=b | wc -l) + # Note that overflow and lost errors are suppressed for the error count + decode_err_cnt=$(perf script -i "${perfdatafile}" --itrace=e-o-l | grep -ci error) + cd - + # Should be thousands of branches + if [ "${decode_br_cnt}" -lt 1000 ] ; then + echo "Decode failed, only ${decode_br_cnt} branches" + return 1 + fi + # Should be no errors + if [ "${decode_err_cnt}" -ne 0 ] ; then + echo "Decode failed, ${decode_err_cnt} errors" + perf script -i "${perfdatafile}" --itrace=e-o-l --show-mmap-events | cat + return 1 + fi + + echo OK + return 0 +} + +test_packet_filter() +{ + echo "--- Test with MTC and TSC disabled ---" + # Disable MTC and TSC + perf_record_no_decode -o "${perfdatafile}" -e intel_pt/mtc=0,tsc=0/u uname + # Should not get MTC packet + mtc_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "MTC 0x") + if [ "${mtc_cnt}" -ne 0 ] ; then + echo "Failed to filter with mtc=0" + return 1 + fi + # Should not get TSC package + tsc_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "TSC 0x") + if [ "${tsc_cnt}" -ne 0 ] ; then + echo "Failed to filter with tsc=0" + return 1 + fi + echo OK + return 0 +} + +test_disable_branch() +{ + echo "--- Test with branches disabled ---" + # Disable branch + perf_record_no_decode -o "${perfdatafile}" -e intel_pt/branch=0/u uname + # Should not get branch related packets + tnt_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "TNT 0x") + tip_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "TIP 0x") + fup_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "FUP 0x") + if [ "${tnt_cnt}" -ne 0 ] || [ "${tip_cnt}" -ne 0 ] || [ "${fup_cnt}" -ne 0 ] ; then + echo "Failed to disable branches" + return 1 + fi + echo OK + return 0 +} + +test_time_cyc() +{ + echo "--- Test with/without CYC ---" + # Check if CYC is supported + cyc=$(cat /sys/bus/event_source/devices/intel_pt/caps/psb_cyc) + if [ "${cyc}" != "1" ] ; then + echo "SKIP: CYC is not supported" + return 2 + fi + # Enable CYC + perf_record_no_decode -o "${perfdatafile}" -e intel_pt/cyc/u uname + # should get CYC packets + cyc_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "CYC 0x") + if [ "${cyc_cnt}" = "0" ] ; then + echo "Failed to get CYC packet" + return 1 + fi + # Without CYC + perf_record_no_decode -o "${perfdatafile}" -e intel_pt//u uname + # Should not get CYC packets + cyc_cnt=$(perf script -i "${perfdatafile}" -D 2>/dev/null | grep -c "CYC 0x") + if [ "${cyc_cnt}" -gt 0 ] ; then + echo "Still get CYC packet without cyc" + return 1 + fi + echo OK + return 0 +} + +test_sample() +{ + echo "--- Test recording with sample mode ---" + # Check if recording with sample mode is working + if ! perf_record_no_decode -o "${perfdatafile}" --aux-sample=8192 -e '{intel_pt//u,branch-misses:u}' uname ; then + echo "perf record failed with --aux-sample" + return 1 + fi + echo OK + return 0 +} + +test_kernel_trace() +{ + echo "--- Test with kernel trace ---" + # Check if recording with kernel trace is working + can_kernel || return 2 + if ! perf_record_no_decode -o "${perfdatafile}" -e intel_pt//k -m1,128 uname ; then + echo "perf record failed with intel_pt//k" + return 1 + fi + echo OK + return 0 +} + +test_virtual_lbr() +{ + echo "--- Test virtual LBR ---" + # Check if python script is supported + libpython=$(perf version --build-options | grep python | grep -cv OFF) + if [ "${libpython}" != "1" ] ; then + echo "SKIP: python scripting is not supported" + return 2 + fi + + # Python script to determine the maximum size of branch stacks + cat << "_end_of_file_" > "${maxbrstack}" +from __future__ import print_function + +bmax = 0 + +def process_event(param_dict): + if "brstack" in param_dict: + brstack = param_dict["brstack"] + n = len(brstack) + global bmax + if n > bmax: + bmax = n + +def trace_end(): + print("max brstack", bmax) +_end_of_file_ + + # Check if virtual lbr is working + perf_record_no_bpf -o "${perfdatafile}" --aux-sample -e '{intel_pt//,cycles}:u' uname + times_val=$(perf script -i "${perfdatafile}" --itrace=L -s "${maxbrstack}" 2>/dev/null | grep "max brstack " | cut -d " " -f 3) + case "${times_val}" in + [0-9]*) ;; + *) times_val=0;; + esac + if [ "${times_val}" -lt 2 ] ; then + echo "Failed with virtual lbr" + return 1 + fi + echo OK + return 0 +} + +test_power_event() +{ + echo "--- Test power events ---" + # Check if power events are supported + power_event=$(cat /sys/bus/event_source/devices/intel_pt/caps/power_event_trace) + if [ "${power_event}" != "1" ] ; then + echo "SKIP: power_event_trace is not supported" + return 2 + fi + if ! perf_record_no_decode -o "${perfdatafile}" -a -e intel_pt/pwr_evt/u uname ; then + echo "perf record failed with pwr_evt" + return 1 + fi + echo OK + return 0 +} + +test_no_tnt() +{ + echo "--- Test with TNT packets disabled ---" + # Check if TNT disable is supported + notnt=$(cat /sys/bus/event_source/devices/intel_pt/caps/tnt_disable) + if [ "${notnt}" != "1" ] ; then + echo "SKIP: tnt_disable is not supported" + return 2 + fi + perf_record_no_decode -o "${perfdatafile}" -e intel_pt/notnt/u uname + # Should be no TNT packets + tnt_cnt=$(perf script -i "${perfdatafile}" -D | grep -c TNT) + if [ "${tnt_cnt}" -ne 0 ] ; then + echo "TNT packets still there after notnt" + return 1 + fi + echo OK + return 0 +} + +test_event_trace() +{ + echo "--- Test with event_trace ---" + # Check if event_trace is supported + event_trace=$(cat /sys/bus/event_source/devices/intel_pt/caps/event_trace) + if [ "${event_trace}" != 1 ] ; then + echo "SKIP: event_trace is not supported" + return 2 + fi + if ! perf_record_no_decode -o "${perfdatafile}" -e intel_pt/event/u uname ; then + echo "perf record failed with event trace" + return 1 + fi + echo OK + return 0 +} + +count_result() +{ + if [ "$1" -eq 2 ] ; then + skip_cnt=$((skip_cnt + 1)) + return + fi + if [ "$1" -eq 0 ] ; then + ok_cnt=$((ok_cnt + 1)) + return + fi + err_cnt=$((err_cnt + 1)) +} + +ret=0 +test_system_wide_side_band || ret=$? ; count_result $ret ; ret=0 +test_per_thread "" "" || ret=$? ; count_result $ret ; ret=0 +test_per_thread "k" "(incl. kernel) " || ret=$? ; count_result $ret ; ret=0 +test_jitdump || ret=$? ; count_result $ret ; ret=0 +test_packet_filter || ret=$? ; count_result $ret ; ret=0 +test_disable_branch || ret=$? ; count_result $ret ; ret=0 +test_time_cyc || ret=$? ; count_result $ret ; ret=0 +test_sample || ret=$? ; count_result $ret ; ret=0 +test_kernel_trace || ret=$? ; count_result $ret ; ret=0 +test_virtual_lbr || ret=$? ; count_result $ret ; ret=0 +test_power_event || ret=$? ; count_result $ret ; ret=0 +test_no_tnt || ret=$? ; count_result $ret ; ret=0 +test_event_trace || ret=$? ; count_result $ret ; ret=0 + +cleanup + +echo "--- Done ---" + +if [ ${err_cnt} -gt 0 ] ; then + exit 1 +fi + +if [ ${ok_cnt} -gt 0 ] ; then + exit 0 +fi + +exit 2 diff --git a/tools/perf/tests/shell/test_java_symbol.sh b/tools/perf/tests/shell/test_java_symbol.sh new file mode 100755 index 000000000000..f221225808a3 --- /dev/null +++ b/tools/perf/tests/shell/test_java_symbol.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Test java symbol + +# SPDX-License-Identifier: GPL-2.0 +# Leo Yan <leo.yan@linaro.org>, 2022 + +# skip if there's no jshell +if ! [ -x "$(command -v jshell)" ]; then + echo "skip: no jshell, install JDK" + exit 2 +fi + +PERF_DATA=$(mktemp /tmp/__perf_test.perf.data.XXXXX) +PERF_INJ_DATA=$(mktemp /tmp/__perf_test.perf.data.inj.XXXXX) + +cleanup_files() +{ + echo "Cleaning up files..." + rm -f ${PERF_DATA} + rm -f ${PERF_INJ_DATA} +} + +trap cleanup_files exit term int + +if [ -e "$PWD/tools/perf/libperf-jvmti.so" ]; then + LIBJVMTI=$PWD/tools/perf/libperf-jvmti.so +elif [ -e "$PWD/libperf-jvmti.so" ]; then + LIBJVMTI=$PWD/libperf-jvmti.so +elif [ -e "$PREFIX/lib64/libperf-jvmti.so" ]; then + LIBJVMTI=$PREFIX/lib64/libperf-jvmti.so +elif [ -e "$PREFIX/lib/libperf-jvmti.so" ]; then + LIBJVMTI=$PREFIX/lib/libperf-jvmti.so +elif [ -e "/usr/lib/linux-tools-$(uname -a | awk '{ print $3 }' | sed -r 's/-generic//')/libperf-jvmti.so" ]; then + LIBJVMTI=/usr/lib/linux-tools-$(uname -a | awk '{ print $3 }' | sed -r 's/-generic//')/libperf-jvmti.so +else + echo "Fail to find libperf-jvmti.so" + # JVMTI is a build option, skip the test if fail to find lib + exit 2 +fi + +cat <<EOF | perf record -k 1 -o $PERF_DATA jshell -s -J-agentpath:$LIBJVMTI +int fib(int x) { + return x > 1 ? fib(x - 2) + fib(x - 1) : 1; +} + +int q = 0; + +for (int i = 0; i < 10; i++) + q += fib(i); + +System.out.println(q); +EOF + +if [ $? -ne 0 ]; then + echo "Fail to record for java program" + exit 1 +fi + +if ! perf inject -i $PERF_DATA -o $PERF_INJ_DATA -j; then + echo "Fail to inject samples" + exit 1 +fi + +# Below is an example of the instruction samples reporting: +# 8.18% jshell jitted-50116-29.so [.] Interpreter +# 0.75% Thread-1 jitted-83602-1670.so [.] jdk.internal.jimage.BasicImageReader.getString(int) +perf report --stdio -i ${PERF_INJ_DATA} 2>&1 | \ + egrep " +[0-9]+\.[0-9]+% .* (Interpreter|jdk\.internal).*" > /dev/null 2>&1 + +if [ $? -ne 0 ]; then + echo "Fail to find java symbols" + exit 1 +fi + +exit 0 diff --git a/tools/perf/tests/sigtrap.c b/tools/perf/tests/sigtrap.c new file mode 100644 index 000000000000..1de7478ec189 --- /dev/null +++ b/tools/perf/tests/sigtrap.c @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Basic test for sigtrap support. + * + * Copyright (C) 2021, Google LLC. + */ + +#include <errno.h> +#include <stdint.h> +#include <stdlib.h> +#include <linux/hw_breakpoint.h> +#include <linux/string.h> +#include <pthread.h> +#include <signal.h> +#include <sys/ioctl.h> +#include <sys/syscall.h> +#include <unistd.h> + +#include "cloexec.h" +#include "debug.h" +#include "event.h" +#include "tests.h" +#include "../perf-sys.h" + +#define NUM_THREADS 5 + +static struct { + int tids_want_signal; /* Which threads still want a signal. */ + int signal_count; /* Sanity check number of signals received. */ + volatile int iterate_on; /* Variable to set breakpoint on. */ + siginfo_t first_siginfo; /* First observed siginfo_t. */ +} ctx; + +#define TEST_SIG_DATA (~(unsigned long)(&ctx.iterate_on)) + +static struct perf_event_attr make_event_attr(void) +{ + struct perf_event_attr attr = { + .type = PERF_TYPE_BREAKPOINT, + .size = sizeof(attr), + .sample_period = 1, + .disabled = 1, + .bp_addr = (unsigned long)&ctx.iterate_on, + .bp_type = HW_BREAKPOINT_RW, + .bp_len = HW_BREAKPOINT_LEN_1, + .inherit = 1, /* Children inherit events ... */ + .inherit_thread = 1, /* ... but only cloned with CLONE_THREAD. */ + .remove_on_exec = 1, /* Required by sigtrap. */ + .sigtrap = 1, /* Request synchronous SIGTRAP on event. */ + .sig_data = TEST_SIG_DATA, + .exclude_kernel = 1, /* To allow */ + .exclude_hv = 1, /* running as !root */ + }; + return attr; +} + +#ifdef HAVE_BPF_SKEL +#include <bpf/btf.h> + +static bool attr_has_sigtrap(void) +{ + bool ret = false; + struct btf *btf; + const struct btf_type *t; + const struct btf_member *m; + const char *name; + int i, id; + + btf = btf__load_vmlinux_btf(); + if (btf == NULL) { + /* should be an old kernel */ + return false; + } + + id = btf__find_by_name_kind(btf, "perf_event_attr", BTF_KIND_STRUCT); + if (id < 0) + goto out; + + t = btf__type_by_id(btf, id); + for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) { + name = btf__name_by_offset(btf, m->name_off); + if (!strcmp(name, "sigtrap")) { + ret = true; + break; + } + } +out: + btf__free(btf); + return ret; +} +#else /* !HAVE_BPF_SKEL */ +static bool attr_has_sigtrap(void) +{ + struct perf_event_attr attr = { + .type = PERF_TYPE_SOFTWARE, + .config = PERF_COUNT_SW_DUMMY, + .size = sizeof(attr), + .remove_on_exec = 1, /* Required by sigtrap. */ + .sigtrap = 1, /* Request synchronous SIGTRAP on event. */ + }; + int fd; + bool ret = false; + + fd = sys_perf_event_open(&attr, 0, -1, -1, perf_event_open_cloexec_flag()); + if (fd >= 0) { + ret = true; + close(fd); + } + + return ret; +} +#endif /* HAVE_BPF_SKEL */ + +static void +sigtrap_handler(int signum __maybe_unused, siginfo_t *info, void *ucontext __maybe_unused) +{ + if (!__atomic_fetch_add(&ctx.signal_count, 1, __ATOMIC_RELAXED)) + ctx.first_siginfo = *info; + __atomic_fetch_sub(&ctx.tids_want_signal, syscall(SYS_gettid), __ATOMIC_RELAXED); +} + +static void *test_thread(void *arg) +{ + pthread_barrier_t *barrier = (pthread_barrier_t *)arg; + pid_t tid = syscall(SYS_gettid); + int i; + + pthread_barrier_wait(barrier); + + __atomic_fetch_add(&ctx.tids_want_signal, tid, __ATOMIC_RELAXED); + for (i = 0; i < ctx.iterate_on - 1; i++) + __atomic_fetch_add(&ctx.tids_want_signal, tid, __ATOMIC_RELAXED); + + return NULL; +} + +static int run_test_threads(pthread_t *threads, pthread_barrier_t *barrier) +{ + int i; + + pthread_barrier_wait(barrier); + for (i = 0; i < NUM_THREADS; i++) + TEST_ASSERT_EQUAL("pthread_join() failed", pthread_join(threads[i], NULL), 0); + + return TEST_OK; +} + +static int run_stress_test(int fd, pthread_t *threads, pthread_barrier_t *barrier) +{ + int ret; + + ctx.iterate_on = 3000; + + TEST_ASSERT_EQUAL("misfired signal?", ctx.signal_count, 0); + TEST_ASSERT_EQUAL("enable failed", ioctl(fd, PERF_EVENT_IOC_ENABLE, 0), 0); + ret = run_test_threads(threads, barrier); + TEST_ASSERT_EQUAL("disable failed", ioctl(fd, PERF_EVENT_IOC_DISABLE, 0), 0); + + TEST_ASSERT_EQUAL("unexpected sigtraps", ctx.signal_count, NUM_THREADS * ctx.iterate_on); + TEST_ASSERT_EQUAL("missing signals or incorrectly delivered", ctx.tids_want_signal, 0); + TEST_ASSERT_VAL("unexpected si_addr", ctx.first_siginfo.si_addr == &ctx.iterate_on); +#if 0 /* FIXME: enable when libc's signal.h has si_perf_{type,data} */ + TEST_ASSERT_EQUAL("unexpected si_perf_type", ctx.first_siginfo.si_perf_type, + PERF_TYPE_BREAKPOINT); + TEST_ASSERT_EQUAL("unexpected si_perf_data", ctx.first_siginfo.si_perf_data, + TEST_SIG_DATA); +#endif + + return ret; +} + +static int test__sigtrap(struct test_suite *test __maybe_unused, int subtest __maybe_unused) +{ + struct perf_event_attr attr = make_event_attr(); + struct sigaction action = {}; + struct sigaction oldact; + pthread_t threads[NUM_THREADS]; + pthread_barrier_t barrier; + char sbuf[STRERR_BUFSIZE]; + int i, fd, ret = TEST_FAIL; + + if (!BP_SIGNAL_IS_SUPPORTED) { + pr_debug("Test not supported on this architecture"); + return TEST_SKIP; + } + + pthread_barrier_init(&barrier, NULL, NUM_THREADS + 1); + + action.sa_flags = SA_SIGINFO | SA_NODEFER; + action.sa_sigaction = sigtrap_handler; + sigemptyset(&action.sa_mask); + if (sigaction(SIGTRAP, &action, &oldact)) { + pr_debug("FAILED sigaction(): %s\n", str_error_r(errno, sbuf, sizeof(sbuf))); + goto out; + } + + fd = sys_perf_event_open(&attr, 0, -1, -1, perf_event_open_cloexec_flag()); + if (fd < 0) { + if (attr_has_sigtrap()) { + pr_debug("FAILED sys_perf_event_open(): %s\n", + str_error_r(errno, sbuf, sizeof(sbuf))); + } else { + pr_debug("perf_event_attr doesn't have sigtrap\n"); + ret = TEST_SKIP; + } + goto out_restore_sigaction; + } + + for (i = 0; i < NUM_THREADS; i++) { + if (pthread_create(&threads[i], NULL, test_thread, &barrier)) { + pr_debug("FAILED pthread_create(): %s\n", str_error_r(errno, sbuf, sizeof(sbuf))); + goto out_close_perf_event; + } + } + + ret = run_stress_test(fd, threads, &barrier); + +out_close_perf_event: + close(fd); +out_restore_sigaction: + sigaction(SIGTRAP, &oldact, NULL); +out: + pthread_barrier_destroy(&barrier); + return ret; +} + +DEFINE_SUITE("Sigtrap", sigtrap); diff --git a/tools/perf/tests/stat.c b/tools/perf/tests/stat.c index 2eb096b5e6da..500974040fe3 100644 --- a/tools/perf/tests/stat.c +++ b/tools/perf/tests/stat.c @@ -87,7 +87,8 @@ static int test__synthesize_stat(struct test_suite *test __maybe_unused, int sub count.run = 300; TEST_ASSERT_VAL("failed to synthesize stat_config", - !perf_event__synthesize_stat(NULL, 1, 2, 3, &count, process_stat_event, NULL)); + !perf_event__synthesize_stat(NULL, (struct perf_cpu){.cpu = 1}, 2, 3, + &count, process_stat_event, NULL)); return 0; } diff --git a/tools/perf/tests/switch-tracking.c b/tools/perf/tests/switch-tracking.c index 0c0c2328bf4e..87f565c7f650 100644 --- a/tools/perf/tests/switch-tracking.c +++ b/tools/perf/tests/switch-tracking.c @@ -6,6 +6,7 @@ #include <time.h> #include <stdlib.h> #include <linux/zalloc.h> +#include <linux/err.h> #include <perf/cpumap.h> #include <perf/evlist.h> #include <perf/mmap.h> @@ -324,6 +325,7 @@ out_free_nodes: static int test__switch_tracking(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { const char *sched_switch = "sched:sched_switch"; + const char *cycles = "cycles:u"; struct switch_tracking switch_tracking = { .tids = NULL, }; struct record_opts opts = { .mmap_pages = UINT_MAX, @@ -363,7 +365,7 @@ static int test__switch_tracking(struct test_suite *test __maybe_unused, int sub perf_evlist__set_maps(&evlist->core, cpus, threads); /* First event */ - err = parse_events(evlist, "cpu-clock:u", NULL); + err = parse_event(evlist, "cpu-clock:u"); if (err) { pr_debug("Failed to parse event dummy:u\n"); goto out_err; @@ -372,12 +374,19 @@ static int test__switch_tracking(struct test_suite *test __maybe_unused, int sub cpu_clocks_evsel = evlist__last(evlist); /* Second event */ - if (perf_pmu__has_hybrid()) - err = parse_events(evlist, "cpu_core/cycles/u", NULL); - else - err = parse_events(evlist, "cycles:u", NULL); + if (perf_pmu__has_hybrid()) { + cycles = "cpu_core/cycles/u"; + err = parse_event(evlist, cycles); + if (err) { + cycles = "cpu_atom/cycles/u"; + pr_debug("Trying %s\n", cycles); + err = parse_event(evlist, cycles); + } + } else { + err = parse_event(evlist, cycles); + } if (err) { - pr_debug("Failed to parse event cycles:u\n"); + pr_debug("Failed to parse event %s\n", cycles); goto out_err; } @@ -390,19 +399,13 @@ static int test__switch_tracking(struct test_suite *test __maybe_unused, int sub goto out; } - err = parse_events(evlist, sched_switch, NULL); - if (err) { - pr_debug("Failed to parse event %s\n", sched_switch); + switch_evsel = evlist__add_sched_switch(evlist, true); + if (IS_ERR(switch_evsel)) { + err = PTR_ERR(switch_evsel); + pr_debug("Failed to create event %s\n", sched_switch); goto out_err; } - switch_evsel = evlist__last(evlist); - - evsel__set_sample_bit(switch_evsel, CPU); - evsel__set_sample_bit(switch_evsel, TIME); - - switch_evsel->core.system_wide = true; - switch_evsel->no_aux_samples = true; switch_evsel->immediate = true; /* Test moving an event to the front */ @@ -420,7 +423,7 @@ static int test__switch_tracking(struct test_suite *test __maybe_unused, int sub evsel__set_sample_bit(cycles_evsel, TIME); /* Fourth event */ - err = parse_events(evlist, "dummy:u", NULL); + err = parse_event(evlist, "dummy:u"); if (err) { pr_debug("Failed to parse event dummy:u\n"); goto out_err; diff --git a/tools/perf/tests/tests.h b/tools/perf/tests/tests.h index 8f65098110fc..5bbb8f6a48fc 100644 --- a/tools/perf/tests/tests.h +++ b/tools/perf/tests/tests.h @@ -146,6 +146,7 @@ DECLARE_SUITE(pe_file_parsing); DECLARE_SUITE(expand_cgroup_events); DECLARE_SUITE(perf_time_to_tsc); DECLARE_SUITE(dlfilter); +DECLARE_SUITE(sigtrap); /* * PowerPC and S390 do not support creation of instruction breakpoints using the diff --git a/tools/perf/tests/topology.c b/tools/perf/tests/topology.c index 869986139146..c4630cfc80ea 100644 --- a/tools/perf/tests/topology.c +++ b/tools/perf/tests/topology.c @@ -109,66 +109,103 @@ static int check_cpu_topology(char *path, struct perf_cpu_map *map) && strncmp(session->header.env.arch, "aarch64", 7)) return TEST_SKIP; + /* + * In powerpc pSeries platform, not all the topology information + * are exposed via sysfs. Due to restriction, detail like + * physical_package_id will be set to -1. Hence skip this + * test if physical_package_id returns -1 for cpu from perf_cpu_map. + */ + if (!strncmp(session->header.env.arch, "ppc64le", 7)) { + if (cpu__get_socket_id(perf_cpu_map__cpu(map, 0)) == -1) + return TEST_SKIP; + } + TEST_ASSERT_VAL("Session header CPU map not set", session->header.env.cpu); for (i = 0; i < session->header.env.nr_cpus_avail; i++) { - if (!cpu_map__has(map, i)) + struct perf_cpu cpu = { .cpu = i }; + + if (!perf_cpu_map__has(map, cpu)) continue; pr_debug("CPU %d, core %d, socket %d\n", i, session->header.env.cpu[i].core_id, session->header.env.cpu[i].socket_id); } + // Test that CPU ID contains socket, die, core and CPU + for (i = 0; i < perf_cpu_map__nr(map); i++) { + id = aggr_cpu_id__cpu(perf_cpu_map__cpu(map, i), NULL); + TEST_ASSERT_VAL("Cpu map - CPU ID doesn't match", + perf_cpu_map__cpu(map, i).cpu == id.cpu.cpu); + + TEST_ASSERT_VAL("Cpu map - Core ID doesn't match", + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].core_id == id.core); + TEST_ASSERT_VAL("Cpu map - Socket ID doesn't match", + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].socket_id == + id.socket); + + TEST_ASSERT_VAL("Cpu map - Die ID doesn't match", + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].die_id == id.die); + TEST_ASSERT_VAL("Cpu map - Node ID is set", id.node == -1); + TEST_ASSERT_VAL("Cpu map - Thread IDX is set", id.thread_idx == -1); + } + // Test that core ID contains socket, die and core - for (i = 0; i < map->nr; i++) { - id = cpu_map__get_core(map, i, NULL); + for (i = 0; i < perf_cpu_map__nr(map); i++) { + id = aggr_cpu_id__core(perf_cpu_map__cpu(map, i), NULL); TEST_ASSERT_VAL("Core map - Core ID doesn't match", - session->header.env.cpu[map->map[i]].core_id == id.core); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].core_id == id.core); TEST_ASSERT_VAL("Core map - Socket ID doesn't match", - session->header.env.cpu[map->map[i]].socket_id == id.socket); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].socket_id == + id.socket); TEST_ASSERT_VAL("Core map - Die ID doesn't match", - session->header.env.cpu[map->map[i]].die_id == id.die); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].die_id == id.die); TEST_ASSERT_VAL("Core map - Node ID is set", id.node == -1); - TEST_ASSERT_VAL("Core map - Thread is set", id.thread == -1); + TEST_ASSERT_VAL("Core map - Thread IDX is set", id.thread_idx == -1); } // Test that die ID contains socket and die - for (i = 0; i < map->nr; i++) { - id = cpu_map__get_die(map, i, NULL); + for (i = 0; i < perf_cpu_map__nr(map); i++) { + id = aggr_cpu_id__die(perf_cpu_map__cpu(map, i), NULL); TEST_ASSERT_VAL("Die map - Socket ID doesn't match", - session->header.env.cpu[map->map[i]].socket_id == id.socket); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].socket_id == + id.socket); TEST_ASSERT_VAL("Die map - Die ID doesn't match", - session->header.env.cpu[map->map[i]].die_id == id.die); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].die_id == id.die); TEST_ASSERT_VAL("Die map - Node ID is set", id.node == -1); TEST_ASSERT_VAL("Die map - Core is set", id.core == -1); - TEST_ASSERT_VAL("Die map - Thread is set", id.thread == -1); + TEST_ASSERT_VAL("Die map - CPU is set", id.cpu.cpu == -1); + TEST_ASSERT_VAL("Die map - Thread IDX is set", id.thread_idx == -1); } // Test that socket ID contains only socket - for (i = 0; i < map->nr; i++) { - id = cpu_map__get_socket(map, i, NULL); + for (i = 0; i < perf_cpu_map__nr(map); i++) { + id = aggr_cpu_id__socket(perf_cpu_map__cpu(map, i), NULL); TEST_ASSERT_VAL("Socket map - Socket ID doesn't match", - session->header.env.cpu[map->map[i]].socket_id == id.socket); + session->header.env.cpu[perf_cpu_map__cpu(map, i).cpu].socket_id == + id.socket); TEST_ASSERT_VAL("Socket map - Node ID is set", id.node == -1); TEST_ASSERT_VAL("Socket map - Die ID is set", id.die == -1); TEST_ASSERT_VAL("Socket map - Core is set", id.core == -1); - TEST_ASSERT_VAL("Socket map - Thread is set", id.thread == -1); + TEST_ASSERT_VAL("Socket map - CPU is set", id.cpu.cpu == -1); + TEST_ASSERT_VAL("Socket map - Thread IDX is set", id.thread_idx == -1); } // Test that node ID contains only node - for (i = 0; i < map->nr; i++) { - id = cpu_map__get_node(map, i, NULL); + for (i = 0; i < perf_cpu_map__nr(map); i++) { + id = aggr_cpu_id__node(perf_cpu_map__cpu(map, i), NULL); TEST_ASSERT_VAL("Node map - Node ID doesn't match", - cpu__get_node(map->map[i]) == id.node); + cpu__get_node(perf_cpu_map__cpu(map, i)) == id.node); TEST_ASSERT_VAL("Node map - Socket is set", id.socket == -1); TEST_ASSERT_VAL("Node map - Die ID is set", id.die == -1); TEST_ASSERT_VAL("Node map - Core is set", id.core == -1); - TEST_ASSERT_VAL("Node map - Thread is set", id.thread == -1); + TEST_ASSERT_VAL("Node map - CPU is set", id.cpu.cpu == -1); + TEST_ASSERT_VAL("Node map - Thread IDX is set", id.thread_idx == -1); } perf_session__delete(session); diff --git a/tools/perf/tests/vmlinux-kallsyms.c b/tools/perf/tests/vmlinux-kallsyms.c index e80df13c0420..8ab035b55875 100644 --- a/tools/perf/tests/vmlinux-kallsyms.c +++ b/tools/perf/tests/vmlinux-kallsyms.c @@ -43,10 +43,11 @@ static bool is_ignored_symbol(const char *name, char type) /* Symbol names that begin with the following are ignored.*/ static const char * const ignored_prefixes[] = { "$", /* local symbols for ARM, MIPS, etc. */ - ".LASANPC", /* s390 kasan local symbols */ + ".L", /* local labels, .LBB,.Ltmpxxx,.L__unnamed_xx,.LASANPC, etc. */ "__crc_", /* modversions */ "__efistub_", /* arm64 EFI stub namespace */ - "__kvm_nvhe_", /* arm64 non-VHE KVM namespace */ + "__kvm_nvhe_$", /* arm64 local symbols in non-VHE KVM namespace */ + "__kvm_nvhe_.L", /* arm64 local symbols in non-VHE KVM namespace */ "__AArch64ADRPThunk_", /* arm64 lld */ "__ARMV5PILongThunk_", /* arm lld */ "__ARMV7PILongThunk_", @@ -114,12 +115,12 @@ static bool is_ignored_symbol(const char *name, char type) static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { - int err = -1; + int err = TEST_FAIL; struct rb_node *nd; struct symbol *sym; struct map *kallsyms_map, *vmlinux_map, *map; struct machine kallsyms, vmlinux; - struct maps *maps = machine__kernel_maps(&vmlinux); + struct maps *maps; u64 mem_start, mem_end; bool header_printed; @@ -132,6 +133,8 @@ static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused machine__init(&kallsyms, "", HOST_KERNEL_ID); machine__init(&vmlinux, "", HOST_KERNEL_ID); + maps = machine__kernel_maps(&vmlinux); + /* * Step 2: * @@ -140,7 +143,8 @@ static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused * and find the .ko files that match them in /lib/modules/`uname -r`/. */ if (machine__create_kernel_maps(&kallsyms) < 0) { - pr_debug("machine__create_kernel_maps "); + pr_debug("machine__create_kernel_maps failed"); + err = TEST_SKIP; goto out; } @@ -156,7 +160,8 @@ static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused * code and with the one got from /proc/modules from the "kallsyms" code. */ if (machine__load_kallsyms(&kallsyms, "/proc/kallsyms") <= 0) { - pr_debug("dso__load_kallsyms "); + pr_debug("machine__load_kallsyms failed"); + err = TEST_SKIP; goto out; } @@ -176,7 +181,7 @@ static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused * Now repeat step 2, this time for the vmlinux file we'll auto-locate. */ if (machine__create_kernel_maps(&vmlinux) < 0) { - pr_debug("machine__create_kernel_maps "); + pr_info("machine__create_kernel_maps failed"); goto out; } @@ -194,7 +199,7 @@ static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_unused * to fixup the symbols. */ if (machine__load_vmlinux_path(&vmlinux) <= 0) { - pr_debug("Couldn't find a vmlinux that matches the kernel running on this machine, skipping test\n"); + pr_info("Couldn't find a vmlinux that matches the kernel running on this machine, skipping test\n"); err = TEST_SKIP; goto out; } @@ -293,7 +298,7 @@ next_pair: * so use the short name, less descriptive but the same ("[kernel]" in * both cases. */ - pair = maps__find_by_name(&kallsyms.kmaps, (map->dso->kernel ? + pair = maps__find_by_name(kallsyms.kmaps, (map->dso->kernel ? map->dso->short_name : map->dso->name)); if (pair) { @@ -315,7 +320,7 @@ next_pair: mem_start = vmlinux_map->unmap_ip(vmlinux_map, map->start); mem_end = vmlinux_map->unmap_ip(vmlinux_map, map->end); - pair = maps__find(&kallsyms.kmaps, mem_start); + pair = maps__find(kallsyms.kmaps, mem_start); if (pair == NULL || pair->priv) continue; diff --git a/tools/perf/tests/wp.c b/tools/perf/tests/wp.c index 9d4c45184e71..56455da30341 100644 --- a/tools/perf/tests/wp.c +++ b/tools/perf/tests/wp.c @@ -2,7 +2,9 @@ #include <stdlib.h> #include <string.h> #include <unistd.h> +#include <errno.h> #include <sys/ioctl.h> +#include <linux/compiler.h> #include <linux/hw_breakpoint.h> #include <linux/kernel.h> #include "tests.h" @@ -137,8 +139,7 @@ static int test__wp_rw(struct test_suite *test __maybe_unused, #endif } -static int test__wp_modify(struct test_suite *test __maybe_unused, - int subtest __maybe_unused) +static int test__wp_modify(struct test_suite *test __maybe_unused, int subtest __maybe_unused) { #if defined(__s390x__) return TEST_SKIP; @@ -160,6 +161,11 @@ static int test__wp_modify(struct test_suite *test __maybe_unused, new_attr.disabled = 1; ret = ioctl(fd, PERF_EVENT_IOC_MODIFY_ATTRIBUTES, &new_attr); if (ret < 0) { + if (errno == ENOTTY) { + test->test_cases[subtest].skip_reason = "missing kernel support"; + ret = TEST_SKIP; + } + pr_debug("ioctl(PERF_EVENT_IOC_MODIFY_ATTRIBUTES) failed\n"); close(fd); return ret; |