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