ARM64: DTS: Add rk3399-firefly uart4 device, node as /dev/ttyS1
[firefly-linux-kernel-4.4.55.git] / drivers / thermal / rk3368_thermal.c
1 /*
2  * Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd
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
14 #include <linux/clk.h>
15 #include <linux/delay.h>
16 #include <linux/interrupt.h>
17 #include <linux/io.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/of_address.h>
21 #include <linux/of_irq.h>
22 #include <linux/platform_device.h>
23 #include <linux/reset.h>
24 #include <linux/thermal.h>
25 #include <linux/timer.h>
26 #include <linux/mfd/syscon.h>
27 #include <linux/regmap.h>
28 #include <linux/gpio.h>
29 #include <linux/of_gpio.h>
30 #include <linux/rockchip/common.h>
31 #include <linux/reboot.h>
32 #include <linux/regulator/consumer.h>
33 #include <linux/slab.h>
34 #include <linux/mutex.h>
35 #include <linux/nvmem-consumer.h>
36 #include <linux/pm_qos.h>
37 #include <soc/rockchip/scpi.h>
38
39 /**
40  * If the temperature over a period of time High,
41  * the resulting TSHUT gave CRU module,let it reset the entire chip,
42  * or via GPIO give PMIC.
43  */
44 enum tshut_mode {
45         TSHUT_MODE_CRU = 0,
46         TSHUT_MODE_GPIO,
47 };
48
49 enum tsadc_mode {
50         TSADC_AUTO_MODE = 0,
51         TSHUT_USER_MODE,
52 };
53
54 /**
55  * the system Temperature Sensors tshut(tshut) polarity
56  * the bit 8 is tshut polarity.
57  * 0: low active, 1: high active
58  */
59 enum tshut_polarity {
60         TSHUT_LOW_ACTIVE = 0,
61         TSHUT_HIGH_ACTIVE,
62 };
63
64 #define NUM_SENSORS     2
65
66 /* TSADC V2 Sensor info define: */
67 #define TSADCV2_USER_CON                        0x00
68 #define TSADCV2_AUTO_CON                        0x04
69 #define TSADCV2_INT_EN                          0x08
70 #define TSADCV2_INT_PD                          0x0c
71 #define TSADCV2_DATA(chn)                       (0x20 + (chn) * 0x04)
72
73 #define TSADC_CLK_CYCLE_TIME        32  /* usec */
74 #define TSADCV3_DATA_MASK                       0x3ff
75
76 /**
77  * The conversion table has the adc value and temperature.
78  * ADC_DECREMENT: the adc value is of diminishing.(e.g. rk3288_code_table)
79  * ADC_INCREMENT: the adc value is incremental.(e.g. rk3368_code_table)
80  */
81 enum adc_sort_mode {
82         ADC_DECREMENT = 0,
83         ADC_INCREMENT,
84 };
85
86 #define TIME_OUT_TOTAL 2000
87 #define INVALID_EFUSE_VALUE           0xff
88
89 enum {
90         ACCESS_FORBIDDEN = 0,
91 };
92
93 #define MIN_TEMP (-40000)
94 #define MAX_TEMP (125000)
95
96 #define BASE (1024)
97 #define BASE_SHIFT (10)
98 #define START_BOUNDING_COUNT (100)
99 #define HIGHER_BOUNDING_TEMP (30)
100 #define LOWER_BOUNDING_TEMP (15)
101
102 /**
103  * struct tsadc_table - hold information about code and temp mapping
104  * @code: raw code from tsadc ip
105  * @temp: the mapping temperature
106  */
107
108 struct tsadc_table {
109         unsigned long code;
110         int temp;
111 };
112
113 /**
114  * struct chip_tsadc_table - hold information about chip-specific differences
115  * @id: conversion table
116  * @length: size of conversion table
117  * @data_mask: mask to apply on data inputs
118  * @mode: sort mode of this adc variant (incrementing or decrementing)
119  */
120 struct chip_tsadc_table {
121         const struct tsadc_table *id;
122         unsigned int length;
123         u32 data_mask;
124         enum adc_sort_mode mode;
125 };
126
127 /**
128  * struct rk3368_tsadc_chip - hold the private data of tsadc chip
129  * @chn_id[SOC_MAX_SENSORS]: the sensor id of chip correspond to the channel
130  * @chn_num: the channel number of tsadc chip
131  * @tshut_temp: the hardware-controlled shutdown temperature value
132  * @tshut_mode: the hardware-controlled shutdown mode (0:CRU 1:GPIO)
133  * @tshut_polarity: the hardware-controlled active polarity (0:LOW 1:HIGH)
134  * @chip_tsadc_table: the chip-specific conversion table
135  * @get_temp: get the temperature
136  * @set_alarm_temp: set the high temperature interrupt
137  * @set_tshut_temp: set the hardware-controlled shutdown temperature
138  * @set_tshut_mode: set the hardware-controlled shutdown mode
139  */
140 struct rk3368_tsadc_chip {
141         int chn_id[NUM_SENSORS];
142         int chn_num;
143         long hw_shut_temp;
144         enum tshut_mode tshut_mode;
145         enum tsadc_mode mode;
146         enum tshut_polarity tshut_polarity;
147         int latency_bound;
148
149         const struct chip_tsadc_table *temp_table;
150
151         /* Per-sensor methods */
152         int (*get_temp)(const struct chip_tsadc_table *table,
153                         int chn, void __iomem *reg, int *temp);
154         void (*set_alarm_temp)(const struct chip_tsadc_table *table,
155                                int chn, void __iomem *reg, int temp);
156         void (*set_tshut_temp)(const struct chip_tsadc_table *table,
157                                int chn, void __iomem *reg, int temp);
158         void (*set_tshut_mode)(int chn, void __iomem *reg, enum tshut_mode m);
159 };
160
161 /**
162  * struct rk3368_thermal_sensor - hold the information of thermal sensor
163  * @ctx:  pointer to the platform/configuration data
164  * @tzd: pointer to a thermal zone
165  * @id: identifier of the thermal sensor
166  */
167 struct rk3368_thermal_sensor {
168         struct rk3368_thermal_data *ctx;
169         struct thermal_zone_device *tzd;
170         int id;
171 };
172
173 /**
174  * struct rk3368_thermal_data - hold the private data of thermal driver
175  * @chip: pointer to the platform/configuration data
176  * @pdev: platform device of thermal
177  * @reset: the reset controller of tsadc
178  * @sensors[SOC_MAX_SENSORS]: the thermal sensor
179  * @clk: the controller clock is divided by the external 24MHz
180  * @pclk: the advanced peripherals bus clock
181  * @regs: the base address of tsadc controller
182  * @tshut_temp: the hardware-controlled shutdown temperature value
183  * @tshut_mode: the hardware-controlled shutdown mode (0:CRU 1:GPIO)
184  * @tshut_polarity: the hardware-controlled active polarity (0:LOW 1:HIGH)
185  * @cpu_temp_adjust: efuse value used to ajust the temperature
186  * @gpu_temp_adjust: efuse value used to ajust the temperature
187  * @cpu_temp: the current cpu's temperature
188  * @logout: switch to control log output or not
189  * @rk3368_thermal_kobj: node in sys fs
190  */
191 struct rk3368_thermal_data {
192         const struct rk3368_tsadc_chip *chip;
193         struct platform_device *pdev;
194         struct reset_control *reset;
195
196         struct rk3368_thermal_sensor sensors[NUM_SENSORS];
197
198         struct clk *clk;
199         struct clk *pclk;
200         void __iomem *regs;
201
202         long hw_shut_temp;
203         enum tshut_mode tshut_mode;
204         enum tshut_polarity tshut_polarity;
205
206         int cpu_temp_adjust;
207         int gpu_temp_adjust;
208         int cpu_temp;
209         bool logout;
210         struct kobject *rk3368_thermal_kobj;
211         struct regulator *ref_regulator;
212         int regulator_uv;
213         int latency_req;
214         int latency_bound;
215         struct notifier_block tsadc_nb;
216 };
217
218 static struct rk3368_thermal_data *thermal_ctx;
219
220 static DEFINE_MUTEX(thermal_reg_mutex);
221
222 static DEFINE_MUTEX(thermal_lat_mutex);
223
224 static const struct tsadc_table code_table_3368[] = {
225         {0, MIN_TEMP},
226         {106, MIN_TEMP},
227         {108, -35000},
228         {110, -30000},
229         {112, -25000},
230         {114, -20000},
231         {116, -15000},
232         {118, -10000},
233         {120, -5000},
234         {122, 0},
235         {124, 5000},
236         {126, 10000},
237         {128, 15000},
238         {130, 20000},
239         {132, 25000},
240         {134, 30000},
241         {136, 35000},
242         {138, 40000},
243         {140, 45000},
244         {142, 50000},
245         {144, 55000},
246         {146, 60000},
247         {148, 65000},
248         {150, 70000},
249         {152, 75000},
250         {154, 80000},
251         {156, 85000},
252         {158, 90000},
253         {160, 95000},
254         {162, 100000},
255         {163, 105000},
256         {165, 110000},
257         {167, 115000},
258         {169, 120000},
259         {171, MAX_TEMP},
260         {TSADCV3_DATA_MASK, MAX_TEMP},
261 };
262
263 static const struct chip_tsadc_table tsadc_table_3368 = {
264         .id = code_table_3368,
265         .length = ARRAY_SIZE(code_table_3368),
266         .data_mask = TSADCV3_DATA_MASK,
267         .mode = ADC_INCREMENT,
268 };
269
270 static int rk3368_get_ajust_code(struct device_node *np, int *ajust_code)
271 {
272         struct nvmem_cell *cell;
273         unsigned char *buf;
274         size_t len;
275
276         cell = of_nvmem_cell_get(np, "temp_adjust");
277         if (IS_ERR(cell)) {
278                 pr_err("avs failed to get temp_adjust cell\n");
279                 return PTR_ERR(cell);
280         }
281
282         buf = (unsigned char *)nvmem_cell_read(cell, &len);
283
284         nvmem_cell_put(cell);
285
286         if (IS_ERR(buf))
287                 return PTR_ERR(buf);
288
289         if (buf[0] == INVALID_EFUSE_VALUE)
290                 return -EINVAL;
291
292         if (buf[0] & 0x80)
293                 *ajust_code = -(buf[0] & 0x7f);
294         else
295                 *ajust_code = buf[0];
296
297         kfree(buf);
298
299         return 0;
300 }
301
302 static struct rk3368_thermal_data *rk3368_thermal_get_data(void)
303 {
304         WARN_ON(!thermal_ctx);
305         return thermal_ctx;
306 }
307
308 static int rk3368_temp_to_code(const struct chip_tsadc_table *tmp_table,
309                                  long temp, u32 *code)
310 {
311         unsigned int low = 1;
312         unsigned int high = tmp_table->length - 1;
313         unsigned int mid = (low + high) / 2;
314         unsigned int num;
315         unsigned long denom;
316         *code = tmp_table->data_mask;
317
318         WARN_ON(tmp_table->length < 2);
319
320         if (temp < tmp_table->id[low].temp)
321                 return -EAGAIN; /* Incorrect reading */
322
323         while (low <= high) {
324                 if (temp == tmp_table->id[mid].temp) {
325                         *code = tmp_table->id[mid].code;
326                         break;
327                 } else if (temp > tmp_table->id[mid].temp) {
328                         low = mid + 1;
329                 } else {
330                         high = mid - 1;
331                 }
332
333                 mid = (low + high) / 2;
334         }
335         /*
336          * The 5C granularity provided by the table is too much. Let's
337          * assume that the relationship between sensor readings and
338          * temperature between 2 table entries is linear and interpolate
339          * to produce less granular result.
340          */
341         if (*code == tmp_table->data_mask) {
342                 num = abs(tmp_table->id[low].code - tmp_table->id[high].code);
343                 num *= abs(tmp_table->id[high].temp - temp);
344                 denom = abs(tmp_table->id[high].temp - tmp_table->id[low].temp);
345                 *code = tmp_table->id[high].code + (num / denom);
346         }
347
348         return 0;
349 }
350
351 static int rk3368_code_to_temp(const struct chip_tsadc_table *tmp_table,
352                                  u32 code, int *temp)
353 {
354         unsigned int low = 1;
355         unsigned int high = tmp_table->length - 1;
356         unsigned int mid = (low + high) / 2;
357         unsigned int num;
358         unsigned long denom;
359         *temp = INVALID_TEMP;
360
361         WARN_ON(tmp_table->length < 2);
362
363         switch (tmp_table->mode) {
364         case ADC_DECREMENT:
365                 code &= tmp_table->data_mask;
366                 if (code < tmp_table->id[high].code)
367                         return -EAGAIN; /* Incorrect reading */
368
369                 while (low <= high) {
370                         if (code == tmp_table->id[mid].code) {
371                                 *temp = tmp_table->id[mid].temp;
372                                 break;
373                         } else if (code < tmp_table->id[mid].code) {
374                                 low = mid + 1;
375                         } else {
376                                 high = mid - 1;
377                         }
378
379                         mid = (low + high) / 2;
380                 }
381                 break;
382         case ADC_INCREMENT:
383                 code &= tmp_table->data_mask;
384                 if (code < tmp_table->id[low].code)
385                         return -EAGAIN; /* Incorrect reading */
386
387                 while (low <= high) {
388                         if (code == tmp_table->id[mid].code) {
389                                 *temp = tmp_table->id[mid].temp;
390                                 break;
391                         } else if (code > tmp_table->id[mid].code) {
392                                 low = mid + 1;
393                         } else {
394                                 high = mid - 1;
395                         }
396
397                         mid = (low + high) / 2;
398                 }
399                 break;
400         default:
401                 pr_err("Invalid the conversion table\n");
402         }
403
404         /*
405          * The 5C granularity provided by the table is too much. Let's
406          * assume that the relationship between sensor readings and
407          * temperature between 2 table entries is linear and interpolate
408          * to produce less granular result.
409          */
410         if (*temp == INVALID_TEMP) {
411                 num = abs(tmp_table->id[low].temp - tmp_table->id[high].temp);
412                 num *= abs(tmp_table->id[high].code - code);
413                 denom = abs(tmp_table->id[high].code - tmp_table->id[low].code);
414                 *temp = tmp_table->id[high].temp + (num / denom);
415         }
416
417         return 0;
418 }
419
420 static const struct rk3368_tsadc_chip rk3368_tsadc_data = {
421         .tshut_mode = TSHUT_MODE_GPIO,  /* default TSHUT via GPIO give PMIC */
422         .tshut_polarity = TSHUT_LOW_ACTIVE,     /* default TSHUT LOW ACTIVE */
423         .latency_bound = 50000, /* default 50000 us */
424         .hw_shut_temp = 125000,
425         .mode = TSHUT_USER_MODE,
426         .chn_num = 2,
427         .chn_id[0] = 0,
428         .chn_id[1] = 1,
429         .temp_table = &tsadc_table_3368,
430 };
431
432 static int rk3368_configure_from_dt(struct device *dev,
433                                       struct device_node *np,
434                                       struct rk3368_thermal_data *thermal)
435 {
436         u32 shut_temp;
437         u32 rate;
438         u32 cycle;
439         int lat_bound;
440         int ret;
441
442         if (of_property_read_u32(np, "clock-frequency", &rate)) {
443                 dev_err(dev, "Missing clock-frequency property in the DT.\n");
444                 return -EINVAL;
445         }
446         ret = clk_set_rate(thermal->clk, rate);
447
448         cycle = DIV_ROUND_UP(1000000000, rate) / 1000;
449
450         if (scpi_thermal_set_clk_cycle(cycle)) {
451                 dev_err(dev, "scpi_thermal_set_clk_cycle error.\n");
452                 return -EINVAL;
453         }
454
455         if (of_property_read_u32(np, "hw-shut-temp", &shut_temp)) {
456                 dev_warn(dev,
457                          "Missing tshut temp property, using default %ld\n",
458                          thermal->chip->hw_shut_temp);
459                 thermal->hw_shut_temp = thermal->chip->hw_shut_temp;
460         } else {
461                 thermal->hw_shut_temp = shut_temp;
462         }
463
464         if (of_property_read_u32(np, "latency-bound", &lat_bound)) {
465                 dev_warn(dev,
466                          "Missing latency-bound property, using default %d\n",
467                          thermal->chip->latency_bound);
468                 thermal->latency_bound = thermal->chip->latency_bound;
469         } else {
470                 thermal->latency_bound = lat_bound;
471         }
472
473         if (thermal->hw_shut_temp > INT_MAX) {
474                 dev_err(dev, "Invalid tshut temperature specified: %ld\n",
475                         thermal->hw_shut_temp);
476                 return -ERANGE;
477         }
478
479         return 0;
480 }
481
482 static int predict_temp(int temp)
483 {
484         int cov_q = 18;
485         int cov_r = 542;
486
487         int gain;
488         int temp_mid;
489         int temp_now;
490         int prob_mid;
491         int prob_now;
492         static int temp_last = 25;
493         static int prob_last = 20;
494         static int bounding_cnt;
495
496         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
497
498         if (!ctx)
499                 return INVALID_TEMP;
500
501         if (bounding_cnt++ > START_BOUNDING_COUNT) {
502                 bounding_cnt = START_BOUNDING_COUNT;
503                 if (temp - temp_last > HIGHER_BOUNDING_TEMP)
504                         temp = temp_last + HIGHER_BOUNDING_TEMP / 3;
505                 if (temp_last - temp > LOWER_BOUNDING_TEMP)
506                         temp = temp_last - LOWER_BOUNDING_TEMP / 3;
507         }
508
509         temp_mid = temp_last;
510         prob_mid = prob_last + cov_q;
511         gain = (prob_mid * BASE) / (prob_mid + cov_r);
512
513         temp_now = temp_mid + (gain * (temp - temp_mid) >> BASE_SHIFT);
514         prob_now = ((BASE - gain) * prob_mid) >> BASE_SHIFT;
515
516         prob_last = prob_now;
517         temp_last = temp_now;
518
519         if (ctx->logout)
520                 pr_info("prob_now %d, temp_last %d, temp %d gain %d", prob_now,
521                         temp_now, temp, gain);
522
523         return temp_last;
524 }
525
526 static int get_raw_code_internal(void)
527 {
528         u32 val_cpu_pd;
529         int val_cpu;
530         int i;
531         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
532
533         if (!ctx)
534                 return INVALID_TEMP;
535
536         /* power up, channel 0 */
537         writel_relaxed(0x18, ctx->regs + TSADCV2_USER_CON);
538
539         udelay(TSADC_CLK_CYCLE_TIME * 2);
540         /* start working */
541         writel_relaxed(0x38, ctx->regs + TSADCV2_USER_CON);
542         udelay(TSADC_CLK_CYCLE_TIME * 13);
543
544         /* try 50 times */
545         for (i = 0; i < 50; i++) {
546                 udelay(TSADC_CLK_CYCLE_TIME);
547                 val_cpu_pd = readl_relaxed(ctx->regs + TSADCV2_INT_PD);
548
549                 if ((val_cpu_pd & 0x100) == 0x100) {
550                         udelay(1);
551                         /*clear eoc inter */
552                         writel_relaxed(0x100, ctx->regs + TSADCV2_INT_PD);
553                         /*read adc data */
554                         val_cpu = readl_relaxed(ctx->regs + TSADCV2_DATA(0));
555                         break;
556                 }
557         }
558         /*power down, channel 0 */
559         writel_relaxed(0x0, ctx->regs + TSADCV2_USER_CON);
560
561         return val_cpu;
562 }
563
564 #define RAW_CODE_MIN (50)
565 #define RAW_CODE_MAX (225)
566
567 static int rk3368_get_raw_code(struct rk3368_thermal_data *ctx)
568 {
569         static int old_data = 130;
570         int tsadc_data = 0;
571
572         if (ctx->latency_req > ctx->latency_bound)
573                 tsadc_data = scpi_thermal_get_temperature();
574         else
575                 tsadc_data = get_raw_code_internal();
576
577         if ((tsadc_data < RAW_CODE_MIN) || (tsadc_data > RAW_CODE_MAX))
578                 tsadc_data = old_data;
579         else
580                 old_data = tsadc_data;
581
582         return tsadc_data;
583 }
584
585 static int rk3368_convert_code_2_temp(int tsadc_data, int voltage)
586 {
587         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
588         const struct rk3368_tsadc_chip *tsadc;
589         int out_temp;
590         static int old_temp;
591         int data_adjust;
592
593         u32 code_temp;
594         u32 tmp_code1;
595         u32 tmp_code2;
596
597         if (!ctx)
598                 return INVALID_TEMP;
599
600         tsadc = ctx->chip;
601
602         rk3368_temp_to_code(tsadc->temp_table,
603                               ctx->cpu_temp_adjust * 1000, &tmp_code1);
604         rk3368_temp_to_code(tsadc->temp_table, 0, &tmp_code2);
605         data_adjust = tmp_code1 - tmp_code2;
606         code_temp =
607             ((tsadc_data * voltage - data_adjust * 1000000) + 500000) / 1000000;
608         rk3368_code_to_temp(tsadc->temp_table, code_temp, &out_temp);
609
610         if (ctx->logout)
611                 pr_info("cpu code temp:[%d, %d], voltage: %d\n",
612                         tsadc_data, out_temp / 1000, voltage);
613
614         if ((out_temp < MIN_TEMP) || (out_temp > MAX_TEMP))
615                 out_temp = old_temp;
616         else
617                 old_temp = out_temp;
618
619         ctx->cpu_temp = out_temp / 1000;
620         return out_temp;
621 }
622
623 static int rk3368_thermal_set_trips(void *_sensor, int low, int high)
624 {
625         return 0;
626 }
627
628 static int rk3368_thermal_get_temp(void *_sensor, int *out_temp)
629 {
630         int raw_code;
631         int temp;
632         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
633         struct platform_device *pdev;
634
635         if (!ctx)
636                 return INVALID_TEMP;
637
638         pdev = ctx->pdev;
639
640         mutex_lock(&thermal_reg_mutex);
641         raw_code = rk3368_get_raw_code(ctx);
642         temp = rk3368_convert_code_2_temp(raw_code, ctx->regulator_uv);
643         *out_temp = predict_temp(temp / 1000) * 1000;
644         mutex_unlock(&thermal_reg_mutex);
645
646         return 0;
647 }
648
649 static const struct thermal_zone_of_device_ops rk3368_of_thermal_ops = {
650         .get_temp = rk3368_thermal_get_temp,
651         .set_trips = rk3368_thermal_set_trips,
652 };
653
654 static int
655 rk3368_thermal_register_sensor(struct platform_device *pdev,
656                                  struct rk3368_thermal_data *ctx,
657                                  struct rk3368_thermal_sensor *sensor, int id)
658 {
659         int error;
660
661         sensor->ctx = ctx;
662         sensor->id = id;
663         sensor->tzd = devm_thermal_zone_of_sensor_register(&pdev->dev, id,
664                                                            sensor,
665                                                            &rk3368_of_thermal_ops);
666         if (IS_ERR(sensor->tzd)) {
667                 error = PTR_ERR(sensor->tzd);
668                 dev_err(&pdev->dev, "failed to register sensor %d: %d\n",
669                         id, error);
670                 return error;
671         }
672
673         return 0;
674 }
675
676 /*
677  * Reset TSADC Controller, reset all tsadc registers.
678  */
679 static void rk3368_thermal_reset_controller(struct reset_control *reset)
680 {
681         reset_control_assert(reset);
682         udelay(10);
683         reset_control_deassert(reset);
684 }
685
686 static ssize_t rk3368_thermal_temp_adjust_test_store(struct kobject *kobj,
687                                                        struct kobj_attribute
688                                                        *attr, const char *buf,
689                                                        size_t n)
690 {
691         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
692         int getdata;
693         char cmd;
694         const char *buftmp = buf;
695         int ret;
696
697         if (!ctx)
698                 return n;
699
700         ret = sscanf(buftmp, "%c ", &cmd);
701         if (ret != 1)
702                 return -EINVAL;
703
704         switch (cmd) {
705         case 'c':
706                 ret = sscanf(buftmp, "%c %d", &cmd, &getdata);
707                 if (ret != 2)
708                         return -EINVAL;
709                 ctx->cpu_temp_adjust = getdata;
710                 pr_info("get cpu_temp_adjust value = %d\n", getdata);
711
712                 break;
713         case 'g':
714                 ret = sscanf(buftmp, "%c %d", &cmd, &getdata);
715                 if (ret != 2)
716                         return -EINVAL;
717                 ctx->gpu_temp_adjust = getdata;
718                 pr_info("get gpu_temp_adjust value = %d\n", getdata);
719
720                 break;
721         default:
722                 pr_info("Unknown command\n");
723                 break;
724         }
725
726         return n;
727 }
728
729 static ssize_t rk3368_thermal_temp_adjust_test_show(struct kobject *kobj,
730                                                       struct kobj_attribute
731                                                       *attr, char *buf)
732 {
733         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
734         char *str = buf;
735
736         if (!ctx)
737                 return 0;
738
739         str +=
740             sprintf(str, "rk3368_thermal: cpu:%d, gpu:%d\n",
741                     ctx->cpu_temp_adjust, ctx->gpu_temp_adjust);
742         return (str - buf);
743 }
744
745 static ssize_t rk3368_thermal_temp_test_store(struct kobject *kobj,
746                                                 struct kobj_attribute *attr,
747                                                 const char *buf, size_t n)
748 {
749         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
750         char cmd;
751         const char *buftmp = buf;
752         int ret;
753
754         if (!ctx)
755                 return n;
756
757         ret = sscanf(buftmp, "%c", &cmd);
758         if (ret != 1)
759                 return -EINVAL;
760
761         switch (cmd) {
762         case 't':
763                 ctx->logout = true;
764                 break;
765         case 'f':
766                 ctx->logout = false;
767                 break;
768         default:
769                 pr_info("Unknown command\n");
770                 break;
771         }
772
773         return n;
774 }
775
776 static ssize_t rk3368_thermal_temp_test_show(struct kobject *kobj,
777                                                struct kobj_attribute *attr,
778                                                char *buf)
779 {
780         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
781         char *str = buf;
782
783         if (!ctx)
784                 return 0;
785
786         str += sprintf(str, "current cpu_temp:%d\n", ctx->cpu_temp);
787         return (str - buf);
788 }
789
790 struct rk3368_thermal_attribute {
791         struct attribute attr;
792         ssize_t (*show) (struct kobject *kobj, struct kobj_attribute *attr,
793                          char *buf);
794         ssize_t (*store) (struct kobject *kobj, struct kobj_attribute *attr,
795                           const char *buf, size_t n);
796 };
797
798 static struct rk3368_thermal_attribute rk3368_thermal_attrs[] = {
799         /*node_name permission show_func store_func */
800         __ATTR(temp_adjust, 0644,
801                rk3368_thermal_temp_adjust_test_show,
802                rk3368_thermal_temp_adjust_test_store),
803         __ATTR(temp, 0644, rk3368_thermal_temp_test_show,
804                rk3368_thermal_temp_test_store),
805 };
806
807 static void rk3368_dump_temperature(void)
808 {
809         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
810         struct platform_device *pdev;
811
812         if (!ctx)
813                 return;
814
815         pdev = ctx->pdev;
816
817         if (ctx->cpu_temp != INVALID_TEMP)
818                 dev_warn(&pdev->dev, "cpu channal temperature(%d C)\n",
819                          ctx->cpu_temp);
820
821         if (ctx->regs) {
822                 pr_warn("THERMAL REGS:\n");
823                 print_hex_dump(KERN_WARNING, "", DUMP_PREFIX_OFFSET,
824                                32, 4, ctx->regs, 0x88, false);
825         }
826 }
827 EXPORT_SYMBOL_GPL(rk3368_dump_temperature);
828
829 static int rk3368_thermal_panic(struct notifier_block *this,
830                                   unsigned long ev, void *ptr)
831 {
832         rk3368_dump_temperature();
833         return NOTIFY_DONE;
834 }
835
836 static struct notifier_block rk3368_thermal_panic_block = {
837         .notifier_call = rk3368_thermal_panic,
838 };
839
840 static int rk3368_thermal_notify(struct notifier_block *nb,
841                                    unsigned long event, void *data)
842 {
843         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
844         struct platform_device *pdev;
845
846         if (!ctx)
847                 return NOTIFY_OK;
848
849         pdev = ctx->pdev;
850
851         if (event & REGULATOR_EVENT_PRE_VOLTAGE_CHANGE) {
852                 mutex_lock(&thermal_reg_mutex);
853         } else if (event & (REGULATOR_EVENT_VOLTAGE_CHANGE |
854                             REGULATOR_EVENT_ABORT_VOLTAGE_CHANGE)) {
855                 ctx->regulator_uv = (unsigned long)data;
856                 mutex_unlock(&thermal_reg_mutex);
857         } else {
858                 return NOTIFY_OK;
859         }
860         return NOTIFY_OK;
861 }
862
863 /*
864  * This function gets called when a part of the kernel has a new latency
865  * requirement. We record this requirement to instruct us to get temperature.
866  */
867 static int tsadc_latency_notify(struct notifier_block *b,
868                                 unsigned long l, void *v)
869 {
870         struct rk3368_thermal_data *ctx = rk3368_thermal_get_data();
871
872         if (!ctx)
873                 return NOTIFY_OK;
874
875         mutex_lock(&thermal_lat_mutex);
876         ctx->latency_req = (int)l;
877         mutex_unlock(&thermal_lat_mutex);
878
879         return NOTIFY_OK;
880 }
881
882 static struct notifier_block tsadc_latency_notifier = {
883         .notifier_call = tsadc_latency_notify,
884 };
885
886 static inline int tsadc_add_latency_notifier(struct notifier_block *n)
887 {
888         return pm_qos_add_notifier(PM_QOS_CPU_DMA_LATENCY, n);
889 }
890
891 static inline int tsadc_remove_latency_notifier(struct notifier_block *n)
892 {
893         return pm_qos_remove_notifier(PM_QOS_CPU_DMA_LATENCY, n);
894 }
895
896 static const struct of_device_id of_rk3368_thermal_match[] = {
897         {
898          .compatible = "rockchip,rk3368-tsadc-legacy",
899          .data = (void *)&rk3368_tsadc_data,
900          },
901
902         { /* end */ },
903 };
904 MODULE_DEVICE_TABLE(of, of_rk3368_thermal_match);
905
906 static int rk3368_thermal_probe(struct platform_device *pdev)
907 {
908         struct device_node *np = pdev->dev.of_node;
909         struct rk3368_thermal_data *ctx;
910         const struct of_device_id *match;
911         struct resource *res;
912         int irq;
913         int i, j;
914         int error;
915         int uv;
916         int ajust_code = 0;
917         int latency_req = 0;
918
919         match = of_match_node(of_rk3368_thermal_match, np);
920         if (!match)
921                 return -ENXIO;
922
923         irq = platform_get_irq(pdev, 0);
924         if (irq < 0) {
925                 dev_err(&pdev->dev, "no irq resource?\n");
926                 return -EINVAL;
927         }
928
929         ctx = devm_kzalloc(&pdev->dev, sizeof(struct rk3368_thermal_data),
930                            GFP_KERNEL);
931         if (!ctx)
932                 return -ENOMEM;
933
934         ctx->pdev = pdev;
935
936         ctx->chip = (const struct rk3368_tsadc_chip *)match->data;
937         if (!ctx->chip)
938                 return -EINVAL;
939
940         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
941         ctx->regs = devm_ioremap_resource(&pdev->dev, res);
942         if (IS_ERR(ctx->regs))
943                 return PTR_ERR(ctx->regs);
944
945         ctx->reset = devm_reset_control_get(&pdev->dev, "tsadc-apb");
946         if (IS_ERR(ctx->reset)) {
947                 error = PTR_ERR(ctx->reset);
948                 dev_err(&pdev->dev, "failed to get tsadc reset: %d\n", error);
949                 return error;
950         }
951
952         ctx->clk = devm_clk_get(&pdev->dev, "tsadc");
953         if (IS_ERR(ctx->clk)) {
954                 error = PTR_ERR(ctx->clk);
955                 dev_err(&pdev->dev, "failed to get tsadc clock: %d\n", error);
956                 return error;
957         }
958
959         ctx->pclk = devm_clk_get(&pdev->dev, "apb_pclk");
960         if (IS_ERR(ctx->pclk)) {
961                 error = PTR_ERR(ctx->pclk);
962                 dev_err(&pdev->dev, "failed to get apb_pclk clock: %d\n",
963                         error);
964                 return error;
965         }
966
967         error = clk_prepare_enable(ctx->clk);
968         if (error) {
969                 dev_err(&pdev->dev, "failed to enable converter clock: %d\n",
970                         error);
971                 return error;
972         }
973
974         error = clk_prepare_enable(ctx->pclk);
975         if (error) {
976                 dev_err(&pdev->dev, "failed to enable pclk: %d\n", error);
977                 goto err_disable_clk;
978         }
979
980         rk3368_thermal_reset_controller(ctx->reset);
981
982         error = rk3368_configure_from_dt(&pdev->dev, np, ctx);
983         if (error) {
984                 dev_err(&pdev->dev, "failed to parse device tree data: %d\n",
985                         error);
986                 goto err_disable_pclk;
987         }
988
989         thermal_ctx = ctx;
990         ctx->ref_regulator = devm_regulator_get_optional(&pdev->dev, "tsadc");
991
992         if (IS_ERR(ctx->ref_regulator)) {
993                 error = PTR_ERR(ctx->ref_regulator);
994
995                 if (error != -EPROBE_DEFER)
996                         dev_err(&pdev->dev,
997                                 "couldn't get regulator tsadc-supply\n");
998                 goto err_disable_pclk;
999         }
1000
1001         ctx->tsadc_nb.notifier_call = rk3368_thermal_notify;
1002
1003         /* register regulator notifier */
1004         error =
1005             regulator_register_notifier(ctx->ref_regulator, &ctx->tsadc_nb);
1006         if (error) {
1007                 dev_err(&pdev->dev, "regulator notifier request failed\n");
1008                 goto err_disable_pclk;
1009         }
1010
1011         uv = regulator_get_voltage(ctx->ref_regulator);
1012         if (uv <= 0) {
1013                 dev_WARN(&pdev->dev, "regulator get failed\n");
1014                 uv = 1000000;
1015         }
1016
1017         mutex_lock(&thermal_reg_mutex);
1018         if (!ctx->regulator_uv)
1019                 ctx->regulator_uv = uv;
1020         mutex_unlock(&thermal_reg_mutex);
1021
1022         error = tsadc_add_latency_notifier(&tsadc_latency_notifier);
1023         if (error) {
1024                 dev_err(&pdev->dev, "latency notifier request failed\n");
1025                 goto err_unreg_notifier;
1026         }
1027
1028         latency_req = pm_qos_request(PM_QOS_CPU_DMA_LATENCY);
1029
1030         mutex_lock(&thermal_lat_mutex);
1031         if (!ctx->latency_req)
1032                 ctx->latency_req = latency_req;
1033         mutex_unlock(&thermal_lat_mutex);
1034
1035         rk3368_get_ajust_code(np, &ajust_code);
1036
1037         ctx->cpu_temp_adjust = (int)ajust_code;
1038
1039         for (i = 0; i < ctx->chip->chn_num; i++) {
1040                 error = rk3368_thermal_register_sensor(pdev, ctx,
1041                                                          &ctx->sensors[i],
1042                                                          ctx->chip->chn_id[i]);
1043                 if (error) {
1044                         dev_err(&pdev->dev,
1045                                 "failed to register thermal sensor %d : error= %d\n",
1046                                 i, error);
1047                         for (j = 0; j < i; j++)
1048                                 thermal_zone_of_sensor_unregister(&pdev->dev,
1049                                                                   ctx->sensors[j].tzd);
1050                         goto err_remove_latancy_notifier;
1051                 }
1052         }
1053
1054         ctx->rk3368_thermal_kobj =
1055             kobject_create_and_add("rk3368_thermal", NULL);
1056         if (!ctx->rk3368_thermal_kobj) {
1057                 error = -ENOMEM;
1058                 dev_err(&pdev->dev,
1059                         "failed to creat debug node : error= %d\n", error);
1060                 goto err_remove_latancy_notifier;
1061         }
1062
1063         for (i = 0; i < ARRAY_SIZE(rk3368_thermal_attrs); i++) {
1064                 error =
1065                     sysfs_create_file(ctx->rk3368_thermal_kobj,
1066                                       &rk3368_thermal_attrs[i].attr);
1067                 if (error) {
1068                         dev_err(&pdev->dev,
1069                                 "failed to register thermal sensor %d : error= %d\n",
1070                                 i, error);
1071                         for (j = 0; j < i; j++)
1072                                 sysfs_remove_file(ctx->rk3368_thermal_kobj,
1073                                                   &rk3368_thermal_attrs[j].attr);
1074
1075                         goto err_remove_latancy_notifier;
1076                 }
1077         }
1078
1079         platform_set_drvdata(pdev, ctx);
1080
1081         atomic_notifier_chain_register(&panic_notifier_list,
1082                                        &rk3368_thermal_panic_block);
1083
1084         ctx->cpu_temp = INVALID_TEMP;
1085
1086         pr_info("rk3368 tsadc probed successfully\n");
1087
1088         return 0;
1089
1090 err_remove_latancy_notifier:
1091         tsadc_remove_latency_notifier(&tsadc_latency_notifier);
1092 err_unreg_notifier:
1093         regulator_unregister_notifier(ctx->ref_regulator, &ctx->tsadc_nb);
1094
1095 err_disable_pclk:
1096         clk_disable_unprepare(ctx->pclk);
1097 err_disable_clk:
1098         clk_disable_unprepare(ctx->clk);
1099
1100         return error;
1101 }
1102
1103 static int rk3368_thermal_remove(struct platform_device *pdev)
1104 {
1105         struct rk3368_thermal_data *ctx = platform_get_drvdata(pdev);
1106         int i;
1107
1108         atomic_notifier_chain_unregister(&panic_notifier_list,
1109                                          &rk3368_thermal_panic_block);
1110         for (i = 0; i < ctx->chip->chn_num; i++) {
1111                 struct rk3368_thermal_sensor *sensor = &ctx->sensors[i];
1112
1113                 thermal_zone_of_sensor_unregister(&pdev->dev, sensor->tzd);
1114         }
1115         tsadc_remove_latency_notifier(&tsadc_latency_notifier);
1116         regulator_unregister_notifier(ctx->ref_regulator, &ctx->tsadc_nb);
1117         clk_disable_unprepare(ctx->pclk);
1118         clk_disable_unprepare(ctx->clk);
1119
1120         return 0;
1121 }
1122
1123 static int __maybe_unused rk3368_thermal_suspend(struct device *dev)
1124 {
1125         struct platform_device *pdev = to_platform_device(dev);
1126         struct rk3368_thermal_data *ctx = platform_get_drvdata(pdev);
1127
1128         clk_disable(ctx->pclk);
1129         clk_disable(ctx->clk);
1130         return 0;
1131 }
1132
1133 static int __maybe_unused rk3368_thermal_resume(struct device *dev)
1134 {
1135         struct platform_device *pdev = to_platform_device(dev);
1136         struct rk3368_thermal_data *ctx = platform_get_drvdata(pdev);
1137         int error;
1138
1139         error = clk_enable(ctx->clk);
1140         if (error)
1141                 return error;
1142
1143         error = clk_enable(ctx->pclk);
1144         if (error) {
1145                 clk_disable(ctx->clk);
1146                 return error;
1147         }
1148
1149         rk3368_thermal_reset_controller(ctx->reset);
1150
1151         return 0;
1152 }
1153
1154 static SIMPLE_DEV_PM_OPS(rk3368_thermal_pm_ops,
1155                          rk3368_thermal_suspend, rk3368_thermal_resume);
1156
1157 static struct platform_driver rk3368_thermal_driver = {
1158         .driver = {
1159                 .name = "rk3368-thermal",
1160                 .pm = &rk3368_thermal_pm_ops,
1161                 .of_match_table = of_rk3368_thermal_match,
1162         },
1163         .probe = rk3368_thermal_probe,
1164         .remove = rk3368_thermal_remove,
1165 };
1166
1167 /* rk3368 thermal needs a clock source of 32k from rk818, so this init process
1168  * is postponed
1169  */
1170 static int __init rk3368_thermal_init_driver(void)
1171 {
1172         return platform_driver_register(&rk3368_thermal_driver);
1173 }
1174 late_initcall(rk3368_thermal_init_driver);
1175
1176 MODULE_DESCRIPTION("ROCKCHIP THERMAL Driver");
1177 MODULE_AUTHOR("Rockchip, Inc.");
1178 MODULE_LICENSE("GPL v2");
1179 MODULE_ALIAS("platform:rk3368-thermal");