Merge tag 'mfd-next-4.15' of git://git.kernel.org/pub/scm/linux/kernel/git/lee/mfd
[platform/kernel/linux-starfive.git] / drivers / hwmon / sht15.c
1 /*
2  * sht15.c - support for the SHT15 Temperature and Humidity Sensor
3  *
4  * Portions Copyright (c) 2010-2012 Savoir-faire Linux Inc.
5  *          Jerome Oufella <jerome.oufella@savoirfairelinux.com>
6  *          Vivien Didelot <vivien.didelot@savoirfairelinux.com>
7  *
8  * Copyright (c) 2009 Jonathan Cameron
9  *
10  * Copyright (c) 2007 Wouter Horre
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License version 2 as
14  * published by the Free Software Foundation.
15  *
16  * For further information, see the Documentation/hwmon/sht15 file.
17  */
18
19 #include <linux/interrupt.h>
20 #include <linux/irq.h>
21 #include <linux/module.h>
22 #include <linux/init.h>
23 #include <linux/hwmon.h>
24 #include <linux/hwmon-sysfs.h>
25 #include <linux/mutex.h>
26 #include <linux/platform_device.h>
27 #include <linux/sched.h>
28 #include <linux/delay.h>
29 #include <linux/jiffies.h>
30 #include <linux/err.h>
31 #include <linux/regulator/consumer.h>
32 #include <linux/slab.h>
33 #include <linux/atomic.h>
34 #include <linux/bitrev.h>
35 #include <linux/gpio/consumer.h>
36 #include <linux/of.h>
37
38 /* Commands */
39 #define SHT15_MEASURE_TEMP              0x03
40 #define SHT15_MEASURE_RH                0x05
41 #define SHT15_WRITE_STATUS              0x06
42 #define SHT15_READ_STATUS               0x07
43 #define SHT15_SOFT_RESET                0x1E
44
45 /* Min timings */
46 #define SHT15_TSCKL                     100     /* (nsecs) clock low */
47 #define SHT15_TSCKH                     100     /* (nsecs) clock high */
48 #define SHT15_TSU                       150     /* (nsecs) data setup time */
49 #define SHT15_TSRST                     11      /* (msecs) soft reset time */
50
51 /* Status Register Bits */
52 #define SHT15_STATUS_LOW_RESOLUTION     0x01
53 #define SHT15_STATUS_NO_OTP_RELOAD      0x02
54 #define SHT15_STATUS_HEATER             0x04
55 #define SHT15_STATUS_LOW_BATTERY        0x40
56
57 /* List of supported chips */
58 enum sht15_chips { sht10, sht11, sht15, sht71, sht75 };
59
60 /* Actions the driver may be doing */
61 enum sht15_state {
62         SHT15_READING_NOTHING,
63         SHT15_READING_TEMP,
64         SHT15_READING_HUMID
65 };
66
67 /**
68  * struct sht15_temppair - elements of voltage dependent temp calc
69  * @vdd:        supply voltage in microvolts
70  * @d1:         see data sheet
71  */
72 struct sht15_temppair {
73         int vdd; /* microvolts */
74         int d1;
75 };
76
77 /* Table 9 from datasheet - relates temperature calculation to supply voltage */
78 static const struct sht15_temppair temppoints[] = {
79         { 2500000, -39400 },
80         { 3000000, -39600 },
81         { 3500000, -39700 },
82         { 4000000, -39800 },
83         { 5000000, -40100 },
84 };
85
86 /* Table from CRC datasheet, section 2.4 */
87 static const u8 sht15_crc8_table[] = {
88         0,      49,     98,     83,     196,    245,    166,    151,
89         185,    136,    219,    234,    125,    76,     31,     46,
90         67,     114,    33,     16,     135,    182,    229,    212,
91         250,    203,    152,    169,    62,     15,     92,     109,
92         134,    183,    228,    213,    66,     115,    32,     17,
93         63,     14,     93,     108,    251,    202,    153,    168,
94         197,    244,    167,    150,    1,      48,     99,     82,
95         124,    77,     30,     47,     184,    137,    218,    235,
96         61,     12,     95,     110,    249,    200,    155,    170,
97         132,    181,    230,    215,    64,     113,    34,     19,
98         126,    79,     28,     45,     186,    139,    216,    233,
99         199,    246,    165,    148,    3,      50,     97,     80,
100         187,    138,    217,    232,    127,    78,     29,     44,
101         2,      51,     96,     81,     198,    247,    164,    149,
102         248,    201,    154,    171,    60,     13,     94,     111,
103         65,     112,    35,     18,     133,    180,    231,    214,
104         122,    75,     24,     41,     190,    143,    220,    237,
105         195,    242,    161,    144,    7,      54,     101,    84,
106         57,     8,      91,     106,    253,    204,    159,    174,
107         128,    177,    226,    211,    68,     117,    38,     23,
108         252,    205,    158,    175,    56,     9,      90,     107,
109         69,     116,    39,     22,     129,    176,    227,    210,
110         191,    142,    221,    236,    123,    74,     25,     40,
111         6,      55,     100,    85,     194,    243,    160,    145,
112         71,     118,    37,     20,     131,    178,    225,    208,
113         254,    207,    156,    173,    58,     11,     88,     105,
114         4,      53,     102,    87,     192,    241,    162,    147,
115         189,    140,    223,    238,    121,    72,     27,     42,
116         193,    240,    163,    146,    5,      52,     103,    86,
117         120,    73,     26,     43,     188,    141,    222,    239,
118         130,    179,    224,    209,    70,     119,    36,     21,
119         59,     10,     89,     104,    255,    206,    157,    172
120 };
121
122 /**
123  * struct sht15_data - device instance specific data
124  * @sck:                clock GPIO line
125  * @data:               data GPIO line
126  * @read_work:          bh of interrupt handler.
127  * @wait_queue:         wait queue for getting values from device.
128  * @val_temp:           last temperature value read from device.
129  * @val_humid:          last humidity value read from device.
130  * @val_status:         last status register value read from device.
131  * @checksum_ok:        last value read from the device passed CRC validation.
132  * @checksumming:       flag used to enable the data validation with CRC.
133  * @state:              state identifying the action the driver is doing.
134  * @measurements_valid: are the current stored measures valid (start condition).
135  * @status_valid:       is the current stored status valid (start condition).
136  * @last_measurement:   time of last measure.
137  * @last_status:        time of last status reading.
138  * @read_lock:          mutex to ensure only one read in progress at a time.
139  * @dev:                associate device structure.
140  * @hwmon_dev:          device associated with hwmon subsystem.
141  * @reg:                associated regulator (if specified).
142  * @nb:                 notifier block to handle notifications of voltage
143  *                      changes.
144  * @supply_uv:          local copy of supply voltage used to allow use of
145  *                      regulator consumer if available.
146  * @supply_uv_valid:    indicates that an updated value has not yet been
147  *                      obtained from the regulator and so any calculations
148  *                      based upon it will be invalid.
149  * @update_supply_work: work struct that is used to update the supply_uv.
150  * @interrupt_handled:  flag used to indicate a handler has been scheduled.
151  */
152 struct sht15_data {
153         struct gpio_desc                *sck;
154         struct gpio_desc                *data;
155         struct work_struct              read_work;
156         wait_queue_head_t               wait_queue;
157         uint16_t                        val_temp;
158         uint16_t                        val_humid;
159         u8                              val_status;
160         bool                            checksum_ok;
161         bool                            checksumming;
162         enum sht15_state                state;
163         bool                            measurements_valid;
164         bool                            status_valid;
165         unsigned long                   last_measurement;
166         unsigned long                   last_status;
167         struct mutex                    read_lock;
168         struct device                   *dev;
169         struct device                   *hwmon_dev;
170         struct regulator                *reg;
171         struct notifier_block           nb;
172         int                             supply_uv;
173         bool                            supply_uv_valid;
174         struct work_struct              update_supply_work;
175         atomic_t                        interrupt_handled;
176 };
177
178 /**
179  * sht15_crc8() - compute crc8
180  * @data:       sht15 specific data.
181  * @value:      sht15 retrieved data.
182  *
183  * This implements section 2 of the CRC datasheet.
184  */
185 static u8 sht15_crc8(struct sht15_data *data,
186                 const u8 *value,
187                 int len)
188 {
189         u8 crc = bitrev8(data->val_status & 0x0F);
190
191         while (len--) {
192                 crc = sht15_crc8_table[*value ^ crc];
193                 value++;
194         }
195
196         return crc;
197 }
198
199 /**
200  * sht15_connection_reset() - reset the comms interface
201  * @data:       sht15 specific data
202  *
203  * This implements section 3.4 of the data sheet
204  */
205 static int sht15_connection_reset(struct sht15_data *data)
206 {
207         int i, err;
208
209         err = gpiod_direction_output(data->data, 1);
210         if (err)
211                 return err;
212         ndelay(SHT15_TSCKL);
213         gpiod_set_value(data->sck, 0);
214         ndelay(SHT15_TSCKL);
215         for (i = 0; i < 9; ++i) {
216                 gpiod_set_value(data->sck, 1);
217                 ndelay(SHT15_TSCKH);
218                 gpiod_set_value(data->sck, 0);
219                 ndelay(SHT15_TSCKL);
220         }
221         return 0;
222 }
223
224 /**
225  * sht15_send_bit() - send an individual bit to the device
226  * @data:       device state data
227  * @val:        value of bit to be sent
228  */
229 static inline void sht15_send_bit(struct sht15_data *data, int val)
230 {
231         gpiod_set_value(data->data, val);
232         ndelay(SHT15_TSU);
233         gpiod_set_value(data->sck, 1);
234         ndelay(SHT15_TSCKH);
235         gpiod_set_value(data->sck, 0);
236         ndelay(SHT15_TSCKL); /* clock low time */
237 }
238
239 /**
240  * sht15_transmission_start() - specific sequence for new transmission
241  * @data:       device state data
242  *
243  * Timings for this are not documented on the data sheet, so very
244  * conservative ones used in implementation. This implements
245  * figure 12 on the data sheet.
246  */
247 static int sht15_transmission_start(struct sht15_data *data)
248 {
249         int err;
250
251         /* ensure data is high and output */
252         err = gpiod_direction_output(data->data, 1);
253         if (err)
254                 return err;
255         ndelay(SHT15_TSU);
256         gpiod_set_value(data->sck, 0);
257         ndelay(SHT15_TSCKL);
258         gpiod_set_value(data->sck, 1);
259         ndelay(SHT15_TSCKH);
260         gpiod_set_value(data->data, 0);
261         ndelay(SHT15_TSU);
262         gpiod_set_value(data->sck, 0);
263         ndelay(SHT15_TSCKL);
264         gpiod_set_value(data->sck, 1);
265         ndelay(SHT15_TSCKH);
266         gpiod_set_value(data->data, 1);
267         ndelay(SHT15_TSU);
268         gpiod_set_value(data->sck, 0);
269         ndelay(SHT15_TSCKL);
270         return 0;
271 }
272
273 /**
274  * sht15_send_byte() - send a single byte to the device
275  * @data:       device state
276  * @byte:       value to be sent
277  */
278 static void sht15_send_byte(struct sht15_data *data, u8 byte)
279 {
280         int i;
281
282         for (i = 0; i < 8; i++) {
283                 sht15_send_bit(data, !!(byte & 0x80));
284                 byte <<= 1;
285         }
286 }
287
288 /**
289  * sht15_wait_for_response() - checks for ack from device
290  * @data:       device state
291  */
292 static int sht15_wait_for_response(struct sht15_data *data)
293 {
294         int err;
295
296         err = gpiod_direction_input(data->data);
297         if (err)
298                 return err;
299         gpiod_set_value(data->sck, 1);
300         ndelay(SHT15_TSCKH);
301         if (gpiod_get_value(data->data)) {
302                 gpiod_set_value(data->sck, 0);
303                 dev_err(data->dev, "Command not acknowledged\n");
304                 err = sht15_connection_reset(data);
305                 if (err)
306                         return err;
307                 return -EIO;
308         }
309         gpiod_set_value(data->sck, 0);
310         ndelay(SHT15_TSCKL);
311         return 0;
312 }
313
314 /**
315  * sht15_send_cmd() - Sends a command to the device.
316  * @data:       device state
317  * @cmd:        command byte to be sent
318  *
319  * On entry, sck is output low, data is output pull high
320  * and the interrupt disabled.
321  */
322 static int sht15_send_cmd(struct sht15_data *data, u8 cmd)
323 {
324         int err;
325
326         err = sht15_transmission_start(data);
327         if (err)
328                 return err;
329         sht15_send_byte(data, cmd);
330         return sht15_wait_for_response(data);
331 }
332
333 /**
334  * sht15_soft_reset() - send a soft reset command
335  * @data:       sht15 specific data.
336  *
337  * As described in section 3.2 of the datasheet.
338  */
339 static int sht15_soft_reset(struct sht15_data *data)
340 {
341         int ret;
342
343         ret = sht15_send_cmd(data, SHT15_SOFT_RESET);
344         if (ret)
345                 return ret;
346         msleep(SHT15_TSRST);
347         /* device resets default hardware status register value */
348         data->val_status = 0;
349
350         return ret;
351 }
352
353 /**
354  * sht15_ack() - send a ack
355  * @data:       sht15 specific data.
356  *
357  * Each byte of data is acknowledged by pulling the data line
358  * low for one clock pulse.
359  */
360 static int sht15_ack(struct sht15_data *data)
361 {
362         int err;
363
364         err = gpiod_direction_output(data->data, 0);
365         if (err)
366                 return err;
367         ndelay(SHT15_TSU);
368         gpiod_set_value(data->sck, 1);
369         ndelay(SHT15_TSU);
370         gpiod_set_value(data->sck, 0);
371         ndelay(SHT15_TSU);
372         gpiod_set_value(data->data, 1);
373
374         return gpiod_direction_input(data->data);
375 }
376
377 /**
378  * sht15_end_transmission() - notify device of end of transmission
379  * @data:       device state.
380  *
381  * This is basically a NAK (single clock pulse, data high).
382  */
383 static int sht15_end_transmission(struct sht15_data *data)
384 {
385         int err;
386
387         err = gpiod_direction_output(data->data, 1);
388         if (err)
389                 return err;
390         ndelay(SHT15_TSU);
391         gpiod_set_value(data->sck, 1);
392         ndelay(SHT15_TSCKH);
393         gpiod_set_value(data->sck, 0);
394         ndelay(SHT15_TSCKL);
395         return 0;
396 }
397
398 /**
399  * sht15_read_byte() - Read a byte back from the device
400  * @data:       device state.
401  */
402 static u8 sht15_read_byte(struct sht15_data *data)
403 {
404         int i;
405         u8 byte = 0;
406
407         for (i = 0; i < 8; ++i) {
408                 byte <<= 1;
409                 gpiod_set_value(data->sck, 1);
410                 ndelay(SHT15_TSCKH);
411                 byte |= !!gpiod_get_value(data->data);
412                 gpiod_set_value(data->sck, 0);
413                 ndelay(SHT15_TSCKL);
414         }
415         return byte;
416 }
417
418 /**
419  * sht15_send_status() - write the status register byte
420  * @data:       sht15 specific data.
421  * @status:     the byte to set the status register with.
422  *
423  * As described in figure 14 and table 5 of the datasheet.
424  */
425 static int sht15_send_status(struct sht15_data *data, u8 status)
426 {
427         int err;
428
429         err = sht15_send_cmd(data, SHT15_WRITE_STATUS);
430         if (err)
431                 return err;
432         err = gpiod_direction_output(data->data, 1);
433         if (err)
434                 return err;
435         ndelay(SHT15_TSU);
436         sht15_send_byte(data, status);
437         err = sht15_wait_for_response(data);
438         if (err)
439                 return err;
440
441         data->val_status = status;
442         return 0;
443 }
444
445 /**
446  * sht15_update_status() - get updated status register from device if too old
447  * @data:       device instance specific data.
448  *
449  * As described in figure 15 and table 5 of the datasheet.
450  */
451 static int sht15_update_status(struct sht15_data *data)
452 {
453         int ret = 0;
454         u8 status;
455         u8 previous_config;
456         u8 dev_checksum = 0;
457         u8 checksum_vals[2];
458         int timeout = HZ;
459
460         mutex_lock(&data->read_lock);
461         if (time_after(jiffies, data->last_status + timeout)
462                         || !data->status_valid) {
463                 ret = sht15_send_cmd(data, SHT15_READ_STATUS);
464                 if (ret)
465                         goto unlock;
466                 status = sht15_read_byte(data);
467
468                 if (data->checksumming) {
469                         sht15_ack(data);
470                         dev_checksum = bitrev8(sht15_read_byte(data));
471                         checksum_vals[0] = SHT15_READ_STATUS;
472                         checksum_vals[1] = status;
473                         data->checksum_ok = (sht15_crc8(data, checksum_vals, 2)
474                                         == dev_checksum);
475                 }
476
477                 ret = sht15_end_transmission(data);
478                 if (ret)
479                         goto unlock;
480
481                 /*
482                  * Perform checksum validation on the received data.
483                  * Specification mentions that in case a checksum verification
484                  * fails, a soft reset command must be sent to the device.
485                  */
486                 if (data->checksumming && !data->checksum_ok) {
487                         previous_config = data->val_status & 0x07;
488                         ret = sht15_soft_reset(data);
489                         if (ret)
490                                 goto unlock;
491                         if (previous_config) {
492                                 ret = sht15_send_status(data, previous_config);
493                                 if (ret) {
494                                         dev_err(data->dev,
495                                                 "CRC validation failed, unable "
496                                                 "to restore device settings\n");
497                                         goto unlock;
498                                 }
499                         }
500                         ret = -EAGAIN;
501                         goto unlock;
502                 }
503
504                 data->val_status = status;
505                 data->status_valid = true;
506                 data->last_status = jiffies;
507         }
508
509 unlock:
510         mutex_unlock(&data->read_lock);
511         return ret;
512 }
513
514 /**
515  * sht15_measurement() - get a new value from device
516  * @data:               device instance specific data
517  * @command:            command sent to request value
518  * @timeout_msecs:      timeout after which comms are assumed
519  *                      to have failed are reset.
520  */
521 static int sht15_measurement(struct sht15_data *data,
522                              int command,
523                              int timeout_msecs)
524 {
525         int ret;
526         u8 previous_config;
527
528         ret = sht15_send_cmd(data, command);
529         if (ret)
530                 return ret;
531
532         ret = gpiod_direction_input(data->data);
533         if (ret)
534                 return ret;
535         atomic_set(&data->interrupt_handled, 0);
536
537         enable_irq(gpiod_to_irq(data->data));
538         if (gpiod_get_value(data->data) == 0) {
539                 disable_irq_nosync(gpiod_to_irq(data->data));
540                 /* Only relevant if the interrupt hasn't occurred. */
541                 if (!atomic_read(&data->interrupt_handled))
542                         schedule_work(&data->read_work);
543         }
544         ret = wait_event_timeout(data->wait_queue,
545                                  (data->state == SHT15_READING_NOTHING),
546                                  msecs_to_jiffies(timeout_msecs));
547         if (data->state != SHT15_READING_NOTHING) { /* I/O error occurred */
548                 data->state = SHT15_READING_NOTHING;
549                 return -EIO;
550         } else if (ret == 0) { /* timeout occurred */
551                 disable_irq_nosync(gpiod_to_irq(data->data));
552                 ret = sht15_connection_reset(data);
553                 if (ret)
554                         return ret;
555                 return -ETIME;
556         }
557
558         /*
559          *  Perform checksum validation on the received data.
560          *  Specification mentions that in case a checksum verification fails,
561          *  a soft reset command must be sent to the device.
562          */
563         if (data->checksumming && !data->checksum_ok) {
564                 previous_config = data->val_status & 0x07;
565                 ret = sht15_soft_reset(data);
566                 if (ret)
567                         return ret;
568                 if (previous_config) {
569                         ret = sht15_send_status(data, previous_config);
570                         if (ret) {
571                                 dev_err(data->dev,
572                                         "CRC validation failed, unable "
573                                         "to restore device settings\n");
574                                 return ret;
575                         }
576                 }
577                 return -EAGAIN;
578         }
579
580         return 0;
581 }
582
583 /**
584  * sht15_update_measurements() - get updated measures from device if too old
585  * @data:       device state
586  */
587 static int sht15_update_measurements(struct sht15_data *data)
588 {
589         int ret = 0;
590         int timeout = HZ;
591
592         mutex_lock(&data->read_lock);
593         if (time_after(jiffies, data->last_measurement + timeout)
594             || !data->measurements_valid) {
595                 data->state = SHT15_READING_HUMID;
596                 ret = sht15_measurement(data, SHT15_MEASURE_RH, 160);
597                 if (ret)
598                         goto unlock;
599                 data->state = SHT15_READING_TEMP;
600                 ret = sht15_measurement(data, SHT15_MEASURE_TEMP, 400);
601                 if (ret)
602                         goto unlock;
603                 data->measurements_valid = true;
604                 data->last_measurement = jiffies;
605         }
606
607 unlock:
608         mutex_unlock(&data->read_lock);
609         return ret;
610 }
611
612 /**
613  * sht15_calc_temp() - convert the raw reading to a temperature
614  * @data:       device state
615  *
616  * As per section 4.3 of the data sheet.
617  */
618 static inline int sht15_calc_temp(struct sht15_data *data)
619 {
620         int d1 = temppoints[0].d1;
621         int d2 = (data->val_status & SHT15_STATUS_LOW_RESOLUTION) ? 40 : 10;
622         int i;
623
624         for (i = ARRAY_SIZE(temppoints) - 1; i > 0; i--)
625                 /* Find pointer to interpolate */
626                 if (data->supply_uv > temppoints[i - 1].vdd) {
627                         d1 = (data->supply_uv - temppoints[i - 1].vdd)
628                                 * (temppoints[i].d1 - temppoints[i - 1].d1)
629                                 / (temppoints[i].vdd - temppoints[i - 1].vdd)
630                                 + temppoints[i - 1].d1;
631                         break;
632                 }
633
634         return data->val_temp * d2 + d1;
635 }
636
637 /**
638  * sht15_calc_humid() - using last temperature convert raw to humid
639  * @data:       device state
640  *
641  * This is the temperature compensated version as per section 4.2 of
642  * the data sheet.
643  *
644  * The sensor is assumed to be V3, which is compatible with V4.
645  * Humidity conversion coefficients are shown in table 7 of the datasheet.
646  */
647 static inline int sht15_calc_humid(struct sht15_data *data)
648 {
649         int rh_linear; /* milli percent */
650         int temp = sht15_calc_temp(data);
651         int c2, c3;
652         int t2;
653         const int c1 = -4;
654
655         if (data->val_status & SHT15_STATUS_LOW_RESOLUTION) {
656                 c2 = 648000; /* x 10 ^ -6 */
657                 c3 = -7200;  /* x 10 ^ -7 */
658                 t2 = 1280;
659         } else {
660                 c2 = 40500;  /* x 10 ^ -6 */
661                 c3 = -28;    /* x 10 ^ -7 */
662                 t2 = 80;
663         }
664
665         rh_linear = c1 * 1000
666                 + c2 * data->val_humid / 1000
667                 + (data->val_humid * data->val_humid * c3) / 10000;
668         return (temp - 25000) * (10000 + t2 * data->val_humid)
669                 / 1000000 + rh_linear;
670 }
671
672 /**
673  * sht15_show_status() - show status information in sysfs
674  * @dev:        device.
675  * @attr:       device attribute.
676  * @buf:        sysfs buffer where information is written to.
677  *
678  * Will be called on read access to temp1_fault, humidity1_fault
679  * and heater_enable sysfs attributes.
680  * Returns number of bytes written into buffer, negative errno on error.
681  */
682 static ssize_t sht15_show_status(struct device *dev,
683                                  struct device_attribute *attr,
684                                  char *buf)
685 {
686         int ret;
687         struct sht15_data *data = dev_get_drvdata(dev);
688         u8 bit = to_sensor_dev_attr(attr)->index;
689
690         ret = sht15_update_status(data);
691
692         return ret ? ret : sprintf(buf, "%d\n", !!(data->val_status & bit));
693 }
694
695 /**
696  * sht15_store_heater() - change heater state via sysfs
697  * @dev:        device.
698  * @attr:       device attribute.
699  * @buf:        sysfs buffer to read the new heater state from.
700  * @count:      length of the data.
701  *
702  * Will be called on write access to heater_enable sysfs attribute.
703  * Returns number of bytes actually decoded, negative errno on error.
704  */
705 static ssize_t sht15_store_heater(struct device *dev,
706                                   struct device_attribute *attr,
707                                   const char *buf, size_t count)
708 {
709         int ret;
710         struct sht15_data *data = dev_get_drvdata(dev);
711         long value;
712         u8 status;
713
714         if (kstrtol(buf, 10, &value))
715                 return -EINVAL;
716
717         mutex_lock(&data->read_lock);
718         status = data->val_status & 0x07;
719         if (!!value)
720                 status |= SHT15_STATUS_HEATER;
721         else
722                 status &= ~SHT15_STATUS_HEATER;
723
724         ret = sht15_send_status(data, status);
725         mutex_unlock(&data->read_lock);
726
727         return ret ? ret : count;
728 }
729
730 /**
731  * sht15_show_temp() - show temperature measurement value in sysfs
732  * @dev:        device.
733  * @attr:       device attribute.
734  * @buf:        sysfs buffer where measurement values are written to.
735  *
736  * Will be called on read access to temp1_input sysfs attribute.
737  * Returns number of bytes written into buffer, negative errno on error.
738  */
739 static ssize_t sht15_show_temp(struct device *dev,
740                                struct device_attribute *attr,
741                                char *buf)
742 {
743         int ret;
744         struct sht15_data *data = dev_get_drvdata(dev);
745
746         /* Technically no need to read humidity as well */
747         ret = sht15_update_measurements(data);
748
749         return ret ? ret : sprintf(buf, "%d\n",
750                                    sht15_calc_temp(data));
751 }
752
753 /**
754  * sht15_show_humidity() - show humidity measurement value in sysfs
755  * @dev:        device.
756  * @attr:       device attribute.
757  * @buf:        sysfs buffer where measurement values are written to.
758  *
759  * Will be called on read access to humidity1_input sysfs attribute.
760  * Returns number of bytes written into buffer, negative errno on error.
761  */
762 static ssize_t sht15_show_humidity(struct device *dev,
763                                    struct device_attribute *attr,
764                                    char *buf)
765 {
766         int ret;
767         struct sht15_data *data = dev_get_drvdata(dev);
768
769         ret = sht15_update_measurements(data);
770
771         return ret ? ret : sprintf(buf, "%d\n", sht15_calc_humid(data));
772 }
773
774 static ssize_t name_show(struct device *dev,
775                          struct device_attribute *attr,
776                          char *buf)
777 {
778         struct platform_device *pdev = to_platform_device(dev);
779         return sprintf(buf, "%s\n", pdev->name);
780 }
781
782 static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO,
783                           sht15_show_temp, NULL, 0);
784 static SENSOR_DEVICE_ATTR(humidity1_input, S_IRUGO,
785                           sht15_show_humidity, NULL, 0);
786 static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, sht15_show_status, NULL,
787                           SHT15_STATUS_LOW_BATTERY);
788 static SENSOR_DEVICE_ATTR(humidity1_fault, S_IRUGO, sht15_show_status, NULL,
789                           SHT15_STATUS_LOW_BATTERY);
790 static SENSOR_DEVICE_ATTR(heater_enable, S_IRUGO | S_IWUSR, sht15_show_status,
791                           sht15_store_heater, SHT15_STATUS_HEATER);
792 static DEVICE_ATTR_RO(name);
793 static struct attribute *sht15_attrs[] = {
794         &sensor_dev_attr_temp1_input.dev_attr.attr,
795         &sensor_dev_attr_humidity1_input.dev_attr.attr,
796         &sensor_dev_attr_temp1_fault.dev_attr.attr,
797         &sensor_dev_attr_humidity1_fault.dev_attr.attr,
798         &sensor_dev_attr_heater_enable.dev_attr.attr,
799         &dev_attr_name.attr,
800         NULL,
801 };
802
803 static const struct attribute_group sht15_attr_group = {
804         .attrs = sht15_attrs,
805 };
806
807 static irqreturn_t sht15_interrupt_fired(int irq, void *d)
808 {
809         struct sht15_data *data = d;
810
811         /* First disable the interrupt */
812         disable_irq_nosync(irq);
813         atomic_inc(&data->interrupt_handled);
814         /* Then schedule a reading work struct */
815         if (data->state != SHT15_READING_NOTHING)
816                 schedule_work(&data->read_work);
817         return IRQ_HANDLED;
818 }
819
820 static void sht15_bh_read_data(struct work_struct *work_s)
821 {
822         uint16_t val = 0;
823         u8 dev_checksum = 0;
824         u8 checksum_vals[3];
825         struct sht15_data *data
826                 = container_of(work_s, struct sht15_data,
827                                read_work);
828
829         /* Firstly, verify the line is low */
830         if (gpiod_get_value(data->data)) {
831                 /*
832                  * If not, then start the interrupt again - care here as could
833                  * have gone low in meantime so verify it hasn't!
834                  */
835                 atomic_set(&data->interrupt_handled, 0);
836                 enable_irq(gpiod_to_irq(data->data));
837                 /* If still not occurred or another handler was scheduled */
838                 if (gpiod_get_value(data->data)
839                     || atomic_read(&data->interrupt_handled))
840                         return;
841         }
842
843         /* Read the data back from the device */
844         val = sht15_read_byte(data);
845         val <<= 8;
846         if (sht15_ack(data))
847                 goto wakeup;
848         val |= sht15_read_byte(data);
849
850         if (data->checksumming) {
851                 /*
852                  * Ask the device for a checksum and read it back.
853                  * Note: the device sends the checksum byte reversed.
854                  */
855                 if (sht15_ack(data))
856                         goto wakeup;
857                 dev_checksum = bitrev8(sht15_read_byte(data));
858                 checksum_vals[0] = (data->state == SHT15_READING_TEMP) ?
859                         SHT15_MEASURE_TEMP : SHT15_MEASURE_RH;
860                 checksum_vals[1] = (u8) (val >> 8);
861                 checksum_vals[2] = (u8) val;
862                 data->checksum_ok
863                         = (sht15_crc8(data, checksum_vals, 3) == dev_checksum);
864         }
865
866         /* Tell the device we are done */
867         if (sht15_end_transmission(data))
868                 goto wakeup;
869
870         switch (data->state) {
871         case SHT15_READING_TEMP:
872                 data->val_temp = val;
873                 break;
874         case SHT15_READING_HUMID:
875                 data->val_humid = val;
876                 break;
877         default:
878                 break;
879         }
880
881         data->state = SHT15_READING_NOTHING;
882 wakeup:
883         wake_up(&data->wait_queue);
884 }
885
886 static void sht15_update_voltage(struct work_struct *work_s)
887 {
888         struct sht15_data *data
889                 = container_of(work_s, struct sht15_data,
890                                update_supply_work);
891         data->supply_uv = regulator_get_voltage(data->reg);
892 }
893
894 /**
895  * sht15_invalidate_voltage() - mark supply voltage invalid when notified by reg
896  * @nb:         associated notification structure
897  * @event:      voltage regulator state change event code
898  * @ignored:    function parameter - ignored here
899  *
900  * Note that as the notification code holds the regulator lock, we have
901  * to schedule an update of the supply voltage rather than getting it directly.
902  */
903 static int sht15_invalidate_voltage(struct notifier_block *nb,
904                                     unsigned long event,
905                                     void *ignored)
906 {
907         struct sht15_data *data = container_of(nb, struct sht15_data, nb);
908
909         if (event == REGULATOR_EVENT_VOLTAGE_CHANGE)
910                 data->supply_uv_valid = false;
911         schedule_work(&data->update_supply_work);
912
913         return NOTIFY_OK;
914 }
915
916 #ifdef CONFIG_OF
917 static const struct of_device_id sht15_dt_match[] = {
918         { .compatible = "sensirion,sht15" },
919         { },
920 };
921 MODULE_DEVICE_TABLE(of, sht15_dt_match);
922 #endif
923
924 static int sht15_probe(struct platform_device *pdev)
925 {
926         int ret;
927         struct sht15_data *data;
928
929         data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
930         if (!data)
931                 return -ENOMEM;
932
933         INIT_WORK(&data->read_work, sht15_bh_read_data);
934         INIT_WORK(&data->update_supply_work, sht15_update_voltage);
935         platform_set_drvdata(pdev, data);
936         mutex_init(&data->read_lock);
937         data->dev = &pdev->dev;
938         init_waitqueue_head(&data->wait_queue);
939
940         /*
941          * If a regulator is available,
942          * query what the supply voltage actually is!
943          */
944         data->reg = devm_regulator_get_optional(data->dev, "vcc");
945         if (!IS_ERR(data->reg)) {
946                 int voltage;
947
948                 voltage = regulator_get_voltage(data->reg);
949                 if (voltage)
950                         data->supply_uv = voltage;
951
952                 ret = regulator_enable(data->reg);
953                 if (ret != 0) {
954                         dev_err(&pdev->dev,
955                                 "failed to enable regulator: %d\n", ret);
956                         return ret;
957                 }
958
959                 /*
960                  * Setup a notifier block to update this if another device
961                  * causes the voltage to change
962                  */
963                 data->nb.notifier_call = &sht15_invalidate_voltage;
964                 ret = regulator_register_notifier(data->reg, &data->nb);
965                 if (ret) {
966                         dev_err(&pdev->dev,
967                                 "regulator notifier request failed\n");
968                         regulator_disable(data->reg);
969                         return ret;
970                 }
971         }
972
973         /* Try requesting the GPIOs */
974         data->sck = devm_gpiod_get(&pdev->dev, "clk", GPIOD_OUT_LOW);
975         if (IS_ERR(data->sck)) {
976                 ret = PTR_ERR(data->sck);
977                 dev_err(&pdev->dev, "clock line GPIO request failed\n");
978                 goto err_release_reg;
979         }
980         data->data = devm_gpiod_get(&pdev->dev, "data", GPIOD_IN);
981         if (IS_ERR(data->data)) {
982                 ret = PTR_ERR(data->data);
983                 dev_err(&pdev->dev, "data line GPIO request failed\n");
984                 goto err_release_reg;
985         }
986
987         ret = devm_request_irq(&pdev->dev, gpiod_to_irq(data->data),
988                                sht15_interrupt_fired,
989                                IRQF_TRIGGER_FALLING,
990                                "sht15 data",
991                                data);
992         if (ret) {
993                 dev_err(&pdev->dev, "failed to get irq for data line\n");
994                 goto err_release_reg;
995         }
996         disable_irq_nosync(gpiod_to_irq(data->data));
997         ret = sht15_connection_reset(data);
998         if (ret)
999                 goto err_release_reg;
1000         ret = sht15_soft_reset(data);
1001         if (ret)
1002                 goto err_release_reg;
1003
1004         ret = sysfs_create_group(&pdev->dev.kobj, &sht15_attr_group);
1005         if (ret) {
1006                 dev_err(&pdev->dev, "sysfs create failed\n");
1007                 goto err_release_reg;
1008         }
1009
1010         data->hwmon_dev = hwmon_device_register(data->dev);
1011         if (IS_ERR(data->hwmon_dev)) {
1012                 ret = PTR_ERR(data->hwmon_dev);
1013                 goto err_release_sysfs_group;
1014         }
1015
1016         return 0;
1017
1018 err_release_sysfs_group:
1019         sysfs_remove_group(&pdev->dev.kobj, &sht15_attr_group);
1020 err_release_reg:
1021         if (!IS_ERR(data->reg)) {
1022                 regulator_unregister_notifier(data->reg, &data->nb);
1023                 regulator_disable(data->reg);
1024         }
1025         return ret;
1026 }
1027
1028 static int sht15_remove(struct platform_device *pdev)
1029 {
1030         struct sht15_data *data = platform_get_drvdata(pdev);
1031
1032         /*
1033          * Make sure any reads from the device are done and
1034          * prevent new ones beginning
1035          */
1036         mutex_lock(&data->read_lock);
1037         if (sht15_soft_reset(data)) {
1038                 mutex_unlock(&data->read_lock);
1039                 return -EFAULT;
1040         }
1041         hwmon_device_unregister(data->hwmon_dev);
1042         sysfs_remove_group(&pdev->dev.kobj, &sht15_attr_group);
1043         if (!IS_ERR(data->reg)) {
1044                 regulator_unregister_notifier(data->reg, &data->nb);
1045                 regulator_disable(data->reg);
1046         }
1047
1048         mutex_unlock(&data->read_lock);
1049
1050         return 0;
1051 }
1052
1053 static const struct platform_device_id sht15_device_ids[] = {
1054         { "sht10", sht10 },
1055         { "sht11", sht11 },
1056         { "sht15", sht15 },
1057         { "sht71", sht71 },
1058         { "sht75", sht75 },
1059         { }
1060 };
1061 MODULE_DEVICE_TABLE(platform, sht15_device_ids);
1062
1063 static struct platform_driver sht15_driver = {
1064         .driver = {
1065                 .name = "sht15",
1066                 .of_match_table = of_match_ptr(sht15_dt_match),
1067         },
1068         .probe = sht15_probe,
1069         .remove = sht15_remove,
1070         .id_table = sht15_device_ids,
1071 };
1072 module_platform_driver(sht15_driver);
1073
1074 MODULE_LICENSE("GPL");
1075 MODULE_DESCRIPTION("Sensirion SHT15 temperature and humidity sensor driver");