xref: /linux/drivers/iio/adc/envelope-detector.c (revision 889600e21e3be388a6817c2a0dac0411df860751)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Driver for an envelope detector using a DAC and a comparator
4  *
5  * Copyright (C) 2016 Axentia Technologies AB
6  *
7  * Author: Peter Rosin <peda@axentia.se>
8  */
9 
10 /*
11  * The DAC is used to find the peak level of an alternating voltage input
12  * signal by a binary search using the output of a comparator wired to
13  * an interrupt pin. Like so:
14  *                           _
15  *                          | \
16  *     input +------>-------|+ \
17  *                          |   \
18  *            .-------.     |    }---.
19  *            |       |     |   /    |
20  *            |    dac|-->--|- /     |
21  *            |       |     |_/      |
22  *            |       |              |
23  *            |       |              |
24  *            |    irq|------<-------'
25  *            |       |
26  *            '-------'
27  */
28 
29 #include <linux/completion.h>
30 #include <linux/device.h>
31 #include <linux/err.h>
32 #include <linux/kernel.h>
33 #include <linux/module.h>
34 #include <linux/mutex.h>
35 #include <linux/iio/consumer.h>
36 #include <linux/iio/iio.h>
37 #include <linux/iio/sysfs.h>
38 #include <linux/interrupt.h>
39 #include <linux/irq.h>
40 #include <linux/platform_device.h>
41 #include <linux/spinlock.h>
42 #include <linux/workqueue.h>
43 
44 struct envelope {
45 	spinlock_t comp_lock; /* protects comp */
46 	int comp;
47 
48 	struct mutex read_lock; /* protects everything else */
49 
50 	int comp_irq;
51 	u32 comp_irq_trigger;
52 	u32 comp_irq_trigger_inv;
53 
54 	struct iio_channel *dac;
55 	struct delayed_work comp_timeout;
56 
57 	unsigned int comp_interval;
58 	bool invert;
59 	u32 dac_max;
60 
61 	int high;
62 	int level;
63 	int low;
64 
65 	struct completion done;
66 };
67 
68 /*
69  * The envelope_detector_comp_latch function works together with the compare
70  * interrupt service routine below (envelope_detector_comp_isr) as a latch
71  * (one-bit memory) for if the interrupt has triggered since last calling
72  * this function.
73  * The ..._comp_isr function disables the interrupt so that the cpu does not
74  * need to service a possible interrupt flood from the comparator when no-one
75  * cares anyway, and this ..._comp_latch function reenables them again if
76  * needed.
77  */
envelope_detector_comp_latch(struct envelope * env)78 static int envelope_detector_comp_latch(struct envelope *env)
79 {
80 	int comp;
81 
82 	spin_lock_irq(&env->comp_lock);
83 	comp = env->comp;
84 	env->comp = 0;
85 	spin_unlock_irq(&env->comp_lock);
86 
87 	if (!comp)
88 		return 0;
89 
90 	/*
91 	 * The irq was disabled, and is reenabled just now.
92 	 * But there might have been a pending irq that
93 	 * happened while the irq was disabled that fires
94 	 * just as the irq is reenabled. That is not what
95 	 * is desired.
96 	 */
97 	enable_irq(env->comp_irq);
98 
99 	/* So, synchronize this possibly pending irq... */
100 	synchronize_irq(env->comp_irq);
101 
102 	/* ...and redo the whole dance. */
103 	spin_lock_irq(&env->comp_lock);
104 	comp = env->comp;
105 	env->comp = 0;
106 	spin_unlock_irq(&env->comp_lock);
107 
108 	if (comp)
109 		enable_irq(env->comp_irq);
110 
111 	return 1;
112 }
113 
envelope_detector_comp_isr(int irq,void * ctx)114 static irqreturn_t envelope_detector_comp_isr(int irq, void *ctx)
115 {
116 	struct envelope *env = ctx;
117 
118 	spin_lock(&env->comp_lock);
119 	env->comp = 1;
120 	disable_irq_nosync(env->comp_irq);
121 	spin_unlock(&env->comp_lock);
122 
123 	return IRQ_HANDLED;
124 }
125 
envelope_detector_setup_compare(struct envelope * env)126 static void envelope_detector_setup_compare(struct envelope *env)
127 {
128 	int ret;
129 
130 	/*
131 	 * Do a binary search for the peak input level, and stop
132 	 * when that level is "trapped" between two adjacent DAC
133 	 * values.
134 	 * When invert is active, use the midpoint floor so that
135 	 * env->level ends up as env->low when the termination
136 	 * criteria below is fulfilled, and use the midpoint
137 	 * ceiling when invert is not active so that env->level
138 	 * ends up as env->high in that case.
139 	 */
140 	env->level = (env->high + env->low + !env->invert) / 2;
141 
142 	if (env->high == env->low + 1) {
143 		complete(&env->done);
144 		return;
145 	}
146 
147 	/* Set a "safe" DAC level (if there is such a thing)... */
148 	ret = iio_write_channel_raw(env->dac, env->invert ? 0 : env->dac_max);
149 	if (ret < 0)
150 		goto err;
151 
152 	/* ...clear the comparison result... */
153 	envelope_detector_comp_latch(env);
154 
155 	/* ...set the real DAC level... */
156 	ret = iio_write_channel_raw(env->dac, env->level);
157 	if (ret < 0)
158 		goto err;
159 
160 	/* ...and wait for a bit to see if the latch catches anything. */
161 	schedule_delayed_work(&env->comp_timeout,
162 			      msecs_to_jiffies(env->comp_interval));
163 	return;
164 
165 err:
166 	env->level = ret;
167 	complete(&env->done);
168 }
169 
envelope_detector_timeout(struct work_struct * work)170 static void envelope_detector_timeout(struct work_struct *work)
171 {
172 	struct envelope *env = container_of(work, struct envelope,
173 					    comp_timeout.work);
174 
175 	/* Adjust low/high depending on the latch content... */
176 	if (!envelope_detector_comp_latch(env) ^ !env->invert)
177 		env->low = env->level;
178 	else
179 		env->high = env->level;
180 
181 	/* ...and continue the search. */
182 	envelope_detector_setup_compare(env);
183 }
184 
envelope_detector_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)185 static int envelope_detector_read_raw(struct iio_dev *indio_dev,
186 				      struct iio_chan_spec const *chan,
187 				      int *val, int *val2, long mask)
188 {
189 	struct envelope *env = iio_priv(indio_dev);
190 	int ret;
191 
192 	switch (mask) {
193 	case IIO_CHAN_INFO_RAW:
194 		/*
195 		 * When invert is active, start with high=max+1 and low=0
196 		 * since we will end up with the low value when the
197 		 * termination criteria is fulfilled (rounding down). And
198 		 * start with high=max and low=-1 when invert is not active
199 		 * since we will end up with the high value in that case.
200 		 * This ensures that the returned value in both cases are
201 		 * in the same range as the DAC and is a value that has not
202 		 * triggered the comparator.
203 		 */
204 		mutex_lock(&env->read_lock);
205 		env->high = env->dac_max + env->invert;
206 		env->low = -1 + env->invert;
207 		envelope_detector_setup_compare(env);
208 		wait_for_completion(&env->done);
209 		if (env->level < 0) {
210 			ret = env->level;
211 			goto err_unlock;
212 		}
213 		*val = env->invert ? env->dac_max - env->level : env->level;
214 		mutex_unlock(&env->read_lock);
215 
216 		return IIO_VAL_INT;
217 
218 	case IIO_CHAN_INFO_SCALE:
219 		return iio_read_channel_scale(env->dac, val, val2);
220 	}
221 
222 	return -EINVAL;
223 
224 err_unlock:
225 	mutex_unlock(&env->read_lock);
226 	return ret;
227 }
228 
envelope_show_invert(struct iio_dev * indio_dev,uintptr_t private,struct iio_chan_spec const * ch,char * buf)229 static ssize_t envelope_show_invert(struct iio_dev *indio_dev,
230 				    uintptr_t private,
231 				    struct iio_chan_spec const *ch, char *buf)
232 {
233 	struct envelope *env = iio_priv(indio_dev);
234 
235 	return sprintf(buf, "%u\n", env->invert);
236 }
237 
envelope_store_invert(struct iio_dev * indio_dev,uintptr_t private,struct iio_chan_spec const * ch,const char * buf,size_t len)238 static ssize_t envelope_store_invert(struct iio_dev *indio_dev,
239 				     uintptr_t private,
240 				     struct iio_chan_spec const *ch,
241 				     const char *buf, size_t len)
242 {
243 	struct envelope *env = iio_priv(indio_dev);
244 	unsigned long invert;
245 	int ret;
246 	u32 trigger;
247 
248 	ret = kstrtoul(buf, 0, &invert);
249 	if (ret < 0)
250 		return ret;
251 	if (invert > 1)
252 		return -EINVAL;
253 
254 	trigger = invert ? env->comp_irq_trigger_inv : env->comp_irq_trigger;
255 
256 	mutex_lock(&env->read_lock);
257 	if (invert != env->invert)
258 		ret = irq_set_irq_type(env->comp_irq, trigger);
259 	if (!ret) {
260 		env->invert = invert;
261 		ret = len;
262 	}
263 	mutex_unlock(&env->read_lock);
264 
265 	return ret;
266 }
267 
envelope_show_comp_interval(struct iio_dev * indio_dev,uintptr_t private,struct iio_chan_spec const * ch,char * buf)268 static ssize_t envelope_show_comp_interval(struct iio_dev *indio_dev,
269 					   uintptr_t private,
270 					   struct iio_chan_spec const *ch,
271 					   char *buf)
272 {
273 	struct envelope *env = iio_priv(indio_dev);
274 
275 	return sprintf(buf, "%u\n", env->comp_interval);
276 }
277 
envelope_store_comp_interval(struct iio_dev * indio_dev,uintptr_t private,struct iio_chan_spec const * ch,const char * buf,size_t len)278 static ssize_t envelope_store_comp_interval(struct iio_dev *indio_dev,
279 					    uintptr_t private,
280 					    struct iio_chan_spec const *ch,
281 					    const char *buf, size_t len)
282 {
283 	struct envelope *env = iio_priv(indio_dev);
284 	unsigned long interval;
285 	int ret;
286 
287 	ret = kstrtoul(buf, 0, &interval);
288 	if (ret < 0)
289 		return ret;
290 	if (interval > 1000)
291 		return -EINVAL;
292 
293 	mutex_lock(&env->read_lock);
294 	env->comp_interval = interval;
295 	mutex_unlock(&env->read_lock);
296 
297 	return len;
298 }
299 
300 static const struct iio_chan_spec_ext_info envelope_detector_ext_info[] = {
301 	{ .name = "invert",
302 	  .read = envelope_show_invert,
303 	  .write = envelope_store_invert, },
304 	{ .name = "compare_interval",
305 	  .read = envelope_show_comp_interval,
306 	  .write = envelope_store_comp_interval, },
307 	{ }
308 };
309 
310 static const struct iio_chan_spec envelope_detector_iio_channel = {
311 	.type = IIO_ALTVOLTAGE,
312 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW)
313 			    | BIT(IIO_CHAN_INFO_SCALE),
314 	.ext_info = envelope_detector_ext_info,
315 	.indexed = 1,
316 };
317 
318 static const struct iio_info envelope_detector_info = {
319 	.read_raw = &envelope_detector_read_raw,
320 };
321 
envelope_detector_probe(struct platform_device * pdev)322 static int envelope_detector_probe(struct platform_device *pdev)
323 {
324 	struct device *dev = &pdev->dev;
325 	struct iio_dev *indio_dev;
326 	struct envelope *env;
327 	enum iio_chan_type type;
328 	int ret;
329 
330 	indio_dev = devm_iio_device_alloc(dev, sizeof(*env));
331 	if (!indio_dev)
332 		return -ENOMEM;
333 
334 	platform_set_drvdata(pdev, indio_dev);
335 	env = iio_priv(indio_dev);
336 	env->comp_interval = 50; /* some sensible default? */
337 
338 	spin_lock_init(&env->comp_lock);
339 	mutex_init(&env->read_lock);
340 	init_completion(&env->done);
341 	INIT_DELAYED_WORK(&env->comp_timeout, envelope_detector_timeout);
342 
343 	indio_dev->name = dev_name(dev);
344 	indio_dev->info = &envelope_detector_info;
345 	indio_dev->channels = &envelope_detector_iio_channel;
346 	indio_dev->num_channels = 1;
347 
348 	env->dac = devm_iio_channel_get(dev, "dac");
349 	if (IS_ERR(env->dac))
350 		return dev_err_probe(dev, PTR_ERR(env->dac),
351 				     "failed to get dac input channel\n");
352 
353 	env->comp_irq = platform_get_irq_byname(pdev, "comp");
354 	if (env->comp_irq < 0)
355 		return env->comp_irq;
356 
357 	ret = devm_request_irq(dev, env->comp_irq, envelope_detector_comp_isr,
358 			       0, "envelope-detector", env);
359 	if (ret)
360 		return dev_err_probe(dev, ret, "failed to request interrupt\n");
361 
362 	env->comp_irq_trigger = irq_get_trigger_type(env->comp_irq);
363 	if (env->comp_irq_trigger & IRQF_TRIGGER_RISING)
364 		env->comp_irq_trigger_inv |= IRQF_TRIGGER_FALLING;
365 	if (env->comp_irq_trigger & IRQF_TRIGGER_FALLING)
366 		env->comp_irq_trigger_inv |= IRQF_TRIGGER_RISING;
367 	if (env->comp_irq_trigger & IRQF_TRIGGER_HIGH)
368 		env->comp_irq_trigger_inv |= IRQF_TRIGGER_LOW;
369 	if (env->comp_irq_trigger & IRQF_TRIGGER_LOW)
370 		env->comp_irq_trigger_inv |= IRQF_TRIGGER_HIGH;
371 
372 	ret = iio_get_channel_type(env->dac, &type);
373 	if (ret < 0)
374 		return ret;
375 
376 	if (type != IIO_VOLTAGE) {
377 		dev_err(dev, "dac is of the wrong type\n");
378 		return -EINVAL;
379 	}
380 
381 	ret = iio_read_max_channel_raw(env->dac, &env->dac_max);
382 	if (ret < 0) {
383 		dev_err(dev, "dac does not indicate its raw maximum value\n");
384 		return ret;
385 	}
386 
387 	return devm_iio_device_register(dev, indio_dev);
388 }
389 
390 static const struct of_device_id envelope_detector_match[] = {
391 	{ .compatible = "axentia,tse850-envelope-detector", },
392 	{ }
393 };
394 MODULE_DEVICE_TABLE(of, envelope_detector_match);
395 
396 static struct platform_driver envelope_detector_driver = {
397 	.probe = envelope_detector_probe,
398 	.driver = {
399 		.name = "iio-envelope-detector",
400 		.of_match_table = envelope_detector_match,
401 	},
402 };
403 module_platform_driver(envelope_detector_driver);
404 
405 MODULE_DESCRIPTION("Envelope detector using a DAC and a comparator");
406 MODULE_AUTHOR("Peter Rosin <peda@axentia.se>");
407 MODULE_LICENSE("GPL v2");
408 MODULE_IMPORT_NS("IIO_CONSUMER");
409