GNU Linux-libre 4.9.318-gnu1
[releases.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 ATOM_RATIOS             0x66a
41 #define ATOM_VIDS               0x66b
42 #define ATOM_TURBO_RATIOS       0x66c
43 #define ATOM_TURBO_VIDS         0x66d
44
45 #ifdef CONFIG_ACPI
46 #include <acpi/processor.h>
47 #endif
48
49 #define FRAC_BITS 8
50 #define int_tofp(X) ((int64_t)(X) << FRAC_BITS)
51 #define fp_toint(X) ((X) >> FRAC_BITS)
52
53 #define EXT_BITS 6
54 #define EXT_FRAC_BITS (EXT_BITS + FRAC_BITS)
55
56 static inline int32_t mul_fp(int32_t x, int32_t y)
57 {
58         return ((int64_t)x * (int64_t)y) >> FRAC_BITS;
59 }
60
61 static inline int32_t div_fp(s64 x, s64 y)
62 {
63         return div64_s64((int64_t)x << FRAC_BITS, y);
64 }
65
66 static inline int ceiling_fp(int32_t x)
67 {
68         int mask, ret;
69
70         ret = fp_toint(x);
71         mask = (1 << FRAC_BITS) - 1;
72         if (x & mask)
73                 ret += 1;
74         return ret;
75 }
76
77 static inline u64 mul_ext_fp(u64 x, u64 y)
78 {
79         return (x * y) >> EXT_FRAC_BITS;
80 }
81
82 static inline u64 div_ext_fp(u64 x, u64 y)
83 {
84         return div64_u64(x << EXT_FRAC_BITS, y);
85 }
86
87 /**
88  * struct sample -      Store performance sample
89  * @core_avg_perf:      Ratio of APERF/MPERF which is the actual average
90  *                      performance during last sample period
91  * @busy_scaled:        Scaled busy value which is used to calculate next
92  *                      P state. This can be different than core_avg_perf
93  *                      to account for cpu idle period
94  * @aperf:              Difference of actual performance frequency clock count
95  *                      read from APERF MSR between last and current sample
96  * @mperf:              Difference of maximum performance frequency clock count
97  *                      read from MPERF MSR between last and current sample
98  * @tsc:                Difference of time stamp counter between last and
99  *                      current sample
100  * @time:               Current time from scheduler
101  *
102  * This structure is used in the cpudata structure to store performance sample
103  * data for choosing next P State.
104  */
105 struct sample {
106         int32_t core_avg_perf;
107         int32_t busy_scaled;
108         u64 aperf;
109         u64 mperf;
110         u64 tsc;
111         u64 time;
112 };
113
114 /**
115  * struct pstate_data - Store P state data
116  * @current_pstate:     Current requested P state
117  * @min_pstate:         Min P state possible for this platform
118  * @max_pstate:         Max P state possible for this platform
119  * @max_pstate_physical:This is physical Max P state for a processor
120  *                      This can be higher than the max_pstate which can
121  *                      be limited by platform thermal design power limits
122  * @scaling:            Scaling factor to  convert frequency to cpufreq
123  *                      frequency units
124  * @turbo_pstate:       Max Turbo P state possible for this platform
125  *
126  * Stores the per cpu model P state limits and current P state.
127  */
128 struct pstate_data {
129         int     current_pstate;
130         int     min_pstate;
131         int     max_pstate;
132         int     max_pstate_physical;
133         int     scaling;
134         int     turbo_pstate;
135 };
136
137 /**
138  * struct vid_data -    Stores voltage information data
139  * @min:                VID data for this platform corresponding to
140  *                      the lowest P state
141  * @max:                VID data corresponding to the highest P State.
142  * @turbo:              VID data for turbo P state
143  * @ratio:              Ratio of (vid max - vid min) /
144  *                      (max P state - Min P State)
145  *
146  * Stores the voltage data for DVFS (Dynamic Voltage and Frequency Scaling)
147  * This data is used in Atom platforms, where in addition to target P state,
148  * the voltage data needs to be specified to select next P State.
149  */
150 struct vid_data {
151         int min;
152         int max;
153         int turbo;
154         int32_t ratio;
155 };
156
157 /**
158  * struct _pid -        Stores PID data
159  * @setpoint:           Target set point for busyness or performance
160  * @integral:           Storage for accumulated error values
161  * @p_gain:             PID proportional gain
162  * @i_gain:             PID integral gain
163  * @d_gain:             PID derivative gain
164  * @deadband:           PID deadband
165  * @last_err:           Last error storage for integral part of PID calculation
166  *
167  * Stores PID coefficients and last error for PID controller.
168  */
169 struct _pid {
170         int setpoint;
171         int32_t integral;
172         int32_t p_gain;
173         int32_t i_gain;
174         int32_t d_gain;
175         int deadband;
176         int32_t last_err;
177 };
178
179 /**
180  * struct cpudata -     Per CPU instance data storage
181  * @cpu:                CPU number for this instance data
182  * @policy:             CPUFreq policy value
183  * @update_util:        CPUFreq utility callback information
184  * @update_util_set:    CPUFreq utility callback is set
185  * @iowait_boost:       iowait-related boost fraction
186  * @last_update:        Time of the last update.
187  * @pstate:             Stores P state limits for this CPU
188  * @vid:                Stores VID limits for this CPU
189  * @pid:                Stores PID parameters for this CPU
190  * @last_sample_time:   Last Sample time
191  * @prev_aperf:         Last APERF value read from APERF MSR
192  * @prev_mperf:         Last MPERF value read from MPERF MSR
193  * @prev_tsc:           Last timestamp counter (TSC) value
194  * @prev_cummulative_iowait: IO Wait time difference from last and
195  *                      current sample
196  * @sample:             Storage for storing last Sample data
197  * @acpi_perf_data:     Stores ACPI perf information read from _PSS
198  * @valid_pss_table:    Set to true for valid ACPI _PSS entries found
199  *
200  * This structure stores per CPU instance data for all CPUs.
201  */
202 struct cpudata {
203         int cpu;
204
205         unsigned int policy;
206         struct update_util_data update_util;
207         bool   update_util_set;
208
209         struct pstate_data pstate;
210         struct vid_data vid;
211         struct _pid pid;
212
213         u64     last_update;
214         u64     last_sample_time;
215         u64     prev_aperf;
216         u64     prev_mperf;
217         u64     prev_tsc;
218         u64     prev_cummulative_iowait;
219         struct sample sample;
220 #ifdef CONFIG_ACPI
221         struct acpi_processor_performance acpi_perf_data;
222         bool valid_pss_table;
223 #endif
224         unsigned int iowait_boost;
225 };
226
227 static struct cpudata **all_cpu_data;
228
229 /**
230  * struct pstate_adjust_policy - Stores static PID configuration data
231  * @sample_rate_ms:     PID calculation sample rate in ms
232  * @sample_rate_ns:     Sample rate calculation in ns
233  * @deadband:           PID deadband
234  * @setpoint:           PID Setpoint
235  * @p_gain_pct:         PID proportional gain
236  * @i_gain_pct:         PID integral gain
237  * @d_gain_pct:         PID derivative gain
238  * @boost_iowait:       Whether or not to use iowait boosting.
239  *
240  * Stores per CPU model static PID configuration data.
241  */
242 struct pstate_adjust_policy {
243         int sample_rate_ms;
244         s64 sample_rate_ns;
245         int deadband;
246         int setpoint;
247         int p_gain_pct;
248         int d_gain_pct;
249         int i_gain_pct;
250         bool boost_iowait;
251 };
252
253 /**
254  * struct pstate_funcs - Per CPU model specific callbacks
255  * @get_max:            Callback to get maximum non turbo effective P state
256  * @get_max_physical:   Callback to get maximum non turbo physical P state
257  * @get_min:            Callback to get minimum P state
258  * @get_turbo:          Callback to get turbo P state
259  * @get_scaling:        Callback to get frequency scaling factor
260  * @get_val:            Callback to convert P state to actual MSR write value
261  * @get_vid:            Callback to get VID data for Atom platforms
262  * @get_target_pstate:  Callback to a function to calculate next P state to use
263  *
264  * Core and Atom CPU models have different way to get P State limits. This
265  * structure is used to store those callbacks.
266  */
267 struct pstate_funcs {
268         int (*get_max)(void);
269         int (*get_max_physical)(void);
270         int (*get_min)(void);
271         int (*get_turbo)(void);
272         int (*get_scaling)(void);
273         u64 (*get_val)(struct cpudata*, int pstate);
274         void (*get_vid)(struct cpudata *);
275         int32_t (*get_target_pstate)(struct cpudata *);
276 };
277
278 /**
279  * struct cpu_defaults- Per CPU model default config data
280  * @pid_policy: PID config data
281  * @funcs:              Callback function data
282  */
283 struct cpu_defaults {
284         struct pstate_adjust_policy pid_policy;
285         struct pstate_funcs funcs;
286 };
287
288 static inline int32_t get_target_pstate_use_performance(struct cpudata *cpu);
289 static inline int32_t get_target_pstate_use_cpu_load(struct cpudata *cpu);
290
291 static struct pstate_adjust_policy pid_params __read_mostly;
292 static struct pstate_funcs pstate_funcs __read_mostly;
293 static int hwp_active __read_mostly;
294
295 #ifdef CONFIG_ACPI
296 static bool acpi_ppc;
297 #endif
298
299 /**
300  * struct perf_limits - Store user and policy limits
301  * @no_turbo:           User requested turbo state from intel_pstate sysfs
302  * @turbo_disabled:     Platform turbo status either from msr
303  *                      MSR_IA32_MISC_ENABLE or when maximum available pstate
304  *                      matches the maximum turbo pstate
305  * @max_perf_pct:       Effective maximum performance limit in percentage, this
306  *                      is minimum of either limits enforced by cpufreq policy
307  *                      or limits from user set limits via intel_pstate sysfs
308  * @min_perf_pct:       Effective minimum performance limit in percentage, this
309  *                      is maximum of either limits enforced by cpufreq policy
310  *                      or limits from user set limits via intel_pstate sysfs
311  * @max_perf:           This is a scaled value between 0 to 255 for max_perf_pct
312  *                      This value is used to limit max pstate
313  * @min_perf:           This is a scaled value between 0 to 255 for min_perf_pct
314  *                      This value is used to limit min pstate
315  * @max_policy_pct:     The maximum performance in percentage enforced by
316  *                      cpufreq setpolicy interface
317  * @max_sysfs_pct:      The maximum performance in percentage enforced by
318  *                      intel pstate sysfs interface
319  * @min_policy_pct:     The minimum performance in percentage enforced by
320  *                      cpufreq setpolicy interface
321  * @min_sysfs_pct:      The minimum performance in percentage enforced by
322  *                      intel pstate sysfs interface
323  *
324  * Storage for user and policy defined limits.
325  */
326 struct perf_limits {
327         int no_turbo;
328         int turbo_disabled;
329         int max_perf_pct;
330         int min_perf_pct;
331         int32_t max_perf;
332         int32_t min_perf;
333         int max_policy_pct;
334         int max_sysfs_pct;
335         int min_policy_pct;
336         int min_sysfs_pct;
337 };
338
339 static struct perf_limits performance_limits = {
340         .no_turbo = 0,
341         .turbo_disabled = 0,
342         .max_perf_pct = 100,
343         .max_perf = int_tofp(1),
344         .min_perf_pct = 100,
345         .min_perf = int_tofp(1),
346         .max_policy_pct = 100,
347         .max_sysfs_pct = 100,
348         .min_policy_pct = 0,
349         .min_sysfs_pct = 0,
350 };
351
352 static struct perf_limits powersave_limits = {
353         .no_turbo = 0,
354         .turbo_disabled = 0,
355         .max_perf_pct = 100,
356         .max_perf = int_tofp(1),
357         .min_perf_pct = 0,
358         .min_perf = 0,
359         .max_policy_pct = 100,
360         .max_sysfs_pct = 100,
361         .min_policy_pct = 0,
362         .min_sysfs_pct = 0,
363 };
364
365 #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE
366 static struct perf_limits *limits = &performance_limits;
367 #else
368 static struct perf_limits *limits = &powersave_limits;
369 #endif
370
371 #ifdef CONFIG_ACPI
372
373 static bool intel_pstate_get_ppc_enable_status(void)
374 {
375         if (acpi_gbl_FADT.preferred_profile == PM_ENTERPRISE_SERVER ||
376             acpi_gbl_FADT.preferred_profile == PM_PERFORMANCE_SERVER)
377                 return true;
378
379         return acpi_ppc;
380 }
381
382 static void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
383 {
384         struct cpudata *cpu;
385         int ret;
386         int i;
387
388         if (hwp_active)
389                 return;
390
391         if (!intel_pstate_get_ppc_enable_status())
392                 return;
393
394         cpu = all_cpu_data[policy->cpu];
395
396         ret = acpi_processor_register_performance(&cpu->acpi_perf_data,
397                                                   policy->cpu);
398         if (ret)
399                 return;
400
401         /*
402          * Check if the control value in _PSS is for PERF_CTL MSR, which should
403          * guarantee that the states returned by it map to the states in our
404          * list directly.
405          */
406         if (cpu->acpi_perf_data.control_register.space_id !=
407                                                 ACPI_ADR_SPACE_FIXED_HARDWARE)
408                 goto err;
409
410         /*
411          * If there is only one entry _PSS, simply ignore _PSS and continue as
412          * usual without taking _PSS into account
413          */
414         if (cpu->acpi_perf_data.state_count < 2)
415                 goto err;
416
417         pr_debug("CPU%u - ACPI _PSS perf data\n", policy->cpu);
418         for (i = 0; i < cpu->acpi_perf_data.state_count; i++) {
419                 pr_debug("     %cP%d: %u MHz, %u mW, 0x%x\n",
420                          (i == cpu->acpi_perf_data.state ? '*' : ' '), i,
421                          (u32) cpu->acpi_perf_data.states[i].core_frequency,
422                          (u32) cpu->acpi_perf_data.states[i].power,
423                          (u32) cpu->acpi_perf_data.states[i].control);
424         }
425
426         /*
427          * The _PSS table doesn't contain whole turbo frequency range.
428          * This just contains +1 MHZ above the max non turbo frequency,
429          * with control value corresponding to max turbo ratio. But
430          * when cpufreq set policy is called, it will call with this
431          * max frequency, which will cause a reduced performance as
432          * this driver uses real max turbo frequency as the max
433          * frequency. So correct this frequency in _PSS table to
434          * correct max turbo frequency based on the turbo state.
435          * Also need to convert to MHz as _PSS freq is in MHz.
436          */
437         if (!limits->turbo_disabled)
438                 cpu->acpi_perf_data.states[0].core_frequency =
439                                         policy->cpuinfo.max_freq / 1000;
440         cpu->valid_pss_table = true;
441         pr_debug("_PPC limits will be enforced\n");
442
443         return;
444
445  err:
446         cpu->valid_pss_table = false;
447         acpi_processor_unregister_performance(policy->cpu);
448 }
449
450 static void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
451 {
452         struct cpudata *cpu;
453
454         cpu = all_cpu_data[policy->cpu];
455         if (!cpu->valid_pss_table)
456                 return;
457
458         acpi_processor_unregister_performance(policy->cpu);
459 }
460
461 #else
462 static void intel_pstate_init_acpi_perf_limits(struct cpufreq_policy *policy)
463 {
464 }
465
466 static void intel_pstate_exit_perf_limits(struct cpufreq_policy *policy)
467 {
468 }
469 #endif
470
471 static inline void pid_reset(struct _pid *pid, int setpoint, int busy,
472                              int deadband, int integral) {
473         pid->setpoint = int_tofp(setpoint);
474         pid->deadband  = int_tofp(deadband);
475         pid->integral  = int_tofp(integral);
476         pid->last_err  = int_tofp(setpoint) - int_tofp(busy);
477 }
478
479 static inline void pid_p_gain_set(struct _pid *pid, int percent)
480 {
481         pid->p_gain = div_fp(percent, 100);
482 }
483
484 static inline void pid_i_gain_set(struct _pid *pid, int percent)
485 {
486         pid->i_gain = div_fp(percent, 100);
487 }
488
489 static inline void pid_d_gain_set(struct _pid *pid, int percent)
490 {
491         pid->d_gain = div_fp(percent, 100);
492 }
493
494 static signed int pid_calc(struct _pid *pid, int32_t busy)
495 {
496         signed int result;
497         int32_t pterm, dterm, fp_error;
498         int32_t integral_limit;
499
500         fp_error = pid->setpoint - busy;
501
502         if (abs(fp_error) <= pid->deadband)
503                 return 0;
504
505         pterm = mul_fp(pid->p_gain, fp_error);
506
507         pid->integral += fp_error;
508
509         /*
510          * We limit the integral here so that it will never
511          * get higher than 30.  This prevents it from becoming
512          * too large an input over long periods of time and allows
513          * it to get factored out sooner.
514          *
515          * The value of 30 was chosen through experimentation.
516          */
517         integral_limit = int_tofp(30);
518         if (pid->integral > integral_limit)
519                 pid->integral = integral_limit;
520         if (pid->integral < -integral_limit)
521                 pid->integral = -integral_limit;
522
523         dterm = mul_fp(pid->d_gain, fp_error - pid->last_err);
524         pid->last_err = fp_error;
525
526         result = pterm + mul_fp(pid->integral, pid->i_gain) + dterm;
527         result = result + (1 << (FRAC_BITS-1));
528         return (signed int)fp_toint(result);
529 }
530
531 static inline void intel_pstate_busy_pid_reset(struct cpudata *cpu)
532 {
533         pid_p_gain_set(&cpu->pid, pid_params.p_gain_pct);
534         pid_d_gain_set(&cpu->pid, pid_params.d_gain_pct);
535         pid_i_gain_set(&cpu->pid, pid_params.i_gain_pct);
536
537         pid_reset(&cpu->pid, pid_params.setpoint, 100, pid_params.deadband, 0);
538 }
539
540 static inline void intel_pstate_reset_all_pid(void)
541 {
542         unsigned int cpu;
543
544         for_each_online_cpu(cpu) {
545                 if (all_cpu_data[cpu])
546                         intel_pstate_busy_pid_reset(all_cpu_data[cpu]);
547         }
548 }
549
550 static inline void update_turbo_state(void)
551 {
552         u64 misc_en;
553         struct cpudata *cpu;
554
555         cpu = all_cpu_data[0];
556         rdmsrl(MSR_IA32_MISC_ENABLE, misc_en);
557         limits->turbo_disabled =
558                 (misc_en & MSR_IA32_MISC_ENABLE_TURBO_DISABLE ||
559                  cpu->pstate.max_pstate == cpu->pstate.turbo_pstate);
560 }
561
562 static void intel_pstate_hwp_set(const struct cpumask *cpumask)
563 {
564         int min, hw_min, max, hw_max, cpu, range, adj_range;
565         u64 value, cap;
566
567         for_each_cpu(cpu, cpumask) {
568                 rdmsrl_on_cpu(cpu, MSR_HWP_CAPABILITIES, &cap);
569                 hw_min = HWP_LOWEST_PERF(cap);
570                 hw_max = HWP_HIGHEST_PERF(cap);
571                 range = hw_max - hw_min;
572
573                 rdmsrl_on_cpu(cpu, MSR_HWP_REQUEST, &value);
574                 adj_range = limits->min_perf_pct * range / 100;
575                 min = hw_min + adj_range;
576                 value &= ~HWP_MIN_PERF(~0L);
577                 value |= HWP_MIN_PERF(min);
578
579                 adj_range = limits->max_perf_pct * range / 100;
580                 max = hw_min + adj_range;
581                 if (limits->no_turbo) {
582                         hw_max = HWP_GUARANTEED_PERF(cap);
583                         if (hw_max < max)
584                                 max = hw_max;
585                 }
586
587                 value &= ~HWP_MAX_PERF(~0L);
588                 value |= HWP_MAX_PERF(max);
589                 wrmsrl_on_cpu(cpu, MSR_HWP_REQUEST, value);
590         }
591 }
592
593 static int intel_pstate_hwp_set_policy(struct cpufreq_policy *policy)
594 {
595         if (hwp_active)
596                 intel_pstate_hwp_set(policy->cpus);
597
598         return 0;
599 }
600
601 static void intel_pstate_hwp_set_online_cpus(void)
602 {
603         get_online_cpus();
604         intel_pstate_hwp_set(cpu_online_mask);
605         put_online_cpus();
606 }
607
608 /************************** debugfs begin ************************/
609 static int pid_param_set(void *data, u64 val)
610 {
611         *(u32 *)data = val;
612         pid_params.sample_rate_ns = pid_params.sample_rate_ms * NSEC_PER_MSEC;
613         intel_pstate_reset_all_pid();
614         return 0;
615 }
616
617 static int pid_param_get(void *data, u64 *val)
618 {
619         *val = *(u32 *)data;
620         return 0;
621 }
622 DEFINE_SIMPLE_ATTRIBUTE(fops_pid_param, pid_param_get, pid_param_set, "%llu\n");
623
624 struct pid_param {
625         char *name;
626         void *value;
627 };
628
629 static struct pid_param pid_files[] = {
630         {"sample_rate_ms", &pid_params.sample_rate_ms},
631         {"d_gain_pct", &pid_params.d_gain_pct},
632         {"i_gain_pct", &pid_params.i_gain_pct},
633         {"deadband", &pid_params.deadband},
634         {"setpoint", &pid_params.setpoint},
635         {"p_gain_pct", &pid_params.p_gain_pct},
636         {NULL, NULL}
637 };
638
639 static void __init intel_pstate_debug_expose_params(void)
640 {
641         struct dentry *debugfs_parent;
642         int i = 0;
643
644         if (hwp_active)
645                 return;
646         debugfs_parent = debugfs_create_dir("pstate_snb", NULL);
647         if (IS_ERR_OR_NULL(debugfs_parent))
648                 return;
649         while (pid_files[i].name) {
650                 debugfs_create_file(pid_files[i].name, 0660,
651                                     debugfs_parent, pid_files[i].value,
652                                     &fops_pid_param);
653                 i++;
654         }
655 }
656
657 /************************** debugfs end ************************/
658
659 /************************** sysfs begin ************************/
660 #define show_one(file_name, object)                                     \
661         static ssize_t show_##file_name                                 \
662         (struct kobject *kobj, struct kobj_attribute *attr, char *buf)  \
663         {                                                               \
664                 return sprintf(buf, "%u\n", limits->object);            \
665         }
666
667 static ssize_t show_turbo_pct(struct kobject *kobj,
668                                 struct kobj_attribute *attr, char *buf)
669 {
670         struct cpudata *cpu;
671         int total, no_turbo, turbo_pct;
672         uint32_t turbo_fp;
673
674         cpu = all_cpu_data[0];
675
676         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
677         no_turbo = cpu->pstate.max_pstate - cpu->pstate.min_pstate + 1;
678         turbo_fp = div_fp(no_turbo, total);
679         turbo_pct = 100 - fp_toint(mul_fp(turbo_fp, int_tofp(100)));
680         return sprintf(buf, "%u\n", turbo_pct);
681 }
682
683 static ssize_t show_num_pstates(struct kobject *kobj,
684                                 struct kobj_attribute *attr, char *buf)
685 {
686         struct cpudata *cpu;
687         int total;
688
689         cpu = all_cpu_data[0];
690         total = cpu->pstate.turbo_pstate - cpu->pstate.min_pstate + 1;
691         return sprintf(buf, "%u\n", total);
692 }
693
694 static ssize_t show_no_turbo(struct kobject *kobj,
695                              struct kobj_attribute *attr, char *buf)
696 {
697         ssize_t ret;
698
699         update_turbo_state();
700         if (limits->turbo_disabled)
701                 ret = sprintf(buf, "%u\n", limits->turbo_disabled);
702         else
703                 ret = sprintf(buf, "%u\n", limits->no_turbo);
704
705         return ret;
706 }
707
708 static ssize_t store_no_turbo(struct kobject *a, struct kobj_attribute *b,
709                               const char *buf, size_t count)
710 {
711         unsigned int input;
712         int ret;
713
714         ret = sscanf(buf, "%u", &input);
715         if (ret != 1)
716                 return -EINVAL;
717
718         update_turbo_state();
719         if (limits->turbo_disabled) {
720                 pr_warn("Turbo disabled by BIOS or unavailable on processor\n");
721                 return -EPERM;
722         }
723
724         limits->no_turbo = clamp_t(int, input, 0, 1);
725
726         if (hwp_active)
727                 intel_pstate_hwp_set_online_cpus();
728
729         return count;
730 }
731
732 static ssize_t store_max_perf_pct(struct kobject *a, struct kobj_attribute *b,
733                                   const char *buf, size_t count)
734 {
735         unsigned int input;
736         int ret;
737
738         ret = sscanf(buf, "%u", &input);
739         if (ret != 1)
740                 return -EINVAL;
741
742         limits->max_sysfs_pct = clamp_t(int, input, 0 , 100);
743         limits->max_perf_pct = min(limits->max_policy_pct,
744                                    limits->max_sysfs_pct);
745         limits->max_perf_pct = max(limits->min_policy_pct,
746                                    limits->max_perf_pct);
747         limits->max_perf_pct = max(limits->min_perf_pct,
748                                    limits->max_perf_pct);
749         limits->max_perf = div_fp(limits->max_perf_pct, 100);
750
751         if (hwp_active)
752                 intel_pstate_hwp_set_online_cpus();
753         return count;
754 }
755
756 static ssize_t store_min_perf_pct(struct kobject *a, struct kobj_attribute *b,
757                                   const char *buf, size_t count)
758 {
759         unsigned int input;
760         int ret;
761
762         ret = sscanf(buf, "%u", &input);
763         if (ret != 1)
764                 return -EINVAL;
765
766         limits->min_sysfs_pct = clamp_t(int, input, 0 , 100);
767         limits->min_perf_pct = max(limits->min_policy_pct,
768                                    limits->min_sysfs_pct);
769         limits->min_perf_pct = min(limits->max_policy_pct,
770                                    limits->min_perf_pct);
771         limits->min_perf_pct = min(limits->max_perf_pct,
772                                    limits->min_perf_pct);
773         limits->min_perf = div_fp(limits->min_perf_pct, 100);
774
775         if (hwp_active)
776                 intel_pstate_hwp_set_online_cpus();
777         return count;
778 }
779
780 show_one(max_perf_pct, max_perf_pct);
781 show_one(min_perf_pct, min_perf_pct);
782
783 define_one_global_rw(no_turbo);
784 define_one_global_rw(max_perf_pct);
785 define_one_global_rw(min_perf_pct);
786 define_one_global_ro(turbo_pct);
787 define_one_global_ro(num_pstates);
788
789 static struct attribute *intel_pstate_attributes[] = {
790         &no_turbo.attr,
791         &max_perf_pct.attr,
792         &min_perf_pct.attr,
793         &turbo_pct.attr,
794         &num_pstates.attr,
795         NULL
796 };
797
798 static struct attribute_group intel_pstate_attr_group = {
799         .attrs = intel_pstate_attributes,
800 };
801
802 static void __init intel_pstate_sysfs_expose_params(void)
803 {
804         struct kobject *intel_pstate_kobject;
805         int rc;
806
807         intel_pstate_kobject = kobject_create_and_add("intel_pstate",
808                                                 &cpu_subsys.dev_root->kobj);
809         BUG_ON(!intel_pstate_kobject);
810         rc = sysfs_create_group(intel_pstate_kobject, &intel_pstate_attr_group);
811         BUG_ON(rc);
812 }
813 /************************** sysfs end ************************/
814
815 static void intel_pstate_hwp_enable(struct cpudata *cpudata)
816 {
817         /* First disable HWP notification interrupt as we don't process them */
818         if (static_cpu_has(X86_FEATURE_HWP_NOTIFY))
819                 wrmsrl_on_cpu(cpudata->cpu, MSR_HWP_INTERRUPT, 0x00);
820
821         wrmsrl_on_cpu(cpudata->cpu, MSR_PM_ENABLE, 0x1);
822 }
823
824 #define MSR_IA32_POWER_CTL_BIT_EE       19
825
826 /* Disable energy efficiency optimization */
827 static void intel_pstate_disable_ee(int cpu)
828 {
829         u64 power_ctl;
830         int ret;
831
832         ret = rdmsrl_on_cpu(cpu, MSR_IA32_POWER_CTL, &power_ctl);
833         if (ret)
834                 return;
835
836         if (!(power_ctl & BIT(MSR_IA32_POWER_CTL_BIT_EE))) {
837                 pr_info("Disabling energy efficiency optimization\n");
838                 power_ctl |= BIT(MSR_IA32_POWER_CTL_BIT_EE);
839                 wrmsrl_on_cpu(cpu, MSR_IA32_POWER_CTL, power_ctl);
840         }
841 }
842
843 static int atom_get_min_pstate(void)
844 {
845         u64 value;
846
847         rdmsrl(ATOM_RATIOS, value);
848         return (value >> 8) & 0x7F;
849 }
850
851 static int atom_get_max_pstate(void)
852 {
853         u64 value;
854
855         rdmsrl(ATOM_RATIOS, value);
856         return (value >> 16) & 0x7F;
857 }
858
859 static int atom_get_turbo_pstate(void)
860 {
861         u64 value;
862
863         rdmsrl(ATOM_TURBO_RATIOS, value);
864         return value & 0x7F;
865 }
866
867 static u64 atom_get_val(struct cpudata *cpudata, int pstate)
868 {
869         u64 val;
870         int32_t vid_fp;
871         u32 vid;
872
873         val = (u64)pstate << 8;
874         if (limits->no_turbo && !limits->turbo_disabled)
875                 val |= (u64)1 << 32;
876
877         vid_fp = cpudata->vid.min + mul_fp(
878                 int_tofp(pstate - cpudata->pstate.min_pstate),
879                 cpudata->vid.ratio);
880
881         vid_fp = clamp_t(int32_t, vid_fp, cpudata->vid.min, cpudata->vid.max);
882         vid = ceiling_fp(vid_fp);
883
884         if (pstate > cpudata->pstate.max_pstate)
885                 vid = cpudata->vid.turbo;
886
887         return val | vid;
888 }
889
890 static int silvermont_get_scaling(void)
891 {
892         u64 value;
893         int i;
894         /* Defined in Table 35-6 from SDM (Sept 2015) */
895         static int silvermont_freq_table[] = {
896                 83300, 100000, 133300, 116700, 80000};
897
898         rdmsrl(MSR_FSB_FREQ, value);
899         i = value & 0x7;
900         WARN_ON(i > 4);
901
902         return silvermont_freq_table[i];
903 }
904
905 static int airmont_get_scaling(void)
906 {
907         u64 value;
908         int i;
909         /* Defined in Table 35-10 from SDM (Sept 2015) */
910         static int airmont_freq_table[] = {
911                 83300, 100000, 133300, 116700, 80000,
912                 93300, 90000, 88900, 87500};
913
914         rdmsrl(MSR_FSB_FREQ, value);
915         i = value & 0xF;
916         WARN_ON(i > 8);
917
918         return airmont_freq_table[i];
919 }
920
921 static void atom_get_vid(struct cpudata *cpudata)
922 {
923         u64 value;
924
925         rdmsrl(ATOM_VIDS, value);
926         cpudata->vid.min = int_tofp((value >> 8) & 0x7f);
927         cpudata->vid.max = int_tofp((value >> 16) & 0x7f);
928         cpudata->vid.ratio = div_fp(
929                 cpudata->vid.max - cpudata->vid.min,
930                 int_tofp(cpudata->pstate.max_pstate -
931                         cpudata->pstate.min_pstate));
932
933         rdmsrl(ATOM_TURBO_VIDS, value);
934         cpudata->vid.turbo = value & 0x7f;
935 }
936
937 static int core_get_min_pstate(void)
938 {
939         u64 value;
940
941         rdmsrl(MSR_PLATFORM_INFO, value);
942         return (value >> 40) & 0xFF;
943 }
944
945 static int core_get_max_pstate_physical(void)
946 {
947         u64 value;
948
949         rdmsrl(MSR_PLATFORM_INFO, value);
950         return (value >> 8) & 0xFF;
951 }
952
953 static int core_get_max_pstate(void)
954 {
955         u64 tar;
956         u64 plat_info;
957         int max_pstate;
958         int err;
959
960         rdmsrl(MSR_PLATFORM_INFO, plat_info);
961         max_pstate = (plat_info >> 8) & 0xFF;
962
963         err = rdmsrl_safe(MSR_TURBO_ACTIVATION_RATIO, &tar);
964         if (!err) {
965                 /* Do some sanity checking for safety */
966                 if (plat_info & 0x600000000) {
967                         u64 tdp_ctrl;
968                         u64 tdp_ratio;
969                         int tdp_msr;
970
971                         err = rdmsrl_safe(MSR_CONFIG_TDP_CONTROL, &tdp_ctrl);
972                         if (err)
973                                 goto skip_tar;
974
975                         tdp_msr = MSR_CONFIG_TDP_NOMINAL + (tdp_ctrl & 0x3);
976                         err = rdmsrl_safe(tdp_msr, &tdp_ratio);
977                         if (err)
978                                 goto skip_tar;
979
980                         /* For level 1 and 2, bits[23:16] contain the ratio */
981                         if (tdp_ctrl)
982                                 tdp_ratio >>= 16;
983
984                         tdp_ratio &= 0xff; /* ratios are only 8 bits long */
985                         if (tdp_ratio - 1 == tar) {
986                                 max_pstate = tar;
987                                 pr_debug("max_pstate=TAC %x\n", max_pstate);
988                         } else {
989                                 goto skip_tar;
990                         }
991                 }
992         }
993
994 skip_tar:
995         return max_pstate;
996 }
997
998 static int core_get_turbo_pstate(void)
999 {
1000         u64 value;
1001         int nont, ret;
1002
1003         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1004         nont = core_get_max_pstate();
1005         ret = (value) & 255;
1006         if (ret <= nont)
1007                 ret = nont;
1008         return ret;
1009 }
1010
1011 static inline int core_get_scaling(void)
1012 {
1013         return 100000;
1014 }
1015
1016 static u64 core_get_val(struct cpudata *cpudata, int pstate)
1017 {
1018         u64 val;
1019
1020         val = (u64)pstate << 8;
1021         if (limits->no_turbo && !limits->turbo_disabled)
1022                 val |= (u64)1 << 32;
1023
1024         return val;
1025 }
1026
1027 static int knl_get_turbo_pstate(void)
1028 {
1029         u64 value;
1030         int nont, ret;
1031
1032         rdmsrl(MSR_TURBO_RATIO_LIMIT, value);
1033         nont = core_get_max_pstate();
1034         ret = (((value) >> 8) & 0xFF);
1035         if (ret <= nont)
1036                 ret = nont;
1037         return ret;
1038 }
1039
1040 static struct cpu_defaults core_params = {
1041         .pid_policy = {
1042                 .sample_rate_ms = 10,
1043                 .deadband = 0,
1044                 .setpoint = 97,
1045                 .p_gain_pct = 20,
1046                 .d_gain_pct = 0,
1047                 .i_gain_pct = 0,
1048         },
1049         .funcs = {
1050                 .get_max = core_get_max_pstate,
1051                 .get_max_physical = core_get_max_pstate_physical,
1052                 .get_min = core_get_min_pstate,
1053                 .get_turbo = core_get_turbo_pstate,
1054                 .get_scaling = core_get_scaling,
1055                 .get_val = core_get_val,
1056                 .get_target_pstate = get_target_pstate_use_performance,
1057         },
1058 };
1059
1060 static const struct cpu_defaults silvermont_params = {
1061         .pid_policy = {
1062                 .sample_rate_ms = 10,
1063                 .deadband = 0,
1064                 .setpoint = 60,
1065                 .p_gain_pct = 14,
1066                 .d_gain_pct = 0,
1067                 .i_gain_pct = 4,
1068                 .boost_iowait = true,
1069         },
1070         .funcs = {
1071                 .get_max = atom_get_max_pstate,
1072                 .get_max_physical = atom_get_max_pstate,
1073                 .get_min = atom_get_min_pstate,
1074                 .get_turbo = atom_get_turbo_pstate,
1075                 .get_val = atom_get_val,
1076                 .get_scaling = silvermont_get_scaling,
1077                 .get_vid = atom_get_vid,
1078                 .get_target_pstate = get_target_pstate_use_cpu_load,
1079         },
1080 };
1081
1082 static const struct cpu_defaults airmont_params = {
1083         .pid_policy = {
1084                 .sample_rate_ms = 10,
1085                 .deadband = 0,
1086                 .setpoint = 60,
1087                 .p_gain_pct = 14,
1088                 .d_gain_pct = 0,
1089                 .i_gain_pct = 4,
1090                 .boost_iowait = true,
1091         },
1092         .funcs = {
1093                 .get_max = atom_get_max_pstate,
1094                 .get_max_physical = atom_get_max_pstate,
1095                 .get_min = atom_get_min_pstate,
1096                 .get_turbo = atom_get_turbo_pstate,
1097                 .get_val = atom_get_val,
1098                 .get_scaling = airmont_get_scaling,
1099                 .get_vid = atom_get_vid,
1100                 .get_target_pstate = get_target_pstate_use_cpu_load,
1101         },
1102 };
1103
1104 static const struct cpu_defaults knl_params = {
1105         .pid_policy = {
1106                 .sample_rate_ms = 10,
1107                 .deadband = 0,
1108                 .setpoint = 97,
1109                 .p_gain_pct = 20,
1110                 .d_gain_pct = 0,
1111                 .i_gain_pct = 0,
1112         },
1113         .funcs = {
1114                 .get_max = core_get_max_pstate,
1115                 .get_max_physical = core_get_max_pstate_physical,
1116                 .get_min = core_get_min_pstate,
1117                 .get_turbo = knl_get_turbo_pstate,
1118                 .get_scaling = core_get_scaling,
1119                 .get_val = core_get_val,
1120                 .get_target_pstate = get_target_pstate_use_performance,
1121         },
1122 };
1123
1124 static const struct cpu_defaults bxt_params = {
1125         .pid_policy = {
1126                 .sample_rate_ms = 10,
1127                 .deadband = 0,
1128                 .setpoint = 60,
1129                 .p_gain_pct = 14,
1130                 .d_gain_pct = 0,
1131                 .i_gain_pct = 4,
1132                 .boost_iowait = true,
1133         },
1134         .funcs = {
1135                 .get_max = core_get_max_pstate,
1136                 .get_max_physical = core_get_max_pstate_physical,
1137                 .get_min = core_get_min_pstate,
1138                 .get_turbo = core_get_turbo_pstate,
1139                 .get_scaling = core_get_scaling,
1140                 .get_val = core_get_val,
1141                 .get_target_pstate = get_target_pstate_use_cpu_load,
1142         },
1143 };
1144
1145 static void intel_pstate_get_min_max(struct cpudata *cpu, int *min, int *max)
1146 {
1147         int max_perf = cpu->pstate.turbo_pstate;
1148         int max_perf_adj;
1149         int min_perf;
1150
1151         if (limits->no_turbo || limits->turbo_disabled)
1152                 max_perf = cpu->pstate.max_pstate;
1153
1154         /*
1155          * performance can be limited by user through sysfs, by cpufreq
1156          * policy, or by cpu specific default values determined through
1157          * experimentation.
1158          */
1159         max_perf_adj = fp_toint(max_perf * limits->max_perf);
1160         *max = clamp_t(int, max_perf_adj,
1161                         cpu->pstate.min_pstate, cpu->pstate.turbo_pstate);
1162
1163         min_perf = fp_toint(max_perf * limits->min_perf);
1164         *min = clamp_t(int, min_perf, cpu->pstate.min_pstate, max_perf);
1165 }
1166
1167 static void intel_pstate_set_pstate(struct cpudata *cpu, int pstate)
1168 {
1169         trace_cpu_frequency(pstate * cpu->pstate.scaling, cpu->cpu);
1170         cpu->pstate.current_pstate = pstate;
1171         /*
1172          * Generally, there is no guarantee that this code will always run on
1173          * the CPU being updated, so force the register update to run on the
1174          * right CPU.
1175          */
1176         wrmsrl_on_cpu(cpu->cpu, MSR_IA32_PERF_CTL,
1177                       pstate_funcs.get_val(cpu, pstate));
1178 }
1179
1180 static void intel_pstate_set_min_pstate(struct cpudata *cpu)
1181 {
1182         intel_pstate_set_pstate(cpu, cpu->pstate.min_pstate);
1183 }
1184
1185 static void intel_pstate_max_within_limits(struct cpudata *cpu)
1186 {
1187         int min_pstate, max_pstate;
1188
1189         update_turbo_state();
1190         intel_pstate_get_min_max(cpu, &min_pstate, &max_pstate);
1191         intel_pstate_set_pstate(cpu, max_pstate);
1192 }
1193
1194 static void intel_pstate_get_cpu_pstates(struct cpudata *cpu)
1195 {
1196         cpu->pstate.min_pstate = pstate_funcs.get_min();
1197         cpu->pstate.max_pstate = pstate_funcs.get_max();
1198         cpu->pstate.max_pstate_physical = pstate_funcs.get_max_physical();
1199         cpu->pstate.turbo_pstate = pstate_funcs.get_turbo();
1200         cpu->pstate.scaling = pstate_funcs.get_scaling();
1201
1202         if (pstate_funcs.get_vid)
1203                 pstate_funcs.get_vid(cpu);
1204
1205         intel_pstate_set_min_pstate(cpu);
1206 }
1207
1208 static inline void intel_pstate_calc_avg_perf(struct cpudata *cpu)
1209 {
1210         struct sample *sample = &cpu->sample;
1211
1212         sample->core_avg_perf = div_ext_fp(sample->aperf, sample->mperf);
1213 }
1214
1215 static inline bool intel_pstate_sample(struct cpudata *cpu, u64 time)
1216 {
1217         u64 aperf, mperf;
1218         unsigned long flags;
1219         u64 tsc;
1220
1221         local_irq_save(flags);
1222         rdmsrl(MSR_IA32_APERF, aperf);
1223         rdmsrl(MSR_IA32_MPERF, mperf);
1224         tsc = rdtsc();
1225         if (cpu->prev_mperf == mperf || cpu->prev_tsc == tsc) {
1226                 local_irq_restore(flags);
1227                 return false;
1228         }
1229         local_irq_restore(flags);
1230
1231         cpu->last_sample_time = cpu->sample.time;
1232         cpu->sample.time = time;
1233         cpu->sample.aperf = aperf;
1234         cpu->sample.mperf = mperf;
1235         cpu->sample.tsc =  tsc;
1236         cpu->sample.aperf -= cpu->prev_aperf;
1237         cpu->sample.mperf -= cpu->prev_mperf;
1238         cpu->sample.tsc -= cpu->prev_tsc;
1239
1240         cpu->prev_aperf = aperf;
1241         cpu->prev_mperf = mperf;
1242         cpu->prev_tsc = tsc;
1243         /*
1244          * First time this function is invoked in a given cycle, all of the
1245          * previous sample data fields are equal to zero or stale and they must
1246          * be populated with meaningful numbers for things to work, so assume
1247          * that sample.time will always be reset before setting the utilization
1248          * update hook and make the caller skip the sample then.
1249          */
1250         return !!cpu->last_sample_time;
1251 }
1252
1253 static inline int32_t get_avg_frequency(struct cpudata *cpu)
1254 {
1255         return mul_ext_fp(cpu->sample.core_avg_perf,
1256                           cpu->pstate.max_pstate_physical * cpu->pstate.scaling);
1257 }
1258
1259 static inline int32_t get_avg_pstate(struct cpudata *cpu)
1260 {
1261         return mul_ext_fp(cpu->pstate.max_pstate_physical,
1262                           cpu->sample.core_avg_perf);
1263 }
1264
1265 static inline int32_t get_target_pstate_use_cpu_load(struct cpudata *cpu)
1266 {
1267         struct sample *sample = &cpu->sample;
1268         int32_t busy_frac, boost;
1269         int target, avg_pstate;
1270
1271         busy_frac = div_fp(sample->mperf, sample->tsc);
1272
1273         boost = cpu->iowait_boost;
1274         cpu->iowait_boost >>= 1;
1275
1276         if (busy_frac < boost)
1277                 busy_frac = boost;
1278
1279         sample->busy_scaled = busy_frac * 100;
1280
1281         target = limits->no_turbo || limits->turbo_disabled ?
1282                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
1283         target += target >> 2;
1284         target = mul_fp(target, busy_frac);
1285         if (target < cpu->pstate.min_pstate)
1286                 target = cpu->pstate.min_pstate;
1287
1288         /*
1289          * If the average P-state during the previous cycle was higher than the
1290          * current target, add 50% of the difference to the target to reduce
1291          * possible performance oscillations and offset possible performance
1292          * loss related to moving the workload from one CPU to another within
1293          * a package/module.
1294          */
1295         avg_pstate = get_avg_pstate(cpu);
1296         if (avg_pstate > target)
1297                 target += (avg_pstate - target) >> 1;
1298
1299         return target;
1300 }
1301
1302 static inline int32_t get_target_pstate_use_performance(struct cpudata *cpu)
1303 {
1304         int32_t perf_scaled, max_pstate, current_pstate, sample_ratio;
1305         u64 duration_ns;
1306
1307         /*
1308          * perf_scaled is the ratio of the average P-state during the last
1309          * sampling period to the P-state requested last time (in percent).
1310          *
1311          * That measures the system's response to the previous P-state
1312          * selection.
1313          */
1314         max_pstate = cpu->pstate.max_pstate_physical;
1315         current_pstate = cpu->pstate.current_pstate;
1316         perf_scaled = mul_ext_fp(cpu->sample.core_avg_perf,
1317                                div_fp(100 * max_pstate, current_pstate));
1318
1319         /*
1320          * Since our utilization update callback will not run unless we are
1321          * in C0, check if the actual elapsed time is significantly greater (3x)
1322          * than our sample interval.  If it is, then we were idle for a long
1323          * enough period of time to adjust our performance metric.
1324          */
1325         duration_ns = cpu->sample.time - cpu->last_sample_time;
1326         if ((s64)duration_ns > pid_params.sample_rate_ns * 3) {
1327                 sample_ratio = div_fp(pid_params.sample_rate_ns, duration_ns);
1328                 perf_scaled = mul_fp(perf_scaled, sample_ratio);
1329         } else {
1330                 sample_ratio = div_fp(100 * cpu->sample.mperf, cpu->sample.tsc);
1331                 if (sample_ratio < int_tofp(1))
1332                         perf_scaled = 0;
1333         }
1334
1335         cpu->sample.busy_scaled = perf_scaled;
1336         return cpu->pstate.current_pstate - pid_calc(&cpu->pid, perf_scaled);
1337 }
1338
1339 static inline void intel_pstate_update_pstate(struct cpudata *cpu, int pstate)
1340 {
1341         int max_perf, min_perf;
1342
1343         update_turbo_state();
1344
1345         intel_pstate_get_min_max(cpu, &min_perf, &max_perf);
1346         pstate = clamp_t(int, pstate, min_perf, max_perf);
1347         trace_cpu_frequency(pstate * cpu->pstate.scaling, cpu->cpu);
1348         if (pstate == cpu->pstate.current_pstate)
1349                 return;
1350
1351         cpu->pstate.current_pstate = pstate;
1352         wrmsrl(MSR_IA32_PERF_CTL, pstate_funcs.get_val(cpu, pstate));
1353 }
1354
1355 static inline void intel_pstate_adjust_busy_pstate(struct cpudata *cpu)
1356 {
1357         int from, target_pstate;
1358         struct sample *sample;
1359
1360         from = cpu->pstate.current_pstate;
1361
1362         target_pstate = cpu->policy == CPUFREQ_POLICY_PERFORMANCE ?
1363                 cpu->pstate.turbo_pstate : pstate_funcs.get_target_pstate(cpu);
1364
1365         intel_pstate_update_pstate(cpu, target_pstate);
1366
1367         sample = &cpu->sample;
1368         trace_pstate_sample(mul_ext_fp(100, sample->core_avg_perf),
1369                 fp_toint(sample->busy_scaled),
1370                 from,
1371                 cpu->pstate.current_pstate,
1372                 sample->mperf,
1373                 sample->aperf,
1374                 sample->tsc,
1375                 get_avg_frequency(cpu),
1376                 fp_toint(cpu->iowait_boost * 100));
1377 }
1378
1379 static void intel_pstate_update_util(struct update_util_data *data, u64 time,
1380                                      unsigned int flags)
1381 {
1382         struct cpudata *cpu = container_of(data, struct cpudata, update_util);
1383         u64 delta_ns;
1384
1385         if (pid_params.boost_iowait) {
1386                 if (flags & SCHED_CPUFREQ_IOWAIT) {
1387                         cpu->iowait_boost = int_tofp(1);
1388                 } else if (cpu->iowait_boost) {
1389                         /* Clear iowait_boost if the CPU may have been idle. */
1390                         delta_ns = time - cpu->last_update;
1391                         if (delta_ns > TICK_NSEC)
1392                                 cpu->iowait_boost = 0;
1393                 }
1394                 cpu->last_update = time;
1395         }
1396
1397         delta_ns = time - cpu->sample.time;
1398         if ((s64)delta_ns >= pid_params.sample_rate_ns) {
1399                 bool sample_taken = intel_pstate_sample(cpu, time);
1400
1401                 if (sample_taken) {
1402                         intel_pstate_calc_avg_perf(cpu);
1403                         if (!hwp_active)
1404                                 intel_pstate_adjust_busy_pstate(cpu);
1405                 }
1406         }
1407 }
1408
1409 #define ICPU(model, policy) \
1410         { X86_VENDOR_INTEL, 6, model, X86_FEATURE_APERFMPERF,\
1411                         (unsigned long)&policy }
1412
1413 static const struct x86_cpu_id intel_pstate_cpu_ids[] = {
1414         ICPU(INTEL_FAM6_SANDYBRIDGE,            core_params),
1415         ICPU(INTEL_FAM6_SANDYBRIDGE_X,          core_params),
1416         ICPU(INTEL_FAM6_ATOM_SILVERMONT,        silvermont_params),
1417         ICPU(INTEL_FAM6_IVYBRIDGE,              core_params),
1418         ICPU(INTEL_FAM6_HASWELL_CORE,           core_params),
1419         ICPU(INTEL_FAM6_BROADWELL_CORE,         core_params),
1420         ICPU(INTEL_FAM6_IVYBRIDGE_X,            core_params),
1421         ICPU(INTEL_FAM6_HASWELL_X,              core_params),
1422         ICPU(INTEL_FAM6_HASWELL_ULT,            core_params),
1423         ICPU(INTEL_FAM6_HASWELL_GT3E,           core_params),
1424         ICPU(INTEL_FAM6_BROADWELL_GT3E,         core_params),
1425         ICPU(INTEL_FAM6_ATOM_AIRMONT,           airmont_params),
1426         ICPU(INTEL_FAM6_SKYLAKE_MOBILE,         core_params),
1427         ICPU(INTEL_FAM6_BROADWELL_X,            core_params),
1428         ICPU(INTEL_FAM6_SKYLAKE_DESKTOP,        core_params),
1429         ICPU(INTEL_FAM6_BROADWELL_XEON_D,       core_params),
1430         ICPU(INTEL_FAM6_XEON_PHI_KNL,           knl_params),
1431         ICPU(INTEL_FAM6_ATOM_GOLDMONT,          bxt_params),
1432         {}
1433 };
1434 MODULE_DEVICE_TABLE(x86cpu, intel_pstate_cpu_ids);
1435
1436 static const struct x86_cpu_id intel_pstate_cpu_oob_ids[] __initconst = {
1437         ICPU(INTEL_FAM6_BROADWELL_XEON_D, core_params),
1438         ICPU(INTEL_FAM6_BROADWELL_X, core_params),
1439         ICPU(INTEL_FAM6_SKYLAKE_X, core_params),
1440         {}
1441 };
1442
1443 static const struct x86_cpu_id intel_pstate_cpu_ee_disable_ids[] = {
1444         ICPU(INTEL_FAM6_KABYLAKE_DESKTOP, core_params),
1445         {}
1446 };
1447
1448 static int intel_pstate_init_cpu(unsigned int cpunum)
1449 {
1450         struct cpudata *cpu;
1451
1452         if (!all_cpu_data[cpunum])
1453                 all_cpu_data[cpunum] = kzalloc(sizeof(struct cpudata),
1454                                                GFP_KERNEL);
1455         if (!all_cpu_data[cpunum])
1456                 return -ENOMEM;
1457
1458         cpu = all_cpu_data[cpunum];
1459
1460         cpu->cpu = cpunum;
1461
1462         if (hwp_active) {
1463                 const struct x86_cpu_id *id;
1464
1465                 id = x86_match_cpu(intel_pstate_cpu_ee_disable_ids);
1466                 if (id)
1467                         intel_pstate_disable_ee(cpunum);
1468
1469                 intel_pstate_hwp_enable(cpu);
1470                 pid_params.sample_rate_ms = 50;
1471                 pid_params.sample_rate_ns = 50 * NSEC_PER_MSEC;
1472         }
1473
1474         intel_pstate_get_cpu_pstates(cpu);
1475
1476         intel_pstate_busy_pid_reset(cpu);
1477
1478         pr_debug("controlling: cpu %d\n", cpunum);
1479
1480         return 0;
1481 }
1482
1483 static unsigned int intel_pstate_get(unsigned int cpu_num)
1484 {
1485         struct cpudata *cpu = all_cpu_data[cpu_num];
1486
1487         return cpu ? get_avg_frequency(cpu) : 0;
1488 }
1489
1490 static void intel_pstate_set_update_util_hook(unsigned int cpu_num)
1491 {
1492         struct cpudata *cpu = all_cpu_data[cpu_num];
1493
1494         if (cpu->update_util_set)
1495                 return;
1496
1497         /* Prevent intel_pstate_update_util() from using stale data. */
1498         cpu->sample.time = 0;
1499         cpufreq_add_update_util_hook(cpu_num, &cpu->update_util,
1500                                      intel_pstate_update_util);
1501         cpu->update_util_set = true;
1502 }
1503
1504 static void intel_pstate_clear_update_util_hook(unsigned int cpu)
1505 {
1506         struct cpudata *cpu_data = all_cpu_data[cpu];
1507
1508         if (!cpu_data->update_util_set)
1509                 return;
1510
1511         cpufreq_remove_update_util_hook(cpu);
1512         cpu_data->update_util_set = false;
1513         synchronize_sched();
1514 }
1515
1516 static void intel_pstate_set_performance_limits(struct perf_limits *limits)
1517 {
1518         limits->no_turbo = 0;
1519         limits->turbo_disabled = 0;
1520         limits->max_perf_pct = 100;
1521         limits->max_perf = int_tofp(1);
1522         limits->min_perf_pct = 100;
1523         limits->min_perf = int_tofp(1);
1524         limits->max_policy_pct = 100;
1525         limits->max_sysfs_pct = 100;
1526         limits->min_policy_pct = 0;
1527         limits->min_sysfs_pct = 0;
1528 }
1529
1530 static int intel_pstate_set_policy(struct cpufreq_policy *policy)
1531 {
1532         struct cpudata *cpu;
1533
1534         if (!policy->cpuinfo.max_freq)
1535                 return -ENODEV;
1536
1537         pr_debug("set_policy cpuinfo.max %u policy->max %u\n",
1538                  policy->cpuinfo.max_freq, policy->max);
1539
1540         cpu = all_cpu_data[policy->cpu];
1541         cpu->policy = policy->policy;
1542
1543         if (cpu->pstate.max_pstate_physical > cpu->pstate.max_pstate &&
1544             policy->max < policy->cpuinfo.max_freq &&
1545             policy->max > cpu->pstate.max_pstate * cpu->pstate.scaling) {
1546                 pr_debug("policy->max > max non turbo frequency\n");
1547                 policy->max = policy->cpuinfo.max_freq;
1548         }
1549
1550         if (cpu->policy == CPUFREQ_POLICY_PERFORMANCE) {
1551                 limits = &performance_limits;
1552                 if (policy->max >= policy->cpuinfo.max_freq) {
1553                         pr_debug("set performance\n");
1554                         intel_pstate_set_performance_limits(limits);
1555                         goto out;
1556                 }
1557         } else {
1558                 pr_debug("set powersave\n");
1559                 limits = &powersave_limits;
1560         }
1561
1562         limits->min_policy_pct = (policy->min * 100) / policy->cpuinfo.max_freq;
1563         limits->min_policy_pct = clamp_t(int, limits->min_policy_pct, 0 , 100);
1564         limits->max_policy_pct = DIV_ROUND_UP(policy->max * 100,
1565                                               policy->cpuinfo.max_freq);
1566         limits->max_policy_pct = clamp_t(int, limits->max_policy_pct, 0 , 100);
1567
1568         /* Normalize user input to [min_policy_pct, max_policy_pct] */
1569         limits->min_perf_pct = max(limits->min_policy_pct,
1570                                    limits->min_sysfs_pct);
1571         limits->min_perf_pct = min(limits->max_policy_pct,
1572                                    limits->min_perf_pct);
1573         limits->max_perf_pct = min(limits->max_policy_pct,
1574                                    limits->max_sysfs_pct);
1575         limits->max_perf_pct = max(limits->min_policy_pct,
1576                                    limits->max_perf_pct);
1577
1578         /* Make sure min_perf_pct <= max_perf_pct */
1579         limits->min_perf_pct = min(limits->max_perf_pct, limits->min_perf_pct);
1580
1581         limits->min_perf = div_fp(limits->min_perf_pct, 100);
1582         limits->max_perf = div_fp(limits->max_perf_pct, 100);
1583         limits->max_perf = round_up(limits->max_perf, FRAC_BITS);
1584
1585  out:
1586         if (cpu->policy == CPUFREQ_POLICY_PERFORMANCE) {
1587                 /*
1588                  * NOHZ_FULL CPUs need this as the governor callback may not
1589                  * be invoked on them.
1590                  */
1591                 intel_pstate_clear_update_util_hook(policy->cpu);
1592                 intel_pstate_max_within_limits(cpu);
1593         }
1594
1595         intel_pstate_set_update_util_hook(policy->cpu);
1596
1597         intel_pstate_hwp_set_policy(policy);
1598
1599         return 0;
1600 }
1601
1602 static int intel_pstate_verify_policy(struct cpufreq_policy *policy)
1603 {
1604         cpufreq_verify_within_cpu_limits(policy);
1605
1606         if (policy->policy != CPUFREQ_POLICY_POWERSAVE &&
1607             policy->policy != CPUFREQ_POLICY_PERFORMANCE)
1608                 return -EINVAL;
1609
1610         return 0;
1611 }
1612
1613 static void intel_pstate_stop_cpu(struct cpufreq_policy *policy)
1614 {
1615         int cpu_num = policy->cpu;
1616         struct cpudata *cpu = all_cpu_data[cpu_num];
1617
1618         pr_debug("CPU %d exiting\n", cpu_num);
1619
1620         intel_pstate_clear_update_util_hook(cpu_num);
1621
1622         if (hwp_active)
1623                 return;
1624
1625         intel_pstate_set_min_pstate(cpu);
1626 }
1627
1628 static int intel_pstate_cpu_init(struct cpufreq_policy *policy)
1629 {
1630         struct cpudata *cpu;
1631         int rc;
1632
1633         rc = intel_pstate_init_cpu(policy->cpu);
1634         if (rc)
1635                 return rc;
1636
1637         cpu = all_cpu_data[policy->cpu];
1638
1639         if (limits->min_perf_pct == 100 && limits->max_perf_pct == 100)
1640                 policy->policy = CPUFREQ_POLICY_PERFORMANCE;
1641         else
1642                 policy->policy = CPUFREQ_POLICY_POWERSAVE;
1643
1644         policy->min = cpu->pstate.min_pstate * cpu->pstate.scaling;
1645         policy->max = cpu->pstate.turbo_pstate * cpu->pstate.scaling;
1646
1647         /* cpuinfo and default policy values */
1648         policy->cpuinfo.min_freq = cpu->pstate.min_pstate * cpu->pstate.scaling;
1649         update_turbo_state();
1650         policy->cpuinfo.max_freq = limits->turbo_disabled ?
1651                         cpu->pstate.max_pstate : cpu->pstate.turbo_pstate;
1652         policy->cpuinfo.max_freq *= cpu->pstate.scaling;
1653
1654         intel_pstate_init_acpi_perf_limits(policy);
1655         policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL;
1656         cpumask_set_cpu(policy->cpu, policy->cpus);
1657
1658         return 0;
1659 }
1660
1661 static int intel_pstate_cpu_exit(struct cpufreq_policy *policy)
1662 {
1663         intel_pstate_exit_perf_limits(policy);
1664
1665         return 0;
1666 }
1667
1668 static struct cpufreq_driver intel_pstate_driver = {
1669         .flags          = CPUFREQ_CONST_LOOPS,
1670         .verify         = intel_pstate_verify_policy,
1671         .setpolicy      = intel_pstate_set_policy,
1672         .resume         = intel_pstate_hwp_set_policy,
1673         .get            = intel_pstate_get,
1674         .init           = intel_pstate_cpu_init,
1675         .exit           = intel_pstate_cpu_exit,
1676         .stop_cpu       = intel_pstate_stop_cpu,
1677         .name           = "intel_pstate",
1678 };
1679
1680 static int no_load __initdata;
1681 static int no_hwp __initdata;
1682 static int hwp_only __initdata;
1683 static unsigned int force_load __initdata;
1684
1685 static int __init intel_pstate_msrs_not_valid(void)
1686 {
1687         if (!pstate_funcs.get_max() ||
1688             !pstate_funcs.get_min() ||
1689             !pstate_funcs.get_turbo())
1690                 return -ENODEV;
1691
1692         return 0;
1693 }
1694
1695 static void __init copy_pid_params(struct pstate_adjust_policy *policy)
1696 {
1697         pid_params.sample_rate_ms = policy->sample_rate_ms;
1698         pid_params.sample_rate_ns = pid_params.sample_rate_ms * NSEC_PER_MSEC;
1699         pid_params.p_gain_pct = policy->p_gain_pct;
1700         pid_params.i_gain_pct = policy->i_gain_pct;
1701         pid_params.d_gain_pct = policy->d_gain_pct;
1702         pid_params.deadband = policy->deadband;
1703         pid_params.setpoint = policy->setpoint;
1704 }
1705
1706 static void __init copy_cpu_funcs(struct pstate_funcs *funcs)
1707 {
1708         pstate_funcs.get_max   = funcs->get_max;
1709         pstate_funcs.get_max_physical = funcs->get_max_physical;
1710         pstate_funcs.get_min   = funcs->get_min;
1711         pstate_funcs.get_turbo = funcs->get_turbo;
1712         pstate_funcs.get_scaling = funcs->get_scaling;
1713         pstate_funcs.get_val   = funcs->get_val;
1714         pstate_funcs.get_vid   = funcs->get_vid;
1715         pstate_funcs.get_target_pstate = funcs->get_target_pstate;
1716
1717 }
1718
1719 #ifdef CONFIG_ACPI
1720
1721 static bool __init intel_pstate_no_acpi_pss(void)
1722 {
1723         int i;
1724
1725         for_each_possible_cpu(i) {
1726                 acpi_status status;
1727                 union acpi_object *pss;
1728                 struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
1729                 struct acpi_processor *pr = per_cpu(processors, i);
1730
1731                 if (!pr)
1732                         continue;
1733
1734                 status = acpi_evaluate_object(pr->handle, "_PSS", NULL, &buffer);
1735                 if (ACPI_FAILURE(status))
1736                         continue;
1737
1738                 pss = buffer.pointer;
1739                 if (pss && pss->type == ACPI_TYPE_PACKAGE) {
1740                         kfree(pss);
1741                         return false;
1742                 }
1743
1744                 kfree(pss);
1745         }
1746
1747         return true;
1748 }
1749
1750 static bool __init intel_pstate_has_acpi_ppc(void)
1751 {
1752         int i;
1753
1754         for_each_possible_cpu(i) {
1755                 struct acpi_processor *pr = per_cpu(processors, i);
1756
1757                 if (!pr)
1758                         continue;
1759                 if (acpi_has_method(pr->handle, "_PPC"))
1760                         return true;
1761         }
1762         return false;
1763 }
1764
1765 enum {
1766         PSS,
1767         PPC,
1768 };
1769
1770 struct hw_vendor_info {
1771         u16  valid;
1772         char oem_id[ACPI_OEM_ID_SIZE];
1773         char oem_table_id[ACPI_OEM_TABLE_ID_SIZE];
1774         int  oem_pwr_table;
1775 };
1776
1777 /* Hardware vendor-specific info that has its own power management modes */
1778 static struct hw_vendor_info vendor_info[] __initdata = {
1779         {1, "HP    ", "ProLiant", PSS},
1780         {1, "ORACLE", "X4-2    ", PPC},
1781         {1, "ORACLE", "X4-2L   ", PPC},
1782         {1, "ORACLE", "X4-2B   ", PPC},
1783         {1, "ORACLE", "X3-2    ", PPC},
1784         {1, "ORACLE", "X3-2L   ", PPC},
1785         {1, "ORACLE", "X3-2B   ", PPC},
1786         {1, "ORACLE", "X4470M2 ", PPC},
1787         {1, "ORACLE", "X4270M3 ", PPC},
1788         {1, "ORACLE", "X4270M2 ", PPC},
1789         {1, "ORACLE", "X4170M2 ", PPC},
1790         {1, "ORACLE", "X4170 M3", PPC},
1791         {1, "ORACLE", "X4275 M3", PPC},
1792         {1, "ORACLE", "X6-2    ", PPC},
1793         {1, "ORACLE", "Sudbury ", PPC},
1794         {0, "", ""},
1795 };
1796
1797 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
1798 {
1799         struct acpi_table_header hdr;
1800         struct hw_vendor_info *v_info;
1801         const struct x86_cpu_id *id;
1802         u64 misc_pwr;
1803
1804         id = x86_match_cpu(intel_pstate_cpu_oob_ids);
1805         if (id) {
1806                 rdmsrl(MSR_MISC_PWR_MGMT, misc_pwr);
1807                 if ( misc_pwr & (1 << 8))
1808                         return true;
1809         }
1810
1811         if (acpi_disabled ||
1812             ACPI_FAILURE(acpi_get_table_header(ACPI_SIG_FADT, 0, &hdr)))
1813                 return false;
1814
1815         for (v_info = vendor_info; v_info->valid; v_info++) {
1816                 if (!strncmp(hdr.oem_id, v_info->oem_id, ACPI_OEM_ID_SIZE) &&
1817                         !strncmp(hdr.oem_table_id, v_info->oem_table_id,
1818                                                 ACPI_OEM_TABLE_ID_SIZE))
1819                         switch (v_info->oem_pwr_table) {
1820                         case PSS:
1821                                 return intel_pstate_no_acpi_pss();
1822                         case PPC:
1823                                 return intel_pstate_has_acpi_ppc() &&
1824                                         (!force_load);
1825                         }
1826         }
1827
1828         return false;
1829 }
1830 #else /* CONFIG_ACPI not enabled */
1831 static inline bool intel_pstate_platform_pwr_mgmt_exists(void) { return false; }
1832 static inline bool intel_pstate_has_acpi_ppc(void) { return false; }
1833 #endif /* CONFIG_ACPI */
1834
1835 static const struct x86_cpu_id hwp_support_ids[] __initconst = {
1836         { X86_VENDOR_INTEL, 6, X86_MODEL_ANY, X86_FEATURE_HWP },
1837         {}
1838 };
1839
1840 static int __init intel_pstate_init(void)
1841 {
1842         int cpu, rc = 0;
1843         const struct x86_cpu_id *id;
1844         struct cpu_defaults *cpu_def;
1845
1846         if (no_load)
1847                 return -ENODEV;
1848
1849         if (x86_match_cpu(hwp_support_ids) && !no_hwp) {
1850                 copy_cpu_funcs(&core_params.funcs);
1851                 hwp_active++;
1852                 goto hwp_cpu_matched;
1853         }
1854
1855         id = x86_match_cpu(intel_pstate_cpu_ids);
1856         if (!id)
1857                 return -ENODEV;
1858
1859         cpu_def = (struct cpu_defaults *)id->driver_data;
1860
1861         copy_pid_params(&cpu_def->pid_policy);
1862         copy_cpu_funcs(&cpu_def->funcs);
1863
1864         if (intel_pstate_msrs_not_valid())
1865                 return -ENODEV;
1866
1867 hwp_cpu_matched:
1868         /*
1869          * The Intel pstate driver will be ignored if the platform
1870          * firmware has its own power management modes.
1871          */
1872         if (intel_pstate_platform_pwr_mgmt_exists())
1873                 return -ENODEV;
1874
1875         pr_info("Intel P-state driver initializing\n");
1876
1877         all_cpu_data = vzalloc(sizeof(void *) * num_possible_cpus());
1878         if (!all_cpu_data)
1879                 return -ENOMEM;
1880
1881         if (!hwp_active && hwp_only)
1882                 goto out;
1883
1884         rc = cpufreq_register_driver(&intel_pstate_driver);
1885         if (rc)
1886                 goto out;
1887
1888         intel_pstate_debug_expose_params();
1889         intel_pstate_sysfs_expose_params();
1890
1891         if (hwp_active)
1892                 pr_info("HWP enabled\n");
1893
1894         return rc;
1895 out:
1896         get_online_cpus();
1897         for_each_online_cpu(cpu) {
1898                 if (all_cpu_data[cpu]) {
1899                         intel_pstate_clear_update_util_hook(cpu);
1900                         kfree(all_cpu_data[cpu]);
1901                 }
1902         }
1903
1904         put_online_cpus();
1905         vfree(all_cpu_data);
1906         return -ENODEV;
1907 }
1908 device_initcall(intel_pstate_init);
1909
1910 static int __init intel_pstate_setup(char *str)
1911 {
1912         if (!str)
1913                 return -EINVAL;
1914
1915         if (!strcmp(str, "disable"))
1916                 no_load = 1;
1917         if (!strcmp(str, "no_hwp")) {
1918                 pr_info("HWP disabled\n");
1919                 no_hwp = 1;
1920         }
1921         if (!strcmp(str, "force"))
1922                 force_load = 1;
1923         if (!strcmp(str, "hwp_only"))
1924                 hwp_only = 1;
1925
1926 #ifdef CONFIG_ACPI
1927         if (!strcmp(str, "support_acpi_ppc"))
1928                 acpi_ppc = true;
1929 #endif
1930
1931         return 0;
1932 }
1933 early_param("intel_pstate", intel_pstate_setup);
1934
1935 MODULE_AUTHOR("Dirk Brandewie <dirk.j.brandewie@intel.com>");
1936 MODULE_DESCRIPTION("'intel_pstate' - P state driver Intel Core processors");
1937 MODULE_LICENSE("GPL");