2 * intel_powerclamp.c - package c-state idle injection
4 * Copyright (c) 2012, Intel Corporation.
7 * Arjan van de Ven <arjan@linux.intel.com>
8 * Jacob Pan <jacob.jun.pan@linux.intel.com>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms and conditions of the GNU General Public License,
12 * version 2, as published by the Free Software Foundation.
14 * This program is distributed in the hope it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19 * You should have received a copy of the GNU General Public License along with
20 * this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
25 * 1. better handle wakeup from external interrupts, currently a fixed
26 * compensation is added to clamping duration when excessive amount
27 * of wakeups are observed during idle time. the reason is that in
28 * case of external interrupts without need for ack, clamping down
29 * cpu in non-irq context does not reduce irq. for majority of the
30 * cases, clamping down cpu does help reduce irq as well, we should
31 * be able to differenciate the two cases and give a quantitative
32 * solution for the irqs that we can control. perhaps based on
33 * get_cpu_iowait_time_us()
35 * 2. synchronization with other hw blocks
40 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
42 #include <linux/module.h>
43 #include <linux/kernel.h>
44 #include <linux/delay.h>
45 #include <linux/kthread.h>
46 #include <linux/freezer.h>
47 #include <linux/cpu.h>
48 #include <linux/thermal.h>
49 #include <linux/slab.h>
50 #include <linux/tick.h>
51 #include <linux/debugfs.h>
52 #include <linux/seq_file.h>
53 #include <linux/sched/rt.h>
57 #include <asm/mwait.h>
58 #include <asm/cpu_device_id.h>
60 #include <asm/hardirq.h>
62 #define MAX_TARGET_RATIO (50U)
63 /* For each undisturbed clamping period (no extra wake ups during idle time),
64 * we increment the confidence counter for the given target ratio.
65 * CONFIDENCE_OK defines the level where runtime calibration results are
68 #define CONFIDENCE_OK (3)
69 /* Default idle injection duration, driver adjust sleep time to meet target
70 * idle ratio. Similar to frequency modulation.
72 #define DEFAULT_DURATION_JIFFIES (6)
74 static unsigned int target_mwait
;
75 static struct dentry
*debug_dir
;
77 /* user selected target */
78 static unsigned int set_target_ratio
;
79 static unsigned int current_ratio
;
80 static bool should_skip
;
81 static bool reduce_irq
;
82 static atomic_t idle_wakeup_counter
;
83 static unsigned int control_cpu
; /* The cpu assigned to collect stat and update
84 * control parameters. default to BSP but BSP
90 static struct task_struct
* __percpu
*powerclamp_thread
;
91 static struct thermal_cooling_device
*cooling_dev
;
92 static unsigned long *cpu_clamping_mask
; /* bit map for tracking per cpu
96 static unsigned int duration
;
97 static unsigned int pkg_cstate_ratio_cur
;
98 static unsigned int window_size
;
100 static int duration_set(const char *arg
, const struct kernel_param
*kp
)
103 unsigned long new_duration
;
105 ret
= kstrtoul(arg
, 10, &new_duration
);
108 if (new_duration
> 25 || new_duration
< 6) {
109 pr_err("Out of recommended range %lu, between 6-25ms\n",
114 duration
= clamp(new_duration
, 6ul, 25ul);
122 static struct kernel_param_ops duration_ops
= {
124 .get
= param_get_int
,
128 module_param_cb(duration
, &duration_ops
, &duration
, 0644);
129 MODULE_PARM_DESC(duration
, "forced idle time for each attempt in msec.");
131 struct powerclamp_calibration_data
{
132 unsigned long confidence
; /* used for calibration, basically a counter
133 * gets incremented each time a clamping
134 * period is completed without extra wakeups
135 * once that counter is reached given level,
136 * compensation is deemed usable.
138 unsigned long steady_comp
; /* steady state compensation used when
139 * no extra wakeups occurred.
141 unsigned long dynamic_comp
; /* compensate excessive wakeup from idle
142 * mostly from external interrupts.
146 static struct powerclamp_calibration_data cal_data
[MAX_TARGET_RATIO
];
148 static int window_size_set(const char *arg
, const struct kernel_param
*kp
)
151 unsigned long new_window_size
;
153 ret
= kstrtoul(arg
, 10, &new_window_size
);
156 if (new_window_size
> 10 || new_window_size
< 2) {
157 pr_err("Out of recommended window size %lu, between 2-10\n",
162 window_size
= clamp(new_window_size
, 2ul, 10ul);
170 static struct kernel_param_ops window_size_ops
= {
171 .set
= window_size_set
,
172 .get
= param_get_int
,
175 module_param_cb(window_size
, &window_size_ops
, &window_size
, 0644);
176 MODULE_PARM_DESC(window_size
, "sliding window in number of clamping cycles\n"
177 "\tpowerclamp controls idle ratio within this window. larger\n"
178 "\twindow size results in slower response time but more smooth\n"
179 "\tclamping results. default to 2.");
181 static void find_target_mwait(void)
183 unsigned int eax
, ebx
, ecx
, edx
;
184 unsigned int highest_cstate
= 0;
185 unsigned int highest_subcstate
= 0;
188 if (boot_cpu_data
.cpuid_level
< CPUID_MWAIT_LEAF
)
191 cpuid(CPUID_MWAIT_LEAF
, &eax
, &ebx
, &ecx
, &edx
);
193 if (!(ecx
& CPUID5_ECX_EXTENSIONS_SUPPORTED
) ||
194 !(ecx
& CPUID5_ECX_INTERRUPT_BREAK
))
197 edx
>>= MWAIT_SUBSTATE_SIZE
;
198 for (i
= 0; i
< 7 && edx
; i
++, edx
>>= MWAIT_SUBSTATE_SIZE
) {
199 if (edx
& MWAIT_SUBSTATE_MASK
) {
201 highest_subcstate
= edx
& MWAIT_SUBSTATE_MASK
;
204 target_mwait
= (highest_cstate
<< MWAIT_SUBSTATE_SIZE
) |
205 (highest_subcstate
- 1);
209 static u64
pkg_state_counter(void)
220 if (!rdmsrl_safe(MSR_PKG_C2_RESIDENCY
, &val
))
227 if (!rdmsrl_safe(MSR_PKG_C3_RESIDENCY
, &val
))
234 if (!rdmsrl_safe(MSR_PKG_C6_RESIDENCY
, &val
))
241 if (!rdmsrl_safe(MSR_PKG_C7_RESIDENCY
, &val
))
250 static void noop_timer(unsigned long foo
)
252 /* empty... just the fact that we get the interrupt wakes us up */
255 static unsigned int get_compensation(int ratio
)
257 unsigned int comp
= 0;
259 /* we only use compensation if all adjacent ones are good */
261 cal_data
[ratio
].confidence
>= CONFIDENCE_OK
&&
262 cal_data
[ratio
+ 1].confidence
>= CONFIDENCE_OK
&&
263 cal_data
[ratio
+ 2].confidence
>= CONFIDENCE_OK
) {
264 comp
= (cal_data
[ratio
].steady_comp
+
265 cal_data
[ratio
+ 1].steady_comp
+
266 cal_data
[ratio
+ 2].steady_comp
) / 3;
267 } else if (ratio
== MAX_TARGET_RATIO
- 1 &&
268 cal_data
[ratio
].confidence
>= CONFIDENCE_OK
&&
269 cal_data
[ratio
- 1].confidence
>= CONFIDENCE_OK
&&
270 cal_data
[ratio
- 2].confidence
>= CONFIDENCE_OK
) {
271 comp
= (cal_data
[ratio
].steady_comp
+
272 cal_data
[ratio
- 1].steady_comp
+
273 cal_data
[ratio
- 2].steady_comp
) / 3;
274 } else if (cal_data
[ratio
].confidence
>= CONFIDENCE_OK
&&
275 cal_data
[ratio
- 1].confidence
>= CONFIDENCE_OK
&&
276 cal_data
[ratio
+ 1].confidence
>= CONFIDENCE_OK
) {
277 comp
= (cal_data
[ratio
].steady_comp
+
278 cal_data
[ratio
- 1].steady_comp
+
279 cal_data
[ratio
+ 1].steady_comp
) / 3;
282 /* REVISIT: simple penalty of double idle injection */
285 /* do not exceed limit */
286 if (comp
+ ratio
>= MAX_TARGET_RATIO
)
287 comp
= MAX_TARGET_RATIO
- ratio
- 1;
292 static void adjust_compensation(int target_ratio
, unsigned int win
)
295 struct powerclamp_calibration_data
*d
= &cal_data
[target_ratio
];
298 * adjust compensations if confidence level has not been reached or
299 * there are too many wakeups during the last idle injection period, we
300 * cannot trust the data for compensation.
302 if (d
->confidence
>= CONFIDENCE_OK
||
303 atomic_read(&idle_wakeup_counter
) >
304 win
* num_online_cpus())
307 delta
= set_target_ratio
- current_ratio
;
308 /* filter out bad data */
309 if (delta
>= 0 && delta
<= (1+target_ratio
/10)) {
312 roundup(delta
+d
->steady_comp
, 2)/2;
314 d
->steady_comp
= delta
;
319 static bool powerclamp_adjust_controls(unsigned int target_ratio
,
320 unsigned int guard
, unsigned int win
)
322 static u64 msr_last
, tsc_last
;
323 u64 msr_now
, tsc_now
;
326 /* check result for the last window */
327 msr_now
= pkg_state_counter();
330 /* calculate pkg cstate vs tsc ratio */
331 if (!msr_last
|| !tsc_last
)
333 else if (tsc_now
-tsc_last
) {
334 val64
= 100*(msr_now
-msr_last
);
335 do_div(val64
, (tsc_now
-tsc_last
));
336 current_ratio
= val64
;
343 adjust_compensation(target_ratio
, win
);
345 * too many external interrupts, set flag such
346 * that we can take measure later.
348 reduce_irq
= atomic_read(&idle_wakeup_counter
) >=
349 2 * win
* num_online_cpus();
351 atomic_set(&idle_wakeup_counter
, 0);
352 /* if we are above target+guard, skip */
353 return set_target_ratio
+ guard
<= current_ratio
;
356 static int clamp_thread(void *arg
)
358 int cpunr
= (unsigned long)arg
;
359 DEFINE_TIMER(wakeup_timer
, noop_timer
, 0, 0);
360 static const struct sched_param param
= {
361 .sched_priority
= MAX_USER_RT_PRIO
/2,
363 unsigned int count
= 0;
364 unsigned int target_ratio
;
366 set_bit(cpunr
, cpu_clamping_mask
);
368 init_timer_on_stack(&wakeup_timer
);
369 sched_setscheduler(current
, SCHED_FIFO
, ¶m
);
371 while (true == clamping
&& !kthread_should_stop() &&
374 unsigned long target_jiffies
;
376 unsigned int compensation
= 0;
377 int interval
; /* jiffies to sleep for each attempt */
378 unsigned int duration_jiffies
= msecs_to_jiffies(duration
);
379 unsigned int window_size_now
;
383 * make sure user selected ratio does not take effect until
384 * the next round. adjust target_ratio if user has changed
385 * target such that we can converge quickly.
387 target_ratio
= set_target_ratio
;
388 guard
= 1 + target_ratio
/20;
389 window_size_now
= window_size
;
393 * systems may have different ability to enter package level
394 * c-states, thus we need to compensate the injected idle ratio
395 * to achieve the actual target reported by the HW.
397 compensation
= get_compensation(target_ratio
);
398 interval
= duration_jiffies
*100/(target_ratio
+compensation
);
400 /* align idle time */
401 target_jiffies
= roundup(jiffies
, interval
);
402 sleeptime
= target_jiffies
- jiffies
;
405 schedule_timeout_interruptible(sleeptime
);
407 * only elected controlling cpu can collect stats and update
408 * control parameters.
410 if (cpunr
== control_cpu
&& !(count
%window_size_now
)) {
412 powerclamp_adjust_controls(target_ratio
,
413 guard
, window_size_now
);
420 target_jiffies
= jiffies
+ duration_jiffies
;
421 mod_timer(&wakeup_timer
, target_jiffies
);
422 if (unlikely(local_softirq_pending()))
425 * stop tick sched during idle time, interrupts are still
426 * allowed. thus jiffies are updated properly.
429 /* mwait until target jiffies is reached */
430 while (time_before(jiffies
, target_jiffies
)) {
431 unsigned long ecx
= 1;
432 unsigned long eax
= target_mwait
;
435 * REVISIT: may call enter_idle() to notify drivers who
436 * can save power during cpu idle. same for exit_idle()
439 stop_critical_timings();
440 __monitor((void *)¤t_thread_info()->flags
, 0, 0);
441 cpu_relax(); /* allow HT sibling to run */
443 start_critical_timings();
444 atomic_inc(&idle_wakeup_counter
);
446 preempt_enable_no_resched();
448 del_timer_sync(&wakeup_timer
);
449 clear_bit(cpunr
, cpu_clamping_mask
);
455 * 1 HZ polling while clamping is active, useful for userspace
456 * to monitor actual idle ratio.
458 static void poll_pkg_cstate(struct work_struct
*dummy
);
459 static DECLARE_DELAYED_WORK(poll_pkg_cstate_work
, poll_pkg_cstate
);
460 static void poll_pkg_cstate(struct work_struct
*dummy
)
464 static unsigned long jiffies_last
;
467 unsigned long jiffies_now
;
471 msr_now
= pkg_state_counter();
473 jiffies_now
= jiffies
;
475 /* calculate pkg cstate vs tsc ratio */
476 if (!msr_last
|| !tsc_last
)
477 pkg_cstate_ratio_cur
= 1;
479 if (tsc_now
- tsc_last
) {
480 val64
= 100 * (msr_now
- msr_last
);
481 do_div(val64
, (tsc_now
- tsc_last
));
482 pkg_cstate_ratio_cur
= val64
;
488 jiffies_last
= jiffies_now
;
491 if (true == clamping
)
492 schedule_delayed_work(&poll_pkg_cstate_work
, HZ
);
495 static int start_power_clamp(void)
498 struct task_struct
*thread
;
500 /* check if pkg cstate counter is completely 0, abort in this case */
501 if (!pkg_state_counter()) {
502 pr_err("pkg cstate counter not functional, abort\n");
506 set_target_ratio
= clamp(set_target_ratio
, 0U, MAX_TARGET_RATIO
- 1);
507 /* prevent cpu hotplug */
512 if (!cpu_online(control_cpu
))
513 control_cpu
= smp_processor_id();
516 schedule_delayed_work(&poll_pkg_cstate_work
, 0);
518 /* start one thread per online cpu */
519 for_each_online_cpu(cpu
) {
520 struct task_struct
**p
=
521 per_cpu_ptr(powerclamp_thread
, cpu
);
523 thread
= kthread_create_on_node(clamp_thread
,
526 "kidle_inject/%ld", cpu
);
527 /* bind to cpu here */
528 if (likely(!IS_ERR(thread
))) {
529 kthread_bind(thread
, cpu
);
530 wake_up_process(thread
);
540 static void end_power_clamp(void)
543 struct task_struct
*thread
;
547 * make clamping visible to other cpus and give per cpu clamping threads
548 * sometime to exit, or gets killed later.
552 if (bitmap_weight(cpu_clamping_mask
, num_possible_cpus())) {
553 for_each_set_bit(i
, cpu_clamping_mask
, num_possible_cpus()) {
554 pr_debug("clamping thread for cpu %d alive, kill\n", i
);
555 thread
= *per_cpu_ptr(powerclamp_thread
, i
);
556 kthread_stop(thread
);
561 static int powerclamp_cpu_callback(struct notifier_block
*nfb
,
562 unsigned long action
, void *hcpu
)
564 unsigned long cpu
= (unsigned long)hcpu
;
565 struct task_struct
*thread
;
566 struct task_struct
**percpu_thread
=
567 per_cpu_ptr(powerclamp_thread
, cpu
);
569 if (false == clamping
)
574 thread
= kthread_create_on_node(clamp_thread
,
577 "kidle_inject/%lu", cpu
);
578 if (likely(!IS_ERR(thread
))) {
579 kthread_bind(thread
, cpu
);
580 wake_up_process(thread
);
581 *percpu_thread
= thread
;
583 /* prefer BSP as controlling CPU */
590 if (test_bit(cpu
, cpu_clamping_mask
)) {
591 pr_err("cpu %lu dead but powerclamping thread is not\n",
593 kthread_stop(*percpu_thread
);
595 if (cpu
== control_cpu
) {
596 control_cpu
= smp_processor_id();
605 static struct notifier_block powerclamp_cpu_notifier
= {
606 .notifier_call
= powerclamp_cpu_callback
,
609 static int powerclamp_get_max_state(struct thermal_cooling_device
*cdev
,
610 unsigned long *state
)
612 *state
= MAX_TARGET_RATIO
;
617 static int powerclamp_get_cur_state(struct thermal_cooling_device
*cdev
,
618 unsigned long *state
)
620 if (true == clamping
)
621 *state
= pkg_cstate_ratio_cur
;
623 /* to save power, do not poll idle ratio while not clamping */
624 *state
= -1; /* indicates invalid state */
629 static int powerclamp_set_cur_state(struct thermal_cooling_device
*cdev
,
630 unsigned long new_target_ratio
)
634 new_target_ratio
= clamp(new_target_ratio
, 0UL,
635 (unsigned long) (MAX_TARGET_RATIO
-1));
636 if (set_target_ratio
== 0 && new_target_ratio
> 0) {
637 pr_info("Start idle injection to reduce power\n");
638 set_target_ratio
= new_target_ratio
;
639 ret
= start_power_clamp();
641 } else if (set_target_ratio
> 0 && new_target_ratio
== 0) {
642 pr_info("Stop forced idle injection\n");
643 set_target_ratio
= 0;
645 } else /* adjust currently running */ {
646 set_target_ratio
= new_target_ratio
;
647 /* make new set_target_ratio visible to other cpus */
655 /* bind to generic thermal layer as cooling device*/
656 static struct thermal_cooling_device_ops powerclamp_cooling_ops
= {
657 .get_max_state
= powerclamp_get_max_state
,
658 .get_cur_state
= powerclamp_get_cur_state
,
659 .set_cur_state
= powerclamp_set_cur_state
,
662 /* runs on Nehalem and later */
663 static const struct x86_cpu_id intel_powerclamp_ids
[] = {
664 { X86_VENDOR_INTEL
, 6, 0x1a},
665 { X86_VENDOR_INTEL
, 6, 0x1c},
666 { X86_VENDOR_INTEL
, 6, 0x1e},
667 { X86_VENDOR_INTEL
, 6, 0x1f},
668 { X86_VENDOR_INTEL
, 6, 0x25},
669 { X86_VENDOR_INTEL
, 6, 0x26},
670 { X86_VENDOR_INTEL
, 6, 0x2a},
671 { X86_VENDOR_INTEL
, 6, 0x2c},
672 { X86_VENDOR_INTEL
, 6, 0x2d},
673 { X86_VENDOR_INTEL
, 6, 0x2e},
674 { X86_VENDOR_INTEL
, 6, 0x2f},
675 { X86_VENDOR_INTEL
, 6, 0x3a},
678 MODULE_DEVICE_TABLE(x86cpu
, intel_powerclamp_ids
);
680 static int powerclamp_probe(void)
682 if (!x86_match_cpu(intel_powerclamp_ids
)) {
683 pr_err("Intel powerclamp does not run on family %d model %d\n",
684 boot_cpu_data
.x86
, boot_cpu_data
.x86_model
);
687 if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC
) ||
688 !boot_cpu_has(X86_FEATURE_CONSTANT_TSC
) ||
689 !boot_cpu_has(X86_FEATURE_MWAIT
) ||
690 !boot_cpu_has(X86_FEATURE_ARAT
))
693 /* find the deepest mwait value */
699 static int powerclamp_debug_show(struct seq_file
*m
, void *unused
)
703 seq_printf(m
, "controlling cpu: %d\n", control_cpu
);
704 seq_printf(m
, "pct confidence steady dynamic (compensation)\n");
705 for (i
= 0; i
< MAX_TARGET_RATIO
; i
++) {
706 seq_printf(m
, "%d\t%lu\t%lu\t%lu\n",
708 cal_data
[i
].confidence
,
709 cal_data
[i
].steady_comp
,
710 cal_data
[i
].dynamic_comp
);
716 static int powerclamp_debug_open(struct inode
*inode
,
719 return single_open(file
, powerclamp_debug_show
, inode
->i_private
);
722 static const struct file_operations powerclamp_debug_fops
= {
723 .open
= powerclamp_debug_open
,
726 .release
= single_release
,
727 .owner
= THIS_MODULE
,
730 static inline void powerclamp_create_debug_files(void)
732 debug_dir
= debugfs_create_dir("intel_powerclamp", NULL
);
736 if (!debugfs_create_file("powerclamp_calib", S_IRUGO
, debug_dir
,
737 cal_data
, &powerclamp_debug_fops
))
743 debugfs_remove_recursive(debug_dir
);
746 static int powerclamp_init(void)
751 bitmap_size
= BITS_TO_LONGS(num_possible_cpus()) * sizeof(long);
752 cpu_clamping_mask
= kzalloc(bitmap_size
, GFP_KERNEL
);
753 if (!cpu_clamping_mask
)
756 /* probe cpu features and ids here */
757 retval
= powerclamp_probe();
760 /* set default limit, maybe adjusted during runtime based on feedback */
762 register_hotcpu_notifier(&powerclamp_cpu_notifier
);
763 powerclamp_thread
= alloc_percpu(struct task_struct
*);
764 cooling_dev
= thermal_cooling_device_register("intel_powerclamp", NULL
,
765 &powerclamp_cooling_ops
);
766 if (IS_ERR(cooling_dev
))
770 duration
= jiffies_to_msecs(DEFAULT_DURATION_JIFFIES
);
771 powerclamp_create_debug_files();
775 module_init(powerclamp_init
);
777 static void powerclamp_exit(void)
779 unregister_hotcpu_notifier(&powerclamp_cpu_notifier
);
781 free_percpu(powerclamp_thread
);
782 thermal_cooling_device_unregister(cooling_dev
);
783 kfree(cpu_clamping_mask
);
785 cancel_delayed_work_sync(&poll_pkg_cstate_work
);
786 debugfs_remove_recursive(debug_dir
);
788 module_exit(powerclamp_exit
);
790 MODULE_LICENSE("GPL");
791 MODULE_AUTHOR("Arjan van de Ven <arjan@linux.intel.com>");
792 MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@linux.intel.com>");
793 MODULE_DESCRIPTION("Package Level C-state Idle Injection for Intel CPUs");