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