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