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