xref: /linux/drivers/iio/resolver/ad2s1210.c (revision c5dbf04160005e07e8ca7232a7faa77ab1547ae0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ad2s1210.c support for the ADI Resolver to Digital Converters: AD2S1210
4  *
5  * Copyright (c) 2010-2010 Analog Devices Inc.
6  * Copyright (c) 2023 BayLibre, SAS
7  *
8  * Device register to IIO ABI mapping:
9  *
10  * Register                    | Addr | IIO ABI (sysfs)
11  * ----------------------------|------|-------------------------------------------
12  * DOS Overrange Threshold     | 0x89 | events/in_altvoltage0_thresh_rising_value
13  * DOS Mismatch Threshold      | 0x8A | events/in_altvoltage0_mag_rising_value
14  * DOS Reset Maximum Threshold | 0x8B | events/in_altvoltage0_mag_rising_reset_max
15  * DOS Reset Minimum Threshold | 0x8C | events/in_altvoltage0_mag_rising_reset_min
16  * LOT High Threshold          | 0x8D | events/in_angl1_thresh_rising_value
17  * LOT Low Threshold [1]       | 0x8E | events/in_angl1_thresh_rising_hysteresis
18  * Excitation Frequency        | 0x91 | out_altvoltage0_frequency
19  * Control                     | 0x92 | *as bit fields*
20  *   Phase lock range          | D5   | events/in_phase0_mag_rising_value
21  *   Hysteresis                | D4   | in_angl0_hysteresis
22  *   Encoder resolution        | D3:2 | *not implemented*
23  *   Resolution                | D1:0 | *device tree: assigned-resolution-bits*
24  * Soft Reset                  | 0xF0 | [2]
25  * Fault                       | 0xFF | *not implemented*
26  *
27  * [1]: The value written to the LOT low register is high value minus the
28  * hysteresis.
29  * [2]: Soft reset is performed when `out_altvoltage0_frequency` is written.
30  *
31  * Fault to event mapping:
32  *
33  * Fault                                   |    | Channel     | Type   | Direction
34  * ----------------------------------------|----|---------------------------------
35  * Sine/cosine inputs clipped [3]          | D7 | altvoltage1 | mag    | either
36  * Sine/cosine inputs below LOS            | D6 | altvoltage0 | thresh | falling
37  * Sine/cosine inputs exceed DOS overrange | D5 | altvoltage0 | thresh | rising
38  * Sine/cosine inputs exceed DOS mismatch  | D4 | altvoltage0 | mag    | rising
39  * Tracking error exceeds LOT              | D3 | angl1       | thresh | rising
40  * Velocity exceeds maximum tracking rate  | D2 | anglvel0    | mag    | rising
41  * Phase error exceeds phase lock range    | D1 | phase0      | mag    | rising
42  * Configuration parity error              | D0 | *writes to kernel log*
43  *
44  * [3]: The chip does not differentiate between fault on sine vs. cosine so
45  * there will also be an event on the altvoltage2 channel.
46  */
47 
48 #include <linux/bitfield.h>
49 #include <linux/bits.h>
50 #include <linux/cleanup.h>
51 #include <linux/clk.h>
52 #include <linux/delay.h>
53 #include <linux/device.h>
54 #include <linux/gpio/consumer.h>
55 #include <linux/module.h>
56 #include <linux/mutex.h>
57 #include <linux/regmap.h>
58 #include <linux/slab.h>
59 #include <linux/spi/spi.h>
60 #include <linux/sysfs.h>
61 #include <linux/types.h>
62 
63 #include <linux/iio/buffer.h>
64 #include <linux/iio/events.h>
65 #include <linux/iio/iio.h>
66 #include <linux/iio/sysfs.h>
67 #include <linux/iio/trigger_consumer.h>
68 #include <linux/iio/triggered_buffer.h>
69 
70 /* control register flags */
71 #define AD2S1210_ADDRESS_DATA		BIT(7)
72 #define AD2S1210_PHASE_LOCK_RANGE_44	BIT(5)
73 #define AD2S1210_ENABLE_HYSTERESIS	BIT(4)
74 #define AD2S1210_SET_ENRES		GENMASK(3, 2)
75 #define AD2S1210_SET_RES		GENMASK(1, 0)
76 
77 /* fault register flags */
78 #define AD2S1210_FAULT_CLIP		BIT(7)
79 #define AD2S1210_FAULT_LOS		BIT(6)
80 #define AD2S1210_FAULT_DOS_OVR		BIT(5)
81 #define AD2S1210_FAULT_DOS_MIS		BIT(4)
82 #define AD2S1210_FAULT_LOT		BIT(3)
83 #define AD2S1210_FAULT_VELOCITY		BIT(2)
84 #define AD2S1210_FAULT_PHASE		BIT(1)
85 #define AD2S1210_FAULT_CONFIG_PARITY	BIT(0)
86 
87 #define AD2S1210_REG_POSITION_MSB	0x80
88 #define AD2S1210_REG_POSITION_LSB	0x81
89 #define AD2S1210_REG_VELOCITY_MSB	0x82
90 #define AD2S1210_REG_VELOCITY_LSB	0x83
91 #define AD2S1210_REG_LOS_THRD		0x88
92 #define AD2S1210_REG_DOS_OVR_THRD	0x89
93 #define AD2S1210_REG_DOS_MIS_THRD	0x8A
94 #define AD2S1210_REG_DOS_RST_MAX_THRD	0x8B
95 #define AD2S1210_REG_DOS_RST_MIN_THRD	0x8C
96 #define AD2S1210_REG_LOT_HIGH_THRD	0x8D
97 #define AD2S1210_REG_LOT_LOW_THRD	0x8E
98 #define AD2S1210_REG_EXCIT_FREQ		0x91
99 #define AD2S1210_REG_CONTROL		0x92
100 #define AD2S1210_REG_SOFT_RESET		0xF0
101 #define AD2S1210_REG_FAULT		0xFF
102 
103 #define AD2S1210_MIN_CLKIN	6144000
104 #define AD2S1210_MAX_CLKIN	10240000
105 #define AD2S1210_MIN_EXCIT	2000
106 #define AD2S1210_DEF_EXCIT	10000
107 #define AD2S1210_MAX_EXCIT	20000
108 #define AD2S1210_MIN_FCW	0x4
109 #define AD2S1210_MAX_FCW	0x50
110 
111 /* 44 degrees ~= 0.767945 radians */
112 #define PHASE_44_DEG_TO_RAD_INT 0
113 #define PHASE_44_DEG_TO_RAD_MICRO 767945
114 /* 360 degrees ~= 6.283185 radians */
115 #define PHASE_360_DEG_TO_RAD_INT 6
116 #define PHASE_360_DEG_TO_RAD_MICRO 283185
117 
118 /* Threshold voltage registers have 1 LSB == 38 mV */
119 #define THRESHOLD_MILLIVOLT_PER_LSB 38
120 /* max voltage for threshold registers is 0x7F * 38 mV */
121 #define THRESHOLD_RANGE_STR "[0 38 4826]"
122 
123 #define FAULT_ONESHOT(bit, new, old) (new & bit && !(old & bit))
124 
125 enum ad2s1210_mode {
126 	MOD_POS = 0b00,
127 	MOD_VEL = 0b01,
128 	MOD_RESERVED = 0b10,
129 	MOD_CONFIG = 0b11,
130 };
131 
132 enum ad2s1210_resolution {
133 	AD2S1210_RES_10 = 0b00,
134 	AD2S1210_RES_12 = 0b01,
135 	AD2S1210_RES_14 = 0b10,
136 	AD2S1210_RES_16 = 0b11,
137 };
138 
139 struct ad2s1210_state {
140 	struct mutex lock;
141 	struct spi_device *sdev;
142 	/** GPIO pin connected to SAMPLE line. */
143 	struct gpio_desc *sample_gpio;
144 	/** GPIO pins connected to A0 and A1 lines. */
145 	struct gpio_descs *mode_gpios;
146 	/** Used to access config registers. */
147 	struct regmap *regmap;
148 	/** The external oscillator frequency in Hz. */
149 	unsigned long clkin_hz;
150 	/** Available raw hysteresis values based on resolution. */
151 	int hysteresis_available[2];
152 	/** The selected resolution */
153 	enum ad2s1210_resolution resolution;
154 	/** Copy of fault register from the previous read. */
155 	u8 prev_fault_flags;
156 	/** For reading raw sample value via SPI. */
157 	struct {
158 		__be16 raw;
159 		u8 fault;
160 	} sample __aligned(IIO_DMA_MINALIGN);
161 	/** Scan buffer */
162 	struct {
163 		__be16 chan[2];
164 		/* Ensure timestamp is naturally aligned. */
165 		s64 timestamp __aligned(8);
166 	} scan;
167 	/** SPI transmit buffer. */
168 	u8 rx[2];
169 	/** SPI receive buffer. */
170 	u8 tx[2];
171 };
172 
173 static int ad2s1210_set_mode(struct ad2s1210_state *st, enum ad2s1210_mode mode)
174 {
175 	struct gpio_descs *gpios = st->mode_gpios;
176 	DECLARE_BITMAP(bitmap, 2);
177 
178 	bitmap[0] = mode;
179 
180 	return gpiod_set_array_value(gpios->ndescs, gpios->desc, gpios->info,
181 				     bitmap);
182 }
183 
184 /*
185  * Writes the given data to the given register address.
186  *
187  * If the mode is configurable, the device will first be placed in
188  * configuration mode.
189  */
190 static int ad2s1210_regmap_reg_write(void *context, unsigned int reg,
191 				     unsigned int val)
192 {
193 	struct ad2s1210_state *st = context;
194 	struct spi_transfer xfers[] = {
195 		{
196 			.len = 1,
197 			.rx_buf = &st->rx[0],
198 			.tx_buf = &st->tx[0],
199 			.cs_change = 1,
200 		}, {
201 			.len = 1,
202 			.rx_buf = &st->rx[1],
203 			.tx_buf = &st->tx[1],
204 		},
205 	};
206 	int ret;
207 
208 	/* values can only be 7 bits, the MSB indicates an address */
209 	if (val & ~0x7F)
210 		return -EINVAL;
211 
212 	st->tx[0] = reg;
213 	st->tx[1] = val;
214 
215 	ret = ad2s1210_set_mode(st, MOD_CONFIG);
216 	if (ret < 0)
217 		return ret;
218 
219 	ret = spi_sync_transfer(st->sdev, xfers, ARRAY_SIZE(xfers));
220 	if (ret < 0)
221 		return ret;
222 
223 	/* soft reset also clears the fault register */
224 	if (reg == AD2S1210_REG_SOFT_RESET)
225 		st->prev_fault_flags = 0;
226 
227 	return 0;
228 }
229 
230 /*
231  * Reads value from one of the registers.
232  *
233  * If the mode is configurable, the device will first be placed in
234  * configuration mode.
235  */
236 static int ad2s1210_regmap_reg_read(void *context, unsigned int reg,
237 				    unsigned int *val)
238 {
239 	struct ad2s1210_state *st = context;
240 	struct spi_transfer xfers[] = {
241 		{
242 			.len = 1,
243 			.rx_buf = &st->rx[0],
244 			.tx_buf = &st->tx[0],
245 			.cs_change = 1,
246 		}, {
247 			.len = 1,
248 			.rx_buf = &st->rx[1],
249 			.tx_buf = &st->tx[1],
250 		},
251 	};
252 	int ret;
253 
254 	ret = ad2s1210_set_mode(st, MOD_CONFIG);
255 	if (ret < 0)
256 		return ret;
257 
258 	st->tx[0] = reg;
259 	/*
260 	 * Must be valid register address here otherwise this could write data.
261 	 * It doesn't matter which one as long as reading doesn't have side-
262 	 * effects.
263 	 */
264 	st->tx[1] = AD2S1210_REG_CONTROL;
265 
266 	ret = spi_sync_transfer(st->sdev, xfers, ARRAY_SIZE(xfers));
267 	if (ret < 0)
268 		return ret;
269 
270 	/* reading the fault register also clears it */
271 	if (reg == AD2S1210_REG_FAULT)
272 		st->prev_fault_flags = 0;
273 
274 	/*
275 	 * If the D7 bit is set on any read/write register, it indicates a
276 	 * parity error. The fault register is read-only and the D7 bit means
277 	 * something else there.
278 	 */
279 	if (reg != AD2S1210_REG_FAULT && st->rx[1] & AD2S1210_ADDRESS_DATA)
280 		return -EBADMSG;
281 
282 	*val = st->rx[1];
283 
284 	return 0;
285 }
286 
287 /*
288  * Toggles the SAMPLE line on the AD2S1210 to latch in the current position,
289  * velocity, and faults.
290  *
291  * Must be called with lock held.
292  */
293 static void ad2s1210_toggle_sample_line(struct ad2s1210_state *st)
294 {
295 	/*
296 	 * Datasheet specifies minimum hold time t16 = 2 * tck + 20 ns. So the
297 	 * longest time needed is when CLKIN is 6.144 MHz, in which case t16
298 	 * ~= 350 ns. The same delay is also needed before re-asserting the
299 	 * SAMPLE line.
300 	 */
301 	gpiod_set_value(st->sample_gpio, 1);
302 	ndelay(350);
303 	gpiod_set_value(st->sample_gpio, 0);
304 	ndelay(350);
305 }
306 
307 /*
308  * Sets the excitation frequency and performs software reset.
309  *
310  * Must be called with lock held.
311  */
312 static int ad2s1210_reinit_excitation_frequency(struct ad2s1210_state *st,
313 						u16 fexcit)
314 {
315 	/* Map resolution to settle time in milliseconds. */
316 	static const int track_time_ms[] = { 10, 20, 25, 60 };
317 	unsigned int ignored;
318 	int ret;
319 	u8 fcw;
320 
321 	fcw = fexcit * (1 << 15) / st->clkin_hz;
322 	if (fcw < AD2S1210_MIN_FCW || fcw > AD2S1210_MAX_FCW)
323 		return -ERANGE;
324 
325 	ret = regmap_write(st->regmap, AD2S1210_REG_EXCIT_FREQ, fcw);
326 	if (ret < 0)
327 		return ret;
328 
329 	/*
330 	 * Software reset reinitializes the excitation frequency output.
331 	 * It does not reset any of the configuration registers.
332 	 */
333 	ret = regmap_write(st->regmap, AD2S1210_REG_SOFT_RESET, 0);
334 	if (ret < 0)
335 		return ret;
336 
337 	/*
338 	 * Soft reset always triggers some faults due the change in the output
339 	 * signal so clear the faults too. We need to delay for some time
340 	 * (what datasheet calls t[track]) to allow things to settle before
341 	 * clearing the faults.
342 	 */
343 	msleep(track_time_ms[st->resolution] * 8192000 / st->clkin_hz);
344 
345 	/* Reading the fault register clears the faults. */
346 	ret = regmap_read(st->regmap, AD2S1210_REG_FAULT, &ignored);
347 	if (ret < 0)
348 		return ret;
349 
350 	/* Have to toggle sample line to get fault output pins to reset. */
351 	ad2s1210_toggle_sample_line(st);
352 
353 	return 0;
354 }
355 
356 static void ad2s1210_push_events(struct iio_dev *indio_dev,
357 				 u8 flags, s64 timestamp)
358 {
359 	struct ad2s1210_state *st = iio_priv(indio_dev);
360 
361 	/* Sine/cosine inputs clipped */
362 	if (FAULT_ONESHOT(AD2S1210_FAULT_CLIP, flags, st->prev_fault_flags)) {
363 		/*
364 		 * The chip does not differentiate between fault on sine vs.
365 		 * cosine channel so we just send an event on both channels.
366 		 */
367 		iio_push_event(indio_dev,
368 			       IIO_UNMOD_EVENT_CODE(IIO_ALTVOLTAGE, 1,
369 						    IIO_EV_TYPE_MAG,
370 						    IIO_EV_DIR_EITHER),
371 			       timestamp);
372 		iio_push_event(indio_dev,
373 			       IIO_UNMOD_EVENT_CODE(IIO_ALTVOLTAGE, 2,
374 						    IIO_EV_TYPE_MAG,
375 						    IIO_EV_DIR_EITHER),
376 			       timestamp);
377 	}
378 
379 	/* Sine/cosine inputs below LOS threshold */
380 	if (FAULT_ONESHOT(AD2S1210_FAULT_LOS, flags, st->prev_fault_flags))
381 		iio_push_event(indio_dev,
382 			       IIO_UNMOD_EVENT_CODE(IIO_ALTVOLTAGE, 0,
383 						    IIO_EV_TYPE_THRESH,
384 						    IIO_EV_DIR_FALLING),
385 			       timestamp);
386 
387 	/* Sine/cosine inputs exceed DOS overrange threshold */
388 	if (FAULT_ONESHOT(AD2S1210_FAULT_DOS_OVR, flags, st->prev_fault_flags))
389 		iio_push_event(indio_dev,
390 			       IIO_UNMOD_EVENT_CODE(IIO_ALTVOLTAGE, 0,
391 						    IIO_EV_TYPE_THRESH,
392 						    IIO_EV_DIR_RISING),
393 			       timestamp);
394 
395 	/* Sine/cosine inputs exceed DOS mismatch threshold */
396 	if (FAULT_ONESHOT(AD2S1210_FAULT_DOS_MIS, flags, st->prev_fault_flags))
397 		iio_push_event(indio_dev,
398 			       IIO_UNMOD_EVENT_CODE(IIO_ALTVOLTAGE, 0,
399 						    IIO_EV_TYPE_MAG,
400 						    IIO_EV_DIR_RISING),
401 			       timestamp);
402 
403 	/* Tracking error exceeds LOT threshold */
404 	if (FAULT_ONESHOT(AD2S1210_FAULT_LOT, flags, st->prev_fault_flags))
405 		iio_push_event(indio_dev,
406 			       IIO_UNMOD_EVENT_CODE(IIO_ANGL, 1,
407 						    IIO_EV_TYPE_THRESH,
408 						    IIO_EV_DIR_RISING),
409 			       timestamp);
410 
411 	/* Velocity exceeds maximum tracking rate */
412 	if (FAULT_ONESHOT(AD2S1210_FAULT_VELOCITY, flags, st->prev_fault_flags))
413 		iio_push_event(indio_dev,
414 			       IIO_UNMOD_EVENT_CODE(IIO_ANGL_VEL, 0,
415 						    IIO_EV_TYPE_THRESH,
416 						    IIO_EV_DIR_RISING),
417 			       timestamp);
418 
419 	/* Phase error exceeds phase lock range */
420 	if (FAULT_ONESHOT(AD2S1210_FAULT_PHASE, flags, st->prev_fault_flags))
421 		iio_push_event(indio_dev,
422 			       IIO_UNMOD_EVENT_CODE(IIO_PHASE, 0,
423 						    IIO_EV_TYPE_MAG,
424 						    IIO_EV_DIR_RISING),
425 			       timestamp);
426 
427 	/* Configuration parity error */
428 	if (FAULT_ONESHOT(AD2S1210_FAULT_CONFIG_PARITY, flags,
429 			  st->prev_fault_flags))
430 		/*
431 		 * Userspace should also get notified of this via error return
432 		 * when trying to write to any attribute that writes a register.
433 		 */
434 		dev_err_ratelimited(&indio_dev->dev,
435 				    "Configuration parity error\n");
436 
437 	st->prev_fault_flags = flags;
438 }
439 
440 static int ad2s1210_single_conversion(struct iio_dev *indio_dev,
441 				      struct iio_chan_spec const *chan,
442 				      int *val)
443 {
444 	struct ad2s1210_state *st = iio_priv(indio_dev);
445 	s64 timestamp;
446 	int ret;
447 
448 	guard(mutex)(&st->lock);
449 
450 	ad2s1210_toggle_sample_line(st);
451 	timestamp = iio_get_time_ns(indio_dev);
452 
453 	switch (chan->type) {
454 	case IIO_ANGL:
455 		ret = ad2s1210_set_mode(st, MOD_POS);
456 		break;
457 	case IIO_ANGL_VEL:
458 		ret = ad2s1210_set_mode(st, MOD_VEL);
459 		break;
460 	default:
461 		return -EINVAL;
462 	}
463 	if (ret < 0)
464 		return ret;
465 	ret = spi_read(st->sdev, &st->sample, 3);
466 	if (ret < 0)
467 		return ret;
468 
469 	switch (chan->type) {
470 	case IIO_ANGL:
471 		*val = be16_to_cpu(st->sample.raw);
472 		ret = IIO_VAL_INT;
473 		break;
474 	case IIO_ANGL_VEL:
475 		*val = (s16)be16_to_cpu(st->sample.raw);
476 		ret = IIO_VAL_INT;
477 		break;
478 	default:
479 		return -EINVAL;
480 	}
481 
482 	ad2s1210_push_events(indio_dev, st->sample.fault, timestamp);
483 
484 	return ret;
485 }
486 
487 static int ad2s1210_get_hysteresis(struct ad2s1210_state *st, int *val)
488 {
489 	int ret;
490 
491 	guard(mutex)(&st->lock);
492 	ret = regmap_test_bits(st->regmap, AD2S1210_REG_CONTROL,
493 			       AD2S1210_ENABLE_HYSTERESIS);
494 	if (ret < 0)
495 		return ret;
496 
497 	*val = ret << (2 * (AD2S1210_RES_16 - st->resolution));
498 	return IIO_VAL_INT;
499 }
500 
501 static int ad2s1210_set_hysteresis(struct ad2s1210_state *st, int val)
502 {
503 	guard(mutex)(&st->lock);
504 	return regmap_update_bits(st->regmap, AD2S1210_REG_CONTROL,
505 				  AD2S1210_ENABLE_HYSTERESIS,
506 				  val ? AD2S1210_ENABLE_HYSTERESIS : 0);
507 }
508 
509 static int ad2s1210_get_phase_lock_range(struct ad2s1210_state *st,
510 					 int *val, int *val2)
511 {
512 	int ret;
513 
514 	guard(mutex)(&st->lock);
515 	ret = regmap_test_bits(st->regmap, AD2S1210_REG_CONTROL,
516 			       AD2S1210_PHASE_LOCK_RANGE_44);
517 	if (ret < 0)
518 		return ret;
519 
520 	if (ret) {
521 		/* 44 degrees as radians */
522 		*val = PHASE_44_DEG_TO_RAD_INT;
523 		*val2 = PHASE_44_DEG_TO_RAD_MICRO;
524 	} else {
525 		/* 360 degrees as radians */
526 		*val = PHASE_360_DEG_TO_RAD_INT;
527 		*val2 = PHASE_360_DEG_TO_RAD_MICRO;
528 	}
529 
530 	return IIO_VAL_INT_PLUS_MICRO;
531 }
532 
533 static int ad2s1210_set_phase_lock_range(struct ad2s1210_state *st,
534 					 int val, int val2)
535 {
536 	int deg;
537 
538 	/* convert radians to degrees - only two allowable values */
539 	if (val == PHASE_44_DEG_TO_RAD_INT && val2 == PHASE_44_DEG_TO_RAD_MICRO)
540 		deg = 44;
541 	else if (val == PHASE_360_DEG_TO_RAD_INT &&
542 		 val2 == PHASE_360_DEG_TO_RAD_MICRO)
543 		deg = 360;
544 	else
545 		return -EINVAL;
546 
547 	guard(mutex)(&st->lock);
548 	return regmap_update_bits(st->regmap, AD2S1210_REG_CONTROL,
549 				  AD2S1210_PHASE_LOCK_RANGE_44,
550 				  deg == 44 ? AD2S1210_PHASE_LOCK_RANGE_44 : 0);
551 }
552 
553 /* map resolution to microradians/LSB for LOT registers */
554 static const int ad2s1210_lot_threshold_urad_per_lsb[] = {
555 	6184, /* 10-bit: ~0.35 deg/LSB, 45 deg max */
556 	2473, /* 12-bit: ~0.14 deg/LSB, 18 deg max */
557 	1237, /* 14-bit: ~0.07 deg/LSB, 9 deg max */
558 	1237, /* 16-bit: same as 14-bit */
559 };
560 
561 static int ad2s1210_get_voltage_threshold(struct ad2s1210_state *st,
562 					  unsigned int reg, int *val)
563 {
564 	unsigned int reg_val;
565 	int ret;
566 
567 	guard(mutex)(&st->lock);
568 	ret = regmap_read(st->regmap, reg, &reg_val);
569 	if (ret < 0)
570 		return ret;
571 
572 	*val = reg_val * THRESHOLD_MILLIVOLT_PER_LSB;
573 	return IIO_VAL_INT;
574 }
575 
576 static int ad2s1210_set_voltage_threshold(struct ad2s1210_state *st,
577 					  unsigned int reg, int val)
578 {
579 	unsigned int reg_val;
580 
581 	reg_val = val / THRESHOLD_MILLIVOLT_PER_LSB;
582 
583 	guard(mutex)(&st->lock);
584 	return regmap_write(st->regmap, reg, reg_val);
585 }
586 
587 static int ad2s1210_get_lot_high_threshold(struct ad2s1210_state *st,
588 					   int *val, int *val2)
589 {
590 	unsigned int reg_val;
591 	int ret;
592 
593 	guard(mutex)(&st->lock);
594 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_HIGH_THRD, &reg_val);
595 	if (ret < 0)
596 		return ret;
597 
598 	*val = 0;
599 	*val2 = reg_val * ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
600 	return IIO_VAL_INT_PLUS_MICRO;
601 }
602 
603 static int ad2s1210_set_lot_high_threshold(struct ad2s1210_state *st,
604 					   int val, int val2)
605 {
606 	unsigned int high_reg_val, low_reg_val, hysteresis;
607 	int ret;
608 
609 	/* all valid values are between 0 and pi/4 radians */
610 	if (val != 0)
611 		return -EINVAL;
612 
613 	guard(mutex)(&st->lock);
614 	/*
615 	 * We need to read both high and low registers first so we can preserve
616 	 * the hysteresis.
617 	 */
618 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_HIGH_THRD, &high_reg_val);
619 	if (ret < 0)
620 		return ret;
621 
622 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_LOW_THRD, &low_reg_val);
623 	if (ret < 0)
624 		return ret;
625 
626 	hysteresis = high_reg_val - low_reg_val;
627 	high_reg_val = val2 / ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
628 	low_reg_val = high_reg_val - hysteresis;
629 
630 	ret = regmap_write(st->regmap, AD2S1210_REG_LOT_HIGH_THRD, high_reg_val);
631 	if (ret < 0)
632 		return ret;
633 
634 	return regmap_write(st->regmap, AD2S1210_REG_LOT_LOW_THRD, low_reg_val);
635 }
636 
637 static int ad2s1210_get_lot_low_threshold(struct ad2s1210_state *st,
638 					  int *val, int *val2)
639 {
640 	unsigned int high_reg_val, low_reg_val;
641 	int ret;
642 
643 	guard(mutex)(&st->lock);
644 
645 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_HIGH_THRD, &high_reg_val);
646 	if (ret < 0)
647 		return ret;
648 
649 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_LOW_THRD, &low_reg_val);
650 	if (ret < 0)
651 		return ret;
652 
653 	/* sysfs value is hysteresis rather than actual low value */
654 	*val = 0;
655 	*val2 = (high_reg_val - low_reg_val) *
656 		ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
657 	return IIO_VAL_INT_PLUS_MICRO;
658 }
659 
660 static int ad2s1210_set_lot_low_threshold(struct ad2s1210_state *st,
661 					  int val, int val2)
662 {
663 	unsigned int reg_val, hysteresis;
664 	int ret;
665 
666 	/* all valid values are between 0 and pi/4 radians */
667 	if (val != 0)
668 		return -EINVAL;
669 
670 	hysteresis = val2 / ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
671 
672 	guard(mutex)(&st->lock);
673 
674 	ret = regmap_read(st->regmap, AD2S1210_REG_LOT_HIGH_THRD, &reg_val);
675 	if (ret < 0)
676 		return ret;
677 
678 	return regmap_write(st->regmap, AD2S1210_REG_LOT_LOW_THRD,
679 			   reg_val - hysteresis);
680 }
681 
682 static int ad2s1210_get_excitation_frequency(struct ad2s1210_state *st, int *val)
683 {
684 	unsigned int reg_val;
685 	int ret;
686 
687 	guard(mutex)(&st->lock);
688 
689 	ret = regmap_read(st->regmap, AD2S1210_REG_EXCIT_FREQ, &reg_val);
690 	if (ret < 0)
691 		return ret;
692 
693 	*val = reg_val * st->clkin_hz / (1 << 15);
694 	return IIO_VAL_INT;
695 }
696 
697 static int ad2s1210_set_excitation_frequency(struct ad2s1210_state *st, int val)
698 {
699 	if (val < AD2S1210_MIN_EXCIT || val > AD2S1210_MAX_EXCIT)
700 		return -EINVAL;
701 
702 	guard(mutex)(&st->lock);
703 	return ad2s1210_reinit_excitation_frequency(st, val);
704 }
705 
706 static const int ad2s1210_velocity_scale[] = {
707 	17089132, /* 8.192MHz / (2*pi * 2500 / 2^15) */
708 	42722830, /* 8.192MHz / (2*pi * 1000 / 2^15) */
709 	85445659, /* 8.192MHz / (2*pi * 500 / 2^15) */
710 	341782638, /* 8.192MHz / (2*pi * 125 / 2^15) */
711 };
712 
713 static int ad2s1210_read_raw(struct iio_dev *indio_dev,
714 			     struct iio_chan_spec const *chan,
715 			     int *val,
716 			     int *val2,
717 			     long mask)
718 {
719 	struct ad2s1210_state *st = iio_priv(indio_dev);
720 
721 	switch (mask) {
722 	case IIO_CHAN_INFO_RAW:
723 		return ad2s1210_single_conversion(indio_dev, chan, val);
724 	case IIO_CHAN_INFO_SCALE:
725 		switch (chan->type) {
726 		case IIO_ANGL:
727 			/* approx 0.3 arc min converted to radians */
728 			*val = 0;
729 			*val2 = 95874;
730 			return IIO_VAL_INT_PLUS_NANO;
731 		case IIO_ANGL_VEL:
732 			*val = st->clkin_hz;
733 			*val2 = ad2s1210_velocity_scale[st->resolution];
734 			return IIO_VAL_FRACTIONAL;
735 		default:
736 			return -EINVAL;
737 		}
738 	case IIO_CHAN_INFO_FREQUENCY:
739 		switch (chan->type) {
740 		case IIO_ALTVOLTAGE:
741 			return ad2s1210_get_excitation_frequency(st, val);
742 		default:
743 			return -EINVAL;
744 		}
745 	case IIO_CHAN_INFO_HYSTERESIS:
746 		switch (chan->type) {
747 		case IIO_ANGL:
748 			return ad2s1210_get_hysteresis(st, val);
749 		default:
750 			return -EINVAL;
751 		}
752 	default:
753 		return -EINVAL;
754 	}
755 }
756 
757 static int ad2s1210_read_avail(struct iio_dev *indio_dev,
758 			       struct iio_chan_spec const *chan,
759 			       const int **vals, int *type,
760 			       int *length, long mask)
761 {
762 	static const int excitation_frequency_available[] = {
763 		AD2S1210_MIN_EXCIT,
764 		250, /* step */
765 		AD2S1210_MAX_EXCIT,
766 	};
767 
768 	struct ad2s1210_state *st = iio_priv(indio_dev);
769 
770 	switch (mask) {
771 	case IIO_CHAN_INFO_FREQUENCY:
772 		switch (chan->type) {
773 		case IIO_ALTVOLTAGE:
774 			*type = IIO_VAL_INT;
775 			*vals = excitation_frequency_available;
776 			return IIO_AVAIL_RANGE;
777 		default:
778 			return -EINVAL;
779 		}
780 	case IIO_CHAN_INFO_HYSTERESIS:
781 		switch (chan->type) {
782 		case IIO_ANGL:
783 			*vals = st->hysteresis_available;
784 			*type = IIO_VAL_INT;
785 			*length = ARRAY_SIZE(st->hysteresis_available);
786 			return IIO_AVAIL_LIST;
787 		default:
788 			return -EINVAL;
789 		}
790 	default:
791 		return -EINVAL;
792 	}
793 }
794 
795 static int ad2s1210_write_raw(struct iio_dev *indio_dev,
796 			      struct iio_chan_spec const *chan,
797 			      int val, int val2, long mask)
798 {
799 	struct ad2s1210_state *st = iio_priv(indio_dev);
800 
801 	switch (mask) {
802 	case IIO_CHAN_INFO_FREQUENCY:
803 		switch (chan->type) {
804 		case IIO_ALTVOLTAGE:
805 			return ad2s1210_set_excitation_frequency(st, val);
806 		default:
807 			return -EINVAL;
808 		}
809 	case IIO_CHAN_INFO_HYSTERESIS:
810 		switch (chan->type) {
811 		case IIO_ANGL:
812 			return ad2s1210_set_hysteresis(st, val);
813 		default:
814 			return -EINVAL;
815 		}
816 	default:
817 		return -EINVAL;
818 	}
819 }
820 
821 static const struct iio_event_spec ad2s1210_position_event_spec[] = {
822 	{
823 		/* Tracking error exceeds LOT threshold fault. */
824 		.type = IIO_EV_TYPE_THRESH,
825 		.dir = IIO_EV_DIR_RISING,
826 		.mask_separate =
827 			/* Loss of tracking high threshold. */
828 			BIT(IIO_EV_INFO_VALUE) |
829 			/* Loss of tracking low threshold. */
830 			BIT(IIO_EV_INFO_HYSTERESIS),
831 	},
832 };
833 
834 static const struct iio_event_spec ad2s1210_velocity_event_spec[] = {
835 	{
836 		/* Velocity exceeds maximum tracking rate fault. */
837 		.type = IIO_EV_TYPE_MAG,
838 		.dir = IIO_EV_DIR_RISING,
839 	},
840 };
841 
842 static const struct iio_event_spec ad2s1210_phase_event_spec[] = {
843 	{
844 		/* Phase error fault. */
845 		.type = IIO_EV_TYPE_MAG,
846 		.dir = IIO_EV_DIR_RISING,
847 		/* Phase lock range. */
848 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
849 	},
850 };
851 
852 static const struct iio_event_spec ad2s1210_monitor_signal_event_spec[] = {
853 	{
854 		/* Sine/cosine below LOS threshold fault. */
855 		.type = IIO_EV_TYPE_THRESH,
856 		.dir = IIO_EV_DIR_FALLING,
857 		/* Loss of signal threshold. */
858 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
859 	},
860 	{
861 		/* Sine/cosine DOS overrange fault.*/
862 		.type = IIO_EV_TYPE_THRESH,
863 		.dir = IIO_EV_DIR_RISING,
864 		/* Degredation of signal overrange threshold. */
865 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
866 	},
867 	{
868 		/* Sine/cosine DOS mismatch fault.*/
869 		.type = IIO_EV_TYPE_MAG,
870 		.dir = IIO_EV_DIR_RISING,
871 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
872 	},
873 };
874 
875 static const struct iio_event_spec ad2s1210_sin_cos_event_spec[] = {
876 	{
877 		/* Sine/cosine clipping fault. */
878 		.type = IIO_EV_TYPE_MAG,
879 		.dir = IIO_EV_DIR_EITHER,
880 	},
881 };
882 
883 static const struct iio_chan_spec ad2s1210_channels[] = {
884 	{
885 		.type = IIO_ANGL,
886 		.indexed = 1,
887 		.channel = 0,
888 		.scan_index = 0,
889 		.scan_type = {
890 			.sign = 'u',
891 			.realbits = 16,
892 			.storagebits = 16,
893 			.endianness = IIO_BE,
894 		},
895 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
896 				      BIT(IIO_CHAN_INFO_SCALE) |
897 				      BIT(IIO_CHAN_INFO_HYSTERESIS),
898 		.info_mask_separate_available =
899 					BIT(IIO_CHAN_INFO_HYSTERESIS),
900 	}, {
901 		.type = IIO_ANGL_VEL,
902 		.indexed = 1,
903 		.channel = 0,
904 		.scan_index = 1,
905 		.scan_type = {
906 			.sign = 's',
907 			.realbits = 16,
908 			.storagebits = 16,
909 			.endianness = IIO_BE,
910 		},
911 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
912 				      BIT(IIO_CHAN_INFO_SCALE),
913 		.event_spec = ad2s1210_velocity_event_spec,
914 		.num_event_specs = ARRAY_SIZE(ad2s1210_velocity_event_spec),
915 	},
916 	IIO_CHAN_SOFT_TIMESTAMP(2),
917 	{
918 		/* used to configure LOT thresholds and get tracking error */
919 		.type = IIO_ANGL,
920 		.indexed = 1,
921 		.channel = 1,
922 		.scan_index = -1,
923 		.event_spec = ad2s1210_position_event_spec,
924 		.num_event_specs = ARRAY_SIZE(ad2s1210_position_event_spec),
925 	},
926 	{
927 		/* used to configure phase lock range and get phase lock error */
928 		.type = IIO_PHASE,
929 		.indexed = 1,
930 		.channel = 0,
931 		.scan_index = -1,
932 		.event_spec = ad2s1210_phase_event_spec,
933 		.num_event_specs = ARRAY_SIZE(ad2s1210_phase_event_spec),
934 	}, {
935 		/* excitation frequency output */
936 		.type = IIO_ALTVOLTAGE,
937 		.indexed = 1,
938 		.channel = 0,
939 		.output = 1,
940 		.scan_index = -1,
941 		.info_mask_separate = BIT(IIO_CHAN_INFO_FREQUENCY),
942 		.info_mask_separate_available = BIT(IIO_CHAN_INFO_FREQUENCY),
943 	}, {
944 		/* monitor signal */
945 		.type = IIO_ALTVOLTAGE,
946 		.indexed = 1,
947 		.channel = 0,
948 		.scan_index = -1,
949 		.event_spec = ad2s1210_monitor_signal_event_spec,
950 		.num_event_specs = ARRAY_SIZE(ad2s1210_monitor_signal_event_spec),
951 	}, {
952 		/* sine input */
953 		.type = IIO_ALTVOLTAGE,
954 		.indexed = 1,
955 		.channel = 1,
956 		.scan_index = -1,
957 		.event_spec = ad2s1210_sin_cos_event_spec,
958 		.num_event_specs = ARRAY_SIZE(ad2s1210_sin_cos_event_spec),
959 	}, {
960 		/* cosine input */
961 		.type = IIO_ALTVOLTAGE,
962 		.indexed = 1,
963 		.channel = 2,
964 		.scan_index = -1,
965 		.event_spec = ad2s1210_sin_cos_event_spec,
966 		.num_event_specs = ARRAY_SIZE(ad2s1210_sin_cos_event_spec),
967 	},
968 };
969 
970 static ssize_t event_attr_voltage_reg_show(struct device *dev,
971 					   struct device_attribute *attr,
972 					   char *buf)
973 {
974 	struct ad2s1210_state *st = iio_priv(dev_to_iio_dev(dev));
975 	struct iio_dev_attr *iattr = to_iio_dev_attr(attr);
976 	unsigned int value;
977 	int ret;
978 
979 	guard(mutex)(&st->lock);
980 	ret = regmap_read(st->regmap, iattr->address, &value);
981 	if (ret < 0)
982 		return ret;
983 
984 	return sprintf(buf, "%d\n", value * THRESHOLD_MILLIVOLT_PER_LSB);
985 }
986 
987 static ssize_t event_attr_voltage_reg_store(struct device *dev,
988 					    struct device_attribute *attr,
989 					    const char *buf, size_t len)
990 {
991 	struct ad2s1210_state *st = iio_priv(dev_to_iio_dev(dev));
992 	struct iio_dev_attr *iattr = to_iio_dev_attr(attr);
993 	u16 data;
994 	int ret;
995 
996 	ret = kstrtou16(buf, 10, &data);
997 	if (ret)
998 		return -EINVAL;
999 
1000 	guard(mutex)(&st->lock);
1001 	ret = regmap_write(st->regmap, iattr->address,
1002 			   data / THRESHOLD_MILLIVOLT_PER_LSB);
1003 	if (ret < 0)
1004 		return ret;
1005 
1006 	return len;
1007 }
1008 
1009 static ssize_t
1010 in_angl1_thresh_rising_value_available_show(struct device *dev,
1011 					    struct device_attribute *attr,
1012 					    char *buf)
1013 {
1014 	struct ad2s1210_state *st = iio_priv(dev_to_iio_dev(dev));
1015 	int step = ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
1016 
1017 	return sysfs_emit(buf, "[0 0.%06d 0.%06d]\n", step, step * 0x7F);
1018 }
1019 
1020 static ssize_t
1021 in_angl1_thresh_rising_hysteresis_available_show(struct device *dev,
1022 						 struct device_attribute *attr,
1023 						 char *buf)
1024 {
1025 	struct ad2s1210_state *st = iio_priv(dev_to_iio_dev(dev));
1026 	int step = ad2s1210_lot_threshold_urad_per_lsb[st->resolution];
1027 
1028 	return sysfs_emit(buf, "[0 0.%06d 0.%06d]\n", step, step * 0x7F);
1029 }
1030 
1031 static IIO_CONST_ATTR(in_phase0_mag_rising_value_available,
1032 		      __stringify(PHASE_44_DEG_TO_RAD_INT) "."
1033 		      __stringify(PHASE_44_DEG_TO_RAD_MICRO) " "
1034 		      __stringify(PHASE_360_DEG_TO_RAD_INT) "."
1035 		      __stringify(PHASE_360_DEG_TO_RAD_MICRO));
1036 static IIO_CONST_ATTR(in_altvoltage0_thresh_falling_value_available,
1037 		      THRESHOLD_RANGE_STR);
1038 static IIO_CONST_ATTR(in_altvoltage0_thresh_rising_value_available,
1039 		      THRESHOLD_RANGE_STR);
1040 static IIO_CONST_ATTR(in_altvoltage0_mag_rising_value_available,
1041 		      THRESHOLD_RANGE_STR);
1042 static IIO_DEVICE_ATTR(in_altvoltage0_mag_rising_reset_max, 0644,
1043 		       event_attr_voltage_reg_show, event_attr_voltage_reg_store,
1044 		       AD2S1210_REG_DOS_RST_MAX_THRD);
1045 static IIO_CONST_ATTR(in_altvoltage0_mag_rising_reset_max_available, THRESHOLD_RANGE_STR);
1046 static IIO_DEVICE_ATTR(in_altvoltage0_mag_rising_reset_min, 0644,
1047 		       event_attr_voltage_reg_show, event_attr_voltage_reg_store,
1048 		       AD2S1210_REG_DOS_RST_MIN_THRD);
1049 static IIO_CONST_ATTR(in_altvoltage0_mag_rising_reset_min_available, THRESHOLD_RANGE_STR);
1050 static IIO_DEVICE_ATTR_RO(in_angl1_thresh_rising_value_available, 0);
1051 static IIO_DEVICE_ATTR_RO(in_angl1_thresh_rising_hysteresis_available, 0);
1052 
1053 static struct attribute *ad2s1210_event_attributes[] = {
1054 	&iio_const_attr_in_phase0_mag_rising_value_available.dev_attr.attr,
1055 	&iio_const_attr_in_altvoltage0_thresh_falling_value_available.dev_attr.attr,
1056 	&iio_const_attr_in_altvoltage0_thresh_rising_value_available.dev_attr.attr,
1057 	&iio_const_attr_in_altvoltage0_mag_rising_value_available.dev_attr.attr,
1058 	&iio_dev_attr_in_altvoltage0_mag_rising_reset_max.dev_attr.attr,
1059 	&iio_const_attr_in_altvoltage0_mag_rising_reset_max_available.dev_attr.attr,
1060 	&iio_dev_attr_in_altvoltage0_mag_rising_reset_min.dev_attr.attr,
1061 	&iio_const_attr_in_altvoltage0_mag_rising_reset_min_available.dev_attr.attr,
1062 	&iio_dev_attr_in_angl1_thresh_rising_value_available.dev_attr.attr,
1063 	&iio_dev_attr_in_angl1_thresh_rising_hysteresis_available.dev_attr.attr,
1064 	NULL,
1065 };
1066 
1067 static const struct attribute_group ad2s1210_event_attribute_group = {
1068 	.attrs = ad2s1210_event_attributes,
1069 };
1070 
1071 static int ad2s1210_initial(struct ad2s1210_state *st)
1072 {
1073 	unsigned int data;
1074 	int ret;
1075 
1076 	guard(mutex)(&st->lock);
1077 
1078 	/* Use default config register value plus resolution from devicetree. */
1079 	data = FIELD_PREP(AD2S1210_PHASE_LOCK_RANGE_44, 1);
1080 	data |= FIELD_PREP(AD2S1210_ENABLE_HYSTERESIS, 1);
1081 	data |= FIELD_PREP(AD2S1210_SET_ENRES, 0x3);
1082 	data |= FIELD_PREP(AD2S1210_SET_RES, st->resolution);
1083 
1084 	ret = regmap_write(st->regmap, AD2S1210_REG_CONTROL, data);
1085 	if (ret < 0)
1086 		return ret;
1087 
1088 	return ad2s1210_reinit_excitation_frequency(st, AD2S1210_DEF_EXCIT);
1089 }
1090 
1091 static int ad2s1210_read_label(struct iio_dev *indio_dev,
1092 			       struct iio_chan_spec const *chan,
1093 			       char *label)
1094 {
1095 	if (chan->type == IIO_ANGL) {
1096 		if (chan->channel == 0)
1097 			return sprintf(label, "position\n");
1098 		if (chan->channel == 1)
1099 			return sprintf(label, "tracking error\n");
1100 	}
1101 	if (chan->type == IIO_ANGL_VEL)
1102 		return sprintf(label, "velocity\n");
1103 	if (chan->type == IIO_PHASE)
1104 		return sprintf(label, "synthetic reference\n");
1105 	if (chan->type == IIO_ALTVOLTAGE) {
1106 		if (chan->output)
1107 			return sprintf(label, "excitation\n");
1108 		if (chan->channel == 0)
1109 			return sprintf(label, "monitor signal\n");
1110 		if (chan->channel == 1)
1111 			return sprintf(label, "cosine\n");
1112 		if (chan->channel == 2)
1113 			return sprintf(label, "sine\n");
1114 	}
1115 
1116 	return -EINVAL;
1117 }
1118 
1119 static int ad2s1210_read_event_value(struct iio_dev *indio_dev,
1120 				     const struct iio_chan_spec *chan,
1121 				     enum iio_event_type type,
1122 				     enum iio_event_direction dir,
1123 				     enum iio_event_info info,
1124 				     int *val, int *val2)
1125 {
1126 	struct ad2s1210_state *st = iio_priv(indio_dev);
1127 
1128 	switch (chan->type) {
1129 	case IIO_ANGL:
1130 		switch (info) {
1131 		case IIO_EV_INFO_VALUE:
1132 			return ad2s1210_get_lot_high_threshold(st, val, val2);
1133 		case IIO_EV_INFO_HYSTERESIS:
1134 			return ad2s1210_get_lot_low_threshold(st, val, val2);
1135 		default:
1136 			return -EINVAL;
1137 		}
1138 	case IIO_ALTVOLTAGE:
1139 		if (chan->output)
1140 			return -EINVAL;
1141 		if (type == IIO_EV_TYPE_THRESH && dir == IIO_EV_DIR_FALLING)
1142 			return ad2s1210_get_voltage_threshold(st,
1143 						AD2S1210_REG_LOS_THRD, val);
1144 		if (type == IIO_EV_TYPE_THRESH && dir == IIO_EV_DIR_RISING)
1145 			return ad2s1210_get_voltage_threshold(st,
1146 						AD2S1210_REG_DOS_OVR_THRD, val);
1147 		if (type == IIO_EV_TYPE_MAG)
1148 			return ad2s1210_get_voltage_threshold(st,
1149 						AD2S1210_REG_DOS_MIS_THRD, val);
1150 		return -EINVAL;
1151 	case IIO_PHASE:
1152 		return ad2s1210_get_phase_lock_range(st, val, val2);
1153 	default:
1154 		return -EINVAL;
1155 	}
1156 }
1157 
1158 static int ad2s1210_write_event_value(struct iio_dev *indio_dev,
1159 				      const struct iio_chan_spec *chan,
1160 				      enum iio_event_type type,
1161 				      enum iio_event_direction dir,
1162 				      enum iio_event_info info,
1163 				      int val, int val2)
1164 {
1165 	struct ad2s1210_state *st = iio_priv(indio_dev);
1166 
1167 	switch (chan->type) {
1168 	case IIO_ANGL:
1169 		switch (info) {
1170 		case IIO_EV_INFO_VALUE:
1171 			return ad2s1210_set_lot_high_threshold(st, val, val2);
1172 		case IIO_EV_INFO_HYSTERESIS:
1173 			return ad2s1210_set_lot_low_threshold(st, val, val2);
1174 		default:
1175 			return -EINVAL;
1176 		}
1177 	case IIO_ALTVOLTAGE:
1178 		if (chan->output)
1179 			return -EINVAL;
1180 		if (type == IIO_EV_TYPE_THRESH && dir == IIO_EV_DIR_FALLING)
1181 			return ad2s1210_set_voltage_threshold(st,
1182 						AD2S1210_REG_LOS_THRD, val);
1183 		if (type == IIO_EV_TYPE_THRESH && dir == IIO_EV_DIR_RISING)
1184 			return ad2s1210_set_voltage_threshold(st,
1185 						AD2S1210_REG_DOS_OVR_THRD, val);
1186 		if (type == IIO_EV_TYPE_MAG)
1187 			return ad2s1210_set_voltage_threshold(st,
1188 						AD2S1210_REG_DOS_MIS_THRD, val);
1189 		return -EINVAL;
1190 	case IIO_PHASE:
1191 		return ad2s1210_set_phase_lock_range(st, val, val2);
1192 	default:
1193 		return -EINVAL;
1194 	}
1195 }
1196 
1197 static int ad2s1210_read_event_label(struct iio_dev *indio_dev,
1198 				     struct iio_chan_spec const *chan,
1199 				     enum iio_event_type type,
1200 				     enum iio_event_direction dir,
1201 				     char *label)
1202 {
1203 	if (chan->type == IIO_ANGL)
1204 		return sprintf(label, "LOT\n");
1205 	if (chan->type == IIO_ANGL_VEL)
1206 		return sprintf(label, "max tracking rate\n");
1207 	if (chan->type == IIO_PHASE)
1208 		return sprintf(label, "phase lock\n");
1209 	if (chan->type == IIO_ALTVOLTAGE) {
1210 		if (chan->channel == 0) {
1211 			if (type == IIO_EV_TYPE_THRESH &&
1212 			    dir == IIO_EV_DIR_FALLING)
1213 				return sprintf(label, "LOS\n");
1214 			if (type == IIO_EV_TYPE_THRESH &&
1215 			    dir == IIO_EV_DIR_RISING)
1216 				return sprintf(label, "DOS overrange\n");
1217 			if (type == IIO_EV_TYPE_MAG)
1218 				return sprintf(label, "DOS mismatch\n");
1219 		}
1220 		if (chan->channel == 1 || chan->channel == 2)
1221 			return sprintf(label, "clipped\n");
1222 	}
1223 
1224 	return -EINVAL;
1225 }
1226 
1227 static int ad2s1210_debugfs_reg_access(struct iio_dev *indio_dev,
1228 				       unsigned int reg, unsigned int writeval,
1229 				       unsigned int *readval)
1230 {
1231 	struct ad2s1210_state *st = iio_priv(indio_dev);
1232 
1233 	guard(mutex)(&st->lock);
1234 
1235 	if (readval)
1236 		return regmap_read(st->regmap, reg, readval);
1237 
1238 	return regmap_write(st->regmap, reg, writeval);
1239 }
1240 
1241 static irqreturn_t ad2s1210_trigger_handler(int irq, void *p)
1242 {
1243 	struct iio_poll_func *pf = p;
1244 	struct iio_dev *indio_dev = pf->indio_dev;
1245 	struct ad2s1210_state *st = iio_priv(indio_dev);
1246 	size_t chan = 0;
1247 	int ret;
1248 
1249 	guard(mutex)(&st->lock);
1250 
1251 	memset(&st->scan, 0, sizeof(st->scan));
1252 	ad2s1210_toggle_sample_line(st);
1253 
1254 	if (test_bit(0, indio_dev->active_scan_mask)) {
1255 		ret = ad2s1210_set_mode(st, MOD_POS);
1256 		if (ret < 0)
1257 			goto error_ret;
1258 
1259 		ret = spi_read(st->sdev, &st->sample, 3);
1260 		if (ret < 0)
1261 			goto error_ret;
1262 
1263 		memcpy(&st->scan.chan[chan++], &st->sample.raw, 2);
1264 	}
1265 
1266 	if (test_bit(1, indio_dev->active_scan_mask)) {
1267 		ret = ad2s1210_set_mode(st, MOD_VEL);
1268 		if (ret < 0)
1269 			goto error_ret;
1270 
1271 		ret = spi_read(st->sdev, &st->sample, 3);
1272 		if (ret < 0)
1273 			goto error_ret;
1274 
1275 		memcpy(&st->scan.chan[chan++], &st->sample.raw, 2);
1276 	}
1277 
1278 	ad2s1210_push_events(indio_dev, st->sample.fault, pf->timestamp);
1279 	iio_push_to_buffers_with_timestamp(indio_dev, &st->scan, pf->timestamp);
1280 
1281 error_ret:
1282 	iio_trigger_notify_done(indio_dev->trig);
1283 
1284 	return IRQ_HANDLED;
1285 }
1286 
1287 static const struct iio_info ad2s1210_info = {
1288 	.event_attrs = &ad2s1210_event_attribute_group,
1289 	.read_raw = ad2s1210_read_raw,
1290 	.read_avail = ad2s1210_read_avail,
1291 	.write_raw = ad2s1210_write_raw,
1292 	.read_label = ad2s1210_read_label,
1293 	.read_event_value = ad2s1210_read_event_value,
1294 	.write_event_value = ad2s1210_write_event_value,
1295 	.read_event_label = ad2s1210_read_event_label,
1296 	.debugfs_reg_access = &ad2s1210_debugfs_reg_access,
1297 };
1298 
1299 static int ad2s1210_setup_properties(struct ad2s1210_state *st)
1300 {
1301 	struct device *dev = &st->sdev->dev;
1302 	u32 val;
1303 	int ret;
1304 
1305 	ret = device_property_read_u32(dev, "assigned-resolution-bits", &val);
1306 	if (ret < 0)
1307 		return dev_err_probe(dev, ret,
1308 			"failed to read assigned-resolution-bits property\n");
1309 
1310 	if (val < 10 || val > 16)
1311 		return dev_err_probe(dev, -EINVAL,
1312 				     "resolution out of range: %u\n", val);
1313 
1314 	st->resolution = (val - 10) >> 1;
1315 	/*
1316 	 * These are values that correlate to the hysteresis bit in the Control
1317 	 * register. 0 = disabled, 1 = enabled. When enabled, the actual
1318 	 * hysteresis is +/- 1 LSB of the raw position value. Which bit is the
1319 	 * LSB depends on the specified resolution.
1320 	 */
1321 	st->hysteresis_available[0] = 0;
1322 	st->hysteresis_available[1] = 1 << (2 * (AD2S1210_RES_16 -
1323 						 st->resolution));
1324 
1325 	return 0;
1326 }
1327 
1328 static int ad2s1210_setup_clocks(struct ad2s1210_state *st)
1329 {
1330 	struct device *dev = &st->sdev->dev;
1331 	struct clk *clk;
1332 
1333 	clk = devm_clk_get_enabled(dev, NULL);
1334 	if (IS_ERR(clk))
1335 		return dev_err_probe(dev, PTR_ERR(clk), "failed to get clock\n");
1336 
1337 	st->clkin_hz = clk_get_rate(clk);
1338 	if (st->clkin_hz < AD2S1210_MIN_CLKIN || st->clkin_hz > AD2S1210_MAX_CLKIN)
1339 		return dev_err_probe(dev, -EINVAL,
1340 				     "clock frequency out of range: %lu\n",
1341 				     st->clkin_hz);
1342 
1343 	return 0;
1344 }
1345 
1346 static int ad2s1210_setup_gpios(struct ad2s1210_state *st)
1347 {
1348 	struct device *dev = &st->sdev->dev;
1349 	struct gpio_descs *resolution_gpios;
1350 	DECLARE_BITMAP(bitmap, 2);
1351 	int ret;
1352 
1353 	/* should not be sampling on startup */
1354 	st->sample_gpio = devm_gpiod_get(dev, "sample", GPIOD_OUT_LOW);
1355 	if (IS_ERR(st->sample_gpio))
1356 		return dev_err_probe(dev, PTR_ERR(st->sample_gpio),
1357 				     "failed to request sample GPIO\n");
1358 
1359 	/* both pins high means that we start in config mode */
1360 	st->mode_gpios = devm_gpiod_get_array(dev, "mode", GPIOD_OUT_HIGH);
1361 	if (IS_ERR(st->mode_gpios))
1362 		return dev_err_probe(dev, PTR_ERR(st->mode_gpios),
1363 				     "failed to request mode GPIOs\n");
1364 
1365 	if (st->mode_gpios->ndescs != 2)
1366 		return dev_err_probe(dev, -EINVAL,
1367 				     "requires exactly 2 mode-gpios\n");
1368 
1369 	/*
1370 	 * If resolution gpios are provided, they get set to the required
1371 	 * resolution, otherwise it is assumed the RES0 and RES1 pins are
1372 	 * hard-wired to match the resolution indicated in the devicetree.
1373 	 */
1374 	resolution_gpios = devm_gpiod_get_array_optional(dev, "resolution",
1375 							 GPIOD_ASIS);
1376 	if (IS_ERR(resolution_gpios))
1377 		return dev_err_probe(dev, PTR_ERR(resolution_gpios),
1378 				     "failed to request resolution GPIOs\n");
1379 
1380 	if (resolution_gpios) {
1381 		if (resolution_gpios->ndescs != 2)
1382 			return dev_err_probe(dev, -EINVAL,
1383 				      "requires exactly 2 resolution-gpios\n");
1384 
1385 		bitmap[0] = st->resolution;
1386 
1387 		ret = gpiod_set_array_value(resolution_gpios->ndescs,
1388 					    resolution_gpios->desc,
1389 					    resolution_gpios->info,
1390 					    bitmap);
1391 		if (ret < 0)
1392 			return dev_err_probe(dev, ret,
1393 					     "failed to set resolution gpios\n");
1394 	}
1395 
1396 	return 0;
1397 }
1398 
1399 static const struct regmap_range ad2s1210_regmap_readable_ranges[] = {
1400 	regmap_reg_range(AD2S1210_REG_POSITION_MSB, AD2S1210_REG_VELOCITY_LSB),
1401 	regmap_reg_range(AD2S1210_REG_LOS_THRD, AD2S1210_REG_LOT_LOW_THRD),
1402 	regmap_reg_range(AD2S1210_REG_EXCIT_FREQ, AD2S1210_REG_CONTROL),
1403 	regmap_reg_range(AD2S1210_REG_FAULT, AD2S1210_REG_FAULT),
1404 };
1405 
1406 static const struct regmap_access_table ad2s1210_regmap_rd_table = {
1407 	.yes_ranges = ad2s1210_regmap_readable_ranges,
1408 	.n_yes_ranges = ARRAY_SIZE(ad2s1210_regmap_readable_ranges),
1409 };
1410 
1411 static const struct regmap_range ad2s1210_regmap_writeable_ranges[] = {
1412 	regmap_reg_range(AD2S1210_REG_LOS_THRD, AD2S1210_REG_LOT_LOW_THRD),
1413 	regmap_reg_range(AD2S1210_REG_EXCIT_FREQ, AD2S1210_REG_CONTROL),
1414 	regmap_reg_range(AD2S1210_REG_SOFT_RESET, AD2S1210_REG_SOFT_RESET),
1415 	regmap_reg_range(AD2S1210_REG_FAULT, AD2S1210_REG_FAULT),
1416 };
1417 
1418 static const struct regmap_access_table ad2s1210_regmap_wr_table = {
1419 	.yes_ranges = ad2s1210_regmap_writeable_ranges,
1420 	.n_yes_ranges = ARRAY_SIZE(ad2s1210_regmap_writeable_ranges),
1421 };
1422 
1423 static int ad2s1210_setup_regmap(struct ad2s1210_state *st)
1424 {
1425 	struct device *dev = &st->sdev->dev;
1426 	const struct regmap_config config = {
1427 		.reg_bits = 8,
1428 		.val_bits = 8,
1429 		.disable_locking = true,
1430 		.reg_read = ad2s1210_regmap_reg_read,
1431 		.reg_write = ad2s1210_regmap_reg_write,
1432 		.rd_table = &ad2s1210_regmap_rd_table,
1433 		.wr_table = &ad2s1210_regmap_wr_table,
1434 		.can_sleep = true,
1435 	};
1436 
1437 	st->regmap = devm_regmap_init(dev, NULL, st, &config);
1438 	if (IS_ERR(st->regmap))
1439 		return dev_err_probe(dev, PTR_ERR(st->regmap),
1440 				     "failed to allocate register map\n");
1441 
1442 	return 0;
1443 }
1444 
1445 static int ad2s1210_probe(struct spi_device *spi)
1446 {
1447 	struct iio_dev *indio_dev;
1448 	struct ad2s1210_state *st;
1449 	int ret;
1450 
1451 	indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
1452 	if (!indio_dev)
1453 		return -ENOMEM;
1454 	st = iio_priv(indio_dev);
1455 
1456 	mutex_init(&st->lock);
1457 	st->sdev = spi;
1458 
1459 	ret = ad2s1210_setup_properties(st);
1460 	if (ret < 0)
1461 		return ret;
1462 
1463 	ret = ad2s1210_setup_clocks(st);
1464 	if (ret < 0)
1465 		return ret;
1466 
1467 	ret = ad2s1210_setup_gpios(st);
1468 	if (ret < 0)
1469 		return ret;
1470 
1471 	ret = ad2s1210_setup_regmap(st);
1472 	if (ret < 0)
1473 		return ret;
1474 
1475 	ret = ad2s1210_initial(st);
1476 	if (ret < 0)
1477 		return ret;
1478 
1479 	indio_dev->info = &ad2s1210_info;
1480 	indio_dev->modes = INDIO_DIRECT_MODE;
1481 	indio_dev->channels = ad2s1210_channels;
1482 	indio_dev->num_channels = ARRAY_SIZE(ad2s1210_channels);
1483 	indio_dev->name = spi_get_device_id(spi)->name;
1484 
1485 	ret = devm_iio_triggered_buffer_setup(&spi->dev, indio_dev,
1486 					      &iio_pollfunc_store_time,
1487 					      &ad2s1210_trigger_handler, NULL);
1488 	if (ret < 0)
1489 		return dev_err_probe(&spi->dev, ret,
1490 				     "iio triggered buffer setup failed\n");
1491 
1492 	return devm_iio_device_register(&spi->dev, indio_dev);
1493 }
1494 
1495 static const struct of_device_id ad2s1210_of_match[] = {
1496 	{ .compatible = "adi,ad2s1210", },
1497 	{ }
1498 };
1499 MODULE_DEVICE_TABLE(of, ad2s1210_of_match);
1500 
1501 static const struct spi_device_id ad2s1210_id[] = {
1502 	{ "ad2s1210" },
1503 	{}
1504 };
1505 MODULE_DEVICE_TABLE(spi, ad2s1210_id);
1506 
1507 static struct spi_driver ad2s1210_driver = {
1508 	.driver = {
1509 		.name = "ad2s1210",
1510 		.of_match_table = ad2s1210_of_match,
1511 	},
1512 	.probe = ad2s1210_probe,
1513 	.id_table = ad2s1210_id,
1514 };
1515 module_spi_driver(ad2s1210_driver);
1516 
1517 MODULE_AUTHOR("Graff Yang <graff.yang@gmail.com>");
1518 MODULE_DESCRIPTION("Analog Devices AD2S1210 Resolver to Digital SPI driver");
1519 MODULE_LICENSE("GPL v2");
1520