xref: /linux/drivers/iio/adc/rohm-bd79124.c (revision d2c9a99135da931377240942d44f3dea104cedb8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * ROHM ADC driver for BD79124 ADC/GPO device
4  * https://fscdn.rohm.com/en/products/databook/datasheet/ic/data_converter/dac/bd79124muf-c-e.pdf
5  *
6  * Copyright (c) 2025, ROHM Semiconductor.
7  */
8 
9 #include <linux/array_size.h>
10 #include <linux/bitfield.h>
11 #include <linux/bitmap.h>
12 #include <linux/bits.h>
13 #include <linux/device.h>
14 #include <linux/delay.h>
15 #include <linux/devm-helpers.h>
16 #include <linux/err.h>
17 #include <linux/gpio/driver.h>
18 #include <linux/i2c.h>
19 #include <linux/interrupt.h>
20 #include <linux/irqreturn.h>
21 #include <linux/module.h>
22 #include <linux/regmap.h>
23 #include <linux/types.h>
24 
25 #include <asm/byteorder.h>
26 
27 #include <linux/iio/events.h>
28 #include <linux/iio/iio.h>
29 #include <linux/iio/adc-helpers.h>
30 
31 #define BD79124_I2C_MULTI_READ		0x30
32 #define BD79124_I2C_MULTI_WRITE		0x28
33 #define BD79124_REG_MAX			0xaf
34 
35 #define BD79124_REG_SYSTEM_STATUS	0x00
36 #define BD79124_REG_GEN_CFG		0x01
37 #define BD79124_REG_OPMODE_CFG		0x04
38 #define BD79124_REG_PINCFG		0x05
39 #define BD79124_REG_GPO_VAL		0x0B
40 #define BD79124_REG_SEQ_CFG		0x10
41 #define BD79124_REG_MANUAL_CHANNELS	0x11
42 #define BD79124_REG_AUTO_CHANNELS	0x12
43 #define BD79124_REG_ALERT_CH_SEL	0x14
44 #define BD79124_REG_EVENT_FLAG		0x18
45 #define BD79124_REG_EVENT_FLAG_HI	0x1a
46 #define BD79124_REG_EVENT_FLAG_LO	0x1c
47 #define BD79124_REG_HYSTERESIS_CH0	0x20
48 #define BD79124_REG_EVENTCOUNT_CH0	0x22
49 #define BD79124_REG_RECENT_CH0_LSB	0xa0
50 #define BD79124_REG_RECENT_CH7_MSB	0xaf
51 
52 #define BD79124_ADC_BITS 12
53 
54 /* Masks for the BD79124_REG_OPMODE_CFG */
55 #define BD79124_MSK_CONV_MODE GENMASK(6, 5)
56 #define BD79124_CONV_MODE_MANSEQ 0
57 #define BD79124_CONV_MODE_AUTO 1
58 #define BD79124_MSK_AUTO_INTERVAL GENMASK(1, 0)
59 #define BD79124_INTERVAL_750_US 0
60 
61 /* Masks for the BD79124_REG_GEN_CFG */
62 #define BD79124_MSK_DWC_EN BIT(4)
63 #define BD79124_MSK_STATS_EN BIT(5)
64 
65 /* Masks for the BD79124_REG_SEQ_CFG */
66 #define BD79124_MSK_SEQ_START BIT(4)
67 #define BD79124_MSK_SEQ_MODE GENMASK(1, 0)
68 #define BD79124_MSK_SEQ_MANUAL 0
69 #define BD79124_MSK_SEQ_SEQ 1
70 
71 #define BD79124_MSK_HYSTERESIS GENMASK(3, 0)
72 #define BD79124_LOW_LIMIT_MIN 0
73 #define BD79124_HIGH_LIMIT_MAX GENMASK(11, 0)
74 
75 /*
76  * The high limit, low limit and last measurement result are each stored in
77  * 2 consecutive registers. 4 bits are in the high bits of the first register
78  * and 8 bits in the next register.
79  *
80  * These macros return the address of the first reg for the given channel.
81  */
82 #define BD79124_GET_HIGH_LIMIT_REG(ch) (BD79124_REG_HYSTERESIS_CH0 + (ch) * 4)
83 #define BD79124_GET_LOW_LIMIT_REG(ch) (BD79124_REG_EVENTCOUNT_CH0 + (ch) * 4)
84 #define BD79124_GET_LIMIT_REG(ch, dir) ((dir) == IIO_EV_DIR_RISING ?		\
85 		BD79124_GET_HIGH_LIMIT_REG(ch) : BD79124_GET_LOW_LIMIT_REG(ch))
86 #define BD79124_GET_RECENT_RES_REG(ch) (BD79124_REG_RECENT_CH0_LSB + (ch) * 2)
87 
88 /*
89  * The hysteresis for a channel is stored in the same register where the
90  * 4 bits of high limit reside.
91  */
92 #define BD79124_GET_HYSTERESIS_REG(ch) BD79124_GET_HIGH_LIMIT_REG(ch)
93 
94 #define BD79124_MAX_NUM_CHANNELS 8
95 
96 struct bd79124_data {
97 	s64 timestamp;
98 	struct regmap *map;
99 	struct device *dev;
100 	int vmax;
101 	/*
102 	 * Keep measurement status so read_raw() knows if the measurement needs
103 	 * to be started.
104 	 */
105 	int alarm_monitored[BD79124_MAX_NUM_CHANNELS];
106 	/*
107 	 * The BD79124 does not allow disabling/enabling limit separately for
108 	 * one direction only. Hence, we do the disabling by changing the limit
109 	 * to maximum/minimum measurable value. This means we need to cache
110 	 * the limit in order to maintain it over the time limit is disabled.
111 	 */
112 	u16 alarm_r_limit[BD79124_MAX_NUM_CHANNELS];
113 	u16 alarm_f_limit[BD79124_MAX_NUM_CHANNELS];
114 	/* Bitmask of disabled events (for rate limiting) for each channel. */
115 	int alarm_suppressed[BD79124_MAX_NUM_CHANNELS];
116 	/*
117 	 * The BD79124 is configured to run the measurements in the background.
118 	 * This is done for the event monitoring as well as for the read_raw().
119 	 * Protect the measurement starting/stopping using a mutex.
120 	 */
121 	struct mutex mutex;
122 	struct delayed_work alm_enable_work;
123 	struct gpio_chip gc;
124 	u8 gpio_valid_mask;
125 };
126 
127 static const struct regmap_range bd79124_ro_ranges[] = {
128 	regmap_reg_range(BD79124_REG_EVENT_FLAG, BD79124_REG_EVENT_FLAG),
129 	regmap_reg_range(BD79124_REG_RECENT_CH0_LSB, BD79124_REG_RECENT_CH7_MSB),
130 };
131 
132 static const struct regmap_access_table bd79124_ro_regs = {
133 	.no_ranges	= &bd79124_ro_ranges[0],
134 	.n_no_ranges	= ARRAY_SIZE(bd79124_ro_ranges),
135 };
136 
137 static const struct regmap_range bd79124_volatile_ranges[] = {
138 	regmap_reg_range(BD79124_REG_RECENT_CH0_LSB, BD79124_REG_RECENT_CH7_MSB),
139 	regmap_reg_range(BD79124_REG_EVENT_FLAG, BD79124_REG_EVENT_FLAG),
140 	regmap_reg_range(BD79124_REG_EVENT_FLAG_HI, BD79124_REG_EVENT_FLAG_HI),
141 	regmap_reg_range(BD79124_REG_EVENT_FLAG_LO, BD79124_REG_EVENT_FLAG_LO),
142 	regmap_reg_range(BD79124_REG_SYSTEM_STATUS, BD79124_REG_SYSTEM_STATUS),
143 };
144 
145 static const struct regmap_access_table bd79124_volatile_regs = {
146 	.yes_ranges	= &bd79124_volatile_ranges[0],
147 	.n_yes_ranges	= ARRAY_SIZE(bd79124_volatile_ranges),
148 };
149 
150 static const struct regmap_range bd79124_precious_ranges[] = {
151 	regmap_reg_range(BD79124_REG_EVENT_FLAG_HI, BD79124_REG_EVENT_FLAG_HI),
152 	regmap_reg_range(BD79124_REG_EVENT_FLAG_LO, BD79124_REG_EVENT_FLAG_LO),
153 };
154 
155 static const struct regmap_access_table bd79124_precious_regs = {
156 	.yes_ranges	= &bd79124_precious_ranges[0],
157 	.n_yes_ranges	= ARRAY_SIZE(bd79124_precious_ranges),
158 };
159 
160 static const struct regmap_config bd79124_regmap = {
161 	.reg_bits		= 16,
162 	.val_bits		= 8,
163 	.read_flag_mask		= BD79124_I2C_MULTI_READ,
164 	.write_flag_mask	= BD79124_I2C_MULTI_WRITE,
165 	.max_register		= BD79124_REG_MAX,
166 	.cache_type		= REGCACHE_MAPLE,
167 	.volatile_table		= &bd79124_volatile_regs,
168 	.wr_table		= &bd79124_ro_regs,
169 	.precious_table		= &bd79124_precious_regs,
170 };
171 
bd79124gpo_direction_get(struct gpio_chip * gc,unsigned int offset)172 static int bd79124gpo_direction_get(struct gpio_chip *gc, unsigned int offset)
173 {
174 	return GPIO_LINE_DIRECTION_OUT;
175 }
176 
bd79124gpo_set(struct gpio_chip * gc,unsigned int offset,int value)177 static int bd79124gpo_set(struct gpio_chip *gc, unsigned int offset, int value)
178 {
179 	struct bd79124_data *data = gpiochip_get_data(gc);
180 
181 	return regmap_assign_bits(data->map, BD79124_REG_GPO_VAL, BIT(offset),
182 				  value);
183 }
184 
bd79124gpo_set_multiple(struct gpio_chip * gc,unsigned long * mask,unsigned long * bits)185 static int bd79124gpo_set_multiple(struct gpio_chip *gc, unsigned long *mask,
186 				    unsigned long *bits)
187 {
188 	unsigned int all_gpos;
189 	int ret;
190 	struct bd79124_data *data = gpiochip_get_data(gc);
191 
192 	/*
193 	 * Ensure all GPIOs in 'mask' are set to be GPIOs
194 	 * The valid_mask was not obeyed by the gpiolib in all cases prior the
195 	 * https://lore.kernel.org/all/cd5e067b80e1bb590027bc3bfa817e7f794f21c3.1741180097.git.mazziesaccount@gmail.com/
196 	 *
197 	 * Keep this check here for a couple of cycles.
198 	 */
199 	ret = regmap_read(data->map, BD79124_REG_PINCFG, &all_gpos);
200 	if (ret)
201 		return ret;
202 
203 	if (all_gpos ^ *mask) {
204 		dev_dbg(data->dev, "Invalid mux config. Can't set value.\n");
205 
206 		return -EINVAL;
207 	}
208 
209 	return regmap_update_bits(data->map, BD79124_REG_GPO_VAL, *mask, *bits);
210 }
211 
bd79124_init_valid_mask(struct gpio_chip * gc,unsigned long * valid_mask,unsigned int ngpios)212 static int bd79124_init_valid_mask(struct gpio_chip *gc,
213 				   unsigned long *valid_mask,
214 				   unsigned int ngpios)
215 {
216 	struct bd79124_data *data = gpiochip_get_data(gc);
217 
218 	*valid_mask = data->gpio_valid_mask;
219 
220 	return 0;
221 }
222 
223 /* Template for GPIO chip */
224 static const struct gpio_chip bd79124gpo_chip = {
225 	.label			= "bd79124-gpo",
226 	.get_direction		= bd79124gpo_direction_get,
227 	.set			= bd79124gpo_set,
228 	.set_multiple		= bd79124gpo_set_multiple,
229 	.init_valid_mask	= bd79124_init_valid_mask,
230 	.can_sleep		= true,
231 	.ngpio			= 8,
232 	.base			= -1,
233 };
234 
235 struct bd79124_raw {
236 	u8 val_bit3_0; /* Is set in high bits of the byte */
237 	u8 val_bit11_4;
238 };
239 #define BD79124_RAW_TO_INT(r) ((r.val_bit11_4 << 4) | (r.val_bit3_0 >> 4))
240 #define BD79124_INT_TO_RAW(val) {					\
241 	.val_bit11_4 = (val) >> 4,					\
242 	.val_bit3_0 = (val) << 4,					\
243 }
244 
245 /*
246  * The high and low limits as well as the recent result values are stored in
247  * the same way in 2 consequent registers. The first register contains 4 bits
248  * of the value. These bits are stored in the high bits [7:4] of register, but
249  * they represent the low bits [3:0] of the value.
250  * The value bits [11:4] are stored in the next register.
251  *
252  * Read data from register and convert to integer.
253  */
bd79124_read_reg_to_int(struct bd79124_data * data,int reg,unsigned int * val)254 static int bd79124_read_reg_to_int(struct bd79124_data *data, int reg,
255 				   unsigned int *val)
256 {
257 	int ret;
258 	struct bd79124_raw raw;
259 
260 	ret = regmap_bulk_read(data->map, reg, &raw, sizeof(raw));
261 	if (ret) {
262 		dev_dbg(data->dev, "bulk_read failed %d\n", ret);
263 
264 		return ret;
265 	}
266 
267 	*val = BD79124_RAW_TO_INT(raw);
268 
269 	return 0;
270 }
271 
272 /*
273  * The high and low limits as well as the recent result values are stored in
274  * the same way in 2 consequent registers. The first register contains 4 bits
275  * of the value. These bits are stored in the high bits [7:4] of register, but
276  * they represent the low bits [3:0] of the value.
277  * The value bits [11:4] are stored in the next register.
278  *
279  * Convert the integer to register format and write it using rmw cycle.
280  */
bd79124_write_int_to_reg(struct bd79124_data * data,int reg,unsigned int val)281 static int bd79124_write_int_to_reg(struct bd79124_data *data, int reg,
282 				    unsigned int val)
283 {
284 	struct bd79124_raw raw = BD79124_INT_TO_RAW(val);
285 	unsigned int tmp;
286 	int ret;
287 
288 	ret = regmap_read(data->map, reg, &tmp);
289 	if (ret)
290 		return ret;
291 
292 	raw.val_bit3_0 |= (tmp & 0xf);
293 
294 	return regmap_bulk_write(data->map, reg, &raw, sizeof(raw));
295 }
296 
297 static const struct iio_event_spec bd79124_events[] = {
298 	{
299 		.type = IIO_EV_TYPE_THRESH,
300 		.dir = IIO_EV_DIR_RISING,
301 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
302 				 BIT(IIO_EV_INFO_ENABLE),
303 	},
304 	{
305 		.type = IIO_EV_TYPE_THRESH,
306 		.dir = IIO_EV_DIR_FALLING,
307 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
308 				 BIT(IIO_EV_INFO_ENABLE),
309 	},
310 	{
311 		.type = IIO_EV_TYPE_THRESH,
312 		.dir = IIO_EV_DIR_EITHER,
313 		.mask_separate = BIT(IIO_EV_INFO_HYSTERESIS),
314 	},
315 };
316 
317 static const struct iio_chan_spec bd79124_chan_template_noirq = {
318 	.type = IIO_VOLTAGE,
319 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
320 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
321 	.indexed = 1,
322 };
323 
324 static const struct iio_chan_spec bd79124_chan_template = {
325 	.type = IIO_VOLTAGE,
326 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
327 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
328 	.indexed = 1,
329 	.event_spec = bd79124_events,
330 	.num_event_specs = ARRAY_SIZE(bd79124_events),
331 };
332 
bd79124_read_event_value(struct iio_dev * iio_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)333 static int bd79124_read_event_value(struct iio_dev *iio_dev,
334 				    const struct iio_chan_spec *chan,
335 				    enum iio_event_type type,
336 				    enum iio_event_direction dir,
337 				    enum iio_event_info info, int *val,
338 				    int *val2)
339 {
340 	struct bd79124_data *data = iio_priv(iio_dev);
341 	int ret, reg;
342 
343 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
344 		return -EINVAL;
345 
346 	switch (info) {
347 	case IIO_EV_INFO_VALUE:
348 		if (dir == IIO_EV_DIR_RISING)
349 			*val = data->alarm_r_limit[chan->channel];
350 		else if (dir == IIO_EV_DIR_FALLING)
351 			*val = data->alarm_f_limit[chan->channel];
352 		else
353 			return -EINVAL;
354 
355 		return IIO_VAL_INT;
356 
357 	case IIO_EV_INFO_HYSTERESIS:
358 		reg = BD79124_GET_HYSTERESIS_REG(chan->channel);
359 		ret = regmap_read(data->map, reg, val);
360 		if (ret)
361 			return ret;
362 
363 		*val &= BD79124_MSK_HYSTERESIS;
364 		/*
365 		 * The data-sheet says the hysteresis register value needs to be
366 		 * shifted left by 3.
367 		 */
368 		*val <<= 3;
369 
370 		return IIO_VAL_INT;
371 
372 	default:
373 		return -EINVAL;
374 	}
375 }
376 
bd79124_start_measurement(struct bd79124_data * data,int chan)377 static int bd79124_start_measurement(struct bd79124_data *data, int chan)
378 {
379 	unsigned int val, regval;
380 	int ret;
381 
382 	/* See if already started */
383 	ret = regmap_read(data->map, BD79124_REG_AUTO_CHANNELS, &val);
384 	if (val & BIT(chan))
385 		return 0;
386 
387 	/*
388 	 * The sequencer must be stopped when channels are added/removed from
389 	 * the list of the measured channels to ensure the new channel
390 	 * configuration is used.
391 	 */
392 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
393 				BD79124_MSK_SEQ_START);
394 	if (ret)
395 		return ret;
396 
397 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, val | BIT(chan));
398 	if (ret)
399 		return ret;
400 
401 	ret = regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
402 			      BD79124_MSK_SEQ_START);
403 	if (ret)
404 		return ret;
405 
406 	/*
407 	 * Start the measurement at the background. Don't bother checking if
408 	 * it was started, regmap has cache.
409 	 */
410 	regval = FIELD_PREP(BD79124_MSK_CONV_MODE, BD79124_CONV_MODE_AUTO);
411 
412 	return regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
413 				BD79124_MSK_CONV_MODE, regval);
414 }
415 
bd79124_stop_measurement(struct bd79124_data * data,int chan)416 static int bd79124_stop_measurement(struct bd79124_data *data, int chan)
417 {
418 	unsigned int enabled_chans;
419 	int ret;
420 
421 	/* See if already stopped */
422 	ret = regmap_read(data->map, BD79124_REG_AUTO_CHANNELS, &enabled_chans);
423 	if (!(enabled_chans & BIT(chan)))
424 		return 0;
425 
426 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
427 				BD79124_MSK_SEQ_START);
428 
429 	/* Clear the channel from the measured channels */
430 	enabled_chans &= ~BIT(chan);
431 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS,
432 			   enabled_chans);
433 	if (ret)
434 		return ret;
435 
436 	/*
437 	 * Stop background conversion for power saving if it was the last
438 	 * channel.
439 	 */
440 	if (!enabled_chans) {
441 		int regval = FIELD_PREP(BD79124_MSK_CONV_MODE,
442 					BD79124_CONV_MODE_MANSEQ);
443 
444 		ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
445 					 BD79124_MSK_CONV_MODE, regval);
446 		if (ret)
447 			return ret;
448 	}
449 
450 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
451 			       BD79124_MSK_SEQ_START);
452 }
453 
bd79124_read_event_config(struct iio_dev * iio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir)454 static int bd79124_read_event_config(struct iio_dev *iio_dev,
455 				     const struct iio_chan_spec *chan,
456 				     enum iio_event_type type,
457 				     enum iio_event_direction dir)
458 {
459 	struct bd79124_data *data = iio_priv(iio_dev);
460 
461 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
462 		return -EINVAL;
463 
464 	return !!(data->alarm_monitored[chan->channel] & BIT(dir));
465 }
466 
bd79124_disable_event(struct bd79124_data * data,enum iio_event_direction dir,int channel)467 static int bd79124_disable_event(struct bd79124_data *data,
468 				 enum iio_event_direction dir, int channel)
469 {
470 	int dir_bit = BIT(dir);
471 	int reg;
472 	unsigned int limit;
473 
474 	guard(mutex)(&data->mutex);
475 
476 	/*
477 	 * Set thresholds either to 0 or to 2^12 - 1 as appropriate to prevent
478 	 * alerts and thus disable event generation.
479 	 */
480 	if (dir == IIO_EV_DIR_RISING) {
481 		reg = BD79124_GET_HIGH_LIMIT_REG(channel);
482 		limit = BD79124_HIGH_LIMIT_MAX;
483 	} else if (dir == IIO_EV_DIR_FALLING) {
484 		reg = BD79124_GET_LOW_LIMIT_REG(channel);
485 		limit = BD79124_LOW_LIMIT_MIN;
486 	} else {
487 		return -EINVAL;
488 	}
489 
490 	data->alarm_monitored[channel] &= ~dir_bit;
491 
492 	/*
493 	 * Stop measurement if there is no more events to monitor.
494 	 * We don't bother checking the retval because the limit
495 	 * setting should in any case effectively disable the alarm.
496 	 */
497 	if (!data->alarm_monitored[channel]) {
498 		bd79124_stop_measurement(data, channel);
499 		regmap_clear_bits(data->map, BD79124_REG_ALERT_CH_SEL,
500 				  BIT(channel));
501 	}
502 
503 	return bd79124_write_int_to_reg(data, reg, limit);
504 }
505 
bd79124_enable_event(struct bd79124_data * data,enum iio_event_direction dir,unsigned int channel)506 static int bd79124_enable_event(struct bd79124_data *data,
507 				enum iio_event_direction dir,
508 				unsigned int channel)
509 {
510 	int dir_bit = BIT(dir);
511 	int reg, ret;
512 	u16 *limit;
513 
514 	guard(mutex)(&data->mutex);
515 	ret = bd79124_start_measurement(data, channel);
516 	if (ret)
517 		return ret;
518 
519 	data->alarm_monitored[channel] |= dir_bit;
520 
521 	/* Add the channel to the list of monitored channels */
522 	ret = regmap_set_bits(data->map, BD79124_REG_ALERT_CH_SEL, BIT(channel));
523 	if (ret)
524 		return ret;
525 
526 	if (dir == IIO_EV_DIR_RISING) {
527 		limit = &data->alarm_f_limit[channel];
528 		reg = BD79124_GET_HIGH_LIMIT_REG(channel);
529 	} else {
530 		limit = &data->alarm_f_limit[channel];
531 		reg = BD79124_GET_LOW_LIMIT_REG(channel);
532 	}
533 	/*
534 	 * Don't write the new limit to the hardware if we are in the
535 	 * rate-limit period. The timer which re-enables the event will set
536 	 * the limit.
537 	 */
538 	if (!(data->alarm_suppressed[channel] & dir_bit)) {
539 		ret = bd79124_write_int_to_reg(data, reg, *limit);
540 		if (ret)
541 			return ret;
542 	}
543 
544 	/*
545 	 * Enable comparator. Trust the regmap cache, no need to check
546 	 * if it was already enabled.
547 	 *
548 	 * We could do this in the hw-init, but there may be users who
549 	 * never enable alarms and for them it makes sense to not
550 	 * enable the comparator at probe.
551 	 */
552 	return regmap_set_bits(data->map, BD79124_REG_GEN_CFG,
553 				      BD79124_MSK_DWC_EN);
554 }
555 
bd79124_write_event_config(struct iio_dev * iio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,bool state)556 static int bd79124_write_event_config(struct iio_dev *iio_dev,
557 				      const struct iio_chan_spec *chan,
558 				      enum iio_event_type type,
559 				      enum iio_event_direction dir, bool state)
560 {
561 	struct bd79124_data *data = iio_priv(iio_dev);
562 
563 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
564 		return -EINVAL;
565 
566 	if (state)
567 		return bd79124_enable_event(data, dir, chan->channel);
568 
569 	return bd79124_disable_event(data, dir, chan->channel);
570 }
571 
bd79124_write_event_value(struct iio_dev * iio_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)572 static int bd79124_write_event_value(struct iio_dev *iio_dev,
573 				     const struct iio_chan_spec *chan,
574 				     enum iio_event_type type,
575 				     enum iio_event_direction dir,
576 				     enum iio_event_info info, int val,
577 				     int val2)
578 {
579 	struct bd79124_data *data = iio_priv(iio_dev);
580 	int reg;
581 
582 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
583 		return -EINVAL;
584 
585 	switch (info) {
586 	case IIO_EV_INFO_VALUE:
587 	{
588 		guard(mutex)(&data->mutex);
589 
590 		if (dir == IIO_EV_DIR_RISING) {
591 			data->alarm_r_limit[chan->channel] = val;
592 			reg = BD79124_GET_HIGH_LIMIT_REG(chan->channel);
593 		} else if (dir == IIO_EV_DIR_FALLING) {
594 			data->alarm_f_limit[chan->channel] = val;
595 			reg = BD79124_GET_LOW_LIMIT_REG(chan->channel);
596 		} else {
597 			return -EINVAL;
598 		}
599 		/*
600 		 * We don't want to enable the alarm if it is not enabled or
601 		 * if it is suppressed. In that case skip writing to the
602 		 * register.
603 		 */
604 		if (!(data->alarm_monitored[chan->channel] & BIT(dir)) ||
605 		    data->alarm_suppressed[chan->channel] & BIT(dir))
606 			return 0;
607 
608 		return bd79124_write_int_to_reg(data, reg, val);
609 	}
610 	case IIO_EV_INFO_HYSTERESIS:
611 		reg = BD79124_GET_HYSTERESIS_REG(chan->channel);
612 		val >>= 3;
613 
614 		return regmap_update_bits(data->map, reg, BD79124_MSK_HYSTERESIS,
615 					  val);
616 	default:
617 		return -EINVAL;
618 	}
619 }
620 
bd79124_single_chan_seq(struct bd79124_data * data,int chan,unsigned int * old)621 static int bd79124_single_chan_seq(struct bd79124_data *data, int chan, unsigned int *old)
622 {
623 	int ret;
624 
625 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
626 				BD79124_MSK_SEQ_START);
627 	if (ret)
628 		return ret;
629 
630 	/*
631 	 * It may be we have some channels monitored for alarms so we want to
632 	 * cache the old config and return it when the single channel
633 	 * measurement has been completed.
634 	 */
635 	ret = regmap_read(data->map, BD79124_REG_AUTO_CHANNELS, old);
636 	if (ret)
637 		return ret;
638 
639 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, BIT(chan));
640 	if (ret)
641 		return ret;
642 
643 	/* Restart the sequencer */
644 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
645 			       BD79124_MSK_SEQ_START);
646 }
647 
bd79124_single_chan_seq_end(struct bd79124_data * data,unsigned int old)648 static int bd79124_single_chan_seq_end(struct bd79124_data *data, unsigned int old)
649 {
650 	int ret;
651 
652 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
653 				BD79124_MSK_SEQ_START);
654 	if (ret)
655 		return ret;
656 
657 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, old);
658 	if (ret)
659 		return ret;
660 
661 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
662 			       BD79124_MSK_SEQ_START);
663 }
664 
bd79124_read_raw(struct iio_dev * iio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long m)665 static int bd79124_read_raw(struct iio_dev *iio_dev,
666 			    struct iio_chan_spec const *chan,
667 			    int *val, int *val2, long m)
668 {
669 	struct bd79124_data *data = iio_priv(iio_dev);
670 	int ret;
671 
672 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
673 		return -EINVAL;
674 
675 	switch (m) {
676 	case IIO_CHAN_INFO_RAW:
677 	{
678 		unsigned int old_chan_cfg, regval;
679 		int tmp;
680 
681 		guard(mutex)(&data->mutex);
682 
683 		/*
684 		 * Start the automatic conversion. This is needed here if no
685 		 * events have been enabled.
686 		 */
687 		regval = FIELD_PREP(BD79124_MSK_CONV_MODE,
688 				    BD79124_CONV_MODE_AUTO);
689 		ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
690 					 BD79124_MSK_CONV_MODE, regval);
691 		if (ret)
692 			return ret;
693 
694 		ret = bd79124_single_chan_seq(data, chan->channel, &old_chan_cfg);
695 		if (ret)
696 			return ret;
697 
698 		/* The maximum conversion time is 6 uS. */
699 		udelay(6);
700 
701 		ret = bd79124_read_reg_to_int(data,
702 			BD79124_GET_RECENT_RES_REG(chan->channel), val);
703 		/*
704 		 * Return the old chan config even if data reading failed in
705 		 * order to re-enable the event monitoring.
706 		 */
707 		tmp = bd79124_single_chan_seq_end(data, old_chan_cfg);
708 		if (tmp)
709 			dev_err(data->dev,
710 				"Failed to return config. Alarms may be disabled\n");
711 
712 		if (ret)
713 			return ret;
714 
715 		return IIO_VAL_INT;
716 	}
717 	case IIO_CHAN_INFO_SCALE:
718 		*val = data->vmax / 1000;
719 		*val2 = BD79124_ADC_BITS;
720 		return IIO_VAL_FRACTIONAL_LOG2;
721 	default:
722 		return -EINVAL;
723 	}
724 }
725 
726 static const struct iio_info bd79124_info = {
727 	.read_raw = bd79124_read_raw,
728 	.read_event_config = &bd79124_read_event_config,
729 	.write_event_config = &bd79124_write_event_config,
730 	.read_event_value = &bd79124_read_event_value,
731 	.write_event_value = &bd79124_write_event_value,
732 };
733 
bd79124_re_enable_lo(struct bd79124_data * data,unsigned int channel)734 static void bd79124_re_enable_lo(struct bd79124_data *data, unsigned int channel)
735 {
736 	int ret, evbit = BIT(IIO_EV_DIR_FALLING);
737 
738 	/*
739 	 * We should not re-enable the event if user has disabled it while
740 	 * rate-limiting was enabled.
741 	 */
742 	if (!(data->alarm_suppressed[channel] & evbit))
743 		return;
744 
745 	data->alarm_suppressed[channel] &= ~evbit;
746 
747 	if (!(data->alarm_monitored[channel] & evbit))
748 		return;
749 
750 	ret = bd79124_write_int_to_reg(data, BD79124_GET_LOW_LIMIT_REG(channel),
751 				       data->alarm_f_limit[channel]);
752 	if (ret)
753 		dev_warn(data->dev, "Low limit enabling failed for channel%d\n",
754 			 channel);
755 }
756 
bd79124_re_enable_hi(struct bd79124_data * data,unsigned int channel)757 static void bd79124_re_enable_hi(struct bd79124_data *data, unsigned int channel)
758 {
759 	int ret, evbit = BIT(IIO_EV_DIR_RISING);
760 
761 	/*
762 	 * We should not re-enable the event if user has disabled it while
763 	 * rate-limiting was enabled.
764 	 */
765 	if (!(data->alarm_suppressed[channel] & evbit))
766 		return;
767 
768 	data->alarm_suppressed[channel] &= ~evbit;
769 
770 	if (!(data->alarm_monitored[channel] & evbit))
771 		return;
772 
773 	ret = bd79124_write_int_to_reg(data, BD79124_GET_HIGH_LIMIT_REG(channel),
774 				       data->alarm_r_limit[channel]);
775 	if (ret)
776 		dev_warn(data->dev, "High limit enabling failed for channel%d\n",
777 			 channel);
778 }
779 
bd79124_alm_enable_worker(struct work_struct * work)780 static void bd79124_alm_enable_worker(struct work_struct *work)
781 {
782 	int i;
783 	struct bd79124_data *data = container_of(work, struct bd79124_data,
784 						 alm_enable_work.work);
785 
786 	/* Take the mutex so there is no race with user disabling the alarm */
787 	guard(mutex)(&data->mutex);
788 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
789 		bd79124_re_enable_hi(data, i);
790 		bd79124_re_enable_lo(data, i);
791 	}
792 }
793 
__bd79124_event_ratelimit(struct bd79124_data * data,int reg,unsigned int limit)794 static int __bd79124_event_ratelimit(struct bd79124_data *data, int reg,
795 				     unsigned int limit)
796 {
797 	int ret;
798 
799 	if (limit > BD79124_HIGH_LIMIT_MAX)
800 		return -EINVAL;
801 
802 	ret = bd79124_write_int_to_reg(data, reg, limit);
803 	if (ret)
804 		return ret;
805 
806 	/*
807 	 * We use 1 sec 'grace period'. At the moment I see no reason to make
808 	 * this user configurable. We need an ABI for this if configuration is
809 	 * needed.
810 	 */
811 	schedule_delayed_work(&data->alm_enable_work, msecs_to_jiffies(1000));
812 
813 	return 0;
814 }
815 
bd79124_event_ratelimit_hi(struct bd79124_data * data,unsigned int channel)816 static int bd79124_event_ratelimit_hi(struct bd79124_data *data,
817 				      unsigned int channel)
818 {
819 	guard(mutex)(&data->mutex);
820 	data->alarm_suppressed[channel] |= BIT(IIO_EV_DIR_RISING);
821 
822 	return __bd79124_event_ratelimit(data,
823 					 BD79124_GET_HIGH_LIMIT_REG(channel),
824 					 BD79124_HIGH_LIMIT_MAX);
825 }
826 
bd79124_event_ratelimit_lo(struct bd79124_data * data,unsigned int channel)827 static int bd79124_event_ratelimit_lo(struct bd79124_data *data,
828 				      unsigned int channel)
829 {
830 	guard(mutex)(&data->mutex);
831 	data->alarm_suppressed[channel] |= BIT(IIO_EV_DIR_FALLING);
832 
833 	return __bd79124_event_ratelimit(data,
834 					 BD79124_GET_LOW_LIMIT_REG(channel),
835 					 BD79124_LOW_LIMIT_MIN);
836 }
837 
bd79124_event_handler(int irq,void * priv)838 static irqreturn_t bd79124_event_handler(int irq, void *priv)
839 {
840 	unsigned int i_hi, i_lo;
841 	int i, ret;
842 	struct iio_dev *iio_dev = priv;
843 	struct bd79124_data *data = iio_priv(iio_dev);
844 
845 	/*
846 	 * Return IRQ_NONE if bailing-out without acking. This allows the IRQ
847 	 * subsystem to disable the offending IRQ line if we get a hardware
848 	 * problem. This behaviour has saved my poor bottom a few times in the
849 	 * past as, instead of getting unusably unresponsive, the system has
850 	 * spilled out the magic words "...nobody cared".
851 	 */
852 	ret = regmap_read(data->map, BD79124_REG_EVENT_FLAG_HI, &i_hi);
853 	if (ret)
854 		return IRQ_NONE;
855 
856 	ret = regmap_read(data->map, BD79124_REG_EVENT_FLAG_LO, &i_lo);
857 	if (ret)
858 		return IRQ_NONE;
859 
860 	if (!i_lo && !i_hi)
861 		return IRQ_NONE;
862 
863 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
864 		u64 ecode;
865 
866 		if (BIT(i) & i_hi) {
867 			ecode = IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, i,
868 						     IIO_EV_TYPE_THRESH,
869 						     IIO_EV_DIR_RISING);
870 
871 			iio_push_event(iio_dev, ecode, data->timestamp);
872 			/*
873 			 * The BD79124 keeps the IRQ asserted for as long as
874 			 * the voltage exceeds the threshold. It causes the IRQ
875 			 * to keep firing.
876 			 *
877 			 * Disable the event for the channel and schedule the
878 			 * re-enabling the event later to prevent storm of
879 			 * events.
880 			 */
881 			ret = bd79124_event_ratelimit_hi(data, i);
882 			if (ret)
883 				return IRQ_NONE;
884 		}
885 		if (BIT(i) & i_lo) {
886 			ecode = IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, i,
887 						     IIO_EV_TYPE_THRESH,
888 						     IIO_EV_DIR_FALLING);
889 
890 			iio_push_event(iio_dev, ecode, data->timestamp);
891 			ret = bd79124_event_ratelimit_lo(data, i);
892 			if (ret)
893 				return IRQ_NONE;
894 		}
895 	}
896 
897 	ret = regmap_write(data->map, BD79124_REG_EVENT_FLAG_HI, i_hi);
898 	if (ret)
899 		return IRQ_NONE;
900 
901 	ret = regmap_write(data->map, BD79124_REG_EVENT_FLAG_LO, i_lo);
902 	if (ret)
903 		return IRQ_NONE;
904 
905 	return IRQ_HANDLED;
906 }
907 
bd79124_irq_handler(int irq,void * priv)908 static irqreturn_t bd79124_irq_handler(int irq, void *priv)
909 {
910 	struct iio_dev *iio_dev = priv;
911 	struct bd79124_data *data = iio_priv(iio_dev);
912 
913 	data->timestamp = iio_get_time_ns(iio_dev);
914 
915 	return IRQ_WAKE_THREAD;
916 }
917 
bd79124_chan_init(struct bd79124_data * data,int channel)918 static int bd79124_chan_init(struct bd79124_data *data, int channel)
919 {
920 	int ret;
921 
922 	ret = regmap_write(data->map, BD79124_GET_HIGH_LIMIT_REG(channel),
923 			   BD79124_HIGH_LIMIT_MAX);
924 	if (ret)
925 		return ret;
926 
927 	return regmap_write(data->map, BD79124_GET_LOW_LIMIT_REG(channel),
928 			    BD79124_LOW_LIMIT_MIN);
929 }
930 
bd79124_get_gpio_pins(const struct iio_chan_spec * cs,int num_channels)931 static int bd79124_get_gpio_pins(const struct iio_chan_spec *cs, int num_channels)
932 {
933 	int i, gpio_channels;
934 
935 	/*
936 	 * Let's initialize the mux config to say that all 8 channels are
937 	 * GPIOs. Then we can just loop through the iio_chan_spec and clear the
938 	 * bits for found ADC channels.
939 	 */
940 	gpio_channels = GENMASK(7, 0);
941 	for (i = 0; i < num_channels; i++)
942 		gpio_channels &= ~BIT(cs[i].channel);
943 
944 	return gpio_channels;
945 }
946 
bd79124_hw_init(struct bd79124_data * data)947 static int bd79124_hw_init(struct bd79124_data *data)
948 {
949 	unsigned int regval;
950 	int ret, i;
951 
952 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
953 		ret = bd79124_chan_init(data, i);
954 		if (ret)
955 			return ret;
956 		data->alarm_r_limit[i] = BD79124_HIGH_LIMIT_MAX;
957 	}
958 	/* Stop auto sequencer */
959 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
960 				BD79124_MSK_SEQ_START);
961 	if (ret)
962 		return ret;
963 
964 	/* Enable writing the measured values to the registers */
965 	ret = regmap_set_bits(data->map, BD79124_REG_GEN_CFG,
966 			      BD79124_MSK_STATS_EN);
967 	if (ret)
968 		return ret;
969 
970 	/* Set no channels to be auto-measured */
971 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, 0x0);
972 	if (ret)
973 		return ret;
974 
975 	/* Set no channels to be manually measured */
976 	ret = regmap_write(data->map, BD79124_REG_MANUAL_CHANNELS, 0x0);
977 	if (ret)
978 		return ret;
979 
980 	regval = FIELD_PREP(BD79124_MSK_AUTO_INTERVAL, BD79124_INTERVAL_750_US);
981 	ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
982 				 BD79124_MSK_AUTO_INTERVAL, regval);
983 	if (ret)
984 		return ret;
985 
986 	/* Sequencer mode to auto */
987 	ret = regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
988 			      BD79124_MSK_SEQ_SEQ);
989 	if (ret)
990 		return ret;
991 
992 	/* Don't start the measurement */
993 	regval = FIELD_PREP(BD79124_MSK_CONV_MODE, BD79124_CONV_MODE_MANSEQ);
994 	return regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
995 				  BD79124_MSK_CONV_MODE, regval);
996 }
997 
bd79124_probe(struct i2c_client * i2c)998 static int bd79124_probe(struct i2c_client *i2c)
999 {
1000 	struct bd79124_data *data;
1001 	struct iio_dev *iio_dev;
1002 	const struct iio_chan_spec *template;
1003 	struct iio_chan_spec *cs;
1004 	struct device *dev = &i2c->dev;
1005 	unsigned int gpio_pins;
1006 	int ret;
1007 
1008 	iio_dev = devm_iio_device_alloc(dev, sizeof(*data));
1009 	if (!iio_dev)
1010 		return -ENOMEM;
1011 
1012 	data = iio_priv(iio_dev);
1013 	data->dev = dev;
1014 	data->map = devm_regmap_init_i2c(i2c, &bd79124_regmap);
1015 	if (IS_ERR(data->map))
1016 		return dev_err_probe(dev, PTR_ERR(data->map),
1017 				     "Failed to initialize Regmap\n");
1018 
1019 	ret = devm_regulator_get_enable_read_voltage(dev, "vdd");
1020 	if (ret < 0)
1021 		return dev_err_probe(dev, ret, "Failed to get the Vdd\n");
1022 
1023 	data->vmax = ret;
1024 
1025 	ret = devm_regulator_get_enable(dev, "iovdd");
1026 	if (ret < 0)
1027 		return dev_err_probe(dev, ret, "Failed to enable I/O voltage\n");
1028 
1029 	ret = devm_delayed_work_autocancel(dev, &data->alm_enable_work,
1030 					   bd79124_alm_enable_worker);
1031 	if (ret)
1032 		return ret;
1033 
1034 	if (i2c->irq) {
1035 		template = &bd79124_chan_template;
1036 	} else {
1037 		template = &bd79124_chan_template_noirq;
1038 		dev_dbg(dev, "No IRQ found, events disabled\n");
1039 	}
1040 
1041 	ret = devm_mutex_init(dev, &data->mutex);
1042 	if (ret)
1043 		return ret;
1044 
1045 	ret = devm_iio_adc_device_alloc_chaninfo_se(dev, template,
1046 		BD79124_MAX_NUM_CHANNELS - 1, &cs);
1047 	if (ret < 0) {
1048 		/* Register all pins as GPOs if there are no ADC channels */
1049 		if (ret == -ENOENT)
1050 			goto register_gpios;
1051 		return ret;
1052 	}
1053 	iio_dev->channels = cs;
1054 	iio_dev->num_channels = ret;
1055 	iio_dev->info = &bd79124_info;
1056 	iio_dev->name = "bd79124";
1057 	iio_dev->modes = INDIO_DIRECT_MODE;
1058 
1059 	ret = bd79124_hw_init(data);
1060 	if (ret)
1061 		return ret;
1062 
1063 	if (i2c->irq > 0) {
1064 		ret = devm_request_threaded_irq(dev, i2c->irq,
1065 			bd79124_irq_handler, &bd79124_event_handler,
1066 			IRQF_ONESHOT, "adc-thresh-alert", iio_dev);
1067 		if (ret)
1068 			return dev_err_probe(data->dev, ret,
1069 					     "Failed to register IRQ\n");
1070 	}
1071 
1072 	ret = devm_iio_device_register(data->dev, iio_dev);
1073 	if (ret)
1074 		return dev_err_probe(data->dev, ret, "Failed to register ADC\n");
1075 
1076 register_gpios:
1077 	gpio_pins = bd79124_get_gpio_pins(iio_dev->channels,
1078 					  iio_dev->num_channels);
1079 
1080 	/*
1081 	 * The mux should default to "all ADCs", but better to not trust it.
1082 	 * Thus we do set the mux even when we have only ADCs and no GPOs.
1083 	 */
1084 	ret = regmap_write(data->map, BD79124_REG_PINCFG, gpio_pins);
1085 	if (ret)
1086 		return ret;
1087 
1088 	/* No GPOs if all channels are reserved for ADC, so we're done. */
1089 	if (!gpio_pins)
1090 		return 0;
1091 
1092 	data->gpio_valid_mask = gpio_pins;
1093 	data->gc = bd79124gpo_chip;
1094 	data->gc.parent = dev;
1095 
1096 	return devm_gpiochip_add_data(dev, &data->gc, data);
1097 }
1098 
1099 static const struct of_device_id bd79124_of_match[] = {
1100 	{ .compatible = "rohm,bd79124" },
1101 	{ }
1102 };
1103 MODULE_DEVICE_TABLE(of, bd79124_of_match);
1104 
1105 static const struct i2c_device_id bd79124_id[] = {
1106 	{ .name = "bd79124" },
1107 	{ }
1108 };
1109 MODULE_DEVICE_TABLE(i2c, bd79124_id);
1110 
1111 static struct i2c_driver bd79124_driver = {
1112 	.driver = {
1113 		.name = "bd79124",
1114 		.of_match_table = bd79124_of_match,
1115 	},
1116 	.probe = bd79124_probe,
1117 	.id_table = bd79124_id,
1118 };
1119 module_i2c_driver(bd79124_driver);
1120 
1121 MODULE_AUTHOR("Matti Vaittinen <mazziesaccount@gmail.com>");
1122 MODULE_DESCRIPTION("Driver for ROHM BD79124 ADC");
1123 MODULE_LICENSE("GPL");
1124 MODULE_IMPORT_NS("IIO_DRIVER");
1125