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(LAKEFIELD,		&rapl_defaults_core),
1266 
1267 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT,	&rapl_defaults_byt),
1268 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_AIRMONT,	&rapl_defaults_cht),
1269 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_SILVERMONT_MID,	&rapl_defaults_tng),
1270 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_AIRMONT_MID,	&rapl_defaults_ann),
1271 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT,	&rapl_defaults_core),
1272 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_PLUS,	&rapl_defaults_core),
1273 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_GOLDMONT_D,	&rapl_defaults_core),
1274 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT,	&rapl_defaults_core),
1275 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_D,	&rapl_defaults_core),
1276 	X86_MATCH_INTEL_FAM6_MODEL(ATOM_TREMONT_L,	&rapl_defaults_core),
1277 
1278 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNL,	&rapl_defaults_hsw_server),
1279 	X86_MATCH_INTEL_FAM6_MODEL(XEON_PHI_KNM,	&rapl_defaults_hsw_server),
1280 
1281 	X86_MATCH_VENDOR_FAM(AMD, 0x17, &rapl_defaults_amd),
1282 	X86_MATCH_VENDOR_FAM(AMD, 0x19, &rapl_defaults_amd),
1283 	X86_MATCH_VENDOR_FAM(HYGON, 0x18, &rapl_defaults_amd),
1284 	{}
1285 };
1286 MODULE_DEVICE_TABLE(x86cpu, rapl_ids);
1287 
1288 /* Read once for all raw primitive data for domains */
1289 static void rapl_update_domain_data(struct rapl_package *rp)
1290 {
1291 	int dmn, prim;
1292 	u64 val;
1293 
1294 	for (dmn = 0; dmn < rp->nr_domains; dmn++) {
1295 		pr_debug("update %s domain %s data\n", rp->name,
1296 			 rp->domains[dmn].name);
1297 		/* exclude non-raw primitives */
1298 		for (prim = 0; prim < NR_RAW_PRIMITIVES; prim++) {
1299 			struct rapl_primitive_info *rpi = get_rpi(rp, prim);
1300 
1301 			if (!rapl_read_data_raw(&rp->domains[dmn], prim,
1302 						rpi->unit, &val))
1303 				rp->domains[dmn].rdd.primitives[prim] = val;
1304 		}
1305 	}
1306 
1307 }
1308 
1309 static int rapl_package_register_powercap(struct rapl_package *rp)
1310 {
1311 	struct rapl_domain *rd;
1312 	struct powercap_zone *power_zone = NULL;
1313 	int nr_pl, ret;
1314 
1315 	/* Update the domain data of the new package */
1316 	rapl_update_domain_data(rp);
1317 
1318 	/* first we register package domain as the parent zone */
1319 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1320 		if (rd->id == RAPL_DOMAIN_PACKAGE) {
1321 			nr_pl = find_nr_power_limit(rd);
1322 			pr_debug("register package domain %s\n", rp->name);
1323 			power_zone = powercap_register_zone(&rd->power_zone,
1324 					    rp->priv->control_type, rp->name,
1325 					    NULL, &zone_ops[rd->id], nr_pl,
1326 					    &constraint_ops);
1327 			if (IS_ERR(power_zone)) {
1328 				pr_debug("failed to register power zone %s\n",
1329 					 rp->name);
1330 				return PTR_ERR(power_zone);
1331 			}
1332 			/* track parent zone in per package/socket data */
1333 			rp->power_zone = power_zone;
1334 			/* done, only one package domain per socket */
1335 			break;
1336 		}
1337 	}
1338 	if (!power_zone) {
1339 		pr_err("no package domain found, unknown topology!\n");
1340 		return -ENODEV;
1341 	}
1342 	/* now register domains as children of the socket/package */
1343 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1344 		struct powercap_zone *parent = rp->power_zone;
1345 
1346 		if (rd->id == RAPL_DOMAIN_PACKAGE)
1347 			continue;
1348 		if (rd->id == RAPL_DOMAIN_PLATFORM)
1349 			parent = NULL;
1350 		/* number of power limits per domain varies */
1351 		nr_pl = find_nr_power_limit(rd);
1352 		power_zone = powercap_register_zone(&rd->power_zone,
1353 						    rp->priv->control_type,
1354 						    rd->name, parent,
1355 						    &zone_ops[rd->id], nr_pl,
1356 						    &constraint_ops);
1357 
1358 		if (IS_ERR(power_zone)) {
1359 			pr_debug("failed to register power_zone, %s:%s\n",
1360 				 rp->name, rd->name);
1361 			ret = PTR_ERR(power_zone);
1362 			goto err_cleanup;
1363 		}
1364 	}
1365 	return 0;
1366 
1367 err_cleanup:
1368 	/*
1369 	 * Clean up previously initialized domains within the package if we
1370 	 * failed after the first domain setup.
1371 	 */
1372 	while (--rd >= rp->domains) {
1373 		pr_debug("unregister %s domain %s\n", rp->name, rd->name);
1374 		powercap_unregister_zone(rp->priv->control_type,
1375 					 &rd->power_zone);
1376 	}
1377 
1378 	return ret;
1379 }
1380 
1381 static int rapl_check_domain(int domain, struct rapl_package *rp)
1382 {
1383 	struct reg_action ra;
1384 
1385 	switch (domain) {
1386 	case RAPL_DOMAIN_PACKAGE:
1387 	case RAPL_DOMAIN_PP0:
1388 	case RAPL_DOMAIN_PP1:
1389 	case RAPL_DOMAIN_DRAM:
1390 	case RAPL_DOMAIN_PLATFORM:
1391 		ra.reg = rp->priv->regs[domain][RAPL_DOMAIN_REG_STATUS];
1392 		break;
1393 	default:
1394 		pr_err("invalid domain id %d\n", domain);
1395 		return -EINVAL;
1396 	}
1397 	/* make sure domain counters are available and contains non-zero
1398 	 * values, otherwise skip it.
1399 	 */
1400 
1401 	ra.mask = ENERGY_STATUS_MASK;
1402 	if (rp->priv->read_raw(get_rid(rp), &ra) || !ra.value)
1403 		return -ENODEV;
1404 
1405 	return 0;
1406 }
1407 
1408 /*
1409  * Get per domain energy/power/time unit.
1410  * RAPL Interfaces without per domain unit register will use the package
1411  * scope unit register to set per domain units.
1412  */
1413 static int rapl_get_domain_unit(struct rapl_domain *rd)
1414 {
1415 	struct rapl_defaults *defaults = get_defaults(rd->rp);
1416 	int ret;
1417 
1418 	if (!rd->regs[RAPL_DOMAIN_REG_UNIT].val) {
1419 		if (!rd->rp->priv->reg_unit.val) {
1420 			pr_err("No valid Unit register found\n");
1421 			return -ENODEV;
1422 		}
1423 		rd->regs[RAPL_DOMAIN_REG_UNIT] = rd->rp->priv->reg_unit;
1424 	}
1425 
1426 	if (!defaults->check_unit) {
1427 		pr_err("missing .check_unit() callback\n");
1428 		return -ENODEV;
1429 	}
1430 
1431 	ret = defaults->check_unit(rd);
1432 	if (ret)
1433 		return ret;
1434 
1435 	if (rd->id == RAPL_DOMAIN_DRAM && defaults->dram_domain_energy_unit)
1436 		rd->energy_unit = defaults->dram_domain_energy_unit;
1437 	if (rd->id == RAPL_DOMAIN_PLATFORM && defaults->psys_domain_energy_unit)
1438 		rd->energy_unit = defaults->psys_domain_energy_unit;
1439 	return 0;
1440 }
1441 
1442 /*
1443  * Check if power limits are available. Two cases when they are not available:
1444  * 1. Locked by BIOS, in this case we still provide read-only access so that
1445  *    users can see what limit is set by the BIOS.
1446  * 2. Some CPUs make some domains monitoring only which means PLx MSRs may not
1447  *    exist at all. In this case, we do not show the constraints in powercap.
1448  *
1449  * Called after domains are detected and initialized.
1450  */
1451 static void rapl_detect_powerlimit(struct rapl_domain *rd)
1452 {
1453 	u64 val64;
1454 	int i;
1455 
1456 	for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1457 		if (!rapl_read_pl_data(rd, i, PL_LOCK, false, &val64)) {
1458 			if (val64) {
1459 				rd->rpl[i].locked = true;
1460 				pr_info("%s:%s:%s locked by BIOS\n",
1461 					rd->rp->name, rd->name, pl_names[i]);
1462 			}
1463 		}
1464 
1465 		if (rapl_read_pl_data(rd, i, PL_LIMIT, false, &val64))
1466 			rd->rpl[i].name = NULL;
1467 	}
1468 }
1469 
1470 /* Detect active and valid domains for the given CPU, caller must
1471  * ensure the CPU belongs to the targeted package and CPU hotlug is disabled.
1472  */
1473 static int rapl_detect_domains(struct rapl_package *rp)
1474 {
1475 	struct rapl_domain *rd;
1476 	int i;
1477 
1478 	for (i = 0; i < RAPL_DOMAIN_MAX; i++) {
1479 		/* use physical package id to read counters */
1480 		if (!rapl_check_domain(i, rp)) {
1481 			rp->domain_map |= 1 << i;
1482 			pr_info("Found RAPL domain %s\n", rapl_domain_names[i]);
1483 		}
1484 	}
1485 	rp->nr_domains = bitmap_weight(&rp->domain_map, RAPL_DOMAIN_MAX);
1486 	if (!rp->nr_domains) {
1487 		pr_debug("no valid rapl domains found in %s\n", rp->name);
1488 		return -ENODEV;
1489 	}
1490 	pr_debug("found %d domains on %s\n", rp->nr_domains, rp->name);
1491 
1492 	rp->domains = kcalloc(rp->nr_domains, sizeof(struct rapl_domain),
1493 			      GFP_KERNEL);
1494 	if (!rp->domains)
1495 		return -ENOMEM;
1496 
1497 	rapl_init_domains(rp);
1498 
1499 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1500 		rapl_get_domain_unit(rd);
1501 		rapl_detect_powerlimit(rd);
1502 	}
1503 
1504 	return 0;
1505 }
1506 
1507 /* called from CPU hotplug notifier, hotplug lock held */
1508 void rapl_remove_package_cpuslocked(struct rapl_package *rp)
1509 {
1510 	struct rapl_domain *rd, *rd_package = NULL;
1511 
1512 	package_power_limit_irq_restore(rp);
1513 
1514 	for (rd = rp->domains; rd < rp->domains + rp->nr_domains; rd++) {
1515 		int i;
1516 
1517 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1518 			rapl_write_pl_data(rd, i, PL_ENABLE, 0);
1519 			rapl_write_pl_data(rd, i, PL_CLAMP, 0);
1520 		}
1521 
1522 		if (rd->id == RAPL_DOMAIN_PACKAGE) {
1523 			rd_package = rd;
1524 			continue;
1525 		}
1526 		pr_debug("remove package, undo power limit on %s: %s\n",
1527 			 rp->name, rd->name);
1528 		powercap_unregister_zone(rp->priv->control_type,
1529 					 &rd->power_zone);
1530 	}
1531 	/* do parent zone last */
1532 	powercap_unregister_zone(rp->priv->control_type,
1533 				 &rd_package->power_zone);
1534 	list_del(&rp->plist);
1535 	kfree(rp);
1536 }
1537 EXPORT_SYMBOL_GPL(rapl_remove_package_cpuslocked);
1538 
1539 void rapl_remove_package(struct rapl_package *rp)
1540 {
1541 	guard(cpus_read_lock)();
1542 	rapl_remove_package_cpuslocked(rp);
1543 }
1544 EXPORT_SYMBOL_GPL(rapl_remove_package);
1545 
1546 /* caller to ensure CPU hotplug lock is held */
1547 struct rapl_package *rapl_find_package_domain_cpuslocked(int id, struct rapl_if_priv *priv,
1548 							 bool id_is_cpu)
1549 {
1550 	struct rapl_package *rp;
1551 	int uid;
1552 
1553 	if (id_is_cpu)
1554 		uid = topology_logical_die_id(id);
1555 	else
1556 		uid = id;
1557 
1558 	list_for_each_entry(rp, &rapl_packages, plist) {
1559 		if (rp->id == uid
1560 		    && rp->priv->control_type == priv->control_type)
1561 			return rp;
1562 	}
1563 
1564 	return NULL;
1565 }
1566 EXPORT_SYMBOL_GPL(rapl_find_package_domain_cpuslocked);
1567 
1568 struct rapl_package *rapl_find_package_domain(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1569 {
1570 	guard(cpus_read_lock)();
1571 	return rapl_find_package_domain_cpuslocked(id, priv, id_is_cpu);
1572 }
1573 EXPORT_SYMBOL_GPL(rapl_find_package_domain);
1574 
1575 /* called from CPU hotplug notifier, hotplug lock held */
1576 struct rapl_package *rapl_add_package_cpuslocked(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1577 {
1578 	struct rapl_package *rp;
1579 	int ret;
1580 
1581 	rp = kzalloc(sizeof(struct rapl_package), GFP_KERNEL);
1582 	if (!rp)
1583 		return ERR_PTR(-ENOMEM);
1584 
1585 	if (id_is_cpu) {
1586 		rp->id = topology_logical_die_id(id);
1587 		rp->lead_cpu = id;
1588 		if (topology_max_die_per_package() > 1)
1589 			snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d-die-%d",
1590 				 topology_physical_package_id(id), topology_die_id(id));
1591 		else
1592 			snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d",
1593 				 topology_physical_package_id(id));
1594 	} else {
1595 		rp->id = id;
1596 		rp->lead_cpu = -1;
1597 		snprintf(rp->name, PACKAGE_DOMAIN_NAME_LENGTH, "package-%d", id);
1598 	}
1599 
1600 	rp->priv = priv;
1601 	ret = rapl_config(rp);
1602 	if (ret)
1603 		goto err_free_package;
1604 
1605 	/* check if the package contains valid domains */
1606 	if (rapl_detect_domains(rp)) {
1607 		ret = -ENODEV;
1608 		goto err_free_package;
1609 	}
1610 	ret = rapl_package_register_powercap(rp);
1611 	if (!ret) {
1612 		INIT_LIST_HEAD(&rp->plist);
1613 		list_add(&rp->plist, &rapl_packages);
1614 		return rp;
1615 	}
1616 
1617 err_free_package:
1618 	kfree(rp->domains);
1619 	kfree(rp);
1620 	return ERR_PTR(ret);
1621 }
1622 EXPORT_SYMBOL_GPL(rapl_add_package_cpuslocked);
1623 
1624 struct rapl_package *rapl_add_package(int id, struct rapl_if_priv *priv, bool id_is_cpu)
1625 {
1626 	guard(cpus_read_lock)();
1627 	return rapl_add_package_cpuslocked(id, priv, id_is_cpu);
1628 }
1629 EXPORT_SYMBOL_GPL(rapl_add_package);
1630 
1631 static void power_limit_state_save(void)
1632 {
1633 	struct rapl_package *rp;
1634 	struct rapl_domain *rd;
1635 	int ret, i;
1636 
1637 	cpus_read_lock();
1638 	list_for_each_entry(rp, &rapl_packages, plist) {
1639 		if (!rp->power_zone)
1640 			continue;
1641 		rd = power_zone_to_rapl_domain(rp->power_zone);
1642 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++) {
1643 			ret = rapl_read_pl_data(rd, i, PL_LIMIT, true,
1644 						 &rd->rpl[i].last_power_limit);
1645 			if (ret)
1646 				rd->rpl[i].last_power_limit = 0;
1647 		}
1648 	}
1649 	cpus_read_unlock();
1650 }
1651 
1652 static void power_limit_state_restore(void)
1653 {
1654 	struct rapl_package *rp;
1655 	struct rapl_domain *rd;
1656 	int i;
1657 
1658 	cpus_read_lock();
1659 	list_for_each_entry(rp, &rapl_packages, plist) {
1660 		if (!rp->power_zone)
1661 			continue;
1662 		rd = power_zone_to_rapl_domain(rp->power_zone);
1663 		for (i = POWER_LIMIT1; i < NR_POWER_LIMITS; i++)
1664 			if (rd->rpl[i].last_power_limit)
1665 				rapl_write_pl_data(rd, i, PL_LIMIT,
1666 					       rd->rpl[i].last_power_limit);
1667 	}
1668 	cpus_read_unlock();
1669 }
1670 
1671 static int rapl_pm_callback(struct notifier_block *nb,
1672 			    unsigned long mode, void *_unused)
1673 {
1674 	switch (mode) {
1675 	case PM_SUSPEND_PREPARE:
1676 		power_limit_state_save();
1677 		break;
1678 	case PM_POST_SUSPEND:
1679 		power_limit_state_restore();
1680 		break;
1681 	}
1682 	return NOTIFY_OK;
1683 }
1684 
1685 static struct notifier_block rapl_pm_notifier = {
1686 	.notifier_call = rapl_pm_callback,
1687 };
1688 
1689 static struct platform_device *rapl_msr_platdev;
1690 
1691 static int __init rapl_init(void)
1692 {
1693 	const struct x86_cpu_id *id;
1694 	int ret;
1695 
1696 	id = x86_match_cpu(rapl_ids);
1697 	if (id) {
1698 		defaults_msr = (struct rapl_defaults *)id->driver_data;
1699 
1700 		rapl_msr_platdev = platform_device_alloc("intel_rapl_msr", 0);
1701 		if (!rapl_msr_platdev)
1702 			return -ENOMEM;
1703 
1704 		ret = platform_device_add(rapl_msr_platdev);
1705 		if (ret) {
1706 			platform_device_put(rapl_msr_platdev);
1707 			return ret;
1708 		}
1709 	}
1710 
1711 	ret = register_pm_notifier(&rapl_pm_notifier);
1712 	if (ret && rapl_msr_platdev) {
1713 		platform_device_del(rapl_msr_platdev);
1714 		platform_device_put(rapl_msr_platdev);
1715 	}
1716 
1717 	return ret;
1718 }
1719 
1720 static void __exit rapl_exit(void)
1721 {
1722 	platform_device_unregister(rapl_msr_platdev);
1723 	unregister_pm_notifier(&rapl_pm_notifier);
1724 }
1725 
1726 fs_initcall(rapl_init);
1727 module_exit(rapl_exit);
1728 
1729 MODULE_DESCRIPTION("Intel Runtime Average Power Limit (RAPL) common code");
1730 MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@intel.com>");
1731 MODULE_LICENSE("GPL v2");
1732