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