• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 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 SystemMemory */
104 #define CPC_IN_SYSTEM_MEMORY(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
105 				(cpc)->cpc_entry.reg.space_id ==	\
106 				ACPI_ADR_SPACE_SYSTEM_MEMORY)
107 
108 /* Check if a CPC register is in SystemIo */
109 #define CPC_IN_SYSTEM_IO(cpc) ((cpc)->type == ACPI_TYPE_BUFFER &&	\
110 				(cpc)->cpc_entry.reg.space_id ==	\
111 				ACPI_ADR_SPACE_SYSTEM_IO)
112 
113 /* Evaluates to True if reg is a NULL register descriptor */
114 #define IS_NULL_REG(reg) ((reg)->space_id ==  ACPI_ADR_SPACE_SYSTEM_MEMORY && \
115 				(reg)->address == 0 &&			\
116 				(reg)->bit_width == 0 &&		\
117 				(reg)->bit_offset == 0 &&		\
118 				(reg)->access_width == 0)
119 
120 /* Evaluates to True if an optional cpc field is supported */
121 #define CPC_SUPPORTED(cpc) ((cpc)->type == ACPI_TYPE_INTEGER ?		\
122 				!!(cpc)->cpc_entry.int_value :		\
123 				!IS_NULL_REG(&(cpc)->cpc_entry.reg))
124 /*
125  * Arbitrary Retries in case the remote processor is slow to respond
126  * to PCC commands. Keeping it high enough to cover emulators where
127  * the processors run painfully slow.
128  */
129 #define NUM_RETRIES 500ULL
130 
131 #define define_one_cppc_ro(_name)		\
132 static struct kobj_attribute _name =		\
133 __ATTR(_name, 0444, show_##_name, NULL)
134 
135 #define to_cpc_desc(a) container_of(a, struct cpc_desc, kobj)
136 
137 #define show_cppc_data(access_fn, struct_name, member_name)		\
138 	static ssize_t show_##member_name(struct kobject *kobj,		\
139 				struct kobj_attribute *attr, char *buf)	\
140 	{								\
141 		struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);		\
142 		struct struct_name st_name = {0};			\
143 		int ret;						\
144 									\
145 		ret = access_fn(cpc_ptr->cpu_id, &st_name);		\
146 		if (ret)						\
147 			return ret;					\
148 									\
149 		return scnprintf(buf, PAGE_SIZE, "%llu\n",		\
150 				(u64)st_name.member_name);		\
151 	}								\
152 	define_one_cppc_ro(member_name)
153 
154 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, highest_perf);
155 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_perf);
156 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_perf);
157 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_nonlinear_perf);
158 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, lowest_freq);
159 show_cppc_data(cppc_get_perf_caps, cppc_perf_caps, nominal_freq);
160 
161 show_cppc_data(cppc_get_perf_ctrs, cppc_perf_fb_ctrs, reference_perf);
162 show_cppc_data(cppc_get_perf_ctrs, cppc_perf_fb_ctrs, wraparound_time);
163 
show_feedback_ctrs(struct kobject * kobj,struct kobj_attribute * attr,char * buf)164 static ssize_t show_feedback_ctrs(struct kobject *kobj,
165 		struct kobj_attribute *attr, char *buf)
166 {
167 	struct cpc_desc *cpc_ptr = to_cpc_desc(kobj);
168 	struct cppc_perf_fb_ctrs fb_ctrs = {0};
169 	int ret;
170 
171 	ret = cppc_get_perf_ctrs(cpc_ptr->cpu_id, &fb_ctrs);
172 	if (ret)
173 		return ret;
174 
175 	return scnprintf(buf, PAGE_SIZE, "ref:%llu del:%llu\n",
176 			fb_ctrs.reference, fb_ctrs.delivered);
177 }
178 define_one_cppc_ro(feedback_ctrs);
179 
180 static struct attribute *cppc_attrs[] = {
181 	&feedback_ctrs.attr,
182 	&reference_perf.attr,
183 	&wraparound_time.attr,
184 	&highest_perf.attr,
185 	&lowest_perf.attr,
186 	&lowest_nonlinear_perf.attr,
187 	&nominal_perf.attr,
188 	&nominal_freq.attr,
189 	&lowest_freq.attr,
190 	NULL
191 };
192 
193 static struct kobj_type cppc_ktype = {
194 	.sysfs_ops = &kobj_sysfs_ops,
195 	.default_attrs = cppc_attrs,
196 };
197 
check_pcc_chan(int pcc_ss_id,bool chk_err_bit)198 static int check_pcc_chan(int pcc_ss_id, bool chk_err_bit)
199 {
200 	int ret, status;
201 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
202 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
203 		pcc_ss_data->pcc_comm_addr;
204 
205 	if (!pcc_ss_data->platform_owns_pcc)
206 		return 0;
207 
208 	/*
209 	 * Poll PCC status register every 3us(delay_us) for maximum of
210 	 * deadline_us(timeout_us) until PCC command complete bit is set(cond)
211 	 */
212 	ret = readw_relaxed_poll_timeout(&generic_comm_base->status, status,
213 					status & PCC_CMD_COMPLETE_MASK, 3,
214 					pcc_ss_data->deadline_us);
215 
216 	if (likely(!ret)) {
217 		pcc_ss_data->platform_owns_pcc = false;
218 		if (chk_err_bit && (status & PCC_ERROR_MASK))
219 			ret = -EIO;
220 	}
221 
222 	if (unlikely(ret))
223 		pr_err("PCC check channel failed for ss: %d. ret=%d\n",
224 		       pcc_ss_id, ret);
225 
226 	return ret;
227 }
228 
229 /*
230  * This function transfers the ownership of the PCC to the platform
231  * So it must be called while holding write_lock(pcc_lock)
232  */
send_pcc_cmd(int pcc_ss_id,u16 cmd)233 static int send_pcc_cmd(int pcc_ss_id, u16 cmd)
234 {
235 	int ret = -EIO, i;
236 	struct cppc_pcc_data *pcc_ss_data = pcc_data[pcc_ss_id];
237 	struct acpi_pcct_shared_memory __iomem *generic_comm_base =
238 		pcc_ss_data->pcc_comm_addr;
239 	unsigned int time_delta;
240 
241 	/*
242 	 * For CMD_WRITE we know for a fact the caller should have checked
243 	 * the channel before writing to PCC space
244 	 */
245 	if (cmd == CMD_READ) {
246 		/*
247 		 * If there are pending cpc_writes, then we stole the channel
248 		 * before write completion, so first send a WRITE command to
249 		 * platform
250 		 */
251 		if (pcc_ss_data->pending_pcc_write_cmd)
252 			send_pcc_cmd(pcc_ss_id, CMD_WRITE);
253 
254 		ret = check_pcc_chan(pcc_ss_id, false);
255 		if (ret)
256 			goto end;
257 	} else /* CMD_WRITE */
258 		pcc_ss_data->pending_pcc_write_cmd = FALSE;
259 
260 	/*
261 	 * Handle the Minimum Request Turnaround Time(MRTT)
262 	 * "The minimum amount of time that OSPM must wait after the completion
263 	 * of a command before issuing the next command, in microseconds"
264 	 */
265 	if (pcc_ss_data->pcc_mrtt) {
266 		time_delta = ktime_us_delta(ktime_get(),
267 					    pcc_ss_data->last_cmd_cmpl_time);
268 		if (pcc_ss_data->pcc_mrtt > time_delta)
269 			udelay(pcc_ss_data->pcc_mrtt - time_delta);
270 	}
271 
272 	/*
273 	 * Handle the non-zero Maximum Periodic Access Rate(MPAR)
274 	 * "The maximum number of periodic requests that the subspace channel can
275 	 * support, reported in commands per minute. 0 indicates no limitation."
276 	 *
277 	 * This parameter should be ideally zero or large enough so that it can
278 	 * handle maximum number of requests that all the cores in the system can
279 	 * collectively generate. If it is not, we will follow the spec and just
280 	 * not send the request to the platform after hitting the MPAR limit in
281 	 * any 60s window
282 	 */
283 	if (pcc_ss_data->pcc_mpar) {
284 		if (pcc_ss_data->mpar_count == 0) {
285 			time_delta = ktime_ms_delta(ktime_get(),
286 						    pcc_ss_data->last_mpar_reset);
287 			if ((time_delta < 60 * MSEC_PER_SEC) && pcc_ss_data->last_mpar_reset) {
288 				pr_debug("PCC cmd for subspace %d not sent due to MPAR limit",
289 					 pcc_ss_id);
290 				ret = -EIO;
291 				goto end;
292 			}
293 			pcc_ss_data->last_mpar_reset = ktime_get();
294 			pcc_ss_data->mpar_count = pcc_ss_data->pcc_mpar;
295 		}
296 		pcc_ss_data->mpar_count--;
297 	}
298 
299 	/* Write to the shared comm region. */
300 	writew_relaxed(cmd, &generic_comm_base->command);
301 
302 	/* Flip CMD COMPLETE bit */
303 	writew_relaxed(0, &generic_comm_base->status);
304 
305 	pcc_ss_data->platform_owns_pcc = true;
306 
307 	/* Ring doorbell */
308 	ret = mbox_send_message(pcc_ss_data->pcc_channel, &cmd);
309 	if (ret < 0) {
310 		pr_err("Err sending PCC mbox message. ss: %d cmd:%d, ret:%d\n",
311 		       pcc_ss_id, cmd, ret);
312 		goto end;
313 	}
314 
315 	/* wait for completion and check for PCC errro bit */
316 	ret = check_pcc_chan(pcc_ss_id, true);
317 
318 	if (pcc_ss_data->pcc_mrtt)
319 		pcc_ss_data->last_cmd_cmpl_time = ktime_get();
320 
321 	if (pcc_ss_data->pcc_channel->mbox->txdone_irq)
322 		mbox_chan_txdone(pcc_ss_data->pcc_channel, ret);
323 	else
324 		mbox_client_txdone(pcc_ss_data->pcc_channel, ret);
325 
326 end:
327 	if (cmd == CMD_WRITE) {
328 		if (unlikely(ret)) {
329 			for_each_possible_cpu(i) {
330 				struct cpc_desc *desc = per_cpu(cpc_desc_ptr, i);
331 
332 				if (!desc)
333 					continue;
334 
335 				if (desc->write_cmd_id == pcc_ss_data->pcc_write_cnt)
336 					desc->write_cmd_status = ret;
337 			}
338 		}
339 		pcc_ss_data->pcc_write_cnt++;
340 		wake_up_all(&pcc_ss_data->pcc_write_wait_q);
341 	}
342 
343 	return ret;
344 }
345 
cppc_chan_tx_done(struct mbox_client * cl,void * msg,int ret)346 static void cppc_chan_tx_done(struct mbox_client *cl, void *msg, int ret)
347 {
348 	if (ret < 0)
349 		pr_debug("TX did not complete: CMD sent:%x, ret:%d\n",
350 				*(u16 *)msg, ret);
351 	else
352 		pr_debug("TX completed. CMD sent:%x, ret:%d\n",
353 				*(u16 *)msg, ret);
354 }
355 
356 static struct mbox_client cppc_mbox_cl = {
357 	.tx_done = cppc_chan_tx_done,
358 	.knows_txdone = true,
359 };
360 
acpi_get_psd(struct cpc_desc * cpc_ptr,acpi_handle handle)361 static int acpi_get_psd(struct cpc_desc *cpc_ptr, acpi_handle handle)
362 {
363 	int result = -EFAULT;
364 	acpi_status status = AE_OK;
365 	struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
366 	struct acpi_buffer format = {sizeof("NNNNN"), "NNNNN"};
367 	struct acpi_buffer state = {0, NULL};
368 	union acpi_object  *psd = NULL;
369 	struct acpi_psd_package *pdomain;
370 
371 	status = acpi_evaluate_object_typed(handle, "_PSD", NULL,
372 					    &buffer, ACPI_TYPE_PACKAGE);
373 	if (status == AE_NOT_FOUND)	/* _PSD is optional */
374 		return 0;
375 	if (ACPI_FAILURE(status))
376 		return -ENODEV;
377 
378 	psd = buffer.pointer;
379 	if (!psd || psd->package.count != 1) {
380 		pr_debug("Invalid _PSD data\n");
381 		goto end;
382 	}
383 
384 	pdomain = &(cpc_ptr->domain_info);
385 
386 	state.length = sizeof(struct acpi_psd_package);
387 	state.pointer = pdomain;
388 
389 	status = acpi_extract_package(&(psd->package.elements[0]),
390 		&format, &state);
391 	if (ACPI_FAILURE(status)) {
392 		pr_debug("Invalid _PSD data for CPU:%d\n", cpc_ptr->cpu_id);
393 		goto end;
394 	}
395 
396 	if (pdomain->num_entries != ACPI_PSD_REV0_ENTRIES) {
397 		pr_debug("Unknown _PSD:num_entries for CPU:%d\n", cpc_ptr->cpu_id);
398 		goto end;
399 	}
400 
401 	if (pdomain->revision != ACPI_PSD_REV0_REVISION) {
402 		pr_debug("Unknown _PSD:revision for CPU: %d\n", cpc_ptr->cpu_id);
403 		goto end;
404 	}
405 
406 	if (pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ALL &&
407 	    pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ANY &&
408 	    pdomain->coord_type != DOMAIN_COORD_TYPE_HW_ALL) {
409 		pr_debug("Invalid _PSD:coord_type for CPU:%d\n", cpc_ptr->cpu_id);
410 		goto end;
411 	}
412 
413 	result = 0;
414 end:
415 	kfree(buffer.pointer);
416 	return result;
417 }
418 
acpi_cpc_valid(void)419 bool acpi_cpc_valid(void)
420 {
421 	struct cpc_desc *cpc_ptr;
422 	int cpu;
423 
424 	for_each_present_cpu(cpu) {
425 		cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
426 		if (!cpc_ptr)
427 			return false;
428 	}
429 
430 	return true;
431 }
432 EXPORT_SYMBOL_GPL(acpi_cpc_valid);
433 
434 /**
435  * acpi_get_psd_map - Map the CPUs in the freq domain of a given cpu
436  * @cpu: Find all CPUs that share a domain with cpu.
437  * @cpu_data: Pointer to CPU specific CPPC data including PSD info.
438  *
439  *	Return: 0 for success or negative value for err.
440  */
acpi_get_psd_map(unsigned int cpu,struct cppc_cpudata * cpu_data)441 int acpi_get_psd_map(unsigned int cpu, struct cppc_cpudata *cpu_data)
442 {
443 	struct cpc_desc *cpc_ptr, *match_cpc_ptr;
444 	struct acpi_psd_package *match_pdomain;
445 	struct acpi_psd_package *pdomain;
446 	int count_target, i;
447 
448 	/*
449 	 * Now that we have _PSD data from all CPUs, let's setup P-state
450 	 * domain info.
451 	 */
452 	cpc_ptr = per_cpu(cpc_desc_ptr, cpu);
453 	if (!cpc_ptr)
454 		return -EFAULT;
455 
456 	pdomain = &(cpc_ptr->domain_info);
457 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
458 	if (pdomain->num_processors <= 1)
459 		return 0;
460 
461 	/* Validate the Domain info */
462 	count_target = pdomain->num_processors;
463 	if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ALL)
464 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ALL;
465 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_HW_ALL)
466 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_HW;
467 	else if (pdomain->coord_type == DOMAIN_COORD_TYPE_SW_ANY)
468 		cpu_data->shared_type = CPUFREQ_SHARED_TYPE_ANY;
469 
470 	for_each_possible_cpu(i) {
471 		if (i == cpu)
472 			continue;
473 
474 		match_cpc_ptr = per_cpu(cpc_desc_ptr, i);
475 		if (!match_cpc_ptr)
476 			goto err_fault;
477 
478 		match_pdomain = &(match_cpc_ptr->domain_info);
479 		if (match_pdomain->domain != pdomain->domain)
480 			continue;
481 
482 		/* Here i and cpu are in the same domain */
483 		if (match_pdomain->num_processors != count_target)
484 			goto err_fault;
485 
486 		if (pdomain->coord_type != match_pdomain->coord_type)
487 			goto err_fault;
488 
489 		cpumask_set_cpu(i, cpu_data->shared_cpu_map);
490 	}
491 
492 	return 0;
493 
494 err_fault:
495 	/* Assume no coordination on any error parsing domain info */
496 	cpumask_clear(cpu_data->shared_cpu_map);
497 	cpumask_set_cpu(cpu, cpu_data->shared_cpu_map);
498 	cpu_data->shared_type = CPUFREQ_SHARED_TYPE_NONE;
499 
500 	return -EFAULT;
501 }
502 EXPORT_SYMBOL_GPL(acpi_get_psd_map);
503 
register_pcc_channel(int pcc_ss_idx)504 static int register_pcc_channel(int pcc_ss_idx)
505 {
506 	struct acpi_pcct_hw_reduced *cppc_ss;
507 	u64 usecs_lat;
508 
509 	if (pcc_ss_idx >= 0) {
510 		pcc_data[pcc_ss_idx]->pcc_channel =
511 			pcc_mbox_request_channel(&cppc_mbox_cl,	pcc_ss_idx);
512 
513 		if (IS_ERR(pcc_data[pcc_ss_idx]->pcc_channel)) {
514 			pr_err("Failed to find PCC channel for subspace %d\n",
515 			       pcc_ss_idx);
516 			return -ENODEV;
517 		}
518 
519 		/*
520 		 * The PCC mailbox controller driver should
521 		 * have parsed the PCCT (global table of all
522 		 * PCC channels) and stored pointers to the
523 		 * subspace communication region in con_priv.
524 		 */
525 		cppc_ss = (pcc_data[pcc_ss_idx]->pcc_channel)->con_priv;
526 
527 		if (!cppc_ss) {
528 			pr_err("No PCC subspace found for %d CPPC\n",
529 			       pcc_ss_idx);
530 			return -ENODEV;
531 		}
532 
533 		/*
534 		 * cppc_ss->latency is just a Nominal value. In reality
535 		 * the remote processor could be much slower to reply.
536 		 * So add an arbitrary amount of wait on top of Nominal.
537 		 */
538 		usecs_lat = NUM_RETRIES * cppc_ss->latency;
539 		pcc_data[pcc_ss_idx]->deadline_us = usecs_lat;
540 		pcc_data[pcc_ss_idx]->pcc_mrtt = cppc_ss->min_turnaround_time;
541 		pcc_data[pcc_ss_idx]->pcc_mpar = cppc_ss->max_access_rate;
542 		pcc_data[pcc_ss_idx]->pcc_nominal = cppc_ss->latency;
543 
544 		pcc_data[pcc_ss_idx]->pcc_comm_addr =
545 			acpi_os_ioremap(cppc_ss->base_address, cppc_ss->length);
546 		if (!pcc_data[pcc_ss_idx]->pcc_comm_addr) {
547 			pr_err("Failed to ioremap PCC comm region mem for %d\n",
548 			       pcc_ss_idx);
549 			return -ENOMEM;
550 		}
551 
552 		/* Set flag so that we don't come here for each CPU. */
553 		pcc_data[pcc_ss_idx]->pcc_channel_acquired = true;
554 	}
555 
556 	return 0;
557 }
558 
559 /**
560  * cpc_ffh_supported() - check if FFH reading supported
561  *
562  * Check if the architecture has support for functional fixed hardware
563  * read/write capability.
564  *
565  * Return: true for supported, false for not supported
566  */
cpc_ffh_supported(void)567 bool __weak cpc_ffh_supported(void)
568 {
569 	return false;
570 }
571 
572 /**
573  * pcc_data_alloc() - Allocate the pcc_data memory for pcc subspace
574  *
575  * Check and allocate the cppc_pcc_data memory.
576  * In some processor configurations it is possible that same subspace
577  * is shared between multiple CPUs. This is seen especially in CPUs
578  * with hardware multi-threading support.
579  *
580  * Return: 0 for success, errno for failure
581  */
pcc_data_alloc(int pcc_ss_id)582 static int pcc_data_alloc(int pcc_ss_id)
583 {
584 	if (pcc_ss_id < 0 || pcc_ss_id >= MAX_PCC_SUBSPACES)
585 		return -EINVAL;
586 
587 	if (pcc_data[pcc_ss_id]) {
588 		pcc_data[pcc_ss_id]->refcount++;
589 	} else {
590 		pcc_data[pcc_ss_id] = kzalloc(sizeof(struct cppc_pcc_data),
591 					      GFP_KERNEL);
592 		if (!pcc_data[pcc_ss_id])
593 			return -ENOMEM;
594 		pcc_data[pcc_ss_id]->refcount++;
595 	}
596 
597 	return 0;
598 }
599 
600 /*
601  * An example CPC table looks like the following.
602  *
603  *	Name(_CPC, Package()
604  *			{
605  *			17,
606  *			NumEntries
607  *			1,
608  *			// Revision
609  *			ResourceTemplate(){Register(PCC, 32, 0, 0x120, 2)},
610  *			// Highest Performance
611  *			ResourceTemplate(){Register(PCC, 32, 0, 0x124, 2)},
612  *			// Nominal Performance
613  *			ResourceTemplate(){Register(PCC, 32, 0, 0x128, 2)},
614  *			// Lowest Nonlinear Performance
615  *			ResourceTemplate(){Register(PCC, 32, 0, 0x12C, 2)},
616  *			// Lowest Performance
617  *			ResourceTemplate(){Register(PCC, 32, 0, 0x130, 2)},
618  *			// Guaranteed Performance Register
619  *			ResourceTemplate(){Register(PCC, 32, 0, 0x110, 2)},
620  *			// Desired Performance Register
621  *			ResourceTemplate(){Register(SystemMemory, 0, 0, 0, 0)},
622  *			..
623  *			..
624  *			..
625  *
626  *		}
627  * Each Register() encodes how to access that specific register.
628  * e.g. a sample PCC entry has the following encoding:
629  *
630  *	Register (
631  *		PCC,
632  *		AddressSpaceKeyword
633  *		8,
634  *		//RegisterBitWidth
635  *		8,
636  *		//RegisterBitOffset
637  *		0x30,
638  *		//RegisterAddress
639  *		9
640  *		//AccessSize (subspace ID)
641  *		0
642  *		)
643  *	}
644  */
645 
646 #ifndef init_freq_invariance_cppc
init_freq_invariance_cppc(void)647 static inline void init_freq_invariance_cppc(void) { }
648 #endif
649 
650 /**
651  * acpi_cppc_processor_probe - Search for per CPU _CPC objects.
652  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
653  *
654  *	Return: 0 for success or negative value for err.
655  */
acpi_cppc_processor_probe(struct acpi_processor * pr)656 int acpi_cppc_processor_probe(struct acpi_processor *pr)
657 {
658 	struct acpi_buffer output = {ACPI_ALLOCATE_BUFFER, NULL};
659 	union acpi_object *out_obj, *cpc_obj;
660 	struct cpc_desc *cpc_ptr;
661 	struct cpc_reg *gas_t;
662 	struct device *cpu_dev;
663 	acpi_handle handle = pr->handle;
664 	unsigned int num_ent, i, cpc_rev;
665 	int pcc_subspace_id = -1;
666 	acpi_status status;
667 	int ret = -EFAULT;
668 
669 	/* Parse the ACPI _CPC table for this CPU. */
670 	status = acpi_evaluate_object_typed(handle, "_CPC", NULL, &output,
671 			ACPI_TYPE_PACKAGE);
672 	if (ACPI_FAILURE(status)) {
673 		ret = -ENODEV;
674 		goto out_buf_free;
675 	}
676 
677 	out_obj = (union acpi_object *) output.pointer;
678 
679 	cpc_ptr = kzalloc(sizeof(struct cpc_desc), GFP_KERNEL);
680 	if (!cpc_ptr) {
681 		ret = -ENOMEM;
682 		goto out_buf_free;
683 	}
684 
685 	/* First entry is NumEntries. */
686 	cpc_obj = &out_obj->package.elements[0];
687 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
688 		num_ent = cpc_obj->integer.value;
689 		if (num_ent <= 1) {
690 			pr_debug("Unexpected _CPC NumEntries value (%d) for CPU:%d\n",
691 				 num_ent, pr->id);
692 			goto out_free;
693 		}
694 	} else {
695 		pr_debug("Unexpected entry type(%d) for NumEntries\n",
696 				cpc_obj->type);
697 		goto out_free;
698 	}
699 
700 	/* Second entry should be revision. */
701 	cpc_obj = &out_obj->package.elements[1];
702 	if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
703 		cpc_rev = cpc_obj->integer.value;
704 	} else {
705 		pr_debug("Unexpected entry type(%d) for Revision\n",
706 				cpc_obj->type);
707 		goto out_free;
708 	}
709 
710 	if (cpc_rev < CPPC_V2_REV) {
711 		pr_debug("Unsupported _CPC Revision (%d) for CPU:%d\n", cpc_rev,
712 			 pr->id);
713 		goto out_free;
714 	}
715 
716 	/*
717 	 * Disregard _CPC if the number of entries in the return pachage is not
718 	 * as expected, but support future revisions being proper supersets of
719 	 * the v3 and only causing more entries to be returned by _CPC.
720 	 */
721 	if ((cpc_rev == CPPC_V2_REV && num_ent != CPPC_V2_NUM_ENT) ||
722 	    (cpc_rev == CPPC_V3_REV && num_ent != CPPC_V3_NUM_ENT) ||
723 	    (cpc_rev > CPPC_V3_REV && num_ent <= CPPC_V3_NUM_ENT)) {
724 		pr_debug("Unexpected number of _CPC return package entries (%d) for CPU:%d\n",
725 			 num_ent, pr->id);
726 		goto out_free;
727 	}
728 	if (cpc_rev > CPPC_V3_REV) {
729 		num_ent = CPPC_V3_NUM_ENT;
730 		cpc_rev = CPPC_V3_REV;
731 	}
732 
733 	cpc_ptr->num_entries = num_ent;
734 	cpc_ptr->version = cpc_rev;
735 
736 	/* Iterate through remaining entries in _CPC */
737 	for (i = 2; i < num_ent; i++) {
738 		cpc_obj = &out_obj->package.elements[i];
739 
740 		if (cpc_obj->type == ACPI_TYPE_INTEGER)	{
741 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_INTEGER;
742 			cpc_ptr->cpc_regs[i-2].cpc_entry.int_value = cpc_obj->integer.value;
743 		} else if (cpc_obj->type == ACPI_TYPE_BUFFER) {
744 			gas_t = (struct cpc_reg *)
745 				cpc_obj->buffer.pointer;
746 
747 			/*
748 			 * The PCC Subspace index is encoded inside
749 			 * the CPC table entries. The same PCC index
750 			 * will be used for all the PCC entries,
751 			 * so extract it only once.
752 			 */
753 			if (gas_t->space_id == ACPI_ADR_SPACE_PLATFORM_COMM) {
754 				if (pcc_subspace_id < 0) {
755 					pcc_subspace_id = gas_t->access_width;
756 					if (pcc_data_alloc(pcc_subspace_id))
757 						goto out_free;
758 				} else if (pcc_subspace_id != gas_t->access_width) {
759 					pr_debug("Mismatched PCC ids.\n");
760 					goto out_free;
761 				}
762 			} else if (gas_t->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
763 				if (gas_t->address) {
764 					void __iomem *addr;
765 
766 					addr = ioremap(gas_t->address, gas_t->bit_width/8);
767 					if (!addr)
768 						goto out_free;
769 					cpc_ptr->cpc_regs[i-2].sys_mem_vaddr = addr;
770 				}
771 			} else {
772 				if (gas_t->space_id != ACPI_ADR_SPACE_FIXED_HARDWARE || !cpc_ffh_supported()) {
773 					/* Support only PCC ,SYS MEM and FFH type regs */
774 					pr_debug("Unsupported register type: %d\n", gas_t->space_id);
775 					goto out_free;
776 				}
777 			}
778 
779 			cpc_ptr->cpc_regs[i-2].type = ACPI_TYPE_BUFFER;
780 			memcpy(&cpc_ptr->cpc_regs[i-2].cpc_entry.reg, gas_t, sizeof(*gas_t));
781 		} else {
782 			pr_debug("Err in entry:%d in CPC table of CPU:%d\n", i, pr->id);
783 			goto out_free;
784 		}
785 	}
786 	per_cpu(cpu_pcc_subspace_idx, pr->id) = pcc_subspace_id;
787 
788 	/*
789 	 * Initialize the remaining cpc_regs as unsupported.
790 	 * Example: In case FW exposes CPPC v2, the below loop will initialize
791 	 * LOWEST_FREQ and NOMINAL_FREQ regs as unsupported
792 	 */
793 	for (i = num_ent - 2; i < MAX_CPC_REG_ENT; i++) {
794 		cpc_ptr->cpc_regs[i].type = ACPI_TYPE_INTEGER;
795 		cpc_ptr->cpc_regs[i].cpc_entry.int_value = 0;
796 	}
797 
798 
799 	/* Store CPU Logical ID */
800 	cpc_ptr->cpu_id = pr->id;
801 
802 	/* Parse PSD data for this CPU */
803 	ret = acpi_get_psd(cpc_ptr, handle);
804 	if (ret)
805 		goto out_free;
806 
807 	/* Register PCC channel once for all PCC subspace ID. */
808 	if (pcc_subspace_id >= 0 && !pcc_data[pcc_subspace_id]->pcc_channel_acquired) {
809 		ret = register_pcc_channel(pcc_subspace_id);
810 		if (ret)
811 			goto out_free;
812 
813 		init_rwsem(&pcc_data[pcc_subspace_id]->pcc_lock);
814 		init_waitqueue_head(&pcc_data[pcc_subspace_id]->pcc_write_wait_q);
815 	}
816 
817 	/* Everything looks okay */
818 	pr_debug("Parsed CPC struct for CPU: %d\n", pr->id);
819 
820 	/* Add per logical CPU nodes for reading its feedback counters. */
821 	cpu_dev = get_cpu_device(pr->id);
822 	if (!cpu_dev) {
823 		ret = -EINVAL;
824 		goto out_free;
825 	}
826 
827 	/* Plug PSD data into this CPU's CPC descriptor. */
828 	per_cpu(cpc_desc_ptr, pr->id) = cpc_ptr;
829 
830 	ret = kobject_init_and_add(&cpc_ptr->kobj, &cppc_ktype, &cpu_dev->kobj,
831 			"acpi_cppc");
832 	if (ret) {
833 		per_cpu(cpc_desc_ptr, pr->id) = NULL;
834 		kobject_put(&cpc_ptr->kobj);
835 		goto out_free;
836 	}
837 
838 	init_freq_invariance_cppc();
839 
840 	kfree(output.pointer);
841 	return 0;
842 
843 out_free:
844 	/* Free all the mapped sys mem areas for this CPU */
845 	for (i = 2; i < cpc_ptr->num_entries; i++) {
846 		void __iomem *addr = cpc_ptr->cpc_regs[i-2].sys_mem_vaddr;
847 
848 		if (addr)
849 			iounmap(addr);
850 	}
851 	kfree(cpc_ptr);
852 
853 out_buf_free:
854 	kfree(output.pointer);
855 	return ret;
856 }
857 EXPORT_SYMBOL_GPL(acpi_cppc_processor_probe);
858 
859 /**
860  * acpi_cppc_processor_exit - Cleanup CPC structs.
861  * @pr: Ptr to acpi_processor containing this CPU's logical ID.
862  *
863  * Return: Void
864  */
acpi_cppc_processor_exit(struct acpi_processor * pr)865 void acpi_cppc_processor_exit(struct acpi_processor *pr)
866 {
867 	struct cpc_desc *cpc_ptr;
868 	unsigned int i;
869 	void __iomem *addr;
870 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, pr->id);
871 
872 	if (pcc_ss_id >= 0 && pcc_data[pcc_ss_id]) {
873 		if (pcc_data[pcc_ss_id]->pcc_channel_acquired) {
874 			pcc_data[pcc_ss_id]->refcount--;
875 			if (!pcc_data[pcc_ss_id]->refcount) {
876 				pcc_mbox_free_channel(pcc_data[pcc_ss_id]->pcc_channel);
877 				kfree(pcc_data[pcc_ss_id]);
878 				pcc_data[pcc_ss_id] = NULL;
879 			}
880 		}
881 	}
882 
883 	cpc_ptr = per_cpu(cpc_desc_ptr, pr->id);
884 	if (!cpc_ptr)
885 		return;
886 
887 	/* Free all the mapped sys mem areas for this CPU */
888 	for (i = 2; i < cpc_ptr->num_entries; i++) {
889 		addr = cpc_ptr->cpc_regs[i-2].sys_mem_vaddr;
890 		if (addr)
891 			iounmap(addr);
892 	}
893 
894 	kobject_put(&cpc_ptr->kobj);
895 	kfree(cpc_ptr);
896 }
897 EXPORT_SYMBOL_GPL(acpi_cppc_processor_exit);
898 
899 /**
900  * cpc_read_ffh() - Read FFH register
901  * @cpunum:	CPU number to read
902  * @reg:	cppc register information
903  * @val:	place holder for return value
904  *
905  * Read bit_width bits from a specified address and bit_offset
906  *
907  * Return: 0 for success and error code
908  */
cpc_read_ffh(int cpunum,struct cpc_reg * reg,u64 * val)909 int __weak cpc_read_ffh(int cpunum, struct cpc_reg *reg, u64 *val)
910 {
911 	return -ENOTSUPP;
912 }
913 
914 /**
915  * cpc_write_ffh() - Write FFH register
916  * @cpunum:	CPU number to write
917  * @reg:	cppc register information
918  * @val:	value to write
919  *
920  * Write value of bit_width bits to a specified address and bit_offset
921  *
922  * Return: 0 for success and error code
923  */
cpc_write_ffh(int cpunum,struct cpc_reg * reg,u64 val)924 int __weak cpc_write_ffh(int cpunum, struct cpc_reg *reg, u64 val)
925 {
926 	return -ENOTSUPP;
927 }
928 
929 /*
930  * Since cpc_read and cpc_write are called while holding pcc_lock, it should be
931  * as fast as possible. We have already mapped the PCC subspace during init, so
932  * we can directly write to it.
933  */
934 
cpc_read(int cpu,struct cpc_register_resource * reg_res,u64 * val)935 static int cpc_read(int cpu, struct cpc_register_resource *reg_res, u64 *val)
936 {
937 	int ret_val = 0;
938 	void __iomem *vaddr = NULL;
939 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
940 	struct cpc_reg *reg = &reg_res->cpc_entry.reg;
941 
942 	if (reg_res->type == ACPI_TYPE_INTEGER) {
943 		*val = reg_res->cpc_entry.int_value;
944 		return ret_val;
945 	}
946 
947 	*val = 0;
948 	if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM && pcc_ss_id >= 0)
949 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
950 	else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
951 		vaddr = reg_res->sys_mem_vaddr;
952 	else if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
953 		return cpc_read_ffh(cpu, reg, val);
954 	else
955 		return acpi_os_read_memory((acpi_physical_address)reg->address,
956 				val, reg->bit_width);
957 
958 	switch (reg->bit_width) {
959 	case 8:
960 		*val = readb_relaxed(vaddr);
961 		break;
962 	case 16:
963 		*val = readw_relaxed(vaddr);
964 		break;
965 	case 32:
966 		*val = readl_relaxed(vaddr);
967 		break;
968 	case 64:
969 		*val = readq_relaxed(vaddr);
970 		break;
971 	default:
972 		pr_debug("Error: Cannot read %u bit width from PCC for ss: %d\n",
973 			 reg->bit_width, pcc_ss_id);
974 		ret_val = -EFAULT;
975 	}
976 
977 	return ret_val;
978 }
979 
cpc_write(int cpu,struct cpc_register_resource * reg_res,u64 val)980 static int cpc_write(int cpu, struct cpc_register_resource *reg_res, u64 val)
981 {
982 	int ret_val = 0;
983 	void __iomem *vaddr = NULL;
984 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
985 	struct cpc_reg *reg = &reg_res->cpc_entry.reg;
986 
987 	if (reg->space_id == ACPI_ADR_SPACE_PLATFORM_COMM && pcc_ss_id >= 0)
988 		vaddr = GET_PCC_VADDR(reg->address, pcc_ss_id);
989 	else if (reg->space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
990 		vaddr = reg_res->sys_mem_vaddr;
991 	else if (reg->space_id == ACPI_ADR_SPACE_FIXED_HARDWARE)
992 		return cpc_write_ffh(cpu, reg, val);
993 	else
994 		return acpi_os_write_memory((acpi_physical_address)reg->address,
995 				val, reg->bit_width);
996 
997 	switch (reg->bit_width) {
998 	case 8:
999 		writeb_relaxed(val, vaddr);
1000 		break;
1001 	case 16:
1002 		writew_relaxed(val, vaddr);
1003 		break;
1004 	case 32:
1005 		writel_relaxed(val, vaddr);
1006 		break;
1007 	case 64:
1008 		writeq_relaxed(val, vaddr);
1009 		break;
1010 	default:
1011 		pr_debug("Error: Cannot write %u bit width to PCC for ss: %d\n",
1012 			 reg->bit_width, pcc_ss_id);
1013 		ret_val = -EFAULT;
1014 		break;
1015 	}
1016 
1017 	return ret_val;
1018 }
1019 
cppc_get_perf(int cpunum,enum cppc_regs reg_idx,u64 * perf)1020 static int cppc_get_perf(int cpunum, enum cppc_regs reg_idx, u64 *perf)
1021 {
1022 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
1023 	struct cpc_register_resource *reg;
1024 
1025 	if (!cpc_desc) {
1026 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
1027 		return -ENODEV;
1028 	}
1029 
1030 	reg = &cpc_desc->cpc_regs[reg_idx];
1031 
1032 	if (CPC_IN_PCC(reg)) {
1033 		int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
1034 		struct cppc_pcc_data *pcc_ss_data = NULL;
1035 		int ret = 0;
1036 
1037 		if (pcc_ss_id < 0)
1038 			return -EIO;
1039 
1040 		pcc_ss_data = pcc_data[pcc_ss_id];
1041 
1042 		down_write(&pcc_ss_data->pcc_lock);
1043 
1044 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) >= 0)
1045 			cpc_read(cpunum, reg, perf);
1046 		else
1047 			ret = -EIO;
1048 
1049 		up_write(&pcc_ss_data->pcc_lock);
1050 
1051 		return ret;
1052 	}
1053 
1054 	cpc_read(cpunum, reg, perf);
1055 
1056 	return 0;
1057 }
1058 
1059 /**
1060  * cppc_get_desired_perf - Get the desired performance register value.
1061  * @cpunum: CPU from which to get desired performance.
1062  * @desired_perf: Return address.
1063  *
1064  * Return: 0 for success, -EIO otherwise.
1065  */
cppc_get_desired_perf(int cpunum,u64 * desired_perf)1066 int cppc_get_desired_perf(int cpunum, u64 *desired_perf)
1067 {
1068 	return cppc_get_perf(cpunum, DESIRED_PERF, desired_perf);
1069 }
1070 EXPORT_SYMBOL_GPL(cppc_get_desired_perf);
1071 
1072 /**
1073  * cppc_get_nominal_perf - Get the nominal performance register value.
1074  * @cpunum: CPU from which to get nominal performance.
1075  * @nominal_perf: Return address.
1076  *
1077  * Return: 0 for success, -EIO otherwise.
1078  */
cppc_get_nominal_perf(int cpunum,u64 * nominal_perf)1079 int cppc_get_nominal_perf(int cpunum, u64 *nominal_perf)
1080 {
1081 	return cppc_get_perf(cpunum, NOMINAL_PERF, nominal_perf);
1082 }
1083 
1084 /**
1085  * cppc_get_perf_caps - Get a CPU's performance capabilities.
1086  * @cpunum: CPU from which to get capabilities info.
1087  * @perf_caps: ptr to cppc_perf_caps. See cppc_acpi.h
1088  *
1089  * Return: 0 for success with perf_caps populated else -ERRNO.
1090  */
cppc_get_perf_caps(int cpunum,struct cppc_perf_caps * perf_caps)1091 int cppc_get_perf_caps(int cpunum, struct cppc_perf_caps *perf_caps)
1092 {
1093 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
1094 	struct cpc_register_resource *highest_reg, *lowest_reg,
1095 		*lowest_non_linear_reg, *nominal_reg, *guaranteed_reg,
1096 		*low_freq_reg = NULL, *nom_freq_reg = NULL;
1097 	u64 high, low, guaranteed, nom, min_nonlinear, low_f = 0, nom_f = 0;
1098 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
1099 	struct cppc_pcc_data *pcc_ss_data = NULL;
1100 	int ret = 0, regs_in_pcc = 0;
1101 
1102 	if (!cpc_desc) {
1103 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
1104 		return -ENODEV;
1105 	}
1106 
1107 	highest_reg = &cpc_desc->cpc_regs[HIGHEST_PERF];
1108 	lowest_reg = &cpc_desc->cpc_regs[LOWEST_PERF];
1109 	lowest_non_linear_reg = &cpc_desc->cpc_regs[LOW_NON_LINEAR_PERF];
1110 	nominal_reg = &cpc_desc->cpc_regs[NOMINAL_PERF];
1111 	low_freq_reg = &cpc_desc->cpc_regs[LOWEST_FREQ];
1112 	nom_freq_reg = &cpc_desc->cpc_regs[NOMINAL_FREQ];
1113 	guaranteed_reg = &cpc_desc->cpc_regs[GUARANTEED_PERF];
1114 
1115 	/* Are any of the regs PCC ?*/
1116 	if (CPC_IN_PCC(highest_reg) || CPC_IN_PCC(lowest_reg) ||
1117 		CPC_IN_PCC(lowest_non_linear_reg) || CPC_IN_PCC(nominal_reg) ||
1118 		CPC_IN_PCC(low_freq_reg) || CPC_IN_PCC(nom_freq_reg)) {
1119 		if (pcc_ss_id < 0) {
1120 			pr_debug("Invalid pcc_ss_id\n");
1121 			return -ENODEV;
1122 		}
1123 		pcc_ss_data = pcc_data[pcc_ss_id];
1124 		regs_in_pcc = 1;
1125 		down_write(&pcc_ss_data->pcc_lock);
1126 		/* Ring doorbell once to update PCC subspace */
1127 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
1128 			ret = -EIO;
1129 			goto out_err;
1130 		}
1131 	}
1132 
1133 	cpc_read(cpunum, highest_reg, &high);
1134 	perf_caps->highest_perf = high;
1135 
1136 	cpc_read(cpunum, lowest_reg, &low);
1137 	perf_caps->lowest_perf = low;
1138 
1139 	cpc_read(cpunum, nominal_reg, &nom);
1140 	perf_caps->nominal_perf = nom;
1141 
1142 	if (guaranteed_reg->type != ACPI_TYPE_BUFFER  ||
1143 	    IS_NULL_REG(&guaranteed_reg->cpc_entry.reg)) {
1144 		perf_caps->guaranteed_perf = 0;
1145 	} else {
1146 		cpc_read(cpunum, guaranteed_reg, &guaranteed);
1147 		perf_caps->guaranteed_perf = guaranteed;
1148 	}
1149 
1150 	cpc_read(cpunum, lowest_non_linear_reg, &min_nonlinear);
1151 	perf_caps->lowest_nonlinear_perf = min_nonlinear;
1152 
1153 	if (!high || !low || !nom || !min_nonlinear)
1154 		ret = -EFAULT;
1155 
1156 	/* Read optional lowest and nominal frequencies if present */
1157 	if (CPC_SUPPORTED(low_freq_reg))
1158 		cpc_read(cpunum, low_freq_reg, &low_f);
1159 
1160 	if (CPC_SUPPORTED(nom_freq_reg))
1161 		cpc_read(cpunum, nom_freq_reg, &nom_f);
1162 
1163 	perf_caps->lowest_freq = low_f;
1164 	perf_caps->nominal_freq = nom_f;
1165 
1166 
1167 out_err:
1168 	if (regs_in_pcc)
1169 		up_write(&pcc_ss_data->pcc_lock);
1170 	return ret;
1171 }
1172 EXPORT_SYMBOL_GPL(cppc_get_perf_caps);
1173 
1174 /**
1175  * cppc_get_perf_ctrs - Read a CPU's performance feedback counters.
1176  * @cpunum: CPU from which to read counters.
1177  * @perf_fb_ctrs: ptr to cppc_perf_fb_ctrs. See cppc_acpi.h
1178  *
1179  * Return: 0 for success with perf_fb_ctrs populated else -ERRNO.
1180  */
cppc_get_perf_ctrs(int cpunum,struct cppc_perf_fb_ctrs * perf_fb_ctrs)1181 int cppc_get_perf_ctrs(int cpunum, struct cppc_perf_fb_ctrs *perf_fb_ctrs)
1182 {
1183 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpunum);
1184 	struct cpc_register_resource *delivered_reg, *reference_reg,
1185 		*ref_perf_reg, *ctr_wrap_reg;
1186 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpunum);
1187 	struct cppc_pcc_data *pcc_ss_data = NULL;
1188 	u64 delivered, reference, ref_perf, ctr_wrap_time;
1189 	int ret = 0, regs_in_pcc = 0;
1190 
1191 	if (!cpc_desc) {
1192 		pr_debug("No CPC descriptor for CPU:%d\n", cpunum);
1193 		return -ENODEV;
1194 	}
1195 
1196 	delivered_reg = &cpc_desc->cpc_regs[DELIVERED_CTR];
1197 	reference_reg = &cpc_desc->cpc_regs[REFERENCE_CTR];
1198 	ref_perf_reg = &cpc_desc->cpc_regs[REFERENCE_PERF];
1199 	ctr_wrap_reg = &cpc_desc->cpc_regs[CTR_WRAP_TIME];
1200 
1201 	/*
1202 	 * If reference perf register is not supported then we should
1203 	 * use the nominal perf value
1204 	 */
1205 	if (!CPC_SUPPORTED(ref_perf_reg))
1206 		ref_perf_reg = &cpc_desc->cpc_regs[NOMINAL_PERF];
1207 
1208 	/* Are any of the regs PCC ?*/
1209 	if (CPC_IN_PCC(delivered_reg) || CPC_IN_PCC(reference_reg) ||
1210 		CPC_IN_PCC(ctr_wrap_reg) || CPC_IN_PCC(ref_perf_reg)) {
1211 		if (pcc_ss_id < 0) {
1212 			pr_debug("Invalid pcc_ss_id\n");
1213 			return -ENODEV;
1214 		}
1215 		pcc_ss_data = pcc_data[pcc_ss_id];
1216 		down_write(&pcc_ss_data->pcc_lock);
1217 		regs_in_pcc = 1;
1218 		/* Ring doorbell once to update PCC subspace */
1219 		if (send_pcc_cmd(pcc_ss_id, CMD_READ) < 0) {
1220 			ret = -EIO;
1221 			goto out_err;
1222 		}
1223 	}
1224 
1225 	cpc_read(cpunum, delivered_reg, &delivered);
1226 	cpc_read(cpunum, reference_reg, &reference);
1227 	cpc_read(cpunum, ref_perf_reg, &ref_perf);
1228 
1229 	/*
1230 	 * Per spec, if ctr_wrap_time optional register is unsupported, then the
1231 	 * performance counters are assumed to never wrap during the lifetime of
1232 	 * platform
1233 	 */
1234 	ctr_wrap_time = (u64)(~((u64)0));
1235 	if (CPC_SUPPORTED(ctr_wrap_reg))
1236 		cpc_read(cpunum, ctr_wrap_reg, &ctr_wrap_time);
1237 
1238 	if (!delivered || !reference ||	!ref_perf) {
1239 		ret = -EFAULT;
1240 		goto out_err;
1241 	}
1242 
1243 	perf_fb_ctrs->delivered = delivered;
1244 	perf_fb_ctrs->reference = reference;
1245 	perf_fb_ctrs->reference_perf = ref_perf;
1246 	perf_fb_ctrs->wraparound_time = ctr_wrap_time;
1247 out_err:
1248 	if (regs_in_pcc)
1249 		up_write(&pcc_ss_data->pcc_lock);
1250 	return ret;
1251 }
1252 EXPORT_SYMBOL_GPL(cppc_get_perf_ctrs);
1253 
1254 /**
1255  * cppc_set_perf - Set a CPU's performance controls.
1256  * @cpu: CPU for which to set performance controls.
1257  * @perf_ctrls: ptr to cppc_perf_ctrls. See cppc_acpi.h
1258  *
1259  * Return: 0 for success, -ERRNO otherwise.
1260  */
cppc_set_perf(int cpu,struct cppc_perf_ctrls * perf_ctrls)1261 int cppc_set_perf(int cpu, struct cppc_perf_ctrls *perf_ctrls)
1262 {
1263 	struct cpc_desc *cpc_desc = per_cpu(cpc_desc_ptr, cpu);
1264 	struct cpc_register_resource *desired_reg;
1265 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu);
1266 	struct cppc_pcc_data *pcc_ss_data = NULL;
1267 	int ret = 0;
1268 
1269 	if (!cpc_desc) {
1270 		pr_debug("No CPC descriptor for CPU:%d\n", cpu);
1271 		return -ENODEV;
1272 	}
1273 
1274 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
1275 
1276 	/*
1277 	 * This is Phase-I where we want to write to CPC registers
1278 	 * -> We want all CPUs to be able to execute this phase in parallel
1279 	 *
1280 	 * Since read_lock can be acquired by multiple CPUs simultaneously we
1281 	 * achieve that goal here
1282 	 */
1283 	if (CPC_IN_PCC(desired_reg)) {
1284 		if (pcc_ss_id < 0) {
1285 			pr_debug("Invalid pcc_ss_id\n");
1286 			return -ENODEV;
1287 		}
1288 		pcc_ss_data = pcc_data[pcc_ss_id];
1289 		down_read(&pcc_ss_data->pcc_lock); /* BEGIN Phase-I */
1290 		if (pcc_ss_data->platform_owns_pcc) {
1291 			ret = check_pcc_chan(pcc_ss_id, false);
1292 			if (ret) {
1293 				up_read(&pcc_ss_data->pcc_lock);
1294 				return ret;
1295 			}
1296 		}
1297 		/*
1298 		 * Update the pending_write to make sure a PCC CMD_READ will not
1299 		 * arrive and steal the channel during the switch to write lock
1300 		 */
1301 		pcc_ss_data->pending_pcc_write_cmd = true;
1302 		cpc_desc->write_cmd_id = pcc_ss_data->pcc_write_cnt;
1303 		cpc_desc->write_cmd_status = 0;
1304 	}
1305 
1306 	/*
1307 	 * Skip writing MIN/MAX until Linux knows how to come up with
1308 	 * useful values.
1309 	 */
1310 	cpc_write(cpu, desired_reg, perf_ctrls->desired_perf);
1311 
1312 	if (CPC_IN_PCC(desired_reg))
1313 		up_read(&pcc_ss_data->pcc_lock);	/* END Phase-I */
1314 	/*
1315 	 * This is Phase-II where we transfer the ownership of PCC to Platform
1316 	 *
1317 	 * Short Summary: Basically if we think of a group of cppc_set_perf
1318 	 * requests that happened in short overlapping interval. The last CPU to
1319 	 * come out of Phase-I will enter Phase-II and ring the doorbell.
1320 	 *
1321 	 * We have the following requirements for Phase-II:
1322 	 *     1. We want to execute Phase-II only when there are no CPUs
1323 	 * currently executing in Phase-I
1324 	 *     2. Once we start Phase-II we want to avoid all other CPUs from
1325 	 * entering Phase-I.
1326 	 *     3. We want only one CPU among all those who went through Phase-I
1327 	 * to run phase-II
1328 	 *
1329 	 * If write_trylock fails to get the lock and doesn't transfer the
1330 	 * PCC ownership to the platform, then one of the following will be TRUE
1331 	 *     1. There is at-least one CPU in Phase-I which will later execute
1332 	 * write_trylock, so the CPUs in Phase-I will be responsible for
1333 	 * executing the Phase-II.
1334 	 *     2. Some other CPU has beaten this CPU to successfully execute the
1335 	 * write_trylock and has already acquired the write_lock. We know for a
1336 	 * fact it (other CPU acquiring the write_lock) couldn't have happened
1337 	 * before this CPU's Phase-I as we held the read_lock.
1338 	 *     3. Some other CPU executing pcc CMD_READ has stolen the
1339 	 * down_write, in which case, send_pcc_cmd will check for pending
1340 	 * CMD_WRITE commands by checking the pending_pcc_write_cmd.
1341 	 * So this CPU can be certain that its request will be delivered
1342 	 *    So in all cases, this CPU knows that its request will be delivered
1343 	 * by another CPU and can return
1344 	 *
1345 	 * After getting the down_write we still need to check for
1346 	 * pending_pcc_write_cmd to take care of the following scenario
1347 	 *    The thread running this code could be scheduled out between
1348 	 * Phase-I and Phase-II. Before it is scheduled back on, another CPU
1349 	 * could have delivered the request to Platform by triggering the
1350 	 * doorbell and transferred the ownership of PCC to platform. So this
1351 	 * avoids triggering an unnecessary doorbell and more importantly before
1352 	 * triggering the doorbell it makes sure that the PCC channel ownership
1353 	 * is still with OSPM.
1354 	 *   pending_pcc_write_cmd can also be cleared by a different CPU, if
1355 	 * there was a pcc CMD_READ waiting on down_write and it steals the lock
1356 	 * before the pcc CMD_WRITE is completed. send_pcc_cmd checks for this
1357 	 * case during a CMD_READ and if there are pending writes it delivers
1358 	 * the write command before servicing the read command
1359 	 */
1360 	if (CPC_IN_PCC(desired_reg)) {
1361 		if (down_write_trylock(&pcc_ss_data->pcc_lock)) {/* BEGIN Phase-II */
1362 			/* Update only if there are pending write commands */
1363 			if (pcc_ss_data->pending_pcc_write_cmd)
1364 				send_pcc_cmd(pcc_ss_id, CMD_WRITE);
1365 			up_write(&pcc_ss_data->pcc_lock);	/* END Phase-II */
1366 		} else
1367 			/* Wait until pcc_write_cnt is updated by send_pcc_cmd */
1368 			wait_event(pcc_ss_data->pcc_write_wait_q,
1369 				   cpc_desc->write_cmd_id != pcc_ss_data->pcc_write_cnt);
1370 
1371 		/* send_pcc_cmd updates the status in case of failure */
1372 		ret = cpc_desc->write_cmd_status;
1373 	}
1374 	return ret;
1375 }
1376 EXPORT_SYMBOL_GPL(cppc_set_perf);
1377 
1378 /**
1379  * cppc_get_transition_latency - returns frequency transition latency in ns
1380  *
1381  * ACPI CPPC does not explicitly specify how a platform can specify the
1382  * transition latency for performance change requests. The closest we have
1383  * is the timing information from the PCCT tables which provides the info
1384  * on the number and frequency of PCC commands the platform can handle.
1385  *
1386  * If desired_reg is in the SystemMemory or SystemIo ACPI address space,
1387  * then assume there is no latency.
1388  */
cppc_get_transition_latency(int cpu_num)1389 unsigned int cppc_get_transition_latency(int cpu_num)
1390 {
1391 	/*
1392 	 * Expected transition latency is based on the PCCT timing values
1393 	 * Below are definition from ACPI spec:
1394 	 * pcc_nominal- Expected latency to process a command, in microseconds
1395 	 * pcc_mpar   - The maximum number of periodic requests that the subspace
1396 	 *              channel can support, reported in commands per minute. 0
1397 	 *              indicates no limitation.
1398 	 * pcc_mrtt   - The minimum amount of time that OSPM must wait after the
1399 	 *              completion of a command before issuing the next command,
1400 	 *              in microseconds.
1401 	 */
1402 	unsigned int latency_ns = 0;
1403 	struct cpc_desc *cpc_desc;
1404 	struct cpc_register_resource *desired_reg;
1405 	int pcc_ss_id = per_cpu(cpu_pcc_subspace_idx, cpu_num);
1406 	struct cppc_pcc_data *pcc_ss_data;
1407 
1408 	cpc_desc = per_cpu(cpc_desc_ptr, cpu_num);
1409 	if (!cpc_desc)
1410 		return CPUFREQ_ETERNAL;
1411 
1412 	desired_reg = &cpc_desc->cpc_regs[DESIRED_PERF];
1413 	if (CPC_IN_SYSTEM_MEMORY(desired_reg) || CPC_IN_SYSTEM_IO(desired_reg))
1414 		return 0;
1415 	else if (!CPC_IN_PCC(desired_reg))
1416 		return CPUFREQ_ETERNAL;
1417 
1418 	if (pcc_ss_id < 0)
1419 		return CPUFREQ_ETERNAL;
1420 
1421 	pcc_ss_data = pcc_data[pcc_ss_id];
1422 	if (pcc_ss_data->pcc_mpar)
1423 		latency_ns = 60 * (1000 * 1000 * 1000 / pcc_ss_data->pcc_mpar);
1424 
1425 	latency_ns = max(latency_ns, pcc_ss_data->pcc_nominal * 1000);
1426 	latency_ns = max(latency_ns, pcc_ss_data->pcc_mrtt * 1000);
1427 
1428 	return latency_ns;
1429 }
1430 EXPORT_SYMBOL_GPL(cppc_get_transition_latency);
1431