cpufreq: intel_pstate: Do not reinit performance limits in ->setpolicy
[linux-2.6-microblaze.git] / drivers / cpufreq / intel_pstate.c
1 /*
2  * intel_pstate.c: Native P state management for Intel processors
3  *
4  * (C) Copyright 2012 Intel Corporation
5  * Author: Dirk Brandewie <dirk.j.brandewie@intel.com>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; version 2
10  * of the License.
11  */
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/kernel.h>
16 #include <linux/kernel_stat.h>
17 #include <linux/module.h>
18 #include <linux/ktime.h>
19 #include <linux/hrtimer.h>
20 #include <linux/tick.h>
21 #include <linux/slab.h>
22 #include <linux/sched.h>
23 #include <linux/list.h>
24 #include <linux/cpu.h>
25 #include <linux/cpufreq.h>
26 #include <linux/sysfs.h>
27 #include <linux/types.h>
28 #include <linux/fs.h>
29 #include <linux/debugfs.h>
30 #include <linux/acpi.h>
31 #include <linux/vmalloc.h>
32 #include <trace/events/power.h>
33
34 #include <asm/div64.h>
35 #include <asm/msr.h>
36 #include <asm/cpu_device_id.h>
37 #include <asm/cpufeature.h>
38 #include <asm/intel-family.h>
39
40 #define INTEL_CPUFREQ_TRANSITION_LATENCY        20000
41
42 #define ATOM_RATIOS             0x66a
43 #define ATOM_VIDS               0x66b
44 #define ATOM_TURBO_RATIOS       0x66c
45 #define ATOM_TURBO_VIDS         0x66d
46
47 #ifdef CONFIG_ACPI
48 #include <acpi/processor.h>
49 #include <acpi/cppc_acpi.h>
50 #endif
51
52 #define FRAC_BITS 8
53 #define int_tofp(X) ((int64_t)(X) << FRAC_BITS)
54 #define fp_toint(X) ((X) >> FRAC_BITS)
55
56 #define EXT_BITS 6
57 #define EXT_FRAC_BITS (EXT_BITS + FRAC_BITS)
58 #define fp_ext_toint(X) ((X) >> EXT_FRAC_BITS)
59 #define int_ext_tofp(X) ((int64_t)(X) << EXT_FRAC_BITS)
60
61 static inline int32_t mul_fp(int32_t x, int32_t y)
62 {
63         return ((int64_t)x * (int64_t)y) >> FRAC_BITS;
64 }
65
66 static inline int32_t div_fp(s64 x, s64 y)
67 {
68         return div64_s64((int64_t)x << FRAC_BITS, y);
69 }
70
71 static inline int ceiling_fp(int32_t x)
72 {
73         int mask, ret;
74
75         ret = fp_toint(x);
76         mask = (1 << FRAC_BITS) - 1;
77         if (x & mask)
78                 ret += 1;
79         return ret;
80 }
81
82 static inline u64 mul_ext_fp(u64 x, u64 y)
83 {
84         return (x * y) >> EXT_FRAC_BITS;
85 }
86
87 static inline u64 div_ext_fp(u64 x, u64 y)
88 {
89         return div64_u64(x << EXT_FRAC_BITS, y);
90 }
91
92 /**
93  * struct sample -      Store performance sample
94  * @core_avg_perf:      Ratio of APERF/MPERF which is the actual average
95  *                      performance during last sample period
96  * @busy_scaled:        Scaled busy value which is used to calculate next
97  *                      P state. This can be different than core_avg_perf
98  *                      to account for cpu idle period
99  * @aperf:              Difference of actual performance frequency clock count
100  *                      read from APERF MSR between last and current sample
101  * @mperf:              Difference of maximum performance frequency clock count
102  *                      read from MPERF MSR between last and current sample
103  * @tsc:                Difference of time stamp counter between last and
104  *                      current sample
105  * @time:               Current time from scheduler
106  *
107  * This structure is used in the cpudata structure to store performance sample
108  * data for choosing next P State.
109  */
110 struct sample {
111         int32_t core_avg_perf;
112         int32_t busy_scaled;
113         u64 aperf;
114         u64 mperf;
115         u64 tsc;
116         u64 time;
117 };
118
119 /**
120  * struct pstate_data - Store P state data
121  * @current_pstate:     Current requested P state
122  * @min_pstate:         Min P state possible for this platform
123  * @max_pstate:         Max P state possible for this platform
124  * @max_pstate_physical:This is physical Max P state for a processor
125  *                      This can be higher than the max_pstate which can
126  *                      be limited by platform thermal design power limits
127  * @scaling:            Scaling factor to  convert frequency to cpufreq
128  *                      frequency units
129  * @turbo_pstate:       Max Turbo P state possible for this platform
130  * @max_freq:           @max_pstate frequency in cpufreq units
131  * @turbo_freq:         @turbo_pstate frequency in cpufreq units
132  *
133  * Stores the per cpu model P state limits and current P state.
134  */
135 struct pstate_data {
136         int     current_pstate;
137         int     min_pstate;
138         int     max_pstate;
139         int     max_pstate_physical;
140         int     scaling;
141         int     turbo_pstate;
142         unsigned int max_freq;
143         unsigned int turbo_freq;
144 };
145
146 /**
147  * struct vid_data -    Stores voltage information data
148  * @min:                VID data for this platform corresponding to
149  *                      the lowest P state
150  * @max:                VID data corresponding to the highest P State.
151  * @turbo:              VID data for turbo P state
152  * @ratio:              Ratio of (vid max - vid min) /
153  *                      (max P state - Min P State)
154  *
155  * Stores the voltage data for DVFS (Dynamic Voltage and Frequency Scaling)
156  * This data is used in Atom platforms, where in addition to target P state,
157  * the voltage data needs to be specified to select next P State.
158  */
159 struct vid_data {
160         int min;
161         int max;
162         int turbo;
163         int32_t ratio;
164 };
165
166 /**
167  * struct _pid -        Stores PID data
168  * @setpoint:           Target set point for busyness or performance
169  * @integral:           Storage for accumulated error values
170  * @p_gain:             PID proportional gain
171  * @i_gain:             PID integral gain
172  * @d_gain:             PID derivative gain
173  * @deadband:           PID deadband
174  * @last_err:           Last error storage for integral part of PID calculation
175  *
176  * Stores PID coefficients and last error for PID controller.
177  */
178 struct _pid {
179         int setpoint;
180         int32_t integral;
181         int32_t p_gain;
182         int32_t i_gain;
183         int32_t d_gain;
184         int deadband;
185         int32_t last_err;
186 };
187
188 /**
189  * struct perf_limits - Store user and policy limits
190  * @no_turbo:           User requested turbo state from intel_pstate sysfs
191  * @turbo_disabled:     Platform turbo status either from msr
192  *                      MSR_IA32_MISC_ENABLE or when maximum available pstate
193  *                      matches the maximum turbo pstate
194  * @max_perf_pct:       Effective maximum performance limit in percentage, this
195  *                      is minimum of either limits enforced by cpufreq policy
196  *                      or limits from user set limits via intel_pstate sysfs
197  * @min_perf_pct:       Effective minimum performance limit in percentage, this
198  *                      is maximum of either limits enforced by cpufreq policy
199  *                      or limits from user set limits via intel_pstate sysfs
200  * @max_perf:           This is a scaled value between 0 to 255 for max_perf_pct
201  *                      This value is used to limit max pstate
202  * @min_perf:           This is a scaled value between 0 to 255 for min_perf_pct
203  *                      This value is used to limit min pstate
204  * @max_policy_pct:     The maximum performance in percentage enforced by
205  *                      cpufreq setpolicy interface
206  * @max_sysfs_pct:      The maximum performance in percentage enforced by
207  *                      intel pstate sysfs interface, unused when per cpu
208  *                      controls are enforced
209  * @min_policy_pct:     The minimum performance in percentage enforced by
210  *                      cpufreq setpolicy interface
211  * @min_sysfs_pct:      The minimum performance in percentage enforced by
212  *                      intel pstate sysfs interface, unused when per cpu
213  *                      controls are enforced
214  *
215  * Storage for user and policy defined limits.
216  */
217 struct perf_limits {
218         int no_turbo;
219         int turbo_disabled;
220         int max_perf_pct;
221         int min_perf_pct;
222         int32_t max_perf;
223         int32_t min_perf;
224         int max_policy_pct;
225         int max_sysfs_pct;
226         int min_policy_pct;
227         int min_sysfs_pct;
228 };
229
230 /**
231  * struct cpudata -     Per CPU instance data storage
232  * @cpu:                CPU number for this instance data
233  * @policy:             CPUFreq policy value
234  * @update_util:        CPUFreq utility callback information
235  * @update_util_set:    CPUFreq utility callback is set
236  * @iowait_boost:       iowait-related boost fraction
237  * @last_update:        Time of the last update.
238  * @pstate:             Stores P state limits for this CPU
239  * @vid:                Stores VID limits for this CPU
240  * @pid:                Stores PID parameters for this CPU
241  * @last_sample_time:   Last Sample time
242  * @prev_aperf:         Last APERF value read from APERF MSR
243  * @prev_mperf:         Last MPERF value read from MPERF MSR
244  * @prev_tsc:           Last timestamp counter (TSC) value
245  * @prev_cummulative_iowait: IO Wait time difference from last and
246  *                      current sample
247  * @sample:             Storage for storing last Sample data
248  * @perf_limits:        Pointer to perf_limit unique to this CPU
249  *                      Not all field in the structure are applicable
250  *                      when per cpu controls are enforced
251  * @acpi_perf_data:     Stores ACPI perf information read from _PSS
252  * @valid_pss_table:    Set to true for valid ACPI _PSS entries found
253  * @epp_powersave:      Last saved HWP energy performance preference
254  *                      (EPP) or energy performance bias (EPB),
255  *                      when policy switched to performance
256  * @epp_policy:         Last saved policy used to set EPP/EPB
257  * @epp_default:        Power on default HWP energy performance
258  *                      preference/bias
259  * @epp_saved:          Saved EPP/EPB during system suspend or CPU offline
260  *                      operation
261  *
262  * This structure stores per CPU instance data for all CPUs.
263  */
264 struct cpudata {
265         int cpu;
266
267         unsigned int policy;
268         struct update_util_data update_util;
269         bool   update_util_set;
270
271         struct pstate_data pstate;
272         struct vid_data vid;
273         struct _pid pid;
274
275         u64     last_update;
276         u64     last_sample_time;
277         u64     prev_aperf;
278         u64     prev_mperf;
279         u64     prev_tsc;
280         u64     prev_cummulative_iowait;
281         struct sample sample;
282         struct perf_limits *perf_limits;
283 #ifdef CONFIG_ACPI
284         struct acpi_processor_performance acpi_perf_data;
285         bool valid_pss_table;
286 #endif
287         unsigned int iowait_boost;
288         s16 epp_powersave;
289         s16 epp_policy;
290         s16 epp_default;
291         s16 epp_saved;
292 };
293
294 static struct cpudata **all_cpu_data;
295
296 /**
297  * struct pstate_adjust_policy - Stores static PID configuration data
298  * @sample_rate_ms:     PID calculation sample rate in ms
299  * @sample_rate_ns:     Sample rate calculation in ns
300  * @deadband:           PID deadband
301  * @setpoint:           PID Setpoint
302  * @p_gain_pct:         PID proportional gain
303  * @i_gain_pct:         PID integral gain
304  * @d_gain_pct:         PID derivative gain
305  *
306  * Stores per CPU model static PID configuration data.
307  */
308 struct pstate_adjust_policy {
309         int sample_rate_ms;
310         s64 sample_rate_ns;
311         int deadband;
312         int setpoint;
313         int p_gain_pct;
314         int d_gain_pct;
315         int i_gain_pct;
316 };
317
318 /**
319  * struct pstate_funcs - Per CPU model specific callbacks
320  * @get_max:            Callback to get maximum non turbo effective P state
321  * @get_max_physical:   Callback to get maximum non turbo physical P state
322  * @get_min:            Callback to get minimum P state
323  * @get_turbo:          Callback to get turbo P state
324  * @get_scaling:        Callback to get frequency scaling factor
325  * @get_val:            Callback to convert P state to actual MSR write value
326  * @get_vid:            Callback to get VID data for Atom platforms
327  * @get_target_pstate:  Callback to a function to calculate next P state to use
328  *
329  * Core and Atom CPU models have different way to get P State limits. This
330  * structure is used to store those callbacks.
331  */
332 struct pstate_funcs {
333         int (*get_max)(void);
334         int (*get_max_physical)(void);
335         int (*get_min)(void);
336         int (*get_turbo)(void);
337         int (*get_scaling)(void);
338         u64 (*get_val)(struct cpudata*, int pstate);
339         void (*get_vid)(struct cpudata *);
340         int32_t (*get_target_pstate)(struct cpudata *);
341 };
342
343 /**
344  * struct cpu_defaults- Per CPU model default config data
345  * @pid_policy: PID config data
346  * @funcs:              Callback function data
347  */
348 struct cpu_defaults {
349         struct pstate_adjust_policy pid_policy;
350         struct pstate_funcs funcs;
351 };
352
353 static inline int32_t get_target_pstate_use_performance(struct cpudata *cpu);
354 static inline int32_t get_target_pstate_use_cpu_load(struct cpudata *cpu);
355
356 static struct pstate_adjust_policy pid_params __read_mostly;
357 static struct pstate_funcs pstate_funcs __read_mostly;
358 static int hwp_active __read_mostly;
359 static bool per_cpu_limits __read_mostly;
360
361 static bool driver_registered __read_mostly;
362
363 #ifdef CONFIG_ACPI
364 static bool acpi_ppc;
365 #endif
366
367 static struct perf_limits performance_limits;
368 static struct perf_limits powersave_limits;
369 static struct perf_limits *limits;
370
371 static void intel_pstate_init_limits(struct perf_limits *limits)
372 {
373         memset(limits, 0, sizeof(*limits));
374         limits->max_perf_pct = 100;
375         limits->max_perf = int_ext_tofp(1);
376         limits->max_policy_pct = 100;
377         limits->max_sysfs_pct = 100;
378 }
379
380 static void intel_pstate_set_performance_limits(struct perf_limits *limits)
381 {
382         intel_pstate_init_limits(limits);
383         limits->min_perf_pct = 100;
384         limits->min_perf = int_ext_tofp(1);
385         limits->min_sysfs_pct = 100;
386 }
387
388 static DEFINE_MUTEX(intel_pstate_driver_lock);
389 static DEFINE_MUTEX(intel_pstate_limits_lock);
390
391 #ifdef CONFIG_ACPI
392
393 static bool intel_pstate_get_ppc_enable_status(void)
394 {
395         if (acpi_gbl_FADT.preferred_profile == PM_ENTERPRISE_SERVER ||
396             acpi_gbl_FADT.preferred_profile == PM_PERFORMANCE_SERVER)
397                 return true;
398
399         return acpi_ppc;
400 }
401
402 #ifdef CONFIG_ACPI_CPPC_LIB
403
404 /* The work item is needed to avoid CPU hotplug locking issues */
405 static void intel_pstste_sched_itmt_work_fn(struct work_struct *work)
406 {
407         sched_set_itmt_support();
408 }
409
410 static DECLARE_WORK(sched_itmt_work, intel_pstste_sched_itmt_work_fn);
411
412 static void intel_pstate_set_itmt_prio(int cpu)
413 {
414         struct cppc_perf_caps cppc_perf;
415         static u32 max_highest_perf = 0, min_highest_perf = U32_MAX;
416         int ret;
417
418         ret = cppc_get_perf_caps(cpu, &cppc_perf);
419         if (ret)
420                 return;
421
422         /*
423          * The priorities can be set regardless of whether or not
424          * sched_set_itmt_support(true) has been called and it is valid to
425          * update them at any time after it has been called.
426          */
427         sched_set_itmt_core_prio(cppc_perf.highest_perf, cpu);
428
429         if (max_highest_perf <= min_highest_perf) {
430                 if (cppc_perf.highest_perf > max_highest_perf)
431                         max_highest_perf = cppc_perf.highest_perf;
432
433                 if (cppc_perf.highest_perf < min_highest_perf)
434                         min_highest_perf = cppc_perf.highest_perf;
435
436                 if (max_highest_perf > min_highest_perf) {
437                         /*
438                          * This code can be run during CPU online under the
439                          * CPU hotplug locks, so sched_set_itmt_support()
440                          * cannot be called from here.  Queue up a work item
441                          * to invoke it.
442                          */
443                         schedule_work(&sched_itmt_work);
444                 }
445         }
446 }
447 #else
448 static void intel_pstate_set_itmt_prio(int cpu)
449 {
450 }
451 #endif
452
453 static void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
454 {
455         struct cpudata *cpu;
456         int ret;
457         int i;
458
459         if (hwp_active) {
460                 intel_pstate_set_itmt_prio(policy->cpu);
461                 return;
462         }
463
464         if (!intel_pstate_get_ppc_enable_status())
465                 return;
466
467         cpu = all_cpu_data[policy->cpu];
468
469         ret = acpi_processor_register_performance(&cpu->acpi_perf_data,
470                                                   policy->cpu);
471         if (ret)
472                 return;
473
474         /*
475          * Check if the control value in _PSS is for PERF_CTL MSR, which should
476          * guarantee that the states returned by it map to the states in our
477          * list directly.
478          */
479         if (cpu->acpi_perf_data.control_register.space_id !=
480                                                 ACPI_ADR_SPACE_FIXED_HARDWARE)
481                 goto err;
482
483         /*
484          * If there is only one entry _PSS, simply ignore _PSS and continue as
485          * usual without taking _PSS into account
486          */
487         if (cpu->acpi_perf_data.state_count < 2)
488                 goto err;
489
490         pr_debug("CPU%u - ACPI _PSS perf data\n", policy->cpu);
491         for (i = 0; i < cpu->acpi_perf_data.state_count; i++) {
492                 pr_debug("     %cP%d: %u MHz, %u mW, 0x%x\n",
493                          (i == cpu->acpi_perf_data.state ? '*' : ' '), i,
494                          (u32) cpu->acpi_perf_data.states[i].core_frequency,
495                          (u32) cpu->acpi_perf_data.states[i].power,
496                          (u32) cpu->acpi_perf_data.states[i].control);
497         }
498
499         /*
500          * The _PSS table doesn't contain whole turbo frequency range.
501          * This just contains +1 MHZ above the max non turbo frequency,
502          * with control value corresponding to max turbo ratio. But
503          * when cpufreq set policy is called, it will call with this
504          * max frequency, which will cause a reduced performance as
505          * this driver uses real max turbo frequency as the max
506          * frequency. So correct this frequency in _PSS table to
507          * correct max turbo frequency based on the turbo state.
508          * Also need to convert to MHz as _PSS freq is in MHz.
509          */
510         if (!limits->turbo_disabled)
511                 cpu->acpi_perf_data.states[0].core_frequency =
512                                         policy->cpuinfo.max_freq / 1000;
513         cpu->valid_pss_table = true;
514         pr_debug("_PPC limits will be enforced\n");
515
516         return;
517
518  err:
519         cpu->valid_pss_table = false;
520         acpi_processor_unregister_performance(policy->cpu);
521 }
522
523 static void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
524 {
525         struct cpudata *cpu;
526
527         cpu = all_cpu_data[policy->cpu];
528         if (!cpu->valid_pss_table)
529                 return;
530
531         acpi_processor_unregister_performance(policy->cpu);
532 }
533 #else
534 static inline void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
535 {
536 }
537
538 static inline void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
539 {
540 }
541 #endif
542
543 static inline void pid_reset(struct _pid *pid, int setpoint, int busy,
544                              int deadband, int integral) {
545         pid->setpoint = int_tofp(setpoint);
546         pid->deadband  = int_tofp(deadband);
547         pid->integral  = int_tofp(integral);
548         pid->last_err  = int_tofp(setpoint) - int_tofp(busy);
549 }
550
551 static inline void pid_p_gain_set(struct _pid *pid, int percent)
552 {
553         pid->p_gain = div_fp(percent, 100);
554 }
555
556 static inline void pid_i_gain_set(struct _pid *pid, int percent)
557 {
558         pid->i_gain = div_fp(percent, 100);
559 }
560
561 static inline void pid_d_gain_set(struct _pid *pid, int percent)
562 {
563         pid->d_gain = div_fp(percent, 100);
564 }
565
566 static signed int pid_calc(struct _pid *pid, int32_t busy)
567 {
568         signed int result;
569         int32_t pterm, dterm, fp_error;
570         int32_t integral_limit;
571
572         fp_error = pid->setpoint - busy;
573
574         if (abs(fp_error) <= pid->deadband)
575                 return 0;
576
577         pterm = mul_fp(pid->p_gain, fp_error);
578
579         pid->integral += fp_error;
580
581         /*
582          * We limit the integral here so that it will never
583          * get higher than 30.  This prevents it from becoming
584          * too large an input over long periods of time and allows
585          * it to get factored out sooner.
586          *
587          * The value of 30 was chosen through experimentation.
588          */
589         integral_limit = int_tofp(30);
590         if (pid->integral > integral_limit)
591                 pid->integral = integral_limit;
592         if (pid->integral < -integral_limit)
593                 pid->integral = -integral_limit;
594
595         dterm = mul_fp(pid->d_gain, fp_error - pid->last_err);
596         pid->last_err = fp_error;
597
598         result = pterm + mul_fp(pid->integral, pid->i_gain) + dterm;
599         result = result + (1 << (FRAC_BITS-1));
600         return (signed int)fp_toint(result);
601 }
602
603 static inline void intel_pstate_busy_pid_reset(struct cpudata *cpu)
604 {
605         pid_p_gain_set(&cpu->pid, pid_params.p_gain_pct);
606         pid_d_gain_set(&cpu->pid, pid_params.d_gain_pct);
607         pid_i_gain_set(&cpu->pid, pid_params.i_gain_pct);
608
609         pid_reset(&cpu->pid, pid_params.setpoint, 100, pid_params.deadband, 0);
610 }
611
612 static inline void intel_pstate_reset_all_pid(void)
613 {
614         unsigned int cpu;
615
616         for_each_online_cpu(cpu) {
617                 if (all_cpu_data[cpu])
618                         intel_pstate_busy_pid_reset(all_cpu_data[cpu]);
619         }
620 }
621
622 static inline void update_turbo_state(void)
623 {
624         u64 misc_en;
625         struct cpudata *cpu;
626
627         cpu = all_cpu_data[0];
628         rdmsrl(MSR_IA32_MISC_ENABLE, misc_en);
629         limits->turbo_disabled =
630                 (misc_en & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ||
631                  cpu->pstate.max_pstate == cpu->pstate.turbo_pstate);
632 }
633
634 static s16 intel_pstate_get_epb(struct cpudata *cpu_data)
635 {
636         u64 epb;
637         int ret;
638
639         if (!static_cpu_has(X86_FEATURE_EPB))
640                 return -ENXIO;
641
642         ret = rdmsrl_on_cpu(cpu_data->cpu, MSR_IA32_ENERGY_PERF_BIAS, &epb);
643         if (ret)
644                 return (s16)ret;
645
646         return (s16)(epb & 0x0f);
647 }
648
649 static s16 intel_pstate_get_epp(struct cpudata *cpu_data, u64 hwp_req_data)
650 {
651         s16 epp;
652
653         if (static_cpu_has(X86_FEATURE_HWP_EPP)) {
654                 /*
655                  * When hwp_req_data is 0, means that caller didn't read
656                  * MSR_HWP_REQUEST, so need to read and get EPP.
657                  */
658                 if (!hwp_req_data) {
659                         epp = rdmsrl_on_cpu(cpu_data->cpu, MSR_HWP_REQUEST,
660                                             &hwp_req_data);
661                         if (epp)
662                                 return epp;
663                 }
664                 epp = (hwp_req_data >> 24) & 0xff;
665         } else {
666                 /* When there is no EPP present, HWP uses EPB settings */
667                 epp = intel_pstate_get_epb(cpu_data);
668         }
669
670         return epp;
671 }
672
673 static int intel_pstate_set_epb(int cpu, s16 pref)
674 {
675         u64 epb;
676         int ret;
677
678         if (!static_cpu_has(X86_FEATURE_EPB))
679                 return -ENXIO;
680
681         ret = rdmsrl_on_cpu(cpu, MSR_IA32_ENERGY_PERF_BIAS, &epb);
682         if (ret)
683                 return ret;
684
685         epb = (epb & ~0x0f) | pref;
686         wrmsrl_on_cpu(cpu, MSR_IA32_ENERGY_PERF_BIAS, epb);
687
688         return 0;
689 }
690
691 /*
692  * EPP/EPB display strings corresponding to EPP index in the
693  * energy_perf_strings[]
694  *      index           String
695  *-------------------------------------
696  *      0               default
697  *      1               performance
698  *      2               balance_performance
699  *      3               balance_power
700  *      4               power
701  */
702 static const char * const energy_perf_strings[] = {
703         "default",
704         "performance",
705         "balance_performance",
706         "balance_power",
707         "power",
708         NULL
709 };
710
711 static int intel_pstate_get_energy_pref_index(struct cpudata *cpu_data)
712 {
713         s16 epp;
714         int index = -EINVAL;
715
716         epp = intel_pstate_get_epp(cpu_data, 0);
717         if (epp < 0)
718                 return epp;
719
720         if (static_cpu_has(X86_FEATURE_HWP_EPP)) {
721                 /*
722                  * Range:
723                  *      0x00-0x3F       :       Performance
724                  *      0x40-0x7F       :       Balance performance
725                  *      0x80-0xBF       :       Balance power
726                  *      0xC0-0xFF       :       Power
727                  * The EPP is a 8 bit value, but our ranges restrict the
728                  * value which can be set. Here only using top two bits
729                  * effectively.
730                  */
731                 index = (epp >> 6) + 1;
732         } else if (static_cpu_has(X86_FEATURE_EPB)) {
733                 /*
734                  * Range:
735                  *      0x00-0x03       :       Performance
736                  *      0x04-0x07       :       Balance performance
737                  *      0x08-0x0B       :       Balance power
738                  *      0x0C-0x0F       :       Power
739                  * The EPB is a 4 bit value, but our ranges restrict the
740                  * value which can be set. Here only using top two bits
741                  * effectively.
742                  */
743                 index = (epp >> 2) + 1;
744         }
745
746         return index;
747 }
748
749 static int intel_pstate_set_energy_pref_index(struct cpudata *cpu_data,
750                                               int pref_index)
751 {
752         int epp = -EINVAL;
753         int ret;
754
755         if (!pref_index)
756                 epp = cpu_data->epp_default;
757
758         mutex_lock(&intel_pstate_limits_lock);
759
760         if (static_cpu_has(X86_FEATURE_HWP_EPP)) {
761                 u64 value;
762
763                 ret = rdmsrl_on_cpu(cpu_data->cpu, MSR_HWP_REQUEST, &value);
764                 if (ret)
765                         goto return_pref;
766
767                 value &= ~GENMASK_ULL(31, 24);
768
769                 /*
770                  * If epp is not default, convert from index into
771                  * energy_perf_strings to epp value, by shifting 6
772                  * bits left to use only top two bits in epp.
773                  * The resultant epp need to shifted by 24 bits to
774                  * epp position in MSR_HWP_REQUEST.
775                  */
776                 if (epp == -EINVAL)
777                         epp = (pref_index - 1) << 6;
778
779                 value |= (u64)epp << 24;
780                 ret = wrmsrl_on_cpu(cpu_data->cpu, MSR_HWP_REQUEST, value);
781         } else {
782                 if (epp == -EINVAL)
783                         epp = (pref_index - 1) << 2;
784                 ret = intel_pstate_set_epb(cpu_data->cpu, epp);
785         }
786 return_pref:
787         mutex_unlock(&intel_pstate_limits_lock);
788
789         return ret;
790 }
791
792 static ssize_t show_energy_performance_available_preferences(
793                                 struct cpufreq_policy *policy, char *buf)
794 {
795         int i = 0;
796         int ret = 0;
797
798         while (energy_perf_strings[i] != NULL)
799                 ret += sprintf(&buf[ret], "%s ", energy_perf_strings[i++]);
800
801         ret += sprintf(&buf[ret], "\n");
802
803         return ret;
804 }
805
806 cpufreq_freq_attr_ro(energy_performance_available_preferences);
807
808 static ssize_t store_energy_performance_preference(
809                 struct cpufreq_policy *policy, const char *buf, size_t count)
810 {
811         struct cpudata *cpu_data = all_cpu_data[policy->cpu];
812         char str_preference[21];
813         int ret, i = 0;
814
815         ret = sscanf(buf, "%20s", str_preference);
816         if (ret != 1)
817                 return -EINVAL;
818
819         while (energy_perf_strings[i] != NULL) {
820                 if (!strcmp(str_preference, energy_perf_strings[i])) {
821                         intel_pstate_set_energy_pref_index(cpu_data, i);
822                         return count;
823                 }
824                 ++i;
825         }
826
827         return -EINVAL;
828 }
829
830 static ssize_t show_energy_performance_preference(
831                                 struct cpufreq_policy *policy, char *buf)
832 {
833         struct cpudata *cpu_data = all_cpu_data[policy->cpu];
834         int preference;
835
836         preference = intel_pstate_get_energy_pref_index(cpu_data);
837         if (preference < 0)
838                 return preference;
839
840         return  sprintf(buf, "%s\n", energy_perf_strings[preference]);
841 }
842
843 cpufreq_freq_attr_rw(energy_performance_preference);
844
845 static struct freq_attr *hwp_cpufreq_attrs[] = {
846         &energy_performance_preference,
847         &energy_performance_available_preferences,
848         NULL,
849 };
850
851 static void intel_pstate_hwp_set(struct cpufreq_policy *policy)
852 {
853         int min, hw_min, max, hw_max, cpu, range, adj_range;
854         struct perf_limits *perf_limits = limits;
855         u64 value, cap;
856
857         for_each_cpu(cpu, policy->cpus) {
858                 int max_perf_pct, min_perf_pct;
859                 struct cpudata *cpu_data = all_cpu_data[cpu];
860                 s16 epp;
861
862                 if (per_cpu_limits)
863                         perf_limits = all_cpu_data[cpu]->perf_limits;
864
865                 rdmsrl_on_cpu(cpu, MSR_HWP_CAPABILITIES, &cap);
866                 hw_min = HWP_LOWEST_PERF(cap);
867                 if (limits->no_turbo)
868                         hw_max = HWP_GUARANTEED_PERF(cap);
869                 else
870                         hw_max = HWP_HIGHEST_PERF(cap);
871                 range = hw_max - hw_min;
872
873                 max_perf_pct = perf_limits->max_perf_pct;
874                 min_perf_pct = perf_limits->min_perf_pct;
875
876                 rdmsrl_on_cpu(cpu, MSR_HWP_REQUEST, &value);
877                 adj_range = min_perf_pct * range / 100;
878                 min = hw_min + adj_range;
879                 value &= ~HWP_MIN_PERF(~0L);
880                 value |= HWP_MIN_PERF(min);
881
882                 adj_range = max_perf_pct * range / 100;
883                 max = hw_min + adj_range;
884
885                 value &= ~HWP_MAX_PERF(~0L);
886                 value |= HWP_MAX_PERF(max);
887
888                 if (cpu_data->epp_policy == cpu_data->policy)
889                         goto skip_epp;
890
891                 cpu_data->epp_policy = cpu_data->policy;
892
893                 if (cpu_data->epp_saved >= 0) {
894                         epp = cpu_data->epp_saved;
895                         cpu_data->epp_saved = -EINVAL;
896                         goto update_epp;
897                 }
898
899                 if (cpu_data->policy == CPUFREQ_POLICY_PERFORMANCE) {
900                         epp = intel_pstate_get_epp(cpu_data, value);
901                         cpu_data->epp_powersave = epp;
902                         /* If EPP read was failed, then don't try to write */
903                         if (epp < 0)
904                                 goto skip_epp;
905
906
907                         epp = 0;
908                 } else {
909                         /* skip setting EPP, when saved value is invalid */
910                         if (cpu_data->epp_powersave < 0)
911                                 goto skip_epp;
912
913                         /*
914                          * No need to restore EPP when it is not zero. This
915                          * means:
916                          *  - Policy is not changed
917                          *  - user has manually changed
918                          *  - Error reading EPB
919                          */
920                         epp = intel_pstate_get_epp(cpu_data, value);
921                         if (epp)
922                                 goto skip_epp;
923
924                         epp = cpu_data->epp_powersave;
925                 }
926 update_epp:
927                 if (static_cpu_has(X86_FEATURE_HWP_EPP)) {
928                         value &= ~GENMASK_ULL(31, 24);
929                         value |= (u64)epp << 24;
930                 } else {
931                         intel_pstate_set_epb(cpu, epp);
932                 }
933 skip_epp:
934                 wrmsrl_on_cpu(cpu, MSR_HWP_REQUEST, value);
935         }
936 }
937
938 static int intel_pstate_hwp_set_policy(struct cpufreq_policy *policy)
939 {
940         if (hwp_active)
941                 intel_pstate_hwp_set(policy);
942
943         return 0;
944 }
945
946 static int intel_pstate_hwp_save_state(struct cpufreq_policy *policy)
947 {
948         struct cpudata *cpu_data = all_cpu_data[policy->cpu];
949
950         if (!hwp_active)
951                 return 0;
952
953         cpu_data->epp_saved = intel_pstate_get_epp(cpu_data, 0);
954
955         return 0;
956 }
957
958 static int intel_pstate_resume(struct cpufreq_policy *policy)
959 {
960         int ret;
961
962         if (!hwp_active)
963                 return 0;
964
965         mutex_lock(&intel_pstate_limits_lock);
966
967         all_cpu_data[policy->cpu]->epp_policy = 0;
968
969         ret = intel_pstate_hwp_set_policy(policy);
970
971         mutex_unlock(&intel_pstate_limits_lock);
972
973         return ret;
974 }
975
976 static void intel_pstate_update_policies(void)
977         __releases(&intel_pstate_limits_lock)
978         __acquires(&intel_pstate_limits_lock)
979 {
980         struct perf_limits *saved_limits = limits;
981         int cpu;
982
983         mutex_unlock(&intel_pstate_limits_lock);
984
985         for_each_possible_cpu(cpu)
986                 cpufreq_update_policy(cpu);
987
988         mutex_lock(&intel_pstate_limits_lock);
989
990         limits = saved_limits;
991 }
992
993 /************************** debugfs begin ************************/
994 static int pid_param_set(void *data, u64 val)
995 {
996         *(u32 *)data = val;
997         intel_pstate_reset_all_pid();
998         return 0;
999 }
1000
1001 static int pid_param_get(void *data, u64 *val)
1002 {
1003         *val = *(u32 *)data;
1004         return 0;
1005 }
1006 DEFINE_SIMPLE_ATTRIBUTE(fops_pid_param, pid_param_get, pid_param_set, "%llu\n");
1007
1008 static struct dentry *debugfs_parent;
1009
1010 struct pid_param {
1011         char *name;
1012         void *value;
1013         struct dentry *dentry;
1014 };
1015
1016 static struct pid_param pid_files[] = {
1017         {"sample_rate_ms", &pid_params.sample_rate_ms, },
1018         {"d_gain_pct", &pid_params.d_gain_pct, },
1019         {"i_gain_pct", &pid_params.i_gain_pct, },
1020         {"deadband", &pid_params.deadband, },
1021         {"setpoint", &pid_params.setpoint, },
1022         {"p_gain_pct", &pid_params.p_gain_pct, },
1023         {NULL, NULL, }
1024 };
1025
1026 static void intel_pstate_debug_expose_params(void)
1027 {
1028         int i;
1029
1030         debugfs_parent = debugfs_create_dir("pstate_snb", NULL);
1031         if (IS_ERR_OR_NULL(debugfs_parent))
1032                 return;
1033
1034         for (i = 0; pid_files[i].name; i++) {
1035                 struct dentry *dentry;
1036
1037                 dentry = debugfs_create_file(pid_files[i].name, 0660,
1038                                              debugfs_parent, pid_files[i].value,
1039                                              &fops_pid_param);
1040                 if (!IS_ERR(dentry))
1041                         pid_files[i].dentry = dentry;
1042         }
1043 }
1044
1045 static void intel_pstate_debug_hide_params(void)
1046 {
1047         int i;
1048
1049         if (IS_ERR_OR_NULL(debugfs_parent))
1050                 return;
1051
1052         for (i = 0; pid_files[i].name; i++) {
1053                 debugfs_remove(pid_files[i].dentry);
1054                 pid_files[i].dentry = NULL;
1055         }
1056
1057         debugfs_remove(debugfs_parent);
1058         debugfs_parent = NULL;
1059 }
1060
1061 /************************** debugfs end ************************/
1062
1063 /************************** sysfs begin ************************/
1064 #define show_one(file_name, object)                                     \
1065         static ssize_t show_##file_name                                 \
1066         (struct kobject *kobj, struct attribute *attr, char *buf)       \
1067         {                                                               \
1068                 return sprintf(buf, "%u\n", limits->object);            \
1069         }
1070
1071 static ssize_t intel_pstate_show_status(char *buf);
1072 static int intel_pstate_update_status(const char *buf, size_t size);
1073
1074 static ssize_t show_status(struct kobject *kobj,
1075                            struct attribute *attr, char *buf)
1076 {
1077         ssize_t ret;
1078
1079         mutex_lock(&intel_pstate_driver_lock);
1080         ret = intel_pstate_show_status(buf);
1081         mutex_unlock(&intel_pstate_driver_lock);
1082
1083         return ret;
1084 }
1085
1086 static ssize_t store_status(struct kobject *a, struct attribute *b,
1087                             const char *buf, size_t count)
1088 {
1089         char *p = memchr(buf, '\n', count);
1090         int ret;
1091
1092         mutex_lock(&intel_pstate_driver_lock);
1093         ret = intel_pstate_update_status(buf, p ? p - buf : count);
1094         mutex_unlock(&intel_pstate_driver_lock);
1095
1096         return ret < 0 ? ret : count;
1097 }
1098
1099 static ssize_t show_turbo_pct(struct kobject *kobj,
1100                                 struct attribute *attr, char *buf)
1101 {
1102         struct cpudata *cpu;
1103         int total, no_turbo, turbo_pct;
1104         uint32_t turbo_fp;
1105
1106         mutex_lock(&intel_pstate_driver_lock);
1107
1108         if (!driver_registered) {
1109                 mutex_unlock(&intel_pstate_driver_lock);
1110                 return -EAGAIN;
1111         }
1112
1113         cpu = all_cpu_data[0];
1114
1115         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1116         no_turbo = cpu->pstate.max_pstate - cpu->pstate.min_pstate + 1;
1117         turbo_fp = div_fp(no_turbo, total);
1118         turbo_pct = 100 - fp_toint(mul_fp(turbo_fp, int_tofp(100)));
1119
1120         mutex_unlock(&intel_pstate_driver_lock);
1121
1122         return sprintf(buf, "%u\n", turbo_pct);
1123 }
1124
1125 static ssize_t show_num_pstates(struct kobject *kobj,
1126                                 struct attribute *attr, char *buf)
1127 {
1128         struct cpudata *cpu;
1129         int total;
1130
1131         mutex_lock(&intel_pstate_driver_lock);
1132
1133         if (!driver_registered) {
1134                 mutex_unlock(&intel_pstate_driver_lock);
1135                 return -EAGAIN;
1136         }
1137
1138         cpu = all_cpu_data[0];
1139         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
1140
1141         mutex_unlock(&intel_pstate_driver_lock);
1142
1143         return sprintf(buf, "%u\n", total);
1144 }
1145
1146 static ssize_t show_no_turbo(struct kobject *kobj,
1147                              struct attribute *attr, char *buf)
1148 {
1149         ssize_t ret;
1150
1151         mutex_lock(&intel_pstate_driver_lock);
1152
1153         if (!driver_registered) {
1154                 mutex_unlock(&intel_pstate_driver_lock);
1155                 return -EAGAIN;
1156         }
1157
1158         update_turbo_state();
1159         if (limits->turbo_disabled)
1160                 ret = sprintf(buf, "%u\n", limits->turbo_disabled);
1161         else
1162                 ret = sprintf(buf, "%u\n", limits->no_turbo);
1163
1164         mutex_unlock(&intel_pstate_driver_lock);
1165
1166         return ret;
1167 }
1168
1169 static ssize_t store_no_turbo(struct kobject *a, struct attribute *b,
1170                               const char *buf, size_t count)
1171 {
1172         unsigned int input;
1173         int ret;
1174
1175         ret = sscanf(buf, "%u", &input);
1176         if (ret != 1)
1177                 return -EINVAL;
1178
1179         mutex_lock(&intel_pstate_driver_lock);
1180
1181         if (!driver_registered) {
1182                 mutex_unlock(&intel_pstate_driver_lock);
1183                 return -EAGAIN;
1184         }
1185
1186         mutex_lock(&intel_pstate_limits_lock);
1187
1188         update_turbo_state();
1189         if (limits->turbo_disabled) {
1190                 pr_warn("Turbo disabled by BIOS or unavailable on processor\n");
1191                 mutex_unlock(&intel_pstate_limits_lock);
1192                 mutex_unlock(&intel_pstate_driver_lock);
1193                 return -EPERM;
1194         }
1195
1196         limits->no_turbo = clamp_t(int, input, 0, 1);
1197
1198         intel_pstate_update_policies();
1199
1200         mutex_unlock(&intel_pstate_limits_lock);
1201
1202         mutex_unlock(&intel_pstate_driver_lock);
1203
1204         return count;
1205 }
1206
1207 static ssize_t store_max_perf_pct(struct kobject *a, struct attribute *b,
1208                                   const char *buf, size_t count)
1209 {
1210         unsigned int input;
1211         int ret;
1212
1213         ret = sscanf(buf, "%u", &input);
1214         if (ret != 1)
1215                 return -EINVAL;
1216
1217         mutex_lock(&intel_pstate_driver_lock);
1218
1219         if (!driver_registered) {
1220                 mutex_unlock(&intel_pstate_driver_lock);
1221                 return -EAGAIN;
1222         }
1223
1224         mutex_lock(&intel_pstate_limits_lock);
1225
1226         limits->max_sysfs_pct = clamp_t(int, input, 0 , 100);
1227         limits->max_perf_pct = min(limits->max_policy_pct,
1228                                    limits->max_sysfs_pct);
1229         limits->max_perf_pct = max(limits->min_policy_pct,
1230                                    limits->max_perf_pct);
1231         limits->max_perf_pct = max(limits->min_perf_pct,
1232                                    limits->max_perf_pct);
1233         limits->max_perf = div_ext_fp(limits->max_perf_pct, 100);
1234
1235         intel_pstate_update_policies();
1236
1237         mutex_unlock(&intel_pstate_limits_lock);
1238
1239         mutex_unlock(&intel_pstate_driver_lock);
1240
1241         return count;
1242 }
1243
1244 static ssize_t store_min_perf_pct(struct kobject *a, struct attribute *b,
1245                                   const char *buf, size_t count)
1246 {
1247         unsigned int input;
1248         int ret;
1249
1250         ret = sscanf(buf, "%u", &input);
1251         if (ret != 1)
1252                 return -EINVAL;
1253
1254         mutex_lock(&intel_pstate_driver_lock);
1255
1256         if (!driver_registered) {
1257                 mutex_unlock(&intel_pstate_driver_lock);
1258                 return -EAGAIN;
1259         }
1260
1261         mutex_lock(&intel_pstate_limits_lock);
1262
1263         limits->min_sysfs_pct = clamp_t(int, input, 0 , 100);
1264         limits->min_perf_pct = max(limits->min_policy_pct,
1265                                    limits->min_sysfs_pct);
1266         limits->min_perf_pct = min(limits->max_policy_pct,
1267                                    limits->min_perf_pct);
1268         limits->min_perf_pct = min(limits->max_perf_pct,
1269                                    limits->min_perf_pct);
1270         limits->min_perf = div_ext_fp(limits->min_perf_pct, 100);
1271
1272         intel_pstate_update_policies();
1273
1274         mutex_unlock(&intel_pstate_limits_lock);
1275
1276         mutex_unlock(&intel_pstate_driver_lock);
1277
1278         return count;
1279 }
1280
1281 show_one(max_perf_pct, max_perf_pct);
1282 show_one(min_perf_pct, min_perf_pct);
1283
1284 define_one_global_rw(status);
1285 define_one_global_rw(no_turbo);
1286 define_one_global_rw(max_perf_pct);
1287 define_one_global_rw(min_perf_pct);
1288 define_one_global_ro(turbo_pct);
1289 define_one_global_ro(num_pstates);
1290
1291 static struct attribute *intel_pstate_attributes[] = {
1292         &status.attr,
1293         &no_turbo.attr,
1294         &turbo_pct.attr,
1295         &num_pstates.attr,
1296         NULL
1297 };
1298
1299 static struct attribute_group intel_pstate_attr_group = {
1300         .attrs = intel_pstate_attributes,
1301 };
1302
1303 static void __init intel_pstate_sysfs_expose_params(void)
1304 {
1305         struct kobject *intel_pstate_kobject;
1306         int rc;
1307
1308         intel_pstate_kobject = kobject_create_and_add("intel_pstate",
1309                                                 &cpu_subsys.dev_root->kobj);
1310         if (WARN_ON(!intel_pstate_kobject))
1311                 return;
1312
1313         rc = sysfs_create_group(intel_pstate_kobject, &intel_pstate_attr_group);
1314         if (WARN_ON(rc))
1315                 return;
1316
1317         /*
1318          * If per cpu limits are enforced there are no global limits, so
1319          * return without creating max/min_perf_pct attributes
1320          */
1321         if (per_cpu_limits)
1322                 return;
1323
1324         rc = sysfs_create_file(intel_pstate_kobject, &max_perf_pct.attr);
1325         WARN_ON(rc);
1326
1327         rc = sysfs_create_file(intel_pstate_kobject, &min_perf_pct.attr);
1328         WARN_ON(rc);
1329
1330 }
1331 /************************** sysfs end ************************/
1332
1333 static void intel_pstate_hwp_enable(struct cpudata *cpudata)
1334 {
1335         /* First disable HWP notification interrupt as we don't process them */
1336         if (static_cpu_has(X86_FEATURE_HWP_NOTIFY))
1337                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x00);
1338
1339         wrmsrl_on_cpu(cpudata->cpu, MSR_PM_ENABLE, 0x1);
1340         cpudata->epp_policy = 0;
1341         if (cpudata->epp_default == -EINVAL)
1342                 cpudata->epp_default = intel_pstate_get_epp(cpudata, 0);
1343 }
1344
1345 #define MSR_IA32_POWER_CTL_BIT_EE       19
1346
1347 /* Disable energy efficiency optimization */
1348 static void intel_pstate_disable_ee(int cpu)
1349 {
1350         u64 power_ctl;
1351         int ret;
1352
1353         ret = rdmsrl_on_cpu(cpu, MSR_IA32_POWER_CTL, &power_ctl);
1354         if (ret)
1355                 return;
1356
1357         if (!(power_ctl & BIT(MSR_IA32_POWER_CTL_BIT_EE))) {
1358                 pr_info("Disabling energy efficiency optimization\n");
1359                 power_ctl |= BIT(MSR_IA32_POWER_CTL_BIT_EE);
1360                 wrmsrl_on_cpu(cpu, MSR_IA32_POWER_CTL, power_ctl);
1361         }
1362 }
1363
1364 static int atom_get_min_pstate(void)
1365 {
1366         u64 value;
1367
1368         rdmsrl(ATOM_RATIOS, value);
1369         return (value >> 8) & 0x7F;
1370 }
1371
1372 static int atom_get_max_pstate(void)
1373 {
1374         u64 value;
1375
1376         rdmsrl(ATOM_RATIOS, value);
1377         return (value >> 16) & 0x7F;
1378 }
1379
1380 static int atom_get_turbo_pstate(void)
1381 {
1382         u64 value;
1383
1384         rdmsrl(ATOM_TURBO_RATIOS, value);
1385         return value & 0x7F;
1386 }
1387
1388 static u64 atom_get_val(struct cpudata *cpudata, int pstate)
1389 {
1390         u64 val;
1391         int32_t vid_fp;
1392         u32 vid;
1393
1394         val = (u64)pstate << 8;
1395         if (limits->no_turbo && !limits->turbo_disabled)
1396                 val |= (u64)1 << 32;
1397
1398         vid_fp = cpudata->vid.min + mul_fp(
1399                 int_tofp(pstate - cpudata->pstate.min_pstate),
1400                 cpudata->vid.ratio);
1401
1402         vid_fp = clamp_t(int32_t, vid_fp, cpudata->vid.min, cpudata->vid.max);
1403         vid = ceiling_fp(vid_fp);
1404
1405         if (pstate > cpudata->pstate.max_pstate)
1406                 vid = cpudata->vid.turbo;
1407
1408         return val | vid;
1409 }
1410
1411 static int silvermont_get_scaling(void)
1412 {
1413         u64 value;
1414         int i;
1415         /* Defined in Table 35-6 from SDM (Sept 2015) */
1416         static int silvermont_freq_table[] = {
1417                 83300, 100000, 133300, 116700, 80000};
1418
1419         rdmsrl(MSR_FSB_FREQ, value);
1420         i = value & 0x7;
1421         WARN_ON(i > 4);
1422
1423         return silvermont_freq_table[i];
1424 }
1425
1426 static int airmont_get_scaling(void)
1427 {
1428         u64 value;
1429         int i;
1430         /* Defined in Table 35-10 from SDM (Sept 2015) */
1431         static int airmont_freq_table[] = {
1432                 83300, 100000, 133300, 116700, 80000,
1433                 93300, 90000, 88900, 87500};
1434
1435         rdmsrl(MSR_FSB_FREQ, value);
1436         i = value & 0xF;
1437         WARN_ON(i > 8);
1438
1439         return airmont_freq_table[i];
1440 }
1441
1442 static void atom_get_vid(struct cpudata *cpudata)
1443 {
1444         u64 value;
1445
1446         rdmsrl(ATOM_VIDS, value);
1447         cpudata->vid.min = int_tofp((value >> 8) & 0x7f);
1448         cpudata->vid.max = int_tofp((value >> 16) & 0x7f);
1449         cpudata->vid.ratio = div_fp(
1450                 cpudata->vid.max - cpudata->vid.min,
1451                 int_tofp(cpudata->pstate.max_pstate -
1452                         cpudata->pstate.min_pstate));
1453
1454         rdmsrl(ATOM_TURBO_VIDS, value);
1455         cpudata->vid.turbo = value & 0x7f;
1456 }
1457
1458 static int core_get_min_pstate(void)
1459 {
1460         u64 value;
1461
1462         rdmsrl(MSR_PLATFORM_INFO, value);
1463         return (value >> 40) & 0xFF;
1464 }
1465
1466 static int core_get_max_pstate_physical(void)
1467 {
1468         u64 value;
1469
1470         rdmsrl(MSR_PLATFORM_INFO, value);
1471         return (value >> 8) & 0xFF;
1472 }
1473
1474 static int core_get_tdp_ratio(u64 plat_info)
1475 {
1476         /* Check how many TDP levels present */
1477         if (plat_info & 0x600000000) {
1478                 u64 tdp_ctrl;
1479                 u64 tdp_ratio;
1480                 int tdp_msr;
1481                 int err;
1482
1483                 /* Get the TDP level (0, 1, 2) to get ratios */
1484                 err = rdmsrl_safe(MSR_CONFIG_TDP_CONTROL, &tdp_ctrl);
1485                 if (err)
1486                         return err;
1487
1488                 /* TDP MSR are continuous starting at 0x648 */
1489                 tdp_msr = MSR_CONFIG_TDP_NOMINAL + (tdp_ctrl & 0x03);
1490                 err = rdmsrl_safe(tdp_msr, &tdp_ratio);
1491                 if (err)
1492                         return err;
1493
1494                 /* For level 1 and 2, bits[23:16] contain the ratio */
1495                 if (tdp_ctrl & 0x03)
1496                         tdp_ratio >>= 16;
1497
1498                 tdp_ratio &= 0xff; /* ratios are only 8 bits long */
1499                 pr_debug("tdp_ratio %x\n", (int)tdp_ratio);
1500
1501                 return (int)tdp_ratio;
1502         }
1503
1504         return -ENXIO;
1505 }
1506
1507 static int core_get_max_pstate(void)
1508 {
1509         u64 tar;
1510         u64 plat_info;
1511         int max_pstate;
1512         int tdp_ratio;
1513         int err;
1514
1515         rdmsrl(MSR_PLATFORM_INFO, plat_info);
1516         max_pstate = (plat_info >> 8) & 0xFF;
1517
1518         tdp_ratio = core_get_tdp_ratio(plat_info);
1519         if (tdp_ratio <= 0)
1520                 return max_pstate;
1521
1522         if (hwp_active) {
1523                 /* Turbo activation ratio is not used on HWP platforms */
1524                 return tdp_ratio;
1525         }
1526
1527         err = rdmsrl_safe(MSR_TURBO_ACTIVATION_RATIO, &tar);
1528         if (!err) {
1529                 int tar_levels;
1530
1531                 /* Do some sanity checking for safety */
1532                 tar_levels = tar & 0xff;
1533                 if (tdp_ratio - 1 == tar_levels) {
1534                         max_pstate = tar_levels;
1535                         pr_debug("max_pstate=TAC %x\n", max_pstate);
1536                 }
1537         }
1538
1539         return max_pstate;
1540 }
1541
1542 static int core_get_turbo_pstate(void)
1543 {
1544         u64 value;
1545         int nont, ret;
1546
1547         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1548         nont = core_get_max_pstate();
1549         ret = (value) & 255;
1550         if (ret <= nont)
1551                 ret = nont;
1552         return ret;
1553 }
1554
1555 static inline int core_get_scaling(void)
1556 {
1557         return 100000;
1558 }
1559
1560 static u64 core_get_val(struct cpudata *cpudata, int pstate)
1561 {
1562         u64 val;
1563
1564         val = (u64)pstate << 8;
1565         if (limits->no_turbo && !limits->turbo_disabled)
1566                 val |= (u64)1 << 32;
1567
1568         return val;
1569 }
1570
1571 static int knl_get_turbo_pstate(void)
1572 {
1573         u64 value;
1574         int nont, ret;
1575
1576         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1577         nont = core_get_max_pstate();
1578         ret = (((value) >> 8) & 0xFF);
1579         if (ret <= nont)
1580                 ret = nont;
1581         return ret;
1582 }
1583
1584 static struct cpu_defaults core_params = {
1585         .pid_policy = {
1586                 .sample_rate_ms = 10,
1587                 .deadband = 0,
1588                 .setpoint = 97,
1589                 .p_gain_pct = 20,
1590                 .d_gain_pct = 0,
1591                 .i_gain_pct = 0,
1592         },
1593         .funcs = {
1594                 .get_max = core_get_max_pstate,
1595                 .get_max_physical = core_get_max_pstate_physical,
1596                 .get_min = core_get_min_pstate,
1597                 .get_turbo = core_get_turbo_pstate,
1598                 .get_scaling = core_get_scaling,
1599                 .get_val = core_get_val,
1600                 .get_target_pstate = get_target_pstate_use_performance,
1601         },
1602 };
1603
1604 static const struct cpu_defaults silvermont_params = {
1605         .pid_policy = {
1606                 .sample_rate_ms = 10,
1607                 .deadband = 0,
1608                 .setpoint = 60,
1609                 .p_gain_pct = 14,
1610                 .d_gain_pct = 0,
1611                 .i_gain_pct = 4,
1612         },
1613         .funcs = {
1614                 .get_max = atom_get_max_pstate,
1615                 .get_max_physical = atom_get_max_pstate,
1616                 .get_min = atom_get_min_pstate,
1617                 .get_turbo = atom_get_turbo_pstate,
1618                 .get_val = atom_get_val,
1619                 .get_scaling = silvermont_get_scaling,
1620                 .get_vid = atom_get_vid,
1621                 .get_target_pstate = get_target_pstate_use_cpu_load,
1622         },
1623 };
1624
1625 static const struct cpu_defaults airmont_params = {
1626         .pid_policy = {
1627                 .sample_rate_ms = 10,
1628                 .deadband = 0,
1629                 .setpoint = 60,
1630                 .p_gain_pct = 14,
1631                 .d_gain_pct = 0,
1632                 .i_gain_pct = 4,
1633         },
1634         .funcs = {
1635                 .get_max = atom_get_max_pstate,
1636                 .get_max_physical = atom_get_max_pstate,
1637                 .get_min = atom_get_min_pstate,
1638                 .get_turbo = atom_get_turbo_pstate,
1639                 .get_val = atom_get_val,
1640                 .get_scaling = airmont_get_scaling,
1641                 .get_vid = atom_get_vid,
1642                 .get_target_pstate = get_target_pstate_use_cpu_load,
1643         },
1644 };
1645
1646 static const struct cpu_defaults knl_params = {
1647         .pid_policy = {
1648                 .sample_rate_ms = 10,
1649                 .deadband = 0,
1650                 .setpoint = 97,
1651                 .p_gain_pct = 20,
1652                 .d_gain_pct = 0,
1653                 .i_gain_pct = 0,
1654         },
1655         .funcs = {
1656                 .get_max = core_get_max_pstate,
1657                 .get_max_physical = core_get_max_pstate_physical,
1658                 .get_min = core_get_min_pstate,
1659                 .get_turbo = knl_get_turbo_pstate,
1660                 .get_scaling = core_get_scaling,
1661                 .get_val = core_get_val,
1662                 .get_target_pstate = get_target_pstate_use_performance,
1663         },
1664 };
1665
1666 static const struct cpu_defaults bxt_params = {
1667         .pid_policy = {
1668                 .sample_rate_ms = 10,
1669                 .deadband = 0,
1670                 .setpoint = 60,
1671                 .p_gain_pct = 14,
1672                 .d_gain_pct = 0,
1673                 .i_gain_pct = 4,
1674         },
1675         .funcs = {
1676                 .get_max = core_get_max_pstate,
1677                 .get_max_physical = core_get_max_pstate_physical,
1678                 .get_min = core_get_min_pstate,
1679                 .get_turbo = core_get_turbo_pstate,
1680                 .get_scaling = core_get_scaling,
1681                 .get_val = core_get_val,
1682                 .get_target_pstate = get_target_pstate_use_cpu_load,
1683         },
1684 };
1685
1686 static void intel_pstate_get_min_max(struct cpudata *cpu, int *min, int *max)
1687 {
1688         int max_perf = cpu->pstate.turbo_pstate;
1689         int max_perf_adj;
1690         int min_perf;
1691         struct perf_limits *perf_limits = limits;
1692
1693         if (limits->no_turbo || limits->turbo_disabled)
1694                 max_perf = cpu->pstate.max_pstate;
1695
1696         if (per_cpu_limits)
1697                 perf_limits = cpu->perf_limits;
1698
1699         /*
1700          * performance can be limited by user through sysfs, by cpufreq
1701          * policy, or by cpu specific default values determined through
1702          * experimentation.
1703          */
1704         max_perf_adj = fp_ext_toint(max_perf * perf_limits->max_perf);
1705         *max = clamp_t(int, max_perf_adj,
1706                         cpu->pstate.min_pstate, cpu->pstate.turbo_pstate);
1707
1708         min_perf = fp_ext_toint(max_perf * perf_limits->min_perf);
1709         *min = clamp_t(int, min_perf, cpu->pstate.min_pstate, max_perf);
1710 }
1711
1712 static void intel_pstate_set_pstate(struct cpudata *cpu, int pstate)
1713 {
1714         trace_cpu_frequency(pstate * cpu->pstate.scaling, cpu->cpu);
1715         cpu->pstate.current_pstate = pstate;
1716         /*
1717          * Generally, there is no guarantee that this code will always run on
1718          * the CPU being updated, so force the register update to run on the
1719          * right CPU.
1720          */
1721         wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
1722                       pstate_funcs.get_val(cpu, pstate));
1723 }
1724
1725 static void intel_pstate_set_min_pstate(struct cpudata *cpu)
1726 {
1727         intel_pstate_set_pstate(cpu, cpu->pstate.min_pstate);
1728 }
1729
1730 static void intel_pstate_max_within_limits(struct cpudata *cpu)
1731 {
1732         int min_pstate, max_pstate;
1733
1734         update_turbo_state();
1735         intel_pstate_get_min_max(cpu, &min_pstate, &max_pstate);
1736         intel_pstate_set_pstate(cpu, max_pstate);
1737 }
1738
1739 static void intel_pstate_get_cpu_pstates(struct cpudata *cpu)
1740 {
1741         cpu->pstate.min_pstate = pstate_funcs.get_min();
1742         cpu->pstate.max_pstate = pstate_funcs.get_max();
1743         cpu->pstate.max_pstate_physical = pstate_funcs.get_max_physical();
1744         cpu->pstate.turbo_pstate = pstate_funcs.get_turbo();
1745         cpu->pstate.scaling = pstate_funcs.get_scaling();
1746         cpu->pstate.max_freq = cpu->pstate.max_pstate * cpu->pstate.scaling;
1747         cpu->pstate.turbo_freq = cpu->pstate.turbo_pstate * cpu->pstate.scaling;
1748
1749         if (pstate_funcs.get_vid)
1750                 pstate_funcs.get_vid(cpu);
1751
1752         intel_pstate_set_min_pstate(cpu);
1753 }
1754
1755 static inline void intel_pstate_calc_avg_perf(struct cpudata *cpu)
1756 {
1757         struct sample *sample = &cpu->sample;
1758
1759         sample->core_avg_perf = div_ext_fp(sample->aperf, sample->mperf);
1760 }
1761
1762 static inline bool intel_pstate_sample(struct cpudata *cpu, u64 time)
1763 {
1764         u64 aperf, mperf;
1765         unsigned long flags;
1766         u64 tsc;
1767
1768         local_irq_save(flags);
1769         rdmsrl(MSR_IA32_APERF, aperf);
1770         rdmsrl(MSR_IA32_MPERF, mperf);
1771         tsc = rdtsc();
1772         if (cpu->prev_mperf == mperf || cpu->prev_tsc == tsc) {
1773                 local_irq_restore(flags);
1774                 return false;
1775         }
1776         local_irq_restore(flags);
1777
1778         cpu->last_sample_time = cpu->sample.time;
1779         cpu->sample.time = time;
1780         cpu->sample.aperf = aperf;
1781         cpu->sample.mperf = mperf;
1782         cpu->sample.tsc =  tsc;
1783         cpu->sample.aperf -= cpu->prev_aperf;
1784         cpu->sample.mperf -= cpu->prev_mperf;
1785         cpu->sample.tsc -= cpu->prev_tsc;
1786
1787         cpu->prev_aperf = aperf;
1788         cpu->prev_mperf = mperf;
1789         cpu->prev_tsc = tsc;
1790         /*
1791          * First time this function is invoked in a given cycle, all of the
1792          * previous sample data fields are equal to zero or stale and they must
1793          * be populated with meaningful numbers for things to work, so assume
1794          * that sample.time will always be reset before setting the utilization
1795          * update hook and make the caller skip the sample then.
1796          */
1797         return !!cpu->last_sample_time;
1798 }
1799
1800 static inline int32_t get_avg_frequency(struct cpudata *cpu)
1801 {
1802         return mul_ext_fp(cpu->sample.core_avg_perf,
1803                           cpu->pstate.max_pstate_physical * cpu->pstate.scaling);
1804 }
1805
1806 static inline int32_t get_avg_pstate(struct cpudata *cpu)
1807 {
1808         return mul_ext_fp(cpu->pstate.max_pstate_physical,
1809                           cpu->sample.core_avg_perf);
1810 }
1811
1812 static inline int32_t get_target_pstate_use_cpu_load(struct cpudata *cpu)
1813 {
1814         struct sample *sample = &cpu->sample;
1815         int32_t busy_frac, boost;
1816         int target, avg_pstate;
1817
1818         busy_frac = div_fp(sample->mperf, sample->tsc);
1819
1820         boost = cpu->iowait_boost;
1821         cpu->iowait_boost >>= 1;
1822
1823         if (busy_frac < boost)
1824                 busy_frac = boost;
1825
1826         sample->busy_scaled = busy_frac * 100;
1827
1828         target = limits->no_turbo || limits->turbo_disabled ?
1829                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
1830         target += target >> 2;
1831         target = mul_fp(target, busy_frac);
1832         if (target < cpu->pstate.min_pstate)
1833                 target = cpu->pstate.min_pstate;
1834
1835         /*
1836          * If the average P-state during the previous cycle was higher than the
1837          * current target, add 50% of the difference to the target to reduce
1838          * possible performance oscillations and offset possible performance
1839          * loss related to moving the workload from one CPU to another within
1840          * a package/module.
1841          */
1842         avg_pstate = get_avg_pstate(cpu);
1843         if (avg_pstate > target)
1844                 target += (avg_pstate - target) >> 1;
1845
1846         return target;
1847 }
1848
1849 static inline int32_t get_target_pstate_use_performance(struct cpudata *cpu)
1850 {
1851         int32_t perf_scaled, max_pstate, current_pstate, sample_ratio;
1852         u64 duration_ns;
1853
1854         /*
1855          * perf_scaled is the ratio of the average P-state during the last
1856          * sampling period to the P-state requested last time (in percent).
1857          *
1858          * That measures the system's response to the previous P-state
1859          * selection.
1860          */
1861         max_pstate = cpu->pstate.max_pstate_physical;
1862         current_pstate = cpu->pstate.current_pstate;
1863         perf_scaled = mul_ext_fp(cpu->sample.core_avg_perf,
1864                                div_fp(100 * max_pstate, current_pstate));
1865
1866         /*
1867          * Since our utilization update callback will not run unless we are
1868          * in C0, check if the actual elapsed time is significantly greater (3x)
1869          * than our sample interval.  If it is, then we were idle for a long
1870          * enough period of time to adjust our performance metric.
1871          */
1872         duration_ns = cpu->sample.time - cpu->last_sample_time;
1873         if ((s64)duration_ns > pid_params.sample_rate_ns * 3) {
1874                 sample_ratio = div_fp(pid_params.sample_rate_ns, duration_ns);
1875                 perf_scaled = mul_fp(perf_scaled, sample_ratio);
1876         } else {
1877                 sample_ratio = div_fp(100 * cpu->sample.mperf, cpu->sample.tsc);
1878                 if (sample_ratio < int_tofp(1))
1879                         perf_scaled = 0;
1880         }
1881
1882         cpu->sample.busy_scaled = perf_scaled;
1883         return cpu->pstate.current_pstate - pid_calc(&cpu->pid, perf_scaled);
1884 }
1885
1886 static int intel_pstate_prepare_request(struct cpudata *cpu, int pstate)
1887 {
1888         int max_perf, min_perf;
1889
1890         intel_pstate_get_min_max(cpu, &min_perf, &max_perf);
1891         pstate = clamp_t(int, pstate, min_perf, max_perf);
1892         return pstate;
1893 }
1894
1895 static void intel_pstate_update_pstate(struct cpudata *cpu, int pstate)
1896 {
1897         if (pstate == cpu->pstate.current_pstate)
1898                 return;
1899
1900         cpu->pstate.current_pstate = pstate;
1901         wrmsrl(MSR_IA32_PERF_CTL, pstate_funcs.get_val(cpu, pstate));
1902 }
1903
1904 static inline void intel_pstate_adjust_busy_pstate(struct cpudata *cpu)
1905 {
1906         int from, target_pstate;
1907         struct sample *sample;
1908
1909         from = cpu->pstate.current_pstate;
1910
1911         target_pstate = cpu->policy == CPUFREQ_POLICY_PERFORMANCE ?
1912                 cpu->pstate.turbo_pstate : pstate_funcs.get_target_pstate(cpu);
1913
1914         update_turbo_state();
1915
1916         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
1917         trace_cpu_frequency(target_pstate * cpu->pstate.scaling, cpu->cpu);
1918         intel_pstate_update_pstate(cpu, target_pstate);
1919
1920         sample = &cpu->sample;
1921         trace_pstate_sample(mul_ext_fp(100, sample->core_avg_perf),
1922                 fp_toint(sample->busy_scaled),
1923                 from,
1924                 cpu->pstate.current_pstate,
1925                 sample->mperf,
1926                 sample->aperf,
1927                 sample->tsc,
1928                 get_avg_frequency(cpu),
1929                 fp_toint(cpu->iowait_boost * 100));
1930 }
1931
1932 static void intel_pstate_update_util(struct update_util_data *data, u64 time,
1933                                      unsigned int flags)
1934 {
1935         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
1936         u64 delta_ns;
1937
1938         if (pstate_funcs.get_target_pstate == get_target_pstate_use_cpu_load) {
1939                 if (flags & SCHED_CPUFREQ_IOWAIT) {
1940                         cpu->iowait_boost = int_tofp(1);
1941                 } else if (cpu->iowait_boost) {
1942                         /* Clear iowait_boost if the CPU may have been idle. */
1943                         delta_ns = time - cpu->last_update;
1944                         if (delta_ns > TICK_NSEC)
1945                                 cpu->iowait_boost = 0;
1946                 }
1947                 cpu->last_update = time;
1948         }
1949
1950         delta_ns = time - cpu->sample.time;
1951         if ((s64)delta_ns >= pid_params.sample_rate_ns) {
1952                 bool sample_taken = intel_pstate_sample(cpu, time);
1953
1954                 if (sample_taken) {
1955                         intel_pstate_calc_avg_perf(cpu);
1956                         if (!hwp_active)
1957                                 intel_pstate_adjust_busy_pstate(cpu);
1958                 }
1959         }
1960 }
1961
1962 #define ICPU(model, policy) \
1963         { X86_VENDOR_INTEL, 6, model, X86_FEATURE_APERFMPERF,\
1964                         (unsigned long)&policy }
1965
1966 static const struct x86_cpu_id intel_pstate_cpu_ids[] = {
1967         ICPU(INTEL_FAM6_SANDYBRIDGE,            core_params),
1968         ICPU(INTEL_FAM6_SANDYBRIDGE_X,          core_params),
1969         ICPU(INTEL_FAM6_ATOM_SILVERMONT1,       silvermont_params),
1970         ICPU(INTEL_FAM6_IVYBRIDGE,              core_params),
1971         ICPU(INTEL_FAM6_HASWELL_CORE,           core_params),
1972         ICPU(INTEL_FAM6_BROADWELL_CORE,         core_params),
1973         ICPU(INTEL_FAM6_IVYBRIDGE_X,            core_params),
1974         ICPU(INTEL_FAM6_HASWELL_X,              core_params),
1975         ICPU(INTEL_FAM6_HASWELL_ULT,            core_params),
1976         ICPU(INTEL_FAM6_HASWELL_GT3E,           core_params),
1977         ICPU(INTEL_FAM6_BROADWELL_GT3E,         core_params),
1978         ICPU(INTEL_FAM6_ATOM_AIRMONT,           airmont_params),
1979         ICPU(INTEL_FAM6_SKYLAKE_MOBILE,         core_params),
1980         ICPU(INTEL_FAM6_BROADWELL_X,            core_params),
1981         ICPU(INTEL_FAM6_SKYLAKE_DESKTOP,        core_params),
1982         ICPU(INTEL_FAM6_BROADWELL_XEON_D,       core_params),
1983         ICPU(INTEL_FAM6_XEON_PHI_KNL,           knl_params),
1984         ICPU(INTEL_FAM6_XEON_PHI_KNM,           knl_params),
1985         ICPU(INTEL_FAM6_ATOM_GOLDMONT,          bxt_params),
1986         {}
1987 };
1988 MODULE_DEVICE_TABLE(x86cpu, intel_pstate_cpu_ids);
1989
1990 static const struct x86_cpu_id intel_pstate_cpu_oob_ids[] __initconst = {
1991         ICPU(INTEL_FAM6_BROADWELL_XEON_D, core_params),
1992         ICPU(INTEL_FAM6_BROADWELL_X, core_params),
1993         ICPU(INTEL_FAM6_SKYLAKE_X, core_params),
1994         {}
1995 };
1996
1997 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[] = {
1998         ICPU(INTEL_FAM6_KABYLAKE_DESKTOP, core_params),
1999         {}
2000 };
2001
2002 static int intel_pstate_init_cpu(unsigned int cpunum)
2003 {
2004         struct cpudata *cpu;
2005
2006         cpu = all_cpu_data[cpunum];
2007
2008         if (!cpu) {
2009                 unsigned int size = sizeof(struct cpudata);
2010
2011                 if (per_cpu_limits)
2012                         size += sizeof(struct perf_limits);
2013
2014                 cpu = kzalloc(size, GFP_KERNEL);
2015                 if (!cpu)
2016                         return -ENOMEM;
2017
2018                 all_cpu_data[cpunum] = cpu;
2019                 if (per_cpu_limits)
2020                         cpu->perf_limits = (struct perf_limits *)(cpu + 1);
2021
2022                 cpu->epp_default = -EINVAL;
2023                 cpu->epp_powersave = -EINVAL;
2024                 cpu->epp_saved = -EINVAL;
2025         }
2026
2027         cpu = all_cpu_data[cpunum];
2028
2029         cpu->cpu = cpunum;
2030
2031         if (hwp_active) {
2032                 const struct x86_cpu_id *id;
2033
2034                 id = x86_match_cpu(intel_pstate_cpu_ee_disable_ids);
2035                 if (id)
2036                         intel_pstate_disable_ee(cpunum);
2037
2038                 intel_pstate_hwp_enable(cpu);
2039                 pid_params.sample_rate_ms = 50;
2040                 pid_params.sample_rate_ns = 50 * NSEC_PER_MSEC;
2041         }
2042
2043         intel_pstate_get_cpu_pstates(cpu);
2044
2045         intel_pstate_busy_pid_reset(cpu);
2046
2047         pr_debug("controlling: cpu %d\n", cpunum);
2048
2049         return 0;
2050 }
2051
2052 static unsigned int intel_pstate_get(unsigned int cpu_num)
2053 {
2054         struct cpudata *cpu = all_cpu_data[cpu_num];
2055
2056         return cpu ? get_avg_frequency(cpu) : 0;
2057 }
2058
2059 static void intel_pstate_set_update_util_hook(unsigned int cpu_num)
2060 {
2061         struct cpudata *cpu = all_cpu_data[cpu_num];
2062
2063         if (cpu->update_util_set)
2064                 return;
2065
2066         /* Prevent intel_pstate_update_util() from using stale data. */
2067         cpu->sample.time = 0;
2068         cpufreq_add_update_util_hook(cpu_num, &cpu->update_util,
2069                                      intel_pstate_update_util);
2070         cpu->update_util_set = true;
2071 }
2072
2073 static void intel_pstate_clear_update_util_hook(unsigned int cpu)
2074 {
2075         struct cpudata *cpu_data = all_cpu_data[cpu];
2076
2077         if (!cpu_data->update_util_set)
2078                 return;
2079
2080         cpufreq_remove_update_util_hook(cpu);
2081         cpu_data->update_util_set = false;
2082         synchronize_sched();
2083 }
2084
2085 static void intel_pstate_update_perf_limits(struct cpufreq_policy *policy,
2086                                             struct perf_limits *limits)
2087 {
2088
2089         limits->max_policy_pct = DIV_ROUND_UP(policy->max * 100,
2090                                               policy->cpuinfo.max_freq);
2091         limits->max_policy_pct = clamp_t(int, limits->max_policy_pct, 0, 100);
2092         if (policy->max == policy->min) {
2093                 limits->min_policy_pct = limits->max_policy_pct;
2094         } else {
2095                 limits->min_policy_pct = DIV_ROUND_UP(policy->min * 100,
2096                                                       policy->cpuinfo.max_freq);
2097                 limits->min_policy_pct = clamp_t(int, limits->min_policy_pct,
2098                                                  0, 100);
2099         }
2100
2101         /* Normalize user input to [min_policy_pct, max_policy_pct] */
2102         limits->min_perf_pct = max(limits->min_policy_pct,
2103                                    limits->min_sysfs_pct);
2104         limits->min_perf_pct = min(limits->max_policy_pct,
2105                                    limits->min_perf_pct);
2106         limits->max_perf_pct = min(limits->max_policy_pct,
2107                                    limits->max_sysfs_pct);
2108         limits->max_perf_pct = max(limits->min_policy_pct,
2109                                    limits->max_perf_pct);
2110
2111         /* Make sure min_perf_pct <= max_perf_pct */
2112         limits->min_perf_pct = min(limits->max_perf_pct, limits->min_perf_pct);
2113
2114         limits->min_perf = div_ext_fp(limits->min_perf_pct, 100);
2115         limits->max_perf = div_ext_fp(limits->max_perf_pct, 100);
2116         limits->max_perf = round_up(limits->max_perf, EXT_FRAC_BITS);
2117         limits->min_perf = round_up(limits->min_perf, EXT_FRAC_BITS);
2118
2119         pr_debug("cpu:%d max_perf_pct:%d min_perf_pct:%d\n", policy->cpu,
2120                  limits->max_perf_pct, limits->min_perf_pct);
2121 }
2122
2123 static int intel_pstate_set_policy(struct cpufreq_policy *policy)
2124 {
2125         struct cpudata *cpu;
2126         struct perf_limits *perf_limits = NULL;
2127
2128         if (!policy->cpuinfo.max_freq)
2129                 return -ENODEV;
2130
2131         pr_debug("set_policy cpuinfo.max %u policy->max %u\n",
2132                  policy->cpuinfo.max_freq, policy->max);
2133
2134         cpu = all_cpu_data[policy->cpu];
2135         cpu->policy = policy->policy;
2136
2137         if (cpu->pstate.max_pstate_physical > cpu->pstate.max_pstate &&
2138             policy->max < policy->cpuinfo.max_freq &&
2139             policy->max > cpu->pstate.max_pstate * cpu->pstate.scaling) {
2140                 pr_debug("policy->max > max non turbo frequency\n");
2141                 policy->max = policy->cpuinfo.max_freq;
2142         }
2143
2144         if (per_cpu_limits)
2145                 perf_limits = cpu->perf_limits;
2146
2147         mutex_lock(&intel_pstate_limits_lock);
2148
2149         if (policy->policy == CPUFREQ_POLICY_PERFORMANCE) {
2150                 pr_debug("set performance\n");
2151                 if (!perf_limits) {
2152                         limits = &performance_limits;
2153                         perf_limits = limits;
2154                 }
2155         } else {
2156                 pr_debug("set powersave\n");
2157                 if (!perf_limits) {
2158                         limits = &powersave_limits;
2159                         perf_limits = limits;
2160                 }
2161
2162         }
2163
2164         intel_pstate_update_perf_limits(policy, perf_limits);
2165
2166         if (cpu->policy == CPUFREQ_POLICY_PERFORMANCE) {
2167                 /*
2168                  * NOHZ_FULL CPUs need this as the governor callback may not
2169                  * be invoked on them.
2170                  */
2171                 intel_pstate_clear_update_util_hook(policy->cpu);
2172                 intel_pstate_max_within_limits(cpu);
2173         }
2174
2175         intel_pstate_set_update_util_hook(policy->cpu);
2176
2177         intel_pstate_hwp_set_policy(policy);
2178
2179         mutex_unlock(&intel_pstate_limits_lock);
2180
2181         return 0;
2182 }
2183
2184 static int intel_pstate_verify_policy(struct cpufreq_policy *policy)
2185 {
2186         struct cpudata *cpu = all_cpu_data[policy->cpu];
2187         struct perf_limits *perf_limits;
2188
2189         if (policy->policy == CPUFREQ_POLICY_PERFORMANCE)
2190                 perf_limits = &performance_limits;
2191         else
2192                 perf_limits = &powersave_limits;
2193
2194         update_turbo_state();
2195         policy->cpuinfo.max_freq = perf_limits->turbo_disabled ||
2196                                         perf_limits->no_turbo ?
2197                                         cpu->pstate.max_freq :
2198                                         cpu->pstate.turbo_freq;
2199
2200         cpufreq_verify_within_cpu_limits(policy);
2201
2202         if (policy->policy != CPUFREQ_POLICY_POWERSAVE &&
2203             policy->policy != CPUFREQ_POLICY_PERFORMANCE)
2204                 return -EINVAL;
2205
2206         /* When per-CPU limits are used, sysfs limits are not used */
2207         if (!per_cpu_limits) {
2208                 unsigned int max_freq, min_freq;
2209
2210                 max_freq = policy->cpuinfo.max_freq *
2211                                         perf_limits->max_sysfs_pct / 100;
2212                 min_freq = policy->cpuinfo.max_freq *
2213                                         perf_limits->min_sysfs_pct / 100;
2214                 cpufreq_verify_within_limits(policy, min_freq, max_freq);
2215         }
2216
2217         return 0;
2218 }
2219
2220 static void intel_cpufreq_stop_cpu(struct cpufreq_policy *policy)
2221 {
2222         intel_pstate_set_min_pstate(all_cpu_data[policy->cpu]);
2223 }
2224
2225 static void intel_pstate_stop_cpu(struct cpufreq_policy *policy)
2226 {
2227         pr_debug("CPU %d exiting\n", policy->cpu);
2228
2229         intel_pstate_clear_update_util_hook(policy->cpu);
2230         if (hwp_active)
2231                 intel_pstate_hwp_save_state(policy);
2232         else
2233                 intel_cpufreq_stop_cpu(policy);
2234 }
2235
2236 static int intel_pstate_cpu_exit(struct cpufreq_policy *policy)
2237 {
2238         intel_pstate_exit_perf_limits(policy);
2239
2240         policy->fast_switch_possible = false;
2241
2242         return 0;
2243 }
2244
2245 static int __intel_pstate_cpu_init(struct cpufreq_policy *policy)
2246 {
2247         struct cpudata *cpu;
2248         int rc;
2249
2250         rc = intel_pstate_init_cpu(policy->cpu);
2251         if (rc)
2252                 return rc;
2253
2254         cpu = all_cpu_data[policy->cpu];
2255
2256         if (per_cpu_limits)
2257                 intel_pstate_init_limits(cpu->perf_limits);
2258
2259         policy->min = cpu->pstate.min_pstate * cpu->pstate.scaling;
2260         policy->max = cpu->pstate.turbo_pstate * cpu->pstate.scaling;
2261
2262         /* cpuinfo and default policy values */
2263         policy->cpuinfo.min_freq = cpu->pstate.min_pstate * cpu->pstate.scaling;
2264         update_turbo_state();
2265         policy->cpuinfo.max_freq = limits->turbo_disabled ?
2266                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
2267         policy->cpuinfo.max_freq *= cpu->pstate.scaling;
2268
2269         intel_pstate_init_acpi_perf_limits(policy);
2270         cpumask_set_cpu(policy->cpu, policy->cpus);
2271
2272         policy->fast_switch_possible = true;
2273
2274         return 0;
2275 }
2276
2277 static int intel_pstate_cpu_init(struct cpufreq_policy *policy)
2278 {
2279         int ret = __intel_pstate_cpu_init(policy);
2280
2281         if (ret)
2282                 return ret;
2283
2284         policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL;
2285         if (limits->min_perf_pct == 100 && limits->max_perf_pct == 100)
2286                 policy->policy = CPUFREQ_POLICY_PERFORMANCE;
2287         else
2288                 policy->policy = CPUFREQ_POLICY_POWERSAVE;
2289
2290         return 0;
2291 }
2292
2293 static struct cpufreq_driver intel_pstate = {
2294         .flags          = CPUFREQ_CONST_LOOPS,
2295         .verify         = intel_pstate_verify_policy,
2296         .setpolicy      = intel_pstate_set_policy,
2297         .suspend        = intel_pstate_hwp_save_state,
2298         .resume         = intel_pstate_resume,
2299         .get            = intel_pstate_get,
2300         .init           = intel_pstate_cpu_init,
2301         .exit           = intel_pstate_cpu_exit,
2302         .stop_cpu       = intel_pstate_stop_cpu,
2303         .name           = "intel_pstate",
2304 };
2305
2306 static int intel_cpufreq_verify_policy(struct cpufreq_policy *policy)
2307 {
2308         struct cpudata *cpu = all_cpu_data[policy->cpu];
2309
2310         update_turbo_state();
2311         policy->cpuinfo.max_freq = limits->turbo_disabled ?
2312                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2313
2314         cpufreq_verify_within_cpu_limits(policy);
2315
2316         return 0;
2317 }
2318
2319 static unsigned int intel_cpufreq_turbo_update(struct cpudata *cpu,
2320                                                struct cpufreq_policy *policy,
2321                                                unsigned int target_freq)
2322 {
2323         unsigned int max_freq;
2324
2325         update_turbo_state();
2326
2327         max_freq = limits->no_turbo || limits->turbo_disabled ?
2328                         cpu->pstate.max_freq : cpu->pstate.turbo_freq;
2329         policy->cpuinfo.max_freq = max_freq;
2330         if (policy->max > max_freq)
2331                 policy->max = max_freq;
2332
2333         if (target_freq > max_freq)
2334                 target_freq = max_freq;
2335
2336         return target_freq;
2337 }
2338
2339 static int intel_cpufreq_target(struct cpufreq_policy *policy,
2340                                 unsigned int target_freq,
2341                                 unsigned int relation)
2342 {
2343         struct cpudata *cpu = all_cpu_data[policy->cpu];
2344         struct cpufreq_freqs freqs;
2345         int target_pstate;
2346
2347         freqs.old = policy->cur;
2348         freqs.new = intel_cpufreq_turbo_update(cpu, policy, target_freq);
2349
2350         cpufreq_freq_transition_begin(policy, &freqs);
2351         switch (relation) {
2352         case CPUFREQ_RELATION_L:
2353                 target_pstate = DIV_ROUND_UP(freqs.new, cpu->pstate.scaling);
2354                 break;
2355         case CPUFREQ_RELATION_H:
2356                 target_pstate = freqs.new / cpu->pstate.scaling;
2357                 break;
2358         default:
2359                 target_pstate = DIV_ROUND_CLOSEST(freqs.new, cpu->pstate.scaling);
2360                 break;
2361         }
2362         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2363         if (target_pstate != cpu->pstate.current_pstate) {
2364                 cpu->pstate.current_pstate = target_pstate;
2365                 wrmsrl_on_cpu(policy->cpu, MSR_IA32_PERF_CTL,
2366                               pstate_funcs.get_val(cpu, target_pstate));
2367         }
2368         freqs.new = target_pstate * cpu->pstate.scaling;
2369         cpufreq_freq_transition_end(policy, &freqs, false);
2370
2371         return 0;
2372 }
2373
2374 static unsigned int intel_cpufreq_fast_switch(struct cpufreq_policy *policy,
2375                                               unsigned int target_freq)
2376 {
2377         struct cpudata *cpu = all_cpu_data[policy->cpu];
2378         int target_pstate;
2379
2380         target_freq = intel_cpufreq_turbo_update(cpu, policy, target_freq);
2381         target_pstate = DIV_ROUND_UP(target_freq, cpu->pstate.scaling);
2382         target_pstate = intel_pstate_prepare_request(cpu, target_pstate);
2383         intel_pstate_update_pstate(cpu, target_pstate);
2384         return target_pstate * cpu->pstate.scaling;
2385 }
2386
2387 static int intel_cpufreq_cpu_init(struct cpufreq_policy *policy)
2388 {
2389         int ret = __intel_pstate_cpu_init(policy);
2390
2391         if (ret)
2392                 return ret;
2393
2394         policy->cpuinfo.transition_latency = INTEL_CPUFREQ_TRANSITION_LATENCY;
2395         /* This reflects the intel_pstate_get_cpu_pstates() setting. */
2396         policy->cur = policy->cpuinfo.min_freq;
2397
2398         return 0;
2399 }
2400
2401 static struct cpufreq_driver intel_cpufreq = {
2402         .flags          = CPUFREQ_CONST_LOOPS,
2403         .verify         = intel_cpufreq_verify_policy,
2404         .target         = intel_cpufreq_target,
2405         .fast_switch    = intel_cpufreq_fast_switch,
2406         .init           = intel_cpufreq_cpu_init,
2407         .exit           = intel_pstate_cpu_exit,
2408         .stop_cpu       = intel_cpufreq_stop_cpu,
2409         .name           = "intel_cpufreq",
2410 };
2411
2412 static struct cpufreq_driver *intel_pstate_driver = &intel_pstate;
2413
2414 static void intel_pstate_driver_cleanup(void)
2415 {
2416         unsigned int cpu;
2417
2418         get_online_cpus();
2419         for_each_online_cpu(cpu) {
2420                 if (all_cpu_data[cpu]) {
2421                         if (intel_pstate_driver == &intel_pstate)
2422                                 intel_pstate_clear_update_util_hook(cpu);
2423
2424                         kfree(all_cpu_data[cpu]);
2425                         all_cpu_data[cpu] = NULL;
2426                 }
2427         }
2428         put_online_cpus();
2429 }
2430
2431 static int intel_pstate_register_driver(void)
2432 {
2433         int ret;
2434
2435         intel_pstate_init_limits(&powersave_limits);
2436         intel_pstate_set_performance_limits(&performance_limits);
2437         if (IS_ENABLED(CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE) &&
2438             intel_pstate_driver == &intel_pstate)
2439                 limits = &performance_limits;
2440         else
2441                 limits = &powersave_limits;
2442
2443         ret = cpufreq_register_driver(intel_pstate_driver);
2444         if (ret) {
2445                 intel_pstate_driver_cleanup();
2446                 return ret;
2447         }
2448
2449         mutex_lock(&intel_pstate_limits_lock);
2450         driver_registered = true;
2451         mutex_unlock(&intel_pstate_limits_lock);
2452
2453         if (intel_pstate_driver == &intel_pstate && !hwp_active &&
2454             pstate_funcs.get_target_pstate != get_target_pstate_use_cpu_load)
2455                 intel_pstate_debug_expose_params();
2456
2457         return 0;
2458 }
2459
2460 static int intel_pstate_unregister_driver(void)
2461 {
2462         if (hwp_active)
2463                 return -EBUSY;
2464
2465         if (intel_pstate_driver == &intel_pstate && !hwp_active &&
2466             pstate_funcs.get_target_pstate != get_target_pstate_use_cpu_load)
2467                 intel_pstate_debug_hide_params();
2468
2469         mutex_lock(&intel_pstate_limits_lock);
2470         driver_registered = false;
2471         mutex_unlock(&intel_pstate_limits_lock);
2472
2473         cpufreq_unregister_driver(intel_pstate_driver);
2474         intel_pstate_driver_cleanup();
2475
2476         return 0;
2477 }
2478
2479 static ssize_t intel_pstate_show_status(char *buf)
2480 {
2481         if (!driver_registered)
2482                 return sprintf(buf, "off\n");
2483
2484         return sprintf(buf, "%s\n", intel_pstate_driver == &intel_pstate ?
2485                                         "active" : "passive");
2486 }
2487
2488 static int intel_pstate_update_status(const char *buf, size_t size)
2489 {
2490         int ret;
2491
2492         if (size == 3 && !strncmp(buf, "off", size))
2493                 return driver_registered ?
2494                         intel_pstate_unregister_driver() : -EINVAL;
2495
2496         if (size == 6 && !strncmp(buf, "active", size)) {
2497                 if (driver_registered) {
2498                         if (intel_pstate_driver == &intel_pstate)
2499                                 return 0;
2500
2501                         ret = intel_pstate_unregister_driver();
2502                         if (ret)
2503                                 return ret;
2504                 }
2505
2506                 intel_pstate_driver = &intel_pstate;
2507                 return intel_pstate_register_driver();
2508         }
2509
2510         if (size == 7 && !strncmp(buf, "passive", size)) {
2511                 if (driver_registered) {
2512                         if (intel_pstate_driver != &intel_pstate)
2513                                 return 0;
2514
2515                         ret = intel_pstate_unregister_driver();
2516                         if (ret)
2517                                 return ret;
2518                 }
2519
2520                 intel_pstate_driver = &intel_cpufreq;
2521                 return intel_pstate_register_driver();
2522         }
2523
2524         return -EINVAL;
2525 }
2526
2527 static int no_load __initdata;
2528 static int no_hwp __initdata;
2529 static int hwp_only __initdata;
2530 static unsigned int force_load __initdata;
2531
2532 static int __init intel_pstate_msrs_not_valid(void)
2533 {
2534         if (!pstate_funcs.get_max() ||
2535             !pstate_funcs.get_min() ||
2536             !pstate_funcs.get_turbo())
2537                 return -ENODEV;
2538
2539         return 0;
2540 }
2541
2542 static void __init copy_pid_params(struct pstate_adjust_policy *policy)
2543 {
2544         pid_params.sample_rate_ms = policy->sample_rate_ms;
2545         pid_params.sample_rate_ns = pid_params.sample_rate_ms * NSEC_PER_MSEC;
2546         pid_params.p_gain_pct = policy->p_gain_pct;
2547         pid_params.i_gain_pct = policy->i_gain_pct;
2548         pid_params.d_gain_pct = policy->d_gain_pct;
2549         pid_params.deadband = policy->deadband;
2550         pid_params.setpoint = policy->setpoint;
2551 }
2552
2553 #ifdef CONFIG_ACPI
2554 static void intel_pstate_use_acpi_profile(void)
2555 {
2556         if (acpi_gbl_FADT.preferred_profile == PM_MOBILE)
2557                 pstate_funcs.get_target_pstate =
2558                                 get_target_pstate_use_cpu_load;
2559 }
2560 #else
2561 static void intel_pstate_use_acpi_profile(void)
2562 {
2563 }
2564 #endif
2565
2566 static void __init copy_cpu_funcs(struct pstate_funcs *funcs)
2567 {
2568         pstate_funcs.get_max   = funcs->get_max;
2569         pstate_funcs.get_max_physical = funcs->get_max_physical;
2570         pstate_funcs.get_min   = funcs->get_min;
2571         pstate_funcs.get_turbo = funcs->get_turbo;
2572         pstate_funcs.get_scaling = funcs->get_scaling;
2573         pstate_funcs.get_val   = funcs->get_val;
2574         pstate_funcs.get_vid   = funcs->get_vid;
2575         pstate_funcs.get_target_pstate = funcs->get_target_pstate;
2576
2577         intel_pstate_use_acpi_profile();
2578 }
2579
2580 #ifdef CONFIG_ACPI
2581
2582 static bool __init intel_pstate_no_acpi_pss(void)
2583 {
2584         int i;
2585
2586         for_each_possible_cpu(i) {
2587                 acpi_status status;
2588                 union acpi_object *pss;
2589                 struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
2590                 struct acpi_processor *pr = per_cpu(processors, i);
2591
2592                 if (!pr)
2593                         continue;
2594
2595                 status = acpi_evaluate_object(pr->handle, "_PSS", NULL, &buffer);
2596                 if (ACPI_FAILURE(status))
2597                         continue;
2598
2599                 pss = buffer.pointer;
2600                 if (pss && pss->type == ACPI_TYPE_PACKAGE) {
2601                         kfree(pss);
2602                         return false;
2603                 }
2604
2605                 kfree(pss);
2606         }
2607
2608         return true;
2609 }
2610
2611 static bool __init intel_pstate_has_acpi_ppc(void)
2612 {
2613         int i;
2614
2615         for_each_possible_cpu(i) {
2616                 struct acpi_processor *pr = per_cpu(processors, i);
2617
2618                 if (!pr)
2619                         continue;
2620                 if (acpi_has_method(pr->handle, "_PPC"))
2621                         return true;
2622         }
2623         return false;
2624 }
2625
2626 enum {
2627         PSS,
2628         PPC,
2629 };
2630
2631 struct hw_vendor_info {
2632         u16  valid;
2633         char oem_id[ACPI_OEM_ID_SIZE];
2634         char oem_table_id[ACPI_OEM_TABLE_ID_SIZE];
2635         int  oem_pwr_table;
2636 };
2637
2638 /* Hardware vendor-specific info that has its own power management modes */
2639 static struct hw_vendor_info vendor_info[] __initdata = {
2640         {1, "HP    ", "ProLiant", PSS},
2641         {1, "ORACLE", "X4-2    ", PPC},
2642         {1, "ORACLE", "X4-2L   ", PPC},
2643         {1, "ORACLE", "X4-2B   ", PPC},
2644         {1, "ORACLE", "X3-2    ", PPC},
2645         {1, "ORACLE", "X3-2L   ", PPC},
2646         {1, "ORACLE", "X3-2B   ", PPC},
2647         {1, "ORACLE", "X4470M2 ", PPC},
2648         {1, "ORACLE", "X4270M3 ", PPC},
2649         {1, "ORACLE", "X4270M2 ", PPC},
2650         {1, "ORACLE", "X4170M2 ", PPC},
2651         {1, "ORACLE", "X4170 M3", PPC},
2652         {1, "ORACLE", "X4275 M3", PPC},
2653         {1, "ORACLE", "X6-2    ", PPC},
2654         {1, "ORACLE", "Sudbury ", PPC},
2655         {0, "", ""},
2656 };
2657
2658 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
2659 {
2660         struct acpi_table_header hdr;
2661         struct hw_vendor_info *v_info;
2662         const struct x86_cpu_id *id;
2663         u64 misc_pwr;
2664
2665         id = x86_match_cpu(intel_pstate_cpu_oob_ids);
2666         if (id) {
2667                 rdmsrl(MSR_MISC_PWR_MGMT, misc_pwr);
2668                 if ( misc_pwr & (1 << 8))
2669                         return true;
2670         }
2671
2672         if (acpi_disabled ||
2673             ACPI_FAILURE(acpi_get_table_header(ACPI_SIG_FADT, 0, &hdr)))
2674                 return false;
2675
2676         for (v_info = vendor_info; v_info->valid; v_info++) {
2677                 if (!strncmp(hdr.oem_id, v_info->oem_id, ACPI_OEM_ID_SIZE) &&
2678                         !strncmp(hdr.oem_table_id, v_info->oem_table_id,
2679                                                 ACPI_OEM_TABLE_ID_SIZE))
2680                         switch (v_info->oem_pwr_table) {
2681                         case PSS:
2682                                 return intel_pstate_no_acpi_pss();
2683                         case PPC:
2684                                 return intel_pstate_has_acpi_ppc() &&
2685                                         (!force_load);
2686                         }
2687         }
2688
2689         return false;
2690 }
2691
2692 static void intel_pstate_request_control_from_smm(void)
2693 {
2694         /*
2695          * It may be unsafe to request P-states control from SMM if _PPC support
2696          * has not been enabled.
2697          */
2698         if (acpi_ppc)
2699                 acpi_processor_pstate_control();
2700 }
2701 #else /* CONFIG_ACPI not enabled */
2702 static inline bool intel_pstate_platform_pwr_mgmt_exists(void) { return false; }
2703 static inline bool intel_pstate_has_acpi_ppc(void) { return false; }
2704 static inline void intel_pstate_request_control_from_smm(void) {}
2705 #endif /* CONFIG_ACPI */
2706
2707 static const struct x86_cpu_id hwp_support_ids[] __initconst = {
2708         { X86_VENDOR_INTEL, 6, X86_MODEL_ANY, X86_FEATURE_HWP },
2709         {}
2710 };
2711
2712 static int __init intel_pstate_init(void)
2713 {
2714         const struct x86_cpu_id *id;
2715         struct cpu_defaults *cpu_def;
2716         int rc = 0;
2717
2718         if (no_load)
2719                 return -ENODEV;
2720
2721         if (x86_match_cpu(hwp_support_ids) && !no_hwp) {
2722                 copy_cpu_funcs(&core_params.funcs);
2723                 hwp_active++;
2724                 intel_pstate.attr = hwp_cpufreq_attrs;
2725                 goto hwp_cpu_matched;
2726         }
2727
2728         id = x86_match_cpu(intel_pstate_cpu_ids);
2729         if (!id)
2730                 return -ENODEV;
2731
2732         cpu_def = (struct cpu_defaults *)id->driver_data;
2733
2734         copy_pid_params(&cpu_def->pid_policy);
2735         copy_cpu_funcs(&cpu_def->funcs);
2736
2737         if (intel_pstate_msrs_not_valid())
2738                 return -ENODEV;
2739
2740 hwp_cpu_matched:
2741         /*
2742          * The Intel pstate driver will be ignored if the platform
2743          * firmware has its own power management modes.
2744          */
2745         if (intel_pstate_platform_pwr_mgmt_exists())
2746                 return -ENODEV;
2747
2748         if (!hwp_active && hwp_only)
2749                 return -ENOTSUPP;
2750
2751         pr_info("Intel P-state driver initializing\n");
2752
2753         all_cpu_data = vzalloc(sizeof(void *) * num_possible_cpus());
2754         if (!all_cpu_data)
2755                 return -ENOMEM;
2756
2757         intel_pstate_request_control_from_smm();
2758
2759         intel_pstate_sysfs_expose_params();
2760
2761         mutex_lock(&intel_pstate_driver_lock);
2762         rc = intel_pstate_register_driver();
2763         mutex_unlock(&intel_pstate_driver_lock);
2764         if (rc)
2765                 return rc;
2766
2767         if (hwp_active)
2768                 pr_info("HWP enabled\n");
2769
2770         return 0;
2771 }
2772 device_initcall(intel_pstate_init);
2773
2774 static int __init intel_pstate_setup(char *str)
2775 {
2776         if (!str)
2777                 return -EINVAL;
2778
2779         if (!strcmp(str, "disable")) {
2780                 no_load = 1;
2781         } else if (!strcmp(str, "passive")) {
2782                 pr_info("Passive mode enabled\n");
2783                 intel_pstate_driver = &intel_cpufreq;
2784                 no_hwp = 1;
2785         }
2786         if (!strcmp(str, "no_hwp")) {
2787                 pr_info("HWP disabled\n");
2788                 no_hwp = 1;
2789         }
2790         if (!strcmp(str, "force"))
2791                 force_load = 1;
2792         if (!strcmp(str, "hwp_only"))
2793                 hwp_only = 1;
2794         if (!strcmp(str, "per_cpu_perf_limits"))
2795                 per_cpu_limits = true;
2796
2797 #ifdef CONFIG_ACPI
2798         if (!strcmp(str, "support_acpi_ppc"))
2799                 acpi_ppc = true;
2800 #endif
2801
2802         return 0;
2803 }
2804 early_param("intel_pstate", intel_pstate_setup);
2805
2806 MODULE_AUTHOR("Dirk Brandewie <dirk.j.brandewie@intel.com>");
2807 MODULE_DESCRIPTION("'intel_pstate' - P state driver Intel Core processors");
2808 MODULE_LICENSE("GPL");