Merge tag 'sound-5.19-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/tiwai...
[linux-2.6-microblaze.git] / drivers / iio / adc / ad7192.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * AD7190 AD7192 AD7193 AD7195 SPI ADC driver
4  *
5  * Copyright 2011-2015 Analog Devices Inc.
6  */
7
8 #include <linux/interrupt.h>
9 #include <linux/clk.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/slab.h>
13 #include <linux/sysfs.h>
14 #include <linux/spi/spi.h>
15 #include <linux/regulator/consumer.h>
16 #include <linux/err.h>
17 #include <linux/sched.h>
18 #include <linux/delay.h>
19 #include <linux/of_device.h>
20
21 #include <linux/iio/iio.h>
22 #include <linux/iio/sysfs.h>
23 #include <linux/iio/buffer.h>
24 #include <linux/iio/trigger.h>
25 #include <linux/iio/trigger_consumer.h>
26 #include <linux/iio/triggered_buffer.h>
27 #include <linux/iio/adc/ad_sigma_delta.h>
28
29 /* Registers */
30 #define AD7192_REG_COMM         0 /* Communications Register (WO, 8-bit) */
31 #define AD7192_REG_STAT         0 /* Status Register         (RO, 8-bit) */
32 #define AD7192_REG_MODE         1 /* Mode Register           (RW, 24-bit */
33 #define AD7192_REG_CONF         2 /* Configuration Register  (RW, 24-bit) */
34 #define AD7192_REG_DATA         3 /* Data Register           (RO, 24/32-bit) */
35 #define AD7192_REG_ID           4 /* ID Register             (RO, 8-bit) */
36 #define AD7192_REG_GPOCON       5 /* GPOCON Register         (RO, 8-bit) */
37 #define AD7192_REG_OFFSET       6 /* Offset Register         (RW, 16-bit */
38                                   /* (AD7792)/24-bit (AD7192)) */
39 #define AD7192_REG_FULLSALE     7 /* Full-Scale Register */
40                                   /* (RW, 16-bit (AD7792)/24-bit (AD7192)) */
41
42 /* Communications Register Bit Designations (AD7192_REG_COMM) */
43 #define AD7192_COMM_WEN         BIT(7) /* Write Enable */
44 #define AD7192_COMM_WRITE       0 /* Write Operation */
45 #define AD7192_COMM_READ        BIT(6) /* Read Operation */
46 #define AD7192_COMM_ADDR(x)     (((x) & 0x7) << 3) /* Register Address */
47 #define AD7192_COMM_CREAD       BIT(2) /* Continuous Read of Data Register */
48
49 /* Status Register Bit Designations (AD7192_REG_STAT) */
50 #define AD7192_STAT_RDY         BIT(7) /* Ready */
51 #define AD7192_STAT_ERR         BIT(6) /* Error (Overrange, Underrange) */
52 #define AD7192_STAT_NOREF       BIT(5) /* Error no external reference */
53 #define AD7192_STAT_PARITY      BIT(4) /* Parity */
54 #define AD7192_STAT_CH3         BIT(2) /* Channel 3 */
55 #define AD7192_STAT_CH2         BIT(1) /* Channel 2 */
56 #define AD7192_STAT_CH1         BIT(0) /* Channel 1 */
57
58 /* Mode Register Bit Designations (AD7192_REG_MODE) */
59 #define AD7192_MODE_SEL(x)      (((x) & 0x7) << 21) /* Operation Mode Select */
60 #define AD7192_MODE_SEL_MASK    (0x7 << 21) /* Operation Mode Select Mask */
61 #define AD7192_MODE_STA(x)      (((x) & 0x1) << 20) /* Status Register transmission */
62 #define AD7192_MODE_STA_MASK    BIT(20) /* Status Register transmission Mask */
63 #define AD7192_MODE_CLKSRC(x)   (((x) & 0x3) << 18) /* Clock Source Select */
64 #define AD7192_MODE_SINC3       BIT(15) /* SINC3 Filter Select */
65 #define AD7192_MODE_ACX         BIT(14) /* AC excitation enable(AD7195 only)*/
66 #define AD7192_MODE_ENPAR       BIT(13) /* Parity Enable */
67 #define AD7192_MODE_CLKDIV      BIT(12) /* Clock divide by 2 (AD7190/2 only)*/
68 #define AD7192_MODE_SCYCLE      BIT(11) /* Single cycle conversion */
69 #define AD7192_MODE_REJ60       BIT(10) /* 50/60Hz notch filter */
70 #define AD7192_MODE_RATE(x)     ((x) & 0x3FF) /* Filter Update Rate Select */
71
72 /* Mode Register: AD7192_MODE_SEL options */
73 #define AD7192_MODE_CONT                0 /* Continuous Conversion Mode */
74 #define AD7192_MODE_SINGLE              1 /* Single Conversion Mode */
75 #define AD7192_MODE_IDLE                2 /* Idle Mode */
76 #define AD7192_MODE_PWRDN               3 /* Power-Down Mode */
77 #define AD7192_MODE_CAL_INT_ZERO        4 /* Internal Zero-Scale Calibration */
78 #define AD7192_MODE_CAL_INT_FULL        5 /* Internal Full-Scale Calibration */
79 #define AD7192_MODE_CAL_SYS_ZERO        6 /* System Zero-Scale Calibration */
80 #define AD7192_MODE_CAL_SYS_FULL        7 /* System Full-Scale Calibration */
81
82 /* Mode Register: AD7192_MODE_CLKSRC options */
83 #define AD7192_CLK_EXT_MCLK1_2          0 /* External 4.92 MHz Clock connected*/
84                                           /* from MCLK1 to MCLK2 */
85 #define AD7192_CLK_EXT_MCLK2            1 /* External Clock applied to MCLK2 */
86 #define AD7192_CLK_INT                  2 /* Internal 4.92 MHz Clock not */
87                                           /* available at the MCLK2 pin */
88 #define AD7192_CLK_INT_CO               3 /* Internal 4.92 MHz Clock available*/
89                                           /* at the MCLK2 pin */
90
91 /* Configuration Register Bit Designations (AD7192_REG_CONF) */
92
93 #define AD7192_CONF_CHOP        BIT(23) /* CHOP enable */
94 #define AD7192_CONF_REFSEL      BIT(20) /* REFIN1/REFIN2 Reference Select */
95 #define AD7192_CONF_CHAN(x)     ((x) << 8) /* Channel select */
96 #define AD7192_CONF_CHAN_MASK   (0x7FF << 8) /* Channel select mask */
97 #define AD7192_CONF_BURN        BIT(7) /* Burnout current enable */
98 #define AD7192_CONF_REFDET      BIT(6) /* Reference detect enable */
99 #define AD7192_CONF_BUF         BIT(4) /* Buffered Mode Enable */
100 #define AD7192_CONF_UNIPOLAR    BIT(3) /* Unipolar/Bipolar Enable */
101 #define AD7192_CONF_GAIN(x)     ((x) & 0x7) /* Gain Select */
102
103 #define AD7192_CH_AIN1P_AIN2M   BIT(0) /* AIN1(+) - AIN2(-) */
104 #define AD7192_CH_AIN3P_AIN4M   BIT(1) /* AIN3(+) - AIN4(-) */
105 #define AD7192_CH_TEMP          BIT(2) /* Temp Sensor */
106 #define AD7192_CH_AIN2P_AIN2M   BIT(3) /* AIN2(+) - AIN2(-) */
107 #define AD7192_CH_AIN1          BIT(4) /* AIN1 - AINCOM */
108 #define AD7192_CH_AIN2          BIT(5) /* AIN2 - AINCOM */
109 #define AD7192_CH_AIN3          BIT(6) /* AIN3 - AINCOM */
110 #define AD7192_CH_AIN4          BIT(7) /* AIN4 - AINCOM */
111
112 #define AD7193_CH_AIN1P_AIN2M   0x001  /* AIN1(+) - AIN2(-) */
113 #define AD7193_CH_AIN3P_AIN4M   0x002  /* AIN3(+) - AIN4(-) */
114 #define AD7193_CH_AIN5P_AIN6M   0x004  /* AIN5(+) - AIN6(-) */
115 #define AD7193_CH_AIN7P_AIN8M   0x008  /* AIN7(+) - AIN8(-) */
116 #define AD7193_CH_TEMP          0x100 /* Temp senseor */
117 #define AD7193_CH_AIN2P_AIN2M   0x200 /* AIN2(+) - AIN2(-) */
118 #define AD7193_CH_AIN1          0x401 /* AIN1 - AINCOM */
119 #define AD7193_CH_AIN2          0x402 /* AIN2 - AINCOM */
120 #define AD7193_CH_AIN3          0x404 /* AIN3 - AINCOM */
121 #define AD7193_CH_AIN4          0x408 /* AIN4 - AINCOM */
122 #define AD7193_CH_AIN5          0x410 /* AIN5 - AINCOM */
123 #define AD7193_CH_AIN6          0x420 /* AIN6 - AINCOM */
124 #define AD7193_CH_AIN7          0x440 /* AIN7 - AINCOM */
125 #define AD7193_CH_AIN8          0x480 /* AIN7 - AINCOM */
126 #define AD7193_CH_AINCOM        0x600 /* AINCOM - AINCOM */
127
128 /* ID Register Bit Designations (AD7192_REG_ID) */
129 #define CHIPID_AD7190           0x4
130 #define CHIPID_AD7192           0x0
131 #define CHIPID_AD7193           0x2
132 #define CHIPID_AD7195           0x6
133 #define AD7192_ID_MASK          0x0F
134
135 /* GPOCON Register Bit Designations (AD7192_REG_GPOCON) */
136 #define AD7192_GPOCON_BPDSW     BIT(6) /* Bridge power-down switch enable */
137 #define AD7192_GPOCON_GP32EN    BIT(5) /* Digital Output P3 and P2 enable */
138 #define AD7192_GPOCON_GP10EN    BIT(4) /* Digital Output P1 and P0 enable */
139 #define AD7192_GPOCON_P3DAT     BIT(3) /* P3 state */
140 #define AD7192_GPOCON_P2DAT     BIT(2) /* P2 state */
141 #define AD7192_GPOCON_P1DAT     BIT(1) /* P1 state */
142 #define AD7192_GPOCON_P0DAT     BIT(0) /* P0 state */
143
144 #define AD7192_EXT_FREQ_MHZ_MIN 2457600
145 #define AD7192_EXT_FREQ_MHZ_MAX 5120000
146 #define AD7192_INT_FREQ_MHZ     4915200
147
148 #define AD7192_NO_SYNC_FILTER   1
149 #define AD7192_SYNC3_FILTER     3
150 #define AD7192_SYNC4_FILTER     4
151
152 /* NOTE:
153  * The AD7190/2/5 features a dual use data out ready DOUT/RDY output.
154  * In order to avoid contentions on the SPI bus, it's therefore necessary
155  * to use spi bus locking.
156  *
157  * The DOUT/RDY output must also be wired to an interrupt capable GPIO.
158  */
159
160 enum {
161         AD7192_SYSCALIB_ZERO_SCALE,
162         AD7192_SYSCALIB_FULL_SCALE,
163 };
164
165 enum {
166         ID_AD7190,
167         ID_AD7192,
168         ID_AD7193,
169         ID_AD7195,
170 };
171
172 struct ad7192_chip_info {
173         unsigned int                    chip_id;
174         const char                      *name;
175 };
176
177 struct ad7192_state {
178         const struct ad7192_chip_info   *chip_info;
179         struct regulator                *avdd;
180         struct regulator                *dvdd;
181         struct clk                      *mclk;
182         u16                             int_vref_mv;
183         u32                             fclk;
184         u32                             f_order;
185         u32                             mode;
186         u32                             conf;
187         u32                             scale_avail[8][2];
188         u8                              gpocon;
189         u8                              clock_sel;
190         struct mutex                    lock;   /* protect sensor state */
191         u8                              syscalib_mode[8];
192
193         struct ad_sigma_delta           sd;
194 };
195
196 static const char * const ad7192_syscalib_modes[] = {
197         [AD7192_SYSCALIB_ZERO_SCALE] = "zero_scale",
198         [AD7192_SYSCALIB_FULL_SCALE] = "full_scale",
199 };
200
201 static int ad7192_set_syscalib_mode(struct iio_dev *indio_dev,
202                                     const struct iio_chan_spec *chan,
203                                     unsigned int mode)
204 {
205         struct ad7192_state *st = iio_priv(indio_dev);
206
207         st->syscalib_mode[chan->channel] = mode;
208
209         return 0;
210 }
211
212 static int ad7192_get_syscalib_mode(struct iio_dev *indio_dev,
213                                     const struct iio_chan_spec *chan)
214 {
215         struct ad7192_state *st = iio_priv(indio_dev);
216
217         return st->syscalib_mode[chan->channel];
218 }
219
220 static ssize_t ad7192_write_syscalib(struct iio_dev *indio_dev,
221                                      uintptr_t private,
222                                      const struct iio_chan_spec *chan,
223                                      const char *buf, size_t len)
224 {
225         struct ad7192_state *st = iio_priv(indio_dev);
226         bool sys_calib;
227         int ret, temp;
228
229         ret = kstrtobool(buf, &sys_calib);
230         if (ret)
231                 return ret;
232
233         temp = st->syscalib_mode[chan->channel];
234         if (sys_calib) {
235                 if (temp == AD7192_SYSCALIB_ZERO_SCALE)
236                         ret = ad_sd_calibrate(&st->sd, AD7192_MODE_CAL_SYS_ZERO,
237                                               chan->address);
238                 else
239                         ret = ad_sd_calibrate(&st->sd, AD7192_MODE_CAL_SYS_FULL,
240                                               chan->address);
241         }
242
243         return ret ? ret : len;
244 }
245
246 static const struct iio_enum ad7192_syscalib_mode_enum = {
247         .items = ad7192_syscalib_modes,
248         .num_items = ARRAY_SIZE(ad7192_syscalib_modes),
249         .set = ad7192_set_syscalib_mode,
250         .get = ad7192_get_syscalib_mode
251 };
252
253 static const struct iio_chan_spec_ext_info ad7192_calibsys_ext_info[] = {
254         {
255                 .name = "sys_calibration",
256                 .write = ad7192_write_syscalib,
257                 .shared = IIO_SEPARATE,
258         },
259         IIO_ENUM("sys_calibration_mode", IIO_SEPARATE,
260                  &ad7192_syscalib_mode_enum),
261         IIO_ENUM_AVAILABLE("sys_calibration_mode", IIO_SHARED_BY_TYPE,
262                            &ad7192_syscalib_mode_enum),
263         {}
264 };
265
266 static struct ad7192_state *ad_sigma_delta_to_ad7192(struct ad_sigma_delta *sd)
267 {
268         return container_of(sd, struct ad7192_state, sd);
269 }
270
271 static int ad7192_set_channel(struct ad_sigma_delta *sd, unsigned int channel)
272 {
273         struct ad7192_state *st = ad_sigma_delta_to_ad7192(sd);
274
275         st->conf &= ~AD7192_CONF_CHAN_MASK;
276         st->conf |= AD7192_CONF_CHAN(channel);
277
278         return ad_sd_write_reg(&st->sd, AD7192_REG_CONF, 3, st->conf);
279 }
280
281 static int ad7192_set_mode(struct ad_sigma_delta *sd,
282                            enum ad_sigma_delta_mode mode)
283 {
284         struct ad7192_state *st = ad_sigma_delta_to_ad7192(sd);
285
286         st->mode &= ~AD7192_MODE_SEL_MASK;
287         st->mode |= AD7192_MODE_SEL(mode);
288
289         return ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, st->mode);
290 }
291
292 static int ad7192_append_status(struct ad_sigma_delta *sd, bool append)
293 {
294         struct ad7192_state *st = ad_sigma_delta_to_ad7192(sd);
295         unsigned int mode = st->mode;
296         int ret;
297
298         mode &= ~AD7192_MODE_STA_MASK;
299         mode |= AD7192_MODE_STA(append);
300
301         ret = ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, mode);
302         if (ret < 0)
303                 return ret;
304
305         st->mode = mode;
306
307         return 0;
308 }
309
310 static int ad7192_disable_all(struct ad_sigma_delta *sd)
311 {
312         struct ad7192_state *st = ad_sigma_delta_to_ad7192(sd);
313         u32 conf = st->conf;
314         int ret;
315
316         conf &= ~AD7192_CONF_CHAN_MASK;
317
318         ret = ad_sd_write_reg(&st->sd, AD7192_REG_CONF, 3, conf);
319         if (ret < 0)
320                 return ret;
321
322         st->conf = conf;
323
324         return 0;
325 }
326
327 static const struct ad_sigma_delta_info ad7192_sigma_delta_info = {
328         .set_channel = ad7192_set_channel,
329         .append_status = ad7192_append_status,
330         .disable_all = ad7192_disable_all,
331         .set_mode = ad7192_set_mode,
332         .has_registers = true,
333         .addr_shift = 3,
334         .read_mask = BIT(6),
335         .status_ch_mask = GENMASK(3, 0),
336         .num_slots = 4,
337         .irq_flags = IRQF_TRIGGER_FALLING,
338 };
339
340 static const struct ad_sd_calib_data ad7192_calib_arr[8] = {
341         {AD7192_MODE_CAL_INT_ZERO, AD7192_CH_AIN1},
342         {AD7192_MODE_CAL_INT_FULL, AD7192_CH_AIN1},
343         {AD7192_MODE_CAL_INT_ZERO, AD7192_CH_AIN2},
344         {AD7192_MODE_CAL_INT_FULL, AD7192_CH_AIN2},
345         {AD7192_MODE_CAL_INT_ZERO, AD7192_CH_AIN3},
346         {AD7192_MODE_CAL_INT_FULL, AD7192_CH_AIN3},
347         {AD7192_MODE_CAL_INT_ZERO, AD7192_CH_AIN4},
348         {AD7192_MODE_CAL_INT_FULL, AD7192_CH_AIN4}
349 };
350
351 static int ad7192_calibrate_all(struct ad7192_state *st)
352 {
353         return ad_sd_calibrate_all(&st->sd, ad7192_calib_arr,
354                                    ARRAY_SIZE(ad7192_calib_arr));
355 }
356
357 static inline bool ad7192_valid_external_frequency(u32 freq)
358 {
359         return (freq >= AD7192_EXT_FREQ_MHZ_MIN &&
360                 freq <= AD7192_EXT_FREQ_MHZ_MAX);
361 }
362
363 static int ad7192_of_clock_select(struct ad7192_state *st)
364 {
365         struct device_node *np = st->sd.spi->dev.of_node;
366         unsigned int clock_sel;
367
368         clock_sel = AD7192_CLK_INT;
369
370         /* use internal clock */
371         if (st->mclk) {
372                 if (of_property_read_bool(np, "adi,int-clock-output-enable"))
373                         clock_sel = AD7192_CLK_INT_CO;
374         } else {
375                 if (of_property_read_bool(np, "adi,clock-xtal"))
376                         clock_sel = AD7192_CLK_EXT_MCLK1_2;
377                 else
378                         clock_sel = AD7192_CLK_EXT_MCLK2;
379         }
380
381         return clock_sel;
382 }
383
384 static int ad7192_setup(struct ad7192_state *st, struct device_node *np)
385 {
386         struct iio_dev *indio_dev = spi_get_drvdata(st->sd.spi);
387         bool rej60_en, refin2_en;
388         bool buf_en, bipolar, burnout_curr_en;
389         unsigned long long scale_uv;
390         int i, ret, id;
391
392         /* reset the serial interface */
393         ret = ad_sd_reset(&st->sd, 48);
394         if (ret < 0)
395                 return ret;
396         usleep_range(500, 1000); /* Wait for at least 500us */
397
398         /* write/read test for device presence */
399         ret = ad_sd_read_reg(&st->sd, AD7192_REG_ID, 1, &id);
400         if (ret)
401                 return ret;
402
403         id &= AD7192_ID_MASK;
404
405         if (id != st->chip_info->chip_id)
406                 dev_warn(&st->sd.spi->dev, "device ID query failed (0x%X)\n",
407                          id);
408
409         st->mode = AD7192_MODE_SEL(AD7192_MODE_IDLE) |
410                 AD7192_MODE_CLKSRC(st->clock_sel) |
411                 AD7192_MODE_RATE(480);
412
413         st->conf = AD7192_CONF_GAIN(0);
414
415         rej60_en = of_property_read_bool(np, "adi,rejection-60-Hz-enable");
416         if (rej60_en)
417                 st->mode |= AD7192_MODE_REJ60;
418
419         refin2_en = of_property_read_bool(np, "adi,refin2-pins-enable");
420         if (refin2_en && st->chip_info->chip_id != CHIPID_AD7195)
421                 st->conf |= AD7192_CONF_REFSEL;
422
423         st->conf &= ~AD7192_CONF_CHOP;
424         st->f_order = AD7192_NO_SYNC_FILTER;
425
426         buf_en = of_property_read_bool(np, "adi,buffer-enable");
427         if (buf_en)
428                 st->conf |= AD7192_CONF_BUF;
429
430         bipolar = of_property_read_bool(np, "bipolar");
431         if (!bipolar)
432                 st->conf |= AD7192_CONF_UNIPOLAR;
433
434         burnout_curr_en = of_property_read_bool(np,
435                                                 "adi,burnout-currents-enable");
436         if (burnout_curr_en && buf_en) {
437                 st->conf |= AD7192_CONF_BURN;
438         } else if (burnout_curr_en) {
439                 dev_warn(&st->sd.spi->dev,
440                          "Can't enable burnout currents: see CHOP or buffer\n");
441         }
442
443         ret = ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, st->mode);
444         if (ret)
445                 return ret;
446
447         ret = ad_sd_write_reg(&st->sd, AD7192_REG_CONF, 3, st->conf);
448         if (ret)
449                 return ret;
450
451         ret = ad7192_calibrate_all(st);
452         if (ret)
453                 return ret;
454
455         /* Populate available ADC input ranges */
456         for (i = 0; i < ARRAY_SIZE(st->scale_avail); i++) {
457                 scale_uv = ((u64)st->int_vref_mv * 100000000)
458                         >> (indio_dev->channels[0].scan_type.realbits -
459                         ((st->conf & AD7192_CONF_UNIPOLAR) ? 0 : 1));
460                 scale_uv >>= i;
461
462                 st->scale_avail[i][1] = do_div(scale_uv, 100000000) * 10;
463                 st->scale_avail[i][0] = scale_uv;
464         }
465
466         return 0;
467 }
468
469 static ssize_t ad7192_show_ac_excitation(struct device *dev,
470                                          struct device_attribute *attr,
471                                          char *buf)
472 {
473         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
474         struct ad7192_state *st = iio_priv(indio_dev);
475
476         return sysfs_emit(buf, "%d\n", !!(st->mode & AD7192_MODE_ACX));
477 }
478
479 static ssize_t ad7192_show_bridge_switch(struct device *dev,
480                                          struct device_attribute *attr,
481                                          char *buf)
482 {
483         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
484         struct ad7192_state *st = iio_priv(indio_dev);
485
486         return sysfs_emit(buf, "%d\n", !!(st->gpocon & AD7192_GPOCON_BPDSW));
487 }
488
489 static ssize_t ad7192_set(struct device *dev,
490                           struct device_attribute *attr,
491                           const char *buf,
492                           size_t len)
493 {
494         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
495         struct ad7192_state *st = iio_priv(indio_dev);
496         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
497         int ret;
498         bool val;
499
500         ret = kstrtobool(buf, &val);
501         if (ret < 0)
502                 return ret;
503
504         ret = iio_device_claim_direct_mode(indio_dev);
505         if (ret)
506                 return ret;
507
508         switch ((u32)this_attr->address) {
509         case AD7192_REG_GPOCON:
510                 if (val)
511                         st->gpocon |= AD7192_GPOCON_BPDSW;
512                 else
513                         st->gpocon &= ~AD7192_GPOCON_BPDSW;
514
515                 ad_sd_write_reg(&st->sd, AD7192_REG_GPOCON, 1, st->gpocon);
516                 break;
517         case AD7192_REG_MODE:
518                 if (val)
519                         st->mode |= AD7192_MODE_ACX;
520                 else
521                         st->mode &= ~AD7192_MODE_ACX;
522
523                 ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, st->mode);
524                 break;
525         default:
526                 ret = -EINVAL;
527         }
528
529         iio_device_release_direct_mode(indio_dev);
530
531         return ret ? ret : len;
532 }
533
534 static void ad7192_get_available_filter_freq(struct ad7192_state *st,
535                                                     int *freq)
536 {
537         unsigned int fadc;
538
539         /* Formulas for filter at page 25 of the datasheet */
540         fadc = DIV_ROUND_CLOSEST(st->fclk,
541                                  AD7192_SYNC4_FILTER * AD7192_MODE_RATE(st->mode));
542         freq[0] = DIV_ROUND_CLOSEST(fadc * 240, 1024);
543
544         fadc = DIV_ROUND_CLOSEST(st->fclk,
545                                  AD7192_SYNC3_FILTER * AD7192_MODE_RATE(st->mode));
546         freq[1] = DIV_ROUND_CLOSEST(fadc * 240, 1024);
547
548         fadc = DIV_ROUND_CLOSEST(st->fclk, AD7192_MODE_RATE(st->mode));
549         freq[2] = DIV_ROUND_CLOSEST(fadc * 230, 1024);
550         freq[3] = DIV_ROUND_CLOSEST(fadc * 272, 1024);
551 }
552
553 static ssize_t ad7192_show_filter_avail(struct device *dev,
554                                         struct device_attribute *attr,
555                                         char *buf)
556 {
557         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
558         struct ad7192_state *st = iio_priv(indio_dev);
559         unsigned int freq_avail[4], i;
560         size_t len = 0;
561
562         ad7192_get_available_filter_freq(st, freq_avail);
563
564         for (i = 0; i < ARRAY_SIZE(freq_avail); i++)
565                 len += scnprintf(buf + len, PAGE_SIZE - len,
566                                  "%d.%d ", freq_avail[i] / 1000,
567                                  freq_avail[i] % 1000);
568
569         buf[len - 1] = '\n';
570
571         return len;
572 }
573
574 static IIO_DEVICE_ATTR(filter_low_pass_3db_frequency_available,
575                        0444, ad7192_show_filter_avail, NULL, 0);
576
577 static IIO_DEVICE_ATTR(bridge_switch_en, 0644,
578                        ad7192_show_bridge_switch, ad7192_set,
579                        AD7192_REG_GPOCON);
580
581 static IIO_DEVICE_ATTR(ac_excitation_en, 0644,
582                        ad7192_show_ac_excitation, ad7192_set,
583                        AD7192_REG_MODE);
584
585 static struct attribute *ad7192_attributes[] = {
586         &iio_dev_attr_filter_low_pass_3db_frequency_available.dev_attr.attr,
587         &iio_dev_attr_bridge_switch_en.dev_attr.attr,
588         &iio_dev_attr_ac_excitation_en.dev_attr.attr,
589         NULL
590 };
591
592 static const struct attribute_group ad7192_attribute_group = {
593         .attrs = ad7192_attributes,
594 };
595
596 static struct attribute *ad7195_attributes[] = {
597         &iio_dev_attr_filter_low_pass_3db_frequency_available.dev_attr.attr,
598         &iio_dev_attr_bridge_switch_en.dev_attr.attr,
599         NULL
600 };
601
602 static const struct attribute_group ad7195_attribute_group = {
603         .attrs = ad7195_attributes,
604 };
605
606 static unsigned int ad7192_get_temp_scale(bool unipolar)
607 {
608         return unipolar ? 2815 * 2 : 2815;
609 }
610
611 static int ad7192_set_3db_filter_freq(struct ad7192_state *st,
612                                       int val, int val2)
613 {
614         int freq_avail[4], i, ret, freq;
615         unsigned int diff_new, diff_old;
616         int idx = 0;
617
618         diff_old = U32_MAX;
619         freq = val * 1000 + val2;
620
621         ad7192_get_available_filter_freq(st, freq_avail);
622
623         for (i = 0; i < ARRAY_SIZE(freq_avail); i++) {
624                 diff_new = abs(freq - freq_avail[i]);
625                 if (diff_new < diff_old) {
626                         diff_old = diff_new;
627                         idx = i;
628                 }
629         }
630
631         switch (idx) {
632         case 0:
633                 st->f_order = AD7192_SYNC4_FILTER;
634                 st->mode &= ~AD7192_MODE_SINC3;
635
636                 st->conf |= AD7192_CONF_CHOP;
637                 break;
638         case 1:
639                 st->f_order = AD7192_SYNC3_FILTER;
640                 st->mode |= AD7192_MODE_SINC3;
641
642                 st->conf |= AD7192_CONF_CHOP;
643                 break;
644         case 2:
645                 st->f_order = AD7192_NO_SYNC_FILTER;
646                 st->mode &= ~AD7192_MODE_SINC3;
647
648                 st->conf &= ~AD7192_CONF_CHOP;
649                 break;
650         case 3:
651                 st->f_order = AD7192_NO_SYNC_FILTER;
652                 st->mode |= AD7192_MODE_SINC3;
653
654                 st->conf &= ~AD7192_CONF_CHOP;
655                 break;
656         }
657
658         ret = ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, st->mode);
659         if (ret < 0)
660                 return ret;
661
662         return ad_sd_write_reg(&st->sd, AD7192_REG_CONF, 3, st->conf);
663 }
664
665 static int ad7192_get_3db_filter_freq(struct ad7192_state *st)
666 {
667         unsigned int fadc;
668
669         fadc = DIV_ROUND_CLOSEST(st->fclk,
670                                  st->f_order * AD7192_MODE_RATE(st->mode));
671
672         if (st->conf & AD7192_CONF_CHOP)
673                 return DIV_ROUND_CLOSEST(fadc * 240, 1024);
674         if (st->mode & AD7192_MODE_SINC3)
675                 return DIV_ROUND_CLOSEST(fadc * 272, 1024);
676         else
677                 return DIV_ROUND_CLOSEST(fadc * 230, 1024);
678 }
679
680 static int ad7192_read_raw(struct iio_dev *indio_dev,
681                            struct iio_chan_spec const *chan,
682                            int *val,
683                            int *val2,
684                            long m)
685 {
686         struct ad7192_state *st = iio_priv(indio_dev);
687         bool unipolar = !!(st->conf & AD7192_CONF_UNIPOLAR);
688
689         switch (m) {
690         case IIO_CHAN_INFO_RAW:
691                 return ad_sigma_delta_single_conversion(indio_dev, chan, val);
692         case IIO_CHAN_INFO_SCALE:
693                 switch (chan->type) {
694                 case IIO_VOLTAGE:
695                         mutex_lock(&st->lock);
696                         *val = st->scale_avail[AD7192_CONF_GAIN(st->conf)][0];
697                         *val2 = st->scale_avail[AD7192_CONF_GAIN(st->conf)][1];
698                         mutex_unlock(&st->lock);
699                         return IIO_VAL_INT_PLUS_NANO;
700                 case IIO_TEMP:
701                         *val = 0;
702                         *val2 = 1000000000 / ad7192_get_temp_scale(unipolar);
703                         return IIO_VAL_INT_PLUS_NANO;
704                 default:
705                         return -EINVAL;
706                 }
707         case IIO_CHAN_INFO_OFFSET:
708                 if (!unipolar)
709                         *val = -(1 << (chan->scan_type.realbits - 1));
710                 else
711                         *val = 0;
712                 /* Kelvin to Celsius */
713                 if (chan->type == IIO_TEMP)
714                         *val -= 273 * ad7192_get_temp_scale(unipolar);
715                 return IIO_VAL_INT;
716         case IIO_CHAN_INFO_SAMP_FREQ:
717                 *val = st->fclk /
718                         (st->f_order * 1024 * AD7192_MODE_RATE(st->mode));
719                 return IIO_VAL_INT;
720         case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
721                 *val = ad7192_get_3db_filter_freq(st);
722                 *val2 = 1000;
723                 return IIO_VAL_FRACTIONAL;
724         }
725
726         return -EINVAL;
727 }
728
729 static int ad7192_write_raw(struct iio_dev *indio_dev,
730                             struct iio_chan_spec const *chan,
731                             int val,
732                             int val2,
733                             long mask)
734 {
735         struct ad7192_state *st = iio_priv(indio_dev);
736         int ret, i, div;
737         unsigned int tmp;
738
739         ret = iio_device_claim_direct_mode(indio_dev);
740         if (ret)
741                 return ret;
742
743         switch (mask) {
744         case IIO_CHAN_INFO_SCALE:
745                 ret = -EINVAL;
746                 mutex_lock(&st->lock);
747                 for (i = 0; i < ARRAY_SIZE(st->scale_avail); i++)
748                         if (val2 == st->scale_avail[i][1]) {
749                                 ret = 0;
750                                 tmp = st->conf;
751                                 st->conf &= ~AD7192_CONF_GAIN(-1);
752                                 st->conf |= AD7192_CONF_GAIN(i);
753                                 if (tmp == st->conf)
754                                         break;
755                                 ad_sd_write_reg(&st->sd, AD7192_REG_CONF,
756                                                 3, st->conf);
757                                 ad7192_calibrate_all(st);
758                                 break;
759                         }
760                 mutex_unlock(&st->lock);
761                 break;
762         case IIO_CHAN_INFO_SAMP_FREQ:
763                 if (!val) {
764                         ret = -EINVAL;
765                         break;
766                 }
767
768                 div = st->fclk / (val * st->f_order * 1024);
769                 if (div < 1 || div > 1023) {
770                         ret = -EINVAL;
771                         break;
772                 }
773
774                 st->mode &= ~AD7192_MODE_RATE(-1);
775                 st->mode |= AD7192_MODE_RATE(div);
776                 ad_sd_write_reg(&st->sd, AD7192_REG_MODE, 3, st->mode);
777                 break;
778         case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
779                 ret = ad7192_set_3db_filter_freq(st, val, val2 / 1000);
780                 break;
781         default:
782                 ret = -EINVAL;
783         }
784
785         iio_device_release_direct_mode(indio_dev);
786
787         return ret;
788 }
789
790 static int ad7192_write_raw_get_fmt(struct iio_dev *indio_dev,
791                                     struct iio_chan_spec const *chan,
792                                     long mask)
793 {
794         switch (mask) {
795         case IIO_CHAN_INFO_SCALE:
796                 return IIO_VAL_INT_PLUS_NANO;
797         case IIO_CHAN_INFO_SAMP_FREQ:
798                 return IIO_VAL_INT;
799         case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
800                 return IIO_VAL_INT_PLUS_MICRO;
801         default:
802                 return -EINVAL;
803         }
804 }
805
806 static int ad7192_read_avail(struct iio_dev *indio_dev,
807                              struct iio_chan_spec const *chan,
808                              const int **vals, int *type, int *length,
809                              long mask)
810 {
811         struct ad7192_state *st = iio_priv(indio_dev);
812
813         switch (mask) {
814         case IIO_CHAN_INFO_SCALE:
815                 *vals = (int *)st->scale_avail;
816                 *type = IIO_VAL_INT_PLUS_NANO;
817                 /* Values are stored in a 2D matrix  */
818                 *length = ARRAY_SIZE(st->scale_avail) * 2;
819
820                 return IIO_AVAIL_LIST;
821         }
822
823         return -EINVAL;
824 }
825
826 static int ad7192_update_scan_mode(struct iio_dev *indio_dev, const unsigned long *scan_mask)
827 {
828         struct ad7192_state *st = iio_priv(indio_dev);
829         u32 conf = st->conf;
830         int ret;
831         int i;
832
833         conf &= ~AD7192_CONF_CHAN_MASK;
834         for_each_set_bit(i, scan_mask, 8)
835                 conf |= AD7192_CONF_CHAN(i);
836
837         ret = ad_sd_write_reg(&st->sd, AD7192_REG_CONF, 3, conf);
838         if (ret < 0)
839                 return ret;
840
841         st->conf = conf;
842
843         return 0;
844 }
845
846 static const struct iio_info ad7192_info = {
847         .read_raw = ad7192_read_raw,
848         .write_raw = ad7192_write_raw,
849         .write_raw_get_fmt = ad7192_write_raw_get_fmt,
850         .read_avail = ad7192_read_avail,
851         .attrs = &ad7192_attribute_group,
852         .validate_trigger = ad_sd_validate_trigger,
853         .update_scan_mode = ad7192_update_scan_mode,
854 };
855
856 static const struct iio_info ad7195_info = {
857         .read_raw = ad7192_read_raw,
858         .write_raw = ad7192_write_raw,
859         .write_raw_get_fmt = ad7192_write_raw_get_fmt,
860         .read_avail = ad7192_read_avail,
861         .attrs = &ad7195_attribute_group,
862         .validate_trigger = ad_sd_validate_trigger,
863         .update_scan_mode = ad7192_update_scan_mode,
864 };
865
866 #define __AD719x_CHANNEL(_si, _channel1, _channel2, _address, _extend_name, \
867         _type, _mask_type_av, _ext_info) \
868         { \
869                 .type = (_type), \
870                 .differential = ((_channel2) == -1 ? 0 : 1), \
871                 .indexed = 1, \
872                 .channel = (_channel1), \
873                 .channel2 = (_channel2), \
874                 .address = (_address), \
875                 .extend_name = (_extend_name), \
876                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
877                         BIT(IIO_CHAN_INFO_OFFSET), \
878                 .info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
879                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
880                         BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY), \
881                 .info_mask_shared_by_type_available = (_mask_type_av), \
882                 .ext_info = (_ext_info), \
883                 .scan_index = (_si), \
884                 .scan_type = { \
885                         .sign = 'u', \
886                         .realbits = 24, \
887                         .storagebits = 32, \
888                         .endianness = IIO_BE, \
889                 }, \
890         }
891
892 #define AD719x_DIFF_CHANNEL(_si, _channel1, _channel2, _address) \
893         __AD719x_CHANNEL(_si, _channel1, _channel2, _address, NULL, \
894                 IIO_VOLTAGE, BIT(IIO_CHAN_INFO_SCALE), \
895                 ad7192_calibsys_ext_info)
896
897 #define AD719x_CHANNEL(_si, _channel1, _address) \
898         __AD719x_CHANNEL(_si, _channel1, -1, _address, NULL, IIO_VOLTAGE, \
899                 BIT(IIO_CHAN_INFO_SCALE), ad7192_calibsys_ext_info)
900
901 #define AD719x_SHORTED_CHANNEL(_si, _channel1, _address) \
902         __AD719x_CHANNEL(_si, _channel1, -1, _address, "shorted", IIO_VOLTAGE, \
903                 BIT(IIO_CHAN_INFO_SCALE), ad7192_calibsys_ext_info)
904
905 #define AD719x_TEMP_CHANNEL(_si, _address) \
906         __AD719x_CHANNEL(_si, 0, -1, _address, NULL, IIO_TEMP, 0, NULL)
907
908 static const struct iio_chan_spec ad7192_channels[] = {
909         AD719x_DIFF_CHANNEL(0, 1, 2, AD7192_CH_AIN1P_AIN2M),
910         AD719x_DIFF_CHANNEL(1, 3, 4, AD7192_CH_AIN3P_AIN4M),
911         AD719x_TEMP_CHANNEL(2, AD7192_CH_TEMP),
912         AD719x_SHORTED_CHANNEL(3, 2, AD7192_CH_AIN2P_AIN2M),
913         AD719x_CHANNEL(4, 1, AD7192_CH_AIN1),
914         AD719x_CHANNEL(5, 2, AD7192_CH_AIN2),
915         AD719x_CHANNEL(6, 3, AD7192_CH_AIN3),
916         AD719x_CHANNEL(7, 4, AD7192_CH_AIN4),
917         IIO_CHAN_SOFT_TIMESTAMP(8),
918 };
919
920 static const struct iio_chan_spec ad7193_channels[] = {
921         AD719x_DIFF_CHANNEL(0, 1, 2, AD7193_CH_AIN1P_AIN2M),
922         AD719x_DIFF_CHANNEL(1, 3, 4, AD7193_CH_AIN3P_AIN4M),
923         AD719x_DIFF_CHANNEL(2, 5, 6, AD7193_CH_AIN5P_AIN6M),
924         AD719x_DIFF_CHANNEL(3, 7, 8, AD7193_CH_AIN7P_AIN8M),
925         AD719x_TEMP_CHANNEL(4, AD7193_CH_TEMP),
926         AD719x_SHORTED_CHANNEL(5, 2, AD7193_CH_AIN2P_AIN2M),
927         AD719x_CHANNEL(6, 1, AD7193_CH_AIN1),
928         AD719x_CHANNEL(7, 2, AD7193_CH_AIN2),
929         AD719x_CHANNEL(8, 3, AD7193_CH_AIN3),
930         AD719x_CHANNEL(9, 4, AD7193_CH_AIN4),
931         AD719x_CHANNEL(10, 5, AD7193_CH_AIN5),
932         AD719x_CHANNEL(11, 6, AD7193_CH_AIN6),
933         AD719x_CHANNEL(12, 7, AD7193_CH_AIN7),
934         AD719x_CHANNEL(13, 8, AD7193_CH_AIN8),
935         IIO_CHAN_SOFT_TIMESTAMP(14),
936 };
937
938 static const struct ad7192_chip_info ad7192_chip_info_tbl[] = {
939         [ID_AD7190] = {
940                 .chip_id = CHIPID_AD7190,
941                 .name = "ad7190",
942         },
943         [ID_AD7192] = {
944                 .chip_id = CHIPID_AD7192,
945                 .name = "ad7192",
946         },
947         [ID_AD7193] = {
948                 .chip_id = CHIPID_AD7193,
949                 .name = "ad7193",
950         },
951         [ID_AD7195] = {
952                 .chip_id = CHIPID_AD7195,
953                 .name = "ad7195",
954         },
955 };
956
957 static int ad7192_channels_config(struct iio_dev *indio_dev)
958 {
959         struct ad7192_state *st = iio_priv(indio_dev);
960
961         switch (st->chip_info->chip_id) {
962         case CHIPID_AD7193:
963                 indio_dev->channels = ad7193_channels;
964                 indio_dev->num_channels = ARRAY_SIZE(ad7193_channels);
965                 break;
966         default:
967                 indio_dev->channels = ad7192_channels;
968                 indio_dev->num_channels = ARRAY_SIZE(ad7192_channels);
969                 break;
970         }
971
972         return 0;
973 }
974
975 static void ad7192_reg_disable(void *reg)
976 {
977         regulator_disable(reg);
978 }
979
980 static void ad7192_clk_disable(void *clk)
981 {
982         clk_disable_unprepare(clk);
983 }
984
985 static int ad7192_probe(struct spi_device *spi)
986 {
987         struct ad7192_state *st;
988         struct iio_dev *indio_dev;
989         int ret;
990
991         if (!spi->irq) {
992                 dev_err(&spi->dev, "no IRQ?\n");
993                 return -ENODEV;
994         }
995
996         indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
997         if (!indio_dev)
998                 return -ENOMEM;
999
1000         st = iio_priv(indio_dev);
1001
1002         mutex_init(&st->lock);
1003
1004         st->avdd = devm_regulator_get(&spi->dev, "avdd");
1005         if (IS_ERR(st->avdd))
1006                 return PTR_ERR(st->avdd);
1007
1008         ret = regulator_enable(st->avdd);
1009         if (ret) {
1010                 dev_err(&spi->dev, "Failed to enable specified AVdd supply\n");
1011                 return ret;
1012         }
1013
1014         ret = devm_add_action_or_reset(&spi->dev, ad7192_reg_disable, st->avdd);
1015         if (ret)
1016                 return ret;
1017
1018         st->dvdd = devm_regulator_get(&spi->dev, "dvdd");
1019         if (IS_ERR(st->dvdd))
1020                 return PTR_ERR(st->dvdd);
1021
1022         ret = regulator_enable(st->dvdd);
1023         if (ret) {
1024                 dev_err(&spi->dev, "Failed to enable specified DVdd supply\n");
1025                 return ret;
1026         }
1027
1028         ret = devm_add_action_or_reset(&spi->dev, ad7192_reg_disable, st->dvdd);
1029         if (ret)
1030                 return ret;
1031
1032         ret = regulator_get_voltage(st->avdd);
1033         if (ret < 0) {
1034                 dev_err(&spi->dev, "Device tree error, reference voltage undefined\n");
1035                 return ret;
1036         }
1037         st->int_vref_mv = ret / 1000;
1038
1039         st->chip_info = of_device_get_match_data(&spi->dev);
1040         indio_dev->name = st->chip_info->name;
1041         indio_dev->modes = INDIO_DIRECT_MODE;
1042
1043         ret = ad7192_channels_config(indio_dev);
1044         if (ret < 0)
1045                 return ret;
1046
1047         if (st->chip_info->chip_id == CHIPID_AD7195)
1048                 indio_dev->info = &ad7195_info;
1049         else
1050                 indio_dev->info = &ad7192_info;
1051
1052         ad_sd_init(&st->sd, indio_dev, spi, &ad7192_sigma_delta_info);
1053
1054         ret = devm_ad_sd_setup_buffer_and_trigger(&spi->dev, indio_dev);
1055         if (ret)
1056                 return ret;
1057
1058         st->fclk = AD7192_INT_FREQ_MHZ;
1059
1060         st->mclk = devm_clk_get_optional(&spi->dev, "mclk");
1061         if (IS_ERR(st->mclk))
1062                 return PTR_ERR(st->mclk);
1063
1064         st->clock_sel = ad7192_of_clock_select(st);
1065
1066         if (st->clock_sel == AD7192_CLK_EXT_MCLK1_2 ||
1067             st->clock_sel == AD7192_CLK_EXT_MCLK2) {
1068                 ret = clk_prepare_enable(st->mclk);
1069                 if (ret < 0)
1070                         return ret;
1071
1072                 ret = devm_add_action_or_reset(&spi->dev, ad7192_clk_disable,
1073                                                st->mclk);
1074                 if (ret)
1075                         return ret;
1076
1077                 st->fclk = clk_get_rate(st->mclk);
1078                 if (!ad7192_valid_external_frequency(st->fclk)) {
1079                         dev_err(&spi->dev,
1080                                 "External clock frequency out of bounds\n");
1081                         return -EINVAL;
1082                 }
1083         }
1084
1085         ret = ad7192_setup(st, spi->dev.of_node);
1086         if (ret)
1087                 return ret;
1088
1089         return devm_iio_device_register(&spi->dev, indio_dev);
1090 }
1091
1092 static const struct of_device_id ad7192_of_match[] = {
1093         { .compatible = "adi,ad7190", .data = &ad7192_chip_info_tbl[ID_AD7190] },
1094         { .compatible = "adi,ad7192", .data = &ad7192_chip_info_tbl[ID_AD7192] },
1095         { .compatible = "adi,ad7193", .data = &ad7192_chip_info_tbl[ID_AD7193] },
1096         { .compatible = "adi,ad7195", .data = &ad7192_chip_info_tbl[ID_AD7195] },
1097         {}
1098 };
1099 MODULE_DEVICE_TABLE(of, ad7192_of_match);
1100
1101 static struct spi_driver ad7192_driver = {
1102         .driver = {
1103                 .name   = "ad7192",
1104                 .of_match_table = ad7192_of_match,
1105         },
1106         .probe          = ad7192_probe,
1107 };
1108 module_spi_driver(ad7192_driver);
1109
1110 MODULE_AUTHOR("Michael Hennerich <michael.hennerich@analog.com>");
1111 MODULE_DESCRIPTION("Analog Devices AD7190, AD7192, AD7193, AD7195 ADC");
1112 MODULE_LICENSE("GPL v2");
1113 MODULE_IMPORT_NS(IIO_AD_SIGMA_DELTA);