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