]> git.karo-electronics.de Git - linux-beck.git/blob - arch/x86/kernel/cpu/perf_event_intel_rapl.c
bf8e4a736d48ee00e75abd1586673571a56ae903
[linux-beck.git] / arch / x86 / kernel / cpu / perf_event_intel_rapl.c
1 /*
2  * perf_event_intel_rapl.c: support Intel RAPL energy consumption counters
3  * Copyright (C) 2013 Google, Inc., Stephane Eranian
4  *
5  * Intel RAPL interface is specified in the IA-32 Manual Vol3b
6  * section 14.7.1 (September 2013)
7  *
8  * RAPL provides more controls than just reporting energy consumption
9  * however here we only expose the 3 energy consumption free running
10  * counters (pp0, pkg, dram).
11  *
12  * Each of those counters increments in a power unit defined by the
13  * RAPL_POWER_UNIT MSR. On SandyBridge, this unit is 1/(2^16) Joules
14  * but it can vary.
15  *
16  * Counter to rapl events mappings:
17  *
18  *  pp0 counter: consumption of all physical cores (power plane 0)
19  *        event: rapl_energy_cores
20  *    perf code: 0x1
21  *
22  *  pkg counter: consumption of the whole processor package
23  *        event: rapl_energy_pkg
24  *    perf code: 0x2
25  *
26  * dram counter: consumption of the dram domain (servers only)
27  *        event: rapl_energy_dram
28  *    perf code: 0x3
29  *
30  * We manage those counters as free running (read-only). They may be
31  * use simultaneously by other tools, such as turbostat.
32  *
33  * The events only support system-wide mode counting. There is no
34  * sampling support because it does not make sense and is not
35  * supported by the RAPL hardware.
36  *
37  * Because we want to avoid floating-point operations in the kernel,
38  * the events are all reported in fixed point arithmetic (32.32).
39  * Tools must adjust the counts to convert them to Watts using
40  * the duration of the measurement. Tools may use a function such as
41  * ldexp(raw_count, -32);
42  */
43 #include <linux/module.h>
44 #include <linux/slab.h>
45 #include <linux/perf_event.h>
46 #include <asm/cpu_device_id.h>
47 #include "perf_event.h"
48
49 /*
50  * RAPL energy status counters
51  */
52 #define RAPL_IDX_PP0_NRG_STAT   0       /* all cores */
53 #define INTEL_RAPL_PP0          0x1     /* pseudo-encoding */
54 #define RAPL_IDX_PKG_NRG_STAT   1       /* entire package */
55 #define INTEL_RAPL_PKG          0x2     /* pseudo-encoding */
56 #define RAPL_IDX_RAM_NRG_STAT   2       /* DRAM */
57 #define INTEL_RAPL_RAM          0x3     /* pseudo-encoding */
58
59 /* Clients have PP0, PKG */
60 #define RAPL_IDX_CLN    (1<<RAPL_IDX_PP0_NRG_STAT|\
61                          1<<RAPL_IDX_PKG_NRG_STAT)
62
63 /* Servers have PP0, PKG, RAM */
64 #define RAPL_IDX_SRV    (1<<RAPL_IDX_PP0_NRG_STAT|\
65                          1<<RAPL_IDX_PKG_NRG_STAT|\
66                          1<<RAPL_IDX_RAM_NRG_STAT)
67
68 /*
69  * event code: LSB 8 bits, passed in attr->config
70  * any other bit is reserved
71  */
72 #define RAPL_EVENT_MASK 0xFFULL
73
74 #define DEFINE_RAPL_FORMAT_ATTR(_var, _name, _format)           \
75 static ssize_t __rapl_##_var##_show(struct kobject *kobj,       \
76                                 struct kobj_attribute *attr,    \
77                                 char *page)                     \
78 {                                                               \
79         BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE);             \
80         return sprintf(page, _format "\n");                     \
81 }                                                               \
82 static struct kobj_attribute format_attr_##_var =               \
83         __ATTR(_name, 0444, __rapl_##_var##_show, NULL)
84
85 #define RAPL_EVENT_DESC(_name, _config)                         \
86 {                                                               \
87         .attr   = __ATTR(_name, 0444, rapl_event_show, NULL),   \
88         .config = _config,                                      \
89 }
90
91 #define RAPL_CNTR_WIDTH 32 /* 32-bit rapl counters */
92
93 struct rapl_pmu {
94         spinlock_t       lock;
95         int              hw_unit;  /* 1/2^hw_unit Joule */
96         int              n_active; /* number of active events */
97         struct list_head active_list;
98         struct pmu       *pmu; /* pointer to rapl_pmu_class */
99         ktime_t          timer_interval; /* in ktime_t unit */
100         struct hrtimer   hrtimer;
101 };
102
103 static struct pmu rapl_pmu_class;
104 static cpumask_t rapl_cpu_mask;
105 static int rapl_cntr_mask;
106
107 static DEFINE_PER_CPU(struct rapl_pmu *, rapl_pmu);
108 static DEFINE_PER_CPU(struct rapl_pmu *, rapl_pmu_to_free);
109
110 static inline u64 rapl_read_counter(struct perf_event *event)
111 {
112         u64 raw;
113         rdmsrl(event->hw.event_base, raw);
114         return raw;
115 }
116
117 static inline u64 rapl_scale(u64 v)
118 {
119         /*
120          * scale delta to smallest unit (1/2^32)
121          * users must then scale back: count * 1/(1e9*2^32) to get Joules
122          * or use ldexp(count, -32).
123          * Watts = Joules/Time delta
124          */
125         return v << (32 - __get_cpu_var(rapl_pmu)->hw_unit);
126 }
127
128 static u64 rapl_event_update(struct perf_event *event)
129 {
130         struct hw_perf_event *hwc = &event->hw;
131         u64 prev_raw_count, new_raw_count;
132         s64 delta, sdelta;
133         int shift = RAPL_CNTR_WIDTH;
134
135 again:
136         prev_raw_count = local64_read(&hwc->prev_count);
137         rdmsrl(event->hw.event_base, new_raw_count);
138
139         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
140                             new_raw_count) != prev_raw_count) {
141                 cpu_relax();
142                 goto again;
143         }
144
145         /*
146          * Now we have the new raw value and have updated the prev
147          * timestamp already. We can now calculate the elapsed delta
148          * (event-)time and add that to the generic event.
149          *
150          * Careful, not all hw sign-extends above the physical width
151          * of the count.
152          */
153         delta = (new_raw_count << shift) - (prev_raw_count << shift);
154         delta >>= shift;
155
156         sdelta = rapl_scale(delta);
157
158         local64_add(sdelta, &event->count);
159
160         return new_raw_count;
161 }
162
163 static void rapl_start_hrtimer(struct rapl_pmu *pmu)
164 {
165         __hrtimer_start_range_ns(&pmu->hrtimer,
166                         pmu->timer_interval, 0,
167                         HRTIMER_MODE_REL_PINNED, 0);
168 }
169
170 static void rapl_stop_hrtimer(struct rapl_pmu *pmu)
171 {
172         hrtimer_cancel(&pmu->hrtimer);
173 }
174
175 static enum hrtimer_restart rapl_hrtimer_handle(struct hrtimer *hrtimer)
176 {
177         struct rapl_pmu *pmu = __get_cpu_var(rapl_pmu);
178         struct perf_event *event;
179         unsigned long flags;
180
181         if (!pmu->n_active)
182                 return HRTIMER_NORESTART;
183
184         spin_lock_irqsave(&pmu->lock, flags);
185
186         list_for_each_entry(event, &pmu->active_list, active_entry) {
187                 rapl_event_update(event);
188         }
189
190         spin_unlock_irqrestore(&pmu->lock, flags);
191
192         hrtimer_forward_now(hrtimer, pmu->timer_interval);
193
194         return HRTIMER_RESTART;
195 }
196
197 static void rapl_hrtimer_init(struct rapl_pmu *pmu)
198 {
199         struct hrtimer *hr = &pmu->hrtimer;
200
201         hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
202         hr->function = rapl_hrtimer_handle;
203 }
204
205 static void __rapl_pmu_event_start(struct rapl_pmu *pmu,
206                                    struct perf_event *event)
207 {
208         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
209                 return;
210
211         event->hw.state = 0;
212
213         list_add_tail(&event->active_entry, &pmu->active_list);
214
215         local64_set(&event->hw.prev_count, rapl_read_counter(event));
216
217         pmu->n_active++;
218         if (pmu->n_active == 1)
219                 rapl_start_hrtimer(pmu);
220 }
221
222 static void rapl_pmu_event_start(struct perf_event *event, int mode)
223 {
224         struct rapl_pmu *pmu = __get_cpu_var(rapl_pmu);
225         unsigned long flags;
226
227         spin_lock_irqsave(&pmu->lock, flags);
228         __rapl_pmu_event_start(pmu, event);
229         spin_unlock_irqrestore(&pmu->lock, flags);
230 }
231
232 static void rapl_pmu_event_stop(struct perf_event *event, int mode)
233 {
234         struct rapl_pmu *pmu = __get_cpu_var(rapl_pmu);
235         struct hw_perf_event *hwc = &event->hw;
236         unsigned long flags;
237
238         spin_lock_irqsave(&pmu->lock, flags);
239
240         /* mark event as deactivated and stopped */
241         if (!(hwc->state & PERF_HES_STOPPED)) {
242                 WARN_ON_ONCE(pmu->n_active <= 0);
243                 pmu->n_active--;
244                 if (pmu->n_active == 0)
245                         rapl_stop_hrtimer(pmu);
246
247                 list_del(&event->active_entry);
248
249                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
250                 hwc->state |= PERF_HES_STOPPED;
251         }
252
253         /* check if update of sw counter is necessary */
254         if ((mode & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
255                 /*
256                  * Drain the remaining delta count out of a event
257                  * that we are disabling:
258                  */
259                 rapl_event_update(event);
260                 hwc->state |= PERF_HES_UPTODATE;
261         }
262
263         spin_unlock_irqrestore(&pmu->lock, flags);
264 }
265
266 static int rapl_pmu_event_add(struct perf_event *event, int mode)
267 {
268         struct rapl_pmu *pmu = __get_cpu_var(rapl_pmu);
269         struct hw_perf_event *hwc = &event->hw;
270         unsigned long flags;
271
272         spin_lock_irqsave(&pmu->lock, flags);
273
274         hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
275
276         if (mode & PERF_EF_START)
277                 __rapl_pmu_event_start(pmu, event);
278
279         spin_unlock_irqrestore(&pmu->lock, flags);
280
281         return 0;
282 }
283
284 static void rapl_pmu_event_del(struct perf_event *event, int flags)
285 {
286         rapl_pmu_event_stop(event, PERF_EF_UPDATE);
287 }
288
289 static int rapl_pmu_event_init(struct perf_event *event)
290 {
291         u64 cfg = event->attr.config & RAPL_EVENT_MASK;
292         int bit, msr, ret = 0;
293
294         /* only look at RAPL events */
295         if (event->attr.type != rapl_pmu_class.type)
296                 return -ENOENT;
297
298         /* check only supported bits are set */
299         if (event->attr.config & ~RAPL_EVENT_MASK)
300                 return -EINVAL;
301
302         /*
303          * check event is known (determines counter)
304          */
305         switch (cfg) {
306         case INTEL_RAPL_PP0:
307                 bit = RAPL_IDX_PP0_NRG_STAT;
308                 msr = MSR_PP0_ENERGY_STATUS;
309                 break;
310         case INTEL_RAPL_PKG:
311                 bit = RAPL_IDX_PKG_NRG_STAT;
312                 msr = MSR_PKG_ENERGY_STATUS;
313                 break;
314         case INTEL_RAPL_RAM:
315                 bit = RAPL_IDX_RAM_NRG_STAT;
316                 msr = MSR_DRAM_ENERGY_STATUS;
317                 break;
318         default:
319                 return -EINVAL;
320         }
321         /* check event supported */
322         if (!(rapl_cntr_mask & (1 << bit)))
323                 return -EINVAL;
324
325         /* unsupported modes and filters */
326         if (event->attr.exclude_user   ||
327             event->attr.exclude_kernel ||
328             event->attr.exclude_hv     ||
329             event->attr.exclude_idle   ||
330             event->attr.exclude_host   ||
331             event->attr.exclude_guest  ||
332             event->attr.sample_period) /* no sampling */
333                 return -EINVAL;
334
335         /* must be done before validate_group */
336         event->hw.event_base = msr;
337         event->hw.config = cfg;
338         event->hw.idx = bit;
339
340         return ret;
341 }
342
343 static void rapl_pmu_event_read(struct perf_event *event)
344 {
345         rapl_event_update(event);
346 }
347
348 static ssize_t rapl_get_attr_cpumask(struct device *dev,
349                                 struct device_attribute *attr, char *buf)
350 {
351         int n = cpulist_scnprintf(buf, PAGE_SIZE - 2, &rapl_cpu_mask);
352
353         buf[n++] = '\n';
354         buf[n] = '\0';
355         return n;
356 }
357
358 static DEVICE_ATTR(cpumask, S_IRUGO, rapl_get_attr_cpumask, NULL);
359
360 static struct attribute *rapl_pmu_attrs[] = {
361         &dev_attr_cpumask.attr,
362         NULL,
363 };
364
365 static struct attribute_group rapl_pmu_attr_group = {
366         .attrs = rapl_pmu_attrs,
367 };
368
369 EVENT_ATTR_STR(energy-cores, rapl_cores, "event=0x01");
370 EVENT_ATTR_STR(energy-pkg  , rapl_pkg, "event=0x02");
371 EVENT_ATTR_STR(energy-ram  , rapl_ram, "event=0x03");
372
373 EVENT_ATTR_STR(energy-cores.unit, rapl_cores_unit, "Joules");
374 EVENT_ATTR_STR(energy-pkg.unit  , rapl_pkg_unit, "Joules");
375 EVENT_ATTR_STR(energy-ram.unit  , rapl_ram_unit, "Joules");
376
377 /*
378  * we compute in 0.23 nJ increments regardless of MSR
379  */
380 EVENT_ATTR_STR(energy-cores.scale, rapl_cores_scale, "2.3283064365386962890625e-10");
381 EVENT_ATTR_STR(energy-pkg.scale, rapl_pkg_scale, "2.3283064365386962890625e-10");
382 EVENT_ATTR_STR(energy-ram.scale, rapl_ram_scale, "2.3283064365386962890625e-10");
383
384 static struct attribute *rapl_events_srv_attr[] = {
385         EVENT_PTR(rapl_cores),
386         EVENT_PTR(rapl_pkg),
387         EVENT_PTR(rapl_ram),
388
389         EVENT_PTR(rapl_cores_unit),
390         EVENT_PTR(rapl_pkg_unit),
391         EVENT_PTR(rapl_ram_unit),
392
393         EVENT_PTR(rapl_cores_scale),
394         EVENT_PTR(rapl_pkg_scale),
395         EVENT_PTR(rapl_ram_scale),
396         NULL,
397 };
398
399 static struct attribute *rapl_events_cln_attr[] = {
400         EVENT_PTR(rapl_cores),
401         EVENT_PTR(rapl_pkg),
402
403         EVENT_PTR(rapl_cores_unit),
404         EVENT_PTR(rapl_pkg_unit),
405
406         EVENT_PTR(rapl_cores_scale),
407         EVENT_PTR(rapl_pkg_scale),
408         NULL,
409 };
410
411 static struct attribute_group rapl_pmu_events_group = {
412         .name = "events",
413         .attrs = NULL, /* patched at runtime */
414 };
415
416 DEFINE_RAPL_FORMAT_ATTR(event, event, "config:0-7");
417 static struct attribute *rapl_formats_attr[] = {
418         &format_attr_event.attr,
419         NULL,
420 };
421
422 static struct attribute_group rapl_pmu_format_group = {
423         .name = "format",
424         .attrs = rapl_formats_attr,
425 };
426
427 const struct attribute_group *rapl_attr_groups[] = {
428         &rapl_pmu_attr_group,
429         &rapl_pmu_format_group,
430         &rapl_pmu_events_group,
431         NULL,
432 };
433
434 static struct pmu rapl_pmu_class = {
435         .attr_groups    = rapl_attr_groups,
436         .task_ctx_nr    = perf_invalid_context, /* system-wide only */
437         .event_init     = rapl_pmu_event_init,
438         .add            = rapl_pmu_event_add, /* must have */
439         .del            = rapl_pmu_event_del, /* must have */
440         .start          = rapl_pmu_event_start,
441         .stop           = rapl_pmu_event_stop,
442         .read           = rapl_pmu_event_read,
443 };
444
445 static void rapl_cpu_exit(int cpu)
446 {
447         struct rapl_pmu *pmu = per_cpu(rapl_pmu, cpu);
448         int i, phys_id = topology_physical_package_id(cpu);
449         int target = -1;
450
451         /* find a new cpu on same package */
452         for_each_online_cpu(i) {
453                 if (i == cpu)
454                         continue;
455                 if (phys_id == topology_physical_package_id(i)) {
456                         target = i;
457                         break;
458                 }
459         }
460         /*
461          * clear cpu from cpumask
462          * if was set in cpumask and still some cpu on package,
463          * then move to new cpu
464          */
465         if (cpumask_test_and_clear_cpu(cpu, &rapl_cpu_mask) && target >= 0)
466                 cpumask_set_cpu(target, &rapl_cpu_mask);
467
468         WARN_ON(cpumask_empty(&rapl_cpu_mask));
469         /*
470          * migrate events and context to new cpu
471          */
472         if (target >= 0)
473                 perf_pmu_migrate_context(pmu->pmu, cpu, target);
474
475         /* cancel overflow polling timer for CPU */
476         rapl_stop_hrtimer(pmu);
477 }
478
479 static void rapl_cpu_init(int cpu)
480 {
481         int i, phys_id = topology_physical_package_id(cpu);
482
483         /* check if phys_is is already covered */
484         for_each_cpu(i, &rapl_cpu_mask) {
485                 if (phys_id == topology_physical_package_id(i))
486                         return;
487         }
488         /* was not found, so add it */
489         cpumask_set_cpu(cpu, &rapl_cpu_mask);
490 }
491
492 static int rapl_cpu_prepare(int cpu)
493 {
494         struct rapl_pmu *pmu = per_cpu(rapl_pmu, cpu);
495         int phys_id = topology_physical_package_id(cpu);
496         u64 ms;
497
498         if (pmu)
499                 return 0;
500
501         if (phys_id < 0)
502                 return -1;
503
504         pmu = kzalloc_node(sizeof(*pmu), GFP_KERNEL, cpu_to_node(cpu));
505         if (!pmu)
506                 return -1;
507
508         spin_lock_init(&pmu->lock);
509
510         INIT_LIST_HEAD(&pmu->active_list);
511
512         /*
513          * grab power unit as: 1/2^unit Joules
514          *
515          * we cache in local PMU instance
516          */
517         rdmsrl(MSR_RAPL_POWER_UNIT, pmu->hw_unit);
518         pmu->hw_unit = (pmu->hw_unit >> 8) & 0x1FULL;
519         pmu->pmu = &rapl_pmu_class;
520
521         /*
522          * use reference of 200W for scaling the timeout
523          * to avoid missing counter overflows.
524          * 200W = 200 Joules/sec
525          * divide interval by 2 to avoid lockstep (2 * 100)
526          * if hw unit is 32, then we use 2 ms 1/200/2
527          */
528         if (pmu->hw_unit < 32)
529                 ms = (1000 / (2 * 100)) * (1ULL << (32 - pmu->hw_unit - 1));
530         else
531                 ms = 2;
532
533         pmu->timer_interval = ms_to_ktime(ms);
534
535         rapl_hrtimer_init(pmu);
536
537         /* set RAPL pmu for this cpu for now */
538         per_cpu(rapl_pmu, cpu) = pmu;
539         per_cpu(rapl_pmu_to_free, cpu) = NULL;
540
541         return 0;
542 }
543
544 static void rapl_cpu_kfree(int cpu)
545 {
546         struct rapl_pmu *pmu = per_cpu(rapl_pmu_to_free, cpu);
547
548         kfree(pmu);
549
550         per_cpu(rapl_pmu_to_free, cpu) = NULL;
551 }
552
553 static int rapl_cpu_dying(int cpu)
554 {
555         struct rapl_pmu *pmu = per_cpu(rapl_pmu, cpu);
556
557         if (!pmu)
558                 return 0;
559
560         per_cpu(rapl_pmu, cpu) = NULL;
561
562         per_cpu(rapl_pmu_to_free, cpu) = pmu;
563
564         return 0;
565 }
566
567 static int rapl_cpu_notifier(struct notifier_block *self,
568                              unsigned long action, void *hcpu)
569 {
570         unsigned int cpu = (long)hcpu;
571
572         switch (action & ~CPU_TASKS_FROZEN) {
573         case CPU_UP_PREPARE:
574                 rapl_cpu_prepare(cpu);
575                 break;
576         case CPU_STARTING:
577                 rapl_cpu_init(cpu);
578                 break;
579         case CPU_UP_CANCELED:
580         case CPU_DYING:
581                 rapl_cpu_dying(cpu);
582                 break;
583         case CPU_ONLINE:
584         case CPU_DEAD:
585                 rapl_cpu_kfree(cpu);
586                 break;
587         case CPU_DOWN_PREPARE:
588                 rapl_cpu_exit(cpu);
589                 break;
590         default:
591                 break;
592         }
593
594         return NOTIFY_OK;
595 }
596
597 static const struct x86_cpu_id rapl_cpu_match[] = {
598         [0] = { .vendor = X86_VENDOR_INTEL, .family = 6 },
599         [1] = {},
600 };
601
602 static int __init rapl_pmu_init(void)
603 {
604         struct rapl_pmu *pmu;
605         int cpu, ret;
606
607         /*
608          * check for Intel processor family 6
609          */
610         if (!x86_match_cpu(rapl_cpu_match))
611                 return 0;
612
613         /* check supported CPU */
614         switch (boot_cpu_data.x86_model) {
615         case 42: /* Sandy Bridge */
616         case 58: /* Ivy Bridge */
617         case 60: /* Haswell */
618                 rapl_cntr_mask = RAPL_IDX_CLN;
619                 rapl_pmu_events_group.attrs = rapl_events_cln_attr;
620                 break;
621         case 45: /* Sandy Bridge-EP */
622         case 62: /* IvyTown */
623                 rapl_cntr_mask = RAPL_IDX_SRV;
624                 rapl_pmu_events_group.attrs = rapl_events_srv_attr;
625                 break;
626
627         default:
628                 /* unsupported */
629                 return 0;
630         }
631         get_online_cpus();
632
633         for_each_online_cpu(cpu) {
634                 rapl_cpu_prepare(cpu);
635                 rapl_cpu_init(cpu);
636         }
637
638         perf_cpu_notifier(rapl_cpu_notifier);
639
640         ret = perf_pmu_register(&rapl_pmu_class, "power", -1);
641         if (WARN_ON(ret)) {
642                 pr_info("RAPL PMU detected, registration failed (%d), RAPL PMU disabled\n", ret);
643                 put_online_cpus();
644                 return -1;
645         }
646
647         pmu = __get_cpu_var(rapl_pmu);
648
649         pr_info("RAPL PMU detected, hw unit 2^-%d Joules,"
650                 " API unit is 2^-32 Joules,"
651                 " %d fixed counters"
652                 " %llu ms ovfl timer\n",
653                 pmu->hw_unit,
654                 hweight32(rapl_cntr_mask),
655                 ktime_to_ms(pmu->timer_interval));
656
657         put_online_cpus();
658
659         return 0;
660 }
661 device_initcall(rapl_pmu_init);