xref: /linux/drivers/iio/humidity/hdc3020.c (revision 6cf62f0174de64e4161e301bb0ed52e198ce25dc)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * hdc3020.c - Support for the TI HDC3020,HDC3021 and HDC3022
4  * temperature + relative humidity sensors
5  *
6  * Copyright (C) 2023
7  *
8  * Copyright (C) 2024 Liebherr-Electronics and Drives GmbH
9  *
10  * Datasheet: https://www.ti.com/lit/ds/symlink/hdc3020.pdf
11  */
12 
13 #include <linux/bitfield.h>
14 #include <linux/bitops.h>
15 #include <linux/cleanup.h>
16 #include <linux/crc8.h>
17 #include <linux/delay.h>
18 #include <linux/gpio/consumer.h>
19 #include <linux/i2c.h>
20 #include <linux/init.h>
21 #include <linux/interrupt.h>
22 #include <linux/math64.h>
23 #include <linux/module.h>
24 #include <linux/mutex.h>
25 #include <linux/pm.h>
26 #include <linux/regulator/consumer.h>
27 #include <linux/units.h>
28 
29 #include <linux/unaligned.h>
30 
31 #include <linux/iio/events.h>
32 #include <linux/iio/iio.h>
33 
34 #define HDC3020_S_AUTO_10HZ_MOD0	0x2737
35 #define HDC3020_S_STATUS		0x3041
36 #define HDC3020_HEATER_DISABLE		0x3066
37 #define HDC3020_HEATER_ENABLE		0x306D
38 #define HDC3020_HEATER_CONFIG		0x306E
39 #define HDC3020_EXIT_AUTO		0x3093
40 #define HDC3020_S_T_RH_THRESH_LOW	0x6100
41 #define HDC3020_S_T_RH_THRESH_LOW_CLR	0x610B
42 #define HDC3020_S_T_RH_THRESH_HIGH_CLR	0x6116
43 #define HDC3020_S_T_RH_THRESH_HIGH	0x611D
44 #define HDC3020_R_T_RH_AUTO		0xE000
45 #define HDC3020_R_T_LOW_AUTO		0xE002
46 #define HDC3020_R_T_HIGH_AUTO		0xE003
47 #define HDC3020_R_RH_LOW_AUTO		0xE004
48 #define HDC3020_R_RH_HIGH_AUTO		0xE005
49 #define HDC3020_R_T_RH_THRESH_LOW	0xE102
50 #define HDC3020_R_T_RH_THRESH_LOW_CLR	0xE109
51 #define HDC3020_R_T_RH_THRESH_HIGH_CLR	0xE114
52 #define HDC3020_R_T_RH_THRESH_HIGH	0xE11F
53 #define HDC3020_R_STATUS		0xF32D
54 
55 #define HDC3020_THRESH_TEMP_MASK	GENMASK(8, 0)
56 #define HDC3020_THRESH_TEMP_TRUNC_SHIFT	7
57 #define HDC3020_THRESH_HUM_MASK		GENMASK(15, 9)
58 #define HDC3020_THRESH_HUM_TRUNC_SHIFT	9
59 
60 #define HDC3020_STATUS_T_LOW_ALERT	BIT(6)
61 #define HDC3020_STATUS_T_HIGH_ALERT	BIT(7)
62 #define HDC3020_STATUS_RH_LOW_ALERT	BIT(8)
63 #define HDC3020_STATUS_RH_HIGH_ALERT	BIT(9)
64 
65 #define HDC3020_READ_RETRY_TIMES	10
66 #define HDC3020_BUSY_DELAY_MS		10
67 
68 #define HDC3020_CRC8_POLYNOMIAL		0x31
69 
70 #define HDC3020_MIN_TEMP_MICRO		-39872968
71 #define HDC3020_MAX_TEMP_MICRO		124875639
72 #define HDC3020_MAX_TEMP_HYST_MICRO	164748607
73 #define HDC3020_MAX_HUM_MICRO		99220264
74 
75 /* Divide 65535 from the datasheet by 5 to avoid overflows */
76 #define HDC3020_THRESH_FRACTION		(65535 / 5)
77 
78 struct hdc3020_data {
79 	struct i2c_client *client;
80 	struct gpio_desc *reset_gpio;
81 	struct regulator *vdd_supply;
82 	/*
83 	 * Ensure that the sensor configuration (currently only heater is
84 	 * supported) will not be changed during the process of reading
85 	 * sensor data (this driver will try HDC3020_READ_RETRY_TIMES times
86 	 * if the device does not respond).
87 	 */
88 	struct mutex lock;
89 };
90 
91 static const int hdc3020_heater_vals[] = {0, 1, 0x3FFF};
92 
93 static const struct iio_event_spec hdc3020_t_rh_event[] = {
94 	{
95 		.type = IIO_EV_TYPE_THRESH,
96 		.dir = IIO_EV_DIR_RISING,
97 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
98 		BIT(IIO_EV_INFO_HYSTERESIS),
99 	},
100 	{
101 		.type = IIO_EV_TYPE_THRESH,
102 		.dir = IIO_EV_DIR_FALLING,
103 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
104 		BIT(IIO_EV_INFO_HYSTERESIS),
105 	},
106 };
107 
108 static const struct iio_chan_spec hdc3020_channels[] = {
109 	{
110 		.type = IIO_TEMP,
111 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
112 		BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_PEAK) |
113 		BIT(IIO_CHAN_INFO_TROUGH) | BIT(IIO_CHAN_INFO_OFFSET),
114 		.event_spec = hdc3020_t_rh_event,
115 		.num_event_specs = ARRAY_SIZE(hdc3020_t_rh_event),
116 	},
117 	{
118 		.type = IIO_HUMIDITYRELATIVE,
119 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
120 		BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_PEAK) |
121 		BIT(IIO_CHAN_INFO_TROUGH),
122 		.event_spec = hdc3020_t_rh_event,
123 		.num_event_specs = ARRAY_SIZE(hdc3020_t_rh_event),
124 	},
125 	{
126 		/*
127 		 * For setting the internal heater, which can be switched on to
128 		 * prevent or remove any condensation that may develop when the
129 		 * ambient environment approaches its dew point temperature.
130 		 */
131 		.type = IIO_CURRENT,
132 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
133 		.info_mask_separate_available = BIT(IIO_CHAN_INFO_RAW),
134 		.output = 1,
135 	},
136 };
137 
138 DECLARE_CRC8_TABLE(hdc3020_crc8_table);
139 
hdc3020_write_bytes(struct hdc3020_data * data,u8 * buf,u8 len)140 static int hdc3020_write_bytes(struct hdc3020_data *data, u8 *buf, u8 len)
141 {
142 	struct i2c_client *client = data->client;
143 	struct i2c_msg msg;
144 	int ret, cnt;
145 
146 	msg.addr = client->addr;
147 	msg.flags = 0;
148 	msg.buf = buf;
149 	msg.len = len;
150 
151 	/*
152 	 * During the measurement process, HDC3020 will not return data.
153 	 * So wait for a while and try again
154 	 */
155 	for (cnt = 0; cnt < HDC3020_READ_RETRY_TIMES; cnt++) {
156 		ret = i2c_transfer(client->adapter, &msg, 1);
157 		if (ret == 1)
158 			return 0;
159 
160 		mdelay(HDC3020_BUSY_DELAY_MS);
161 	}
162 	dev_err(&client->dev, "Could not write sensor command\n");
163 
164 	return -ETIMEDOUT;
165 }
166 
167 static
hdc3020_read_bytes(struct hdc3020_data * data,u16 reg,u8 * buf,int len)168 int hdc3020_read_bytes(struct hdc3020_data *data, u16 reg, u8 *buf, int len)
169 {
170 	u8 reg_buf[2];
171 	int ret, cnt;
172 	struct i2c_client *client = data->client;
173 	struct i2c_msg msg[2] = {
174 		[0] = {
175 			.addr = client->addr,
176 			.flags = 0,
177 			.buf = reg_buf,
178 			.len = 2,
179 		},
180 		[1] = {
181 			.addr = client->addr,
182 			.flags = I2C_M_RD,
183 			.buf = buf,
184 			.len = len,
185 		},
186 	};
187 
188 	put_unaligned_be16(reg, reg_buf);
189 	/*
190 	 * During the measurement process, HDC3020 will not return data.
191 	 * So wait for a while and try again
192 	 */
193 	for (cnt = 0; cnt < HDC3020_READ_RETRY_TIMES; cnt++) {
194 		ret = i2c_transfer(client->adapter, msg, 2);
195 		if (ret == 2)
196 			return 0;
197 
198 		mdelay(HDC3020_BUSY_DELAY_MS);
199 	}
200 	dev_err(&client->dev, "Could not read sensor data\n");
201 
202 	return -ETIMEDOUT;
203 }
204 
hdc3020_read_be16(struct hdc3020_data * data,u16 reg)205 static int hdc3020_read_be16(struct hdc3020_data *data, u16 reg)
206 {
207 	u8 crc, buf[3];
208 	int ret;
209 
210 	ret = hdc3020_read_bytes(data, reg, buf, 3);
211 	if (ret < 0)
212 		return ret;
213 
214 	crc = crc8(hdc3020_crc8_table, buf, 2, CRC8_INIT_VALUE);
215 	if (crc != buf[2])
216 		return -EINVAL;
217 
218 	return get_unaligned_be16(buf);
219 }
220 
hdc3020_exec_cmd(struct hdc3020_data * data,u16 reg)221 static int hdc3020_exec_cmd(struct hdc3020_data *data, u16 reg)
222 {
223 	u8 reg_buf[2];
224 
225 	put_unaligned_be16(reg, reg_buf);
226 	return hdc3020_write_bytes(data, reg_buf, 2);
227 }
228 
hdc3020_read_measurement(struct hdc3020_data * data,enum iio_chan_type type,int * val)229 static int hdc3020_read_measurement(struct hdc3020_data *data,
230 				    enum iio_chan_type type, int *val)
231 {
232 	u8 crc, buf[6];
233 	int ret;
234 
235 	ret = hdc3020_read_bytes(data, HDC3020_R_T_RH_AUTO, buf, 6);
236 	if (ret < 0)
237 		return ret;
238 
239 	/* CRC check of the temperature measurement */
240 	crc = crc8(hdc3020_crc8_table, buf, 2, CRC8_INIT_VALUE);
241 	if (crc != buf[2])
242 		return -EINVAL;
243 
244 	/* CRC check of the relative humidity measurement */
245 	crc = crc8(hdc3020_crc8_table, buf + 3, 2, CRC8_INIT_VALUE);
246 	if (crc != buf[5])
247 		return -EINVAL;
248 
249 	if (type == IIO_TEMP)
250 		*val = get_unaligned_be16(buf);
251 	else if (type == IIO_HUMIDITYRELATIVE)
252 		*val = get_unaligned_be16(&buf[3]);
253 	else
254 		return -EINVAL;
255 
256 	return 0;
257 }
258 
hdc3020_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)259 static int hdc3020_read_raw(struct iio_dev *indio_dev,
260 			    struct iio_chan_spec const *chan, int *val,
261 			    int *val2, long mask)
262 {
263 	struct hdc3020_data *data = iio_priv(indio_dev);
264 	int ret;
265 
266 	if (chan->type != IIO_TEMP && chan->type != IIO_HUMIDITYRELATIVE)
267 		return -EINVAL;
268 
269 	switch (mask) {
270 	case IIO_CHAN_INFO_RAW: {
271 		guard(mutex)(&data->lock);
272 		ret = hdc3020_read_measurement(data, chan->type, val);
273 		if (ret < 0)
274 			return ret;
275 
276 		return IIO_VAL_INT;
277 	}
278 	case IIO_CHAN_INFO_PEAK: {
279 		guard(mutex)(&data->lock);
280 		if (chan->type == IIO_TEMP)
281 			ret = hdc3020_read_be16(data, HDC3020_R_T_HIGH_AUTO);
282 		else
283 			ret = hdc3020_read_be16(data, HDC3020_R_RH_HIGH_AUTO);
284 
285 		if (ret < 0)
286 			return ret;
287 
288 		*val = ret;
289 		return IIO_VAL_INT;
290 	}
291 	case IIO_CHAN_INFO_TROUGH: {
292 		guard(mutex)(&data->lock);
293 		if (chan->type == IIO_TEMP)
294 			ret = hdc3020_read_be16(data, HDC3020_R_T_LOW_AUTO);
295 		else
296 			ret = hdc3020_read_be16(data, HDC3020_R_RH_LOW_AUTO);
297 
298 		if (ret < 0)
299 			return ret;
300 
301 		*val = ret;
302 		return IIO_VAL_INT;
303 	}
304 	case IIO_CHAN_INFO_SCALE:
305 		*val2 = 65536;
306 		if (chan->type == IIO_TEMP)
307 			*val = 175 * MILLI;
308 		else
309 			*val = 100 * MILLI;
310 		return IIO_VAL_FRACTIONAL;
311 
312 	case IIO_CHAN_INFO_OFFSET:
313 		if (chan->type != IIO_TEMP)
314 			return -EINVAL;
315 
316 		*val = -16852;
317 		return IIO_VAL_INT;
318 
319 	default:
320 		return -EINVAL;
321 	}
322 }
323 
hdc3020_read_available(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)324 static int hdc3020_read_available(struct iio_dev *indio_dev,
325 				  struct iio_chan_spec const *chan,
326 				  const int **vals,
327 				  int *type, int *length, long mask)
328 {
329 	if (mask != IIO_CHAN_INFO_RAW || chan->type != IIO_CURRENT)
330 		return -EINVAL;
331 
332 	*vals = hdc3020_heater_vals;
333 	*type = IIO_VAL_INT;
334 
335 	return IIO_AVAIL_RANGE;
336 }
337 
hdc3020_update_heater(struct hdc3020_data * data,int val)338 static int hdc3020_update_heater(struct hdc3020_data *data, int val)
339 {
340 	u8 buf[5];
341 	int ret;
342 
343 	if (val < hdc3020_heater_vals[0] || val > hdc3020_heater_vals[2])
344 		return -EINVAL;
345 
346 	if (!val)
347 		hdc3020_exec_cmd(data, HDC3020_HEATER_DISABLE);
348 
349 	put_unaligned_be16(HDC3020_HEATER_CONFIG, buf);
350 	put_unaligned_be16(val & GENMASK(13, 0), &buf[2]);
351 	buf[4] = crc8(hdc3020_crc8_table, buf + 2, 2, CRC8_INIT_VALUE);
352 	ret = hdc3020_write_bytes(data, buf, 5);
353 	if (ret < 0)
354 		return ret;
355 
356 	return hdc3020_exec_cmd(data, HDC3020_HEATER_ENABLE);
357 }
358 
hdc3020_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)359 static int hdc3020_write_raw(struct iio_dev *indio_dev,
360 			     struct iio_chan_spec const *chan,
361 			     int val, int val2, long mask)
362 {
363 	struct hdc3020_data *data = iio_priv(indio_dev);
364 
365 	switch (mask) {
366 	case IIO_CHAN_INFO_RAW:
367 		if (chan->type != IIO_CURRENT)
368 			return -EINVAL;
369 
370 		guard(mutex)(&data->lock);
371 		return hdc3020_update_heater(data, val);
372 	}
373 
374 	return -EINVAL;
375 }
376 
hdc3020_thresh_get_temp(u16 thresh)377 static int hdc3020_thresh_get_temp(u16 thresh)
378 {
379 	int temp;
380 
381 	/*
382 	 * Get the temperature threshold from 9 LSBs, shift them to get the
383 	 * truncated temperature threshold representation and calculate the
384 	 * threshold according to the explicit formula in the datasheet:
385 	 * T(C) = -45 + (175 * temp) / 65535.
386 	 * Additionally scale by HDC3020_THRESH_FRACTION to avoid precision loss
387 	 * when calculating threshold and hysteresis values. Result is degree
388 	 * celsius scaled by HDC3020_THRESH_FRACTION.
389 	 */
390 	temp = FIELD_GET(HDC3020_THRESH_TEMP_MASK, thresh) <<
391 	       HDC3020_THRESH_TEMP_TRUNC_SHIFT;
392 
393 	return -2949075 / 5 + (175 / 5 * temp);
394 }
395 
hdc3020_thresh_get_hum(u16 thresh)396 static int hdc3020_thresh_get_hum(u16 thresh)
397 {
398 	int hum;
399 
400 	/*
401 	 * Get the humidity threshold from 7 MSBs, shift them to get the
402 	 * truncated humidity threshold representation and calculate the
403 	 * threshold according to the explicit formula in the datasheet:
404 	 * RH(%) = 100 * hum / 65535.
405 	 * Additionally scale by HDC3020_THRESH_FRACTION to avoid precision loss
406 	 * when calculating threshold and hysteresis values. Result is percent
407 	 * scaled by HDC3020_THRESH_FRACTION.
408 	 */
409 	hum = FIELD_GET(HDC3020_THRESH_HUM_MASK, thresh) <<
410 	      HDC3020_THRESH_HUM_TRUNC_SHIFT;
411 
412 	return hum * 100 / 5;
413 }
414 
hdc3020_thresh_set_temp(int s_temp,u16 curr_thresh)415 static u16 hdc3020_thresh_set_temp(int s_temp, u16 curr_thresh)
416 {
417 	u64 temp;
418 	u16 thresh;
419 
420 	/*
421 	 * Calculate temperature threshold, shift it down to get the
422 	 * truncated threshold representation in the 9LSBs while keeping
423 	 * the current humidity threshold in the 7 MSBs.
424 	 */
425 	temp = (u64)(s_temp + 45000000) * 65535ULL;
426 	temp = div_u64(temp, 1000000 * 175) >> HDC3020_THRESH_TEMP_TRUNC_SHIFT;
427 	thresh = FIELD_PREP(HDC3020_THRESH_TEMP_MASK, temp);
428 	thresh |= (FIELD_GET(HDC3020_THRESH_HUM_MASK, curr_thresh) <<
429 		  HDC3020_THRESH_HUM_TRUNC_SHIFT);
430 
431 	return thresh;
432 }
433 
hdc3020_thresh_set_hum(int s_hum,u16 curr_thresh)434 static u16 hdc3020_thresh_set_hum(int s_hum, u16 curr_thresh)
435 {
436 	u64 hum;
437 	u16 thresh;
438 
439 	/*
440 	 * Calculate humidity threshold, shift it down and up to get the
441 	 * truncated threshold representation in the 7MSBs while keeping
442 	 * the current temperature threshold in the 9 LSBs.
443 	 */
444 	hum = (u64)(s_hum) * 65535ULL;
445 	hum = div_u64(hum, 1000000 * 100) >> HDC3020_THRESH_HUM_TRUNC_SHIFT;
446 	thresh = FIELD_PREP(HDC3020_THRESH_HUM_MASK, hum);
447 	thresh |= FIELD_GET(HDC3020_THRESH_TEMP_MASK, curr_thresh);
448 
449 	return thresh;
450 }
451 
452 static
hdc3020_thresh_clr(s64 s_thresh,s64 s_hyst,enum iio_event_direction dir)453 int hdc3020_thresh_clr(s64 s_thresh, s64 s_hyst, enum iio_event_direction dir)
454 {
455 	s64 s_clr;
456 
457 	/*
458 	 * Include directions when calculation the clear value,
459 	 * since hysteresis is unsigned by definition and the
460 	 * clear value is an absolute value which is signed.
461 	 */
462 	if (dir == IIO_EV_DIR_RISING)
463 		s_clr = s_thresh - s_hyst;
464 	else
465 		s_clr = s_thresh + s_hyst;
466 
467 	/* Divide by HDC3020_THRESH_FRACTION to get units of micro */
468 	return div_s64(s_clr, HDC3020_THRESH_FRACTION);
469 }
470 
_hdc3020_write_thresh(struct hdc3020_data * data,u16 reg,u16 val)471 static int _hdc3020_write_thresh(struct hdc3020_data *data, u16 reg, u16 val)
472 {
473 	u8 buf[5];
474 
475 	put_unaligned_be16(reg, buf);
476 	put_unaligned_be16(val, buf + 2);
477 	buf[4] = crc8(hdc3020_crc8_table, buf + 2, 2, CRC8_INIT_VALUE);
478 
479 	return hdc3020_write_bytes(data, buf, 5);
480 }
481 
hdc3020_write_thresh(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,enum iio_event_info info,int val,int val2)482 static int hdc3020_write_thresh(struct iio_dev *indio_dev,
483 				const struct iio_chan_spec *chan,
484 				enum iio_event_type type,
485 				enum iio_event_direction dir,
486 				enum iio_event_info info,
487 				int val, int val2)
488 {
489 	struct hdc3020_data *data = iio_priv(indio_dev);
490 	u16 reg, reg_val, reg_thresh_rd, reg_clr_rd, reg_thresh_wr, reg_clr_wr;
491 	s64 s_thresh, s_hyst, s_clr;
492 	int s_val, thresh, clr, ret;
493 
494 	/* Select threshold registers */
495 	if (dir == IIO_EV_DIR_RISING) {
496 		reg_thresh_rd = HDC3020_R_T_RH_THRESH_HIGH;
497 		reg_thresh_wr = HDC3020_S_T_RH_THRESH_HIGH;
498 		reg_clr_rd = HDC3020_R_T_RH_THRESH_HIGH_CLR;
499 		reg_clr_wr = HDC3020_S_T_RH_THRESH_HIGH_CLR;
500 	} else {
501 		reg_thresh_rd = HDC3020_R_T_RH_THRESH_LOW;
502 		reg_thresh_wr = HDC3020_S_T_RH_THRESH_LOW;
503 		reg_clr_rd = HDC3020_R_T_RH_THRESH_LOW_CLR;
504 		reg_clr_wr = HDC3020_S_T_RH_THRESH_LOW_CLR;
505 	}
506 
507 	guard(mutex)(&data->lock);
508 	ret = hdc3020_read_be16(data, reg_thresh_rd);
509 	if (ret < 0)
510 		return ret;
511 
512 	thresh = ret;
513 	ret = hdc3020_read_be16(data, reg_clr_rd);
514 	if (ret < 0)
515 		return ret;
516 
517 	clr = ret;
518 	/* Scale value to include decimal part into calculations */
519 	s_val = (val < 0) ? (val * 1000 - val2) : (val * 1000 + val2);
520 	switch (chan->type) {
521 	case IIO_TEMP:
522 		switch (info) {
523 		case IIO_EV_INFO_VALUE:
524 			s_val = max(s_val, HDC3020_MIN_TEMP_MICRO);
525 			s_val = min(s_val, HDC3020_MAX_TEMP_MICRO);
526 			reg = reg_thresh_wr;
527 			reg_val = hdc3020_thresh_set_temp(s_val, thresh);
528 			ret = _hdc3020_write_thresh(data, reg, reg_val);
529 			if (ret < 0)
530 				return ret;
531 
532 			/* Calculate old hysteresis */
533 			s_thresh = (s64)hdc3020_thresh_get_temp(thresh) * 1000000;
534 			s_clr = (s64)hdc3020_thresh_get_temp(clr) * 1000000;
535 			s_hyst = div_s64(abs(s_thresh - s_clr),
536 					 HDC3020_THRESH_FRACTION);
537 			/* Set new threshold */
538 			thresh = reg_val;
539 			/* Set old hysteresis */
540 			s_val = s_hyst;
541 			fallthrough;
542 		case IIO_EV_INFO_HYSTERESIS:
543 			/*
544 			 * Function hdc3020_thresh_get_temp returns temperature
545 			 * in degree celsius scaled by HDC3020_THRESH_FRACTION.
546 			 * Scale by 1000000 to be able to subtract scaled
547 			 * hysteresis value.
548 			 */
549 			s_thresh = (s64)hdc3020_thresh_get_temp(thresh) * 1000000;
550 			/*
551 			 * Units of s_val are in micro degree celsius, scale by
552 			 * HDC3020_THRESH_FRACTION to get same units as s_thresh.
553 			 */
554 			s_val = min(abs(s_val), HDC3020_MAX_TEMP_HYST_MICRO);
555 			s_hyst = (s64)s_val * HDC3020_THRESH_FRACTION;
556 			s_clr = hdc3020_thresh_clr(s_thresh, s_hyst, dir);
557 			s_clr = max(s_clr, HDC3020_MIN_TEMP_MICRO);
558 			s_clr = min(s_clr, HDC3020_MAX_TEMP_MICRO);
559 			reg = reg_clr_wr;
560 			reg_val = hdc3020_thresh_set_temp(s_clr, clr);
561 			break;
562 		default:
563 			return -EOPNOTSUPP;
564 		}
565 		break;
566 	case IIO_HUMIDITYRELATIVE:
567 		s_val = (s_val < 0) ? 0 : min(s_val, HDC3020_MAX_HUM_MICRO);
568 		switch (info) {
569 		case IIO_EV_INFO_VALUE:
570 			reg = reg_thresh_wr;
571 			reg_val = hdc3020_thresh_set_hum(s_val, thresh);
572 			ret = _hdc3020_write_thresh(data, reg, reg_val);
573 			if (ret < 0)
574 				return ret;
575 
576 			/* Calculate old hysteresis */
577 			s_thresh = (s64)hdc3020_thresh_get_hum(thresh) * 1000000;
578 			s_clr = (s64)hdc3020_thresh_get_hum(clr) * 1000000;
579 			s_hyst = div_s64(abs(s_thresh - s_clr),
580 					 HDC3020_THRESH_FRACTION);
581 			/* Set new threshold */
582 			thresh = reg_val;
583 			/* Try to set old hysteresis */
584 			s_val = min(abs(s_hyst), HDC3020_MAX_HUM_MICRO);
585 			fallthrough;
586 		case IIO_EV_INFO_HYSTERESIS:
587 			/*
588 			 * Function hdc3020_thresh_get_hum returns relative
589 			 * humidity in percent scaled by HDC3020_THRESH_FRACTION.
590 			 * Scale by 1000000 to be able to subtract scaled
591 			 * hysteresis value.
592 			 */
593 			s_thresh = (s64)hdc3020_thresh_get_hum(thresh) * 1000000;
594 			/*
595 			 * Units of s_val are in micro percent, scale by
596 			 * HDC3020_THRESH_FRACTION to get same units as s_thresh.
597 			 */
598 			s_hyst = (s64)s_val * HDC3020_THRESH_FRACTION;
599 			s_clr = hdc3020_thresh_clr(s_thresh, s_hyst, dir);
600 			s_clr = max(s_clr, 0);
601 			s_clr = min(s_clr, HDC3020_MAX_HUM_MICRO);
602 			reg = reg_clr_wr;
603 			reg_val = hdc3020_thresh_set_hum(s_clr, clr);
604 			break;
605 		default:
606 			return -EOPNOTSUPP;
607 		}
608 		break;
609 	default:
610 		return -EOPNOTSUPP;
611 	}
612 
613 	return _hdc3020_write_thresh(data, reg, reg_val);
614 }
615 
hdc3020_read_thresh(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,enum iio_event_info info,int * val,int * val2)616 static int hdc3020_read_thresh(struct iio_dev *indio_dev,
617 			       const struct iio_chan_spec *chan,
618 			       enum iio_event_type type,
619 			       enum iio_event_direction dir,
620 			       enum iio_event_info info,
621 			       int *val, int *val2)
622 {
623 	struct hdc3020_data *data = iio_priv(indio_dev);
624 	u16 reg_thresh, reg_clr;
625 	int thresh, clr, ret;
626 
627 	/* Select threshold registers */
628 	if (dir == IIO_EV_DIR_RISING) {
629 		reg_thresh = HDC3020_R_T_RH_THRESH_HIGH;
630 		reg_clr = HDC3020_R_T_RH_THRESH_HIGH_CLR;
631 	} else {
632 		reg_thresh = HDC3020_R_T_RH_THRESH_LOW;
633 		reg_clr = HDC3020_R_T_RH_THRESH_LOW_CLR;
634 	}
635 
636 	guard(mutex)(&data->lock);
637 	ret = hdc3020_read_be16(data, reg_thresh);
638 	if (ret < 0)
639 		return ret;
640 
641 	switch (chan->type) {
642 	case IIO_TEMP:
643 		thresh = hdc3020_thresh_get_temp(ret);
644 		switch (info) {
645 		case IIO_EV_INFO_VALUE:
646 			*val = thresh * MILLI;
647 			break;
648 		case IIO_EV_INFO_HYSTERESIS:
649 			ret = hdc3020_read_be16(data, reg_clr);
650 			if (ret < 0)
651 				return ret;
652 
653 			clr = hdc3020_thresh_get_temp(ret);
654 			*val = abs(thresh - clr) * MILLI;
655 			break;
656 		default:
657 			return -EOPNOTSUPP;
658 		}
659 		*val2 = HDC3020_THRESH_FRACTION;
660 		return IIO_VAL_FRACTIONAL;
661 	case IIO_HUMIDITYRELATIVE:
662 		thresh = hdc3020_thresh_get_hum(ret);
663 		switch (info) {
664 		case IIO_EV_INFO_VALUE:
665 			*val = thresh * MILLI;
666 			break;
667 		case IIO_EV_INFO_HYSTERESIS:
668 			ret = hdc3020_read_be16(data, reg_clr);
669 			if (ret < 0)
670 				return ret;
671 
672 			clr = hdc3020_thresh_get_hum(ret);
673 			*val = abs(thresh - clr) * MILLI;
674 			break;
675 		default:
676 			return -EOPNOTSUPP;
677 		}
678 		*val2 = HDC3020_THRESH_FRACTION;
679 		return IIO_VAL_FRACTIONAL;
680 	default:
681 		return -EOPNOTSUPP;
682 	}
683 }
684 
hdc3020_interrupt_handler(int irq,void * private)685 static irqreturn_t hdc3020_interrupt_handler(int irq, void *private)
686 {
687 	struct iio_dev *indio_dev = private;
688 	struct hdc3020_data *data;
689 	s64 time;
690 	int ret;
691 
692 	data = iio_priv(indio_dev);
693 	ret = hdc3020_read_be16(data, HDC3020_R_STATUS);
694 	if (ret < 0)
695 		return IRQ_HANDLED;
696 
697 	if (!(ret & (HDC3020_STATUS_T_HIGH_ALERT | HDC3020_STATUS_T_LOW_ALERT |
698 		HDC3020_STATUS_RH_HIGH_ALERT | HDC3020_STATUS_RH_LOW_ALERT)))
699 		return IRQ_NONE;
700 
701 	time = iio_get_time_ns(indio_dev);
702 	if (ret & HDC3020_STATUS_T_HIGH_ALERT)
703 		iio_push_event(indio_dev,
704 			       IIO_MOD_EVENT_CODE(IIO_TEMP, 0,
705 						  IIO_NO_MOD,
706 						  IIO_EV_TYPE_THRESH,
707 						  IIO_EV_DIR_RISING),
708 						  time);
709 
710 	if (ret & HDC3020_STATUS_T_LOW_ALERT)
711 		iio_push_event(indio_dev,
712 			       IIO_MOD_EVENT_CODE(IIO_TEMP, 0,
713 						  IIO_NO_MOD,
714 						  IIO_EV_TYPE_THRESH,
715 						  IIO_EV_DIR_FALLING),
716 						  time);
717 
718 	if (ret & HDC3020_STATUS_RH_HIGH_ALERT)
719 		iio_push_event(indio_dev,
720 			       IIO_MOD_EVENT_CODE(IIO_HUMIDITYRELATIVE, 0,
721 						  IIO_NO_MOD,
722 						  IIO_EV_TYPE_THRESH,
723 						  IIO_EV_DIR_RISING),
724 						  time);
725 
726 	if (ret & HDC3020_STATUS_RH_LOW_ALERT)
727 		iio_push_event(indio_dev,
728 			       IIO_MOD_EVENT_CODE(IIO_HUMIDITYRELATIVE, 0,
729 						  IIO_NO_MOD,
730 						  IIO_EV_TYPE_THRESH,
731 						  IIO_EV_DIR_FALLING),
732 						  time);
733 
734 	return IRQ_HANDLED;
735 }
736 
737 static const struct iio_info hdc3020_info = {
738 	.read_raw = hdc3020_read_raw,
739 	.write_raw = hdc3020_write_raw,
740 	.read_avail = hdc3020_read_available,
741 	.read_event_value = hdc3020_read_thresh,
742 	.write_event_value = hdc3020_write_thresh,
743 };
744 
hdc3020_power_off(struct hdc3020_data * data)745 static int hdc3020_power_off(struct hdc3020_data *data)
746 {
747 	hdc3020_exec_cmd(data, HDC3020_EXIT_AUTO);
748 
749 	if (data->reset_gpio)
750 		gpiod_set_value_cansleep(data->reset_gpio, 1);
751 
752 	return regulator_disable(data->vdd_supply);
753 }
754 
hdc3020_power_on(struct hdc3020_data * data)755 static int hdc3020_power_on(struct hdc3020_data *data)
756 {
757 	int ret;
758 
759 	ret = regulator_enable(data->vdd_supply);
760 	if (ret)
761 		return ret;
762 
763 	fsleep(5000);
764 
765 	if (data->reset_gpio) {
766 		gpiod_set_value_cansleep(data->reset_gpio, 0);
767 		fsleep(3000);
768 	}
769 
770 	if (data->client->irq) {
771 		/*
772 		 * The alert output is activated by default upon power up,
773 		 * hardware reset, and soft reset. Clear the status register.
774 		 */
775 		ret = hdc3020_exec_cmd(data, HDC3020_S_STATUS);
776 		if (ret) {
777 			hdc3020_power_off(data);
778 			return ret;
779 		}
780 	}
781 
782 	ret = hdc3020_exec_cmd(data, HDC3020_S_AUTO_10HZ_MOD0);
783 	if (ret)
784 		hdc3020_power_off(data);
785 
786 	return ret;
787 }
788 
hdc3020_exit(void * data)789 static void hdc3020_exit(void *data)
790 {
791 	hdc3020_power_off(data);
792 }
793 
hdc3020_probe(struct i2c_client * client)794 static int hdc3020_probe(struct i2c_client *client)
795 {
796 	struct iio_dev *indio_dev;
797 	struct hdc3020_data *data;
798 	int ret;
799 
800 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
801 		return -EOPNOTSUPP;
802 
803 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
804 	if (!indio_dev)
805 		return -ENOMEM;
806 
807 	dev_set_drvdata(&client->dev, indio_dev);
808 
809 	data = iio_priv(indio_dev);
810 	data->client = client;
811 	mutex_init(&data->lock);
812 
813 	crc8_populate_msb(hdc3020_crc8_table, HDC3020_CRC8_POLYNOMIAL);
814 
815 	indio_dev->name = "hdc3020";
816 	indio_dev->modes = INDIO_DIRECT_MODE;
817 	indio_dev->info = &hdc3020_info;
818 	indio_dev->channels = hdc3020_channels;
819 	indio_dev->num_channels = ARRAY_SIZE(hdc3020_channels);
820 
821 	data->vdd_supply = devm_regulator_get(&client->dev, "vdd");
822 	if (IS_ERR(data->vdd_supply))
823 		return dev_err_probe(&client->dev, PTR_ERR(data->vdd_supply),
824 				     "Unable to get VDD regulator\n");
825 
826 	data->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset",
827 						   GPIOD_OUT_HIGH);
828 	if (IS_ERR(data->reset_gpio))
829 		return dev_err_probe(&client->dev, PTR_ERR(data->reset_gpio),
830 				     "Cannot get reset GPIO\n");
831 
832 	ret = hdc3020_power_on(data);
833 	if (ret)
834 		return dev_err_probe(&client->dev, ret, "Power on failed\n");
835 
836 	ret = devm_add_action_or_reset(&data->client->dev, hdc3020_exit, data);
837 	if (ret)
838 		return ret;
839 
840 	if (client->irq) {
841 		ret = devm_request_threaded_irq(&client->dev, client->irq,
842 						NULL, hdc3020_interrupt_handler,
843 						IRQF_ONESHOT, "hdc3020",
844 						indio_dev);
845 		if (ret)
846 			return dev_err_probe(&client->dev, ret,
847 					     "Failed to request IRQ\n");
848 	}
849 
850 	ret = devm_iio_device_register(&data->client->dev, indio_dev);
851 	if (ret)
852 		return dev_err_probe(&client->dev, ret, "Failed to add device");
853 
854 	return 0;
855 }
856 
hdc3020_suspend(struct device * dev)857 static int hdc3020_suspend(struct device *dev)
858 {
859 	struct iio_dev *iio_dev = dev_get_drvdata(dev);
860 	struct hdc3020_data *data = iio_priv(iio_dev);
861 
862 	return hdc3020_power_off(data);
863 }
864 
hdc3020_resume(struct device * dev)865 static int hdc3020_resume(struct device *dev)
866 {
867 	struct iio_dev *iio_dev = dev_get_drvdata(dev);
868 	struct hdc3020_data *data = iio_priv(iio_dev);
869 
870 	return hdc3020_power_on(data);
871 }
872 
873 static DEFINE_SIMPLE_DEV_PM_OPS(hdc3020_pm_ops, hdc3020_suspend, hdc3020_resume);
874 
875 static const struct i2c_device_id hdc3020_id[] = {
876 	{ "hdc3020" },
877 	{ "hdc3021" },
878 	{ "hdc3022" },
879 	{ }
880 };
881 MODULE_DEVICE_TABLE(i2c, hdc3020_id);
882 
883 static const struct of_device_id hdc3020_dt_ids[] = {
884 	{ .compatible = "ti,hdc3020" },
885 	{ .compatible = "ti,hdc3021" },
886 	{ .compatible = "ti,hdc3022" },
887 	{ }
888 };
889 MODULE_DEVICE_TABLE(of, hdc3020_dt_ids);
890 
891 static struct i2c_driver hdc3020_driver = {
892 	.driver = {
893 		.name = "hdc3020",
894 		.pm = pm_sleep_ptr(&hdc3020_pm_ops),
895 		.of_match_table = hdc3020_dt_ids,
896 	},
897 	.probe = hdc3020_probe,
898 	.id_table = hdc3020_id,
899 };
900 module_i2c_driver(hdc3020_driver);
901 
902 MODULE_AUTHOR("Javier Carrasco <javier.carrasco.cruz@gmail.com>");
903 MODULE_AUTHOR("Li peiyu <579lpy@gmail.com>");
904 MODULE_DESCRIPTION("TI HDC3020 humidity and temperature sensor driver");
905 MODULE_LICENSE("GPL");
906