Skip to contentSkip to conversation

perf: Intel Cache QoS Monitoring support

PATCH In review Matt Fleming 3 participants 33 messages Nov 14, 2014 – Jan 15, 2015

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

v4 cover perf: Intel Cache QoS Monitoring support

From: Matt Fleming <[email protected]>

This patch series adds a new PMU driver for the Intel Cache Monitoring hardware feature available in Intel Xeon processors, which allows monitoring of LLC occupancy on a task, group or system-wide basis.

The first few patches modify tools/perf to handle per-package counters, which necessitates discarding some values when doing per-cpu reads to avoid getting duplicate data. The rest add support for the new PMU code.

I've left a notoriously funky bit of code near the end of the series, the RMID rotation code, in an attempt to simplify things. Doing the rotation provides the ability to multiplex the RMIDs and basically overcome the hardware limitation, but the rest of the patches work fine without it. But there are a number of scenarios where being able to monitor more tasks than RMIDs is extremely useful.

The series is based on tip/perf/core.

Changes in v4:

- Swapped smp_call_function_many() for on_each_cpu_mask()

- Use atomic_t for serialisation for cache occupancy IPI reads

- Calculate a max threshold value based on number of RMIDs and LLC size

- Drop the list, bitmap, list juggle in favour of RMID ->state member

- Use pmu::hrtimer_interval_ms as rotation timer tick for consistency

Changes in v3:

- Dropped patches that have been applied in tip/perf/core

- Upated commit message in PATCH 3 based on Peter's feedback

- Simplified PATCH 5 by only using int cgroup_fd as param

- Added a new patch (11) to perform internal scheduling on conflict monitoring events

- Make RMIDs wait in limbo for a minimium queue time to avoid IPIs wherever possible

- Provide a user-configurable upper bound on the recycling threshold

- Reduce the size of a preemption disabled section (pointed out by Thomas Gleixner)

- Reduce the limbo bitmap size due to worries of mass memory consumption on larg CPU systems (Peter Zijlstra)

- Picked a patch (2) from Jiri to fix the -I (interval) mode of perf stat with CQM

Changes in v2:

- Added Jiri Olsa's Acked-by to PATCH 02/11.

- Use x86_match_cpu() in intel_cqm_init() and make sure we grab the hotplug lock to prevent races as pointed out by Andi Kleen in PATCH 08/11.

- Delete a stale comment in commit message of PATCH 10/11.

Jiri Olsa (1):
perf tools: Implement snapshot event file logic

Matt Fleming (9):
perf tools: Parse event per-package info files
perf: Make perf_cgroup_from_task() global
perf: Add ->count() function to read per-package counters
perf: Move cgroup init before PMU ->event_init() perf/x86/intel: Add Intel Cache QoS Monitoring support perf/x86/intel: Implement LRU monitoring ID allocation for CQM perf/x86/intel: Support task events with Intel CQM perf/x86/intel: Perform rotation on Intel CQM RMIDs perf/x86/intel: Enable conflicting event scheduling for CQM

Peter P Waskiewicz Jr (1):
x86: Add support for Intel Cache QoS Monitoring (CQM) detection

 arch/x86/include/asm/cpufeature.h          |    9 +-
 arch/x86/include/asm/processor.h           |    3 +
 arch/x86/kernel/cpu/Makefile               |    2 +-
 arch/x86/kernel/cpu/common.c               |   39 +
 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 1349 ++++++++++++++++++++++++++++
 include/linux/perf_event.h                 |   48 +
 include/uapi/linux/perf_event.h            |    1 +
 kernel/events/core.c                       |   63 +-
 tools/perf/builtin-stat.c                  |   88 +-
 tools/perf/util/evsel.c                    |   12 +-
 tools/perf/util/evsel.h                    |    9 +-
 tools/perf/util/parse-events.c             |    2 +
 tools/perf/util/pmu.c                      |   74 +-
 tools/perf/util/pmu.h                      |    4 +
 14 files changed, 1643 insertions(+), 60 deletions(-)
 create mode 100644 arch/x86/kernel/cpu/perf_event_intel_cqm.c
Signature · 1 line
1.9.3
#1 lore raw

PATCH v4 1/11 perf tools: Parse event per-package info files

From: Matt Fleming <[email protected]>

In preparation for upcoming PMU drivers that support system-wide, per-package counters and hence report duplicate values, add support for parsing the .per-pkg file.

An event can export this info file to indicate that all but one value per socket should be discarded.

The discarding is much easier to do in userspace than inside the kernel because the kernel cannot infer what userspace is going to do with the reported values, what order it will read them in, etc.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 tools/perf/builtin-stat.c      | 88 +++++++++++++++++++++++++++++++++++++++++-
 tools/perf/util/evsel.c        |  6 ++-
 tools/perf/util/evsel.h        |  8 ++--
 tools/perf/util/parse-events.c |  1 +
 tools/perf/util/pmu.c          | 27 +++++++++++++
 tools/perf/util/pmu.h          |  2 +
 6 files changed, 127 insertions(+), 5 deletions(-)
tools/perf/builtin-stat.c +87 -1
index 055ce9232c9e..fa5264668187 100644
@@ -389,17 +389,92 @@ static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
 }
 
 /*
+ * If 'evsel' is a per-socket event we may get duplicate values
+ * reported. We need to discard all but one per-socket value.
+ */
+static bool counter_per_socket_skip(struct perf_evsel *evsel, int cpu, u64 val)
+{
+	struct cpu_map *map;
+	int i, ncpus;
+	int s1, s2;
+
+	if (!evsel->system_wide)
+		return false;
+
+	map = perf_evsel__cpus(evsel);
+	ncpus = map->nr;
+
+	s1 = cpu_map__get_socket(evsel_list->cpus, map->map[cpu]);
+
+	/*
+	 * Read all CPUs for this socket and see if any already have
+	 * value assigned.
+	 */
+	for (i = 0; i < ncpus; i++) {
+		s2 = cpu_map__get_socket(evsel_list->cpus, map->map[i]);
+		if (s1 != s2)
+			continue;
+
+		if (evsel->counts->cpu[i].val)
+			return true;
+	}
+
+	/* Stash the counter value in unused ->counts */
+	evsel->counts->cpu[cpu].val = val;
+	return false;
+}
+
+static bool aggr_per_socket_skip(struct perf_evsel *evsel, int cpu)
+{
+	struct cpu_map *map;
+	int leader_cpu = -1;
+	int i, ncpus;
+	int s1, s2;
+
+	map = perf_evsel__cpus(evsel);
+	ncpus = map->nr;
+
+	s1 = cpu_map__get_socket(evsel_list->cpus, map->map[cpu]);
+
+	/*
+	 * Find the first enabled counter for this socket and skip
+	 * everything else.
+	 */
+	for (i = 0; i < ncpus; i++) {
+		s2 = cpu_map__get_socket(evsel_list->cpus, map->map[i]);
+		if (s1 != s2)
+			continue;
+
+		if (!evsel->counts->cpu[i].ena)
+			continue;
+
+		leader_cpu = i;
+		break;
+	}
+
+	if (cpu == leader_cpu)
+		return false;
+
+	return true;
+}
+
+/*
  * Read out the results of a single counter:
  * aggregate counts across CPUs in system-wide mode
  */
 static int read_counter_aggr(struct perf_evsel *counter)
 {
 	struct perf_stat *ps = counter->priv;
+	bool (*f_skip)(struct perf_evsel *evsel, int cpu, u64 val) = NULL;
 	u64 *count = counter->counts->aggr.values;
 	int i;
 
+	if (counter->per_pkg)
+		f_skip = counter_per_socket_skip;
+
 	if (__perf_evsel__read(counter, perf_evsel__nr_cpus(counter),
-			       thread_map__nr(evsel_list->threads), scale) < 0)
+			       thread_map__nr(evsel_list->threads),
+			       scale, f_skip) < 0)
 		return -1;
 
 	for (i = 0; i < 3; i++)
@@ -451,12 +526,18 @@ static void print_interval(void)
 		evlist__for_each(evsel_list, counter) {
 			ps = counter->priv;
 			memset(ps->res_stats, 0, sizeof(ps->res_stats));
+			memset(counter->counts->cpu, 0,
+			       sizeof(struct perf_counts_values) *
+			       perf_evsel__nr_cpus(counter));
 			read_counter_aggr(counter);
 		}
 	} else	{
 		evlist__for_each(evsel_list, counter) {
 			ps = counter->priv;
 			memset(ps->res_stats, 0, sizeof(ps->res_stats));
+			memset(counter->counts->cpu, 0,
+			       sizeof(struct perf_counts_values) *
+			       perf_evsel__nr_cpus(counter));
 			read_counter(counter);
 		}
 	}
@@ -1130,6 +1211,11 @@ static void print_aggr(char *prefix)
 			val = ena = run = 0;
 			nr = 0;
 			for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
+				if (counter->per_pkg) {
+					if (aggr_per_socket_skip(counter, cpu))
+						continue;
+				}
+
 				cpu2 = perf_evsel__cpus(counter)->map[cpu];
 				s2 = aggr_get_id(evsel_list->cpus, cpu2);
 				if (s2 != id)
tools/perf/util/evsel.c +5 -1
index 12b4396c7175..4aced93672a8 100644
@@ -915,7 +915,8 @@ int __perf_evsel__read_on_cpu(struct perf_evsel *evsel,
 }
 
 int __perf_evsel__read(struct perf_evsel *evsel,
-		       int ncpus, int nthreads, bool scale)
+		       int ncpus, int nthreads, bool scale,
+		       bool (*f_skip)(struct perf_evsel *evsel, int cpu, u64 val))
 {
 	size_t nv = scale ? 3 : 1;
 	int cpu, thread;
@@ -935,6 +936,9 @@ int __perf_evsel__read(struct perf_evsel *evsel,
 				  &count, nv * sizeof(u64)) < 0)
 				return -errno;
 
+			if (f_skip && f_skip(evsel, cpu, count.val))
+				continue;
+
 			aggr->val += count.val;
 			if (scale) {
 				aggr->ena += count.ena;
tools/perf/util/evsel.h +5 -3
index 979790951bfb..13ca8a7693e4 100644
@@ -91,6 +91,7 @@ struct perf_evsel {
 	bool			immediate;
 	bool			system_wide;
 	bool			tracking;
+	bool			per_pkg;
 	/* parse modifier helper */
 	int			exclude_GH;
 	int			nr_members;
@@ -257,7 +258,8 @@ static inline int perf_evsel__read_on_cpu_scaled(struct perf_evsel *evsel,
 }
 
 int __perf_evsel__read(struct perf_evsel *evsel, int ncpus, int nthreads,
-		       bool scale);
+		       bool scale,
+		       bool (*f_skip)(struct perf_evsel *evsel, int cpu, u64 val));
 
 /**
  * perf_evsel__read - Read the aggregate results on all CPUs
@@ -269,7 +271,7 @@ int __perf_evsel__read(struct perf_evsel *evsel, int ncpus, int nthreads,
 static inline int perf_evsel__read(struct perf_evsel *evsel,
 				    int ncpus, int nthreads)
 {
-	return __perf_evsel__read(evsel, ncpus, nthreads, false);
+	return __perf_evsel__read(evsel, ncpus, nthreads, false, NULL);
 }
 
 /**
@@ -282,7 +284,7 @@ static inline int perf_evsel__read(struct perf_evsel *evsel,
 static inline int perf_evsel__read_scaled(struct perf_evsel *evsel,
 					  int ncpus, int nthreads)
 {
-	return __perf_evsel__read(evsel, ncpus, nthreads, true);
+	return __perf_evsel__read(evsel, ncpus, nthreads, true, NULL);
 }
 
 int perf_evsel__parse_sample(struct perf_evsel *evsel, union perf_event *event,
tools/perf/util/parse-events.c +1 -0
index c659a3ca1283..5a373483f0e4 100644
@@ -681,6 +681,7 @@ int parse_events_add_pmu(struct list_head *list, int *idx,
 	if (evsel) {
 		evsel->unit = info.unit;
 		evsel->scale = info.scale;
+		evsel->per_pkg = info.per_pkg;
 	}
 
 	return evsel ? 0 : -ENOMEM;
tools/perf/util/pmu.c +27 -0
index 881b75490533..f003b5a9e059 100644
@@ -163,6 +163,24 @@ error:
 	return -1;
 }
 
+static int
+perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, char *dir, char *name)
+{
+	char path[PATH_MAX];
+	int fd;
+
+	snprintf(path, PATH_MAX, "%s/%s.per-pkg", dir, name);
+
+	fd = open(path, O_RDONLY);
+	if (fd == -1)
+		return -1;
+
+	close(fd);
+
+	alias->per_pkg = true;
+	return 0;
+}
+
 static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FILE *file)
 {
 	struct perf_pmu_alias *alias;
@@ -181,6 +199,7 @@ static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FI
 	INIT_LIST_HEAD(&alias->terms);
 	alias->scale = 1.0;
 	alias->unit[0] = '\0';
+	alias->per_pkg = false;
 
 	ret = parse_events_terms(&alias->terms, buf);
 	if (ret) {
@@ -194,6 +213,7 @@ static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FI
 	 */
 	perf_pmu__parse_unit(alias, dir, name);
 	perf_pmu__parse_scale(alias, dir, name);
+	perf_pmu__parse_per_pkg(alias, dir, name);
 
 	list_add_tail(&alias->list, list);
 
@@ -209,6 +229,8 @@ static inline bool pmu_alias_info_file(char *name)
 		return true;
 	if (len > 6 && !strcmp(name + len - 6, ".scale"))
 		return true;
+	if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
+		return true;
 
 	return false;
 }
@@ -649,6 +671,8 @@ int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
 	struct perf_pmu_alias *alias;
 	int ret;
 
+	info->per_pkg = false;
+
 	/*
 	 * Mark unit and scale as not set
 	 * (different from default values, see below)
@@ -668,6 +692,9 @@ int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
 		if (ret)
 			return ret;
 
+		if (alias->per_pkg)
+			info->per_pkg = true;
+
 		list_del(&term->list);
 		free(term);
 	}
tools/perf/util/pmu.h +2 -0
index 8092de78e818..c3a74e0e17a2 100644
@@ -29,6 +29,7 @@ struct perf_pmu {
 struct perf_pmu_info {
 	const char *unit;
 	double scale;
+	bool per_pkg;
 };
 
 #define UNIT_MAX_LEN	31 /* max length for event unit name */
@@ -39,6 +40,7 @@ struct perf_pmu_alias {
 	struct list_head list;  /* ELEM */
 	char unit[UNIT_MAX_LEN+1];
 	double scale;
+	bool per_pkg;
 };
 
 struct perf_pmu *perf_pmu__find(const char *name);
Signature · 1 line
1.9.3
#2 lore raw

PATCH v4 2/11 perf tools: Implement snapshot event file logic

In reply to Matt Fleming

From: Jiri Olsa <[email protected]>

Adding support to parse and read the snapshot file, and using this information to omit the compute_delta function logic.

---
 tools/perf/util/evsel.c        |  6 ++++--
 tools/perf/util/evsel.h        |  1 +
 tools/perf/util/parse-events.c |  1 +
 tools/perf/util/pmu.c          | 47 ++++++++++++++++++++++++++++++++----------
 tools/perf/util/pmu.h          |  2 ++
 5 files changed, 44 insertions(+), 13 deletions(-)
tools/perf/util/evsel.c +4 -2
index 4aced93672a8..a7a26b46e21c 100644
@@ -900,7 +900,8 @@ int __perf_evsel__read_on_cpu(struct perf_evsel *evsel,
 	if (readn(FD(evsel, cpu, thread), &count, nv * sizeof(u64)) < 0)
 		return -errno;
 
-	compute_deltas(evsel, cpu, &count);
+	if (!evsel->snapshot)
+		compute_deltas(evsel, cpu, &count);
 
 	if (scale) {
 		if (count.run == 0)
@@ -947,7 +948,8 @@ int __perf_evsel__read(struct perf_evsel *evsel,
 		}
 	}
 
-	compute_deltas(evsel, -1, aggr);
+	if (!evsel->snapshot)
+		compute_deltas(evsel, -1, aggr);
 
 	evsel->counts->scaled = 0;
 	if (scale) {
tools/perf/util/evsel.h +1 -0
index 13ca8a7693e4..d9fa85e203f8 100644
@@ -73,6 +73,7 @@ struct perf_evsel {
 	char			*name;
 	double			scale;
 	const char		*unit;
+	bool			snapshot;
 	struct event_format	*tp_format;
 	union {
 		void		*priv;
tools/perf/util/parse-events.c +1 -0
index 5a373483f0e4..77b43fe43d55 100644
@@ -682,6 +682,7 @@ int parse_events_add_pmu(struct list_head *list, int *idx,
 		evsel->unit = info.unit;
 		evsel->scale = info.scale;
 		evsel->per_pkg = info.per_pkg;
+		evsel->snapshot = info.snapshot;
 	}
 
 	return evsel ? 0 : -ENOMEM;
tools/perf/util/pmu.c +36 -11

92 lines not on this page · raw message

tools/perf/util/pmu.h +2 -0
index c3a74e0e17a2..6b1249fbdb5f 100644
@@ -30,6 +30,7 @@ struct perf_pmu_info {
 	const char *unit;
 	double scale;
 	bool per_pkg;
+	bool snapshot;
 };
 
 #define UNIT_MAX_LEN	31 /* max length for event unit name */
@@ -41,6 +42,7 @@ struct perf_pmu_alias {
 	char unit[UNIT_MAX_LEN+1];
 	double scale;
 	bool per_pkg;
+	bool snapshot;
 };
 
 struct perf_pmu *perf_pmu__find(const char *name);
Signature · 1 line
1.9.3
#3 lore raw

PATCH v4 3/11 perf: Make perf_cgroup_from_task() global

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

Move perf_cgroup_from_task() from kernel/events/ to include/linux/ along with the necessary struct definitions, so that it can be used by the PMU code.

When the upcoming Intel Cache Monitoring PMU driver assigns monitoring IDs to perf events, it needs to be able to check whether any two monitoring events overlap (say, a cgroup and task event), which means we need to be able to lookup the cgroup associated with a task (if any).

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 include/linux/perf_event.h | 30 ++++++++++++++++++++++++++++++
 kernel/events/core.c       | 28 +---------------------------
 2 files changed, 31 insertions(+), 27 deletions(-)
include/linux/perf_event.h +30 -0
index 893a0d07986f..1a4e2846d6fb 100644
@@ -53,6 +53,7 @@ struct perf_guest_info_callbacks {
 #include <linux/sysfs.h>
 #include <linux/perf_regs.h>
 #include <linux/workqueue.h>
+#include <linux/cgroup.h>
 #include <asm/local.h>
 
 struct perf_callchain_entry {
@@ -544,6 +545,35 @@ struct perf_output_handle {
 	int				page;
 };
 
+#ifdef CONFIG_CGROUP_PERF
+
+/*
+ * perf_cgroup_info keeps track of time_enabled for a cgroup.
+ * This is a per-cpu dynamically allocated data structure.
+ */
+struct perf_cgroup_info {
+	u64				time;
+	u64				timestamp;
+};
+
+struct perf_cgroup {
+	struct cgroup_subsys_state	css;
+	struct perf_cgroup_info	__percpu *info;
+};
+
+/*
+ * Must ensure cgroup is pinned (css_get) before calling
+ * this function. In other words, we cannot call this function
+ * if there is no cgroup event for the current CPU context.
+ */
+static inline struct perf_cgroup *
+perf_cgroup_from_task(struct task_struct *task)
+{
+	return container_of(task_css(task, perf_event_cgrp_id),
+			    struct perf_cgroup, css);
+}
+#endif /* CONFIG_CGROUP_PERF */
+
 #ifdef CONFIG_PERF_EVENTS
 
 extern int perf_pmu_register(struct pmu *pmu, const char *name, int type);
kernel/events/core.c +1 -27
index 2b02c9fda790..a65f4c47eb56 100644
@@ -34,11 +34,11 @@
 #include <linux/syscalls.h>
 #include <linux/anon_inodes.h>
 #include <linux/kernel_stat.h>
+#include <linux/cgroup.h>
 #include <linux/perf_event.h>
 #include <linux/ftrace_event.h>
 #include <linux/hw_breakpoint.h>
 #include <linux/mm_types.h>
-#include <linux/cgroup.h>
 #include <linux/module.h>
 #include <linux/mman.h>
 #include <linux/compat.h>
@@ -351,32 +351,6 @@ static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
 
 #ifdef CONFIG_CGROUP_PERF
 
-/*
- * perf_cgroup_info keeps track of time_enabled for a cgroup.
- * This is a per-cpu dynamically allocated data structure.
- */
-struct perf_cgroup_info {
-	u64				time;
-	u64				timestamp;
-};
-
-struct perf_cgroup {
-	struct cgroup_subsys_state	css;
-	struct perf_cgroup_info	__percpu *info;
-};
-
-/*
- * Must ensure cgroup is pinned (css_get) before calling
- * this function. In other words, we cannot call this function
- * if there is no cgroup event for the current CPU context.
- */
-static inline struct perf_cgroup *
-perf_cgroup_from_task(struct task_struct *task)
-{
-	return container_of(task_css(task, perf_event_cgrp_id),
-			    struct perf_cgroup, css);
-}
-
 static inline bool
 perf_cgroup_match(struct perf_event *event)
 {
Signature · 1 line
1.9.3
#4 lore raw

PATCH v4 4/11 perf: Add ->count() function to read per-package counters

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

For PMU drivers that record per-package counters, the ->count variable cannot be used to record an accurate aggregated value, since it's not possible to perform SMP cross-calls to cpus on other packages from the context in which we update ->count.

Introduce a new optional ->count() accessor function that can be used to customize how values are collected. If a PMU driver doesn't provide a ->count() function, we fallback to the existing code.

There is necessarily a window of staleness with this approach because the task that generated the counter value may not have been scheduled by the cpu recently.

An alternative and more complex approach would be to use a hrtimer to periodically refresh the values from a more permissive scheduling context. So, we're trading off complexity for accuracy.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 include/linux/perf_event.h | 10 ++++++++++
 kernel/events/core.c       |  5 ++++-
 2 files changed, 14 insertions(+), 1 deletion(-)
include/linux/perf_event.h +10 -0
index 1a4e2846d6fb..1bf06b6fd5dc 100644
@@ -264,6 +264,11 @@ struct pmu {
 	 * flush branch stack on context-switches (needed in cpu-wide mode)
 	 */
 	void (*flush_branch_stack)	(void);
+
+	/*
+	 * Return the count value for a counter.
+	 */
+	u64 (*count)			(struct perf_event *event); /*optional*/
 };
 
 /**
@@ -743,6 +748,11 @@ static inline void perf_event_task_sched_out(struct task_struct *prev,
 		__perf_event_task_sched_out(prev, next);
 }
 
+static inline u64 __perf_event_count(struct perf_event *event)
+{
+	return local64_read(&event->count) + atomic64_read(&event->child_count);
+}
+
 extern void perf_event_mmap(struct vm_area_struct *vma);
 extern struct perf_guest_info_callbacks *perf_guest_cbs;
 extern int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *callbacks);
kernel/events/core.c +4 -1
index a65f4c47eb56..a2ea4a52dbbf 100644
@@ -3074,7 +3074,10 @@ static void __perf_event_read(void *info)
 
 static inline u64 perf_event_count(struct perf_event *event)
 {
-	return local64_read(&event->count) + atomic64_read(&event->child_count);
+	if (event->pmu->count)
+		return event->pmu->count(event);
+
+	return __perf_event_count(event);
 }
 
 static u64 perf_event_read(struct perf_event *event)
Signature · 1 line
1.9.3
#5 lore raw

PATCH v4 5/11 perf: Move cgroup init before PMU ->event_init()

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

The Intel QoS PMU needs to know whether an event is part of a cgroup during ->event_init(), because tasks in the same cgroup share a monitoring ID.

Move the cgroup initialisation before calling into the PMU driver.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 kernel/events/core.c | 28 ++++++++++++++++------------
 1 file changed, 16 insertions(+), 12 deletions(-)
kernel/events/core.c +16 -12
index a2ea4a52dbbf..540d995322dd 100644
@@ -6884,7 +6884,7 @@ perf_event_alloc(struct perf_event_attr *attr, int cpu,
 		 struct perf_event *group_leader,
 		 struct perf_event *parent_event,
 		 perf_overflow_handler_t overflow_handler,
-		 void *context)
+		 void *context, int cgroup_fd)
 {
 	struct pmu *pmu;
 	struct perf_event *event;
@@ -6977,6 +6977,12 @@ perf_event_alloc(struct perf_event_attr *attr, int cpu,
 	if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
 		goto err_ns;
 
+	if (cgroup_fd != -1) {
+		err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
+		if (err)
+			goto err_ns;
+	}
+
 	pmu = perf_init_event(event);
 	if (!pmu)
 		goto err_ns;
@@ -7000,6 +7006,8 @@ err_pmu:
 		event->destroy(event);
 	module_put(pmu->module);
 err_ns:
+	if (is_cgroup_event(event))
+		perf_detach_cgroup(event);
 	if (event->ns)
 		put_pid_ns(event->ns);
 	kfree(event);
@@ -7207,6 +7215,7 @@ SYSCALL_DEFINE5(perf_event_open,
 	int move_group = 0;
 	int err;
 	int f_flags = O_RDWR;
+	int cgroup_fd = -1;
 
 	/* for future expandability... */
 	if (flags & ~PERF_FLAG_ALL)
@@ -7272,21 +7281,16 @@ SYSCALL_DEFINE5(perf_event_open,
 
 	get_online_cpus();
 
+	if (flags & PERF_FLAG_PID_CGROUP)
+		cgroup_fd = pid;
+
 	event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
-				 NULL, NULL);
+				 NULL, NULL, cgroup_fd);
 	if (IS_ERR(event)) {
 		err = PTR_ERR(event);
 		goto err_cpus;
 	}
 
-	if (flags & PERF_FLAG_PID_CGROUP) {
-		err = perf_cgroup_connect(pid, event, &attr, group_leader);
-		if (err) {
-			__free_event(event);
-			goto err_cpus;
-		}
-	}
-
 	if (is_sampling_event(event)) {
 		if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
 			err = -ENOTSUPP;
@@ -7486,7 +7490,7 @@ perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
 	 */
 
 	event = perf_event_alloc(attr, cpu, task, NULL, NULL,
-				 overflow_handler, context);
+				 overflow_handler, context, -1);
 	if (IS_ERR(event)) {
 		err = PTR_ERR(event);
 		goto err;
@@ -7812,7 +7816,7 @@ inherit_event(struct perf_event *parent_event,
 					   parent_event->cpu,
 					   child,
 					   group_leader, parent_event,
-				           NULL, NULL);
+				           NULL, NULL, -1);
 	if (IS_ERR(child_event))
 		return child_event;
 
Signature · 1 line
1.9.3
#6 lore raw

PATCH v4 6/11 x86: Add support for Intel Cache QoS Monitoring (CQM) detection

In reply to Matt Fleming

From: Peter P Waskiewicz Jr <[email protected]>

This patch adds support for the new Cache QoS Monitoring (CQM) feature found in future Intel Xeon processors. It includes the new values to track CQM resources to the cpuinfo_x86 structure, plus the CPUID detection routines for CQM.

CQM allows a process, or set of processes, to be tracked by the CPU to determine the cache usage of that task group. Using this data from the CPU, software can be written to extract this data and report cache usage and occupancy for a particular process, or group of processes.

More information about Cache QoS Monitoring can be found in the Intel (R) x86 Architecture Software Developer Manual, section 17.14.

---
 arch/x86/include/asm/cpufeature.h |  9 ++++++++-
 arch/x86/include/asm/processor.h  |  3 +++
 arch/x86/kernel/cpu/common.c      | 39 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 50 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeature.h +8 -1
index 0bb1335313b2..a57d98b3e5dd 100644
@@ -12,7 +12,7 @@
 #include <asm/disabled-features.h>
 #endif
 
-#define NCAPINTS	11	/* N 32-bit words worth of info */
+#define NCAPINTS	13	/* N 32-bit words worth of info */
 #define NBUGINTS	1	/* N 32-bit bug flags */
 
 /*
@@ -220,6 +220,7 @@
 #define X86_FEATURE_ERMS	( 9*32+ 9) /* Enhanced REP MOVSB/STOSB */
 #define X86_FEATURE_INVPCID	( 9*32+10) /* Invalidate Processor Context ID */
 #define X86_FEATURE_RTM		( 9*32+11) /* Restricted Transactional Memory */
+#define X86_FEATURE_CQM		( 9*32+12) /* Cache QoS Monitoring */
 #define X86_FEATURE_MPX		( 9*32+14) /* Memory Protection Extension */
 #define X86_FEATURE_AVX512F	( 9*32+16) /* AVX-512 Foundation */
 #define X86_FEATURE_RDSEED	( 9*32+18) /* The RDSEED instruction */
@@ -236,6 +237,12 @@
 #define X86_FEATURE_XGETBV1	(10*32+ 2) /* XGETBV with ECX = 1 */
 #define X86_FEATURE_XSAVES	(10*32+ 3) /* XSAVES/XRSTORS */
 
+/* Intel-defined CPU QoS Sub-leaf, CPUID level 0x0000000F:0 (edx), word 11 */
+#define X86_FEATURE_CQM_LLC	(11*32+ 1) /* LLC QoS if 1 */
+
+/* Intel-defined CPU QoS Sub-leaf, CPUID level 0x0000000F:1 (edx), word 12 */
+#define X86_FEATURE_CQM_OCCUP_LLC (12*32+ 0) /* LLC occupancy monitoring if 1 */
+
 /*
  * BUG word(s)
  */
arch/x86/include/asm/processor.h +3 -0
index eb71ec794732..2c3a46af3334 100644
@@ -109,6 +109,9 @@ struct cpuinfo_x86 {
 	/* in KB - valid for CPUS which support this call: */
 	int			x86_cache_size;
 	int			x86_cache_alignment;	/* In bytes */
+	/* Cache QoS architectural values: */
+	int			x86_cache_max_rmid;	/* max index */
+	int			x86_cache_occ_scale;	/* scale to bytes */
 	int			x86_power;
 	unsigned long		loops_per_jiffy;
 	/* cpuid returned max cores value: */
arch/x86/kernel/cpu/common.c +39 -0
index 4b4f78c9ba19..4230745fdcf8 100644
@@ -642,6 +642,30 @@ void get_cpu_cap(struct cpuinfo_x86 *c)
 		c->x86_capability[10] = eax;
 	}
 
+	/* Additional Intel-defined flags: level 0x0000000F */
+	if (c->cpuid_level >= 0x0000000F) {
+		u32 eax, ebx, ecx, edx;
+
+		/* QoS sub-leaf, EAX=0Fh, ECX=0 */
+		cpuid_count(0x0000000F, 0, &eax, &ebx, &ecx, &edx);
+		c->x86_capability[11] = edx;
+		if (cpu_has(c, X86_FEATURE_CQM_LLC)) {
+			/* will be overridden if occupancy monitoring exists */
+			c->x86_cache_max_rmid = ebx;
+
+			/* QoS sub-leaf, EAX=0Fh, ECX=1 */
+			cpuid_count(0x0000000F, 1, &eax, &ebx, &ecx, &edx);
+			c->x86_capability[12] = edx;
+			if (cpu_has(c, X86_FEATURE_CQM_OCCUP_LLC)) {
+				c->x86_cache_max_rmid = ecx;
+				c->x86_cache_occ_scale = ebx;
+			}
+		} else {
+			c->x86_cache_max_rmid = -1;
+			c->x86_cache_occ_scale = -1;
+		}
+	}
+
 	/* AMD-defined flags: level 0x80000001 */
 	xlvl = cpuid_eax(0x80000000);
 	c->extended_cpuid_level = xlvl;
@@ -830,6 +854,20 @@ static void generic_identify(struct cpuinfo_x86 *c)
 	detect_nopl(c);
 }
 
+static void x86_init_cache_qos(struct cpuinfo_x86 *c)
+{
+	/*
+	 * The heavy lifting of max_rmid and cache_occ_scale are handled
+	 * in get_cpu_cap().  Here we just set the max_rmid for the boot_cpu
+	 * in case CQM bits really aren't there in this CPU.
+	 */
+	if (c != &boot_cpu_data) {
+		boot_cpu_data.x86_cache_max_rmid =
+			min(boot_cpu_data.x86_cache_max_rmid,
+			    c->x86_cache_max_rmid);
+	}
+}
+
 /*
  * This does the hard work of actually picking apart the CPU stuff...
  */
@@ -919,6 +957,7 @@ static void identify_cpu(struct cpuinfo_x86 *c)
 
 	init_hypervisor(c);
 	x86_init_rdrand(c);
+	x86_init_cache_qos(c);
 
 	/*
 	 * Clear/Set all flags overriden by options, need do it
Signature · 1 line
1.9.3
#7 lore raw

PATCH v4 7/11 perf/x86/intel: Add Intel Cache QoS Monitoring support

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

Future Intel Xeon processors support a Cache QoS Monitoring feature that allows tracking of the LLC occupancy for a task or task group, i.e. the amount of data in pulled into the LLC for the task (group).

Currently the PMU only supports per-cpu events. We create an event for each cpu and read out all the LLC occupancy values.

Because this results in duplicate values being written out to userspace, we also export a .per-pkg event file so that the perf tools only accumulate values for one cpu per package.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 arch/x86/kernel/cpu/Makefile               |   2 +-
 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 528 +++++++++++++++++++++++++++++
 include/linux/perf_event.h                 |   7 +
 3 files changed, 536 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/kernel/cpu/perf_event_intel_cqm.c
arch/x86/kernel/cpu/Makefile +1 -1
index e27b49d7c922..18e5341bb3fd 100644
@@ -39,7 +39,7 @@ obj-$(CONFIG_CPU_SUP_AMD)		+= perf_event_amd_iommu.o
 endif
 obj-$(CONFIG_CPU_SUP_INTEL)		+= perf_event_p6.o perf_event_knc.o perf_event_p4.o
 obj-$(CONFIG_CPU_SUP_INTEL)		+= perf_event_intel_lbr.o perf_event_intel_ds.o perf_event_intel.o
-obj-$(CONFIG_CPU_SUP_INTEL)		+= perf_event_intel_rapl.o
+obj-$(CONFIG_CPU_SUP_INTEL)		+= perf_event_intel_rapl.o perf_event_intel_cqm.o
 
 obj-$(CONFIG_PERF_EVENTS_INTEL_UNCORE)	+= perf_event_intel_uncore.o \
 					   perf_event_intel_uncore_snb.o \
arch/x86/kernel/cpu/perf_event_intel_cqm.c new file +528 -0

528 lines not on this page · raw message

include/linux/perf_event.h +7 -0
index 1bf06b6fd5dc..50ceb0665cda 100644
@@ -128,6 +128,13 @@ struct hw_perf_event {
 			/* for tp_event->class */
 			struct list_head	tp_list;
 		};
+		struct { /* intel_cqm */
+			int			cqm_state;
+			int			cqm_rmid;
+			struct list_head	cqm_events_entry;
+			struct list_head	cqm_groups_entry;
+			struct list_head	cqm_group_entry;
+		};
 #ifdef CONFIG_HAVE_HW_BREAKPOINT
 		struct { /* breakpoint */
 			/*
Signature · 1 line
1.9.3
#8 lore raw

PATCH v4 8/11 perf/x86/intel: Implement LRU monitoring ID allocation for CQM

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

It's possible to run into issues with re-using unused monitoring IDs because there may be stale cachelines associated with that ID from a previous allocation. This can cause the LLC occupancy values to be inaccurate.

To attempt to mitigate this problem we place the IDs on a least recently used list, essentially a FIFO. The basic idea is that the longer the time period between ID re-use the lower the probability that stale cachelines exist in the cache.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 100 ++++++++++++++++++++++++++---
 1 file changed, 92 insertions(+), 8 deletions(-)
arch/x86/kernel/cpu/perf_event_intel_cqm.c +92 -8
index b16458ff274e..60e0043ca922 100644
@@ -25,7 +25,7 @@ struct intel_cqm_state {
 static DEFINE_PER_CPU(struct intel_cqm_state, cqm_state);
 
 /*
- * Protects cache_cgroups.
+ * Protects cache_cgroups and cqm_rmid_lru.
  */
 static DEFINE_MUTEX(cache_mutex);
 
@@ -64,36 +64,120 @@ static u64 __rmid_read(unsigned long rmid)
 	return val;
 }
 
-static unsigned long *cqm_rmid_bitmap;
+struct cqm_rmid_entry {
+	u64 rmid;
+	struct list_head list;
+};
+
+/*
+ * A least recently used list of RMIDs.
+ *
+ * Oldest entry at the head, newest (most recently used) entry at the
+ * tail. This list is never traversed, it's only used to keep track of
+ * the lru order. That is, we only pick entries of the head or insert
+ * them on the tail.
+ *
+ * All entries on the list are 'free', and their RMIDs are not currently
+ * in use. To mark an RMID as in use, remove its entry from the lru
+ * list.
+ *
+ * This list is protected by cache_mutex.
+ */
+static LIST_HEAD(cqm_rmid_lru);
+
+/*
+ * We use a simple array of pointers so that we can lookup a struct
+ * cqm_rmid_entry in O(1). This alleviates the callers of __get_rmid()
+ * and __put_rmid() from having to worry about dealing with struct
+ * cqm_rmid_entry - they just deal with rmids, i.e. integers.
+ *
+ * Once this array is initialized it is read-only. No locks are required
+ * to access it.
+ *
+ * All entries for all RMIDs can be looked up in the this array at all
+ * times.
+ */
+static struct cqm_rmid_entry **cqm_rmid_ptrs;
+
+static inline struct cqm_rmid_entry *__rmid_entry(int rmid)
+{
+	struct cqm_rmid_entry *entry;
+
+	entry = cqm_rmid_ptrs[rmid];
+	WARN_ON(entry->rmid != rmid);
+
+	return entry;
+}
 
 /*
  * Returns < 0 on fail.
+ *
+ * We expect to be called with cache_mutex held.
  */
 static int __get_rmid(void)
 {
-	return bitmap_find_free_region(cqm_rmid_bitmap, cqm_max_rmid, 0);
+	struct cqm_rmid_entry *entry;
+
+	lockdep_assert_held(&cache_mutex);
+
+	if (list_empty(&cqm_rmid_lru))
+		return -EAGAIN;
+
+	entry = list_first_entry(&cqm_rmid_lru, struct cqm_rmid_entry, list);
+	list_del(&entry->list);
+
+	return entry->rmid;
 }
 
 static void __put_rmid(int rmid)
 {
-	bitmap_release_region(cqm_rmid_bitmap, rmid, 0);
+	struct cqm_rmid_entry *entry;
+
+	lockdep_assert_held(&cache_mutex);
+
+	entry = __rmid_entry(rmid);
+
+	list_add_tail(&entry->list, &cqm_rmid_lru);
 }
 
 static int intel_cqm_setup_rmid_cache(void)
 {
-	cqm_rmid_bitmap = kmalloc(sizeof(long) * BITS_TO_LONGS(cqm_max_rmid), GFP_KERNEL);
-	if (!cqm_rmid_bitmap)
+	struct cqm_rmid_entry *entry;
+	int r;
+
+	cqm_rmid_ptrs = kmalloc(sizeof(struct cqm_rmid_entry *) *
+				(cqm_max_rmid + 1), GFP_KERNEL);
+	if (!cqm_rmid_ptrs)
 		return -ENOMEM;
 
-	bitmap_zero(cqm_rmid_bitmap, cqm_max_rmid);
+	for (r = 0; r <= cqm_max_rmid; r++) {
+		struct cqm_rmid_entry *entry;
+
+		entry = kmalloc(sizeof(*entry), GFP_KERNEL);
+		if (!entry)
+			goto fail;
+
+		INIT_LIST_HEAD(&entry->list);
+		entry->rmid = r;
+		cqm_rmid_ptrs[r] = entry;
+
+		list_add_tail(&entry->list, &cqm_rmid_lru);
+	}
 
 	/*
 	 * RMID 0 is special and is always allocated. It's used for all
 	 * tasks that are not monitored.
 	 */
-	bitmap_allocate_region(cqm_rmid_bitmap, 0, 0);
+	entry = __rmid_entry(0);
+	list_del(&entry->list);
 
 	return 0;
+fail:
+	while (r--)
+		kfree(cqm_rmid_ptrs[r]);
+
+	kfree(cqm_rmid_ptrs);
+	return -ENOMEM;
 }
 
 /*
Signature · 1 line
1.9.3
#9 lore raw

PATCH v4 9/11 perf/x86/intel: Support task events with Intel CQM

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

Add support for task events as well as system-wide events. This change has a big impact on the way that we gather LLC occupancy values in intel_cqm_event_read().

Currently, for system-wide (per-cpu) events we defer processing to userspace which knows how to discard all but one cpu result per package.

Things aren't so simple for task events because we need to do the value aggregation ourselves. To do this, we defer updating the LLC occupancy value in event->count from intel_cqm_event_read() and do an SMP cross-call to read values for all packages in intel_cqm_event_count(). We need to ensure that we only do this for one task event per cache group, otherwise we'll report duplicate values.

If we're a system-wide event we want to fallback to the default perf_event_count() implementation. Refactor this into a common function so that we don't duplicate the code.

Also, introduce PERF_TYPE_INTEL_CQM, since we need a way to track an event's task (if the event isn't per-cpu) inside of the Intel CQM PMU driver. This task information is only availble in the upper layers of the perf infrastructure.

Other perf backends stash the target task in event->hw.*target so we need to do something similar. The task is used to determine whether events should share a cache group and an RMID.

Cc Jiri Olsa <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Peter Zijlstra <[email protected]>

---
Changes in v4:

- Swap smp_call_function_many() for on_each_cpu_mask() in case the current cpu is part of the cpumask

- Use atomic_t to perform reads across IPIs for atomicity of updates

 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 195 +++++++++++++++++++++++++----
 include/linux/perf_event.h                 |   1 +
 include/uapi/linux/perf_event.h            |   1 +
 kernel/events/core.c                       |   2 +
 4 files changed, 178 insertions(+), 21 deletions(-)
arch/x86/kernel/cpu/perf_event_intel_cqm.c +174 -21
index 60e0043ca922..2bd023f8fb6a 100644
@@ -182,23 +182,124 @@ fail:
 
 /*
  * Determine if @a and @b measure the same set of tasks.
+ *
+ * If @a and @b measure the same set of tasks then we want to share a
+ * single RMID.
  */
 static bool __match_event(struct perf_event *a, struct perf_event *b)
 {
+	/* Per-cpu and task events don't mix */
 	if ((a->attach_state & PERF_ATTACH_TASK) !=
 	    (b->attach_state & PERF_ATTACH_TASK))
 		return false;
 
-	/* not task */
+#ifdef CONFIG_CGROUP_PERF
+	if (a->cgrp != b->cgrp)
+		return false;
+#endif
+
+	/* If not task event, we're machine wide */
+	if (!(b->attach_state & PERF_ATTACH_TASK))
+		return true;
+
+	/*
+	 * Events that target same task are placed into the same cache group.
+	 */
+	if (a->hw.cqm_target == b->hw.cqm_target)
+		return true;
+
+	/*
+	 * Are we an inherited event?
+	 */
+	if (b->parent == a)
+		return true;
+
+	return false;
+}
+
+#ifdef CONFIG_CGROUP_PERF
+static inline struct perf_cgroup *event_to_cgroup(struct perf_event *event)
+{
+	if (event->attach_state & PERF_ATTACH_TASK)
+		return perf_cgroup_from_task(event->hw.cqm_target);
 
-	return true; /* if not task, we're machine wide */
+	return event->cgrp;
 }
+#endif
 
 /*
  * Determine if @a's tasks intersect with @b's tasks
+ *
+ * There are combinations of events that we explicitly prohibit,
+ *
+ *		   PROHIBITS
+ *     system-wide    -> 	cgroup and task
+ *     cgroup 	      ->	system-wide
+ *     		      ->	task in cgroup
+ *     task 	      -> 	system-wide
+ *     		      ->	task in cgroup
+ *
+ * Call this function before allocating an RMID.
  */
 static bool __conflict_event(struct perf_event *a, struct perf_event *b)
 {
+#ifdef CONFIG_CGROUP_PERF
+	/*
+	 * We can have any number of cgroups but only one system-wide
+	 * event at a time.
+	 */
+	if (a->cgrp && b->cgrp) {
+		struct perf_cgroup *ac = a->cgrp;
+		struct perf_cgroup *bc = b->cgrp;
+
+		/*
+		 * This condition should have been caught in
+		 * __match_event() and we should be sharing an RMID.
+		 */
+		WARN_ON_ONCE(ac == bc);
+
+		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
+		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
+			return true;
+
+		return false;
+	}
+
+	if (a->cgrp || b->cgrp) {
+		struct perf_cgroup *ac, *bc;
+
+		/*
+		 * cgroup and system-wide events are mutually exclusive
+		 */
+		if ((a->cgrp && !(b->attach_state & PERF_ATTACH_TASK)) ||
+		    (b->cgrp && !(a->attach_state & PERF_ATTACH_TASK)))
+			return true;
+
+		/*
+		 * Ensure neither event is part of the other's cgroup
+		 */
+		ac = event_to_cgroup(a);
+		bc = event_to_cgroup(b);
+		if (ac == bc)
+			return true;
+
+		/*
+		 * Must have cgroup and non-intersecting task events.
+		 */
+		if (!ac || !bc)
+			return false;
+
+		/*
+		 * We have cgroup and task events, and the task belongs
+		 * to a cgroup. Check for for overlap.
+		 */
+		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
+		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
+			return true;
+
+		return false;
+	}
+#endif
 	/*
 	 * If one of them is not a task, same story as above with cgroups.
 	 */
@@ -245,9 +346,16 @@ static int intel_cqm_setup_event(struct perf_event *event,
 
 static void intel_cqm_event_read(struct perf_event *event)
 {
-	unsigned long rmid = event->hw.cqm_rmid;
+	unsigned long rmid;
 	u64 val;
 
+	/*
+	 * Task events are handled by intel_cqm_event_count().
+	 */
+	if (event->cpu == -1)
+		return;
+
+	rmid = event->hw.cqm_rmid;
 	val = __rmid_read(rmid);
 
 	/*
@@ -259,6 +367,63 @@ static void intel_cqm_event_read(struct perf_event *event)
 	local64_set(&event->count, val);
 }
 
+struct rmid_read {
+	unsigned int rmid;
+	atomic64_t value;
+};
+
+static void __intel_cqm_event_count(void *info)
+{
+	struct rmid_read *rr = info;
+	u64 val;
+
+	val = __rmid_read(rr->rmid);
+
+	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
+		return;
+
+	atomic64_add(val, &rr->value);
+}
+
+static inline bool cqm_group_leader(struct perf_event *event)
+{
+	return !list_empty(&event->hw.cqm_groups_entry);
+}
+
+static u64 intel_cqm_event_count(struct perf_event *event)
+{
+	struct rmid_read rr = {
+		.rmid = event->hw.cqm_rmid,
+		.value = ATOMIC64_INIT(0),
+	};
+
+	/*
+	 * We only need to worry about task events. System-wide events
+	 * are handled like usual, i.e. entirely with
+	 * intel_cqm_event_read().
+	 */
+	if (event->cpu != -1)
+		return __perf_event_count(event);
+
+	/*
+	 * Only the group leader gets to report values. This stops us
+	 * reporting duplicate values to userspace, and gives us a clear
+	 * rule for which task gets to report the values.
+	 *
+	 * Note that it is impossible to attribute these values to
+	 * specific packages - we forfeit that ability when we create
+	 * task events.
+	 */
+	if (!cqm_group_leader(event))
+		return 0;
+
+	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
+
+	local64_set(&event->count, atomic64_read(&rr.value));
+
+	return __perf_event_count(event);
+}
+
 static void intel_cqm_event_start(struct perf_event *event, int mode)
 {
 	struct intel_cqm_state *state = &__get_cpu_var(cqm_state);
@@ -344,7 +509,7 @@ static void intel_cqm_event_destroy(struct perf_event *event)
 	/*
 	 * And we're the group leader..
 	 */
-	if (!list_empty(&event->hw.cqm_groups_entry)) {
+	if (cqm_group_leader(event)) {
 		/*
 		 * If there was a group_other, make that leader, otherwise
 		 * destroy the group and return the RMID.
@@ -364,17 +529,6 @@ static void intel_cqm_event_destroy(struct perf_event *event)
 
 static struct pmu intel_cqm_pmu;
 
-/*
- * XXX there's a bit of a problem in that we cannot simply do the one
- * event per node as one would want, since that one event would one get
- * scheduled on the one cpu. But we want to 'schedule' the RMID on all
- * CPUs.
- *
- * This means we want events for each CPU, however, that generates a lot
- * of duplicate values out to userspace -- this is not to be helped
- * unless we want to change the core code in some way. Fore more info,
- * see intel_cqm_event_read().
- */
 static int intel_cqm_event_init(struct perf_event *event)
 {
 	struct perf_event *group = NULL;
@@ -386,9 +540,6 @@ static int intel_cqm_event_init(struct perf_event *event)
 	if (event->attr.config & ~QOS_EVENT_MASK)
 		return -EINVAL;
 
-	if (event->cpu == -1)
-		return -EINVAL;
-
 	/* unsupported modes and filters */
 	if (event->attr.exclude_user   ||
 	    event->attr.exclude_kernel ||
@@ -406,7 +557,8 @@ static int intel_cqm_event_init(struct perf_event *event)
 
 	mutex_lock(&cache_mutex);
 
-	err = intel_cqm_setup_event(event, &group); /* will also set rmid */
+	/* Will also set rmid */
+	err = intel_cqm_setup_event(event, &group);
 	if (err)
 		goto out;
 
@@ -469,6 +621,7 @@ static struct pmu intel_cqm_pmu = {
 	.start		= intel_cqm_event_start,
 	.stop		= intel_cqm_event_stop,
 	.read		= intel_cqm_event_read,
+	.count		= intel_cqm_event_count,
 };
 
 static inline void cqm_pick_event_reader(int cpu)
@@ -597,8 +750,8 @@ static int __init intel_cqm_init(void)
 
 	__perf_cpu_notifier(intel_cqm_cpu_notifier);
 
-	ret = perf_pmu_register(&intel_cqm_pmu, "intel_cqm", -1);
-
+	ret = perf_pmu_register(&intel_cqm_pmu, "intel_cqm",
+				PERF_TYPE_INTEL_CQM);
 	if (ret)
 		pr_err("Intel CQM perf registration failed: %d\n", ret);
 	else
include/linux/perf_event.h +1 -0
index 50ceb0665cda..4cb6e1e668a1 100644
@@ -134,6 +134,7 @@ struct hw_perf_event {
 			struct list_head	cqm_events_entry;
 			struct list_head	cqm_groups_entry;
 			struct list_head	cqm_group_entry;
+			struct task_struct	*cqm_target;
 		};
 #ifdef CONFIG_HAVE_HW_BREAKPOINT
 		struct { /* breakpoint */
include/uapi/linux/perf_event.h +1 -0
index 9d845404d875..0706ed0a0bf2 100644
@@ -32,6 +32,7 @@ enum perf_type_id {
 	PERF_TYPE_HW_CACHE			= 3,
 	PERF_TYPE_RAW				= 4,
 	PERF_TYPE_BREAKPOINT			= 5,
+	PERF_TYPE_INTEL_CQM			= 6,
 
 	PERF_TYPE_MAX,				/* non-ABI */
 };
kernel/events/core.c +2 -0
index 540d995322dd..31469c739216 100644
@@ -6949,6 +6949,8 @@ perf_event_alloc(struct perf_event_attr *attr, int cpu,
 		else if (attr->type == PERF_TYPE_BREAKPOINT)
 			event->hw.bp_target = task;
 #endif
+		else if (attr->type == PERF_TYPE_INTEL_CQM)
+			event->hw.cqm_target = task;
 	}
 
 	if (!overflow_handler && parent_event) {
Signature · 1 line
1.9.3
#10 lore raw

PATCH v4 10/11 perf/x86/intel: Perform rotation on Intel CQM RMIDs

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

There are many use cases where people will want to monitor more tasks than there exist RMIDs in the hardware, meaning that we have to perform some kind of multiplexing.

We do this by "rotating" the RMIDs in a workqueue, and assigning an RMID to a waiting event when the RMID becomes unused.

This scheme reserves one RMID at all times for rotation. When we need to schedule a new event we give it the reserved RMID, pick a victim event from the front of the global CQM list and wait for the victim's RMID to drop to zero occupancy, before it becomes the new reserved RMID.

We put the victim's RMID onto the limbo list, where it resides for a "minimum queue time", which is intended to save ourselves an expensive smp IPI when the RMID is unlikely to have a occupancy value below __intel_cqm_threshold.

If we fail to recycle an RMID, even after waiting the minimum queue time then we need to increment __intel_cqm_threshold. There is an upper bound on this threshold, __intel_cqm_max_threshold, which is programmable from userland as /sys/devices/intel_cqm/max_recycling_threshold.

The comments above __intel_cqm_rmid_rotate() have more details.

Cc Peter Zijlstra <[email protected]>

---
Changes in v4:

- Calculate __intel_cqm_max_threshold based on the size of the LLC and number of RMIDs

- Drop the list, bitmap, list dance in the rotation code and just use the limbo list but add a ->state member to the RMID struct so we can track when an RMID has been recycled

- Use pmu::hrtimer_interval_ms for our rotation timer tick

 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 640 ++++++++++++++++++++++++++---
 1 file changed, 592 insertions(+), 48 deletions(-)
arch/x86/kernel/cpu/perf_event_intel_cqm.c +592 -48
index 2bd023f8fb6a..df15d28c00e3 100644
@@ -25,9 +25,13 @@ struct intel_cqm_state {
 static DEFINE_PER_CPU(struct intel_cqm_state, cqm_state);
 
 /*
- * Protects cache_cgroups and cqm_rmid_lru.
+ * Protects cache_cgroups and cqm_rmid_free_lru and cqm_rmid_limbo_lru.
+ * Also protects event->hw.cqm_rmid
+ *
+ * Hold either for stability, both for modification of ->hw.cqm_rmid.
  */
 static DEFINE_MUTEX(cache_mutex);
+static DEFINE_RAW_SPINLOCK(cache_lock);
 
 /*
  * Groups of events that have the same target(s), one RMID per group.
@@ -46,7 +50,34 @@ static cpumask_t cqm_cpumask;
 
 #define QOS_EVENT_MASK	QOS_L3_OCCUP_EVENT_ID
 
-static u64 __rmid_read(unsigned long rmid)
+/*
+ * This is central to the rotation algorithm in __intel_cqm_rmid_rotate().
+ *
+ * This rmid is always free and is guaranteed to have an associated
+ * near-zero occupancy value, i.e. no cachelines are tagged with this
+ * RMID, once __intel_cqm_rmid_rotate() returns.
+ */
+static unsigned int intel_cqm_rotation_rmid;
+
+#define INVALID_RMID		(-1)
+
+/*
+ * Is @rmid valid for programming the hardware?
+ *
+ * rmid 0 is reserved by the hardware for all non-monitored tasks, which
+ * means that we should never come across an rmid with that value.
+ * Likewise, an rmid value of -1 is used to indicate "no rmid currently
+ * assigned" and is used as part of the rotation code.
+ */
+static inline bool __rmid_valid(unsigned int rmid)
+{
+	if (!rmid || rmid == INVALID_RMID)
+		return false;
+
+	return true;
+}
+
+static u64 __rmid_read(unsigned int rmid)
 {
 	u64 val;
 
@@ -64,13 +95,21 @@ static u64 __rmid_read(unsigned long rmid)
 	return val;
 }
 
+enum rmid_recycle_state {
+	RMID_YOUNG = 0,
+	RMID_AVAILABLE,
+	RMID_DIRTY,
+};
+
 struct cqm_rmid_entry {
-	u64 rmid;
+	unsigned int rmid;
 	struct list_head list;
+	unsigned long queue_time;
+	enum rmid_recycle_state state;
 };
 
 /*
- * A least recently used list of RMIDs.
+ * cqm_rmid_free_lru - A least recently used list of RMIDs.
  *
  * Oldest entry at the head, newest (most recently used) entry at the
  * tail. This list is never traversed, it's only used to keep track of
@@ -81,9 +120,18 @@ struct cqm_rmid_entry {
  * in use. To mark an RMID as in use, remove its entry from the lru
  * list.
  *
- * This list is protected by cache_mutex.
+ *
+ * cqm_rmid_limbo_lru - list of currently unused but (potentially) dirty RMIDs.
+ *
+ * This list is contains RMIDs that no one is currently using but that
+ * may have a non-zero occupancy value associated with them. The
+ * rotation worker moves RMIDs from the limbo list to the free list once
+ * the occupancy value drops below __intel_cqm_threshold.
+ *
+ * Both lists are protected by cache_mutex.
  */
-static LIST_HEAD(cqm_rmid_lru);
+static LIST_HEAD(cqm_rmid_free_lru);
+static LIST_HEAD(cqm_rmid_limbo_lru);
 
 /*
  * We use a simple array of pointers so that we can lookup a struct
@@ -120,37 +168,43 @@ static int __get_rmid(void)
 
 	lockdep_assert_held(&cache_mutex);
 
-	if (list_empty(&cqm_rmid_lru))
-		return -EAGAIN;
+	if (list_empty(&cqm_rmid_free_lru))
+		return INVALID_RMID;
 
-	entry = list_first_entry(&cqm_rmid_lru, struct cqm_rmid_entry, list);
+	entry = list_first_entry(&cqm_rmid_free_lru, struct cqm_rmid_entry, list);
 	list_del(&entry->list);
 
 	return entry->rmid;
 }
 
-static void __put_rmid(int rmid)
+static void __put_rmid(unsigned int rmid)
 {
 	struct cqm_rmid_entry *entry;
 
 	lockdep_assert_held(&cache_mutex);
 
+	WARN_ON(!__rmid_valid(rmid));
 	entry = __rmid_entry(rmid);
 
-	list_add_tail(&entry->list, &cqm_rmid_lru);
+	entry->queue_time = jiffies;
+	entry->state = RMID_YOUNG;
+
+	list_add_tail(&entry->list, &cqm_rmid_limbo_lru);
 }
 
 static int intel_cqm_setup_rmid_cache(void)
 {
 	struct cqm_rmid_entry *entry;
-	int r;
+	unsigned int nr_rmids;
+	int r = 0;
 
+	nr_rmids = cqm_max_rmid + 1;
 	cqm_rmid_ptrs = kmalloc(sizeof(struct cqm_rmid_entry *) *
-				(cqm_max_rmid + 1), GFP_KERNEL);
+				nr_rmids, GFP_KERNEL);
 	if (!cqm_rmid_ptrs)
 		return -ENOMEM;
 
-	for (r = 0; r <= cqm_max_rmid; r++) {
+	for (; r <= cqm_max_rmid; r++) {
 		struct cqm_rmid_entry *entry;
 
 		entry = kmalloc(sizeof(*entry), GFP_KERNEL);
@@ -161,7 +215,7 @@ static int intel_cqm_setup_rmid_cache(void)
 		entry->rmid = r;
 		cqm_rmid_ptrs[r] = entry;
 
-		list_add_tail(&entry->list, &cqm_rmid_lru);
+		list_add_tail(&entry->list, &cqm_rmid_free_lru);
 	}
 
 	/*
@@ -171,6 +225,10 @@ static int intel_cqm_setup_rmid_cache(void)
 	entry = __rmid_entry(0);
 	list_del(&entry->list);
 
+	mutex_lock(&cache_mutex);
+	intel_cqm_rotation_rmid = __get_rmid();
+	mutex_unlock(&cache_mutex);
+
 	return 0;
 fail:
 	while (r--)
@@ -313,6 +371,390 @@ static bool __conflict_event(struct perf_event *a, struct perf_event *b)
 	return false;
 }
 
+struct rmid_read {
+	unsigned int rmid;
+	atomic64_t value;
+};
+
+static void __intel_cqm_event_count(void *info);
+
+/*
+ * Exchange the RMID of a group of events.
+ */
+static unsigned int
+intel_cqm_xchg_rmid(struct perf_event *group, unsigned int rmid)
+{
+	struct perf_event *event;
+	unsigned int old_rmid = group->hw.cqm_rmid;
+	struct list_head *head = &group->hw.cqm_group_entry;
+
+	lockdep_assert_held(&cache_mutex);
+
+	/*
+	 * If our RMID is being deallocated, perform a read now.
+	 */
+	if (__rmid_valid(old_rmid) && !__rmid_valid(rmid)) {
+		struct rmid_read rr = {
+			.value = ATOMIC64_INIT(0),
+			.rmid = old_rmid,
+		};
+
+		on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count,
+				 &rr, 1);
+		local64_set(&group->count, atomic64_read(&rr.value));
+	}
+
+	raw_spin_lock_irq(&cache_lock);
+
+	group->hw.cqm_rmid = rmid;
+	list_for_each_entry(event, head, hw.cqm_group_entry)
+		event->hw.cqm_rmid = rmid;
+
+	raw_spin_unlock_irq(&cache_lock);
+
+	return old_rmid;
+}
+
+/*
+ * If we fail to assign a new RMID for intel_cqm_rotation_rmid because
+ * cachelines are still tagged with RMIDs in limbo, we progressively
+ * increment the threshold until we find an RMID in limbo with <=
+ * __intel_cqm_threshold lines tagged. This is designed to mitigate the
+ * problem where cachelines tagged with an RMID are not steadily being
+ * evicted.
+ *
+ * On successful rotations we decrease the threshold back towards zero.
+ *
+ * __intel_cqm_max_threshold provides an upper bound on the threshold,
+ * and is measured in bytes because it's exposed to userland.
+ */
+static unsigned int __intel_cqm_threshold;
+static unsigned int __intel_cqm_max_threshold;
+
+/*
+ * Test whether an RMID has a zero occupancy value on this cpu.
+ */
+static void intel_cqm_stable(void *arg)
+{
+	struct cqm_rmid_entry *entry;
+
+	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
+		if (entry->state != RMID_AVAILABLE)
+			break;
+
+		if (__rmid_read(entry->rmid) > __intel_cqm_threshold)
+			entry->state = RMID_DIRTY;
+	}
+}
+
+/*
+ * If we have group events waiting for an RMID that don't conflict with
+ * events already running, assign @rmid.
+ */
+static bool intel_cqm_sched_in_event(unsigned int rmid)
+{
+	struct perf_event *leader, *event;
+
+	lockdep_assert_held(&cache_mutex);
+
+	leader = list_first_entry(&cache_groups, struct perf_event,
+				  hw.cqm_groups_entry);
+	event = leader;
+
+	list_for_each_entry_continue(event, &cache_groups,
+				     hw.cqm_groups_entry) {
+		if (__rmid_valid(event->hw.cqm_rmid))
+			continue;
+
+		if (__conflict_event(event, leader))
+			continue;
+
+		intel_cqm_xchg_rmid(event, rmid);
+		return true;
+	}
+
+	return false;
+}
+
+/*
+ * Initially use this constant for both the limbo queue time and the
+ * rotation timer interval, pmu::hrtimer_interval_ms.
+ *
+ * They don't need to be the same, but the two are related since if you
+ * rotate faster than you recycle RMIDs, you may run out of available
+ * RMIDs.
+ */
+#define RMID_DEFAULT_QUEUE_TIME 250	/* ms */
+
+static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;
+
+/*
+ * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
+ * @available: are there freeable RMIDs on the limbo list?
+ *
+ * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
+ * cachelines are tagged with those RMIDs. After this we can reuse them
+ * and know that the current set of active RMIDs is stable.
+ *
+ * Return %true or %false depending on whether we were able to stabilize
+ * an RMID for intel_cqm_rotation_rmid.
+ *
+ * If we return %false then @available is updated to indicate the reason
+ * we couldn't stabilize any RMIDs. @available is %false if no suitable
+ * RMIDs were found on the limbo list to recycle, i.e. no RMIDs had been
+ * on the list for the minimum queue time. If @available is %true then,
+ * we found suitable RMIDs to recycle but none had an associated
+ * occupancy value below __intel_cqm_threshold and the threshold should
+ * be increased and stabilization reattempted.
+ */
+static bool intel_cqm_rmid_stabilize(bool *available)
+{
+	struct cqm_rmid_entry *entry, *tmp;
+	struct perf_event *event;
+
+	lockdep_assert_held(&cache_mutex);
+
+	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
+		unsigned long min_queue_time;
+		unsigned long now = jiffies;
+
+		/*
+		 * We hold RMIDs placed into limbo for a minimum queue
+		 * time. Before the minimum queue time has elapsed we do
+		 * not recycle RMIDs.
+		 *
+		 * The reasoning is that until a sufficient time has
+		 * passed since we stopped using an RMID, any RMID
+		 * placed onto the limbo list will likely still have
+		 * data tagged in the cache, which means we'll probably
+		 * fail to recycle it anyway.
+		 *
+		 * We can save ourselves an expensive IPI by skipping
+		 * any RMIDs that have not been queued for the minimum
+		 * time.
+		 */
+		min_queue_time = entry->queue_time +
+			msecs_to_jiffies(__rmid_queue_time_ms);
+
+		if (time_after(min_queue_time, now))
+			break;
+
+		entry->state = RMID_AVAILABLE;
+		*available = true;
+	}
+
+	/*
+	 * Fast return if none of the RMIDs on the limbo list have been
+	 * sitting on the queue for the minimum queue time.
+	 */
+	if (!*available)
+		return false;
+
+	/*
+	 * Test whether an RMID is free for each package.
+	 */
+	on_each_cpu_mask(&cqm_cpumask, intel_cqm_stable, NULL, true);
+
+	list_for_each_entry_safe(entry, tmp, &cqm_rmid_limbo_lru, list) {
+		/*
+		 * Exhausted all RMIDs that have waited min queue time.
+		 */
+		if (entry->state == RMID_YOUNG)
+			break;
+
+		if (entry->state == RMID_DIRTY)
+			continue;
+
+		list_del(&entry->list);	/* remove from limbo */
+
+		/*
+		 * The rotation RMID gets priority if it's
+		 * currently invalid. In which case, skip adding
+		 * the RMID to the the free lru.
+		 */
+		if (!__rmid_valid(intel_cqm_rotation_rmid)) {
+			intel_cqm_rotation_rmid = entry->rmid;
+			continue;
+		}
+
+		/*
+		 * If we have groups waiting for RMIDs, hand
+		 * them one now.
+		 */
+		list_for_each_entry(event, &cache_groups,
+				    hw.cqm_groups_entry) {
+			if (__rmid_valid(event->hw.cqm_rmid))
+				continue;
+
+			intel_cqm_xchg_rmid(event, entry->rmid);
+			entry = NULL;
+			break;
+		}
+
+		if (!entry)
+			continue;
+
+		/*
+		 * Otherwise place it onto the free list.
+		 */
+		list_add_tail(&entry->list, &cqm_rmid_free_lru);
+	}
+
+
+	return __rmid_valid(intel_cqm_rotation_rmid);
+}
+
+/*
+ * Pick a victim group and move it to the tail of the group list.
+ */
+static struct perf_event *
+__intel_cqm_pick_and_rotate(void)
+{
+	struct perf_event *rotor;
+
+	lockdep_assert_held(&cache_mutex);
+	lockdep_assert_held(&cache_lock);
+
+	rotor = list_first_entry(&cache_groups, struct perf_event,
+				 hw.cqm_groups_entry);
+	list_rotate_left(&cache_groups);
+
+	return rotor;
+}
+
+/*
+ * Attempt to rotate the groups and assign new RMIDs.
+ *
+ * Rotating RMIDs is complicated because the hardware doesn't give us
+ * any clues.
+ *
+ * There's problems with the hardware interface; when you change the
+ * task:RMID map cachelines retain their 'old' tags, giving a skewed
+ * picture. In order to work around this, we must always keep one free
+ * RMID - intel_cqm_rotation_rmid.
+ *
+ * Rotation works by taking away an RMID from a group (the old RMID),
+ * and assigning the free RMID to another group (the new RMID). We must
+ * then wait for the old RMID to not be used (no cachelines tagged).
+ * This ensure that all cachelines are tagged with 'active' RMIDs. At
+ * this point we can start reading values for the new RMID and treat the
+ * old RMID as the free RMID for the next rotation.
+ *
+ * Return %true or %false depending on whether we did any rotating.
+ */
+static bool __intel_cqm_rmid_rotate(void)
+{
+	struct perf_event *group, *rotor, *start = NULL;
+	unsigned int nr_needed = 0;
+	unsigned int rmid;
+	bool rotated = false;
+	bool available;
+
+	mutex_lock(&cache_mutex);
+
+again:
+	/*
+	 * Fast path through this function if there are no groups and no
+	 * RMIDs that need cleaning.
+	 */
+	if (list_empty(&cache_groups) && list_empty(&cqm_rmid_limbo_lru))
+		goto out;
+
+	list_for_each_entry(group, &cache_groups, hw.cqm_groups_entry) {
+		if (!__rmid_valid(group->hw.cqm_rmid)) {
+			if (!start)
+				start = group;
+			nr_needed++;
+		}
+	}
+
+	/*
+	 * We have some event groups, but they all have RMIDs assigned
+	 * and no RMIDs need cleaning.
+	 */
+	if (!nr_needed && list_empty(&cqm_rmid_limbo_lru))
+		goto out;
+
+	if (!nr_needed)
+		goto stabilize;
+
+	/*
+	 * We have more event groups without RMIDs than available RMIDs.
+	 *
+	 * We force deallocate the rmid of the group at the head of
+	 * cache_groups. The first event group without an RMID then gets
+	 * assigned intel_cqm_rotation_rmid. This ensures we always make
+	 * forward progress.
+	 *
+	 * Rotate the cache_groups list so the previous head is now the
+	 * tail.
+	 */
+	rotor = __intel_cqm_pick_and_rotate();
+	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
+
+	/*
+	 * The group at the front of the list should always have a valid
+	 * RMID. If it doesn't then no groups have RMIDs assigned.
+	 */
+	if (!__rmid_valid(rmid))
+		goto stabilize;
+
+	/*
+	 * If the rotation is going to succeed, reduce the threshold so
+	 * that we don't needlessly reuse dirty RMIDs.
+	 */
+	if (__rmid_valid(intel_cqm_rotation_rmid)) {
+		intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
+		intel_cqm_rotation_rmid = INVALID_RMID;
+
+		if (__intel_cqm_threshold)
+			__intel_cqm_threshold--;
+	}
+
+	__put_rmid(rmid);
+
+	rotated = true;
+
+stabilize:
+	/*
+	 * We now need to stablize the RMID we freed above (if any) to
+	 * ensure that the next time we rotate we have an RMID with zero
+	 * occupancy value.
+	 *
+	 * Alternatively, if we didn't need to perform any rotation,
+	 * we'll have a bunch of RMIDs in limbo that need stabilizing.
+	 */
+	if (!intel_cqm_rmid_stabilize(&available)) {
+		unsigned int limit;
+
+		limit = __intel_cqm_max_threshold / cqm_l3_scale;
+		if (available && __intel_cqm_threshold < limit) {
+			__intel_cqm_threshold++;
+			goto again;
+		}
+	}
+
+out:
+	mutex_unlock(&cache_mutex);
+	return rotated;
+}
+
+static void intel_cqm_rmid_rotate(struct work_struct *work);
+
+static DECLARE_DELAYED_WORK(intel_cqm_rmid_work, intel_cqm_rmid_rotate);
+
+static struct pmu intel_cqm_pmu;
+
+static void intel_cqm_rmid_rotate(struct work_struct *work)
+{
+	unsigned long delay;
+
+	__intel_cqm_rmid_rotate();
+
+	delay = msecs_to_jiffies(intel_cqm_pmu.hrtimer_interval_ms);
+	schedule_delayed_work(&intel_cqm_rmid_work, delay);
+}
+
 /*
  * Find a group and setup RMID.
  *
@@ -322,7 +764,6 @@ static int intel_cqm_setup_event(struct perf_event *event,
 				 struct perf_event **group)
 {
 	struct perf_event *iter;
-	int rmid;
 
 	list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
 		if (__match_event(iter, event)) {
@@ -336,17 +777,14 @@ static int intel_cqm_setup_event(struct perf_event *event,
 			return -EBUSY;
 	}
 
-	rmid = __get_rmid();
-	if (rmid < 0)
-		return rmid;
-
-	event->hw.cqm_rmid = rmid;
+	event->hw.cqm_rmid = __get_rmid();
 	return 0;
 }
 
 static void intel_cqm_event_read(struct perf_event *event)
 {
-	unsigned long rmid;
+	unsigned long flags;
+	unsigned int rmid;
 	u64 val;
 
 	/*
@@ -355,23 +793,25 @@ static void intel_cqm_event_read(struct perf_event *event)
 	if (event->cpu == -1)
 		return;
 
+	raw_spin_lock_irqsave(&cache_lock, flags);
 	rmid = event->hw.cqm_rmid;
+
+	if (!__rmid_valid(rmid))
+		goto out;
+
 	val = __rmid_read(rmid);
 
 	/*
 	 * Ignore this reading on error states and do not update the value.
 	 */
 	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
-		return;
+		goto out;
 
 	local64_set(&event->count, val);
+out:
+	raw_spin_unlock_irqrestore(&cache_lock, flags);
 }
 
-struct rmid_read {
-	unsigned int rmid;
-	atomic64_t value;
-};
-
 static void __intel_cqm_event_count(void *info)
 {
 	struct rmid_read *rr = info;
@@ -392,8 +832,8 @@ static inline bool cqm_group_leader(struct perf_event *event)
 
 static u64 intel_cqm_event_count(struct perf_event *event)
 {
+	unsigned long flags;
 	struct rmid_read rr = {
-		.rmid = event->hw.cqm_rmid,
 		.value = ATOMIC64_INIT(0),
 	};
 
@@ -417,17 +857,38 @@ static u64 intel_cqm_event_count(struct perf_event *event)
 	if (!cqm_group_leader(event))
 		return 0;
 
-	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
+	/*
+	 * Notice that we don't perform the reading of an RMID
+	 * atomically, because we can't hold a spin lock across the
+	 * IPIs.
+	 *
+	 * Speculatively perform the read, since @event might be
+	 * assigned a different (possibly invalid) RMID while we're
+	 * busying performing the IPI calls. It's therefore necessary to
+	 * check @event's RMID afterwards, and if it has changed,
+	 * discard the result of the read.
+	 */
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	rr.rmid = event->hw.cqm_rmid;
+	raw_spin_unlock_irqrestore(&cache_lock, flags);
+
+	if (!__rmid_valid(rr.rmid))
+		goto out;
 
-	local64_set(&event->count, atomic64_read(&rr.value));
+	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
 
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	if (event->hw.cqm_rmid == rr.rmid)
+		local64_set(&event->count, atomic64_read(&rr.value));
+	raw_spin_unlock_irqrestore(&cache_lock, flags);
+out:
 	return __perf_event_count(event);
 }
 
 static void intel_cqm_event_start(struct perf_event *event, int mode)
 {
 	struct intel_cqm_state *state = &__get_cpu_var(cqm_state);
-	unsigned long rmid = event->hw.cqm_rmid;
+	unsigned int rmid = event->hw.cqm_rmid;
 	unsigned long flags;
 
 	if (!(event->hw.cqm_state & PERF_HES_STOPPED))
@@ -473,15 +934,19 @@ static void intel_cqm_event_stop(struct perf_event *event, int mode)
 
 static int intel_cqm_event_add(struct perf_event *event, int mode)
 {
-	int rmid;
+	unsigned long flags;
+	unsigned int rmid;
+
+	raw_spin_lock_irqsave(&cache_lock, flags);
 
 	event->hw.cqm_state = PERF_HES_STOPPED;
 	rmid = event->hw.cqm_rmid;
-	WARN_ON_ONCE(!rmid);
 
-	if (mode & PERF_EF_START)
+	if (__rmid_valid(rmid) && (mode & PERF_EF_START))
 		intel_cqm_event_start(event, mode);
 
+	raw_spin_unlock_irqrestore(&cache_lock, flags);
+
 	return 0;
 }
 
@@ -518,8 +983,10 @@ static void intel_cqm_event_destroy(struct perf_event *event)
 			list_replace(&event->hw.cqm_groups_entry,
 				     &group_other->hw.cqm_groups_entry);
 		} else {
-			int rmid = event->hw.cqm_rmid;
-			__put_rmid(rmid);
+			unsigned int rmid = event->hw.cqm_rmid;
+
+			if (__rmid_valid(rmid))
+				__put_rmid(rmid);
 			list_del(&event->hw.cqm_groups_entry);
 		}
 	}
@@ -527,11 +994,10 @@ static void intel_cqm_event_destroy(struct perf_event *event)
 	mutex_unlock(&cache_mutex);
 }
 
-static struct pmu intel_cqm_pmu;
-
 static int intel_cqm_event_init(struct perf_event *event)
 {
 	struct perf_event *group = NULL;
+	bool rotate = false;
 	int err;
 
 	if (event->attr.type != intel_cqm_pmu.type)
@@ -568,10 +1034,24 @@ static int intel_cqm_event_init(struct perf_event *event)
 	} else {
 		list_add_tail(&event->hw.cqm_groups_entry,
 			      &cache_groups);
+
+		/*
+		 * All RMIDs are either in use or have recently been
+		 * used. Kick the rotation worker to clean/free some.
+		 *
+		 * We only do this for the group leader, rather than for
+		 * every event in a group to save on needless work.
+		 */
+		if (!__rmid_valid(event->hw.cqm_rmid))
+			rotate = true;
 	}
 
 out:
 	mutex_unlock(&cache_mutex);
+
+	if (rotate)
+		schedule_delayed_work(&intel_cqm_rmid_work, 0);
+
 	return err;
 }
 
@@ -606,22 +1086,76 @@ static struct attribute_group intel_cqm_format_group = {
 	.attrs = intel_cqm_formats_attr,
 };
 
+static ssize_t
+max_recycle_threshold_show(struct device *dev, struct device_attribute *attr,
+			   char *page)
+{
+	ssize_t rv;
+
+	mutex_lock(&cache_mutex);
+	rv = snprintf(page, PAGE_SIZE-1, "%u\n", __intel_cqm_max_threshold);
+	mutex_unlock(&cache_mutex);
+
+	return rv;
+}
+
+static ssize_t
+max_recycle_threshold_store(struct device *dev,
+			    struct device_attribute *attr,
+			    const char *buf, size_t count)
+{
+	unsigned int bytes, cachelines;
+	int ret;
+
+	ret = kstrtouint(buf, 0, &bytes);
+	if (ret)
+		return ret;
+
+	mutex_lock(&cache_mutex);
+
+	__intel_cqm_max_threshold = bytes;
+	cachelines = bytes / cqm_l3_scale;
+
+	/*
+	 * The new maximum takes effect immediately.
+	 */
+	if (__intel_cqm_threshold > cachelines)
+		__intel_cqm_threshold = cachelines;
+
+	mutex_unlock(&cache_mutex);
+
+	return count;
+}
+
+static DEVICE_ATTR_RW(max_recycle_threshold);
+
+static struct attribute *intel_cqm_attrs[] = {
+	&dev_attr_max_recycle_threshold.attr,
+	NULL,
+};
+
+static const struct attribute_group intel_cqm_group = {
+	.attrs = intel_cqm_attrs,
+};
+
 static const struct attribute_group *intel_cqm_attr_groups[] = {
 	&intel_cqm_events_group,
 	&intel_cqm_format_group,
+	&intel_cqm_group,
 	NULL,
 };
 
 static struct pmu intel_cqm_pmu = {
-	.attr_groups	= intel_cqm_attr_groups,
-	.task_ctx_nr	= perf_sw_context,
-	.event_init	= intel_cqm_event_init,
-	.add		= intel_cqm_event_add,
-	.del		= intel_cqm_event_del,
-	.start		= intel_cqm_event_start,
-	.stop		= intel_cqm_event_stop,
-	.read		= intel_cqm_event_read,
-	.count		= intel_cqm_event_count,
+	.hrtimer_interval_ms = RMID_DEFAULT_QUEUE_TIME,
+	.attr_groups	     = intel_cqm_attr_groups,
+	.task_ctx_nr	     = perf_sw_context,
+	.event_init	     = intel_cqm_event_init,
+	.add		     = intel_cqm_event_add,
+	.del		     = intel_cqm_event_del,
+	.start		     = intel_cqm_event_start,
+	.stop		     = intel_cqm_event_stop,
+	.read		     = intel_cqm_event_read,
+	.count		     = intel_cqm_event_count,
 };
 
 static inline void cqm_pick_event_reader(int cpu)
@@ -730,6 +1264,16 @@ static int __init intel_cqm_init(void)
 		}
 	}
 
+	/*
+	 * A reasonable upper limit on the max threshold is the number
+	 * of lines tagged per RMID if all RMIDs have the same number of
+	 * lines tagged in the LLC.
+	 *
+	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
+	 */
+	__intel_cqm_max_threshold =
+		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);
+
 	snprintf(scale, sizeof(scale), "%u", cqm_l3_scale);
 	str = kstrdup(scale, GFP_KERNEL);
 	if (!str) {
Signature · 1 line
1.9.3
maintainer
#11 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

arch/x86/kernel/cpu/perf_event_intel_cqm.c static u64 __rmid_read(unsigned long rmid) · line 109

Quoted 13 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +9 -1
+enum rmid_recycle_state {
+	RMID_YOUNG = 0,
+	RMID_AVAILABLE,
+	RMID_DIRTY,
+};
+
 struct cqm_rmid_entry {
-	u64 rmid;
+	unsigned int rmid;
 	struct list_head list;
+	unsigned long queue_time;
+	enum rmid_recycle_state state;
 };

You probably want that enum after rmid to better pack the structure.

maintainer
#12 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

In reply to Matt Fleming
Quoted 10 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +10 -0
+/*
+ * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
+ * @available: are there freeable RMIDs on the limbo list?
+ *
+ * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
+ * cachelines are tagged with those RMIDs. After this we can reuse them
+ * and know that the current set of active RMIDs is stable.
+ *
+ * Return %true or %false depending on whether we were able to stabilize
+ * an RMID for intel_cqm_rotation_rmid.

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool __conflict_event(struct perf_event *a, struct perf_event *b) · line 510

Quoted 10 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +10 -0
+ *
+ * If we return %false then @available is updated to indicate the reason
+ * we couldn't stabilize any RMIDs. @available is %false if no suitable
+ * RMIDs were found on the limbo list to recycle, i.e. no RMIDs had been
+ * on the list for the minimum queue time. If @available is %true then,
+ * we found suitable RMIDs to recycle but none had an associated
+ * occupancy value below __intel_cqm_threshold and the threshold should
+ * be increased and stabilization reattempted.
+ */
+static bool intel_cqm_rmid_stabilize(bool *available)

slightly excessive quoting, bear with me, see below:

Quoted 99 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +99 -0
+/*
+ * Attempt to rotate the groups and assign new RMIDs.
+ *
+ * Rotating RMIDs is complicated because the hardware doesn't give us
+ * any clues.
+ *
+ * There's problems with the hardware interface; when you change the
+ * task:RMID map cachelines retain their 'old' tags, giving a skewed
+ * picture. In order to work around this, we must always keep one free
+ * RMID - intel_cqm_rotation_rmid.
+ *
+ * Rotation works by taking away an RMID from a group (the old RMID),
+ * and assigning the free RMID to another group (the new RMID). We must
+ * then wait for the old RMID to not be used (no cachelines tagged).
+ * This ensure that all cachelines are tagged with 'active' RMIDs. At
+ * this point we can start reading values for the new RMID and treat the
+ * old RMID as the free RMID for the next rotation.
+ *
+ * Return %true or %false depending on whether we did any rotating.
+ */
+static bool __intel_cqm_rmid_rotate(void)
+{
+	struct perf_event *group, *rotor, *start = NULL;
+	unsigned int nr_needed = 0;
+	unsigned int rmid;
+	bool rotated = false;
+	bool available;
+
+	mutex_lock(&cache_mutex);
+
+again:
+	/*
+	 * Fast path through this function if there are no groups and no
+	 * RMIDs that need cleaning.
+	 */
+	if (list_empty(&cache_groups) && list_empty(&cqm_rmid_limbo_lru))
+		goto out;
+
+	list_for_each_entry(group, &cache_groups, hw.cqm_groups_entry) {
+		if (!__rmid_valid(group->hw.cqm_rmid)) {
+			if (!start)
+				start = group;
+			nr_needed++;
+		}
+	}
+
+	/*
+	 * We have some event groups, but they all have RMIDs assigned
+	 * and no RMIDs need cleaning.
+	 */
+	if (!nr_needed && list_empty(&cqm_rmid_limbo_lru))
+		goto out;
+
+	if (!nr_needed)
+		goto stabilize;
+
+	/*
+	 * We have more event groups without RMIDs than available RMIDs.
+	 *
+	 * We force deallocate the rmid of the group at the head of
+	 * cache_groups. The first event group without an RMID then gets
+	 * assigned intel_cqm_rotation_rmid. This ensures we always make
+	 * forward progress.
+	 *
+	 * Rotate the cache_groups list so the previous head is now the
+	 * tail.
+	 */
+	rotor = __intel_cqm_pick_and_rotate();
+	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
+
+	/*
+	 * The group at the front of the list should always have a valid
+	 * RMID. If it doesn't then no groups have RMIDs assigned.
+	 */
+	if (!__rmid_valid(rmid))
+		goto stabilize;
+
+	/*
+	 * If the rotation is going to succeed, reduce the threshold so
+	 * that we don't needlessly reuse dirty RMIDs.
+	 */
+	if (__rmid_valid(intel_cqm_rotation_rmid)) {
+		intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
+		intel_cqm_rotation_rmid = INVALID_RMID;
+
+		if (__intel_cqm_threshold)
+			__intel_cqm_threshold--;
+	}
+
+	__put_rmid(rmid);
+
+	rotated = true;
+
+stabilize:
+	/*
+	 * We now need to stablize the RMID we freed above (if any) to
+	 * ensure that the next time we rotate we have an RMID with zero
+	 * occupancy value.
+	 *

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool __conflict_event(struct perf_event *a, struct perf_event *b) · line 733

Quoted 10 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +10 -0
+	 * Alternatively, if we didn't need to perform any rotation,
+	 * we'll have a bunch of RMIDs in limbo that need stabilizing.
+	 */
+	if (!intel_cqm_rmid_stabilize(&available)) {
+		unsigned int limit;
+
+		limit = __intel_cqm_max_threshold / cqm_l3_scale;
+		if (available && __intel_cqm_threshold < limit) {
+			__intel_cqm_threshold++;
+			goto again;

afaict the again label will try and steal yet another rmid, if rmids don't decay fast enough, we could end up with all rmids on the limbo list and none active. Or am I missing something here?

Quoted 7 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +7 -0
+		}
+	}
+
+out:
+	mutex_unlock(&cache_mutex);
+	return rotated;
+}
#13 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 4 lines · Peter Zijlstra

afaict the again label will try and steal yet another rmid, if rmids don't decay fast enough, we could end up with all rmids on the limbo list and none active. Or am I missing something here?

You're not missing anything, that's true, we will try and steal more RMIDs. We could perhaps put a limit on how many RMIDs we're willing to steal, but I think it should definitely be > 1 because RMIDs can stabilize out of order.

It's worth pointing out that we only steal more RMIDs if the ones on the limbo list have been queued for the "minimum queue time" - it really is a last resort.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#14 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 6 lines · Matt Fleming
Quoted 4 lines · Peter Zijlstra

afaict the again label will try and steal yet another rmid, if rmids don't decay fast enough, we could end up with all rmids on the limbo list and none active. Or am I missing something here?

Quoted 8 lines

You're not missing anything, that's true, we will try and steal more RMIDs. We could perhaps put a limit on how many RMIDs we're willing to steal, but I think it should definitely be > 1 because RMIDs can stabilize out of order.

It's worth pointing out that we only steal more RMIDs if the ones on the limbo list have been queued for the "minimum queue time" - it really is a last resort.

Do we really care? Why not just hold up everything until the one(s) we have are low enough?

Yes it all blows, but would not some active be better than none active, just because the stupid lines aren't clearing fast enough?

#15 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 16 lines · Peter Zijlstra
Quoted 6 lines · Matt Fleming
Quoted 4 lines · Peter Zijlstra

afaict the again label will try and steal yet another rmid, if rmids don't decay fast enough, we could end up with all rmids on the limbo list and none active. Or am I missing something here?

Quoted 8 lines

You're not missing anything, that's true, we will try and steal more RMIDs. We could perhaps put a limit on how many RMIDs we're willing to steal, but I think it should definitely be > 1 because RMIDs can stabilize out of order.

It's worth pointing out that we only steal more RMIDs if the ones on the limbo list have been queued for the "minimum queue time" - it really is a last resort.

Quoted 5 lines

Do we really care? Why not just hold up everything until the one(s) we have are low enough?

Yes it all blows, but would not some active be better than none active, just because the stupid lines aren't clearing fast enough?

Right, but now we need a "steal limit", so we know when to stop stealing active RMIDs.

	(cqm_max_rmid + 1) / 4 ?

I guess any limit is better than no limit.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#16 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 23 lines · Matt Fleming
Quoted 16 lines · Peter Zijlstra
Quoted 6 lines · Matt Fleming
Quoted 4 lines · Peter Zijlstra

afaict the again label will try and steal yet another rmid, if rmids don't decay fast enough, we could end up with all rmids on the limbo list and none active. Or am I missing something here?

Quoted 8 lines

You're not missing anything, that's true, we will try and steal more RMIDs. We could perhaps put a limit on how many RMIDs we're willing to steal, but I think it should definitely be > 1 because RMIDs can stabilize out of order.

It's worth pointing out that we only steal more RMIDs if the ones on the limbo list have been queued for the "minimum queue time" - it really is a last resort.

Quoted 5 lines

Do we really care? Why not just hold up everything until the one(s) we have are low enough?

Yes it all blows, but would not some active be better than none active, just because the stupid lines aren't clearing fast enough?

Quoted 6 lines

Right, but now we need a "steal limit", so we know when to stop stealing active RMIDs.

	(cqm_max_rmid + 1) / 4 ?

I guess any limit is better than no limit.

Yeah, that'll work, when the free+limbo count is 1/4th the total we should stop pulling more plugs.

#17 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 11 lines · Peter Zijlstra
Quoted 7 lines · Matt Fleming

Right, but now we need a "steal limit", so we know when to stop stealing active RMIDs.

	(cqm_max_rmid + 1) / 4 ?

I guess any limit is better than no limit.

Yeah, that'll work, when the free+limbo count is 1/4th the total we should stop pulling more plugs.

We actually stop pulling plugs as soon as there's a single RMID available to use as the rotation RMID. When we find one, we don't wait any longer to do any kind of batching (though if we go from zero available RMIDs, to 5 RMIDs in one loop, we'll pickup all 5 RMIDs).

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
#18 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

In reply to Peter Zijlstra
Quoted 3 lines · Peter Zijlstra

Yeah, that'll work, when the free+limbo count is 1/4th the total we should stop pulling more plugs.

Perhaps something like this? It favours stealing more RMIDs over increasing the "dirty threshold".

---

arch/x86/kernel/cpu/perf_event_intel_cqm.c +46 -20
index fc1a90245601..af58f233c93c 100644
@@ -490,29 +490,27 @@ static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;
 
 /*
  * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
- * @available: are there freeable RMIDs on the limbo list?
+ * @nr_available: number of freeable RMIDs on the limbo list
  *
  * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
  * cachelines are tagged with those RMIDs. After this we can reuse them
  * and know that the current set of active RMIDs is stable.
  *
- * Return %true or %false depending on whether we were able to stabilize
- * an RMID for intel_cqm_rotation_rmid.
+ * Return %true or %false depending on whether stabilization needs to be
+ * reattempted.
  *
- * If we return %false then @available is updated to indicate the reason
- * we couldn't stabilize any RMIDs. @available is %false if no suitable
- * RMIDs were found on the limbo list to recycle, i.e. no RMIDs had been
- * on the list for the minimum queue time. If @available is %true then,
- * we found suitable RMIDs to recycle but none had an associated
- * occupancy value below __intel_cqm_threshold and the threshold should
- * be increased and stabilization reattempted.
+ * If we return %true then @nr_available is updated to indicate the
+ * number of RMIDs on the limbo list that have been queued for the
+ * minimum queue time (RMID_AVAILABLE), but whose data occupancy values
+ * are above __intel_cqm_threshold.
  */
-static bool intel_cqm_rmid_stabilize(bool *available)
+static bool intel_cqm_rmid_stabilize(unsigned int *available)
 {
 	struct cqm_rmid_entry *entry, *tmp;
 
 	lockdep_assert_held(&cache_mutex);
 
+	*available = 0;
 	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
 		unsigned long min_queue_time;
 		unsigned long now = jiffies;
@@ -539,7 +537,7 @@ static bool intel_cqm_rmid_stabilize(bool *available)
 			break;
 
 		entry->state = RMID_AVAILABLE;
-		*available = true;
+		*available++;
 	}
 
 	/*
@@ -547,7 +545,7 @@ static bool intel_cqm_rmid_stabilize(bool *available)
 	 * sitting on the queue for the minimum queue time.
 	 */
 	if (!*available)
-		return false;
+		return true;
 
 	/*
 	 * Test whether an RMID is free for each package.
@@ -684,9 +682,10 @@ static void intel_cqm_sched_out_events(struct perf_event *event)
 static bool __intel_cqm_rmid_rotate(void)
 {
 	struct perf_event *group, *start = NULL;
+	unsigned int threshold_limit;
 	unsigned int nr_needed = 0;
+	unsigned int nr_available;
 	bool rotated = false;
-	bool available;
 
 	mutex_lock(&cache_mutex);
 
@@ -756,14 +755,41 @@ stabilize:
 	 * Alternatively, if we didn't need to perform any rotation,
 	 * we'll have a bunch of RMIDs in limbo that need stabilizing.
 	 */
-	if (!intel_cqm_rmid_stabilize(&available)) {
-		unsigned int limit;
+	threshold_limit = __intel_cqm_max_threshold / cqm_l3_scale;
+
+	while (intel_cqm_rmid_stabilize(&nr_available) &&
+	       __intel_cqm_threshold < threshold_limit) {
+		unsigned int steal_limit;
+
+		/* Allow max 25% of RMIDs to be in limbo. */
+		steal_limit = (cqm_max_rmid + 1) / 4;
 
-		limit = __intel_cqm_max_threshold / cqm_l3_scale;
-		if (available && __intel_cqm_threshold < limit) {
-			__intel_cqm_threshold++;
+		/*
+		 * We failed to stabilize any RMIDs so our rotation
+		 * logic is now stuck. In order to make forward progress
+		 * we have a few options:
+		 *
+		 *   1. rotate ("steal") another RMID
+		 *   2. increase the threshold
+		 *   3. do nothing
+		 *
+		 * We do both of 1. and 2. until we hit the steal limit.
+		 *
+		 * The steal limit prevents all RMIDs ending up on the
+		 * limbo list. This can happen if every RMID has a
+		 * non-zero occupancy above threshold_limit, and the
+		 * occupancy values aren't dropping fast enough.
+		 *
+		 * Note that there is prioritisation at work here - we'd
+		 * rather increase the number of RMIDs on the limbo list
+		 * than increase the threshold, because increasing the
+		 * threshold skews the event data (because we reuse
+		 * dirty RMIDs) - threshold bumps are a last resort.
+		 */
+		if (nr_available < steal_limit)
 			goto again;
-		}
+
+		__intel_cqm_threshold++;
 	}
 
 out:
Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#19 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

In reply to Matt Fleming
Quoted 9 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +4 -1
@@ -417,17 +857,38 @@ static u64 intel_cqm_event_count(struct perf_event *event)
 	if (!cqm_group_leader(event))
 		return 0;
 
-	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
+	/*
+	 * Notice that we don't perform the reading of an RMID
+	 * atomically, because we can't hold a spin lock across the
+	 * IPIs.

arch/x86/kernel/cpu/perf_event_intel_cqm.c static u64 intel_cqm_event_count(struct perf_event *event) · line 873

Quoted 10 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +10 -0
+	 *
+	 * Speculatively perform the read, since @event might be
+	 * assigned a different (possibly invalid) RMID while we're
+	 * busying performing the IPI calls. It's therefore necessary to
+	 * check @event's RMID afterwards, and if it has changed,
+	 * discard the result of the read.
+	 */
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	rr.rmid = event->hw.cqm_rmid;
+	raw_spin_unlock_irqrestore(&cache_lock, flags);

You don't actually have to hold the lock here, only ACCESS_ONCE() or whatever newfangled thing replaced that.

arch/x86/kernel/cpu/perf_event_intel_cqm.c static u64 intel_cqm_event_count(struct perf_event *event) · line 883

Quoted 11 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +8 -1
+
+	if (!__rmid_valid(rr.rmid))
+		goto out;
 
-	local64_set(&event->count, atomic64_read(&rr.value));
+	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
 
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	if (event->hw.cqm_rmid == rr.rmid)
+		local64_set(&event->count, atomic64_read(&rr.value));
+	raw_spin_unlock_irqrestore(&cache_lock, flags);

Here you do indeed need the lock as its more than a single op :-)

Quoted 3 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +1 -0
+out:
 	return __perf_event_count(event);
 }
#20 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +9 -1
@@ -417,17 +857,38 @@ static u64 intel_cqm_event_count(struct perf_event *event)
 	if (!cqm_group_leader(event))
 		return 0;
 
-	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
+	/*
+	 * Notice that we don't perform the reading of an RMID
+	 * atomically, because we can't hold a spin lock across the
+	 * IPIs.
+	 *
+	 * Speculatively perform the read, since @event might be
+	 * assigned a different (possibly invalid) RMID while we're
+	 * busying performing the IPI calls. It's therefore necessary to
+	 * check @event's RMID afterwards, and if it has changed,
Quoted 8 lines

arch/x86/kernel/cpu/perf_event_intel_cqm.c static u64 intel_cqm_event_count(struct perf_event *event) · line 873

Quoted 5 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +5 -0
+	 * discard the result of the read.
+	 */
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	rr.rmid = event->hw.cqm_rmid;
+	raw_spin_unlock_irqrestore(&cache_lock, flags);

You don't actually have to hold the lock here, only ACCESS_ONCE() or whatever newfangled thing replaced that.

Remind me again, are accesses to 'int' guaranteed to be atomic? There's no way to read a partial value?

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#21 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 25 lines · Matt Fleming
Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +9 -1
@@ -417,17 +857,38 @@ static u64 intel_cqm_event_count(struct perf_event *event)
 	if (!cqm_group_leader(event))
 		return 0;
 
-	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
+	/*
+	 * Notice that we don't perform the reading of an RMID
+	 * atomically, because we can't hold a spin lock across the
+	 * IPIs.
+	 *
+	 * Speculatively perform the read, since @event might be
+	 * assigned a different (possibly invalid) RMID while we're
+	 * busying performing the IPI calls. It's therefore necessary to
+	 * check @event's RMID afterwards, and if it has changed,
Quoted 8 lines

arch/x86/kernel/cpu/perf_event_intel_cqm.c static u64 intel_cqm_event_count(struct perf_event *event) · line 873

Quoted 5 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +5 -0
+	 * discard the result of the read.
+	 */
+	raw_spin_lock_irqsave(&cache_lock, flags);
+	rr.rmid = event->hw.cqm_rmid;
+	raw_spin_unlock_irqrestore(&cache_lock, flags);

You don't actually have to hold the lock here, only ACCESS_ONCE() or whatever newfangled thing replaced that.

Quoted 2 lines

Remind me again, are accesses to 'int' guaranteed to be atomic? There's no way to read a partial value?

Yah, assuming natural alignment, loads from ints (and any other native machine word size) are atomic.

maintainer
#22 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

In reply to Matt Fleming

On Fri, Nov 14, 2014 at 09:15:11PM +0000, Matt Fleming wrote:
+ /*

arch/x86/kernel/cpu/perf_event_intel_cqm.c static int __init intel_cqm_init(void) · line 1275

Quoted 8 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +8 -0
+	 * A reasonable upper limit on the max threshold is the number
+	 * of lines tagged per RMID if all RMIDs have the same number of
+	 * lines tagged in the LLC.
+	 *
+	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
+	 */
+	__intel_cqm_max_threshold =
+		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);

Seeing how a percentage is without unit, the 35MB figure seems pointless.

Also, why would a flat distribution be a good measure for 'empty'? I would think that would in fact constitute in use.

Should we make this 1/16th of this figure or any other random fraction < 1 ?

#23 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 13 lines · Peter Zijlstra

On Fri, Nov 14, 2014 at 09:15:11PM +0000, Matt Fleming wrote:
+ /*

arch/x86/kernel/cpu/perf_event_intel_cqm.c static int __init intel_cqm_init(void) · line 1275

Quoted 8 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +8 -0
+	 * A reasonable upper limit on the max threshold is the number
+	 * of lines tagged per RMID if all RMIDs have the same number of
+	 * lines tagged in the LLC.
+	 *
+	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
+	 */
+	__intel_cqm_max_threshold =
+		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);

Seeing how a percentage is without unit, the 35MB figure seems pointless.

It's only an example to demonstrate that this fudge calculation makes sense on the current class of CQM-enabled hardware.

Quoted 2 lines

Also, why would a flat distribution be a good measure for 'empty'? I would think that would in fact constitute in use.

It's not, it's a good measure for 'full'. This is the *max* threshold. When searching for RMIDs to stabilize we'll stop searching if __intel_cqm_threshold == __intel_cqm_max_threshold, since that indicates all our RMIDs have *so* many lines tagged that it's unlikely increasing __intel_cqm_threshold any further would be a win.

Suppose all our RMIDs associated cachelines, if any RMID (say, RMID_A) has more lines tagged than the above flat distribution that means at least one RMID must have less than the above value (RMID_B), so we'd really hope for the lesser RMID to be become free sooner - we'd rather pick RMID_B than bump the threshold value and risk picking RMID_A, since the higher the threshold value, the "dirtier" we allow our RMIDs to be when we reuse them.

And very dirty RMIDs skew your monitoring results because they introduce noise into your data.

Quoted 2 lines

Should we make this 1/16th of this figure or any other random fraction < 1 ?

I don't see how that'd be better than the above, but since I introduced this code at your request, I'm not going to fight too hard.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#24 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 18 lines · Matt Fleming
Quoted 13 lines · Peter Zijlstra

On Fri, Nov 14, 2014 at 09:15:11PM +0000, Matt Fleming wrote:
+ /*

arch/x86/kernel/cpu/perf_event_intel_cqm.c static int __init intel_cqm_init(void) · line 1275

Quoted 8 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +8 -0
+	 * A reasonable upper limit on the max threshold is the number
+	 * of lines tagged per RMID if all RMIDs have the same number of
+	 * lines tagged in the LLC.
+	 *
+	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
+	 */
+	__intel_cqm_max_threshold =
+		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);

Seeing how a percentage is without unit, the 35MB figure seems pointless.

It's only an example to demonstrate that this fudge calculation makes sense on the current class of CQM-enabled hardware.

Quoted 8 lines
Quoted 2 lines

Also, why would a flat distribution be a good measure for 'empty'? I would think that would in fact constitute in use.

It's not, it's a good measure for 'full'. This is the *max* threshold. When searching for RMIDs to stabilize we'll stop searching if __intel_cqm_threshold == __intel_cqm_max_threshold, since that indicates all our RMIDs have *so* many lines tagged that it's unlikely increasing __intel_cqm_threshold any further would be a win.

Right, but we'll also consider RMIDs with less than this as fit for reuse. So we'll re-use RMIDs that are effectively full.

Our aim is to acquire an 'empty' RMID, not give up and start reusing full ones just because, right?

#25 lore raw

Re: [PATCH v4 10/11] perf/x86/intel: Perform rotation on Intel CQM RMIDs

Quoted 6 lines · Peter Zijlstra

Right, but we'll also consider RMIDs with less than this as fit for reuse. So we'll re-use RMIDs that are effectively full.

Our aim is to acquire an 'empty' RMID, not give up and start reusing full ones just because, right?

The threshold was designed so that we're guaranteed to make forward progress. If we're bumping the threshold, *none* of the RMIDs on the limbo list have an occupancy value less than the threshold value.

At that point, we've got two options,

1) Increase the threshold value and further skew the results
2) Steal another RMID and pray it's below the threshold

We actually do both currently.

Now, one thing that we don't do is traverse the entire list of active RMIDs looking for the least value one, because it's pretty expensive to do that as it incurs lots of MSR reads and writes.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
#26 lore raw

PATCH v4 11/11 perf/x86/intel: Enable conflicting event scheduling for CQM

In reply to Matt Fleming

From: Matt Fleming <[email protected]>

We can leverage the workqueue that we use for RMID rotation to support scheduling of conflicting monitoring events. Allowing events that monitor conflicting things is done at various other places in the perf subsystem, so there's precedent there.

An example of two conflicting events would be monitoring a cgroup and simultaneously monitoring a task within that cgroup.

This uses the cache_groups list as a queuing mechanism, where every event that reaches the front of the list gets the chance to be scheduled in, possibly descheduling any conflicting events that are running.

Cc Peter Zijlstra <[email protected]>
---
 arch/x86/kernel/cpu/perf_event_intel_cqm.c | 132 +++++++++++++++++++----------
 1 file changed, 86 insertions(+), 46 deletions(-)
arch/x86/kernel/cpu/perf_event_intel_cqm.c +86 -46
index df15d28c00e3..4720ba30d503 100644
@@ -510,7 +510,6 @@ static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;
 static bool intel_cqm_rmid_stabilize(bool *available)
 {
 	struct cqm_rmid_entry *entry, *tmp;
-	struct perf_event *event;
 
 	lockdep_assert_held(&cache_mutex);
 
@@ -579,19 +578,9 @@ static bool intel_cqm_rmid_stabilize(bool *available)
 
 		/*
 		 * If we have groups waiting for RMIDs, hand
-		 * them one now.
+		 * them one now provided they don't conflict.
 		 */
-		list_for_each_entry(event, &cache_groups,
-				    hw.cqm_groups_entry) {
-			if (__rmid_valid(event->hw.cqm_rmid))
-				continue;
-
-			intel_cqm_xchg_rmid(event, entry->rmid);
-			entry = NULL;
-			break;
-		}
-
-		if (!entry)
+		if (intel_cqm_sched_in_event(entry->rmid))
 			continue;
 
 		/*
@@ -606,25 +595,75 @@ static bool intel_cqm_rmid_stabilize(bool *available)
 
 /*
  * Pick a victim group and move it to the tail of the group list.
+ * @next: The first group without an RMID
  */
-static struct perf_event *
-__intel_cqm_pick_and_rotate(void)
+static void __intel_cqm_pick_and_rotate(struct perf_event *next)
 {
 	struct perf_event *rotor;
+	unsigned int rmid;
 
 	lockdep_assert_held(&cache_mutex);
-	lockdep_assert_held(&cache_lock);
 
 	rotor = list_first_entry(&cache_groups, struct perf_event,
 				 hw.cqm_groups_entry);
+
+	/*
+	 * The group at the front of the list should always have a valid
+	 * RMID. If it doesn't then no groups have RMIDs assigned and we
+	 * don't need to rotate the list.
+	 */
+	if (next == rotor)
+		return;
+
+	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
+	__put_rmid(rmid);
+
 	list_rotate_left(&cache_groups);
+}
+
+/*
+ * Deallocate the RMIDs from any events that conflict with @event, and
+ * place them on the back of the group list.
+ */
+static void intel_cqm_sched_out_events(struct perf_event *event)
+{
+	struct perf_event *group, *g;
+	unsigned int rmid;
 
-	return rotor;
+	lockdep_assert_held(&cache_mutex);
+
+	list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
+		if (group == event)
+			continue;
+
+		rmid = group->hw.cqm_rmid;
+
+		/*
+		 * Skip events that don't have a valid RMID.
+		 */
+		if (!__rmid_valid(rmid))
+			continue;
+
+		/*
+		 * No conflict? No problem! Leave the event alone.
+		 */
+		if (!__conflict_event(group, event))
+			continue;
+
+		intel_cqm_xchg_rmid(group, INVALID_RMID);
+		__put_rmid(rmid);
+
+		list_move_tail(&group->hw.cqm_groups_entry, &cache_groups);
+	}
 }
 
 /*
  * Attempt to rotate the groups and assign new RMIDs.
  *
+ * We rotate for two reasons,
+ *   1. To handle the scheduling of conflicting events
+ *   2. To recycle RMIDs
+ *
  * Rotating RMIDs is complicated because the hardware doesn't give us
  * any clues.
  *
@@ -644,9 +683,8 @@ __intel_cqm_pick_and_rotate(void)
  */
 static bool __intel_cqm_rmid_rotate(void)
 {
-	struct perf_event *group, *rotor, *start = NULL;
+	struct perf_event *group, *start = NULL;
 	unsigned int nr_needed = 0;
-	unsigned int rmid;
 	bool rotated = false;
 	bool available;
 
@@ -679,7 +717,9 @@ again:
 		goto stabilize;
 
 	/*
-	 * We have more event groups without RMIDs than available RMIDs.
+	 * We have more event groups without RMIDs than available RMIDs,
+	 * or we have event groups that conflict with the ones currently
+	 * scheduled.
 	 *
 	 * We force deallocate the rmid of the group at the head of
 	 * cache_groups. The first event group without an RMID then gets
@@ -689,15 +729,7 @@ again:
 	 * Rotate the cache_groups list so the previous head is now the
 	 * tail.
 	 */
-	rotor = __intel_cqm_pick_and_rotate();
-	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
-
-	/*
-	 * The group at the front of the list should always have a valid
-	 * RMID. If it doesn't then no groups have RMIDs assigned.
-	 */
-	if (!__rmid_valid(rmid))
-		goto stabilize;
+	__intel_cqm_pick_and_rotate(start);
 
 	/*
 	 * If the rotation is going to succeed, reduce the threshold so
@@ -705,14 +737,14 @@ again:
 	 */
 	if (__rmid_valid(intel_cqm_rotation_rmid)) {
 		intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
-		intel_cqm_rotation_rmid = INVALID_RMID;
+		intel_cqm_rotation_rmid = __get_rmid();
+
+		intel_cqm_sched_out_events(start);
 
 		if (__intel_cqm_threshold)
 			__intel_cqm_threshold--;
 	}
 
-	__put_rmid(rmid);
-
 	rotated = true;
 
 stabilize:
@@ -760,25 +792,37 @@ static void intel_cqm_rmid_rotate(struct work_struct *work)
  *
  * If we're part of a group, we use the group's RMID.
  */
-static int intel_cqm_setup_event(struct perf_event *event,
-				 struct perf_event **group)
+static void intel_cqm_setup_event(struct perf_event *event,
+				  struct perf_event **group)
 {
 	struct perf_event *iter;
+	unsigned int rmid;
+	bool conflict = false;
 
 	list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
+		rmid = iter->hw.cqm_rmid;
+
 		if (__match_event(iter, event)) {
 			/* All tasks in a group share an RMID */
-			event->hw.cqm_rmid = iter->hw.cqm_rmid;
+			event->hw.cqm_rmid = rmid;
 			*group = iter;
-			return 0;
+			return;
 		}
 
-		if (__conflict_event(iter, event))
-			return -EBUSY;
+		/*
+		 * We only care about conflicts for events that are
+		 * actually scheduled in (and hence have a valid RMID).
+		 */
+		if (__conflict_event(iter, event) && __rmid_valid(rmid))
+			conflict = true;
 	}
 
-	event->hw.cqm_rmid = __get_rmid();
-	return 0;
+	if (conflict)
+		rmid = INVALID_RMID;
+	else
+		rmid = __get_rmid();
+
+	event->hw.cqm_rmid = rmid;
 }
 
 static void intel_cqm_event_read(struct perf_event *event)
@@ -998,7 +1042,6 @@ static int intel_cqm_event_init(struct perf_event *event)
 {
 	struct perf_event *group = NULL;
 	bool rotate = false;
-	int err;
 
 	if (event->attr.type != intel_cqm_pmu.type)
 		return -ENOENT;
@@ -1024,9 +1067,7 @@ static int intel_cqm_event_init(struct perf_event *event)
 	mutex_lock(&cache_mutex);
 
 	/* Will also set rmid */
-	err = intel_cqm_setup_event(event, &group);
-	if (err)
-		goto out;
+	intel_cqm_setup_event(event, &group);
 
 	if (group) {
 		list_add_tail(&event->hw.cqm_group_entry,
@@ -1046,13 +1087,12 @@ static int intel_cqm_event_init(struct perf_event *event)
 			rotate = true;
 	}
 
-out:
 	mutex_unlock(&cache_mutex);
 
 	if (rotate)
 		schedule_delayed_work(&intel_cqm_rmid_work, 0);
 
-	return err;
+	return 0;
 }
 
 EVENT_ATTR_STR(llc_occupancy, intel_cqm_llc, "event=0x01");
Signature · 1 line
1.9.3
maintainer
#27 lore raw

Re: [PATCH 11/11] perf/x86/intel: Enable conflicting event scheduling for CQM

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool intel_cqm_rmid_stabilize(bool *available) · line 628

Quoted 5 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +5 -0
+/*
+ * Deallocate the RMIDs from any events that conflict with @event, and
+ * place them on the back of the group list.
+ */
+static void intel_cqm_sched_out_events(struct perf_event *event)

I realize this function name is already very long, but how about:

intel_cqm_sched_out_conflicting_events()

instead?

#28 lore raw

Re: [PATCH 11/11] perf/x86/intel: Enable conflicting event scheduling for CQM

Quoted 9 lines · Peter Zijlstra

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool intel_cqm_rmid_stabilize(bool *available) · line 628

Quoted 5 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +5 -0
+/*
+ * Deallocate the RMIDs from any events that conflict with @event, and
+ * place them on the back of the group list.
+ */
+static void intel_cqm_sched_out_events(struct perf_event *event)

I realize this function name is already very long, but how about:

Quoted 3 lines

intel_cqm_sched_out_conflicting_events()

instead?

Sure. I'll make the change.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
maintainer
#29 lore raw

Re: [PATCH 11/11] perf/x86/intel: Enable conflicting event scheduling for CQM

In reply to Matt Fleming
Quoted 25 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +24 -0
+/*
+ * Deallocate the RMIDs from any events that conflict with @event, and
+ * place them on the back of the group list.
+ */
+static void intel_cqm_sched_out_events(struct perf_event *event)
+{
+	struct perf_event *group, *g;
+	unsigned int rmid;
 
+	lockdep_assert_held(&cache_mutex);
+
+	list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
+		if (group == event)
+			continue;
+
+		rmid = group->hw.cqm_rmid;
+
+		/*
+		 * Skip events that don't have a valid RMID.
+		 */
+		if (!__rmid_valid(rmid))
+			continue;
+
+		/*
+		 * No conflict? No problem! Leave the event alone.

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool intel_cqm_rmid_stabilize(bool *available) · line 658

Quoted 10 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +9 -0
+		 */
+		if (!__conflict_event(group, event))
+			continue;
+
+		intel_cqm_xchg_rmid(group, INVALID_RMID);
+		__put_rmid(rmid);
+
+		list_move_tail(&group->hw.cqm_groups_entry, &cache_groups);
+	}
 }

I'm not sure about that list_move_tail() there, is wrecks the rotation order and would cause conflicting events to get less than their 'fair' share I suspect.

#30 lore raw

Re: [PATCH 11/11] perf/x86/intel: Enable conflicting event scheduling for CQM

Quoted 32 lines · Peter Zijlstra
Quoted 31 lines · Matt Fleming
arch/x86/kernel/cpu/perf_event_intel_cqm.c +30 -0
+/*
+ * Deallocate the RMIDs from any events that conflict with @event, and
+ * place them on the back of the group list.
+ */
+static void intel_cqm_sched_out_events(struct perf_event *event)
+{
+	struct perf_event *group, *g;
+	unsigned int rmid;
 
+	lockdep_assert_held(&cache_mutex);
+
+	list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
+		if (group == event)
+			continue;
+
+		rmid = group->hw.cqm_rmid;
+
+		/*
+		 * Skip events that don't have a valid RMID.
+		 */
+		if (!__rmid_valid(rmid))
+			continue;
+
+		/*
+		 * No conflict? No problem! Leave the event alone.
+		 */
+		if (!__conflict_event(group, event))
+			continue;
+
+		intel_cqm_xchg_rmid(group, INVALID_RMID);
+		__put_rmid(rmid);
Quoted 8 lines

arch/x86/kernel/cpu/perf_event_intel_cqm.c static bool intel_cqm_rmid_stabilize(bool *available) · line 658

Quoted 4 lines
arch/x86/kernel/cpu/perf_event_intel_cqm.c +3 -0
+
+		list_move_tail(&group->hw.cqm_groups_entry, &cache_groups);
+	}
 }

I'm not sure about that list_move_tail() there, is wrecks the rotation order and would cause conflicting events to get less than their 'fair' share I suspect.

Good point, this is just plain wrong.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
#31 lore raw
In reply to Matt Fleming
Quoted 10 lines · Matt Fleming

From: Matt Fleming <[email protected]>

This patch series adds a new PMU driver for the Intel Cache Monitoring hardware feature available in Intel Xeon processors, which allows monitoring of LLC occupancy on a task, group or system-wide basis.

The first few patches modify tools/perf to handle per-package counters, which necessitates discarding some values when doing per-cpu reads to avoid getting duplicate data. The rest add support for the new PMU code.

Quoted 8 lines

I've left a notoriously funky bit of code near the end of the series, the RMID rotation code, in an attempt to simplify things. Doing the rotation provides the ability to multiplex the RMIDs and basically overcome the hardware limitation, but the rest of the patches work fine without it. But there are a number of scenarios where being able to monitor more tasks than RMIDs is extremely useful.

The series is based on tip/perf/core.

Any feedback on this series?

Stephane, the original thread is here,

https://lkml.kernel.org/r/[email protected]

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center
#32 lore raw
Quoted 18 lines · Matt Fleming
Quoted 17 lines · Matt Fleming

From: Matt Fleming <[email protected]>

This patch series adds a new PMU driver for the Intel Cache Monitoring hardware feature available in Intel Xeon processors, which allows monitoring of LLC occupancy on a task, group or system-wide basis.

The first few patches modify tools/perf to handle per-package counters, which necessitates discarding some values when doing per-cpu reads to avoid getting duplicate data. The rest add support for the new PMU code.

I've left a notoriously funky bit of code near the end of the series, the RMID rotation code, in an attempt to simplify things. Doing the rotation provides the ability to multiplex the RMIDs and basically overcome the hardware limitation, but the rest of the patches work fine without it. But there are a number of scenarios where being able to monitor more tasks than RMIDs is extremely useful.

Quoted 7 lines
Quoted 1 line

The series is based on tip/perf/core.

Any feedback on this series?

Stephane, the original thread is here,

https://lkml.kernel.org/r/[email protected]

Ping.

Signature · 1 line
Matt Fleming, Intel Open Source Technology Center