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