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