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