xref: /linux/drivers/acpi/cppc_acpi.c (revision 4bcc60d326c5acaa28c5913259decb22a33a83a1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CPPC (Collaborative Processor Performance Control) methods used by CPUfreq drivers.
4  *
5  * (C) Copyright 2014, 2015 Linaro Ltd.
6  * Author: Ashwin Chaugule <ashwin.chaugule@linaro.org>
7  *
8  * CPPC describes a few methods for controlling CPU performance using
9  * information from a per CPU table called CPC. This table is described in
10  * the ACPI v5.0+ specification. The table consists of a list of
11  * registers which may be memory mapped or hardware registers and also may
12  * include some static integer values.
13  *
14  * CPU performance is on an abstract continuous scale as against a discretized
15  * P-state scale which is tied to CPU frequency only. In brief, the basic
16  * operation involves:
17  *
18  * - OS makes a CPU performance request. (Can provide min and max bounds)
19  *
20  * - Platform (such as BMC) is free to optimize request within requested bounds
21  *   depending on power/thermal budgets etc.
22  *
23  * - Platform conveys its decision back to OS
24  *
25  * The communication between OS and platform occurs through another medium
26  * called (PCC) Platform Communication Channel. This is a generic mailbox like
27  * mechanism which includes doorbell semantics to indicate register updates.
28  * See drivers/mailbox/pcc.c for details on PCC.
29  *
30  * Finer details about the PCC and CPPC spec are available in the ACPI v5.1 and
31  * above specifications.
32  */
33 
34 #define pr_fmt(fmt)	"ACPI CPPC: " fmt
35 
36 #include <linux/delay.h>
37 #include <linux/interval_tree_generic.h>
38 #include <linux/iopoll.h>
39 #include <linux/ktime.h>
40 #include <linux/list.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/rwsem.h>
44 #include <linux/wait.h>
45 #include <linux/topology.h>
46 #include <linux/dmi.h>
47 #include <linux/units.h>
48 #include <linux/unaligned.h>
49 
50 #include <acpi/cppc_acpi.h>
51 
52 struct cppc_pcc_data {
53 	struct pcc_mbox_chan *pcc_channel;
54 	bool pcc_channel_acquired;
55 	unsigned int deadline_us;
56 	unsigned int pcc_mpar, pcc_mrtt, pcc_nominal;
57 
58 	bool pending_pcc_write_cmd;	/* Any pending/batched PCC write cmds? */
59 	bool platform_owns_pcc;		/* Ownership of PCC subspace */
60 	unsigned int pcc_write_cnt;	/* Running count of PCC write commands */
61 
62 	/*
63 	 * Lock to provide controlled access to the PCC channel.
64 	 *
65 	 * For performance critical usecases(currently cppc_set_perf)
66 	 *	We need to take read_lock and check if channel belongs to OSPM
67 	 * before reading or writing to PCC subspace
68 	 *	We need to take write_lock before transferring the channel
69 	 * ownership to the platform via a Doorbell
70 	 *	This allows us to batch a number of CPPC requests if they happen
71 	 * to originate in about the same time
72 	 *
73 	 * For non-performance critical usecases(init)
74 	 *	Take write_lock for all purposes which gives exclusive access
75 	 */
76 	struct rw_semaphore pcc_lock;
77 	/* Serialize byte-oriented accesses to aliased PCC payload fields. */
78 	raw_spinlock_t payload_lock;
79 
80 	/* Wait queue for CPUs whose requests were batched */
81 	wait_queue_head_t pcc_write_wait_q;
82 	ktime_t last_cmd_cmpl_time;
83 	ktime_t last_mpar_reset;
84 	int mpar_count;
85 	int refcount;
86 };
87 
88 /* Array to represent the PCC channel per subspace ID */
89 static struct cppc_pcc_data *pcc_data[MAX_PCC_SUBSPACES];
90 static DEFINE_MUTEX(pcc_data_lock);
91 /* The cpu_pcc_subspace_idx contains per CPU subspace ID */
92 static DEFINE_PER_CPU(int, cpu_pcc_subspace_idx);
93 
94 /*
95  * The cpc_desc structure contains the ACPI register details
96  * as described in the per CPU _CPC tables. The details
97  * include the type of register (e.g. PCC, System IO, FFH etc.)
98  * and destination addresses which lets us READ/WRITE CPU performance
99  * information using the appropriate I/O methods.
100  */
101 static DEFINE_PER_CPU(struct cpc_desc *, cpc_desc_ptr);
102 
103 /* Protect immutable capability queries against descriptor removal. */
104 static DEFINE_MUTEX(cpc_desc_lock);
105 
106 static void cpc_set_desc(unsigned int cpu, struct cpc_desc *desc)
107 {
108 	guard(mutex)(&cpc_desc_lock);
109 	per_cpu(cpc_desc_ptr, cpu) = desc;
110 }
111 
112 struct cpc_sysmem_node {
113 	struct rb_node rb;
114 	u64 subtree_last;
115 	u64 start;
116 	u64 last;
117 	struct cpc_desc *desc;
118 	unsigned int reg_idx;
119 	struct list_head aliases;
120 	struct list_head alias_node;
121 	struct cpc_sysmem_node *alias_of;
122 	bool registered;
123 };
124 
125 struct cpc_non_mmio_node {
126 	struct rb_node rb;
127 	u64 subtree_last;
128 	u64 start;
129 	u64 last;
130 	struct cpc_desc *desc;
131 	unsigned int reg_idx;
132 	u8 space_id;
133 	u8 pcc_ss_id;
134 	bool registered;
135 };
136 
137 #define CPC_SYSMEM_START(node) ((node)->start)
138 #define CPC_SYSMEM_LAST(node) ((node)->last)
139 
140 INTERVAL_TREE_DEFINE(struct cpc_sysmem_node, rb, u64, subtree_last,
141 		     CPC_SYSMEM_START, CPC_SYSMEM_LAST, static inline,
142 		     cpc_sysmem_itree)
143 
144 static struct rb_root_cached cpc_sysmem_tree = RB_ROOT_CACHED;
145 static DEFINE_MUTEX(cpc_sysmem_lock);
146 
147 #define CPC_NON_MMIO_START(node) ((node)->start)
148 #define CPC_NON_MMIO_LAST(node) ((node)->last)
149 
150 INTERVAL_TREE_DEFINE(struct cpc_non_mmio_node, rb, u64, subtree_last,
151 		     CPC_NON_MMIO_START, CPC_NON_MMIO_LAST, static inline,
152 		     cpc_non_mmio_itree)
153 
154 static struct rb_root_cached cpc_pcc_trees[MAX_PCC_SUBSPACES];
155 static struct rb_root_cached cpc_sysio_tree = RB_ROOT_CACHED;
156 static DEFINE_MUTEX(cpc_non_mmio_lock);
157 
158 static struct cpc_sysmem_node *cpc_sysmem_first(u64 start, u64 last)
159 {
160 	return cpc_sysmem_itree_iter_first(&cpc_sysmem_tree, start, last);
161 }
162 
163 static struct cpc_sysmem_node *cpc_sysmem_next(struct cpc_sysmem_node *node,
164 					       u64 start, u64 last)
165 {
166 	return cpc_sysmem_itree_iter_next(node, start, last);
167 }
168 
169 #define CPC_PCC_HEADER_SIZE	0x8
170 
171 /* pcc mapped address + header size + offset within PCC subspace */
172 #define GET_PCC_VADDR(offs, pcc_ss_id) (pcc_data[pcc_ss_id]->pcc_channel->shmem + \
173 						CPC_PCC_HEADER_SIZE + (offs))
174 
175 /* Check if a CPC register is in PCC */
176 #define CPC_IN_PCC(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&		\
177 				(cpc)->cpc_entry.reg.space_id ==	\
178 				ACPI_ADR_SPACE_PLATFORM_COMM)
179 
180 /* Check if a CPC register is in FFH */
181 #define CPC_IN_FFH(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&		\
182 				(cpc)->cpc_entry.reg.space_id ==	\
183 				ACPI_ADR_SPACE_FIXED_HARDWARE)
184 
185 /* Check if a CPC register is in SystemMemory */
186 #define CPC_IN_SYSTEM_MEMORY(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
187 				(cpc)->cpc_entry.reg.space_id ==	\
188 				ACPI_ADR_SPACE_SYSTEM_MEMORY)
189 
190 /* Check if a CPC register is in SystemIo */
191 #define CPC_IN_SYSTEM_IO(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
192 				(cpc)->cpc_entry.reg.space_id ==	\
193 				ACPI_ADR_SPACE_SYSTEM_IO)
194 
195 /* Evaluates to True if reg is a NULL register descriptor */
196 #define IS_NULL_REG(reg) ((reg)->space_id ==  ACPI_ADR_SPACE_SYSTEM_MEMORY && \
197 				(reg)->address == 0 &&			\
198 				(reg)->bit_width == 0 &&		\
199 				(reg)->bit_offset == 0 &&		\
200 				(reg)->access_width == 0)
201 
202 /* Evaluates to True if an optional cpc field is supported */
203 #define CPC_SUPPORTED(cpc) ((cpc)->type == ACPI_TYPE_INTEGER ?		\
204 				!!(cpc)->cpc_entry.int_value :		\
205 				!IS_NULL_REG(&(cpc)->cpc_entry.reg))
206 
207 static bool cpc_is_writable(const struct cpc_register_resource *cpc)
208 {
209 	return cpc->type == ACPI_TYPE_BUFFER &&
210 	       !IS_NULL_REG(&cpc->cpc_entry.reg) &&
211 	       !cpc->cpc_entry.write_unsupported;
212 }
213 
214 static bool cpc_is_readable(const struct cpc_register_resource *cpc)
215 {
216 	return cpc->type != ACPI_TYPE_BUFFER ||
217 	       !cpc->cpc_entry.read_unsupported;
218 }
219 
220 static bool cpc_entry_present(const struct cpc_register_resource *cpc)
221 {
222 	if (cpc->type == ACPI_TYPE_INTEGER)
223 		return true;
224 
225 	return cpc->type == ACPI_TYPE_BUFFER &&
226 	       !IS_NULL_REG(&cpc->cpc_entry.reg);
227 }
228 
229 /*
230  * Each bit indicates the optionality of the register in per-cpu
231  * cpc_regs[] with the corresponding index. 0 means mandatory and 1
232  * means optional.
233  */
234 #define REG_OPTIONAL (0x7FC7D0)
235 
236 /*
237  * Use the index of the register in per-cpu cpc_regs[] to check if
238  * it's an optional one.
239  */
240 #define IS_OPTIONAL_CPC_REG(reg_idx) (REG_OPTIONAL & (1U << (reg_idx)))
241 
242 static bool cpc_integer_entry_valid(unsigned int reg_idx, u64 value,
243 				    bool *legacy_null)
244 {
245 	*legacy_null = false;
246 
247 	switch (reg_idx) {
248 	case HIGHEST_PERF:
249 	case NOMINAL_PERF:
250 	case LOW_NON_LINEAR_PERF:
251 	case LOWEST_PERF:
252 	case REFERENCE_PERF:
253 	case LOWEST_FREQ:
254 	case NOMINAL_FREQ:
255 		return value <= U32_MAX;
256 	case CTR_WRAP_TIME:
257 		/* AML Integers and the kernel interface are both 64-bit. */
258 		return true;
259 	case AUTO_SEL_ENABLE:
260 		return value <= 1;
261 	case DESIRED_PERF:
262 		/* Validated against Autonomous Selection after parsing. */
263 		*legacy_null = value == 0;
264 		return *legacy_null;
265 	default:
266 		/* Tolerate legacy Integer 0 placeholders for absent options. */
267 		*legacy_null = value == 0 && IS_OPTIONAL_CPC_REG(reg_idx);
268 		return *legacy_null;
269 	}
270 }
271 
272 /*
273  * Arbitrary Retries in case the remote processor is slow to respond
274  * to PCC commands. Keeping it high enough to cover emulators where
275  * the processors run painfully slow.
276  */
277 #define NUM_RETRIES 500ULL
278 
279 #define CPC_GENERIC_REGISTER_DESCRIPTOR 0x82
280 #define CPC_GENERIC_REGISTER_LENGTH (sizeof(struct cpc_reg) - 3)
281 
282 #define define_one_cppc_ro(_name)		\
283 static struct kobj_attribute _name =		\
284 __ATTR(_name, 0444, show_##_name, NULL)
285 
286 #define to_cpc_desc(a) container_of(a, struct cpc_desc, kobj)
287 
288 #define show_cppc_data(access_fn, struct_name, member_name)		\
289 	static ssize_t show_##member_name(struct kobject *kobj,		\
290 				struct kobj_attribute *attr, char *buf)	\
291 	{								\
292 		struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);		\
293 		struct struct_name st_name = {0};			\
294 		int ret;						\
295 									\
296 		ret = access_fn(cpc_ptr->cpu_id, &st_name);		\
297 		if (ret)						\
298 			return ret;					\
299 									\
300 		return sysfs_emit(buf, "%llu\n",		\
301 				(u64)st_name.member_name);		\
302 	}								\
303 	define_one_cppc_ro(member_name)
304 
305 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, highest_perf);
306 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_perf);
307 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_perf);
308 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, reference_perf);
309 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_nonlinear_perf);
310 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, guaranteed_perf);
311 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_freq);
312 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_freq);
313 
314 show_cppc_data(cppc_get_perf_ctrs, cppc_perf_fb_ctrs, wraparound_time);
315 
316 /*
317  * PCC reuses the access_width field as the subspace id, so only decode access
318  * size for non-PCC registers. Otherwise, use the bit_width.
319  */
320 #define GET_BIT_WIDTH(reg) (((reg)->access_width &&				\
321 			     (reg)->space_id != ACPI_ADR_SPACE_PLATFORM_COMM) ? \
322 			    (8 << ((reg)->access_width - 1)) : (reg)->bit_width)
323 
324 /* Shift and apply the mask for CPC reads/writes */
325 #define MASK_VAL_READ(reg, val) (((val) >> (reg)->bit_offset) &				\
326 					GENMASK(((reg)->bit_width) - 1, 0))
327 #define MASK_VAL_WRITE(reg, prev_val, val)						\
328 	((((val) & GENMASK(((reg)->bit_width) - 1, 0)) << (reg)->bit_offset) |		\
329 	((prev_val) & ~(GENMASK(((reg)->bit_width) - 1, 0) << (reg)->bit_offset)))	\
330 
331 static unsigned int cpc_reg_access_width(const struct cpc_reg *reg)
332 {
333 	if (reg->access_width > 4)
334 		return 0;
335 
336 	if (reg->access_width)
337 		return 8U << (reg->access_width - 1);
338 
339 	return reg->bit_width;
340 }
341 
342 enum cpc_platform_quirk {
343 	CPC_QUIRK_PERF_LIMITED_OWNS_UNIT = BIT(0),
344 };
345 
346 static const struct acpi_platform_list cpc_platform_quirk_list[] = {
347 	{
348 		.oem_id = "NVIDIA",
349 		.oem_table_id = "T41",
350 		.table = ACPI_SIG_DSDT,
351 		.pred = all_versions,
352 		.reason = "Performance Limited owns its access unit",
353 		.data = CPC_QUIRK_PERF_LIMITED_OWNS_UNIT,
354 	},
355 	{ }
356 };
357 
358 static DEFINE_MUTEX(cpc_platform_quirk_lock);
359 static bool cpc_platform_quirks_initialized;
360 static u32 cpc_platform_quirks;
361 
362 static int cpc_get_platform_quirks(u32 *quirks)
363 {
364 	int idx, ret = 0;
365 
366 	mutex_lock(&cpc_platform_quirk_lock);
367 	if (!cpc_platform_quirks_initialized) {
368 		idx = acpi_match_platform_list(cpc_platform_quirk_list);
369 		if (idx < 0 && idx != -ENODEV) {
370 			ret = idx;
371 			goto out;
372 		}
373 		if (idx >= 0)
374 			cpc_platform_quirks = cpc_platform_quirk_list[idx].data;
375 		cpc_platform_quirks_initialized = true;
376 	}
377 	*quirks = cpc_platform_quirks;
378 out:
379 	mutex_unlock(&cpc_platform_quirk_lock);
380 
381 	return ret;
382 }
383 
384 static void cpc_apply_platform_quirks(struct cpc_reg *reg,
385 				      unsigned int reg_idx, u32 quirks)
386 {
387 	unsigned int access_width;
388 
389 	if (!(quirks & CPC_QUIRK_PERF_LIMITED_OWNS_UNIT) ||
390 	    reg_idx != PERF_LIMITED ||
391 	    reg->space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY ||
392 	    reg->bit_width != 2 || reg->bit_offset)
393 		return;
394 
395 	access_width = cpc_reg_access_width(reg);
396 	if (access_width != 32)
397 		return;
398 
399 	reg->bit_width = access_width;
400 	pr_info_once("firmware quirk: Performance Limited owns its access unit, using Bit Width %u\n",
401 		     access_width);
402 }
403 
404 static u64 cpc_sysmem_access_size(const struct cpc_register_resource *reg)
405 {
406 	unsigned int width = cpc_reg_access_width(&reg->cpc_entry.reg);
407 
408 	if (width != 8 && width != 16 && width != 32 && width != 64)
409 		return 0;
410 
411 	return width / 8;
412 }
413 
414 static u64 cpc_sysmem_field_size(const struct cpc_reg *gas)
415 {
416 	return DIV_ROUND_UP((u64)gas->bit_offset + gas->bit_width, 8);
417 }
418 
419 static u64 cpc_sysmem_claim_size(const struct cpc_register_resource *reg)
420 {
421 	const struct cpc_reg *gas = &reg->cpc_entry.reg;
422 	u64 access_size = cpc_sysmem_access_size(reg);
423 
424 	if (!gas->bit_width)
425 		return access_size;
426 
427 	return max(access_size, cpc_sysmem_field_size(gas));
428 }
429 
430 static bool cpc_reg_access_aligned(const struct cpc_reg *reg, u64 access_size)
431 {
432 	/* x86 MMIO and port-I/O accessors support unaligned addresses. */
433 	return IS_ENABLED(CONFIG_X86) || IS_ALIGNED(reg->address, access_size);
434 }
435 
436 static bool cpc_sysmem_access_units_overlap(const struct cpc_register_resource *a,
437 					    const struct cpc_register_resource *b)
438 {
439 	const struct cpc_reg *a_gas = &a->cpc_entry.reg;
440 	const struct cpc_reg *b_gas = &b->cpc_entry.reg;
441 	u64 a_size = cpc_sysmem_claim_size(a);
442 	u64 b_size = cpc_sysmem_claim_size(b);
443 
444 	/* Keep the conservative locking path for malformed access widths. */
445 	if (!a_size || !b_size)
446 		return true;
447 
448 	if (a_gas->address < b_gas->address)
449 		return b_gas->address - a_gas->address < a_size;
450 
451 	return a_gas->address - b_gas->address < b_size;
452 }
453 
454 static bool cpc_reg_is_writable(unsigned int reg_idx)
455 {
456 	/* Only controls written by this driver can be competing writers. */
457 	switch (reg_idx) {
458 	case DESIRED_PERF:
459 	case MIN_PERF:
460 	case MAX_PERF:
461 	case PERF_LIMITED:
462 	case ENABLE:
463 	case AUTO_SEL_ENABLE:
464 	case AUTO_ACT_WINDOW:
465 	case ENERGY_PERF:
466 		return true;
467 	default:
468 		return false;
469 	}
470 }
471 
472 static bool cpc_reg_is_write_only(const struct cpc_desc *cpc_desc,
473 				  unsigned int reg_idx)
474 {
475 	return cpc_desc->version >= CPPC_V4_REV &&
476 	       (reg_idx == DESIRED_PERF || reg_idx == OSPM_NOMINAL_PERF);
477 }
478 
479 static void cpc_disable_reg(struct cpc_desc *cpc_desc, unsigned int reg_idx)
480 {
481 	struct cpc_register_resource *reg = &cpc_desc->cpc_regs[reg_idx];
482 
483 	reg->type = ACPI_TYPE_INTEGER;
484 	reg->cpc_entry.int_value = 0;
485 }
486 
487 static bool cpc_optional_writer_can_be_disabled(unsigned int reg_idx)
488 {
489 	if (!IS_OPTIONAL_CPC_REG(reg_idx) || !cpc_reg_is_writable(reg_idx) ||
490 	    reg_idx == MIN_PERF || reg_idx == MAX_PERF || reg_idx == ENABLE ||
491 	    reg_idx == AUTO_SEL_ENABLE)
492 		return false;
493 
494 	return true;
495 }
496 
497 static bool cpc_sysmem_reg_needs_rmw(const struct cpc_register_resource *reg)
498 {
499 	const struct cpc_reg *gas = &reg->cpc_entry.reg;
500 	u64 access_size = cpc_sysmem_access_size(reg);
501 
502 	return gas->bit_offset || gas->bit_width != access_size * 8;
503 }
504 
505 static int cpc_validate_sysmem_reg(struct cpc_desc *cpc_desc,
506 				   const struct cpc_reg *gas,
507 				   unsigned int reg_idx)
508 {
509 	unsigned int access_width = cpc_reg_access_width(gas);
510 	u64 access_size;
511 
512 	if (access_width != 8 && access_width != 16 &&
513 	    access_width != 32 && access_width != 64)
514 		goto invalid;
515 
516 	if (!gas->bit_width || gas->bit_width > access_width ||
517 	    gas->bit_offset >= access_width ||
518 	    gas->bit_width > access_width - gas->bit_offset)
519 		goto invalid;
520 
521 	access_size = access_width / 8;
522 	if (!gas->address || gas->address > U64_MAX - (access_size - 1))
523 		goto invalid;
524 	if (!cpc_reg_access_aligned(gas, access_size))
525 		goto invalid;
526 
527 	if (reg_idx == PERF_LIMITED) {
528 		if (access_width == 64 && !IS_ENABLED(CONFIG_64BIT)) {
529 			pr_warn_once("CPU%d: Performance Limited register cannot be accessed atomically; keeping its range reserved\n",
530 				     cpc_desc->cpu_id);
531 			cpc_desc->cpc_regs[reg_idx].cpc_entry.read_unsupported = true;
532 			cpc_desc->cpc_regs[reg_idx].cpc_entry.write_unsupported = true;
533 			return 0;
534 		}
535 
536 		if (gas->bit_offset || gas->bit_width != access_width) {
537 			pr_warn_once("CPU%d: Performance Limited register cannot be cleared safely; keeping it readable\n",
538 				     cpc_desc->cpu_id);
539 			cpc_desc->cpc_regs[reg_idx].cpc_entry.write_unsupported = true;
540 		}
541 	}
542 
543 	return 0;
544 
545 invalid:
546 	access_size = 0;
547 	if (access_width == 8 || access_width == 16 ||
548 	    access_width == 32 || access_width == 64)
549 		access_size = access_width / 8;
550 	if (gas->bit_width)
551 		access_size = max(access_size, cpc_sysmem_field_size(gas));
552 	if ((cpc_reg_is_write_only(cpc_desc, reg_idx) ||
553 	     reg_idx == PERF_LIMITED) && gas->address && access_size &&
554 	    gas->address <= U64_MAX - (access_size - 1)) {
555 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[reg_idx];
556 
557 		if (reg_idx == PERF_LIMITED)
558 			pr_warn_once("CPU%d: _CPC v%d register %u is inaccessible; keeping its range reserved\n",
559 				     cpc_desc->cpu_id, cpc_desc->version, reg_idx);
560 		else
561 			pr_warn("CPU%d: _CPC v%d register %u is inaccessible; keeping its range reserved\n",
562 				cpc_desc->cpu_id, cpc_desc->version, reg_idx);
563 		reg->cpc_entry.read_unsupported = true;
564 		reg->cpc_entry.write_unsupported = true;
565 		return 0;
566 	}
567 
568 	pr_debug("CPU:%d invalid SystemMemory GAS for _CPC register %u\n",
569 		 cpc_desc->cpu_id, reg_idx);
570 	return -EINVAL;
571 }
572 
573 static bool cpc_immutable_autonomous(const struct cpc_desc *cpc_desc)
574 {
575 	const struct cpc_register_resource *reg;
576 
577 	reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
578 	return osc_sb_cppc2_support_acked && reg->type == ACPI_TYPE_INTEGER &&
579 	       reg->cpc_entry.int_value == 1;
580 }
581 
582 static bool cpc_retain_pcc_status(struct cpc_desc *cpc_desc,
583 				  unsigned int reg_idx);
584 
585 static int cpc_resolve_unsupported(struct cpc_desc *cpc_desc,
586 				   u32 unsupported)
587 {
588 	unsigned int i;
589 	u32 bounds = BIT(MIN_PERF) | BIT(MAX_PERF);
590 	bool min_unusable, max_unusable;
591 
592 	if (unsupported & bounds) {
593 		min_unusable = (unsupported & BIT(MIN_PERF)) ||
594 			       !cpc_is_writable(&cpc_desc->cpc_regs[MIN_PERF]);
595 		max_unusable = (unsupported & BIT(MAX_PERF)) ||
596 			       !cpc_is_writable(&cpc_desc->cpc_regs[MAX_PERF]);
597 		if (min_unusable && max_unusable) {
598 			pr_warn("CPU%d: ignoring inaccessible Minimum and Maximum Performance registers\n",
599 				cpc_desc->cpu_id);
600 			cpc_disable_reg(cpc_desc, MIN_PERF);
601 			cpc_disable_reg(cpc_desc, MAX_PERF);
602 			unsupported &= ~bounds;
603 		}
604 	}
605 
606 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
607 		if (!(unsupported & BIT(i)))
608 			continue;
609 
610 		/* CPPC control does not depend on Performance Limited status. */
611 		if (i == PERF_LIMITED) {
612 			if (CPC_IN_PCC(&cpc_desc->cpc_regs[i]) &&
613 			    cpc_retain_pcc_status(cpc_desc, i))
614 				continue;
615 
616 			pr_warn_once("CPU%d: ignoring inaccessible Performance Limited register\n",
617 				     cpc_desc->cpu_id);
618 			cpc_disable_reg(cpc_desc, i);
619 			continue;
620 		}
621 
622 		if (i == DESIRED_PERF && cpc_immutable_autonomous(cpc_desc)) {
623 			pr_warn("CPU%d: ignoring inaccessible Desired Performance register in autonomous mode\n",
624 				cpc_desc->cpu_id);
625 			cpc_disable_reg(cpc_desc, i);
626 			continue;
627 		}
628 
629 		/*
630 		 * A present Enable or Autonomous Selection control must remain
631 		 * usable.  Disabling the latter could leave autonomous selection
632 		 * enabled while OSPM believes that it has disabled it.
633 		 */
634 		if (i == ENABLE ||
635 		    (i == AUTO_SEL_ENABLE && cpc_entry_present(&cpc_desc->cpc_regs[i])) ||
636 		    i == MIN_PERF || i == MAX_PERF ||
637 		    !IS_OPTIONAL_CPC_REG(i)) {
638 			pr_err("CPU%d: cannot access _CPC register %u\n",
639 			       cpc_desc->cpu_id, i);
640 			return -EINVAL;
641 		}
642 
643 		pr_warn("CPU%d: ignoring inaccessible optional _CPC register %u\n",
644 			cpc_desc->cpu_id, i);
645 		cpc_disable_reg(cpc_desc, i);
646 	}
647 
648 	return 0;
649 }
650 
651 static int cpc_validate_required_controls(struct cpc_desc *cpc_desc)
652 {
653 	unsigned int i;
654 
655 	/*
656 	 * Performance Limited is required by the specification, but tolerate a
657 	 * NULL descriptor used by firmware which cannot report limiting events.
658 	 * CPPC control does not depend on this status.
659 	 */
660 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
661 		if (i != DESIRED_PERF && i != PERF_LIMITED &&
662 		    !IS_OPTIONAL_CPC_REG(i) &&
663 		    !cpc_entry_present(&cpc_desc->cpc_regs[i])) {
664 			pr_debug("CPU:%d lacks mandatory _CPC register %u\n",
665 				 cpc_desc->cpu_id, i);
666 			return -EINVAL;
667 		}
668 	}
669 
670 	/* Desired may be absent only for immutable autonomous operation. */
671 	if (!cpc_is_writable(&cpc_desc->cpc_regs[DESIRED_PERF]) &&
672 	    !cpc_immutable_autonomous(cpc_desc)) {
673 		pr_debug("CPU:%d lacks a writable Desired Performance register\n",
674 			 cpc_desc->cpu_id);
675 		return -EINVAL;
676 	}
677 
678 	return 0;
679 }
680 
681 static int cpc_validate_bound_controls(struct cpc_desc *cpc_desc)
682 {
683 	bool have_min, have_max;
684 
685 	have_min = cpc_is_writable(&cpc_desc->cpc_regs[MIN_PERF]);
686 	have_max = cpc_is_writable(&cpc_desc->cpc_regs[MAX_PERF]);
687 	if (have_min != have_max) {
688 		pr_err("CPU%d: _CPC must provide both Minimum and Maximum Performance or neither\n",
689 		       cpc_desc->cpu_id);
690 		return -EINVAL;
691 	}
692 
693 	return 0;
694 }
695 
696 static bool
697 cpc_retain_pcc_status(struct cpc_desc *cpc_desc, unsigned int reg_idx)
698 {
699 	struct cpc_register_resource *reg = &cpc_desc->cpc_regs[reg_idx];
700 	const struct cpc_reg *gas = &reg->cpc_entry.reg;
701 	u64 size;
702 
703 	if (reg_idx != PERF_LIMITED || !gas->bit_width)
704 		return false;
705 
706 	size = DIV_ROUND_UP((u64)gas->bit_offset + gas->bit_width, 8);
707 	if (!size || gas->address > U64_MAX - (size - 1))
708 		return false;
709 
710 	reg->cpc_entry.read_unsupported = true;
711 	reg->cpc_entry.write_unsupported = true;
712 	pr_warn_once("CPU%d: Performance Limited register cannot be accessed; keeping its PCC range reserved\n",
713 		     cpc_desc->cpu_id);
714 	return true;
715 }
716 
717 static bool
718 cpc_retain_sysio_status(struct cpc_desc *cpc_desc, unsigned int reg_idx)
719 {
720 	struct cpc_register_resource *reg = &cpc_desc->cpc_regs[reg_idx];
721 	const struct cpc_reg *gas = &reg->cpc_entry.reg;
722 
723 	if (reg_idx != PERF_LIMITED || !gas->bit_width)
724 		return false;
725 
726 	/* Retain any in-range portion for overlap validation only. */
727 	if (gas->address > U16_MAX)
728 		return false;
729 
730 	pr_warn_once("CPU%d: Performance Limited register cannot be accessed; keeping its SystemIO range reserved\n",
731 		     cpc_desc->cpu_id);
732 	reg->cpc_entry.read_unsupported = true;
733 	reg->cpc_entry.write_unsupported = true;
734 	return true;
735 }
736 
737 static u64 cpc_non_mmio_access_size(const struct cpc_register_resource *reg)
738 {
739 	const struct cpc_reg *gas = &reg->cpc_entry.reg;
740 
741 	if (gas->space_id == ACPI_ADR_SPACE_PLATFORM_COMM)
742 		return DIV_ROUND_UP((u64)gas->bit_offset + gas->bit_width, 8);
743 
744 	return max((u64)cpc_reg_access_width(gas) / 8,
745 		   DIV_ROUND_UP((u64)gas->bit_offset + gas->bit_width, 8));
746 }
747 
748 static void cpc_validate_pcc_bounds(struct cpc_desc *cpc_desc,
749 				    int pcc_ss_id, struct cppc_pcc_data *data,
750 				    u32 *unsupported)
751 {
752 	u64 shmem_size = data->pcc_channel->shmem_size;
753 	unsigned int i;
754 
755 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
756 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
757 		struct cpc_reg *gas;
758 		u64 access_size;
759 
760 		if ((*unsupported & BIT(i)) || !CPC_SUPPORTED(reg) ||
761 		    !CPC_IN_PCC(reg))
762 			continue;
763 
764 		gas = &reg->cpc_entry.reg;
765 		if (gas->access_width != pcc_ss_id)
766 			continue;
767 		access_size = cpc_non_mmio_access_size(reg);
768 		if (shmem_size >= CPC_PCC_HEADER_SIZE &&
769 		    gas->address <= shmem_size - CPC_PCC_HEADER_SIZE &&
770 		    access_size <= shmem_size - CPC_PCC_HEADER_SIZE - gas->address)
771 			continue;
772 
773 		pr_debug("CPU%d: _CPC register %u exceeds the PCC shared region\n",
774 			 cpc_desc->cpu_id, i);
775 		*unsupported |= BIT(i);
776 	}
777 }
778 
779 static bool cpc_pcc_access_needed(const struct cpc_desc *cpc_desc)
780 {
781 	unsigned int i;
782 
783 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
784 		const struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
785 
786 		if (CPC_SUPPORTED(reg) && CPC_IN_PCC(reg) &&
787 		    (cpc_is_readable(reg) || cpc_is_writable(reg)))
788 			return true;
789 	}
790 
791 	return false;
792 }
793 
794 static bool cpc_non_mmio_overlap_conflicts(u8 space_id, bool a_writable,
795 					   bool b_writable, bool a_write_only,
796 					   bool b_write_only)
797 {
798 	/* Only a write-only control can use a separate read-side port alias. */
799 	if (space_id == ACPI_ADR_SPACE_SYSTEM_IO && a_writable != b_writable)
800 		return a_writable ? !a_write_only : !b_write_only;
801 
802 	return a_writable || b_writable;
803 }
804 
805 static bool
806 cpc_sysio_perf_limited_conflicts(unsigned int a_idx, bool a_writable,
807 				 unsigned int b_idx, bool b_writable)
808 {
809 	return (a_idx == PERF_LIMITED && b_writable) ||
810 	       (b_idx == PERF_LIMITED && a_writable);
811 }
812 
813 static struct rb_root_cached *cpc_non_mmio_tree(u8 space_id, u8 pcc_ss_id)
814 {
815 	if (space_id == ACPI_ADR_SPACE_PLATFORM_COMM)
816 		return &cpc_pcc_trees[pcc_ss_id];
817 	if (space_id == ACPI_ADR_SPACE_SYSTEM_IO)
818 		return &cpc_sysio_tree;
819 	return NULL;
820 }
821 
822 static bool cpc_same_non_mmio_register(const struct cpc_non_mmio_node *a,
823 				       const struct cpc_non_mmio_node *b)
824 {
825 	const struct cpc_reg *a_gas =
826 		&a->desc->cpc_regs[a->reg_idx].cpc_entry.reg;
827 	const struct cpc_reg *b_gas =
828 		&b->desc->cpc_regs[b->reg_idx].cpc_entry.reg;
829 
830 	return a->space_id == b->space_id && a->pcc_ss_id == b->pcc_ss_id &&
831 	       a->reg_idx == b->reg_idx && a->start == b->start &&
832 	       a->last == b->last && a_gas->bit_offset == b_gas->bit_offset &&
833 	       a_gas->bit_width == b_gas->bit_width &&
834 	       (a->space_id == ACPI_ADR_SPACE_PLATFORM_COMM ||
835 		cpc_reg_access_width(a_gas) == cpc_reg_access_width(b_gas));
836 }
837 
838 static int cpc_validate_non_mmio_pair(const struct cpc_non_mmio_node *a,
839 				      const struct cpc_non_mmio_node *b)
840 {
841 	const struct cpc_register_resource *a_reg;
842 	const struct cpc_register_resource *b_reg;
843 	bool a_writable, b_writable;
844 	const char *name;
845 
846 	a_reg = &a->desc->cpc_regs[a->reg_idx];
847 	b_reg = &b->desc->cpc_regs[b->reg_idx];
848 	a_writable = cpc_reg_is_writable(a->reg_idx) && cpc_is_writable(a_reg);
849 	b_writable = cpc_reg_is_writable(b->reg_idx) && cpc_is_writable(b_reg);
850 
851 	if (!cpc_non_mmio_overlap_conflicts(a->space_id, a_writable,
852 					    b_writable,
853 					    cpc_reg_is_write_only(a->desc, a->reg_idx),
854 					    cpc_reg_is_write_only(b->desc, b->reg_idx)) &&
855 	    !(a->space_id == ACPI_ADR_SPACE_SYSTEM_IO &&
856 	      cpc_sysio_perf_limited_conflicts(a->reg_idx, a_writable,
857 					       b->reg_idx, b_writable)))
858 		return 0;
859 
860 	if (cpc_same_non_mmio_register(a, b))
861 		return 0;
862 
863 	name = a->space_id == ACPI_ADR_SPACE_PLATFORM_COMM ?
864 	       "PCC" : "SystemIO";
865 	pr_err("CPU%d: %s _CPC register %u conflicts with CPU%d register %u\n",
866 	       a->desc->cpu_id, name, a->reg_idx, b->desc->cpu_id,
867 	       b->reg_idx);
868 	return -EINVAL;
869 }
870 
871 static void cpc_unregister_non_mmio_desc_locked(struct cpc_desc *cpc_desc)
872 {
873 	unsigned int i;
874 
875 	if (!cpc_desc->non_mmio_nodes)
876 		return;
877 
878 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
879 		struct cpc_non_mmio_node *node = &cpc_desc->non_mmio_nodes[i];
880 		struct rb_root_cached *tree;
881 
882 		if (!node->registered)
883 			continue;
884 
885 		tree = cpc_non_mmio_tree(node->space_id, node->pcc_ss_id);
886 		cpc_non_mmio_itree_remove(node, tree);
887 	}
888 
889 	kfree(cpc_desc->non_mmio_nodes);
890 	cpc_desc->non_mmio_nodes = NULL;
891 }
892 
893 static int cpc_register_non_mmio_desc(struct cpc_desc *cpc_desc)
894 {
895 	unsigned int nr_regs = cpc_desc->num_entries - 2;
896 	unsigned int i;
897 	int ret = 0;
898 	bool found = false;
899 
900 	for (i = 0; i < nr_regs; i++) {
901 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
902 		u8 space_id;
903 
904 		if (!CPC_SUPPORTED(reg) || reg->type != ACPI_TYPE_BUFFER)
905 			continue;
906 		space_id = reg->cpc_entry.reg.space_id;
907 		if (space_id == ACPI_ADR_SPACE_PLATFORM_COMM ||
908 		    space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
909 			found = true;
910 			break;
911 		}
912 	}
913 	if (!found)
914 		return 0;
915 
916 	cpc_desc->non_mmio_nodes = kcalloc(nr_regs,
917 					   sizeof(*cpc_desc->non_mmio_nodes),
918 					   GFP_KERNEL);
919 	if (!cpc_desc->non_mmio_nodes)
920 		return -ENOMEM;
921 
922 	mutex_lock(&cpc_non_mmio_lock);
923 
924 	for (i = 0; i < nr_regs; i++) {
925 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
926 		struct cpc_non_mmio_node *match, *node;
927 		struct rb_root_cached *tree;
928 		u8 space_id;
929 		u64 size;
930 
931 		if (!CPC_SUPPORTED(reg) || reg->type != ACPI_TYPE_BUFFER)
932 			continue;
933 
934 		space_id = reg->cpc_entry.reg.space_id;
935 		if (space_id != ACPI_ADR_SPACE_PLATFORM_COMM &&
936 		    space_id != ACPI_ADR_SPACE_SYSTEM_IO)
937 			continue;
938 
939 		node = &cpc_desc->non_mmio_nodes[i];
940 		size = cpc_non_mmio_access_size(reg);
941 		node->start = reg->cpc_entry.reg.address;
942 		node->last = node->start + size - 1;
943 		node->desc = cpc_desc;
944 		node->reg_idx = i;
945 		node->space_id = space_id;
946 		node->pcc_ss_id = space_id == ACPI_ADR_SPACE_PLATFORM_COMM ?
947 				      reg->cpc_entry.reg.access_width : 0;
948 		tree = cpc_non_mmio_tree(space_id, node->pcc_ss_id);
949 
950 		match = cpc_non_mmio_itree_iter_first(tree, node->start,
951 						      node->last);
952 		while (match) {
953 			ret = cpc_validate_non_mmio_pair(node, match);
954 			if (ret)
955 				goto out_unregister;
956 
957 			match = cpc_non_mmio_itree_iter_next(match, node->start,
958 							     node->last);
959 		}
960 		cpc_non_mmio_itree_insert(node, tree);
961 		node->registered = true;
962 	}
963 
964 	mutex_unlock(&cpc_non_mmio_lock);
965 	return 0;
966 
967 out_unregister:
968 	cpc_unregister_non_mmio_desc_locked(cpc_desc);
969 	mutex_unlock(&cpc_non_mmio_lock);
970 	return ret;
971 }
972 
973 static void cpc_unregister_non_mmio_desc(struct cpc_desc *cpc_desc)
974 {
975 	if (!cpc_desc->non_mmio_nodes)
976 		return;
977 
978 	mutex_lock(&cpc_non_mmio_lock);
979 	cpc_unregister_non_mmio_desc_locked(cpc_desc);
980 	mutex_unlock(&cpc_non_mmio_lock);
981 }
982 
983 static void cpc_mark_rmw_lock_users(struct cpc_desc *cpc_desc)
984 {
985 	int i;
986 
987 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
988 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
989 
990 		if (CPC_SUPPORTED(reg) && CPC_IN_SYSTEM_MEMORY(reg) &&
991 		    cpc_is_writable(reg))
992 			reg->cpc_entry.use_rmw_lock =
993 				cpc_sysmem_reg_needs_rmw(reg);
994 	}
995 }
996 
997 struct cpc_bit_position {
998 	u64 byte;
999 	u8 bit;
1000 };
1001 
1002 static bool cpc_bit_position_before(const struct cpc_bit_position *a,
1003 				    const struct cpc_bit_position *b)
1004 {
1005 	return a->byte < b->byte || (a->byte == b->byte && a->bit < b->bit);
1006 }
1007 
1008 static bool cpc_sysmem_fields_overlap(const struct cpc_register_resource *a,
1009 				      const struct cpc_register_resource *b)
1010 {
1011 	const struct cpc_reg *a_gas = &a->cpc_entry.reg;
1012 	const struct cpc_reg *b_gas = &b->cpc_entry.reg;
1013 	unsigned int a_last_bit = a_gas->bit_offset + a_gas->bit_width - 1;
1014 	unsigned int b_last_bit = b_gas->bit_offset + b_gas->bit_width - 1;
1015 	struct cpc_bit_position a_start = {
1016 		.byte = a_gas->address + a_gas->bit_offset / 8,
1017 		.bit = a_gas->bit_offset % 8,
1018 	};
1019 	struct cpc_bit_position a_end = {
1020 		.byte = a_gas->address + a_last_bit / 8,
1021 		.bit = a_last_bit % 8,
1022 	};
1023 	struct cpc_bit_position b_start = {
1024 		.byte = b_gas->address + b_gas->bit_offset / 8,
1025 		.bit = b_gas->bit_offset % 8,
1026 	};
1027 	struct cpc_bit_position b_end = {
1028 		.byte = b_gas->address + b_last_bit / 8,
1029 		.bit = b_last_bit % 8,
1030 	};
1031 
1032 	return !cpc_bit_position_before(&a_end, &b_start) &&
1033 	       !cpc_bit_position_before(&b_end, &a_start);
1034 }
1035 
1036 static bool cpc_sysmem_access_overlaps_field(const struct cpc_register_resource *access,
1037 					     const struct cpc_register_resource *field)
1038 {
1039 	const struct cpc_reg *access_gas = &access->cpc_entry.reg;
1040 	const struct cpc_reg *field_gas = &field->cpc_entry.reg;
1041 	u64 access_last;
1042 	u64 field_start;
1043 	u64 field_last;
1044 
1045 	if (!field_gas->bit_width)
1046 		return cpc_sysmem_access_units_overlap(access, field);
1047 
1048 	access_last = access_gas->address +
1049 		      cpc_sysmem_access_size(access) - 1;
1050 	field_start = field_gas->address + field_gas->bit_offset / 8;
1051 	field_last = field_gas->address +
1052 		     (field_gas->bit_offset + field_gas->bit_width - 1) / 8;
1053 
1054 	return access_gas->address <= field_last && field_start <= access_last;
1055 }
1056 
1057 static bool cpc_same_sysmem_register(unsigned int a_idx,
1058 				     const struct cpc_register_resource *a,
1059 				     unsigned int b_idx,
1060 				     const struct cpc_register_resource *b)
1061 {
1062 	const struct cpc_reg *a_gas = &a->cpc_entry.reg;
1063 	const struct cpc_reg *b_gas = &b->cpc_entry.reg;
1064 
1065 	return a_idx == b_idx &&
1066 	       a_gas->address == b_gas->address &&
1067 	       a_gas->bit_width == b_gas->bit_width &&
1068 	       a_gas->bit_offset == b_gas->bit_offset &&
1069 	       cpc_reg_access_width(a_gas) == cpc_reg_access_width(b_gas);
1070 }
1071 
1072 static int cpc_validate_sysmem_pair(const struct cpc_desc *a_desc,
1073 				    unsigned int a_idx,
1074 				    const struct cpc_desc *b_desc,
1075 				    unsigned int b_idx)
1076 {
1077 	const struct cpc_register_resource *a = &a_desc->cpc_regs[a_idx];
1078 	const struct cpc_register_resource *b = &b_desc->cpc_regs[b_idx];
1079 	bool a_write_only, b_write_only;
1080 	bool a_writable, b_writable;
1081 	bool fields_overlap;
1082 
1083 	/* The overlap helper includes each descriptor's conservative claim. */
1084 	if (!CPC_SUPPORTED(a) || !CPC_IN_SYSTEM_MEMORY(a) ||
1085 	    !CPC_SUPPORTED(b) || !CPC_IN_SYSTEM_MEMORY(b) ||
1086 	    !cpc_sysmem_access_units_overlap(a, b))
1087 		return 0;
1088 
1089 	a_write_only = cpc_reg_is_write_only(a_desc, a_idx);
1090 	b_write_only = cpc_reg_is_write_only(b_desc, b_idx);
1091 	fields_overlap = !a->cpc_entry.reg.bit_width ||
1092 			 !b->cpc_entry.reg.bit_width ||
1093 			 cpc_sysmem_fields_overlap(a, b);
1094 	/* A readable field must not expose another field's undefined bits. */
1095 	if (a_write_only != b_write_only &&
1096 	    cpc_is_readable(a_write_only ? b : a) &&
1097 	    fields_overlap)
1098 		goto conflict;
1099 
1100 	a_writable = cpc_reg_is_writable(a_idx) && cpc_is_writable(a);
1101 	b_writable = cpc_reg_is_writable(b_idx) && cpc_is_writable(b);
1102 	if (!a_writable && !b_writable)
1103 		return 0;
1104 
1105 	if (cpc_same_sysmem_register(a_idx, a, b_idx, b)) {
1106 		u64 access_size = cpc_sysmem_access_size(a);
1107 
1108 		/*
1109 		 * Exact partial aliases update the same field and retain
1110 		 * last-writer-wins semantics when the complete access is one native
1111 		 * transaction.  A 64-bit MMIO write may be split on 32-bit kernels,
1112 		 * and an unaligned x86 access is not guaranteed to be one device
1113 		 * transaction.
1114 		 */
1115 		if (!a_writable ||
1116 		    (IS_ALIGNED(a->cpc_entry.reg.address, access_size) &&
1117 		     (access_size < sizeof(u64) ||
1118 		      IS_ENABLED(CONFIG_64BIT))))
1119 			return 0;
1120 		goto conflict;
1121 	}
1122 
1123 	/*
1124 	 * The platform may set Performance Limited asynchronously.  A write to
1125 	 * another field in the same access unit could write back stale status
1126 	 * bits, which an OSPM lock cannot prevent.
1127 	 */
1128 	if ((a_idx == PERF_LIMITED && b_writable) ||
1129 	    (b_idx == PERF_LIMITED && a_writable))
1130 		goto conflict;
1131 
1132 	/* A full-width writer must not overwrite another logical field. */
1133 	if (fields_overlap &&
1134 	    ((a_writable && b_writable) ||
1135 	     (a_writable && !cpc_sysmem_reg_needs_rmw(a)) ||
1136 	     (b_writable && !cpc_sysmem_reg_needs_rmw(b))))
1137 		goto conflict;
1138 
1139 	/* Different descriptors do not share their partial-write locks. */
1140 	if (a_desc != b_desc && a_writable && b_writable)
1141 		goto conflict;
1142 
1143 	/*
1144 	 * RMW of either writer preserves the other field.  If that field is
1145 	 * write-only, its readback is undefined and cannot safely be replayed.
1146 	 */
1147 	if ((a_write_only && b_writable &&
1148 	     cpc_sysmem_reg_needs_rmw(b) &&
1149 	     cpc_sysmem_access_overlaps_field(b, a)) ||
1150 	    (b_write_only && a_writable &&
1151 	     cpc_sysmem_reg_needs_rmw(a) &&
1152 	     cpc_sysmem_access_overlaps_field(a, b)))
1153 		goto conflict;
1154 
1155 	return 0;
1156 
1157 conflict:
1158 	pr_err("CPU%d: SystemMemory _CPC register %u conflicts with CPU%d register %u\n",
1159 	       a_desc->cpu_id, a_idx, b_desc->cpu_id, b_idx);
1160 	return -EINVAL;
1161 }
1162 
1163 static bool cpc_disable_new_sysmem_writer(struct cpc_desc *cpc_desc,
1164 					  unsigned int reg_idx,
1165 					  const struct cpc_sysmem_node *node)
1166 {
1167 	struct cpc_register_resource *reg = &cpc_desc->cpc_regs[reg_idx];
1168 	struct cpc_sysmem_node *match;
1169 	unsigned int status_cpu = 0;
1170 	bool found = false;
1171 
1172 	if (!cpc_optional_writer_can_be_disabled(reg_idx) ||
1173 	    !cpc_is_writable(reg))
1174 		return false;
1175 
1176 	match = cpc_sysmem_first(node->start, node->last);
1177 	while (match) {
1178 		const struct cpc_register_resource *status;
1179 
1180 		if (match->reg_idx == PERF_LIMITED) {
1181 			status = &match->desc->cpc_regs[PERF_LIMITED];
1182 			if (!status->cpc_entry.reg.bit_width ||
1183 			    cpc_sysmem_fields_overlap(reg, status))
1184 				return false;
1185 			status_cpu = match->desc->cpu_id;
1186 			found = true;
1187 		}
1188 
1189 		match = cpc_sysmem_next(match, node->start, node->last);
1190 	}
1191 	if (!found)
1192 		return false;
1193 
1194 	pr_warn_once("CPU%d: ignoring optional _CPC register %u sharing CPU%d Performance Limited access unit\n",
1195 		     cpc_desc->cpu_id, reg_idx, status_cpu);
1196 	cpc_disable_reg(cpc_desc, reg_idx);
1197 	return true;
1198 }
1199 
1200 static void cpc_unregister_sysmem_desc_locked(struct cpc_desc *cpc_desc)
1201 {
1202 	unsigned int i;
1203 
1204 	if (!cpc_desc->sysmem_nodes)
1205 		return;
1206 
1207 	for (i = 0; i < cpc_desc->num_entries - 2; i++) {
1208 		struct cpc_sysmem_node *node = &cpc_desc->sysmem_nodes[i];
1209 		struct cpc_sysmem_node *alias, *child;
1210 
1211 		if (node->alias_of) {
1212 			list_del(&node->alias_node);
1213 			continue;
1214 		}
1215 		if (!node->registered)
1216 			continue;
1217 
1218 		cpc_sysmem_itree_remove(node, &cpc_sysmem_tree);
1219 		node->registered = false;
1220 		if (list_empty(&node->aliases))
1221 			continue;
1222 
1223 		/* Keep one representative for aliases owned by live descriptors. */
1224 		alias = list_first_entry(&node->aliases,
1225 					 struct cpc_sysmem_node, alias_node);
1226 		list_del_init(&alias->alias_node);
1227 		alias->alias_of = NULL;
1228 		alias->registered = true;
1229 		list_splice_init(&node->aliases, &alias->aliases);
1230 		list_for_each_entry(child, &alias->aliases, alias_node)
1231 			child->alias_of = alias;
1232 		cpc_sysmem_itree_insert(alias, &cpc_sysmem_tree);
1233 	}
1234 
1235 	kfree(cpc_desc->sysmem_nodes);
1236 	cpc_desc->sysmem_nodes = NULL;
1237 }
1238 
1239 static int cpc_register_sysmem_desc(struct cpc_desc *cpc_desc)
1240 {
1241 	unsigned int nr_regs = cpc_desc->num_entries - 2;
1242 	unsigned int i;
1243 	int ret = 0;
1244 	bool found = false;
1245 
1246 	for (i = 0; i < nr_regs; i++) {
1247 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
1248 
1249 		if (CPC_SUPPORTED(reg) && CPC_IN_SYSTEM_MEMORY(reg)) {
1250 			found = true;
1251 			break;
1252 		}
1253 	}
1254 	if (!found)
1255 		return 0;
1256 
1257 	cpc_desc->sysmem_nodes = kcalloc(nr_regs,
1258 					 sizeof(*cpc_desc->sysmem_nodes),
1259 					 GFP_KERNEL);
1260 	if (!cpc_desc->sysmem_nodes)
1261 		return -ENOMEM;
1262 
1263 	mutex_lock(&cpc_sysmem_lock);
1264 
1265 	for (i = 0; i < nr_regs; i++) {
1266 		struct cpc_register_resource *reg = &cpc_desc->cpc_regs[i];
1267 		struct cpc_sysmem_node *alias = NULL, *match, *node;
1268 		u64 size;
1269 
1270 		if (!CPC_SUPPORTED(reg) || !CPC_IN_SYSTEM_MEMORY(reg))
1271 			continue;
1272 
1273 		node = &cpc_desc->sysmem_nodes[i];
1274 		size = cpc_sysmem_claim_size(reg);
1275 		node->start = reg->cpc_entry.reg.address;
1276 		node->last = node->start + size - 1;
1277 		node->desc = cpc_desc;
1278 		node->reg_idx = i;
1279 		INIT_LIST_HEAD(&node->aliases);
1280 		INIT_LIST_HEAD(&node->alias_node);
1281 
1282 		/* Performance Limited precedes every optional writer we may disable. */
1283 		if (cpc_disable_new_sysmem_writer(cpc_desc, i, node))
1284 			continue;
1285 
1286 		match = cpc_sysmem_first(node->start, node->last);
1287 		while (match) {
1288 			struct cpc_register_resource *match_reg;
1289 
1290 			match_reg = &match->desc->cpc_regs[match->reg_idx];
1291 			ret = cpc_validate_sysmem_pair(cpc_desc, i, match->desc,
1292 						       match->reg_idx);
1293 			if (ret)
1294 				goto out_unregister;
1295 			if (cpc_desc == match->desc) {
1296 				reg->cpc_entry.use_rmw_lock = true;
1297 				match_reg->cpc_entry.use_rmw_lock = true;
1298 			}
1299 			if (cpc_same_sysmem_register(i, reg, match->reg_idx, match_reg))
1300 				alias = match;
1301 
1302 			match = cpc_sysmem_next(match, node->start, node->last);
1303 		}
1304 		if (alias) {
1305 			node->alias_of = alias;
1306 			list_add_tail(&node->alias_node, &alias->aliases);
1307 			continue;
1308 		}
1309 
1310 		cpc_sysmem_itree_insert(node, &cpc_sysmem_tree);
1311 		node->registered = true;
1312 	}
1313 
1314 	mutex_unlock(&cpc_sysmem_lock);
1315 	return 0;
1316 
1317 out_unregister:
1318 	cpc_unregister_sysmem_desc_locked(cpc_desc);
1319 	mutex_unlock(&cpc_sysmem_lock);
1320 	return ret;
1321 }
1322 
1323 static void cpc_unregister_sysmem_desc(struct cpc_desc *cpc_desc)
1324 {
1325 	if (!cpc_desc->sysmem_nodes)
1326 		return;
1327 
1328 	mutex_lock(&cpc_sysmem_lock);
1329 	cpc_unregister_sysmem_desc_locked(cpc_desc);
1330 	mutex_unlock(&cpc_sysmem_lock);
1331 }
1332 
1333 static ssize_t show_feedback_ctrs(struct kobject *kobj,
1334 		struct kobj_attribute *attr, char *buf)
1335 {
1336 	struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);
1337 	struct cppc_perf_fb_ctrs fb_ctrs = {0};
1338 	int ret;
1339 
1340 	ret = cppc_get_perf_ctrs(cpc_ptr->cpu_id, &fb_ctrs);
1341 	if (ret)
1342 		return ret;
1343 
1344 	return sysfs_emit(buf, "ref:%llu del:%llu\n",
1345 			fb_ctrs.reference, fb_ctrs.delivered);
1346 }
1347 define_one_cppc_ro(feedback_ctrs);
1348 
1349 static struct attribute *cppc_attrs[] = {
1350 	&feedback_ctrs.attr,
1351 	&reference_perf.attr,
1352 	&wraparound_time.attr,
1353 	&highest_perf.attr,
1354 	&lowest_perf.attr,
1355 	&lowest_nonlinear_perf.attr,
1356 	&guaranteed_perf.attr,
1357 	&nominal_perf.attr,
1358 	&nominal_freq.attr,
1359 	&lowest_freq.attr,
1360 	NULL
1361 };
1362 ATTRIBUTE_GROUPS(cppc);
1363 
1364 static void cppc_free_desc(struct cpc_desc *cpc_ptr)
1365 {
1366 	unsigned int i;
1367 
1368 	cpc_unregister_non_mmio_desc(cpc_ptr);
1369 	cpc_unregister_sysmem_desc(cpc_ptr);
1370 
1371 	for (i = 2; i < cpc_ptr->num_entries; i++) {
1372 		void __iomem *addr = cpc_ptr->cpc_regs[i - 2].sys_mem_vaddr;
1373 
1374 		if (addr)
1375 			iounmap(addr);
1376 	}
1377 
1378 	kfree(cpc_ptr);
1379 }
1380 
1381 static void cppc_kobj_release(struct kobject *kobj)
1382 {
1383 	cppc_free_desc(to_cpc_desc(kobj));
1384 }
1385 
1386 static const struct kobj_type cppc_ktype = {
1387 	.release = cppc_kobj_release,
1388 	.sysfs_ops = &kobj_sysfs_ops,
1389 	.default_groups = cppc_groups,
1390 };
1391 
1392 static int check_pcc_chan(int pcc_ss_id, bool chk_err_bit)
1393 {
1394 	int ret, status;
1395 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
1396 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
1397 					pcc_ss_data->pcc_channel->shmem;
1398 
1399 	if (!pcc_ss_data->platform_owns_pcc)
1400 		return 0;
1401 
1402 	/*
1403 	 * Poll PCC status register every 3us(delay_us) for maximum of
1404 	 * deadline_us(timeout_us) until PCC command complete bit is set(cond)
1405 	 */
1406 	ret = readw_relaxed_poll_timeout(&generic_comm_base->status, status,
1407 					status & PCC_CMD_COMPLETE_MASK, 3,
1408 					pcc_ss_data->deadline_us);
1409 
1410 	if (likely(!ret)) {
1411 		/* Order completion status before reading the returned payload. */
1412 		rmb();
1413 		pcc_ss_data->platform_owns_pcc = false;
1414 		if (chk_err_bit && (status & PCC_ERROR_MASK))
1415 			ret = -EIO;
1416 	}
1417 
1418 	if (unlikely(ret))
1419 		pr_err("PCC check channel failed for ss: %d. ret=%d\n",
1420 		       pcc_ss_id, ret);
1421 
1422 	return ret;
1423 }
1424 
1425 static void cppc_complete_pcc_write(int pcc_ss_id,
1426 				    struct cppc_pcc_data *pcc_ss_data, int ret)
1427 {
1428 	int i;
1429 
1430 	if (unlikely(ret)) {
1431 		for_each_possible_cpu(i) {
1432 			struct cpc_desc *desc = per_cpu(cpc_desc_ptr, i);
1433 
1434 			if (!desc ||
1435 			    per_cpu(cpu_pcc_subspace_idx, i) != pcc_ss_id)
1436 				continue;
1437 
1438 			if (desc->write_cmd_id == pcc_ss_data->pcc_write_cnt)
1439 				desc->write_cmd_status = ret;
1440 		}
1441 	}
1442 
1443 	pcc_ss_data->pcc_write_cnt++;
1444 	wake_up_all(&pcc_ss_data->pcc_write_wait_q);
1445 }
1446 
1447 /* The caller must hold pcc_lock for write. */
1448 static void cppc_abort_pending_pcc_write(int pcc_ss_id,
1449 					 struct cppc_pcc_data *pcc_ss_data,
1450 					 int ret)
1451 {
1452 	if (!pcc_ss_data->pending_pcc_write_cmd)
1453 		return;
1454 
1455 	pcc_ss_data->pending_pcc_write_cmd = false;
1456 	cppc_complete_pcc_write(pcc_ss_id, pcc_ss_data, ret);
1457 }
1458 
1459 /*
1460  * This function transfers the ownership of the PCC to the platform
1461  * So it must be called while holding write_lock(pcc_lock)
1462  */
1463 static int send_pcc_cmd(int pcc_ss_id, u16 cmd)
1464 {
1465 	int ret = -EIO;
1466 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
1467 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
1468 					pcc_ss_data->pcc_channel->shmem;
1469 	unsigned int time_delta;
1470 
1471 	/*
1472 	 * For CMD_WRITE we know for a fact the caller should have checked
1473 	 * the channel before writing to PCC space
1474 	 */
1475 	if (cmd == CMD_READ) {
1476 		/*
1477 		 * If there are pending cpc_writes, then we stole the channel
1478 		 * before write completion, so first send a WRITE command to
1479 		 * platform
1480 		 */
1481 		if (pcc_ss_data->pending_pcc_write_cmd)
1482 			send_pcc_cmd(pcc_ss_id, CMD_WRITE);
1483 
1484 		ret = check_pcc_chan(pcc_ss_id, false);
1485 		if (ret)
1486 			goto end;
1487 	} else /* CMD_WRITE */
1488 		pcc_ss_data->pending_pcc_write_cmd = FALSE;
1489 
1490 	/*
1491 	 * Handle the Minimum Request Turnaround Time(MRTT)
1492 	 * "The minimum amount of time that OSPM must wait after the completion
1493 	 * of a command before issuing the next command, in microseconds"
1494 	 */
1495 	if (pcc_ss_data->pcc_mrtt) {
1496 		time_delta = ktime_us_delta(ktime_get(),
1497 					    pcc_ss_data->last_cmd_cmpl_time);
1498 		if (pcc_ss_data->pcc_mrtt > time_delta)
1499 			udelay(pcc_ss_data->pcc_mrtt - time_delta);
1500 	}
1501 
1502 	/*
1503 	 * Handle the non-zero Maximum Periodic Access Rate(MPAR)
1504 	 * "The maximum number of periodic requests that the subspace channel can
1505 	 * support, reported in commands per minute. 0 indicates no limitation."
1506 	 *
1507 	 * This parameter should be ideally zero or large enough so that it can
1508 	 * handle maximum number of requests that all the cores in the system can
1509 	 * collectively generate. If it is not, we will follow the spec and just
1510 	 * not send the request to the platform after hitting the MPAR limit in
1511 	 * any 60s window
1512 	 */
1513 	if (pcc_ss_data->pcc_mpar) {
1514 		if (pcc_ss_data->mpar_count == 0) {
1515 			time_delta = ktime_ms_delta(ktime_get(),
1516 						    pcc_ss_data->last_mpar_reset);
1517 			if ((time_delta < 60 * MSEC_PER_SEC) && pcc_ss_data->last_mpar_reset) {
1518 				pr_debug("PCC cmd for subspace %d not sent due to MPAR limit",
1519 					 pcc_ss_id);
1520 				ret = -EIO;
1521 				goto end;
1522 			}
1523 			pcc_ss_data->last_mpar_reset = ktime_get();
1524 			pcc_ss_data->mpar_count = pcc_ss_data->pcc_mpar;
1525 		}
1526 		pcc_ss_data->mpar_count--;
1527 	}
1528 
1529 	/* Write to the shared comm region. */
1530 	writew_relaxed(cmd, &generic_comm_base->command);
1531 
1532 	/* Flip CMD COMPLETE bit */
1533 	writew_relaxed(0, &generic_comm_base->status);
1534 
1535 	pcc_ss_data->platform_owns_pcc = true;
1536 
1537 	/* Ring doorbell */
1538 	ret = mbox_send_message(pcc_ss_data->pcc_channel->mchan, &cmd);
1539 	if (ret < 0) {
1540 		pr_err("Err sending PCC mbox message. ss: %d cmd:%d, ret:%d\n",
1541 		       pcc_ss_id, cmd, ret);
1542 		goto end;
1543 	}
1544 
1545 	/* wait for completion and check for PCC error bit */
1546 	ret = check_pcc_chan(pcc_ss_id, true);
1547 
1548 	if (pcc_ss_data->pcc_mrtt)
1549 		pcc_ss_data->last_cmd_cmpl_time = ktime_get();
1550 
1551 	if (pcc_ss_data->pcc_channel->mchan->mbox->txdone_irq)
1552 		mbox_chan_txdone(pcc_ss_data->pcc_channel->mchan, ret);
1553 	else
1554 		mbox_client_txdone(pcc_ss_data->pcc_channel->mchan, ret);
1555 
1556 end:
1557 	if (cmd == CMD_WRITE)
1558 		cppc_complete_pcc_write(pcc_ss_id, pcc_ss_data, ret);
1559 
1560 	return ret;
1561 }
1562 
1563 static void cppc_chan_tx_done(struct mbox_client *cl, void *msg, int ret)
1564 {
1565 	if (ret < 0)
1566 		pr_debug("TX did not complete: CMD sent:%x, ret:%d\n",
1567 				*(u16 *)msg, ret);
1568 	else
1569 		pr_debug("TX completed. CMD sent:%x, ret:%d\n",
1570 				*(u16 *)msg, ret);
1571 }
1572 
1573 static struct mbox_client cppc_mbox_cl = {
1574 	.tx_done = cppc_chan_tx_done,
1575 	.knows_txdone = true,
1576 };
1577 
1578 static int acpi_get_psd(struct cpc_desc *cpc_ptr, acpi_handle handle)
1579 {
1580 	int result = -EFAULT;
1581 	acpi_status status = AE_OK;
1582 	struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
1583 	struct acpi_buffer format = {sizeof("NNNNN"), "NNNNN"};
1584 	struct acpi_buffer state = {0, NULL};
1585 	union acpi_object  *psd = NULL;
1586 	struct acpi_psd_package *pdomain;
1587 
1588 	status = acpi_evaluate_object_typed(handle, "_PSD", NULL,
1589 					    &buffer, ACPI_TYPE_PACKAGE);
1590 	if (status == AE_NOT_FOUND)	/* _PSD is optional */
1591 		return 0;
1592 	if (ACPI_FAILURE(status))
1593 		return -ENODEV;
1594 
1595 	psd = buffer.pointer;
1596 	if (!psd || psd->package.count != 1) {
1597 		pr_debug("Invalid _PSD data\n");
1598 		goto end;
1599 	}
1600 
1601 	pdomain = &(cpc_ptr->domain_info);
1602 
1603 	state.length = sizeof(struct acpi_psd_package);
1604 	state.pointer = pdomain;
1605 
1606 	status = acpi_extract_package(&(psd->package.elements[0]),
1607 		&format, &state);
1608 	if (ACPI_FAILURE(status)) {
1609 		pr_debug("Invalid _PSD data for CPU:%d\n", cpc_ptr->cpu_id);
1610 		goto end;
1611 	}
1612 
1613 	if (pdomain->num_entries != ACPI_PSD_REV0_ENTRIES) {
1614 		pr_debug("Unknown _PSD:num_entries for CPU:%d\n", cpc_ptr->cpu_id);
1615 		goto end;
1616 	}
1617 
1618 	if (pdomain->revision != ACPI_PSD_REV0_REVISION) {
1619 		pr_debug("Unknown _PSD:revision for CPU: %d\n", cpc_ptr->cpu_id);
1620 		goto end;
1621 	}
1622 
1623 	if (pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ALL &&
1624 	    pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ANY &&
1625 	    pdomain->coord_type != DOMAIN_COORD_TYPE_HW_ALL) {
1626 		pr_debug("Invalid _PSD:coord_type for CPU:%d\n", cpc_ptr->cpu_id);
1627 		goto end;
1628 	}
1629 
1630 	result = 0;
1631 end:
1632 	kfree(buffer.pointer);
1633 	return result;
1634 }
1635 
1636 bool acpi_cpc_valid(void)
1637 {
1638 	struct cpc_desc *cpc_ptr;
1639 	int cpu;
1640 
1641 	if (acpi_disabled)
1642 		return false;
1643 
1644 	for_each_online_cpu(cpu) {
1645 		cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
1646 		if (!cpc_ptr)
1647 			return false;
1648 	}
1649 
1650 	return true;
1651 }
1652 EXPORT_SYMBOL_GPL(acpi_cpc_valid);
1653 
1654 bool cppc_allow_fast_switch(const struct cpumask *cpus)
1655 {
1656 	struct cpc_register_resource *desired_reg, *min_reg, *max_reg;
1657 	struct cpc_desc *cpc_ptr;
1658 	int cpu;
1659 
1660 	for_each_cpu(cpu, cpus) {
1661 		cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
1662 		if (!cpc_ptr)
1663 			return false;
1664 		desired_reg = &cpc_ptr->cpc_regs[DESIRED_PERF];
1665 		min_reg = &cpc_ptr->cpc_regs[MIN_PERF];
1666 		max_reg = &cpc_ptr->cpc_regs[MAX_PERF];
1667 
1668 		if (!cpc_is_writable(desired_reg) ||
1669 		    (!CPC_IN_SYSTEM_MEMORY(desired_reg) &&
1670 		     !CPC_IN_SYSTEM_IO(desired_reg)) ||
1671 		    (CPC_SUPPORTED(min_reg) &&
1672 		     !CPC_IN_SYSTEM_MEMORY(min_reg) &&
1673 		     !CPC_IN_SYSTEM_IO(min_reg)) ||
1674 		    (CPC_SUPPORTED(max_reg) &&
1675 		     !CPC_IN_SYSTEM_MEMORY(max_reg) &&
1676 		     !CPC_IN_SYSTEM_IO(max_reg)))
1677 			return false;
1678 	}
1679 
1680 	return true;
1681 }
1682 EXPORT_SYMBOL_GPL(cppc_allow_fast_switch);
1683 
1684 /**
1685  * acpi_get_psd_map - Map the CPUs in the freq domain of a given cpu
1686  * @cpu: Find all CPUs that share a domain with cpu.
1687  * @cpu_data: Pointer to CPU specific CPPC data including PSD info.
1688  *
1689  *	Return: 0 for success or negative value for err.
1690  */
1691 int acpi_get_psd_map(unsigned int cpu, struct cppc_cpudata *cpu_data)
1692 {
1693 	struct cpc_desc *cpc_ptr, *match_cpc_ptr;
1694 	struct acpi_psd_package *match_pdomain;
1695 	struct acpi_psd_package *pdomain;
1696 	int count_target, i;
1697 
1698 	/*
1699 	 * Now that we have _PSD data from all CPUs, let's setup P-state
1700 	 * domain info.
1701 	 */
1702 	cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
1703 	if (!cpc_ptr)
1704 		return -EFAULT;
1705 
1706 	pdomain = &(cpc_ptr->domain_info);
1707 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
1708 	if (pdomain->num_processors <= 1)
1709 		return 0;
1710 
1711 	/* Validate the Domain info */
1712 	count_target = pdomain->num_processors;
1713 	if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ALL)
1714 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ALL;
1715 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_HW_ALL)
1716 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_HW;
1717 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ANY)
1718 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ANY;
1719 
1720 	for_each_possible_cpu(i) {
1721 		if (i == cpu)
1722 			continue;
1723 
1724 		match_cpc_ptr = per_cpu(cpc_desc_ptr, i);
1725 		if (!match_cpc_ptr)
1726 			continue;
1727 
1728 		match_pdomain = &(match_cpc_ptr->domain_info);
1729 		if (match_pdomain->domain != pdomain->domain)
1730 			continue;
1731 
1732 		/* Here i and cpu are in the same domain */
1733 		if (match_pdomain->num_processors != count_target)
1734 			goto err_fault;
1735 
1736 		if (pdomain->coord_type != match_pdomain->coord_type)
1737 			goto err_fault;
1738 
1739 		cpumask_set_cpu(i, cpu_data->shared_cpu_map);
1740 	}
1741 
1742 	return 0;
1743 
1744 err_fault:
1745 	/* Assume no coordination on any error parsing domain info */
1746 	cpumask_clear(cpu_data->shared_cpu_map);
1747 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
1748 	cpu_data->shared_type = CPUFREQ_SHARED_TYPE_NONE;
1749 
1750 	return -EFAULT;
1751 }
1752 EXPORT_SYMBOL_GPL(acpi_get_psd_map);
1753 
1754 static int register_pcc_channel(int pcc_ss_idx)
1755 {
1756 	struct cppc_pcc_data *data;
1757 	struct pcc_mbox_chan *pcc_chan;
1758 	u64 usecs_lat;
1759 	int ret = 0;
1760 
1761 	if (pcc_ss_idx < 0 || pcc_ss_idx >= MAX_PCC_SUBSPACES)
1762 		return -EINVAL;
1763 
1764 	mutex_lock(&pcc_data_lock);
1765 	data = pcc_data[pcc_ss_idx];
1766 	if (!data) {
1767 		ret = -ENODEV;
1768 		goto out_unlock;
1769 	}
1770 	if (data->pcc_channel_acquired)
1771 		goto out_unlock;
1772 
1773 	pcc_chan = pcc_mbox_request_channel(&cppc_mbox_cl, pcc_ss_idx);
1774 	if (IS_ERR(pcc_chan)) {
1775 		ret = -ENODEV;
1776 		goto out_unlock;
1777 	}
1778 
1779 	data->pcc_channel = pcc_chan;
1780 	/*
1781 	 * cppc_ss->latency is just a Nominal value. In reality
1782 	 * the remote processor could be much slower to reply.
1783 	 * So add an arbitrary amount of wait on top of Nominal.
1784 	 */
1785 	usecs_lat = NUM_RETRIES * pcc_chan->latency;
1786 	data->deadline_us = usecs_lat;
1787 	data->pcc_mrtt = pcc_chan->min_turnaround_time;
1788 	data->pcc_mpar = pcc_chan->max_access_rate;
1789 	data->pcc_nominal = pcc_chan->latency;
1790 	init_rwsem(&data->pcc_lock);
1791 	init_waitqueue_head(&data->pcc_write_wait_q);
1792 
1793 	/* Reuse this channel when another CPU references the same subspace. */
1794 	data->pcc_channel_acquired = true;
1795 
1796 out_unlock:
1797 	mutex_unlock(&pcc_data_lock);
1798 	return ret;
1799 }
1800 
1801 /**
1802  * cpc_ffh_supported() - check if FFH reading supported
1803  *
1804  * Check if the architecture has support for functional fixed hardware
1805  * read/write capability.
1806  *
1807  * Return: true for supported, false for not supported
1808  */
1809 bool __weak cpc_ffh_supported(void)
1810 {
1811 	return false;
1812 }
1813 
1814 /**
1815  * cpc_supported_by_cpu() - check if CPPC is supported by CPU
1816  *
1817  * Check if the architectural support for CPPC is present even
1818  * if the _OSC hasn't prescribed it
1819  *
1820  * Return: true for supported, false for not supported
1821  */
1822 bool __weak cpc_supported_by_cpu(void)
1823 {
1824 	return false;
1825 }
1826 
1827 /**
1828  * pcc_data_alloc() - Allocate the pcc_data memory for pcc subspace
1829  * @pcc_ss_id: PCC Subspace index as in the PCC client ACPI package.
1830  *
1831  * Check and allocate the cppc_pcc_data memory.
1832  * In some processor configurations it is possible that same subspace
1833  * is shared between multiple CPUs. This is seen especially in CPUs
1834  * with hardware multi-threading support.
1835  *
1836  * Return: 0 for success, errno for failure
1837  */
1838 static int pcc_data_alloc(int pcc_ss_id)
1839 {
1840 	struct cppc_pcc_data *data;
1841 	int ret = 0;
1842 
1843 	if (pcc_ss_id < 0 || pcc_ss_id >= MAX_PCC_SUBSPACES)
1844 		return -EINVAL;
1845 
1846 	mutex_lock(&pcc_data_lock);
1847 	data = pcc_data[pcc_ss_id];
1848 	if (!data) {
1849 		data = kzalloc_obj(struct cppc_pcc_data);
1850 		if (!data) {
1851 			ret = -ENOMEM;
1852 			goto out_unlock;
1853 		}
1854 		raw_spin_lock_init(&data->payload_lock);
1855 		pcc_data[pcc_ss_id] = data;
1856 	}
1857 	data->refcount++;
1858 
1859 out_unlock:
1860 	mutex_unlock(&pcc_data_lock);
1861 	return ret;
1862 }
1863 
1864 static void pcc_data_put(int pcc_ss_id)
1865 {
1866 	struct cppc_pcc_data *data;
1867 
1868 	if (pcc_ss_id < 0 || pcc_ss_id >= MAX_PCC_SUBSPACES)
1869 		return;
1870 
1871 	mutex_lock(&pcc_data_lock);
1872 	data = pcc_data[pcc_ss_id];
1873 	if (!data || --data->refcount)
1874 		goto out_unlock;
1875 
1876 	pcc_data[pcc_ss_id] = NULL;
1877 	if (data->pcc_channel_acquired)
1878 		pcc_mbox_free_channel(data->pcc_channel);
1879 
1880 	kfree(data);
1881 
1882 out_unlock:
1883 	mutex_unlock(&pcc_data_lock);
1884 }
1885 
1886 /*
1887  * An example CPC table looks like the following.
1888  *
1889  *  Name (_CPC, Package() {
1890  *      17,							// NumEntries
1891  *      1,							// Revision
1892  *      ResourceTemplate() {Register(PCC, 32, 0, 0x120, 2)},	// Highest Performance
1893  *      ResourceTemplate() {Register(PCC, 32, 0, 0x124, 2)},	// Nominal Performance
1894  *      ResourceTemplate() {Register(PCC, 32, 0, 0x128, 2)},	// Lowest Nonlinear Performance
1895  *      ResourceTemplate() {Register(PCC, 32, 0, 0x12C, 2)},	// Lowest Performance
1896  *      ResourceTemplate() {Register(PCC, 32, 0, 0x130, 2)},	// Guaranteed Performance Register
1897  *      ResourceTemplate() {Register(PCC, 32, 0, 0x110, 2)},	// Desired Performance Register
1898  *      ResourceTemplate() {Register(SystemMemory, 0, 0, 0, 0)},
1899  *      ...
1900  *      ...
1901  *      ...
1902  *  }
1903  * Each Register() encodes how to access that specific register.
1904  * e.g. a sample PCC entry has the following encoding:
1905  *
1906  *  Register (
1907  *      PCC,	// AddressSpaceKeyword
1908  *      8,	// RegisterBitWidth
1909  *      8,	// RegisterBitOffset
1910  *      0x30,	// RegisterAddress
1911  *      9,	// AccessSize (subspace ID)
1912  *  )
1913  */
1914 
1915 /**
1916  * acpi_cppc_processor_probe - Search for per CPU _CPC objects.
1917  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
1918  *
1919  *	Return: 0 for success or negative value for err.
1920  */
1921 int acpi_cppc_processor_probe(struct acpi_processor *pr)
1922 {
1923 	struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
1924 	union acpi_object *out_obj, *cpc_obj;
1925 	struct cpc_desc *cpc_ptr;
1926 	struct cpc_reg *gas_t;
1927 	struct device *cpu_dev;
1928 	acpi_handle handle = pr->handle;
1929 	unsigned int num_ent, i, cpc_rev;
1930 	u32 unsupported_regs = 0;
1931 	u32 platform_quirks;
1932 	int pcc_subspace_id = -1;
1933 	bool pcc_data_ref = false;
1934 	bool cpc_present = false;
1935 	acpi_status status;
1936 	int ret = -EINVAL;
1937 	int err;
1938 
1939 	if (per_cpu(cpc_desc_ptr, pr->id))
1940 		return 0;
1941 	ret = cpc_get_platform_quirks(&platform_quirks);
1942 	if (ret) {
1943 		pr_err("CPU%d: failed to match CPPC platform quirks: %d\n",
1944 		       pr->id, ret);
1945 		return ret;
1946 	}
1947 	per_cpu(cpu_pcc_subspace_idx, pr->id) = -1;
1948 
1949 	if (!osc_sb_cppc2_support_acked) {
1950 		pr_debug("CPPC v2 _OSC not acked\n");
1951 		if (!cpc_supported_by_cpu()) {
1952 			pr_debug("CPPC is not supported by the CPU\n");
1953 			return -ENODEV;
1954 		}
1955 	}
1956 
1957 	/* Parse the ACPI _CPC table for this CPU. */
1958 	status = acpi_evaluate_object_typed(handle, "_CPC", NULL, &output,
1959 			ACPI_TYPE_PACKAGE);
1960 	if (ACPI_FAILURE(status)) {
1961 		ret = -ENODEV;
1962 		goto out_buf_free;
1963 	}
1964 	cpc_present = true;
1965 	ret = -EINVAL;
1966 
1967 	out_obj = (union acpi_object *) output.pointer;
1968 	if (out_obj->package.count < 2) {
1969 		pr_debug("Unexpected _CPC package count (%u) for CPU:%d\n",
1970 			 out_obj->package.count, pr->id);
1971 		goto out_buf_free;
1972 	}
1973 
1974 	cpc_ptr = kzalloc_obj(struct cpc_desc);
1975 	if (!cpc_ptr) {
1976 		ret = -ENOMEM;
1977 		goto out_buf_free;
1978 	}
1979 	cpc_ptr->cpu_id = pr->id;
1980 
1981 	/* First entry is NumEntries. */
1982 	cpc_obj = &out_obj->package.elements[0];
1983 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
1984 		if (cpc_obj->integer.value < 2 ||
1985 		    cpc_obj->integer.value > out_obj->package.count) {
1986 			pr_debug("Invalid _CPC NumEntries (%llu) for package count (%u) on CPU:%d\n",
1987 				 cpc_obj->integer.value, out_obj->package.count,
1988 				 pr->id);
1989 			goto out_free;
1990 		}
1991 
1992 		num_ent = cpc_obj->integer.value;
1993 	} else {
1994 		pr_debug("Unexpected _CPC NumEntries entry type (%d) for CPU:%d\n",
1995 			 cpc_obj->type, pr->id);
1996 		goto out_free;
1997 	}
1998 
1999 	/* Second entry should be revision. */
2000 	cpc_obj = &out_obj->package.elements[1];
2001 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
2002 		if (cpc_obj->integer.value > U8_MAX) {
2003 			pr_debug("Invalid _CPC Revision (%llu) for CPU:%d\n",
2004 				 cpc_obj->integer.value, pr->id);
2005 			ret = -EINVAL;
2006 			goto out_free;
2007 		}
2008 		cpc_rev = cpc_obj->integer.value;
2009 	} else {
2010 		pr_debug("Unexpected _CPC Revision entry type (%d) for CPU:%d\n",
2011 			 cpc_obj->type, pr->id);
2012 		goto out_free;
2013 	}
2014 
2015 	if (cpc_rev < CPPC_V2_REV) {
2016 		pr_debug("Unsupported _CPC Revision (%d) for CPU:%d\n", cpc_rev,
2017 			 pr->id);
2018 		goto out_free;
2019 	}
2020 
2021 	/*
2022 	 * Disregard _CPC if the number of entries in the return package is not
2023 	 * as expected, but support future revisions being proper supersets of
2024 	 * the v4 and only causing more entries to be returned by _CPC.
2025 	 */
2026 	if ((cpc_rev == CPPC_V2_REV && num_ent != CPPC_V2_NUM_ENT) ||
2027 	    (cpc_rev == CPPC_V3_REV && num_ent != CPPC_V3_NUM_ENT) ||
2028 	    (cpc_rev == CPPC_V4_REV && num_ent != CPPC_V4_NUM_ENT) ||
2029 	    (cpc_rev > CPPC_V4_REV && num_ent <= CPPC_V4_NUM_ENT)) {
2030 		pr_debug("Unexpected number of _CPC return package entries (%d) for CPU:%d\n",
2031 			 num_ent, pr->id);
2032 		goto out_free;
2033 	}
2034 	if (cpc_rev > CPPC_V4_REV) {
2035 		num_ent = CPPC_V4_NUM_ENT;
2036 		cpc_rev = CPPC_V4_REV;
2037 	}
2038 
2039 	cpc_ptr->num_entries = num_ent;
2040 	cpc_ptr->version = cpc_rev;
2041 
2042 	/* Iterate through remaining entries in _CPC */
2043 	for (i = 2; i < num_ent; i++) {
2044 		cpc_obj = &out_obj->package.elements[i];
2045 
2046 		if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
2047 			bool legacy_null;
2048 
2049 			if (!cpc_integer_entry_valid(i - 2,
2050 						     cpc_obj->integer.value,
2051 						     &legacy_null)) {
2052 				pr_debug("Invalid Integer _CPC register %u for CPU:%d\n",
2053 					 i - 2, pr->id);
2054 				ret = -EINVAL;
2055 				goto out_free;
2056 			}
2057 			if (legacy_null)
2058 				pr_warn_once(FW_BUG "_CPC register %u uses Integer 0 for an absent Buffer\n",
2059 					     i - 2);
2060 			cpc_ptr->cpc_regs[i - 2].type = ACPI_TYPE_INTEGER;
2061 			cpc_ptr->cpc_regs[i - 2].cpc_entry.int_value = cpc_obj->integer.value;
2062 		} else if (cpc_obj->type == ACPI_TYPE_BUFFER) {
2063 			if (cpc_obj->buffer.length < sizeof(*gas_t)) {
2064 				pr_debug("Invalid register descriptor for CPU:%d\n",
2065 					 pr->id);
2066 				ret = -EINVAL;
2067 				goto out_free;
2068 			}
2069 
2070 			gas_t = (struct cpc_reg *)
2071 				cpc_obj->buffer.pointer;
2072 			if (gas_t->descriptor != CPC_GENERIC_REGISTER_DESCRIPTOR ||
2073 			    gas_t->length != CPC_GENERIC_REGISTER_LENGTH) {
2074 				pr_debug("Invalid register resource for CPU:%d\n",
2075 					 pr->id);
2076 				ret = -EINVAL;
2077 				goto out_free;
2078 			}
2079 
2080 			cpc_ptr->cpc_regs[i - 2].type = ACPI_TYPE_BUFFER;
2081 			memcpy(&cpc_ptr->cpc_regs[i - 2].cpc_entry.reg, gas_t,
2082 			       sizeof(*gas_t));
2083 			gas_t = &cpc_ptr->cpc_regs[i - 2].cpc_entry.reg;
2084 			cpc_apply_platform_quirks(gas_t, i - 2,
2085 						  platform_quirks);
2086 
2087 			/*
2088 			 * The PCC Subspace index is encoded inside
2089 			 * the CPC table entries. The same PCC index
2090 			 * will be used for all the PCC entries,
2091 			 * so extract it only once.
2092 			 */
2093 			if (gas_t->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
2094 				/* These registers have no specified 32-bit upper bound. */
2095 				bool wide_write = i - 2 == PERF_LIMITED ||
2096 						  i - 2 == ENABLE ||
2097 						  i - 2 == AUTO_SEL_ENABLE;
2098 				bool write_width_supported = gas_t->bit_width == 8 ||
2099 						     gas_t->bit_width == 16 ||
2100 						     gas_t->bit_width == 32 ||
2101 						     gas_t->bit_width == 64;
2102 				bool unsupported;
2103 
2104 				unsupported = !gas_t->bit_width ||
2105 					      gas_t->bit_width > 64 ||
2106 					      gas_t->bit_offset ||
2107 					      gas_t->bit_width % 8 ||
2108 					      (cpc_reg_is_writable(i - 2) &&
2109 					       (!write_width_supported ||
2110 						(!wide_write && gas_t->bit_width > 32)));
2111 				if (unsupported) {
2112 					if (!cpc_retain_pcc_status(cpc_ptr, i - 2))
2113 						unsupported_regs |= BIT(i - 2);
2114 					continue;
2115 				}
2116 
2117 				if (pcc_subspace_id < 0) {
2118 					pcc_subspace_id = gas_t->access_width;
2119 				} else if (pcc_subspace_id != gas_t->access_width) {
2120 					pr_debug("Mismatched PCC ids in _CPC for CPU:%d\n",
2121 						 pr->id);
2122 					ret = -EINVAL;
2123 					goto out_free;
2124 				}
2125 
2126 				if (!pcc_data_ref) {
2127 					err = pcc_data_alloc(pcc_subspace_id);
2128 					if (err) {
2129 						ret = err;
2130 						goto out_free;
2131 					}
2132 					pcc_data_ref = true;
2133 				}
2134 			} else if (gas_t->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
2135 				if (!IS_NULL_REG(gas_t)) {
2136 					void __iomem *addr;
2137 					size_t access_width;
2138 
2139 					err = cpc_validate_sysmem_reg(cpc_ptr, gas_t,
2140 								      i - 2);
2141 					if (err) {
2142 						unsupported_regs |= BIT(i - 2);
2143 						continue;
2144 					}
2145 					if (!cpc_is_readable(&cpc_ptr->cpc_regs[i - 2]) &&
2146 					    !cpc_is_writable(&cpc_ptr->cpc_regs[i - 2]))
2147 						continue;
2148 
2149 					if (!osc_cpc_flexible_adr_space_confirmed) {
2150 						pr_debug("Flexible address space capability not supported\n");
2151 						ret = -EOPNOTSUPP;
2152 						if (!cpc_supported_by_cpu())
2153 							goto out_free;
2154 						ret = -EINVAL;
2155 					}
2156 
2157 					access_width = cpc_reg_access_width(gas_t);
2158 					access_width /= 8;
2159 					addr = ioremap(gas_t->address, access_width);
2160 					if (!addr) {
2161 						ret = -ENOMEM;
2162 						goto out_free;
2163 					}
2164 					cpc_ptr->cpc_regs[i - 2].sys_mem_vaddr = addr;
2165 				}
2166 			} else if (gas_t->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
2167 				u64 access_size;
2168 				const char *reason = "uses unsupported SystemIO geometry";
2169 				unsigned int access_width;
2170 				bool partial = false;
2171 				bool unsupported;
2172 
2173 				access_width = cpc_reg_access_width(gas_t);
2174 				unsupported = !IS_ENABLED(CONFIG_HAS_IOPORT);
2175 				if (unsupported)
2176 					reason = "requires unavailable SystemIO support";
2177 				else
2178 					unsupported = access_width != 8 &&
2179 					      access_width != 16 &&
2180 					      access_width != 32;
2181 				if (!unsupported) {
2182 					access_size = access_width / 8;
2183 					unsupported = !gas_t->bit_width ||
2184 						gas_t->bit_width > access_width ||
2185 						gas_t->bit_offset >= access_width ||
2186 						gas_t->bit_width > access_width -
2187 									   gas_t->bit_offset;
2188 					partial = gas_t->bit_offset ||
2189 						  gas_t->bit_width != access_width;
2190 				}
2191 				if (!unsupported) {
2192 					unsupported = (cpc_reg_is_writable(i - 2) &&
2193 						i - 2 != PERF_LIMITED &&
2194 						cpc_is_writable(&cpc_ptr->cpc_regs[i - 2]) &&
2195 						partial) ||
2196 						!cpc_reg_access_aligned(gas_t,
2197 									access_size) ||
2198 						gas_t->address >
2199 						U16_MAX - (access_size - 1);
2200 				}
2201 				if (unsupported) {
2202 					if (cpc_retain_sysio_status(cpc_ptr, i - 2))
2203 						continue;
2204 					pr_debug("CPU%d: _CPC register %u %s\n",
2205 						 pr->id, i - 2, reason);
2206 					unsupported_regs |= BIT(i - 2);
2207 					continue;
2208 				}
2209 				if (i - 2 == PERF_LIMITED && partial) {
2210 					pr_warn_once("CPU%d: Performance Limited register cannot be cleared safely; keeping it readable\n",
2211 						     cpc_ptr->cpu_id);
2212 					cpc_ptr->cpc_regs[i - 2].cpc_entry.write_unsupported = true;
2213 				}
2214 				if (!osc_cpc_flexible_adr_space_confirmed) {
2215 					pr_debug("Flexible address space capability not supported\n");
2216 					ret = -EOPNOTSUPP;
2217 					if (!cpc_supported_by_cpu())
2218 						goto out_free;
2219 					ret = -EINVAL;
2220 				}
2221 			} else {
2222 				if (gas_t->space_id != ACPI_ADR_SPACE_FIXED_HARDWARE || !cpc_ffh_supported()) {
2223 					/* Support only PCC, SystemMemory, SystemIO, and FFH type regs. */
2224 					pr_debug("Unsupported register type (%d) in _CPC\n",
2225 						 gas_t->space_id);
2226 					ret = -EOPNOTSUPP;
2227 					goto out_free;
2228 				}
2229 			}
2230 		} else if (cpc_obj->type == ACPI_TYPE_PACKAGE && (i - 2) == RESOURCE_PRIORITY) {
2231 			/*
2232 			 * ACPI 6.6, s8.4.6.1.2.7 defines Resource Priority as a
2233 			 * Package of Resource Priority Register Descriptor sub-packages.
2234 			 * Parsing the full structure is not yet supported.
2235 			 * Mark the register as unsupported for now.
2236 			 */
2237 			pr_debug("CPU:%d Resource Priority not supported\n", pr->id);
2238 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_INTEGER;
2239 			cpc_ptr->cpc_regs[i-2].cpc_entry.int_value = 0;
2240 		} else {
2241 			pr_debug("Invalid entry type (%d) in _CPC for CPU:%d\n",
2242 				 i, pr->id);
2243 			goto out_free;
2244 		}
2245 	}
2246 
2247 	per_cpu(cpu_pcc_subspace_idx, pr->id) = pcc_data_ref ?
2248 						 pcc_subspace_id : -1;
2249 
2250 	ret = cpc_resolve_unsupported(cpc_ptr, unsupported_regs);
2251 	if (ret)
2252 		goto out_free;
2253 	unsupported_regs = 0;
2254 
2255 	ret = cpc_validate_required_controls(cpc_ptr);
2256 	if (ret)
2257 		goto out_free;
2258 
2259 	/*
2260 	 * Initialize the remaining cpc_regs as unsupported.
2261 	 * Example: In case FW exposes CPPC v2, the below loop will initialize
2262 	 * LOWEST_FREQ and NOMINAL_FREQ regs as unsupported
2263 	 */
2264 	for (i = num_ent - 2; i < MAX_CPC_REG_ENT; i++) {
2265 		cpc_ptr->cpc_regs[i].type = ACPI_TYPE_INTEGER;
2266 		cpc_ptr->cpc_regs[i].cpc_entry.int_value = 0;
2267 	}
2268 
2269 
2270 	cpc_mark_rmw_lock_users(cpc_ptr);
2271 	raw_spin_lock_init(&cpc_ptr->rmw_lock);
2272 
2273 	/* Parse PSD data for this CPU */
2274 	ret = acpi_get_psd(cpc_ptr, handle);
2275 	if (ret)
2276 		goto out_free;
2277 
2278 	ret = cpc_register_sysmem_desc(cpc_ptr);
2279 	if (ret)
2280 		goto out_free;
2281 
2282 	/* Register PCC channel once for all PCC subspace ID. */
2283 	if (pcc_data_ref) {
2284 		ret = register_pcc_channel(pcc_subspace_id);
2285 		if (ret) {
2286 			pr_err("Failed to find PCC channel for subspace %d\n",
2287 			       pcc_subspace_id);
2288 			goto out_free;
2289 		}
2290 
2291 		cpc_validate_pcc_bounds(cpc_ptr, pcc_subspace_id,
2292 					pcc_data[pcc_subspace_id],
2293 					&unsupported_regs);
2294 
2295 		ret = cpc_resolve_unsupported(cpc_ptr, unsupported_regs);
2296 		if (ret)
2297 			goto out_free;
2298 
2299 		/* A range-only status entry needs the channel only for bounds. */
2300 		if (!cpc_pcc_access_needed(cpc_ptr)) {
2301 			pcc_data_put(pcc_subspace_id);
2302 			pcc_data_ref = false;
2303 			per_cpu(cpu_pcc_subspace_idx, pr->id) = -1;
2304 		}
2305 	}
2306 
2307 	ret = cpc_validate_bound_controls(cpc_ptr);
2308 	if (ret)
2309 		goto out_free;
2310 
2311 	ret = cpc_register_non_mmio_desc(cpc_ptr);
2312 	if (ret)
2313 		goto out_free;
2314 
2315 	/* Everything looks okay */
2316 	pr_debug("Parsed CPC struct for CPU: %d\n", pr->id);
2317 
2318 	/* Add per logical CPU nodes for reading its feedback counters. */
2319 	cpu_dev = get_cpu_device(pr->id);
2320 	if (!cpu_dev) {
2321 		ret = -EINVAL;
2322 		goto out_free;
2323 	}
2324 
2325 	/* Plug PSD data into this CPU's CPC descriptor. */
2326 	cpc_set_desc(pr->id, cpc_ptr);
2327 
2328 	ret = kobject_init_and_add(&cpc_ptr->kobj, &cppc_ktype, &cpu_dev->kobj,
2329 			"acpi_cppc");
2330 	if (ret) {
2331 		cpc_set_desc(pr->id, NULL);
2332 		cpc_unregister_non_mmio_desc(cpc_ptr);
2333 		cpc_unregister_sysmem_desc(cpc_ptr);
2334 		kobject_put(&cpc_ptr->kobj);
2335 		goto out_pcc_put;
2336 	}
2337 
2338 	kfree(output.pointer);
2339 	return 0;
2340 
2341 out_free:
2342 	cppc_free_desc(cpc_ptr);
2343 
2344 out_pcc_put:
2345 	if (pcc_data_ref)
2346 		pcc_data_put(pcc_subspace_id);
2347 	per_cpu(cpu_pcc_subspace_idx, pr->id) = -1;
2348 
2349 out_buf_free:
2350 	if (cpc_present)
2351 		pr_err("CPU%d: failed to initialize _CPC: %d\n", pr->id, ret);
2352 	kfree(output.pointer);
2353 	return ret;
2354 }
2355 EXPORT_SYMBOL_GPL(acpi_cppc_processor_probe);
2356 
2357 /**
2358  * acpi_cppc_processor_exit - Cleanup CPC structs.
2359  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
2360  *
2361  * Return: Void
2362  */
2363 void acpi_cppc_processor_exit(struct acpi_processor *pr)
2364 {
2365 	struct cpc_desc *cpc_ptr;
2366 	int pcc_ss_id;
2367 
2368 	cpc_ptr = per_cpu(cpc_desc_ptr, pr->id);
2369 	if (!cpc_ptr) {
2370 		per_cpu(cpu_pcc_subspace_idx, pr->id) = -1;
2371 		return;
2372 	}
2373 
2374 	pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, pr->id);
2375 	cpc_set_desc(pr->id, NULL);
2376 	kobject_del(&cpc_ptr->kobj);
2377 	cpc_unregister_non_mmio_desc(cpc_ptr);
2378 	cpc_unregister_sysmem_desc(cpc_ptr);
2379 
2380 	pcc_data_put(pcc_ss_id);
2381 	per_cpu(cpu_pcc_subspace_idx, pr->id) = -1;
2382 
2383 	kobject_put(&cpc_ptr->kobj);
2384 }
2385 EXPORT_SYMBOL_GPL(acpi_cppc_processor_exit);
2386 
2387 /**
2388  * cpc_read_ffh() - Read FFH register
2389  * @cpunum:	CPU number to read
2390  * @reg:	cppc register information
2391  * @val:	place holder for return value
2392  *
2393  * Read bit_width bits from a specified address and bit_offset
2394  *
2395  * Return: 0 for success and error code
2396  */
2397 int __weak cpc_read_ffh(int cpunum, struct cpc_reg *reg, u64 *val)
2398 {
2399 	return -ENOTSUPP;
2400 }
2401 
2402 /**
2403  * cpc_read_ffh_fb_ctrs() - Read FFH feedback counters together
2404  * @cpunum:	Target CPU
2405  * @reg1:	first CPPC register information
2406  * @val1:	place holder for first return value
2407  * @reg2:	second CPPC register information
2408  * @val2:	place holder for second return value
2409  *
2410  * Return: 0 on success, error code otherwise
2411  */
2412 int __weak cpc_read_ffh_fb_ctrs(int cpunum, struct cpc_reg *reg1,
2413 				u64 *val1, struct cpc_reg *reg2, u64 *val2)
2414 {
2415 	return -EOPNOTSUPP;
2416 }
2417 
2418 /**
2419  * cpc_write_ffh() - Write FFH register
2420  * @cpunum:	CPU number to write
2421  * @reg:	cppc register information
2422  * @val:	value to write
2423  *
2424  * Write value of bit_width bits to a specified address and bit_offset
2425  *
2426  * Return: 0 for success and error code
2427  */
2428 int __weak cpc_write_ffh(int cpunum, struct cpc_reg *reg, u64 val)
2429 {
2430 	return -ENOTSUPP;
2431 }
2432 
2433 /*
2434  * Since cpc_read and cpc_write are called while holding pcc_lock, it should be
2435  * as fast as possible. We have already mapped the PCC subspace during init, so
2436  * we can directly write to it.
2437  */
2438 
2439 static int cpc_read(int cpu, struct cpc_register_resource *reg_res, u64 *val)
2440 {
2441 	void __iomem *vaddr = NULL;
2442 	unsigned long flags;
2443 	u8 buf[sizeof(*val)];
2444 	unsigned int i;
2445 	int size;
2446 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
2447 	struct cpc_reg *reg = &reg_res->cpc_entry.reg;
2448 
2449 	if (!cpc_is_readable(reg_res))
2450 		return -EOPNOTSUPP;
2451 
2452 	if (reg_res->type == ACPI_TYPE_INTEGER) {
2453 		*val = reg_res->cpc_entry.int_value;
2454 		return 0;
2455 	}
2456 
2457 	*val = 0;
2458 	if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
2459 		return cpc_read_ffh(cpu, reg, val);
2460 
2461 	size = GET_BIT_WIDTH(reg);
2462 
2463 	if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
2464 		u32 val_u32;
2465 		acpi_status status;
2466 
2467 		if (!IS_ENABLED(CONFIG_HAS_IOPORT))
2468 			return -EOPNOTSUPP;
2469 
2470 		status = acpi_os_read_port((acpi_io_address)reg->address,
2471 					   &val_u32, size);
2472 		if (ACPI_FAILURE(status)) {
2473 			pr_debug("Error: Failed to read SystemIO port %llx\n",
2474 				 reg->address);
2475 			return -EFAULT;
2476 		}
2477 
2478 		*val = MASK_VAL_READ(reg, val_u32);
2479 		return 0;
2480 	} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
2481 		if (pcc_ss_id < 0 || !pcc_data[pcc_ss_id])
2482 			return -ENODEV;
2483 
2484 		/*
2485 		 * For registers in PCC space, the register size is determined
2486 		 * by the bit width field; the access size is used to indicate
2487 		 * the PCC subspace id.
2488 		 */
2489 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
2490 		size = reg->bit_width / 8;
2491 		if (!size || size > sizeof(buf) || reg->bit_width % 8)
2492 			return -EFAULT;
2493 
2494 		raw_spin_lock_irqsave(&pcc_data[pcc_ss_id]->payload_lock, flags);
2495 		memcpy_fromio(buf, vaddr, size);
2496 		raw_spin_unlock_irqrestore(&pcc_data[pcc_ss_id]->payload_lock,
2497 					   flags);
2498 
2499 		*val = 0;
2500 		for (i = 0; i < size; i++)
2501 			*val |= (u64)buf[i] << (i * 8);
2502 		return 0;
2503 	} else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
2504 		vaddr = reg_res->sys_mem_vaddr;
2505 	else
2506 		return acpi_os_read_memory((acpi_physical_address)reg->address,
2507 				val, size);
2508 
2509 	switch (size) {
2510 	case 8:
2511 		*val = readb_relaxed(vaddr);
2512 		break;
2513 	case 16:
2514 		*val = readw_relaxed(vaddr);
2515 		break;
2516 	case 32:
2517 		*val = readl_relaxed(vaddr);
2518 		break;
2519 	case 64:
2520 		*val = readq_relaxed(vaddr);
2521 		break;
2522 	default:
2523 		pr_debug("Error: Cannot read %u bit width from system memory: 0x%llx\n",
2524 			 size, reg->address);
2525 		return -EFAULT;
2526 	}
2527 
2528 	*val = MASK_VAL_READ(reg, *val);
2529 
2530 	return 0;
2531 }
2532 
2533 static int cpc_write(int cpu, struct cpc_register_resource *reg_res, u64 val)
2534 {
2535 	int ret_val = 0;
2536 	int size;
2537 	u64 prev_val;
2538 	void __iomem *vaddr = NULL;
2539 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
2540 	struct cpc_reg *reg;
2541 	struct cpc_desc *cpc_desc;
2542 	unsigned long flags;
2543 	u8 buf[sizeof(val)];
2544 	unsigned int i;
2545 	bool locked = false;
2546 
2547 	if (!cpc_is_writable(reg_res))
2548 		return -EOPNOTSUPP;
2549 
2550 	reg = &reg_res->cpc_entry.reg;
2551 	if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
2552 		return cpc_write_ffh(cpu, reg, val);
2553 
2554 	size = GET_BIT_WIDTH(reg);
2555 
2556 	if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
2557 		acpi_status status;
2558 
2559 		if (!IS_ENABLED(CONFIG_HAS_IOPORT))
2560 			return -EOPNOTSUPP;
2561 
2562 		status = acpi_os_write_port((acpi_io_address)reg->address,
2563 					    (u32)val, size);
2564 		if (ACPI_FAILURE(status)) {
2565 			pr_debug("Error: Failed to write SystemIO port %llx\n",
2566 				 reg->address);
2567 			return -EFAULT;
2568 		}
2569 
2570 		return 0;
2571 	} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
2572 		if (pcc_ss_id < 0 || !pcc_data[pcc_ss_id])
2573 			return -ENODEV;
2574 
2575 		/*
2576 		 * For registers in PCC space, the register size is determined
2577 		 * by the bit width field; the access size is used to indicate
2578 		 * the PCC subspace id.
2579 		 */
2580 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
2581 		size = reg->bit_width / 8;
2582 		if (!size || size > sizeof(buf) || reg->bit_width % 8)
2583 			return -EFAULT;
2584 
2585 		for (i = 0; i < size; i++)
2586 			buf[i] = val >> (i * 8);
2587 
2588 		raw_spin_lock_irqsave(&pcc_data[pcc_ss_id]->payload_lock, flags);
2589 		memcpy_toio(vaddr, buf, size);
2590 		/* Publish every payload byte before another CPU can ring the doorbell. */
2591 		wmb();
2592 		raw_spin_unlock_irqrestore(&pcc_data[pcc_ss_id]->payload_lock,
2593 					   flags);
2594 		return 0;
2595 	} else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
2596 		vaddr = reg_res->sys_mem_vaddr;
2597 	else
2598 		return acpi_os_write_memory((acpi_physical_address)reg->address,
2599 				val, size);
2600 
2601 	/* Partial fields and local overlaps use the descriptor lock. */
2602 	locked = reg_res->cpc_entry.use_rmw_lock;
2603 	if (locked) {
2604 		cpc_desc = per_cpu(cpc_desc_ptr, cpu);
2605 		if (!cpc_desc) {
2606 			pr_debug("No CPC descriptor for CPU:%d\n", cpu);
2607 			return -ENODEV;
2608 		}
2609 		raw_spin_lock_irqsave(&cpc_desc->rmw_lock, flags);
2610 	}
2611 
2612 	if (reg->bit_offset || reg->bit_width != size) {
2613 		/*
2614 		 * MASK_VAL_WRITE() discards the field's old bits, so undefined
2615 		 * readback from a write-only field is not propagated.
2616 		 */
2617 		switch (size) {
2618 		case 8:
2619 			prev_val = readb_relaxed(vaddr);
2620 			break;
2621 		case 16:
2622 			prev_val = readw_relaxed(vaddr);
2623 			break;
2624 		case 32:
2625 			prev_val = readl_relaxed(vaddr);
2626 			break;
2627 		case 64:
2628 			prev_val = readq_relaxed(vaddr);
2629 			break;
2630 		default:
2631 			if (locked)
2632 				raw_spin_unlock_irqrestore(&cpc_desc->rmw_lock,
2633 							   flags);
2634 			return -EFAULT;
2635 		}
2636 		val = MASK_VAL_WRITE(reg, prev_val, val);
2637 	}
2638 
2639 	switch (size) {
2640 	case 8:
2641 		writeb_relaxed(val, vaddr);
2642 		break;
2643 	case 16:
2644 		writew_relaxed(val, vaddr);
2645 		break;
2646 	case 32:
2647 		writel_relaxed(val, vaddr);
2648 		break;
2649 	case 64:
2650 		writeq_relaxed(val, vaddr);
2651 		break;
2652 	default:
2653 		pr_debug("Error: Cannot write %u bit width to system memory: 0x%llx\n",
2654 			 size, reg->address);
2655 		ret_val = -EFAULT;
2656 		break;
2657 	}
2658 
2659 	if (locked) {
2660 		if (!ret_val)
2661 			mmiowb_set_pending();
2662 		raw_spin_unlock_irqrestore(&cpc_desc->rmw_lock, flags);
2663 	}
2664 
2665 	return ret_val;
2666 }
2667 
2668 static int cppc_get_reg_val_in_pcc(int cpu, struct cpc_register_resource *reg, u64 *val)
2669 {
2670 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
2671 	struct cppc_pcc_data *pcc_ss_data = NULL;
2672 	int ret;
2673 
2674 	if (pcc_ss_id < 0) {
2675 		pr_debug("Invalid pcc_ss_id\n");
2676 		return -ENODEV;
2677 	}
2678 
2679 	pcc_ss_data = pcc_data[pcc_ss_id];
2680 
2681 	down_write(&pcc_ss_data->pcc_lock);
2682 
2683 	if (send_pcc_cmd(pcc_ss_id, CMD_READ) >= 0)
2684 		ret = cpc_read(cpu, reg, val);
2685 	else
2686 		ret = -EIO;
2687 
2688 	up_write(&pcc_ss_data->pcc_lock);
2689 
2690 	return ret;
2691 }
2692 
2693 static int cppc_get_reg_val(int cpu, enum cppc_regs reg_idx, u64 *val)
2694 {
2695 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
2696 	struct cpc_register_resource *reg;
2697 
2698 	if (val == NULL)
2699 		return -EINVAL;
2700 
2701 	if (!cpc_desc) {
2702 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
2703 		return -ENODEV;
2704 	}
2705 	if (cpc_reg_is_write_only(cpc_desc, reg_idx))
2706 		return -EOPNOTSUPP;
2707 
2708 	reg = &cpc_desc->cpc_regs[reg_idx];
2709 
2710 	/*
2711 	 * Desired and Performance Limited may be disabled despite not being
2712 	 * generally optional.
2713 	 */
2714 	if ((reg->type == ACPI_TYPE_INTEGER &&
2715 	     (IS_OPTIONAL_CPC_REG(reg_idx) || reg_idx == DESIRED_PERF ||
2716 	      reg_idx == PERF_LIMITED) &&
2717 	     !reg->cpc_entry.int_value) || (reg->type != ACPI_TYPE_INTEGER &&
2718 	     IS_NULL_REG(&reg->cpc_entry.reg))) {
2719 		pr_debug("CPC register is not supported\n");
2720 		return -EOPNOTSUPP;
2721 	}
2722 	if (!cpc_is_readable(reg))
2723 		return -EOPNOTSUPP;
2724 
2725 	if (CPC_IN_PCC(reg))
2726 		return cppc_get_reg_val_in_pcc(cpu, reg, val);
2727 
2728 	return cpc_read(cpu, reg, val);
2729 }
2730 
2731 static int cppc_set_reg_val_in_pcc(int cpu, struct cpc_register_resource *reg, u64 val)
2732 {
2733 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
2734 	struct cppc_pcc_data *pcc_ss_data;
2735 	int ret;
2736 
2737 	if (pcc_ss_id < 0) {
2738 		pr_debug("Invalid pcc_ss_id\n");
2739 		return -ENODEV;
2740 	}
2741 	pcc_ss_data = pcc_data[pcc_ss_id];
2742 	if (!pcc_ss_data)
2743 		return -ENODEV;
2744 
2745 	down_write(&pcc_ss_data->pcc_lock);
2746 
2747 	ret = check_pcc_chan(pcc_ss_id, false);
2748 	if (ret)
2749 		goto out;
2750 
2751 	ret = cpc_write(cpu, reg, val);
2752 	if (ret)
2753 		goto out;
2754 
2755 	/* after writing CPC, transfer the ownership of PCC to platform */
2756 	ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
2757 
2758 out:
2759 	if (ret)
2760 		cppc_abort_pending_pcc_write(pcc_ss_id, pcc_ss_data, ret);
2761 	up_write(&pcc_ss_data->pcc_lock);
2762 
2763 	return ret;
2764 }
2765 
2766 static int cppc_set_reg_val(int cpu, enum cppc_regs reg_idx, u64 val)
2767 {
2768 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
2769 	struct cpc_register_resource *reg;
2770 
2771 	if (!cpc_desc) {
2772 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
2773 		return -ENODEV;
2774 	}
2775 
2776 	reg = &cpc_desc->cpc_regs[reg_idx];
2777 
2778 	/* Integer 1 describes autonomous selection that is always enabled. */
2779 	if (reg_idx == AUTO_SEL_ENABLE && reg->type == ACPI_TYPE_INTEGER &&
2780 	    reg->cpc_entry.int_value == 1)
2781 		return val == 1 ? 0 : -EOPNOTSUPP;
2782 
2783 	/* if a register is writeable, it must be a buffer and not null */
2784 	if (!cpc_is_writable(reg)) {
2785 		pr_debug("CPC register is not supported\n");
2786 		return -EOPNOTSUPP;
2787 	}
2788 
2789 	if (CPC_IN_PCC(reg))
2790 		return cppc_set_reg_val_in_pcc(cpu, reg, val);
2791 
2792 	return cpc_write(cpu, reg, val);
2793 }
2794 
2795 /**
2796  * cppc_get_desired_perf - Get the desired performance register value.
2797  * @cpunum: CPU from which to get desired performance.
2798  * @desired_perf: Return address.
2799  *
2800  * Return: 0 for success, -EOPNOTSUPP for _CPC revision 4 or later, and a
2801  * negative errno otherwise.
2802  */
2803 int cppc_get_desired_perf(int cpunum, u64 *desired_perf)
2804 {
2805 	return cppc_get_reg_val(cpunum, DESIRED_PERF, desired_perf);
2806 }
2807 EXPORT_SYMBOL_GPL(cppc_get_desired_perf);
2808 
2809 /**
2810  * cppc_get_nominal_perf - Get the nominal performance register value.
2811  * @cpunum: CPU from which to get nominal performance.
2812  * @nominal_perf: Return address.
2813  *
2814  * Return: 0 for success, -EIO otherwise.
2815  */
2816 int cppc_get_nominal_perf(int cpunum, u64 *nominal_perf)
2817 {
2818 	return cppc_get_reg_val(cpunum, NOMINAL_PERF, nominal_perf);
2819 }
2820 
2821 /**
2822  * cppc_get_highest_perf - Get the highest performance register value.
2823  * @cpunum: CPU from which to get highest performance.
2824  * @highest_perf: Return address.
2825  *
2826  * Return: 0 for success, -EIO otherwise.
2827  */
2828 int cppc_get_highest_perf(int cpunum, u64 *highest_perf)
2829 {
2830 	return cppc_get_reg_val(cpunum, HIGHEST_PERF, highest_perf);
2831 }
2832 EXPORT_SYMBOL_GPL(cppc_get_highest_perf);
2833 
2834 /**
2835  * cppc_get_epp_perf - Get the epp register value.
2836  * @cpunum: CPU from which to get epp preference value.
2837  * @epp_perf: Return address.
2838  *
2839  * Return: 0 for success, -EIO otherwise.
2840  */
2841 int cppc_get_epp_perf(int cpunum, u64 *epp_perf)
2842 {
2843 	return cppc_get_reg_val(cpunum, ENERGY_PERF, epp_perf);
2844 }
2845 EXPORT_SYMBOL_GPL(cppc_get_epp_perf);
2846 
2847 /**
2848  * cppc_get_perf_caps - Get a CPU's performance capabilities.
2849  * @cpunum: CPU from which to get capabilities info.
2850  * @perf_caps: ptr to cppc_perf_caps. See cppc_acpi.h
2851  *
2852  * Return: 0 for success with perf_caps populated else -ERRNO.
2853  */
2854 int cppc_get_perf_caps(int cpunum, struct cppc_perf_caps *perf_caps)
2855 {
2856 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
2857 	struct cpc_register_resource *highest_reg, *lowest_reg,
2858 		*lowest_non_linear_reg, *nominal_reg, *reference_reg,
2859 		*guaranteed_reg, *low_freq_reg = NULL, *nom_freq_reg = NULL;
2860 	u64 high, low, guaranteed = 0, nom, ref, min_nonlinear,
2861 	    low_f = 0, nom_f = 0;
2862 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
2863 	struct cppc_pcc_data *pcc_ss_data = NULL;
2864 	int ret = 0, regs_in_pcc = 0;
2865 
2866 	if (!cpc_desc) {
2867 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
2868 		return -ENODEV;
2869 	}
2870 
2871 	highest_reg = &cpc_desc->cpc_regs[HIGHEST_PERF];
2872 	lowest_reg = &cpc_desc->cpc_regs[LOWEST_PERF];
2873 	lowest_non_linear_reg = &cpc_desc->cpc_regs[LOW_NON_LINEAR_PERF];
2874 	nominal_reg = &cpc_desc->cpc_regs[NOMINAL_PERF];
2875 	reference_reg = &cpc_desc->cpc_regs[REFERENCE_PERF];
2876 	low_freq_reg = &cpc_desc->cpc_regs[LOWEST_FREQ];
2877 	nom_freq_reg = &cpc_desc->cpc_regs[NOMINAL_FREQ];
2878 	guaranteed_reg = &cpc_desc->cpc_regs[GUARANTEED_PERF];
2879 
2880 	/* Are any of the regs PCC ?*/
2881 	if (CPC_IN_PCC(highest_reg) || CPC_IN_PCC(lowest_reg) ||
2882 		CPC_IN_PCC(lowest_non_linear_reg) || CPC_IN_PCC(nominal_reg) ||
2883 		(CPC_SUPPORTED(reference_reg) && CPC_IN_PCC(reference_reg)) ||
2884 		CPC_IN_PCC(low_freq_reg) || CPC_IN_PCC(nom_freq_reg) ||
2885 		CPC_IN_PCC(guaranteed_reg)) {
2886 		if (pcc_ss_id < 0) {
2887 			pr_debug("Invalid pcc_ss_id\n");
2888 			return -ENODEV;
2889 		}
2890 		pcc_ss_data = pcc_data[pcc_ss_id];
2891 		regs_in_pcc = 1;
2892 		down_write(&pcc_ss_data->pcc_lock);
2893 		/* Ring doorbell once to update PCC subspace */
2894 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
2895 			ret = -EIO;
2896 			goto out_err;
2897 		}
2898 	}
2899 
2900 	ret = cpc_read(cpunum, highest_reg, &high);
2901 	if (ret)
2902 		goto out_err;
2903 	perf_caps->highest_perf = high;
2904 
2905 	ret = cpc_read(cpunum, lowest_reg, &low);
2906 	if (ret)
2907 		goto out_err;
2908 	perf_caps->lowest_perf = low;
2909 
2910 	ret = cpc_read(cpunum, nominal_reg, &nom);
2911 	if (ret)
2912 		goto out_err;
2913 	perf_caps->nominal_perf = nom;
2914 
2915 	/*
2916 	 * If reference perf register is not supported then we should
2917 	 * use the nominal perf value
2918 	 */
2919 	if (CPC_SUPPORTED(reference_reg)) {
2920 		ret = cpc_read(cpunum, reference_reg, &ref);
2921 		if (ret)
2922 			goto out_err;
2923 	} else {
2924 		ref = nom;
2925 	}
2926 	perf_caps->reference_perf = ref;
2927 
2928 	if (guaranteed_reg->type != ACPI_TYPE_BUFFER  ||
2929 	    IS_NULL_REG(&guaranteed_reg->cpc_entry.reg)) {
2930 		perf_caps->guaranteed_perf = 0;
2931 	} else {
2932 		ret = cpc_read(cpunum, guaranteed_reg, &guaranteed);
2933 		if (ret)
2934 			goto out_err;
2935 		perf_caps->guaranteed_perf = guaranteed;
2936 	}
2937 
2938 	ret = cpc_read(cpunum, lowest_non_linear_reg, &min_nonlinear);
2939 	if (ret)
2940 		goto out_err;
2941 	perf_caps->lowest_nonlinear_perf = min_nonlinear;
2942 
2943 	if (!high || !low || !nom || !ref || !min_nonlinear ||
2944 	    high > U32_MAX || low > U32_MAX || guaranteed > U32_MAX ||
2945 	    nom > U32_MAX || ref > U32_MAX || min_nonlinear > U32_MAX ||
2946 	    high < nom || nom < min_nonlinear || min_nonlinear < low ||
2947 	    (CPC_SUPPORTED(guaranteed_reg) &&
2948 	     (guaranteed < low || guaranteed > nom))) {
2949 		ret = -EFAULT;
2950 		goto out_err;
2951 	}
2952 
2953 	/* Read optional lowest and nominal frequencies if present */
2954 	if (CPC_SUPPORTED(low_freq_reg)) {
2955 		ret = cpc_read(cpunum, low_freq_reg, &low_f);
2956 		if (ret)
2957 			goto out_err;
2958 	}
2959 
2960 	if (CPC_SUPPORTED(nom_freq_reg)) {
2961 		ret = cpc_read(cpunum, nom_freq_reg, &nom_f);
2962 		if (ret)
2963 			goto out_err;
2964 	}
2965 	/* Require ordered anchors and a nonzero slope when frequencies differ. */
2966 	if (low_f > U32_MAX || nom_f > U32_MAX ||
2967 	    (low_f && nom_f &&
2968 	     (nom_f < low_f || nom < low ||
2969 	      (nom_f != low_f && nom == low)))) {
2970 		ret = -EFAULT;
2971 		goto out_err;
2972 	}
2973 
2974 	perf_caps->lowest_freq = low_f;
2975 	perf_caps->nominal_freq = nom_f;
2976 
2977 
2978 out_err:
2979 	if (regs_in_pcc)
2980 		up_write(&pcc_ss_data->pcc_lock);
2981 	return ret;
2982 }
2983 EXPORT_SYMBOL_GPL(cppc_get_perf_caps);
2984 
2985 /**
2986  * cppc_perf_ctrs_in_pcc_cpu - Check if any perf counters of a CPU are in PCC.
2987  * @cpu: CPU on which to check perf counters.
2988  *
2989  * Return: true if any of the counters are in PCC regions, false otherwise
2990  */
2991 bool cppc_perf_ctrs_in_pcc_cpu(unsigned int cpu)
2992 {
2993 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
2994 
2995 	if (!cpc_desc)
2996 		return false;
2997 
2998 	return CPC_IN_PCC(&cpc_desc->cpc_regs[DELIVERED_CTR]) ||
2999 		CPC_IN_PCC(&cpc_desc->cpc_regs[REFERENCE_CTR]) ||
3000 		CPC_IN_PCC(&cpc_desc->cpc_regs[CTR_WRAP_TIME]);
3001 }
3002 EXPORT_SYMBOL_GPL(cppc_perf_ctrs_in_pcc_cpu);
3003 
3004 static int cppc_read_fb_ctrs(int cpunum,
3005 			     struct cpc_register_resource *delivered_reg,
3006 			     struct cpc_register_resource *reference_reg,
3007 			     u64 *delivered, u64 *reference)
3008 {
3009 	int ret;
3010 
3011 	/*
3012 	 * For FFH feedback counters, try a paired read first to reduce
3013 	 * sampling skew between delivered and reference counters. Fall
3014 	 * back to the existing per-register reads if unsupported.
3015 	 */
3016 	if (CPC_IN_FFH(delivered_reg) && CPC_IN_FFH(reference_reg)) {
3017 		ret = cpc_read_ffh_fb_ctrs(cpunum,
3018 					&delivered_reg->cpc_entry.reg, delivered,
3019 					&reference_reg->cpc_entry.reg, reference);
3020 		if (ret != -EOPNOTSUPP)
3021 			return ret;
3022 	}
3023 
3024 	ret = cpc_read(cpunum, delivered_reg, delivered);
3025 	if (ret)
3026 		return ret;
3027 
3028 	return cpc_read(cpunum, reference_reg, reference);
3029 }
3030 
3031 /**
3032  * cppc_perf_ctrs_in_pcc - Check if any perf counters are in a PCC region.
3033  *
3034  * CPPC has flexibility about how CPU performance counters are accessed.
3035  * One of the choices is PCC regions, which can have a high access latency. This
3036  * routine allows callers of cppc_get_perf_ctrs() to know this ahead of time.
3037  *
3038  * Return: true if any of the counters are in PCC regions, false otherwise
3039  */
3040 bool cppc_perf_ctrs_in_pcc(void)
3041 {
3042 	int cpu;
3043 
3044 	for_each_online_cpu(cpu) {
3045 		if (cppc_perf_ctrs_in_pcc_cpu(cpu))
3046 			return true;
3047 	}
3048 
3049 	return false;
3050 }
3051 EXPORT_SYMBOL_GPL(cppc_perf_ctrs_in_pcc);
3052 
3053 /**
3054  * cppc_get_perf_ctrs - Read a CPU's performance feedback counters.
3055  * @cpunum: CPU from which to read counters.
3056  * @perf_fb_ctrs: ptr to cppc_perf_fb_ctrs. See cppc_acpi.h
3057  *
3058  * Return: 0 for success with perf_fb_ctrs populated else -ERRNO.
3059  */
3060 int cppc_get_perf_ctrs(int cpunum, struct cppc_perf_fb_ctrs *perf_fb_ctrs)
3061 {
3062 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
3063 	struct cpc_register_resource *delivered_reg, *reference_reg,
3064 		*ctr_wrap_reg;
3065 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
3066 	struct cppc_pcc_data *pcc_ss_data = NULL;
3067 	u64 delivered, reference, ctr_wrap_time;
3068 	int ret = 0, regs_in_pcc = 0;
3069 
3070 	if (!cpc_desc) {
3071 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
3072 		return -ENODEV;
3073 	}
3074 
3075 	delivered_reg = &cpc_desc->cpc_regs[DELIVERED_CTR];
3076 	reference_reg = &cpc_desc->cpc_regs[REFERENCE_CTR];
3077 	ctr_wrap_reg = &cpc_desc->cpc_regs[CTR_WRAP_TIME];
3078 
3079 	/* Are any of the regs PCC ?*/
3080 	if (CPC_IN_PCC(delivered_reg) || CPC_IN_PCC(reference_reg) ||
3081 		CPC_IN_PCC(ctr_wrap_reg)) {
3082 		if (pcc_ss_id < 0) {
3083 			pr_debug("Invalid pcc_ss_id\n");
3084 			return -ENODEV;
3085 		}
3086 		pcc_ss_data = pcc_data[pcc_ss_id];
3087 		down_write(&pcc_ss_data->pcc_lock);
3088 		regs_in_pcc = 1;
3089 		/* Ring doorbell once to update PCC subspace */
3090 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
3091 			ret = -EIO;
3092 			goto out_err;
3093 		}
3094 	}
3095 
3096 	ret = cppc_read_fb_ctrs(cpunum, delivered_reg, reference_reg,
3097 				&delivered, &reference);
3098 	if (ret)
3099 		goto out_err;
3100 
3101 	/*
3102 	 * Per spec, if ctr_wrap_time optional register is unsupported, then the
3103 	 * performance counters are assumed to never wrap during the lifetime of
3104 	 * platform
3105 	 */
3106 	ctr_wrap_time = (u64)(~((u64)0));
3107 	if (CPC_SUPPORTED(ctr_wrap_reg)) {
3108 		ret = cpc_read(cpunum, ctr_wrap_reg, &ctr_wrap_time);
3109 		if (ret)
3110 			goto out_err;
3111 	}
3112 
3113 	if (!delivered || !reference) {
3114 		ret = -EFAULT;
3115 		goto out_err;
3116 	}
3117 
3118 	perf_fb_ctrs->delivered = delivered;
3119 	perf_fb_ctrs->reference = reference;
3120 	perf_fb_ctrs->wraparound_time = ctr_wrap_time;
3121 out_err:
3122 	if (regs_in_pcc)
3123 		up_write(&pcc_ss_data->pcc_lock);
3124 	return ret;
3125 }
3126 EXPORT_SYMBOL_GPL(cppc_get_perf_ctrs);
3127 
3128 /*
3129  * Set Energy Performance Preference Register value through
3130  * Performance Controls Interface
3131  */
3132 int cppc_set_epp_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls, bool enable)
3133 {
3134 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
3135 	struct cpc_register_resource *epp_set_reg;
3136 	struct cpc_register_resource *auto_sel_reg;
3137 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
3138 	struct cppc_pcc_data *pcc_ss_data = NULL;
3139 	bool auto_sel_pcc;
3140 	bool auto_sel_non_pcc;
3141 	bool epp_pcc;
3142 	bool epp_non_pcc;
3143 	int ret;
3144 
3145 	if (!cpc_desc) {
3146 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
3147 		return -ENODEV;
3148 	}
3149 
3150 	auto_sel_reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
3151 	epp_set_reg = &cpc_desc->cpc_regs[ENERGY_PERF];
3152 	if (!enable && auto_sel_reg->type == ACPI_TYPE_INTEGER &&
3153 	    auto_sel_reg->cpc_entry.int_value == 1)
3154 		return -EOPNOTSUPP;
3155 
3156 	auto_sel_pcc = cpc_is_writable(auto_sel_reg) &&
3157 		CPC_IN_PCC(auto_sel_reg);
3158 	epp_pcc = cpc_is_writable(epp_set_reg) && CPC_IN_PCC(epp_set_reg);
3159 
3160 	auto_sel_non_pcc = cpc_is_writable(auto_sel_reg) && !auto_sel_pcc;
3161 	epp_non_pcc = cpc_is_writable(epp_set_reg) && !epp_pcc;
3162 
3163 	/* Complete fallible non-PCC writes before staging PCC data. */
3164 	if (auto_sel_non_pcc) {
3165 		ret = cpc_write(cpu, auto_sel_reg, enable);
3166 		if (ret)
3167 			return ret;
3168 	}
3169 	if (epp_non_pcc) {
3170 		ret = cpc_write(cpu, epp_set_reg, perf_ctrls->energy_perf);
3171 		if (ret)
3172 			return ret;
3173 	}
3174 
3175 	if (epp_pcc || auto_sel_pcc) {
3176 		if (pcc_ss_id < 0) {
3177 			pr_debug("Invalid pcc_ss_id for CPU:%d\n", cpu);
3178 			return -ENODEV;
3179 		}
3180 
3181 		pcc_ss_data = pcc_data[pcc_ss_id];
3182 		if (!pcc_ss_data)
3183 			return -ENODEV;
3184 
3185 		down_write(&pcc_ss_data->pcc_lock);
3186 
3187 		ret = check_pcc_chan(pcc_ss_id, false);
3188 		if (ret)
3189 			goto out_unlock;
3190 
3191 		if (auto_sel_pcc) {
3192 			ret = cpc_write(cpu, auto_sel_reg, enable);
3193 			if (ret)
3194 				goto out_unlock;
3195 		}
3196 
3197 		if (epp_pcc) {
3198 			ret = cpc_write(cpu, epp_set_reg, perf_ctrls->energy_perf);
3199 			if (ret)
3200 				goto out_unlock;
3201 		}
3202 
3203 		/* after writing CPC, transfer the ownership of PCC to platform */
3204 		ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
3205 
3206 out_unlock:
3207 		if (ret)
3208 			cppc_abort_pending_pcc_write(pcc_ss_id, pcc_ss_data, ret);
3209 		up_write(&pcc_ss_data->pcc_lock);
3210 	} else if (epp_non_pcc || auto_sel_non_pcc) {
3211 		ret = 0;
3212 	} else {
3213 		ret = -EOPNOTSUPP;
3214 		pr_debug("No writable EPP controls for CPU:%d\n", cpu);
3215 	}
3216 
3217 	return ret;
3218 }
3219 EXPORT_SYMBOL_GPL(cppc_set_epp_perf);
3220 
3221 /**
3222  * cppc_set_epp() - Write the EPP register.
3223  * @cpu: CPU on which to write register.
3224  * @epp_val: Value to write to the EPP register.
3225  */
3226 int cppc_set_epp(int cpu, u64 epp_val)
3227 {
3228 	if (epp_val > CPPC_EPP_ENERGY_EFFICIENCY_PREF)
3229 		return -EINVAL;
3230 
3231 	return cppc_set_reg_val(cpu, ENERGY_PERF, epp_val);
3232 }
3233 EXPORT_SYMBOL_GPL(cppc_set_epp);
3234 
3235 /**
3236  * cppc_get_auto_act_window() - Read autonomous activity window register.
3237  * @cpu: CPU from which to read register.
3238  * @auto_act_window: Return address.
3239  *
3240  * According to ACPI 6.5, s8.4.6.1.6, the value read from the autonomous
3241  * activity window register consists of two parts: a 7 bits value indicate
3242  * significand and a 3 bits value indicate exponent.
3243  */
3244 int cppc_get_auto_act_window(int cpu, u64 *auto_act_window)
3245 {
3246 	unsigned int exp;
3247 	u64 val, sig;
3248 	int ret;
3249 
3250 	if (auto_act_window == NULL)
3251 		return -EINVAL;
3252 
3253 	ret = cppc_get_reg_val(cpu, AUTO_ACT_WINDOW, &val);
3254 	if (ret)
3255 		return ret;
3256 
3257 	sig = val & CPPC_AUTO_ACT_WINDOW_MAX_SIG;
3258 	exp = (val >> CPPC_AUTO_ACT_WINDOW_SIG_BIT_SIZE) & CPPC_AUTO_ACT_WINDOW_MAX_EXP;
3259 	*auto_act_window = sig * int_pow(10, exp);
3260 
3261 	return 0;
3262 }
3263 EXPORT_SYMBOL_GPL(cppc_get_auto_act_window);
3264 
3265 /**
3266  * cppc_set_auto_act_window() - Write autonomous activity window register.
3267  * @cpu: CPU on which to write register.
3268  * @auto_act_window: usec value to write to the autonomous activity window register.
3269  *
3270  * According to ACPI 6.5, s8.4.6.1.6, the value to write to the autonomous
3271  * activity window register consists of two parts: a 7 bits value indicate
3272  * significand and a 3 bits value indicate exponent.
3273  */
3274 int cppc_set_auto_act_window(int cpu, u64 auto_act_window)
3275 {
3276 	/* The max value to store is 1270000000 */
3277 	u64 max_val = CPPC_AUTO_ACT_WINDOW_MAX_SIG * int_pow(10, CPPC_AUTO_ACT_WINDOW_MAX_EXP);
3278 	int exp = 0;
3279 	u64 val;
3280 
3281 	if (auto_act_window > max_val)
3282 		return -EINVAL;
3283 
3284 	/*
3285 	 * The max significand is 127, when auto_act_window is larger than
3286 	 * 129, discard the precision of the last digit and increase the
3287 	 * exponent by 1.
3288 	 */
3289 	while (auto_act_window > CPPC_AUTO_ACT_WINDOW_SIG_CARRY_THRESH) {
3290 		auto_act_window /= 10;
3291 		exp += 1;
3292 	}
3293 
3294 	/* For 128 and 129, cut it to 127. */
3295 	if (auto_act_window > CPPC_AUTO_ACT_WINDOW_MAX_SIG)
3296 		auto_act_window = CPPC_AUTO_ACT_WINDOW_MAX_SIG;
3297 
3298 	val = (exp << CPPC_AUTO_ACT_WINDOW_SIG_BIT_SIZE) + auto_act_window;
3299 
3300 	return cppc_set_reg_val(cpu, AUTO_ACT_WINDOW, val);
3301 }
3302 EXPORT_SYMBOL_GPL(cppc_set_auto_act_window);
3303 
3304 /**
3305  * cppc_get_auto_sel() - Read autonomous selection register.
3306  * @cpu: CPU from which to read register.
3307  * @enable: Return address.
3308  */
3309 int cppc_get_auto_sel(int cpu, bool *enable)
3310 {
3311 	u64 auto_sel;
3312 	int ret;
3313 
3314 	if (enable == NULL)
3315 		return -EINVAL;
3316 
3317 	ret = cppc_get_reg_val(cpu, AUTO_SEL_ENABLE, &auto_sel);
3318 	if (ret)
3319 		return ret;
3320 
3321 	*enable = (bool)auto_sel;
3322 
3323 	return 0;
3324 }
3325 EXPORT_SYMBOL_GPL(cppc_get_auto_sel);
3326 
3327 /**
3328  * cppc_auto_sel_is_immutable - Check for always-enabled autonomous selection.
3329  * @cpu: CPU whose _CPC descriptor to check.
3330  *
3331  * Context: Process context.
3332  * Return: true for Integer 1, false for a register or an absent descriptor.
3333  */
3334 bool cppc_auto_sel_is_immutable(int cpu)
3335 {
3336 	struct cpc_desc *cpc_desc;
3337 	struct cpc_register_resource *reg;
3338 
3339 	guard(mutex)(&cpc_desc_lock);
3340 	cpc_desc = per_cpu(cpc_desc_ptr, cpu);
3341 	if (!cpc_desc)
3342 		return false;
3343 
3344 	reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
3345 	return reg->type == ACPI_TYPE_INTEGER && reg->cpc_entry.int_value == 1;
3346 }
3347 EXPORT_SYMBOL_GPL(cppc_auto_sel_is_immutable);
3348 
3349 /**
3350  * cppc_set_auto_sel - Write autonomous selection register.
3351  * @cpu    : CPU to which to write register.
3352  * @enable : the desired value of autonomous selection resiter to be updated.
3353  */
3354 int cppc_set_auto_sel(int cpu, bool enable)
3355 {
3356 	return cppc_set_reg_val(cpu, AUTO_SEL_ENABLE, enable);
3357 }
3358 EXPORT_SYMBOL_GPL(cppc_set_auto_sel);
3359 
3360 /**
3361  * cppc_set_enable - Set to enable CPPC on the processor by writing the
3362  * Continuous Performance Control package EnableRegister field.
3363  * @cpu: CPU for which to enable CPPC register.
3364  * @enable: 0 - disable, 1 - enable CPPC feature on the processor.
3365  *
3366  * Return: 0 for success, -ERRNO or -EIO otherwise.
3367  */
3368 int cppc_set_enable(int cpu, bool enable)
3369 {
3370 	return cppc_set_reg_val(cpu, ENABLE, enable);
3371 }
3372 EXPORT_SYMBOL_GPL(cppc_set_enable);
3373 
3374 /**
3375  * cppc_get_perf - Get a CPU's performance controls.
3376  * @cpu: CPU for which to get performance controls.
3377  * @perf_ctrls: ptr to cppc_perf_ctrls. See cppc_acpi.h
3378  *
3379  * Desired Performance is not read and is returned as 0.
3380  *
3381  * Return: 0 for success with perf_ctrls, -ERRNO otherwise.
3382  */
3383 int cppc_get_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls)
3384 {
3385 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
3386 	struct cpc_register_resource *min_perf_reg, *max_perf_reg,
3387 				     *energy_perf_reg, *auto_sel_reg;
3388 	u64 min = 0, max = 0, energy_perf = 0, auto_sel = 0;
3389 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
3390 	struct cppc_pcc_data *pcc_ss_data = NULL;
3391 	int ret = 0, regs_in_pcc = 0;
3392 
3393 	if (!cpc_desc) {
3394 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
3395 		return -ENODEV;
3396 	}
3397 
3398 	if (!perf_ctrls) {
3399 		pr_debug("Invalid perf_ctrls pointer\n");
3400 		return -EINVAL;
3401 	}
3402 
3403 	min_perf_reg = &cpc_desc->cpc_regs[MIN_PERF];
3404 	max_perf_reg = &cpc_desc->cpc_regs[MAX_PERF];
3405 	energy_perf_reg = &cpc_desc->cpc_regs[ENERGY_PERF];
3406 	auto_sel_reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
3407 	perf_ctrls->min_perf_valid = false;
3408 
3409 	/* Are any of the regs PCC ?*/
3410 	if (CPC_IN_PCC(min_perf_reg) || CPC_IN_PCC(max_perf_reg) ||
3411 	    CPC_IN_PCC(energy_perf_reg) ||
3412 	    CPC_IN_PCC(auto_sel_reg)) {
3413 		if (pcc_ss_id < 0) {
3414 			pr_debug("Invalid pcc_ss_id for CPU:%d\n", cpu);
3415 			return -ENODEV;
3416 		}
3417 		pcc_ss_data = pcc_data[pcc_ss_id];
3418 		regs_in_pcc = 1;
3419 		down_write(&pcc_ss_data->pcc_lock);
3420 		/* Ring doorbell once to update PCC subspace */
3421 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
3422 			ret = -EIO;
3423 			goto out_err;
3424 		}
3425 	}
3426 
3427 	/* Read optional elements if present */
3428 	if (CPC_SUPPORTED(max_perf_reg)) {
3429 		ret = cpc_read(cpu, max_perf_reg, &max);
3430 		if (ret)
3431 			goto out_err;
3432 		if (max > U32_MAX) {
3433 			ret = -EFAULT;
3434 			goto out_err;
3435 		}
3436 	}
3437 	perf_ctrls->max_perf = max;
3438 
3439 	if (CPC_SUPPORTED(min_perf_reg)) {
3440 		ret = cpc_read(cpu, min_perf_reg, &min);
3441 		if (ret)
3442 			goto out_err;
3443 		if (min > U32_MAX) {
3444 			ret = -EFAULT;
3445 			goto out_err;
3446 		}
3447 		perf_ctrls->min_perf_valid = true;
3448 	}
3449 	perf_ctrls->min_perf = min;
3450 
3451 	perf_ctrls->desired_perf = 0;
3452 
3453 	if (CPC_SUPPORTED(energy_perf_reg)) {
3454 		ret = cpc_read(cpu, energy_perf_reg, &energy_perf);
3455 		if (ret)
3456 			goto out_err;
3457 	}
3458 	perf_ctrls->energy_perf = energy_perf;
3459 
3460 	if (CPC_SUPPORTED(auto_sel_reg)) {
3461 		ret = cpc_read(cpu, auto_sel_reg, &auto_sel);
3462 		if (ret)
3463 			goto out_err;
3464 	}
3465 	perf_ctrls->auto_sel = (bool)auto_sel;
3466 
3467 out_err:
3468 	if (regs_in_pcc)
3469 		up_write(&pcc_ss_data->pcc_lock);
3470 	return ret;
3471 }
3472 EXPORT_SYMBOL_GPL(cppc_get_perf);
3473 
3474 /**
3475  * cppc_set_perf - Set a CPU's performance controls.
3476  * @cpu: CPU for which to set performance controls.
3477  * @perf_ctrls: ptr to cppc_perf_ctrls. See cppc_acpi.h
3478  *
3479  * Return: 0 for success, -ERRNO otherwise.
3480  */
3481 int cppc_set_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls)
3482 {
3483 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
3484 	struct cpc_register_resource *desired_reg, *min_perf_reg, *max_perf_reg;
3485 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
3486 	struct cppc_pcc_data *pcc_ss_data = NULL;
3487 	bool desired_update, min_update, max_update;
3488 	bool desired_pcc, min_pcc, max_pcc, pcc_update;
3489 	bool pcc_layout, direct_layout, mixed_layout;
3490 	int ret = 0;
3491 
3492 	if (!cpc_desc) {
3493 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
3494 		return -ENODEV;
3495 	}
3496 
3497 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
3498 	min_perf_reg = &cpc_desc->cpc_regs[MIN_PERF];
3499 	max_perf_reg = &cpc_desc->cpc_regs[MAX_PERF];
3500 	desired_update = cpc_is_writable(desired_reg);
3501 	min_update = cpc_is_writable(min_perf_reg) &&
3502 		     (perf_ctrls->min_perf || perf_ctrls->min_perf_valid);
3503 	max_update = cpc_is_writable(max_perf_reg) &&
3504 		     perf_ctrls->max_perf;
3505 	desired_pcc = desired_update && CPC_IN_PCC(desired_reg);
3506 	min_pcc = min_update && CPC_IN_PCC(min_perf_reg);
3507 	max_pcc = max_update && CPC_IN_PCC(max_perf_reg);
3508 	pcc_update = desired_pcc || min_pcc || max_pcc;
3509 	pcc_layout = (cpc_is_writable(desired_reg) && CPC_IN_PCC(desired_reg)) ||
3510 		     (cpc_is_writable(min_perf_reg) && CPC_IN_PCC(min_perf_reg)) ||
3511 		     (cpc_is_writable(max_perf_reg) && CPC_IN_PCC(max_perf_reg));
3512 	direct_layout = (cpc_is_writable(desired_reg) &&
3513 			 !CPC_IN_PCC(desired_reg)) ||
3514 			(cpc_is_writable(min_perf_reg) &&
3515 			 !CPC_IN_PCC(min_perf_reg)) ||
3516 			(cpc_is_writable(max_perf_reg) &&
3517 			 !CPC_IN_PCC(max_perf_reg));
3518 	mixed_layout = pcc_layout && direct_layout;
3519 
3520 	if (mixed_layout || pcc_update) {
3521 		if (pcc_ss_id < 0) {
3522 			pr_debug("Invalid pcc_ss_id\n");
3523 			return -ENODEV;
3524 		}
3525 		pcc_ss_data = pcc_data[pcc_ss_id];
3526 		if (!pcc_ss_data)
3527 			return -ENODEV;
3528 	}
3529 
3530 	/*
3531 	 * A mixed layout cannot batch fallible direct writes safely: another
3532 	 * CPU's staged PCC values may no longer match if a direct write fails.
3533 	 * Serialize the complete mixed transaction and drain an older batch
3534 	 * before changing a direct control.
3535 	 */
3536 	if (mixed_layout) {
3537 		down_write(&pcc_ss_data->pcc_lock);
3538 		if (pcc_ss_data->pending_pcc_write_cmd) {
3539 			ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
3540 			if (ret)
3541 				goto out_mixed_unlock;
3542 		}
3543 
3544 		if (pcc_ss_data->platform_owns_pcc) {
3545 			ret = check_pcc_chan(pcc_ss_id, false);
3546 			if (ret)
3547 				goto out_mixed_unlock;
3548 		}
3549 
3550 		if (desired_update && !desired_pcc) {
3551 			ret = cpc_write(cpu, desired_reg,
3552 					perf_ctrls->desired_perf);
3553 			if (ret)
3554 				goto out_mixed_unlock;
3555 		}
3556 		if (min_update && !min_pcc) {
3557 			ret = cpc_write(cpu, min_perf_reg,
3558 					perf_ctrls->min_perf);
3559 			if (ret)
3560 				goto out_mixed_unlock;
3561 		}
3562 		if (max_update && !max_pcc) {
3563 			ret = cpc_write(cpu, max_perf_reg,
3564 					perf_ctrls->max_perf);
3565 			if (ret)
3566 				goto out_mixed_unlock;
3567 		}
3568 
3569 		if (desired_pcc) {
3570 			ret = cpc_write(cpu, desired_reg,
3571 					perf_ctrls->desired_perf);
3572 			if (ret)
3573 				goto out_mixed_unlock;
3574 		}
3575 		if (min_pcc) {
3576 			ret = cpc_write(cpu, min_perf_reg,
3577 					perf_ctrls->min_perf);
3578 			if (ret)
3579 				goto out_mixed_unlock;
3580 		}
3581 		if (max_pcc) {
3582 			ret = cpc_write(cpu, max_perf_reg,
3583 					perf_ctrls->max_perf);
3584 			if (ret)
3585 				goto out_mixed_unlock;
3586 		}
3587 
3588 		if (pcc_update) {
3589 			WRITE_ONCE(pcc_ss_data->pending_pcc_write_cmd, true);
3590 			cpc_desc->write_cmd_id = pcc_ss_data->pcc_write_cnt;
3591 			cpc_desc->write_cmd_status = 0;
3592 			ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
3593 		}
3594 
3595 out_mixed_unlock:
3596 		up_write(&pcc_ss_data->pcc_lock);
3597 		return ret;
3598 	}
3599 
3600 	/* A request without PCC updates has no payload to coordinate. */
3601 	if (!pcc_update) {
3602 		if (desired_update) {
3603 			ret = cpc_write(cpu, desired_reg,
3604 					perf_ctrls->desired_perf);
3605 			if (ret)
3606 				return ret;
3607 		}
3608 		if (min_update) {
3609 			ret = cpc_write(cpu, min_perf_reg,
3610 					perf_ctrls->min_perf);
3611 			if (ret)
3612 				return ret;
3613 		}
3614 		if (max_update)
3615 			ret = cpc_write(cpu, max_perf_reg,
3616 					perf_ctrls->max_perf);
3617 		return ret;
3618 	}
3619 
3620 	down_read(&pcc_ss_data->pcc_lock); /* BEGIN Phase-I */
3621 	if (pcc_ss_data->platform_owns_pcc) {
3622 		ret = check_pcc_chan(pcc_ss_id, false);
3623 		if (ret)
3624 			goto out_pcc_read_unlock;
3625 	}
3626 
3627 	/*
3628 	 * This is Phase-I where we want to write to CPC registers
3629 	 * -> We want all CPUs to be able to execute this phase in parallel
3630 	 *
3631 	 * Since read_lock can be acquired by multiple CPUs simultaneously we
3632 	 * achieve that goal here.
3633 	 */
3634 	if (desired_pcc) {
3635 		ret = cpc_write(cpu, desired_reg, perf_ctrls->desired_perf);
3636 		if (ret)
3637 			goto out_pcc_read_unlock;
3638 	}
3639 
3640 	if (min_pcc) {
3641 		ret = cpc_write(cpu, min_perf_reg, perf_ctrls->min_perf);
3642 		if (ret)
3643 			goto out_pcc_read_unlock;
3644 	}
3645 	if (max_pcc) {
3646 		ret = cpc_write(cpu, max_perf_reg, perf_ctrls->max_perf);
3647 		if (ret)
3648 			goto out_pcc_read_unlock;
3649 	}
3650 
3651 	/* Block a PCC read until the staged payload has been submitted. */
3652 	WRITE_ONCE(pcc_ss_data->pending_pcc_write_cmd, true);
3653 	cpc_desc->write_cmd_id = pcc_ss_data->pcc_write_cnt;
3654 	cpc_desc->write_cmd_status = 0;
3655 	up_read(&pcc_ss_data->pcc_lock);	/* END Phase-I */
3656 	/*
3657 	 * This is Phase-II where we transfer the ownership of PCC to Platform
3658 	 *
3659 	 * Short Summary: Basically if we think of a group of cppc_set_perf
3660 	 * requests that happened in short overlapping interval. The last CPU to
3661 	 * come out of Phase-I will enter Phase-II and ring the doorbell.
3662 	 *
3663 	 * We have the following requirements for Phase-II:
3664 	 *     1. We want to execute Phase-II only when there are no CPUs
3665 	 * currently executing in Phase-I
3666 	 *     2. Once we start Phase-II we want to avoid all other CPUs from
3667 	 * entering Phase-I.
3668 	 *     3. We want only one CPU among all those who went through Phase-I
3669 	 * to run phase-II
3670 	 *
3671 	 * If write_trylock fails to get the lock and doesn't transfer the
3672 	 * PCC ownership to the platform, then one of the following will be TRUE
3673 	 *     1. There is at-least one CPU in Phase-I which will later execute
3674 	 * write_trylock, so the CPUs in Phase-I will be responsible for
3675 	 * executing the Phase-II.
3676 	 *     2. Some other CPU has beaten this CPU to successfully execute the
3677 	 * write_trylock and has already acquired the write_lock. We know for a
3678 	 * fact it (other CPU acquiring the write_lock) couldn't have happened
3679 	 * before this CPU's Phase-I as we held the read_lock.
3680 	 *     3. Some other CPU executing pcc CMD_READ has stolen the
3681 	 * down_write, in which case, send_pcc_cmd will check for pending
3682 	 * CMD_WRITE commands by checking the pending_pcc_write_cmd.
3683 	 * So this CPU can be certain that its request will be delivered
3684 	 *    So in all cases, this CPU knows that its request will be delivered
3685 	 * by another CPU and can return
3686 	 *
3687 	 * After getting the down_write we still need to check for
3688 	 * pending_pcc_write_cmd to take care of the following scenario
3689 	 *    The thread running this code could be scheduled out between
3690 	 * Phase-I and Phase-II. Before it is scheduled back on, another CPU
3691 	 * could have delivered the request to Platform by triggering the
3692 	 * doorbell and transferred the ownership of PCC to platform. So this
3693 	 * avoids triggering an unnecessary doorbell and more importantly before
3694 	 * triggering the doorbell it makes sure that the PCC channel ownership
3695 	 * is still with OSPM.
3696 	 *   pending_pcc_write_cmd can also be cleared by a different CPU, if
3697 	 * there was a pcc CMD_READ waiting on down_write and it steals the lock
3698 	 * before the pcc CMD_WRITE is completed. send_pcc_cmd checks for this
3699 	 * case during a CMD_READ and if there are pending writes it delivers
3700 	 * the write command before servicing the read command
3701 	 */
3702 	if (down_write_trylock(&pcc_ss_data->pcc_lock)) {/* BEGIN Phase-II */
3703 		/* Update only if there are pending write commands */
3704 		if (pcc_ss_data->pending_pcc_write_cmd)
3705 			send_pcc_cmd(pcc_ss_id, CMD_WRITE);
3706 		up_write(&pcc_ss_data->pcc_lock);	/* END Phase-II */
3707 	} else {
3708 		/* Wait until pcc_write_cnt is updated by send_pcc_cmd */
3709 		wait_event(pcc_ss_data->pcc_write_wait_q,
3710 			   cpc_desc->write_cmd_id != pcc_ss_data->pcc_write_cnt);
3711 	}
3712 
3713 	/* send_pcc_cmd updates the status in case of failure */
3714 	return cpc_desc->write_cmd_status;
3715 
3716 out_pcc_read_unlock:
3717 	up_read(&pcc_ss_data->pcc_lock);
3718 	return ret;
3719 }
3720 EXPORT_SYMBOL_GPL(cppc_set_perf);
3721 
3722 /**
3723  * cppc_get_perf_limited - Get the Performance Limited register value.
3724  * @cpu: CPU from which to get Performance Limited register.
3725  * @perf_limited: Pointer to store the Performance Limited value.
3726  *
3727  * The returned value contains sticky status bits indicating platform-imposed
3728  * performance limitations.
3729  *
3730  * Return: 0 for success, -EIO on failure, -EOPNOTSUPP if not supported.
3731  */
3732 int cppc_get_perf_limited(int cpu, u64 *perf_limited)
3733 {
3734 	return cppc_get_reg_val(cpu, PERF_LIMITED, perf_limited);
3735 }
3736 EXPORT_SYMBOL_GPL(cppc_get_perf_limited);
3737 
3738 /**
3739  * cppc_set_perf_limited() - Clear bits in the Performance Limited register.
3740  * @cpu: CPU on which to write register.
3741  * @bits_to_clear: Zero for no-op or CPPC_PERF_LIMITED_MASK to clear both bits.
3742  *
3743  * The Performance Limited register contains two sticky bits set by platform:
3744  *   - Bit 0 (Desired_Excursion): Set when delivered performance is constrained
3745  *     below desired performance. Not used when Autonomous Selection is enabled.
3746  *   - Bit 1 (Minimum_Excursion): Set when delivered performance is constrained
3747  *     below minimum performance.
3748  *
3749  * These bits are sticky and remain set until OSPM explicitly clears them.
3750  * Selective clears are unsupported because they require an interlocked RMW.
3751  *
3752  * Return: 0 for success, -EINVAL for invalid bits, -EIO on register
3753  *         access failure, -EOPNOTSUPP if not supported.
3754  */
3755 int cppc_set_perf_limited(int cpu, u64 bits_to_clear)
3756 {
3757 	/* Only bits 0 and 1 are valid */
3758 	if (bits_to_clear & ~(u64)CPPC_PERF_LIMITED_MASK)
3759 		return -EINVAL;
3760 
3761 	if (!bits_to_clear)
3762 		return 0;
3763 
3764 	/*
3765 	 * Writing zero clears both bits without depending on how a platform
3766 	 * treats written ones. ACPI does not define the effect of writing one,
3767 	 * so a selective clear cannot be implemented without an interlocked RMW.
3768 	 */
3769 	if (bits_to_clear != CPPC_PERF_LIMITED_MASK)
3770 		return -EOPNOTSUPP;
3771 
3772 	return cppc_set_reg_val(cpu, PERF_LIMITED, 0);
3773 }
3774 EXPORT_SYMBOL_GPL(cppc_set_perf_limited);
3775 
3776 /**
3777  * cppc_get_transition_latency - returns frequency transition latency in ns
3778  * @cpu_num: CPU number for per_cpu().
3779  *
3780  * ACPI CPPC does not explicitly specify how a platform can specify the
3781  * transition latency for performance change requests. The closest we have
3782  * is the timing information from the PCCT tables which provides the info
3783  * on the number and frequency of PCC commands the platform can handle.
3784  *
3785  * If desired_reg is in the SystemMemory or SystemIo ACPI address space,
3786  * then assume there is no latency.
3787  */
3788 int cppc_get_transition_latency(int cpu_num)
3789 {
3790 	/*
3791 	 * Expected transition latency is based on the PCCT timing values
3792 	 * Below are definition from ACPI spec:
3793 	 * pcc_nominal- Expected latency to process a command, in microseconds
3794 	 * pcc_mpar   - The maximum number of periodic requests that the subspace
3795 	 *              channel can support, reported in commands per minute. 0
3796 	 *              indicates no limitation.
3797 	 * pcc_mrtt   - The minimum amount of time that OSPM must wait after the
3798 	 *              completion of a command before issuing the next command,
3799 	 *              in microseconds.
3800 	 */
3801 	struct cpc_desc *cpc_desc;
3802 	struct cpc_register_resource *desired_reg;
3803 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu_num);
3804 	struct cppc_pcc_data *pcc_ss_data;
3805 	int latency_ns = 0;
3806 
3807 	cpc_desc = per_cpu(cpc_desc_ptr, cpu_num);
3808 	if (!cpc_desc)
3809 		return -ENODATA;
3810 
3811 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
3812 	if (!cpc_is_writable(desired_reg))
3813 		return -ENODATA;
3814 
3815 	if (CPC_IN_SYSTEM_MEMORY(desired_reg) || CPC_IN_SYSTEM_IO(desired_reg))
3816 		return 0;
3817 
3818 	if (!CPC_IN_PCC(desired_reg) || pcc_ss_id < 0)
3819 		return -ENODATA;
3820 
3821 	pcc_ss_data = pcc_data[pcc_ss_id];
3822 	if (pcc_ss_data->pcc_mpar)
3823 		latency_ns = 60 * (1000 * 1000 * 1000 / pcc_ss_data->pcc_mpar);
3824 
3825 	latency_ns = max_t(int, latency_ns, pcc_ss_data->pcc_nominal * 1000);
3826 	latency_ns = max_t(int, latency_ns, pcc_ss_data->pcc_mrtt * 1000);
3827 
3828 	return latency_ns;
3829 }
3830 EXPORT_SYMBOL_GPL(cppc_get_transition_latency);
3831 
3832 /* Minimum struct length needed for the DMI processor entry we want */
3833 #define DMI_ENTRY_PROCESSOR_MIN_LENGTH	48
3834 
3835 /* Offset in the DMI processor structure for the max frequency */
3836 #define DMI_PROCESSOR_MAX_SPEED		0x14
3837 
3838 /* Callback function used to retrieve the max frequency from DMI */
3839 static void cppc_find_dmi_mhz(const struct dmi_header *dm, void *private)
3840 {
3841 	const u8 *dmi_data = (const u8 *)dm;
3842 	u16 *mhz = (u16 *)private;
3843 
3844 	if (dm->type == DMI_ENTRY_PROCESSOR &&
3845 	    dm->length >= DMI_ENTRY_PROCESSOR_MIN_LENGTH) {
3846 		u16 val = (u16)get_unaligned((const u16 *)
3847 				(dmi_data + DMI_PROCESSOR_MAX_SPEED));
3848 		*mhz = umax(val, *mhz);
3849 	}
3850 }
3851 
3852 /* Look up the max frequency in DMI */
3853 u64 cppc_get_dmi_max_khz(void)
3854 {
3855 	u16 mhz = 0;
3856 
3857 	dmi_walk(cppc_find_dmi_mhz, &mhz);
3858 
3859 	/*
3860 	 * Real stupid fallback value, just in case there is no
3861 	 * actual value set.
3862 	 */
3863 	mhz = mhz ? mhz : 1;
3864 
3865 	return KHZ_PER_MHZ * mhz;
3866 }
3867 EXPORT_SYMBOL_GPL(cppc_get_dmi_max_khz);
3868 
3869 /*
3870  * If CPPC lowest_freq and nominal_freq registers are exposed then we can
3871  * use them to convert perf to freq and vice versa. The conversion is
3872  * extrapolated as an affine function passing by the 2 points:
3873  *  - (Low perf, Low freq)
3874  *  - (Nominal perf, Nominal freq)
3875  */
3876 unsigned int cppc_perf_to_khz(struct cppc_perf_caps *caps, unsigned int perf)
3877 {
3878 	s64 retval, offset = 0;
3879 	static u64 max_khz;
3880 	u64 mul, div;
3881 
3882 	if (caps->lowest_freq && caps->nominal_freq) {
3883 		/* Avoid special case when nominal_freq is equal to lowest_freq */
3884 		if (caps->lowest_freq == caps->nominal_freq) {
3885 			mul = caps->nominal_freq;
3886 			div = caps->nominal_perf;
3887 		} else {
3888 			mul = caps->nominal_freq - caps->lowest_freq;
3889 			div = caps->nominal_perf - caps->lowest_perf;
3890 		}
3891 		mul *= KHZ_PER_MHZ;
3892 		offset = caps->nominal_freq * KHZ_PER_MHZ -
3893 			 div64_u64(caps->nominal_perf * mul, div);
3894 	} else {
3895 		if (!max_khz)
3896 			max_khz = cppc_get_dmi_max_khz();
3897 		mul = max_khz;
3898 		div = caps->highest_perf;
3899 	}
3900 
3901 	retval = offset + div64_u64(perf * mul, div);
3902 	if (retval >= 0)
3903 		return retval;
3904 	return 0;
3905 }
3906 EXPORT_SYMBOL_GPL(cppc_perf_to_khz);
3907 
3908 unsigned int cppc_khz_to_perf(struct cppc_perf_caps *caps, unsigned int freq)
3909 {
3910 	s64 retval, offset = 0;
3911 	static u64 max_khz;
3912 	u64 mul, div;
3913 
3914 	if (caps->lowest_freq && caps->nominal_freq) {
3915 		/* Avoid special case when nominal_freq is equal to lowest_freq */
3916 		if (caps->lowest_freq == caps->nominal_freq) {
3917 			mul = caps->nominal_perf;
3918 			div = caps->nominal_freq;
3919 		} else {
3920 			mul = caps->nominal_perf - caps->lowest_perf;
3921 			div = caps->nominal_freq - caps->lowest_freq;
3922 		}
3923 		/*
3924 		 * We don't need to convert to kHz for computing offset and can
3925 		 * directly use nominal_freq and lowest_freq as the div64_u64
3926 		 * will remove the frequency unit.
3927 		 */
3928 		offset = caps->nominal_perf -
3929 			 div64_u64(caps->nominal_freq * mul, div);
3930 		/* But we need it for computing the perf level. */
3931 		div *= KHZ_PER_MHZ;
3932 	} else {
3933 		if (!max_khz)
3934 			max_khz = cppc_get_dmi_max_khz();
3935 		mul = caps->highest_perf;
3936 		div = max_khz;
3937 	}
3938 
3939 	retval = offset + div64_u64(freq * mul, div);
3940 	if (retval >= 0)
3941 		return retval;
3942 	return 0;
3943 }
3944 EXPORT_SYMBOL_GPL(cppc_khz_to_perf);
3945