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