xref: /linux/drivers/powercap/intel_rapl_common.c (revision 71dfa617ea9f18e4585fe78364217cd32b1fc382)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Common code for Intel Running Average Power Limit (RAPL) support.
4  * Copyright (c) 2019, Intel Corporation.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/cleanup.h>
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/list.h>
12 #include <linux/types.h>
13 #include <linux/device.h>
14 #include <linux/slab.h>
15 #include <linux/log2.h>
16 #include <linux/bitmap.h>
17 #include <linux/delay.h>
18 #include <linux/sysfs.h>
19 #include <linux/cpu.h>
20 #include <linux/powercap.h>
21 #include <linux/suspend.h>
22 #include <linux/intel_rapl.h>
23 #include <linux/processor.h>
24 #include <linux/platform_device.h>
25 
26 #include <asm/iosf_mbi.h>
27 #include <asm/cpu_device_id.h>
28 #include <asm/intel-family.h>
29 
30 /* bitmasks for RAPL MSRs, used by primitive access functions */
31 #define ENERGY_STATUS_MASK      0xffffffff
32 
33 #define POWER_LIMIT1_MASK       0x7FFF
34 #define POWER_LIMIT1_ENABLE     BIT(15)
35 #define POWER_LIMIT1_CLAMP      BIT(16)
36 
37 #define POWER_LIMIT2_MASK       (0x7FFFULL<<32)
38 #define POWER_LIMIT2_ENABLE     BIT_ULL(47)
39 #define POWER_LIMIT2_CLAMP      BIT_ULL(48)
40 #define POWER_HIGH_LOCK         BIT_ULL(63)
41 #define POWER_LOW_LOCK          BIT(31)
42 
43 #define POWER_LIMIT4_MASK		0x1FFF
44 
45 #define TIME_WINDOW1_MASK       (0x7FULL<<17)
46 #define TIME_WINDOW2_MASK       (0x7FULL<<49)
47 
48 #define POWER_UNIT_OFFSET	0
49 #define POWER_UNIT_MASK		0x0F
50 
51 #define ENERGY_UNIT_OFFSET	0x08
52 #define ENERGY_UNIT_MASK	0x1F00
53 
54 #define TIME_UNIT_OFFSET	0x10
55 #define TIME_UNIT_MASK		0xF0000
56 
57 #define POWER_INFO_MAX_MASK     (0x7fffULL<<32)
58 #define POWER_INFO_MIN_MASK     (0x7fffULL<<16)
59 #define POWER_INFO_MAX_TIME_WIN_MASK     (0x3fULL<<48)
60 #define POWER_INFO_THERMAL_SPEC_MASK     0x7fff
61 
62 #define PERF_STATUS_THROTTLE_TIME_MASK 0xffffffff
63 #define PP_POLICY_MASK         0x1F
64 
65 /*
66  * SPR has different layout for Psys Domain PowerLimit registers.
67  * There are 17 bits of PL1 and PL2 instead of 15 bits.
68  * The Enable bits and TimeWindow bits are also shifted as a result.
69  */
70 #define PSYS_POWER_LIMIT1_MASK       0x1FFFF
71 #define PSYS_POWER_LIMIT1_ENABLE     BIT(17)
72 
73 #define PSYS_POWER_LIMIT2_MASK       (0x1FFFFULL<<32)
74 #define PSYS_POWER_LIMIT2_ENABLE     BIT_ULL(49)
75 
76 #define PSYS_TIME_WINDOW1_MASK       (0x7FULL<<19)
77 #define PSYS_TIME_WINDOW2_MASK       (0x7FULL<<51)
78 
79 /* bitmasks for RAPL TPMI, used by primitive access functions */
80 #define TPMI_POWER_LIMIT_MASK	0x3FFFF
81 #define TPMI_POWER_LIMIT_ENABLE	BIT_ULL(62)
82 #define TPMI_TIME_WINDOW_MASK	(0x7FULL<<18)
83 #define TPMI_INFO_SPEC_MASK	0x3FFFF
84 #define TPMI_INFO_MIN_MASK	(0x3FFFFULL << 18)
85 #define TPMI_INFO_MAX_MASK	(0x3FFFFULL << 36)
86 #define TPMI_INFO_MAX_TIME_WIN_MASK	(0x7FULL << 54)
87 
88 /* Non HW constants */
89 #define RAPL_PRIMITIVE_DERIVED       BIT(1)	/* not from raw data */
90 #define RAPL_PRIMITIVE_DUMMY         BIT(2)
91 
92 #define TIME_WINDOW_MAX_MSEC 40000
93 #define TIME_WINDOW_MIN_MSEC 250
94 #define ENERGY_UNIT_SCALE    1000	/* scale from driver unit to powercap unit */
95 enum unit_type {
96 	ARBITRARY_UNIT,		/* no translation */
97 	POWER_UNIT,
98 	ENERGY_UNIT,
99 	TIME_UNIT,
100 };
101 
102 /* per domain data, some are optional */
103 #define NR_RAW_PRIMITIVES (NR_RAPL_PRIMITIVES - 2)
104 
105 #define	DOMAIN_STATE_INACTIVE           BIT(0)
106 #define	DOMAIN_STATE_POWER_LIMIT_SET    BIT(1)
107 
108 static const char *pl_names[NR_POWER_LIMITS] = {
109 	[POWER_LIMIT1] = "long_term",
110 	[POWER_LIMIT2] = "short_term",
111 	[POWER_LIMIT4] = "peak_power",
112 };
113 
114 enum pl_prims {
115 	PL_ENABLE,
116 	PL_CLAMP,
117 	PL_LIMIT,
118 	PL_TIME_WINDOW,
119 	PL_MAX_POWER,
120 	PL_LOCK,
121 };
122 
123 static bool is_pl_valid(struct rapl_domain *rd, int pl)
124 {
125 	if (pl < POWER_LIMIT1 || pl > POWER_LIMIT4)
126 		return false;
127 	return rd->rpl[pl].name ? true : false;
128 }
129 
130 static int get_pl_lock_prim(struct rapl_domain *rd, int pl)
131 {
132 	if (rd->rp->priv->type == RAPL_IF_TPMI) {
133 		if (pl == POWER_LIMIT1)
134 			return PL1_LOCK;
135 		if (pl == POWER_LIMIT2)
136 			return PL2_LOCK;
137 		if (pl == POWER_LIMIT4)
138 			return PL4_LOCK;
139 	}
140 
141 	/* MSR/MMIO Interface doesn't have Lock bit for PL4 */
142 	if (pl == POWER_LIMIT4)
143 		return -EINVAL;
144 
145 	/*
146 	 * Power Limit register that supports two power limits has a different
147 	 * bit position for the Lock bit.
148 	 */
149 	if (rd->rp->priv->limits[rd->id] & BIT(POWER_LIMIT2))
150 		return FW_HIGH_LOCK;
151 	return FW_LOCK;
152 }
153 
154 static int get_pl_prim(struct rapl_domain *rd, int pl, enum pl_prims prim)
155 {
156 	switch (pl) {
157 	case POWER_LIMIT1:
158 		if (prim == PL_ENABLE)
159 			return PL1_ENABLE;
160 		if (prim == PL_CLAMP && rd->rp->priv->type != RAPL_IF_TPMI)
161 			return PL1_CLAMP;
162 		if (prim == PL_LIMIT)
163 			return POWER_LIMIT1;
164 		if (prim == PL_TIME_WINDOW)
165 			return TIME_WINDOW1;
166 		if (prim == PL_MAX_POWER)
167 			return THERMAL_SPEC_POWER;
168 		if (prim == PL_LOCK)
169 			return get_pl_lock_prim(rd, pl);
170 		return -EINVAL;
171 	case POWER_LIMIT2:
172 		if (prim == PL_ENABLE)
173 			return PL2_ENABLE;
174 		if (prim == PL_CLAMP && rd->rp->priv->type != RAPL_IF_TPMI)
175 			return PL2_CLAMP;
176 		if (prim == PL_LIMIT)
177 			return POWER_LIMIT2;
178 		if (prim == PL_TIME_WINDOW)
179 			return TIME_WINDOW2;
180 		if (prim == PL_MAX_POWER)
181 			return MAX_POWER;
182 		if (prim == PL_LOCK)
183 			return get_pl_lock_prim(rd, pl);
184 		return -EINVAL;
185 	case POWER_LIMIT4:
186 		if (prim == PL_LIMIT)
187 			return POWER_LIMIT4;
188 		if (prim == PL_ENABLE)
189 			return PL4_ENABLE;
190 		/* PL4 would be around two times PL2, use same prim as PL2. */
191 		if (prim == PL_MAX_POWER)
192 			return MAX_POWER;
193 		if (prim == PL_LOCK)
194 			return get_pl_lock_prim(rd, pl);
195 		return -EINVAL;
196 	default:
197 		return -EINVAL;
198 	}
199 }
200 
201 #define power_zone_to_rapl_domain(_zone) \
202 	container_of(_zone, struct rapl_domain, power_zone)
203 
204 struct rapl_defaults {
205 	u8 floor_freq_reg_addr;
206 	int (*check_unit)(struct rapl_domain *rd);
207 	void (*set_floor_freq)(struct rapl_domain *rd, bool mode);
208 	u64 (*compute_time_window)(struct rapl_domain *rd, u64 val,
209 				    bool to_raw);
210 	unsigned int dram_domain_energy_unit;
211 	unsigned int psys_domain_energy_unit;
212 	bool spr_psys_bits;
213 };
214 static struct rapl_defaults *defaults_msr;
215 static const struct rapl_defaults defaults_tpmi;
216 
217 static struct rapl_defaults *get_defaults(struct rapl_package *rp)
218 {
219 	return rp->priv->defaults;
220 }
221 
222 /* Sideband MBI registers */
223 #define IOSF_CPU_POWER_BUDGET_CTL_BYT (0x2)
224 #define IOSF_CPU_POWER_BUDGET_CTL_TNG (0xdf)
225 
226 #define PACKAGE_PLN_INT_SAVED   BIT(0)
227 #define MAX_PRIM_NAME (32)
228 
229 /* per domain data. used to describe individual knobs such that access function
230  * can be consolidated into one instead of many inline functions.
231  */
232 struct rapl_primitive_info {
233 	const char *name;
234 	u64 mask;
235 	int shift;
236 	enum rapl_domain_reg_id id;
237 	enum unit_type unit;
238 	u32 flag;
239 };
240 
241 #define PRIMITIVE_INFO_INIT(p, m, s, i, u, f) {	\
242 		.name = #p,			\
243 		.mask = m,			\
244 		.shift = s,			\
245 		.id = i,			\
246 		.unit = u,			\
247 		.flag = f			\
248 	}
249 
250 static void rapl_init_domains(struct rapl_package *rp);
251 static int rapl_read_data_raw(struct rapl_domain *rd,
252 			      enum rapl_primitives prim,
253 			      bool xlate, u64 *data);
254 static int rapl_write_data_raw(struct rapl_domain *rd,
255 			       enum rapl_primitives prim,
256 			       unsigned long long value);
257 static int rapl_read_pl_data(struct rapl_domain *rd, int pl,
258 			      enum pl_prims pl_prim,
259 			      bool xlate, u64 *data);
260 static int rapl_write_pl_data(struct rapl_domain *rd, int pl,
261 			       enum pl_prims pl_prim,
262 			       unsigned long long value);
263 static u64 rapl_unit_xlate(struct rapl_domain *rd,
264 			   enum unit_type type, u64 value, int to_raw);
265 static void package_power_limit_irq_save(struct rapl_package *rp);
266 
267 static LIST_HEAD(rapl_packages);	/* guarded by CPU hotplug lock */
268 
269 static const char *const rapl_domain_names[] = {
270 	"package",
271 	"core",
272 	"uncore",
273 	"dram",
274 	"psys",
275 };
276 
277 static int get_energy_counter(struct powercap_zone *power_zone,
278 			      u64 *energy_raw)
279 {
280 	struct rapl_domain *rd;
281 	u64 energy_now;
282 
283 	/* prevent CPU hotplug, make sure the RAPL domain does not go
284 	 * away while reading the counter.
285 	 */
286 	cpus_read_lock();
287 	rd = power_zone_to_rapl_domain(power_zone);
288 
289 	if (!rapl_read_data_raw(rd, ENERGY_COUNTER, true, &energy_now)) {
290 		*energy_raw = energy_now;
291 		cpus_read_unlock();
292 
293 		return 0;
294 	}
295 	cpus_read_unlock();
296 
297 	return -EIO;
298 }
299 
300 static int get_max_energy_counter(struct powercap_zone *pcd_dev, u64 *energy)
301 {
302 	struct rapl_domain *rd = power_zone_to_rapl_domain(pcd_dev);
303 
304 	*energy = rapl_unit_xlate(rd, ENERGY_UNIT, ENERGY_STATUS_MASK, 0);
305 	return 0;
306 }
307 
308 static int release_zone(struct powercap_zone *power_zone)
309 {
310 	struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
311 	struct rapl_package *rp = rd->rp;
312 
313 	/* package zone is the last zone of a package, we can free
314 	 * memory here since all children has been unregistered.
315 	 */
316 	if (rd->id == RAPL_DOMAIN_PACKAGE) {
317 		kfree(rd);
318 		rp->domains = NULL;
319 	}
320 
321 	return 0;
322 
323 }
324 
325 static int find_nr_power_limit(struct rapl_domain *rd)
326 {
327 	int i, nr_pl = 0;
328 
329 	for (i = 0; i < NR_POWER_LIMITS; i++) {
330 		if (is_pl_valid(rd, i))
331 			nr_pl++;
332 	}
333 
334 	return nr_pl;
335 }
336 
337 static int set_domain_enable(struct powercap_zone *power_zone, bool mode)
338 {
339 	struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
340 	struct rapl_defaults *defaults = get_defaults(rd->rp);
341 	int ret;
342 
343 	cpus_read_lock();
344 	ret = rapl_write_pl_data(rd, POWER_LIMIT1, PL_ENABLE, mode);
345 	if (!ret && defaults->set_floor_freq)
346 		defaults->set_floor_freq(rd, mode);
347 	cpus_read_unlock();
348 
349 	return ret;
350 }
351 
352 static int get_domain_enable(struct powercap_zone *power_zone, bool *mode)
353 {
354 	struct rapl_domain *rd = power_zone_to_rapl_domain(power_zone);
355 	u64 val;
356 	int ret;
357 
358 	if (rd->rpl[POWER_LIMIT1].locked) {
359 		*mode = false;
360 		return 0;
361 	}
362 	cpus_read_lock();
363 	ret = rapl_read_pl_data(rd, POWER_LIMIT1, PL_ENABLE, true, &val);
364 	if (!ret)
365 		*mode = val;
366 	cpus_read_unlock();
367 
368 	return ret;
369 }
370 
371 /* per RAPL domain ops, in the order of rapl_domain_type */
372 static const struct powercap_zone_ops zone_ops[] = {
373 	/* RAPL_DOMAIN_PACKAGE */
374 	{
375 	 .get_energy_uj = get_energy_counter,
376 	 .get_max_energy_range_uj = get_max_energy_counter,
377 	 .release = release_zone,
378 	 .set_enable = set_domain_enable,
379 	 .get_enable = get_domain_enable,
380 	 },
381 	/* RAPL_DOMAIN_PP0 */
382 	{
383 	 .get_energy_uj = get_energy_counter,
384 	 .get_max_energy_range_uj = get_max_energy_counter,
385 	 .release = release_zone,
386 	 .set_enable = set_domain_enable,
387 	 .get_enable = get_domain_enable,
388 	 },
389 	/* RAPL_DOMAIN_PP1 */
390 	{
391 	 .get_energy_uj = get_energy_counter,
392 	 .get_max_energy_range_uj = get_max_energy_counter,
393 	 .release = release_zone,
394 	 .set_enable = set_domain_enable,
395 	 .get_enable = get_domain_enable,
396 	 },
397 	/* RAPL_DOMAIN_DRAM */
398 	{
399 	 .get_energy_uj = get_energy_counter,
400 	 .get_max_energy_range_uj = get_max_energy_counter,
401 	 .release = release_zone,
402 	 .set_enable = set_domain_enable,
403 	 .get_enable = get_domain_enable,
404 	 },
405 	/* RAPL_DOMAIN_PLATFORM */
406 	{
407 	 .get_energy_uj = get_energy_counter,
408 	 .get_max_energy_range_uj = get_max_energy_counter,
409 	 .release = release_zone,
410 	 .set_enable = set_domain_enable,
411 	 .get_enable = get_domain_enable,
412 	 },
413 };
414 
415 /*
416  * Constraint index used by powercap can be different than power limit (PL)
417  * index in that some  PLs maybe missing due to non-existent MSRs. So we
418  * need to convert here by finding the valid PLs only (name populated).
419  */
420 static int contraint_to_pl(struct rapl_domain *rd, int cid)
421 {
422 	int i, j;
423 
424 	for (i = POWER_LIMIT1, j = 0; i < NR_POWER_LIMITS; i++) {
425 		if (is_pl_valid(rd, i) && j++ == cid) {
426 			pr_debug("%s: index %d\n", __func__, i);
427 			return i;
428 		}
429 	}
430 	pr_err("Cannot find matching power limit for constraint %d\n", cid);
431 
432 	return -EINVAL;
433 }
434 
435 static int set_power_limit(struct powercap_zone *power_zone, int cid,
436 			   u64 power_limit)
437 {
438 	struct rapl_domain *rd;
439 	struct rapl_package *rp;
440 	int ret = 0;
441 	int id;
442 
443 	cpus_read_lock();
444 	rd = power_zone_to_rapl_domain(power_zone);
445 	id = contraint_to_pl(rd, cid);
446 	rp = rd->rp;
447 
448 	ret = rapl_write_pl_data(rd, id, PL_LIMIT, power_limit);
449 	if (!ret)
450 		package_power_limit_irq_save(rp);
451 	cpus_read_unlock();
452 	return ret;
453 }
454 
455 static int get_current_power_limit(struct powercap_zone *power_zone, int cid,
456 				   u64 *data)
457 {
458 	struct rapl_domain *rd;
459 	u64 val;
460 	int ret = 0;
461 	int id;
462 
463 	cpus_read_lock();
464 	rd = power_zone_to_rapl_domain(power_zone);
465 	id = contraint_to_pl(rd, cid);
466 
467 	ret = rapl_read_pl_data(rd, id, PL_LIMIT, true, &val);
468 	if (!ret)
469 		*data = val;
470 
471 	cpus_read_unlock();
472 
473 	return ret;
474 }
475 
476 static int set_time_window(struct powercap_zone *power_zone, int cid,
477 			   u64 window)
478 {
479 	struct rapl_domain *rd;
480 	int ret = 0;
481 	int id;
482 
483 	cpus_read_lock();
484 	rd = power_zone_to_rapl_domain(power_zone);
485 	id = contraint_to_pl(rd, cid);
486 
487 	ret = rapl_write_pl_data(rd, id, PL_TIME_WINDOW, window);
488 
489 	cpus_read_unlock();
490 	return ret;
491 }
492 
493 static int get_time_window(struct powercap_zone *power_zone, int cid,
494 			   u64 *data)
495 {
496 	struct rapl_domain *rd;
497 	u64 val;
498 	int ret = 0;
499 	int id;
500 
501 	cpus_read_lock();
502 	rd = power_zone_to_rapl_domain(power_zone);
503 	id = contraint_to_pl(rd, cid);
504 
505 	ret = rapl_read_pl_data(rd, id, PL_TIME_WINDOW, true, &val);
506 	if (!ret)
507 		*data = val;
508 
509 	cpus_read_unlock();
510 
511 	return ret;
512 }
513 
514 static const char *get_constraint_name(struct powercap_zone *power_zone,
515 				       int cid)
516 {
517 	struct rapl_domain *rd;
518 	int id;
519 
520 	rd = power_zone_to_rapl_domain(power_zone);
521 	id = contraint_to_pl(rd, cid);
522 	if (id >= 0)
523 		return rd->rpl[id].name;
524 
525 	return NULL;
526 }
527 
528 static int get_max_power(struct powercap_zone *power_zone, int cid, u64 *data)
529 {
530 	struct rapl_domain *rd;
531 	u64 val;
532 	int ret = 0;
533 	int id;
534 
535 	cpus_read_lock();
536 	rd = power_zone_to_rapl_domain(power_zone);
537 	id = contraint_to_pl(rd, cid);
538 
539 	ret = rapl_read_pl_data(rd, id, PL_MAX_POWER, true, &val);
540 	if (!ret)
541 		*data = val;
542 
543 	/* As a generalization rule, PL4 would be around two times PL2. */
544 	if (id == POWER_LIMIT4)
545 		*data = *data * 2;
546 
547 	cpus_read_unlock();
548 
549 	return ret;
550 }
551 
552 static const struct powercap_zone_constraint_ops constraint_ops = {
553 	.set_power_limit_uw = set_power_limit,
554 	.get_power_limit_uw = get_current_power_limit,
555 	.set_time_window_us = set_time_window,
556 	.get_time_window_us = get_time_window,
557 	.get_max_power_uw = get_max_power,
558 	.get_name = get_constraint_name,
559 };
560 
561 /* Return the id used for read_raw/write_raw callback */
562 static int get_rid(struct rapl_package *rp)
563 {
564 	return rp->lead_cpu >= 0 ? rp->lead_cpu : rp->id;
565 }
566 
567 /* called after domain detection and package level data are set */
568 static void rapl_init_domains(struct rapl_package *rp)
569 {
570 	enum rapl_domain_type i;
571 	enum rapl_domain_reg_id j;
572 	struct rapl_domain *rd = rp->domains;
573 
574 	for (i = 0; i < RAPL_DOMAIN_MAX; i++) {
575 		unsigned int mask = rp->domain_map & (1 << i);
576 		int t;
577 
578 		if (!mask)
579 			continue;
580 
581 		rd->rp = rp;
582 
583 		if (i == RAPL_DOMAIN_PLATFORM && rp->id > 0) {
584 			snprintf(rd->name, RAPL_DOMAIN_NAME_LENGTH, "psys-%d",
585 				rp->lead_cpu >= 0 ? topology_physical_package_id(rp->lead_cpu) :
586 				rp->id);
587 		} else {
588 			snprintf(rd->name, RAPL_DOMAIN_NAME_LENGTH, "%s",
589 				rapl_domain_names[i]);
590 		}
591 
592 		rd->id = i;
593 
594 		/* PL1 is supported by default */
595 		rp->priv->limits[i] |= BIT(POWER_LIMIT1);
596 
597 		for (t = POWER_LIMIT1; t < NR_POWER_LIMITS; t++) {
598 			if (rp->priv->limits[i] & BIT(t))
599 				rd->rpl[t].name = pl_names[t];
600 		}
601 
602 		for (j = 0; j < RAPL_DOMAIN_REG_MAX; j++)
603 			rd->regs[j] = rp->priv->regs[i][j];
604 
605 		rd++;
606 	}
607 }
608 
609 static u64 rapl_unit_xlate(struct rapl_domain *rd, enum unit_type type,
610 			   u64 value, int to_raw)
611 {
612 	u64 units = 1;
613 	struct rapl_defaults *defaults = get_defaults(rd->rp);
614 	u64 scale = 1;
615 
616 	switch (type) {
617 	case POWER_UNIT:
618 		units = rd->power_unit;
619 		break;
620 	case ENERGY_UNIT:
621 		scale = ENERGY_UNIT_SCALE;
622 		units = rd->energy_unit;
623 		break;
624 	case TIME_UNIT:
625 		return defaults->compute_time_window(rd, value, to_raw);
626 	case ARBITRARY_UNIT:
627 	default:
628 		return value;
629 	}
630 
631 	if (to_raw)
632 		return div64_u64(value, units) * scale;
633 
634 	value *= units;
635 
636 	return div64_u64(value, scale);
637 }
638 
639 /* RAPL primitives for MSR and MMIO I/F */
640 static struct rapl_primitive_info rpi_msr[NR_RAPL_PRIMITIVES] = {
641 	/* name, mask, shift, msr index, unit divisor */
642 	[POWER_LIMIT1] = PRIMITIVE_INFO_INIT(POWER_LIMIT1, POWER_LIMIT1_MASK, 0,
643 			    RAPL_DOMAIN_REG_LIMIT, POWER_UNIT, 0),
644 	[POWER_LIMIT2] = PRIMITIVE_INFO_INIT(POWER_LIMIT2, POWER_LIMIT2_MASK, 32,
645 			    RAPL_DOMAIN_REG_LIMIT, POWER_UNIT, 0),
646 	[POWER_LIMIT4] = PRIMITIVE_INFO_INIT(POWER_LIMIT4, POWER_LIMIT4_MASK, 0,
647 				RAPL_DOMAIN_REG_PL4, POWER_UNIT, 0),
648 	[ENERGY_COUNTER] = PRIMITIVE_INFO_INIT(ENERGY_COUNTER, ENERGY_STATUS_MASK, 0,
649 			    RAPL_DOMAIN_REG_STATUS, ENERGY_UNIT, 0),
650 	[FW_LOCK] = PRIMITIVE_INFO_INIT(FW_LOCK, POWER_LOW_LOCK, 31,
651 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
652 	[FW_HIGH_LOCK] = PRIMITIVE_INFO_INIT(FW_LOCK, POWER_HIGH_LOCK, 63,
653 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
654 	[PL1_ENABLE] = PRIMITIVE_INFO_INIT(PL1_ENABLE, POWER_LIMIT1_ENABLE, 15,
655 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
656 	[PL1_CLAMP] = PRIMITIVE_INFO_INIT(PL1_CLAMP, POWER_LIMIT1_CLAMP, 16,
657 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
658 	[PL2_ENABLE] = PRIMITIVE_INFO_INIT(PL2_ENABLE, POWER_LIMIT2_ENABLE, 47,
659 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
660 	[PL2_CLAMP] = PRIMITIVE_INFO_INIT(PL2_CLAMP, POWER_LIMIT2_CLAMP, 48,
661 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
662 	[TIME_WINDOW1] = PRIMITIVE_INFO_INIT(TIME_WINDOW1, TIME_WINDOW1_MASK, 17,
663 			    RAPL_DOMAIN_REG_LIMIT, TIME_UNIT, 0),
664 	[TIME_WINDOW2] = PRIMITIVE_INFO_INIT(TIME_WINDOW2, TIME_WINDOW2_MASK, 49,
665 			    RAPL_DOMAIN_REG_LIMIT, TIME_UNIT, 0),
666 	[THERMAL_SPEC_POWER] = PRIMITIVE_INFO_INIT(THERMAL_SPEC_POWER, POWER_INFO_THERMAL_SPEC_MASK,
667 			    0, RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
668 	[MAX_POWER] = PRIMITIVE_INFO_INIT(MAX_POWER, POWER_INFO_MAX_MASK, 32,
669 			    RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
670 	[MIN_POWER] = PRIMITIVE_INFO_INIT(MIN_POWER, POWER_INFO_MIN_MASK, 16,
671 			    RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
672 	[MAX_TIME_WINDOW] = PRIMITIVE_INFO_INIT(MAX_TIME_WINDOW, POWER_INFO_MAX_TIME_WIN_MASK, 48,
673 			    RAPL_DOMAIN_REG_INFO, TIME_UNIT, 0),
674 	[THROTTLED_TIME] = PRIMITIVE_INFO_INIT(THROTTLED_TIME, PERF_STATUS_THROTTLE_TIME_MASK, 0,
675 			    RAPL_DOMAIN_REG_PERF, TIME_UNIT, 0),
676 	[PRIORITY_LEVEL] = PRIMITIVE_INFO_INIT(PRIORITY_LEVEL, PP_POLICY_MASK, 0,
677 			    RAPL_DOMAIN_REG_POLICY, ARBITRARY_UNIT, 0),
678 	[PSYS_POWER_LIMIT1] = PRIMITIVE_INFO_INIT(PSYS_POWER_LIMIT1, PSYS_POWER_LIMIT1_MASK, 0,
679 			    RAPL_DOMAIN_REG_LIMIT, POWER_UNIT, 0),
680 	[PSYS_POWER_LIMIT2] = PRIMITIVE_INFO_INIT(PSYS_POWER_LIMIT2, PSYS_POWER_LIMIT2_MASK, 32,
681 			    RAPL_DOMAIN_REG_LIMIT, POWER_UNIT, 0),
682 	[PSYS_PL1_ENABLE] = PRIMITIVE_INFO_INIT(PSYS_PL1_ENABLE, PSYS_POWER_LIMIT1_ENABLE, 17,
683 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
684 	[PSYS_PL2_ENABLE] = PRIMITIVE_INFO_INIT(PSYS_PL2_ENABLE, PSYS_POWER_LIMIT2_ENABLE, 49,
685 			    RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
686 	[PSYS_TIME_WINDOW1] = PRIMITIVE_INFO_INIT(PSYS_TIME_WINDOW1, PSYS_TIME_WINDOW1_MASK, 19,
687 			    RAPL_DOMAIN_REG_LIMIT, TIME_UNIT, 0),
688 	[PSYS_TIME_WINDOW2] = PRIMITIVE_INFO_INIT(PSYS_TIME_WINDOW2, PSYS_TIME_WINDOW2_MASK, 51,
689 			    RAPL_DOMAIN_REG_LIMIT, TIME_UNIT, 0),
690 	/* non-hardware */
691 	[AVERAGE_POWER] = PRIMITIVE_INFO_INIT(AVERAGE_POWER, 0, 0, 0, POWER_UNIT,
692 			    RAPL_PRIMITIVE_DERIVED),
693 };
694 
695 /* RAPL primitives for TPMI I/F */
696 static struct rapl_primitive_info rpi_tpmi[NR_RAPL_PRIMITIVES] = {
697 	/* name, mask, shift, msr index, unit divisor */
698 	[POWER_LIMIT1] = PRIMITIVE_INFO_INIT(POWER_LIMIT1, TPMI_POWER_LIMIT_MASK, 0,
699 		RAPL_DOMAIN_REG_LIMIT, POWER_UNIT, 0),
700 	[POWER_LIMIT2] = PRIMITIVE_INFO_INIT(POWER_LIMIT2, TPMI_POWER_LIMIT_MASK, 0,
701 		RAPL_DOMAIN_REG_PL2, POWER_UNIT, 0),
702 	[POWER_LIMIT4] = PRIMITIVE_INFO_INIT(POWER_LIMIT4, TPMI_POWER_LIMIT_MASK, 0,
703 		RAPL_DOMAIN_REG_PL4, POWER_UNIT, 0),
704 	[ENERGY_COUNTER] = PRIMITIVE_INFO_INIT(ENERGY_COUNTER, ENERGY_STATUS_MASK, 0,
705 		RAPL_DOMAIN_REG_STATUS, ENERGY_UNIT, 0),
706 	[PL1_LOCK] = PRIMITIVE_INFO_INIT(PL1_LOCK, POWER_HIGH_LOCK, 63,
707 		RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
708 	[PL2_LOCK] = PRIMITIVE_INFO_INIT(PL2_LOCK, POWER_HIGH_LOCK, 63,
709 		RAPL_DOMAIN_REG_PL2, ARBITRARY_UNIT, 0),
710 	[PL4_LOCK] = PRIMITIVE_INFO_INIT(PL4_LOCK, POWER_HIGH_LOCK, 63,
711 		RAPL_DOMAIN_REG_PL4, ARBITRARY_UNIT, 0),
712 	[PL1_ENABLE] = PRIMITIVE_INFO_INIT(PL1_ENABLE, TPMI_POWER_LIMIT_ENABLE, 62,
713 		RAPL_DOMAIN_REG_LIMIT, ARBITRARY_UNIT, 0),
714 	[PL2_ENABLE] = PRIMITIVE_INFO_INIT(PL2_ENABLE, TPMI_POWER_LIMIT_ENABLE, 62,
715 		RAPL_DOMAIN_REG_PL2, ARBITRARY_UNIT, 0),
716 	[PL4_ENABLE] = PRIMITIVE_INFO_INIT(PL4_ENABLE, TPMI_POWER_LIMIT_ENABLE, 62,
717 		RAPL_DOMAIN_REG_PL4, ARBITRARY_UNIT, 0),
718 	[TIME_WINDOW1] = PRIMITIVE_INFO_INIT(TIME_WINDOW1, TPMI_TIME_WINDOW_MASK, 18,
719 		RAPL_DOMAIN_REG_LIMIT, TIME_UNIT, 0),
720 	[TIME_WINDOW2] = PRIMITIVE_INFO_INIT(TIME_WINDOW2, TPMI_TIME_WINDOW_MASK, 18,
721 		RAPL_DOMAIN_REG_PL2, TIME_UNIT, 0),
722 	[THERMAL_SPEC_POWER] = PRIMITIVE_INFO_INIT(THERMAL_SPEC_POWER, TPMI_INFO_SPEC_MASK, 0,
723 		RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
724 	[MAX_POWER] = PRIMITIVE_INFO_INIT(MAX_POWER, TPMI_INFO_MAX_MASK, 36,
725 		RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
726 	[MIN_POWER] = PRIMITIVE_INFO_INIT(MIN_POWER, TPMI_INFO_MIN_MASK, 18,
727 		RAPL_DOMAIN_REG_INFO, POWER_UNIT, 0),
728 	[MAX_TIME_WINDOW] = PRIMITIVE_INFO_INIT(MAX_TIME_WINDOW, TPMI_INFO_MAX_TIME_WIN_MASK, 54,
729 		RAPL_DOMAIN_REG_INFO, TIME_UNIT, 0),
730 	[THROTTLED_TIME] = PRIMITIVE_INFO_INIT(THROTTLED_TIME, PERF_STATUS_THROTTLE_TIME_MASK, 0,
731 		RAPL_DOMAIN_REG_PERF, TIME_UNIT, 0),
732 	/* non-hardware */
733 	[AVERAGE_POWER] = PRIMITIVE_INFO_INIT(AVERAGE_POWER, 0, 0, 0,
734 		POWER_UNIT, RAPL_PRIMITIVE_DERIVED),
735 };
736 
737 static struct rapl_primitive_info *get_rpi(struct rapl_package *rp, int prim)
738 {
739 	struct rapl_primitive_info *rpi = rp->priv->rpi;
740 
741 	if (prim < 0 || prim > NR_RAPL_PRIMITIVES || !rpi)
742 		return NULL;
743 
744 	return &rpi[prim];
745 }
746 
747 static int rapl_config(struct rapl_package *rp)
748 {
749 	switch (rp->priv->type) {
750 	/* MMIO I/F shares the same register layout as MSR registers */
751 	case RAPL_IF_MMIO:
752 	case RAPL_IF_MSR:
753 		rp->priv->defaults = (void *)defaults_msr;
754 		rp->priv->rpi = (void *)rpi_msr;
755 		break;
756 	case RAPL_IF_TPMI:
757 		rp->priv->defaults = (void *)&defaults_tpmi;
758 		rp->priv->rpi = (void *)rpi_tpmi;
759 		break;
760 	default:
761 		return -EINVAL;
762 	}
763 
764 	/* defaults_msr can be NULL on unsupported platforms */
765 	if (!rp->priv->defaults || !rp->priv->rpi)
766 		return -ENODEV;
767 
768 	return 0;
769 }
770 
771 static enum rapl_primitives
772 prim_fixups(struct rapl_domain *rd, enum rapl_primitives prim)
773 {
774 	struct rapl_defaults *defaults = get_defaults(rd->rp);
775 
776 	if (!defaults->spr_psys_bits)
777 		return prim;
778 
779 	if (rd->id != RAPL_DOMAIN_PLATFORM)
780 		return prim;
781 
782 	switch (prim) {
783 	case POWER_LIMIT1:
784 		return PSYS_POWER_LIMIT1;
785 	case POWER_LIMIT2:
786 		return PSYS_POWER_LIMIT2;
787 	case PL1_ENABLE:
788 		return PSYS_PL1_ENABLE;
789 	case PL2_ENABLE:
790 		return PSYS_PL2_ENABLE;
791 	case TIME_WINDOW1:
792 		return PSYS_TIME_WINDOW1;
793 	case TIME_WINDOW2:
794 		return PSYS_TIME_WINDOW2;
795 	default:
796 		return prim;
797 	}
798 }
799 
800 /* Read primitive data based on its related struct rapl_primitive_info.
801  * if xlate flag is set, return translated data based on data units, i.e.
802  * time, energy, and power.
803  * RAPL MSRs are non-architectual and are laid out not consistently across
804  * domains. Here we use primitive info to allow writing consolidated access
805  * functions.
806  * For a given primitive, it is processed by MSR mask and shift. Unit conversion
807  * is pre-assigned based on RAPL unit MSRs read at init time.
808  * 63-------------------------- 31--------------------------- 0
809  * |                           xxxxx (mask)                   |
810  * |                                |<- shift ----------------|
811  * 63-------------------------- 31--------------------------- 0
812  */
813 static int rapl_read_data_raw(struct rapl_domain *rd,
814 			      enum rapl_primitives prim, bool xlate, u64 *data)
815 {
816 	u64 value;
817 	enum rapl_primitives prim_fixed = prim_fixups(rd, prim);
818 	struct rapl_primitive_info *rpi = get_rpi(rd->rp, prim_fixed);
819 	struct reg_action ra;
820 
821 	if (!rpi || !rpi->name || rpi->flag & RAPL_PRIMITIVE_DUMMY)
822 		return -EINVAL;
823 
824 	ra.reg = rd->regs[rpi->id];
825 	if (!ra.reg.val)
826 		return -EINVAL;
827 
828 	/* non-hardware data are collected by the polling thread */
829 	if (rpi->flag & RAPL_PRIMITIVE_DERIVED) {
830 		*data = rd->rdd.primitives[prim];
831 		return 0;
832 	}
833 
834 	ra.mask = rpi->mask;
835 
836 	if (rd->rp->priv->read_raw(get_rid(rd->rp), &ra)) {
837 		pr_debug("failed to read reg 0x%llx for %s:%s\n", ra.reg.val, rd->rp->name, rd->name);
838 		return -EIO;
839 	}
840 
841 	value = ra.value >> rpi->shift;
842 
843 	if (xlate)
844 		*data = rapl_unit_xlate(rd, rpi->unit, value, 0);
845 	else
846 		*data = value;
847 
848 	return 0;
849 }
850 
851 /* Similar use of primitive info in the read counterpart */
852 static int rapl_write_data_raw(struct rapl_domain *rd,
853 			       enum rapl_primitives prim,
854 			       unsigned long long value)
855 {
856 	enum rapl_primitives prim_fixed = prim_fixups(rd, prim);
857 	struct rapl_primitive_info *rpi = get_rpi(rd->rp, prim_fixed);
858 	u64 bits;
859 	struct reg_action ra;
860 	int ret;
861 
862 	if (!rpi || !rpi->name || rpi->flag & RAPL_PRIMITIVE_DUMMY)
863 		return -EINVAL;
864 
865 	bits = rapl_unit_xlate(rd, rpi->unit, value, 1);
866 	bits <<= rpi->shift;
867 	bits &= rpi->mask;
868 
869 	memset(&ra, 0, sizeof(ra));
870 
871 	ra.reg = rd->regs[rpi->id];
872 	ra.mask = rpi->mask;
873 	ra.value = bits;
874 
875 	ret = rd->rp->priv->write_raw(get_rid(rd->rp), &ra);
876 
877 	return ret;
878 }
879 
880 static int rapl_read_pl_data(struct rapl_domain *rd, int pl,
881 			      enum pl_prims pl_prim, bool xlate, u64 *data)
882 {
883 	enum rapl_primitives prim = get_pl_prim(rd, pl, pl_prim);
884 
885 	if (!is_pl_valid(rd, pl))
886 		return -EINVAL;
887 
888 	return rapl_read_data_raw(rd, prim, xlate, data);
889 }
890 
891 static int rapl_write_pl_data(struct rapl_domain *rd, int pl,
892 			       enum pl_prims pl_prim,
893 			       unsigned long long value)
894 {
895 	enum rapl_primitives prim = get_pl_prim(rd, pl, pl_prim);
896 
897 	if (!is_pl_valid(rd, pl))
898 		return -EINVAL;
899 
900 	if (rd->rpl[pl].locked) {
901 		pr_debug("%s:%s:%s locked by BIOS\n", rd->rp->name, rd->name, pl_names[pl]);
902 		return -EACCES;
903 	}
904 
905 	return rapl_write_data_raw(rd, prim, value);
906 }
907 /*
908  * Raw RAPL data stored in MSRs are in certain scales. We need to
909  * convert them into standard units based on the units reported in
910  * the RAPL unit MSRs. This is specific to CPUs as the method to
911  * calculate units differ on different CPUs.
912  * We convert the units to below format based on CPUs.
913  * i.e.
914  * energy unit: picoJoules  : Represented in picoJoules by default
915  * power unit : microWatts  : Represented in milliWatts by default
916  * time unit  : microseconds: Represented in seconds by default
917  */
918 static int rapl_check_unit_core(struct rapl_domain *rd)
919 {
920 	struct reg_action ra;
921 	u32 value;
922 
923 	ra.reg = rd->regs[RAPL_DOMAIN_REG_UNIT];
924 	ra.mask = ~0;
925 	if (rd->rp->priv->read_raw(get_rid(rd->rp), &ra)) {
926 		pr_err("Failed to read power unit REG 0x%llx on %s:%s, exit.\n",
927 			ra.reg.val, rd->rp->name, rd->name);
928 		return -ENODEV;
929 	}
930 
931 	value = (ra.value & ENERGY_UNIT_MASK) >> ENERGY_UNIT_OFFSET;
932 	rd->energy_unit = ENERGY_UNIT_SCALE * 1000000 / (1 << value);
933 
934 	value = (ra.value & POWER_UNIT_MASK) >> POWER_UNIT_OFFSET;
935 	rd->power_unit = 1000000 / (1 << value);
936 
937 	value = (ra.value & TIME_UNIT_MASK) >> TIME_UNIT_OFFSET;
938 	rd->time_unit = 1000000 / (1 << value);
939 
940 	pr_debug("Core CPU %s:%s energy=%dpJ, time=%dus, power=%duW\n",
941 		 rd->rp->name, rd->name, rd->energy_unit, rd->time_unit, rd->power_unit);
942 
943 	return 0;
944 }
945 
946 static int rapl_check_unit_atom(struct rapl_domain *rd)
947 {
948 	struct reg_action ra;
949 	u32 value;
950 
951 	ra.reg = rd->regs[RAPL_DOMAIN_REG_UNIT];
952 	ra.mask = ~0;
953 	if (rd->rp->priv->read_raw(get_rid(rd->rp), &ra)) {
954 		pr_err("Failed to read power unit REG 0x%llx on %s:%s, exit.\n",
955 			ra.reg.val, rd->rp->name, rd->name);
956 		return -ENODEV;
957 	}
958 
959 	value = (ra.value & ENERGY_UNIT_MASK) >> ENERGY_UNIT_OFFSET;
960 	rd->energy_unit = ENERGY_UNIT_SCALE * 1 << value;
961 
962 	value = (ra.value & POWER_UNIT_MASK) >> POWER_UNIT_OFFSET;
963 	rd->power_unit = (1 << value) * 1000;
964 
965 	value = (ra.value & TIME_UNIT_MASK) >> TIME_UNIT_OFFSET;
966 	rd->time_unit = 1000000 / (1 << value);
967 
968 	pr_debug("Atom %s:%s energy=%dpJ, time=%dus, power=%duW\n",
969 		 rd->rp->name, rd->name, rd->energy_unit, rd->time_unit, rd->power_unit);
970 
971 	return 0;
972 }
973 
974 static void power_limit_irq_save_cpu(void *info)
975 {
976 	u32 l, h = 0;
977 	struct rapl_package *rp = (struct rapl_package *)info;
978 
979 	/* save the state of PLN irq mask bit before disabling it */
980 	rdmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, &l, &h);
981 	if (!(rp->power_limit_irq & PACKAGE_PLN_INT_SAVED)) {
982 		rp->power_limit_irq = l & PACKAGE_THERM_INT_PLN_ENABLE;
983 		rp->power_limit_irq |= PACKAGE_PLN_INT_SAVED;
984 	}
985 	l &= ~PACKAGE_THERM_INT_PLN_ENABLE;
986 	wrmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, l, h);
987 }
988 
989 /* REVISIT:
990  * When package power limit is set artificially low by RAPL, LVT
991  * thermal interrupt for package power limit should be ignored
992  * since we are not really exceeding the real limit. The intention
993  * is to avoid excessive interrupts while we are trying to save power.
994  * A useful feature might be routing the package_power_limit interrupt
995  * to userspace via eventfd. once we have a usecase, this is simple
996  * to do by adding an atomic notifier.
997  */
998 
999 static void package_power_limit_irq_save(struct rapl_package *rp)
1000 {
1001 	if (rp->lead_cpu < 0)
1002 		return;
1003 
1004 	if (!boot_cpu_has(X86_FEATURE_PTS) || !boot_cpu_has(X86_FEATURE_PLN))
1005 		return;
1006 
1007 	smp_call_function_single(rp->lead_cpu, power_limit_irq_save_cpu, rp, 1);
1008 }
1009 
1010 /*
1011  * Restore per package power limit interrupt enable state. Called from cpu
1012  * hotplug code on package removal.
1013  */
1014 static void package_power_limit_irq_restore(struct rapl_package *rp)
1015 {
1016 	u32 l, h;
1017 
1018 	if (rp->lead_cpu < 0)
1019 		return;
1020 
1021 	if (!boot_cpu_has(X86_FEATURE_PTS) || !boot_cpu_has(X86_FEATURE_PLN))
1022 		return;
1023 
1024 	/* irq enable state not saved, nothing to restore */
1025 	if (!(rp->power_limit_irq & PACKAGE_PLN_INT_SAVED))
1026 		return;
1027 
1028 	rdmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, &l, &h);
1029 
1030 	if (rp->power_limit_irq & PACKAGE_THERM_INT_PLN_ENABLE)
1031 		l |= PACKAGE_THERM_INT_PLN_ENABLE;
1032 	else
1033 		l &= ~PACKAGE_THERM_INT_PLN_ENABLE;
1034 
1035 	wrmsr_safe(MSR_IA32_PACKAGE_THERM_INTERRUPT, l, h);
1036 }
1037 
1038 static void set_floor_freq_default(struct rapl_domain *rd, bool mode)
1039 {
1040 	int i;
1041 
1042 	/* always enable clamp such that p-state can go below OS requested
1043 	 * range. power capping priority over guranteed frequency.
1044 	 */
1045 	rapl_write_pl_data(rd, POWER_LIMIT1, PL_CLAMP, mode);
1046 
1047 	for (i = POWER_LIMIT2; i < NR_POWER_LIMITS; i++) {
1048 		rapl_write_pl_data(rd, i, PL_ENABLE, mode);
1049 		rapl_write_pl_data(rd, i, PL_CLAMP, mode);
1050 	}
1051 }
1052 
1053 static void set_floor_freq_atom(struct rapl_domain *rd, bool enable)
1054 {
1055 	static u32 power_ctrl_orig_val;
1056 	struct rapl_defaults *defaults = get_defaults(rd->rp);
1057 	u32 mdata;
1058 
1059 	if (!defaults->floor_freq_reg_addr) {
1060 		pr_err("Invalid floor frequency config register\n");
1061 		return;
1062 	}
1063 
1064 	if (!power_ctrl_orig_val)
1065 		iosf_mbi_read(BT_MBI_UNIT_PMC, MBI_CR_READ,
1066 			      defaults->floor_freq_reg_addr,
1067 			      &power_ctrl_orig_val);
1068 	mdata = power_ctrl_orig_val;
1069 	if (enable) {
1070 		mdata &= ~(0x7f << 8);
1071 		mdata |= 1 << 8;
1072 	}
1073 	iosf_mbi_write(BT_MBI_UNIT_PMC, MBI_CR_WRITE,
1074 		       defaults->floor_freq_reg_addr, mdata);
1075 }
1076 
1077 static u64 rapl_compute_time_window_core(struct rapl_domain *rd, u64 value,
1078 					 bool to_raw)
1079 {
1080 	u64 f, y;		/* fraction and exp. used for time unit */
1081 
1082 	/*
1083 	 * Special processing based on 2^Y*(1+F/4), refer
1084 	 * to Intel Software Developer's manual Vol.3B: CH 14.9.3.
1085 	 */
1086 	if (!to_raw) {
1087 		f = (value & 0x60) >> 5;
1088 		y = value & 0x1f;
1089 		value = (1 << y) * (4 + f) * rd->time_unit / 4;
1090 	} else {
1091 		if (value < rd->time_unit)
1092 			return 0;
1093 
1094 		do_div(value, rd->time_unit);
1095 		y = ilog2(value);
1096 
1097 		/*
1098 		 * The target hardware field is 7 bits wide, so return all ones
1099 		 * if the exponent is too large.
1100 		 */
1101 		if (y > 0x1f)
1102 			return 0x7f;
1103 
1104 		f = div64_u64(4 * (value - (1ULL << y)), 1ULL << y);
1105 		value = (y & 0x1f) | ((f & 0x3) << 5);
1106 	}
1107 	return value;
1108 }
1109 
1110 static u64 rapl_compute_time_window_atom(struct rapl_domain *rd, u64 value,
1111 					 bool to_raw)
1112 {
1113 	/*
1114 	 * Atom time unit encoding is straight forward val * time_unit,
1115 	 * where time_unit is default to 1 sec. Never 0.
1116 	 */
1117 	if (!to_raw)
1118 		return (value) ? value * rd->time_unit : rd->time_unit;
1119 
1120 	value = div64_u64(value, rd->time_unit);
1121 
1122 	return value;
1123 }
1124 
1125 /* TPMI Unit register has different layout */
1126 #define TPMI_POWER_UNIT_OFFSET	POWER_UNIT_OFFSET
1127 #define TPMI_POWER_UNIT_MASK	POWER_UNIT_MASK
1128 #define TPMI_ENERGY_UNIT_OFFSET	0x06
1129 #define TPMI_ENERGY_UNIT_MASK	0x7C0
1130 #define TPMI_TIME_UNIT_OFFSET	0x0C
1131 #define TPMI_TIME_UNIT_MASK	0xF000
1132 
1133 static int rapl_check_unit_tpmi(struct rapl_domain *rd)
1134 {
1135 	struct reg_action ra;
1136 	u32 value;
1137 
1138 	ra.reg = rd->regs[RAPL_DOMAIN_REG_UNIT];
1139 	ra.mask = ~0;
1140 	if (rd->rp->priv->read_raw(get_rid(rd->rp), &ra)) {
1141 		pr_err("Failed to read power unit REG 0x%llx on %s:%s, exit.\n",
1142 			ra.reg.val, rd->rp->name, rd->name);
1143 		return -ENODEV;
1144 	}
1145 
1146 	value = (ra.value & TPMI_ENERGY_UNIT_MASK) >> TPMI_ENERGY_UNIT_OFFSET;
1147 	rd->energy_unit = ENERGY_UNIT_SCALE * 1000000 / (1 << value);
1148 
1149 	value = (ra.value & TPMI_POWER_UNIT_MASK) >> TPMI_POWER_UNIT_OFFSET;
1150 	rd->power_unit = 1000000 / (1 << value);
1151 
1152 	value = (ra.value & TPMI_TIME_UNIT_MASK) >> TPMI_TIME_UNIT_OFFSET;
1153 	rd->time_unit = 1000000 / (1 << value);
1154 
1155 	pr_debug("Core CPU %s:%s energy=%dpJ, time=%dus, power=%duW\n",
1156 		 rd->rp->name, rd->name, rd->energy_unit, rd->time_unit, rd->power_unit);
1157 
1158 	return 0;
1159 }
1160 
1161 static const struct rapl_defaults defaults_tpmi = {
1162 	.check_unit = rapl_check_unit_tpmi,
1163 	/* Reuse existing logic, ignore the PL_CLAMP failures and enable all Power Limits */
1164 	.set_floor_freq = set_floor_freq_default,
1165 	.compute_time_window = rapl_compute_time_window_core,
1166 };
1167 
1168 static const struct rapl_defaults rapl_defaults_core = {
1169 	.floor_freq_reg_addr = 0,
1170 	.check_unit = rapl_check_unit_core,
1171 	.set_floor_freq = set_floor_freq_default,
1172 	.compute_time_window = rapl_compute_time_window_core,
1173 };
1174 
1175 static const struct rapl_defaults rapl_defaults_hsw_server = {
1176 	.check_unit = rapl_check_unit_core,
1177 	.set_floor_freq = set_floor_freq_default,
1178 	.compute_time_window = rapl_compute_time_window_core,
1179 	.dram_domain_energy_unit = 15300,
1180 };
1181 
1182 static const struct rapl_defaults rapl_defaults_spr_server = {
1183 	.check_unit = rapl_check_unit_core,
1184 	.set_floor_freq = set_floor_freq_default,
1185 	.compute_time_window = rapl_compute_time_window_core,
1186 	.psys_domain_energy_unit = 1000000000,
1187 	.spr_psys_bits = true,
1188 };
1189 
1190 static const struct rapl_defaults rapl_defaults_byt = {
1191 	.floor_freq_reg_addr = IOSF_CPU_POWER_BUDGET_CTL_BYT,
1192 	.check_unit = rapl_check_unit_atom,
1193 	.set_floor_freq = set_floor_freq_atom,
1194 	.compute_time_window = rapl_compute_time_window_atom,
1195 };
1196 
1197 static const struct rapl_defaults rapl_defaults_tng = {
1198 	.floor_freq_reg_addr = IOSF_CPU_POWER_BUDGET_CTL_TNG,
1199 	.check_unit = rapl_check_unit_atom,
1200 	.set_floor_freq = set_floor_freq_atom,
1201 	.compute_time_window = rapl_compute_time_window_atom,
1202 };
1203 
1204 static const struct rapl_defaults rapl_defaults_ann = {
1205 	.floor_freq_reg_addr = 0,
1206 	.check_unit = rapl_check_unit_atom,
1207 	.set_floor_freq = NULL,
1208 	.compute_time_window = rapl_compute_time_window_atom,
1209 };
1210 
1211 static const struct rapl_defaults rapl_defaults_cht = {
1212 	.floor_freq_reg_addr = 0,
1213 	.check_unit = rapl_check_unit_atom,
1214 	.set_floor_freq = NULL,
1215 	.compute_time_window = rapl_compute_time_window_atom,
1216 };
1217 
1218 static const struct rapl_defaults rapl_defaults_amd = {
1219 	.check_unit = rapl_check_unit_core,
1220 };
1221 
1222 static const struct x86_cpu_id rapl_ids[] __initconst = {
1223 	X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE,		&rapl_defaults_core),
1224 	X86_MATCH_INTEL_FAM6_MODEL(SANDYBRIDGE_X,	&rapl_defaults_core),
1225 
1226 	X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE,		&rapl_defaults_core),
1227 	X86_MATCH_INTEL_FAM6_MODEL(IVYBRIDGE_X,		&rapl_defaults_core),
1228 
1229 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL,		&rapl_defaults_core),
1230 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_L,		&rapl_defaults_core),
1231 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_G,		&rapl_defaults_core),
1232 	X86_MATCH_INTEL_FAM6_MODEL(HASWELL_X,		&rapl_defaults_hsw_server),
1233 
1234 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL,		&rapl_defaults_core),
1235 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_G,		&rapl_defaults_core),
1236 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_D,		&rapl_defaults_core),
1237 	X86_MATCH_INTEL_FAM6_MODEL(BROADWELL_X,		&rapl_defaults_hsw_server),
1238 
1239 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE,		&rapl_defaults_core),
1240 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_L,		&rapl_defaults_core),
1241 	X86_MATCH_INTEL_FAM6_MODEL(SKYLAKE_X,		&rapl_defaults_hsw_server),
1242 	X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE_L,		&rapl_defaults_core),
1243 	X86_MATCH_INTEL_FAM6_MODEL(KABYLAKE,		&rapl_defaults_core),
1244 	X86_MATCH_INTEL_FAM6_MODEL(CANNONLAKE_L,	&rapl_defaults_core),
1245 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_L,		&rapl_defaults_core),
1246 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE,		&rapl_defaults_core),
1247 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_NNPI,	&rapl_defaults_core),
1248 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X,		&rapl_defaults_hsw_server),
1249 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D,		&rapl_defaults_hsw_server),
1250 	X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE_L,		&rapl_defaults_core),
1251 	X86_MATCH_INTEL_FAM6_MODEL(COMETLAKE,		&rapl_defaults_core),
1252 	X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE_L,		&rapl_defaults_core),
1253 	X86_MATCH_INTEL_FAM6_MODEL(TIGERLAKE,		&rapl_defaults_core),
1254 	X86_MATCH_INTEL_FAM6_MODEL(ROCKETLAKE,		&rapl_defaults_core),
1255 	X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE,		&rapl_defaults_core),
1256 	X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE_L,		&rapl_defaults_core),
1257 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GRACEMONT,	&rapl_defaults_core),
1258 	X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE,		&rapl_defaults_core),
1259 	X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_P,        &rapl_defaults_core),
1260 	X86_MATCH_INTEL_FAM6_MODEL(RAPTORLAKE_S,	&rapl_defaults_core),
1261 	X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE,		&rapl_defaults_core),
1262 	X86_MATCH_INTEL_FAM6_MODEL(METEORLAKE_L,	&rapl_defaults_core),
1263 	X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X,	&rapl_defaults_spr_server),
1264 	X86_MATCH_INTEL_FAM6_MODEL(EMERALDRAPIDS_X,	&rapl_defaults_spr_server),
1265 	X86_MATCH_INTEL_FAM6_MODEL(LUNARLAKE_M,		&rapl_defaults_core),
1266 	X86_MATCH_INTEL_FAM6_MODEL(ARROWLAKE,		&rapl_defaults_core),
1267 	X86_MATCH_INTEL_FAM6_MODEL(LAKEFIELD,		&rapl_defaults_core),
1268 
1269 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT,	&rapl_defaults_byt),
1270 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_AIRMONT,	&rapl_defaults_cht),
1271 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT_MID,	&rapl_defaults_tng),
1272 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_AIRMONT_MID,	&rapl_defaults_ann),
1273 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT,	&rapl_defaults_core),
1274 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_PLUS,	&rapl_defaults_core),
1275 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_D,	&rapl_defaults_core),
1276 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT,	&rapl_defaults_core),
1277 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_D,	&rapl_defaults_core),
1278 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_L,	&rapl_defaults_core),
1279 
1280 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNL,	&rapl_defaults_hsw_server),
1281 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNM,	&rapl_defaults_hsw_server),
1282 
1283 	X86_MATCH_VENDOR_FAM(AMD, 0x17, &rapl_defaults_amd),
1284 	X86_MATCH_VENDOR_FAM(AMD, 0x19, &rapl_defaults_amd),
1285 	X86_MATCH_VENDOR_FAM(HYGON, 0x18, &rapl_defaults_amd),
1286 	{}
1287 };
1288 MODULE_DEVICE_TABLE(x86cpu, rapl_ids);
1289 
1290 /* Read once for all raw primitive data for domains */
1291 static void rapl_update_domain_data(struct rapl_package *rp)
1292 {
1293 	int dmn, prim;
1294 	u64 val;
1295 
1296 	for (dmn = 0; dmn < rp->nr_domains; dmn++) {
1297 		pr_debug("update %s domain %s data\n", rp->name,
1298 			 rp->domains[dmn].name);
1299 		/* exclude non-raw primitives */
1300 		for (prim = 0; prim < NR_RAW_PRIMITIVES; prim++) {
1301 			struct rapl_primitive_info *rpi = get_rpi(rp, prim);
1302 
1303 			if (!rapl_read_data_raw(&rp->domains[dmn], prim,
1304 						rpi->unit, &val))
1305 				rp->domains[dmn].rdd.primitives[prim] = val;
1306 		}
1307 	}
1308 
1309 }
1310 
1311 static int rapl_package_register_powercap(struct rapl_package *rp)
1312 {
1313 	struct rapl_domain *rd;
1314 	struct powercap_zone *power_zone = NULL;
1315 	int nr_pl, ret;
1316 
1317 	/* Update the domain data of the new package */
1318 	rapl_update_domain_data(rp);
1319 
1320 	/* first we register package domain as the parent zone */
1321 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1322 		if (rd->id == RAPL_DOMAIN_PACKAGE) {
1323 			nr_pl = find_nr_power_limit(rd);
1324 			pr_debug("register package domain %s\n", rp->name);
1325 			power_zone = powercap_register_zone(&rd->power_zone,
1326 					    rp->priv->control_type, rp->name,
1327 					    NULL, &zone_ops[rd->id], nr_pl,
1328 					    &constraint_ops);
1329 			if (IS_ERR(power_zone)) {
1330 				pr_debug("failed to register power zone %s\n",
1331 					 rp->name);
1332 				return PTR_ERR(power_zone);
1333 			}
1334 			/* track parent zone in per package/socket data */
1335 			rp->power_zone = power_zone;
1336 			/* done, only one package domain per socket */
1337 			break;
1338 		}
1339 	}
1340 	if (!power_zone) {
1341 		pr_err("no package domain found, unknown topology!\n");
1342 		return -ENODEV;
1343 	}
1344 	/* now register domains as children of the socket/package */
1345 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1346 		struct powercap_zone *parent = rp->power_zone;
1347 
1348 		if (rd->id == RAPL_DOMAIN_PACKAGE)
1349 			continue;
1350 		if (rd->id == RAPL_DOMAIN_PLATFORM)
1351 			parent = NULL;
1352 		/* number of power limits per domain varies */
1353 		nr_pl = find_nr_power_limit(rd);
1354 		power_zone = powercap_register_zone(&rd->power_zone,
1355 						    rp->priv->control_type,
1356 						    rd->name, parent,
1357 						    &zone_ops[rd->id], nr_pl,
1358 						    &constraint_ops);
1359 
1360 		if (IS_ERR(power_zone)) {
1361 			pr_debug("failed to register power_zone, %s:%s\n",
1362 				 rp->name, rd->name);
1363 			ret = PTR_ERR(power_zone);
1364 			goto err_cleanup;
1365 		}
1366 	}
1367 	return 0;
1368 
1369 err_cleanup:
1370 	/*
1371 	 * Clean up previously initialized domains within the package if we
1372 	 * failed after the first domain setup.
1373 	 */
1374 	while (--rd >= rp->domains) {
1375 		pr_debug("unregister %s domain %s\n", rp->name, rd->name);
1376 		powercap_unregister_zone(rp->priv->control_type,
1377 					 &rd->power_zone);
1378 	}
1379 
1380 	return ret;
1381 }
1382 
1383 static int rapl_check_domain(int domain, struct rapl_package *rp)
1384 {
1385 	struct reg_action ra;
1386 
1387 	switch (domain) {
1388 	case RAPL_DOMAIN_PACKAGE:
1389 	case RAPL_DOMAIN_PP0:
1390 	case RAPL_DOMAIN_PP1:
1391 	case RAPL_DOMAIN_DRAM:
1392 	case RAPL_DOMAIN_PLATFORM:
1393 		ra.reg = rp->priv->regs[domain][RAPL_DOMAIN_REG_STATUS];
1394 		break;
1395 	default:
1396 		pr_err("invalid domain id %d\n", domain);
1397 		return -EINVAL;
1398 	}
1399 	/* make sure domain counters are available and contains non-zero
1400 	 * values, otherwise skip it.
1401 	 */
1402 
1403 	ra.mask = ENERGY_STATUS_MASK;
1404 	if (rp->priv->read_raw(get_rid(rp), &ra) || !ra.value)
1405 		return -ENODEV;
1406 
1407 	return 0;
1408 }
1409 
1410 /*
1411  * Get per domain energy/power/time unit.
1412  * RAPL Interfaces without per domain unit register will use the package
1413  * scope unit register to set per domain units.
1414  */
1415 static int rapl_get_domain_unit(struct rapl_domain *rd)
1416 {
1417 	struct rapl_defaults *defaults = get_defaults(rd->rp);
1418 	int ret;
1419 
1420 	if (!rd->regs[RAPL_DOMAIN_REG_UNIT].val) {
1421 		if (!rd->rp->priv->reg_unit.val) {
1422 			pr_err("No valid Unit register found\n");
1423 			return -ENODEV;
1424 		}
1425 		rd->regs[RAPL_DOMAIN_REG_UNIT] = rd->rp->priv->reg_unit;
1426 	}
1427 
1428 	if (!defaults->check_unit) {
1429 		pr_err("missing .check_unit() callback\n");
1430 		return -ENODEV;
1431 	}
1432 
1433 	ret = defaults->check_unit(rd);
1434 	if (ret)
1435 		return ret;
1436 
1437 	if (rd->id == RAPL_DOMAIN_DRAM && defaults->dram_domain_energy_unit)
1438 		rd->energy_unit = defaults->dram_domain_energy_unit;
1439 	if (rd->id == RAPL_DOMAIN_PLATFORM && defaults->psys_domain_energy_unit)
1440 		rd->energy_unit = defaults->psys_domain_energy_unit;
1441 	return 0;
1442 }
1443 
1444 /*
1445  * Check if power limits are available. Two cases when they are not available:
1446  * 1. Locked by BIOS, in this case we still provide read-only access so that
1447  *    users can see what limit is set by the BIOS.
1448  * 2. Some CPUs make some domains monitoring only which means PLx MSRs may not
1449  *    exist at all. In this case, we do not show the constraints in powercap.
1450  *
1451  * Called after domains are detected and initialized.
1452  */
1453 static void rapl_detect_powerlimit(struct rapl_domain *rd)
1454 {
1455 	u64 val64;
1456 	int i;
1457 
1458 	for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1459 		if (!rapl_read_pl_data(rd, i, PL_LOCK, false, &val64)) {
1460 			if (val64) {
1461 				rd->rpl[i].locked = true;
1462 				pr_info("%s:%s:%s locked by BIOS\n",
1463 					rd->rp->name, rd->name, pl_names[i]);
1464 			}
1465 		}
1466 
1467 		if (rapl_read_pl_data(rd, i, PL_LIMIT, false, &val64))
1468 			rd->rpl[i].name = NULL;
1469 	}
1470 }
1471 
1472 /* Detect active and valid domains for the given CPU, caller must
1473  * ensure the CPU belongs to the targeted package and CPU hotlug is disabled.
1474  */
1475 static int rapl_detect_domains(struct rapl_package *rp)
1476 {
1477 	struct rapl_domain *rd;
1478 	int i;
1479 
1480 	for (i = 0; i < RAPL_DOMAIN_MAX; i++) {
1481 		/* use physical package id to read counters */
1482 		if (!rapl_check_domain(i, rp)) {
1483 			rp->domain_map |= 1 << i;
1484 			pr_info("Found RAPL domain %s\n", rapl_domain_names[i]);
1485 		}
1486 	}
1487 	rp->nr_domains = bitmap_weight(&rp->domain_map, RAPL_DOMAIN_MAX);
1488 	if (!rp->nr_domains) {
1489 		pr_debug("no valid rapl domains found in %s\n", rp->name);
1490 		return -ENODEV;
1491 	}
1492 	pr_debug("found %d domains on %s\n", rp->nr_domains, rp->name);
1493 
1494 	rp->domains = kcalloc(rp->nr_domains, sizeof(struct rapl_domain),
1495 			      GFP_KERNEL);
1496 	if (!rp->domains)
1497 		return -ENOMEM;
1498 
1499 	rapl_init_domains(rp);
1500 
1501 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1502 		rapl_get_domain_unit(rd);
1503 		rapl_detect_powerlimit(rd);
1504 	}
1505 
1506 	return 0;
1507 }
1508 
1509 /* called from CPU hotplug notifier, hotplug lock held */
1510 void rapl_remove_package_cpuslocked(struct rapl_package *rp)
1511 {
1512 	struct rapl_domain *rd, *rd_package = NULL;
1513 
1514 	package_power_limit_irq_restore(rp);
1515 
1516 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1517 		int i;
1518 
1519 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1520 			rapl_write_pl_data(rd, i, PL_ENABLE, 0);
1521 			rapl_write_pl_data(rd, i, PL_CLAMP, 0);
1522 		}
1523 
1524 		if (rd->id == RAPL_DOMAIN_PACKAGE) {
1525 			rd_package = rd;
1526 			continue;
1527 		}
1528 		pr_debug("remove package, undo power limit on %s: %s\n",
1529 			 rp->name, rd->name);
1530 		powercap_unregister_zone(rp->priv->control_type,
1531 					 &rd->power_zone);
1532 	}
1533 	/* do parent zone last */
1534 	powercap_unregister_zone(rp->priv->control_type,
1535 				 &rd_package->power_zone);
1536 	list_del(&rp->plist);
1537 	kfree(rp);
1538 }
1539 EXPORT_SYMBOL_GPL(rapl_remove_package_cpuslocked);
1540 
1541 void rapl_remove_package(struct rapl_package *rp)
1542 {
1543 	guard(cpus_read_lock)();
1544 	rapl_remove_package_cpuslocked(rp);
1545 }
1546 EXPORT_SYMBOL_GPL(rapl_remove_package);
1547 
1548 /* caller to ensure CPU hotplug lock is held */
1549 struct rapl_package *rapl_find_package_domain_cpuslocked(int id, struct rapl_if_priv *priv,
1550 							 bool id_is_cpu)
1551 {
1552 	struct rapl_package *rp;
1553 	int uid;
1554 
1555 	if (id_is_cpu)
1556 		uid = topology_logical_die_id(id);
1557 	else
1558 		uid = id;
1559 
1560 	list_for_each_entry(rp, &rapl_packages, plist) {
1561 		if (rp->id == uid
1562 		    && rp->priv->control_type == priv->control_type)
1563 			return rp;
1564 	}
1565 
1566 	return NULL;
1567 }
1568 EXPORT_SYMBOL_GPL(rapl_find_package_domain_cpuslocked);
1569 
1570 struct rapl_package *rapl_find_package_domain(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1571 {
1572 	guard(cpus_read_lock)();
1573 	return rapl_find_package_domain_cpuslocked(id, priv, id_is_cpu);
1574 }
1575 EXPORT_SYMBOL_GPL(rapl_find_package_domain);
1576 
1577 /* called from CPU hotplug notifier, hotplug lock held */
1578 struct rapl_package *rapl_add_package_cpuslocked(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1579 {
1580 	struct rapl_package *rp;
1581 	int ret;
1582 
1583 	rp = kzalloc(sizeof(struct rapl_package), GFP_KERNEL);
1584 	if (!rp)
1585 		return ERR_PTR(-ENOMEM);
1586 
1587 	if (id_is_cpu) {
1588 		rp->id = topology_logical_die_id(id);
1589 		rp->lead_cpu = id;
1590 		if (topology_max_dies_per_package() > 1)
1591 			snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d-die-%d",
1592 				 topology_physical_package_id(id), topology_die_id(id));
1593 		else
1594 			snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d",
1595 				 topology_physical_package_id(id));
1596 	} else {
1597 		rp->id = id;
1598 		rp->lead_cpu = -1;
1599 		snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d", id);
1600 	}
1601 
1602 	rp->priv = priv;
1603 	ret = rapl_config(rp);
1604 	if (ret)
1605 		goto err_free_package;
1606 
1607 	/* check if the package contains valid domains */
1608 	if (rapl_detect_domains(rp)) {
1609 		ret = -ENODEV;
1610 		goto err_free_package;
1611 	}
1612 	ret = rapl_package_register_powercap(rp);
1613 	if (!ret) {
1614 		INIT_LIST_HEAD(&rp->plist);
1615 		list_add(&rp->plist, &rapl_packages);
1616 		return rp;
1617 	}
1618 
1619 err_free_package:
1620 	kfree(rp->domains);
1621 	kfree(rp);
1622 	return ERR_PTR(ret);
1623 }
1624 EXPORT_SYMBOL_GPL(rapl_add_package_cpuslocked);
1625 
1626 struct rapl_package *rapl_add_package(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1627 {
1628 	guard(cpus_read_lock)();
1629 	return rapl_add_package_cpuslocked(id, priv, id_is_cpu);
1630 }
1631 EXPORT_SYMBOL_GPL(rapl_add_package);
1632 
1633 static void power_limit_state_save(void)
1634 {
1635 	struct rapl_package *rp;
1636 	struct rapl_domain *rd;
1637 	int ret, i;
1638 
1639 	cpus_read_lock();
1640 	list_for_each_entry(rp, &rapl_packages, plist) {
1641 		if (!rp->power_zone)
1642 			continue;
1643 		rd = power_zone_to_rapl_domain(rp->power_zone);
1644 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1645 			ret = rapl_read_pl_data(rd, i, PL_LIMIT, true,
1646 						 &rd->rpl[i].last_power_limit);
1647 			if (ret)
1648 				rd->rpl[i].last_power_limit = 0;
1649 		}
1650 	}
1651 	cpus_read_unlock();
1652 }
1653 
1654 static void power_limit_state_restore(void)
1655 {
1656 	struct rapl_package *rp;
1657 	struct rapl_domain *rd;
1658 	int i;
1659 
1660 	cpus_read_lock();
1661 	list_for_each_entry(rp, &rapl_packages, plist) {
1662 		if (!rp->power_zone)
1663 			continue;
1664 		rd = power_zone_to_rapl_domain(rp->power_zone);
1665 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++)
1666 			if (rd->rpl[i].last_power_limit)
1667 				rapl_write_pl_data(rd, i, PL_LIMIT,
1668 					       rd->rpl[i].last_power_limit);
1669 	}
1670 	cpus_read_unlock();
1671 }
1672 
1673 static int rapl_pm_callback(struct notifier_block *nb,
1674 			    unsigned long mode, void *_unused)
1675 {
1676 	switch (mode) {
1677 	case PM_SUSPEND_PREPARE:
1678 		power_limit_state_save();
1679 		break;
1680 	case PM_POST_SUSPEND:
1681 		power_limit_state_restore();
1682 		break;
1683 	}
1684 	return NOTIFY_OK;
1685 }
1686 
1687 static struct notifier_block rapl_pm_notifier = {
1688 	.notifier_call = rapl_pm_callback,
1689 };
1690 
1691 static struct platform_device *rapl_msr_platdev;
1692 
1693 static int __init rapl_init(void)
1694 {
1695 	const struct x86_cpu_id *id;
1696 	int ret;
1697 
1698 	id = x86_match_cpu(rapl_ids);
1699 	if (id) {
1700 		defaults_msr = (struct rapl_defaults *)id->driver_data;
1701 
1702 		rapl_msr_platdev = platform_device_alloc("intel_rapl_msr", 0);
1703 		if (!rapl_msr_platdev)
1704 			return -ENOMEM;
1705 
1706 		ret = platform_device_add(rapl_msr_platdev);
1707 		if (ret) {
1708 			platform_device_put(rapl_msr_platdev);
1709 			return ret;
1710 		}
1711 	}
1712 
1713 	ret = register_pm_notifier(&rapl_pm_notifier);
1714 	if (ret && rapl_msr_platdev) {
1715 		platform_device_del(rapl_msr_platdev);
1716 		platform_device_put(rapl_msr_platdev);
1717 	}
1718 
1719 	return ret;
1720 }
1721 
1722 static void __exit rapl_exit(void)
1723 {
1724 	platform_device_unregister(rapl_msr_platdev);
1725 	unregister_pm_notifier(&rapl_pm_notifier);
1726 }
1727 
1728 fs_initcall(rapl_init);
1729 module_exit(rapl_exit);
1730 
1731 MODULE_DESCRIPTION("Intel Runtime Average Power Limit (RAPL) common code");
1732 MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@intel.com>");
1733 MODULE_LICENSE("GPL v2");
1734