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