xref: /linux/drivers/acpi/cppc_acpi.c (revision 346630e46b387ad6db7b3b254ba6f6d513d64d14)
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/iopoll.h>
38 #include <linux/ktime.h>
39 #include <linux/rwsem.h>
40 #include <linux/wait.h>
41 #include <linux/topology.h>
42 #include <linux/dmi.h>
43 #include <linux/units.h>
44 #include <linux/unaligned.h>
45 
46 #include <acpi/cppc_acpi.h>
47 
48 struct cppc_pcc_data {
49 	struct pcc_mbox_chan *pcc_channel;
50 	bool pcc_channel_acquired;
51 	unsigned int deadline_us;
52 	unsigned int pcc_mpar, pcc_mrtt, pcc_nominal;
53 
54 	bool pending_pcc_write_cmd;	/* Any pending/batched PCC write cmds? */
55 	bool platform_owns_pcc;		/* Ownership of PCC subspace */
56 	unsigned int pcc_write_cnt;	/* Running count of PCC write commands */
57 
58 	/*
59 	 * Lock to provide controlled access to the PCC channel.
60 	 *
61 	 * For performance critical usecases(currently cppc_set_perf)
62 	 *	We need to take read_lock and check if channel belongs to OSPM
63 	 * before reading or writing to PCC subspace
64 	 *	We need to take write_lock before transferring the channel
65 	 * ownership to the platform via a Doorbell
66 	 *	This allows us to batch a number of CPPC requests if they happen
67 	 * to originate in about the same time
68 	 *
69 	 * For non-performance critical usecases(init)
70 	 *	Take write_lock for all purposes which gives exclusive access
71 	 */
72 	struct rw_semaphore pcc_lock;
73 
74 	/* Wait queue for CPUs whose requests were batched */
75 	wait_queue_head_t pcc_write_wait_q;
76 	ktime_t last_cmd_cmpl_time;
77 	ktime_t last_mpar_reset;
78 	int mpar_count;
79 	int refcount;
80 };
81 
82 /* Array to represent the PCC channel per subspace ID */
83 static struct cppc_pcc_data *pcc_data[MAX_PCC_SUBSPACES];
84 /* The cpu_pcc_subspace_idx contains per CPU subspace ID */
85 static DEFINE_PER_CPU(int, cpu_pcc_subspace_idx);
86 
87 /*
88  * The cpc_desc structure contains the ACPI register details
89  * as described in the per CPU _CPC tables. The details
90  * include the type of register (e.g. PCC, System IO, FFH etc.)
91  * and destination addresses which lets us READ/WRITE CPU performance
92  * information using the appropriate I/O methods.
93  */
94 static DEFINE_PER_CPU(struct cpc_desc *, cpc_desc_ptr);
95 
96 /* pcc mapped address + header size + offset within PCC subspace */
97 #define GET_PCC_VADDR(offs, pcc_ss_id) (pcc_data[pcc_ss_id]->pcc_channel->shmem + \
98 						0x8 + (offs))
99 
100 /* Check if a CPC register is in PCC */
101 #define CPC_IN_PCC(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&		\
102 				(cpc)->cpc_entry.reg.space_id ==	\
103 				ACPI_ADR_SPACE_PLATFORM_COMM)
104 
105 /* Check if a CPC register is in FFH */
106 #define CPC_IN_FFH(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&		\
107 				(cpc)->cpc_entry.reg.space_id ==	\
108 				ACPI_ADR_SPACE_FIXED_HARDWARE)
109 
110 /* Check if a CPC register is in SystemMemory */
111 #define CPC_IN_SYSTEM_MEMORY(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
112 				(cpc)->cpc_entry.reg.space_id ==	\
113 				ACPI_ADR_SPACE_SYSTEM_MEMORY)
114 
115 /* Check if a CPC register is in SystemIo */
116 #define CPC_IN_SYSTEM_IO(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
117 				(cpc)->cpc_entry.reg.space_id ==	\
118 				ACPI_ADR_SPACE_SYSTEM_IO)
119 
120 /* Evaluates to True if reg is a NULL register descriptor */
121 #define IS_NULL_REG(reg) ((reg)->space_id ==  ACPI_ADR_SPACE_SYSTEM_MEMORY && \
122 				(reg)->address == 0 &&			\
123 				(reg)->bit_width == 0 &&		\
124 				(reg)->bit_offset == 0 &&		\
125 				(reg)->access_width == 0)
126 
127 /* Evaluates to True if an optional cpc field is supported */
128 #define CPC_SUPPORTED(cpc) ((cpc)->type == ACPI_TYPE_INTEGER ?		\
129 				!!(cpc)->cpc_entry.int_value :		\
130 				!IS_NULL_REG(&(cpc)->cpc_entry.reg))
131 
132 /*
133  * Each bit indicates the optionality of the register in per-cpu
134  * cpc_regs[] with the corresponding index. 0 means mandatory and 1
135  * means optional.
136  */
137 #define REG_OPTIONAL (0x7FC7D0)
138 
139 /*
140  * Use the index of the register in per-cpu cpc_regs[] to check if
141  * it's an optional one.
142  */
143 #define IS_OPTIONAL_CPC_REG(reg_idx) (REG_OPTIONAL & (1U << (reg_idx)))
144 
145 /*
146  * Arbitrary Retries in case the remote processor is slow to respond
147  * to PCC commands. Keeping it high enough to cover emulators where
148  * the processors run painfully slow.
149  */
150 #define NUM_RETRIES 500ULL
151 
152 #define OVER_16BTS_MASK ~0xFFFFULL
153 
154 #define define_one_cppc_ro(_name)		\
155 static struct kobj_attribute _name =		\
156 __ATTR(_name, 0444, show_##_name, NULL)
157 
158 #define to_cpc_desc(a) container_of(a, struct cpc_desc, kobj)
159 
160 #define show_cppc_data(access_fn, struct_name, member_name)		\
161 	static ssize_t show_##member_name(struct kobject *kobj,		\
162 				struct kobj_attribute *attr, char *buf)	\
163 	{								\
164 		struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);		\
165 		struct struct_name st_name = {0};			\
166 		int ret;						\
167 									\
168 		ret = access_fn(cpc_ptr->cpu_id, &st_name);		\
169 		if (ret)						\
170 			return ret;					\
171 									\
172 		return sysfs_emit(buf, "%llu\n",		\
173 				(u64)st_name.member_name);		\
174 	}								\
175 	define_one_cppc_ro(member_name)
176 
177 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, highest_perf);
178 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_perf);
179 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_perf);
180 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, reference_perf);
181 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_nonlinear_perf);
182 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, guaranteed_perf);
183 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_freq);
184 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_freq);
185 
186 show_cppc_data(cppc_get_perf_ctrs, cppc_perf_fb_ctrs, wraparound_time);
187 
188 /*
189  * PCC reuses the access_width field as the subspace id, so only decode access
190  * size for non-PCC registers. Otherwise, use the bit_width.
191  */
192 #define GET_BIT_WIDTH(reg) (((reg)->access_width &&				\
193 			     (reg)->space_id != ACPI_ADR_SPACE_PLATFORM_COMM) ? \
194 			    (8 << ((reg)->access_width - 1)) : (reg)->bit_width)
195 
196 /* Shift and apply the mask for CPC reads/writes */
197 #define MASK_VAL_READ(reg, val) (((val) >> (reg)->bit_offset) &				\
198 					GENMASK(((reg)->bit_width) - 1, 0))
199 #define MASK_VAL_WRITE(reg, prev_val, val)						\
200 	((((val) & GENMASK(((reg)->bit_width) - 1, 0)) << (reg)->bit_offset) |		\
201 	((prev_val) & ~(GENMASK(((reg)->bit_width) - 1, 0) << (reg)->bit_offset)))	\
202 
203 static ssize_t show_feedback_ctrs(struct kobject *kobj,
204 		struct kobj_attribute *attr, char *buf)
205 {
206 	struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);
207 	struct cppc_perf_fb_ctrs fb_ctrs = {0};
208 	int ret;
209 
210 	ret = cppc_get_perf_ctrs(cpc_ptr->cpu_id, &fb_ctrs);
211 	if (ret)
212 		return ret;
213 
214 	return sysfs_emit(buf, "ref:%llu del:%llu\n",
215 			fb_ctrs.reference, fb_ctrs.delivered);
216 }
217 define_one_cppc_ro(feedback_ctrs);
218 
219 static struct attribute *cppc_attrs[] = {
220 	&feedback_ctrs.attr,
221 	&reference_perf.attr,
222 	&wraparound_time.attr,
223 	&highest_perf.attr,
224 	&lowest_perf.attr,
225 	&lowest_nonlinear_perf.attr,
226 	&guaranteed_perf.attr,
227 	&nominal_perf.attr,
228 	&nominal_freq.attr,
229 	&lowest_freq.attr,
230 	NULL
231 };
232 ATTRIBUTE_GROUPS(cppc);
233 
234 static const struct kobj_type cppc_ktype = {
235 	.sysfs_ops = &kobj_sysfs_ops,
236 	.default_groups = cppc_groups,
237 };
238 
239 static int check_pcc_chan(int pcc_ss_id, bool chk_err_bit)
240 {
241 	int ret, status;
242 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
243 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
244 					pcc_ss_data->pcc_channel->shmem;
245 
246 	if (!pcc_ss_data->platform_owns_pcc)
247 		return 0;
248 
249 	/*
250 	 * Poll PCC status register every 3us(delay_us) for maximum of
251 	 * deadline_us(timeout_us) until PCC command complete bit is set(cond)
252 	 */
253 	ret = readw_relaxed_poll_timeout(&generic_comm_base->status, status,
254 					status & PCC_CMD_COMPLETE_MASK, 3,
255 					pcc_ss_data->deadline_us);
256 
257 	if (likely(!ret)) {
258 		pcc_ss_data->platform_owns_pcc = false;
259 		if (chk_err_bit && (status & PCC_ERROR_MASK))
260 			ret = -EIO;
261 	}
262 
263 	if (unlikely(ret))
264 		pr_err("PCC check channel failed for ss: %d. ret=%d\n",
265 		       pcc_ss_id, ret);
266 
267 	return ret;
268 }
269 
270 /*
271  * This function transfers the ownership of the PCC to the platform
272  * So it must be called while holding write_lock(pcc_lock)
273  */
274 static int send_pcc_cmd(int pcc_ss_id, u16 cmd)
275 {
276 	int ret = -EIO, i;
277 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
278 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
279 					pcc_ss_data->pcc_channel->shmem;
280 	unsigned int time_delta;
281 
282 	/*
283 	 * For CMD_WRITE we know for a fact the caller should have checked
284 	 * the channel before writing to PCC space
285 	 */
286 	if (cmd == CMD_READ) {
287 		/*
288 		 * If there are pending cpc_writes, then we stole the channel
289 		 * before write completion, so first send a WRITE command to
290 		 * platform
291 		 */
292 		if (pcc_ss_data->pending_pcc_write_cmd)
293 			send_pcc_cmd(pcc_ss_id, CMD_WRITE);
294 
295 		ret = check_pcc_chan(pcc_ss_id, false);
296 		if (ret)
297 			goto end;
298 	} else /* CMD_WRITE */
299 		pcc_ss_data->pending_pcc_write_cmd = FALSE;
300 
301 	/*
302 	 * Handle the Minimum Request Turnaround Time(MRTT)
303 	 * "The minimum amount of time that OSPM must wait after the completion
304 	 * of a command before issuing the next command, in microseconds"
305 	 */
306 	if (pcc_ss_data->pcc_mrtt) {
307 		time_delta = ktime_us_delta(ktime_get(),
308 					    pcc_ss_data->last_cmd_cmpl_time);
309 		if (pcc_ss_data->pcc_mrtt > time_delta)
310 			udelay(pcc_ss_data->pcc_mrtt - time_delta);
311 	}
312 
313 	/*
314 	 * Handle the non-zero Maximum Periodic Access Rate(MPAR)
315 	 * "The maximum number of periodic requests that the subspace channel can
316 	 * support, reported in commands per minute. 0 indicates no limitation."
317 	 *
318 	 * This parameter should be ideally zero or large enough so that it can
319 	 * handle maximum number of requests that all the cores in the system can
320 	 * collectively generate. If it is not, we will follow the spec and just
321 	 * not send the request to the platform after hitting the MPAR limit in
322 	 * any 60s window
323 	 */
324 	if (pcc_ss_data->pcc_mpar) {
325 		if (pcc_ss_data->mpar_count == 0) {
326 			time_delta = ktime_ms_delta(ktime_get(),
327 						    pcc_ss_data->last_mpar_reset);
328 			if ((time_delta < 60 * MSEC_PER_SEC) && pcc_ss_data->last_mpar_reset) {
329 				pr_debug("PCC cmd for subspace %d not sent due to MPAR limit",
330 					 pcc_ss_id);
331 				ret = -EIO;
332 				goto end;
333 			}
334 			pcc_ss_data->last_mpar_reset = ktime_get();
335 			pcc_ss_data->mpar_count = pcc_ss_data->pcc_mpar;
336 		}
337 		pcc_ss_data->mpar_count--;
338 	}
339 
340 	/* Write to the shared comm region. */
341 	writew_relaxed(cmd, &generic_comm_base->command);
342 
343 	/* Flip CMD COMPLETE bit */
344 	writew_relaxed(0, &generic_comm_base->status);
345 
346 	pcc_ss_data->platform_owns_pcc = true;
347 
348 	/* Ring doorbell */
349 	ret = mbox_send_message(pcc_ss_data->pcc_channel->mchan, &cmd);
350 	if (ret < 0) {
351 		pr_err("Err sending PCC mbox message. ss: %d cmd:%d, ret:%d\n",
352 		       pcc_ss_id, cmd, ret);
353 		goto end;
354 	}
355 
356 	/* wait for completion and check for PCC error bit */
357 	ret = check_pcc_chan(pcc_ss_id, true);
358 
359 	if (pcc_ss_data->pcc_mrtt)
360 		pcc_ss_data->last_cmd_cmpl_time = ktime_get();
361 
362 	if (pcc_ss_data->pcc_channel->mchan->mbox->txdone_irq)
363 		mbox_chan_txdone(pcc_ss_data->pcc_channel->mchan, ret);
364 	else
365 		mbox_client_txdone(pcc_ss_data->pcc_channel->mchan, ret);
366 
367 end:
368 	if (cmd == CMD_WRITE) {
369 		if (unlikely(ret)) {
370 			for_each_possible_cpu(i) {
371 				struct cpc_desc *desc = per_cpu(cpc_desc_ptr, i);
372 
373 				if (!desc)
374 					continue;
375 
376 				if (desc->write_cmd_id == pcc_ss_data->pcc_write_cnt)
377 					desc->write_cmd_status = ret;
378 			}
379 		}
380 		pcc_ss_data->pcc_write_cnt++;
381 		wake_up_all(&pcc_ss_data->pcc_write_wait_q);
382 	}
383 
384 	return ret;
385 }
386 
387 static void cppc_chan_tx_done(struct mbox_client *cl, void *msg, int ret)
388 {
389 	if (ret < 0)
390 		pr_debug("TX did not complete: CMD sent:%x, ret:%d\n",
391 				*(u16 *)msg, ret);
392 	else
393 		pr_debug("TX completed. CMD sent:%x, ret:%d\n",
394 				*(u16 *)msg, ret);
395 }
396 
397 static struct mbox_client cppc_mbox_cl = {
398 	.tx_done = cppc_chan_tx_done,
399 	.knows_txdone = true,
400 };
401 
402 static int acpi_get_psd(struct cpc_desc *cpc_ptr, acpi_handle handle)
403 {
404 	int result = -EFAULT;
405 	acpi_status status = AE_OK;
406 	struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
407 	struct acpi_buffer format = {sizeof("NNNNN"), "NNNNN"};
408 	struct acpi_buffer state = {0, NULL};
409 	union acpi_object  *psd = NULL;
410 	struct acpi_psd_package *pdomain;
411 
412 	status = acpi_evaluate_object_typed(handle, "_PSD", NULL,
413 					    &buffer, ACPI_TYPE_PACKAGE);
414 	if (status == AE_NOT_FOUND)	/* _PSD is optional */
415 		return 0;
416 	if (ACPI_FAILURE(status))
417 		return -ENODEV;
418 
419 	psd = buffer.pointer;
420 	if (!psd || psd->package.count != 1) {
421 		pr_debug("Invalid _PSD data\n");
422 		goto end;
423 	}
424 
425 	pdomain = &(cpc_ptr->domain_info);
426 
427 	state.length = sizeof(struct acpi_psd_package);
428 	state.pointer = pdomain;
429 
430 	status = acpi_extract_package(&(psd->package.elements[0]),
431 		&format, &state);
432 	if (ACPI_FAILURE(status)) {
433 		pr_debug("Invalid _PSD data for CPU:%d\n", cpc_ptr->cpu_id);
434 		goto end;
435 	}
436 
437 	if (pdomain->num_entries != ACPI_PSD_REV0_ENTRIES) {
438 		pr_debug("Unknown _PSD:num_entries for CPU:%d\n", cpc_ptr->cpu_id);
439 		goto end;
440 	}
441 
442 	if (pdomain->revision != ACPI_PSD_REV0_REVISION) {
443 		pr_debug("Unknown _PSD:revision for CPU: %d\n", cpc_ptr->cpu_id);
444 		goto end;
445 	}
446 
447 	if (pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ALL &&
448 	    pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ANY &&
449 	    pdomain->coord_type != DOMAIN_COORD_TYPE_HW_ALL) {
450 		pr_debug("Invalid _PSD:coord_type for CPU:%d\n", cpc_ptr->cpu_id);
451 		goto end;
452 	}
453 
454 	result = 0;
455 end:
456 	kfree(buffer.pointer);
457 	return result;
458 }
459 
460 bool acpi_cpc_valid(void)
461 {
462 	struct cpc_desc *cpc_ptr;
463 	int cpu;
464 
465 	if (acpi_disabled)
466 		return false;
467 
468 	for_each_online_cpu(cpu) {
469 		cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
470 		if (!cpc_ptr)
471 			return false;
472 	}
473 
474 	return true;
475 }
476 EXPORT_SYMBOL_GPL(acpi_cpc_valid);
477 
478 bool cppc_allow_fast_switch(const struct cpumask *cpus)
479 {
480 	struct cpc_register_resource *desired_reg, *min_reg, *max_reg;
481 	struct cpc_desc *cpc_ptr;
482 	int cpu;
483 
484 	for_each_cpu(cpu, cpus) {
485 		cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
486 		if (!cpc_ptr)
487 			return false;
488 		desired_reg = &cpc_ptr->cpc_regs[DESIRED_PERF];
489 		min_reg = &cpc_ptr->cpc_regs[MIN_PERF];
490 		max_reg = &cpc_ptr->cpc_regs[MAX_PERF];
491 
492 		if (!CPC_SUPPORTED(desired_reg) ||
493 		    (!CPC_IN_SYSTEM_MEMORY(desired_reg) &&
494 		     !CPC_IN_SYSTEM_IO(desired_reg)) ||
495 		    (CPC_SUPPORTED(min_reg) &&
496 		     !CPC_IN_SYSTEM_MEMORY(min_reg) &&
497 		     !CPC_IN_SYSTEM_IO(min_reg)) ||
498 		    (CPC_SUPPORTED(max_reg) &&
499 		     !CPC_IN_SYSTEM_MEMORY(max_reg) &&
500 		     !CPC_IN_SYSTEM_IO(max_reg)))
501 			return false;
502 	}
503 
504 	return true;
505 }
506 EXPORT_SYMBOL_GPL(cppc_allow_fast_switch);
507 
508 /**
509  * acpi_get_psd_map - Map the CPUs in the freq domain of a given cpu
510  * @cpu: Find all CPUs that share a domain with cpu.
511  * @cpu_data: Pointer to CPU specific CPPC data including PSD info.
512  *
513  *	Return: 0 for success or negative value for err.
514  */
515 int acpi_get_psd_map(unsigned int cpu, struct cppc_cpudata *cpu_data)
516 {
517 	struct cpc_desc *cpc_ptr, *match_cpc_ptr;
518 	struct acpi_psd_package *match_pdomain;
519 	struct acpi_psd_package *pdomain;
520 	int count_target, i;
521 
522 	/*
523 	 * Now that we have _PSD data from all CPUs, let's setup P-state
524 	 * domain info.
525 	 */
526 	cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
527 	if (!cpc_ptr)
528 		return -EFAULT;
529 
530 	pdomain = &(cpc_ptr->domain_info);
531 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
532 	if (pdomain->num_processors <= 1)
533 		return 0;
534 
535 	/* Validate the Domain info */
536 	count_target = pdomain->num_processors;
537 	if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ALL)
538 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ALL;
539 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_HW_ALL)
540 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_HW;
541 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ANY)
542 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ANY;
543 
544 	for_each_possible_cpu(i) {
545 		if (i == cpu)
546 			continue;
547 
548 		match_cpc_ptr = per_cpu(cpc_desc_ptr, i);
549 		if (!match_cpc_ptr)
550 			continue;
551 
552 		match_pdomain = &(match_cpc_ptr->domain_info);
553 		if (match_pdomain->domain != pdomain->domain)
554 			continue;
555 
556 		/* Here i and cpu are in the same domain */
557 		if (match_pdomain->num_processors != count_target)
558 			goto err_fault;
559 
560 		if (pdomain->coord_type != match_pdomain->coord_type)
561 			goto err_fault;
562 
563 		cpumask_set_cpu(i, cpu_data->shared_cpu_map);
564 	}
565 
566 	return 0;
567 
568 err_fault:
569 	/* Assume no coordination on any error parsing domain info */
570 	cpumask_clear(cpu_data->shared_cpu_map);
571 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
572 	cpu_data->shared_type = CPUFREQ_SHARED_TYPE_NONE;
573 
574 	return -EFAULT;
575 }
576 EXPORT_SYMBOL_GPL(acpi_get_psd_map);
577 
578 static int register_pcc_channel(int pcc_ss_idx)
579 {
580 	struct pcc_mbox_chan *pcc_chan;
581 	u64 usecs_lat;
582 
583 	if (pcc_ss_idx >= 0) {
584 		pcc_chan = pcc_mbox_request_channel(&cppc_mbox_cl, pcc_ss_idx);
585 
586 		if (IS_ERR(pcc_chan)) {
587 			pr_err("Failed to find PCC channel for subspace %d\n",
588 			       pcc_ss_idx);
589 			return -ENODEV;
590 		}
591 
592 		pcc_data[pcc_ss_idx]->pcc_channel = pcc_chan;
593 		/*
594 		 * cppc_ss->latency is just a Nominal value. In reality
595 		 * the remote processor could be much slower to reply.
596 		 * So add an arbitrary amount of wait on top of Nominal.
597 		 */
598 		usecs_lat = NUM_RETRIES * pcc_chan->latency;
599 		pcc_data[pcc_ss_idx]->deadline_us = usecs_lat;
600 		pcc_data[pcc_ss_idx]->pcc_mrtt = pcc_chan->min_turnaround_time;
601 		pcc_data[pcc_ss_idx]->pcc_mpar = pcc_chan->max_access_rate;
602 		pcc_data[pcc_ss_idx]->pcc_nominal = pcc_chan->latency;
603 
604 		/* Set flag so that we don't come here for each CPU. */
605 		pcc_data[pcc_ss_idx]->pcc_channel_acquired = true;
606 	}
607 
608 	return 0;
609 }
610 
611 /**
612  * cpc_ffh_supported() - check if FFH reading supported
613  *
614  * Check if the architecture has support for functional fixed hardware
615  * read/write capability.
616  *
617  * Return: true for supported, false for not supported
618  */
619 bool __weak cpc_ffh_supported(void)
620 {
621 	return false;
622 }
623 
624 /**
625  * cpc_supported_by_cpu() - check if CPPC is supported by CPU
626  *
627  * Check if the architectural support for CPPC is present even
628  * if the _OSC hasn't prescribed it
629  *
630  * Return: true for supported, false for not supported
631  */
632 bool __weak cpc_supported_by_cpu(void)
633 {
634 	return false;
635 }
636 
637 /**
638  * pcc_data_alloc() - Allocate the pcc_data memory for pcc subspace
639  * @pcc_ss_id: PCC Subspace index as in the PCC client ACPI package.
640  *
641  * Check and allocate the cppc_pcc_data memory.
642  * In some processor configurations it is possible that same subspace
643  * is shared between multiple CPUs. This is seen especially in CPUs
644  * with hardware multi-threading support.
645  *
646  * Return: 0 for success, errno for failure
647  */
648 static int pcc_data_alloc(int pcc_ss_id)
649 {
650 	if (pcc_ss_id < 0 || pcc_ss_id >= MAX_PCC_SUBSPACES)
651 		return -EINVAL;
652 
653 	if (pcc_data[pcc_ss_id]) {
654 		pcc_data[pcc_ss_id]->refcount++;
655 	} else {
656 		pcc_data[pcc_ss_id] = kzalloc_obj(struct cppc_pcc_data);
657 		if (!pcc_data[pcc_ss_id])
658 			return -ENOMEM;
659 		pcc_data[pcc_ss_id]->refcount++;
660 	}
661 
662 	return 0;
663 }
664 
665 /*
666  * An example CPC table looks like the following.
667  *
668  *  Name (_CPC, Package() {
669  *      17,							// NumEntries
670  *      1,							// Revision
671  *      ResourceTemplate() {Register(PCC, 32, 0, 0x120, 2)},	// Highest Performance
672  *      ResourceTemplate() {Register(PCC, 32, 0, 0x124, 2)},	// Nominal Performance
673  *      ResourceTemplate() {Register(PCC, 32, 0, 0x128, 2)},	// Lowest Nonlinear Performance
674  *      ResourceTemplate() {Register(PCC, 32, 0, 0x12C, 2)},	// Lowest Performance
675  *      ResourceTemplate() {Register(PCC, 32, 0, 0x130, 2)},	// Guaranteed Performance Register
676  *      ResourceTemplate() {Register(PCC, 32, 0, 0x110, 2)},	// Desired Performance Register
677  *      ResourceTemplate() {Register(SystemMemory, 0, 0, 0, 0)},
678  *      ...
679  *      ...
680  *      ...
681  *  }
682  * Each Register() encodes how to access that specific register.
683  * e.g. a sample PCC entry has the following encoding:
684  *
685  *  Register (
686  *      PCC,	// AddressSpaceKeyword
687  *      8,	// RegisterBitWidth
688  *      8,	// RegisterBitOffset
689  *      0x30,	// RegisterAddress
690  *      9,	// AccessSize (subspace ID)
691  *  )
692  */
693 
694 /**
695  * acpi_cppc_processor_probe - Search for per CPU _CPC objects.
696  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
697  *
698  *	Return: 0 for success or negative value for err.
699  */
700 int acpi_cppc_processor_probe(struct acpi_processor *pr)
701 {
702 	struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
703 	union acpi_object *out_obj, *cpc_obj;
704 	struct cpc_desc *cpc_ptr;
705 	struct cpc_reg *gas_t;
706 	struct device *cpu_dev;
707 	acpi_handle handle = pr->handle;
708 	unsigned int num_ent, i, cpc_rev;
709 	int pcc_subspace_id = -1;
710 	acpi_status status;
711 	int ret = -ENODATA;
712 
713 	if (!osc_sb_cppc2_support_acked) {
714 		pr_debug("CPPC v2 _OSC not acked\n");
715 		if (!cpc_supported_by_cpu()) {
716 			pr_debug("CPPC is not supported by the CPU\n");
717 			return -ENODEV;
718 		}
719 	}
720 
721 	/* Parse the ACPI _CPC table for this CPU. */
722 	status = acpi_evaluate_object_typed(handle, "_CPC", NULL, &output,
723 			ACPI_TYPE_PACKAGE);
724 	if (ACPI_FAILURE(status)) {
725 		ret = -ENODEV;
726 		goto out_buf_free;
727 	}
728 
729 	out_obj = (union acpi_object *) output.pointer;
730 
731 	cpc_ptr = kzalloc_obj(struct cpc_desc);
732 	if (!cpc_ptr) {
733 		ret = -ENOMEM;
734 		goto out_buf_free;
735 	}
736 
737 	/* First entry is NumEntries. */
738 	cpc_obj = &out_obj->package.elements[0];
739 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
740 		num_ent = cpc_obj->integer.value;
741 		if (num_ent <= 1) {
742 			pr_debug("Unexpected _CPC NumEntries value (%d) for CPU:%d\n",
743 				 num_ent, pr->id);
744 			goto out_free;
745 		}
746 	} else {
747 		pr_debug("Unexpected _CPC NumEntries entry type (%d) for CPU:%d\n",
748 			 cpc_obj->type, pr->id);
749 		goto out_free;
750 	}
751 
752 	/* Second entry should be revision. */
753 	cpc_obj = &out_obj->package.elements[1];
754 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
755 		cpc_rev = cpc_obj->integer.value;
756 	} else {
757 		pr_debug("Unexpected _CPC Revision entry type (%d) for CPU:%d\n",
758 			 cpc_obj->type, pr->id);
759 		goto out_free;
760 	}
761 
762 	if (cpc_rev < CPPC_V2_REV) {
763 		pr_debug("Unsupported _CPC Revision (%d) for CPU:%d\n", cpc_rev,
764 			 pr->id);
765 		goto out_free;
766 	}
767 
768 	/*
769 	 * Disregard _CPC if the number of entries in the return package is not
770 	 * as expected, but support future revisions being proper supersets of
771 	 * the v4 and only causing more entries to be returned by _CPC.
772 	 */
773 	if ((cpc_rev == CPPC_V2_REV && num_ent != CPPC_V2_NUM_ENT) ||
774 	    (cpc_rev == CPPC_V3_REV && num_ent != CPPC_V3_NUM_ENT) ||
775 	    (cpc_rev == CPPC_V4_REV && num_ent != CPPC_V4_NUM_ENT) ||
776 	    (cpc_rev > CPPC_V4_REV && num_ent <= CPPC_V4_NUM_ENT)) {
777 		pr_debug("Unexpected number of _CPC return package entries (%d) for CPU:%d\n",
778 			 num_ent, pr->id);
779 		goto out_free;
780 	}
781 	if (cpc_rev > CPPC_V4_REV) {
782 		num_ent = CPPC_V4_NUM_ENT;
783 		cpc_rev = CPPC_V4_REV;
784 	}
785 
786 	cpc_ptr->num_entries = num_ent;
787 	cpc_ptr->version = cpc_rev;
788 
789 	/* Iterate through remaining entries in _CPC */
790 	for (i = 2; i < num_ent; i++) {
791 		cpc_obj = &out_obj->package.elements[i];
792 
793 		if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
794 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_INTEGER;
795 			cpc_ptr->cpc_regs[i-2].cpc_entry.int_value = cpc_obj->integer.value;
796 		} else if (cpc_obj->type == ACPI_TYPE_BUFFER) {
797 			gas_t = (struct cpc_reg *)
798 				cpc_obj->buffer.pointer;
799 
800 			/*
801 			 * The PCC Subspace index is encoded inside
802 			 * the CPC table entries. The same PCC index
803 			 * will be used for all the PCC entries,
804 			 * so extract it only once.
805 			 */
806 			if (gas_t->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
807 				if (pcc_subspace_id < 0) {
808 					pcc_subspace_id = gas_t->access_width;
809 					if (pcc_data_alloc(pcc_subspace_id))
810 						goto out_free;
811 				} else if (pcc_subspace_id != gas_t->access_width) {
812 					pr_debug("Mismatched PCC ids in _CPC for CPU:%d\n",
813 						 pr->id);
814 					goto out_free;
815 				}
816 			} else if (gas_t->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
817 				if (gas_t->address) {
818 					void __iomem *addr;
819 					size_t access_width;
820 
821 					if (!osc_cpc_flexible_adr_space_confirmed) {
822 						pr_debug("Flexible address space capability not supported\n");
823 						if (!cpc_supported_by_cpu())
824 							goto out_free;
825 					}
826 
827 					access_width = GET_BIT_WIDTH(gas_t) / 8;
828 					addr = ioremap(gas_t->address, access_width);
829 					if (!addr)
830 						goto out_free;
831 					cpc_ptr->cpc_regs[i-2].sys_mem_vaddr = addr;
832 				}
833 			} else if (gas_t->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
834 				if (gas_t->access_width < 1 || gas_t->access_width > 3) {
835 					/*
836 					 * 1 = 8-bit, 2 = 16-bit, and 3 = 32-bit.
837 					 * SystemIO doesn't implement 64-bit
838 					 * registers.
839 					 */
840 					pr_debug("Invalid access width %d for SystemIO register in _CPC\n",
841 						 gas_t->access_width);
842 					goto out_free;
843 				}
844 				if (gas_t->address & OVER_16BTS_MASK) {
845 					/* SystemIO registers use 16-bit integer addresses */
846 					pr_debug("Invalid IO port %llu for SystemIO register in _CPC\n",
847 						 gas_t->address);
848 					goto out_free;
849 				}
850 				if (!osc_cpc_flexible_adr_space_confirmed) {
851 					pr_debug("Flexible address space capability not supported\n");
852 					if (!cpc_supported_by_cpu())
853 						goto out_free;
854 				}
855 			} else {
856 				if (gas_t->space_id != ACPI_ADR_SPACE_FIXED_HARDWARE || !cpc_ffh_supported()) {
857 					/* Support only PCC, SystemMemory, SystemIO, and FFH type regs. */
858 					pr_debug("Unsupported register type (%d) in _CPC\n",
859 						 gas_t->space_id);
860 					goto out_free;
861 				}
862 			}
863 
864 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_BUFFER;
865 			memcpy(&cpc_ptr->cpc_regs[i-2].cpc_entry.reg, gas_t, sizeof(*gas_t));
866 		} else if (cpc_obj->type == ACPI_TYPE_PACKAGE && (i - 2) == RESOURCE_PRIORITY) {
867 			/*
868 			 * ACPI 6.6, s8.4.6.1.2.7 defines Resource Priority as a
869 			 * Package of Resource Priority Register Descriptor sub-packages.
870 			 * Parsing the full structure is not yet supported.
871 			 * Mark the register as unsupported for now.
872 			 */
873 			pr_debug("CPU:%d Resource Priority not supported\n", pr->id);
874 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_INTEGER;
875 			cpc_ptr->cpc_regs[i-2].cpc_entry.int_value = 0;
876 		} else {
877 			pr_debug("Invalid entry type (%d) in _CPC for CPU:%d\n",
878 				 i, pr->id);
879 			goto out_free;
880 		}
881 	}
882 	per_cpu(cpu_pcc_subspace_idx, pr->id) = pcc_subspace_id;
883 
884 	/*
885 	 * In CPPC v1, DESIRED_PERF is mandatory. In CPPC v2, it is optional
886 	 * only when AUTO_SEL_ENABLE is supported.
887 	 */
888 	if (!CPC_SUPPORTED(&cpc_ptr->cpc_regs[DESIRED_PERF]) &&
889 	    (!osc_sb_cppc2_support_acked ||
890 	     !CPC_SUPPORTED(&cpc_ptr->cpc_regs[AUTO_SEL_ENABLE])))
891 		pr_warn("Desired perf. register is mandatory if CPPC v2 is not supported "
892 			"or autonomous selection is disabled\n");
893 
894 	/*
895 	 * Initialize the remaining cpc_regs as unsupported.
896 	 * Example: In case FW exposes CPPC v2, the below loop will initialize
897 	 * LOWEST_FREQ and NOMINAL_FREQ regs as unsupported
898 	 */
899 	for (i = num_ent - 2; i < MAX_CPC_REG_ENT; i++) {
900 		cpc_ptr->cpc_regs[i].type = ACPI_TYPE_INTEGER;
901 		cpc_ptr->cpc_regs[i].cpc_entry.int_value = 0;
902 	}
903 
904 
905 	/* Store CPU Logical ID */
906 	cpc_ptr->cpu_id = pr->id;
907 	raw_spin_lock_init(&cpc_ptr->rmw_lock);
908 
909 	/* Parse PSD data for this CPU */
910 	ret = acpi_get_psd(cpc_ptr, handle);
911 	if (ret)
912 		goto out_free;
913 
914 	/* Register PCC channel once for all PCC subspace ID. */
915 	if (pcc_subspace_id >= 0 && !pcc_data[pcc_subspace_id]->pcc_channel_acquired) {
916 		ret = register_pcc_channel(pcc_subspace_id);
917 		if (ret)
918 			goto out_free;
919 
920 		init_rwsem(&pcc_data[pcc_subspace_id]->pcc_lock);
921 		init_waitqueue_head(&pcc_data[pcc_subspace_id]->pcc_write_wait_q);
922 	}
923 
924 	/* Everything looks okay */
925 	pr_debug("Parsed CPC struct for CPU: %d\n", pr->id);
926 
927 	/* Add per logical CPU nodes for reading its feedback counters. */
928 	cpu_dev = get_cpu_device(pr->id);
929 	if (!cpu_dev) {
930 		ret = -EINVAL;
931 		goto out_free;
932 	}
933 
934 	/* Plug PSD data into this CPU's CPC descriptor. */
935 	per_cpu(cpc_desc_ptr, pr->id) = cpc_ptr;
936 
937 	ret = kobject_init_and_add(&cpc_ptr->kobj, &cppc_ktype, &cpu_dev->kobj,
938 			"acpi_cppc");
939 	if (ret) {
940 		per_cpu(cpc_desc_ptr, pr->id) = NULL;
941 		kobject_put(&cpc_ptr->kobj);
942 		goto out_free;
943 	}
944 
945 	kfree(output.pointer);
946 	return 0;
947 
948 out_free:
949 	/* Free all the mapped sys mem areas for this CPU */
950 	for (i = 2; i < cpc_ptr->num_entries; i++) {
951 		void __iomem *addr = cpc_ptr->cpc_regs[i-2].sys_mem_vaddr;
952 
953 		if (addr)
954 			iounmap(addr);
955 	}
956 	kfree(cpc_ptr);
957 
958 out_buf_free:
959 	kfree(output.pointer);
960 	return ret;
961 }
962 EXPORT_SYMBOL_GPL(acpi_cppc_processor_probe);
963 
964 /**
965  * acpi_cppc_processor_exit - Cleanup CPC structs.
966  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
967  *
968  * Return: Void
969  */
970 void acpi_cppc_processor_exit(struct acpi_processor *pr)
971 {
972 	struct cpc_desc *cpc_ptr;
973 	unsigned int i;
974 	void __iomem *addr;
975 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, pr->id);
976 
977 	if (pcc_ss_id >= 0 && pcc_data[pcc_ss_id]) {
978 		if (pcc_data[pcc_ss_id]->pcc_channel_acquired) {
979 			pcc_data[pcc_ss_id]->refcount--;
980 			if (!pcc_data[pcc_ss_id]->refcount) {
981 				pcc_mbox_free_channel(pcc_data[pcc_ss_id]->pcc_channel);
982 				kfree(pcc_data[pcc_ss_id]);
983 				pcc_data[pcc_ss_id] = NULL;
984 			}
985 		}
986 	}
987 
988 	cpc_ptr = per_cpu(cpc_desc_ptr, pr->id);
989 	if (!cpc_ptr)
990 		return;
991 
992 	/* Free all the mapped sys mem areas for this CPU */
993 	for (i = 2; i < cpc_ptr->num_entries; i++) {
994 		addr = cpc_ptr->cpc_regs[i-2].sys_mem_vaddr;
995 		if (addr)
996 			iounmap(addr);
997 	}
998 
999 	kobject_put(&cpc_ptr->kobj);
1000 	kfree(cpc_ptr);
1001 }
1002 EXPORT_SYMBOL_GPL(acpi_cppc_processor_exit);
1003 
1004 /**
1005  * cpc_read_ffh() - Read FFH register
1006  * @cpunum:	CPU number to read
1007  * @reg:	cppc register information
1008  * @val:	place holder for return value
1009  *
1010  * Read bit_width bits from a specified address and bit_offset
1011  *
1012  * Return: 0 for success and error code
1013  */
1014 int __weak cpc_read_ffh(int cpunum, struct cpc_reg *reg, u64 *val)
1015 {
1016 	return -ENOTSUPP;
1017 }
1018 
1019 /**
1020  * cpc_write_ffh() - Write FFH register
1021  * @cpunum:	CPU number to write
1022  * @reg:	cppc register information
1023  * @val:	value to write
1024  *
1025  * Write value of bit_width bits to a specified address and bit_offset
1026  *
1027  * Return: 0 for success and error code
1028  */
1029 int __weak cpc_write_ffh(int cpunum, struct cpc_reg *reg, u64 val)
1030 {
1031 	return -ENOTSUPP;
1032 }
1033 
1034 /*
1035  * Since cpc_read and cpc_write are called while holding pcc_lock, it should be
1036  * as fast as possible. We have already mapped the PCC subspace during init, so
1037  * we can directly write to it.
1038  */
1039 
1040 static int cpc_read(int cpu, struct cpc_register_resource *reg_res, u64 *val)
1041 {
1042 	void __iomem *vaddr = NULL;
1043 	int size;
1044 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1045 	struct cpc_reg *reg = &reg_res->cpc_entry.reg;
1046 
1047 	if (reg_res->type == ACPI_TYPE_INTEGER) {
1048 		*val = reg_res->cpc_entry.int_value;
1049 		return 0;
1050 	}
1051 
1052 	*val = 0;
1053 	size = GET_BIT_WIDTH(reg);
1054 
1055 	if (IS_ENABLED(CONFIG_HAS_IOPORT) &&
1056 	    reg->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
1057 		u32 val_u32;
1058 		acpi_status status;
1059 
1060 		status = acpi_os_read_port((acpi_io_address)reg->address,
1061 					   &val_u32, size);
1062 		if (ACPI_FAILURE(status)) {
1063 			pr_debug("Error: Failed to read SystemIO port %llx\n",
1064 				 reg->address);
1065 			return -EFAULT;
1066 		}
1067 
1068 		*val = val_u32;
1069 		return 0;
1070 	} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM && pcc_ss_id >= 0) {
1071 		/*
1072 		 * For registers in PCC space, the register size is determined
1073 		 * by the bit width field; the access size is used to indicate
1074 		 * the PCC subspace id.
1075 		 */
1076 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
1077 	}
1078 	else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
1079 		vaddr = reg_res->sys_mem_vaddr;
1080 	else if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
1081 		return cpc_read_ffh(cpu, reg, val);
1082 	else
1083 		return acpi_os_read_memory((acpi_physical_address)reg->address,
1084 				val, size);
1085 
1086 	switch (size) {
1087 	case 8:
1088 		*val = readb_relaxed(vaddr);
1089 		break;
1090 	case 16:
1091 		*val = readw_relaxed(vaddr);
1092 		break;
1093 	case 32:
1094 		*val = readl_relaxed(vaddr);
1095 		break;
1096 	case 64:
1097 		*val = readq_relaxed(vaddr);
1098 		break;
1099 	default:
1100 		if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
1101 			pr_debug("Error: Cannot read %u bit width from system memory: 0x%llx\n",
1102 				size, reg->address);
1103 		} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
1104 			pr_debug("Error: Cannot read %u bit width from PCC for ss: %d\n",
1105 				size, pcc_ss_id);
1106 		}
1107 		return -EFAULT;
1108 	}
1109 
1110 	if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
1111 		*val = MASK_VAL_READ(reg, *val);
1112 
1113 	return 0;
1114 }
1115 
1116 static int cpc_write(int cpu, struct cpc_register_resource *reg_res, u64 val)
1117 {
1118 	int ret_val = 0;
1119 	int size;
1120 	u64 prev_val;
1121 	void __iomem *vaddr = NULL;
1122 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1123 	struct cpc_reg *reg = &reg_res->cpc_entry.reg;
1124 	struct cpc_desc *cpc_desc;
1125 	unsigned long flags;
1126 
1127 	size = GET_BIT_WIDTH(reg);
1128 
1129 	if (IS_ENABLED(CONFIG_HAS_IOPORT) &&
1130 	    reg->space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
1131 		acpi_status status;
1132 
1133 		status = acpi_os_write_port((acpi_io_address)reg->address,
1134 					    (u32)val, size);
1135 		if (ACPI_FAILURE(status)) {
1136 			pr_debug("Error: Failed to write SystemIO port %llx\n",
1137 				 reg->address);
1138 			return -EFAULT;
1139 		}
1140 
1141 		return 0;
1142 	} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM && pcc_ss_id >= 0) {
1143 		/*
1144 		 * For registers in PCC space, the register size is determined
1145 		 * by the bit width field; the access size is used to indicate
1146 		 * the PCC subspace id.
1147 		 */
1148 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
1149 	}
1150 	else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
1151 		vaddr = reg_res->sys_mem_vaddr;
1152 	else if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
1153 		return cpc_write_ffh(cpu, reg, val);
1154 	else
1155 		return acpi_os_write_memory((acpi_physical_address)reg->address,
1156 				val, size);
1157 
1158 	if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
1159 		cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1160 		if (!cpc_desc) {
1161 			pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1162 			return -ENODEV;
1163 		}
1164 
1165 		raw_spin_lock_irqsave(&cpc_desc->rmw_lock, flags);
1166 		switch (size) {
1167 		case 8:
1168 			prev_val = readb_relaxed(vaddr);
1169 			break;
1170 		case 16:
1171 			prev_val = readw_relaxed(vaddr);
1172 			break;
1173 		case 32:
1174 			prev_val = readl_relaxed(vaddr);
1175 			break;
1176 		case 64:
1177 			prev_val = readq_relaxed(vaddr);
1178 			break;
1179 		default:
1180 			raw_spin_unlock_irqrestore(&cpc_desc->rmw_lock, flags);
1181 			return -EFAULT;
1182 		}
1183 		val = MASK_VAL_WRITE(reg, prev_val, val);
1184 	}
1185 
1186 	switch (size) {
1187 	case 8:
1188 		writeb_relaxed(val, vaddr);
1189 		break;
1190 	case 16:
1191 		writew_relaxed(val, vaddr);
1192 		break;
1193 	case 32:
1194 		writel_relaxed(val, vaddr);
1195 		break;
1196 	case 64:
1197 		writeq_relaxed(val, vaddr);
1198 		break;
1199 	default:
1200 		if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
1201 			pr_debug("Error: Cannot write %u bit width to system memory: 0x%llx\n",
1202 				size, reg->address);
1203 		} else if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
1204 			pr_debug("Error: Cannot write %u bit width to PCC for ss: %d\n",
1205 				size, pcc_ss_id);
1206 		}
1207 		ret_val = -EFAULT;
1208 		break;
1209 	}
1210 
1211 	if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
1212 		raw_spin_unlock_irqrestore(&cpc_desc->rmw_lock, flags);
1213 
1214 	return ret_val;
1215 }
1216 
1217 static int cppc_get_reg_val_in_pcc(int cpu, struct cpc_register_resource *reg, u64 *val)
1218 {
1219 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1220 	struct cppc_pcc_data *pcc_ss_data = NULL;
1221 	int ret;
1222 
1223 	if (pcc_ss_id < 0) {
1224 		pr_debug("Invalid pcc_ss_id\n");
1225 		return -ENODEV;
1226 	}
1227 
1228 	pcc_ss_data = pcc_data[pcc_ss_id];
1229 
1230 	down_write(&pcc_ss_data->pcc_lock);
1231 
1232 	if (send_pcc_cmd(pcc_ss_id, CMD_READ) >= 0)
1233 		ret = cpc_read(cpu, reg, val);
1234 	else
1235 		ret = -EIO;
1236 
1237 	up_write(&pcc_ss_data->pcc_lock);
1238 
1239 	return ret;
1240 }
1241 
1242 static int cppc_get_reg_val(int cpu, enum cppc_regs reg_idx, u64 *val)
1243 {
1244 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1245 	struct cpc_register_resource *reg;
1246 
1247 	if (val == NULL)
1248 		return -EINVAL;
1249 
1250 	if (!cpc_desc) {
1251 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1252 		return -ENODEV;
1253 	}
1254 
1255 	reg = &cpc_desc->cpc_regs[reg_idx];
1256 
1257 	if ((reg->type == ACPI_TYPE_INTEGER && IS_OPTIONAL_CPC_REG(reg_idx) &&
1258 	     !reg->cpc_entry.int_value) || (reg->type != ACPI_TYPE_INTEGER &&
1259 	     IS_NULL_REG(&reg->cpc_entry.reg))) {
1260 		pr_debug("CPC register is not supported\n");
1261 		return -EOPNOTSUPP;
1262 	}
1263 
1264 	if (CPC_IN_PCC(reg))
1265 		return cppc_get_reg_val_in_pcc(cpu, reg, val);
1266 
1267 	return cpc_read(cpu, reg, val);
1268 }
1269 
1270 static int cppc_set_reg_val_in_pcc(int cpu, struct cpc_register_resource *reg, u64 val)
1271 {
1272 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1273 	struct cppc_pcc_data *pcc_ss_data = NULL;
1274 	int ret;
1275 
1276 	if (pcc_ss_id < 0) {
1277 		pr_debug("Invalid pcc_ss_id\n");
1278 		return -ENODEV;
1279 	}
1280 
1281 	ret = cpc_write(cpu, reg, val);
1282 	if (ret)
1283 		return ret;
1284 
1285 	pcc_ss_data = pcc_data[pcc_ss_id];
1286 
1287 	down_write(&pcc_ss_data->pcc_lock);
1288 	/* after writing CPC, transfer the ownership of PCC to platform */
1289 	ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
1290 	up_write(&pcc_ss_data->pcc_lock);
1291 
1292 	return ret;
1293 }
1294 
1295 static int cppc_set_reg_val(int cpu, enum cppc_regs reg_idx, u64 val)
1296 {
1297 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1298 	struct cpc_register_resource *reg;
1299 
1300 	if (!cpc_desc) {
1301 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1302 		return -ENODEV;
1303 	}
1304 
1305 	reg = &cpc_desc->cpc_regs[reg_idx];
1306 
1307 	/* if a register is writeable, it must be a buffer and not null */
1308 	if ((reg->type != ACPI_TYPE_BUFFER) || IS_NULL_REG(&reg->cpc_entry.reg)) {
1309 		pr_debug("CPC register is not supported\n");
1310 		return -EOPNOTSUPP;
1311 	}
1312 
1313 	if (CPC_IN_PCC(reg))
1314 		return cppc_set_reg_val_in_pcc(cpu, reg, val);
1315 
1316 	return cpc_write(cpu, reg, val);
1317 }
1318 
1319 /**
1320  * cppc_get_desired_perf - Get the desired performance register value.
1321  * @cpunum: CPU from which to get desired performance.
1322  * @desired_perf: Return address.
1323  *
1324  * Return: 0 for success, -EIO otherwise.
1325  */
1326 int cppc_get_desired_perf(int cpunum, u64 *desired_perf)
1327 {
1328 	return cppc_get_reg_val(cpunum, DESIRED_PERF, desired_perf);
1329 }
1330 EXPORT_SYMBOL_GPL(cppc_get_desired_perf);
1331 
1332 /**
1333  * cppc_get_nominal_perf - Get the nominal performance register value.
1334  * @cpunum: CPU from which to get nominal performance.
1335  * @nominal_perf: Return address.
1336  *
1337  * Return: 0 for success, -EIO otherwise.
1338  */
1339 int cppc_get_nominal_perf(int cpunum, u64 *nominal_perf)
1340 {
1341 	return cppc_get_reg_val(cpunum, NOMINAL_PERF, nominal_perf);
1342 }
1343 
1344 /**
1345  * cppc_get_highest_perf - Get the highest performance register value.
1346  * @cpunum: CPU from which to get highest performance.
1347  * @highest_perf: Return address.
1348  *
1349  * Return: 0 for success, -EIO otherwise.
1350  */
1351 int cppc_get_highest_perf(int cpunum, u64 *highest_perf)
1352 {
1353 	return cppc_get_reg_val(cpunum, HIGHEST_PERF, highest_perf);
1354 }
1355 EXPORT_SYMBOL_GPL(cppc_get_highest_perf);
1356 
1357 /**
1358  * cppc_get_epp_perf - Get the epp register value.
1359  * @cpunum: CPU from which to get epp preference value.
1360  * @epp_perf: Return address.
1361  *
1362  * Return: 0 for success, -EIO otherwise.
1363  */
1364 int cppc_get_epp_perf(int cpunum, u64 *epp_perf)
1365 {
1366 	return cppc_get_reg_val(cpunum, ENERGY_PERF, epp_perf);
1367 }
1368 EXPORT_SYMBOL_GPL(cppc_get_epp_perf);
1369 
1370 /**
1371  * cppc_get_perf_caps - Get a CPU's performance capabilities.
1372  * @cpunum: CPU from which to get capabilities info.
1373  * @perf_caps: ptr to cppc_perf_caps. See cppc_acpi.h
1374  *
1375  * Return: 0 for success with perf_caps populated else -ERRNO.
1376  */
1377 int cppc_get_perf_caps(int cpunum, struct cppc_perf_caps *perf_caps)
1378 {
1379 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
1380 	struct cpc_register_resource *highest_reg, *lowest_reg,
1381 		*lowest_non_linear_reg, *nominal_reg, *reference_reg,
1382 		*guaranteed_reg, *low_freq_reg = NULL, *nom_freq_reg = NULL;
1383 	u64 high, low, guaranteed, nom, ref, min_nonlinear,
1384 	    low_f = 0, nom_f = 0;
1385 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
1386 	struct cppc_pcc_data *pcc_ss_data = NULL;
1387 	int ret = 0, regs_in_pcc = 0;
1388 
1389 	if (!cpc_desc) {
1390 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
1391 		return -ENODEV;
1392 	}
1393 
1394 	highest_reg = &cpc_desc->cpc_regs[HIGHEST_PERF];
1395 	lowest_reg = &cpc_desc->cpc_regs[LOWEST_PERF];
1396 	lowest_non_linear_reg = &cpc_desc->cpc_regs[LOW_NON_LINEAR_PERF];
1397 	nominal_reg = &cpc_desc->cpc_regs[NOMINAL_PERF];
1398 	reference_reg = &cpc_desc->cpc_regs[REFERENCE_PERF];
1399 	low_freq_reg = &cpc_desc->cpc_regs[LOWEST_FREQ];
1400 	nom_freq_reg = &cpc_desc->cpc_regs[NOMINAL_FREQ];
1401 	guaranteed_reg = &cpc_desc->cpc_regs[GUARANTEED_PERF];
1402 
1403 	/* Are any of the regs PCC ?*/
1404 	if (CPC_IN_PCC(highest_reg) || CPC_IN_PCC(lowest_reg) ||
1405 		CPC_IN_PCC(lowest_non_linear_reg) || CPC_IN_PCC(nominal_reg) ||
1406 		(CPC_SUPPORTED(reference_reg) && CPC_IN_PCC(reference_reg)) ||
1407 		CPC_IN_PCC(low_freq_reg) || CPC_IN_PCC(nom_freq_reg) ||
1408 		CPC_IN_PCC(guaranteed_reg)) {
1409 		if (pcc_ss_id < 0) {
1410 			pr_debug("Invalid pcc_ss_id\n");
1411 			return -ENODEV;
1412 		}
1413 		pcc_ss_data = pcc_data[pcc_ss_id];
1414 		regs_in_pcc = 1;
1415 		down_write(&pcc_ss_data->pcc_lock);
1416 		/* Ring doorbell once to update PCC subspace */
1417 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
1418 			ret = -EIO;
1419 			goto out_err;
1420 		}
1421 	}
1422 
1423 	ret = cpc_read(cpunum, highest_reg, &high);
1424 	if (ret)
1425 		goto out_err;
1426 	perf_caps->highest_perf = high;
1427 
1428 	ret = cpc_read(cpunum, lowest_reg, &low);
1429 	if (ret)
1430 		goto out_err;
1431 	perf_caps->lowest_perf = low;
1432 
1433 	ret = cpc_read(cpunum, nominal_reg, &nom);
1434 	if (ret)
1435 		goto out_err;
1436 	perf_caps->nominal_perf = nom;
1437 
1438 	/*
1439 	 * If reference perf register is not supported then we should
1440 	 * use the nominal perf value
1441 	 */
1442 	if (CPC_SUPPORTED(reference_reg)) {
1443 		ret = cpc_read(cpunum, reference_reg, &ref);
1444 		if (ret)
1445 			goto out_err;
1446 	} else {
1447 		ref = nom;
1448 	}
1449 	perf_caps->reference_perf = ref;
1450 
1451 	if (guaranteed_reg->type != ACPI_TYPE_BUFFER  ||
1452 	    IS_NULL_REG(&guaranteed_reg->cpc_entry.reg)) {
1453 		perf_caps->guaranteed_perf = 0;
1454 	} else {
1455 		ret = cpc_read(cpunum, guaranteed_reg, &guaranteed);
1456 		if (ret)
1457 			goto out_err;
1458 		perf_caps->guaranteed_perf = guaranteed;
1459 	}
1460 
1461 	ret = cpc_read(cpunum, lowest_non_linear_reg, &min_nonlinear);
1462 	if (ret)
1463 		goto out_err;
1464 	perf_caps->lowest_nonlinear_perf = min_nonlinear;
1465 
1466 	if (!high || !low || !nom || !ref || !min_nonlinear) {
1467 		ret = -EFAULT;
1468 		goto out_err;
1469 	}
1470 
1471 	/* Read optional lowest and nominal frequencies if present */
1472 	if (CPC_SUPPORTED(low_freq_reg)) {
1473 		ret = cpc_read(cpunum, low_freq_reg, &low_f);
1474 		if (ret)
1475 			goto out_err;
1476 	}
1477 
1478 	if (CPC_SUPPORTED(nom_freq_reg)) {
1479 		ret = cpc_read(cpunum, nom_freq_reg, &nom_f);
1480 		if (ret)
1481 			goto out_err;
1482 	}
1483 
1484 	perf_caps->lowest_freq = low_f;
1485 	perf_caps->nominal_freq = nom_f;
1486 
1487 
1488 out_err:
1489 	if (regs_in_pcc)
1490 		up_write(&pcc_ss_data->pcc_lock);
1491 	return ret;
1492 }
1493 EXPORT_SYMBOL_GPL(cppc_get_perf_caps);
1494 
1495 /**
1496  * cppc_perf_ctrs_in_pcc_cpu - Check if any perf counters of a CPU are in PCC.
1497  * @cpu: CPU on which to check perf counters.
1498  *
1499  * Return: true if any of the counters are in PCC regions, false otherwise
1500  */
1501 bool cppc_perf_ctrs_in_pcc_cpu(unsigned int cpu)
1502 {
1503 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1504 
1505 	return CPC_IN_PCC(&cpc_desc->cpc_regs[DELIVERED_CTR]) ||
1506 		CPC_IN_PCC(&cpc_desc->cpc_regs[REFERENCE_CTR]) ||
1507 		CPC_IN_PCC(&cpc_desc->cpc_regs[CTR_WRAP_TIME]);
1508 }
1509 EXPORT_SYMBOL_GPL(cppc_perf_ctrs_in_pcc_cpu);
1510 
1511 /**
1512  * cppc_perf_ctrs_in_pcc - Check if any perf counters are in a PCC region.
1513  *
1514  * CPPC has flexibility about how CPU performance counters are accessed.
1515  * One of the choices is PCC regions, which can have a high access latency. This
1516  * routine allows callers of cppc_get_perf_ctrs() to know this ahead of time.
1517  *
1518  * Return: true if any of the counters are in PCC regions, false otherwise
1519  */
1520 bool cppc_perf_ctrs_in_pcc(void)
1521 {
1522 	int cpu;
1523 
1524 	for_each_online_cpu(cpu) {
1525 		if (cppc_perf_ctrs_in_pcc_cpu(cpu))
1526 			return true;
1527 	}
1528 
1529 	return false;
1530 }
1531 EXPORT_SYMBOL_GPL(cppc_perf_ctrs_in_pcc);
1532 
1533 /**
1534  * cppc_get_perf_ctrs - Read a CPU's performance feedback counters.
1535  * @cpunum: CPU from which to read counters.
1536  * @perf_fb_ctrs: ptr to cppc_perf_fb_ctrs. See cppc_acpi.h
1537  *
1538  * Return: 0 for success with perf_fb_ctrs populated else -ERRNO.
1539  */
1540 int cppc_get_perf_ctrs(int cpunum, struct cppc_perf_fb_ctrs *perf_fb_ctrs)
1541 {
1542 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
1543 	struct cpc_register_resource *delivered_reg, *reference_reg,
1544 		*ctr_wrap_reg;
1545 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
1546 	struct cppc_pcc_data *pcc_ss_data = NULL;
1547 	u64 delivered, reference, ctr_wrap_time;
1548 	int ret = 0, regs_in_pcc = 0;
1549 
1550 	if (!cpc_desc) {
1551 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
1552 		return -ENODEV;
1553 	}
1554 
1555 	delivered_reg = &cpc_desc->cpc_regs[DELIVERED_CTR];
1556 	reference_reg = &cpc_desc->cpc_regs[REFERENCE_CTR];
1557 	ctr_wrap_reg = &cpc_desc->cpc_regs[CTR_WRAP_TIME];
1558 
1559 	/* Are any of the regs PCC ?*/
1560 	if (CPC_IN_PCC(delivered_reg) || CPC_IN_PCC(reference_reg) ||
1561 		CPC_IN_PCC(ctr_wrap_reg)) {
1562 		if (pcc_ss_id < 0) {
1563 			pr_debug("Invalid pcc_ss_id\n");
1564 			return -ENODEV;
1565 		}
1566 		pcc_ss_data = pcc_data[pcc_ss_id];
1567 		down_write(&pcc_ss_data->pcc_lock);
1568 		regs_in_pcc = 1;
1569 		/* Ring doorbell once to update PCC subspace */
1570 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
1571 			ret = -EIO;
1572 			goto out_err;
1573 		}
1574 	}
1575 
1576 	ret = cpc_read(cpunum, delivered_reg, &delivered);
1577 	if (ret)
1578 		goto out_err;
1579 
1580 	ret = cpc_read(cpunum, reference_reg, &reference);
1581 	if (ret)
1582 		goto out_err;
1583 
1584 	/*
1585 	 * Per spec, if ctr_wrap_time optional register is unsupported, then the
1586 	 * performance counters are assumed to never wrap during the lifetime of
1587 	 * platform
1588 	 */
1589 	ctr_wrap_time = (u64)(~((u64)0));
1590 	if (CPC_SUPPORTED(ctr_wrap_reg)) {
1591 		ret = cpc_read(cpunum, ctr_wrap_reg, &ctr_wrap_time);
1592 		if (ret)
1593 			goto out_err;
1594 	}
1595 
1596 	if (!delivered || !reference) {
1597 		ret = -EFAULT;
1598 		goto out_err;
1599 	}
1600 
1601 	perf_fb_ctrs->delivered = delivered;
1602 	perf_fb_ctrs->reference = reference;
1603 	perf_fb_ctrs->wraparound_time = ctr_wrap_time;
1604 out_err:
1605 	if (regs_in_pcc)
1606 		up_write(&pcc_ss_data->pcc_lock);
1607 	return ret;
1608 }
1609 EXPORT_SYMBOL_GPL(cppc_get_perf_ctrs);
1610 
1611 /*
1612  * Set Energy Performance Preference Register value through
1613  * Performance Controls Interface
1614  */
1615 int cppc_set_epp_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls, bool enable)
1616 {
1617 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1618 	struct cpc_register_resource *epp_set_reg;
1619 	struct cpc_register_resource *auto_sel_reg;
1620 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1621 	struct cppc_pcc_data *pcc_ss_data = NULL;
1622 	bool autosel_ffh_sysmem;
1623 	bool epp_ffh_sysmem;
1624 	int ret;
1625 
1626 	if (!cpc_desc) {
1627 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1628 		return -ENODEV;
1629 	}
1630 
1631 	auto_sel_reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
1632 	epp_set_reg = &cpc_desc->cpc_regs[ENERGY_PERF];
1633 
1634 	epp_ffh_sysmem = CPC_SUPPORTED(epp_set_reg) &&
1635 		(CPC_IN_FFH(epp_set_reg) || CPC_IN_SYSTEM_MEMORY(epp_set_reg));
1636 	autosel_ffh_sysmem = CPC_SUPPORTED(auto_sel_reg) &&
1637 		(CPC_IN_FFH(auto_sel_reg) || CPC_IN_SYSTEM_MEMORY(auto_sel_reg));
1638 
1639 	if (CPC_IN_PCC(epp_set_reg) || CPC_IN_PCC(auto_sel_reg)) {
1640 		if (pcc_ss_id < 0) {
1641 			pr_debug("Invalid pcc_ss_id for CPU:%d\n", cpu);
1642 			return -ENODEV;
1643 		}
1644 
1645 		if (CPC_SUPPORTED(auto_sel_reg)) {
1646 			ret = cpc_write(cpu, auto_sel_reg, enable);
1647 			if (ret)
1648 				return ret;
1649 		}
1650 
1651 		if (CPC_SUPPORTED(epp_set_reg)) {
1652 			ret = cpc_write(cpu, epp_set_reg, perf_ctrls->energy_perf);
1653 			if (ret)
1654 				return ret;
1655 		}
1656 
1657 		pcc_ss_data = pcc_data[pcc_ss_id];
1658 
1659 		down_write(&pcc_ss_data->pcc_lock);
1660 		/* after writing CPC, transfer the ownership of PCC to platform */
1661 		ret = send_pcc_cmd(pcc_ss_id, CMD_WRITE);
1662 		up_write(&pcc_ss_data->pcc_lock);
1663 	} else if (osc_cpc_flexible_adr_space_confirmed &&
1664 		   (epp_ffh_sysmem || autosel_ffh_sysmem)) {
1665 		if (autosel_ffh_sysmem) {
1666 			ret = cpc_write(cpu, auto_sel_reg, enable);
1667 			if (ret)
1668 				return ret;
1669 		}
1670 
1671 		if (epp_ffh_sysmem) {
1672 			ret = cpc_write(cpu, epp_set_reg,
1673 					perf_ctrls->energy_perf);
1674 			if (ret)
1675 				return ret;
1676 		}
1677 	} else {
1678 		ret = -ENOTSUPP;
1679 		pr_debug("_CPC in PCC/FFH/SystemMemory are not supported\n");
1680 	}
1681 
1682 	return ret;
1683 }
1684 EXPORT_SYMBOL_GPL(cppc_set_epp_perf);
1685 
1686 /**
1687  * cppc_set_epp() - Write the EPP register.
1688  * @cpu: CPU on which to write register.
1689  * @epp_val: Value to write to the EPP register.
1690  */
1691 int cppc_set_epp(int cpu, u64 epp_val)
1692 {
1693 	if (epp_val > CPPC_EPP_ENERGY_EFFICIENCY_PREF)
1694 		return -EINVAL;
1695 
1696 	return cppc_set_reg_val(cpu, ENERGY_PERF, epp_val);
1697 }
1698 EXPORT_SYMBOL_GPL(cppc_set_epp);
1699 
1700 /**
1701  * cppc_get_auto_act_window() - Read autonomous activity window register.
1702  * @cpu: CPU from which to read register.
1703  * @auto_act_window: Return address.
1704  *
1705  * According to ACPI 6.5, s8.4.6.1.6, the value read from the autonomous
1706  * activity window register consists of two parts: a 7 bits value indicate
1707  * significand and a 3 bits value indicate exponent.
1708  */
1709 int cppc_get_auto_act_window(int cpu, u64 *auto_act_window)
1710 {
1711 	unsigned int exp;
1712 	u64 val, sig;
1713 	int ret;
1714 
1715 	if (auto_act_window == NULL)
1716 		return -EINVAL;
1717 
1718 	ret = cppc_get_reg_val(cpu, AUTO_ACT_WINDOW, &val);
1719 	if (ret)
1720 		return ret;
1721 
1722 	sig = val & CPPC_AUTO_ACT_WINDOW_MAX_SIG;
1723 	exp = (val >> CPPC_AUTO_ACT_WINDOW_SIG_BIT_SIZE) & CPPC_AUTO_ACT_WINDOW_MAX_EXP;
1724 	*auto_act_window = sig * int_pow(10, exp);
1725 
1726 	return 0;
1727 }
1728 EXPORT_SYMBOL_GPL(cppc_get_auto_act_window);
1729 
1730 /**
1731  * cppc_set_auto_act_window() - Write autonomous activity window register.
1732  * @cpu: CPU on which to write register.
1733  * @auto_act_window: usec value to write to the autonomous activity window register.
1734  *
1735  * According to ACPI 6.5, s8.4.6.1.6, the value to write to the autonomous
1736  * activity window register consists of two parts: a 7 bits value indicate
1737  * significand and a 3 bits value indicate exponent.
1738  */
1739 int cppc_set_auto_act_window(int cpu, u64 auto_act_window)
1740 {
1741 	/* The max value to store is 1270000000 */
1742 	u64 max_val = CPPC_AUTO_ACT_WINDOW_MAX_SIG * int_pow(10, CPPC_AUTO_ACT_WINDOW_MAX_EXP);
1743 	int exp = 0;
1744 	u64 val;
1745 
1746 	if (auto_act_window > max_val)
1747 		return -EINVAL;
1748 
1749 	/*
1750 	 * The max significand is 127, when auto_act_window is larger than
1751 	 * 129, discard the precision of the last digit and increase the
1752 	 * exponent by 1.
1753 	 */
1754 	while (auto_act_window > CPPC_AUTO_ACT_WINDOW_SIG_CARRY_THRESH) {
1755 		auto_act_window /= 10;
1756 		exp += 1;
1757 	}
1758 
1759 	/* For 128 and 129, cut it to 127. */
1760 	if (auto_act_window > CPPC_AUTO_ACT_WINDOW_MAX_SIG)
1761 		auto_act_window = CPPC_AUTO_ACT_WINDOW_MAX_SIG;
1762 
1763 	val = (exp << CPPC_AUTO_ACT_WINDOW_SIG_BIT_SIZE) + auto_act_window;
1764 
1765 	return cppc_set_reg_val(cpu, AUTO_ACT_WINDOW, val);
1766 }
1767 EXPORT_SYMBOL_GPL(cppc_set_auto_act_window);
1768 
1769 /**
1770  * cppc_get_auto_sel() - Read autonomous selection register.
1771  * @cpu: CPU from which to read register.
1772  * @enable: Return address.
1773  */
1774 int cppc_get_auto_sel(int cpu, bool *enable)
1775 {
1776 	u64 auto_sel;
1777 	int ret;
1778 
1779 	if (enable == NULL)
1780 		return -EINVAL;
1781 
1782 	ret = cppc_get_reg_val(cpu, AUTO_SEL_ENABLE, &auto_sel);
1783 	if (ret)
1784 		return ret;
1785 
1786 	*enable = (bool)auto_sel;
1787 
1788 	return 0;
1789 }
1790 EXPORT_SYMBOL_GPL(cppc_get_auto_sel);
1791 
1792 /**
1793  * cppc_set_auto_sel - Write autonomous selection register.
1794  * @cpu    : CPU to which to write register.
1795  * @enable : the desired value of autonomous selection resiter to be updated.
1796  */
1797 int cppc_set_auto_sel(int cpu, bool enable)
1798 {
1799 	return cppc_set_reg_val(cpu, AUTO_SEL_ENABLE, enable);
1800 }
1801 EXPORT_SYMBOL_GPL(cppc_set_auto_sel);
1802 
1803 /**
1804  * cppc_set_enable - Set to enable CPPC on the processor by writing the
1805  * Continuous Performance Control package EnableRegister field.
1806  * @cpu: CPU for which to enable CPPC register.
1807  * @enable: 0 - disable, 1 - enable CPPC feature on the processor.
1808  *
1809  * Return: 0 for success, -ERRNO or -EIO otherwise.
1810  */
1811 int cppc_set_enable(int cpu, bool enable)
1812 {
1813 	return cppc_set_reg_val(cpu, ENABLE, enable);
1814 }
1815 EXPORT_SYMBOL_GPL(cppc_set_enable);
1816 
1817 /**
1818  * cppc_get_perf - Get a CPU's performance controls.
1819  * @cpu: CPU for which to get performance controls.
1820  * @perf_ctrls: ptr to cppc_perf_ctrls. See cppc_acpi.h
1821  *
1822  * Return: 0 for success with perf_ctrls, -ERRNO otherwise.
1823  */
1824 int cppc_get_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls)
1825 {
1826 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1827 	struct cpc_register_resource *desired_perf_reg,
1828 				     *min_perf_reg, *max_perf_reg,
1829 				     *energy_perf_reg, *auto_sel_reg;
1830 	u64 desired_perf = 0, min = 0, max = 0, energy_perf = 0, auto_sel = 0;
1831 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1832 	struct cppc_pcc_data *pcc_ss_data = NULL;
1833 	int ret = 0, regs_in_pcc = 0;
1834 
1835 	if (!cpc_desc) {
1836 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1837 		return -ENODEV;
1838 	}
1839 
1840 	if (!perf_ctrls) {
1841 		pr_debug("Invalid perf_ctrls pointer\n");
1842 		return -EINVAL;
1843 	}
1844 
1845 	desired_perf_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
1846 	min_perf_reg = &cpc_desc->cpc_regs[MIN_PERF];
1847 	max_perf_reg = &cpc_desc->cpc_regs[MAX_PERF];
1848 	energy_perf_reg = &cpc_desc->cpc_regs[ENERGY_PERF];
1849 	auto_sel_reg = &cpc_desc->cpc_regs[AUTO_SEL_ENABLE];
1850 
1851 	/* Are any of the regs PCC ?*/
1852 	if (CPC_IN_PCC(desired_perf_reg) || CPC_IN_PCC(min_perf_reg) ||
1853 	    CPC_IN_PCC(max_perf_reg) || CPC_IN_PCC(energy_perf_reg) ||
1854 	    CPC_IN_PCC(auto_sel_reg)) {
1855 		if (pcc_ss_id < 0) {
1856 			pr_debug("Invalid pcc_ss_id for CPU:%d\n", cpu);
1857 			return -ENODEV;
1858 		}
1859 		pcc_ss_data = pcc_data[pcc_ss_id];
1860 		regs_in_pcc = 1;
1861 		down_write(&pcc_ss_data->pcc_lock);
1862 		/* Ring doorbell once to update PCC subspace */
1863 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
1864 			ret = -EIO;
1865 			goto out_err;
1866 		}
1867 	}
1868 
1869 	/* Read optional elements if present */
1870 	if (CPC_SUPPORTED(max_perf_reg)) {
1871 		ret = cpc_read(cpu, max_perf_reg, &max);
1872 		if (ret)
1873 			goto out_err;
1874 	}
1875 	perf_ctrls->max_perf = max;
1876 
1877 	if (CPC_SUPPORTED(min_perf_reg)) {
1878 		ret = cpc_read(cpu, min_perf_reg, &min);
1879 		if (ret)
1880 			goto out_err;
1881 	}
1882 	perf_ctrls->min_perf = min;
1883 
1884 	if (CPC_SUPPORTED(desired_perf_reg)) {
1885 		ret = cpc_read(cpu, desired_perf_reg, &desired_perf);
1886 		if (ret)
1887 			goto out_err;
1888 	}
1889 	perf_ctrls->desired_perf = desired_perf;
1890 
1891 	if (CPC_SUPPORTED(energy_perf_reg)) {
1892 		ret = cpc_read(cpu, energy_perf_reg, &energy_perf);
1893 		if (ret)
1894 			goto out_err;
1895 	}
1896 	perf_ctrls->energy_perf = energy_perf;
1897 
1898 	if (CPC_SUPPORTED(auto_sel_reg)) {
1899 		ret = cpc_read(cpu, auto_sel_reg, &auto_sel);
1900 		if (ret)
1901 			goto out_err;
1902 	}
1903 	perf_ctrls->auto_sel = (bool)auto_sel;
1904 
1905 out_err:
1906 	if (regs_in_pcc)
1907 		up_write(&pcc_ss_data->pcc_lock);
1908 	return ret;
1909 }
1910 EXPORT_SYMBOL_GPL(cppc_get_perf);
1911 
1912 /**
1913  * cppc_set_perf - Set a CPU's performance controls.
1914  * @cpu: CPU for which to set performance controls.
1915  * @perf_ctrls: ptr to cppc_perf_ctrls. See cppc_acpi.h
1916  *
1917  * Return: 0 for success, -ERRNO otherwise.
1918  */
1919 int cppc_set_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls)
1920 {
1921 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1922 	struct cpc_register_resource *desired_reg, *min_perf_reg, *max_perf_reg;
1923 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1924 	struct cppc_pcc_data *pcc_ss_data = NULL;
1925 	int ret = 0;
1926 
1927 	if (!cpc_desc) {
1928 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1929 		return -ENODEV;
1930 	}
1931 
1932 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
1933 	min_perf_reg = &cpc_desc->cpc_regs[MIN_PERF];
1934 	max_perf_reg = &cpc_desc->cpc_regs[MAX_PERF];
1935 
1936 	/*
1937 	 * This is Phase-I where we want to write to CPC registers
1938 	 * -> We want all CPUs to be able to execute this phase in parallel
1939 	 *
1940 	 * Since read_lock can be acquired by multiple CPUs simultaneously we
1941 	 * achieve that goal here
1942 	 */
1943 	if (CPC_IN_PCC(desired_reg) || CPC_IN_PCC(min_perf_reg) || CPC_IN_PCC(max_perf_reg)) {
1944 		if (pcc_ss_id < 0) {
1945 			pr_debug("Invalid pcc_ss_id\n");
1946 			return -ENODEV;
1947 		}
1948 		pcc_ss_data = pcc_data[pcc_ss_id];
1949 		down_read(&pcc_ss_data->pcc_lock); /* BEGIN Phase-I */
1950 		if (pcc_ss_data->platform_owns_pcc) {
1951 			ret = check_pcc_chan(pcc_ss_id, false);
1952 			if (ret) {
1953 				up_read(&pcc_ss_data->pcc_lock);
1954 				return ret;
1955 			}
1956 		}
1957 		/*
1958 		 * Update the pending_write to make sure a PCC CMD_READ will not
1959 		 * arrive and steal the channel during the switch to write lock
1960 		 */
1961 		pcc_ss_data->pending_pcc_write_cmd = true;
1962 		cpc_desc->write_cmd_id = pcc_ss_data->pcc_write_cnt;
1963 		cpc_desc->write_cmd_status = 0;
1964 	}
1965 
1966 	if (CPC_SUPPORTED(desired_reg))
1967 		cpc_write(cpu, desired_reg, perf_ctrls->desired_perf);
1968 
1969 	/*
1970 	 * Only write if min_perf and max_perf not zero. Some drivers pass zero
1971 	 * value to min and max perf, but they don't mean to set the zero value,
1972 	 * they just don't want to write to those registers.
1973 	 */
1974 	if (perf_ctrls->min_perf && CPC_SUPPORTED(min_perf_reg))
1975 		cpc_write(cpu, min_perf_reg, perf_ctrls->min_perf);
1976 	if (perf_ctrls->max_perf && CPC_SUPPORTED(max_perf_reg))
1977 		cpc_write(cpu, max_perf_reg, perf_ctrls->max_perf);
1978 
1979 	if (CPC_IN_PCC(desired_reg) || CPC_IN_PCC(min_perf_reg) || CPC_IN_PCC(max_perf_reg))
1980 		up_read(&pcc_ss_data->pcc_lock);	/* END Phase-I */
1981 	/*
1982 	 * This is Phase-II where we transfer the ownership of PCC to Platform
1983 	 *
1984 	 * Short Summary: Basically if we think of a group of cppc_set_perf
1985 	 * requests that happened in short overlapping interval. The last CPU to
1986 	 * come out of Phase-I will enter Phase-II and ring the doorbell.
1987 	 *
1988 	 * We have the following requirements for Phase-II:
1989 	 *     1. We want to execute Phase-II only when there are no CPUs
1990 	 * currently executing in Phase-I
1991 	 *     2. Once we start Phase-II we want to avoid all other CPUs from
1992 	 * entering Phase-I.
1993 	 *     3. We want only one CPU among all those who went through Phase-I
1994 	 * to run phase-II
1995 	 *
1996 	 * If write_trylock fails to get the lock and doesn't transfer the
1997 	 * PCC ownership to the platform, then one of the following will be TRUE
1998 	 *     1. There is at-least one CPU in Phase-I which will later execute
1999 	 * write_trylock, so the CPUs in Phase-I will be responsible for
2000 	 * executing the Phase-II.
2001 	 *     2. Some other CPU has beaten this CPU to successfully execute the
2002 	 * write_trylock and has already acquired the write_lock. We know for a
2003 	 * fact it (other CPU acquiring the write_lock) couldn't have happened
2004 	 * before this CPU's Phase-I as we held the read_lock.
2005 	 *     3. Some other CPU executing pcc CMD_READ has stolen the
2006 	 * down_write, in which case, send_pcc_cmd will check for pending
2007 	 * CMD_WRITE commands by checking the pending_pcc_write_cmd.
2008 	 * So this CPU can be certain that its request will be delivered
2009 	 *    So in all cases, this CPU knows that its request will be delivered
2010 	 * by another CPU and can return
2011 	 *
2012 	 * After getting the down_write we still need to check for
2013 	 * pending_pcc_write_cmd to take care of the following scenario
2014 	 *    The thread running this code could be scheduled out between
2015 	 * Phase-I and Phase-II. Before it is scheduled back on, another CPU
2016 	 * could have delivered the request to Platform by triggering the
2017 	 * doorbell and transferred the ownership of PCC to platform. So this
2018 	 * avoids triggering an unnecessary doorbell and more importantly before
2019 	 * triggering the doorbell it makes sure that the PCC channel ownership
2020 	 * is still with OSPM.
2021 	 *   pending_pcc_write_cmd can also be cleared by a different CPU, if
2022 	 * there was a pcc CMD_READ waiting on down_write and it steals the lock
2023 	 * before the pcc CMD_WRITE is completed. send_pcc_cmd checks for this
2024 	 * case during a CMD_READ and if there are pending writes it delivers
2025 	 * the write command before servicing the read command
2026 	 */
2027 	if (CPC_IN_PCC(desired_reg) || CPC_IN_PCC(min_perf_reg) || CPC_IN_PCC(max_perf_reg)) {
2028 		if (down_write_trylock(&pcc_ss_data->pcc_lock)) {/* BEGIN Phase-II */
2029 			/* Update only if there are pending write commands */
2030 			if (pcc_ss_data->pending_pcc_write_cmd)
2031 				send_pcc_cmd(pcc_ss_id, CMD_WRITE);
2032 			up_write(&pcc_ss_data->pcc_lock);	/* END Phase-II */
2033 		} else
2034 			/* Wait until pcc_write_cnt is updated by send_pcc_cmd */
2035 			wait_event(pcc_ss_data->pcc_write_wait_q,
2036 				   cpc_desc->write_cmd_id != pcc_ss_data->pcc_write_cnt);
2037 
2038 		/* send_pcc_cmd updates the status in case of failure */
2039 		ret = cpc_desc->write_cmd_status;
2040 	}
2041 	return ret;
2042 }
2043 EXPORT_SYMBOL_GPL(cppc_set_perf);
2044 
2045 /**
2046  * cppc_get_perf_limited - Get the Performance Limited register value.
2047  * @cpu: CPU from which to get Performance Limited register.
2048  * @perf_limited: Pointer to store the Performance Limited value.
2049  *
2050  * The returned value contains sticky status bits indicating platform-imposed
2051  * performance limitations.
2052  *
2053  * Return: 0 for success, -EIO on failure, -EOPNOTSUPP if not supported.
2054  */
2055 int cppc_get_perf_limited(int cpu, u64 *perf_limited)
2056 {
2057 	return cppc_get_reg_val(cpu, PERF_LIMITED, perf_limited);
2058 }
2059 EXPORT_SYMBOL_GPL(cppc_get_perf_limited);
2060 
2061 /**
2062  * cppc_set_perf_limited() - Clear bits in the Performance Limited register.
2063  * @cpu: CPU on which to write register.
2064  * @bits_to_clear: Bitmask of bits to clear in the perf_limited register.
2065  *
2066  * The Performance Limited register contains two sticky bits set by platform:
2067  *   - Bit 0 (Desired_Excursion): Set when delivered performance is constrained
2068  *     below desired performance. Not used when Autonomous Selection is enabled.
2069  *   - Bit 1 (Minimum_Excursion): Set when delivered performance is constrained
2070  *     below minimum performance.
2071  *
2072  * These bits are sticky and remain set until OSPM explicitly clears them.
2073  * This function only allows clearing bits (the platform sets them).
2074  *
2075  * Return: 0 for success, -EINVAL for invalid bits, -EIO on register
2076  *         access failure, -EOPNOTSUPP if not supported.
2077  */
2078 int cppc_set_perf_limited(int cpu, u64 bits_to_clear)
2079 {
2080 	u64 current_val, new_val;
2081 	int ret;
2082 
2083 	/* Only bits 0 and 1 are valid */
2084 	if (bits_to_clear & ~CPPC_PERF_LIMITED_MASK)
2085 		return -EINVAL;
2086 
2087 	if (!bits_to_clear)
2088 		return 0;
2089 
2090 	ret = cppc_get_perf_limited(cpu, &current_val);
2091 	if (ret)
2092 		return ret;
2093 
2094 	/* Clear the specified bits */
2095 	new_val = current_val & ~bits_to_clear;
2096 
2097 	return cppc_set_reg_val(cpu, PERF_LIMITED, new_val);
2098 }
2099 EXPORT_SYMBOL_GPL(cppc_set_perf_limited);
2100 
2101 /**
2102  * cppc_get_transition_latency - returns frequency transition latency in ns
2103  * @cpu_num: CPU number for per_cpu().
2104  *
2105  * ACPI CPPC does not explicitly specify how a platform can specify the
2106  * transition latency for performance change requests. The closest we have
2107  * is the timing information from the PCCT tables which provides the info
2108  * on the number and frequency of PCC commands the platform can handle.
2109  *
2110  * If desired_reg is in the SystemMemory or SystemIo ACPI address space,
2111  * then assume there is no latency.
2112  */
2113 int cppc_get_transition_latency(int cpu_num)
2114 {
2115 	/*
2116 	 * Expected transition latency is based on the PCCT timing values
2117 	 * Below are definition from ACPI spec:
2118 	 * pcc_nominal- Expected latency to process a command, in microseconds
2119 	 * pcc_mpar   - The maximum number of periodic requests that the subspace
2120 	 *              channel can support, reported in commands per minute. 0
2121 	 *              indicates no limitation.
2122 	 * pcc_mrtt   - The minimum amount of time that OSPM must wait after the
2123 	 *              completion of a command before issuing the next command,
2124 	 *              in microseconds.
2125 	 */
2126 	struct cpc_desc *cpc_desc;
2127 	struct cpc_register_resource *desired_reg;
2128 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu_num);
2129 	struct cppc_pcc_data *pcc_ss_data;
2130 	int latency_ns = 0;
2131 
2132 	cpc_desc = per_cpu(cpc_desc_ptr, cpu_num);
2133 	if (!cpc_desc)
2134 		return -ENODATA;
2135 
2136 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
2137 	if (CPC_IN_SYSTEM_MEMORY(desired_reg) || CPC_IN_SYSTEM_IO(desired_reg))
2138 		return 0;
2139 
2140 	if (!CPC_IN_PCC(desired_reg) || pcc_ss_id < 0)
2141 		return -ENODATA;
2142 
2143 	pcc_ss_data = pcc_data[pcc_ss_id];
2144 	if (pcc_ss_data->pcc_mpar)
2145 		latency_ns = 60 * (1000 * 1000 * 1000 / pcc_ss_data->pcc_mpar);
2146 
2147 	latency_ns = max_t(int, latency_ns, pcc_ss_data->pcc_nominal * 1000);
2148 	latency_ns = max_t(int, latency_ns, pcc_ss_data->pcc_mrtt * 1000);
2149 
2150 	return latency_ns;
2151 }
2152 EXPORT_SYMBOL_GPL(cppc_get_transition_latency);
2153 
2154 /* Minimum struct length needed for the DMI processor entry we want */
2155 #define DMI_ENTRY_PROCESSOR_MIN_LENGTH	48
2156 
2157 /* Offset in the DMI processor structure for the max frequency */
2158 #define DMI_PROCESSOR_MAX_SPEED		0x14
2159 
2160 /* Callback function used to retrieve the max frequency from DMI */
2161 static void cppc_find_dmi_mhz(const struct dmi_header *dm, void *private)
2162 {
2163 	const u8 *dmi_data = (const u8 *)dm;
2164 	u16 *mhz = (u16 *)private;
2165 
2166 	if (dm->type == DMI_ENTRY_PROCESSOR &&
2167 	    dm->length >= DMI_ENTRY_PROCESSOR_MIN_LENGTH) {
2168 		u16 val = (u16)get_unaligned((const u16 *)
2169 				(dmi_data + DMI_PROCESSOR_MAX_SPEED));
2170 		*mhz = umax(val, *mhz);
2171 	}
2172 }
2173 
2174 /* Look up the max frequency in DMI */
2175 u64 cppc_get_dmi_max_khz(void)
2176 {
2177 	u16 mhz = 0;
2178 
2179 	dmi_walk(cppc_find_dmi_mhz, &mhz);
2180 
2181 	/*
2182 	 * Real stupid fallback value, just in case there is no
2183 	 * actual value set.
2184 	 */
2185 	mhz = mhz ? mhz : 1;
2186 
2187 	return KHZ_PER_MHZ * mhz;
2188 }
2189 EXPORT_SYMBOL_GPL(cppc_get_dmi_max_khz);
2190 
2191 /*
2192  * If CPPC lowest_freq and nominal_freq registers are exposed then we can
2193  * use them to convert perf to freq and vice versa. The conversion is
2194  * extrapolated as an affine function passing by the 2 points:
2195  *  - (Low perf, Low freq)
2196  *  - (Nominal perf, Nominal freq)
2197  */
2198 unsigned int cppc_perf_to_khz(struct cppc_perf_caps *caps, unsigned int perf)
2199 {
2200 	s64 retval, offset = 0;
2201 	static u64 max_khz;
2202 	u64 mul, div;
2203 
2204 	if (caps->lowest_freq && caps->nominal_freq) {
2205 		/* Avoid special case when nominal_freq is equal to lowest_freq */
2206 		if (caps->lowest_freq == caps->nominal_freq) {
2207 			mul = caps->nominal_freq;
2208 			div = caps->nominal_perf;
2209 		} else {
2210 			mul = caps->nominal_freq - caps->lowest_freq;
2211 			div = caps->nominal_perf - caps->lowest_perf;
2212 		}
2213 		mul *= KHZ_PER_MHZ;
2214 		offset = caps->nominal_freq * KHZ_PER_MHZ -
2215 			 div64_u64(caps->nominal_perf * mul, div);
2216 	} else {
2217 		if (!max_khz)
2218 			max_khz = cppc_get_dmi_max_khz();
2219 		mul = max_khz;
2220 		div = caps->highest_perf;
2221 	}
2222 
2223 	retval = offset + div64_u64(perf * mul, div);
2224 	if (retval >= 0)
2225 		return retval;
2226 	return 0;
2227 }
2228 EXPORT_SYMBOL_GPL(cppc_perf_to_khz);
2229 
2230 unsigned int cppc_khz_to_perf(struct cppc_perf_caps *caps, unsigned int freq)
2231 {
2232 	s64 retval, offset = 0;
2233 	static u64 max_khz;
2234 	u64 mul, div;
2235 
2236 	if (caps->lowest_freq && caps->nominal_freq) {
2237 		/* Avoid special case when nominal_freq is equal to lowest_freq */
2238 		if (caps->lowest_freq == caps->nominal_freq) {
2239 			mul = caps->nominal_perf;
2240 			div = caps->nominal_freq;
2241 		} else {
2242 			mul = caps->nominal_perf - caps->lowest_perf;
2243 			div = caps->nominal_freq - caps->lowest_freq;
2244 		}
2245 		/*
2246 		 * We don't need to convert to kHz for computing offset and can
2247 		 * directly use nominal_freq and lowest_freq as the div64_u64
2248 		 * will remove the frequency unit.
2249 		 */
2250 		offset = caps->nominal_perf -
2251 			 div64_u64(caps->nominal_freq * mul, div);
2252 		/* But we need it for computing the perf level. */
2253 		div *= KHZ_PER_MHZ;
2254 	} else {
2255 		if (!max_khz)
2256 			max_khz = cppc_get_dmi_max_khz();
2257 		mul = caps->highest_perf;
2258 		div = max_khz;
2259 	}
2260 
2261 	retval = offset + div64_u64(freq * mul, div);
2262 	if (retval >= 0)
2263 		return retval;
2264 	return 0;
2265 }
2266 EXPORT_SYMBOL_GPL(cppc_khz_to_perf);
2267