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