xref: /linux/drivers/iio/adc/rohm-bd79124.c (revision 196cc715dce3576a54065f5cb07185c75778f9a8)
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 
172 static int bd79124gpo_direction_get(struct gpio_chip *gc, unsigned int offset)
173 {
174 	return GPIO_LINE_DIRECTION_OUT;
175 }
176 
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 
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 (*mask & ~all_gpos) {
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 
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  */
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  */
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 
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 
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 (ret)
385 		return ret;
386 
387 	if (val & BIT(chan))
388 		return 0;
389 
390 	/*
391 	 * The sequencer must be stopped when channels are added/removed from
392 	 * the list of the measured channels to ensure the new channel
393 	 * configuration is used.
394 	 */
395 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
396 				BD79124_MSK_SEQ_START);
397 	if (ret)
398 		return ret;
399 
400 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, val | BIT(chan));
401 	if (ret)
402 		return ret;
403 
404 	ret = regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
405 			      BD79124_MSK_SEQ_START);
406 	if (ret)
407 		return ret;
408 
409 	/*
410 	 * Start the measurement at the background. Don't bother checking if
411 	 * it was started, regmap has cache.
412 	 */
413 	regval = FIELD_PREP(BD79124_MSK_CONV_MODE, BD79124_CONV_MODE_AUTO);
414 
415 	return regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
416 				BD79124_MSK_CONV_MODE, regval);
417 }
418 
419 static int bd79124_stop_measurement(struct bd79124_data *data, int chan)
420 {
421 	unsigned int enabled_chans;
422 	int ret;
423 
424 	/* See if already stopped */
425 	ret = regmap_read(data->map, BD79124_REG_AUTO_CHANNELS, &enabled_chans);
426 	if (ret)
427 		return ret;
428 
429 	if (!(enabled_chans & BIT(chan)))
430 		return 0;
431 
432 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
433 				BD79124_MSK_SEQ_START);
434 	if (ret)
435 		return ret;
436 
437 	/* Clear the channel from the measured channels */
438 	enabled_chans &= ~BIT(chan);
439 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS,
440 			   enabled_chans);
441 	if (ret)
442 		return ret;
443 
444 	/*
445 	 * Stop background conversion for power saving if it was the last
446 	 * channel.
447 	 */
448 	if (!enabled_chans) {
449 		int regval = FIELD_PREP(BD79124_MSK_CONV_MODE,
450 					BD79124_CONV_MODE_MANSEQ);
451 
452 		ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
453 					 BD79124_MSK_CONV_MODE, regval);
454 		if (ret)
455 			return ret;
456 	}
457 
458 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
459 			       BD79124_MSK_SEQ_START);
460 }
461 
462 static int bd79124_read_event_config(struct iio_dev *iio_dev,
463 				     const struct iio_chan_spec *chan,
464 				     enum iio_event_type type,
465 				     enum iio_event_direction dir)
466 {
467 	struct bd79124_data *data = iio_priv(iio_dev);
468 
469 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
470 		return -EINVAL;
471 
472 	return !!(data->alarm_monitored[chan->channel] & BIT(dir));
473 }
474 
475 static int bd79124_disable_event(struct bd79124_data *data,
476 				 enum iio_event_direction dir, int channel)
477 {
478 	int dir_bit = BIT(dir);
479 	int reg;
480 	unsigned int limit;
481 
482 	guard(mutex)(&data->mutex);
483 
484 	/*
485 	 * Set thresholds either to 0 or to 2^12 - 1 as appropriate to prevent
486 	 * alerts and thus disable event generation.
487 	 */
488 	if (dir == IIO_EV_DIR_RISING) {
489 		reg = BD79124_GET_HIGH_LIMIT_REG(channel);
490 		limit = BD79124_HIGH_LIMIT_MAX;
491 	} else if (dir == IIO_EV_DIR_FALLING) {
492 		reg = BD79124_GET_LOW_LIMIT_REG(channel);
493 		limit = BD79124_LOW_LIMIT_MIN;
494 	} else {
495 		return -EINVAL;
496 	}
497 
498 	data->alarm_monitored[channel] &= ~dir_bit;
499 
500 	/*
501 	 * Stop measurement if there is no more events to monitor.
502 	 * We don't bother checking the retval because the limit
503 	 * setting should in any case effectively disable the alarm.
504 	 */
505 	if (!data->alarm_monitored[channel]) {
506 		bd79124_stop_measurement(data, channel);
507 		regmap_clear_bits(data->map, BD79124_REG_ALERT_CH_SEL,
508 				  BIT(channel));
509 	}
510 
511 	return bd79124_write_int_to_reg(data, reg, limit);
512 }
513 
514 static int bd79124_enable_event(struct bd79124_data *data,
515 				enum iio_event_direction dir,
516 				unsigned int channel)
517 {
518 	int dir_bit = BIT(dir);
519 	int reg, ret;
520 	u16 *limit;
521 
522 	guard(mutex)(&data->mutex);
523 	ret = bd79124_start_measurement(data, channel);
524 	if (ret)
525 		return ret;
526 
527 	data->alarm_monitored[channel] |= dir_bit;
528 
529 	/* Add the channel to the list of monitored channels */
530 	ret = regmap_set_bits(data->map, BD79124_REG_ALERT_CH_SEL, BIT(channel));
531 	if (ret)
532 		return ret;
533 
534 	if (dir == IIO_EV_DIR_RISING) {
535 		limit = &data->alarm_r_limit[channel];
536 		reg = BD79124_GET_HIGH_LIMIT_REG(channel);
537 	} else {
538 		limit = &data->alarm_f_limit[channel];
539 		reg = BD79124_GET_LOW_LIMIT_REG(channel);
540 	}
541 	/*
542 	 * Don't write the new limit to the hardware if we are in the
543 	 * rate-limit period. The timer which re-enables the event will set
544 	 * the limit.
545 	 */
546 	if (!(data->alarm_suppressed[channel] & dir_bit)) {
547 		ret = bd79124_write_int_to_reg(data, reg, *limit);
548 		if (ret)
549 			return ret;
550 	}
551 
552 	/*
553 	 * Enable comparator. Trust the regmap cache, no need to check
554 	 * if it was already enabled.
555 	 *
556 	 * We could do this in the hw-init, but there may be users who
557 	 * never enable alarms and for them it makes sense to not
558 	 * enable the comparator at probe.
559 	 */
560 	return regmap_set_bits(data->map, BD79124_REG_GEN_CFG,
561 				      BD79124_MSK_DWC_EN);
562 }
563 
564 static int bd79124_write_event_config(struct iio_dev *iio_dev,
565 				      const struct iio_chan_spec *chan,
566 				      enum iio_event_type type,
567 				      enum iio_event_direction dir, bool state)
568 {
569 	struct bd79124_data *data = iio_priv(iio_dev);
570 
571 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
572 		return -EINVAL;
573 
574 	if (state)
575 		return bd79124_enable_event(data, dir, chan->channel);
576 
577 	return bd79124_disable_event(data, dir, chan->channel);
578 }
579 
580 static int bd79124_write_event_value(struct iio_dev *iio_dev,
581 				     const struct iio_chan_spec *chan,
582 				     enum iio_event_type type,
583 				     enum iio_event_direction dir,
584 				     enum iio_event_info info, int val,
585 				     int val2)
586 {
587 	struct bd79124_data *data = iio_priv(iio_dev);
588 	int reg;
589 
590 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
591 		return -EINVAL;
592 
593 	switch (info) {
594 	case IIO_EV_INFO_VALUE:
595 	{
596 		guard(mutex)(&data->mutex);
597 
598 		if (dir == IIO_EV_DIR_RISING) {
599 			data->alarm_r_limit[chan->channel] = val;
600 			reg = BD79124_GET_HIGH_LIMIT_REG(chan->channel);
601 		} else if (dir == IIO_EV_DIR_FALLING) {
602 			data->alarm_f_limit[chan->channel] = val;
603 			reg = BD79124_GET_LOW_LIMIT_REG(chan->channel);
604 		} else {
605 			return -EINVAL;
606 		}
607 		/*
608 		 * We don't want to enable the alarm if it is not enabled or
609 		 * if it is suppressed. In that case skip writing to the
610 		 * register.
611 		 */
612 		if (!(data->alarm_monitored[chan->channel] & BIT(dir)) ||
613 		    data->alarm_suppressed[chan->channel] & BIT(dir))
614 			return 0;
615 
616 		return bd79124_write_int_to_reg(data, reg, val);
617 	}
618 	case IIO_EV_INFO_HYSTERESIS:
619 		reg = BD79124_GET_HYSTERESIS_REG(chan->channel);
620 		val >>= 3;
621 
622 		return regmap_update_bits(data->map, reg, BD79124_MSK_HYSTERESIS,
623 					  val);
624 	default:
625 		return -EINVAL;
626 	}
627 }
628 
629 static int bd79124_single_chan_seq(struct bd79124_data *data, int chan, unsigned int *old)
630 {
631 	int ret;
632 
633 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
634 				BD79124_MSK_SEQ_START);
635 	if (ret)
636 		return ret;
637 
638 	/*
639 	 * It may be we have some channels monitored for alarms so we want to
640 	 * cache the old config and return it when the single channel
641 	 * measurement has been completed.
642 	 */
643 	ret = regmap_read(data->map, BD79124_REG_AUTO_CHANNELS, old);
644 	if (ret)
645 		return ret;
646 
647 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, BIT(chan));
648 	if (ret)
649 		return ret;
650 
651 	/* Restart the sequencer */
652 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
653 			       BD79124_MSK_SEQ_START);
654 }
655 
656 static int bd79124_single_chan_seq_end(struct bd79124_data *data, unsigned int old)
657 {
658 	int ret;
659 
660 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
661 				BD79124_MSK_SEQ_START);
662 	if (ret)
663 		return ret;
664 
665 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, old);
666 	if (ret)
667 		return ret;
668 
669 	return regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
670 			       BD79124_MSK_SEQ_START);
671 }
672 
673 static int bd79124_read_raw(struct iio_dev *iio_dev,
674 			    struct iio_chan_spec const *chan,
675 			    int *val, int *val2, long m)
676 {
677 	struct bd79124_data *data = iio_priv(iio_dev);
678 	int ret;
679 
680 	if (chan->channel >= BD79124_MAX_NUM_CHANNELS)
681 		return -EINVAL;
682 
683 	switch (m) {
684 	case IIO_CHAN_INFO_RAW:
685 	{
686 		unsigned int old_chan_cfg, regval;
687 		int tmp;
688 
689 		guard(mutex)(&data->mutex);
690 
691 		/*
692 		 * Start the automatic conversion. This is needed here if no
693 		 * events have been enabled.
694 		 */
695 		regval = FIELD_PREP(BD79124_MSK_CONV_MODE,
696 				    BD79124_CONV_MODE_AUTO);
697 		ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
698 					 BD79124_MSK_CONV_MODE, regval);
699 		if (ret)
700 			return ret;
701 
702 		ret = bd79124_single_chan_seq(data, chan->channel, &old_chan_cfg);
703 		if (ret)
704 			return ret;
705 
706 		/* The maximum conversion time is 6 uS. */
707 		udelay(6);
708 
709 		ret = bd79124_read_reg_to_int(data,
710 			BD79124_GET_RECENT_RES_REG(chan->channel), val);
711 		/*
712 		 * Return the old chan config even if data reading failed in
713 		 * order to re-enable the event monitoring.
714 		 */
715 		tmp = bd79124_single_chan_seq_end(data, old_chan_cfg);
716 		if (tmp)
717 			dev_err(data->dev,
718 				"Failed to return config. Alarms may be disabled\n");
719 
720 		if (ret)
721 			return ret;
722 
723 		return IIO_VAL_INT;
724 	}
725 	case IIO_CHAN_INFO_SCALE:
726 		*val = data->vmax / 1000;
727 		*val2 = BD79124_ADC_BITS;
728 		return IIO_VAL_FRACTIONAL_LOG2;
729 	default:
730 		return -EINVAL;
731 	}
732 }
733 
734 static const struct iio_info bd79124_info = {
735 	.read_raw = bd79124_read_raw,
736 	.read_event_config = &bd79124_read_event_config,
737 	.write_event_config = &bd79124_write_event_config,
738 	.read_event_value = &bd79124_read_event_value,
739 	.write_event_value = &bd79124_write_event_value,
740 };
741 
742 static void bd79124_re_enable_lo(struct bd79124_data *data, unsigned int channel)
743 {
744 	int ret, evbit = BIT(IIO_EV_DIR_FALLING);
745 
746 	/*
747 	 * We should not re-enable the event if user has disabled it while
748 	 * rate-limiting was enabled.
749 	 */
750 	if (!(data->alarm_suppressed[channel] & evbit))
751 		return;
752 
753 	data->alarm_suppressed[channel] &= ~evbit;
754 
755 	if (!(data->alarm_monitored[channel] & evbit))
756 		return;
757 
758 	ret = bd79124_write_int_to_reg(data, BD79124_GET_LOW_LIMIT_REG(channel),
759 				       data->alarm_f_limit[channel]);
760 	if (ret)
761 		dev_warn(data->dev, "Low limit enabling failed for channel%d\n",
762 			 channel);
763 }
764 
765 static void bd79124_re_enable_hi(struct bd79124_data *data, unsigned int channel)
766 {
767 	int ret, evbit = BIT(IIO_EV_DIR_RISING);
768 
769 	/*
770 	 * We should not re-enable the event if user has disabled it while
771 	 * rate-limiting was enabled.
772 	 */
773 	if (!(data->alarm_suppressed[channel] & evbit))
774 		return;
775 
776 	data->alarm_suppressed[channel] &= ~evbit;
777 
778 	if (!(data->alarm_monitored[channel] & evbit))
779 		return;
780 
781 	ret = bd79124_write_int_to_reg(data, BD79124_GET_HIGH_LIMIT_REG(channel),
782 				       data->alarm_r_limit[channel]);
783 	if (ret)
784 		dev_warn(data->dev, "High limit enabling failed for channel%d\n",
785 			 channel);
786 }
787 
788 static void bd79124_alm_enable_worker(struct work_struct *work)
789 {
790 	int i;
791 	struct bd79124_data *data = container_of(work, struct bd79124_data,
792 						 alm_enable_work.work);
793 
794 	/* Take the mutex so there is no race with user disabling the alarm */
795 	guard(mutex)(&data->mutex);
796 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
797 		bd79124_re_enable_hi(data, i);
798 		bd79124_re_enable_lo(data, i);
799 	}
800 }
801 
802 static int __bd79124_event_ratelimit(struct bd79124_data *data, int reg,
803 				     unsigned int limit)
804 {
805 	int ret;
806 
807 	if (limit > BD79124_HIGH_LIMIT_MAX)
808 		return -EINVAL;
809 
810 	ret = bd79124_write_int_to_reg(data, reg, limit);
811 	if (ret)
812 		return ret;
813 
814 	/*
815 	 * We use 1 sec 'grace period'. At the moment I see no reason to make
816 	 * this user configurable. We need an ABI for this if configuration is
817 	 * needed.
818 	 */
819 	schedule_delayed_work(&data->alm_enable_work, msecs_to_jiffies(1000));
820 
821 	return 0;
822 }
823 
824 static int bd79124_event_ratelimit_hi(struct bd79124_data *data,
825 				      unsigned int channel)
826 {
827 	guard(mutex)(&data->mutex);
828 	data->alarm_suppressed[channel] |= BIT(IIO_EV_DIR_RISING);
829 
830 	return __bd79124_event_ratelimit(data,
831 					 BD79124_GET_HIGH_LIMIT_REG(channel),
832 					 BD79124_HIGH_LIMIT_MAX);
833 }
834 
835 static int bd79124_event_ratelimit_lo(struct bd79124_data *data,
836 				      unsigned int channel)
837 {
838 	guard(mutex)(&data->mutex);
839 	data->alarm_suppressed[channel] |= BIT(IIO_EV_DIR_FALLING);
840 
841 	return __bd79124_event_ratelimit(data,
842 					 BD79124_GET_LOW_LIMIT_REG(channel),
843 					 BD79124_LOW_LIMIT_MIN);
844 }
845 
846 static irqreturn_t bd79124_event_handler(int irq, void *priv)
847 {
848 	unsigned int i_hi, i_lo;
849 	int i, ret;
850 	struct iio_dev *iio_dev = priv;
851 	struct bd79124_data *data = iio_priv(iio_dev);
852 
853 	/*
854 	 * Return IRQ_NONE if bailing-out without acking. This allows the IRQ
855 	 * subsystem to disable the offending IRQ line if we get a hardware
856 	 * problem. This behaviour has saved my poor bottom a few times in the
857 	 * past as, instead of getting unusably unresponsive, the system has
858 	 * spilled out the magic words "...nobody cared".
859 	 */
860 	ret = regmap_read(data->map, BD79124_REG_EVENT_FLAG_HI, &i_hi);
861 	if (ret)
862 		return IRQ_NONE;
863 
864 	ret = regmap_read(data->map, BD79124_REG_EVENT_FLAG_LO, &i_lo);
865 	if (ret)
866 		return IRQ_NONE;
867 
868 	if (!i_lo && !i_hi)
869 		return IRQ_NONE;
870 
871 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
872 		u64 ecode;
873 
874 		if (BIT(i) & i_hi) {
875 			ecode = IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, i,
876 						     IIO_EV_TYPE_THRESH,
877 						     IIO_EV_DIR_RISING);
878 
879 			iio_push_event(iio_dev, ecode, data->timestamp);
880 			/*
881 			 * The BD79124 keeps the IRQ asserted for as long as
882 			 * the voltage exceeds the threshold. It causes the IRQ
883 			 * to keep firing.
884 			 *
885 			 * Disable the event for the channel and schedule the
886 			 * re-enabling the event later to prevent storm of
887 			 * events.
888 			 */
889 			ret = bd79124_event_ratelimit_hi(data, i);
890 			if (ret)
891 				return IRQ_NONE;
892 		}
893 		if (BIT(i) & i_lo) {
894 			ecode = IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, i,
895 						     IIO_EV_TYPE_THRESH,
896 						     IIO_EV_DIR_FALLING);
897 
898 			iio_push_event(iio_dev, ecode, data->timestamp);
899 			ret = bd79124_event_ratelimit_lo(data, i);
900 			if (ret)
901 				return IRQ_NONE;
902 		}
903 	}
904 
905 	ret = regmap_write(data->map, BD79124_REG_EVENT_FLAG_HI, i_hi);
906 	if (ret)
907 		return IRQ_NONE;
908 
909 	ret = regmap_write(data->map, BD79124_REG_EVENT_FLAG_LO, i_lo);
910 	if (ret)
911 		return IRQ_NONE;
912 
913 	return IRQ_HANDLED;
914 }
915 
916 static irqreturn_t bd79124_irq_handler(int irq, void *priv)
917 {
918 	struct iio_dev *iio_dev = priv;
919 	struct bd79124_data *data = iio_priv(iio_dev);
920 
921 	data->timestamp = iio_get_time_ns(iio_dev);
922 
923 	return IRQ_WAKE_THREAD;
924 }
925 
926 static int bd79124_chan_init(struct bd79124_data *data, int channel)
927 {
928 	int ret;
929 
930 	ret = bd79124_write_int_to_reg(data, BD79124_GET_HIGH_LIMIT_REG(channel),
931 				       BD79124_HIGH_LIMIT_MAX);
932 	if (ret)
933 		return ret;
934 
935 	return bd79124_write_int_to_reg(data, BD79124_GET_LOW_LIMIT_REG(channel),
936 					BD79124_LOW_LIMIT_MIN);
937 }
938 
939 static int bd79124_get_gpio_pins(const struct iio_chan_spec *cs, int num_channels)
940 {
941 	int i, gpio_channels;
942 
943 	/*
944 	 * Let's initialize the mux config to say that all 8 channels are
945 	 * GPIOs. Then we can just loop through the iio_chan_spec and clear the
946 	 * bits for found ADC channels.
947 	 */
948 	gpio_channels = GENMASK(7, 0);
949 	for (i = 0; i < num_channels; i++)
950 		gpio_channels &= ~BIT(cs[i].channel);
951 
952 	return gpio_channels;
953 }
954 
955 static int bd79124_hw_init(struct bd79124_data *data)
956 {
957 	unsigned int regval;
958 	int ret, i;
959 
960 	for (i = 0; i < BD79124_MAX_NUM_CHANNELS; i++) {
961 		ret = bd79124_chan_init(data, i);
962 		if (ret)
963 			return ret;
964 		data->alarm_r_limit[i] = BD79124_HIGH_LIMIT_MAX;
965 	}
966 	/* Stop auto sequencer */
967 	ret = regmap_clear_bits(data->map, BD79124_REG_SEQ_CFG,
968 				BD79124_MSK_SEQ_START);
969 	if (ret)
970 		return ret;
971 
972 	/* Enable writing the measured values to the registers */
973 	ret = regmap_set_bits(data->map, BD79124_REG_GEN_CFG,
974 			      BD79124_MSK_STATS_EN);
975 	if (ret)
976 		return ret;
977 
978 	/* Set no channels to be auto-measured */
979 	ret = regmap_write(data->map, BD79124_REG_AUTO_CHANNELS, 0x0);
980 	if (ret)
981 		return ret;
982 
983 	/* Set no channels to be manually measured */
984 	ret = regmap_write(data->map, BD79124_REG_MANUAL_CHANNELS, 0x0);
985 	if (ret)
986 		return ret;
987 
988 	regval = FIELD_PREP(BD79124_MSK_AUTO_INTERVAL, BD79124_INTERVAL_750_US);
989 	ret = regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
990 				 BD79124_MSK_AUTO_INTERVAL, regval);
991 	if (ret)
992 		return ret;
993 
994 	/* Sequencer mode to auto */
995 	ret = regmap_set_bits(data->map, BD79124_REG_SEQ_CFG,
996 			      BD79124_MSK_SEQ_SEQ);
997 	if (ret)
998 		return ret;
999 
1000 	/* Don't start the measurement */
1001 	regval = FIELD_PREP(BD79124_MSK_CONV_MODE, BD79124_CONV_MODE_MANSEQ);
1002 	return regmap_update_bits(data->map, BD79124_REG_OPMODE_CFG,
1003 				  BD79124_MSK_CONV_MODE, regval);
1004 }
1005 
1006 static int bd79124_probe(struct i2c_client *i2c)
1007 {
1008 	struct bd79124_data *data;
1009 	struct iio_dev *iio_dev;
1010 	const struct iio_chan_spec *template;
1011 	struct iio_chan_spec *cs;
1012 	struct device *dev = &i2c->dev;
1013 	unsigned int gpio_pins;
1014 	int ret;
1015 
1016 	iio_dev = devm_iio_device_alloc(dev, sizeof(*data));
1017 	if (!iio_dev)
1018 		return -ENOMEM;
1019 
1020 	data = iio_priv(iio_dev);
1021 	data->dev = dev;
1022 	data->map = devm_regmap_init_i2c(i2c, &bd79124_regmap);
1023 	if (IS_ERR(data->map))
1024 		return dev_err_probe(dev, PTR_ERR(data->map),
1025 				     "Failed to initialize Regmap\n");
1026 
1027 	ret = devm_regulator_get_enable_read_voltage(dev, "vdd");
1028 	if (ret < 0)
1029 		return dev_err_probe(dev, ret, "Failed to get the Vdd\n");
1030 
1031 	data->vmax = ret;
1032 
1033 	ret = devm_regulator_get_enable(dev, "iovdd");
1034 	if (ret < 0)
1035 		return dev_err_probe(dev, ret, "Failed to enable I/O voltage\n");
1036 
1037 	ret = devm_delayed_work_autocancel(dev, &data->alm_enable_work,
1038 					   bd79124_alm_enable_worker);
1039 	if (ret)
1040 		return ret;
1041 
1042 	if (i2c->irq) {
1043 		template = &bd79124_chan_template;
1044 	} else {
1045 		template = &bd79124_chan_template_noirq;
1046 		dev_dbg(dev, "No IRQ found, events disabled\n");
1047 	}
1048 
1049 	ret = devm_mutex_init(dev, &data->mutex);
1050 	if (ret)
1051 		return ret;
1052 
1053 	ret = devm_iio_adc_device_alloc_chaninfo_se(dev, template,
1054 		BD79124_MAX_NUM_CHANNELS - 1, &cs);
1055 	if (ret < 0) {
1056 		/* Register all pins as GPOs if there are no ADC channels */
1057 		if (ret == -ENOENT)
1058 			goto register_gpios;
1059 		return ret;
1060 	}
1061 	iio_dev->channels = cs;
1062 	iio_dev->num_channels = ret;
1063 	iio_dev->info = &bd79124_info;
1064 	iio_dev->name = "bd79124";
1065 	iio_dev->modes = INDIO_DIRECT_MODE;
1066 
1067 	ret = bd79124_hw_init(data);
1068 	if (ret)
1069 		return ret;
1070 
1071 	if (i2c->irq > 0) {
1072 		ret = devm_request_threaded_irq(dev, i2c->irq,
1073 			bd79124_irq_handler, &bd79124_event_handler,
1074 			IRQF_ONESHOT, "adc-thresh-alert", iio_dev);
1075 		if (ret)
1076 			return dev_err_probe(data->dev, ret,
1077 					     "Failed to register IRQ\n");
1078 	}
1079 
1080 	ret = devm_iio_device_register(data->dev, iio_dev);
1081 	if (ret)
1082 		return dev_err_probe(data->dev, ret, "Failed to register ADC\n");
1083 
1084 register_gpios:
1085 	gpio_pins = bd79124_get_gpio_pins(iio_dev->channels,
1086 					  iio_dev->num_channels);
1087 
1088 	/*
1089 	 * The mux should default to "all ADCs", but better to not trust it.
1090 	 * Thus we do set the mux even when we have only ADCs and no GPOs.
1091 	 */
1092 	ret = regmap_write(data->map, BD79124_REG_PINCFG, gpio_pins);
1093 	if (ret)
1094 		return ret;
1095 
1096 	/* No GPOs if all channels are reserved for ADC, so we're done. */
1097 	if (!gpio_pins)
1098 		return 0;
1099 
1100 	data->gpio_valid_mask = gpio_pins;
1101 	data->gc = bd79124gpo_chip;
1102 	data->gc.parent = dev;
1103 
1104 	return devm_gpiochip_add_data(dev, &data->gc, data);
1105 }
1106 
1107 static const struct of_device_id bd79124_of_match[] = {
1108 	{ .compatible = "rohm,bd79124" },
1109 	{ }
1110 };
1111 MODULE_DEVICE_TABLE(of, bd79124_of_match);
1112 
1113 static const struct i2c_device_id bd79124_id[] = {
1114 	{ .name = "bd79124" },
1115 	{ }
1116 };
1117 MODULE_DEVICE_TABLE(i2c, bd79124_id);
1118 
1119 static struct i2c_driver bd79124_driver = {
1120 	.driver = {
1121 		.name = "bd79124",
1122 		.of_match_table = bd79124_of_match,
1123 	},
1124 	.probe = bd79124_probe,
1125 	.id_table = bd79124_id,
1126 };
1127 module_i2c_driver(bd79124_driver);
1128 
1129 MODULE_AUTHOR("Matti Vaittinen <mazziesaccount@gmail.com>");
1130 MODULE_DESCRIPTION("Driver for ROHM BD79124 ADC");
1131 MODULE_LICENSE("GPL");
1132 MODULE_IMPORT_NS("IIO_DRIVER");
1133