Merge branch 'x86-urgent-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[cascardo/linux.git] / drivers / powercap / intel_rapl.c
1 /*
2  * Intel Running Average Power Limit (RAPL) Driver
3  * Copyright (c) 2013, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.
16  *
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list.h>
23 #include <linux/types.h>
24 #include <linux/device.h>
25 #include <linux/slab.h>
26 #include <linux/log2.h>
27 #include <linux/bitmap.h>
28 #include <linux/delay.h>
29 #include <linux/sysfs.h>
30 #include <linux/cpu.h>
31 #include <linux/powercap.h>
32 #include <asm/iosf_mbi.h>
33
34 #include <asm/processor.h>
35 #include <asm/cpu_device_id.h>
36
37 /* Local defines */
38 #define MSR_PLATFORM_POWER_LIMIT        0x0000065C
39
40 /* bitmasks for RAPL MSRs, used by primitive access functions */
41 #define ENERGY_STATUS_MASK      0xffffffff
42
43 #define POWER_LIMIT1_MASK       0x7FFF
44 #define POWER_LIMIT1_ENABLE     BIT(15)
45 #define POWER_LIMIT1_CLAMP      BIT(16)
46
47 #define POWER_LIMIT2_MASK       (0x7FFFULL<<32)
48 #define POWER_LIMIT2_ENABLE     BIT_ULL(47)
49 #define POWER_LIMIT2_CLAMP      BIT_ULL(48)
50 #define POWER_PACKAGE_LOCK      BIT_ULL(63)
51 #define POWER_PP_LOCK           BIT(31)
52
53 #define TIME_WINDOW1_MASK       (0x7FULL<<17)
54 #define TIME_WINDOW2_MASK       (0x7FULL<<49)
55
56 #define POWER_UNIT_OFFSET       0
57 #define POWER_UNIT_MASK         0x0F
58
59 #define ENERGY_UNIT_OFFSET      0x08
60 #define ENERGY_UNIT_MASK        0x1F00
61
62 #define TIME_UNIT_OFFSET        0x10
63 #define TIME_UNIT_MASK          0xF0000
64
65 #define POWER_INFO_MAX_MASK     (0x7fffULL<<32)
66 #define POWER_INFO_MIN_MASK     (0x7fffULL<<16)
67 #define POWER_INFO_MAX_TIME_WIN_MASK     (0x3fULL<<48)
68 #define POWER_INFO_THERMAL_SPEC_MASK     0x7fff
69
70 #define PERF_STATUS_THROTTLE_TIME_MASK 0xffffffff
71 #define PP_POLICY_MASK         0x1F
72
73 /* Non HW constants */
74 #define RAPL_PRIMITIVE_DERIVED       BIT(1) /* not from raw data */
75 #define RAPL_PRIMITIVE_DUMMY         BIT(2)
76
77 #define TIME_WINDOW_MAX_MSEC 40000
78 #define TIME_WINDOW_MIN_MSEC 250
79 #define ENERGY_UNIT_SCALE    1000 /* scale from driver unit to powercap unit */
80 enum unit_type {
81         ARBITRARY_UNIT, /* no translation */
82         POWER_UNIT,
83         ENERGY_UNIT,
84         TIME_UNIT,
85 };
86
87 enum rapl_domain_type {
88         RAPL_DOMAIN_PACKAGE, /* entire package/socket */
89         RAPL_DOMAIN_PP0, /* core power plane */
90         RAPL_DOMAIN_PP1, /* graphics uncore */
91         RAPL_DOMAIN_DRAM,/* DRAM control_type */
92         RAPL_DOMAIN_PLATFORM, /* PSys control_type */
93         RAPL_DOMAIN_MAX,
94 };
95
96 enum rapl_domain_msr_id {
97         RAPL_DOMAIN_MSR_LIMIT,
98         RAPL_DOMAIN_MSR_STATUS,
99         RAPL_DOMAIN_MSR_PERF,
100         RAPL_DOMAIN_MSR_POLICY,
101         RAPL_DOMAIN_MSR_INFO,
102         RAPL_DOMAIN_MSR_MAX,
103 };
104
105 /* per domain data, some are optional */
106 enum rapl_primitives {
107         ENERGY_COUNTER,
108         POWER_LIMIT1,
109         POWER_LIMIT2,
110         FW_LOCK,
111
112         PL1_ENABLE,  /* power limit 1, aka long term */
113         PL1_CLAMP,   /* allow frequency to go below OS request */
114         PL2_ENABLE,  /* power limit 2, aka short term, instantaneous */
115         PL2_CLAMP,
116
117         TIME_WINDOW1, /* long term */
118         TIME_WINDOW2, /* short term */
119         THERMAL_SPEC_POWER,
120         MAX_POWER,
121
122         MIN_POWER,
123         MAX_TIME_WINDOW,
124         THROTTLED_TIME,
125         PRIORITY_LEVEL,
126
127         /* below are not raw primitive data */
128         AVERAGE_POWER,
129         NR_RAPL_PRIMITIVES,
130 };
131
132 #define NR_RAW_PRIMITIVES (NR_RAPL_PRIMITIVES - 2)
133
134 /* Can be expanded to include events, etc.*/
135 struct rapl_domain_data {
136         u64 primitives[NR_RAPL_PRIMITIVES];
137         unsigned long timestamp;
138 };
139
140 struct msrl_action {
141         u32 msr_no;
142         u64 clear_mask;
143         u64 set_mask;
144         int err;
145 };
146
147 #define DOMAIN_STATE_INACTIVE           BIT(0)
148 #define DOMAIN_STATE_POWER_LIMIT_SET    BIT(1)
149 #define DOMAIN_STATE_BIOS_LOCKED        BIT(2)
150
151 #define NR_POWER_LIMITS (2)
152 struct rapl_power_limit {
153         struct powercap_zone_constraint *constraint;
154         int prim_id; /* primitive ID used to enable */
155         struct rapl_domain *domain;
156         const char *name;
157 };
158
159 static const char pl1_name[] = "long_term";
160 static const char pl2_name[] = "short_term";
161
162 struct rapl_package;
163 struct rapl_domain {
164         const char *name;
165         enum rapl_domain_type id;
166         int msrs[RAPL_DOMAIN_MSR_MAX];
167         struct powercap_zone power_zone;
168         struct rapl_domain_data rdd;
169         struct rapl_power_limit rpl[NR_POWER_LIMITS];
170         u64 attr_map; /* track capabilities */
171         unsigned int state;
172         unsigned int domain_energy_unit;
173         struct rapl_package *rp;
174 };
175 #define power_zone_to_rapl_domain(_zone) \
176         container_of(_zone, struct rapl_domain, power_zone)
177
178
179 /* Each physical package contains multiple domains, these are the common
180  * data across RAPL domains within a package.
181  */
182 struct rapl_package {
183         unsigned int id; /* physical package/socket id */
184         unsigned int nr_domains;
185         unsigned long domain_map; /* bit map of active domains */
186         unsigned int power_unit;
187         unsigned int energy_unit;
188         unsigned int time_unit;
189         struct rapl_domain *domains; /* array of domains, sized at runtime */
190         struct powercap_zone *power_zone; /* keep track of parent zone */
191         int nr_cpus; /* active cpus on the package, topology info is lost during
192                       * cpu hotplug. so we have to track ourselves.
193                       */
194         unsigned long power_limit_irq; /* keep track of package power limit
195                                         * notify interrupt enable status.
196                                         */
197         struct list_head plist;
198         int lead_cpu; /* one active cpu per package for access */
199 };
200
201 struct rapl_defaults {
202         u8 floor_freq_reg_addr;
203         int (*check_unit)(struct rapl_package *rp, int cpu);
204         void (*set_floor_freq)(struct rapl_domain *rd, bool mode);
205         u64 (*compute_time_window)(struct rapl_package *rp, u64 val,
206                                 bool to_raw);
207         unsigned int dram_domain_energy_unit;
208 };
209 static struct rapl_defaults *rapl_defaults;
210
211 /* Sideband MBI registers */
212 #define IOSF_CPU_POWER_BUDGET_CTL_BYT (0x2)
213 #define IOSF_CPU_POWER_BUDGET_CTL_TNG (0xdf)
214
215 #define PACKAGE_PLN_INT_SAVED   BIT(0)
216 #define MAX_PRIM_NAME (32)
217
218 /* per domain data. used to describe individual knobs such that access function
219  * can be consolidated into one instead of many inline functions.
220  */
221 struct rapl_primitive_info {
222         const char *name;
223         u64 mask;
224         int shift;
225         enum rapl_domain_msr_id id;
226         enum unit_type unit;
227         u32 flag;
228 };
229
230 #define PRIMITIVE_INFO_INIT(p, m, s, i, u, f) { \
231                 .name = #p,                     \
232                 .mask = m,                      \
233                 .shift = s,                     \
234                 .id = i,                        \
235                 .unit = u,                      \
236                 .flag = f                       \
237         }
238
239 static void rapl_init_domains(struct rapl_package *rp);
240 static int rapl_read_data_raw(struct rapl_domain *rd,
241                         enum rapl_primitives prim,
242                         bool xlate, u64 *data);
243 static int rapl_write_data_raw(struct rapl_domain *rd,
244                         enum rapl_primitives prim,
245                         unsigned long long value);
246 static u64 rapl_unit_xlate(struct rapl_domain *rd,
247                         enum unit_type type, u64 value,
248                         int to_raw);
249 static void package_power_limit_irq_save(struct rapl_package *rp);
250
251 static LIST_HEAD(rapl_packages); /* guarded by CPU hotplug lock */
252
253 static const char * const rapl_domain_names[] = {
254         "package",
255         "core",
256         "uncore",
257         "dram",
258         "psys",
259 };
260
261 static struct powercap_control_type *control_type; /* PowerCap Controller */
262 static struct rapl_domain *platform_rapl_domain; /* Platform (PSys) domain */
263
264 /* caller to ensure CPU hotplug lock is held */
265 static struct rapl_package *find_package_by_id(int id)
266 {
267         struct rapl_package *rp;
268
269         list_for_each_entry(rp, &rapl_packages, plist) {
270                 if (rp->id == id)
271                         return rp;
272         }
273
274         return NULL;
275 }
276
277 /* caller must hold cpu hotplug lock */
278 static void rapl_cleanup_data(void)
279 {
280         struct rapl_package *p, *tmp;
281
282         list_for_each_entry_safe(p, tmp, &rapl_packages, plist) {
283                 kfree(p->domains);
284                 list_del(&p->plist);
285                 kfree(p);
286         }
287 }
288
289 static int get_energy_counter(struct powercap_zone *power_zone, u64 *energy_raw)
290 {
291         struct rapl_domain *rd;
292         u64 energy_now;
293
294         /* prevent CPU hotplug, make sure the RAPL domain does not go
295          * away while reading the counter.
296          */
297         get_online_cpus();
298         rd = power_zone_to_rapl_domain(power_zone);
299
300         if (!rapl_read_data_raw(rd, ENERGY_COUNTER, true, &energy_now)) {
301                 *energy_raw = energy_now;
302                 put_online_cpus();
303
304                 return 0;
305         }
306         put_online_cpus();
307
308         return -EIO;
309 }
310
311 static int get_max_energy_counter(struct powercap_zone *pcd_dev, u64 *energy)
312 {
313         struct rapl_domain *rd = power_zone_to_rapl_domain(pcd_dev);
314
315         *energy = rapl_unit_xlate(rd, ENERGY_UNIT, ENERGY_STATUS_MASK, 0);
316         return 0;
317 }
318
319 static int release_zone(struct powercap_zone *power_zone)
320 {
321         struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
322         struct rapl_package *rp = rd->rp;
323
324         /* package zone is the last zone of a package, we can free
325          * memory here since all children has been unregistered.
326          */
327         if (rd->id == RAPL_DOMAIN_PACKAGE) {
328                 kfree(rd);
329                 rp->domains = NULL;
330         }
331
332         return 0;
333
334 }
335
336 static int find_nr_power_limit(struct rapl_domain *rd)
337 {
338         int i;
339
340         for (i = 0; i < NR_POWER_LIMITS; i++) {
341                 if (rd->rpl[i].name == NULL)
342                         break;
343         }
344
345         return i;
346 }
347
348 static int set_domain_enable(struct powercap_zone *power_zone, bool mode)
349 {
350         struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
351
352         if (rd->state & DOMAIN_STATE_BIOS_LOCKED)
353                 return -EACCES;
354
355         get_online_cpus();
356         rapl_write_data_raw(rd, PL1_ENABLE, mode);
357         if (rapl_defaults->set_floor_freq)
358                 rapl_defaults->set_floor_freq(rd, mode);
359         put_online_cpus();
360
361         return 0;
362 }
363
364 static int get_domain_enable(struct powercap_zone *power_zone, bool *mode)
365 {
366         struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
367         u64 val;
368
369         if (rd->state & DOMAIN_STATE_BIOS_LOCKED) {
370                 *mode = false;
371                 return 0;
372         }
373         get_online_cpus();
374         if (rapl_read_data_raw(rd, PL1_ENABLE, true, &val)) {
375                 put_online_cpus();
376                 return -EIO;
377         }
378         *mode = val;
379         put_online_cpus();
380
381         return 0;
382 }
383
384 /* per RAPL domain ops, in the order of rapl_domain_type */
385 static const struct powercap_zone_ops zone_ops[] = {
386         /* RAPL_DOMAIN_PACKAGE */
387         {
388                 .get_energy_uj = get_energy_counter,
389                 .get_max_energy_range_uj = get_max_energy_counter,
390                 .release = release_zone,
391                 .set_enable = set_domain_enable,
392                 .get_enable = get_domain_enable,
393         },
394         /* RAPL_DOMAIN_PP0 */
395         {
396                 .get_energy_uj = get_energy_counter,
397                 .get_max_energy_range_uj = get_max_energy_counter,
398                 .release = release_zone,
399                 .set_enable = set_domain_enable,
400                 .get_enable = get_domain_enable,
401         },
402         /* RAPL_DOMAIN_PP1 */
403         {
404                 .get_energy_uj = get_energy_counter,
405                 .get_max_energy_range_uj = get_max_energy_counter,
406                 .release = release_zone,
407                 .set_enable = set_domain_enable,
408                 .get_enable = get_domain_enable,
409         },
410         /* RAPL_DOMAIN_DRAM */
411         {
412                 .get_energy_uj = get_energy_counter,
413                 .get_max_energy_range_uj = get_max_energy_counter,
414                 .release = release_zone,
415                 .set_enable = set_domain_enable,
416                 .get_enable = get_domain_enable,
417         },
418         /* RAPL_DOMAIN_PLATFORM */
419         {
420                 .get_energy_uj = get_energy_counter,
421                 .get_max_energy_range_uj = get_max_energy_counter,
422                 .release = release_zone,
423                 .set_enable = set_domain_enable,
424                 .get_enable = get_domain_enable,
425         },
426 };
427
428 static int set_power_limit(struct powercap_zone *power_zone, int id,
429                         u64 power_limit)
430 {
431         struct rapl_domain *rd;
432         struct rapl_package *rp;
433         int ret = 0;
434
435         get_online_cpus();
436         rd = power_zone_to_rapl_domain(power_zone);
437         rp = rd->rp;
438
439         if (rd->state & DOMAIN_STATE_BIOS_LOCKED) {
440                 dev_warn(&power_zone->dev, "%s locked by BIOS, monitoring only\n",
441                         rd->name);
442                 ret = -EACCES;
443                 goto set_exit;
444         }
445
446         switch (rd->rpl[id].prim_id) {
447         case PL1_ENABLE:
448                 rapl_write_data_raw(rd, POWER_LIMIT1, power_limit);
449                 break;
450         case PL2_ENABLE:
451                 rapl_write_data_raw(rd, POWER_LIMIT2, power_limit);
452                 break;
453         default:
454                 ret = -EINVAL;
455         }
456         if (!ret)
457                 package_power_limit_irq_save(rp);
458 set_exit:
459         put_online_cpus();
460         return ret;
461 }
462
463 static int get_current_power_limit(struct powercap_zone *power_zone, int id,
464                                         u64 *data)
465 {
466         struct rapl_domain *rd;
467         u64 val;
468         int prim;
469         int ret = 0;
470
471         get_online_cpus();
472         rd = power_zone_to_rapl_domain(power_zone);
473         switch (rd->rpl[id].prim_id) {
474         case PL1_ENABLE:
475                 prim = POWER_LIMIT1;
476                 break;
477         case PL2_ENABLE:
478                 prim = POWER_LIMIT2;
479                 break;
480         default:
481                 put_online_cpus();
482                 return -EINVAL;
483         }
484         if (rapl_read_data_raw(rd, prim, true, &val))
485                 ret = -EIO;
486         else
487                 *data = val;
488
489         put_online_cpus();
490
491         return ret;
492 }
493
494 static int set_time_window(struct powercap_zone *power_zone, int id,
495                                                                 u64 window)
496 {
497         struct rapl_domain *rd;
498         int ret = 0;
499
500         get_online_cpus();
501         rd = power_zone_to_rapl_domain(power_zone);
502         switch (rd->rpl[id].prim_id) {
503         case PL1_ENABLE:
504                 rapl_write_data_raw(rd, TIME_WINDOW1, window);
505                 break;
506         case PL2_ENABLE:
507                 rapl_write_data_raw(rd, TIME_WINDOW2, window);
508                 break;
509         default:
510                 ret = -EINVAL;
511         }
512         put_online_cpus();
513         return ret;
514 }
515
516 static int get_time_window(struct powercap_zone *power_zone, int id, u64 *data)
517 {
518         struct rapl_domain *rd;
519         u64 val;
520         int ret = 0;
521
522         get_online_cpus();
523         rd = power_zone_to_rapl_domain(power_zone);
524         switch (rd->rpl[id].prim_id) {
525         case PL1_ENABLE:
526                 ret = rapl_read_data_raw(rd, TIME_WINDOW1, true, &val);
527                 break;
528         case PL2_ENABLE:
529                 ret = rapl_read_data_raw(rd, TIME_WINDOW2, true, &val);
530                 break;
531         default:
532                 put_online_cpus();
533                 return -EINVAL;
534         }
535         if (!ret)
536                 *data = val;
537         put_online_cpus();
538
539         return ret;
540 }
541
542 static const char *get_constraint_name(struct powercap_zone *power_zone, int id)
543 {
544         struct rapl_power_limit *rpl;
545         struct rapl_domain *rd;
546
547         rd = power_zone_to_rapl_domain(power_zone);
548         rpl = (struct rapl_power_limit *) &rd->rpl[id];
549
550         return rpl->name;
551 }
552
553
554 static int get_max_power(struct powercap_zone *power_zone, int id,
555                                         u64 *data)
556 {
557         struct rapl_domain *rd;
558         u64 val;
559         int prim;
560         int ret = 0;
561
562         get_online_cpus();
563         rd = power_zone_to_rapl_domain(power_zone);
564         switch (rd->rpl[id].prim_id) {
565         case PL1_ENABLE:
566                 prim = THERMAL_SPEC_POWER;
567                 break;
568         case PL2_ENABLE:
569                 prim = MAX_POWER;
570                 break;
571         default:
572                 put_online_cpus();
573                 return -EINVAL;
574         }
575         if (rapl_read_data_raw(rd, prim, true, &val))
576                 ret = -EIO;
577         else
578                 *data = val;
579
580         put_online_cpus();
581
582         return ret;
583 }
584
585 static const struct powercap_zone_constraint_ops constraint_ops = {
586         .set_power_limit_uw = set_power_limit,
587         .get_power_limit_uw = get_current_power_limit,
588         .set_time_window_us = set_time_window,
589         .get_time_window_us = get_time_window,
590         .get_max_power_uw = get_max_power,
591         .get_name = get_constraint_name,
592 };
593
594 /* called after domain detection and package level data are set */
595 static void rapl_init_domains(struct rapl_package *rp)
596 {
597         int i;
598         struct rapl_domain *rd = rp->domains;
599
600         for (i = 0; i < RAPL_DOMAIN_MAX; i++) {
601                 unsigned int mask = rp->domain_map & (1 << i);
602                 switch (mask) {
603                 case BIT(RAPL_DOMAIN_PACKAGE):
604                         rd->name = rapl_domain_names[RAPL_DOMAIN_PACKAGE];
605                         rd->id = RAPL_DOMAIN_PACKAGE;
606                         rd->msrs[0] = MSR_PKG_POWER_LIMIT;
607                         rd->msrs[1] = MSR_PKG_ENERGY_STATUS;
608                         rd->msrs[2] = MSR_PKG_PERF_STATUS;
609                         rd->msrs[3] = 0;
610                         rd->msrs[4] = MSR_PKG_POWER_INFO;
611                         rd->rpl[0].prim_id = PL1_ENABLE;
612                         rd->rpl[0].name = pl1_name;
613                         rd->rpl[1].prim_id = PL2_ENABLE;
614                         rd->rpl[1].name = pl2_name;
615                         break;
616                 case BIT(RAPL_DOMAIN_PP0):
617                         rd->name = rapl_domain_names[RAPL_DOMAIN_PP0];
618                         rd->id = RAPL_DOMAIN_PP0;
619                         rd->msrs[0] = MSR_PP0_POWER_LIMIT;
620                         rd->msrs[1] = MSR_PP0_ENERGY_STATUS;
621                         rd->msrs[2] = 0;
622                         rd->msrs[3] = MSR_PP0_POLICY;
623                         rd->msrs[4] = 0;
624                         rd->rpl[0].prim_id = PL1_ENABLE;
625                         rd->rpl[0].name = pl1_name;
626                         break;
627                 case BIT(RAPL_DOMAIN_PP1):
628                         rd->name = rapl_domain_names[RAPL_DOMAIN_PP1];
629                         rd->id = RAPL_DOMAIN_PP1;
630                         rd->msrs[0] = MSR_PP1_POWER_LIMIT;
631                         rd->msrs[1] = MSR_PP1_ENERGY_STATUS;
632                         rd->msrs[2] = 0;
633                         rd->msrs[3] = MSR_PP1_POLICY;
634                         rd->msrs[4] = 0;
635                         rd->rpl[0].prim_id = PL1_ENABLE;
636                         rd->rpl[0].name = pl1_name;
637                         break;
638                 case BIT(RAPL_DOMAIN_DRAM):
639                         rd->name = rapl_domain_names[RAPL_DOMAIN_DRAM];
640                         rd->id = RAPL_DOMAIN_DRAM;
641                         rd->msrs[0] = MSR_DRAM_POWER_LIMIT;
642                         rd->msrs[1] = MSR_DRAM_ENERGY_STATUS;
643                         rd->msrs[2] = MSR_DRAM_PERF_STATUS;
644                         rd->msrs[3] = 0;
645                         rd->msrs[4] = MSR_DRAM_POWER_INFO;
646                         rd->rpl[0].prim_id = PL1_ENABLE;
647                         rd->rpl[0].name = pl1_name;
648                         rd->domain_energy_unit =
649                                 rapl_defaults->dram_domain_energy_unit;
650                         if (rd->domain_energy_unit)
651                                 pr_info("DRAM domain energy unit %dpj\n",
652                                         rd->domain_energy_unit);
653                         break;
654                 }
655                 if (mask) {
656                         rd->rp = rp;
657                         rd++;
658                 }
659         }
660 }
661
662 static u64 rapl_unit_xlate(struct rapl_domain *rd, enum unit_type type,
663                         u64 value, int to_raw)
664 {
665         u64 units = 1;
666         struct rapl_package *rp = rd->rp;
667         u64 scale = 1;
668
669         switch (type) {
670         case POWER_UNIT:
671                 units = rp->power_unit;
672                 break;
673         case ENERGY_UNIT:
674                 scale = ENERGY_UNIT_SCALE;
675                 /* per domain unit takes precedence */
676                 if (rd && rd->domain_energy_unit)
677                         units = rd->domain_energy_unit;
678                 else
679                         units = rp->energy_unit;
680                 break;
681         case TIME_UNIT:
682                 return rapl_defaults->compute_time_window(rp, value, to_raw);
683         case ARBITRARY_UNIT:
684         default:
685                 return value;
686         };
687
688         if (to_raw)
689                 return div64_u64(value, units) * scale;
690
691         value *= units;
692
693         return div64_u64(value, scale);
694 }
695
696 /* in the order of enum rapl_primitives */
697 static struct rapl_primitive_info rpi[] = {
698         /* name, mask, shift, msr index, unit divisor */
699         PRIMITIVE_INFO_INIT(ENERGY_COUNTER, ENERGY_STATUS_MASK, 0,
700                                 RAPL_DOMAIN_MSR_STATUS, ENERGY_UNIT, 0),
701         PRIMITIVE_INFO_INIT(POWER_LIMIT1, POWER_LIMIT1_MASK, 0,
702                                 RAPL_DOMAIN_MSR_LIMIT, POWER_UNIT, 0),
703         PRIMITIVE_INFO_INIT(POWER_LIMIT2, POWER_LIMIT2_MASK, 32,
704                                 RAPL_DOMAIN_MSR_LIMIT, POWER_UNIT, 0),
705         PRIMITIVE_INFO_INIT(FW_LOCK, POWER_PP_LOCK, 31,
706                                 RAPL_DOMAIN_MSR_LIMIT, ARBITRARY_UNIT, 0),
707         PRIMITIVE_INFO_INIT(PL1_ENABLE, POWER_LIMIT1_ENABLE, 15,
708                                 RAPL_DOMAIN_MSR_LIMIT, ARBITRARY_UNIT, 0),
709         PRIMITIVE_INFO_INIT(PL1_CLAMP, POWER_LIMIT1_CLAMP, 16,
710                                 RAPL_DOMAIN_MSR_LIMIT, ARBITRARY_UNIT, 0),
711         PRIMITIVE_INFO_INIT(PL2_ENABLE, POWER_LIMIT2_ENABLE, 47,
712                                 RAPL_DOMAIN_MSR_LIMIT, ARBITRARY_UNIT, 0),
713         PRIMITIVE_INFO_INIT(PL2_CLAMP, POWER_LIMIT2_CLAMP, 48,
714                                 RAPL_DOMAIN_MSR_LIMIT, ARBITRARY_UNIT, 0),
715         PRIMITIVE_INFO_INIT(TIME_WINDOW1, TIME_WINDOW1_MASK, 17,
716                                 RAPL_DOMAIN_MSR_LIMIT, TIME_UNIT, 0),
717         PRIMITIVE_INFO_INIT(TIME_WINDOW2, TIME_WINDOW2_MASK, 49,
718                                 RAPL_DOMAIN_MSR_LIMIT, TIME_UNIT, 0),
719         PRIMITIVE_INFO_INIT(THERMAL_SPEC_POWER, POWER_INFO_THERMAL_SPEC_MASK,
720                                 0, RAPL_DOMAIN_MSR_INFO, POWER_UNIT, 0),
721         PRIMITIVE_INFO_INIT(MAX_POWER, POWER_INFO_MAX_MASK, 32,
722                                 RAPL_DOMAIN_MSR_INFO, POWER_UNIT, 0),
723         PRIMITIVE_INFO_INIT(MIN_POWER, POWER_INFO_MIN_MASK, 16,
724                                 RAPL_DOMAIN_MSR_INFO, POWER_UNIT, 0),
725         PRIMITIVE_INFO_INIT(MAX_TIME_WINDOW, POWER_INFO_MAX_TIME_WIN_MASK, 48,
726                                 RAPL_DOMAIN_MSR_INFO, TIME_UNIT, 0),
727         PRIMITIVE_INFO_INIT(THROTTLED_TIME, PERF_STATUS_THROTTLE_TIME_MASK, 0,
728                                 RAPL_DOMAIN_MSR_PERF, TIME_UNIT, 0),
729         PRIMITIVE_INFO_INIT(PRIORITY_LEVEL, PP_POLICY_MASK, 0,
730                                 RAPL_DOMAIN_MSR_POLICY, ARBITRARY_UNIT, 0),
731         /* non-hardware */
732         PRIMITIVE_INFO_INIT(AVERAGE_POWER, 0, 0, 0, POWER_UNIT,
733                                 RAPL_PRIMITIVE_DERIVED),
734         {NULL, 0, 0, 0},
735 };
736
737 /* Read primitive data based on its related struct rapl_primitive_info.
738  * if xlate flag is set, return translated data based on data units, i.e.
739  * time, energy, and power.
740  * RAPL MSRs are non-architectual and are laid out not consistently across
741  * domains. Here we use primitive info to allow writing consolidated access
742  * functions.
743  * For a given primitive, it is processed by MSR mask and shift. Unit conversion
744  * is pre-assigned based on RAPL unit MSRs read at init time.
745  * 63-------------------------- 31--------------------------- 0
746  * |                           xxxxx (mask)                   |
747  * |                                |<- shift ----------------|
748  * 63-------------------------- 31--------------------------- 0
749  */
750 static int rapl_read_data_raw(struct rapl_domain *rd,
751                         enum rapl_primitives prim,
752                         bool xlate, u64 *data)
753 {
754         u64 value, final;
755         u32 msr;
756         struct rapl_primitive_info *rp = &rpi[prim];
757         int cpu;
758
759         if (!rp->name || rp->flag & RAPL_PRIMITIVE_DUMMY)
760                 return -EINVAL;
761
762         msr = rd->msrs[rp->id];
763         if (!msr)
764                 return -EINVAL;
765
766         cpu = rd->rp->lead_cpu;
767
768         /* special-case package domain, which uses a different bit*/
769         if (prim == FW_LOCK && rd->id == RAPL_DOMAIN_PACKAGE) {
770                 rp->mask = POWER_PACKAGE_LOCK;
771                 rp->shift = 63;
772         }
773         /* non-hardware data are collected by the polling thread */
774         if (rp->flag & RAPL_PRIMITIVE_DERIVED) {
775                 *data = rd->rdd.primitives[prim];
776                 return 0;
777         }
778
779         if (rdmsrl_safe_on_cpu(cpu, msr, &value)) {
780                 pr_debug("failed to read msr 0x%x on cpu %d\n", msr, cpu);
781                 return -EIO;
782         }
783
784         final = value & rp->mask;
785         final = final >> rp->shift;
786         if (xlate)
787                 *data = rapl_unit_xlate(rd, rp->unit, final, 0);
788         else
789                 *data = final;
790
791         return 0;
792 }
793
794
795 static int msrl_update_safe(u32 msr_no, u64 clear_mask, u64 set_mask)
796 {
797         int err;
798         u64 val;
799
800         err = rdmsrl_safe(msr_no, &val);
801         if (err)
802                 goto out;
803
804         val &= ~clear_mask;
805         val |= set_mask;
806
807         err = wrmsrl_safe(msr_no, val);
808
809 out:
810         return err;
811 }
812
813 static void msrl_update_func(void *info)
814 {
815         struct msrl_action *ma = info;
816
817         ma->err = msrl_update_safe(ma->msr_no, ma->clear_mask, ma->set_mask);
818 }
819
820 /* Similar use of primitive info in the read counterpart */
821 static int rapl_write_data_raw(struct rapl_domain *rd,
822                         enum rapl_primitives prim,
823                         unsigned long long value)
824 {
825         struct rapl_primitive_info *rp = &rpi[prim];
826         int cpu;
827         u64 bits;
828         struct msrl_action ma;
829         int ret;
830
831         cpu = rd->rp->lead_cpu;
832         bits = rapl_unit_xlate(rd, rp->unit, value, 1);
833         bits |= bits << rp->shift;
834         memset(&ma, 0, sizeof(ma));
835
836         ma.msr_no = rd->msrs[rp->id];
837         ma.clear_mask = rp->mask;
838         ma.set_mask = bits;
839
840         ret = smp_call_function_single(cpu, msrl_update_func, &ma, 1);
841         if (ret)
842                 WARN_ON_ONCE(ret);
843         else
844                 ret = ma.err;
845
846         return ret;
847 }
848
849 /*
850  * Raw RAPL data stored in MSRs are in certain scales. We need to
851  * convert them into standard units based on the units reported in
852  * the RAPL unit MSRs. This is specific to CPUs as the method to
853  * calculate units differ on different CPUs.
854  * We convert the units to below format based on CPUs.
855  * i.e.
856  * energy unit: picoJoules  : Represented in picoJoules by default
857  * power unit : microWatts  : Represented in milliWatts by default
858  * time unit  : microseconds: Represented in seconds by default
859  */
860 static int rapl_check_unit_core(struct rapl_package *rp, int cpu)
861 {
862         u64 msr_val;
863         u32 value;
864
865         if (rdmsrl_safe_on_cpu(cpu, MSR_RAPL_POWER_UNIT, &msr_val)) {
866                 pr_err("Failed to read power unit MSR 0x%x on CPU %d, exit.\n",
867                         MSR_RAPL_POWER_UNIT, cpu);
868                 return -ENODEV;
869         }
870
871         value = (msr_val & ENERGY_UNIT_MASK) >> ENERGY_UNIT_OFFSET;
872         rp->energy_unit = ENERGY_UNIT_SCALE * 1000000 / (1 << value);
873
874         value = (msr_val & POWER_UNIT_MASK) >> POWER_UNIT_OFFSET;
875         rp->power_unit = 1000000 / (1 << value);
876
877         value = (msr_val & TIME_UNIT_MASK) >> TIME_UNIT_OFFSET;
878         rp->time_unit = 1000000 / (1 << value);
879
880         pr_debug("Core CPU package %d energy=%dpJ, time=%dus, power=%duW\n",
881                 rp->id, rp->energy_unit, rp->time_unit, rp->power_unit);
882
883         return 0;
884 }
885
886 static int rapl_check_unit_atom(struct rapl_package *rp, int cpu)
887 {
888         u64 msr_val;
889         u32 value;
890
891         if (rdmsrl_safe_on_cpu(cpu, MSR_RAPL_POWER_UNIT, &msr_val)) {
892                 pr_err("Failed to read power unit MSR 0x%x on CPU %d, exit.\n",
893                         MSR_RAPL_POWER_UNIT, cpu);
894                 return -ENODEV;
895         }
896         value = (msr_val & ENERGY_UNIT_MASK) >> ENERGY_UNIT_OFFSET;
897         rp->energy_unit = ENERGY_UNIT_SCALE * 1 << value;
898
899         value = (msr_val & POWER_UNIT_MASK) >> POWER_UNIT_OFFSET;
900         rp->power_unit = (1 << value) * 1000;
901
902         value = (msr_val & TIME_UNIT_MASK) >> TIME_UNIT_OFFSET;
903         rp->time_unit = 1000000 / (1 << value);
904
905         pr_debug("Atom package %d energy=%dpJ, time=%dus, power=%duW\n",
906                 rp->id, rp->energy_unit, rp->time_unit, rp->power_unit);
907
908         return 0;
909 }
910
911 static void power_limit_irq_save_cpu(void *info)
912 {
913         u32 l, h = 0;
914         struct rapl_package *rp = (struct rapl_package *)info;
915
916         /* save the state of PLN irq mask bit before disabling it */
917         rdmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, &l, &h);
918         if (!(rp->power_limit_irq & PACKAGE_PLN_INT_SAVED)) {
919                 rp->power_limit_irq = l & PACKAGE_THERM_INT_PLN_ENABLE;
920                 rp->power_limit_irq |= PACKAGE_PLN_INT_SAVED;
921         }
922         l &= ~PACKAGE_THERM_INT_PLN_ENABLE;
923         wrmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, l, h);
924 }
925
926
927 /* REVISIT:
928  * When package power limit is set artificially low by RAPL, LVT
929  * thermal interrupt for package power limit should be ignored
930  * since we are not really exceeding the real limit. The intention
931  * is to avoid excessive interrupts while we are trying to save power.
932  * A useful feature might be routing the package_power_limit interrupt
933  * to userspace via eventfd. once we have a usecase, this is simple
934  * to do by adding an atomic notifier.
935  */
936
937 static void package_power_limit_irq_save(struct rapl_package *rp)
938 {
939         if (!boot_cpu_has(X86_FEATURE_PTS) || !boot_cpu_has(X86_FEATURE_PLN))
940                 return;
941
942         smp_call_function_single(rp->lead_cpu, power_limit_irq_save_cpu, rp, 1);
943 }
944
945 static void power_limit_irq_restore_cpu(void *info)
946 {
947         u32 l, h = 0;
948         struct rapl_package *rp = (struct rapl_package *)info;
949
950         rdmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, &l, &h);
951
952         if (rp->power_limit_irq & PACKAGE_THERM_INT_PLN_ENABLE)
953                 l |= PACKAGE_THERM_INT_PLN_ENABLE;
954         else
955                 l &= ~PACKAGE_THERM_INT_PLN_ENABLE;
956
957         wrmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, l, h);
958 }
959
960 /* restore per package power limit interrupt enable state */
961 static void package_power_limit_irq_restore(struct rapl_package *rp)
962 {
963         if (!boot_cpu_has(X86_FEATURE_PTS) || !boot_cpu_has(X86_FEATURE_PLN))
964                 return;
965
966         /* irq enable state not saved, nothing to restore */
967         if (!(rp->power_limit_irq & PACKAGE_PLN_INT_SAVED))
968                 return;
969
970         smp_call_function_single(rp->lead_cpu, power_limit_irq_restore_cpu, rp, 1);
971 }
972
973 static void set_floor_freq_default(struct rapl_domain *rd, bool mode)
974 {
975         int nr_powerlimit = find_nr_power_limit(rd);
976
977         /* always enable clamp such that p-state can go below OS requested
978          * range. power capping priority over guranteed frequency.
979          */
980         rapl_write_data_raw(rd, PL1_CLAMP, mode);
981
982         /* some domains have pl2 */
983         if (nr_powerlimit > 1) {
984                 rapl_write_data_raw(rd, PL2_ENABLE, mode);
985                 rapl_write_data_raw(rd, PL2_CLAMP, mode);
986         }
987 }
988
989 static void set_floor_freq_atom(struct rapl_domain *rd, bool enable)
990 {
991         static u32 power_ctrl_orig_val;
992         u32 mdata;
993
994         if (!rapl_defaults->floor_freq_reg_addr) {
995                 pr_err("Invalid floor frequency config register\n");
996                 return;
997         }
998
999         if (!power_ctrl_orig_val)
1000                 iosf_mbi_read(BT_MBI_UNIT_PMC, MBI_CR_READ,
1001                               rapl_defaults->floor_freq_reg_addr,
1002                               &power_ctrl_orig_val);
1003         mdata = power_ctrl_orig_val;
1004         if (enable) {
1005                 mdata &= ~(0x7f << 8);
1006                 mdata |= 1 << 8;
1007         }
1008         iosf_mbi_write(BT_MBI_UNIT_PMC, MBI_CR_WRITE,
1009                        rapl_defaults->floor_freq_reg_addr, mdata);
1010 }
1011
1012 static u64 rapl_compute_time_window_core(struct rapl_package *rp, u64 value,
1013                                         bool to_raw)
1014 {
1015         u64 f, y; /* fraction and exp. used for time unit */
1016
1017         /*
1018          * Special processing based on 2^Y*(1+F/4), refer
1019          * to Intel Software Developer's manual Vol.3B: CH 14.9.3.
1020          */
1021         if (!to_raw) {
1022                 f = (value & 0x60) >> 5;
1023                 y = value & 0x1f;
1024                 value = (1 << y) * (4 + f) * rp->time_unit / 4;
1025         } else {
1026                 do_div(value, rp->time_unit);
1027                 y = ilog2(value);
1028                 f = div64_u64(4 * (value - (1 << y)), 1 << y);
1029                 value = (y & 0x1f) | ((f & 0x3) << 5);
1030         }
1031         return value;
1032 }
1033
1034 static u64 rapl_compute_time_window_atom(struct rapl_package *rp, u64 value,
1035                                         bool to_raw)
1036 {
1037         /*
1038          * Atom time unit encoding is straight forward val * time_unit,
1039          * where time_unit is default to 1 sec. Never 0.
1040          */
1041         if (!to_raw)
1042                 return (value) ? value *= rp->time_unit : rp->time_unit;
1043         else
1044                 value = div64_u64(value, rp->time_unit);
1045
1046         return value;
1047 }
1048
1049 static const struct rapl_defaults rapl_defaults_core = {
1050         .floor_freq_reg_addr = 0,
1051         .check_unit = rapl_check_unit_core,
1052         .set_floor_freq = set_floor_freq_default,
1053         .compute_time_window = rapl_compute_time_window_core,
1054 };
1055
1056 static const struct rapl_defaults rapl_defaults_hsw_server = {
1057         .check_unit = rapl_check_unit_core,
1058         .set_floor_freq = set_floor_freq_default,
1059         .compute_time_window = rapl_compute_time_window_core,
1060         .dram_domain_energy_unit = 15300,
1061 };
1062
1063 static const struct rapl_defaults rapl_defaults_byt = {
1064         .floor_freq_reg_addr = IOSF_CPU_POWER_BUDGET_CTL_BYT,
1065         .check_unit = rapl_check_unit_atom,
1066         .set_floor_freq = set_floor_freq_atom,
1067         .compute_time_window = rapl_compute_time_window_atom,
1068 };
1069
1070 static const struct rapl_defaults rapl_defaults_tng = {
1071         .floor_freq_reg_addr = IOSF_CPU_POWER_BUDGET_CTL_TNG,
1072         .check_unit = rapl_check_unit_atom,
1073         .set_floor_freq = set_floor_freq_atom,
1074         .compute_time_window = rapl_compute_time_window_atom,
1075 };
1076
1077 static const struct rapl_defaults rapl_defaults_ann = {
1078         .floor_freq_reg_addr = 0,
1079         .check_unit = rapl_check_unit_atom,
1080         .set_floor_freq = NULL,
1081         .compute_time_window = rapl_compute_time_window_atom,
1082 };
1083
1084 static const struct rapl_defaults rapl_defaults_cht = {
1085         .floor_freq_reg_addr = 0,
1086         .check_unit = rapl_check_unit_atom,
1087         .set_floor_freq = NULL,
1088         .compute_time_window = rapl_compute_time_window_atom,
1089 };
1090
1091 #define RAPL_CPU(_model, _ops) {                        \
1092                 .vendor = X86_VENDOR_INTEL,             \
1093                 .family = 6,                            \
1094                 .model = _model,                        \
1095                 .driver_data = (kernel_ulong_t)&_ops,   \
1096                 }
1097
1098 static const struct x86_cpu_id rapl_ids[] __initconst = {
1099         RAPL_CPU(0x2a, rapl_defaults_core),/* Sandy Bridge */
1100         RAPL_CPU(0x2d, rapl_defaults_core),/* Sandy Bridge EP */
1101         RAPL_CPU(0x37, rapl_defaults_byt),/* Valleyview */
1102         RAPL_CPU(0x3a, rapl_defaults_core),/* Ivy Bridge */
1103         RAPL_CPU(0x3c, rapl_defaults_core),/* Haswell */
1104         RAPL_CPU(0x3d, rapl_defaults_core),/* Broadwell */
1105         RAPL_CPU(0x3f, rapl_defaults_hsw_server),/* Haswell servers */
1106         RAPL_CPU(0x4f, rapl_defaults_hsw_server),/* Broadwell servers */
1107         RAPL_CPU(0x45, rapl_defaults_core),/* Haswell ULT */
1108         RAPL_CPU(0x46, rapl_defaults_core),/* Haswell */
1109         RAPL_CPU(0x47, rapl_defaults_core),/* Broadwell-H */
1110         RAPL_CPU(0x4E, rapl_defaults_core),/* Skylake */
1111         RAPL_CPU(0x4C, rapl_defaults_cht),/* Braswell/Cherryview */
1112         RAPL_CPU(0x4A, rapl_defaults_tng),/* Tangier */
1113         RAPL_CPU(0x56, rapl_defaults_core),/* Future Xeon */
1114         RAPL_CPU(0x5A, rapl_defaults_ann),/* Annidale */
1115         RAPL_CPU(0X5C, rapl_defaults_core),/* Broxton */
1116         RAPL_CPU(0x5E, rapl_defaults_core),/* Skylake-H/S */
1117         RAPL_CPU(0x57, rapl_defaults_hsw_server),/* Knights Landing */
1118         RAPL_CPU(0x8E, rapl_defaults_core),/* Kabylake */
1119         RAPL_CPU(0x9E, rapl_defaults_core),/* Kabylake */
1120         {}
1121 };
1122 MODULE_DEVICE_TABLE(x86cpu, rapl_ids);
1123
1124 /* read once for all raw primitive data for all packages, domains */
1125 static void rapl_update_domain_data(void)
1126 {
1127         int dmn, prim;
1128         u64 val;
1129         struct rapl_package *rp;
1130
1131         list_for_each_entry(rp, &rapl_packages, plist) {
1132                 for (dmn = 0; dmn < rp->nr_domains; dmn++) {
1133                         pr_debug("update package %d domain %s data\n", rp->id,
1134                                 rp->domains[dmn].name);
1135                         /* exclude non-raw primitives */
1136                         for (prim = 0; prim < NR_RAW_PRIMITIVES; prim++)
1137                                 if (!rapl_read_data_raw(&rp->domains[dmn], prim,
1138                                                                 rpi[prim].unit,
1139                                                                 &val))
1140                                         rp->domains[dmn].rdd.primitives[prim] =
1141                                                                         val;
1142                 }
1143         }
1144
1145 }
1146
1147 static int rapl_unregister_powercap(void)
1148 {
1149         struct rapl_package *rp;
1150         struct rapl_domain *rd, *rd_package = NULL;
1151
1152         /* unregister all active rapl packages from the powercap layer,
1153          * hotplug lock held
1154          */
1155         list_for_each_entry(rp, &rapl_packages, plist) {
1156                 package_power_limit_irq_restore(rp);
1157
1158                 for (rd = rp->domains; rd < rp->domains + rp->nr_domains;
1159                      rd++) {
1160                         pr_debug("remove package, undo power limit on %d: %s\n",
1161                                 rp->id, rd->name);
1162                         rapl_write_data_raw(rd, PL1_ENABLE, 0);
1163                         rapl_write_data_raw(rd, PL1_CLAMP, 0);
1164                         if (find_nr_power_limit(rd) > 1) {
1165                                 rapl_write_data_raw(rd, PL2_ENABLE, 0);
1166                                 rapl_write_data_raw(rd, PL2_CLAMP, 0);
1167                         }
1168                         if (rd->id == RAPL_DOMAIN_PACKAGE) {
1169                                 rd_package = rd;
1170                                 continue;
1171                         }
1172                         powercap_unregister_zone(control_type, &rd->power_zone);
1173                 }
1174                 /* do the package zone last */
1175                 if (rd_package)
1176                         powercap_unregister_zone(control_type,
1177                                                 &rd_package->power_zone);
1178         }
1179
1180         if (platform_rapl_domain) {
1181                 powercap_unregister_zone(control_type,
1182                                          &platform_rapl_domain->power_zone);
1183                 kfree(platform_rapl_domain);
1184         }
1185
1186         powercap_unregister_control_type(control_type);
1187
1188         return 0;
1189 }
1190
1191 static int rapl_package_register_powercap(struct rapl_package *rp)
1192 {
1193         struct rapl_domain *rd;
1194         int ret = 0;
1195         char dev_name[17]; /* max domain name = 7 + 1 + 8 for int + 1 for null*/
1196         struct powercap_zone *power_zone = NULL;
1197         int nr_pl;
1198
1199         /* first we register package domain as the parent zone*/
1200         for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1201                 if (rd->id == RAPL_DOMAIN_PACKAGE) {
1202                         nr_pl = find_nr_power_limit(rd);
1203                         pr_debug("register socket %d package domain %s\n",
1204                                 rp->id, rd->name);
1205                         memset(dev_name, 0, sizeof(dev_name));
1206                         snprintf(dev_name, sizeof(dev_name), "%s-%d",
1207                                 rd->name, rp->id);
1208                         power_zone = powercap_register_zone(&rd->power_zone,
1209                                                         control_type,
1210                                                         dev_name, NULL,
1211                                                         &zone_ops[rd->id],
1212                                                         nr_pl,
1213                                                         &constraint_ops);
1214                         if (IS_ERR(power_zone)) {
1215                                 pr_debug("failed to register package, %d\n",
1216                                         rp->id);
1217                                 ret = PTR_ERR(power_zone);
1218                                 goto exit_package;
1219                         }
1220                         /* track parent zone in per package/socket data */
1221                         rp->power_zone = power_zone;
1222                         /* done, only one package domain per socket */
1223                         break;
1224                 }
1225         }
1226         if (!power_zone) {
1227                 pr_err("no package domain found, unknown topology!\n");
1228                 ret = -ENODEV;
1229                 goto exit_package;
1230         }
1231         /* now register domains as children of the socket/package*/
1232         for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1233                 if (rd->id == RAPL_DOMAIN_PACKAGE)
1234                         continue;
1235                 /* number of power limits per domain varies */
1236                 nr_pl = find_nr_power_limit(rd);
1237                 power_zone = powercap_register_zone(&rd->power_zone,
1238                                                 control_type, rd->name,
1239                                                 rp->power_zone,
1240                                                 &zone_ops[rd->id], nr_pl,
1241                                                 &constraint_ops);
1242
1243                 if (IS_ERR(power_zone)) {
1244                         pr_debug("failed to register power_zone, %d:%s:%s\n",
1245                                 rp->id, rd->name, dev_name);
1246                         ret = PTR_ERR(power_zone);
1247                         goto err_cleanup;
1248                 }
1249         }
1250
1251 exit_package:
1252         return ret;
1253 err_cleanup:
1254         /* clean up previously initialized domains within the package if we
1255          * failed after the first domain setup.
1256          */
1257         while (--rd >= rp->domains) {
1258                 pr_debug("unregister package %d domain %s\n", rp->id, rd->name);
1259                 powercap_unregister_zone(control_type, &rd->power_zone);
1260         }
1261
1262         return ret;
1263 }
1264
1265 static int rapl_register_psys(void)
1266 {
1267         struct rapl_domain *rd;
1268         struct powercap_zone *power_zone;
1269         u64 val;
1270
1271         if (rdmsrl_safe_on_cpu(0, MSR_PLATFORM_ENERGY_STATUS, &val) || !val)
1272                 return -ENODEV;
1273
1274         if (rdmsrl_safe_on_cpu(0, MSR_PLATFORM_POWER_LIMIT, &val) || !val)
1275                 return -ENODEV;
1276
1277         rd = kzalloc(sizeof(*rd), GFP_KERNEL);
1278         if (!rd)
1279                 return -ENOMEM;
1280
1281         rd->name = rapl_domain_names[RAPL_DOMAIN_PLATFORM];
1282         rd->id = RAPL_DOMAIN_PLATFORM;
1283         rd->msrs[0] = MSR_PLATFORM_POWER_LIMIT;
1284         rd->msrs[1] = MSR_PLATFORM_ENERGY_STATUS;
1285         rd->rpl[0].prim_id = PL1_ENABLE;
1286         rd->rpl[0].name = pl1_name;
1287         rd->rpl[1].prim_id = PL2_ENABLE;
1288         rd->rpl[1].name = pl2_name;
1289         rd->rp = find_package_by_id(0);
1290
1291         power_zone = powercap_register_zone(&rd->power_zone, control_type,
1292                                             "psys", NULL,
1293                                             &zone_ops[RAPL_DOMAIN_PLATFORM],
1294                                             2, &constraint_ops);
1295
1296         if (IS_ERR(power_zone)) {
1297                 kfree(rd);
1298                 return PTR_ERR(power_zone);
1299         }
1300
1301         platform_rapl_domain = rd;
1302
1303         return 0;
1304 }
1305
1306 static int rapl_register_powercap(void)
1307 {
1308         struct rapl_domain *rd;
1309         struct rapl_package *rp;
1310         int ret = 0;
1311
1312         control_type = powercap_register_control_type(NULL, "intel-rapl", NULL);
1313         if (IS_ERR(control_type)) {
1314                 pr_debug("failed to register powercap control_type.\n");
1315                 return PTR_ERR(control_type);
1316         }
1317         /* read the initial data */
1318         rapl_update_domain_data();
1319         list_for_each_entry(rp, &rapl_packages, plist)
1320                 if (rapl_package_register_powercap(rp))
1321                         goto err_cleanup_package;
1322
1323         /* Don't bail out if PSys is not supported */
1324         rapl_register_psys();
1325
1326         return ret;
1327
1328 err_cleanup_package:
1329         /* clean up previously initialized packages */
1330         list_for_each_entry_continue_reverse(rp, &rapl_packages, plist) {
1331                 for (rd = rp->domains; rd < rp->domains + rp->nr_domains;
1332                      rd++) {
1333                         pr_debug("unregister zone/package %d, %s domain\n",
1334                                 rp->id, rd->name);
1335                         powercap_unregister_zone(control_type, &rd->power_zone);
1336                 }
1337         }
1338
1339         return ret;
1340 }
1341
1342 static int rapl_check_domain(int cpu, int domain)
1343 {
1344         unsigned msr;
1345         u64 val = 0;
1346
1347         switch (domain) {
1348         case RAPL_DOMAIN_PACKAGE:
1349                 msr = MSR_PKG_ENERGY_STATUS;
1350                 break;
1351         case RAPL_DOMAIN_PP0:
1352                 msr = MSR_PP0_ENERGY_STATUS;
1353                 break;
1354         case RAPL_DOMAIN_PP1:
1355                 msr = MSR_PP1_ENERGY_STATUS;
1356                 break;
1357         case RAPL_DOMAIN_DRAM:
1358                 msr = MSR_DRAM_ENERGY_STATUS;
1359                 break;
1360         case RAPL_DOMAIN_PLATFORM:
1361                 /* PSYS(PLATFORM) is not a CPU domain, so avoid printng error */
1362                 return -EINVAL;
1363         default:
1364                 pr_err("invalid domain id %d\n", domain);
1365                 return -EINVAL;
1366         }
1367         /* make sure domain counters are available and contains non-zero
1368          * values, otherwise skip it.
1369          */
1370         if (rdmsrl_safe_on_cpu(cpu, msr, &val) || !val)
1371                 return -ENODEV;
1372
1373         return 0;
1374 }
1375
1376 /* Detect active and valid domains for the given CPU, caller must
1377  * ensure the CPU belongs to the targeted package and CPU hotlug is disabled.
1378  */
1379 static int rapl_detect_domains(struct rapl_package *rp, int cpu)
1380 {
1381         int i;
1382         int ret = 0;
1383         struct rapl_domain *rd;
1384         u64 locked;
1385
1386         for (i = 0; i < RAPL_DOMAIN_MAX; i++) {
1387                 /* use physical package id to read counters */
1388                 if (!rapl_check_domain(cpu, i)) {
1389                         rp->domain_map |= 1 << i;
1390                         pr_info("Found RAPL domain %s\n", rapl_domain_names[i]);
1391                 }
1392         }
1393         rp->nr_domains = bitmap_weight(&rp->domain_map, RAPL_DOMAIN_MAX);
1394         if (!rp->nr_domains) {
1395                 pr_err("no valid rapl domains found in package %d\n", rp->id);
1396                 ret = -ENODEV;
1397                 goto done;
1398         }
1399         pr_debug("found %d domains on package %d\n", rp->nr_domains, rp->id);
1400
1401         rp->domains = kcalloc(rp->nr_domains + 1, sizeof(struct rapl_domain),
1402                         GFP_KERNEL);
1403         if (!rp->domains) {
1404                 ret = -ENOMEM;
1405                 goto done;
1406         }
1407         rapl_init_domains(rp);
1408
1409         for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1410                 /* check if the domain is locked by BIOS */
1411                 ret = rapl_read_data_raw(rd, FW_LOCK, false, &locked);
1412                 if (ret)
1413                         return ret;
1414                 if (locked) {
1415                         pr_info("RAPL package %d domain %s locked by BIOS\n",
1416                                 rp->id, rd->name);
1417                         rd->state |= DOMAIN_STATE_BIOS_LOCKED;
1418                 }
1419         }
1420
1421
1422 done:
1423         return ret;
1424 }
1425
1426 static bool is_package_new(int package)
1427 {
1428         struct rapl_package *rp;
1429
1430         /* caller prevents cpu hotplug, there will be no new packages added
1431          * or deleted while traversing the package list, no need for locking.
1432          */
1433         list_for_each_entry(rp, &rapl_packages, plist)
1434                 if (package == rp->id)
1435                         return false;
1436
1437         return true;
1438 }
1439
1440 /* RAPL interface can be made of a two-level hierarchy: package level and domain
1441  * level. We first detect the number of packages then domains of each package.
1442  * We have to consider the possiblity of CPU online/offline due to hotplug and
1443  * other scenarios.
1444  */
1445 static int rapl_detect_topology(void)
1446 {
1447         int i;
1448         int phy_package_id;
1449         struct rapl_package *new_package, *rp;
1450
1451         for_each_online_cpu(i) {
1452                 phy_package_id = topology_physical_package_id(i);
1453                 if (is_package_new(phy_package_id)) {
1454                         new_package = kzalloc(sizeof(*rp), GFP_KERNEL);
1455                         if (!new_package) {
1456                                 rapl_cleanup_data();
1457                                 return -ENOMEM;
1458                         }
1459                         /* add the new package to the list */
1460                         new_package->id = phy_package_id;
1461                         new_package->nr_cpus = 1;
1462                         /* use the first active cpu of the package to access */
1463                         new_package->lead_cpu = i;
1464                         /* check if the package contains valid domains */
1465                         if (rapl_detect_domains(new_package, i) ||
1466                                 rapl_defaults->check_unit(new_package, i)) {
1467                                 kfree(new_package->domains);
1468                                 kfree(new_package);
1469                                 /* free up the packages already initialized */
1470                                 rapl_cleanup_data();
1471                                 return -ENODEV;
1472                         }
1473                         INIT_LIST_HEAD(&new_package->plist);
1474                         list_add(&new_package->plist, &rapl_packages);
1475                 } else {
1476                         rp = find_package_by_id(phy_package_id);
1477                         if (rp)
1478                                 ++rp->nr_cpus;
1479                 }
1480         }
1481
1482         return 0;
1483 }
1484
1485 /* called from CPU hotplug notifier, hotplug lock held */
1486 static void rapl_remove_package(struct rapl_package *rp)
1487 {
1488         struct rapl_domain *rd, *rd_package = NULL;
1489
1490         for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1491                 if (rd->id == RAPL_DOMAIN_PACKAGE) {
1492                         rd_package = rd;
1493                         continue;
1494                 }
1495                 pr_debug("remove package %d, %s domain\n", rp->id, rd->name);
1496                 powercap_unregister_zone(control_type, &rd->power_zone);
1497         }
1498         /* do parent zone last */
1499         powercap_unregister_zone(control_type, &rd_package->power_zone);
1500         list_del(&rp->plist);
1501         kfree(rp);
1502 }
1503
1504 /* called from CPU hotplug notifier, hotplug lock held */
1505 static int rapl_add_package(int cpu)
1506 {
1507         int ret = 0;
1508         int phy_package_id;
1509         struct rapl_package *rp;
1510
1511         phy_package_id = topology_physical_package_id(cpu);
1512         rp = kzalloc(sizeof(struct rapl_package), GFP_KERNEL);
1513         if (!rp)
1514                 return -ENOMEM;
1515
1516         /* add the new package to the list */
1517         rp->id = phy_package_id;
1518         rp->nr_cpus = 1;
1519         rp->lead_cpu = cpu;
1520
1521         /* check if the package contains valid domains */
1522         if (rapl_detect_domains(rp, cpu) ||
1523                 rapl_defaults->check_unit(rp, cpu)) {
1524                 ret = -ENODEV;
1525                 goto err_free_package;
1526         }
1527         if (!rapl_package_register_powercap(rp)) {
1528                 INIT_LIST_HEAD(&rp->plist);
1529                 list_add(&rp->plist, &rapl_packages);
1530                 return ret;
1531         }
1532
1533 err_free_package:
1534         kfree(rp->domains);
1535         kfree(rp);
1536
1537         return ret;
1538 }
1539
1540 /* Handles CPU hotplug on multi-socket systems.
1541  * If a CPU goes online as the first CPU of the physical package
1542  * we add the RAPL package to the system. Similarly, when the last
1543  * CPU of the package is removed, we remove the RAPL package and its
1544  * associated domains. Cooling devices are handled accordingly at
1545  * per-domain level.
1546  */
1547 static int rapl_cpu_callback(struct notifier_block *nfb,
1548                                 unsigned long action, void *hcpu)
1549 {
1550         unsigned long cpu = (unsigned long)hcpu;
1551         int phy_package_id;
1552         struct rapl_package *rp;
1553         int lead_cpu;
1554
1555         phy_package_id = topology_physical_package_id(cpu);
1556         switch (action) {
1557         case CPU_ONLINE:
1558         case CPU_ONLINE_FROZEN:
1559         case CPU_DOWN_FAILED:
1560         case CPU_DOWN_FAILED_FROZEN:
1561                 rp = find_package_by_id(phy_package_id);
1562                 if (rp)
1563                         ++rp->nr_cpus;
1564                 else
1565                         rapl_add_package(cpu);
1566                 break;
1567         case CPU_DOWN_PREPARE:
1568         case CPU_DOWN_PREPARE_FROZEN:
1569                 rp = find_package_by_id(phy_package_id);
1570                 if (!rp)
1571                         break;
1572                 if (--rp->nr_cpus == 0)
1573                         rapl_remove_package(rp);
1574                 else if (cpu == rp->lead_cpu) {
1575                         /* choose another active cpu in the package */
1576                         lead_cpu = cpumask_any_but(topology_core_cpumask(cpu), cpu);
1577                         if (lead_cpu < nr_cpu_ids)
1578                                 rp->lead_cpu = lead_cpu;
1579                         else /* should never go here */
1580                                 pr_err("no active cpu available for package %d\n",
1581                                         phy_package_id);
1582                 }
1583         }
1584
1585         return NOTIFY_OK;
1586 }
1587
1588 static struct notifier_block rapl_cpu_notifier = {
1589         .notifier_call = rapl_cpu_callback,
1590 };
1591
1592 static int __init rapl_init(void)
1593 {
1594         int ret = 0;
1595         const struct x86_cpu_id *id;
1596
1597         id = x86_match_cpu(rapl_ids);
1598         if (!id) {
1599                 pr_err("driver does not support CPU family %d model %d\n",
1600                         boot_cpu_data.x86, boot_cpu_data.x86_model);
1601
1602                 return -ENODEV;
1603         }
1604
1605         rapl_defaults = (struct rapl_defaults *)id->driver_data;
1606
1607         cpu_notifier_register_begin();
1608
1609         /* prevent CPU hotplug during detection */
1610         get_online_cpus();
1611         ret = rapl_detect_topology();
1612         if (ret)
1613                 goto done;
1614
1615         if (rapl_register_powercap()) {
1616                 rapl_cleanup_data();
1617                 ret = -ENODEV;
1618                 goto done;
1619         }
1620         __register_hotcpu_notifier(&rapl_cpu_notifier);
1621 done:
1622         put_online_cpus();
1623         cpu_notifier_register_done();
1624
1625         return ret;
1626 }
1627
1628 static void __exit rapl_exit(void)
1629 {
1630         cpu_notifier_register_begin();
1631         get_online_cpus();
1632         __unregister_hotcpu_notifier(&rapl_cpu_notifier);
1633         rapl_unregister_powercap();
1634         rapl_cleanup_data();
1635         put_online_cpus();
1636         cpu_notifier_register_done();
1637 }
1638
1639 module_init(rapl_init);
1640 module_exit(rapl_exit);
1641
1642 MODULE_DESCRIPTION("Driver for Intel RAPL (Running Average Power Limit)");
1643 MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@intel.com>");
1644 MODULE_LICENSE("GPL v2");