cpufreq: intel_pstate: Clear HWP desired on suspend/shutdown and offline
[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
1004         /*
1005          * Clear the desired perf field in the cached HWP request value to
1006          * prevent nonzero desired values from being leaked into the active
1007          * mode.
1008          */
1009         value &= ~HWP_DESIRED_PERF(~0L);
1010         WRITE_ONCE(cpu->hwp_req_cached, value);
1011
1012         value &= ~GENMASK_ULL(31, 0);
1013         min_perf = HWP_LOWEST_PERF(READ_ONCE(cpu->hwp_cap_cached));
1014
1015         /* Set hwp_max = hwp_min */
1016         value |= HWP_MAX_PERF(min_perf);
1017         value |= HWP_MIN_PERF(min_perf);
1018
1019         /* Set EPP to min */
1020         if (boot_cpu_has(X86_FEATURE_HWP_EPP))
1021                 value |= HWP_ENERGY_PERF_PREFERENCE(HWP_EPP_POWERSAVE);
1022
1023         wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
1024 }
1025
1026 #define POWER_CTL_EE_ENABLE     1
1027 #define POWER_CTL_EE_DISABLE    2
1028
1029 static int power_ctl_ee_state;
1030
1031 static void set_power_ctl_ee_state(bool input)
1032 {
1033         u64 power_ctl;
1034
1035         mutex_lock(&intel_pstate_driver_lock);
1036         rdmsrl(MSR_IA32_POWER_CTL, power_ctl);
1037         if (input) {
1038                 power_ctl &= ~BIT(MSR_IA32_POWER_CTL_BIT_EE);
1039                 power_ctl_ee_state = POWER_CTL_EE_ENABLE;
1040         } else {
1041                 power_ctl |= BIT(MSR_IA32_POWER_CTL_BIT_EE);
1042                 power_ctl_ee_state = POWER_CTL_EE_DISABLE;
1043         }
1044         wrmsrl(MSR_IA32_POWER_CTL, power_ctl);
1045         mutex_unlock(&intel_pstate_driver_lock);
1046 }
1047
1048 static void intel_pstate_hwp_enable(struct cpudata *cpudata);
1049
1050 static void intel_pstate_hwp_reenable(struct cpudata *cpu)
1051 {
1052         intel_pstate_hwp_enable(cpu);
1053         wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, READ_ONCE(cpu->hwp_req_cached));
1054 }
1055
1056 static int intel_pstate_suspend(struct cpufreq_policy *policy)
1057 {
1058         struct cpudata *cpu = all_cpu_data[policy->cpu];
1059
1060         pr_debug("CPU %d suspending\n", cpu->cpu);
1061
1062         cpu->suspended = true;
1063
1064         return 0;
1065 }
1066
1067 static int intel_pstate_resume(struct cpufreq_policy *policy)
1068 {
1069         struct cpudata *cpu = all_cpu_data[policy->cpu];
1070
1071         pr_debug("CPU %d resuming\n", cpu->cpu);
1072
1073         /* Only restore if the system default is changed */
1074         if (power_ctl_ee_state == POWER_CTL_EE_ENABLE)
1075                 set_power_ctl_ee_state(true);
1076         else if (power_ctl_ee_state == POWER_CTL_EE_DISABLE)
1077                 set_power_ctl_ee_state(false);
1078
1079         if (cpu->suspended && hwp_active) {
1080                 mutex_lock(&intel_pstate_limits_lock);
1081
1082                 /* Re-enable HWP, because "online" has not done that. */
1083                 intel_pstate_hwp_reenable(cpu);
1084
1085                 mutex_unlock(&intel_pstate_limits_lock);
1086         }
1087
1088         cpu->suspended = false;
1089
1090         return 0;
1091 }
1092
1093 static void intel_pstate_update_policies(void)
1094 {
1095         int cpu;
1096
1097         for_each_possible_cpu(cpu)
1098                 cpufreq_update_policy(cpu);
1099 }
1100
1101 static void intel_pstate_update_max_freq(unsigned int cpu)
1102 {
1103         struct cpufreq_policy *policy = cpufreq_cpu_acquire(cpu);
1104         struct cpudata *cpudata;
1105
1106         if (!policy)
1107                 return;
1108
1109         cpudata = all_cpu_data[cpu];
1110         policy->cpuinfo.max_freq = global.turbo_disabled_mf ?
1111                         cpudata->pstate.max_freq : cpudata->pstate.turbo_freq;
1112
1113         refresh_frequency_limits(policy);
1114
1115         cpufreq_cpu_release(policy);
1116 }
1117
1118 static void intel_pstate_update_limits(unsigned int cpu)
1119 {
1120         mutex_lock(&intel_pstate_driver_lock);
1121
1122         update_turbo_state();
1123         /*
1124          * If turbo has been turned on or off globally, policy limits for
1125          * all CPUs need to be updated to reflect that.
1126          */
1127         if (global.turbo_disabled_mf != global.turbo_disabled) {
1128                 global.turbo_disabled_mf = global.turbo_disabled;
1129                 arch_set_max_freq_ratio(global.turbo_disabled);
1130                 for_each_possible_cpu(cpu)
1131                         intel_pstate_update_max_freq(cpu);
1132         } else {
1133                 cpufreq_update_policy(cpu);
1134         }
1135
1136         mutex_unlock(&intel_pstate_driver_lock);
1137 }
1138
1139 /************************** sysfs begin ************************/
1140 #define show_one(file_name, object)                                     \
1141         static ssize_t show_##file_name                                 \
1142         (struct kobject *kobj, struct kobj_attribute *attr, char *buf)  \
1143         {                                                               \
1144                 return sprintf(buf, "%u\n", global.object);             \
1145         }
1146
1147 static ssize_t intel_pstate_show_status(char *buf);
1148 static int intel_pstate_update_status(const char *buf, size_t size);
1149
1150 static ssize_t show_status(struct kobject *kobj,
1151                            struct kobj_attribute *attr, char *buf)
1152 {
1153         ssize_t ret;
1154
1155         mutex_lock(&intel_pstate_driver_lock);
1156         ret = intel_pstate_show_status(buf);
1157         mutex_unlock(&intel_pstate_driver_lock);
1158
1159         return ret;
1160 }
1161
1162 static ssize_t store_status(struct kobject *a, struct kobj_attribute *b,
1163                             const char *buf, size_t count)
1164 {
1165         char *p = memchr(buf, '\n', count);
1166         int ret;
1167
1168         mutex_lock(&intel_pstate_driver_lock);
1169         ret = intel_pstate_update_status(buf, p ? p - buf : count);
1170         mutex_unlock(&intel_pstate_driver_lock);
1171
1172         return ret < 0 ? ret : count;
1173 }
1174
1175 static ssize_t show_turbo_pct(struct kobject *kobj,
1176                                 struct kobj_attribute *attr, char *buf)
1177 {
1178         struct cpudata *cpu;
1179         int total, no_turbo, turbo_pct;
1180         uint32_t turbo_fp;
1181
1182         mutex_lock(&intel_pstate_driver_lock);
1183
1184         if (!intel_pstate_driver) {
1185                 mutex_unlock(&intel_pstate_driver_lock);
1186                 return -EAGAIN;
1187         }
1188
1189         cpu = all_cpu_data[0];
1190
1191         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1192         no_turbo = cpu->pstate.max_pstate - cpu->pstate.min_pstate + 1;
1193         turbo_fp = div_fp(no_turbo, total);
1194         turbo_pct = 100 - fp_toint(mul_fp(turbo_fp, int_tofp(100)));
1195
1196         mutex_unlock(&intel_pstate_driver_lock);
1197
1198         return sprintf(buf, "%u\n", turbo_pct);
1199 }
1200
1201 static ssize_t show_num_pstates(struct kobject *kobj,
1202                                 struct kobj_attribute *attr, char *buf)
1203 {
1204         struct cpudata *cpu;
1205         int total;
1206
1207         mutex_lock(&intel_pstate_driver_lock);
1208
1209         if (!intel_pstate_driver) {
1210                 mutex_unlock(&intel_pstate_driver_lock);
1211                 return -EAGAIN;
1212         }
1213
1214         cpu = all_cpu_data[0];
1215         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1216
1217         mutex_unlock(&intel_pstate_driver_lock);
1218
1219         return sprintf(buf, "%u\n", total);
1220 }
1221
1222 static ssize_t show_no_turbo(struct kobject *kobj,
1223                              struct kobj_attribute *attr, char *buf)
1224 {
1225         ssize_t ret;
1226
1227         mutex_lock(&intel_pstate_driver_lock);
1228
1229         if (!intel_pstate_driver) {
1230                 mutex_unlock(&intel_pstate_driver_lock);
1231                 return -EAGAIN;
1232         }
1233
1234         update_turbo_state();
1235         if (global.turbo_disabled)
1236                 ret = sprintf(buf, "%u\n", global.turbo_disabled);
1237         else
1238                 ret = sprintf(buf, "%u\n", global.no_turbo);
1239
1240         mutex_unlock(&intel_pstate_driver_lock);
1241
1242         return ret;
1243 }
1244
1245 static ssize_t store_no_turbo(struct kobject *a, struct kobj_attribute *b,
1246                               const char *buf, size_t count)
1247 {
1248         unsigned int input;
1249         int ret;
1250
1251         ret = sscanf(buf, "%u", &input);
1252         if (ret != 1)
1253                 return -EINVAL;
1254
1255         mutex_lock(&intel_pstate_driver_lock);
1256
1257         if (!intel_pstate_driver) {
1258                 mutex_unlock(&intel_pstate_driver_lock);
1259                 return -EAGAIN;
1260         }
1261
1262         mutex_lock(&intel_pstate_limits_lock);
1263
1264         update_turbo_state();
1265         if (global.turbo_disabled) {
1266                 pr_notice_once("Turbo disabled by BIOS or unavailable on processor\n");
1267                 mutex_unlock(&intel_pstate_limits_lock);
1268                 mutex_unlock(&intel_pstate_driver_lock);
1269                 return -EPERM;
1270         }
1271
1272         global.no_turbo = clamp_t(int, input, 0, 1);
1273
1274         if (global.no_turbo) {
1275                 struct cpudata *cpu = all_cpu_data[0];
1276                 int pct = cpu->pstate.max_pstate * 100 / cpu->pstate.turbo_pstate;
1277
1278                 /* Squash the global minimum into the permitted range. */
1279                 if (global.min_perf_pct > pct)
1280                         global.min_perf_pct = pct;
1281         }
1282
1283         mutex_unlock(&intel_pstate_limits_lock);
1284
1285         intel_pstate_update_policies();
1286
1287         mutex_unlock(&intel_pstate_driver_lock);
1288
1289         return count;
1290 }
1291
1292 static void update_qos_request(enum freq_qos_req_type type)
1293 {
1294         struct freq_qos_request *req;
1295         struct cpufreq_policy *policy;
1296         int i;
1297
1298         for_each_possible_cpu(i) {
1299                 struct cpudata *cpu = all_cpu_data[i];
1300                 unsigned int freq, perf_pct;
1301
1302                 policy = cpufreq_cpu_get(i);
1303                 if (!policy)
1304                         continue;
1305
1306                 req = policy->driver_data;
1307                 cpufreq_cpu_put(policy);
1308
1309                 if (!req)
1310                         continue;
1311
1312                 if (hwp_active)
1313                         intel_pstate_get_hwp_cap(cpu);
1314
1315                 if (type == FREQ_QOS_MIN) {
1316                         perf_pct = global.min_perf_pct;
1317                 } else {
1318                         req++;
1319                         perf_pct = global.max_perf_pct;
1320                 }
1321
1322                 freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * perf_pct, 100);
1323
1324                 if (freq_qos_update_request(req, freq) < 0)
1325                         pr_warn("Failed to update freq constraint: CPU%d\n", i);
1326         }
1327 }
1328
1329 static ssize_t store_max_perf_pct(struct kobject *a, struct kobj_attribute *b,
1330                                   const char *buf, size_t count)
1331 {
1332         unsigned int input;
1333         int ret;
1334
1335         ret = sscanf(buf, "%u", &input);
1336         if (ret != 1)
1337                 return -EINVAL;
1338
1339         mutex_lock(&intel_pstate_driver_lock);
1340
1341         if (!intel_pstate_driver) {
1342                 mutex_unlock(&intel_pstate_driver_lock);
1343                 return -EAGAIN;
1344         }
1345
1346         mutex_lock(&intel_pstate_limits_lock);
1347
1348         global.max_perf_pct = clamp_t(int, input, global.min_perf_pct, 100);
1349
1350         mutex_unlock(&intel_pstate_limits_lock);
1351
1352         if (intel_pstate_driver == &intel_pstate)
1353                 intel_pstate_update_policies();
1354         else
1355                 update_qos_request(FREQ_QOS_MAX);
1356
1357         mutex_unlock(&intel_pstate_driver_lock);
1358
1359         return count;
1360 }
1361
1362 static ssize_t store_min_perf_pct(struct kobject *a, struct kobj_attribute *b,
1363                                   const char *buf, size_t count)
1364 {
1365         unsigned int input;
1366         int ret;
1367
1368         ret = sscanf(buf, "%u", &input);
1369         if (ret != 1)
1370                 return -EINVAL;
1371
1372         mutex_lock(&intel_pstate_driver_lock);
1373
1374         if (!intel_pstate_driver) {
1375                 mutex_unlock(&intel_pstate_driver_lock);
1376                 return -EAGAIN;
1377         }
1378
1379         mutex_lock(&intel_pstate_limits_lock);
1380
1381         global.min_perf_pct = clamp_t(int, input,
1382                                       min_perf_pct_min(), global.max_perf_pct);
1383
1384         mutex_unlock(&intel_pstate_limits_lock);
1385
1386         if (intel_pstate_driver == &intel_pstate)
1387                 intel_pstate_update_policies();
1388         else
1389                 update_qos_request(FREQ_QOS_MIN);
1390
1391         mutex_unlock(&intel_pstate_driver_lock);
1392
1393         return count;
1394 }
1395
1396 static ssize_t show_hwp_dynamic_boost(struct kobject *kobj,
1397                                 struct kobj_attribute *attr, char *buf)
1398 {
1399         return sprintf(buf, "%u\n", hwp_boost);
1400 }
1401
1402 static ssize_t store_hwp_dynamic_boost(struct kobject *a,
1403                                        struct kobj_attribute *b,
1404                                        const char *buf, size_t count)
1405 {
1406         unsigned int input;
1407         int ret;
1408
1409         ret = kstrtouint(buf, 10, &input);
1410         if (ret)
1411                 return ret;
1412
1413         mutex_lock(&intel_pstate_driver_lock);
1414         hwp_boost = !!input;
1415         intel_pstate_update_policies();
1416         mutex_unlock(&intel_pstate_driver_lock);
1417
1418         return count;
1419 }
1420
1421 static ssize_t show_energy_efficiency(struct kobject *kobj, struct kobj_attribute *attr,
1422                                       char *buf)
1423 {
1424         u64 power_ctl;
1425         int enable;
1426
1427         rdmsrl(MSR_IA32_POWER_CTL, power_ctl);
1428         enable = !!(power_ctl & BIT(MSR_IA32_POWER_CTL_BIT_EE));
1429         return sprintf(buf, "%d\n", !enable);
1430 }
1431
1432 static ssize_t store_energy_efficiency(struct kobject *a, struct kobj_attribute *b,
1433                                        const char *buf, size_t count)
1434 {
1435         bool input;
1436         int ret;
1437
1438         ret = kstrtobool(buf, &input);
1439         if (ret)
1440                 return ret;
1441
1442         set_power_ctl_ee_state(input);
1443
1444         return count;
1445 }
1446
1447 show_one(max_perf_pct, max_perf_pct);
1448 show_one(min_perf_pct, min_perf_pct);
1449
1450 define_one_global_rw(status);
1451 define_one_global_rw(no_turbo);
1452 define_one_global_rw(max_perf_pct);
1453 define_one_global_rw(min_perf_pct);
1454 define_one_global_ro(turbo_pct);
1455 define_one_global_ro(num_pstates);
1456 define_one_global_rw(hwp_dynamic_boost);
1457 define_one_global_rw(energy_efficiency);
1458
1459 static struct attribute *intel_pstate_attributes[] = {
1460         &status.attr,
1461         &no_turbo.attr,
1462         NULL
1463 };
1464
1465 static const struct attribute_group intel_pstate_attr_group = {
1466         .attrs = intel_pstate_attributes,
1467 };
1468
1469 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[];
1470
1471 static struct kobject *intel_pstate_kobject;
1472
1473 static void __init intel_pstate_sysfs_expose_params(void)
1474 {
1475         int rc;
1476
1477         intel_pstate_kobject = kobject_create_and_add("intel_pstate",
1478                                                 &cpu_subsys.dev_root->kobj);
1479         if (WARN_ON(!intel_pstate_kobject))
1480                 return;
1481
1482         rc = sysfs_create_group(intel_pstate_kobject, &intel_pstate_attr_group);
1483         if (WARN_ON(rc))
1484                 return;
1485
1486         if (!boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
1487                 rc = sysfs_create_file(intel_pstate_kobject, &turbo_pct.attr);
1488                 WARN_ON(rc);
1489
1490                 rc = sysfs_create_file(intel_pstate_kobject, &num_pstates.attr);
1491                 WARN_ON(rc);
1492         }
1493
1494         /*
1495          * If per cpu limits are enforced there are no global limits, so
1496          * return without creating max/min_perf_pct attributes
1497          */
1498         if (per_cpu_limits)
1499                 return;
1500
1501         rc = sysfs_create_file(intel_pstate_kobject, &max_perf_pct.attr);
1502         WARN_ON(rc);
1503
1504         rc = sysfs_create_file(intel_pstate_kobject, &min_perf_pct.attr);
1505         WARN_ON(rc);
1506
1507         if (x86_match_cpu(intel_pstate_cpu_ee_disable_ids)) {
1508                 rc = sysfs_create_file(intel_pstate_kobject, &energy_efficiency.attr);
1509                 WARN_ON(rc);
1510         }
1511 }
1512
1513 static void __init intel_pstate_sysfs_remove(void)
1514 {
1515         if (!intel_pstate_kobject)
1516                 return;
1517
1518         sysfs_remove_group(intel_pstate_kobject, &intel_pstate_attr_group);
1519
1520         if (!boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
1521                 sysfs_remove_file(intel_pstate_kobject, &num_pstates.attr);
1522                 sysfs_remove_file(intel_pstate_kobject, &turbo_pct.attr);
1523         }
1524
1525         if (!per_cpu_limits) {
1526                 sysfs_remove_file(intel_pstate_kobject, &max_perf_pct.attr);
1527                 sysfs_remove_file(intel_pstate_kobject, &min_perf_pct.attr);
1528
1529                 if (x86_match_cpu(intel_pstate_cpu_ee_disable_ids))
1530                         sysfs_remove_file(intel_pstate_kobject, &energy_efficiency.attr);
1531         }
1532
1533         kobject_put(intel_pstate_kobject);
1534 }
1535
1536 static void intel_pstate_sysfs_expose_hwp_dynamic_boost(void)
1537 {
1538         int rc;
1539
1540         if (!hwp_active)
1541                 return;
1542
1543         rc = sysfs_create_file(intel_pstate_kobject, &hwp_dynamic_boost.attr);
1544         WARN_ON_ONCE(rc);
1545 }
1546
1547 static void intel_pstate_sysfs_hide_hwp_dynamic_boost(void)
1548 {
1549         if (!hwp_active)
1550                 return;
1551
1552         sysfs_remove_file(intel_pstate_kobject, &hwp_dynamic_boost.attr);
1553 }
1554
1555 /************************** sysfs end ************************/
1556
1557 static void intel_pstate_hwp_enable(struct cpudata *cpudata)
1558 {
1559         /* First disable HWP notification interrupt as we don't process them */
1560         if (boot_cpu_has(X86_FEATURE_HWP_NOTIFY))
1561                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x00);
1562
1563         wrmsrl_on_cpu(cpudata->cpu, MSR_PM_ENABLE, 0x1);
1564         if (cpudata->epp_default == -EINVAL)
1565                 cpudata->epp_default = intel_pstate_get_epp(cpudata, 0);
1566 }
1567
1568 static int atom_get_min_pstate(void)
1569 {
1570         u64 value;
1571
1572         rdmsrl(MSR_ATOM_CORE_RATIOS, value);
1573         return (value >> 8) & 0x7F;
1574 }
1575
1576 static int atom_get_max_pstate(void)
1577 {
1578         u64 value;
1579
1580         rdmsrl(MSR_ATOM_CORE_RATIOS, value);
1581         return (value >> 16) & 0x7F;
1582 }
1583
1584 static int atom_get_turbo_pstate(void)
1585 {
1586         u64 value;
1587
1588         rdmsrl(MSR_ATOM_CORE_TURBO_RATIOS, value);
1589         return value & 0x7F;
1590 }
1591
1592 static u64 atom_get_val(struct cpudata *cpudata, int pstate)
1593 {
1594         u64 val;
1595         int32_t vid_fp;
1596         u32 vid;
1597
1598         val = (u64)pstate << 8;
1599         if (global.no_turbo && !global.turbo_disabled)
1600                 val |= (u64)1 << 32;
1601
1602         vid_fp = cpudata->vid.min + mul_fp(
1603                 int_tofp(pstate - cpudata->pstate.min_pstate),
1604                 cpudata->vid.ratio);
1605
1606         vid_fp = clamp_t(int32_t, vid_fp, cpudata->vid.min, cpudata->vid.max);
1607         vid = ceiling_fp(vid_fp);
1608
1609         if (pstate > cpudata->pstate.max_pstate)
1610                 vid = cpudata->vid.turbo;
1611
1612         return val | vid;
1613 }
1614
1615 static int silvermont_get_scaling(void)
1616 {
1617         u64 value;
1618         int i;
1619         /* Defined in Table 35-6 from SDM (Sept 2015) */
1620         static int silvermont_freq_table[] = {
1621                 83300, 100000, 133300, 116700, 80000};
1622
1623         rdmsrl(MSR_FSB_FREQ, value);
1624         i = value & 0x7;
1625         WARN_ON(i > 4);
1626
1627         return silvermont_freq_table[i];
1628 }
1629
1630 static int airmont_get_scaling(void)
1631 {
1632         u64 value;
1633         int i;
1634         /* Defined in Table 35-10 from SDM (Sept 2015) */
1635         static int airmont_freq_table[] = {
1636                 83300, 100000, 133300, 116700, 80000,
1637                 93300, 90000, 88900, 87500};
1638
1639         rdmsrl(MSR_FSB_FREQ, value);
1640         i = value & 0xF;
1641         WARN_ON(i > 8);
1642
1643         return airmont_freq_table[i];
1644 }
1645
1646 static void atom_get_vid(struct cpudata *cpudata)
1647 {
1648         u64 value;
1649
1650         rdmsrl(MSR_ATOM_CORE_VIDS, value);
1651         cpudata->vid.min = int_tofp((value >> 8) & 0x7f);
1652         cpudata->vid.max = int_tofp((value >> 16) & 0x7f);
1653         cpudata->vid.ratio = div_fp(
1654                 cpudata->vid.max - cpudata->vid.min,
1655                 int_tofp(cpudata->pstate.max_pstate -
1656                         cpudata->pstate.min_pstate));
1657
1658         rdmsrl(MSR_ATOM_CORE_TURBO_VIDS, value);
1659         cpudata->vid.turbo = value & 0x7f;
1660 }
1661
1662 static int core_get_min_pstate(void)
1663 {
1664         u64 value;
1665
1666         rdmsrl(MSR_PLATFORM_INFO, value);
1667         return (value >> 40) & 0xFF;
1668 }
1669
1670 static int core_get_max_pstate_physical(void)
1671 {
1672         u64 value;
1673
1674         rdmsrl(MSR_PLATFORM_INFO, value);
1675         return (value >> 8) & 0xFF;
1676 }
1677
1678 static int core_get_tdp_ratio(u64 plat_info)
1679 {
1680         /* Check how many TDP levels present */
1681         if (plat_info & 0x600000000) {
1682                 u64 tdp_ctrl;
1683                 u64 tdp_ratio;
1684                 int tdp_msr;
1685                 int err;
1686
1687                 /* Get the TDP level (0, 1, 2) to get ratios */
1688                 err = rdmsrl_safe(MSR_CONFIG_TDP_CONTROL, &tdp_ctrl);
1689                 if (err)
1690                         return err;
1691
1692                 /* TDP MSR are continuous starting at 0x648 */
1693                 tdp_msr = MSR_CONFIG_TDP_NOMINAL + (tdp_ctrl & 0x03);
1694                 err = rdmsrl_safe(tdp_msr, &tdp_ratio);
1695                 if (err)
1696                         return err;
1697
1698                 /* For level 1 and 2, bits[23:16] contain the ratio */
1699                 if (tdp_ctrl & 0x03)
1700                         tdp_ratio >>= 16;
1701
1702                 tdp_ratio &= 0xff; /* ratios are only 8 bits long */
1703                 pr_debug("tdp_ratio %x\n", (int)tdp_ratio);
1704
1705                 return (int)tdp_ratio;
1706         }
1707
1708         return -ENXIO;
1709 }
1710
1711 static int core_get_max_pstate(void)
1712 {
1713         u64 tar;
1714         u64 plat_info;
1715         int max_pstate;
1716         int tdp_ratio;
1717         int err;
1718
1719         rdmsrl(MSR_PLATFORM_INFO, plat_info);
1720         max_pstate = (plat_info >> 8) & 0xFF;
1721
1722         tdp_ratio = core_get_tdp_ratio(plat_info);
1723         if (tdp_ratio <= 0)
1724                 return max_pstate;
1725
1726         if (hwp_active) {
1727                 /* Turbo activation ratio is not used on HWP platforms */
1728                 return tdp_ratio;
1729         }
1730
1731         err = rdmsrl_safe(MSR_TURBO_ACTIVATION_RATIO, &tar);
1732         if (!err) {
1733                 int tar_levels;
1734
1735                 /* Do some sanity checking for safety */
1736                 tar_levels = tar & 0xff;
1737                 if (tdp_ratio - 1 == tar_levels) {
1738                         max_pstate = tar_levels;
1739                         pr_debug("max_pstate=TAC %x\n", max_pstate);
1740                 }
1741         }
1742
1743         return max_pstate;
1744 }
1745
1746 static int core_get_turbo_pstate(void)
1747 {
1748         u64 value;
1749         int nont, ret;
1750
1751         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1752         nont = core_get_max_pstate();
1753         ret = (value) & 255;
1754         if (ret <= nont)
1755                 ret = nont;
1756         return ret;
1757 }
1758
1759 static inline int core_get_scaling(void)
1760 {
1761         return 100000;
1762 }
1763
1764 static u64 core_get_val(struct cpudata *cpudata, int pstate)
1765 {
1766         u64 val;
1767
1768         val = (u64)pstate << 8;
1769         if (global.no_turbo && !global.turbo_disabled)
1770                 val |= (u64)1 << 32;
1771
1772         return val;
1773 }
1774
1775 static int knl_get_aperf_mperf_shift(void)
1776 {
1777         return 10;
1778 }
1779
1780 static int knl_get_turbo_pstate(void)
1781 {
1782         u64 value;
1783         int nont, ret;
1784
1785         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1786         nont = core_get_max_pstate();
1787         ret = (((value) >> 8) & 0xFF);
1788         if (ret <= nont)
1789                 ret = nont;
1790         return ret;
1791 }
1792
1793 #ifdef CONFIG_ACPI_CPPC_LIB
1794 static u32 hybrid_ref_perf;
1795
1796 static int hybrid_get_cpu_scaling(int cpu)
1797 {
1798         return DIV_ROUND_UP(core_get_scaling() * hybrid_ref_perf,
1799                             intel_pstate_cppc_nominal(cpu));
1800 }
1801
1802 static void intel_pstate_cppc_set_cpu_scaling(void)
1803 {
1804         u32 min_nominal_perf = U32_MAX;
1805         int cpu;
1806
1807         for_each_present_cpu(cpu) {
1808                 u32 nominal_perf = intel_pstate_cppc_nominal(cpu);
1809
1810                 if (nominal_perf && nominal_perf < min_nominal_perf)
1811                         min_nominal_perf = nominal_perf;
1812         }
1813
1814         if (min_nominal_perf < U32_MAX) {
1815                 hybrid_ref_perf = min_nominal_perf;
1816                 pstate_funcs.get_cpu_scaling = hybrid_get_cpu_scaling;
1817         }
1818 }
1819 #else
1820 static inline void intel_pstate_cppc_set_cpu_scaling(void)
1821 {
1822 }
1823 #endif /* CONFIG_ACPI_CPPC_LIB */
1824
1825 static void intel_pstate_set_pstate(struct cpudata *cpu, int pstate)
1826 {
1827         trace_cpu_frequency(pstate * cpu->pstate.scaling, cpu->cpu);
1828         cpu->pstate.current_pstate = pstate;
1829         /*
1830          * Generally, there is no guarantee that this code will always run on
1831          * the CPU being updated, so force the register update to run on the
1832          * right CPU.
1833          */
1834         wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
1835                       pstate_funcs.get_val(cpu, pstate));
1836 }
1837
1838 static void intel_pstate_set_min_pstate(struct cpudata *cpu)
1839 {
1840         intel_pstate_set_pstate(cpu, cpu->pstate.min_pstate);
1841 }
1842
1843 static void intel_pstate_max_within_limits(struct cpudata *cpu)
1844 {
1845         int pstate = max(cpu->pstate.min_pstate, cpu->max_perf_ratio);
1846
1847         update_turbo_state();
1848         intel_pstate_set_pstate(cpu, pstate);
1849 }
1850
1851 static void intel_pstate_get_cpu_pstates(struct cpudata *cpu)
1852 {
1853         int perf_ctl_max_phys = pstate_funcs.get_max_physical();
1854         int perf_ctl_scaling = pstate_funcs.get_scaling();
1855
1856         cpu->pstate.min_pstate = pstate_funcs.get_min();
1857         cpu->pstate.max_pstate_physical = perf_ctl_max_phys;
1858         cpu->pstate.perf_ctl_scaling = perf_ctl_scaling;
1859
1860         if (hwp_active && !hwp_mode_bdw) {
1861                 __intel_pstate_get_hwp_cap(cpu);
1862
1863                 if (pstate_funcs.get_cpu_scaling) {
1864                         cpu->pstate.scaling = pstate_funcs.get_cpu_scaling(cpu->cpu);
1865                         if (cpu->pstate.scaling != perf_ctl_scaling)
1866                                 intel_pstate_hybrid_hwp_adjust(cpu);
1867                 } else {
1868                         cpu->pstate.scaling = perf_ctl_scaling;
1869                 }
1870         } else {
1871                 cpu->pstate.scaling = perf_ctl_scaling;
1872                 cpu->pstate.max_pstate = pstate_funcs.get_max();
1873                 cpu->pstate.turbo_pstate = pstate_funcs.get_turbo();
1874         }
1875
1876         if (cpu->pstate.scaling == perf_ctl_scaling) {
1877                 cpu->pstate.min_freq = cpu->pstate.min_pstate * perf_ctl_scaling;
1878                 cpu->pstate.max_freq = cpu->pstate.max_pstate * perf_ctl_scaling;
1879                 cpu->pstate.turbo_freq = cpu->pstate.turbo_pstate * perf_ctl_scaling;
1880         }
1881
1882         if (pstate_funcs.get_aperf_mperf_shift)
1883                 cpu->aperf_mperf_shift = pstate_funcs.get_aperf_mperf_shift();
1884
1885         if (pstate_funcs.get_vid)
1886                 pstate_funcs.get_vid(cpu);
1887
1888         intel_pstate_set_min_pstate(cpu);
1889 }
1890
1891 /*
1892  * Long hold time will keep high perf limits for long time,
1893  * which negatively impacts perf/watt for some workloads,
1894  * like specpower. 3ms is based on experiements on some
1895  * workoads.
1896  */
1897 static int hwp_boost_hold_time_ns = 3 * NSEC_PER_MSEC;
1898
1899 static inline void intel_pstate_hwp_boost_up(struct cpudata *cpu)
1900 {
1901         u64 hwp_req = READ_ONCE(cpu->hwp_req_cached);
1902         u64 hwp_cap = READ_ONCE(cpu->hwp_cap_cached);
1903         u32 max_limit = (hwp_req & 0xff00) >> 8;
1904         u32 min_limit = (hwp_req & 0xff);
1905         u32 boost_level1;
1906
1907         /*
1908          * Cases to consider (User changes via sysfs or boot time):
1909          * If, P0 (Turbo max) = P1 (Guaranteed max) = min:
1910          *      No boost, return.
1911          * If, P0 (Turbo max) > P1 (Guaranteed max) = min:
1912          *     Should result in one level boost only for P0.
1913          * If, P0 (Turbo max) = P1 (Guaranteed max) > min:
1914          *     Should result in two level boost:
1915          *         (min + p1)/2 and P1.
1916          * If, P0 (Turbo max) > P1 (Guaranteed max) > min:
1917          *     Should result in three level boost:
1918          *        (min + p1)/2, P1 and P0.
1919          */
1920
1921         /* If max and min are equal or already at max, nothing to boost */
1922         if (max_limit == min_limit || cpu->hwp_boost_min >= max_limit)
1923                 return;
1924
1925         if (!cpu->hwp_boost_min)
1926                 cpu->hwp_boost_min = min_limit;
1927
1928         /* level at half way mark between min and guranteed */
1929         boost_level1 = (HWP_GUARANTEED_PERF(hwp_cap) + min_limit) >> 1;
1930
1931         if (cpu->hwp_boost_min < boost_level1)
1932                 cpu->hwp_boost_min = boost_level1;
1933         else if (cpu->hwp_boost_min < HWP_GUARANTEED_PERF(hwp_cap))
1934                 cpu->hwp_boost_min = HWP_GUARANTEED_PERF(hwp_cap);
1935         else if (cpu->hwp_boost_min == HWP_GUARANTEED_PERF(hwp_cap) &&
1936                  max_limit != HWP_GUARANTEED_PERF(hwp_cap))
1937                 cpu->hwp_boost_min = max_limit;
1938         else
1939                 return;
1940
1941         hwp_req = (hwp_req & ~GENMASK_ULL(7, 0)) | cpu->hwp_boost_min;
1942         wrmsrl(MSR_HWP_REQUEST, hwp_req);
1943         cpu->last_update = cpu->sample.time;
1944 }
1945
1946 static inline void intel_pstate_hwp_boost_down(struct cpudata *cpu)
1947 {
1948         if (cpu->hwp_boost_min) {
1949                 bool expired;
1950
1951                 /* Check if we are idle for hold time to boost down */
1952                 expired = time_after64(cpu->sample.time, cpu->last_update +
1953                                        hwp_boost_hold_time_ns);
1954                 if (expired) {
1955                         wrmsrl(MSR_HWP_REQUEST, cpu->hwp_req_cached);
1956                         cpu->hwp_boost_min = 0;
1957                 }
1958         }
1959         cpu->last_update = cpu->sample.time;
1960 }
1961
1962 static inline void intel_pstate_update_util_hwp_local(struct cpudata *cpu,
1963                                                       u64 time)
1964 {
1965         cpu->sample.time = time;
1966
1967         if (cpu->sched_flags & SCHED_CPUFREQ_IOWAIT) {
1968                 bool do_io = false;
1969
1970                 cpu->sched_flags = 0;
1971                 /*
1972                  * Set iowait_boost flag and update time. Since IO WAIT flag
1973                  * is set all the time, we can't just conclude that there is
1974                  * some IO bound activity is scheduled on this CPU with just
1975                  * one occurrence. If we receive at least two in two
1976                  * consecutive ticks, then we treat as boost candidate.
1977                  */
1978                 if (time_before64(time, cpu->last_io_update + 2 * TICK_NSEC))
1979                         do_io = true;
1980
1981                 cpu->last_io_update = time;
1982
1983                 if (do_io)
1984                         intel_pstate_hwp_boost_up(cpu);
1985
1986         } else {
1987                 intel_pstate_hwp_boost_down(cpu);
1988         }
1989 }
1990
1991 static inline void intel_pstate_update_util_hwp(struct update_util_data *data,
1992                                                 u64 time, unsigned int flags)
1993 {
1994         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
1995
1996         cpu->sched_flags |= flags;
1997
1998         if (smp_processor_id() == cpu->cpu)
1999                 intel_pstate_update_util_hwp_local(cpu, time);
2000 }
2001
2002 static inline void intel_pstate_calc_avg_perf(struct cpudata *cpu)
2003 {
2004         struct sample *sample = &cpu->sample;
2005
2006         sample->core_avg_perf = div_ext_fp(sample->aperf, sample->mperf);
2007 }
2008
2009 static inline bool intel_pstate_sample(struct cpudata *cpu, u64 time)
2010 {
2011         u64 aperf, mperf;
2012         unsigned long flags;
2013         u64 tsc;
2014
2015         local_irq_save(flags);
2016         rdmsrl(MSR_IA32_APERF, aperf);
2017         rdmsrl(MSR_IA32_MPERF, mperf);
2018         tsc = rdtsc();
2019         if (cpu->prev_mperf == mperf || cpu->prev_tsc == tsc) {
2020                 local_irq_restore(flags);
2021                 return false;
2022         }
2023         local_irq_restore(flags);
2024
2025         cpu->last_sample_time = cpu->sample.time;
2026         cpu->sample.time = time;
2027         cpu->sample.aperf = aperf;
2028         cpu->sample.mperf = mperf;
2029         cpu->sample.tsc =  tsc;
2030         cpu->sample.aperf -= cpu->prev_aperf;
2031         cpu->sample.mperf -= cpu->prev_mperf;
2032         cpu->sample.tsc -= cpu->prev_tsc;
2033
2034         cpu->prev_aperf = aperf;
2035         cpu->prev_mperf = mperf;
2036         cpu->prev_tsc = tsc;
2037         /*
2038          * First time this function is invoked in a given cycle, all of the
2039          * previous sample data fields are equal to zero or stale and they must
2040          * be populated with meaningful numbers for things to work, so assume
2041          * that sample.time will always be reset before setting the utilization
2042          * update hook and make the caller skip the sample then.
2043          */
2044         if (cpu->last_sample_time) {
2045                 intel_pstate_calc_avg_perf(cpu);
2046                 return true;
2047         }
2048         return false;
2049 }
2050
2051 static inline int32_t get_avg_frequency(struct cpudata *cpu)
2052 {
2053         return mul_ext_fp(cpu->sample.core_avg_perf, cpu_khz);
2054 }
2055
2056 static inline int32_t get_avg_pstate(struct cpudata *cpu)
2057 {
2058         return mul_ext_fp(cpu->pstate.max_pstate_physical,
2059                           cpu->sample.core_avg_perf);
2060 }
2061
2062 static inline int32_t get_target_pstate(struct cpudata *cpu)
2063 {
2064         struct sample *sample = &cpu->sample;
2065         int32_t busy_frac;
2066         int target, avg_pstate;
2067
2068         busy_frac = div_fp(sample->mperf << cpu->aperf_mperf_shift,
2069                            sample->tsc);
2070
2071         if (busy_frac < cpu->iowait_boost)
2072                 busy_frac = cpu->iowait_boost;
2073
2074         sample->busy_scaled = busy_frac * 100;
2075
2076         target = global.no_turbo || global.turbo_disabled ?
2077                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
2078         target += target >> 2;
2079         target = mul_fp(target, busy_frac);
2080         if (target < cpu->pstate.min_pstate)
2081                 target = cpu->pstate.min_pstate;
2082
2083         /*
2084          * If the average P-state during the previous cycle was higher than the
2085          * current target, add 50% of the difference to the target to reduce
2086          * possible performance oscillations and offset possible performance
2087          * loss related to moving the workload from one CPU to another within
2088          * a package/module.
2089          */
2090         avg_pstate = get_avg_pstate(cpu);
2091         if (avg_pstate > target)
2092                 target += (avg_pstate - target) >> 1;
2093
2094         return target;
2095 }
2096
2097 static int intel_pstate_prepare_request(struct cpudata *cpu, int pstate)
2098 {
2099         int min_pstate = max(cpu->pstate.min_pstate, cpu->min_perf_ratio);
2100         int max_pstate = max(min_pstate, cpu->max_perf_ratio);
2101
2102         return clamp_t(int, pstate, min_pstate, max_pstate);
2103 }
2104
2105 static void intel_pstate_update_pstate(struct cpudata *cpu, int pstate)
2106 {
2107         if (pstate == cpu->pstate.current_pstate)
2108                 return;
2109
2110         cpu->pstate.current_pstate = pstate;
2111         wrmsrl(MSR_IA32_PERF_CTL, pstate_funcs.get_val(cpu, pstate));
2112 }
2113
2114 static void intel_pstate_adjust_pstate(struct cpudata *cpu)
2115 {
2116         int from = cpu->pstate.current_pstate;
2117         struct sample *sample;
2118         int target_pstate;
2119
2120         update_turbo_state();
2121
2122         target_pstate = get_target_pstate(cpu);
2123         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2124         trace_cpu_frequency(target_pstate * cpu->pstate.scaling, cpu->cpu);
2125         intel_pstate_update_pstate(cpu, target_pstate);
2126
2127         sample = &cpu->sample;
2128         trace_pstate_sample(mul_ext_fp(100, sample->core_avg_perf),
2129                 fp_toint(sample->busy_scaled),
2130                 from,
2131                 cpu->pstate.current_pstate,
2132                 sample->mperf,
2133                 sample->aperf,
2134                 sample->tsc,
2135                 get_avg_frequency(cpu),
2136                 fp_toint(cpu->iowait_boost * 100));
2137 }
2138
2139 static void intel_pstate_update_util(struct update_util_data *data, u64 time,
2140                                      unsigned int flags)
2141 {
2142         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
2143         u64 delta_ns;
2144
2145         /* Don't allow remote callbacks */
2146         if (smp_processor_id() != cpu->cpu)
2147                 return;
2148
2149         delta_ns = time - cpu->last_update;
2150         if (flags & SCHED_CPUFREQ_IOWAIT) {
2151                 /* Start over if the CPU may have been idle. */
2152                 if (delta_ns > TICK_NSEC) {
2153                         cpu->iowait_boost = ONE_EIGHTH_FP;
2154                 } else if (cpu->iowait_boost >= ONE_EIGHTH_FP) {
2155                         cpu->iowait_boost <<= 1;
2156                         if (cpu->iowait_boost > int_tofp(1))
2157                                 cpu->iowait_boost = int_tofp(1);
2158                 } else {
2159                         cpu->iowait_boost = ONE_EIGHTH_FP;
2160                 }
2161         } else if (cpu->iowait_boost) {
2162                 /* Clear iowait_boost if the CPU may have been idle. */
2163                 if (delta_ns > TICK_NSEC)
2164                         cpu->iowait_boost = 0;
2165                 else
2166                         cpu->iowait_boost >>= 1;
2167         }
2168         cpu->last_update = time;
2169         delta_ns = time - cpu->sample.time;
2170         if ((s64)delta_ns < INTEL_PSTATE_SAMPLING_INTERVAL)
2171                 return;
2172
2173         if (intel_pstate_sample(cpu, time))
2174                 intel_pstate_adjust_pstate(cpu);
2175 }
2176
2177 static struct pstate_funcs core_funcs = {
2178         .get_max = core_get_max_pstate,
2179         .get_max_physical = core_get_max_pstate_physical,
2180         .get_min = core_get_min_pstate,
2181         .get_turbo = core_get_turbo_pstate,
2182         .get_scaling = core_get_scaling,
2183         .get_val = core_get_val,
2184 };
2185
2186 static const struct pstate_funcs silvermont_funcs = {
2187         .get_max = atom_get_max_pstate,
2188         .get_max_physical = atom_get_max_pstate,
2189         .get_min = atom_get_min_pstate,
2190         .get_turbo = atom_get_turbo_pstate,
2191         .get_val = atom_get_val,
2192         .get_scaling = silvermont_get_scaling,
2193         .get_vid = atom_get_vid,
2194 };
2195
2196 static const struct pstate_funcs airmont_funcs = {
2197         .get_max = atom_get_max_pstate,
2198         .get_max_physical = atom_get_max_pstate,
2199         .get_min = atom_get_min_pstate,
2200         .get_turbo = atom_get_turbo_pstate,
2201         .get_val = atom_get_val,
2202         .get_scaling = airmont_get_scaling,
2203         .get_vid = atom_get_vid,
2204 };
2205
2206 static const struct pstate_funcs knl_funcs = {
2207         .get_max = core_get_max_pstate,
2208         .get_max_physical = core_get_max_pstate_physical,
2209         .get_min = core_get_min_pstate,
2210         .get_turbo = knl_get_turbo_pstate,
2211         .get_aperf_mperf_shift = knl_get_aperf_mperf_shift,
2212         .get_scaling = core_get_scaling,
2213         .get_val = core_get_val,
2214 };
2215
2216 #define X86_MATCH(model, policy)                                         \
2217         X86_MATCH_VENDOR_FAM_MODEL_FEATURE(INTEL, 6, INTEL_FAM6_##model, \
2218                                            X86_FEATURE_APERFMPERF, &policy)
2219
2220 static const struct x86_cpu_id intel_pstate_cpu_ids[] = {
2221         X86_MATCH(SANDYBRIDGE,          core_funcs),
2222         X86_MATCH(SANDYBRIDGE_X,        core_funcs),
2223         X86_MATCH(ATOM_SILVERMONT,      silvermont_funcs),
2224         X86_MATCH(IVYBRIDGE,            core_funcs),
2225         X86_MATCH(HASWELL,              core_funcs),
2226         X86_MATCH(BROADWELL,            core_funcs),
2227         X86_MATCH(IVYBRIDGE_X,          core_funcs),
2228         X86_MATCH(HASWELL_X,            core_funcs),
2229         X86_MATCH(HASWELL_L,            core_funcs),
2230         X86_MATCH(HASWELL_G,            core_funcs),
2231         X86_MATCH(BROADWELL_G,          core_funcs),
2232         X86_MATCH(ATOM_AIRMONT,         airmont_funcs),
2233         X86_MATCH(SKYLAKE_L,            core_funcs),
2234         X86_MATCH(BROADWELL_X,          core_funcs),
2235         X86_MATCH(SKYLAKE,              core_funcs),
2236         X86_MATCH(BROADWELL_D,          core_funcs),
2237         X86_MATCH(XEON_PHI_KNL,         knl_funcs),
2238         X86_MATCH(XEON_PHI_KNM,         knl_funcs),
2239         X86_MATCH(ATOM_GOLDMONT,        core_funcs),
2240         X86_MATCH(ATOM_GOLDMONT_PLUS,   core_funcs),
2241         X86_MATCH(SKYLAKE_X,            core_funcs),
2242         X86_MATCH(COMETLAKE,            core_funcs),
2243         X86_MATCH(ICELAKE_X,            core_funcs),
2244         {}
2245 };
2246 MODULE_DEVICE_TABLE(x86cpu, intel_pstate_cpu_ids);
2247
2248 static const struct x86_cpu_id intel_pstate_cpu_oob_ids[] __initconst = {
2249         X86_MATCH(BROADWELL_D,          core_funcs),
2250         X86_MATCH(BROADWELL_X,          core_funcs),
2251         X86_MATCH(SKYLAKE_X,            core_funcs),
2252         {}
2253 };
2254
2255 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[] = {
2256         X86_MATCH(KABYLAKE,             core_funcs),
2257         {}
2258 };
2259
2260 static const struct x86_cpu_id intel_pstate_hwp_boost_ids[] = {
2261         X86_MATCH(SKYLAKE_X,            core_funcs),
2262         X86_MATCH(SKYLAKE,              core_funcs),
2263         {}
2264 };
2265
2266 static int intel_pstate_init_cpu(unsigned int cpunum)
2267 {
2268         struct cpudata *cpu;
2269
2270         cpu = all_cpu_data[cpunum];
2271
2272         if (!cpu) {
2273                 cpu = kzalloc(sizeof(*cpu), GFP_KERNEL);
2274                 if (!cpu)
2275                         return -ENOMEM;
2276
2277                 all_cpu_data[cpunum] = cpu;
2278
2279                 cpu->cpu = cpunum;
2280
2281                 cpu->epp_default = -EINVAL;
2282
2283                 if (hwp_active) {
2284                         const struct x86_cpu_id *id;
2285
2286                         intel_pstate_hwp_enable(cpu);
2287
2288                         id = x86_match_cpu(intel_pstate_hwp_boost_ids);
2289                         if (id && intel_pstate_acpi_pm_profile_server())
2290                                 hwp_boost = true;
2291                 }
2292         } else if (hwp_active) {
2293                 /*
2294                  * Re-enable HWP in case this happens after a resume from ACPI
2295                  * S3 if the CPU was offline during the whole system/resume
2296                  * cycle.
2297                  */
2298                 intel_pstate_hwp_reenable(cpu);
2299         }
2300
2301         cpu->epp_powersave = -EINVAL;
2302         cpu->epp_policy = 0;
2303
2304         intel_pstate_get_cpu_pstates(cpu);
2305
2306         pr_debug("controlling: cpu %d\n", cpunum);
2307
2308         return 0;
2309 }
2310
2311 static void intel_pstate_set_update_util_hook(unsigned int cpu_num)
2312 {
2313         struct cpudata *cpu = all_cpu_data[cpu_num];
2314
2315         if (hwp_active && !hwp_boost)
2316                 return;
2317
2318         if (cpu->update_util_set)
2319                 return;
2320
2321         /* Prevent intel_pstate_update_util() from using stale data. */
2322         cpu->sample.time = 0;
2323         cpufreq_add_update_util_hook(cpu_num, &cpu->update_util,
2324                                      (hwp_active ?
2325                                       intel_pstate_update_util_hwp :
2326                                       intel_pstate_update_util));
2327         cpu->update_util_set = true;
2328 }
2329
2330 static void intel_pstate_clear_update_util_hook(unsigned int cpu)
2331 {
2332         struct cpudata *cpu_data = all_cpu_data[cpu];
2333
2334         if (!cpu_data->update_util_set)
2335                 return;
2336
2337         cpufreq_remove_update_util_hook(cpu);
2338         cpu_data->update_util_set = false;
2339         synchronize_rcu();
2340 }
2341
2342 static int intel_pstate_get_max_freq(struct cpudata *cpu)
2343 {
2344         return global.turbo_disabled || global.no_turbo ?
2345                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2346 }
2347
2348 static void intel_pstate_update_perf_limits(struct cpudata *cpu,
2349                                             unsigned int policy_min,
2350                                             unsigned int policy_max)
2351 {
2352         int perf_ctl_scaling = cpu->pstate.perf_ctl_scaling;
2353         int32_t max_policy_perf, min_policy_perf;
2354
2355         max_policy_perf = policy_max / perf_ctl_scaling;
2356         if (policy_max == policy_min) {
2357                 min_policy_perf = max_policy_perf;
2358         } else {
2359                 min_policy_perf = policy_min / perf_ctl_scaling;
2360                 min_policy_perf = clamp_t(int32_t, min_policy_perf,
2361                                           0, max_policy_perf);
2362         }
2363
2364         /*
2365          * HWP needs some special consideration, because HWP_REQUEST uses
2366          * abstract values to represent performance rather than pure ratios.
2367          */
2368         if (hwp_active) {
2369                 intel_pstate_get_hwp_cap(cpu);
2370
2371                 if (cpu->pstate.scaling != perf_ctl_scaling) {
2372                         int scaling = cpu->pstate.scaling;
2373                         int freq;
2374
2375                         freq = max_policy_perf * perf_ctl_scaling;
2376                         max_policy_perf = DIV_ROUND_UP(freq, scaling);
2377                         freq = min_policy_perf * perf_ctl_scaling;
2378                         min_policy_perf = DIV_ROUND_UP(freq, scaling);
2379                 }
2380         }
2381
2382         pr_debug("cpu:%d min_policy_perf:%d max_policy_perf:%d\n",
2383                  cpu->cpu, min_policy_perf, max_policy_perf);
2384
2385         /* Normalize user input to [min_perf, max_perf] */
2386         if (per_cpu_limits) {
2387                 cpu->min_perf_ratio = min_policy_perf;
2388                 cpu->max_perf_ratio = max_policy_perf;
2389         } else {
2390                 int turbo_max = cpu->pstate.turbo_pstate;
2391                 int32_t global_min, global_max;
2392
2393                 /* Global limits are in percent of the maximum turbo P-state. */
2394                 global_max = DIV_ROUND_UP(turbo_max * global.max_perf_pct, 100);
2395                 global_min = DIV_ROUND_UP(turbo_max * global.min_perf_pct, 100);
2396                 global_min = clamp_t(int32_t, global_min, 0, global_max);
2397
2398                 pr_debug("cpu:%d global_min:%d global_max:%d\n", cpu->cpu,
2399                          global_min, global_max);
2400
2401                 cpu->min_perf_ratio = max(min_policy_perf, global_min);
2402                 cpu->min_perf_ratio = min(cpu->min_perf_ratio, max_policy_perf);
2403                 cpu->max_perf_ratio = min(max_policy_perf, global_max);
2404                 cpu->max_perf_ratio = max(min_policy_perf, cpu->max_perf_ratio);
2405
2406                 /* Make sure min_perf <= max_perf */
2407                 cpu->min_perf_ratio = min(cpu->min_perf_ratio,
2408                                           cpu->max_perf_ratio);
2409
2410         }
2411         pr_debug("cpu:%d max_perf_ratio:%d min_perf_ratio:%d\n", cpu->cpu,
2412                  cpu->max_perf_ratio,
2413                  cpu->min_perf_ratio);
2414 }
2415
2416 static int intel_pstate_set_policy(struct cpufreq_policy *policy)
2417 {
2418         struct cpudata *cpu;
2419
2420         if (!policy->cpuinfo.max_freq)
2421                 return -ENODEV;
2422
2423         pr_debug("set_policy cpuinfo.max %u policy->max %u\n",
2424                  policy->cpuinfo.max_freq, policy->max);
2425
2426         cpu = all_cpu_data[policy->cpu];
2427         cpu->policy = policy->policy;
2428
2429         mutex_lock(&intel_pstate_limits_lock);
2430
2431         intel_pstate_update_perf_limits(cpu, policy->min, policy->max);
2432
2433         if (cpu->policy == CPUFREQ_POLICY_PERFORMANCE) {
2434                 /*
2435                  * NOHZ_FULL CPUs need this as the governor callback may not
2436                  * be invoked on them.
2437                  */
2438                 intel_pstate_clear_update_util_hook(policy->cpu);
2439                 intel_pstate_max_within_limits(cpu);
2440         } else {
2441                 intel_pstate_set_update_util_hook(policy->cpu);
2442         }
2443
2444         if (hwp_active) {
2445                 /*
2446                  * When hwp_boost was active before and dynamically it
2447                  * was turned off, in that case we need to clear the
2448                  * update util hook.
2449                  */
2450                 if (!hwp_boost)
2451                         intel_pstate_clear_update_util_hook(policy->cpu);
2452                 intel_pstate_hwp_set(policy->cpu);
2453         }
2454
2455         mutex_unlock(&intel_pstate_limits_lock);
2456
2457         return 0;
2458 }
2459
2460 static void intel_pstate_adjust_policy_max(struct cpudata *cpu,
2461                                            struct cpufreq_policy_data *policy)
2462 {
2463         if (!hwp_active &&
2464             cpu->pstate.max_pstate_physical > cpu->pstate.max_pstate &&
2465             policy->max < policy->cpuinfo.max_freq &&
2466             policy->max > cpu->pstate.max_freq) {
2467                 pr_debug("policy->max > max non turbo frequency\n");
2468                 policy->max = policy->cpuinfo.max_freq;
2469         }
2470 }
2471
2472 static void intel_pstate_verify_cpu_policy(struct cpudata *cpu,
2473                                            struct cpufreq_policy_data *policy)
2474 {
2475         int max_freq;
2476
2477         update_turbo_state();
2478         if (hwp_active) {
2479                 intel_pstate_get_hwp_cap(cpu);
2480                 max_freq = global.no_turbo || global.turbo_disabled ?
2481                                 cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2482         } else {
2483                 max_freq = intel_pstate_get_max_freq(cpu);
2484         }
2485         cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, max_freq);
2486
2487         intel_pstate_adjust_policy_max(cpu, policy);
2488 }
2489
2490 static int intel_pstate_verify_policy(struct cpufreq_policy_data *policy)
2491 {
2492         intel_pstate_verify_cpu_policy(all_cpu_data[policy->cpu], policy);
2493
2494         return 0;
2495 }
2496
2497 static int intel_cpufreq_cpu_offline(struct cpufreq_policy *policy)
2498 {
2499         struct cpudata *cpu = all_cpu_data[policy->cpu];
2500
2501         pr_debug("CPU %d going offline\n", cpu->cpu);
2502
2503         if (cpu->suspended)
2504                 return 0;
2505
2506         /*
2507          * If the CPU is an SMT thread and it goes offline with the performance
2508          * settings different from the minimum, it will prevent its sibling
2509          * from getting to lower performance levels, so force the minimum
2510          * performance on CPU offline to prevent that from happening.
2511          */
2512         if (hwp_active)
2513                 intel_pstate_hwp_offline(cpu);
2514         else
2515                 intel_pstate_set_min_pstate(cpu);
2516
2517         intel_pstate_exit_perf_limits(policy);
2518
2519         return 0;
2520 }
2521
2522 static int intel_pstate_cpu_online(struct cpufreq_policy *policy)
2523 {
2524         struct cpudata *cpu = all_cpu_data[policy->cpu];
2525
2526         pr_debug("CPU %d going online\n", cpu->cpu);
2527
2528         intel_pstate_init_acpi_perf_limits(policy);
2529
2530         if (hwp_active) {
2531                 /*
2532                  * Re-enable HWP and clear the "suspended" flag to let "resume"
2533                  * know that it need not do that.
2534                  */
2535                 intel_pstate_hwp_reenable(cpu);
2536                 cpu->suspended = false;
2537         }
2538
2539         return 0;
2540 }
2541
2542 static int intel_pstate_cpu_offline(struct cpufreq_policy *policy)
2543 {
2544         intel_pstate_clear_update_util_hook(policy->cpu);
2545
2546         return intel_cpufreq_cpu_offline(policy);
2547 }
2548
2549 static int intel_pstate_cpu_exit(struct cpufreq_policy *policy)
2550 {
2551         pr_debug("CPU %d exiting\n", policy->cpu);
2552
2553         policy->fast_switch_possible = false;
2554
2555         return 0;
2556 }
2557
2558 static int __intel_pstate_cpu_init(struct cpufreq_policy *policy)
2559 {
2560         struct cpudata *cpu;
2561         int rc;
2562
2563         rc = intel_pstate_init_cpu(policy->cpu);
2564         if (rc)
2565                 return rc;
2566
2567         cpu = all_cpu_data[policy->cpu];
2568
2569         cpu->max_perf_ratio = 0xFF;
2570         cpu->min_perf_ratio = 0;
2571
2572         /* cpuinfo and default policy values */
2573         policy->cpuinfo.min_freq = cpu->pstate.min_freq;
2574         update_turbo_state();
2575         global.turbo_disabled_mf = global.turbo_disabled;
2576         policy->cpuinfo.max_freq = global.turbo_disabled ?
2577                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2578
2579         policy->min = policy->cpuinfo.min_freq;
2580         policy->max = policy->cpuinfo.max_freq;
2581
2582         intel_pstate_init_acpi_perf_limits(policy);
2583
2584         policy->fast_switch_possible = true;
2585
2586         return 0;
2587 }
2588
2589 static int intel_pstate_cpu_init(struct cpufreq_policy *policy)
2590 {
2591         int ret = __intel_pstate_cpu_init(policy);
2592
2593         if (ret)
2594                 return ret;
2595
2596         /*
2597          * Set the policy to powersave to provide a valid fallback value in case
2598          * the default cpufreq governor is neither powersave nor performance.
2599          */
2600         policy->policy = CPUFREQ_POLICY_POWERSAVE;
2601
2602         if (hwp_active) {
2603                 struct cpudata *cpu = all_cpu_data[policy->cpu];
2604
2605                 cpu->epp_cached = intel_pstate_get_epp(cpu, 0);
2606         }
2607
2608         return 0;
2609 }
2610
2611 static struct cpufreq_driver intel_pstate = {
2612         .flags          = CPUFREQ_CONST_LOOPS,
2613         .verify         = intel_pstate_verify_policy,
2614         .setpolicy      = intel_pstate_set_policy,
2615         .suspend        = intel_pstate_suspend,
2616         .resume         = intel_pstate_resume,
2617         .init           = intel_pstate_cpu_init,
2618         .exit           = intel_pstate_cpu_exit,
2619         .offline        = intel_pstate_cpu_offline,
2620         .online         = intel_pstate_cpu_online,
2621         .update_limits  = intel_pstate_update_limits,
2622         .name           = "intel_pstate",
2623 };
2624
2625 static int intel_cpufreq_verify_policy(struct cpufreq_policy_data *policy)
2626 {
2627         struct cpudata *cpu = all_cpu_data[policy->cpu];
2628
2629         intel_pstate_verify_cpu_policy(cpu, policy);
2630         intel_pstate_update_perf_limits(cpu, policy->min, policy->max);
2631
2632         return 0;
2633 }
2634
2635 /* Use of trace in passive mode:
2636  *
2637  * In passive mode the trace core_busy field (also known as the
2638  * performance field, and lablelled as such on the graphs; also known as
2639  * core_avg_perf) is not needed and so is re-assigned to indicate if the
2640  * driver call was via the normal or fast switch path. Various graphs
2641  * output from the intel_pstate_tracer.py utility that include core_busy
2642  * (or performance or core_avg_perf) have a fixed y-axis from 0 to 100%,
2643  * so we use 10 to indicate the normal path through the driver, and
2644  * 90 to indicate the fast switch path through the driver.
2645  * The scaled_busy field is not used, and is set to 0.
2646  */
2647
2648 #define INTEL_PSTATE_TRACE_TARGET 10
2649 #define INTEL_PSTATE_TRACE_FAST_SWITCH 90
2650
2651 static void intel_cpufreq_trace(struct cpudata *cpu, unsigned int trace_type, int old_pstate)
2652 {
2653         struct sample *sample;
2654
2655         if (!trace_pstate_sample_enabled())
2656                 return;
2657
2658         if (!intel_pstate_sample(cpu, ktime_get()))
2659                 return;
2660
2661         sample = &cpu->sample;
2662         trace_pstate_sample(trace_type,
2663                 0,
2664                 old_pstate,
2665                 cpu->pstate.current_pstate,
2666                 sample->mperf,
2667                 sample->aperf,
2668                 sample->tsc,
2669                 get_avg_frequency(cpu),
2670                 fp_toint(cpu->iowait_boost * 100));
2671 }
2672
2673 static void intel_cpufreq_hwp_update(struct cpudata *cpu, u32 min, u32 max,
2674                                      u32 desired, bool fast_switch)
2675 {
2676         u64 prev = READ_ONCE(cpu->hwp_req_cached), value = prev;
2677
2678         value &= ~HWP_MIN_PERF(~0L);
2679         value |= HWP_MIN_PERF(min);
2680
2681         value &= ~HWP_MAX_PERF(~0L);
2682         value |= HWP_MAX_PERF(max);
2683
2684         value &= ~HWP_DESIRED_PERF(~0L);
2685         value |= HWP_DESIRED_PERF(desired);
2686
2687         if (value == prev)
2688                 return;
2689
2690         WRITE_ONCE(cpu->hwp_req_cached, value);
2691         if (fast_switch)
2692                 wrmsrl(MSR_HWP_REQUEST, value);
2693         else
2694                 wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
2695 }
2696
2697 static void intel_cpufreq_perf_ctl_update(struct cpudata *cpu,
2698                                           u32 target_pstate, bool fast_switch)
2699 {
2700         if (fast_switch)
2701                 wrmsrl(MSR_IA32_PERF_CTL,
2702                        pstate_funcs.get_val(cpu, target_pstate));
2703         else
2704                 wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
2705                               pstate_funcs.get_val(cpu, target_pstate));
2706 }
2707
2708 static int intel_cpufreq_update_pstate(struct cpufreq_policy *policy,
2709                                        int target_pstate, bool fast_switch)
2710 {
2711         struct cpudata *cpu = all_cpu_data[policy->cpu];
2712         int old_pstate = cpu->pstate.current_pstate;
2713
2714         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2715         if (hwp_active) {
2716                 int max_pstate = policy->strict_target ?
2717                                         target_pstate : cpu->max_perf_ratio;
2718
2719                 intel_cpufreq_hwp_update(cpu, target_pstate, max_pstate, 0,
2720                                          fast_switch);
2721         } else if (target_pstate != old_pstate) {
2722                 intel_cpufreq_perf_ctl_update(cpu, target_pstate, fast_switch);
2723         }
2724
2725         cpu->pstate.current_pstate = target_pstate;
2726
2727         intel_cpufreq_trace(cpu, fast_switch ? INTEL_PSTATE_TRACE_FAST_SWITCH :
2728                             INTEL_PSTATE_TRACE_TARGET, old_pstate);
2729
2730         return target_pstate;
2731 }
2732
2733 static int intel_cpufreq_target(struct cpufreq_policy *policy,
2734                                 unsigned int target_freq,
2735                                 unsigned int relation)
2736 {
2737         struct cpudata *cpu = all_cpu_data[policy->cpu];
2738         struct cpufreq_freqs freqs;
2739         int target_pstate;
2740
2741         update_turbo_state();
2742
2743         freqs.old = policy->cur;
2744         freqs.new = target_freq;
2745
2746         cpufreq_freq_transition_begin(policy, &freqs);
2747
2748         switch (relation) {
2749         case CPUFREQ_RELATION_L:
2750                 target_pstate = DIV_ROUND_UP(freqs.new, cpu->pstate.scaling);
2751                 break;
2752         case CPUFREQ_RELATION_H:
2753                 target_pstate = freqs.new / cpu->pstate.scaling;
2754                 break;
2755         default:
2756                 target_pstate = DIV_ROUND_CLOSEST(freqs.new, cpu->pstate.scaling);
2757                 break;
2758         }
2759
2760         target_pstate = intel_cpufreq_update_pstate(policy, target_pstate, false);
2761
2762         freqs.new = target_pstate * cpu->pstate.scaling;
2763
2764         cpufreq_freq_transition_end(policy, &freqs, false);
2765
2766         return 0;
2767 }
2768
2769 static unsigned int intel_cpufreq_fast_switch(struct cpufreq_policy *policy,
2770                                               unsigned int target_freq)
2771 {
2772         struct cpudata *cpu = all_cpu_data[policy->cpu];
2773         int target_pstate;
2774
2775         update_turbo_state();
2776
2777         target_pstate = DIV_ROUND_UP(target_freq, cpu->pstate.scaling);
2778
2779         target_pstate = intel_cpufreq_update_pstate(policy, target_pstate, true);
2780
2781         return target_pstate * cpu->pstate.scaling;
2782 }
2783
2784 static void intel_cpufreq_adjust_perf(unsigned int cpunum,
2785                                       unsigned long min_perf,
2786                                       unsigned long target_perf,
2787                                       unsigned long capacity)
2788 {
2789         struct cpudata *cpu = all_cpu_data[cpunum];
2790         u64 hwp_cap = READ_ONCE(cpu->hwp_cap_cached);
2791         int old_pstate = cpu->pstate.current_pstate;
2792         int cap_pstate, min_pstate, max_pstate, target_pstate;
2793
2794         update_turbo_state();
2795         cap_pstate = global.turbo_disabled ? HWP_GUARANTEED_PERF(hwp_cap) :
2796                                              HWP_HIGHEST_PERF(hwp_cap);
2797
2798         /* Optimization: Avoid unnecessary divisions. */
2799
2800         target_pstate = cap_pstate;
2801         if (target_perf < capacity)
2802                 target_pstate = DIV_ROUND_UP(cap_pstate * target_perf, capacity);
2803
2804         min_pstate = cap_pstate;
2805         if (min_perf < capacity)
2806                 min_pstate = DIV_ROUND_UP(cap_pstate * min_perf, capacity);
2807
2808         if (min_pstate < cpu->pstate.min_pstate)
2809                 min_pstate = cpu->pstate.min_pstate;
2810
2811         if (min_pstate < cpu->min_perf_ratio)
2812                 min_pstate = cpu->min_perf_ratio;
2813
2814         max_pstate = min(cap_pstate, cpu->max_perf_ratio);
2815         if (max_pstate < min_pstate)
2816                 max_pstate = min_pstate;
2817
2818         target_pstate = clamp_t(int, target_pstate, min_pstate, max_pstate);
2819
2820         intel_cpufreq_hwp_update(cpu, min_pstate, max_pstate, target_pstate, true);
2821
2822         cpu->pstate.current_pstate = target_pstate;
2823         intel_cpufreq_trace(cpu, INTEL_PSTATE_TRACE_FAST_SWITCH, old_pstate);
2824 }
2825
2826 static int intel_cpufreq_cpu_init(struct cpufreq_policy *policy)
2827 {
2828         struct freq_qos_request *req;
2829         struct cpudata *cpu;
2830         struct device *dev;
2831         int ret, freq;
2832
2833         dev = get_cpu_device(policy->cpu);
2834         if (!dev)
2835                 return -ENODEV;
2836
2837         ret = __intel_pstate_cpu_init(policy);
2838         if (ret)
2839                 return ret;
2840
2841         policy->cpuinfo.transition_latency = INTEL_CPUFREQ_TRANSITION_LATENCY;
2842         /* This reflects the intel_pstate_get_cpu_pstates() setting. */
2843         policy->cur = policy->cpuinfo.min_freq;
2844
2845         req = kcalloc(2, sizeof(*req), GFP_KERNEL);
2846         if (!req) {
2847                 ret = -ENOMEM;
2848                 goto pstate_exit;
2849         }
2850
2851         cpu = all_cpu_data[policy->cpu];
2852
2853         if (hwp_active) {
2854                 u64 value;
2855
2856                 policy->transition_delay_us = INTEL_CPUFREQ_TRANSITION_DELAY_HWP;
2857
2858                 intel_pstate_get_hwp_cap(cpu);
2859
2860                 rdmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, &value);
2861                 WRITE_ONCE(cpu->hwp_req_cached, value);
2862
2863                 cpu->epp_cached = intel_pstate_get_epp(cpu, value);
2864         } else {
2865                 policy->transition_delay_us = INTEL_CPUFREQ_TRANSITION_DELAY;
2866         }
2867
2868         freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * global.min_perf_pct, 100);
2869
2870         ret = freq_qos_add_request(&policy->constraints, req, FREQ_QOS_MIN,
2871                                    freq);
2872         if (ret < 0) {
2873                 dev_err(dev, "Failed to add min-freq constraint (%d)\n", ret);
2874                 goto free_req;
2875         }
2876
2877         freq = DIV_ROUND_UP(cpu->pstate.turbo_freq * global.max_perf_pct, 100);
2878
2879         ret = freq_qos_add_request(&policy->constraints, req + 1, FREQ_QOS_MAX,
2880                                    freq);
2881         if (ret < 0) {
2882                 dev_err(dev, "Failed to add max-freq constraint (%d)\n", ret);
2883                 goto remove_min_req;
2884         }
2885
2886         policy->driver_data = req;
2887
2888         return 0;
2889
2890 remove_min_req:
2891         freq_qos_remove_request(req);
2892 free_req:
2893         kfree(req);
2894 pstate_exit:
2895         intel_pstate_exit_perf_limits(policy);
2896
2897         return ret;
2898 }
2899
2900 static int intel_cpufreq_cpu_exit(struct cpufreq_policy *policy)
2901 {
2902         struct freq_qos_request *req;
2903
2904         req = policy->driver_data;
2905
2906         freq_qos_remove_request(req + 1);
2907         freq_qos_remove_request(req);
2908         kfree(req);
2909
2910         return intel_pstate_cpu_exit(policy);
2911 }
2912
2913 static int intel_cpufreq_suspend(struct cpufreq_policy *policy)
2914 {
2915         intel_pstate_suspend(policy);
2916
2917         if (hwp_active) {
2918                 struct cpudata *cpu = all_cpu_data[policy->cpu];
2919                 u64 value = READ_ONCE(cpu->hwp_req_cached);
2920
2921                 /*
2922                  * Clear the desired perf field in MSR_HWP_REQUEST in case
2923                  * intel_cpufreq_adjust_perf() is in use and the last value
2924                  * written by it may not be suitable.
2925                  */
2926                 value &= ~HWP_DESIRED_PERF(~0L);
2927                 wrmsrl_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
2928                 WRITE_ONCE(cpu->hwp_req_cached, value);
2929         }
2930
2931         return 0;
2932 }
2933
2934 static struct cpufreq_driver intel_cpufreq = {
2935         .flags          = CPUFREQ_CONST_LOOPS,
2936         .verify         = intel_cpufreq_verify_policy,
2937         .target         = intel_cpufreq_target,
2938         .fast_switch    = intel_cpufreq_fast_switch,
2939         .init           = intel_cpufreq_cpu_init,
2940         .exit           = intel_cpufreq_cpu_exit,
2941         .offline        = intel_cpufreq_cpu_offline,
2942         .online         = intel_pstate_cpu_online,
2943         .suspend        = intel_cpufreq_suspend,
2944         .resume         = intel_pstate_resume,
2945         .update_limits  = intel_pstate_update_limits,
2946         .name           = "intel_cpufreq",
2947 };
2948
2949 static struct cpufreq_driver *default_driver;
2950
2951 static void intel_pstate_driver_cleanup(void)
2952 {
2953         unsigned int cpu;
2954
2955         cpus_read_lock();
2956         for_each_online_cpu(cpu) {
2957                 if (all_cpu_data[cpu]) {
2958                         if (intel_pstate_driver == &intel_pstate)
2959                                 intel_pstate_clear_update_util_hook(cpu);
2960
2961                         kfree(all_cpu_data[cpu]);
2962                         all_cpu_data[cpu] = NULL;
2963                 }
2964         }
2965         cpus_read_unlock();
2966
2967         intel_pstate_driver = NULL;
2968 }
2969
2970 static int intel_pstate_register_driver(struct cpufreq_driver *driver)
2971 {
2972         int ret;
2973
2974         if (driver == &intel_pstate)
2975                 intel_pstate_sysfs_expose_hwp_dynamic_boost();
2976
2977         memset(&global, 0, sizeof(global));
2978         global.max_perf_pct = 100;
2979
2980         intel_pstate_driver = driver;
2981         ret = cpufreq_register_driver(intel_pstate_driver);
2982         if (ret) {
2983                 intel_pstate_driver_cleanup();
2984                 return ret;
2985         }
2986
2987         global.min_perf_pct = min_perf_pct_min();
2988
2989         return 0;
2990 }
2991
2992 static ssize_t intel_pstate_show_status(char *buf)
2993 {
2994         if (!intel_pstate_driver)
2995                 return sprintf(buf, "off\n");
2996
2997         return sprintf(buf, "%s\n", intel_pstate_driver == &intel_pstate ?
2998                                         "active" : "passive");
2999 }
3000
3001 static int intel_pstate_update_status(const char *buf, size_t size)
3002 {
3003         if (size == 3 && !strncmp(buf, "off", size)) {
3004                 if (!intel_pstate_driver)
3005                         return -EINVAL;
3006
3007                 if (hwp_active)
3008                         return -EBUSY;
3009
3010                 cpufreq_unregister_driver(intel_pstate_driver);
3011                 intel_pstate_driver_cleanup();
3012                 return 0;
3013         }
3014
3015         if (size == 6 && !strncmp(buf, "active", size)) {
3016                 if (intel_pstate_driver) {
3017                         if (intel_pstate_driver == &intel_pstate)
3018                                 return 0;
3019
3020                         cpufreq_unregister_driver(intel_pstate_driver);
3021                 }
3022
3023                 return intel_pstate_register_driver(&intel_pstate);
3024         }
3025
3026         if (size == 7 && !strncmp(buf, "passive", size)) {
3027                 if (intel_pstate_driver) {
3028                         if (intel_pstate_driver == &intel_cpufreq)
3029                                 return 0;
3030
3031                         cpufreq_unregister_driver(intel_pstate_driver);
3032                         intel_pstate_sysfs_hide_hwp_dynamic_boost();
3033                 }
3034
3035                 return intel_pstate_register_driver(&intel_cpufreq);
3036         }
3037
3038         return -EINVAL;
3039 }
3040
3041 static int no_load __initdata;
3042 static int no_hwp __initdata;
3043 static int hwp_only __initdata;
3044 static unsigned int force_load __initdata;
3045
3046 static int __init intel_pstate_msrs_not_valid(void)
3047 {
3048         if (!pstate_funcs.get_max() ||
3049             !pstate_funcs.get_min() ||
3050             !pstate_funcs.get_turbo())
3051                 return -ENODEV;
3052
3053         return 0;
3054 }
3055
3056 static void __init copy_cpu_funcs(struct pstate_funcs *funcs)
3057 {
3058         pstate_funcs.get_max   = funcs->get_max;
3059         pstate_funcs.get_max_physical = funcs->get_max_physical;
3060         pstate_funcs.get_min   = funcs->get_min;
3061         pstate_funcs.get_turbo = funcs->get_turbo;
3062         pstate_funcs.get_scaling = funcs->get_scaling;
3063         pstate_funcs.get_val   = funcs->get_val;
3064         pstate_funcs.get_vid   = funcs->get_vid;
3065         pstate_funcs.get_aperf_mperf_shift = funcs->get_aperf_mperf_shift;
3066 }
3067
3068 #ifdef CONFIG_ACPI
3069
3070 static bool __init intel_pstate_no_acpi_pss(void)
3071 {
3072         int i;
3073
3074         for_each_possible_cpu(i) {
3075                 acpi_status status;
3076                 union acpi_object *pss;
3077                 struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
3078                 struct acpi_processor *pr = per_cpu(processors, i);
3079
3080                 if (!pr)
3081                         continue;
3082
3083                 status = acpi_evaluate_object(pr->handle, "_PSS", NULL, &buffer);
3084                 if (ACPI_FAILURE(status))
3085                         continue;
3086
3087                 pss = buffer.pointer;
3088                 if (pss && pss->type == ACPI_TYPE_PACKAGE) {
3089                         kfree(pss);
3090                         return false;
3091                 }
3092
3093                 kfree(pss);
3094         }
3095
3096         pr_debug("ACPI _PSS not found\n");
3097         return true;
3098 }
3099
3100 static bool __init intel_pstate_no_acpi_pcch(void)
3101 {
3102         acpi_status status;
3103         acpi_handle handle;
3104
3105         status = acpi_get_handle(NULL, "\\_SB", &handle);
3106         if (ACPI_FAILURE(status))
3107                 goto not_found;
3108
3109         if (acpi_has_method(handle, "PCCH"))
3110                 return false;
3111
3112 not_found:
3113         pr_debug("ACPI PCCH not found\n");
3114         return true;
3115 }
3116
3117 static bool __init intel_pstate_has_acpi_ppc(void)
3118 {
3119         int i;
3120
3121         for_each_possible_cpu(i) {
3122                 struct acpi_processor *pr = per_cpu(processors, i);
3123
3124                 if (!pr)
3125                         continue;
3126                 if (acpi_has_method(pr->handle, "_PPC"))
3127                         return true;
3128         }
3129         pr_debug("ACPI _PPC not found\n");
3130         return false;
3131 }
3132
3133 enum {
3134         PSS,
3135         PPC,
3136 };
3137
3138 /* Hardware vendor-specific info that has its own power management modes */
3139 static struct acpi_platform_list plat_info[] __initdata = {
3140         {"HP    ", "ProLiant", 0, ACPI_SIG_FADT, all_versions, NULL, PSS},
3141         {"ORACLE", "X4-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3142         {"ORACLE", "X4-2L   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3143         {"ORACLE", "X4-2B   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3144         {"ORACLE", "X3-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3145         {"ORACLE", "X3-2L   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3146         {"ORACLE", "X3-2B   ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3147         {"ORACLE", "X4470M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3148         {"ORACLE", "X4270M3 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3149         {"ORACLE", "X4270M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3150         {"ORACLE", "X4170M2 ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3151         {"ORACLE", "X4170 M3", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3152         {"ORACLE", "X4275 M3", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3153         {"ORACLE", "X6-2    ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3154         {"ORACLE", "Sudbury ", 0, ACPI_SIG_FADT, all_versions, NULL, PPC},
3155         { } /* End */
3156 };
3157
3158 #define BITMASK_OOB     (BIT(8) | BIT(18))
3159
3160 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
3161 {
3162         const struct x86_cpu_id *id;
3163         u64 misc_pwr;
3164         int idx;
3165
3166         id = x86_match_cpu(intel_pstate_cpu_oob_ids);
3167         if (id) {
3168                 rdmsrl(MSR_MISC_PWR_MGMT, misc_pwr);
3169                 if (misc_pwr & BITMASK_OOB) {
3170                         pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n");
3171                         pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n");
3172                         return true;
3173                 }
3174         }
3175
3176         idx = acpi_match_platform_list(plat_info);
3177         if (idx < 0)
3178                 return false;
3179
3180         switch (plat_info[idx].data) {
3181         case PSS:
3182                 if (!intel_pstate_no_acpi_pss())
3183                         return false;
3184
3185                 return intel_pstate_no_acpi_pcch();
3186         case PPC:
3187                 return intel_pstate_has_acpi_ppc() && !force_load;
3188         }
3189
3190         return false;
3191 }
3192
3193 static void intel_pstate_request_control_from_smm(void)
3194 {
3195         /*
3196          * It may be unsafe to request P-states control from SMM if _PPC support
3197          * has not been enabled.
3198          */
3199         if (acpi_ppc)
3200                 acpi_processor_pstate_control();
3201 }
3202 #else /* CONFIG_ACPI not enabled */
3203 static inline bool intel_pstate_platform_pwr_mgmt_exists(void) { return false; }
3204 static inline bool intel_pstate_has_acpi_ppc(void) { return false; }
3205 static inline void intel_pstate_request_control_from_smm(void) {}
3206 #endif /* CONFIG_ACPI */
3207
3208 #define INTEL_PSTATE_HWP_BROADWELL      0x01
3209
3210 #define X86_MATCH_HWP(model, hwp_mode)                                  \
3211         X86_MATCH_VENDOR_FAM_MODEL_FEATURE(INTEL, 6, INTEL_FAM6_##model, \
3212                                            X86_FEATURE_HWP, hwp_mode)
3213
3214 static const struct x86_cpu_id hwp_support_ids[] __initconst = {
3215         X86_MATCH_HWP(BROADWELL_X,      INTEL_PSTATE_HWP_BROADWELL),
3216         X86_MATCH_HWP(BROADWELL_D,      INTEL_PSTATE_HWP_BROADWELL),
3217         X86_MATCH_HWP(ANY,              0),
3218         {}
3219 };
3220
3221 static bool intel_pstate_hwp_is_enabled(void)
3222 {
3223         u64 value;
3224
3225         rdmsrl(MSR_PM_ENABLE, value);
3226         return !!(value & 0x1);
3227 }
3228
3229 static int __init intel_pstate_init(void)
3230 {
3231         const struct x86_cpu_id *id;
3232         int rc;
3233
3234         if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
3235                 return -ENODEV;
3236
3237         id = x86_match_cpu(hwp_support_ids);
3238         if (id) {
3239                 bool hwp_forced = intel_pstate_hwp_is_enabled();
3240
3241                 if (hwp_forced)
3242                         pr_info("HWP enabled by BIOS\n");
3243                 else if (no_load)
3244                         return -ENODEV;
3245
3246                 copy_cpu_funcs(&core_funcs);
3247                 /*
3248                  * Avoid enabling HWP for processors without EPP support,
3249                  * because that means incomplete HWP implementation which is a
3250                  * corner case and supporting it is generally problematic.
3251                  *
3252                  * If HWP is enabled already, though, there is no choice but to
3253                  * deal with it.
3254                  */
3255                 if ((!no_hwp && boot_cpu_has(X86_FEATURE_HWP_EPP)) || hwp_forced) {
3256                         hwp_active++;
3257                         hwp_mode_bdw = id->driver_data;
3258                         intel_pstate.attr = hwp_cpufreq_attrs;
3259                         intel_cpufreq.attr = hwp_cpufreq_attrs;
3260                         intel_cpufreq.flags |= CPUFREQ_NEED_UPDATE_LIMITS;
3261                         intel_cpufreq.adjust_perf = intel_cpufreq_adjust_perf;
3262                         if (!default_driver)
3263                                 default_driver = &intel_pstate;
3264
3265                         if (boot_cpu_has(X86_FEATURE_HYBRID_CPU))
3266                                 intel_pstate_cppc_set_cpu_scaling();
3267
3268                         goto hwp_cpu_matched;
3269                 }
3270                 pr_info("HWP not enabled\n");
3271         } else {
3272                 if (no_load)
3273                         return -ENODEV;
3274
3275                 id = x86_match_cpu(intel_pstate_cpu_ids);
3276                 if (!id) {
3277                         pr_info("CPU model not supported\n");
3278                         return -ENODEV;
3279                 }
3280
3281                 copy_cpu_funcs((struct pstate_funcs *)id->driver_data);
3282         }
3283
3284         if (intel_pstate_msrs_not_valid()) {
3285                 pr_info("Invalid MSRs\n");
3286                 return -ENODEV;
3287         }
3288         /* Without HWP start in the passive mode. */
3289         if (!default_driver)
3290                 default_driver = &intel_cpufreq;
3291
3292 hwp_cpu_matched:
3293         /*
3294          * The Intel pstate driver will be ignored if the platform
3295          * firmware has its own power management modes.
3296          */
3297         if (intel_pstate_platform_pwr_mgmt_exists()) {
3298                 pr_info("P-states controlled by the platform\n");
3299                 return -ENODEV;
3300         }
3301
3302         if (!hwp_active && hwp_only)
3303                 return -ENOTSUPP;
3304
3305         pr_info("Intel P-state driver initializing\n");
3306
3307         all_cpu_data = vzalloc(array_size(sizeof(void *), num_possible_cpus()));
3308         if (!all_cpu_data)
3309                 return -ENOMEM;
3310
3311         intel_pstate_request_control_from_smm();
3312
3313         intel_pstate_sysfs_expose_params();
3314
3315         mutex_lock(&intel_pstate_driver_lock);
3316         rc = intel_pstate_register_driver(default_driver);
3317         mutex_unlock(&intel_pstate_driver_lock);
3318         if (rc) {
3319                 intel_pstate_sysfs_remove();
3320                 return rc;
3321         }
3322
3323         if (hwp_active) {
3324                 const struct x86_cpu_id *id;
3325
3326                 id = x86_match_cpu(intel_pstate_cpu_ee_disable_ids);
3327                 if (id) {
3328                         set_power_ctl_ee_state(false);
3329                         pr_info("Disabling energy efficiency optimization\n");
3330                 }
3331
3332                 pr_info("HWP enabled\n");
3333         } else if (boot_cpu_has(X86_FEATURE_HYBRID_CPU)) {
3334                 pr_warn("Problematic setup: Hybrid processor with disabled HWP\n");
3335         }
3336
3337         return 0;
3338 }
3339 device_initcall(intel_pstate_init);
3340
3341 static int __init intel_pstate_setup(char *str)
3342 {
3343         if (!str)
3344                 return -EINVAL;
3345
3346         if (!strcmp(str, "disable"))
3347                 no_load = 1;
3348         else if (!strcmp(str, "active"))
3349                 default_driver = &intel_pstate;
3350         else if (!strcmp(str, "passive"))
3351                 default_driver = &intel_cpufreq;
3352
3353         if (!strcmp(str, "no_hwp"))
3354                 no_hwp = 1;
3355
3356         if (!strcmp(str, "force"))
3357                 force_load = 1;
3358         if (!strcmp(str, "hwp_only"))
3359                 hwp_only = 1;
3360         if (!strcmp(str, "per_cpu_perf_limits"))
3361                 per_cpu_limits = true;
3362
3363 #ifdef CONFIG_ACPI
3364         if (!strcmp(str, "support_acpi_ppc"))
3365                 acpi_ppc = true;
3366 #endif
3367
3368         return 0;
3369 }
3370 early_param("intel_pstate", intel_pstate_setup);
3371
3372 MODULE_AUTHOR("Dirk Brandewie <dirk.j.brandewie@intel.com>");
3373 MODULE_DESCRIPTION("'intel_pstate' - P state driver Intel Core processors");
3374 MODULE_LICENSE("GPL");