intel_ips: blacklist HP ProBook laptops
[pandora-kernel.git] / drivers / platform / x86 / intel_ips.c
1 /*
2  * Copyright (c) 2009-2010 Intel Corporation
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
16  *
17  * The full GNU General Public License is included in this distribution in
18  * the file called "COPYING".
19  *
20  * Authors:
21  *      Jesse Barnes <jbarnes@virtuousgeek.org>
22  */
23
24 /*
25  * Some Intel Ibex Peak based platforms support so-called "intelligent
26  * power sharing", which allows the CPU and GPU to cooperate to maximize
27  * performance within a given TDP (thermal design point).  This driver
28  * performs the coordination between the CPU and GPU, monitors thermal and
29  * power statistics in the platform, and initializes power monitoring
30  * hardware.  It also provides a few tunables to control behavior.  Its
31  * primary purpose is to safely allow CPU and GPU turbo modes to be enabled
32  * by tracking power and thermal budget; secondarily it can boost turbo
33  * performance by allocating more power or thermal budget to the CPU or GPU
34  * based on available headroom and activity.
35  *
36  * The basic algorithm is driven by a 5s moving average of tempurature.  If
37  * thermal headroom is available, the CPU and/or GPU power clamps may be
38  * adjusted upwards.  If we hit the thermal ceiling or a thermal trigger,
39  * we scale back the clamp.  Aside from trigger events (when we're critically
40  * close or over our TDP) we don't adjust the clamps more than once every
41  * five seconds.
42  *
43  * The thermal device (device 31, function 6) has a set of registers that
44  * are updated by the ME firmware.  The ME should also take the clamp values
45  * written to those registers and write them to the CPU, but we currently
46  * bypass that functionality and write the CPU MSR directly.
47  *
48  * UNSUPPORTED:
49  *   - dual MCP configs
50  *
51  * TODO:
52  *   - handle CPU hotplug
53  *   - provide turbo enable/disable api
54  *
55  * Related documents:
56  *   - CDI 403777, 403778 - Auburndale EDS vol 1 & 2
57  *   - CDI 401376 - Ibex Peak EDS
58  *   - ref 26037, 26641 - IPS BIOS spec
59  *   - ref 26489 - Nehalem BIOS writer's guide
60  *   - ref 26921 - Ibex Peak BIOS Specification
61  */
62
63 #include <linux/debugfs.h>
64 #include <linux/delay.h>
65 #include <linux/interrupt.h>
66 #include <linux/kernel.h>
67 #include <linux/kthread.h>
68 #include <linux/module.h>
69 #include <linux/pci.h>
70 #include <linux/sched.h>
71 #include <linux/seq_file.h>
72 #include <linux/string.h>
73 #include <linux/tick.h>
74 #include <linux/timer.h>
75 #include <linux/dmi.h>
76 #include <drm/i915_drm.h>
77 #include <asm/msr.h>
78 #include <asm/processor.h>
79 #include "intel_ips.h"
80
81 #define PCI_DEVICE_ID_INTEL_THERMAL_SENSOR 0x3b32
82
83 /*
84  * Package level MSRs for monitor/control
85  */
86 #define PLATFORM_INFO   0xce
87 #define   PLATFORM_TDP          (1<<29)
88 #define   PLATFORM_RATIO        (1<<28)
89
90 #define IA32_MISC_ENABLE        0x1a0
91 #define   IA32_MISC_TURBO_EN    (1ULL<<38)
92
93 #define TURBO_POWER_CURRENT_LIMIT       0x1ac
94 #define   TURBO_TDC_OVR_EN      (1UL<<31)
95 #define   TURBO_TDC_MASK        (0x000000007fff0000UL)
96 #define   TURBO_TDC_SHIFT       (16)
97 #define   TURBO_TDP_OVR_EN      (1UL<<15)
98 #define   TURBO_TDP_MASK        (0x0000000000003fffUL)
99
100 /*
101  * Core/thread MSRs for monitoring
102  */
103 #define IA32_PERF_CTL           0x199
104 #define   IA32_PERF_TURBO_DIS   (1ULL<<32)
105
106 /*
107  * Thermal PCI device regs
108  */
109 #define THM_CFG_TBAR    0x10
110 #define THM_CFG_TBAR_HI 0x14
111
112 #define THM_TSIU        0x00
113 #define THM_TSE         0x01
114 #define   TSE_EN        0xb8
115 #define THM_TSS         0x02
116 #define THM_TSTR        0x03
117 #define THM_TSTTP       0x04
118 #define THM_TSCO        0x08
119 #define THM_TSES        0x0c
120 #define THM_TSGPEN      0x0d
121 #define   TSGPEN_HOT_LOHI       (1<<1)
122 #define   TSGPEN_CRIT_LOHI      (1<<2)
123 #define THM_TSPC        0x0e
124 #define THM_PPEC        0x10
125 #define THM_CTA         0x12
126 #define THM_PTA         0x14
127 #define   PTA_SLOPE_MASK        (0xff00)
128 #define   PTA_SLOPE_SHIFT       8
129 #define   PTA_OFFSET_MASK       (0x00ff)
130 #define THM_MGTA        0x16
131 #define   MGTA_SLOPE_MASK       (0xff00)
132 #define   MGTA_SLOPE_SHIFT      8
133 #define   MGTA_OFFSET_MASK      (0x00ff)
134 #define THM_TRC         0x1a
135 #define   TRC_CORE2_EN  (1<<15)
136 #define   TRC_THM_EN    (1<<12)
137 #define   TRC_C6_WAR    (1<<8)
138 #define   TRC_CORE1_EN  (1<<7)
139 #define   TRC_CORE_PWR  (1<<6)
140 #define   TRC_PCH_EN    (1<<5)
141 #define   TRC_MCH_EN    (1<<4)
142 #define   TRC_DIMM4     (1<<3)
143 #define   TRC_DIMM3     (1<<2)
144 #define   TRC_DIMM2     (1<<1)
145 #define   TRC_DIMM1     (1<<0)
146 #define THM_TES         0x20
147 #define THM_TEN         0x21
148 #define   TEN_UPDATE_EN 1
149 #define THM_PSC         0x24
150 #define   PSC_NTG       (1<<0) /* No GFX turbo support */
151 #define   PSC_NTPC      (1<<1) /* No CPU turbo support */
152 #define   PSC_PP_DEF    (0<<2) /* Perf policy up to driver */
153 #define   PSP_PP_PC     (1<<2) /* BIOS prefers CPU perf */
154 #define   PSP_PP_BAL    (2<<2) /* BIOS wants balanced perf */
155 #define   PSP_PP_GFX    (3<<2) /* BIOS prefers GFX perf */
156 #define   PSP_PBRT      (1<<4) /* BIOS run time support */
157 #define THM_CTV1        0x30
158 #define   CTV_TEMP_ERROR (1<<15)
159 #define   CTV_TEMP_MASK 0x3f
160 #define   CTV_
161 #define THM_CTV2        0x32
162 #define THM_CEC         0x34 /* undocumented power accumulator in joules */
163 #define THM_AE          0x3f
164 #define THM_HTS         0x50 /* 32 bits */
165 #define   HTS_PCPL_MASK (0x7fe00000)
166 #define   HTS_PCPL_SHIFT 21
167 #define   HTS_GPL_MASK  (0x001ff000)
168 #define   HTS_GPL_SHIFT 12
169 #define   HTS_PP_MASK   (0x00000c00)
170 #define   HTS_PP_SHIFT  10
171 #define   HTS_PP_DEF    0
172 #define   HTS_PP_PROC   1
173 #define   HTS_PP_BAL    2
174 #define   HTS_PP_GFX    3
175 #define   HTS_PCTD_DIS  (1<<9)
176 #define   HTS_GTD_DIS   (1<<8)
177 #define   HTS_PTL_MASK  (0x000000fe)
178 #define   HTS_PTL_SHIFT 1
179 #define   HTS_NVV       (1<<0)
180 #define THM_HTSHI       0x54 /* 16 bits */
181 #define   HTS2_PPL_MASK         (0x03ff)
182 #define   HTS2_PRST_MASK        (0x3c00)
183 #define   HTS2_PRST_SHIFT       10
184 #define   HTS2_PRST_UNLOADED    0
185 #define   HTS2_PRST_RUNNING     1
186 #define   HTS2_PRST_TDISOP      2 /* turbo disabled due to power */
187 #define   HTS2_PRST_TDISHT      3 /* turbo disabled due to high temp */
188 #define   HTS2_PRST_TDISUSR     4 /* user disabled turbo */
189 #define   HTS2_PRST_TDISPLAT    5 /* platform disabled turbo */
190 #define   HTS2_PRST_TDISPM      6 /* power management disabled turbo */
191 #define   HTS2_PRST_TDISERR     7 /* some kind of error disabled turbo */
192 #define THM_PTL         0x56
193 #define THM_MGTV        0x58
194 #define   TV_MASK       0x000000000000ff00
195 #define   TV_SHIFT      8
196 #define THM_PTV         0x60
197 #define   PTV_MASK      0x00ff
198 #define THM_MMGPC       0x64
199 #define THM_MPPC        0x66
200 #define THM_MPCPC       0x68
201 #define THM_TSPIEN      0x82
202 #define   TSPIEN_AUX_LOHI       (1<<0)
203 #define   TSPIEN_HOT_LOHI       (1<<1)
204 #define   TSPIEN_CRIT_LOHI      (1<<2)
205 #define   TSPIEN_AUX2_LOHI      (1<<3)
206 #define THM_TSLOCK      0x83
207 #define THM_ATR         0x84
208 #define THM_TOF         0x87
209 #define THM_STS         0x98
210 #define   STS_PCPL_MASK         (0x7fe00000)
211 #define   STS_PCPL_SHIFT        21
212 #define   STS_GPL_MASK          (0x001ff000)
213 #define   STS_GPL_SHIFT         12
214 #define   STS_PP_MASK           (0x00000c00)
215 #define   STS_PP_SHIFT          10
216 #define   STS_PP_DEF            0
217 #define   STS_PP_PROC           1
218 #define   STS_PP_BAL            2
219 #define   STS_PP_GFX            3
220 #define   STS_PCTD_DIS          (1<<9)
221 #define   STS_GTD_DIS           (1<<8)
222 #define   STS_PTL_MASK          (0x000000fe)
223 #define   STS_PTL_SHIFT         1
224 #define   STS_NVV               (1<<0)
225 #define THM_SEC         0x9c
226 #define   SEC_ACK       (1<<0)
227 #define THM_TC3         0xa4
228 #define THM_TC1         0xa8
229 #define   STS_PPL_MASK          (0x0003ff00)
230 #define   STS_PPL_SHIFT         16
231 #define THM_TC2         0xac
232 #define THM_DTV         0xb0
233 #define THM_ITV         0xd8
234 #define   ITV_ME_SEQNO_MASK 0x00ff0000 /* ME should update every ~200ms */
235 #define   ITV_ME_SEQNO_SHIFT (16)
236 #define   ITV_MCH_TEMP_MASK 0x0000ff00
237 #define   ITV_MCH_TEMP_SHIFT (8)
238 #define   ITV_PCH_TEMP_MASK 0x000000ff
239
240 #define thm_readb(off) readb(ips->regmap + (off))
241 #define thm_readw(off) readw(ips->regmap + (off))
242 #define thm_readl(off) readl(ips->regmap + (off))
243 #define thm_readq(off) readq(ips->regmap + (off))
244
245 #define thm_writeb(off, val) writeb((val), ips->regmap + (off))
246 #define thm_writew(off, val) writew((val), ips->regmap + (off))
247 #define thm_writel(off, val) writel((val), ips->regmap + (off))
248
249 static const int IPS_ADJUST_PERIOD = 5000; /* ms */
250 static bool late_i915_load = false;
251
252 /* For initial average collection */
253 static const int IPS_SAMPLE_PERIOD = 200; /* ms */
254 static const int IPS_SAMPLE_WINDOW = 5000; /* 5s moving window of samples */
255 #define IPS_SAMPLE_COUNT (IPS_SAMPLE_WINDOW / IPS_SAMPLE_PERIOD)
256
257 /* Per-SKU limits */
258 struct ips_mcp_limits {
259         int cpu_family;
260         int cpu_model; /* includes extended model... */
261         int mcp_power_limit; /* mW units */
262         int core_power_limit;
263         int mch_power_limit;
264         int core_temp_limit; /* degrees C */
265         int mch_temp_limit;
266 };
267
268 /* Max temps are -10 degrees C to avoid PROCHOT# */
269
270 struct ips_mcp_limits ips_sv_limits = {
271         .mcp_power_limit = 35000,
272         .core_power_limit = 29000,
273         .mch_power_limit = 20000,
274         .core_temp_limit = 95,
275         .mch_temp_limit = 90
276 };
277
278 struct ips_mcp_limits ips_lv_limits = {
279         .mcp_power_limit = 25000,
280         .core_power_limit = 21000,
281         .mch_power_limit = 13000,
282         .core_temp_limit = 95,
283         .mch_temp_limit = 90
284 };
285
286 struct ips_mcp_limits ips_ulv_limits = {
287         .mcp_power_limit = 18000,
288         .core_power_limit = 14000,
289         .mch_power_limit = 11000,
290         .core_temp_limit = 95,
291         .mch_temp_limit = 90
292 };
293
294 struct ips_driver {
295         struct pci_dev *dev;
296         void *regmap;
297         struct task_struct *monitor;
298         struct task_struct *adjust;
299         struct dentry *debug_root;
300
301         /* Average CPU core temps (all averages in .01 degrees C for precision) */
302         u16 ctv1_avg_temp;
303         u16 ctv2_avg_temp;
304         /* GMCH average */
305         u16 mch_avg_temp;
306         /* Average for the CPU (both cores?) */
307         u16 mcp_avg_temp;
308         /* Average power consumption (in mW) */
309         u32 cpu_avg_power;
310         u32 mch_avg_power;
311
312         /* Offset values */
313         u16 cta_val;
314         u16 pta_val;
315         u16 mgta_val;
316
317         /* Maximums & prefs, protected by turbo status lock */
318         spinlock_t turbo_status_lock;
319         u16 mcp_temp_limit;
320         u16 mcp_power_limit;
321         u16 core_power_limit;
322         u16 mch_power_limit;
323         bool cpu_turbo_enabled;
324         bool __cpu_turbo_on;
325         bool gpu_turbo_enabled;
326         bool __gpu_turbo_on;
327         bool gpu_preferred;
328         bool poll_turbo_status;
329         bool second_cpu;
330         bool turbo_toggle_allowed;
331         struct ips_mcp_limits *limits;
332
333         /* Optional MCH interfaces for if i915 is in use */
334         unsigned long (*read_mch_val)(void);
335         bool (*gpu_raise)(void);
336         bool (*gpu_lower)(void);
337         bool (*gpu_busy)(void);
338         bool (*gpu_turbo_disable)(void);
339
340         /* For restoration at unload */
341         u64 orig_turbo_limit;
342         u64 orig_turbo_ratios;
343 };
344
345 static bool
346 ips_gpu_turbo_enabled(struct ips_driver *ips);
347
348 #ifndef readq
349 static inline __u64 readq(const volatile void __iomem *addr)
350 {
351         const volatile u32 __iomem *p = addr;
352         u32 low, high;
353
354         low = readl(p);
355         high = readl(p + 1);
356
357         return low + ((u64)high << 32);
358 }
359 #endif
360
361 /**
362  * ips_cpu_busy - is CPU busy?
363  * @ips: IPS driver struct
364  *
365  * Check CPU for load to see whether we should increase its thermal budget.
366  *
367  * RETURNS:
368  * True if the CPU could use more power, false otherwise.
369  */
370 static bool ips_cpu_busy(struct ips_driver *ips)
371 {
372         if ((avenrun[0] >> FSHIFT) > 1)
373                 return true;
374
375         return false;
376 }
377
378 /**
379  * ips_cpu_raise - raise CPU power clamp
380  * @ips: IPS driver struct
381  *
382  * Raise the CPU power clamp by %IPS_CPU_STEP, in accordance with TDP for
383  * this platform.
384  *
385  * We do this by adjusting the TURBO_POWER_CURRENT_LIMIT MSR upwards (as
386  * long as we haven't hit the TDP limit for the SKU).
387  */
388 static void ips_cpu_raise(struct ips_driver *ips)
389 {
390         u64 turbo_override;
391         u16 cur_tdp_limit, new_tdp_limit;
392
393         if (!ips->cpu_turbo_enabled)
394                 return;
395
396         rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
397
398         cur_tdp_limit = turbo_override & TURBO_TDP_MASK;
399         new_tdp_limit = cur_tdp_limit + 8; /* 1W increase */
400
401         /* Clamp to SKU TDP limit */
402         if (((new_tdp_limit * 10) / 8) > ips->core_power_limit)
403                 new_tdp_limit = cur_tdp_limit;
404
405         thm_writew(THM_MPCPC, (new_tdp_limit * 10) / 8);
406
407         turbo_override |= TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN;
408         wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
409
410         turbo_override &= ~TURBO_TDP_MASK;
411         turbo_override |= new_tdp_limit;
412
413         wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
414 }
415
416 /**
417  * ips_cpu_lower - lower CPU power clamp
418  * @ips: IPS driver struct
419  *
420  * Lower CPU power clamp b %IPS_CPU_STEP if possible.
421  *
422  * We do this by adjusting the TURBO_POWER_CURRENT_LIMIT MSR down, going
423  * as low as the platform limits will allow (though we could go lower there
424  * wouldn't be much point).
425  */
426 static void ips_cpu_lower(struct ips_driver *ips)
427 {
428         u64 turbo_override;
429         u16 cur_limit, new_limit;
430
431         rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
432
433         cur_limit = turbo_override & TURBO_TDP_MASK;
434         new_limit = cur_limit - 8; /* 1W decrease */
435
436         /* Clamp to SKU TDP limit */
437         if (new_limit  < (ips->orig_turbo_limit & TURBO_TDP_MASK))
438                 new_limit = ips->orig_turbo_limit & TURBO_TDP_MASK;
439
440         thm_writew(THM_MPCPC, (new_limit * 10) / 8);
441
442         turbo_override |= TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN;
443         wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
444
445         turbo_override &= ~TURBO_TDP_MASK;
446         turbo_override |= new_limit;
447
448         wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
449 }
450
451 /**
452  * do_enable_cpu_turbo - internal turbo enable function
453  * @data: unused
454  *
455  * Internal function for actually updating MSRs.  When we enable/disable
456  * turbo, we need to do it on each CPU; this function is the one called
457  * by on_each_cpu() when needed.
458  */
459 static void do_enable_cpu_turbo(void *data)
460 {
461         u64 perf_ctl;
462
463         rdmsrl(IA32_PERF_CTL, perf_ctl);
464         if (perf_ctl & IA32_PERF_TURBO_DIS) {
465                 perf_ctl &= ~IA32_PERF_TURBO_DIS;
466                 wrmsrl(IA32_PERF_CTL, perf_ctl);
467         }
468 }
469
470 /**
471  * ips_enable_cpu_turbo - enable turbo mode on all CPUs
472  * @ips: IPS driver struct
473  *
474  * Enable turbo mode by clearing the disable bit in IA32_PERF_CTL on
475  * all logical threads.
476  */
477 static void ips_enable_cpu_turbo(struct ips_driver *ips)
478 {
479         /* Already on, no need to mess with MSRs */
480         if (ips->__cpu_turbo_on)
481                 return;
482
483         if (ips->turbo_toggle_allowed)
484                 on_each_cpu(do_enable_cpu_turbo, ips, 1);
485
486         ips->__cpu_turbo_on = true;
487 }
488
489 /**
490  * do_disable_cpu_turbo - internal turbo disable function
491  * @data: unused
492  *
493  * Internal function for actually updating MSRs.  When we enable/disable
494  * turbo, we need to do it on each CPU; this function is the one called
495  * by on_each_cpu() when needed.
496  */
497 static void do_disable_cpu_turbo(void *data)
498 {
499         u64 perf_ctl;
500
501         rdmsrl(IA32_PERF_CTL, perf_ctl);
502         if (!(perf_ctl & IA32_PERF_TURBO_DIS)) {
503                 perf_ctl |= IA32_PERF_TURBO_DIS;
504                 wrmsrl(IA32_PERF_CTL, perf_ctl);
505         }
506 }
507
508 /**
509  * ips_disable_cpu_turbo - disable turbo mode on all CPUs
510  * @ips: IPS driver struct
511  *
512  * Disable turbo mode by setting the disable bit in IA32_PERF_CTL on
513  * all logical threads.
514  */
515 static void ips_disable_cpu_turbo(struct ips_driver *ips)
516 {
517         /* Already off, leave it */
518         if (!ips->__cpu_turbo_on)
519                 return;
520
521         if (ips->turbo_toggle_allowed)
522                 on_each_cpu(do_disable_cpu_turbo, ips, 1);
523
524         ips->__cpu_turbo_on = false;
525 }
526
527 /**
528  * ips_gpu_busy - is GPU busy?
529  * @ips: IPS driver struct
530  *
531  * Check GPU for load to see whether we should increase its thermal budget.
532  * We need to call into the i915 driver in this case.
533  *
534  * RETURNS:
535  * True if the GPU could use more power, false otherwise.
536  */
537 static bool ips_gpu_busy(struct ips_driver *ips)
538 {
539         if (!ips_gpu_turbo_enabled(ips))
540                 return false;
541
542         return ips->gpu_busy();
543 }
544
545 /**
546  * ips_gpu_raise - raise GPU power clamp
547  * @ips: IPS driver struct
548  *
549  * Raise the GPU frequency/power if possible.  We need to call into the
550  * i915 driver in this case.
551  */
552 static void ips_gpu_raise(struct ips_driver *ips)
553 {
554         if (!ips_gpu_turbo_enabled(ips))
555                 return;
556
557         if (!ips->gpu_raise())
558                 ips->gpu_turbo_enabled = false;
559
560         return;
561 }
562
563 /**
564  * ips_gpu_lower - lower GPU power clamp
565  * @ips: IPS driver struct
566  *
567  * Lower GPU frequency/power if possible.  Need to call i915.
568  */
569 static void ips_gpu_lower(struct ips_driver *ips)
570 {
571         if (!ips_gpu_turbo_enabled(ips))
572                 return;
573
574         if (!ips->gpu_lower())
575                 ips->gpu_turbo_enabled = false;
576
577         return;
578 }
579
580 /**
581  * ips_enable_gpu_turbo - notify the gfx driver turbo is available
582  * @ips: IPS driver struct
583  *
584  * Call into the graphics driver indicating that it can safely use
585  * turbo mode.
586  */
587 static void ips_enable_gpu_turbo(struct ips_driver *ips)
588 {
589         if (ips->__gpu_turbo_on)
590                 return;
591         ips->__gpu_turbo_on = true;
592 }
593
594 /**
595  * ips_disable_gpu_turbo - notify the gfx driver to disable turbo mode
596  * @ips: IPS driver struct
597  *
598  * Request that the graphics driver disable turbo mode.
599  */
600 static void ips_disable_gpu_turbo(struct ips_driver *ips)
601 {
602         /* Avoid calling i915 if turbo is already disabled */
603         if (!ips->__gpu_turbo_on)
604                 return;
605
606         if (!ips->gpu_turbo_disable())
607                 dev_err(&ips->dev->dev, "failed to disable graphis turbo\n");
608         else
609                 ips->__gpu_turbo_on = false;
610 }
611
612 /**
613  * mcp_exceeded - check whether we're outside our thermal & power limits
614  * @ips: IPS driver struct
615  *
616  * Check whether the MCP is over its thermal or power budget.
617  */
618 static bool mcp_exceeded(struct ips_driver *ips)
619 {
620         unsigned long flags;
621         bool ret = false;
622         u32 temp_limit;
623         u32 avg_power;
624         const char *msg = "MCP limit exceeded: ";
625
626         spin_lock_irqsave(&ips->turbo_status_lock, flags);
627
628         temp_limit = ips->mcp_temp_limit * 100;
629         if (ips->mcp_avg_temp > temp_limit) {
630                 dev_info(&ips->dev->dev,
631                         "%sAvg temp %u, limit %u\n", msg, ips->mcp_avg_temp,
632                         temp_limit);
633                 ret = true;
634         }
635
636         avg_power = ips->cpu_avg_power + ips->mch_avg_power;
637         if (avg_power > ips->mcp_power_limit) {
638                 dev_info(&ips->dev->dev,
639                         "%sAvg power %u, limit %u\n", msg, avg_power,
640                         ips->mcp_power_limit);
641                 ret = true;
642         }
643
644         spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
645
646         return ret;
647 }
648
649 /**
650  * cpu_exceeded - check whether a CPU core is outside its limits
651  * @ips: IPS driver struct
652  * @cpu: CPU number to check
653  *
654  * Check a given CPU's average temp or power is over its limit.
655  */
656 static bool cpu_exceeded(struct ips_driver *ips, int cpu)
657 {
658         unsigned long flags;
659         int avg;
660         bool ret = false;
661
662         spin_lock_irqsave(&ips->turbo_status_lock, flags);
663         avg = cpu ? ips->ctv2_avg_temp : ips->ctv1_avg_temp;
664         if (avg > (ips->limits->core_temp_limit * 100))
665                 ret = true;
666         if (ips->cpu_avg_power > ips->core_power_limit * 100)
667                 ret = true;
668         spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
669
670         if (ret)
671                 dev_info(&ips->dev->dev,
672                          "CPU power or thermal limit exceeded\n");
673
674         return ret;
675 }
676
677 /**
678  * mch_exceeded - check whether the GPU is over budget
679  * @ips: IPS driver struct
680  *
681  * Check the MCH temp & power against their maximums.
682  */
683 static bool mch_exceeded(struct ips_driver *ips)
684 {
685         unsigned long flags;
686         bool ret = false;
687
688         spin_lock_irqsave(&ips->turbo_status_lock, flags);
689         if (ips->mch_avg_temp > (ips->limits->mch_temp_limit * 100))
690                 ret = true;
691         if (ips->mch_avg_power > ips->mch_power_limit)
692                 ret = true;
693         spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
694
695         return ret;
696 }
697
698 /**
699  * verify_limits - verify BIOS provided limits
700  * @ips: IPS structure
701  *
702  * BIOS can optionally provide non-default limits for power and temp.  Check
703  * them here and use the defaults if the BIOS values are not provided or
704  * are otherwise unusable.
705  */
706 static void verify_limits(struct ips_driver *ips)
707 {
708         if (ips->mcp_power_limit < ips->limits->mcp_power_limit ||
709             ips->mcp_power_limit > 35000)
710                 ips->mcp_power_limit = ips->limits->mcp_power_limit;
711
712         if (ips->mcp_temp_limit < ips->limits->core_temp_limit ||
713             ips->mcp_temp_limit < ips->limits->mch_temp_limit ||
714             ips->mcp_temp_limit > 150)
715                 ips->mcp_temp_limit = min(ips->limits->core_temp_limit,
716                                           ips->limits->mch_temp_limit);
717 }
718
719 /**
720  * update_turbo_limits - get various limits & settings from regs
721  * @ips: IPS driver struct
722  *
723  * Update the IPS power & temp limits, along with turbo enable flags,
724  * based on latest register contents.
725  *
726  * Used at init time and for runtime BIOS support, which requires polling
727  * the regs for updates (as a result of AC->DC transition for example).
728  *
729  * LOCKING:
730  * Caller must hold turbo_status_lock (outside of init)
731  */
732 static void update_turbo_limits(struct ips_driver *ips)
733 {
734         u32 hts = thm_readl(THM_HTS);
735
736         ips->cpu_turbo_enabled = !(hts & HTS_PCTD_DIS);
737         /* 
738          * Disable turbo for now, until we can figure out why the power figures
739          * are wrong
740          */
741         ips->cpu_turbo_enabled = false;
742
743         if (ips->gpu_busy)
744                 ips->gpu_turbo_enabled = !(hts & HTS_GTD_DIS);
745
746         ips->core_power_limit = thm_readw(THM_MPCPC);
747         ips->mch_power_limit = thm_readw(THM_MMGPC);
748         ips->mcp_temp_limit = thm_readw(THM_PTL);
749         ips->mcp_power_limit = thm_readw(THM_MPPC);
750
751         verify_limits(ips);
752         /* Ignore BIOS CPU vs GPU pref */
753 }
754
755 /**
756  * ips_adjust - adjust power clamp based on thermal state
757  * @data: ips driver structure
758  *
759  * Wake up every 5s or so and check whether we should adjust the power clamp.
760  * Check CPU and GPU load to determine which needs adjustment.  There are
761  * several things to consider here:
762  *   - do we need to adjust up or down?
763  *   - is CPU busy?
764  *   - is GPU busy?
765  *   - is CPU in turbo?
766  *   - is GPU in turbo?
767  *   - is CPU or GPU preferred? (CPU is default)
768  *
769  * So, given the above, we do the following:
770  *   - up (TDP available)
771  *     - CPU not busy, GPU not busy - nothing
772  *     - CPU busy, GPU not busy - adjust CPU up
773  *     - CPU not busy, GPU busy - adjust GPU up
774  *     - CPU busy, GPU busy - adjust preferred unit up, taking headroom from
775  *       non-preferred unit if necessary
776  *   - down (at TDP limit)
777  *     - adjust both CPU and GPU down if possible
778  *
779                 cpu+ gpu+       cpu+gpu-        cpu-gpu+        cpu-gpu-
780 cpu < gpu <     cpu+gpu+        cpu+            gpu+            nothing
781 cpu < gpu >=    cpu+gpu-(mcp<)  cpu+gpu-(mcp<)  gpu-            gpu-
782 cpu >= gpu <    cpu-gpu+(mcp<)  cpu-            cpu-gpu+(mcp<)  cpu-
783 cpu >= gpu >=   cpu-gpu-        cpu-gpu-        cpu-gpu-        cpu-gpu-
784  *
785  */
786 static int ips_adjust(void *data)
787 {
788         struct ips_driver *ips = data;
789         unsigned long flags;
790
791         dev_dbg(&ips->dev->dev, "starting ips-adjust thread\n");
792
793         /*
794          * Adjust CPU and GPU clamps every 5s if needed.  Doing it more
795          * often isn't recommended due to ME interaction.
796          */
797         do {
798                 bool cpu_busy = ips_cpu_busy(ips);
799                 bool gpu_busy = ips_gpu_busy(ips);
800
801                 spin_lock_irqsave(&ips->turbo_status_lock, flags);
802                 if (ips->poll_turbo_status)
803                         update_turbo_limits(ips);
804                 spin_unlock_irqrestore(&ips->turbo_status_lock, flags);
805
806                 /* Update turbo status if necessary */
807                 if (ips->cpu_turbo_enabled)
808                         ips_enable_cpu_turbo(ips);
809                 else
810                         ips_disable_cpu_turbo(ips);
811
812                 if (ips->gpu_turbo_enabled)
813                         ips_enable_gpu_turbo(ips);
814                 else
815                         ips_disable_gpu_turbo(ips);
816
817                 /* We're outside our comfort zone, crank them down */
818                 if (mcp_exceeded(ips)) {
819                         ips_cpu_lower(ips);
820                         ips_gpu_lower(ips);
821                         goto sleep;
822                 }
823
824                 if (!cpu_exceeded(ips, 0) && cpu_busy)
825                         ips_cpu_raise(ips);
826                 else
827                         ips_cpu_lower(ips);
828
829                 if (!mch_exceeded(ips) && gpu_busy)
830                         ips_gpu_raise(ips);
831                 else
832                         ips_gpu_lower(ips);
833
834 sleep:
835                 schedule_timeout_interruptible(msecs_to_jiffies(IPS_ADJUST_PERIOD));
836         } while (!kthread_should_stop());
837
838         dev_dbg(&ips->dev->dev, "ips-adjust thread stopped\n");
839
840         return 0;
841 }
842
843 /*
844  * Helpers for reading out temp/power values and calculating their
845  * averages for the decision making and monitoring functions.
846  */
847
848 static u16 calc_avg_temp(struct ips_driver *ips, u16 *array)
849 {
850         u64 total = 0;
851         int i;
852         u16 avg;
853
854         for (i = 0; i < IPS_SAMPLE_COUNT; i++)
855                 total += (u64)(array[i] * 100);
856
857         do_div(total, IPS_SAMPLE_COUNT);
858
859         avg = (u16)total;
860
861         return avg;
862 }
863
864 static u16 read_mgtv(struct ips_driver *ips)
865 {
866         u16 ret;
867         u64 slope, offset;
868         u64 val;
869
870         val = thm_readq(THM_MGTV);
871         val = (val & TV_MASK) >> TV_SHIFT;
872
873         slope = offset = thm_readw(THM_MGTA);
874         slope = (slope & MGTA_SLOPE_MASK) >> MGTA_SLOPE_SHIFT;
875         offset = offset & MGTA_OFFSET_MASK;
876
877         ret = ((val * slope + 0x40) >> 7) + offset;
878
879         return 0; /* MCH temp reporting buggy */
880 }
881
882 static u16 read_ptv(struct ips_driver *ips)
883 {
884         u16 val, slope, offset;
885
886         slope = (ips->pta_val & PTA_SLOPE_MASK) >> PTA_SLOPE_SHIFT;
887         offset = ips->pta_val & PTA_OFFSET_MASK;
888
889         val = thm_readw(THM_PTV) & PTV_MASK;
890
891         return val;
892 }
893
894 static u16 read_ctv(struct ips_driver *ips, int cpu)
895 {
896         int reg = cpu ? THM_CTV2 : THM_CTV1;
897         u16 val;
898
899         val = thm_readw(reg);
900         if (!(val & CTV_TEMP_ERROR))
901                 val = (val) >> 6; /* discard fractional component */
902         else
903                 val = 0;
904
905         return val;
906 }
907
908 static u32 get_cpu_power(struct ips_driver *ips, u32 *last, int period)
909 {
910         u32 val;
911         u32 ret;
912
913         /*
914          * CEC is in joules/65535.  Take difference over time to
915          * get watts.
916          */
917         val = thm_readl(THM_CEC);
918
919         /* period is in ms and we want mW */
920         ret = (((val - *last) * 1000) / period);
921         ret = (ret * 1000) / 65535;
922         *last = val;
923
924         return 0;
925 }
926
927 static const u16 temp_decay_factor = 2;
928 static u16 update_average_temp(u16 avg, u16 val)
929 {
930         u16 ret;
931
932         /* Multiply by 100 for extra precision */
933         ret = (val * 100 / temp_decay_factor) +
934                 (((temp_decay_factor - 1) * avg) / temp_decay_factor);
935         return ret;
936 }
937
938 static const u16 power_decay_factor = 2;
939 static u16 update_average_power(u32 avg, u32 val)
940 {
941         u32 ret;
942
943         ret = (val / power_decay_factor) +
944                 (((power_decay_factor - 1) * avg) / power_decay_factor);
945
946         return ret;
947 }
948
949 static u32 calc_avg_power(struct ips_driver *ips, u32 *array)
950 {
951         u64 total = 0;
952         u32 avg;
953         int i;
954
955         for (i = 0; i < IPS_SAMPLE_COUNT; i++)
956                 total += array[i];
957
958         do_div(total, IPS_SAMPLE_COUNT);
959         avg = (u32)total;
960
961         return avg;
962 }
963
964 static void monitor_timeout(unsigned long arg)
965 {
966         wake_up_process((struct task_struct *)arg);
967 }
968
969 /**
970  * ips_monitor - temp/power monitoring thread
971  * @data: ips driver structure
972  *
973  * This is the main function for the IPS driver.  It monitors power and
974  * tempurature in the MCP and adjusts CPU and GPU power clams accordingly.
975  *
976  * We keep a 5s moving average of power consumption and tempurature.  Using
977  * that data, along with CPU vs GPU preference, we adjust the power clamps
978  * up or down.
979  */
980 static int ips_monitor(void *data)
981 {
982         struct ips_driver *ips = data;
983         struct timer_list timer;
984         unsigned long seqno_timestamp, expire, last_msecs, last_sample_period;
985         int i;
986         u32 *cpu_samples, *mchp_samples, old_cpu_power;
987         u16 *mcp_samples, *ctv1_samples, *ctv2_samples, *mch_samples;
988         u8 cur_seqno, last_seqno;
989
990         mcp_samples = kzalloc(sizeof(u16) * IPS_SAMPLE_COUNT, GFP_KERNEL);
991         ctv1_samples = kzalloc(sizeof(u16) * IPS_SAMPLE_COUNT, GFP_KERNEL);
992         ctv2_samples = kzalloc(sizeof(u16) * IPS_SAMPLE_COUNT, GFP_KERNEL);
993         mch_samples = kzalloc(sizeof(u16) * IPS_SAMPLE_COUNT, GFP_KERNEL);
994         cpu_samples = kzalloc(sizeof(u32) * IPS_SAMPLE_COUNT, GFP_KERNEL);
995         mchp_samples = kzalloc(sizeof(u32) * IPS_SAMPLE_COUNT, GFP_KERNEL);
996         if (!mcp_samples || !ctv1_samples || !ctv2_samples || !mch_samples ||
997                         !cpu_samples || !mchp_samples) {
998                 dev_err(&ips->dev->dev,
999                         "failed to allocate sample array, ips disabled\n");
1000                 kfree(mcp_samples);
1001                 kfree(ctv1_samples);
1002                 kfree(ctv2_samples);
1003                 kfree(mch_samples);
1004                 kfree(cpu_samples);
1005                 kfree(mchp_samples);
1006                 return -ENOMEM;
1007         }
1008
1009         last_seqno = (thm_readl(THM_ITV) & ITV_ME_SEQNO_MASK) >>
1010                 ITV_ME_SEQNO_SHIFT;
1011         seqno_timestamp = get_jiffies_64();
1012
1013         old_cpu_power = thm_readl(THM_CEC);
1014         schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
1015
1016         /* Collect an initial average */
1017         for (i = 0; i < IPS_SAMPLE_COUNT; i++) {
1018                 u32 mchp, cpu_power;
1019                 u16 val;
1020
1021                 mcp_samples[i] = read_ptv(ips);
1022
1023                 val = read_ctv(ips, 0);
1024                 ctv1_samples[i] = val;
1025
1026                 val = read_ctv(ips, 1);
1027                 ctv2_samples[i] = val;
1028
1029                 val = read_mgtv(ips);
1030                 mch_samples[i] = val;
1031
1032                 cpu_power = get_cpu_power(ips, &old_cpu_power,
1033                                           IPS_SAMPLE_PERIOD);
1034                 cpu_samples[i] = cpu_power;
1035
1036                 if (ips->read_mch_val) {
1037                         mchp = ips->read_mch_val();
1038                         mchp_samples[i] = mchp;
1039                 }
1040
1041                 schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
1042                 if (kthread_should_stop())
1043                         break;
1044         }
1045
1046         ips->mcp_avg_temp = calc_avg_temp(ips, mcp_samples);
1047         ips->ctv1_avg_temp = calc_avg_temp(ips, ctv1_samples);
1048         ips->ctv2_avg_temp = calc_avg_temp(ips, ctv2_samples);
1049         ips->mch_avg_temp = calc_avg_temp(ips, mch_samples);
1050         ips->cpu_avg_power = calc_avg_power(ips, cpu_samples);
1051         ips->mch_avg_power = calc_avg_power(ips, mchp_samples);
1052         kfree(mcp_samples);
1053         kfree(ctv1_samples);
1054         kfree(ctv2_samples);
1055         kfree(mch_samples);
1056         kfree(cpu_samples);
1057         kfree(mchp_samples);
1058
1059         /* Start the adjustment thread now that we have data */
1060         wake_up_process(ips->adjust);
1061
1062         /*
1063          * Ok, now we have an initial avg.  From here on out, we track the
1064          * running avg using a decaying average calculation.  This allows
1065          * us to reduce the sample frequency if the CPU and GPU are idle.
1066          */
1067         old_cpu_power = thm_readl(THM_CEC);
1068         schedule_timeout_interruptible(msecs_to_jiffies(IPS_SAMPLE_PERIOD));
1069         last_sample_period = IPS_SAMPLE_PERIOD;
1070
1071         setup_deferrable_timer_on_stack(&timer, monitor_timeout,
1072                                         (unsigned long)current);
1073         do {
1074                 u32 cpu_val, mch_val;
1075                 u16 val;
1076
1077                 /* MCP itself */
1078                 val = read_ptv(ips);
1079                 ips->mcp_avg_temp = update_average_temp(ips->mcp_avg_temp, val);
1080
1081                 /* Processor 0 */
1082                 val = read_ctv(ips, 0);
1083                 ips->ctv1_avg_temp =
1084                         update_average_temp(ips->ctv1_avg_temp, val);
1085                 /* Power */
1086                 cpu_val = get_cpu_power(ips, &old_cpu_power,
1087                                         last_sample_period);
1088                 ips->cpu_avg_power =
1089                         update_average_power(ips->cpu_avg_power, cpu_val);
1090
1091                 if (ips->second_cpu) {
1092                         /* Processor 1 */
1093                         val = read_ctv(ips, 1);
1094                         ips->ctv2_avg_temp =
1095                                 update_average_temp(ips->ctv2_avg_temp, val);
1096                 }
1097
1098                 /* MCH */
1099                 val = read_mgtv(ips);
1100                 ips->mch_avg_temp = update_average_temp(ips->mch_avg_temp, val);
1101                 /* Power */
1102                 if (ips->read_mch_val) {
1103                         mch_val = ips->read_mch_val();
1104                         ips->mch_avg_power =
1105                                 update_average_power(ips->mch_avg_power,
1106                                                      mch_val);
1107                 }
1108
1109                 /*
1110                  * Make sure ME is updating thermal regs.
1111                  * Note:
1112                  * If it's been more than a second since the last update,
1113                  * the ME is probably hung.
1114                  */
1115                 cur_seqno = (thm_readl(THM_ITV) & ITV_ME_SEQNO_MASK) >>
1116                         ITV_ME_SEQNO_SHIFT;
1117                 if (cur_seqno == last_seqno &&
1118                     time_after(jiffies, seqno_timestamp + HZ)) {
1119                         dev_warn(&ips->dev->dev, "ME failed to update for more than 1s, likely hung\n");
1120                 } else {
1121                         seqno_timestamp = get_jiffies_64();
1122                         last_seqno = cur_seqno;
1123                 }
1124
1125                 last_msecs = jiffies_to_msecs(jiffies);
1126                 expire = jiffies + msecs_to_jiffies(IPS_SAMPLE_PERIOD);
1127
1128                 __set_current_state(TASK_INTERRUPTIBLE);
1129                 mod_timer(&timer, expire);
1130                 schedule();
1131
1132                 /* Calculate actual sample period for power averaging */
1133                 last_sample_period = jiffies_to_msecs(jiffies) - last_msecs;
1134                 if (!last_sample_period)
1135                         last_sample_period = 1;
1136         } while (!kthread_should_stop());
1137
1138         del_timer_sync(&timer);
1139         destroy_timer_on_stack(&timer);
1140
1141         dev_dbg(&ips->dev->dev, "ips-monitor thread stopped\n");
1142
1143         return 0;
1144 }
1145
1146 #if 0
1147 #define THM_DUMPW(reg) \
1148         { \
1149         u16 val = thm_readw(reg); \
1150         dev_dbg(&ips->dev->dev, #reg ": 0x%04x\n", val); \
1151         }
1152 #define THM_DUMPL(reg) \
1153         { \
1154         u32 val = thm_readl(reg); \
1155         dev_dbg(&ips->dev->dev, #reg ": 0x%08x\n", val); \
1156         }
1157 #define THM_DUMPQ(reg) \
1158         { \
1159         u64 val = thm_readq(reg); \
1160         dev_dbg(&ips->dev->dev, #reg ": 0x%016x\n", val); \
1161         }
1162
1163 static void dump_thermal_info(struct ips_driver *ips)
1164 {
1165         u16 ptl;
1166
1167         ptl = thm_readw(THM_PTL);
1168         dev_dbg(&ips->dev->dev, "Processor temp limit: %d\n", ptl);
1169
1170         THM_DUMPW(THM_CTA);
1171         THM_DUMPW(THM_TRC);
1172         THM_DUMPW(THM_CTV1);
1173         THM_DUMPL(THM_STS);
1174         THM_DUMPW(THM_PTV);
1175         THM_DUMPQ(THM_MGTV);
1176 }
1177 #endif
1178
1179 /**
1180  * ips_irq_handler - handle temperature triggers and other IPS events
1181  * @irq: irq number
1182  * @arg: unused
1183  *
1184  * Handle temperature limit trigger events, generally by lowering the clamps.
1185  * If we're at a critical limit, we clamp back to the lowest possible value
1186  * to prevent emergency shutdown.
1187  */
1188 static irqreturn_t ips_irq_handler(int irq, void *arg)
1189 {
1190         struct ips_driver *ips = arg;
1191         u8 tses = thm_readb(THM_TSES);
1192         u8 tes = thm_readb(THM_TES);
1193
1194         if (!tses && !tes)
1195                 return IRQ_NONE;
1196
1197         dev_info(&ips->dev->dev, "TSES: 0x%02x\n", tses);
1198         dev_info(&ips->dev->dev, "TES: 0x%02x\n", tes);
1199
1200         /* STS update from EC? */
1201         if (tes & 1) {
1202                 u32 sts, tc1;
1203
1204                 sts = thm_readl(THM_STS);
1205                 tc1 = thm_readl(THM_TC1);
1206
1207                 if (sts & STS_NVV) {
1208                         spin_lock(&ips->turbo_status_lock);
1209                         ips->core_power_limit = (sts & STS_PCPL_MASK) >>
1210                                 STS_PCPL_SHIFT;
1211                         ips->mch_power_limit = (sts & STS_GPL_MASK) >>
1212                                 STS_GPL_SHIFT;
1213                         /* ignore EC CPU vs GPU pref */
1214                         ips->cpu_turbo_enabled = !(sts & STS_PCTD_DIS);
1215                         /* 
1216                          * Disable turbo for now, until we can figure
1217                          * out why the power figures are wrong
1218                          */
1219                         ips->cpu_turbo_enabled = false;
1220                         if (ips->gpu_busy)
1221                                 ips->gpu_turbo_enabled = !(sts & STS_GTD_DIS);
1222                         ips->mcp_temp_limit = (sts & STS_PTL_MASK) >>
1223                                 STS_PTL_SHIFT;
1224                         ips->mcp_power_limit = (tc1 & STS_PPL_MASK) >>
1225                                 STS_PPL_SHIFT;
1226                         verify_limits(ips);
1227                         spin_unlock(&ips->turbo_status_lock);
1228
1229                         thm_writeb(THM_SEC, SEC_ACK);
1230                 }
1231                 thm_writeb(THM_TES, tes);
1232         }
1233
1234         /* Thermal trip */
1235         if (tses) {
1236                 dev_warn(&ips->dev->dev,
1237                          "thermal trip occurred, tses: 0x%04x\n", tses);
1238                 thm_writeb(THM_TSES, tses);
1239         }
1240
1241         return IRQ_HANDLED;
1242 }
1243
1244 #ifndef CONFIG_DEBUG_FS
1245 static void ips_debugfs_init(struct ips_driver *ips) { return; }
1246 static void ips_debugfs_cleanup(struct ips_driver *ips) { return; }
1247 #else
1248
1249 /* Expose current state and limits in debugfs if possible */
1250
1251 struct ips_debugfs_node {
1252         struct ips_driver *ips;
1253         char *name;
1254         int (*show)(struct seq_file *m, void *data);
1255 };
1256
1257 static int show_cpu_temp(struct seq_file *m, void *data)
1258 {
1259         struct ips_driver *ips = m->private;
1260
1261         seq_printf(m, "%d.%02d\n", ips->ctv1_avg_temp / 100,
1262                    ips->ctv1_avg_temp % 100);
1263
1264         return 0;
1265 }
1266
1267 static int show_cpu_power(struct seq_file *m, void *data)
1268 {
1269         struct ips_driver *ips = m->private;
1270
1271         seq_printf(m, "%dmW\n", ips->cpu_avg_power);
1272
1273         return 0;
1274 }
1275
1276 static int show_cpu_clamp(struct seq_file *m, void *data)
1277 {
1278         u64 turbo_override;
1279         int tdp, tdc;
1280
1281         rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
1282
1283         tdp = (int)(turbo_override & TURBO_TDP_MASK);
1284         tdc = (int)((turbo_override & TURBO_TDC_MASK) >> TURBO_TDC_SHIFT);
1285
1286         /* Convert to .1W/A units */
1287         tdp = tdp * 10 / 8;
1288         tdc = tdc * 10 / 8;
1289
1290         /* Watts Amperes */
1291         seq_printf(m, "%d.%dW %d.%dA\n", tdp / 10, tdp % 10,
1292                    tdc / 10, tdc % 10);
1293
1294         return 0;
1295 }
1296
1297 static int show_mch_temp(struct seq_file *m, void *data)
1298 {
1299         struct ips_driver *ips = m->private;
1300
1301         seq_printf(m, "%d.%02d\n", ips->mch_avg_temp / 100,
1302                    ips->mch_avg_temp % 100);
1303
1304         return 0;
1305 }
1306
1307 static int show_mch_power(struct seq_file *m, void *data)
1308 {
1309         struct ips_driver *ips = m->private;
1310
1311         seq_printf(m, "%dmW\n", ips->mch_avg_power);
1312
1313         return 0;
1314 }
1315
1316 static struct ips_debugfs_node ips_debug_files[] = {
1317         { NULL, "cpu_temp", show_cpu_temp },
1318         { NULL, "cpu_power", show_cpu_power },
1319         { NULL, "cpu_clamp", show_cpu_clamp },
1320         { NULL, "mch_temp", show_mch_temp },
1321         { NULL, "mch_power", show_mch_power },
1322 };
1323
1324 static int ips_debugfs_open(struct inode *inode, struct file *file)
1325 {
1326         struct ips_debugfs_node *node = inode->i_private;
1327
1328         return single_open(file, node->show, node->ips);
1329 }
1330
1331 static const struct file_operations ips_debugfs_ops = {
1332         .owner = THIS_MODULE,
1333         .open = ips_debugfs_open,
1334         .read = seq_read,
1335         .llseek = seq_lseek,
1336         .release = single_release,
1337 };
1338
1339 static void ips_debugfs_cleanup(struct ips_driver *ips)
1340 {
1341         if (ips->debug_root)
1342                 debugfs_remove_recursive(ips->debug_root);
1343         return;
1344 }
1345
1346 static void ips_debugfs_init(struct ips_driver *ips)
1347 {
1348         int i;
1349
1350         ips->debug_root = debugfs_create_dir("ips", NULL);
1351         if (!ips->debug_root) {
1352                 dev_err(&ips->dev->dev,
1353                         "failed to create debugfs entries: %ld\n",
1354                         PTR_ERR(ips->debug_root));
1355                 return;
1356         }
1357
1358         for (i = 0; i < ARRAY_SIZE(ips_debug_files); i++) {
1359                 struct dentry *ent;
1360                 struct ips_debugfs_node *node = &ips_debug_files[i];
1361
1362                 node->ips = ips;
1363                 ent = debugfs_create_file(node->name, S_IFREG | S_IRUGO,
1364                                           ips->debug_root, node,
1365                                           &ips_debugfs_ops);
1366                 if (!ent) {
1367                         dev_err(&ips->dev->dev,
1368                                 "failed to create debug file: %ld\n",
1369                                 PTR_ERR(ent));
1370                         goto err_cleanup;
1371                 }
1372         }
1373
1374         return;
1375
1376 err_cleanup:
1377         ips_debugfs_cleanup(ips);
1378         return;
1379 }
1380 #endif /* CONFIG_DEBUG_FS */
1381
1382 /**
1383  * ips_detect_cpu - detect whether CPU supports IPS
1384  *
1385  * Walk our list and see if we're on a supported CPU.  If we find one,
1386  * return the limits for it.
1387  */
1388 static struct ips_mcp_limits *ips_detect_cpu(struct ips_driver *ips)
1389 {
1390         u64 turbo_power, misc_en;
1391         struct ips_mcp_limits *limits = NULL;
1392         u16 tdp;
1393
1394         if (!(boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 37)) {
1395                 dev_info(&ips->dev->dev, "Non-IPS CPU detected.\n");
1396                 goto out;
1397         }
1398
1399         rdmsrl(IA32_MISC_ENABLE, misc_en);
1400         /*
1401          * If the turbo enable bit isn't set, we shouldn't try to enable/disable
1402          * turbo manually or we'll get an illegal MSR access, even though
1403          * turbo will still be available.
1404          */
1405         if (misc_en & IA32_MISC_TURBO_EN)
1406                 ips->turbo_toggle_allowed = true;
1407         else
1408                 ips->turbo_toggle_allowed = false;
1409
1410         if (strstr(boot_cpu_data.x86_model_id, "CPU       M"))
1411                 limits = &ips_sv_limits;
1412         else if (strstr(boot_cpu_data.x86_model_id, "CPU       L"))
1413                 limits = &ips_lv_limits;
1414         else if (strstr(boot_cpu_data.x86_model_id, "CPU       U"))
1415                 limits = &ips_ulv_limits;
1416         else {
1417                 dev_info(&ips->dev->dev, "No CPUID match found.\n");
1418                 goto out;
1419         }
1420
1421         rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_power);
1422         tdp = turbo_power & TURBO_TDP_MASK;
1423
1424         /* Sanity check TDP against CPU */
1425         if (limits->core_power_limit != (tdp / 8) * 1000) {
1426                 dev_info(&ips->dev->dev, "CPU TDP doesn't match expected value (found %d, expected %d)\n",
1427                          tdp / 8, limits->core_power_limit / 1000);
1428                 limits->core_power_limit = (tdp / 8) * 1000;
1429         }
1430
1431 out:
1432         return limits;
1433 }
1434
1435 /**
1436  * ips_get_i915_syms - try to get GPU control methods from i915 driver
1437  * @ips: IPS driver
1438  *
1439  * The i915 driver exports several interfaces to allow the IPS driver to
1440  * monitor and control graphics turbo mode.  If we can find them, we can
1441  * enable graphics turbo, otherwise we must disable it to avoid exceeding
1442  * thermal and power limits in the MCP.
1443  */
1444 static bool ips_get_i915_syms(struct ips_driver *ips)
1445 {
1446         ips->read_mch_val = symbol_get(i915_read_mch_val);
1447         if (!ips->read_mch_val)
1448                 goto out_err;
1449         ips->gpu_raise = symbol_get(i915_gpu_raise);
1450         if (!ips->gpu_raise)
1451                 goto out_put_mch;
1452         ips->gpu_lower = symbol_get(i915_gpu_lower);
1453         if (!ips->gpu_lower)
1454                 goto out_put_raise;
1455         ips->gpu_busy = symbol_get(i915_gpu_busy);
1456         if (!ips->gpu_busy)
1457                 goto out_put_lower;
1458         ips->gpu_turbo_disable = symbol_get(i915_gpu_turbo_disable);
1459         if (!ips->gpu_turbo_disable)
1460                 goto out_put_busy;
1461
1462         return true;
1463
1464 out_put_busy:
1465         symbol_put(i915_gpu_busy);
1466 out_put_lower:
1467         symbol_put(i915_gpu_lower);
1468 out_put_raise:
1469         symbol_put(i915_gpu_raise);
1470 out_put_mch:
1471         symbol_put(i915_read_mch_val);
1472 out_err:
1473         return false;
1474 }
1475
1476 static bool
1477 ips_gpu_turbo_enabled(struct ips_driver *ips)
1478 {
1479         if (!ips->gpu_busy && late_i915_load) {
1480                 if (ips_get_i915_syms(ips)) {
1481                         dev_info(&ips->dev->dev,
1482                                  "i915 driver attached, reenabling gpu turbo\n");
1483                         ips->gpu_turbo_enabled = !(thm_readl(THM_HTS) & HTS_GTD_DIS);
1484                 }
1485         }
1486
1487         return ips->gpu_turbo_enabled;
1488 }
1489
1490 void
1491 ips_link_to_i915_driver(void)
1492 {
1493         /* We can't cleanly get at the various ips_driver structs from
1494          * this caller (the i915 driver), so just set a flag saying
1495          * that it's time to try getting the symbols again.
1496          */
1497         late_i915_load = true;
1498 }
1499 EXPORT_SYMBOL_GPL(ips_link_to_i915_driver);
1500
1501 static DEFINE_PCI_DEVICE_TABLE(ips_id_table) = {
1502         { PCI_DEVICE(PCI_VENDOR_ID_INTEL,
1503                      PCI_DEVICE_ID_INTEL_THERMAL_SENSOR), },
1504         { 0, }
1505 };
1506
1507 MODULE_DEVICE_TABLE(pci, ips_id_table);
1508
1509 static int ips_blacklist_callback(const struct dmi_system_id *id)
1510 {
1511         pr_info("Blacklisted intel_ips for %s\n", id->ident);
1512         return 1;
1513 }
1514
1515 static const struct dmi_system_id ips_blacklist[] = {
1516         {
1517                 .callback = ips_blacklist_callback,
1518                 .ident = "HP ProBook",
1519                 .matches = {
1520                         DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
1521                         DMI_MATCH(DMI_PRODUCT_NAME, "HP ProBook"),
1522                 },
1523         },
1524         { }     /* terminating entry */
1525 };
1526
1527 static int ips_probe(struct pci_dev *dev, const struct pci_device_id *id)
1528 {
1529         u64 platform_info;
1530         struct ips_driver *ips;
1531         u32 hts;
1532         int ret = 0;
1533         u16 htshi, trc, trc_required_mask;
1534         u8 tse;
1535
1536         if (dmi_check_system(ips_blacklist))
1537                 return -ENODEV;
1538
1539         ips = kzalloc(sizeof(struct ips_driver), GFP_KERNEL);
1540         if (!ips)
1541                 return -ENOMEM;
1542
1543         pci_set_drvdata(dev, ips);
1544         ips->dev = dev;
1545
1546         ips->limits = ips_detect_cpu(ips);
1547         if (!ips->limits) {
1548                 dev_info(&dev->dev, "IPS not supported on this CPU\n");
1549                 ret = -ENXIO;
1550                 goto error_free;
1551         }
1552
1553         spin_lock_init(&ips->turbo_status_lock);
1554
1555         ret = pci_enable_device(dev);
1556         if (ret) {
1557                 dev_err(&dev->dev, "can't enable PCI device, aborting\n");
1558                 goto error_free;
1559         }
1560
1561         if (!pci_resource_start(dev, 0)) {
1562                 dev_err(&dev->dev, "TBAR not assigned, aborting\n");
1563                 ret = -ENXIO;
1564                 goto error_free;
1565         }
1566
1567         ret = pci_request_regions(dev, "ips thermal sensor");
1568         if (ret) {
1569                 dev_err(&dev->dev, "thermal resource busy, aborting\n");
1570                 goto error_free;
1571         }
1572
1573
1574         ips->regmap = ioremap(pci_resource_start(dev, 0),
1575                               pci_resource_len(dev, 0));
1576         if (!ips->regmap) {
1577                 dev_err(&dev->dev, "failed to map thermal regs, aborting\n");
1578                 ret = -EBUSY;
1579                 goto error_release;
1580         }
1581
1582         tse = thm_readb(THM_TSE);
1583         if (tse != TSE_EN) {
1584                 dev_err(&dev->dev, "thermal device not enabled (0x%02x), aborting\n", tse);
1585                 ret = -ENXIO;
1586                 goto error_unmap;
1587         }
1588
1589         trc = thm_readw(THM_TRC);
1590         trc_required_mask = TRC_CORE1_EN | TRC_CORE_PWR | TRC_MCH_EN;
1591         if ((trc & trc_required_mask) != trc_required_mask) {
1592                 dev_err(&dev->dev, "thermal reporting for required devices not enabled, aborting\n");
1593                 ret = -ENXIO;
1594                 goto error_unmap;
1595         }
1596
1597         if (trc & TRC_CORE2_EN)
1598                 ips->second_cpu = true;
1599
1600         update_turbo_limits(ips);
1601         dev_dbg(&dev->dev, "max cpu power clamp: %dW\n",
1602                 ips->mcp_power_limit / 10);
1603         dev_dbg(&dev->dev, "max core power clamp: %dW\n",
1604                 ips->core_power_limit / 10);
1605         /* BIOS may update limits at runtime */
1606         if (thm_readl(THM_PSC) & PSP_PBRT)
1607                 ips->poll_turbo_status = true;
1608
1609         if (!ips_get_i915_syms(ips)) {
1610                 dev_err(&dev->dev, "failed to get i915 symbols, graphics turbo disabled\n");
1611                 ips->gpu_turbo_enabled = false;
1612         } else {
1613                 dev_dbg(&dev->dev, "graphics turbo enabled\n");
1614                 ips->gpu_turbo_enabled = true;
1615         }
1616
1617         /*
1618          * Check PLATFORM_INFO MSR to make sure this chip is
1619          * turbo capable.
1620          */
1621         rdmsrl(PLATFORM_INFO, platform_info);
1622         if (!(platform_info & PLATFORM_TDP)) {
1623                 dev_err(&dev->dev, "platform indicates TDP override unavailable, aborting\n");
1624                 ret = -ENODEV;
1625                 goto error_unmap;
1626         }
1627
1628         /*
1629          * IRQ handler for ME interaction
1630          * Note: don't use MSI here as the PCH has bugs.
1631          */
1632         pci_disable_msi(dev);
1633         ret = request_irq(dev->irq, ips_irq_handler, IRQF_SHARED, "ips",
1634                           ips);
1635         if (ret) {
1636                 dev_err(&dev->dev, "request irq failed, aborting\n");
1637                 goto error_unmap;
1638         }
1639
1640         /* Enable aux, hot & critical interrupts */
1641         thm_writeb(THM_TSPIEN, TSPIEN_AUX2_LOHI | TSPIEN_CRIT_LOHI |
1642                    TSPIEN_HOT_LOHI | TSPIEN_AUX_LOHI);
1643         thm_writeb(THM_TEN, TEN_UPDATE_EN);
1644
1645         /* Collect adjustment values */
1646         ips->cta_val = thm_readw(THM_CTA);
1647         ips->pta_val = thm_readw(THM_PTA);
1648         ips->mgta_val = thm_readw(THM_MGTA);
1649
1650         /* Save turbo limits & ratios */
1651         rdmsrl(TURBO_POWER_CURRENT_LIMIT, ips->orig_turbo_limit);
1652
1653         ips_disable_cpu_turbo(ips);
1654         ips->cpu_turbo_enabled = false;
1655
1656         /* Create thermal adjust thread */
1657         ips->adjust = kthread_create(ips_adjust, ips, "ips-adjust");
1658         if (IS_ERR(ips->adjust)) {
1659                 dev_err(&dev->dev,
1660                         "failed to create thermal adjust thread, aborting\n");
1661                 ret = -ENOMEM;
1662                 goto error_free_irq;
1663
1664         }
1665
1666         /*
1667          * Set up the work queue and monitor thread. The monitor thread
1668          * will wake up ips_adjust thread.
1669          */
1670         ips->monitor = kthread_run(ips_monitor, ips, "ips-monitor");
1671         if (IS_ERR(ips->monitor)) {
1672                 dev_err(&dev->dev,
1673                         "failed to create thermal monitor thread, aborting\n");
1674                 ret = -ENOMEM;
1675                 goto error_thread_cleanup;
1676         }
1677
1678         hts = (ips->core_power_limit << HTS_PCPL_SHIFT) |
1679                 (ips->mcp_temp_limit << HTS_PTL_SHIFT) | HTS_NVV;
1680         htshi = HTS2_PRST_RUNNING << HTS2_PRST_SHIFT;
1681
1682         thm_writew(THM_HTSHI, htshi);
1683         thm_writel(THM_HTS, hts);
1684
1685         ips_debugfs_init(ips);
1686
1687         dev_info(&dev->dev, "IPS driver initialized, MCP temp limit %d\n",
1688                  ips->mcp_temp_limit);
1689         return ret;
1690
1691 error_thread_cleanup:
1692         kthread_stop(ips->adjust);
1693 error_free_irq:
1694         free_irq(ips->dev->irq, ips);
1695 error_unmap:
1696         iounmap(ips->regmap);
1697 error_release:
1698         pci_release_regions(dev);
1699 error_free:
1700         kfree(ips);
1701         return ret;
1702 }
1703
1704 static void ips_remove(struct pci_dev *dev)
1705 {
1706         struct ips_driver *ips = pci_get_drvdata(dev);
1707         u64 turbo_override;
1708
1709         if (!ips)
1710                 return;
1711
1712         ips_debugfs_cleanup(ips);
1713
1714         /* Release i915 driver */
1715         if (ips->read_mch_val)
1716                 symbol_put(i915_read_mch_val);
1717         if (ips->gpu_raise)
1718                 symbol_put(i915_gpu_raise);
1719         if (ips->gpu_lower)
1720                 symbol_put(i915_gpu_lower);
1721         if (ips->gpu_busy)
1722                 symbol_put(i915_gpu_busy);
1723         if (ips->gpu_turbo_disable)
1724                 symbol_put(i915_gpu_turbo_disable);
1725
1726         rdmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
1727         turbo_override &= ~(TURBO_TDC_OVR_EN | TURBO_TDP_OVR_EN);
1728         wrmsrl(TURBO_POWER_CURRENT_LIMIT, turbo_override);
1729         wrmsrl(TURBO_POWER_CURRENT_LIMIT, ips->orig_turbo_limit);
1730
1731         free_irq(ips->dev->irq, ips);
1732         if (ips->adjust)
1733                 kthread_stop(ips->adjust);
1734         if (ips->monitor)
1735                 kthread_stop(ips->monitor);
1736         iounmap(ips->regmap);
1737         pci_release_regions(dev);
1738         kfree(ips);
1739         dev_dbg(&dev->dev, "IPS driver removed\n");
1740 }
1741
1742 #ifdef CONFIG_PM
1743 static int ips_suspend(struct pci_dev *dev, pm_message_t state)
1744 {
1745         return 0;
1746 }
1747
1748 static int ips_resume(struct pci_dev *dev)
1749 {
1750         return 0;
1751 }
1752 #else
1753 #define ips_suspend NULL
1754 #define ips_resume NULL
1755 #endif /* CONFIG_PM */
1756
1757 static void ips_shutdown(struct pci_dev *dev)
1758 {
1759 }
1760
1761 static struct pci_driver ips_pci_driver = {
1762         .name = "intel ips",
1763         .id_table = ips_id_table,
1764         .probe = ips_probe,
1765         .remove = ips_remove,
1766         .suspend = ips_suspend,
1767         .resume = ips_resume,
1768         .shutdown = ips_shutdown,
1769 };
1770
1771 static int __init ips_init(void)
1772 {
1773         return pci_register_driver(&ips_pci_driver);
1774 }
1775 module_init(ips_init);
1776
1777 static void ips_exit(void)
1778 {
1779         pci_unregister_driver(&ips_pci_driver);
1780         return;
1781 }
1782 module_exit(ips_exit);
1783
1784 MODULE_LICENSE("GPL");
1785 MODULE_AUTHOR("Jesse Barnes <jbarnes@virtuousgeek.org>");
1786 MODULE_DESCRIPTION("Intelligent Power Sharing Driver");