cachepc-linux

Fork of AMDESE/linux with modifications for CachePC side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-linux
Log | Files | Refs | README | LICENSE | sfeed.txt

parse-events.c (84773B)


      1// SPDX-License-Identifier: GPL-2.0
      2#include <linux/hw_breakpoint.h>
      3#include <linux/err.h>
      4#include <linux/zalloc.h>
      5#include <dirent.h>
      6#include <errno.h>
      7#include <sys/ioctl.h>
      8#include <sys/types.h>
      9#include <sys/stat.h>
     10#include <fcntl.h>
     11#include <sys/param.h>
     12#include "term.h"
     13#include "build-id.h"
     14#include "evlist.h"
     15#include "evsel.h"
     16#include <subcmd/pager.h>
     17#include <subcmd/parse-options.h>
     18#include "parse-events.h"
     19#include <subcmd/exec-cmd.h>
     20#include "string2.h"
     21#include "strlist.h"
     22#include "bpf-loader.h"
     23#include "debug.h"
     24#include <api/fs/tracing_path.h>
     25#include <perf/cpumap.h>
     26#include "parse-events-bison.h"
     27#define YY_EXTRA_TYPE void*
     28#include "parse-events-flex.h"
     29#include "pmu.h"
     30#include "thread_map.h"
     31#include "probe-file.h"
     32#include "asm/bug.h"
     33#include "util/parse-branch-options.h"
     34#include "metricgroup.h"
     35#include "util/evsel_config.h"
     36#include "util/event.h"
     37#include "util/pfm.h"
     38#include "util/parse-events-hybrid.h"
     39#include "util/pmu-hybrid.h"
     40#include "perf.h"
     41
     42#define MAX_NAME_LEN 100
     43
     44#ifdef PARSER_DEBUG
     45extern int parse_events_debug;
     46#endif
     47int parse_events_parse(void *parse_state, void *scanner);
     48static int get_config_terms(struct list_head *head_config,
     49			    struct list_head *head_terms __maybe_unused);
     50static int parse_events__with_hybrid_pmu(struct parse_events_state *parse_state,
     51					 const char *str, char *pmu_name,
     52					 struct list_head *list);
     53
     54static struct perf_pmu_event_symbol *perf_pmu_events_list;
     55/*
     56 * The variable indicates the number of supported pmu event symbols.
     57 * 0 means not initialized and ready to init
     58 * -1 means failed to init, don't try anymore
     59 * >0 is the number of supported pmu event symbols
     60 */
     61static int perf_pmu_events_list_num;
     62
     63struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
     64	[PERF_COUNT_HW_CPU_CYCLES] = {
     65		.symbol = "cpu-cycles",
     66		.alias  = "cycles",
     67	},
     68	[PERF_COUNT_HW_INSTRUCTIONS] = {
     69		.symbol = "instructions",
     70		.alias  = "",
     71	},
     72	[PERF_COUNT_HW_CACHE_REFERENCES] = {
     73		.symbol = "cache-references",
     74		.alias  = "",
     75	},
     76	[PERF_COUNT_HW_CACHE_MISSES] = {
     77		.symbol = "cache-misses",
     78		.alias  = "",
     79	},
     80	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
     81		.symbol = "branch-instructions",
     82		.alias  = "branches",
     83	},
     84	[PERF_COUNT_HW_BRANCH_MISSES] = {
     85		.symbol = "branch-misses",
     86		.alias  = "",
     87	},
     88	[PERF_COUNT_HW_BUS_CYCLES] = {
     89		.symbol = "bus-cycles",
     90		.alias  = "",
     91	},
     92	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
     93		.symbol = "stalled-cycles-frontend",
     94		.alias  = "idle-cycles-frontend",
     95	},
     96	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
     97		.symbol = "stalled-cycles-backend",
     98		.alias  = "idle-cycles-backend",
     99	},
    100	[PERF_COUNT_HW_REF_CPU_CYCLES] = {
    101		.symbol = "ref-cycles",
    102		.alias  = "",
    103	},
    104};
    105
    106struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
    107	[PERF_COUNT_SW_CPU_CLOCK] = {
    108		.symbol = "cpu-clock",
    109		.alias  = "",
    110	},
    111	[PERF_COUNT_SW_TASK_CLOCK] = {
    112		.symbol = "task-clock",
    113		.alias  = "",
    114	},
    115	[PERF_COUNT_SW_PAGE_FAULTS] = {
    116		.symbol = "page-faults",
    117		.alias  = "faults",
    118	},
    119	[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
    120		.symbol = "context-switches",
    121		.alias  = "cs",
    122	},
    123	[PERF_COUNT_SW_CPU_MIGRATIONS] = {
    124		.symbol = "cpu-migrations",
    125		.alias  = "migrations",
    126	},
    127	[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
    128		.symbol = "minor-faults",
    129		.alias  = "",
    130	},
    131	[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
    132		.symbol = "major-faults",
    133		.alias  = "",
    134	},
    135	[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
    136		.symbol = "alignment-faults",
    137		.alias  = "",
    138	},
    139	[PERF_COUNT_SW_EMULATION_FAULTS] = {
    140		.symbol = "emulation-faults",
    141		.alias  = "",
    142	},
    143	[PERF_COUNT_SW_DUMMY] = {
    144		.symbol = "dummy",
    145		.alias  = "",
    146	},
    147	[PERF_COUNT_SW_BPF_OUTPUT] = {
    148		.symbol = "bpf-output",
    149		.alias  = "",
    150	},
    151	[PERF_COUNT_SW_CGROUP_SWITCHES] = {
    152		.symbol = "cgroup-switches",
    153		.alias  = "",
    154	},
    155};
    156
    157struct event_symbol event_symbols_tool[PERF_TOOL_MAX] = {
    158	[PERF_TOOL_DURATION_TIME] = {
    159		.symbol = "duration_time",
    160		.alias  = "",
    161	},
    162	[PERF_TOOL_USER_TIME] = {
    163		.symbol = "user_time",
    164		.alias  = "",
    165	},
    166	[PERF_TOOL_SYSTEM_TIME] = {
    167		.symbol = "system_time",
    168		.alias  = "",
    169	},
    170};
    171
    172#define __PERF_EVENT_FIELD(config, name) \
    173	((config & PERF_EVENT_##name##_MASK) >> PERF_EVENT_##name##_SHIFT)
    174
    175#define PERF_EVENT_RAW(config)		__PERF_EVENT_FIELD(config, RAW)
    176#define PERF_EVENT_CONFIG(config)	__PERF_EVENT_FIELD(config, CONFIG)
    177#define PERF_EVENT_TYPE(config)		__PERF_EVENT_FIELD(config, TYPE)
    178#define PERF_EVENT_ID(config)		__PERF_EVENT_FIELD(config, EVENT)
    179
    180#define for_each_subsystem(sys_dir, sys_dirent)			\
    181	while ((sys_dirent = readdir(sys_dir)) != NULL)		\
    182		if (sys_dirent->d_type == DT_DIR &&		\
    183		    (strcmp(sys_dirent->d_name, ".")) &&	\
    184		    (strcmp(sys_dirent->d_name, "..")))
    185
    186static int tp_event_has_id(const char *dir_path, struct dirent *evt_dir)
    187{
    188	char evt_path[MAXPATHLEN];
    189	int fd;
    190
    191	snprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path, evt_dir->d_name);
    192	fd = open(evt_path, O_RDONLY);
    193	if (fd < 0)
    194		return -EINVAL;
    195	close(fd);
    196
    197	return 0;
    198}
    199
    200#define for_each_event(dir_path, evt_dir, evt_dirent)		\
    201	while ((evt_dirent = readdir(evt_dir)) != NULL)		\
    202		if (evt_dirent->d_type == DT_DIR &&		\
    203		    (strcmp(evt_dirent->d_name, ".")) &&	\
    204		    (strcmp(evt_dirent->d_name, "..")) &&	\
    205		    (!tp_event_has_id(dir_path, evt_dirent)))
    206
    207#define MAX_EVENT_LENGTH 512
    208
    209struct tracepoint_path *tracepoint_id_to_path(u64 config)
    210{
    211	struct tracepoint_path *path = NULL;
    212	DIR *sys_dir, *evt_dir;
    213	struct dirent *sys_dirent, *evt_dirent;
    214	char id_buf[24];
    215	int fd;
    216	u64 id;
    217	char evt_path[MAXPATHLEN];
    218	char *dir_path;
    219
    220	sys_dir = tracing_events__opendir();
    221	if (!sys_dir)
    222		return NULL;
    223
    224	for_each_subsystem(sys_dir, sys_dirent) {
    225		dir_path = get_events_file(sys_dirent->d_name);
    226		if (!dir_path)
    227			continue;
    228		evt_dir = opendir(dir_path);
    229		if (!evt_dir)
    230			goto next;
    231
    232		for_each_event(dir_path, evt_dir, evt_dirent) {
    233
    234			scnprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path,
    235				  evt_dirent->d_name);
    236			fd = open(evt_path, O_RDONLY);
    237			if (fd < 0)
    238				continue;
    239			if (read(fd, id_buf, sizeof(id_buf)) < 0) {
    240				close(fd);
    241				continue;
    242			}
    243			close(fd);
    244			id = atoll(id_buf);
    245			if (id == config) {
    246				put_events_file(dir_path);
    247				closedir(evt_dir);
    248				closedir(sys_dir);
    249				path = zalloc(sizeof(*path));
    250				if (!path)
    251					return NULL;
    252				if (asprintf(&path->system, "%.*s", MAX_EVENT_LENGTH, sys_dirent->d_name) < 0) {
    253					free(path);
    254					return NULL;
    255				}
    256				if (asprintf(&path->name, "%.*s", MAX_EVENT_LENGTH, evt_dirent->d_name) < 0) {
    257					zfree(&path->system);
    258					free(path);
    259					return NULL;
    260				}
    261				return path;
    262			}
    263		}
    264		closedir(evt_dir);
    265next:
    266		put_events_file(dir_path);
    267	}
    268
    269	closedir(sys_dir);
    270	return NULL;
    271}
    272
    273struct tracepoint_path *tracepoint_name_to_path(const char *name)
    274{
    275	struct tracepoint_path *path = zalloc(sizeof(*path));
    276	char *str = strchr(name, ':');
    277
    278	if (path == NULL || str == NULL) {
    279		free(path);
    280		return NULL;
    281	}
    282
    283	path->system = strndup(name, str - name);
    284	path->name = strdup(str+1);
    285
    286	if (path->system == NULL || path->name == NULL) {
    287		zfree(&path->system);
    288		zfree(&path->name);
    289		zfree(&path);
    290	}
    291
    292	return path;
    293}
    294
    295const char *event_type(int type)
    296{
    297	switch (type) {
    298	case PERF_TYPE_HARDWARE:
    299		return "hardware";
    300
    301	case PERF_TYPE_SOFTWARE:
    302		return "software";
    303
    304	case PERF_TYPE_TRACEPOINT:
    305		return "tracepoint";
    306
    307	case PERF_TYPE_HW_CACHE:
    308		return "hardware-cache";
    309
    310	default:
    311		break;
    312	}
    313
    314	return "unknown";
    315}
    316
    317static char *get_config_str(struct list_head *head_terms, int type_term)
    318{
    319	struct parse_events_term *term;
    320
    321	if (!head_terms)
    322		return NULL;
    323
    324	list_for_each_entry(term, head_terms, list)
    325		if (term->type_term == type_term)
    326			return term->val.str;
    327
    328	return NULL;
    329}
    330
    331static char *get_config_metric_id(struct list_head *head_terms)
    332{
    333	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_METRIC_ID);
    334}
    335
    336static char *get_config_name(struct list_head *head_terms)
    337{
    338	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_NAME);
    339}
    340
    341static struct evsel *
    342__add_event(struct list_head *list, int *idx,
    343	    struct perf_event_attr *attr,
    344	    bool init_attr,
    345	    const char *name, const char *metric_id, struct perf_pmu *pmu,
    346	    struct list_head *config_terms, bool auto_merge_stats,
    347	    const char *cpu_list)
    348{
    349	struct evsel *evsel;
    350	struct perf_cpu_map *cpus = pmu ? perf_cpu_map__get(pmu->cpus) :
    351			       cpu_list ? perf_cpu_map__new(cpu_list) : NULL;
    352
    353	if (pmu && attr->type == PERF_TYPE_RAW)
    354		perf_pmu__warn_invalid_config(pmu, attr->config, name);
    355
    356	if (init_attr)
    357		event_attr_init(attr);
    358
    359	evsel = evsel__new_idx(attr, *idx);
    360	if (!evsel) {
    361		perf_cpu_map__put(cpus);
    362		return NULL;
    363	}
    364
    365	(*idx)++;
    366	evsel->core.cpus = cpus;
    367	evsel->core.own_cpus = perf_cpu_map__get(cpus);
    368	evsel->core.requires_cpu = pmu ? pmu->is_uncore : false;
    369	evsel->auto_merge_stats = auto_merge_stats;
    370
    371	if (name)
    372		evsel->name = strdup(name);
    373
    374	if (metric_id)
    375		evsel->metric_id = strdup(metric_id);
    376
    377	if (config_terms)
    378		list_splice_init(config_terms, &evsel->config_terms);
    379
    380	if (list)
    381		list_add_tail(&evsel->core.node, list);
    382
    383	return evsel;
    384}
    385
    386struct evsel *parse_events__add_event(int idx, struct perf_event_attr *attr,
    387				      const char *name, const char *metric_id,
    388				      struct perf_pmu *pmu)
    389{
    390	return __add_event(/*list=*/NULL, &idx, attr, /*init_attr=*/false, name,
    391			   metric_id, pmu, /*config_terms=*/NULL,
    392			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL);
    393}
    394
    395static int add_event(struct list_head *list, int *idx,
    396		     struct perf_event_attr *attr, const char *name,
    397		     const char *metric_id, struct list_head *config_terms)
    398{
    399	return __add_event(list, idx, attr, /*init_attr*/true, name, metric_id,
    400			   /*pmu=*/NULL, config_terms,
    401			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL) ? 0 : -ENOMEM;
    402}
    403
    404static int add_event_tool(struct list_head *list, int *idx,
    405			  enum perf_tool_event tool_event)
    406{
    407	struct evsel *evsel;
    408	struct perf_event_attr attr = {
    409		.type = PERF_TYPE_SOFTWARE,
    410		.config = PERF_COUNT_SW_DUMMY,
    411	};
    412
    413	evsel = __add_event(list, idx, &attr, /*init_attr=*/true, /*name=*/NULL,
    414			    /*metric_id=*/NULL, /*pmu=*/NULL,
    415			    /*config_terms=*/NULL, /*auto_merge_stats=*/false,
    416			    /*cpu_list=*/"0");
    417	if (!evsel)
    418		return -ENOMEM;
    419	evsel->tool_event = tool_event;
    420	if (tool_event == PERF_TOOL_DURATION_TIME
    421	    || tool_event == PERF_TOOL_USER_TIME
    422	    || tool_event == PERF_TOOL_SYSTEM_TIME) {
    423		free((char *)evsel->unit);
    424		evsel->unit = strdup("ns");
    425	}
    426	return 0;
    427}
    428
    429static int parse_aliases(char *str, const char *const names[][EVSEL__MAX_ALIASES], int size)
    430{
    431	int i, j;
    432	int n, longest = -1;
    433
    434	for (i = 0; i < size; i++) {
    435		for (j = 0; j < EVSEL__MAX_ALIASES && names[i][j]; j++) {
    436			n = strlen(names[i][j]);
    437			if (n > longest && !strncasecmp(str, names[i][j], n))
    438				longest = n;
    439		}
    440		if (longest > 0)
    441			return i;
    442	}
    443
    444	return -1;
    445}
    446
    447typedef int config_term_func_t(struct perf_event_attr *attr,
    448			       struct parse_events_term *term,
    449			       struct parse_events_error *err);
    450static int config_term_common(struct perf_event_attr *attr,
    451			      struct parse_events_term *term,
    452			      struct parse_events_error *err);
    453static int config_attr(struct perf_event_attr *attr,
    454		       struct list_head *head,
    455		       struct parse_events_error *err,
    456		       config_term_func_t config_term);
    457
    458int parse_events_add_cache(struct list_head *list, int *idx,
    459			   char *type, char *op_result1, char *op_result2,
    460			   struct parse_events_error *err,
    461			   struct list_head *head_config,
    462			   struct parse_events_state *parse_state)
    463{
    464	struct perf_event_attr attr;
    465	LIST_HEAD(config_terms);
    466	char name[MAX_NAME_LEN];
    467	const char *config_name, *metric_id;
    468	int cache_type = -1, cache_op = -1, cache_result = -1;
    469	char *op_result[2] = { op_result1, op_result2 };
    470	int i, n, ret;
    471	bool hybrid;
    472
    473	/*
    474	 * No fallback - if we cannot get a clear cache type
    475	 * then bail out:
    476	 */
    477	cache_type = parse_aliases(type, evsel__hw_cache, PERF_COUNT_HW_CACHE_MAX);
    478	if (cache_type == -1)
    479		return -EINVAL;
    480
    481	config_name = get_config_name(head_config);
    482	n = snprintf(name, MAX_NAME_LEN, "%s", type);
    483
    484	for (i = 0; (i < 2) && (op_result[i]); i++) {
    485		char *str = op_result[i];
    486
    487		n += snprintf(name + n, MAX_NAME_LEN - n, "-%s", str);
    488
    489		if (cache_op == -1) {
    490			cache_op = parse_aliases(str, evsel__hw_cache_op,
    491						 PERF_COUNT_HW_CACHE_OP_MAX);
    492			if (cache_op >= 0) {
    493				if (!evsel__is_cache_op_valid(cache_type, cache_op))
    494					return -EINVAL;
    495				continue;
    496			}
    497		}
    498
    499		if (cache_result == -1) {
    500			cache_result = parse_aliases(str, evsel__hw_cache_result,
    501						     PERF_COUNT_HW_CACHE_RESULT_MAX);
    502			if (cache_result >= 0)
    503				continue;
    504		}
    505	}
    506
    507	/*
    508	 * Fall back to reads:
    509	 */
    510	if (cache_op == -1)
    511		cache_op = PERF_COUNT_HW_CACHE_OP_READ;
    512
    513	/*
    514	 * Fall back to accesses:
    515	 */
    516	if (cache_result == -1)
    517		cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
    518
    519	memset(&attr, 0, sizeof(attr));
    520	attr.config = cache_type | (cache_op << 8) | (cache_result << 16);
    521	attr.type = PERF_TYPE_HW_CACHE;
    522
    523	if (head_config) {
    524		if (config_attr(&attr, head_config, err,
    525				config_term_common))
    526			return -EINVAL;
    527
    528		if (get_config_terms(head_config, &config_terms))
    529			return -ENOMEM;
    530	}
    531
    532	metric_id = get_config_metric_id(head_config);
    533	ret = parse_events__add_cache_hybrid(list, idx, &attr,
    534					     config_name ? : name,
    535					     metric_id,
    536					     &config_terms,
    537					     &hybrid, parse_state);
    538	if (hybrid)
    539		goto out_free_terms;
    540
    541	ret = add_event(list, idx, &attr, config_name ? : name, metric_id,
    542			&config_terms);
    543out_free_terms:
    544	free_config_terms(&config_terms);
    545	return ret;
    546}
    547
    548static void tracepoint_error(struct parse_events_error *e, int err,
    549			     const char *sys, const char *name)
    550{
    551	const char *str;
    552	char help[BUFSIZ];
    553
    554	if (!e)
    555		return;
    556
    557	/*
    558	 * We get error directly from syscall errno ( > 0),
    559	 * or from encoded pointer's error ( < 0).
    560	 */
    561	err = abs(err);
    562
    563	switch (err) {
    564	case EACCES:
    565		str = "can't access trace events";
    566		break;
    567	case ENOENT:
    568		str = "unknown tracepoint";
    569		break;
    570	default:
    571		str = "failed to add tracepoint";
    572		break;
    573	}
    574
    575	tracing_path__strerror_open_tp(err, help, sizeof(help), sys, name);
    576	parse_events_error__handle(e, 0, strdup(str), strdup(help));
    577}
    578
    579static int add_tracepoint(struct list_head *list, int *idx,
    580			  const char *sys_name, const char *evt_name,
    581			  struct parse_events_error *err,
    582			  struct list_head *head_config)
    583{
    584	struct evsel *evsel = evsel__newtp_idx(sys_name, evt_name, (*idx)++);
    585
    586	if (IS_ERR(evsel)) {
    587		tracepoint_error(err, PTR_ERR(evsel), sys_name, evt_name);
    588		return PTR_ERR(evsel);
    589	}
    590
    591	if (head_config) {
    592		LIST_HEAD(config_terms);
    593
    594		if (get_config_terms(head_config, &config_terms))
    595			return -ENOMEM;
    596		list_splice(&config_terms, &evsel->config_terms);
    597	}
    598
    599	list_add_tail(&evsel->core.node, list);
    600	return 0;
    601}
    602
    603static int add_tracepoint_multi_event(struct list_head *list, int *idx,
    604				      const char *sys_name, const char *evt_name,
    605				      struct parse_events_error *err,
    606				      struct list_head *head_config)
    607{
    608	char *evt_path;
    609	struct dirent *evt_ent;
    610	DIR *evt_dir;
    611	int ret = 0, found = 0;
    612
    613	evt_path = get_events_file(sys_name);
    614	if (!evt_path) {
    615		tracepoint_error(err, errno, sys_name, evt_name);
    616		return -1;
    617	}
    618	evt_dir = opendir(evt_path);
    619	if (!evt_dir) {
    620		put_events_file(evt_path);
    621		tracepoint_error(err, errno, sys_name, evt_name);
    622		return -1;
    623	}
    624
    625	while (!ret && (evt_ent = readdir(evt_dir))) {
    626		if (!strcmp(evt_ent->d_name, ".")
    627		    || !strcmp(evt_ent->d_name, "..")
    628		    || !strcmp(evt_ent->d_name, "enable")
    629		    || !strcmp(evt_ent->d_name, "filter"))
    630			continue;
    631
    632		if (!strglobmatch(evt_ent->d_name, evt_name))
    633			continue;
    634
    635		found++;
    636
    637		ret = add_tracepoint(list, idx, sys_name, evt_ent->d_name,
    638				     err, head_config);
    639	}
    640
    641	if (!found) {
    642		tracepoint_error(err, ENOENT, sys_name, evt_name);
    643		ret = -1;
    644	}
    645
    646	put_events_file(evt_path);
    647	closedir(evt_dir);
    648	return ret;
    649}
    650
    651static int add_tracepoint_event(struct list_head *list, int *idx,
    652				const char *sys_name, const char *evt_name,
    653				struct parse_events_error *err,
    654				struct list_head *head_config)
    655{
    656	return strpbrk(evt_name, "*?") ?
    657	       add_tracepoint_multi_event(list, idx, sys_name, evt_name,
    658					  err, head_config) :
    659	       add_tracepoint(list, idx, sys_name, evt_name,
    660			      err, head_config);
    661}
    662
    663static int add_tracepoint_multi_sys(struct list_head *list, int *idx,
    664				    const char *sys_name, const char *evt_name,
    665				    struct parse_events_error *err,
    666				    struct list_head *head_config)
    667{
    668	struct dirent *events_ent;
    669	DIR *events_dir;
    670	int ret = 0;
    671
    672	events_dir = tracing_events__opendir();
    673	if (!events_dir) {
    674		tracepoint_error(err, errno, sys_name, evt_name);
    675		return -1;
    676	}
    677
    678	while (!ret && (events_ent = readdir(events_dir))) {
    679		if (!strcmp(events_ent->d_name, ".")
    680		    || !strcmp(events_ent->d_name, "..")
    681		    || !strcmp(events_ent->d_name, "enable")
    682		    || !strcmp(events_ent->d_name, "header_event")
    683		    || !strcmp(events_ent->d_name, "header_page"))
    684			continue;
    685
    686		if (!strglobmatch(events_ent->d_name, sys_name))
    687			continue;
    688
    689		ret = add_tracepoint_event(list, idx, events_ent->d_name,
    690					   evt_name, err, head_config);
    691	}
    692
    693	closedir(events_dir);
    694	return ret;
    695}
    696
    697#ifdef HAVE_LIBBPF_SUPPORT
    698struct __add_bpf_event_param {
    699	struct parse_events_state *parse_state;
    700	struct list_head *list;
    701	struct list_head *head_config;
    702};
    703
    704static int add_bpf_event(const char *group, const char *event, int fd, struct bpf_object *obj,
    705			 void *_param)
    706{
    707	LIST_HEAD(new_evsels);
    708	struct __add_bpf_event_param *param = _param;
    709	struct parse_events_state *parse_state = param->parse_state;
    710	struct list_head *list = param->list;
    711	struct evsel *pos;
    712	int err;
    713	/*
    714	 * Check if we should add the event, i.e. if it is a TP but starts with a '!',
    715	 * then don't add the tracepoint, this will be used for something else, like
    716	 * adding to a BPF_MAP_TYPE_PROG_ARRAY.
    717	 *
    718	 * See tools/perf/examples/bpf/augmented_raw_syscalls.c
    719	 */
    720	if (group[0] == '!')
    721		return 0;
    722
    723	pr_debug("add bpf event %s:%s and attach bpf program %d\n",
    724		 group, event, fd);
    725
    726	err = parse_events_add_tracepoint(&new_evsels, &parse_state->idx, group,
    727					  event, parse_state->error,
    728					  param->head_config);
    729	if (err) {
    730		struct evsel *evsel, *tmp;
    731
    732		pr_debug("Failed to add BPF event %s:%s\n",
    733			 group, event);
    734		list_for_each_entry_safe(evsel, tmp, &new_evsels, core.node) {
    735			list_del_init(&evsel->core.node);
    736			evsel__delete(evsel);
    737		}
    738		return err;
    739	}
    740	pr_debug("adding %s:%s\n", group, event);
    741
    742	list_for_each_entry(pos, &new_evsels, core.node) {
    743		pr_debug("adding %s:%s to %p\n",
    744			 group, event, pos);
    745		pos->bpf_fd = fd;
    746		pos->bpf_obj = obj;
    747	}
    748	list_splice(&new_evsels, list);
    749	return 0;
    750}
    751
    752int parse_events_load_bpf_obj(struct parse_events_state *parse_state,
    753			      struct list_head *list,
    754			      struct bpf_object *obj,
    755			      struct list_head *head_config)
    756{
    757	int err;
    758	char errbuf[BUFSIZ];
    759	struct __add_bpf_event_param param = {parse_state, list, head_config};
    760	static bool registered_unprobe_atexit = false;
    761
    762	if (IS_ERR(obj) || !obj) {
    763		snprintf(errbuf, sizeof(errbuf),
    764			 "Internal error: load bpf obj with NULL");
    765		err = -EINVAL;
    766		goto errout;
    767	}
    768
    769	/*
    770	 * Register atexit handler before calling bpf__probe() so
    771	 * bpf__probe() don't need to unprobe probe points its already
    772	 * created when failure.
    773	 */
    774	if (!registered_unprobe_atexit) {
    775		atexit(bpf__clear);
    776		registered_unprobe_atexit = true;
    777	}
    778
    779	err = bpf__probe(obj);
    780	if (err) {
    781		bpf__strerror_probe(obj, err, errbuf, sizeof(errbuf));
    782		goto errout;
    783	}
    784
    785	err = bpf__load(obj);
    786	if (err) {
    787		bpf__strerror_load(obj, err, errbuf, sizeof(errbuf));
    788		goto errout;
    789	}
    790
    791	err = bpf__foreach_event(obj, add_bpf_event, &param);
    792	if (err) {
    793		snprintf(errbuf, sizeof(errbuf),
    794			 "Attach events in BPF object failed");
    795		goto errout;
    796	}
    797
    798	return 0;
    799errout:
    800	parse_events_error__handle(parse_state->error, 0,
    801				strdup(errbuf), strdup("(add -v to see detail)"));
    802	return err;
    803}
    804
    805static int
    806parse_events_config_bpf(struct parse_events_state *parse_state,
    807			struct bpf_object *obj,
    808			struct list_head *head_config)
    809{
    810	struct parse_events_term *term;
    811	int error_pos;
    812
    813	if (!head_config || list_empty(head_config))
    814		return 0;
    815
    816	list_for_each_entry(term, head_config, list) {
    817		int err;
    818
    819		if (term->type_term != PARSE_EVENTS__TERM_TYPE_USER) {
    820			parse_events_error__handle(parse_state->error, term->err_term,
    821						strdup("Invalid config term for BPF object"),
    822						NULL);
    823			return -EINVAL;
    824		}
    825
    826		err = bpf__config_obj(obj, term, parse_state->evlist, &error_pos);
    827		if (err) {
    828			char errbuf[BUFSIZ];
    829			int idx;
    830
    831			bpf__strerror_config_obj(obj, term, parse_state->evlist,
    832						 &error_pos, err, errbuf,
    833						 sizeof(errbuf));
    834
    835			if (err == -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE)
    836				idx = term->err_val;
    837			else
    838				idx = term->err_term + error_pos;
    839
    840			parse_events_error__handle(parse_state->error, idx,
    841						strdup(errbuf),
    842						strdup(
    843"Hint:\tValid config terms:\n"
    844"     \tmap:[<arraymap>].value<indices>=[value]\n"
    845"     \tmap:[<eventmap>].event<indices>=[event]\n"
    846"\n"
    847"     \twhere <indices> is something like [0,3...5] or [all]\n"
    848"     \t(add -v to see detail)"));
    849			return err;
    850		}
    851	}
    852	return 0;
    853}
    854
    855/*
    856 * Split config terms:
    857 * perf record -e bpf.c/call-graph=fp,map:array.value[0]=1/ ...
    858 *  'call-graph=fp' is 'evt config', should be applied to each
    859 *  events in bpf.c.
    860 * 'map:array.value[0]=1' is 'obj config', should be processed
    861 * with parse_events_config_bpf.
    862 *
    863 * Move object config terms from the first list to obj_head_config.
    864 */
    865static void
    866split_bpf_config_terms(struct list_head *evt_head_config,
    867		       struct list_head *obj_head_config)
    868{
    869	struct parse_events_term *term, *temp;
    870
    871	/*
    872	 * Currently, all possible user config term
    873	 * belong to bpf object. parse_events__is_hardcoded_term()
    874	 * happens to be a good flag.
    875	 *
    876	 * See parse_events_config_bpf() and
    877	 * config_term_tracepoint().
    878	 */
    879	list_for_each_entry_safe(term, temp, evt_head_config, list)
    880		if (!parse_events__is_hardcoded_term(term))
    881			list_move_tail(&term->list, obj_head_config);
    882}
    883
    884int parse_events_load_bpf(struct parse_events_state *parse_state,
    885			  struct list_head *list,
    886			  char *bpf_file_name,
    887			  bool source,
    888			  struct list_head *head_config)
    889{
    890	int err;
    891	struct bpf_object *obj;
    892	LIST_HEAD(obj_head_config);
    893
    894	if (head_config)
    895		split_bpf_config_terms(head_config, &obj_head_config);
    896
    897	obj = bpf__prepare_load(bpf_file_name, source);
    898	if (IS_ERR(obj)) {
    899		char errbuf[BUFSIZ];
    900
    901		err = PTR_ERR(obj);
    902
    903		if (err == -ENOTSUP)
    904			snprintf(errbuf, sizeof(errbuf),
    905				 "BPF support is not compiled");
    906		else
    907			bpf__strerror_prepare_load(bpf_file_name,
    908						   source,
    909						   -err, errbuf,
    910						   sizeof(errbuf));
    911
    912		parse_events_error__handle(parse_state->error, 0,
    913					strdup(errbuf), strdup("(add -v to see detail)"));
    914		return err;
    915	}
    916
    917	err = parse_events_load_bpf_obj(parse_state, list, obj, head_config);
    918	if (err)
    919		return err;
    920	err = parse_events_config_bpf(parse_state, obj, &obj_head_config);
    921
    922	/*
    923	 * Caller doesn't know anything about obj_head_config,
    924	 * so combine them together again before returning.
    925	 */
    926	if (head_config)
    927		list_splice_tail(&obj_head_config, head_config);
    928	return err;
    929}
    930#else // HAVE_LIBBPF_SUPPORT
    931int parse_events_load_bpf_obj(struct parse_events_state *parse_state,
    932			      struct list_head *list __maybe_unused,
    933			      struct bpf_object *obj __maybe_unused,
    934			      struct list_head *head_config __maybe_unused)
    935{
    936	parse_events_error__handle(parse_state->error, 0,
    937				   strdup("BPF support is not compiled"),
    938				   strdup("Make sure libbpf-devel is available at build time."));
    939	return -ENOTSUP;
    940}
    941
    942int parse_events_load_bpf(struct parse_events_state *parse_state,
    943			  struct list_head *list __maybe_unused,
    944			  char *bpf_file_name __maybe_unused,
    945			  bool source __maybe_unused,
    946			  struct list_head *head_config __maybe_unused)
    947{
    948	parse_events_error__handle(parse_state->error, 0,
    949				   strdup("BPF support is not compiled"),
    950				   strdup("Make sure libbpf-devel is available at build time."));
    951	return -ENOTSUP;
    952}
    953#endif // HAVE_LIBBPF_SUPPORT
    954
    955static int
    956parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
    957{
    958	int i;
    959
    960	for (i = 0; i < 3; i++) {
    961		if (!type || !type[i])
    962			break;
    963
    964#define CHECK_SET_TYPE(bit)		\
    965do {					\
    966	if (attr->bp_type & bit)	\
    967		return -EINVAL;		\
    968	else				\
    969		attr->bp_type |= bit;	\
    970} while (0)
    971
    972		switch (type[i]) {
    973		case 'r':
    974			CHECK_SET_TYPE(HW_BREAKPOINT_R);
    975			break;
    976		case 'w':
    977			CHECK_SET_TYPE(HW_BREAKPOINT_W);
    978			break;
    979		case 'x':
    980			CHECK_SET_TYPE(HW_BREAKPOINT_X);
    981			break;
    982		default:
    983			return -EINVAL;
    984		}
    985	}
    986
    987#undef CHECK_SET_TYPE
    988
    989	if (!attr->bp_type) /* Default */
    990		attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
    991
    992	return 0;
    993}
    994
    995int parse_events_add_breakpoint(struct list_head *list, int *idx,
    996				u64 addr, char *type, u64 len)
    997{
    998	struct perf_event_attr attr;
    999
   1000	memset(&attr, 0, sizeof(attr));
   1001	attr.bp_addr = addr;
   1002
   1003	if (parse_breakpoint_type(type, &attr))
   1004		return -EINVAL;
   1005
   1006	/* Provide some defaults if len is not specified */
   1007	if (!len) {
   1008		if (attr.bp_type == HW_BREAKPOINT_X)
   1009			len = sizeof(long);
   1010		else
   1011			len = HW_BREAKPOINT_LEN_4;
   1012	}
   1013
   1014	attr.bp_len = len;
   1015
   1016	attr.type = PERF_TYPE_BREAKPOINT;
   1017	attr.sample_period = 1;
   1018
   1019	return add_event(list, idx, &attr, /*name=*/NULL, /*mertic_id=*/NULL,
   1020			 /*config_terms=*/NULL);
   1021}
   1022
   1023static int check_type_val(struct parse_events_term *term,
   1024			  struct parse_events_error *err,
   1025			  int type)
   1026{
   1027	if (type == term->type_val)
   1028		return 0;
   1029
   1030	if (err) {
   1031		parse_events_error__handle(err, term->err_val,
   1032					type == PARSE_EVENTS__TERM_TYPE_NUM
   1033					? strdup("expected numeric value")
   1034					: strdup("expected string value"),
   1035					NULL);
   1036	}
   1037	return -EINVAL;
   1038}
   1039
   1040/*
   1041 * Update according to parse-events.l
   1042 */
   1043static const char *config_term_names[__PARSE_EVENTS__TERM_TYPE_NR] = {
   1044	[PARSE_EVENTS__TERM_TYPE_USER]			= "<sysfs term>",
   1045	[PARSE_EVENTS__TERM_TYPE_CONFIG]		= "config",
   1046	[PARSE_EVENTS__TERM_TYPE_CONFIG1]		= "config1",
   1047	[PARSE_EVENTS__TERM_TYPE_CONFIG2]		= "config2",
   1048	[PARSE_EVENTS__TERM_TYPE_NAME]			= "name",
   1049	[PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD]		= "period",
   1050	[PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ]		= "freq",
   1051	[PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE]	= "branch_type",
   1052	[PARSE_EVENTS__TERM_TYPE_TIME]			= "time",
   1053	[PARSE_EVENTS__TERM_TYPE_CALLGRAPH]		= "call-graph",
   1054	[PARSE_EVENTS__TERM_TYPE_STACKSIZE]		= "stack-size",
   1055	[PARSE_EVENTS__TERM_TYPE_NOINHERIT]		= "no-inherit",
   1056	[PARSE_EVENTS__TERM_TYPE_INHERIT]		= "inherit",
   1057	[PARSE_EVENTS__TERM_TYPE_MAX_STACK]		= "max-stack",
   1058	[PARSE_EVENTS__TERM_TYPE_MAX_EVENTS]		= "nr",
   1059	[PARSE_EVENTS__TERM_TYPE_OVERWRITE]		= "overwrite",
   1060	[PARSE_EVENTS__TERM_TYPE_NOOVERWRITE]		= "no-overwrite",
   1061	[PARSE_EVENTS__TERM_TYPE_DRV_CFG]		= "driver-config",
   1062	[PARSE_EVENTS__TERM_TYPE_PERCORE]		= "percore",
   1063	[PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT]		= "aux-output",
   1064	[PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE]	= "aux-sample-size",
   1065	[PARSE_EVENTS__TERM_TYPE_METRIC_ID]		= "metric-id",
   1066};
   1067
   1068static bool config_term_shrinked;
   1069
   1070static bool
   1071config_term_avail(int term_type, struct parse_events_error *err)
   1072{
   1073	char *err_str;
   1074
   1075	if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
   1076		parse_events_error__handle(err, -1,
   1077					strdup("Invalid term_type"), NULL);
   1078		return false;
   1079	}
   1080	if (!config_term_shrinked)
   1081		return true;
   1082
   1083	switch (term_type) {
   1084	case PARSE_EVENTS__TERM_TYPE_CONFIG:
   1085	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
   1086	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
   1087	case PARSE_EVENTS__TERM_TYPE_NAME:
   1088	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
   1089	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
   1090	case PARSE_EVENTS__TERM_TYPE_PERCORE:
   1091		return true;
   1092	default:
   1093		if (!err)
   1094			return false;
   1095
   1096		/* term_type is validated so indexing is safe */
   1097		if (asprintf(&err_str, "'%s' is not usable in 'perf stat'",
   1098				config_term_names[term_type]) >= 0)
   1099			parse_events_error__handle(err, -1, err_str, NULL);
   1100		return false;
   1101	}
   1102}
   1103
   1104void parse_events__shrink_config_terms(void)
   1105{
   1106	config_term_shrinked = true;
   1107}
   1108
   1109static int config_term_common(struct perf_event_attr *attr,
   1110			      struct parse_events_term *term,
   1111			      struct parse_events_error *err)
   1112{
   1113#define CHECK_TYPE_VAL(type)						   \
   1114do {									   \
   1115	if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
   1116		return -EINVAL;						   \
   1117} while (0)
   1118
   1119	switch (term->type_term) {
   1120	case PARSE_EVENTS__TERM_TYPE_CONFIG:
   1121		CHECK_TYPE_VAL(NUM);
   1122		attr->config = term->val.num;
   1123		break;
   1124	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
   1125		CHECK_TYPE_VAL(NUM);
   1126		attr->config1 = term->val.num;
   1127		break;
   1128	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
   1129		CHECK_TYPE_VAL(NUM);
   1130		attr->config2 = term->val.num;
   1131		break;
   1132	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
   1133		CHECK_TYPE_VAL(NUM);
   1134		break;
   1135	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
   1136		CHECK_TYPE_VAL(NUM);
   1137		break;
   1138	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
   1139		CHECK_TYPE_VAL(STR);
   1140		if (strcmp(term->val.str, "no") &&
   1141		    parse_branch_str(term->val.str,
   1142				    &attr->branch_sample_type)) {
   1143			parse_events_error__handle(err, term->err_val,
   1144					strdup("invalid branch sample type"),
   1145					NULL);
   1146			return -EINVAL;
   1147		}
   1148		break;
   1149	case PARSE_EVENTS__TERM_TYPE_TIME:
   1150		CHECK_TYPE_VAL(NUM);
   1151		if (term->val.num > 1) {
   1152			parse_events_error__handle(err, term->err_val,
   1153						strdup("expected 0 or 1"),
   1154						NULL);
   1155			return -EINVAL;
   1156		}
   1157		break;
   1158	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
   1159		CHECK_TYPE_VAL(STR);
   1160		break;
   1161	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
   1162		CHECK_TYPE_VAL(NUM);
   1163		break;
   1164	case PARSE_EVENTS__TERM_TYPE_INHERIT:
   1165		CHECK_TYPE_VAL(NUM);
   1166		break;
   1167	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
   1168		CHECK_TYPE_VAL(NUM);
   1169		break;
   1170	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
   1171		CHECK_TYPE_VAL(NUM);
   1172		break;
   1173	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
   1174		CHECK_TYPE_VAL(NUM);
   1175		break;
   1176	case PARSE_EVENTS__TERM_TYPE_NAME:
   1177		CHECK_TYPE_VAL(STR);
   1178		break;
   1179	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
   1180		CHECK_TYPE_VAL(STR);
   1181		break;
   1182	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
   1183		CHECK_TYPE_VAL(NUM);
   1184		break;
   1185	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
   1186		CHECK_TYPE_VAL(NUM);
   1187		break;
   1188	case PARSE_EVENTS__TERM_TYPE_PERCORE:
   1189		CHECK_TYPE_VAL(NUM);
   1190		if ((unsigned int)term->val.num > 1) {
   1191			parse_events_error__handle(err, term->err_val,
   1192						strdup("expected 0 or 1"),
   1193						NULL);
   1194			return -EINVAL;
   1195		}
   1196		break;
   1197	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
   1198		CHECK_TYPE_VAL(NUM);
   1199		break;
   1200	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
   1201		CHECK_TYPE_VAL(NUM);
   1202		if (term->val.num > UINT_MAX) {
   1203			parse_events_error__handle(err, term->err_val,
   1204						strdup("too big"),
   1205						NULL);
   1206			return -EINVAL;
   1207		}
   1208		break;
   1209	default:
   1210		parse_events_error__handle(err, term->err_term,
   1211				strdup("unknown term"),
   1212				parse_events_formats_error_string(NULL));
   1213		return -EINVAL;
   1214	}
   1215
   1216	/*
   1217	 * Check term availability after basic checking so
   1218	 * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
   1219	 *
   1220	 * If check availability at the entry of this function,
   1221	 * user will see "'<sysfs term>' is not usable in 'perf stat'"
   1222	 * if an invalid config term is provided for legacy events
   1223	 * (for example, instructions/badterm/...), which is confusing.
   1224	 */
   1225	if (!config_term_avail(term->type_term, err))
   1226		return -EINVAL;
   1227	return 0;
   1228#undef CHECK_TYPE_VAL
   1229}
   1230
   1231static int config_term_pmu(struct perf_event_attr *attr,
   1232			   struct parse_events_term *term,
   1233			   struct parse_events_error *err)
   1234{
   1235	if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
   1236	    term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG)
   1237		/*
   1238		 * Always succeed for sysfs terms, as we dont know
   1239		 * at this point what type they need to have.
   1240		 */
   1241		return 0;
   1242	else
   1243		return config_term_common(attr, term, err);
   1244}
   1245
   1246static int config_term_tracepoint(struct perf_event_attr *attr,
   1247				  struct parse_events_term *term,
   1248				  struct parse_events_error *err)
   1249{
   1250	switch (term->type_term) {
   1251	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
   1252	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
   1253	case PARSE_EVENTS__TERM_TYPE_INHERIT:
   1254	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
   1255	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
   1256	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
   1257	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
   1258	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
   1259	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
   1260	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
   1261		return config_term_common(attr, term, err);
   1262	default:
   1263		if (err) {
   1264			parse_events_error__handle(err, term->err_term,
   1265				strdup("unknown term"),
   1266				strdup("valid terms: call-graph,stack-size\n"));
   1267		}
   1268		return -EINVAL;
   1269	}
   1270
   1271	return 0;
   1272}
   1273
   1274static int config_attr(struct perf_event_attr *attr,
   1275		       struct list_head *head,
   1276		       struct parse_events_error *err,
   1277		       config_term_func_t config_term)
   1278{
   1279	struct parse_events_term *term;
   1280
   1281	list_for_each_entry(term, head, list)
   1282		if (config_term(attr, term, err))
   1283			return -EINVAL;
   1284
   1285	return 0;
   1286}
   1287
   1288static int get_config_terms(struct list_head *head_config,
   1289			    struct list_head *head_terms __maybe_unused)
   1290{
   1291#define ADD_CONFIG_TERM(__type, __weak)				\
   1292	struct evsel_config_term *__t;			\
   1293								\
   1294	__t = zalloc(sizeof(*__t));				\
   1295	if (!__t)						\
   1296		return -ENOMEM;					\
   1297								\
   1298	INIT_LIST_HEAD(&__t->list);				\
   1299	__t->type       = EVSEL__CONFIG_TERM_ ## __type;	\
   1300	__t->weak	= __weak;				\
   1301	list_add_tail(&__t->list, head_terms)
   1302
   1303#define ADD_CONFIG_TERM_VAL(__type, __name, __val, __weak)	\
   1304do {								\
   1305	ADD_CONFIG_TERM(__type, __weak);			\
   1306	__t->val.__name = __val;				\
   1307} while (0)
   1308
   1309#define ADD_CONFIG_TERM_STR(__type, __val, __weak)		\
   1310do {								\
   1311	ADD_CONFIG_TERM(__type, __weak);			\
   1312	__t->val.str = strdup(__val);				\
   1313	if (!__t->val.str) {					\
   1314		zfree(&__t);					\
   1315		return -ENOMEM;					\
   1316	}							\
   1317	__t->free_str = true;					\
   1318} while (0)
   1319
   1320	struct parse_events_term *term;
   1321
   1322	list_for_each_entry(term, head_config, list) {
   1323		switch (term->type_term) {
   1324		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
   1325			ADD_CONFIG_TERM_VAL(PERIOD, period, term->val.num, term->weak);
   1326			break;
   1327		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
   1328			ADD_CONFIG_TERM_VAL(FREQ, freq, term->val.num, term->weak);
   1329			break;
   1330		case PARSE_EVENTS__TERM_TYPE_TIME:
   1331			ADD_CONFIG_TERM_VAL(TIME, time, term->val.num, term->weak);
   1332			break;
   1333		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
   1334			ADD_CONFIG_TERM_STR(CALLGRAPH, term->val.str, term->weak);
   1335			break;
   1336		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
   1337			ADD_CONFIG_TERM_STR(BRANCH, term->val.str, term->weak);
   1338			break;
   1339		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
   1340			ADD_CONFIG_TERM_VAL(STACK_USER, stack_user,
   1341					    term->val.num, term->weak);
   1342			break;
   1343		case PARSE_EVENTS__TERM_TYPE_INHERIT:
   1344			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
   1345					    term->val.num ? 1 : 0, term->weak);
   1346			break;
   1347		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
   1348			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
   1349					    term->val.num ? 0 : 1, term->weak);
   1350			break;
   1351		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
   1352			ADD_CONFIG_TERM_VAL(MAX_STACK, max_stack,
   1353					    term->val.num, term->weak);
   1354			break;
   1355		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
   1356			ADD_CONFIG_TERM_VAL(MAX_EVENTS, max_events,
   1357					    term->val.num, term->weak);
   1358			break;
   1359		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
   1360			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
   1361					    term->val.num ? 1 : 0, term->weak);
   1362			break;
   1363		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
   1364			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
   1365					    term->val.num ? 0 : 1, term->weak);
   1366			break;
   1367		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
   1368			ADD_CONFIG_TERM_STR(DRV_CFG, term->val.str, term->weak);
   1369			break;
   1370		case PARSE_EVENTS__TERM_TYPE_PERCORE:
   1371			ADD_CONFIG_TERM_VAL(PERCORE, percore,
   1372					    term->val.num ? true : false, term->weak);
   1373			break;
   1374		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
   1375			ADD_CONFIG_TERM_VAL(AUX_OUTPUT, aux_output,
   1376					    term->val.num ? 1 : 0, term->weak);
   1377			break;
   1378		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
   1379			ADD_CONFIG_TERM_VAL(AUX_SAMPLE_SIZE, aux_sample_size,
   1380					    term->val.num, term->weak);
   1381			break;
   1382		default:
   1383			break;
   1384		}
   1385	}
   1386	return 0;
   1387}
   1388
   1389/*
   1390 * Add EVSEL__CONFIG_TERM_CFG_CHG where cfg_chg will have a bit set for
   1391 * each bit of attr->config that the user has changed.
   1392 */
   1393static int get_config_chgs(struct perf_pmu *pmu, struct list_head *head_config,
   1394			   struct list_head *head_terms)
   1395{
   1396	struct parse_events_term *term;
   1397	u64 bits = 0;
   1398	int type;
   1399
   1400	list_for_each_entry(term, head_config, list) {
   1401		switch (term->type_term) {
   1402		case PARSE_EVENTS__TERM_TYPE_USER:
   1403			type = perf_pmu__format_type(&pmu->format, term->config);
   1404			if (type != PERF_PMU_FORMAT_VALUE_CONFIG)
   1405				continue;
   1406			bits |= perf_pmu__format_bits(&pmu->format, term->config);
   1407			break;
   1408		case PARSE_EVENTS__TERM_TYPE_CONFIG:
   1409			bits = ~(u64)0;
   1410			break;
   1411		default:
   1412			break;
   1413		}
   1414	}
   1415
   1416	if (bits)
   1417		ADD_CONFIG_TERM_VAL(CFG_CHG, cfg_chg, bits, false);
   1418
   1419#undef ADD_CONFIG_TERM
   1420	return 0;
   1421}
   1422
   1423int parse_events_add_tracepoint(struct list_head *list, int *idx,
   1424				const char *sys, const char *event,
   1425				struct parse_events_error *err,
   1426				struct list_head *head_config)
   1427{
   1428	if (head_config) {
   1429		struct perf_event_attr attr;
   1430
   1431		if (config_attr(&attr, head_config, err,
   1432				config_term_tracepoint))
   1433			return -EINVAL;
   1434	}
   1435
   1436	if (strpbrk(sys, "*?"))
   1437		return add_tracepoint_multi_sys(list, idx, sys, event,
   1438						err, head_config);
   1439	else
   1440		return add_tracepoint_event(list, idx, sys, event,
   1441					    err, head_config);
   1442}
   1443
   1444int parse_events_add_numeric(struct parse_events_state *parse_state,
   1445			     struct list_head *list,
   1446			     u32 type, u64 config,
   1447			     struct list_head *head_config)
   1448{
   1449	struct perf_event_attr attr;
   1450	LIST_HEAD(config_terms);
   1451	const char *name, *metric_id;
   1452	bool hybrid;
   1453	int ret;
   1454
   1455	memset(&attr, 0, sizeof(attr));
   1456	attr.type = type;
   1457	attr.config = config;
   1458
   1459	if (head_config) {
   1460		if (config_attr(&attr, head_config, parse_state->error,
   1461				config_term_common))
   1462			return -EINVAL;
   1463
   1464		if (get_config_terms(head_config, &config_terms))
   1465			return -ENOMEM;
   1466	}
   1467
   1468	name = get_config_name(head_config);
   1469	metric_id = get_config_metric_id(head_config);
   1470	ret = parse_events__add_numeric_hybrid(parse_state, list, &attr,
   1471					       name, metric_id,
   1472					       &config_terms, &hybrid);
   1473	if (hybrid)
   1474		goto out_free_terms;
   1475
   1476	ret = add_event(list, &parse_state->idx, &attr, name, metric_id,
   1477			&config_terms);
   1478out_free_terms:
   1479	free_config_terms(&config_terms);
   1480	return ret;
   1481}
   1482
   1483int parse_events_add_tool(struct parse_events_state *parse_state,
   1484			  struct list_head *list,
   1485			  int tool_event)
   1486{
   1487	return add_event_tool(list, &parse_state->idx, tool_event);
   1488}
   1489
   1490static bool config_term_percore(struct list_head *config_terms)
   1491{
   1492	struct evsel_config_term *term;
   1493
   1494	list_for_each_entry(term, config_terms, list) {
   1495		if (term->type == EVSEL__CONFIG_TERM_PERCORE)
   1496			return term->val.percore;
   1497	}
   1498
   1499	return false;
   1500}
   1501
   1502static int parse_events__inside_hybrid_pmu(struct parse_events_state *parse_state,
   1503					   struct list_head *list, char *name,
   1504					   struct list_head *head_config)
   1505{
   1506	struct parse_events_term *term;
   1507	int ret = -1;
   1508
   1509	if (parse_state->fake_pmu || !head_config || list_empty(head_config) ||
   1510	    !perf_pmu__is_hybrid(name)) {
   1511		return -1;
   1512	}
   1513
   1514	/*
   1515	 * More than one term in list.
   1516	 */
   1517	if (head_config->next && head_config->next->next != head_config)
   1518		return -1;
   1519
   1520	term = list_first_entry(head_config, struct parse_events_term, list);
   1521	if (term && term->config && strcmp(term->config, "event")) {
   1522		ret = parse_events__with_hybrid_pmu(parse_state, term->config,
   1523						    name, list);
   1524	}
   1525
   1526	return ret;
   1527}
   1528
   1529int parse_events_add_pmu(struct parse_events_state *parse_state,
   1530			 struct list_head *list, char *name,
   1531			 struct list_head *head_config,
   1532			 bool auto_merge_stats,
   1533			 bool use_alias)
   1534{
   1535	struct perf_event_attr attr;
   1536	struct perf_pmu_info info;
   1537	struct perf_pmu *pmu;
   1538	struct evsel *evsel;
   1539	struct parse_events_error *err = parse_state->error;
   1540	bool use_uncore_alias;
   1541	LIST_HEAD(config_terms);
   1542
   1543	pmu = parse_state->fake_pmu ?: perf_pmu__find(name);
   1544
   1545	if (verbose > 1 && !(pmu && pmu->selectable)) {
   1546		fprintf(stderr, "Attempting to add event pmu '%s' with '",
   1547			name);
   1548		if (head_config) {
   1549			struct parse_events_term *term;
   1550
   1551			list_for_each_entry(term, head_config, list) {
   1552				fprintf(stderr, "%s,", term->config);
   1553			}
   1554		}
   1555		fprintf(stderr, "' that may result in non-fatal errors\n");
   1556	}
   1557
   1558	if (!pmu) {
   1559		char *err_str;
   1560
   1561		if (asprintf(&err_str,
   1562				"Cannot find PMU `%s'. Missing kernel support?",
   1563				name) >= 0)
   1564			parse_events_error__handle(err, 0, err_str, NULL);
   1565		return -EINVAL;
   1566	}
   1567
   1568	if (pmu->default_config) {
   1569		memcpy(&attr, pmu->default_config,
   1570		       sizeof(struct perf_event_attr));
   1571	} else {
   1572		memset(&attr, 0, sizeof(attr));
   1573	}
   1574
   1575	use_uncore_alias = (pmu->is_uncore && use_alias);
   1576
   1577	if (!head_config) {
   1578		attr.type = pmu->type;
   1579		evsel = __add_event(list, &parse_state->idx, &attr,
   1580				    /*init_attr=*/true, /*name=*/NULL,
   1581				    /*metric_id=*/NULL, pmu,
   1582				    /*config_terms=*/NULL, auto_merge_stats,
   1583				    /*cpu_list=*/NULL);
   1584		if (evsel) {
   1585			evsel->pmu_name = name ? strdup(name) : NULL;
   1586			evsel->use_uncore_alias = use_uncore_alias;
   1587			return 0;
   1588		} else {
   1589			return -ENOMEM;
   1590		}
   1591	}
   1592
   1593	if (!parse_state->fake_pmu && perf_pmu__check_alias(pmu, head_config, &info))
   1594		return -EINVAL;
   1595
   1596	if (verbose > 1) {
   1597		fprintf(stderr, "After aliases, add event pmu '%s' with '",
   1598			name);
   1599		if (head_config) {
   1600			struct parse_events_term *term;
   1601
   1602			list_for_each_entry(term, head_config, list) {
   1603				fprintf(stderr, "%s,", term->config);
   1604			}
   1605		}
   1606		fprintf(stderr, "' that may result in non-fatal errors\n");
   1607	}
   1608
   1609	/*
   1610	 * Configure hardcoded terms first, no need to check
   1611	 * return value when called with fail == 0 ;)
   1612	 */
   1613	if (config_attr(&attr, head_config, parse_state->error, config_term_pmu))
   1614		return -EINVAL;
   1615
   1616	if (get_config_terms(head_config, &config_terms))
   1617		return -ENOMEM;
   1618
   1619	/*
   1620	 * When using default config, record which bits of attr->config were
   1621	 * changed by the user.
   1622	 */
   1623	if (pmu->default_config && get_config_chgs(pmu, head_config, &config_terms))
   1624		return -ENOMEM;
   1625
   1626	if (!parse_events__inside_hybrid_pmu(parse_state, list, name,
   1627					     head_config)) {
   1628		return 0;
   1629	}
   1630
   1631	if (!parse_state->fake_pmu && perf_pmu__config(pmu, &attr, head_config, parse_state->error)) {
   1632		free_config_terms(&config_terms);
   1633		return -EINVAL;
   1634	}
   1635
   1636	evsel = __add_event(list, &parse_state->idx, &attr, /*init_attr=*/true,
   1637			    get_config_name(head_config),
   1638			    get_config_metric_id(head_config), pmu,
   1639			    &config_terms, auto_merge_stats, /*cpu_list=*/NULL);
   1640	if (!evsel)
   1641		return -ENOMEM;
   1642
   1643	if (evsel->name)
   1644		evsel->use_config_name = true;
   1645
   1646	evsel->pmu_name = name ? strdup(name) : NULL;
   1647	evsel->use_uncore_alias = use_uncore_alias;
   1648	evsel->percore = config_term_percore(&evsel->config_terms);
   1649
   1650	if (parse_state->fake_pmu)
   1651		return 0;
   1652
   1653	free((char *)evsel->unit);
   1654	evsel->unit = strdup(info.unit);
   1655	evsel->scale = info.scale;
   1656	evsel->per_pkg = info.per_pkg;
   1657	evsel->snapshot = info.snapshot;
   1658	evsel->metric_expr = info.metric_expr;
   1659	evsel->metric_name = info.metric_name;
   1660	return 0;
   1661}
   1662
   1663int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
   1664			       char *str, struct list_head *head,
   1665			       struct list_head **listp)
   1666{
   1667	struct parse_events_term *term;
   1668	struct list_head *list = NULL;
   1669	struct list_head *orig_head = NULL;
   1670	struct perf_pmu *pmu = NULL;
   1671	int ok = 0;
   1672	char *config;
   1673
   1674	*listp = NULL;
   1675
   1676	if (!head) {
   1677		head = malloc(sizeof(struct list_head));
   1678		if (!head)
   1679			goto out_err;
   1680
   1681		INIT_LIST_HEAD(head);
   1682	}
   1683	config = strdup(str);
   1684	if (!config)
   1685		goto out_err;
   1686
   1687	if (parse_events_term__num(&term,
   1688				   PARSE_EVENTS__TERM_TYPE_USER,
   1689				   config, 1, false, &config,
   1690					NULL) < 0) {
   1691		free(config);
   1692		goto out_err;
   1693	}
   1694	list_add_tail(&term->list, head);
   1695
   1696	/* Add it for all PMUs that support the alias */
   1697	list = malloc(sizeof(struct list_head));
   1698	if (!list)
   1699		goto out_err;
   1700
   1701	INIT_LIST_HEAD(list);
   1702
   1703	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
   1704		struct perf_pmu_alias *alias;
   1705
   1706		list_for_each_entry(alias, &pmu->aliases, list) {
   1707			if (!strcasecmp(alias->name, str)) {
   1708				parse_events_copy_term_list(head, &orig_head);
   1709				if (!parse_events_add_pmu(parse_state, list,
   1710							  pmu->name, orig_head,
   1711							  true, true)) {
   1712					pr_debug("%s -> %s/%s/\n", str,
   1713						 pmu->name, alias->str);
   1714					ok++;
   1715				}
   1716				parse_events_terms__delete(orig_head);
   1717			}
   1718		}
   1719	}
   1720
   1721	if (parse_state->fake_pmu) {
   1722		if (!parse_events_add_pmu(parse_state, list, str, head,
   1723					  true, true)) {
   1724			pr_debug("%s -> %s/%s/\n", str, "fake_pmu", str);
   1725			ok++;
   1726		}
   1727	}
   1728
   1729out_err:
   1730	if (ok)
   1731		*listp = list;
   1732	else
   1733		free(list);
   1734
   1735	parse_events_terms__delete(head);
   1736	return ok ? 0 : -1;
   1737}
   1738
   1739int parse_events__modifier_group(struct list_head *list,
   1740				 char *event_mod)
   1741{
   1742	return parse_events__modifier_event(list, event_mod, true);
   1743}
   1744
   1745/*
   1746 * Check if the two uncore PMUs are from the same uncore block
   1747 * The format of the uncore PMU name is uncore_#blockname_#pmuidx
   1748 */
   1749static bool is_same_uncore_block(const char *pmu_name_a, const char *pmu_name_b)
   1750{
   1751	char *end_a, *end_b;
   1752
   1753	end_a = strrchr(pmu_name_a, '_');
   1754	end_b = strrchr(pmu_name_b, '_');
   1755
   1756	if (!end_a || !end_b)
   1757		return false;
   1758
   1759	if ((end_a - pmu_name_a) != (end_b - pmu_name_b))
   1760		return false;
   1761
   1762	return (strncmp(pmu_name_a, pmu_name_b, end_a - pmu_name_a) == 0);
   1763}
   1764
   1765static int
   1766parse_events__set_leader_for_uncore_aliase(char *name, struct list_head *list,
   1767					   struct parse_events_state *parse_state)
   1768{
   1769	struct evsel *evsel, *leader;
   1770	uintptr_t *leaders;
   1771	bool is_leader = true;
   1772	int i, nr_pmu = 0, total_members, ret = 0;
   1773
   1774	leader = list_first_entry(list, struct evsel, core.node);
   1775	evsel = list_last_entry(list, struct evsel, core.node);
   1776	total_members = evsel->core.idx - leader->core.idx + 1;
   1777
   1778	leaders = calloc(total_members, sizeof(uintptr_t));
   1779	if (WARN_ON(!leaders))
   1780		return 0;
   1781
   1782	/*
   1783	 * Going through the whole group and doing sanity check.
   1784	 * All members must use alias, and be from the same uncore block.
   1785	 * Also, storing the leader events in an array.
   1786	 */
   1787	__evlist__for_each_entry(list, evsel) {
   1788
   1789		/* Only split the uncore group which members use alias */
   1790		if (!evsel->use_uncore_alias)
   1791			goto out;
   1792
   1793		/* The events must be from the same uncore block */
   1794		if (!is_same_uncore_block(leader->pmu_name, evsel->pmu_name))
   1795			goto out;
   1796
   1797		if (!is_leader)
   1798			continue;
   1799		/*
   1800		 * If the event's PMU name starts to repeat, it must be a new
   1801		 * event. That can be used to distinguish the leader from
   1802		 * other members, even they have the same event name.
   1803		 */
   1804		if ((leader != evsel) &&
   1805		    !strcmp(leader->pmu_name, evsel->pmu_name)) {
   1806			is_leader = false;
   1807			continue;
   1808		}
   1809
   1810		/* Store the leader event for each PMU */
   1811		leaders[nr_pmu++] = (uintptr_t) evsel;
   1812	}
   1813
   1814	/* only one event alias */
   1815	if (nr_pmu == total_members) {
   1816		parse_state->nr_groups--;
   1817		goto handled;
   1818	}
   1819
   1820	/*
   1821	 * An uncore event alias is a joint name which means the same event
   1822	 * runs on all PMUs of a block.
   1823	 * Perf doesn't support mixed events from different PMUs in the same
   1824	 * group. The big group has to be split into multiple small groups
   1825	 * which only include the events from the same PMU.
   1826	 *
   1827	 * Here the uncore event aliases must be from the same uncore block.
   1828	 * The number of PMUs must be same for each alias. The number of new
   1829	 * small groups equals to the number of PMUs.
   1830	 * Setting the leader event for corresponding members in each group.
   1831	 */
   1832	i = 0;
   1833	__evlist__for_each_entry(list, evsel) {
   1834		if (i >= nr_pmu)
   1835			i = 0;
   1836		evsel__set_leader(evsel, (struct evsel *) leaders[i++]);
   1837	}
   1838
   1839	/* The number of members and group name are same for each group */
   1840	for (i = 0; i < nr_pmu; i++) {
   1841		evsel = (struct evsel *) leaders[i];
   1842		evsel->core.nr_members = total_members / nr_pmu;
   1843		evsel->group_name = name ? strdup(name) : NULL;
   1844	}
   1845
   1846	/* Take the new small groups into account */
   1847	parse_state->nr_groups += nr_pmu - 1;
   1848
   1849handled:
   1850	ret = 1;
   1851out:
   1852	free(leaders);
   1853	return ret;
   1854}
   1855
   1856__weak struct evsel *arch_evlist__leader(struct list_head *list)
   1857{
   1858	return list_first_entry(list, struct evsel, core.node);
   1859}
   1860
   1861void parse_events__set_leader(char *name, struct list_head *list,
   1862			      struct parse_events_state *parse_state)
   1863{
   1864	struct evsel *leader;
   1865
   1866	if (list_empty(list)) {
   1867		WARN_ONCE(true, "WARNING: failed to set leader: empty list");
   1868		return;
   1869	}
   1870
   1871	if (parse_events__set_leader_for_uncore_aliase(name, list, parse_state))
   1872		return;
   1873
   1874	leader = arch_evlist__leader(list);
   1875	__perf_evlist__set_leader(list, &leader->core);
   1876	leader->group_name = name ? strdup(name) : NULL;
   1877	list_move(&leader->core.node, list);
   1878}
   1879
   1880/* list_event is assumed to point to malloc'ed memory */
   1881void parse_events_update_lists(struct list_head *list_event,
   1882			       struct list_head *list_all)
   1883{
   1884	/*
   1885	 * Called for single event definition. Update the
   1886	 * 'all event' list, and reinit the 'single event'
   1887	 * list, for next event definition.
   1888	 */
   1889	list_splice_tail(list_event, list_all);
   1890	free(list_event);
   1891}
   1892
   1893struct event_modifier {
   1894	int eu;
   1895	int ek;
   1896	int eh;
   1897	int eH;
   1898	int eG;
   1899	int eI;
   1900	int precise;
   1901	int precise_max;
   1902	int exclude_GH;
   1903	int sample_read;
   1904	int pinned;
   1905	int weak;
   1906	int exclusive;
   1907	int bpf_counter;
   1908};
   1909
   1910static int get_event_modifier(struct event_modifier *mod, char *str,
   1911			       struct evsel *evsel)
   1912{
   1913	int eu = evsel ? evsel->core.attr.exclude_user : 0;
   1914	int ek = evsel ? evsel->core.attr.exclude_kernel : 0;
   1915	int eh = evsel ? evsel->core.attr.exclude_hv : 0;
   1916	int eH = evsel ? evsel->core.attr.exclude_host : 0;
   1917	int eG = evsel ? evsel->core.attr.exclude_guest : 0;
   1918	int eI = evsel ? evsel->core.attr.exclude_idle : 0;
   1919	int precise = evsel ? evsel->core.attr.precise_ip : 0;
   1920	int precise_max = 0;
   1921	int sample_read = 0;
   1922	int pinned = evsel ? evsel->core.attr.pinned : 0;
   1923	int exclusive = evsel ? evsel->core.attr.exclusive : 0;
   1924
   1925	int exclude = eu | ek | eh;
   1926	int exclude_GH = evsel ? evsel->exclude_GH : 0;
   1927	int weak = 0;
   1928	int bpf_counter = 0;
   1929
   1930	memset(mod, 0, sizeof(*mod));
   1931
   1932	while (*str) {
   1933		if (*str == 'u') {
   1934			if (!exclude)
   1935				exclude = eu = ek = eh = 1;
   1936			if (!exclude_GH && !perf_guest)
   1937				eG = 1;
   1938			eu = 0;
   1939		} else if (*str == 'k') {
   1940			if (!exclude)
   1941				exclude = eu = ek = eh = 1;
   1942			ek = 0;
   1943		} else if (*str == 'h') {
   1944			if (!exclude)
   1945				exclude = eu = ek = eh = 1;
   1946			eh = 0;
   1947		} else if (*str == 'G') {
   1948			if (!exclude_GH)
   1949				exclude_GH = eG = eH = 1;
   1950			eG = 0;
   1951		} else if (*str == 'H') {
   1952			if (!exclude_GH)
   1953				exclude_GH = eG = eH = 1;
   1954			eH = 0;
   1955		} else if (*str == 'I') {
   1956			eI = 1;
   1957		} else if (*str == 'p') {
   1958			precise++;
   1959			/* use of precise requires exclude_guest */
   1960			if (!exclude_GH)
   1961				eG = 1;
   1962		} else if (*str == 'P') {
   1963			precise_max = 1;
   1964		} else if (*str == 'S') {
   1965			sample_read = 1;
   1966		} else if (*str == 'D') {
   1967			pinned = 1;
   1968		} else if (*str == 'e') {
   1969			exclusive = 1;
   1970		} else if (*str == 'W') {
   1971			weak = 1;
   1972		} else if (*str == 'b') {
   1973			bpf_counter = 1;
   1974		} else
   1975			break;
   1976
   1977		++str;
   1978	}
   1979
   1980	/*
   1981	 * precise ip:
   1982	 *
   1983	 *  0 - SAMPLE_IP can have arbitrary skid
   1984	 *  1 - SAMPLE_IP must have constant skid
   1985	 *  2 - SAMPLE_IP requested to have 0 skid
   1986	 *  3 - SAMPLE_IP must have 0 skid
   1987	 *
   1988	 *  See also PERF_RECORD_MISC_EXACT_IP
   1989	 */
   1990	if (precise > 3)
   1991		return -EINVAL;
   1992
   1993	mod->eu = eu;
   1994	mod->ek = ek;
   1995	mod->eh = eh;
   1996	mod->eH = eH;
   1997	mod->eG = eG;
   1998	mod->eI = eI;
   1999	mod->precise = precise;
   2000	mod->precise_max = precise_max;
   2001	mod->exclude_GH = exclude_GH;
   2002	mod->sample_read = sample_read;
   2003	mod->pinned = pinned;
   2004	mod->weak = weak;
   2005	mod->bpf_counter = bpf_counter;
   2006	mod->exclusive = exclusive;
   2007
   2008	return 0;
   2009}
   2010
   2011/*
   2012 * Basic modifier sanity check to validate it contains only one
   2013 * instance of any modifier (apart from 'p') present.
   2014 */
   2015static int check_modifier(char *str)
   2016{
   2017	char *p = str;
   2018
   2019	/* The sizeof includes 0 byte as well. */
   2020	if (strlen(str) > (sizeof("ukhGHpppPSDIWeb") - 1))
   2021		return -1;
   2022
   2023	while (*p) {
   2024		if (*p != 'p' && strchr(p + 1, *p))
   2025			return -1;
   2026		p++;
   2027	}
   2028
   2029	return 0;
   2030}
   2031
   2032int parse_events__modifier_event(struct list_head *list, char *str, bool add)
   2033{
   2034	struct evsel *evsel;
   2035	struct event_modifier mod;
   2036
   2037	if (str == NULL)
   2038		return 0;
   2039
   2040	if (check_modifier(str))
   2041		return -EINVAL;
   2042
   2043	if (!add && get_event_modifier(&mod, str, NULL))
   2044		return -EINVAL;
   2045
   2046	__evlist__for_each_entry(list, evsel) {
   2047		if (add && get_event_modifier(&mod, str, evsel))
   2048			return -EINVAL;
   2049
   2050		evsel->core.attr.exclude_user   = mod.eu;
   2051		evsel->core.attr.exclude_kernel = mod.ek;
   2052		evsel->core.attr.exclude_hv     = mod.eh;
   2053		evsel->core.attr.precise_ip     = mod.precise;
   2054		evsel->core.attr.exclude_host   = mod.eH;
   2055		evsel->core.attr.exclude_guest  = mod.eG;
   2056		evsel->core.attr.exclude_idle   = mod.eI;
   2057		evsel->exclude_GH          = mod.exclude_GH;
   2058		evsel->sample_read         = mod.sample_read;
   2059		evsel->precise_max         = mod.precise_max;
   2060		evsel->weak_group	   = mod.weak;
   2061		evsel->bpf_counter	   = mod.bpf_counter;
   2062
   2063		if (evsel__is_group_leader(evsel)) {
   2064			evsel->core.attr.pinned = mod.pinned;
   2065			evsel->core.attr.exclusive = mod.exclusive;
   2066		}
   2067	}
   2068
   2069	return 0;
   2070}
   2071
   2072int parse_events_name(struct list_head *list, const char *name)
   2073{
   2074	struct evsel *evsel;
   2075
   2076	__evlist__for_each_entry(list, evsel) {
   2077		if (!evsel->name)
   2078			evsel->name = strdup(name);
   2079	}
   2080
   2081	return 0;
   2082}
   2083
   2084static int
   2085comp_pmu(const void *p1, const void *p2)
   2086{
   2087	struct perf_pmu_event_symbol *pmu1 = (struct perf_pmu_event_symbol *) p1;
   2088	struct perf_pmu_event_symbol *pmu2 = (struct perf_pmu_event_symbol *) p2;
   2089
   2090	return strcasecmp(pmu1->symbol, pmu2->symbol);
   2091}
   2092
   2093static void perf_pmu__parse_cleanup(void)
   2094{
   2095	if (perf_pmu_events_list_num > 0) {
   2096		struct perf_pmu_event_symbol *p;
   2097		int i;
   2098
   2099		for (i = 0; i < perf_pmu_events_list_num; i++) {
   2100			p = perf_pmu_events_list + i;
   2101			zfree(&p->symbol);
   2102		}
   2103		zfree(&perf_pmu_events_list);
   2104		perf_pmu_events_list_num = 0;
   2105	}
   2106}
   2107
   2108#define SET_SYMBOL(str, stype)		\
   2109do {					\
   2110	p->symbol = str;		\
   2111	if (!p->symbol)			\
   2112		goto err;		\
   2113	p->type = stype;		\
   2114} while (0)
   2115
   2116/*
   2117 * Read the pmu events list from sysfs
   2118 * Save it into perf_pmu_events_list
   2119 */
   2120static void perf_pmu__parse_init(void)
   2121{
   2122
   2123	struct perf_pmu *pmu = NULL;
   2124	struct perf_pmu_alias *alias;
   2125	int len = 0;
   2126
   2127	pmu = NULL;
   2128	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
   2129		list_for_each_entry(alias, &pmu->aliases, list) {
   2130			char *tmp = strchr(alias->name, '-');
   2131
   2132			if (tmp) {
   2133				char *tmp2 = NULL;
   2134
   2135				tmp2 = strchr(tmp + 1, '-');
   2136				len++;
   2137				if (tmp2)
   2138					len++;
   2139			}
   2140
   2141			len++;
   2142		}
   2143	}
   2144
   2145	if (len == 0) {
   2146		perf_pmu_events_list_num = -1;
   2147		return;
   2148	}
   2149	perf_pmu_events_list = malloc(sizeof(struct perf_pmu_event_symbol) * len);
   2150	if (!perf_pmu_events_list)
   2151		return;
   2152	perf_pmu_events_list_num = len;
   2153
   2154	len = 0;
   2155	pmu = NULL;
   2156	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
   2157		list_for_each_entry(alias, &pmu->aliases, list) {
   2158			struct perf_pmu_event_symbol *p = perf_pmu_events_list + len;
   2159			char *tmp = strchr(alias->name, '-');
   2160			char *tmp2 = NULL;
   2161
   2162			if (tmp)
   2163				tmp2 = strchr(tmp + 1, '-');
   2164			if (tmp2) {
   2165				SET_SYMBOL(strndup(alias->name, tmp - alias->name),
   2166						PMU_EVENT_SYMBOL_PREFIX);
   2167				p++;
   2168				tmp++;
   2169				SET_SYMBOL(strndup(tmp, tmp2 - tmp), PMU_EVENT_SYMBOL_SUFFIX);
   2170				p++;
   2171				SET_SYMBOL(strdup(++tmp2), PMU_EVENT_SYMBOL_SUFFIX2);
   2172				len += 3;
   2173			} else if (tmp) {
   2174				SET_SYMBOL(strndup(alias->name, tmp - alias->name),
   2175						PMU_EVENT_SYMBOL_PREFIX);
   2176				p++;
   2177				SET_SYMBOL(strdup(++tmp), PMU_EVENT_SYMBOL_SUFFIX);
   2178				len += 2;
   2179			} else {
   2180				SET_SYMBOL(strdup(alias->name), PMU_EVENT_SYMBOL);
   2181				len++;
   2182			}
   2183		}
   2184	}
   2185	qsort(perf_pmu_events_list, len,
   2186		sizeof(struct perf_pmu_event_symbol), comp_pmu);
   2187
   2188	return;
   2189err:
   2190	perf_pmu__parse_cleanup();
   2191}
   2192
   2193/*
   2194 * This function injects special term in
   2195 * perf_pmu_events_list so the test code
   2196 * can check on this functionality.
   2197 */
   2198int perf_pmu__test_parse_init(void)
   2199{
   2200	struct perf_pmu_event_symbol *list, *tmp, symbols[] = {
   2201		{(char *)"read", PMU_EVENT_SYMBOL},
   2202		{(char *)"event", PMU_EVENT_SYMBOL_PREFIX},
   2203		{(char *)"two", PMU_EVENT_SYMBOL_SUFFIX},
   2204		{(char *)"hyphen", PMU_EVENT_SYMBOL_SUFFIX},
   2205		{(char *)"hyph", PMU_EVENT_SYMBOL_SUFFIX2},
   2206	};
   2207	unsigned long i, j;
   2208
   2209	tmp = list = malloc(sizeof(*list) * ARRAY_SIZE(symbols));
   2210	if (!list)
   2211		return -ENOMEM;
   2212
   2213	for (i = 0; i < ARRAY_SIZE(symbols); i++, tmp++) {
   2214		tmp->type = symbols[i].type;
   2215		tmp->symbol = strdup(symbols[i].symbol);
   2216		if (!tmp->symbol)
   2217			goto err_free;
   2218	}
   2219
   2220	perf_pmu_events_list = list;
   2221	perf_pmu_events_list_num = ARRAY_SIZE(symbols);
   2222
   2223	qsort(perf_pmu_events_list, ARRAY_SIZE(symbols),
   2224	      sizeof(struct perf_pmu_event_symbol), comp_pmu);
   2225	return 0;
   2226
   2227err_free:
   2228	for (j = 0, tmp = list; j < i; j++, tmp++)
   2229		free(tmp->symbol);
   2230	free(list);
   2231	return -ENOMEM;
   2232}
   2233
   2234enum perf_pmu_event_symbol_type
   2235perf_pmu__parse_check(const char *name)
   2236{
   2237	struct perf_pmu_event_symbol p, *r;
   2238
   2239	/* scan kernel pmu events from sysfs if needed */
   2240	if (perf_pmu_events_list_num == 0)
   2241		perf_pmu__parse_init();
   2242	/*
   2243	 * name "cpu" could be prefix of cpu-cycles or cpu// events.
   2244	 * cpu-cycles has been handled by hardcode.
   2245	 * So it must be cpu// events, not kernel pmu event.
   2246	 */
   2247	if ((perf_pmu_events_list_num <= 0) || !strcmp(name, "cpu"))
   2248		return PMU_EVENT_SYMBOL_ERR;
   2249
   2250	p.symbol = strdup(name);
   2251	r = bsearch(&p, perf_pmu_events_list,
   2252			(size_t) perf_pmu_events_list_num,
   2253			sizeof(struct perf_pmu_event_symbol), comp_pmu);
   2254	zfree(&p.symbol);
   2255	return r ? r->type : PMU_EVENT_SYMBOL_ERR;
   2256}
   2257
   2258static int parse_events__scanner(const char *str,
   2259				 struct parse_events_state *parse_state)
   2260{
   2261	YY_BUFFER_STATE buffer;
   2262	void *scanner;
   2263	int ret;
   2264
   2265	ret = parse_events_lex_init_extra(parse_state, &scanner);
   2266	if (ret)
   2267		return ret;
   2268
   2269	buffer = parse_events__scan_string(str, scanner);
   2270
   2271#ifdef PARSER_DEBUG
   2272	parse_events_debug = 1;
   2273	parse_events_set_debug(1, scanner);
   2274#endif
   2275	ret = parse_events_parse(parse_state, scanner);
   2276
   2277	parse_events__flush_buffer(buffer, scanner);
   2278	parse_events__delete_buffer(buffer, scanner);
   2279	parse_events_lex_destroy(scanner);
   2280	return ret;
   2281}
   2282
   2283/*
   2284 * parse event config string, return a list of event terms.
   2285 */
   2286int parse_events_terms(struct list_head *terms, const char *str)
   2287{
   2288	struct parse_events_state parse_state = {
   2289		.terms  = NULL,
   2290		.stoken = PE_START_TERMS,
   2291	};
   2292	int ret;
   2293
   2294	ret = parse_events__scanner(str, &parse_state);
   2295	perf_pmu__parse_cleanup();
   2296
   2297	if (!ret) {
   2298		list_splice(parse_state.terms, terms);
   2299		zfree(&parse_state.terms);
   2300		return 0;
   2301	}
   2302
   2303	parse_events_terms__delete(parse_state.terms);
   2304	return ret;
   2305}
   2306
   2307static int parse_events__with_hybrid_pmu(struct parse_events_state *parse_state,
   2308					 const char *str, char *pmu_name,
   2309					 struct list_head *list)
   2310{
   2311	struct parse_events_state ps = {
   2312		.list            = LIST_HEAD_INIT(ps.list),
   2313		.stoken          = PE_START_EVENTS,
   2314		.hybrid_pmu_name = pmu_name,
   2315		.idx             = parse_state->idx,
   2316	};
   2317	int ret;
   2318
   2319	ret = parse_events__scanner(str, &ps);
   2320	perf_pmu__parse_cleanup();
   2321
   2322	if (!ret) {
   2323		if (!list_empty(&ps.list)) {
   2324			list_splice(&ps.list, list);
   2325			parse_state->idx = ps.idx;
   2326			return 0;
   2327		} else
   2328			return -1;
   2329	}
   2330
   2331	return ret;
   2332}
   2333
   2334int __parse_events(struct evlist *evlist, const char *str,
   2335		   struct parse_events_error *err, struct perf_pmu *fake_pmu)
   2336{
   2337	struct parse_events_state parse_state = {
   2338		.list	  = LIST_HEAD_INIT(parse_state.list),
   2339		.idx	  = evlist->core.nr_entries,
   2340		.error	  = err,
   2341		.evlist	  = evlist,
   2342		.stoken	  = PE_START_EVENTS,
   2343		.fake_pmu = fake_pmu,
   2344	};
   2345	int ret;
   2346
   2347	ret = parse_events__scanner(str, &parse_state);
   2348	perf_pmu__parse_cleanup();
   2349
   2350	if (!ret && list_empty(&parse_state.list)) {
   2351		WARN_ONCE(true, "WARNING: event parser found nothing\n");
   2352		return -1;
   2353	}
   2354
   2355	/*
   2356	 * Add list to the evlist even with errors to allow callers to clean up.
   2357	 */
   2358	evlist__splice_list_tail(evlist, &parse_state.list);
   2359
   2360	if (!ret) {
   2361		struct evsel *last;
   2362
   2363		evlist->core.nr_groups += parse_state.nr_groups;
   2364		last = evlist__last(evlist);
   2365		last->cmdline_group_boundary = true;
   2366
   2367		return 0;
   2368	}
   2369
   2370	/*
   2371	 * There are 2 users - builtin-record and builtin-test objects.
   2372	 * Both call evlist__delete in case of error, so we dont
   2373	 * need to bother.
   2374	 */
   2375	return ret;
   2376}
   2377
   2378void parse_events_error__init(struct parse_events_error *err)
   2379{
   2380	bzero(err, sizeof(*err));
   2381}
   2382
   2383void parse_events_error__exit(struct parse_events_error *err)
   2384{
   2385	zfree(&err->str);
   2386	zfree(&err->help);
   2387	zfree(&err->first_str);
   2388	zfree(&err->first_help);
   2389}
   2390
   2391void parse_events_error__handle(struct parse_events_error *err, int idx,
   2392				char *str, char *help)
   2393{
   2394	if (WARN(!str, "WARNING: failed to provide error string\n")) {
   2395		free(help);
   2396		return;
   2397	}
   2398	switch (err->num_errors) {
   2399	case 0:
   2400		err->idx = idx;
   2401		err->str = str;
   2402		err->help = help;
   2403		break;
   2404	case 1:
   2405		err->first_idx = err->idx;
   2406		err->idx = idx;
   2407		err->first_str = err->str;
   2408		err->str = str;
   2409		err->first_help = err->help;
   2410		err->help = help;
   2411		break;
   2412	default:
   2413		pr_debug("Multiple errors dropping message: %s (%s)\n",
   2414			err->str, err->help);
   2415		free(err->str);
   2416		err->str = str;
   2417		free(err->help);
   2418		err->help = help;
   2419		break;
   2420	}
   2421	err->num_errors++;
   2422}
   2423
   2424#define MAX_WIDTH 1000
   2425static int get_term_width(void)
   2426{
   2427	struct winsize ws;
   2428
   2429	get_term_dimensions(&ws);
   2430	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
   2431}
   2432
   2433static void __parse_events_error__print(int err_idx, const char *err_str,
   2434					const char *err_help, const char *event)
   2435{
   2436	const char *str = "invalid or unsupported event: ";
   2437	char _buf[MAX_WIDTH];
   2438	char *buf = (char *) event;
   2439	int idx = 0;
   2440	if (err_str) {
   2441		/* -2 for extra '' in the final fprintf */
   2442		int width       = get_term_width() - 2;
   2443		int len_event   = strlen(event);
   2444		int len_str, max_len, cut = 0;
   2445
   2446		/*
   2447		 * Maximum error index indent, we will cut
   2448		 * the event string if it's bigger.
   2449		 */
   2450		int max_err_idx = 13;
   2451
   2452		/*
   2453		 * Let's be specific with the message when
   2454		 * we have the precise error.
   2455		 */
   2456		str     = "event syntax error: ";
   2457		len_str = strlen(str);
   2458		max_len = width - len_str;
   2459
   2460		buf = _buf;
   2461
   2462		/* We're cutting from the beginning. */
   2463		if (err_idx > max_err_idx)
   2464			cut = err_idx - max_err_idx;
   2465
   2466		strncpy(buf, event + cut, max_len);
   2467
   2468		/* Mark cut parts with '..' on both sides. */
   2469		if (cut)
   2470			buf[0] = buf[1] = '.';
   2471
   2472		if ((len_event - cut) > max_len) {
   2473			buf[max_len - 1] = buf[max_len - 2] = '.';
   2474			buf[max_len] = 0;
   2475		}
   2476
   2477		idx = len_str + err_idx - cut;
   2478	}
   2479
   2480	fprintf(stderr, "%s'%s'\n", str, buf);
   2481	if (idx) {
   2482		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err_str);
   2483		if (err_help)
   2484			fprintf(stderr, "\n%s\n", err_help);
   2485	}
   2486}
   2487
   2488void parse_events_error__print(struct parse_events_error *err,
   2489			       const char *event)
   2490{
   2491	if (!err->num_errors)
   2492		return;
   2493
   2494	__parse_events_error__print(err->idx, err->str, err->help, event);
   2495
   2496	if (err->num_errors > 1) {
   2497		fputs("\nInitial error:\n", stderr);
   2498		__parse_events_error__print(err->first_idx, err->first_str,
   2499					err->first_help, event);
   2500	}
   2501}
   2502
   2503#undef MAX_WIDTH
   2504
   2505int parse_events_option(const struct option *opt, const char *str,
   2506			int unset __maybe_unused)
   2507{
   2508	struct evlist *evlist = *(struct evlist **)opt->value;
   2509	struct parse_events_error err;
   2510	int ret;
   2511
   2512	parse_events_error__init(&err);
   2513	ret = parse_events(evlist, str, &err);
   2514
   2515	if (ret) {
   2516		parse_events_error__print(&err, str);
   2517		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
   2518	}
   2519	parse_events_error__exit(&err);
   2520
   2521	return ret;
   2522}
   2523
   2524int parse_events_option_new_evlist(const struct option *opt, const char *str, int unset)
   2525{
   2526	struct evlist **evlistp = opt->value;
   2527	int ret;
   2528
   2529	if (*evlistp == NULL) {
   2530		*evlistp = evlist__new();
   2531
   2532		if (*evlistp == NULL) {
   2533			fprintf(stderr, "Not enough memory to create evlist\n");
   2534			return -1;
   2535		}
   2536	}
   2537
   2538	ret = parse_events_option(opt, str, unset);
   2539	if (ret) {
   2540		evlist__delete(*evlistp);
   2541		*evlistp = NULL;
   2542	}
   2543
   2544	return ret;
   2545}
   2546
   2547static int
   2548foreach_evsel_in_last_glob(struct evlist *evlist,
   2549			   int (*func)(struct evsel *evsel,
   2550				       const void *arg),
   2551			   const void *arg)
   2552{
   2553	struct evsel *last = NULL;
   2554	int err;
   2555
   2556	/*
   2557	 * Don't return when list_empty, give func a chance to report
   2558	 * error when it found last == NULL.
   2559	 *
   2560	 * So no need to WARN here, let *func do this.
   2561	 */
   2562	if (evlist->core.nr_entries > 0)
   2563		last = evlist__last(evlist);
   2564
   2565	do {
   2566		err = (*func)(last, arg);
   2567		if (err)
   2568			return -1;
   2569		if (!last)
   2570			return 0;
   2571
   2572		if (last->core.node.prev == &evlist->core.entries)
   2573			return 0;
   2574		last = list_entry(last->core.node.prev, struct evsel, core.node);
   2575	} while (!last->cmdline_group_boundary);
   2576
   2577	return 0;
   2578}
   2579
   2580static int set_filter(struct evsel *evsel, const void *arg)
   2581{
   2582	const char *str = arg;
   2583	bool found = false;
   2584	int nr_addr_filters = 0;
   2585	struct perf_pmu *pmu = NULL;
   2586
   2587	if (evsel == NULL) {
   2588		fprintf(stderr,
   2589			"--filter option should follow a -e tracepoint or HW tracer option\n");
   2590		return -1;
   2591	}
   2592
   2593	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
   2594		if (evsel__append_tp_filter(evsel, str) < 0) {
   2595			fprintf(stderr,
   2596				"not enough memory to hold filter string\n");
   2597			return -1;
   2598		}
   2599
   2600		return 0;
   2601	}
   2602
   2603	while ((pmu = perf_pmu__scan(pmu)) != NULL)
   2604		if (pmu->type == evsel->core.attr.type) {
   2605			found = true;
   2606			break;
   2607		}
   2608
   2609	if (found)
   2610		perf_pmu__scan_file(pmu, "nr_addr_filters",
   2611				    "%d", &nr_addr_filters);
   2612
   2613	if (!nr_addr_filters) {
   2614		fprintf(stderr,
   2615			"This CPU does not support address filtering\n");
   2616		return -1;
   2617	}
   2618
   2619	if (evsel__append_addr_filter(evsel, str) < 0) {
   2620		fprintf(stderr,
   2621			"not enough memory to hold filter string\n");
   2622		return -1;
   2623	}
   2624
   2625	return 0;
   2626}
   2627
   2628int parse_filter(const struct option *opt, const char *str,
   2629		 int unset __maybe_unused)
   2630{
   2631	struct evlist *evlist = *(struct evlist **)opt->value;
   2632
   2633	return foreach_evsel_in_last_glob(evlist, set_filter,
   2634					  (const void *)str);
   2635}
   2636
   2637static int add_exclude_perf_filter(struct evsel *evsel,
   2638				   const void *arg __maybe_unused)
   2639{
   2640	char new_filter[64];
   2641
   2642	if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
   2643		fprintf(stderr,
   2644			"--exclude-perf option should follow a -e tracepoint option\n");
   2645		return -1;
   2646	}
   2647
   2648	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
   2649
   2650	if (evsel__append_tp_filter(evsel, new_filter) < 0) {
   2651		fprintf(stderr,
   2652			"not enough memory to hold filter string\n");
   2653		return -1;
   2654	}
   2655
   2656	return 0;
   2657}
   2658
   2659int exclude_perf(const struct option *opt,
   2660		 const char *arg __maybe_unused,
   2661		 int unset __maybe_unused)
   2662{
   2663	struct evlist *evlist = *(struct evlist **)opt->value;
   2664
   2665	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
   2666					  NULL);
   2667}
   2668
   2669static const char * const event_type_descriptors[] = {
   2670	"Hardware event",
   2671	"Software event",
   2672	"Tracepoint event",
   2673	"Hardware cache event",
   2674	"Raw hardware event descriptor",
   2675	"Hardware breakpoint",
   2676};
   2677
   2678static int cmp_string(const void *a, const void *b)
   2679{
   2680	const char * const *as = a;
   2681	const char * const *bs = b;
   2682
   2683	return strcmp(*as, *bs);
   2684}
   2685
   2686/*
   2687 * Print the events from <debugfs_mount_point>/tracing/events
   2688 */
   2689
   2690void print_tracepoint_events(const char *subsys_glob, const char *event_glob,
   2691			     bool name_only)
   2692{
   2693	DIR *sys_dir, *evt_dir;
   2694	struct dirent *sys_dirent, *evt_dirent;
   2695	char evt_path[MAXPATHLEN];
   2696	char *dir_path;
   2697	char **evt_list = NULL;
   2698	unsigned int evt_i = 0, evt_num = 0;
   2699	bool evt_num_known = false;
   2700
   2701restart:
   2702	sys_dir = tracing_events__opendir();
   2703	if (!sys_dir)
   2704		return;
   2705
   2706	if (evt_num_known) {
   2707		evt_list = zalloc(sizeof(char *) * evt_num);
   2708		if (!evt_list)
   2709			goto out_close_sys_dir;
   2710	}
   2711
   2712	for_each_subsystem(sys_dir, sys_dirent) {
   2713		if (subsys_glob != NULL &&
   2714		    !strglobmatch(sys_dirent->d_name, subsys_glob))
   2715			continue;
   2716
   2717		dir_path = get_events_file(sys_dirent->d_name);
   2718		if (!dir_path)
   2719			continue;
   2720		evt_dir = opendir(dir_path);
   2721		if (!evt_dir)
   2722			goto next;
   2723
   2724		for_each_event(dir_path, evt_dir, evt_dirent) {
   2725			if (event_glob != NULL &&
   2726			    !strglobmatch(evt_dirent->d_name, event_glob))
   2727				continue;
   2728
   2729			if (!evt_num_known) {
   2730				evt_num++;
   2731				continue;
   2732			}
   2733
   2734			snprintf(evt_path, MAXPATHLEN, "%s:%s",
   2735				 sys_dirent->d_name, evt_dirent->d_name);
   2736
   2737			evt_list[evt_i] = strdup(evt_path);
   2738			if (evt_list[evt_i] == NULL) {
   2739				put_events_file(dir_path);
   2740				goto out_close_evt_dir;
   2741			}
   2742			evt_i++;
   2743		}
   2744		closedir(evt_dir);
   2745next:
   2746		put_events_file(dir_path);
   2747	}
   2748	closedir(sys_dir);
   2749
   2750	if (!evt_num_known) {
   2751		evt_num_known = true;
   2752		goto restart;
   2753	}
   2754	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
   2755	evt_i = 0;
   2756	while (evt_i < evt_num) {
   2757		if (name_only) {
   2758			printf("%s ", evt_list[evt_i++]);
   2759			continue;
   2760		}
   2761		printf("  %-50s [%s]\n", evt_list[evt_i++],
   2762				event_type_descriptors[PERF_TYPE_TRACEPOINT]);
   2763	}
   2764	if (evt_num && pager_in_use())
   2765		printf("\n");
   2766
   2767out_free:
   2768	evt_num = evt_i;
   2769	for (evt_i = 0; evt_i < evt_num; evt_i++)
   2770		zfree(&evt_list[evt_i]);
   2771	zfree(&evt_list);
   2772	return;
   2773
   2774out_close_evt_dir:
   2775	closedir(evt_dir);
   2776out_close_sys_dir:
   2777	closedir(sys_dir);
   2778
   2779	printf("FATAL: not enough memory to print %s\n",
   2780			event_type_descriptors[PERF_TYPE_TRACEPOINT]);
   2781	if (evt_list)
   2782		goto out_free;
   2783}
   2784
   2785/*
   2786 * Check whether event is in <debugfs_mount_point>/tracing/events
   2787 */
   2788
   2789int is_valid_tracepoint(const char *event_string)
   2790{
   2791	DIR *sys_dir, *evt_dir;
   2792	struct dirent *sys_dirent, *evt_dirent;
   2793	char evt_path[MAXPATHLEN];
   2794	char *dir_path;
   2795
   2796	sys_dir = tracing_events__opendir();
   2797	if (!sys_dir)
   2798		return 0;
   2799
   2800	for_each_subsystem(sys_dir, sys_dirent) {
   2801		dir_path = get_events_file(sys_dirent->d_name);
   2802		if (!dir_path)
   2803			continue;
   2804		evt_dir = opendir(dir_path);
   2805		if (!evt_dir)
   2806			goto next;
   2807
   2808		for_each_event(dir_path, evt_dir, evt_dirent) {
   2809			snprintf(evt_path, MAXPATHLEN, "%s:%s",
   2810				 sys_dirent->d_name, evt_dirent->d_name);
   2811			if (!strcmp(evt_path, event_string)) {
   2812				closedir(evt_dir);
   2813				closedir(sys_dir);
   2814				return 1;
   2815			}
   2816		}
   2817		closedir(evt_dir);
   2818next:
   2819		put_events_file(dir_path);
   2820	}
   2821	closedir(sys_dir);
   2822	return 0;
   2823}
   2824
   2825static bool is_event_supported(u8 type, u64 config)
   2826{
   2827	bool ret = true;
   2828	int open_return;
   2829	struct evsel *evsel;
   2830	struct perf_event_attr attr = {
   2831		.type = type,
   2832		.config = config,
   2833		.disabled = 1,
   2834	};
   2835	struct perf_thread_map *tmap = thread_map__new_by_tid(0);
   2836
   2837	if (tmap == NULL)
   2838		return false;
   2839
   2840	evsel = evsel__new(&attr);
   2841	if (evsel) {
   2842		open_return = evsel__open(evsel, NULL, tmap);
   2843		ret = open_return >= 0;
   2844
   2845		if (open_return == -EACCES) {
   2846			/*
   2847			 * This happens if the paranoid value
   2848			 * /proc/sys/kernel/perf_event_paranoid is set to 2
   2849			 * Re-run with exclude_kernel set; we don't do that
   2850			 * by default as some ARM machines do not support it.
   2851			 *
   2852			 */
   2853			evsel->core.attr.exclude_kernel = 1;
   2854			ret = evsel__open(evsel, NULL, tmap) >= 0;
   2855		}
   2856		evsel__delete(evsel);
   2857	}
   2858
   2859	perf_thread_map__put(tmap);
   2860	return ret;
   2861}
   2862
   2863void print_sdt_events(const char *subsys_glob, const char *event_glob,
   2864		      bool name_only)
   2865{
   2866	struct probe_cache *pcache;
   2867	struct probe_cache_entry *ent;
   2868	struct strlist *bidlist, *sdtlist;
   2869	struct strlist_config cfg = {.dont_dupstr = true};
   2870	struct str_node *nd, *nd2;
   2871	char *buf, *path, *ptr = NULL;
   2872	bool show_detail = false;
   2873	int ret;
   2874
   2875	sdtlist = strlist__new(NULL, &cfg);
   2876	if (!sdtlist) {
   2877		pr_debug("Failed to allocate new strlist for SDT\n");
   2878		return;
   2879	}
   2880	bidlist = build_id_cache__list_all(true);
   2881	if (!bidlist) {
   2882		pr_debug("Failed to get buildids: %d\n", errno);
   2883		return;
   2884	}
   2885	strlist__for_each_entry(nd, bidlist) {
   2886		pcache = probe_cache__new(nd->s, NULL);
   2887		if (!pcache)
   2888			continue;
   2889		list_for_each_entry(ent, &pcache->entries, node) {
   2890			if (!ent->sdt)
   2891				continue;
   2892			if (subsys_glob &&
   2893			    !strglobmatch(ent->pev.group, subsys_glob))
   2894				continue;
   2895			if (event_glob &&
   2896			    !strglobmatch(ent->pev.event, event_glob))
   2897				continue;
   2898			ret = asprintf(&buf, "%s:%s@%s", ent->pev.group,
   2899					ent->pev.event, nd->s);
   2900			if (ret > 0)
   2901				strlist__add(sdtlist, buf);
   2902		}
   2903		probe_cache__delete(pcache);
   2904	}
   2905	strlist__delete(bidlist);
   2906
   2907	strlist__for_each_entry(nd, sdtlist) {
   2908		buf = strchr(nd->s, '@');
   2909		if (buf)
   2910			*(buf++) = '\0';
   2911		if (name_only) {
   2912			printf("%s ", nd->s);
   2913			continue;
   2914		}
   2915		nd2 = strlist__next(nd);
   2916		if (nd2) {
   2917			ptr = strchr(nd2->s, '@');
   2918			if (ptr)
   2919				*ptr = '\0';
   2920			if (strcmp(nd->s, nd2->s) == 0)
   2921				show_detail = true;
   2922		}
   2923		if (show_detail) {
   2924			path = build_id_cache__origname(buf);
   2925			ret = asprintf(&buf, "%s@%s(%.12s)", nd->s, path, buf);
   2926			if (ret > 0) {
   2927				printf("  %-50s [%s]\n", buf, "SDT event");
   2928				free(buf);
   2929			}
   2930			free(path);
   2931		} else
   2932			printf("  %-50s [%s]\n", nd->s, "SDT event");
   2933		if (nd2) {
   2934			if (strcmp(nd->s, nd2->s) != 0)
   2935				show_detail = false;
   2936			if (ptr)
   2937				*ptr = '@';
   2938		}
   2939	}
   2940	strlist__delete(sdtlist);
   2941}
   2942
   2943int print_hwcache_events(const char *event_glob, bool name_only)
   2944{
   2945	unsigned int type, op, i, evt_i = 0, evt_num = 0, npmus = 0;
   2946	char name[64], new_name[128];
   2947	char **evt_list = NULL, **evt_pmus = NULL;
   2948	bool evt_num_known = false;
   2949	struct perf_pmu *pmu = NULL;
   2950
   2951	if (perf_pmu__has_hybrid()) {
   2952		npmus = perf_pmu__hybrid_pmu_num();
   2953		evt_pmus = zalloc(sizeof(char *) * npmus);
   2954		if (!evt_pmus)
   2955			goto out_enomem;
   2956	}
   2957
   2958restart:
   2959	if (evt_num_known) {
   2960		evt_list = zalloc(sizeof(char *) * evt_num);
   2961		if (!evt_list)
   2962			goto out_enomem;
   2963	}
   2964
   2965	for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
   2966		for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
   2967			/* skip invalid cache type */
   2968			if (!evsel__is_cache_op_valid(type, op))
   2969				continue;
   2970
   2971			for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
   2972				unsigned int hybrid_supported = 0, j;
   2973				bool supported;
   2974
   2975				__evsel__hw_cache_type_op_res_name(type, op, i, name, sizeof(name));
   2976				if (event_glob != NULL && !strglobmatch(name, event_glob))
   2977					continue;
   2978
   2979				if (!perf_pmu__has_hybrid()) {
   2980					if (!is_event_supported(PERF_TYPE_HW_CACHE,
   2981								type | (op << 8) | (i << 16))) {
   2982						continue;
   2983					}
   2984				} else {
   2985					perf_pmu__for_each_hybrid_pmu(pmu) {
   2986						if (!evt_num_known) {
   2987							evt_num++;
   2988							continue;
   2989						}
   2990
   2991						supported = is_event_supported(
   2992									PERF_TYPE_HW_CACHE,
   2993									type | (op << 8) | (i << 16) |
   2994									((__u64)pmu->type << PERF_PMU_TYPE_SHIFT));
   2995						if (supported) {
   2996							snprintf(new_name, sizeof(new_name), "%s/%s/",
   2997								 pmu->name, name);
   2998							evt_pmus[hybrid_supported] = strdup(new_name);
   2999							hybrid_supported++;
   3000						}
   3001					}
   3002
   3003					if (hybrid_supported == 0)
   3004						continue;
   3005				}
   3006
   3007				if (!evt_num_known) {
   3008					evt_num++;
   3009					continue;
   3010				}
   3011
   3012				if ((hybrid_supported == 0) ||
   3013				    (hybrid_supported == npmus)) {
   3014					evt_list[evt_i] = strdup(name);
   3015					if (npmus > 0) {
   3016						for (j = 0; j < npmus; j++)
   3017							zfree(&evt_pmus[j]);
   3018					}
   3019				} else {
   3020					for (j = 0; j < hybrid_supported; j++) {
   3021						evt_list[evt_i++] = evt_pmus[j];
   3022						evt_pmus[j] = NULL;
   3023					}
   3024					continue;
   3025				}
   3026
   3027				if (evt_list[evt_i] == NULL)
   3028					goto out_enomem;
   3029				evt_i++;
   3030			}
   3031		}
   3032	}
   3033
   3034	if (!evt_num_known) {
   3035		evt_num_known = true;
   3036		goto restart;
   3037	}
   3038
   3039	for (evt_i = 0; evt_i < evt_num; evt_i++) {
   3040		if (!evt_list[evt_i])
   3041			break;
   3042	}
   3043
   3044	evt_num = evt_i;
   3045	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
   3046	evt_i = 0;
   3047	while (evt_i < evt_num) {
   3048		if (name_only) {
   3049			printf("%s ", evt_list[evt_i++]);
   3050			continue;
   3051		}
   3052		printf("  %-50s [%s]\n", evt_list[evt_i++],
   3053				event_type_descriptors[PERF_TYPE_HW_CACHE]);
   3054	}
   3055	if (evt_num && pager_in_use())
   3056		printf("\n");
   3057
   3058out_free:
   3059	evt_num = evt_i;
   3060	for (evt_i = 0; evt_i < evt_num; evt_i++)
   3061		zfree(&evt_list[evt_i]);
   3062	zfree(&evt_list);
   3063
   3064	for (evt_i = 0; evt_i < npmus; evt_i++)
   3065		zfree(&evt_pmus[evt_i]);
   3066	zfree(&evt_pmus);
   3067	return evt_num;
   3068
   3069out_enomem:
   3070	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[PERF_TYPE_HW_CACHE]);
   3071	if (evt_list)
   3072		goto out_free;
   3073	return evt_num;
   3074}
   3075
   3076static void print_tool_event(const struct event_symbol *syms, const char *event_glob,
   3077			     bool name_only)
   3078{
   3079	if (syms->symbol == NULL)
   3080		return;
   3081
   3082	if (event_glob && !(strglobmatch(syms->symbol, event_glob) ||
   3083	      (syms->alias && strglobmatch(syms->alias, event_glob))))
   3084		return;
   3085
   3086	if (name_only)
   3087		printf("%s ", syms->symbol);
   3088	else {
   3089		char name[MAX_NAME_LEN];
   3090		if (syms->alias && strlen(syms->alias))
   3091			snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
   3092		else
   3093			strlcpy(name, syms->symbol, MAX_NAME_LEN);
   3094		printf("  %-50s [%s]\n", name, "Tool event");
   3095	}
   3096}
   3097
   3098void print_tool_events(const char *event_glob, bool name_only)
   3099{
   3100	// Start at 1 because the first enum entry symbols no tool event
   3101	for (int i = 1; i < PERF_TOOL_MAX; ++i) {
   3102		print_tool_event(event_symbols_tool + i, event_glob, name_only);
   3103	}
   3104	if (pager_in_use())
   3105		printf("\n");
   3106}
   3107
   3108void print_symbol_events(const char *event_glob, unsigned type,
   3109				struct event_symbol *syms, unsigned max,
   3110				bool name_only)
   3111{
   3112	unsigned int i, evt_i = 0, evt_num = 0;
   3113	char name[MAX_NAME_LEN];
   3114	char **evt_list = NULL;
   3115	bool evt_num_known = false;
   3116
   3117restart:
   3118	if (evt_num_known) {
   3119		evt_list = zalloc(sizeof(char *) * evt_num);
   3120		if (!evt_list)
   3121			goto out_enomem;
   3122		syms -= max;
   3123	}
   3124
   3125	for (i = 0; i < max; i++, syms++) {
   3126		/*
   3127		 * New attr.config still not supported here, the latest
   3128		 * example was PERF_COUNT_SW_CGROUP_SWITCHES
   3129		 */
   3130		if (syms->symbol == NULL)
   3131			continue;
   3132
   3133		if (event_glob != NULL && !(strglobmatch(syms->symbol, event_glob) ||
   3134		      (syms->alias && strglobmatch(syms->alias, event_glob))))
   3135			continue;
   3136
   3137		if (!is_event_supported(type, i))
   3138			continue;
   3139
   3140		if (!evt_num_known) {
   3141			evt_num++;
   3142			continue;
   3143		}
   3144
   3145		if (!name_only && strlen(syms->alias))
   3146			snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
   3147		else
   3148			strlcpy(name, syms->symbol, MAX_NAME_LEN);
   3149
   3150		evt_list[evt_i] = strdup(name);
   3151		if (evt_list[evt_i] == NULL)
   3152			goto out_enomem;
   3153		evt_i++;
   3154	}
   3155
   3156	if (!evt_num_known) {
   3157		evt_num_known = true;
   3158		goto restart;
   3159	}
   3160	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
   3161	evt_i = 0;
   3162	while (evt_i < evt_num) {
   3163		if (name_only) {
   3164			printf("%s ", evt_list[evt_i++]);
   3165			continue;
   3166		}
   3167		printf("  %-50s [%s]\n", evt_list[evt_i++], event_type_descriptors[type]);
   3168	}
   3169	if (evt_num && pager_in_use())
   3170		printf("\n");
   3171
   3172out_free:
   3173	evt_num = evt_i;
   3174	for (evt_i = 0; evt_i < evt_num; evt_i++)
   3175		zfree(&evt_list[evt_i]);
   3176	zfree(&evt_list);
   3177	return;
   3178
   3179out_enomem:
   3180	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[type]);
   3181	if (evt_list)
   3182		goto out_free;
   3183}
   3184
   3185/*
   3186 * Print the help text for the event symbols:
   3187 */
   3188void print_events(const char *event_glob, bool name_only, bool quiet_flag,
   3189			bool long_desc, bool details_flag, bool deprecated,
   3190			const char *pmu_name)
   3191{
   3192	print_symbol_events(event_glob, PERF_TYPE_HARDWARE,
   3193			    event_symbols_hw, PERF_COUNT_HW_MAX, name_only);
   3194
   3195	print_symbol_events(event_glob, PERF_TYPE_SOFTWARE,
   3196			    event_symbols_sw, PERF_COUNT_SW_MAX, name_only);
   3197	print_tool_events(event_glob, name_only);
   3198
   3199	print_hwcache_events(event_glob, name_only);
   3200
   3201	print_pmu_events(event_glob, name_only, quiet_flag, long_desc,
   3202			details_flag, deprecated, pmu_name);
   3203
   3204	if (event_glob != NULL)
   3205		return;
   3206
   3207	if (!name_only) {
   3208		printf("  %-50s [%s]\n",
   3209		       "rNNN",
   3210		       event_type_descriptors[PERF_TYPE_RAW]);
   3211		printf("  %-50s [%s]\n",
   3212		       "cpu/t1=v1[,t2=v2,t3 ...]/modifier",
   3213		       event_type_descriptors[PERF_TYPE_RAW]);
   3214		if (pager_in_use())
   3215			printf("   (see 'man perf-list' on how to encode it)\n\n");
   3216
   3217		printf("  %-50s [%s]\n",
   3218		       "mem:<addr>[/len][:access]",
   3219			event_type_descriptors[PERF_TYPE_BREAKPOINT]);
   3220		if (pager_in_use())
   3221			printf("\n");
   3222	}
   3223
   3224	print_tracepoint_events(NULL, NULL, name_only);
   3225
   3226	print_sdt_events(NULL, NULL, name_only);
   3227
   3228	metricgroup__print(true, true, NULL, name_only, details_flag,
   3229			   pmu_name);
   3230
   3231	print_libpfm_events(name_only, long_desc);
   3232}
   3233
   3234int parse_events__is_hardcoded_term(struct parse_events_term *term)
   3235{
   3236	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
   3237}
   3238
   3239static int new_term(struct parse_events_term **_term,
   3240		    struct parse_events_term *temp,
   3241		    char *str, u64 num)
   3242{
   3243	struct parse_events_term *term;
   3244
   3245	term = malloc(sizeof(*term));
   3246	if (!term)
   3247		return -ENOMEM;
   3248
   3249	*term = *temp;
   3250	INIT_LIST_HEAD(&term->list);
   3251	term->weak = false;
   3252
   3253	switch (term->type_val) {
   3254	case PARSE_EVENTS__TERM_TYPE_NUM:
   3255		term->val.num = num;
   3256		break;
   3257	case PARSE_EVENTS__TERM_TYPE_STR:
   3258		term->val.str = str;
   3259		break;
   3260	default:
   3261		free(term);
   3262		return -EINVAL;
   3263	}
   3264
   3265	*_term = term;
   3266	return 0;
   3267}
   3268
   3269int parse_events_term__num(struct parse_events_term **term,
   3270			   int type_term, char *config, u64 num,
   3271			   bool no_value,
   3272			   void *loc_term_, void *loc_val_)
   3273{
   3274	YYLTYPE *loc_term = loc_term_;
   3275	YYLTYPE *loc_val = loc_val_;
   3276
   3277	struct parse_events_term temp = {
   3278		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
   3279		.type_term = type_term,
   3280		.config    = config ? : strdup(config_term_names[type_term]),
   3281		.no_value  = no_value,
   3282		.err_term  = loc_term ? loc_term->first_column : 0,
   3283		.err_val   = loc_val  ? loc_val->first_column  : 0,
   3284	};
   3285
   3286	return new_term(term, &temp, NULL, num);
   3287}
   3288
   3289int parse_events_term__str(struct parse_events_term **term,
   3290			   int type_term, char *config, char *str,
   3291			   void *loc_term_, void *loc_val_)
   3292{
   3293	YYLTYPE *loc_term = loc_term_;
   3294	YYLTYPE *loc_val = loc_val_;
   3295
   3296	struct parse_events_term temp = {
   3297		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
   3298		.type_term = type_term,
   3299		.config    = config,
   3300		.err_term  = loc_term ? loc_term->first_column : 0,
   3301		.err_val   = loc_val  ? loc_val->first_column  : 0,
   3302	};
   3303
   3304	return new_term(term, &temp, str, 0);
   3305}
   3306
   3307int parse_events_term__sym_hw(struct parse_events_term **term,
   3308			      char *config, unsigned idx)
   3309{
   3310	struct event_symbol *sym;
   3311	char *str;
   3312	struct parse_events_term temp = {
   3313		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
   3314		.type_term = PARSE_EVENTS__TERM_TYPE_USER,
   3315		.config    = config,
   3316	};
   3317
   3318	if (!temp.config) {
   3319		temp.config = strdup("event");
   3320		if (!temp.config)
   3321			return -ENOMEM;
   3322	}
   3323	BUG_ON(idx >= PERF_COUNT_HW_MAX);
   3324	sym = &event_symbols_hw[idx];
   3325
   3326	str = strdup(sym->symbol);
   3327	if (!str)
   3328		return -ENOMEM;
   3329	return new_term(term, &temp, str, 0);
   3330}
   3331
   3332int parse_events_term__clone(struct parse_events_term **new,
   3333			     struct parse_events_term *term)
   3334{
   3335	char *str;
   3336	struct parse_events_term temp = {
   3337		.type_val  = term->type_val,
   3338		.type_term = term->type_term,
   3339		.config    = NULL,
   3340		.err_term  = term->err_term,
   3341		.err_val   = term->err_val,
   3342	};
   3343
   3344	if (term->config) {
   3345		temp.config = strdup(term->config);
   3346		if (!temp.config)
   3347			return -ENOMEM;
   3348	}
   3349	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
   3350		return new_term(new, &temp, NULL, term->val.num);
   3351
   3352	str = strdup(term->val.str);
   3353	if (!str)
   3354		return -ENOMEM;
   3355	return new_term(new, &temp, str, 0);
   3356}
   3357
   3358void parse_events_term__delete(struct parse_events_term *term)
   3359{
   3360	if (term->array.nr_ranges)
   3361		zfree(&term->array.ranges);
   3362
   3363	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM)
   3364		zfree(&term->val.str);
   3365
   3366	zfree(&term->config);
   3367	free(term);
   3368}
   3369
   3370int parse_events_copy_term_list(struct list_head *old,
   3371				 struct list_head **new)
   3372{
   3373	struct parse_events_term *term, *n;
   3374	int ret;
   3375
   3376	if (!old) {
   3377		*new = NULL;
   3378		return 0;
   3379	}
   3380
   3381	*new = malloc(sizeof(struct list_head));
   3382	if (!*new)
   3383		return -ENOMEM;
   3384	INIT_LIST_HEAD(*new);
   3385
   3386	list_for_each_entry (term, old, list) {
   3387		ret = parse_events_term__clone(&n, term);
   3388		if (ret)
   3389			return ret;
   3390		list_add_tail(&n->list, *new);
   3391	}
   3392	return 0;
   3393}
   3394
   3395void parse_events_terms__purge(struct list_head *terms)
   3396{
   3397	struct parse_events_term *term, *h;
   3398
   3399	list_for_each_entry_safe(term, h, terms, list) {
   3400		list_del_init(&term->list);
   3401		parse_events_term__delete(term);
   3402	}
   3403}
   3404
   3405void parse_events_terms__delete(struct list_head *terms)
   3406{
   3407	if (!terms)
   3408		return;
   3409	parse_events_terms__purge(terms);
   3410	free(terms);
   3411}
   3412
   3413void parse_events__clear_array(struct parse_events_array *a)
   3414{
   3415	zfree(&a->ranges);
   3416}
   3417
   3418void parse_events_evlist_error(struct parse_events_state *parse_state,
   3419			       int idx, const char *str)
   3420{
   3421	if (!parse_state->error)
   3422		return;
   3423
   3424	parse_events_error__handle(parse_state->error, idx, strdup(str), NULL);
   3425}
   3426
   3427static void config_terms_list(char *buf, size_t buf_sz)
   3428{
   3429	int i;
   3430	bool first = true;
   3431
   3432	buf[0] = '\0';
   3433	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
   3434		const char *name = config_term_names[i];
   3435
   3436		if (!config_term_avail(i, NULL))
   3437			continue;
   3438		if (!name)
   3439			continue;
   3440		if (name[0] == '<')
   3441			continue;
   3442
   3443		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
   3444			return;
   3445
   3446		if (!first)
   3447			strcat(buf, ",");
   3448		else
   3449			first = false;
   3450		strcat(buf, name);
   3451	}
   3452}
   3453
   3454/*
   3455 * Return string contains valid config terms of an event.
   3456 * @additional_terms: For terms such as PMU sysfs terms.
   3457 */
   3458char *parse_events_formats_error_string(char *additional_terms)
   3459{
   3460	char *str;
   3461	/* "no-overwrite" is the longest name */
   3462	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
   3463			  (sizeof("no-overwrite") - 1)];
   3464
   3465	config_terms_list(static_terms, sizeof(static_terms));
   3466	/* valid terms */
   3467	if (additional_terms) {
   3468		if (asprintf(&str, "valid terms: %s,%s",
   3469			     additional_terms, static_terms) < 0)
   3470			goto fail;
   3471	} else {
   3472		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
   3473			goto fail;
   3474	}
   3475	return str;
   3476
   3477fail:
   3478	return NULL;
   3479}
   3480
   3481struct evsel *parse_events__add_event_hybrid(struct list_head *list, int *idx,
   3482					     struct perf_event_attr *attr,
   3483					     const char *name,
   3484					     const char *metric_id,
   3485					     struct perf_pmu *pmu,
   3486					     struct list_head *config_terms)
   3487{
   3488	return __add_event(list, idx, attr, /*init_attr=*/true, name, metric_id,
   3489			   pmu, config_terms, /*auto_merge_stats=*/false,
   3490			   /*cpu_list=*/NULL);
   3491}