xref: /openbmc/linux/arch/x86/events/rapl.c (revision 3a83e4e6)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Support Intel/AMD RAPL energy consumption counters
4  * Copyright (C) 2013 Google, Inc., Stephane Eranian
5  *
6  * Intel RAPL interface is specified in the IA-32 Manual Vol3b
7  * section 14.7.1 (September 2013)
8  *
9  * AMD RAPL interface for Fam17h is described in the public PPR:
10  * https://bugzilla.kernel.org/show_bug.cgi?id=206537
11  *
12  * RAPL provides more controls than just reporting energy consumption
13  * however here we only expose the 3 energy consumption free running
14  * counters (pp0, pkg, dram).
15  *
16  * Each of those counters increments in a power unit defined by the
17  * RAPL_POWER_UNIT MSR. On SandyBridge, this unit is 1/(2^16) Joules
18  * but it can vary.
19  *
20  * Counter to rapl events mappings:
21  *
22  *  pp0 counter: consumption of all physical cores (power plane 0)
23  * 	  event: rapl_energy_cores
24  *    perf code: 0x1
25  *
26  *  pkg counter: consumption of the whole processor package
27  *	  event: rapl_energy_pkg
28  *    perf code: 0x2
29  *
30  * dram counter: consumption of the dram domain (servers only)
31  *	  event: rapl_energy_dram
32  *    perf code: 0x3
33  *
34  * gpu counter: consumption of the builtin-gpu domain (client only)
35  *	  event: rapl_energy_gpu
36  *    perf code: 0x4
37  *
38  *  psys counter: consumption of the builtin-psys domain (client only)
39  *	  event: rapl_energy_psys
40  *    perf code: 0x5
41  *
42  * We manage those counters as free running (read-only). They may be
43  * use simultaneously by other tools, such as turbostat.
44  *
45  * The events only support system-wide mode counting. There is no
46  * sampling support because it does not make sense and is not
47  * supported by the RAPL hardware.
48  *
49  * Because we want to avoid floating-point operations in the kernel,
50  * the events are all reported in fixed point arithmetic (32.32).
51  * Tools must adjust the counts to convert them to Watts using
52  * the duration of the measurement. Tools may use a function such as
53  * ldexp(raw_count, -32);
54  */
55 
56 #define pr_fmt(fmt) "RAPL PMU: " fmt
57 
58 #include <linux/module.h>
59 #include <linux/slab.h>
60 #include <linux/perf_event.h>
61 #include <linux/nospec.h>
62 #include <asm/cpu_device_id.h>
63 #include <asm/intel-family.h>
64 #include "perf_event.h"
65 #include "probe.h"
66 
67 MODULE_LICENSE("GPL");
68 
69 /*
70  * RAPL energy status counters
71  */
72 enum perf_rapl_events {
73 	PERF_RAPL_PP0 = 0,		/* all cores */
74 	PERF_RAPL_PKG,			/* entire package */
75 	PERF_RAPL_RAM,			/* DRAM */
76 	PERF_RAPL_PP1,			/* gpu */
77 	PERF_RAPL_PSYS,			/* psys */
78 
79 	PERF_RAPL_MAX,
80 	NR_RAPL_DOMAINS = PERF_RAPL_MAX,
81 };
82 
83 static const char *const rapl_domain_names[NR_RAPL_DOMAINS] __initconst = {
84 	"pp0-core",
85 	"package",
86 	"dram",
87 	"pp1-gpu",
88 	"psys",
89 };
90 
91 /*
92  * event code: LSB 8 bits, passed in attr->config
93  * any other bit is reserved
94  */
95 #define RAPL_EVENT_MASK	0xFFULL
96 
97 #define DEFINE_RAPL_FORMAT_ATTR(_var, _name, _format)		\
98 static ssize_t __rapl_##_var##_show(struct kobject *kobj,	\
99 				struct kobj_attribute *attr,	\
100 				char *page)			\
101 {								\
102 	BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE);		\
103 	return sprintf(page, _format "\n");			\
104 }								\
105 static struct kobj_attribute format_attr_##_var =		\
106 	__ATTR(_name, 0444, __rapl_##_var##_show, NULL)
107 
108 #define RAPL_CNTR_WIDTH 32
109 
110 #define RAPL_EVENT_ATTR_STR(_name, v, str)					\
111 static struct perf_pmu_events_attr event_attr_##v = {				\
112 	.attr		= __ATTR(_name, 0444, perf_event_sysfs_show, NULL),	\
113 	.id		= 0,							\
114 	.event_str	= str,							\
115 };
116 
117 struct rapl_pmu {
118 	raw_spinlock_t		lock;
119 	int			n_active;
120 	int			cpu;
121 	struct list_head	active_list;
122 	struct pmu		*pmu;
123 	ktime_t			timer_interval;
124 	struct hrtimer		hrtimer;
125 };
126 
127 struct rapl_pmus {
128 	struct pmu		pmu;
129 	unsigned int		maxdie;
130 	struct rapl_pmu		*pmus[];
131 };
132 
133 enum rapl_unit_quirk {
134 	RAPL_UNIT_QUIRK_NONE,
135 	RAPL_UNIT_QUIRK_INTEL_HSW,
136 	RAPL_UNIT_QUIRK_INTEL_SPR,
137 };
138 
139 struct rapl_model {
140 	struct perf_msr *rapl_msrs;
141 	unsigned long	events;
142 	unsigned int	msr_power_unit;
143 	enum rapl_unit_quirk	unit_quirk;
144 };
145 
146  /* 1/2^hw_unit Joule */
147 static int rapl_hw_unit[NR_RAPL_DOMAINS] __read_mostly;
148 static struct rapl_pmus *rapl_pmus;
149 static cpumask_t rapl_cpu_mask;
150 static unsigned int rapl_cntr_mask;
151 static u64 rapl_timer_ms;
152 static struct perf_msr *rapl_msrs;
153 
154 static inline struct rapl_pmu *cpu_to_rapl_pmu(unsigned int cpu)
155 {
156 	unsigned int dieid = topology_logical_die_id(cpu);
157 
158 	/*
159 	 * The unsigned check also catches the '-1' return value for non
160 	 * existent mappings in the topology map.
161 	 */
162 	return dieid < rapl_pmus->maxdie ? rapl_pmus->pmus[dieid] : NULL;
163 }
164 
165 static inline u64 rapl_read_counter(struct perf_event *event)
166 {
167 	u64 raw;
168 	rdmsrl(event->hw.event_base, raw);
169 	return raw;
170 }
171 
172 static inline u64 rapl_scale(u64 v, int cfg)
173 {
174 	if (cfg > NR_RAPL_DOMAINS) {
175 		pr_warn("Invalid domain %d, failed to scale data\n", cfg);
176 		return v;
177 	}
178 	/*
179 	 * scale delta to smallest unit (1/2^32)
180 	 * users must then scale back: count * 1/(1e9*2^32) to get Joules
181 	 * or use ldexp(count, -32).
182 	 * Watts = Joules/Time delta
183 	 */
184 	return v << (32 - rapl_hw_unit[cfg - 1]);
185 }
186 
187 static u64 rapl_event_update(struct perf_event *event)
188 {
189 	struct hw_perf_event *hwc = &event->hw;
190 	u64 prev_raw_count, new_raw_count;
191 	s64 delta, sdelta;
192 	int shift = RAPL_CNTR_WIDTH;
193 
194 again:
195 	prev_raw_count = local64_read(&hwc->prev_count);
196 	rdmsrl(event->hw.event_base, new_raw_count);
197 
198 	if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
199 			    new_raw_count) != prev_raw_count) {
200 		cpu_relax();
201 		goto again;
202 	}
203 
204 	/*
205 	 * Now we have the new raw value and have updated the prev
206 	 * timestamp already. We can now calculate the elapsed delta
207 	 * (event-)time and add that to the generic event.
208 	 *
209 	 * Careful, not all hw sign-extends above the physical width
210 	 * of the count.
211 	 */
212 	delta = (new_raw_count << shift) - (prev_raw_count << shift);
213 	delta >>= shift;
214 
215 	sdelta = rapl_scale(delta, event->hw.config);
216 
217 	local64_add(sdelta, &event->count);
218 
219 	return new_raw_count;
220 }
221 
222 static void rapl_start_hrtimer(struct rapl_pmu *pmu)
223 {
224        hrtimer_start(&pmu->hrtimer, pmu->timer_interval,
225 		     HRTIMER_MODE_REL_PINNED);
226 }
227 
228 static enum hrtimer_restart rapl_hrtimer_handle(struct hrtimer *hrtimer)
229 {
230 	struct rapl_pmu *pmu = container_of(hrtimer, struct rapl_pmu, hrtimer);
231 	struct perf_event *event;
232 	unsigned long flags;
233 
234 	if (!pmu->n_active)
235 		return HRTIMER_NORESTART;
236 
237 	raw_spin_lock_irqsave(&pmu->lock, flags);
238 
239 	list_for_each_entry(event, &pmu->active_list, active_entry)
240 		rapl_event_update(event);
241 
242 	raw_spin_unlock_irqrestore(&pmu->lock, flags);
243 
244 	hrtimer_forward_now(hrtimer, pmu->timer_interval);
245 
246 	return HRTIMER_RESTART;
247 }
248 
249 static void rapl_hrtimer_init(struct rapl_pmu *pmu)
250 {
251 	struct hrtimer *hr = &pmu->hrtimer;
252 
253 	hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
254 	hr->function = rapl_hrtimer_handle;
255 }
256 
257 static void __rapl_pmu_event_start(struct rapl_pmu *pmu,
258 				   struct perf_event *event)
259 {
260 	if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
261 		return;
262 
263 	event->hw.state = 0;
264 
265 	list_add_tail(&event->active_entry, &pmu->active_list);
266 
267 	local64_set(&event->hw.prev_count, rapl_read_counter(event));
268 
269 	pmu->n_active++;
270 	if (pmu->n_active == 1)
271 		rapl_start_hrtimer(pmu);
272 }
273 
274 static void rapl_pmu_event_start(struct perf_event *event, int mode)
275 {
276 	struct rapl_pmu *pmu = event->pmu_private;
277 	unsigned long flags;
278 
279 	raw_spin_lock_irqsave(&pmu->lock, flags);
280 	__rapl_pmu_event_start(pmu, event);
281 	raw_spin_unlock_irqrestore(&pmu->lock, flags);
282 }
283 
284 static void rapl_pmu_event_stop(struct perf_event *event, int mode)
285 {
286 	struct rapl_pmu *pmu = event->pmu_private;
287 	struct hw_perf_event *hwc = &event->hw;
288 	unsigned long flags;
289 
290 	raw_spin_lock_irqsave(&pmu->lock, flags);
291 
292 	/* mark event as deactivated and stopped */
293 	if (!(hwc->state & PERF_HES_STOPPED)) {
294 		WARN_ON_ONCE(pmu->n_active <= 0);
295 		pmu->n_active--;
296 		if (pmu->n_active == 0)
297 			hrtimer_cancel(&pmu->hrtimer);
298 
299 		list_del(&event->active_entry);
300 
301 		WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
302 		hwc->state |= PERF_HES_STOPPED;
303 	}
304 
305 	/* check if update of sw counter is necessary */
306 	if ((mode & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
307 		/*
308 		 * Drain the remaining delta count out of a event
309 		 * that we are disabling:
310 		 */
311 		rapl_event_update(event);
312 		hwc->state |= PERF_HES_UPTODATE;
313 	}
314 
315 	raw_spin_unlock_irqrestore(&pmu->lock, flags);
316 }
317 
318 static int rapl_pmu_event_add(struct perf_event *event, int mode)
319 {
320 	struct rapl_pmu *pmu = event->pmu_private;
321 	struct hw_perf_event *hwc = &event->hw;
322 	unsigned long flags;
323 
324 	raw_spin_lock_irqsave(&pmu->lock, flags);
325 
326 	hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
327 
328 	if (mode & PERF_EF_START)
329 		__rapl_pmu_event_start(pmu, event);
330 
331 	raw_spin_unlock_irqrestore(&pmu->lock, flags);
332 
333 	return 0;
334 }
335 
336 static void rapl_pmu_event_del(struct perf_event *event, int flags)
337 {
338 	rapl_pmu_event_stop(event, PERF_EF_UPDATE);
339 }
340 
341 static int rapl_pmu_event_init(struct perf_event *event)
342 {
343 	u64 cfg = event->attr.config & RAPL_EVENT_MASK;
344 	int bit, ret = 0;
345 	struct rapl_pmu *pmu;
346 
347 	/* only look at RAPL events */
348 	if (event->attr.type != rapl_pmus->pmu.type)
349 		return -ENOENT;
350 
351 	/* check only supported bits are set */
352 	if (event->attr.config & ~RAPL_EVENT_MASK)
353 		return -EINVAL;
354 
355 	if (event->cpu < 0)
356 		return -EINVAL;
357 
358 	event->event_caps |= PERF_EV_CAP_READ_ACTIVE_PKG;
359 
360 	if (!cfg || cfg >= NR_RAPL_DOMAINS + 1)
361 		return -EINVAL;
362 
363 	cfg = array_index_nospec((long)cfg, NR_RAPL_DOMAINS + 1);
364 	bit = cfg - 1;
365 
366 	/* check event supported */
367 	if (!(rapl_cntr_mask & (1 << bit)))
368 		return -EINVAL;
369 
370 	/* unsupported modes and filters */
371 	if (event->attr.sample_period) /* no sampling */
372 		return -EINVAL;
373 
374 	/* must be done before validate_group */
375 	pmu = cpu_to_rapl_pmu(event->cpu);
376 	if (!pmu)
377 		return -EINVAL;
378 	event->cpu = pmu->cpu;
379 	event->pmu_private = pmu;
380 	event->hw.event_base = rapl_msrs[bit].msr;
381 	event->hw.config = cfg;
382 	event->hw.idx = bit;
383 
384 	return ret;
385 }
386 
387 static void rapl_pmu_event_read(struct perf_event *event)
388 {
389 	rapl_event_update(event);
390 }
391 
392 static ssize_t rapl_get_attr_cpumask(struct device *dev,
393 				struct device_attribute *attr, char *buf)
394 {
395 	return cpumap_print_to_pagebuf(true, buf, &rapl_cpu_mask);
396 }
397 
398 static DEVICE_ATTR(cpumask, S_IRUGO, rapl_get_attr_cpumask, NULL);
399 
400 static struct attribute *rapl_pmu_attrs[] = {
401 	&dev_attr_cpumask.attr,
402 	NULL,
403 };
404 
405 static struct attribute_group rapl_pmu_attr_group = {
406 	.attrs = rapl_pmu_attrs,
407 };
408 
409 RAPL_EVENT_ATTR_STR(energy-cores, rapl_cores, "event=0x01");
410 RAPL_EVENT_ATTR_STR(energy-pkg  ,   rapl_pkg, "event=0x02");
411 RAPL_EVENT_ATTR_STR(energy-ram  ,   rapl_ram, "event=0x03");
412 RAPL_EVENT_ATTR_STR(energy-gpu  ,   rapl_gpu, "event=0x04");
413 RAPL_EVENT_ATTR_STR(energy-psys,   rapl_psys, "event=0x05");
414 
415 RAPL_EVENT_ATTR_STR(energy-cores.unit, rapl_cores_unit, "Joules");
416 RAPL_EVENT_ATTR_STR(energy-pkg.unit  ,   rapl_pkg_unit, "Joules");
417 RAPL_EVENT_ATTR_STR(energy-ram.unit  ,   rapl_ram_unit, "Joules");
418 RAPL_EVENT_ATTR_STR(energy-gpu.unit  ,   rapl_gpu_unit, "Joules");
419 RAPL_EVENT_ATTR_STR(energy-psys.unit,   rapl_psys_unit, "Joules");
420 
421 /*
422  * we compute in 0.23 nJ increments regardless of MSR
423  */
424 RAPL_EVENT_ATTR_STR(energy-cores.scale, rapl_cores_scale, "2.3283064365386962890625e-10");
425 RAPL_EVENT_ATTR_STR(energy-pkg.scale,     rapl_pkg_scale, "2.3283064365386962890625e-10");
426 RAPL_EVENT_ATTR_STR(energy-ram.scale,     rapl_ram_scale, "2.3283064365386962890625e-10");
427 RAPL_EVENT_ATTR_STR(energy-gpu.scale,     rapl_gpu_scale, "2.3283064365386962890625e-10");
428 RAPL_EVENT_ATTR_STR(energy-psys.scale,   rapl_psys_scale, "2.3283064365386962890625e-10");
429 
430 /*
431  * There are no default events, but we need to create
432  * "events" group (with empty attrs) before updating
433  * it with detected events.
434  */
435 static struct attribute *attrs_empty[] = {
436 	NULL,
437 };
438 
439 static struct attribute_group rapl_pmu_events_group = {
440 	.name = "events",
441 	.attrs = attrs_empty,
442 };
443 
444 DEFINE_RAPL_FORMAT_ATTR(event, event, "config:0-7");
445 static struct attribute *rapl_formats_attr[] = {
446 	&format_attr_event.attr,
447 	NULL,
448 };
449 
450 static struct attribute_group rapl_pmu_format_group = {
451 	.name = "format",
452 	.attrs = rapl_formats_attr,
453 };
454 
455 static const struct attribute_group *rapl_attr_groups[] = {
456 	&rapl_pmu_attr_group,
457 	&rapl_pmu_format_group,
458 	&rapl_pmu_events_group,
459 	NULL,
460 };
461 
462 static struct attribute *rapl_events_cores[] = {
463 	EVENT_PTR(rapl_cores),
464 	EVENT_PTR(rapl_cores_unit),
465 	EVENT_PTR(rapl_cores_scale),
466 	NULL,
467 };
468 
469 static umode_t
470 rapl_not_visible(struct kobject *kobj, struct attribute *attr, int i)
471 {
472 	return 0;
473 }
474 
475 static struct attribute_group rapl_events_cores_group = {
476 	.name  = "events",
477 	.attrs = rapl_events_cores,
478 	.is_visible = rapl_not_visible,
479 };
480 
481 static struct attribute *rapl_events_pkg[] = {
482 	EVENT_PTR(rapl_pkg),
483 	EVENT_PTR(rapl_pkg_unit),
484 	EVENT_PTR(rapl_pkg_scale),
485 	NULL,
486 };
487 
488 static struct attribute_group rapl_events_pkg_group = {
489 	.name  = "events",
490 	.attrs = rapl_events_pkg,
491 	.is_visible = rapl_not_visible,
492 };
493 
494 static struct attribute *rapl_events_ram[] = {
495 	EVENT_PTR(rapl_ram),
496 	EVENT_PTR(rapl_ram_unit),
497 	EVENT_PTR(rapl_ram_scale),
498 	NULL,
499 };
500 
501 static struct attribute_group rapl_events_ram_group = {
502 	.name  = "events",
503 	.attrs = rapl_events_ram,
504 	.is_visible = rapl_not_visible,
505 };
506 
507 static struct attribute *rapl_events_gpu[] = {
508 	EVENT_PTR(rapl_gpu),
509 	EVENT_PTR(rapl_gpu_unit),
510 	EVENT_PTR(rapl_gpu_scale),
511 	NULL,
512 };
513 
514 static struct attribute_group rapl_events_gpu_group = {
515 	.name  = "events",
516 	.attrs = rapl_events_gpu,
517 	.is_visible = rapl_not_visible,
518 };
519 
520 static struct attribute *rapl_events_psys[] = {
521 	EVENT_PTR(rapl_psys),
522 	EVENT_PTR(rapl_psys_unit),
523 	EVENT_PTR(rapl_psys_scale),
524 	NULL,
525 };
526 
527 static struct attribute_group rapl_events_psys_group = {
528 	.name  = "events",
529 	.attrs = rapl_events_psys,
530 	.is_visible = rapl_not_visible,
531 };
532 
533 static bool test_msr(int idx, void *data)
534 {
535 	return test_bit(idx, (unsigned long *) data);
536 }
537 
538 static struct perf_msr intel_rapl_msrs[] = {
539 	[PERF_RAPL_PP0]  = { MSR_PP0_ENERGY_STATUS,      &rapl_events_cores_group, test_msr },
540 	[PERF_RAPL_PKG]  = { MSR_PKG_ENERGY_STATUS,      &rapl_events_pkg_group,   test_msr },
541 	[PERF_RAPL_RAM]  = { MSR_DRAM_ENERGY_STATUS,     &rapl_events_ram_group,   test_msr },
542 	[PERF_RAPL_PP1]  = { MSR_PP1_ENERGY_STATUS,      &rapl_events_gpu_group,   test_msr },
543 	[PERF_RAPL_PSYS] = { MSR_PLATFORM_ENERGY_STATUS, &rapl_events_psys_group,  test_msr },
544 };
545 
546 /*
547  * Force to PERF_RAPL_MAX size due to:
548  * - perf_msr_probe(PERF_RAPL_MAX)
549  * - want to use same event codes across both architectures
550  */
551 static struct perf_msr amd_rapl_msrs[PERF_RAPL_MAX] = {
552 	[PERF_RAPL_PKG]  = { MSR_AMD_PKG_ENERGY_STATUS,  &rapl_events_pkg_group,   test_msr },
553 };
554 
555 
556 static int rapl_cpu_offline(unsigned int cpu)
557 {
558 	struct rapl_pmu *pmu = cpu_to_rapl_pmu(cpu);
559 	int target;
560 
561 	/* Check if exiting cpu is used for collecting rapl events */
562 	if (!cpumask_test_and_clear_cpu(cpu, &rapl_cpu_mask))
563 		return 0;
564 
565 	pmu->cpu = -1;
566 	/* Find a new cpu to collect rapl events */
567 	target = cpumask_any_but(topology_die_cpumask(cpu), cpu);
568 
569 	/* Migrate rapl events to the new target */
570 	if (target < nr_cpu_ids) {
571 		cpumask_set_cpu(target, &rapl_cpu_mask);
572 		pmu->cpu = target;
573 		perf_pmu_migrate_context(pmu->pmu, cpu, target);
574 	}
575 	return 0;
576 }
577 
578 static int rapl_cpu_online(unsigned int cpu)
579 {
580 	struct rapl_pmu *pmu = cpu_to_rapl_pmu(cpu);
581 	int target;
582 
583 	if (!pmu) {
584 		pmu = kzalloc_node(sizeof(*pmu), GFP_KERNEL, cpu_to_node(cpu));
585 		if (!pmu)
586 			return -ENOMEM;
587 
588 		raw_spin_lock_init(&pmu->lock);
589 		INIT_LIST_HEAD(&pmu->active_list);
590 		pmu->pmu = &rapl_pmus->pmu;
591 		pmu->timer_interval = ms_to_ktime(rapl_timer_ms);
592 		rapl_hrtimer_init(pmu);
593 
594 		rapl_pmus->pmus[topology_logical_die_id(cpu)] = pmu;
595 	}
596 
597 	/*
598 	 * Check if there is an online cpu in the package which collects rapl
599 	 * events already.
600 	 */
601 	target = cpumask_any_and(&rapl_cpu_mask, topology_die_cpumask(cpu));
602 	if (target < nr_cpu_ids)
603 		return 0;
604 
605 	cpumask_set_cpu(cpu, &rapl_cpu_mask);
606 	pmu->cpu = cpu;
607 	return 0;
608 }
609 
610 static int rapl_check_hw_unit(struct rapl_model *rm)
611 {
612 	u64 msr_rapl_power_unit_bits;
613 	int i;
614 
615 	/* protect rdmsrl() to handle virtualization */
616 	if (rdmsrl_safe(rm->msr_power_unit, &msr_rapl_power_unit_bits))
617 		return -1;
618 	for (i = 0; i < NR_RAPL_DOMAINS; i++)
619 		rapl_hw_unit[i] = (msr_rapl_power_unit_bits >> 8) & 0x1FULL;
620 
621 	switch (rm->unit_quirk) {
622 	/*
623 	 * DRAM domain on HSW server and KNL has fixed energy unit which can be
624 	 * different than the unit from power unit MSR. See
625 	 * "Intel Xeon Processor E5-1600 and E5-2600 v3 Product Families, V2
626 	 * of 2. Datasheet, September 2014, Reference Number: 330784-001 "
627 	 */
628 	case RAPL_UNIT_QUIRK_INTEL_HSW:
629 		rapl_hw_unit[PERF_RAPL_RAM] = 16;
630 		break;
631 	/*
632 	 * SPR shares the same DRAM domain energy unit as HSW, plus it
633 	 * also has a fixed energy unit for Psys domain.
634 	 */
635 	case RAPL_UNIT_QUIRK_INTEL_SPR:
636 		rapl_hw_unit[PERF_RAPL_RAM] = 16;
637 		rapl_hw_unit[PERF_RAPL_PSYS] = 0;
638 		break;
639 	default:
640 		break;
641 	}
642 
643 
644 	/*
645 	 * Calculate the timer rate:
646 	 * Use reference of 200W for scaling the timeout to avoid counter
647 	 * overflows. 200W = 200 Joules/sec
648 	 * Divide interval by 2 to avoid lockstep (2 * 100)
649 	 * if hw unit is 32, then we use 2 ms 1/200/2
650 	 */
651 	rapl_timer_ms = 2;
652 	if (rapl_hw_unit[0] < 32) {
653 		rapl_timer_ms = (1000 / (2 * 100));
654 		rapl_timer_ms *= (1ULL << (32 - rapl_hw_unit[0] - 1));
655 	}
656 	return 0;
657 }
658 
659 static void __init rapl_advertise(void)
660 {
661 	int i;
662 
663 	pr_info("API unit is 2^-32 Joules, %d fixed counters, %llu ms ovfl timer\n",
664 		hweight32(rapl_cntr_mask), rapl_timer_ms);
665 
666 	for (i = 0; i < NR_RAPL_DOMAINS; i++) {
667 		if (rapl_cntr_mask & (1 << i)) {
668 			pr_info("hw unit of domain %s 2^-%d Joules\n",
669 				rapl_domain_names[i], rapl_hw_unit[i]);
670 		}
671 	}
672 }
673 
674 static void cleanup_rapl_pmus(void)
675 {
676 	int i;
677 
678 	for (i = 0; i < rapl_pmus->maxdie; i++)
679 		kfree(rapl_pmus->pmus[i]);
680 	kfree(rapl_pmus);
681 }
682 
683 static const struct attribute_group *rapl_attr_update[] = {
684 	&rapl_events_cores_group,
685 	&rapl_events_pkg_group,
686 	&rapl_events_ram_group,
687 	&rapl_events_gpu_group,
688 	&rapl_events_psys_group,
689 	NULL,
690 };
691 
692 static int __init init_rapl_pmus(void)
693 {
694 	int maxdie = topology_max_packages() * topology_max_die_per_package();
695 	size_t size;
696 
697 	size = sizeof(*rapl_pmus) + maxdie * sizeof(struct rapl_pmu *);
698 	rapl_pmus = kzalloc(size, GFP_KERNEL);
699 	if (!rapl_pmus)
700 		return -ENOMEM;
701 
702 	rapl_pmus->maxdie		= maxdie;
703 	rapl_pmus->pmu.attr_groups	= rapl_attr_groups;
704 	rapl_pmus->pmu.attr_update	= rapl_attr_update;
705 	rapl_pmus->pmu.task_ctx_nr	= perf_invalid_context;
706 	rapl_pmus->pmu.event_init	= rapl_pmu_event_init;
707 	rapl_pmus->pmu.add		= rapl_pmu_event_add;
708 	rapl_pmus->pmu.del		= rapl_pmu_event_del;
709 	rapl_pmus->pmu.start		= rapl_pmu_event_start;
710 	rapl_pmus->pmu.stop		= rapl_pmu_event_stop;
711 	rapl_pmus->pmu.read		= rapl_pmu_event_read;
712 	rapl_pmus->pmu.module		= THIS_MODULE;
713 	rapl_pmus->pmu.capabilities	= PERF_PMU_CAP_NO_EXCLUDE;
714 	return 0;
715 }
716 
717 static struct rapl_model model_snb = {
718 	.events		= BIT(PERF_RAPL_PP0) |
719 			  BIT(PERF_RAPL_PKG) |
720 			  BIT(PERF_RAPL_PP1),
721 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
722 	.rapl_msrs      = intel_rapl_msrs,
723 };
724 
725 static struct rapl_model model_snbep = {
726 	.events		= BIT(PERF_RAPL_PP0) |
727 			  BIT(PERF_RAPL_PKG) |
728 			  BIT(PERF_RAPL_RAM),
729 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
730 	.rapl_msrs      = intel_rapl_msrs,
731 };
732 
733 static struct rapl_model model_hsw = {
734 	.events		= BIT(PERF_RAPL_PP0) |
735 			  BIT(PERF_RAPL_PKG) |
736 			  BIT(PERF_RAPL_RAM) |
737 			  BIT(PERF_RAPL_PP1),
738 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
739 	.rapl_msrs      = intel_rapl_msrs,
740 };
741 
742 static struct rapl_model model_hsx = {
743 	.events		= BIT(PERF_RAPL_PP0) |
744 			  BIT(PERF_RAPL_PKG) |
745 			  BIT(PERF_RAPL_RAM),
746 	.unit_quirk	= RAPL_UNIT_QUIRK_INTEL_HSW,
747 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
748 	.rapl_msrs      = intel_rapl_msrs,
749 };
750 
751 static struct rapl_model model_knl = {
752 	.events		= BIT(PERF_RAPL_PKG) |
753 			  BIT(PERF_RAPL_RAM),
754 	.unit_quirk	= RAPL_UNIT_QUIRK_INTEL_HSW,
755 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
756 	.rapl_msrs      = intel_rapl_msrs,
757 };
758 
759 static struct rapl_model model_skl = {
760 	.events		= BIT(PERF_RAPL_PP0) |
761 			  BIT(PERF_RAPL_PKG) |
762 			  BIT(PERF_RAPL_RAM) |
763 			  BIT(PERF_RAPL_PP1) |
764 			  BIT(PERF_RAPL_PSYS),
765 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
766 	.rapl_msrs      = intel_rapl_msrs,
767 };
768 
769 static struct rapl_model model_spr = {
770 	.events		= BIT(PERF_RAPL_PP0) |
771 			  BIT(PERF_RAPL_PKG) |
772 			  BIT(PERF_RAPL_RAM) |
773 			  BIT(PERF_RAPL_PSYS),
774 	.unit_quirk	= RAPL_UNIT_QUIRK_INTEL_SPR,
775 	.msr_power_unit = MSR_RAPL_POWER_UNIT,
776 	.rapl_msrs      = intel_rapl_msrs,
777 };
778 
779 static struct rapl_model model_amd_fam17h = {
780 	.events		= BIT(PERF_RAPL_PKG),
781 	.msr_power_unit = MSR_AMD_RAPL_POWER_UNIT,
782 	.rapl_msrs      = amd_rapl_msrs,
783 };
784 
785 static const struct x86_cpu_id rapl_model_match[] __initconst = {
786 	X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE,		&model_snb),
787 	X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE_X,	&model_snbep),
788 	X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE,		&model_snb),
789 	X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE_X,		&model_snbep),
790 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL,		&model_hsw),
791 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X,		&model_hsx),
792 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_L,		&model_hsw),
793 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_G,		&model_hsw),
794 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL,		&model_hsw),
795 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_G,		&model_hsw),
796 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X,		&model_hsx),
797 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_D,		&model_hsx),
798 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNL,	&model_knl),
799 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNM,	&model_knl),
800 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_L,		&model_skl),
801 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE,		&model_skl),
802 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_X,		&model_hsx),
803 	X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE_L,		&model_skl),
804 	X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE,		&model_skl),
805 	X86_MATCH_INTEL_FAM6_MODEL(CANNONLAKE_L,	&model_skl),
806 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT,	&model_hsw),
807 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_D,	&model_hsw),
808 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_PLUS,	&model_hsw),
809 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_L,		&model_skl),
810 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE,		&model_skl),
811 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D,		&model_hsx),
812 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X,		&model_hsx),
813 	X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE_L,		&model_skl),
814 	X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE,		&model_skl),
815 	X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X,	&model_spr),
816 	X86_MATCH_VENDOR_FAM(AMD,	0x17,		&model_amd_fam17h),
817 	X86_MATCH_VENDOR_FAM(HYGON,	0x18,		&model_amd_fam17h),
818 	{},
819 };
820 MODULE_DEVICE_TABLE(x86cpu, rapl_model_match);
821 
822 static int __init rapl_pmu_init(void)
823 {
824 	const struct x86_cpu_id *id;
825 	struct rapl_model *rm;
826 	int ret;
827 
828 	id = x86_match_cpu(rapl_model_match);
829 	if (!id)
830 		return -ENODEV;
831 
832 	rm = (struct rapl_model *) id->driver_data;
833 
834 	rapl_msrs = rm->rapl_msrs;
835 
836 	rapl_cntr_mask = perf_msr_probe(rapl_msrs, PERF_RAPL_MAX,
837 					false, (void *) &rm->events);
838 
839 	ret = rapl_check_hw_unit(rm);
840 	if (ret)
841 		return ret;
842 
843 	ret = init_rapl_pmus();
844 	if (ret)
845 		return ret;
846 
847 	/*
848 	 * Install callbacks. Core will call them for each online cpu.
849 	 */
850 	ret = cpuhp_setup_state(CPUHP_AP_PERF_X86_RAPL_ONLINE,
851 				"perf/x86/rapl:online",
852 				rapl_cpu_online, rapl_cpu_offline);
853 	if (ret)
854 		goto out;
855 
856 	ret = perf_pmu_register(&rapl_pmus->pmu, "power", -1);
857 	if (ret)
858 		goto out1;
859 
860 	rapl_advertise();
861 	return 0;
862 
863 out1:
864 	cpuhp_remove_state(CPUHP_AP_PERF_X86_RAPL_ONLINE);
865 out:
866 	pr_warn("Initialization failed (%d), disabled\n", ret);
867 	cleanup_rapl_pmus();
868 	return ret;
869 }
870 module_init(rapl_pmu_init);
871 
872 static void __exit intel_rapl_exit(void)
873 {
874 	cpuhp_remove_state_nocalls(CPUHP_AP_PERF_X86_RAPL_ONLINE);
875 	perf_pmu_unregister(&rapl_pmus->pmu);
876 	cleanup_rapl_pmus();
877 }
878 module_exit(intel_rapl_exit);
879