]> Git Repo - linux.git/blob - drivers/iio/industrialio-backend.c
dma-mapping: don't return errors from dma_set_max_seg_size
[linux.git] / drivers / iio / industrialio-backend.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Framework to handle complex IIO aggregate devices.
4  *
5  * The typical architecture is to have one device as the frontend device which
6  * can be "linked" against one or multiple backend devices. All the IIO and
7  * userspace interface is expected to be registers/managed by the frontend
8  * device which will callback into the backends when needed (to get/set some
9  * configuration that it does not directly control).
10  *
11  *                                           -------------------------------------------------------
12  * ------------------                        | ------------         ------------      -------  FPGA|
13  * |     ADC        |------------------------| | ADC CORE |---------| DMA CORE |------| RAM |      |
14  * | (Frontend/IIO) | Serial Data (eg: LVDS) | |(backend) |---------|          |------|     |      |
15  * |                |------------------------| ------------         ------------      -------      |
16  * ------------------                        -------------------------------------------------------
17  *
18  * The framework interface is pretty simple:
19  *   - Backends should register themselves with devm_iio_backend_register()
20  *   - Frontend devices should get backends with devm_iio_backend_get()
21  *
22  * Also to note that the primary target for this framework are converters like
23  * ADC/DACs so iio_backend_ops will have some operations typical of converter
24  * devices. On top of that, this is "generic" for all IIO which means any kind
25  * of device can make use of the framework. That said, If the iio_backend_ops
26  * struct begins to grow out of control, we can always refactor things so that
27  * the industrialio-backend.c is only left with the really generic stuff. Then,
28  * we can build on top of it depending on the needs.
29  *
30  * Copyright (C) 2023-2024 Analog Devices Inc.
31  */
32 #define dev_fmt(fmt) "iio-backend: " fmt
33
34 #include <linux/cleanup.h>
35 #include <linux/device.h>
36 #include <linux/err.h>
37 #include <linux/errno.h>
38 #include <linux/list.h>
39 #include <linux/module.h>
40 #include <linux/mutex.h>
41 #include <linux/property.h>
42 #include <linux/slab.h>
43 #include <linux/types.h>
44
45 #include <linux/iio/backend.h>
46 #include <linux/iio/iio.h>
47
48 struct iio_backend {
49         struct list_head entry;
50         const struct iio_backend_ops *ops;
51         struct device *frontend_dev;
52         struct device *dev;
53         struct module *owner;
54         void *priv;
55 };
56
57 /*
58  * Helper struct for requesting buffers. This ensures that we have all data
59  * that we need to free the buffer in a device managed action.
60  */
61 struct iio_backend_buffer_pair {
62         struct iio_backend *back;
63         struct iio_buffer *buffer;
64 };
65
66 static LIST_HEAD(iio_back_list);
67 static DEFINE_MUTEX(iio_back_lock);
68
69 /*
70  * Helper macros to call backend ops. Makes sure the option is supported.
71  */
72 #define iio_backend_check_op(back, op) ({ \
73         struct iio_backend *____back = back;                            \
74         int ____ret = 0;                                                \
75                                                                         \
76         if (!____back->ops->op)                                         \
77                 ____ret = -EOPNOTSUPP;                                  \
78                                                                         \
79         ____ret;                                                        \
80 })
81
82 #define iio_backend_op_call(back, op, args...) ({               \
83         struct iio_backend *__back = back;                      \
84         int __ret;                                              \
85                                                                 \
86         __ret = iio_backend_check_op(__back, op);               \
87         if (!__ret)                                             \
88                 __ret = __back->ops->op(__back, ##args);        \
89                                                                 \
90         __ret;                                                  \
91 })
92
93 #define iio_backend_ptr_op_call(back, op, args...) ({           \
94         struct iio_backend *__back = back;                      \
95         void *ptr_err;                                          \
96         int __ret;                                              \
97                                                                 \
98         __ret = iio_backend_check_op(__back, op);               \
99         if (__ret)                                              \
100                 ptr_err = ERR_PTR(__ret);                       \
101         else                                                    \
102                 ptr_err = __back->ops->op(__back, ##args);      \
103                                                                 \
104         ptr_err;                                                \
105 })
106
107 #define iio_backend_void_op_call(back, op, args...) {           \
108         struct iio_backend *__back = back;                      \
109         int __ret;                                              \
110                                                                 \
111         __ret = iio_backend_check_op(__back, op);               \
112         if (!__ret)                                             \
113                 __back->ops->op(__back, ##args);                \
114 }
115
116 /**
117  * iio_backend_chan_enable - Enable a backend channel
118  * @back: Backend device
119  * @chan: Channel number
120  *
121  * RETURNS:
122  * 0 on success, negative error number on failure.
123  */
124 int iio_backend_chan_enable(struct iio_backend *back, unsigned int chan)
125 {
126         return iio_backend_op_call(back, chan_enable, chan);
127 }
128 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_enable, IIO_BACKEND);
129
130 /**
131  * iio_backend_chan_disable - Disable a backend channel
132  * @back: Backend device
133  * @chan: Channel number
134  *
135  * RETURNS:
136  * 0 on success, negative error number on failure.
137  */
138 int iio_backend_chan_disable(struct iio_backend *back, unsigned int chan)
139 {
140         return iio_backend_op_call(back, chan_disable, chan);
141 }
142 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_disable, IIO_BACKEND);
143
144 static void __iio_backend_disable(void *back)
145 {
146         iio_backend_void_op_call(back, disable);
147 }
148
149 /**
150  * devm_iio_backend_enable - Device managed backend enable
151  * @dev: Consumer device for the backend
152  * @back: Backend device
153  *
154  * RETURNS:
155  * 0 on success, negative error number on failure.
156  */
157 int devm_iio_backend_enable(struct device *dev, struct iio_backend *back)
158 {
159         int ret;
160
161         ret = iio_backend_op_call(back, enable);
162         if (ret)
163                 return ret;
164
165         return devm_add_action_or_reset(dev, __iio_backend_disable, back);
166 }
167 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_enable, IIO_BACKEND);
168
169 /**
170  * iio_backend_data_format_set - Configure the channel data format
171  * @back: Backend device
172  * @chan: Channel number
173  * @data: Data format
174  *
175  * Properly configure a channel with respect to the expected data format. A
176  * @struct iio_backend_data_fmt must be passed with the settings.
177  *
178  * RETURNS:
179  * 0 on success, negative error number on failure.
180  */
181 int iio_backend_data_format_set(struct iio_backend *back, unsigned int chan,
182                                 const struct iio_backend_data_fmt *data)
183 {
184         if (!data || data->type >= IIO_BACKEND_DATA_TYPE_MAX)
185                 return -EINVAL;
186
187         return iio_backend_op_call(back, data_format_set, chan, data);
188 }
189 EXPORT_SYMBOL_NS_GPL(iio_backend_data_format_set, IIO_BACKEND);
190
191 /**
192  * iio_backend_data_source_set - Select data source
193  * @back: Backend device
194  * @chan: Channel number
195  * @data: Data source
196  *
197  * A given backend may have different sources to stream/sync data. This allows
198  * to choose that source.
199  *
200  * RETURNS:
201  * 0 on success, negative error number on failure.
202  */
203 int iio_backend_data_source_set(struct iio_backend *back, unsigned int chan,
204                                 enum iio_backend_data_source data)
205 {
206         if (data >= IIO_BACKEND_DATA_SOURCE_MAX)
207                 return -EINVAL;
208
209         return iio_backend_op_call(back, data_source_set, chan, data);
210 }
211 EXPORT_SYMBOL_NS_GPL(iio_backend_data_source_set, IIO_BACKEND);
212
213 /**
214  * iio_backend_set_sampling_freq - Set channel sampling rate
215  * @back: Backend device
216  * @chan: Channel number
217  * @sample_rate_hz: Sample rate
218  *
219  * RETURNS:
220  * 0 on success, negative error number on failure.
221  */
222 int iio_backend_set_sampling_freq(struct iio_backend *back, unsigned int chan,
223                                   u64 sample_rate_hz)
224 {
225         return iio_backend_op_call(back, set_sample_rate, chan, sample_rate_hz);
226 }
227 EXPORT_SYMBOL_NS_GPL(iio_backend_set_sampling_freq, IIO_BACKEND);
228
229 /**
230  * iio_backend_test_pattern_set - Configure a test pattern
231  * @back: Backend device
232  * @chan: Channel number
233  * @pattern: Test pattern
234  *
235  * Configure a test pattern on the backend. This is typically used for
236  * calibrating the timings on the data digital interface.
237  *
238  * RETURNS:
239  * 0 on success, negative error number on failure.
240  */
241 int iio_backend_test_pattern_set(struct iio_backend *back,
242                                  unsigned int chan,
243                                  enum iio_backend_test_pattern pattern)
244 {
245         if (pattern >= IIO_BACKEND_TEST_PATTERN_MAX)
246                 return -EINVAL;
247
248         return iio_backend_op_call(back, test_pattern_set, chan, pattern);
249 }
250 EXPORT_SYMBOL_NS_GPL(iio_backend_test_pattern_set, IIO_BACKEND);
251
252 /**
253  * iio_backend_chan_status - Get the channel status
254  * @back: Backend device
255  * @chan: Channel number
256  * @error: Error indication
257  *
258  * Get the current state of the backend channel. Typically used to check if
259  * there were any errors sending/receiving data.
260  *
261  * RETURNS:
262  * 0 on success, negative error number on failure.
263  */
264 int iio_backend_chan_status(struct iio_backend *back, unsigned int chan,
265                             bool *error)
266 {
267         return iio_backend_op_call(back, chan_status, chan, error);
268 }
269 EXPORT_SYMBOL_NS_GPL(iio_backend_chan_status, IIO_BACKEND);
270
271 /**
272  * iio_backend_iodelay_set - Set digital I/O delay
273  * @back: Backend device
274  * @lane: Lane number
275  * @taps: Number of taps
276  *
277  * Controls delays on sending/receiving data. One usecase for this is to
278  * calibrate the data digital interface so we get the best results when
279  * transferring data. Note that @taps has no unit since the actual delay per tap
280  * is very backend specific. Hence, frontend devices typically should go through
281  * an array of @taps (the size of that array should typically match the size of
282  * calibration points on the frontend device) and call this API.
283  *
284  * RETURNS:
285  * 0 on success, negative error number on failure.
286  */
287 int iio_backend_iodelay_set(struct iio_backend *back, unsigned int lane,
288                             unsigned int taps)
289 {
290         return iio_backend_op_call(back, iodelay_set, lane, taps);
291 }
292 EXPORT_SYMBOL_NS_GPL(iio_backend_iodelay_set, IIO_BACKEND);
293
294 /**
295  * iio_backend_data_sample_trigger - Control when to sample data
296  * @back: Backend device
297  * @trigger: Data trigger
298  *
299  * Mostly useful for input backends. Configures the backend for when to sample
300  * data (eg: rising vs falling edge).
301  *
302  * RETURNS:
303  * 0 on success, negative error number on failure.
304  */
305 int iio_backend_data_sample_trigger(struct iio_backend *back,
306                                     enum iio_backend_sample_trigger trigger)
307 {
308         if (trigger >= IIO_BACKEND_SAMPLE_TRIGGER_MAX)
309                 return -EINVAL;
310
311         return iio_backend_op_call(back, data_sample_trigger, trigger);
312 }
313 EXPORT_SYMBOL_NS_GPL(iio_backend_data_sample_trigger, IIO_BACKEND);
314
315 static void iio_backend_free_buffer(void *arg)
316 {
317         struct iio_backend_buffer_pair *pair = arg;
318
319         iio_backend_void_op_call(pair->back, free_buffer, pair->buffer);
320 }
321
322 /**
323  * devm_iio_backend_request_buffer - Device managed buffer request
324  * @dev: Consumer device for the backend
325  * @back: Backend device
326  * @indio_dev: IIO device
327  *
328  * Request an IIO buffer from the backend. The type of the buffer (typically
329  * INDIO_BUFFER_HARDWARE) is up to the backend to decide. This is because,
330  * normally, the backend dictates what kind of buffering we can get.
331  *
332  * The backend .free_buffer() hooks is automatically called on @dev detach.
333  *
334  * RETURNS:
335  * 0 on success, negative error number on failure.
336  */
337 int devm_iio_backend_request_buffer(struct device *dev,
338                                     struct iio_backend *back,
339                                     struct iio_dev *indio_dev)
340 {
341         struct iio_backend_buffer_pair *pair;
342         struct iio_buffer *buffer;
343
344         pair = devm_kzalloc(dev, sizeof(*pair), GFP_KERNEL);
345         if (!pair)
346                 return -ENOMEM;
347
348         buffer = iio_backend_ptr_op_call(back, request_buffer, indio_dev);
349         if (IS_ERR(buffer))
350                 return PTR_ERR(buffer);
351
352         /* weak reference should be all what we need */
353         pair->back = back;
354         pair->buffer = buffer;
355
356         return devm_add_action_or_reset(dev, iio_backend_free_buffer, pair);
357 }
358 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_request_buffer, IIO_BACKEND);
359
360 static struct iio_backend *iio_backend_from_indio_dev_parent(const struct device *dev)
361 {
362         struct iio_backend *back = ERR_PTR(-ENODEV), *iter;
363
364         /*
365          * We deliberately go through all backends even after finding a match.
366          * The reason is that we want to catch frontend devices which have more
367          * than one backend in which case returning the first we find is bogus.
368          * For those cases, frontends need to explicitly define
369          * get_iio_backend() in struct iio_info.
370          */
371         guard(mutex)(&iio_back_lock);
372         list_for_each_entry(iter, &iio_back_list, entry) {
373                 if (dev == iter->frontend_dev) {
374                         if (!IS_ERR(back)) {
375                                 dev_warn(dev,
376                                          "Multiple backends! get_iio_backend() needs to be implemented");
377                                 return ERR_PTR(-ENODEV);
378                         }
379
380                         back = iter;
381                 }
382         }
383
384         return back;
385 }
386
387 /**
388  * iio_backend_ext_info_get - IIO ext_info read callback
389  * @indio_dev: IIO device
390  * @private: Data private to the driver
391  * @chan: IIO channel
392  * @buf: Buffer where to place the attribute data
393  *
394  * This helper is intended to be used by backends that extend an IIO channel
395  * (through iio_backend_extend_chan_spec()) with extended info. In that case,
396  * backends are not supposed to give their own callbacks (as they would not have
397  * a way to get the backend from indio_dev). This is the getter.
398  *
399  * RETURNS:
400  * Number of bytes written to buf, negative error number on failure.
401  */
402 ssize_t iio_backend_ext_info_get(struct iio_dev *indio_dev, uintptr_t private,
403                                  const struct iio_chan_spec *chan, char *buf)
404 {
405         struct iio_backend *back;
406
407         /*
408          * The below should work for the majority of the cases. It will not work
409          * when one frontend has multiple backends in which case we'll need a
410          * new callback in struct iio_info so we can directly request the proper
411          * backend from the frontend. Anyways, let's only introduce new options
412          * when really needed...
413          */
414         back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
415         if (IS_ERR(back))
416                 return PTR_ERR(back);
417
418         return iio_backend_op_call(back, ext_info_get, private, chan, buf);
419 }
420 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_get, IIO_BACKEND);
421
422 /**
423  * iio_backend_ext_info_set - IIO ext_info write callback
424  * @indio_dev: IIO device
425  * @private: Data private to the driver
426  * @chan: IIO channel
427  * @buf: Buffer holding the sysfs attribute
428  * @len: Buffer length
429  *
430  * This helper is intended to be used by backends that extend an IIO channel
431  * (trough iio_backend_extend_chan_spec()) with extended info. In that case,
432  * backends are not supposed to give their own callbacks (as they would not have
433  * a way to get the backend from indio_dev). This is the setter.
434  *
435  * RETURNS:
436  * Buffer length on success, negative error number on failure.
437  */
438 ssize_t iio_backend_ext_info_set(struct iio_dev *indio_dev, uintptr_t private,
439                                  const struct iio_chan_spec *chan,
440                                  const char *buf, size_t len)
441 {
442         struct iio_backend *back;
443
444         back = iio_backend_from_indio_dev_parent(indio_dev->dev.parent);
445         if (IS_ERR(back))
446                 return PTR_ERR(back);
447
448         return iio_backend_op_call(back, ext_info_set, private, chan, buf, len);
449 }
450 EXPORT_SYMBOL_NS_GPL(iio_backend_ext_info_set, IIO_BACKEND);
451
452 /**
453  * iio_backend_extend_chan_spec - Extend an IIO channel
454  * @indio_dev: IIO device
455  * @back: Backend device
456  * @chan: IIO channel
457  *
458  * Some backends may have their own functionalities and hence capable of
459  * extending a frontend's channel.
460  *
461  * RETURNS:
462  * 0 on success, negative error number on failure.
463  */
464 int iio_backend_extend_chan_spec(struct iio_dev *indio_dev,
465                                  struct iio_backend *back,
466                                  struct iio_chan_spec *chan)
467 {
468         const struct iio_chan_spec_ext_info *frontend_ext_info = chan->ext_info;
469         const struct iio_chan_spec_ext_info *back_ext_info;
470         int ret;
471
472         ret = iio_backend_op_call(back, extend_chan_spec, chan);
473         if (ret)
474                 return ret;
475         /*
476          * Let's keep things simple for now. Don't allow to overwrite the
477          * frontend's extended info. If ever needed, we can support appending
478          * it.
479          */
480         if (frontend_ext_info && chan->ext_info != frontend_ext_info)
481                 return -EOPNOTSUPP;
482         if (!chan->ext_info)
483                 return 0;
484
485         /* Don't allow backends to get creative and force their own handlers */
486         for (back_ext_info = chan->ext_info; back_ext_info->name; back_ext_info++) {
487                 if (back_ext_info->read != iio_backend_ext_info_get)
488                         return -EINVAL;
489                 if (back_ext_info->write != iio_backend_ext_info_set)
490                         return -EINVAL;
491         }
492
493         return 0;
494 }
495 EXPORT_SYMBOL_NS_GPL(iio_backend_extend_chan_spec, IIO_BACKEND);
496
497 static void iio_backend_release(void *arg)
498 {
499         struct iio_backend *back = arg;
500
501         module_put(back->owner);
502 }
503
504 static int __devm_iio_backend_get(struct device *dev, struct iio_backend *back)
505 {
506         struct device_link *link;
507         int ret;
508
509         /*
510          * Make sure the provider cannot be unloaded before the consumer module.
511          * Note that device_links would still guarantee that nothing is
512          * accessible (and breaks) but this makes it explicit that the consumer
513          * module must be also unloaded.
514          */
515         if (!try_module_get(back->owner))
516                 return dev_err_probe(dev, -ENODEV,
517                                      "Cannot get module reference\n");
518
519         ret = devm_add_action_or_reset(dev, iio_backend_release, back);
520         if (ret)
521                 return ret;
522
523         link = device_link_add(dev, back->dev, DL_FLAG_AUTOREMOVE_CONSUMER);
524         if (!link)
525                 return dev_err_probe(dev, -EINVAL,
526                                      "Could not link to supplier(%s)\n",
527                                      dev_name(back->dev));
528
529         back->frontend_dev = dev;
530
531         dev_dbg(dev, "Found backend(%s) device\n", dev_name(back->dev));
532
533         return 0;
534 }
535
536 /**
537  * devm_iio_backend_get - Device managed backend device get
538  * @dev: Consumer device for the backend
539  * @name: Backend name
540  *
541  * Get's the backend associated with @dev.
542  *
543  * RETURNS:
544  * A backend pointer, negative error pointer otherwise.
545  */
546 struct iio_backend *devm_iio_backend_get(struct device *dev, const char *name)
547 {
548         struct fwnode_handle *fwnode;
549         struct iio_backend *back;
550         unsigned int index;
551         int ret;
552
553         if (name) {
554                 ret = device_property_match_string(dev, "io-backend-names",
555                                                    name);
556                 if (ret < 0)
557                         return ERR_PTR(ret);
558                 index = ret;
559         } else {
560                 index = 0;
561         }
562
563         fwnode = fwnode_find_reference(dev_fwnode(dev), "io-backends", index);
564         if (IS_ERR(fwnode))
565                 return dev_err_cast_probe(dev, fwnode,
566                                           "Cannot get Firmware reference\n");
567
568         guard(mutex)(&iio_back_lock);
569         list_for_each_entry(back, &iio_back_list, entry) {
570                 if (!device_match_fwnode(back->dev, fwnode))
571                         continue;
572
573                 fwnode_handle_put(fwnode);
574                 ret = __devm_iio_backend_get(dev, back);
575                 if (ret)
576                         return ERR_PTR(ret);
577
578                 return back;
579         }
580
581         fwnode_handle_put(fwnode);
582         return ERR_PTR(-EPROBE_DEFER);
583 }
584 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_get, IIO_BACKEND);
585
586 /**
587  * __devm_iio_backend_get_from_fwnode_lookup - Device managed fwnode backend device get
588  * @dev: Consumer device for the backend
589  * @fwnode: Firmware node of the backend device
590  *
591  * Search the backend list for a device matching @fwnode.
592  * This API should not be used and it's only present for preventing the first
593  * user of this framework to break it's DT ABI.
594  *
595  * RETURNS:
596  * A backend pointer, negative error pointer otherwise.
597  */
598 struct iio_backend *
599 __devm_iio_backend_get_from_fwnode_lookup(struct device *dev,
600                                           struct fwnode_handle *fwnode)
601 {
602         struct iio_backend *back;
603         int ret;
604
605         guard(mutex)(&iio_back_lock);
606         list_for_each_entry(back, &iio_back_list, entry) {
607                 if (!device_match_fwnode(back->dev, fwnode))
608                         continue;
609
610                 ret = __devm_iio_backend_get(dev, back);
611                 if (ret)
612                         return ERR_PTR(ret);
613
614                 return back;
615         }
616
617         return ERR_PTR(-EPROBE_DEFER);
618 }
619 EXPORT_SYMBOL_NS_GPL(__devm_iio_backend_get_from_fwnode_lookup, IIO_BACKEND);
620
621 /**
622  * iio_backend_get_priv - Get driver private data
623  * @back: Backend device
624  */
625 void *iio_backend_get_priv(const struct iio_backend *back)
626 {
627         return back->priv;
628 }
629 EXPORT_SYMBOL_NS_GPL(iio_backend_get_priv, IIO_BACKEND);
630
631 static void iio_backend_unregister(void *arg)
632 {
633         struct iio_backend *back = arg;
634
635         guard(mutex)(&iio_back_lock);
636         list_del(&back->entry);
637 }
638
639 /**
640  * devm_iio_backend_register - Device managed backend device register
641  * @dev: Backend device being registered
642  * @ops: Backend ops
643  * @priv: Device private data
644  *
645  * @ops is mandatory. Not providing it results in -EINVAL.
646  *
647  * RETURNS:
648  * 0 on success, negative error number on failure.
649  */
650 int devm_iio_backend_register(struct device *dev,
651                               const struct iio_backend_ops *ops, void *priv)
652 {
653         struct iio_backend *back;
654
655         if (!ops)
656                 return dev_err_probe(dev, -EINVAL, "No backend ops given\n");
657
658         /*
659          * Through device_links, we guarantee that a frontend device cannot be
660          * bound/exist if the backend driver is not around. Hence, we can bind
661          * the backend object lifetime with the device being passed since
662          * removing it will tear the frontend/consumer down.
663          */
664         back = devm_kzalloc(dev, sizeof(*back), GFP_KERNEL);
665         if (!back)
666                 return -ENOMEM;
667
668         back->ops = ops;
669         back->owner = dev->driver->owner;
670         back->dev = dev;
671         back->priv = priv;
672         scoped_guard(mutex, &iio_back_lock)
673                 list_add(&back->entry, &iio_back_list);
674
675         return devm_add_action_or_reset(dev, iio_backend_unregister, back);
676 }
677 EXPORT_SYMBOL_NS_GPL(devm_iio_backend_register, IIO_BACKEND);
678
679 MODULE_AUTHOR("Nuno Sa <[email protected]>");
680 MODULE_DESCRIPTION("Framework to handle complex IIO aggregate devices");
681 MODULE_LICENSE("GPL");
This page took 0.069288 seconds and 4 git commands to generate.