hwmon:tegra:tsensor driver added
[linux-2.6.git] / drivers / hwmon / tegra-tsensor.c
1 /*
2  * NVIDIA Tegra SOC - temperature sensor driver
3  *
4  * Copyright (C) 2011 NVIDIA Corporation
5  *
6  * This software is licensed under the terms of the GNU General Public
7  * License version 2, as published by the Free Software Foundation, and
8  * may be copied, distributed, and modified under those terms.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 #if 0
18 #define VERBOSE_DEBUG
19 #define DEBUG
20 #endif
21
22 #include <linux/slab.h>
23 #include <linux/platform_device.h>
24 #include <linux/hwmon.h>
25 #include <linux/clk.h>
26 #include <linux/io.h>
27 #include <linux/irq.h>
28 #include <linux/interrupt.h>
29 #include <linux/irqreturn.h>
30 #include <linux/err.h>
31 #include <linux/spinlock.h>
32 #include <linux/hwmon-sysfs.h>
33 #include <linux/regulator/consumer.h>
34 #include <linux/delay.h>
35
36 #include <mach/iomap.h>
37 #include <mach/clk.h>
38 #include <mach/delay.h>
39 #include <mach/tsensor.h>
40
41 /* We have multiple tsensor instances with following registers */
42 #define SENSOR_CFG0                             0x40
43 #define SENSOR_CFG1                             0x48
44 #define SENSOR_CFG2                             0x4c
45 #define SENSOR_STATUS0                          0x58
46 #define SENSOR_TS_STATUS1                       0x5c
47 #define SENSOR_TS_STATUS2                       0x60
48
49 /* interrupt mask in tsensor status register */
50 #define TSENSOR_SENSOR_X_STATUS0_0_INTR_MASK    (1 << 8)
51
52 #define SENSOR_CFG0_M_MASK                      0xffff
53 #define SENSOR_CFG0_M_SHIFT                     8
54 #define SENSOR_CFG0_N_MASK                      0xff
55 #define SENSOR_CFG0_N_SHIFT                     24
56 #define SENSOR_CFG0_RST_INTR_SHIFT              6
57 #define SENSOR_CFG0_HW_DIV2_INTR_SHIFT          5
58 #define SENSOR_CFG0_OVERFLOW_INTR               4
59 #define SENSOR_CFG0_RST_ENABLE_SHIFT            2
60 #define SENSOR_CFG0_HW_DIV2_ENABLE_SHIFT        1
61 #define SENSOR_CFG0_STOP_SHIFT                  0
62
63 #define SENSOR_CFG_X_TH_X_MASK                  0xffff
64 #define SENSOR_CFG1_TH2_SHIFT                   16
65 #define SENSOR_CFG1_TH1_SHIFT                   0
66 #define SENSOR_CFG2_TH3_SHIFT                   0
67 #define SENSOR_CFG2_TH0_SHIFT                   16
68
69 #define SENSOR_STATUS_AVG_VALID_SHIFT           10
70 #define SENSOR_STATUS_CURR_VALID_SHIFT          9
71
72 #define STATE_MASK                              0x7
73 #define STATUS0_STATE_SHIFT                     0
74 #define STATUS0_PREV_STATE_SHIFT                4
75
76 #define LOCAL_STR_SIZE1                         60
77 #define MAX_STR_LINE                            100
78 #define MAX_TSENSOR_LOOP1                       (1000 * 2)
79
80 /* fuse spare bits are used to get Tj-ADT values */
81 #define FUSE_SPARE_BIT_0_0                      0x244
82 #define FUSE_SPARE_BIT_6_0                      0x25c
83 #define FUSE_SPARE_BIT_20_0                     0x294
84 #define NUM_FUSE_REGS                           7
85
86 #define FUSE_TSENSOR_CALIB_0                    0x198
87
88 #define TSENSOR_COUNTER_TOLERANCE               100
89
90 #define SENSOR_CTRL_RST_SHIFT                   1
91 #define RST_SRC_MASK                            0x7
92 #define RST_SRC_SENSOR                          2
93 #define TEGRA_REV_REG_OFFSET                    0x804
94 #define CCLK_G_BURST_POLICY_REG_REL_OFFSET      0x368
95 #define TSENSOR_SLOWDOWN_BIT                    23
96
97 /* macros used for temperature calculations */
98 #define get_temperature_int(X)                  ((X) / 100)
99 #define get_temperature_fraction(X)             (((int)(abs(X))) % 100)
100 #define get_temperature_round(X)                DIV_ROUND_CLOSEST(X, 100)
101
102 /* tsensor states */
103 enum ts_state {
104         TS_INVALID = 0,
105         TS_LEVEL0,
106         TS_LEVEL1,
107         TS_LEVEL2,
108         TS_LEVEL3,
109         TS_OVERFLOW,
110         TS_MAX_STATE = TS_OVERFLOW
111 };
112
113 /* composite type with tsensor state */
114 struct tsensor_state {
115         unsigned int prev_state;
116         unsigned int state;
117 };
118
119 enum {
120         /* temperature is sensed from 2 points on tegra */
121         TSENSOR_COUNT = 2,
122         /* divide by 2 temperature threshold */
123         DIV2_CELSIUS_TEMP_THRESHOLD_DEFAULT = 70,
124         /* reset chip temperature threshold */
125         RESET_CELSIUS_TEMP_THRESHOLD_DEFAULT = 75,
126         /* tsensor frequency in Hz for clk src CLK_M and divisor=24 */
127         DEFAULT_TSENSOR_CLK_HZ = 500000,
128         DEFAULT_TSENSOR_N = 255,
129         DEFAULT_TSENSOR_M = 500,
130         /* tsensor instance offset */
131         TSENSOR_INSTANCE_OFFSET = 0x40,
132         MIN_THRESHOLD = 0x0,
133         MAX_THRESHOLD = 0xffff,
134         DEFAULT_THRESHOLD_TH0 = MAX_THRESHOLD,
135         DEFAULT_THRESHOLD_TH1 = MAX_THRESHOLD,
136         DEFAULT_THRESHOLD_TH2 = MAX_THRESHOLD,
137         DEFAULT_THRESHOLD_TH3 = MAX_THRESHOLD,
138 };
139
140 /* constants used to implement sysfs interface */
141 enum tsensor_params {
142         TSENSOR_PARAM_TH1 = 0,
143         TSENSOR_PARAM_TH2,
144         TSENSOR_PARAM_TH3,
145         TSENSOR_TEMPERATURE
146 };
147
148 /*
149  * For each registered chip, we need to keep some data in memory.
150  * The structure is dynamically allocated.
151  */
152 struct tegra_tsensor_data {
153         struct device *hwmon_dev;
154         spinlock_t tsensor_lock;
155         struct clk *dev_clk;
156         /* tsensor register space */
157         void __iomem            *base;
158         unsigned long           phys;
159         unsigned long           phys_end;
160         /* pmc register space */
161         void __iomem            *pmc_rst_base;
162         unsigned long           pmc_phys;
163         unsigned long           pmc_phys_end;
164         /* clk register space */
165         void __iomem            *clk_rst_base;
166         int                     irq;
167         unsigned int            int_status[TSENSOR_COUNT];
168
169         /* threshold for hardware triggered clock divide by 2 */
170         int div2_temp;
171         /* temperature threshold for hardware triggered system reset */
172         int reset_temp;
173         /* temperature threshold to trigger software interrupt */
174         int sw_intr_temp;
175         int hysteresis;
176         unsigned int ts_state_saved[TSENSOR_COUNT];
177 };
178
179 enum {
180         TSENSOR_COEFF_SET1 = 0,
181         TSENSOR_COEFF_END
182 };
183
184 struct tegra_tsensor_coeff {
185         int e_minus6_m;
186         int e_minus6_n;
187         int e_minus2_p;
188 };
189
190 static struct tegra_tsensor_coeff coeff_table[] = {
191         [TSENSOR_COEFF_SET1] = {
192                 -2775,
193                 1338811,
194                 -730
195         }
196         /* FIXME: add tsensor coefficients after chip characterization */
197 };
198
199 static unsigned int tsensor_index;
200 static char my_fixed_str[LOCAL_STR_SIZE1] = "YYYYYY";
201 static char error_str[LOCAL_STR_SIZE1] = "ERROR:";
202 static unsigned int fuse_T1, fuse_F1, fuse_T2, fuse_F2;
203 static int A_e_minus6, B_e_minus2;
204 static int m_e_minus6;
205 static int n_e_minus6;
206 static int p_e_minus2;
207 static unsigned int init_flag;
208
209 static int tsensor_count_2_temp(struct tegra_tsensor_data *data,
210         unsigned int count, int *p_temperature);
211 static unsigned int tsensor_get_threshold_counter(
212         struct tegra_tsensor_data *data, unsigned int temp);
213
214 /* tsensor register access functions */
215
216 static void tsensor_writel(struct tegra_tsensor_data *data, u32 val,
217                                 unsigned long reg)
218 {
219         unsigned int reg_offset = reg & 0xffff;
220         unsigned char inst = (reg >> 16) & 0xffff;
221         writel(val, data->base + (inst * TSENSOR_INSTANCE_OFFSET) +
222                 reg_offset);
223         return;
224 }
225
226 static unsigned int tsensor_readl(struct tegra_tsensor_data *data,
227                                 unsigned long reg)
228 {
229         unsigned int reg_offset = reg & 0xffff;
230         unsigned char inst = (reg >> 16) & 0xffff;
231         return readl(data->base +
232                 (inst * TSENSOR_INSTANCE_OFFSET) + reg_offset);
233 }
234
235 static unsigned int tsensor_get_reg_field(
236         struct tegra_tsensor_data *data, unsigned int reg,
237         unsigned int shift, unsigned int mask)
238 {
239         unsigned int reg_val;
240         reg_val = tsensor_readl(data, reg);
241         return (reg_val & (mask << shift)) >> shift;
242 }
243
244 static int tsensor_set_reg_field(
245         struct tegra_tsensor_data *data, unsigned int value,
246         unsigned int reg, unsigned int shift, unsigned int mask)
247 {
248         unsigned int reg_val;
249         unsigned int rd_val;
250         reg_val = tsensor_readl(data, reg);
251         reg_val &= ~(mask << shift);
252         reg_val |= ((value & mask) << shift);
253         tsensor_writel(data, reg_val, reg);
254         rd_val = tsensor_readl(data, reg);
255         if (rd_val == reg_val)
256                 return 0;
257         else
258                 return -EINVAL;
259 }
260
261 /* enable argument is true to enable reset, false disables pmc reset */
262 static void pmc_rst_enable(struct tegra_tsensor_data *data, bool enable)
263 {
264         unsigned int val;
265         /* mapped first pmc reg is SENSOR_CTRL */
266         val = readl(data->pmc_rst_base);
267         if (enable)
268                 val |= (1 << SENSOR_CTRL_RST_SHIFT);
269         else
270                 val &= ~(1 << SENSOR_CTRL_RST_SHIFT);
271         writel(val, data->pmc_rst_base);
272 }
273
274 /* true returned when pmc reset source is tsensor */
275 static bool pmc_check_rst_sensor(struct tegra_tsensor_data *data)
276 {
277         unsigned int val;
278         unsigned char src;
279         val = readl(data->pmc_rst_base + 4);
280         src = (unsigned char)(val & RST_SRC_MASK);
281         if (src == RST_SRC_SENSOR)
282                 return true;
283         else
284                 return false;
285 }
286
287 /* function to get chip revision */
288 static void get_chip_rev(unsigned short *p_id, unsigned short *p_major,
289                 unsigned short *p_minor)
290 {
291         unsigned int reg;
292
293         reg = readl(IO_TO_VIRT(TEGRA_APB_MISC_BASE) +
294                 TEGRA_REV_REG_OFFSET);
295         *p_id = (reg >> 8) & 0xff;
296         *p_major = (reg >> 4) & 0xf;
297         *p_minor = (reg >> 16) & 0xf;
298         pr_info("\n Tegra chip revision for tsensor detected as: "
299                 " Chip Id=%d, Major=%d, Minor=%d ", (int)*p_id,
300                 (int)*p_major, (int)*p_minor);
301 }
302
303 /*
304  * function to get chip revision specific tsensor coefficients
305  * obtained after chip characterization
306  */
307 static int get_chip_tsensor_coeff(void)
308 {
309         unsigned short chip_id, major_rev, minor_rev;
310         unsigned short coeff_index;
311
312         get_chip_rev(&chip_id, &major_rev, &minor_rev);
313         switch (minor_rev) {
314         case 2:
315                 pr_info("\n Warning: tsensor coefficient for chip pending ");
316         case 1:
317                 coeff_index = TSENSOR_COEFF_SET1;
318                 break;
319         default:
320                 pr_err("\n Error: tsensor unsupported for detected chip ");
321                 return -ENOENT;
322         }
323         m_e_minus6 = coeff_table[coeff_index].e_minus6_m;
324         n_e_minus6 = coeff_table[coeff_index].e_minus6_n;
325         p_e_minus2 = coeff_table[coeff_index].e_minus2_p;
326         return 0;
327 }
328
329 /* tsensor counter read function */
330 static unsigned int tsensor_read_counter(
331         struct tegra_tsensor_data *data, u8 instance,
332         unsigned int *p_counterA, unsigned int *p_counterB)
333 {
334         unsigned int status_reg;
335         unsigned int config0;
336         int iter_count = 0;
337         const int max_loop = 50;
338
339         do {
340                 config0 = tsensor_readl(data, ((instance << 16) |
341                         SENSOR_CFG0));
342                 if (config0 & (1 << SENSOR_CFG0_STOP_SHIFT)) {
343                         dev_dbg(data->hwmon_dev, "\n Error: tsensor "
344                                 "counter read with STOP bit not supported ");
345                         *p_counterA = 0;
346                         *p_counterB = 0;
347                         return 0;
348                 }
349                 status_reg = tsensor_readl(data,
350                         (instance << 16) | SENSOR_STATUS0);
351                 if ((status_reg & (1 <<
352                         SENSOR_STATUS_AVG_VALID_SHIFT)) &&
353                         (status_reg & (1 <<
354                         SENSOR_STATUS_CURR_VALID_SHIFT))) {
355                         *p_counterA = tsensor_readl(data, (instance
356                                 << 16) | SENSOR_TS_STATUS1);
357                         *p_counterB = tsensor_readl(data, (instance
358                                 << 16) | SENSOR_TS_STATUS2);
359                         break;
360                 }
361                 if (!(iter_count % 10))
362                         dev_dbg(data->hwmon_dev, "\n retry %d ", iter_count);
363                 msleep(1);
364                 iter_count++;
365         } while (iter_count < max_loop);
366         if (iter_count == max_loop)
367                 return -ENODEV;
368         return 0;
369 }
370
371 /* tsensor threshold print function */
372 static void dump_threshold(struct tegra_tsensor_data *data)
373 {
374         int i;
375         unsigned int TH_2_1, TH_0_3;
376         unsigned int curr_avg, min_max;
377         int err;
378         for (i = 0; i < TSENSOR_COUNT; i++) {
379                 TH_2_1 = tsensor_readl(data, ((i << 16) | SENSOR_CFG1));
380                 TH_0_3 = tsensor_readl(data, ((i << 16) | SENSOR_CFG2));
381                 dev_dbg(data->hwmon_dev, "\n Tsensor[%d]: TH_2_1=0x%x, "
382                         "TH_0_3=0x%x ", i, TH_2_1, TH_0_3);
383                 err = tsensor_read_counter(data, i, &curr_avg, &min_max);
384                 if (err < 0)
385                         pr_err("\n Error: tsensor %d counter read, "
386                                 "err=%d ", i, err);
387                 else
388                         dev_dbg(data->hwmon_dev, "\n Tsensor[%d]: "
389                                 "curr_avg=0x%x, min_max=0x%x ",
390                                 i, curr_avg, min_max);
391         }
392 }
393
394 /* tsensor temperature show function */
395 static ssize_t tsensor_show_counters(struct device *dev,
396         struct device_attribute *da, char *buf)
397 {
398         int i;
399         unsigned int curr_avg[TSENSOR_COUNT];
400         unsigned int min_max[TSENSOR_COUNT];
401         char err_str[] = "error-sysfs-counter-read\n";
402         char fixed_str[MAX_STR_LINE];
403         struct tegra_tsensor_data *data = dev_get_drvdata(dev);
404         struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
405         int err;
406         int temp0, temp1;
407
408         if (attr->index == TSENSOR_TEMPERATURE)
409                 snprintf(fixed_str, MAX_STR_LINE, "temperature: ");
410         for (i = 0; i < TSENSOR_COUNT; i++) {
411                 err = tsensor_read_counter(data, i,
412                         &curr_avg[i], &min_max[i]);
413                 if (err < 0)
414                         goto error;
415         }
416         if (attr->index == TSENSOR_TEMPERATURE) {
417                 /* use current counter value to calculate temperature */
418                 err = tsensor_count_2_temp(data,
419                         ((curr_avg[0] & 0xFFFF0000) >> 16), &temp0);
420                 dev_vdbg(data->hwmon_dev, "\n %s has curr_avg=0x%x, "
421                         "minmax=0x%x, temp0=%d ", __func__,
422                         curr_avg[0], min_max[0], temp0);
423                 if (err < 0)
424                         goto error;
425                 err = tsensor_count_2_temp(data,
426                         ((curr_avg[1] & 0xFFFF0000) >> 16), &temp1);
427                 dev_vdbg(data->hwmon_dev, "\n %s has curr_avg=0x%x, "
428                         "minmax=0x%x, temp1=%d ", __func__,
429                         curr_avg[1], min_max[1], temp1);
430                 if (err < 0)
431                         goto error;
432                 snprintf(buf, (((LOCAL_STR_SIZE1 << 1) + 3) +
433                         strlen(fixed_str)),
434                         "%s "
435                         "[1]: current counter=0x%x, %d.%d"
436                         " deg Celsius ", fixed_str,
437                         ((curr_avg[1] & 0xFFFF0000) >> 16),
438                         get_temperature_int(temp1),
439                         get_temperature_fraction(temp1));
440         } else {
441                 snprintf(buf, ((LOCAL_STR_SIZE1 << 1) + 3) +
442                         strlen(fixed_str),
443                         "%s[%d %d %d %d] ",
444                         fixed_str,
445                         ((curr_avg[0] >> 16) & 0xffff),
446                         (curr_avg[0] & 0xffff),
447                         ((min_max[0] >> 16) & 0xffff),
448                         (min_max[0] & 0xffff));
449         }
450         strcat(buf, "\n");
451         return strlen(buf);
452 error:
453         return snprintf(buf, strlen(err_str),
454                 "%s", err_str);
455 }
456
457 /* utility function to check hw clock divide by 2 condition */
458 static bool cclkg_check_hwdiv2_sensor(struct tegra_tsensor_data *data)
459 {
460         unsigned int val;
461         val = readl(IO_ADDRESS(TEGRA_CLK_RESET_BASE +
462                 CCLK_G_BURST_POLICY_REG_REL_OFFSET));
463         if ((1 << TSENSOR_SLOWDOWN_BIT) & val) {
464                 dev_err(data->hwmon_dev, "\n Warning: ***** tsensor "
465                         "slowdown bit detected ");
466                 return true;
467         } else {
468                 return false;
469         }
470 }
471
472 /*
473  * function with table to return register, field shift and mask
474  * values for supported parameters
475  */
476 static int get_param_values(unsigned int indx,
477         unsigned int *p_reg, unsigned int *p_sft, unsigned int *p_msk)
478 {
479         switch (indx) {
480         case TSENSOR_PARAM_TH1:
481                 *p_reg = ((tsensor_index << 16) | SENSOR_CFG1);
482                 *p_sft = SENSOR_CFG1_TH1_SHIFT;
483                 *p_msk = SENSOR_CFG_X_TH_X_MASK;
484                 snprintf(my_fixed_str, LOCAL_STR_SIZE1, "TH1[%d]: ",
485                         tsensor_index);
486                 break;
487         case TSENSOR_PARAM_TH2:
488                 *p_reg = ((tsensor_index << 16) | SENSOR_CFG1);
489                 *p_sft = SENSOR_CFG1_TH2_SHIFT;
490                 *p_msk = SENSOR_CFG_X_TH_X_MASK;
491                 snprintf(my_fixed_str, LOCAL_STR_SIZE1, "TH2[%d]: ",
492                         tsensor_index);
493                 break;
494         case TSENSOR_PARAM_TH3:
495                 *p_reg = ((tsensor_index << 16) | SENSOR_CFG2);
496                 *p_sft = SENSOR_CFG2_TH3_SHIFT;
497                 *p_msk = SENSOR_CFG_X_TH_X_MASK;
498                 snprintf(my_fixed_str, LOCAL_STR_SIZE1, "TH3[%d]: ",
499                         tsensor_index);
500                 break;
501         default:
502                 return -ENOENT;
503         }
504         return 0;
505 }
506
507 /* tsensor driver sysfs show function */
508 static ssize_t show_tsensor_param(struct device *dev,
509                                 struct device_attribute *da,
510                                 char *buf)
511 {
512         unsigned int val;
513         struct tegra_tsensor_data *data = dev_get_drvdata(dev);
514         struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
515         unsigned int reg;
516         unsigned int sft;
517         unsigned int msk;
518         int err;
519
520         err = get_param_values(attr->index, &reg, &sft, &msk);
521         if (err < 0)
522                 goto labelErr;
523         val = tsensor_get_reg_field(data, reg, sft, msk);
524         snprintf(buf, LOCAL_STR_SIZE1 + strlen(my_fixed_str), "%s%d",
525                 my_fixed_str, val);
526         strcat(buf, "\n");
527         return strlen(buf);
528 labelErr:
529         snprintf(buf, strlen(error_str), "%s", error_str);
530         return strlen(buf);
531 }
532
533 /* tsensor driver sysfs store function */
534 static ssize_t set_tsensor_param(struct device *dev,
535                         struct device_attribute *da,
536                         const char *buf, size_t count)
537 {
538         int num;
539         struct tegra_tsensor_data *data = dev_get_drvdata(dev);
540         struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
541         unsigned int reg;
542         unsigned int sft;
543         unsigned int msk;
544         int err;
545         unsigned int counter;
546
547         if (strict_strtoul(buf, 0, (long int *)&num)) {
548                 dev_err(dev, "\n file: %s, line=%d return %s() ",
549                         __FILE__, __LINE__, __func__);
550                 return -EINVAL;
551         }
552
553         counter = tsensor_get_threshold_counter(data, num);
554
555         err = get_param_values(attr->index, &reg, &sft, &msk);
556         if (err < 0)
557                 goto labelErr;
558
559         err = tsensor_set_reg_field(data, counter, reg, sft, msk);
560         if (err < 0)
561                 goto labelErr;
562
563         /* TH2 clk divide check */
564         if (attr->index == TSENSOR_PARAM_TH2) {
565                 msleep(20);
566                 (void)cclkg_check_hwdiv2_sensor(data);
567         }
568         return count;
569 labelErr:
570         dev_err(dev, "\n file: %s, line=%d, %s(), error=0x%x ", __FILE__,
571                 __LINE__, __func__, err);
572         return 0;
573 }
574
575 static SENSOR_DEVICE_ATTR(tsensor_TH1, S_IRUGO | S_IWUSR,
576                 show_tsensor_param, set_tsensor_param, TSENSOR_PARAM_TH1);
577 static SENSOR_DEVICE_ATTR(tsensor_TH2, S_IRUGO | S_IWUSR,
578                 show_tsensor_param, set_tsensor_param, TSENSOR_PARAM_TH2);
579 static SENSOR_DEVICE_ATTR(tsensor_TH3, S_IRUGO | S_IWUSR,
580                 show_tsensor_param, set_tsensor_param, TSENSOR_PARAM_TH3);
581 static SENSOR_DEVICE_ATTR(tsensor_temperature, S_IRUGO | S_IWUSR,
582                 tsensor_show_counters, NULL, TSENSOR_TEMPERATURE);
583
584 static struct attribute *tsensor_attributes[] = {
585         &sensor_dev_attr_tsensor_TH1.dev_attr.attr,
586         &sensor_dev_attr_tsensor_TH2.dev_attr.attr,
587         &sensor_dev_attr_tsensor_TH3.dev_attr.attr,
588         &sensor_dev_attr_tsensor_temperature.dev_attr.attr,
589         NULL
590 };
591
592 static const struct attribute_group tsensor_attr_group = {
593         .attrs = tsensor_attributes,
594 };
595
596 /*
597  * returns current state of tsensor
598  * input: tsensor instance
599  *      initializes argument pointer to tsensor_state
600  */
601 static void get_ts_state(struct tegra_tsensor_data *data,
602         unsigned char inst, struct tsensor_state *p_state)
603 {
604         p_state->prev_state =
605                 tsensor_get_reg_field(data,
606                 ((inst << 16) | SENSOR_STATUS0),
607                 STATUS0_PREV_STATE_SHIFT, STATE_MASK);
608         p_state->state =
609                 tsensor_get_reg_field(data,
610                 ((inst << 16) | SENSOR_STATUS0),
611                 STATUS0_STATE_SHIFT, STATE_MASK);
612 }
613
614 /* tsensor driver interrupt handler */
615 static irqreturn_t tegra_tsensor_isr(int irq, void *arg_data)
616 {
617         struct tegra_tsensor_data *data =
618                 (struct tegra_tsensor_data *)arg_data;
619         unsigned long flags;
620         unsigned int val;
621         unsigned int i;
622         struct tsensor_state new_state;
623
624         spin_lock_irqsave(&data->tsensor_lock, flags);
625
626         for (i = 0; i < TSENSOR_COUNT; i++) {
627                 val = tsensor_readl(data, ((i << 16) | SENSOR_STATUS0));
628                 tsensor_writel(data, val, ((i << 16) | SENSOR_STATUS0));
629                 if (val & TSENSOR_SENSOR_X_STATUS0_0_INTR_MASK) {
630                         dev_err(data->hwmon_dev, "\n tsensor instance-%d "
631                                 "interrupt ", i);
632                         get_ts_state(data, (unsigned char)i, &new_state);
633                         /* counter overflow check */
634                         if (new_state.state == TS_OVERFLOW)
635                                 dev_err(data->hwmon_dev, "\nWarning: "
636                                         "***** OVERFLOW tsensor ");
637                         if (new_state.state != data->ts_state_saved[i]) {
638                                 dev_err(data->hwmon_dev, "\nTS state "
639                                         "change: old=%d, new=%d ",
640                                         data->ts_state_saved[i],
641                                         new_state.state);
642                                 data->ts_state_saved[i] = new_state.state;
643                         }
644                 }
645         }
646
647         spin_unlock_irqrestore(&data->tsensor_lock, flags);
648
649         return IRQ_HANDLED;
650 }
651
652 /*
653  * function to read fuse registers and give - T1, T2, F1 and F2
654  */
655 static int read_tsensor_fuse_regs(struct tegra_tsensor_data *data)
656 {
657         unsigned int reg1, reg2;
658         int i;
659         unsigned int start, offset1;
660         unsigned int T1, T2;
661
662         /* read tsensor calibration register */
663         /*
664          * High (~90 DegC) Temperature Calibration value (upper 16 bits of
665          *          FUSE_TSENSOR_CALIB_0) - F2
666          * Low (~25 deg C) Temperature Calibration value (lower 16 bits of
667          *          FUSE_TSENSOR_CALIB_0) - F1
668          */
669         reg1 = readl(IO_ADDRESS(TEGRA_FUSE_BASE + FUSE_TSENSOR_CALIB_0));
670         fuse_F1 = reg1 & 0xFFFF;
671         fuse_F2 = (reg1 >> 16) & 0xFFFF;
672
673         /*
674          * FUSE_TJ_ADT_LOWT = T1, FUSE_TJ_ADJ = T2
675          */
676
677         /*
678          * Low temp is:
679          * FUSE_TJ_ADT_LOWT = bits [20:14] or’ed with bits [27:21]
680          */
681         dev_vdbg(data->hwmon_dev, "\n Tsensor low temp (T1) fuse : ");
682         T1 = 0;
683         start = FUSE_SPARE_BIT_20_0;
684         offset1 = NUM_FUSE_REGS * 4;
685         for (i = 0; i < NUM_FUSE_REGS; i++) {
686                 reg1 = readl(IO_ADDRESS((unsigned int)TEGRA_FUSE_BASE +
687                         start - (i << 2)));
688                 dev_vdbg(data->hwmon_dev, "\n FUSE_SPARE_BIT_%d_0: 0x%x ",
689                         (((start - FUSE_SPARE_BIT_0_0) >> 2) - i), reg1);
690                 reg2 = readl(IO_ADDRESS((unsigned int)TEGRA_FUSE_BASE +
691                         start + offset1 - (i << 2)));
692                 dev_vdbg(data->hwmon_dev, "\n FUSE_SPARE_BIT_%d_0: 0x%x ",
693                         ((((start + offset1) - FUSE_SPARE_BIT_0_0) >> 2)
694                         - i), reg2);
695                 T1 = (T1 << 1) + ((reg1 | reg2) & 0x1);
696         }
697
698         /*
699          * High temp is:
700          * FUSE_TJ_ADJ = bits [6:0] or’ed with bits [13:7]
701          */
702         dev_vdbg(data->hwmon_dev, "\n Tsensor low temp (T2) fuse : ");
703         start = FUSE_SPARE_BIT_6_0;
704         T2 = 0;
705         for (i = 0; i < NUM_FUSE_REGS; i++) {
706                 reg1 = readl(IO_ADDRESS(TEGRA_FUSE_BASE + start -
707                         (i << 2)));
708                 dev_vdbg(data->hwmon_dev, "\n FUSE_SPARE_BIT_%d_0: 0x%x ",
709                         (((start - FUSE_SPARE_BIT_0_0) >> 2) - i), reg1);
710                 reg2 = readl(IO_ADDRESS(TEGRA_FUSE_BASE + start + offset1
711                         - (i << 2)));
712                 dev_vdbg(data->hwmon_dev, "\n FUSE_SPARE_BIT_%d_0: 0x%x ",
713                         ((((start + offset1) - FUSE_SPARE_BIT_0_0) >> 2)
714                         - i), reg2);
715                 T2 = (T2 << 1) + ((reg1 | reg2) & 0x1);
716         }
717         pr_info("\n Tsensor fuse calibration F1=%d, F2=%d, T1=%d, T2=%d "
718                 , fuse_F1, fuse_F2, T1, T2);
719         fuse_T1 = T1;
720         fuse_T2 = T2;
721         return 0;
722 }
723
724 /* function to calculate interim temperature */
725 static int calc_interim_temp(struct tegra_tsensor_data *data,
726         unsigned int counter, int *p_interim_temp)
727 {
728         int val1;
729         /*
730          * T-int = A * Counter + B
731          * (Counter is the sensor frequency output)
732          */
733         if ((fuse_F2 - fuse_F1) <= (fuse_T2 - fuse_T1)) {
734                 dev_err(data->hwmon_dev, "\n Error: F2=%d, F1=%d "
735                         "difference unexpectedly low. "
736                         "Aborting temperature processing ", fuse_F2, fuse_F1);
737                 return -EINVAL;
738         } else {
739                 /* expression modified after assuming s_A is 10^6 times,
740                  * s_B is 10^2 times and want end result to be 10^2 times
741                  * actual value
742                  */
743                 val1 = DIV_ROUND_CLOSEST((A_e_minus6 * counter) , 10000);
744                 dev_vdbg(data->hwmon_dev, "\n A*counter / 100 = %d ",
745                         val1);
746                 *p_interim_temp = (val1 + B_e_minus2);
747         }
748         dev_dbg(data->hwmon_dev, "\n tsensor: counter=0x%x, interim "
749                 "temp*100=%d ",
750                 counter, *p_interim_temp);
751         return 0;
752 }
753
754 /*
755  * function to calculate final temperature, given
756  * interim temperature
757  */
758 static void calc_final_temp(struct tegra_tsensor_data *data,
759         int interim_temp, int *p_final_temp)
760 {
761         int temp1, temp2, temp;
762         /*
763          * T-final = m * T-int ^2 + n * T-int + p
764          * m = -0.002775
765          * n = 1.338811
766          * p = -7.3
767          */
768
769         dev_vdbg(data->hwmon_dev, "\n interim_temp=%d ", interim_temp);
770         temp1 = (DIV_ROUND_CLOSEST((interim_temp * interim_temp) , 100));
771         dev_vdbg(data->hwmon_dev, "\n temp1=%d ", temp1);
772         temp1 *= (DIV_ROUND_CLOSEST(m_e_minus6 , 10));
773         dev_vdbg(data->hwmon_dev, "\n m*T-int^2=%d ", temp1);
774         temp1 = (DIV_ROUND_CLOSEST(temp1, 10000));
775         /* we want to keep 3 decimal point digits */
776         dev_vdbg(data->hwmon_dev, "\n m*T-int^2 / 10000=%d ", temp1);
777         dev_dbg(data->hwmon_dev, "\n temp1*100=%d ", temp1);
778
779         temp2 = (DIV_ROUND_CLOSEST(interim_temp * (
780                 DIV_ROUND_CLOSEST(n_e_minus6, 100)
781                 ), 1000)); /* 1000 times actual */
782         dev_vdbg(data->hwmon_dev, "\n n*T-int =%d ", temp2);
783
784         temp = temp1 + temp2;
785         dev_vdbg(data->hwmon_dev, "\n m*T-int^2 + n*T-int =%d ", temp);
786         temp += (p_e_minus2 * 10);
787         temp = DIV_ROUND_CLOSEST(temp, 10);
788         /* final temperature(temp) is 100 times actual value
789          * to preserve 2 decimal digits and enable fixed point
790          * computation
791          */
792         dev_vdbg(data->hwmon_dev, "\n m*T-int^2 + n*T-int + p =%d ",
793                 temp);
794         dev_dbg(data->hwmon_dev, "\n Final temp=%d.%d ",
795                 get_temperature_int(temp), get_temperature_fraction(temp));
796         *p_final_temp = (int)(temp);
797 }
798
799 /*
800  * Function to compute constants A and B needed for temperature
801  * calculation
802  * A = (T2-T1) / (F2-F1)
803  * B = T1 – A * F1
804  */
805 static int tsensor_get_const_AB(struct tegra_tsensor_data *data)
806 {
807         int err;
808
809         /*
810          *   1. Find fusing registers for 25C (T1, F1) and 90C (T2, F2);
811          */
812         err = read_tsensor_fuse_regs(data);
813         if (err) {
814                 dev_err(data->hwmon_dev, "\n Fuse register read required "
815                         "for internal tsensor returns err=%d ", err);
816                 return err;
817         }
818
819         if (fuse_F2 != fuse_F1) {
820                 if ((fuse_F2 - fuse_F1) <= (fuse_T2 - fuse_T1)) {
821                         dev_err(data->hwmon_dev, "\n Error: F2=%d, "
822                                 "F1=%d, difference"
823                                 " unexpectedly low. Aborting temperature"
824                                 "computation ", fuse_F2, fuse_F1);
825                         return -EINVAL;
826                 } else {
827                         A_e_minus6 = ((fuse_T2 - fuse_T1) * 1000000);
828                         A_e_minus6 /= (fuse_F2 - fuse_F1);
829                         B_e_minus2 = (fuse_T1 * 100) - (
830                                 DIV_ROUND_CLOSEST((A_e_minus6 *
831                                 fuse_F1), 10000));
832                         /* B is 100 times now */
833                 }
834         }
835         dev_dbg(data->hwmon_dev, "\n A_e_minus6 = %d ", A_e_minus6);
836         dev_dbg(data->hwmon_dev, "\n B_e_minus2 = %d ", B_e_minus2);
837         return 0;
838 }
839
840 /*
841  * function calculates expected temperature corresponding to
842  * given tsensor counter value
843  * Value returned is 100 times calculated temperature since the
844  * calculations are using fixed point arithmetic instead of floating point
845  */
846 static int tsensor_count_2_temp(struct tegra_tsensor_data *data,
847         unsigned int count, int *p_temperature)
848 {
849         int interim_temp;
850         int err;
851
852         /*
853          *
854          * 2. Calculate interim temperature:
855          */
856         err = calc_interim_temp(data, count, &interim_temp);
857         if (err < 0) {
858                 dev_err(data->hwmon_dev, "\n cannot read temperature\n");
859                 *p_temperature = -1;
860                 return err;
861         }
862
863         /*
864          *
865          * 3. Calculate final temperature:
866          */
867         calc_final_temp(data, interim_temp, p_temperature);
868         return 0;
869 }
870
871 /*
872  * utility function implements ceil to power of 10 -
873  * e.g. given 987 it returns 1000
874  */
875 static int my_ceil_pow10(int num)
876 {
877         int tmp;
878         int val = 1;
879         tmp = (num < 0) ? -num : num;
880         if (tmp == 0)
881                 return 0;
882         while (tmp > 1) {
883                 val *= 10;
884                 tmp /= 10;
885         }
886         return val;
887 }
888
889 /*
890  * function to solve quadratic roots of equation
891  * used to get counter corresponding to given temperature
892  */
893 static void get_quadratic_roots(struct tegra_tsensor_data *data,
894                 unsigned int temp, unsigned int *p_counter1,
895                 unsigned int *p_counter2)
896 {
897         /* expr1 = 2 * m * B + n */
898         int expr1_e_minus6;
899         /* expr2 = expr1^2 */
900         int expr2_e_minus6;
901         /* expr3 = m * B^2 + n * B + p */
902         int expr3_e_minus4_1;
903         int expr3_e_minus4_2;
904         int expr3_e_minus4;
905         int expr4_e_minus6;
906         int expr4_e_minus2_1;
907         int expr4_e_minus6_2;
908         int expr4_e_minus6_3;
909         int expr5_e_minus6, expr5_e_minus6_1, expr6, expr7;
910         int expr8_e_minus6, expr9_e_minus6;
911         int multiplier;
912         const int multiplier2 = 1000000;
913         int expr10_e_minus6, expr11_e_minus6;
914         int expr12, expr13;
915
916         dev_vdbg(data->hwmon_dev, "\n A_e_minus6=%d, B_e_minus2=%d, "
917                 "m_e_minus6=%d, n_e_minus6=%d, p_e_minus2=%d, "
918                 "temp=%d ", A_e_minus6, B_e_minus2, m_e_minus6,
919                 n_e_minus6, p_e_minus2, (int)temp);
920         expr1_e_minus6 = (DIV_ROUND_CLOSEST((2 * m_e_minus6 * B_e_minus2),
921                 100) + n_e_minus6);
922         dev_vdbg(data->hwmon_dev, "\n 2_m_B_plun_e_minus6=%d ",
923                 expr1_e_minus6);
924         expr2_e_minus6 = (DIV_ROUND_CLOSEST(expr1_e_minus6, 1000)) *
925                 (DIV_ROUND_CLOSEST(expr1_e_minus6, 1000));
926         dev_vdbg(data->hwmon_dev, "\n expr1^2=%d ", expr2_e_minus6);
927         expr3_e_minus4_1 = (DIV_ROUND_CLOSEST((
928                 (DIV_ROUND_CLOSEST((m_e_minus6 * B_e_minus2), 1000)) *
929                 (DIV_ROUND_CLOSEST(B_e_minus2, 10))
930                 ), 100));
931         dev_vdbg(data->hwmon_dev, "\n expr3_e_minus4_1=%d ",
932                 expr3_e_minus4_1);
933         expr3_e_minus4_2 = DIV_ROUND_CLOSEST(
934                 (DIV_ROUND_CLOSEST(n_e_minus6, 100) * B_e_minus2),
935                 100);
936         dev_vdbg(data->hwmon_dev, "\n expr3_e_minus4_2=%d ",
937                 expr3_e_minus4_2);
938         expr3_e_minus4 = expr3_e_minus4_1 + expr3_e_minus4_2;
939         dev_vdbg(data->hwmon_dev, "\n expr3=%d ", expr3_e_minus4);
940         expr4_e_minus2_1 = DIV_ROUND_CLOSEST((expr3_e_minus4 +
941                 (p_e_minus2 * 1000)), 100);
942         dev_vdbg(data->hwmon_dev, "\n expr4_e_minus2_1=%d ",
943                 expr4_e_minus2_1);
944         expr4_e_minus6_2 = (4 * m_e_minus6);
945         dev_vdbg(data->hwmon_dev, "\n expr4_e_minus6_2=%d ",
946                 expr4_e_minus6_2);
947         expr4_e_minus6 = DIV_ROUND_CLOSEST((expr4_e_minus2_1 *
948                 expr4_e_minus6_2), 100);
949         dev_vdbg(data->hwmon_dev, "\n expr4_minus6=%d ", expr4_e_minus6);
950         expr5_e_minus6_1 = expr2_e_minus6 - expr4_e_minus6;
951         dev_vdbg(data->hwmon_dev, "\n expr5_e_minus6_1=%d ",
952                 expr5_e_minus6_1);
953         expr4_e_minus6_3 = (expr4_e_minus6_2 * temp);
954         dev_vdbg(data->hwmon_dev, "\n expr4_e_minus6_3=%d ",
955                 expr4_e_minus6_3);
956         expr5_e_minus6 = (expr5_e_minus6_1 + expr4_e_minus6_3);
957         dev_vdbg(data->hwmon_dev, "\n expr5_e_minus6=%d ",
958                 expr5_e_minus6);
959         multiplier = my_ceil_pow10(expr5_e_minus6);
960         dev_vdbg(data->hwmon_dev, "\n multiplier=%d ", multiplier);
961         expr6 = int_sqrt(expr5_e_minus6);
962         dev_vdbg(data->hwmon_dev, "\n sqrt top=%d ", expr6);
963         expr7 = int_sqrt(multiplier);
964         dev_vdbg(data->hwmon_dev, "\n sqrt bot=%d ", expr7);
965         if (expr7 == 0) {
966                 pr_err("\n Error: %s line=%d, expr7=%d ",
967                         __func__, __LINE__, expr7);
968                 return;
969         } else {
970                 expr8_e_minus6 = (expr6 * multiplier2) / expr7;
971         }
972         dev_vdbg(data->hwmon_dev, "\n sqrt final=%d ", expr8_e_minus6);
973         dev_vdbg(data->hwmon_dev, "\n 2_m_B_plus_n_e_minus6=%d ",
974                 expr1_e_minus6);
975         expr9_e_minus6 = DIV_ROUND_CLOSEST((2 * m_e_minus6 * A_e_minus6),
976                 1000000);
977         dev_vdbg(data->hwmon_dev, "\n denominator=%d ", expr9_e_minus6);
978         if (expr9_e_minus6 == 0) {
979                 pr_err("\n Error: %s line=%d, expr9_e_minus6=%d ",
980                         __func__, __LINE__, expr9_e_minus6);
981                 return;
982         }
983         expr10_e_minus6 = -expr1_e_minus6 - expr8_e_minus6;
984         dev_vdbg(data->hwmon_dev, "\n expr10_e_minus6=%d ",
985                 expr10_e_minus6);
986         expr11_e_minus6 = -expr1_e_minus6 + expr8_e_minus6;
987         dev_vdbg(data->hwmon_dev, "\n expr11_e_minus6=%d ",
988                 expr11_e_minus6);
989         expr12 = (expr10_e_minus6 / expr9_e_minus6);
990         dev_vdbg(data->hwmon_dev, "\ncounter1=%d ", expr12);
991         expr13 = (expr11_e_minus6 / expr9_e_minus6);
992         dev_vdbg(data->hwmon_dev, "\ncounter2=%d ", expr13);
993         *p_counter1 = expr12;
994         *p_counter2 = expr13;
995 }
996
997 /*
998  * function returns tsensor expected counter corresponding to input
999  * temperature in degree Celsius.
1000  * e.g. for temperature of 35C, temp=35
1001  */
1002 static void tsensor_temp_2_count(struct tegra_tsensor_data *data,
1003                                 int temp,
1004                                 unsigned int *p_counter1,
1005                                 unsigned int *p_counter2)
1006 {
1007         if (temp > 0) {
1008                 dev_dbg(data->hwmon_dev, "\n Trying to calculate counter"
1009                         " for requested temperature"
1010                         " threshold=%d ", temp);
1011                 /*
1012                  * calculate the constants needed to get roots of
1013                  * following quadratic eqn:
1014                  * m * A^2 * Counter^2 +
1015                  * A * (2 * m * B + n) * Counter +
1016                  * (m * B^2 + n * B + p - Temperature) = 0
1017                  */
1018                 get_quadratic_roots(data, temp, p_counter1, p_counter2);
1019                 /*
1020                  * checked at current temperature=35 the counter=11418
1021                  * for 50 deg temperature: counter1=22731, counter2=11817
1022                  * at 35 deg temperature: counter1=23137, counter2=11411
1023                  * hence, for above values we are assuming counter2 has
1024                  * the correct value
1025                  */
1026         } else {
1027                 if (temp == data->div2_temp) {
1028                         *p_counter1 = DEFAULT_THRESHOLD_TH2;
1029                         *p_counter2 = DEFAULT_THRESHOLD_TH2;
1030                 } else {
1031                         *p_counter1 = DEFAULT_THRESHOLD_TH3;
1032                         *p_counter2 = DEFAULT_THRESHOLD_TH3;
1033                 }
1034         }
1035 }
1036
1037 /*
1038  * function to compare computed and expected values with
1039  * certain tolerance setting hard coded here
1040  */
1041 static bool cmp_counter(unsigned int actual, unsigned int exp)
1042 {
1043         unsigned int smaller;
1044         unsigned int larger;
1045         smaller = (actual > exp) ? exp : actual;
1046         larger = (smaller == actual) ? exp : actual;
1047         if ((larger - smaller) > TSENSOR_COUNTER_TOLERANCE)
1048                 return false;
1049         return true;
1050 }
1051
1052 /* function to print chart of temperature to counter values */
1053 static void print_temperature_2_counter_table(
1054         struct tegra_tsensor_data *data)
1055 {
1056         int i;
1057         /* static list of temperature tested */
1058         unsigned int temp_list[] = {
1059                 30,
1060                 35,
1061                 40,
1062                 45,
1063                 50,
1064                 55,
1065                 60,
1066                 61,
1067                 62,
1068                 63,
1069                 64,
1070                 65,
1071                 70,
1072                 75,
1073                 80,
1074                 85,
1075                 90,
1076                 95,
1077                 100,
1078                 105,
1079                 110,
1080                 115,
1081                 120
1082         };
1083         unsigned int counter1, counter2;
1084         dev_dbg(data->hwmon_dev, "\n Temperature and counter1 and "
1085                 "counter2 chart ********** ");
1086         for (i = 0; i < ARRAY_SIZE(temp_list); i++) {
1087                 tsensor_temp_2_count(data, temp_list[i],
1088                         &counter1, &counter2);
1089                 dev_dbg(data->hwmon_dev, "\n temperature[%d]=%d, "
1090                         "counter1=0x%x, counter2=0x%x ",
1091                         i, temp_list[i], counter1, counter2);
1092         }
1093         dev_dbg(data->hwmon_dev, "\n\n ");
1094 }
1095
1096 /*
1097  * function to test if conversion of counter to temperature
1098  * and vice-versa is working
1099  */
1100 static bool test_temperature_algo(struct tegra_tsensor_data *data)
1101 {
1102         unsigned int actual_counter;
1103         unsigned int curr_avg, min_max;
1104         unsigned int counter1, counter2;
1105         unsigned int T1;
1106         int err;
1107         bool result1, result2;
1108         bool result = false;
1109
1110         /* read actual counter */
1111         err = tsensor_read_counter(data, 0, &curr_avg, &min_max);
1112         if (err < 0) {
1113                 pr_err("\n Error: tsensor0 counter read, err=%d ", err);
1114                 goto endLabel;
1115         }
1116         actual_counter = ((curr_avg & 0xFFFF0000) >> 16);
1117         dev_dbg(data->hwmon_dev, "\n counter read=0x%x ", actual_counter);
1118
1119         /* calculate temperature */
1120         err = tsensor_count_2_temp(data, actual_counter, &T1);
1121         dev_dbg(data->hwmon_dev, "\n %s actual counter=0x%x, calculated "
1122                 "temperature=%d.%d ", __func__,
1123                 actual_counter, get_temperature_int(T1),
1124                 get_temperature_fraction(T1));
1125         if (err < 0) {
1126                 pr_err("\n Error: calculate temperature step ");
1127                 goto endLabel;
1128         }
1129
1130         /* calculate counter corresponding to read temperature */
1131         tsensor_temp_2_count(data, get_temperature_round(T1),
1132                 &counter1, &counter2);
1133         dev_dbg(data->hwmon_dev, "\n given temperature=%d, counter1=0x%x,"
1134                 " counter2=0x%x ",
1135                 get_temperature_round(T1), counter1, counter2);
1136
1137         /* compare counter calculated with actual original counter */
1138         result1 = cmp_counter(actual_counter, counter1);
1139         result2 = cmp_counter(actual_counter, counter2);
1140         if (result1) {
1141                 dev_dbg(data->hwmon_dev, "\n counter1 matches: actual=%d,"
1142                         " calc=%d ", actual_counter, counter1);
1143                 result = true;
1144         }
1145         if (result2) {
1146                 dev_dbg(data->hwmon_dev, "\n counter2 matches: actual=%d,"
1147                         " calc=%d ", actual_counter, counter2);
1148                 result = true;
1149         }
1150
1151 endLabel:
1152         return result;
1153 }
1154
1155 /* tsensor threshold temperature to threshold counter conversion function */
1156 static unsigned int tsensor_get_threshold_counter(
1157         struct tegra_tsensor_data *data,
1158         unsigned int temp_threshold)
1159 {
1160         unsigned int counter1, counter2;
1161         unsigned int curr_avg, min_max;
1162         unsigned int counter;
1163         int err;
1164
1165         tsensor_temp_2_count(data, temp_threshold, &counter1, &counter2);
1166         err = tsensor_read_counter(data, 0, &curr_avg, &min_max);
1167         if (err < 0) {
1168                 pr_err("\n Error: tsensor0 counter read, err=%d ", err);
1169                 return MAX_THRESHOLD;
1170         }
1171         if (counter2 > ((curr_avg & 0xFFFF0000) >> 16)) {
1172                 dev_dbg(data->hwmon_dev, "\n choosing counter2=0x%x as "
1173                         "root ", counter2);
1174                 counter = counter2;
1175         } else {
1176                 pr_err("\n Error: choosing counter1=0x%x as root, "
1177                         "counter=0x%x ", counter1,
1178                         ((curr_avg & 0xFFFF0000) >> 16));
1179                 counter = counter1;
1180         }
1181         return counter;
1182 }
1183
1184 /* tsensor temperature threshold setup function */
1185 static void tsensor_threshold_setup(
1186                 struct tegra_tsensor_data *data,
1187                 unsigned char index, bool is_default_threshold)
1188 {
1189         unsigned long config0;
1190         unsigned char i = index;
1191         unsigned int th2_count = DEFAULT_THRESHOLD_TH2;
1192         unsigned int th3_count = DEFAULT_THRESHOLD_TH3;
1193         unsigned int th1_count = DEFAULT_THRESHOLD_TH1;
1194         unsigned int hysteresis_count;
1195         int th0_diff = (DEFAULT_THRESHOLD_TH1 - MIN_THRESHOLD);
1196
1197         dev_dbg(data->hwmon_dev, "\n started tsensor_threshold_setup %d ",
1198                 index);
1199         config0 = tsensor_readl(data, ((i << 16) | SENSOR_CFG0));
1200
1201         /* Choose thresholds for sensor0 and sensor1 */
1202         /* set to very high values initially - DEFAULT_THRESHOLD */
1203         if ((!is_default_threshold) && (i == 0)) {
1204                 dev_dbg(data->hwmon_dev, "\n before div2 temp_2_count ");
1205                 th2_count = tsensor_get_threshold_counter(data,
1206                         data->div2_temp);
1207                 dev_dbg(data->hwmon_dev, "\n div2_temp=%d, count=%d ",
1208                         data->div2_temp, th2_count);
1209                 dev_dbg(data->hwmon_dev, "\n before reset temp_2_count ");
1210                 th3_count = tsensor_get_threshold_counter(data,
1211                         data->reset_temp);
1212                 dev_dbg(data->hwmon_dev, "\n reset_temp=%d, count=%d ",
1213                         (unsigned int)data->reset_temp, th3_count);
1214                 dev_dbg(data->hwmon_dev, "\n before sw_intr temp_2_count ");
1215                 th1_count = tsensor_get_threshold_counter(data,
1216                         data->sw_intr_temp);
1217                 dev_dbg(data->hwmon_dev, "\n sw_intr_temp=%d, count=%d ",
1218                         (unsigned int)data->sw_intr_temp, th1_count);
1219                 dev_dbg(data->hwmon_dev, "\n before hysteresis temp_2_count ");
1220                 hysteresis_count = tsensor_get_threshold_counter(data,
1221                         (data->sw_intr_temp - data->hysteresis));
1222                 dev_dbg(data->hwmon_dev, "\n hysteresis_temp=%d, count=%d ",
1223                         (unsigned int)(data->sw_intr_temp - data->hysteresis),
1224                         hysteresis_count);
1225                 th0_diff = th1_count - hysteresis_count;
1226                 dev_dbg(data->hwmon_dev, "\n th0_diff=%d ", th0_diff);
1227         }
1228         dev_dbg(data->hwmon_dev, "\n before threshold program TH dump: ");
1229         dump_threshold(data);
1230         dev_dbg(data->hwmon_dev, "\n th3=0x%x, th2=0x%x, th1=0x%x, th0=0x%x ",
1231                 th3_count, th2_count, th1_count, th0_diff);
1232         config0 = (((th2_count & SENSOR_CFG_X_TH_X_MASK)
1233                 << SENSOR_CFG1_TH2_SHIFT) |
1234                 ((th1_count & SENSOR_CFG_X_TH_X_MASK) <<
1235                 SENSOR_CFG1_TH1_SHIFT));
1236         tsensor_writel(data, config0, ((i << 16) | SENSOR_CFG1));
1237         config0 = (((th0_diff & SENSOR_CFG_X_TH_X_MASK)
1238                 << SENSOR_CFG2_TH0_SHIFT) |
1239                 ((th3_count & SENSOR_CFG_X_TH_X_MASK) <<
1240                 SENSOR_CFG2_TH3_SHIFT));
1241         tsensor_writel(data, config0, ((i << 16) | SENSOR_CFG2));
1242         dev_dbg(data->hwmon_dev, "\n after threshold program TH dump: ");
1243         dump_threshold(data);
1244 }
1245
1246 /* tsensor config programming function */
1247 static int tsensor_config_setup(struct tegra_tsensor_data *data)
1248 {
1249         unsigned int config0;
1250         unsigned int i;
1251         unsigned int status_reg;
1252         unsigned int no_resp_count;
1253         int err;
1254         struct tsensor_state curr_state;
1255
1256         for (i = 0; i < TSENSOR_COUNT; i++) {
1257                 /*
1258                  * Pre-read setup:
1259                  * Set M and N values
1260                  * Enable HW features HW_FREQ_DIV_EN, THERMAL_RST_EN
1261                  */
1262                 config0 = tsensor_readl(data, ((i << 16) | SENSOR_CFG0));
1263                 config0 &= ~((SENSOR_CFG0_M_MASK << SENSOR_CFG0_M_SHIFT) |
1264                         (SENSOR_CFG0_N_MASK << SENSOR_CFG0_N_SHIFT) |
1265                         (1 << SENSOR_CFG0_OVERFLOW_INTR) |
1266                         (1 << SENSOR_CFG0_RST_INTR_SHIFT) |
1267                         (1 << SENSOR_CFG0_HW_DIV2_INTR_SHIFT) |
1268                         (1 << SENSOR_CFG0_RST_ENABLE_SHIFT) |
1269                         (1 << SENSOR_CFG0_HW_DIV2_ENABLE_SHIFT)
1270                         );
1271                 /* Set STOP bit */
1272                 /* Set M and N values */
1273                 /* Enable HW features HW_FREQ_DIV_EN, THERMAL_RST_EN */
1274                 config0 |= (((DEFAULT_TSENSOR_M & SENSOR_CFG0_M_MASK) <<
1275                         SENSOR_CFG0_M_SHIFT) |
1276                         ((DEFAULT_TSENSOR_N & SENSOR_CFG0_N_MASK) <<
1277                         SENSOR_CFG0_N_SHIFT) |
1278                         (1 << SENSOR_CFG0_OVERFLOW_INTR) |
1279                         /*(1 << SENSOR_CFG0_RST_INTR_SHIFT) |
1280                         (1 << SENSOR_CFG0_HW_DIV2_INTR_SHIFT) |*/
1281                         (1 << SENSOR_CFG0_STOP_SHIFT) |
1282                         (1 << SENSOR_CFG0_RST_ENABLE_SHIFT) |
1283                         (1 << SENSOR_CFG0_HW_DIV2_ENABLE_SHIFT));
1284
1285                 tsensor_writel(data, config0, ((i << 16) | SENSOR_CFG0));
1286                 tsensor_threshold_setup(data, i, true);
1287         }
1288
1289         for (i = 0; i < TSENSOR_COUNT; i++) {
1290                 config0 = tsensor_readl(data, ((i << 16) | SENSOR_CFG0));
1291                 /* Enables interrupts and clears sensor stop */
1292                 /*
1293                  * Interrupts not enabled as software handling is not
1294                  * needed in rev1 driver
1295                  */
1296                 /* Disable sensor stop bit */
1297                 config0 &= ~(1 << SENSOR_CFG0_STOP_SHIFT);
1298                 tsensor_writel(data, config0, ((i << 16) | SENSOR_CFG0));
1299         }
1300
1301         /* Check if counters are getting updated */
1302         no_resp_count = 0;
1303
1304         for (i = 0; i < TSENSOR_COUNT; i++) {
1305                 /* if STOP bit is set skip this check */
1306                 config0 = tsensor_readl(data, ((i << 16) | SENSOR_CFG0));
1307                 if (!(config0 & (1 << SENSOR_CFG0_STOP_SHIFT))) {
1308                         unsigned int loop_count = 0;
1309                         do {
1310                                 status_reg = tsensor_readl(data,
1311                                         (i << 16) | SENSOR_STATUS0);
1312                                 if ((status_reg & (1 <<
1313                                         SENSOR_STATUS_AVG_VALID_SHIFT)) &&
1314                                         (status_reg & (1 <<
1315                                         SENSOR_STATUS_CURR_VALID_SHIFT))) {
1316                                         msleep(1);
1317                                         loop_count++;
1318                                         if (!(loop_count % 200))
1319                                                 dev_err(data->hwmon_dev,
1320                                                 "\n Warning: Tsensor Counter "
1321                                                 "sensor%d not Valid yet. ", i);
1322                                         if (loop_count > MAX_TSENSOR_LOOP1) {
1323                                                 no_resp_count++;
1324                                                 break;
1325                                         }
1326                                 }
1327                         } while (!(status_reg &
1328                                 (1 << SENSOR_STATUS_AVG_VALID_SHIFT)) ||
1329                                 (!(status_reg &
1330                                 (1 << SENSOR_STATUS_CURR_VALID_SHIFT))));
1331                         if (no_resp_count == TSENSOR_COUNT)
1332                                 return -ENODEV;
1333                 }
1334                 /* check initial state */
1335                 get_ts_state(data, (unsigned char)i, &curr_state);
1336                 data->ts_state_saved[i] = curr_state.state;
1337         }
1338         /* initialize tsensor chip coefficients */
1339         err = get_chip_tsensor_coeff();
1340         return err;
1341 }
1342
1343 /* function to enable tsensor clock */
1344 static int tsensor_clk_enable(
1345         struct tegra_tsensor_data *data,
1346         bool enable)
1347 {
1348         int err = 0;
1349         unsigned long rate;
1350         struct clk *clk_m;
1351
1352         if (enable) {
1353                 clk_enable(data->dev_clk);
1354                 rate = clk_get_rate(data->dev_clk);
1355                 clk_m = clk_get_sys(NULL, "clk_m");
1356                 if (clk_get_parent(data->dev_clk) != clk_m) {
1357                         err = clk_set_parent(data->dev_clk, clk_m);
1358                         if (err < 0)
1359                                 goto fail;
1360                 }
1361                 rate = DEFAULT_TSENSOR_CLK_HZ;
1362                 if (rate != clk_get_rate(clk_m)) {
1363                         err = clk_set_rate(data->dev_clk, rate);
1364                         if (err < 0)
1365                                 goto fail;
1366                 }
1367         } else {
1368                 clk_disable(data->dev_clk);
1369                 clk_put(data->dev_clk);
1370         }
1371 fail:
1372         return err;
1373 }
1374
1375 /*
1376  * This function enables the tsensor using default configuration
1377  * 1. We would need some configuration APIs to calibrate
1378  *    the tsensor counters to right temperature
1379  * 2. hardware triggered divide cpu clock by 2 as well pmu reset is enabled
1380  *    implementation. No software actions are enabled at this point
1381  */
1382 static int tegra_tsensor_setup(struct platform_device *pdev)
1383 {
1384         struct tegra_tsensor_data *data = platform_get_drvdata(pdev);
1385         struct resource *r;
1386         int err;
1387         struct tegra_tsensor_platform_data *tsensor_data;
1388
1389         data->dev_clk = clk_get(&pdev->dev, NULL);
1390         if ((!data->dev_clk) || ((int)data->dev_clk == -(ENOENT))) {
1391                 dev_err(&pdev->dev, "Couldn't get the clock\n");
1392                 err = PTR_ERR(data->dev_clk);
1393                 goto fail;
1394         }
1395
1396         /* Enable tsensor clock */
1397         err = tsensor_clk_enable(data, true);
1398         if (err < 0)
1399                 goto err_irq;
1400
1401         /* Reset tsensor */
1402         dev_dbg(&pdev->dev, "\n before tsensor reset %s ", __func__);
1403         tegra_periph_reset_assert(data->dev_clk);
1404         msleep(1);
1405         tegra_periph_reset_deassert(data->dev_clk);
1406         msleep(1);
1407
1408         dev_dbg(&pdev->dev, "\n before tsensor chk pmc reset %s ",
1409                 __func__);
1410         /* Check for previous resets in pmc */
1411         if (pmc_check_rst_sensor(data)) {
1412                 dev_err(data->hwmon_dev, "\n Warning: ***** Last PMC "
1413                         "Reset source: tsensor detected ");
1414         }
1415
1416         dev_dbg(&pdev->dev, "\n before tsensor pmc reset enable %s ",
1417                 __func__);
1418         /* Enable the sensor reset in PMC */
1419         pmc_rst_enable(data, true);
1420
1421         /* register interrupt */
1422         r = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
1423         if (!r) {
1424                 dev_err(&pdev->dev, "Failed to get IRQ\n");
1425                 err = -ENXIO;
1426                 goto err_irq;
1427         }
1428         data->irq = r->start;
1429         err = request_irq(data->irq, tegra_tsensor_isr,
1430                         IRQF_DISABLED, pdev->name, data);
1431         if (err < 0) {
1432                 dev_err(&pdev->dev, "Failed to register IRQ\n");
1433                 goto err_irq;
1434         }
1435
1436         /* tsensor thresholds are read from board/platform specific files */
1437         dev_dbg(&pdev->dev, "\n before tsensor get platform data %s ",
1438                 __func__);
1439         tsensor_data = pdev->dev.platform_data;
1440         dev_dbg(&pdev->dev, "\n tsensor platform_data=0x%x ",
1441                 (unsigned int)pdev->dev.platform_data);
1442         dev_dbg(&pdev->dev, "\n clk_div temperature=%d ",
1443                 tsensor_data->hw_clk_div_temperature);
1444         data->div2_temp = tsensor_data->hw_clk_div_temperature;
1445         dev_dbg(&pdev->dev, "\n reset temperature=%d ",
1446                 tsensor_data->hw_reset_temperature);
1447         data->reset_temp = tsensor_data->hw_reset_temperature;
1448         dev_dbg(&pdev->dev, "\n sw_intr temperature=%d ",
1449                 tsensor_data->sw_intr_temperature);
1450         data->sw_intr_temp = tsensor_data->sw_intr_temperature;
1451         dev_dbg(&pdev->dev, "\n hysteresis temperature=%d ",
1452                 tsensor_data->hysteresis);
1453         data->hysteresis = tsensor_data->hysteresis;
1454
1455         dev_dbg(&pdev->dev, "\n before tsensor_config_setup ");
1456         if (tsensor_config_setup(data)) {
1457                 dev_err(&pdev->dev, " [%s,line=%d]: tsensor counters dead! ",
1458                         __func__, __LINE__);
1459                 goto err_setup;
1460         }
1461         dev_dbg(&pdev->dev, "\n before tsensor_get_const_AB ");
1462         /* calculate constants needed for temperature conversion */
1463         err = tsensor_get_const_AB(data);
1464         if (err < 0) {
1465                 dev_err(&pdev->dev, " Failed to extract temperature "
1466                         "const\n");
1467                 goto err_setup;
1468         }
1469
1470         /* test if counter-to-temperature and temperature-to-counter
1471          * are matching */
1472         if (!test_temperature_algo(data)) {
1473                 dev_err(&pdev->dev, " Error: read temperature "
1474                         "algorithm broken ");
1475         }
1476
1477         print_temperature_2_counter_table(data);
1478
1479         dev_dbg(&pdev->dev, "\n before tsensor_threshold_setup ");
1480         /* change tsensor threshold for instance 0 */
1481         tsensor_threshold_setup(data, 0, false);
1482         dev_dbg(&pdev->dev, "\n end tsensor_threshold_setup ");
1483
1484         return 0;
1485 err_setup:
1486         free_irq(data->irq, data);
1487 err_irq:
1488         tsensor_clk_enable(data, false);
1489 fail:
1490         dev_err(&pdev->dev, "\n %s error=%d returned ", __func__, err);
1491         return err;
1492 }
1493
1494 static int __devinit tegra_tsensor_probe(struct platform_device *pdev)
1495 {
1496         struct tegra_tsensor_data *data;
1497         struct resource *r;
1498         int err;
1499
1500         data = kzalloc(sizeof(struct tegra_tsensor_data), GFP_KERNEL);
1501         if (!data) {
1502                 dev_err(&pdev->dev, " [%s,line=%d]: Failed to allocate "
1503                         "memory\n", __func__, __LINE__);
1504                 err = -ENOMEM;
1505                 goto exit;
1506         }
1507         platform_set_drvdata(pdev, data);
1508
1509         /* Register sysfs hooks */
1510         err = sysfs_create_group(&pdev->dev.kobj, &tsensor_attr_group);
1511         if (err < 0)
1512                 goto err0;
1513
1514         data->hwmon_dev = hwmon_device_register(&pdev->dev);
1515         if (IS_ERR(data->hwmon_dev)) {
1516                 err = PTR_ERR(data->hwmon_dev);
1517                 goto err0b;
1518         }
1519
1520         dev_set_drvdata(data->hwmon_dev, data);
1521
1522         spin_lock_init(&data->tsensor_lock);
1523
1524         /* map tsensor register space */
1525         r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1526         if (r == NULL) {
1527                 dev_err(&pdev->dev, " [%s,line=%d]: Failed to get io "
1528                         "resource\n", __func__, __LINE__);
1529                 err = -ENODEV;
1530                 goto err0b;
1531         }
1532
1533         if (!request_mem_region(r->start, (r->end - r->start) + 1,
1534                                 dev_name(&pdev->dev))) {
1535                 dev_err(&pdev->dev, " [%s,line=%d]: Error mem busy\n",
1536                         __func__, __LINE__);
1537                 err = -EBUSY;
1538                 goto err0b;
1539         }
1540
1541         data->phys = r->start;
1542         data->phys_end = r->end;
1543         data->base = ioremap(r->start, r->end - r->start + 1);
1544         if (!data->base) {
1545                 dev_err(&pdev->dev, " [%s, line=%d]: can't ioremap "
1546                         "tsensor iomem\n", __FILE__, __LINE__);
1547                 err = -ENOMEM;
1548                 goto err1;
1549         }
1550
1551         /* map pmc rst_status register  */
1552         r = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1553         if (r == NULL) {
1554                 dev_err(&pdev->dev, " [%s,line=%d]: Failed to get io "
1555                         "resource\n", __func__, __LINE__);
1556                 err = -ENODEV;
1557                 goto err2;
1558         }
1559
1560         if (!request_mem_region(r->start, (r->end - r->start) + 1,
1561                                 dev_name(&pdev->dev))) {
1562                 dev_err(&pdev->dev, " [%s, line=%d]: Error mem busy\n",
1563                         __func__, __LINE__);
1564                 err = -EBUSY;
1565                 goto err2;
1566         }
1567
1568         data->pmc_phys = r->start;
1569         data->pmc_phys_end = r->end;
1570         data->pmc_rst_base = ioremap(r->start, r->end - r->start + 1);
1571         if (!data->pmc_rst_base) {
1572                 dev_err(&pdev->dev, " [%s, line=%d]: can't ioremap "
1573                         "pmc iomem\n", __FILE__, __LINE__);
1574                 err = -ENOMEM;
1575                 goto err3;
1576         }
1577
1578         /* tegra tsensor - setup and init */
1579         if (tegra_tsensor_setup(pdev) != 0)
1580                 goto err4;
1581
1582         dev_dbg(&pdev->dev, "\n end tegra_tsensor_probe ");
1583         return 0;
1584 err4:
1585         iounmap(data->pmc_rst_base);
1586 err3:
1587         release_mem_region(data->pmc_phys, (data->pmc_phys_end -
1588                 data->pmc_phys) + 1);
1589 err2:
1590         iounmap(data->base);
1591 err1:
1592         release_mem_region(data->phys, (data->phys_end -
1593                 data->phys) + 1);
1594 err0b:
1595         sysfs_remove_group(&pdev->dev.kobj, &tsensor_attr_group);
1596         hwmon_device_unregister(data->hwmon_dev);
1597
1598 err0:
1599         kfree(data);
1600 exit:
1601         dev_err(&pdev->dev, "\n %s error=%d returned ", __func__, err);
1602         return err;
1603 }
1604
1605 static int __devexit tegra_tsensor_remove(struct platform_device *pdev)
1606 {
1607         struct tegra_tsensor_data *data = platform_get_drvdata(pdev);
1608
1609         hwmon_device_unregister(data->hwmon_dev);
1610
1611         free_irq(data->irq, data);
1612
1613         iounmap(data->pmc_rst_base);
1614         release_mem_region(data->pmc_phys, (data->pmc_phys_end -
1615                 data->pmc_phys) + 1);
1616         iounmap(data->base);
1617         release_mem_region(data->phys, (data->phys_end -
1618                 data->phys) + 1);
1619         sysfs_remove_group(&pdev->dev.kobj, &tsensor_attr_group);
1620         platform_set_drvdata(pdev, NULL);
1621         kfree(data);
1622
1623         return 0;
1624 }
1625
1626 #ifdef CONFIG_PM
1627 static int tsensor_suspend(struct platform_device *pdev,
1628         pm_message_t state)
1629 {
1630         struct tegra_tsensor_data *data = platform_get_drvdata(pdev);
1631         /* TBD: check anything else that could be needed for suspend */
1632         tsensor_clk_enable(data, false);
1633
1634         return 0;
1635 }
1636
1637 static int tsensor_resume(struct platform_device *pdev)
1638 {
1639         struct tegra_tsensor_data *data = platform_get_drvdata(pdev);
1640         /* TBD: check anything else that could be needed for resume */
1641         tsensor_clk_enable(data, true);
1642
1643         return 0;
1644 }
1645 #endif
1646
1647 static struct platform_driver tegra_tsensor_driver = {
1648         .driver = {
1649                 .owner  = THIS_MODULE,
1650                 .name   = "tegra-tsensor",
1651         },
1652         .probe          = tegra_tsensor_probe,
1653         .remove         = __devexit_p(tegra_tsensor_remove),
1654 #ifdef CONFIG_PM
1655         .suspend        = tsensor_suspend,
1656         .resume         = tsensor_resume,
1657 #endif
1658 };
1659
1660 static int __init tegra_tsensor_init(void)
1661 {
1662         init_flag = 0;
1663         if (platform_driver_register(&tegra_tsensor_driver))
1664                 goto exit;
1665         init_flag = 1;
1666         return 0;
1667
1668 exit:
1669         return -ENODEV;
1670 }
1671
1672 static void __exit tegra_tsensor_exit(void)
1673 {
1674         if (init_flag) {
1675                 platform_driver_unregister(&tegra_tsensor_driver);
1676                 init_flag = 0;
1677         }
1678 }
1679
1680 MODULE_AUTHOR("nvidia");
1681 MODULE_DESCRIPTION("Nvidia Tegra Temperature Sensor driver");
1682 MODULE_LICENSE("GPL");
1683
1684 module_init(tegra_tsensor_init);
1685 module_exit(tegra_tsensor_exit);
1686