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