USB: misc: iowarrior: fix up header size for USB_DEVICE_ID_CODEMERCS_IOW100
[platform/kernel/linux-starfive.git] / drivers / cpufreq / intel_pstate.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * intel_pstate.c: Native P state management for Intel processors
4  *
5  * (C) Copyright 2012 Intel Corporation
6  * Author: Dirk Brandewie <dirk.j.brandewie@intel.com>
7  */
8
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10
11 #include <linux/kernel.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/module.h>
14 #include <linux/ktime.h>
15 #include <linux/hrtimer.h>
16 #include <linux/tick.h>
17 #include <linux/slab.h>
18 #include <linux/sched/cpufreq.h>
19 #include <linux/list.h>
20 #include <linux/cpu.h>
21 #include <linux/cpufreq.h>
22 #include <linux/sysfs.h>
23 #include <linux/types.h>
24 #include <linux/fs.h>
25 #include <linux/acpi.h>
26 #include <linux/vmalloc.h>
27 #include <linux/pm_qos.h>
28 #include <trace/events/power.h>
29
30 #include <asm/cpu.h>
31 #include <asm/div64.h>
32 #include <asm/msr.h>
33 #include <asm/cpu_device_id.h>
34 #include <asm/cpufeature.h>
35 #include <asm/intel-family.h>
36 #include "../drivers/thermal/intel/thermal_interrupt.h"
37
38 #define INTEL_PSTATE_SAMPLING_INTERVAL  (10 * NSEC_PER_MSEC)
39
40 #define INTEL_CPUFREQ_TRANSITION_LATENCY        20000
41 #define INTEL_CPUFREQ_TRANSITION_DELAY_HWP      5000
42 #define INTEL_CPUFREQ_TRANSITION_DELAY          500
43
44 #ifdef CONFIG_ACPI
45 #include <acpi/processor.h>
46 #include <acpi/cppc_acpi.h>
47 #endif
48
49 #define FRAC_BITS 8
50 #define int_tofp(X) ((int64_t)(X) << FRAC_BITS)
51 #define fp_toint(X) ((X) >> FRAC_BITS)
52
53 #define ONE_EIGHTH_FP ((int64_t)1 << (FRAC_BITS - 3))
54
55 #define EXT_BITS 6
56 #define EXT_FRAC_BITS (EXT_BITS + FRAC_BITS)
57 #define fp_ext_toint(X) ((X) >> EXT_FRAC_BITS)
58 #define int_ext_tofp(X) ((int64_t)(X) << EXT_FRAC_BITS)
59
60 static inline int32_t mul_fp(int32_t x, int32_t y)
61 {
62         return ((int64_t)x * (int64_t)y) >> FRAC_BITS;
63 }
64
65 static inline int32_t div_fp(s64 x, s64 y)
66 {
67         return div64_s64((int64_t)x << FRAC_BITS, y);
68 }
69
70 static inline int ceiling_fp(int32_t x)
71 {
72         int mask, ret;
73
74         ret = fp_toint(x);
75         mask = (1 << FRAC_BITS) - 1;
76         if (x & mask)
77                 ret += 1;
78         return ret;
79 }
80
81 static inline u64 mul_ext_fp(u64 x, u64 y)
82 {
83         return (x * y) >> EXT_FRAC_BITS;
84 }
85
86 static inline u64 div_ext_fp(u64 x, u64 y)
87 {
88         return div64_u64(x << EXT_FRAC_BITS, y);
89 }
90
91 /**
92  * struct sample -      Store performance sample
93  * @core_avg_perf:      Ratio of APERF/MPERF which is the actual average
94  *                      performance during last sample period
95  * @busy_scaled:        Scaled busy value which is used to calculate next
96  *                      P state. This can be different than core_avg_perf
97  *                      to account for cpu idle period
98  * @aperf:              Difference of actual performance frequency clock count
99  *                      read from APERF MSR between last and current sample
100  * @mperf:              Difference of maximum performance frequency clock count
101  *                      read from MPERF MSR between last and current sample
102  * @tsc:                Difference of time stamp counter between last and
103  *                      current sample
104  * @time:               Current time from scheduler
105  *
106  * This structure is used in the cpudata structure to store performance sample
107  * data for choosing next P State.
108  */
109 struct sample {
110         int32_t core_avg_perf;
111         int32_t busy_scaled;
112         u64 aperf;
113         u64 mperf;
114         u64 tsc;
115         u64 time;
116 };
117
118 /**
119  * struct pstate_data - Store P state data
120  * @current_pstate:     Current requested P state
121  * @min_pstate:         Min P state possible for this platform
122  * @max_pstate:         Max P state possible for this platform
123  * @max_pstate_physical:This is physical Max P state for a processor
124  *                      This can be higher than the max_pstate which can
125  *                      be limited by platform thermal design power limits
126  * @perf_ctl_scaling:   PERF_CTL P-state to frequency scaling factor
127  * @scaling:            Scaling factor between performance and frequency
128  * @turbo_pstate:       Max Turbo P state possible for this platform
129  * @min_freq:           @min_pstate frequency in cpufreq units
130  * @max_freq:           @max_pstate frequency in cpufreq units
131  * @turbo_freq:         @turbo_pstate frequency in cpufreq units
132  *
133  * Stores the per cpu model P state limits and current P state.
134  */
135 struct pstate_data {
136         int     current_pstate;
137         int     min_pstate;
138         int     max_pstate;
139         int     max_pstate_physical;
140         int     perf_ctl_scaling;
141         int     scaling;
142         int     turbo_pstate;
143         unsigned int min_freq;
144         unsigned int max_freq;
145         unsigned int turbo_freq;
146 };
147
148 /**
149  * struct vid_data -    Stores voltage information data
150  * @min:                VID data for this platform corresponding to
151  *                      the lowest P state
152  * @max:                VID data corresponding to the highest P State.
153  * @turbo:              VID data for turbo P state
154  * @ratio:              Ratio of (vid max - vid min) /
155  *                      (max P state - Min P State)
156  *
157  * Stores the voltage data for DVFS (Dynamic Voltage and Frequency Scaling)
158  * This data is used in Atom platforms, where in addition to target P state,
159  * the voltage data needs to be specified to select next P State.
160  */
161 struct vid_data {
162         int min;
163         int max;
164         int turbo;
165         int32_t ratio;
166 };
167
168 /**
169  * struct global_params - Global parameters, mostly tunable via sysfs.
170  * @no_turbo:           Whether or not to use turbo P-states.
171  * @turbo_disabled:     Whether or not turbo P-states are available at all,
172  *                      based on the MSR_IA32_MISC_ENABLE value and whether or
173  *                      not the maximum reported turbo P-state is different from
174  *                      the maximum reported non-turbo one.
175  * @turbo_disabled_mf:  The @turbo_disabled value reflected by cpuinfo.max_freq.
176  * @min_perf_pct:       Minimum capacity limit in percent of the maximum turbo
177  *                      P-state capacity.
178  * @max_perf_pct:       Maximum capacity limit in percent of the maximum turbo
179  *                      P-state capacity.
180  */
181 struct global_params {
182         bool no_turbo;
183         bool turbo_disabled;
184         bool turbo_disabled_mf;
185         int max_perf_pct;
186         int min_perf_pct;
187 };
188
189 /**
190  * struct cpudata -     Per CPU instance data storage
191  * @cpu:                CPU number for this instance data
192  * @policy:             CPUFreq policy value
193  * @update_util:        CPUFreq utility callback information
194  * @update_util_set:    CPUFreq utility callback is set
195  * @iowait_boost:       iowait-related boost fraction
196  * @last_update:        Time of the last update.
197  * @pstate:             Stores P state limits for this CPU
198  * @vid:                Stores VID limits for this CPU
199  * @last_sample_time:   Last Sample time
200  * @aperf_mperf_shift:  APERF vs MPERF counting frequency difference
201  * @prev_aperf:         Last APERF value read from APERF MSR
202  * @prev_mperf:         Last MPERF value read from MPERF MSR
203  * @prev_tsc:           Last timestamp counter (TSC) value
204  * @prev_cummulative_iowait: IO Wait time difference from last and
205  *                      current sample
206  * @sample:             Storage for storing last Sample data
207  * @min_perf_ratio:     Minimum capacity in terms of PERF or HWP ratios
208  * @max_perf_ratio:     Maximum capacity in terms of PERF or HWP ratios
209  * @acpi_perf_data:     Stores ACPI perf information read from _PSS
210  * @valid_pss_table:    Set to true for valid ACPI _PSS entries found
211  * @epp_powersave:      Last saved HWP energy performance preference
212  *                      (EPP) or energy performance bias (EPB),
213  *                      when policy switched to performance
214  * @epp_policy:         Last saved policy used to set EPP/EPB
215  * @epp_default:        Power on default HWP energy performance
216  *                      preference/bias
217  * @epp_cached          Cached HWP energy-performance preference value
218  * @hwp_req_cached:     Cached value of the last HWP Request MSR
219  * @hwp_cap_cached:     Cached value of the last HWP Capabilities MSR
220  * @last_io_update:     Last time when IO wake flag was set
221  * @sched_flags:        Store scheduler flags for possible cross CPU update
222  * @hwp_boost_min:      Last HWP boosted min performance
223  * @suspended:          Whether or not the driver has been suspended.
224  * @hwp_notify_work:    workqueue for HWP notifications.
225  *
226  * This structure stores per CPU instance data for all CPUs.
227  */
228 struct cpudata {
229         int cpu;
230
231         unsigned int policy;
232         struct update_util_data update_util;
233         bool   update_util_set;
234
235         struct pstate_data pstate;
236         struct vid_data vid;
237
238         u64     last_update;
239         u64     last_sample_time;
240         u64     aperf_mperf_shift;
241         u64     prev_aperf;
242         u64     prev_mperf;
243         u64     prev_tsc;
244         u64     prev_cummulative_iowait;
245         struct sample sample;
246         int32_t min_perf_ratio;
247         int32_t max_perf_ratio;
248 #ifdef CONFIG_ACPI
249         struct acpi_processor_performance acpi_perf_data;
250         bool valid_pss_table;
251 #endif
252         unsigned int iowait_boost;
253         s16 epp_powersave;
254         s16 epp_policy;
255         s16 epp_default;
256         s16 epp_cached;
257         u64 hwp_req_cached;
258         u64 hwp_cap_cached;
259         u64 last_io_update;
260         unsigned int sched_flags;
261         u32 hwp_boost_min;
262         bool suspended;
263         struct delayed_work hwp_notify_work;
264 };
265
266 static struct cpudata **all_cpu_data;
267
268 /**
269  * struct pstate_funcs - Per CPU model specific callbacks
270  * @get_max:            Callback to get maximum non turbo effective P state
271  * @get_max_physical:   Callback to get maximum non turbo physical P state
272  * @get_min:            Callback to get minimum P state
273  * @get_turbo:          Callback to get turbo P state
274  * @get_scaling:        Callback to get frequency scaling factor
275  * @get_cpu_scaling:    Get frequency scaling factor for a given cpu
276  * @get_aperf_mperf_shift: Callback to get the APERF vs MPERF frequency difference
277  * @get_val:            Callback to convert P state to actual MSR write value
278  * @get_vid:            Callback to get VID data for Atom platforms
279  *
280  * Core and Atom CPU models have different way to get P State limits. This
281  * structure is used to store those callbacks.
282  */
283 struct pstate_funcs {
284         int (*get_max)(int cpu);
285         int (*get_max_physical)(int cpu);
286         int (*get_min)(int cpu);
287         int (*get_turbo)(int cpu);
288         int (*get_scaling)(void);
289         int (*get_cpu_scaling)(int cpu);
290         int (*get_aperf_mperf_shift)(void);
291         u64 (*get_val)(struct cpudata*, int pstate);
292         void (*get_vid)(struct cpudata *);
293 };
294
295 static struct pstate_funcs pstate_funcs __read_mostly;
296
297 static int hwp_active __read_mostly;
298 static int hwp_mode_bdw __read_mostly;
299 static bool per_cpu_limits __read_mostly;
300 static bool hwp_boost __read_mostly;
301
302 static struct cpufreq_driver *intel_pstate_driver __read_mostly;
303
304 #ifdef CONFIG_ACPI
305 static bool acpi_ppc;
306 #endif
307
308 static struct global_params global;
309
310 static DEFINE_MUTEX(intel_pstate_driver_lock);
311 static DEFINE_MUTEX(intel_pstate_limits_lock);
312
313 #ifdef CONFIG_ACPI
314
315 static bool intel_pstate_acpi_pm_profile_server(void)
316 {
317         if (acpi_gbl_FADT.preferred_profile == PM_ENTERPRISE_SERVER ||
318             acpi_gbl_FADT.preferred_profile == PM_PERFORMANCE_SERVER)
319                 return true;
320
321         return false;
322 }
323
324 static bool intel_pstate_get_ppc_enable_status(void)
325 {
326         if (intel_pstate_acpi_pm_profile_server())
327                 return true;
328
329         return acpi_ppc;
330 }
331
332 #ifdef CONFIG_ACPI_CPPC_LIB
333
334 /* The work item is needed to avoid CPU hotplug locking issues */
335 static void intel_pstste_sched_itmt_work_fn(struct work_struct *work)
336 {
337         sched_set_itmt_support();
338 }
339
340 static DECLARE_WORK(sched_itmt_work, intel_pstste_sched_itmt_work_fn);
341
342 #define CPPC_MAX_PERF   U8_MAX
343
344 static void intel_pstate_set_itmt_prio(int cpu)
345 {
346         struct cppc_perf_caps cppc_perf;
347         static u32 max_highest_perf = 0, min_highest_perf = U32_MAX;
348         int ret;
349
350         ret = cppc_get_perf_caps(cpu, &cppc_perf);
351         if (ret)
352                 return;
353
354         /*
355          * On some systems with overclocking enabled, CPPC.highest_perf is hardcoded to 0xff.
356          * In this case we can't use CPPC.highest_perf to enable ITMT.
357          * In this case we can look at MSR_HWP_CAPABILITIES bits [8:0] to decide.
358          */
359         if (cppc_perf.highest_perf == CPPC_MAX_PERF)
360                 cppc_perf.highest_perf = HWP_HIGHEST_PERF(READ_ONCE(all_cpu_data[cpu]->hwp_cap_cached));
361
362         /*
363          * The priorities can be set regardless of whether or not
364          * sched_set_itmt_support(true) has been called and it is valid to
365          * update them at any time after it has been called.
366          */
367         sched_set_itmt_core_prio(cppc_perf.highest_perf, cpu);
368
369         if (max_highest_perf <= min_highest_perf) {
370                 if (cppc_perf.highest_perf > max_highest_perf)
371                         max_highest_perf = cppc_perf.highest_perf;
372
373                 if (cppc_perf.highest_perf < min_highest_perf)
374                         min_highest_perf = cppc_perf.highest_perf;
375
376                 if (max_highest_perf > min_highest_perf) {
377                         /*
378                          * This code can be run during CPU online under the
379                          * CPU hotplug locks, so sched_set_itmt_support()
380                          * cannot be called from here.  Queue up a work item
381                          * to invoke it.
382                          */
383                         schedule_work(&sched_itmt_work);
384                 }
385         }
386 }
387
388 static int intel_pstate_get_cppc_guaranteed(int cpu)
389 {
390         struct cppc_perf_caps cppc_perf;
391         int ret;
392
393         ret = cppc_get_perf_caps(cpu, &cppc_perf);
394         if (ret)
395                 return ret;
396
397         if (cppc_perf.guaranteed_perf)
398                 return cppc_perf.guaranteed_perf;
399
400         return cppc_perf.nominal_perf;
401 }
402 #else /* CONFIG_ACPI_CPPC_LIB */
403 static inline void intel_pstate_set_itmt_prio(int cpu)
404 {
405 }
406 #endif /* CONFIG_ACPI_CPPC_LIB */
407
408 static void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
409 {
410         struct cpudata *cpu;
411         int ret;
412         int i;
413
414         if (hwp_active) {
415                 intel_pstate_set_itmt_prio(policy->cpu);
416                 return;
417         }
418
419         if (!intel_pstate_get_ppc_enable_status())
420                 return;
421
422         cpu = all_cpu_data[policy->cpu];
423
424         ret = acpi_processor_register_performance(&cpu->acpi_perf_data,
425                                                   policy->cpu);
426         if (ret)
427                 return;
428
429         /*
430          * Check if the control value in _PSS is for PERF_CTL MSR, which should
431          * guarantee that the states returned by it map to the states in our
432          * list directly.
433          */
434         if (cpu->acpi_perf_data.control_register.space_id !=
435                                                 ACPI_ADR_SPACE_FIXED_HARDWARE)
436                 goto err;
437
438         /*
439          * If there is only one entry _PSS, simply ignore _PSS and continue as
440          * usual without taking _PSS into account
441          */
442         if (cpu->acpi_perf_data.state_count < 2)
443                 goto err;
444
445         pr_debug("CPU%u - ACPI _PSS perf data\n", policy->cpu);
446         for (i = 0; i < cpu->acpi_perf_data.state_count; i++) {
447                 pr_debug("     %cP%d: %u MHz, %u mW, 0x%x\n",
448                          (i == cpu->acpi_perf_data.state ? '*' : ' '), i,
449                          (u32) cpu->acpi_perf_data.states[i].core_frequency,
450                          (u32) cpu->acpi_perf_data.states[i].power,
451                          (u32) cpu->acpi_perf_data.states[i].control);
452         }
453
454         /*
455          * The _PSS table doesn't contain whole turbo frequency range.
456          * This just contains +1 MHZ above the max non turbo frequency,
457          * with control value corresponding to max turbo ratio. But
458          * when cpufreq set policy is called, it will call with this
459          * max frequency, which will cause a reduced performance as
460          * this driver uses real max turbo frequency as the max
461          * frequency. So correct this frequency in _PSS table to
462          * correct max turbo frequency based on the turbo state.
463          * Also need to convert to MHz as _PSS freq is in MHz.
464          */
465         if (!global.turbo_disabled)
466                 cpu->acpi_perf_data.states[0].core_frequency =
467                                         policy->cpuinfo.max_freq / 1000;
468         cpu->valid_pss_table = true;
469         pr_debug("_PPC limits will be enforced\n");
470
471         return;
472
473  err:
474         cpu->valid_pss_table = false;
475         acpi_processor_unregister_performance(policy->cpu);
476 }
477
478 static void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
479 {
480         struct cpudata *cpu;
481
482         cpu = all_cpu_data[policy->cpu];
483         if (!cpu->valid_pss_table)
484                 return;
485
486         acpi_processor_unregister_performance(policy->cpu);
487 }
488 #else /* CONFIG_ACPI */
489 static inline void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
490 {
491 }
492
493 static inline void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
494 {
495 }
496
497 static inline bool intel_pstate_acpi_pm_profile_server(void)
498 {
499         return false;
500 }
501 #endif /* CONFIG_ACPI */
502
503 #ifndef CONFIG_ACPI_CPPC_LIB
504 static inline int intel_pstate_get_cppc_guaranteed(int cpu)
505 {
506         return -ENOTSUPP;
507 }
508 #endif /* CONFIG_ACPI_CPPC_LIB */
509
510 /**
511  * intel_pstate_hybrid_hwp_adjust - Calibrate HWP performance levels.
512  * @cpu: Target CPU.
513  *
514  * On hybrid processors, HWP may expose more performance levels than there are
515  * P-states accessible through the PERF_CTL interface.  If that happens, the
516  * scaling factor between HWP performance levels and CPU frequency will be less
517  * than the scaling factor between P-state values and CPU frequency.
518  *
519  * In that case, adjust the CPU parameters used in computations accordingly.
520  */
521 static void intel_pstate_hybrid_hwp_adjust(struct cpudata *cpu)
522 {
523         int perf_ctl_max_phys = cpu->pstate.max_pstate_physical;
524         int perf_ctl_scaling = cpu->pstate.perf_ctl_scaling;
525         int perf_ctl_turbo = pstate_funcs.get_turbo(cpu->cpu);
526         int scaling = cpu->pstate.scaling;
527
528         pr_debug("CPU%d: perf_ctl_max_phys = %d\n", cpu->cpu, perf_ctl_max_phys);
529         pr_debug("CPU%d: perf_ctl_turbo = %d\n", cpu->cpu, perf_ctl_turbo);
530         pr_debug("CPU%d: perf_ctl_scaling = %d\n", cpu->cpu, perf_ctl_scaling);
531         pr_debug("CPU%d: HWP_CAP guaranteed = %d\n", cpu->cpu, cpu->pstate.max_pstate);
532         pr_debug("CPU%d: HWP_CAP highest = %d\n", cpu->cpu, cpu->pstate.turbo_pstate);
533         pr_debug("CPU%d: HWP-to-frequency scaling factor: %d\n", cpu->cpu, scaling);
534
535         cpu->pstate.turbo_freq = rounddown(cpu->pstate.turbo_pstate * scaling,
536                                            perf_ctl_scaling);
537         cpu->pstate.max_freq = rounddown(cpu->pstate.max_pstate * scaling,
538                                          perf_ctl_scaling);
539
540         cpu->pstate.max_pstate_physical =
541                         DIV_ROUND_UP(perf_ctl_max_phys * perf_ctl_scaling,
542                                      scaling);
543
544         cpu->pstate.min_freq = cpu->pstate.min_pstate * perf_ctl_scaling;
545         /*
546          * Cast the min P-state value retrieved via pstate_funcs.get_min() to
547          * the effective range of HWP performance levels.
548          */
549         cpu->pstate.min_pstate = DIV_ROUND_UP(cpu->pstate.min_freq, scaling);
550 }
551
552 static inline void update_turbo_state(void)
553 {
554         u64 misc_en;
555         struct cpudata *cpu;
556
557         cpu = all_cpu_data[0];
558         rdmsrl(MSR_IA32_MISC_ENABLE, misc_en);
559         global.turbo_disabled =
560                 (misc_en & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ||
561                  cpu->pstate.max_pstate == cpu->pstate.turbo_pstate);
562 }
563
564 static int min_perf_pct_min(void)
565 {
566         struct cpudata *cpu = all_cpu_data[0];
567         int turbo_pstate = cpu->pstate.turbo_pstate;
568
569         return turbo_pstate ?
570                 (cpu->pstate.min_pstate * 100 / turbo_pstate) : 0;
571 }
572
573 static s16 intel_pstate_get_epb(struct cpudata *cpu_data)
574 {
575         u64 epb;
576         int ret;
577
578         if (!boot_cpu_has(X86_FEATURE_EPB))
579                 return -ENXIO;
580
581         ret = rdmsrl_on_cpu(cpu_data->cpu, MSR_IA32_ENERGY_PERF_BIAS, &epb);
582         if (ret)
583                 return (s16)ret;
584
585         return (s16)(epb & 0x0f);
586 }
587
588 static s16 intel_pstate_get_epp(struct cpudata *cpu_data, u64 hwp_req_data)
589 {
590         s16 epp;
591
592         if (boot_cpu_has(X86_FEATURE_HWP_EPP)) {
593                 /*
594                  * When hwp_req_data is 0, means that caller didn't read
595                  * MSR_HWP_REQUEST, so need to read and get EPP.
596                  */
597                 if (!hwp_req_data) {
598                         epp = rdmsrl_on_cpu(cpu_data->cpu, MSR_HWP_REQUEST,
599                                             &hwp_req_data);
600                         if (epp)
601                                 return epp;
602                 }
603                 epp = (hwp_req_data >> 24) & 0xff;
604         } else {
605                 /* When there is no EPP present, HWP uses EPB settings */
606                 epp = intel_pstate_get_epb(cpu_data);
607         }
608
609         return epp;
610 }
611
612 static int intel_pstate_set_epb(int cpu, s16 pref)
613 {
614         u64 epb;
615         int ret;
616
617         if (!boot_cpu_has(X86_FEATURE_EPB))
618                 return -ENXIO;
619
620         ret = rdmsrl_on_cpu(cpu, MSR_IA32_ENERGY_PERF_BIAS, &epb);
621         if (ret)
622                 return ret;
623
624         epb = (epb & ~0x0f) | pref;
625         wrmsrl_on_cpu(cpu, MSR_IA32_ENERGY_PERF_BIAS, epb);
626
627         return 0;
628 }
629
630 /*
631  * EPP/EPB display strings corresponding to EPP index in the
632  * energy_perf_strings[]
633  *      index           String
634  *-------------------------------------
635  *      0               default
636  *      1               performance
637  *      2               balance_performance
638  *      3               balance_power
639  *      4               power
640  */
641
642 enum energy_perf_value_index {
643         EPP_INDEX_DEFAULT = 0,
644         EPP_INDEX_PERFORMANCE,
645         EPP_INDEX_BALANCE_PERFORMANCE,
646         EPP_INDEX_BALANCE_POWERSAVE,
647         EPP_INDEX_POWERSAVE,
648 };
649
650 static const char * const energy_perf_strings[] = {
651         [EPP_INDEX_DEFAULT] = "default",
652         [EPP_INDEX_PERFORMANCE] = "performance",
653         [EPP_INDEX_BALANCE_PERFORMANCE] = "balance_performance",
654         [EPP_INDEX_BALANCE_POWERSAVE] = "balance_power",
655         [EPP_INDEX_POWERSAVE] = "power",
656         NULL
657 };
658 static unsigned int epp_values[] = {
659         [EPP_INDEX_DEFAULT] = 0, /* Unused index */
660         [EPP_INDEX_PERFORMANCE] = HWP_EPP_PERFORMANCE,
661         [EPP_INDEX_BALANCE_PERFORMANCE] = HWP_EPP_BALANCE_PERFORMANCE,
662         [EPP_INDEX_BALANCE_POWERSAVE] = HWP_EPP_BALANCE_POWERSAVE,
663         [EPP_INDEX_POWERSAVE] = HWP_EPP_POWERSAVE,
664 };
665
666 static int intel_pstate_get_energy_pref_index(struct cpudata *cpu_data, int *raw_epp)
667 {
668         s16 epp;
669         int index = -EINVAL;
670
671         *raw_epp = 0;
672         epp = intel_pstate_get_epp(cpu_data, 0);
673         if (epp < 0)
674                 return epp;
675
676         if (boot_cpu_has(X86_FEATURE_HWP_EPP)) {
677                 if (epp == epp_values[EPP_INDEX_PERFORMANCE])
678                         return EPP_INDEX_PERFORMANCE;
679                 if (epp == epp_values[EPP_INDEX_BALANCE_PERFORMANCE])
680                         return EPP_INDEX_BALANCE_PERFORMANCE;
681                 if (epp == epp_values[EPP_INDEX_BALANCE_POWERSAVE])
682                         return EPP_INDEX_BALANCE_POWERSAVE;
683                 if (epp == epp_values[EPP_INDEX_POWERSAVE])
684                         return EPP_INDEX_POWERSAVE;
685                 *raw_epp = epp;
686                 return 0;
687         } else if (boot_cpu_has(X86_FEATURE_EPB)) {
688                 /*
689                  * Range:
690                  *      0x00-0x03       :       Performance
691                  *      0x04-0x07       :       Balance performance
692                  *      0x08-0x0B       :       Balance power
693                  *      0x0C-0x0F       :       Power
694                  * The EPB is a 4 bit value, but our ranges restrict the
695                  * value which can be set. Here only using top two bits
696                  * effectively.
697                  */
698                 index = (epp >> 2) + 1;
699         }
700
701         return index;
702 }
703
704 static int intel_pstate_set_epp(struct cpudata *cpu, u32 epp)
705 {
706         int ret;
707
708         /*
709          * Use the cached HWP Request MSR value, because in the active mode the
710          * register itself may be updated by intel_pstate_hwp_boost_up() or
711          * intel_pstate_hwp_boost_down() at any time.
712          */
713         u64 value = READ_ONCE(cpu->hwp_req_cached);
714
715         value &= ~GENMASK_ULL(31, 24);
716         value |= (u64)epp << 24;
717         /*
718          * The only other updater of hwp_req_cached in the active mode,
719          * intel_pstate_hwp_set(), is called under the same lock as this
720          * function, so it cannot run in parallel with the update below.
721          */
722         WRITE_ONCE(cpu->hwp_req_cached, value);
723         ret = wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
724         if (!ret)
725                 cpu->epp_cached = epp;
726
727         return ret;
728 }
729
730 static int intel_pstate_set_energy_pref_index(struct cpudata *cpu_data,
731                                               int pref_index, bool use_raw,
732                                               u32 raw_epp)
733 {
734         int epp = -EINVAL;
735         int ret;
736
737         if (!pref_index)
738                 epp = cpu_data->epp_default;
739
740         if (boot_cpu_has(X86_FEATURE_HWP_EPP)) {
741                 if (use_raw)
742                         epp = raw_epp;
743                 else if (epp == -EINVAL)
744                         epp = epp_values[pref_index];
745
746                 /*
747                  * To avoid confusion, refuse to set EPP to any values different
748                  * from 0 (performance) if the current policy is "performance",
749                  * because those values would be overridden.
750                  */
751                 if (epp > 0 && cpu_data->policy == CPUFREQ_POLICY_PERFORMANCE)
752                         return -EBUSY;
753
754                 ret = intel_pstate_set_epp(cpu_data, epp);
755         } else {
756                 if (epp == -EINVAL)
757                         epp = (pref_index - 1) << 2;
758                 ret = intel_pstate_set_epb(cpu_data->cpu, epp);
759         }
760
761         return ret;
762 }
763
764 static ssize_t show_energy_performance_available_preferences(
765                                 struct cpufreq_policy *policy, char *buf)
766 {
767         int i = 0;
768         int ret = 0;
769
770         while (energy_perf_strings[i] != NULL)
771                 ret += sprintf(&buf[ret], "%s ", energy_perf_strings[i++]);
772
773         ret += sprintf(&buf[ret], "\n");
774
775         return ret;
776 }
777
778 cpufreq_freq_attr_ro(energy_performance_available_preferences);
779
780 static struct cpufreq_driver intel_pstate;
781
782 static ssize_t store_energy_performance_preference(
783                 struct cpufreq_policy *policy, const char *buf, size_t count)
784 {
785         struct cpudata *cpu = all_cpu_data[policy->cpu];
786         char str_preference[21];
787         bool raw = false;
788         ssize_t ret;
789         u32 epp = 0;
790
791         ret = sscanf(buf, "%20s", str_preference);
792         if (ret != 1)
793                 return -EINVAL;
794
795         ret = match_string(energy_perf_strings, -1, str_preference);
796         if (ret < 0) {
797                 if (!boot_cpu_has(X86_FEATURE_HWP_EPP))
798                         return ret;
799
800                 ret = kstrtouint(buf, 10, &epp);
801                 if (ret)
802                         return ret;
803
804                 if (epp > 255)
805                         return -EINVAL;
806
807                 raw = true;
808         }
809
810         /*
811          * This function runs with the policy R/W semaphore held, which
812          * guarantees that the driver pointer will not change while it is
813          * running.
814          */
815         if (!intel_pstate_driver)
816                 return -EAGAIN;
817
818         mutex_lock(&intel_pstate_limits_lock);
819
820         if (intel_pstate_driver == &intel_pstate) {
821                 ret = intel_pstate_set_energy_pref_index(cpu, ret, raw, epp);
822         } else {
823                 /*
824                  * In the passive mode the governor needs to be stopped on the
825                  * target CPU before the EPP update and restarted after it,
826                  * which is super-heavy-weight, so make sure it is worth doing
827                  * upfront.
828                  */
829                 if (!raw)
830                         epp = ret ? epp_values[ret] : cpu->epp_default;
831
832                 if (cpu->epp_cached != epp) {
833                         int err;
834
835                         cpufreq_stop_governor(policy);
836                         ret = intel_pstate_set_epp(cpu, epp);
837                         err = cpufreq_start_governor(policy);
838                         if (!ret)
839                                 ret = err;
840                 }
841         }
842
843         mutex_unlock(&intel_pstate_limits_lock);
844
845         return ret ?: count;
846 }
847
848 static ssize_t show_energy_performance_preference(
849                                 struct cpufreq_policy *policy, char *buf)
850 {
851         struct cpudata *cpu_data = all_cpu_data[policy->cpu];
852         int preference, raw_epp;
853
854         preference = intel_pstate_get_energy_pref_index(cpu_data, &raw_epp);
855         if (preference < 0)
856                 return preference;
857
858         if (raw_epp)
859                 return  sprintf(buf, "%d\n", raw_epp);
860         else
861                 return  sprintf(buf, "%s\n", energy_perf_strings[preference]);
862 }
863
864 cpufreq_freq_attr_rw(energy_performance_preference);
865
866 static ssize_t show_base_frequency(struct cpufreq_policy *policy, char *buf)
867 {
868         struct cpudata *cpu = all_cpu_data[policy->cpu];
869         int ratio, freq;
870
871         ratio = intel_pstate_get_cppc_guaranteed(policy->cpu);
872         if (ratio <= 0) {
873                 u64 cap;
874
875                 rdmsrl_on_cpu(policy->cpu, MSR_HWP_CAPABILITIES, &cap);
876                 ratio = HWP_GUARANTEED_PERF(cap);
877         }
878
879         freq = ratio * cpu->pstate.scaling;
880         if (cpu->pstate.scaling != cpu->pstate.perf_ctl_scaling)
881                 freq = rounddown(freq, cpu->pstate.perf_ctl_scaling);
882
883         return sprintf(buf, "%d\n", freq);
884 }
885
886 cpufreq_freq_attr_ro(base_frequency);
887
888 static struct freq_attr *hwp_cpufreq_attrs[] = {
889         &energy_performance_preference,
890         &energy_performance_available_preferences,
891         &base_frequency,
892         NULL,
893 };
894
895 static void __intel_pstate_get_hwp_cap(struct cpudata *cpu)
896 {
897         u64 cap;
898
899         rdmsrl_on_cpu(cpu->cpu, MSR_HWP_CAPABILITIES, &cap);
900         WRITE_ONCE(cpu->hwp_cap_cached, cap);
901         cpu->pstate.max_pstate = HWP_GUARANTEED_PERF(cap);
902         cpu->pstate.turbo_pstate = HWP_HIGHEST_PERF(cap);
903 }
904
905 static void intel_pstate_get_hwp_cap(struct cpudata *cpu)
906 {
907         int scaling = cpu->pstate.scaling;
908
909         __intel_pstate_get_hwp_cap(cpu);
910
911         cpu->pstate.max_freq = cpu->pstate.max_pstate * scaling;
912         cpu->pstate.turbo_freq = cpu->pstate.turbo_pstate * scaling;
913         if (scaling != cpu->pstate.perf_ctl_scaling) {
914                 int perf_ctl_scaling = cpu->pstate.perf_ctl_scaling;
915
916                 cpu->pstate.max_freq = rounddown(cpu->pstate.max_freq,
917                                                  perf_ctl_scaling);
918                 cpu->pstate.turbo_freq = rounddown(cpu->pstate.turbo_freq,
919                                                    perf_ctl_scaling);
920         }
921 }
922
923 static void intel_pstate_hwp_set(unsigned int cpu)
924 {
925         struct cpudata *cpu_data = all_cpu_data[cpu];
926         int max, min;
927         u64 value;
928         s16 epp;
929
930         max = cpu_data->max_perf_ratio;
931         min = cpu_data->min_perf_ratio;
932
933         if (cpu_data->policy == CPUFREQ_POLICY_PERFORMANCE)
934                 min = max;
935
936         rdmsrl_on_cpu(cpu, MSR_HWP_REQUEST, &value);
937
938         value &= ~HWP_MIN_PERF(~0L);
939         value |= HWP_MIN_PERF(min);
940
941         value &= ~HWP_MAX_PERF(~0L);
942         value |= HWP_MAX_PERF(max);
943
944         if (cpu_data->epp_policy == cpu_data->policy)
945                 goto skip_epp;
946
947         cpu_data->epp_policy = cpu_data->policy;
948
949         if (cpu_data->policy == CPUFREQ_POLICY_PERFORMANCE) {
950                 epp = intel_pstate_get_epp(cpu_data, value);
951                 cpu_data->epp_powersave = epp;
952                 /* If EPP read was failed, then don't try to write */
953                 if (epp < 0)
954                         goto skip_epp;
955
956                 epp = 0;
957         } else {
958                 /* skip setting EPP, when saved value is invalid */
959                 if (cpu_data->epp_powersave < 0)
960                         goto skip_epp;
961
962                 /*
963                  * No need to restore EPP when it is not zero. This
964                  * means:
965                  *  - Policy is not changed
966                  *  - user has manually changed
967                  *  - Error reading EPB
968                  */
969                 epp = intel_pstate_get_epp(cpu_data, value);
970                 if (epp)
971                         goto skip_epp;
972
973                 epp = cpu_data->epp_powersave;
974         }
975         if (boot_cpu_has(X86_FEATURE_HWP_EPP)) {
976                 value &= ~GENMASK_ULL(31, 24);
977                 value |= (u64)epp << 24;
978         } else {
979                 intel_pstate_set_epb(cpu, epp);
980         }
981 skip_epp:
982         WRITE_ONCE(cpu_data->hwp_req_cached, value);
983         wrmsrl_on_cpu(cpu, MSR_HWP_REQUEST, value);
984 }
985
986 static void intel_pstate_disable_hwp_interrupt(struct cpudata *cpudata);
987
988 static void intel_pstate_hwp_offline(struct cpudata *cpu)
989 {
990         u64 value = READ_ONCE(cpu->hwp_req_cached);
991         int min_perf;
992
993         intel_pstate_disable_hwp_interrupt(cpu);
994
995         if (boot_cpu_has(X86_FEATURE_HWP_EPP)) {
996                 /*
997                  * In case the EPP has been set to "performance" by the
998                  * active mode "performance" scaling algorithm, replace that
999                  * temporary value with the cached EPP one.
1000                  */
1001                 value &= ~GENMASK_ULL(31, 24);
1002                 value |= HWP_ENERGY_PERF_PREFERENCE(cpu->epp_cached);
1003                 /*
1004                  * However, make sure that EPP will be set to "performance" when
1005                  * the CPU is brought back online again and the "performance"
1006                  * scaling algorithm is still in effect.
1007                  */
1008                 cpu->epp_policy = CPUFREQ_POLICY_UNKNOWN;
1009         }
1010
1011         /*
1012          * Clear the desired perf field in the cached HWP request value to
1013          * prevent nonzero desired values from being leaked into the active
1014          * mode.
1015          */
1016         value &= ~HWP_DESIRED_PERF(~0L);
1017         WRITE_ONCE(cpu->hwp_req_cached, value);
1018
1019         value &= ~GENMASK_ULL(31, 0);
1020         min_perf = HWP_LOWEST_PERF(READ_ONCE(cpu->hwp_cap_cached));
1021
1022         /* Set hwp_max = hwp_min */
1023         value |= HWP_MAX_PERF(min_perf);
1024         value |= HWP_MIN_PERF(min_perf);
1025
1026         /* Set EPP to min */
1027         if (boot_cpu_has(X86_FEATURE_HWP_EPP))
1028                 value |= HWP_ENERGY_PERF_PREFERENCE(HWP_EPP_POWERSAVE);
1029
1030         wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
1031 }
1032
1033 #define POWER_CTL_EE_ENABLE     1
1034 #define POWER_CTL_EE_DISABLE    2
1035
1036 static int power_ctl_ee_state;
1037
1038 static void set_power_ctl_ee_state(bool input)
1039 {
1040         u64 power_ctl;
1041
1042         mutex_lock(&intel_pstate_driver_lock);
1043         rdmsrl(MSR_IA32_POWER_CTL, power_ctl);
1044         if (input) {
1045                 power_ctl &= ~BIT(MSR_IA32_POWER_CTL_BIT_EE);
1046                 power_ctl_ee_state = POWER_CTL_EE_ENABLE;
1047         } else {
1048                 power_ctl |= BIT(MSR_IA32_POWER_CTL_BIT_EE);
1049                 power_ctl_ee_state = POWER_CTL_EE_DISABLE;
1050         }
1051         wrmsrl(MSR_IA32_POWER_CTL, power_ctl);
1052         mutex_unlock(&intel_pstate_driver_lock);
1053 }
1054
1055 static void intel_pstate_hwp_enable(struct cpudata *cpudata);
1056
1057 static void intel_pstate_hwp_reenable(struct cpudata *cpu)
1058 {
1059         intel_pstate_hwp_enable(cpu);
1060         wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, READ_ONCE(cpu->hwp_req_cached));
1061 }
1062
1063 static int intel_pstate_suspend(struct cpufreq_policy *policy)
1064 {
1065         struct cpudata *cpu = all_cpu_data[policy->cpu];
1066
1067         pr_debug("CPU %d suspending\n", cpu->cpu);
1068
1069         cpu->suspended = true;
1070
1071         /* disable HWP interrupt and cancel any pending work */
1072         intel_pstate_disable_hwp_interrupt(cpu);
1073
1074         return 0;
1075 }
1076
1077 static int intel_pstate_resume(struct cpufreq_policy *policy)
1078 {
1079         struct cpudata *cpu = all_cpu_data[policy->cpu];
1080
1081         pr_debug("CPU %d resuming\n", cpu->cpu);
1082
1083         /* Only restore if the system default is changed */
1084         if (power_ctl_ee_state == POWER_CTL_EE_ENABLE)
1085                 set_power_ctl_ee_state(true);
1086         else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE)
1087                 set_power_ctl_ee_state(false);
1088
1089         if (cpu->suspended && hwp_active) {
1090                 mutex_lock(&intel_pstate_limits_lock);
1091
1092                 /* Re-enable HWP, because "online" has not done that. */
1093                 intel_pstate_hwp_reenable(cpu);
1094
1095                 mutex_unlock(&intel_pstate_limits_lock);
1096         }
1097
1098         cpu->suspended = false;
1099
1100         return 0;
1101 }
1102
1103 static void intel_pstate_update_policies(void)
1104 {
1105         int cpu;
1106
1107         for_each_possible_cpu(cpu)
1108                 cpufreq_update_policy(cpu);
1109 }
1110
1111 static void __intel_pstate_update_max_freq(struct cpudata *cpudata,
1112                                            struct cpufreq_policy *policy)
1113 {
1114         policy->cpuinfo.max_freq = global.turbo_disabled_mf ?
1115                         cpudata->pstate.max_freq : cpudata->pstate.turbo_freq;
1116         refresh_frequency_limits(policy);
1117 }
1118
1119 static void intel_pstate_update_max_freq(unsigned int cpu)
1120 {
1121         struct cpufreq_policy *policy = cpufreq_cpu_acquire(cpu);
1122
1123         if (!policy)
1124                 return;
1125
1126         __intel_pstate_update_max_freq(all_cpu_data[cpu], policy);
1127
1128         cpufreq_cpu_release(policy);
1129 }
1130
1131 static void intel_pstate_update_limits(unsigned int cpu)
1132 {
1133         mutex_lock(&intel_pstate_driver_lock);
1134
1135         update_turbo_state();
1136         /*
1137          * If turbo has been turned on or off globally, policy limits for
1138          * all CPUs need to be updated to reflect that.
1139          */
1140         if (global.turbo_disabled_mf != global.turbo_disabled) {
1141                 global.turbo_disabled_mf = global.turbo_disabled;
1142                 arch_set_max_freq_ratio(global.turbo_disabled);
1143                 for_each_possible_cpu(cpu)
1144                         intel_pstate_update_max_freq(cpu);
1145         } else {
1146                 cpufreq_update_policy(cpu);
1147         }
1148
1149         mutex_unlock(&intel_pstate_driver_lock);
1150 }
1151
1152 /************************** sysfs begin ************************/
1153 #define show_one(file_name, object)                                     \
1154         static ssize_t show_##file_name                                 \
1155         (struct kobject *kobj, struct kobj_attribute *attr, char *buf)  \
1156         {                                                               \
1157                 return sprintf(buf, "%u\n", global.object);             \
1158         }
1159
1160 static ssize_t intel_pstate_show_status(char *buf);
1161 static int intel_pstate_update_status(const char *buf, size_t size);
1162
1163 static ssize_t show_status(struct kobject *kobj,
1164                            struct kobj_attribute *attr, char *buf)
1165 {
1166         ssize_t ret;
1167
1168         mutex_lock(&intel_pstate_driver_lock);
1169         ret = intel_pstate_show_status(buf);
1170         mutex_unlock(&intel_pstate_driver_lock);
1171
1172         return ret;
1173 }
1174
1175 static ssize_t store_status(struct kobject *a, struct kobj_attribute *b,
1176                             const char *buf, size_t count)
1177 {
1178         char *p = memchr(buf, '\n', count);
1179         int ret;
1180
1181         mutex_lock(&intel_pstate_driver_lock);
1182         ret = intel_pstate_update_status(buf, p ? p - buf : count);
1183         mutex_unlock(&intel_pstate_driver_lock);
1184
1185         return ret < 0 ? ret : count;
1186 }
1187
1188 static ssize_t show_turbo_pct(struct kobject *kobj,
1189                                 struct kobj_attribute *attr, char *buf)
1190 {
1191         struct cpudata *cpu;
1192         int total, no_turbo, turbo_pct;
1193         uint32_t turbo_fp;
1194
1195         mutex_lock(&intel_pstate_driver_lock);
1196
1197         if (!intel_pstate_driver) {
1198                 mutex_unlock(&intel_pstate_driver_lock);
1199                 return -EAGAIN;
1200         }
1201
1202         cpu = all_cpu_data[0];
1203
1204         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1205         no_turbo = cpu->pstate.max_pstate - cpu->pstate.min_pstate + 1;
1206         turbo_fp = div_fp(no_turbo, total);
1207         turbo_pct = 100 - fp_toint(mul_fp(turbo_fp, int_tofp(100)));
1208
1209         mutex_unlock(&intel_pstate_driver_lock);
1210
1211         return sprintf(buf, "%u\n", turbo_pct);
1212 }
1213
1214 static ssize_t show_num_pstates(struct kobject *kobj,
1215                                 struct kobj_attribute *attr, char *buf)
1216 {
1217         struct cpudata *cpu;
1218         int total;
1219
1220         mutex_lock(&intel_pstate_driver_lock);
1221
1222         if (!intel_pstate_driver) {
1223                 mutex_unlock(&intel_pstate_driver_lock);
1224                 return -EAGAIN;
1225         }
1226
1227         cpu = all_cpu_data[0];
1228         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1229
1230         mutex_unlock(&intel_pstate_driver_lock);
1231
1232         return sprintf(buf, "%u\n", total);
1233 }
1234
1235 static ssize_t show_no_turbo(struct kobject *kobj,
1236                              struct kobj_attribute *attr, char *buf)
1237 {
1238         ssize_t ret;
1239
1240         mutex_lock(&intel_pstate_driver_lock);
1241
1242         if (!intel_pstate_driver) {
1243                 mutex_unlock(&intel_pstate_driver_lock);
1244                 return -EAGAIN;
1245         }
1246
1247         update_turbo_state();
1248         if (global.turbo_disabled)
1249                 ret = sprintf(buf, "%u\n", global.turbo_disabled);
1250         else
1251                 ret = sprintf(buf, "%u\n", global.no_turbo);
1252
1253         mutex_unlock(&intel_pstate_driver_lock);
1254
1255         return ret;
1256 }
1257
1258 static ssize_t store_no_turbo(struct kobject *a, struct kobj_attribute *b,
1259                               const char *buf, size_t count)
1260 {
1261         unsigned int input;
1262         int ret;
1263
1264         ret = sscanf(buf, "%u", &input);
1265         if (ret != 1)
1266                 return -EINVAL;
1267
1268         mutex_lock(&intel_pstate_driver_lock);
1269
1270         if (!intel_pstate_driver) {
1271                 mutex_unlock(&intel_pstate_driver_lock);
1272                 return -EAGAIN;
1273         }
1274
1275         mutex_lock(&intel_pstate_limits_lock);
1276
1277         update_turbo_state();
1278         if (global.turbo_disabled) {
1279                 pr_notice_once("Turbo disabled by BIOS or unavailable on processor\n");
1280                 mutex_unlock(&intel_pstate_limits_lock);
1281                 mutex_unlock(&intel_pstate_driver_lock);
1282                 return -EPERM;
1283         }
1284
1285         global.no_turbo = clamp_t(int, input, 0, 1);
1286
1287         if (global.no_turbo) {
1288                 struct cpudata *cpu = all_cpu_data[0];
1289                 int pct = cpu->pstate.max_pstate * 100 / cpu->pstate.turbo_pstate;
1290
1291                 /* Squash the global minimum into the permitted range. */
1292                 if (global.min_perf_pct > pct)
1293                         global.min_perf_pct = pct;
1294         }
1295
1296         mutex_unlock(&intel_pstate_limits_lock);
1297
1298         intel_pstate_update_policies();
1299         arch_set_max_freq_ratio(global.no_turbo);
1300
1301         mutex_unlock(&intel_pstate_driver_lock);
1302
1303         return count;
1304 }
1305
1306 static void update_qos_request(enum freq_qos_req_type type)
1307 {
1308         struct freq_qos_request *req;
1309         struct cpufreq_policy *policy;
1310         int i;
1311
1312         for_each_possible_cpu(i) {
1313                 struct cpudata *cpu = all_cpu_data[i];
1314                 unsigned int freq, perf_pct;
1315
1316                 policy = cpufreq_cpu_get(i);
1317                 if (!policy)
1318                         continue;
1319
1320                 req = policy->driver_data;
1321                 cpufreq_cpu_put(policy);
1322
1323                 if (!req)
1324                         continue;
1325
1326                 if (hwp_active)
1327                         intel_pstate_get_hwp_cap(cpu);
1328
1329                 if (type == FREQ_QOS_MIN) {
1330                         perf_pct = global.min_perf_pct;
1331                 } else {
1332                         req++;
1333                         perf_pct = global.max_perf_pct;
1334                 }
1335
1336                 freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * perf_pct, 100);
1337
1338                 if (freq_qos_update_request(req, freq) < 0)
1339                         pr_warn("Failed to update freq constraint: CPU%d\n", i);
1340         }
1341 }
1342
1343 static ssize_t store_max_perf_pct(struct kobject *a, struct kobj_attribute *b,
1344                                   const char *buf, size_t count)
1345 {
1346         unsigned int input;
1347         int ret;
1348
1349         ret = sscanf(buf, "%u", &input);
1350         if (ret != 1)
1351                 return -EINVAL;
1352
1353         mutex_lock(&intel_pstate_driver_lock);
1354
1355         if (!intel_pstate_driver) {
1356                 mutex_unlock(&intel_pstate_driver_lock);
1357                 return -EAGAIN;
1358         }
1359
1360         mutex_lock(&intel_pstate_limits_lock);
1361
1362         global.max_perf_pct = clamp_t(int, input, global.min_perf_pct, 100);
1363
1364         mutex_unlock(&intel_pstate_limits_lock);
1365
1366         if (intel_pstate_driver == &intel_pstate)
1367                 intel_pstate_update_policies();
1368         else
1369                 update_qos_request(FREQ_QOS_MAX);
1370
1371         mutex_unlock(&intel_pstate_driver_lock);
1372
1373         return count;
1374 }
1375
1376 static ssize_t store_min_perf_pct(struct kobject *a, struct kobj_attribute *b,
1377                                   const char *buf, size_t count)
1378 {
1379         unsigned int input;
1380         int ret;
1381
1382         ret = sscanf(buf, "%u", &input);
1383         if (ret != 1)
1384                 return -EINVAL;
1385
1386         mutex_lock(&intel_pstate_driver_lock);
1387
1388         if (!intel_pstate_driver) {
1389                 mutex_unlock(&intel_pstate_driver_lock);
1390                 return -EAGAIN;
1391         }
1392
1393         mutex_lock(&intel_pstate_limits_lock);
1394
1395         global.min_perf_pct = clamp_t(int, input,
1396                                       min_perf_pct_min(), global.max_perf_pct);
1397
1398         mutex_unlock(&intel_pstate_limits_lock);
1399
1400         if (intel_pstate_driver == &intel_pstate)
1401                 intel_pstate_update_policies();
1402         else
1403                 update_qos_request(FREQ_QOS_MIN);
1404
1405         mutex_unlock(&intel_pstate_driver_lock);
1406
1407         return count;
1408 }
1409
1410 static ssize_t show_hwp_dynamic_boost(struct kobject *kobj,
1411                                 struct kobj_attribute *attr, char *buf)
1412 {
1413         return sprintf(buf, "%u\n", hwp_boost);
1414 }
1415
1416 static ssize_t store_hwp_dynamic_boost(struct kobject *a,
1417                                        struct kobj_attribute *b,
1418                                        const char *buf, size_t count)
1419 {
1420         unsigned int input;
1421         int ret;
1422
1423         ret = kstrtouint(buf, 10, &input);
1424         if (ret)
1425                 return ret;
1426
1427         mutex_lock(&intel_pstate_driver_lock);
1428         hwp_boost = !!input;
1429         intel_pstate_update_policies();
1430         mutex_unlock(&intel_pstate_driver_lock);
1431
1432         return count;
1433 }
1434
1435 static ssize_t show_energy_efficiency(struct kobject *kobj, struct kobj_attribute *attr,
1436                                       char *buf)
1437 {
1438         u64 power_ctl;
1439         int enable;
1440
1441         rdmsrl(MSR_IA32_POWER_CTL, power_ctl);
1442         enable = !!(power_ctl & BIT(MSR_IA32_POWER_CTL_BIT_EE));
1443         return sprintf(buf, "%d\n", !enable);
1444 }
1445
1446 static ssize_t store_energy_efficiency(struct kobject *a, struct kobj_attribute *b,
1447                                        const char *buf, size_t count)
1448 {
1449         bool input;
1450         int ret;
1451
1452         ret = kstrtobool(buf, &input);
1453         if (ret)
1454                 return ret;
1455
1456         set_power_ctl_ee_state(input);
1457
1458         return count;
1459 }
1460
1461 show_one(max_perf_pct, max_perf_pct);
1462 show_one(min_perf_pct, min_perf_pct);
1463
1464 define_one_global_rw(status);
1465 define_one_global_rw(no_turbo);
1466 define_one_global_rw(max_perf_pct);
1467 define_one_global_rw(min_perf_pct);
1468 define_one_global_ro(turbo_pct);
1469 define_one_global_ro(num_pstates);
1470 define_one_global_rw(hwp_dynamic_boost);
1471 define_one_global_rw(energy_efficiency);
1472
1473 static struct attribute *intel_pstate_attributes[] = {
1474         &status.attr,
1475         &no_turbo.attr,
1476         NULL
1477 };
1478
1479 static const struct attribute_group intel_pstate_attr_group = {
1480         .attrs = intel_pstate_attributes,
1481 };
1482
1483 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[];
1484
1485 static struct kobject *intel_pstate_kobject;
1486
1487 static void __init intel_pstate_sysfs_expose_params(void)
1488 {
1489         int rc;
1490
1491         intel_pstate_kobject = kobject_create_and_add("intel_pstate",
1492                                                 &cpu_subsys.dev_root->kobj);
1493         if (WARN_ON(!intel_pstate_kobject))
1494                 return;
1495
1496         rc = sysfs_create_group(intel_pstate_kobject, &intel_pstate_attr_group);
1497         if (WARN_ON(rc))
1498                 return;
1499
1500         if (!boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
1501                 rc = sysfs_create_file(intel_pstate_kobject, &turbo_pct.attr);
1502                 WARN_ON(rc);
1503
1504                 rc = sysfs_create_file(intel_pstate_kobject, &num_pstates.attr);
1505                 WARN_ON(rc);
1506         }
1507
1508         /*
1509          * If per cpu limits are enforced there are no global limits, so
1510          * return without creating max/min_perf_pct attributes
1511          */
1512         if (per_cpu_limits)
1513                 return;
1514
1515         rc = sysfs_create_file(intel_pstate_kobject, &max_perf_pct.attr);
1516         WARN_ON(rc);
1517
1518         rc = sysfs_create_file(intel_pstate_kobject, &min_perf_pct.attr);
1519         WARN_ON(rc);
1520
1521         if (x86_match_cpu(intel_pstate_cpu_ee_disable_ids)) {
1522                 rc = sysfs_create_file(intel_pstate_kobject, &energy_efficiency.attr);
1523                 WARN_ON(rc);
1524         }
1525 }
1526
1527 static void __init intel_pstate_sysfs_remove(void)
1528 {
1529         if (!intel_pstate_kobject)
1530                 return;
1531
1532         sysfs_remove_group(intel_pstate_kobject, &intel_pstate_attr_group);
1533
1534         if (!boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
1535                 sysfs_remove_file(intel_pstate_kobject, &num_pstates.attr);
1536                 sysfs_remove_file(intel_pstate_kobject, &turbo_pct.attr);
1537         }
1538
1539         if (!per_cpu_limits) {
1540                 sysfs_remove_file(intel_pstate_kobject, &max_perf_pct.attr);
1541                 sysfs_remove_file(intel_pstate_kobject, &min_perf_pct.attr);
1542
1543                 if (x86_match_cpu(intel_pstate_cpu_ee_disable_ids))
1544                         sysfs_remove_file(intel_pstate_kobject, &energy_efficiency.attr);
1545         }
1546
1547         kobject_put(intel_pstate_kobject);
1548 }
1549
1550 static void intel_pstate_sysfs_expose_hwp_dynamic_boost(void)
1551 {
1552         int rc;
1553
1554         if (!hwp_active)
1555                 return;
1556
1557         rc = sysfs_create_file(intel_pstate_kobject, &hwp_dynamic_boost.attr);
1558         WARN_ON_ONCE(rc);
1559 }
1560
1561 static void intel_pstate_sysfs_hide_hwp_dynamic_boost(void)
1562 {
1563         if (!hwp_active)
1564                 return;
1565
1566         sysfs_remove_file(intel_pstate_kobject, &hwp_dynamic_boost.attr);
1567 }
1568
1569 /************************** sysfs end ************************/
1570
1571 static void intel_pstate_notify_work(struct work_struct *work)
1572 {
1573         struct cpudata *cpudata =
1574                 container_of(to_delayed_work(work), struct cpudata, hwp_notify_work);
1575         struct cpufreq_policy *policy = cpufreq_cpu_acquire(cpudata->cpu);
1576
1577         if (policy) {
1578                 intel_pstate_get_hwp_cap(cpudata);
1579                 __intel_pstate_update_max_freq(cpudata, policy);
1580
1581                 cpufreq_cpu_release(policy);
1582         }
1583
1584         wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_STATUS, 0);
1585 }
1586
1587 static DEFINE_SPINLOCK(hwp_notify_lock);
1588 static cpumask_t hwp_intr_enable_mask;
1589
1590 void notify_hwp_interrupt(void)
1591 {
1592         unsigned int this_cpu = smp_processor_id();
1593         struct cpudata *cpudata;
1594         unsigned long flags;
1595         u64 value;
1596
1597         if (!READ_ONCE(hwp_active) || !boot_cpu_has(X86_FEATURE_HWP_NOTIFY))
1598                 return;
1599
1600         rdmsrl_safe(MSR_HWP_STATUS, &value);
1601         if (!(value & 0x01))
1602                 return;
1603
1604         spin_lock_irqsave(&hwp_notify_lock, flags);
1605
1606         if (!cpumask_test_cpu(this_cpu, &hwp_intr_enable_mask))
1607                 goto ack_intr;
1608
1609         /*
1610          * Currently we never free all_cpu_data. And we can't reach here
1611          * without this allocated. But for safety for future changes, added
1612          * check.
1613          */
1614         if (unlikely(!READ_ONCE(all_cpu_data)))
1615                 goto ack_intr;
1616
1617         /*
1618          * The free is done during cleanup, when cpufreq registry is failed.
1619          * We wouldn't be here if it fails on init or switch status. But for
1620          * future changes, added check.
1621          */
1622         cpudata = READ_ONCE(all_cpu_data[this_cpu]);
1623         if (unlikely(!cpudata))
1624                 goto ack_intr;
1625
1626         schedule_delayed_work(&cpudata->hwp_notify_work, msecs_to_jiffies(10));
1627
1628         spin_unlock_irqrestore(&hwp_notify_lock, flags);
1629
1630         return;
1631
1632 ack_intr:
1633         wrmsrl_safe(MSR_HWP_STATUS, 0);
1634         spin_unlock_irqrestore(&hwp_notify_lock, flags);
1635 }
1636
1637 static void intel_pstate_disable_hwp_interrupt(struct cpudata *cpudata)
1638 {
1639         unsigned long flags;
1640
1641         if (!boot_cpu_has(X86_FEATURE_HWP_NOTIFY))
1642                 return;
1643
1644         /* wrmsrl_on_cpu has to be outside spinlock as this can result in IPC */
1645         wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x00);
1646
1647         spin_lock_irqsave(&hwp_notify_lock, flags);
1648         if (cpumask_test_and_clear_cpu(cpudata->cpu, &hwp_intr_enable_mask))
1649                 cancel_delayed_work(&cpudata->hwp_notify_work);
1650         spin_unlock_irqrestore(&hwp_notify_lock, flags);
1651 }
1652
1653 static void intel_pstate_enable_hwp_interrupt(struct cpudata *cpudata)
1654 {
1655         /* Enable HWP notification interrupt for guaranteed performance change */
1656         if (boot_cpu_has(X86_FEATURE_HWP_NOTIFY)) {
1657                 unsigned long flags;
1658
1659                 spin_lock_irqsave(&hwp_notify_lock, flags);
1660                 INIT_DELAYED_WORK(&cpudata->hwp_notify_work, intel_pstate_notify_work);
1661                 cpumask_set_cpu(cpudata->cpu, &hwp_intr_enable_mask);
1662                 spin_unlock_irqrestore(&hwp_notify_lock, flags);
1663
1664                 /* wrmsrl_on_cpu has to be outside spinlock as this can result in IPC */
1665                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x01);
1666                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_STATUS, 0);
1667         }
1668 }
1669
1670 static void intel_pstate_update_epp_defaults(struct cpudata *cpudata)
1671 {
1672         cpudata->epp_default = intel_pstate_get_epp(cpudata, 0);
1673
1674         /*
1675          * If this CPU gen doesn't call for change in balance_perf
1676          * EPP return.
1677          */
1678         if (epp_values[EPP_INDEX_BALANCE_PERFORMANCE] == HWP_EPP_BALANCE_PERFORMANCE)
1679                 return;
1680
1681         /*
1682          * If powerup EPP is something other than chipset default 0x80 and
1683          * - is more performance oriented than 0x80 (default balance_perf EPP)
1684          * - But less performance oriented than performance EPP
1685          *   then use this as new balance_perf EPP.
1686          */
1687         if (cpudata->epp_default < HWP_EPP_BALANCE_PERFORMANCE &&
1688             cpudata->epp_default > HWP_EPP_PERFORMANCE) {
1689                 epp_values[EPP_INDEX_BALANCE_PERFORMANCE] = cpudata->epp_default;
1690                 return;
1691         }
1692
1693         /*
1694          * Use hard coded value per gen to update the balance_perf
1695          * and default EPP.
1696          */
1697         cpudata->epp_default = epp_values[EPP_INDEX_BALANCE_PERFORMANCE];
1698         intel_pstate_set_epp(cpudata, cpudata->epp_default);
1699 }
1700
1701 static void intel_pstate_hwp_enable(struct cpudata *cpudata)
1702 {
1703         /* First disable HWP notification interrupt till we activate again */
1704         if (boot_cpu_has(X86_FEATURE_HWP_NOTIFY))
1705                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x00);
1706
1707         wrmsrl_on_cpu(cpudata->cpu, MSR_PM_ENABLE, 0x1);
1708
1709         intel_pstate_enable_hwp_interrupt(cpudata);
1710
1711         if (cpudata->epp_default >= 0)
1712                 return;
1713
1714         intel_pstate_update_epp_defaults(cpudata);
1715 }
1716
1717 static int atom_get_min_pstate(int not_used)
1718 {
1719         u64 value;
1720
1721         rdmsrl(MSR_ATOM_CORE_RATIOS, value);
1722         return (value >> 8) & 0x7F;
1723 }
1724
1725 static int atom_get_max_pstate(int not_used)
1726 {
1727         u64 value;
1728
1729         rdmsrl(MSR_ATOM_CORE_RATIOS, value);
1730         return (value >> 16) & 0x7F;
1731 }
1732
1733 static int atom_get_turbo_pstate(int not_used)
1734 {
1735         u64 value;
1736
1737         rdmsrl(MSR_ATOM_CORE_TURBO_RATIOS, value);
1738         return value & 0x7F;
1739 }
1740
1741 static u64 atom_get_val(struct cpudata *cpudata, int pstate)
1742 {
1743         u64 val;
1744         int32_t vid_fp;
1745         u32 vid;
1746
1747         val = (u64)pstate << 8;
1748         if (global.no_turbo && !global.turbo_disabled)
1749                 val |= (u64)1 << 32;
1750
1751         vid_fp = cpudata->vid.min + mul_fp(
1752                 int_tofp(pstate - cpudata->pstate.min_pstate),
1753                 cpudata->vid.ratio);
1754
1755         vid_fp = clamp_t(int32_t, vid_fp, cpudata->vid.min, cpudata->vid.max);
1756         vid = ceiling_fp(vid_fp);
1757
1758         if (pstate > cpudata->pstate.max_pstate)
1759                 vid = cpudata->vid.turbo;
1760
1761         return val | vid;
1762 }
1763
1764 static int silvermont_get_scaling(void)
1765 {
1766         u64 value;
1767         int i;
1768         /* Defined in Table 35-6 from SDM (Sept 2015) */
1769         static int silvermont_freq_table[] = {
1770                 83300, 100000, 133300, 116700, 80000};
1771
1772         rdmsrl(MSR_FSB_FREQ, value);
1773         i = value & 0x7;
1774         WARN_ON(i > 4);
1775
1776         return silvermont_freq_table[i];
1777 }
1778
1779 static int airmont_get_scaling(void)
1780 {
1781         u64 value;
1782         int i;
1783         /* Defined in Table 35-10 from SDM (Sept 2015) */
1784         static int airmont_freq_table[] = {
1785                 83300, 100000, 133300, 116700, 80000,
1786                 93300, 90000, 88900, 87500};
1787
1788         rdmsrl(MSR_FSB_FREQ, value);
1789         i = value & 0xF;
1790         WARN_ON(i > 8);
1791
1792         return airmont_freq_table[i];
1793 }
1794
1795 static void atom_get_vid(struct cpudata *cpudata)
1796 {
1797         u64 value;
1798
1799         rdmsrl(MSR_ATOM_CORE_VIDS, value);
1800         cpudata->vid.min = int_tofp((value >> 8) & 0x7f);
1801         cpudata->vid.max = int_tofp((value >> 16) & 0x7f);
1802         cpudata->vid.ratio = div_fp(
1803                 cpudata->vid.max - cpudata->vid.min,
1804                 int_tofp(cpudata->pstate.max_pstate -
1805                         cpudata->pstate.min_pstate));
1806
1807         rdmsrl(MSR_ATOM_CORE_TURBO_VIDS, value);
1808         cpudata->vid.turbo = value & 0x7f;
1809 }
1810
1811 static int core_get_min_pstate(int cpu)
1812 {
1813         u64 value;
1814
1815         rdmsrl_on_cpu(cpu, MSR_PLATFORM_INFO, &value);
1816         return (value >> 40) & 0xFF;
1817 }
1818
1819 static int core_get_max_pstate_physical(int cpu)
1820 {
1821         u64 value;
1822
1823         rdmsrl_on_cpu(cpu, MSR_PLATFORM_INFO, &value);
1824         return (value >> 8) & 0xFF;
1825 }
1826
1827 static int core_get_tdp_ratio(int cpu, u64 plat_info)
1828 {
1829         /* Check how many TDP levels present */
1830         if (plat_info & 0x600000000) {
1831                 u64 tdp_ctrl;
1832                 u64 tdp_ratio;
1833                 int tdp_msr;
1834                 int err;
1835
1836                 /* Get the TDP level (0, 1, 2) to get ratios */
1837                 err = rdmsrl_safe_on_cpu(cpu, MSR_CONFIG_TDP_CONTROL, &tdp_ctrl);
1838                 if (err)
1839                         return err;
1840
1841                 /* TDP MSR are continuous starting at 0x648 */
1842                 tdp_msr = MSR_CONFIG_TDP_NOMINAL + (tdp_ctrl & 0x03);
1843                 err = rdmsrl_safe_on_cpu(cpu, tdp_msr, &tdp_ratio);
1844                 if (err)
1845                         return err;
1846
1847                 /* For level 1 and 2, bits[23:16] contain the ratio */
1848                 if (tdp_ctrl & 0x03)
1849                         tdp_ratio >>= 16;
1850
1851                 tdp_ratio &= 0xff; /* ratios are only 8 bits long */
1852                 pr_debug("tdp_ratio %x\n", (int)tdp_ratio);
1853
1854                 return (int)tdp_ratio;
1855         }
1856
1857         return -ENXIO;
1858 }
1859
1860 static int core_get_max_pstate(int cpu)
1861 {
1862         u64 tar;
1863         u64 plat_info;
1864         int max_pstate;
1865         int tdp_ratio;
1866         int err;
1867
1868         rdmsrl_on_cpu(cpu, MSR_PLATFORM_INFO, &plat_info);
1869         max_pstate = (plat_info >> 8) & 0xFF;
1870
1871         tdp_ratio = core_get_tdp_ratio(cpu, plat_info);
1872         if (tdp_ratio <= 0)
1873                 return max_pstate;
1874
1875         if (hwp_active) {
1876                 /* Turbo activation ratio is not used on HWP platforms */
1877                 return tdp_ratio;
1878         }
1879
1880         err = rdmsrl_safe_on_cpu(cpu, MSR_TURBO_ACTIVATION_RATIO, &tar);
1881         if (!err) {
1882                 int tar_levels;
1883
1884                 /* Do some sanity checking for safety */
1885                 tar_levels = tar & 0xff;
1886                 if (tdp_ratio - 1 == tar_levels) {
1887                         max_pstate = tar_levels;
1888                         pr_debug("max_pstate=TAC %x\n", max_pstate);
1889                 }
1890         }
1891
1892         return max_pstate;
1893 }
1894
1895 static int core_get_turbo_pstate(int cpu)
1896 {
1897         u64 value;
1898         int nont, ret;
1899
1900         rdmsrl_on_cpu(cpu, MSR_TURBO_RATIO_LIMIT, &value);
1901         nont = core_get_max_pstate(cpu);
1902         ret = (value) & 255;
1903         if (ret <= nont)
1904                 ret = nont;
1905         return ret;
1906 }
1907
1908 static inline int core_get_scaling(void)
1909 {
1910         return 100000;
1911 }
1912
1913 static u64 core_get_val(struct cpudata *cpudata, int pstate)
1914 {
1915         u64 val;
1916
1917         val = (u64)pstate << 8;
1918         if (global.no_turbo && !global.turbo_disabled)
1919                 val |= (u64)1 << 32;
1920
1921         return val;
1922 }
1923
1924 static int knl_get_aperf_mperf_shift(void)
1925 {
1926         return 10;
1927 }
1928
1929 static int knl_get_turbo_pstate(int cpu)
1930 {
1931         u64 value;
1932         int nont, ret;
1933
1934         rdmsrl_on_cpu(cpu, MSR_TURBO_RATIO_LIMIT, &value);
1935         nont = core_get_max_pstate(cpu);
1936         ret = (((value) >> 8) & 0xFF);
1937         if (ret <= nont)
1938                 ret = nont;
1939         return ret;
1940 }
1941
1942 static void hybrid_get_type(void *data)
1943 {
1944         u8 *cpu_type = data;
1945
1946         *cpu_type = get_this_hybrid_cpu_type();
1947 }
1948
1949 static int hybrid_get_cpu_scaling(int cpu)
1950 {
1951         u8 cpu_type = 0;
1952
1953         smp_call_function_single(cpu, hybrid_get_type, &cpu_type, 1);
1954         /* P-cores have a smaller perf level-to-freqency scaling factor. */
1955         if (cpu_type == 0x40)
1956                 return 78741;
1957
1958         return core_get_scaling();
1959 }
1960
1961 static void intel_pstate_set_pstate(struct cpudata *cpu, int pstate)
1962 {
1963         trace_cpu_frequency(pstate * cpu->pstate.scaling, cpu->cpu);
1964         cpu->pstate.current_pstate = pstate;
1965         /*
1966          * Generally, there is no guarantee that this code will always run on
1967          * the CPU being updated, so force the register update to run on the
1968          * right CPU.
1969          */
1970         wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
1971                       pstate_funcs.get_val(cpu, pstate));
1972 }
1973
1974 static void intel_pstate_set_min_pstate(struct cpudata *cpu)
1975 {
1976         intel_pstate_set_pstate(cpu, cpu->pstate.min_pstate);
1977 }
1978
1979 static void intel_pstate_max_within_limits(struct cpudata *cpu)
1980 {
1981         int pstate = max(cpu->pstate.min_pstate, cpu->max_perf_ratio);
1982
1983         update_turbo_state();
1984         intel_pstate_set_pstate(cpu, pstate);
1985 }
1986
1987 static void intel_pstate_get_cpu_pstates(struct cpudata *cpu)
1988 {
1989         int perf_ctl_max_phys = pstate_funcs.get_max_physical(cpu->cpu);
1990         int perf_ctl_scaling = pstate_funcs.get_scaling();
1991
1992         cpu->pstate.min_pstate = pstate_funcs.get_min(cpu->cpu);
1993         cpu->pstate.max_pstate_physical = perf_ctl_max_phys;
1994         cpu->pstate.perf_ctl_scaling = perf_ctl_scaling;
1995
1996         if (hwp_active && !hwp_mode_bdw) {
1997                 __intel_pstate_get_hwp_cap(cpu);
1998
1999                 if (pstate_funcs.get_cpu_scaling) {
2000                         cpu->pstate.scaling = pstate_funcs.get_cpu_scaling(cpu->cpu);
2001                         if (cpu->pstate.scaling != perf_ctl_scaling)
2002                                 intel_pstate_hybrid_hwp_adjust(cpu);
2003                 } else {
2004                         cpu->pstate.scaling = perf_ctl_scaling;
2005                 }
2006         } else {
2007                 cpu->pstate.scaling = perf_ctl_scaling;
2008                 cpu->pstate.max_pstate = pstate_funcs.get_max(cpu->cpu);
2009                 cpu->pstate.turbo_pstate = pstate_funcs.get_turbo(cpu->cpu);
2010         }
2011
2012         if (cpu->pstate.scaling == perf_ctl_scaling) {
2013                 cpu->pstate.min_freq = cpu->pstate.min_pstate * perf_ctl_scaling;
2014                 cpu->pstate.max_freq = cpu->pstate.max_pstate * perf_ctl_scaling;
2015                 cpu->pstate.turbo_freq = cpu->pstate.turbo_pstate * perf_ctl_scaling;
2016         }
2017
2018         if (pstate_funcs.get_aperf_mperf_shift)
2019                 cpu->aperf_mperf_shift = pstate_funcs.get_aperf_mperf_shift();
2020
2021         if (pstate_funcs.get_vid)
2022                 pstate_funcs.get_vid(cpu);
2023
2024         intel_pstate_set_min_pstate(cpu);
2025 }
2026
2027 /*
2028  * Long hold time will keep high perf limits for long time,
2029  * which negatively impacts perf/watt for some workloads,
2030  * like specpower. 3ms is based on experiements on some
2031  * workoads.
2032  */
2033 static int hwp_boost_hold_time_ns = 3 * NSEC_PER_MSEC;
2034
2035 static inline void intel_pstate_hwp_boost_up(struct cpudata *cpu)
2036 {
2037         u64 hwp_req = READ_ONCE(cpu->hwp_req_cached);
2038         u64 hwp_cap = READ_ONCE(cpu->hwp_cap_cached);
2039         u32 max_limit = (hwp_req & 0xff00) >> 8;
2040         u32 min_limit = (hwp_req & 0xff);
2041         u32 boost_level1;
2042
2043         /*
2044          * Cases to consider (User changes via sysfs or boot time):
2045          * If, P0 (Turbo max) = P1 (Guaranteed max) = min:
2046          *      No boost, return.
2047          * If, P0 (Turbo max) > P1 (Guaranteed max) = min:
2048          *     Should result in one level boost only for P0.
2049          * If, P0 (Turbo max) = P1 (Guaranteed max) > min:
2050          *     Should result in two level boost:
2051          *         (min + p1)/2 and P1.
2052          * If, P0 (Turbo max) > P1 (Guaranteed max) > min:
2053          *     Should result in three level boost:
2054          *        (min + p1)/2, P1 and P0.
2055          */
2056
2057         /* If max and min are equal or already at max, nothing to boost */
2058         if (max_limit == min_limit || cpu->hwp_boost_min >= max_limit)
2059                 return;
2060
2061         if (!cpu->hwp_boost_min)
2062                 cpu->hwp_boost_min = min_limit;
2063
2064         /* level at half way mark between min and guranteed */
2065         boost_level1 = (HWP_GUARANTEED_PERF(hwp_cap) + min_limit) >> 1;
2066
2067         if (cpu->hwp_boost_min < boost_level1)
2068                 cpu->hwp_boost_min = boost_level1;
2069         else if (cpu->hwp_boost_min < HWP_GUARANTEED_PERF(hwp_cap))
2070                 cpu->hwp_boost_min = HWP_GUARANTEED_PERF(hwp_cap);
2071         else if (cpu->hwp_boost_min == HWP_GUARANTEED_PERF(hwp_cap) &&
2072                  max_limit != HWP_GUARANTEED_PERF(hwp_cap))
2073                 cpu->hwp_boost_min = max_limit;
2074         else
2075                 return;
2076
2077         hwp_req = (hwp_req & ~GENMASK_ULL(7, 0)) | cpu->hwp_boost_min;
2078         wrmsrl(MSR_HWP_REQUEST, hwp_req);
2079         cpu->last_update = cpu->sample.time;
2080 }
2081
2082 static inline void intel_pstate_hwp_boost_down(struct cpudata *cpu)
2083 {
2084         if (cpu->hwp_boost_min) {
2085                 bool expired;
2086
2087                 /* Check if we are idle for hold time to boost down */
2088                 expired = time_after64(cpu->sample.time, cpu->last_update +
2089                                        hwp_boost_hold_time_ns);
2090                 if (expired) {
2091                         wrmsrl(MSR_HWP_REQUEST, cpu->hwp_req_cached);
2092                         cpu->hwp_boost_min = 0;
2093                 }
2094         }
2095         cpu->last_update = cpu->sample.time;
2096 }
2097
2098 static inline void intel_pstate_update_util_hwp_local(struct cpudata *cpu,
2099                                                       u64 time)
2100 {
2101         cpu->sample.time = time;
2102
2103         if (cpu->sched_flags & SCHED_CPUFREQ_IOWAIT) {
2104                 bool do_io = false;
2105
2106                 cpu->sched_flags = 0;
2107                 /*
2108                  * Set iowait_boost flag and update time. Since IO WAIT flag
2109                  * is set all the time, we can't just conclude that there is
2110                  * some IO bound activity is scheduled on this CPU with just
2111                  * one occurrence. If we receive at least two in two
2112                  * consecutive ticks, then we treat as boost candidate.
2113                  */
2114                 if (time_before64(time, cpu->last_io_update + 2 * TICK_NSEC))
2115                         do_io = true;
2116
2117                 cpu->last_io_update = time;
2118
2119                 if (do_io)
2120                         intel_pstate_hwp_boost_up(cpu);
2121
2122         } else {
2123                 intel_pstate_hwp_boost_down(cpu);
2124         }
2125 }
2126
2127 static inline void intel_pstate_update_util_hwp(struct update_util_data *data,
2128                                                 u64 time, unsigned int flags)
2129 {
2130         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
2131
2132         cpu->sched_flags |= flags;
2133
2134         if (smp_processor_id() == cpu->cpu)
2135                 intel_pstate_update_util_hwp_local(cpu, time);
2136 }
2137
2138 static inline void intel_pstate_calc_avg_perf(struct cpudata *cpu)
2139 {
2140         struct sample *sample = &cpu->sample;
2141
2142         sample->core_avg_perf = div_ext_fp(sample->aperf, sample->mperf);
2143 }
2144
2145 static inline bool intel_pstate_sample(struct cpudata *cpu, u64 time)
2146 {
2147         u64 aperf, mperf;
2148         unsigned long flags;
2149         u64 tsc;
2150
2151         local_irq_save(flags);
2152         rdmsrl(MSR_IA32_APERF, aperf);
2153         rdmsrl(MSR_IA32_MPERF, mperf);
2154         tsc = rdtsc();
2155         if (cpu->prev_mperf == mperf || cpu->prev_tsc == tsc) {
2156                 local_irq_restore(flags);
2157                 return false;
2158         }
2159         local_irq_restore(flags);
2160
2161         cpu->last_sample_time = cpu->sample.time;
2162         cpu->sample.time = time;
2163         cpu->sample.aperf = aperf;
2164         cpu->sample.mperf = mperf;
2165         cpu->sample.tsc =  tsc;
2166         cpu->sample.aperf -= cpu->prev_aperf;
2167         cpu->sample.mperf -= cpu->prev_mperf;
2168         cpu->sample.tsc -= cpu->prev_tsc;
2169
2170         cpu->prev_aperf = aperf;
2171         cpu->prev_mperf = mperf;
2172         cpu->prev_tsc = tsc;
2173         /*
2174          * First time this function is invoked in a given cycle, all of the
2175          * previous sample data fields are equal to zero or stale and they must
2176          * be populated with meaningful numbers for things to work, so assume
2177          * that sample.time will always be reset before setting the utilization
2178          * update hook and make the caller skip the sample then.
2179          */
2180         if (cpu->last_sample_time) {
2181                 intel_pstate_calc_avg_perf(cpu);
2182                 return true;
2183         }
2184         return false;
2185 }
2186
2187 static inline int32_t get_avg_frequency(struct cpudata *cpu)
2188 {
2189         return mul_ext_fp(cpu->sample.core_avg_perf, cpu_khz);
2190 }
2191
2192 static inline int32_t get_avg_pstate(struct cpudata *cpu)
2193 {
2194         return mul_ext_fp(cpu->pstate.max_pstate_physical,
2195                           cpu->sample.core_avg_perf);
2196 }
2197
2198 static inline int32_t get_target_pstate(struct cpudata *cpu)
2199 {
2200         struct sample *sample = &cpu->sample;
2201         int32_t busy_frac;
2202         int target, avg_pstate;
2203
2204         busy_frac = div_fp(sample->mperf << cpu->aperf_mperf_shift,
2205                            sample->tsc);
2206
2207         if (busy_frac < cpu->iowait_boost)
2208                 busy_frac = cpu->iowait_boost;
2209
2210         sample->busy_scaled = busy_frac * 100;
2211
2212         target = global.no_turbo || global.turbo_disabled ?
2213                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
2214         target += target >> 2;
2215         target = mul_fp(target, busy_frac);
2216         if (target < cpu->pstate.min_pstate)
2217                 target = cpu->pstate.min_pstate;
2218
2219         /*
2220          * If the average P-state during the previous cycle was higher than the
2221          * current target, add 50% of the difference to the target to reduce
2222          * possible performance oscillations and offset possible performance
2223          * loss related to moving the workload from one CPU to another within
2224          * a package/module.
2225          */
2226         avg_pstate = get_avg_pstate(cpu);
2227         if (avg_pstate > target)
2228                 target += (avg_pstate - target) >> 1;
2229
2230         return target;
2231 }
2232
2233 static int intel_pstate_prepare_request(struct cpudata *cpu, int pstate)
2234 {
2235         int min_pstate = max(cpu->pstate.min_pstate, cpu->min_perf_ratio);
2236         int max_pstate = max(min_pstate, cpu->max_perf_ratio);
2237
2238         return clamp_t(int, pstate, min_pstate, max_pstate);
2239 }
2240
2241 static void intel_pstate_update_pstate(struct cpudata *cpu, int pstate)
2242 {
2243         if (pstate == cpu->pstate.current_pstate)
2244                 return;
2245
2246         cpu->pstate.current_pstate = pstate;
2247         wrmsrl(MSR_IA32_PERF_CTL, pstate_funcs.get_val(cpu, pstate));
2248 }
2249
2250 static void intel_pstate_adjust_pstate(struct cpudata *cpu)
2251 {
2252         int from = cpu->pstate.current_pstate;
2253         struct sample *sample;
2254         int target_pstate;
2255
2256         update_turbo_state();
2257
2258         target_pstate = get_target_pstate(cpu);
2259         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2260         trace_cpu_frequency(target_pstate * cpu->pstate.scaling, cpu->cpu);
2261         intel_pstate_update_pstate(cpu, target_pstate);
2262
2263         sample = &cpu->sample;
2264         trace_pstate_sample(mul_ext_fp(100, sample->core_avg_perf),
2265                 fp_toint(sample->busy_scaled),
2266                 from,
2267                 cpu->pstate.current_pstate,
2268                 sample->mperf,
2269                 sample->aperf,
2270                 sample->tsc,
2271                 get_avg_frequency(cpu),
2272                 fp_toint(cpu->iowait_boost * 100));
2273 }
2274
2275 static void intel_pstate_update_util(struct update_util_data *data, u64 time,
2276                                      unsigned int flags)
2277 {
2278         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
2279         u64 delta_ns;
2280
2281         /* Don't allow remote callbacks */
2282         if (smp_processor_id() != cpu->cpu)
2283                 return;
2284
2285         delta_ns = time - cpu->last_update;
2286         if (flags & SCHED_CPUFREQ_IOWAIT) {
2287                 /* Start over if the CPU may have been idle. */
2288                 if (delta_ns > TICK_NSEC) {
2289                         cpu->iowait_boost = ONE_EIGHTH_FP;
2290                 } else if (cpu->iowait_boost >= ONE_EIGHTH_FP) {
2291                         cpu->iowait_boost <<= 1;
2292                         if (cpu->iowait_boost > int_tofp(1))
2293                                 cpu->iowait_boost = int_tofp(1);
2294                 } else {
2295                         cpu->iowait_boost = ONE_EIGHTH_FP;
2296                 }
2297         } else if (cpu->iowait_boost) {
2298                 /* Clear iowait_boost if the CPU may have been idle. */
2299                 if (delta_ns > TICK_NSEC)
2300                         cpu->iowait_boost = 0;
2301                 else
2302                         cpu->iowait_boost >>= 1;
2303         }
2304         cpu->last_update = time;
2305         delta_ns = time - cpu->sample.time;
2306         if ((s64)delta_ns < INTEL_PSTATE_SAMPLING_INTERVAL)
2307                 return;
2308
2309         if (intel_pstate_sample(cpu, time))
2310                 intel_pstate_adjust_pstate(cpu);
2311 }
2312
2313 static struct pstate_funcs core_funcs = {
2314         .get_max = core_get_max_pstate,
2315         .get_max_physical = core_get_max_pstate_physical,
2316         .get_min = core_get_min_pstate,
2317         .get_turbo = core_get_turbo_pstate,
2318         .get_scaling = core_get_scaling,
2319         .get_val = core_get_val,
2320 };
2321
2322 static const struct pstate_funcs silvermont_funcs = {
2323         .get_max = atom_get_max_pstate,
2324         .get_max_physical = atom_get_max_pstate,
2325         .get_min = atom_get_min_pstate,
2326         .get_turbo = atom_get_turbo_pstate,
2327         .get_val = atom_get_val,
2328         .get_scaling = silvermont_get_scaling,
2329         .get_vid = atom_get_vid,
2330 };
2331
2332 static const struct pstate_funcs airmont_funcs = {
2333         .get_max = atom_get_max_pstate,
2334         .get_max_physical = atom_get_max_pstate,
2335         .get_min = atom_get_min_pstate,
2336         .get_turbo = atom_get_turbo_pstate,
2337         .get_val = atom_get_val,
2338         .get_scaling = airmont_get_scaling,
2339         .get_vid = atom_get_vid,
2340 };
2341
2342 static const struct pstate_funcs knl_funcs = {
2343         .get_max = core_get_max_pstate,
2344         .get_max_physical = core_get_max_pstate_physical,
2345         .get_min = core_get_min_pstate,
2346         .get_turbo = knl_get_turbo_pstate,
2347         .get_aperf_mperf_shift = knl_get_aperf_mperf_shift,
2348         .get_scaling = core_get_scaling,
2349         .get_val = core_get_val,
2350 };
2351
2352 #define X86_MATCH(model, policy)                                         \
2353         X86_MATCH_VENDOR_FAM_MODEL_FEATURE(INTEL, 6, INTEL_FAM6_##model, \
2354                                            X86_FEATURE_APERFMPERF, &policy)
2355
2356 static const struct x86_cpu_id intel_pstate_cpu_ids[] = {
2357         X86_MATCH(SANDYBRIDGE,          core_funcs),
2358         X86_MATCH(SANDYBRIDGE_X,        core_funcs),
2359         X86_MATCH(ATOM_SILVERMONT,      silvermont_funcs),
2360         X86_MATCH(IVYBRIDGE,            core_funcs),
2361         X86_MATCH(HASWELL,              core_funcs),
2362         X86_MATCH(BROADWELL,            core_funcs),
2363         X86_MATCH(IVYBRIDGE_X,          core_funcs),
2364         X86_MATCH(HASWELL_X,            core_funcs),
2365         X86_MATCH(HASWELL_L,            core_funcs),
2366         X86_MATCH(HASWELL_G,            core_funcs),
2367         X86_MATCH(BROADWELL_G,          core_funcs),
2368         X86_MATCH(ATOM_AIRMONT,         airmont_funcs),
2369         X86_MATCH(SKYLAKE_L,            core_funcs),
2370         X86_MATCH(BROADWELL_X,          core_funcs),
2371         X86_MATCH(SKYLAKE,              core_funcs),
2372         X86_MATCH(BROADWELL_D,          core_funcs),
2373         X86_MATCH(XEON_PHI_KNL,         knl_funcs),
2374         X86_MATCH(XEON_PHI_KNM,         knl_funcs),
2375         X86_MATCH(ATOM_GOLDMONT,        core_funcs),
2376         X86_MATCH(ATOM_GOLDMONT_PLUS,   core_funcs),
2377         X86_MATCH(SKYLAKE_X,            core_funcs),
2378         X86_MATCH(COMETLAKE,            core_funcs),
2379         X86_MATCH(ICELAKE_X,            core_funcs),
2380         X86_MATCH(TIGERLAKE,            core_funcs),
2381         {}
2382 };
2383 MODULE_DEVICE_TABLE(x86cpu, intel_pstate_cpu_ids);
2384
2385 static const struct x86_cpu_id intel_pstate_cpu_oob_ids[] __initconst = {
2386         X86_MATCH(BROADWELL_D,          core_funcs),
2387         X86_MATCH(BROADWELL_X,          core_funcs),
2388         X86_MATCH(SKYLAKE_X,            core_funcs),
2389         X86_MATCH(ICELAKE_X,            core_funcs),
2390         X86_MATCH(SAPPHIRERAPIDS_X,     core_funcs),
2391         {}
2392 };
2393
2394 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[] = {
2395         X86_MATCH(KABYLAKE,             core_funcs),
2396         {}
2397 };
2398
2399 static const struct x86_cpu_id intel_pstate_hwp_boost_ids[] = {
2400         X86_MATCH(SKYLAKE_X,            core_funcs),
2401         X86_MATCH(SKYLAKE,              core_funcs),
2402         {}
2403 };
2404
2405 static int intel_pstate_init_cpu(unsigned int cpunum)
2406 {
2407         struct cpudata *cpu;
2408
2409         cpu = all_cpu_data[cpunum];
2410
2411         if (!cpu) {
2412                 cpu = kzalloc(sizeof(*cpu), GFP_KERNEL);
2413                 if (!cpu)
2414                         return -ENOMEM;
2415
2416                 WRITE_ONCE(all_cpu_data[cpunum], cpu);
2417
2418                 cpu->cpu = cpunum;
2419
2420                 cpu->epp_default = -EINVAL;
2421
2422                 if (hwp_active) {
2423                         const struct x86_cpu_id *id;
2424
2425                         intel_pstate_hwp_enable(cpu);
2426
2427                         id = x86_match_cpu(intel_pstate_hwp_boost_ids);
2428                         if (id && intel_pstate_acpi_pm_profile_server())
2429                                 hwp_boost = true;
2430                 }
2431         } else if (hwp_active) {
2432                 /*
2433                  * Re-enable HWP in case this happens after a resume from ACPI
2434                  * S3 if the CPU was offline during the whole system/resume
2435                  * cycle.
2436                  */
2437                 intel_pstate_hwp_reenable(cpu);
2438         }
2439
2440         cpu->epp_powersave = -EINVAL;
2441         cpu->epp_policy = 0;
2442
2443         intel_pstate_get_cpu_pstates(cpu);
2444
2445         pr_debug("controlling: cpu %d\n", cpunum);
2446
2447         return 0;
2448 }
2449
2450 static void intel_pstate_set_update_util_hook(unsigned int cpu_num)
2451 {
2452         struct cpudata *cpu = all_cpu_data[cpu_num];
2453
2454         if (hwp_active && !hwp_boost)
2455                 return;
2456
2457         if (cpu->update_util_set)
2458                 return;
2459
2460         /* Prevent intel_pstate_update_util() from using stale data. */
2461         cpu->sample.time = 0;
2462         cpufreq_add_update_util_hook(cpu_num, &cpu->update_util,
2463                                      (hwp_active ?
2464                                       intel_pstate_update_util_hwp :
2465                                       intel_pstate_update_util));
2466         cpu->update_util_set = true;
2467 }
2468
2469 static void intel_pstate_clear_update_util_hook(unsigned int cpu)
2470 {
2471         struct cpudata *cpu_data = all_cpu_data[cpu];
2472
2473         if (!cpu_data->update_util_set)
2474                 return;
2475
2476         cpufreq_remove_update_util_hook(cpu);
2477         cpu_data->update_util_set = false;
2478         synchronize_rcu();
2479 }
2480
2481 static int intel_pstate_get_max_freq(struct cpudata *cpu)
2482 {
2483         return global.turbo_disabled || global.no_turbo ?
2484                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2485 }
2486
2487 static void intel_pstate_update_perf_limits(struct cpudata *cpu,
2488                                             unsigned int policy_min,
2489                                             unsigned int policy_max)
2490 {
2491         int perf_ctl_scaling = cpu->pstate.perf_ctl_scaling;
2492         int32_t max_policy_perf, min_policy_perf;
2493
2494         max_policy_perf = policy_max / perf_ctl_scaling;
2495         if (policy_max == policy_min) {
2496                 min_policy_perf = max_policy_perf;
2497         } else {
2498                 min_policy_perf = policy_min / perf_ctl_scaling;
2499                 min_policy_perf = clamp_t(int32_t, min_policy_perf,
2500                                           0, max_policy_perf);
2501         }
2502
2503         /*
2504          * HWP needs some special consideration, because HWP_REQUEST uses
2505          * abstract values to represent performance rather than pure ratios.
2506          */
2507         if (hwp_active && cpu->pstate.scaling != perf_ctl_scaling) {
2508                 int scaling = cpu->pstate.scaling;
2509                 int freq;
2510
2511                 freq = max_policy_perf * perf_ctl_scaling;
2512                 max_policy_perf = DIV_ROUND_UP(freq, scaling);
2513                 freq = min_policy_perf * perf_ctl_scaling;
2514                 min_policy_perf = DIV_ROUND_UP(freq, scaling);
2515         }
2516
2517         pr_debug("cpu:%d min_policy_perf:%d max_policy_perf:%d\n",
2518                  cpu->cpu, min_policy_perf, max_policy_perf);
2519
2520         /* Normalize user input to [min_perf, max_perf] */
2521         if (per_cpu_limits) {
2522                 cpu->min_perf_ratio = min_policy_perf;
2523                 cpu->max_perf_ratio = max_policy_perf;
2524         } else {
2525                 int turbo_max = cpu->pstate.turbo_pstate;
2526                 int32_t global_min, global_max;
2527
2528                 /* Global limits are in percent of the maximum turbo P-state. */
2529                 global_max = DIV_ROUND_UP(turbo_max * global.max_perf_pct, 100);
2530                 global_min = DIV_ROUND_UP(turbo_max * global.min_perf_pct, 100);
2531                 global_min = clamp_t(int32_t, global_min, 0, global_max);
2532
2533                 pr_debug("cpu:%d global_min:%d global_max:%d\n", cpu->cpu,
2534                          global_min, global_max);
2535
2536                 cpu->min_perf_ratio = max(min_policy_perf, global_min);
2537                 cpu->min_perf_ratio = min(cpu->min_perf_ratio, max_policy_perf);
2538                 cpu->max_perf_ratio = min(max_policy_perf, global_max);
2539                 cpu->max_perf_ratio = max(min_policy_perf, cpu->max_perf_ratio);
2540
2541                 /* Make sure min_perf <= max_perf */
2542                 cpu->min_perf_ratio = min(cpu->min_perf_ratio,
2543                                           cpu->max_perf_ratio);
2544
2545         }
2546         pr_debug("cpu:%d max_perf_ratio:%d min_perf_ratio:%d\n", cpu->cpu,
2547                  cpu->max_perf_ratio,
2548                  cpu->min_perf_ratio);
2549 }
2550
2551 static int intel_pstate_set_policy(struct cpufreq_policy *policy)
2552 {
2553         struct cpudata *cpu;
2554
2555         if (!policy->cpuinfo.max_freq)
2556                 return -ENODEV;
2557
2558         pr_debug("set_policy cpuinfo.max %u policy->max %u\n",
2559                  policy->cpuinfo.max_freq, policy->max);
2560
2561         cpu = all_cpu_data[policy->cpu];
2562         cpu->policy = policy->policy;
2563
2564         mutex_lock(&intel_pstate_limits_lock);
2565
2566         intel_pstate_update_perf_limits(cpu, policy->min, policy->max);
2567
2568         if (cpu->policy == CPUFREQ_POLICY_PERFORMANCE) {
2569                 /*
2570                  * NOHZ_FULL CPUs need this as the governor callback may not
2571                  * be invoked on them.
2572                  */
2573                 intel_pstate_clear_update_util_hook(policy->cpu);
2574                 intel_pstate_max_within_limits(cpu);
2575         } else {
2576                 intel_pstate_set_update_util_hook(policy->cpu);
2577         }
2578
2579         if (hwp_active) {
2580                 /*
2581                  * When hwp_boost was active before and dynamically it
2582                  * was turned off, in that case we need to clear the
2583                  * update util hook.
2584                  */
2585                 if (!hwp_boost)
2586                         intel_pstate_clear_update_util_hook(policy->cpu);
2587                 intel_pstate_hwp_set(policy->cpu);
2588         }
2589
2590         mutex_unlock(&intel_pstate_limits_lock);
2591
2592         return 0;
2593 }
2594
2595 static void intel_pstate_adjust_policy_max(struct cpudata *cpu,
2596                                            struct cpufreq_policy_data *policy)
2597 {
2598         if (!hwp_active &&
2599             cpu->pstate.max_pstate_physical > cpu->pstate.max_pstate &&
2600             policy->max < policy->cpuinfo.max_freq &&
2601             policy->max > cpu->pstate.max_freq) {
2602                 pr_debug("policy->max > max non turbo frequency\n");
2603                 policy->max = policy->cpuinfo.max_freq;
2604         }
2605 }
2606
2607 static void intel_pstate_verify_cpu_policy(struct cpudata *cpu,
2608                                            struct cpufreq_policy_data *policy)
2609 {
2610         int max_freq;
2611
2612         update_turbo_state();
2613         if (hwp_active) {
2614                 intel_pstate_get_hwp_cap(cpu);
2615                 max_freq = global.no_turbo || global.turbo_disabled ?
2616                                 cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2617         } else {
2618                 max_freq = intel_pstate_get_max_freq(cpu);
2619         }
2620         cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, max_freq);
2621
2622         intel_pstate_adjust_policy_max(cpu, policy);
2623 }
2624
2625 static int intel_pstate_verify_policy(struct cpufreq_policy_data *policy)
2626 {
2627         intel_pstate_verify_cpu_policy(all_cpu_data[policy->cpu], policy);
2628
2629         return 0;
2630 }
2631
2632 static int intel_cpufreq_cpu_offline(struct cpufreq_policy *policy)
2633 {
2634         struct cpudata *cpu = all_cpu_data[policy->cpu];
2635
2636         pr_debug("CPU %d going offline\n", cpu->cpu);
2637
2638         if (cpu->suspended)
2639                 return 0;
2640
2641         /*
2642          * If the CPU is an SMT thread and it goes offline with the performance
2643          * settings different from the minimum, it will prevent its sibling
2644          * from getting to lower performance levels, so force the minimum
2645          * performance on CPU offline to prevent that from happening.
2646          */
2647         if (hwp_active)
2648                 intel_pstate_hwp_offline(cpu);
2649         else
2650                 intel_pstate_set_min_pstate(cpu);
2651
2652         intel_pstate_exit_perf_limits(policy);
2653
2654         return 0;
2655 }
2656
2657 static int intel_pstate_cpu_online(struct cpufreq_policy *policy)
2658 {
2659         struct cpudata *cpu = all_cpu_data[policy->cpu];
2660
2661         pr_debug("CPU %d going online\n", cpu->cpu);
2662
2663         intel_pstate_init_acpi_perf_limits(policy);
2664
2665         if (hwp_active) {
2666                 /*
2667                  * Re-enable HWP and clear the "suspended" flag to let "resume"
2668                  * know that it need not do that.
2669                  */
2670                 intel_pstate_hwp_reenable(cpu);
2671                 cpu->suspended = false;
2672         }
2673
2674         return 0;
2675 }
2676
2677 static int intel_pstate_cpu_offline(struct cpufreq_policy *policy)
2678 {
2679         intel_pstate_clear_update_util_hook(policy->cpu);
2680
2681         return intel_cpufreq_cpu_offline(policy);
2682 }
2683
2684 static int intel_pstate_cpu_exit(struct cpufreq_policy *policy)
2685 {
2686         pr_debug("CPU %d exiting\n", policy->cpu);
2687
2688         policy->fast_switch_possible = false;
2689
2690         return 0;
2691 }
2692
2693 static int __intel_pstate_cpu_init(struct cpufreq_policy *policy)
2694 {
2695         struct cpudata *cpu;
2696         int rc;
2697
2698         rc = intel_pstate_init_cpu(policy->cpu);
2699         if (rc)
2700                 return rc;
2701
2702         cpu = all_cpu_data[policy->cpu];
2703
2704         cpu->max_perf_ratio = 0xFF;
2705         cpu->min_perf_ratio = 0;
2706
2707         /* cpuinfo and default policy values */
2708         policy->cpuinfo.min_freq = cpu->pstate.min_freq;
2709         update_turbo_state();
2710         global.turbo_disabled_mf = global.turbo_disabled;
2711         policy->cpuinfo.max_freq = global.turbo_disabled ?
2712                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2713
2714         policy->min = policy->cpuinfo.min_freq;
2715         policy->max = policy->cpuinfo.max_freq;
2716
2717         intel_pstate_init_acpi_perf_limits(policy);
2718
2719         policy->fast_switch_possible = true;
2720
2721         return 0;
2722 }
2723
2724 static int intel_pstate_cpu_init(struct cpufreq_policy *policy)
2725 {
2726         int ret = __intel_pstate_cpu_init(policy);
2727
2728         if (ret)
2729                 return ret;
2730
2731         /*
2732          * Set the policy to powersave to provide a valid fallback value in case
2733          * the default cpufreq governor is neither powersave nor performance.
2734          */
2735         policy->policy = CPUFREQ_POLICY_POWERSAVE;
2736
2737         if (hwp_active) {
2738                 struct cpudata *cpu = all_cpu_data[policy->cpu];
2739
2740                 cpu->epp_cached = intel_pstate_get_epp(cpu, 0);
2741         }
2742
2743         return 0;
2744 }
2745
2746 static struct cpufreq_driver intel_pstate = {
2747         .flags          = CPUFREQ_CONST_LOOPS,
2748         .verify         = intel_pstate_verify_policy,
2749         .setpolicy      = intel_pstate_set_policy,
2750         .suspend        = intel_pstate_suspend,
2751         .resume         = intel_pstate_resume,
2752         .init           = intel_pstate_cpu_init,
2753         .exit           = intel_pstate_cpu_exit,
2754         .offline        = intel_pstate_cpu_offline,
2755         .online         = intel_pstate_cpu_online,
2756         .update_limits  = intel_pstate_update_limits,
2757         .name           = "intel_pstate",
2758 };
2759
2760 static int intel_cpufreq_verify_policy(struct cpufreq_policy_data *policy)
2761 {
2762         struct cpudata *cpu = all_cpu_data[policy->cpu];
2763
2764         intel_pstate_verify_cpu_policy(cpu, policy);
2765         intel_pstate_update_perf_limits(cpu, policy->min, policy->max);
2766
2767         return 0;
2768 }
2769
2770 /* Use of trace in passive mode:
2771  *
2772  * In passive mode the trace core_busy field (also known as the
2773  * performance field, and lablelled as such on the graphs; also known as
2774  * core_avg_perf) is not needed and so is re-assigned to indicate if the
2775  * driver call was via the normal or fast switch path. Various graphs
2776  * output from the intel_pstate_tracer.py utility that include core_busy
2777  * (or performance or core_avg_perf) have a fixed y-axis from 0 to 100%,
2778  * so we use 10 to indicate the normal path through the driver, and
2779  * 90 to indicate the fast switch path through the driver.
2780  * The scaled_busy field is not used, and is set to 0.
2781  */
2782
2783 #define INTEL_PSTATE_TRACE_TARGET 10
2784 #define INTEL_PSTATE_TRACE_FAST_SWITCH 90
2785
2786 static void intel_cpufreq_trace(struct cpudata *cpu, unsigned int trace_type, int old_pstate)
2787 {
2788         struct sample *sample;
2789
2790         if (!trace_pstate_sample_enabled())
2791                 return;
2792
2793         if (!intel_pstate_sample(cpu, ktime_get()))
2794                 return;
2795
2796         sample = &cpu->sample;
2797         trace_pstate_sample(trace_type,
2798                 0,
2799                 old_pstate,
2800                 cpu->pstate.current_pstate,
2801                 sample->mperf,
2802                 sample->aperf,
2803                 sample->tsc,
2804                 get_avg_frequency(cpu),
2805                 fp_toint(cpu->iowait_boost * 100));
2806 }
2807
2808 static void intel_cpufreq_hwp_update(struct cpudata *cpu, u32 min, u32 max,
2809                                      u32 desired, bool fast_switch)
2810 {
2811         u64 prev = READ_ONCE(cpu->hwp_req_cached), value = prev;
2812
2813         value &= ~HWP_MIN_PERF(~0L);
2814         value |= HWP_MIN_PERF(min);
2815
2816         value &= ~HWP_MAX_PERF(~0L);
2817         value |= HWP_MAX_PERF(max);
2818
2819         value &= ~HWP_DESIRED_PERF(~0L);
2820         value |= HWP_DESIRED_PERF(desired);
2821
2822         if (value == prev)
2823                 return;
2824
2825         WRITE_ONCE(cpu->hwp_req_cached, value);
2826         if (fast_switch)
2827                 wrmsrl(MSR_HWP_REQUEST, value);
2828         else
2829                 wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
2830 }
2831
2832 static void intel_cpufreq_perf_ctl_update(struct cpudata *cpu,
2833                                           u32 target_pstate, bool fast_switch)
2834 {
2835         if (fast_switch)
2836                 wrmsrl(MSR_IA32_PERF_CTL,
2837                        pstate_funcs.get_val(cpu, target_pstate));
2838         else
2839                 wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
2840                               pstate_funcs.get_val(cpu, target_pstate));
2841 }
2842
2843 static int intel_cpufreq_update_pstate(struct cpufreq_policy *policy,
2844                                        int target_pstate, bool fast_switch)
2845 {
2846         struct cpudata *cpu = all_cpu_data[policy->cpu];
2847         int old_pstate = cpu->pstate.current_pstate;
2848
2849         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2850         if (hwp_active) {
2851                 int max_pstate = policy->strict_target ?
2852                                         target_pstate : cpu->max_perf_ratio;
2853
2854                 intel_cpufreq_hwp_update(cpu, target_pstate, max_pstate, 0,
2855                                          fast_switch);
2856         } else if (target_pstate != old_pstate) {
2857                 intel_cpufreq_perf_ctl_update(cpu, target_pstate, fast_switch);
2858         }
2859
2860         cpu->pstate.current_pstate = target_pstate;
2861
2862         intel_cpufreq_trace(cpu, fast_switch ? INTEL_PSTATE_TRACE_FAST_SWITCH :
2863                             INTEL_PSTATE_TRACE_TARGET, old_pstate);
2864
2865         return target_pstate;
2866 }
2867
2868 static int intel_cpufreq_target(struct cpufreq_policy *policy,
2869                                 unsigned int target_freq,
2870                                 unsigned int relation)
2871 {
2872         struct cpudata *cpu = all_cpu_data[policy->cpu];
2873         struct cpufreq_freqs freqs;
2874         int target_pstate;
2875
2876         update_turbo_state();
2877
2878         freqs.old = policy->cur;
2879         freqs.new = target_freq;
2880
2881         cpufreq_freq_transition_begin(policy, &freqs);
2882
2883         switch (relation) {
2884         case CPUFREQ_RELATION_L:
2885                 target_pstate = DIV_ROUND_UP(freqs.new, cpu->pstate.scaling);
2886                 break;
2887         case CPUFREQ_RELATION_H:
2888                 target_pstate = freqs.new / cpu->pstate.scaling;
2889                 break;
2890         default:
2891                 target_pstate = DIV_ROUND_CLOSEST(freqs.new, cpu->pstate.scaling);
2892                 break;
2893         }
2894
2895         target_pstate = intel_cpufreq_update_pstate(policy, target_pstate, false);
2896
2897         freqs.new = target_pstate * cpu->pstate.scaling;
2898
2899         cpufreq_freq_transition_end(policy, &freqs, false);
2900
2901         return 0;
2902 }
2903
2904 static unsigned int intel_cpufreq_fast_switch(struct cpufreq_policy *policy,
2905                                               unsigned int target_freq)
2906 {
2907         struct cpudata *cpu = all_cpu_data[policy->cpu];
2908         int target_pstate;
2909
2910         update_turbo_state();
2911
2912         target_pstate = DIV_ROUND_UP(target_freq, cpu->pstate.scaling);
2913
2914         target_pstate = intel_cpufreq_update_pstate(policy, target_pstate, true);
2915
2916         return target_pstate * cpu->pstate.scaling;
2917 }
2918
2919 static void intel_cpufreq_adjust_perf(unsigned int cpunum,
2920                                       unsigned long min_perf,
2921                                       unsigned long target_perf,
2922                                       unsigned long capacity)
2923 {
2924         struct cpudata *cpu = all_cpu_data[cpunum];
2925         u64 hwp_cap = READ_ONCE(cpu->hwp_cap_cached);
2926         int old_pstate = cpu->pstate.current_pstate;
2927         int cap_pstate, min_pstate, max_pstate, target_pstate;
2928
2929         update_turbo_state();
2930         cap_pstate = global.turbo_disabled ? HWP_GUARANTEED_PERF(hwp_cap) :
2931                                              HWP_HIGHEST_PERF(hwp_cap);
2932
2933         /* Optimization: Avoid unnecessary divisions. */
2934
2935         target_pstate = cap_pstate;
2936         if (target_perf < capacity)
2937                 target_pstate = DIV_ROUND_UP(cap_pstate * target_perf, capacity);
2938
2939         min_pstate = cap_pstate;
2940         if (min_perf < capacity)
2941                 min_pstate = DIV_ROUND_UP(cap_pstate * min_perf, capacity);
2942
2943         if (min_pstate < cpu->pstate.min_pstate)
2944                 min_pstate = cpu->pstate.min_pstate;
2945
2946         if (min_pstate < cpu->min_perf_ratio)
2947                 min_pstate = cpu->min_perf_ratio;
2948
2949         max_pstate = min(cap_pstate, cpu->max_perf_ratio);
2950         if (max_pstate < min_pstate)
2951                 max_pstate = min_pstate;
2952
2953         target_pstate = clamp_t(int, target_pstate, min_pstate, max_pstate);
2954
2955         intel_cpufreq_hwp_update(cpu, min_pstate, max_pstate, target_pstate, true);
2956
2957         cpu->pstate.current_pstate = target_pstate;
2958         intel_cpufreq_trace(cpu, INTEL_PSTATE_TRACE_FAST_SWITCH, old_pstate);
2959 }
2960
2961 static int intel_cpufreq_cpu_init(struct cpufreq_policy *policy)
2962 {
2963         struct freq_qos_request *req;
2964         struct cpudata *cpu;
2965         struct device *dev;
2966         int ret, freq;
2967
2968         dev = get_cpu_device(policy->cpu);
2969         if (!dev)
2970                 return -ENODEV;
2971
2972         ret = __intel_pstate_cpu_init(policy);
2973         if (ret)
2974                 return ret;
2975
2976         policy->cpuinfo.transition_latency = INTEL_CPUFREQ_TRANSITION_LATENCY;
2977         /* This reflects the intel_pstate_get_cpu_pstates() setting. */
2978         policy->cur = policy->cpuinfo.min_freq;
2979
2980         req = kcalloc(2, sizeof(*req), GFP_KERNEL);
2981         if (!req) {
2982                 ret = -ENOMEM;
2983                 goto pstate_exit;
2984         }
2985
2986         cpu = all_cpu_data[policy->cpu];
2987
2988         if (hwp_active) {
2989                 u64 value;
2990
2991                 policy->transition_delay_us = INTEL_CPUFREQ_TRANSITION_DELAY_HWP;
2992
2993                 intel_pstate_get_hwp_cap(cpu);
2994
2995                 rdmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, &value);
2996                 WRITE_ONCE(cpu->hwp_req_cached, value);
2997
2998                 cpu->epp_cached = intel_pstate_get_epp(cpu, value);
2999         } else {
3000                 policy->transition_delay_us = INTEL_CPUFREQ_TRANSITION_DELAY;
3001         }
3002
3003         freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * global.min_perf_pct, 100);
3004
3005         ret = freq_qos_add_request(&policy->constraints, req, FREQ_QOS_MIN,
3006                                    freq);
3007         if (ret < 0) {
3008                 dev_err(dev, "Failed to add min-freq constraint (%d)\n", ret);
3009                 goto free_req;
3010         }
3011
3012         freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * global.max_perf_pct, 100);
3013
3014         ret = freq_qos_add_request(&policy->constraints, req + 1, FREQ_QOS_MAX,
3015                                    freq);
3016         if (ret < 0) {
3017                 dev_err(dev, "Failed to add max-freq constraint (%d)\n", ret);
3018                 goto remove_min_req;
3019         }
3020
3021         policy->driver_data = req;
3022
3023         return 0;
3024
3025 remove_min_req:
3026         freq_qos_remove_request(req);
3027 free_req:
3028         kfree(req);
3029 pstate_exit:
3030         intel_pstate_exit_perf_limits(policy);
3031
3032         return ret;
3033 }
3034
3035 static int intel_cpufreq_cpu_exit(struct cpufreq_policy *policy)
3036 {
3037         struct freq_qos_request *req;
3038
3039         req = policy->driver_data;
3040
3041         freq_qos_remove_request(req + 1);
3042         freq_qos_remove_request(req);
3043         kfree(req);
3044
3045         return intel_pstate_cpu_exit(policy);
3046 }
3047
3048 static int intel_cpufreq_suspend(struct cpufreq_policy *policy)
3049 {
3050         intel_pstate_suspend(policy);
3051
3052         if (hwp_active) {
3053                 struct cpudata *cpu = all_cpu_data[policy->cpu];
3054                 u64 value = READ_ONCE(cpu->hwp_req_cached);
3055
3056                 /*
3057                  * Clear the desired perf field in MSR_HWP_REQUEST in case
3058                  * intel_cpufreq_adjust_perf() is in use and the last value
3059                  * written by it may not be suitable.
3060                  */
3061                 value &= ~HWP_DESIRED_PERF(~0L);
3062                 wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
3063                 WRITE_ONCE(cpu->hwp_req_cached, value);
3064         }
3065
3066         return 0;
3067 }
3068
3069 static struct cpufreq_driver intel_cpufreq = {
3070         .flags          = CPUFREQ_CONST_LOOPS,
3071         .verify         = intel_cpufreq_verify_policy,
3072         .target         = intel_cpufreq_target,
3073         .fast_switch    = intel_cpufreq_fast_switch,
3074         .init           = intel_cpufreq_cpu_init,
3075         .exit           = intel_cpufreq_cpu_exit,
3076         .offline        = intel_cpufreq_cpu_offline,
3077         .online         = intel_pstate_cpu_online,
3078         .suspend        = intel_cpufreq_suspend,
3079         .resume         = intel_pstate_resume,
3080         .update_limits  = intel_pstate_update_limits,
3081         .name           = "intel_cpufreq",
3082 };
3083
3084 static struct cpufreq_driver *default_driver;
3085
3086 static void intel_pstate_driver_cleanup(void)
3087 {
3088         unsigned int cpu;
3089
3090         cpus_read_lock();
3091         for_each_online_cpu(cpu) {
3092                 if (all_cpu_data[cpu]) {
3093                         if (intel_pstate_driver == &intel_pstate)
3094                                 intel_pstate_clear_update_util_hook(cpu);
3095
3096                         spin_lock(&hwp_notify_lock);
3097                         kfree(all_cpu_data[cpu]);
3098                         WRITE_ONCE(all_cpu_data[cpu], NULL);
3099                         spin_unlock(&hwp_notify_lock);
3100                 }
3101         }
3102         cpus_read_unlock();
3103
3104         intel_pstate_driver = NULL;
3105 }
3106
3107 static int intel_pstate_register_driver(struct cpufreq_driver *driver)
3108 {
3109         int ret;
3110
3111         if (driver == &intel_pstate)
3112                 intel_pstate_sysfs_expose_hwp_dynamic_boost();
3113
3114         memset(&global, 0, sizeof(global));
3115         global.max_perf_pct = 100;
3116
3117         intel_pstate_driver = driver;
3118         ret = cpufreq_register_driver(intel_pstate_driver);
3119         if (ret) {
3120                 intel_pstate_driver_cleanup();
3121                 return ret;
3122         }
3123
3124         global.min_perf_pct = min_perf_pct_min();
3125
3126         return 0;
3127 }
3128
3129 static ssize_t intel_pstate_show_status(char *buf)
3130 {
3131         if (!intel_pstate_driver)
3132                 return sprintf(buf, "off\n");
3133
3134         return sprintf(buf, "%s\n", intel_pstate_driver == &intel_pstate ?
3135                                         "active" : "passive");
3136 }
3137
3138 static int intel_pstate_update_status(const char *buf, size_t size)
3139 {
3140         if (size == 3 && !strncmp(buf, "off", size)) {
3141                 if (!intel_pstate_driver)
3142                         return -EINVAL;
3143
3144                 if (hwp_active)
3145                         return -EBUSY;
3146
3147                 cpufreq_unregister_driver(intel_pstate_driver);
3148                 intel_pstate_driver_cleanup();
3149                 return 0;
3150         }
3151
3152         if (size == 6 && !strncmp(buf, "active", size)) {
3153                 if (intel_pstate_driver) {
3154                         if (intel_pstate_driver == &intel_pstate)
3155                                 return 0;
3156
3157                         cpufreq_unregister_driver(intel_pstate_driver);
3158                 }
3159
3160                 return intel_pstate_register_driver(&intel_pstate);
3161         }
3162
3163         if (size == 7 && !strncmp(buf, "passive", size)) {
3164                 if (intel_pstate_driver) {
3165                         if (intel_pstate_driver == &intel_cpufreq)
3166                                 return 0;
3167
3168                         cpufreq_unregister_driver(intel_pstate_driver);
3169                         intel_pstate_sysfs_hide_hwp_dynamic_boost();
3170                 }
3171
3172                 return intel_pstate_register_driver(&intel_cpufreq);
3173         }
3174
3175         return -EINVAL;
3176 }
3177
3178 static int no_load __initdata;
3179 static int no_hwp __initdata;
3180 static int hwp_only __initdata;
3181 static unsigned int force_load __initdata;
3182
3183 static int __init intel_pstate_msrs_not_valid(void)
3184 {
3185         if (!pstate_funcs.get_max(0) ||
3186             !pstate_funcs.get_min(0) ||
3187             !pstate_funcs.get_turbo(0))
3188                 return -ENODEV;
3189
3190         return 0;
3191 }
3192
3193 static void __init copy_cpu_funcs(struct pstate_funcs *funcs)
3194 {
3195         pstate_funcs.get_max   = funcs->get_max;
3196         pstate_funcs.get_max_physical = funcs->get_max_physical;
3197         pstate_funcs.get_min   = funcs->get_min;
3198         pstate_funcs.get_turbo = funcs->get_turbo;
3199         pstate_funcs.get_scaling = funcs->get_scaling;
3200         pstate_funcs.get_val   = funcs->get_val;
3201         pstate_funcs.get_vid   = funcs->get_vid;
3202         pstate_funcs.get_aperf_mperf_shift = funcs->get_aperf_mperf_shift;
3203 }
3204
3205 #ifdef CONFIG_ACPI
3206
3207 static bool __init intel_pstate_no_acpi_pss(void)
3208 {
3209         int i;
3210
3211         for_each_possible_cpu(i) {
3212                 acpi_status status;
3213                 union acpi_object *pss;
3214                 struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
3215                 struct acpi_processor *pr = per_cpu(processors, i);
3216
3217                 if (!pr)
3218                         continue;
3219
3220                 status = acpi_evaluate_object(pr->handle, "_PSS", NULL, &buffer);
3221                 if (ACPI_FAILURE(status))
3222                         continue;
3223
3224                 pss = buffer.pointer;
3225                 if (pss && pss->type == ACPI_TYPE_PACKAGE) {
3226                         kfree(pss);
3227                         return false;
3228                 }
3229
3230                 kfree(pss);
3231         }
3232
3233         pr_debug("ACPI _PSS not found\n");
3234         return true;
3235 }
3236
3237 static bool __init intel_pstate_no_acpi_pcch(void)
3238 {
3239         acpi_status status;
3240         acpi_handle handle;
3241
3242         status = acpi_get_handle(NULL, "\\_SB", &handle);
3243         if (ACPI_FAILURE(status))
3244                 goto not_found;
3245
3246         if (acpi_has_method(handle, "PCCH"))
3247                 return false;
3248
3249 not_found:
3250         pr_debug("ACPI PCCH not found\n");
3251         return true;
3252 }
3253
3254 static bool __init intel_pstate_has_acpi_ppc(void)
3255 {
3256         int i;
3257
3258         for_each_possible_cpu(i) {
3259                 struct acpi_processor *pr = per_cpu(processors, i);
3260
3261                 if (!pr)
3262                         continue;
3263                 if (acpi_has_method(pr->handle, "_PPC"))
3264                         return true;
3265         }
3266         pr_debug("ACPI _PPC not found\n");
3267         return false;
3268 }
3269
3270 enum {
3271         PSS,
3272         PPC,
3273 };
3274
3275 /* Hardware vendor-specific info that has its own power management modes */
3276 static struct acpi_platform_list plat_info[] __initdata = {
3277         {"HP    ", "ProLiant", 0, ACPI_SIG_FADT, all_versions, NULL, PSS},
3278         {"ORACLE", "X4-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3279         {"ORACLE", "X4-2L   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3280         {"ORACLE", "X4-2B   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3281         {"ORACLE", "X3-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3282         {"ORACLE", "X3-2L   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3283         {"ORACLE", "X3-2B   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3284         {"ORACLE", "X4470M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3285         {"ORACLE", "X4270M3 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3286         {"ORACLE", "X4270M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3287         {"ORACLE", "X4170M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3288         {"ORACLE", "X4170 M3", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3289         {"ORACLE", "X4275 M3", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3290         {"ORACLE", "X6-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3291         {"ORACLE", "Sudbury ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3292         { } /* End */
3293 };
3294
3295 #define BITMASK_OOB     (BIT(8) | BIT(18))
3296
3297 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
3298 {
3299         const struct x86_cpu_id *id;
3300         u64 misc_pwr;
3301         int idx;
3302
3303         id = x86_match_cpu(intel_pstate_cpu_oob_ids);
3304         if (id) {
3305                 rdmsrl(MSR_MISC_PWR_MGMT, misc_pwr);
3306                 if (misc_pwr & BITMASK_OOB) {
3307                         pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n");
3308                         pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n");
3309                         return true;
3310                 }
3311         }
3312
3313         idx = acpi_match_platform_list(plat_info);
3314         if (idx < 0)
3315                 return false;
3316
3317         switch (plat_info[idx].data) {
3318         case PSS:
3319                 if (!intel_pstate_no_acpi_pss())
3320                         return false;
3321
3322                 return intel_pstate_no_acpi_pcch();
3323         case PPC:
3324                 return intel_pstate_has_acpi_ppc() && !force_load;
3325         }
3326
3327         return false;
3328 }
3329
3330 static void intel_pstate_request_control_from_smm(void)
3331 {
3332         /*
3333          * It may be unsafe to request P-states control from SMM if _PPC support
3334          * has not been enabled.
3335          */
3336         if (acpi_ppc)
3337                 acpi_processor_pstate_control();
3338 }
3339 #else /* CONFIG_ACPI not enabled */
3340 static inline bool intel_pstate_platform_pwr_mgmt_exists(void) { return false; }
3341 static inline bool intel_pstate_has_acpi_ppc(void) { return false; }
3342 static inline void intel_pstate_request_control_from_smm(void) {}
3343 #endif /* CONFIG_ACPI */
3344
3345 #define INTEL_PSTATE_HWP_BROADWELL      0x01
3346
3347 #define X86_MATCH_HWP(model, hwp_mode)                                  \
3348         X86_MATCH_VENDOR_FAM_MODEL_FEATURE(INTEL, 6, INTEL_FAM6_##model, \
3349                                            X86_FEATURE_HWP, hwp_mode)
3350
3351 static const struct x86_cpu_id hwp_support_ids[] __initconst = {
3352         X86_MATCH_HWP(BROADWELL_X,      INTEL_PSTATE_HWP_BROADWELL),
3353         X86_MATCH_HWP(BROADWELL_D,      INTEL_PSTATE_HWP_BROADWELL),
3354         X86_MATCH_HWP(ANY,              0),
3355         {}
3356 };
3357
3358 static bool intel_pstate_hwp_is_enabled(void)
3359 {
3360         u64 value;
3361
3362         rdmsrl(MSR_PM_ENABLE, value);
3363         return !!(value & 0x1);
3364 }
3365
3366 static const struct x86_cpu_id intel_epp_balance_perf[] = {
3367         /*
3368          * Set EPP value as 102, this is the max suggested EPP
3369          * which can result in one core turbo frequency for
3370          * AlderLake Mobile CPUs.
3371          */
3372         X86_MATCH_INTEL_FAM6_MODEL(ALDERLAKE_L, 102),
3373         {}
3374 };
3375
3376 static int __init intel_pstate_init(void)
3377 {
3378         static struct cpudata **_all_cpu_data;
3379         const struct x86_cpu_id *id;
3380         int rc;
3381
3382         if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
3383                 return -ENODEV;
3384
3385         id = x86_match_cpu(hwp_support_ids);
3386         if (id) {
3387                 bool hwp_forced = intel_pstate_hwp_is_enabled();
3388
3389                 if (hwp_forced)
3390                         pr_info("HWP enabled by BIOS\n");
3391                 else if (no_load)
3392                         return -ENODEV;
3393
3394                 copy_cpu_funcs(&core_funcs);
3395                 /*
3396                  * Avoid enabling HWP for processors without EPP support,
3397                  * because that means incomplete HWP implementation which is a
3398                  * corner case and supporting it is generally problematic.
3399                  *
3400                  * If HWP is enabled already, though, there is no choice but to
3401                  * deal with it.
3402                  */
3403                 if ((!no_hwp && boot_cpu_has(X86_FEATURE_HWP_EPP)) || hwp_forced) {
3404                         WRITE_ONCE(hwp_active, 1);
3405                         hwp_mode_bdw = id->driver_data;
3406                         intel_pstate.attr = hwp_cpufreq_attrs;
3407                         intel_cpufreq.attr = hwp_cpufreq_attrs;
3408                         intel_cpufreq.flags |= CPUFREQ_NEED_UPDATE_LIMITS;
3409                         intel_cpufreq.adjust_perf = intel_cpufreq_adjust_perf;
3410                         if (!default_driver)
3411                                 default_driver = &intel_pstate;
3412
3413                         if (boot_cpu_has(X86_FEATURE_HYBRID_CPU))
3414                                 pstate_funcs.get_cpu_scaling = hybrid_get_cpu_scaling;
3415
3416                         goto hwp_cpu_matched;
3417                 }
3418                 pr_info("HWP not enabled\n");
3419         } else {
3420                 if (no_load)
3421                         return -ENODEV;
3422
3423                 id = x86_match_cpu(intel_pstate_cpu_ids);
3424                 if (!id) {
3425                         pr_info("CPU model not supported\n");
3426                         return -ENODEV;
3427                 }
3428
3429                 copy_cpu_funcs((struct pstate_funcs *)id->driver_data);
3430         }
3431
3432         if (intel_pstate_msrs_not_valid()) {
3433                 pr_info("Invalid MSRs\n");
3434                 return -ENODEV;
3435         }
3436         /* Without HWP start in the passive mode. */
3437         if (!default_driver)
3438                 default_driver = &intel_cpufreq;
3439
3440 hwp_cpu_matched:
3441         /*
3442          * The Intel pstate driver will be ignored if the platform
3443          * firmware has its own power management modes.
3444          */
3445         if (intel_pstate_platform_pwr_mgmt_exists()) {
3446                 pr_info("P-states controlled by the platform\n");
3447                 return -ENODEV;
3448         }
3449
3450         if (!hwp_active && hwp_only)
3451                 return -ENOTSUPP;
3452
3453         pr_info("Intel P-state driver initializing\n");
3454
3455         _all_cpu_data = vzalloc(array_size(sizeof(void *), num_possible_cpus()));
3456         if (!_all_cpu_data)
3457                 return -ENOMEM;
3458
3459         WRITE_ONCE(all_cpu_data, _all_cpu_data);
3460
3461         intel_pstate_request_control_from_smm();
3462
3463         intel_pstate_sysfs_expose_params();
3464
3465         if (hwp_active) {
3466                 const struct x86_cpu_id *id = x86_match_cpu(intel_epp_balance_perf);
3467
3468                 if (id)
3469                         epp_values[EPP_INDEX_BALANCE_PERFORMANCE] = id->driver_data;
3470         }
3471
3472         mutex_lock(&intel_pstate_driver_lock);
3473         rc = intel_pstate_register_driver(default_driver);
3474         mutex_unlock(&intel_pstate_driver_lock);
3475         if (rc) {
3476                 intel_pstate_sysfs_remove();
3477                 return rc;
3478         }
3479
3480         if (hwp_active) {
3481                 const struct x86_cpu_id *id;
3482
3483                 id = x86_match_cpu(intel_pstate_cpu_ee_disable_ids);
3484                 if (id) {
3485                         set_power_ctl_ee_state(false);
3486                         pr_info("Disabling energy efficiency optimization\n");
3487                 }
3488
3489                 pr_info("HWP enabled\n");
3490         } else if (boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
3491                 pr_warn("Problematic setup: Hybrid processor with disabled HWP\n");
3492         }
3493
3494         return 0;
3495 }
3496 device_initcall(intel_pstate_init);
3497
3498 static int __init intel_pstate_setup(char *str)
3499 {
3500         if (!str)
3501                 return -EINVAL;
3502
3503         if (!strcmp(str, "disable"))
3504                 no_load = 1;
3505         else if (!strcmp(str, "active"))
3506                 default_driver = &intel_pstate;
3507         else if (!strcmp(str, "passive"))
3508                 default_driver = &intel_cpufreq;
3509
3510         if (!strcmp(str, "no_hwp"))
3511                 no_hwp = 1;
3512
3513         if (!strcmp(str, "force"))
3514                 force_load = 1;
3515         if (!strcmp(str, "hwp_only"))
3516                 hwp_only = 1;
3517         if (!strcmp(str, "per_cpu_perf_limits"))
3518                 per_cpu_limits = true;
3519
3520 #ifdef CONFIG_ACPI
3521         if (!strcmp(str, "support_acpi_ppc"))
3522                 acpi_ppc = true;
3523 #endif
3524
3525         return 0;
3526 }
3527 early_param("intel_pstate", intel_pstate_setup);
3528
3529 MODULE_AUTHOR("Dirk Brandewie <dirk.j.brandewie@intel.com>");
3530 MODULE_DESCRIPTION("'intel_pstate' - P state driver Intel Core processors");
3531 MODULE_LICENSE("GPL");