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