xref: /linux/drivers/iio/adc/stm32-dfsdm-adc.c (revision 955abe0a1b41de5ba61fe4cd614ebc123084d499)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This file is the ADC part of the STM32 DFSDM driver
4  *
5  * Copyright (C) 2017, STMicroelectronics - All Rights Reserved
6  * Author: Arnaud Pouliquen <arnaud.pouliquen@st.com>.
7  */
8 
9 #include <linux/dmaengine.h>
10 #include <linux/dma-mapping.h>
11 #include <linux/iio/adc/stm32-dfsdm-adc.h>
12 #include <linux/iio/buffer.h>
13 #include <linux/iio/hw-consumer.h>
14 #include <linux/iio/sysfs.h>
15 #include <linux/iio/timer/stm32-lptim-trigger.h>
16 #include <linux/iio/timer/stm32-timer-trigger.h>
17 #include <linux/iio/trigger.h>
18 #include <linux/iio/trigger_consumer.h>
19 #include <linux/iio/triggered_buffer.h>
20 #include <linux/interrupt.h>
21 #include <linux/module.h>
22 #include <linux/of.h>
23 #include <linux/of_platform.h>
24 #include <linux/platform_device.h>
25 #include <linux/regmap.h>
26 #include <linux/slab.h>
27 
28 #include "stm32-dfsdm.h"
29 
30 #define DFSDM_DMA_BUFFER_SIZE (4 * PAGE_SIZE)
31 
32 /* Conversion timeout */
33 #define DFSDM_TIMEOUT_US 100000
34 #define DFSDM_TIMEOUT (msecs_to_jiffies(DFSDM_TIMEOUT_US / 1000))
35 
36 /* Oversampling attribute default */
37 #define DFSDM_DEFAULT_OVERSAMPLING  100
38 
39 /* Oversampling max values */
40 #define DFSDM_MAX_INT_OVERSAMPLING 256
41 #define DFSDM_MAX_FL_OVERSAMPLING 1024
42 
43 /* Limit filter output resolution to 31 bits. (i.e. sample range is +/-2^30) */
44 #define DFSDM_DATA_MAX BIT(30)
45 /*
46  * Data are output as two's complement data in a 24 bit field.
47  * Data from filters are in the range +/-2^(n-1)
48  * 2^(n-1) maximum positive value cannot be coded in 2's complement n bits
49  * An extra bit is required to avoid wrap-around of the binary code for 2^(n-1)
50  * So, the resolution of samples from filter is actually limited to 23 bits
51  */
52 #define DFSDM_DATA_RES 24
53 
54 /* Filter configuration */
55 #define DFSDM_CR1_CFG_MASK (DFSDM_CR1_RCH_MASK | DFSDM_CR1_RCONT_MASK | \
56 			    DFSDM_CR1_RSYNC_MASK | DFSDM_CR1_JSYNC_MASK | \
57 			    DFSDM_CR1_JSCAN_MASK)
58 
59 enum sd_converter_type {
60 	DFSDM_AUDIO,
61 	DFSDM_IIO,
62 };
63 
64 struct stm32_dfsdm_dev_data {
65 	int type;
66 	int (*init)(struct device *dev, struct iio_dev *indio_dev);
67 	unsigned int num_channels;
68 	const struct regmap_config *regmap_cfg;
69 };
70 
71 struct stm32_dfsdm_adc {
72 	struct stm32_dfsdm *dfsdm;
73 	const struct stm32_dfsdm_dev_data *dev_data;
74 	unsigned int fl_id;
75 	unsigned int nconv;
76 	unsigned long smask;
77 
78 	/* ADC specific */
79 	unsigned int oversamp;
80 	struct iio_hw_consumer *hwc;
81 	struct completion completion;
82 	u32 *buffer;
83 
84 	/* Audio specific */
85 	unsigned int spi_freq;  /* SPI bus clock frequency */
86 	unsigned int sample_freq; /* Sample frequency after filter decimation */
87 	int (*cb)(const void *data, size_t size, void *cb_priv);
88 	void *cb_priv;
89 
90 	/* DMA */
91 	u8 *rx_buf;
92 	unsigned int bufi; /* Buffer current position */
93 	unsigned int buf_sz; /* Buffer size */
94 	struct dma_chan	*dma_chan;
95 	dma_addr_t dma_buf;
96 };
97 
98 struct stm32_dfsdm_str2field {
99 	const char	*name;
100 	unsigned int	val;
101 };
102 
103 /* DFSDM channel serial interface type */
104 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_type[] = {
105 	{ "SPI_R", 0 }, /* SPI with data on rising edge */
106 	{ "SPI_F", 1 }, /* SPI with data on falling edge */
107 	{ "MANCH_R", 2 }, /* Manchester codec, rising edge = logic 0 */
108 	{ "MANCH_F", 3 }, /* Manchester codec, falling edge = logic 1 */
109 	{},
110 };
111 
112 /* DFSDM channel clock source */
113 static const struct stm32_dfsdm_str2field stm32_dfsdm_chan_src[] = {
114 	/* External SPI clock (CLKIN x) */
115 	{ "CLKIN", DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL },
116 	/* Internal SPI clock (CLKOUT) */
117 	{ "CLKOUT", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL },
118 	/* Internal SPI clock divided by 2 (falling edge) */
119 	{ "CLKOUT_F", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING },
120 	/* Internal SPI clock divided by 2 (falling edge) */
121 	{ "CLKOUT_R", DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING },
122 	{},
123 };
124 
125 static int stm32_dfsdm_str2val(const char *str,
126 			       const struct stm32_dfsdm_str2field *list)
127 {
128 	const struct stm32_dfsdm_str2field *p = list;
129 
130 	for (p = list; p && p->name; p++)
131 		if (!strcmp(p->name, str))
132 			return p->val;
133 
134 	return -EINVAL;
135 }
136 
137 /**
138  * struct stm32_dfsdm_trig_info - DFSDM trigger info
139  * @name:		name of the trigger, corresponding to its source
140  * @jextsel:		trigger signal selection
141  */
142 struct stm32_dfsdm_trig_info {
143 	const char *name;
144 	unsigned int jextsel;
145 };
146 
147 /* hardware injected trigger enable, edge selection */
148 enum stm32_dfsdm_jexten {
149 	STM32_DFSDM_JEXTEN_DISABLED,
150 	STM32_DFSDM_JEXTEN_RISING_EDGE,
151 	STM32_DFSDM_JEXTEN_FALLING_EDGE,
152 	STM32_DFSDM_EXTEN_BOTH_EDGES,
153 };
154 
155 static const struct stm32_dfsdm_trig_info stm32_dfsdm_trigs[] = {
156 	{ TIM1_TRGO, 0 },
157 	{ TIM1_TRGO2, 1 },
158 	{ TIM8_TRGO, 2 },
159 	{ TIM8_TRGO2, 3 },
160 	{ TIM3_TRGO, 4 },
161 	{ TIM4_TRGO, 5 },
162 	{ TIM16_OC1, 6 },
163 	{ TIM6_TRGO, 7 },
164 	{ TIM7_TRGO, 8 },
165 	{ LPTIM1_OUT, 26 },
166 	{ LPTIM2_OUT, 27 },
167 	{ LPTIM3_OUT, 28 },
168 	{},
169 };
170 
171 static int stm32_dfsdm_get_jextsel(struct iio_dev *indio_dev,
172 				   struct iio_trigger *trig)
173 {
174 	int i;
175 
176 	/* lookup triggers registered by stm32 timer trigger driver */
177 	for (i = 0; stm32_dfsdm_trigs[i].name; i++) {
178 		/**
179 		 * Checking both stm32 timer trigger type and trig name
180 		 * should be safe against arbitrary trigger names.
181 		 */
182 		if ((is_stm32_timer_trigger(trig) ||
183 		     is_stm32_lptim_trigger(trig)) &&
184 		    !strcmp(stm32_dfsdm_trigs[i].name, trig->name)) {
185 			return stm32_dfsdm_trigs[i].jextsel;
186 		}
187 	}
188 
189 	return -EINVAL;
190 }
191 
192 static int stm32_dfsdm_compute_osrs(struct stm32_dfsdm_filter *fl,
193 				    unsigned int fast, unsigned int oversamp)
194 {
195 	unsigned int i, d, fosr, iosr;
196 	u64 res, max;
197 	int bits, shift;
198 	unsigned int m = 1;	/* multiplication factor */
199 	unsigned int p = fl->ford;	/* filter order (ford) */
200 	struct stm32_dfsdm_filter_osr *flo = &fl->flo[fast];
201 
202 	pr_debug("Requested oversampling: %d\n", oversamp);
203 	/*
204 	 * This function tries to compute filter oversampling and integrator
205 	 * oversampling, base on oversampling ratio requested by user.
206 	 *
207 	 * Decimation d depends on the filter order and the oversampling ratios.
208 	 * ford: filter order
209 	 * fosr: filter over sampling ratio
210 	 * iosr: integrator over sampling ratio
211 	 */
212 	if (fl->ford == DFSDM_FASTSINC_ORDER) {
213 		m = 2;
214 		p = 2;
215 	}
216 
217 	/*
218 	 * Look for filter and integrator oversampling ratios which allows
219 	 * to maximize data output resolution.
220 	 */
221 	for (fosr = 1; fosr <= DFSDM_MAX_FL_OVERSAMPLING; fosr++) {
222 		for (iosr = 1; iosr <= DFSDM_MAX_INT_OVERSAMPLING; iosr++) {
223 			if (fast)
224 				d = fosr * iosr;
225 			else if (fl->ford == DFSDM_FASTSINC_ORDER)
226 				d = fosr * (iosr + 3) + 2;
227 			else
228 				d = fosr * (iosr - 1 + p) + p;
229 
230 			if (d > oversamp)
231 				break;
232 			else if (d != oversamp)
233 				continue;
234 			/*
235 			 * Check resolution (limited to signed 32 bits)
236 			 *   res <= 2^31
237 			 * Sincx filters:
238 			 *   res = m * fosr^p x iosr (with m=1, p=ford)
239 			 * FastSinc filter
240 			 *   res = m * fosr^p x iosr (with m=2, p=2)
241 			 */
242 			res = fosr;
243 			for (i = p - 1; i > 0; i--) {
244 				res = res * (u64)fosr;
245 				if (res > DFSDM_DATA_MAX)
246 					break;
247 			}
248 			if (res > DFSDM_DATA_MAX)
249 				continue;
250 
251 			res = res * (u64)m * (u64)iosr;
252 			if (res > DFSDM_DATA_MAX)
253 				continue;
254 
255 			if (res >= flo->res) {
256 				flo->res = res;
257 				flo->fosr = fosr;
258 				flo->iosr = iosr;
259 
260 				bits = fls(flo->res);
261 				/* 8 LBSs in data register contain chan info */
262 				max = flo->res << 8;
263 
264 				/* if resolution is not a power of two */
265 				if (flo->res > BIT(bits - 1))
266 					bits++;
267 				else
268 					max--;
269 
270 				shift = DFSDM_DATA_RES - bits;
271 				/*
272 				 * Compute right/left shift
273 				 * Right shift is performed by hardware
274 				 * when transferring samples to data register.
275 				 * Left shift is done by software on buffer
276 				 */
277 				if (shift > 0) {
278 					/* Resolution is lower than 24 bits */
279 					flo->rshift = 0;
280 					flo->lshift = shift;
281 				} else {
282 					/*
283 					 * If resolution is 24 bits or more,
284 					 * max positive value may be ambiguous
285 					 * (equal to max negative value as sign
286 					 * bit is dropped).
287 					 * Reduce resolution to 23 bits (rshift)
288 					 * to keep the sign on bit 23 and treat
289 					 * saturation before rescaling on 24
290 					 * bits (lshift).
291 					 */
292 					flo->rshift = 1 - shift;
293 					flo->lshift = 1;
294 					max >>= flo->rshift;
295 				}
296 				flo->max = (s32)max;
297 				flo->bits = bits;
298 
299 				pr_debug("fast %d, fosr %d, iosr %d, res 0x%llx/%d bits, rshift %d, lshift %d\n",
300 					 fast, flo->fosr, flo->iosr,
301 					 flo->res, bits, flo->rshift,
302 					 flo->lshift);
303 			}
304 		}
305 	}
306 
307 	if (!flo->res)
308 		return -EINVAL;
309 
310 	return 0;
311 }
312 
313 static int stm32_dfsdm_compute_all_osrs(struct iio_dev *indio_dev,
314 					unsigned int oversamp)
315 {
316 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
317 	struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
318 	int ret0, ret1;
319 
320 	memset(&fl->flo[0], 0, sizeof(fl->flo[0]));
321 	memset(&fl->flo[1], 0, sizeof(fl->flo[1]));
322 
323 	ret0 = stm32_dfsdm_compute_osrs(fl, 0, oversamp);
324 	ret1 = stm32_dfsdm_compute_osrs(fl, 1, oversamp);
325 	if (ret0 < 0 && ret1 < 0) {
326 		dev_err(&indio_dev->dev,
327 			"Filter parameters not found: errors %d/%d\n",
328 			ret0, ret1);
329 		return -EINVAL;
330 	}
331 
332 	return 0;
333 }
334 
335 static int stm32_dfsdm_start_channel(struct iio_dev *indio_dev)
336 {
337 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
338 	struct regmap *regmap = adc->dfsdm->regmap;
339 	const struct iio_chan_spec *chan;
340 	unsigned int bit;
341 	int ret;
342 
343 	for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
344 		chan = indio_dev->channels + bit;
345 		ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
346 					 DFSDM_CHCFGR1_CHEN_MASK,
347 					 DFSDM_CHCFGR1_CHEN(1));
348 		if (ret < 0)
349 			return ret;
350 	}
351 
352 	return 0;
353 }
354 
355 static void stm32_dfsdm_stop_channel(struct iio_dev *indio_dev)
356 {
357 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
358 	struct regmap *regmap = adc->dfsdm->regmap;
359 	const struct iio_chan_spec *chan;
360 	unsigned int bit;
361 
362 	for_each_set_bit(bit, &adc->smask, sizeof(adc->smask) * BITS_PER_BYTE) {
363 		chan = indio_dev->channels + bit;
364 		regmap_update_bits(regmap, DFSDM_CHCFGR1(chan->channel),
365 				   DFSDM_CHCFGR1_CHEN_MASK,
366 				   DFSDM_CHCFGR1_CHEN(0));
367 	}
368 }
369 
370 static int stm32_dfsdm_chan_configure(struct stm32_dfsdm *dfsdm,
371 				      struct stm32_dfsdm_channel *ch)
372 {
373 	unsigned int id = ch->id;
374 	struct regmap *regmap = dfsdm->regmap;
375 	int ret;
376 
377 	ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
378 				 DFSDM_CHCFGR1_SITP_MASK,
379 				 DFSDM_CHCFGR1_SITP(ch->type));
380 	if (ret < 0)
381 		return ret;
382 	ret = regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
383 				 DFSDM_CHCFGR1_SPICKSEL_MASK,
384 				 DFSDM_CHCFGR1_SPICKSEL(ch->src));
385 	if (ret < 0)
386 		return ret;
387 	return regmap_update_bits(regmap, DFSDM_CHCFGR1(id),
388 				  DFSDM_CHCFGR1_CHINSEL_MASK,
389 				  DFSDM_CHCFGR1_CHINSEL(ch->alt_si));
390 }
391 
392 static int stm32_dfsdm_start_filter(struct stm32_dfsdm_adc *adc,
393 				    unsigned int fl_id,
394 				    struct iio_trigger *trig)
395 {
396 	struct stm32_dfsdm *dfsdm = adc->dfsdm;
397 	int ret;
398 
399 	/* Enable filter */
400 	ret = regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
401 				 DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(1));
402 	if (ret < 0)
403 		return ret;
404 
405 	/* Nothing more to do for injected (scan mode/triggered) conversions */
406 	if (adc->nconv > 1 || trig)
407 		return 0;
408 
409 	/* Software start (single or continuous) regular conversion */
410 	return regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
411 				  DFSDM_CR1_RSWSTART_MASK,
412 				  DFSDM_CR1_RSWSTART(1));
413 }
414 
415 static void stm32_dfsdm_stop_filter(struct stm32_dfsdm *dfsdm,
416 				    unsigned int fl_id)
417 {
418 	/* Disable conversion */
419 	regmap_update_bits(dfsdm->regmap, DFSDM_CR1(fl_id),
420 			   DFSDM_CR1_DFEN_MASK, DFSDM_CR1_DFEN(0));
421 }
422 
423 static int stm32_dfsdm_filter_set_trig(struct iio_dev *indio_dev,
424 				       unsigned int fl_id,
425 				       struct iio_trigger *trig)
426 {
427 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
428 	struct regmap *regmap = adc->dfsdm->regmap;
429 	u32 jextsel = 0, jexten = STM32_DFSDM_JEXTEN_DISABLED;
430 	int ret;
431 
432 	if (trig) {
433 		ret = stm32_dfsdm_get_jextsel(indio_dev, trig);
434 		if (ret < 0)
435 			return ret;
436 
437 		/* set trigger source and polarity (default to rising edge) */
438 		jextsel = ret;
439 		jexten = STM32_DFSDM_JEXTEN_RISING_EDGE;
440 	}
441 
442 	ret = regmap_update_bits(regmap, DFSDM_CR1(fl_id),
443 				 DFSDM_CR1_JEXTSEL_MASK | DFSDM_CR1_JEXTEN_MASK,
444 				 DFSDM_CR1_JEXTSEL(jextsel) |
445 				 DFSDM_CR1_JEXTEN(jexten));
446 	if (ret < 0)
447 		return ret;
448 
449 	return 0;
450 }
451 
452 static int stm32_dfsdm_channels_configure(struct iio_dev *indio_dev,
453 					  unsigned int fl_id,
454 					  struct iio_trigger *trig)
455 {
456 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
457 	struct regmap *regmap = adc->dfsdm->regmap;
458 	struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
459 	struct stm32_dfsdm_filter_osr *flo = &fl->flo[0];
460 	const struct iio_chan_spec *chan;
461 	unsigned int bit;
462 	int ret;
463 
464 	fl->fast = 0;
465 
466 	/*
467 	 * In continuous mode, use fast mode configuration,
468 	 * if it provides a better resolution.
469 	 */
470 	if (adc->nconv == 1 && !trig && iio_buffer_enabled(indio_dev)) {
471 		if (fl->flo[1].res >= fl->flo[0].res) {
472 			fl->fast = 1;
473 			flo = &fl->flo[1];
474 		}
475 	}
476 
477 	if (!flo->res)
478 		return -EINVAL;
479 
480 	dev_dbg(&indio_dev->dev, "Samples actual resolution: %d bits",
481 		min(flo->bits, (u32)DFSDM_DATA_RES - 1));
482 
483 	for_each_set_bit(bit, &adc->smask,
484 			 sizeof(adc->smask) * BITS_PER_BYTE) {
485 		chan = indio_dev->channels + bit;
486 
487 		ret = regmap_update_bits(regmap,
488 					 DFSDM_CHCFGR2(chan->channel),
489 					 DFSDM_CHCFGR2_DTRBS_MASK,
490 					 DFSDM_CHCFGR2_DTRBS(flo->rshift));
491 		if (ret)
492 			return ret;
493 	}
494 
495 	return 0;
496 }
497 
498 static int stm32_dfsdm_filter_configure(struct iio_dev *indio_dev,
499 					unsigned int fl_id,
500 					struct iio_trigger *trig)
501 {
502 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
503 	struct regmap *regmap = adc->dfsdm->regmap;
504 	struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[fl_id];
505 	struct stm32_dfsdm_filter_osr *flo = &fl->flo[fl->fast];
506 	u32 cr1;
507 	const struct iio_chan_spec *chan;
508 	unsigned int bit, jchg = 0;
509 	int ret;
510 
511 	/* Average integrator oversampling */
512 	ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_IOSR_MASK,
513 				 DFSDM_FCR_IOSR(flo->iosr - 1));
514 	if (ret)
515 		return ret;
516 
517 	/* Filter order and Oversampling */
518 	ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FOSR_MASK,
519 				 DFSDM_FCR_FOSR(flo->fosr - 1));
520 	if (ret)
521 		return ret;
522 
523 	ret = regmap_update_bits(regmap, DFSDM_FCR(fl_id), DFSDM_FCR_FORD_MASK,
524 				 DFSDM_FCR_FORD(fl->ford));
525 	if (ret)
526 		return ret;
527 
528 	ret = stm32_dfsdm_filter_set_trig(indio_dev, fl_id, trig);
529 	if (ret)
530 		return ret;
531 
532 	ret = regmap_update_bits(regmap, DFSDM_CR1(fl_id),
533 				 DFSDM_CR1_FAST_MASK,
534 				 DFSDM_CR1_FAST(fl->fast));
535 	if (ret)
536 		return ret;
537 
538 	/*
539 	 * DFSDM modes configuration W.R.T audio/iio type modes
540 	 * ----------------------------------------------------------------
541 	 * Modes         | regular |  regular     | injected | injected   |
542 	 *               |         |  continuous  |          | + scan     |
543 	 * --------------|---------|--------------|----------|------------|
544 	 * single conv   |    x    |              |          |            |
545 	 * (1 chan)      |         |              |          |            |
546 	 * --------------|---------|--------------|----------|------------|
547 	 * 1 Audio chan	 |         | sample freq  |          |            |
548 	 *               |         | or sync_mode |          |            |
549 	 * --------------|---------|--------------|----------|------------|
550 	 * 1 IIO chan	 |         | sample freq  | trigger  |            |
551 	 *               |         | or sync_mode |          |            |
552 	 * --------------|---------|--------------|----------|------------|
553 	 * 2+ IIO chans  |         |              |          | trigger or |
554 	 *               |         |              |          | sync_mode  |
555 	 * ----------------------------------------------------------------
556 	 */
557 	if (adc->nconv == 1 && !trig) {
558 		bit = __ffs(adc->smask);
559 		chan = indio_dev->channels + bit;
560 
561 		/* Use regular conversion for single channel without trigger */
562 		cr1 = DFSDM_CR1_RCH(chan->channel);
563 
564 		/* Continuous conversions triggered by SPI clk in buffer mode */
565 		if (iio_buffer_enabled(indio_dev))
566 			cr1 |= DFSDM_CR1_RCONT(1);
567 
568 		cr1 |= DFSDM_CR1_RSYNC(fl->sync_mode);
569 	} else {
570 		/* Use injected conversion for multiple channels */
571 		for_each_set_bit(bit, &adc->smask,
572 				 sizeof(adc->smask) * BITS_PER_BYTE) {
573 			chan = indio_dev->channels + bit;
574 			jchg |= BIT(chan->channel);
575 		}
576 		ret = regmap_write(regmap, DFSDM_JCHGR(fl_id), jchg);
577 		if (ret < 0)
578 			return ret;
579 
580 		/* Use scan mode for multiple channels */
581 		cr1 = DFSDM_CR1_JSCAN((adc->nconv > 1) ? 1 : 0);
582 
583 		/*
584 		 * Continuous conversions not supported in injected mode,
585 		 * either use:
586 		 * - conversions in sync with filter 0
587 		 * - triggered conversions
588 		 */
589 		if (!fl->sync_mode && !trig)
590 			return -EINVAL;
591 		cr1 |= DFSDM_CR1_JSYNC(fl->sync_mode);
592 	}
593 
594 	return regmap_update_bits(regmap, DFSDM_CR1(fl_id), DFSDM_CR1_CFG_MASK,
595 				  cr1);
596 }
597 
598 static int stm32_dfsdm_channel_parse_of(struct stm32_dfsdm *dfsdm,
599 					struct iio_dev *indio_dev,
600 					struct iio_chan_spec *ch)
601 {
602 	struct stm32_dfsdm_channel *df_ch;
603 	const char *of_str;
604 	int chan_idx = ch->scan_index;
605 	int ret, val;
606 
607 	ret = of_property_read_u32_index(indio_dev->dev.of_node,
608 					 "st,adc-channels", chan_idx,
609 					 &ch->channel);
610 	if (ret < 0) {
611 		dev_err(&indio_dev->dev,
612 			" Error parsing 'st,adc-channels' for idx %d\n",
613 			chan_idx);
614 		return ret;
615 	}
616 	if (ch->channel >= dfsdm->num_chs) {
617 		dev_err(&indio_dev->dev,
618 			" Error bad channel number %d (max = %d)\n",
619 			ch->channel, dfsdm->num_chs);
620 		return -EINVAL;
621 	}
622 
623 	ret = of_property_read_string_index(indio_dev->dev.of_node,
624 					    "st,adc-channel-names", chan_idx,
625 					    &ch->datasheet_name);
626 	if (ret < 0) {
627 		dev_err(&indio_dev->dev,
628 			" Error parsing 'st,adc-channel-names' for idx %d\n",
629 			chan_idx);
630 		return ret;
631 	}
632 
633 	df_ch =  &dfsdm->ch_list[ch->channel];
634 	df_ch->id = ch->channel;
635 
636 	ret = of_property_read_string_index(indio_dev->dev.of_node,
637 					    "st,adc-channel-types", chan_idx,
638 					    &of_str);
639 	if (!ret) {
640 		val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_type);
641 		if (val < 0)
642 			return val;
643 	} else {
644 		val = 0;
645 	}
646 	df_ch->type = val;
647 
648 	ret = of_property_read_string_index(indio_dev->dev.of_node,
649 					    "st,adc-channel-clk-src", chan_idx,
650 					    &of_str);
651 	if (!ret) {
652 		val = stm32_dfsdm_str2val(of_str, stm32_dfsdm_chan_src);
653 		if (val < 0)
654 			return val;
655 	} else {
656 		val = 0;
657 	}
658 	df_ch->src = val;
659 
660 	ret = of_property_read_u32_index(indio_dev->dev.of_node,
661 					 "st,adc-alt-channel", chan_idx,
662 					 &df_ch->alt_si);
663 	if (ret < 0)
664 		df_ch->alt_si = 0;
665 
666 	return 0;
667 }
668 
669 static ssize_t dfsdm_adc_audio_get_spiclk(struct iio_dev *indio_dev,
670 					  uintptr_t priv,
671 					  const struct iio_chan_spec *chan,
672 					  char *buf)
673 {
674 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
675 
676 	return snprintf(buf, PAGE_SIZE, "%d\n", adc->spi_freq);
677 }
678 
679 static int dfsdm_adc_set_samp_freq(struct iio_dev *indio_dev,
680 				   unsigned int sample_freq,
681 				   unsigned int spi_freq)
682 {
683 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
684 	unsigned int oversamp;
685 	int ret;
686 
687 	oversamp = DIV_ROUND_CLOSEST(spi_freq, sample_freq);
688 	if (spi_freq % sample_freq)
689 		dev_dbg(&indio_dev->dev,
690 			"Rate not accurate. requested (%u), actual (%u)\n",
691 			sample_freq, spi_freq / oversamp);
692 
693 	ret = stm32_dfsdm_compute_all_osrs(indio_dev, oversamp);
694 	if (ret < 0)
695 		return ret;
696 
697 	adc->sample_freq = spi_freq / oversamp;
698 	adc->oversamp = oversamp;
699 
700 	return 0;
701 }
702 
703 static ssize_t dfsdm_adc_audio_set_spiclk(struct iio_dev *indio_dev,
704 					  uintptr_t priv,
705 					  const struct iio_chan_spec *chan,
706 					  const char *buf, size_t len)
707 {
708 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
709 	struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
710 	unsigned int sample_freq = adc->sample_freq;
711 	unsigned int spi_freq;
712 	int ret;
713 
714 	dev_err(&indio_dev->dev, "enter %s\n", __func__);
715 	/* If DFSDM is master on SPI, SPI freq can not be updated */
716 	if (ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
717 		return -EPERM;
718 
719 	ret = kstrtoint(buf, 0, &spi_freq);
720 	if (ret)
721 		return ret;
722 
723 	if (!spi_freq)
724 		return -EINVAL;
725 
726 	if (sample_freq) {
727 		ret = dfsdm_adc_set_samp_freq(indio_dev, sample_freq, spi_freq);
728 		if (ret < 0)
729 			return ret;
730 	}
731 	adc->spi_freq = spi_freq;
732 
733 	return len;
734 }
735 
736 static int stm32_dfsdm_start_conv(struct iio_dev *indio_dev,
737 				  struct iio_trigger *trig)
738 {
739 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
740 	struct regmap *regmap = adc->dfsdm->regmap;
741 	int ret;
742 
743 	ret = stm32_dfsdm_channels_configure(indio_dev, adc->fl_id, trig);
744 	if (ret < 0)
745 		return ret;
746 
747 	ret = stm32_dfsdm_start_channel(indio_dev);
748 	if (ret < 0)
749 		return ret;
750 
751 	ret = stm32_dfsdm_filter_configure(indio_dev, adc->fl_id, trig);
752 	if (ret < 0)
753 		goto stop_channels;
754 
755 	ret = stm32_dfsdm_start_filter(adc, adc->fl_id, trig);
756 	if (ret < 0)
757 		goto filter_unconfigure;
758 
759 	return 0;
760 
761 filter_unconfigure:
762 	regmap_clear_bits(regmap, DFSDM_CR1(adc->fl_id), DFSDM_CR1_CFG_MASK);
763 stop_channels:
764 	stm32_dfsdm_stop_channel(indio_dev);
765 
766 	return ret;
767 }
768 
769 static void stm32_dfsdm_stop_conv(struct iio_dev *indio_dev)
770 {
771 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
772 	struct regmap *regmap = adc->dfsdm->regmap;
773 
774 	stm32_dfsdm_stop_filter(adc->dfsdm, adc->fl_id);
775 
776 	regmap_clear_bits(regmap, DFSDM_CR1(adc->fl_id), DFSDM_CR1_CFG_MASK);
777 
778 	stm32_dfsdm_stop_channel(indio_dev);
779 }
780 
781 static int stm32_dfsdm_set_watermark(struct iio_dev *indio_dev,
782 				     unsigned int val)
783 {
784 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
785 	unsigned int watermark = DFSDM_DMA_BUFFER_SIZE / 2;
786 	unsigned int rx_buf_sz = DFSDM_DMA_BUFFER_SIZE;
787 
788 	/*
789 	 * DMA cyclic transfers are used, buffer is split into two periods.
790 	 * There should be :
791 	 * - always one buffer (period) DMA is working on
792 	 * - one buffer (period) driver pushed to ASoC side.
793 	 */
794 	watermark = min(watermark, val * (unsigned int)(sizeof(u32)));
795 	adc->buf_sz = min(rx_buf_sz, watermark * 2 * adc->nconv);
796 
797 	return 0;
798 }
799 
800 static unsigned int stm32_dfsdm_adc_dma_residue(struct stm32_dfsdm_adc *adc)
801 {
802 	struct dma_tx_state state;
803 	enum dma_status status;
804 
805 	status = dmaengine_tx_status(adc->dma_chan,
806 				     adc->dma_chan->cookie,
807 				     &state);
808 	if (status == DMA_IN_PROGRESS) {
809 		/* Residue is size in bytes from end of buffer */
810 		unsigned int i = adc->buf_sz - state.residue;
811 		unsigned int size;
812 
813 		/* Return available bytes */
814 		if (i >= adc->bufi)
815 			size = i - adc->bufi;
816 		else
817 			size = adc->buf_sz + i - adc->bufi;
818 
819 		return size;
820 	}
821 
822 	return 0;
823 }
824 
825 static inline void stm32_dfsdm_process_data(struct stm32_dfsdm_adc *adc,
826 					    s32 *buffer)
827 {
828 	struct stm32_dfsdm_filter *fl = &adc->dfsdm->fl_list[adc->fl_id];
829 	struct stm32_dfsdm_filter_osr *flo = &fl->flo[fl->fast];
830 	unsigned int i = adc->nconv;
831 	s32 *ptr = buffer;
832 
833 	while (i--) {
834 		/* Mask 8 LSB that contains the channel ID */
835 		*ptr &= 0xFFFFFF00;
836 		/* Convert 2^(n-1) sample to 2^(n-1)-1 to avoid wrap-around */
837 		if (*ptr > flo->max)
838 			*ptr -= 1;
839 		/*
840 		 * Samples from filter are retrieved with 23 bits resolution
841 		 * or less. Shift left to align MSB on 24 bits.
842 		 */
843 		*ptr <<= flo->lshift;
844 
845 		ptr++;
846 	}
847 }
848 
849 static void stm32_dfsdm_dma_buffer_done(void *data)
850 {
851 	struct iio_dev *indio_dev = data;
852 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
853 	int available = stm32_dfsdm_adc_dma_residue(adc);
854 	size_t old_pos;
855 
856 	/*
857 	 * FIXME: In Kernel interface does not support cyclic DMA buffer,and
858 	 * offers only an interface to push data samples per samples.
859 	 * For this reason IIO buffer interface is not used and interface is
860 	 * bypassed using a private callback registered by ASoC.
861 	 * This should be a temporary solution waiting a cyclic DMA engine
862 	 * support in IIO.
863 	 */
864 
865 	dev_dbg(&indio_dev->dev, "pos = %d, available = %d\n",
866 		adc->bufi, available);
867 	old_pos = adc->bufi;
868 
869 	while (available >= indio_dev->scan_bytes) {
870 		s32 *buffer = (s32 *)&adc->rx_buf[adc->bufi];
871 
872 		stm32_dfsdm_process_data(adc, buffer);
873 
874 		available -= indio_dev->scan_bytes;
875 		adc->bufi += indio_dev->scan_bytes;
876 		if (adc->bufi >= adc->buf_sz) {
877 			if (adc->cb)
878 				adc->cb(&adc->rx_buf[old_pos],
879 					 adc->buf_sz - old_pos, adc->cb_priv);
880 			adc->bufi = 0;
881 			old_pos = 0;
882 		}
883 		/*
884 		 * In DMA mode the trigger services of IIO are not used
885 		 * (e.g. no call to iio_trigger_poll).
886 		 * Calling irq handler associated to the hardware trigger is not
887 		 * relevant as the conversions have already been done. Data
888 		 * transfers are performed directly in DMA callback instead.
889 		 * This implementation avoids to call trigger irq handler that
890 		 * may sleep, in an atomic context (DMA irq handler context).
891 		 */
892 		if (adc->dev_data->type == DFSDM_IIO)
893 			iio_push_to_buffers(indio_dev, buffer);
894 	}
895 	if (adc->cb)
896 		adc->cb(&adc->rx_buf[old_pos], adc->bufi - old_pos,
897 			adc->cb_priv);
898 }
899 
900 static int stm32_dfsdm_adc_dma_start(struct iio_dev *indio_dev)
901 {
902 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
903 	/*
904 	 * The DFSDM supports half-word transfers. However, for 16 bits record,
905 	 * 4 bytes buswidth is kept, to avoid losing samples LSBs when left
906 	 * shift is required.
907 	 */
908 	struct dma_slave_config config = {
909 		.src_addr = (dma_addr_t)adc->dfsdm->phys_base,
910 		.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
911 	};
912 	struct dma_async_tx_descriptor *desc;
913 	dma_cookie_t cookie;
914 	int ret;
915 
916 	if (!adc->dma_chan)
917 		return -EINVAL;
918 
919 	dev_dbg(&indio_dev->dev, "size=%d watermark=%d\n",
920 		adc->buf_sz, adc->buf_sz / 2);
921 
922 	if (adc->nconv == 1 && !indio_dev->trig)
923 		config.src_addr += DFSDM_RDATAR(adc->fl_id);
924 	else
925 		config.src_addr += DFSDM_JDATAR(adc->fl_id);
926 	ret = dmaengine_slave_config(adc->dma_chan, &config);
927 	if (ret)
928 		return ret;
929 
930 	/* Prepare a DMA cyclic transaction */
931 	desc = dmaengine_prep_dma_cyclic(adc->dma_chan,
932 					 adc->dma_buf,
933 					 adc->buf_sz, adc->buf_sz / 2,
934 					 DMA_DEV_TO_MEM,
935 					 DMA_PREP_INTERRUPT);
936 	if (!desc)
937 		return -EBUSY;
938 
939 	desc->callback = stm32_dfsdm_dma_buffer_done;
940 	desc->callback_param = indio_dev;
941 
942 	cookie = dmaengine_submit(desc);
943 	ret = dma_submit_error(cookie);
944 	if (ret)
945 		goto err_stop_dma;
946 
947 	/* Issue pending DMA requests */
948 	dma_async_issue_pending(adc->dma_chan);
949 
950 	if (adc->nconv == 1 && !indio_dev->trig) {
951 		/* Enable regular DMA transfer*/
952 		ret = regmap_set_bits(adc->dfsdm->regmap,
953 				      DFSDM_CR1(adc->fl_id),
954 				      DFSDM_CR1_RDMAEN_MASK);
955 	} else {
956 		/* Enable injected DMA transfer*/
957 		ret = regmap_set_bits(adc->dfsdm->regmap,
958 				      DFSDM_CR1(adc->fl_id),
959 				      DFSDM_CR1_JDMAEN_MASK);
960 	}
961 
962 	if (ret < 0)
963 		goto err_stop_dma;
964 
965 	return 0;
966 
967 err_stop_dma:
968 	dmaengine_terminate_all(adc->dma_chan);
969 
970 	return ret;
971 }
972 
973 static void stm32_dfsdm_adc_dma_stop(struct iio_dev *indio_dev)
974 {
975 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
976 
977 	if (!adc->dma_chan)
978 		return;
979 
980 	regmap_clear_bits(adc->dfsdm->regmap, DFSDM_CR1(adc->fl_id),
981 			  DFSDM_CR1_RDMAEN_MASK | DFSDM_CR1_JDMAEN_MASK);
982 	dmaengine_terminate_all(adc->dma_chan);
983 }
984 
985 static int stm32_dfsdm_update_scan_mode(struct iio_dev *indio_dev,
986 					const unsigned long *scan_mask)
987 {
988 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
989 
990 	adc->nconv = bitmap_weight(scan_mask, indio_dev->masklength);
991 	adc->smask = *scan_mask;
992 
993 	dev_dbg(&indio_dev->dev, "nconv=%d mask=%lx\n", adc->nconv, *scan_mask);
994 
995 	return 0;
996 }
997 
998 static int stm32_dfsdm_postenable(struct iio_dev *indio_dev)
999 {
1000 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1001 	int ret;
1002 
1003 	/* Reset adc buffer index */
1004 	adc->bufi = 0;
1005 
1006 	if (adc->hwc) {
1007 		ret = iio_hw_consumer_enable(adc->hwc);
1008 		if (ret < 0)
1009 			return ret;
1010 	}
1011 
1012 	ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
1013 	if (ret < 0)
1014 		goto err_stop_hwc;
1015 
1016 	ret = stm32_dfsdm_adc_dma_start(indio_dev);
1017 	if (ret) {
1018 		dev_err(&indio_dev->dev, "Can't start DMA\n");
1019 		goto stop_dfsdm;
1020 	}
1021 
1022 	ret = stm32_dfsdm_start_conv(indio_dev, indio_dev->trig);
1023 	if (ret) {
1024 		dev_err(&indio_dev->dev, "Can't start conversion\n");
1025 		goto err_stop_dma;
1026 	}
1027 
1028 	return 0;
1029 
1030 err_stop_dma:
1031 	stm32_dfsdm_adc_dma_stop(indio_dev);
1032 stop_dfsdm:
1033 	stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1034 err_stop_hwc:
1035 	if (adc->hwc)
1036 		iio_hw_consumer_disable(adc->hwc);
1037 
1038 	return ret;
1039 }
1040 
1041 static int stm32_dfsdm_predisable(struct iio_dev *indio_dev)
1042 {
1043 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1044 
1045 	stm32_dfsdm_stop_conv(indio_dev);
1046 
1047 	stm32_dfsdm_adc_dma_stop(indio_dev);
1048 
1049 	stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1050 
1051 	if (adc->hwc)
1052 		iio_hw_consumer_disable(adc->hwc);
1053 
1054 	return 0;
1055 }
1056 
1057 static const struct iio_buffer_setup_ops stm32_dfsdm_buffer_setup_ops = {
1058 	.postenable = &stm32_dfsdm_postenable,
1059 	.predisable = &stm32_dfsdm_predisable,
1060 };
1061 
1062 /**
1063  * stm32_dfsdm_get_buff_cb() - register a callback that will be called when
1064  *                             DMA transfer period is achieved.
1065  *
1066  * @iio_dev: Handle to IIO device.
1067  * @cb: Pointer to callback function:
1068  *      - data: pointer to data buffer
1069  *      - size: size in byte of the data buffer
1070  *      - private: pointer to consumer private structure.
1071  * @private: Pointer to consumer private structure.
1072  */
1073 int stm32_dfsdm_get_buff_cb(struct iio_dev *iio_dev,
1074 			    int (*cb)(const void *data, size_t size,
1075 				      void *private),
1076 			    void *private)
1077 {
1078 	struct stm32_dfsdm_adc *adc;
1079 
1080 	if (!iio_dev)
1081 		return -EINVAL;
1082 	adc = iio_priv(iio_dev);
1083 
1084 	adc->cb = cb;
1085 	adc->cb_priv = private;
1086 
1087 	return 0;
1088 }
1089 EXPORT_SYMBOL_GPL(stm32_dfsdm_get_buff_cb);
1090 
1091 /**
1092  * stm32_dfsdm_release_buff_cb - unregister buffer callback
1093  *
1094  * @iio_dev: Handle to IIO device.
1095  */
1096 int stm32_dfsdm_release_buff_cb(struct iio_dev *iio_dev)
1097 {
1098 	struct stm32_dfsdm_adc *adc;
1099 
1100 	if (!iio_dev)
1101 		return -EINVAL;
1102 	adc = iio_priv(iio_dev);
1103 
1104 	adc->cb = NULL;
1105 	adc->cb_priv = NULL;
1106 
1107 	return 0;
1108 }
1109 EXPORT_SYMBOL_GPL(stm32_dfsdm_release_buff_cb);
1110 
1111 static int stm32_dfsdm_single_conv(struct iio_dev *indio_dev,
1112 				   const struct iio_chan_spec *chan, int *res)
1113 {
1114 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1115 	long time_left;
1116 	int ret;
1117 
1118 	reinit_completion(&adc->completion);
1119 
1120 	adc->buffer = res;
1121 
1122 	ret = stm32_dfsdm_start_dfsdm(adc->dfsdm);
1123 	if (ret < 0)
1124 		return ret;
1125 
1126 	ret = regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1127 				 DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(1));
1128 	if (ret < 0)
1129 		goto stop_dfsdm;
1130 
1131 	adc->nconv = 1;
1132 	adc->smask = BIT(chan->scan_index);
1133 	ret = stm32_dfsdm_start_conv(indio_dev, NULL);
1134 	if (ret < 0) {
1135 		regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1136 				   DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1137 		goto stop_dfsdm;
1138 	}
1139 
1140 	time_left = wait_for_completion_interruptible_timeout(&adc->completion,
1141 							      DFSDM_TIMEOUT);
1142 
1143 	/* Mask IRQ for regular conversion achievement*/
1144 	regmap_update_bits(adc->dfsdm->regmap, DFSDM_CR2(adc->fl_id),
1145 			   DFSDM_CR2_REOCIE_MASK, DFSDM_CR2_REOCIE(0));
1146 
1147 	if (time_left == 0)
1148 		ret = -ETIMEDOUT;
1149 	else if (time_left < 0)
1150 		ret = time_left;
1151 	else
1152 		ret = IIO_VAL_INT;
1153 
1154 	stm32_dfsdm_stop_conv(indio_dev);
1155 
1156 	stm32_dfsdm_process_data(adc, res);
1157 
1158 stop_dfsdm:
1159 	stm32_dfsdm_stop_dfsdm(adc->dfsdm);
1160 
1161 	return ret;
1162 }
1163 
1164 static int stm32_dfsdm_write_raw(struct iio_dev *indio_dev,
1165 				 struct iio_chan_spec const *chan,
1166 				 int val, int val2, long mask)
1167 {
1168 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1169 	struct stm32_dfsdm_channel *ch = &adc->dfsdm->ch_list[chan->channel];
1170 	unsigned int spi_freq;
1171 	int ret = -EINVAL;
1172 
1173 	switch (ch->src) {
1174 	case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL:
1175 		spi_freq = adc->dfsdm->spi_master_freq;
1176 		break;
1177 	case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_FALLING:
1178 	case DFSDM_CHANNEL_SPI_CLOCK_INTERNAL_DIV2_RISING:
1179 		spi_freq = adc->dfsdm->spi_master_freq / 2;
1180 		break;
1181 	default:
1182 		spi_freq = adc->spi_freq;
1183 	}
1184 
1185 	switch (mask) {
1186 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1187 		ret = iio_device_claim_direct_mode(indio_dev);
1188 		if (ret)
1189 			return ret;
1190 
1191 		ret = stm32_dfsdm_compute_all_osrs(indio_dev, val);
1192 		if (!ret) {
1193 			dev_dbg(&indio_dev->dev,
1194 				"Sampling rate changed from (%u) to (%u)\n",
1195 				adc->sample_freq, spi_freq / val);
1196 			adc->oversamp = val;
1197 			adc->sample_freq = spi_freq / val;
1198 		}
1199 		iio_device_release_direct_mode(indio_dev);
1200 		return ret;
1201 
1202 	case IIO_CHAN_INFO_SAMP_FREQ:
1203 		if (!val)
1204 			return -EINVAL;
1205 
1206 		ret = iio_device_claim_direct_mode(indio_dev);
1207 		if (ret)
1208 			return ret;
1209 
1210 		ret = dfsdm_adc_set_samp_freq(indio_dev, val, spi_freq);
1211 		iio_device_release_direct_mode(indio_dev);
1212 		return ret;
1213 	}
1214 
1215 	return -EINVAL;
1216 }
1217 
1218 static int stm32_dfsdm_read_raw(struct iio_dev *indio_dev,
1219 				struct iio_chan_spec const *chan, int *val,
1220 				int *val2, long mask)
1221 {
1222 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1223 	int ret;
1224 
1225 	switch (mask) {
1226 	case IIO_CHAN_INFO_RAW:
1227 		ret = iio_device_claim_direct_mode(indio_dev);
1228 		if (ret)
1229 			return ret;
1230 		ret = iio_hw_consumer_enable(adc->hwc);
1231 		if (ret < 0) {
1232 			dev_err(&indio_dev->dev,
1233 				"%s: IIO enable failed (channel %d)\n",
1234 				__func__, chan->channel);
1235 			iio_device_release_direct_mode(indio_dev);
1236 			return ret;
1237 		}
1238 		ret = stm32_dfsdm_single_conv(indio_dev, chan, val);
1239 		iio_hw_consumer_disable(adc->hwc);
1240 		if (ret < 0) {
1241 			dev_err(&indio_dev->dev,
1242 				"%s: Conversion failed (channel %d)\n",
1243 				__func__, chan->channel);
1244 			iio_device_release_direct_mode(indio_dev);
1245 			return ret;
1246 		}
1247 		iio_device_release_direct_mode(indio_dev);
1248 		return IIO_VAL_INT;
1249 
1250 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1251 		*val = adc->oversamp;
1252 
1253 		return IIO_VAL_INT;
1254 
1255 	case IIO_CHAN_INFO_SAMP_FREQ:
1256 		*val = adc->sample_freq;
1257 
1258 		return IIO_VAL_INT;
1259 	}
1260 
1261 	return -EINVAL;
1262 }
1263 
1264 static int stm32_dfsdm_validate_trigger(struct iio_dev *indio_dev,
1265 					struct iio_trigger *trig)
1266 {
1267 	return stm32_dfsdm_get_jextsel(indio_dev, trig) < 0 ? -EINVAL : 0;
1268 }
1269 
1270 static const struct iio_info stm32_dfsdm_info_audio = {
1271 	.hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1272 	.read_raw = stm32_dfsdm_read_raw,
1273 	.write_raw = stm32_dfsdm_write_raw,
1274 	.update_scan_mode = stm32_dfsdm_update_scan_mode,
1275 };
1276 
1277 static const struct iio_info stm32_dfsdm_info_adc = {
1278 	.hwfifo_set_watermark = stm32_dfsdm_set_watermark,
1279 	.read_raw = stm32_dfsdm_read_raw,
1280 	.write_raw = stm32_dfsdm_write_raw,
1281 	.update_scan_mode = stm32_dfsdm_update_scan_mode,
1282 	.validate_trigger = stm32_dfsdm_validate_trigger,
1283 };
1284 
1285 static irqreturn_t stm32_dfsdm_irq(int irq, void *arg)
1286 {
1287 	struct iio_dev *indio_dev = arg;
1288 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1289 	struct regmap *regmap = adc->dfsdm->regmap;
1290 	unsigned int status, int_en;
1291 
1292 	regmap_read(regmap, DFSDM_ISR(adc->fl_id), &status);
1293 	regmap_read(regmap, DFSDM_CR2(adc->fl_id), &int_en);
1294 
1295 	if (status & DFSDM_ISR_REOCF_MASK) {
1296 		/* Read the data register clean the IRQ status */
1297 		regmap_read(regmap, DFSDM_RDATAR(adc->fl_id), adc->buffer);
1298 		complete(&adc->completion);
1299 	}
1300 
1301 	if (status & DFSDM_ISR_ROVRF_MASK) {
1302 		if (int_en & DFSDM_CR2_ROVRIE_MASK)
1303 			dev_warn(&indio_dev->dev, "Overrun detected\n");
1304 		regmap_set_bits(regmap, DFSDM_ICR(adc->fl_id),
1305 				DFSDM_ICR_CLRROVRF_MASK);
1306 	}
1307 
1308 	return IRQ_HANDLED;
1309 }
1310 
1311 /*
1312  * Define external info for SPI Frequency and audio sampling rate that can be
1313  * configured by ASoC driver through consumer.h API
1314  */
1315 static const struct iio_chan_spec_ext_info dfsdm_adc_audio_ext_info[] = {
1316 	/* spi_clk_freq : clock freq on SPI/manchester bus used by channel */
1317 	{
1318 		.name = "spi_clk_freq",
1319 		.shared = IIO_SHARED_BY_TYPE,
1320 		.read = dfsdm_adc_audio_get_spiclk,
1321 		.write = dfsdm_adc_audio_set_spiclk,
1322 	},
1323 	{},
1324 };
1325 
1326 static void stm32_dfsdm_dma_release(struct iio_dev *indio_dev)
1327 {
1328 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1329 
1330 	if (adc->dma_chan) {
1331 		dma_free_coherent(adc->dma_chan->device->dev,
1332 				  DFSDM_DMA_BUFFER_SIZE,
1333 				  adc->rx_buf, adc->dma_buf);
1334 		dma_release_channel(adc->dma_chan);
1335 	}
1336 }
1337 
1338 static int stm32_dfsdm_dma_request(struct device *dev,
1339 				   struct iio_dev *indio_dev)
1340 {
1341 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1342 
1343 	adc->dma_chan = dma_request_chan(dev, "rx");
1344 	if (IS_ERR(adc->dma_chan)) {
1345 		int ret = PTR_ERR(adc->dma_chan);
1346 
1347 		adc->dma_chan = NULL;
1348 		return ret;
1349 	}
1350 
1351 	adc->rx_buf = dma_alloc_coherent(adc->dma_chan->device->dev,
1352 					 DFSDM_DMA_BUFFER_SIZE,
1353 					 &adc->dma_buf, GFP_KERNEL);
1354 	if (!adc->rx_buf) {
1355 		dma_release_channel(adc->dma_chan);
1356 		return -ENOMEM;
1357 	}
1358 
1359 	indio_dev->modes |= INDIO_BUFFER_SOFTWARE;
1360 	indio_dev->setup_ops = &stm32_dfsdm_buffer_setup_ops;
1361 
1362 	return 0;
1363 }
1364 
1365 static int stm32_dfsdm_adc_chan_init_one(struct iio_dev *indio_dev,
1366 					 struct iio_chan_spec *ch)
1367 {
1368 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1369 	int ret;
1370 
1371 	ret = stm32_dfsdm_channel_parse_of(adc->dfsdm, indio_dev, ch);
1372 	if (ret < 0)
1373 		return ret;
1374 
1375 	ch->type = IIO_VOLTAGE;
1376 	ch->indexed = 1;
1377 
1378 	/*
1379 	 * IIO_CHAN_INFO_RAW: used to compute regular conversion
1380 	 * IIO_CHAN_INFO_OVERSAMPLING_RATIO: used to set oversampling
1381 	 */
1382 	ch->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1383 	ch->info_mask_shared_by_all = BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |
1384 					BIT(IIO_CHAN_INFO_SAMP_FREQ);
1385 
1386 	if (adc->dev_data->type == DFSDM_AUDIO) {
1387 		ch->ext_info = dfsdm_adc_audio_ext_info;
1388 	} else {
1389 		ch->scan_type.shift = 8;
1390 	}
1391 	ch->scan_type.sign = 's';
1392 	ch->scan_type.realbits = 24;
1393 	ch->scan_type.storagebits = 32;
1394 
1395 	return stm32_dfsdm_chan_configure(adc->dfsdm,
1396 					  &adc->dfsdm->ch_list[ch->channel]);
1397 }
1398 
1399 static int stm32_dfsdm_audio_init(struct device *dev, struct iio_dev *indio_dev)
1400 {
1401 	struct iio_chan_spec *ch;
1402 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1403 	struct stm32_dfsdm_channel *d_ch;
1404 	int ret;
1405 
1406 	ch = devm_kzalloc(&indio_dev->dev, sizeof(*ch), GFP_KERNEL);
1407 	if (!ch)
1408 		return -ENOMEM;
1409 
1410 	ch->scan_index = 0;
1411 
1412 	ret = stm32_dfsdm_adc_chan_init_one(indio_dev, ch);
1413 	if (ret < 0) {
1414 		dev_err(&indio_dev->dev, "Channels init failed\n");
1415 		return ret;
1416 	}
1417 	ch->info_mask_separate = BIT(IIO_CHAN_INFO_SAMP_FREQ);
1418 
1419 	d_ch = &adc->dfsdm->ch_list[ch->channel];
1420 	if (d_ch->src != DFSDM_CHANNEL_SPI_CLOCK_EXTERNAL)
1421 		adc->spi_freq = adc->dfsdm->spi_master_freq;
1422 
1423 	indio_dev->num_channels = 1;
1424 	indio_dev->channels = ch;
1425 
1426 	return stm32_dfsdm_dma_request(dev, indio_dev);
1427 }
1428 
1429 static int stm32_dfsdm_adc_init(struct device *dev, struct iio_dev *indio_dev)
1430 {
1431 	struct iio_chan_spec *ch;
1432 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1433 	int num_ch;
1434 	int ret, chan_idx;
1435 
1436 	adc->oversamp = DFSDM_DEFAULT_OVERSAMPLING;
1437 	ret = stm32_dfsdm_compute_all_osrs(indio_dev, adc->oversamp);
1438 	if (ret < 0)
1439 		return ret;
1440 
1441 	num_ch = of_property_count_u32_elems(indio_dev->dev.of_node,
1442 					     "st,adc-channels");
1443 	if (num_ch < 0 || num_ch > adc->dfsdm->num_chs) {
1444 		dev_err(&indio_dev->dev, "Bad st,adc-channels\n");
1445 		return num_ch < 0 ? num_ch : -EINVAL;
1446 	}
1447 
1448 	/* Bind to SD modulator IIO device */
1449 	adc->hwc = devm_iio_hw_consumer_alloc(&indio_dev->dev);
1450 	if (IS_ERR(adc->hwc))
1451 		return -EPROBE_DEFER;
1452 
1453 	ch = devm_kcalloc(&indio_dev->dev, num_ch, sizeof(*ch),
1454 			  GFP_KERNEL);
1455 	if (!ch)
1456 		return -ENOMEM;
1457 
1458 	for (chan_idx = 0; chan_idx < num_ch; chan_idx++) {
1459 		ch[chan_idx].scan_index = chan_idx;
1460 		ret = stm32_dfsdm_adc_chan_init_one(indio_dev, &ch[chan_idx]);
1461 		if (ret < 0) {
1462 			dev_err(&indio_dev->dev, "Channels init failed\n");
1463 			return ret;
1464 		}
1465 	}
1466 
1467 	indio_dev->num_channels = num_ch;
1468 	indio_dev->channels = ch;
1469 
1470 	init_completion(&adc->completion);
1471 
1472 	/* Optionally request DMA */
1473 	ret = stm32_dfsdm_dma_request(dev, indio_dev);
1474 	if (ret) {
1475 		if (ret != -ENODEV)
1476 			return dev_err_probe(dev, ret,
1477 					     "DMA channel request failed with\n");
1478 
1479 		dev_dbg(dev, "No DMA support\n");
1480 		return 0;
1481 	}
1482 
1483 	ret = iio_triggered_buffer_setup(indio_dev,
1484 					 &iio_pollfunc_store_time, NULL,
1485 					 &stm32_dfsdm_buffer_setup_ops);
1486 	if (ret) {
1487 		stm32_dfsdm_dma_release(indio_dev);
1488 		dev_err(&indio_dev->dev, "buffer setup failed\n");
1489 		return ret;
1490 	}
1491 
1492 	/* lptimer/timer hardware triggers */
1493 	indio_dev->modes |= INDIO_HARDWARE_TRIGGERED;
1494 
1495 	return 0;
1496 }
1497 
1498 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_adc_data = {
1499 	.type = DFSDM_IIO,
1500 	.init = stm32_dfsdm_adc_init,
1501 };
1502 
1503 static const struct stm32_dfsdm_dev_data stm32h7_dfsdm_audio_data = {
1504 	.type = DFSDM_AUDIO,
1505 	.init = stm32_dfsdm_audio_init,
1506 };
1507 
1508 static const struct of_device_id stm32_dfsdm_adc_match[] = {
1509 	{
1510 		.compatible = "st,stm32-dfsdm-adc",
1511 		.data = &stm32h7_dfsdm_adc_data,
1512 	},
1513 	{
1514 		.compatible = "st,stm32-dfsdm-dmic",
1515 		.data = &stm32h7_dfsdm_audio_data,
1516 	},
1517 	{}
1518 };
1519 MODULE_DEVICE_TABLE(of, stm32_dfsdm_adc_match);
1520 
1521 static int stm32_dfsdm_adc_probe(struct platform_device *pdev)
1522 {
1523 	struct device *dev = &pdev->dev;
1524 	struct stm32_dfsdm_adc *adc;
1525 	struct device_node *np = dev->of_node;
1526 	const struct stm32_dfsdm_dev_data *dev_data;
1527 	struct iio_dev *iio;
1528 	char *name;
1529 	int ret, irq, val;
1530 
1531 	dev_data = of_device_get_match_data(dev);
1532 	iio = devm_iio_device_alloc(dev, sizeof(*adc));
1533 	if (!iio) {
1534 		dev_err(dev, "%s: Failed to allocate IIO\n", __func__);
1535 		return -ENOMEM;
1536 	}
1537 
1538 	adc = iio_priv(iio);
1539 	adc->dfsdm = dev_get_drvdata(dev->parent);
1540 
1541 	iio->dev.of_node = np;
1542 	iio->modes = INDIO_DIRECT_MODE;
1543 
1544 	platform_set_drvdata(pdev, iio);
1545 
1546 	ret = of_property_read_u32(dev->of_node, "reg", &adc->fl_id);
1547 	if (ret != 0 || adc->fl_id >= adc->dfsdm->num_fls) {
1548 		dev_err(dev, "Missing or bad reg property\n");
1549 		return -EINVAL;
1550 	}
1551 
1552 	name = devm_kzalloc(dev, sizeof("dfsdm-adc0"), GFP_KERNEL);
1553 	if (!name)
1554 		return -ENOMEM;
1555 	if (dev_data->type == DFSDM_AUDIO) {
1556 		iio->info = &stm32_dfsdm_info_audio;
1557 		snprintf(name, sizeof("dfsdm-pdm0"), "dfsdm-pdm%d", adc->fl_id);
1558 	} else {
1559 		iio->info = &stm32_dfsdm_info_adc;
1560 		snprintf(name, sizeof("dfsdm-adc0"), "dfsdm-adc%d", adc->fl_id);
1561 	}
1562 	iio->name = name;
1563 
1564 	/*
1565 	 * In a first step IRQs generated for channels are not treated.
1566 	 * So IRQ associated to filter instance 0 is dedicated to the Filter 0.
1567 	 */
1568 	irq = platform_get_irq(pdev, 0);
1569 	if (irq < 0)
1570 		return irq;
1571 
1572 	ret = devm_request_irq(dev, irq, stm32_dfsdm_irq,
1573 			       0, pdev->name, iio);
1574 	if (ret < 0) {
1575 		dev_err(dev, "Failed to request IRQ\n");
1576 		return ret;
1577 	}
1578 
1579 	ret = of_property_read_u32(dev->of_node, "st,filter-order", &val);
1580 	if (ret < 0) {
1581 		dev_err(dev, "Failed to set filter order\n");
1582 		return ret;
1583 	}
1584 
1585 	adc->dfsdm->fl_list[adc->fl_id].ford = val;
1586 
1587 	ret = of_property_read_u32(dev->of_node, "st,filter0-sync", &val);
1588 	if (!ret)
1589 		adc->dfsdm->fl_list[adc->fl_id].sync_mode = val;
1590 
1591 	adc->dev_data = dev_data;
1592 	ret = dev_data->init(dev, iio);
1593 	if (ret < 0)
1594 		return ret;
1595 
1596 	ret = iio_device_register(iio);
1597 	if (ret < 0)
1598 		goto err_cleanup;
1599 
1600 	if (dev_data->type == DFSDM_AUDIO) {
1601 		ret = of_platform_populate(np, NULL, NULL, dev);
1602 		if (ret < 0) {
1603 			dev_err(dev, "Failed to find an audio DAI\n");
1604 			goto err_unregister;
1605 		}
1606 	}
1607 
1608 	return 0;
1609 
1610 err_unregister:
1611 	iio_device_unregister(iio);
1612 err_cleanup:
1613 	stm32_dfsdm_dma_release(iio);
1614 
1615 	return ret;
1616 }
1617 
1618 static void stm32_dfsdm_adc_remove(struct platform_device *pdev)
1619 {
1620 	struct iio_dev *indio_dev = platform_get_drvdata(pdev);
1621 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1622 
1623 	if (adc->dev_data->type == DFSDM_AUDIO)
1624 		of_platform_depopulate(&pdev->dev);
1625 	iio_device_unregister(indio_dev);
1626 	stm32_dfsdm_dma_release(indio_dev);
1627 }
1628 
1629 static int stm32_dfsdm_adc_suspend(struct device *dev)
1630 {
1631 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1632 
1633 	if (iio_buffer_enabled(indio_dev))
1634 		stm32_dfsdm_predisable(indio_dev);
1635 
1636 	return 0;
1637 }
1638 
1639 static int stm32_dfsdm_adc_resume(struct device *dev)
1640 {
1641 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
1642 	struct stm32_dfsdm_adc *adc = iio_priv(indio_dev);
1643 	const struct iio_chan_spec *chan;
1644 	struct stm32_dfsdm_channel *ch;
1645 	int i, ret;
1646 
1647 	/* restore channels configuration */
1648 	for (i = 0; i < indio_dev->num_channels; i++) {
1649 		chan = indio_dev->channels + i;
1650 		ch = &adc->dfsdm->ch_list[chan->channel];
1651 		ret = stm32_dfsdm_chan_configure(adc->dfsdm, ch);
1652 		if (ret)
1653 			return ret;
1654 	}
1655 
1656 	if (iio_buffer_enabled(indio_dev))
1657 		stm32_dfsdm_postenable(indio_dev);
1658 
1659 	return 0;
1660 }
1661 
1662 static DEFINE_SIMPLE_DEV_PM_OPS(stm32_dfsdm_adc_pm_ops,
1663 				stm32_dfsdm_adc_suspend,
1664 				stm32_dfsdm_adc_resume);
1665 
1666 static struct platform_driver stm32_dfsdm_adc_driver = {
1667 	.driver = {
1668 		.name = "stm32-dfsdm-adc",
1669 		.of_match_table = stm32_dfsdm_adc_match,
1670 		.pm = pm_sleep_ptr(&stm32_dfsdm_adc_pm_ops),
1671 	},
1672 	.probe = stm32_dfsdm_adc_probe,
1673 	.remove_new = stm32_dfsdm_adc_remove,
1674 };
1675 module_platform_driver(stm32_dfsdm_adc_driver);
1676 
1677 MODULE_DESCRIPTION("STM32 sigma delta ADC");
1678 MODULE_AUTHOR("Arnaud Pouliquen <arnaud.pouliquen@st.com>");
1679 MODULE_LICENSE("GPL v2");
1680